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
package/dist/stores.js CHANGED
@@ -1,69 +1,175 @@
1
- import { randomUUID } from "node:crypto";
2
- import { mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, mkdir, open, readdir, readFile, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
3
4
  import path from "node:path";
5
+ import { DocumentScopeError } from "./errors.js";
6
+ import { Limiter } from "./limiter.js";
7
+ import { checkScope, MAX_SCOPE_SEGMENTS, scopeKey } from "./scope.js";
8
+ /** The shape of the document IDs the library makes: "doc_" and 32 hex digits. */
4
9
  export const DOCUMENT_ID_PATTERN = /^doc_[a-f0-9]{32}$/;
10
+ /**
11
+ * The shape of a document ID an application may choose (`IngestInput.id`): lowercase letters,
12
+ * digits, "_" and "-", up to 64 characters, starting with a letter or a digit, and not a name
13
+ * Windows keeps for a device (`con`, `prn`, `aux`, `nul`, `com0`-`com9`, `lpt0`-`lpt9`), which
14
+ * cannot name a file there. The IDs the library makes have it too. New in 0.9.0.
15
+ */
16
+ export const APP_DOCUMENT_ID_PATTERN = /^(?!(?:con|prn|aux|nul|com[0-9]|lpt[0-9])$)[a-z0-9][a-z0-9_-]{0,63}$/;
17
+ /**
18
+ * The version of `DocumentMeta` this package writes (`metaVersion`), and the highest it reads.
19
+ * New in 0.9.0: metadata without a version is that of an earlier version, and is read as before.
20
+ */
21
+ export const DOCUMENT_META_VERSION = 1;
5
22
  function expired(meta, now = new Date()) {
6
23
  return Date.parse(meta.expiresAt) <= now.getTime();
7
24
  }
8
- /** Keeps documents in process memory. Good for tests and single-process demos. */
25
+ /**
26
+ * Keeps documents in process memory. Good for tests and single-process demos.
27
+ *
28
+ * The documents of each scope (`DocumentContext.scope`) are kept apart: one ID in two scopes is two
29
+ * documents. Calls without a scope share the documents of no scope, as every call did before 0.9.0.
30
+ */
9
31
  export class MemoryDocumentStore {
32
+ /** The documents of no scope, by ID, as all documents were kept before 0.9.0. */
10
33
  documents = new Map();
34
+ /** The original files of the documents of no scope. */
11
35
  originals = new Map();
36
+ #unscoped = { scope: undefined, documents: this.documents, originals: this.originals };
37
+ /** The documents of each scope, by the key of the scope (`scopeKey`). */
38
+ #scoped = new Map();
12
39
  now;
13
40
  constructor(options = {}) {
14
41
  this.now = options.now ?? (() => new Date());
15
42
  }
43
+ #shelf(context, create = false) {
44
+ const scope = checkScope(context?.scope);
45
+ if (scope === undefined)
46
+ return this.#unscoped;
47
+ const key = scopeKey(scope);
48
+ let shelf = this.#scoped.get(key);
49
+ if (!shelf && create) {
50
+ shelf = { scope, documents: new Map(), originals: new Map() };
51
+ this.#scoped.set(key, shelf);
52
+ }
53
+ return shelf;
54
+ }
16
55
  // The metadata is copied on the way in and on the way out, as a store that writes it somewhere
17
56
  // does: an app that changes the metadata it was handed (deletes its owner before sending it to a
18
57
  // browser) must not change the document's owner or expiry.
19
- async put(document) {
20
- this.documents.set(document.meta.id, { meta: structuredClone(document.meta), text: document.text });
58
+ async put(document, context) {
59
+ this.#shelf(context, true).documents.set(document.meta.id, { meta: structuredClone(document.meta), text: document.text });
21
60
  }
22
- async get(id) {
23
- const document = this.documents.get(id);
61
+ async get(id, context) {
62
+ const document = this.#shelf(context)?.documents.get(id);
24
63
  if (document && expired(document.meta, this.now())) {
25
- await this.delete(id);
64
+ await this.delete(id, context);
26
65
  return undefined;
27
66
  }
28
67
  return document && { meta: structuredClone(document.meta), text: document.text };
29
68
  }
30
- async getMeta(id) {
31
- return (await this.get(id))?.meta;
69
+ async getMeta(id, context) {
70
+ return (await this.get(id, context))?.meta;
32
71
  }
33
- async delete(id) {
34
- this.originals.delete(id);
35
- return this.documents.delete(id);
72
+ async delete(id, context) {
73
+ const shelf = this.#shelf(context);
74
+ if (!shelf)
75
+ return false;
76
+ shelf.originals.delete(id);
77
+ const existed = shelf.documents.delete(id);
78
+ // A scope with nothing left takes no memory: one for each chat would add up.
79
+ if (shelf !== this.#unscoped && shelf.documents.size === 0 && shelf.originals.size === 0)
80
+ this.#scoped.delete(scopeKey(shelf.scope));
81
+ return existed;
36
82
  }
37
- async sweep(now = this.now()) {
83
+ /** Removes expired documents: those of the scope of `context`, or those of every scope when it has none. */
84
+ async sweep(now = this.now(), context) {
85
+ const shelves = context?.scope === undefined ? [this.#unscoped, ...this.#scoped.values()] : [this.#shelf(context)];
38
86
  let removed = 0;
39
- for (const [id, document] of this.documents) {
40
- if (expired(document.meta, now)) {
41
- await this.delete(id);
42
- removed++;
87
+ for (const shelf of shelves) {
88
+ if (!shelf)
89
+ continue;
90
+ for (const [id, document] of shelf.documents) {
91
+ if (expired(document.meta, now)) {
92
+ await this.delete(id, shelf.scope === undefined ? undefined : { scope: shelf.scope });
93
+ removed++;
94
+ }
43
95
  }
44
96
  }
45
97
  return removed;
46
98
  }
47
- async putOriginal(id, bytes) {
99
+ async putOriginal(id, bytes, context) {
48
100
  // A copy: the caller may reuse its buffer after the upload.
49
- this.originals.set(id, bytes.slice());
101
+ this.#shelf(context, true).originals.set(id, bytes.slice());
50
102
  }
51
- async getOriginal(id) {
52
- return await this.get(id) ? this.originals.get(id) : undefined;
103
+ async getOriginal(id, context) {
104
+ // A copy too, new in 0.9.0: a caller that changed the bytes it was handed changed the stored file.
105
+ return await this.get(id, context) ? this.#shelf(context)?.originals.get(id)?.slice() : undefined;
53
106
  }
54
107
  }
55
- /** The files of a document, and the temporary files written on the way to them. */
56
- const FILE_NAME = /^(doc_[a-f0-9]{32})\.(json|txt|bin|idx)(\.[a-f0-9]{8}\.tmp)?$/;
57
108
  /**
58
- * Errors a rename can meet on Windows while another process (a reader, an antivirus scanner) has
59
- * the file open for a moment. Retried with growing pauses for up to about three seconds, as
60
- * graceful-fs does.
109
+ * The files of a document, and the temporary files written on the way to them. Since 0.9.0 the ID
110
+ * may be an application's (`APP_DOCUMENT_ID_PATTERN`), which the IDs the library makes fit too.
111
+ */
112
+ const FILE_NAME = /^([a-z0-9][a-z0-9_-]{0,63})\.(json|txt|bin|idx)(\.[a-f0-9]{8}\.tmp)?$/;
113
+ /**
114
+ * Names Windows keeps for devices, with or without an extension: `con.json` is the console, not a
115
+ * file. Refused as scope segments and as file names, since a volume may be shared with Windows.
116
+ */
117
+ const DEVICE_NAME = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/;
118
+ /** A name of one folder of a scope (`isSafeScopeSegment`): the shape of an application's document ID. */
119
+ const SAFE_SEGMENT = /^[a-z0-9][a-z0-9_-]{0,63}$/;
120
+ /** A name of the store's own folder in each scope's folder (`scopes.folder`). */
121
+ const FOLDER_NAME = /^[A-Za-z0-9._-]{1,64}$/;
122
+ /**
123
+ * Errors a rename or a removal can meet on Windows while another process (a reader, an antivirus
124
+ * scanner) has the file open for a moment. Tried again after each of these pauses, as graceful-fs
125
+ * does: ten more tries, and 2,630 ms of pauses in all, so about 2.6 seconds.
61
126
  */
62
- const RETRY_RENAME = new Set(["EPERM", "EACCES", "EBUSY"]);
63
- const RENAME_PAUSES_MS = [10, 20, 40, 80, 160, 320, 500, 500, 500, 500];
127
+ const RETRY_CODES = new Set(["EPERM", "EACCES", "EBUSY"]);
128
+ const RETRY_PAUSES_MS = [10, 20, 40, 80, 160, 320, 500, 500, 500, 500];
64
129
  const code = (error) => error?.code;
65
130
  /** There is no such file. Every other failure (a volume that does not answer, too many open files) says nothing about the file. */
66
131
  const missing = (error) => code(error) === "ENOENT";
132
+ /** There is no such file or folder, or a part of its path is a file. */
133
+ const absent = (error) => code(error) === "ENOENT" || code(error) === "ENOTDIR";
134
+ /** The file is a link, which a read does not follow (READ_FLAGS): Linux and macOS say ELOOP, FreeBSD EMLINK. */
135
+ const linked = (error) => code(error) === "ELOOP" || code(error) === "EMLINK";
136
+ /**
137
+ * How a document's file is opened for reading: without following a link at its name, where the
138
+ * platform can (`O_NOFOLLOW`; Windows has none). Folders are checked by their real path instead.
139
+ */
140
+ const READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0);
141
+ /** The refusal of a folder of a scope that is a link, or under one. */
142
+ const LINKED_FOLDER = "The folder of the scope is a link, or inside one: this store follows no folder links below its directory.";
143
+ /**
144
+ * How long a read takes a folder of a scope that passed its check as still checked, and how many
145
+ * such folders a store remembers. Writes, deletes and removals always check again.
146
+ */
147
+ const CHECK_KEPT_MS = 1_000;
148
+ const CHECKS_KEPT = 4_096;
149
+ /**
150
+ * Whether `value` can name a folder of a scope in a `FileDocumentStore` with `scopes`: lowercase
151
+ * letters, digits, "_" and "-", 1 to 64 characters, starting with a letter or a digit, and not a
152
+ * name Windows keeps for a device (`con`, `prn`, `aux`, `nul`, `com0`-`com9`, `lpt0`-`lpt9`). Lower
153
+ * case only, because SMB and Azure Files ignore case: `Alice` and `alice` would be one folder. Use
154
+ * `hashedScopeSegment` for an ID that does not pass. New in 0.9.0.
155
+ */
156
+ export function isSafeScopeSegment(value) {
157
+ return typeof value === "string" && SAFE_SEGMENT.test(value) && !DEVICE_NAME.test(value);
158
+ }
159
+ /**
160
+ * A segment that `isSafeScopeSegment` accepts, made from any string: "h" and the first 40 hex
161
+ * digits of its SHA-256. For user or chat IDs in mixed case, or in Hebrew. The same value always
162
+ * gives the same segment, and two values almost surely two. Use it for every value of that level of
163
+ * the scope, not only for those that would not pass, and pass the result as the scope's segment:
164
+ * the store never hashes on its own. New in 0.9.0.
165
+ */
166
+ export function hashedScopeSegment(value) {
167
+ if (typeof value !== "string" || value.length === 0)
168
+ throw new TypeError("hashedScopeSegment needs a string that is not empty.");
169
+ return `h${createHash("sha256").update(value, "utf8").digest("hex").slice(0, 40)}`;
170
+ }
171
+ /** An ID that may become a file name: an application's ID shape, and not a device name. */
172
+ const fileId = (id) => typeof id === "string" && APP_DOCUMENT_ID_PATTERN.test(id) && !DEVICE_NAME.test(id);
67
173
  /** Metadata as it was written, or undefined for text that is not that: cut short, or damaged. */
68
174
  function parseMeta(raw) {
69
175
  try {
@@ -74,35 +180,110 @@ function parseMeta(raw) {
74
180
  return undefined;
75
181
  }
76
182
  }
183
+ /** Runs `task`, and again after each pause of RETRY_PAUSES_MS while it fails with a code of RETRY_CODES. */
184
+ async function retried(task) {
185
+ for (let attempt = 0;; attempt++) {
186
+ try {
187
+ return await task();
188
+ }
189
+ catch (error) {
190
+ if (attempt >= RETRY_PAUSES_MS.length || !RETRY_CODES.has(code(error)))
191
+ throw error;
192
+ await new Promise((resolve) => setTimeout(resolve, RETRY_PAUSES_MS[attempt]));
193
+ }
194
+ }
195
+ }
77
196
  /**
78
- * Writes a file whole or not at all, as other processes see it: to a temporary name first, then
79
- * renamed. A server reading a shared volume never sees half of a file another server is writing.
197
+ * Removes a file, trying again as a rename is (Node's own `rm` retries neither `EACCES` nor a file
198
+ * without `recursive`). True when it was there, false when it was not.
80
199
  */
81
- async function writeWhole(target, data) {
82
- const temporary = `${target}.${randomUUID().slice(0, 8)}.tmp`;
200
+ async function removeFile(file) {
83
201
  try {
84
- await writeFile(temporary, data);
85
- for (let attempt = 0;; attempt++) {
86
- try {
87
- await rename(temporary, target);
88
- return;
89
- }
90
- catch (error) {
91
- if (attempt >= RENAME_PAUSES_MS.length || !RETRY_RENAME.has(code(error)))
92
- throw error;
93
- await new Promise((resolve) => setTimeout(resolve, RENAME_PAUSES_MS[attempt]));
202
+ await retried(() => unlink(file));
203
+ return true;
204
+ }
205
+ catch (error) {
206
+ if (missing(error))
207
+ return false;
208
+ throw error;
209
+ }
210
+ }
211
+ /** A temporary name of the store for `target`: `<name>.<8 hex>.tmp`, which `sweep` removes once it is old. */
212
+ const temporaryOf = (target) => `${target}.${randomUUID().slice(0, 8)}.tmp`;
213
+ /**
214
+ * A text longer than this, in UTF-16 units, is written a slice of this many at a time, so that no
215
+ * one turn of the event loop encodes it all: a text of 97.5 MB, encoded at once, held the thread
216
+ * for a second. New in 0.10.0.
217
+ */
218
+ export const WRITE_SLICE_CHARACTERS = 1024 * 1024;
219
+ /**
220
+ * Writes `text` to `file`, new, in UTF-8: in slices of `WRITE_SLICE_CHARACTERS`, each cut before a
221
+ * high surrogate rather than after it, so that no character is cut in two and the bytes are those
222
+ * of the whole text encoded at once.
223
+ */
224
+ async function writeSlices(file, text, mode) {
225
+ const handle = await open(file, "w", mode);
226
+ try {
227
+ for (let at = 0; at < text.length;) {
228
+ let end = Math.min(at + WRITE_SLICE_CHARACTERS, text.length);
229
+ const last = text.charCodeAt(end - 1);
230
+ if (end < text.length && last >= 0xd800 && last <= 0xdbff)
231
+ end--;
232
+ const bytes = Buffer.from(text.slice(at, end), "utf8");
233
+ for (let written = 0; written < bytes.byteLength;) {
234
+ const { bytesWritten } = await handle.write(bytes, written, bytes.byteLength - written);
235
+ if (bytesWritten <= 0)
236
+ throw Object.assign(new Error("The text could not be written."), { code: "EIO", syscall: "write" });
237
+ written += bytesWritten;
94
238
  }
239
+ at = end;
95
240
  }
96
241
  }
242
+ finally {
243
+ await handle.close();
244
+ }
245
+ }
246
+ /**
247
+ * Writes a file whole or not at all, as other processes see it: to a temporary name first, then
248
+ * renamed. A server reading a shared volume never sees half of a file another server is writing.
249
+ * The temporary file is made with `mode`, and the rename keeps it. A text longer than
250
+ * `WRITE_SLICE_CHARACTERS` is written in slices (0.10.0).
251
+ */
252
+ async function writeWhole(target, data, mode) {
253
+ const temporary = temporaryOf(target);
254
+ try {
255
+ if (typeof data === "string" && data.length > WRITE_SLICE_CHARACTERS)
256
+ await writeSlices(temporary, data, mode);
257
+ else
258
+ await writeFile(temporary, data, { mode });
259
+ await retried(() => rename(temporary, target));
260
+ }
97
261
  catch (error) {
98
262
  await rm(temporary, { force: true }).catch(() => undefined);
99
263
  throw error;
100
264
  }
101
265
  }
266
+ /** The files of a document in `folder`. */
267
+ function filesOf(folder, id) {
268
+ const file = (extension) => path.join(folder, `${id}.${extension}`);
269
+ return { text: file("txt"), meta: file("json"), original: file("bin"), index: file("idx") };
270
+ }
271
+ function checkMode(name, value, fallback) {
272
+ if (value === undefined)
273
+ return fallback;
274
+ if (!Number.isInteger(value) || value < 0 || value > 0o777)
275
+ throw new TypeError(`${name} must be a file mode from 0 to 0o777, such as 0o640.`);
276
+ return value;
277
+ }
102
278
  /**
103
279
  * Keeps each document as `<id>.txt` plus `<id>.json` in one directory, so files survive a
104
280
  * server restart, its line index as `<id>.idx`, and its original file as `<id>.bin` when one is
105
- * kept. Only IDs matching DOCUMENT_ID_PATTERN ever reach the file system.
281
+ * kept. Only IDs matching APP_DOCUMENT_ID_PATTERN (which leaves out names Windows keeps for
282
+ * devices) ever reach the file system. Those names, for every ID it is given, are the store's: keep
283
+ * files of your own in a subfolder. A read does not follow a link at a file name, except on Windows.
284
+ *
285
+ * With `scopes`, the documents of each scope are kept in a folder of their own:
286
+ * `<directory>/<userId>/<chatId>/.llm-large-files/<id>.json`. New in 0.9.0.
106
287
  *
107
288
  * Several servers may share the directory (a network volume): every file is written whole under
108
289
  * a temporary name and then renamed, a tool call reads only the lines it needs (`readTextRange`),
@@ -112,38 +293,235 @@ export class FileDocumentStore {
112
293
  directory;
113
294
  now;
114
295
  orphanAgeMs;
296
+ #scopes;
297
+ #fileMode;
298
+ #directoryMode;
299
+ #sweepConcurrency;
300
+ /** The directory, with links resolved, once it was found. */
301
+ #realDirectory;
302
+ /** The folders of scopes that passed `#checkReal`, and when (`Date.now()`), the oldest first. */
303
+ #checked = new Map();
115
304
  constructor(directory, options = {}) {
116
305
  this.directory = directory;
117
306
  this.now = options.now ?? (() => new Date());
118
307
  this.orphanAgeMs = options.orphanAgeMs ?? 60 * 60 * 1000;
308
+ this.#fileMode = checkMode("fileMode", options.fileMode, 0o600);
309
+ this.#directoryMode = checkMode("directoryMode", options.directoryMode, 0o700);
310
+ const concurrency = options.sweepConcurrency ?? 16;
311
+ if (!Number.isInteger(concurrency) || concurrency < 1)
312
+ throw new TypeError("sweepConcurrency must be a whole number of 1 or more.");
313
+ this.#sweepConcurrency = concurrency;
314
+ const scopes = options.scopes;
315
+ if (scopes === undefined) {
316
+ this.#scopes = undefined;
317
+ return;
318
+ }
319
+ if (!Number.isInteger(scopes.depth) || scopes.depth < 1 || scopes.depth > MAX_SCOPE_SEGMENTS) {
320
+ throw new TypeError(`scopes.depth must be a whole number from 1 to ${MAX_SCOPE_SEGMENTS}.`);
321
+ }
322
+ const folder = scopes.folder ?? ".llm-large-files";
323
+ if (folder !== "" && (!FOLDER_NAME.test(folder) || folder === "." || folder === "..")) {
324
+ throw new TypeError('scopes.folder must be "" or the name of one folder: letters, digits, ".", "_" and "-", such as ".llm-large-files".');
325
+ }
326
+ const unscoped = scopes.unscoped ?? "refuse";
327
+ if (unscoped !== "refuse" && unscoped !== "root")
328
+ throw new TypeError('scopes.unscoped must be "refuse" or "root".');
329
+ this.#scopes = { depth: scopes.depth, folder, createScopeFolders: scopes.createScopeFolders === true, unscoped };
119
330
  }
120
- paths(id) {
121
- if (!DOCUMENT_ID_PATTERN.test(id))
122
- return undefined;
123
- const file = (extension) => path.join(this.directory, `${id}.${extension}`);
124
- return { text: file("txt"), meta: file("json"), original: file("bin"), index: file("idx") };
331
+ /** The scope of a call, checked against the rules of this store, or undefined for none. */
332
+ #scopeOf(context) {
333
+ const scope = checkScope(context?.scope);
334
+ if (scope === undefined || this.#scopes === undefined)
335
+ return scope;
336
+ if (scope.length !== this.#scopes.depth) {
337
+ throw new DocumentScopeError("scope_invalid", `This store keeps scopes of ${this.#scopes.depth} segments (scopes.depth); the scope has ${scope.length}.`);
338
+ }
339
+ scope.forEach((segment, index) => {
340
+ if (!isSafeScopeSegment(segment)) {
341
+ throw new DocumentScopeError("scope_invalid", `scope segment ${index + 1} cannot name a folder: use lowercase letters, digits, "_" and "-", up to 64 characters, and no name Windows keeps for a device (isSafeScopeSegment), or hashedScopeSegment(value).`);
342
+ }
343
+ });
344
+ return scope;
345
+ }
346
+ /** The directory itself: that of a store without scopes, or of a call without a scope under `unscoped: "root"`. */
347
+ #root() {
348
+ if (this.#scopes && this.#scopes.unscoped !== "root")
349
+ throw new DocumentScopeError("scope_required");
350
+ return { folder: this.directory, shared: true, scoped: false };
125
351
  }
126
- async put(document) {
127
- const paths = this.paths(document.meta.id);
128
- if (!paths)
352
+ /** The folder of a scope, and that of the store in it. */
353
+ #folders(scope) {
354
+ const scopeFolder = path.join(this.directory, ...scope);
355
+ return { scope: scopeFolder, documents: this.#scopes.folder ? path.join(scopeFolder, this.#scopes.folder) : scopeFolder };
356
+ }
357
+ /**
358
+ * Checks that `folder` is where its path says, with no link on the way below the directory, and
359
+ * so inside the directory. Throws its error when it is not there. A folder that passes is
360
+ * remembered for CHECK_KEPT_MS, for reads (`#find`); one that fails is forgotten.
361
+ */
362
+ async #checkReal(folder) {
363
+ try {
364
+ const real = await realpath(folder);
365
+ this.#realDirectory ??= realpath(this.directory);
366
+ let directory;
367
+ try {
368
+ directory = await this.#realDirectory;
369
+ }
370
+ catch (error) {
371
+ this.#realDirectory = undefined;
372
+ throw error;
373
+ }
374
+ if (real !== path.join(directory, path.relative(this.directory, folder)))
375
+ throw new DocumentScopeError("scope_invalid", LINKED_FOLDER);
376
+ }
377
+ catch (error) {
378
+ this.#checked.delete(folder);
379
+ throw error;
380
+ }
381
+ this.#checked.delete(folder);
382
+ this.#checked.set(folder, Date.now());
383
+ if (this.#checked.size > CHECKS_KEPT)
384
+ this.#checked.delete(this.#checked.keys().next().value);
385
+ }
386
+ /** Whether `folder` passed `#checkReal` less than CHECK_KEPT_MS ago. A clock set back counts as not. */
387
+ #checkedRecently(folder) {
388
+ const at = this.#checked.get(folder);
389
+ if (at === undefined)
390
+ return false;
391
+ const age = Date.now() - at;
392
+ if (age >= 0 && age < CHECK_KEPT_MS)
393
+ return true;
394
+ this.#checked.delete(folder);
395
+ return false;
396
+ }
397
+ /**
398
+ * Whether a read's error means that the file is not there to read: missing, or a link, which is
399
+ * not followed. A file that is missing makes the next call check its folder again.
400
+ */
401
+ #unreadable(place, error) {
402
+ if (absent(error)) {
403
+ if (place.scoped)
404
+ this.#checked.delete(place.folder);
405
+ return true;
406
+ }
407
+ return linked(error);
408
+ }
409
+ /**
410
+ * The folder of the documents of a call, or undefined when it is not there, and so neither are
411
+ * they. A read (`fresh` false) takes a folder checked less than CHECK_KEPT_MS ago as it was; a
412
+ * delete or a sweep checks it again.
413
+ */
414
+ async #find(context, fresh = false) {
415
+ if (!this.#scopes)
416
+ return { folder: this.directory, shared: true, scoped: false };
417
+ const scope = this.#scopeOf(context);
418
+ if (scope === undefined)
419
+ return this.#root();
420
+ const folders = this.#folders(scope);
421
+ if (fresh || !this.#checkedRecently(folders.documents)) {
422
+ try {
423
+ await this.#checkReal(folders.documents);
424
+ }
425
+ catch (error) {
426
+ if (absent(error))
427
+ return undefined;
428
+ throw error;
429
+ }
430
+ }
431
+ return { folder: folders.documents, shared: this.#scopes.folder === "", scoped: true };
432
+ }
433
+ /**
434
+ * Makes the folders of a scope (`createScopeFolders`) one level at a time. Each is made, or found,
435
+ * as a folder and not a link before the next is made in it, so nothing is made where a link
436
+ * points. A file where a folder should be stops it: the check that follows finds the scope missing.
437
+ */
438
+ async #makeScopeFolders(scope) {
439
+ await mkdir(this.directory, { recursive: true, mode: this.#directoryMode });
440
+ let level = this.directory;
441
+ for (const segment of scope) {
442
+ level = path.join(level, segment);
443
+ await mkdir(level, { mode: this.#directoryMode }).catch((error) => {
444
+ if (code(error) !== "EEXIST")
445
+ throw error;
446
+ });
447
+ const info = await lstat(level);
448
+ if (info.isSymbolicLink())
449
+ throw new DocumentScopeError("scope_invalid", LINKED_FOLDER);
450
+ if (!info.isDirectory())
451
+ return;
452
+ }
453
+ }
454
+ /** The folder of the documents of a call, made when it is not there yet. */
455
+ async #make(context) {
456
+ const scope = this.#scopes ? this.#scopeOf(context) : undefined;
457
+ if (scope === undefined) {
458
+ const place = this.#scopes ? this.#root() : { folder: this.directory, shared: true, scoped: false };
459
+ await mkdir(this.directory, { recursive: true, mode: this.#directoryMode });
460
+ return place;
461
+ }
462
+ const scopes = this.#scopes;
463
+ const folders = this.#folders(scope);
464
+ const place = { folder: folders.documents, shared: scopes.folder === "", scoped: true };
465
+ try {
466
+ await this.#checkReal(folders.documents);
467
+ return place;
468
+ }
469
+ catch (error) {
470
+ if (!absent(error))
471
+ throw error;
472
+ }
473
+ try {
474
+ // Made only when asked to: the application may have removed the folder of a chat it deleted.
475
+ if (scopes.createScopeFolders)
476
+ await this.#makeScopeFolders(scope);
477
+ await this.#checkReal(folders.scope);
478
+ if (folders.documents !== folders.scope) {
479
+ // Not recursive: if the scope's folder went in the meantime, it is not made again.
480
+ await mkdir(folders.documents, { mode: this.#directoryMode }).catch((error) => {
481
+ if (code(error) !== "EEXIST")
482
+ throw error;
483
+ });
484
+ await this.#checkReal(folders.documents);
485
+ }
486
+ }
487
+ catch (error) {
488
+ if (absent(error))
489
+ throw new DocumentScopeError("scope_missing", undefined, { cause: error });
490
+ throw error;
491
+ }
492
+ return place;
493
+ }
494
+ /** Writes one file of a document whole. A scope's folder that went while it was written is "scope_missing". */
495
+ async #write(place, target, data) {
496
+ try {
497
+ await writeWhole(target, data, this.#fileMode);
498
+ }
499
+ catch (error) {
500
+ if (place.scoped && absent(error))
501
+ throw new DocumentScopeError("scope_missing", undefined, { cause: error });
502
+ throw error;
503
+ }
504
+ }
505
+ async put(document, context) {
506
+ if (!fileId(document.meta.id))
129
507
  throw new Error("Invalid document ID.");
130
- await mkdir(this.directory, { recursive: true });
131
- await writeWhole(paths.text, document.text);
508
+ const place = await this.#make(context);
509
+ const files = filesOf(place.folder, document.meta.id);
510
+ await this.#write(place, files.text, document.text);
132
511
  // Write metadata last: a document without metadata is treated as absent.
133
- await writeWhole(paths.meta, JSON.stringify(document.meta));
512
+ await this.#write(place, files.meta, JSON.stringify(document.meta));
134
513
  }
135
- async getMeta(id) {
136
- const paths = this.paths(id);
137
- if (!paths)
138
- return undefined;
514
+ /** The metadata of a document in `place`, or undefined. An expired one is removed, as far as that works. */
515
+ async #meta(place, id) {
139
516
  let raw;
140
517
  try {
141
- raw = await readFile(paths.meta, "utf8");
518
+ raw = await readFile(filesOf(place.folder, id).meta, { encoding: "utf8", flag: READ_FLAGS });
142
519
  }
143
520
  catch (error) {
144
- // Only a file that is not there means that the document is not there. A read that failed for
145
- // another reason is thrown, so that a busy volume is not taken for a deleted document.
146
- if (missing(error))
521
+ // Only a file that is not there (or a link, not followed) means that the document is not
522
+ // there. A read that failed for another reason is thrown, so that a busy volume is not taken
523
+ // for a deleted document.
524
+ if (this.#unreadable(place, error))
147
525
  return undefined;
148
526
  throw error;
149
527
  }
@@ -152,35 +530,49 @@ export class FileDocumentStore {
152
530
  if (!meta)
153
531
  return undefined;
154
532
  if (expired(meta, this.now())) {
155
- await this.delete(id);
533
+ // Expired is missing, whether or not its files could be removed now: sweep tries again. The
534
+ // folder is checked again first: a read may have taken it as checked a moment ago.
535
+ await (place.scoped ? this.#checkReal(place.folder) : Promise.resolve())
536
+ .then(() => this.#remove(place, id))
537
+ .catch(() => undefined);
156
538
  return undefined;
157
539
  }
158
540
  return meta;
159
541
  }
160
- async get(id) {
161
- const meta = await this.getMeta(id);
162
- const paths = this.paths(id);
163
- if (!meta || !paths)
542
+ async getMeta(id, context) {
543
+ if (!fileId(id))
544
+ return undefined;
545
+ const place = await this.#find(context);
546
+ return place && this.#meta(place, id);
547
+ }
548
+ async get(id, context) {
549
+ if (!fileId(id))
550
+ return undefined;
551
+ const place = await this.#find(context);
552
+ const meta = place && await this.#meta(place, id);
553
+ if (!place || !meta)
164
554
  return undefined;
165
555
  try {
166
- return { meta, text: await readFile(paths.text, "utf8") };
556
+ return { meta, text: await readFile(filesOf(place.folder, id).text, { encoding: "utf8", flag: READ_FLAGS }) };
167
557
  }
168
558
  catch (error) {
169
- if (missing(error))
559
+ if (this.#unreadable(place, error))
170
560
  return undefined;
171
561
  throw error;
172
562
  }
173
563
  }
174
- async readTextRange(id, start, end) {
175
- const paths = this.paths(id);
176
- if (!paths)
564
+ async readTextRange(id, start, end, context) {
565
+ if (!fileId(id))
566
+ return undefined;
567
+ const place = await this.#find(context);
568
+ if (!place)
177
569
  return undefined;
178
570
  let handle;
179
571
  try {
180
- handle = await open(paths.text, "r");
572
+ handle = await open(filesOf(place.folder, id).text, READ_FLAGS);
181
573
  }
182
574
  catch (error) {
183
- if (code(error) === "ENOENT")
575
+ if (this.#unreadable(place, error))
184
576
  return undefined;
185
577
  throw error;
186
578
  }
@@ -200,62 +592,98 @@ export class FileDocumentStore {
200
592
  await handle.close();
201
593
  }
202
594
  }
203
- async putIndex(id, index) {
204
- const paths = this.paths(id);
205
- if (!paths)
595
+ async putIndex(id, index, context) {
596
+ if (!fileId(id))
206
597
  throw new Error("Invalid document ID.");
207
- await mkdir(this.directory, { recursive: true });
208
- await writeWhole(paths.index, index);
598
+ const place = await this.#make(context);
599
+ await this.#write(place, filesOf(place.folder, id).index, index);
209
600
  }
210
- async getIndex(id) {
211
- const paths = this.paths(id);
212
- if (!paths)
601
+ async getIndex(id, context) {
602
+ if (!fileId(id))
603
+ return undefined;
604
+ const place = await this.#find(context);
605
+ if (!place)
213
606
  return undefined;
214
607
  try {
215
- const file = await readFile(paths.index);
608
+ const file = await readFile(filesOf(place.folder, id).index, { flag: READ_FLAGS });
216
609
  return new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
217
610
  }
218
- catch {
611
+ catch (error) {
612
+ this.#unreadable(place, error);
219
613
  return undefined;
220
614
  }
221
615
  }
222
- async delete(id) {
223
- const paths = this.paths(id);
224
- if (!paths)
225
- return false;
226
- const existed = Boolean(await readFile(paths.meta, "utf8").catch(() => null));
227
- // The metadata first: a document is there while its metadata is. If that file cannot be removed,
228
- // nothing else is, and the document stays whole. The other way round, a document whose text is
229
- // gone would still be listed.
230
- await rm(paths.meta, { force: true });
231
- await Promise.all([paths.text, paths.original, paths.index].map((file) => rm(file, { force: true })));
616
+ /**
617
+ * Removes the metadata, then the other files. True only when this call removed the metadata.
618
+ * When the metadata cannot be removed, the error is thrown and nothing else is touched: the
619
+ * document stays whole. Once it is gone, the document is gone: a text, index or original that
620
+ * cannot be removed now is left for `sweep`.
621
+ *
622
+ * Since 0.10.0 the metadata is first renamed to a name of this call's own (`<id>.json.<8 hex>.tmp`),
623
+ * then that name is removed, and the removal is this call's only when that succeeds. On Windows
624
+ * two unlinks of one file at the same moment can both succeed (the file goes when the last handle
625
+ * closes), so two sweeps counted one document twice, and two deletes both said true. A rename of
626
+ * a name that is gone fails (ENOENT); two renames of one file can both succeed on Windows, when
627
+ * both opened it before either moved it, but the file then has the last name only, and only that
628
+ * call's unlink finds it. The rename is tried again while Windows refuses it for a moment
629
+ * (EPERM, EBUSY, EACCES: a reader or a scanner has the file open), as a write's is. A name of
630
+ * this call's own that cannot be removed now (it is renamed already: the document is gone) is
631
+ * left for `sweep`, which removes temporary files once they are old, and the removal counts. The
632
+ * rename keeps the time the metadata was written, so the sweep reads the age of such a name from
633
+ * its last change (ctime), which the rename sets: a sweep on another server between the rename
634
+ * and the unlink leaves it.
635
+ */
636
+ async #remove(place, id) {
637
+ const files = filesOf(place.folder, id);
638
+ const claim = temporaryOf(files.meta);
639
+ let existed;
640
+ try {
641
+ await retried(() => rename(files.meta, claim));
642
+ existed = true;
643
+ }
644
+ catch (error) {
645
+ if (!missing(error))
646
+ throw error;
647
+ existed = false;
648
+ }
649
+ if (existed)
650
+ existed = await removeFile(claim).catch(() => true);
651
+ await Promise.allSettled([files.text, files.original, files.index].map(removeFile));
232
652
  return existed;
233
653
  }
234
- async putOriginal(id, bytes) {
235
- const paths = this.paths(id);
236
- if (!paths)
654
+ async delete(id, context) {
655
+ if (!fileId(id))
656
+ return false;
657
+ const place = await this.#find(context, true);
658
+ return place ? this.#remove(place, id) : false;
659
+ }
660
+ async putOriginal(id, bytes, context) {
661
+ if (!fileId(id))
237
662
  throw new Error("Invalid document ID.");
238
- await mkdir(this.directory, { recursive: true });
663
+ const place = await this.#make(context);
239
664
  // Written before the metadata (see put): until that exists, the document is treated as absent.
240
- await writeWhole(paths.original, bytes);
665
+ await this.#write(place, filesOf(place.folder, id).original, bytes);
241
666
  }
242
- async getOriginal(id) {
243
- const paths = this.paths(id);
244
- // The metadata decides whether the document is still there. getMeta also removes an expired one.
245
- if (!paths || !await this.getMeta(id))
667
+ async getOriginal(id, context) {
668
+ if (!fileId(id))
669
+ return undefined;
670
+ const place = await this.#find(context);
671
+ // The metadata decides whether the document is still there, and removes an expired one.
672
+ if (!place || !await this.#meta(place, id))
246
673
  return undefined;
247
674
  try {
248
- const file = await readFile(paths.original);
675
+ const file = await readFile(filesOf(place.folder, id).original, { flag: READ_FLAGS });
249
676
  return new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
250
677
  }
251
678
  catch (error) {
252
- if (missing(error))
679
+ if (this.#unreadable(place, error))
253
680
  return undefined;
254
681
  throw error;
255
682
  }
256
683
  }
257
684
  /**
258
- * Removes expired documents and returns how many. Also removes files that belong to no
685
+ * Removes expired documents and returns how many: those whose metadata this sweep removed, so
686
+ * that two sweeps at once count each document once. Also removes files that belong to no
259
687
  * document, and temporary files, once they are older than `orphanAgeMs`. A document whose
260
688
  * metadata is not valid is removed only when that file is that old too: it may be being
261
689
  * written by a server of an older version, which does not write whole files.
@@ -263,59 +691,145 @@ export class FileDocumentStore {
263
691
  * A document whose metadata could not be read at all (the volume did not answer, too many files
264
692
  * were open) is left alone, whatever its age: the next sweep looks at it again. A document that
265
693
  * cannot be removed is left for the next sweep too, and does not stop this one.
694
+ *
695
+ * With `scopes`: with a scope in `context`, the folder of that scope only. Without one, every
696
+ * scope's: it goes down exactly `scopes.depth` levels of folders, into folders whose names pass
697
+ * `isSafeScopeSegment` only, and follows no link. With `unscoped: "root"`, the directory itself too.
698
+ * Without `scopes`, the context is not used.
266
699
  */
267
- async sweep(now = this.now()) {
700
+ async sweep(now = this.now(), context) {
701
+ const slots = new Limiter(this.#sweepConcurrency);
702
+ const pool = async (task) => {
703
+ const release = await slots.acquire();
704
+ try {
705
+ return await task();
706
+ }
707
+ finally {
708
+ release();
709
+ }
710
+ };
711
+ const scopes = this.#scopes;
712
+ if (!scopes)
713
+ return this.#sweepFolder({ folder: this.directory, shared: true, scoped: false }, now, pool);
714
+ const scope = this.#scopeOf(context);
715
+ if (scope !== undefined) {
716
+ const place = await this.#find({ scope }, true);
717
+ return place ? this.#sweepFolder(place, now, pool) : 0;
718
+ }
719
+ let removed = scopes.unscoped === "root" ? await this.#sweepFolder({ folder: this.directory, shared: true, scoped: false }, now, pool) : 0;
720
+ // The folders of the scopes, a few at a time: one pool bounds the file system calls of all of them.
721
+ const running = new Set();
722
+ for await (const folder of this.#scopeFolders(pool)) {
723
+ const sweeping = this.#sweepFolder({ folder, shared: scopes.folder === "", scoped: true }, now, pool)
724
+ .then((count) => { removed += count; }, () => undefined)
725
+ .finally(() => running.delete(sweeping));
726
+ running.add(sweeping);
727
+ if (running.size >= this.#sweepConcurrency)
728
+ await Promise.race(running);
729
+ }
730
+ await Promise.all(running);
731
+ return removed;
732
+ }
733
+ /** The folders of the store in every scope's folder, found one level at a time, depth first. */
734
+ async *#scopeFolders(pool) {
735
+ const scopes = this.#scopes;
736
+ const walk = async function* (folder, level) {
737
+ let entries;
738
+ try {
739
+ entries = await pool(() => readdir(folder, { withFileTypes: true }));
740
+ }
741
+ catch {
742
+ return;
743
+ }
744
+ for (const entry of entries) {
745
+ // A link is not a directory here: it is never followed. Nor is a folder the application
746
+ // keeps beside the scopes, whose name is not one a scope may have.
747
+ if (!entry.isDirectory() || !isSafeScopeSegment(entry.name))
748
+ continue;
749
+ const next = path.join(folder, entry.name);
750
+ if (level + 1 < scopes.depth) {
751
+ yield* walk(next, level + 1);
752
+ continue;
753
+ }
754
+ if (!scopes.folder) {
755
+ yield next;
756
+ continue;
757
+ }
758
+ const documents = path.join(next, scopes.folder);
759
+ const info = await pool(() => lstat(documents)).catch(() => undefined);
760
+ if (info?.isDirectory())
761
+ yield documents;
762
+ }
763
+ };
764
+ yield* walk(this.directory, 0);
765
+ }
766
+ /** Sweeps one folder. Never throws: a folder that cannot be listed gives 0. */
767
+ async #sweepFolder(place, now, pool) {
268
768
  let entries;
269
769
  try {
270
- entries = await readdir(this.directory);
770
+ entries = await pool(() => readdir(place.folder, { withFileTypes: true }));
271
771
  }
272
772
  catch {
273
773
  return 0;
274
774
  }
275
775
  const files = new Map();
276
776
  for (const entry of entries) {
277
- const match = FILE_NAME.exec(entry);
777
+ const match = entry.isFile() ? FILE_NAME.exec(entry.name) : null;
278
778
  if (!match)
279
779
  continue;
280
780
  const list = files.get(match[1]) ?? [];
281
- list.push(entry);
781
+ list.push(entry.name);
282
782
  files.set(match[1], list);
283
783
  }
784
+ const counts = await Promise.all([...files].map(([id, names]) => this.#sweepDocument(place, id, names, now, pool)));
785
+ return counts.reduce((sum, count) => sum + count, 0);
786
+ }
787
+ /** Sweeps the files of one ID in a folder: 1 when it removed an expired or broken document. */
788
+ async #sweepDocument(place, id, names, now, pool) {
789
+ const metaFile = `${id}.json`;
284
790
  const old = async (entry) => {
285
- const info = await stat(path.join(this.directory, entry)).catch(() => undefined);
286
- return info !== undefined && now.getTime() - info.mtimeMs >= this.orphanAgeMs;
791
+ const info = await pool(() => stat(path.join(place.folder, entry))).catch(() => undefined);
792
+ if (info === undefined)
793
+ return false;
794
+ // A temporary name of the metadata may be the claim of a delete under way (`#remove`): the
795
+ // metadata renamed, with the time it was written. Its age is from the rename, which sets the
796
+ // time of its last change (ctime, on Linux, NFS and NTFS): a claim of a live document is
797
+ // never taken for an old file, which would leave the delete without it (0.10.0).
798
+ const since = entry.startsWith(`${metaFile}.`) && entry.endsWith(".tmp") ? Math.max(info.mtimeMs, info.ctimeMs) : info.mtimeMs;
799
+ return now.getTime() - since >= this.orphanAgeMs;
287
800
  };
288
- let removed = 0;
289
- for (const [id, names] of files) {
290
- const metaFile = `${id}.json`;
291
- if (names.includes(metaFile)) {
292
- let raw;
293
- try {
294
- raw = await readFile(path.join(this.directory, metaFile), "utf8");
295
- }
296
- catch (error) {
297
- // Not read is not the same as not valid: nothing of this document is touched.
298
- if (!missing(error))
299
- continue;
300
- }
301
- if (raw !== undefined) {
302
- const meta = parseMeta(raw);
303
- if (meta ? expired(meta, now) : await old(metaFile)) {
304
- if (await this.delete(id).then(() => true, () => false))
305
- removed++;
306
- continue;
307
- }
308
- }
801
+ // In a folder of the store's own, every file named like a document's is the store's. In one the
802
+ // application shares, a file of an application's ID is, only when its metadata names it.
803
+ const ours = !place.shared || DOCUMENT_ID_PATTERN.test(id);
804
+ const hasMeta = names.includes(metaFile);
805
+ if (hasMeta) {
806
+ let raw;
807
+ try {
808
+ raw = await pool(() => readFile(path.join(place.folder, metaFile), { encoding: "utf8", flag: READ_FLAGS }));
309
809
  }
310
- // Temporary files of this document, and every file of one without metadata, once they are old.
311
- for (const entry of names) {
312
- if (entry === metaFile || (!entry.endsWith(".tmp") && names.includes(metaFile)))
313
- continue;
314
- if (await old(entry))
315
- await rm(path.join(this.directory, entry), { force: true }).catch(() => undefined);
810
+ catch (error) {
811
+ // Not read is not the same as not valid: nothing of this document is touched.
812
+ if (!missing(error))
813
+ return 0;
814
+ }
815
+ if (raw !== undefined) {
816
+ const meta = parseMeta(raw);
817
+ const known = meta !== undefined && (ours || meta.id === id);
818
+ if (known ? expired(meta, now) : ours && await old(metaFile)) {
819
+ // 1 only when this sweep removed the metadata: another sweep at the same time may have.
820
+ return await pool(() => this.#remove(place, id)).then((existed) => (existed ? 1 : 0), () => 0);
821
+ }
316
822
  }
317
823
  }
318
- return removed;
824
+ // Temporary files of this ID, and, when they are the store's, the files of a document without
825
+ // metadata, once they are old.
826
+ for (const entry of names) {
827
+ if (entry === metaFile || (!entry.endsWith(".tmp") && (hasMeta || !ours)))
828
+ continue;
829
+ if (await old(entry))
830
+ await pool(() => rm(path.join(place.folder, entry), { force: true })).catch(() => undefined);
831
+ }
832
+ return 0;
319
833
  }
320
834
  }
321
835
  //# sourceMappingURL=stores.js.map