-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsqlite-cache-store.js
More file actions
578 lines (509 loc) · 15.2 KB
/
sqlite-cache-store.js
File metadata and controls
578 lines (509 loc) · 15.2 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
import { DatabaseSync } from 'node:sqlite'
import { parseRangeHeader, getFastNow } from './utils.js'
// Bump version when the URL key format or schema changes to invalidate old caches.
const VERSION = 10
/** @typedef {{ gc: () => void, clear: () => void } } */
const stores = new Set()
{
const offPeakBC = new BroadcastChannel('nxt:offPeak')
offPeakBC.unref()
offPeakBC.onmessage = () => {
for (const store of stores) {
store.gc()
}
}
}
{
const clearCacheBC = new BroadcastChannel('nxt:clearCache')
clearCacheBC.unref()
clearCacheBC.onmessage = () => {
for (const store of stores) {
store.clear()
}
}
}
/**
* @typedef {import('undici-types/cache-interceptor.d.ts').default.CacheStore} CacheStore
* @implements {CacheStore}
*
* @typedef {{
* id: Readonly<number>,
* body?: Uint8Array
* start: number
* end: number
* statusCode: number
* statusMessage: string
* headers?: string
* vary?: string
* etag?: string
* cacheControlDirectives?: string
* cachedAt: number
* deleteAt: number
* }} SqliteStoreValue
*/
export class SqliteCacheStore {
/**
* @type {import('node:sqlite').DatabaseSync}
*/
#db
/**
* @type {number}
*/
#dbTimeout = 20
/**
* @type {import('node:sqlite').StatementSync}
*/
#getValuesQuery
/**
* @type {import('node:sqlite').StatementSync}
*/
#insertValueQuery
/**
* @type {import('node:sqlite').StatementSync}
*/
#deleteExpiredValuesQuery
/**
* @type {import('node:sqlite').StatementSync}
*/
#evictQuery
#insertBatch = []
#closed = false
/**
* @param {import('undici-types/cache-interceptor.d.ts').default.SqliteCacheStoreOpts & { maxSize?: number } | undefined} opts
*/
constructor(opts) {
this.#dbTimeout = opts?.db?.timeout ?? this.#dbTimeout
this.#db = new DatabaseSync(opts?.location ?? ':memory:', {
...opts?.db,
timeout: this.#dbTimeout,
})
const maxSize = opts?.maxSize ?? 256 * 1024 * 1024
this.#db.exec(`
PRAGMA journal_mode = WAL;
PRAGMA synchronous = OFF;
PRAGMA wal_autocheckpoint = 10000;
PRAGMA cache_size = -${Math.ceil(maxSize / 1024 / 8)};
PRAGMA mmap_size = ${maxSize};
PRAGMA max_page_count = ${Math.ceil(maxSize / 4096)};
PRAGMA optimize;
CREATE TABLE IF NOT EXISTS cacheInterceptorV${VERSION} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL,
method TEXT NOT NULL,
body BLOB NULL,
start INTEGER NOT NULL,
end INTEGER NOT NULL,
deleteAt INTEGER NOT NULL,
statusCode INTEGER NOT NULL,
statusMessage TEXT NOT NULL,
headers TEXT NULL,
cacheControlDirectives TEXT NULL,
etag TEXT NULL,
vary TEXT NULL,
cachedAt INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_getValuesQuery ON cacheInterceptorV${VERSION}(url, method, start, deleteAt);
CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_deleteExpiredValuesQuery ON cacheInterceptorV${VERSION}(deleteAt);
`)
this.#getValuesQuery = this.#db.prepare(`
SELECT
id,
body,
start,
end,
deleteAt,
statusCode,
statusMessage,
headers,
etag,
cacheControlDirectives,
vary,
cachedAt
FROM cacheInterceptorV${VERSION}
WHERE
url = ?
AND method = ?
AND start <= ?
AND deleteAt > ?
ORDER BY
cachedAt DESC
`)
this.#insertValueQuery = this.#db.prepare(`
INSERT INTO cacheInterceptorV${VERSION} (
url,
method,
body,
start,
end,
deleteAt,
statusCode,
statusMessage,
headers,
etag,
cacheControlDirectives,
vary,
cachedAt
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`)
this.#deleteExpiredValuesQuery = this.#db.prepare(
`DELETE FROM cacheInterceptorV${VERSION} WHERE deleteAt <= ?`,
)
// Evict the N entries expiring soonest. Used on SQLITE_FULL to free space
// without requiring expired entries to already exist.
this.#evictQuery = this.#db.prepare(
`DELETE FROM cacheInterceptorV${VERSION} WHERE id IN (SELECT id FROM cacheInterceptorV${VERSION} ORDER BY deleteAt ASC LIMIT ?)`,
)
stores.add(this)
}
gc() {
try {
this.#db.exec('PRAGMA busy_timeout = 1000')
this.#deleteExpiredValuesQuery.run(getFastNow())
this.#db.exec('PRAGMA wal_checkpoint(TRUNCATE)')
this.#db.exec('PRAGMA optimize')
} catch (err) {
process.emitWarning(err)
} finally {
try {
this.#db.exec(`PRAGMA busy_timeout = ${this.#dbTimeout}`)
} catch (err) {
process.emitWarning(err)
}
}
}
clear() {
this.#insertBatch.length = 0
if (this.#closed) {
return
}
try {
this.#db.exec('PRAGMA busy_timeout = 1000')
this.#db.exec(`DELETE FROM cacheInterceptorV${VERSION}`)
this.#db.exec('PRAGMA wal_checkpoint(TRUNCATE)')
this.#db.exec('PRAGMA optimize')
} catch (err) {
process.emitWarning(err)
} finally {
try {
this.#db.exec(`PRAGMA busy_timeout = ${this.#dbTimeout}`)
} catch (err) {
process.emitWarning(err)
}
}
}
close() {
stores.delete(this)
if (this.#insertBatch.length > 0) {
this.#flush()
}
this.#closed = true
this.#db.close()
}
/**
* @param {import('undici-types/cache-interceptor.d.ts').default.CacheKey} key
* @returns {(import('undici-types/cache-interceptor.d.ts').default.GetResult & { body?: Buffer }) | undefined}
*/
get(key) {
assertCacheKey(key)
if (this.#closed) {
return undefined
}
const value = this.#findValue(key)
return value ? makeResult(value) : undefined
}
/**
* @param {import('undici-types/cache-interceptor.d.ts').default.CacheKey} key
* @param {import('undici-types/cache-interceptor.d.ts').default.CacheValue & { body: null | Buffer | Array<Buffer>, start: number, end: number }} value
*/
set(key, value) {
assertCacheKey(key)
assertCacheValue(value)
const body = Array.isArray(value.body) ? Buffer.concat(value.body) : value.body
if (typeof value.start !== 'number') {
throw new TypeError(
`expected value.start to be a number, got ${printType(value.start)} [${value.start}]`,
)
}
if (!Number.isFinite(value.start) || value.start < 0) {
throw new RangeError(
`expected value.start to be a non-negative finite number, got ${value.start}`,
)
}
if (typeof value.end !== 'number') {
throw new TypeError(
`expected value.end to be a number, got ${printType(value.end)} [${value.end}]`,
)
}
if (!Number.isFinite(value.end) || value.end < value.start) {
throw new RangeError(
`expected value.end to be a finite number >= start (${value.start}), got ${value.end}`,
)
}
if (body && body.byteLength !== value.end - value.start) {
throw new RangeError(
`body length ${body.byteLength} does not match end - start (${value.end} - ${value.start} = ${value.end - value.start})`,
)
}
if (this.#closed) {
return
}
if (this.#insertBatch.length === 0) {
setImmediate(this.#flush)
}
this.#insertBatch.push({
url: makeValueUrl(key),
method: key.method,
body,
start: value.start,
end: value.end,
deleteAt: value.deleteAt,
statusCode: value.statusCode,
statusMessage: value.statusMessage,
headers: value.headers ? JSON.stringify(value.headers) : null,
etag: value.etag != null ? value.etag : null,
cacheControlDirectives: value.cacheControlDirectives
? JSON.stringify(value.cacheControlDirectives)
: null,
vary: value.vary ? JSON.stringify(value.vary) : null,
cachedAt: value.cachedAt,
})
}
#flush = () => {
if (this.#insertBatch.length === 0) return
if (this.#closed) {
this.#insertBatch.length = 0
return
}
try {
const startTime = performance.now()
for (let retryCount = 0; true; retryCount++) {
let n = 0
try {
this.#db.exec('BEGIN')
while (n < this.#insertBatch.length) {
const {
url,
method,
body,
start,
end,
deleteAt,
statusCode,
statusMessage,
headers,
etag,
cacheControlDirectives,
vary,
cachedAt,
} = this.#insertBatch[n++]
this.#insertValueQuery.run(
url,
method,
body,
start,
end,
deleteAt,
statusCode,
statusMessage,
headers,
etag,
cacheControlDirectives,
vary,
cachedAt,
)
if ((n & 0xf) === 0 && performance.now() - startTime > 10) {
break
}
}
this.#db.exec('COMMIT')
this.#insertBatch.splice(0, n)
break
} catch (err) {
// ROLLBACK is required: a failed statement leaves the connection with
// an open transaction; without it the next BEGIN would throw.
// On SQLITE_FULL, SQLite automatically rolls back the transaction, so
// the explicit ROLLBACK may fail with "no transaction is active" — ignore it.
try {
this.#db.exec('ROLLBACK')
} catch {
// already rolled back automatically
// TODO (fix): Check that the error is what we expect (something like "no transaction is active")...
}
if (err?.errcode === 13 /* SQLITE_FULL */ && retryCount < 3) {
this.#evictQuery.run(256)
} else {
// If BEGIN failed (n=0) clear the whole batch to avoid an infinite
// retry loop. If an INSERT/COMMIT failed, only clear the entries
// that were part of the attempted transaction.
this.#insertBatch.splice(0, n || this.#insertBatch.length)
throw err
}
}
}
} catch (err) {
process.emitWarning(err)
}
if (this.#insertBatch.length > 0) {
// If we weren't able to flush the entire batch within the time limit, schedule another flush.
setImmediate(this.#flush)
}
}
/**
* @param {import('undici-types/cache-interceptor.d.ts').default.CacheKey} key
* @returns {SqliteStoreValue | undefined}
*/
#findValue(key) {
const { headers, method } = key
if (Array.isArray(headers?.range)) {
return undefined
}
const range = parseRangeHeader(headers?.range)
if (range === null) {
return undefined
}
const url = makeValueUrl(key)
const now = getFastNow()
const requestedStart = range?.start ?? 0
/**
* @type {SqliteStoreValue[]}
*/
const values = this.#getValuesQuery.all(url, method, requestedStart, now)
for (const entry of this.#insertBatch) {
if (
entry.url === url &&
entry.method === method &&
entry.start <= requestedStart &&
entry.deleteAt > now
) {
values.push(entry)
}
}
if (values.length === 0) {
return undefined
}
values.sort((a, b) => b.cachedAt - a.cachedAt)
for (const value of values) {
// TODO (fix): Allow full and partial match?
if (range && (range.start !== value.start || range.end !== value.end)) {
continue
}
if (value.vary) {
const vary = JSON.parse(value.vary)
let matches = true
for (const header in vary) {
if (!headerValueEquals(headers?.[header], vary[header])) {
matches = false
break
}
}
if (!matches) {
continue
}
}
return value
}
return undefined
}
}
/**
* @param {string|string[]|null|undefined} lhs
* @param {string|string[]|null|undefined} rhs
* @returns {boolean}
*/
function headerValueEquals(lhs, rhs) {
if (lhs == null && rhs == null) {
return true
}
if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) {
return false
}
if (Array.isArray(lhs) && Array.isArray(rhs)) {
if (lhs.length !== rhs.length) {
return false
}
return lhs.every((x, i) => x === rhs[i])
}
return lhs === rhs
}
/**
* @param {import('undici-types/cache-interceptor.d.ts').default.CacheKey} key
* @returns {string}
*/
function makeValueUrl(key) {
return `${key.origin}${key.path}`
}
function makeResult(value) {
return {
body: value.body
? Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength)
: undefined,
statusCode: value.statusCode,
statusMessage: value.statusMessage,
headers: value.headers ? JSON.parse(value.headers) : undefined,
etag: value.etag != null ? value.etag : undefined,
vary: value.vary ? JSON.parse(value.vary) : undefined,
cacheControlDirectives: value.cacheControlDirectives
? JSON.parse(value.cacheControlDirectives)
: undefined,
cachedAt: value.cachedAt,
deleteAt: value.deleteAt,
}
}
function printType(val) {
return val == null ? 'null' : typeof val === 'object' ? val.constructor.name : typeof val
}
/**
* @param {any} key
*/
function assertCacheKey(key) {
if (typeof key !== 'object' || key == null) {
throw new TypeError(`expected key to be object, got ${printType(key)} [${key}]`)
}
for (const property of ['origin', 'method', 'path']) {
if (typeof key[property] !== 'string') {
throw new TypeError(
`expected key.${property} to be string, got ${printType(key[property])} [${key[property]}]`,
)
}
}
if (key.headers !== undefined && typeof key.headers !== 'object') {
throw new TypeError(
`expected headers to be object, got ${printType(key.headers)} [${key.headers}]`,
)
}
}
/**
* @param {any} value
*/
function assertCacheValue(value) {
if (typeof value !== 'object' || value == null) {
throw new TypeError(`expected value to be object, got ${printType(value)}`)
}
for (const property of ['statusCode', 'cachedAt', 'deleteAt']) {
if (typeof value[property] !== 'number') {
throw new TypeError(
`expected value.${property} to be number, got ${printType(value[property])} [${value[property]}]`,
)
}
}
if (typeof value.statusMessage !== 'string') {
throw new TypeError(
`expected value.statusMessage to be string, got ${printType(value.statusMessage)} [${value.statusMessage}]`,
)
}
if (value.headers != null && typeof value.headers !== 'object') {
throw new TypeError(
`expected value.rawHeaders to be object, got ${printType(value.headers)} [${value.headers}]`,
)
}
if (value.vary !== undefined && typeof value.vary !== 'object') {
throw new TypeError(
`expected value.vary to be object, got ${printType(value.vary)} [${value.vary}]`,
)
}
if (value.etag !== undefined && typeof value.etag !== 'string') {
throw new TypeError(
`expected value.etag to be string, got ${printType(value.etag)} [${value.etag}]`,
)
}
}