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.
Files changed (201) hide show
  1. package/CHANGELOG.md +535 -0
  2. package/README.md +9 -10
  3. package/dist/access.d.ts +86 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +131 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/ask.d.ts +45 -1
  8. package/dist/ask.d.ts.map +1 -1
  9. package/dist/ask.js +181 -20
  10. package/dist/ask.js.map +1 -1
  11. package/dist/cache.d.ts +12 -3
  12. package/dist/cache.d.ts.map +1 -1
  13. package/dist/cache.js +18 -5
  14. package/dist/cache.js.map +1 -1
  15. package/dist/encoding.js +5 -3
  16. package/dist/encoding.js.map +1 -1
  17. package/dist/error-info.d.ts +57 -0
  18. package/dist/error-info.d.ts.map +1 -0
  19. package/dist/error-info.js +217 -0
  20. package/dist/error-info.js.map +1 -0
  21. package/dist/errors.d.ts +72 -8
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js +102 -15
  24. package/dist/errors.js.map +1 -1
  25. package/dist/events.d.ts +35 -9
  26. package/dist/events.d.ts.map +1 -1
  27. package/dist/events.js +42 -11
  28. package/dist/events.js.map +1 -1
  29. package/dist/evidence.d.ts +4 -2
  30. package/dist/evidence.d.ts.map +1 -1
  31. package/dist/evidence.js +14 -3
  32. package/dist/evidence.js.map +1 -1
  33. package/dist/extract.d.ts +32 -8
  34. package/dist/extract.d.ts.map +1 -1
  35. package/dist/extract.js +46 -35
  36. package/dist/extract.js.map +1 -1
  37. package/dist/gemini/adapter.d.ts +19 -3
  38. package/dist/gemini/adapter.d.ts.map +1 -1
  39. package/dist/gemini/adapter.js +84 -12
  40. package/dist/gemini/adapter.js.map +1 -1
  41. package/dist/gemini/chat.d.ts +18 -6
  42. package/dist/gemini/chat.d.ts.map +1 -1
  43. package/dist/gemini/chat.js +2 -0
  44. package/dist/gemini/chat.js.map +1 -1
  45. package/dist/gemini/index.d.ts +1 -1
  46. package/dist/gemini/index.d.ts.map +1 -1
  47. package/dist/index.d.ts +9 -6
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +4 -3
  50. package/dist/index.js.map +1 -1
  51. package/dist/ingest.d.ts +70 -0
  52. package/dist/ingest.d.ts.map +1 -0
  53. package/dist/ingest.js +868 -0
  54. package/dist/ingest.js.map +1 -0
  55. package/dist/library.d.ts +169 -34
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +324 -591
  58. package/dist/library.js.map +1 -1
  59. package/dist/map-reduce.js +3 -3
  60. package/dist/map-reduce.js.map +1 -1
  61. package/dist/model.d.ts +43 -2
  62. package/dist/model.d.ts.map +1 -1
  63. package/dist/model.js +63 -3
  64. package/dist/model.js.map +1 -1
  65. package/dist/node/handlers.d.ts +226 -14
  66. package/dist/node/handlers.d.ts.map +1 -1
  67. package/dist/node/handlers.js +423 -181
  68. package/dist/node/handlers.js.map +1 -1
  69. package/dist/node/index.d.ts +3 -2
  70. package/dist/node/index.d.ts.map +1 -1
  71. package/dist/node/index.js +2 -1
  72. package/dist/node/index.js.map +1 -1
  73. package/dist/node/ingest-child.d.ts +7 -1
  74. package/dist/node/ingest-child.d.ts.map +1 -1
  75. package/dist/node/ingest-child.js +18 -3
  76. package/dist/node/ingest-child.js.map +1 -1
  77. package/dist/node/isolated.d.ts +3 -1
  78. package/dist/node/isolated.d.ts.map +1 -1
  79. package/dist/node/isolated.js +11 -4
  80. package/dist/node/isolated.js.map +1 -1
  81. package/dist/node/originals.d.ts +19 -0
  82. package/dist/node/originals.d.ts.map +1 -0
  83. package/dist/node/originals.js +82 -0
  84. package/dist/node/originals.js.map +1 -0
  85. package/dist/node/spool.d.ts +102 -0
  86. package/dist/node/spool.d.ts.map +1 -0
  87. package/dist/node/spool.js +365 -0
  88. package/dist/node/spool.js.map +1 -0
  89. package/dist/node/sse.d.ts +4 -3
  90. package/dist/node/sse.d.ts.map +1 -1
  91. package/dist/node/sse.js +7 -6
  92. package/dist/node/sse.js.map +1 -1
  93. package/dist/pdf-layout.d.ts.map +1 -1
  94. package/dist/pdf-layout.js +71 -12
  95. package/dist/pdf-layout.js.map +1 -1
  96. package/dist/ranged.d.ts +15 -11
  97. package/dist/ranged.d.ts.map +1 -1
  98. package/dist/ranged.js +42 -11
  99. package/dist/ranged.js.map +1 -1
  100. package/dist/retry.d.ts +3 -1
  101. package/dist/retry.d.ts.map +1 -1
  102. package/dist/retry.js +6 -2
  103. package/dist/retry.js.map +1 -1
  104. package/dist/scope.d.ts +25 -0
  105. package/dist/scope.d.ts.map +1 -0
  106. package/dist/scope.js +60 -0
  107. package/dist/scope.js.map +1 -0
  108. package/dist/source.d.ts +60 -0
  109. package/dist/source.d.ts.map +1 -0
  110. package/dist/source.js +170 -0
  111. package/dist/source.js.map +1 -0
  112. package/dist/stores.d.ts +120 -31
  113. package/dist/stores.d.ts.map +1 -1
  114. package/dist/stores.js +582 -139
  115. package/dist/stores.js.map +1 -1
  116. package/dist/testing/fake-fetch.d.ts +31 -0
  117. package/dist/testing/fake-fetch.d.ts.map +1 -0
  118. package/dist/testing/fake-fetch.js +66 -0
  119. package/dist/testing/fake-fetch.js.map +1 -0
  120. package/dist/testing/fake-model.d.ts +38 -0
  121. package/dist/testing/fake-model.d.ts.map +1 -0
  122. package/dist/testing/fake-model.js +62 -0
  123. package/dist/testing/fake-model.js.map +1 -0
  124. package/dist/testing/index.d.ts +7 -0
  125. package/dist/testing/index.d.ts.map +1 -0
  126. package/dist/testing/index.js +9 -0
  127. package/dist/testing/index.js.map +1 -0
  128. package/dist/testing/store-checks.d.ts +72 -0
  129. package/dist/testing/store-checks.d.ts.map +1 -0
  130. package/dist/testing/store-checks.js +619 -0
  131. package/dist/testing/store-checks.js.map +1 -0
  132. package/dist/tools.d.ts +25 -0
  133. package/dist/tools.d.ts.map +1 -1
  134. package/dist/tools.js +135 -13
  135. package/dist/tools.js.map +1 -1
  136. package/dist/types.d.ts +116 -13
  137. package/dist/types.d.ts.map +1 -1
  138. package/docs/README.md +17 -8
  139. package/docs/getting-started.md +18 -13
  140. package/docs/guides/anthropic.md +12 -8
  141. package/docs/guides/conversations.md +112 -47
  142. package/docs/guides/costs-and-limits.md +16 -7
  143. package/docs/guides/deployment.md +284 -83
  144. package/docs/guides/errors-and-reliability.md +161 -23
  145. package/docs/guides/own-adapter-and-loop.md +27 -10
  146. package/docs/guides/pdfs.md +123 -29
  147. package/docs/guides/storage.md +633 -145
  148. package/docs/guides/testing.md +78 -129
  149. package/docs/guides/vertex-and-gemini.md +10 -7
  150. package/docs/guides/web-app.md +312 -78
  151. package/docs/how-it-works.md +35 -8
  152. package/docs/measurements.md +43 -8
  153. package/docs/publishing.md +112 -36
  154. package/docs/reference/ask.md +154 -13
  155. package/docs/reference/errors-and-retries.md +166 -14
  156. package/docs/reference/events.md +53 -20
  157. package/docs/reference/gemini.md +70 -21
  158. package/docs/reference/library.md +706 -165
  159. package/docs/reference/node.md +624 -110
  160. package/docs/reference/testing.md +311 -0
  161. package/docs/reference/tools.md +15 -5
  162. package/docs/security.md +304 -67
  163. package/docs/troubleshooting.md +144 -65
  164. package/docs/upgrading-0.9.md +890 -0
  165. package/package.json +12 -3
  166. package/src/access.ts +144 -0
  167. package/src/ask.ts +230 -19
  168. package/src/cache.ts +20 -5
  169. package/src/encoding.ts +6 -4
  170. package/src/error-info.ts +255 -0
  171. package/src/errors.ts +129 -15
  172. package/src/events.ts +86 -21
  173. package/src/evidence.ts +14 -3
  174. package/src/extract.ts +50 -33
  175. package/src/gemini/adapter.ts +97 -11
  176. package/src/gemini/chat.ts +20 -6
  177. package/src/gemini/index.ts +1 -1
  178. package/src/index.ts +9 -6
  179. package/src/ingest.ts +927 -0
  180. package/src/library.ts +467 -601
  181. package/src/map-reduce.ts +3 -3
  182. package/src/model.ts +69 -5
  183. package/src/node/handlers.ts +630 -183
  184. package/src/node/index.ts +13 -2
  185. package/src/node/ingest-child.ts +23 -5
  186. package/src/node/isolated.ts +11 -4
  187. package/src/node/originals.ts +78 -0
  188. package/src/node/spool.ts +365 -0
  189. package/src/node/sse.ts +7 -6
  190. package/src/pdf-layout.ts +69 -11
  191. package/src/ranged.ts +34 -13
  192. package/src/retry.ts +6 -2
  193. package/src/scope.ts +63 -0
  194. package/src/source.ts +178 -0
  195. package/src/stores.ts +635 -140
  196. package/src/testing/fake-fetch.ts +80 -0
  197. package/src/testing/fake-model.ts +78 -0
  198. package/src/testing/index.ts +11 -0
  199. package/src/testing/store-checks.ts +660 -0
  200. package/src/tools.ts +150 -14
  201. package/src/types.ts +106 -13
