Skip to content

feat: add br & zstd to supported compression 🗜️ algos #4549

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,45 @@ Default value: `{ minBytes: 1024 }`.
Defines server handling of content encoding requests. If `false`, response content encoding is
disabled and no compression is performed by the server.

##### <a name="server.options.compression.enableBrotli" /> `server.options.compression.enableBrotli`

Default value: `false`.

Enables built-in support of `brotli` compression algorithm.

Available values:

- `false` - no compression.
- `true` - compression with system defaults.
- [`BrotliOptions`](https://nodejs.org/api/zlib.html#class-brotlioptions) - compression with specified options.

##### <a name="server.options.compression.enableZstd" /> `server.options.compression.enableZstd`

Default value: `false`.

Enables built-in support of `zstd` compression algorithm (node: `>=22.15.0`).
Zstd compression is experimental (see [node Zstd documentation](https://nodejs.org/api/zlib.html#zlibcreatezstdcompressoptions)).

Available values:

- `false` - no compression.
- `true` - compression with system defaults.
- [`ZstdOptions`](https://nodejs.org/api/zlib.html#class-zstdoptions) - compression with specified options.

##### <a name="server.options.compression.minBytes" /> `server.options.compression.minBytes`

Default value: '1024'.

Sets the minimum response payload size in bytes that is required for content encoding compression.
If the payload size is under the limit, no compression is performed.

##### <a name="server.options.compression.priority" /> `server.options.compression.priority`

Default value: `null`.

Sets the priority for content encoding compression algorithms in descending order,
e.g.: `['zstd', 'br', 'gzip', 'deflate']`.

#### <a name="server.options.debug" /> `server.options.debug`

Default value: `{ request: ['implementation'] }`.
Expand Down
41 changes: 39 additions & 2 deletions lib/compression.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,17 @@ const Accept = require('@hapi/accept');
const Bounce = require('@hapi/bounce');
const Hoek = require('@hapi/hoek');


const internals = {
common: ['gzip, deflate', 'deflate, gzip', 'gzip', 'deflate', 'gzip, deflate, br']
common: [
'gzip, deflate, br, zstd',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It makes sense to update the common encoding with 'gzip, deflate, br, zstd', as this is used by both Chrome and Firefox. This can go in a separate PR.

'gzip, deflate, br',
'zstd',
'br',
'gzip, deflate',
'deflate, gzip',
'gzip',
'deflate'
]
};


Expand Down Expand Up @@ -116,4 +124,33 @@ exports = module.exports = internals.Compression = class {
Hoek.assert(encoder !== undefined, `Unknown encoding ${encoding}`);
return encoder(request.route.settings.compression[encoding]);
}

enableBrotliCompression(compressionOptions) {

const defaults = {
params: {
[Zlib.constants.BROTLI_PARAM_QUALITY]: 4
}
};
compressionOptions = Hoek.applyToDefaults(defaults, compressionOptions);
this.decoders.br = (options) => Zlib.createBrotliDecompress({ ...options, ...compressionOptions });
this.encoders.br = (options) => Zlib.createBrotliCompress({ ...options, ...compressionOptions });
this.setPriority(['br']);
}

enableZstdCompression(compressionOptions) {

/* $lab:coverage:off$ */
Hoek.assert(!!Zlib.constants.ZSTD_CLEVEL_DEFAULT, 'Zstd is not supported by the engine');
this.decoders.zstd = (options) => Zlib.createZstdDecompress({ ...options, ...compressionOptions });
this.encoders.zstd = (options) => Zlib.createZstdCompress({ ...options, ...compressionOptions });
this.setPriority(['zstd']);
/* $lab:coverage:on$ */
}

setPriority(priority) {

this.encodings = [...new Set([...priority, ...this.encodings])];
this._updateCommons();
}
};
11 changes: 10 additions & 1 deletion lib/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,16 @@ internals.server = Validate.object({
autoListen: Validate.boolean(),
cache: Validate.allow(null), // Validated elsewhere
compression: Validate.object({
minBytes: Validate.number().min(1).integer().default(1024)
enableBrotli: Validate.alternatives([
Validate.boolean(),
Validate.object()
]).default(false),
enableZstd: Validate.alternatives([
Validate.boolean(),
Validate.object()
]).default(false),
minBytes: Validate.number().min(1).integer().default(1024),
priority: Validate.array().items(Validate.string().valid('gzip', 'deflate', 'br', 'zstd')).default(null)
})
.allow(false)
.default(),
Expand Down
14 changes: 14 additions & 0 deletions lib/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,20 @@ exports = module.exports = internals.Core = class {
this._debug();
this._initializeCache();

if (this.settings.compression.enableBrotli) {
this.compression.enableBrotliCompression(this.settings.compression.enableBrotli);
}

/* $lab:coverage:off$ */
if (this.settings.compression.enableZstd) {
this.compression.enableZstdCompression(this.settings.compression.enableZstd);
}
/* $lab:coverage:on$ */

if (this.settings.compression.priority) {
this.compression.setPriority(this.settings.compression.priority);
}

if (this.settings.routes.validate.validator) {
this.validator = Validation.validator(this.settings.routes.validate.validator);
}
Expand Down
6 changes: 5 additions & 1 deletion lib/types/server/encoders.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createDeflate, createGunzip, createGzip, createInflate } from 'zlib';
import { createBrotliCompress, createBrotliDecompress, createDeflate, createGunzip, createGzip, createInflate, createZstdCompress, createZstdDecompress } from 'zlib';

/**
* Available [content encoders](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder).
Expand All @@ -7,6 +7,8 @@ export interface ContentEncoders {

deflate: typeof createDeflate;
gzip: typeof createGzip;
br: typeof createBrotliCompress;
zstd: typeof createZstdCompress;
}

/**
Expand All @@ -16,4 +18,6 @@ export interface ContentDecoders {

deflate: typeof createInflate;
gzip: typeof createGunzip;
br: typeof createBrotliDecompress;
zstd: typeof createZstdDecompress;
}
4 changes: 4 additions & 0 deletions lib/types/server/options.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as http from 'http';
import * as https from 'https';
import { BrotliOptions, ZstdOptions } from 'zlib';

import { MimosOptions } from '@hapi/mimos';

Expand All @@ -9,7 +10,10 @@ import { CacheProvider, ServerOptionsCache } from './cache';
import { SameSitePolicy, ServerStateCookieOptions } from './state';

export interface ServerOptionsCompression {
enableBrotli: boolean | BrotliOptions;
enableZstd: boolean | ZstdOptions;
minBytes: number;
priority: string[];
}

/**
Expand Down
12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@
"@hapi/catbox": "^12.1.1",
"@hapi/catbox-memory": "^6.0.2",
"@hapi/heavy": "^8.0.1",
"@hapi/hoek": "^11.0.6",
"@hapi/hoek": "^11.0.7",
"@hapi/mimos": "^7.0.1",
"@hapi/podium": "^5.0.1",
"@hapi/podium": "^5.0.2",
"@hapi/shot": "^6.0.1",
"@hapi/somever": "^4.1.1",
"@hapi/statehood": "^8.2.0",
Expand All @@ -47,15 +47,15 @@
"@hapi/code": "^9.0.3",
"@hapi/eslint-plugin": "^6.0.0",
"@hapi/inert": "^7.1.0",
"@hapi/joi-legacy-test": "npm:@hapi/joi@^15.0.0",
"@hapi/joi-legacy-test": "npm:@hapi/joi@^15.1.1",
"@hapi/lab": "^25.3.2",
"@hapi/vision": "^7.0.3",
"@hapi/wreck": "^18.1.0",
"@types/node": "^18.19.59",
"@types/node": "^22.17.0",
"handlebars": "^4.7.8",
"joi": "^17.13.3",
"legacy-readable-stream": "npm:readable-stream@^1.0.34",
"typescript": "^4.9.4"
"legacy-readable-stream": "npm:readable-stream@^1.1.14",
"typescript": "^5.9.2"
},
"scripts": {
"test": "lab -a @hapi/code -t 100 -L -m 5000 -Y",
Expand Down
3 changes: 3 additions & 0 deletions test/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const ChildProcess = require('child_process');
const Http = require('http');
const Net = require('net');
const Zlib = require('zlib');

const internals = {};

Expand Down Expand Up @@ -30,3 +31,5 @@ internals.hasIPv6 = () => {
exports.hasLsof = internals.hasLsof();

exports.hasIPv6 = internals.hasIPv6();

exports.hasZstd = !!Zlib.constants.ZSTD_CLEVEL_DEFAULT;
50 changes: 50 additions & 0 deletions test/payload.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ const Hoek = require('@hapi/hoek');
const Lab = require('@hapi/lab');
const Wreck = require('@hapi/wreck');

const Common = require('./common');

const internals = {};


Expand Down Expand Up @@ -525,6 +527,54 @@ describe('Payload', () => {
expect(res.result).to.equal(message);
});

it('handles br payload', async () => {

const message = { 'msg': 'This message is going to be brotlied.' };
const server = Hapi.server({ compression: { enableBrotli: true } });
server.route({ method: 'POST', path: '/', handler: (request) => request.payload });

const compressed = await new Promise((resolve) => Zlib.brotliCompress(JSON.stringify(message), (ignore, result) => resolve(result)));

const request = {
method: 'POST',
url: '/',
headers: {
'content-type': 'application/json',
'content-encoding': 'br',
'content-length': compressed.length
},
payload: compressed
};

const res = await server.inject(request);
expect(res.result).to.exist();
expect(res.result).to.equal(message);
});

it('handles zstd payload', { skip: !Common.hasZstd }, async () => {

const message = { 'msg': 'This message is going to be zstded.' };
const server = Hapi.server({ compression: { enableZstd: true } });
server.route({ method: 'POST', path: '/', handler: (request) => request.payload });

const compressed = await new Promise((resolve) => Zlib.zstdCompress(JSON.stringify(message), (ignore, result) => resolve(result)));

const request = {
method: 'POST',
url: '/',
headers: {
'content-type': 'application/json',
'content-encoding': 'zstd',
'content-length': compressed.length
},
payload: compressed
};

const res = await server.inject(request);
expect(res.result).to.exist();
expect(res.result).to.equal(message);
});

it('handles custom compression', async () => {

const message = { 'msg': 'This message is going to be gzipped.' };
Expand Down
Loading