llm-large-files 0.9.0 → 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 (222) hide show
  1. package/CHANGELOG.md +446 -0
  2. package/README.md +13 -7
  3. package/dist/access.d.ts +45 -3
  4. package/dist/access.d.ts.map +1 -1
  5. package/dist/access.js +106 -3
  6. package/dist/access.js.map +1 -1
  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 +115 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +572 -103
  26. package/dist/ask.js.map +1 -1
  27. package/dist/citations.d.ts +36 -0
  28. package/dist/citations.d.ts.map +1 -0
  29. package/dist/citations.js +291 -0
  30. package/dist/citations.js.map +1 -0
  31. package/dist/error-info.d.ts +13 -0
  32. package/dist/error-info.d.ts.map +1 -1
  33. package/dist/error-info.js +37 -1
  34. package/dist/error-info.js.map +1 -1
  35. package/dist/errors.d.ts +3 -1
  36. package/dist/errors.d.ts.map +1 -1
  37. package/dist/errors.js +3 -1
  38. package/dist/errors.js.map +1 -1
  39. package/dist/events.d.ts +25 -7
  40. package/dist/events.d.ts.map +1 -1
  41. package/dist/events.js.map +1 -1
  42. package/dist/evidence.d.ts.map +1 -1
  43. package/dist/evidence.js +21 -2
  44. package/dist/evidence.js.map +1 -1
  45. package/dist/extract.d.ts.map +1 -1
  46. package/dist/extract.js +6 -1
  47. package/dist/extract.js.map +1 -1
  48. package/dist/gemini/adapter.d.ts +35 -4
  49. package/dist/gemini/adapter.d.ts.map +1 -1
  50. package/dist/gemini/adapter.js +68 -29
  51. package/dist/gemini/adapter.js.map +1 -1
  52. package/dist/gemini/chat.d.ts +28 -55
  53. package/dist/gemini/chat.d.ts.map +1 -1
  54. package/dist/gemini/chat.js +20 -27
  55. package/dist/gemini/chat.js.map +1 -1
  56. package/dist/gemini/endpoints.d.ts +59 -11
  57. package/dist/gemini/endpoints.d.ts.map +1 -1
  58. package/dist/gemini/endpoints.js +33 -7
  59. package/dist/gemini/endpoints.js.map +1 -1
  60. package/dist/gemini/errors.d.ts +39 -5
  61. package/dist/gemini/errors.d.ts.map +1 -1
  62. package/dist/gemini/errors.js +70 -9
  63. package/dist/gemini/errors.js.map +1 -1
  64. package/dist/gemini/generate.d.ts +53 -2
  65. package/dist/gemini/generate.d.ts.map +1 -1
  66. package/dist/gemini/generate.js +100 -50
  67. package/dist/gemini/generate.js.map +1 -1
  68. package/dist/gemini/index.d.ts +3 -3
  69. package/dist/gemini/index.d.ts.map +1 -1
  70. package/dist/http.d.ts +41 -3
  71. package/dist/http.d.ts.map +1 -1
  72. package/dist/http.js +40 -2
  73. package/dist/http.js.map +1 -1
  74. package/dist/index.d.ts +6 -4
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +4 -2
  77. package/dist/index.js.map +1 -1
  78. package/dist/ingest.d.ts +9 -1
  79. package/dist/ingest.d.ts.map +1 -1
  80. package/dist/ingest.js +50 -25
  81. package/dist/ingest.js.map +1 -1
  82. package/dist/library.d.ts +129 -2
  83. package/dist/library.d.ts.map +1 -1
  84. package/dist/library.js +224 -149
  85. package/dist/library.js.map +1 -1
  86. package/dist/map-reduce.d.ts +176 -10
  87. package/dist/map-reduce.d.ts.map +1 -1
  88. package/dist/map-reduce.js +804 -58
  89. package/dist/map-reduce.js.map +1 -1
  90. package/dist/model.d.ts +36 -4
  91. package/dist/model.d.ts.map +1 -1
  92. package/dist/model.js +17 -1
  93. package/dist/model.js.map +1 -1
  94. package/dist/node/handlers.d.ts +29 -8
  95. package/dist/node/handlers.d.ts.map +1 -1
  96. package/dist/node/handlers.js +148 -126
  97. package/dist/node/handlers.js.map +1 -1
  98. package/dist/node/index.d.ts +1 -1
  99. package/dist/node/index.d.ts.map +1 -1
  100. package/dist/node/index.js.map +1 -1
  101. package/dist/node/ingest-child.js +2 -2
  102. package/dist/node/ingest-child.js.map +1 -1
  103. package/dist/node/spool.d.ts +9 -5
  104. package/dist/node/spool.d.ts.map +1 -1
  105. package/dist/node/spool.js +28 -15
  106. package/dist/node/spool.js.map +1 -1
  107. package/dist/node/sse.d.ts +6 -5
  108. package/dist/node/sse.d.ts.map +1 -1
  109. package/dist/node/sse.js +8 -7
  110. package/dist/node/sse.js.map +1 -1
  111. package/dist/openai/adapter.d.ts +5 -1
  112. package/dist/openai/adapter.d.ts.map +1 -1
  113. package/dist/openai/adapter.js +53 -12
  114. package/dist/openai/adapter.js.map +1 -1
  115. package/dist/output-limit.d.ts +2 -1
  116. package/dist/output-limit.d.ts.map +1 -1
  117. package/dist/output-limit.js +5 -2
  118. package/dist/output-limit.js.map +1 -1
  119. package/dist/pdf-outline.d.ts +71 -0
  120. package/dist/pdf-outline.d.ts.map +1 -0
  121. package/dist/pdf-outline.js +414 -0
  122. package/dist/pdf-outline.js.map +1 -0
  123. package/dist/plan.d.ts +137 -7
  124. package/dist/plan.d.ts.map +1 -1
  125. package/dist/plan.js +248 -26
  126. package/dist/plan.js.map +1 -1
  127. package/dist/prepare.d.ts +50 -0
  128. package/dist/prepare.d.ts.map +1 -0
  129. package/dist/prepare.js +207 -0
  130. package/dist/prepare.js.map +1 -0
  131. package/dist/ranged.d.ts +2 -1
  132. package/dist/ranged.d.ts.map +1 -1
  133. package/dist/ranged.js +16 -3
  134. package/dist/ranged.js.map +1 -1
  135. package/dist/search.d.ts +7 -0
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +72 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/stores.d.ts +6 -0
  140. package/dist/stores.d.ts.map +1 -1
  141. package/dist/stores.js +82 -11
  142. package/dist/stores.js.map +1 -1
  143. package/dist/tools.d.ts +22 -2
  144. package/dist/tools.d.ts.map +1 -1
  145. package/dist/tools.js +323 -76
  146. package/dist/tools.js.map +1 -1
  147. package/dist/types.d.ts +49 -1
  148. package/dist/types.d.ts.map +1 -1
  149. package/dist/whole-cost.d.ts +37 -0
  150. package/dist/whole-cost.d.ts.map +1 -0
  151. package/dist/whole-cost.js +46 -0
  152. package/dist/whole-cost.js.map +1 -0
  153. package/docs/README.md +4 -0
  154. package/docs/guides/anthropic.md +5 -2
  155. package/docs/guides/conversations.md +1 -1
  156. package/docs/guides/costs-and-limits.md +132 -36
  157. package/docs/guides/deployment.md +106 -13
  158. package/docs/guides/errors-and-reliability.md +157 -45
  159. package/docs/guides/explorer-model.md +4 -1
  160. package/docs/guides/openai-compatible.md +47 -7
  161. package/docs/guides/own-adapter-and-loop.md +33 -6
  162. package/docs/guides/pdfs.md +96 -7
  163. package/docs/guides/storage.md +46 -3
  164. package/docs/guides/testing.md +71 -0
  165. package/docs/guides/vertex-and-gemini.md +159 -50
  166. package/docs/guides/web-app.md +10 -6
  167. package/docs/how-it-works.md +120 -22
  168. package/docs/measurements.md +172 -5
  169. package/docs/publishing.md +76 -4
  170. package/docs/reference/anthropic.md +12 -7
  171. package/docs/reference/ask.md +262 -35
  172. package/docs/reference/errors-and-retries.md +30 -2
  173. package/docs/reference/events.md +27 -10
  174. package/docs/reference/gemini.md +184 -68
  175. package/docs/reference/library.md +190 -23
  176. package/docs/reference/node.md +51 -17
  177. package/docs/reference/openai.md +21 -10
  178. package/docs/reference/tools.md +271 -26
  179. package/docs/security.md +101 -12
  180. package/docs/troubleshooting.md +14 -12
  181. package/docs/upgrading-0.10.md +472 -0
  182. package/package.json +5 -1
  183. package/src/access.ts +127 -4
  184. package/src/aggregate.ts +92 -14
  185. package/src/analyze.ts +2 -2
  186. package/src/answer-info.ts +45 -0
  187. package/src/anthropic/adapter.ts +40 -11
  188. package/src/ask.ts +646 -106
  189. package/src/citations.ts +294 -0
  190. package/src/error-info.ts +36 -1
  191. package/src/errors.ts +3 -1
  192. package/src/events.ts +29 -6
  193. package/src/evidence.ts +21 -2
  194. package/src/extract.ts +6 -1
  195. package/src/gemini/adapter.ts +99 -32
  196. package/src/gemini/chat.ts +53 -82
  197. package/src/gemini/endpoints.ts +89 -16
  198. package/src/gemini/errors.ts +74 -11
  199. package/src/gemini/generate.ts +147 -57
  200. package/src/gemini/index.ts +3 -3
  201. package/src/http.ts +65 -4
  202. package/src/index.ts +6 -4
  203. package/src/ingest.ts +58 -27
  204. package/src/library.ts +336 -142
  205. package/src/map-reduce.ts +855 -67
  206. package/src/model.ts +44 -4
  207. package/src/node/handlers.ts +159 -118
  208. package/src/node/index.ts +1 -0
  209. package/src/node/ingest-child.ts +2 -2
  210. package/src/node/spool.ts +28 -14
  211. package/src/node/sse.ts +8 -7
  212. package/src/openai/adapter.ts +56 -13
  213. package/src/output-limit.ts +5 -2
  214. package/src/pdf-outline.ts +400 -0
  215. package/src/plan.ts +287 -36
  216. package/src/prepare.ts +253 -0
  217. package/src/ranged.ts +16 -3
  218. package/src/search.ts +69 -13
  219. package/src/stores.ts +76 -11
  220. package/src/tools.ts +327 -75
  221. package/src/types.ts +45 -1
  222. package/src/whole-cost.ts +64 -0
