llm-large-files 0.8.1 → 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 (204) hide show
  1. package/CHANGELOG.md +631 -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 +176 -34
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +332 -512
  58. package/dist/library.js.map +1 -1
  59. package/dist/limiter.d.ts +2 -2
  60. package/dist/limiter.js +2 -2
  61. package/dist/map-reduce.js +3 -3
  62. package/dist/map-reduce.js.map +1 -1
  63. package/dist/model.d.ts +43 -2
  64. package/dist/model.d.ts.map +1 -1
  65. package/dist/model.js +63 -3
  66. package/dist/model.js.map +1 -1
  67. package/dist/node/handlers.d.ts +234 -7
  68. package/dist/node/handlers.d.ts.map +1 -1
  69. package/dist/node/handlers.js +482 -121
  70. package/dist/node/handlers.js.map +1 -1
  71. package/dist/node/index.d.ts +3 -2
  72. package/dist/node/index.d.ts.map +1 -1
  73. package/dist/node/index.js +2 -1
  74. package/dist/node/index.js.map +1 -1
  75. package/dist/node/ingest-child.d.ts +7 -1
  76. package/dist/node/ingest-child.d.ts.map +1 -1
  77. package/dist/node/ingest-child.js +18 -3
  78. package/dist/node/ingest-child.js.map +1 -1
  79. package/dist/node/isolated.d.ts +3 -1
  80. package/dist/node/isolated.d.ts.map +1 -1
  81. package/dist/node/isolated.js +11 -4
  82. package/dist/node/isolated.js.map +1 -1
  83. package/dist/node/originals.d.ts +19 -0
  84. package/dist/node/originals.d.ts.map +1 -0
  85. package/dist/node/originals.js +82 -0
  86. package/dist/node/originals.js.map +1 -0
  87. package/dist/node/spool.d.ts +102 -0
  88. package/dist/node/spool.d.ts.map +1 -0
  89. package/dist/node/spool.js +365 -0
  90. package/dist/node/spool.js.map +1 -0
  91. package/dist/node/sse.d.ts +4 -3
  92. package/dist/node/sse.d.ts.map +1 -1
  93. package/dist/node/sse.js +7 -6
  94. package/dist/node/sse.js.map +1 -1
  95. package/dist/pdf-layout.d.ts.map +1 -1
  96. package/dist/pdf-layout.js +71 -12
  97. package/dist/pdf-layout.js.map +1 -1
  98. package/dist/ranged.d.ts +22 -11
  99. package/dist/ranged.d.ts.map +1 -1
  100. package/dist/ranged.js +50 -12
  101. package/dist/ranged.js.map +1 -1
  102. package/dist/retry.d.ts +3 -1
  103. package/dist/retry.d.ts.map +1 -1
  104. package/dist/retry.js +6 -2
  105. package/dist/retry.js.map +1 -1
  106. package/dist/scope.d.ts +25 -0
  107. package/dist/scope.d.ts.map +1 -0
  108. package/dist/scope.js +60 -0
  109. package/dist/scope.js.map +1 -0
  110. package/dist/source.d.ts +60 -0
  111. package/dist/source.d.ts.map +1 -0
  112. package/dist/source.js +170 -0
  113. package/dist/source.js.map +1 -0
  114. package/dist/stores.d.ts +120 -31
  115. package/dist/stores.d.ts.map +1 -1
  116. package/dist/stores.js +582 -139
  117. package/dist/stores.js.map +1 -1
  118. package/dist/testing/fake-fetch.d.ts +31 -0
  119. package/dist/testing/fake-fetch.d.ts.map +1 -0
  120. package/dist/testing/fake-fetch.js +66 -0
  121. package/dist/testing/fake-fetch.js.map +1 -0
  122. package/dist/testing/fake-model.d.ts +38 -0
  123. package/dist/testing/fake-model.d.ts.map +1 -0
  124. package/dist/testing/fake-model.js +62 -0
  125. package/dist/testing/fake-model.js.map +1 -0
  126. package/dist/testing/index.d.ts +7 -0
  127. package/dist/testing/index.d.ts.map +1 -0
  128. package/dist/testing/index.js +9 -0
  129. package/dist/testing/index.js.map +1 -0
  130. package/dist/testing/store-checks.d.ts +72 -0
  131. package/dist/testing/store-checks.d.ts.map +1 -0
  132. package/dist/testing/store-checks.js +619 -0
  133. package/dist/testing/store-checks.js.map +1 -0
  134. package/dist/tools.d.ts +25 -0
  135. package/dist/tools.d.ts.map +1 -1
  136. package/dist/tools.js +135 -13
  137. package/dist/tools.js.map +1 -1
  138. package/dist/types.d.ts +116 -13
  139. package/dist/types.d.ts.map +1 -1
  140. package/docs/README.md +17 -8
  141. package/docs/getting-started.md +18 -13
  142. package/docs/guides/anthropic.md +12 -8
  143. package/docs/guides/conversations.md +112 -47
  144. package/docs/guides/costs-and-limits.md +16 -7
  145. package/docs/guides/deployment.md +309 -87
  146. package/docs/guides/errors-and-reliability.md +161 -23
  147. package/docs/guides/own-adapter-and-loop.md +27 -10
  148. package/docs/guides/pdfs.md +123 -29
  149. package/docs/guides/storage.md +634 -143
  150. package/docs/guides/testing.md +78 -129
  151. package/docs/guides/vertex-and-gemini.md +10 -7
  152. package/docs/guides/web-app.md +322 -77
  153. package/docs/how-it-works.md +35 -8
  154. package/docs/measurements.md +63 -8
  155. package/docs/publishing.md +112 -36
  156. package/docs/reference/ask.md +154 -13
  157. package/docs/reference/errors-and-retries.md +166 -14
  158. package/docs/reference/events.md +53 -20
  159. package/docs/reference/gemini.md +70 -21
  160. package/docs/reference/library.md +709 -165
  161. package/docs/reference/node.md +633 -104
  162. package/docs/reference/testing.md +311 -0
  163. package/docs/reference/tools.md +15 -5
  164. package/docs/security.md +316 -70
  165. package/docs/troubleshooting.md +165 -58
  166. package/docs/upgrading-0.9.md +890 -0
  167. package/package.json +12 -3
  168. package/src/access.ts +144 -0
  169. package/src/ask.ts +230 -19
  170. package/src/cache.ts +20 -5
  171. package/src/encoding.ts +6 -4
  172. package/src/error-info.ts +255 -0
  173. package/src/errors.ts +129 -15
  174. package/src/events.ts +86 -21
  175. package/src/evidence.ts +14 -3
  176. package/src/extract.ts +50 -33
  177. package/src/gemini/adapter.ts +97 -11
  178. package/src/gemini/chat.ts +20 -6
  179. package/src/gemini/index.ts +1 -1
  180. package/src/index.ts +9 -6
  181. package/src/ingest.ts +927 -0
  182. package/src/library.ts +482 -523
  183. package/src/limiter.ts +2 -2
  184. package/src/map-reduce.ts +3 -3
  185. package/src/model.ts +69 -5
  186. package/src/node/handlers.ts +691 -117
  187. package/src/node/index.ts +13 -2
  188. package/src/node/ingest-child.ts +23 -5
  189. package/src/node/isolated.ts +11 -4
  190. package/src/node/originals.ts +78 -0
  191. package/src/node/spool.ts +365 -0
  192. package/src/node/sse.ts +7 -6
  193. package/src/pdf-layout.ts +69 -11
  194. package/src/ranged.ts +42 -14
  195. package/src/retry.ts +6 -2
  196. package/src/scope.ts +63 -0
  197. package/src/source.ts +178 -0
  198. package/src/stores.ts +635 -140
  199. package/src/testing/fake-fetch.ts +80 -0
  200. package/src/testing/fake-model.ts +78 -0
  201. package/src/testing/index.ts +11 -0
  202. package/src/testing/store-checks.ts +660 -0
  203. package/src/tools.ts +150 -14
  204. 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,12 +129,107 @@ 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
