@lenne.tech/nest-server 11.46.3 → 11.46.5

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 (59) hide show
  1. package/.claude/rules/configurable-features.md +1 -1
  2. package/.claude/rules/testing.md +4 -4
  3. package/FRAMEWORK-API.md +1 -1
  4. package/dist/core/common/helpers/byte-range.helper.d.ts +8 -0
  5. package/dist/core/common/helpers/byte-range.helper.js +76 -0
  6. package/dist/core/common/helpers/byte-range.helper.js.map +1 -0
  7. package/dist/core/common/helpers/gridfs.helper.d.ts +7 -2
  8. package/dist/core/common/helpers/gridfs.helper.js +7 -4
  9. package/dist/core/common/helpers/gridfs.helper.js.map +1 -1
  10. package/dist/core/common/services/core-s3.service.d.ts +3 -0
  11. package/dist/core/common/services/core-s3.service.js +8 -1
  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/error-code/error-codes.d.ts +9 -0
  16. package/dist/core/modules/error-code/error-codes.js +8 -0
  17. package/dist/core/modules/error-code/error-codes.js.map +1 -1
  18. package/dist/core/modules/file/core-file.controller.d.ts +6 -0
  19. package/dist/core/modules/file/core-file.controller.js +94 -26
  20. package/dist/core/modules/file/core-file.controller.js.map +1 -1
  21. package/dist/core/modules/file/core-file.service.d.ts +2 -0
  22. package/dist/core/modules/file/core-file.service.js +17 -6
  23. package/dist/core/modules/file/core-file.service.js.map +1 -1
  24. package/dist/core/modules/file/filesystem-file.helper.d.ts +2 -1
  25. package/dist/core/modules/file/filesystem-file.helper.js +2 -2
  26. package/dist/core/modules/file/filesystem-file.helper.js.map +1 -1
  27. package/dist/core/modules/file/interfaces/file-service-options.interface.d.ts +2 -0
  28. package/dist/core/modules/file/s3-file.helper.d.ts +2 -0
  29. package/dist/core/modules/file/s3-file.helper.js.map +1 -1
  30. package/dist/index.d.ts +1 -0
  31. package/dist/index.js +1 -0
  32. package/dist/index.js.map +1 -1
  33. package/dist/server/modules/error-code/error-codes.d.ts +1 -0
  34. package/dist/test/test.helper.d.ts +1 -0
  35. package/dist/test/test.helper.js +6 -0
  36. package/dist/test/test.helper.js.map +1 -1
  37. package/dist/tsconfig.build.tsbuildinfo +1 -1
  38. package/docs/REQUEST-LIFECYCLE.md +1 -1
  39. package/docs/error-codes.md +14 -0
  40. package/docs/security-overrides.md +21 -6
  41. package/migration-guides/11.46.2-to-11.46.3.md +15 -3
  42. package/migration-guides/11.46.3-to-11.46.4.md +75 -0
  43. package/migration-guides/11.46.4-to-11.46.5.md +183 -0
  44. package/package.json +6 -6
  45. package/src/core/common/helpers/byte-range.helper.ts +144 -0
  46. package/src/core/common/helpers/gridfs.helper.ts +20 -6
  47. package/src/core/common/services/core-s3.service.ts +16 -2
  48. package/src/core/modules/ai/core-ai.controller.ts +12 -4
  49. package/src/core/modules/error-code/error-codes.ts +13 -0
  50. package/src/core/modules/file/INTEGRATION-CHECKLIST.md +17 -15
  51. package/src/core/modules/file/README.md +91 -3
  52. package/src/core/modules/file/core-file.controller.ts +202 -32
  53. package/src/core/modules/file/core-file.service.ts +33 -13
  54. package/src/core/modules/file/filesystem-file.helper.ts +8 -3
  55. package/src/core/modules/file/interfaces/file-service-options.interface.ts +13 -0
  56. package/src/core/modules/file/s3-file.helper.ts +3 -2
  57. package/src/index.ts +1 -0
  58. package/src/test/README.md +8 -4
  59. package/src/test/test.helper.ts +12 -0
@@ -6,6 +6,7 @@ import { PassThrough } from 'stream';
6
6
  import { buildContentDisposition } from '../helpers/content-disposition.helper';
7
7
  import { DEFAULT_STREAM_IDLE_TIMEOUT_MS, guardIdleStream, MAX_TIMER_DELAY_MS } from '../helpers/idle-stream.helper';
8
8
  import { ConfigService } from './config.service';
9
+ import { assertByteRange, type ByteRange } from '../helpers/byte-range.helper';
9
10
 
10
11
  import type { IS3Config } from '../interfaces/server-options.interface';
11
12
  import type { S3Client } from '@aws-sdk/client-s3';
@@ -687,6 +688,11 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
687
688
  /**
688
689
  * Get an object stream (plus metadata) from the main bucket.
689
690
  * Throws the SDK's NoSuchKey error when the object does not exist.
691
+ *
692
+ * With `range`, only those bytes are read (`Range: bytes=<start>-<end>`, end inclusive): `contentLength` is then
693
+ * the length of the range and `contentRange` S3's `bytes <start>-<end>/<total>`. The range must lie inside the
694
+ * object — a range starting past its end is refused by S3 with `InvalidRange`; `resolveDownloadRange()` produces a
695
+ * valid one from a request's `Range` header. A malformed range throws a `RangeError` before S3 is asked.
690
696
  */
