@lenne.tech/nest-server 12.6.9 → 12.6.11

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 (43) 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/ai/core-ai.controller.js +8 -4
  12. package/dist/core/modules/ai/core-ai.controller.js.map +1 -1
  13. package/dist/core/modules/file/core-file.controller.d.ts +17 -0
  14. package/dist/core/modules/file/core-file.controller.js +218 -8
  15. package/dist/core/modules/file/core-file.controller.js.map +1 -1
  16. package/dist/core/modules/file/core-file.service.d.ts +5 -0
  17. package/dist/core/modules/file/core-file.service.js +17 -7
  18. package/dist/core/modules/file/core-file.service.js.map +1 -1
  19. package/dist/core/modules/file/interfaces/file-service-options.interface.d.ts +2 -0
  20. package/dist/core/modules/file/s3-file.helper.d.ts +4 -1
  21. package/dist/core/modules/file/s3-file.helper.js +2 -2
  22. package/dist/core/modules/file/s3-file.helper.js.map +1 -1
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.js +1 -0
  25. package/dist/index.js.map +1 -1
  26. package/dist/main.js +1 -3
  27. package/dist/main.js.map +1 -1
  28. package/docs/REQUEST-LIFECYCLE.md +2 -2
  29. package/migration-guides/12.6.10-to-12.6.11.md +75 -0
  30. package/migration-guides/12.6.9-to-12.6.10.md +161 -0
  31. package/package.json +1 -1
  32. package/src/core/common/helpers/idle-stream.helper.ts +192 -0
  33. package/src/core/common/interfaces/server-options.interface.ts +78 -0
  34. package/src/core/common/services/core-s3.service.ts +186 -3
  35. package/src/core/modules/ai/core-ai.controller.ts +12 -4
  36. package/src/core/modules/file/INTEGRATION-CHECKLIST.md +16 -14
  37. package/src/core/modules/file/README.md +63 -0
  38. package/src/core/modules/file/core-file.controller.ts +390 -10
  39. package/src/core/modules/file/core-file.service.ts +46 -7
  40. package/src/core/modules/file/interfaces/file-service-options.interface.ts +22 -0
  41. package/src/core/modules/file/s3-file.helper.ts +6 -2
  42. package/src/index.ts +1 -0
  43. 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,132 @@ 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
