perf(serve-static): performance optimization for precompressed feature (#3414)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* perf(serve-static): use "Set" for checking precompressed * refactor: define COMPRESSIBLE_CONTENT_TYPE_REGEX in utils * refactor: set "Content-Type" header only if the content is defined * perf(serve-static): find compressed file only if the mime type is compressible
authored by Taku Amano · committed by GitHub · parent 5f78e4e · Browse files · 4 files·+67 added−19 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+67 added−19 removed
- tests:+39 added−0 removed
- other:+28 added−19 removed
Provenance
- Commit
0edb243- Tree
1bb94d5- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
5f78e4e
4 files changed+67 added−19 removed
modified:src/middleware/compress/index.ts+2 added-3 removed
2 unmodified lines34567891010111112131451 unmodified lines666768697170717273744 unmodified lines2 unmodified lines * Compress Middleware for Hono. */
import type { MiddlewareHandler } from '../../types'import { COMPRESSIBLE_CONTENT_TYPE_REGEX } from '../../utils/compress'
const ENCODING_TYPES = ['gzip', 'deflate'] as constconst cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/iconst compressibleContentTypeRegExp = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i
interface CompressionOptions { encoding?: (typeof ENCODING_TYPES)[number] threshold?: number51 unmodified lines}
const shouldCompress = (res: Response) => { const type = res.headers.get('Content-Type') return type && compressibleContentTypeRegExp.test(type) return type && COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type)}
const shouldTransform = (res: Response) => { const cacheControl = res.headers.get('Cache-Control')4 unmodified linesmodified:src/middleware/serve-static/index.test.ts+39 added
125 unmodified lines126 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)127 expect(await res.text()).toBe('Hello in static/hello.html.br')128 })129 130+ it('Should return a pre-compressed brotli response - /static/hello.unknown', async () => {131+ const app = new Hono().use(132+ '*',133+ baseServeStatic({134+ getContent,135+ precompressed: true,136+ })137+ )138+139+ const res = await app.request('/static/hello.unknown', {140+ headers: { 'Accept-Encoding': 'wompwomp, gzip, br, deflate, zstd' },141+ })142+143+ expect(res.status).toBe(200)144+ expect(res.headers.get('Content-Encoding')).toBe('br')145+ expect(res.headers.get('Vary')).toBe('Accept-Encoding')146+ expect(await res.text()).toBe('Hello in static/hello.unknown.br')147+ })148+149 it('Should not return a pre-compressed response - /static/not-found.txt', async () => {150 const app = new Hono().use(151 '*',152 baseServeStatic({32 unmodified lines185 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)186 expect(await res.text()).toBe('Hello in static/hello.html')187 })188 189+ it('Should not find pre-compressed files - /static/hello.jpg', async () => {190+ const app = new Hono().use(191+ '*',192+ baseServeStatic({193+ getContent,194+ precompressed: true,195+ })196+ )197+198+ const res = await app.request('/static/hello.jpg', {199+ headers: { 'Accept-Encoding': 'gzip, br, deflate, zstd' },200+ })201+202+ expect(res.status).toBe(200)203+ expect(res.headers.get('Content-Encoding')).toBeNull()204+ expect(res.headers.get('Vary')).toBeNull()205+ expect(res.headers.get('Content-Type')).toMatch(/^image\/jpeg/)206+ expect(await res.text()).toBe('Hello in static/hello.jpg')207+ })208+209 it('Should return response object content as-is', async () => {210 const body = new ReadableStream()211 const response = new Response(body)212 const app = new Hono().use(16 unmodified linesmodified:src/middleware/serve-static/index.ts+16 added-16 removed
3 unmodified lines4 */5 6 import type { Context, Data } from '../../context'7 import type { Env, MiddlewareHandler } from '../../types'8+import { COMPRESSIBLE_CONTENT_TYPE_REGEX } from '../../utils/compress'9 import { getFilePath, getFilePathWithoutDefaultDocument } from '../../utils/filepath'10 import { getMimeType } from '../../utils/mime'11 12 export type ServeStaticOptions<E extends Env = Env> = {10 unmodified lines23 br: '.br',24 zstd: '.zst',25 gzip: '.gz',26 } as const27+const ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS) as (keyof typeof ENCODINGS)[]28 29 const DEFAULT_DOCUMENT = 'index.html'30 const defaultPathResolve = (path: string) => path31 65 unmodified lines97 if (content instanceof Response) {98 return c.newResponse(content.body, content)99 }100 101+ if (content) {99- const mimeType = options.mimes100- ? getMimeType(path, options.mimes) ?? getMimeType(path)101- : getMimeType(path)102+ const mimeType = options.mimes103+ ? getMimeType(path, options.mimes) ?? getMimeType(path)104+ : getMimeType(path)105 103- if (mimeType) {104- c.header('Content-Type', mimeType)105- }106+ if (mimeType) {107+ c.header('Content-Type', mimeType)108+ }109 107- if (content) {108- if (options.precompressed) {109- const acceptEncodings =110+ if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {111+ const acceptEncodingSet = new Set(112 c.req113 .header('Accept-Encoding')114 ?.split(',')115 .map((encoding) => encoding.trim())114- .filter((encoding): encoding is keyof typeof ENCODINGS =>115- Object.hasOwn(ENCODINGS, encoding)116- )116+ )117- .sort(118- (a, b) => Object.keys(ENCODINGS).indexOf(a) - Object.keys(ENCODINGS).indexOf(b)119- ) ?? []117 121- for (const encoding of acceptEncodings) {118+ for (const encoding of ENCODINGS_ORDERED_KEYS) {119+ if (!acceptEncodingSet.has(encoding)) {120+ continue121+ }122 const compressedContent = (await getContent(path + ENCODINGS[encoding], c)) as Data | null123 124 if (compressedContent) {125 content = compressedContent15 unmodified linesadded:src/utils/compress.ts+10 added
12345678910/** * @module * Constants for compression. */
/** * Match for compressible content type. */export const COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i