@lenne.tech/nest-server 11.46.2 → 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 (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 +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.2-to-11.46.3.md +149 -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/plugins/mongoose-id.plugin.ts +9 -0
  35. package/src/core/common/services/core-s3.service.ts +186 -3
  36. package/src/core/modules/file/INTEGRATION-CHECKLIST.md +15 -14
  37. package/src/core/modules/file/README.md +48 -0
  38. package/src/core/modules/file/core-file.controller.ts +356 -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
@@ -42,7 +42,7 @@ The `CoreModule` is a dynamic module that bootstraps the entire framework:
42
42
  | **Mongoose Plugins** | Auto-registration of ID, password, audit, and role guard plugins |
43
43
  | **GraphQL Subscriptions** | WebSocket support with JWT/session authentication (cluster-wide when `redis` is configured — see the Subscriptions row under GraphQL Features) |
44
44
  | **Central Redis (optional)** | `CoreRedisService` — globally provided **and exported** by `CoreModule`, always present but **inert unless `redis` is configured** ("presence implies enabled"). Injected with `@Optional()`; every consumer keeps a process-local fallback. One service serves all features: shared client (`getClient()`), one cached subscriber (`getSubscriber()` — a subscribing client cannot run commands), dedicated connections (`createClient(label)`); all tracked and quit on shutdown. Keys are namespaced by the framework per key via `key(...)`, **not** through ioredis's own `keyPrefix` (that would collide with BullMQ's prefix). Requires the OPTIONAL peer `ioredis` — configured but missing **fails the boot**. Switches on: exact cross-replica rate limits, cron deduplication, `CoreRedisPubSub` as `PUB_SUB`, tenant-cache invalidation broadcast, Hub collector mirroring, MCP session registry |
45
- | **Central S3 (optional)** | `CoreS3Service` — globally provided **and exported** by `CoreModule`, inert unless `s3` is configured *and* names a `bucket` (a bucket-less block is ignored with a warning). Backs `file.storage: 's3'` and TUS staging (`tus.s3Staging`). Requires the OPTIONAL peers `@aws-sdk/client-s3` (+ `@aws-sdk/s3-request-presigner` for `presignedDownloads`) — configured but missing **fails the boot**. `@aws-sdk/lib-storage` (optional) uploads streams of unknown length in parts; without it they are buffered in memory, with one boot warning |
45
+ | **Central S3 (optional)** | `CoreS3Service` — globally provided **and exported** by `CoreModule`, inert unless `s3` is configured *and* names a `bucket` (a bucket-less block is ignored with a warning). Backs `file.storage: 's3'` and TUS staging (`tus.s3Staging`). Requires the OPTIONAL peers `@aws-sdk/client-s3` (+ `@aws-sdk/s3-request-presigner` for `presignedDownloads`) — configured but missing **fails the boot**. `@aws-sdk/lib-storage` (optional) uploads streams of unknown length in parts; without it they are buffered in memory, with one boot warning. Since 11.46.3 the client runs on its own agents (`s3.maxSockets` 200, `connectionTimeoutMs`, `socketTimeoutMs`), every body from `getObject()` is idle-guarded (`s3.downloadIdleTimeoutMs`, `guardIdleStream()`), and an exhausted socket pool is logged as an ERROR once per minute (`getSocketPoolStats()`) |
46
46
  | **Configuration System** | `config.env.ts` with ENV variables, `NEST_SERVER_CONFIG` JSON, `NSC__*` prefixes |
47
47
  | **Cookie Handling** | Enabled by default (`cookies: true`), configurable via `ICookiesConfig` with `exposeTokenInBody` option |
