@lenne.tech/nest-server 12.9.2 → 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.
- package/.claude/rules/testing.md +4 -4
- package/FRAMEWORK-API.md +1 -1
- package/dist/core/common/helpers/byte-range.helper.d.ts +8 -0
- package/dist/core/common/helpers/byte-range.helper.js +71 -0
- package/dist/core/common/helpers/byte-range.helper.js.map +1 -0
- package/dist/core/common/helpers/gridfs.helper.d.ts +7 -2
- package/dist/core/common/helpers/gridfs.helper.js +7 -4
- package/dist/core/common/helpers/gridfs.helper.js.map +1 -1
- package/dist/core/common/services/core-s3.service.d.ts +3 -0
- package/dist/core/common/services/core-s3.service.js +8 -1
- package/dist/core/common/services/core-s3.service.js.map +1 -1
- package/dist/core/modules/error-code/error-codes.d.ts +9 -0
- package/dist/core/modules/error-code/error-codes.js +8 -0
- package/dist/core/modules/error-code/error-codes.js.map +1 -1
- package/dist/core/modules/file/core-file.controller.d.ts +5 -0
- package/dist/core/modules/file/core-file.controller.js +58 -4
- package/dist/core/modules/file/core-file.controller.js.map +1 -1
- package/dist/core/modules/file/core-file.service.d.ts +2 -0
- package/dist/core/modules/file/core-file.service.js +17 -6
- package/dist/core/modules/file/core-file.service.js.map +1 -1
- package/dist/core/modules/file/filesystem-file.helper.d.ts +2 -1
- package/dist/core/modules/file/filesystem-file.helper.js +2 -2
- package/dist/core/modules/file/filesystem-file.helper.js.map +1 -1
- package/dist/core/modules/file/interfaces/file-service-options.interface.d.ts +2 -0
- package/dist/core/modules/file/s3-file.helper.d.ts +2 -0
- package/dist/core/modules/file/s3-file.helper.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/server/modules/error-code/error-codes.d.ts +1 -0
- package/dist/test/test.helper.d.ts +1 -0
- package/dist/test/test.helper.js +6 -0
- package/dist/test/test.helper.js.map +1 -1
- package/docs/REQUEST-LIFECYCLE.md +1 -1
- package/docs/error-codes.md +14 -0
- package/migration-guides/12.9.2-to-12.9.3.md +127 -0
- package/package.json +1 -1
- package/src/core/common/helpers/byte-range.helper.ts +144 -0
- package/src/core/common/helpers/gridfs.helper.ts +20 -6
- package/src/core/common/services/core-s3.service.ts +16 -2
- package/src/core/modules/error-code/error-codes.ts +13 -0
- package/src/core/modules/file/INTEGRATION-CHECKLIST.md +1 -0
- package/src/core/modules/file/README.md +73 -1
- package/src/core/modules/file/core-file.controller.ts +122 -3
- package/src/core/modules/file/core-file.service.ts +33 -13
- package/src/core/modules/file/filesystem-file.helper.ts +8 -3
- package/src/core/modules/file/interfaces/file-service-options.interface.ts +13 -0
- package/src/core/modules/file/s3-file.helper.ts +3 -2
- package/src/index.ts +1 -0
- package/src/test/README.md +8 -4
- package/src/test/test.helper.ts +12 -0
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# Migration Guide: 12.9.2 → 12.9.3
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
| Category | Details |
|
|
6
|
+
|---|---|
|
|
7
|
+
| **Breaking Changes** | None |
|
|
8
|
+
| **New Features** | Byte ranges from every file store: `getFileStream(id, { range })`, `CoreS3Service.getObject(key, { range })`, `resolveDownloadRange()`, `setDownloadRangeHeaders()`, `parseRangeHeader()`; `TestDownloadOptions.headers` |
|
|
9
|
+
| **Bugfixes** | `GET /files/id/:id` and `GET /files/:filename` answered every `Range` request with `200` and the whole file — Safari does not play a video from such a server (§1) |
|
|
10
|
+
| **Migration Effort** | Projects with their OWN route for video, audio or large downloads: answer `Range` (§2). Everyone else: `pnpm run update` |
|
|
11
|
+
|
|
12
|
+
## Quick Migration
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pnpm add @lenne.tech/nest-server@12.9.3
|
|
16
|
+
pnpm run update # nest-server-starter based projects
|
|
17
|
+
grep -rn "pipeFileToResponse(" src/ # own download routes: serve ranges where media is delivered (§2)
|
|
18
|
+
pnpm run build
|
|
19
|
+
pnpm test
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
**Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
|
|
23
|
+
|
|
24
|
+
## 1. The framework's download routes answer ranges
|
|
25
|
+
|
|
26
|
+
Safari refuses to play a video, and stalls audio, from a server that answers a `Range` request with `200` and the
|
|
27
|
+
whole file. Chrome plays it anyway, so the problem showed neither locally nor in a Chromium-based Playwright run — it
|
|
28
|
+
showed on the first iPhone. Until 12.9.2 the core could not read a byte range at all: `CoreS3Service.getObject()` sent
|
|
29
|
+
no `Range`, and `getFileStream()` always opened the whole file. A project could serve ranges from GridFS and the
|
|
30
|
+
filesystem with its own code, but not from S3, which every deployed stage with `s3` configured uses.
|
|
31
|
+
|
|
32
|
+
Since 12.9.3 both download routes answer ranges on every store, without any change in the project:
|
|
33
|
+
|
|
34
|
+
| Request | Answer |
|
|
35
|
+
|---|---|
|
|
36
|
+
| `Range: bytes=0-1` (one range inside the file) | `206`, `Content-Range: bytes 0-1/<length>`, `Content-Length: 2`, only those bytes |
|
|
37
|
+
| `Range: bytes=1000-` / `bytes=-500` | `206` with the rest of the file / its last 500 bytes |
|
|
38
|
+
| A range starting at or past the end of the file | `416`, `Content-Range: bytes */<length>`, `#LTNS_0503` |
|
|
39
|
+
| Several ranges, an invalid header, `If-Range` | `200` with the whole file, as before |
|
|
40
|
+
| No `Range` | `200` as before, now with `Accept-Ranges: bytes` |
|
|
41
|
+
|
|
42
|
+
The rights check runs first, as before: a refused or unknown file is `404` whatever the `Range` says. A `206` carries
|
|
43
|
+
`no-transform` in `Cache-Control` (`private, no-store, no-transform` by default), which keeps a `compression`
|
|
44
|
+
middleware from gzipping the partial body.
|
|
45
|
+
|
|
46
|
+
## 2. Own download routes
|
|
47
|
+
|
|
48
|
+
A route of your own that delivers media (or large files a client may resume) answers ranges with three calls:
|
|
49
|
+
|
|
50
|
+
```typescript
|
|
51
|
+
import {
|
|
52
|
+
downloadAbortSignal,
|
|
53
|
+
openDownloadStream,
|
|
54
|
+
pipeFileToResponse,
|
|
55
|
+
resolveDownloadRange,
|
|
56
|
+
RESPONSE_GONE,
|
|
57
|
+
setDownloadRangeHeaders,
|
|
58
|
+
} from '@lenne.tech/nest-server';
|
|
59
|
+
|
|
60
|
+
@Get('video/:id')
|
|
61
|
+
async video(@Param('id') id: string, @Res() res: Response, @CurrentUser() currentUser) {
|
|
62
|
+
const serviceOptions = { abortSignal: downloadAbortSignal(res), currentUser };
|
|
63
|
+
const resolved = await this.fileService.resolveFile(id, serviceOptions); // rights check, length, store
|
|
64
|
+
if (!resolved) {
|
|
65
|
+
throw new NotFoundException();
|
|
66
|
+
}
|
|
67
|
+
const range = resolveDownloadRange(res, resolved.info.length); // throws 416 past the end
|
|
68
|
+
const stream = await openDownloadStream(res, () =>
|
|
69
|
+
this.fileService.getFileStream(id, { ...serviceOptions, range }, resolved.store),
|
|
70
|
+
);
|
|
71
|
+
if (stream === RESPONSE_GONE) {
|
|
72
|
+
return res;
|
|
73
|
+
}
|
|
74
|
+
if (!stream) {
|
|
75
|
+
throw new NotFoundException();
|
|
76
|
+
}
|
|
77
|
+
res.header('Content-Type', resolved.info.contentType || 'video/mp4');
|
|
78
|
+
res.header('Cache-Control', 'private, no-store');
|
|
79
|
+
setDownloadRangeHeaders(res, range, resolved.info.length); // 206 + Content-Range, or Accept-Ranges only
|
|
80
|
+
return pipeFileToResponse(stream, res);
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
- `resolveDownloadRange()` must run AFTER the rights check: a `416` confirms that the file exists.
|
|
85
|
+
- `setDownloadRangeHeaders()` goes after your own headers — it replaces `Content-Length` with the length of the range
|
|
86
|
+
and appends `no-transform` to `Cache-Control`.
|
|
87
|
+
- The range reaches every store: S3 with a ranged `GetObject`, GridFS from the chunk holding the first byte, the
|
|
88
|
+
filesystem from that offset — with the same idle guard and abort signal as a whole file, so an aborted range
|
|
89
|
+
releases its S3 socket at once.
|
|
90
|
+
|
|
91
|
+
**A project that reads ranges itself** (GridFS `openDownloadStream(id, { start, end })`, `createReadStream({ start,
|
|
92
|
+
end })`, a hand-written Range parser) can switch to these functions and drop its own code — and gets S3, which such
|
|
93
|
+
code could not reach. Mind the end: `range.end` is INCLUSIVE, like HTTP and `createReadStream()`; GridFS counts it
|
|
94
|
+
exclusive, which `getFileStream()` translates.
|
|
95
|
+
|
|
96
|
+
Lower-level pieces, for code that does not go through `CoreFileService`:
|
|
97
|
+
|
|
98
|
+
- `CoreS3Service.getObject(key, { range: { start, end } })` — the result carries `contentRange` (S3's
|
|
99
|
+
`bytes <start>-<end>/<total>`) and the range's `contentLength`.
|
|
100
|
+
- `parseRangeHeader(header, length)` — the pure parser (`{ start, end }`, `'unsatisfiable'` or `undefined`), for a
|
|
101
|
+
route that decides `If-Range` with a strong validator of its own.
|
|
102
|
+
- A malformed range (`start > end`, negative, not an integer) throws a `RangeError` before any store is asked.
|
|
103
|
+
|
|
104
|
+
## 3. Tests
|
|
105
|
+
|
|
106
|
+
`testHelper.download()` / `downloadBuffer()` take request headers:
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
const res = await testHelper.download(`/files/id/${id}`, { headers: { Range: 'bytes=0-1' }, token });
|
|
110
|
+
expect(res.statusCode).toBe(206);
|
|
111
|
+
expect(res.headers['content-range']).toBe(`bytes 0-1/${length}`);
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## Troubleshooting
|
|
115
|
+
|
|
116
|
+
| Symptom | Cause | Fix |
|
|
117
|
+
|---|---|---|
|
|
118
|
+
| A video plays in Chrome but not in Safari (iPhone, macOS) | The route answers `Range` with `200` and the whole file | Framework routes: update. Own route: §2 |
|
|
119
|
+
| `416` with `#LTNS_0503` | The client asked for bytes past the end of the file; `Content-Range: bytes */<length>` names the real size | Usually a player with a cached, outdated length — reload |
|
|
120
|
+
| `RangeError: Invalid byte range` | A `range` with `start > end`, a negative or fractional value reached `getFileStream()` / `getObject()` | Produce it with `resolveDownloadRange()` |
|
|
121
|
+
| `InvalidRange` from S3, or a GridFS stream error `Stream end (…) must not be more than the length of the file` | A `range` past the end of the file reached the store | Resolve it against the file's `length` with `resolveDownloadRange()`, which cuts it at the last byte |
|
|
122
|
+
|
|
123
|
+
## Module Documentation
|
|
124
|
+
|
|
125
|
+
- `src/core/modules/file/README.md` — "Byte ranges: video, audio, resumed downloads (12.9.3)"
|
|
126
|
+
- `src/core/modules/file/INTEGRATION-CHECKLIST.md` — Common Mistakes
|
|
127
|
+
- `docs/error-codes.md` — `LTNS_0503`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lenne.tech/nest-server",
|
|
3
|
-
"version": "12.9.
|
|
3
|
+
"version": "12.9.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Server framework in TypeScript on top of NestJS: GraphQL and REST APIs on MongoDB, PostgreSQL, MySQL or MariaDB, with authentication, field-level permissions, multi-tenancy, offline sync and an AI assistant.",
|
|
6
6
|
"keywords": [
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A byte range of a file: the bytes `start` through `end`, both INCLUSIVE — the way HTTP counts them
|
|
3
|
+
* (`Range: bytes=0-1` is two bytes) and `fs.createReadStream()` takes them.
|
|
4
|
+
*
|
|
5
|
+
* Read with `CoreFileService.getFileStream(id, { range })` / `getFileStreamByName()` or
|
|
6
|
+
* `CoreS3Service.getObject(key, { range })`. The range must lie inside the file (`end` below its
|
|
7
|
+
* length); {@link parseRangeHeader} / `resolveDownloadRange()` produce such a range from a request.
|
|
8
|
+
*/
|
|
9
|
+
export interface ByteRange {
|
|
10
|
+
/** Last byte, inclusive */
|
|
11
|
+
end: number;
|
|
12
|
+
/** First byte, counted from 0 */
|
|
13
|
+
start: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* What {@link parseRangeHeader} decided about a `Range` header:
|
|
18
|
+
* - a {@link ByteRange} — deliver these bytes (`206 Partial Content`);
|
|
19
|
+
* - `'unsatisfiable'` — the range starts at or past the end of the file (`416 Range Not Satisfiable`);
|
|
20
|
+
* - `undefined` — deliver the whole file (`200`), the header asks for nothing this server serves.
|
|
21
|
+
*/
|
|
22
|
+
export type RangeHeaderDecision = 'unsatisfiable' | ByteRange | undefined;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Longest `Range` header that is parsed at all. A single byte range of a file the size of any store's limit is
|
|
26
|
+
* well below 100 characters; a longer header is a list of ranges or garbage, and both are answered with the whole
|
|
27
|
+
* file anyway.
|
|
28
|
+
*/
|
|
29
|
+
const MAX_RANGE_HEADER_LENGTH = 200;
|
|
30
|
+
|
|
31
|
+
/** One range of the set, `first-last`, `first-` or `-suffix`. Anchored and without nested quantifiers. */
|
|
32
|
+
const RANGE_SPEC = /^(\d*)[ \t]*-[ \t]*(\d*)$/;
|
|
33
|
+
|
|
34
|
+
/** The unit and the range set: `bytes=<set>`, the unit case-insensitive (RFC 9110 §14.1) */
|
|
35
|
+
const RANGE_UNIT = /^[ \t]*bytes[ \t]*=(.*)$/i;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Decide what a `Range` request header asks for, against a file of `length` bytes (RFC 9110 §14.1.2, §14.2).
|
|
39
|
+
*
|
|
40
|
+
* Only ONE range is served. The whole file (`undefined`) is the answer to:
|
|
41
|
+
* - no header, an empty one, or a unit other than `bytes`;
|
|
42
|
+
* - an invalid header (`bytes=5-2`, `bytes=abc`, `bytes=-`) — RFC 9110 lets a server ignore it, and the whole file
|
|
43
|
+
* is what a client that sent garbage can still use;
|
|
44
|
+
* - SEVERAL ranges (`bytes=0-1,5-9`): a `multipart/byteranges` answer is not served, the way Express's `send` does
|
|
45
|
+
* it. Media players and download managers ask for one range at a time;
|
|
46
|
+
* - a file whose length is unknown (`undefined`, negative, not an integer): a `206` must name the total length.
|
|
47
|
+
*
|
|
48
|
+
* `'unsatisfiable'` is the answer to a single range that starts at or past the end of the file, or a suffix range
|
|
49
|
+
* of length 0 — and to every range of an EMPTY file, which has no byte to start at.
|
|
50
|
+
*
|
|
51
|
+
* A range that ends past the file is cut at its last byte, and a suffix longer than the file is the whole file —
|
|
52
|
+
* both are satisfiable by definition, so a client may ask for `bytes=0-` or `bytes=0-999999999` without knowing
|
|
53
|
+
* the size.
|
|
54
|
+
*
|
|
55
|
+
* Pure function, no I/O — the HTTP glue (`resolveDownloadRange()`, `setDownloadRangeHeaders()`) lives next to
|
|
56
|
+
* `pipeFileToResponse()` in the file module.
|
|
57
|
+
*/
|
|
58
|
+
export function parseRangeHeader(
|
|
59
|
+
header: string | string[] | undefined,
|
|
60
|
+
length: number | undefined,
|
|
61
|
+
): RangeHeaderDecision {
|
|
62
|
+
if (typeof length !== 'number' || !Number.isSafeInteger(length) || length < 0) {
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
// Node joins repeated headers with ', ' — a repeated Range header is a list of ranges, answered with the whole file
|
|
66
|
+
const value = Array.isArray(header) ? header.join(',') : header;
|
|
67
|
+
if (typeof value !== 'string' || !value || value.length > MAX_RANGE_HEADER_LENGTH) {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
const unit = RANGE_UNIT.exec(value);
|
|
71
|
+
if (!unit) {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
// Empty list elements are allowed and ignored (RFC 9110 §5.6.1)
|
|
75
|
+
const specs = unit[1]
|
|
76
|
+
.split(',')
|
|
77
|
+
.map((spec) => spec.trim())
|
|
78
|
+
.filter(Boolean);
|
|
79
|
+
if (specs.length !== 1) {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
const match = RANGE_SPEC.exec(specs[0]);
|
|
83
|
+
if (!match) {
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
const [, first, last] = match;
|
|
87
|
+
if (!first && !last) {
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
if (!first) {
|
|
91
|
+
// Suffix range: the last N bytes
|
|
92
|
+
const suffix = toSafeInteger(last);
|
|
93
|
+
if (suffix === undefined) {
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
if (suffix === 0 || length === 0) {
|
|
97
|
+
return 'unsatisfiable';
|
|
98
|
+
}
|
|
99
|
+
return { end: length - 1, start: Math.max(0, length - suffix) };
|
|
100
|
+
}
|
|
101
|
+
const start = toSafeInteger(first);
|
|
102
|
+
const end = last ? toSafeInteger(last) : length - 1;
|
|
103
|
+
if (start === undefined || end === undefined) {
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
if (last && end < start) {
|
|
107
|
+
// `bytes=5-2` is invalid, not unsatisfiable — ignored
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
if (start >= length) {
|
|
111
|
+
return 'unsatisfiable';
|
|
112
|
+
}
|
|
113
|
+
return { end: Math.min(end, length - 1), start };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Check a range handed to a store read: two safe integers, `0 <= start <= end`. Returns it unchanged, `undefined`
|
|
118
|
+
* for no range, and throws a `RangeError` for anything else — the same answer from every store, before any of them
|
|
119
|
+
* is asked (each would otherwise fail in its own way: S3 with `InvalidRange`, GridFS with a driver error on the
|
|
120
|
+
* stream, the filesystem with a silently empty stream).
|
|
121
|
+
*/
|
|
122
|
+
export function assertByteRange(range: unknown): ByteRange | undefined {
|
|
123
|
+
if (range === undefined || range === null) {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
const { end, start } = range as { end: number; start: number };
|
|
127
|
+
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start) {
|
|
128
|
+
throw new RangeError(
|
|
129
|
+
`Invalid byte range { start: ${String(start)}, end: ${String(end)} }: start and end must be integers with 0 <= start <= end (end inclusive)`,
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
return { end, start };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** The `Content-Range` value of a range of a file with `length` bytes: `bytes 0-1/1234` */
|
|
136
|
+
export function contentRangeValue(range: ByteRange, length: number): string {
|
|
137
|
+
return `bytes ${range.start}-${range.end}/${length}`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Digits as a safe integer, `undefined` when they exceed what a Number holds exactly */
|
|
141
|
+
function toSafeInteger(digits: string): number | undefined {
|
|
142
|
+
const value = Number(digits);
|
|
143
|
+
return Number.isSafeInteger(value) ? value : undefined;
|
|
144
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { mongo, Types } from 'mongoose';
|
|
2
2
|
import { Readable } from 'stream';
|
|
3
3
|
import { newObjectId } from '../persistence/mongo/mongoose-compat.js';
|
|
4
|
+
import type { ByteRange } from './byte-range.helper.js';
|
|
4
5
|
|
|
5
6
|
// Use Mongoose's MongoDB types to avoid BSON version conflicts
|
|
6
7
|
|
|
@@ -298,18 +299,31 @@ export class GridFSHelper {
|
|
|
298
299
|
}
|
|
299
300
|
|
|
300
301
|
/**
|
|
301
|
-
* Open download stream by ID
|
|
302
|
+
* Open download stream by ID — with `range`, only those bytes (both inclusive). The range must lie inside the
|
|
303
|
+
* file: GridFS refuses a start or end past its length with an error on the stream.
|
|
302
304
|
*/
|
|
303
|
-
static openDownloadStream(
|
|
305
|
+
static openDownloadStream(
|
|
306
|
+
bucket: GridFSBucket,
|
|
307
|
+
id: string | Types.ObjectId,
|
|
308
|
+
range?: ByteRange,
|
|
309
|
+
): GridFSBucketReadStream {
|
|
304
310
|
const objectId = typeof id === 'string' ? newObjectId(id) : id;
|
|
305
|
-
return bucket.openDownloadStream(objectId);
|
|
311
|
+
return bucket.openDownloadStream(objectId, GridFSHelper.streamRange(range));
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Open download stream by name — with `range`, only those bytes (both inclusive)
|
|
316
|
+
*/
|
|
317
|
+
static openDownloadStreamByName(bucket: GridFSBucket, filename: string, range?: ByteRange): GridFSBucketReadStream {
|
|
318
|
+
return bucket.openDownloadStreamByName(filename, GridFSHelper.streamRange(range));
|
|
306
319
|
}
|
|
307
320
|
|
|
308
321
|
/**
|
|
309
|
-
*
|
|
322
|
+
* The GridFS stream options of a range. GridFS counts `end` EXCLUSIVE (the byte after the last one), HTTP and
|
|
323
|
+
* `ByteRange` count it inclusive — hence the `+ 1`.
|
|
310
324
|
*/
|
|
311
|
-
static
|
|
312
|
-
return
|
|
325
|
+
static streamRange(range?: ByteRange): undefined | { end: number; start: number } {
|
|
326
|
+
return range ? { end: range.end + 1, start: range.start } : undefined;
|
|
313
327
|
}
|
|
314
328
|
|
|
315
329
|
/**
|
|
@@ -4,6 +4,7 @@ import { Agent as HttpsAgent } from 'https';
|
|
|
4
4
|
import { PassThrough } from 'stream';
|
|
5
5
|
|
|
6
6
|
import { buildContentDisposition } from '../helpers/content-disposition.helper.js';
|
|
7
|
+
import { assertByteRange, type ByteRange } from '../helpers/byte-range.helper.js';
|
|
7
8
|
import { DEFAULT_STREAM_IDLE_TIMEOUT_MS, guardIdleStream, MAX_TIMER_DELAY_MS } from '../helpers/idle-stream.helper.js';
|
|
8
9
|
import { ConfigService } from './config.service.js';
|
|
9
10
|
|
|
@@ -701,6 +702,11 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
|
|
|
701
702
|
/**
|
|
702
703
|
* Get an object stream (plus metadata) from the main bucket.
|
|
703
704
|
* Throws the SDK's NoSuchKey error when the object does not exist.
|
|
705
|
+
*
|
|
706
|
+
* With `range`, only those bytes are read (`Range: bytes=<start>-<end>`, end inclusive): `contentLength` is then
|
|
707
|
+
* the length of the range and `contentRange` S3's `bytes <start>-<end>/<total>`. The range must lie inside the
|
|
708
|
+
* object — a range starting past its end is refused by S3 with `InvalidRange`; `resolveDownloadRange()` produces a
|
|
709
|
+
* valid one from a request's `Range` header. A malformed range throws a `RangeError` before S3 is asked.
|
|
704
710
|
*/
|
|
705
711
|
async getObject(
|
|
706
712
|
key: string,
|
|
@@ -712,14 +718,21 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
|
|
|
712
718
|
* its turn comes) AND is certain to read it to the end or destroy it; such a body holds its socket until then.
|
|
713
719
|
*/
|
|
714
720
|
idleTimeoutMs?: false | number;
|
|
721
|
+
/** Read only these bytes (both inclusive). Since 12.9.3. */
|
|
722
|
+
range?: ByteRange;
|
|
715
723
|
},
|
|
716
|
-
): Promise<{ body: Readable; contentLength?: number; contentType?: string }> {
|
|
724
|
+
): Promise<{ body: Readable; contentLength?: number; contentRange?: string; contentType?: string }> {
|
|
717
725
|
const { client, config, sdk } = this.requireInit();
|
|
726
|
+
const range = assertByteRange(options?.range);
|
|
718
727
|
// `abortSignal`: a caller whose client has gone aborts the request, also while it still waits for a socket —
|
|
719
728
|
// otherwise it stays queued and takes a socket and a body later, for nobody (see `IS3Config.maxSockets`)
|
|
720
729
|
const idleMs = options?.idleTimeoutMs;
|
|
721
730
|
const result = await client.send(
|
|
722
|
-
new sdk.GetObjectCommand({
|
|
731
|
+
new sdk.GetObjectCommand({
|
|
732
|
+
Bucket: config.bucket,
|
|
733
|
+
Key: key,
|
|
734
|
+
...(range ? { Range: `bytes=${range.start}-${range.end}` } : {}),
|
|
735
|
+
}),
|
|
723
736
|
options?.abortSignal ? { abortSignal: options.abortSignal } : undefined,
|
|
724
737
|
);
|
|
725
738
|
return {
|
|
@@ -734,6 +747,7 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
|
|
|
734
747
|
},
|
|
735
748
|
}),
|
|
736
749
|
contentLength: result.ContentLength,
|
|
750
|
+
...(result.ContentRange ? { contentRange: result.ContentRange } : {}),
|
|
737
751
|
contentType: result.ContentType,
|
|
738
752
|
};
|
|
739
753
|
}
|
|
@@ -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
|
// =====================================================
|
|
@@ -240,5 +240,6 @@ personal or medical, a per-file rule is not optional.
|
|
|
240
240
|
| `super(connection)` in `FileService` with `file.storage: 's3'` | Boot fails: "that storage is not available" | Forward `{ configService, s3Service }` — step 6 |
|
|
241
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
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") |
|
|
243
244
|
| S3 packages in `devDependencies` | Production image cannot load S3 | Move them to `dependencies` — step 6 |
|
|
244
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
|
|
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
|
|
|
@@ -551,6 +557,72 @@ Layers below it, each effective on its own:
|
|
|
551
557
|
waits for a socket instead of taking one later. The framework's routes do this.
|
|
552
558
|
- `s3.presignedDownloads` moves the bytes off the API entirely (a `302` to S3) — consider it for public files.
|
|
553
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
|
+
|
|
554
626
|
### Upload filtering
|
|
555
627
|
|
|
556
628
|
Upload endpoints are project-specific, but the filter they install comes from the framework
|