llm-large-files 0.3.5 → 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 +74 -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/extract.d.ts +1 -1
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +204 -22
- package/dist/extract.js.map +1 -1
- 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/node/handlers.d.ts +9 -0
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +56 -13
- package/dist/node/handlers.js.map +1 -1
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +52 -9
- package/dist/pdf-pictures.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 +13 -4
- 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 +21 -5
- package/docs/configuration.md +50 -4
- package/docs/getting-started.md +3 -1
- package/docs/how-it-works.md +3 -1
- package/docs/security.md +8 -0
- package/package.json +7 -3
- package/src/cache.ts +83 -0
- package/src/extract.ts +198 -19
- 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/node/handlers.ts +61 -9
- package/src/pdf-pictures.ts +60 -10
- 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 +13 -4
- package/src/tools.ts +22 -16
- package/src/types.ts +15 -0
package/src/pdf-pictures.ts
CHANGED
|
@@ -42,10 +42,50 @@ const FURNITURE_SHARE = 0.3;
|
|
|
42
42
|
const DRAWING_COLOURS = 3;
|
|
43
43
|
const MAX_SHAPES = 20_000;
|
|
44
44
|
const MAX_FORM_DEPTH = 4;
|
|
45
|
+
/** Images painted on one page past which the page is marked without reading further. */
|
|
46
|
+
const MAX_IMAGES = 20_000;
|
|
47
|
+
/**
|
|
48
|
+
* Content read for one page, a form counted each time it is painted. A page of text holds a few
|
|
49
|
+
* kilobytes. A page past this paints so much that it is a drawing, and is marked: forms painted
|
|
50
|
+
* inside forms, many times over, grow to that in a few milliseconds instead of without end.
|
|
51
|
+
*/
|
|
52
|
+
const MAX_PAGE_CONTENT = 16 * 1024 * 1024;
|
|
53
|
+
/** Decoded forms kept for the whole file, so that a letterhead painted on every page is decoded once. */
|
|
54
|
+
const MAX_KEPT_FORMS = 64 * 1024 * 1024;
|
|
45
55
|
|
|
46
56
|
type Image = { id: number; box: Box };
|
|
47
57
|
type Shape = { box: Box; fill: string };
|
|
48
|
-
|
|
58
|
+
/** What a page draws. `read` counts the content run for it, forms each time they are painted. */
|
|
59
|
+
type Graphics = { images: Image[]; shapes: Shape[]; tooLarge: boolean; read: number };
|
|
60
|
+
|
|
61
|
+
/** What one reading of a file shares between its pages. */
|
|
62
|
+
type Reading = {
|
|
63
|
+
library: PdfLibrary;
|
|
64
|
+
context: PDFContext;
|
|
65
|
+
/** The content of each form, decoded once however many times and on however many pages it is painted. */
|
|
66
|
+
forms: Map<PDFObject, string | undefined>;
|
|
67
|
+
/** Characters of content in `forms`. Past `MAX_KEPT_FORMS`, a form is decoded each time instead. */
|
|
68
|
+
kept: number;
|
|
69
|
+
/** When the time for the whole file is up. */
|
|
70
|
+
deadline: number;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** The content of a form, from the forms already decoded for this file when it is there. */
|
|
74
|
+
function formContent(reading: Reading, form: PDFObject): string | undefined {
|
|
75
|
+
if (reading.forms.has(form)) return reading.forms.get(form);
|
|
76
|
+
const content = decodeContent(reading.library, reading.context, form, MAX_CONTENT_BYTES);
|
|
77
|
+
const size = content?.length ?? 0;
|
|
78
|
+
if (reading.kept + size <= MAX_KEPT_FORMS) {
|
|
79
|
+
reading.forms.set(form, content);
|
|
80
|
+
reading.kept += size;
|
|
81
|
+
}
|
|
82
|
+
return content;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** A page paints too much to be text: it is marked as showing a drawing. */
|
|
86
|
+
class PaintsTooMuch extends Error {}
|
|
87
|
+
/** The time for the whole file is up: no page is marked. */
|
|
88
|
+
class OutOfTime extends Error {}
|
|
49
89
|
|
|
50
90
|
const IDENTITY: Matrix = [1, 0, 0, 1, 0, 0];
|
|
51
91
|
/** Applies `first`, then `second`. */
|
|
@@ -69,8 +109,13 @@ const INLINE_IMAGE_END = /[\x00\t\n\f\r ]EI(?![^\x00\t\n\f\r /\[\]<>(){}%])/g;
|
|
|
69
109
|
* Runs the content of a page, or of a form it paints, and adds what it draws to `found`.
|
|
70
110
|
* It understands just enough: the matrix (q, Q, cm), paths and how they are painted, the fill
|
|
71
111
|
* colour, and Do. Text, clipping and everything else pass through unread.
|
|
112
|
+
* Throws `PaintsTooMuch` when the page paints more than a page of text can, and `OutOfTime`.
|
|
72
113
|
*/
|
|
73
|
-
function run(
|
|
114
|
+
function run(reading: Reading, content: string, resources: PDFDict | undefined, matrix: Matrix, found: Graphics, depth: number, open: Set<PDFObject>): void {
|
|
115
|
+
found.read += content.length;
|
|
116
|
+
if (found.read > MAX_PAGE_CONTENT) throw new PaintsTooMuch();
|
|
117
|
+
if (performance.now() > reading.deadline) throw new OutOfTime();
|
|
118
|
+
const { library, context } = reading;
|
|
74
119
|
const { PDFArray, PDFDict, PDFName, PDFNumber, PDFRef, PDFStream } = library;
|
|
75
120
|
const saved: Array<{ ctm: Matrix; fill: string }> = [];
|
|
76
121
|
let ctm = matrix;
|
|
@@ -208,19 +253,20 @@ function run(library: PdfLibrary, context: PDFContext, content: string, resource
|
|
|
208
253
|
if (!(object instanceof PDFStream)) break;
|
|
209
254
|
const subtype = object.dict.lookup(PDFName.of("Subtype"));
|
|
210
255
|
if (subtype === PDFName.of("Image")) {
|
|
256
|
+
if (found.images.length >= MAX_IMAGES) throw new PaintsTooMuch();
|
|
211
257
|
// An image fills the unit square of the space it is painted in.
|
|
212
258
|
const xs = [mapX(ctm, 0, 0), mapX(ctm, 1, 0), mapX(ctm, 0, 1), mapX(ctm, 1, 1)];
|
|
213
259
|
const ys = [mapY(ctm, 0, 0), mapY(ctm, 1, 0), mapY(ctm, 0, 1), mapY(ctm, 1, 1)];
|
|
214
260
|
found.images.push({ id: value instanceof PDFRef ? value.objectNumber : -1, box: [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)] });
|
|
215
261
|
} else if (subtype === PDFName.of("Form") && depth < MAX_FORM_DEPTH && !open.has(object)) {
|
|
216
|
-
const inner =
|
|
262
|
+
const inner = formContent(reading, object);
|
|
217
263
|
if (inner === undefined) break;
|
|
218
264
|
const own = object.dict.lookup(PDFName.of("Resources"));
|
|
219
265
|
const formMatrix = object.dict.lookup(PDFName.of("Matrix"));
|
|
220
266
|
const values = formMatrix instanceof PDFArray ? formMatrix.asArray().map((entry) => (entry instanceof PDFNumber ? entry.asNumber() : Number.NaN)) : [];
|
|
221
267
|
open.add(object);
|
|
222
268
|
// A form without resources of its own uses those of the content that paints it.
|
|
223
|
-
run(
|
|
269
|
+
run(reading, inner, own instanceof PDFDict ? own : resources, values.length === 6 && values.every(Number.isFinite) ? multiply(values, ctm) : ctm, found, depth + 1, open);
|
|
224
270
|
open.delete(object);
|
|
225
271
|
}
|
|
226
272
|
break;
|
|
@@ -292,11 +338,11 @@ export async function findPicturePages(bytes: Uint8Array, pages: readonly PageGe
|
|
|
292
338
|
const leaves = document.getPages();
|
|
293
339
|
if (leaves.length !== pages.length) return undefined;
|
|
294
340
|
const { context } = document;
|
|
295
|
-
const
|
|
341
|
+
const reading: Reading = { library, context, forms: new Map(), kept: 0, deadline: performance.now() + TIME_LIMIT_MS };
|
|
296
342
|
const graphics: Graphics[] = [];
|
|
297
343
|
for (const leaf of leaves) {
|
|
298
|
-
if (performance.now() > deadline) return undefined;
|
|
299
|
-
const found: Graphics = { images: [], shapes: [], tooLarge: false };
|
|
344
|
+
if (performance.now() > reading.deadline) return undefined;
|
|
345
|
+
const found: Graphics = { images: [], shapes: [], tooLarge: false, read: 0 };
|
|
300
346
|
graphics.push(found);
|
|
301
347
|
try {
|
|
302
348
|
const contents = leaf.node.Contents();
|
|
@@ -307,9 +353,13 @@ export async function findPicturePages(bytes: Uint8Array, pages: readonly PageGe
|
|
|
307
353
|
}
|
|
308
354
|
const parts = streams.map((stream) => decodeContent(library, context, stream, MAX_CONTENT_BYTES));
|
|
309
355
|
// Content that cannot be read is not guessed at: the page stays unmarked.
|
|
310
|
-
if (!parts.includes(undefined)) run(
|
|
311
|
-
} catch {
|
|
312
|
-
//
|
|
356
|
+
if (!parts.includes(undefined)) run(reading, parts.join(" "), leaf.node.Resources(), IDENTITY, found, 0, new Set());
|
|
357
|
+
} catch (error) {
|
|
358
|
+
// The time for the file is up within a page: no page is marked, as between pages.
|
|
359
|
+
if (error instanceof OutOfTime) return undefined;
|
|
360
|
+
// A page that paints more than a page of text can is a drawing. Any other trouble leaves
|
|
361
|
+
// an unusual page unmarked.
|
|
362
|
+
if (error instanceof PaintsTooMuch) found.tooLarge = true;
|
|
313
363
|
}
|
|
314
364
|
}
|
|
315
365
|
// An image painted on many pages is part of the page design, whatever its size.
|
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
|
+
}
|