@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
@@ -1262,6 +1262,33 @@ export interface IFileConfig {
1262
1262
  */
1263
1263
  deleteRoles?: string[];
1264
1264
 
1265
+ /**
1266
+ * Browser caching of file downloads (`GET /files/id/:id`, `GET /files/:filename`).
1267
+ *
1268
+ * - `'none'`: `Cache-Control: private, no-store` — nothing is kept, every view reads the store again.
1269
+ * - `'revalidate'`: `Cache-Control: private, no-cache` plus `ETag` — the browser keeps the file but asks
1270
+ * again on every use; the request runs the full role and rights check and is answered `304 Not Modified`
1271
+ * without reading the store. Recommended for image-heavy apps: it removes most store reads (S3 sockets)
1272
+ * while every view stays authorized. Shared caches stay excluded (`private`). Note that the browser then
1273
+ * stores authorized file content on the device.
1274
+ *
1275
+ * Both modes send a weak `ETag` (`W/"<file id>"`) and answer a matching `If-None-Match` with 304.
1276
+ * @default 'none'
1277
+ * @since 12.6.10
1278
+ */
1279
+ downloadCaching?: 'none' | 'revalidate';
1280
+
1281
+ /**
1282
+ * Time in milliseconds a download stream from `CoreFileService.getFileStream()` / `getFileStreamByName()` may
1283
+ * go without ANY read progress before it is destroyed, releasing the file handle (filesystem) or the cursor
1284
+ * (GridFS) it holds. Protects against a stream piped with a bare `stream.pipe(res)` to a client that aborts,
1285
+ * and a stream obtained and never read. A slow reader that keeps reading is never cut off. S3 streams use
1286
+ * `s3.downloadIdleTimeoutMs`. A non-positive or non-numeric value uses the default.
1287
+ * @default 30000
1288
+ * @since 12.6.10
1289
+ */
1290
+ downloadIdleTimeoutMs?: number;
1291
+
1265
1292
  /**
1266
1293
  * Roles allowed to DOWNLOAD files and read file info
1267
1294
  * (`GET /files/id/:id`, `GET /files/:filename`, `getFileInfo` query).
@@ -3871,6 +3898,34 @@ export interface IS3Config {
3871
3898
  */
3872
3899
  bucket: string;
3873
3900
 
3901
+ /**
3902
+ * Upper bound in milliseconds for ONE attempt of a request to get a socket: the time it WAITS for a free socket of
3903
+ * the pool (see `maxSockets`) plus the time to connect. The SDK starts this timer when the request is created, not
3904
+ * when it gets a socket, so it bounds the queue wait as well — which keeps the queue from growing without end under
3905
+ * overload (each waiting request holds memory). The SDK retries a timed-out attempt (3 attempts in all), so a
3906
+ * download that cannot get a socket is answered `503` with `Retry-After` after up to about 3 × this value plus a
3907
+ * short backoff — with the default about 46 s, below the common 60 s read timeout of reverse proxies. Keep
3908
+ * 3 × this value below your proxy's read timeout, and well above normal queue waits: a short value fails healthy
3909
+ * downloads under load. A non-positive or non-numeric value uses the default.
3910
+ * @default 15000
3911
+ * @since 12.6.10
3912
+ */
3913
+ connectionTimeoutMs?: number;
3914
+
3915
+ /**
3916
+ * Time in milliseconds a download stream from S3 (`CoreS3Service.getObject()`, and with it
3917
+ * `CoreFileService.getFileStream()` for S3-stored files) may go without ANY read progress before it is
3918
+ * destroyed and its socket returns to the pool.
3919
+ *
3920
+ * A stream that is obtained and never read, or piped with a bare `stream.pipe(res)` to a client that
3921
+ * aborts, otherwise holds its socket for the life of the process — and the pool is finite (see
3922
+ * `maxSockets`). A slow reader that keeps reading is never cut off: every chunk resets the timer.
3923
+ * A non-positive or non-numeric value uses the default; the guard cannot be switched off.
3924
+ * @default 30000
3925
+ * @since 12.6.10
3926
+ */
3927
+ downloadIdleTimeoutMs?: number;
3928
+
3874
3929
  /**
3875
3930
  * Whether S3 is enabled.
3876
3931
  * Presence of the config object implies true.
@@ -3891,6 +3946,19 @@ export interface IS3Config {
3891
3946
  */
3892
3947
  forcePathStyle?: boolean;
3893
3948
 
3949
+ /**
3950
+ * Maximum number of concurrent sockets to the S3 endpoint (per protocol). Requests beyond it wait for a
3951
+ * free socket — and are reported as an error in the log while they do (pool saturation).
3952
+ *
3953
+ * The AWS SDK's own default is 50, which a single process reaches with 50 simultaneous downloads; every
3954
+ * stream holds its socket until it is read to the end or destroyed. 200 lets that many transfers run at
3955
+ * once — each costs one file descriptor and a few KB — while staying far below what S3 and S3-compatible
3956
+ * stores accept per client. A non-positive or non-numeric value uses the default.
3957
+ * @default 200
3958
+ * @since 12.6.10
3959
+ */
3960
+ maxSockets?: number;
3961
+
3894
3962
  /**
3895
3963
  * Serve downloads as presigned URL redirects instead of streaming
3896
3964
  * through the API (offloads traffic from the server).
@@ -3942,6 +4010,16 @@ export interface IS3Config {
3942
4010
  */
3943
4011
  secretAccessKey?: string;
3944
4012
 
4013
+ /**
4014
+ * Time in milliseconds a socket to S3 may stay without any traffic before the SDK destroys it — the
4015
+ * backstop under `downloadIdleTimeoutMs` for every request, uploads and copies included. Kept well above
4016
+ * the download idle time, because an S3-compatible store may take a while without sending a byte to
4017
+ * finish a large copy or multipart upload. A non-positive or non-numeric value uses the default.
4018
+ * @default 120000
4019
+ * @since 12.6.10
4020
+ */
4021
+ socketTimeoutMs?: number;
4022
+
3945
4023
  /**
3946
4024
  * Bucket used as staging area for resumable TUS uploads.
3947
4025
  * Configure a lifecycle rule on this bucket to expire aborted uploads.
@@ -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
  /**
@@ -122,7 +122,9 @@ export class CoreAiController {
122
122
  @Body() input: CoreAiPromptInput,
123
123
  @Res() res: Response,
124
124
  ): Promise<void> {
125
- res.setHeader('Cache-Control', 'no-cache');
125
+ // `no-transform` keeps a `compression` middleware out of the stream: gzip would otherwise hold every event until
126
+ // the response ends (measured: events written at 0, 300 and 600 ms all arrived together at about 900 ms)
127
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
126
128
  res.setHeader('Connection', 'keep-alive');
127
129
  res.setHeader('Content-Type', 'text/event-stream');
128
130
  // Disable proxy-side response buffering (nginx and friends honour this); without
@@ -136,17 +138,23 @@ export class CoreAiController {
136
138
  // idle connection at 60 s, which the client then sees as a turn that silently
137
139
  // vanished. Comment frames are ignored by every SSE client and keep the
138
140
  // connection observably alive.
141
+ // A compressor that ignores `no-transform` still sends what was written once it is flushed (`compression` adds
142
+ // `flush()` to the response)
143
+ const send = (chunk: string) => {
144
+ res.write(chunk);
145
+ (res as Response & { flush?: () => void }).flush?.();
146
+ };
139
147
  const heartbeat = setInterval(() => {
140
- res.write(': keep-alive\n\n');
148
+ send(': keep-alive\n\n');
141
149
  }, 15_000);
142
150
  heartbeat.unref?.();
143
151
 
144
152
  try {
145
153
  for await (const event of this.aiService.promptStream(input, serviceOptions)) {
146
- res.write(`data: ${JSON.stringify(event)}\n\n`);
154
+ send(`data: ${JSON.stringify(event)}\n\n`);
147
155
  }
148
156
  } catch (err) {
149
- res.write(`data: ${JSON.stringify({ message: (err as Error).message, type: 'error' })}\n\n`);
157
+ send(`data: ${JSON.stringify({ message: (err as Error).message, type: 'error' })}\n\n`);
150
158
  } finally {
151
159
  clearInterval(heartbeat);
152
160
  res.end();
@@ -226,17 +226,19 @@ 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
+ | Own download route passing `downloadAbortSignal(res)` to `getFileStream()` without `openDownloadStream()` | Every client that leaves before S3 answers logs `ERROR [ExceptionsHandler] … AbortError` with a stack trace; a busy store answers 500 instead of 503 | Open the stream with `openDownloadStream(res, () => getFileStream(…))` and end the route with `return res` on `RESPONSE_GONE` (12.6.11+) |
243
+ | S3 packages in `devDependencies` | Production image cannot load S3 | Move them to `dependencies` — step 6 |
244
+ | 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,63 @@ 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
+ **Open the stream with `openDownloadStream(res, open)` (12.6.11+)**, the function the framework's own routes use. It
513
+ does not ask the store when the client has already gone, destroys a stream that arrives after the client left, and
514
+ answers `503` with `Retry-After` when the store hands out no connection in time. It also turns a store request that
515
+ failed BECAUSE the client left into `RESPONSE_GONE`: an S3 request aborted through `downloadAbortSignal(res)` rejects
516
+ with `AbortError`, and without it every aborted download is an ERROR with a stack trace in the log and a `500` sent
517
+ into a closed response — under the load the `S3 socket pool exhausted:` line has to stand out in.
518
+
519
+ ```typescript
520
+ import { downloadAbortSignal, openDownloadStream, pipeFileToResponse, RESPONSE_GONE } from '@lenne.tech/nest-server';
521
+
522
+ const stream = await openDownloadStream(res, () =>
523
+ this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser }),
524
+ );
525
+ if (stream === RESPONSE_GONE) {
526
+ return res; // nobody left to deliver to
527
+ }
528
+ if (!stream) {
529
+ throw new NotFoundException();
530
+ }
531
+ return pipeFileToResponse(stream, res);
532
+ ```
533
+
534
+ Layers below it, each effective on its own:
535
+
536
+ - Every stream from `CoreFileService.getFileStream()` / `getFileStreamByName()` and `CoreS3Service.getObject()` closes
537
+ itself after `downloadIdleTimeoutMs` (30 s) without read progress. A slow reader that keeps reading is never cut off.
538
+ **Read a stream right after obtaining it**: code that collects streams and reads them later (a ZIP export appending
539
+ every file first) breaks — the closed stream ends without `end`. Open each stream right before it is read, or opt out
540
+ for that call with `downloadIdleTimeoutMs: false` (`getObject(key, { idleTimeoutMs: false })`) when the code is
541
+ certain to read it to the end or destroy it.
542
+ - The S3 client runs with its own agents: `s3.maxSockets` (200 instead of the SDK's 50), `s3.connectionTimeoutMs`
543
+ (15 s per attempt — the bound for waiting for a socket, too; the SDK makes 3 attempts, so a download that gets no
544
+ socket answers `503` after about 46 s, below the common 60 s proxy timeout), `s3.socketTimeoutMs` (120 s inactivity
545
+ backstop).
546
+ - An exhausted pool is logged as an ERROR once per minute with numbers (`S3 socket pool exhausted: …`) — alert on it.
547
+ Downloads closed for lack of progress are one WARN line per minute, never an ERROR per download.
548
+ `CoreS3Service.getSocketPoolStats()` gives the same numbers to a project's monitoring. It is deliberately not a
549
+ health-check failure: a short S3 disturbance would take the whole API out of the load balancer.
550
+ - Pass `abortSignal` (aborted when the response closes) so an S3 request whose client has gone is dropped while it
551
+ waits for a socket instead of taking one later. The framework's routes do this.
552
+ - `s3.presignedDownloads` moves the bytes off the API entirely (a `302` to S3) — consider it for public files.
553
+
491
554
  ### Upload filtering
492
555
 
493
556
  Upload endpoints are project-specific, but the filter they install comes from the framework