@lenne.tech/nest-server 11.46.2 → 11.46.4

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/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/ai/core-ai.controller.js +8 -4
  14. package/dist/core/modules/ai/core-ai.controller.js.map +1 -1
  15. package/dist/core/modules/file/core-file.controller.d.ts +17 -0
  16. package/dist/core/modules/file/core-file.controller.js +221 -8
  17. package/dist/core/modules/file/core-file.controller.js.map +1 -1
  18. package/dist/core/modules/file/core-file.service.d.ts +5 -0
  19. package/dist/core/modules/file/core-file.service.js +17 -7
  20. package/dist/core/modules/file/core-file.service.js.map +1 -1
  21. package/dist/core/modules/file/interfaces/file-service-options.interface.d.ts +2 -0
  22. package/dist/core/modules/file/s3-file.helper.d.ts +4 -1
  23. package/dist/core/modules/file/s3-file.helper.js +2 -2
  24. package/dist/core/modules/file/s3-file.helper.js.map +1 -1
  25. package/dist/index.d.ts +1 -0
  26. package/dist/index.js +1 -0
  27. package/dist/index.js.map +1 -1
  28. package/dist/main.js +1 -3
  29. package/dist/main.js.map +1 -1
  30. package/dist/tsconfig.build.tsbuildinfo +1 -1
  31. package/docs/REQUEST-LIFECYCLE.md +2 -2
  32. package/migration-guides/11.46.2-to-11.46.3.md +161 -0
  33. package/migration-guides/11.46.3-to-11.46.4.md +75 -0
  34. package/package.json +1 -1
  35. package/src/core/common/helpers/idle-stream.helper.ts +192 -0
  36. package/src/core/common/interfaces/server-options.interface.ts +78 -0
  37. package/src/core/common/plugins/mongoose-id.plugin.ts +9 -0
  38. package/src/core/common/services/core-s3.service.ts +186 -3
  39. package/src/core/modules/ai/core-ai.controller.ts +12 -4
  40. package/src/core/modules/file/INTEGRATION-CHECKLIST.md +16 -14
  41. package/src/core/modules/file/README.md +63 -0
  42. package/src/core/modules/file/core-file.controller.ts +390 -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
@@ -338,6 +338,7 @@ This pattern is currently applied to:
338
338
  | File Access Roles | `file.downloadRoles`, `file.uploadRoles`, `file.deleteRoles` | Config-Driven Role List | `[RoleEnum.ADMIN]` each. **These are the only breaking change a single-replica project gets in 11.33.0** — six members moved from `@Roles(S_EVERYONE)` to these knobs: `GET /files/id/:id`, `GET /files/:filename` and `getFileInfo` (`downloadRoles`), `uploadFile` / `uploadFiles` (`uploadRoles`), `deleteFile` (`deleteRoles`). Plain role STRINGS, not `RoleEnum` members, so project roles work (`['company-admin', 'editor']`). Applied at boot by `applyFileRoles()` via `Reflect.defineMetadata('roles', …)` on the base-class methods — the same runtime mechanism `CorePermissionsModule` uses, because the value is only known from config. **`[]`, a non-array, or an array holding a non-string is REJECTED with a warning and the default applies** — an all-empty role set reads to the guards as "no roles required" and would OPEN the route, the exact opposite of the intent. **ADMIN is always unioned in**: both `CoreFileController` and `CoreFileResolver` carry a class-level `@Roles(RoleEnum.ADMIN)` and the guards UNION class + handler metadata, so these knobs can grant but never exclude admins. Both classes also carry `@SkipTenantCheck()` — GridFS and the S3 metadata collection are reached outside Mongoose, so `mongooseTenantPlugin` never scopes them and a role name alone cannot express a per-tenant rule; roles resolve against `user.roles`, never `membership.role`. **A subclass that OVERRIDES a member opts out permanently** (decorator metadata lives on the function object, and an override is a different function) — inherit the member instead. **Since 11.35.1 that opt-out is REPORTED**: `CoreFileAccessAuditInitializer` reads the roles off the class the project actually registered at `onApplicationBootstrap` (the earliest point at which the route table exists, which is why it is a provider and not part of `applyFileRoles()`) and warns when a member is open beyond ADMIN for a reason the configuration cannot explain — the case the construction-time warning below is structurally blind to. It only REPORTS: overwriting an override's metadata, the way `TusModule.applyRoles()` does, would silently relax a route a project pinned on purpose. Roles are the coarse filter only; per-file rules belong in `CoreFileService.checkRights()`, which now receives `currentUser` and can read raw metadata via `getRawFileInfo()`. **Since 11.35.0 a reused FILENAME resolves to the most recent file** in all three stores (`uploadDate` desc, `_id` tie-break) and every by-name read path resolves a document and then reads by ID — under GridFS the by-name metadata lookup answered the oldest document while `openDownloadStreamByName()` served the newest, so a per-file rule approved one file and the bytes of another came back. Consequence: `duplicateById()` keeps the source's filename and the copy carries no metadata, so the copy now wins the name and an `ownerId` rule refuses it — give the copy its own metadata or its own name. **Since 11.35.0 `CoreFileService` WARNS at construction** when `multiTenancy` is active AND a knob names a role other than ADMIN AND `checkRights()` is not overridden — the file stores are reached outside Mongoose, so these role names resolve against `user.roles` (global) and every holder reaches every tenant's files; only `checkRights()` can narrow that. Silent on the admin-only default and silent when a per-file rule exists. Implementation: `src/core/modules/file/file-roles.config.ts` (`FILE_ROLE_DEFAULTS`, `FILE_ROLE_MEMBERS`, the three warnings, the shared `hasDeclaredFilePolicy()` silencer) + `file-roles.helper.ts` (`applyFileRoles`) + `core-file-access-audit.initializer.ts` (the registered-class audit) |