@@ -1,11 +1,125 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
- import { IngestError, isStoreWriteFailure } from "../errors.js";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
4
+ import { errorInfoOf, STORE_RETRY_AFTER_MS, UNREADABLE_MESSAGE } from "../error-info.js";
5
+ import { DocumentScopeError, DocumentStoreError, IngestError, isErrorCode, type IngestErrorCode } from "../errors.js";
3
6
  import { eventStream, newRunId, type EventError, type IngestEvent } from "../events.js";
4
- import { checkOwner, toDocumentSummary, type IngestInput, type LargeFiles } from "../library.js";
7
+ import { checkOwner, cleanFileName, toDocumentSummary, type AccessOptions, type IngestInput, type LargeFiles } from "../library.js";
8
+ import { DocumentsNotFoundError, errorKindOf, ModelRequestError, type ModelErrorKind } from "../model.js";
5
9
  import { formatBytes } from "../plan.js";
6
- import type { DocumentMeta } from "../types.js";
10
+ import { checkScope } from "../scope.js";
11
+ import type { DocumentMeta, DocumentScope } from "../types.js";
12
+ import { BodyFile, checkRefFolders, HttpError, parsedBody, readBody, Room, spoolFileIn, writeBody, type Held } from "./spool.js";
7
13
  import { writeSseEvents } from "./sse.js";
8
14
 
