llm-large-files 0.8.2 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +981 -0
- package/README.md +22 -17
- package/dist/access.d.ts +128 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +234 -0
- package/dist/access.js.map +1 -0
- package/dist/aggregate.d.ts +6 -0
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/aggregate.js +86 -13
- package/dist/aggregate.js.map +1 -1
- package/dist/analyze.d.ts +4 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +2 -2
- package/dist/analyze.js.map +1 -1
- package/dist/answer-info.d.ts +26 -0
- package/dist/answer-info.d.ts.map +1 -0
- package/dist/answer-info.js +32 -0
- package/dist/answer-info.js.map +1 -0
- package/dist/anthropic/adapter.d.ts +5 -1
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +35 -10
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +159 -14
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +743 -113
- 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/citations.d.ts +36 -0
- package/dist/citations.d.ts.map +1 -0
- package/dist/citations.js +291 -0
- package/dist/citations.js.map +1 -0
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +70 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +253 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +74 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +104 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +57 -13
- 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 +35 -5
- 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 +52 -36
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +54 -7
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +152 -41
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +38 -53
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +20 -25
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +59 -11
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +33 -7
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +39 -5
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +70 -9
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +53 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +100 -50
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +4 -4
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/http.d.ts +41 -3
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +40 -2
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +13 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -5
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +78 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +893 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +295 -33
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +458 -650
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +176 -10
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +807 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +79 -6
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +80 -4
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +247 -14
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +491 -227
- 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 +19 -4
- 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 +106 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +378 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +6 -4
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +9 -7
- package/dist/node/sse.js.map +1 -1
- package/dist/openai/adapter.d.ts +5 -1
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +53 -12
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +2 -1
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +5 -2
- package/dist/output-limit.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/pdf-outline.d.ts +71 -0
- package/dist/pdf-outline.d.ts.map +1 -0
- package/dist/pdf-outline.js +414 -0
- package/dist/pdf-outline.js.map +1 -0
- package/dist/plan.d.ts +137 -7
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +248 -26
- package/dist/plan.js.map +1 -1
- package/dist/prepare.d.ts +50 -0
- package/dist/prepare.d.ts.map +1 -0
- package/dist/prepare.js +207 -0
- package/dist/prepare.js.map +1 -0
- package/dist/ranged.d.ts +16 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +56 -12
- 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/search.d.ts +7 -0
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +72 -10
- package/dist/search.js.map +1 -1
- 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 +126 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +655 -141
- 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 +47 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +440 -71
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +165 -14
- package/dist/types.d.ts.map +1 -1
- package/dist/whole-cost.d.ts +37 -0
- package/dist/whole-cost.d.ts.map +1 -0
- package/dist/whole-cost.js +46 -0
- package/dist/whole-cost.js.map +1 -0
- package/docs/README.md +21 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +17 -10
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +147 -42
- package/docs/guides/deployment.md +380 -86
- package/docs/guides/errors-and-reliability.md +317 -67
- package/docs/guides/explorer-model.md +4 -1
- package/docs/guides/openai-compatible.md +47 -7
- package/docs/guides/own-adapter-and-loop.md +60 -16
- package/docs/guides/pdfs.md +219 -36
- package/docs/guides/storage.md +676 -145
- package/docs/guides/testing.md +149 -129
- package/docs/guides/vertex-and-gemini.md +169 -57
- package/docs/guides/web-app.md +318 -80
- package/docs/how-it-works.md +155 -30
- package/docs/measurements.md +215 -13
- package/docs/publishing.md +185 -37
- package/docs/reference/anthropic.md +12 -7
- package/docs/reference/ask.md +415 -47
- package/docs/reference/errors-and-retries.md +194 -14
- package/docs/reference/events.md +77 -27
- package/docs/reference/gemini.md +252 -87
- package/docs/reference/library.md +886 -178
- package/docs/reference/node.md +659 -111
- package/docs/reference/openai.md +21 -10
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +285 -30
- package/docs/security.md +404 -78
- package/docs/troubleshooting.md +151 -70
- package/docs/upgrading-0.10.md +472 -0
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +16 -3
- package/src/access.ts +267 -0
- package/src/aggregate.ts +92 -14
- package/src/analyze.ts +2 -2
- package/src/answer-info.ts +45 -0
- package/src/anthropic/adapter.ts +40 -11
- package/src/ask.ts +866 -115
- package/src/cache.ts +20 -5
- package/src/citations.ts +294 -0
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +290 -0
- package/src/errors.ts +131 -15
- package/src/events.ts +112 -24
- package/src/evidence.ts +35 -5
- package/src/extract.ts +56 -34
- package/src/gemini/adapter.ts +196 -43
- package/src/gemini/chat.ts +63 -78
- package/src/gemini/endpoints.ts +89 -16
- package/src/gemini/errors.ts +74 -11
- package/src/gemini/generate.ts +147 -57
- package/src/gemini/index.ts +4 -4
- package/src/http.ts +65 -4
- package/src/index.ts +13 -8
- package/src/ingest.ts +958 -0
- package/src/library.ts +711 -651
- package/src/map-reduce.ts +858 -70
- package/src/model.ts +113 -9
- package/src/node/handlers.ts +709 -221
- package/src/node/index.ts +14 -2
- package/src/node/ingest-child.ts +24 -6
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +379 -0
- package/src/node/sse.ts +9 -7
- package/src/openai/adapter.ts +56 -13
- package/src/output-limit.ts +5 -2
- package/src/pdf-layout.ts +69 -11
- package/src/pdf-outline.ts +400 -0
- package/src/plan.ts +287 -36
- package/src/prepare.ts +253 -0
- package/src/ranged.ts +48 -14
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/search.ts +69 -13
- package/src/source.ts +178 -0
- package/src/stores.ts +702 -142
- 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 +461 -73
- package/src/types.ts +151 -14
- package/src/whole-cost.ts +64 -0
package/dist/library.js
CHANGED
|
@@ -1,82 +1,27 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { buildLogProfileInSlices, buildOutlineInSlices, looksLikeLog } from "./analyze.js";
|
|
1
|
+
import { callerOf, checkMetaVersion, checkStuck, documentContext, isTimeLimit, mayUse, metaOf, OWNER_REQUIRED, SCOPE_REQUIRED, storeCall, storeContext, storeTimeout, stuckCalls, } from "./access.js";
|
|
3
2
|
import { givenBudget, resolveBudget } from "./budget.js";
|
|
4
3
|
import { DocumentCache, documentVersion } from "./cache.js";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { detectFormat, extractText } from "./extract.js";
|
|
4
|
+
import { until } from "./http.js";
|
|
5
|
+
import { ingestDocument, LONGEST_TIMER_MS } from "./ingest.js";
|
|
8
6
|
import { Limiter } from "./limiter.js";
|
|
7
|
+
import { canBeReadWhole, TABLE_FORMATS } from "./plan.js";
|
|
8
|
+
import { prepareDocuments } from "./prepare.js";
|
|
9
|
+
import { openRangedDocument, pieceKey, RangedDocument } from "./ranged.js";
|
|
10
|
+
import { SearchableDocument } from "./search.js";
|
|
9
11
|
import { TimeSlicer } from "./pause.js";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import { DOCUMENT_ID_PATTERN } from "./stores.js";
|
|
15
|
-
import { buildTextIndexInSlices, canSerialize, serializeTextIndex } from "./text-index.js";
|
|
16
|
-
import { measureText, prepareText, removeInvisible, sliceWhole, wellFormed } from "./text.js";
|
|
12
|
+
import { checkScope } from "./scope.js";
|
|
13
|
+
import { isSha256, sha256InSlices } from "./source.js";
|
|
14
|
+
import { APP_DOCUMENT_ID_PATTERN } from "./stores.js";
|
|
15
|
+
import { wellFormed } from "./text.js";
|
|
17
16
|
import { createDocumentTools } from "./tools.js";
|
|
18
17
|
export { DEFAULT_BUDGET } from "./budget.js";
|
|
19
|
-
export
|
|
20
|
-
return typeof value === "string" && DOCUMENT_ID_PATTERN.test(value);
|
|
21
|
-
}
|
|
22
|
-
/** The fields of a document that are safe to return to a browser. */
|
|
23
|
-
export function toDocumentSummary(meta) {
|
|
24
|
-
return {
|
|
25
|
-
id: meta.id,
|
|
26
|
-
name: meta.name,
|
|
27
|
-
mimeType: meta.mimeType,
|
|
28
|
-
format: meta.format,
|
|
29
|
-
bytes: meta.bytes,
|
|
30
|
-
lines: meta.lines,
|
|
31
|
-
estimatedTokens: meta.estimatedTokens,
|
|
32
|
-
...(meta.pages ? { pages: meta.pages } : {}),
|
|
33
|
-
...(meta.encoding ? { encoding: meta.encoding } : {}),
|
|
34
|
-
...(meta.replacedCharacters ? { replacedCharacters: meta.replacedCharacters } : {}),
|
|
35
|
-
expiresAt: meta.expiresAt,
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
/** An encoding's name as TextDecoder gives it ("windows-1255"): an extractor of your own may name another. */
|
|
39
|
-
const ENCODING_NAME = /^[a-z0-9][a-z0-9._:-]{0,39}$/i;
|
|
40
|
-
/**
|
|
41
|
-
* Whether the name is an older encoding, as `DocumentMeta.encoding` records: not UTF-8 or UTF-16,
|
|
42
|
-
* under any of their names ("utf8", "unicode"). The model is told the file is not in UTF-8.
|
|
43
|
-
*/
|
|
44
|
-
function olderEncoding(name) {
|
|
45
|
-
if (typeof name !== "string" || !ENCODING_NAME.test(name))
|
|
46
|
-
return false;
|
|
47
|
-
let known;
|
|
48
|
-
try {
|
|
49
|
-
known = new TextDecoder(name).encoding;
|
|
50
|
-
}
|
|
51
|
-
catch {
|
|
52
|
-
// A name TextDecoder does not know: the extractor read the file itself.
|
|
53
|
-
return true;
|
|
54
|
-
}
|
|
55
|
-
return known !== "utf-8" && known !== "utf-16le" && known !== "utf-16be";
|
|
56
|
-
}
|
|
57
|
-
/** How the text of a file was read, as its extractor said, in the fields of `DocumentMeta`. */
|
|
58
|
-
function readingOf(extracted) {
|
|
59
|
-
const { encoding, replacedCharacters } = extracted;
|
|
60
|
-
return {
|
|
61
|
-
...(olderEncoding(encoding) ? { encoding } : {}),
|
|
62
|
-
...(typeof replacedCharacters === "number" && Number.isSafeInteger(replacedCharacters) && replacedCharacters > 0 ? { replacedCharacters } : {}),
|
|
63
|
-
};
|
|
64
|
-
}
|
|
18
|
+
export { checkOwner, cleanFileName, cleanMimeType, NEVER_EXPIRES, toDocumentSummary } from "./ingest.js";
|
|
65
19
|
/**
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
* Names are shown to the model and in UIs, so a name must not be able to start a new line of the
|
|
69
|
-
* prompt, or disguise its extension. Most characters that show nothing are removed (tag characters,
|
|
70
|
-
* zero-width spaces); the variation selectors and joiners that scripts and emoji need are kept, and
|
|
71
|
-
* can still carry data a person does not see.
|
|
20
|
+
* Whether `value` has the shape of a document ID: one the library makes ("doc_" and 32 hex digits),
|
|
21
|
+
* or one an application may give (`APP_DOCUMENT_ID_PATTERN`, since 0.9.0), which the library's fit too.
|
|
72
22
|
*/
|
|
73
|
-
export function
|
|
74
|
-
|
|
75
|
-
// Control characters, line and paragraph separators, and text-direction controls become a space.
|
|
76
|
-
const spaced = base.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]+/gu, " ");
|
|
77
|
-
const name = removeInvisible(spaced).replace(/\s+/g, " ").trim();
|
|
78
|
-
// At most 255 characters, never half of an emoji. A flag cut short loses the tags left of it.
|
|
79
|
-
return (name.length > 255 ? removeInvisible(sliceWhole(name, 255)) : name) || "file";
|
|
23
|
+
export function isDocumentId(value) {
|
|
24
|
+
return typeof value === "string" && APP_DOCUMENT_ID_PATTERN.test(value);
|
|
80
25
|
}
|
|
81
26
|
/**
|
|
82
27
|
* Metadata with a whole file name. 0.5.0 and earlier cut a long name at 255 UTF-16 units, at times
|
|
@@ -87,224 +32,61 @@ function wholeName(meta) {
|
|
|
87
32
|
const name = wellFormed(meta.name);
|
|
88
33
|
return name === meta.name ? meta : { ...meta, name };
|
|
89
34
|
}
|
|
35
|
+
/** The key a caller's copy of a document is kept under in memory: the key of its scope, then the ID. */
|
|
36
|
+
const documentKey = (caller, id) => `${caller.key}\u0000${id}`;
|
|
37
|
+
/** A caller with no owner and no scope. */
|
|
38
|
+
const NO_CALLER = Object.freeze({ context: storeContext(undefined, undefined), key: "" });
|
|
90
39
|
/**
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
* through, as before, for JavaScript code that passes numeric user IDs.
|
|
40
|
+
* What `view_pages` answers for a file the application keeps (`IngestInput.original`) that is no
|
|
41
|
+
* longer the one that was ingested. New in 0.9.0.
|
|
94
42
|
*/
|
|
95
|
-
|
|
96
|
-
if (owner === undefined || (typeof owner === "string" && owner.trim() !== "") || (typeof owner === "number" && Number.isFinite(owner)))
|
|
97
|
-
return;
|
|
98
|
-
throw new TypeError("owner must be a string that is not empty or only spaces, such as the signed-in user's ID. To let anyone with the document's ID use it, leave owner out.");
|
|
99
|
-
}
|
|
100
|
-
/**
|
|
101
|
-
* A read of the store. Whatever it throws is passed on as a `DocumentStoreError`: a store that
|
|
102
|
-
* could not be read is not a document that is gone, and its own error names paths or hosts.
|
|
103
|
-
*/
|
|
104
|
-
async function reading(read) {
|
|
105
|
-
try {
|
|
106
|
-
return await read();
|
|
107
|
-
}
|
|
108
|
-
catch (error) {
|
|
109
|
-
throw error instanceof DocumentStoreError ? error : new DocumentStoreError(error);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
43
|
+
const changedOriginal = (file) => `${file} changed on the server since it was read. Attach it again to look at its pages.`;
|
|
112
44
|
/**
|
|
113
|
-
*
|
|
114
|
-
*
|
|
45
|
+
* Where the application keeps the uploaded file of a document (`DocumentMeta.original`), when its
|
|
46
|
+
* metadata says so in the shape the library writes. Undefined for one kept in the store, and for
|
|
47
|
+
* one written by hand in another shape, which reads as missing.
|
|
115
48
|
*/
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
49
|
+
function refOf(meta) {
|
|
50
|
+
const original = meta.original;
|
|
51
|
+
if (typeof original !== "object" || original === null)
|
|
52
|
+
return undefined;
|
|
53
|
+
const { ref, bytes, sha256 } = original;
|
|
54
|
+
return typeof ref === "string" && ref.length > 0 && typeof bytes === "number" && Number.isSafeInteger(bytes) && bytes >= 0 && isSha256(sha256)
|
|
55
|
+
? { ref, bytes, sha256 }
|
|
56
|
+
: undefined;
|
|
119
57
|
}
|
|
120
58
|
/** Default for `cacheBytes`. */
|
|
121
59
|
export const DEFAULT_CACHE_BYTES = 256 * 1024 * 1024;
|
|
122
|
-
/** The refusal of a file whose text is larger than `maxTextBytes`. */
|
|
123
|
-
const tooMuchText = (name, maxTextBytes) => 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.`);
|
|
124
60
|
/** Default for `maxPdfPages`. */
|
|
125
61
|
export const DEFAULT_MAX_PDF_PAGES = 5_000;
|
|
126
62
|
/** Default for `maxTextBytes`, when `maxUploadBytes` is not larger: 100 MB. */
|
|
127
63
|
export const DEFAULT_MAX_TEXT_BYTES = 100 * 1024 * 1024;
|
|
128
64
|
/** Default for `ingestTimeoutMs`: 2 minutes. */
|
|
129
65
|
export const DEFAULT_INGEST_TIMEOUT_MS = 120_000;
|
|
130
|
-
/**
|
|
131
|
-
const
|
|
132
|
-
/**
|
|
133
|
-
|
|
134
|
-
return JSON.parse(JSON.stringify(value));
|
|
135
|
-
}
|
|
136
|
-
/** `work`, or the error `late` makes once `ms` have passed without it settling. */
|
|
137
|
-
function settleWithin(work, ms, late) {
|
|
138
|
-
let timer;
|
|
139
|
-
const timeUp = new Promise((_, reject) => {
|
|
140
|
-
timer = setTimeout(() => reject(late()), ms);
|
|
141
|
-
});
|
|
142
|
-
return Promise.race([work, timeUp]).finally(() => clearTimeout(timer));
|
|
143
|
-
}
|
|
144
|
-
/**
|
|
145
|
-
* The turn of one ingest (`maxConcurrentIngests`). It is given back when the ingest ends; when the
|
|
146
|
-
* ingest gave up on work that goes on (an extractor that does not stop on the signal, such as a
|
|
147
|
-
* PDF being parsed when its caller left), once that work ends, or `capMs` later when it does not.
|
|
148
|
-
* (Store writes that do not end fail the ingest after `capMs`: see `ingestFile`.)
|
|
149
|
-
*/
|
|
150
|
-
class IngestSlot {
|
|
151
|
-
release;
|
|
152
|
-
capMs;
|
|
153
|
-
released = false;
|
|
154
|
-
timer;
|
|
155
|
-
constructor(release, capMs) {
|
|
156
|
-
this.release = release;
|
|
157
|
-
this.capMs = capMs;
|
|
158
|
-
}
|
|
159
|
-
free = () => {
|
|
160
|
-
if (this.released)
|
|
161
|
-
return;
|
|
162
|
-
this.released = true;
|
|
163
|
-
clearTimeout(this.timer);
|
|
164
|
-
this.release();
|
|
165
|
-
};
|
|
166
|
-
/**
|
|
167
|
-
* Gives the turn back `capMs` from now at the latest. The timer keeps the process alive: work
|
|
168
|
-
* that never ends may hold nothing that does, and ingests waiting for the turn would be lost.
|
|
169
|
-
*/
|
|
170
|
-
limit() {
|
|
171
|
-
if (this.released || this.timer !== undefined)
|
|
172
|
-
return;
|
|
173
|
-
this.timer = setTimeout(this.free, this.capMs);
|
|
174
|
-
}
|
|
175
|
-
/** The ingest is over: the turn goes back now, or once `abandoned` ends (`capMs` at the latest). */
|
|
176
|
-
end(abandoned) {
|
|
177
|
-
if (!abandoned)
|
|
178
|
-
return this.free();
|
|
179
|
-
abandoned.then(this.free, this.free);
|
|
180
|
-
this.limit();
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
/** A time limit in the words of a message: "500 ms", "45 s", "2 min". */
|
|
184
|
-
function formatDuration(ms) {
|
|
185
|
-
if (ms < 1_000)
|
|
186
|
-
return `${Math.max(1, Math.round(ms))} ms`;
|
|
187
|
-
if (ms < 120_000)
|
|
188
|
-
return `${Number((ms / 1_000).toFixed(1))} s`;
|
|
189
|
-
return `${Number((ms / 60_000).toFixed(1))} min`;
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* The signal one ingest runs under: aborted when the caller's is, or when `timeoutMs` has passed
|
|
193
|
-
* (with an error that says the file took too long). `dispose` stops the timer.
|
|
194
|
-
*/
|
|
195
|
-
function ingestSignal(name, caller, timeoutMs) {
|
|
196
|
-
const controller = new AbortController();
|
|
197
|
-
const onAbort = () => controller.abort(caller.reason);
|
|
198
|
-
if (caller?.aborted)
|
|
199
|
-
controller.abort(caller.reason);
|
|
200
|
-
else
|
|
201
|
-
caller?.addEventListener("abort", onAbort, { once: true });
|
|
202
|
-
const timer = timeoutMs > 0 && timeoutMs <= LONGEST_TIMER_MS
|
|
203
|
-
? 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)
|
|
204
|
-
: undefined;
|
|
205
|
-
return {
|
|
206
|
-
signal: controller.signal,
|
|
207
|
-
dispose() {
|
|
208
|
-
clearTimeout(timer);
|
|
209
|
-
caller?.removeEventListener("abort", onAbort);
|
|
210
|
-
},
|
|
211
|
-
};
|
|
212
|
-
}
|
|
66
|
+
/** Default for `wholeDocumentBytes`. */
|
|
67
|
+
export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
|
|
68
|
+
/** Default for `storeTimeoutMs`: 30 seconds. */
|
|
69
|
+
export const DEFAULT_STORE_TIMEOUT_MS = 30_000;
|
|
213
70
|
/**
|
|
214
|
-
*
|
|
215
|
-
*
|
|
71
|
+
* Default for `maxStuckStoreCalls`: half of the threads of libuv's pool, and at least 1. The pool
|
|
72
|
+
* is read from `UV_THREADPOOL_SIZE` as libuv reads it (`atoi`): 4 when it is not set; its leading
|
|
73
|
+
* digits ("32abc" is 32); 1 thread for a value without them or for 0 ("", "x", "0"), which a
|
|
74
|
+
* template with an empty value gives; 1,024 at most, and for a value below 0, which libuv reads as
|
|
75
|
+
* a number without a sign, past the most.
|
|
216
76
|
*/
|
|
217
|
-
function
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
const
|
|
222
|
-
|
|
223
|
-
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
/** The message of `ingest.error` when the store failed to write the document. */
|
|
227
|
-
const STORE_WRITE_FAILED = "The document could not be stored. Try again later.";
|
|
228
|
-
/** The least time between two `ingest.progress` events of one stage, in milliseconds: a slice of `TimeSlicer`. */
|
|
229
|
-
const PROGRESS_MS = 12;
|
|
230
|
-
const EXTRACT_STAGES = new Set(["extract", "check", "pictures", "decode"]);
|
|
231
|
-
const EXTRACT_UNITS = new Set(["pages", "parts", "bytes"]);
|
|
232
|
-
const isCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
233
|
-
/** What `ingest.start` says of an ingest, worked out from whatever it was given: the checks come after it. */
|
|
234
|
-
function startOf(input) {
|
|
235
|
-
try {
|
|
236
|
-
const name = typeof input?.name === "string" ? cleanFileName(input.name) : "";
|
|
237
|
-
const mimeType = (typeof input?.mimeType === "string" ? input.mimeType.trim() : "") || "application/octet-stream";
|
|
238
|
-
const bytes = input?.bytes?.byteLength;
|
|
239
|
-
return { name, format: detectFormat(name, mimeType), bytes: isCount(bytes) ? bytes : 0 };
|
|
240
|
-
}
|
|
241
|
-
catch {
|
|
242
|
-
return { name: "", format: "text", bytes: 0 };
|
|
77
|
+
function defaultMaxStuck() {
|
|
78
|
+
const value = globalThis.process?.env?.UV_THREADPOOL_SIZE;
|
|
79
|
+
let pool = 4;
|
|
80
|
+
if (value !== undefined) {
|
|
81
|
+
const given = Number.parseInt(value, 10);
|
|
82
|
+
pool = Number.isNaN(given) || given === 0 ? 1 : given < 0 ? 1_024 : Math.min(1_024, given);
|
|
243
83
|
}
|
|
84
|
+
return Math.max(1, Math.floor(pool / 2));
|
|
244
85
|
}
|
|
245
|
-
/**
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
* after the other end in that order. Made only when someone listens.
|
|
250
|
-
*/
|
|
251
|
-
class IngestProgress {
|
|
252
|
-
events;
|
|
253
|
-
/** Each stage that reported, in the order it first did: when it last sent, and its last progress. */
|
|
254
|
-
stages = new Map();
|
|
255
|
-
/** Set once a stage after the extractor's began: an extract stage is not reported again. */
|
|
256
|
-
extractOver = false;
|
|
257
|
-
constructor(events) {
|
|
258
|
-
this.events = events;
|
|
259
|
-
}
|
|
260
|
-
report(stage, done, total, unit) {
|
|
261
|
-
if (!EXTRACT_STAGES.has(stage))
|
|
262
|
-
this.extractOver = true;
|
|
263
|
-
const last = { done, total, unit, sent: false };
|
|
264
|
-
let state = this.stages.get(stage);
|
|
265
|
-
if (!state) {
|
|
266
|
-
state = { sentAt: Number.NEGATIVE_INFINITY, completed: false, last };
|
|
267
|
-
this.stages.set(stage, state);
|
|
268
|
-
}
|
|
269
|
-
state.last = last;
|
|
270
|
-
const now = performance.now();
|
|
271
|
-
const completes = !state.completed && total !== undefined && done >= total;
|
|
272
|
-
if (completes)
|
|
273
|
-
state.completed = true;
|
|
274
|
-
if (completes || now - state.sentAt >= PROGRESS_MS) {
|
|
275
|
-
state.sentAt = now;
|
|
276
|
-
this.send(stage, last);
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
/** The progress an extractor reported (`ExtractInput.onProgress`). One of your own may send anything: what does not fit is left out. */
|
|
280
|
-
extracted(progress) {
|
|
281
|
-
if (this.extractOver)
|
|
282
|
-
return;
|
|
283
|
-
const stage = progress?.stage ?? "extract";
|
|
284
|
-
if (!EXTRACT_STAGES.has(stage) || !EXTRACT_UNITS.has(progress?.unit) || !isCount(progress?.done))
|
|
285
|
-
return;
|
|
286
|
-
this.report(stage, progress.done, isCount(progress.total) ? progress.total : undefined, progress.unit);
|
|
287
|
-
}
|
|
288
|
-
/** The stages so far are over: the last progress of each, when it was held back, goes out, in the order they began. */
|
|
289
|
-
end() {
|
|
290
|
-
const held = [...this.stages].filter(([, state]) => !state.last.sent);
|
|
291
|
-
this.stages.clear();
|
|
292
|
-
for (const [stage, state] of held)
|
|
293
|
-
this.send(stage, state.last);
|
|
294
|
-
}
|
|
295
|
-
send(stage, last) {
|
|
296
|
-
last.sent = true;
|
|
297
|
-
this.events.emit({
|
|
298
|
-
type: "ingest.progress",
|
|
299
|
-
stage,
|
|
300
|
-
done: last.done,
|
|
301
|
-
...(last.total !== undefined ? { total: last.total } : {}),
|
|
302
|
-
unit: last.unit,
|
|
303
|
-
});
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
/** Default for `wholeDocumentBytes`. */
|
|
307
|
-
export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
|
|
86
|
+
/** Looks at pages that run at once in a library, unless `maxConcurrentPageLooks` says otherwise. */
|
|
87
|
+
const DEFAULT_PAGE_LOOKS = 1;
|
|
88
|
+
/** How long a look at pages waits for its turn, unless `pageLookWaitMs` says otherwise. */
|
|
89
|
+
const DEFAULT_PAGE_LOOK_WAIT_MS = 30_000;
|
|
308
90
|
/**
|
|
309
91
|
* A number option as it was given, or `fallback` when it was left out. NaN, which
|
|
310
92
|
* `Number(process.env.X)` gives for a variable that is not set, and a value that is not a number
|
|
@@ -334,37 +116,88 @@ export function createLargeFiles(options) {
|
|
|
334
116
|
const now = options.now ?? (() => new Date());
|
|
335
117
|
const { store } = options;
|
|
336
118
|
const cacheBytes = Math.max(0, numberOption("cacheBytes", options.cacheBytes, DEFAULT_CACHE_BYTES));
|
|
337
|
-
/**
|
|
119
|
+
/** What every call must name (`requireOwner`, `requireScope`). */
|
|
120
|
+
const rules = Object.freeze({ requireOwner: options.requireOwner === true, requireScope: options.requireScope === true });
|
|
121
|
+
/**
|
|
122
|
+
* Documents ready to search, and decoded pieces of documents read by range, in one memory budget.
|
|
123
|
+
* Each is kept under the key of the caller's scope and the document's ID (`documentKey`): one ID
|
|
124
|
+
* in two scopes is two documents, and the copy of one is never served to the other. Its version
|
|
125
|
+
* (`documentVersion`) holds the document's owner and scope too, so a copy is not served to
|
|
126
|
+
* another owner either, once another document is stored under the same ID.
|
|
127
|
+
*/
|
|
338
128
|
const cache = new DocumentCache(cacheBytes, Math.max(0, Math.trunc(numberOption("cacheSize", options.cacheSize, Number.POSITIVE_INFINITY))));
|
|
339
|
-
/** Forgets everything kept of
|
|
129
|
+
/** Forgets everything kept of the document of one key (`documentKey`): the document, and its pieces. */
|
|
130
|
+
const forgetKey = (key) => {
|
|
131
|
+
cache.delete(key);
|
|
132
|
+
cache.deletePrefix(pieceKey(key, 0).slice(0, -1));
|
|
133
|
+
};
|
|
134
|
+
/** Whether `key` is that of document `id`, or of one of its pieces, in any scope. */
|
|
135
|
+
const keyOfId = (key, id) => {
|
|
136
|
+
const rest = key.slice(key.indexOf("\u0000") + 1);
|
|
137
|
+
return rest === id || rest.startsWith(`${id}#`);
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* Forgets everything kept of document `id`, in every scope: it was deleted, or written again.
|
|
141
|
+
* In a store that keeps no scopes apart, the copies of all scopes are of that one document.
|
|
142
|
+
*/
|
|
340
143
|
const forget = (id) => {
|
|
341
|
-
cache.
|
|
342
|
-
|
|
144
|
+
cache.deleteWhere((key) => keyOfId(key, id));
|
|
145
|
+
for (const key of rebuildIndex)
|
|
146
|
+
if (keyOfId(key, id))
|
|
147
|
+
rebuildIndex.delete(key);
|
|
343
148
|
};
|
|
149
|
+
/** The most time one store call may take (`storeTimeoutMs`): 0 for no limit. */
|
|
150
|
+
const storeTimeoutMs = Math.max(0, numberOption("storeTimeoutMs", options.storeTimeoutMs, DEFAULT_STORE_TIMEOUT_MS));
|
|
151
|
+
/** The most time one sweep may take (`sweepTimeoutMs`): 0 for no limit. */
|
|
152
|
+
const sweepTimeoutMs = Math.max(0, numberOption("sweepTimeoutMs", options.sweepTimeoutMs, 0));
|
|
153
|
+
/** While this many calls of the process are stuck, store calls of this library fail at once (`maxStuckStoreCalls`). */
|
|
154
|
+
const maxStuckStoreCalls = Math.max(1, Math.trunc(numberOption("maxStuckStoreCalls", options.maxStuckStoreCalls, defaultMaxStuck())));
|
|
155
|
+
/**
|
|
156
|
+
* A call of the store, within `storeTimeoutMs`, refused at once while too many calls of the
|
|
157
|
+
* process are stuck. `signal` ends the caller's wait, never the call: a call that other callers
|
|
158
|
+
* wait on too (an opening of a document) is given none.
|
|
159
|
+
*/
|
|
160
|
+
const timed = (operation, call, signal) => (storeCall(operation, call, { timeoutMs: storeTimeoutMs, maxStuck: maxStuckStoreCalls, signal }));
|
|
161
|
+
/**
|
|
162
|
+
* A read of the store. Whatever it throws is passed on as a `DocumentStoreError`: a store that
|
|
163
|
+
* could not be read is not a document that is gone, and its own error names paths or hosts.
|
|
164
|
+
*/
|
|
165
|
+
const reading = (read, signal) => timed("read", read, signal);
|
|
344
166
|
/** Documents being opened, so that calls arriving together open each one once. */
|
|
345
167
|
const opening = new Map();
|
|
346
|
-
/**
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
168
|
+
/**
|
|
169
|
+
* The store, to read the text of a document by range rather than load it whole: each call carries
|
|
170
|
+
* `context`: the caller's scope, and the document's owner when it has one (`documentContext`).
|
|
171
|
+
* A document read by range is shared by every caller of its scope: its reads have a time limit,
|
|
172
|
+
* and no caller's signal.
|
|
173
|
+
*/
|
|
174
|
+
const rangeStore = (context) => ({
|
|
175
|
+
readTextRange: (id, start, end) => reading(() => store.readTextRange(id, start, end, context)),
|
|
176
|
+
...(store.getIndex ? { getIndex: (id) => reading(() => store.getIndex(id, context)) } : {}),
|
|
177
|
+
...(store.putIndex ? { putIndex: (id, index) => timed("write", () => store.putIndex(id, index, context)) } : {}),
|
|
178
|
+
});
|
|
352
179
|
/** The uploaded file of a document, when the store keeps such files. */
|
|
353
|
-
const loadOriginal =
|
|
180
|
+
const loadOriginal = (id, context, signal) => reading(() => store.getOriginal(id, context), signal);
|
|
181
|
+
/**
|
|
182
|
+
* Removals of documents (`delete`) take their turns, one at a time: a store that does not answer
|
|
183
|
+
* then holds one thread of the pool for them, not one for each.
|
|
184
|
+
*/
|
|
185
|
+
const removals = new Limiter(1);
|
|
354
186
|
const wholeDocumentBytes = Math.max(0, numberOption("wholeDocumentBytes", options.wholeDocumentBytes, DEFAULT_WHOLE_DOCUMENT_BYTES));
|
|
355
|
-
/** Documents whose saved index did not match their text: the next opening builds it from the text. */
|
|
187
|
+
/** Documents (by `documentKey`) whose saved index did not match their text: the next opening builds it from the text. */
|
|
356
188
|
const rebuildIndex = new Set();
|
|
357
189
|
const scan = {
|
|
358
190
|
chunkBytes: Math.max(1, Math.trunc(numberOption("scanChunkBytes", options.scanChunkBytes, 1024 * 1024, true))),
|
|
359
191
|
limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentScans", options.maxConcurrentScans, 4)))),
|
|
360
|
-
onBroken: (
|
|
361
|
-
rebuildIndex.add(
|
|
362
|
-
|
|
192
|
+
onBroken: (key) => {
|
|
193
|
+
rebuildIndex.add(key);
|
|
194
|
+
forgetKey(key);
|
|
363
195
|
},
|
|
364
196
|
pieces: {
|
|
365
197
|
get: (key, version) => cache.get(key, version),
|
|
366
|
-
// A piece belongs to its document: it is not one of the `cacheSize` documents, and leaves with
|
|
367
|
-
|
|
198
|
+
// A piece belongs to its document: it is not one of the `cacheSize` documents, and leaves with
|
|
199
|
+
// it. The document's key is all before the last "#", which no ID holds, and no scope key either.
|
|
200
|
+
set: (key, version, piece) => cache.set(key, version, piece, key.slice(0, key.lastIndexOf("#"))),
|
|
368
201
|
// A quarter of the cache: a few documents can be kept, and no one pushes out all the rest.
|
|
369
202
|
maxDocumentBytes: cacheBytes / 4,
|
|
370
203
|
},
|
|
@@ -374,423 +207,398 @@ export function createLargeFiles(options) {
|
|
|
374
207
|
const ingests = new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentIngests", options.maxConcurrentIngests, 2))));
|
|
375
208
|
/** How long work an ingest waits on, or gave up on, may keep its turn (see `IngestSlot`). */
|
|
376
209
|
const slotCapMs = ingestTimeoutMs > 0 && ingestTimeoutMs <= LONGEST_TIMER_MS ? ingestTimeoutMs : DEFAULT_INGEST_TIMEOUT_MS;
|
|
210
|
+
/**
|
|
211
|
+
* The looks at pages of every question of this library take their turns (`maxConcurrentPageLooks`).
|
|
212
|
+
* A look reads its original within the time the library gives its store calls (`slotCapMs`).
|
|
213
|
+
*/
|
|
214
|
+
const pageLooks = {
|
|
215
|
+
limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentPageLooks", options.maxConcurrentPageLooks, DEFAULT_PAGE_LOOKS)))),
|
|
216
|
+
waitMs: Math.max(0, numberOption("pageLookWaitMs", options.pageLookWaitMs, DEFAULT_PAGE_LOOK_WAIT_MS)),
|
|
217
|
+
holdMs: slotCapMs,
|
|
218
|
+
};
|
|
377
219
|
const scannedPdfPages = Math.max(0, Math.trunc(numberOption("scannedPdfPages", options.scannedPdfPages, 30)));
|
|
378
|
-
|
|
379
|
-
|
|
220
|
+
const { originals } = options;
|
|
221
|
+
if (originals !== undefined && (typeof originals !== "object" || originals === null || typeof originals.read !== "function")) {
|
|
222
|
+
throw new TypeError("originals must be an object with a read(ref, context) method, such as fileOriginals(root) gives.");
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Whether the uploaded file of a document of this format is kept: by its ref (`IngestInput.original`),
|
|
226
|
+
* which `originals` reads back, or as a copy in the store (`putOriginal`).
|
|
227
|
+
*/
|
|
228
|
+
const keeps = (format, byRef) => keepOriginals.has(format) && (byRef ? originals !== undefined : typeof store.putOriginal === "function");
|
|
229
|
+
/**
|
|
230
|
+
* Whether the original of a document, which its metadata says is kept, can be read: by its ref,
|
|
231
|
+
* through `originals`, or from the store (`getOriginal`).
|
|
232
|
+
*/
|
|
233
|
+
const readable = (meta) => (meta.original !== undefined && meta.original !== null ? originals !== undefined : typeof store.getOriginal === "function");
|
|
234
|
+
/** Whether `view_pages` can show the pages of a document: a PDF whose original is kept, and can be read. */
|
|
235
|
+
const viewableMeta = (meta) => meta.format === "pdf" && meta.originalKept === true && readable(meta);
|
|
236
|
+
/** What `ingest` (src/ingest.ts) needs of this library. */
|
|
237
|
+
const ingestContext = {
|
|
238
|
+
store,
|
|
239
|
+
now,
|
|
240
|
+
ttlMs,
|
|
241
|
+
maxUploadBytes,
|
|
242
|
+
maxTextBytes,
|
|
243
|
+
maxPdfPages,
|
|
244
|
+
ingestTimeoutMs,
|
|
245
|
+
scannedPdfPages,
|
|
246
|
+
// Read at each ingest, as before the move: an application may set them after.
|
|
247
|
+
get extractors() {
|
|
248
|
+
return options.extractors;
|
|
249
|
+
},
|
|
250
|
+
ingests,
|
|
251
|
+
slotCapMs,
|
|
252
|
+
maxStuck: maxStuckStoreCalls,
|
|
253
|
+
keeps,
|
|
254
|
+
readsRefs: originals !== undefined,
|
|
255
|
+
forget,
|
|
256
|
+
rules,
|
|
257
|
+
ingesting: new Set(),
|
|
258
|
+
};
|
|
380
259
|
/**
|
|
381
|
-
* The document as the store describes it now
|
|
382
|
-
* deleted (by this server or another one sharing the store), or has
|
|
260
|
+
* The document as the store describes it now, asked with the caller's context: undefined when it
|
|
261
|
+
* was never there, has been deleted (by this server or another one sharing the store), or has
|
|
262
|
+
* expired. Whether the caller may use it is `metaFor`'s to say.
|
|
383
263
|
*/
|
|
384
|
-
async function currentMeta(id) {
|
|
264
|
+
async function currentMeta(id, caller) {
|
|
385
265
|
if (!isDocumentId(id))
|
|
386
266
|
return undefined;
|
|
387
|
-
const meta = await reading(() => store.getMeta(id));
|
|
267
|
+
const meta = metaOf(await reading(() => store.getMeta(id, caller.context), caller.signal), id);
|
|
268
|
+
if (meta)
|
|
269
|
+
checkMetaVersion(meta);
|
|
388
270
|
if (!meta || Date.parse(meta.expiresAt) <= now().getTime()) {
|
|
389
|
-
|
|
271
|
+
forgetKey(documentKey(caller, id));
|
|
390
272
|
return undefined;
|
|
391
273
|
}
|
|
392
274
|
return wholeName(meta);
|
|
393
275
|
}
|
|
276
|
+
/** The document, when `caller` may use it: one of another owner or scope is missing, not forbidden. */
|
|
277
|
+
async function metaFor(id, caller) {
|
|
278
|
+
const meta = await currentMeta(id, caller);
|
|
279
|
+
return meta && mayUse(meta, caller, rules) ? meta : undefined;
|
|
280
|
+
}
|
|
394
281
|
/**
|
|
395
|
-
* A document ready to read and search. The store is asked first,
|
|
396
|
-
* used only while the store still has the same document. `known` is
|
|
397
|
-
* the store, to save asking twice.
|
|
282
|
+
* A document ready to read and search, for `caller`, who may use it. The store is asked first,
|
|
283
|
+
* every time: a kept copy is used only while the store still has the same document. `known` is
|
|
284
|
+
* metadata just read from the store and checked, to save asking twice. One opening serves every
|
|
285
|
+
* caller of the scope who asks meanwhile: its reads have time limits, and each caller stops
|
|
286
|
+
* waiting for it when its own signal aborts, which leaves the others waiting (0.10.0).
|
|
398
287
|
*/
|
|
399
|
-
async function load(id, known) {
|
|
400
|
-
const meta = known ?? await
|
|
288
|
+
async function load(id, caller, known) {
|
|
289
|
+
const meta = known ?? await metaFor(id, caller);
|
|
401
290
|
if (!meta)
|
|
402
291
|
return undefined;
|
|
292
|
+
const key = documentKey(caller, id);
|
|
403
293
|
const version = documentVersion(meta);
|
|
404
|
-
const cached = cache.get(
|
|
294
|
+
const cached = cache.get(key, version);
|
|
405
295
|
if (cached && !cached.broken)
|
|
406
296
|
return cached;
|
|
407
|
-
const
|
|
408
|
-
let pending = opening.get(
|
|
297
|
+
const opened = `${key}|${version}`;
|
|
298
|
+
let pending = opening.get(opened);
|
|
409
299
|
if (!pending) {
|
|
410
|
-
|
|
411
|
-
|
|
300
|
+
// Kept once opened, whether or not a caller still waits for it.
|
|
301
|
+
pending = open(id, meta, caller, key)
|
|
302
|
+
.then((document) => {
|
|
303
|
+
if (document)
|
|
304
|
+
cache.set(key, version, document);
|
|
305
|
+
return document;
|
|
306
|
+
})
|
|
307
|
+
.finally(() => opening.delete(opened));
|
|
308
|
+
opening.set(opened, pending);
|
|
412
309
|
}
|
|
413
|
-
|
|
414
|
-
if (document)
|
|
415
|
-
cache.set(id, version, document);
|
|
416
|
-
return document;
|
|
310
|
+
return until(pending, caller.signal);
|
|
417
311
|
}
|
|
418
|
-
/**
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
312
|
+
/**
|
|
313
|
+
* Reads a document from the store: its index, to read it by range, or all of it. `meta` is what
|
|
314
|
+
* `metaFor` found for `caller`. The reads carry the caller's scope, and the document's owner when it
|
|
315
|
+
* has one (`documentContext`): the copy is kept for every caller of the scope.
|
|
316
|
+
*/
|
|
317
|
+
async function open(id, meta, caller, key) {
|
|
318
|
+
const context = documentContext(meta, caller);
|
|
319
|
+
if (typeof store.readTextRange === "function" && meta.textBytes > wholeDocumentBytes) {
|
|
320
|
+
const rebuild = rebuildIndex.delete(key);
|
|
321
|
+
return openRangedDocument(rangeStore(context), meta, scan, { ignoreSavedIndex: rebuild, key });
|
|
423
322
|
}
|
|
424
|
-
const stored = await reading(() => store.get(id));
|
|
425
|
-
|
|
323
|
+
const stored = await reading(() => store.get(id, context));
|
|
324
|
+
// Another document is not this one: the metadata `get` gives must be of this ID, owner and
|
|
325
|
+
// scope, and of the version `meta` is (not one deleted and stored again since, by another
|
|
326
|
+
// server, nor one a store of your own gave from the wrong scope). And the text must be the one
|
|
327
|
+
// that metadata describes, of its length and its number of lines: a store that writes the text
|
|
328
|
+
// and the metadata apart can give one document's metadata with another's text (two servers that
|
|
329
|
+
// ingest one ID at once, a file read between two writes). A document read by range is checked
|
|
330
|
+
// too: its index against the metadata, and the end of its text against its index
|
|
331
|
+
// (openRangedDocument). Missing, as for a caller who may not use it.
|
|
332
|
+
const found = stored ? metaOf(stored.meta, id) : undefined;
|
|
333
|
+
if (!stored || !found || !mayUse(found, caller, rules) || documentVersion(found) !== documentVersion(meta))
|
|
334
|
+
return undefined;
|
|
335
|
+
if (typeof stored.text !== "string" || stored.text.length !== found.characters)
|
|
426
336
|
return undefined;
|
|
427
|
-
const named = wholeName(
|
|
428
|
-
|
|
337
|
+
const named = wholeName(found);
|
|
338
|
+
const document = new SearchableDocument(named === stored.meta ? stored : { ...stored, meta: named });
|
|
339
|
+
return document.lineCount === found.lines ? document : undefined;
|
|
429
340
|
}
|
|
430
341
|
/**
|
|
431
|
-
*
|
|
432
|
-
*
|
|
342
|
+
* The uploaded file of document `id`, which `meta`, checked for `caller`, says is kept: read from
|
|
343
|
+
* where the application keeps it (`meta.original`, through `originals`), or from the store. Another
|
|
344
|
+
* server may delete the document and store another under its ID while the bytes are read: so the
|
|
345
|
+
* store is asked again once they are. "missing" unless it still describes the same document, of
|
|
346
|
+
* the same owner and scope, and the bytes are the size of the file that was ingested, and have its
|
|
347
|
+
* SHA-256 when it is known (0.9.0): a store that gives back other bytes of the same size is caught
|
|
348
|
+
* too. "changed" for a file kept by the application that is no longer the one that was ingested:
|
|
349
|
+
* of another size or another SHA-256.
|
|
433
350
|
*/
|
|
434
|
-
async function
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
: renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, wholeRead);
|
|
443
|
-
}
|
|
444
|
-
catch (error) {
|
|
445
|
-
// The text is gone while its metadata is still there (removed outside the library): the
|
|
446
|
-
// same as missing. It was a plain Error, which failed the whole question.
|
|
447
|
-
if (error instanceof DocumentGoneError)
|
|
448
|
-
return undefined;
|
|
449
|
-
if (!document.broken) {
|
|
450
|
-
// Deleted between the look-up and the read: the same as missing.
|
|
451
|
-
if (!await currentMeta(id))
|
|
452
|
-
return undefined;
|
|
453
|
-
throw error;
|
|
454
|
-
}
|
|
455
|
-
}
|
|
351
|
+
async function originalOf(id, caller, meta) {
|
|
352
|
+
const kept = refOf(meta);
|
|
353
|
+
let read;
|
|
354
|
+
if (kept) {
|
|
355
|
+
if (!originals)
|
|
356
|
+
return "missing";
|
|
357
|
+
const context = Object.freeze({ ...caller.context, id, bytes: kept.bytes });
|
|
358
|
+
read = await reading(() => originals.read(kept.ref, context), caller.signal);
|
|
456
359
|
}
|
|
457
|
-
|
|
360
|
+
else {
|
|
361
|
+
if (meta.original !== undefined && meta.original !== null)
|
|
362
|
+
return "missing";
|
|
363
|
+
if (!store.getOriginal)
|
|
364
|
+
return "missing";
|
|
365
|
+
read = await loadOriginal(id, caller.context, caller.signal);
|
|
366
|
+
}
|
|
367
|
+
if (!read)
|
|
368
|
+
return "missing";
|
|
369
|
+
const bytes = read;
|
|
370
|
+
const after = await metaFor(id, caller);
|
|
371
|
+
if (!after || documentVersion(after) !== documentVersion(meta))
|
|
372
|
+
return "missing";
|
|
373
|
+
// The SHA-256 of a file of up to the upload limit is taken a slice at a time.
|
|
374
|
+
const same = async (sha256) => await sha256InSlices(bytes, new TimeSlicer()) === sha256;
|
|
375
|
+
if (kept)
|
|
376
|
+
return bytes.byteLength === kept.bytes && await same(kept.sha256) ? bytes : "changed";
|
|
377
|
+
if (bytes.byteLength !== meta.bytes)
|
|
378
|
+
return "missing";
|
|
379
|
+
return typeof meta.sha256 === "string" && !await same(meta.sha256) ? "missing" : bytes;
|
|
458
380
|
}
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
381
|
+
/**
|
|
382
|
+
* Whether `document`, which a call of `caller` has just read, is still the one the store describes
|
|
383
|
+
* for `caller`. A document loaded whole was checked as it was read (see `open`). The bytes of one
|
|
384
|
+
* read by range carry nothing to check them by, and another server, or this one, may delete the
|
|
385
|
+
* document and store another under its ID while they are read, or between the look-up and the
|
|
386
|
+
* reads: so the store is asked again once they are, as `originalOf` does. When it no longer
|
|
387
|
+
* describes the same document, of the same owner and scope, what was read may be another's: the
|
|
388
|
+
* copy kept of it, read from the store too, is forgotten, and the read is missing.
|
|
389
|
+
*/
|
|
390
|
+
async function stillOpened(document, caller) {
|
|
391
|
+
if (!(document instanceof RangedDocument))
|
|
392
|
+
return true;
|
|
393
|
+
const after = await metaFor(document.meta.id, caller);
|
|
394
|
+
if (after && documentVersion(after) === documentVersion(document.meta))
|
|
395
|
+
return true;
|
|
396
|
+
forgetKey(documentKey(caller, document.meta.id));
|
|
397
|
+
return false;
|
|
462
398
|
}
|
|
463
399
|
/**
|
|
464
|
-
*
|
|
465
|
-
*
|
|
466
|
-
*
|
|
400
|
+
* Removes a document from the store (`store.delete`), in the removals' turn (`removals`). The turn
|
|
401
|
+
* and the store call are waited for until `deadline` aborts (the delete's time limit, which they
|
|
402
|
+
* share), or the caller's signal does; the turn is then held until the store call ends, even past
|
|
403
|
+
* its time limit. The store call counts as stuck once it has itself run `storeTimeoutMs`.
|
|
467
404
|
*/
|
|
468
|
-
async function
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
let
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
405
|
+
async function removal(call, signal, deadline) {
|
|
406
|
+
checkStuck("delete", maxStuckStoreCalls);
|
|
407
|
+
if (signal?.aborted)
|
|
408
|
+
throw signal.reason;
|
|
409
|
+
if (deadline.aborted)
|
|
410
|
+
throw deadline.reason;
|
|
411
|
+
const waits = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
412
|
+
let release;
|
|
413
|
+
try {
|
|
414
|
+
release = await removals.acquire(waits);
|
|
415
|
+
}
|
|
416
|
+
catch (error) {
|
|
417
|
+
if (signal?.aborted)
|
|
418
|
+
throw signal.reason;
|
|
419
|
+
throw deadline.aborted ? deadline.reason : error;
|
|
420
|
+
}
|
|
421
|
+
let started = false;
|
|
484
422
|
try {
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
const read = async () => {
|
|
489
|
-
// What an extractor of your own reports once it has settled (from a timer, a worker) is
|
|
490
|
-
// not reported: the stages after it have begun.
|
|
491
|
-
let extracting = true;
|
|
492
|
-
let extracted;
|
|
423
|
+
return await timed("delete", () => {
|
|
424
|
+
started = true;
|
|
425
|
+
let running;
|
|
493
426
|
try {
|
|
494
|
-
|
|
495
|
-
// keeps its turn until the extractor is done too: it still holds memory.
|
|
496
|
-
const extraction = extractText(input.bytes, {
|
|
497
|
-
name,
|
|
498
|
-
mimeType,
|
|
499
|
-
format,
|
|
500
|
-
// A scan is worth storing only if its pages can be shown later: that needs the file itself.
|
|
501
|
-
...(format === "pdf" && keeps(format) && scannedPdfPages > 0 ? { scannedPages: scannedPdfPages } : {}),
|
|
502
|
-
signal,
|
|
503
|
-
maxTextBytes,
|
|
504
|
-
maxPages: maxPdfPages,
|
|
505
|
-
...(progress ? { onProgress: (report) => { if (extracting)
|
|
506
|
-
progress.extracted(report); } } : {}),
|
|
507
|
-
}, options.extractors);
|
|
508
|
-
work.abandoned = extraction;
|
|
509
|
-
extracted = await untilAborted(extraction, signal);
|
|
510
|
-
work.abandoned = undefined;
|
|
427
|
+
running = Promise.resolve(call());
|
|
511
428
|
}
|
|
512
|
-
|
|
513
|
-
|
|
429
|
+
catch (error) {
|
|
430
|
+
running = Promise.reject(error);
|
|
514
431
|
}
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
throw tooMuchText(name, maxTextBytes);
|
|
519
|
-
await slicer.pauseNow();
|
|
520
|
-
return { pages: extracted.pages, reading: readingOf(extracted), ...await prepareText(extracted.text, slicer, progress && ((done, total) => progress.report("prepare", done, total, "characters"))) };
|
|
521
|
-
};
|
|
522
|
-
({ pages, reading, text, wrapped, lines } = await read());
|
|
523
|
-
progress?.end();
|
|
524
|
-
if (!text.trim())
|
|
525
|
-
throw new Error(`${name} did not contain any text.`);
|
|
526
|
-
if (format === "text" && looksLikeLog(lines))
|
|
527
|
-
format = "log";
|
|
528
|
-
measured = await measureText(text, slicer);
|
|
529
|
-
if (measured.utf8 > maxTextBytes)
|
|
530
|
-
throw tooMuchText(name, maxTextBytes);
|
|
531
|
-
outline = await buildOutlineInSlices(lines, format, slicer);
|
|
532
|
-
logProfile = format === "log" ? await buildLogProfileInSlices(lines, slicer) : undefined;
|
|
533
|
-
quality = await measureQuality(lines, format, slicer);
|
|
534
|
-
// The line index, so that the text can be read by range: a few bytes a line, built from the
|
|
535
|
-
// UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
|
|
536
|
-
// then loads whole, so that switching to reading by range finds it ready.
|
|
537
|
-
index = typeof store.putIndex === "function"
|
|
538
|
-
? await buildTextIndexInSlices(text, slicer, progress && ((done, total) => progress.report("index", done, total, "characters")))
|
|
539
|
-
: undefined;
|
|
540
|
-
progress?.end();
|
|
541
|
-
signal.throwIfAborted();
|
|
432
|
+
running.then(release, release);
|
|
433
|
+
return running;
|
|
434
|
+
}, waits);
|
|
542
435
|
}
|
|
543
436
|
finally {
|
|
544
|
-
|
|
437
|
+
if (!started)
|
|
438
|
+
release();
|
|
545
439
|
}
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
//
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
name,
|
|
557
|
-
mimeType,
|
|
558
|
-
format,
|
|
559
|
-
bytes: input.bytes.byteLength,
|
|
560
|
-
textBytes: measured.utf8,
|
|
561
|
-
jsonBytes: measured.json,
|
|
562
|
-
characters: text.length,
|
|
563
|
-
lines: lines.length,
|
|
564
|
-
estimatedTokens: measured.tokens,
|
|
565
|
-
wrappedLines: wrapped,
|
|
566
|
-
...(pages ? { pages } : {}),
|
|
567
|
-
...reading,
|
|
568
|
-
...(keepOriginal ? { originalKept: true } : {}),
|
|
569
|
-
outline,
|
|
570
|
-
...(logProfile ? { logProfile } : {}),
|
|
571
|
-
...quality,
|
|
572
|
-
createdAt: created.toISOString(),
|
|
573
|
-
// Never, for a time to live without end (or one that runs past what a date can hold).
|
|
574
|
-
expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
|
|
575
|
-
});
|
|
576
|
-
const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && index.textBytes === meta.textBytes
|
|
577
|
-
? serializeTextIndex(index)
|
|
578
|
-
: undefined;
|
|
579
|
-
// Each write is reported once done. What the listener of the events throws is not the store's failure.
|
|
580
|
-
const writes = (keepOriginal ? 1 : 0) + (savedIndex ? 1 : 0) + 1;
|
|
581
|
-
let written = 0;
|
|
582
|
-
let listenerFailed;
|
|
583
|
-
const wrote = (last) => {
|
|
584
|
-
if (!progress)
|
|
585
|
-
return;
|
|
586
|
-
try {
|
|
587
|
-
progress.report("store", ++written, writes, "parts");
|
|
588
|
-
if (last)
|
|
589
|
-
progress.end();
|
|
590
|
-
}
|
|
591
|
-
catch (error) {
|
|
592
|
-
listenerFailed = { error };
|
|
593
|
-
throw error;
|
|
594
|
-
}
|
|
595
|
-
};
|
|
596
|
-
// The files first, the document last: a document is there once its metadata is.
|
|
597
|
-
const storing = (async () => {
|
|
598
|
-
if (keepOriginal) {
|
|
599
|
-
await store.putOriginal(meta.id, input.bytes);
|
|
600
|
-
wrote(false);
|
|
601
|
-
}
|
|
602
|
-
if (savedIndex) {
|
|
603
|
-
await store.putIndex(meta.id, savedIndex);
|
|
604
|
-
wrote(false);
|
|
605
|
-
}
|
|
606
|
-
await store.put({ meta, text });
|
|
607
|
-
wrote(true);
|
|
608
|
-
})();
|
|
609
|
-
try {
|
|
610
|
-
// A store that does not answer fails the ingest after `slotCapMs`: it held the ingest's turn,
|
|
611
|
-
// and the upload handler's room for the file, for as long as it did not answer.
|
|
612
|
-
await settleWithin(storing, slotCapMs, () => new Error(`The store did not finish writing ${name} within ${formatDuration(slotCapMs)}.`));
|
|
613
|
-
}
|
|
614
|
-
catch (error) {
|
|
615
|
-
// Do not leave a file of up to the upload limit, or a part of one, behind for a document
|
|
616
|
-
// that does not exist: once the writes have ended, when they have not yet. The removal is not
|
|
617
|
-
// waited for longer than the writes were.
|
|
618
|
-
const removal = storing.then(() => store.delete(meta.id), () => store.delete(meta.id)).catch(() => undefined);
|
|
619
|
-
await settleWithin(removal, slotCapMs, () => new Error("")).catch(() => undefined);
|
|
620
|
-
if (listenerFailed?.error !== error) {
|
|
621
|
-
noteStoreWriteFailure(error);
|
|
622
|
-
storeFailed();
|
|
623
|
-
}
|
|
624
|
-
throw error;
|
|
440
|
+
}
|
|
441
|
+
/** What planning a request (`prepareDocuments`, src/prepare.ts) needs of this library. */
|
|
442
|
+
const planning = { callerOf: (access) => callerOf(access, rules), metaFor, load, stillOpened, budgetFor, viewableMeta, rules };
|
|
443
|
+
/** `files.tools`: the tools for `documents`. */
|
|
444
|
+
function tools(documents, toolOptions = {}) {
|
|
445
|
+
const { viewPages, budget: overrides, access, ...rest } = toolOptions;
|
|
446
|
+
// Without `access`, the owner and scope of each document are those it was handed in with: a
|
|
447
|
+
// library that requires them takes them only from the caller.
|
|
448
|
+
if (access === undefined && (rules.requireOwner || rules.requireScope)) {
|
|
449
|
+
throw new TypeError(rules.requireOwner ? OWNER_REQUIRED : SCOPE_REQUIRED);
|
|
625
450
|
}
|
|
626
|
-
|
|
451
|
+
// The tool set's signal ends its waits for the store too, unless `access` has a signal of its own.
|
|
452
|
+
// It is taken as it is, as before 0.10.0 (an object made like an AbortSignal too): only
|
|
453
|
+
// `access.signal`, new in 0.10.0, must be an AbortSignal (`callerOf`).
|
|
454
|
+
const signal = access?.signal ?? toolOptions.signal;
|
|
455
|
+
const asker = access !== undefined ? withSignal(callerOf(access, rules), signal) : undefined;
|
|
456
|
+
const budget = budgetFor(overrides);
|
|
457
|
+
// Which PDFs can be looked at, by the metadata handed in: each look reads the metadata the
|
|
458
|
+
// store holds, and the file it names, not the one handed in.
|
|
459
|
+
const viewable = (viewPages === true ? documents : viewPages || []).filter(viewableMeta);
|
|
460
|
+
// Without `access`, as before 0.9.0: the owner and scope each document was handed in with.
|
|
461
|
+
// The store is asked with them, and the owner and scope it holds are checked against them on
|
|
462
|
+
// every call, so metadata built from an ID alone cannot read another owner's document: such a
|
|
463
|
+
// document is answered as no longer available, as `getMeta` reports it missing. A handed scope
|
|
464
|
+
// that is not valid reads nothing.
|
|
465
|
+
const handed = new Map(asker ? [] : [...documents, ...viewable].map((meta) => [meta.id, handedCaller(meta, signal)]));
|
|
466
|
+
const noCaller = signal ? { ...NO_CALLER, signal } : NO_CALLER;
|
|
467
|
+
const callerFor = (id) => asker ?? (handed.has(id) ? handed.get(id) : noCaller);
|
|
468
|
+
// The metadata the store holds now, not that of a copy kept in memory.
|
|
469
|
+
const checkedLoad = async (id) => {
|
|
470
|
+
const caller = callerFor(id);
|
|
471
|
+
const meta = caller && await metaFor(id, caller);
|
|
472
|
+
return meta ? load(id, caller, meta) : undefined;
|
|
473
|
+
};
|
|
474
|
+
const checkedOriginal = (store.getOriginal || originals) && (async (id) => {
|
|
475
|
+
const caller = callerFor(id);
|
|
476
|
+
const meta = caller && await metaFor(id, caller);
|
|
477
|
+
if (!meta || !readable(meta))
|
|
478
|
+
return undefined;
|
|
479
|
+
const original = await originalOf(id, caller, meta);
|
|
480
|
+
// A file the application keeps that has changed since it was ingested: its pages are not
|
|
481
|
+
// those of the text the model has, and the model is told so.
|
|
482
|
+
if (original === "changed")
|
|
483
|
+
throw new Error(changedOriginal(meta.name));
|
|
484
|
+
return original === "missing" ? undefined : original;
|
|
485
|
+
});
|
|
486
|
+
return createDocumentTools({
|
|
487
|
+
load: checkedLoad,
|
|
488
|
+
// Once a call has read a document by range: the store is asked again (`stillOpened`).
|
|
489
|
+
checkRead: async (document) => {
|
|
490
|
+
const caller = callerFor(document.meta.id);
|
|
491
|
+
return caller !== undefined && await stillOpened(document, caller);
|
|
492
|
+
},
|
|
493
|
+
documentIds: documents.map((meta) => meta.id),
|
|
494
|
+
names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, wellFormed(meta.name)])),
|
|
495
|
+
budget,
|
|
496
|
+
...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal, pageLooks } : {}),
|
|
497
|
+
// `analyze_whole_document` is declared only when it can read at least one of the documents.
|
|
498
|
+
wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
|
|
499
|
+
// `aggregate_table` only when one may hold a table.
|
|
500
|
+
tables: documents.some((meta) => TABLE_FORMATS.has(meta.format)),
|
|
501
|
+
...rest,
|
|
502
|
+
});
|
|
627
503
|
}
|
|
628
504
|
return {
|
|
629
505
|
budget,
|
|
630
506
|
budgetFor,
|
|
631
507
|
maxUploadBytes,
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
508
|
+
access: rules,
|
|
509
|
+
ingest(input) {
|
|
510
|
+
return ingestDocument(ingestContext, input);
|
|
511
|
+
},
|
|
512
|
+
async getMeta(id, access) {
|
|
513
|
+
return metaFor(id, callerOf(access, rules));
|
|
514
|
+
},
|
|
515
|
+
async getOriginal(id, access) {
|
|
516
|
+
const caller = callerOf(access, rules);
|
|
517
|
+
const meta = await metaFor(id, caller);
|
|
518
|
+
if (!meta?.originalKept || !readable(meta))
|
|
519
|
+
return undefined;
|
|
520
|
+
const original = await originalOf(id, caller, meta);
|
|
521
|
+
return original instanceof Uint8Array ? original : undefined;
|
|
522
|
+
},
|
|
523
|
+
async delete(id, access) {
|
|
524
|
+
const caller = callerOf(access, rules);
|
|
525
|
+
// One time limit for the whole delete: the look-up (which keeps its own, and its error of a
|
|
526
|
+
// read), then the wait for the removals' turn and the store's delete. Before, the turn and the
|
|
527
|
+
// delete had one each: with a slow delete before it, a delete answered after twice the limit.
|
|
528
|
+
const deadline = new AbortController();
|
|
529
|
+
const timer = isTimeLimit(storeTimeoutMs) ? setTimeout(() => deadline.abort(storeTimeout("delete", storeTimeoutMs)), storeTimeoutMs) : undefined;
|
|
647
530
|
try {
|
|
648
|
-
if (
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
const mimeType = input.mimeType?.trim() || "application/octet-stream";
|
|
653
|
-
// A file whose name and type say nothing is known by its bytes: a PDF, an Office file, a page.
|
|
654
|
-
const format = detectFormat(name, mimeType, input.bytes instanceof Uint8Array ? input.bytes : undefined);
|
|
655
|
-
// Progress is worked out only for someone who listens.
|
|
656
|
-
const progress = events.active ? new IngestProgress(events) : undefined;
|
|
657
|
-
let meta;
|
|
658
|
-
try {
|
|
659
|
-
// Refused at once, without waiting for a turn.
|
|
660
|
-
if (input.bytes.byteLength === 0)
|
|
661
|
-
throw new Error(`${name} is empty.`);
|
|
662
|
-
if (input.bytes.byteLength > maxUploadBytes) {
|
|
663
|
-
throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
|
|
664
|
-
}
|
|
665
|
-
// Its turn (`maxConcurrentIngests`): a caller that gives up while it waits gets its own
|
|
666
|
-
// reason, as it would once the work had begun. (An ingest started inside another of this
|
|
667
|
-
// library, by an extractor of your own, waits for a turn like any other. Telling it apart
|
|
668
|
-
// with AsyncLocalStorage made pdf.js about five times slower on Node 22, for every PDF.)
|
|
669
|
-
const slot = new IngestSlot(await ingests.acquire(input.signal), slotCapMs);
|
|
670
|
-
const work = {};
|
|
671
|
-
try {
|
|
672
|
-
meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true), work);
|
|
673
|
-
}
|
|
674
|
-
finally {
|
|
675
|
-
slot.end(work.abandoned);
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
catch (error) {
|
|
679
|
-
// A store that failed, and a caller that gave up (its own reason), are passed on as they
|
|
680
|
-
// are; a file that could not be read is told with a code.
|
|
681
|
-
if (storeFailed || (input.signal?.aborted && error === input.signal.reason) || isStoreWriteFailure(error) || (listenerFailure && error === listenerFailure.error))
|
|
682
|
-
throw error;
|
|
683
|
-
throw toIngestError(error);
|
|
684
|
-
}
|
|
685
|
-
try {
|
|
686
|
-
events.emit({ type: "ingest.finish", document: toDocumentSummary(meta) });
|
|
687
|
-
}
|
|
688
|
-
catch (error) {
|
|
689
|
-
// The caller never gets the id: the document goes, as on a throw of the listener a moment earlier.
|
|
690
|
-
await store.delete(meta.id).catch(() => undefined);
|
|
691
|
-
forget(meta.id);
|
|
692
|
-
throw error;
|
|
693
|
-
}
|
|
694
|
-
return meta;
|
|
531
|
+
if (!await metaFor(id, caller))
|
|
532
|
+
return false;
|
|
533
|
+
forget(id);
|
|
534
|
+
return await removal(() => store.delete(id, caller.context), caller.signal, deadline.signal);
|
|
695
535
|
}
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
// may see, says only that the document could not be stored.
|
|
699
|
-
events.emit({ type: "ingest.error", error: storeFailed ? { message: STORE_WRITE_FAILED } : eventErrorOf(error) });
|
|
700
|
-
throw error;
|
|
536
|
+
finally {
|
|
537
|
+
clearTimeout(timer);
|
|
701
538
|
}
|
|
702
539
|
},
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
const
|
|
706
|
-
|
|
540
|
+
async sweep(sweepOptions) {
|
|
541
|
+
// Upkeep of the store, not a user's access: allowed without a scope under `requireScope`.
|
|
542
|
+
const scope = checkScope(sweepOptions?.scope ?? undefined);
|
|
543
|
+
if (typeof store.sweep !== "function")
|
|
544
|
+
return 0;
|
|
545
|
+
// Within its own time limit, and never counted as stuck: a sweep of a large volume may take
|
|
546
|
+
// long. It is refused, as other calls are, while too many calls are stuck.
|
|
547
|
+
return storeCall("sweep", () => store.sweep(now(), storeContext(scope, undefined)), { timeoutMs: sweepTimeoutMs, maxStuck: maxStuckStoreCalls, counts: false });
|
|
707
548
|
},
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
forget(id);
|
|
712
|
-
return options.store.delete(id);
|
|
549
|
+
// The options go on whole: planning (src/prepare.ts) reads the ones it knows.
|
|
550
|
+
prepare(ids, base, prepareOptions) {
|
|
551
|
+
return prepareDocuments(planning, ids, base, prepareOptions);
|
|
713
552
|
},
|
|
714
|
-
|
|
715
|
-
|
|
553
|
+
tools,
|
|
554
|
+
stats() {
|
|
555
|
+
// Counters only: no store call, no turn waited for.
|
|
556
|
+
return {
|
|
557
|
+
ingests: ingests.load,
|
|
558
|
+
scans: scan.limiter.load,
|
|
559
|
+
pageLooks: pageLooks.limiter.load,
|
|
560
|
+
cache: { bytes: cache.bytes, entries: cache.size, maxBytes: cacheBytes },
|
|
561
|
+
stuckStoreCalls: stuckCalls(),
|
|
562
|
+
maxStuckStoreCalls,
|
|
563
|
+
};
|
|
716
564
|
},
|
|
717
|
-
async
|
|
718
|
-
const
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
565
|
+
async toolsFor(ids, toolOptions) {
|
|
566
|
+
const access = toolOptions?.access;
|
|
567
|
+
if (typeof access !== "object" || access === null)
|
|
568
|
+
throw new TypeError("toolsFor needs options.access: the owner and scope of the caller, such as { owner: userId }.");
|
|
569
|
+
if (!Array.isArray(ids))
|
|
570
|
+
throw new TypeError("toolsFor needs an array of document IDs.");
|
|
571
|
+
const caller = withSignal(callerOf(toolOptions.access, rules), toolOptions.access.signal ?? toolOptions.signal);
|
|
572
|
+
const found = [];
|
|
722
573
|
const missing = [];
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
const meta = await metaFor(id, access);
|
|
574
|
+
// One look-up at a time: a store that does not answer holds one thread of the pool, not one for each ID.
|
|
575
|
+
for (const id of new Set(ids)) {
|
|
576
|
+
const meta = await metaFor(id, caller);
|
|
727
577
|
if (meta)
|
|
728
|
-
|
|
578
|
+
found.push(meta);
|
|
729
579
|
else
|
|
730
580
|
missing.push(id);
|
|
731
581
|
}
|
|
732
|
-
|
|
733
|
-
// first lines for the others. One that is gone by then is missing, and the plan is made again.
|
|
734
|
-
for (;;) {
|
|
735
|
-
const plan = planDocuments(documents, budget, base);
|
|
736
|
-
const inline = new Set(plan.inline.map((meta) => meta.id));
|
|
737
|
-
// Pages can be shown for a PDF whose file is kept, whether its text is in the prompt or searched.
|
|
738
|
-
const viewable = access?.viewPages && store.getOriginal
|
|
739
|
-
? documents.filter((meta) => meta.format === "pdf" && meta.originalKept)
|
|
740
|
-
: [];
|
|
741
|
-
const shown = new Set(viewable.map((meta) => meta.id));
|
|
742
|
-
const blocks = new Map();
|
|
743
|
-
const gone = [];
|
|
744
|
-
for (const meta of documents) {
|
|
745
|
-
const wholeRead = !analysis ? "not_offered" : canBeReadWhole(meta, budget) ? "offered" : "too_large";
|
|
746
|
-
const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id), wholeRead);
|
|
747
|
-
if (text === undefined)
|
|
748
|
-
gone.push(meta.id);
|
|
749
|
-
else
|
|
750
|
-
blocks.set(meta.id, text);
|
|
751
|
-
}
|
|
752
|
-
if (gone.length === 0) {
|
|
753
|
-
// A whole-document read is named only when the tools have it, and one of the files is
|
|
754
|
-
// small enough for it.
|
|
755
|
-
const wholeReads = analysis && plan.searchable.some((meta) => canBeReadWhole(meta, budget));
|
|
756
|
-
return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable, wholeReads), missing, viewable };
|
|
757
|
-
}
|
|
758
|
-
missing.push(...gone);
|
|
759
|
-
documents = documents.filter((meta) => !gone.includes(meta.id));
|
|
760
|
-
}
|
|
761
|
-
},
|
|
762
|
-
tools(documents, toolOptions = {}) {
|
|
763
|
-
const { viewPages, budget: overrides, ...rest } = toolOptions;
|
|
764
|
-
const budget = budgetFor(overrides);
|
|
765
|
-
const viewable = (loadOriginal ? (viewPages === true ? documents : viewPages || []) : [])
|
|
766
|
-
.filter((meta) => meta.format === "pdf" && meta.originalKept);
|
|
767
|
-
// The owner each document was handed in with. The store's owner is checked against it on
|
|
768
|
-
// every call, so metadata built from an ID alone cannot read another owner's document: such
|
|
769
|
-
// a document is answered as no longer available, as `getMeta` reports it missing.
|
|
770
|
-
const handedOwner = new Map([...documents, ...viewable].map((meta) => [meta.id, meta.owner]));
|
|
771
|
-
const mayUse = (meta) => meta.owner === undefined || (handedOwner.has(meta.id) && meta.owner === handedOwner.get(meta.id));
|
|
772
|
-
// The metadata the store holds now, not that of a copy kept in memory.
|
|
773
|
-
const checkedLoad = async (id) => {
|
|
774
|
-
const meta = await currentMeta(id);
|
|
775
|
-
return meta && mayUse(meta) ? load(id, meta) : undefined;
|
|
776
|
-
};
|
|
777
|
-
const checkedOriginal = loadOriginal && (async (id) => {
|
|
778
|
-
const meta = await currentMeta(id);
|
|
779
|
-
return meta && mayUse(meta) ? loadOriginal(id) : undefined;
|
|
780
|
-
});
|
|
781
|
-
return createDocumentTools({
|
|
782
|
-
load: checkedLoad,
|
|
783
|
-
documentIds: documents.map((meta) => meta.id),
|
|
784
|
-
names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, wellFormed(meta.name)])),
|
|
785
|
-
budget,
|
|
786
|
-
...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal } : {}),
|
|
787
|
-
// `analyze_whole_document` is declared only when it can read at least one of the documents.
|
|
788
|
-
wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
|
|
789
|
-
// `aggregate_table` only when one may hold a table.
|
|
790
|
-
tables: documents.some((meta) => TABLE_FORMATS.has(meta.format)),
|
|
791
|
-
...rest,
|
|
792
|
-
});
|
|
582
|
+
return { tools: tools(found, toolOptions), missing };
|
|
793
583
|
},
|
|
794
584
|
};
|
|
585
|
+
/**
|
|
586
|
+
* The caller a document was handed to `tools` for (without `access`): its owner and scope, and the
|
|
587
|
+
* tool set's signal. Undefined for a scope that is not valid: only that reads as missing.
|
|
588
|
+
*/
|
|
589
|
+
function handedCaller(meta, signal) {
|
|
590
|
+
let caller;
|
|
591
|
+
try {
|
|
592
|
+
caller = callerOf({ owner: meta.owner, scope: meta.scope }, rules);
|
|
593
|
+
}
|
|
594
|
+
catch {
|
|
595
|
+
return undefined;
|
|
596
|
+
}
|
|
597
|
+
return withSignal(caller, signal);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
/** `caller`, whose waits for the store end when `signal` aborts. */
|
|
601
|
+
function withSignal(caller, signal) {
|
|
602
|
+
return signal === undefined ? caller : { ...caller, signal };
|
|
795
603
|
}
|
|
796
604
|
//# sourceMappingURL=library.js.map
|