feat(cache): key cache entries by configured vary headers (#4915)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Taku Amano · committed by GitHub · parent 48a7ccb · Browse files · 2 files·+227 added−41 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+227 added−41 removed
- tests:+184 added−2 removed
- other:+43 added−39 removed
Provenance
- Commit
e59db59- Tree
13007e4- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
48a7ccb
2 files changed+227 added−41 removed
modified:src/middleware/cache/index.test.ts+184 added-2 removed
377 unmodified lines378 })379 })380 381 describe('Cache Skipping Logic', () => {382+ const stubStoreBackedCache = () => {383+ const store = new Map<string | Request, Response>()384+ const mockCache = {385+ match: vi.fn((key: string | Request) => Promise.resolve(store.get(key)?.clone())),386+ put: vi.fn((key: string | Request, response: Response) => {387+ store.set(key, response.clone())388+ return Promise.resolve()389+ }),390+ keys: vi.fn(() => Promise.resolve(Array.from(store.keys()))),391+ }392+393+ vi.stubGlobal('caches', {394+ open: vi.fn().mockResolvedValue(mockCache),395+ })396+397+ return { mockCache }398+ }399+400 let putSpy: ReturnType<typeof vi.fn>401 let matchSpy: ReturnType<typeof vi.fn>402 403 beforeEach(() => {90 unmodified lines494 expect(putSpy).not.toHaveBeenCalled()495 }496 )497 480- it('Should set configured Vary header but not cache the response', async () => {498+ it('Should set configured Vary header and cache by the configured request header value', async () => {499+ const { mockCache } = stubStoreBackedCache()500 const app = new Hono()501 let count = 0502 app.use('*', cache({ cacheName: 'skip-test', wait: true, vary: 'Accept' }))503 app.get('/', (c) => {4 unmodified lines508 509 await app.request('/')510 const res = await app.request('/')511 expect(res.headers.get('Vary')).toBe('accept')493- expect(res.headers.get('X-Count')).toBe('2')512+ expect(res.headers.get('X-Count')).toBe('1')513+ expect(mockCache.put).toHaveBeenCalledOnce()514+ })515+516+ it('Should store separate variants for different Accept-Language request values', async () => {517+ const { mockCache } = stubStoreBackedCache()518+ const app = new Hono()519+ let count = 0520+ app.use('*', cache({ cacheName: 'vary-language-test', wait: true, vary: 'Accept-Language' }))521+ app.get('/', (c) => {522+ count++523+ c.header('X-Count', `${count}`)524+ return c.text(c.req.header('Accept-Language') ?? 'missing')525+ })526+527+ await app.request('/', {528+ headers: {529+ 'Accept-Language': 'en',530+ },531+ })532+ const en = await app.request('/', {533+ headers: {534+ 'Accept-Language': 'en',535+ },536+ })537+ await app.request('/', {538+ headers: {539+ 'Accept-Language': 'ja',540+ },541+ })542+ const ja = await app.request('/', {543+ headers: {544+ 'Accept-Language': 'ja',545+ },546+ })547+548+ expect(await en.text()).toBe('en')549+ expect(en.headers.get('X-Count')).toBe('1')550+ expect(await ja.text()).toBe('ja')551+ expect(ja.headers.get('X-Count')).toBe('2')552+ expect(mockCache.put).toHaveBeenCalledTimes(2)553+ })554+555+ it('Should keep missing and present Vary request header values in separate variants', async () => {556+ stubStoreBackedCache()557+ const app = new Hono()558+ let count = 0559+ app.use('*', cache({ cacheName: 'vary-missing-test', wait: true, vary: 'Accept-Language' }))560+ app.get('/', (c) => {561+ count++562+ c.header('X-Count', `${count}`)563+ return c.text(c.req.header('Accept-Language') ?? 'missing')564+ })565+566+ await app.request('/')567+ await app.request('/', {568+ headers: {569+ 'Accept-Language': 'en',570+ },571+ })572+ const missing = await app.request('/')573+ const present = await app.request('/', {574+ headers: {575+ 'Accept-Language': 'en',576+ },577+ })578+579+ expect(await missing.text()).toBe('missing')580+ expect(missing.headers.get('X-Count')).toBe('1')581+ expect(await present.text()).toBe('en')582+ expect(present.headers.get('X-Count')).toBe('2')583+ })584+585+ it('Should store separate variants using multiple configured request headers', async () => {586+ const { mockCache } = stubStoreBackedCache()587+ const app = new Hono()588+ let count = 0589+ app.use(590+ '*',591+ cache({ cacheName: 'vary-multiple-test', wait: true, vary: ['Accept', 'Accept-Encoding'] })592+ )593+ app.get('/', (c) => {594+ count++595+ c.header('X-Count', `${count}`)596+ return c.text(`${c.req.header('Accept')}:${c.req.header('Accept-Encoding')}`)597+ })598+599+ await app.request('/', {600+ headers: {601+ Accept: 'text/plain',602+ 'Accept-Encoding': 'gzip',603+ },604+ })605+ const same = await app.request('/', {606+ headers: {607+ Accept: 'text/plain',608+ 'Accept-Encoding': 'gzip',609+ },610+ })611+ await app.request('/', {612+ headers: {613+ Accept: 'application/json',614+ 'Accept-Encoding': 'gzip',615+ },616+ })617+ const differentAccept = await app.request('/', {618+ headers: {619+ Accept: 'application/json',620+ 'Accept-Encoding': 'gzip',621+ },622+ })623+ await app.request('/', {624+ headers: {625+ Accept: 'text/plain',626+ 'Accept-Encoding': 'br',627+ },628+ })629+ const differentEncoding = await app.request('/', {630+ headers: {631+ Accept: 'text/plain',632+ 'Accept-Encoding': 'br',633+ },634+ })635+636+ expect(same.headers.get('X-Count')).toBe('1')637+ expect(differentAccept.headers.get('X-Count')).toBe('2')638+ expect(differentEncoding.headers.get('X-Count')).toBe('3')639+ expect(mockCache.put).toHaveBeenCalledTimes(3)640+ })641+642+ it('Should store when the handler Vary header is covered by configured Vary headers', async () => {643+ const { mockCache } = stubStoreBackedCache()644+ const app = new Hono()645+ app.use('*', cache({ cacheName: 'vary-covered-test', wait: true, vary: 'Accept-Language' }))646+ app.get('/', (c) => {647+ c.header('Vary', 'Accept-Language')648+ return c.text('response')649+ })650+651+ await app.request('/')652+ expect(mockCache.put).toHaveBeenCalledOnce()653+ })654+655+ it('Should not store when the handler adds Vary headers not covered by configured Vary headers', async () => {656+ const app = new Hono()657+ app.use('*', cache({ cacheName: 'skip-test', wait: true, vary: 'Accept-Language' }))658+ app.get('/', (c) => {659+ c.header('Vary', 'Accept-Language, Cookie')660+ return c.text('response')661+ })662+663+ await app.request('/')664 expect(putSpy).not.toHaveBeenCalled()665 })666 667+ it('Should not store Vary: * responses even when Vary headers are configured', async () => {668+ const app = new Hono()669+ app.use('*', cache({ cacheName: 'skip-test', wait: true, vary: 'Accept-Language' }))670+ app.get('/', (c) => {671+ c.header('Vary', '*')672+ return c.text('response')673+ })674+675+ await app.request('/')676+ expect(putSpy).not.toHaveBeenCalled()677+ })678+679 it('Should bypass cache for Authorization requests', async () => {680 const app = new Hono()681 app.use('*', cache({ cacheName: 'skip-test', wait: true, cacheControl: 'max-age=10' }))682 app.get('/', (c) => {38 unmodified linesmodified:src/middleware/cache/index.ts+43 added-39 removed
10 unmodified lines11121314151617181516172021222324251819202127282930313222232425262728293031323334353637383940414243444544464748495036 unmodified lines87888990899091919293949495969798991001011021031041041051061071081098 unmodified lines1181191201211211221231241251261271281291301311321331341221231241251261271281291301311361321331341351361376 unmodified lines1441451461471481491501511521531541551561575 unmodified lines1631641651661641671681691661701711721731747 unmodified lines10 unmodified lines * status codes that can be cached by default. */const defaultCacheableStatusCodes: ReadonlyArray<StatusCode> = [200]
const shouldSkipCache = (res: Response) => { if (res.headers.has('Vary')) { return true }const shouldSkipCacheControl = (cacheControl: string | null): boolean => !!cacheControl && /(?:^|,\s*)(?:private|no-(?:store|cache))(?:\s*(?:=|,|$))/i.test(cacheControl)
const cacheControl = res.headers.get('Cache-Control') if ( cacheControl && /(?:^|,\s*)(?:private|no-(?:store|cache))(?:\s*(?:=|,|$))/i.test(cacheControl) ) { return trueconst parseVaryDirectives = (vary: string | string[] | null | undefined): string[] => { if (vary == null) { return [] }
if (res.headers.has('Set-Cookie')) { return true }
return false return (Array.isArray(vary) ? vary : vary.split(',')) .map((directive) => directive.trim().toLowerCase()) .filter(Boolean)}
const shouldSkipCache = ( res: Response, optionsVaryDirectives: Set<string> | undefined, responseVary: string[]): boolean => (responseVary.length && (!optionsVaryDirectives || responseVary.some((name) => !optionsVaryDirectives.has(name)))) || shouldSkipCacheControl(res.headers.get('Cache-Control')) || res.headers.has('Set-Cookie')
/** * Cache Middleware for Hono. * * @see {@link https://hono.dev/docs/middleware/builtin/cache} * * @param {Object} options - The options for the cache middleware. * @param {string | Function} options.cacheName - The name of the cache. Can be used to store multiple caches with different identifiers. * @param {boolean} [options.wait=false] - A boolean indicating if Hono should wait for the Promise of the `cache.put` function to resolve before continuing with the request. Required to be true for the Deno environment. * @param {string} [options.cacheControl] - A string of directives for the `Cache-Control` header. * @param {string | string[]} [options.vary] - Sets the `Vary` header in the response. If the original response header already contains a `Vary` header, the values are merged, removing any duplicates. * @param {string | string[]} [options.vary] - Adds the configured request headers to the cache key variants and sets the `Vary` header in the response. If the original response header already contains a `Vary` header, the values are merged, removing any duplicates. * @param {Function} [options.keyGenerator] - Generates keys for every request in the `cacheName` store. This can be used to cache data based on request parameters or context parameters. * @param {number[]} [options.cacheableStatusCodes=[200]] - An array of status codes that can be cached. * @param {Function | false} [options.onCacheNotAvailable] - A callback invoked when `globalThis.caches` is not available. By default, a message is logged to the console. Set to `false` to suppress the log, or provide a custom function. * @returns {MiddlewareHandler} The middleware handler function.36 unmodified lines
const cacheControlDirectives = options.cacheControl ?.split(',') .map((directive) => directive.toLowerCase()) const varyDirectives = Array.isArray(options.vary) ? options.vary : options.vary?.split(',').map((directive) => directive.trim()) const optionsVaryList = parseVaryDirectives(options.vary) const varyDirectives = optionsVaryList.length ? new Set(optionsVaryList) : undefined // RFC 7231 Section 7.1.4 specifies that "*" is not allowed in Vary header. // See: https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.4 if (options.vary?.includes('*')) { if (varyDirectives?.has('*')) { throw new Error( 'Middleware vary configuration cannot include "*", as it disallows effective caching.' ) }
const cacheableStatusCodes = new Set<number>( options.cacheableStatusCodes ?? defaultCacheableStatusCodes )
const addHeader = (c: Context) => { const addHeader = (c: Context, responseVary: string[]) => { if (cacheControlDirectives) { const existingDirectives = c.res.headers .get('Cache-Control')8 unmodified lines } }
if (varyDirectives) { const existingDirectives = c.res.headers .get('Vary') ?.split(',') .map((d) => d.trim()) ?? []
const vary = Array.from( new Set( [...existingDirectives, ...varyDirectives].map((directive) => directive.toLowerCase()) ) ).sort()
if (vary.includes('*')) { c.header('Vary', '*') if (responseVary.length === 0) { c.header('Vary', Array.from(varyDirectives).join(', ')) } else { const merged = new Set(varyDirectives) for (const directive of responseVary) { merged.add(directive) } if (merged.has('*')) { c.header('Vary', '*') } else { c.header('Vary', vary.join(', ')) c.header('Vary', Array.from(merged).join(', ')) } } } }
6 unmodified lines let key = c.req.url if (options.keyGenerator) { key = await options.keyGenerator(c) } if (varyDirectives) { for (const directive of varyDirectives) { const value = c.req.raw.headers.get(directive) ?? '' key += `::${directive}=${encodeURIComponent(value)}` } }
const cacheName = typeof options.cacheName === 'function' ? await options.cacheName(c) : options.cacheName const cache = await caches.open(cacheName)5 unmodified lines await next() if (!cacheableStatusCodes.has(c.res.status)) { return } addHeader(c) const responseVary = parseVaryDirectives(c.res.headers.get('Vary')) addHeader(c, responseVary)
if (shouldSkipCache(c.res)) { if (shouldSkipCache(c.res, varyDirectives, responseVary)) { return }
const res = c.res.clone()7 unmodified lines