package/src/ranged.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  * text the first time an older document without one is opened, and saved for next time.
6
6
  */
7
7
  import { holderOf } from "./cache.js";
8
+ import { DocumentStoreError } from "./errors.js";
8
9
  import type { Limiter } from "./limiter.js";
9
10
  import { pagesOfLines, pause, type DocumentSource, type ScanFeed, type TextChunk } from "./search.js";
10
11
  import { canSerialize, parseTextIndex, positionOf, serializeTextIndex, TextIndexBuilder, type TextIndex } from "./text-index.js";
@@ -343,11 +344,23 @@ export async function buildIndexFromStore(store: RangeStore, id: string, limiter
343
344
  }
344
345
  }
345
346
 
347
+ /**
348
+ * A read of the saved index, or of the end of the text, that failed: no saved index, so that it is
349
+ * built again from the text. Unless the store did not answer in time ("ETIMEDOUT"), or was not
350
+ * called because too many calls are stuck ("STORE_STUCK"): reading the whole text from that store
351
+ * would take longer still, and leave more calls stuck. That error is thrown (0.10.0).
352
+ */
353
+ function noSavedIndex(error: unknown): undefined {
354
+ if (DocumentStoreError.is(error) && (error.code === "ETIMEDOUT" || error.code === "STORE_STUCK")) throw error;
355
+ return undefined;
356
+ }
357
+
346
358
  /**
347
359
  * Opens a document to be read by range. Uses the saved index when there is one that fits the
348
360
  * document; otherwise builds it from the text and saves it (best effort: a store that cannot
349
361
  * write, or another server writing the same index, changes nothing). Undefined when the text is gone.
350
- * `key` is what its pieces are kept under (see `RangedDocument.key`).
362
+ * `key` is what its pieces are kept under (see `RangedDocument.key`). A store that does not answer
363
+ * in time is thrown, not taken for one without an index (`noSavedIndex`, 0.10.0).
351
364
  */
