@lenne.tech/nest-server 11.46.3 → 11.46.4
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 +3 -3
- package/FRAMEWORK-API.md +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/file/core-file.controller.d.ts +1 -0
- package/dist/core/modules/file/core-file.controller.js +27 -23
- package/dist/core/modules/file/core-file.controller.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/docs/REQUEST-LIFECYCLE.md +1 -1
- package/migration-guides/11.46.2-to-11.46.3.md +15 -3
- package/migration-guides/11.46.3-to-11.46.4.md +75 -0
- package/package.json +1 -1
- package/src/core/modules/ai/core-ai.controller.ts +12 -4
- package/src/core/modules/file/INTEGRATION-CHECKLIST.md +16 -15
- package/src/core/modules/file/README.md +17 -2
- package/src/core/modules/file/core-file.controller.ts +63 -29
|
@@ -168,7 +168,7 @@ JWT-based authentication for existing projects:
|
|
|
168
168
|
| Feature | Description |
|
|
169
169
|
|---------|-------------|
|
|
170
170
|
| **File Module** | Upload/download with MongoDB GridFS storage |
|
|
171
|
-
| **REST Endpoints** | `GET /files/id/:id`, `GET /files/:filename` (core, gated by `file.downloadRoles`, default ADMIN); `POST /files/upload`, `DELETE /files/:id` (project-specific). Since 11.46.3 the download routes answer after the rights check: weak `ETag` + `If-None-Match` → `304` without a store read, `Cache-Control` per `file.downloadCaching`, `Content-Length`; the store request carries an abort signal (`downloadAbortSignal()`), delivery goes through `pipeFileToResponse()` (releases the source when the client goes), every stream is idle-guarded (`file.downloadIdleTimeoutMs`), and a store that gives no connection in time answers `503` + `Retry-After` |
|
|
171
|
+
| **REST Endpoints** | `GET /files/id/:id`, `GET /files/:filename` (core, gated by `file.downloadRoles`, default ADMIN); `POST /files/upload`, `DELETE /files/:id` (project-specific). Since 11.46.3 the download routes answer after the rights check: weak `ETag` + `If-None-Match` → `304` without a store read, `Cache-Control` per `file.downloadCaching`, `Content-Length`; the store request carries an abort signal (`downloadAbortSignal()`) and is opened through `openDownloadStream()` (exported since 11.46.4: a gone client is `RESPONSE_GONE`, never an error), delivery goes through `pipeFileToResponse()` (releases the source when the client goes), every stream is idle-guarded (`file.downloadIdleTimeoutMs`), and a store that gives no connection in time answers `503` + `Retry-After` |
|
|
172
172
|
| **GraphQL Endpoints** | `getFileInfo` (`file.downloadRoles`), `uploadFile` / `uploadFiles` (`file.uploadRoles`), `deleteFile` (`file.deleteRoles`) — all default ADMIN |
|
|
173
173
|
| **File access control** | Roles are the coarse filter; per-file rules go in `CoreFileService.checkRights()` using metadata written at upload time. Cover BOTH the `id` and the `filename` branch — the filename route authorizes on the by-name lookup alone when presigned S3 downloads are on, and `deleteFileByName()` always does. Working reference: `src/server/modules/file/file.service.ts` (with `file.downloadRoles: [S_USER]` in `src/config.env.ts`, so the rule is actually reached). Both file classes carry `@SkipTenantCheck()` — GridFS is not tenant-scoped |
|
|
174
174
|
| **TUS Module** | Resumable uploads via tus.io protocol (creation, termination, expiration), gated by `tus.roles` (default `S_USER`); `OPTIONS` stays public for the CORS preflight. Records owner and, with `multiTenancy` only, the validated tenant at upload creation; a custom service plugs in via `TusModule.forRoot({ service })`. Configured by `TusModule.forRoot({ config })`, else the server config's `tus` key (11.42.9+). Switched-off `creation` / `termination` answer 501 (enforced by `CoreTusService`, not `@tus/server`); upload URLs follow the path the upload was created at. The response that completes an upload carries the stored file's ID as `X-File-Id` (11.42.13+, listed in `Access-Control-Expose-Headers`) — the last segment of the TUS URL is the upload id, not the file id |
|
|
@@ -79,16 +79,28 @@ package default); nest-server-starter follows.
|
|
|
79
79
|
|
|
80
80
|
## 3. Own download routes
|
|
81
81
|
|
|
82
|
-
Replace every `stream.pipe(res)` that delivers a file with `pipeFileToResponse(stream, res)`, and pass an abort signal
|
|
82
|
+
Replace every `stream.pipe(res)` that delivers a file with `pipeFileToResponse(stream, res)`, and pass an abort signal.
|
|
83
|
+
|
|
84
|
+
**Since 11.46.4, open the stream with `openDownloadStream()`** — see `migration-guides/11.46.3-to-11.46.4.md`. With the
|
|
85
|
+
abort signal alone, a client that leaves before S3 answers makes the store request reject with `AbortError`, and an
|
|
86
|
+
uncaught one is an ERROR with a stack trace per aborted download. On 11.46.3, catch it yourself:
|
|
83
87
|
|
|
84
88
|
```typescript
|
|
85
|
-
import { downloadAbortSignal, pipeFileToResponse } from '@lenne.tech/nest-server';
|
|
89
|
+
import { downloadAbortSignal, isResponseGone, pipeFileToResponse } from '@lenne.tech/nest-server';
|
|
86
90
|
|
|
87
91
|
@Get('image/:id')
|
|
88
92
|
async image(@Param('id') id: string, @Res() res: Response, @CurrentUser() currentUser) {
|
|
89
93
|
// Fires when the client goes (response or request close), so a store request waiting for a socket is dropped
|
|
90
94
|
const abortSignal = downloadAbortSignal(res);
|
|
91
|
-
|
|
95
|
+
let stream: Readable | null;
|
|
96
|
+
try {
|
|
97
|
+
stream = await this.fileService.getFileStream(id, { abortSignal, currentUser });
|
|
98
|
+
} catch (error) {
|
|
99
|
+
if (isResponseGone(res)) {
|
|
100
|
+
return res; // the client left; the aborted store request is not an error
|
|
101
|
+
}
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
92
104
|
if (!stream) {
|
|
93
105
|
throw new NotFoundException();
|
|
94
106
|
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# Migration Guide: 11.46.3 → 11.46.4
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
| Category | Details |
|
|
6
|
+
|---|---|
|
|
7
|
+
| **Breaking Changes** | None |
|
|
8
|
+
| **New Features** | `openDownloadStream(res, open)` is exported — the function the framework's download routes open a file stream with |
|
|
9
|
+
| **Bugfixes** | The documented pattern for an own download route logged an ERROR with a stack trace for every client that left before S3 answered, and answered a busy store with 500 instead of 503 (§1) |
|
|
10
|
+
| **Migration Effort** | Projects with their OWN download route: open the stream with `openDownloadStream()` (§1). Everyone else: `pnpm run update` |
|
|
11
|
+
|
|
12
|
+
## Quick Migration
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pnpm add @lenne.tech/nest-server@11.46.4
|
|
16
|
+
pnpm run update # nest-server-starter based projects
|
|
17
|
+
grep -rn "downloadAbortSignal(" src/ # own download routes: open the stream with openDownloadStream() (§1)
|
|
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. Own download routes
|
|
25
|
+
|
|
26
|
+
11.46.3 documented passing `downloadAbortSignal(res)` to `getFileStream()`, so an S3 request whose client has gone is
|
|
27
|
+
dropped while it waits for a socket. The aborted request then REJECTS with `AbortError`. Nothing in the documented
|
|
28
|
+
pattern caught it: every client that left before S3 answered became `ERROR [ExceptionsHandler] … AbortError` with a
|
|
29
|
+
stack trace and a `500` sent into a closed response — under exactly the load the `S3 socket pool exhausted:` line has
|
|
30
|
+
to stand out in. A store that handed out no connection in time (`TimeoutError`) reached Nest as a `500` instead of the
|
|
31
|
+
`503` with `Retry-After` the framework's routes answer.
|
|
32
|
+
|
|
33
|
+
The framework's routes were not affected: they open the stream through `openDownloadStream()`, which was a protected
|
|
34
|
+
controller method until now. It is exported since 11.46.4:
|
|
35
|
+
|
|
36
|
+
```typescript
|
|
37
|
+
import { downloadAbortSignal, openDownloadStream, pipeFileToResponse, RESPONSE_GONE } from '@lenne.tech/nest-server';
|
|
38
|
+
|
|
39
|
+
@Get('image/:id')
|
|
40
|
+
async image(@Param('id') id: string, @Res() res: Response, @CurrentUser() currentUser) {
|
|
41
|
+
const stream = await openDownloadStream(res, () =>
|
|
42
|
+
this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser }),
|
|
43
|
+
);
|
|
44
|
+
if (stream === RESPONSE_GONE) {
|
|
45
|
+
return res; // nobody left to deliver to
|
|
46
|
+
}
|
|
47
|
+
if (!stream) {
|
|
48
|
+
throw new NotFoundException();
|
|
49
|
+
}
|
|
50
|
+
res.header('Content-Type', 'image/png');
|
|
51
|
+
return pipeFileToResponse(stream, res);
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`openDownloadStream()`:
|
|
56
|
+
|
|
57
|
+
- does not ask the store when the client has already gone,
|
|
58
|
+
- answers `RESPONSE_GONE` when the store request failed because the client left meanwhile,
|
|
59
|
+
- destroys a stream that arrives after the client left,
|
|
60
|
+
- answers `503` with `Retry-After: 5` for `TimeoutError`, and rethrows every other error,
|
|
61
|
+
- passes `null` (the service's rights check refused) on unchanged.
|
|
62
|
+
|
|
63
|
+
`open` may return any stream: `CoreS3Service.getObject()` callers pass `async () => (await s3.getObject(key, { abortSignal })).body`.
|
|
64
|
+
|
|
65
|
+
## Troubleshooting
|
|
66
|
+
|
|
67
|
+
| Symptom | Cause | Fix |
|
|
68
|
+
|---|---|---|
|
|
69
|
+
| `ERROR [ExceptionsHandler] … AbortError` with a stack trace, often in bursts under load | an own download route passes `downloadAbortSignal(res)` but opens the stream without `openDownloadStream()` | §1 |
|
|
70
|
+
| Own download route answers `500` while `S3 socket pool exhausted` is logged | the `TimeoutError` of a busy store is not turned into a `503` | §1 |
|
|
71
|
+
|
|
72
|
+
## Module Documentation
|
|
73
|
+
|
|
74
|
+
- `src/core/modules/file/README.md` — "Delivering a file from your own route"
|
|
75
|
+
- `src/core/modules/file/INTEGRATION-CHECKLIST.md` — Common Mistakes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lenne.tech/nest-server",
|
|
3
|
-
"version": "11.46.
|
|
3
|
+
"version": "11.46.4",
|
|
4
4
|
"description": "Modern, fast, powerful Node.js web framework in TypeScript based on Nest with a GraphQL API and a connection to MongoDB (or other databases).",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"node",
|
|
@@ -93,7 +93,9 @@ export class CoreAiController {
|
|
|
93
93
|
@Body() input: CoreAiPromptInput,
|
|
94
94
|
@Res() res: Response,
|
|
95
95
|
): Promise<void> {
|
|
96
|
-
|
|
96
|
+
// `no-transform` keeps a `compression` middleware out of the stream: gzip would otherwise hold every event until
|
|
97
|
+
// the response ends (measured: events written at 0, 300 and 600 ms all arrived together at about 900 ms)
|
|
98
|
+
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
|
97
99
|
res.setHeader('Connection', 'keep-alive');
|
|
98
100
|
res.setHeader('Content-Type', 'text/event-stream');
|
|
99
101
|
// Disable proxy-side response buffering (nginx and friends honour this); without
|
|
@@ -107,17 +109,23 @@ export class CoreAiController {
|
|
|
107
109
|
// idle connection at 60 s, which the client then sees as a turn that silently
|
|
108
110
|
// vanished. Comment frames are ignored by every SSE client and keep the
|
|
109
111
|
// connection observably alive.
|
|
112
|
+
// A compressor that ignores `no-transform` still sends what was written once it is flushed (`compression` adds
|
|
113
|
+
// `flush()` to the response)
|
|
114
|
+
const send = (chunk: string) => {
|
|
115
|
+
res.write(chunk);
|
|
116
|
+
(res as Response & { flush?: () => void }).flush?.();
|
|
117
|
+
};
|
|
110
118
|
const heartbeat = setInterval(() => {
|
|
111
|
-
|
|
119
|
+
send(': keep-alive\n\n');
|
|
112
120
|
}, 15_000);
|
|
113
121
|
heartbeat.unref?.();
|
|
114
122
|
|
|
115
123
|
try {
|
|
116
124
|
for await (const event of this.aiService.promptStream(input, serviceOptions)) {
|
|
117
|
-
|
|
125
|
+
send(`data: ${JSON.stringify(event)}\n\n`);
|
|
118
126
|
}
|
|
119
127
|
} catch (err) {
|
|
120
|
-
|
|
128
|
+
send(`data: ${JSON.stringify({ message: (err as Error).message, type: 'error' })}\n\n`);
|
|
121
129
|
} finally {
|
|
122
130
|
clearInterval(heartbeat);
|
|
123
131
|
res.end();
|
|
@@ -226,18 +226,19 @@ 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` (11.46.4+) |
|
|
243
|
+
| S3 packages in `devDependencies` | Production image cannot load S3 | Move them to `dependencies` — step 6 |
|
|
244
|
+
| A quota aggregating only `fs.files` | Reads 0 on the S3 / filesystem driver | Aggregate `fs.files`, `filesystem-files` and `s3-files` — step 6 |
|
|
@@ -496,10 +496,25 @@ check stays green. A production outage had exactly this cause. `pipeFileToRespon
|
|
|
496
496
|
client goes — on the response's `close`, the request's `close` before its end or the socket's `end`/`close`, and at once when the client
|
|
497
497
|
had already gone before the call — and answers a store error before the first byte with `404`.
|
|
498
498
|
|
|
499
|
+
**Open the stream with `openDownloadStream(res, open)` (11.46.4+)**, the function the framework's own routes use. It
|
|
500
|
+
does not ask the store when the client has already gone, destroys a stream that arrives after the client left, and
|
|
501
|
+
answers `503` with `Retry-After` when the store hands out no connection in time. It also turns a store request that
|
|
502
|
+
failed BECAUSE the client left into `RESPONSE_GONE`: an S3 request aborted through `downloadAbortSignal(res)` rejects
|
|
503
|
+
with `AbortError`, and without it every aborted download is an ERROR with a stack trace in the log and a `500` sent
|
|
504
|
+
into a closed response — under the load the `S3 socket pool exhausted:` line has to stand out in.
|
|
505
|
+
|
|
499
506
|
```typescript
|
|
500
|
-
import { downloadAbortSignal, pipeFileToResponse } from '@lenne.tech/nest-server';
|
|
507
|
+
import { downloadAbortSignal, openDownloadStream, pipeFileToResponse, RESPONSE_GONE } from '@lenne.tech/nest-server';
|
|
501
508
|
|
|
502
|
-
const stream = await
|
|
509
|
+
const stream = await openDownloadStream(res, () =>
|
|
510
|
+
this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser }),
|
|
511
|
+
);
|
|
512
|
+
if (stream === RESPONSE_GONE) {
|
|
513
|
+
return res; // nobody left to deliver to
|
|
514
|
+
}
|
|
515
|
+
if (!stream) {
|
|
516
|
+
throw new NotFoundException();
|
|
517
|
+
}
|
|
503
518
|
return pipeFileToResponse(stream, res);
|
|
504
519
|
```
|
|
505
520
|
|
|
@@ -310,6 +310,66 @@ export function downloadAbortSignal(res: Response): AbortSignal {
|
|
|
310
310
|
return controller.signal;
|
|
311
311
|
}
|
|
312
312
|
|
|
313
|
+
/**
|
|
314
|
+
* Open a download stream unless the client has already gone, and release a stream that arrives after it left — the
|
|
315
|
+
* framework's download routes use it, and so should a project's own (with {@link pipeFileToResponse} for delivery):
|
|
316
|
+
*
|
|
317
|
+
* ```typescript
|
|
318
|
+
* const stream = await openDownloadStream(res, () =>
|
|
319
|
+
* this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser }),
|
|
320
|
+
* );
|
|
321
|
+
* if (stream === RESPONSE_GONE) {
|
|
322
|
+
* return res;
|
|
323
|
+
* }
|
|
324
|
+
* if (!stream) {
|
|
325
|
+
* throw new NotFoundException();
|
|
326
|
+
* }
|
|
327
|
+
* return pipeFileToResponse(stream, res);
|
|
328
|
+
* ```
|
|
329
|
+
*
|
|
330
|
+
* Answers {@link RESPONSE_GONE} when there is nobody left to deliver to — end the route with `return res` then:
|
|
331
|
+
* - the client had gone before the store was asked;
|
|
332
|
+
* - the store request failed because the client left meanwhile. An S3 request aborted through
|
|
333
|
+
* {@link downloadAbortSignal} rejects with `AbortError`; rethrown, every aborted download became an ERROR with a
|
|
334
|
+
* stack trace in the log and a 500 sent into a closed response, under exactly the load the log line
|
|
335
|
+
* `S3 socket pool exhausted:` has to stand out in;
|
|
336
|
+
* - the stream arrived after the client left — it is destroyed here, so its socket, file handle or cursor is free at
|
|
337
|
+
* once.
|
|
338
|
+
*
|
|
339
|
+
* A store that handed out no connection in time (`TimeoutError`, see `s3.connectionTimeoutMs`) answers `503` with
|
|
340
|
+
* `Retry-After: 5`. Any other error is rethrown. `null` or `undefined` (the service's rights check refused) is passed
|
|
341
|
+
* on unchanged.
|
|
342
|
+
*/
|
|
343
|
+
export async function openDownloadStream<T extends null | Readable | undefined>(
|
|
344
|
+
res: Response,
|
|
345
|
+
open: () => Promise<T>,
|
|
346
|
+
): Promise<T | typeof RESPONSE_GONE> {
|
|
347
|
+
if (isResponseGone(res)) {
|
|
348
|
+
return RESPONSE_GONE;
|
|
349
|
+
}
|
|
350
|
+
let stream: T;
|
|
351
|
+
try {
|
|
352
|
+
stream = await open();
|
|
353
|
+
} catch (error) {
|
|
354
|
+
if (isResponseGone(res)) {
|
|
355
|
+
return RESPONSE_GONE;
|
|
356
|
+
}
|
|
357
|
+
// The store did not hand out a connection in time (`s3.connectionTimeoutMs`, which includes the wait for a
|
|
358
|
+
// free socket): the store is busy, not broken, and the client may try again — 503, not 500
|
|
359
|
+
if ((error as { name?: string })?.name === 'TimeoutError') {
|
|
360
|
+
fileStreamLogger.warn(`File store busy, download answered 503: ${(error as Error).message}`);
|
|
361
|
+
res.header('Retry-After', '5');
|
|
362
|
+
throw new ServiceUnavailableException('File storage is busy, please retry');
|
|
363
|
+
}
|
|
364
|
+
throw error;
|
|
365
|
+
}
|
|
366
|
+
if (stream && isResponseGone(res)) {
|
|
367
|
+
stream.destroy();
|
|
368
|
+
return RESPONSE_GONE;
|
|
369
|
+
}
|
|
370
|
+
return stream;
|
|
371
|
+
}
|
|
372
|
+
|
|
313
373
|
/**
|
|
314
374
|
* File controller
|
|
315
375
|
*
|
|
@@ -517,40 +577,14 @@ export abstract class CoreFileController {
|
|
|
517
577
|
}
|
|
518
578
|
|
|
519
579
|
/**
|
|
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).
|
|
580
|
+
* Open the download stream unless the client has already gone, and release a stream that arrives after it left —
|
|
581
|
+
* see the exported {@link openDownloadStream}, which a project's own download route uses the same way.
|
|
525
582
|
*/
|
|
526
583
|
protected async openDownloadStream(
|
|
527
584
|
res: Response,
|
|
528
585
|
open: () => Promise<Readable>,
|
|
529
586
|
): Promise<Readable | typeof RESPONSE_GONE> {
|
|
530
|
-
|
|
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;
|
|
587
|
+
return openDownloadStream(res, open);
|
|
554
588
|
}
|
|
555
589
|
|
|
556
590
|
/**
|