691
697
  async getObject(
692
698
  key: string,
@@ -698,14 +704,21 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
698
704
  * its turn comes) AND is certain to read it to the end or destroy it; such a body holds its socket until then.
699
705
  */
700
706
  idleTimeoutMs?: false | number;
707
+ /** Read only these bytes (both inclusive). Since 11.46.5. */
708
+ range?: ByteRange;
701
709
  },
702
- ): Promise<{ body: Readable; contentLength?: number; contentType?: string }> {
710
+ ): Promise<{ body: Readable; contentLength?: number; contentRange?: string; contentType?: string }> {
703
711
  const { client, config, sdk } = this.requireInit();
712
+ const range = assertByteRange(options?.range);
704
713
  // `abortSignal`: a caller whose client has gone aborts the request, also while it still waits for a socket —
705
714
  // otherwise it stays queued and takes a socket and a body later, for nobody (see `IS3Config.maxSockets`)
706
715
  const idleMs = options?.idleTimeoutMs;
707
716
  const result = await client.send(
708
- new sdk.GetObjectCommand({ Bucket: config.bucket, Key: key }),
717
+ new sdk.GetObjectCommand({
718
+ Bucket: config.bucket,
719
+ Key: key,
720
+ ...(range ? { Range: `bytes=${range.start}-${range.end}` } : {}),
721
+ }),
709
722
  options?.abortSignal ? { abortSignal: options.abortSignal } : undefined,
710
723
  );
711
724
  return {
@@ -720,6 +733,7 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
720
733
  },
721
734
  }),
722
735
  contentLength: result.ContentLength,
736
+ ...(result.ContentRange ? { contentRange: result.ContentRange } : {}),
723
737
  contentType: result.ContentType,
724
738
  };
725
739
  }
