@lenne.tech/nest-server 12.6.8 → 12.6.10

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.
Files changed (40) hide show
  1. package/.claude/rules/configurable-features.md +1 -0
  2. package/.claude/rules/testing.md +4 -4
  3. package/FRAMEWORK-API.md +7 -1
  4. package/dist/core/common/helpers/idle-stream.helper.d.ts +14 -0
  5. package/dist/core/common/helpers/idle-stream.helper.js +94 -0
  6. package/dist/core/common/helpers/idle-stream.helper.js.map +1 -0
  7. package/dist/core/common/interfaces/server-options.interface.d.ts +6 -0
  8. package/dist/core/common/services/core-s3.service.d.ts +27 -1
  9. package/dist/core/common/services/core-s3.service.js +89 -3
  10. package/dist/core/common/services/core-s3.service.js.map +1 -1
  11. package/dist/core/modules/file/core-file.controller.d.ts +16 -0
  12. package/dist/core/modules/file/core-file.controller.js +215 -8
  13. package/dist/core/modules/file/core-file.controller.js.map +1 -1
  14. package/dist/core/modules/file/core-file.service.d.ts +5 -0
  15. package/dist/core/modules/file/core-file.service.js +17 -7
  16. package/dist/core/modules/file/core-file.service.js.map +1 -1
  17. package/dist/core/modules/file/interfaces/file-service-options.interface.d.ts +2 -0
  18. package/dist/core/modules/file/s3-file.helper.d.ts +4 -1
  19. package/dist/core/modules/file/s3-file.helper.js +2 -2
  20. package/dist/core/modules/file/s3-file.helper.js.map +1 -1
  21. package/dist/index.d.ts +1 -0
  22. package/dist/index.js +1 -0
  23. package/dist/index.js.map +1 -1
  24. package/dist/main.js +1 -3
  25. package/dist/main.js.map +1 -1
  26. package/docs/REQUEST-LIFECYCLE.md +2 -2
  27. package/migration-guides/12.6.8-to-12.6.9.md +44 -0
  28. package/migration-guides/12.6.9-to-12.6.10.md +149 -0
  29. package/package.json +3 -3
  30. package/src/core/common/helpers/idle-stream.helper.ts +192 -0
  31. package/src/core/common/interfaces/server-options.interface.ts +78 -0
  32. package/src/core/common/services/core-s3.service.ts +186 -3
  33. package/src/core/modules/file/INTEGRATION-CHECKLIST.md +15 -14
  34. package/src/core/modules/file/README.md +48 -0
  35. package/src/core/modules/file/core-file.controller.ts +356 -10
  36. package/src/core/modules/file/core-file.service.ts +46 -7
  37. package/src/core/modules/file/interfaces/file-service-options.interface.ts +22 -0
  38. package/src/core/modules/file/s3-file.helper.ts +6 -2
  39. package/src/index.ts +1 -0
  40. package/src/main.ts +3 -3
@@ -1,4 +1,13 @@
1
- import { BadRequestException, Controller, Get, Logger, NotFoundException, Param, Res } from '@nestjs/common';
1
+ import {
2
+ BadRequestException,
3
+ Controller,
4
+ Get,
5
+ Logger,
6
+ NotFoundException,
7
+ Param,
8
+ Res,
9
+ ServiceUnavailableException,
10
+ } from '@nestjs/common';
2
11
  import type { Response } from 'express';
3
12
  import type { Readable } from 'stream';
4
13
 
@@ -6,6 +15,8 @@ import { CurrentUser } from '../../common/decorators/current-user.decorator.js';
6
15
  import { Roles } from '../../common/decorators/roles.decorator.js';
7
16
  import { RoleEnum } from '../../common/enums/role.enum.js';
8
17
  import { buildContentDisposition } from '../../common/helpers/content-disposition.helper.js';
18
+ import { StreamIdleTimeoutError } from '../../common/helpers/idle-stream.helper.js';
19
+ import { ConfigService } from '../../common/services/config.service.js';
9
20
  import { ErrorCode } from '../error-code/error-codes.js';
10
21
  import { SkipTenantCheck } from '../tenant/core-tenant.decorators.js';
11
22
  import { CoreFileService } from './core-file.service.js';
@@ -13,6 +24,110 @@ import type { FileServiceOptions } from './interfaces/file-service-options.inter
13
24
 
14
25
  const fileStreamLogger = new Logger('CoreFileController');
15
26
 
