-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache-persistence-memory.ts
More file actions
226 lines (204 loc) · 7.22 KB
/
cache-persistence-memory.ts
File metadata and controls
226 lines (204 loc) · 7.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import { CachePersistenceBase } from './cache-persistence-base.ts';
import type {
CachePersistenceLike,
CachePersistenceMemoryOptions,
PlainReqRes,
} from './types.ts';
import * as webidl from './webidl.ts';
import * as sorted from 'sorted';
export class CachePersistenceMemory extends CachePersistenceBase
implements CachePersistenceLike {
protected _storage: Record<string, PlainReqRes | Uint8Array> = Object
.create(null);
protected _indexes: Record<string, Set<string>> = Object.create(null);
protected _timers: Record<string, number> = Object.create(null);
protected _maxInteger: number = Math.pow(2, 31) - 1;
protected override _options: CachePersistenceMemoryOptions;
constructor(options?: CachePersistenceMemoryOptions) {
super();
this._options = { ...this._defaultOptions, ...options };
}
async keys(): Promise<string[]> {
const cacheNames = new Set<string>();
const persistenceKey = (await this._persistenceKey('')).slice(0, -1);
for (const key of await this._dbScan(persistenceKey)) {
cacheNames.add(this._splitKey(key)[1]);
}
return [...cacheNames];
}
async put(
cacheName: string,
request: Request,
response: Response,
): Promise<boolean> {
const pair = await this._pairToPlain(request, response);
if (!pair) {
return false;
}
const [plainReqRes, expiresIn] = pair;
const persistenceKey = await this._persistenceKey(
cacheName,
plainReqRes,
);
await this._dbSet(
persistenceKey,
plainReqRes,
expiresIn,
);
return true;
}
async delete(
cacheName: string,
request: Request,
response?: Response,
): Promise<boolean> {
if (!response) {
const persistenceKey = await this._persistenceKey(
cacheName,
request,
);
const keys = await this._dbKeys(persistenceKey);
let hasDeleted = false;
for (const key of keys) {
if (await this._dbDel(key)) {
hasDeleted = true;
}
}
return hasDeleted;
}
const persistenceKey = await this._persistenceKey(
cacheName,
request,
response,
);
return await this._dbDel(persistenceKey);
}
async *get(
cacheName: string,
request: Request,
): AsyncGenerator<readonly [Request, Response], void, unknown> {
const persistenceKey = await this._persistenceKey(cacheName, request);
const keys = await this._dbKeys(persistenceKey);
for (const key of keys) {
const plainReqRes = await this._dbGet(key);
if (!plainReqRes) {
continue;
}
if (this._hasExpired(plainReqRes)) {
continue;
}
yield [
this._plainToRequest(plainReqRes),
this._plainToResponse(plainReqRes),
] as const;
}
}
[Symbol.asyncIterator](
cacheName: string,
): AsyncGenerator<readonly [Request, Response], void, unknown> {
const prefix =
"Failed to execute '[[Symbol.asyncIterator]]' on 'CachePersistence'";
webidl.requiredArguments(arguments.length, 1, prefix);
const instance = this;
return (async function* () {
const persistenceKey = await instance._persistenceKey(cacheName);
const keys = await instance._dbScan(persistenceKey);
for (const key of keys) {
const plainReqRes = await instance._dbGet(key);
if (!plainReqRes) {
continue;
}
yield [
instance._plainToRequest(plainReqRes),
instance._plainToResponse(plainReqRes),
] as const;
}
})();
}
async [Symbol.asyncDispose](): Promise<void> {
for (const timer of Object.values(this._timers)) {
clearTimeout(timer);
}
}
protected async _dbScan(key: string[]): Promise<string[]> {
const persistenceKey = this._joinKey(key);
const found: string[] = [];
for (const index in this._indexes) {
if (index.startsWith(persistenceKey)) {
for (const key of this._indexes[index]) {
sorted.add(found, key, this._compareFn);
}
}
}
return found;
}
protected async _dbKeys(key: string[]): Promise<string[]> {
const persistenceKey = this._joinKey(key);
const indexKey = this._indexKey(persistenceKey);
const index = this._indexes[indexKey] || [];
return [...index].sort();
}
protected async _dbGet(
key: string[] | string,
): Promise<PlainReqRes | null> {
const persistenceKey = Array.isArray(key) ? this._joinKey(key) : key;
const maybeSerializedPlainReqRes = this._storage[persistenceKey];
const plainReqRes = maybeSerializedPlainReqRes instanceof Uint8Array
? this._parse(maybeSerializedPlainReqRes)
: maybeSerializedPlainReqRes;
return plainReqRes ?? null;
}
protected async _dbDel(key: string[] | string): Promise<boolean> {
const persistenceKey = Array.isArray(key) ? this._joinKey(key) : key;
const hasDeleted = persistenceKey in this._storage;
const existingTimer = this._timers[persistenceKey];
if (existingTimer) {
clearTimeout(existingTimer);
delete this._timers[persistenceKey];
}
delete this._storage[persistenceKey];
const indexKey = this._indexKey(key);
const index = this._indexes[indexKey];
if (index) {
index.delete(persistenceKey);
if (!index.size) {
delete this._indexes[indexKey];
}
}
return hasDeleted;
}
protected async _dbSet(
key: string[],
value: PlainReqRes,
expiresIn: number,
): Promise<void> {
const persistenceKey = this._joinKey(key);
this._storage[persistenceKey] = this._options.compress
? this._serialize(value)
: value;
const indexKey = this._indexKey(persistenceKey);
const index = this._indexes[indexKey] = this._indexes[indexKey] ||
new Set<string>();
index.add(persistenceKey);
this._indexes[indexKey] = index;
this._scheduleRemoval(persistenceKey, expiresIn);
}
protected _indexKey(
key: string[] | string,
): string {
const splitKey = Array.isArray(key) ? key : this._splitKey(key);
return this._joinKey(splitKey.slice(0, 3));
}
protected _scheduleRemoval(
persistenceKey: string,
expiresIn: number,
) {
const existingTimer = this._timers[persistenceKey];
if (existingTimer) {
clearTimeout(existingTimer);
}
this._timers[persistenceKey] = setTimeout(() => {
this._dbDel(this._splitKey(persistenceKey));
}, Math.min(expiresIn, this._maxInteger));
}
}