@@ -93,7 +93,9 @@ export class CoreAiController {
93
93
  @Body() input: CoreAiPromptInput,
94
94
  @Res() res: Response,
95
95
  ): Promise<void> {
96
- res.setHeader('Cache-Control', 'no-cache');
96
+ // `no-transform` keeps a `compression` middleware out of the stream: gzip would otherwise hold every event until
97
+ // the response ends (measured: events written at 0, 300 and 600 ms all arrived together at about 900 ms)
98
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
97
99
  res.setHeader('Connection', 'keep-alive');
98
100
  res.setHeader('Content-Type', 'text/event-stream');
99
101
  // Disable proxy-side response buffering (nginx and friends honour this); without
@@ -107,17 +109,23 @@ export class CoreAiController {
107
109
  // idle connection at 60 s, which the client then sees as a turn that silently
108
110
  // vanished. Comment frames are ignored by every SSE client and keep the
109
111
  // connection observably alive.
112
+ // A compressor that ignores `no-transform` still sends what was written once it is flushed (`compression` adds
113
+ // `flush()` to the response)
114
+ const send = (chunk: string) => {
115
+ res.write(chunk);
116
+ (res as Response & { flush?: () => void }).flush?.();
117
+ };
110
118
  const heartbeat = setInterval(() => {
111
- res.write(': keep-alive\n\n');
119
+ send(': keep-alive\n\n');
112
120
  }, 15_000);
113
121
  heartbeat.unref?.();
114
122
 
115
123
  try {
116
124
  for await (const event of this.aiService.promptStream(input, serviceOptions)) {
117
- res.write(`data: ${JSON.stringify(event)}\n\n`);
125
+ send(`data: ${JSON.stringify(event)}\n\n`);
118
126
  }
119
127
  } catch (err) {
120
- res.write(`data: ${JSON.stringify({ message: (err as Error).message, type: 'error' })}\n\n`);
128
+ send(`data: ${JSON.stringify({ message: (err as Error).message, type: 'error' })}\n\n`);
121
129
  } finally {
122
130
  clearInterval(heartbeat);
123
131
  res.end();
@@ -568,6 +568,19 @@ export const LtnsErrors = {
568
568
  },
569
569
  },
570
570
 
571
+ /**
572
+ * A download asked for a byte range that starts at or past the end of the file (`Range` header, HTTP 416). The
573
+ * response carries `Content-Range: bytes * /<length>` (without the space), so the client learns the real size.
574
+ */
575
+ FILE_RANGE_NOT_SATISFIABLE: {
576
+ code: 'LTNS_0503',
577
+ message: 'Requested range not satisfiable',
578
+ translations: {
579
+ de: 'Der angeforderte Bereich liegt außerhalb der Datei.',
580
+ en: 'The requested range lies outside the file.',
581
+ },
582
+ },
583
+
571
584
  // =====================================================
572
585
  // Internal Errors (LTNS_0900-LTNS_0999)
573
586
  // =====================================================
@@ -226,18 +226,20 @@ personal or medical, a per-file rule is not optional.
226
226
 
227
227
  ## Common Mistakes
228
228
 
229
- | Mistake | Symptom | Fix |
230
- | -------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
231
- | Overriding `getFileById` to add Swagger decorators | `file.downloadRoles` silently ignored | Don't override; document at class level |
232
- | Overriding without re-declaring `@Get(...)` | Route 404s for everyone, no error logged | Don't override |
233
- | `downloadRoles: []` | Warning logged, default applied | Use a non-empty array; `[]` would read as "no roles required" and open the route |
234
- | Expecting `metadata` back from `getFileInfo()` | `undefined` | Use `getRawFileInfo()` inside `checkRights()` |
235
- | `downloadRoles: ['member']` with multiTenancy | Works from code, fails from `<img>` | Both file classes carry `@SkipTenantCheck()`; roles resolve against `user.roles`. Use `checkRights()` for tenant rules |
236
- | Signed-in user can upload via TUS but not download | 403 on their own file | `tus.roles` and `file.downloadRoles` are separate. Add an owner to the metadata and authorize per file |
237
- | Rule narrows only `'id'` / `'filename'` | `findFileInfo()` returns every file | Refuse `'filterArgs'`; force a per-user filter server-side with `{ force: true }` |
238
- | Treating the file id as unguessable | Enumerable inventory | Ids share a per-process random part and an incrementing counter — authorize every read, do not rely on the id |
239
- | Approving the caller's `filterArgs` as "narrowed" | Bypass via a different filter shape | `filterArgs` is client-controlled. Override the filter; never approve it |
240
- | `super(connection)` in `FileService` with `file.storage: 's3'` | Boot fails: "that storage is not available" | Forward `{ configService, s3Service }` — step 6 |
241
- | Own download route with `stream.pipe(res)` | After enough aborted downloads every S3 request hangs; health check stays green | `pipeFileToResponse(stream, res)` — it destroys the source when the response closes (README, "Delivering a file from your own route") |
242
- | S3 packages in `devDependencies` | Production image cannot load S3 | Move them to `dependencies` — step 6 |
243
- | A quota aggregating only `fs.files` | Reads 0 on the S3 / filesystem driver | Aggregate `fs.files`, `filesystem-files` and `s3-files` — step 6 |
229
+ | Mistake | Symptom | Fix |
230
+ | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
231
+ | Overriding `getFileById` to add Swagger decorators | `file.downloadRoles` silently ignored | Don't override; document at class level |
232
+ | Overriding without re-declaring `@Get(...)` | Route 404s for everyone, no error logged | Don't override |
233
+ | `downloadRoles: []` | Warning logged, default applied | Use a non-empty array; `[]` would read as "no roles required" and open the route |
234
+ | Expecting `metadata` back from `getFileInfo()` | `undefined` | Use `getRawFileInfo()` inside `checkRights()` |
235
+ | `downloadRoles: ['member']` with multiTenancy | Works from code, fails from `<img>` | Both file classes carry `@SkipTenantCheck()`; roles resolve against `user.roles`. Use `checkRights()` for tenant rules |
236
+ | Signed-in user can upload via TUS but not download | 403 on their own file | `tus.roles` and `file.downloadRoles` are separate. Add an owner to the metadata and authorize per file |
237
+ | Rule narrows only `'id'` / `'filename'` | `findFileInfo()` returns every file | Refuse `'filterArgs'`; force a per-user filter server-side with `{ force: true }` |
238
+ | Treating the file id as unguessable | Enumerable inventory | Ids share a per-process random part and an incrementing counter — authorize every read, do not rely on the id |
239
+ | Approving the caller's `filterArgs` as "narrowed" | Bypass via a different filter shape | `filterArgs` is client-controlled. Override the filter; never approve it |
240
+ | `super(connection)` in `FileService` with `file.storage: 's3'` | Boot fails: "that storage is not available" | Forward `{ configService, s3Service }` — step 6 |
241
+ | Own download route with `stream.pipe(res)` | After enough aborted downloads every S3 request hangs; health check stays green | `pipeFileToResponse(stream, res)` — it destroys the source when the response closes (README, "Delivering a file from your own route") |
242
+ | Own download route passing `downloadAbortSignal(res)` to `getFileStream()` without `openDownloadStream()` | Every client that leaves before S3 answers logs `ERROR [ExceptionsHandler] … AbortError` with a stack trace; a busy store answers 500 instead of 503 | Open the stream with `openDownloadStream(res, () => getFileStream(…))` and end the route with `return res` on `RESPONSE_GONE` (11.46.4+) |
243
+ | Own video/audio route that ignores `Range` | Plays in Chrome, not in Safari (no `206` for `Range`); seeking reloads the whole file | `resolveDownloadRange()` + `getFileStream(id, { range })` + `setDownloadRangeHeaders()` (11.46.5+, README "Byte ranges") |
244
+ | S3 packages in `devDependencies` | Production image cannot load S3 | Move them to `dependencies` — step 6 |
245
+ | A quota aggregating only `fs.files` | Reads 0 on the S3 / filesystem driver | Aggregate `fs.files`, `filesystem-files` and `s3-files` — step 6 |
@@ -11,6 +11,9 @@ File upload and download functionality with MongoDB GridFS storage.
11
11
  | GET | `/files/id/:id` | Download file by ID | `downloadRoles` |
12
12
  | GET | `/files/:filename` | Download file by filename | `downloadRoles` |
13
13
 
14
+ Both answer a `Range` request with `206 Partial Content` (11.46.5+) — see
15
+ [Byte ranges](#byte-ranges-video-audio-resumed-downloads-1293).
16
+
14
17
  ### GraphQL members (via CoreFileResolver)
15
18
 
16
19
  | Member | Kind | Gated by |
@@ -474,7 +477,8 @@ export class FileController extends CoreFileController {
474
477
  The mid-stream failure case is handled by `pipeFileToResponse()`. Without it the stream error would
475
478
  go unhandled, Node would destroy the socket, and a reverse proxy would report **502 Bad Gateway** —
476
479
  i.e. "the server is down", while every other route keeps answering. On the error path the headers
477
- describing the file (`Content-Type`, `Content-Disposition`, `Cache-Control`, `ETag`) are removed, so
480
+ describing the file (`Content-Type`, `Content-Disposition`, `Cache-Control`, `ETag`, and since 11.46.5 `Content-Range`
481
+ and `Accept-Ranges`) are removed, so
478
482
  the JSON body is not labelled as the image it failed to deliver. The error itself is logged
479
483
  server-side even though the client answer stays deliberately generic.
480
484
 
@@ -486,6 +490,9 @@ on the controller rather than the exported function of the same name.
486
490
  | `If-None-Match` names the file's weak `ETag` (`W/"<id>"`), after the rights check | `304` | No body; the store is not read |
487
491
  | The store hands out no connection within 3 attempts of `s3.connectionTimeoutMs` (pool busy) | `503` | `Retry-After: 5`; the store is busy, not broken |
488
492
  | The client left before the stream was handed over | — | Nothing is sent; the stream is destroyed at once, a pending S3 request aborted |
493
+ | The client left mid-transfer and the store reports the abort (S3: `aborted`) (11.46.5+) | — | Nothing is sent; logged at debug, never as ERROR |
494
+ | `Range` names one range inside the file (11.46.5+) | `206` | `Content-Range: bytes <start>-<end>/<length>`, only those bytes |
495
+ | `Range` starts at or past the end of the file (11.46.5+) | `416` | `Content-Range: bytes */<length>`, `ErrorCode.FILE_RANGE_NOT_SATISFIABLE` |
489
496
 
490
497
  ### Delivering a file from your own route (11.46.3)
491
498
 
@@ -496,10 +503,25 @@ check stays green. A production outage had exactly this cause. `pipeFileToRespon
496
503
  client goes — on the response's `close`, the request's `close` before its end or the socket's `end`/`close`, and at once when the client
497
504
  had already gone before the call — and answers a store error before the first byte with `404`.
498
505
 
506
+ **Open the stream with `openDownloadStream(res, open)` (11.46.4+)**, the function the framework's own routes use. It
507
+ does not ask the store when the client has already gone, destroys a stream that arrives after the client left, and
508
+ answers `503` with `Retry-After` when the store hands out no connection in time. It also turns a store request that
509
+ failed BECAUSE the client left into `RESPONSE_GONE`: an S3 request aborted through `downloadAbortSignal(res)` rejects
510
+ with `AbortError`, and without it every aborted download is an ERROR with a stack trace in the log and a `500` sent
511
+ into a closed response — under the load the `S3 socket pool exhausted:` line has to stand out in.
512
+
499
513
  ```typescript
500
- import { downloadAbortSignal, pipeFileToResponse } from '@lenne.tech/nest-server';
514
+ import { downloadAbortSignal, openDownloadStream, pipeFileToResponse, RESPONSE_GONE } from '@lenne.tech/nest-server';
501
515
 
502
- const stream = await this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser });
516
+ const stream = await openDownloadStream(res, () =>
517
+ this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser }),
518
+ );
519
+ if (stream === RESPONSE_GONE) {
520
+ return res; // nobody left to deliver to
521
+ }
522
+ if (!stream) {
523
+ throw new NotFoundException();
524
+ }
503
525
  return pipeFileToResponse(stream, res);
