Skip to content
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
42 changes: 36 additions & 6 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,35 @@ assigned one or more (array):

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

Default value: `{ minBytes: 1024 }`.
Default value: `{ decompress: true, encodings: { gzip: true, deflate: true, br: false, zstd: false }, minBytes: 1024 }`.

Defines server handling of content encoding requests. If `false`, response content encoding is
disabled and no compression is performed by the server.
disabled, and no compression is performed by the server.

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

Default value: `true`.

Controls whether the server automatically decompresses incoming content encoding requests.
If `false`, no decompression automatically performed by the server.

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

Default value: `{ gzip: true, deflate: true, br: false, zstd: false }`.

Configures the built-in support of compression algorithms aka encodings, represented by the object of kv pairs.

Available values for each kv pair:

- `true` - enables the encoding with default options.
- `false` - disables the encoding.

Note that default encoder and decoder options can be configured at the server default [route configuration](#server.options.routes)

Zstd compression is experimental (see [node Zstd documentation](https://nodejs.org/api/zlib.html#zlibcreatezstdcompressoptions)).

Disabling an encoding allows custom compression algorithm to be applied by
[`server.encoder()`](#server.encoder()) and [`server.decoder()`](#server.decoder()).

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

Expand All @@ -110,6 +135,13 @@ 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 Expand Up @@ -1290,8 +1322,7 @@ are called, where:

### <a name="server.decoder()" /> `server.decoder(encoding, decoder)`

Registers a custom content decoding compressor to extend the built-in support for `'gzip'` and
'`deflate`' where:
Registers a custom content decoding compressor to extend the built-in support where:

- `encoding` - the decoder name string.

Expand Down Expand Up @@ -1487,8 +1518,7 @@ The `dependencies` configuration accepts one of:

### <a name="server.encoder()" /> `server.encoder(encoding, encoder)`

Registers a custom content encoding compressor to extend the built-in support for `'gzip'` and
'`deflate`' where:
Registers a custom content encoding compressor to extend the built-in support where:

- `encoding` - the encoder name string.

Expand Down
89 changes: 75 additions & 14 deletions lib/compression.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,88 @@ const Zlib = require('zlib');
const Accept = require('@hapi/accept');
const Bounce = require('@hapi/bounce');
const Hoek = require('@hapi/hoek');
const Boom = require('@hapi/boom');

const compressorOptions = {
brotliCompress: {
params: {
[Zlib.constants.BROTLI_PARAM_QUALITY]: 4
}
},
zstdCompress: {
params: {
[Zlib.constants.ZSTD_c_compressionLevel]: 6
}
}
};

const internals = {
common: ['gzip, deflate', 'deflate, gzip', 'gzip', 'deflate', 'gzip, deflate, br']
common: [
'gzip, deflate, br, zstd',
Comment thread
bricss marked this conversation as resolved.
Resolved
'gzip, deflate, br',
'zstd',
'br',
'gzip, deflate',
'deflate, gzip',
'gzip',
'deflate'
],
provision: new Map([
['zstd', [
(options = {}) => Zlib.createZstdCompress(Hoek.applyToDefaults(compressorOptions.zstdCompress, options)),
(options) => Zlib.createZstdDecompress(options)
]],
['br', [
(options = {}) => Zlib.createBrotliCompress(Hoek.applyToDefaults(compressorOptions.brotliCompress, options)),
(options) => Zlib.createBrotliDecompress(options)
]],
['deflate', [
(options) => Zlib.createDeflate(options),
(options) => Zlib.createInflate(options)
]],
['gzip', [
(options) => Zlib.createGzip(options),
(options) => Zlib.createGunzip(options)
]]
])
};


exports = module.exports = internals.Compression = class {

decoders = {
gzip: (options) => Zlib.createGunzip(options),
deflate: (options) => Zlib.createInflate(options)
};
decoders = {};

encodings = ['identity', 'gzip', 'deflate'];
encodings = ['identity'];
Comment thread
bricss marked this conversation as resolved.
Resolved

encoders = {
identity: null,
gzip: (options) => Zlib.createGzip(options),
deflate: (options) => Zlib.createDeflate(options)
identity: null
};

#common = null;
#options = null;

constructor() {
constructor(options) {

this._updateCommons();
this.#options = options;
if (!this.#options) {
return this._updateCommons();
}

for (const [encoding, [encoder, decoder]] of internals.provision.entries()) {
const conditions = this.#options?.encodings?.[encoding];
if (conditions) {
this.addEncoder(encoding, encoder);
if (this.#options.decompress !== false) {
this.addDecoder(encoding, decoder);
}
else {
this.addDecoder(encoding, () => {

throw Boom.unsupportedMediaType();
});
}
}
}
}

_updateCommons() {
Expand Down Expand Up @@ -89,13 +144,13 @@ exports = module.exports = internals.Compression = class {
return null;
}

const request = response.request;
if (!request._core.settings.compression ||
length !== null && length < request._core.settings.compression.minBytes) {
if (!this.#options ||
length !== null && length < this.#options.minBytes) {

return null;
}

const request = response.request;
const mime = request._core.mime.type(response.headers['content-type'] || 'application/octet-stream');
if (!mime.compressible) {
return null;
Expand All @@ -116,4 +171,10 @@ exports = module.exports = internals.Compression = class {
Hoek.assert(encoder !== undefined, `Unknown encoding ${encoding}`);
return encoder(request.route.settings.compression[encoding]);
}

setPriority(priority) {

this.encodings = [...new Set([...priority, ...this.encodings])];
this._updateCommons();
}
};
10 changes: 9 additions & 1 deletion lib/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,15 @@ internals.server = Validate.object({
autoListen: Validate.boolean(),
cache: Validate.allow(null), // Validated elsewhere
compression: Validate.object({
minBytes: Validate.number().min(1).integer().default(1024)
decompress: Validate.boolean().default(true),
encodings: Validate.object({
gzip: Validate.boolean().default(true),
deflate: Validate.boolean().default(true),
br: Validate.boolean().default(false),
zstd: Validate.boolean().default(false)
}).default(),
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
7 changes: 6 additions & 1 deletion lib/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ exports = module.exports = internals.Core = class {
app = {};
auth = new Auth(this);
caches = new Map(); // Cache clients
compression = new Compression();
compression = null;
controlled = null; // Other servers linked to the phases of this server
dependencies = []; // Plugin dependencies
events = new Podium.Podium(internals.events);
Expand Down Expand Up @@ -119,6 +119,7 @@ exports = module.exports = internals.Core = class {
this.settings = settings;
this.type = type;

this.compression = new Compression(this.settings.compression);
this.heavy = new Heavy(this.settings.load);
this.mime = new Mimos(this.settings.mime);
this.router = new Call.Router(this.settings.router);
Expand All @@ -127,6 +128,10 @@ exports = module.exports = internals.Core = class {
this._debug();
this._initializeCache();

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;
}
8 changes: 8 additions & 0 deletions lib/types/server/options.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,15 @@ import { CacheProvider, ServerOptionsCache } from './cache';
import { SameSitePolicy, ServerStateCookieOptions } from './state';

export interface ServerOptionsCompression {
decompress?: boolean;
encodings?: {
gzip?: boolean;
deflate?: boolean;
br?: boolean;
zstd?: boolean;
};
minBytes: number;
priority?: string[];
}

/**
Expand Down
4 changes: 2 additions & 2 deletions lib/types/server/server.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ export class Server<A = ServerApplicationState> {
cache: ServerCache;

/**
* Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' where:
* Registers a custom content decoding compressor to extend the built-in support where:
* @param encoding - the decoder name string.
* @param decoder - a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the
* return value is an object compatible with the output of node's zlib.createGunzip().
Expand Down Expand Up @@ -392,7 +392,7 @@ export class Server<A = ServerApplicationState> {
dependency(dependencies: Dependencies, after?: ((server: Server) => Promise<void>) | undefined): void;

/**
* Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where:
* Registers a custom content encoding compressor to extend the built-in support where:
* @param encoding - the encoder name string.
* @param encoder - a function using the signature function(options) where options are the encoding specific options configured in the route compression option, and the return value is an object
* compatible with the output of node's zlib.createGzip().
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
"@hapi/lab": "^25.3.2",
"@hapi/vision": "^7.0.3",
"@hapi/wreck": "^18.1.3",
"@types/node": "^18.19.130",
"@types/node": "^22.20.5",
"handlebars": "^4.7.10",
"joi": "^17.13.8",
"legacy-readable-stream": "npm:readable-stream@^1.0.34",
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 @@ -38,3 +39,5 @@ exports.http2ClientSendsHost = parseInt(process.versions.node, 10) >= 16;
// node.js < 20 http/1.1 parser accepts ':authority' as a header with an empty name

exports.http1RejectsPseudoHeaders = parseInt(process.versions.node, 10) >= 20;

exports.hasZstd = !!Zlib.constants.ZSTD_CLEVEL_DEFAULT;
Loading