index.ts
This file
Path
src/middleware/cache/index.ts
324 lines · 10.6 KiB · TypeScript
Last changed by
Merge commit from forkTaku Amanobefore adoption9c28d72
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–6why, one step back1/**2 * @module3 * Cache Middleware for Hono.4 */56import type { Context } from '../../context'Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 7why, one step back7import { cloneRawRequest } from '../../request'Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 8why, one step back8import type { MiddlewareHandler } from '../../types'Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 9why, one step back9import { sha256 } from '../../utils/crypto'Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 10–16why, one step back10import type { StatusCode } from '../../utils/http-status'1112/**13 * status codes that can be cached by default.14 */15const defaultCacheableStatusCodes: ReadonlyArray<StatusCode> = [200]16Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 17–38why, one step back17const 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 const38Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 39–50why, one step back39const shouldSkipCacheControl = (cacheControl: string | null): boolean =>40 !!cacheControl && /(?:^|,\s*)(?:private|no-(?:store|cache))(?:\s*(?:=|,|$))/i.test(cacheControl)4142const parseVaryDirectives = (vary: string | string[] | null | undefined): string[] => {43 if (vary == null) {44 return []45 }46 return (Array.isArray(vary) ? vary : vary.split(','))47 .map((directive) => directive.trim().toLowerCase())48 .filter(Boolean)49}50Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 51–57why, one step back51const createCacheKey = (52 key: string,53 requestUrl: string,54 request: CacheKeyRequest,55 varyHeaders: [string, string][]56): string => {57 const url = new URL(cacheKeyPath, requestUrl)Merge commit from forkTaku Amanobefore adoption9c28d72
line 58why, one step back58 url.searchParams.append(cacheKeyParameter, key)Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 59–71why, one step back59 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}71Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 72–81why, one step back72const shouldSkipCache = (73 res: Response,74 optionsVaryDirectives: Set<string> | undefined,75 responseVary: string[]76): boolean =>77 (responseVary.length &&78 (!optionsVaryDirectives || responseVary.some((name) => !optionsVaryDirectives.has(name)))) ||79 shouldSkipCacheControl(res.headers.get('Cache-Control')) ||80 res.headers.has('Set-Cookie')81Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 82–154why, one step back82const 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}154Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 155–164why, one step back155/**156 * Cache Middleware for Hono.157 *158 * @see {@link https://hono.dev/docs/middleware/builtin/cache}159 *160 * @param {Object} options - The options for the cache middleware.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.Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 165–166why, one step back165 * @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.Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 167why, one step back167 * @param {number[]} [options.cacheableStatusCodes=[200]] - An array of status codes that can be cached.Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 168why, one step back168 * @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.Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 169–173why, one step back169 * @returns {MiddlewareHandler} The middleware handler function.170 * @throws {Error} If the `vary` option includes "*".171 *172 * @example173 * ```tsMerge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 174why, one step back174 * app.use(Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 175–188why, one step back175 * '*',176 * cache({177 * cacheName: 'my-app',178 * cacheControl: 'max-age=3600',179 * })180 * )181 * ```182 */183export const cache = (options: {184 cacheName: string | ((c: Context) => Promise<string> | string)185 wait?: boolean186 cacheControl?: string187 vary?: string | string[]188 keyGenerator?: (c: Context) => Promise<string> | stringMerge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 189why, one step back189 maxQueryBodySize?: numberMerge commit from forkYusuke Wadabefore adoptionf0b094d
line 190why, one step back190 cacheableStatusCodes?: StatusCode[]Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 191why, one step back191 onCacheNotAvailable?: ((reason: string) => void) | falseMerge commit from forkYusuke Wadabefore adoptionf0b094d
lines 192–193why, one step back192}): MiddlewareHandler => {193 if (!globalThis.caches) {Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 194–197why, one step back194 reportCacheNotAvailable(195 options.onCacheNotAvailable,196 'Cache Middleware is not enabled because caches is not defined.'197 )Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 198–200why, one step back198 return async (_c, next) => await next()199 }200Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 201–207why, one step back201 if (!globalThis.crypto?.subtle) {202 reportCacheNotAvailable(203 options.onCacheNotAvailable,204 'Cache Middleware cannot cache QUERY requests because Web Crypto is not available.'205 )206 }207Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 208–227why, one step back208 if (options.wait === undefined) {209 options.wait = false210 }211212 const cacheControlDirectives = options.cacheControl213 ?.split(',')214 .map((directive) => directive.toLowerCase())215 const optionsVaryList = parseVaryDirectives(options.vary)216 const varyDirectives = optionsVaryList.length ? new Set(optionsVaryList) : undefined217 // RFC 7231 Section 7.1.4 specifies that "*" is not allowed in Vary header.218 // See: https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.4219 if (varyDirectives?.has('*')) {220 throw new Error(221 'Middleware vary configuration cannot include "*", as it disallows effective caching.'222 )223 }224225 const cacheableStatusCodes = new Set<number>(226 options.cacheableStatusCodes ?? defaultCacheableStatusCodes227 )Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 228why, one step back228 const maxQueryBodySize = options.maxQueryBodySize ?? defaultMaxQueryBodySizeMerge commit from forkYusuke Wadabefore adoptionf0b094d
lines 229–235why, one step back229230 const addHeader = (c: Context, responseVary: string[]) => {231 if (cacheControlDirectives) {232 const existingDirectives =233 c.res.headers234 .get('Cache-Control')235 ?.split(',')fix(cache): deduplicate Cache-Control directives case-insensitively (#5025)nyxst4ckbefore adoptiona48c8bf
lines 236–239why, one step back236 // Directive names are case-insensitive (RFC 7234 §5.2); lower-case so237 // the case-insensitive de-dup check below matches handler-set names238 // like `Max-Age`.239 .map((d) => d.trim().split('=', 1)[0].toLowerCase()) ?? []Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 240–266why, one step back240 for (const directive of cacheControlDirectives) {241 let [name, value] = directive.trim().split('=', 2)242 name = name.toLowerCase()243 if (!existingDirectives.includes(name)) {244 c.header('Cache-Control', `${name}${value ? `=${value}` : ''}`, { append: true })245 }246 }247 }248249 if (varyDirectives) {250 if (responseVary.length === 0) {251 c.header('Vary', Array.from(varyDirectives).join(', '))252 } else {253 const merged = new Set(varyDirectives)254 for (const directive of responseVary) {255 merged.add(directive)256 }257 if (merged.has('*')) {258 c.header('Vary', '*')259 } else {260 c.header('Vary', Array.from(merged).join(', '))261 }262 }263 }264 }265266 return async function cache(c, next) {Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 267–270why, one step back267 if (268 (c.req.method !== 'GET' && c.req.method !== 'QUERY') ||269 c.req.raw.headers.has('Authorization')270 ) {Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 271–274why, one step back271 await next()272 return273 }274Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 275–284why, one step back275 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 }284Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 285–288why, one step back285 let key = c.req.url286 if (options.keyGenerator) {287 key = await options.keyGenerator(c)288 }Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 289why, one step back289 const varyHeaders: [string, string][] = []Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 290–292why, one step back290 if (varyDirectives) {291 for (const directive of varyDirectives) {292 const value = c.req.raw.headers.get(directive) ?? ''Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 293why, one step back293 varyHeaders.push([directive, value])Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 294–295why, one step back294 }295 }Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 296why, one step back296 key = createCacheKey(key, c.req.url, cacheKeyRequest, varyHeaders)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 297–324why, one step back297298 const cacheName =299 typeof options.cacheName === 'function' ? await options.cacheName(c) : options.cacheName300 const cache = await caches.open(cacheName)301 const response = await cache.match(key)302 if (response) {303 return new Response(response.body, response)304 }305306 await next()307 if (!cacheableStatusCodes.has(c.res.status)) {308 return309 }310 const responseVary = parseVaryDirectives(c.res.headers.get('Vary'))311 addHeader(c, responseVary)312313 if (shouldSkipCache(c.res, varyDirectives, responseVary)) {314 return315 }316317 const res = c.res.clone()318 if (options.wait) {319 await cache.put(key, res)320 } else {321 c.executionCtx.waitUntil(cache.put(key, res))322 }323 }324}