21
142
  * the upload is read, so a refused upload is not buffered.
22
143
  */
23
144
  getOwner?: (request: IncomingMessage) => string | undefined | Promise<string | undefined>;
145
+ /**
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.
220
+ */
221
+ maxPendingUploadBytes?: number;
222
+ /**
223
+ * An upload whose body stops arriving for this many milliseconds is answered 408, its connection
224
+ * closed and its room given back: a client that sends its headers and then nothing, or stalls,
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.
231
+ */
232
+ uploadIdleTimeoutMs?: number;
24
233
  };
25
234
 
26
235
  /**
@@ -32,26 +241,30 @@ export type DocumentHandlers = {
32
241
  /**
33
242
  * POST: the body is the raw file. Name it with an `X-File-Name` header (URI-encoded) or `?name=`.
34
243
  * A file that cannot be read is answered with a 422 and the reason. A store that fails while it
35
- * 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).
36
247
  *
37
248
  * When the request's `Accept` header names `text/event-stream` (not with `q=0`, nor only through a
38
- * wildcard), a file that passes the checks of the name, the owner and the size (which still
39
- * answer with an HTTP error) is answered with a 200 and Server-Sent Events: the ingest's events (`ingest.start`, `ingest.progress`…), ending
40
- * with `ingest.finish`, whose data is the summary a 201 would hold, or `ingest.error`, whose data
41
- * 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`.
42
256
  */
