@lenne.tech/nest-server 12.6.10 → 12.6.12
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/configurable-features.md +1 -1
- 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/ai/core-ai.controller.js +8 -4
- package/dist/core/modules/ai/core-ai.controller.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 +6 -0
- package/dist/core/modules/file/core-file.controller.js +92 -27
- 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/docs/security-overrides.md +31 -4
- package/migration-guides/12.6.10-to-12.6.11.md +75 -0
- package/migration-guides/12.6.11-to-12.6.12.md +180 -0
- package/migration-guides/12.6.9-to-12.6.10.md +15 -3
- package/package.json +6 -6
- 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/ai/core-ai.controller.ts +12 -4
- package/src/core/modules/error-code/error-codes.ts +13 -0
- package/src/core/modules/file/INTEGRATION-CHECKLIST.md +17 -15
- package/src/core/modules/file/README.md +91 -3
- package/src/core/modules/file/core-file.controller.ts +202 -32
- 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,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.6.12. */
|
|
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
|
}
|
|
@@ -122,7 +122,9 @@ export class CoreAiController {
|
|
|
122
122
|
@Body() input: CoreAiPromptInput,
|
|
123
123
|
@Res() res: Response,
|
|
124
124
|
): Promise<void> {
|
|
125
|
-
|
|
125
|
+
// `no-transform` keeps a `compression` middleware out of the stream: gzip would otherwise hold every event until
|
|
126
|
+
// the response ends (measured: events written at 0, 300 and 600 ms all arrived together at about 900 ms)
|
|
127
|
+
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
|
126
128
|
res.setHeader('Connection', 'keep-alive');
|
|
127
129
|
res.setHeader('Content-Type', 'text/event-stream');
|
|
128
130
|
// Disable proxy-side response buffering (nginx and friends honour this); without
|
|
@@ -136,17 +138,23 @@ export class CoreAiController {
|
|
|
136
138
|
// idle connection at 60 s, which the client then sees as a turn that silently
|
|
137
139
|
// vanished. Comment frames are ignored by every SSE client and keep the
|
|
138
140
|
// connection observably alive.
|
|
141
|
+
// A compressor that ignores `no-transform` still sends what was written once it is flushed (`compression` adds
|
|
142
|
+
// `flush()` to the response)
|
|
143
|
+
const send = (chunk: string) => {
|
|
144
|
+
res.write(chunk);
|
|
145
|
+
(res as Response & { flush?: () => void }).flush?.();
|
|
146
|
+
};
|
|
139
147
|
const heartbeat = setInterval(() => {
|
|
140
|
-
|
|
148
|
+
send(': keep-alive\n\n');
|
|
141
149
|
}, 15_000);
|
|
142
150
|
heartbeat.unref?.();
|
|
143
151
|
|
|
144
152
|
try {
|
|
145
153
|
for await (const event of this.aiService.promptStream(input, serviceOptions)) {
|
|
146
|
-
|
|
154
|
+
send(`data: ${JSON.stringify(event)}\n\n`);
|
|
147
155
|
}
|
|
148
156
|
} catch (err) {
|
|
149
|
-
|
|
157
|
+
send(`data: ${JSON.stringify({ message: (err as Error).message, type: 'error' })}\n\n`);
|
|
150
158
|
} finally {
|
|
151
159
|
clearInterval(heartbeat);
|
|
152
160
|
res.end();
|
|
@@ -565,6 +565,19 @@ export const LtnsErrors = {
|
|
|
565
565
|
},
|
|
566
566
|
},
|
|
567
567
|
|
|
568
|
+
/**
|
|
569
|
+
* A download asked for a byte range that starts at or past the end of the file (`Range` header, HTTP 416). The
|
|
570
|
+
* response carries `Content-Range: bytes * /<length>` (without the space), so the client learns the real size.
|
|
571
|
+
*/
|
|
572
|
+
FILE_RANGE_NOT_SATISFIABLE: {
|
|
573
|
+
code: 'LTNS_0503',
|
|
574
|
+
message: 'Requested range not satisfiable',
|
|
575
|
+
translations: {
|
|
576
|
+
de: 'Der angeforderte Bereich liegt außerhalb der Datei.',
|
|
577
|
+
en: 'The requested range lies outside the file.',
|
|
578
|
+
},
|
|
579
|
+
},
|
|
580
|
+
|
|
568
581
|
// =====================================================
|
|
569
582
|
// Internal Errors (LTNS_0900-LTNS_0999)
|
|
570
583
|
// =====================================================
|
|
@@ -226,18 +226,20 @@ personal or medical, a per-file rule is not optional.
|
|
|
226
226
|
|
|
227
227
|
## Common Mistakes
|
|
228
228
|
|
|
229
|
-
| Mistake
|
|
230
|
-
|
|
|
231
|
-
| Overriding `getFileById` to add Swagger decorators
|
|
232
|
-
| Overriding without re-declaring `@Get(...)`
|
|
233
|
-
| `downloadRoles: []`
|
|
234
|
-
| Expecting `metadata` back from `getFileInfo()`
|
|
235
|
-
| `downloadRoles: ['member']` with multiTenancy
|
|
236
|
-
| Signed-in user can upload via TUS but not download
|
|
237
|
-
| Rule narrows only `'id'` / `'filename'`
|
|
238
|
-
| Treating the file id as unguessable
|
|
239
|
-
| Approving the caller's `filterArgs` as "narrowed"
|
|
240
|
-
| `super(connection)` in `FileService` with `file.storage: 's3'`
|
|
241
|
-
| Own download route with `stream.pipe(res)`
|
|
242
|
-
|
|
|
243
|
-
|
|
|
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.6.11+) |
|
|
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.6.12+, 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.6.12+) — 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.6.12 `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,9 @@ 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
|
+
| The client left mid-transfer and the store reports the abort (S3: `aborted`) (12.6.12+) | — | Nothing is sent; logged at debug, never as ERROR |
|
|
507
|
+
| `Range` names one range inside the file (12.6.12+) | `206` | `Content-Range: bytes <start>-<end>/<length>`, only those bytes |
|
|
508
|
+
| `Range` starts at or past the end of the file (12.6.12+) | `416` | `Content-Range: bytes */<length>`, `ErrorCode.FILE_RANGE_NOT_SATISFIABLE` |
|
|
502
509
|
|
|
503
510
|
### Delivering a file from your own route (12.6.10)
|
|
504
511
|
|
|
@@ -509,10 +516,25 @@ check stays green. A production outage had exactly this cause. `pipeFileToRespon
|
|
|
509
516
|
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
517
|
had already gone before the call — and answers a store error before the first byte with `404`.
|
|
511
518
|
|
|
519
|
+
**Open the stream with `openDownloadStream(res, open)` (12.6.11+)**, the function the framework's own routes use. It
|
|
520
|
+
does not ask the store when the client has already gone, destroys a stream that arrives after the client left, and
|
|
521
|
+
answers `503` with `Retry-After` when the store hands out no connection in time. It also turns a store request that
|
|
522
|
+
failed BECAUSE the client left into `RESPONSE_GONE`: an S3 request aborted through `downloadAbortSignal(res)` rejects
|
|
523
|
+
with `AbortError`, and without it every aborted download is an ERROR with a stack trace in the log and a `500` sent
|
|
524
|
+
into a closed response — under the load the `S3 socket pool exhausted:` line has to stand out in.
|
|
525
|
+
|
|
512
526
|
```typescript
|
|
513
|
-
import { downloadAbortSignal, pipeFileToResponse } from '@lenne.tech/nest-server';
|
|
527
|
+
import { downloadAbortSignal, openDownloadStream, pipeFileToResponse, RESPONSE_GONE } from '@lenne.tech/nest-server';
|
|
514
528
|
|
|
515
|
-
const stream = await
|
|
529
|
+
const stream = await openDownloadStream(res, () =>
|
|
530
|
+
this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser }),
|
|
531
|
+
);
|
|
532
|
+
if (stream === RESPONSE_GONE) {
|
|
533
|
+
return res; // nobody left to deliver to
|
|
534
|
+
}
|
|
535
|
+
if (!stream) {
|
|
536
|
+
throw new NotFoundException();
|
|
537
|
+
}
|
|
516
538
|
return pipeFileToResponse(stream, res);
|
|
517
539
|
```
|
|
518
540
|
|
|
@@ -536,6 +558,72 @@ Layers below it, each effective on its own:
|
|
|
536
558
|
waits for a socket instead of taking one later. The framework's routes do this.
|
|
537
559
|
- `s3.presignedDownloads` moves the bytes off the API entirely (a `302` to S3) — consider it for public files.
|
|
538
560
|
|
|
561
|
+
### Byte ranges: video, audio, resumed downloads (12.6.12)
|
|
562
|
+
|
|
563
|
+
Safari refuses to play a video — and stalls audio — from a server that answers a `Range` request with `200` and the
|
|
564
|
+
whole file. Chrome plays it anyway, so the problem does not show locally or in a Chromium-based Playwright run. Media
|
|
565
|
+
players seek with ranges, download managers resume with them.
|
|
566
|
+
|
|
567
|
+
The framework's download routes answer ranges on every store. For a route of your own, three pieces:
|
|
568
|
+
|
|
569
|
+
| Piece | What it does |
|
|
570
|
+
| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
571
|
+
| `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 |
|
|
572
|
+
| `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 |
|
|
573
|
+
| `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()` |
|
|
574
|
+
|
|
575
|
+
```typescript
|
|
576
|
+
import {
|
|
577
|
+
downloadAbortSignal,
|
|
578
|
+
openDownloadStream,
|
|
579
|
+
pipeFileToResponse,
|
|
580
|
+
resolveDownloadRange,
|
|
581
|
+
RESPONSE_GONE,
|
|
582
|
+
setDownloadRangeHeaders,
|
|
583
|
+
} from '@lenne.tech/nest-server';
|
|
584
|
+
|
|
585
|
+
@Get('video/:id')
|
|
586
|
+
async video(@Param('id') id: string, @Res() res: Response, @CurrentUser() currentUser) {
|
|
587
|
+
const serviceOptions = { abortSignal: downloadAbortSignal(res), currentUser };
|
|
588
|
+
const resolved = await this.fileService.resolveFile(id, serviceOptions); // rights check, length, store
|
|
589
|
+
if (!resolved) {
|
|
590
|
+
throw new NotFoundException();
|
|
591
|
+
}
|
|
592
|
+
const range = resolveDownloadRange(res, resolved.info.length); // throws 416 past the end
|
|
593
|
+
const stream = await openDownloadStream(res, () =>
|
|
594
|
+
this.fileService.getFileStream(id, { ...serviceOptions, range }, resolved.store),
|
|
595
|
+
);
|
|
596
|
+
if (stream === RESPONSE_GONE) {
|
|
597
|
+
return res;
|
|
598
|
+
}
|
|
599
|
+
if (!stream) {
|
|
600
|
+
throw new NotFoundException();
|
|
601
|
+
}
|
|
602
|
+
res.header('Content-Type', resolved.info.contentType || 'video/mp4');
|
|
603
|
+
res.header('Cache-Control', 'private, no-store');
|
|
604
|
+
setDownloadRangeHeaders(res, range, resolved.info.length);
|
|
605
|
+
return pipeFileToResponse(stream, res);
|
|
606
|
+
}
|
|
607
|
+
```
|
|
608
|
+
|
|
609
|
+
What is served, and why:
|
|
610
|
+
|
|
611
|
+
- **One range per request.** Several ranges (`bytes=0-1,5-9`) get the whole file with `200` — a `multipart/byteranges`
|
|
612
|
+
answer is not built, the way Express's `send` handles it. Every media player asks for one range at a time.
|
|
613
|
+
- **A range past the end is cut at the last byte** (`bytes=0-999999999` is the whole file), a suffix longer than the
|
|
614
|
+
file is the whole file. Only a range STARTING at or past the end is `416`, and every range of an empty file.
|
|
615
|
+
- **An invalid header** (`bytes=5-2`, another unit) is ignored: the whole file with `200`, which every client can use.
|
|
616
|
+
- **`If-Range` gets the whole file.** The routes' validator is a weak `ETag`, which `If-Range` never matches
|
|
617
|
+
(RFC 9110 §13.1.5). A route with a strong validator can decide `If-Range` itself and call `parseRangeHeader()`.
|
|
618
|
+
- **`no-transform` on a `206`** keeps `compression` away: a gzipped partial body would no longer match the offsets in
|
|
619
|
+
its `Content-Range`. A whole file is compressed as before (when its type is compressible).
|
|
620
|
+
- **`range` on the service must lie inside the file** — `resolveDownloadRange()` guarantees it. A malformed range
|
|
621
|
+
(negative, not an integer, `start > end`) throws a `RangeError` before any store is asked; a range reaching past the
|
|
622
|
+
end of the file is not checked by the service and fails per store (GridFS: an error on the stream, S3: `InvalidRange`
|
|
623
|
+
for a start past the end).
|
|
624
|
+
- **Presigned downloads** (`s3.presignedDownloads`) redirect before any of this: the browser sends its `Range` to S3,
|
|
625
|
+
which answers it itself.
|
|
626
|
+
|
|
539
627
|
### Upload filtering
|
|
540
628
|
|
|
541
629
|
Upload endpoints are project-specific, but the filter they install comes from the framework
|