llm-large-files 0.7.0 → 0.8.1
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 +370 -1
- package/README.md +12 -8
- package/dist/aggregate.d.ts +103 -0
- package/dist/aggregate.d.ts.map +1 -0
- package/dist/aggregate.js +651 -0
- package/dist/aggregate.js.map +1 -0
- package/dist/analyze.d.ts +3 -1
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +109 -14
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +4 -1
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +3 -3
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +72 -17
- package/dist/ask.js.map +1 -1
- package/dist/decode.d.ts +19 -0
- package/dist/decode.d.ts.map +1 -0
- package/dist/decode.js +97 -0
- package/dist/decode.js.map +1 -0
- package/dist/errors.d.ts +55 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +65 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +6 -0
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +5 -1
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +23 -0
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +12 -18
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +82 -746
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +9 -5
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +5 -1
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +11 -2
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +20 -3
- package/dist/gemini/generate.js.map +1 -1
- package/dist/groups.d.ts +54 -0
- package/dist/groups.d.ts.map +1 -0
- package/dist/groups.js +136 -0
- package/dist/groups.js.map +1 -0
- package/dist/html.d.ts +11 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +1112 -0
- package/dist/html.js.map +1 -0
- package/dist/index.d.ts +2 -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.map +1 -1
- package/dist/library.js +57 -14
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -1
- package/dist/limiter.d.ts.map +1 -1
- package/dist/limiter.js +3 -2
- package/dist/limiter.js.map +1 -1
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +8 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +69 -15
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +38 -0
- package/dist/node/ingest-child.d.ts.map +1 -0
- package/dist/node/ingest-child.js +42 -0
- package/dist/node/ingest-child.js.map +1 -0
- package/dist/node/isolated.d.ts +88 -0
- package/dist/node/isolated.d.ts.map +1 -0
- package/dist/node/isolated.js +381 -0
- package/dist/node/isolated.js.map +1 -0
- package/dist/office.d.ts +105 -0
- package/dist/office.d.ts.map +1 -0
- package/dist/office.js +1092 -0
- package/dist/office.js.map +1 -0
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +15 -1
- package/dist/openai/adapter.js.map +1 -1
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +2 -6
- package/dist/pdf-pages.js.map +1 -1
- package/dist/peers.d.ts +8 -0
- package/dist/peers.d.ts.map +1 -0
- package/dist/peers.js +32 -0
- package/dist/peers.js.map +1 -0
- package/dist/plan.d.ts +3 -1
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +17 -1
- package/dist/plan.js.map +1 -1
- package/dist/quality.d.ts +16 -0
- package/dist/quality.d.ts.map +1 -0
- package/dist/quality.js +157 -0
- package/dist/quality.js.map +1 -0
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +4 -2
- package/dist/ranged.js.map +1 -1
- package/dist/search.d.ts +99 -22
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +744 -140
- package/dist/search.js.map +1 -1
- package/dist/text-index.d.ts +3 -1
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +3 -1
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +27 -3
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +225 -23
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +9 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +457 -16
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +23 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/word-styles.d.ts +102 -0
- package/dist/word-styles.d.ts.map +1 -0
- package/dist/word-styles.js +419 -0
- package/dist/word-styles.js.map +1 -0
- package/dist/xlsx.d.ts +23 -0
- package/dist/xlsx.d.ts.map +1 -0
- package/dist/xlsx.js +511 -0
- package/dist/xlsx.js.map +1 -0
- package/dist/xml-stream.d.ts +55 -0
- package/dist/xml-stream.d.ts.map +1 -0
- package/dist/xml-stream.js +235 -0
- package/dist/xml-stream.js.map +1 -0
- package/docs/README.md +8 -8
- package/docs/getting-started.md +1 -1
- package/docs/guides/costs-and-limits.md +7 -5
- package/docs/guides/deployment.md +95 -29
- package/docs/guides/errors-and-reliability.md +23 -10
- package/docs/guides/pdfs.md +127 -74
- package/docs/guides/storage.md +1 -1
- package/docs/guides/testing.md +5 -1
- package/docs/guides/web-app.md +10 -9
- package/docs/how-it-works.md +80 -50
- package/docs/reference/ask.md +26 -8
- package/docs/reference/errors-and-retries.md +5 -3
- package/docs/reference/events.md +14 -6
- package/docs/reference/gemini.md +6 -2
- package/docs/reference/library.md +221 -79
- package/docs/reference/node.md +201 -23
- package/docs/reference/openai.md +1 -1
- package/docs/reference/tools.md +269 -23
- package/docs/security.md +114 -69
- package/docs/troubleshooting.md +40 -20
- package/package.json +6 -2
- package/src/aggregate.ts +674 -0
- package/src/analyze.ts +117 -13
- package/src/anthropic/adapter.ts +4 -1
- package/src/ask.ts +73 -17
- package/src/decode.ts +89 -0
- package/src/errors.ts +108 -0
- package/src/events.ts +10 -1
- package/src/evidence.ts +23 -0
- package/src/extract.ts +79 -701
- package/src/gemini/adapter.ts +9 -5
- package/src/gemini/endpoints.ts +12 -2
- package/src/gemini/generate.ts +19 -3
- package/src/groups.ts +162 -0
- package/src/html.ts +1071 -0
- package/src/index.ts +2 -1
- package/src/library.ts +52 -14
- package/src/limiter.ts +6 -1
- package/src/model.ts +8 -1
- package/src/node/handlers.ts +66 -16
- package/src/node/index.ts +2 -0
- package/src/node/ingest-child.ts +61 -0
- package/src/node/isolated.ts +464 -0
- package/src/office.ts +1047 -0
- package/src/openai/adapter.ts +14 -1
- package/src/pdf-pages.ts +2 -5
- package/src/peers.ts +29 -0
- package/src/plan.ts +19 -1
- package/src/quality.ts +146 -0
- package/src/ranged.ts +4 -2
- package/src/search.ts +738 -146
- package/src/text-index.ts +4 -2
- package/src/text.ts +214 -23
- package/src/tools.ts +440 -16
- package/src/types.ts +20 -3
- package/src/word-styles.ts +420 -0
- package/src/xlsx.ts +478 -0
- package/src/xml-stream.ts +224 -0
package/src/index.ts
CHANGED
|
@@ -53,7 +53,8 @@ export { parseSseJson, SseEventTooLongError } from "./sse.js";
|
|
|
53
53
|
export type { SseHooks } from "./sse.js";
|
|
54
54
|
export { DEFAULT_FIRST_BYTE_TIMEOUT_MS, DEFAULT_IDLE_TIMEOUT_MS } from "./http.js";
|
|
55
55
|
export type { IdleWaits } from "./http.js";
|
|
56
|
-
export { DocumentStoreError } from "./errors.js";
|
|
56
|
+
export { DocumentStoreError, IngestError, ingestErrorCodeOf } from "./errors.js";
|
|
57
|
+
export type { IngestErrorCode } from "./errors.js";
|
|
57
58
|
export { FileDocumentStore, MemoryDocumentStore, DOCUMENT_ID_PATTERN } from "./stores.js";
|
|
58
59
|
export { createPdfExtractor, defaultExtractors, detectFormat } from "./extract.js";
|
|
59
60
|
export type { PdfExtractorOptions } from "./extract.js";
|
package/src/library.ts
CHANGED
|
@@ -2,12 +2,13 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { buildLogProfileInSlices, buildOutlineInSlices, looksLikeLog } from "./analyze.js";
|
|
3
3
|
import { givenBudget, resolveBudget, type ModelLimits } from "./budget.js";
|
|
4
4
|
import { DocumentCache, documentVersion, type Sized } from "./cache.js";
|
|
5
|
-
import { DocumentStoreError, noteStoreWriteFailure } from "./errors.js";
|
|
5
|
+
import { DocumentStoreError, isStoreWriteFailure, noteStoreWriteFailure, toIngestError } from "./errors.js";
|
|
6
6
|
import { EventEmitter, eventErrorOf, newRunId, type IngestEvent, type IngestStage } from "./events.js";
|
|
7
7
|
import { detectFormat, extractText } from "./extract.js";
|
|
8
8
|
import { Limiter } from "./limiter.js";
|
|
9
9
|
import { TimeSlicer } from "./pause.js";
|
|
10
|
-
import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline, type WholeRead } from "./plan.js";
|
|
10
|
+
import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline, TABLE_FORMATS, type WholeRead } from "./plan.js";
|
|
11
|
+
import { measureQuality, type TextQuality } from "./quality.js";
|
|
11
12
|
import { openRangedDocument, pieceKey, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
|
|
12
13
|
import { numberLines, SearchableDocument, type DocumentSource } from "./search.js";
|
|
13
14
|
import { DOCUMENT_ID_PATTERN } from "./stores.js";
|
|
@@ -477,6 +478,19 @@ class IngestProgress {
|
|
|
477
478
|
/** Default for `wholeDocumentBytes`. */
|
|
478
479
|
export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
|
|
479
480
|
|
|
481
|
+
/**
|
|
482
|
+
* A number option as it was given, or `fallback` when it was left out. NaN, which
|
|
483
|
+
* `Number(process.env.X)` gives for a variable that is not set, and a value that is not a number
|
|
484
|
+
* are an error: NaN passes every `Math.max` and fails every comparison, so it hung the scans or
|
|
485
|
+
* turned a limit off. `finite` refuses `Infinity` too, for an option that cannot be endless.
|
|
486
|
+
*/
|
|
487
|
+
function numberOption(name: string, value: unknown, fallback: number, finite = false): number {
|
|
488
|
+
if (value === undefined) return fallback;
|
|
489
|
+
if (typeof value !== "number") throw new TypeError(`${name} must be a number, and is ${typeof value === "string" ? JSON.stringify(value) : typeof value}.`);
|
|
490
|
+
if (Number.isNaN(value) || (finite && !Number.isFinite(value))) throw new RangeError(`${name} must be a ${finite ? "finite " : ""}number, and is ${value}. Leave it out for the default.`);
|
|
491
|
+
return value;
|
|
492
|
+
}
|
|
493
|
+
|
|
480
494
|
export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
481
495
|
/** The fields the application set. The others follow the context window, whichever it is for a request. */
|
|
482
496
|
const ownBudget = givenBudget(options.budget);
|
|
@@ -484,19 +498,19 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
484
498
|
const budgetFor = (overrides?: Partial<Budget>, limits?: ModelLimits): Budget => (
|
|
485
499
|
overrides || limits ? resolveBudget({ ...ownBudget, ...givenBudget(overrides) }, limits) : budget
|
|
486
500
|
);
|
|
487
|
-
const ttlMs = options.ttlMs
|
|
488
|
-
const maxUploadBytes = options.maxUploadBytes
|
|
501
|
+
const ttlMs = numberOption("ttlMs", options.ttlMs, 72 * 60 * 60 * 1000);
|
|
502
|
+
const maxUploadBytes = numberOption("maxUploadBytes", options.maxUploadBytes, 100 * 1024 * 1024);
|
|
489
503
|
const given = (value: number | undefined, fallback: number) => (typeof value === "number" && !Number.isNaN(value) ? value : fallback);
|
|
490
504
|
const maxTextBytes = Math.max(1, given(options.maxTextBytes, Math.max(maxUploadBytes, DEFAULT_MAX_TEXT_BYTES)));
|
|
491
505
|
const maxPdfPages = Math.max(1, Math.trunc(given(options.maxPdfPages, DEFAULT_MAX_PDF_PAGES)));
|
|
492
506
|
const ingestTimeoutMs = given(options.ingestTimeoutMs, DEFAULT_INGEST_TIMEOUT_MS);
|
|
493
507
|
const now = options.now ?? (() => new Date());
|
|
494
508
|
const { store } = options;
|
|
495
|
-
const cacheBytes = Math.max(0, options.cacheBytes
|
|
509
|
+
const cacheBytes = Math.max(0, numberOption("cacheBytes", options.cacheBytes, DEFAULT_CACHE_BYTES));
|
|
496
510
|
/** Documents ready to search, and decoded pieces of documents read by range, in one memory budget. */
|
|
497
511
|
const cache = new DocumentCache<Sized>(
|
|
498
512
|
cacheBytes,
|
|
499
|
-
|
|
513
|
+
Math.max(0, Math.trunc(numberOption("cacheSize", options.cacheSize, Number.POSITIVE_INFINITY))),
|
|
500
514
|
);
|
|
501
515
|
/** Forgets everything kept of a document: the document, and its pieces. */
|
|
502
516
|
const forget = (id: string) => {
|
|
@@ -513,12 +527,12 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
513
527
|
} : undefined;
|
|
514
528
|
/** The uploaded file of a document, when the store keeps such files. */
|
|
515
529
|
const loadOriginal = store.getOriginal ? (id: string) => reading(() => store.getOriginal!(id)) : undefined;
|
|
516
|
-
const wholeDocumentBytes = Math.max(0, options.wholeDocumentBytes
|
|
530
|
+
const wholeDocumentBytes = Math.max(0, numberOption("wholeDocumentBytes", options.wholeDocumentBytes, DEFAULT_WHOLE_DOCUMENT_BYTES));
|
|
517
531
|
/** Documents whose saved index did not match their text: the next opening builds it from the text. */
|
|
518
532
|
const rebuildIndex = new Set<string>();
|
|
519
533
|
const scan: ScanSettings = {
|
|
520
|
-
chunkBytes: Math.max(1, Math.trunc(options.scanChunkBytes
|
|
521
|
-
limiter: new Limiter(Math.max(1, Math.trunc(options.maxConcurrentScans
|
|
534
|
+
chunkBytes: Math.max(1, Math.trunc(numberOption("scanChunkBytes", options.scanChunkBytes, 1024 * 1024, true))),
|
|
535
|
+
limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentScans", options.maxConcurrentScans, 4)))),
|
|
522
536
|
onBroken: (id) => {
|
|
523
537
|
rebuildIndex.add(id);
|
|
524
538
|
forget(id);
|
|
@@ -532,7 +546,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
532
546
|
},
|
|
533
547
|
};
|
|
534
548
|
const keepOriginals = new Set<DocumentFormat>(options.keepOriginals ?? []);
|
|
535
|
-
const scannedPdfPages = Math.max(0, Math.trunc(options.scannedPdfPages
|
|
549
|
+
const scannedPdfPages = Math.max(0, Math.trunc(numberOption("scannedPdfPages", options.scannedPdfPages, 30)));
|
|
536
550
|
/** Whether the uploaded file of a document of this format is kept. */
|
|
537
551
|
const keeps = (format: DocumentFormat) => keepOriginals.has(format) && typeof options.store.putOriginal === "function";
|
|
538
552
|
|
|
@@ -642,6 +656,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
642
656
|
let measured: Awaited<ReturnType<typeof measureText>>;
|
|
643
657
|
let outline: DocumentMeta["outline"];
|
|
644
658
|
let logProfile: DocumentMeta["logProfile"];
|
|
659
|
+
let quality: TextQuality = {};
|
|
645
660
|
let index: Awaited<ReturnType<typeof buildTextIndexInSlices>> | undefined;
|
|
646
661
|
try {
|
|
647
662
|
signal.throwIfAborted();
|
|
@@ -681,6 +696,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
681
696
|
if (measured.utf8 > maxTextBytes) throw tooMuchText(name, maxTextBytes);
|
|
682
697
|
outline = await buildOutlineInSlices(lines, format, slicer);
|
|
683
698
|
logProfile = format === "log" ? await buildLogProfileInSlices(lines, slicer) : undefined;
|
|
699
|
+
quality = await measureQuality(lines, format, slicer);
|
|
684
700
|
// The line index, so that the text can be read by range: a few bytes a line, built from the
|
|
685
701
|
// UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
|
|
686
702
|
// then loads whole, so that switching to reading by range finds it ready.
|
|
@@ -713,11 +729,12 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
713
729
|
...(keepOriginal ? { originalKept: true } : {}),
|
|
714
730
|
outline,
|
|
715
731
|
...(logProfile ? { logProfile } : {}),
|
|
732
|
+
...quality,
|
|
716
733
|
createdAt: created.toISOString(),
|
|
717
734
|
// Never, for a time to live without end (or one that runs past what a date can hold).
|
|
718
735
|
expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
|
|
719
736
|
};
|
|
720
|
-
const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters
|
|
737
|
+
const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && index.textBytes === meta.textBytes
|
|
721
738
|
? serializeTextIndex(index)
|
|
722
739
|
: undefined;
|
|
723
740
|
// Each write is reported once done. What the listener of the events throws is not the store's failure.
|
|
@@ -766,17 +783,36 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
766
783
|
|
|
767
784
|
async ingest(input) {
|
|
768
785
|
// The events first, so that every ingest that throws, even on what it was given, ends with ingest.error.
|
|
769
|
-
|
|
786
|
+
// What the caller's listener throws is passed on as it is, not told as a file that could not be read.
|
|
787
|
+
let listenerFailure: { error: unknown } | undefined;
|
|
788
|
+
const listener = input?.onEvent;
|
|
789
|
+
const events = new EventEmitter<IngestEvent>(input?.runId ?? newRunId("ing"), listener && ((event: IngestEvent) => {
|
|
790
|
+
try {
|
|
791
|
+
listener(event);
|
|
792
|
+
} catch (error) {
|
|
793
|
+
listenerFailure ??= { error };
|
|
794
|
+
throw error;
|
|
795
|
+
}
|
|
796
|
+
}));
|
|
770
797
|
let storeFailed = false;
|
|
771
798
|
try {
|
|
772
799
|
if (events.active) events.emit({ type: "ingest.start", ...startOf(input) });
|
|
773
800
|
checkOwner(input.owner);
|
|
774
801
|
const name = cleanFileName(input.name);
|
|
775
802
|
const mimeType = input.mimeType?.trim() || "application/octet-stream";
|
|
776
|
-
|
|
803
|
+
// A file whose name and type say nothing is known by its bytes: a PDF, an Office file, a page.
|
|
804
|
+
const format = detectFormat(name, mimeType, input.bytes instanceof Uint8Array ? input.bytes : undefined);
|
|
777
805
|
// Progress is worked out only for someone who listens.
|
|
778
806
|
const progress = events.active ? new IngestProgress(events) : undefined;
|
|
779
|
-
|
|
807
|
+
let meta: DocumentMeta;
|
|
808
|
+
try {
|
|
809
|
+
meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true));
|
|
810
|
+
} catch (error) {
|
|
811
|
+
// A store that failed, and a caller that gave up (its own reason), are passed on as they
|
|
812
|
+
// are; a file that could not be read is told with a code.
|
|
813
|
+
if (storeFailed || (input.signal?.aborted && error === input.signal.reason) || isStoreWriteFailure(error) || (listenerFailure && error === listenerFailure.error)) throw error;
|
|
814
|
+
throw toIngestError(error);
|
|
815
|
+
}
|
|
780
816
|
try {
|
|
781
817
|
events.emit({ type: "ingest.finish", document: toDocumentSummary(meta) });
|
|
782
818
|
} catch (error) {
|
|
@@ -880,6 +916,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
880
916
|
...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal } : {}),
|
|
881
917
|
// `analyze_whole_document` is declared only when it can read at least one of the documents.
|
|
882
918
|
wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
|
|
919
|
+
// `aggregate_table` only when one may hold a table.
|
|
920
|
+
tables: documents.some((meta) => TABLE_FORMATS.has(meta.format)),
|
|
883
921
|
...rest,
|
|
884
922
|
});
|
|
885
923
|
},
|
package/src/limiter.ts
CHANGED
|
@@ -7,7 +7,12 @@ export class Limiter {
|
|
|
7
7
|
private active = 0;
|
|
8
8
|
private readonly waiting: Array<() => void> = [];
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
private readonly max: number;
|
|
11
|
+
|
|
12
|
+
/** `max` is at least 1: with NaN or 0 no slot was ever free, and every task waited forever. */
|
|
13
|
+
constructor(max: number) {
|
|
14
|
+
this.max = Number.isNaN(max) ? 1 : Math.max(1, Math.trunc(max));
|
|
15
|
+
}
|
|
11
16
|
|
|
12
17
|
/** Waits for a slot. Call the returned function once to give it back. */
|
|
13
18
|
async acquire(signal?: AbortSignal): Promise<() => void> {
|
package/src/model.ts
CHANGED
|
@@ -421,7 +421,14 @@ export class UsageMeter {
|
|
|
421
421
|
readonly totals: UsageTotals = { requests: 0, ...EMPTY_USAGE, byModel: {} };
|
|
422
422
|
|
|
423
423
|
add(model: string, usage: Partial<ModelUsage> | undefined): void {
|
|
424
|
-
const
|
|
424
|
+
const { byModel } = this.totals;
|
|
425
|
+
// An own entry only: an id such as "__proto__" or "constructor" found what every object
|
|
426
|
+
// inherits, and "__proto__" then counted the usage into Object.prototype.
|
|
427
|
+
let of = Object.hasOwn(byModel, model) ? byModel[model] : undefined;
|
|
428
|
+
if (!of) {
|
|
429
|
+
of = { requests: 0, ...EMPTY_USAGE };
|
|
430
|
+
Object.defineProperty(byModel, model, { value: of, enumerable: true, writable: true, configurable: true });
|
|
431
|
+
}
|
|
425
432
|
for (const sum of [this.totals, of]) {
|
|
426
433
|
sum.requests++;
|
|
427
434
|
for (const key of Object.keys(EMPTY_USAGE) as Array<keyof ModelUsage>) {
|
package/src/node/handlers.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
-
import { isStoreWriteFailure } from "../errors.js";
|
|
2
|
+
import { IngestError, isStoreWriteFailure } from "../errors.js";
|
|
3
3
|
import { eventStream, newRunId, type EventError, type IngestEvent } from "../events.js";
|
|
4
4
|
import { checkOwner, toDocumentSummary, type IngestInput, type LargeFiles } from "../library.js";
|
|
5
5
|
import { formatBytes } from "../plan.js";
|
|
@@ -84,10 +84,14 @@ function answerOf(error: unknown, failed: string, tooLarge: string): { status: n
|
|
|
84
84
|
return { status: 500, message: code ? `${failed} (${code}).` : `${failed}.` };
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
-
/** Answers a failed request with JSON (see `answerOf`). */
|
|
88
|
-
function fail(response: ServerResponse, error: unknown, failed: string, tooLarge: string): void {
|
|
87
|
+
/** Answers a failed request with JSON (see `answerOf`). A refusal that says when to try again (a busy reader) sets `Retry-After`. */
|
|
88
|
+
function fail(response: ServerResponse, error: unknown, failed: string, tooLarge: string, unread?: IncomingMessage): void {
|
|
89
89
|
const { status, message } = answerOf(error, failed, tooLarge);
|
|
90
|
-
|
|
90
|
+
const retryAfterMs = (error as { retryAfterMs?: unknown } | null)?.retryAfterMs;
|
|
91
|
+
if (status === 503 && typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) && !response.headersSent) {
|
|
92
|
+
response.setHeader("Retry-After", String(Math.max(1, Math.ceil(retryAfterMs / 1_000))));
|
|
93
|
+
}
|
|
94
|
+
send(response, status, { error: message }, unread);
|
|
91
95
|
}
|
|
92
96
|
|
|
93
97
|
/**
|
|
@@ -133,7 +137,9 @@ async function streamIngest(files: LargeFiles, input: IngestInput, response: Ser
|
|
|
133
137
|
await stream.result;
|
|
134
138
|
return { message: fallback.message, ...(fallback.status !== undefined ? { status: fallback.status } : {}) };
|
|
135
139
|
} catch (error) {
|
|
136
|
-
|
|
140
|
+
const failure = ingestFailure(error);
|
|
141
|
+
// A file that could not be read also says why, for a page that tells it in its own words.
|
|
142
|
+
return { ...answerOf(failure, "Upload failed", tooLarge), ...(failure instanceof IngestError ? { code: failure.code } : {}) };
|
|
137
143
|
}
|
|
138
144
|
};
|
|
139
145
|
async function* events(): AsyncGenerator<IngestEvent> {
|
|
@@ -160,11 +166,19 @@ async function streamIngest(files: LargeFiles, input: IngestInput, response: Ser
|
|
|
160
166
|
await writeSseEvents(response, events());
|
|
161
167
|
}
|
|
162
168
|
|
|
163
|
-
|
|
169
|
+
/**
|
|
170
|
+
* Answers with `value` as JSON. With `unread`, a request whose body was not read to its end (an
|
|
171
|
+
* upload refused as too large, or before it was read): the answer is written now, so that a client
|
|
172
|
+
* still sending reads it, and ended once the rest of the body is drained (see `drain`).
|
|
173
|
+
*/
|
|
174
|
+
function send(response: ServerResponse, status: number, value: unknown, unread?: IncomingMessage): void {
|
|
164
175
|
if (response.headersSent) return;
|
|
165
176
|
response.statusCode = status;
|
|
166
177
|
response.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
167
|
-
|
|
178
|
+
const body = JSON.stringify(value);
|
|
179
|
+
if (!unread || unread.complete || unread.destroyed) return void response.end(body);
|
|
180
|
+
response.write(body);
|
|
181
|
+
drain(unread, response);
|
|
168
182
|
}
|
|
169
183
|
|
|
170
184
|
function header(request: IncomingMessage, name: string): string {
|
|
@@ -192,20 +206,54 @@ async function readBody(request: IncomingMessage, limit: number): Promise<Uint8A
|
|
|
192
206
|
if (Number.isFinite(declared) && declared > limit) throw new HttpError(413, "");
|
|
193
207
|
const chunks: Buffer[] = [];
|
|
194
208
|
let size = 0;
|
|
195
|
-
|
|
209
|
+
// Leaving the loop early must not destroy the request: the rest of the body is drained after
|
|
210
|
+
// the answer (see `drain`), which a destroyed request would not do.
|
|
211
|
+
for await (const chunk of request.iterator({ destroyOnReturn: false })) {
|
|
196
212
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
|
|
197
213
|
size += buffer.byteLength;
|
|
198
|
-
if (size > limit)
|
|
199
|
-
// Stop buffering; drain the rest so the client can read the response.
|
|
200
|
-
request.resume();
|
|
201
|
-
throw new HttpError(413, "");
|
|
202
|
-
}
|
|
214
|
+
if (size > limit) throw new HttpError(413, "");
|
|
203
215
|
chunks.push(buffer);
|
|
204
216
|
}
|
|
205
217
|
const body = Buffer.concat(chunks);
|
|
206
218
|
return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
|
|
207
219
|
}
|
|
208
220
|
|
|
221
|
+
/**
|
|
222
|
+
* The most bytes of an upload's body that are read and dropped after it was answered before the
|
|
223
|
+
* body was read to its end (too large, no name). Past it the connection is closed.
|
|
224
|
+
*/
|
|
225
|
+
const DRAIN_BYTES = 8 * 1024 * 1024;
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Reads and drops the rest of a body that was answered before it was read to its end, up to
|
|
229
|
+
* `DRAIN_BYTES`, then ends the answer, which was written but not ended. The client, still
|
|
230
|
+
* sending, reads the answer and can use the connection again. Two things Node does shape this:
|
|
231
|
+
* it stops reading a request once its answer has ended, and its client stops sending once it has
|
|
232
|
+
* a whole answer (so the answer has no Content-Length, and ends only after the drain). Closing the
|
|
233
|
+
* connection at once instead makes some systems (Windows) reset it, and the client then never
|
|
234
|
+
* reads the answer. A body larger than `DRAIN_BYTES` is cut off: the answer ends, and the
|
|
235
|
+
* connection is closed.
|
|
236
|
+
*/
|
|
237
|
+
function drain(request: IncomingMessage, response: ServerResponse): void {
|
|
238
|
+
let drained = 0;
|
|
239
|
+
const end = () => {
|
|
240
|
+
request.off("data", count);
|
|
241
|
+
if (!response.writableEnded) response.end();
|
|
242
|
+
};
|
|
243
|
+
const count = (chunk: Buffer | string) => {
|
|
244
|
+
drained += chunk.length;
|
|
245
|
+
if (drained <= DRAIN_BYTES) return;
|
|
246
|
+
end();
|
|
247
|
+
if (response.writableFinished) request.destroy();
|
|
248
|
+
else response.once("finish", () => request.destroy());
|
|
249
|
+
};
|
|
250
|
+
request.on("data", count);
|
|
251
|
+
request.once("end", end);
|
|
252
|
+
request.once("close", end);
|
|
253
|
+
request.on("error", () => {});
|
|
254
|
+
request.resume();
|
|
255
|
+
}
|
|
256
|
+
|
|
209
257
|
/**
|
|
210
258
|
* Upload, get, and delete handlers for any Node HTTP server (node:http, Express, Fastify via
|
|
211
259
|
* `request.raw`/`reply.raw`, Next.js API routes on the Node runtime). Responses are JSON, except an upload that asks for
|
|
@@ -260,9 +308,11 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
|
|
|
260
308
|
}
|
|
261
309
|
send(response, 201, toDocumentSummary(meta));
|
|
262
310
|
} catch (error) {
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
311
|
+
// Answered before the body was read to its end (too large, no name): the rest is drained.
|
|
312
|
+
fail(response, error, "Upload failed", tooLarge, request);
|
|
313
|
+
// An event stream that failed after its headers were sent cannot answer with a status. (An
|
|
314
|
+
// answer to a body still being drained is ended by `drain`.)
|
|
315
|
+
if (response.headersSent && !response.writableEnded && request.complete) response.end();
|
|
266
316
|
}
|
|
267
317
|
},
|
|
268
318
|
|
package/src/node/index.ts
CHANGED
|
@@ -2,3 +2,5 @@ export { createDocumentHandlers } from "./handlers.js";
|
|
|
2
2
|
export type { DocumentHandlerOptions, DocumentHandlers } from "./handlers.js";
|
|
3
3
|
export { sseMessageOf, writeSseEvents } from "./sse.js";
|
|
4
4
|
export type { SseMessage, SseWriteOptions } from "./sse.js";
|
|
5
|
+
export { createIsolatedExtractors } from "./isolated.js";
|
|
6
|
+
export type { IsolatedExtractorOptions, IsolatedExtractors } from "./isolated.js";
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// The child process of `createIsolatedExtractors` (isolated.ts): it reads the files it is sent with
|
|
2
|
+
// the built-in extractors, one at a time, and answers over the IPC channel. It runs with a heap
|
|
3
|
+
// limit of its own: a file that would exhaust the memory kills this process, not the server.
|
|
4
|
+
import { createPdfExtractor, extractText, type PdfExtractorOptions } from "../extract.js";
|
|
5
|
+
import type { DocumentFormat, ExtractedText, ExtractProgress } from "../types.js";
|
|
6
|
+
|
|
7
|
+
/** A file to read. */
|
|
8
|
+
export type ChildJob = {
|
|
9
|
+
type: "extract";
|
|
10
|
+
id: number;
|
|
11
|
+
bytes: Uint8Array;
|
|
12
|
+
input: { name: string; mimeType: string; format: DocumentFormat; scannedPages?: number; maxTextBytes?: number; maxPages?: number; progress: boolean };
|
|
13
|
+
pdf?: PdfExtractorOptions;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** What the child answers. */
|
|
17
|
+
export type ChildMessage =
|
|
18
|
+
| { type: "ready" }
|
|
19
|
+
| { type: "progress"; id: number; progress: ExtractProgress }
|
|
20
|
+
| { type: "done"; id: number; result: ExtractedText }
|
|
21
|
+
| { type: "error"; id: number; message: string; name: string; code?: string; syscall?: string };
|
|
22
|
+
|
|
23
|
+
const send = (message: ChildMessage) => {
|
|
24
|
+
process.send?.(message);
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
process.on("message", (message: ChildJob | { type: "abort"; id: number }) => {
|
|
28
|
+
if (message?.type === "extract") void run(message);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
// The parent went away: nothing is left to answer.
|
|
32
|
+
process.on("disconnect", () => process.exit(0));
|
|
33
|
+
|
|
34
|
+
let pdfExtractor: { options: string; extract: ReturnType<typeof createPdfExtractor> } | undefined;
|
|
35
|
+
|
|
36
|
+
async function run(job: ChildJob): Promise<void> {
|
|
37
|
+
try {
|
|
38
|
+
const options = JSON.stringify(job.pdf ?? {});
|
|
39
|
+
if (job.input.format === "pdf" && pdfExtractor?.options !== options) pdfExtractor = { options, extract: createPdfExtractor(job.pdf ?? {}) };
|
|
40
|
+
const { progress, ...input } = job.input;
|
|
41
|
+
const result = await extractText(job.bytes, {
|
|
42
|
+
...input,
|
|
43
|
+
...(progress ? { onProgress: (report: ExtractProgress) => send({ type: "progress", id: job.id, progress: report }) } : {}),
|
|
44
|
+
}, job.input.format === "pdf" && pdfExtractor ? { pdf: pdfExtractor.extract } : {});
|
|
45
|
+
const { text, pages, encoding, replacedCharacters } = result;
|
|
46
|
+
send({ type: "done", id: job.id, result: { text, ...(pages !== undefined ? { pages } : {}), ...(encoding !== undefined ? { encoding } : {}), ...(replacedCharacters !== undefined ? { replacedCharacters } : {}) } });
|
|
47
|
+
} catch (error) {
|
|
48
|
+
// A system error keeps its code and system call: the server tells it apart from a file that cannot be read.
|
|
49
|
+
const { code, syscall } = (error ?? {}) as { code?: unknown; syscall?: unknown };
|
|
50
|
+
send({
|
|
51
|
+
type: "error",
|
|
52
|
+
id: job.id,
|
|
53
|
+
message: error instanceof Error ? error.message : String(error),
|
|
54
|
+
name: error instanceof Error ? error.name : "Error",
|
|
55
|
+
...(typeof code === "string" ? { code } : {}),
|
|
56
|
+
...(typeof syscall === "string" ? { syscall } : {}),
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
send({ type: "ready" });
|