43
257
  upload(request: IncomingMessage, response: ServerResponse): Promise<void>;
44
- /** 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. */
45
259
  get(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
46
- /** DELETE: removes the document. Responds `{ deleted: boolean }`. */
260
+ /** DELETE: removes the document, then calls `onRemoved`. Responds `{ deleted: boolean }`. */
47
261
  remove(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
48
262
  };
49
263
 
50
- class HttpError extends Error {
51
- constructor(readonly status: number, message: string) {
52
- super(message);
53
- }
54
- }
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;
55
268
 
56
269
  /** The HTTP status an error carries: this module's, or one `getOwner` throws (`http-errors` style). */
57
270
  function statusOf(error: unknown): number | undefined {
@@ -59,51 +272,104 @@ function statusOf(error: unknown): number | undefined {
59
272
  if (!(error instanceof Error)) return undefined;
60
273
  const { status, statusCode } = error as Error & { status?: unknown; statusCode?: unknown };
61
274
  const value = typeof status === "number" ? status : statusCode;
62
- return typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599 ? value : undefined;
275
+ return isErrorStatus(value) ? value : undefined;
63
276
  }
64
277
 
65
278
  /**
66
279
  * The code of a Node system error (a file or network call that failed, as `ENOSPC`). Its message
67
- * 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`.
68
282
  */
69
283
  function systemErrorCode(error: unknown): string | undefined {
70
284
  const { code, syscall } = (error ?? {}) as { code?: unknown; syscall?: unknown };
71
- return typeof code === "string" && typeof syscall === "string" ? code : undefined;
285
+ return isErrorCode(code) && typeof syscall === "string" ? code : undefined;
72
286
  }
73
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
+
74
291
  /**
75
- * The answer to a failed request. An error with a status keeps its status and message. Anything
76
- * 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.
77
294
  */
78
- function answerOf(error: unknown, failed: string, tooLarge: string): { status: number; message: string } {
79
- const status = statusOf(error);
80
- if (status !== undefined) {
81
- 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;
82
329
  }
83
- const code = systemErrorCode(error);
84
- return { status: 500, message: code ? `${failed} (${code}).` : `${failed}.` };
85
330
  }
86
331
 
87
- /** Answers a failed request with JSON (see `answerOf`). A refusal that says when to try again (a busy reader) sets `Retry-After`. */
88
- function fail(response: ServerResponse, error: unknown, failed: string, tooLarge: string, unread?: IncomingMessage): void {
89
- const { status, message } = answerOf(error, failed, tooLarge);
90
- const retryAfterMs = (error as { retryAfterMs?: unknown } | null)?.retryAfterMs;
91
- if (status === 503 && typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) && !response.headersSent) {
92
- response.setHeader("Retry-After", String(Math.max(1, Math.ceil(retryAfterMs / 1_000))));
93
- }
94
- 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");
95
355
  }
96
356
 
97
357
  /**
98
- * An error of `ingest` as the upload answers it. A file that cannot be read is the client's 422,
99
- * with the reason. An error with a status keeps it, and a system error is the server's 500 with its
100
- * code. A store that failed in another way is the server's 500 too, without its message: that is
101
- * 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`.
102
361
  */
103
- function ingestFailure(error: unknown): unknown {
104
- if (statusOf(error) !== undefined || systemErrorCode(error) !== undefined) return error;
105
- if (isStoreWriteFailure(error) || !(error instanceof Error)) return error;
106
- 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;
107
373
  }
108
374
 
109
375
  /**
@@ -121,26 +387,91 @@ function wantsEvents(request: IncomingMessage): boolean {
121
387
  });
122
388
  }
123
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
+
124
431
  /**
125
432
  * Ingests the upload and answers with its events as Server-Sent Events. The last one is always
126
- * `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`.
127
437
  */
128
- 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> {
129
446
  const runId = newRunId("ing");
130
447
  const stream = eventStream<IngestEvent, DocumentMeta>(
131
- (onEvent, signal) => files.ingest({ ...input, runId, onEvent, signal }),
132
- { signal: input.signal },
448
+ (onEvent, stop) => start({ runId, onEvent, signal: stop }),
449
+ { signal },
133
450
  );
451
+ // The ingest ended: its room is given back, while `onUploaded` may still run.
452
+ stream.result.then(release, release);
134
453
  // The error as a JSON answer would give it: the event's own may hold a store's message.
135
454
  const answer = async (fallback: EventError): Promise<EventError> => {
136
455
  try {
137
456
  await stream.result;
138
457
  return { message: fallback.message, ...(fallback.status !== undefined ? { status: fallback.status } : {}) };
139
458
  } catch (error) {
140
- const failure = ingestFailure(error);
141
- // A file that could not be read also says why, for a page that tells it in its own words.
142
- 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." }) };
143
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;
144
475
  };
145
476
  async function* events(): AsyncGenerator<IngestEvent> {
146
477
  let seq = 0;
@@ -150,20 +481,24 @@ async function streamIngest(files: LargeFiles, input: IngestInput, response: Ser
150
481
  yield { ...event, error: await answer(event.error) };
151
482
  return;
152
483
  }
484
+ if (event.type === "ingest.finish") {
485
+ yield await finished({ seq: event.seq, runId: event.runId, time: event.time }, event);
486
+ return;
487
+ }
153
488
  yield event;
154
- if (event.type === "ingest.finish") return;
155
489
  }
156
490
  // The ingest ended without a last event: a `LargeFiles` of your own whose ingest sends none.
157
- const base = { seq: seq + 1, runId, time: Date.now() };
158
- try {
159
- yield { ...base, type: "ingest.finish", document: toDocumentSummary(await stream.result) };
160
- } catch {
161
- yield { ...base, type: "ingest.error", error: await answer({ message: "Upload failed." }) };
162
- }
491
+ yield await finished({ seq: seq + 1, runId, time: Date.now() }, undefined);
163
492
  }
164
493
  // Each message is the event itself, as for a question: `ingest.finish` holds the summary a 201
165
494
  // answer would (`document`), `ingest.error` the message and status a JSON answer would (`error`).
166
495
  await writeSseEvents(response, events());
496
+ // A client that went away ends the stream at once, while the ingest stops (a store write may still
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);
167
502
  }
