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