llm-large-files 0.8.2 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +535 -0
- package/README.md +9 -10
- package/dist/access.d.ts +86 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +131 -0
- package/dist/access.js.map +1 -0
- package/dist/ask.d.ts +45 -1
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +181 -20
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +12 -3
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +18 -5
- package/dist/cache.js.map +1 -1
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +57 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +217 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +72 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +102 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +35 -9
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +42 -11
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts +4 -2
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +14 -3
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +32 -8
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +46 -35
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +19 -3
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +84 -12
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +18 -6
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +2 -0
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/index.d.ts +1 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/index.d.ts +9 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +70 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +868 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +169 -34
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +324 -591
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.js +3 -3
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +43 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +63 -3
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +226 -14
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +423 -181
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +7 -1
- package/dist/node/ingest-child.d.ts.map +1 -1
- package/dist/node/ingest-child.js +18 -3
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/isolated.d.ts +3 -1
- package/dist/node/isolated.d.ts.map +1 -1
- package/dist/node/isolated.js +11 -4
- package/dist/node/isolated.js.map +1 -1
- package/dist/node/originals.d.ts +19 -0
- package/dist/node/originals.d.ts.map +1 -0
- package/dist/node/originals.js +82 -0
- package/dist/node/originals.js.map +1 -0
- package/dist/node/spool.d.ts +102 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +365 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +4 -3
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +7 -6
- package/dist/node/sse.js.map +1 -1
- package/dist/pdf-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +71 -12
- package/dist/pdf-layout.js.map +1 -1
- package/dist/ranged.d.ts +15 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +42 -11
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +3 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +6 -2
- package/dist/retry.js.map +1 -1
- package/dist/scope.d.ts +25 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +60 -0
- package/dist/scope.js.map +1 -0
- package/dist/source.d.ts +60 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +170 -0
- package/dist/source.js.map +1 -0
- package/dist/stores.d.ts +120 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +582 -139
- package/dist/stores.js.map +1 -1
- package/dist/testing/fake-fetch.d.ts +31 -0
- package/dist/testing/fake-fetch.d.ts.map +1 -0
- package/dist/testing/fake-fetch.js +66 -0
- package/dist/testing/fake-fetch.js.map +1 -0
- package/dist/testing/fake-model.d.ts +38 -0
- package/dist/testing/fake-model.d.ts.map +1 -0
- package/dist/testing/fake-model.js +62 -0
- package/dist/testing/fake-model.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/store-checks.d.ts +72 -0
- package/dist/testing/store-checks.d.ts.map +1 -0
- package/dist/testing/store-checks.js +619 -0
- package/dist/testing/store-checks.js.map +1 -0
- package/dist/tools.d.ts +25 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +135 -13
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +116 -13
- package/dist/types.d.ts.map +1 -1
- package/docs/README.md +17 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +12 -8
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +16 -7
- package/docs/guides/deployment.md +284 -83
- package/docs/guides/errors-and-reliability.md +161 -23
- package/docs/guides/own-adapter-and-loop.md +27 -10
- package/docs/guides/pdfs.md +123 -29
- package/docs/guides/storage.md +633 -145
- package/docs/guides/testing.md +78 -129
- package/docs/guides/vertex-and-gemini.md +10 -7
- package/docs/guides/web-app.md +312 -78
- package/docs/how-it-works.md +35 -8
- package/docs/measurements.md +43 -8
- package/docs/publishing.md +112 -36
- package/docs/reference/ask.md +154 -13
- package/docs/reference/errors-and-retries.md +166 -14
- package/docs/reference/events.md +53 -20
- package/docs/reference/gemini.md +70 -21
- package/docs/reference/library.md +706 -165
- package/docs/reference/node.md +624 -110
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +15 -5
- package/docs/security.md +304 -67
- package/docs/troubleshooting.md +144 -65
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +12 -3
- package/src/access.ts +144 -0
- package/src/ask.ts +230 -19
- package/src/cache.ts +20 -5
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +255 -0
- package/src/errors.ts +129 -15
- package/src/events.ts +86 -21
- package/src/evidence.ts +14 -3
- package/src/extract.ts +50 -33
- package/src/gemini/adapter.ts +97 -11
- package/src/gemini/chat.ts +20 -6
- package/src/gemini/index.ts +1 -1
- package/src/index.ts +9 -6
- package/src/ingest.ts +927 -0
- package/src/library.ts +467 -601
- package/src/map-reduce.ts +3 -3
- package/src/model.ts +69 -5
- package/src/node/handlers.ts +630 -183
- package/src/node/index.ts +13 -2
- package/src/node/ingest-child.ts +23 -5
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +365 -0
- package/src/node/sse.ts +7 -6
- package/src/pdf-layout.ts +69 -11
- package/src/ranged.ts +34 -13
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/source.ts +178 -0
- package/src/stores.ts +635 -140
- package/src/testing/fake-fetch.ts +80 -0
- package/src/testing/fake-model.ts +78 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/store-checks.ts +660 -0
- package/src/tools.ts +150 -14
- package/src/types.ts +106 -13
package/src/ingest.ts
ADDED
|
@@ -0,0 +1,927 @@
|
|
|
1
|
+
// `files.ingest`: reads a file, prepares its text, and stores it. Moved out of library.ts in 0.9.0:
|
|
2
|
+
// the library hands it what it needs in an `IngestContext`.
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { checkMetaVersion, checkOwner, heldBy, metaOf, OWNER_REQUIRED, SCOPE_REQUIRED, storeCall, storeContext, type AccessRules } from "./access.js";
|
|
5
|
+
import { buildLogProfileInSlices, buildOutlineInSlices, looksLikeLog } from "./analyze.js";
|
|
6
|
+
import { DocumentScopeError, DocumentStoreError, IngestError, isStoreWriteFailure, noteStoreWriteFailure, toIngestError } from "./errors.js";
|
|
7
|
+
import { EventEmitter, eventErrorOf, newRunId, type EventError, type IngestEvent, type IngestStage } from "./events.js";
|
|
8
|
+
import { detectFormat, extractorFor, extractText, isZip, namedFormat, sniffParts, SNIFFED_FIRST, SNIFFED_HEAD, SNIFFED_TAIL } from "./extract.js";
|
|
9
|
+
import type { IngestFromSource, IngestInput } from "./library.js";
|
|
10
|
+
import type { Limiter } from "./limiter.js";
|
|
11
|
+
import { TimeSlicer } from "./pause.js";
|
|
12
|
+
import { formatBytes } from "./plan.js";
|
|
13
|
+
import { measureQuality, type TextQuality } from "./quality.js";
|
|
14
|
+
import { checkScope } from "./scope.js";
|
|
15
|
+
import { absolutePath, isSha256, readRanges, readSource, sha256InSlices, statSource, type SourceRead } from "./source.js";
|
|
16
|
+
import { APP_DOCUMENT_ID_PATTERN, DOCUMENT_META_VERSION } from "./stores.js";
|
|
17
|
+
import { buildTextIndexInSlices, canSerialize, serializeTextIndex } from "./text-index.js";
|
|
18
|
+
import { measureText, prepareText, removeInvisible, sliceWhole } from "./text.js";
|
|
19
|
+
import type { DocumentContext, DocumentFormat, DocumentMeta, DocumentScope, DocumentStore, DocumentSummary, ExtractedText, ExtractProgress, Extractor } from "./types.js";
|
|
20
|
+
|
|
21
|
+
export { checkOwner } from "./access.js";
|
|
22
|
+
|
|
23
|
+
/** What `ingest` needs of the library it belongs to: its options, as the library read them, and its state. */
|
|
24
|
+
export type IngestContext = {
|
|
25
|
+
readonly store: DocumentStore;
|
|
26
|
+
readonly now: () => Date;
|
|
27
|
+
readonly ttlMs: number;
|
|
28
|
+
readonly maxUploadBytes: number;
|
|
29
|
+
readonly maxTextBytes: number;
|
|
30
|
+
readonly maxPdfPages: number;
|
|
31
|
+
readonly ingestTimeoutMs: number;
|
|
32
|
+
readonly scannedPdfPages: number;
|
|
33
|
+
readonly extractors: Partial<Record<DocumentFormat, Extractor>> | undefined;
|
|
34
|
+
/** The ingests doing their work, and those waiting their turn (`maxConcurrentIngests`). */
|
|
35
|
+
readonly ingests: Limiter;
|
|
36
|
+
/** How long work an ingest waits on, or gave up on, may keep its turn (see `IngestSlot`). */
|
|
37
|
+
readonly slotCapMs: number;
|
|
38
|
+
/**
|
|
39
|
+
* Whether the uploaded file of a document of this format is kept: by its ref (`IngestInput.original`,
|
|
40
|
+
* read by `LargeFilesOptions.originals`), or else as a copy in the store (`putOriginal`).
|
|
41
|
+
*/
|
|
42
|
+
readonly keeps: (format: DocumentFormat, byRef: boolean) => boolean;
|
|
43
|
+
/** Whether the library reads uploaded files that the application keeps (`LargeFilesOptions.originals`). */
|
|
44
|
+
readonly readsRefs: boolean;
|
|
45
|
+
/** Forgets everything kept in memory of a document, in every scope: the document, and its pieces. */
|
|
46
|
+
readonly forget: (id: string) => void;
|
|
47
|
+
/** What every call must name (`requireOwner`, `requireScope`). */
|
|
48
|
+
readonly rules: AccessRules;
|
|
49
|
+
/**
|
|
50
|
+
* The application's IDs (`IngestInput.id`) of the ingests of this library under way, from their
|
|
51
|
+
* first look at the store to the end of their writes and of `ingest.finish`; and when writes did
|
|
52
|
+
* not end in time, until they and the removal of what they wrote have ended. A second ingest of
|
|
53
|
+
* one of them is refused ("exists"), whatever its `ifExists`, owner or scope: two ingests that both
|
|
54
|
+
* found the ID free would write over each other, and a store that ignores the context keeps one
|
|
55
|
+
* document of an ID for every scope.
|
|
56
|
+
*/
|
|
57
|
+
readonly ingesting: Set<string>;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Where an ingest writes: the ID the application gave (`IngestInput.id`), when it gave one, what
|
|
62
|
+
* to do when it is taken, and the owner and scope of the document, which every store call carries.
|
|
63
|
+
*/
|
|
64
|
+
type Target = {
|
|
65
|
+
readonly id: string | undefined;
|
|
66
|
+
readonly ifExists: "fail" | "replace";
|
|
67
|
+
readonly owner: string | undefined;
|
|
68
|
+
readonly scope: DocumentScope | undefined;
|
|
69
|
+
/** The context of every store call of the ingest. */
|
|
70
|
+
readonly context: DocumentContext;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** The TypeError of an `IngestInput.id` of another shape. It does not repeat the ID, which may hold what it must not. */
|
|
74
|
+
const ID_SHAPE = 'id must be lowercase letters, digits, "_" and "-", up to 64 characters, starting with a letter or a digit (APP_DOCUMENT_ID_PATTERN), and not a name Windows keeps for a device (con, nul, com1…).';
|
|
75
|
+
|
|
76
|
+
/** The ID, `ifExists`, owner and scope of an ingest, checked (the owner already is). */
|
|
77
|
+
function targetOf(input: IngestInput | IngestFromSource, rules: AccessRules): Target {
|
|
78
|
+
if (rules.requireOwner && input.owner === undefined) throw new TypeError(OWNER_REQUIRED);
|
|
79
|
+
// Null is no scope, as a database gives a field that was left out.
|
|
80
|
+
const scope = checkScope(input.scope ?? undefined);
|
|
81
|
+
if (rules.requireScope && scope === undefined) throw new TypeError(SCOPE_REQUIRED);
|
|
82
|
+
const { id, ifExists = "fail" } = input;
|
|
83
|
+
if (id !== undefined && (typeof id !== "string" || !APP_DOCUMENT_ID_PATTERN.test(id))) throw new TypeError(ID_SHAPE);
|
|
84
|
+
if (ifExists !== "fail" && ifExists !== "replace") throw new TypeError('ifExists must be "fail" or "replace".');
|
|
85
|
+
return { id, ifExists, owner: input.owner, scope, context: storeContext(scope, input.owner) };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The refusal of an application's ID that is taken (`ifExists`). It says nothing of the document that has it. */
|
|
89
|
+
const exists = (name: string) => new IngestError("exists", `${name}: a document with this ID already exists.`);
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Whether the application's ID may be written, as the store sees it for this context: a document
|
|
93
|
+
* of that ID that is there is an `IngestError` "exists", unless `ifExists` is "replace" and the
|
|
94
|
+
* document has the same owner and scope. One of another owner or scope is never replaced, even when
|
|
95
|
+
* its text looks gone: a store, or a wrapper of one, that does not pass the context on to every
|
|
96
|
+
* call would say so of a document that is there. A document written by a newer version of the
|
|
97
|
+
* package is never replaced (`DocumentStoreError` "NEWER_VERSION"). Returns true when there is a
|
|
98
|
+
* document to delete before the new one is written: the one being replaced, or one expired.
|
|
99
|
+
*/
|
|
100
|
+
async function claim(context: IngestContext, target: Target & { id: string }, name: string): Promise<boolean> {
|
|
101
|
+
const { store, now } = context;
|
|
102
|
+
const { id } = target;
|
|
103
|
+
const found = metaOf(await storeCall("read", () => store.getMeta(id, target.context)), id);
|
|
104
|
+
if (!found) return false;
|
|
105
|
+
if (Date.parse(found.expiresAt) <= now().getTime()) return true;
|
|
106
|
+
if (target.ifExists === "fail") throw exists(name);
|
|
107
|
+
checkMetaVersion(found);
|
|
108
|
+
if (heldBy(found, target.owner, target.scope)) return true;
|
|
109
|
+
throw exists(name);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Removes what an ingest wrote under its ID, after a write that failed or a listener that threw on
|
|
114
|
+
* `ingest.finish`: only while the document there, if any, is the ingest's own (the same `createdAt`,
|
|
115
|
+
* owner and scope). A made ID is the ingest's alone. Under an application's ID, another document may
|
|
116
|
+
* be there: one the ingest was to replace (its delete failed), or one another server stored
|
|
117
|
+
* meanwhile. It is left. "taken" when the ingest could not have replaced it: it has not expired, and
|
|
118
|
+
* it is of another owner or scope. "left" for any other.
|
|
119
|
+
*/
|
|
120
|
+
async function removeOwn(context: Pick<IngestContext, "store" | "now">, target: Target, meta: DocumentMeta): Promise<"removed" | "left" | "taken"> {
|
|
121
|
+
const { store, now } = context;
|
|
122
|
+
if (target.id !== undefined) {
|
|
123
|
+
const found = metaOf(await storeCall("read", () => store.getMeta(meta.id, target.context)), meta.id);
|
|
124
|
+
if (found && !(found.createdAt === meta.createdAt && heldBy(found, meta.owner, meta.scope))) {
|
|
125
|
+
// As `claim` sees it: a date that cannot be read has not expired.
|
|
126
|
+
const expired = Date.parse(found.expiresAt) <= now().getTime();
|
|
127
|
+
return !expired && !heldBy(found, target.owner, target.scope) ? "taken" : "left";
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
await store.delete(meta.id, target.context);
|
|
131
|
+
return "removed";
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A store that did not answer in time, as it wrote or was read at ingest: its cause says for how long it was waited for. */
|
|
135
|
+
const storeTimeout = (name: string, ms: number, operation: "write" | "read" = "write") => new DocumentStoreError(
|
|
136
|
+
Object.assign(new Error(`The store did not ${operation === "write" ? "finish writing" : "answer about"} ${name} within ${formatDuration(ms)}.`), { code: "ETIMEDOUT" }),
|
|
137
|
+
{ operation, code: "ETIMEDOUT" },
|
|
138
|
+
);
|
|
139
|
+
|
|
140
|
+
/** The fields of a document that are safe to return to a browser. */
|
|
141
|
+
export function toDocumentSummary(meta: DocumentMeta): DocumentSummary {
|
|
142
|
+
return {
|
|
143
|
+
id: meta.id,
|
|
144
|
+
name: meta.name,
|
|
145
|
+
mimeType: meta.mimeType,
|
|
146
|
+
format: meta.format,
|
|
147
|
+
bytes: meta.bytes,
|
|
148
|
+
lines: meta.lines,
|
|
149
|
+
estimatedTokens: meta.estimatedTokens,
|
|
150
|
+
...(meta.pages ? { pages: meta.pages } : {}),
|
|
151
|
+
...(meta.encoding ? { encoding: meta.encoding } : {}),
|
|
152
|
+
...(meta.replacedCharacters ? { replacedCharacters: meta.replacedCharacters } : {}),
|
|
153
|
+
expiresAt: meta.expiresAt,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** An encoding's name as TextDecoder gives it ("windows-1255"): an extractor of your own may name another. */
|
|
158
|
+
const ENCODING_NAME = /^[a-z0-9][a-z0-9._:-]{0,39}$/i;
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Whether the name is an older encoding, as `DocumentMeta.encoding` records: not UTF-8 or UTF-16,
|
|
162
|
+
* under any of their names ("utf8", "unicode"). The model is told the file is not in UTF-8.
|
|
163
|
+
*/
|
|
164
|
+
function olderEncoding(name: unknown): name is string {
|
|
165
|
+
if (typeof name !== "string" || !ENCODING_NAME.test(name)) return false;
|
|
166
|
+
let known: string;
|
|
167
|
+
try {
|
|
168
|
+
known = new TextDecoder(name).encoding;
|
|
169
|
+
} catch {
|
|
170
|
+
// A name TextDecoder does not know: the extractor read the file itself.
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
return known !== "utf-8" && known !== "utf-16le" && known !== "utf-16be";
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** How the text of a file was read, as its extractor said, in the fields of `DocumentMeta`. */
|
|
177
|
+
function readingOf(extracted: ExtractedText): Pick<DocumentMeta, "encoding" | "replacedCharacters"> {
|
|
178
|
+
const { encoding, replacedCharacters } = extracted;
|
|
179
|
+
return {
|
|
180
|
+
...(olderEncoding(encoding) ? { encoding } : {}),
|
|
181
|
+
...(typeof replacedCharacters === "number" && Number.isSafeInteger(replacedCharacters) && replacedCharacters > 0 ? { replacedCharacters } : {}),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* A file name as one printable line: the last path segment. Control characters, line and paragraph
|
|
187
|
+
* separators, and text-direction controls (the marks of right-to-left text included) become a space.
|
|
188
|
+
* Names are shown to the model and in UIs, so a name must not be able to start a new line of the
|
|
189
|
+
* prompt, or disguise its extension. Most characters that show nothing are removed (tag characters,
|
|
190
|
+
* zero-width spaces); the variation selectors and joiners that scripts and emoji need are kept, and
|
|
191
|
+
* can still carry data a person does not see.
|
|
192
|
+
*/
|
|
193
|
+
export function cleanFileName(raw: string): string {
|
|
194
|
+
const base = raw.split(/[\\/]/).at(-1) ?? "";
|
|
195
|
+
// Control characters, line and paragraph separators, and text-direction controls become a space.
|
|
196
|
+
const spaced = base.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]+/gu, " ");
|
|
197
|
+
const name = removeInvisible(spaced).replace(/\s+/g, " ").trim();
|
|
198
|
+
// At most 255 characters, never half of an emoji. A flag cut short loses the tags left of it.
|
|
199
|
+
return (name.length > 255 ? removeInvisible(sliceWhole(name, 255)) : name) || "file";
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The MIME type of a file that says nothing of what it is. */
|
|
203
|
+
const OCTET_STREAM = "application/octet-stream";
|
|
204
|
+
/** A token of RFC 9110: the characters a type or a subtype of a MIME type is made of. */
|
|
205
|
+
const MIME_TOKEN = "[!#$%&'*+.^_`|~0-9a-z-]+";
|
|
206
|
+
const MIME_TYPE = new RegExp(`^${MIME_TOKEN}/${MIME_TOKEN}$`);
|
|
207
|
+
/** Printable ASCII, and tabs: a header value without a line break, or a character that shows nothing. */
|
|
208
|
+
const PRINTABLE = /^[\t\x20-\x7e]*$/;
|
|
209
|
+
/** The longest type/subtype kept: 127 characters. */
|
|
210
|
+
const MAX_MIME_TYPE = 127;
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* A file's MIME type as it is kept: its type and subtype, in lower case, without parameters
|
|
214
|
+
* ("Text/CSV; charset=x" is "text/csv"). One that is not a type/subtype of RFC 9110 token
|
|
215
|
+
* characters, of at most 127 characters, or that holds anything but printable ASCII anywhere (a
|
|
216
|
+
* line break, a text-direction control, a tag character), is "application/octet-stream". The
|
|
217
|
+
* library never used the parameters: a text's encoding is found from its bytes. New in 0.9.0.
|
|
218
|
+
*/
|
|
219
|
+
export function cleanMimeType(raw: unknown): string {
|
|
220
|
+
if (typeof raw !== "string" || !PRINTABLE.test(raw)) return OCTET_STREAM;
|
|
221
|
+
const type = raw.split(";", 1)[0]!.trim().toLowerCase();
|
|
222
|
+
return type.length <= MAX_MIME_TYPE && MIME_TYPE.test(type) ? type : OCTET_STREAM;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** The longest `IngestInput.original.ref`, in UTF-16 units. */
|
|
226
|
+
const MAX_REF_LENGTH = 1_024;
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* The path of an ingest from a path (`IngestFromSource.source`), checked; undefined for an ingest
|
|
230
|
+
* of bytes. A source of null is none, as a database gives a field that was left out.
|
|
231
|
+
*
|
|
232
|
+
* A relative path is made absolute here, once, against the working directory of the call
|
|
233
|
+
* (`absolutePath`): every read of the file, at the call, at the turn, and in a child process of an
|
|
234
|
+
* isolated reader (whose working directory is its own), reads the file named then. Neither is
|
|
235
|
+
* normalized: a ".." after a link, and a "/" at the end, are the system's to resolve, for a
|
|
236
|
+
* relative path as for an absolute one.
|
|
237
|
+
*/
|
|
238
|
+
function sourcePathOf(input: IngestInput | IngestFromSource): string | undefined {
|
|
239
|
+
const source: unknown = (input as { source?: unknown }).source;
|
|
240
|
+
if (source === undefined || source === null) return undefined;
|
|
241
|
+
if ((input as { bytes?: unknown }).bytes !== undefined) throw new TypeError("Give the file as bytes or as source, not both.");
|
|
242
|
+
const path: unknown = typeof source === "object" ? (source as { path?: unknown }).path : undefined;
|
|
243
|
+
if (typeof path !== "string" || path.length === 0 || path.includes("\0")) throw new TypeError("source.path must be the path of a file: a string that is not empty.");
|
|
244
|
+
return absolutePath(path);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* The ref of the uploaded file the application keeps (`IngestInput.original`), checked. It needs
|
|
249
|
+
* a reader (`LargeFilesOptions.originals`): without one, the file could never be read back.
|
|
250
|
+
*/
|
|
251
|
+
function originalRefOf(input: IngestInput | IngestFromSource, readsRefs: boolean): string | undefined {
|
|
252
|
+
const original: unknown = input.original;
|
|
253
|
+
if (original === undefined || original === null) return undefined;
|
|
254
|
+
const ref: unknown = typeof original === "object" ? (original as { ref?: unknown }).ref : undefined;
|
|
255
|
+
if (typeof ref !== "string" || ref.length === 0 || ref.length > MAX_REF_LENGTH) throw new TypeError("original.ref must be a string of 1 to 1,024 characters.");
|
|
256
|
+
if (!readsRefs) throw new TypeError("original needs LargeFilesOptions.originals, which reads the file from its ref.");
|
|
257
|
+
return ref;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** The refusal of a file of no bytes. */
|
|
261
|
+
const emptyFile = (name: string) => new Error(`${name} is empty.`);
|
|
262
|
+
/** The refusal of a file larger than `maxUploadBytes`. */
|
|
263
|
+
const tooLarge = (name: string, maxUploadBytes: number) => new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
|
|
264
|
+
|
|
265
|
+
/** `size`, the size of the file of an ingest, once it is neither empty nor larger than the upload limit. */
|
|
266
|
+
function checkedSize(name: string, size: number, maxUploadBytes: number): number {
|
|
267
|
+
if (size === 0) throw emptyFile(name);
|
|
268
|
+
if (size > maxUploadBytes) throw tooLarge(name, maxUploadBytes);
|
|
269
|
+
return size;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const NO_BYTES = new Uint8Array(0);
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* The format of a file at a path: the one its name and type say, or, when they say nothing, the
|
|
276
|
+
* one its bytes say (`sniffParts`), from reads of the parts looked at and not the rest: its first
|
|
277
|
+
* KB, and for a ZIP its first 64 KB and its last MB.
|
|
278
|
+
*/
|
|
279
|
+
async function formatAtPath(name: string, mimeType: string, path: string, size: number): Promise<DocumentFormat> {
|
|
280
|
+
const { format, sniff } = namedFormat(name, mimeType);
|
|
281
|
+
if (!sniff) return format;
|
|
282
|
+
const [first = NO_BYTES] = await readRanges(path, [[0, Math.min(size, SNIFFED_FIRST)]]);
|
|
283
|
+
if (!isZip(first)) return sniffParts(first, NO_BYTES) ?? format;
|
|
284
|
+
const [head = NO_BYTES, tail = NO_BYTES] = await readRanges(path, [[0, Math.min(size, SNIFFED_HEAD)], [Math.max(SNIFFED_HEAD, size - SNIFFED_TAIL), size]]);
|
|
285
|
+
return sniffParts(head, tail) ?? format;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* What an extractor that reads paths read (`ExtractedText.file`), when it said so in the shape it
|
|
290
|
+
* is kept in: a whole number of bytes, and a SHA-256 of 64 lowercase hex digits.
|
|
291
|
+
*/
|
|
292
|
+
function fileOf(extracted: ExtractedText): { bytes: number; sha256: string } | undefined {
|
|
293
|
+
const file: unknown = extracted.file;
|
|
294
|
+
if (typeof file !== "object" || file === null) return undefined;
|
|
295
|
+
const { bytes, sha256 } = file as { bytes?: unknown; sha256?: unknown };
|
|
296
|
+
return typeof bytes === "number" && Number.isSafeInteger(bytes) && bytes >= 0 && isSha256(sha256) ? { bytes, sha256 } : undefined;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* The `expiresAt` of a document that never expires (`ttlMs: Infinity`): the last instant of the
|
|
301
|
+
* year 9999. A date, so that every comparison, and a server of an older version, reads it as any other.
|
|
302
|
+
*/
|
|
303
|
+
export const NEVER_EXPIRES = "9999-12-31T23:59:59.999Z";
|
|
304
|
+
|
|
305
|
+
/** The refusal of a file whose text is larger than `maxTextBytes`. */
|
|
306
|
+
const tooMuchText = (name: string, maxTextBytes: number) =>
|
|
307
|
+
new Error(`${name} holds more than ${formatBytes(maxTextBytes)} of text, more than is kept from one file. Split it, and attach the part you need.`);
|
|
308
|
+
|
|
309
|
+
/** The longest a Node.js timer waits: a longer one fires at once. A limit past it is no limit. */
|
|
310
|
+
export const LONGEST_TIMER_MS = 2 ** 31 - 1;
|
|
311
|
+
|
|
312
|
+
/** `value` copied through JSON: new strings, none of them a piece of a larger one. */
|
|
313
|
+
function jsonCopy<T>(value: T): T {
|
|
314
|
+
return JSON.parse(JSON.stringify(value)) as T;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** `work`, or the error `late` makes once `ms` have passed without it settling. */
|
|
318
|
+
function settleWithin<T>(work: Promise<T>, ms: number, late: () => Error): Promise<T> {
|
|
319
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
320
|
+
const timeUp = new Promise<never>((_, reject) => {
|
|
321
|
+
timer = setTimeout(() => reject(late()), ms);
|
|
322
|
+
});
|
|
323
|
+
return Promise.race([work, timeUp]).finally(() => clearTimeout(timer));
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* A look at a file at a path before the ingest's turn (its lstat, the parts read for its format):
|
|
328
|
+
* given up on with the caller's reason when the caller leaves, and failed, as the server's trouble
|
|
329
|
+
* (a system error, which names no path), when the volume does not answer within `ms`. The look
|
|
330
|
+
* itself cannot be stopped; it holds no turn.
|
|
331
|
+
*/
|
|
332
|
+
function lookWithin<T>(look: Promise<T>, signal: AbortSignal | undefined, ms: number, syscall: "lstat" | "read"): Promise<T> {
|
|
333
|
+
return settleWithin(signal ? untilAborted(look, signal) : look, ms, () =>
|
|
334
|
+
Object.assign(new Error(`The file to ingest did not answer within ${formatDuration(ms)}.`), { code: "ETIMEDOUT", syscall }));
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* The turn of one ingest (`maxConcurrentIngests`). It is given back when the ingest ends; when the
|
|
339
|
+
* ingest gave up on work that goes on (an extractor that does not stop on the signal, such as a
|
|
340
|
+
* PDF being parsed when its caller left), once that work ends, or `capMs` later when it does not.
|
|
341
|
+
* (Store writes that do not end fail the ingest after `capMs`: see `ingestFile`.)
|
|
342
|
+
*/
|
|
343
|
+
class IngestSlot {
|
|
344
|
+
private released = false;
|
|
345
|
+
private timer: ReturnType<typeof setTimeout> | undefined;
|
|
346
|
+
|
|
347
|
+
constructor(private readonly release: () => void, private readonly capMs: number) {}
|
|
348
|
+
|
|
349
|
+
private readonly free = () => {
|
|
350
|
+
if (this.released) return;
|
|
351
|
+
this.released = true;
|
|
352
|
+
clearTimeout(this.timer);
|
|
353
|
+
this.release();
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Gives the turn back `capMs` from now at the latest. The timer keeps the process alive: work
|
|
358
|
+
* that never ends may hold nothing that does, and ingests waiting for the turn would be lost.
|
|
359
|
+
*/
|
|
360
|
+
limit(): void {
|
|
361
|
+
if (this.released || this.timer !== undefined) return;
|
|
362
|
+
this.timer = setTimeout(this.free, this.capMs);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** The ingest is over: the turn goes back now, or once `abandoned` ends (`capMs` at the latest). */
|
|
366
|
+
end(abandoned?: Promise<unknown>): void {
|
|
367
|
+
if (!abandoned) return this.free();
|
|
368
|
+
abandoned.then(this.free, this.free);
|
|
369
|
+
this.limit();
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** A time limit in the words of a message: "500 ms", "45 s", "2 min". */
|
|
374
|
+
function formatDuration(ms: number): string {
|
|
375
|
+
if (ms < 1_000) return `${Math.max(1, Math.round(ms))} ms`;
|
|
376
|
+
if (ms < 120_000) return `${Number((ms / 1_000).toFixed(1))} s`;
|
|
377
|
+
return `${Number((ms / 60_000).toFixed(1))} min`;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* The signal one ingest runs under: aborted when the caller's is, or when `timeoutMs` has passed
|
|
382
|
+
* (with an error that says the file took too long). `dispose` stops the timer.
|
|
383
|
+
*/
|
|
384
|
+
function ingestSignal(name: string, caller: AbortSignal | undefined, timeoutMs: number): { signal: AbortSignal; dispose(): void } {
|
|
385
|
+
const controller = new AbortController();
|
|
386
|
+
const onAbort = () => controller.abort(caller!.reason);
|
|
387
|
+
if (caller?.aborted) controller.abort(caller.reason);
|
|
388
|
+
else caller?.addEventListener("abort", onAbort, { once: true });
|
|
389
|
+
const timer = timeoutMs > 0 && timeoutMs <= LONGEST_TIMER_MS
|
|
390
|
+
? setTimeout(() => controller.abort(new Error(`${name} took too long to read (more than ${formatDuration(timeoutMs)}). Split it, or save it as plain text, and attach that.`)), timeoutMs)
|
|
391
|
+
: undefined;
|
|
392
|
+
return {
|
|
393
|
+
signal: controller.signal,
|
|
394
|
+
dispose() {
|
|
395
|
+
clearTimeout(timer);
|
|
396
|
+
caller?.removeEventListener("abort", onAbort);
|
|
397
|
+
},
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* `work`, or the signal's reason as soon as it is aborted: an extractor of your own that does not
|
|
403
|
+
* look at the signal is no longer waited for (though the work it does cannot be stopped). Work
|
|
404
|
+
* given up on is still watched: if it fails later, that is not an unhandled rejection, which ends
|
|
405
|
+
* a Node.js process.
|
|
406
|
+
*/
|
|
407
|
+
function untilAborted<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
408
|
+
if (signal.aborted) {
|
|
409
|
+
work.catch(() => undefined);
|
|
410
|
+
return Promise.reject(signal.reason);
|
|
411
|
+
}
|
|
412
|
+
return new Promise<T>((resolve, reject) => {
|
|
413
|
+
const onAbort = () => reject(signal.reason);
|
|
414
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
415
|
+
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* The error of `ingest.error` when the store failed to write the document: a `DocumentStoreError`
|
|
421
|
+
* (503), in these words whatever the store threw, which may name a host or a path. Its name and
|
|
422
|
+
* status are set here, not taken from the error: a store's own subclass of `DocumentStoreError`,
|
|
423
|
+
* of a name of its own, is still told as one, which `errorInfoOf` reads as a store that failed.
|
|
424
|
+
*/
|
|
425
|
+
const storeWriteFailed = (): EventError => ({ message: "The document could not be stored. Try again later.", name: "DocumentStoreError", status: 503 });
|
|
426
|
+
|
|
427
|
+
/** The least time between two `ingest.progress` events of one stage, in milliseconds: a slice of `TimeSlicer`. */
|
|
428
|
+
const PROGRESS_MS = 12;
|
|
429
|
+
|
|
430
|
+
type ProgressUnit = Extract<IngestEvent, { type: "ingest.progress" }>["unit"];
|
|
431
|
+
const EXTRACT_STAGES = new Set<unknown>(["extract", "check", "pictures", "decode"]);
|
|
432
|
+
const EXTRACT_UNITS = new Set<unknown>(["pages", "parts", "bytes"]);
|
|
433
|
+
const isCount = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* What `ingest.start` says of an ingest, worked out from whatever it was given: the checks come
|
|
437
|
+
* after it. `statSize`: the size of a file at a path, as `lstat` gave it.
|
|
438
|
+
*/
|
|
439
|
+
function startOf(input: IngestInput | IngestFromSource | undefined, statSize: number | undefined): { name: string; format: DocumentFormat; bytes: number } {
|
|
440
|
+
try {
|
|
441
|
+
const name = typeof input?.name === "string" ? cleanFileName(input.name) : "";
|
|
442
|
+
const mimeType = cleanMimeType(input?.mimeType);
|
|
443
|
+
const bytes = statSize ?? input?.bytes?.byteLength;
|
|
444
|
+
return { name, format: detectFormat(name, mimeType), bytes: isCount(bytes) ? bytes : 0 };
|
|
445
|
+
} catch {
|
|
446
|
+
return { name: "", format: "text", bytes: 0 };
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
type HeldProgress = { done: number; total: number | undefined; unit: ProgressUnit; sent: boolean };
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Sends the `ingest.progress` events of one ingest: at most one every `PROGRESS_MS` for each stage,
|
|
454
|
+
* however the stages take turns, then the last progress of each stage when the stages end (`end`).
|
|
455
|
+
* A progress that completes its stage goes out at once, the first time, so that stages that run one
|
|
456
|
+
* after the other end in that order. Made only when someone listens.
|
|
457
|
+
*/
|
|
458
|
+
class IngestProgress {
|
|
459
|
+
/** Each stage that reported, in the order it first did: when it last sent, and its last progress. */
|
|
460
|
+
private readonly stages = new Map<IngestStage, { sentAt: number; completed: boolean; last: HeldProgress }>();
|
|
461
|
+
/** Set once a stage after the extractor's began: an extract stage is not reported again. */
|
|
462
|
+
private extractOver = false;
|
|
463
|
+
|
|
464
|
+
constructor(private readonly events: EventEmitter<IngestEvent>) {}
|
|
465
|
+
|
|
466
|
+
report(stage: IngestStage, done: number, total: number | undefined, unit: ProgressUnit): void {
|
|
467
|
+
if (!EXTRACT_STAGES.has(stage)) this.extractOver = true;
|
|
468
|
+
const last: HeldProgress = { done, total, unit, sent: false };
|
|
469
|
+
let state = this.stages.get(stage);
|
|
470
|
+
if (!state) {
|
|
471
|
+
state = { sentAt: Number.NEGATIVE_INFINITY, completed: false, last };
|
|
472
|
+
this.stages.set(stage, state);
|
|
473
|
+
}
|
|
474
|
+
state.last = last;
|
|
475
|
+
const now = performance.now();
|
|
476
|
+
const completes = !state.completed && total !== undefined && done >= total;
|
|
477
|
+
if (completes) state.completed = true;
|
|
478
|
+
if (completes || now - state.sentAt >= PROGRESS_MS) {
|
|
479
|
+
state.sentAt = now;
|
|
480
|
+
this.send(stage, last);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** The progress an extractor reported (`ExtractInput.onProgress`). One of your own may send anything: what does not fit is left out. */
|
|
485
|
+
extracted(progress: ExtractProgress): void {
|
|
486
|
+
if (this.extractOver) return;
|
|
487
|
+
const stage = progress?.stage ?? "extract";
|
|
488
|
+
if (!EXTRACT_STAGES.has(stage) || !EXTRACT_UNITS.has(progress?.unit) || !isCount(progress?.done)) return;
|
|
489
|
+
this.report(stage, progress.done, isCount(progress.total) ? progress.total : undefined, progress.unit);
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** The stages so far are over: the last progress of each, when it was held back, goes out, in the order they began. */
|
|
493
|
+
end(): void {
|
|
494
|
+
const held = [...this.stages].filter(([, state]) => !state.last.sent);
|
|
495
|
+
this.stages.clear();
|
|
496
|
+
for (const [stage, state] of held) this.send(stage, state.last);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
private send(stage: IngestStage, last: HeldProgress): void {
|
|
500
|
+
last.sent = true;
|
|
501
|
+
this.events.emit({
|
|
502
|
+
type: "ingest.progress",
|
|
503
|
+
stage,
|
|
504
|
+
done: last.done,
|
|
505
|
+
...(last.total !== undefined ? { total: last.total } : {}),
|
|
506
|
+
unit: last.unit,
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** Work an ingest gave up on, which goes on once it has ended. */
|
|
512
|
+
type IngestWork = {
|
|
513
|
+
/** An extraction it no longer waits for: the ingest's turn is kept until it ends (`IngestSlot`). */
|
|
514
|
+
abandoned?: Promise<unknown>;
|
|
515
|
+
/**
|
|
516
|
+
* Writes that did not end in time, then the removal of what they wrote: the application's ID
|
|
517
|
+
* stays held in `ingesting` until they have ended, since they may still land.
|
|
518
|
+
*/
|
|
519
|
+
writes?: Promise<unknown>;
|
|
520
|
+
};
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Where the file of an ingest is: `path` for one from a path (`IngestFromSource`), else its bytes
|
|
524
|
+
* (`IngestInput.bytes`); and `ref`, where the application keeps it (`IngestInput.original`).
|
|
525
|
+
*/
|
|
526
|
+
type Upload = { readonly path: string | undefined; readonly ref: string | undefined };
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* The caller left (`IngestInput.signal`) while the document was written: once the writes have
|
|
530
|
+
* ended, what they wrote is removed, while it is this ingest's own (`removeOwn`), and within the time
|
|
531
|
+
* the writes were given; the caller gets its own reason. Before 0.9.0, a client that left during the
|
|
532
|
+
* write left the document behind, kept for good under `ttlMs: Infinity`.
|
|
533
|
+
*/
|
|
534
|
+
async function removeAbandoned(context: IngestContext, target: Target, meta: DocumentMeta, work: IngestWork, reason: unknown): Promise<never> {
|
|
535
|
+
let ended = false;
|
|
536
|
+
const removal = removeOwn(context, target, meta).catch(() => undefined).then(() => {
|
|
537
|
+
ended = true;
|
|
538
|
+
});
|
|
539
|
+
await settleWithin(removal, context.slotCapMs, () => new Error("")).catch(() => undefined);
|
|
540
|
+
// A removal that has not ended may still land: the ID stays held until it has (see `IngestWork`).
|
|
541
|
+
if (!ended) work.writes = removal;
|
|
542
|
+
context.forget(meta.id);
|
|
543
|
+
throw reason;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* The work of `ingest`, once the file is named: `detected` is the format its name and type say.
|
|
548
|
+
* `progress` is given when someone listens to the events of the ingest. `storeFailed` is called
|
|
549
|
+
* when the store fails to write the document, whatever it throws.
|
|
550
|
+
*/
|
|
551
|
+
async function ingestFile(
|
|
552
|
+
context: IngestContext,
|
|
553
|
+
input: IngestInput | IngestFromSource,
|
|
554
|
+
target: Target,
|
|
555
|
+
name: string,
|
|
556
|
+
mimeType: string,
|
|
557
|
+
detected: DocumentFormat,
|
|
558
|
+
progress: IngestProgress | undefined,
|
|
559
|
+
storeFailed: () => void,
|
|
560
|
+
work: IngestWork,
|
|
561
|
+
upload: Upload,
|
|
562
|
+
): Promise<DocumentMeta> {
|
|
563
|
+
const { store, now, ttlMs, maxUploadBytes, maxTextBytes, maxPdfPages, ingestTimeoutMs, scannedPdfPages, extractors, slotCapMs, keeps, forget } = context;
|
|
564
|
+
const { path, ref } = upload;
|
|
565
|
+
const byRef = ref !== undefined;
|
|
566
|
+
let format = detected;
|
|
567
|
+
// A file kept in the store (`putOriginal`, without a ref) needs its bytes in the server. A text
|
|
568
|
+
// may turn out to be a log once it is read.
|
|
569
|
+
const mayCopy = !byRef && (keeps(format, false) || (format === "text" && keeps("log", false)));
|
|
570
|
+
// A file at a path that its extractor reads itself (an isolated reader) is not read here at all.
|
|
571
|
+
const extractorReads = path !== undefined && extractorFor(format, extractors).readsPath === true && !mayCopy;
|
|
572
|
+
const { signal, dispose } = ingestSignal(name, input.signal, ingestTimeoutMs);
|
|
573
|
+
// Each long step works in slices, with pauses for other requests: one large upload no longer
|
|
574
|
+
// holds the whole server while it is read.
|
|
575
|
+
const slicer = new TimeSlicer(signal);
|
|
576
|
+
/** The bytes of the file, while they are needed: until it is extracted, or kept in the store. */
|
|
577
|
+
let bytes: Uint8Array | undefined;
|
|
578
|
+
let size = 0;
|
|
579
|
+
let sha256 = "";
|
|
580
|
+
/** The bytes to keep in the store (`putOriginal`), until they are written. */
|
|
581
|
+
let copy: Uint8Array | undefined;
|
|
582
|
+
/**
|
|
583
|
+
* A read of the file at `path`, or the signal's reason once it aborts: a volume that does not
|
|
584
|
+
* answer fails the ingest in its time, as an extractor does. The ingest keeps its turn until the
|
|
585
|
+
* read ends (`IngestSlot`).
|
|
586
|
+
*/
|
|
587
|
+
const readWithin = async <T>(read: Promise<T>): Promise<T> => {
|
|
588
|
+
work.abandoned = read;
|
|
589
|
+
const got = await untilAborted(read, signal);
|
|
590
|
+
work.abandoned = undefined;
|
|
591
|
+
return got;
|
|
592
|
+
};
|
|
593
|
+
let pages: number | undefined;
|
|
594
|
+
let reading: ReturnType<typeof readingOf>;
|
|
595
|
+
let text: string;
|
|
596
|
+
let wrapped: number;
|
|
597
|
+
let lines: string[];
|
|
598
|
+
let measured: Awaited<ReturnType<typeof measureText>>;
|
|
599
|
+
let outline: DocumentMeta["outline"];
|
|
600
|
+
let logProfile: DocumentMeta["logProfile"];
|
|
601
|
+
let quality: TextQuality = {};
|
|
602
|
+
let index: Awaited<ReturnType<typeof buildTextIndexInSlices>> | undefined;
|
|
603
|
+
try {
|
|
604
|
+
signal.throwIfAborted();
|
|
605
|
+
// The file is read once, at its turn, and never past the upload limit: one that has grown
|
|
606
|
+
// since it was looked at is refused. Its SHA-256 is taken as it is read, a slice at a time.
|
|
607
|
+
if (path === undefined) {
|
|
608
|
+
bytes = (input as IngestInput).bytes;
|
|
609
|
+
size = bytes.byteLength;
|
|
610
|
+
} else if (!extractorReads) {
|
|
611
|
+
// Cleared once taken apart: a variable of a block would hold the bytes in the suspended
|
|
612
|
+
// function until the ingest ends.
|
|
613
|
+
let got: SourceRead | undefined = await readWithin(readSource(path, maxUploadBytes, { keep: true, slicer, signal }));
|
|
614
|
+
size = checkedSize(name, got.size, maxUploadBytes);
|
|
615
|
+
bytes = got.bytes;
|
|
616
|
+
sha256 = got.sha256;
|
|
617
|
+
got = undefined;
|
|
618
|
+
}
|
|
619
|
+
// In a function of its own, so that the text as extracted is let go once it is prepared:
|
|
620
|
+
// the steps after it hold only the prepared text.
|
|
621
|
+
const read = async () => {
|
|
622
|
+
// What an extractor of your own reports once it has settled (from a timer, a worker) is
|
|
623
|
+
// not reported: the stages after it have begun.
|
|
624
|
+
let extracting = true;
|
|
625
|
+
let extracted: ExtractedText;
|
|
626
|
+
try {
|
|
627
|
+
// Kept, so that an ingest that stops waiting for it (its time is up, its caller left)
|
|
628
|
+
// keeps its turn until the extractor is done too: it still holds memory.
|
|
629
|
+
const extraction = extractText(bytes ?? NO_BYTES, {
|
|
630
|
+
name,
|
|
631
|
+
mimeType,
|
|
632
|
+
format,
|
|
633
|
+
// A scan is worth storing only if its pages can be shown later: that needs the file itself.
|
|
634
|
+
...(format === "pdf" && keeps(format, byRef) && scannedPdfPages > 0 ? { scannedPages: scannedPdfPages } : {}),
|
|
635
|
+
// The extractor reads the file from its path, once, within the upload limit.
|
|
636
|
+
...(extractorReads ? { path, maxUploadBytes } : {}),
|
|
637
|
+
signal,
|
|
638
|
+
maxTextBytes,
|
|
639
|
+
maxPages: maxPdfPages,
|
|
640
|
+
...(progress ? { onProgress: (report: ExtractProgress) => { if (extracting) progress.extracted(report); } } : {}),
|
|
641
|
+
}, extractors);
|
|
642
|
+
work.abandoned = extraction;
|
|
643
|
+
extracted = await untilAborted(extraction, signal);
|
|
644
|
+
work.abandoned = undefined;
|
|
645
|
+
// The bytes read from a path go once the extractor is done with them: their SHA-256 was
|
|
646
|
+
// taken as they were read, and only a copy for the store needs them. (Bytes given are the
|
|
647
|
+
// caller's, and are hashed next.)
|
|
648
|
+
if (path !== undefined && !mayCopy) bytes = undefined;
|
|
649
|
+
} finally {
|
|
650
|
+
extracting = false;
|
|
651
|
+
}
|
|
652
|
+
progress?.end();
|
|
653
|
+
// A character is at least one byte: a text this long is too large whatever it holds.
|
|
654
|
+
if (extracted.text.length > maxTextBytes) throw tooMuchText(name, maxTextBytes);
|
|
655
|
+
await slicer.pauseNow();
|
|
656
|
+
return { pages: extracted.pages, reading: readingOf(extracted), file: fileOf(extracted), ...await prepareText(extracted.text, slicer, progress && ((done, total) => progress.report("prepare", done, total, "characters"))) };
|
|
657
|
+
};
|
|
658
|
+
const done = await read();
|
|
659
|
+
({ pages, reading, text, wrapped, lines } = done);
|
|
660
|
+
progress?.end();
|
|
661
|
+
// Bytes given are hashed once the extractor is done with them, a slice at a time: the extractor
|
|
662
|
+
// is called at once at the ingest's turn, as before 0.9.0, so the ingests of one turn reach it
|
|
663
|
+
// in the order they came, and the SHA-256 is that of the bytes a kept copy holds.
|
|
664
|
+
if (path === undefined) sha256 = await sha256InSlices(bytes!, slicer);
|
|
665
|
+
if (path !== undefined && extractorReads) {
|
|
666
|
+
// What the extractor read of the file: its size and SHA-256. One that did not say is hashed
|
|
667
|
+
// here, a slice at a time, and nothing of it is kept.
|
|
668
|
+
let hashed = done.file;
|
|
669
|
+
if (!hashed) {
|
|
670
|
+
const got = await readWithin(readSource(path, maxUploadBytes, { keep: false, slicer, signal }));
|
|
671
|
+
hashed = { bytes: got.size, sha256: got.sha256 };
|
|
672
|
+
}
|
|
673
|
+
size = checkedSize(name, hashed.bytes, maxUploadBytes);
|
|
674
|
+
sha256 = hashed.sha256;
|
|
675
|
+
}
|
|
676
|
+
if (!text.trim()) throw new Error(`${name} did not contain any text.`);
|
|
677
|
+
if (format === "text" && looksLikeLog(lines)) format = "log";
|
|
678
|
+
// The bytes are let go once the text is read, unless the store keeps them.
|
|
679
|
+
if (keeps(format, byRef) && !byRef) copy = bytes;
|
|
680
|
+
bytes = undefined;
|
|
681
|
+
measured = await measureText(text, slicer);
|
|
682
|
+
if (measured.utf8 > maxTextBytes) throw tooMuchText(name, maxTextBytes);
|
|
683
|
+
outline = await buildOutlineInSlices(lines, format, slicer);
|
|
684
|
+
logProfile = format === "log" ? await buildLogProfileInSlices(lines, slicer) : undefined;
|
|
685
|
+
quality = await measureQuality(lines, format, slicer);
|
|
686
|
+
// The line index, so that the text can be read by range: a few bytes a line, built from the
|
|
687
|
+
// UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
|
|
688
|
+
// then loads whole, so that switching to reading by range finds it ready.
|
|
689
|
+
index = typeof store.putIndex === "function"
|
|
690
|
+
? await buildTextIndexInSlices(text, slicer, progress && ((done, total) => progress.report("index", done, total, "characters")))
|
|
691
|
+
: undefined;
|
|
692
|
+
progress?.end();
|
|
693
|
+
signal.throwIfAborted();
|
|
694
|
+
} finally {
|
|
695
|
+
dispose();
|
|
696
|
+
}
|
|
697
|
+
const created = now();
|
|
698
|
+
const expires = created.getTime() + ttlMs;
|
|
699
|
+
// Kept by its ref, or as a copy in the store, which has the bytes to write.
|
|
700
|
+
const keepOriginal = byRef ? keeps(format, true) : copy !== undefined;
|
|
701
|
+
// A copy: the outline's headings and the log's timestamps are pieces of the text, and a piece
|
|
702
|
+
// keeps the whole text in memory as long as it is held. A meta an application kept held its
|
|
703
|
+
// text: 25 MB of heap for a log of 10 MB in Hebrew, 194 MB for one of 100 MB. Copied through
|
|
704
|
+
// JSON, as a store that keeps it as JSON gives it back.
|
|
705
|
+
const meta: DocumentMeta = jsonCopy<DocumentMeta>({
|
|
706
|
+
id: target.id ?? `doc_${randomUUID().replaceAll("-", "")}`,
|
|
707
|
+
metaVersion: DOCUMENT_META_VERSION,
|
|
708
|
+
...(input.owner !== undefined ? { owner: input.owner } : {}),
|
|
709
|
+
// Never sent to the model, nor in a summary. An event holds it only with eventResults: true, in
|
|
710
|
+
// the full plan of run.finish and run.error.
|
|
711
|
+
...(target.scope !== undefined ? { scope: [...target.scope] } : {}),
|
|
712
|
+
// Nor these: the SHA-256 of the file, and where the application keeps it.
|
|
713
|
+
sha256,
|
|
714
|
+
...(keepOriginal && byRef ? { original: { ref, bytes: size, sha256 } } : {}),
|
|
715
|
+
name,
|
|
716
|
+
mimeType,
|
|
717
|
+
format,
|
|
718
|
+
bytes: size,
|
|
719
|
+
textBytes: measured.utf8,
|
|
720
|
+
jsonBytes: measured.json,
|
|
721
|
+
characters: text.length,
|
|
722
|
+
lines: lines.length,
|
|
723
|
+
estimatedTokens: measured.tokens,
|
|
724
|
+
wrappedLines: wrapped,
|
|
725
|
+
...(pages ? { pages } : {}),
|
|
726
|
+
...reading,
|
|
727
|
+
...(keepOriginal ? { originalKept: true } : {}),
|
|
728
|
+
outline,
|
|
729
|
+
...(logProfile ? { logProfile } : {}),
|
|
730
|
+
...quality,
|
|
731
|
+
createdAt: created.toISOString(),
|
|
732
|
+
// Never, for a time to live without end (or one that runs past what a date can hold).
|
|
733
|
+
expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
|
|
734
|
+
});
|
|
735
|
+
const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && index.textBytes === meta.textBytes
|
|
736
|
+
? serializeTextIndex(index)
|
|
737
|
+
: undefined;
|
|
738
|
+
// Each write is reported once done. What the listener of the events throws is not the store's failure.
|
|
739
|
+
const writes = (copy ? 1 : 0) + (savedIndex ? 1 : 0) + 1;
|
|
740
|
+
let written = 0;
|
|
741
|
+
let listenerFailed: { error: unknown } | undefined;
|
|
742
|
+
const wrote = (last: boolean) => {
|
|
743
|
+
if (!progress) return;
|
|
744
|
+
try {
|
|
745
|
+
progress.report("store", ++written, writes, "parts");
|
|
746
|
+
if (last) progress.end();
|
|
747
|
+
} catch (error) {
|
|
748
|
+
listenerFailed = { error };
|
|
749
|
+
throw error;
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
// An application's ID is looked at again just before the writes: another server may have stored
|
|
753
|
+
// a document under it while the file was read. Within the time the writes are given, as they are.
|
|
754
|
+
const clear = target.id !== undefined
|
|
755
|
+
&& await settleWithin(claim(context, { ...target, id: target.id }, name), slotCapMs, () => storeTimeout(name, slotCapMs, "read"));
|
|
756
|
+
// The files first, the document last: a document is there once its metadata is. Every call
|
|
757
|
+
// carries the owner and scope of the document.
|
|
758
|
+
const storing = (async () => {
|
|
759
|
+
if (clear) {
|
|
760
|
+
await store.delete(meta.id, target.context);
|
|
761
|
+
forget(meta.id);
|
|
762
|
+
}
|
|
763
|
+
if (copy) {
|
|
764
|
+
await store.putOriginal!(meta.id, copy, target.context);
|
|
765
|
+
copy = undefined;
|
|
766
|
+
wrote(false);
|
|
767
|
+
}
|
|
768
|
+
if (savedIndex) {
|
|
769
|
+
await store.putIndex!(meta.id, savedIndex, target.context);
|
|
770
|
+
wrote(false);
|
|
771
|
+
}
|
|
772
|
+
await store.put({ meta, text }, target.context);
|
|
773
|
+
wrote(true);
|
|
774
|
+
})();
|
|
775
|
+
try {
|
|
776
|
+
// A store that does not answer fails the ingest after `slotCapMs`: it held the ingest's turn,
|
|
777
|
+
// and the upload handler's room for the file, for as long as it did not answer.
|
|
778
|
+
await settleWithin(storing, slotCapMs, () => storeTimeout(name, slotCapMs));
|
|
779
|
+
} catch (error) {
|
|
780
|
+
// Do not leave a file of up to the upload limit, or a part of one, behind for a document
|
|
781
|
+
// that does not exist: once the writes have ended, when they have not yet. The removal is not
|
|
782
|
+
// waited for longer than the writes were. A document under the ID that is not this ingest's is
|
|
783
|
+
// left alone: the ID is taken when it is another owner's or another scope's, and live.
|
|
784
|
+
let taken = false;
|
|
785
|
+
let ended = false;
|
|
786
|
+
const remove = async () => {
|
|
787
|
+
taken = await removeOwn(context, target, meta) === "taken";
|
|
788
|
+
};
|
|
789
|
+
const removal = storing.then(remove, remove).catch(() => undefined).then(() => {
|
|
790
|
+
ended = true;
|
|
791
|
+
});
|
|
792
|
+
await settleWithin(removal, slotCapMs, () => new Error("")).catch(() => undefined);
|
|
793
|
+
// Writes that have not ended may still land, and so may their removal: the ID stays held in this
|
|
794
|
+
// library until they have, or another ingest of it could be written over, or removed. A store
|
|
795
|
+
// that never answers keeps that one ID refused here.
|
|
796
|
+
if (!ended) work.writes = removal;
|
|
797
|
+
// What the listener of the events threw is passed on as it is, and so is a scope the store
|
|
798
|
+
// cannot use: a mistake of the call, which the same call would make again.
|
|
799
|
+
if (listenerFailed?.error === error || DocumentScopeError.is(error)) throw error;
|
|
800
|
+
// The write failed because another document had the ID by then (a store that refuses an ID it
|
|
801
|
+
// has, as an insert with a unique key does): the answer of an ID that is taken.
|
|
802
|
+
if (taken) throw exists(name);
|
|
803
|
+
// The store's own error may name a path, a host or a bucket: it is the cause.
|
|
804
|
+
const failure = DocumentStoreError.is(error) ? error : new DocumentStoreError(error, { operation: "write" });
|
|
805
|
+
noteStoreWriteFailure(failure);
|
|
806
|
+
storeFailed();
|
|
807
|
+
throw failure;
|
|
808
|
+
}
|
|
809
|
+
// A copy of an earlier document of this ID, kept in memory, is not this one.
|
|
810
|
+
if (target.id !== undefined) forget(meta.id);
|
|
811
|
+
// The caller left while the document was written: it is not left behind.
|
|
812
|
+
if (input.signal?.aborted) await removeAbandoned(context, target, meta, work, input.signal.reason);
|
|
813
|
+
return meta;
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
/** `files.ingest` of the library that `context` describes. */
|
|
817
|
+
export async function ingestDocument(context: IngestContext, input: IngestInput | IngestFromSource): Promise<DocumentMeta> {
|
|
818
|
+
const { maxUploadBytes, ingests, slotCapMs, forget, ingesting } = context;
|
|
819
|
+
// The events first, so that every ingest that throws, even on what it was given, ends with ingest.error.
|
|
820
|
+
// What the caller's listener throws is passed on as it is, not told as a file that could not be read.
|
|
821
|
+
let listenerFailure: { error: unknown } | undefined;
|
|
822
|
+
const listener = input?.onEvent;
|
|
823
|
+
const events = new EventEmitter<IngestEvent>(input?.runId ?? newRunId("ing"), listener && ((event: IngestEvent) => {
|
|
824
|
+
try {
|
|
825
|
+
listener(event);
|
|
826
|
+
} catch (error) {
|
|
827
|
+
listenerFailure ??= { error };
|
|
828
|
+
throw error;
|
|
829
|
+
}
|
|
830
|
+
}));
|
|
831
|
+
let storeFailed = false;
|
|
832
|
+
/** The application's ID this ingest holds in `ingesting`, once it does. */
|
|
833
|
+
let holding: string | undefined;
|
|
834
|
+
const work: IngestWork = {};
|
|
835
|
+
try {
|
|
836
|
+
// A file at a path is looked at first, without being read, so that ingest.start gives its size.
|
|
837
|
+
// The library never writes, moves or deletes it.
|
|
838
|
+
let quietPath: string | undefined;
|
|
839
|
+
try {
|
|
840
|
+
quietPath = sourcePathOf(input);
|
|
841
|
+
} catch {
|
|
842
|
+
// Told once ingest.start is out.
|
|
843
|
+
}
|
|
844
|
+
// Given up on when the caller leaves, and failed when the volume does not answer in the time the
|
|
845
|
+
// ingest's store calls are given: the ingest's own time begins at its turn.
|
|
846
|
+
const stated = quietPath === undefined
|
|
847
|
+
? undefined
|
|
848
|
+
: await lookWithin(statSource(quietPath), input.signal, slotCapMs, "lstat").then((size) => ({ size }), (error: unknown) => ({ size: undefined, error }));
|
|
849
|
+
if (events.active) events.emit({ type: "ingest.start", ...startOf(input, stated?.size) });
|
|
850
|
+
checkOwner(input.owner);
|
|
851
|
+
const target = targetOf(input, context.rules);
|
|
852
|
+
// The path looked at, as it was made absolute then (the working directory may have changed
|
|
853
|
+
// since); checked again for an input it was not taken from, which throws here.
|
|
854
|
+
const path = quietPath ?? sourcePathOf(input);
|
|
855
|
+
const ref = originalRefOf(input, context.readsRefs);
|
|
856
|
+
const name = cleanFileName(input.name);
|
|
857
|
+
const mimeType = cleanMimeType(input.mimeType);
|
|
858
|
+
// Progress is worked out only for someone who listens.
|
|
859
|
+
const progress = events.active ? new IngestProgress(events) : undefined;
|
|
860
|
+
let meta: DocumentMeta;
|
|
861
|
+
try {
|
|
862
|
+
// A path that is not there, a link or a folder: the server's trouble, passed on as it is.
|
|
863
|
+
if (stated && "error" in stated) throw stated.error;
|
|
864
|
+
// Refused at once, without waiting for a turn, and without reading a file at a path.
|
|
865
|
+
checkedSize(name, path !== undefined ? stated!.size! : (input as IngestInput).bytes.byteLength, maxUploadBytes);
|
|
866
|
+
// A file whose name and type say nothing is known by its bytes: a PDF, an Office file, a page.
|
|
867
|
+
// Of a file at a path, only the parts looked at are read.
|
|
868
|
+
const bytes = (input as IngestInput).bytes;
|
|
869
|
+
// The parts read to tell the format are given up on, with the caller's reason, when the caller
|
|
870
|
+
// leaves, and fail the ingest when they do not answer in time, as the lstat does.
|
|
871
|
+
const sniffed = path !== undefined ? formatAtPath(name, mimeType, path, stated!.size!) : undefined;
|
|
872
|
+
const format = sniffed ? await lookWithin(sniffed, input.signal, slotCapMs, "read") : detectFormat(name, mimeType, bytes instanceof Uint8Array ? bytes : undefined);
|
|
873
|
+
if (target.id !== undefined) {
|
|
874
|
+
// An ID another ingest of this library is storing: refused, whoever's it is to be.
|
|
875
|
+
if (ingesting.has(target.id)) throw exists(name);
|
|
876
|
+
// A caller that has already gone: nothing is held, and the store is not asked.
|
|
877
|
+
input.signal?.throwIfAborted();
|
|
878
|
+
ingesting.add(target.id);
|
|
879
|
+
holding = target.id;
|
|
880
|
+
// An application's ID that is taken, before the file is read (again before it is written):
|
|
881
|
+
// within the time the writes are given, and given up on, with the caller's own reason, when
|
|
882
|
+
// the caller leaves meanwhile.
|
|
883
|
+
const asked = settleWithin(claim(context, { ...target, id: target.id }, name), slotCapMs, () => storeTimeout(name, slotCapMs, "read"));
|
|
884
|
+
await (input.signal ? untilAborted(asked, input.signal) : asked);
|
|
885
|
+
}
|
|
886
|
+
// Its turn (`maxConcurrentIngests`): a caller that gives up while it waits gets its own
|
|
887
|
+
// reason, as it would once the work had begun. (An ingest started inside another of this
|
|
888
|
+
// library, by an extractor of your own, waits for a turn like any other. Telling it apart
|
|
889
|
+
// with AsyncLocalStorage made pdf.js about five times slower on Node 22, for every PDF.)
|
|
890
|
+
const slot = new IngestSlot(await ingests.acquire(input.signal), slotCapMs);
|
|
891
|
+
try {
|
|
892
|
+
meta = await ingestFile(context, input, target, name, mimeType, format, progress, () => (storeFailed = true), work, { path, ref });
|
|
893
|
+
} finally {
|
|
894
|
+
slot.end(work.abandoned);
|
|
895
|
+
}
|
|
896
|
+
} catch (error) {
|
|
897
|
+
// A store that failed, a scope it cannot use, and a caller that gave up (its own reason), are
|
|
898
|
+
// passed on as they are; a file that could not be read is told with a code.
|
|
899
|
+
if (storeFailed || (input.signal?.aborted && error === input.signal.reason) || isStoreWriteFailure(error) || DocumentScopeError.is(error) || (listenerFailure && error === listenerFailure.error)) throw error;
|
|
900
|
+
throw toIngestError(error);
|
|
901
|
+
}
|
|
902
|
+
// Once more, before the document is told stored: a caller that has left by now gets its reason.
|
|
903
|
+
if (input.signal?.aborted) await removeAbandoned(context, target, meta, work, input.signal.reason);
|
|
904
|
+
try {
|
|
905
|
+
events.emit({ type: "ingest.finish", document: toDocumentSummary(meta) });
|
|
906
|
+
} catch (error) {
|
|
907
|
+
// The caller never gets the id: the document goes, as on a throw of the listener a moment
|
|
908
|
+
// earlier, while it is this ingest's own. The listener's error is passed on as it is.
|
|
909
|
+
await removeOwn(context, target, meta).catch(() => undefined);
|
|
910
|
+
forget(meta.id);
|
|
911
|
+
throw error;
|
|
912
|
+
}
|
|
913
|
+
return meta;
|
|
914
|
+
} catch (error) {
|
|
915
|
+
// A store's own error may name a host or a path, whatever it is: the event, which a browser
|
|
916
|
+
// may see, says only that the document could not be stored (a DocumentStoreError, 503).
|
|
917
|
+
events.emit({ type: "ingest.error", error: storeFailed ? storeWriteFailed() : eventErrorOf(error) });
|
|
918
|
+
throw error;
|
|
919
|
+
} finally {
|
|
920
|
+
if (holding !== undefined) {
|
|
921
|
+
// Once writes given up on have ended, and the removal of what they wrote (see `IngestWork`).
|
|
922
|
+
const id = holding;
|
|
923
|
+
if (work.writes) void work.writes.finally(() => ingesting.delete(id));
|
|
924
|
+
else ingesting.delete(id);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
}
|