@wazootech/worlds-cloudflare 0.15.9 → 0.15.11
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/README.md +40 -6
- package/dist/{shapes-graph-6g22feyx.js → d1-provenance-sql-CV6Mly6b.js} +51 -19
- package/dist/{d1-schema-builder-BLPr77rK.d.ts → d1-schema-builder-BZMZ8CCv.d.ts} +1 -1
- package/dist/{d1-schema-builder-emxvwyf9.js → d1-schema-builder-hkZBWMiA.js} +3 -2
- package/dist/index.d.ts +14 -7
- package/dist/index.js +53 -28
- package/dist/{mod-BjVVdQCh.d.ts → mod-Bkjkds_5.d.ts} +1 -1
- package/dist/{mod-BfGKU5Gt.d.ts → mod-C6Nc-jgN.d.ts} +2 -2
- package/dist/{mod-B4BJr5j0.d.ts → mod-a3SVCa8c.d.ts} +20 -3
- package/dist/quad-store-BwIxBs51.js +794 -0
- package/dist/quad-store.d.ts +1 -1
- package/dist/quad-store.js +1 -1
- package/dist/{rdfjs-store-YJhcJ8eq.js → rdfjs-store-DjRonoBl.js} +1 -1
- package/dist/rdfjs-store.d.ts +1 -1
- package/dist/rdfjs-store.js +1 -1
- package/dist/schema.d.ts +1 -1
- package/dist/schema.js +1 -1
- package/dist/{search-index-_yyeZAVm.js → search-index-BgOTomws.js} +166 -11
- package/dist/search-index.d.ts +1 -1
- package/dist/search-index.js +1 -1
- package/package.json +1 -1
- package/dist/quad-store-C1IJEz2D.js +0 -492
|
@@ -1,492 +0,0 @@
|
|
|
1
|
-
import { InMemoryProvenanceStore, Transaction, exportFromRdfjsStore, filterQuads, hashQuads, importViaTransaction, isReplaceImportCommit, preparePatch } from "@wazootech/worlds-sdk/quad-store";
|
|
2
|
-
import { planSearchIndexing } from "@wazootech/worlds-sdk/search-index";
|
|
3
|
-
import { commitSqlPatch } from "@wazootech/worlds-sqlite/sql-core";
|
|
4
|
-
import { _ as effectiveLookupChunkSize, a as buildSelectAssertedQuadsPage, d as DEFAULT_D1_MATCH_PAGE_SIZE, f as buildInsertRow, n as buildCountAssertedQuads, p as quadFromD1Row } from "./d1-quad-insert-sql-B4ZiZZe8.js";
|
|
5
|
-
import { c as buildSelectQuadRecords, i as buildInsertProvenance, l as chunk, n as PROVENANCE_IDS_PER_STATEMENT, o as buildSelectProvenance, r as buildDeleteWriteRecords, s as buildSelectProvenanceChains, t as SHAPES_GRAPH } from "./shapes-graph-6g22feyx.js";
|
|
6
|
-
import { Reasoner } from "@wazootech/reasoner";
|
|
7
|
-
import { i as createD1CommitDriver, s as createD1CommitDialect, t as isFullRebuild } from "./project-search-chunks-options-qI9m5FWz.js";
|
|
8
|
-
import { r as matchD1Pages } from "./d1-rdfjs-store-read-2QTEEe_a.js";
|
|
9
|
-
// src/cloudflare/provenance/read-stored-quads.ts
|
|
10
|
-
/** selectStored runs one read; it names `derived` only when inference guarantees the column. */
|
|
11
|
-
async function selectStored(condition, arg, options) {
|
|
12
|
-
const { rows } = await options.connection.execute({
|
|
13
|
-
sql: `SELECT quad_id AS id, s, p, g FROM quads WHERE ${condition}${options.worldId ? " AND world_id = ?" : ""}${options.inferenceEnabled ? " AND derived = 0" : ""} ORDER BY quad_id LIMIT ${PROVENANCE_IDS_PER_STATEMENT}`,
|
|
14
|
-
args: [arg, ...options.worldId ? [options.worldId] : []]
|
|
15
|
-
});
|
|
16
|
-
return rows;
|
|
17
|
-
}
|
|
18
|
-
/** lookupStoredQuads yields the quads among `ids` that the world holds. */
|
|
19
|
-
async function* lookupStoredQuads(ids, options) {
|
|
20
|
-
for (const group of chunk([...new Set(ids)])) yield* await selectStored("quad_id IN (SELECT value FROM json_each(?))", JSON.stringify(group), options);
|
|
21
|
-
}
|
|
22
|
-
/** streamStoredQuads yields every quad of the world, a page at a time. */
|
|
23
|
-
async function* streamStoredQuads(options) {
|
|
24
|
-
let after = "";
|
|
25
|
-
for (;;) {
|
|
26
|
-
const rows = await selectStored("quad_id > ?", after, options);
|
|
27
|
-
yield* rows;
|
|
28
|
-
if (rows.length < 5e3) return;
|
|
29
|
-
after = rows[rows.length - 1].id;
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
// src/cloudflare/provenance/plan-d1-provenance.ts
|
|
33
|
-
/** positionKey identifies the statement a quad makes; a correction changes only the object. */
|
|
34
|
-
function positionKey(s, p, g) {
|
|
35
|
-
return JSON.stringify([
|
|
36
|
-
s,
|
|
37
|
-
p,
|
|
38
|
-
g
|
|
39
|
-
]);
|
|
40
|
-
}
|
|
41
|
-
function positionOf(quad) {
|
|
42
|
-
return positionKey(quad.subject.value, quad.predicate.value, quad.graph.value);
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* planD1Provenance works out, before anything is written, which quads a commit
|
|
46
|
-
* really adds and removes. A quad the world already holds gets no new record, so
|
|
47
|
-
* importing the same data again neither grows the table nor makes an old quad
|
|
48
|
-
* look newly written. The SDK's in-memory store records every insertion instead.
|
|
49
|
-
*/
|
|
50
|
-
async function planD1Provenance(patch, context, options) {
|
|
51
|
-
const { worldId } = options;
|
|
52
|
-
const replacing = isReplaceImportCommit(context);
|
|
53
|
-
const prepared = preparePatch(patch, options);
|
|
54
|
-
const inserted = new Map(prepared.insertionIds.map((id, i) => [id, prepared.insertions[i]]));
|
|
55
|
-
const insertedPositions = new Set([...inserted.values()].map(positionOf));
|
|
56
|
-
const kept = [];
|
|
57
|
-
const removed = [];
|
|
58
|
-
const supersededAt = /* @__PURE__ */ new Map();
|
|
59
|
-
const stored = replacing ? streamStoredQuads(options) : lookupStoredQuads([...inserted.keys(), ...prepared.deletionIds], options);
|
|
60
|
-
for await (const row of stored) {
|
|
61
|
-
if (inserted.has(row.id)) {
|
|
62
|
-
kept.push(row.id);
|
|
63
|
-
continue;
|
|
64
|
-
}
|
|
65
|
-
removed.push([row.id]);
|
|
66
|
-
const position = positionKey(row.s, row.p, row.g);
|
|
67
|
-
if (insertedPositions.has(position)) supersededAt.set(position, row.id);
|
|
68
|
-
}
|
|
69
|
-
const keptIds = new Set(kept);
|
|
70
|
-
const written = [];
|
|
71
|
-
for (const [id, quad] of inserted) if (!keptIds.has(id)) written.push([id, supersededAt.get(positionOf(quad))]);
|
|
72
|
-
const lostByCleanup = replacing ? kept : [];
|
|
73
|
-
const stamp = {
|
|
74
|
-
...context?.provenance,
|
|
75
|
-
recordedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
76
|
-
};
|
|
77
|
-
return {
|
|
78
|
-
removals: buildInsertProvenance("remove", removed, stamp, worldId),
|
|
79
|
-
writes: buildInsertProvenance("write", written, stamp, worldId),
|
|
80
|
-
cleanup: [...buildDeleteWriteRecords(written.map(([id]) => id), stamp.recordedAt, worldId), ...buildInsertProvenance("remove", lostByCleanup.map((id) => [id]), stamp, worldId)]
|
|
81
|
-
};
|
|
82
|
-
}
|
|
83
|
-
// src/cloudflare/provenance/with-provenance.ts
|
|
84
|
-
/**
|
|
85
|
-
* withProvenance adds a plan's statements to a commit dialect, so they join the
|
|
86
|
-
* commit's own batch: removals before the first delete or wipe, writes after the
|
|
87
|
-
* quads they describe. Create one per commit, like the dialect itself.
|
|
88
|
-
*/
|
|
89
|
-
function withProvenance(dialect, plan) {
|
|
90
|
-
const pendingRemovals = [...plan.removals];
|
|
91
|
-
const takeRemovals = () => pendingRemovals.splice(0);
|
|
92
|
-
return {
|
|
93
|
-
...dialect,
|
|
94
|
-
buildWipe: () => [...takeRemovals(), ...dialect.buildWipe()],
|
|
95
|
-
buildDeletions: (keys, hashes) => [...takeRemovals(), ...dialect.buildDeletions(keys, hashes)],
|
|
96
|
-
buildInserts: (quads, keys, hashes) => [...dialect.buildInserts(quads, keys, hashes), ...plan.writes],
|
|
97
|
-
buildCleanup: (keys, hashes) => [...dialect.buildCleanup(keys, hashes), ...plan.cleanup]
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
// src/cloudflare/inference/inference-planner.ts
|
|
101
|
-
/** quadKey identifies a quad by term type and value, datatype and language included. */
|
|
102
|
-
function quadKey(quad) {
|
|
103
|
-
return [
|
|
104
|
-
quad.subject,
|
|
105
|
-
quad.predicate,
|
|
106
|
-
quad.object,
|
|
107
|
-
quad.graph
|
|
108
|
-
].map((term) => {
|
|
109
|
-
if (term.termType === "Literal") return `L|${term.value}|${term.datatype.value}|${term.language}`;
|
|
110
|
-
return `${term.termType}|${term.value}`;
|
|
111
|
-
}).join("\0");
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* planInference reasons about one patch.
|
|
115
|
-
*
|
|
116
|
-
* It rebuilds a Reasoner from the asserted quads (the reasoner has no
|
|
117
|
-
* serialize/restore, so there is no persisted state to resume), runs it, then
|
|
118
|
-
* uses `retract` and `extend` to get exactly the inferred quads the patch
|
|
119
|
-
* removes and adds instead of diffing two closures. The result is correct only
|
|
120
|
-
* if the stored inferred rows equal the closure of `assertedBefore`; a world
|
|
121
|
-
* that had data before inference was enabled needs a one-time rebuild.
|
|
122
|
-
*/
|
|
123
|
-
function planInference(input) {
|
|
124
|
-
const reasoner = new Reasoner({ graphs: input.graphs ?? "per-graph" });
|
|
125
|
-
const asserted = /* @__PURE__ */ new Map();
|
|
126
|
-
for (const quad of input.assertedBefore) asserted.set(quadKey(quad), quad);
|
|
127
|
-
reasoner.add(asserted.values());
|
|
128
|
-
reasoner.run();
|
|
129
|
-
const deletions = dedupe(input.deletions);
|
|
130
|
-
const derivedToRemove = reasoner.retract(deletions.filter((quad) => asserted.has(quadKey(quad))), "application");
|
|
131
|
-
for (const quad of deletions) asserted.delete(quadKey(quad));
|
|
132
|
-
const fresh = dedupe(input.insertions).filter((quad) => !asserted.has(quadKey(quad)));
|
|
133
|
-
return {
|
|
134
|
-
derivedToAdd: reasoner.extend(fresh, "application"),
|
|
135
|
-
derivedToRemove,
|
|
136
|
-
entailedDeletions: deletions.filter((quad) => !asserted.has(quadKey(quad)) && quad.predicate.termType === "NamedNode" && reasoner.has(quad.subject, quad.predicate, quad.object, quad.graph)),
|
|
137
|
-
inconsistencies: reasoner.inconsistencies()
|
|
138
|
-
};
|
|
139
|
-
}
|
|
140
|
-
function dedupe(quads) {
|
|
141
|
-
const seen = /* @__PURE__ */ new Map();
|
|
142
|
-
for (const quad of quads) seen.set(quadKey(quad), quad);
|
|
143
|
-
return [...seen.values()];
|
|
144
|
-
}
|
|
145
|
-
// src/cloudflare/shacl/create-d1-shacl-source.ts
|
|
146
|
-
/** MAX_SHAPE_QUADS is how large a world's shapes graph may be. */
|
|
147
|
-
const MAX_SHAPE_QUADS = 1e4;
|
|
148
|
-
const VALUES_PER_STATEMENT = 2e3;
|
|
149
|
-
const CHARACTERS_PER_STATEMENT = 4e5;
|
|
150
|
-
/** createD1ShaclSource reads the facts that a SHACL check asks for from D1. */
|
|
151
|
-
function createD1ShaclSource(options) {
|
|
152
|
-
const { connection, worldId, inferenceEnabled } = options;
|
|
153
|
-
async function select(condition, args, limit, world = "world_id") {
|
|
154
|
-
const { rows } = await connection.execute({
|
|
155
|
-
sql: `SELECT s, s_type, p, o, o_type, o_datatype, o_lang, g, g_type FROM quads WHERE ${condition}${worldId ? ` AND ${world} = ?` : ""} LIMIT ${Math.min(Math.floor(limit), Number.MAX_SAFE_INTEGER)}`,
|
|
156
|
-
args: worldId ? [...args, worldId] : args
|
|
157
|
-
});
|
|
158
|
-
return rows.map(quadFromD1Row);
|
|
159
|
-
}
|
|
160
|
-
/** selectAmong runs one statement per group of values, up to one row over the limit. */
|
|
161
|
-
async function selectAmong(column, terms, predicates, limit) {
|
|
162
|
-
const found = [];
|
|
163
|
-
const among = (name) => `${name} IN (SELECT value FROM json_each(?))`;
|
|
164
|
-
for (const values of groupValues(terms)) {
|
|
165
|
-
const rows = await select(`${predicates ? `${among("p")} AND ` : ""}${among(column)} AND g <> '${SHAPES_GRAPH}'`, [...predicates ? [JSON.stringify(predicates)] : [], values], limit + 1 - found.length, "+world_id");
|
|
166
|
-
for (const row of rows) found.push(row);
|
|
167
|
-
if (found.length > limit) break;
|
|
168
|
-
}
|
|
169
|
-
return found;
|
|
170
|
-
}
|
|
171
|
-
return {
|
|
172
|
-
shapes: () => select(`g = '${SHAPES_GRAPH}'${inferenceEnabled ? " AND derived = 0" : ""}`, [], 10001),
|
|
173
|
-
outgoing: ({ subjects, predicates, limit }) => selectAmong("s", subjects, predicates, limit),
|
|
174
|
-
incoming: ({ objects, predicate, limit }) => selectAmong("o", objects, [predicate], limit)
|
|
175
|
-
};
|
|
176
|
-
}
|
|
177
|
-
/** groupValues packs the terms' values into JSON lists that fit a D1 parameter. */
|
|
178
|
-
function* groupValues(terms) {
|
|
179
|
-
let group = [];
|
|
180
|
-
let characters = 0;
|
|
181
|
-
for (const value of new Set(terms.map((term) => term.value))) {
|
|
182
|
-
if ((group.length >= VALUES_PER_STATEMENT || characters + value.length > CHARACTERS_PER_STATEMENT) && group.length > 0) {
|
|
183
|
-
yield JSON.stringify(group);
|
|
184
|
-
group = [];
|
|
185
|
-
characters = 0;
|
|
186
|
-
}
|
|
187
|
-
group.push(value);
|
|
188
|
-
characters += value.length;
|
|
189
|
-
}
|
|
190
|
-
if (group.length > 0) yield JSON.stringify(group);
|
|
191
|
-
}
|
|
192
|
-
// src/cloudflare/shacl/check-d1-patch.ts
|
|
193
|
-
/**
|
|
194
|
-
* checkD1Patch rejects when a commit would add violations of the world's SHACL
|
|
195
|
-
* shapes, counting the inferred quads it adds and removes. Call it before
|
|
196
|
-
* anything is written. A world without shapes costs one indexed read, and never
|
|
197
|
-
* loads the validator.
|
|
198
|
-
*/
|
|
199
|
-
async function checkD1Patch(patch, context, options, derived) {
|
|
200
|
-
if (options.shacl?.enabled === false) return;
|
|
201
|
-
const matches = filterQuads(options);
|
|
202
|
-
const insertions = patch.insertions.filter(matches);
|
|
203
|
-
const deletions = patch.deletions.filter(matches);
|
|
204
|
-
const source = createD1ShaclSource({
|
|
205
|
-
connection: options.connection,
|
|
206
|
-
worldId: options.worldId,
|
|
207
|
-
inferenceEnabled: options.inference?.enabled === true
|
|
208
|
-
});
|
|
209
|
-
const shapes = isReplaceImportCommit(context) ? [] : await source.shapes();
|
|
210
|
-
if (shapes.length === 0 && !insertions.some(isShape)) return;
|
|
211
|
-
const { InvalidShapesError, validateWrite } = await import("@wazootech/worlds-sdk/shacl");
|
|
212
|
-
if (countShapesAfter(shapes, insertions, deletions) > 1e4) throw new InvalidShapesError([`A world can have at most ${MAX_SHAPE_QUADS} quads of shapes.`]);
|
|
213
|
-
await validateWrite({
|
|
214
|
-
patch: {
|
|
215
|
-
insertions: [...insertions, ...(derived?.added ?? []).filter((quad) => !isShape(quad))],
|
|
216
|
-
deletions: [...deletions, ...(derived?.removed ?? []).filter((quad) => !isShape(quad))]
|
|
217
|
-
},
|
|
218
|
-
context,
|
|
219
|
-
source: {
|
|
220
|
-
...source,
|
|
221
|
-
shapes: () => Promise.resolve(shapes)
|
|
222
|
-
},
|
|
223
|
-
maxCheckedFacts: options.shacl?.maxCheckedFacts
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
function isShape(quad) {
|
|
227
|
-
return quad.graph.value === SHAPES_GRAPH;
|
|
228
|
-
}
|
|
229
|
-
function countShapesAfter(stored, insertions, deletions) {
|
|
230
|
-
const keys = new Set(stored.map(quadKey));
|
|
231
|
-
for (const quad of deletions) keys.delete(quadKey(quad));
|
|
232
|
-
for (const quad of insertions) if (isShape(quad)) keys.add(quadKey(quad));
|
|
233
|
-
return keys.size;
|
|
234
|
-
}
|
|
235
|
-
// src/cloudflare/inference/load-asserted-quads.ts
|
|
236
|
-
/** DEFAULT_MAX_ASSERTED_QUADS is the default inference size guard. */
|
|
237
|
-
const DEFAULT_MAX_ASSERTED_QUADS = 1e5;
|
|
238
|
-
const PAGE_SIZE = 1e3;
|
|
239
|
-
/** InferenceSizeGuardError is thrown, before any write, when a world is too big to reason over. */
|
|
240
|
-
var InferenceSizeGuardError = class extends Error {
|
|
241
|
-
assertedQuads;
|
|
242
|
-
maxAssertedQuads;
|
|
243
|
-
constructor(assertedQuads, maxAssertedQuads) {
|
|
244
|
-
super(`inference size guard: ${assertedQuads} asserted quads exceed maxAssertedQuads (${maxAssertedQuads}); each commit rebuilds the reasoner from all asserted quads. Disable inference for this world or raise the limit.`);
|
|
245
|
-
this.assertedQuads = assertedQuads;
|
|
246
|
-
this.maxAssertedQuads = maxAssertedQuads;
|
|
247
|
-
this.name = "InferenceSizeGuardError";
|
|
248
|
-
}
|
|
249
|
-
};
|
|
250
|
-
/**
|
|
251
|
-
* loadAssertedQuads reads every asserted (derived = 0) quad of the world,
|
|
252
|
-
* failing with InferenceSizeGuardError when `pendingInsertions` more would
|
|
253
|
-
* exceed `maxAssertedQuads`.
|
|
254
|
-
*/
|
|
255
|
-
async function loadAssertedQuads(connection, options) {
|
|
256
|
-
const count = await connection.execute(buildCountAssertedQuads(options.worldId));
|
|
257
|
-
const total = Number(count.rows[0]?.count ?? 0);
|
|
258
|
-
if (total + options.pendingInsertions > options.maxAssertedQuads) throw new InferenceSizeGuardError(total + options.pendingInsertions, options.maxAssertedQuads);
|
|
259
|
-
const quads = [];
|
|
260
|
-
let afterQuadId;
|
|
261
|
-
for (;;) {
|
|
262
|
-
const page = await connection.execute(buildSelectAssertedQuadsPage({
|
|
263
|
-
afterQuadId,
|
|
264
|
-
limit: PAGE_SIZE
|
|
265
|
-
}, options.worldId));
|
|
266
|
-
for (const row of page.rows) quads.push(quadFromD1Row(row));
|
|
267
|
-
if (page.rows.length < PAGE_SIZE) return quads;
|
|
268
|
-
afterQuadId = String(page.rows[page.rows.length - 1].id);
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
// src/cloudflare/commit/d1-derived-changes.ts
|
|
272
|
-
/**
|
|
273
|
-
* planD1DerivedChanges reasons over the world's asserted quads before the
|
|
274
|
-
* commit writes anything, so a size-guard failure leaves the world untouched.
|
|
275
|
-
* A replace import wipes the world first, so nothing existing counts.
|
|
276
|
-
*/
|
|
277
|
-
async function planD1DerivedChanges(patch, context, inference, driverOptions) {
|
|
278
|
-
const prepared = preparePatch(patch, driverOptions);
|
|
279
|
-
const maxAssertedQuads = inference.maxAssertedQuads ?? 1e5;
|
|
280
|
-
const replacing = isReplaceImportCommit(context);
|
|
281
|
-
if (replacing && prepared.insertions.length > maxAssertedQuads) throw new InferenceSizeGuardError(prepared.insertions.length, maxAssertedQuads);
|
|
282
|
-
const plan = planInference({
|
|
283
|
-
assertedBefore: replacing ? [] : await loadAssertedQuads(driverOptions.connection, {
|
|
284
|
-
worldId: driverOptions.worldId,
|
|
285
|
-
maxAssertedQuads,
|
|
286
|
-
pendingInsertions: prepared.insertions.length
|
|
287
|
-
}),
|
|
288
|
-
deletions: prepared.deletions,
|
|
289
|
-
insertions: prepared.insertions,
|
|
290
|
-
graphs: inference.graphs
|
|
291
|
-
});
|
|
292
|
-
const addRows = /* @__PURE__ */ new Map();
|
|
293
|
-
const derived = [...plan.derivedToAdd, ...plan.entailedDeletions];
|
|
294
|
-
const derivedIds = hashQuads(derived);
|
|
295
|
-
derived.forEach((quad, index) => {
|
|
296
|
-
const id = derivedIds[index];
|
|
297
|
-
if (!addRows.has(id)) addRows.set(id, {
|
|
298
|
-
...buildInsertRow(quad, id),
|
|
299
|
-
world_id: driverOptions.worldId,
|
|
300
|
-
derived: 1
|
|
301
|
-
});
|
|
302
|
-
});
|
|
303
|
-
return {
|
|
304
|
-
removeIds: hashQuads(plan.derivedToRemove),
|
|
305
|
-
addRows: [...addRows.values()],
|
|
306
|
-
removed: plan.derivedToRemove,
|
|
307
|
-
added: derived
|
|
308
|
-
};
|
|
309
|
-
}
|
|
310
|
-
// src/cloudflare/commit/commit-d1-patch.ts
|
|
311
|
-
/**
|
|
312
|
-
* commitD1Patch runs one D1 commit through the shared SQL commit core
|
|
313
|
-
* (`commitSqlPatch`). D1 batches are not atomic with the outside-D1 Vectorize
|
|
314
|
-
* index, which the platform forces: vectors sync after the D1 write lands, and
|
|
315
|
-
* a failure there is logged drift that a reindex repairs. An embedding failure
|
|
316
|
-
* throws before anything is written, so the caller can retry. So does a SHACL
|
|
317
|
-
* violation. Imports project
|
|
318
|
-
* chunks during the commit (`searchIndexOnImport` defaults to the shared
|
|
319
|
-
* `"incremental"`); `"deferred"` stays available as an option.
|
|
320
|
-
*/
|
|
321
|
-
async function commitD1Patch(patch, context, options) {
|
|
322
|
-
const { connection, worldId, searchIndexProjector: projector } = options;
|
|
323
|
-
const sync = projector?.createVectorSync();
|
|
324
|
-
const driverOptions = {
|
|
325
|
-
...options,
|
|
326
|
-
connection,
|
|
327
|
-
inferenceEnabled: options.inference?.enabled === true,
|
|
328
|
-
beforePage: sync?.beforePage
|
|
329
|
-
};
|
|
330
|
-
const derived = options.inference?.enabled ? await planD1DerivedChanges(patch, context, options.inference, driverOptions) : void 0;
|
|
331
|
-
await checkD1Patch(patch, context, options, derived);
|
|
332
|
-
const provenance = options.provenance?.enabled ? await planD1Provenance(patch, context, driverOptions) : void 0;
|
|
333
|
-
const indexing = planSearchIndexing(options.searchIndexOnImport, context);
|
|
334
|
-
const dialect = createD1CommitDialect({
|
|
335
|
-
searchQueryBuilder: options.searchQueryBuilder,
|
|
336
|
-
worldId,
|
|
337
|
-
lookupChunkSize: effectiveLookupChunkSize(options.maxLookupChunkSize, Boolean(worldId)),
|
|
338
|
-
derived,
|
|
339
|
-
onChunkRows: sync?.collect
|
|
340
|
-
});
|
|
341
|
-
await commitSqlPatch(patch, context, createD1CommitDriver(driverOptions), provenance ? withProvenance(dialect, provenance) : dialect, {
|
|
342
|
-
filter: options,
|
|
343
|
-
searchIndexOnImport: options.searchIndexOnImport,
|
|
344
|
-
projection: projector?.projection,
|
|
345
|
-
rebuildPageSize: DEFAULT_D1_MATCH_PAGE_SIZE,
|
|
346
|
-
afterWrite: async () => {
|
|
347
|
-
if (indexing.reindexAfterCommit ? isFullRebuild(options) : isReplaceImportCommit(context) && indexing.projectDuringCommit) await sync?.purgeWorld();
|
|
348
|
-
await sync?.flush();
|
|
349
|
-
}
|
|
350
|
-
});
|
|
351
|
-
await sync?.flush();
|
|
352
|
-
sync?.logDrift(indexing.reindexAfterCommit ? "reindex" : "import");
|
|
353
|
-
}
|
|
354
|
-
// src/cloudflare/provenance/d1-provenance-store.ts
|
|
355
|
-
/** recordFromRow maps a `provenance` row to the SDK's record, omitting empty fields. */
|
|
356
|
-
function recordFromRow(row) {
|
|
357
|
-
return {
|
|
358
|
-
quadId: String(row.quad_id),
|
|
359
|
-
recordedAt: String(row.recorded_at),
|
|
360
|
-
type: row.type,
|
|
361
|
-
...row.writer != null && { writer: String(row.writer) },
|
|
362
|
-
...row.source != null && { source: String(row.source) },
|
|
363
|
-
...row.supersedes_quad_id != null && { supersedesQuadId: String(row.supersedes_quad_id) }
|
|
364
|
-
};
|
|
365
|
-
}
|
|
366
|
-
/**
|
|
367
|
-
* D1ProvenanceStore is the durable ProvenanceStore over the `provenance` table.
|
|
368
|
-
* Commits do not go through `record`: they write their records in the same batch
|
|
369
|
-
* as the quads (see `planD1Provenance`).
|
|
370
|
-
*/
|
|
371
|
-
var D1ProvenanceStore = class {
|
|
372
|
-
options;
|
|
373
|
-
constructor(options) {
|
|
374
|
-
this.options = options;
|
|
375
|
-
}
|
|
376
|
-
/** record appends one record on its own, outside any commit. */
|
|
377
|
-
async record(input) {
|
|
378
|
-
const recordedAt = input.recordedAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
379
|
-
const type = input.type ?? "write";
|
|
380
|
-
await this.options.connection.batch(buildInsertProvenance(type, [[input.quadId, input.supersedesQuadId]], {
|
|
381
|
-
recordedAt,
|
|
382
|
-
writer: input.writer,
|
|
383
|
-
source: input.source
|
|
384
|
-
}, this.options.worldId));
|
|
385
|
-
return {
|
|
386
|
-
...input,
|
|
387
|
-
recordedAt,
|
|
388
|
-
type
|
|
389
|
-
};
|
|
390
|
-
}
|
|
391
|
-
/** list returns matching records, oldest first. */
|
|
392
|
-
async list(query) {
|
|
393
|
-
const { rows } = await this.options.connection.execute(buildSelectProvenance(query ?? {}, this.options.worldId));
|
|
394
|
-
return rows.map(recordFromRow);
|
|
395
|
-
}
|
|
396
|
-
/** history walks what the quad replaced and what replaced it. */
|
|
397
|
-
async history(quadId) {
|
|
398
|
-
return await (await this.load([quadId])).history(quadId);
|
|
399
|
-
}
|
|
400
|
-
/**
|
|
401
|
-
* load reads the records of `quadIds` in one query, with their full correction
|
|
402
|
-
* chains unless `chains` is false, into the SDK's in-memory store, so walks
|
|
403
|
-
* behave exactly as they do there.
|
|
404
|
-
*/
|
|
405
|
-
async load(quadIds, chains = true) {
|
|
406
|
-
const build = chains ? buildSelectProvenanceChains : buildSelectQuadRecords;
|
|
407
|
-
const { rows } = await this.options.connection.execute(build(quadIds, this.options.worldId));
|
|
408
|
-
const loaded = new InMemoryProvenanceStore();
|
|
409
|
-
for (const row of rows) await loaded.record(recordFromRow(row));
|
|
410
|
-
return loaded;
|
|
411
|
-
}
|
|
412
|
-
};
|
|
413
|
-
// src/cloudflare/provenance/query-d1-provenance.ts
|
|
414
|
-
/** matchQuads reads the quads matching the pattern, fetching no page past the limit. */
|
|
415
|
-
async function matchQuads(request, options) {
|
|
416
|
-
const limit = request.limit ?? 1e400;
|
|
417
|
-
const pageSize = options.matchPageSize ?? 1e3;
|
|
418
|
-
const quads = [];
|
|
419
|
-
for await (const quad of matchD1Pages(options.connection, Math.min(pageSize, limit), options.worldId, request.subject, request.predicate, request.object)) {
|
|
420
|
-
quads.push(quad);
|
|
421
|
-
if (quads.length >= limit) break;
|
|
422
|
-
}
|
|
423
|
-
return quads;
|
|
424
|
-
}
|
|
425
|
-
/**
|
|
426
|
-
* queryD1Provenance pairs each quad matching the pattern, up to the request's
|
|
427
|
-
* limit, with its records and history. Quads written before the world opted in come back with none.
|
|
428
|
-
*/
|
|
429
|
-
async function queryD1Provenance(request, options) {
|
|
430
|
-
const chains = options.provenance?.history !== false;
|
|
431
|
-
const provenance = new D1ProvenanceStore(options);
|
|
432
|
-
const quads = await matchQuads(request, options);
|
|
433
|
-
const ids = quads.length > 0 ? hashQuads(quads) : [];
|
|
434
|
-
const results = [];
|
|
435
|
-
for (const group of chunk(ids)) {
|
|
436
|
-
const loaded = await provenance.load(group, chains);
|
|
437
|
-
for (const quadId of group) results.push({
|
|
438
|
-
quadId,
|
|
439
|
-
quad: quads[results.length],
|
|
440
|
-
records: await loaded.list({ quadId }),
|
|
441
|
-
history: chains ? await loaded.history(quadId) : {
|
|
442
|
-
quadId,
|
|
443
|
-
supersedes: [],
|
|
444
|
-
supersededBy: []
|
|
445
|
-
}
|
|
446
|
-
});
|
|
447
|
-
}
|
|
448
|
-
return { results };
|
|
449
|
-
}
|
|
450
|
-
// src/cloudflare/quad-store/d1-quad-store.ts
|
|
451
|
-
/**
|
|
452
|
-
* D1QuadStore implements the QuadStoreInterface for D1 backed durable persistence.
|
|
453
|
-
* It encapsulates transaction routing, commits, and indexing synchronization.
|
|
454
|
-
*/
|
|
455
|
-
var D1QuadStore = class {
|
|
456
|
-
options;
|
|
457
|
-
constructor(options) {
|
|
458
|
-
this.options = options;
|
|
459
|
-
}
|
|
460
|
-
/**
|
|
461
|
-
* import merges or replaces the underlying store with provided RDF source data.
|
|
462
|
-
*
|
|
463
|
-
* @param request The payload defining the ingestion source and overwrite mode.
|
|
464
|
-
*/
|
|
465
|
-
async import(request) {
|
|
466
|
-
await importViaTransaction(request, { createTransaction: () => this.createTransaction() });
|
|
467
|
-
}
|
|
468
|
-
/**
|
|
469
|
-
* export extracts the graph contents in raw quads or serialized formats.
|
|
470
|
-
*
|
|
471
|
-
* @param request The desired format specifications.
|
|
472
|
-
*/
|
|
473
|
-
async export(request) {
|
|
474
|
-
return await exportFromRdfjsStore(this.options.store, request);
|
|
475
|
-
}
|
|
476
|
-
/**
|
|
477
|
-
* provenanceQuery returns the records and correction history of the quads
|
|
478
|
-
* matching the pattern. It rejects when the world has not opted in.
|
|
479
|
-
*/
|
|
480
|
-
async provenanceQuery(request) {
|
|
481
|
-
if (!this.options.provenance?.enabled) throw new Error("Provenance is not configured.");
|
|
482
|
-
return await queryD1Provenance(request, this.options);
|
|
483
|
-
}
|
|
484
|
-
/**
|
|
485
|
-
* createTransaction returns a pre-configured Transaction bound to internal commit hooks.
|
|
486
|
-
* Its commit uses `defaults` when it is given no context of its own.
|
|
487
|
-
*/
|
|
488
|
-
createTransaction(defaults) {
|
|
489
|
-
return new Transaction({ commit: (patch, context) => commitD1Patch(patch, context ?? defaults, this.options) });
|
|
490
|
-
}
|
|
491
|
-
};
|
|
492
|
-
export { loadAssertedQuads as a, InferenceSizeGuardError as i, D1ProvenanceStore as n, planInference as o, DEFAULT_MAX_ASSERTED_QUADS as r, D1QuadStore as t };
|