339
339
  | TUS Roles | `tus.roles` | Config-Driven Role List | `[RoleEnum.S_USER]` (was `S_EVERYONE` — breaking). A TUS upload writes into the SAME store the download routes guard, and the termination extension (on by default) can delete from it, so anonymous writes into a store only privileged callers may read is the wrong way round. Applied by `TusModule.applyRoles()` onto the registered controller class **and** onto `handleTus` / `handleTusWithId`. Same rejection rule as the file roles: `[]` / non-array / non-string → warning + `DEFAULT_TUS_CONFIG.roles`. **`OPTIONS` is deliberately exempt**: `handleTusOptions` / `handleTusOptionsWithId` keep their own handler-level `@Roles(RoleEnum.S_EVERYONE)`, because that is the CORS preflight — browsers send it WITHOUT credentials, and it returns server capabilities only. Gating it would make every browser upload fail before the first byte. `CoreTusController` also carries `@SkipTenantCheck()`. A custom controller is covered as long as it INHERITS the handlers; one that re-declares `@All()` / `@Roles()` carries its own metadata and thereby opts out — the documented way to hard-code a policy config must not be able to change. **Set `roles: [RoleEnum.S_EVERYONE]` explicitly if you accept attachments on a public form.** **Since 11.35.0 `tus.roles` is no longer the only gate**: `onUploadCreate` records the authenticated creator under `TUS_OWNER_METADATA_KEY` (`ltOwnerId`, always OVERWRITING any client-supplied value) and `onIncomingRequest` refuses HEAD/PATCH/DELETE naming an upload the caller does not own — with **404**, the file module's refusal policy. Before that, any authenticated caller who learned an upload id could APPEND BYTES to somebody else's upload, which are then migrated into the file store under the victim's filename. The finished file also gains `metadata.ownerId`, without which the documented per-file ownership rule could never authorize a tus-uploaded file (admin-only in practice). An OWNER-LESS upload stays reachable — uploads predating 11.35.0 have none, and neither does a deliberately public form. `readRequestUserId()` / `assertUploadOwnership()` are `protected`. **Since 11.41.9 the tenant is recorded too, but ONLY with `multiTenancy` configured** (not `enabled: false`) and a tenant guard registered: `onUploadCreate` validates the tenant header against the caller's active memberships through `core-tenant-context.registry.ts` (the routes carry `@SkipTenantCheck()`, so the guard did not), refuses a non-member with **403**, writes it under `TUS_TENANT_METADATA_KEY` (`ltTenantId`, always overwritten like the owner key) and the finished file gains `metadata.tenantId`. No header → tenant-less, as before; without `multiTenancy` nothing is read or written. A project hooks in through `TusModule.forRoot({ service })` (a `CoreTusService` subclass, constructed by the module as `(connection, options)` — project providers come from `options.moduleRef` at call time) and the `protected onUploadCreate(req, upload)`, the one point where `Upload-Length` is known and nothing is stored yet; an override must return `super.onUploadCreate()`. Note that `@tus/server` v2 hands its hooks a WHATWG `ServerRequest`, so a guard's `req.user` is reachable only via `runtime.node.req`. **CORS (11.42.1)**: the tus handler's `Access-Control-Allow-Origin` comes from `buildCorsConfig()` (or `tus.allowedOrigins`), plus `allowedCredentials` — without it `@tus/server` answered `*`, which browsers refuse on a credentialed request, so cookie-authenticated uploads across split app/API origins failed in every browser while the server answered 201; no credentialed CORS configured → the `*` default stays. **compression (11.42.2)**: `@tus/server` finishes responses with `res.end(callback)`, which `compression`'s two-argument `res.end(chunk, encoding)` patch reads as a chunk (`ERR_INVALID_ARG_TYPE … Received function`); with the starter's `filter: () => true, threshold: 0` every finished upload HUNG without an answer AFTER the file was stored (headers already sent, so no error response could follow). `CoreTusService` wraps `server.handle()` and normalises `res.end` per response (`normalizeEndCallback()`, callback on `finish`/`close`), so no `main.ts` change is needed. Implementation: `src/core/modules/tus/tus.module.ts`, `src/core/modules/tus/core-tus.service.ts`, `src/core/modules/tus/tus.constants.ts` |
340
340
  | File Storage | `file.storage` + `file.storageDir` + `s3` | Explicit Enum with DERIVED default | `'filesystem' \| 'gridfs' \| 's3'`. **Unset → derived**, most capable first: `'s3'` when `s3.bucket` is set, else `'gridfs'` when `mongoose.uri` is set, else `'filesystem'`. **Set → enforced**: an unavailable store FAILS THE BOOT (`assertFileStorageAvailable()`), it never falls back — a silent fallback puts files in a store the operator does not believe they are in, unrecoverably. A DERIVED driver is enforced too (`s3.bucket` set but `s3Service` not forwarded to `super()` → boot error). Metadata always lives in MongoDB whichever driver holds the bytes (`fs.files` / `s3-files` / `filesystem-files`) — it has to stay queryable for `findFileInfo()` and `checkRights()`. Reads consult ALL stores so switching drivers is forward-only with no migration; writes go to the active driver only. `'filesystem'` is pod-local: not shared between replicas, lost on restart unless `storageDir` is a mounted volume. `s3`: `bucket` (required — the one thing S3 cannot default, hence the eligibility test), `region: 'us-east-1'`, `forcePathStyle: false`, `autoCreateBucket: false` (off by design: production buckets come from infrastructure code, whose credentials usually cannot CreateBucket), `stagingBucket: bucket`, `presignedDownloads: false` (`true`/`{}` → `expiresInSeconds: 300`), `endpoint` (MinIO/RustFS), `accessKeyId`/`secretAccessKey` (omit → AWS default credential chain), `enabled: false` to pre-configure. Requires the OPTIONAL peer `@aws-sdk/client-s3`, plus `@aws-sdk/s3-request-presigner` for presigned downloads. **Uploads are never buffered on the S3 path** (11.41.7): a known length (`FileUploadSource.size`, TUS, a buffer) goes up as one streamed PutObject up to `CoreS3Service.MAX_SINGLE_PUT_BYTES` (5 GiB — AWS S3 refuses more in one request, `EntityTooLarge`) and as a multipart upload above it, an unknown one — every GraphQL and streamed REST upload — as a multipart upload via the OPTIONAL peer `@aws-sdk/lib-storage`. Missing peer → one boot warning and the old in-memory buffering, NOT a boot failure (multipart optimises a path that works without it). `size` must be the file's EXACT length — never a multipart request's `Content-Length`; anything but a positive integer counts as unknown (`isKnownUploadSize()`), and the recorded length of an unknown-length upload comes from a HEAD of the stored object. `presignedDownloads` makes `GET /files/id/:id` answer `302` to a time-limited S3 URL instead of streaming — the URL is a bearer capability, authorized once at issue time. The resolved driver is logged at boot (`[CoreFileStorage] File storage: …`) |
