@lenne.tech/nest-server 12.9.1 → 12.9.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 (54) 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 +71 -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/error-code/error-codes.d.ts +9 -0
  14. package/dist/core/modules/error-code/error-codes.js +8 -0
  15. package/dist/core/modules/error-code/error-codes.js.map +1 -1
  16. package/dist/core/modules/file/core-file.controller.d.ts +6 -0
  17. package/dist/core/modules/file/core-file.controller.js +84 -27
  18. package/dist/core/modules/file/core-file.controller.js.map +1 -1
  19. package/dist/core/modules/file/core-file.service.d.ts +2 -0
  20. package/dist/core/modules/file/core-file.service.js +17 -6
  21. package/dist/core/modules/file/core-file.service.js.map +1 -1
  22. package/dist/core/modules/file/filesystem-file.helper.d.ts +2 -1
  23. package/dist/core/modules/file/filesystem-file.helper.js +2 -2
  24. package/dist/core/modules/file/filesystem-file.helper.js.map +1 -1
  25. package/dist/core/modules/file/interfaces/file-service-options.interface.d.ts +2 -0
  26. package/dist/core/modules/file/s3-file.helper.d.ts +2 -0
  27. package/dist/core/modules/file/s3-file.helper.js.map +1 -1
  28. package/dist/index.d.ts +1 -0
  29. package/dist/index.js +1 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/server/modules/error-code/error-codes.d.ts +1 -0
  32. package/dist/test/test.helper.d.ts +1 -0
  33. package/dist/test/test.helper.js +6 -0
  34. package/dist/test/test.helper.js.map +1 -1
  35. package/docs/REQUEST-LIFECYCLE.md +1 -1
  36. package/docs/error-codes.md +14 -0
  37. package/migration-guides/12.8.8-to-12.8.9.md +15 -3
  38. package/migration-guides/12.9.1-to-12.9.2.md +75 -0
  39. package/migration-guides/12.9.2-to-12.9.3.md +127 -0
  40. package/package.json +1 -1
  41. package/src/core/common/helpers/byte-range.helper.ts +144 -0
  42. package/src/core/common/helpers/gridfs.helper.ts +20 -6
  43. package/src/core/common/services/core-s3.service.ts +16 -2
  44. package/src/core/modules/error-code/error-codes.ts +13 -0
  45. package/src/core/modules/file/INTEGRATION-CHECKLIST.md +17 -15
  46. package/src/core/modules/file/README.md +90 -3
  47. package/src/core/modules/file/core-file.controller.ts +185 -32
  48. package/src/core/modules/file/core-file.service.ts +33 -13
  49. package/src/core/modules/file/filesystem-file.helper.ts +8 -3
  50. package/src/core/modules/file/interfaces/file-service-options.interface.ts +13 -0
  51. package/src/core/modules/file/s3-file.helper.ts +3 -2
  52. package/src/index.ts +1 -0
  53. package/src/test/README.md +8 -4
  54. package/src/test/test.helper.ts +12 -0
@@ -578,6 +578,19 @@ export const LtnsErrors = {
578
578
  },
579
579
  },
580
580
 
581
+ /**
582
+ * A download asked for a byte range that starts at or past the end of the file (`Range` header, HTTP 416). The
583
+ * response carries `Content-Range: bytes * /<length>` (without the space), so the client learns the real size.
584
+ */
585
+ FILE_RANGE_NOT_SATISFIABLE: {
586
+ code: 'LTNS_0503',
587
+ message: 'Requested range not satisfiable',
588
+ translations: {
589
+ de: 'Der angeforderte Bereich liegt außerhalb der Datei.',
590
+ en: 'The requested range lies outside the file.',
591
+ },
592
+ },
593
+
581
594
  // =====================================================
582
595
  // Internal Errors (LTNS_0900-LTNS_0999)
583
596
  // =====================================================
