fatedb 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +264 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +3 -0
- package/dist/cli.d.ts +15 -0
- package/dist/cli.js +256 -0
- package/dist/client.d.ts +152 -0
- package/dist/client.js +416 -0
- package/dist/cloudflare.d.ts +197 -0
- package/dist/cloudflare.js +159 -0
- package/dist/datalog/ast.d.ts +35 -0
- package/dist/datalog/ast.js +40 -0
- package/dist/datalog/evaluator.d.ts +14 -0
- package/dist/datalog/evaluator.js +395 -0
- package/dist/datalog/fact-source.d.ts +30 -0
- package/dist/datalog/fact-source.js +1 -0
- package/dist/datalog/fingerprint.d.ts +12 -0
- package/dist/datalog/fingerprint.js +50 -0
- package/dist/datalog/parser.d.ts +3 -0
- package/dist/datalog/parser.js +302 -0
- package/dist/datalog/value.d.ts +34 -0
- package/dist/datalog/value.js +104 -0
- package/dist/domain/date-validation.d.ts +2 -0
- package/dist/domain/date-validation.js +32 -0
- package/dist/domain/fact-value.d.ts +91 -0
- package/dist/domain/fact-value.js +167 -0
- package/dist/domain/fact.d.ts +14 -0
- package/dist/domain/fact.js +47 -0
- package/dist/domain/failure.d.ts +44 -0
- package/dist/domain/failure.js +30 -0
- package/dist/domain/graph-id.d.ts +7 -0
- package/dist/domain/graph-id.js +10 -0
- package/dist/domain/histogram.d.ts +29 -0
- package/dist/domain/histogram.js +48 -0
- package/dist/domain/identifiers.d.ts +26 -0
- package/dist/domain/identifiers.js +75 -0
- package/dist/domain/numbers.d.ts +12 -0
- package/dist/domain/numbers.js +77 -0
- package/dist/domain/projection.d.ts +252 -0
- package/dist/domain/projection.js +51 -0
- package/dist/domain/query-metrics.d.ts +31 -0
- package/dist/domain/query-metrics.js +35 -0
- package/dist/domain/read-token.d.ts +37 -0
- package/dist/domain/read-token.js +93 -0
- package/dist/domain/result.d.ts +22 -0
- package/dist/domain/result.js +16 -0
- package/dist/domain/schema-observation.d.ts +20 -0
- package/dist/domain/schema-observation.js +61 -0
- package/dist/domain/string-order.d.ts +2 -0
- package/dist/domain/string-order.js +15 -0
- package/dist/domain/vocabulary.d.ts +101 -0
- package/dist/domain/vocabulary.js +276 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +14 -0
- package/dist/projection-config.d.ts +3 -0
- package/dist/projection-config.js +212 -0
- package/dist/server/access.d.ts +32 -0
- package/dist/server/access.js +117 -0
- package/dist/server/admin.d.ts +233 -0
- package/dist/server/admin.js +483 -0
- package/dist/server/authorization.d.ts +35 -0
- package/dist/server/authorization.js +76 -0
- package/dist/server/console-assets.d.ts +6 -0
- package/dist/server/console-assets.js +2 -0
- package/dist/server/console.d.ts +8 -0
- package/dist/server/console.js +301 -0
- package/dist/server/index.d.ts +122 -0
- package/dist/server/index.js +487 -0
- package/dist/server/mcp.d.ts +31 -0
- package/dist/server/mcp.js +169 -0
- package/dist/server/telemetry-do.d.ts +31 -0
- package/dist/server/telemetry-do.js +342 -0
- package/dist/server/telemetry.d.ts +27 -0
- package/dist/server/telemetry.js +191 -0
- package/dist/storage/constants.d.ts +20 -0
- package/dist/storage/constants.js +21 -0
- package/dist/storage/environment.d.ts +438 -0
- package/dist/storage/environment.js +145 -0
- package/dist/storage/facts.d.ts +41 -0
- package/dist/storage/facts.js +73 -0
- package/dist/storage/http.d.ts +55 -0
- package/dist/storage/http.js +169 -0
- package/dist/storage/keys.d.ts +50 -0
- package/dist/storage/keys.js +84 -0
- package/dist/storage/layout.d.ts +67 -0
- package/dist/storage/layout.js +134 -0
- package/dist/storage/log.d.ts +41 -0
- package/dist/storage/log.js +137 -0
- package/dist/storage/manifest.d.ts +26 -0
- package/dist/storage/manifest.js +206 -0
- package/dist/storage/operations.d.ts +303 -0
- package/dist/storage/operations.js +719 -0
- package/dist/storage/partition.d.ts +125 -0
- package/dist/storage/partition.js +816 -0
- package/dist/storage/projection.d.ts +72 -0
- package/dist/storage/projection.js +1349 -0
- package/dist/storage/root.d.ts +120 -0
- package/dist/storage/root.js +596 -0
- package/dist/storage/segment.d.ts +145 -0
- package/dist/storage/segment.js +451 -0
- package/dist/storage/shard.d.ts +82 -0
- package/dist/storage/shard.js +710 -0
- package/dist/storage/source.d.ts +60 -0
- package/dist/storage/source.js +199 -0
- package/dist/telemetry/model.d.ts +123 -0
- package/dist/telemetry/model.js +292 -0
- package/dist/version.d.ts +4 -0
- package/dist/version.js +6 -0
- package/package.json +82 -4
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
import { compareDatalogValues, equalDatalogValues, sameDatalogValue } from "./value.js";
|
|
2
|
+
const DEFAULT_MAX_RESULTS = 10_000;
|
|
3
|
+
const MAX_CONCURRENT_FINAL_SCANS = 4;
|
|
4
|
+
const MAX_FINAL_JOIN_BINDINGS = 16;
|
|
5
|
+
/**
|
|
6
|
+
* Bindings handed from one atom to the next at a time: a first batch small enough that a caller who
|
|
7
|
+
* wants a few rows waits for few lookups, then batches big enough that a join sees how many lookups
|
|
8
|
+
* it would make.
|
|
9
|
+
*/
|
|
10
|
+
const FIRST_BATCH_BINDINGS = 256;
|
|
11
|
+
const BATCH_BINDINGS = 4_096;
|
|
12
|
+
/** Scans by binding in flight at once, when an atom looks each binding up. */
|
|
13
|
+
const CONCURRENT_SCANS = 16;
|
|
14
|
+
export class QueryResultLimitExceeded extends Error {
|
|
15
|
+
maxResults;
|
|
16
|
+
constructor(maxResults) {
|
|
17
|
+
super(`query result limit exceeded (${maxResults})`);
|
|
18
|
+
this.maxResults = maxResults;
|
|
19
|
+
this.name = "QueryResultLimitExceeded";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export async function* evaluateDatalog(query, facts, options = {}) {
|
|
23
|
+
const maxResults = options.maxResults ?? DEFAULT_MAX_RESULTS;
|
|
24
|
+
if (!Number.isSafeInteger(maxResults) || maxResults < 1) {
|
|
25
|
+
throw new RangeError("maxResults must be a positive safe integer");
|
|
26
|
+
}
|
|
27
|
+
let emitted = 0;
|
|
28
|
+
for await (const batch of evaluateQueryFacts(query.facts, facts, options.signal)) {
|
|
29
|
+
throwIfAborted(options.signal);
|
|
30
|
+
for (const binding of batch) {
|
|
31
|
+
if (!query.constraints.every((constraint) => {
|
|
32
|
+
const left = resolveTerm(constraint.left, binding);
|
|
33
|
+
const right = resolveTerm(constraint.right, binding);
|
|
34
|
+
return left !== undefined && right !== undefined && evaluateBuiltin(constraint.name, left, right);
|
|
35
|
+
}))
|
|
36
|
+
continue;
|
|
37
|
+
if (emitted === maxResults)
|
|
38
|
+
throw new QueryResultLimitExceeded(maxResults);
|
|
39
|
+
emitted += 1;
|
|
40
|
+
yield binding;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async function* evaluateQueryFacts(clauses, facts, signal) {
|
|
45
|
+
const [filter, output] = clauses;
|
|
46
|
+
// This physical operator needs no cross-entity exchange. Distinct variables
|
|
47
|
+
// keep repeated-variable unification on the general evaluation path.
|
|
48
|
+
if (facts.scanEntityJoin && clauses.length === 2 && filter && output &&
|
|
49
|
+
filter.entity.kind === "variable" && output.entity.kind === "variable" &&
|
|
50
|
+
filter.entity.name === output.entity.name && filter.value.kind === "constant" &&
|
|
51
|
+
output.value.kind === "variable" && output.value.name !== filter.entity.name) {
|
|
52
|
+
yield* batchesOf(entityJoin(facts.scanEntityJoin({ field: filter.predicate, value: filter.value.value }, output.predicate, signal), filter.entity.name, output.value.name, signal));
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (canScanFinalJoinConcurrently(clauses)) {
|
|
56
|
+
if (facts.scanValues)
|
|
57
|
+
yield* batchesOf(evaluateFinalJoinBatched(clauses, facts, signal));
|
|
58
|
+
else
|
|
59
|
+
yield* batchesOf(evaluateFinalJoinConcurrently(clauses, facts, signal));
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
yield* evaluateClauses(clauses, facts, signal);
|
|
63
|
+
}
|
|
64
|
+
async function* entityJoin(tuples, entity, value, signal) {
|
|
65
|
+
for await (const tuple of tuples) {
|
|
66
|
+
throwIfAborted(signal);
|
|
67
|
+
yield new Map([[entity, tuple.entity], [value, tuple.value]]);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function canScanFinalJoinConcurrently(clauses) {
|
|
71
|
+
if (clauses.length !== 3)
|
|
72
|
+
return false;
|
|
73
|
+
const first = clauses[0];
|
|
74
|
+
const final = clauses[2];
|
|
75
|
+
if (!first || !final || first.entity.kind !== "variable" || first.value.kind !== "constant")
|
|
76
|
+
return false;
|
|
77
|
+
if (final.entity.kind !== "variable" || final.value.kind !== "variable" || final.entity.name === final.value.name)
|
|
78
|
+
return false;
|
|
79
|
+
const finalEntityName = final.entity.name;
|
|
80
|
+
const finalValueName = final.value.name;
|
|
81
|
+
const prefix = clauses.slice(0, -1);
|
|
82
|
+
const finalEntityIsAlreadyBound = prefix.some(clause => clauseHasVariable(clause, finalEntityName));
|
|
83
|
+
const finalValueIsBound = prefix.some(clause => clauseHasVariable(clause, finalValueName));
|
|
84
|
+
return !finalEntityIsAlreadyBound && finalValueIsBound;
|
|
85
|
+
}
|
|
86
|
+
function clauseHasVariable(clause, name) {
|
|
87
|
+
return (clause.entity.kind === "variable" && clause.entity.name === name)
|
|
88
|
+
|| (clause.value.kind === "variable" && clause.value.name === name);
|
|
89
|
+
}
|
|
90
|
+
async function* evaluateFinalJoinConcurrently(clauses, facts, signal) {
|
|
91
|
+
const final = clauses[2];
|
|
92
|
+
if (!final)
|
|
93
|
+
return;
|
|
94
|
+
const prefix = bindingsOf(evaluateClauses(clauses.slice(0, -1), facts, signal))[Symbol.asyncIterator]();
|
|
95
|
+
let prefixDone = false;
|
|
96
|
+
try {
|
|
97
|
+
while (!prefixDone) {
|
|
98
|
+
const scans = [];
|
|
99
|
+
let prefixFailure;
|
|
100
|
+
let prefixFailed = false;
|
|
101
|
+
while (scans.length < MAX_CONCURRENT_FINAL_SCANS) {
|
|
102
|
+
let next;
|
|
103
|
+
try {
|
|
104
|
+
next = await prefix.next();
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
prefixFailure = error;
|
|
108
|
+
prefixFailed = true;
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
if (next.done) {
|
|
112
|
+
prefixDone = true;
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
const binding = next.value;
|
|
116
|
+
const lookup = lookupFor(final, binding);
|
|
117
|
+
scans.push(Promise.resolve().then(() => collectFinalMatches(facts.scan(lookup, signal), final, binding, signal)));
|
|
118
|
+
}
|
|
119
|
+
const settled = await Promise.allSettled(scans);
|
|
120
|
+
if (prefixFailed)
|
|
121
|
+
throw prefixFailure;
|
|
122
|
+
const failedScan = settled.find((result) => result.status === "rejected");
|
|
123
|
+
if (failedScan)
|
|
124
|
+
throw failedScan.reason;
|
|
125
|
+
for (const result of settled) {
|
|
126
|
+
if (result.status === "fulfilled") {
|
|
127
|
+
for (const binding of result.value)
|
|
128
|
+
yield binding;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
await prefix.return?.(undefined);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
async function* evaluateFinalJoinBatched(clauses, facts, signal) {
|
|
138
|
+
const final = clauses[2];
|
|
139
|
+
const scanValues = facts.scanValues;
|
|
140
|
+
if (!final || final.value.kind !== "variable" || !scanValues)
|
|
141
|
+
return;
|
|
142
|
+
const bindingsByValue = new Map();
|
|
143
|
+
const prefix = bindingsOf(evaluateClauses(clauses.slice(0, -1), facts, signal))[Symbol.asyncIterator]();
|
|
144
|
+
let prefixDone = false;
|
|
145
|
+
let bufferedBindings = 0;
|
|
146
|
+
const flush = async function* () {
|
|
147
|
+
if (bindingsByValue.size === 0)
|
|
148
|
+
return;
|
|
149
|
+
const values = [...bindingsByValue.values()].map(group => group.value);
|
|
150
|
+
for await (const tuple of scanValues.call(facts, { field: final.predicate, values }, signal)) {
|
|
151
|
+
throwIfAborted(signal);
|
|
152
|
+
const matches = bindingsByValue.get(valueKey(tuple.value))?.bindings;
|
|
153
|
+
if (!matches)
|
|
154
|
+
continue;
|
|
155
|
+
for (const binding of matches) {
|
|
156
|
+
const next = new Map(binding);
|
|
157
|
+
if (unify(final.entity, tuple.entity, next) && unify(final.value, tuple.value, next))
|
|
158
|
+
yield next;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
bindingsByValue.clear();
|
|
162
|
+
bufferedBindings = 0;
|
|
163
|
+
};
|
|
164
|
+
try {
|
|
165
|
+
while (!prefixDone) {
|
|
166
|
+
const next = await prefix.next();
|
|
167
|
+
if (next.done) {
|
|
168
|
+
prefixDone = true;
|
|
169
|
+
yield* flush();
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
const binding = next.value;
|
|
173
|
+
const value = binding.get(final.value.name);
|
|
174
|
+
if (value === undefined)
|
|
175
|
+
throw new Error(`final join value ${final.value.name} is not bound`);
|
|
176
|
+
const key = valueKey(value);
|
|
177
|
+
let group = bindingsByValue.get(key);
|
|
178
|
+
if (group === undefined) {
|
|
179
|
+
if (bindingsByValue.size === MAX_FINAL_JOIN_BINDINGS)
|
|
180
|
+
yield* flush();
|
|
181
|
+
group = { value, bindings: [] };
|
|
182
|
+
bindingsByValue.set(key, group);
|
|
183
|
+
}
|
|
184
|
+
group.bindings.push(binding);
|
|
185
|
+
bufferedBindings += 1;
|
|
186
|
+
if (bufferedBindings >= MAX_FINAL_JOIN_BINDINGS)
|
|
187
|
+
yield* flush();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
finally {
|
|
191
|
+
await prefix.return?.(undefined);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function valueKey(value) {
|
|
195
|
+
return JSON.stringify([value.type, value.value]);
|
|
196
|
+
}
|
|
197
|
+
async function collectFinalMatches(tuples, clause, binding, signal) {
|
|
198
|
+
const matches = [];
|
|
199
|
+
for await (const tuple of tuples) {
|
|
200
|
+
throwIfAborted(signal);
|
|
201
|
+
const nextBinding = new Map(binding);
|
|
202
|
+
if (!unify(clause.entity, tuple.entity, nextBinding))
|
|
203
|
+
continue;
|
|
204
|
+
if (!unify(clause.value, tuple.value, nextBinding))
|
|
205
|
+
continue;
|
|
206
|
+
matches.push(nextBinding);
|
|
207
|
+
}
|
|
208
|
+
return matches;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* The atoms joined left to right, over batches of bindings, in the order a nested loop would give
|
|
212
|
+
* them: each binding's matches in scan order, before the next binding's. An atom whose entity the
|
|
213
|
+
* bindings fix reads its field's index when the source has one worth reading, else scans per
|
|
214
|
+
* binding, a few at a time. Rows move between atoms as arrays, so a row costs no promise per atom.
|
|
215
|
+
*/
|
|
216
|
+
async function* evaluateClauses(clauses, facts, signal) {
|
|
217
|
+
let batches = start();
|
|
218
|
+
for (const clause of clauses)
|
|
219
|
+
batches = joinClause(clause, rebatch(batches), facts, signal);
|
|
220
|
+
yield* batches;
|
|
221
|
+
}
|
|
222
|
+
async function* start() {
|
|
223
|
+
yield [new Map()];
|
|
224
|
+
}
|
|
225
|
+
/** The bindings regrouped into the batches the next atom takes: a small one, then big ones. */
|
|
226
|
+
async function* rebatch(batches) {
|
|
227
|
+
let batch = [];
|
|
228
|
+
let size = FIRST_BATCH_BINDINGS;
|
|
229
|
+
for await (const bindings of batches) {
|
|
230
|
+
for (const binding of bindings) {
|
|
231
|
+
batch.push(binding);
|
|
232
|
+
if (batch.length === size) {
|
|
233
|
+
yield batch;
|
|
234
|
+
batch = [];
|
|
235
|
+
size = BATCH_BINDINGS;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (batch.length > 0)
|
|
240
|
+
yield batch;
|
|
241
|
+
}
|
|
242
|
+
async function* batchesOf(bindings) {
|
|
243
|
+
for await (const binding of bindings)
|
|
244
|
+
yield [binding];
|
|
245
|
+
}
|
|
246
|
+
async function* bindingsOf(batches) {
|
|
247
|
+
for await (const batch of batches)
|
|
248
|
+
yield* batch;
|
|
249
|
+
}
|
|
250
|
+
async function* joinClause(clause, batches, facts, signal) {
|
|
251
|
+
// The lookups by entity this atom has needed so far, this batch's included: the source reads the
|
|
252
|
+
// field whole once they cost more than that would.
|
|
253
|
+
let lookups = 0;
|
|
254
|
+
for await (const batch of batches) {
|
|
255
|
+
const entities = boundEntities(clause, batch);
|
|
256
|
+
lookups += entities === null ? 0 : new Set(entities).size;
|
|
257
|
+
yield* joinBatch(clause, batch, entities, lookups, facts, signal);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
async function* joinBatch(clause, batch, entities, lookups, facts, signal) {
|
|
261
|
+
throwIfAborted(signal);
|
|
262
|
+
const index = entities === null || facts.fieldIndex === undefined ? null : await facts.fieldIndex({ field: clause.predicate, lookups }, signal);
|
|
263
|
+
if (entities !== null && index !== null) {
|
|
264
|
+
yield probe(clause, batch, entities, index);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
for (let i = 0; i < batch.length; i += CONCURRENT_SCANS)
|
|
268
|
+
yield* scanChunk(clause, batch.slice(i, i + CONCURRENT_SCANS), facts, signal);
|
|
269
|
+
}
|
|
270
|
+
/** Each binding's entity for this atom, as a lookup would use it (null: not text, so nothing matches); null if the atom's entity is not a variable these bindings fix. */
|
|
271
|
+
function boundEntities(clause, batch) {
|
|
272
|
+
if (clause.entity.kind !== "variable")
|
|
273
|
+
return null;
|
|
274
|
+
const name = clause.entity.name;
|
|
275
|
+
const entities = [];
|
|
276
|
+
for (const binding of batch) {
|
|
277
|
+
const value = binding.get(name);
|
|
278
|
+
if (value === undefined)
|
|
279
|
+
return null;
|
|
280
|
+
entities.push(value.type === "string" ? value.value : null);
|
|
281
|
+
}
|
|
282
|
+
return entities;
|
|
283
|
+
}
|
|
284
|
+
function probe(clause, batch, entities, index) {
|
|
285
|
+
const out = [];
|
|
286
|
+
for (const [i, binding] of batch.entries()) {
|
|
287
|
+
const entity = entities[i];
|
|
288
|
+
const tuples = entity === null || entity === undefined ? undefined : index.get(entity);
|
|
289
|
+
if (tuples !== undefined)
|
|
290
|
+
extend(clause, binding, tuples, out);
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
}
|
|
294
|
+
async function* scanChunk(clause, chunk, facts, signal) {
|
|
295
|
+
const found = await Promise.all(chunk.map((binding) => tuplesOf(facts, lookupFor(clause, binding), signal)));
|
|
296
|
+
throwIfAborted(signal);
|
|
297
|
+
const out = [];
|
|
298
|
+
for (const [i, binding] of chunk.entries())
|
|
299
|
+
extend(clause, binding, found[i] ?? [], out);
|
|
300
|
+
yield out;
|
|
301
|
+
}
|
|
302
|
+
function tuplesOf(facts, lookup, signal) {
|
|
303
|
+
return facts.scanAll ? facts.scanAll(lookup, signal) : collect(facts.scan(lookup, signal));
|
|
304
|
+
}
|
|
305
|
+
async function collect(tuples) {
|
|
306
|
+
const all = [];
|
|
307
|
+
for await (const tuple of tuples)
|
|
308
|
+
all.push(tuple);
|
|
309
|
+
return all;
|
|
310
|
+
}
|
|
311
|
+
/** The binding extended by each tuple that unifies with the atom, in the tuples' order. */
|
|
312
|
+
function extend(clause, binding, tuples, out) {
|
|
313
|
+
for (const tuple of tuples) {
|
|
314
|
+
const next = new Map(binding);
|
|
315
|
+
if (unify(clause.entity, tuple.entity, next) && unify(clause.value, tuple.value, next))
|
|
316
|
+
out.push(next);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
function lookupFor(clause, binding) {
|
|
320
|
+
const lookup = {
|
|
321
|
+
field: clause.predicate,
|
|
322
|
+
};
|
|
323
|
+
const entity = resolveTerm(clause.entity, binding);
|
|
324
|
+
if (entity !== undefined)
|
|
325
|
+
lookup.entity = entity;
|
|
326
|
+
const value = resolveTerm(clause.value, binding);
|
|
327
|
+
if (value !== undefined)
|
|
328
|
+
lookup.value = value;
|
|
329
|
+
return lookup;
|
|
330
|
+
}
|
|
331
|
+
function resolveTerm(term, binding) {
|
|
332
|
+
switch (term.kind) {
|
|
333
|
+
case "constant":
|
|
334
|
+
return term.value;
|
|
335
|
+
case "variable":
|
|
336
|
+
return binding.get(term.name);
|
|
337
|
+
case "wildcard":
|
|
338
|
+
return undefined;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
function unify(term, value, binding) {
|
|
342
|
+
switch (term.kind) {
|
|
343
|
+
case "constant":
|
|
344
|
+
return sameDatalogValue(term.value, value);
|
|
345
|
+
case "wildcard":
|
|
346
|
+
return true;
|
|
347
|
+
case "variable": {
|
|
348
|
+
const existing = binding.get(term.name);
|
|
349
|
+
if (existing !== undefined)
|
|
350
|
+
return sameDatalogValue(existing, value);
|
|
351
|
+
binding.set(term.name, value);
|
|
352
|
+
return true;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
function evaluateBuiltin(name, left, right) {
|
|
357
|
+
switch (name) {
|
|
358
|
+
case "=":
|
|
359
|
+
case "eq":
|
|
360
|
+
return equalDatalogValues(left, right);
|
|
361
|
+
case "<":
|
|
362
|
+
case "lt":
|
|
363
|
+
case "before":
|
|
364
|
+
return ordered(left, right, (ordering) => ordering < 0);
|
|
365
|
+
case "<=":
|
|
366
|
+
case "lte":
|
|
367
|
+
return ordered(left, right, (ordering) => ordering <= 0);
|
|
368
|
+
case ">":
|
|
369
|
+
case "gt":
|
|
370
|
+
case "after":
|
|
371
|
+
return ordered(left, right, (ordering) => ordering > 0);
|
|
372
|
+
case ">=":
|
|
373
|
+
case "gte":
|
|
374
|
+
return ordered(left, right, (ordering) => ordering >= 0);
|
|
375
|
+
case "contains":
|
|
376
|
+
return stringPair(left, right, (value, part) => value.includes(part));
|
|
377
|
+
case "startsWith":
|
|
378
|
+
return stringPair(left, right, (value, prefix) => value.startsWith(prefix));
|
|
379
|
+
case "endsWith":
|
|
380
|
+
return stringPair(left, right, (value, suffix) => value.endsWith(suffix));
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
/** Whether two values have an order, and it holds: only comparisons order, so only they pay for it. */
|
|
384
|
+
function ordered(left, right, holds) {
|
|
385
|
+
const ordering = compareDatalogValues(left, right);
|
|
386
|
+
return ordering !== undefined && holds(ordering);
|
|
387
|
+
}
|
|
388
|
+
function stringPair(left, right, matches) {
|
|
389
|
+
return left.type === "string" && right.type === "string" && matches(left.value, right.value);
|
|
390
|
+
}
|
|
391
|
+
function throwIfAborted(signal) {
|
|
392
|
+
if (signal?.aborted) {
|
|
393
|
+
throw signal.reason instanceof Error ? signal.reason : new DOMException("Query was aborted", "AbortError");
|
|
394
|
+
}
|
|
395
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Uri } from "../domain/identifiers.js";
|
|
2
|
+
import type { BoundValue, DatalogValue } from "./value.js";
|
|
3
|
+
export type FactLookup = Readonly<{
|
|
4
|
+
field: Uri;
|
|
5
|
+
entity?: DatalogValue;
|
|
6
|
+
value?: DatalogValue;
|
|
7
|
+
}>;
|
|
8
|
+
/** One active fact, or one item of a list fact: its entity, as a reference, and its value, typed. */
|
|
9
|
+
export type FactTuple = Readonly<{
|
|
10
|
+
entity: BoundValue;
|
|
11
|
+
value: BoundValue;
|
|
12
|
+
}>;
|
|
13
|
+
export type FactValueSetLookup = Readonly<{
|
|
14
|
+
field: Uri;
|
|
15
|
+
values: readonly DatalogValue[];
|
|
16
|
+
}>;
|
|
17
|
+
/** Every entity's tuples in one field: its id, then the tuples a scan by that entity gives, in that order. */
|
|
18
|
+
export type FieldIndex = ReadonlyMap<string, readonly FactTuple[]>;
|
|
19
|
+
export interface FactSource {
|
|
20
|
+
scan(lookup: FactLookup, signal?: AbortSignal): AsyncIterable<FactTuple>;
|
|
21
|
+
scanAll?(lookup: FactLookup, signal?: AbortSignal): Promise<readonly FactTuple[]>;
|
|
22
|
+
fieldIndex?(lookup: Readonly<{
|
|
23
|
+
field: Uri;
|
|
24
|
+
lookups: number;
|
|
25
|
+
}>, signal?: AbortSignal): Promise<FieldIndex | null>;
|
|
26
|
+
scanValues?(lookup: FactValueSetLookup, signal?: AbortSignal): AsyncIterable<FactTuple>;
|
|
27
|
+
scanEntityJoin?(lookup: FactLookup & Readonly<{
|
|
28
|
+
value: DatalogValue;
|
|
29
|
+
}>, outputField: Uri, signal?: AbortSignal): AsyncIterable<FactTuple>;
|
|
30
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export type QueryFingerprint = Readonly<{
|
|
2
|
+
/** Short deterministic hash of the canonical query shape. */
|
|
3
|
+
id: string;
|
|
4
|
+
/** Canonical Datalog with literal constants replaced by `?`. */
|
|
5
|
+
datalog: string;
|
|
6
|
+
/** Cleaned representative concrete query text (capped in length). */
|
|
7
|
+
example: string;
|
|
8
|
+
}>;
|
|
9
|
+
/**
|
|
10
|
+
* Returns the canonical shape of a valid Datalog query, or null if the source does not parse.
|
|
11
|
+
*/
|
|
12
|
+
export declare function fingerprintDatalog(source: string): QueryFingerprint | null;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Canonical Datalog query fingerprinting: parses a query and replaces every literal constant with
|
|
2
|
+
// `?` so calls that differ only in their constants roll up into a single query shape.
|
|
3
|
+
import { parseDatalogQuery } from "./parser.js";
|
|
4
|
+
const BARE_PREDICATE = /^[a-z][A-Za-z0-9:_.-]*$/;
|
|
5
|
+
const INFIX_BUILTINS = new Set(["=", "<", "<=", ">", ">="]);
|
|
6
|
+
const MAX_EXAMPLE_LENGTH = 512;
|
|
7
|
+
function formatPredicate(predicate) {
|
|
8
|
+
return BARE_PREDICATE.test(predicate) ? predicate : `'${predicate.replace(/'/g, "\\'")}'`;
|
|
9
|
+
}
|
|
10
|
+
function formatTerm(term) {
|
|
11
|
+
switch (term.kind) {
|
|
12
|
+
case "variable": return term.name;
|
|
13
|
+
case "wildcard": return "_";
|
|
14
|
+
case "constant": return "?";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function formatFact(clause) {
|
|
18
|
+
return `${formatPredicate(clause.predicate)}(${formatTerm(clause.entity)}, ${formatTerm(clause.value)})`;
|
|
19
|
+
}
|
|
20
|
+
function formatBuiltin(clause) {
|
|
21
|
+
const left = formatTerm(clause.left);
|
|
22
|
+
const right = formatTerm(clause.right);
|
|
23
|
+
return INFIX_BUILTINS.has(clause.name) ? `${left} ${clause.name} ${right}` : `${clause.name}(${left}, ${right})`;
|
|
24
|
+
}
|
|
25
|
+
function fnv1a64Hex(input) {
|
|
26
|
+
let h = 0xcbf29ce484222325n;
|
|
27
|
+
const prime = 0x100000001b3n;
|
|
28
|
+
const mask = 0xffffffffffffffffn;
|
|
29
|
+
for (let i = 0; i < input.length; i++) {
|
|
30
|
+
h ^= BigInt(input.charCodeAt(i));
|
|
31
|
+
h = (h * prime) & mask;
|
|
32
|
+
}
|
|
33
|
+
return `q${h.toString(16).padStart(16, "0")}`;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Returns the canonical shape of a valid Datalog query, or null if the source does not parse.
|
|
37
|
+
*/
|
|
38
|
+
export function fingerprintDatalog(source) {
|
|
39
|
+
const parsed = parseDatalogQuery(source);
|
|
40
|
+
if (!parsed.ok)
|
|
41
|
+
return null;
|
|
42
|
+
const parts = [
|
|
43
|
+
...parsed.value.facts.map(formatFact),
|
|
44
|
+
...parsed.value.constraints.map(formatBuiltin),
|
|
45
|
+
];
|
|
46
|
+
const datalog = parts.join(", ");
|
|
47
|
+
const cleaned = source.trim().replace(/\s+/g, " ");
|
|
48
|
+
const example = cleaned.length <= MAX_EXAMPLE_LENGTH ? cleaned : `${cleaned.slice(0, MAX_EXAMPLE_LENGTH - 1)}…`;
|
|
49
|
+
return { id: fnv1a64Hex(datalog), datalog, example };
|
|
50
|
+
}
|