168
503
 
169
504
  /**
@@ -181,9 +516,19 @@ function send(response: ServerResponse, status: number, value: unknown, unread?:
181
516
  drain(unread, response);
182
517
  }
183
518
 
184
- 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 {
185
521
  const raw = request.headers[name];
186
522
  const value = Array.isArray(raw) ? raw[0] : raw;
523
+ return value ?? "";
524
+ }
525
+
526
+ /**
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.
529
+ */
530
+ function header(request: IncomingMessage, name: string): string {
531
+ const value = rawHeader(request, name);
187
532
  if (!value) return "";
188
533
  try {
189
534
  return decodeURIComponent(value);
@@ -192,30 +537,90 @@ function header(request: IncomingMessage, name: string): string {
192
537
  }
193
538
  }
194
539
 
195
- /** Reads the raw body, or uses one a framework already parsed into a Buffer (e.g. express.raw()). */
196
- async function readBody(request: IncomingMessage, limit: number): Promise<Uint8Array> {
197
- const parsed = (request as IncomingMessage & { body?: unknown }).body;
198
- if (parsed instanceof Uint8Array) {
199
- if (parsed.byteLength > limit) throw new HttpError(413, "");
200
- return parsed;
540
+ /** `uploadIdleTimeoutMs`, checked: a number of 0 or more (0 and Infinity for no limit). */
541
+ function idleLimit(value: unknown): number {
542
+ if (value === undefined) return 30_000;
543
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0) {
544
+ throw new RangeError(`uploadIdleTimeoutMs must be a number of 0 or more, and is ${typeof value === "number" ? value : typeof value}. Leave it out for the default.`);
545
+ }
546
+ return value;
547
+ }
548
+
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;
552
+ if (typeof value !== "number" || Number.isNaN(value) || value <= 0) {
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.`);
201
554
  }
202
- if (parsed !== undefined && typeof parsed === "object" && parsed !== null && Object.keys(parsed).length) {
203
- 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.");
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.");
204
569
  }
205
- const declared = Number(request.headers["content-length"]);
206
- if (Number.isFinite(declared) && declared > limit) throw new HttpError(413, "");
207
- const chunks: Buffer[] = [];
208
- let size = 0;
209
- // Leaving the loop early must not destroy the request: the rest of the body is drained after
210
- // the answer (see `drain`), which a destroyed request would not do.
211
- for await (const chunk of request.iterator({ destroyOnReturn: false })) {
212
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
213
- size += buffer.byteLength;
214
- if (size > limit) throw new HttpError(413, "");
215
- chunks.push(buffer);
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.");
581
+ }
582
+ return value;
583
+ }
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;
216
604
  }
217
- const body = Buffer.concat(chunks);
218
- return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
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
+
614
+ /**
615
+ * The bytes an upload will hold: a body a framework already read, its declared `Content-Length`,
616
+ * or the upload limit when it declares none. Never more than the limit: a larger one is refused
617
+ * when it is read (413).
618
+ */
619
+ function expectedSize(request: IncomingMessage, limit: number): number {
620
+ const parsed = (request as IncomingMessage & { body?: unknown }).body;
621
+ if (parsed instanceof Uint8Array) return Math.min(parsed.byteLength, limit);
622
+ const declared = Number(request.headers["content-length"]);
623
+ return Number.isFinite(declared) && declared >= 0 ? Math.min(declared, limit) : limit;
219
624
  }
220
625
 
221
626
  /**
@@ -261,7 +666,94 @@ function drain(request: IncomingMessage, response: ServerResponse): void {
261
666
  */
262
667
  export function createDocumentHandlers(files: LargeFiles, options: DocumentHandlerOptions = {}): DocumentHandlers {
263
668
  const tooLarge = `The file is larger than the ${formatBytes(files.maxUploadBytes)} upload limit.`;
264
- const owner = async (request: IncomingMessage) => options.getOwner?.(request);
669
+ // The upload limit bounds each body, and the room for all of them: a LargeFiles of your own
670
+ // without it (from JavaScript) had neither.
671
+ if (typeof files.maxUploadBytes !== "number" || !(files.maxUploadBytes > 0)) {
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.`);
673
+ }
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
+ }
687
+ const idleMs = idleLimit(options.uploadIdleTimeoutMs);
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
+ }
265
757
 
