-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
714 lines (577 loc) · 22.9 KB
/
index.js
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
'use strict';
// Can't use ESM yet - need coverage.
const {EventEmitter} = require('events');
const parseCacheControl = require('./parse-cache-control');
// TODO: freshening responses with HEAD
// TODO: content-length mismatch on HEAD invalidates the cached response
// Big thanks to @ronag - https://github.com/nodejs/node/issues/39632#issuecomment-891739612
const {on} = EventEmitter.prototype;
const cloneStream = stream => {
const chunks = [];
on.call(stream, 'data', chunk => {
chunks.push(chunk);
});
return chunks;
};
// Use crypto.randomUUID() when targeting Node.js 15
const random = () => Math.random().toString(36).slice(2);
// A small utility that returns `undefined` for non-finite numbers
const toNumber = x => {
if (x === undefined) {
return;
}
const parsed = Number.parseInt(x);
if (Number.isFinite(parsed)) {
return parsed;
}
};
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
const isHopByHop = header => {
return header === 'connection' ||
header === 'keep-alive' ||
header === 'proxy-authenticate' ||
header === 'proxy-authorization' ||
header === 'te' ||
header === 'trailer' ||
header === 'transfer-encoding' ||
header === 'upgrade';
};
const withoutHopByHop = headers => {
const newHeaders = {};
// https://datatracker.ietf.org/doc/html/rfc7230#section-6.1
const hopByHop = headers.connection ? headers.connection.split(',').map(header => header.trim()) : '';
for (const header in headers) {
if (!isHopByHop(header) && !hopByHop.includes(header)) {
newHeaders[header] = headers[header];
}
}
return newHeaders;
};
// https://datatracker.ietf.org/doc/html/rfc7231#section-4.2.3
const isMethodCacheable = method => {
return method === 'GET' || method === 'HEAD' || method === 'POST';
};
// https://datatracker.ietf.org/doc/html/rfc7234#section-4.4
const isMethodUnsafe = method => {
return method !== 'GET' &&
method !== 'HEAD' &&
method !== 'OPTIONS' &&
method !== 'TRACE';
};
// https://datatracker.ietf.org/doc/html/rfc6585
// 428, 429, 431, 511 MUST NOT be stored by a cache.
// https://datatracker.ietf.org/doc/html/rfc7231#section-6.1
// 206 is hard to implement: https://datatracker.ietf.org/doc/html/rfc7234#section-3.1
const isHeuristicStatusCode = statusCode => {
return statusCode === 200 ||
statusCode === 203 ||
statusCode === 204 ||
statusCode === 300 ||
statusCode === 301 ||
statusCode === 308 ||
statusCode === 404 ||
statusCode === 405 ||
statusCode === 410 ||
statusCode === 414 ||
statusCode === 421 ||
statusCode === 451 ||
statusCode === 501;
};
// https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.2
const getDate = (date, requestTime) => {
if (date) {
const parsed = Date.parse(date);
// It must be a number
if (Number.isFinite(parsed)) {
const now = Date.now();
// Accept only valid dates
if (parsed >= requestTime && parsed <= now) {
return date;
}
}
}
return new Date(requestTime).toUTCString();
};
// https://datatracker.ietf.org/doc/html/rfc7234#section-3.2
const isCacheControlAuthorizationOk = (isShared, authenticated, responseCacheControl) => {
if (!isShared) {
return true;
}
if (!authenticated) {
return true;
}
return responseCacheControl['public'] === '' ||
responseCacheControl['must-revalidate'] === '' ||
toNumber(responseCacheControl['max-age']) !== undefined ||
// Shared cache only:
responseCacheControl['proxy-revalidate'] === '' ||
toNumber(responseCacheControl['s-maxage']) !== undefined;
};
class HttpCache {
constructor(cache = new Map()) {
// Disk or RAM cache
this.cache = cache;
this.shared = true;
// https://datatracker.ietf.org/doc/html/rfc7234#section-4.2.2
this.heuristicFraction = 0.1;
this.maxHeuristic = 86400; // 24h
this.processing = new Set();
this.removeOnInvalidation = true;
// https://datatracker.ietf.org/doc/html/rfc8246
// The `immutable` extension made sense when browsers were behaving
// like the `no-cache` directive was always set.
//
// This is not the case anymore, therefore the directive is moot now.
// See https://bugs.chromium.org/p/chromium/issues/detail?id=611416#c12
}
onError() {}
setRevalidationHeaders(method, headers, responseHeaders) {
// TODO: in the future caches will be able to independently perform validation
// https://httpwg.org/http-core/draft-ietf-httpbis-cache-latest.html#rfc.section.4.3.1
// https://datatracker.ietf.org/doc/html/rfc2616#section-13.3.3
const acceptsWeak = method === 'GET' || method === 'HEAD';
const {etag} = responseHeaders;
if (etag) {
const strong = etag[0] === 'W' && etag[1] === '/';
if (acceptsWeak || strong) {
headers['if-none-match'] = etag;
}
} else if (acceptsWeak) {
headers['if-modified-since'] = responseHeaders['last-modified'] || responseHeaders.date;
}
}
action(data, parsedCacheControl, method, headers) {
if (!data || data.method !== method) {
return 'MISS';
}
// Unsupported
if (headers['if-match'] || headers['if-unmodified-since'] || headers['if-range']) {
return 'MISS';
}
// https://datatracker.ietf.org/doc/html/rfc7234#section-4.1
for (const [header, value] of Object.entries(data.vary)) {
if (value !== headers[header]) {
return 'MISS';
}
}
if (data.alwaysRevalidate || parsedCacheControl['no-cache'] === '' || data.invalidated) {
return 'REVALIDATE';
}
// https://datatracker.ietf.org/doc/html/rfc7234#section-4.2.3
const residentTime = Date.now() - data.responseTime;
const currentAge = data.correctedInitialAge + residentTime;
const age = Math.floor(currentAge / 1000);
if (data.revalidateOnStale && age > data.lifetime) {
return 'REVALIDATE';
}
// https://datatracker.ietf.org/doc/html/rfc7234#section-5.2.1.1
const maxAge = toNumber(parsedCacheControl['max-age']) ?? data.lifetime;
// https://datatracker.ietf.org/doc/html/rfc7234#section-5.2.1.2
const minFresh = toNumber(parsedCacheControl['min-fresh']) ?? 0;
const maxStale = (parsedCacheControl['max-stale'] === '' ? Number.POSITIVE_INFINITY : (toNumber(parsedCacheControl['max-stale']) ?? 0));
// https://datatracker.ietf.org/doc/html/rfc5861
const staleWhileRevalidate = toNumber(parsedCacheControl['stale-while-revalidate']);
const staleIfError = toNumber(parsedCacheControl['stale-if-error']);
// These extensions aren't supported but we can read information from them
const correctMaxStale = maxStale ?? staleWhileRevalidate ?? staleIfError;
const ttl = maxAge - age;
if (ttl <= minFresh && -ttl > correctMaxStale) {
if (data.revalidateOnStale) {
return 'REVALIDATE';
}
return 'MISS';
}
data.responseHeaders.age = String(age);
return 'HIT';
}
async get(url, method, headers) {
const data = await this.cache.get(url);
const parsedCacheControl = parseCacheControl(headers['cache-control']);
const action = this.action(data, parsedCacheControl, method, withoutHopByHop(headers));
if (action !== 'HIT' && parsedCacheControl['only-if-cached'] === '') {
return {
statusCode: 504,
responseHeaders: {},
buffer: Buffer.alloc(0)
};
}
if (action === 'REVALIDATE') {
this.setRevalidationHeaders(method, headers, data.responseHeaders);
} else if (action === 'HIT') {
return this.retrieve(url, data);
} else if (action !== 'MISS') {
throw new Error(`Unknown cache action: ${action}`);
}
}
async retrieve(url, data) {
const {id, statusCode, responseHeaders} = data;
const bufferData = await this.cache.get(`buffer|${url}`);
if (!bufferData) {
// Cache error, remove the entry.
await this.cache.delete(url);
return;
}
const [check, buffer] = bufferData;
if (check !== id) {
// Whoops, we need to prevent race condition.
return;
}
// Warning header has been deprecated, no need to modify it.
return {
statusCode,
responseHeaders: withoutHopByHop(responseHeaders),
buffer: Buffer.from(buffer)
};
}
async invalidate(url, baseUrl) {
if (!url) {
return;
}
if (baseUrl) {
try {
url = (new URL(url, baseUrl)).href;
baseUrl = new URL(baseUrl);
} catch {
return;
}
// However, a cache MUST NOT invalidate a URI from a Location or
// Content-Location response header field if the host part of that URI
// differs from the host part in the effective request URI (Section 5.5
// of [RFC7230]). This helps prevent denial-of-service attacks.
if (url.origin !== baseUrl.origin) {
return;
}
}
url = String(url);
try {
if (this.removeOnInvalidation) {
await this.cache.delete(`buffer|${url}`);
await this.cache.delete(url);
return;
}
const data = await this.cache.get(url);
if (!data) {
return;
}
data.invalidated = true;
await this.cache.set(url, data);
} catch (error) {
this.onError(error);
}
}
shouldInvalidate({method, statusCode}) {
// https://datatracker.ietf.org/doc/html/rfc7234#section-4.4
return isMethodUnsafe(method)
&& (
(statusCode >= 200 && statusCode < 400 && statusCode !== 304)
// These status codes do not guarantee the request hasn't been processed
|| (statusCode === 500 || statusCode === 502 || statusCode === 504 || statusCode === 507)
);
}
calculateLifetime({method, statusCode, responseHeaders, responseCacheControl, requestHeaders, requestCacheControl }) {
if (!isMethodCacheable(method)) {
return {
state: 'SKIP'
};
}
if (!isCacheControlAuthorizationOk(this.shared, 'authorization' in requestHeaders, responseCacheControl)) {
return {
state: 'SKIP'
};
}
// Lifetime legend:
// undefined - update on 304
// false - remove
// number - update if 304, save otherwise
let lifetime;
// https://datatracker.ietf.org/doc/html/rfc7234#section-3
if (
requestCacheControl['no-store'] === '' ||
responseCacheControl['no-store'] === '' ||
(this.shared && 'private' in responseCacheControl) ||
// https://datatracker.ietf.org/doc/html/rfc7234#section-4.1
// A Vary header field-value of "*" always fails to match.
responseHeaders.vary === '*'
) {
lifetime = false;
} else if (responseCacheControl['no-cache'] === '') {
lifetime = 0;
} else if (this.shared && responseCacheControl['s-maxage']) {
responseCacheControl['proxy-revalidate'] = '';
lifetime = toNumber(responseCacheControl['s-maxage']) ?? false;
} else if (responseCacheControl['max-age']) {
lifetime = toNumber(responseCacheControl['max-age']) ?? false;
} else if (responseHeaders.expires) {
const parsed = Date.parse(responseHeaders.expires);
lifetime = !Number.isFinite(parsed) ? 0 : (Date.now() - parsed);
} else if (
isHeuristicStatusCode(statusCode) ||
responseCacheControl['public'] === '' ||
(!this.shared && 'private' in responseCacheControl)
) {
do {
// https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.3
if (method === 'POST') {
lifetime = undefined;
break;
}
// https://datatracker.ietf.org/doc/html/rfc7234#section-4.2.2
const hashIndex = url.indexOf('#');
const queryIndex = url.indexOf('?');
const hasQuery = hashIndex === -1 ? queryIndex !== -1 : (queryIndex < hashIndex);
if (hasQuery) {
lifetime = false;
break;
}
// https://datatracker.ietf.org/doc/html/rfc7234#section-4.2.2
if (!responseHeaders['last-modified']) {
lifetime = undefined;
break;
}
const parsed = Date.parse(responseHeaders['last-modified']);
if (Number.isNaN(parsed)) {
lifetime = false;
break;
}
lifetime = Math.floor(Math.min(this.maxHeuristic, (Date.now() - parsed) * this.heuristicFraction));
} while (false);
}
if (lifetime === false) {
return {
state: 'INVALIDATE',
};
}
if (lifetime === undefined) {
if (statusCode === 304) {
return {
state: 'CACHEABLE',
};
}
return {
state: 'SKIP',
};
}
return {
state: 'CACHEABLE',
lifetime,
};
}
// TODO: refactor this
process(url, method, requestHeaders, statusCode, responseHeaders, stream, requestTime, onError) {
// TODO: Cancel previous caching tasks instead of this check
if (this.processing.has(url) && statusCode !== 304) {
return;
}
const responseCacheControl = parseCacheControl(responseHeaders['cache-control']);
const requestCacheControl = parseCacheControl(requestHeaders['cache-control']);
let {lifetime, state} = this.calculateLifetime({
method,
statusCode,
responseHeaders,
responseCacheControl,
requestHeaders,
requestCacheControl,
});
if (state !== 'SKIP' && state !== 'INVALIDATE' && state !== 'CACHEABLE') {
throw new Error(`Invalid lifetime state: ${state}`);
}
if (this.shouldInvalidate({method, statusCode}) || state === 'INVALIDATE') {
this.invalidate(url);
this.invalidate(responseHeaders.location, url);
this.invalidate(responseHeaders['content-location'], url);
}
if (state !== 'CACHEABLE') {
return;
}
// Invalid lifetime
// Let the processing begin
this.processing.add(url);
let resolve;
let promise;
let cacheError;
let removing = false;
if (statusCode === 304) {
promise = new Promise(_resolve => {
resolve = _resolve;
});
}
const chunks = cloneStream(stream);
stream.once('close', () => {
chunks.length = 0;
});
stream.once('error', () => {
this.processing.delete(url);
});
let previousData;
let data;
// TODO: if the new response has a validator then, then the cached response may be updated only if its validator is the same as the new response
stream.once('end', async () => {
const buffer = Buffer.concat(chunks);
chunks.length = 0;
// https://datatracker.ietf.org/doc/html/rfc7234#section-4.3.4
if (lifetime !== false && statusCode === 304) {
try {
// We can't reuse data object from the validation step because it might change
previousData = await this.cache.get(url);
if (!previousData) {
resolve();
return;
}
if (previousData.method !== method) {
// TODO: do not throw if this is not revalidation
throw new Error('Cache mismatch - please try again');
}
} catch (error) {
this.processing.delete(url);
cacheError = error;
resolve();
return;
}
}
// We need to clone only those request headers we really need
let vary = {};
if (lifetime !== false && responseHeaders.vary) {
const varyHeaders = responseHeaders.vary.split(',').map(header => header.toLowerCase().trim());
for (const header of varyHeaders) {
vary[header] = requestHeaders[header];
}
}
try {
if (lifetime !== false) {
// The ID changes on refresh
const id = previousData ? previousData.id : random();
// We need to clone all the response headers
if (previousData) {
responseHeaders = {
...previousData.responseHeaders,
...responseHeaders
};
} else {
responseHeaders = {...responseHeaders};
}
// Fix the date
responseHeaders.date = getDate(responseHeaders.date, requestTime);
// https://datatracker.ietf.org/doc/html/rfc7234#section-4.2.3
const dateValue = Date.parse(responseHeaders.date);
const responseTime = Date.now();
const apparentAge = Math.max(0, responseTime - dateValue);
const responseDelay = responseTime - requestTime;
const ageValue = toNumber(responseHeaders.age) ?? 0;
const correctedAgeValue = ageValue + responseDelay;
const correctedInitialAge = Math.max(apparentAge, correctedAgeValue);
// Prepare the data
data = {
id,
responseTime,
correctedInitialAge,
lifetime,
method,
statusCode: previousData ? previousData.statusCode : statusCode,
responseHeaders,
vary,
alwaysRevalidate: 'no-cache' in responseCacheControl,
revalidateOnStale: responseCacheControl['must-revalidate'] === '' || (this.shared && responseCacheControl['proxy-revalidate'] === ''),
invalidated: false,
};
await this.cache.set(url, data);
if (statusCode !== 304) {
await this.cache.set(`buffer|${url}`, [id, buffer]);
}
} else {
// Remove the response from cache if it's not cacheable anymore
queueMicrotask(async () => {
removing = true;
try {
await this.cache.delete(`buffer|${url}`);
await this.cache.delete(url);
} catch (error) {
this.error = error;
onError(error);
}
});
}
if (statusCode === 304) {
resolve();
}
} catch (error) {
this.processing.delete(url);
if (statusCode === 304) {
this.error = error;
resolve();
return;
}
onError(error);
}
});
if (statusCode === 304) {
return async () => {
await promise;
if (cacheError) {
throw cacheError;
}
if (this.error) {
throw this.error;
}
let result;
if (removing) {
// TODO: this should wait for the removal first, edit: maybe no?
result = await this.get(url, method, requestHeaders);
} else if (data) {
result = await this.retrieve(url, data);
}
if (result === undefined) {
// TODO: what to do here?
}
// TODO: missing age header
return result;
};
}
}
static parseCacheControl = parseCacheControl;
}
const cache = new HttpCache();
const https = require('https');
const url = 'https://szmarczak.com/foobar.txt';
const request = async (url, options = { headers: {} }) => {
const data = await cache.get(url, 'GET', options.headers);
if (data) {
return data;
}
return new Promise((resolve, reject) => {
const start = Date.now();
const req = https.get(url, options, response => {
const maybe = cache.process(url, 'GET', options.headers, response.statusCode, response.headers, response, start, error => {
console.log('cache error', error);
});
console.log(response.statusCode);
const chunks = [];
response.on('data', chunk => {
chunks.push(chunk);
});
response.on('end', async () => {
if (maybe) {
const result = await maybe();
result.cached = true;
resolve(result);
return;
}
resolve({
statusCode: response.statusCode,
responseHeaders: response.headers,
buffer: Buffer.concat(chunks),
cached: false
});
});
response.once('error', reject);
});
req.once('error', reject);
});
};
(async () => {
console.log(await request(url));
console.log(await request(url, {
headers: {
'cache-control': 'no-cache'
}
}));
})();