48
48
  | **Body Parser Limits** | `bodyParser.json.limit` / `bodyParser.urlencoded.limit` (default 100 kB each, body-parser's own). Applied in place to the parsers NestJS registers, so they hold under `Test.createTestingModule()` too. Every 413 is answered with `#LTNS_0304` plus size and limit, and logged with the route and the config key — see [0d. Body parsers](#0d-body-parsers) |
@@ -168,7 +168,7 @@ JWT-based authentication for existing projects:
168
168
  | Feature | Description |
169
169
  |---------|-------------|
170
170
  | **File Module** | Upload/download with MongoDB GridFS storage |
171
- | **REST Endpoints** | `GET /files/id/:id`, `GET /files/:filename` (core, gated by `file.downloadRoles`, default ADMIN); `POST /files/upload`, `DELETE /files/:id` (project-specific) |
171
+ | **REST Endpoints** | `GET /files/id/:id`, `GET /files/:filename` (core, gated by `file.downloadRoles`, default ADMIN); `POST /files/upload`, `DELETE /files/:id` (project-specific). Since 11.46.3 the download routes answer after the rights check: weak `ETag` + `If-None-Match` → `304` without a store read, `Cache-Control` per `file.downloadCaching`, `Content-Length`; the store request carries an abort signal (`downloadAbortSignal()`), delivery goes through `pipeFileToResponse()` (releases the source when the client goes), every stream is idle-guarded (`file.downloadIdleTimeoutMs`), and a store that gives no connection in time answers `503` + `Retry-After` |
172
172
  | **GraphQL Endpoints** | `getFileInfo` (`file.downloadRoles`), `uploadFile` / `uploadFiles` (`file.uploadRoles`), `deleteFile` (`file.deleteRoles`) — all default ADMIN |
173
173
  | **File access control** | Roles are the coarse filter; per-file rules go in `CoreFileService.checkRights()` using metadata written at upload time. Cover BOTH the `id` and the `filename` branch — the filename route authorizes on the by-name lookup alone when presigned S3 downloads are on, and `deleteFileByName()` always does. Working reference: `src/server/modules/file/file.service.ts` (with `file.downloadRoles: [S_USER]` in `src/config.env.ts`, so the rule is actually reached). Both file classes carry `@SkipTenantCheck()` — GridFS is not tenant-scoped |
174
174
  | **TUS Module** | Resumable uploads via tus.io protocol (creation, termination, expiration), gated by `tus.roles` (default `S_USER`); `OPTIONS` stays public for the CORS preflight. Records owner and, with `multiTenancy` only, the validated tenant at upload creation; a custom service plugs in via `TusModule.forRoot({ service })`. Configured by `TusModule.forRoot({ config })`, else the server config's `tus` key (11.42.9+). Switched-off `creation` / `termination` answer 501 (enforced by `CoreTusService`, not `@tus/server`); upload URLs follow the path the upload was created at. The response that completes an upload carries the stored file's ID as `X-File-Id` (11.42.13+, listed in `Access-Control-Expose-Headers`) — the last segment of the TUS URL is the upload id, not the file id |
@@ -0,0 +1,149 @@
1
+ # Migration Guide: 11.46.2 → 11.46.3
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None in the API. **Behaviour change:** a download stream that makes no read progress for 30 s is now closed — code that opens a stream and reads it much later (a ZIP export that appends every file first) must open it right before reading or opt out per call (§5). A download that cannot get a store connection answers `503` instead of waiting without end (§2) |
8
+ | **New Features** | `s3.maxSockets`, `s3.connectionTimeoutMs`, `s3.socketTimeoutMs`, `s3.downloadIdleTimeoutMs`, `file.downloadIdleTimeoutMs`, `file.downloadCaching`; `ETag`, `304` and `Content-Length` on downloads; `CoreS3Service.getSocketPoolStats()`; `guardIdleStream()`, `isResponseGone()`, `downloadAbortSignal()`; `abortSignal` and `downloadIdleTimeoutMs` in `FileServiceOptions`, `abortSignal` and `idleTimeoutMs` in `CoreS3Service.getObject()` |
9
+ | **Bugfixes** | S3 downloads could exhaust the S3 client's socket pool for good (§1) |
10
+ | **Migration Effort** | `pnpm run update`. A project with its OWN download route replaces `stream.pipe(res)` with `pipeFileToResponse(stream, res)` (§3). Check code that reads file streams late (§5). Alert on the new error log line (§4) |
11
+
12
+ ## Quick Migration
13
+
14
+ ```bash
15
+ pnpm add @lenne.tech/nest-server@11.46.3
16
+ pnpm run update # nest-server-starter based projects
17
+ grep -rn "\.pipe(res" src/ # own download routes: switch them to pipeFileToResponse() (§3)
18
+ pnpm run build
19
+ pnpm test
20
+ ```
21
+
22
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
23
+
24
+ ## 1. What happened
25
+
26
+ A project delivered S3 downloads with a bare `stream.pipe(res)`. When a client aborted, `pipe()` only unpiped: the S3
27
+ body was never read and never destroyed, and it kept one socket of the S3 client's pool. The pool had the SDK's default
28
+ size of 50 and no timeout that frees an unread body. After 50 aborted downloads every S3 request waited without end;
29
+ the health check stayed green because it does not touch S3, and the process ran out of heap hours later. Under load it
30
+ became an avalanche: slow downloads made waiting clients give up, and every one of them leaked the next socket.
31
+
32
+ 11.46.3 makes that impossible in several layers, each effective on its own:
33
+
34
+ | Layer | What it does |
35
+ |---|---|
36
+ | Idle guard on every download stream | `CoreS3Service.getObject()`, `CoreFileService.getFileStream()` and `getFileStreamByName()` return a stream that destroys its source after `downloadIdleTimeoutMs` (30 s) without read progress. A slow reader that keeps reading is never cut off |
37
+ | `pipeFileToResponse()` | destroys the source when the client goes — on the response's `close`, the request's `close` before its end or the socket's `end`/`close` (under an abort storm about one in six aborted downloads reported it only through the request or the socket) — and at once when the client had already gone (a client that gave up while waiting for a socket) |
38
+ | Download routes | pass an `abortSignal` to the store (an S3 request still waiting for a socket is dropped when the client leaves), skip the store when the client has gone, destroy a stream that arrives late |
39
+ | S3 client | own agents with `maxSockets` 200, `connectionTimeoutMs` 15 000, `socketTimeoutMs` 120 000 |
40
+ | Visibility | an exhausted pool is logged as an ERROR once per minute with numbers |
41
+
42
+ ## 2. Configuration
43
+
44
+ All optional; the defaults are what 11.46.3 runs with.
45
+
46
+ ```typescript
47
+ s3: {
48
+ bucket: 'files',
49
+ maxSockets: 200, // SDK default was 50
50
+ connectionTimeoutMs: 15_000, // per attempt: wait for a free socket + connect; 3 attempts → 503 after ~46 s
51
+ socketTimeoutMs: 120_000, // inactivity backstop for every S3 request
52
+ downloadIdleTimeoutMs: 30_000, // S3 download stream without read progress is closed
53
+ },
54
+ file: {
55
+ downloadIdleTimeoutMs: 30_000, // the same for GridFS and filesystem streams
56
+ downloadCaching: 'none', // or 'revalidate' (see below)
57
+ },
58
+ ```
59
+
60
+ Environment: `NSC__S3__MAX_SOCKETS`, `NSC__S3__CONNECTION_TIMEOUT_MS`, `NSC__S3__SOCKET_TIMEOUT_MS`,
61
+ `NSC__S3__DOWNLOAD_IDLE_TIMEOUT_MS`, `NSC__FILE__DOWNLOAD_IDLE_TIMEOUT_MS`, `NSC__FILE__DOWNLOAD_CACHING`.
62
+
63
+ A non-positive or non-numeric value uses the default; the guards cannot be switched off globally (§5 has the per-call
64
+ exception). `connectionTimeoutMs` bounds the wait for a free socket too (the SDK starts it when the request is created),
65
+ and the SDK retries a timed-out attempt — 3 attempts in all, so the `503` comes after up to about 3 × `connectionTimeoutMs`
66
+ plus a short backoff (about 46 s with the default). Keep 3 × the value below your reverse proxy's read timeout (60 s for
67
+ nginx and AWS ALB by default; otherwise the proxy answers `504` first) and well above normal queue waits — a short value
68
+ fails healthy downloads under load.
69
+
70
+ **`file.downloadCaching: 'revalidate'`** sends `Cache-Control: private, no-cache`: the browser keeps the file but asks
71
+ again on every use; that request runs the full role and rights check and is answered `304 Not Modified` without reading
72
+ the store. For image-heavy apps it removes most store reads. The default `'none'` keeps `private, no-store` (nothing is
73
+ kept on the device). Both modes send a weak `ETag` (`W/"<file id>"` — weak because a `compression` middleware may
74
+ deliver the same file gzip-encoded or not) and `Content-Length`.
75
+
76
+ **Compression:** a `compression({ filter: () => true })` gzips already compressed downloads (JPEG, PNG, PDF, ZIP) and only
77
+ burns CPU under many parallel downloads. nest-server's reference `main.ts` now uses `filter: compression.filter` (the
78
+ package default); nest-server-starter follows.
79
+
80
+ ## 3. Own download routes
81
+
82
+ Replace every `stream.pipe(res)` that delivers a file with `pipeFileToResponse(stream, res)`, and pass an abort signal:
83
+
84
+ ```typescript
85
+ import { downloadAbortSignal, pipeFileToResponse } from '@lenne.tech/nest-server';
86
+
87
+ @Get('image/:id')
88
+ async image(@Param('id') id: string, @Res() res: Response, @CurrentUser() currentUser) {
89
+ // Fires when the client goes (response or request close), so a store request waiting for a socket is dropped
90
+ const abortSignal = downloadAbortSignal(res);
91
+ const stream = await this.fileService.getFileStream(id, { abortSignal, currentUser });
92
+ if (!stream) {
93
+ throw new NotFoundException();
94
+ }
95
+ res.header('Content-Type', 'image/png');
96
+ return pipeFileToResponse(stream, res);
97
+ }
98
+ ```
99
+
100
+ The idle guard would release a bare-piped stream after 30 s as well, but under load 30 s per aborted download is enough
101
+ to fill a pool.
102
+
103
+ ## 4. Monitoring
104
+
105
+ Alert on `S3 socket pool exhausted:` in the log (level ERROR, at most once per minute per process). It names the
106
+ sockets in use, the waiting requests and the download streams closed for lack of progress. Genuine load → raise
107
+ `s3.maxSockets`; a growing count without load → a download path that does not use `pipeFileToResponse()`.
108
+ `CoreS3Service.getSocketPoolStats()` returns the same numbers for a metrics endpoint.
109
+
110
+ Downloads the idle guard closed are reported as ONE warning per minute (`N file download(s) closed after no read
111
+ progress …`), split into clients that stopped reading without closing and stores that delivered nothing. A client that
112
+ stops reading is not a server error, so it never produces an ERROR line per download. A store that delivered nothing
113
+ before the first byte answers `503` with `Retry-After`. The health check deliberately does
114
+ not fail on it: a short S3 disturbance would take the whole API, sign-in included, out of the load balancer.
115
+
116
+ ## 5. Streams that are read late
117
+
118
+ Every stream from `getFileStream()`, `getFileStreamByName()` and `CoreS3Service.getObject()` must be read within
119
+ `downloadIdleTimeoutMs` (30 s) of being obtained and keep making progress. Code that collects streams first and reads
120
+ them later breaks: a ZIP export with `archiver.append(await getFileStream(id), …)` in a loop pipes each source into a
121
+ buffer at once but reads it only when that entry's turn comes. A stream the guard closes ends WITHOUT `end`: a `.pipe()`
122
+ consumer waits forever, `pipeline()` and `for await` reject (`ERR_STREAM_PREMATURE_CLOSE` / `StreamIdleTimeoutError`).
123
+
124
+ | Fix | How |
125
+ |---|---|
126
+ | Open each stream right before it is read (preferred) | archiver: append the next file only after the previous entry finished (`entry` event) |
127
+ | Raise the idle time | `file.downloadIdleTimeoutMs` / `s3.downloadIdleTimeoutMs` (capped at 2^31 − 1 ms, about 24.8 days) |
128
+ | Opt out for one call | `getFileStream(id, { downloadIdleTimeoutMs: false, … })` / `getObject(key, { idleTimeoutMs: false })` — only when the code is certain to read the stream to the end or destroy it; until then it holds its socket, file handle or cursor |
129
+
130
+ For S3 both have a second limit: a socket without traffic for `s3.socketTimeoutMs` (120 s) is closed by the SDK, so an
131
+ S3 stream that is not read for that long ends with an error even with the opt-out — raise `s3.socketTimeoutMs` as well
132
+ for exports that let an entry wait longer. The opt-out keeps the guard's error handling, so that error never ends the
133
+ process.
134
+
135
+ ## Troubleshooting
136
+
137
+ | Symptom | Cause | Fix |
138
+ |---|---|---|
139
+ | Downloads answer `503` with `Retry-After` | no store connection within `s3.connectionTimeoutMs` — the pool is exhausted | genuine load: raise `s3.maxSockets`; otherwise look for downloads that do not go through `pipeFileToResponse()` |
140
+ | A very slow client gets a truncated file | it read nothing for `downloadIdleTimeoutMs` | raise `s3.downloadIdleTimeoutMs` / `file.downloadIdleTimeoutMs` |
141
+ | A ZIP export or batch job hangs or produces truncated entries | it opens file streams first and reads them later (§5) | open each stream right before reading it, or opt out per call (§5) |
142
+ | The proxy answers `504` while the pool is exhausted, the API never shows its `503` | 3 × `connectionTimeoutMs` (SDK retries) exceeds the proxy's read timeout | lower `s3.connectionTimeoutMs` (§2) |
143
+ | `S3 socket pool exhausted` in the log | see §4 | see §4 |
144
+
145
+ ## Module Documentation
146
+
147
+ - `src/core/modules/file/README.md` — "Delivering a file from your own route (11.46.3)"
148
+ - `src/core/modules/file/INTEGRATION-CHECKLIST.md` — Common Mistakes
149
+ - `src/core/common/helpers/idle-stream.helper.ts`, `src/core/common/services/core-s3.service.ts`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "11.46.2",
3
+ "version": "11.46.3",
4
4
  "description": "Modern, fast, powerful Node.js web framework in TypeScript based on Nest with a GraphQL API and a connection to MongoDB (or other databases).",
