@lenne.tech/nest-server 11.46.1 → 11.46.3

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 (44) 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 +100 -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/plugins/mongoose-id.plugin.js +3 -0
  9. package/dist/core/common/plugins/mongoose-id.plugin.js.map +1 -1
  10. package/dist/core/common/services/core-s3.service.d.ts +27 -1
  11. package/dist/core/common/services/core-s3.service.js +89 -3
  12. package/dist/core/common/services/core-s3.service.js.map +1 -1
  13. package/dist/core/modules/file/core-file.controller.d.ts +16 -0
  14. package/dist/core/modules/file/core-file.controller.js +217 -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/dist/tsconfig.build.tsbuildinfo +1 -1
  29. package/docs/REQUEST-LIFECYCLE.md +2 -2
  30. package/migration-guides/11.46.1-to-11.46.2.md +44 -0
  31. package/migration-guides/11.46.2-to-11.46.3.md +149 -0
  32. package/package.json +3 -3
  33. package/src/core/common/helpers/idle-stream.helper.ts +192 -0
  34. package/src/core/common/interfaces/server-options.interface.ts +78 -0
  35. package/src/core/common/plugins/mongoose-id.plugin.ts +9 -0
  36. package/src/core/common/services/core-s3.service.ts +186 -3
  37. package/src/core/modules/file/INTEGRATION-CHECKLIST.md +15 -14
  38. package/src/core/modules/file/README.md +48 -0
  39. package/src/core/modules/file/core-file.controller.ts +356 -10
  40. package/src/core/modules/file/core-file.service.ts +46 -7
  41. package/src/core/modules/file/interfaces/file-service-options.interface.ts +22 -0
  42. package/src/core/modules/file/s3-file.helper.ts +6 -2
  43. package/src/index.ts +1 -0
  44. 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';
7
+ import { DEFAULT_STREAM_IDLE_TIMEOUT_MS, guardIdleStream, MAX_TIMER_DELAY_MS } from '../helpers/idle-stream.helper';
5
8
  import { ConfigService } from './config.service';
6
9
 
7
10
  import type { IS3Config } from '../interfaces/server-options.interface';
@@ -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
  region,
198
256
  // Fall back to the SDK default credential chain when no keys are configured
199
257
  ...(accessKeyId && secretAccessKey ? { credentials: { accessKeyId, secretAccessKey } } : {}),
@@ -203,9 +261,101 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
203
261
  // where operators look — the startup log — instead of during the first large upload.
204
262
  await this.loadMultipartUploader();
205
263
 
264
+ this.startPoolMonitor();
265
+
206
266
  await this.verifyBuckets();
207
267
  }
208
268
 
