@lenne.tech/nest-server 12.8.8 → 12.9.0
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/architecture.md +1 -1
- package/.claude/rules/configurable-features.md +1 -0
- package/.claude/rules/testing.md +4 -4
- package/CLAUDE.md +2 -2
- package/FRAMEWORK-API.md +7 -1
- package/bin/check-unified-field-types.js +15 -3
- package/dist/core/common/decorators/unified-field.decorator.js +10 -11
- package/dist/core/common/decorators/unified-field.decorator.js.map +1 -1
- package/dist/core/common/helpers/idle-stream.helper.d.ts +14 -0
- package/dist/core/common/helpers/idle-stream.helper.js +94 -0
- package/dist/core/common/helpers/idle-stream.helper.js.map +1 -0
- package/dist/core/common/interfaces/server-options.interface.d.ts +6 -0
- package/dist/core/common/services/core-s3.service.d.ts +27 -1
- package/dist/core/common/services/core-s3.service.js +89 -3
- package/dist/core/common/services/core-s3.service.js.map +1 -1
- package/dist/core/modules/file/core-file.controller.d.ts +16 -0
- package/dist/core/modules/file/core-file.controller.js +215 -8
- package/dist/core/modules/file/core-file.controller.js.map +1 -1
- package/dist/core/modules/file/core-file.service.d.ts +5 -0
- package/dist/core/modules/file/core-file.service.js +17 -7
- package/dist/core/modules/file/core-file.service.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 +4 -1
- package/dist/core/modules/file/s3-file.helper.js +2 -2
- 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/main.js +1 -3
- package/dist/main.js.map +1 -1
- package/docs/REQUEST-LIFECYCLE.md +6 -6
- package/migration-guides/12.8.6-to-12.8.7.md +3 -3
- package/migration-guides/12.8.8-to-12.8.9.md +149 -0
- package/migration-guides/12.8.x-to-12.9.x.md +105 -0
- package/package.json +4 -4
- package/src/core/common/decorators/unified-field.decorator.ts +20 -22
- package/src/core/common/helpers/idle-stream.helper.ts +192 -0
- package/src/core/common/interfaces/server-options.interface.ts +78 -0
- package/src/core/common/services/core-s3.service.ts +186 -3
- package/src/core/modules/file/INTEGRATION-CHECKLIST.md +15 -14
- package/src/core/modules/file/README.md +48 -0
- package/src/core/modules/file/core-file.controller.ts +356 -10
- package/src/core/modules/file/core-file.service.ts +46 -7
- package/src/core/modules/file/interfaces/file-service-options.interface.ts +22 -0
- package/src/core/modules/file/s3-file.helper.ts +6 -2
- package/src/index.ts +1 -0
- package/src/main.ts +3 -3
|
@@ -226,17 +226,18 @@ personal or medical, a per-file rule is not optional.
|
|
|
226
226
|
|
|
227
227
|
## Common Mistakes
|
|
228
228
|
|
|
229
|
-
| Mistake | Symptom
|
|
230
|
-
| -------------------------------------------------------------- |
|
|
231
|
-
| Overriding `getFileById` to add Swagger decorators | `file.downloadRoles` silently ignored
|
|
232
|
-
| Overriding without re-declaring `@Get(...)` | Route 404s for everyone, no error logged
|
|
233
|
-
| `downloadRoles: []` | Warning logged, default applied
|
|
234
|
-
| Expecting `metadata` back from `getFileInfo()` | `undefined`
|
|
235
|
-
| `downloadRoles: ['member']` with multiTenancy | Works from code, fails from `<img>`
|
|
236
|
-
| Signed-in user can upload via TUS but not download | 403 on their own file
|
|
237
|
-
| Rule narrows only `'id'` / `'filename'` | `findFileInfo()` returns every file
|
|
238
|
-
| Treating the file id as unguessable | Enumerable inventory
|
|
239
|
-
| Approving the caller's `filterArgs` as "narrowed" | Bypass via a different filter shape
|
|
240
|
-
| `super(connection)` in `FileService` with `file.storage: 's3'` | Boot fails: "that storage is not available"
|
|
241
|
-
|
|
|
242
|
-
|
|
|
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 |
|
|
@@ -41,6 +41,12 @@ file: {
|
|
|
41
41
|
|
|
42
42
|
`storage` and the role knobs are orthogonal: one picks the driver, the others the access.
|
|
43
43
|
|
|
44
|
+
Downloads (12.8.9+): `downloadIdleTimeoutMs` (30 000) closes a download stream that makes no read progress, so an
|
|
45
|
+
aborted or dropped download releases its file handle or GridFS cursor; `downloadCaching: 'revalidate'` lets the browser
|
|
46
|
+
keep a file and revalidate it (`304` after the rights check, no store read). S3 has its own pool settings under `s3`
|
|
47
|
+
(`maxSockets`, `connectionTimeoutMs`, `socketTimeoutMs`, `downloadIdleTimeoutMs`) — see
|
|
48
|
+
[Delivering a file from your own route](#delivering-a-file-from-your-own-route-1289).
|
|
49
|
+
|
|
44
50
|
## Storage drivers
|
|
45
51
|
|
|
46
52
|
Three equivalent options. They differ only in where the bytes end up:
|
|
@@ -488,6 +494,48 @@ server-side even though the client answer stays deliberately generic.
|
|
|
488
494
|
To change the status, the body or the logging, override the `protected pipeFileToResponse()` method
|
|
489
495
|
on the controller rather than the exported function of the same name.
|
|
490
496
|
|
|
497
|
+
| Situation (12.8.9+) | Status | Body / headers |
|
|
498
|
+
| ------------------------------------------------------------------------------------------- | ------ | ------------------------------------------------------------------------------ |
|
|
499
|
+
| `If-None-Match` names the file's weak `ETag` (`W/"<id>"`), after the rights check | `304` | No body; the store is not read |
|
|
500
|
+
| 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
|
+
| The client left before the stream was handed over | — | Nothing is sent; the stream is destroyed at once, a pending S3 request aborted |
|
|
502
|
+
|
|
503
|
+
### Delivering a file from your own route (12.8.9)
|
|
504
|
+
|
|
505
|
+
**Use `pipeFileToResponse(stream, res)` for every download route of your own — never `stream.pipe(res)`.**
|
|
506
|
+
When the client aborts, `pipe()` only unpipes: the source stays open and keeps what it holds — for S3 a socket of the
|
|
507
|
+
client's pool. Enough aborted downloads and the pool is full; every S3 request then waits forever while the health
|
|
508
|
+
check stays green. A production outage had exactly this cause. `pipeFileToResponse()` destroys the source when the
|
|
509
|
+
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
|
+
had already gone before the call — and answers a store error before the first byte with `404`.
|
|
511
|
+
|
|
512
|
+
```typescript
|
|
513
|
+
import { downloadAbortSignal, pipeFileToResponse } from '@lenne.tech/nest-server';
|
|
514
|
+
|
|
515
|
+
const stream = await this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser });
|
|
516
|
+
return pipeFileToResponse(stream, res);
|
|
517
|
+
```
|
|
518
|
+
|
|
519
|
+
Layers below it, each effective on its own:
|
|
520
|
+
|
|
521
|
+
- Every stream from `CoreFileService.getFileStream()` / `getFileStreamByName()` and `CoreS3Service.getObject()` closes
|
|
522
|
+
itself after `downloadIdleTimeoutMs` (30 s) without read progress. A slow reader that keeps reading is never cut off.
|
|
523
|
+
**Read a stream right after obtaining it**: code that collects streams and reads them later (a ZIP export appending
|
|
524
|
+
every file first) breaks — the closed stream ends without `end`. Open each stream right before it is read, or opt out
|
|
525
|
+
for that call with `downloadIdleTimeoutMs: false` (`getObject(key, { idleTimeoutMs: false })`) when the code is
|
|
526
|
+
certain to read it to the end or destroy it.
|
|
527
|
+
- The S3 client runs with its own agents: `s3.maxSockets` (200 instead of the SDK's 50), `s3.connectionTimeoutMs`
|
|
528
|
+
(15 s per attempt — the bound for waiting for a socket, too; the SDK makes 3 attempts, so a download that gets no
|
|
529
|
+
socket answers `503` after about 46 s, below the common 60 s proxy timeout), `s3.socketTimeoutMs` (120 s inactivity
|
|
530
|
+
backstop).
|
|
531
|
+
- An exhausted pool is logged as an ERROR once per minute with numbers (`S3 socket pool exhausted: …`) — alert on it.
|
|
532
|
+
Downloads closed for lack of progress are one WARN line per minute, never an ERROR per download.
|
|
533
|
+
`CoreS3Service.getSocketPoolStats()` gives the same numbers to a project's monitoring. It is deliberately not a
|
|
534
|
+
health-check failure: a short S3 disturbance would take the whole API out of the load balancer.
|
|
535
|
+
- Pass `abortSignal` (aborted when the response closes) so an S3 request whose client has gone is dropped while it
|
|
536
|
+
waits for a socket instead of taking one later. The framework's routes do this.
|
|
537
|
+
- `s3.presignedDownloads` moves the bytes off the API entirely (a `302` to S3) — consider it for public files.
|
|
538
|
+
|
|
491
539
|
### Upload filtering
|
|
492
540
|
|
|
493
541
|
Upload endpoints are project-specific, but the filter they install comes from the framework
|
|
@@ -1,4 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
BadRequestException,
|
|
3
|
+
Controller,
|
|
4
|
+
Get,
|
|
5
|
+
Logger,
|
|
6
|
+
NotFoundException,
|
|
7
|
+
Param,
|
|
8
|
+
Res,
|
|
9
|
+
ServiceUnavailableException,
|
|
10
|
+
} from '@nestjs/common';
|
|
2
11
|
import type { Response } from 'express';
|
|
3
12
|
import type { Readable } from 'stream';
|
|
4
13
|
|
|
@@ -6,6 +15,8 @@ import { CurrentUser } from '../../common/decorators/current-user.decorator.js';
|
|
|
6
15
|
import { Roles } from '../../common/decorators/roles.decorator.js';
|
|
7
16
|
import { RoleEnum } from '../../common/enums/role.enum.js';
|
|
8
17
|
import { buildContentDisposition } from '../../common/helpers/content-disposition.helper.js';
|
|
18
|
+
import { StreamIdleTimeoutError } from '../../common/helpers/idle-stream.helper.js';
|
|
19
|
+
import { ConfigService } from '../../common/services/config.service.js';
|
|
9
20
|
import { ErrorCode } from '../error-code/error-codes.js';
|
|
10
21
|
import { SkipTenantCheck } from '../tenant/core-tenant.decorators.js';
|
|
11
22
|
import { CoreFileService } from './core-file.service.js';
|
|
@@ -13,6 +24,110 @@ import type { FileServiceOptions } from './interfaces/file-service-options.inter
|
|
|
13
24
|
|
|
14
25
|
const fileStreamLogger = new Logger('CoreFileController');
|
|
15
26
|
|
|
27
|
+
/**
|
|
28
|
+
* Downloads closed by the idle guard since the last report, and when the last report was written.
|
|
29
|
+
*
|
|
30
|
+
* Reported as ONE warning per minute instead of a line per download: a client that stops reading is not a server
|
|
31
|
+
* error, and under an abort storm a line per event (measured: 20 per second, each with a stack) turns the log into an
|
|
32
|
+
* alert storm. `withOpenConnection` counts the closes whose client connection was still open — clients that stopped
|
|
33
|
+
* reading without closing; the rest were waiting on a store that delivered nothing.
|
|
34
|
+
*/
|
|
35
|
+
const idleCloses = { afterResponseClose: 0, lastReportAt: 0, sample: '', total: 0, withOpenConnection: 0 };
|
|
36
|
+
const IDLE_CLOSE_REPORT_INTERVAL_MS = 60_000;
|
|
37
|
+
|
|
38
|
+
/** An idle close of the download guard — by class or by code, so a second copy of the helper module counts too. */
|
|
39
|
+
function isStreamIdleTimeout(error: unknown): error is StreamIdleTimeoutError {
|
|
40
|
+
return error instanceof StreamIdleTimeoutError || (error as { code?: string })?.code === 'LT_STREAM_IDLE_TIMEOUT';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function reportIdleClose(
|
|
44
|
+
res: Response,
|
|
45
|
+
error: StreamIdleTimeoutError,
|
|
46
|
+
state: { attachedAt: number; clientGoneSignal: string; responseClosed: boolean },
|
|
47
|
+
): void {
|
|
48
|
+
idleCloses.total++;
|
|
49
|
+
const socket = (res as Response & { socket?: { destroyed?: boolean } | null }).socket;
|
|
50
|
+
if (socket && !socket.destroyed) {
|
|
51
|
+
idleCloses.withOpenConnection++;
|
|
52
|
+
}
|
|
53
|
+
// A close the response had already reported: the stream should have been destroyed then, not by the idle guard
|
|
54
|
+
if (state.responseClosed) {
|
|
55
|
+
idleCloses.afterResponseClose++;
|
|
56
|
+
}
|
|
57
|
+
if (!idleCloses.sample) {
|
|
58
|
+
const r = res as Response & { closed?: boolean; writableEnded?: boolean };
|
|
59
|
+
const req = (res as Response & { req?: { destroyed?: boolean } }).req;
|
|
60
|
+
idleCloses.sample =
|
|
61
|
+
`example: ${Date.now() - state.attachedAt} ms after delivery started, response closed event ${state.responseClosed}, ` +
|
|
62
|
+
`destroyed ${r.destroyed}, closed ${r.closed}, headersSent ${r.headersSent}, writableEnded ${r.writableEnded}, ` +
|
|
63
|
+
`socket ${socket ? (socket.destroyed ? 'destroyed' : 'open') : 'none'}, request destroyed ${req?.destroyed}, ` +
|
|
64
|
+
`client-gone signal ${state.clientGoneSignal || 'none'}`;
|
|
65
|
+
}
|
|
66
|
+
const now = Date.now();
|
|
67
|
+
if (now - idleCloses.lastReportAt < IDLE_CLOSE_REPORT_INTERVAL_MS) {
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
fileStreamLogger.warn(
|
|
71
|
+
`${idleCloses.total} file download(s) closed after no read progress for ${error.idleMs} ms since the last ` +
|
|
72
|
+
`report (${idleCloses.withOpenConnection} with the client connection still open: clients that stopped reading ` +
|
|
73
|
+
`without closing; ${idleCloses.afterResponseClose} after the response had already closed; ${idleCloses.sample}). ` +
|
|
74
|
+
'This releases the store socket, file handle or cursor; many of them under load hold S3 sockets for that long — ' +
|
|
75
|
+
'see s3.downloadIdleTimeoutMs.',
|
|
76
|
+
);
|
|
77
|
+
idleCloses.lastReportAt = now;
|
|
78
|
+
idleCloses.total = 0;
|
|
79
|
+
idleCloses.withOpenConnection = 0;
|
|
80
|
+
idleCloses.afterResponseClose = 0;
|
|
81
|
+
idleCloses.sample = '';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Release the source on every signal that the client has gone, not only on the response's `close`.
|
|
86
|
+
*
|
|
87
|
+
* Measured under an abort storm (k6, 40 aborts/s against S3 through the full controller route): about one in six
|
|
88
|
+
* aborted downloads never got a `close` on the response although the client's connection was gone on the server side —
|
|
89
|
+
* headers sent, body mid-flight, `res.destroyed` false. Those held their S3 socket until the idle guard ran out. The
|
|
90
|
+
* request and the socket carry the same news through other events: the request closes before its end (it was
|
|
91
|
+
* aborted), and the socket ends or closes. A request whose body was read to the end — a POST export, or any request a
|
|
92
|
+
* body-parsing middleware read — is closed by Node itself on a healthy connection, so its `close` says nothing about
|
|
93
|
+
* the client; the socket listeners still report that client leaving later.
|
|
94
|
+
* Listeners on a keep-alive socket are removed once this response is done, so they never reach the next request.
|
|
95
|
+
*/
|
|
96
|
+
function watchClientGone(stream: Readable, res: Response, state: { clientGoneSignal: string }): void {
|
|
97
|
+
const req = res.req;
|
|
98
|
+
const socket = res.socket;
|
|
99
|
+
const release = (signal: string) => () => {
|
|
100
|
+
if (res.writableFinished || (signal === 'request close' && req?.readableEnded)) {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
state.clientGoneSignal ||= signal;
|
|
104
|
+
if (!stream.destroyed) {
|
|
105
|
+
stream.destroy();
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
const onRequestClose = release('request close');
|
|
109
|
+
const onSocketEnd = release('socket end');
|
|
110
|
+
const onSocketClose = release('socket close');
|
|
111
|
+
if (typeof req?.once === 'function') {
|
|
112
|
+
req.once('close', onRequestClose);
|
|
113
|
+
}
|
|
114
|
+
socket?.once('end', onSocketEnd);
|
|
115
|
+
socket?.once('close', onSocketClose);
|
|
116
|
+
const cleanUp = () => {
|
|
117
|
+
if (typeof req?.removeListener === 'function') {
|
|
118
|
+
req.removeListener('close', onRequestClose);
|
|
119
|
+
}
|
|
120
|
+
socket?.removeListener('end', onSocketEnd);
|
|
121
|
+
socket?.removeListener('close', onSocketClose);
|
|
122
|
+
};
|
|
123
|
+
res.once('finish', cleanUp);
|
|
124
|
+
res.once('close', cleanUp);
|
|
125
|
+
stream.once('close', cleanUp);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Marker of {@link CoreFileController.openDownloadStream}: the client has gone, nothing is to be delivered. */
|
|
129
|
+
export const RESPONSE_GONE = Symbol('lt.responseGone');
|
|
130
|
+
|
|
16
131
|
/**
|
|
17
132
|
* Headers that describe the FILE and must not survive onto an error response.
|
|
18
133
|
*
|
|
@@ -26,7 +141,7 @@ const fileStreamLogger = new Logger('CoreFileController');
|
|
|
26
141
|
* ofetch/`$fetch` client picks its parser from that header and hands the caller a
|
|
27
142
|
* Blob instead of the error message.
|
|
28
143
|
*/
|
|
29
|
-
const FILE_DELIVERY_HEADERS = ['Cache-Control', 'Content-Disposition', 'Content-Type', 'ETag'];
|
|
144
|
+
const FILE_DELIVERY_HEADERS = ['Cache-Control', 'Content-Disposition', 'Content-Length', 'Content-Type', 'ETag'];
|
|
30
145
|
|
|
31
146
|
/**
|
|
32
147
|
* Re-exported from the leaf it now lives in, so no import path broke.
|
|
@@ -39,7 +154,16 @@ const FILE_DELIVERY_HEADERS = ['Cache-Control', 'Content-Disposition', 'Content-
|
|
|
39
154
|
export { buildContentDisposition };
|
|
40
155
|
|
|
41
156
|
/**
|
|
42
|
-
*
|
|
157
|
+
* Deliver a download stream to the response — THE way to answer a download route, for every store
|
|
158
|
+
* (S3, filesystem, GridFS), in the framework's controller and in a project's own routes alike.
|
|
159
|
+
*
|
|
160
|
+
* WHY NOT `stream.pipe(res)`: when the client aborts, `pipe()` only unpipes. The source stays open and
|
|
161
|
+
* paused, and it holds what it was given — for S3 a socket of the client's pool. Enough aborted downloads
|
|
162
|
+
* and the pool is full: every further S3 request waits forever while the health check stays green (a
|
|
163
|
+
* production outage with exactly this cause preceded 12.8.9). This function destroys the source as soon as
|
|
164
|
+
* the response closes, and answers a store error before the first byte with a 404 instead of a dropped
|
|
165
|
+
* connection. (Since 12.8.9 the streams of `CoreFileService` and `CoreS3Service` also release themselves
|
|
166
|
+
* after an idle time — a second layer, not a reason to skip this one.)
|
|
43
167
|
*
|
|
44
168
|
* A GridFS record and its chunks are two separate writes, so a file document can
|
|
45
169
|
* outlive its bytes — an interrupted upload, a restored backup, a manual cleanup.
|
|
@@ -62,18 +186,47 @@ export { buildContentDisposition };
|
|
|
62
186
|
* GridFS read stream and its server-side cursor open on every aborted download.
|
|
63
187
|
*/
|
|
64
188
|
export function pipeFileToResponse(stream: Readable, res: Response): Response {
|
|
189
|
+
// A client that left BEFORE this call (it waited for a free socket of the store, then gave up): its response
|
|
190
|
+
// has already closed, and a `close` listener registered now never fires. Without this check the source was
|
|
191
|
+
// never read nor destroyed and kept its S3 socket — under load an avalanche: a few leaks make downloads slow,
|
|
192
|
+
// waiting clients give up, and every one of them leaks the next socket.
|
|
193
|
+
if (isResponseGone(res)) {
|
|
194
|
+
stream.destroy();
|
|
195
|
+
return res;
|
|
196
|
+
}
|
|
197
|
+
const state = { attachedAt: Date.now(), clientGoneSignal: '', responseClosed: false };
|
|
65
198
|
res.on('close', () => {
|
|
199
|
+
state.responseClosed = true;
|
|
66
200
|
if (!stream.destroyed) {
|
|
67
201
|
stream.destroy();
|
|
68
202
|
}
|
|
69
203
|
});
|
|
204
|
+
watchClientGone(stream, res, state);
|
|
70
205
|
|
|
71
206
|
stream.on('error', (err: Error) => {
|
|
207
|
+
// No read progress for the idle time: a client that stopped reading (or a store that delivers nothing) — not
|
|
208
|
+
// a server error, so no ERROR line per download (see `reportIdleClose`). Before the first byte it was the store
|
|
209
|
+
// that stalled: 503, the client may retry; afterwards only closing the connection remains.
|
|
210
|
+
if (isStreamIdleTimeout(err)) {
|
|
211
|
+
reportIdleClose(res, err, state);
|
|
212
|
+
if (res.headersSent) {
|
|
213
|
+
res.destroy();
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
for (const header of FILE_DELIVERY_HEADERS) {
|
|
217
|
+
res.removeHeader(header);
|
|
218
|
+
}
|
|
219
|
+
res.setHeader('Retry-After', '5');
|
|
220
|
+
res
|
|
221
|
+
.status(503)
|
|
222
|
+
.json({ error: 'Service Unavailable', message: 'File storage is busy, please retry', statusCode: 503 });
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
72
225
|
// The answer to the CLIENT stays deliberately indistinguishable from an
|
|
73
226
|
// unknown id, but the server must not lose the event: a files document
|
|
74
227
|
// without its chunks is data corruption, and an error silently converted
|
|
75
228
|
// into a 404 is one nobody will ever notice.
|
|
76
|
-
fileStreamLogger.error(`
|
|
229
|
+
fileStreamLogger.error(`File download failed: ${err.message}`, err.stack);
|
|
77
230
|
|
|
78
231
|
if (res.headersSent) {
|
|
79
232
|
res.destroy();
|
|
@@ -91,6 +244,72 @@ export function pipeFileToResponse(stream: Readable, res: Response): Response {
|
|
|
91
244
|
return stream.pipe(res);
|
|
92
245
|
}
|
|
93
246
|
|
|
247
|
+
/**
|
|
248
|
+
* Whether the client of a response has gone: the response was destroyed or closed, or its request or socket was.
|
|
249
|
+
*
|
|
250
|
+
* The response alone is not enough. Measured under an abort storm through the full controller route: a share of the
|
|
251
|
+
* aborted downloads reached delivery with the socket and the request already destroyed while the response still read
|
|
252
|
+
* `destroyed: false, closed: false` and never emitted `close` — those held their S3 socket until the idle guard ran
|
|
253
|
+
* out. A request destroyed BEFORE its end was aborted. One destroyed after its body was read to the end has merely
|
|
254
|
+
* completed: Node destroys it by itself then, on a healthy connection (a POST export, or any request whose body a
|
|
255
|
+
* middleware read), so only `destroyed && !readableEnded` counts, next to a destroyed socket.
|
|
256
|
+
*/
|
|
257
|
+
export function isResponseGone(res: Response): boolean {
|
|
258
|
+
const r = res as Response & { closed?: boolean };
|
|
259
|
+
return !!(r.destroyed || r.closed || isRequestAborted(r.req) || r.socket?.destroyed);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** A request destroyed before its end: the client has gone. Node also destroys a request whose body was read to the end. */
|
|
263
|
+
function isRequestAborted(req: undefined | { destroyed?: boolean; readableEnded?: boolean }): boolean {
|
|
264
|
+
return !!req?.destroyed && !req.readableEnded;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* An `AbortSignal` that fires when the client of a download has gone — on the same signals `pipeFileToResponse()`
|
|
269
|
+
* releases a source on: the response closes, the request closes before its end, or the socket ends or closes before
|
|
270
|
+
* the response finished (see {@link isResponseGone} for why the response alone is not enough, and why a request read
|
|
271
|
+
* to the end is not a gone client). Pass it as `abortSignal` to `getFileStream()` / `CoreS3Service.getObject()` from
|
|
272
|
+
* a project's own download route, so an S3 request that still waits for a free socket is dropped instead of taking
|
|
273
|
+
* one later for nobody. The socket listeners are removed once the response is done, so a keep-alive socket carries
|
|
274
|
+
* none of them into its next request.
|
|
275
|
+
*/
|
|
276
|
+
export function downloadAbortSignal(res: Response): AbortSignal {
|
|
277
|
+
const controller = new AbortController();
|
|
278
|
+
if (isResponseGone(res)) {
|
|
279
|
+
controller.abort();
|
|
280
|
+
return controller.signal;
|
|
281
|
+
}
|
|
282
|
+
const req = res.req;
|
|
283
|
+
const socket = res.socket;
|
|
284
|
+
const abortWhileUnfinished = () => {
|
|
285
|
+
if (!res.writableFinished) {
|
|
286
|
+
controller.abort();
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
// A request read to the end is closed by Node itself on a healthy connection — not the client leaving. A client
|
|
290
|
+
// that leaves after its body was read is reported by the socket (and usually the response)
|
|
291
|
+
const abortOnRequestClose = () => {
|
|
292
|
+
if (!req?.readableEnded) {
|
|
293
|
+
abortWhileUnfinished();
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
if (typeof req?.once === 'function') {
|
|
297
|
+
req.once('close', abortOnRequestClose);
|
|
298
|
+
}
|
|
299
|
+
socket?.once('end', abortWhileUnfinished);
|
|
300
|
+
socket?.once('close', abortWhileUnfinished);
|
|
301
|
+
const cleanUp = () => {
|
|
302
|
+
socket?.removeListener('end', abortWhileUnfinished);
|
|
303
|
+
socket?.removeListener('close', abortWhileUnfinished);
|
|
304
|
+
};
|
|
305
|
+
res.once('finish', cleanUp);
|
|
306
|
+
res.once('close', () => {
|
|
307
|
+
cleanUp();
|
|
308
|
+
controller.abort();
|
|
309
|
+
});
|
|
310
|
+
return controller.signal;
|
|
311
|
+
}
|
|
312
|
+
|
|
94
313
|
/**
|
|
95
314
|
* File controller
|
|
96
315
|
*
|
|
@@ -181,7 +400,9 @@ export abstract class CoreFileController {
|
|
|
181
400
|
throw new BadRequestException(ErrorCode.REQUIRED_FIELD_MISSING);
|
|
182
401
|
}
|
|
183
402
|
|
|
184
|
-
|
|
403
|
+
// Registered first: the client may leave while the rights check or the store request is still pending
|
|
404
|
+
const abortSignal = this.downloadAbortSignal(res);
|
|
405
|
+
const serviceOptions = { abortSignal, currentUser };
|
|
185
406
|
// One lookup for both answers — metadata AND which store holds the bytes.
|
|
186
407
|
// getFileInfo() followed by getFileStream() had each probe the three stores
|
|
187
408
|
// from scratch, since neither told the other which one had answered. Same
|
|
@@ -191,6 +412,10 @@ export abstract class CoreFileController {
|
|
|
191
412
|
if (!file) {
|
|
192
413
|
throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
|
|
193
414
|
}
|
|
415
|
+
// Authorized above; a client that already holds these bytes gets 304 without the store being read
|
|
416
|
+
if (this.answerNotModified(res, file)) {
|
|
417
|
+
return res;
|
|
418
|
+
}
|
|
194
419
|
// S3-stored file with presigned downloads enabled: let the client fetch the
|
|
195
420
|
// bytes from S3 directly instead of streaming them through the API.
|
|
196
421
|
//
|
|
@@ -217,7 +442,12 @@ export abstract class CoreFileController {
|
|
|
217
442
|
res.redirect(302, url);
|
|
218
443
|
return res;
|
|
219
444
|
}
|
|
220
|
-
const filestream = await this.
|
|
445
|
+
const filestream = await this.openDownloadStream(res, () =>
|
|
446
|
+
this.fileService.getFileStream(id, serviceOptions, resolved.store),
|
|
447
|
+
);
|
|
448
|
+
if (filestream === RESPONSE_GONE) {
|
|
449
|
+
return res;
|
|
450
|
+
}
|
|
221
451
|
// `getFileStream` answers null when the service's own rights check refuses.
|
|
222
452
|
// Same answer as an unknown id: never confirm that the file exists.
|
|
223
453
|
if (!filestream) {
|
|
@@ -248,11 +478,15 @@ export abstract class CoreFileController {
|
|
|
248
478
|
throw new BadRequestException(ErrorCode.REQUIRED_FIELD_MISSING);
|
|
249
479
|
}
|
|
250
480
|
|
|
251
|
-
const
|
|
481
|
+
const abortSignal = this.downloadAbortSignal(res);
|
|
482
|
+
const serviceOptions = { abortSignal, currentUser };
|
|
252
483
|
const file = await this.fileService.getFileInfoByName(filename, serviceOptions);
|
|
253
484
|
if (!file) {
|
|
254
485
|
throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
|
|
255
486
|
}
|
|
487
|
+
if (this.answerNotModified(res, file)) {
|
|
488
|
+
return res;
|
|
489
|
+
}
|
|
256
490
|
// See getFileById(): authorization on the presigned branch rests on the
|
|
257
491
|
// getFileInfoByName() call above.
|
|
258
492
|
const url = await this.resolveDownloadUrl(file.id, serviceOptions);
|
|
@@ -261,7 +495,12 @@ export abstract class CoreFileController {
|
|
|
261
495
|
res.redirect(302, url);
|
|
262
496
|
return res;
|
|
263
497
|
}
|
|
264
|
-
const filestream = await this.
|
|
498
|
+
const filestream = await this.openDownloadStream(res, () =>
|
|
499
|
+
this.fileService.getFileStream(file.id, serviceOptions),
|
|
500
|
+
);
|
|
501
|
+
if (filestream === RESPONSE_GONE) {
|
|
502
|
+
return res;
|
|
503
|
+
}
|
|
265
504
|
if (!filestream) {
|
|
266
505
|
throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
|
|
267
506
|
}
|
|
@@ -269,6 +508,51 @@ export abstract class CoreFileController {
|
|
|
269
508
|
return this.pipeFileToResponse(filestream, res);
|
|
270
509
|
}
|
|
271
510
|
|
|
511
|
+
/**
|
|
512
|
+
* An `AbortSignal` that fires when the response closes — the client has gone. Passed to the store, so an S3
|
|
513
|
+
* request that still waits for a free socket is dropped instead of taking one later for nobody.
|
|
514
|
+
*/
|
|
515
|
+
protected downloadAbortSignal(res: Response): AbortSignal {
|
|
516
|
+
return downloadAbortSignal(res);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
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).
|
|
525
|
+
*/
|
|
526
|
+
protected async openDownloadStream(
|
|
527
|
+
res: Response,
|
|
528
|
+
open: () => Promise<Readable>,
|
|
529
|
+
): 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;
|
|
554
|
+
}
|
|
555
|
+
|
|
272
556
|
/**
|
|
273
557
|
* Set the response headers that describe the file being delivered.
|
|
274
558
|
*
|
|
@@ -286,12 +570,74 @@ export abstract class CoreFileController {
|
|
|
286
570
|
* are immutable once written, so a validator built from `_id` + `uploadDate`
|
|
287
571
|
* is sound. Do that only for files that are genuinely public.
|
|
288
572
|
*/
|
|
289
|
-
protected setFileHeaders(
|
|
290
|
-
|
|
573
|
+
protected setFileHeaders(
|
|
574
|
+
res: Response,
|
|
575
|
+
file: { contentType?: string; filename?: string; id?: string; length?: number },
|
|
576
|
+
): void {
|
|
577
|
+
this.setCacheHeaders(res, file);
|
|
291
578
|
res.header('Content-Type', file.contentType || 'application/octet-stream');
|
|
292
579
|
// See {@link buildContentDisposition} for why the two filename parameters are
|
|
293
580
|
// rendered differently, and for the injection cases the sanitiser closes.
|
|
294
581
|
res.header('Content-Disposition', buildContentDisposition(file.filename));
|
|
582
|
+
// Lets a client and every proxy see the size up front and detect a truncated transfer. Taken from the
|
|
583
|
+
// stored metadata, which each store records from the bytes it wrote.
|
|
584
|
+
if (typeof file.length === 'number' && Number.isSafeInteger(file.length) && file.length >= 0) {
|
|
585
|
+
res.header('Content-Length', String(file.length));
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* `Cache-Control` and `ETag` of a file response, per `file.downloadCaching`.
|
|
591
|
+
*
|
|
592
|
+
* - `'none'` (default): `private, no-store` — see {@link setFileHeaders} for why.
|
|
593
|
+
* - `'revalidate'`: `private, no-cache` — the BROWSER may keep the file, but must ask again on every use;
|
|
594
|
+
* the request runs the full role and rights check and is answered `304 Not Modified` without the store
|
|
595
|
+
* being read. For image-heavy apps that removes most store reads (and S3 sockets) while every view stays
|
|
596
|
+
* authorized. Shared caches (proxies, CDNs) are still excluded by `private`.
|
|
597
|
+
*
|
|
598
|
+
* The `ETag` is the file id, as a WEAK validator (`W/"<id>"`): the bytes under an id never change (every store
|
|
599
|
+
* writes a new file under a new id; a duplicate is a new id too), but a `compression` middleware in front sends the
|
|
600
|
+
* same file gzip-encoded or not, and RFC 9110 §8.8.3 requires different strong validators for different
|
|
601
|
+
* representations. `If-None-Match` compares weakly anyway, so the 304 works the same.
|
|
602
|
+
*/
|
|
603
|
+
protected setCacheHeaders(res: Response, file: { id?: string }): void {
|
|
604
|
+
const mode = ConfigService.configFastButReadOnly?.file?.downloadCaching;
|
|
605
|
+
res.header('Cache-Control', mode === 'revalidate' ? 'private, no-cache' : 'private, no-store');
|
|
606
|
+
const etag = this.fileEtag(file);
|
|
607
|
+
if (etag) {
|
|
608
|
+
res.header('ETag', etag);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Weak validator of a file: its id, quoted, with `W/` (see {@link setCacheHeaders}). `undefined` without an id.
|
|
614
|
+
*/
|
|
615
|
+
protected fileEtag(file: { id?: string }): string | undefined {
|
|
616
|
+
return file?.id ? `W/"${String(file.id)}"` : undefined;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* Answer `304 Not Modified` when the request's `If-None-Match` names this file's validator.
|
|
621
|
+
*
|
|
622
|
+
* Call it only AFTER the file was resolved with the rights check — a 304 confirms the file exists. Reads the
|
|
623
|
+
* request from `res.req`, so the route signatures (which projects override) stay as they are.
|
|
624
|
+
*/
|
|
625
|
+
protected answerNotModified(res: Response, file: { id?: string }): boolean {
|
|
626
|
+
const etag = this.fileEtag(file);
|
|
627
|
+
const header = (res as Response & { req?: { headers?: Record<string, string | string[] | undefined> } }).req
|
|
628
|
+
?.headers?.['if-none-match'];
|
|
629
|
+
if (!etag || !header) {
|
|
630
|
+
return false;
|
|
631
|
+
}
|
|
632
|
+
// Weak comparison (RFC 9110 §13.1.2): the opaque tags must match, `W/` on either side does not count
|
|
633
|
+
const opaque = (value: string) => value.trim().replace(/^W\//, '');
|
|
634
|
+
const candidates = (Array.isArray(header) ? header.join(',') : header).split(',').map(opaque);
|
|
635
|
+
if (!candidates.includes(opaque(etag)) && !candidates.includes('*')) {
|
|
636
|
+
return false;
|
|
637
|
+
}
|
|
638
|
+
this.setCacheHeaders(res, file);
|
|
639
|
+
res.status(304).end();
|
|
640
|
+
return true;
|
|
295
641
|
}
|
|
296
642
|
|
|
297
643
|
/**
|