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
|
@@ -0,0 +1,660 @@
|
|
|
1
|
+
// documentStoreChecks: the checks a DocumentStore must pass, for the tests of a store of your own.
|
|
2
|
+
// New in 0.9.0. They depend on no test framework: each check is a name, a time limit and a function
|
|
3
|
+
// that throws when the store fails it. Give them to `it` (Vitest), `test` (Jest) or `test`
|
|
4
|
+
// (node:test), as the documentation of documentStoreChecks shows.
|
|
5
|
+
import { DocumentScopeError } from "../errors.js";
|
|
6
|
+
import { createLargeFiles, type LargeFiles } from "../library.js";
|
|
7
|
+
import { MemoryDocumentStore } from "../stores.js";
|
|
8
|
+
import type { DocumentContext, DocumentMeta, DocumentScope, DocumentStore } from "../types.js";
|
|
9
|
+
import { serviceLog, utf8 } from "./fake-model.js";
|
|
10
|
+
|
|
11
|
+
/** What each check gives `create`: its clock, a name for the storage, and the scopes it uses. */
|
|
12
|
+
export type StoreCheckEnvironment = {
|
|
13
|
+
/**
|
|
14
|
+
* The clock of the check: the time it started, which a check may move forward. Give it to the
|
|
15
|
+
* store as its clock, when it has one: the `now` option of the built-in stores.
|
|
16
|
+
*/
|
|
17
|
+
readonly now: () => Date;
|
|
18
|
+
/**
|
|
19
|
+
* A name for the storage of the store: lowercase letters, digits and "-", new for each check. Use
|
|
20
|
+
* it as a folder, a key prefix or a collection name. When `create` is called twice with the same
|
|
21
|
+
* name, give a second store over the same storage, as a second server would open it.
|
|
22
|
+
*/
|
|
23
|
+
readonly storage: string;
|
|
24
|
+
/**
|
|
25
|
+
* The scopes the checks use (`scopeDepth` segments each, lowercase): for a store whose scopes
|
|
26
|
+
* need a place made before a write, such as the folders of a `FileDocumentStore` with `scopes`.
|
|
27
|
+
*/
|
|
28
|
+
readonly scopes: readonly DocumentScope[];
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** A part of the store a check needs, which `skip` leaves out. */
|
|
32
|
+
export type StoreCheckPart = "originals" | "ranges" | "index" | "sweep" | "shared";
|
|
33
|
+
|
|
34
|
+
export type DocumentStoreChecksOptions = {
|
|
35
|
+
/** A new store over new, empty storage, named by `environment.storage`. */
|
|
36
|
+
create(environment: StoreCheckEnvironment): DocumentStore | Promise<DocumentStore>;
|
|
37
|
+
/** Called after each check for each store it made, to close it and remove its storage. */
|
|
38
|
+
dispose?(store: DocumentStore, environment: StoreCheckEnvironment): void | Promise<void>;
|
|
39
|
+
/**
|
|
40
|
+
* Whether the store keeps the documents of each scope apart (`context.scope`), as
|
|
41
|
+
* `MemoryDocumentStore` does: one ID in two scopes is then two documents. Defaults to false: a
|
|
42
|
+
* store that ignores the context, which the library keeps apart by `meta.scope`.
|
|
43
|
+
*/
|
|
44
|
+
isolatesScopes?: boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Whether the store refuses a call without a scope, with a `DocumentScopeError` of code
|
|
47
|
+
* "scope_required", as a `FileDocumentStore` with `scopes` does. Defaults to false.
|
|
48
|
+
*/
|
|
49
|
+
requiresScope?: boolean;
|
|
50
|
+
/** How many segments the scopes of the checks have, from 1 to 8. Defaults to 2: `[userId, chatId]`. */
|
|
51
|
+
scopeDepth?: number;
|
|
52
|
+
/**
|
|
53
|
+
* The parts the store does not have: "originals" (`putOriginal`, `getOriginal`), "ranges"
|
|
54
|
+
* (`readTextRange`), "index" (`putIndex`, `getIndex`), "sweep", or "shared" for a store whose
|
|
55
|
+
* storage two stores cannot share (`MemoryDocumentStore`). A check of a part the store lacks, and
|
|
56
|
+
* that is not skipped, fails and says so.
|
|
57
|
+
*/
|
|
58
|
+
skip?: readonly StoreCheckPart[];
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** One check: give it to your test framework's `it` or `test`. */
|
|
62
|
+
export type DocumentStoreCheck = {
|
|
63
|
+
/** What the store must do, as a sentence. */
|
|
64
|
+
readonly name: string;
|
|
65
|
+
/** The time the check may take, in milliseconds. */
|
|
66
|
+
readonly timeoutMs: number;
|
|
67
|
+
/** Runs the check. Rejects with an `Error` that says what the store did wrong. Takes no argument. */
|
|
68
|
+
readonly run: () => Promise<void>;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const MINUTE = 60_000;
|
|
72
|
+
const HOUR = 60 * MINUTE;
|
|
73
|
+
const DAY = 24 * HOUR;
|
|
74
|
+
|
|
75
|
+
/** A text that is hard to keep exactly: CRLF, Hebrew, an emoji, a tab, a byte-order mark inside, no break at the end. */
|
|
76
|
+
const TEXT = "first line\r\nשלום עולם, a line in Hebrew\n😀 four bytes, é two\n\tindented\na mark inside\nlast line without a break";
|
|
77
|
+
|
|
78
|
+
/** How the message of every failure of a check starts. */
|
|
79
|
+
const FAILED = "The store failed the check: ";
|
|
80
|
+
|
|
81
|
+
/** Throws the failure of a check. */
|
|
82
|
+
function fail(message: string, cause?: unknown): never {
|
|
83
|
+
throw new Error(`${FAILED}${message}`, cause === undefined ? undefined : { cause });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Whether `error` is the failure of a check, made by `fail`. */
|
|
87
|
+
const failure = (error: unknown): error is Error => error instanceof Error && error.message.startsWith(FAILED);
|
|
88
|
+
|
|
89
|
+
/** What a thrown value says, for a failure: the error's name and message. */
|
|
90
|
+
const thrown = (error: unknown) => (error instanceof Error ? `${error.name}: ${error.message}` : show(error));
|
|
91
|
+
|
|
92
|
+
/** "`what` threw `error`.", with one full stop. */
|
|
93
|
+
function threw(what: string, error: unknown): string {
|
|
94
|
+
const text = `${what} threw ${thrown(error)}`;
|
|
95
|
+
return /[.!?]$/.test(text) ? text : `${text}.`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function show(value: unknown): string {
|
|
99
|
+
if (value instanceof Uint8Array) return `${value.length} bytes`;
|
|
100
|
+
if (value === undefined) return "undefined";
|
|
101
|
+
const text = JSON.stringify(value) ?? String(value);
|
|
102
|
+
return text.length > 200 ? `${text.slice(0, 200)}…` : text;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Whether two values are the same, deeply. A field that is undefined counts as absent; bytes are compared byte for byte. */
|
|
106
|
+
function equal(left: unknown, right: unknown): boolean {
|
|
107
|
+
if (Object.is(left, right)) return true;
|
|
108
|
+
if (left instanceof Uint8Array || right instanceof Uint8Array) {
|
|
109
|
+
if (!(left instanceof Uint8Array && right instanceof Uint8Array) || left.length !== right.length) return false;
|
|
110
|
+
return left.every((byte, index) => byte === right[index]);
|
|
111
|
+
}
|
|
112
|
+
if (typeof left !== "object" || typeof right !== "object" || left === null || right === null) return false;
|
|
113
|
+
if (Array.isArray(left) !== Array.isArray(right)) return false;
|
|
114
|
+
const keys = (value: object) => Object.keys(value).filter((key) => (value as Record<string, unknown>)[key] !== undefined).sort();
|
|
115
|
+
const leftKeys = keys(left);
|
|
116
|
+
const rightKeys = keys(right);
|
|
117
|
+
return leftKeys.length === rightKeys.length
|
|
118
|
+
&& leftKeys.every((key, index) => key === rightKeys[index] && equal((left as Record<string, unknown>)[key], (right as Record<string, unknown>)[key]));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function same(actual: unknown, expected: unknown, what: string): void {
|
|
122
|
+
if (!equal(actual, expected)) fail(`${what}: expected ${show(expected)}, got ${show(actual)}.`);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Bytes as a plain Uint8Array, so that a Buffer or a view compares as its bytes. */
|
|
126
|
+
function bytesOf(value: unknown, what: string): Uint8Array {
|
|
127
|
+
if (!(value instanceof Uint8Array)) fail(`${what}: expected bytes (a Uint8Array), got ${show(value)}.`);
|
|
128
|
+
return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The error a call threw, or a failure when it threw none. */
|
|
132
|
+
async function thrownBy(call: () => Promise<unknown>, what: string): Promise<unknown> {
|
|
133
|
+
try {
|
|
134
|
+
await call();
|
|
135
|
+
} catch (error) {
|
|
136
|
+
return error;
|
|
137
|
+
}
|
|
138
|
+
return fail(`${what}: expected it to throw, and it did not.`);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Runs `call`, and fails the check, saying what was called, when it throws. A failure of a check is passed on as it is. */
|
|
142
|
+
async function must<T>(call: () => Promise<T>, what: string): Promise<T> {
|
|
143
|
+
try {
|
|
144
|
+
return await call();
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (failure(error)) throw error;
|
|
147
|
+
return fail(threw(what, error), error);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** A call to a store as a failure names it: `getMeta("check-copy", { scope: […] })`. */
|
|
152
|
+
function callOf(method: string, args: unknown[]): string {
|
|
153
|
+
const shown = args.map((arg) => {
|
|
154
|
+
if (typeof arg === "string" || typeof arg === "number") return JSON.stringify(arg);
|
|
155
|
+
if (arg instanceof Date) return arg.toISOString();
|
|
156
|
+
if (arg instanceof Uint8Array) return `${arg.length} bytes`;
|
|
157
|
+
const id = (arg as { meta?: { id?: unknown } } | null)?.meta?.id;
|
|
158
|
+
if (typeof id === "string") return `{ meta: { id: ${JSON.stringify(id)}, … }, text }`;
|
|
159
|
+
return show(arg);
|
|
160
|
+
});
|
|
161
|
+
return `${method}(${shown.join(", ")})`;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* The store as the checks call it: a method that throws (or rejects) fails the check, and the
|
|
166
|
+
* failure names the call. Its methods are the store's own, so a check can still test whether one
|
|
167
|
+
* exists. The library, and checks of what a store throws, are given the store itself.
|
|
168
|
+
*/
|
|
169
|
+
function named(store: DocumentStore): DocumentStore {
|
|
170
|
+
// Over an empty target: a store whose methods are frozen own properties (Object.freeze({ put, … }))
|
|
171
|
+
// would make the proxy's invariants refuse a wrapped method.
|
|
172
|
+
const target = store;
|
|
173
|
+
return new Proxy(Object.create(null) as DocumentStore, {
|
|
174
|
+
has: (_, key) => Reflect.has(target, key),
|
|
175
|
+
get(_, key) {
|
|
176
|
+
const value = Reflect.get(target, key, target) as unknown;
|
|
177
|
+
if (typeof value !== "function") return value;
|
|
178
|
+
return (...args: unknown[]) => {
|
|
179
|
+
const failed = (error: unknown): never => {
|
|
180
|
+
if (failure(error)) throw error;
|
|
181
|
+
return fail(threw(callOf(String(key), args), error), error);
|
|
182
|
+
};
|
|
183
|
+
let result: unknown;
|
|
184
|
+
try {
|
|
185
|
+
result = (value as (...args: unknown[]) => unknown).apply(target, args);
|
|
186
|
+
} catch (error) {
|
|
187
|
+
failed(error);
|
|
188
|
+
}
|
|
189
|
+
return Promise.resolve(result).catch(failed);
|
|
190
|
+
};
|
|
191
|
+
},
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Metadata as the library writes it, for a document written to the store directly. */
|
|
196
|
+
function metaFor(id: string, text: string, createdAt: number, expiresAt: number, more: Partial<DocumentMeta> = {}): DocumentMeta {
|
|
197
|
+
const bytes = utf8(text).length;
|
|
198
|
+
return {
|
|
199
|
+
id, metaVersion: 1, name: "notes.txt", mimeType: "text/plain", format: "text", bytes, textBytes: bytes, jsonBytes: bytes + 16,
|
|
200
|
+
characters: text.length, lines: text.split("\n").length, estimatedTokens: Math.ceil(bytes / 4), wrappedLines: 0,
|
|
201
|
+
outline: [{ level: 1, title: "first line", line: 1 }], createdAt: new Date(createdAt).toISOString(), expiresAt: new Date(expiresAt).toISOString(),
|
|
202
|
+
...more,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** What a check gets: its store, a way to open another one over the same storage, and its clock. */
|
|
207
|
+
type Harness = {
|
|
208
|
+
/** The store, whose calls fail the check, naming the call, when they throw (`named`). */
|
|
209
|
+
store: DocumentStore;
|
|
210
|
+
/** The store itself, for the library and for checks of what it throws. */
|
|
211
|
+
raw: DocumentStore;
|
|
212
|
+
environment: StoreCheckEnvironment;
|
|
213
|
+
/** When the check started: the clock's time until it is moved. */
|
|
214
|
+
start: number;
|
|
215
|
+
/** Moves the clock of the check (and of the stores that read it). */
|
|
216
|
+
setClock(time: number): void;
|
|
217
|
+
/** Another store over the same storage, as a second server, whose calls fail the check as `store`'s do. */
|
|
218
|
+
open(): Promise<DocumentStore>;
|
|
219
|
+
/** The context of a call in scope A or B, with an owner. */
|
|
220
|
+
context(which?: "a" | "b"): DocumentContext;
|
|
221
|
+
scopes: { a: DocumentScope; b: DocumentScope };
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
let checksMade = 0;
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* The checks a `DocumentStore` must pass: what the library relies on, method by method, and the
|
|
228
|
+
* library itself over the store, compared with `MemoryDocumentStore`. Run them in the tests of a
|
|
229
|
+
* store of your own:
|
|
230
|
+
*
|
|
231
|
+
* ```ts
|
|
232
|
+
* for (const check of documentStoreChecks({ create })) it(check.name, check.run, check.timeoutMs); // Vitest, Jest
|
|
233
|
+
* for (const check of documentStoreChecks({ create })) test(check.name, { timeout: check.timeoutMs }, check.run); // node:test
|
|
234
|
+
* ```
|
|
235
|
+
*
|
|
236
|
+
* Each check makes its own store with `create`, over storage of its own, and gives it to `dispose`
|
|
237
|
+
* at the end. Checks are only added in minor versions. New in 0.9.0.
|
|
238
|
+
*/
|
|
239
|
+
export function documentStoreChecks(options: DocumentStoreChecksOptions): DocumentStoreCheck[] {
|
|
240
|
+
if (typeof options?.create !== "function") throw new TypeError("documentStoreChecks needs a create function that makes a store.");
|
|
241
|
+
const depth = options.scopeDepth ?? 2;
|
|
242
|
+
if (!Number.isInteger(depth) || depth < 1 || depth > 8) throw new TypeError("scopeDepth must be a whole number from 1 to 8.");
|
|
243
|
+
const skip = new Set(options.skip ?? []);
|
|
244
|
+
const isolates = options.isolatesScopes === true;
|
|
245
|
+
const requiresScope = options.requiresScope === true;
|
|
246
|
+
const scopeOf = (tag: string): DocumentScope => Object.freeze(Array.from({ length: depth }, (_, index) => (index === depth - 1 ? `chat-${tag}` : `user-${index + 1}`)));
|
|
247
|
+
const scopes = { a: scopeOf("a"), b: scopeOf("b") };
|
|
248
|
+
|
|
249
|
+
/** Fails when the store lacks the methods of a part that is not skipped. */
|
|
250
|
+
const needs = (store: DocumentStore, part: StoreCheckPart, methods: Array<keyof DocumentStore>) => {
|
|
251
|
+
const absent = methods.filter((method) => typeof store[method] !== "function");
|
|
252
|
+
if (absent.length > 0) fail(`it has no ${absent.join(" or ")}. Pass skip: ["${part}"] if it does not keep that.`);
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
const check = (name: string, body: (harness: Harness) => Promise<void>, timeoutMs = 10_000): DocumentStoreCheck => ({
|
|
256
|
+
name,
|
|
257
|
+
timeoutMs,
|
|
258
|
+
run: async () => {
|
|
259
|
+
let time = Math.floor(Date.now() / 1000) * 1000;
|
|
260
|
+
const start = time;
|
|
261
|
+
const environment: StoreCheckEnvironment = Object.freeze({
|
|
262
|
+
now: () => new Date(time),
|
|
263
|
+
storage: `check-${++checksMade}-${Math.random().toString(36).slice(2, 10)}`,
|
|
264
|
+
scopes: Object.freeze([scopes.a, scopes.b]),
|
|
265
|
+
});
|
|
266
|
+
const stores: DocumentStore[] = [];
|
|
267
|
+
const create = async () => {
|
|
268
|
+
const store = await must(async () => options.create(environment), "create");
|
|
269
|
+
stores.push(store);
|
|
270
|
+
return store;
|
|
271
|
+
};
|
|
272
|
+
// Every failure starts with FAILED: one the check did not foresee names the check.
|
|
273
|
+
const failed: unknown[] = [];
|
|
274
|
+
try {
|
|
275
|
+
const raw = await create();
|
|
276
|
+
await body({
|
|
277
|
+
store: named(raw), raw, environment, start, scopes,
|
|
278
|
+
open: async () => named(await create()),
|
|
279
|
+
setClock: (at) => {
|
|
280
|
+
time = at;
|
|
281
|
+
},
|
|
282
|
+
context: (which = "a") => Object.freeze({ scope: scopes[which], owner: `owner-${which}` }),
|
|
283
|
+
});
|
|
284
|
+
} catch (error) {
|
|
285
|
+
failed.push(error);
|
|
286
|
+
}
|
|
287
|
+
for (const store of stores) {
|
|
288
|
+
try {
|
|
289
|
+
await options.dispose?.(store, environment);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
failed.push(new Error(`${FAILED}${threw("dispose", error)}`, { cause: error }));
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (failed.length === 0) return;
|
|
295
|
+
const [first] = failed;
|
|
296
|
+
throw failure(first) ? first : new Error(`${FAILED}${threw(`the check "${name}"`, first)}`, { cause: first });
|
|
297
|
+
},
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
const checks: DocumentStoreCheck[] = [];
|
|
301
|
+
|
|
302
|
+
checks.push(check("keeps a document as it was put, and copies its metadata on the way in and out", async ({ store, start, context }) => {
|
|
303
|
+
const meta = metaFor("check-copy", TEXT, start, start + DAY, { owner: "owner-a", scope: [...scopes.a] });
|
|
304
|
+
const kept = structuredClone(meta);
|
|
305
|
+
await must(() => store.put({ meta, text: TEXT }, context()), "put");
|
|
306
|
+
meta.name = "changed.txt";
|
|
307
|
+
meta.outline.push({ level: 1, title: "added", line: 2 });
|
|
308
|
+
const got = await must(() => store.get("check-copy", context()), "get");
|
|
309
|
+
if (!got) fail("get gave undefined for a document just put.");
|
|
310
|
+
same(got.text, TEXT, "get(id).text, which must be the text exactly as put");
|
|
311
|
+
same(got.meta, kept, "get(id).meta, after the caller changed the metadata it put");
|
|
312
|
+
got.meta.name = "changed again.txt";
|
|
313
|
+
const read = await must(() => store.getMeta("check-copy", context()), "getMeta");
|
|
314
|
+
same(read, kept, "getMeta(id), after the caller changed the metadata get returned");
|
|
315
|
+
read!.outline.push({ level: 1, title: "added", line: 3 });
|
|
316
|
+
same(await store.getMeta("check-copy", context()), kept, "getMeta(id), after the caller changed the metadata getMeta returned");
|
|
317
|
+
}));
|
|
318
|
+
|
|
319
|
+
checks.push(check("gives undefined for an ID it does not have, and false when asked to delete it", async ({ store, context }) => {
|
|
320
|
+
same(await must(() => store.getMeta("check-unknown", context()), "getMeta"), undefined, "getMeta of an unknown ID");
|
|
321
|
+
same(await must(() => store.get("check-unknown", context()), "get"), undefined, "get of an unknown ID");
|
|
322
|
+
same(await must(() => store.delete("check-unknown", context()), "delete"), false, "delete of an unknown ID");
|
|
323
|
+
if (store.getOriginal && !skip.has("originals")) same(await must(() => store.getOriginal!("check-unknown", context()), "getOriginal"), undefined, "getOriginal of an unknown ID");
|
|
324
|
+
if (store.getIndex && !skip.has("index")) same(await must(() => store.getIndex!("check-unknown", context()), "getIndex"), undefined, "getIndex of an unknown ID");
|
|
325
|
+
}));
|
|
326
|
+
|
|
327
|
+
checks.push(check("keeps fields of the metadata it does not know, for later versions", async ({ store, start, context }) => {
|
|
328
|
+
const meta = metaFor("check-fields", TEXT, start, start + DAY, {
|
|
329
|
+
scope: [...scopes.a], sha256: "0".repeat(64), original: { ref: "uploads/check-fields", bytes: 12, sha256: "1".repeat(64) },
|
|
330
|
+
}) as DocumentMeta & Record<string, unknown>;
|
|
331
|
+
meta.addedLater = { nested: [1, "two", null, { deep: true }], flag: false };
|
|
332
|
+
meta.metaVersion = 1;
|
|
333
|
+
await must(() => store.put({ meta, text: TEXT }, context()), "put");
|
|
334
|
+
same(await store.getMeta("check-fields", context()), meta, "getMeta(id), with fields a later version adds");
|
|
335
|
+
same((await store.get("check-fields", context()))?.meta, meta, "get(id).meta, with fields a later version adds");
|
|
336
|
+
}));
|
|
337
|
+
|
|
338
|
+
checks.push(check("gives back a field that was left out as absent, never as null", async ({ store, start, context }) => {
|
|
339
|
+
await must(() => store.put({ meta: metaFor("check-absent", TEXT, start, start + DAY), text: TEXT }, context()), "put");
|
|
340
|
+
const meta = await store.getMeta("check-absent", context());
|
|
341
|
+
if (!meta) fail("getMeta gave undefined for a document just put.");
|
|
342
|
+
for (const field of ["owner", "scope", "sha256", "original", "pages", "encoding"] as const) {
|
|
343
|
+
if ((meta as Record<string, unknown>)[field] === null) fail(`getMeta gave ${field}: null for a document put without one. Leave it out (a MongoDB driver writes a missing field as null: remove nulls when you read).`);
|
|
344
|
+
}
|
|
345
|
+
await store.put({ meta: metaFor("check-owned", TEXT, start, start + DAY, { owner: "owner-a" }), text: TEXT }, context());
|
|
346
|
+
same((await store.getMeta("check-owned", context()))?.owner, "owner-a", "getMeta(id).owner");
|
|
347
|
+
}));
|
|
348
|
+
|
|
349
|
+
checks.push(check("reads an expired document without an error: as undefined, or as it was for the library to refuse", async ({ store, start, context }) => {
|
|
350
|
+
const meta = metaFor("check-expired", TEXT, start - DAY, start - MINUTE);
|
|
351
|
+
await must(() => store.put({ meta, text: TEXT }, context()), "put");
|
|
352
|
+
const read = await must(() => store.getMeta("check-expired", context()), "getMeta of an expired document");
|
|
353
|
+
if (read !== undefined) same(read, meta, "getMeta of an expired document, which must be undefined or the metadata as it was");
|
|
354
|
+
const whole = await must(() => store.get("check-expired", context()), "get of an expired document");
|
|
355
|
+
if (whole !== undefined) same(whole, { meta, text: TEXT }, "get of an expired document, which must be undefined or the document as it was");
|
|
356
|
+
if (store.sweep && !skip.has("sweep")) {
|
|
357
|
+
await must(() => store.sweep!(new Date(start), {}), "sweep");
|
|
358
|
+
same(await store.getMeta("check-expired", context()), undefined, "getMeta of an expired document after sweep");
|
|
359
|
+
}
|
|
360
|
+
}));
|
|
361
|
+
|
|
362
|
+
checks.push(check("deletes every part of a document, gives false for a second delete, and survives two at once", async ({ store, start, context }) => {
|
|
363
|
+
const originals = !skip.has("originals");
|
|
364
|
+
const indexes = !skip.has("index");
|
|
365
|
+
const ranges = !skip.has("ranges");
|
|
366
|
+
if (originals) needs(store, "originals", ["putOriginal", "getOriginal"]);
|
|
367
|
+
if (indexes) needs(store, "index", ["putIndex", "getIndex"]);
|
|
368
|
+
if (ranges) needs(store, "ranges", ["readTextRange"]);
|
|
369
|
+
const write = async (id: string) => {
|
|
370
|
+
if (originals) await must(() => store.putOriginal!(id, utf8("the upload"), context()), "putOriginal");
|
|
371
|
+
if (indexes) await must(() => store.putIndex!(id, utf8("an index"), context()), "putIndex");
|
|
372
|
+
await must(() => store.put({ meta: metaFor(id, TEXT, start, start + DAY), text: TEXT }, context()), "put");
|
|
373
|
+
};
|
|
374
|
+
const gone = async (id: string, when: string) => {
|
|
375
|
+
same(await store.getMeta(id, context()), undefined, `getMeta ${when}`);
|
|
376
|
+
same(await store.get(id, context()), undefined, `get ${when}`);
|
|
377
|
+
if (originals) same(await store.getOriginal!(id, context()), undefined, `getOriginal ${when}`);
|
|
378
|
+
if (indexes) same(await store.getIndex!(id, context()), undefined, `getIndex ${when}`);
|
|
379
|
+
if (ranges) same(await store.readTextRange!(id, 0, 4, context()), undefined, `readTextRange ${when}`);
|
|
380
|
+
};
|
|
381
|
+
await write("check-delete");
|
|
382
|
+
same(await must(() => store.delete("check-delete", context()), "delete"), true, "delete of a document that is there");
|
|
383
|
+
await gone("check-delete", "after delete");
|
|
384
|
+
same(await must(() => store.delete("check-delete", context()), "a second delete"), false, "a second delete");
|
|
385
|
+
|
|
386
|
+
await write("check-twice");
|
|
387
|
+
await must(() => Promise.all([store.delete("check-twice", context()), store.delete("check-twice", context())]), "two deletes of one document at once");
|
|
388
|
+
await gone("check-twice", "after two deletes at once");
|
|
389
|
+
|
|
390
|
+
// What an ingest that failed leaves: an original and an index, without the document. The
|
|
391
|
+
// library deletes them; a document put later under the ID must not find them.
|
|
392
|
+
if (originals || indexes) {
|
|
393
|
+
if (originals) await store.putOriginal!("check-partial", utf8("the upload"), context());
|
|
394
|
+
if (indexes) await store.putIndex!("check-partial", utf8("an index"), context());
|
|
395
|
+
await must(() => store.delete("check-partial", context()), "delete of a document written only in part");
|
|
396
|
+
await store.put({ meta: metaFor("check-partial", TEXT, start, start + DAY), text: TEXT }, context());
|
|
397
|
+
if (originals) same(await store.getOriginal!("check-partial", context()), undefined, "getOriginal of a document whose original was deleted before it was put");
|
|
398
|
+
if (indexes) same(await store.getIndex!("check-partial", context()), undefined, "getIndex of a document whose index was deleted before it was put");
|
|
399
|
+
}
|
|
400
|
+
}));
|
|
401
|
+
|
|
402
|
+
if (!skip.has("ranges")) {
|
|
403
|
+
checks.push(check("reads the text by range, as UTF-8 bytes: across characters, past the end, and nothing after a delete", async ({ store, start, context }) => {
|
|
404
|
+
needs(store, "ranges", ["readTextRange"]);
|
|
405
|
+
await must(() => store.put({ meta: metaFor("check-range", TEXT, start, start + DAY), text: TEXT }, context()), "put");
|
|
406
|
+
const bytes = utf8(TEXT);
|
|
407
|
+
const size = bytes.length;
|
|
408
|
+
const emoji = bytes.indexOf(0xf0);
|
|
409
|
+
const points = [...new Set([0, 1, 11, 12, 13, emoji, emoji + 1, emoji + 2, emoji + 3, emoji + 4, size - 1, size])].sort((a, b) => a - b);
|
|
410
|
+
for (const from of points) {
|
|
411
|
+
for (const to of points) {
|
|
412
|
+
if (to < from) continue;
|
|
413
|
+
const got = bytesOf(await must(() => store.readTextRange!("check-range", from, to, context()), `readTextRange(id, ${from}, ${to})`), `readTextRange(id, ${from}, ${to})`);
|
|
414
|
+
same(got, bytes.subarray(from, to), `readTextRange(id, ${from}, ${to})`);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
same(bytesOf(await store.readTextRange!("check-range", size - 3, size + 10, context()), "a range past the end"), bytes.subarray(size - 3), `readTextRange(id, ${size - 3}, ${size + 10}), which runs past the end`);
|
|
418
|
+
same(bytesOf(await store.readTextRange!("check-range", size, size + 10, context()), "a range at the end"), new Uint8Array(0), `readTextRange(id, ${size}, ${size + 10}), which starts at the end`);
|
|
419
|
+
same(bytesOf(await store.readTextRange!("check-range", size + 5, size + 10, context()), "a range after the end"), new Uint8Array(0), `readTextRange(id, ${size + 5}, ${size + 10}), which starts after the end`);
|
|
420
|
+
await store.delete("check-range", context());
|
|
421
|
+
same(await must(() => store.readTextRange!("check-range", 0, 4, context()), "readTextRange after delete"), undefined, "readTextRange after delete");
|
|
422
|
+
}));
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
if (!skip.has("index")) {
|
|
426
|
+
checks.push(check("keeps a line index byte for byte, as a copy, the last one written", async ({ store, start, context }) => {
|
|
427
|
+
needs(store, "index", ["putIndex", "getIndex"]);
|
|
428
|
+
const first = Uint8Array.from({ length: 300 }, (_, index) => (index * 7) % 256);
|
|
429
|
+
await must(() => store.putIndex!("check-index", first, context()), "putIndex");
|
|
430
|
+
await store.put({ meta: metaFor("check-index", TEXT, start, start + DAY), text: TEXT }, context());
|
|
431
|
+
same(bytesOf(await must(() => store.getIndex!("check-index", context()), "getIndex"), "getIndex"), first, "getIndex(id)");
|
|
432
|
+
const second = Uint8Array.from({ length: 41 }, (_, index) => 255 - index);
|
|
433
|
+
const kept = second.slice();
|
|
434
|
+
await store.putIndex!("check-index", second, context());
|
|
435
|
+
second.fill(0);
|
|
436
|
+
const got = bytesOf(await store.getIndex!("check-index", context()), "getIndex");
|
|
437
|
+
same(got, kept, "getIndex(id) after a second putIndex, whose bytes the caller then changed");
|
|
438
|
+
got.fill(1);
|
|
439
|
+
same(bytesOf(await store.getIndex!("check-index", context()), "getIndex"), kept, "getIndex(id) after the caller changed the bytes getIndex returned");
|
|
440
|
+
}));
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
if (!skip.has("originals")) {
|
|
444
|
+
checks.push(check("keeps the original byte for byte, as a copy", async ({ store, start, context }) => {
|
|
445
|
+
needs(store, "originals", ["putOriginal", "getOriginal"]);
|
|
446
|
+
const original = Uint8Array.from({ length: 4_096 + 17 }, (_, index) => (index * 31 + (index >> 8)) % 256);
|
|
447
|
+
const kept = original.slice();
|
|
448
|
+
await must(() => store.putOriginal!("check-original", original, context()), "putOriginal");
|
|
449
|
+
original.fill(0);
|
|
450
|
+
await store.put({ meta: metaFor("check-original", TEXT, start, start + DAY, { originalKept: true }), text: TEXT }, context());
|
|
451
|
+
const got = bytesOf(await must(() => store.getOriginal!("check-original", context()), "getOriginal"), "getOriginal");
|
|
452
|
+
same(got, kept, "getOriginal(id), after the caller changed the bytes it put");
|
|
453
|
+
got.fill(1);
|
|
454
|
+
same(bytesOf(await store.getOriginal!("check-original", context()), "getOriginal"), kept, "getOriginal(id), after the caller changed the bytes getOriginal returned");
|
|
455
|
+
}));
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
if (!skip.has("sweep")) {
|
|
459
|
+
checks.push(check("sweeps the documents expired at the time it is given, every part of them, and no other", async ({ store, start, context }) => {
|
|
460
|
+
needs(store, "sweep", ["sweep"]);
|
|
461
|
+
const originals = !skip.has("originals");
|
|
462
|
+
if (originals) needs(store, "originals", ["putOriginal", "getOriginal"]);
|
|
463
|
+
const indexes = Boolean(store.putIndex && store.getIndex) && !skip.has("index");
|
|
464
|
+
const put = async (id: string, expiresAt: number, which: "a" | "b" = "a") => {
|
|
465
|
+
if (originals) await must(() => store.putOriginal!(id, utf8("the upload"), context(which)), "putOriginal");
|
|
466
|
+
if (indexes) await store.putIndex!(id, utf8("an index"), context(which));
|
|
467
|
+
await must(() => store.put({ meta: metaFor(id, TEXT, start, expiresAt, { scope: [...scopes[which]] }), text: TEXT }, context(which)), "put");
|
|
468
|
+
};
|
|
469
|
+
// An original or an index the sweep left is not read while the metadata is gone: it shows once
|
|
470
|
+
// a document is put again under the ID, without them, as the delete check does.
|
|
471
|
+
const left = async (id: string, which: "a" | "b" = "a") => {
|
|
472
|
+
if (!originals && !indexes) return;
|
|
473
|
+
await store.put({ meta: metaFor(id, TEXT, start, start + DAY, { scope: [...scopes[which]] }), text: TEXT }, context(which));
|
|
474
|
+
if (originals) same(await store.getOriginal!(id, context(which)), undefined, "getOriginal of a document put under the ID of a swept one, without an original");
|
|
475
|
+
if (indexes) same(await store.getIndex!(id, context(which)), undefined, "getIndex of a document put under the ID of a swept one, without an index");
|
|
476
|
+
await store.delete(id, context(which));
|
|
477
|
+
};
|
|
478
|
+
await put("check-ends", start + MINUTE);
|
|
479
|
+
await put("check-stays", start + DAY);
|
|
480
|
+
same(await must(() => store.sweep!(new Date(start), {}), "sweep"), 0, "sweep(now) before any document expired");
|
|
481
|
+
same(await must(() => store.sweep!(new Date(start + 2 * MINUTE), {}), "sweep"), 1, "sweep(now) after one document expired (the time it is given, not the time of day)");
|
|
482
|
+
same(await store.getMeta("check-ends", context()), undefined, "getMeta of a swept document");
|
|
483
|
+
if (store.readTextRange && !skip.has("ranges")) same(await store.readTextRange("check-ends", 0, 4, context()), undefined, "readTextRange of a swept document");
|
|
484
|
+
if (indexes) same(await store.getIndex!("check-ends", context()), undefined, "getIndex of a swept document");
|
|
485
|
+
if (!(await store.getMeta("check-stays", context()))) fail("sweep removed a document that had not expired.");
|
|
486
|
+
await left("check-ends");
|
|
487
|
+
if (isolates) {
|
|
488
|
+
await put("check-ends-a", start + MINUTE, "a");
|
|
489
|
+
await put("check-ends-b", start + MINUTE, "b");
|
|
490
|
+
same(await must(() => store.sweep!(new Date(start + 2 * MINUTE), { scope: scopes.a }), "sweep with a scope"), 1, "sweep(now, { scope }) with an expired document in that scope and one in another");
|
|
491
|
+
same(await must(() => store.sweep!(new Date(start + 2 * MINUTE)), "sweep without a context"), 1, "sweep(now) after a sweep of one scope: the expired document of the other scope");
|
|
492
|
+
await left("check-ends-a", "a");
|
|
493
|
+
await left("check-ends-b", "b");
|
|
494
|
+
}
|
|
495
|
+
}));
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
checks.push(check("keeps documents under the IDs an application may choose", async ({ store, start, context }) => {
|
|
499
|
+
const ids = ["a", "0", "upload-3f9a", "a_b-c", `x${"0".repeat(63)}`, `doc_${"0123456789abcdef".repeat(2)}`];
|
|
500
|
+
for (const id of ids) await must(() => store.put({ meta: metaFor(id, `${TEXT} ${id}`, start, start + DAY), text: `${TEXT} ${id}` }, context()), `put of the ID "${id}"`);
|
|
501
|
+
for (const id of ids) {
|
|
502
|
+
same((await store.getMeta(id, context()))?.id, id, `getMeta("${id}").id`);
|
|
503
|
+
same((await store.get(id, context()))?.text, `${TEXT} ${id}`, `get("${id}").text`);
|
|
504
|
+
}
|
|
505
|
+
for (const id of ids) same(await store.delete(id, context()), true, `delete("${id}")`);
|
|
506
|
+
}));
|
|
507
|
+
|
|
508
|
+
checks.push(check("takes a context on every call", async ({ store, start, context }) => {
|
|
509
|
+
const calls = async (id: string, given: DocumentContext | undefined, label: string) => {
|
|
510
|
+
if (store.putOriginal && !skip.has("originals")) await must(() => store.putOriginal!(id, utf8("the upload"), given), `putOriginal ${label}`);
|
|
511
|
+
if (store.putIndex && !skip.has("index")) await must(() => store.putIndex!(id, utf8("an index"), given), `putIndex ${label}`);
|
|
512
|
+
await must(() => store.put({ meta: metaFor(id, TEXT, start, start + DAY), text: TEXT }, given), `put ${label}`);
|
|
513
|
+
if (!(await must(() => store.getMeta(id, given), `getMeta ${label}`))) fail(`getMeta ${label} gave undefined for a document just put.`);
|
|
514
|
+
same((await must(() => store.get(id, given), `get ${label}`))?.text, TEXT, `get ${label}`);
|
|
515
|
+
if (store.readTextRange && !skip.has("ranges")) same(bytesOf(await must(() => store.readTextRange!(id, 0, 5, given), `readTextRange ${label}`), `readTextRange ${label}`), utf8("first"), `readTextRange ${label}`);
|
|
516
|
+
if (store.getIndex && !skip.has("index")) same(bytesOf(await must(() => store.getIndex!(id, given), `getIndex ${label}`), `getIndex ${label}`), utf8("an index"), `getIndex ${label}`);
|
|
517
|
+
if (store.getOriginal && !skip.has("originals")) same(bytesOf(await must(() => store.getOriginal!(id, given), `getOriginal ${label}`), `getOriginal ${label}`), utf8("the upload"), `getOriginal ${label}`);
|
|
518
|
+
same(await must(() => store.delete(id, given), `delete ${label}`), true, `delete ${label}`);
|
|
519
|
+
if (store.sweep && !skip.has("sweep")) await must(() => store.sweep!(new Date(start), given?.scope ? { scope: given.scope } : given), `sweep ${label}`);
|
|
520
|
+
};
|
|
521
|
+
await calls("check-context", context(), "with a scope and an owner");
|
|
522
|
+
await calls("check-context", { scope: scopes.a }, "with a scope alone");
|
|
523
|
+
if (!requiresScope) {
|
|
524
|
+
// As the library called a store before 0.9.0, and as it calls one for a document without a scope.
|
|
525
|
+
await calls("check-context", undefined, "without a context");
|
|
526
|
+
await calls("check-context", {}, "with an empty context");
|
|
527
|
+
await calls("check-context", { owner: "owner-a" }, "with an owner alone");
|
|
528
|
+
}
|
|
529
|
+
}));
|
|
530
|
+
|
|
531
|
+
if (requiresScope) {
|
|
532
|
+
checks.push(check("refuses a call without a scope with a DocumentScopeError of code scope_required, but sweeps every scope without one", async ({ store, raw, start }) => {
|
|
533
|
+
const document = { meta: metaFor("check-scope", TEXT, start, start + DAY), text: TEXT };
|
|
534
|
+
const calls: Array<[string, () => Promise<unknown>]> = [
|
|
535
|
+
["put without a context", () => raw.put(document)],
|
|
536
|
+
["put with an owner alone", () => raw.put(document, { owner: "owner-a" })],
|
|
537
|
+
["getMeta without a context", () => raw.getMeta("check-scope")],
|
|
538
|
+
["get with an empty context", () => raw.get("check-scope", {})],
|
|
539
|
+
["delete without a context", () => raw.delete("check-scope")],
|
|
540
|
+
];
|
|
541
|
+
for (const [label, call] of calls) {
|
|
542
|
+
const error = await thrownBy(call, label);
|
|
543
|
+
if (!DocumentScopeError.is(error) || error.code !== "scope_required") fail(`${label} threw ${thrown(error)}, not a DocumentScopeError of code "scope_required".`);
|
|
544
|
+
}
|
|
545
|
+
if (store.sweep && !skip.has("sweep")) {
|
|
546
|
+
await must(() => store.sweep!(new Date(start)), "sweep without a context");
|
|
547
|
+
await must(() => store.sweep!(new Date(start), {}), "sweep with an empty context");
|
|
548
|
+
}
|
|
549
|
+
}));
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
if (isolates) {
|
|
553
|
+
checks.push(check("the context reaches every call: one ID in two scopes is two documents", async ({ store, start, context }) => {
|
|
554
|
+
const texts = { a: `${TEXT}\nof chat a`, b: `${TEXT}\nof chat b, longer` };
|
|
555
|
+
for (const which of ["a", "b"] as const) {
|
|
556
|
+
if (store.putOriginal && !skip.has("originals")) await store.putOriginal("check-twin", utf8(`upload ${which}`), context(which));
|
|
557
|
+
if (store.putIndex && !skip.has("index")) await store.putIndex("check-twin", utf8(`index ${which}`), context(which));
|
|
558
|
+
await store.put({ meta: metaFor("check-twin", texts[which], start, start + DAY, { scope: [...scopes[which]], owner: `owner-${which}` }), text: texts[which] }, context(which));
|
|
559
|
+
}
|
|
560
|
+
for (const which of ["a", "b"] as const) {
|
|
561
|
+
same((await store.getMeta("check-twin", context(which)))?.scope, [...scopes[which]], `getMeta in scope ${which}`);
|
|
562
|
+
same((await store.get("check-twin", context(which)))?.text, texts[which], `get in scope ${which}`);
|
|
563
|
+
if (store.readTextRange && !skip.has("ranges")) {
|
|
564
|
+
const size = utf8(texts[which]).length;
|
|
565
|
+
same(bytesOf(await store.readTextRange("check-twin", size - 6, size, context(which)), "readTextRange"), utf8(texts[which]).subarray(size - 6), `readTextRange in scope ${which}`);
|
|
566
|
+
}
|
|
567
|
+
if (store.getIndex && !skip.has("index")) same(bytesOf(await store.getIndex("check-twin", context(which)), "getIndex"), utf8(`index ${which}`), `getIndex in scope ${which}`);
|
|
568
|
+
if (store.getOriginal && !skip.has("originals")) same(bytesOf(await store.getOriginal("check-twin", context(which)), "getOriginal"), utf8(`upload ${which}`), `getOriginal in scope ${which}`);
|
|
569
|
+
}
|
|
570
|
+
same(await store.delete("check-twin", context("a")), true, "delete in scope a");
|
|
571
|
+
same(await store.getMeta("check-twin", context("a")), undefined, "getMeta in scope a after its delete");
|
|
572
|
+
same((await store.get("check-twin", context("b")))?.text, texts.b, "get in scope b after the delete in scope a");
|
|
573
|
+
same(await store.delete("check-twin", context("a")), false, "a second delete in scope a");
|
|
574
|
+
}));
|
|
575
|
+
|
|
576
|
+
checks.push(check("a document of one scope is missing from another scope, and from no scope", async ({ store, start, context }) => {
|
|
577
|
+
if (store.putOriginal && !skip.has("originals")) await store.putOriginal("check-apart", utf8("the upload"), context("a"));
|
|
578
|
+
if (store.putIndex && !skip.has("index")) await store.putIndex("check-apart", utf8("an index"), context("a"));
|
|
579
|
+
await store.put({ meta: metaFor("check-apart", TEXT, start, start + DAY, { scope: [...scopes.a] }), text: TEXT }, context("a"));
|
|
580
|
+
const elsewhere: Array<[string, DocumentContext | undefined]> = [["scope b", context("b")]];
|
|
581
|
+
if (!requiresScope) elsewhere.push(["no scope", undefined], ["an owner alone", { owner: "owner-a" }]);
|
|
582
|
+
for (const [label, given] of elsewhere) {
|
|
583
|
+
same(await store.getMeta("check-apart", given), undefined, `getMeta from ${label}`);
|
|
584
|
+
same(await store.get("check-apart", given), undefined, `get from ${label}`);
|
|
585
|
+
if (store.readTextRange && !skip.has("ranges")) same(await store.readTextRange("check-apart", 0, 4, given), undefined, `readTextRange from ${label}`);
|
|
586
|
+
if (store.getIndex && !skip.has("index")) same(await store.getIndex("check-apart", given), undefined, `getIndex from ${label}`);
|
|
587
|
+
if (store.getOriginal && !skip.has("originals")) same(await store.getOriginal("check-apart", given), undefined, `getOriginal from ${label}`);
|
|
588
|
+
same(await store.delete("check-apart", given), false, `delete from ${label}`);
|
|
589
|
+
}
|
|
590
|
+
same((await store.get("check-apart", context("a")))?.text, TEXT, "get in scope a, after the calls from elsewhere");
|
|
591
|
+
}));
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
if (!skip.has("shared")) {
|
|
595
|
+
checks.push(check("two stores over one storage, as two servers, see each other's writes and deletes", async ({ store, start, open, context }) => {
|
|
596
|
+
const other = await open();
|
|
597
|
+
const ranges = (each: DocumentStore) => each.readTextRange && !skip.has("ranges");
|
|
598
|
+
const meta = metaFor("check-shared", TEXT, start, start + DAY);
|
|
599
|
+
await store.put({ meta, text: TEXT }, context());
|
|
600
|
+
// The first store reads the document, as the library does before every use: what it read must
|
|
601
|
+
// not be served once the second store deleted or replaced the document.
|
|
602
|
+
same(await must(() => store.getMeta("check-shared", context()), "getMeta from the first store"), meta, "getMeta from the first store of a document it put");
|
|
603
|
+
same((await must(() => store.get("check-shared", context()), "get from the first store"))?.text, TEXT, "get from the first store of a document it put");
|
|
604
|
+
if (ranges(store)) same(bytesOf(await store.readTextRange!("check-shared", 0, 5, context()), "readTextRange"), utf8("first"), "readTextRange from the first store");
|
|
605
|
+
same((await must(() => other.get("check-shared", context()), "get from the second store"))?.text, TEXT, "get from the second store of a document the first put");
|
|
606
|
+
if (ranges(other)) same(bytesOf(await other.readTextRange!("check-shared", 0, 5, context()), "readTextRange"), utf8("first"), "readTextRange from the second store");
|
|
607
|
+
if (other.putIndex && store.getIndex && !skip.has("index")) {
|
|
608
|
+
await other.putIndex("check-shared", utf8("built on the second server"), context());
|
|
609
|
+
same(bytesOf(await store.getIndex("check-shared", context()), "getIndex"), utf8("built on the second server"), "getIndex from the first store of an index the second put");
|
|
610
|
+
}
|
|
611
|
+
same(await other.delete("check-shared", context()), true, "delete from the second store");
|
|
612
|
+
same(await store.getMeta("check-shared", context()), undefined, "getMeta from the first store after the second deleted the document");
|
|
613
|
+
same(await store.get("check-shared", context()), undefined, "get from the first store after the second deleted the document");
|
|
614
|
+
if (ranges(store)) same(await store.readTextRange!("check-shared", 0, 5, context()), undefined, "readTextRange from the first store after the second deleted the document");
|
|
615
|
+
// The second store puts a new document under the ID, as an ingest with ifExists: "replace" does.
|
|
616
|
+
const text = `${TEXT}\nwritten again on the second server`;
|
|
617
|
+
const replaced = metaFor("check-shared", text, start, start + 2 * DAY, { name: "again.txt" });
|
|
618
|
+
await must(() => other.put({ meta: replaced, text }, context()), "put from the second store");
|
|
619
|
+
same(await store.getMeta("check-shared", context()), replaced, "getMeta from the first store after the second put a new document under the ID");
|
|
620
|
+
// The parts apart, as in the other checks: a store may give more fields, and the message
|
|
621
|
+
// then says which part is not the new one.
|
|
622
|
+
const got = await store.get("check-shared", context());
|
|
623
|
+
same(got?.meta, replaced, "get(id).meta from the first store after the second put a new document under the ID");
|
|
624
|
+
same(got?.text, text, "get(id).text from the first store after the second put a new document under the ID");
|
|
625
|
+
if (ranges(store)) {
|
|
626
|
+
const size = utf8(text).length;
|
|
627
|
+
same(bytesOf(await store.readTextRange!("check-shared", size - 6, size, context()), "readTextRange"), utf8("server"), "readTextRange from the first store after the second put a new document under the ID");
|
|
628
|
+
}
|
|
629
|
+
}));
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
checks.push(check("the library over it, reading by range, gives what it gives over MemoryDocumentStore", async ({ raw, environment, context }) => {
|
|
633
|
+
const keepOriginals = skip.has("originals") ? [] : ["log" as const];
|
|
634
|
+
const libraryOver = (over: DocumentStore): LargeFiles => createLargeFiles({ store: over, now: environment.now, wholeDocumentBytes: 0, budget: { inlineTokens: 1_000 }, keepOriginals });
|
|
635
|
+
const { scope, owner } = context() as { scope: DocumentScope; owner: string };
|
|
636
|
+
const access = { scope, owner };
|
|
637
|
+
const log = serviceLog(3_000);
|
|
638
|
+
const transcript = async (files: LargeFiles) => {
|
|
639
|
+
const meta = await files.ingest({ name: "service.log", bytes: utf8(log), id: "check-log", scope, owner });
|
|
640
|
+
const prepared = await files.prepare([meta.id], { tokens: 0, bytes: 0 }, access);
|
|
641
|
+
const tools = files.tools([meta], { access });
|
|
642
|
+
const results: unknown[] = [meta, [...prepared.blocks], prepared.missing];
|
|
643
|
+
for (const [name, args] of [
|
|
644
|
+
["search_document", { query: "ERROR", mode: "exact", max_results: 50, context_lines: 1 }],
|
|
645
|
+
["search_document", { query: "took 8\\d\\dms", mode: "regex", max_results: 20 }],
|
|
646
|
+
["search_document", { query: "orders 4999 worker" }],
|
|
647
|
+
["read_document", { start_line: 1_490, end_line: 1_510 }],
|
|
648
|
+
["get_document_overview", {}],
|
|
649
|
+
] as const) results.push(await tools.execute(name, { document_id: meta.id, ...args }));
|
|
650
|
+
if (keepOriginals.length > 0) results.push(await files.getOriginal(meta.id, access));
|
|
651
|
+
results.push(await files.delete(meta.id, access), (await files.prepare([meta.id], { tokens: 0, bytes: 0 }, access)).missing);
|
|
652
|
+
return results;
|
|
653
|
+
};
|
|
654
|
+
const expected = await transcript(libraryOver(new MemoryDocumentStore({ now: environment.now })));
|
|
655
|
+
const actual = await must(() => transcript(libraryOver(raw)), "an ingest, a search and a delete through the library");
|
|
656
|
+
expected.forEach((value, index) => same(actual[index], value, `step ${index + 1} of the ingest, search and delete through the library`));
|
|
657
|
+
}, 30_000));
|
|
658
|
+
|
|
659
|
+
return checks;
|
|
660
|
+
}
|