269
+ /**
270
+ * Options for the S3 client's HTTP request handler (`NodeHttpHandler`, created by the SDK from them).
271
+ *
272
+ * WHY NOT THE SDK DEFAULTS: they are a pool of 50 sockets and no timeout that frees a socket whose
273
+ * response body nobody reads. A download stream that is dropped, or piped with a bare `stream.pipe(res)` to
274
+ * a client that aborts, then holds its socket forever; after `maxSockets` such downloads every further S3
275
+ * request waits without end. The defaults here bound both: own agents with `s3.maxSockets`, a connection
276
+ * timeout, and a socket inactivity timeout as the backstop. The main guard for downloads is the idle guard
277
+ * on the body ({@link CoreS3Service.getObject}): the SDK's `requestTimeout` stops counting once the headers
278
+ * have arrived, and its socket timeout destroys the body WITH an error — which ends the process when nothing
279
+ * listens on that body. The guard listens, and it ends a stalled download much earlier.
280
+ *
281
+ * Passed as options rather than a handler instance, so the core does not import `@smithy/node-http-handler`
282
+ * itself (a transitive dependency of the optional peer, not resolvable from every project layout).
283
+ * Override to tune further, e.g. an agent with a CA bundle.
284
+ */
285
+ protected buildRequestHandlerOptions(): Record<string, unknown> {
286
+ const { connectionTimeoutMs, maxSockets, socketTimeoutMs } = this.config;
287
+ this.agents = {
288
+ http: new HttpAgent({ keepAlive: true, maxSockets }),
289
+ https: new HttpsAgent({ keepAlive: true, maxSockets }),
290
+ };
291
+ return {
292
+ connectionTimeout: connectionTimeoutMs,
293
+ httpAgent: this.agents.http,
294
+ httpsAgent: this.agents.https,
295
+ socketTimeout: socketTimeoutMs,
296
+ };
297
+ }
298
+
299
+ /**
300
+ * Usage of the S3 socket pool right now. `undefined` while S3 is disabled or not initialized.
301
+ *
302
+ * `waiting > 0` means requests are queued for a socket: the pool is exhausted. That is reported as an error
303
+ * in the log (see {@link CoreS3Service.checkSocketPool}); a project can also expose it to its monitoring.
304
+ */
305
+ getSocketPoolStats(): S3SocketPoolStats | undefined {
306
+ if (!this.agents || !this.config) {
307
+ return undefined;
308
+ }
309
+ const count = (map: NodeJS.ReadOnlyDict<unknown[]> | undefined) =>
310
+ Object.values(map ?? {}).reduce<number>((sum, list) => sum + (list?.length ?? 0), 0);
311
+ const agents = [this.agents.http, this.agents.https];
312
+ return {
313
+ active: agents.reduce((sum, agent) => sum + count(agent.sockets), 0),
314
+ free: agents.reduce((sum, agent) => sum + count(agent.freeSockets), 0),
315
+ maxSockets: this.config.maxSockets,
316
+ waiting: agents.reduce((sum, agent) => sum + count(agent.requests), 0),
317
+ };
318
+ }
319
+
320
+ /**
321
+ * Start the periodic pool check. The interval never keeps the process alive.
322
+ */
323
+ protected startPoolMonitor(): void {
324
+ if (this.poolMonitor) {
325
+ return;
326
+ }
327
+ this.poolMonitor = setInterval(() => this.checkSocketPool(), S3_POOL_CHECK_INTERVAL_MS);
328
+ this.poolMonitor.unref?.();
329
+ }
330
+
331
+ /**
332
+ * Report an exhausted pool as an ERROR, at most once per minute and with numbers.
333
+ *
334
+ * An exhausted pool makes every S3 request wait — downloads, uploads, existence checks — while the health
335
+ * check, which does not touch S3, stays green. The log line is what an alert can fire on. Deliberately NOT a
336
+ * health-check failure: a short S3 disturbance would then take the whole API (sign-in included) out of the
337
+ * load balancer, which costs far more than slow downloads.
338
+ */
339
+ protected checkSocketPool(): void {
340
+ const stats = this.getSocketPoolStats();
341
+ if (!stats || stats.waiting === 0) {
342
+ return;
343
+ }
344
+ const now = Date.now();
345
+ if (now - this.lastPoolReportAt < S3_POOL_REPORT_INTERVAL_MS) {
346
+ return;
347
+ }
348
+ this.lastPoolReportAt = now;
349
+ this.logger.error(
350
+ `S3 socket pool exhausted: ${stats.active}/${stats.maxSockets} sockets in use, ${stats.waiting} request(s) ` +
351
+ `waiting for a socket, ${this.idleClosedSinceReport} download stream(s) closed for lack of progress since the ` +
352
+ 'last report. Every S3 request waits until a socket is free. Raise s3.maxSockets if this is genuine load; ' +
353
+ 'a growing count without load points to download streams that are not consumed or destroyed — deliver files ' +
354
+ 'with pipeFileToResponse().',
355
+ );
356
+ this.idleClosedSinceReport = 0;
357
+ }
358
+
209
359
  /**
210
360
  * Check at boot that the configured buckets are reachable.
211
361
  *
@@ -538,11 +688,37 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
538
688
  * Get an object stream (plus metadata) from the main bucket.
539
689
  * Throws the SDK's NoSuchKey error when the object does not exist.
540
690
  */