27
+ /**
28
+ * Downloads closed by the idle guard since the last report, and when the last report was written.
29
+ *
30
+ * Reported as ONE warning per minute instead of a line per download: a client that stops reading is not a server
31
+ * error, and under an abort storm a line per event (measured: 20 per second, each with a stack) turns the log into an
32
+ * alert storm. `withOpenConnection` counts the closes whose client connection was still open — clients that stopped
33
+ * reading without closing; the rest were waiting on a store that delivered nothing.
34
+ */
35
+ const idleCloses = { afterResponseClose: 0, lastReportAt: 0, sample: '', total: 0, withOpenConnection: 0 };
36
+ const IDLE_CLOSE_REPORT_INTERVAL_MS = 60_000;
37
+
38
+ /** An idle close of the download guard — by class or by code, so a second copy of the helper module counts too. */
39
+ function isStreamIdleTimeout(error: unknown): error is StreamIdleTimeoutError {
40
+ return error instanceof StreamIdleTimeoutError || (error as { code?: string })?.code === 'LT_STREAM_IDLE_TIMEOUT';
41
+ }
42
+
43
+ function reportIdleClose(
44
+ res: Response,
45
+ error: StreamIdleTimeoutError,
46
+ state: { attachedAt: number; clientGoneSignal: string; responseClosed: boolean },
47
+ ): void {
48
+ idleCloses.total++;
49
+ const socket = (res as Response & { socket?: { destroyed?: boolean } | null }).socket;
50
+ if (socket && !socket.destroyed) {
51
+ idleCloses.withOpenConnection++;
52
+ }
53
+ // A close the response had already reported: the stream should have been destroyed then, not by the idle guard
54
+ if (state.responseClosed) {
55
+ idleCloses.afterResponseClose++;
56
+ }
57
+ if (!idleCloses.sample) {
58
+ const r = res as Response & { closed?: boolean; writableEnded?: boolean };
59
+ const req = (res as Response & { req?: { destroyed?: boolean } }).req;
60
+ idleCloses.sample =
61
+ `example: ${Date.now() - state.attachedAt} ms after delivery started, response closed event ${state.responseClosed}, ` +
62
+ `destroyed ${r.destroyed}, closed ${r.closed}, headersSent ${r.headersSent}, writableEnded ${r.writableEnded}, ` +
63
+ `socket ${socket ? (socket.destroyed ? 'destroyed' : 'open') : 'none'}, request destroyed ${req?.destroyed}, ` +
64
+ `client-gone signal ${state.clientGoneSignal || 'none'}`;
65
+ }
66
+ const now = Date.now();
67
+ if (now - idleCloses.lastReportAt < IDLE_CLOSE_REPORT_INTERVAL_MS) {
68
+ return;
69
+ }
70
+ fileStreamLogger.warn(
71
+ `${idleCloses.total} file download(s) closed after no read progress for ${error.idleMs} ms since the last ` +
72
+ `report (${idleCloses.withOpenConnection} with the client connection still open: clients that stopped reading ` +
73
+ `without closing; ${idleCloses.afterResponseClose} after the response had already closed; ${idleCloses.sample}). ` +
74
+ 'This releases the store socket, file handle or cursor; many of them under load hold S3 sockets for that long — ' +
75
+ 'see s3.downloadIdleTimeoutMs.',
76
+ );
77
+ idleCloses.lastReportAt = now;
78
+ idleCloses.total = 0;
79
+ idleCloses.withOpenConnection = 0;
80
+ idleCloses.afterResponseClose = 0;
81
+ idleCloses.sample = '';
82
+ }
83
+
84
+ /**
85
+ * Release the source on every signal that the client has gone, not only on the response's `close`.
86
+ *
87
+ * Measured under an abort storm (k6, 40 aborts/s against S3 through the full controller route): about one in six
88
+ * aborted downloads never got a `close` on the response although the client's connection was gone on the server side —
89
+ * headers sent, body mid-flight, `res.destroyed` false. Those held their S3 socket until the idle guard ran out. The
90
+ * request and the socket carry the same news through other events: the request closes before its end (it was
91
+ * aborted), and the socket ends or closes. A request whose body was read to the end — a POST export, or any request a
92
+ * body-parsing middleware read — is closed by Node itself on a healthy connection, so its `close` says nothing about
93
+ * the client; the socket listeners still report that client leaving later.
94
+ * Listeners on a keep-alive socket are removed once this response is done, so they never reach the next request.
95
+ */
96
+ function watchClientGone(stream: Readable, res: Response, state: { clientGoneSignal: string }): void {
97
+ const req = res.req;
98
+ const socket = res.socket;
99
+ const release = (signal: string) => () => {
100
+ if (res.writableFinished || (signal === 'request close' && req?.readableEnded)) {
101
+ return;
102
+ }
103
+ state.clientGoneSignal ||= signal;
104
+ if (!stream.destroyed) {
105
+ stream.destroy();
106
+ }
107
+ };
108
+ const onRequestClose = release('request close');
109
+ const onSocketEnd = release('socket end');
110
+ const onSocketClose = release('socket close');
111
+ if (typeof req?.once === 'function') {
112
+ req.once('close', onRequestClose);
113
+ }
114
+ socket?.once('end', onSocketEnd);
115
+ socket?.once('close', onSocketClose);
116
+ const cleanUp = () => {
117
+ if (typeof req?.removeListener === 'function') {
118
+ req.removeListener('close', onRequestClose);
119
+ }
120
+ socket?.removeListener('end', onSocketEnd);
121
+ socket?.removeListener('close', onSocketClose);
122
+ };
123
+ res.once('finish', cleanUp);
124
+ res.once('close', cleanUp);
125
+ stream.once('close', cleanUp);
126
+ }
127
+
128
+ /** Marker of {@link CoreFileController.openDownloadStream}: the client has gone, nothing is to be delivered. */
129
+ export const RESPONSE_GONE = Symbol('lt.responseGone');
130
+
16
131
  /**
17
132
  * Headers that describe the FILE and must not survive onto an error response.
18
133
  *
@@ -26,7 +141,7 @@ const fileStreamLogger = new Logger('CoreFileController');
26
141
  * ofetch/`$fetch` client picks its parser from that header and hands the caller a
27
142
  * Blob instead of the error message.
28
143
  */
