llm-large-files 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/CHANGELOG.md +535 -0
  2. package/README.md +9 -10
  3. package/dist/access.d.ts +86 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +131 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/ask.d.ts +45 -1
  8. package/dist/ask.d.ts.map +1 -1
  9. package/dist/ask.js +181 -20
  10. package/dist/ask.js.map +1 -1
  11. package/dist/cache.d.ts +12 -3
  12. package/dist/cache.d.ts.map +1 -1
  13. package/dist/cache.js +18 -5
  14. package/dist/cache.js.map +1 -1
  15. package/dist/encoding.js +5 -3
  16. package/dist/encoding.js.map +1 -1
  17. package/dist/error-info.d.ts +57 -0
  18. package/dist/error-info.d.ts.map +1 -0
  19. package/dist/error-info.js +217 -0
  20. package/dist/error-info.js.map +1 -0
  21. package/dist/errors.d.ts +72 -8
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js +102 -15
  24. package/dist/errors.js.map +1 -1
  25. package/dist/events.d.ts +35 -9
  26. package/dist/events.d.ts.map +1 -1
  27. package/dist/events.js +42 -11
  28. package/dist/events.js.map +1 -1
  29. package/dist/evidence.d.ts +4 -2
  30. package/dist/evidence.d.ts.map +1 -1
  31. package/dist/evidence.js +14 -3
  32. package/dist/evidence.js.map +1 -1
  33. package/dist/extract.d.ts +32 -8
  34. package/dist/extract.d.ts.map +1 -1
  35. package/dist/extract.js +46 -35
  36. package/dist/extract.js.map +1 -1
  37. package/dist/gemini/adapter.d.ts +19 -3
  38. package/dist/gemini/adapter.d.ts.map +1 -1
  39. package/dist/gemini/adapter.js +84 -12
  40. package/dist/gemini/adapter.js.map +1 -1
  41. package/dist/gemini/chat.d.ts +18 -6
  42. package/dist/gemini/chat.d.ts.map +1 -1
  43. package/dist/gemini/chat.js +2 -0
  44. package/dist/gemini/chat.js.map +1 -1
  45. package/dist/gemini/index.d.ts +1 -1
  46. package/dist/gemini/index.d.ts.map +1 -1
  47. package/dist/index.d.ts +9 -6
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +4 -3
  50. package/dist/index.js.map +1 -1
  51. package/dist/ingest.d.ts +70 -0
  52. package/dist/ingest.d.ts.map +1 -0
  53. package/dist/ingest.js +868 -0
  54. package/dist/ingest.js.map +1 -0
  55. package/dist/library.d.ts +169 -34
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +324 -591
  58. package/dist/library.js.map +1 -1
  59. package/dist/map-reduce.js +3 -3
  60. package/dist/map-reduce.js.map +1 -1
  61. package/dist/model.d.ts +43 -2
  62. package/dist/model.d.ts.map +1 -1
  63. package/dist/model.js +63 -3
  64. package/dist/model.js.map +1 -1
  65. package/dist/node/handlers.d.ts +226 -14
  66. package/dist/node/handlers.d.ts.map +1 -1
  67. package/dist/node/handlers.js +423 -181
  68. package/dist/node/handlers.js.map +1 -1
  69. package/dist/node/index.d.ts +3 -2
  70. package/dist/node/index.d.ts.map +1 -1
  71. package/dist/node/index.js +2 -1
  72. package/dist/node/index.js.map +1 -1
  73. package/dist/node/ingest-child.d.ts +7 -1
  74. package/dist/node/ingest-child.d.ts.map +1 -1
  75. package/dist/node/ingest-child.js +18 -3
  76. package/dist/node/ingest-child.js.map +1 -1
  77. package/dist/node/isolated.d.ts +3 -1
  78. package/dist/node/isolated.d.ts.map +1 -1
  79. package/dist/node/isolated.js +11 -4
  80. package/dist/node/isolated.js.map +1 -1
  81. package/dist/node/originals.d.ts +19 -0
  82. package/dist/node/originals.d.ts.map +1 -0
  83. package/dist/node/originals.js +82 -0
  84. package/dist/node/originals.js.map +1 -0
  85. package/dist/node/spool.d.ts +102 -0
  86. package/dist/node/spool.d.ts.map +1 -0
  87. package/dist/node/spool.js +365 -0
  88. package/dist/node/spool.js.map +1 -0
  89. package/dist/node/sse.d.ts +4 -3
  90. package/dist/node/sse.d.ts.map +1 -1
  91. package/dist/node/sse.js +7 -6
  92. package/dist/node/sse.js.map +1 -1
  93. package/dist/pdf-layout.d.ts.map +1 -1
  94. package/dist/pdf-layout.js +71 -12
  95. package/dist/pdf-layout.js.map +1 -1
  96. package/dist/ranged.d.ts +15 -11
  97. package/dist/ranged.d.ts.map +1 -1
  98. package/dist/ranged.js +42 -11
  99. package/dist/ranged.js.map +1 -1
  100. package/dist/retry.d.ts +3 -1
  101. package/dist/retry.d.ts.map +1 -1
  102. package/dist/retry.js +6 -2
  103. package/dist/retry.js.map +1 -1
  104. package/dist/scope.d.ts +25 -0
  105. package/dist/scope.d.ts.map +1 -0
  106. package/dist/scope.js +60 -0
  107. package/dist/scope.js.map +1 -0
  108. package/dist/source.d.ts +60 -0
  109. package/dist/source.d.ts.map +1 -0
  110. package/dist/source.js +170 -0
  111. package/dist/source.js.map +1 -0
  112. package/dist/stores.d.ts +120 -31
  113. package/dist/stores.d.ts.map +1 -1
  114. package/dist/stores.js +582 -139
  115. package/dist/stores.js.map +1 -1
  116. package/dist/testing/fake-fetch.d.ts +31 -0
  117. package/dist/testing/fake-fetch.d.ts.map +1 -0
  118. package/dist/testing/fake-fetch.js +66 -0
  119. package/dist/testing/fake-fetch.js.map +1 -0
  120. package/dist/testing/fake-model.d.ts +38 -0
  121. package/dist/testing/fake-model.d.ts.map +1 -0
  122. package/dist/testing/fake-model.js +62 -0
  123. package/dist/testing/fake-model.js.map +1 -0
  124. package/dist/testing/index.d.ts +7 -0
  125. package/dist/testing/index.d.ts.map +1 -0
  126. package/dist/testing/index.js +9 -0
  127. package/dist/testing/index.js.map +1 -0
  128. package/dist/testing/store-checks.d.ts +72 -0
  129. package/dist/testing/store-checks.d.ts.map +1 -0
  130. package/dist/testing/store-checks.js +619 -0
  131. package/dist/testing/store-checks.js.map +1 -0
  132. package/dist/tools.d.ts +25 -0
  133. package/dist/tools.d.ts.map +1 -1
  134. package/dist/tools.js +135 -13
  135. package/dist/tools.js.map +1 -1
  136. package/dist/types.d.ts +116 -13
  137. package/dist/types.d.ts.map +1 -1
  138. package/docs/README.md +17 -8
  139. package/docs/getting-started.md +18 -13
  140. package/docs/guides/anthropic.md +12 -8
  141. package/docs/guides/conversations.md +112 -47
  142. package/docs/guides/costs-and-limits.md +16 -7
  143. package/docs/guides/deployment.md +284 -83
  144. package/docs/guides/errors-and-reliability.md +161 -23
  145. package/docs/guides/own-adapter-and-loop.md +27 -10
  146. package/docs/guides/pdfs.md +123 -29
  147. package/docs/guides/storage.md +633 -145
  148. package/docs/guides/testing.md +78 -129
  149. package/docs/guides/vertex-and-gemini.md +10 -7
  150. package/docs/guides/web-app.md +312 -78
  151. package/docs/how-it-works.md +35 -8
  152. package/docs/measurements.md +43 -8
  153. package/docs/publishing.md +112 -36
  154. package/docs/reference/ask.md +154 -13
  155. package/docs/reference/errors-and-retries.md +166 -14
  156. package/docs/reference/events.md +53 -20
  157. package/docs/reference/gemini.md +70 -21
  158. package/docs/reference/library.md +706 -165
  159. package/docs/reference/node.md +624 -110
  160. package/docs/reference/testing.md +311 -0
  161. package/docs/reference/tools.md +15 -5
  162. package/docs/security.md +304 -67
  163. package/docs/troubleshooting.md +144 -65
  164. package/docs/upgrading-0.9.md +890 -0
  165. package/package.json +12 -3
  166. package/src/access.ts +144 -0
  167. package/src/ask.ts +230 -19
  168. package/src/cache.ts +20 -5
  169. package/src/encoding.ts +6 -4
  170. package/src/error-info.ts +255 -0
  171. package/src/errors.ts +129 -15
  172. package/src/events.ts +86 -21
  173. package/src/evidence.ts +14 -3
  174. package/src/extract.ts +50 -33
  175. package/src/gemini/adapter.ts +97 -11
  176. package/src/gemini/chat.ts +20 -6
  177. package/src/gemini/index.ts +1 -1
  178. package/src/index.ts +9 -6
  179. package/src/ingest.ts +927 -0
  180. package/src/library.ts +467 -601
  181. package/src/map-reduce.ts +3 -3
  182. package/src/model.ts +69 -5
  183. package/src/node/handlers.ts +630 -183
  184. package/src/node/index.ts +13 -2
  185. package/src/node/ingest-child.ts +23 -5
  186. package/src/node/isolated.ts +11 -4
  187. package/src/node/originals.ts +78 -0
  188. package/src/node/spool.ts +365 -0
  189. package/src/node/sse.ts +7 -6
  190. package/src/pdf-layout.ts +69 -11
  191. package/src/ranged.ts +34 -13
  192. package/src/retry.ts +6 -2
  193. package/src/scope.ts +63 -0
  194. package/src/source.ts +178 -0
  195. package/src/stores.ts +635 -140
  196. package/src/testing/fake-fetch.ts +80 -0
  197. package/src/testing/fake-model.ts +78 -0
  198. package/src/testing/index.ts +11 -0
  199. package/src/testing/store-checks.ts +660 -0
  200. package/src/tools.ts +150 -14
  201. package/src/types.ts +106 -13
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,136 @@ 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
+
224
+ /**
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.
227
+ */
228
+ async function removeFile(file: string): Promise<boolean> {
229
+ try {
230
+ await retried(() => unlink(file));
231
+ return true;
232
+ } catch (error) {
233
+ if (missing(error)) return false;
234
+ throw error;
235
+ }
236
+ }
237
+
93
238
  /**
94
239
  * Writes a file whole or not at all, as other processes see it: to a temporary name first, then
95
240
  * renamed. A server reading a shared volume never sees half of a file another server is writing.
241
+ * The temporary file is made with `mode`, and the rename keeps it.
96
242
  */