504
526
  ```
505
527
 
@@ -523,6 +545,72 @@ Layers below it, each effective on its own:
523
545
  waits for a socket instead of taking one later. The framework's routes do this.
524
546
  - `s3.presignedDownloads` moves the bytes off the API entirely (a `302` to S3) — consider it for public files.
525
547
 
548
+ ### Byte ranges: video, audio, resumed downloads (11.46.5)
549
+
550
+ Safari refuses to play a video — and stalls audio — from a server that answers a `Range` request with `200` and the
551
+ whole file. Chrome plays it anyway, so the problem does not show locally or in a Chromium-based Playwright run. Media
552
+ players seek with ranges, download managers resume with them.
553
+
554
+ The framework's download routes answer ranges on every store. For a route of your own, three pieces:
555
+
556
+ | Piece | What it does |
557
+ | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
558
+ | `resolveDownloadRange(res, length)` | Reads `Range` from the request. Returns the range (`{ start, end }`, both inclusive) or `undefined` for the whole file; THROWS `416` with `Content-Range: bytes */<length>` for a range past the end. Call it after the rights check — a 416 confirms that the file exists |
559
+ | `getFileStream(id, { range })` | Reads only those bytes: S3 with a ranged `GetObject`, GridFS from the chunk holding the first byte, the filesystem from that offset. Same idle guard and abort signal as a whole file; `getFileStreamByName()` and `CoreS3Service.getObject(key, { range })` take it too |
560
+ | `setDownloadRangeHeaders(res, range, length)` | `Accept-Ranges: bytes`; for a range `206`, `Content-Range`, the range's `Content-Length` and `no-transform` in `Cache-Control`. Call it after your own headers, right before `pipeFileToResponse()` |
561
+
562
+ ```typescript
563
+ import {
564
+ downloadAbortSignal,
565
+ openDownloadStream,
566
+ pipeFileToResponse,
567
+ resolveDownloadRange,
568
+ RESPONSE_GONE,
569
+ setDownloadRangeHeaders,
570
+ } from '@lenne.tech/nest-server';
571
+
572
+ @Get('video/:id')
573
+ async video(@Param('id') id: string, @Res() res: Response, @CurrentUser() currentUser) {
574
+ const serviceOptions = { abortSignal: downloadAbortSignal(res), currentUser };
575
+ const resolved = await this.fileService.resolveFile(id, serviceOptions); // rights check, length, store
576
+ if (!resolved) {
577
+ throw new NotFoundException();
578
+ }
579
+ const range = resolveDownloadRange(res, resolved.info.length); // throws 416 past the end
580
+ const stream = await openDownloadStream(res, () =>
581
+ this.fileService.getFileStream(id, { ...serviceOptions, range }, resolved.store),
582
+ );
583
+ if (stream === RESPONSE_GONE) {
584
+ return res;
585
+ }
586
+ if (!stream) {
587
+ throw new NotFoundException();
588
+ }
589
+ res.header('Content-Type', resolved.info.contentType || 'video/mp4');
590
+ res.header('Cache-Control', 'private, no-store');
591
+ setDownloadRangeHeaders(res, range, resolved.info.length);
592
+ return pipeFileToResponse(stream, res);
593
+ }
594
+ ```
595
+
596
+ What is served, and why:
597
+
598
+ - **One range per request.** Several ranges (`bytes=0-1,5-9`) get the whole file with `200` — a `multipart/byteranges`
599
+ answer is not built, the way Express's `send` handles it. Every media player asks for one range at a time.
600
+ - **A range past the end is cut at the last byte** (`bytes=0-999999999` is the whole file), a suffix longer than the
601
+ file is the whole file. Only a range STARTING at or past the end is `416`, and every range of an empty file.
602
+ - **An invalid header** (`bytes=5-2`, another unit) is ignored: the whole file with `200`, which every client can use.
603
+ - **`If-Range` gets the whole file.** The routes' validator is a weak `ETag`, which `If-Range` never matches
604
+ (RFC 9110 §13.1.5). A route with a strong validator can decide `If-Range` itself and call `parseRangeHeader()`.
605
+ - **`no-transform` on a `206`** keeps `compression` away: a gzipped partial body would no longer match the offsets in
606
+ its `Content-Range`. A whole file is compressed as before (when its type is compressible).
607
+ - **`range` on the service must lie inside the file** — `resolveDownloadRange()` guarantees it. A malformed range
608
+ (negative, not an integer, `start > end`) throws a `RangeError` before any store is asked; a range reaching past the
609
+ end of the file is not checked by the service and fails per store (GridFS: an error on the stream, S3: `InvalidRange`
610
+ for a start past the end).
611
+ - **Presigned downloads** (`s3.presignedDownloads`) redirect before any of this: the browser sends its `Range` to S3,
612
+ which answers it itself.
613
+
526
614
  ### Upload filtering
527
615
 
528
616
  Upload endpoints are project-specific, but the filter they install comes from the framework
@@ -2,6 +2,8 @@ import {
2
2
  BadRequestException,
3
3
  Controller,
4
4
  Get,
5
+ HttpException,
6
+ HttpStatus,
5
7
  Logger,
6
8
  NotFoundException,
7
9
  Param,
@@ -21,6 +23,7 @@ import { ErrorCode } from '../error-code/error-codes';
21
23
  import { SkipTenantCheck } from '../tenant/core-tenant.decorators';
22
24
  import { CoreFileService } from './core-file.service';
23
25
  import type { FileServiceOptions } from './interfaces/file-service-options.interface';
26
+ import { type ByteRange, contentRangeValue, parseRangeHeader } from '../../common/helpers/byte-range.helper';
24
27
 
25
28
  const fileStreamLogger = new Logger('CoreFileController');
26
29
 
@@ -141,7 +144,15 @@ export const RESPONSE_GONE = Symbol('lt.responseGone');
141
144
  * ofetch/`$fetch` client picks its parser from that header and hands the caller a
142
145
  * Blob instead of the error message.
143
146
  */
144
- const FILE_DELIVERY_HEADERS = ['Cache-Control', 'Content-Disposition', 'Content-Length', 'Content-Type', 'ETag'];
147
+ const FILE_DELIVERY_HEADERS = [
148
+ 'Accept-Ranges',
149
+ 'Cache-Control',
150
+ 'Content-Disposition',
151
+ 'Content-Length',
152
+ 'Content-Range',
153
+ 'Content-Type',
154
+ 'ETag',
155
+ ];
145
156
 
146
157
  /**
147
158
  * Re-exported from the leaf it now lives in, so no import path broke.
@@ -222,6 +233,23 @@ export function pipeFileToResponse(stream: Readable, res: Response): Response {
222
233
  .json({ error: 'Service Unavailable', message: 'File storage is busy, please retry', statusCode: 503 });
223
234
  return;
224
235
  }
236
+ // The client has gone, and the store reports the abort that followed. Not a server error: nobody receives an
237
+ // answer any more, so no ERROR line per aborted download and no status. The order is the reason this cannot be
238
+ // left to the release listeners above: `downloadAbortSignal()` registers its listeners first (it must, the client
239
+ // may leave during the rights check), so on the event that reports the client gone it aborts the S3 request
240
+ // BEFORE this function's own listener runs, and the SDK fails the body with `aborted` inside that same dispatch.
241
+ // Measured through the Nest route (a GET whose request is not read to its end, so its `close` reports the
242
+ // abort): every aborted S3 download logged `File download failed: aborted` — one ERROR per seek of a video
243
+ // player, burying the `S3 socket pool exhausted:` line. A store error while the client is still there stays an
244
+ // ERROR below.
245
+ if (state.responseClosed || state.clientGoneSignal || isResponseGone(res)) {
246
+ state.clientGoneSignal ||= 'store error after the client left';
247
+ fileStreamLogger.debug(`File download ended after the client left: ${err.message}`);
248
+ if (!res.destroyed) {
249
+ res.destroy();
250
+ }
251
+ return;
252
+ }
225
253
  // The answer to the CLIENT stays deliberately indistinguishable from an
226
254
  // unknown id, but the server must not lose the event: a files document
227
255
  // without its chunks is data corruption, and an error silently converted
@@ -310,6 +338,152 @@ export function downloadAbortSignal(res: Response): AbortSignal {
310
338
  return controller.signal;
311
339
  }
312
340
 
341
+ /**
342
+ * Open a download stream unless the client has already gone, and release a stream that arrives after it left — the
343
+ * framework's download routes use it, and so should a project's own (with {@link pipeFileToResponse} for delivery):
344
+ *
345
+ * ```typescript
346
+ * const stream = await openDownloadStream(res, () =>
347
+ * this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser }),
348
+ * );
349
+ * if (stream === RESPONSE_GONE) {
350
+ * return res;
351
+ * }
352
+ * if (!stream) {
353
+ * throw new NotFoundException();
354
+ * }
355
+ * return pipeFileToResponse(stream, res);
356
+ * ```
357
+ *
358
+ * Answers {@link RESPONSE_GONE} when there is nobody left to deliver to — end the route with `return res` then:
359
+ * - the client had gone before the store was asked;
360
+ * - the store request failed because the client left meanwhile. An S3 request aborted through
361
+ * {@link downloadAbortSignal} rejects with `AbortError`; rethrown, every aborted download became an ERROR with a
362
+ * stack trace in the log and a 500 sent into a closed response, under exactly the load the log line
363
+ * `S3 socket pool exhausted:` has to stand out in;
364
+ * - the stream arrived after the client left — it is destroyed here, so its socket, file handle or cursor is free at
365
+ * once.
366
+ *
367
+ * A store that handed out no connection in time (`TimeoutError`, see `s3.connectionTimeoutMs`) answers `503` with
368
+ * `Retry-After: 5`. Any other error is rethrown. `null` or `undefined` (the service's rights check refused) is passed
369
+ * on unchanged.
370
+ */
371
+ export async function openDownloadStream<T extends null | Readable | undefined>(
372
+ res: Response,
373
+ open: () => Promise<T>,
374
+ ): Promise<T | typeof RESPONSE_GONE> {
375
+ if (isResponseGone(res)) {
376
+ return RESPONSE_GONE;
377
+ }
378
+ let stream: T;
379
+ try {
380
+ stream = await open();
381
+ } catch (error) {
382
+ if (isResponseGone(res)) {
383
+ return RESPONSE_GONE;
384
+ }
385
+ // The store did not hand out a connection in time (`s3.connectionTimeoutMs`, which includes the wait for a
386
+ // free socket): the store is busy, not broken, and the client may try again — 503, not 500
387
+ if ((error as { name?: string })?.name === 'TimeoutError') {
388
+ fileStreamLogger.warn(`File store busy, download answered 503: ${(error as Error).message}`);
389
+ res.header('Retry-After', '5');
390
+ throw new ServiceUnavailableException('File storage is busy, please retry');
391
+ }
392
+ throw error;
393
+ }
394
+ if (stream && isResponseGone(res)) {
395
+ stream.destroy();
396
+ return RESPONSE_GONE;
397
+ }
398
+ return stream;
399
+ }
400
+
401
+ /**
402
+ * Which bytes of a file a download request asks for — the `Range` header, resolved against the file's `length`.
403
+ *
404
+ * WHY: a server that answers a `Range` request with `200` and the whole file works in Chrome and fails in Safari,
405
+ * which refuses to play a video (and stalls audio) from a server that does not answer ranges with `206 Partial
406
+ * Content`. Media players seek with ranges, download managers resume with them.
407
+ *
408
+ * Returns the range to read (pass it as `range` to `getFileStream()` / `getFileStreamByName()`, then call
409
+ * {@link setDownloadRangeHeaders}), or `undefined` for the whole file: no `Range` header, an invalid one, several
410
+ * ranges, a unit other than `bytes`, an unknown `length`, or an `If-Range` precondition — the framework's file
411
+ * validator is a weak `ETag`, which `If-Range` never matches (RFC 9110 §13.1.5), so such a request gets the whole
412
+ * file, which is always correct. See `parseRangeHeader()` for every rule.
413
+ *
414
+ * A range that starts at or past the end of the file THROWS `416 Range Not Satisfiable` with
415
+ * `Content-Range: bytes *\/<length>` and `#LTNS_0503`. Call it only AFTER the file was resolved with the rights
416
+ * check, like {@link CoreFileController.answerNotModified}: a 416 confirms that the file exists.
417
+ *
418
+ * ```typescript
419
+ * const resolved = await this.fileService.resolveFile(id, serviceOptions);
420
+ * if (!resolved) throw new NotFoundException();
421
+ * const range = resolveDownloadRange(res, resolved.info.length);
422
+ * const stream = await openDownloadStream(res, () =>
423
+ * this.fileService.getFileStream(id, { ...serviceOptions, range }, resolved.store),
424
+ * );
425
+ * // RESPONSE_GONE / null as in openDownloadStream()
426
+ * res.header('Content-Type', resolved.info.contentType);
427
+ * setDownloadRangeHeaders(res, range, resolved.info.length);
428
+ * return pipeFileToResponse(stream, res);
429
+ * ```
430
+ */
431
+ export function resolveDownloadRange(res: Response, length: number | undefined): ByteRange | undefined {
432
+ const headers = (res as Response & { req?: { headers?: Record<string, string | string[] | undefined> } }).req
433
+ ?.headers;
434
+ const header = headers?.range;
435
+ if (!header) {
436
+ return undefined;
437
+ }
438
+ // `If-Range` asks for the range only if the file is still the one the client holds part of. The only validator these
439
+ // routes send is a WEAK `ETag`, and `If-Range` compares strongly — it never matches, so the Range is ignored and the
440
+ // whole file sent (RFC 9110 §13.1.5). A project route with a strong validator decides `If-Range` itself.
441
+ if (headers['if-range'] !== undefined) {
442
+ return undefined;
443
+ }
444
+ const decision = parseRangeHeader(header, length);
445
+ if (decision === 'unsatisfiable') {
446
+ res.setHeader('Content-Range', `bytes */${length}`);
447
+ res.setHeader('Accept-Ranges', 'bytes');
448
+ throw new HttpException(ErrorCode.FILE_RANGE_NOT_SATISFIABLE, HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
449
+ }
450
+ return decision;
451
+ }
452
+
453
+ /**
454
+ * The headers of a ranged (or rangeable) file response — call it after the stream was opened, right before
455
+ * {@link pipeFileToResponse}, AFTER the project's own `Content-Length` (it overrides it for a range):
456
+ *
457
+ * - always (with a known `length`): `Accept-Ranges: bytes`, so a client knows it may ask for ranges;
458
+ * - with a range: status `206`, `Content-Range: bytes <start>-<end>/<length>`, `Content-Length` of the range, and
459
+ * `no-transform` added to `Cache-Control`. The last one keeps a `compression` middleware from gzipping a partial
460
+ * body: `compression` skips a response marked `no-transform`, and a compressed range would no longer match the
461
+ * byte positions its `Content-Range` names. It also tells proxies not to transform it.
462
+ *
463
+ * Without a range and without a known `length` it does nothing.
464
+ */
465
+ export function setDownloadRangeHeaders(res: Response, range: ByteRange | undefined, length: number | undefined): void {
466
+ const knownLength = typeof length === 'number' && Number.isSafeInteger(length) && length >= 0;
467
+ if (knownLength) {
468
+ res.setHeader('Accept-Ranges', 'bytes');
469
+ }
470
+ if (!range) {
471
+ return;
472
+ }
473
+ res.status(HttpStatus.PARTIAL_CONTENT);
474
+ // A 206 must carry Content-Range; `*` stands for a complete length nobody knows (RFC 9110 §14.4)
475
+ res.setHeader(
476
+ 'Content-Range',
477
+ knownLength ? contentRangeValue(range, length) : `bytes ${range.start}-${range.end}/*`,
478
+ );
479
+ res.setHeader('Content-Length', String(range.end - range.start + 1));
480
+ const cacheControl = res.getHeader?.('Cache-Control');
481
+ const directives = Array.isArray(cacheControl) ? cacheControl.join(', ') : String(cacheControl ?? '');
482
+ if (!/(?:^|,)\s*no-transform\s*(?:,|$)/i.test(directives)) {
483
+ res.setHeader('Cache-Control', directives.trim() ? `${directives}, no-transform` : 'no-transform');
484
+ }
485
+ }
486
+
313
487
  /**
314
488
  * File controller
315
489
  *
@@ -442,8 +616,11 @@ export abstract class CoreFileController {
442
616
  res.redirect(302, url);
443
617
  return res;
444
618
  }
619
+ // A `Range` request (Safari's video player, a resumed download) reads only those bytes — decided after the rights
620
+ // check and the 304, because a 416 confirms that the file exists
621
+ const range = this.resolveDownloadRange(res, file.length);
445
622
  const filestream = await this.openDownloadStream(res, () =>
446
- this.fileService.getFileStream(id, serviceOptions, resolved.store),
623
+ this.fileService.getFileStream(id, range ? { ...serviceOptions, range } : serviceOptions, resolved.store),
447
624
  );
448
625
  if (filestream === RESPONSE_GONE) {
449
626
  return res;
@@ -454,6 +631,7 @@ export abstract class CoreFileController {
454
631
  throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
455
632
  }
456
633
  this.setFileHeaders(res, file);
634
+ this.setDownloadRangeHeaders(res, range, file.length);
457
635
  return this.pipeFileToResponse(filestream, res);
458
636
  }
459
637
 
@@ -495,8 +673,9 @@ export abstract class CoreFileController {
495
673
  res.redirect(302, url);
496
674
  return res;
497
675
  }
676
+ const range = this.resolveDownloadRange(res, file.length);
498
677
  const filestream = await this.openDownloadStream(res, () =>
499
- this.fileService.getFileStream(file.id, serviceOptions),
678
+ this.fileService.getFileStream(file.id, range ? { ...serviceOptions, range } : serviceOptions),
500
679
  );
501
680
  if (filestream === RESPONSE_GONE) {
502
681
  return res;
@@ -505,6 +684,7 @@ export abstract class CoreFileController {
505
684
  throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
506
685
  }
507
686
  this.setFileHeaders(res, file);
687
+ this.setDownloadRangeHeaders(res, range, file.length);
508
688
  return this.pipeFileToResponse(filestream, res);
509
689
  }
510
690
 
@@ -517,40 +697,30 @@ export abstract class CoreFileController {
517
697
  }
518
698
 
519
699
  /**
520
- * Open the download stream unless the client has already gone, and release a stream that arrives after it left.
521
- *
522
- * Answers {@link RESPONSE_GONE} when there is nobody left to deliver to: before the store is asked, when the
523
- * store request was aborted because the response closed, or when the stream arrived after it closed (then the
524
- * stream is destroyed here, so its socket, file handle or cursor is free at once).
700
+ * Open the download stream unless the client has already gone, and release a stream that arrives after it left —
701
+ * see the exported {@link openDownloadStream}, which a project's own download route uses the same way.
525
702
  */
526
703
  protected async openDownloadStream(
527
704
  res: Response,
528
705
  open: () => Promise<Readable>,
529
706
  ): Promise<Readable | typeof RESPONSE_GONE> {
530
- if (isResponseGone(res)) {
531
- return RESPONSE_GONE;
532
- }
533
- let stream: Readable;
534
- try {
535
- stream = await open();
536
- } catch (error) {
537
- if (isResponseGone(res)) {
538
- return RESPONSE_GONE;
539
- }
540
- // The store did not hand out a connection in time (`s3.connectionTimeoutMs`, which includes the wait for a
541
- // free socket): the store is busy, not broken, and the client may try again — 503, not 500
542
- if ((error as { name?: string })?.name === 'TimeoutError') {
543
- fileStreamLogger.warn(`File store busy, download answered 503: ${(error as Error).message}`);
544
- res.header('Retry-After', '5');
545
- throw new ServiceUnavailableException('File storage is busy, please retry');
546
- }
547
- throw error;
548
- }
549
- if (stream && isResponseGone(res)) {
550
- stream.destroy();
551
- return RESPONSE_GONE;
552
- }
553
- return stream;
707
+ return openDownloadStream(res, open);
708
+ }
709
+
710
+ /**
711
+ * The byte range a download request asks for — see the exported {@link resolveDownloadRange}. Throws `416` for an
712
+ * unsatisfiable range. Override it to serve ranges differently (or not at all: return `undefined`).
713
+ */
714
+ protected resolveDownloadRange(res: Response, length: number | undefined): ByteRange | undefined {
715
+ return resolveDownloadRange(res, length);
716
+ }
717
+
718
+ /**
719
+ * `Accept-Ranges`, and for a range `206` with `Content-Range` — see the exported {@link setDownloadRangeHeaders}.
720
+ * Called after {@link setFileHeaders}, whose `Content-Length` it replaces for a range.
721
+ */
722
+ protected setDownloadRangeHeaders(res: Response, range: ByteRange | undefined, length: number | undefined): void {
723
+ setDownloadRangeHeaders(res, range, length);
554
724
  }
555
725
 
556
726
  /**