@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,7 +1,10 @@
1
1
  import { Injectable, Logger, OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
2
+ import { Agent as HttpAgent } from 'http';
3
+ import { Agent as HttpsAgent } from 'https';
2
4
  import { PassThrough } from 'stream';
3
5
 
4
6
  import { buildContentDisposition } from '../helpers/content-disposition.helper.js';
7
+ import { DEFAULT_STREAM_IDLE_TIMEOUT_MS, guardIdleStream, MAX_TIMER_DELAY_MS } from '../helpers/idle-stream.helper.js';
5
8
  import { ConfigService } from './config.service.js';
6
9
 
7
10
  import type { IS3Config } from '../interfaces/server-options.interface.js';
@@ -28,18 +31,55 @@ const MAX_PRESIGNED_EXPIRY_SECONDS = 604_800;
28
31
  */
29
32
  const PRESIGNED_EXPIRY_ADVISORY_SECONDS = 900;
30
33
 
34
+ /** Defaults of the S3 connection pool (see `IS3Config`): why each value, is documented there. */
35
+ const S3_DEFAULT_MAX_SOCKETS = 200;
36
+ const S3_DEFAULT_CONNECTION_TIMEOUT_MS = 15_000;
37
+ const S3_DEFAULT_SOCKET_TIMEOUT_MS = 120_000;
38
+
39
+ /** How often the pool is checked for requests waiting on a socket, and how often a saturation is reported. */
40
+ const S3_POOL_CHECK_INTERVAL_MS = 5_000;
41
+ const S3_POOL_REPORT_INTERVAL_MS = 60_000;
42
+
43
+ /**
44
+ * Usage of the S3 socket pool, summed over both protocols and every origin.
45
+ */
46
+ export interface S3SocketPoolStats {
47
+ /** Sockets currently carrying a request (or a response body nobody has finished reading) */
48
+ active: number;
49
+ /** Open keep-alive sockets waiting for the next request */
50
+ free: number;
51
+ /** Configured maximum per origin and protocol (`s3.maxSockets`) */
52
+ maxSockets: number;
53
+ /** Requests waiting for a socket because the pool is exhausted */
54
+ waiting: number;
55
+ }
56
+
31
57
  /**
32
58
  * Fully normalized S3 configuration with defaults applied
33
59
  */
34
60
  export type NormalizedS3Config = Omit<IS3Config, 'enabled' | 'presignedDownloads'> & {
35
61
  bucket: string;
62
+ connectionTimeoutMs: number;
63
+ downloadIdleTimeoutMs: number;
36
64
  forcePathStyle: boolean;
65
+ maxSockets: number;
37
66
  /** undefined = presigned downloads disabled */
38
67
  presignedDownloads?: { expiresInSeconds: number };
39
68
  region: string;
69
+ socketTimeoutMs: number;
40
70
  stagingBucket: string;
41
71
  };
42
72
 
73
+ /**
74
+ * A positive, finite number, or the default — never "unbounded" for a misconfigured value. Capped at the longest delay
75
+ * a Node timer accepts: a larger one is clamped by Node to 1 ms, which would fire every timeout at once.
76
+ */
77
+ function positiveOrDefault(value: unknown, fallback: number): number {
78
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
79
+ ? Math.min(value, MAX_TIMER_DELAY_MS)
80
+ : fallback;
81
+ }
82
+
43
83
  /**
44
84
  * Central S3-compatible object storage service (see IServerOptions.s3).
45
85
  *
@@ -84,6 +124,19 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
84
124
  */
85
125
  protected multipartUploader?: null | typeof import('@aws-sdk/lib-storage');
86
126
 
127
+ /**
128
+ * The agents the S3 client's request handler uses, one per protocol. Kept so the pool can be measured
129
+ * ({@link CoreS3Service.getSocketPoolStats}) and closed at shutdown.
130
+ */
131
+ protected agents?: { http: HttpAgent; https: HttpsAgent };
132
+
133
+ /** Periodic check of the pool for waiting requests, see {@link CoreS3Service.checkSocketPool} */
134
+ protected poolMonitor?: NodeJS.Timeout;
135
+
136
+ /** When a saturation was last reported, and how many download streams were closed idle since the last report */
137
+ protected lastPoolReportAt = 0;
138
+ protected idleClosedSinceReport = 0;
139
+
87
140
  constructor(protected readonly configService: ConfigService) {
88
141
  const raw = this.configService.getFastButReadOnly<IS3Config | undefined>('s3');
89
142
  if (!raw || raw.enabled === false) {
@@ -115,8 +168,11 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
115
168
  accessKeyId: raw.accessKeyId,
116
169
  autoCreateBucket: raw.autoCreateBucket ?? false,
117
170
  bucket: raw.bucket,
171
+ connectionTimeoutMs: positiveOrDefault(raw.connectionTimeoutMs, S3_DEFAULT_CONNECTION_TIMEOUT_MS),
172
+ downloadIdleTimeoutMs: positiveOrDefault(raw.downloadIdleTimeoutMs, DEFAULT_STREAM_IDLE_TIMEOUT_MS),
118
173
  endpoint: raw.endpoint,
119
174
  forcePathStyle: raw.forcePathStyle ?? false,
175
+ maxSockets: Math.floor(positiveOrDefault(raw.maxSockets, S3_DEFAULT_MAX_SOCKETS)) || S3_DEFAULT_MAX_SOCKETS,
120
176
  presignedDownloads: presigned
121
177
  ? {
122
178
  expiresInSeconds: this.clampPresignedExpiry(
@@ -126,6 +182,7 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
126
182
  : undefined,
127
183
  region: raw.region ?? 'us-east-1',
128
184
  secretAccessKey: raw.secretAccessKey,
185
+ socketTimeoutMs: positiveOrDefault(raw.socketTimeoutMs, S3_DEFAULT_SOCKET_TIMEOUT_MS),
129
186
  stagingBucket: raw.stagingBucket ?? raw.bucket,
130
187
  };
131
188
  }
@@ -194,6 +251,7 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
194
251
  this.client = new this.sdk.S3Client({
195
252
  ...(endpoint ? { endpoint } : {}),
196
253
  forcePathStyle,
254
+ requestHandler: this.buildRequestHandlerOptions(),
197
255
  // Without a logger the SDK writes some warnings straight to `console` — "An error was encountered in
198
256
  // a non-retryable streaming request." on every failed or aborted upload stream — outside the app's
199
257
  // log levels and format. Warnings go through this service's logger instead. Everything else stays
@@ -217,9 +275,101 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
217
275
  // where operators look — the startup log — instead of during the first large upload.
218
276
  await this.loadMultipartUploader();
219
277
 
278
+ this.startPoolMonitor();
279
+
220
280
  await this.verifyBuckets();
221
281
  }
222
282
 
283
+ /**
284
+ * Options for the S3 client's HTTP request handler (`NodeHttpHandler`, created by the SDK from them).
285
+ *
286
+ * WHY NOT THE SDK DEFAULTS: they are a pool of 50 sockets and no timeout that frees a socket whose
287
+ * response body nobody reads. A download stream that is dropped, or piped with a bare `stream.pipe(res)` to
288
+ * a client that aborts, then holds its socket forever; after `maxSockets` such downloads every further S3
289
+ * request waits without end. The defaults here bound both: own agents with `s3.maxSockets`, a connection
290
+ * timeout, and a socket inactivity timeout as the backstop. The main guard for downloads is the idle guard
291
+ * on the body ({@link CoreS3Service.getObject}): the SDK's `requestTimeout` stops counting once the headers
292
+ * have arrived, and its socket timeout destroys the body WITH an error — which ends the process when nothing
293
+ * listens on that body. The guard listens, and it ends a stalled download much earlier.
294
+ *
295
+ * Passed as options rather than a handler instance, so the core does not import `@smithy/node-http-handler`
296
+ * itself (a transitive dependency of the optional peer, not resolvable from every project layout).
297
+ * Override to tune further, e.g. an agent with a CA bundle.
298
+ */
299
+ protected buildRequestHandlerOptions(): Record<string, unknown> {
300
+ const { connectionTimeoutMs, maxSockets, socketTimeoutMs } = this.config;
301
+ this.agents = {
302
+ http: new HttpAgent({ keepAlive: true, maxSockets }),
303
+ https: new HttpsAgent({ keepAlive: true, maxSockets }),
304
+ };
305
+ return {
306
+ connectionTimeout: connectionTimeoutMs,
307
+ httpAgent: this.agents.http,
308
+ httpsAgent: this.agents.https,
309
+ socketTimeout: socketTimeoutMs,
310
+ };
311
+ }
312
+
313
+ /**
314
+ * Usage of the S3 socket pool right now. `undefined` while S3 is disabled or not initialized.
315
+ *
316
+ * `waiting > 0` means requests are queued for a socket: the pool is exhausted. That is reported as an error
317
+ * in the log (see {@link CoreS3Service.checkSocketPool}); a project can also expose it to its monitoring.
318
+ */
319
+ getSocketPoolStats(): S3SocketPoolStats | undefined {
320
+ if (!this.agents || !this.config) {
321
+ return undefined;
322
+ }
323
+ const count = (map: NodeJS.ReadOnlyDict<unknown[]> | undefined) =>
324
+ Object.values(map ?? {}).reduce<number>((sum, list) => sum + (list?.length ?? 0), 0);
325
+ const agents = [this.agents.http, this.agents.https];
326
+ return {
327
+ active: agents.reduce((sum, agent) => sum + count(agent.sockets), 0),
328
+ free: agents.reduce((sum, agent) => sum + count(agent.freeSockets), 0),
329
+ maxSockets: this.config.maxSockets,
330
+ waiting: agents.reduce((sum, agent) => sum + count(agent.requests), 0),
331
+ };
332
+ }
333
+
334
+ /**
335
+ * Start the periodic pool check. The interval never keeps the process alive.
336
+ */
337
+ protected startPoolMonitor(): void {
338
+ if (this.poolMonitor) {
339
+ return;
340
+ }
341
+ this.poolMonitor = setInterval(() => this.checkSocketPool(), S3_POOL_CHECK_INTERVAL_MS);
342
+ this.poolMonitor.unref?.();
343
+ }
344
+
345
+ /**
346
+ * Report an exhausted pool as an ERROR, at most once per minute and with numbers.
347
+ *
348
+ * An exhausted pool makes every S3 request wait — downloads, uploads, existence checks — while the health
349
+ * check, which does not touch S3, stays green. The log line is what an alert can fire on. Deliberately NOT a
350
+ * health-check failure: a short S3 disturbance would then take the whole API (sign-in included) out of the
351
+ * load balancer, which costs far more than slow downloads.
352
+ */
353
+ protected checkSocketPool(): void {
354
+ const stats = this.getSocketPoolStats();
355
+ if (!stats || stats.waiting === 0) {
356
+ return;
357
+ }
358
+ const now = Date.now();
359
+ if (now - this.lastPoolReportAt < S3_POOL_REPORT_INTERVAL_MS) {
360
+ return;
361
+ }
362
+ this.lastPoolReportAt = now;
363
+ this.logger.error(
364
+ `S3 socket pool exhausted: ${stats.active}/${stats.maxSockets} sockets in use, ${stats.waiting} request(s) ` +
365
+ `waiting for a socket, ${this.idleClosedSinceReport} download stream(s) closed for lack of progress since the ` +
366
+ 'last report. Every S3 request waits until a socket is free. Raise s3.maxSockets if this is genuine load; ' +
367
+ 'a growing count without load points to download streams that are not consumed or destroyed — deliver files ' +
368
+ 'with pipeFileToResponse().',
369
+ );
370
+ this.idleClosedSinceReport = 0;
371
+ }
372
+
223
373
  /**
224
374
  * Check at boot that the configured buckets are reachable.
225
375
  *
@@ -552,11 +702,37 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
552
702
  * Get an object stream (plus metadata) from the main bucket.
553
703
  * Throws the SDK's NoSuchKey error when the object does not exist.
554
704
  */
555
- async getObject(key: string): Promise<{ body: Readable; contentLength?: number; contentType?: string }> {
705
+ async getObject(
706
+ key: string,
707
+ options?: {
708
+ abortSignal?: AbortSignal;
709
+ /**
710
+ * Idle time of the returned stream for THIS call (default `s3.downloadIdleTimeoutMs`). `false` returns the body
711
+ * unguarded — only for a caller that reads the stream late on purpose (an archive that pipes each entry when
712
+ * its turn comes) AND is certain to read it to the end or destroy it; such a body holds its socket until then.
713
+ */
714
+ idleTimeoutMs?: false | number;
715
+ },
716
+ ): Promise<{ body: Readable; contentLength?: number; contentType?: string }> {
556
717
  const { client, config, sdk } = this.requireInit();
557
- const result = await client.send(new sdk.GetObjectCommand({ Bucket: config.bucket, Key: key }));
718
+ // `abortSignal`: a caller whose client has gone aborts the request, also while it still waits for a socket —
719
+ // otherwise it stays queued and takes a socket and a body later, for nobody (see `IS3Config.maxSockets`)
720
+ const idleMs = options?.idleTimeoutMs;
721
+ const result = await client.send(
722
+ new sdk.GetObjectCommand({ Bucket: config.bucket, Key: key }),
723
+ options?.abortSignal ? { abortSignal: options.abortSignal } : undefined,
724
+ );
558
725
  return {
559
- body: result.Body as Readable,
726
+ // Guarded: a body nobody reads releases its socket after `s3.downloadIdleTimeoutMs` instead of holding it
727
+ // for the life of the process. Destroying the returned stream releases it at once.
728
+ // `idleTimeoutMs: false` keeps the guard WITHOUT its timer: an unread body is destroyed with an error by the
729
+ // SDK's socket timeout (`s3.socketTimeoutMs`), which ends the process when nothing listens on it
730
+ body: guardIdleStream(result.Body as Readable, {
731
+ idleMs: idleMs === false ? false : (idleMs ?? config.downloadIdleTimeoutMs),
732
+ onIdle: () => {
733
+ this.idleClosedSinceReport++;
734
+ },
735
+ }),
560
736
  contentLength: result.ContentLength,
561
737
  contentType: result.ContentType,
562
738
  };
@@ -648,8 +824,15 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
648
824
  * Destroy the shared client
649
825
  */
650
826
  async onApplicationShutdown(): Promise<void> {
827
+ if (this.poolMonitor) {
828
+ clearInterval(this.poolMonitor);
829
+ this.poolMonitor = undefined;
830
+ }
651
831
  this.client?.destroy();
652
832
  this.client = undefined;
833
+ this.agents?.http.destroy();
834
+ this.agents?.https.destroy();
835
+ this.agents = undefined;
653
836
  }
654
837
 
655
838
  /**
@@ -226,17 +226,18 @@ personal or medical, a per-file rule is not optional.
226
226
 
227
227
  ## Common Mistakes
228
228
 
229
- | Mistake | Symptom | Fix |
230
- | -------------------------------------------------------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
231
- | Overriding `getFileById` to add Swagger decorators | `file.downloadRoles` silently ignored | Don't override; document at class level |
232
- | Overriding without re-declaring `@Get(...)` | Route 404s for everyone, no error logged | Don't override |
233
- | `downloadRoles: []` | Warning logged, default applied | Use a non-empty array; `[]` would read as "no roles required" and open the route |
234
- | Expecting `metadata` back from `getFileInfo()` | `undefined` | Use `getRawFileInfo()` inside `checkRights()` |
235
- | `downloadRoles: ['member']` with multiTenancy | Works from code, fails from `<img>` | Both file classes carry `@SkipTenantCheck()`; roles resolve against `user.roles`. Use `checkRights()` for tenant rules |
236
- | Signed-in user can upload via TUS but not download | 403 on their own file | `tus.roles` and `file.downloadRoles` are separate. Add an owner to the metadata and authorize per file |
237
- | Rule narrows only `'id'` / `'filename'` | `findFileInfo()` returns every file | Refuse `'filterArgs'`; force a per-user filter server-side with `{ force: true }` |
238
- | Treating the file id as unguessable | Enumerable inventory | Ids share a per-process random part and an incrementing counter — authorize every read, do not rely on the id |
239
- | Approving the caller's `filterArgs` as "narrowed" | Bypass via a different filter shape | `filterArgs` is client-controlled. Override the filter; never approve it |
240
- | `super(connection)` in `FileService` with `file.storage: 's3'` | Boot fails: "that storage is not available" | Forward `{ configService, s3Service }` — step 6 |
241
- | S3 packages in `devDependencies` | Production image cannot load S3 | Move them to `dependencies` — step 6 |
242
- | A quota aggregating only `fs.files` | Reads 0 on the S3 / filesystem driver | Aggregate `fs.files`, `filesystem-files` and `s3-files` — step 6 |
229
+ | Mistake | Symptom | Fix |
230
+ | -------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
231
+ | Overriding `getFileById` to add Swagger decorators | `file.downloadRoles` silently ignored | Don't override; document at class level |
232
+ | Overriding without re-declaring `@Get(...)` | Route 404s for everyone, no error logged | Don't override |
233
+ | `downloadRoles: []` | Warning logged, default applied | Use a non-empty array; `[]` would read as "no roles required" and open the route |
234
+ | Expecting `metadata` back from `getFileInfo()` | `undefined` | Use `getRawFileInfo()` inside `checkRights()` |
235
+ | `downloadRoles: ['member']` with multiTenancy | Works from code, fails from `<img>` | Both file classes carry `@SkipTenantCheck()`; roles resolve against `user.roles`. Use `checkRights()` for tenant rules |
236
+ | Signed-in user can upload via TUS but not download | 403 on their own file | `tus.roles` and `file.downloadRoles` are separate. Add an owner to the metadata and authorize per file |
237
+ | Rule narrows only `'id'` / `'filename'` | `findFileInfo()` returns every file | Refuse `'filterArgs'`; force a per-user filter server-side with `{ force: true }` |
238
+ | Treating the file id as unguessable | Enumerable inventory | Ids share a per-process random part and an incrementing counter — authorize every read, do not rely on the id |
239
+ | Approving the caller's `filterArgs` as "narrowed" | Bypass via a different filter shape | `filterArgs` is client-controlled. Override the filter; never approve it |
240
+ | `super(connection)` in `FileService` with `file.storage: 's3'` | Boot fails: "that storage is not available" | Forward `{ configService, s3Service }` — step 6 |
241
+ | Own download route with `stream.pipe(res)` | After enough aborted downloads every S3 request hangs; health check stays green | `pipeFileToResponse(stream, res)` — it destroys the source when the response closes (README, "Delivering a file from your own route") |
242
+ | S3 packages in `devDependencies` | Production image cannot load S3 | Move them to `dependencies` — step 6 |
243
+ | A quota aggregating only `fs.files` | Reads 0 on the S3 / filesystem driver | Aggregate `fs.files`, `filesystem-files` and `s3-files` — step 6 |
@@ -41,6 +41,12 @@ file: {
41
41
 
42
42
  `storage` and the role knobs are orthogonal: one picks the driver, the others the access.
43
43
 
44
+ Downloads (12.6.10+): `downloadIdleTimeoutMs` (30 000) closes a download stream that makes no read progress, so an
45
+ aborted or dropped download releases its file handle or GridFS cursor; `downloadCaching: 'revalidate'` lets the browser
46
+ keep a file and revalidate it (`304` after the rights check, no store read). S3 has its own pool settings under `s3`
47
+ (`maxSockets`, `connectionTimeoutMs`, `socketTimeoutMs`, `downloadIdleTimeoutMs`) — see
48
+ [Delivering a file from your own route](#delivering-a-file-from-your-own-route-12610).
49
+
44
50
  ## Storage drivers
45
51
 
46
52
  Three equivalent options. They differ only in where the bytes end up:
@@ -488,6 +494,48 @@ server-side even though the client answer stays deliberately generic.
488
494
  To change the status, the body or the logging, override the `protected pipeFileToResponse()` method
489
495
  on the controller rather than the exported function of the same name.
490
496
 
497
+ | Situation (12.6.10+) | Status | Body / headers |
498
+ | ------------------------------------------------------------------------------------------- | ------ | ------------------------------------------------------------------------------ |
499
+ | `If-None-Match` names the file's weak `ETag` (`W/"<id>"`), after the rights check | `304` | No body; the store is not read |
500
+ | The store hands out no connection within 3 attempts of `s3.connectionTimeoutMs` (pool busy) | `503` | `Retry-After: 5`; the store is busy, not broken |
501
+ | The client left before the stream was handed over | — | Nothing is sent; the stream is destroyed at once, a pending S3 request aborted |
502
+
503
+ ### Delivering a file from your own route (12.6.10)
504
+
505
+ **Use `pipeFileToResponse(stream, res)` for every download route of your own — never `stream.pipe(res)`.**
506
+ When the client aborts, `pipe()` only unpipes: the source stays open and keeps what it holds — for S3 a socket of the
507
+ client's pool. Enough aborted downloads and the pool is full; every S3 request then waits forever while the health
508
+ check stays green. A production outage had exactly this cause. `pipeFileToResponse()` destroys the source when the
509
+ client goes — on the response's `close`, the request's `close` before its end or the socket's `end`/`close`, and at once when the client
510
+ had already gone before the call — and answers a store error before the first byte with `404`.
511
+
512
+ ```typescript
513
+ import { downloadAbortSignal, pipeFileToResponse } from '@lenne.tech/nest-server';
514
+
515
+ const stream = await this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser });
516
+ return pipeFileToResponse(stream, res);
517
+ ```
518
+
519
+ Layers below it, each effective on its own:
520
+
521
+ - Every stream from `CoreFileService.getFileStream()` / `getFileStreamByName()` and `CoreS3Service.getObject()` closes
522
+ itself after `downloadIdleTimeoutMs` (30 s) without read progress. A slow reader that keeps reading is never cut off.
523
+ **Read a stream right after obtaining it**: code that collects streams and reads them later (a ZIP export appending
524
+ every file first) breaks — the closed stream ends without `end`. Open each stream right before it is read, or opt out
525
+ for that call with `downloadIdleTimeoutMs: false` (`getObject(key, { idleTimeoutMs: false })`) when the code is
526
+ certain to read it to the end or destroy it.
527
+ - The S3 client runs with its own agents: `s3.maxSockets` (200 instead of the SDK's 50), `s3.connectionTimeoutMs`
528
+ (15 s per attempt — the bound for waiting for a socket, too; the SDK makes 3 attempts, so a download that gets no
529
+ socket answers `503` after about 46 s, below the common 60 s proxy timeout), `s3.socketTimeoutMs` (120 s inactivity
530
+ backstop).
531
+ - An exhausted pool is logged as an ERROR once per minute with numbers (`S3 socket pool exhausted: …`) — alert on it.
532
+ Downloads closed for lack of progress are one WARN line per minute, never an ERROR per download.
533
+ `CoreS3Service.getSocketPoolStats()` gives the same numbers to a project's monitoring. It is deliberately not a
534
+ health-check failure: a short S3 disturbance would take the whole API out of the load balancer.
535
+ - Pass `abortSignal` (aborted when the response closes) so an S3 request whose client has gone is dropped while it
536
+ waits for a socket instead of taking one later. The framework's routes do this.
537
+ - `s3.presignedDownloads` moves the bytes off the API entirely (a `302` to S3) — consider it for public files.
538
+
491
539
  ### Upload filtering
492
540
 
493
541
  Upload endpoints are project-specific, but the filter they install comes from the framework