29
- const FILE_DELIVERY_HEADERS = ['Cache-Control', 'Content-Disposition', 'Content-Type', 'ETag'];
144
+ const FILE_DELIVERY_HEADERS = ['Cache-Control', 'Content-Disposition', 'Content-Length', 'Content-Type', 'ETag'];
30
145
 
31
146
  /**
32
147
  * Re-exported from the leaf it now lives in, so no import path broke.
@@ -39,7 +154,16 @@ const FILE_DELIVERY_HEADERS = ['Cache-Control', 'Content-Disposition', 'Content-
39
154
  export { buildContentDisposition };
40
155
 
41
156
  /**
42
- * Pipe a GridFS download to the response without letting a read error kill the socket.
157
+ * Deliver a download stream to the response — THE way to answer a download route, for every store
158
+ * (S3, filesystem, GridFS), in the framework's controller and in a project's own routes alike.
159
+ *
160
+ * WHY NOT `stream.pipe(res)`: when the client aborts, `pipe()` only unpipes. The source stays open and
161
+ * paused, and it holds what it was given — for S3 a socket of the client's pool. Enough aborted downloads
162
+ * and the pool is full: every further S3 request waits forever while the health check stays green (a
163
+ * production outage with exactly this cause preceded 12.6.10). This function destroys the source as soon as
164
+ * the response closes, and answers a store error before the first byte with a 404 instead of a dropped
165
+ * connection. (Since 12.6.10 the streams of `CoreFileService` and `CoreS3Service` also release themselves
166
+ * after an idle time — a second layer, not a reason to skip this one.)
43
167
  *
44
168
  * A GridFS record and its chunks are two separate writes, so a file document can
45
169
  * outlive its bytes — an interrupted upload, a restored backup, a manual cleanup.
@@ -62,18 +186,47 @@ export { buildContentDisposition };
62
186
  * GridFS read stream and its server-side cursor open on every aborted download.
63
187
  */
