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