@naturalcycles/backend-lib 9.78.0 → 9.79.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,6 +10,18 @@ export interface CompressionOptions {
10
10
  * @default 1024
11
11
  */
12
12
  threshold?: number | string;
13
+ /**
14
+ * Bodies sent in one `res.end(chunk)` call (which is what `res.json` and `res.send` do) up to this
15
+ * size are compressed synchronously on the event loop, instead of through a zlib stream.
16
+ * For typical JSON responses the per-response stream setup and threadpool round-trip cost more
17
+ * than the compression itself, and the sync path also keeps an exact `Content-Length`
18
+ * (streamed responses are chunked).
19
+ * Bodies above this size, and bodies written in several `res.write` calls, are streamed.
20
+ * Set to `0` to always stream.
21
+ *
22
+ * @default 128kb
23
+ */
24
+ syncMaxBytes?: number | string;
13
25
  /**
14
26
  * Encoding to use when Accept-Encoding header is not present.
15
27
  * @default 'identity'
@@ -39,7 +51,8 @@ export interface CompressionOptions {
39
51
  /**
40
52
  * Compression middleware with support for gzip, deflate, brotli, and zstd.
41
53
  *
42
- * This is a fork of the `compression` npm package with added zstd support.
54
+ * This is a fork of the `compression` npm package with added zstd support,
55
+ * and a synchronous fast path for single-chunk bodies (see `syncMaxBytes`).
43
56
  *
44
57
  * Encoding preference order: zstd > br > gzip > deflate
45
58
  */
@@ -22,7 +22,8 @@ const cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i;
22
22
  /**
23
23
  * Compression middleware with support for gzip, deflate, brotli, and zstd.
24
24
  *
25
- * This is a fork of the `compression` npm package with added zstd support.
25
+ * This is a fork of the `compression` npm package with added zstd support,
26
+ * and a synchronous fast path for single-chunk bodies (see `syncMaxBytes`).
26
27
  *
27
28
  * Encoding preference order: zstd > br > gzip > deflate
28
29
  */
@@ -37,10 +38,14 @@ export function compressionMiddleware(options) {
37
38
  },
38
39
  };
39
40
  // Zstd options
41
+ // Level 1 instead of zstd's own default of 3: for typical JSON responses the CPU cost and
42
+ // compression ratio are the same (measured 2026-10 on 22 KB and 115 KB payloads), but a level 3
43
+ // stream holds ~850 KB of native memory per in-flight response vs ~150 KB at level 1.
44
+ // That per-response allocation churn is what MALLOC_ARENA_MAX=2 works around on Cloud Run.
40
45
  const optsZstd = {
41
46
  ...opts.zstd,
42
47
  params: {
43
- [zlib.constants.ZSTD_c_compressionLevel]: 3,
48
+ [zlib.constants.ZSTD_c_compressionLevel]: 1,
44
49
  ...opts.zstd?.params,
45
50
  },
46
51
  };
