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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325/** * @module * Cache Middleware for Hono. */
import type { Context } from '../../context'import { cloneRawRequest } from '../../request'import type { MiddlewareHandler } from '../../types'import { sha256 } from '../../utils/crypto'import type { StatusCode } from '../../utils/http-status'
/** * status codes that can be cached by default. */const defaultCacheableStatusCodes: ReadonlyArray<StatusCode> = [200]
const defaultMaxQueryBodySize = 64 * 1024
const cacheKeyPath = '/.hono/cache'const cacheKeyParameter = '__hono_cache_key'const cacheMethodKeyParameter = '__hono_cache_method'const queryDigestKeyParameter = '__hono_query_digest'const cacheVaryKeyParameter = '__hono_cache_vary'
type CacheKeyRequest = | { method: 'GET' } | { method: 'QUERY' digest: string }
const queryRepresentationMetadataHeaders = [ 'content-type', 'content-encoding', 'content-language', 'content-location',] as const
const shouldSkipCacheControl = (cacheControl: string | null): boolean => !!cacheControl && /(?:^|,\s*)(?:private|no-(?:store|cache))(?:\s*(?:=|,|$))/i.test(cacheControl)
const parseVaryDirectives = (vary: string | string[] | null | undefined): string[] => { if (vary == null) { return [] } return (Array.isArray(vary) ? vary : vary.split(',')) .map((directive) => directive.trim().toLowerCase()) .filter(Boolean)}
const createCacheKey = ( key: string, requestUrl: string, request: CacheKeyRequest, varyHeaders: [string, string][]): string => { const url = new URL(cacheKeyPath, requestUrl) url.searchParams.append(cacheKeyParameter, key) url.searchParams.append(cacheMethodKeyParameter, request.method)
if (request.method === 'QUERY') { url.searchParams.append(queryDigestKeyParameter, request.digest) }
for (const header of varyHeaders) { url.searchParams.append(cacheVaryKeyParameter, JSON.stringify(header)) }
return url.href}
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')
const reportCacheNotAvailable = ( onCacheNotAvailable: ((reason: string) => void) | false | undefined, reason: string): void => { if (onCacheNotAvailable === false) { // suppress log } else if (onCacheNotAvailable) { onCacheNotAvailable(reason) } else { console.log(reason) }}
const createQueryDigest = async ( c: Context, maxQueryBodySize: number): Promise<string | undefined> => { if (!globalThis.crypto?.subtle) { return undefined }
if (c.req.raw.bodyUsed && Object.keys(c.req.bodyCache)[0] === 'formData') { // FormData cannot be reserialized with a stable multipart boundary after // the original request body has been consumed. return undefined }
try { // RFC 10008 Section 2.7 requires QUERY cache keys to incorporate the // request content and its related representation metadata. const requestHeaders = c.req.raw.headers const metadata = new TextEncoder().encode( JSON.stringify( queryRepresentationMetadataHeaders.map((header) => [header, requestHeaders.get(header)]) ) ) const body = (await cloneRawRequest(c.req)).body const chunks: Uint8Array[] = [] let bodySize = 0
if (body) { const reader = body.getReader() for (;;) { const { done, value } = await reader.read() if (done) { break } bodySize += value.byteLength if (bodySize > maxQueryBodySize) { // Do not await cancellation because a cloned stream's cancellation // can wait for the original request stream to finish. void reader.cancel().catch(() => {}) return undefined } chunks.push(value) } }
const data = new Uint8Array(metadata.byteLength + bodySize) data.set(metadata) let offset = metadata.byteLength for (const chunk of chunks) { data.set(chunk, offset) offset += chunk.byteLength }
return (await sha256(data)) ?? undefined } catch { // A QUERY response cannot be cached safely if its content cannot be read. return undefined }}
/** * 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] - 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. QUERY keys additionally include a digest of the request content and its representation metadata. * @param {number} [options.maxQueryBodySize=65536] - The maximum QUERY request body size in bytes that can be cached. Larger QUERY requests bypass the cache. * @param {number[]} [options.cacheableStatusCodes=[200]] - An array of status codes that can be cached. * @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. * @returns {MiddlewareHandler} The middleware handler function. * @throws {Error} If the `vary` option includes "*". * * @example * ```ts * app.use( * '*', * cache({ * cacheName: 'my-app', * cacheControl: 'max-age=3600', * }) * ) * ``` */export const cache = (options: { cacheName: string | ((c: Context) => Promise<string> | string) wait?: boolean cacheControl?: string vary?: string | string[] keyGenerator?: (c: Context) => Promise<string> | string maxQueryBodySize?: number cacheableStatusCodes?: StatusCode[] onCacheNotAvailable?: ((reason: string) => void) | false}): MiddlewareHandler => { if (!globalThis.caches) { reportCacheNotAvailable( options.onCacheNotAvailable, 'Cache Middleware is not enabled because caches is not defined.' ) return async (_c, next) => await next() }
if (!globalThis.crypto?.subtle) { reportCacheNotAvailable( options.onCacheNotAvailable, 'Cache Middleware cannot cache QUERY requests because Web Crypto is not available.' ) }
if (options.wait === undefined) { options.wait = false }
const cacheControlDirectives = options.cacheControl ?.split(',') .map((directive) => directive.toLowerCase()) 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 (varyDirectives?.has('*')) { throw new Error( 'Middleware vary configuration cannot include "*", as it disallows effective caching.' ) }
const cacheableStatusCodes = new Set<number>( options.cacheableStatusCodes ?? defaultCacheableStatusCodes ) const maxQueryBodySize = options.maxQueryBodySize ?? defaultMaxQueryBodySize
const addHeader = (c: Context, responseVary: string[]) => { if (cacheControlDirectives) { const existingDirectives = c.res.headers .get('Cache-Control') ?.split(',') // Directive names are case-insensitive (RFC 7234 搂5.2); lower-case so // the case-insensitive de-dup check below matches handler-set names // like `Max-Age`. .map((d) => d.trim().split('=', 1)[0].toLowerCase()) ?? [] for (const directive of cacheControlDirectives) { let [name, value] = directive.trim().split('=', 2) name = name.toLowerCase() if (!existingDirectives.includes(name)) { c.header('Cache-Control', `${name}${value ? `=${value}` : ''}`, { append: true }) } } }
if (varyDirectives) { 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', Array.from(merged).join(', ')) } } } }
return async function cache(c, next) { if ( (c.req.method !== 'GET' && c.req.method !== 'QUERY') || c.req.raw.headers.has('Authorization') ) { await next() return }
let cacheKeyRequest: CacheKeyRequest = { method: 'GET' } if (c.req.method === 'QUERY') { const digest = await createQueryDigest(c, maxQueryBodySize) if (digest === undefined) { await next() return } cacheKeyRequest = { method: 'QUERY', digest } }
let key = c.req.url if (options.keyGenerator) { key = await options.keyGenerator(c) } const varyHeaders: [string, string][] = [] if (varyDirectives) { for (const directive of varyDirectives) { const value = c.req.raw.headers.get(directive) ?? '' varyHeaders.push([directive, value]) } } key = createCacheKey(key, c.req.url, cacheKeyRequest, varyHeaders)
const cacheName = typeof options.cacheName === 'function' ? await options.cacheName(c) : options.cacheName const cache = await caches.open(cacheName) const response = await cache.match(key) if (response) { return new Response(response.body, response) }
await next() if (!cacheableStatusCodes.has(c.res.status)) { return } const responseVary = parseVaryDirectives(c.res.headers.get('Vary')) addHeader(c, responseVary)
if (shouldSkipCache(c.res, varyDirectives, responseVary)) { return }
const res = c.res.clone() if (options.wait) { await cache.put(key, res) } else { c.executionCtx.waitUntil(cache.put(key, res)) } }}