266
758
  return {
267
759
  async upload(request, response) {
@@ -269,45 +761,106 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
269
761
  const url = new URL(request.url ?? "/", "http://localhost");
270
762
  const name = header(request, "x-file-name").trim() || url.searchParams.get("name")?.trim() || "";
271
763
  if (!name) throw new HttpError(400, "Name the file with an X-File-Name header or a ?name= query parameter.");
272
- // Who is asking comes first: a refused upload is not read into memory. An owner that
273
- // `ingest` would refuse ("", or an object such as `req.user` from JavaScript) is the server's
274
- // mistake, answered with a 500 before the body is read. Its message says which, so that the
275
- // operator knows where to look; it says nothing else.
276
- const currentOwner = await owner(request);
277
- try {
278
- checkOwner(currentOwner);
279
- } catch {
280
- const empty = typeof currentOwner === "string" || currentOwner === null;
281
- throw new HttpError(500, empty ? "Upload failed (empty owner)." : "Upload failed (owner is not a string).");
764
+ // Who is asking comes first: a refused upload is not read into memory.
765
+ const caller = await callerOf(request, "Upload failed", true);
766
+ // Too large is said first, before any wait for room.
767
+ const declared = Number(request.headers["content-length"]);
768
+ const parsed = parsedBody(request);
769
+ if ((Number.isFinite(declared) && declared > files.maxUploadBytes) || (parsed !== undefined && parsed.byteLength > files.maxUploadBytes)) {
770
+ throw new HttpError(413, "");
282
771
  }
283
- const bytes = await readBody(request, files.maxUploadBytes);
284
- const contentType = header(request, "content-type");
285
- const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
286
- // A client that goes away before the answer stops the reading of its file: nobody would
287
- // get the document, and the server has other work.
288
- const gone = new AbortController();
289
- const onClose = () => {
290
- if (!response.writableFinished) gone.abort(new Error("The upload was cancelled: the client closed the connection."));
291
- };
292
- response.once("close", onClose);
293
- const input: IngestInput = {
294
- name,
295
- bytes,
296
- ...(mimeType ? { mimeType } : {}),
297
- ...(currentOwner !== undefined ? { owner: currentOwner } : {}),
298
- signal: gone.signal,
299
- };
300
- let meta;
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;
301
784
  try {
302
- if (wantsEvents(request)) return await streamIngest(files, input, response, tooLarge);
303
- meta = await files.ingest(input);
304
- } catch (error) {
305
- throw ingestFailure(error);
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);
795
+ }
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");
799
+ const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
800
+ // A client that goes away before the answer stops the reading of its file: nobody would
801
+ // get the document, and the server has other work.
802
+ const gone = new AbortController();
803
+ const onClose = () => {
804
+ if (!response.writableFinished) gone.abort(new Error("The upload was cancelled: the client closed the connection."));
805
+ };
806
+ response.once("close", onClose);
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;
834
+ };
835
+ try {
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) });
847
+ } finally {
848
+ response.off("close", onClose);
849
+ }
306
850
  } finally {
307
- response.off("close", onClose);
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();
308
854
  }
