-
Notifications
You must be signed in to change notification settings - Fork 570
/
Copy pathcache-handler.js
387 lines (330 loc) · 10.1 KB
/
cache-handler.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
'use strict'
const util = require('../core/util')
const DecoratorHandler = require('../handler/decorator-handler')
const {
parseCacheControlHeader,
parseVaryHeader
} = require('../util/cache')
function noop () {}
/**
* Writes a response to a CacheStore and then passes it on to the next handler
*/
class CacheHandler extends DecoratorHandler {
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
*/
#cacheKey
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheStore}
*/
#store
/**
* @type {import('../../types/dispatcher.d.ts').default.DispatchHandlers}
*/
#handler
/**
* @type {import('node:stream').Writable | undefined}
*/
#writeStream
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions} opts
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey
* @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler
*/
constructor (opts, cacheKey, handler) {
const { store } = opts
super(handler)
this.#store = store
this.#cacheKey = cacheKey
this.#handler = handler
}
onConnect (abort) {
if (this.#writeStream) {
this.#writeStream.destroy()
this.#writeStream = undefined
}
if (typeof this.#handler.onConnect === 'function') {
this.#handler.onConnect(abort)
}
}
/**
* @see {DispatchHandlers.onHeaders}
*
* @param {number} statusCode
* @param {Buffer[]} rawHeaders
* @param {() => void} resume
* @param {string} statusMessage
* @returns {boolean}
*/
onHeaders (
statusCode,
rawHeaders,
resume,
statusMessage
) {
const downstreamOnHeaders = () => {
if (typeof this.#handler.onHeaders === 'function') {
return this.#handler.onHeaders(
statusCode,
rawHeaders,
resume,
statusMessage
)
} else {
return true
}
}
if (
!util.safeHTTPMethods.includes(this.#cacheKey.method) &&
statusCode >= 200 &&
statusCode <= 399
) {
// https://www.rfc-editor.org/rfc/rfc9111.html#name-invalidating-stored-response
try {
this.#store.deleteByKey(this.#cacheKey).catch?.(noop)
} catch {
// Fail silently
}
return downstreamOnHeaders()
}
const parsedRawHeaders = util.parseRawHeaders(rawHeaders)
const headers = util.parseHeaders(parsedRawHeaders)
const cacheControlHeader = headers['cache-control']
const isCacheFull = typeof this.#store.isFull !== 'undefined'
? this.#store.isFull
: false
if (
!cacheControlHeader ||
isCacheFull
) {
// Don't have the cache control header or the cache is full
return downstreamOnHeaders()
}
const cacheControlDirectives = parseCacheControlHeader(cacheControlHeader)
if (!canCacheResponse(statusCode, headers, cacheControlDirectives)) {
return downstreamOnHeaders()
}
const now = Date.now()
const staleAt = determineStaleAt(now, headers, cacheControlDirectives)
if (staleAt) {
const varyDirectives = this.#cacheKey.headers && headers.vary && !Array.isArray(headers.vary)
? parseVaryHeader(headers.vary, this.#cacheKey.headers)
: undefined
const deleteAt = determineDeleteAt(now, cacheControlDirectives, staleAt)
const strippedHeaders = stripNecessaryHeaders(
rawHeaders,
parsedRawHeaders,
cacheControlDirectives
)
this.#writeStream = this.#store.createWriteStream(this.#cacheKey, {
statusCode,
statusMessage,
rawHeaders: strippedHeaders,
vary: varyDirectives,
cachedAt: now,
staleAt,
deleteAt
})
if (this.#writeStream) {
const handler = this
this.#writeStream
.on('drain', resume)
.on('error', function () {
// TODO (fix): Make error somehow observable?
})
.on('close', function () {
if (handler.#writeStream === this) {
handler.#writeStream = undefined
}
// TODO (fix): Should we resume even if was paused downstream?
resume()
})
}
}
return downstreamOnHeaders()
}
/**
* @see {DispatchHandlers.onData}
*
* @param {Buffer} chunk
* @returns {boolean}
*/
onData (chunk) {
let paused = false
if (this.#writeStream && this.#cacheKey.method !== 'HEAD') {
paused ||= this.#writeStream.write(chunk) === false
}
if (typeof this.#handler.onData === 'function') {
paused ||= this.#handler.onData(chunk) === false
}
return !paused
}
/**
* @see {DispatchHandlers.onComplete}
*
* @param {string[] | null} rawTrailers
*/
onComplete (rawTrailers) {
if (this.#writeStream) {
this.#writeStream.end()
}
if (typeof this.#handler.onComplete === 'function') {
return this.#handler.onComplete(rawTrailers)
}
}
/**
* @see {DispatchHandlers.onError}
*
* @param {Error} err
*/
onError (err) {
if (this.#writeStream) {
this.#writeStream.destroy(err)
this.#writeStream = undefined
}
if (typeof this.#handler.onError === 'function') {
this.#handler.onError(err)
}
}
}
/**
* @see https://www.rfc-editor.org/rfc/rfc9111.html#name-storing-responses-to-authen
*
* @param {number} statusCode
* @param {Record<string, string | string[]>} headers
* @param {import('../util/cache.js').CacheControlDirectives} cacheControlDirectives
*/
function canCacheResponse (statusCode, headers, cacheControlDirectives) {
if (
statusCode !== 200 &&
statusCode !== 307
) {
return false
}
if (
!cacheControlDirectives.public ||
cacheControlDirectives.private === true ||
cacheControlDirectives['no-cache'] === true ||
cacheControlDirectives['no-store']
) {
return false
}
// https://www.rfc-editor.org/rfc/rfc9111.html#section-4.1-5
if (headers.vary === '*') {
return false
}
// https://www.rfc-editor.org/rfc/rfc9111.html#name-storing-responses-to-authen
if (headers.authorization) {
if (typeof headers.authorization !== 'string') {
return false
}
if (
Array.isArray(cacheControlDirectives['no-cache']) &&
cacheControlDirectives['no-cache'].includes('authorization')
) {
return false
}
if (
Array.isArray(cacheControlDirectives['private']) &&
cacheControlDirectives['private'].includes('authorization')
) {
return false
}
}
return true
}
/**
* @param {number} now
* @param {Record<string, string | string[]>} headers
* @param {import('../util/cache.js').CacheControlDirectives} cacheControlDirectives
*
* @returns {number | undefined} time that the value is stale at or undefined if it shouldn't be cached
*/
function determineStaleAt (now, headers, cacheControlDirectives) {
// Prioritize s-maxage since we're a shared cache
// s-maxage > max-age > Expire
// https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.10-3
const sMaxAge = cacheControlDirectives['s-maxage']
if (sMaxAge) {
return now + (sMaxAge * 1000)
}
if (cacheControlDirectives.immutable) {
// https://www.rfc-editor.org/rfc/rfc8246.html#section-2.2
return now + 31536000
}
const maxAge = cacheControlDirectives['max-age']
if (maxAge) {
return now + (maxAge * 1000)
}
if (headers.expire && typeof headers.expire === 'string') {
// https://www.rfc-editor.org/rfc/rfc9111.html#section-5.3
return now + (Date.now() - new Date(headers.expire).getTime())
}
return undefined
}
/**
* @param {number} now
* @param {import('../util/cache.js').CacheControlDirectives} cacheControlDirectives
* @param {number} staleAt
*/
function determineDeleteAt (now, cacheControlDirectives, staleAt) {
if (cacheControlDirectives['stale-while-revalidate']) {
return now + (cacheControlDirectives['stale-while-revalidate'] * 1000)
}
return staleAt
}
/**
* Strips headers required to be removed in cached responses
* @param {Buffer[]} rawHeaders
* @param {string[]} parsedRawHeaders
* @param {import('../util/cache.js').CacheControlDirectives} cacheControlDirectives
* @returns {Buffer[]}
*/
function stripNecessaryHeaders (rawHeaders, parsedRawHeaders, cacheControlDirectives) {
const headersToRemove = ['connection']
if (Array.isArray(cacheControlDirectives['no-cache'])) {
headersToRemove.push(...cacheControlDirectives['no-cache'])
}
if (Array.isArray(cacheControlDirectives['private'])) {
headersToRemove.push(...cacheControlDirectives['private'])
}
let strippedHeaders
let offset = 0
for (let i = 0; i < parsedRawHeaders.length; i += 2) {
const headerName = parsedRawHeaders[i]
if (headersToRemove.includes(headerName)) {
// We have at least one header we want to remove
if (!strippedHeaders) {
// This is the first header we want to remove, let's create the array
// Since we're stripping headers, this will over allocate. We'll trim
// it later.
strippedHeaders = new Array(parsedRawHeaders.length)
// Backfill the previous headers into it
for (let j = 0; j < i; j += 2) {
strippedHeaders[j] = parsedRawHeaders[j]
strippedHeaders[j + 1] = parsedRawHeaders[j + 1]
}
}
// We can't map indices 1:1 from stripped headers to rawHeaders without
// creating holes (if we skip a header, we now have two holes where at
// element should be). So, let's keep an offset to keep strippedHeaders
// flattened. We can also use this at the end for trimming the empty
// elements off of strippedHeaders.
offset += 2
continue
}
// We want to keep this header. Let's add it to strippedHeaders if it exists
if (strippedHeaders) {
strippedHeaders[i - offset] = parsedRawHeaders[i]
strippedHeaders[i + 1 - offset] = parsedRawHeaders[i + 1]
}
}
if (strippedHeaders) {
// Trim off the empty values at the end
strippedHeaders.length -= offset
}
return strippedHeaders
? util.encodeRawHeaders(strippedHeaders)
: rawHeaders
}
module.exports = CacheHandler