llm-large-files 0.8.2 → 0.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/CHANGELOG.md +535 -0
- package/README.md +9 -10
- package/dist/access.d.ts +86 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +131 -0
- package/dist/access.js.map +1 -0
- package/dist/ask.d.ts +45 -1
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +181 -20
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +12 -3
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +18 -5
- package/dist/cache.js.map +1 -1
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +57 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +217 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +72 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +102 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +35 -9
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +42 -11
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts +4 -2
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +14 -3
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +32 -8
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +46 -35
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +19 -3
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +84 -12
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +18 -6
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +2 -0
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/index.d.ts +1 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/index.d.ts +9 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +70 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +868 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +169 -34
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +324 -591
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.js +3 -3
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +43 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +63 -3
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +226 -14
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +423 -181
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +7 -1
- package/dist/node/ingest-child.d.ts.map +1 -1
- package/dist/node/ingest-child.js +18 -3
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/isolated.d.ts +3 -1
- package/dist/node/isolated.d.ts.map +1 -1
- package/dist/node/isolated.js +11 -4
- package/dist/node/isolated.js.map +1 -1
- package/dist/node/originals.d.ts +19 -0
- package/dist/node/originals.d.ts.map +1 -0
- package/dist/node/originals.js +82 -0
- package/dist/node/originals.js.map +1 -0
- package/dist/node/spool.d.ts +102 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +365 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +4 -3
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +7 -6
- package/dist/node/sse.js.map +1 -1
- package/dist/pdf-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +71 -12
- package/dist/pdf-layout.js.map +1 -1
- package/dist/ranged.d.ts +15 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +42 -11
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +3 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +6 -2
- package/dist/retry.js.map +1 -1
- package/dist/scope.d.ts +25 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +60 -0
- package/dist/scope.js.map +1 -0
- package/dist/source.d.ts +60 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +170 -0
- package/dist/source.js.map +1 -0
- package/dist/stores.d.ts +120 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +582 -139
- package/dist/stores.js.map +1 -1
- package/dist/testing/fake-fetch.d.ts +31 -0
- package/dist/testing/fake-fetch.d.ts.map +1 -0
- package/dist/testing/fake-fetch.js +66 -0
- package/dist/testing/fake-fetch.js.map +1 -0
- package/dist/testing/fake-model.d.ts +38 -0
- package/dist/testing/fake-model.d.ts.map +1 -0
- package/dist/testing/fake-model.js +62 -0
- package/dist/testing/fake-model.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/store-checks.d.ts +72 -0
- package/dist/testing/store-checks.d.ts.map +1 -0
- package/dist/testing/store-checks.js +619 -0
- package/dist/testing/store-checks.js.map +1 -0
- package/dist/tools.d.ts +25 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +135 -13
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +116 -13
- package/dist/types.d.ts.map +1 -1
- package/docs/README.md +17 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +12 -8
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +16 -7
- package/docs/guides/deployment.md +284 -83
- package/docs/guides/errors-and-reliability.md +161 -23
- package/docs/guides/own-adapter-and-loop.md +27 -10
- package/docs/guides/pdfs.md +123 -29
- package/docs/guides/storage.md +633 -145
- package/docs/guides/testing.md +78 -129
- package/docs/guides/vertex-and-gemini.md +10 -7
- package/docs/guides/web-app.md +312 -78
- package/docs/how-it-works.md +35 -8
- package/docs/measurements.md +43 -8
- package/docs/publishing.md +112 -36
- package/docs/reference/ask.md +154 -13
- package/docs/reference/errors-and-retries.md +166 -14
- package/docs/reference/events.md +53 -20
- package/docs/reference/gemini.md +70 -21
- package/docs/reference/library.md +706 -165
- package/docs/reference/node.md +624 -110
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +15 -5
- package/docs/security.md +304 -67
- package/docs/troubleshooting.md +144 -65
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +12 -3
- package/src/access.ts +144 -0
- package/src/ask.ts +230 -19
- package/src/cache.ts +20 -5
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +255 -0
- package/src/errors.ts +129 -15
- package/src/events.ts +86 -21
- package/src/evidence.ts +14 -3
- package/src/extract.ts +50 -33
- package/src/gemini/adapter.ts +97 -11
- package/src/gemini/chat.ts +20 -6
- package/src/gemini/index.ts +1 -1
- package/src/index.ts +9 -6
- package/src/ingest.ts +927 -0
- package/src/library.ts +467 -601
- package/src/map-reduce.ts +3 -3
- package/src/model.ts +69 -5
- package/src/node/handlers.ts +630 -183
- package/src/node/index.ts +13 -2
- package/src/node/ingest-child.ts +23 -5
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +365 -0
- package/src/node/sse.ts +7 -6
- package/src/pdf-layout.ts +69 -11
- package/src/ranged.ts +34 -13
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/source.ts +178 -0
- package/src/stores.ts +635 -140
- package/src/testing/fake-fetch.ts +80 -0
- package/src/testing/fake-model.ts +78 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/store-checks.ts +660 -0
- package/src/tools.ts +150 -14
- package/src/types.ts +106 -13
package/dist/node/handlers.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { tmpdir } from "node:os";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { errorInfoOf, STORE_RETRY_AFTER_MS, UNREADABLE_MESSAGE } from "../error-info.js";
|
|
4
|
+
import { DocumentScopeError, DocumentStoreError, IngestError, isErrorCode } from "../errors.js";
|
|
2
5
|
import { eventStream, newRunId } from "../events.js";
|
|
3
|
-
import { checkOwner, toDocumentSummary } from "../library.js";
|
|
6
|
+
import { checkOwner, cleanFileName, toDocumentSummary } from "../library.js";
|
|
7
|
+
import { DocumentsNotFoundError, errorKindOf, ModelRequestError } from "../model.js";
|
|
4
8
|
import { formatBytes } from "../plan.js";
|
|
9
|
+
import { checkScope } from "../scope.js";
|
|
10
|
+
import { BodyFile, checkRefFolders, HttpError, parsedBody, readBody, Room, spoolFileIn, writeBody } from "./spool.js";
|
|
5
11
|
import { writeSseEvents } from "./sse.js";
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
constructor(status, message, close = false) {
|
|
11
|
-
super(message);
|
|
12
|
-
this.status = status;
|
|
13
|
-
this.close = close;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
12
|
+
/** A whole HTTP status of an error, from 400 to 599. */
|
|
13
|
+
const isErrorStatus = (value) => typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599;
|
|
14
|
+
/** A wait in milliseconds: a finite number of 0 or more. */
|
|
15
|
+
const isWait = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
16
16
|
/** The HTTP status an error carries: this module's, or one `getOwner` throws (`http-errors` style). */
|
|
17
17
|
function statusOf(error) {
|
|
18
18
|
if (error instanceof HttpError)
|
|
@@ -21,49 +21,102 @@ function statusOf(error) {
|
|
|
21
21
|
return undefined;
|
|
22
22
|
const { status, statusCode } = error;
|
|
23
23
|
const value = typeof status === "number" ? status : statusCode;
|
|
24
|
-
return
|
|
24
|
+
return isErrorStatus(value) ? value : undefined;
|
|
25
25
|
}
|
|
26
26
|
/**
|
|
27
27
|
* The code of a Node system error (a file or network call that failed, as `ENOSPC`). Its message
|
|
28
|
-
* names server paths or hosts, so only the code is passed on
|
|
28
|
+
* names server paths or hosts, so only the code is passed on, and only when it reads as one: a
|
|
29
|
+
* driver may put a host in `code`.
|
|
29
30
|
*/
|
|
30
31
|
function systemErrorCode(error) {
|
|
31
32
|
const { code, syscall } = (error ?? {});
|
|
32
|
-
return
|
|
33
|
+
return isErrorCode(code) && typeof syscall === "string" ? code : undefined;
|
|
33
34
|
}
|
|
35
|
+
/** What the handlers answer a scope that is gone (`DocumentScopeError` "scope_missing"): the chat was deleted. */
|
|
36
|
+
const CHAT_GONE = "This chat no longer exists.";
|
|
34
37
|
/**
|
|
35
|
-
*
|
|
36
|
-
*
|
|
38
|
+
* An error as the handlers answer it, `failed` saying what failed ("Upload failed"). See
|
|
39
|
+
* `uploadAnswerOf`. It never throws: an error whose fields throw when read is a 500.
|
|
37
40
|
*/
|
|
38
|
-
function
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
41
|
+
function answerFor(error, failed) {
|
|
42
|
+
const plain = { status: 500, error: `${failed}.` };
|
|
43
|
+
try {
|
|
44
|
+
if (error instanceof HttpError)
|
|
45
|
+
return { status: error.status, error: error.message || plain.error };
|
|
46
|
+
if (IngestError.is(error)) {
|
|
47
|
+
const status = isErrorStatus(error.status) ? error.status : 422;
|
|
48
|
+
return {
|
|
49
|
+
status,
|
|
50
|
+
// An unreadable file has the words of a parser, or of an extractor of your own, which may
|
|
51
|
+
// name a host: not words for a user (as for errorInfoOf).
|
|
52
|
+
error: error.code === "unreadable" ? UNREADABLE_MESSAGE : typeof error.message === "string" && error.message ? error.message : plain.error,
|
|
53
|
+
code: error.code,
|
|
54
|
+
...(status === 503 && isWait(error.retryAfterMs) ? { retryAfterMs: error.retryAfterMs } : {}),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
// Its message names what failed and a code, never a path or a host.
|
|
58
|
+
if (DocumentStoreError.is(error))
|
|
59
|
+
return { status: 503, error: errorInfoOf(error).message, retryAfterMs: STORE_RETRY_AFTER_MS };
|
|
60
|
+
// A scope the server gave wrong, or did not give, is its own bug: not the client's to fix.
|
|
61
|
+
if (DocumentScopeError.is(error))
|
|
62
|
+
return error.code === "scope_missing" ? { status: 404, error: CHAT_GONE } : plain;
|
|
63
|
+
// A model's error (an ingest or a hook of your own that asks one): its status is the provider's,
|
|
64
|
+
// and its message the provider's words, which may name a project or a key.
|
|
65
|
+
if (ModelRequestError.is(error) || errorKindOf(error) !== undefined) {
|
|
66
|
+
const info = errorInfoOf(error);
|
|
67
|
+
if (info.category === "model")
|
|
68
|
+
return { status: info.status, error: info.message, ...(info.status === 429 || info.status === 503 ? retryOf(info.retryAfterMs) : {}) };
|
|
69
|
+
}
|
|
70
|
+
const status = statusOf(error);
|
|
71
|
+
if (status !== undefined) {
|
|
72
|
+
const message = error.message;
|
|
73
|
+
return { status, error: typeof message === "string" && message ? message : plain.error, ...(status === 503 ? retryOf(error.retryAfterMs) : {}) };
|
|
74
|
+
}
|
|
75
|
+
const code = systemErrorCode(error);
|
|
76
|
+
return code ? { status: 500, error: `${failed} (${code}).` } : plain;
|
|
42
77
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
}
|
|
46
|
-
/** Answers a failed request with JSON (see `answerOf`). A refusal that says when to try again (a busy reader) sets `Retry-After`. */
|
|
47
|
-
function fail(response, error, failed, tooLarge, unread) {
|
|
48
|
-
const { status, message } = answerOf(error, failed, tooLarge);
|
|
49
|
-
const retryAfterMs = error?.retryAfterMs;
|
|
50
|
-
if (status === 503 && typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) && !response.headersSent) {
|
|
51
|
-
response.setHeader("Retry-After", String(Math.max(1, Math.ceil(retryAfterMs / 1_000))));
|
|
78
|
+
catch {
|
|
79
|
+
return plain;
|
|
52
80
|
}
|
|
53
|
-
send(response, status, { error: message }, unread);
|
|
54
81
|
}
|
|
82
|
+
const retryOf = (value) => (isWait(value) ? { retryAfterMs: value } : {});
|
|
55
83
|
/**
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
84
|
+
* How the upload handler answers an error, for a route of your own that ingests files and should
|
|
85
|
+
* answer as it does:
|
|
86
|
+
* - an `IngestError` (a file that could not be read): its status (422; 413, 409, or 503 for "busy"
|
|
87
|
+
* with its `retryAfterMs`), its message and its `code`. Only an `IngestError` is a 422. An
|
|
88
|
+
* "unreadable" file is told in fixed words, as `errorInfoOf` tells it: its own message is a
|
|
89
|
+
* parser's, or that of an extractor of your own;
|
|
90
|
+
* - a `DocumentStoreError`: 503, its message (which names no path or host), and 5 s to wait;
|
|
91
|
+
* - a `DocumentScopeError` "scope_missing": 404 "This chat no longer exists."; the other codes
|
|
92
|
+
* are the server's mistake: 500 "Upload failed.";
|
|
93
|
+
* - a model's error (`ModelRequestError`): the status and words of `errorInfoOf`, never the
|
|
94
|
+
* provider's own;
|
|
95
|
+
* - any other error with a `status` (or `statusCode`) from 400 to 599: that status and its message;
|
|
96
|
+
* - a Node system error (a `code` and a `syscall`): 500 "Upload failed (ENOSPC).", or "Upload
|
|
97
|
+
* failed." when its code does not read as one (capitals, digits and "_"), as a host does;
|
|
98
|
+
* - anything else: 500 "Upload failed.", without its message, which may name a host.
|
|
99
|
+
*
|
|
100
|
+
* It reads the errors of every copy of the package, and never throws. New in 0.9.0.
|
|
60
101
|
*/
|
|
61
|
-
function
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
102
|
+
export function uploadAnswerOf(error) {
|
|
103
|
+
return answerFor(error, "Upload failed");
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Answers a failed request with JSON (see `answerFor`). A 413 of the handler or of `ingest` gets the
|
|
107
|
+
* size message of the upload. An answer that says when to try again (a busy reader, a store, a
|
|
108
|
+
* model's rate limit) sets `Retry-After`.
|
|
109
|
+
*/
|
|
110
|
+
function fail(response, error, failed, tooLarge, unread) {
|
|
111
|
+
const answer = answerFor(error, failed);
|
|
112
|
+
if (answer.retryAfterMs !== undefined && !response.headersSent) {
|
|
113
|
+
response.setHeader("Retry-After", String(Math.max(1, Math.ceil(answer.retryAfterMs / 1_000))));
|
|
114
|
+
}
|
|
115
|
+
send(response, answer.status, { error: messageOf(answer, error, tooLarge) }, unread);
|
|
116
|
+
}
|
|
117
|
+
/** The message of an answer: a 413 of the handler itself, or of `ingest`, says the upload limit. */
|
|
118
|
+
function messageOf(answer, error, tooLarge) {
|
|
119
|
+
return answer.status === 413 && (error instanceof HttpError || IngestError.is(error)) ? tooLarge : answer.error;
|
|
67
120
|
}
|
|
68
121
|
/**
|
|
69
122
|
* Whether the client asked for the upload's progress as Server-Sent Events: its `Accept` header
|
|
@@ -80,13 +133,53 @@ function wantsEvents(request) {
|
|
|
80
133
|
return q === undefined || Number(q[1]) > 0;
|
|
81
134
|
});
|
|
82
135
|
}
|
|
136
|
+
/**
|
|
137
|
+
* An error as `ingest.error` carries it: the message, status and code of the JSON answer, and which
|
|
138
|
+
* of the library's errors it is, so that `errorInfoOf` reads it in the browser as on the server.
|
|
139
|
+
*/
|
|
140
|
+
function eventErrorFor(error, tooLarge) {
|
|
141
|
+
const answer = answerFor(error, "Upload failed");
|
|
142
|
+
// A file that could not be read also says why, for a page that tells it in its own words.
|
|
143
|
+
return { message: messageOf(answer, error, tooLarge), status: answer.status, ...identityOf(error), ...(answer.code !== undefined ? { code: answer.code } : {}) };
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* The name of a store's failure, of documents that are gone, or of a scope that cannot be used
|
|
147
|
+
* (with its code, which tells a deleted chat apart), and the kind of a model's error (an ingest or
|
|
148
|
+
* a hook of yours that asks one), as `answerFor` answers it, for `EventError`. Nothing for other
|
|
149
|
+
* errors: a refused file is told by its `code`.
|
|
150
|
+
*/
|
|
151
|
+
function identityOf(error) {
|
|
152
|
+
try {
|
|
153
|
+
if (DocumentStoreError.is(error))
|
|
154
|
+
return { name: "DocumentStoreError" };
|
|
155
|
+
if (DocumentsNotFoundError.is(error))
|
|
156
|
+
return { name: "DocumentsNotFoundError" };
|
|
157
|
+
if (DocumentScopeError.is(error))
|
|
158
|
+
return { name: "DocumentScopeError", ...(typeof error.code === "string" ? { code: error.code } : {}) };
|
|
159
|
+
// A model's EventError always has its kind, as in the events of a question.
|
|
160
|
+
if (ModelRequestError.is(error) || errorKindOf(error) !== undefined) {
|
|
161
|
+
const info = errorInfoOf(error);
|
|
162
|
+
if (info.category === "model")
|
|
163
|
+
return { kind: info.code };
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
// A proxy whose traps throw: told plainly.
|
|
168
|
+
}
|
|
169
|
+
return {};
|
|
170
|
+
}
|
|
83
171
|
/**
|
|
84
172
|
* Ingests the upload and answers with its events as Server-Sent Events. The last one is always
|
|
85
|
-
* `ingest.finish` or `ingest.error`, even with a `LargeFiles` of your own whose `ingest` sends no
|
|
173
|
+
* `ingest.finish` or `ingest.error`, even with a `LargeFiles` of your own whose `ingest` sends no
|
|
174
|
+
* events. `uploaded` runs `onUploaded` once, before `ingest.finish` is sent; or after the stream, for
|
|
175
|
+
* a document stored once the client went away. `start` starts the ingest (see `upload`); `release`
|
|
176
|
+
* is called once the ingest ended, before `onUploaded`.
|
|
86
177
|
*/
|
|
87
|
-
async function streamIngest(
|
|
178
|
+
async function streamIngest(start, signal, response, tooLarge, uploaded, release) {
|
|
88
179
|
const runId = newRunId("ing");
|
|
89
|
-
const stream = eventStream((onEvent,
|
|
180
|
+
const stream = eventStream((onEvent, stop) => start({ runId, onEvent, signal: stop }), { signal });
|
|
181
|
+
// The ingest ended: its room is given back, while `onUploaded` may still run.
|
|
182
|
+
stream.result.then(release, release);
|
|
90
183
|
// The error as a JSON answer would give it: the event's own may hold a store's message.
|
|
91
184
|
const answer = async (fallback) => {
|
|
92
185
|
try {
|
|
@@ -94,11 +187,25 @@ async function streamIngest(files, input, response, tooLarge) {
|
|
|
94
187
|
return { message: fallback.message, ...(fallback.status !== undefined ? { status: fallback.status } : {}) };
|
|
95
188
|
}
|
|
96
189
|
catch (error) {
|
|
97
|
-
|
|
98
|
-
// A file that could not be read also says why, for a page that tells it in its own words.
|
|
99
|
-
return { ...answerOf(failure, "Upload failed", tooLarge), ...(failure instanceof IngestError ? { code: failure.code } : {}) };
|
|
190
|
+
return eventErrorFor(error, tooLarge);
|
|
100
191
|
}
|
|
101
192
|
};
|
|
193
|
+
/** The last event of a stored document: `ingest.finish` once `onUploaded` is done, or `ingest.error` when it failed. */
|
|
194
|
+
const finished = async (base, last) => {
|
|
195
|
+
let meta;
|
|
196
|
+
try {
|
|
197
|
+
meta = await stream.result;
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
// An ingest of your own that sent ingest.finish, then failed.
|
|
201
|
+
return { ...base, type: "ingest.error", error: await answer({ message: "Upload failed." }) };
|
|
202
|
+
}
|
|
203
|
+
const hooked = await uploaded(meta);
|
|
204
|
+
if ("failure" in hooked)
|
|
205
|
+
return { ...base, type: "ingest.error", error: eventErrorFor(hooked.failure, tooLarge) };
|
|
206
|
+
const event = last ?? { ...base, type: "ingest.finish", document: toDocumentSummary(meta) };
|
|
207
|
+
return hooked.answer ? { ...event, app: hooked.answer } : event;
|
|
208
|
+
};
|
|
102
209
|
async function* events() {
|
|
103
210
|
let seq = 0;
|
|
104
211
|
for await (const event of stream) {
|
|
@@ -107,25 +214,25 @@ async function streamIngest(files, input, response, tooLarge) {
|
|
|
107
214
|
yield { ...event, error: await answer(event.error) };
|
|
108
215
|
return;
|
|
109
216
|
}
|
|
110
|
-
|
|
111
|
-
|
|
217
|
+
if (event.type === "ingest.finish") {
|
|
218
|
+
yield await finished({ seq: event.seq, runId: event.runId, time: event.time }, event);
|
|
112
219
|
return;
|
|
220
|
+
}
|
|
221
|
+
yield event;
|
|
113
222
|
}
|
|
114
223
|
// The ingest ended without a last event: a `LargeFiles` of your own whose ingest sends none.
|
|
115
|
-
|
|
116
|
-
try {
|
|
117
|
-
yield { ...base, type: "ingest.finish", document: toDocumentSummary(await stream.result) };
|
|
118
|
-
}
|
|
119
|
-
catch {
|
|
120
|
-
yield { ...base, type: "ingest.error", error: await answer({ message: "Upload failed." }) };
|
|
121
|
-
}
|
|
224
|
+
yield await finished({ seq: seq + 1, runId, time: Date.now() }, undefined);
|
|
122
225
|
}
|
|
123
226
|
// Each message is the event itself, as for a question: `ingest.finish` holds the summary a 201
|
|
124
227
|
// answer would (`document`), `ingest.error` the message and status a JSON answer would (`error`).
|
|
125
228
|
await writeSseEvents(response, events());
|
|
126
229
|
// A client that went away ends the stream at once, while the ingest stops (a store write may still
|
|
127
|
-
// be under way): the upload is held until then, as on the JSON path.
|
|
128
|
-
|
|
230
|
+
// be under way): the upload is held until then, as on the JSON path. A document stored all the
|
|
231
|
+
// same (the ingest had ended, or an ingest of your own did not stop) still goes to `onUploaded`
|
|
232
|
+
// (with `clientGone`), once.
|
|
233
|
+
const meta = await stream.result.catch(() => undefined);
|
|
234
|
+
if (meta !== undefined)
|
|
235
|
+
await uploaded(meta);
|
|
129
236
|
}
|
|
130
237
|
/**
|
|
131
238
|
* Answers with `value` as JSON. With `unread`, a request whose body was not read to its end (an
|
|
@@ -143,9 +250,18 @@ function send(response, status, value, unread) {
|
|
|
143
250
|
response.write(body);
|
|
144
251
|
drain(unread, response);
|
|
145
252
|
}
|
|
146
|
-
|
|
253
|
+
/** A header's value as it came (the first, when it came more than once), or "". */
|
|
254
|
+
function rawHeader(request, name) {
|
|
147
255
|
const raw = request.headers[name];
|
|
148
256
|
const value = Array.isArray(raw) ? raw[0] : raw;
|
|
257
|
+
return value ?? "";
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* A header the page URI-encodes (`X-File-Name`, `X-File-Type`), decoded: a value that does not
|
|
261
|
+
* decode is used as it is.
|
|
262
|
+
*/
|
|
263
|
+
function header(request, name) {
|
|
264
|
+
const value = rawHeader(request, name);
|
|
149
265
|
if (!value)
|
|
150
266
|
return "";
|
|
151
267
|
try {
|
|
@@ -155,73 +271,6 @@ function header(request, name) {
|
|
|
155
271
|
return value;
|
|
156
272
|
}
|
|
157
273
|
}
|
|
158
|
-
/** The longest a timer can wait. */
|
|
159
|
-
const LONGEST_TIMER_MS = 2_147_483_647;
|
|
160
|
-
/** `next`, or a 408 once `idleMs` pass without it. */
|
|
161
|
-
function withinIdle(next, idleMs) {
|
|
162
|
-
// Once the upload is refused, the read it waited on ends with the connection: nobody awaits it.
|
|
163
|
-
next.catch(() => undefined);
|
|
164
|
-
let settled = false;
|
|
165
|
-
let timer;
|
|
166
|
-
const idle = new Promise((_, reject) => {
|
|
167
|
-
const after = idleMs >= 1_000 ? `${Math.round(idleMs / 1_000)} s` : `${idleMs} ms`;
|
|
168
|
-
timer = setTimeout(() => {
|
|
169
|
-
// After the thread was held longer than `idleMs`, timers run before the data that came in the
|
|
170
|
-
// meantime is read: it is read first, in this turn of the loop, and the upload goes on.
|
|
171
|
-
setImmediate(() => {
|
|
172
|
-
if (!settled)
|
|
173
|
-
reject(new HttpError(408, `The upload stopped arriving: nothing came for ${after}. Send it again.`, true));
|
|
174
|
-
});
|
|
175
|
-
}, idleMs);
|
|
176
|
-
});
|
|
177
|
-
return Promise.race([next.finally(() => (settled = true)), idle]).finally(() => clearTimeout(timer));
|
|
178
|
-
}
|
|
179
|
-
/**
|
|
180
|
-
* Reads the raw body, or uses one a framework already parsed into a Buffer (e.g. express.raw()).
|
|
181
|
-
* `idleMs`: the longest wait for the next piece of the body (0 for no limit).
|
|
182
|
-
*/
|
|
183
|
-
async function readBody(request, limit, idleMs = 0) {
|
|
184
|
-
const parsed = request.body;
|
|
185
|
-
if (parsed instanceof Uint8Array) {
|
|
186
|
-
if (parsed.byteLength > limit)
|
|
187
|
-
throw new HttpError(413, "");
|
|
188
|
-
return parsed;
|
|
189
|
-
}
|
|
190
|
-
if (parsed !== undefined && typeof parsed === "object" && parsed !== null && Object.keys(parsed).length) {
|
|
191
|
-
throw new HttpError(400, "The upload body was already parsed by another middleware. Mount the upload route before body parsers, or send Content-Type: application/octet-stream.");
|
|
192
|
-
}
|
|
193
|
-
const declared = Number(request.headers["content-length"]);
|
|
194
|
-
if (Number.isFinite(declared) && declared > limit)
|
|
195
|
-
throw new HttpError(413, "");
|
|
196
|
-
const chunks = [];
|
|
197
|
-
let size = 0;
|
|
198
|
-
// Leaving the loop early must not destroy the request: the rest of the body is drained after
|
|
199
|
-
// the answer (see `drain`), which a destroyed request would not do.
|
|
200
|
-
const pieces = request.iterator({ destroyOnReturn: false });
|
|
201
|
-
const timed = idleMs > 0 && idleMs <= LONGEST_TIMER_MS;
|
|
202
|
-
try {
|
|
203
|
-
for (;;) {
|
|
204
|
-
const next = pieces.next();
|
|
205
|
-
const { done, value: chunk } = timed ? await withinIdle(next, idleMs) : await next;
|
|
206
|
-
if (done)
|
|
207
|
-
break;
|
|
208
|
-
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
209
|
-
size += buffer.byteLength;
|
|
210
|
-
if (size > limit)
|
|
211
|
-
throw new HttpError(413, "");
|
|
212
|
-
chunks.push(buffer);
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
finally {
|
|
216
|
-
// As a `for await` does on leaving early; the request is not destroyed (see above).
|
|
217
|
-
void pieces.return?.().catch(() => undefined);
|
|
218
|
-
}
|
|
219
|
-
const body = Buffer.concat(chunks);
|
|
220
|
-
return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
|
|
221
|
-
}
|
|
222
|
-
const BUSY = "The server is receiving other files right now. Try again in a moment.";
|
|
223
|
-
/** When a client refused for `maxPendingUploadBytes` is told to try again. */
|
|
224
|
-
const BUSY_RETRY_MS = 5_000;
|
|
225
274
|
/** `uploadIdleTimeoutMs`, checked: a number of 0 or more (0 and Infinity for no limit). */
|
|
226
275
|
function idleLimit(value) {
|
|
227
276
|
if (value === undefined)
|
|
@@ -231,15 +280,72 @@ function idleLimit(value) {
|
|
|
231
280
|
}
|
|
232
281
|
return value;
|
|
233
282
|
}
|
|
234
|
-
/** `maxPendingUploadBytes
|
|
235
|
-
function
|
|
283
|
+
/** `maxPendingUploadBytes` or `maxSpooledUploadBytes` (`name`), checked: a number above 0 (Infinity for no limit). */
|
|
284
|
+
function roomLimit(name, value, fallback) {
|
|
236
285
|
if (value === undefined)
|
|
237
|
-
return
|
|
286
|
+
return fallback;
|
|
238
287
|
if (typeof value !== "number" || Number.isNaN(value) || value <= 0) {
|
|
239
|
-
throw new RangeError(
|
|
288
|
+
throw new RangeError(`${name} must be a number above 0, and is ${typeof value === "number" ? value : typeof value}. Leave it out for the default.`);
|
|
240
289
|
}
|
|
241
290
|
return value;
|
|
242
291
|
}
|
|
292
|
+
/** `uploadSpool`, checked: undefined for no spool. */
|
|
293
|
+
function spoolOf(value) {
|
|
294
|
+
if (value === undefined || value === false)
|
|
295
|
+
return undefined;
|
|
296
|
+
const given = value === true ? {} : value;
|
|
297
|
+
if (typeof given !== "object" || given === null)
|
|
298
|
+
throw new TypeError("uploadSpool must be true, false, or { directory?, minBytes? }.");
|
|
299
|
+
const { directory, minBytes } = given;
|
|
300
|
+
if (directory !== undefined && (typeof directory !== "string" || directory.length === 0 || directory.includes("\0"))) {
|
|
301
|
+
throw new TypeError("uploadSpool.directory must be the path of a folder: a string that is not empty.");
|
|
302
|
+
}
|
|
303
|
+
if (minBytes !== undefined && (typeof minBytes !== "number" || Number.isNaN(minBytes) || minBytes < 0)) {
|
|
304
|
+
throw new RangeError(`uploadSpool.minBytes must be a number of 0 or more, and is ${typeof minBytes === "number" ? minBytes : typeof minBytes}. Leave it out for the default.`);
|
|
305
|
+
}
|
|
306
|
+
return { directory: path.resolve(directory ?? tmpdir()), minBytes: minBytes ?? 1024 * 1024 };
|
|
307
|
+
}
|
|
308
|
+
/** `uploadFileMode`, checked: a file mode from 0 to 0o777. */
|
|
309
|
+
function fileModeOf(value) {
|
|
310
|
+
if (value === undefined)
|
|
311
|
+
return 0o600;
|
|
312
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 0o777) {
|
|
313
|
+
throw new TypeError("uploadFileMode must be a file mode from 0 to 0o777, such as 0o640.");
|
|
314
|
+
}
|
|
315
|
+
return value;
|
|
316
|
+
}
|
|
317
|
+
const PREPARED_SHAPE = "prepareUpload must return nothing, or { id?, path?, original? }: id a string, path an absolute path, original { ref } with a path.";
|
|
318
|
+
/**
|
|
319
|
+
* What `prepareUpload` returned, checked (a copy). Null fields are left out, as a database gives
|
|
320
|
+
* them. Anything else is a TypeError, the server's mistake: a 500 "Upload failed.". The rules of
|
|
321
|
+
* `id` and `original.ref` are the library's, checked by `ingest`.
|
|
322
|
+
*/
|
|
323
|
+
function preparedOf(value) {
|
|
324
|
+
if (value === undefined || value === null)
|
|
325
|
+
return {};
|
|
326
|
+
if (typeof value !== "object")
|
|
327
|
+
throw new TypeError(PREPARED_SHAPE);
|
|
328
|
+
const { id, path: at, original } = value;
|
|
329
|
+
const prepared = {};
|
|
330
|
+
if (id !== undefined && id !== null) {
|
|
331
|
+
if (typeof id !== "string")
|
|
332
|
+
throw new TypeError(PREPARED_SHAPE);
|
|
333
|
+
prepared.id = id;
|
|
334
|
+
}
|
|
335
|
+
if (at !== undefined && at !== null) {
|
|
336
|
+
if (typeof at !== "string" || at.includes("\0") || !path.isAbsolute(at))
|
|
337
|
+
throw new TypeError(PREPARED_SHAPE);
|
|
338
|
+
prepared.path = at;
|
|
339
|
+
}
|
|
340
|
+
if (original !== undefined && original !== null) {
|
|
341
|
+
const ref = typeof original === "object" ? original.ref : undefined;
|
|
342
|
+
// A ref names the file the body is saved to: without a path, it would name a file the handler never wrote.
|
|
343
|
+
if (typeof ref !== "string" || prepared.path === undefined)
|
|
344
|
+
throw new TypeError(PREPARED_SHAPE);
|
|
345
|
+
prepared.original = { ref };
|
|
346
|
+
}
|
|
347
|
+
return prepared;
|
|
348
|
+
}
|
|
243
349
|
/**
|
|
244
350
|
* The bytes an upload will hold: a body a framework already read, its declared `Content-Length`,
|
|
245
351
|
* or the upload limit when it declares none. Never more than the limit: a larger one is refused
|
|
@@ -297,18 +403,99 @@ function drain(request, response) {
|
|
|
297
403
|
*/
|
|
298
404
|
export function createDocumentHandlers(files, options = {}) {
|
|
299
405
|
const tooLarge = `The file is larger than the ${formatBytes(files.maxUploadBytes)} upload limit.`;
|
|
300
|
-
const owner = async (request) => options.getOwner?.(request);
|
|
301
406
|
// The upload limit bounds each body, and the room for all of them: a LargeFiles of your own
|
|
302
407
|
// without it (from JavaScript) had neither.
|
|
303
408
|
if (typeof files.maxUploadBytes !== "number" || !(files.maxUploadBytes > 0)) {
|
|
304
409
|
throw new TypeError(`createDocumentHandlers needs files.maxUploadBytes, a number above 0, and it is ${String(files.maxUploadBytes)}. A LargeFiles of your own must keep the one of the library it wraps.`);
|
|
305
410
|
}
|
|
306
|
-
const
|
|
411
|
+
for (const name of ["getScope", "prepareUpload", "onUploaded", "onRemoved"]) {
|
|
412
|
+
if (options[name] !== undefined && typeof options[name] !== "function")
|
|
413
|
+
throw new TypeError(`${name} must be a function, and is ${typeof options[name]}.`);
|
|
414
|
+
}
|
|
415
|
+
// A library that requires an owner or a scope on every call cannot be served without them: every
|
|
416
|
+
// request would fail, after its body was read.
|
|
417
|
+
const requireOwner = files.access?.requireOwner === true;
|
|
418
|
+
const requireScope = files.access?.requireScope === true;
|
|
419
|
+
if (requireOwner && typeof options.getOwner !== "function") {
|
|
420
|
+
throw new TypeError("createDocumentHandlers needs getOwner: the library requires an owner on every call (requireOwner).");
|
|
421
|
+
}
|
|
422
|
+
if (requireScope && typeof options.getScope !== "function") {
|
|
423
|
+
throw new TypeError("createDocumentHandlers needs getScope: the library requires a scope on every call (requireScope).");
|
|
424
|
+
}
|
|
307
425
|
const idleMs = idleLimit(options.uploadIdleTimeoutMs);
|
|
308
|
-
/**
|
|
309
|
-
const
|
|
310
|
-
|
|
311
|
-
|
|
426
|
+
/** The bodies held in memory, from the reading of each to the end of its ingest (`maxPendingUploadBytes`). */
|
|
427
|
+
const memoryRoom = new Room(roomLimit("maxPendingUploadBytes", options.maxPendingUploadBytes, 2 * files.maxUploadBytes));
|
|
428
|
+
const spool = spoolOf(options.uploadSpool);
|
|
429
|
+
/** The files of the spool, from the writing of each to its removal (`maxSpooledUploadBytes`). */
|
|
430
|
+
const spoolRoom = new Room(roomLimit("maxSpooledUploadBytes", options.maxSpooledUploadBytes, 10 * files.maxUploadBytes));
|
|
431
|
+
const fileMode = fileModeOf(options.uploadFileMode);
|
|
432
|
+
/**
|
|
433
|
+
* Whether the body of an upload goes to a file of the spool: with `uploadSpool`, one over
|
|
434
|
+
* `minBytes`, or that does not say its size. Not a body a framework already read into memory.
|
|
435
|
+
*/
|
|
436
|
+
function spools(declared, parsed) {
|
|
437
|
+
if (spool === undefined || parsed !== undefined)
|
|
438
|
+
return false;
|
|
439
|
+
return !(Number.isFinite(declared) && declared >= 0 && declared <= spool.minBytes);
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Who is asking: the owner and the scope of the request, checked, before its body is read. Under
|
|
443
|
+
* `requireOwner`, a request without an owner is answered 401. An owner the library refuses (on
|
|
444
|
+
* the upload, or on every route under `requireOwner`), a scope that is not valid, or none under
|
|
445
|
+
* `requireScope`, is the server's mistake: a 500 that says which, and nothing else. `failed` says
|
|
446
|
+
* what failed ("Upload failed").
|
|
447
|
+
*/
|
|
448
|
+
async function callerOf(request, failed, checkOwnerShape) {
|
|
449
|
+
const owner = await options.getOwner?.(request);
|
|
450
|
+
// No owner, or null (`req.user?.id ?? null` from JavaScript), is a request that is not signed in.
|
|
451
|
+
if (requireOwner && (owner === undefined || owner === null))
|
|
452
|
+
throw new HttpError(401, "Sign in first.");
|
|
453
|
+
// An owner that `ingest` would refuse ("", or an object such as `req.user` from JavaScript) is
|
|
454
|
+
// the server's mistake, answered with a 500 before the body is read. Its message says which, so
|
|
455
|
+
// that the operator knows where to look; it says nothing else. (Without `requireOwner`, `get`
|
|
456
|
+
// and `remove` pass it on, as before, so that documents of 0.5.0 with the owner "" stay
|
|
457
|
+
// readable. Under it, the library refuses such an owner on every call: so do they, in the same
|
|
458
|
+
// words as the upload.)
|
|
459
|
+
if (checkOwnerShape || requireOwner) {
|
|
460
|
+
try {
|
|
461
|
+
checkOwner(owner);
|
|
462
|
+
}
|
|
463
|
+
catch {
|
|
464
|
+
const empty = typeof owner === "string" || owner === null;
|
|
465
|
+
throw new HttpError(500, empty ? `${failed} (empty owner).` : `${failed} (owner is not a string).`);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
const given = options.getScope ? await options.getScope(request) : undefined;
|
|
469
|
+
let scope;
|
|
470
|
+
try {
|
|
471
|
+
// Null is no scope, as for the library.
|
|
472
|
+
scope = checkScope(given ?? undefined);
|
|
473
|
+
}
|
|
474
|
+
catch {
|
|
475
|
+
throw new HttpError(500, `${failed} (invalid scope).`);
|
|
476
|
+
}
|
|
477
|
+
if (requireScope && scope === undefined)
|
|
478
|
+
throw new HttpError(500, `${failed} (no scope).`);
|
|
479
|
+
return { ...(owner !== undefined ? { owner } : {}), ...(scope !== undefined ? { scope } : {}) };
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Runs `onUploaded` for a stored document. When it throws, or its `answer` is not a plain object
|
|
483
|
+
* that JSON can hold, the document is deleted (a failure to delete is not told: the upload has
|
|
484
|
+
* failed either way) and the error is what the upload answers.
|
|
485
|
+
*/
|
|
486
|
+
async function uploaded(meta, request, caller, clientGone, saved) {
|
|
487
|
+
if (!options.onUploaded)
|
|
488
|
+
return {};
|
|
489
|
+
try {
|
|
490
|
+
const returned = await options.onUploaded(meta, { request, ...caller, clientGone, ...(saved !== undefined ? { path: saved } : {}) });
|
|
491
|
+
return hookAnswerOf(returned);
|
|
492
|
+
}
|
|
493
|
+
catch (error) {
|
|
494
|
+
// A delete of your own that throws at once is told no more than one that rejects.
|
|
495
|
+
await Promise.resolve().then(() => files.delete(meta.id, caller)).catch(() => undefined);
|
|
496
|
+
return { failure: error };
|
|
497
|
+
}
|
|
498
|
+
}
|
|
312
499
|
return {
|
|
313
500
|
async upload(request, response) {
|
|
314
501
|
try {
|
|
@@ -316,38 +503,43 @@ export function createDocumentHandlers(files, options = {}) {
|
|
|
316
503
|
const name = header(request, "x-file-name").trim() || url.searchParams.get("name")?.trim() || "";
|
|
317
504
|
if (!name)
|
|
318
505
|
throw new HttpError(400, "Name the file with an X-File-Name header or a ?name= query parameter.");
|
|
319
|
-
// Who is asking comes first: a refused upload is not read into memory.
|
|
320
|
-
|
|
321
|
-
// mistake, answered with a 500 before the body is read. Its message says which, so that the
|
|
322
|
-
// operator knows where to look; it says nothing else.
|
|
323
|
-
const currentOwner = await owner(request);
|
|
324
|
-
try {
|
|
325
|
-
checkOwner(currentOwner);
|
|
326
|
-
}
|
|
327
|
-
catch {
|
|
328
|
-
const empty = typeof currentOwner === "string" || currentOwner === null;
|
|
329
|
-
throw new HttpError(500, empty ? "Upload failed (empty owner)." : "Upload failed (owner is not a string).");
|
|
330
|
-
}
|
|
506
|
+
// Who is asking comes first: a refused upload is not read into memory.
|
|
507
|
+
const caller = await callerOf(request, "Upload failed", true);
|
|
331
508
|
// Too large is said first, before any wait for room.
|
|
332
509
|
const declared = Number(request.headers["content-length"]);
|
|
333
|
-
const parsed = request
|
|
334
|
-
if ((Number.isFinite(declared) && declared > files.maxUploadBytes) || (parsed
|
|
510
|
+
const parsed = parsedBody(request);
|
|
511
|
+
if ((Number.isFinite(declared) && declared > files.maxUploadBytes) || (parsed !== undefined && parsed.byteLength > files.maxUploadBytes)) {
|
|
335
512
|
throw new HttpError(413, "");
|
|
336
513
|
}
|
|
337
|
-
|
|
338
|
-
//
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
514
|
+
const prepared = options.prepareUpload ? preparedOf(await options.prepareUpload(request, { name: cleanFileName(name), ...caller })) : {};
|
|
515
|
+
// A file `fileOriginals` would not read back by its ref is refused before anything is written.
|
|
516
|
+
if (prepared.path !== undefined && prepared.original !== undefined)
|
|
517
|
+
await checkRefFolders(prepared.path, prepared.original.ref, idleMs);
|
|
518
|
+
// Where the body is while it is ingested: in the application's file (`prepareUpload`), in a
|
|
519
|
+
// file of the spool, or in memory. Room is taken for it before it is read, so that a refused
|
|
520
|
+
// upload is not read: in the spool, or in memory. The application's file takes none: it is
|
|
521
|
+
// on the application's disk, and stays.
|
|
522
|
+
const spooled = prepared.path === undefined && spools(declared, parsed);
|
|
523
|
+
const held = prepared.path !== undefined ? undefined : (spooled ? spoolRoom : memoryRoom).take(expectedSize(request, files.maxUploadBytes));
|
|
524
|
+
/** Gives the upload's room back, once: when its ingest ended, so that an `onUploaded` that waits on a database of yours does not hold it, or when the upload failed. */
|
|
525
|
+
const release = () => held?.release();
|
|
526
|
+
let file;
|
|
343
527
|
try {
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
528
|
+
let body;
|
|
529
|
+
if (prepared.path !== undefined || spooled) {
|
|
530
|
+
const at = prepared.path ?? spoolFileIn(spool.directory);
|
|
531
|
+
const size = await writeBody(request, at, { limit: files.maxUploadBytes, idleMs, mode: prepared.path !== undefined ? fileMode : 0o600 });
|
|
532
|
+
file = new BodyFile(at, prepared.path !== undefined, idleMs);
|
|
533
|
+
held?.resize(size);
|
|
534
|
+
}
|
|
535
|
+
else {
|
|
536
|
+
body = await readBody(request, files.maxUploadBytes, idleMs);
|
|
537
|
+
// Counted at its size once read (an upload without a Content-Length was counted at the limit).
|
|
538
|
+
held?.resize(body.byteLength);
|
|
349
539
|
}
|
|
350
|
-
|
|
540
|
+
// Content-Type is a header of HTTP, not one the page encodes: it is taken as it came (S11).
|
|
541
|
+
// `ingest` cleans what it keeps of either.
|
|
542
|
+
const contentType = rawHeader(request, "content-type");
|
|
351
543
|
const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
|
|
352
544
|
// A client that goes away before the answer stops the reading of its file: nobody would
|
|
353
545
|
// get the document, and the server has other work.
|
|
@@ -357,29 +549,59 @@ export function createDocumentHandlers(files, options = {}) {
|
|
|
357
549
|
gone.abort(new Error("The upload was cancelled: the client closed the connection."));
|
|
358
550
|
};
|
|
359
551
|
response.once("close", onClose);
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
552
|
+
// One that left already is told no more: while the last piece of its body was written,
|
|
553
|
+
// or its file closed (where a network volume writes what it held back), or before a body
|
|
554
|
+
// a framework read was taken.
|
|
555
|
+
if (response.destroyed || request.socket?.destroyed)
|
|
556
|
+
onClose();
|
|
557
|
+
const chosen = { ...(prepared.id !== undefined ? { id: prepared.id } : {}), ...(prepared.original !== undefined ? { original: prepared.original } : {}) };
|
|
558
|
+
/**
|
|
559
|
+
* Starts the upload's ingest, once. A body in memory is then the ingest's alone: it is
|
|
560
|
+
* freed when the ingest ends, while `onUploaded` may still run. The input is built in
|
|
561
|
+
* this function, whose frame ends at once: a value in the frame of `upload`, an async
|
|
562
|
+
* function, is kept until it returns, the hook's wait included. A body in a file is
|
|
563
|
+
* ingested from its path: the file of the spool is removed when the ingest ends, and the
|
|
564
|
+
* application's file when the ingest fails.
|
|
565
|
+
*/
|
|
566
|
+
const start = (more) => {
|
|
567
|
+
const input = { name, ...(mimeType ? { mimeType } : {}), ...chosen, ...caller, signal: gone.signal, ...more };
|
|
568
|
+
if (file)
|
|
569
|
+
return file.settle(files.ingest({ ...input, source: { path: file.path } }));
|
|
570
|
+
const bytes = body;
|
|
571
|
+
body = undefined;
|
|
572
|
+
return files.ingest({ ...input, bytes });
|
|
573
|
+
};
|
|
574
|
+
// The path is told only for the application's own file: the spool's is gone by then.
|
|
575
|
+
const saved = file?.kept ? file.path : undefined;
|
|
576
|
+
const hook = async (meta) => {
|
|
577
|
+
const hooked = await uploaded(meta, request, caller, gone.signal.aborted, saved);
|
|
578
|
+
// The document is deleted: the file saved for it goes too.
|
|
579
|
+
if ("failure" in hooked)
|
|
580
|
+
await file?.remove();
|
|
581
|
+
return hooked;
|
|
366
582
|
};
|
|
367
|
-
let meta;
|
|
368
583
|
try {
|
|
369
|
-
if (wantsEvents(request))
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
584
|
+
if (wantsEvents(request)) {
|
|
585
|
+
// `onUploaded` runs once, for the event before ingest.finish or after the stream.
|
|
586
|
+
let hooking;
|
|
587
|
+
return await streamIngest(start, gone.signal, response, tooLarge, (meta) => (hooking ??= hook(meta)), release);
|
|
588
|
+
}
|
|
589
|
+
const meta = await start();
|
|
590
|
+
release();
|
|
591
|
+
const hooked = await hook(meta);
|
|
592
|
+
if ("failure" in hooked)
|
|
593
|
+
throw hooked.failure;
|
|
594
|
+
// The summary's own fields win over the hook's.
|
|
595
|
+
send(response, 201, { ...hooked.answer, ...toDocumentSummary(meta) });
|
|
375
596
|
}
|
|
376
597
|
finally {
|
|
377
598
|
response.off("close", onClose);
|
|
378
599
|
}
|
|
379
|
-
send(response, 201, toDocumentSummary(meta));
|
|
380
600
|
}
|
|
381
601
|
finally {
|
|
382
|
-
|
|
602
|
+
release();
|
|
603
|
+
// Whatever happened: the spool's file is gone, and so is the application's unless its document is stored.
|
|
604
|
+
await file?.end();
|
|
383
605
|
}
|
|
384
606
|
}
|
|
385
607
|
catch (error) {
|
|
@@ -404,8 +626,8 @@ export function createDocumentHandlers(files, options = {}) {
|
|
|
404
626
|
},
|
|
405
627
|
async get(request, response, id) {
|
|
406
628
|
try {
|
|
407
|
-
const
|
|
408
|
-
const meta = await files.getMeta(id,
|
|
629
|
+
const caller = await callerOf(request, "The file could not be looked up", false);
|
|
630
|
+
const meta = await files.getMeta(id, caller);
|
|
409
631
|
if (meta)
|
|
410
632
|
send(response, 200, toDocumentSummary(meta));
|
|
411
633
|
else
|
|
@@ -417,8 +639,11 @@ export function createDocumentHandlers(files, options = {}) {
|
|
|
417
639
|
},
|
|
418
640
|
async remove(request, response, id) {
|
|
419
641
|
try {
|
|
420
|
-
const
|
|
421
|
-
|
|
642
|
+
const caller = await callerOf(request, "The file could not be deleted", false);
|
|
643
|
+
const deleted = await files.delete(id, caller);
|
|
644
|
+
if (deleted && options.onRemoved)
|
|
645
|
+
await options.onRemoved(id, { request, ...caller });
|
|
646
|
+
send(response, 200, { deleted });
|
|
422
647
|
}
|
|
423
648
|
catch (error) {
|
|
424
649
|
fail(response, error, "The file could not be deleted", tooLarge);
|
|
@@ -426,4 +651,21 @@ export function createDocumentHandlers(files, options = {}) {
|
|
|
426
651
|
},
|
|
427
652
|
};
|
|
428
653
|
}
|
|
654
|
+
/**
|
|
655
|
+
* What `onUploaded` returned, as the fields to add to the answer: `{ answer }` with a plain object
|
|
656
|
+
* that JSON can hold (a copy of it, as JSON reads it back). Anything else without an `answer` (a
|
|
657
|
+
* database's own result) adds nothing. An `answer` of another kind is a TypeError.
|
|
658
|
+
*/
|
|
659
|
+
function hookAnswerOf(returned) {
|
|
660
|
+
if (typeof returned !== "object" || returned === null)
|
|
661
|
+
return {};
|
|
662
|
+
const answer = returned.answer;
|
|
663
|
+
if (answer === undefined || answer === null)
|
|
664
|
+
return {};
|
|
665
|
+
const proto = typeof answer === "object" ? Object.getPrototypeOf(answer) : undefined;
|
|
666
|
+
if (typeof answer !== "object" || Array.isArray(answer) || (proto !== Object.prototype && proto !== null)) {
|
|
667
|
+
throw new TypeError("onUploaded must return nothing, or { answer } with a plain object that JSON can hold.");
|
|
668
|
+
}
|
|
669
|
+
return { answer: JSON.parse(JSON.stringify(answer)) };
|
|
670
|
+
}
|
|
429
671
|
//# sourceMappingURL=handlers.js.map
|