llm-large-files 0.3.6 → 0.4.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.
- package/CHANGELOG.md +37 -0
- package/dist/cache.d.ts +40 -0
- package/dist/cache.d.ts.map +1 -0
- package/dist/cache.js +81 -0
- package/dist/cache.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +28 -1
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +155 -47
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +20 -0
- package/dist/limiter.d.ts.map +1 -0
- package/dist/limiter.js +55 -0
- package/dist/limiter.js.map +1 -0
- package/dist/map-reduce.d.ts +8 -4
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +65 -24
- package/dist/map-reduce.js.map +1 -1
- package/dist/plan.d.ts +7 -5
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +9 -8
- package/dist/plan.js.map +1 -1
- package/dist/ranged.d.ts +102 -0
- package/dist/ranged.d.ts.map +1 -0
- package/dist/ranged.js +314 -0
- package/dist/ranged.js.map +1 -0
- package/dist/search.d.ts +79 -15
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +388 -130
- package/dist/search.js.map +1 -1
- package/dist/stores.d.ts +22 -2
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +132 -15
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +64 -0
- package/dist/text-index.d.ts.map +1 -0
- package/dist/text-index.js +211 -0
- package/dist/text-index.js.map +1 -0
- package/dist/text.d.ts +2 -1
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +7 -1
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +2 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +20 -14
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +15 -0
- package/dist/types.d.ts.map +1 -1
- package/docs/api.md +12 -5
- package/docs/configuration.md +45 -3
- package/docs/how-it-works.md +3 -1
- package/docs/security.md +3 -0
- package/package.json +7 -3
- package/src/cache.ts +83 -0
- package/src/index.ts +1 -1
- package/src/library.ts +176 -44
- package/src/limiter.ts +51 -0
- package/src/map-reduce.ts +70 -25
- package/src/plan.ts +10 -9
- package/src/ranged.ts +348 -0
- package/src/search.ts +432 -120
- package/src/stores.ts +136 -17
- package/src/text-index.ts +228 -0
- package/src/text.ts +7 -1
- package/src/tools.ts +22 -16
- package/src/types.ts +15 -0
package/src/map-reduce.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { estimateTokens, jsonBytes } from "./text.js";
|
|
2
|
-
import
|
|
2
|
+
import { numberLines, scanSource, SearchableDocument, type DocumentSource, type TextChunk } from "./search.js";
|
|
3
3
|
import type { Budget, GenerateText, ProgressListener } from "./types.js";
|
|
4
4
|
|
|
5
5
|
const NOTHING = "NOTHING RELEVANT";
|
|
@@ -20,29 +20,73 @@ export type WholeDocumentResult = {
|
|
|
20
20
|
answerTruncated: boolean;
|
|
21
21
|
};
|
|
22
22
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
23
|
+
type Parts = Array<{ from: number; to: number }>;
|
|
24
|
+
|
|
25
|
+
/** Splits a text, fed a piece at a time, into line ranges that each fit one model request. */
|
|
26
|
+
class PartSplitter {
|
|
27
|
+
private readonly maxTokens: number;
|
|
28
|
+
private readonly maxBytes: number;
|
|
29
|
+
private readonly parts: Parts = [];
|
|
30
|
+
private from = 1;
|
|
31
|
+
private tokens = 0;
|
|
32
|
+
private bytes = 0;
|
|
33
|
+
|
|
34
|
+
constructor(budget: Budget) {
|
|
35
|
+
this.maxTokens = budget.mapChunkTokens;
|
|
36
|
+
this.maxBytes = Math.floor(budget.maxRequestBytes * 0.8);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
add(chunk: TextChunk): void {
|
|
40
|
+
for (let local = 1; local <= chunk.lines.lineCount; local++) {
|
|
41
|
+
const line = chunk.firstLine + local - 1;
|
|
42
|
+
// Count the "123| " prefix each line carries in the prompt.
|
|
43
|
+
const text = `${line}| ${chunk.lines.line(local)}\n`;
|
|
44
|
+
const lineTokens = estimateTokens(text);
|
|
45
|
+
const lineBytes = jsonBytes(text);
|
|
46
|
+
if (line > this.from && (this.tokens + lineTokens > this.maxTokens || this.bytes + lineBytes > this.maxBytes)) {
|
|
47
|
+
this.parts.push({ from: this.from, to: line - 1 });
|
|
48
|
+
this.from = line;
|
|
49
|
+
this.tokens = 0;
|
|
50
|
+
this.bytes = 0;
|
|
51
|
+
}
|
|
52
|
+
this.tokens += lineTokens;
|
|
53
|
+
this.bytes += lineBytes;
|
|
41
54
|
}
|
|
42
|
-
tokens += lineTokens;
|
|
43
|
-
bytes += lineBytes;
|
|
44
55
|
}
|
|
45
|
-
|
|
56
|
+
|
|
57
|
+
finish(lineCount: number): Parts {
|
|
58
|
+
if (lineCount >= this.from) this.parts.push({ from: this.from, to: lineCount });
|
|
59
|
+
return this.parts;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Splits a document held in memory into line ranges that each fit one model request. */
|
|
64
|
+
export function splitIntoParts(document: SearchableDocument, budget: Budget): Parts {
|
|
65
|
+
const splitter = new PartSplitter(budget);
|
|
66
|
+
splitter.add(document.wholeChunk());
|
|
67
|
+
return splitter.finish(document.lines.lineCount);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Parts already worked out, by document and budget: counting them reads the whole text. */
|
|
71
|
+
const knownParts = new WeakMap<DocumentSource, Map<string, Parts>>();
|
|
72
|
+
|
|
73
|
+
/** `splitIntoParts` for any document, worked out once per document object and budget. */
|
|
74
|
+
export async function partsOf(source: DocumentSource, budget: Budget, signal?: AbortSignal): Promise<Parts> {
|
|
75
|
+
const key = `${budget.mapChunkTokens}|${budget.maxRequestBytes}`;
|
|
76
|
+
const known = knownParts.get(source)?.get(key);
|
|
77
|
+
if (known) return known;
|
|
78
|
+
let parts: Parts;
|
|
79
|
+
if (source instanceof SearchableDocument) {
|
|
80
|
+
parts = splitIntoParts(source, budget);
|
|
81
|
+
} else {
|
|
82
|
+
const splitter = new PartSplitter(budget);
|
|
83
|
+
await scanSource(source, (chunk) => {
|
|
84
|
+
splitter.add(chunk);
|
|
85
|
+
}, signal);
|
|
86
|
+
parts = splitter.finish(source.lineCount);
|
|
87
|
+
}
|
|
88
|
+
if (!knownParts.has(source)) knownParts.set(source, new Map());
|
|
89
|
+
knownParts.get(source)!.set(key, parts);
|
|
46
90
|
return parts;
|
|
47
91
|
}
|
|
48
92
|
|
|
@@ -88,7 +132,7 @@ async function ask(
|
|
|
88
132
|
* then the notes are combined ("reduce"), in several rounds if the notes are still too large.
|
|
89
133
|
*/
|
|
90
134
|
export async function analyzeWholeDocument(options: {
|
|
91
|
-
document:
|
|
135
|
+
document: DocumentSource;
|
|
92
136
|
task: string;
|
|
93
137
|
generate: GenerateText;
|
|
94
138
|
budget: Budget;
|
|
@@ -98,7 +142,7 @@ export async function analyzeWholeDocument(options: {
|
|
|
98
142
|
}): Promise<WholeDocumentResult> {
|
|
99
143
|
const { document, task, generate, budget, onProgress, signal } = options;
|
|
100
144
|
const name = document.meta.name;
|
|
101
|
-
const parts =
|
|
145
|
+
const parts = await partsOf(document, budget, signal);
|
|
102
146
|
if (parts.length > budget.maxMapChunks) {
|
|
103
147
|
throw new Error(`Reading all of ${name} needs ${parts.length} model calls, over the limit of ${budget.maxMapChunks}. Use search_document to narrow the question first.`);
|
|
104
148
|
}
|
|
@@ -112,6 +156,7 @@ export async function analyzeWholeDocument(options: {
|
|
|
112
156
|
let text: string;
|
|
113
157
|
let read = true;
|
|
114
158
|
try {
|
|
159
|
+
const part = numberLines(await document.readLines(from, to), from);
|
|
115
160
|
const reply = await ask(generate, {
|
|
116
161
|
system: "You read one part of a larger document and take notes for a later step that combines the notes from every part.",
|
|
117
162
|
prompt: [
|
|
@@ -121,7 +166,7 @@ export async function analyzeWholeDocument(options: {
|
|
|
121
166
|
`Write concise notes on everything in this part that is relevant to the task. Keep exact names, numbers, and quotes that matter. Cite line numbers like (L123). If nothing in this part is relevant, reply exactly: ${NOTHING}`,
|
|
122
167
|
"",
|
|
123
168
|
"<part>",
|
|
124
|
-
|
|
169
|
+
part,
|
|
125
170
|
"</part>",
|
|
126
171
|
].join("\n"),
|
|
127
172
|
maxOutputTokens: PART_OUTPUT_TOKENS,
|
package/src/plan.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { Budget, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
|
|
2
|
-
import type { SearchableDocument } from "./search.js";
|
|
3
2
|
|
|
4
3
|
/** Bytes kept free for document cards, the tool declarations, and JSON framing. */
|
|
5
4
|
export const REQUEST_BYTES_MARGIN = 256 * 1024;
|
|
@@ -50,17 +49,19 @@ export function outlineLines(outline: OutlineEntry[]): string[] {
|
|
|
50
49
|
return outline.map((entry) => `L${entry.line} ${" ".repeat(entry.level - top)}${entry.title}`);
|
|
51
50
|
}
|
|
52
51
|
|
|
53
|
-
export function renderInline(
|
|
54
|
-
|
|
55
|
-
return `--- Attached file: ${meta.name} (${meta.format}, ${meta.lines.toLocaleString("en-US")} lines) ---\n${document.text}\n--- End attached file: ${meta.name} ---`;
|
|
52
|
+
export function renderInline(meta: DocumentMeta, text: string): string {
|
|
53
|
+
return `--- Attached file: ${meta.name} (${meta.format}, ${meta.lines.toLocaleString("en-US")} lines) ---\n${text}\n--- End attached file: ${meta.name} ---`;
|
|
56
54
|
}
|
|
57
55
|
|
|
56
|
+
/** How many lines of a file its card shows. */
|
|
57
|
+
export const CARD_LINES = CARD_HEAD_LINES;
|
|
58
|
+
|
|
58
59
|
/**
|
|
59
|
-
* A compact stand-in for a document that is too large for the prompt. `
|
|
60
|
-
* saying that its pages can be looked at
|
|
60
|
+
* A compact stand-in for a document that is too large for the prompt. `head` is its first
|
|
61
|
+
* `CARD_LINES` lines, numbered. `viewable` adds a line saying that its pages can be looked at
|
|
62
|
+
* with `view_pages`.
|
|
61
63
|
*/
|
|
62
|
-
export function renderCard(
|
|
63
|
-
const { meta } = document;
|
|
64
|
+
export function renderCard(meta: DocumentMeta, head: string, viewable = false): string {
|
|
64
65
|
const out = [
|
|
65
66
|
`--- Large attached file: ${meta.name} ---`,
|
|
66
67
|
`document_id: ${meta.id}`,
|
|
@@ -82,7 +83,7 @@ export function renderCard(document: SearchableDocument, viewable = false): stri
|
|
|
82
83
|
out.push(`Outline (${Math.min(meta.outline.length, CARD_OUTLINE_ENTRIES)} of ${meta.outline.length} headings):`);
|
|
83
84
|
out.push(...outlineLines(meta.outline.slice(0, CARD_OUTLINE_ENTRIES)).map((line) => ` ${line}`));
|
|
84
85
|
}
|
|
85
|
-
out.push(`First lines:`,
|
|
86
|
+
out.push(`First lines:`, head.split("\n").map((line) => ` ${line.slice(0, 300)}`).join("\n"));
|
|
86
87
|
out.push(`--- End large attached file: ${meta.name} ---`);
|
|
87
88
|
return out.join("\n");
|
|
88
89
|
}
|
package/src/ranged.ts
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A document read from the store a range at a time, for stores that can (`readTextRange`): a tool
|
|
3
|
+
* call reads the lines it needs, and a search reads the text in pieces, so no call holds a whole
|
|
4
|
+
* large file in memory. The line index comes from the store (`getIndex`), or is built from the
|
|
5
|
+
* text the first time an older document without one is opened, and saved for next time.
|
|
6
|
+
*/
|
|
7
|
+
import type { Limiter } from "./limiter.js";
|
|
8
|
+
import { pagesOfLines, type DocumentSource, type TextChunk } from "./search.js";
|
|
9
|
+
import { canSerialize, parseTextIndex, positionOf, serializeTextIndex, TextIndexBuilder, type TextIndex } from "./text-index.js";
|
|
10
|
+
import { foldCase, LineIndex } from "./text.js";
|
|
11
|
+
import type { DocumentMeta, DocumentStore } from "./types.js";
|
|
12
|
+
|
|
13
|
+
export type RangeStore = Pick<DocumentStore, "getIndex" | "putIndex"> & Required<Pick<DocumentStore, "readTextRange">>;
|
|
14
|
+
|
|
15
|
+
export type ScanSettings = {
|
|
16
|
+
/** About this many bytes of text are read and searched at a time. */
|
|
17
|
+
chunkBytes: number;
|
|
18
|
+
/** Bounds how many scans of whole documents run at once. */
|
|
19
|
+
limiter: Limiter;
|
|
20
|
+
/** Told when the stored text of a document did not agree with its index. */
|
|
21
|
+
onBroken?: (id: string) => void;
|
|
22
|
+
/**
|
|
23
|
+
* Where decoded pieces of frequently searched documents are kept, within the cache's memory
|
|
24
|
+
* limit, so that the next search of them reads and decodes nothing. A document whose decoded
|
|
25
|
+
* text would take more than `maxDocumentBytes` is never kept: one scan of it would push out
|
|
26
|
+
* everything else.
|
|
27
|
+
*/
|
|
28
|
+
pieces?: PieceCache;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** A piece of text kept in memory, and what it takes. */
|
|
32
|
+
export type CachedPiece = TextChunk & { readonly memoryBytes: number };
|
|
33
|
+
|
|
34
|
+
export type PieceCache = {
|
|
35
|
+
get(key: string, version: string): CachedPiece | undefined;
|
|
36
|
+
set(key: string, version: string, piece: CachedPiece): void;
|
|
37
|
+
maxDocumentBytes: number;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** The cache key of piece `at` of a document. All of them start with `${id}#`. */
|
|
41
|
+
export const pieceKey = (id: string, at: number) => `${id}#${at}`;
|
|
42
|
+
|
|
43
|
+
/** Bytes read at a time to build an index from the text. */
|
|
44
|
+
const BUILD_READ_BYTES = 4 * 1024 * 1024;
|
|
45
|
+
/** A pass shared by several scans lets other work run after this much time on the main thread. */
|
|
46
|
+
const YIELD_AFTER_MS = 15;
|
|
47
|
+
const decoder = new TextDecoder("utf-8");
|
|
48
|
+
|
|
49
|
+
const gone = (id: string) => new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
|
|
50
|
+
|
|
51
|
+
/** A scan of a document: fed the pieces in order until it says it is done. */
|
|
52
|
+
type Consumer = { feed: (chunk: TextChunk) => boolean | void; done: boolean; settle: (error?: unknown) => void };
|
|
53
|
+
|
|
54
|
+
export class RangedDocument implements DocumentSource {
|
|
55
|
+
/**
|
|
56
|
+
* Set when the stored text did not agree with the index. The library then drops this object and
|
|
57
|
+
* opens the document again, building its index from the text.
|
|
58
|
+
*/
|
|
59
|
+
broken = false;
|
|
60
|
+
|
|
61
|
+
/** The version its pieces are kept under, and whether they are kept at all. */
|
|
62
|
+
private readonly pieceVersion: string;
|
|
63
|
+
private readonly keepPieces: boolean;
|
|
64
|
+
private ranges?: Array<{ firstLine: number; lastLine: number; start: number; end: number }>;
|
|
65
|
+
|
|
66
|
+
constructor(
|
|
67
|
+
private readonly store: RangeStore,
|
|
68
|
+
readonly meta: DocumentMeta,
|
|
69
|
+
readonly index: TextIndex,
|
|
70
|
+
private readonly settings: ScanSettings,
|
|
71
|
+
) {
|
|
72
|
+
this.pieceVersion = `${meta.createdAt}|${index.textBytes}|${index.characters}|${settings.chunkBytes}`;
|
|
73
|
+
// Decoded text is one byte a character when it is all ASCII, two otherwise; and its lowercased copy as much again.
|
|
74
|
+
const decoded = index.characters * (index.textBytes === index.characters ? 1 : 2) * 2 + index.characterStarts.byteLength;
|
|
75
|
+
this.keepPieces = settings.pieces !== undefined && decoded <= settings.pieces.maxDocumentBytes;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
get lineCount(): number {
|
|
79
|
+
return this.index.lineCount;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
get characters(): number {
|
|
83
|
+
return this.index.characters;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
get passageStarts(): ArrayLike<number> {
|
|
87
|
+
return this.index.passageStarts;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
get memoryBytes(): number {
|
|
91
|
+
const { lineStarts, characterStarts, passageStarts, pageStarts } = this.index;
|
|
92
|
+
return lineStarts.byteLength + characterStarts.byteLength + passageStarts.byteLength + pageStarts.byteLength + 2_048;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
pageOfLine(line: number): number | undefined {
|
|
96
|
+
const starts = this.index.pageStarts;
|
|
97
|
+
return starts.length === 0 || line < starts[0]! ? undefined : positionOf(starts, line);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
pagesOfLines(from: number, to: number): string | undefined {
|
|
101
|
+
return pagesOfLines(this.index.pageStarts, from, to);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async readLines(from: number, to: number): Promise<string[]> {
|
|
105
|
+
const first = Math.max(1, from);
|
|
106
|
+
const last = Math.min(to, this.index.lineCount);
|
|
107
|
+
if (first > last) return [];
|
|
108
|
+
const text = await this.read(...this.bytesOf(first, last));
|
|
109
|
+
const lines = (text.endsWith("\n") ? text.slice(0, -1) : text).split("\n");
|
|
110
|
+
if (lines.length !== last - first + 1) throw this.mismatch();
|
|
111
|
+
return lines;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async readText(): Promise<string> {
|
|
115
|
+
const text = await this.read(0, this.index.textBytes);
|
|
116
|
+
if (text.length !== this.index.characters) throw this.mismatch();
|
|
117
|
+
return text;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The text in pieces of whole passages, about `chunkBytes` each. A scan waits for a slot of the
|
|
122
|
+
* limiter first, and holds it until it ends or is abandoned. `scan` does the same for several
|
|
123
|
+
* scans at once.
|
|
124
|
+
*/
|
|
125
|
+
async *chunks(signal?: AbortSignal): AsyncGenerator<TextChunk> {
|
|
126
|
+
const release = await this.settings.limiter.acquire(signal);
|
|
127
|
+
try {
|
|
128
|
+
for await (const chunk of this.pieces()) {
|
|
129
|
+
signal?.throwIfAborted();
|
|
130
|
+
yield chunk;
|
|
131
|
+
}
|
|
132
|
+
} finally {
|
|
133
|
+
release();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Feeds the text, a piece at a time and in order, to `feed` until it returns true or the text
|
|
139
|
+
* ends. Scans asked for while others of this document wait for a slot of the limiter join them:
|
|
140
|
+
* the pieces are then read, decoded and lowercased once, for all of them. A scan asked for once
|
|
141
|
+
* the pass has started waits for the next one, since every scan must see the text from the start.
|
|
142
|
+
*/
|
|
143
|
+
scan(feed: (chunk: TextChunk) => boolean | void, signal?: AbortSignal): Promise<void> {
|
|
144
|
+
return new Promise<void>((resolve, reject) => {
|
|
145
|
+
if (signal?.aborted) {
|
|
146
|
+
reject(signal.reason);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
const onAbort = () => consumer.settle(signal!.reason);
|
|
150
|
+
const consumer: Consumer = {
|
|
151
|
+
feed,
|
|
152
|
+
done: false,
|
|
153
|
+
settle: (error?: unknown) => {
|
|
154
|
+
if (consumer.done) return;
|
|
155
|
+
consumer.done = true;
|
|
156
|
+
signal?.removeEventListener("abort", onAbort);
|
|
157
|
+
if (error === undefined) resolve();
|
|
158
|
+
else reject(error);
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
162
|
+
if (this.gathering) {
|
|
163
|
+
this.gathering.push(consumer);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const group = [consumer];
|
|
167
|
+
this.gathering = group;
|
|
168
|
+
void this.pass(group);
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Scans waiting for a slot, open to more of them. */
|
|
173
|
+
private gathering: Consumer[] | undefined;
|
|
174
|
+
|
|
175
|
+
private async pass(group: Consumer[]): Promise<void> {
|
|
176
|
+
const release = await this.settings.limiter.acquire();
|
|
177
|
+
// From here on the group is closed.
|
|
178
|
+
if (this.gathering === group) this.gathering = undefined;
|
|
179
|
+
try {
|
|
180
|
+
if (group.every((consumer) => consumer.done)) return;
|
|
181
|
+
let slice = performance.now();
|
|
182
|
+
for await (const chunk of this.pieces()) {
|
|
183
|
+
let open = 0;
|
|
184
|
+
for (const consumer of group) {
|
|
185
|
+
if (consumer.done) continue;
|
|
186
|
+
try {
|
|
187
|
+
if (consumer.feed(chunk) === true) consumer.settle();
|
|
188
|
+
else open++;
|
|
189
|
+
} catch (error) {
|
|
190
|
+
consumer.settle(error);
|
|
191
|
+
}
|
|
192
|
+
// Many scans on one piece add up: give other work (answers streaming to other users) a turn.
|
|
193
|
+
if (performance.now() - slice > YIELD_AFTER_MS) {
|
|
194
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
195
|
+
slice = performance.now();
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (open === 0) break;
|
|
199
|
+
}
|
|
200
|
+
for (const consumer of group) consumer.settle();
|
|
201
|
+
} catch (error) {
|
|
202
|
+
for (const consumer of group) consumer.settle(error);
|
|
203
|
+
} finally {
|
|
204
|
+
release();
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The pieces, in order: kept ones from memory, the others read and decoded, the next one read
|
|
210
|
+
* while the current one is used. Line breaks are where the index says, which each piece read is
|
|
211
|
+
* checked against.
|
|
212
|
+
*/
|
|
213
|
+
private async *pieces(): AsyncGenerator<TextChunk> {
|
|
214
|
+
const count = this.chunkRanges().length;
|
|
215
|
+
const load = (at: number) => {
|
|
216
|
+
const promise = this.piece(at);
|
|
217
|
+
// Read ahead: if the scan stops before it needs this piece, nobody waits for it.
|
|
218
|
+
promise.catch(() => undefined);
|
|
219
|
+
return promise;
|
|
220
|
+
};
|
|
221
|
+
let next = count > 0 ? load(0) : undefined;
|
|
222
|
+
for (let at = 0; at < count; at++) {
|
|
223
|
+
const chunk = await next!;
|
|
224
|
+
next = at + 1 < count ? load(at + 1) : undefined;
|
|
225
|
+
yield chunk;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Piece `at`, from memory when it is kept there. */
|
|
230
|
+
private async piece(at: number): Promise<TextChunk> {
|
|
231
|
+
const cache = this.keepPieces ? this.settings.pieces : undefined;
|
|
232
|
+
const kept = cache?.get(pieceKey(this.meta.id, at), this.pieceVersion);
|
|
233
|
+
if (kept) return kept;
|
|
234
|
+
const { firstLine, lastLine, start, end } = this.chunkRanges()[at]!;
|
|
235
|
+
const text = await this.read(start, end);
|
|
236
|
+
const { characterStarts, characters, lineCount } = this.index;
|
|
237
|
+
const startCharacter = characterStarts[firstLine - 1]!;
|
|
238
|
+
const endCharacter = lastLine < lineCount ? characterStarts[lastLine]! : characters;
|
|
239
|
+
if (text.length !== endCharacter - startCharacter) throw this.mismatch();
|
|
240
|
+
const starts = new Uint32Array(lastLine - firstLine + 1);
|
|
241
|
+
for (let line = 0; line < starts.length; line++) {
|
|
242
|
+
const lineStart = characterStarts[firstLine - 1 + line]! - startCharacter;
|
|
243
|
+
// Each line but the first starts right after a line break.
|
|
244
|
+
if (line > 0 && text.charCodeAt(lineStart - 1) !== 10) throw this.mismatch();
|
|
245
|
+
starts[line] = lineStart;
|
|
246
|
+
}
|
|
247
|
+
if (lastLine < lineCount && text.charCodeAt(text.length - 1) !== 10) throw this.mismatch();
|
|
248
|
+
let lower: string | undefined;
|
|
249
|
+
const ascii = end - start === text.length;
|
|
250
|
+
const piece: CachedPiece = {
|
|
251
|
+
firstLine,
|
|
252
|
+
startCharacter,
|
|
253
|
+
text,
|
|
254
|
+
lines: new LineIndex(text, starts),
|
|
255
|
+
lower: () => (lower ??= foldCase(text)),
|
|
256
|
+
// The text and, once a search needs it, its lowercased copy.
|
|
257
|
+
memoryBytes: text.length * (ascii ? 1 : 2) * 2 + starts.byteLength + 256,
|
|
258
|
+
};
|
|
259
|
+
cache?.set(pieceKey(this.meta.id, at), this.pieceVersion, piece);
|
|
260
|
+
return piece;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** The bytes of lines `first` to `last`, which must exist. */
|
|
264
|
+
private bytesOf(first: number, last: number): [number, number] {
|
|
265
|
+
const { lineStarts, lineCount, textBytes } = this.index;
|
|
266
|
+
return [lineStarts[first - 1]!, last < lineCount ? lineStarts[last]! : textBytes];
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Line ranges of whole passages, each about `chunkBytes` (one passage at least). */
|
|
270
|
+
private chunkRanges(): Array<{ firstLine: number; lastLine: number; start: number; end: number }> {
|
|
271
|
+
if (this.ranges) return this.ranges;
|
|
272
|
+
const { passageStarts, lineStarts, lineCount, textBytes } = this.index;
|
|
273
|
+
const ranges: Array<{ firstLine: number; lastLine: number; start: number; end: number }> = [];
|
|
274
|
+
for (let passage = 0; passage < passageStarts.length;) {
|
|
275
|
+
const firstLine = passageStarts[passage]!;
|
|
276
|
+
const start = lineStarts[firstLine - 1]!;
|
|
277
|
+
let next = passage + 1;
|
|
278
|
+
while (next < passageStarts.length && lineStarts[passageStarts[next]! - 1]! - start < this.settings.chunkBytes) next++;
|
|
279
|
+
const end = next < passageStarts.length ? lineStarts[passageStarts[next]! - 1]! : textBytes;
|
|
280
|
+
ranges.push({ firstLine, lastLine: next < passageStarts.length ? passageStarts[next]! - 1 : lineCount, start, end });
|
|
281
|
+
passage = next;
|
|
282
|
+
}
|
|
283
|
+
this.ranges = ranges;
|
|
284
|
+
return ranges;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
private async read(start: number, end: number): Promise<string> {
|
|
288
|
+
const bytes = await this.store.readTextRange(this.meta.id, start, end);
|
|
289
|
+
if (!bytes) throw gone(this.meta.id);
|
|
290
|
+
if (bytes.length !== end - start) throw this.mismatch();
|
|
291
|
+
return decoder.decode(bytes);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
private mismatch(): Error {
|
|
295
|
+
if (!this.broken) {
|
|
296
|
+
this.broken = true;
|
|
297
|
+
this.settings.onBroken?.(this.meta.id);
|
|
298
|
+
}
|
|
299
|
+
return new Error(`The stored text of ${this.meta.name} did not match its index. Try the call again.`);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Builds the index of a stored text by reading all of it once. Undefined when the text is gone. */
|
|
304
|
+
export async function buildIndexFromStore(store: RangeStore, id: string, limiter: Limiter): Promise<TextIndex | undefined> {
|
|
305
|
+
const release = await limiter.acquire();
|
|
306
|
+
try {
|
|
307
|
+
const builder = new TextIndexBuilder();
|
|
308
|
+
for (let position = 0; ;) {
|
|
309
|
+
const bytes = await store.readTextRange(id, position, position + BUILD_READ_BYTES);
|
|
310
|
+
if (!bytes) return undefined;
|
|
311
|
+
builder.push(bytes);
|
|
312
|
+
position += bytes.length;
|
|
313
|
+
if (bytes.length < BUILD_READ_BYTES) break;
|
|
314
|
+
}
|
|
315
|
+
const index = builder.finish();
|
|
316
|
+
return index.lineCount > 0 ? index : undefined;
|
|
317
|
+
} finally {
|
|
318
|
+
release();
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Opens a document to be read by range. Uses the saved index when there is one that fits the
|
|
324
|
+
* document; otherwise builds it from the text and saves it (best effort: a store that cannot
|
|
325
|
+
* write, or another server writing the same index, changes nothing). Undefined when the text is gone.
|
|
326
|
+
*/
|
|
327
|
+
export async function openRangedDocument(
|
|
328
|
+
store: RangeStore,
|
|
329
|
+
meta: DocumentMeta,
|
|
330
|
+
settings: ScanSettings,
|
|
331
|
+
options: { ignoreSavedIndex?: boolean } = {},
|
|
332
|
+
): Promise<RangedDocument | undefined> {
|
|
333
|
+
let index: TextIndex | undefined;
|
|
334
|
+
if (!options.ignoreSavedIndex && store.getIndex) {
|
|
335
|
+
const saved = await store.getIndex(meta.id).catch(() => undefined);
|
|
336
|
+
if (saved) index = parseTextIndex(saved, meta);
|
|
337
|
+
}
|
|
338
|
+
if (!index) {
|
|
339
|
+
index = await buildIndexFromStore(store, meta.id, settings.limiter);
|
|
340
|
+
if (!index) return undefined;
|
|
341
|
+
// An index that disagrees with the metadata describes a text that is not what was ingested.
|
|
342
|
+
// It is used, since it is what the store holds, but not saved.
|
|
343
|
+
if (store.putIndex && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters) {
|
|
344
|
+
await store.putIndex(meta.id, serializeTextIndex(index)).catch(() => undefined);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return new RangedDocument(store, meta, index, settings);
|
|
348
|
+
}
|