@lenne.tech/nest-server 12.8.8 → 12.9.0

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 (47) hide show
  1. package/.claude/rules/architecture.md +1 -1
  2. package/.claude/rules/configurable-features.md +1 -0
  3. package/.claude/rules/testing.md +4 -4
  4. package/CLAUDE.md +2 -2
  5. package/FRAMEWORK-API.md +7 -1
  6. package/bin/check-unified-field-types.js +15 -3
  7. package/dist/core/common/decorators/unified-field.decorator.js +10 -11
  8. package/dist/core/common/decorators/unified-field.decorator.js.map +1 -1
  9. package/dist/core/common/helpers/idle-stream.helper.d.ts +14 -0
  10. package/dist/core/common/helpers/idle-stream.helper.js +94 -0
  11. package/dist/core/common/helpers/idle-stream.helper.js.map +1 -0
  12. package/dist/core/common/interfaces/server-options.interface.d.ts +6 -0
  13. package/dist/core/common/services/core-s3.service.d.ts +27 -1
  14. package/dist/core/common/services/core-s3.service.js +89 -3
  15. package/dist/core/common/services/core-s3.service.js.map +1 -1
  16. package/dist/core/modules/file/core-file.controller.d.ts +16 -0
  17. package/dist/core/modules/file/core-file.controller.js +215 -8
  18. package/dist/core/modules/file/core-file.controller.js.map +1 -1
  19. package/dist/core/modules/file/core-file.service.d.ts +5 -0
  20. package/dist/core/modules/file/core-file.service.js +17 -7
  21. package/dist/core/modules/file/core-file.service.js.map +1 -1
  22. package/dist/core/modules/file/interfaces/file-service-options.interface.d.ts +2 -0
  23. package/dist/core/modules/file/s3-file.helper.d.ts +4 -1
  24. package/dist/core/modules/file/s3-file.helper.js +2 -2
  25. package/dist/core/modules/file/s3-file.helper.js.map +1 -1
  26. package/dist/index.d.ts +1 -0
  27. package/dist/index.js +1 -0
  28. package/dist/index.js.map +1 -1
  29. package/dist/main.js +1 -3
  30. package/dist/main.js.map +1 -1
  31. package/docs/REQUEST-LIFECYCLE.md +6 -6
  32. package/migration-guides/12.8.6-to-12.8.7.md +3 -3
  33. package/migration-guides/12.8.8-to-12.8.9.md +149 -0
  34. package/migration-guides/12.8.x-to-12.9.x.md +105 -0
  35. package/package.json +4 -4
  36. package/src/core/common/decorators/unified-field.decorator.ts +20 -22
  37. package/src/core/common/helpers/idle-stream.helper.ts +192 -0
  38. package/src/core/common/interfaces/server-options.interface.ts +78 -0
  39. package/src/core/common/services/core-s3.service.ts +186 -3
  40. package/src/core/modules/file/INTEGRATION-CHECKLIST.md +15 -14
  41. package/src/core/modules/file/README.md +48 -0
  42. package/src/core/modules/file/core-file.controller.ts +356 -10
  43. package/src/core/modules/file/core-file.service.ts +46 -7
  44. package/src/core/modules/file/interfaces/file-service-options.interface.ts +22 -0
  45. package/src/core/modules/file/s3-file.helper.ts +6 -2
  46. package/src/index.ts +1 -0
  47. package/src/main.ts +3 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "12.8.8",
3
+ "version": "12.9.0",
4
4
  "type": "module",
5
5
  "description": "Server framework in TypeScript on top of NestJS: GraphQL and REST APIs on MongoDB, PostgreSQL, MySQL or MariaDB, with authentication, field-level permissions, multi-tenancy, offline sync and an AI assistant.",