64
188
  export function pipeFileToResponse(stream: Readable, res: Response): Response {
189
+ // A client that left BEFORE this call (it waited for a free socket of the store, then gave up): its response
190
+ // has already closed, and a `close` listener registered now never fires. Without this check the source was
191
+ // never read nor destroyed and kept its S3 socket — under load an avalanche: a few leaks make downloads slow,
192
+ // waiting clients give up, and every one of them leaks the next socket.
193
+ if (isResponseGone(res)) {
194
+ stream.destroy();
195
+ return res;
196
+ }
197
+ const state = { attachedAt: Date.now(), clientGoneSignal: '', responseClosed: false };
65
198
  res.on('close', () => {
199
+ state.responseClosed = true;
66
200
  if (!stream.destroyed) {
67
201
  stream.destroy();
68
202
  }
69
203
  });
204
+ watchClientGone(stream, res, state);
70
205
 
71
206
  stream.on('error', (err: Error) => {
207
+ // No read progress for the idle time: a client that stopped reading (or a store that delivers nothing) — not
208
+ // a server error, so no ERROR line per download (see `reportIdleClose`). Before the first byte it was the store
209
+ // that stalled: 503, the client may retry; afterwards only closing the connection remains.
210
+ if (isStreamIdleTimeout(err)) {
211
+ reportIdleClose(res, err, state);
212
+ if (res.headersSent) {
213
+ res.destroy();
214
+ return;
215
+ }
216
+ for (const header of FILE_DELIVERY_HEADERS) {
217
+ res.removeHeader(header);
218
+ }
219
+ res.setHeader('Retry-After', '5');
220
+ res
221
+ .status(503)
222
+ .json({ error: 'Service Unavailable', message: 'File storage is busy, please retry', statusCode: 503 });
223
+ return;
224
+ }
72
225
  // The answer to the CLIENT stays deliberately indistinguishable from an
73
226
  // unknown id, but the server must not lose the event: a files document
74
227
  // without its chunks is data corruption, and an error silently converted
75
228
  // into a 404 is one nobody will ever notice.
76
- fileStreamLogger.error(`GridFS download failed: ${err.message}`, err.stack);
229
+ fileStreamLogger.error(`File download failed: ${err.message}`, err.stack);
77
230
 
78
231
  if (res.headersSent) {
79
232
  res.destroy();
@@ -91,6 +244,72 @@ export function pipeFileToResponse(stream: Readable, res: Response): Response {
91
244
  return stream.pipe(res);
92
245
  }
93
246
 
247
+ /**
248
+ * Whether the client of a response has gone: the response was destroyed or closed, or its request or socket was.
249
+ *
250
+ * The response alone is not enough. Measured under an abort storm through the full controller route: a share of the
251
+ * aborted downloads reached delivery with the socket and the request already destroyed while the response still read
252
+ * `destroyed: false, closed: false` and never emitted `close` — those held their S3 socket until the idle guard ran
253
+ * out. A request destroyed BEFORE its end was aborted. One destroyed after its body was read to the end has merely
254
+ * completed: Node destroys it by itself then, on a healthy connection (a POST export, or any request whose body a
255
+ * middleware read), so only `destroyed && !readableEnded` counts, next to a destroyed socket.
256
+ */
257
+ export function isResponseGone(res: Response): boolean {
258
+ const r = res as Response & { closed?: boolean };
259
+ return !!(r.destroyed || r.closed || isRequestAborted(r.req) || r.socket?.destroyed);
260
+ }
261
+
262
+ /** A request destroyed before its end: the client has gone. Node also destroys a request whose body was read to the end. */
263
+ function isRequestAborted(req: undefined | { destroyed?: boolean; readableEnded?: boolean }): boolean {
264
+ return !!req?.destroyed && !req.readableEnded;
265
+ }
266
+
267
+ /**
268
+ * An `AbortSignal` that fires when the client of a download has gone — on the same signals `pipeFileToResponse()`
269
+ * releases a source on: the response closes, the request closes before its end, or the socket ends or closes before
270
+ * the response finished (see {@link isResponseGone} for why the response alone is not enough, and why a request read
271
+ * to the end is not a gone client). Pass it as `abortSignal` to `getFileStream()` / `CoreS3Service.getObject()` from
272
+ * a project's own download route, so an S3 request that still waits for a free socket is dropped instead of taking
273
+ * one later for nobody. The socket listeners are removed once the response is done, so a keep-alive socket carries
274
+ * none of them into its next request.
275
+ */
276
+ export function downloadAbortSignal(res: Response): AbortSignal {
277
+ const controller = new AbortController();
278
+ if (isResponseGone(res)) {
279
+ controller.abort();
280
+ return controller.signal;
281
+ }
282
+ const req = res.req;
283
+ const socket = res.socket;
284
+ const abortWhileUnfinished = () => {
285
+ if (!res.writableFinished) {
286
+ controller.abort();
287
+ }
288
+ };
289
+ // A request read to the end is closed by Node itself on a healthy connection — not the client leaving. A client
290
+ // that leaves after its body was read is reported by the socket (and usually the response)
291
+ const abortOnRequestClose = () => {
292
+ if (!req?.readableEnded) {
293
+ abortWhileUnfinished();
294
+ }
295
+ };
296
+ if (typeof req?.once === 'function') {
297
+ req.once('close', abortOnRequestClose);
298
+ }
299
+ socket?.once('end', abortWhileUnfinished);
300
+ socket?.once('close', abortWhileUnfinished);
301
+ const cleanUp = () => {
302
+ socket?.removeListener('end', abortWhileUnfinished);
303
+ socket?.removeListener('close', abortWhileUnfinished);
304
+ };
305
+ res.once('finish', cleanUp);
306
+ res.once('close', () => {
307
+ cleanUp();
308
+ controller.abort();
309
+ });
310
+ return controller.signal;
311
+ }
312
+
94
313
  /**
95
314
  * File controller
96
315
  *
@@ -181,7 +400,9 @@ export abstract class CoreFileController {
181
400
  throw new BadRequestException(ErrorCode.REQUIRED_FIELD_MISSING);
182
401
  }
183
402
 
184
- const serviceOptions = { currentUser };
403
+ // Registered first: the client may leave while the rights check or the store request is still pending
404
+ const abortSignal = this.downloadAbortSignal(res);
405
+ const serviceOptions = { abortSignal, currentUser };
185
406
  // One lookup for both answers — metadata AND which store holds the bytes.
186
407
  // getFileInfo() followed by getFileStream() had each probe the three stores
187
408
  // from scratch, since neither told the other which one had answered. Same
@@ -191,6 +412,10 @@ export abstract class CoreFileController {
191
412
  if (!file) {
192
413
  throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
193
414
  }
415
+ // Authorized above; a client that already holds these bytes gets 304 without the store being read
416
+ if (this.answerNotModified(res, file)) {
417
+ return res;
418
+ }
194
419
  // S3-stored file with presigned downloads enabled: let the client fetch the
195
420
  // bytes from S3 directly instead of streaming them through the API.
196
421
  //
@@ -217,7 +442,12 @@ export abstract class CoreFileController {
217
442
  res.redirect(302, url);
218
443
  return res;
219
444
  }
220
- const filestream = await this.fileService.getFileStream(id, serviceOptions, resolved.store);
445
+ const filestream = await this.openDownloadStream(res, () =>
446
+ this.fileService.getFileStream(id, serviceOptions, resolved.store),
447
+ );
448
+ if (filestream === RESPONSE_GONE) {
449
+ return res;
450
+ }
221
451
  // `getFileStream` answers null when the service's own rights check refuses.
222
452
  // Same answer as an unknown id: never confirm that the file exists.
223
453
  if (!filestream) {
@@ -248,11 +478,15 @@ export abstract class CoreFileController {
248
478
  throw new BadRequestException(ErrorCode.REQUIRED_FIELD_MISSING);
249
479
  }
250
480
 
251
- const serviceOptions = { currentUser };
481
+ const abortSignal = this.downloadAbortSignal(res);
482
+ const serviceOptions = { abortSignal, currentUser };
252
483
  const file = await this.fileService.getFileInfoByName(filename, serviceOptions);
253
484
  if (!file) {
254
485
  throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
255
486
  }
487
+ if (this.answerNotModified(res, file)) {
488
+ return res;
489
+ }
256
490
  // See getFileById(): authorization on the presigned branch rests on the
257
491
  // getFileInfoByName() call above.
258
492
  const url = await this.resolveDownloadUrl(file.id, serviceOptions);
@@ -261,7 +495,12 @@ export abstract class CoreFileController {
261
495
  res.redirect(302, url);
262
496
  return res;
263
497
  }
264
- const filestream = await this.fileService.getFileStream(file.id, serviceOptions);
498
+ const filestream = await this.openDownloadStream(res, () =>
499
+ this.fileService.getFileStream(file.id, serviceOptions),
500
+ );
501
+ if (filestream === RESPONSE_GONE) {
502
+ return res;
503
+ }
265
504
  if (!filestream) {
266
505
  throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
267
506
  }
@@ -269,6 +508,51 @@ export abstract class CoreFileController {
269
508
  return this.pipeFileToResponse(filestream, res);
270
509
  }
271
510
 
511
+ /**
512
+ * An `AbortSignal` that fires when the response closes — the client has gone. Passed to the store, so an S3
513
+ * request that still waits for a free socket is dropped instead of taking one later for nobody.
514
+ */
515
+ protected downloadAbortSignal(res: Response): AbortSignal {
516
+ return downloadAbortSignal(res);
517
+ }
518
+
519
+ /**
520
+ * Open the download stream unless the client has already gone, and release a stream that arrives after it left.
521
+ *
522
+ * Answers {@link RESPONSE_GONE} when there is nobody left to deliver to: before the store is asked, when the
523
+ * store request was aborted because the response closed, or when the stream arrived after it closed (then the
524
+ * stream is destroyed here, so its socket, file handle or cursor is free at once).
525
+ */
526
+ protected async openDownloadStream(
527
+ res: Response,
528
+ open: () => Promise<Readable>,
529
+ ): Promise<Readable | typeof RESPONSE_GONE> {
530
+ if (isResponseGone(res)) {
531
+ return RESPONSE_GONE;
532
+ }
533
+ let stream: Readable;
534
+ try {
535
+ stream = await open();
536
+ } catch (error) {
537
+ if (isResponseGone(res)) {
538
+ return RESPONSE_GONE;
539
+ }
540
+ // The store did not hand out a connection in time (`s3.connectionTimeoutMs`, which includes the wait for a
541
+ // free socket): the store is busy, not broken, and the client may try again — 503, not 500
542
+ if ((error as { name?: string })?.name === 'TimeoutError') {
543
+ fileStreamLogger.warn(`File store busy, download answered 503: ${(error as Error).message}`);
544
+ res.header('Retry-After', '5');
545
+ throw new ServiceUnavailableException('File storage is busy, please retry');
546
+ }
547
+ throw error;
548
+ }
549
+ if (stream && isResponseGone(res)) {
550
+ stream.destroy();
551
+ return RESPONSE_GONE;
552
+ }
553
+ return stream;
554
+ }
555
+
272
556
  /**
273
557
  * Set the response headers that describe the file being delivered.
274
558
  *
@@ -286,12 +570,74 @@ export abstract class CoreFileController {
286
570
  * are immutable once written, so a validator built from `_id` + `uploadDate`
287
571
  * is sound. Do that only for files that are genuinely public.
288
572
  */
289
- protected setFileHeaders(res: Response, file: { contentType?: string; filename?: string }): void {
290
- this.setNoStore(res);
573
+ protected setFileHeaders(
574
+ res: Response,
575
+ file: { contentType?: string; filename?: string; id?: string; length?: number },
576
+ ): void {
577
+ this.setCacheHeaders(res, file);
291
578
  res.header('Content-Type', file.contentType || 'application/octet-stream');
292
579
  // See {@link buildContentDisposition} for why the two filename parameters are
293
580
  // rendered differently, and for the injection cases the sanitiser closes.
294
581
  res.header('Content-Disposition', buildContentDisposition(file.filename));
582
+ // Lets a client and every proxy see the size up front and detect a truncated transfer. Taken from the
583
+ // stored metadata, which each store records from the bytes it wrote.
584
+ if (typeof file.length === 'number' && Number.isSafeInteger(file.length) && file.length >= 0) {
585
+ res.header('Content-Length', String(file.length));
586
+ }
587
+ }
588
+
589
+ /**
590
+ * `Cache-Control` and `ETag` of a file response, per `file.downloadCaching`.
591
+ *
592
+ * - `'none'` (default): `private, no-store` — see {@link setFileHeaders} for why.
593
+ * - `'revalidate'`: `private, no-cache` — the BROWSER may keep the file, but must ask again on every use;
594
+ * the request runs the full role and rights check and is answered `304 Not Modified` without the store
595
+ * being read. For image-heavy apps that removes most store reads (and S3 sockets) while every view stays
596
+ * authorized. Shared caches (proxies, CDNs) are still excluded by `private`.
597
+ *
598
+ * The `ETag` is the file id, as a WEAK validator (`W/"<id>"`): the bytes under an id never change (every store
599
+ * writes a new file under a new id; a duplicate is a new id too), but a `compression` middleware in front sends the
600
+ * same file gzip-encoded or not, and RFC 9110 §8.8.3 requires different strong validators for different
601
+ * representations. `If-None-Match` compares weakly anyway, so the 304 works the same.
602
+ */
603
+ protected setCacheHeaders(res: Response, file: { id?: string }): void {
604
+ const mode = ConfigService.configFastButReadOnly?.file?.downloadCaching;
605
+ res.header('Cache-Control', mode === 'revalidate' ? 'private, no-cache' : 'private, no-store');
606
+ const etag = this.fileEtag(file);
607
+ if (etag) {
608
+ res.header('ETag', etag);
609
+ }
610
+ }
611
+
612
+ /**
613
+ * Weak validator of a file: its id, quoted, with `W/` (see {@link setCacheHeaders}). `undefined` without an id.
614
+ */
615
+ protected fileEtag(file: { id?: string }): string | undefined {
616
+ return file?.id ? `W/"${String(file.id)}"` : undefined;
617
+ }
618
+
619
+ /**
620
+ * Answer `304 Not Modified` when the request's `If-None-Match` names this file's validator.
621
+ *
622
+ * Call it only AFTER the file was resolved with the rights check — a 304 confirms the file exists. Reads the
623
+ * request from `res.req`, so the route signatures (which projects override) stay as they are.
624
+ */
625
+ protected answerNotModified(res: Response, file: { id?: string }): boolean {
626
+ const etag = this.fileEtag(file);
627
+ const header = (res as Response & { req?: { headers?: Record<string, string | string[] | undefined> } }).req
628
+ ?.headers?.['if-none-match'];
629
+ if (!etag || !header) {
630
+ return false;
631
+ }
632
+ // Weak comparison (RFC 9110 §13.1.2): the opaque tags must match, `W/` on either side does not count
633
+ const opaque = (value: string) => value.trim().replace(/^W\//, '');
634
+ const candidates = (Array.isArray(header) ? header.join(',') : header).split(',').map(opaque);
635
+ if (!candidates.includes(opaque(etag)) && !candidates.includes('*')) {
636
+ return false;
637
+ }
638
+ this.setCacheHeaders(res, file);
639
+ res.status(304).end();
640
+ return true;
295
641
  }
296
642
 
297
643
  /**
@@ -8,6 +8,7 @@ import { accessDeniedException } from '../../common/exceptions/access-denied.exc
8
8
  import { getObjectIds, getStringIds } from '../../common/helpers/db.helper.js';
9
9
  import { convertFilterArgsToQuery } from '../../common/helpers/filter.helper.js';
10
10
  import { GridFSHelper } from '../../common/helpers/gridfs.helper.js';
11
+ import { guardIdleStream } from '../../common/helpers/idle-stream.helper.js';
11
12
  import { check } from '../../common/helpers/input.helper.js';
12
13
  import { prepareOutput } from '../../common/helpers/service.helper.js';
13
14
  import { isWellFormedId } from '../../common/persistence/id-format.js';
@@ -502,12 +503,44 @@ export abstract class CoreFileService {
502
503
  // Omitting it keeps the previous behaviour exactly.
503
504
  const store = knownStore ?? (await this.locateFile(id));
504
505
  if (store === 's3') {
505
- return S3FileHelper.getStream(this.options.s3Service, id);
506
+ return this.guardDownloadStream(
507
+ await S3FileHelper.getStream(this.options.s3Service, id, this.s3StreamOptions(serviceOptions)),
508
+ serviceOptions,
509
+ );
506
510
  }
507
511
  if (store === 'filesystem') {
508
- return FilesystemFileHelper.getStream(this.filesystemDir, id);
512
+ return this.guardDownloadStream(FilesystemFileHelper.getStream(this.filesystemDir, id), serviceOptions);
509
513
  }
510
- return GridFSHelper.openDownloadStream(this.files, getObjectIds(id)) as mongo.GridFSBucketReadStream;
514
+ return this.guardDownloadStream(
515
+ GridFSHelper.openDownloadStream(this.files, getObjectIds(id)) as mongo.GridFSBucketReadStream,
516
+ serviceOptions,
517
+ );
518
+ }
519
+
520
+ /**
521
+ * Guard a download stream against a caller that stops reading (see `guardIdleStream()`).
522
+ *
523
+ * Every store holds something finite while its stream is open — S3 a socket of the client's pool, the
524
+ * filesystem a file handle, GridFS a server-side cursor. A stream piped with a bare `stream.pipe(res)` to a
525
+ * client that aborts, or one that is obtained and dropped, would hold it for the life of the process. The
526
+ * guard releases it after `file.downloadIdleTimeoutMs` without read progress (S3 streams are already guarded
527
+ * by `CoreS3Service` with `s3.downloadIdleTimeoutMs`; guarding twice is a no-op). Errors of the store — a
528
+ * GridFS file without chunks, a missing file on disk — reach the returned stream as before.
529
+ */
530
+ protected guardDownloadStream(stream: Readable, serviceOptions?: FileServiceOptions): Readable {
531
+ const idleMs = serviceOptions?.downloadIdleTimeoutMs;
532
+ // `false` keeps the guard without its timer — the error handling and the release on close stay
533
+ return guardIdleStream(stream, {
534
+ idleMs: idleMs === false ? false : (idleMs ?? ConfigService.configFastButReadOnly?.file?.downloadIdleTimeoutMs),
535
+ });
536
+ }
537
+
538
+ /** Options for the S3 stream of a download: the caller's abort signal and idle time. */
539
+ protected s3StreamOptions(serviceOptions?: FileServiceOptions): {
540
+ abortSignal?: AbortSignal;
541
+ idleTimeoutMs?: false | number;
542
+ } {
543
+ return { abortSignal: serviceOptions?.abortSignal, idleTimeoutMs: serviceOptions?.downloadIdleTimeoutMs };
511
544
  }
512
545
 
513
546
  /**
@@ -620,19 +653,25 @@ export abstract class CoreFileService {
620
653
  }
621
654
  const s3FileInfo = await this.findS3FileByName(filename);
622
655
  if (s3FileInfo) {
623
- return S3FileHelper.getStream(this.options.s3Service, s3FileInfo._id);
656
+ return this.guardDownloadStream(
657
+ await S3FileHelper.getStream(this.options.s3Service, s3FileInfo._id, this.s3StreamOptions(serviceOptions)),
658
+ serviceOptions,
659
+ );
624
660
  }
625
661
  const fsFileInfo = await this.findFilesystemFileByName(filename);
626
662
  if (fsFileInfo) {
627
- return FilesystemFileHelper.getStream(this.filesystemDir, fsFileInfo._id);
663
+ return this.guardDownloadStream(
664
+ FilesystemFileHelper.getStream(this.filesystemDir, fsFileInfo._id),
665
+ serviceOptions,
666
+ );
628
667
  }
629
668
  const gridFsInfo = await GridFSHelper.findFileByName(this.files, filename);
630
669
  if (!gridFsInfo) {
631
670
  // Unchanged answer for an unknown name: GridFS is the terminal store and reports the miss
632
671
  // itself, asynchronously on the stream, which the controller turns into a 404.
633
- return GridFSHelper.openDownloadStreamByName(this.files, filename);
672
+ return this.guardDownloadStream(GridFSHelper.openDownloadStreamByName(this.files, filename), serviceOptions);
634
673
  }
635
- return GridFSHelper.openDownloadStream(this.files, gridFsInfo._id);
674
+ return this.guardDownloadStream(GridFSHelper.openDownloadStream(this.files, gridFsInfo._id), serviceOptions);
636
675
  }
637
676
 
638
677
  /**
@@ -2,7 +2,29 @@
2
2
  * Interface for service options in file services
3
3
  */
4
4
  export interface FileServiceOptions {
5
+ /**
6
+ * Aborts the store request of a download (`getFileStream()` / `getFileStreamByName()`) when it fires.
7
+ *
8
+ * For S3 this matters under load: a request that waits for a free socket of the client's pool stays queued
9
+ * after its HTTP client has gone, and every one of them later takes a socket and allocates a body. The
10
+ * framework's download routes abort it when the response closes. Since 12.6.10.
11
+ */
12
+ abortSignal?: AbortSignal;
13
+
5
14
  currentUser?: { hasRole: (roles: string[]) => boolean; id: any };
15
+
16
+ /**
17
+ * Idle time of a download stream from `getFileStream()` / `getFileStreamByName()` for THIS call (default
18
+ * `file.downloadIdleTimeoutMs`, for S3 `s3.downloadIdleTimeoutMs`). A stream that makes no read progress for that
19
+ * long is closed to release its socket, file handle or cursor.
20
+ *
21
+ * `false` returns the stream unguarded — only for a caller that reads it late on purpose (an archive that appends
22
+ * every file first and pipes each entry when its turn comes) AND is certain to read it to the end or destroy it:
23
+ * such a stream holds its socket, handle or cursor until then. Prefer opening each stream right before it is read.
24
+ * The guard's error handling stays; for S3 the SDK still closes a socket idle for `s3.socketTimeoutMs`.
25
+ * Since 12.6.10.
26
+ */
27
+ downloadIdleTimeoutMs?: false | number;
6
28
  force?: boolean;
7
29
 
8
30
  /**
@@ -218,9 +218,13 @@ export class S3FileHelper {
218
218
  /**
219
219
  * Get the download stream of a file
220
220
  */
221
- static async getStream(s3Service: CoreS3Service, id: string | Types.ObjectId): Promise<Readable> {
221
+ static async getStream(
222
+ s3Service: CoreS3Service,
223
+ id: string | Types.ObjectId,
224
+ options?: { abortSignal?: AbortSignal; idleTimeoutMs?: false | number },
225
+ ): Promise<Readable> {
222
226
  const objectId = typeof id === 'string' ? newObjectId(id) : id;
223
- return (await s3Service.getObject(objectId.toHexString())).body;
227
+ return (await s3Service.getObject(objectId.toHexString(), options)).body;
224
228
  }
225
229
 
226
230
  /**
package/src/index.ts CHANGED
@@ -45,6 +45,7 @@ export * from './core/common/helpers/filter.helper.js';
45
45
  export * from './core/common/helpers/graphql.helper.js';
46
46
  export * from './core/common/helpers/graphql-ws-connection.helper.js';
47
47
  export * from './core/common/helpers/graphql-ws-context.helper.js';
48
+ export * from './core/common/helpers/idle-stream.helper.js';
48
49
  export * from './core/common/helpers/interceptor.helper.js';
49
50
  export * from './core/common/helpers/gridfs.helper.js';
50
51
  export * from './core/common/helpers/input.helper.js';
package/src/main.ts CHANGED
@@ -48,10 +48,10 @@ async function bootstrap() {
48
48
  if (typeof envConfig.compression === 'object') {
49
49
  envCompressionOptions = envConfig.compression;
50
50
  }
51
+ // `compression.filter` is the package's own default: JSON, GraphQL, text, SSE and SVG are compressed, already
52
+ // compressed formats (JPEG, PNG, PDF, ZIP) are not — gzipping them only burns CPU under many parallel downloads
51
53
  const compressionOptions = {
52
- filter: () => {
53
- return true;
54
- },
54
+ filter: compression.filter,
55
55
  threshold: 0,
56
56
  ...envCompressionOptions,
57
57
  };