@@ -56,11 +61,17 @@ export function compressionMiddleware(options) {
56
61
  zlibOpts.windowBits = opts.windowBits;
57
62
  if (opts.chunkSize !== undefined)
58
63
  zlibOpts.chunkSize = opts.chunkSize;
64
+ const codecOpts = { zstd: optsZstd, brotli: optsBrotli, zlib: zlibOpts };
59
65
  const filter = opts.filter || shouldCompress;
60
66
  const threshold = parseBytes(opts.threshold) ?? 1024;
67
+ const syncMaxBytes = parseBytes(opts.syncMaxBytes) ?? 128 * 1024;
61
68
  const enforceEncoding = opts.enforceEncoding || 'identity';
62
69
  return function compression(req, res, next) {
63
70
  let ended = false;
71
+ // Set by the first `res.write`: the body comes in several chunks, so only the stream path applies
72
+ let wrote = false;
73
+ // Set once the compress-or-not decision has been made for this response (by either path)
74
+ let decided = false;
64
75
  let length;
65
76
  let listeners = [];
66
77
  let stream;
@@ -78,6 +89,7 @@ export function compressionMiddleware(options) {
78
89
  if (ended) {
79
90
  return false;
80
91
  }
92
+ wrote = true;
81
93
  if (!headersSent(res)) {
82
94
  res.writeHead(res.statusCode);
83
95
  }
@@ -96,6 +108,26 @@ export function compressionMiddleware(options) {
96
108
  if (!res.getHeader('Content-Length')) {
97
109
  length = chunkLength(chunk, encodingOrCallback);
98
110
  }
111
+ // Single-chunk body (no prior `res.write`): the whole body is right here, so compress it
112
+ // synchronously instead of setting up a zlib stream for one chunk.
113
+ if (chunk && !wrote && !decided) {
114
+ const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback;
115
+ const body = toBuffer(chunk, encoding);
116
+ if (body.length <= syncMaxBytes) {
117
+ const method = decide(body.length);
118
+ if (method) {
119
+ const compressed = compressSync(method, body, codecOpts);
120
+ res.setHeader('Content-Encoding', method);
121
+ res.setHeader('Content-Length', compressed.length);
122
+ ended = true;
123
+ const cb = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback;
124
+ // encoding is irrelevant for a Buffer chunk; it is passed to satisfy the `end` overload
125
+ return _end.call(res, compressed, 'utf8', cb);
126
+ }
127
+ // Not compressing: falls through to the plain `end`.
128
+ // The `onHeaders` listener below sees `decided` and does nothing.
129
+ }
130
+ }
99
131
  res.writeHead(res.statusCode);
100
132
  }
101
133
  if (!stream) {
@@ -127,46 +159,36 @@ export function compressionMiddleware(options) {
127
159
  addListeners(res, _on, listeners);
128
160
  listeners = null;
129
161
  }
130
- // Release the compression stream when the response closes, freeing native
131
- // zlib memory even if the client disconnected before the response finished.
132
- // Registered before onHeaders so a close that happens before the stream
133
- // exists is not missed (the `closed` flag below handles a stream created
134
- // afterwards). Fixes CVE-2026-87776 / GHSA-vc2v-76pw-4v95.
135
- // We use `stream.destroy()` (not the `destroy` npm package upstream added)
136
- // because our Node target frees the zlib handle on destroy().
137
- _on.call(res, 'close', function onResponseClose() {
138
- closed = true;
139
- stream?.destroy();
140
- });
141
- onHeaders(res, function onResponseHeaders() {
162
+ /**
163
+ * The compress-or-not decision, shared by the sync path (`res.end` holding the whole body)
164
+ * and the stream path (`onHeaders`).
165
+ * Returns the encoding to use, or undefined when the response is to be sent as-is.
166
+ */
167
+ function decide(bodyLength) {
168
+ decided = true;
142
169
  // determine if request is filtered
143
170
  if (!filter(req, res)) {
144
- nocompress('filtered');
145
- return;
171
+ return nocompress('filtered');
146
172
  }
147
173
  // determine if the entity should be transformed
148
174
  if (!shouldTransform(req, res)) {
149
- nocompress('no transform');
150
- return;
175
+ return nocompress('no transform');
151
176
  }
152
177
  // vary
153
178
  vary(res, 'Accept-Encoding');
154
179
  // content-length below threshold
155
180
  if (Number(res.getHeader('Content-Length')) < threshold ||
156
- (length !== undefined && length < threshold)) {
157
- nocompress('size below threshold');
158
- return;
181
+ (bodyLength !== undefined && bodyLength < threshold)) {
182
+ return nocompress('size below threshold');
159
183
  }
160
184
  const encoding = res.getHeader('Content-Encoding') || 'identity';
161
185
  // already encoded
162
186
  if (encoding !== 'identity') {
163
- nocompress('already encoded');
164
- return;
187
+ return nocompress('already encoded');
165
188
  }
166
189
  // head
167
190
  if (req.method === 'HEAD') {
168
- nocompress('HEAD request');
169
- return;
191
+ return nocompress('HEAD request');
170
192
  }
171
193
  // compression method
172
194
  // Get all client-accepted encodings, then pick the first one from our preferred order
@@ -180,9 +202,28 @@ export function compressionMiddleware(options) {
180
202
  }
181
203
  // negotiation failed
182
204
  if (!method || method === 'identity') {
183
- nocompress('not acceptable');
184
- return;
205
+ return nocompress('not acceptable');
185
206
  }
207
+ return method;
208
+ }
209
+ // Release the compression stream when the response closes, freeing native
210
+ // zlib memory even if the client disconnected before the response finished.
211
+ // Registered before onHeaders so a close that happens before the stream
212
+ // exists is not missed (the `closed` flag below handles a stream created
213
+ // afterwards). Fixes CVE-2026-87776 / GHSA-vc2v-76pw-4v95.
214
+ // We use `stream.destroy()` (not the `destroy` npm package upstream added)
215
+ // because our Node target frees the zlib handle on destroy().
216
+ _on.call(res, 'close', function onResponseClose() {
217
+ closed = true;
218
+ stream?.destroy();
219
+ });
220
+ onHeaders(res, function onResponseHeaders() {
221
+ // The sync path has already handled this response (compressed it, or declined to)
222
+ if (decided)
223
+ return;
224
+ const method = decide(length);
225
+ if (!method)
226
+ return;
186
227
  // compression stream
187
228
  if (method === 'zstd') {
188
229
  stream = zlib.createZstdCompress(optsZstd);
@@ -236,6 +277,19 @@ export function shouldCompress(_req, res) {
236
277
  }
237
278
  return true;
238
279
  }
280
+ /**
281
+ * Compresses a whole body in one call, on the event loop.
282
+ * Same codec options as the streams, so the output is identical to the streamed one.
283
+ */
284
+ function compressSync(method, body, opts) {
285
+ if (method === 'zstd')
286
+ return zlib.zstdCompressSync(body, opts.zstd);
287
+ if (method === 'br')
288
+ return zlib.brotliCompressSync(body, opts.brotli);
289
+ if (method === 'gzip')
290
+ return zlib.gzipSync(body, opts.zlib);
291
+ return zlib.deflateSync(body, opts.zlib);
292
+ }
239
293
  function addListeners(stream, on, listeners) {
240
294
  for (const [type, listener] of listeners) {
241
295
  on.call(stream, type, listener);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@naturalcycles/backend-lib",
3
3
  "type": "module",
4
- "version": "9.78.0",
4
+ "version": "9.79.0",
5
5
  "dependencies": {
6
6
  "@naturalcycles/db-lib": "^10",
7
7
  "@naturalcycles/js-lib": "^15",
@@ -31,6 +31,19 @@ export interface CompressionOptions {
31
31
  */
32
32
  threshold?: number | string
33
33
 
34
+ /**
35
+ * Bodies sent in one `res.end(chunk)` call (which is what `res.json` and `res.send` do) up to this
36
+ * size are compressed synchronously on the event loop, instead of through a zlib stream.
37
+ * For typical JSON responses the per-response stream setup and threadpool round-trip cost more
38
+ * than the compression itself, and the sync path also keeps an exact `Content-Length`
39
+ * (streamed responses are chunked).
40
+ * Bodies above this size, and bodies written in several `res.write` calls, are streamed.
41
+ * Set to `0` to always stream.
42
+ *
43
+ * @default 128kb
44
+ */
45
+ syncMaxBytes?: number | string
46
+
34
47
  /**
35
48
  * Encoding to use when Accept-Encoding header is not present.
36
49
  * @default 'identity'
@@ -71,7 +84,8 @@ const cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i
71
84
  /**
72
85
  * Compression middleware with support for gzip, deflate, brotli, and zstd.
73
86
  *
74
- * This is a fork of the `compression` npm package with added zstd support.
87
+ * This is a fork of the `compression` npm package with added zstd support,
88
+ * and a synchronous fast path for single-chunk bodies (see `syncMaxBytes`).
75
89
  *
76
90
  * Encoding preference order: zstd > br > gzip > deflate
77
91
  */
@@ -88,10 +102,14 @@ export function compressionMiddleware(options?: CompressionOptions): BackendRequ
88
102
  }
89
103
 
90
104
  // Zstd options
105
+ // Level 1 instead of zstd's own default of 3: for typical JSON responses the CPU cost and
106
+ // compression ratio are the same (measured 2026-10 on 22 KB and 115 KB payloads), but a level 3
107
+ // stream holds ~850 KB of native memory per in-flight response vs ~150 KB at level 1.
108
+ // That per-response allocation churn is what MALLOC_ARENA_MAX=2 works around on Cloud Run.
91
109
  const optsZstd: zlib.ZstdOptions = {
92
110
  ...opts.zstd,
93
111
  params: {
94
- [zlib.constants.ZSTD_c_compressionLevel]: 3,
112
+ [zlib.constants.ZSTD_c_compressionLevel]: 1,
95
113
  ...opts.zstd?.params,
96
114
  },
97
115
  }
@@ -104,12 +122,19 @@ export function compressionMiddleware(options?: CompressionOptions): BackendRequ
104
122
  if (opts.windowBits !== undefined) zlibOpts.windowBits = opts.windowBits
105
123
  if (opts.chunkSize !== undefined) zlibOpts.chunkSize = opts.chunkSize
106
124
 
125
+ const codecOpts: CodecOptions = { zstd: optsZstd, brotli: optsBrotli, zlib: zlibOpts }
126
+
107
127
  const filter = opts.filter || shouldCompress
108
128
  const threshold = parseBytes(opts.threshold) ?? 1024
129
+ const syncMaxBytes = parseBytes(opts.syncMaxBytes) ?? 128 * 1024
109
130
  const enforceEncoding = opts.enforceEncoding || 'identity'
110
131
 
111
132
  return function compression(req, res, next) {
112
133
  let ended = false
134
+ // Set by the first `res.write`: the body comes in several chunks, so only the stream path applies
135
+ let wrote = false
136
+ // Set once the compress-or-not decision has been made for this response (by either path)
137
+ let decided = false
113
138
  let length: number | undefined
114
139
  let listeners: [string, (...args: any[]) => void][] | null = []
115
140
  let stream: zlib.Gzip | zlib.Deflate | zlib.BrotliCompress | zlib.ZstdCompress | undefined
@@ -136,6 +161,8 @@ export function compressionMiddleware(options?: CompressionOptions): BackendRequ
136
161
  return false
137
162
  }
138
163
 
164
+ wrote = true
165
+
139
166
  if (!headersSent(res)) {
140
167
  res.writeHead(res.statusCode)
141
168
  }
@@ -161,6 +188,30 @@ export function compressionMiddleware(options?: CompressionOptions): BackendRequ
161
188
  if (!res.getHeader('Content-Length')) {
162
189
  length = chunkLength(chunk, encodingOrCallback as BufferEncoding)
163
190
  }
191
+
192
+ // Single-chunk body (no prior `res.write`): the whole body is right here, so compress it
193
+ // synchronously instead of setting up a zlib stream for one chunk.
194
+ if (chunk && !wrote && !decided) {
195
+ const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback
196
+ const body = toBuffer(chunk, encoding)
197
+
198
+ if (body.length <= syncMaxBytes) {
199
+ const method = decide(body.length)
200
+
201
+ if (method) {
202
+ const compressed = compressSync(method, body, codecOpts)
203
+ res.setHeader('Content-Encoding', method)
204
+ res.setHeader('Content-Length', compressed.length)
205
+ ended = true
206
+ const cb = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback
207
+ // encoding is irrelevant for a Buffer chunk; it is passed to satisfy the `end` overload
208
+ return _end.call(res, compressed, 'utf8', cb)
209
+ }
210
+ // Not compressing: falls through to the plain `end`.
211
+ // The `onHeaders` listener below sees `decided` and does nothing.
212
+ }
213
+ }
214
+
164
215
  res.writeHead(res.statusCode)
165
216
  }
166
217
 
@@ -195,34 +246,27 @@ export function compressionMiddleware(options?: CompressionOptions): BackendRequ
195
246
  return res
196
247
  }
197
248
 
198
- function nocompress(_msg: string): void {
249
+ function nocompress(_msg: string): undefined {
199
250
  addListeners(res, _on, listeners!)
200
251
  listeners = null
201
252
  }
202
253
 
203
- // Release the compression stream when the response closes, freeing native
204
- // zlib memory even if the client disconnected before the response finished.
205
- // Registered before onHeaders so a close that happens before the stream
206
- // exists is not missed (the `closed` flag below handles a stream created
207
- // afterwards). Fixes CVE-2026-87776 / GHSA-vc2v-76pw-4v95.
208
- // We use `stream.destroy()` (not the `destroy` npm package upstream added)
209
- // because our Node target frees the zlib handle on destroy().
210
- _on.call(res, 'close', function onResponseClose() {
211
- closed = true
212
- stream?.destroy()
213
- })
254
+ /**
255
+ * The compress-or-not decision, shared by the sync path (`res.end` holding the whole body)
256
+ * and the stream path (`onHeaders`).
257
+ * Returns the encoding to use, or undefined when the response is to be sent as-is.
258
+ */
259
+ function decide(bodyLength: number | undefined): string | undefined {
260
+ decided = true
214
261
 
215
- onHeaders(res, function onResponseHeaders() {
216
262
  // determine if request is filtered
217
263
  if (!filter(req, res)) {
218
- nocompress('filtered')
219
- return
264
+ return nocompress('filtered')
220
265
  }
221
266
 
222
267
  // determine if the entity should be transformed
223
268
  if (!shouldTransform(req, res)) {
224
- nocompress('no transform')
225
- return
269
+ return nocompress('no transform')
226
270
  }
227
271
 
228
272
  // vary
@@ -231,24 +275,21 @@ export function compressionMiddleware(options?: CompressionOptions): BackendRequ
231
275
  // content-length below threshold
232
276
  if (
233
277
  Number(res.getHeader('Content-Length')) < threshold ||
234
- (length !== undefined && length < threshold)
278
+ (bodyLength !== undefined && bodyLength < threshold)
235
279
  ) {
236
- nocompress('size below threshold')
237
- return
280
+ return nocompress('size below threshold')
238
281
  }
239
282
 
240
283
  const encoding = (res.getHeader('Content-Encoding') as string) || 'identity'
241
284
 
242
285
  // already encoded
243
286
  if (encoding !== 'identity') {
244
- nocompress('already encoded')
245
- return
287
+ return nocompress('already encoded')
246
288
  }
247
289
 
248
290
  // head
249
291
  if (req.method === 'HEAD') {
250
- nocompress('HEAD request')
251
- return
292
+ return nocompress('HEAD request')
252
293
  }
253
294
 
254
295
  // compression method
@@ -266,10 +307,31 @@ export function compressionMiddleware(options?: CompressionOptions): BackendRequ
266
307
 
267
308
  // negotiation failed
268
309
  if (!method || method === 'identity') {
269
- nocompress('not acceptable')
270
- return
310
+ return nocompress('not acceptable')
271
311
  }
272
312
 
313
+ return method
314
+ }
315
+
316
+ // Release the compression stream when the response closes, freeing native
317
+ // zlib memory even if the client disconnected before the response finished.
318
+ // Registered before onHeaders so a close that happens before the stream
319
+ // exists is not missed (the `closed` flag below handles a stream created
320
+ // afterwards). Fixes CVE-2026-87776 / GHSA-vc2v-76pw-4v95.
321
+ // We use `stream.destroy()` (not the `destroy` npm package upstream added)
322
+ // because our Node target frees the zlib handle on destroy().
323
+ _on.call(res, 'close', function onResponseClose() {
324
+ closed = true
325
+ stream?.destroy()
326
+ })
327
+
328
+ onHeaders(res, function onResponseHeaders() {
329
+ // The sync path has already handled this response (compressed it, or declined to)
330
+ if (decided) return
331
+
332
+ const method = decide(length)
333
+ if (!method) return
334
+
273
335
  // compression stream
274
336
  if (method === 'zstd') {
275
337
  stream = zlib.createZstdCompress(optsZstd)
@@ -331,6 +393,23 @@ export function shouldCompress(_req: any, res: any): boolean {
331
393
  return true
332
394
  }
333
395
 
396
+ interface CodecOptions {
397
+ zstd: zlib.ZstdOptions
398
+ brotli: zlib.BrotliOptions
399
+ zlib: zlib.ZlibOptions
400
+ }
401
+
402
+ /**
403
+ * Compresses a whole body in one call, on the event loop.
404
+ * Same codec options as the streams, so the output is identical to the streamed one.
405
+ */
406
+ function compressSync(method: string, body: Buffer, opts: CodecOptions): Buffer {
407
+ if (method === 'zstd') return zlib.zstdCompressSync(body, opts.zstd)
408
+ if (method === 'br') return zlib.brotliCompressSync(body, opts.brotli)
409
+ if (method === 'gzip') return zlib.gzipSync(body, opts.zlib)
410
+ return zlib.deflateSync(body, opts.zlib)
411
+ }
412
+
334
413
  function addListeners(
335
414
  stream: any,
336
415
  on: (type: string, listener: (...args: any[]) => void) => void,