15
+ /** What `onUploaded` is told besides the document. New in 0.9.0. */
16
+ export type UploadedContext = {
17
+ /**
18
+ * The upload's request, for its headers and URL. Its body has been read: the bytes are not here,
19
+ * unless a framework left them in `request.body` (`express.raw()`), which keeps them until the
20
+ * request ends.
21
+ */
22
+ request: IncomingMessage;
23
+ /** What `getOwner` returned, when it returned an owner. */
24
+ owner?: string;
25
+ /** What `getScope` returned, when it returned a scope (a frozen copy). */
26
+ scope?: DocumentScope;
27
+ /**
28
+ * True when the client went away before the hook was called: the document is stored all the
29
+ * same, and nobody gets the answer. Record it, or remove it, as your app needs. With the
30
+ * library's own `ingest`, a client that leaves before the ingest ends leaves nothing stored, and
31
+ * the hook is not called: this is for a client that left after the ingest ended, or for an
32
+ * `ingest` of your own that does not stop on its `signal`.
33
+ */
34
+ clientGone: boolean;
35
+ /**
36
+ * The path the body was saved to: the `path` that `prepareUpload` returned. Only for such an
37
+ * upload: the file is yours, and stays (unless this hook throws). A file of the spool
38
+ * (`uploadSpool`) is gone by now, and is not told. New in 0.9.0.
39
+ */
40
+ path?: string;
41
+ };
42
+
43
+ /** What `prepareUpload` is told of an upload, before its body is read. New in 0.9.0. */
44
+ export type PrepareUploadInfo = {
45
+ /**
46
+ * The file's name, as the document will have it: the last part of the name sent, without
47
+ * control characters (`cleanFileName`). It is the client's: never build a path from it.
48
+ */
49
+ name: string;
50
+ /** What `getOwner` returned, when it returned an owner. */
51
+ owner?: string;
52
+ /** What `getScope` returned, when it returned a scope (a frozen copy). */
53
+ scope?: DocumentScope;
54
+ };
55
+
56
+ /**
57
+ * What `prepareUpload` may return for an upload: the document's ID, where to save its body, and
58
+ * the ref of that file for `LargeFilesOptions.originals`. Each is optional. New in 0.9.0.
59
+ */
60
+ export type PreparedUpload = {
61
+ /**
62
+ * The document's ID (`IngestInput.id`), such as the ID of the upload in your database. A
63
+ * document of that ID that is already stored makes the upload fail with a 409 ("exists").
64
+ */
65
+ id?: string;
66
+ /**
67
+ * An absolute path where the body is saved as it arrives, then ingested from (`source`). The
68
+ * file must not be there: it is made new (`"wx"`, mode `uploadFileMode`), and never written
69
+ * through a file or a link already at that name (a 409). Its folder must exist: the handler makes
70
+ * no folder. A link in a folder above it is followed, except below the root of a ref (see
71
+ * `original`). The file is yours once the document is stored: the library never removes it, even
72
+ * when the document is deleted or expires. When the upload fails, it is removed.
73
+ */
74
+ path?: string;
75
+ /**
76
+ * The ref of the saved file for `LargeFilesOptions.originals` (`IngestInput.original`), such as
77
+ * its path under the folder of `fileOriginals`: the store then keeps no copy of it. Give it with
78
+ * `path`: the handler does not make a ref of a path, nor check that the ref names that file.
79
+ * When `path` ends with the ref (`<root>/<ref>`, as `fileOriginals(root)` reads it), a link in a
80
+ * folder below that root, which `fileOriginals` would refuse to read through, fails the upload
81
+ * before its body is read: a 500 "Upload failed (ELOOP).".
82
+ */
83
+ original?: { ref: string };
84
+ };
85
+
86
+ /** Where `uploadSpool` writes the bodies of uploads, and which ones. New in 0.9.0. */
87
+ export type UploadSpoolOptions = {
88
+ /** The folder of the temporary files. It must exist. Defaults to `os.tmpdir()`. */
89
+ directory?: string;
90
+ /**
91
+ * Bodies whose `Content-Length` is this many bytes or fewer are held in memory, as without a
92
+ * spool; larger ones, and those without a `Content-Length`, are written to a temporary file.
93
+ * Defaults to 1 MiB (1,048,576). 0 writes every body to a file.
94
+ */
95
+ minBytes?: number;
96
+ };
97
+
98
+ /**
99
+ * What `onUploaded` may return: nothing, or `{ answer }`, whose fields are added to the upload's
100
+ * answer (the `201` JSON, or `ingest.finish.app`). New in 0.9.0.
101
+ */
102
+ export type UploadedResult = void | { answer?: Record<string, unknown> };
103
+
104
+ /** What `onRemoved` is told besides the document's ID. New in 0.9.0. */
105
+ export type RemovedContext = {
106
+ request: IncomingMessage;
107
+ owner?: string;
108
+ scope?: DocumentScope;
109
+ };
110
+
111
+ /**
112
+ * An error as the upload handler answers it (`uploadAnswerOf`): the HTTP status, the message of
113
+ * the JSON body `{ "error": … }`, the `IngestErrorCode` of a file that could not be read, and how
114
+ * long to wait before trying again (the `Retry-After` header of a 503). New in 0.9.0.
115
+ */
116
+ export type UploadAnswer = {
117
+ status: number;
118
+ error: string;
119
+ code?: IngestErrorCode;
120
+ retryAfterMs?: number;
121
+ };
122
+
9
123
  export type DocumentHandlerOptions = {
10
124
  /**
11
125
  * The signed-in user for this request. When set, uploads are owned by that user and other
@@ -15,6 +129,13 @@ export type DocumentHandlerOptions = {
15
129
  * JavaScript that is neither a string nor a finite number (`req.user` in place of `req.user.id`,
16
130
  * say): `{"error":"Upload failed (owner is not a string)."}`.
17
131
  *
132
+ * When the library requires an owner (`requireOwner`), it is required here: the handlers cannot
133
+ * be made without it, and an undefined owner (or null, from JavaScript) is answered 401
134
+ * `{"error":"Sign in first."}` before the body is read, on every route (new in 0.9.0). An empty
135
+ * owner is then a 500 on every route too, without calling the library: `get` answers
136
+ * `{"error":"The file could not be looked up (empty owner)."}`, and `remove`
137
+ * `{"error":"The file could not be deleted (empty owner)."}`.
138
+ *
18
139
  * To refuse a request, throw an error with a `status` (or `statusCode`) between 400 and 599, as
19
140
  * the `http-errors` package makes: the handler answers with that status and the error's message.
20
141
  * Any other error is answered with a 500 that does not repeat its message. It is called before
@@ -22,18 +143,91 @@ export type DocumentHandlerOptions = {
22
143
  */
23
144
  getOwner?: (request: IncomingMessage) => string | undefined | Promise<string | undefined>;
24
145
  /**
25
- * The most bytes of uploads these handlers hold at once: an upload is held whole in memory from
26
- * the moment its body is read until its ingest ends. An upload that would pass it is answered 503
27
- * with `Retry-After` before its body is read, while another upload is held: one upload alone is
28
- * always taken. An upload counts its `Content-Length` (or `maxUploadBytes` without one, then its
29
- * size once read). `Infinity` for no limit (as before 0.8.2). Defaults to twice `maxUploadBytes`.
30
- * New in 0.8.2.
146
+ * The scope of this request, such as [userId, chatId] (`DocumentScope`): uploads are stored in
147
+ * it, and `get` and `remove` find only the documents of the same scope. Called after `getOwner`,
148
+ * before the body is read, on every route. Return undefined for no scope. A scope that is not
149
+ * valid is the server's mistake: a 500 `{"error":"Upload failed (invalid scope)."}`. Throw an
150
+ * error with a status to refuse a request, as for `getOwner`. Required when the library requires
151
+ * a scope (`requireScope`); an undefined scope is then a 500 `{"error":"Upload failed (no scope)."}`.
152
+ * New in 0.9.0.
153
+ */
154
+ getScope?: (request: IncomingMessage) => DocumentScope | undefined | Promise<DocumentScope | undefined>;
155
+ /**
156
+ * Called once an upload is stored, before it is answered: to record the document in your
157
+ * database, say. The `201` is sent, or `ingest.finish` on the event-stream path, once it
158
+ * resolves, with no time limit: bound your own calls. The upload's room
159
+ * (`maxPendingUploadBytes`) is given back, and the body the handler read is freed, before it is
160
+ * called. It is called even when the client went away after the ingest ended (`clientGone`):
161
+ * with the library's own `ingest`, a client that leaves before it ends leaves nothing stored,
162
+ * and no call. Return `{ answer }` to add its fields to the answer: to the `201` JSON (the
163
+ * summary's own fields win), or as `app` in `ingest.finish`. `answer` must be a plain object that
164
+ * JSON can hold.
165
+ *
166
+ * When it throws, or returns an `answer` that is not such an object, the document is deleted
167
+ * (best effort) and the upload is answered as for an error of `ingest`: with the error's status
168
+ * (400 to 599) and message, or a 500 `{"error":"Upload failed."}`. New in 0.9.0.
169
+ */
170
+ onUploaded?: (document: DocumentMeta, context: UploadedContext) => UploadedResult | Promise<UploadedResult>;
171
+ /**
172
+ * Called after `remove` deleted a document (`{ deleted: true }`), before it answers. When it
173
+ * throws, the answer is the error's status and message, or a 500; the document is deleted all
174
+ * the same, and a second `remove` answers `{ deleted: false }` without calling it. New in 0.9.0.
175
+ */
176
+ onRemoved?: (id: string, context: RemovedContext) => void | Promise<void>;
177
+ /**
178
+ * Called for each upload after `getOwner` and `getScope`, before its body is read: returns the
179
+ * document's `id`, a `path` to save the body to, and the `original` ref of that file (see
180
+ * `PreparedUpload`), or nothing. With a `path`, the body is written there as it arrives (under
181
+ * the same limits: `maxUploadBytes`, `uploadIdleTimeoutMs`), then ingested from the file, which
182
+ * stays once the document is stored and is removed when the upload fails, whatever the reason
183
+ * (a process that is killed cannot remove it).
184
+ * Such an upload is not held in memory, and takes no room of `maxPendingUploadBytes` or
185
+ * `maxSpooledUploadBytes`. Throw an error with a status to refuse the upload, as for `getOwner`.
186
+ * The upload can still fail after it (no room, too large…): choose here, record in `onUploaded`.
187
+ * New in 0.9.0.
188
+ */
189
+ prepareUpload?: (request: IncomingMessage, info: PrepareUploadInfo) => PreparedUpload | void | Promise<PreparedUpload | void>;
190
+ /**
191
+ * Writes the bodies of uploads to temporary files, instead of holding them in memory while they
192
+ * are ingested: those over `minBytes` (1 MiB), and those without a `Content-Length`. Each file is
193
+ * made new in `directory` (`os.tmpdir()`), with a random name and mode 0o600, ingested from its
194
+ * path, and removed once the ingest ends, whatever the end. `true` for the defaults. Defaults to
195
+ * false. New in 0.9.0.
196
+ */
197
+ uploadSpool?: boolean | UploadSpoolOptions;
198
+ /**
199
+ * The most bytes of the spool's files (`uploadSpool`) at once. An upload that would pass it is
200
+ * answered 503 with `Retry-After`, before its body is read, as for `maxPendingUploadBytes`. A
201
+ * disk that is full is answered 503 with `Retry-After` too. `Infinity` for no limit. Defaults to
202
+ * ten times `maxUploadBytes`. New in 0.9.0.
203
+ */
204
+ maxSpooledUploadBytes?: number;
205
+ /**
206
+ * The mode of the files saved to the `path` of `prepareUpload`, minus the umask of the process.
207
+ * Defaults to 0o600: only the server's user reads them. 0o640 lets a group read them (pods of
208
+ * another user that share the volume through a group). The spool's files are always 0o600. New
209
+ * in 0.9.0.
210
+ */
211
+ uploadFileMode?: number;
212
+ /**
213
+ * The most bytes of uploads these handlers hold in memory at once: an upload is held whole in
214
+ * memory from the moment its body is read until its ingest ends. An upload that would pass it is
215
+ * answered 503 with `Retry-After` before its body is read, while another upload is held: one
216
+ * upload alone is always taken. An upload counts its `Content-Length` (or `maxUploadBytes`
217
+ * without one, then its size once read). Bodies written to a file (`prepareUpload`'s `path`,
218
+ * `uploadSpool`) do not count, since 0.9.0. `Infinity` for no limit (as before 0.8.2). Defaults
219
+ * to twice `maxUploadBytes`. New in 0.8.2.
31
220
  */
32
221
  maxPendingUploadBytes?: number;
33
222
  /**
34
223
  * An upload whose body stops arriving for this many milliseconds is answered 408, its connection
35
224
  * closed and its room given back: a client that sends its headers and then nothing, or stalls,
36
- * holds its room no longer. 0 or `Infinity` for no limit. Defaults to 30,000. New in 0.8.2.
225
+ * holds its room no longer. Since 0.9.0 it also bounds each call to the disk for a body written
226
+ * to a file (the check of its folders for a link, its opening, each write, its closing): a volume
227
+ * that stops answering fails the upload with a 500 "Upload failed (ETIMEDOUT).", and its room is
228
+ * given back. The removal of the file is waited for no longer either: past it, the removal goes
229
+ * on alone, and the upload is answered all the same. 0 or `Infinity` for no limit. Defaults to
230
+ * 30,000. New in 0.8.2.
37
231
  */
38
232
  uploadIdleTimeoutMs?: number;
39
233
  };