97
- async function writeWhole(target: string, data: string | Uint8Array): Promise<void> {
243
+ async function writeWhole(target: string, data: string | Uint8Array, mode: number): Promise<void> {
98
244
  const temporary = `${target}.${randomUUID().slice(0, 8)}.tmp`;
99
245
  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]));
108
- }
109
- }
246
+ await writeFile(temporary, data, { mode });
247
+ await retried(() => rename(temporary, target));
110
248
  } catch (error) {
111
249
  await rm(temporary, { force: true }).catch(() => undefined);
112
250
  throw error;
113
251
  }
114
252
  }
115
253
 
254
+ /** The files of a document in `folder`. */
255
+ function filesOf(folder: string, id: string): { text: string; meta: string; original: string; index: string } {
256
+ const file = (extension: string) => path.join(folder, `${id}.${extension}`);
257
+ return { text: file("txt"), meta: file("json"), original: file("bin"), index: file("idx") };
258
+ }
259
+
260
+ /** Where the documents of a scope go, when the store keeps each scope in a folder of its own. New in 0.9.0. */
261
+ export type FileDocumentScopes = {
262
+ /**
263
+ * How many segments every scope has, from 1 to 8: 2 for `[userId, chatId]`. A scope of another
264
+ * length is a `DocumentScopeError` of code "scope_invalid".
265
+ */
266
+ depth: number;
267
+ /**
268
+ * The folder of the store in the folder of each scope: `<directory>/<scope...>/<folder>/<id>.json`.
269
+ * Defaults to ".llm-large-files". "" puts the files in the scope's folder itself, beside files of
270
+ * the application's own. The names `<id>.json`, `.txt`, `.idx` and `.bin`, and their temporary
271
+ * files, are then the store's for every ID it is given: keep files of your own in a subfolder.
272
+ */
273
+ folder?: string;
274
+ /**
275
+ * Whether a write makes the folders of a scope that has none. Defaults to false: the folders of a
276
+ * scope are the application's, and the store only makes its own `folder` in them. A write into a
277
+ * scope whose folder is gone (the chat was deleted) is then a `DocumentScopeError` of code
278
+ * "scope_missing", and the folder is not made again. With true, they are made one level at a time,
279
+ * each checked to be a folder and not a link before the next is made in it.
280
+ */
281
+ createScopeFolders?: boolean;
282
+ /**
283
+ * What a call without a scope does. "refuse", the default: it throws a `DocumentScopeError` of
284
+ * code "scope_required". "root": it uses the files directly in the directory, as a store without
285
+ * `scopes` does, to keep reading documents written there before.
286
+ */
287
+ unscoped?: "refuse" | "root";
288
+ };
289
+
290
+ /** The options of a `FileDocumentStore`. */
291
+ export type FileDocumentStoreOptions = {
292
+ /** The clock that decides expiry, and the default `now` of `sweep`. Defaults to `() => new Date()`. */
293
+ now?: () => Date;
294
+ /**
295
+ * `sweep` removes files that belong to no document (an upload that failed, a server that
296
+ * stopped while writing) once they are this old. Younger ones may be an upload in progress,
297
+ * on this server or another one. Defaults to one hour.
298
+ */
299
+ orphanAgeMs?: number;
300
+ /** Keep the documents of each scope in a folder of their own. Without it, every document is in `directory`. New in 0.9.0. */
301
+ scopes?: FileDocumentScopes;
302
+ /** The mode of every file the store writes, minus the umask of the process. Defaults to 0o600. New in 0.9.0. */
303
+ fileMode?: number;
304
+ /** The mode of every folder the store makes, minus the umask of the process. Defaults to 0o700. New in 0.9.0. */
305
+ directoryMode?: number;
306
+ /** 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. */
307
+ sweepConcurrency?: number;
308
+ };
309
+
310
+ /** A folder of documents: the store's directory, or the folder of a scope. */
311
+ type Place = {
312
+ folder: string;
313
+ /**
314
+ * Whether files of the application may sit in the folder too: the directory without scopes, or
315
+ * the folder of a scope with `folder: ""`. There, a file of no document is removed by `sweep` only
316
+ * when its name is an ID the library makes, or a temporary file: `notes.txt` may be the
317
+ * application's, not the text of a document "notes".
318
+ */
319
+ shared: boolean;
320
+ /** Whether the folder is a scope's, which a write must not make again (`createScopeFolders`). */
321
+ scoped: boolean;
322
+ };
323
+
324
+ /** Runs file system calls of one sweep, at most `concurrency` at once. */
325
+ type Pool = <T>(task: () => Promise<T>) => Promise<T>;
326
+
327
+ function checkMode(name: string, value: number | undefined, fallback: number): number {
328
+ if (value === undefined) return fallback;
329
+ if (!Number.isInteger(value) || value < 0 || value > 0o777) throw new TypeError(`${name} must be a file mode from 0 to 0o777, such as 0o640.`);
330
+ return value;
331
+ }
332
+
116
333
  /**
117
334
  * Keeps each document as `<id>.txt` plus `<id>.json` in one directory, so files survive a
118
335
  * 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.
336
+ * kept. Only IDs matching APP_DOCUMENT_ID_PATTERN (which leaves out names Windows keeps for
337
+ * devices) ever reach the file system. Those names, for every ID it is given, are the store's: keep
338
+ * files of your own in a subfolder. A read does not follow a link at a file name, except on Windows.
339
+ *
340
+ * With `scopes`, the documents of each scope are kept in a folder of their own:
341
+ * `<directory>/<userId>/<chatId>/.llm-large-files/<id>.json`. New in 0.9.0.
120
342
  *
121
343
  * Several servers may share the directory (a network volume): every file is written whole under
122
344
  * a temporary name and then renamed, a tool call reads only the lines it needs (`readTextRange`),
@@ -125,77 +347,263 @@ async function writeWhole(target: string, data: string | Uint8Array): Promise<vo
125
347
  export class FileDocumentStore implements DocumentStore {
126
348
  private readonly now: () => Date;
127
349
  private readonly orphanAgeMs: number;
350
+ readonly #scopes: Required<FileDocumentScopes> | undefined;
351
+ readonly #fileMode: number;
352
+ readonly #directoryMode: number;
353
+ readonly #sweepConcurrency: number;
354
+ /** The directory, with links resolved, once it was found. */
355
+ #realDirectory: Promise<string> | undefined;
356
+ /** The folders of scopes that passed `#checkReal`, and when (`Date.now()`), the oldest first. */
357
+ readonly #checked = new Map<string, number>();
128
358
 
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
- } = {}) {
359
+ constructor(private readonly directory: string, options: FileDocumentStoreOptions = {}) {
138
360
  this.now = options.now ?? (() => new Date());
139
361
  this.orphanAgeMs = options.orphanAgeMs ?? 60 * 60 * 1000;
362
+ this.#fileMode = checkMode("fileMode", options.fileMode, 0o600);
363
+ this.#directoryMode = checkMode("directoryMode", options.directoryMode, 0o700);
364
+ const concurrency = options.sweepConcurrency ?? 16;
365
+ if (!Number.isInteger(concurrency) || concurrency < 1) throw new TypeError("sweepConcurrency must be a whole number of 1 or more.");
366
+ this.#sweepConcurrency = concurrency;
367
+ const scopes = options.scopes;
368
+ if (scopes === undefined) {
369
+ this.#scopes = undefined;
370
+ return;
371
+ }
372
+ if (!Number.isInteger(scopes.depth) || scopes.depth < 1 || scopes.depth > MAX_SCOPE_SEGMENTS) {
373
+ throw new TypeError(`scopes.depth must be a whole number from 1 to ${MAX_SCOPE_SEGMENTS}.`);
374
+ }
375
+ const folder = scopes.folder ?? ".llm-large-files";
376
+ if (folder !== "" && (!FOLDER_NAME.test(folder) || folder === "." || folder === "..")) {
377
+ throw new TypeError('scopes.folder must be "" or the name of one folder: letters, digits, ".", "_" and "-", such as ".llm-large-files".');
378
+ }
379
+ const unscoped = scopes.unscoped ?? "refuse";
380
+ if (unscoped !== "refuse" && unscoped !== "root") throw new TypeError('scopes.unscoped must be "refuse" or "root".');
381
+ this.#scopes = { depth: scopes.depth, folder, createScopeFolders: scopes.createScopeFolders === true, unscoped };
140
382
  }
141
383
 
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") };
384
+ /** The scope of a call, checked against the rules of this store, or undefined for none. */
385
+ #scopeOf(context: DocumentContext | undefined): DocumentScope | undefined {
386
+ const scope = checkScope(context?.scope);
387
+ if (scope === undefined || this.#scopes === undefined) return scope;
388
+ if (scope.length !== this.#scopes.depth) {
389
+ throw new DocumentScopeError("scope_invalid", `This store keeps scopes of ${this.#scopes.depth} segments (scopes.depth); the scope has ${scope.length}.`);
390
+ }
391
+ scope.forEach((segment, index) => {
392
+ if (!isSafeScopeSegment(segment)) {
393
+ 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).`);
394
+ }
395
+ });
396
+ return scope;
146
397
  }
147
398
 
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);
399
+ /** The directory itself: that of a store without scopes, or of a call without a scope under `unscoped: "root"`. */
400
+ #root(): Place {
401
+ if (this.#scopes && this.#scopes.unscoped !== "root") throw new DocumentScopeError("scope_required");
402
+ return { folder: this.directory, shared: true, scoped: false };
403
+ }
404
+
405
+ /** The folder of a scope, and that of the store in it. */
406
+ #folders(scope: DocumentScope): { scope: string; documents: string } {
407
+ const scopeFolder = path.join(this.directory, ...scope);
408
+ return { scope: scopeFolder, documents: this.#scopes!.folder ? path.join(scopeFolder, this.#scopes!.folder) : scopeFolder };
409
+ }
410
+
411
+ /**
412
+ * Checks that `folder` is where its path says, with no link on the way below the directory, and
413
+ * so inside the directory. Throws its error when it is not there. A folder that passes is
414
+ * remembered for CHECK_KEPT_MS, for reads (`#find`); one that fails is forgotten.
415
+ */
416
+ async #checkReal(folder: string): Promise<void> {
417
+ try {
418
+ const real = await realpath(folder);
419
+ this.#realDirectory ??= realpath(this.directory);
420
+ let directory: string;
421
+ try {
422
+ directory = await this.#realDirectory;
423
+ } catch (error) {
424
+ this.#realDirectory = undefined;
425
+ throw error;
426
+ }
427
+ if (real !== path.join(directory, path.relative(this.directory, folder))) throw new DocumentScopeError("scope_invalid", LINKED_FOLDER);
428
+ } catch (error) {
429
+ this.#checked.delete(folder);
430
+ throw error;
431
+ }
432
+ this.#checked.delete(folder);
433
+ this.#checked.set(folder, Date.now());
434
+ if (this.#checked.size > CHECKS_KEPT) this.#checked.delete(this.#checked.keys().next().value!);
435
+ }
436
+
437
+ /** Whether `folder` passed `#checkReal` less than CHECK_KEPT_MS ago. A clock set back counts as not. */
438
+ #checkedRecently(folder: string): boolean {
439
+ const at = this.#checked.get(folder);
440
+ if (at === undefined) return false;
441
+ const age = Date.now() - at;
442
+ if (age >= 0 && age < CHECK_KEPT_MS) return true;
443
+ this.#checked.delete(folder);
444
+ return false;
445
+ }
446
+
447
+ /**
448
+ * Whether a read's error means that the file is not there to read: missing, or a link, which is
449
+ * not followed. A file that is missing makes the next call check its folder again.
450
+ */
451
+ #unreadable(place: Place, error: unknown): boolean {
452
+ if (absent(error)) {
453
+ if (place.scoped) this.#checked.delete(place.folder);
454
+ return true;
455
+ }
456
+ return linked(error);
457
+ }
458
+
459
+ /**
460
+ * The folder of the documents of a call, or undefined when it is not there, and so neither are
461
+ * they. A read (`fresh` false) takes a folder checked less than CHECK_KEPT_MS ago as it was; a
462
+ * delete or a sweep checks it again.
463
+ */
464
+ async #find(context: DocumentContext | undefined, fresh = false): Promise<Place | undefined> {
465
+ if (!this.#scopes) return { folder: this.directory, shared: true, scoped: false };
466
+ const scope = this.#scopeOf(context);
467
+ if (scope === undefined) return this.#root();
468
+ const folders = this.#folders(scope);
469
+ if (fresh || !this.#checkedRecently(folders.documents)) {
470
+ try {
471
+ await this.#checkReal(folders.documents);
472
+ } catch (error) {
473
+ if (absent(error)) return undefined;
474
+ throw error;
475
+ }
476
+ }
477
+ return { folder: folders.documents, shared: this.#scopes.folder === "", scoped: true };
478
+ }
479
+
480
+ /**
481
+ * Makes the folders of a scope (`createScopeFolders`) one level at a time. Each is made, or found,
482
+ * as a folder and not a link before the next is made in it, so nothing is made where a link
483
+ * points. A file where a folder should be stops it: the check that follows finds the scope missing.
484
+ */
485
+ async #makeScopeFolders(scope: DocumentScope): Promise<void> {
486
+ await mkdir(this.directory, { recursive: true, mode: this.#directoryMode });
487
+ let level = this.directory;
488
+ for (const segment of scope) {
489
+ level = path.join(level, segment);
490
+ await mkdir(level, { mode: this.#directoryMode }).catch((error: unknown) => {
491
+ if (code(error) !== "EEXIST") throw error;
492
+ });
493
+ const info = await lstat(level);
494
+ if (info.isSymbolicLink()) throw new DocumentScopeError("scope_invalid", LINKED_FOLDER);
495
+ if (!info.isDirectory()) return;
496
+ }
497
+ }
498
+
499
+ /** The folder of the documents of a call, made when it is not there yet. */
500
+ async #make(context: DocumentContext | undefined): Promise<Place> {
501
+ const scope = this.#scopes ? this.#scopeOf(context) : undefined;
502
+ if (scope === undefined) {
503
+ const place = this.#scopes ? this.#root() : { folder: this.directory, shared: true, scoped: false };
504
+ await mkdir(this.directory, { recursive: true, mode: this.#directoryMode });
505
+ return place;
506
+ }
507
+ const scopes = this.#scopes!;
508
+ const folders = this.#folders(scope);
509
+ const place = { folder: folders.documents, shared: scopes.folder === "", scoped: true };
510
+ try {
511
+ await this.#checkReal(folders.documents);
512
+ return place;
513
+ } catch (error) {
514
+ if (!absent(error)) throw error;
515
+ }
516
+ try {
517
+ // Made only when asked to: the application may have removed the folder of a chat it deleted.
518
+ if (scopes.createScopeFolders) await this.#makeScopeFolders(scope);
519
+ await this.#checkReal(folders.scope);
520
+ if (folders.documents !== folders.scope) {
521
+ // Not recursive: if the scope's folder went in the meantime, it is not made again.
522
+ await mkdir(folders.documents, { mode: this.#directoryMode }).catch((error: unknown) => {
523
+ if (code(error) !== "EEXIST") throw error;
524
+ });
525
+ await this.#checkReal(folders.documents);
526
+ }
527
+ } catch (error) {
528
+ if (absent(error)) throw new DocumentScopeError("scope_missing", undefined, { cause: error });
529
+ throw error;
530
+ }
531
+ return place;
532
+ }
533
+
534
+ /** Writes one file of a document whole. A scope's folder that went while it was written is "scope_missing". */
535
+ async #write(place: Place, target: string, data: string | Uint8Array): Promise<void> {
536
+ try {
537
+ await writeWhole(target, data, this.#fileMode);
538
+ } catch (error) {
539
+ if (place.scoped && absent(error)) throw new DocumentScopeError("scope_missing", undefined, { cause: error });
540
+ throw error;
541
+ }
542
+ }
543
+
544
+ async put(document: StoredDocument, context?: DocumentContext): Promise<void> {
545
+ if (!fileId(document.meta.id)) throw new Error("Invalid document ID.");
546
+ const place = await this.#make(context);
547
+ const files = filesOf(place.folder, document.meta.id);
548
+ await this.#write(place, files.text, document.text);
153
549
  // Write metadata last: a document without metadata is treated as absent.
154
- await writeWhole(paths.meta, JSON.stringify(document.meta));
550
+ await this.#write(place, files.meta, JSON.stringify(document.meta));
155
551
  }
156
552
 
157
- async getMeta(id: string): Promise<DocumentMeta | undefined> {
158
- const paths = this.paths(id);
159
- if (!paths) return undefined;
553
+ /** The metadata of a document in `place`, or undefined. An expired one is removed, as far as that works. */
554
+ async #meta(place: Place, id: string): Promise<DocumentMeta | undefined> {
160
555
  let raw: string;
161
556
  try {
162
- raw = await readFile(paths.meta, "utf8");
557
+ raw = await readFile(filesOf(place.folder, id).meta, { encoding: "utf8", flag: READ_FLAGS });
163
558
  } 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;
559
+ // Only a file that is not there (or a link, not followed) means that the document is not
560
+ // there. A read that failed for another reason is thrown, so that a busy volume is not taken
561
+ // for a deleted document.
562
+ if (this.#unreadable(place, error)) return undefined;
167
563
  throw error;
168
564
  }
169
565
  // Metadata that cannot be parsed is an upload being written by a server of 0.3.x, or damaged: absent.
170
566
  const meta = parseMeta(raw);
171
567
  if (!meta) return undefined;
172
568
  if (expired(meta, this.now())) {
173
- await this.delete(id);
569
+ // Expired is missing, whether or not its files could be removed now: sweep tries again. The
570
+ // folder is checked again first: a read may have taken it as checked a moment ago.
571
+ await (place.scoped ? this.#checkReal(place.folder) : Promise.resolve())
572
+ .then(() => this.#remove(place, id))
573
+ .catch(() => undefined);
174
574
  return undefined;
175
575
  }
176
576
  return meta;
177
577
  }
178
578
 
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;
579
+ async getMeta(id: string, context?: DocumentContext): Promise<DocumentMeta | undefined> {
580
+ if (!fileId(id)) return undefined;
581
+ const place = await this.#find(context);
582
+ return place && this.#meta(place, id);
583
+ }
584
+
585
+ async get(id: string, context?: DocumentContext): Promise<StoredDocument | undefined> {
586
+ if (!fileId(id)) return undefined;
587
+ const place = await this.#find(context);
588
+ const meta = place && await this.#meta(place, id);
589
+ if (!place || !meta) return undefined;
183
590
  try {
184
- return { meta, text: await readFile(paths.text, "utf8") };
591
+ return { meta, text: await readFile(filesOf(place.folder, id).text, { encoding: "utf8", flag: READ_FLAGS }) };
185
592
  } catch (error) {
186
- if (missing(error)) return undefined;
593
+ if (this.#unreadable(place, error)) return undefined;
187
594
  throw error;
188
595
  }
189
596
  }
190
597
 
191
- async readTextRange(id: string, start: number, end: number): Promise<Uint8Array | undefined> {
192
- const paths = this.paths(id);
193
- if (!paths) return undefined;
598
+ async readTextRange(id: string, start: number, end: number, context?: DocumentContext): Promise<Uint8Array | undefined> {
599
+ if (!fileId(id)) return undefined;
600
+ const place = await this.#find(context);
601
+ if (!place) return undefined;
194
602
  let handle;
195
603
  try {
196
- handle = await open(paths.text, "r");
604
+ handle = await open(filesOf(place.folder, id).text, READ_FLAGS);
197
605
  } catch (error) {
198
- if (code(error) === "ENOENT") return undefined;
606
+ if (this.#unreadable(place, error)) return undefined;
199
607
  throw error;
200
608
  }
201
609
  try {
@@ -213,59 +621,67 @@ export class FileDocumentStore implements DocumentStore {
213
621
  }
214
622
  }
215
623
 
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);
624
+ async putIndex(id: string, index: Uint8Array, context?: DocumentContext): Promise<void> {
625
+ if (!fileId(id)) throw new Error("Invalid document ID.");
626
+ const place = await this.#make(context);
627
+ await this.#write(place, filesOf(place.folder, id).index, index);
221
628
  }
222
629
 
223
- async getIndex(id: string): Promise<Uint8Array | undefined> {
224
- const paths = this.paths(id);
225
- if (!paths) return undefined;
630
+ async getIndex(id: string, context?: DocumentContext): Promise<Uint8Array | undefined> {
631
+ if (!fileId(id)) return undefined;
632
+ const place = await this.#find(context);
633
+ if (!place) return undefined;
226
634
  try {
227
- const file = await readFile(paths.index);
635
+ const file = await readFile(filesOf(place.folder, id).index, { flag: READ_FLAGS });
228
636
  return new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
229
- } catch {
637
+ } catch (error) {
638
+ this.#unreadable(place, error);
230
639
  return undefined;
231
640
  }
232
641
  }
233
642
 
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 })));
643
+ /**
644
+ * Removes the metadata, then the other files. When the metadata cannot be removed, the error is
645
+ * thrown and nothing else is touched: the document stays whole. Once it is gone, the document is
646
+ * gone: a text, index or original that cannot be removed now is left for `sweep`.
647
+ */
648
+ async #remove(place: Place, id: string): Promise<boolean> {
649
+ const files = filesOf(place.folder, id);
650
+ const existed = await removeFile(files.meta);
651
+ await Promise.allSettled([files.text, files.original, files.index].map(removeFile));
243
652
  return existed;
244
653
  }
245
654
 
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 });
655
+ async delete(id: string, context?: DocumentContext): Promise<boolean> {
656
+ if (!fileId(id)) return false;
657
+ const place = await this.#find(context, true);
658
+ return place ? this.#remove(place, id) : false;
659
+ }
660
+
661
+ async putOriginal(id: string, bytes: Uint8Array, context?: DocumentContext): Promise<void> {
662
+ if (!fileId(id)) throw new Error("Invalid document ID.");
663
+ const place = await this.#make(context);
250
664
  // Written before the metadata (see put): until that exists, the document is treated as absent.
251
- await writeWhole(paths.original, bytes);
665
+ await this.#write(place, filesOf(place.folder, id).original, bytes);
252
666
  }
253
667
 
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;
668
+ async getOriginal(id: string, context?: DocumentContext): Promise<Uint8Array | undefined> {
669
+ if (!fileId(id)) 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)) return undefined;
258
673
  try {
259
- const file = await readFile(paths.original);
674
+ const file = await readFile(filesOf(place.folder, id).original, { flag: READ_FLAGS });
260
675
  return new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
261
676
  } catch (error) {
262
- if (missing(error)) return undefined;
677
+ if (this.#unreadable(place, error)) return undefined;
263
678
  throw error;
264
679
  }
265
680
  }
266
681
 
267
682
  /**
268
- * Removes expired documents and returns how many. Also removes files that belong to no
683
+ * Removes expired documents and returns how many: those whose metadata this sweep removed, so
684
+ * that two sweeps at once count each document once. Also removes files that belong to no
269
685
  * document, and temporary files, once they are older than `orphanAgeMs`. A document whose
270
686
  * metadata is not valid is removed only when that file is that old too: it may be being
271
687
  * written by a server of an older version, which does not write whole files.
@@ -273,51 +689,130 @@ export class FileDocumentStore implements DocumentStore {
273
689
  * A document whose metadata could not be read at all (the volume did not answer, too many files
274
690
  * were open) is left alone, whatever its age: the next sweep looks at it again. A document that
275
691
  * cannot be removed is left for the next sweep too, and does not stop this one.
692
+ *
693
+ * With `scopes`: with a scope in `context`, the folder of that scope only. Without one, every
694
+ * scope's: it goes down exactly `scopes.depth` levels of folders, into folders whose names pass
695
+ * `isSafeScopeSegment` only, and follows no link. With `unscoped: "root"`, the directory itself too.
696
+ * Without `scopes`, the context is not used.
276
697
  */
277
- async sweep(now = this.now()): Promise<number> {
278
- let entries: string[];
698
+ async sweep(now = this.now(), context?: DocumentContext): Promise<number> {
699
+ const slots = new Limiter(this.#sweepConcurrency);
700
+ const pool: Pool = async (task) => {
701
+ const release = await slots.acquire();
702
+ try {
703
+ return await task();
704
+ } finally {
705
+ release();
706
+ }
707
+ };
708
+ const scopes = this.#scopes;
709
+ if (!scopes) return this.#sweepFolder({ folder: this.directory, shared: true, scoped: false }, now, pool);
710
+ const scope = this.#scopeOf(context);
711
+ if (scope !== undefined) {
712
+ const place = await this.#find({ scope }, true);
713
+ return place ? this.#sweepFolder(place, now, pool) : 0;
714
+ }
715
+ let removed = scopes.unscoped === "root" ? await this.#sweepFolder({ folder: this.directory, shared: true, scoped: false }, now, pool) : 0;
716
+ // The folders of the scopes, a few at a time: one pool bounds the file system calls of all of them.
717
+ const running = new Set<Promise<void>>();
718
+ for await (const folder of this.#scopeFolders(pool)) {
719
+ const sweeping: Promise<void> = this.#sweepFolder({ folder, shared: scopes.folder === "", scoped: true }, now, pool)
720
+ .then((count) => { removed += count; }, () => undefined)
721
+ .finally(() => running.delete(sweeping));
722
+ running.add(sweeping);
723
+ if (running.size >= this.#sweepConcurrency) await Promise.race(running);
724
+ }
725
+ await Promise.all(running);
726
+ return removed;
727
+ }
728
+
729
+ /** The folders of the store in every scope's folder, found one level at a time, depth first. */
730
+ async *#scopeFolders(pool: Pool): AsyncGenerator<string> {
731
+ const scopes = this.#scopes!;
732
+ const walk = async function* (folder: string, level: number): AsyncGenerator<string> {
733
+ let entries: Dirent[];
734
+ try {
735
+ entries = await pool(() => readdir(folder, { withFileTypes: true }));
736
+ } catch {
737
+ return;
738
+ }
739
+ for (const entry of entries) {
740
+ // A link is not a directory here: it is never followed. Nor is a folder the application
741
+ // keeps beside the scopes, whose name is not one a scope may have.
742
+ if (!entry.isDirectory() || !isSafeScopeSegment(entry.name)) continue;
743
+ const next = path.join(folder, entry.name);
744
+ if (level + 1 < scopes.depth) {
745
+ yield* walk(next, level + 1);
746
+ continue;
747
+ }
748
+ if (!scopes.folder) {
749
+ yield next;
750
+ continue;
751
+ }
752
+ const documents = path.join(next, scopes.folder);
753
+ const info = await pool(() => lstat(documents)).catch(() => undefined);
754
+ if (info?.isDirectory()) yield documents;
755
+ }
756
+ };
757
+ yield* walk(this.directory, 0);
758
+ }
759
+
760
+ /** Sweeps one folder. Never throws: a folder that cannot be listed gives 0. */
761
+ async #sweepFolder(place: Place, now: Date, pool: Pool): Promise<number> {
762
+ let entries: Dirent[];
279
763
  try {
280
- entries = await readdir(this.directory);
764
+ entries = await pool(() => readdir(place.folder, { withFileTypes: true }));
281
765
  } catch {
282
766
  return 0;
283
767
  }
284
768
  const files = new Map<string, string[]>();
285
769
  for (const entry of entries) {
286
- const match = FILE_NAME.exec(entry);
770
+ const match = entry.isFile() ? FILE_NAME.exec(entry.name) : null;
287
771
  if (!match) continue;
288
772
  const list = files.get(match[1]!) ?? [];
289
- list.push(entry);
773
+ list.push(entry.name);
290
774
  files.set(match[1]!, list);
291
775
  }
776
+ const counts = await Promise.all([...files].map(([id, names]) => this.#sweepDocument(place, id, names, now, pool)));
777
+ return counts.reduce((sum, count) => sum + count, 0);
778
+ }
779
+
780
+ /** Sweeps the files of one ID in a folder: 1 when it removed an expired or broken document. */
781
+ async #sweepDocument(place: Place, id: string, names: string[], now: Date, pool: Pool): Promise<number> {
292
782
  const old = async (entry: string) => {
293
- const info = await stat(path.join(this.directory, entry)).catch(() => undefined);
783
+ const info = await pool(() => stat(path.join(place.folder, entry))).catch(() => undefined);
294
784
  return info !== undefined && now.getTime() - info.mtimeMs >= this.orphanAgeMs;
295
785
  };
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
- }
786
+ // In a folder of the store's own, every file named like a document's is the store's. In one the
787
+ // application shares, a file of an application's ID is, only when its metadata names it.
788
+ const ours = !place.shared || DOCUMENT_ID_PATTERN.test(id);
789
+ const metaFile = `${id}.json`;
790
+ const hasMeta = names.includes(metaFile);
791
+ if (hasMeta) {
792
+ let raw: string | undefined;
793
+ try {
794
+ raw = await pool(() => readFile(path.join(place.folder, metaFile), { encoding: "utf8", flag: READ_FLAGS }));
795
+ } catch (error) {
796
+ // Not read is not the same as not valid: nothing of this document is touched.
797
+ if (!missing(error)) return 0;
314
798
  }
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);
799
+ if (raw !== undefined) {
800
+ const meta = parseMeta(raw);
801
+ const known = meta !== undefined && (ours || meta.id === id);
802
+ if (known ? expired(meta!, now) : ours && await old(metaFile)) {
803
+ // 1 only when this sweep removed the metadata: another sweep at the same time may have.
804
+ // On Windows both unlinks of one file can succeed (the file goes when the last handle
805
+ // closes), and both sweeps count it: claiming it by a rename first would tell them apart.
806
+ return await pool(() => this.#remove(place, id)).then((existed) => (existed ? 1 : 0), () => 0);
807
+ }
319
808
  }
320
809
  }
321
- return removed;
810
+ // Temporary files of this ID, and, when they are the store's, the files of a document without
811
+ // metadata, once they are old.
812
+ for (const entry of names) {
813
+ if (entry === metaFile || (!entry.endsWith(".tmp") && (hasMeta || !ours))) continue;
814
+ if (await old(entry)) await pool(() => rm(path.join(place.folder, entry), { force: true })).catch(() => undefined);
815
+ }
816
+ return 0;
322
817
  }
323
818
  }