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