341
+ | S3 Connection Pool & Download Guard | `s3.maxSockets`, `s3.connectionTimeoutMs`, `s3.socketTimeoutMs`, `s3.downloadIdleTimeoutMs`; `file.downloadIdleTimeoutMs`, `file.downloadCaching` | Numeric — invalid → default, never off (Family C without opt-out) + Explicit Enum | **11.46.3, after a production outage**: S3 downloads delivered with a bare `stream.pipe(res)` kept their sockets when clients aborted; after 50 the SDK's pool was full, every S3 request waited forever (health check green), heap OOM hours later. Since then: `CoreS3Service` builds its client with OWN agents (`maxSockets` **200**, keep-alive), `connectionTimeout` **15 000** per attempt (the SDK starts it when the request is CREATED, so it also bounds the wait for a free socket — a short value fails healthy downloads under load; the SDK retries a timed-out attempt, 3 attempts in all, so a download that gets no socket answers **503** + `Retry-After: 5` after about 46 s — keep 3 × the value below the reverse proxy's read timeout, commonly 60 s), `socketTimeout` **120 000** (inactivity backstop for every request, uploads and copies included). The SDK's `requestTimeout` stops at the headers and its socket timeout destroys the body WITH an error (a process crash without a listener), so the real guard is `guardIdleStream()` (`common/helpers/idle-stream.helper.ts`): every stream from `getObject()` (`s3.downloadIdleTimeoutMs`, 30 000) and from `CoreFileService.getFileStream()` / `getFileStreamByName()` (`file.downloadIdleTimeoutMs`, 30 000 — GridFS cursors, file handles) is destroyed after that long WITHOUT READ PROGRESS, measured on the consumer side (`_read`) and at the source; a slow reader that keeps reading is never cut off; code that opens a stream and reads it LATE (an archive appending every file first) breaks — per call `downloadIdleTimeoutMs: false` (`FileServiceOptions`) / `getObject(key, { idleTimeoutMs: false })` opts out. `pipeFileToResponse()` destroys the source when the client goes — the response's `close`, the request's `close` (before its end and while the response is unfinished — Node closes a request whose body was read to the end by itself, a POST export stays deliverable) or the socket's `end`/`close`: measured under a k6 abort storm, about one in six aborted downloads never got a `close` on the response and reported it only through the request or the socket — and at once when it had ALREADY gone (`isResponseGone()`: response destroyed/closed OR request destroyed before its end OR socket destroyed; a client that gave up while waiting for a socket — the avalanche path); the routes pass an `abortSignal` (`downloadAbortSignal()`, exported: the same client-gone signals) down to `GetObjectCommand` and open the stream through `openDownloadStream()` (exported since 11.46.4 for a project's own routes): no store request for a gone client, `RESPONSE_GONE` instead of an ERROR when the store request failed because the client left (an aborted S3 request rejects with `AbortError`), a late stream destroyed, `TimeoutError` → 503 + `Retry-After`. An exhausted pool is logged as an ERROR once per minute with numbers (`getSocketPoolStats()` exposes them); deliberately NOT a health-check failure. `file.downloadCaching`: `'none'` (default, `private, no-store`) or `'revalidate'` (`private, no-cache` — the browser revalidates every use, `304` after the rights check without a store read); both send a WEAK `ETag` `W/"<id>"` (bytes under an id never change, but a `compression` middleware sends a gzip and an identity representation of the same file — RFC 9110 §8.8.3 forbids one strong validator for both; `If-None-Match` compares weakly) and `Content-Length`. The reference `src/main.ts` uses `compression.filter` (no gzip for JPEG/PNG/PDF/ZIP). Pinned by `tests/unit/idle-stream.spec.ts`, `tests/unit/core-file.controller.spec.ts`, `tests/unit/download-idle-opt-out.spec.ts` and `tests/s3-download-resilience.e2e-spec.ts` (real RustFS: dropped streams, abort storm with bare `pipe()`, clients giving up while waiting, 500 parallel downloads with `maxSockets: 4`, slow reader; mutations `idle-guard-*`, `s3-get-object-*`, `pipe-file-to-response-*`, `download-route-keeps-late-stream`, `file-stream-drops-idle-opt-out`). Implementation: `core-s3.service.ts`, `core-file.controller.ts`, `core-file.service.ts` |
341
342
  | TUS S3 Staging | `tus.s3Staging` | Explicit Boolean (default ON when S3 configured) | `true` when `s3` is configured, otherwise inert. Stages in-progress uploads in `s3.stagingBucket` via `@tus/s3-store` instead of `tus.uploadDir` on local disk, so resumable uploads survive replica restarts and need no sticky sessions. Set `false` to force local disk. Missing OPTIONAL peer `@tus/s3-store` → warning + fall back to local disk (NOT a boot failure). **Give the staging bucket a lifecycle rule expiring incomplete multipart uploads** — the framework's own expiration cleanup is skipped in S3 mode (S3 is the right place for that policy), so aborted uploads otherwise accumulate parts nothing removes |
342
343
  | TUS Configuration Source, Path & Extensions | `tus` (server config) / `TusModule.forRoot({ config })` | Enabled by Default + explicit-config-wins | **Since 11.42.9 `TusModule.forRoot()` without `config` reads the server config's `tus` key** (`ConfigService.get('tus')`, the zero-config rule `CoreBetterAuthModule.forRoot()` follows); an explicit `config` wins. Before, the key was never read: `tus: false`, `allowedTypes`, `maxSize`, `roles` in `config.env.ts` did nothing — real projects had upload restrictions they believed were enforced. **`path`** has three readings (`applyPath()`): unset → follows the controller's route; a new route (`/uploads`) → mounts the registered controller there (writes `PATH_METADATA`, config wins like the roles; the declared route is remembered per class and restored by a later `forRoot()` without `path`); a path ENDING with the controller's route (`/api/tus`, `/files/tus`) → the PUBLIC URL: the controller stays and upload URLs use it. The third reading is load-bearing: it was the only working setting under a global prefix or a prefix-stripping proxy before 11.42.9, and treating it as a route doubled the prefix (`/api/api/tus`, 404 on every upload — caught in the second pre-release review). The upload URL (`Location`) is built from the path the creation request arrived at (`uploadCollectionPath(req)`), or from `path` when that is longer and ends with it (proxy strip); `@tus/server` built it from `path` alone, which broke every resume below a global prefix, a URI version or a project route. **`relativeLocation`** (new): the framework owns `generateUrl`, which takes precedence over `@tus/server`'s option of that name, so it is honoured from `tus.relativeLocation` AND from the tus server's own options (a vendored core may pass it there). **Extensions**: `@tus/server` consults no flag, so `creation`, `creationWithUpload` and `termination` are enforced by `CoreTusService` — the store's advertised `extensions` are narrowed, and `assertExtensionEnabled()` answers 501 inside the server's `onIncomingRequest` / `onUploadCreate` options (not in the overridable hook, so an override without `super` cannot reopen it). `checksum` / `concatenation` have no effect: neither built-in store supports them. `configure(false)` now yields a DISABLED config (before it kept the defaults and started a tus server behind a module with no endpoint). Implementation: `tus.module.ts`, `core-tus.service.ts` |
343
344
  | Health Check | `healthCheck` | Presence Implies Enabled | Absent → no endpoints. Any object registers `GET /health-check` + the `healthCheck` query; **`enabled: false` leaves them out (honoured since 11.42.9 — before, it was declared and ignored)**. Individual checks under `configs.*` each have their own `enabled`. Implementation: `core.module.ts` |
@@ -268,7 +268,7 @@ pnpm run check:mutations -- --id=<id> # one mutation
268
268
  pnpm run check:mutations -- --list # the registry, without running anything
269
269
  pnpm run check:mutations -- --allow-dirty # when the fix and its evidence share a working tree
270
270
  pnpm run check:mutations -- --jobs=4 # N mutations at a time (default: 2, or 4 on >=12 cores)
271
- pnpm run check:mutations -- --no-infra # only the 228 that need no MongoDB
271
+ pnpm run check:mutations -- --no-infra # only the 248 that need no MongoDB
272
272
  pnpm run check:mutations -- --since=<ref> # only mutations touching files changed since <ref>
273
273
  ```
274
274
 
@@ -287,7 +287,7 @@ when the registry, a vitest config or a setup file changed, since those can move
287
287
  commit, and in CI alongside the publish without blocking it. The price of caching is a cache that
288
288
  has to model each spec's full dependency closure correctly, and getting that wrong produces a stale
289
289
  PASS for a test that has since gone vacuous — exactly what the gate is there to prevent. Bad trade
290
- at 326 mutations.
290
+ at 350 mutations.
291
291
 
292
292
  **Decided 2026-10-03 (repo owner): keep the full run.** Measured at 128 mutations, the CI job for
293
293
  11.41.6 took **14 minutes**. The trigger to revisit is that wall time, not the mutation count —
@@ -332,9 +332,9 @@ exactly the environment where the answer matters.
332
332
 
333
333
  ### The cost is vitest's cold start, not the tests
334
334
 
335
- Worth knowing before optimising the wrong thing: the specs behind all 98 e2e mutations add up to
335
+ Worth knowing before optimising the wrong thing: the specs behind all 102 e2e mutations add up to
336
336
  **~40 seconds**. The step takes ~740s. The remaining ~700s is paying vitest's startup — process
337
- spawn, transform, module graph, mongod connect, DB create and drop — once per mutation, 326 times.
337
+ spawn, transform, module graph, mongod connect, DB create and drop — once per mutation, 350 times.
338
338
  That work is largely single-threaded I/O and barely scales with cores: the full registry measures
339
339
  **744s on a 12-core laptop and 777s on a 4-vCPU CI runner**.
340
340
 
package/FRAMEWORK-API.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @lenne.tech/nest-server — Framework API Reference
2
2
 
3
- > Auto-generated from source code as of 2026-11-11 (v11.46.2)
3
+ > Auto-generated from source code as of 2026-11-11 (v11.46.4)
4
4
  > File: `FRAMEWORK-API.md` — compact, machine-readable API surface for Claude Code
5
5
 
6
6
  ## CoreModule.forRoot()
@@ -163,6 +163,8 @@ When `passkey` is enabled, `trustedOrigins` is required (compile-time enforcemen
163
163
 
164
164
  - `access?`: `"authenticated" | "custom" | "owner" | "public" | "tenant" | undefined` (default: `'custom'`) — WHICH PROJECT CLASS this deployment is — the per-file rule, as a declaration instead of code.
165
165
  - `deleteRoles?`: `string[] | undefined` (default: `['admin']`) — Roles allowed to DELETE files (`deleteFile` mutation).
166
+ - `downloadCaching?`: `"none" | "revalidate" | undefined` (default: `'none'`) — Browser caching of file downloads (`GET /files/id/:id`, `GET /files/:filename`).
167
+ - `downloadIdleTimeoutMs?`: `number | undefined` (default: `30000`) — Time in milliseconds a download stream from `CoreFileService.getFileStream()` / `getFileStreamByName()` may
166
168
  - `downloadRoles?`: `string[] | undefined` (default: `['admin']`) — Roles allowed to DOWNLOAD files and read file info
167
169
  - `storage?`: `"filesystem" | "gridfs" | "s3" | undefined` (default: `derived — see above`) — Storage driver for CoreFileService. Three equivalent options:
168
170
  - `storageDir?`: `string | undefined` (default: `'uploads/files'`) — Directory for the `'filesystem'` storage driver.
@@ -185,12 +187,16 @@ When `passkey` is enabled, `trustedOrigins` is required (compile-time enforcemen
185
187
  - `accessKeyId?`: `string | undefined` (default: `undefined`) — Access key ID.
186
188
  - `autoCreateBucket?`: `boolean | undefined` (default: `false`) — Create the configured buckets at startup when they do not exist.
187
189
  - `bucket`: `string` — Bucket for files stored via CoreFileService
190
+ - `connectionTimeoutMs?`: `number | undefined` (default: `15000`) — Upper bound in milliseconds for ONE attempt of a request to get a socket: the time it WAITS for a free socket of
191
+ - `downloadIdleTimeoutMs?`: `number | undefined` (default: `30000`) — Time in milliseconds a download stream from S3 (`CoreS3Service.getObject()`, and with it
188
192
  - `enabled?`: `boolean | undefined` (default: `true (when config object is present)`) — Whether S3 is enabled.
189
193
  - `endpoint?`: `string | undefined` (default: `undefined`) — Custom endpoint URL for S3-compatible services (MinIO, RustFS, ...).
190
194
  - `forcePathStyle?`: `boolean | undefined` (default: `false`) — Use path-style addressing (required by most self-hosted S3 services).
195
+ - `maxSockets?`: `number | undefined` (default: `200`) — Maximum number of concurrent sockets to the S3 endpoint (per protocol). Requests beyond it wait for a
191
196
  - `presignedDownloads?`: `boolean | { enabled?: boolean; expiresInSeconds?: number; } | undefined` (default: `false`) — Serve downloads as presigned URL redirects instead of streaming
192
197
  - `region?`: `string | undefined` (default: `'us-east-1'`) — AWS region
193
198
  - `secretAccessKey?`: `string | undefined` (default: `undefined`) — Secret access key.
199
+ - `socketTimeoutMs?`: `number | undefined` (default: `120000`) — Time in milliseconds a socket to S3 may stay without any traffic before the SDK destroys it — the
194
200
  - `stagingBucket?`: `string | undefined` (default: `same as `bucket``) — Bucket used as staging area for resumable TUS uploads.
195
201
 
196
202
  ### ITusConfig
@@ -0,0 +1,14 @@
1
+ import type { Readable } from 'stream';
2
+ export declare const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 30000;
3
+ export declare const MAX_TIMER_DELAY_MS = 2147483647;
4
+ export declare class StreamIdleTimeoutError extends Error {
5
+ readonly idleMs: number;
6
+ readonly code = "LT_STREAM_IDLE_TIMEOUT";
7
+ constructor(idleMs: number);
8
+ }
9
+ export interface GuardIdleStreamOptions {
10
+ idleMs?: false | number;
11
+ onIdle?: (idleMs: number) => void;
12
+ }
13
+ export declare function isIdleGuardedStream(stream: unknown): boolean;
14
+ export declare function guardIdleStream(source: Readable, options?: GuardIdleStreamOptions): Readable;
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StreamIdleTimeoutError = exports.MAX_TIMER_DELAY_MS = exports.DEFAULT_STREAM_IDLE_TIMEOUT_MS = void 0;
4
+ exports.isIdleGuardedStream = isIdleGuardedStream;
5
+ exports.guardIdleStream = guardIdleStream;
6
+ const stream_1 = require("stream");
7
+ const IDLE_GUARDED = Symbol('lt.idleGuardedStream');
8
+ exports.DEFAULT_STREAM_IDLE_TIMEOUT_MS = 30_000;
9
+ exports.MAX_TIMER_DELAY_MS = 2_147_483_647;
10
+ class StreamIdleTimeoutError extends Error {
11
+ idleMs;
12
+ code = 'LT_STREAM_IDLE_TIMEOUT';
13
+ constructor(idleMs) {
14
+ super(`Download stream made no read progress for ${idleMs} ms and was closed to release its resources`);
15
+ this.idleMs = idleMs;
16
+ this.name = 'StreamIdleTimeoutError';
17
+ }
18
+ }
19
+ exports.StreamIdleTimeoutError = StreamIdleTimeoutError;
20
+ class IdleGuardStream extends stream_1.PassThrough {
21
+ onConsumerRead;
22
+ read(size) {
23
+ this.onConsumerRead?.();
24
+ return super.read(size);
25
+ }
26
+ }
27
+ function isIdleGuardedStream(stream) {
28
+ return !!stream && stream[IDLE_GUARDED] === true;
29
+ }
30
+ function guardIdleStream(source, options = {}) {
31
+ if (isIdleGuardedStream(source)) {
32
+ return source;
33
+ }
34
+ const idleMs = options.idleMs === false
35
+ ? undefined
36
+ : typeof options.idleMs === 'number' && Number.isFinite(options.idleMs) && options.idleMs > 0
37
+ ? Math.min(options.idleMs, exports.MAX_TIMER_DELAY_MS)
38
+ : exports.DEFAULT_STREAM_IDLE_TIMEOUT_MS;
39
+ const guarded = new IdleGuardStream();
40
+ Object.defineProperty(guarded, IDLE_GUARDED, { enumerable: false, value: true });
41
+ let timer;
42
+ const stopTimer = () => {
43
+ if (timer) {
44
+ clearTimeout(timer);
45
+ timer = undefined;
46
+ }
47
+ };
48
+ let pipeErrorListeners = 0;
49
+ const hasConsumerErrorListener = () => guarded.listenerCount('error') > pipeErrorListeners;
50
+ const destroyGuarded = (error) => {
51
+ if (guarded.destroyed) {
52
+ return;
53
+ }
54
+ guarded.destroy(error && hasConsumerErrorListener() ? error : undefined);
55
+ };
56
+ const destroySource = () => {
57
+ if (!source.destroyed) {
58
+ source.destroy();
59
+ }
60
+ };
61
+ const onIdle = () => {
62
+ timer = undefined;
63
+ if (source.readableEnded || guarded.destroyed) {
64
+ return;
65
+ }
66
+ try {
67
+ options.onIdle?.(idleMs);
68
+ }
69
+ catch {
70
+ }
71
+ destroySource();
72
+ destroyGuarded(new StreamIdleTimeoutError(idleMs));
73
+ };
74
+ if (idleMs !== undefined) {
75
+ timer = setTimeout(onIdle, idleMs);
76
+ timer.unref?.();
77
+ }
78
+ guarded.onConsumerRead = () => timer?.refresh();
79
+ source.on('data', () => timer?.refresh());
80
+ source.once('end', stopTimer);
81
+ source.once('close', stopTimer);
82
+ source.on('error', (error) => {
83
+ stopTimer();
84
+ destroyGuarded(error);
85
+ });
86
+ guarded.once('close', () => {
87
+ stopTimer();
88
+ if (!source.readableEnded) {
89
+ destroySource();
90
+ }
91
+ });
92
+ const before = guarded.listenerCount('error');
93
+ source.pipe(guarded);
94
+ pipeErrorListeners = guarded.listenerCount('error') - before;
95
+ source.once('end', () => {
96
+ pipeErrorListeners = 0;
97
+ });
98
+ return guarded;
99
+ }
100
+ //# sourceMappingURL=idle-stream.helper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idle-stream.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/idle-stream.helper.ts"],"names":[],"mappings":";;;AA2EA,kDAEC;AA2BD,0CAuFC;AA/LD,mCAAqC;AAQrC,MAAM,YAAY,GAAG,MAAM,CAAC,sBAAsB,CAAC,CAAC;AAUvC,QAAA,8BAA8B,GAAG,MAAM,CAAC;AAMxC,QAAA,kBAAkB,GAAG,aAAa,CAAC;AAMhD,MAAa,sBAAuB,SAAQ,KAAK;IAG1B;IAFZ,IAAI,GAAG,wBAAwB,CAAC;IAEzC,YAAqB,MAAc;QACjC,KAAK,CAAC,6CAA6C,MAAM,6CAA6C,CAAC,CAAC;QADrF,WAAM,GAAN,MAAM,CAAQ;QAEjC,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;IACvC,CAAC;CACF;AAPD,wDAOC;AA0BD,MAAM,eAAgB,SAAQ,oBAAW;IACvC,cAAc,CAAc;IAEnB,IAAI,CAAC,IAAa;QACzB,IAAI,CAAC,cAAc,EAAE,EAAE,CAAC;QACxB,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;CACF;AAKD,SAAgB,mBAAmB,CAAC,MAAe;IACjD,OAAO,CAAC,CAAC,MAAM,IAAK,MAAkC,CAAC,YAAY,CAAC,KAAK,IAAI,CAAC;AAChF,CAAC;AA2BD,SAAgB,eAAe,CAAC,MAAgB,EAAE,UAAkC,EAAE;IACpF,IAAI,mBAAmB,CAAC,MAAM,CAAC,EAAE,CAAC;QAChC,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,MAAM,MAAM,GACV,OAAO,CAAC,MAAM,KAAK,KAAK;QACtB,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC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kBAAkB,GAAG,CAAC,CAAC;IACzB,CAAC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -141,6 +141,8 @@ export interface IErrorCode {
141
141
  export interface IFileConfig {
142
142
  access?: 'authenticated' | 'custom' | 'owner' | 'public' | 'tenant';
143
143
  deleteRoles?: string[];
144
+ downloadCaching?: 'none' | 'revalidate';
145
+ downloadIdleTimeoutMs?: number;
144
146
  downloadRoles?: string[];
145
147
  storage?: 'filesystem' | 'gridfs' | 's3';
146
148
  storageDir?: string;
@@ -437,15 +439,19 @@ export interface IS3Config {
437
439
  accessKeyId?: string;
438
440
  autoCreateBucket?: boolean;
439
441
  bucket: string;
442
+ connectionTimeoutMs?: number;
443
+ downloadIdleTimeoutMs?: number;
440
444
  enabled?: boolean;
441
445
  endpoint?: string;
442
446
  forcePathStyle?: boolean;
447
+ maxSockets?: number;
443
448
  presignedDownloads?: boolean | {
444
449
  enabled?: boolean;
445
450
  expiresInSeconds?: number;
446
451
  };
447
452
  region?: string;
448
453
  secretAccessKey?: string;
454
+ socketTimeoutMs?: number;
449
455
  stagingBucket?: string;
450
456
  }
451
457
  export interface ISystemSetup {
@@ -5,6 +5,9 @@ function mongooseIdPlugin(schema) {
5
5
  schema.post(/.*/, (docs) => {
6
6
  const docsArray = Array.isArray(docs) ? docs : [docs];
7
7
  for (const doc of docsArray) {
8
+ if (doc?._bsontype === 'ObjectId') {
9
+ continue;
10
+ }
8
11
  if (doc?._id && typeof doc._id.toHexString === 'function') {
9
12
  doc.id = doc._id.toHexString();
10
13
  }
@@ -1 +1 @@
1
- {"version":3,"file":"mongoose-id.plugin.js","sourceRoot":"","sources":["../../../../src/core/common/plugins/mongoose-id.plugin.ts"],"names":[],"mappings":";;AAIA,4CASC;AATD,SAAgB,gBAAgB,CAAC,MAAM;IACrC,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,EAAE;QACzB,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QACtD,KAAK,MAAM,GAAG,IAAI,SAAS,EAAE,CAAC;YAC5B,IAAI,GAAG,EAAE,GAAG,IAAI,OAAO,GAAG,CAAC,GAAG,CAAC,WAAW,KAAK,UAAU,EAAE,CAAC;gBAC1D,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC;YACjC,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC"}
1
+ {"version":3,"file":"mongoose-id.plugin.js","sourceRoot":"","sources":["../../../../src/core/common/plugins/mongoose-id.plugin.ts"],"names":[],"mappings":";;AAIA,4CAkBC;AAlBD,SAAgB,gBAAgB,CAAC,MAAM;IACrC,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,EAAE;QACzB,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QACtD,KAAK,MAAM,GAAG,IAAI,SAAS,EAAE,CAAC;YAO5B,IAAI,GAAG,EAAE,SAAS,KAAK,UAAU,EAAE,CAAC;gBAClC,SAAS;YACX,CAAC;YACD,IAAI,GAAG,EAAE,GAAG,IAAI,OAAO,GAAG,CAAC,GAAG,CAAC,WAAW,KAAK,UAAU,EAAE,CAAC;gBAC1D,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC;YACjC,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -1,15 +1,27 @@
1
1
  import { Logger, OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
2
+ import { Agent as HttpAgent } from 'http';
3
+ import { Agent as HttpsAgent } from 'https';
2
4
  import { ConfigService } from './config.service';
3
5
  import type { IS3Config } from '../interfaces/server-options.interface';
4
6
  import type { S3Client } from '@aws-sdk/client-s3';
5
7
  import type { Readable } from 'stream';
8
+ export interface S3SocketPoolStats {
9
+ active: number;
10
+ free: number;
11
+ maxSockets: number;
12
+ waiting: number;
13
+ }
6
14
  export type NormalizedS3Config = Omit<IS3Config, 'enabled' | 'presignedDownloads'> & {
7
15
  bucket: string;
16
+ connectionTimeoutMs: number;
17
+ downloadIdleTimeoutMs: number;
8
18
  forcePathStyle: boolean;
19
+ maxSockets: number;
9
20
  presignedDownloads?: {
10
21
  expiresInSeconds: number;
11
22
  };
12
23
  region: string;
24
+ socketTimeoutMs: number;
13
25
  stagingBucket: string;
14
26
  };
15
27
  export declare class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
@@ -20,11 +32,22 @@ export declare class CoreS3Service implements OnApplicationShutdown, OnModuleIni
20
32
  protected sdk?: typeof import('@aws-sdk/client-s3');
21
33
  protected presigner?: typeof import('@aws-sdk/s3-request-presigner');
22
34
  protected multipartUploader?: null | typeof import('@aws-sdk/lib-storage');
35
+ protected agents?: {
36
+ http: HttpAgent;
37
+ https: HttpsAgent;
38
+ };
39
+ protected poolMonitor?: NodeJS.Timeout;
40
+ protected lastPoolReportAt: number;
41
+ protected idleClosedSinceReport: number;
23
42
  constructor(configService: ConfigService);
24
43
  protected clampPresignedExpiry(seconds: number): number;
25
44
  get enabled(): boolean;
26
45
  getConfig(): NormalizedS3Config | undefined;
27
46
  onModuleInit(): Promise<void>;
47
+ protected buildRequestHandlerOptions(): Record<string, unknown>;
48
+ getSocketPoolStats(): S3SocketPoolStats | undefined;
49
+ protected startPoolMonitor(): void;
50
+ protected checkSocketPool(): void;
28
51
  protected verifyBuckets(): Promise<void>;
29
52
  protected bucketExists(bucket: string): Promise<boolean>;
30
53
  getClient(): S3Client;
@@ -41,7 +64,10 @@ export declare class CoreS3Service implements OnApplicationShutdown, OnModuleIni
41
64
  protected copySource(bucket: string, key: string): string;
42
65
  protected isStream(body: unknown): body is Readable;
43
66
  protected collect(stream: Readable): Promise<Buffer>;
44
- getObject(key: string): Promise<{
67
+ getObject(key: string, options?: {
68
+ abortSignal?: AbortSignal;
69
+ idleTimeoutMs?: false | number;
70
+ }): Promise<{
45
71
  body: Readable;
46
72
  contentLength?: number;
47
73
  contentType?: string;
@@ -12,11 +12,24 @@ var CoreS3Service_1;
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports.CoreS3Service = void 0;
14
14
  const common_1 = require("@nestjs/common");
15
+ const http_1 = require("http");
16
+ const https_1 = require("https");
15
17
  const stream_1 = require("stream");
16
18
  const content_disposition_helper_1 = require("../helpers/content-disposition.helper");
19
+ const idle_stream_helper_1 = require("../helpers/idle-stream.helper");
17
20
  const config_service_1 = require("./config.service");
18
21
  const MAX_PRESIGNED_EXPIRY_SECONDS = 604_800;
19
22
  const PRESIGNED_EXPIRY_ADVISORY_SECONDS = 900;
23
+ const S3_DEFAULT_MAX_SOCKETS = 200;
24
+ const S3_DEFAULT_CONNECTION_TIMEOUT_MS = 15_000;
25
+ const S3_DEFAULT_SOCKET_TIMEOUT_MS = 120_000;
26
+ const S3_POOL_CHECK_INTERVAL_MS = 5_000;
27
+ const S3_POOL_REPORT_INTERVAL_MS = 60_000;
28
+ function positiveOrDefault(value, fallback) {
29
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
30
+ ? Math.min(value, idle_stream_helper_1.MAX_TIMER_DELAY_MS)
31
+ : fallback;
32
+ }
20
33
  let CoreS3Service = class CoreS3Service {
21
34
  static { CoreS3Service_1 = this; }
22
35
  configService;
@@ -26,6 +39,10 @@ let CoreS3Service = class CoreS3Service {
26
39
  sdk;
27
40
  presigner;
28
41
  multipartUploader;
42
+ agents;
43
+ poolMonitor;
44
+ lastPoolReportAt = 0;
45
+ idleClosedSinceReport = 0;
29
46
  constructor(configService) {
30
47
  this.configService = configService;
31
48
  const raw = this.configService.getFastButReadOnly('s3');
@@ -44,8 +61,11 @@ let CoreS3Service = class CoreS3Service {
44
61
  accessKeyId: raw.accessKeyId,
45
62
  autoCreateBucket: raw.autoCreateBucket ?? false,
46
63
  bucket: raw.bucket,
64
+ connectionTimeoutMs: positiveOrDefault(raw.connectionTimeoutMs, S3_DEFAULT_CONNECTION_TIMEOUT_MS),
65
+ downloadIdleTimeoutMs: positiveOrDefault(raw.downloadIdleTimeoutMs, idle_stream_helper_1.DEFAULT_STREAM_IDLE_TIMEOUT_MS),
47
66
  endpoint: raw.endpoint,
48
67
  forcePathStyle: raw.forcePathStyle ?? false,
68
+ maxSockets: Math.floor(positiveOrDefault(raw.maxSockets, S3_DEFAULT_MAX_SOCKETS)) || S3_DEFAULT_MAX_SOCKETS,
49
69
  presignedDownloads: presigned
50
70
  ? {
51
71
  expiresInSeconds: this.clampPresignedExpiry((typeof presigned === 'object' ? presigned.expiresInSeconds : undefined) ?? 300),
@@ -53,6 +73,7 @@ let CoreS3Service = class CoreS3Service {
53
73
  : undefined,
54
74
  region: raw.region ?? 'us-east-1',
55
75
  secretAccessKey: raw.secretAccessKey,
76
+ socketTimeoutMs: positiveOrDefault(raw.socketTimeoutMs, S3_DEFAULT_SOCKET_TIMEOUT_MS),
56
77
  stagingBucket: raw.stagingBucket ?? raw.bucket,
57
78
  };
58
79
  }
@@ -94,12 +115,64 @@ let CoreS3Service = class CoreS3Service {
94
115
  this.client = new this.sdk.S3Client({
95
116
  ...(endpoint ? { endpoint } : {}),
96
117
  forcePathStyle,
118
+ requestHandler: this.buildRequestHandlerOptions(),
97
119
  region,
98
120
  ...(accessKeyId && secretAccessKey ? { credentials: { accessKeyId, secretAccessKey } } : {}),
99
121
  });
100
122
  await this.loadMultipartUploader();
123
+ this.startPoolMonitor();
101
124
  await this.verifyBuckets();
102
125
  }
126
+ buildRequestHandlerOptions() {
127
+ const { connectionTimeoutMs, maxSockets, socketTimeoutMs } = this.config;
128
+ this.agents = {
129
+ http: new http_1.Agent({ keepAlive: true, maxSockets }),
130
+ https: new https_1.Agent({ keepAlive: true, maxSockets }),
131
+ };
132
+ return {
133
+ connectionTimeout: connectionTimeoutMs,
134
+ httpAgent: this.agents.http,
135
+ httpsAgent: this.agents.https,
136
+ socketTimeout: socketTimeoutMs,
137
+ };
138
+ }
139
+ getSocketPoolStats() {
140
+ if (!this.agents || !this.config) {
141
+ return undefined;
142
+ }
143
+ const count = (map) => Object.values(map ?? {}).reduce((sum, list) => sum + (list?.length ?? 0), 0);
144
+ const agents = [this.agents.http, this.agents.https];
145
+ return {
146
+ active: agents.reduce((sum, agent) => sum + count(agent.sockets), 0),
147
+ free: agents.reduce((sum, agent) => sum + count(agent.freeSockets), 0),
148
+ maxSockets: this.config.maxSockets,
149
+ waiting: agents.reduce((sum, agent) => sum + count(agent.requests), 0),
150
+ };
151
+ }
152
+ startPoolMonitor() {
153
+ if (this.poolMonitor) {
154
+ return;
155
+ }
156
+ this.poolMonitor = setInterval(() => this.checkSocketPool(), S3_POOL_CHECK_INTERVAL_MS);
157
+ this.poolMonitor.unref?.();
158
+ }
159
+ checkSocketPool() {
160
+ const stats = this.getSocketPoolStats();
161
+ if (!stats || stats.waiting === 0) {
162
+ return;
163
+ }
164
+ const now = Date.now();
165
+ if (now - this.lastPoolReportAt < S3_POOL_REPORT_INTERVAL_MS) {
166
+ return;
167
+ }
168
+ this.lastPoolReportAt = now;
169
+ this.logger.error(`S3 socket pool exhausted: ${stats.active}/${stats.maxSockets} sockets in use, ${stats.waiting} request(s) ` +
170
+ `waiting for a socket, ${this.idleClosedSinceReport} download stream(s) closed for lack of progress since the ` +
171
+ 'last report. Every S3 request waits until a socket is free. Raise s3.maxSockets if this is genuine load; ' +
172
+ 'a growing count without load points to download streams that are not consumed or destroyed — deliver files ' +
173
+ 'with pipeFileToResponse().');
174
+ this.idleClosedSinceReport = 0;
175
+ }
103
176
  async verifyBuckets() {
104
177
  const buckets = [...new Set([this.config.bucket, this.config.stagingBucket])];
105
178
  for (const bucket of buckets) {
@@ -251,11 +324,17 @@ let CoreS3Service = class CoreS3Service {
251
324
  }
252
325
  return Buffer.concat(chunks);
253
326
  }
254
- async getObject(key) {
327
+ async getObject(key, options) {
255
328
  const { client, config, sdk } = this.requireInit();
256
- const result = await client.send(new sdk.GetObjectCommand({ Bucket: config.bucket, Key: key }));
329
+ const idleMs = options?.idleTimeoutMs;
330
+ const result = await client.send(new sdk.GetObjectCommand({ Bucket: config.bucket, Key: key }), options?.abortSignal ? { abortSignal: options.abortSignal } : undefined);
257
331
  return {
258
- body: result.Body,
332
+ body: (0, idle_stream_helper_1.guardIdleStream)(result.Body, {
333
+ idleMs: idleMs === false ? false : (idleMs ?? config.downloadIdleTimeoutMs),
334
+ onIdle: () => {
335
+ this.idleClosedSinceReport++;
336
+ },
337
+ }),
259
338
  contentLength: result.ContentLength,
260
339
  contentType: result.ContentType,
261
340
  };
@@ -311,8 +390,15 @@ let CoreS3Service = class CoreS3Service {
311
390
  }
312
391
  }
313
392
  async onApplicationShutdown() {
393
+ if (this.poolMonitor) {
394
+ clearInterval(this.poolMonitor);
395
+ this.poolMonitor = undefined;
396
+ }
314
397
  this.client?.destroy();
315
398
  this.client = undefined;
399
+ this.agents?.http.destroy();
400
+ this.agents?.https.destroy();
401
+ this.agents = undefined;
316
402
  }
317
403
  requireInit() {
318
404
  if (!this.config) {
@@ -1 +1 @@
1
- {"version":3,"file":"core-s3.service.js","sourceRoot":"","sources":["../../../../src/core/common/services/core-s3.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,2CAAyF;AACzF,mCAAqC;AAErC,sFAAgF;AAChF,qDAAiD;AAYjD,MAAM,4BAA4B,GAAG,OAAO,CAAC;AAY7C,MAAM,iCAAiC,GAAG,GAAG,CAAC;AA2BvC,IAAM,aAAa,GAAnB,MAAM,aAAa;;IA+BO;IA9BZ,MAAM,GAAG,IAAI,eAAM,CAAC,eAAa,CAAC,IAAI,CAAC,CAAC;IAGjD,MAAM,CAAsB;IAG5B,MAAM,CAAY;IAGlB,GAAG,CAAuC;IAS1C,SAAS,CAAkD;IAU3D,iBAAiB,CAA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CAAC;QACvB,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC;QAC5B,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;QAC7B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;IAC1B,CAAC;IAKS,WAAW;QACnB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;QACrE,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;YAC9B,MAAM,IAAI,KAAK,CAAC,6DAA6D,CAAC,CAAC;QACjF,CAAC;QACD,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC;IACrE,CAAC;;AAnuBU,sCAAa;wBAAb,aAAa;IADzB,IAAA,mBAAU,GAAE;qCA6CmC,8BAAa;GA5ChD,aAAa,CAouBzB"}
@@ -71,22 +71,26 @@ let CoreAiController = class CoreAiController {
71
71
  return this.aiService.prompt(input, serviceOptions);
72
72
  }
73
73
  async stream(serviceOptions, input, res) {
74
- res.setHeader('Cache-Control', 'no-cache');
74
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
75
75
  res.setHeader('Connection', 'keep-alive');
76
76
  res.setHeader('Content-Type', 'text/event-stream');
77
77
  res.setHeader('X-Accel-Buffering', 'no');
78
78
  res.flushHeaders?.();
79
+ const send = (chunk) => {
80
+ res.write(chunk);
81
+ res.flush?.();
82
+ };
79
83
  const heartbeat = setInterval(() => {
80
- res.write(': keep-alive\n\n');
84
+ send(': keep-alive\n\n');
81
85
  }, 15_000);
82
86
  heartbeat.unref?.();
83
87
  try {
84
88
  for await (const event of this.aiService.promptStream(input, serviceOptions)) {
85
- res.write(`data: ${JSON.stringify(event)}\n\n`);
89
+ send(`data: ${JSON.stringify(event)}\n\n`);
86
90
  }
87
91
  }
88
92
  catch (err) {
89
- res.write(`data: ${JSON.stringify({ message: err.message, type: 'error' })}\n\n`);
93
+ send(`data: ${JSON.stringify({ message: err.message, type: 'error' })}\n\n`);
90
94
  }
91
95
  finally {
92
96
  clearInterval(heartbeat);