352
365
  export async function openRangedDocument(
353
366
  store: RangeStore,
@@ -357,7 +370,7 @@ export async function openRangedDocument(
357
370
  ): Promise<RangedDocument | undefined> {
358
371
  let index: TextIndex | undefined;
359
372
  if (!options.ignoreSavedIndex && store.getIndex) {
360
- const saved = await store.getIndex(meta.id).catch(() => undefined);
373
+ const saved = await store.getIndex(meta.id).catch(noSavedIndex);
361
374
  if (saved) index = parseTextIndex(saved, meta);
362
375
  // A saved index that fits the metadata may still not fit the text: another document's text,
363
376
  // written under the ID apart from its metadata and its index (two servers that ingest one ID at
@@ -365,7 +378,7 @@ export async function openRangedDocument(
365
378
  // the text must end where the index says: one byte is read across that end. Otherwise the index
366
379
  // is built again from the text, and compared with the metadata below.
367
380
  if (index && index.textBytes > 0) {
368
- const tail = await store.readTextRange(meta.id, index.textBytes - 1, index.textBytes + 1).catch(() => undefined);
381
+ const tail = await store.readTextRange(meta.id, index.textBytes - 1, index.textBytes + 1).catch(noSavedIndex);
369
382
  if (tail?.length !== 1) index = undefined;
370
383
  }
371
384
  }
package/src/search.ts CHANGED
@@ -6,6 +6,12 @@ import { composed, foldCase, LineIndex, sliceWhole } from "./text.js";
6
6
  import type { DocumentMeta, StoredDocument } from "./types.js";
7
7
 
8
8
  const MAX_OCCURRENCES_PER_TERM = 200_000;
9
+ /**
10
+ * Past this many matching lines, an exact search goes on counting them within the time of a regex
11
+ * search (`REGEX_TIME_LIMIT_MS`, or the search's own `timeLimitMs`), and stops when that is up. It
12
+ * keeps no more of them than before: the lines it shows, and the last one. Until 0.10.0 it stopped
13
+ * here, and a count of 1,200,000 lines read 1,000,000, a lower bound.
14
+ */
9
15
  const MAX_EXACT_MATCHES = 1_000_000;
10
16
  const MAX_PHRASE_PASSAGES = 10_000;
11
17
  /** The most time one regex search may spend matching. */
@@ -599,6 +605,8 @@ class LineSearch {
599
605
  private batch?: { lines: Int32Array; columns: Int32Array; keys: Array<string | undefined> };
600
606
  /** Exact mode: the scan of the piece that stopped at the end of a time slice. */
601
607
  private exactLeft?: ExactScan;
608
+ /** Exact mode: true once `MAX_EXACT_MATCHES` lines were counted, and the scan goes on within a time limit. */
609
+ private pastCap = false;
602
610
  /** The lines looked at: matches outside them are neither counted nor shown. */
603
611
  private readonly fromLine: number;
604
612
  private readonly toLine: number;
@@ -635,7 +643,7 @@ class LineSearch {
635
643
  }
636
644
  // A plain exact search runs to the end, in slices with pauses: its time follows the text, and its
637
645
  // count must be whole. Only the work that grows with each occurrence (a whole-word check, a group
638
- // key) has a limit, as a regex search does.
646
+ // key) has a limit, as a regex search does; and the lines past `MAX_EXACT_MATCHES` (`scanExact`).
639
647
  this.timeLeft = settings.timeLimitMs ?? (settings.regex ? REGEX_TIME_LIMIT_MS : settings.wholeWord || settings.groupBy ? EXACT_TIME_LIMIT_MS : Number.POSITIVE_INFINITY);
640
648
  this.lastOnes = settings.order === "last";
641
649
  if (settings.groupBy) {
@@ -842,9 +850,11 @@ class LineSearch {
842
850
  const lineText = lines.line(local);
843
851
  this.record(line, at - lines.startOf(local), lineText, this.groups?.keyOf(lineText, undefined));
844
852
  if (this.done) break;
845
- if (this.total >= MAX_EXACT_MATCHES) {
846
- this.stop();
847
- break;
853
+ if (this.total >= MAX_EXACT_MATCHES && !this.pastCap) {
854
+ // The count goes on, within the time of a regex search from here: a plain exact search
855
+ // has no limit of its own, and the lines past this many cost a step each.
856
+ this.pastCap = true;
857
+ this.timeLeft = Math.min(this.timeLeft, this.settings.timeLimitMs ?? REGEX_TIME_LIMIT_MS);
848
858
  }
849
859
  }
850
860
  at = next >= text.length ? -1 : this.find(text, next);
@@ -1152,6 +1162,55 @@ export function queryTerms(query: string): string[] {
1152
1162
 
1153
1163
  export type RankedPassage = { from: number; to: number; score: number };
1154
1164
 
1165
+ /**
1166
+ * The `count` entries of `scores` with the highest score, best first, of those `keep` keeps: what a
1167
+ * stable sort by score, then a slice, gives (of two equal scores, the one met first comes first),
1168
+ * with a heap of `count` entries in place of a sort of all of them. A keyword search of a large
1169
+ * file scores tens of thousands of passages and shows 10 at most. New in 0.10.0 (P9).
1170
+ */
1171
+ export function topScored<K>(scores: Iterable<readonly [K, number]>, count: number, keep: (key: K) => boolean = () => true): Array<[K, number]> {
1172
+ const most = Math.max(0, Math.trunc(count));
1173
+ if (most === 0) return [];
1174
+ // A heap with the worst entry kept at its root: the lowest score, and of equal scores the one met last.
1175
+ const heap: Array<{ key: K; score: number; order: number }> = [];
1176
+ const worse = (left: (typeof heap)[number], right: (typeof heap)[number]) => left.score < right.score || (left.score === right.score && left.order > right.order);
1177
+ const swap = (at: number, other: number) => {
1178
+ const entry = heap[at]!;
1179
+ heap[at] = heap[other]!;
1180
+ heap[other] = entry;
1181
+ };
1182
+ let order = 0;
1183
+ for (const [key, score] of scores) {
1184
+ if (!keep(key)) continue;
1185
+ const entry = { key, score, order: order++ };
1186
+ if (heap.length < most) {
1187
+ heap.push(entry);
1188
+ for (let at = heap.length - 1; at > 0;) {
1189
+ const parent = (at - 1) >> 1;
1190
+ if (!worse(heap[at]!, heap[parent]!)) break;
1191
+ swap(at, parent);
1192
+ at = parent;
1193
+ }
1194
+ continue;
1195
+ }
1196
+ // An entry met later is worse than one met earlier with the same score: it takes the place of
1197
+ // the worst only with a higher score.
1198
+ if (!(score > heap[0]!.score)) continue;
1199
+ heap[0] = entry;
1200
+ for (let at = 0; ;) {
1201
+ const left = 2 * at + 1;
1202
+ const right = left + 1;
1203
+ let worst = at;
1204
+ if (left < heap.length && worse(heap[left]!, heap[worst]!)) worst = left;
1205
+ if (right < heap.length && worse(heap[right]!, heap[worst]!)) worst = right;
1206
+ if (worst === at) break;
1207
+ swap(at, worst);
1208
+ at = worst;
1209
+ }
1210
+ }
1211
+ return heap.sort((left, right) => right.score - left.score || left.order - right.order).map(({ key, score }) => [key, score]);
1212
+ }
1213
+
1155
1214
  /**
1156
1215
  * BM25 over fixed passages, computed at query time from substring hits, over a document fed a
1157
1216
  * piece at a time (pieces start at passage starts). No index to build or store, works for any
@@ -1276,15 +1335,12 @@ class PassageRank {
1276
1335
  }
1277
1336
  if (this.phrase) for (const passage of this.phrase.passages) scores.set(passage, (scores.get(passage) ?? 0) * 1.5 + 1);
1278
1337
  const range = this.range;
1279
- return [...scores.entries()]
1280
- .filter(([passage]) => {
1281
- if (!range) return true;
1282
- const { from, to } = this.rangeOf(passage);
1283
- return to >= range.from && from <= range.to;
1284
- })
1285
- .sort((left, right) => right[1] - left[1])
1286
- .slice(0, topK)
1287
- .map(([passage, score]) => ({ ...this.rangeOf(passage), score: Math.round(score * 100) / 100 }));
1338
+ const inRange = (passage: number) => {
1339
+ if (!range) return true;
1340
+ const { from, to } = this.rangeOf(passage);
1341
+ return to >= range.from && from <= range.to;
1342
+ };
1343
+ return topScored(scores, topK, inRange).map(([passage, score]) => ({ ...this.rangeOf(passage), score: Math.round(score * 100) / 100 }));
1288
1344
  }
1289
1345
 
1290
1346
  private passageOf(line: number): number {
package/src/stores.ts CHANGED
@@ -235,15 +235,52 @@ async function removeFile(file: string): Promise<boolean> {
235
235
  }
236
236
  }
237
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;
265
+ }
266
+ at = end;
267
+ }
268
+ } finally {
269
+ await handle.close();
270
+ }
271
+ }
272
+
238
273
  /**
239
274
  * Writes a file whole or not at all, as other processes see it: to a temporary name first, then
240
275
  * 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.
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).
242
278
  */
243
279
  async function writeWhole(target: string, data: string | Uint8Array, mode: number): Promise<void> {
244
- const temporary = `${target}.${randomUUID().slice(0, 8)}.tmp`;
280
+ const temporary = temporaryOf(target);
245
281
  try {
246
- await writeFile(temporary, data, { mode });
282
+ if (typeof data === "string" && data.length > WRITE_SLICE_CHARACTERS) await writeSlices(temporary, data, mode);
283
+ else await writeFile(temporary, data, { mode });
247
284
  await retried(() => rename(temporary, target));
248
285
  } catch (error) {
249
286
  await rm(temporary, { force: true }).catch(() => undefined);
@@ -641,13 +678,37 @@ export class FileDocumentStore implements DocumentStore {
641
678
  }
642
679
 
643
680
  /**
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`.
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.
647
699
  */
648
700
  async #remove(place: Place, id: string): Promise<boolean> {
649
701
  const files = filesOf(place.folder, id);
650
- const existed = await removeFile(files.meta);
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);
651
712
  await Promise.allSettled([files.text, files.original, files.index].map(removeFile));
652
713
  return existed;
653
714
  }
@@ -779,14 +840,20 @@ export class FileDocumentStore implements DocumentStore {
779
840
 
780
841
  /** Sweeps the files of one ID in a folder: 1 when it removed an expired or broken document. */
781
842
  async #sweepDocument(place: Place, id: string, names: string[], now: Date, pool: Pool): Promise<number> {
843
+ const metaFile = `${id}.json`;
782
844
  const old = async (entry: string) => {
783
845
  const info = await pool(() => stat(path.join(place.folder, entry))).catch(() => undefined);
784
- return info !== undefined && now.getTime() - info.mtimeMs >= this.orphanAgeMs;
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;
785
853
  };
786
854
  // In a folder of the store's own, every file named like a document's is the store's. In one the
787
855
  // application shares, a file of an application's ID is, only when its metadata names it.
788
856
  const ours = !place.shared || DOCUMENT_ID_PATTERN.test(id);
789
- const metaFile = `${id}.json`;
790
857
  const hasMeta = names.includes(metaFile);
791
858
  if (hasMeta) {
792
859
  let raw: string | undefined;
@@ -801,8 +868,6 @@ export class FileDocumentStore implements DocumentStore {
801
868
  const known = meta !== undefined && (ours || meta.id === id);
802
869
  if (known ? expired(meta!, now) : ours && await old(metaFile)) {
803
870
  // 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
871
  return await pool(() => this.#remove(place, id)).then((existed) => (existed ? 1 : 0), () => 0);
807
872
  }
808
873
  }