+
313
+ /**
314
+ * Open a download stream unless the client has already gone, and release a stream that arrives after it left — the
315
+ * framework's download routes use it, and so should a project's own (with {@link pipeFileToResponse} for delivery):
316
+ *
317
+ * ```typescript
318
+ * const stream = await openDownloadStream(res, () =>
319
+ * this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser }),
320
+ * );
321
+ * if (stream === RESPONSE_GONE) {
322
+ * return res;
323
+ * }
324
+ * if (!stream) {
325
+ * throw new NotFoundException();
326
+ * }
327
+ * return pipeFileToResponse(stream, res);
328
+ * ```
329
+ *
330
+ * Answers {@link RESPONSE_GONE} when there is nobody left to deliver to — end the route with `return res` then:
331
+ * - the client had gone before the store was asked;
332
+ * - the store request failed because the client left meanwhile. An S3 request aborted through
333
+ * {@link downloadAbortSignal} rejects with `AbortError`; rethrown, every aborted download became an ERROR with a
334
+ * stack trace in the log and a 500 sent into a closed response, under exactly the load the log line
335
+ * `S3 socket pool exhausted:` has to stand out in;
336
+ * - the stream arrived after the client left — it is destroyed here, so its socket, file handle or cursor is free at
337
+ * once.
338
+ *
339
+ * A store that handed out no connection in time (`TimeoutError`, see `s3.connectionTimeoutMs`) answers `503` with
340
+ * `Retry-After: 5`. Any other error is rethrown. `null` or `undefined` (the service's rights check refused) is passed
341
+ * on unchanged.
342
+ */
343
+ export async function openDownloadStream<T extends null | Readable | undefined>(
344
+ res: Response,
345
+ open: () => Promise<T>,
346
+ ): Promise<T | typeof RESPONSE_GONE> {
347
+ if (isResponseGone(res)) {
348
+ return RESPONSE_GONE;
349
+ }
350
+ let stream: T;
351
+ try {
352
+ stream = await open();
353
+ } catch (error) {
354
+ if (isResponseGone(res)) {
355
+ return RESPONSE_GONE;
356
+ }
357
+ // The store did not hand out a connection in time (`s3.connectionTimeoutMs`, which includes the wait for a
358
+ // free socket): the store is busy, not broken, and the client may try again — 503, not 500
359
+ if ((error as { name?: string })?.name === 'TimeoutError') {
360
+ fileStreamLogger.warn(`File store busy, download answered 503: ${(error as Error).message}`);
361
+ res.header('Retry-After', '5');
362
+ throw new ServiceUnavailableException('File storage is busy, please retry');
363
+ }
364
+ throw error;
365
+ }
366
+ if (stream && isResponseGone(res)) {
367
+ stream.destroy();
368
+ return RESPONSE_GONE;
369
+ }
370
+ return stream;
371
+ }
372
+
94
373
  /**
95
374
  * File controller
96
375
  *
@@ -181,7 +460,9 @@ export abstract class CoreFileController {
181
460
  throw new BadRequestException(ErrorCode.REQUIRED_FIELD_MISSING);
182
461
  }
183
462
 
184
- const serviceOptions = { currentUser };
463
+ // Registered first: the client may leave while the rights check or the store request is still pending
464
+ const abortSignal = this.downloadAbortSignal(res);
465
+ const serviceOptions = { abortSignal, currentUser };
185
466
  // One lookup for both answers — metadata AND which store holds the bytes.
186
467
  // getFileInfo() followed by getFileStream() had each probe the three stores
187
468
  // from scratch, since neither told the other which one had answered. Same
@@ -191,6 +472,10 @@ export abstract class CoreFileController {
191
472
  if (!file) {
192
473
  throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
193
474
  }
475
+ // Authorized above; a client that already holds these bytes gets 304 without the store being read
476
+ if (this.answerNotModified(res, file)) {
477
+ return res;
478
+ }
194
479
  // S3-stored file with presigned downloads enabled: let the client fetch the
195
480
  // bytes from S3 directly instead of streaming them through the API.
196
481
  //
@@ -217,7 +502,12 @@ export abstract class CoreFileController {
217
502
  res.redirect(302, url);
218
503
  return res;
219
504
  }
220
- const filestream = await this.fileService.getFileStream(id, serviceOptions, resolved.store);
505
+ const filestream = await this.openDownloadStream(res, () =>
506
+ this.fileService.getFileStream(id, serviceOptions, resolved.store),
507
+ );
508
+ if (filestream === RESPONSE_GONE) {
509
+ return res;
510
+ }
221
511
  // `getFileStream` answers null when the service's own rights check refuses.
222
512
  // Same answer as an unknown id: never confirm that the file exists.
223
513
  if (!filestream) {
@@ -248,11 +538,15 @@ export abstract class CoreFileController {
248
538
  throw new BadRequestException(ErrorCode.REQUIRED_FIELD_MISSING);
249
539
  }
250
540
 
251
- const serviceOptions = { currentUser };
541
+ const abortSignal = this.downloadAbortSignal(res);
542
+ const serviceOptions = { abortSignal, currentUser };
252
543
  const file = await this.fileService.getFileInfoByName(filename, serviceOptions);
253
544
  if (!file) {
254
545
  throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
255
546
  }
547
+ if (this.answerNotModified(res, file)) {
548
+ return res;
549
+ }
256
550
  // See getFileById(): authorization on the presigned branch rests on the
257
551
  // getFileInfoByName() call above.
258
552
  const url = await this.resolveDownloadUrl(file.id, serviceOptions);
@@ -261,7 +555,12 @@ export abstract class CoreFileController {
261
555
  res.redirect(302, url);
262
556
  return res;
263
557
  }
264
- const filestream = await this.fileService.getFileStream(file.id, serviceOptions);
558
+ const filestream = await this.openDownloadStream(res, () =>
559
+ this.fileService.getFileStream(file.id, serviceOptions),
560
+ );
561
+ if (filestream === RESPONSE_GONE) {
562
+ return res;
563
+ }
265
564
  if (!filestream) {
266
565
  throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
267
566
  }
@@ -269,6 +568,25 @@ export abstract class CoreFileController {
269
568
  return this.pipeFileToResponse(filestream, res);
270
569
  }
271
570
 
571
+ /**
572
+ * An `AbortSignal` that fires when the response closes — the client has gone. Passed to the store, so an S3
573
+ * request that still waits for a free socket is dropped instead of taking one later for nobody.
574
+ */
575
+ protected downloadAbortSignal(res: Response): AbortSignal {
576
+ return downloadAbortSignal(res);
577
+ }
578
+
579
+ /**
580
+ * Open the download stream unless the client has already gone, and release a stream that arrives after it left —
581
+ * see the exported {@link openDownloadStream}, which a project's own download route uses the same way.
582
+ */
583
+ protected async openDownloadStream(
584
+ res: Response,
585
+ open: () => Promise<Readable>,
586
+ ): Promise<Readable | typeof RESPONSE_GONE> {
587
+ return openDownloadStream(res, open);
588
+ }
589
+
272
590
  /**
273
591
  * Set the response headers that describe the file being delivered.
274
592
  *
@@ -286,12 +604,74 @@ export abstract class CoreFileController {
286
604
  * are immutable once written, so a validator built from `_id` + `uploadDate`
287
605
  * is sound. Do that only for files that are genuinely public.
288
606
  */
