feat(compress): improve compress middleware (#3317)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* improve compression middleware * run lint & format * improve test * refactor * fix setting headers * fix ctx.res setter add tests * revert change * minor * remove workaround and simplify * remove diff * update test * improvements
authored by nitedani · committed by GitHub · parent f9349ec · Browse files · 2 files·+195 added−67 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+195 added−67 removed
- tests:+160 added−65 removed
- other:+35 added−2 removed
Provenance
- Commit
12893e2- Tree
42f697b- Author
nitedani <67418286+nitedani@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
f9349ec
2 files changed+195 added−67 removed
modified:src/middleware/compress/index.test.ts+160 added-65 removed
112344567898910101112131415161213171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686916177071727374757619777879222324252680818283282930318485868788893334353637389040414243919293944546474849959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913052535413113213313413556575859601361371381391401411421431441451466364656614714814915015115268697071153737475154155156157158159777879160161162163164818283848586871651661671681691701711721738990174175176177178179180181182183184185186187import { Hono } from '../../hono'import { compress } from '.'import { stream } from '../../helper/streaming'import { Hono } from '../../hono'
describe('Parse Compress Middleware', () => {describe('Compress Middleware', () => { const app = new Hono()
// Apply compress middleware to all routes app.use('*', compress()) app.get('/hello', async (ctx) => { ctx.header('Content-Length', '5') return ctx.text('hello')
// Test routes app.get('/small', (c) => { c.header('Content-Type', 'text/plain') c.header('Content-Length', '5') return c.text('small') }) app.notFound((c) => { return c.text('Custom NotFound', 404) app.get('/large', (c) => { c.header('Content-Type', 'text/plain') c.header('Content-Length', '1024') return c.text('a'.repeat(1024)) }) app.get('/small-json', (c) => { c.header('Content-Type', 'application/json') c.header('Content-Length', '26') return c.json({ message: 'Hello, World!' }) }) app.get('/large-json', (c) => { c.header('Content-Type', 'application/json') c.header('Content-Length', '1024') return c.json({ data: 'a'.repeat(1024), message: 'Large JSON' }) }) app.get('/no-transform', (c) => { c.header('Content-Type', 'text/plain') c.header('Content-Length', '1024') c.header('Cache-Control', 'no-transform') return c.text('a'.repeat(1024)) }) app.get('/jpeg-image', (c) => { c.header('Content-Type', 'image/jpeg') c.header('Content-Length', '1024') return c.body(new Uint8Array(1024)) // Simulated JPEG data }) app.get('/already-compressed', (c) => { c.header('Content-Type', 'application/octet-stream') c.header('Content-Encoding', 'br') c.header('Content-Length', '1024') return c.body(new Uint8Array(1024)) // Simulated compressed data }) app.get('/stream', (c) => stream(c, async (stream) => { c.header('Content-Type', 'text/plain') // 60000 bytes for (let i = 0; i < 10000; i++) { await stream.write('chunk ') } }) ) app.get('/already-compressed-stream', (c) => stream(c, async (stream) => { c.header('Content-Type', 'text/plain') c.header('Content-Encoding', 'br') // 60000 bytes for (let i = 0; i < 10000; i++) { await stream.write(new Uint8Array([0, 1, 2, 3, 4, 5])) // Simulated compressed data } }) ) app.notFound((c) => c.text('Custom NotFound', 404))
it('gzip', async () => { const req = new Request('http://localhost/hello', { const testCompression = async ( path: string, acceptEncoding: string, expectedEncoding: string | null ) => { const req = new Request(`http://localhost${path}`, { method: 'GET', headers: new Headers({ 'Accept-Encoding': 'gzip' }), headers: new Headers({ 'Accept-Encoding': acceptEncoding }), }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(res.headers.get('Content-Encoding')).toEqual('gzip') expect(res.headers.get('Content-Length')).toBeNull() }) expect(res.headers.get('Content-Encoding')).toBe(expectedEncoding) return res }
it('deflate', async () => { const req = new Request('http://localhost/hello', { method: 'GET', headers: new Headers({ 'Accept-Encoding': 'deflate' }), describe('Compression Behavior', () => { it('should compress large responses with gzip', async () => { const res = await testCompression('/large', 'gzip', 'gzip') expect(res.headers.get('Content-Length')).toBeNull() expect((await res.arrayBuffer()).byteLength).toBeLessThan(1024) }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(res.headers.get('Content-Encoding')).toEqual('deflate') expect(res.headers.get('Content-Length')).toBeNull() })
it('gzip or deflate', async () => { const req = new Request('http://localhost/hello', { method: 'GET', headers: new Headers({ 'Accept-Encoding': 'gzip, deflate' }), it('should compress large responses with deflate', async () => { const res = await testCompression('/large', 'deflate', 'deflate') expect((await res.arrayBuffer()).byteLength).toBeLessThan(1024) }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(res.headers.get('Content-Encoding')).toEqual('gzip') expect(res.headers.get('Content-Length')).toBeNull()
it('should prioritize gzip over deflate when both are accepted', async () => { await testCompression('/large', 'gzip, deflate', 'gzip') })
it('should not compress small responses', async () => { const res = await testCompression('/small', 'gzip, deflate', null) expect(res.headers.get('Content-Length')).toBe('5') })
it('should not compress when no Accept-Encoding is provided', async () => { await testCompression('/large', '', null) })
it('should not compress images', async () => { const res = await testCompression('/jpeg-image', 'gzip', null) expect(res.headers.get('Content-Type')).toBe('image/jpeg') expect(res.headers.get('Content-Length')).toBe('1024') })
it('should not compress already compressed responses', async () => { const res = await testCompression('/already-compressed', 'gzip', 'br') expect(res.headers.get('Content-Length')).toBe('1024') })
it('should remove Content-Length when compressing', async () => { const res = await testCompression('/large', 'gzip', 'gzip') expect(res.headers.get('Content-Length')).toBeNull() })
it('should not remove Content-Length when not compressing', async () => { const res = await testCompression('/jpeg-image', 'gzip', null) expect(res.headers.get('Content-Length')).toBeDefined() }) })
it('raw', async () => { const req = new Request('http://localhost/hello', { method: 'GET', describe('JSON Handling', () => { it('should not compress small JSON responses', async () => { const res = await testCompression('/small-json', 'gzip', null) expect(res.headers.get('Content-Length')).toBe('26') }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(res.headers.get('Content-Encoding')).toBeNull() expect(res.headers.get('Content-Length')).toBe('5')
it('should compress large JSON responses', async () => { const res = await testCompression('/large-json', 'gzip', 'gzip') expect(res.headers.get('Content-Length')).toBeNull() const decompressed = await decompressResponse(res) const json = JSON.parse(decompressed) expect(json.data.length).toBe(1024) expect(json.message).toBe('Large JSON') }) })
it('Should handle Custom 404 Not Found', async () => { const req = new Request('http://localhost/not-found', { method: 'GET', headers: new Headers({ 'Accept-Encoding': 'gzip' }), describe('Streaming Responses', () => { it('should compress streaming responses written in multiple chunks', async () => { const res = await testCompression('/stream', 'gzip', 'gzip') const decompressed = await decompressResponse(res) expect(decompressed.length).toBe(60000) }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(404) expect(res.headers.get('Content-Encoding')).toEqual('gzip')
// decompress response body const decompressionStream = new DecompressionStream('gzip') const decompressedStream = res.body!.pipeThrough(decompressionStream) it('should not compress already compressed streaming responses', async () => { const res = await testCompression('/already-compressed-stream', 'gzip', 'br') expect((await res.arrayBuffer()).byteLength).toBe(60000) }) })
const textDecoder = new TextDecoder() const reader = decompressedStream.getReader() let text = '' describe('Edge Cases', () => { it('should not compress responses with Cache-Control: no-transform', async () => { await testCompression('/no-transform', 'gzip', null) })
for (;;) { const { done, value } = await reader.read() if (done) { break } text += textDecoder.decode(value, { stream: true }) } it('should handle HEAD requests without compression', async () => { const req = new Request('http://localhost/large', { method: 'HEAD', headers: new Headers({ 'Accept-Encoding': 'gzip' }), }) const res = await app.request(req) expect(res.headers.get('Content-Encoding')).toBeNull() })
text += textDecoder.decode() expect(text).toBe('Custom NotFound') it('should compress custom 404 Not Found responses', async () => { const res = await testCompression('/not-found', 'gzip', 'gzip') expect(res.status).toBe(404) const decompressed = await decompressResponse(res) expect(decompressed).toBe('Custom NotFound') }) })})
async function decompressResponse(res: Response): Promise<string> { const decompressedStream = res.body!.pipeThrough(new DecompressionStream('gzip')) const decompressedResponse = new Response(decompressedStream) return await decompressedResponse.text()}modified:src/middleware/compress/index.ts+35 added-2 removed
4 unmodified lines5 6 import type { MiddlewareHandler } from '../../types'7 8 const ENCODING_TYPES = ['gzip', 'deflate'] as const9+const cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i10+const compressibleContentTypeRegExp =11+ /^\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]|$)/i12 13 interface CompressionOptions {14 encoding?: (typeof ENCODING_TYPES)[number]15+ threshold?: number16 }17 18 /**19 * Compress Middleware for Hono.1 unmodified line21 * @see {@link https://hono.dev/docs/middleware/builtin/compress}22 *23 * @param {CompressionOptions} [options] - The options for the compress middleware.24 * @param {'gzip' | 'deflate'} [options.encoding] - The compression scheme to allow for response compression. Either 'gzip' or 'deflate'. If not defined, both are allowed and will be used based on the Accept-Encoding header. 'gzip' is prioritized if this option is not provided and the client provides both in the Accept-Encoding header.25+ * @param {number} [options.threshold=1024] - The minimum size in bytes to compress. Defaults to 1024 bytes.26 * @returns {MiddlewareHandler} The middleware handler function.27 *28 * @example29 * ```ts2 unmodified lines32 * app.use(compress())33 * ```34 */35 export const compress = (options?: CompressionOptions): MiddlewareHandler => {36+ const threshold = options?.threshold ?? 102437+38 return async function compress(ctx, next) {39 await next()40+41+ const contentLength = ctx.res.headers.get('Content-Length')42+43+ // Check if response should be compressed44+ if (45+ ctx.res.headers.has('Content-Encoding') || // already encoded46+ ctx.req.method === 'HEAD' || // HEAD request47+ (contentLength && Number(contentLength) < threshold) || // content-length below threshold48+ !shouldCompress(ctx.res) || // not compressible type49+ !shouldTransform(ctx.res) // cache-control: no-transform50+ ) {51+ return52+ }53+54 const accepted = ctx.req.header('Accept-Encoding')55 const encoding =56 options?.encoding ?? ENCODING_TYPES.find((encoding) => accepted?.includes(encoding))57 if (!encoding || !ctx.res.body) {58 return59 }39- // eslint-disable-next-line @typescript-eslint/ban-ts-comment40- // @ts-ignore60+61+ // Compress the response62 const stream = new CompressionStream(encoding)63 ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res)64 ctx.res.headers.delete('Content-Length')65 ctx.res.headers.set('Content-Encoding', encoding)66 }67 }68+69+const shouldCompress = (res: Response) => {70+ const type = res.headers.get('Content-Type')71+ return type && compressibleContentTypeRegExp.test(type)72+}73+74+const shouldTransform = (res: Response) => {75+ const cacheControl = res.headers.get('Cache-Control')76+ // Don't compress for Cache-Control: no-transform77+ // https://tools.ietf.org/html/rfc7234#section-5.2.2.478+ return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl)79+}