6
6
  "keywords": [
@@ -231,8 +231,8 @@
231
231
  "@aws-sdk/client-s3": "3.1165.0",
232
232
  "@aws-sdk/lib-storage": "3.1165.0",
233
233
  "@aws-sdk/s3-request-presigner": "3.1165.0",
234
- "@better-auth/core": "1.7.18",
235
- "@better-auth/passkey": "1.7.18",
234
+ "@better-auth/core": "1.7.19",
235
+ "@better-auth/passkey": "1.7.19",
236
236
  "@compodoc/compodoc": "2.0.0",
237
237
  "@nestjs/cli": "12.0.12",
238
238
  "@nestjs/mongoose": "12.0.1",
@@ -251,7 +251,7 @@
251
251
  "@types/passport": "1.0.17",
252
252
  "@types/pg": "8.23.1",
253
253
  "@vitest/coverage-v8": "5.1.0",
254
- "better-auth": "1.7.18",
254
+ "better-auth": "1.7.19",
255
255
  "bullmq": "6.7.2",
256
256
  "cross-env": "10.1.0",
257
257
  "drizzle-orm": "1.0.0-rc.5",
@@ -299,32 +299,30 @@ function designTypeOf(metadataType: unknown): unknown {
299
299
  return metadataType;
300
300
  }
301
301
 
302
- /** Fields already warned about by {@link warnIfAmbiguousMetadataType}: one line per field, not per decoration. */
303
- const ambiguousTypeWarned = new Set<string>();
304
-
305
302
  /**
306
- * Warn when a field without `type` / `isAny` / `enum` takes its type from compiler metadata that is only `Object`. The
307
- * SWC loader of the dev start writes `design:type` syntactically, file by file: a union with `null` / `undefined` (also
308
- * with an enum), a type alias or an interface become `Object` there, where the tsc build writes `Number`, `String` or
309
- * the class — a plain enum is read like tsc does, see {@link designTypeOf}. The dev API then validates the field as a
310
- * nested object while the deployed one does not — `max: 5` refused in development, accepted in production.
303
+ * Refuse a field without `type` / `isAny` / `enum` whose type would come from compiler metadata that is only `Object`
304
+ * (12.9.0; 12.8.7 warned). The SWC loader of the dev start writes `design:type` syntactically, file by file: a union
305
+ * with `null` / `undefined` (also with an enum), a type alias or an interface become `Object` there, where the tsc build
306
+ * writes `Number`, `String` or the class — a plain enum is read like tsc does, see {@link designTypeOf}. Taken as is,
307
+ * the dev API validated such a field as a nested object while the deployed one did not — `max: 5` refused in
308
+ * development, accepted in production — and a field tsc also writes as `Object` (`any`, `Record`, an interface) was
309
+ * validated as an object nobody declared. Like an array field without `type`, the field has to say what it holds.
311
310
  *
312
311
  * The package bin `nest-check-unified-field-types --fix` (`check:unified-field-types` in nest-server-starter
313
- * projects; vendor mode: `node ./bin/check-unified-field-types.js --fix`) writes the declared type into every such
314
- * field; a later release refuses them at boot.
312
+ * projects; vendor mode: `node ./bin/check-unified-field-types.js --fix`) writes the declared type into every field it
313
+ * can resolve and names the rest.
315
314
  */
316
- function warnIfAmbiguousMetadataType(metadataType: unknown, propertyHint: string): void {
315
+ function assertExplicitTypeForObjectMetadata(metadataType: unknown, propertyHint: string): void {
317
316
  const ambiguous = metadataType === Object || (typeof metadataType === 'object' && metadataType !== null);
318
- if (!ambiguous || ambiguousTypeWarned.has(propertyHint)) return;
319
- ambiguousTypeWarned.add(propertyHint);
320
- // eslint-disable-next-line no-console
321
- console.warn(
322
- `[@UnifiedField] "${propertyHint}" has no explicit type, and the compiler metadata says only "Object". The SWC ` +
323
- 'dev start and the tsc build can disagree here (a union with null/undefined, a type alias, an interface), so ' +
324
- 'the dev API may validate it as a nested object. Declare it: type: () => Number / String / Boolean / ' +
325
- 'Date / <Class>, type: () => Object for a free-form object, or isAny: true. `nest-check-unified-field-types ' +
326
- '--fix` (vendor mode: `node ./bin/check-unified-field-types.js --fix`) writes the declared type; a later ' +
327
- 'release refuses such a field at boot.',
317
+ if (!ambiguous) return;
318
+ throw new Error(
319
+ `[@UnifiedField] "${propertyHint}" has no explicit type, and the compiler metadata says only "Object", which ` +
320
+ 'names no type — and the SWC dev start and the tsc build can write different ones here (a union with ' +
321
+ 'null/undefined, a type alias, an interface, a mixed enum, a class not yet defined because of an import ' +
322
+ 'cycle). Declare it: type: () => Number / String / ' +
323
+ 'Boolean / Date / <Class>, type: () => Object for a free-form object, or isAny: true. ' +
324
+ '`nest-check-unified-field-types --fix` (vendor mode: `node ./bin/check-unified-field-types.js --fix`) writes ' +
325
+ 'the declared type where it can resolve one and names the rest. See migration-guides/12.8.x-to-12.9.x.md.',
328
326
  );
329
327
  }
330
328
 
@@ -421,7 +419,7 @@ export function UnifiedField(opts: UnifiedFieldOptions = {}): PropertyDecorator
421
419
  }
422
420
 
423
421
  if (!userType && !opts.isAny && !normalizedEnum) {
424
- warnIfAmbiguousMetadataType(metadataType, `${target.constructor?.name || '?'}.${key}`);
422
+ assertExplicitTypeForObjectMetadata(metadataType, `${target.constructor?.name || '?'}.${key}`);
425
423
  }
426
424
 
427
425
  const resolvedTypeFn = (): any => {
@@ -0,0 +1,192 @@
1
+ import { PassThrough } from 'stream';
2
+
3
+ import type { Readable } from 'stream';
4
+
5
+ /**
6
+ * Marks a stream returned by {@link guardIdleStream}, so a second guard on the same stream is a no-op.
7
+ * A module-private symbol: a property name could arrive on an object from elsewhere, a symbol cannot.
8
+ */
9
+ const IDLE_GUARDED = Symbol('lt.idleGuardedStream');
10
+
11
+ /**
12
+ * Default idle time after which a download stream that makes no read progress is destroyed: 30 s.
13
+ *
14
+ * Long enough for a slow client: a reader that receives any bytes at all resets the timer, so only a
15
+ * transfer that has made NO progress for this long ends. Short enough that a stream nobody reads
16
+ * releases what it holds (an S3 socket, a file handle, a GridFS cursor) within half a minute instead
17
+ * of never.
18
+ */
19
+ export const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 30_000;
20
+
21
+ /**
22
+ * Longest delay a Node timer accepts (2^31 - 1 ms, about 24.8 days). A larger delay is clamped by Node to 1 ms — an
23
+ * idle time configured as "practically forever" would otherwise close every download within a millisecond.
24
+ */
25
+ export const MAX_TIMER_DELAY_MS = 2_147_483_647;
26
+
27
+ /**
28
+ * Error a guarded stream is destroyed with when it made no read progress for the configured time.
29
+ * Only delivered when someone listens for `error` on the guarded stream (see {@link guardIdleStream}).
30
+ */
31
+ export class StreamIdleTimeoutError extends Error {
32
+ readonly code = 'LT_STREAM_IDLE_TIMEOUT';
33
+
34
+ constructor(readonly idleMs: number) {
35
+ super(`Download stream made no read progress for ${idleMs} ms and was closed to release its resources`);
36
+ this.name = 'StreamIdleTimeoutError';
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Options of {@link guardIdleStream}.
42
+ */
43
+ export interface GuardIdleStreamOptions {
44
+ /**
45
+ * Idle time in milliseconds; a non-positive or non-finite value falls back to {@link DEFAULT_STREAM_IDLE_TIMEOUT_MS},
46
+ * a value above {@link MAX_TIMER_DELAY_MS} is capped there. `false` keeps every other part of the guard (error
47
+ * handling, release on close) but starts no idle timer — for a caller that reads late on purpose.
48
+ */
49
+ idleMs?: false | number;
50
+ /** Called once when the guard closes the stream for lack of progress (logging, metrics). */
51
+ onIdle?: (idleMs: number) => void;
52
+ }
53
+
54
+ /**
55
+ * The stream a guard returns: a `PassThrough` that reports every read of its consumer.
56
+ *
57
+ * Progress has to be measured on the CONSUMER side. The source only delivers when the buffers between it and the
58
+ * reader run low, and those buffers hold several chunks: a slow reader working through them makes progress for
59
+ * a while without the source delivering anything (measured: four 16 KB chunks over 125 ms). Judged by the source
60
+ * alone, such a reader was cut off. `read()` is what every consumer calls — `pipe()` and `'data'` listeners through
61
+ * the stream's flow, async iteration directly — and nothing calls it while nobody reads, which is exactly the
62
+ * stream that must be released.
63
+ */
64
+ class IdleGuardStream extends PassThrough {
65
+ onConsumerRead?: () => void;
66
+
67
+ override read(size?: number): any {
68
+ this.onConsumerRead?.();
69
+ return super.read(size);
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Whether the stream is already guarded by {@link guardIdleStream}.
75
+ */
76
+ export function isIdleGuardedStream(stream: unknown): boolean {
77
+ return !!stream && (stream as Record<symbol, unknown>)[IDLE_GUARDED] === true;
78
+ }
79
+
80
+ /**
81
+ * Wrap a download stream so it releases its source when nobody reads it any more.
82
+ *
83
+ * WHY THIS EXISTS: a download source holds something finite while it is open — an S3 body holds a socket
84
+ * of the SDK's pool, a file stream a file handle, a GridFS stream a server-side cursor. A caller that
85
+ * pipes it with a bare `stream.pipe(res)` stops reading when the client aborts: `pipe()` only unpipes,
86
+ * nothing destroys the source, and it stays paused for the life of the process. For S3 that is a socket
87
+ * taken from a pool of a fixed size; enough aborted downloads and every further S3 request waits forever
88
+ * (measured in production: 50 aborts filled the SDK's default pool, followed by a heap OOM hours later).
89
+ * The same happens to a stream that is obtained and then simply dropped.
90
+ *
91
+ * The guard returns a `PassThrough` the source is piped into. Every read of the consumer, and every chunk the
92
+ * source delivers, resets a timer; nothing resets it while nobody reads (back-pressure pauses the source). When
93
+ * the timer runs out — no read progress for `idleMs` — the source AND the returned stream are destroyed,
94
+ * which releases the socket, handle or cursor. A slow reader that keeps reading is never cut off; only a
95
+ * transfer without ANY progress for the whole period ends.
96
+ *
97
+ * Also: destroying the returned stream (as `pipeFileToResponse()` does when the response closes) destroys
98
+ * the source at once, and an error of the source is forwarded — never left on a stream without a listener,
99
+ * which Node turns into an uncaught exception that ends the process. The idle error itself is only emitted
100
+ * when someone listens for `error` on the returned stream; a stream nobody holds any more is closed
101
+ * silently for the same reason.
102
+ *
103
+ * Guarding an already guarded stream returns it unchanged.
104
+ */
105
+ export function guardIdleStream(source: Readable, options: GuardIdleStreamOptions = {}): Readable {
106
+ if (isIdleGuardedStream(source)) {
107
+ return source;
108
+ }
109
+ const idleMs =
110
+ options.idleMs === false
111
+ ? undefined
112
+ : typeof options.idleMs === 'number' && Number.isFinite(options.idleMs) && options.idleMs > 0
113
+ ? Math.min(options.idleMs, MAX_TIMER_DELAY_MS)
114
+ : DEFAULT_STREAM_IDLE_TIMEOUT_MS;
115
+
116
+ const guarded = new IdleGuardStream();
117
+ Object.defineProperty(guarded, IDLE_GUARDED, { enumerable: false, value: true });
118
+
119
+ let timer: NodeJS.Timeout | undefined;
120
+ const stopTimer = () => {
121
+ if (timer) {
122
+ clearTimeout(timer);
123
+ timer = undefined;
124
+ }
125
+ };
126
+
127
+ // `source.pipe(guarded)` registers an `error` listener of its own on `guarded`, which rethrows when it is the
128
+ // only one. Only listeners beyond it belong to a consumer — counting it made an unread stream's idle error
129
+ // an uncaught exception, the very crash this function exists to prevent.
130
+ let pipeErrorListeners = 0;
131
+ const hasConsumerErrorListener = () => guarded.listenerCount('error') > pipeErrorListeners;
132
+
133
+ // An error is only handed on to a consumer's listener; without one, emitting it would end the process
134
+ const destroyGuarded = (error?: Error) => {
135
+ if (guarded.destroyed) {
136
+ return;
137
+ }
138
+ guarded.destroy(error && hasConsumerErrorListener() ? error : undefined);
139
+ };
140
+ const destroySource = () => {
141
+ if (!source.destroyed) {
142
+ source.destroy();
143
+ }
144
+ };
145
+
146
+ const onIdle = () => {
147
+ timer = undefined;
148
+ if (source.readableEnded || guarded.destroyed) {
149
+ return;
150
+ }
151
+ try {
152
+ options.onIdle?.(idleMs as number);
153
+ } catch {
154
+ // A failing callback must not keep the resources alive
155
+ }
156
+ destroySource();
157
+ destroyGuarded(new StreamIdleTimeoutError(idleMs as number));
158
+ };
159
+ // Without an idle time (`idleMs: false`) the rest of the guard still applies: the source keeps an error listener —
160
+ // an unread S3 body is destroyed WITH an error by the SDK's socket timeout, which ends the process without one
161
+ if (idleMs !== undefined) {
162
+ timer = setTimeout(onIdle, idleMs);
163
+ // The timer must never keep a process alive on its own (a test run, a graceful shutdown)
164
+ timer.unref?.();
165
+ }
166
+
167
+ // Progress: the consumer reads (see `IdleGuardStream`), or the source delivers
168
+ guarded.onConsumerRead = () => timer?.refresh();
169
+ source.on('data', () => timer?.refresh());
170
+ source.once('end', stopTimer);
171
+ source.once('close', stopTimer);
172
+ source.on('error', (error: Error) => {
173
+ stopTimer();
174
+ destroyGuarded(error);
175
+ });
176
+ guarded.once('close', () => {
177
+ stopTimer();
178
+ // The consumer is gone (response closed, stream destroyed): release the source now, not at the timeout
179
+ if (!source.readableEnded) {
180
+ destroySource();
181
+ }
182
+ });
183
+
184
+ const before = guarded.listenerCount('error');
185
+ source.pipe(guarded);
186
+ pipeErrorListeners = guarded.listenerCount('error') - before;
187
+ // `pipe()` removes its listener when the source ends; from then on every listener is a consumer's
188
+ source.once('end', () => {
189
+ pipeErrorListeners = 0;
190
+ });
191
+ return guarded;
192
+ }
@@ -1283,6 +1283,33 @@ export interface IFileConfig {
1283
1283
  */
1284
1284
  deleteRoles?: string[];
1285
1285
 
1286
+ /**
1287
+ * Browser caching of file downloads (`GET /files/id/:id`, `GET /files/:filename`).
1288
+ *
1289
+ * - `'none'`: `Cache-Control: private, no-store` — nothing is kept, every view reads the store again.
1290
+ * - `'revalidate'`: `Cache-Control: private, no-cache` plus `ETag` — the browser keeps the file but asks
1291
+ * again on every use; the request runs the full role and rights check and is answered `304 Not Modified`
1292
+ * without reading the store. Recommended for image-heavy apps: it removes most store reads (S3 sockets)
1293
+ * while every view stays authorized. Shared caches stay excluded (`private`). Note that the browser then
1294
+ * stores authorized file content on the device.
1295
+ *
1296
+ * Both modes send a weak `ETag` (`W/"<file id>"`) and answer a matching `If-None-Match` with 304.
1297
+ * @default 'none'
1298
+ * @since 12.8.9
1299
+ */
1300
+ downloadCaching?: 'none' | 'revalidate';
1301
+
1302
+ /**
1303
+ * Time in milliseconds a download stream from `CoreFileService.getFileStream()` / `getFileStreamByName()` may
1304
+ * go without ANY read progress before it is destroyed, releasing the file handle (filesystem) or the cursor
1305
+ * (GridFS) it holds. Protects against a stream piped with a bare `stream.pipe(res)` to a client that aborts,
1306
+ * and a stream obtained and never read. A slow reader that keeps reading is never cut off. S3 streams use
1307
+ * `s3.downloadIdleTimeoutMs`. A non-positive or non-numeric value uses the default.
1308
+ * @default 30000
1309
+ * @since 12.8.9
1310
+ */
1311
+ downloadIdleTimeoutMs?: number;
1312
+
1286
1313
  /**
1287
1314
  * Roles allowed to DOWNLOAD files and read file info
1288
1315
  * (`GET /files/id/:id`, `GET /files/:filename`, `getFileInfo` query).
@@ -3968,6 +3995,34 @@ export interface IS3Config {
3968
3995
  */
3969
3996
  bucket: string;
3970
3997
 
3998
+ /**
3999
+ * Upper bound in milliseconds for ONE attempt of a request to get a socket: the time it WAITS for a free socket of
4000
+ * the pool (see `maxSockets`) plus the time to connect. The SDK starts this timer when the request is created, not
4001
+ * when it gets a socket, so it bounds the queue wait as well — which keeps the queue from growing without end under
4002
+ * overload (each waiting request holds memory). The SDK retries a timed-out attempt (3 attempts in all), so a
4003
+ * download that cannot get a socket is answered `503` with `Retry-After` after up to about 3 × this value plus a
4004
+ * short backoff — with the default about 46 s, below the common 60 s read timeout of reverse proxies. Keep
4005
+ * 3 × this value below your proxy's read timeout, and well above normal queue waits: a short value fails healthy
4006
+ * downloads under load. A non-positive or non-numeric value uses the default.
4007
+ * @default 15000
4008
+ * @since 12.8.9
4009
+ */
4010
+ connectionTimeoutMs?: number;
4011
+
4012
+ /**
4013
+ * Time in milliseconds a download stream from S3 (`CoreS3Service.getObject()`, and with it
4014
+ * `CoreFileService.getFileStream()` for S3-stored files) may go without ANY read progress before it is
4015
+ * destroyed and its socket returns to the pool.
4016
+ *
4017
+ * A stream that is obtained and never read, or piped with a bare `stream.pipe(res)` to a client that
4018
+ * aborts, otherwise holds its socket for the life of the process — and the pool is finite (see
4019
+ * `maxSockets`). A slow reader that keeps reading is never cut off: every chunk resets the timer.
4020
+ * A non-positive or non-numeric value uses the default; the guard cannot be switched off.
4021
+ * @default 30000
4022
+ * @since 12.8.9
4023
+ */
4024
+ downloadIdleTimeoutMs?: number;
4025
+
3971
4026
  /**
3972
4027
  * Whether S3 is enabled.
3973
4028
  * Presence of the config object implies true.
@@ -3988,6 +4043,19 @@ export interface IS3Config {
3988
4043
  */
3989
4044
  forcePathStyle?: boolean;
3990
4045
 
4046
+ /**
4047
+ * Maximum number of concurrent sockets to the S3 endpoint (per protocol). Requests beyond it wait for a
4048
+ * free socket — and are reported as an error in the log while they do (pool saturation).
4049
+ *
4050
+ * The AWS SDK's own default is 50, which a single process reaches with 50 simultaneous downloads; every
4051
+ * stream holds its socket until it is read to the end or destroyed. 200 lets that many transfers run at
4052
+ * once — each costs one file descriptor and a few KB — while staying far below what S3 and S3-compatible
4053
+ * stores accept per client. A non-positive or non-numeric value uses the default.
4054
+ * @default 200
4055
+ * @since 12.8.9
4056
+ */
4057
+ maxSockets?: number;
4058
+
3991
4059
  /**
3992
4060
  * Serve downloads as presigned URL redirects instead of streaming
3993
4061
  * through the API (offloads traffic from the server).
@@ -4039,6 +4107,16 @@ export interface IS3Config {
4039
4107
  */
4040
4108
  secretAccessKey?: string;
4041
4109
 
4110
+ /**
4111
+ * Time in milliseconds a socket to S3 may stay without any traffic before the SDK destroys it — the
4112
+ * backstop under `downloadIdleTimeoutMs` for every request, uploads and copies included. Kept well above
4113
+ * the download idle time, because an S3-compatible store may take a while without sending a byte to
4114
+ * finish a large copy or multipart upload. A non-positive or non-numeric value uses the default.
4115
+ * @default 120000
4116
+ * @since 12.8.9
4117
+ */
4118
+ socketTimeoutMs?: number;
4119
+
4042
4120
  /**
4043
4121
  * Bucket used as staging area for resumable TUS uploads.
4044
4122
  * 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
  /**