@@ -47,27 +241,30 @@ export type DocumentHandlers = {
47
241
  /**
48
242
  * POST: the body is the raw file. Name it with an `X-File-Name` header (URI-encoded) or `?name=`.
49
243
  * A file that cannot be read is answered with a 422 and the reason. A store that fails while it
50
- * writes is answered with a 500 that does not repeat its message, unless its error has a status.
244
+ * writes is answered with a 503 and `Retry-After`. Any other error is answered as
245
+ * `uploadAnswerOf` says. The body is held in memory, or, with the `path` of `prepareUpload` or
246
+ * with `uploadSpool`, written to a file as it arrives and ingested from its path (new in 0.9.0).
51
247
  *
52
248
  * When the request's `Accept` header names `text/event-stream` (not with `q=0`, nor only through a
53
- * wildcard), a file that passes the checks of the name, the owner and the size (which still
54
- * answer with an HTTP error) is answered with a 200 and Server-Sent Events: the ingest's events (`ingest.start`, `ingest.progress`…), ending
55
- * with `ingest.finish`, whose data is the summary a 201 would hold, or `ingest.error`, whose data
56
- * is `{ error: { message, status } }` with the message and status a JSON answer would have.
249
+ * wildcard), a file that passes the checks of the name, the owner, the scope and the size (which
250
+ * still answer with an HTTP error) is answered with a 200 and Server-Sent Events: the ingest's
251
+ * events (`ingest.start`, `ingest.progress`…), ending with `ingest.finish`, whose data is the
252
+ * summary a 201 would hold (and `onUploaded`'s answer in `app`), or `ingest.error`, whose data is
253
+ * `{ error: { message, status } }` with the message and status a JSON answer would have, the
254
+ * `code` of a refused file, the `name` of a store that failed or of a scope error (with its
255
+ * `code`), and the `kind` of a model's error, for `errorInfoOf`.
57
256
  */
58
257
  upload(request: IncomingMessage, response: ServerResponse): Promise<void>;
59
- /** GET: the document's summary, or 404. */
258
+ /** GET: the document's summary, or 404. With `getScope`, only a document of the request's scope. */
60
259
  get(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
61
- /** DELETE: removes the document. Responds `{ deleted: boolean }`. */
260
+ /** DELETE: removes the document, then calls `onRemoved`. Responds `{ deleted: boolean }`. */
62
261
  remove(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
63
262
  };
64
263
 
65
- class HttpError extends Error {
66
- /** `close`: answer, then close the connection, without waiting for the rest of the body. */
67
- constructor(readonly status: number, message: string, readonly close = false) {
68
- super(message);
69
- }
70
- }
264
+ /** A whole HTTP status of an error, from 400 to 599. */
265
+ const isErrorStatus = (value: unknown): value is number => typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599;
266
+ /** A wait in milliseconds: a finite number of 0 or more. */
267
+ const isWait = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value >= 0;
71
268
 
72
269
  /** The HTTP status an error carries: this module's, or one `getOwner` throws (`http-errors` style). */
73
270
  function statusOf(error: unknown): number | undefined {
@@ -75,51 +272,104 @@ function statusOf(error: unknown): number | undefined {
75
272
  if (!(error instanceof Error)) return undefined;
76
273
  const { status, statusCode } = error as Error & { status?: unknown; statusCode?: unknown };
77
274
  const value = typeof status === "number" ? status : statusCode;
78
- return typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599 ? value : undefined;
275
+ return isErrorStatus(value) ? value : undefined;
79
276
  }
80
277
 
81
278
  /**
82
279
  * The code of a Node system error (a file or network call that failed, as `ENOSPC`). Its message
83
- * names server paths or hosts, so only the code is passed on.
280
+ * names server paths or hosts, so only the code is passed on, and only when it reads as one: a
281
+ * driver may put a host in `code`.
84
282
  */
85
283
  function systemErrorCode(error: unknown): string | undefined {
86
284
  const { code, syscall } = (error ?? {}) as { code?: unknown; syscall?: unknown };
87
- return typeof code === "string" && typeof syscall === "string" ? code : undefined;
285
+ return isErrorCode(code) && typeof syscall === "string" ? code : undefined;
88
286
  }
89
287
 
288
+ /** What the handlers answer a scope that is gone (`DocumentScopeError` "scope_missing"): the chat was deleted. */
289
+ const CHAT_GONE = "This chat no longer exists.";
290
+
90
291
  /**
91
- * The answer to a failed request. An error with a status keeps its status and message. Anything
92
- * else is the server's trouble: a 500 that says what failed and, for a system error, its code.
292
+ * An error as the handlers answer it, `failed` saying what failed ("Upload failed"). See
293
+ * `uploadAnswerOf`. It never throws: an error whose fields throw when read is a 500.
93
294
  */
94
- function answerOf(error: unknown, failed: string, tooLarge: string): { status: number; message: string } {
95
- const status = statusOf(error);
96
- if (status !== undefined) {
97
- return { status, message: status === 413 ? tooLarge : error instanceof Error && error.message ? error.message : `${failed}.` };
295
+ function answerFor(error: unknown, failed: string): UploadAnswer {
296
+ const plain: UploadAnswer = { status: 500, error: `${failed}.` };
297
+ try {
298
+ if (error instanceof HttpError) return { status: error.status, error: error.message || plain.error };
299
+ if (IngestError.is(error)) {
300
+ const status = isErrorStatus(error.status) ? error.status : 422;
301
+ return {
302
+ status,
303
+ // An unreadable file has the words of a parser, or of an extractor of your own, which may
304
+ // name a host: not words for a user (as for errorInfoOf).
305
+ error: error.code === "unreadable" ? UNREADABLE_MESSAGE : typeof error.message === "string" && error.message ? error.message : plain.error,
306
+ code: error.code,
307
+ ...(status === 503 && isWait(error.retryAfterMs) ? { retryAfterMs: error.retryAfterMs } : {}),
308
+ };
309
+ }
310
+ // Its message names what failed and a code, never a path or a host.
311
+ if (DocumentStoreError.is(error)) return { status: 503, error: errorInfoOf(error).message, retryAfterMs: STORE_RETRY_AFTER_MS };
312
+ // A scope the server gave wrong, or did not give, is its own bug: not the client's to fix.
313
+ if (DocumentScopeError.is(error)) return error.code === "scope_missing" ? { status: 404, error: CHAT_GONE } : plain;
314
+ // A model's error (an ingest or a hook of your own that asks one): its status is the provider's,
315
+ // and its message the provider's words, which may name a project or a key.
316
+ if (ModelRequestError.is(error) || errorKindOf(error) !== undefined) {
317
+ const info = errorInfoOf(error);
318
+ if (info.category === "model") return { status: info.status, error: info.message, ...(info.status === 429 || info.status === 503 ? retryOf(info.retryAfterMs) : {}) };
319
+ }
320
+ const status = statusOf(error);
321
+ if (status !== undefined) {
322
+ const message = (error as Error).message;
323
+ return { status, error: typeof message === "string" && message ? message : plain.error, ...(status === 503 ? retryOf((error as { retryAfterMs?: unknown }).retryAfterMs) : {}) };
324
+ }
325
+ const code = systemErrorCode(error);
326
+ return code ? { status: 500, error: `${failed} (${code}).` } : plain;
327
+ } catch {
328
+ return plain;
98
329
  }
99
- const code = systemErrorCode(error);
100
- return { status: 500, message: code ? `${failed} (${code}).` : `${failed}.` };
101
330
  }
102
331
 
103
- /** Answers a failed request with JSON (see `answerOf`). A refusal that says when to try again (a busy reader) sets `Retry-After`. */
104
- function fail(response: ServerResponse, error: unknown, failed: string, tooLarge: string, unread?: IncomingMessage): void {
105
- const { status, message } = answerOf(error, failed, tooLarge);
106
- const retryAfterMs = (error as { retryAfterMs?: unknown } | null)?.retryAfterMs;
107
- if (status === 503 && typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) && !response.headersSent) {
108
- response.setHeader("Retry-After", String(Math.max(1, Math.ceil(retryAfterMs / 1_000))));
109
- }
110
- send(response, status, { error: message }, unread);
332
+ const retryOf = (value: unknown): { retryAfterMs?: number } => (isWait(value) ? { retryAfterMs: value } : {});
333
+
334
+ /**
335
+ * How the upload handler answers an error, for a route of your own that ingests files and should
336
+ * answer as it does:
337
+ * - an `IngestError` (a file that could not be read): its status (422; 413, 409, or 503 for "busy"
338
+ * with its `retryAfterMs`), its message and its `code`. Only an `IngestError` is a 422. An
339
+ * "unreadable" file is told in fixed words, as `errorInfoOf` tells it: its own message is a
340
+ * parser's, or that of an extractor of your own;
341
+ * - a `DocumentStoreError`: 503, its message (which names no path or host), and 5 s to wait;
342
+ * - a `DocumentScopeError` "scope_missing": 404 "This chat no longer exists."; the other codes
343
+ * are the server's mistake: 500 "Upload failed.";
344
+ * - a model's error (`ModelRequestError`): the status and words of `errorInfoOf`, never the
345
+ * provider's own;
346
+ * - any other error with a `status` (or `statusCode`) from 400 to 599: that status and its message;
347
+ * - a Node system error (a `code` and a `syscall`): 500 "Upload failed (ENOSPC).", or "Upload
348
+ * failed." when its code does not read as one (capitals, digits and "_"), as a host does;
349
+ * - anything else: 500 "Upload failed.", without its message, which may name a host.
350
+ *
351
+ * It reads the errors of every copy of the package, and never throws. New in 0.9.0.
352
+ */
353
+ export function uploadAnswerOf(error: unknown): UploadAnswer {
354
+ return answerFor(error, "Upload failed");
111
355
  }
112
356
 
113
357
  /**
114
- * An error of `ingest` as the upload answers it. A file that cannot be read is the client's 422,
115
- * with the reason. An error with a status keeps it, and a system error is the server's 500 with its
116
- * code. A store that failed in another way is the server's 500 too, without its message: that is
117
- * the store's own, and may name a database host. So is a value that is not an Error, whoever threw it.
358
+ * Answers a failed request with JSON (see `answerFor`). A 413 of the handler or of `ingest` gets the
359
+ * size message of the upload. An answer that says when to try again (a busy reader, a store, a
360
+ * model's rate limit) sets `Retry-After`.
118
361
  */
119
- function ingestFailure(error: unknown): unknown {
120
- if (statusOf(error) !== undefined || systemErrorCode(error) !== undefined) return error;
121
- if (isStoreWriteFailure(error) || !(error instanceof Error)) return error;
122
- return new HttpError(422, error.message);
362
+ function fail(response: ServerResponse, error: unknown, failed: string, tooLarge: string, unread?: IncomingMessage): void {
363
+ const answer = answerFor(error, failed);
364
+ if (answer.retryAfterMs !== undefined && !response.headersSent) {
365
+ response.setHeader("Retry-After", String(Math.max(1, Math.ceil(answer.retryAfterMs / 1_000))));
366
+ }
367
+ send(response, answer.status, { error: messageOf(answer, error, tooLarge) }, unread);
368
+ }
369
+
370
+ /** The message of an answer: a 413 of the handler itself, or of `ingest`, says the upload limit. */
371
+ function messageOf(answer: UploadAnswer, error: unknown, tooLarge: string): string {
372
+ return answer.status === 413 && (error instanceof HttpError || IngestError.is(error)) ? tooLarge : answer.error;
123
373
  }
124
374
 
125
375
  /**
@@ -137,26 +387,91 @@ function wantsEvents(request: IncomingMessage): boolean {
137
387
  });
138
388
  }
139
389
 
390
+ /** Starts the ingest of an upload, with the fields of an event stream (`upload`). */
391
+ type StartIngest = (more?: Pick<IngestInput, "runId" | "onEvent" | "signal">) => Promise<DocumentMeta>;
392
+
393
+ /**
394
+ * What `onUploaded` came to for one upload: the fields to add to its answer, or the error to answer
395
+ * with instead (the document then deleted).
396
+ */
397
+ type Hooked = { answer?: Record<string, unknown> } | { failure: unknown };
398
+
399
+ /**
400
+ * An error as `ingest.error` carries it: the message, status and code of the JSON answer, and which
401
+ * of the library's errors it is, so that `errorInfoOf` reads it in the browser as on the server.
402
+ */
403
+ function eventErrorFor(error: unknown, tooLarge: string): EventError {
404
+ const answer = answerFor(error, "Upload failed");
405
+ // A file that could not be read also says why, for a page that tells it in its own words.
406
+ return { message: messageOf(answer, error, tooLarge), status: answer.status, ...identityOf(error), ...(answer.code !== undefined ? { code: answer.code } : {}) };
407
+ }
408
+
409
+ /**
410
+ * The name of a store's failure, of documents that are gone, or of a scope that cannot be used
411
+ * (with its code, which tells a deleted chat apart), and the kind of a model's error (an ingest or
412
+ * a hook of yours that asks one), as `answerFor` answers it, for `EventError`. Nothing for other
413
+ * errors: a refused file is told by its `code`.
414
+ */
415
+ function identityOf(error: unknown): Pick<EventError, "name" | "code" | "kind"> {
416
+ try {
417
+ if (DocumentStoreError.is(error)) return { name: "DocumentStoreError" };
418
+ if (DocumentsNotFoundError.is(error)) return { name: "DocumentsNotFoundError" };
419
+ if (DocumentScopeError.is(error)) return { name: "DocumentScopeError", ...(typeof error.code === "string" ? { code: error.code } : {}) };
420
+ // A model's EventError always has its kind, as in the events of a question.
421
+ if (ModelRequestError.is(error) || errorKindOf(error) !== undefined) {
422
+ const info = errorInfoOf(error);
423
+ if (info.category === "model") return { kind: info.code as ModelErrorKind };
424
+ }
425
+ } catch {
426
+ // A proxy whose traps throw: told plainly.
427
+ }
428
+ return {};
429
+ }
430
+
140
431
  /**
141
432
  * Ingests the upload and answers with its events as Server-Sent Events. The last one is always
142
- * `ingest.finish` or `ingest.error`, even with a `LargeFiles` of your own whose `ingest` sends no events.
433
+ * `ingest.finish` or `ingest.error`, even with a `LargeFiles` of your own whose `ingest` sends no
434
+ * events. `uploaded` runs `onUploaded` once, before `ingest.finish` is sent; or after the stream, for
435
+ * a document stored once the client went away. `start` starts the ingest (see `upload`); `release`
436
+ * is called once the ingest ended, before `onUploaded`.
143
437
  */
144
- async function streamIngest(files: LargeFiles, input: IngestInput, response: ServerResponse, tooLarge: string): Promise<void> {
438
+ async function streamIngest(
439
+ start: StartIngest,
440
+ signal: AbortSignal,
441
+ response: ServerResponse,
442
+ tooLarge: string,
443
+ uploaded: (meta: DocumentMeta) => Promise<Hooked>,
444
+ release: () => void,
445
+ ): Promise<void> {
145
446
  const runId = newRunId("ing");
146
447
  const stream = eventStream<IngestEvent, DocumentMeta>(
147
- (onEvent, signal) => files.ingest({ ...input, runId, onEvent, signal }),
148
- { signal: input.signal },
448
+ (onEvent, stop) => start({ runId, onEvent, signal: stop }),
449
+ { signal },
149
450
  );
451
+ // The ingest ended: its room is given back, while `onUploaded` may still run.
452
+ stream.result.then(release, release);
150
453
  // The error as a JSON answer would give it: the event's own may hold a store's message.
151
454
  const answer = async (fallback: EventError): Promise<EventError> => {
152
455
  try {
153
456
  await stream.result;
154
457
  return { message: fallback.message, ...(fallback.status !== undefined ? { status: fallback.status } : {}) };
155
458
  } catch (error) {
156
- const failure = ingestFailure(error);
157
- // A file that could not be read also says why, for a page that tells it in its own words.
158
- return { ...answerOf(failure, "Upload failed", tooLarge), ...(failure instanceof IngestError ? { code: failure.code } : {}) };
459
+ return eventErrorFor(error, tooLarge);
460
+ }
461
+ };
462
+ /** The last event of a stored document: `ingest.finish` once `onUploaded` is done, or `ingest.error` when it failed. */
463
+ const finished = async (base: { seq: number; runId: string; time: number }, last: (IngestEvent & { type: "ingest.finish" }) | undefined): Promise<IngestEvent> => {
464
+ let meta: DocumentMeta;
465
+ try {
466
+ meta = await stream.result;
467
+ } catch {
468
+ // An ingest of your own that sent ingest.finish, then failed.
469
+ return { ...base, type: "ingest.error", error: await answer({ message: "Upload failed." }) };
159
470
  }
471
+ const hooked = await uploaded(meta);
472
+ if ("failure" in hooked) return { ...base, type: "ingest.error", error: eventErrorFor(hooked.failure, tooLarge) };
473
+ const event: IngestEvent = last ?? { ...base, type: "ingest.finish", document: toDocumentSummary(meta) };
474
+ return hooked.answer ? { ...event, app: hooked.answer } as IngestEvent : event;
160
475
  };
161
476
  async function* events(): AsyncGenerator<IngestEvent> {
162
477
  let seq = 0;
@@ -166,23 +481,24 @@ async function streamIngest(files: LargeFiles, input: IngestInput, response: Ser
166
481
  yield { ...event, error: await answer(event.error) };
167
482
  return;
168
483
  }
484
+ if (event.type === "ingest.finish") {
485
+ yield await finished({ seq: event.seq, runId: event.runId, time: event.time }, event);
486
+ return;
487
+ }
169
488
  yield event;
170
- if (event.type === "ingest.finish") return;
171
489
  }
172
490
  // The ingest ended without a last event: a `LargeFiles` of your own whose ingest sends none.
173
- const base = { seq: seq + 1, runId, time: Date.now() };
174
- try {
175
- yield { ...base, type: "ingest.finish", document: toDocumentSummary(await stream.result) };
176
- } catch {
177
- yield { ...base, type: "ingest.error", error: await answer({ message: "Upload failed." }) };
178
- }
491
+ yield await finished({ seq: seq + 1, runId, time: Date.now() }, undefined);
179
492
  }
180
493
  // Each message is the event itself, as for a question: `ingest.finish` holds the summary a 201
181
494
  // answer would (`document`), `ingest.error` the message and status a JSON answer would (`error`).
182
495
  await writeSseEvents(response, events());
183
496
  // A client that went away ends the stream at once, while the ingest stops (a store write may still
184
- // be under way): the upload is held until then, as on the JSON path.
185
- await stream.result.catch(() => undefined);
497
+ // be under way): the upload is held until then, as on the JSON path. A document stored all the
498
+ // same (the ingest had ended, or an ingest of your own did not stop) still goes to `onUploaded`
499
+ // (with `clientGone`), once.
500
+ const meta = await stream.result.catch(() => undefined);
501
+ if (meta !== undefined) await uploaded(meta);
186
502
  }
187
503
 
188
504
  /**
@@ -200,82 +516,27 @@ function send(response: ServerResponse, status: number, value: unknown, unread?:
200
516
  drain(unread, response);
201
517
  }
202
518
 
203
- function header(request: IncomingMessage, name: string): string {
519
+ /** A header's value as it came (the first, when it came more than once), or "". */
520
+ function rawHeader(request: IncomingMessage, name: string): string {
204
521
  const raw = request.headers[name];
205
522
  const value = Array.isArray(raw) ? raw[0] : raw;
206
- if (!value) return "";
207
- try {
208
- return decodeURIComponent(value);
209
- } catch {
210
- return value;
211
- }
212
- }
213
-
214
- /** The longest a timer can wait. */
215
- const LONGEST_TIMER_MS = 2_147_483_647;
216
-
217
- /** `next`, or a 408 once `idleMs` pass without it. */
218
- function withinIdle<T>(next: Promise<T>, idleMs: number): Promise<T> {
219
- // Once the upload is refused, the read it waited on ends with the connection: nobody awaits it.
220
- next.catch(() => undefined);
221
- let settled = false;
222
- let timer: ReturnType<typeof setTimeout> | undefined;
223
- const idle = new Promise<never>((_, reject) => {
224
- const after = idleMs >= 1_000 ? `${Math.round(idleMs / 1_000)} s` : `${idleMs} ms`;
225
- timer = setTimeout(() => {
226
- // After the thread was held longer than `idleMs`, timers run before the data that came in the
227
- // meantime is read: it is read first, in this turn of the loop, and the upload goes on.
228
- setImmediate(() => {
229
- if (!settled) reject(new HttpError(408, `The upload stopped arriving: nothing came for ${after}. Send it again.`, true));
230
- });
231
- }, idleMs);
232
- });
233
- return Promise.race([next.finally(() => (settled = true)), idle]).finally(() => clearTimeout(timer));
523
+ return value ?? "";
234
524
  }
235
525
 
236
526
  /**
237
- * Reads the raw body, or uses one a framework already parsed into a Buffer (e.g. express.raw()).
238
- * `idleMs`: the longest wait for the next piece of the body (0 for no limit).
527
+ * A header the page URI-encodes (`X-File-Name`, `X-File-Type`), decoded: a value that does not
528
+ * decode is used as it is.
239
529
  */
240
- async function readBody(request: IncomingMessage, limit: number, idleMs = 0): Promise<Uint8Array> {
241
- const parsed = (request as IncomingMessage & { body?: unknown }).body;
242
- if (parsed instanceof Uint8Array) {
243
- if (parsed.byteLength > limit) throw new HttpError(413, "");
244
- return parsed;
245
- }
246
- if (parsed !== undefined && typeof parsed === "object" && parsed !== null && Object.keys(parsed).length) {
247
- 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.");
248
- }
249
- const declared = Number(request.headers["content-length"]);
250
- if (Number.isFinite(declared) && declared > limit) throw new HttpError(413, "");
251
- const chunks: Buffer[] = [];
252
- let size = 0;
253
- // Leaving the loop early must not destroy the request: the rest of the body is drained after
254
- // the answer (see `drain`), which a destroyed request would not do.
255
- const pieces = request.iterator({ destroyOnReturn: false });
256
- const timed = idleMs > 0 && idleMs <= LONGEST_TIMER_MS;
530
+ function header(request: IncomingMessage, name: string): string {
531
+ const value = rawHeader(request, name);
532
+ if (!value) return "";
257
533
  try {
258
- for (;;) {
259
- const next = pieces.next();
260
- const { done, value: chunk } = timed ? await withinIdle(next, idleMs) : await next;
261
- if (done) break;
262
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
263
- size += buffer.byteLength;
264
- if (size > limit) throw new HttpError(413, "");
265
- chunks.push(buffer);
266
- }
267
- } finally {
268
- // As a `for await` does on leaving early; the request is not destroyed (see above).
269
- void pieces.return?.().catch(() => undefined);
534
+ return decodeURIComponent(value);
535
+ } catch {
536
+ return value;
270
537
  }
271
- const body = Buffer.concat(chunks);
272
- return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
273
538
  }
274
539
 
275
- const BUSY = "The server is receiving other files right now. Try again in a moment.";
276
- /** When a client refused for `maxPendingUploadBytes` is told to try again. */
277
- const BUSY_RETRY_MS = 5_000;
278
-
279
540
  /** `uploadIdleTimeoutMs`, checked: a number of 0 or more (0 and Infinity for no limit). */
280
541
  function idleLimit(value: unknown): number {
281
542
  if (value === undefined) return 30_000;
@@ -285,15 +546,71 @@ function idleLimit(value: unknown): number {
285
546
  return value;
286
547
  }
287
548
 
288
- /** `maxPendingUploadBytes`, checked: a number above 0 (Infinity for no limit). */
289
- function pendingLimit(value: unknown, maxUploadBytes: number): number {
290
- if (value === undefined) return 2 * maxUploadBytes;
549
+ /** `maxPendingUploadBytes` or `maxSpooledUploadBytes` (`name`), checked: a number above 0 (Infinity for no limit). */
550
+ function roomLimit(name: string, value: unknown, fallback: number): number {
551
+ if (value === undefined) return fallback;
291
552
  if (typeof value !== "number" || Number.isNaN(value) || value <= 0) {
292
- throw new RangeError(`maxPendingUploadBytes must be a number above 0, and is ${typeof value === "number" ? value : typeof value}. Leave it out for the default.`);
553
+ throw new RangeError(`${name} must be a number above 0, and is ${typeof value === "number" ? value : typeof value}. Leave it out for the default.`);
554
+ }
555
+ return value;
556
+ }
557
+
558
+ /** Where the spool writes bodies, and from which size (`uploadSpool`, checked). */
559
+ type Spool = { directory: string; minBytes: number };
560
+
561
+ /** `uploadSpool`, checked: undefined for no spool. */
562
+ function spoolOf(value: unknown): Spool | undefined {
563
+ if (value === undefined || value === false) return undefined;
564
+ const given: unknown = value === true ? {} : value;
565
+ if (typeof given !== "object" || given === null) throw new TypeError("uploadSpool must be true, false, or { directory?, minBytes? }.");
566
+ const { directory, minBytes } = given as { directory?: unknown; minBytes?: unknown };
567
+ if (directory !== undefined && (typeof directory !== "string" || directory.length === 0 || directory.includes("\0"))) {
568
+ throw new TypeError("uploadSpool.directory must be the path of a folder: a string that is not empty.");
569
+ }
570
+ if (minBytes !== undefined && (typeof minBytes !== "number" || Number.isNaN(minBytes) || minBytes < 0)) {
571
+ 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.`);
572
+ }
573
+ return { directory: path.resolve(directory ?? tmpdir()), minBytes: minBytes ?? 1024 * 1024 };
574
+ }
575
+
576
+ /** `uploadFileMode`, checked: a file mode from 0 to 0o777. */
577
+ function fileModeOf(value: unknown): number {
578
+ if (value === undefined) return 0o600;
579
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 0o777) {
580
+ throw new TypeError("uploadFileMode must be a file mode from 0 to 0o777, such as 0o640.");
293
581
  }
294
582
  return value;
295
583
  }
296
584
 
585
+ const PREPARED_SHAPE = "prepareUpload must return nothing, or { id?, path?, original? }: id a string, path an absolute path, original { ref } with a path.";
586
+
587
+ /**
588
+ * What `prepareUpload` returned, checked (a copy). Null fields are left out, as a database gives
589
+ * them. Anything else is a TypeError, the server's mistake: a 500 "Upload failed.". The rules of
590
+ * `id` and `original.ref` are the library's, checked by `ingest`.
591
+ */
592
+ function preparedOf(value: unknown): PreparedUpload {
593
+ if (value === undefined || value === null) return {};
594
+ if (typeof value !== "object") throw new TypeError(PREPARED_SHAPE);
595
+ const { id, path: at, original } = value as { id?: unknown; path?: unknown; original?: unknown };
596
+ const prepared: PreparedUpload = {};
597
+ if (id !== undefined && id !== null) {
598
+ if (typeof id !== "string") throw new TypeError(PREPARED_SHAPE);
599
+ prepared.id = id;
600
+ }
601
+ if (at !== undefined && at !== null) {
602
+ if (typeof at !== "string" || at.includes("\0") || !path.isAbsolute(at)) throw new TypeError(PREPARED_SHAPE);
603
+ prepared.path = at;
604
+ }
605
+ if (original !== undefined && original !== null) {
606
+ const ref: unknown = typeof original === "object" ? (original as { ref?: unknown }).ref : undefined;
607
+ // A ref names the file the body is saved to: without a path, it would name a file the handler never wrote.
608
+ if (typeof ref !== "string" || prepared.path === undefined) throw new TypeError(PREPARED_SHAPE);
609
+ prepared.original = { ref };
610
+ }
611
+ return prepared;
612
+ }
613
+
297
614
  /**
298
615
  * The bytes an upload will hold: a body a framework already read, its declared `Content-Length`,
299
616
  * or the upload limit when it declares none. Never more than the limit: a larger one is refused
@@ -349,18 +666,94 @@ function drain(request: IncomingMessage, response: ServerResponse): void {
349
666
  */
350
667
  export function createDocumentHandlers(files: LargeFiles, options: DocumentHandlerOptions = {}): DocumentHandlers {
351
668
  const tooLarge = `The file is larger than the ${formatBytes(files.maxUploadBytes)} upload limit.`;
352
- const owner = async (request: IncomingMessage) => options.getOwner?.(request);
353
669
  // The upload limit bounds each body, and the room for all of them: a LargeFiles of your own
354
670
  // without it (from JavaScript) had neither.
355
671
  if (typeof files.maxUploadBytes !== "number" || !(files.maxUploadBytes > 0)) {
356
672
  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.`);
357
673
  }
358
- const maxPending = pendingLimit(options.maxPendingUploadBytes, files.maxUploadBytes);
674
+ for (const name of ["getScope", "prepareUpload", "onUploaded", "onRemoved"] as const) {
675
+ if (options[name] !== undefined && typeof options[name] !== "function") throw new TypeError(`${name} must be a function, and is ${typeof options[name]}.`);
676
+ }
677
+ // A library that requires an owner or a scope on every call cannot be served without them: every
678
+ // request would fail, after its body was read.
679
+ const requireOwner = files.access?.requireOwner === true;
680
+ const requireScope = files.access?.requireScope === true;
681
+ if (requireOwner && typeof options.getOwner !== "function") {
682
+ throw new TypeError("createDocumentHandlers needs getOwner: the library requires an owner on every call (requireOwner).");
683
+ }
684
+ if (requireScope && typeof options.getScope !== "function") {
685
+ throw new TypeError("createDocumentHandlers needs getScope: the library requires a scope on every call (requireScope).");
686
+ }
359
687
  const idleMs = idleLimit(options.uploadIdleTimeoutMs);
360
- /** Whether uploads are counted at all (`maxPendingUploadBytes` is not Infinity). */
361
- const counted = maxPending !== Number.POSITIVE_INFINITY;
362
- /** The bytes of the uploads held now, from the reading of their body to the end of their ingest. */
363
- let pending = 0;
688
+ /** The bodies held in memory, from the reading of each to the end of its ingest (`maxPendingUploadBytes`). */
689
+ const memoryRoom = new Room(roomLimit("maxPendingUploadBytes", options.maxPendingUploadBytes, 2 * files.maxUploadBytes));
690
+ const spool = spoolOf(options.uploadSpool);
691
+ /** The files of the spool, from the writing of each to its removal (`maxSpooledUploadBytes`). */
692
+ const spoolRoom = new Room(roomLimit("maxSpooledUploadBytes", options.maxSpooledUploadBytes, 10 * files.maxUploadBytes));
693
+ const fileMode = fileModeOf(options.uploadFileMode);
694
+
695
+ /**
696
+ * Whether the body of an upload goes to a file of the spool: with `uploadSpool`, one over
697
+ * `minBytes`, or that does not say its size. Not a body a framework already read into memory.
698
+ */
699
+ function spools(declared: number, parsed: Uint8Array | undefined): boolean {
700
+ if (spool === undefined || parsed !== undefined) return false;
701
+ return !(Number.isFinite(declared) && declared >= 0 && declared <= spool.minBytes);
702
+ }
703
+
704
+ /**
705
+ * Who is asking: the owner and the scope of the request, checked, before its body is read. Under
706
+ * `requireOwner`, a request without an owner is answered 401. An owner the library refuses (on
707
+ * the upload, or on every route under `requireOwner`), a scope that is not valid, or none under
708
+ * `requireScope`, is the server's mistake: a 500 that says which, and nothing else. `failed` says
709
+ * what failed ("Upload failed").
710
+ */
711
+ async function callerOf(request: IncomingMessage, failed: string, checkOwnerShape: boolean): Promise<Caller> {
712
+ const owner = await options.getOwner?.(request);
713
+ // No owner, or null (`req.user?.id ?? null` from JavaScript), is a request that is not signed in.
714
+ if (requireOwner && (owner === undefined || owner === null)) throw new HttpError(401, "Sign in first.");
715
+ // An owner that `ingest` would refuse ("", or an object such as `req.user` from JavaScript) is
716
+ // the server's mistake, answered with a 500 before the body is read. Its message says which, so
717
+ // that the operator knows where to look; it says nothing else. (Without `requireOwner`, `get`
718
+ // and `remove` pass it on, as before, so that documents of 0.5.0 with the owner "" stay
719
+ // readable. Under it, the library refuses such an owner on every call: so do they, in the same
720
+ // words as the upload.)
721
+ if (checkOwnerShape || requireOwner) {
722
+ try {
723
+ checkOwner(owner);
724
+ } catch {
725
+ const empty = typeof owner === "string" || owner === null;
726
+ throw new HttpError(500, empty ? `${failed} (empty owner).` : `${failed} (owner is not a string).`);
727
+ }
728
+ }
729
+ const given = options.getScope ? await options.getScope(request) : undefined;
730
+ let scope: DocumentScope | undefined;
731
+ try {
732
+ // Null is no scope, as for the library.
733
+ scope = checkScope(given ?? undefined);
734
+ } catch {
735
+ throw new HttpError(500, `${failed} (invalid scope).`);
736
+ }
737
+ if (requireScope && scope === undefined) throw new HttpError(500, `${failed} (no scope).`);
738
+ return { ...(owner !== undefined ? { owner } : {}), ...(scope !== undefined ? { scope } : {}) };
739
+ }
740
+
741
+ /**
742
+ * Runs `onUploaded` for a stored document. When it throws, or its `answer` is not a plain object
743
+ * that JSON can hold, the document is deleted (a failure to delete is not told: the upload has
744
+ * failed either way) and the error is what the upload answers.
745
+ */
746
+ async function uploaded(meta: DocumentMeta, request: IncomingMessage, caller: Caller, clientGone: boolean, saved: string | undefined): Promise<Hooked> {
747
+ if (!options.onUploaded) return {};
748
+ try {
749
+ const returned: unknown = await options.onUploaded(meta, { request, ...caller, clientGone, ...(saved !== undefined ? { path: saved } : {}) });
750
+ return hookAnswerOf(returned);
751
+ } catch (error) {
752
+ // A delete of your own that throws at once is told no more than one that rejects.
753
+ await Promise.resolve().then(() => files.delete(meta.id, caller)).catch(() => undefined);
754
+ return { failure: error };
755
+ }
756
+ }
364
757
 
365
758
  return {
366
759
  async upload(request, response) {
@@ -368,36 +761,41 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
368
761
  const url = new URL(request.url ?? "/", "http://localhost");
369
762
  const name = header(request, "x-file-name").trim() || url.searchParams.get("name")?.trim() || "";
370
763
  if (!name) throw new HttpError(400, "Name the file with an X-File-Name header or a ?name= query parameter.");
371
- // Who is asking comes first: a refused upload is not read into memory. An owner that
372
- // `ingest` would refuse ("", or an object such as `req.user` from JavaScript) is the server's
373
- // mistake, answered with a 500 before the body is read. Its message says which, so that the
374
- // operator knows where to look; it says nothing else.
375
- const currentOwner = await owner(request);
376
- try {
377
- checkOwner(currentOwner);
378
- } catch {
379
- const empty = typeof currentOwner === "string" || currentOwner === null;
380
- throw new HttpError(500, empty ? "Upload failed (empty owner)." : "Upload failed (owner is not a string).");
381
- }
764
+ // Who is asking comes first: a refused upload is not read into memory.
765
+ const caller = await callerOf(request, "Upload failed", true);
382
766
  // Too large is said first, before any wait for room.
383
767
  const declared = Number(request.headers["content-length"]);
384
- const parsed = (request as IncomingMessage & { body?: unknown }).body;
385
- if ((Number.isFinite(declared) && declared > files.maxUploadBytes) || (parsed instanceof Uint8Array && parsed.byteLength > files.maxUploadBytes)) {
768
+ const parsed = parsedBody(request);
769
+ if ((Number.isFinite(declared) && declared > files.maxUploadBytes) || (parsed !== undefined && parsed.byteLength > files.maxUploadBytes)) {
386
770
  throw new HttpError(413, "");
387
771
  }
388
- // Room for the upload, before its body is read: a refused upload is not buffered. Never
389
- // more than the room itself, so that the count stays a number with an upload limit of Infinity.
390
- let held = counted ? Math.min(expectedSize(request, files.maxUploadBytes), maxPending) : 0;
391
- if (pending > 0 && pending + held > maxPending) throw new IngestError("busy", BUSY, { retryAfterMs: BUSY_RETRY_MS });
392
- pending += held;
772
+ const prepared = options.prepareUpload ? preparedOf(await options.prepareUpload(request, { name: cleanFileName(name), ...caller })) : {};
773
+ // A file `fileOriginals` would not read back by its ref is refused before anything is written.
774
+ if (prepared.path !== undefined && prepared.original !== undefined) await checkRefFolders(prepared.path, prepared.original.ref, idleMs);
775
+ // Where the body is while it is ingested: in the application's file (`prepareUpload`), in a
776
+ // file of the spool, or in memory. Room is taken for it before it is read, so that a refused
777
+ // upload is not read: in the spool, or in memory. The application's file takes none: it is
778
+ // on the application's disk, and stays.
779
+ const spooled = prepared.path === undefined && spools(declared, parsed);
780
+ const held: Held | undefined = prepared.path !== undefined ? undefined : (spooled ? spoolRoom : memoryRoom).take(expectedSize(request, files.maxUploadBytes));
781
+ /** 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. */
782
+ const release = () => held?.release();
783
+ let file: BodyFile | undefined;
393
784
  try {
394
- const bytes = await readBody(request, files.maxUploadBytes, idleMs);
395
- // Counted at its size once read (an upload without a Content-Length was counted at the limit).
396
- if (counted) {
397
- pending += bytes.byteLength - held;
398
- held = bytes.byteLength;
785
+ let body: Uint8Array | undefined;
786
+ if (prepared.path !== undefined || spooled) {
787
+ const at = prepared.path ?? spoolFileIn(spool!.directory);
788
+ const size = await writeBody(request, at, { limit: files.maxUploadBytes, idleMs, mode: prepared.path !== undefined ? fileMode : 0o600 });
789
+ file = new BodyFile(at, prepared.path !== undefined, idleMs);
790
+ held?.resize(size);
791
+ } else {
792
+ body = await readBody(request, files.maxUploadBytes, idleMs);
793
+ // Counted at its size once read (an upload without a Content-Length was counted at the limit).
794
+ held?.resize(body.byteLength);
399
795
  }
400
- const contentType = header(request, "content-type");
796
+ // Content-Type is a header of HTTP, not one the page encodes: it is taken as it came (S11).
797
+ // `ingest` cleans what it keeps of either.
798
+ const contentType = rawHeader(request, "content-type");
401
799
  const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
402
800
  // A client that goes away before the answer stops the reading of its file: nobody would
403
801
  // get the document, and the server has other work.
@@ -406,25 +804,53 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
406
804
  if (!response.writableFinished) gone.abort(new Error("The upload was cancelled: the client closed the connection."));
407
805
  };
408
806
  response.once("close", onClose);
409
- const input: IngestInput = {
410
- name,
411
- bytes,
412
- ...(mimeType ? { mimeType } : {}),
413
- ...(currentOwner !== undefined ? { owner: currentOwner } : {}),
414
- signal: gone.signal,
807
+ // One that left already is told no more: while the last piece of its body was written,
808
+ // or its file closed (where a network volume writes what it held back), or before a body
809
+ // a framework read was taken.
810
+ if (response.destroyed || request.socket?.destroyed) onClose();
811
+ const chosen = { ...(prepared.id !== undefined ? { id: prepared.id } : {}), ...(prepared.original !== undefined ? { original: prepared.original } : {}) };
812
+ /**
813
+ * Starts the upload's ingest, once. A body in memory is then the ingest's alone: it is
814
+ * freed when the ingest ends, while `onUploaded` may still run. The input is built in
815
+ * this function, whose frame ends at once: a value in the frame of `upload`, an async
816
+ * function, is kept until it returns, the hook's wait included. A body in a file is
817
+ * ingested from its path: the file of the spool is removed when the ingest ends, and the
818
+ * application's file when the ingest fails.
819
+ */
820
+ const start: StartIngest = (more) => {
821
+ const input = { name, ...(mimeType ? { mimeType } : {}), ...chosen, ...caller, signal: gone.signal, ...more };
822
+ if (file) return file.settle(files.ingest({ ...input, source: { path: file.path } }));
823
+ const bytes = body!;
824
+ body = undefined;
825
+ return files.ingest({ ...input, bytes });
826
+ };
827
+ // The path is told only for the application's own file: the spool's is gone by then.
828
+ const saved = file?.kept ? file.path : undefined;
829
+ const hook = async (meta: DocumentMeta): Promise<Hooked> => {
830
+ const hooked = await uploaded(meta, request, caller, gone.signal.aborted, saved);
831
+ // The document is deleted: the file saved for it goes too.
832
+ if ("failure" in hooked) await file?.remove();
833
+ return hooked;
415
834
  };
416
- let meta;
417
835
  try {
418
- if (wantsEvents(request)) return await streamIngest(files, input, response, tooLarge);
419
- meta = await files.ingest(input);
420
- } catch (error) {
421
- throw ingestFailure(error);
836
+ if (wantsEvents(request)) {
837
+ // `onUploaded` runs once, for the event before ingest.finish or after the stream.
838
+ let hooking: Promise<Hooked> | undefined;
839
+ return await streamIngest(start, gone.signal, response, tooLarge, (meta) => (hooking ??= hook(meta)), release);
840
+ }
841
+ const meta = await start();
842
+ release();
843
+ const hooked = await hook(meta);
844
+ if ("failure" in hooked) throw hooked.failure;
845
+ // The summary's own fields win over the hook's.
846
+ send(response, 201, { ...hooked.answer, ...toDocumentSummary(meta) });
422
847
  } finally {
423
848
  response.off("close", onClose);
424
849
  }
425
- send(response, 201, toDocumentSummary(meta));
426
850
  } finally {
427
- pending -= held;
851
+ release();
852
+ // Whatever happened: the spool's file is gone, and so is the application's unless its document is stored.
853
+ await file?.end();
428
854
  }
429
855
  } catch (error) {
430
856
  // A body that stopped arriving is not drained: the answer ends, and so does the connection.
@@ -445,8 +871,8 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
445
871
 
446
872
  async get(request, response, id) {
447
873
  try {
448
- const currentOwner = await owner(request);
449
- const meta = await files.getMeta(id, currentOwner !== undefined ? { owner: currentOwner } : {});
874
+ const caller = await callerOf(request, "The file could not be looked up", false);
875
+ const meta = await files.getMeta(id, caller);
450
876
  if (meta) send(response, 200, toDocumentSummary(meta));
451
877
  else send(response, 404, { error: "This file is no longer available." });
452
878
  } catch (error) {
@@ -456,11 +882,32 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
456
882
 
457
883
  async remove(request, response, id) {
458
884
  try {
459
- const currentOwner = await owner(request);
460
- send(response, 200, { deleted: await files.delete(id, currentOwner !== undefined ? { owner: currentOwner } : {}) });
885
+ const caller = await callerOf(request, "The file could not be deleted", false);
886
+ const deleted = await files.delete(id, caller);
887
+ if (deleted && options.onRemoved) await options.onRemoved(id, { request, ...caller });
888
+ send(response, 200, { deleted });
461
889
  } catch (error) {
462
890
  fail(response, error, "The file could not be deleted", tooLarge);
463
891
  }
464
892
  },
465
893
  };
466
894
  }
895
+
896
+ /** The owner and the scope of a request, as `getOwner` and `getScope` gave them, checked. */
897
+ type Caller = AccessOptions;
898
+
899
+ /**
900
+ * What `onUploaded` returned, as the fields to add to the answer: `{ answer }` with a plain object
901
+ * that JSON can hold (a copy of it, as JSON reads it back). Anything else without an `answer` (a
902
+ * database's own result) adds nothing. An `answer` of another kind is a TypeError.
903
+ */
904
+ function hookAnswerOf(returned: unknown): { answer?: Record<string, unknown> } {
905
+ if (typeof returned !== "object" || returned === null) return {};
906
+ const answer: unknown = (returned as { answer?: unknown }).answer;
907
+ if (answer === undefined || answer === null) return {};
908
+ const proto: unknown = typeof answer === "object" ? Object.getPrototypeOf(answer) : undefined;
909
+ if (typeof answer !== "object" || Array.isArray(answer) || (proto !== Object.prototype && proto !== null)) {
910
+ throw new TypeError("onUploaded must return nothing, or { answer } with a plain object that JSON can hold.");
911
+ }
912
+ return { answer: JSON.parse(JSON.stringify(answer)) as Record<string, unknown> };
913
+ }