@@ -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` (12.9.2+) |
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()` (12.9.3+, 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` (12.9.3+) — 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 |
@@ -487,7 +490,8 @@ export class FileController extends CoreFileController {
487
490
  The mid-stream failure case is handled by `pipeFileToResponse()`. Without it the stream error would
488
491
  go unhandled, Node would destroy the socket, and a reverse proxy would report **502 Bad Gateway** —
489
492
  i.e. "the server is down", while every other route keeps answering. On the error path the headers
490
- describing the file (`Content-Type`, `Content-Disposition`, `Cache-Control`, `ETag`) are removed, so
493
+ describing the file (`Content-Type`, `Content-Disposition`, `Cache-Control`, `ETag`, and since 12.9.3 `Content-Range`
494
+ and `Accept-Ranges`) are removed, so
491
495
  the JSON body is not labelled as the image it failed to deliver. The error itself is logged
492
496
  server-side even though the client answer stays deliberately generic.
493
497
 
@@ -499,6 +503,8 @@ on the controller rather than the exported function of the same name.
499
503
  | `If-None-Match` names the file's weak `ETag` (`W/"<id>"`), after the rights check | `304` | No body; the store is not read |
500
504
  | The store hands out no connection within 3 attempts of `s3.connectionTimeoutMs` (pool busy) | `503` | `Retry-After: 5`; the store is busy, not broken |
501
505
  | The client left before the stream was handed over | — | Nothing is sent; the stream is destroyed at once, a pending S3 request aborted |
506
+ | `Range` names one range inside the file (12.9.3+) | `206` | `Content-Range: bytes <start>-<end>/<length>`, only those bytes |
507
+ | `Range` starts at or past the end of the file (12.9.3+) | `416` | `Content-Range: bytes */<length>`, `ErrorCode.FILE_RANGE_NOT_SATISFIABLE` |
502
508
 
503
509
  ### Delivering a file from your own route (12.8.9)
504
510
 
@@ -509,10 +515,25 @@ check stays green. A production outage had exactly this cause. `pipeFileToRespon
509
515
  client goes — on the response's `close`, the request's `close` before its end or the socket's `end`/`close`, and at once when the client
510
516
  had already gone before the call — and answers a store error before the first byte with `404`.
511
517
 
518
+ **Open the stream with `openDownloadStream(res, open)` (12.9.2+)**, the function the framework's own routes use. It
519
+ does not ask the store when the client has already gone, destroys a stream that arrives after the client left, and
520
+ answers `503` with `Retry-After` when the store hands out no connection in time. It also turns a store request that
521
+ failed BECAUSE the client left into `RESPONSE_GONE`: an S3 request aborted through `downloadAbortSignal(res)` rejects
522
+ with `AbortError`, and without it every aborted download is an ERROR with a stack trace in the log and a `500` sent
523
+ into a closed response — under the load the `S3 socket pool exhausted:` line has to stand out in.
524
+
512
525
  ```typescript
513
- import { downloadAbortSignal, pipeFileToResponse } from '@lenne.tech/nest-server';
526
+ import { downloadAbortSignal, openDownloadStream, pipeFileToResponse, RESPONSE_GONE } from '@lenne.tech/nest-server';
514
527
 
515
- const stream = await this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser });
528
+ const stream = await openDownloadStream(res, () =>
529
+ this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser }),
530
+ );
531
+ if (stream === RESPONSE_GONE) {
532
+ return res; // nobody left to deliver to
533
+ }
534
+ if (!stream) {
535
+ throw new NotFoundException();
536
+ }
516
537
  return pipeFileToResponse(stream, res);
517
538
  ```
518
539
 
@@ -536,6 +557,72 @@ Layers below it, each effective on its own:
536
557
  waits for a socket instead of taking one later. The framework's routes do this.
537
558
  - `s3.presignedDownloads` moves the bytes off the API entirely (a `302` to S3) — consider it for public files.
538
559
 
560
+ ### Byte ranges: video, audio, resumed downloads (12.9.3)
561
+
562
+ Safari refuses to play a video — and stalls audio — from a server that answers a `Range` request with `200` and the
563
+ whole file. Chrome plays it anyway, so the problem does not show locally or in a Chromium-based Playwright run. Media
564
+ players seek with ranges, download managers resume with them.
565
+
566
+ The framework's download routes answer ranges on every store. For a route of your own, three pieces:
567
+
568
+ | Piece | What it does |
569
+ | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
570
+ | `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 |
571
+ | `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 |
572
+ | `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()` |
573
+
574
+ ```typescript
575
+ import {
576
+ downloadAbortSignal,
577
+ openDownloadStream,
578
+ pipeFileToResponse,
579
+ resolveDownloadRange,
580
+ RESPONSE_GONE,
581
+ setDownloadRangeHeaders,
582
+ } from '@lenne.tech/nest-server';
583
+
584
+ @Get('video/:id')
585
+ async video(@Param('id') id: string, @Res() res: Response, @CurrentUser() currentUser) {
586
+ const serviceOptions = { abortSignal: downloadAbortSignal(res), currentUser };
587
+ const resolved = await this.fileService.resolveFile(id, serviceOptions); // rights check, length, store
588
+ if (!resolved) {
589
+ throw new NotFoundException();
590
+ }
591
+ const range = resolveDownloadRange(res, resolved.info.length); // throws 416 past the end
592
+ const stream = await openDownloadStream(res, () =>
593
+ this.fileService.getFileStream(id, { ...serviceOptions, range }, resolved.store),
594
+ );
595
+ if (stream === RESPONSE_GONE) {
596
+ return res;
597
+ }
598
+ if (!stream) {
599
+ throw new NotFoundException();
600
+ }
601
+ res.header('Content-Type', resolved.info.contentType || 'video/mp4');
602
+ res.header('Cache-Control', 'private, no-store');
603
+ setDownloadRangeHeaders(res, range, resolved.info.length);
604
+ return pipeFileToResponse(stream, res);
605
+ }
606
+ ```
607
+
608
+ What is served, and why:
609
+
610
+ - **One range per request.** Several ranges (`bytes=0-1,5-9`) get the whole file with `200` — a `multipart/byteranges`
611
+ answer is not built, the way Express's `send` handles it. Every media player asks for one range at a time.
612
+ - **A range past the end is cut at the last byte** (`bytes=0-999999999` is the whole file), a suffix longer than the
613
+ file is the whole file. Only a range STARTING at or past the end is `416`, and every range of an empty file.
614
+ - **An invalid header** (`bytes=5-2`, another unit) is ignored: the whole file with `200`, which every client can use.
615
+ - **`If-Range` gets the whole file.** The routes' validator is a weak `ETag`, which `If-Range` never matches
616
+ (RFC 9110 §13.1.5). A route with a strong validator can decide `If-Range` itself and call `parseRangeHeader()`.
617
+ - **`no-transform` on a `206`** keeps `compression` away: a gzipped partial body would no longer match the offsets in
618
+ its `Content-Range`. A whole file is compressed as before (when its type is compressible).
619
+ - **`range` on the service must lie inside the file** — `resolveDownloadRange()` guarantees it. A malformed range
620
+ (negative, not an integer, `start > end`) throws a `RangeError` before any store is asked; a range reaching past the
621
+ end of the file is not checked by the service and fails per store (GridFS: an error on the stream, S3: `InvalidRange`
622
+ for a start past the end).
623
+ - **Presigned downloads** (`s3.presignedDownloads`) redirect before any of this: the browser sends its `Range` to S3,
624
+ which answers it itself.
625
+
539
626
  ### Upload filtering
540
627
 
541
628
  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,
@@ -14,6 +16,7 @@ import type { Readable } from 'stream';
14
16
  import { CurrentUser } from '../../common/decorators/current-user.decorator.js';
15
17
  import { Roles } from '../../common/decorators/roles.decorator.js';
16
18
  import { RoleEnum } from '../../common/enums/role.enum.js';
19
+ import { type ByteRange, contentRangeValue, parseRangeHeader } from '../../common/helpers/byte-range.helper.js';
17
20
  import { buildContentDisposition } from '../../common/helpers/content-disposition.helper.js';
18
21
  import { StreamIdleTimeoutError } from '../../common/helpers/idle-stream.helper.js';
19
22
  import { ConfigService } from '../../common/services/config.service.js';
@@ -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.
@@ -310,6 +321,152 @@ export function downloadAbortSignal(res: Response): AbortSignal {
310
321
  return controller.signal;
311
322
  }
312
323
 
324
+ /**
325
+ * Open a download stream unless the client has already gone, and release a stream that arrives after it left — the
326
+ * framework's download routes use it, and so should a project's own (with {@link pipeFileToResponse} for delivery):
327
+ *
328
+ * ```typescript
329
+ * const stream = await openDownloadStream(res, () =>
330
+ * this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser }),
331
+ * );
332
+ * if (stream === RESPONSE_GONE) {
333
+ * return res;
334
+ * }
335
+ * if (!stream) {
336
+ * throw new NotFoundException();
337
+ * }
338
+ * return pipeFileToResponse(stream, res);
339
+ * ```
340
+ *
341
+ * Answers {@link RESPONSE_GONE} when there is nobody left to deliver to — end the route with `return res` then:
342
+ * - the client had gone before the store was asked;
343
+ * - the store request failed because the client left meanwhile. An S3 request aborted through
344
+ * {@link downloadAbortSignal} rejects with `AbortError`; rethrown, every aborted download became an ERROR with a
345
+ * stack trace in the log and a 500 sent into a closed response, under exactly the load the log line
346
+ * `S3 socket pool exhausted:` has to stand out in;
347
+ * - the stream arrived after the client left — it is destroyed here, so its socket, file handle or cursor is free at
348
+ * once.
349
+ *
350
+ * A store that handed out no connection in time (`TimeoutError`, see `s3.connectionTimeoutMs`) answers `503` with
351
+ * `Retry-After: 5`. Any other error is rethrown. `null` or `undefined` (the service's rights check refused) is passed
352
+ * on unchanged.
353
+ */
354
+ export async function openDownloadStream<T extends null | Readable | undefined>(
355
+ res: Response,
356
+ open: () => Promise<T>,
357
+ ): Promise<T | typeof RESPONSE_GONE> {
358
+ if (isResponseGone(res)) {
359
+ return RESPONSE_GONE;
360
+ }
361
+ let stream: T;
362
+ try {
363
+ stream = await open();
364
+ } catch (error) {
365
+ if (isResponseGone(res)) {
366
+ return RESPONSE_GONE;
367
+ }
368
+ // The store did not hand out a connection in time (`s3.connectionTimeoutMs`, which includes the wait for a
369
+ // free socket): the store is busy, not broken, and the client may try again — 503, not 500
370
+ if ((error as { name?: string })?.name === 'TimeoutError') {
371
+ fileStreamLogger.warn(`File store busy, download answered 503: ${(error as Error).message}`);
372
+ res.header('Retry-After', '5');
373
+ throw new ServiceUnavailableException('File storage is busy, please retry');
374
+ }
375
+ throw error;
376
+ }
377
+ if (stream && isResponseGone(res)) {
378
+ stream.destroy();
379
+ return RESPONSE_GONE;
380
+ }
381
+ return stream;
382
+ }
383
+
384
+ /**
385
+ * Which bytes of a file a download request asks for — the `Range` header, resolved against the file's `length`.
386
+ *
387
+ * WHY: a server that answers a `Range` request with `200` and the whole file works in Chrome and fails in Safari,
388
+ * which refuses to play a video (and stalls audio) from a server that does not answer ranges with `206 Partial
389
+ * Content`. Media players seek with ranges, download managers resume with them.
390
+ *
391
+ * Returns the range to read (pass it as `range` to `getFileStream()` / `getFileStreamByName()`, then call
392
+ * {@link setDownloadRangeHeaders}), or `undefined` for the whole file: no `Range` header, an invalid one, several
393
+ * ranges, a unit other than `bytes`, an unknown `length`, or an `If-Range` precondition — the framework's file
394
+ * validator is a weak `ETag`, which `If-Range` never matches (RFC 9110 §13.1.5), so such a request gets the whole
395
+ * file, which is always correct. See `parseRangeHeader()` for every rule.
396
+ *
397
+ * A range that starts at or past the end of the file THROWS `416 Range Not Satisfiable` with
398
+ * `Content-Range: bytes *\/<length>` and `#LTNS_0503`. Call it only AFTER the file was resolved with the rights
399
+ * check, like {@link CoreFileController.answerNotModified}: a 416 confirms that the file exists.
400
+ *
401
+ * ```typescript
402
+ * const resolved = await this.fileService.resolveFile(id, serviceOptions);
403
+ * if (!resolved) throw new NotFoundException();
404
+ * const range = resolveDownloadRange(res, resolved.info.length);
405
+ * const stream = await openDownloadStream(res, () =>
406
+ * this.fileService.getFileStream(id, { ...serviceOptions, range }, resolved.store),
407
+ * );
408
+ * // RESPONSE_GONE / null as in openDownloadStream()
409
+ * res.header('Content-Type', resolved.info.contentType);
410
+ * setDownloadRangeHeaders(res, range, resolved.info.length);
411
+ * return pipeFileToResponse(stream, res);
412
+ * ```
413
+ */
414
+ export function resolveDownloadRange(res: Response, length: number | undefined): ByteRange | undefined {
415
+ const headers = (res as Response & { req?: { headers?: Record<string, string | string[] | undefined> } }).req
416
+ ?.headers;
417
+ const header = headers?.range;
418
+ if (!header) {
419
+ return undefined;
420
+ }
421
+ // `If-Range` asks for the range only if the file is still the one the client holds part of. The only validator these
422
+ // routes send is a WEAK `ETag`, and `If-Range` compares strongly — it never matches, so the Range is ignored and the
423
+ // whole file sent (RFC 9110 §13.1.5). A project route with a strong validator decides `If-Range` itself.
424
+ if (headers['if-range'] !== undefined) {
425
+ return undefined;
426
+ }
427
+ const decision = parseRangeHeader(header, length);
428
+ if (decision === 'unsatisfiable') {
429
+ res.setHeader('Content-Range', `bytes */${length}`);
430
+ res.setHeader('Accept-Ranges', 'bytes');
431
+ throw new HttpException(ErrorCode.FILE_RANGE_NOT_SATISFIABLE, HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
432
+ }
433
+ return decision;
434
+ }
435
+
436
+ /**
437
+ * The headers of a ranged (or rangeable) file response — call it after the stream was opened, right before
438
+ * {@link pipeFileToResponse}, AFTER the project's own `Content-Length` (it overrides it for a range):
439
+ *
440
+ * - always (with a known `length`): `Accept-Ranges: bytes`, so a client knows it may ask for ranges;
441
+ * - with a range: status `206`, `Content-Range: bytes <start>-<end>/<length>`, `Content-Length` of the range, and
442
+ * `no-transform` added to `Cache-Control`. The last one keeps a `compression` middleware from gzipping a partial
443
+ * body: `compression` skips a response marked `no-transform`, and a compressed range would no longer match the
444
+ * byte positions its `Content-Range` names. It also tells proxies not to transform it.
445
+ *
446
+ * Without a range and without a known `length` it does nothing.
447
+ */
448
+ export function setDownloadRangeHeaders(res: Response, range: ByteRange | undefined, length: number | undefined): void {
449
+ const knownLength = typeof length === 'number' && Number.isSafeInteger(length) && length >= 0;
450
+ if (knownLength) {
451
+ res.setHeader('Accept-Ranges', 'bytes');
452
+ }
453
+ if (!range) {
454
+ return;
455
+ }
456
+ res.status(HttpStatus.PARTIAL_CONTENT);
457
+ // A 206 must carry Content-Range; `*` stands for a complete length nobody knows (RFC 9110 §14.4)
458
+ res.setHeader(
459
+ 'Content-Range',
460
+ knownLength ? contentRangeValue(range, length) : `bytes ${range.start}-${range.end}/*`,
461
+ );
462
+ res.setHeader('Content-Length', String(range.end - range.start + 1));
463
+ const cacheControl = res.getHeader?.('Cache-Control');
464
+ const directives = Array.isArray(cacheControl) ? cacheControl.join(', ') : String(cacheControl ?? '');
465
+ if (!/(?:^|,)\s*no-transform\s*(?:,|$)/i.test(directives)) {
466
+ res.setHeader('Cache-Control', directives.trim() ? `${directives}, no-transform` : 'no-transform');
467
+ }
468
+ }
469
+
313
470
  /**
314
471
  * File controller
315
472
  *
@@ -442,8 +599,11 @@ export abstract class CoreFileController {
442
599
  res.redirect(302, url);
443
600
  return res;
444
601
  }
602
+ // A `Range` request (Safari's video player, a resumed download) reads only those bytes — decided after the rights
603
+ // check and the 304, because a 416 confirms that the file exists
604
+ const range = this.resolveDownloadRange(res, file.length);
445
605
  const filestream = await this.openDownloadStream(res, () =>
446
- this.fileService.getFileStream(id, serviceOptions, resolved.store),
606
+ this.fileService.getFileStream(id, range ? { ...serviceOptions, range } : serviceOptions, resolved.store),
447
607
  );
448
608
  if (filestream === RESPONSE_GONE) {
449
609
  return res;
@@ -454,6 +614,7 @@ export abstract class CoreFileController {
454
614
  throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
455
615
  }
456
616
  this.setFileHeaders(res, file);
617
+ this.setDownloadRangeHeaders(res, range, file.length);
457
618
  return this.pipeFileToResponse(filestream, res);
458
619
  }
459
620
 
@@ -495,8 +656,9 @@ export abstract class CoreFileController {
495
656
  res.redirect(302, url);
496
657
  return res;
497
658
  }
659
+ const range = this.resolveDownloadRange(res, file.length);
498
660
  const filestream = await this.openDownloadStream(res, () =>
499
- this.fileService.getFileStream(file.id, serviceOptions),
661
+ this.fileService.getFileStream(file.id, range ? { ...serviceOptions, range } : serviceOptions),
500
662
  );
501
663
  if (filestream === RESPONSE_GONE) {
502
664
  return res;
@@ -505,6 +667,7 @@ export abstract class CoreFileController {
505
667
  throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
506
668
  }
507
669
  this.setFileHeaders(res, file);
670
+ this.setDownloadRangeHeaders(res, range, file.length);
508
671
  return this.pipeFileToResponse(filestream, res);
509
672
  }
510
673
 
@@ -517,40 +680,30 @@ export abstract class CoreFileController {
517
680
  }
518
681
 
519
682
  /**
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).
683
+ * Open the download stream unless the client has already gone, and release a stream that arrives after it left —
684
+ * see the exported {@link openDownloadStream}, which a project's own download route uses the same way.
525
685
  */
526
686
  protected async openDownloadStream(
527
687
  res: Response,
528
688
  open: () => Promise<Readable>,
529
689
  ): 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;
690
+ return openDownloadStream(res, open);
691
+ }
692
+
693
+ /**
694
+ * The byte range a download request asks for — see the exported {@link resolveDownloadRange}. Throws `416` for an
695
+ * unsatisfiable range. Override it to serve ranges differently (or not at all: return `undefined`).
696
+ */
697
+ protected resolveDownloadRange(res: Response, length: number | undefined): ByteRange | undefined {
698
+ return resolveDownloadRange(res, length);
699
+ }
700
+
701
+ /**
702
+ * `Accept-Ranges`, and for a range `206` with `Content-Range` — see the exported {@link setDownloadRangeHeaders}.
703
+ * Called after {@link setFileHeaders}, whose `Content-Length` it replaces for a range.
704
+ */
705
+ protected setDownloadRangeHeaders(res: Response, range: ByteRange | undefined, length: number | undefined): void {
706
+ setDownloadRangeHeaders(res, range, length);
554
707
  }
555
708
 
556
709
  /**
@@ -4,6 +4,7 @@ import type { mongo, Types } from 'mongoose';
4
4
  import { Readable } from 'stream';
5
5
 
6
6
  import { FilterArgs } from '../../common/args/filter.args.js';
7
+ import { assertByteRange } from '../../common/helpers/byte-range.helper.js';
7
8
  import { accessDeniedException } from '../../common/exceptions/access-denied.exception.js';
8
9
  import { getObjectIds, getStringIds } from '../../common/helpers/db.helper.js';
9
10
  import { convertFilterArgsToQuery } from '../../common/helpers/filter.helper.js';
@@ -484,6 +485,10 @@ export abstract class CoreFileService {
484
485
 
485
486
  /**
486
487
  * Get file stream (for big files) via file ID
488
+ *
489
+ * With `serviceOptions.range`, only those bytes (both inclusive) — from every store: S3 with a ranged
490
+ * `GetObject`, GridFS from the chunk that holds the first byte, the filesystem from that offset. See
491
+ * {@link FileServiceOptions.range} for the contract and `resolveDownloadRange()` for producing one from a request.
487
492
  */
488
493
  async getFileStream(
489
494
  id: string | Types.ObjectId,
@@ -493,6 +498,8 @@ export abstract class CoreFileService {
493
498
  if (this.isMalformedFileId(id)) {
494
499
  return null;
495
500
  }
501
+ // Checked before anything is asked: a malformed range is a caller's bug, answered the same for every store
502
+ assertByteRange(serviceOptions?.range);
496
503
  if (!(await this.checkRights(id, { ...serviceOptions, checkInputType: 'id' }))) {
497
504
  return null;
498
505
  }
@@ -502,6 +509,19 @@ export abstract class CoreFileService {
502
509
  // the same one-to-three metadata round trips are not repeated per download.
503
510
  // Omitting it keeps the previous behaviour exactly.
504
511
  const store = knownStore ?? (await this.locateFile(id));
512
+ return this.openStoreStream(store, id, serviceOptions);
513
+ }
514
+
515
+ /**
516
+ * Open the download stream of a file in the store that holds it — the whole file, or `serviceOptions.range` —
517
+ * guarded against a caller that stops reading. The rights check is the caller's: this only reads bytes.
518
+ */
519
+ protected async openStoreStream(
520
+ store: FileStorageDriver,
521
+ id: string | Types.ObjectId,
522
+ serviceOptions?: FileServiceOptions,
523
+ ): Promise<Readable> {
524
+ const range = assertByteRange(serviceOptions?.range);
505
525
  if (store === 's3') {
506
526
  return this.guardDownloadStream(
507
527
  await S3FileHelper.getStream(this.options.s3Service, id, this.s3StreamOptions(serviceOptions)),
@@ -509,10 +529,10 @@ export abstract class CoreFileService {
509
529
  );
510
530
  }
511
531
  if (store === 'filesystem') {
512
- return this.guardDownloadStream(FilesystemFileHelper.getStream(this.filesystemDir, id), serviceOptions);
532
+ return this.guardDownloadStream(FilesystemFileHelper.getStream(this.filesystemDir, id, range), serviceOptions);
513
533
  }
514
534
  return this.guardDownloadStream(
515
- GridFSHelper.openDownloadStream(this.files, getObjectIds(id)) as mongo.GridFSBucketReadStream,
535
+ GridFSHelper.openDownloadStream(this.files, getObjectIds(id), range) as mongo.GridFSBucketReadStream,
516
536
  serviceOptions,
517
537
  );
518
538
  }
@@ -535,12 +555,17 @@ export abstract class CoreFileService {
535
555
  });
536
556
  }
537
557
 
538
- /** Options for the S3 stream of a download: the caller's abort signal and idle time. */
558
+ /** Options for the S3 stream of a download: the caller's abort signal, idle time and byte range. */
539
559
  protected s3StreamOptions(serviceOptions?: FileServiceOptions): {
540
560
  abortSignal?: AbortSignal;
541
561
  idleTimeoutMs?: false | number;
562
+ range?: FileServiceOptions['range'];
542
563
  } {
543
- return { abortSignal: serviceOptions?.abortSignal, idleTimeoutMs: serviceOptions?.downloadIdleTimeoutMs };
564
+ return {
565
+ abortSignal: serviceOptions?.abortSignal,
566
+ idleTimeoutMs: serviceOptions?.downloadIdleTimeoutMs,
567
+ ...(serviceOptions?.range ? { range: serviceOptions.range } : {}),
568
+ };
544
569
  }
545
570
 
546
571
  /**
@@ -648,22 +673,17 @@ export abstract class CoreFileService {
648
673
  * unchanged; what changed is that the document authorization inspected is the one being served.
649
674
  */
650
675
  async getFileStreamByName(filename: string, serviceOptions?: FileServiceOptions): Promise<Readable> {
676
+ assertByteRange(serviceOptions?.range);
651
677
  if (!(await this.checkRights(filename, { ...serviceOptions, checkInputType: 'filename' }))) {
652
678
  return null;
653
679
  }
654
680
  const s3FileInfo = await this.findS3FileByName(filename);
655
681
  if (s3FileInfo) {
656
- return this.guardDownloadStream(
657
- await S3FileHelper.getStream(this.options.s3Service, s3FileInfo._id, this.s3StreamOptions(serviceOptions)),
658
- serviceOptions,
659
- );
682
+ return this.openStoreStream('s3', s3FileInfo._id, serviceOptions);
660
683
  }
661
684
  const fsFileInfo = await this.findFilesystemFileByName(filename);
662
685
  if (fsFileInfo) {
663
- return this.guardDownloadStream(
664
- FilesystemFileHelper.getStream(this.filesystemDir, fsFileInfo._id),
665
- serviceOptions,
666
- );
686
+ return this.openStoreStream('filesystem', fsFileInfo._id, serviceOptions);
667
687
  }
668
688
  const gridFsInfo = await GridFSHelper.findFileByName(this.files, filename);
669
689
  if (!gridFsInfo) {
@@ -671,7 +691,7 @@ export abstract class CoreFileService {
671
691
  // itself, asynchronously on the stream, which the controller turns into a 404.
672
692
  return this.guardDownloadStream(GridFSHelper.openDownloadStreamByName(this.files, filename), serviceOptions);
673
693
  }
674
- return this.guardDownloadStream(GridFSHelper.openDownloadStream(this.files, gridFsInfo._id), serviceOptions);
694
+ return this.openStoreStream('gridfs', gridFsInfo._id, serviceOptions);
675
695
  }
676
696
 
677
697
  /**
@@ -14,6 +14,7 @@ import {
14
14
  findMetadataByName,
15
15
  } from './file-metadata.helper.js';
16
16
  import { streamToBuffer } from './s3-file.helper.js';
17
+ import type { ByteRange } from '../../common/helpers/byte-range.helper.js';
17
18
  import { newObjectId } from '../../common/persistence/mongo/mongoose-compat.js';
18
19
 
19
20
  /** Metadata collection for files stored on the local filesystem (on a SQL source: the table `filesystem_files`) */
@@ -172,10 +173,14 @@ export class FilesystemFileHelper {
172
173
  }
173
174
 
174
175
  /**
175
- * Get the download stream of a file
176
+ * Get the download stream of a file — with `range`, only those bytes (both inclusive, as `createReadStream()`
177
+ * counts them)
176
178
  */
177
- static getStream(directory: string, id: string | Types.ObjectId): Readable {
178
- return createReadStream(FilesystemFileHelper.filePath(directory, id));
179
+ static getStream(directory: string, id: string | Types.ObjectId, range?: ByteRange): Readable {
180
+ return createReadStream(
181
+ FilesystemFileHelper.filePath(directory, id),
182
+ range ? { end: range.end, start: range.start } : undefined,
183
+ );
179
184
  }
180
185
 
181
186
  /**
@@ -1,3 +1,5 @@
1
+ import type { ByteRange } from '../../../common/helpers/byte-range.helper.js';
2
+
1
3
  /**
2
4
  * Interface for service options in file services
3
5
  */
@@ -40,5 +42,16 @@ export interface FileServiceOptions {
40
42
  */
41
43
  metadata?: Record<string, any>;
42
44
 
45
+ /**
46
+ * Read only these bytes of the file (both inclusive) — `getFileStream()` / `getFileStreamByName()`, every store.
47
+ *
48
+ * What a route needs to answer a `Range` request with `206 Partial Content` (video and audio in Safari and every
49
+ * media player, resumed downloads). The range must lie inside the file (`end` below its `length`): produce it with
50
+ * `resolveDownloadRange(res, file.length)`, which also answers an unsatisfiable range with `416`. A malformed range
51
+ * (negative, not an integer, `start > end`) throws a `RangeError` before any store is asked. The rights check runs
52
+ * first, as for a whole file. Since 12.9.3.
53
+ */
54
+ range?: ByteRange;
55
+
43
56
  roles?: string | string[];
44
57
  }