289
- protected setFileHeaders(res: Response, file: { contentType?: string; filename?: string }): void {
290
- this.setNoStore(res);
607
+ protected setFileHeaders(
608
+ res: Response,
609
+ file: { contentType?: string; filename?: string; id?: string; length?: number },
610
+ ): void {
611
+ this.setCacheHeaders(res, file);
291
612
  res.header('Content-Type', file.contentType || 'application/octet-stream');
292
613
  // See {@link buildContentDisposition} for why the two filename parameters are
293
614
  // rendered differently, and for the injection cases the sanitiser closes.
294
615
  res.header('Content-Disposition', buildContentDisposition(file.filename));
616
+ // Lets a client and every proxy see the size up front and detect a truncated transfer. Taken from the
617
+ // stored metadata, which each store records from the bytes it wrote.
618
+ if (typeof file.length === 'number' && Number.isSafeInteger(file.length) && file.length >= 0) {
619
+ res.header('Content-Length', String(file.length));
620
+ }
621
+ }
622
+
623
+ /**
624
+ * `Cache-Control` and `ETag` of a file response, per `file.downloadCaching`.
625
+ *
626
+ * - `'none'` (default): `private, no-store` — see {@link setFileHeaders} for why.
627
+ * - `'revalidate'`: `private, no-cache` — the BROWSER may keep the file, but must ask again on every use;
628
+ * the request runs the full role and rights check and is answered `304 Not Modified` without the store
629
+ * being read. For image-heavy apps that removes most store reads (and S3 sockets) while every view stays
630
+ * authorized. Shared caches (proxies, CDNs) are still excluded by `private`.
631
+ *
632
+ * The `ETag` is the file id, as a WEAK validator (`W/"<id>"`): the bytes under an id never change (every store
633
+ * writes a new file under a new id; a duplicate is a new id too), but a `compression` middleware in front sends the
634
+ * same file gzip-encoded or not, and RFC 9110 §8.8.3 requires different strong validators for different
635
+ * representations. `If-None-Match` compares weakly anyway, so the 304 works the same.
636
+ */
637
+ protected setCacheHeaders(res: Response, file: { id?: string }): void {
638
+ const mode = ConfigService.configFastButReadOnly?.file?.downloadCaching;
639
+ res.header('Cache-Control', mode === 'revalidate' ? 'private, no-cache' : 'private, no-store');
640
+ const etag = this.fileEtag(file);
641
+ if (etag) {
642
+ res.header('ETag', etag);
643
+ }
644
+ }
645
+
646
+ /**
647
+ * Weak validator of a file: its id, quoted, with `W/` (see {@link setCacheHeaders}). `undefined` without an id.
648
+ */
649
+ protected fileEtag(file: { id?: string }): string | undefined {
650
+ return file?.id ? `W/"${String(file.id)}"` : undefined;
651
+ }
652
+
653
+ /**
654
+ * Answer `304 Not Modified` when the request's `If-None-Match` names this file's validator.
655
+ *
656
+ * Call it only AFTER the file was resolved with the rights check — a 304 confirms the file exists. Reads the
657
+ * request from `res.req`, so the route signatures (which projects override) stay as they are.
658
+ */
659
+ protected answerNotModified(res: Response, file: { id?: string }): boolean {
660
+ const etag = this.fileEtag(file);
661
+ const header = (res as Response & { req?: { headers?: Record<string, string | string[] | undefined> } }).req
662
+ ?.headers?.['if-none-match'];
663
+ if (!etag || !header) {
664
+ return false;
665
+ }
666
+ // Weak comparison (RFC 9110 §13.1.2): the opaque tags must match, `W/` on either side does not count
667
+ const opaque = (value: string) => value.trim().replace(/^W\//, '');
668
+ const candidates = (Array.isArray(header) ? header.join(',') : header).split(',').map(opaque);
669
+ if (!candidates.includes(opaque(etag)) && !candidates.includes('*')) {
670
+ return false;
671
+ }
672
+ this.setCacheHeaders(res, file);
673
+ res.status(304).end();
674
+ return true;
295
675
  }
296
676
 
297
677
  /**
@@ -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
  };