541
- async getObject(key: string): Promise<{ body: Readable; contentLength?: number; contentType?: string }> {
691
+ async getObject(
692
+ key: string,
693
+ options?: {
694
+ abortSignal?: AbortSignal;
695
+ /**
696
+ * Idle time of the returned stream for THIS call (default `s3.downloadIdleTimeoutMs`). `false` returns the body
697
+ * unguarded — only for a caller that reads the stream late on purpose (an archive that pipes each entry when
698
+ * its turn comes) AND is certain to read it to the end or destroy it; such a body holds its socket until then.
699
+ */
700
+ idleTimeoutMs?: false | number;
701
+ },
702
+ ): Promise<{ body: Readable; contentLength?: number; contentType?: string }> {
542
703
  const { client, config, sdk } = this.requireInit();
543
- const result = await client.send(new sdk.GetObjectCommand({ Bucket: config.bucket, Key: key }));
704
+ // `abortSignal`: a caller whose client has gone aborts the request, also while it still waits for a socket —
705
+ // otherwise it stays queued and takes a socket and a body later, for nobody (see `IS3Config.maxSockets`)
706
+ const idleMs = options?.idleTimeoutMs;
707
+ const result = await client.send(
708
+ new sdk.GetObjectCommand({ Bucket: config.bucket, Key: key }),
709
+ options?.abortSignal ? { abortSignal: options.abortSignal } : undefined,
710
+ );
544
711
  return {
545
- body: result.Body as Readable,
712
+ // Guarded: a body nobody reads releases its socket after `s3.downloadIdleTimeoutMs` instead of holding it
713
+ // for the life of the process. Destroying the returned stream releases it at once.
714
+ // `idleTimeoutMs: false` keeps the guard WITHOUT its timer: an unread body is destroyed with an error by the
715
+ // SDK's socket timeout (`s3.socketTimeoutMs`), which ends the process when nothing listens on it
716
+ body: guardIdleStream(result.Body as Readable, {
717
+ idleMs: idleMs === false ? false : (idleMs ?? config.downloadIdleTimeoutMs),
718
+ onIdle: () => {
719
+ this.idleClosedSinceReport++;
720
+ },
721
+ }),
546
722
  contentLength: result.ContentLength,
547
723
  contentType: result.ContentType,
548
724
  };
@@ -634,8 +810,15 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
634
810
  * Destroy the shared client
635
811
  */
636
812
  async onApplicationShutdown(): Promise<void> {
813
+ if (this.poolMonitor) {
814
+ clearInterval(this.poolMonitor);
815
+ this.poolMonitor = undefined;
816
+ }
637
817
  this.client?.destroy();
638
818
  this.client = undefined;
819
+ this.agents?.http.destroy();
820
+ this.agents?.https.destroy();
821
+ this.agents = undefined;
639
822
  }
640
823
 
641
824
  /**
@@ -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 (11.46.3+): `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-11463).
49
+
44
50
  ## Storage drivers
45
51
 
46
52
  Three equivalent options. They differ only in where the bytes end up:
@@ -475,6 +481,48 @@ server-side even though the client answer stays deliberately generic.
475
481
  To change the status, the body or the logging, override the `protected pipeFileToResponse()` method
476
482
  on the controller rather than the exported function of the same name.
477
483
 
484
+ | Situation (11.46.3+) | Status | Body / headers |
485
+ | ------------------------------------------------------------------------------------------- | ------ | ------------------------------------------------------------------------------ |
486
+ | `If-None-Match` names the file's weak `ETag` (`W/"<id>"`), after the rights check | `304` | No body; the store is not read |
487
+ | The store hands out no connection within 3 attempts of `s3.connectionTimeoutMs` (pool busy) | `503` | `Retry-After: 5`; the store is busy, not broken |
488
+ | The client left before the stream was handed over | — | Nothing is sent; the stream is destroyed at once, a pending S3 request aborted |
489
+
490
+ ### Delivering a file from your own route (11.46.3)
491
+
492
+ **Use `pipeFileToResponse(stream, res)` for every download route of your own — never `stream.pipe(res)`.**
493
+ When the client aborts, `pipe()` only unpipes: the source stays open and keeps what it holds — for S3 a socket of the
494
+ client's pool. Enough aborted downloads and the pool is full; every S3 request then waits forever while the health
495
+ check stays green. A production outage had exactly this cause. `pipeFileToResponse()` destroys the source when the
496
+ 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
497
+ had already gone before the call — and answers a store error before the first byte with `404`.
498
+
499
+ ```typescript
500
+ import { downloadAbortSignal, pipeFileToResponse } from '@lenne.tech/nest-server';
501
+
502
+ const stream = await this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser });
503
+ return pipeFileToResponse(stream, res);
504
+ ```
505
+
506
+ Layers below it, each effective on its own:
507
+
508
+ - Every stream from `CoreFileService.getFileStream()` / `getFileStreamByName()` and `CoreS3Service.getObject()` closes
509
+ itself after `downloadIdleTimeoutMs` (30 s) without read progress. A slow reader that keeps reading is never cut off.
510
+ **Read a stream right after obtaining it**: code that collects streams and reads them later (a ZIP export appending
511
+ every file first) breaks — the closed stream ends without `end`. Open each stream right before it is read, or opt out
512
+ for that call with `downloadIdleTimeoutMs: false` (`getObject(key, { idleTimeoutMs: false })`) when the code is
513
+ certain to read it to the end or destroy it.
514
+ - The S3 client runs with its own agents: `s3.maxSockets` (200 instead of the SDK's 50), `s3.connectionTimeoutMs`
515
+ (15 s per attempt — the bound for waiting for a socket, too; the SDK makes 3 attempts, so a download that gets no
516
+ socket answers `503` after about 46 s, below the common 60 s proxy timeout), `s3.socketTimeoutMs` (120 s inactivity
517
+ backstop).
518
+ - An exhausted pool is logged as an ERROR once per minute with numbers (`S3 socket pool exhausted: …`) — alert on it.
519
+ Downloads closed for lack of progress are one WARN line per minute, never an ERROR per download.
520
+ `CoreS3Service.getSocketPoolStats()` gives the same numbers to a project's monitoring. It is deliberately not a
521
+ health-check failure: a short S3 disturbance would take the whole API out of the load balancer.
522
+ - Pass `abortSignal` (aborted when the response closes) so an S3 request whose client has gone is dropped while it
523
+ waits for a socket instead of taking one later. The framework's routes do this.
524
+ - `s3.presignedDownloads` moves the bytes off the API entirely (a `302` to S3) — consider it for public files.
525
+
478
526
  ### Upload filtering
479
527
 
480
528
  Upload endpoints are project-specific, but the filter they install comes from the framework