309
- send(response, 201, toDocumentSummary(meta));
310
855
  } catch (error) {
856
+ // A body that stopped arriving is not drained: the answer ends, and so does the connection.
857
+ if (error instanceof HttpError && error.close) {
858
+ if (!response.headersSent) response.setHeader("Connection", "close");
859
+ send(response, error.status, { error: error.message });
860
+ if (response.writableFinished) request.destroy();
861
+ else response.once("finish", () => request.destroy());
862
+ return;
863
+ }
311
864
  // Answered before the body was read to its end (too large, no name): the rest is drained.
312
865
  fail(response, error, "Upload failed", tooLarge, request);
313
866
  // An event stream that failed after its headers were sent cannot answer with a status. (An
@@ -318,8 +871,8 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
318
871
 
319
872
  async get(request, response, id) {
320
873
  try {
321
- const currentOwner = await owner(request);
322
- 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);
323
876
  if (meta) send(response, 200, toDocumentSummary(meta));
324
877
  else send(response, 404, { error: "This file is no longer available." });
325
878
  } catch (error) {
@@ -329,11 +882,32 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
329
882
 
330
883
  async remove(request, response, id) {
331
884
  try {
332
- const currentOwner = await owner(request);
333
- 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 });
334
889
  } catch (error) {
335
890
  fail(response, error, "The file could not be deleted", tooLarge);
336
891
  }
337
892
  },
338
893
  };
339
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
+ }