Skip to content
Myr

feat(cache): add first-class support for QUERY requests (#5119)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* feat(cache): support QUERY requests * fix(cache): report unavailable QUERY hashing * fix(cache): include request method in cache keys * docs(cache): show QUERY-compatible registration

authored by Taku Amano · committed by Yusuke Wada · parent 75b8a49 · Browse files · 2 files+547 added−14 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+547 added−14 removed

  • tests:+394 added−1 removed
  • other:+153 added−13 removed

2 files+547 added−14 removed

modified:src/middleware/cache/index.test.ts+394 added-1 removed
99 unmodified lines
100101 it('Should use dynamically generated cache key', async () => {102 await app.request('http://localhost/dynamic-cache-key/')103 const cache = await caches.open('my-app-v1')104 const response = await cache.match(dynamicCacheKey)104 const response = await cache.match(105 'http://localhost/.hono/cache?__hono_cache_key=dynamic-cache-key&__hono_cache_method=GET'106 )107 expect(response).not.toBeNull()108 })109110 it('Should retrieve cached response with dynamic cache name and key', async () => {
295 unmodified lines
406 })407 const res = await app.request('/')408 expect(res.status).toBe(200)409 expect(spy).toHaveBeenCalledOnce()410 expect(spy).toHaveBeenCalledWith(411 'Cache Middleware is not enabled because caches is not defined.'412 )413 vi.unstubAllGlobals()414 })415416 it('Should suppress default log when onCacheNotAvailable is false', async () => {
328 unmodified lines
745 expect(caches.open).not.toHaveBeenCalled()746 expect(putSpy).not.toHaveBeenCalled()747 })748749 it('Should cache QUERY responses without consuming the handler request body', async () => {750 const { mockCache } = stubStoreBackedCache()751 const app = new Hono()752 let queryCount = 0753 app.use('*', cache({ cacheName: 'query-test', wait: true, cacheControl: 'max-age=10' }))754 app.on('QUERY', '/resource', async (c) => {755 queryCount++756 c.header('X-Count', `${queryCount}`)757 return c.text(await c.req.raw.text())758 })759760 const request = () =>761 app.request('/resource', {762 method: 'QUERY',763 headers: { 'Content-Type': 'application/json' },764 body: '{"query":"hono"}',765 })766767 await request()768 const res = await request()769770 expect(await res.text()).toBe('{"query":"hono"}')771 expect(res.headers.get('X-Count')).toBe('1')772 expect(res.headers.get('Cache-Control')).toBe('max-age=10')773 expect(mockCache.put).toHaveBeenCalledOnce()774 })775776 it('Should bypass QUERY caching when the measured body exceeds the configured limit', async () => {777 const { mockCache } = stubStoreBackedCache()778 const app = new Hono()779 let queryCount = 0780 app.use('*', cache({ cacheName: 'query-body-limit-test', wait: true, maxQueryBodySize: 4 }))781 app.on('QUERY', '/resource', async (c) => {782 queryCount++783 c.header('X-Count', `${queryCount}`)784 return c.text(await c.req.text())785 })786787 const request = () => {788 const body = new ReadableStream({789 start(controller) {790 controller.enqueue(new TextEncoder().encode('ab'))791 controller.enqueue(new TextEncoder().encode('cde'))792 controller.close()793 },794 })795 return app.request('/resource', {796 method: 'QUERY',797 headers: {798 'Content-Length': '1',799 'Content-Type': 'text/plain',800 },801 body,802 duplex: 'half',803 } as RequestInit & { duplex: 'half' })804 }805806 await request()807 const res = await request()808809 expect(await res.text()).toBe('abcde')810 expect(res.headers.get('X-Count')).toBe('2')811 expect(caches.open).not.toHaveBeenCalled()812 expect(mockCache.put).not.toHaveBeenCalled()813 })814815 it('Should cache QUERY requests at the configured body size limit', async () => {816 const { mockCache } = stubStoreBackedCache()817 const app = new Hono()818 let queryCount = 0819 app.use(820 '*',821 cache({ cacheName: 'query-body-limit-boundary-test', wait: true, maxQueryBodySize: 4 })822 )823 app.on('QUERY', '/resource', async (c) => {824 queryCount++825 c.header('X-Count', `${queryCount}`)826 return c.text(await c.req.text())827 })828829 const request = () =>830 app.request('/resource', {831 method: 'QUERY',832 headers: { 'Content-Type': 'text/plain' },833 body: 'abcd',834 })835836 await request()837 const res = await request()838839 expect(await res.text()).toBe('abcd')840 expect(res.headers.get('X-Count')).toBe('1')841 expect(mockCache.put).toHaveBeenCalledOnce()842 })843844 it('Should keep QUERY request content and Content-Type in separate cache variants', async () => {845 const { mockCache } = stubStoreBackedCache()846 const app = new Hono()847 let queryCount = 0848 app.use(849 '*',850 cache({ cacheName: 'query-variant-test', wait: true, keyGenerator: () => 'query-key' })851 )852 app.on('QUERY', '/resource', async (c) => {853 queryCount++854 c.header('X-Count', `${queryCount}`)855 return c.text(`${c.req.header('Content-Type')}:${await c.req.text()}`)856 })857858 const request = (body: string, contentType: string) =>859 app.request('/resource', {860 method: 'QUERY',861 headers: { 'Content-Type': contentType },862 body,863 })864865 await request('one', 'text/plain')866 const same = await request('one', 'text/plain')867 await request('two', 'text/plain')868 const differentContent = await request('two', 'text/plain')869 await request('one', 'application/json')870 const differentContentType = await request('one', 'application/json')871872 expect(same.headers.get('X-Count')).toBe('1')873 expect(differentContent.headers.get('X-Count')).toBe('2')874 expect(differentContentType.headers.get('X-Count')).toBe('3')875 expect(mockCache.put).toHaveBeenCalledTimes(3)876 })877878 it('Should keep GET and QUERY responses in separate cache entries', async () => {879 const { mockCache } = stubStoreBackedCache()880 const app = new Hono()881 app.use('*', cache({ cacheName: 'method-test', wait: true }))882 app.get('/resource', (c) => c.text('get response'))883 app.on('QUERY', '/resource', (c) => c.text('query response'))884885 await app.request('/resource')886 await app.request('/resource', {887 method: 'QUERY',888 headers: { 'Content-Type': 'application/json' },889 body: '{}',890 })891 const getRes = await app.request('/resource')892 const queryRes = await app.request('/resource', {893 method: 'QUERY',894 headers: { 'Content-Type': 'application/json' },895 body: '{}',896 })897898 expect(await getRes.text()).toBe('get response')899 expect(await queryRes.text()).toBe('query response')900 expect(mockCache.put).toHaveBeenCalledTimes(2)901 })902903 it('Should not let a GET URL alias an internally generated QUERY cache key', async () => {904 const { mockCache } = stubStoreBackedCache()905 const app = new Hono()906 app.use('*', cache({ cacheName: 'method-collision-test', wait: true }))907 app.get('/resource', (c) => c.text('get response'))908 app.get('*', (c) => c.text('get response'))909 app.on('QUERY', '/resource', (c) => c.text('query response'))910911 await app.request('/resource', {912 method: 'QUERY',913 headers: { 'Content-Type': 'application/json' },914 body: '{}',915 })916917 const queryKey = mockCache.put.mock.calls[0][0] as string918 const getRes = await app.request(queryKey)919 const queryRes = await app.request('/resource', {920 method: 'QUERY',921 headers: { 'Content-Type': 'application/json' },922 body: '{}',923 })924925 expect(await getRes.text()).toBe('get response')926 expect(await queryRes.text()).toBe('query response')927 expect(mockCache.put).toHaveBeenCalledTimes(2)928 })929930 it('Should not resolve a custom cache key as a request URL', async () => {931 const { mockCache } = stubStoreBackedCache()932 const app = new Hono()933 app.use(934 '/resource',935 cache({936 cacheName: 'custom-key-collision-test',937 wait: true,938 keyGenerator: () => 'query-key',939 })940 )941 app.use('/query-key', cache({ cacheName: 'custom-key-collision-test', wait: true }))942 app.get('/resource', (c) => c.text('custom key response'))943 app.get('/query-key', (c) => c.text('request URL response'))944945 expect(await (await app.request('/resource')).text()).toBe('custom key response')946 expect(await (await app.request('/query-key')).text()).toBe('request URL response')947 expect(mockCache.put).toHaveBeenCalledTimes(2)948 })949950 it('Should keep QUERY digest and vary values with a fragmented custom cache key', async () => {951 const { mockCache } = stubStoreBackedCache()952 const app = new Hono()953 let queryCount = 0954 app.use(955 '*',956 cache({957 cacheName: 'query-fragment-test',958 wait: true,959 vary: 'X-Variant',960 keyGenerator: (c) => `${c.req.url}#custom-fragment`,961 })962 )963 app.on('QUERY', '/resource', async (c) => {964 queryCount++965 return c.text(`${await c.req.text()}:${c.req.header('X-Variant')}`)966 })967968 const request = (body: string, variant: string) =>969 app.request('/resource', {970 method: 'QUERY',971 headers: { 'Content-Type': 'text/plain', 'X-Variant': variant },972 body,973 })974975 expect(await (await request('one', 'a')).text()).toBe('one:a')976 expect(await (await request('two', 'a')).text()).toBe('two:a')977 expect(await (await request('one', 'b')).text()).toBe('one:b')978 expect(await (await request('one', 'a')).text()).toBe('one:a')979 expect(queryCount).toBe(3)980 expect(mockCache.put).toHaveBeenCalledTimes(3)981 })982983 it('Should bypass QUERY caching when Web Crypto is not available', async () => {984 const originalCrypto = globalThis.crypto985 vi.stubGlobal('crypto', undefined)986987 try {988 const { mockCache } = stubStoreBackedCache()989 const app = new Hono()990 let queryCount = 0991 let getCount = 0992 const onCacheNotAvailable = vi.fn()993 app.use(994 '*',995 cache({996 cacheName: 'query-no-crypto-test',997 wait: true,998 onCacheNotAvailable,999 })1000 )1001 app.get('/resource', (c) => {1002 getCount++1003 c.header('X-Count', `${getCount}`)1004 return c.text('get response')1005 })1006 app.on('QUERY', '/resource', (c) => {1007 queryCount++1008 c.header('X-Count', `${queryCount}`)1009 return c.text('query response')1010 })10111012 expect(onCacheNotAvailable).toHaveBeenCalledOnce()1013 expect(onCacheNotAvailable).toHaveBeenCalledWith(1014 'Cache Middleware cannot cache QUERY requests because Web Crypto is not available.'1015 )10161017 const request = () =>1018 app.request('/resource', {1019 method: 'QUERY',1020 headers: { 'Content-Type': 'application/json' },1021 body: '{}',1022 })10231024 await request()1025 const res = await request()10261027 expect(res.headers.get('X-Count')).toBe('2')1028 expect(caches.open).not.toHaveBeenCalled()1029 expect(onCacheNotAvailable).toHaveBeenCalledOnce()10301031 await app.request('/resource')1032 const getRes = await app.request('/resource')10331034 expect(getRes.headers.get('X-Count')).toBe('1')1035 expect(mockCache.put).toHaveBeenCalledOnce()1036 } finally {1037 vi.stubGlobal('crypto', originalCrypto)1038 }1039 })10401041 it('Should bypass QUERY caching when the request content cannot be read', async () => {1042 const app = new Hono()1043 let queryCount = 01044 app.use('*', async (c, next) => {1045 await c.req.raw.text()1046 await next()1047 })1048 app.use('*', cache({ cacheName: 'query-consumed-body-test', wait: true }))1049 app.on('QUERY', '/resource', (c) => {1050 queryCount++1051 c.header('X-Count', `${queryCount}`)1052 return c.text('query response')1053 })10541055 const request = () =>1056 app.request('/resource', {1057 method: 'QUERY',1058 headers: { 'Content-Type': 'application/json' },1059 body: '{}',1060 })10611062 await request()1063 const res = await request()10641065 expect(res.headers.get('X-Count')).toBe('2')1066 expect(caches.open).not.toHaveBeenCalled()1067 })10681069 it('Should bypass QUERY caching after the body was read directly as FormData', async () => {1070 const { mockCache } = stubStoreBackedCache()1071 const app = new Hono()1072 let queryCount = 01073 app.use('*', async (c, next) => {1074 expect((await c.req.formData()).get('query')).toBe('hono')1075 await next()1076 })1077 app.use('*', cache({ cacheName: 'query-cached-form-data-test', wait: true }))1078 app.on('QUERY', '/resource', (c) => {1079 queryCount++1080 c.header('X-Count', `${queryCount}`)1081 return c.text('query response')1082 })10831084 const body = [1085 '--hono-boundary',1086 'Content-Disposition: form-data; name="query"',1087 '',1088 'hono',1089 '--hono-boundary--',1090 '',1091 ].join('\r\n')1092 const request = () =>1093 app.request('/resource', {1094 method: 'QUERY',1095 headers: { 'Content-Type': 'multipart/form-data; boundary=hono-boundary' },1096 body,1097 })10981099 await request()1100 const res = await request()11011102 expect(res.headers.get('X-Count')).toBe('2')1103 expect(caches.open).not.toHaveBeenCalled()1104 expect(mockCache.put).not.toHaveBeenCalled()1105 })11061107 it('Should cache QUERY after the body was read through HonoRequest', async () => {1108 const { mockCache } = stubStoreBackedCache()1109 const app = new Hono()1110 let queryCount = 01111 app.use('*', async (c, next) => {1112 expect(await c.req.text()).toBe('{}')1113 await next()1114 })1115 app.use('*', cache({ cacheName: 'query-cached-body-test', wait: true }))1116 app.on('QUERY', '/resource', async (c) => {1117 queryCount++1118 c.header('X-Count', `${queryCount}`)1119 return c.text(await c.req.text())1120 })11211122 const request = () =>1123 app.request('/resource', {1124 method: 'QUERY',1125 headers: { 'Content-Type': 'application/json' },1126 body: '{}',1127 })11281129 await request()1130 const res = await request()11311132 expect(await res.text()).toBe('{}')1133 expect(res.headers.get('X-Count')).toBe('1')1134 expect(mockCache.put).toHaveBeenCalledOnce()1135 })11361137 it('Should not use or store cache for POST requests', async () => {1138 const app = new Hono()1139 let postCount = 01140 app.use('*', cache({ cacheName: 'skip-test', wait: true, cacheControl: 'max-age=10' }))
21 unmodified lines
modified:src/middleware/cache/index.ts+153 added-13 removed
2 unmodified lines
3 * Cache Middleware for Hono.4 */56import type { Context } from '../../context'7import { cloneRawRequest } from '../../request'8import type { MiddlewareHandler } from '../../types'9import { sha256 } from '../../utils/crypto'10import type { StatusCode } from '../../utils/http-status'1112/**13 * status codes that can be cached by default.14 */15const defaultCacheableStatusCodes: ReadonlyArray<StatusCode> = [200]1617const defaultMaxQueryBodySize = 64 * 10241819const cacheKeyPath = '/.hono/cache'20const cacheKeyParameter = '__hono_cache_key'21const cacheMethodKeyParameter = '__hono_cache_method'22const queryDigestKeyParameter = '__hono_query_digest'23const cacheVaryKeyParameter = '__hono_cache_vary'2425type CacheKeyRequest =26 | { method: 'GET' }27 | {28 method: 'QUERY'29 digest: string30 }3132const queryRepresentationMetadataHeaders = [33 'content-type',34 'content-encoding',35 'content-language',36 'content-location',37] as const3839const shouldSkipCacheControl = (cacheControl: string | null): boolean =>40 !!cacheControl && /(?:^|,\s*)(?:private|no-(?:store|cache))(?:\s*(?:=|,|$))/i.test(cacheControl)4142const parseVaryDirectives = (vary: string | string[] | null | undefined): string[] => {
4 unmodified lines
47 .map((directive) => directive.trim().toLowerCase())48 .filter(Boolean)49}5051const createCacheKey = (52 key: string,53 requestUrl: string,54 request: CacheKeyRequest,55 varyHeaders: [string, string][]56): string => {57 const url = new URL(cacheKeyPath, requestUrl)58 url.searchParams.append(cacheKeyParameter, key.split('#', 1)[0])59 url.searchParams.append(cacheMethodKeyParameter, request.method)6061 if (request.method === 'QUERY') {62 url.searchParams.append(queryDigestKeyParameter, request.digest)63 }6465 for (const header of varyHeaders) {66 url.searchParams.append(cacheVaryKeyParameter, JSON.stringify(header))67 }6869 return url.href70}7172const shouldSkipCache = (73 res: Response,74 optionsVaryDirectives: Set<string> | undefined,75 responseVary: string[]
2 unmodified lines
78 (!optionsVaryDirectives || responseVary.some((name) => !optionsVaryDirectives.has(name)))) ||79 shouldSkipCacheControl(res.headers.get('Cache-Control')) ||80 res.headers.has('Set-Cookie')8182const reportCacheNotAvailable = (83 onCacheNotAvailable: ((reason: string) => void) | false | undefined,84 reason: string85): void => {86 if (onCacheNotAvailable === false) {87 // suppress log88 } else if (onCacheNotAvailable) {89 onCacheNotAvailable(reason)90 } else {91 console.log(reason)92 }93}9495const createQueryDigest = async (96 c: Context,97 maxQueryBodySize: number98): Promise<string | undefined> => {99 if (!globalThis.crypto?.subtle) {100 return undefined101 }102103 if (c.req.raw.bodyUsed && Object.keys(c.req.bodyCache)[0] === 'formData') {104 // FormData cannot be reserialized with a stable multipart boundary after105 // the original request body has been consumed.106 return undefined107 }108109 try {110 // RFC 10008 Section 2.7 requires QUERY cache keys to incorporate the111 // request content and its related representation metadata.112 const requestHeaders = c.req.raw.headers113 const metadata = new TextEncoder().encode(114 JSON.stringify(115 queryRepresentationMetadataHeaders.map((header) => [header, requestHeaders.get(header)])116 )117 )118 const body = (await cloneRawRequest(c.req)).body119 const chunks: Uint8Array[] = []120 let bodySize = 0121122 if (body) {123 const reader = body.getReader()124 for (;;) {125 const { done, value } = await reader.read()126 if (done) {127 break128 }129 bodySize += value.byteLength130 if (bodySize > maxQueryBodySize) {131 // Do not await cancellation because a cloned stream's cancellation132 // can wait for the original request stream to finish.133 void reader.cancel().catch(() => {})134 return undefined135 }136 chunks.push(value)137 }138 }139140 const data = new Uint8Array(metadata.byteLength + bodySize)141 data.set(metadata)142 let offset = metadata.byteLength143 for (const chunk of chunks) {144 data.set(chunk, offset)145 offset += chunk.byteLength146 }147148 return (await sha256(data)) ?? undefined149 } catch {150 // A QUERY response cannot be cached safely if its content cannot be read.151 return undefined152 }153}154155/**156 * Cache Middleware for Hono.157 *158 * @see {@link https://hono.dev/docs/middleware/builtin/cache}
2 unmodified lines
161 * @param {string | Function} options.cacheName - The name of the cache. Can be used to store multiple caches with different identifiers.162 * @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.163 * @param {string} [options.cacheControl] - A string of directives for the `Cache-Control` header.164 * @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.47 * @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.165 * @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. QUERY keys additionally include a digest of the request content and its representation metadata.166 * @param {number} [options.maxQueryBodySize=65536] - The maximum QUERY request body size in bytes that can be cached. Larger QUERY requests bypass the cache.167 * @param {number[]} [options.cacheableStatusCodes=[200]] - An array of status codes that can be cached.49 * @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.168 * @param {Function | false} [options.onCacheNotAvailable] - A callback invoked with the reason when `globalThis.caches` is not available or QUERY caching cannot use Web Crypto. By default, the reason is logged to the console. Set to `false` to suppress the log, or provide a custom function.169 * @returns {MiddlewareHandler} The middleware handler function.170 * @throws {Error} If the `vary` option includes "*".171 *172 * @example173 * ```ts55 * app.get(174 * app.use(175 * '*',176 * cache({177 * cacheName: 'my-app',178 * cacheControl: 'max-age=3600',
6 unmodified lines
185 wait?: boolean186 cacheControl?: string187 vary?: string | string[]188 keyGenerator?: (c: Context) => Promise<string> | string189 maxQueryBodySize?: number190 cacheableStatusCodes?: StatusCode[]71 onCacheNotAvailable?: (() => void) | false191 onCacheNotAvailable?: ((reason: string) => void) | false192}): MiddlewareHandler => {193 if (!globalThis.caches) {74 if (options.onCacheNotAvailable === false) {75 // suppress log76 } else if (options.onCacheNotAvailable) {77 options.onCacheNotAvailable()78 } else {79 console.log('Cache Middleware is not enabled because caches is not defined.')80 }194 reportCacheNotAvailable(195 options.onCacheNotAvailable,196 'Cache Middleware is not enabled because caches is not defined.'197 )198 return async (_c, next) => await next()199 }200201 if (!globalThis.crypto?.subtle) {202 reportCacheNotAvailable(203 options.onCacheNotAvailable,204 'Cache Middleware cannot cache QUERY requests because Web Crypto is not available.'205 )206 }207208 if (options.wait === undefined) {209 options.wait = false210 }211
12 unmodified lines
224225 const cacheableStatusCodes = new Set<number>(226 options.cacheableStatusCodes ?? defaultCacheableStatusCodes227 )228 const maxQueryBodySize = options.maxQueryBodySize ?? defaultMaxQueryBodySize229230 const addHeader = (c: Context, responseVary: string[]) => {231 if (cacheControlDirectives) {232 const existingDirectives =
30 unmodified lines
263 }264 }265266 return async function cache(c, next) {142 if (c.req.method !== 'GET' || c.req.raw.headers.has('Authorization')) {267 if (268 (c.req.method !== 'GET' && c.req.method !== 'QUERY') ||269 c.req.raw.headers.has('Authorization')270 ) {271 await next()272 return273 }274275 let cacheKeyRequest: CacheKeyRequest = { method: 'GET' }276 if (c.req.method === 'QUERY') {277 const digest = await createQueryDigest(c, maxQueryBodySize)278 if (digest === undefined) {279 await next()280 return281 }282 cacheKeyRequest = { method: 'QUERY', digest }283 }284285 let key = c.req.url286 if (options.keyGenerator) {287 key = await options.keyGenerator(c)288 }289 const varyHeaders: [string, string][] = []290 if (varyDirectives) {291 for (const directive of varyDirectives) {292 const value = c.req.raw.headers.get(directive) ?? ''154 key += `::${directive}=${encodeURIComponent(value)}`293 varyHeaders.push([directive, value])294 }295 }296 key = createCacheKey(key, c.req.url, cacheKeyRequest, varyHeaders)297298 const cacheName =299 typeof options.cacheName === 'function' ? await options.cacheName(c) : options.cacheName300 const cache = await caches.open(cacheName)
24 unmodified lines