Skip to content
Myr

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

4 files+67 added−19 removed

modified:src/middleware/compress/index.ts+2 added-3 removed
modified:src/middleware/serve-static/index.test.ts+39 added
125 unmodified lines
126 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)127 expect(await res.text()).toBe('Hello in static/hello.html.br')128 })129130 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 )138139 const res = await app.request('/static/hello.unknown', {140 headers: { 'Accept-Encoding': 'wompwomp, gzip, br, deflate, zstd' },141 })142143 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 })148149 it('Should not return a pre-compressed response - /static/not-found.txt', async () => {150 const app = new Hono().use(151 '*',152 baseServeStatic({
32 unmodified lines
185 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)186 expect(await res.text()).toBe('Hello in static/hello.html')187 })188189 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 )197198 const res = await app.request('/static/hello.jpg', {199 headers: { 'Accept-Encoding': 'gzip, br, deflate, zstd' },200 })201202 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 })208209 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 lines
modified:src/middleware/serve-static/index.ts+16 added-16 removed
3 unmodified lines
4 */56import type { Context, Data } from '../../context'7import type { Env, MiddlewareHandler } from '../../types'8import { COMPRESSIBLE_CONTENT_TYPE_REGEX } from '../../utils/compress'9import { getFilePath, getFilePathWithoutDefaultDocument } from '../../utils/filepath'10import { getMimeType } from '../../utils/mime'1112export type ServeStaticOptions<E extends Env = Env> = {
10 unmodified lines
23 br: '.br',24 zstd: '.zst',25 gzip: '.gz',26} as const27const ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS) as (keyof typeof ENCODINGS)[]2829const DEFAULT_DOCUMENT = 'index.html'30const defaultPathResolve = (path: string) => path31
65 unmodified lines
97 if (content instanceof Response) {98 return c.newResponse(content.body, content)99 }100101 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)105103 if (mimeType) {104 c.header('Content-Type', mimeType)105 }106 if (mimeType) {107 c.header('Content-Type', mimeType)108 }109107 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 ) ?? []117121 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 | null123124 if (compressedContent) {125 content = compressedContent
15 unmodified lines
added:src/utils/compress.ts+10 added