5
5
  "keywords": [
6
6
  "node",
@@ -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
+ }
@@ -1257,6 +1257,33 @@ export interface IFileConfig {
1257
1257
  */
1258
1258
  deleteRoles?: string[];
1259
1259
 
1260
+ /**
1261
+ * Browser caching of file downloads (`GET /files/id/:id`, `GET /files/:filename`).
1262
+ *
1263
+ * - `'none'`: `Cache-Control: private, no-store` — nothing is kept, every view reads the store again.
1264
+ * - `'revalidate'`: `Cache-Control: private, no-cache` plus `ETag` — the browser keeps the file but asks
1265
+ * again on every use; the request runs the full role and rights check and is answered `304 Not Modified`
1266
+ * without reading the store. Recommended for image-heavy apps: it removes most store reads (S3 sockets)
1267
+ * while every view stays authorized. Shared caches stay excluded (`private`). Note that the browser then
1268
+ * stores authorized file content on the device.
1269
+ *
1270
+ * Both modes send a weak `ETag` (`W/"<file id>"`) and answer a matching `If-None-Match` with 304.
1271
+ * @default 'none'
1272
+ * @since 11.46.3
1273
+ */
1274
+ downloadCaching?: 'none' | 'revalidate';
1275
+
1276
+ /**
1277
+ * Time in milliseconds a download stream from `CoreFileService.getFileStream()` / `getFileStreamByName()` may
1278
+ * go without ANY read progress before it is destroyed, releasing the file handle (filesystem) or the cursor
1279
+ * (GridFS) it holds. Protects against a stream piped with a bare `stream.pipe(res)` to a client that aborts,
1280
+ * and a stream obtained and never read. A slow reader that keeps reading is never cut off. S3 streams use
1281
+ * `s3.downloadIdleTimeoutMs`. A non-positive or non-numeric value uses the default.
1282
+ * @default 30000
1283
+ * @since 11.46.3
1284
+ */
1285
+ downloadIdleTimeoutMs?: number;
1286
+
1260
1287
  /**
1261
1288
  * Roles allowed to DOWNLOAD files and read file info
1262
1289
  * (`GET /files/id/:id`, `GET /files/:filename`, `getFileInfo` query).
@@ -3728,6 +3755,34 @@ export interface IS3Config {
3728
3755
  */
3729
3756
  bucket: string;
3730
3757
 
3758
+ /**
3759
+ * Upper bound in milliseconds for ONE attempt of a request to get a socket: the time it WAITS for a free socket of
3760
+ * the pool (see `maxSockets`) plus the time to connect. The SDK starts this timer when the request is created, not
3761
+ * when it gets a socket, so it bounds the queue wait as well — which keeps the queue from growing without end under
3762
+ * overload (each waiting request holds memory). The SDK retries a timed-out attempt (3 attempts in all), so a
3763
+ * download that cannot get a socket is answered `503` with `Retry-After` after up to about 3 × this value plus a
3764
+ * short backoff — with the default about 46 s, below the common 60 s read timeout of reverse proxies. Keep
3765
+ * 3 × this value below your proxy's read timeout, and well above normal queue waits: a short value fails healthy
3766
+ * downloads under load. A non-positive or non-numeric value uses the default.
3767
+ * @default 15000
3768
+ * @since 11.46.3
3769
+ */
3770
+ connectionTimeoutMs?: number;
3771
+
3772
+ /**
3773
+ * Time in milliseconds a download stream from S3 (`CoreS3Service.getObject()`, and with it
3774
+ * `CoreFileService.getFileStream()` for S3-stored files) may go without ANY read progress before it is
3775
+ * destroyed and its socket returns to the pool.
3776
+ *
3777
+ * A stream that is obtained and never read, or piped with a bare `stream.pipe(res)` to a client that
3778
+ * aborts, otherwise holds its socket for the life of the process — and the pool is finite (see
3779
+ * `maxSockets`). A slow reader that keeps reading is never cut off: every chunk resets the timer.
3780
+ * A non-positive or non-numeric value uses the default; the guard cannot be switched off.
3781
+ * @default 30000
3782
+ * @since 11.46.3
3783
+ */
3784
+ downloadIdleTimeoutMs?: number;
3785
+
3731
3786
  /**
3732
3787
  * Whether S3 is enabled.
3733
3788
  * Presence of the config object implies true.
@@ -3748,6 +3803,19 @@ export interface IS3Config {
3748
3803
  */
3749
3804
  forcePathStyle?: boolean;
3750
3805
 
3806
+ /**
3807
+ * Maximum number of concurrent sockets to the S3 endpoint (per protocol). Requests beyond it wait for a
3808
+ * free socket — and are reported as an error in the log while they do (pool saturation).
3809
+ *
3810
+ * The AWS SDK's own default is 50, which a single process reaches with 50 simultaneous downloads; every
3811
+ * stream holds its socket until it is read to the end or destroyed. 200 lets that many transfers run at
3812
+ * once — each costs one file descriptor and a few KB — while staying far below what S3 and S3-compatible
3813
+ * stores accept per client. A non-positive or non-numeric value uses the default.
3814
+ * @default 200
3815
+ * @since 11.46.3
3816
+ */
3817
+ maxSockets?: number;
3818
+
3751
3819
  /**
3752
3820
  * Serve downloads as presigned URL redirects instead of streaming
3753
3821
  * through the API (offloads traffic from the server).
@@ -3799,6 +3867,16 @@ export interface IS3Config {
3799
3867
  */
3800
3868
  secretAccessKey?: string;
3801
3869
 
3870
+ /**
3871
+ * Time in milliseconds a socket to S3 may stay without any traffic before the SDK destroys it — the
3872
+ * backstop under `downloadIdleTimeoutMs` for every request, uploads and copies included. Kept well above
3873
+ * the download idle time, because an S3-compatible store may take a while without sending a byte to
3874
+ * finish a large copy or multipart upload. A non-positive or non-numeric value uses the default.
3875
+ * @default 120000
3876
+ * @since 11.46.3
3877
+ */
3878
+ socketTimeoutMs?: number;
3879
+
3802
3880
  /**
3803
3881
  * Bucket used as staging area for resumable TUS uploads.
3804
3882
  * Configure a lifecycle rule on this bucket to expire aborted uploads.
@@ -6,6 +6,15 @@ export function mongooseIdPlugin(schema) {
6
6
  schema.post(/.*/, (docs) => {
7
7
  const docsArray = Array.isArray(docs) ? docs : [docs];
8
8
  for (const doc of docsArray) {
9
+ // A bare ObjectId is a VALUE, not a document — `distinct()` on an ObjectId field returns an
10
+ // array of them. Mongoose gives `ObjectId.prototype` an `_id` getter returning itself, so the
11
+ // check below matched, and the assignment then hit bson's own `id` SETTER (the 12-byte
12
+ // buffer). bson < 7.3 silently accepted the hex string; bson >= 7.3 (mongodb >= 7.7) throws
13
+ // `BSONError: Cannot create Buffer from the passed potentialBuffer`, turning every
14
+ // `distinct()` over an ObjectId field into a 500.
15
+ if (doc?._bsontype === 'ObjectId') {
16
+ continue;
17
+ }
9
18
  if (doc?._id && typeof doc._id.toHexString === 'function') {
10
19
  doc.id = doc._id.toHexString();
11
20
  }