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.
Files changed (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +264 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +3 -0
  5. package/dist/cli.d.ts +15 -0
  6. package/dist/cli.js +256 -0
  7. package/dist/client.d.ts +152 -0
  8. package/dist/client.js +416 -0
  9. package/dist/cloudflare.d.ts +197 -0
  10. package/dist/cloudflare.js +159 -0
  11. package/dist/datalog/ast.d.ts +35 -0
  12. package/dist/datalog/ast.js +40 -0
  13. package/dist/datalog/evaluator.d.ts +14 -0
  14. package/dist/datalog/evaluator.js +395 -0
  15. package/dist/datalog/fact-source.d.ts +30 -0
  16. package/dist/datalog/fact-source.js +1 -0
  17. package/dist/datalog/fingerprint.d.ts +12 -0
  18. package/dist/datalog/fingerprint.js +50 -0
  19. package/dist/datalog/parser.d.ts +3 -0
  20. package/dist/datalog/parser.js +302 -0
  21. package/dist/datalog/value.d.ts +34 -0
  22. package/dist/datalog/value.js +104 -0
  23. package/dist/domain/date-validation.d.ts +2 -0
  24. package/dist/domain/date-validation.js +32 -0
  25. package/dist/domain/fact-value.d.ts +91 -0
  26. package/dist/domain/fact-value.js +167 -0
  27. package/dist/domain/fact.d.ts +14 -0
  28. package/dist/domain/fact.js +47 -0
  29. package/dist/domain/failure.d.ts +44 -0
  30. package/dist/domain/failure.js +30 -0
  31. package/dist/domain/graph-id.d.ts +7 -0
  32. package/dist/domain/graph-id.js +10 -0
  33. package/dist/domain/histogram.d.ts +29 -0
  34. package/dist/domain/histogram.js +48 -0
  35. package/dist/domain/identifiers.d.ts +26 -0
  36. package/dist/domain/identifiers.js +75 -0
  37. package/dist/domain/numbers.d.ts +12 -0
  38. package/dist/domain/numbers.js +77 -0
  39. package/dist/domain/projection.d.ts +252 -0
  40. package/dist/domain/projection.js +51 -0
  41. package/dist/domain/query-metrics.d.ts +31 -0
  42. package/dist/domain/query-metrics.js +35 -0
  43. package/dist/domain/read-token.d.ts +37 -0
  44. package/dist/domain/read-token.js +93 -0
  45. package/dist/domain/result.d.ts +22 -0
  46. package/dist/domain/result.js +16 -0
  47. package/dist/domain/schema-observation.d.ts +20 -0
  48. package/dist/domain/schema-observation.js +61 -0
  49. package/dist/domain/string-order.d.ts +2 -0
  50. package/dist/domain/string-order.js +15 -0
  51. package/dist/domain/vocabulary.d.ts +101 -0
  52. package/dist/domain/vocabulary.js +276 -0
  53. package/dist/index.d.ts +15 -0
  54. package/dist/index.js +14 -0
  55. package/dist/projection-config.d.ts +3 -0
  56. package/dist/projection-config.js +212 -0
  57. package/dist/server/access.d.ts +32 -0
  58. package/dist/server/access.js +117 -0
  59. package/dist/server/admin.d.ts +233 -0
  60. package/dist/server/admin.js +483 -0
  61. package/dist/server/authorization.d.ts +35 -0
  62. package/dist/server/authorization.js +76 -0
  63. package/dist/server/console-assets.d.ts +6 -0
  64. package/dist/server/console-assets.js +2 -0
  65. package/dist/server/console.d.ts +8 -0
  66. package/dist/server/console.js +301 -0
  67. package/dist/server/index.d.ts +122 -0
  68. package/dist/server/index.js +487 -0
  69. package/dist/server/mcp.d.ts +31 -0
  70. package/dist/server/mcp.js +169 -0
  71. package/dist/server/telemetry-do.d.ts +31 -0
  72. package/dist/server/telemetry-do.js +342 -0
  73. package/dist/server/telemetry.d.ts +27 -0
  74. package/dist/server/telemetry.js +191 -0
  75. package/dist/storage/constants.d.ts +20 -0
  76. package/dist/storage/constants.js +21 -0
  77. package/dist/storage/environment.d.ts +438 -0
  78. package/dist/storage/environment.js +145 -0
  79. package/dist/storage/facts.d.ts +41 -0
  80. package/dist/storage/facts.js +73 -0
  81. package/dist/storage/http.d.ts +55 -0
  82. package/dist/storage/http.js +169 -0
  83. package/dist/storage/keys.d.ts +50 -0
  84. package/dist/storage/keys.js +84 -0
  85. package/dist/storage/layout.d.ts +67 -0
  86. package/dist/storage/layout.js +134 -0
  87. package/dist/storage/log.d.ts +41 -0
  88. package/dist/storage/log.js +137 -0
  89. package/dist/storage/manifest.d.ts +26 -0
  90. package/dist/storage/manifest.js +206 -0
  91. package/dist/storage/operations.d.ts +303 -0
  92. package/dist/storage/operations.js +719 -0
  93. package/dist/storage/partition.d.ts +125 -0
  94. package/dist/storage/partition.js +816 -0
  95. package/dist/storage/projection.d.ts +72 -0
  96. package/dist/storage/projection.js +1349 -0
  97. package/dist/storage/root.d.ts +120 -0
  98. package/dist/storage/root.js +596 -0
  99. package/dist/storage/segment.d.ts +145 -0
  100. package/dist/storage/segment.js +451 -0
  101. package/dist/storage/shard.d.ts +82 -0
  102. package/dist/storage/shard.js +710 -0
  103. package/dist/storage/source.d.ts +60 -0
  104. package/dist/storage/source.js +199 -0
  105. package/dist/telemetry/model.d.ts +123 -0
  106. package/dist/telemetry/model.js +292 -0
  107. package/dist/version.d.ts +4 -0
  108. package/dist/version.js +6 -0
  109. package/package.json +82 -4
@@ -0,0 +1,719 @@
1
+ // The public operations: `transact`, `query` and `schema` (RFD0008, "The write path" and "Reads").
2
+ //
3
+ // A write is one call to one partition. A read is at the graph's watermark, from the index in R2,
4
+ // plus the caller's own writes above it from the partitions holding them: the read token names
5
+ // those partitions, and every answer carries the token to send next.
6
+ //
7
+ // Writes are routed by the graph's layout (RFD0011), which each isolate caches from the root for a
8
+ // few seconds: a write with a client request token goes to the token's home, one without to any
9
+ // partition. A partition that knows a newer layout than the Worker's answers that the token moved,
10
+ // with the layout, and the Worker sends the write on to the token's home in it.
11
+ import { parseFactDrafts } from "../domain/fact.js";
12
+ import { parseFactValue } from "../domain/fact-value.js";
13
+ import { isRecord } from "../domain/result.js";
14
+ import { parseGraphId } from "../domain/graph-id.js";
15
+ import { parseClientRequestToken } from "../domain/identifiers.js";
16
+ import { MAX_QUERY_MANY } from "../datalog/ast.js";
17
+ import { parseDatalogQuery } from "../datalog/parser.js";
18
+ import { evaluateDatalog, QueryResultLimitExceeded } from "../datalog/evaluator.js";
19
+ import { encodeReadToken, newReadToken, parseConsistency, parseMaxStalenessMs } from "../domain/read-token.js";
20
+ import { MAX_CLOCK_AHEAD_EPOCHS, MAX_QUERY_RESPONSE_BYTES, MAX_QUERY_RESULTS, MAX_READ_RESTARTS, MAX_TRANSACTION_BYTES, MAX_TRANSACTION_FACTS, QUERY_TIMEOUT_MS, SNAPSHOT_WAIT_MS, } from "./constants.js";
21
+ import { cacheOrigin, inBackground, MAX_PARTITIONS, partitionStub, rootStub, segmentStore, shardStub } from "./environment.js";
22
+ import { BUCKETS, bucketOf, canonicalValue, factsOf } from "./facts.js";
23
+ import { afterRead, afterReplay, afterWrite, decodeToken, epochOf, hash32, wallEpoch } from "./keys.js";
24
+ import { homeOf, isShardCount, newer, partitionCount, partitionLayout } from "./layout.js";
25
+ import { readManifest } from "./manifest.js";
26
+ import { ByteLru, emptyReadMetrics, readEavFacts, readHeader, schemaOf, segmentCacheStats, } from "./segment.js";
27
+ import { MAX_SCHEMA_FIELDS } from "../domain/schema-observation.js";
28
+ import { createSegmentFlight, SegmentFactSource, TupleBudgetExceeded } from "./source.js";
29
+ let isolate;
30
+ // Random values are not allowed at global scope, so the id is made on first use, inside a handler.
31
+ const isolateId = () => (isolate ??= crypto.randomUUID().slice(0, 8));
32
+ /** A refusal with its HTTP status; `retryable` says whether the same call may succeed later. */
33
+ export class GraphError extends Error {
34
+ status;
35
+ retryable;
36
+ constructor(status, message, retryable = false) {
37
+ super(message);
38
+ this.status = status;
39
+ this.retryable = retryable;
40
+ this.name = "GraphError";
41
+ }
42
+ }
43
+ /** How long an isolate routes a graph's writes by the layout it read, before reading it again. */
44
+ const LAYOUT_TTL_MS = 10_000;
45
+ const layouts = new Map();
46
+ /** The graph's layout, as this isolate cached it: the root's, read at most LAYOUT_TTL_MS ago, or a partition's newer one. Reading it makes the graph's first. */
47
+ export async function layoutFor(env, graph, fresh = false) {
48
+ const cached = layouts.get(graph);
49
+ if (!fresh && cached && Date.now() - cached.at < LAYOUT_TTL_MS)
50
+ return cached.layout;
51
+ const layout = await rootStub(env, graph).layout({ graph });
52
+ const next = cached === undefined ? layout : newer(cached.layout, layout);
53
+ layouts.set(graph, { layout: next, at: Date.now() });
54
+ return next;
55
+ }
56
+ function tookLayout(graph, layout, from) {
57
+ if (from.version <= layout.version)
58
+ return layout;
59
+ const next = { ...layout, version: from.version, eras: from.eras };
60
+ layouts.set(graph, { layout: next, at: layouts.get(graph)?.at ?? Date.now() });
61
+ return next;
62
+ }
63
+ /** Tests only: forget every cached layout, as a new isolate would. */
64
+ export function forgetLayouts() {
65
+ layouts.clear();
66
+ }
67
+ const overloadReports = new Map();
68
+ /** Tells the root a partition refused a call because it was overloaded, at most once a second per graph from an isolate. */
69
+ async function reportOverload(env, graph) {
70
+ const now = Date.now();
71
+ if (now - (overloadReports.get(graph) ?? 0) < 1_000)
72
+ return;
73
+ overloadReports.set(graph, now);
74
+ await rootStub(env, graph).overloaded({ graph }).catch(() => undefined);
75
+ }
76
+ function isOverloaded(error) {
77
+ return typeof error === "object" && error !== null && "overloaded" in error && error.overloaded === true;
78
+ }
79
+ const MAX_MOVES = 3;
80
+ export async function transact(env, graphInput, body) {
81
+ const graph = parseGraph(graphInput);
82
+ const facts = parseFacts(body.facts);
83
+ const bytes = new TextEncoder().encode(JSON.stringify(facts)).byteLength;
84
+ if (bytes > MAX_TRANSACTION_BYTES)
85
+ throw new GraphError(413, `a transaction cannot exceed ${MAX_TRANSACTION_BYTES} bytes`);
86
+ let layout = await layoutFor(env, graph);
87
+ const token = await readTokenFor(env, graph, body.readToken, layout);
88
+ if (epochOf(token.after) > wallEpoch(Date.now()) + MAX_CLOCK_AHEAD_EPOCHS)
89
+ throw new GraphError(400, "read token clock is ahead of the graph");
90
+ let tokenHash = null;
91
+ if (body.clientRequestToken !== undefined) {
92
+ const parsed = parseClientRequestToken(body.clientRequestToken);
93
+ if (!parsed.ok)
94
+ throw new GraphError(400, parsed.error.message);
95
+ tokenHash = await sha256(`${graph}\u0000${parsed.value}`);
96
+ }
97
+ const payloadHash = tokenHash === null ? "" : await sha256(canonicalFacts(facts));
98
+ const route = (l) => (tokenHash === null ? Math.floor(Math.random() * partitionCount(l)) : homeOf(hash32(tokenHash), partitionCount(l)));
99
+ let partition = route(layout);
100
+ let result;
101
+ for (let attempt = 0;; attempt++) {
102
+ try {
103
+ result = await partitionStub(env, graph, partition).append({
104
+ graph, partition, layout: partitionLayout(layout), facts, tokenHash, payloadHash, session: token.session, after: token.after, bytes,
105
+ });
106
+ }
107
+ catch (error) {
108
+ if (!isOverloaded(error))
109
+ throw error;
110
+ await reportOverload(env, graph);
111
+ // The call never reached the partition: one without a token may go to another.
112
+ if (tokenHash === null && attempt === 0 && partitionCount(layout) > 1) {
113
+ partition = (partition + 1 + Math.floor(Math.random() * (partitionCount(layout) - 1))) % partitionCount(layout);
114
+ continue;
115
+ }
116
+ throw new GraphError(503, "the graph's partitions are overloaded and it is adding more; retry with the same client request token", true);
117
+ }
118
+ if (result.kind !== "moved")
119
+ break;
120
+ if (attempt >= MAX_MOVES)
121
+ throw new GraphError(503, "the graph's layout is changing; retry with the same client request token", true);
122
+ layout = tookLayout(graph, layout, result.layout);
123
+ partition = route(layout);
124
+ }
125
+ if (result.kind === "conflict")
126
+ throw new GraphError(409, "client request token was used with different facts");
127
+ if (result.kind === "replayed" && !result.sameSession) {
128
+ // Another session's write: the caller's reads find it in no tail of theirs, so it is answered
129
+ // once the watermark covers it. Until then the caller may retry with the same token and facts.
130
+ const manifest = await manifestAt(env, graph, epochOf(result.key.ts), "the write is stored but not yet indexed; retry with the same client request token and facts");
131
+ return { txId: result.txId, key: result.key, replayed: true, readToken: encodeReadToken(afterReplay(token, result.key, manifest?.watermark ?? 0)) };
132
+ }
133
+ return { txId: result.txId, key: result.key, replayed: result.kind === "replayed", readToken: encodeReadToken(afterWrite(token, result.key)) };
134
+ }
135
+ /** The graph's manifest once its watermark has reached `epoch`, read again every 100 ms for up to SNAPSHOT_WAIT_MS. */
136
+ async function manifestAt(env, graph, epoch, timeout) {
137
+ const t0 = Date.now();
138
+ let manifest = await readManifest(env, graph, false);
139
+ let nudged = false;
140
+ while ((manifest?.watermark ?? 0) < epoch) {
141
+ if (Date.now() - t0 > SNAPSHOT_WAIT_MS)
142
+ throw new GraphError(503, timeout, true);
143
+ if (!nudged) {
144
+ nudged = true;
145
+ // Wake index shards immediately so snapshot reads do not wait out a lazy flushMs (e.g. 60–300 s).
146
+ void rootStub(env, graph).ensureIndexing({ graph, immediate: true }).catch(() => undefined);
147
+ }
148
+ await new Promise((resolve) => setTimeout(resolve, 100));
149
+ manifest = await readManifest(env, graph, true);
150
+ }
151
+ return manifest;
152
+ }
153
+ /**
154
+ * What a read sees: the manifest at the latest watermark and, for "own-writes" (the default), the
155
+ * caller's writes above it, read from the partitions its token names. "snapshot" instead waits
156
+ * until the watermark has passed the caller's writes. A partition that trimmed rows above the
157
+ * watermark sends the read back for a newer manifest (rule trimmedTailsRestartReads).
158
+ *
159
+ * A manifest older than the token's watermark, which an isolate can hold for up to 500 ms after
160
+ * another served the caller a newer one, is read again: the token stopped naming the partitions
161
+ * whose writes that newer watermark covers. R2 is strongly consistent, so the read returns one at
162
+ * least as new, unless the graph went back, as a deleted and recreated one does.
163
+ */
164
+ async function readView(env, graph, body, timings) {
165
+ const parsedConsistency = parseConsistency(body.consistency);
166
+ if (!parsedConsistency.ok)
167
+ throw new GraphError(400, parsedConsistency.error.message);
168
+ const parsedStaleness = parseMaxStalenessMs(body.maxStalenessMs);
169
+ if (!parsedStaleness.ok)
170
+ throw new GraphError(400, parsedStaleness.error.message);
171
+ const consistency = parsedConsistency.value;
172
+ const maxStalenessMs = parsedStaleness.value;
173
+ const token = await readTokenFor(env, graph, body.readToken, null);
174
+ const needs = epochOf(token.after);
175
+ let fresh = false;
176
+ for (;;) {
177
+ const t0 = Date.now();
178
+ let manifest = await readManifest(env, graph, fresh, maxStalenessMs);
179
+ if ((manifest?.watermark ?? 0) < token.watermark)
180
+ manifest = await readManifest(env, graph, true);
181
+ if (consistency === "snapshot" && token.after > 0 && (manifest?.watermark ?? 0) < needs) {
182
+ manifest = await manifestAt(env, graph, needs, "the graph's watermark has not reached your writes yet");
183
+ timings.waitedMs += Date.now() - t0;
184
+ }
185
+ const watermark = manifest?.watermark ?? 0;
186
+ timings.manifestMs += Date.now() - t0;
187
+ const t1 = Date.now();
188
+ const asking = needs > watermark ? token.partitions : [];
189
+ const tails = await Promise.all(asking.map(async (p) => ({ p, tail: await partitionStub(env, graph, p).sessionTail({ session: token.session, watermark }) })));
190
+ timings.tailMs += Date.now() - t1;
191
+ if (tails.some(({ tail }) => tail.floor > watermark)) {
192
+ if (++timings.restarts > MAX_READ_RESTARTS)
193
+ throw new GraphError(503, "the graph's index is moving faster than this read", true);
194
+ fresh = true;
195
+ continue;
196
+ }
197
+ timings.tailTxs = tails.reduce((n, { tail }) => n + tail.txs.length, 0);
198
+ return {
199
+ manifest, watermark, token, consistency,
200
+ tail: tails.flatMap(({ tail }) => tail.txs.flatMap(factsOf)),
201
+ stillAbove: tails.filter(({ tail }) => tail.txs.length > 0).map(({ p }) => p),
202
+ };
203
+ }
204
+ }
205
+ function nextReadToken(view) {
206
+ return encodeReadToken(afterRead(view.token, view.watermark, view.consistency === "snapshot" ? [] : view.stillAbove));
207
+ }
208
+ /**
209
+ * Per-isolate immutable query result cache, keyed by (graph, watermark, limit, query).
210
+ * Only populated when `view.tail.length === 0` and `view.watermark > 0` — the graph at a
211
+ * published watermark is strictly immutable, and `readToken` is never cached across callers.
212
+ */
213
+ const QUERY_CACHE_BYTES = 8 * 2 ** 20;
214
+ const QUERY_COLO_CACHE_SECONDS = 86_400;
215
+ /** Marks colo query-cache entries written by this version so hits skip redundant deep FactValue re-validation. */
216
+ const QUERY_CACHE_VERSION_HEADER = "x-fatedb-query-cache";
217
+ const QUERY_CACHE_VERSION = "2";
218
+ let queryCache = new ByteLru(QUERY_CACHE_BYTES);
219
+ /** Tests only: clear the per-isolate watermark query cache. */
220
+ export function clearQueryCache() {
221
+ queryCache = new ByteLru(QUERY_CACHE_BYTES);
222
+ }
223
+ function coloQueryCache() {
224
+ return typeof caches !== "undefined" && caches.default ? caches.default : null;
225
+ }
226
+ async function queryCacheUrl(origin, graph, watermark, limit, normalizedQuery) {
227
+ const hash = await sha256(normalizedQuery);
228
+ return `${origin}/_queries/${encodeURIComponent(graph)}/${watermark}/${limit === undefined ? "all" : limit}/${hash}`;
229
+ }
230
+ /** The colo cache entry for a result: `{"rows":…,"truncated":…}`, which holds the rows' JSON as the answer carries it. */
231
+ function cachedQueryText(rowsJson, truncated) {
232
+ return `{"rows":${rowsJson},"truncated":${truncated ? "true" : "false"}}`;
233
+ }
234
+ /** Zero-allocation structural guard for FactValue objects serialized into our own colo query cache. */
235
+ function isTrustedFactValue(value) {
236
+ if (!isRecord(value))
237
+ return false;
238
+ switch (value["type"]) {
239
+ case "null":
240
+ return true;
241
+ case "text":
242
+ case "number":
243
+ case "decimal":
244
+ case "reference":
245
+ case "date":
246
+ case "date_time":
247
+ return typeof value["value"] === "string";
248
+ case "boolean":
249
+ return typeof value["value"] === "boolean";
250
+ case "bytes":
251
+ return Array.isArray(value["value"]);
252
+ case "list":
253
+ return Array.isArray(value["value"]) && value["value"].every(isTrustedFactValue);
254
+ case "map": {
255
+ const entries = value["value"];
256
+ if (!isRecord(entries))
257
+ return false;
258
+ for (const k in entries) {
259
+ if (!isTrustedFactValue(entries[k]))
260
+ return false;
261
+ }
262
+ return true;
263
+ }
264
+ default:
265
+ return false;
266
+ }
267
+ }
268
+ function isTrustedQueryRow(item) {
269
+ if (!isRecord(item))
270
+ return false;
271
+ for (const k in item) {
272
+ if (!isTrustedFactValue(item[k]))
273
+ return false;
274
+ }
275
+ return true;
276
+ }
277
+ function isTrustedQueryRows(rows) {
278
+ if (!Array.isArray(rows))
279
+ return false;
280
+ for (let i = 0; i < rows.length; i++) {
281
+ if (!isTrustedQueryRow(rows[i]))
282
+ return false;
283
+ }
284
+ return true;
285
+ }
286
+ /**
287
+ * Parses a colo query-cache entry written by this instance without re-running full FactValue
288
+ * regex/date/decimal parsing or cloning every row object.
289
+ */
290
+ function parseTrustedCachedQuery(text) {
291
+ const input = JSON.parse(text);
292
+ if (!isRecord(input) || typeof input["truncated"] !== "boolean" || !isTrustedQueryRows(input["rows"]))
293
+ return null;
294
+ const rows = input["rows"];
295
+ const truncated = input["truncated"];
296
+ const prefix = '{"rows":', suffix = `,"truncated":${truncated ? "true" : "false"}}`;
297
+ const rowsJson = text.startsWith(prefix) && text.endsWith(suffix) ? text.slice(prefix.length, text.length - suffix.length) : JSON.stringify(rows);
298
+ return { cached: { rows, truncated, rowsLength: rowsJson.length }, rowsJson };
299
+ }
300
+ /** A colo cache entry's result, and its rows' JSON, which an entry this instance wrote holds as the answer carries it. */
301
+ function parseCachedQuery(text) {
302
+ const input = JSON.parse(text);
303
+ if (!isRecord(input) || !Array.isArray(input["rows"]) || typeof input["truncated"] !== "boolean")
304
+ return null;
305
+ const rows = [];
306
+ for (const item of input["rows"]) {
307
+ if (!isRecord(item))
308
+ return null;
309
+ const row = {};
310
+ for (const [k, v] of Object.entries(item)) {
311
+ const parsed = parseFactValue(v);
312
+ if (!parsed.ok)
313
+ return null;
314
+ row[k] = parsed.value;
315
+ }
316
+ rows.push(row);
317
+ }
318
+ const truncated = input["truncated"];
319
+ const prefix = '{"rows":', suffix = `,"truncated":${truncated ? "true" : "false"}}`;
320
+ const rowsJson = text.startsWith(prefix) && text.endsWith(suffix) ? text.slice(prefix.length, text.length - suffix.length) : JSON.stringify(rows);
321
+ return { cached: { rows, truncated, rowsLength: rowsJson.length }, rowsJson };
322
+ }
323
+ async function readCachedQuery(env, localKey, graph, watermark, limit, normalizedQuery) {
324
+ const fromIsolate = queryCache.get(localKey);
325
+ if (fromIsolate !== undefined)
326
+ return { cached: fromIsolate, tier: "isolate" };
327
+ const origin = cacheOrigin(env);
328
+ const cache = coloQueryCache();
329
+ if (origin === null || cache === null)
330
+ return null;
331
+ try {
332
+ const hit = await cache.match(await queryCacheUrl(origin, graph, watermark, limit, normalizedQuery));
333
+ if (hit === undefined)
334
+ return null;
335
+ const text = await hit.text();
336
+ const parsed = hit.headers.get(QUERY_CACHE_VERSION_HEADER) === QUERY_CACHE_VERSION
337
+ ? parseTrustedCachedQuery(text)
338
+ : parseCachedQuery(text);
339
+ if (parsed === null)
340
+ return null;
341
+ queryCache.set(localKey, parsed.cached, text.length);
342
+ return { cached: parsed.cached, tier: "colo", rowsJson: parsed.rowsJson };
343
+ }
344
+ catch {
345
+ return null;
346
+ }
347
+ }
348
+ /** Caches a result in the isolate now, and in the colo after the answer. */
349
+ function writeCachedQuery(env, localKey, graph, watermark, limit, normalizedQuery, result, rowsJson) {
350
+ const serialized = cachedQueryText(rowsJson, result.truncated);
351
+ queryCache.set(localKey, result, serialized.length);
352
+ const origin = cacheOrigin(env);
353
+ const cache = coloQueryCache();
354
+ if (origin === null || cache === null || serialized.length > MAX_QUERY_RESPONSE_BYTES)
355
+ return;
356
+ inBackground(async () => cache.put(await queryCacheUrl(origin, graph, watermark, limit, normalizedQuery), new Response(serialized, {
357
+ headers: {
358
+ "content-type": "application/json",
359
+ "cache-control": `public, max-age=${QUERY_COLO_CACHE_SECONDS}, immutable`,
360
+ [QUERY_CACHE_VERSION_HEADER]: QUERY_CACHE_VERSION,
361
+ },
362
+ })));
363
+ }
364
+ /**
365
+ * An answer's JSON, `JSON.stringify(answer)` exactly, from its rows' JSON: the rows are the bulk of
366
+ * an answer, and are serialized at most once.
367
+ */
368
+ export function answerJson(rowsJson, answer) {
369
+ return `{"rows":${rowsJson},"watermark":${JSON.stringify(answer.watermark)},"consistency":${JSON.stringify(answer.consistency)}`
370
+ + `,"readToken":${JSON.stringify(answer.readToken)},"metrics":${JSON.stringify(answer.metrics)}${answer.truncated === true ? ',"truncated":true' : ""}}`;
371
+ }
372
+ /** `answerJson(rowsJson, answer).length`, from the rows' JSON's length alone. */
373
+ export function answerLength(rowsLength, answer) {
374
+ return answerJson("", answer).length + rowsLength;
375
+ }
376
+ /**
377
+ * Runs a query. With `limit`, the answer is the first `limit` rows and says whether there were
378
+ * more (`truncated`), instead of failing past MAX_QUERY_RESULTS: the console and agents read so.
379
+ */
380
+ export async function query(env, graphInput, body, options = {}) {
381
+ return (await serveQuery(env, graphInput, body, options)).answer;
382
+ }
383
+ /** A binding as a row: each variable's fact value. Variables start with a capital letter, so none is a name objects inherit. */
384
+ function rowOf(binding) {
385
+ const row = {};
386
+ for (const [variable, value] of binding)
387
+ row[variable] = value.fact;
388
+ return row;
389
+ }
390
+ /** Runs one parsed Datalog query against an already-resolved read view. */
391
+ async function evaluateOneQuery(env, graph, parsed, normalizedQuery, view, timings, started, limit, flight) {
392
+ const fields = new Set(parsed.facts.map((clause) => clause.predicate));
393
+ const cacheable = view.tail.length === 0 && view.manifest !== null && view.watermark > 0;
394
+ const localCacheKey = cacheable ? `${graph}\u0000${view.watermark}\u0000${limit === undefined ? "" : limit}\u0000${normalizedQuery}` : "";
395
+ const t2 = Date.now();
396
+ if (cacheable) {
397
+ const hit = await readCachedQuery(env, localCacheKey, graph, view.watermark, limit, normalizedQuery);
398
+ if (hit !== null) {
399
+ const sourceMetrics = {
400
+ ...emptyReadMetrics(),
401
+ cacheHits: hit.tier === "isolate" ? 1 : 0,
402
+ edgeHits: hit.tier === "colo" ? 1 : 0,
403
+ scans: 0,
404
+ tuplesRead: 0,
405
+ segmentsTouched: 0,
406
+ };
407
+ const metrics = {
408
+ ...timings, evaluationMs: Date.now() - t2, totalMs: Date.now() - started, source: sourceMetrics, isolate: isolateId(), cache: segmentCacheStats(),
409
+ };
410
+ return {
411
+ rows: hit.cached.rows,
412
+ truncated: hit.cached.truncated,
413
+ rowsJson: hit.tier === "colo" ? hit.rowsJson : null,
414
+ rowsLength: hit.cached.rowsLength,
415
+ metrics,
416
+ };
417
+ }
418
+ }
419
+ const sourceMetrics = { ...emptyReadMetrics(), scans: 0, tuplesRead: 0, segmentsTouched: 0 };
420
+ const tail = view.tail.filter((f) => fields.has(f.field));
421
+ const source = new SegmentFactSource(segmentStore(env), view.manifest?.buckets ?? {}, view.watermark, tail, sourceMetrics, flight);
422
+ const controller = new AbortController();
423
+ const timer = setTimeout(() => controller.abort(new DOMException("query time budget exceeded", "TimeoutError")), QUERY_TIMEOUT_MS);
424
+ const rows = [];
425
+ let truncated = false;
426
+ try {
427
+ for await (const binding of evaluateDatalog(parsed, source, { maxResults: MAX_QUERY_RESULTS, signal: controller.signal })) {
428
+ if (rows.length === limit) {
429
+ truncated = true;
430
+ break;
431
+ }
432
+ rows.push(rowOf(binding));
433
+ }
434
+ }
435
+ catch (error) {
436
+ if (error instanceof QueryResultLimitExceeded || error instanceof TupleBudgetExceeded)
437
+ throw new GraphError(413, error.message);
438
+ if (controller.signal.aborted)
439
+ throw new GraphError(504, "query time budget exceeded", true);
440
+ throw error;
441
+ }
442
+ finally {
443
+ clearTimeout(timer);
444
+ }
445
+ const metrics = {
446
+ ...timings, evaluationMs: Date.now() - t2, totalMs: Date.now() - started, source: sourceMetrics, isolate: isolateId(), cache: segmentCacheStats(),
447
+ };
448
+ const rowsJson = JSON.stringify(rows);
449
+ if (cacheable)
450
+ writeCachedQuery(env, localCacheKey, graph, view.watermark, limit, normalizedQuery, { rows, truncated, rowsLength: rowsJson.length }, rowsJson);
451
+ return { rows, truncated, rowsJson, rowsLength: rowsJson.length, metrics };
452
+ }
453
+ /** `query`, with its rows' JSON when it made it. */
454
+ export async function serveQuery(env, graphInput, body, options = {}) {
455
+ const started = Date.now();
456
+ const graph = parseGraph(graphInput);
457
+ if (typeof body.query !== "string")
458
+ throw new GraphError(400, "query must be a Datalog string");
459
+ const parsed = parseDatalogQuery(body.query);
460
+ if (!parsed.ok)
461
+ throw new GraphError(400, parsed.error.message);
462
+ const timings = { manifestMs: 0, tailMs: 0, tailTxs: 0, restarts: 0, waitedMs: 0 };
463
+ const view = await readView(env, graph, body, timings);
464
+ const limit = options.limit === undefined ? undefined : Math.min(Math.max(1, Math.floor(options.limit)), MAX_QUERY_RESULTS);
465
+ const evaluated = await evaluateOneQuery(env, graph, parsed.value, body.query.trim(), view, timings, started, limit);
466
+ const answer = {
467
+ rows: evaluated.rows,
468
+ watermark: view.watermark,
469
+ consistency: view.consistency,
470
+ readToken: nextReadToken(view),
471
+ metrics: evaluated.metrics,
472
+ ...(evaluated.truncated ? { truncated: true } : {}),
473
+ };
474
+ if (answerLength(evaluated.rowsLength, answer) > MAX_QUERY_RESPONSE_BYTES)
475
+ throw new GraphError(413, "query response byte budget exceeded");
476
+ return { answer, rowsJson: evaluated.rowsJson };
477
+ }
478
+ /**
479
+ * Runs 1 to MAX_QUERY_MANY Datalog queries against one pinned watermark and read view, sharing a
480
+ * single manifest read, session tail read, and in-flight segment header/block reads.
481
+ */
482
+ export async function queryMany(env, graphInput, body, options = {}) {
483
+ const started = Date.now();
484
+ const graph = parseGraph(graphInput);
485
+ if (!Array.isArray(body.queries) || body.queries.length === 0 || body.queries.length > MAX_QUERY_MANY) {
486
+ throw new GraphError(400, `queries must be an array of 1 to ${MAX_QUERY_MANY} Datalog strings`);
487
+ }
488
+ const parsedQueries = [];
489
+ for (let i = 0; i < body.queries.length; i++) {
490
+ const raw = body.queries[i];
491
+ if (typeof raw !== "string")
492
+ throw new GraphError(400, `queries[${i}] must be a Datalog string`);
493
+ const parsed = parseDatalogQuery(raw);
494
+ if (!parsed.ok)
495
+ throw new GraphError(400, `queries[${i}]: ${parsed.error.message}`);
496
+ parsedQueries.push({ query: parsed.value, normalized: raw.trim() });
497
+ }
498
+ const timings = { manifestMs: 0, tailMs: 0, tailTxs: 0, restarts: 0, waitedMs: 0 };
499
+ const view = await readView(env, graph, body, timings);
500
+ const limit = options.limit === undefined ? undefined : Math.min(Math.max(1, Math.floor(options.limit)), MAX_QUERY_RESULTS);
501
+ const flight = createSegmentFlight();
502
+ const tEval = Date.now();
503
+ const zeroTimings = { manifestMs: 0, tailMs: 0, tailTxs: 0, restarts: 0, waitedMs: 0 };
504
+ const evaluated = await Promise.all(parsedQueries.map(({ query: q, normalized }) => evaluateOneQuery(env, graph, q, normalized, view, zeroTimings, tEval, limit, flight)));
505
+ const aggregateSource = { ...emptyReadMetrics(), scans: 0, tuplesRead: 0, segmentsTouched: 0 };
506
+ let totalRowsBytes = 0;
507
+ const answers = evaluated.map((item) => {
508
+ totalRowsBytes += item.rowsLength;
509
+ aggregateSource.scans += item.metrics.source.scans;
510
+ aggregateSource.tuplesRead += item.metrics.source.tuplesRead;
511
+ aggregateSource.segmentsTouched += item.metrics.source.segmentsTouched;
512
+ aggregateSource.blocksRead += item.metrics.source.blocksRead;
513
+ aggregateSource.bytesRead += item.metrics.source.bytesRead;
514
+ aggregateSource.r2Gets += item.metrics.source.r2Gets;
515
+ aggregateSource.edgeHits += item.metrics.source.edgeHits;
516
+ aggregateSource.cacheHits += item.metrics.source.cacheHits;
517
+ return {
518
+ rows: item.rows,
519
+ metrics: item.metrics,
520
+ ...(item.truncated ? { truncated: true } : {}),
521
+ };
522
+ });
523
+ const metrics = {
524
+ ...timings,
525
+ evaluationMs: Date.now() - tEval,
526
+ totalMs: Date.now() - started,
527
+ source: aggregateSource,
528
+ isolate: isolateId(),
529
+ cache: segmentCacheStats(),
530
+ };
531
+ if (totalRowsBytes > MAX_QUERY_RESPONSE_BYTES * 4)
532
+ throw new GraphError(413, "queryMany response byte budget exceeded");
533
+ return {
534
+ answers,
535
+ watermark: view.watermark,
536
+ consistency: view.consistency,
537
+ readToken: nextReadToken(view),
538
+ metrics,
539
+ };
540
+ }
541
+ /** Segments whose headers, or facts, a schema read fetches at once. */
542
+ const SCHEMA_READS = 32;
543
+ /**
544
+ * The graph's fields and the value tags of their active facts, at the watermark plus the caller's
545
+ * own writes: exactly the (field, tag) pairs some active fact holds (tests/storage/schema.test.ts
546
+ * checks the counting below on every short history, in every segmentation).
547
+ *
548
+ * It is read from the tag counts in segment headers. A bucket's segments cover disjoint epochs, so
549
+ * a tag is surely active if, in some segment, more of its tuples end asserted than all later
550
+ * segments retract. A segment reaching above the watermark is read, to count only what is below
551
+ * it. A tag the counts leave open, as many retractions as assertions, is decided by reading the
552
+ * field's active facts, within the query tuple budget.
553
+ */
554
+ export async function schema(env, graphInput, body) {
555
+ const graph = parseGraph(graphInput);
556
+ const view = await readView(env, graph, body, { manifestMs: 0, tailMs: 0, tailTxs: 0, restarts: 0, waitedMs: 0 });
557
+ const store = segmentStore(env);
558
+ const metrics = { ...emptyReadMetrics(), scans: 0, tuplesRead: 0, segmentsTouched: 0 };
559
+ const bucketEntries = Object.entries(view.manifest?.buckets ?? {}).map(([bucketKey, refs]) => ({
560
+ bucket: Number(bucketKey),
561
+ refs: refs.filter((ref) => ref.minEpoch <= view.watermark).sort((a, b) => a.minEpoch - b.minEpoch),
562
+ }));
563
+ const uniqueRefs = [...new Map(bucketEntries.flatMap((entry) => entry.refs).map((ref) => [ref.name, ref])).values()];
564
+ const counted = new Map();
565
+ for (let i = 0; i < uniqueRefs.length; i += SCHEMA_READS) {
566
+ await Promise.all(uniqueRefs.slice(i, i + SCHEMA_READS).map(async (ref) => {
567
+ counted.set(ref.name, ref.maxEpoch <= view.watermark
568
+ ? (await readHeader(store, ref, metrics)).schema
569
+ : schemaOf((await readEavFacts(env.INDEX, ref)).filter((f) => epochOf(f.ts) <= view.watermark)));
570
+ }));
571
+ }
572
+ // Each field's counts, oldest first: a field is in one bucket, so its segments' order is the bucket's.
573
+ // Packed multi-bucket L0 segments appear in multiple buckets, so filter each bucket's pass to its own fields.
574
+ const layers = new Map();
575
+ const add = (counts, onlyBucket) => {
576
+ for (const [field, tags] of Object.entries(counts)) {
577
+ if (onlyBucket !== undefined && bucketOf(field, BUCKETS) !== onlyBucket)
578
+ continue;
579
+ layers.set(field, [...(layers.get(field) ?? []), tags]);
580
+ }
581
+ };
582
+ for (const { bucket, refs } of bucketEntries) {
583
+ for (const ref of refs) {
584
+ const counts = counted.get(ref.name);
585
+ if (counts !== undefined)
586
+ add(counts, bucket);
587
+ }
588
+ }
589
+ add(schemaOf(view.tail));
590
+ const source = new SegmentFactSource(store, view.manifest?.buckets ?? {}, view.watermark, view.tail, metrics);
591
+ const fields = [];
592
+ for (const [field, counts] of [...layers].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
593
+ const { active, open } = tagsOf(counts);
594
+ if (open.size > 0) {
595
+ try {
596
+ for (const f of await source.activeFacts(field))
597
+ if (open.has(f.value.type))
598
+ active.add(f.value.type);
599
+ }
600
+ catch (error) {
601
+ if (error instanceof TupleBudgetExceeded)
602
+ throw new GraphError(413, `schema cannot tell the value tags of ${field} apart within the query tuple budget`);
603
+ throw error;
604
+ }
605
+ }
606
+ if (active.size > 0)
607
+ fields.push({ field, valueTags: [...active].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)) });
608
+ if (fields.length > MAX_SCHEMA_FIELDS)
609
+ throw new GraphError(413, `the graph has more than ${MAX_SCHEMA_FIELDS} fields`);
610
+ }
611
+ return { fields, watermark: view.watermark, consistency: view.consistency, readToken: nextReadToken(view) };
612
+ }
613
+ const VALUE_TAG_LIST = [
614
+ "null", "text", "number", "decimal", "boolean", "bytes", "reference", "date", "date_time", "list", "map",
615
+ ];
616
+ /** The tags the counts show active, and those they leave open. `layers` are oldest first. */
617
+ export function tagsOf(layers) {
618
+ const active = new Set(), asserted = new Set();
619
+ const retractedLater = new Map();
620
+ for (let j = layers.length - 1; j >= 0; j--) {
621
+ const layer = layers[j];
622
+ if (layer === undefined)
623
+ continue;
624
+ const entries = [];
625
+ for (const tag of VALUE_TAG_LIST) {
626
+ const counts = layer[tag];
627
+ if (counts !== undefined)
628
+ entries.push([tag, counts]);
629
+ }
630
+ for (const [tag, counts] of entries) {
631
+ if (counts.asserted > 0)
632
+ asserted.add(tag);
633
+ // Each later retraction ends at most one of this segment's asserted tuples.
634
+ if (counts.asserted > (retractedLater.get(tag) ?? 0))
635
+ active.add(tag);
636
+ }
637
+ for (const [tag, counts] of entries)
638
+ retractedLater.set(tag, (retractedLater.get(tag) ?? 0) + counts.retracted);
639
+ }
640
+ return { active, open: new Set([...asserted].filter((tag) => !active.has(tag))) };
641
+ }
642
+ /**
643
+ * Makes a graph before its first write, so it is listed and has a layout: the instance's initial
644
+ * partitions and one index shard, or the counts asked for, for a graph whose load is known ahead.
645
+ * A graph that exists keeps its layout, and `created` is false.
646
+ */
647
+ export async function createGraph(env, graphInput, body) {
648
+ const graph = parseGraph(graphInput);
649
+ const partitions = body.partitions ?? undefined, shards = body.shards ?? undefined;
650
+ if (partitions !== undefined && !(typeof partitions === "number" && Number.isSafeInteger(partitions) && partitions >= 1 && partitions <= MAX_PARTITIONS)) {
651
+ throw new GraphError(400, `partitions must be a whole number from 1 to ${MAX_PARTITIONS}`);
652
+ }
653
+ if (shards !== undefined && !(typeof shards === "number" && isShardCount(shards)))
654
+ throw new GraphError(400, `shards must be a power of two up to ${BUCKETS}`);
655
+ const { layout, created } = await rootStub(env, graph).create({
656
+ graph, ...(partitions === undefined ? {} : { partitions }), ...(shards === undefined ? {} : { shards }),
657
+ });
658
+ return { graph, created, partitions: partitionCount(layout), shards: layout.shards.length };
659
+ }
660
+ /** The root, every index shard and every partition. A graph never written or created has no layout, and no shards or partitions here. */
661
+ export async function status(env, graphInput) {
662
+ const graph = parseGraph(graphInput);
663
+ const root = await rootStub(env, graph).status();
664
+ const layout = root.layout;
665
+ const [shardStatus, parts] = layout === null ? [[], []] : await Promise.all([
666
+ Promise.all(layout.shards.map((leaf) => shardStub(env, graph, leaf.prefix).status())),
667
+ Promise.all(Array.from({ length: partitionCount(layout) }, (_, p) => partitionStub(env, graph, p).stats())),
668
+ ]);
669
+ const now = Date.now();
670
+ return { graph, now, nowEpoch: wallEpoch(now), root, shards: shardStatus, partitions: parts };
671
+ }
672
+ /** The root's part of the status alone: cheap enough to poll during a load point. */
673
+ export async function rootStatus(env, graphInput) {
674
+ return rootStub(env, parseGraph(graphInput)).status();
675
+ }
676
+ function parseGraph(input) {
677
+ const graph = parseGraphId(input);
678
+ if (!graph.ok)
679
+ throw new GraphError(400, graph.error.message);
680
+ return graph.value;
681
+ }
682
+ function parseFacts(input) {
683
+ if (Array.isArray(input) && input.length > MAX_TRANSACTION_FACTS)
684
+ throw new GraphError(413, `a transaction cannot contain more than ${MAX_TRANSACTION_FACTS} facts`);
685
+ const facts = parseFactDrafts(input);
686
+ if (!facts.ok)
687
+ throw new GraphError(400, facts.error.message);
688
+ return facts.value;
689
+ }
690
+ /**
691
+ * The caller's read token, naming only partitions the graph has. The layout is read only when the
692
+ * token names partitions, so a read of a graph nobody wrote makes no layout; a cached layout that
693
+ * is too old to have a partition the token names is read again.
694
+ */
695
+ async function readTokenFor(env, graph, input, cached) {
696
+ if (input === undefined || input === null)
697
+ return newReadToken();
698
+ const shape = decodeToken(input, Infinity);
699
+ if (!shape.ok)
700
+ throw new GraphError(400, shape.error.message);
701
+ if (shape.value.partitions.length === 0)
702
+ return shape.value;
703
+ let layout = cached ?? (await layoutFor(env, graph));
704
+ let parsed = decodeToken(input, partitionCount(layout));
705
+ if (!parsed.ok) {
706
+ layout = await layoutFor(env, graph, true);
707
+ parsed = decodeToken(input, partitionCount(layout));
708
+ }
709
+ if (!parsed.ok)
710
+ throw new GraphError(400, parsed.error.message);
711
+ return parsed.value;
712
+ }
713
+ function canonicalFacts(facts) {
714
+ return JSON.stringify(facts.map((f) => [f.source, f.entity, f.field, canonicalValue(f.value), f.retraction]));
715
+ }
716
+ async function sha256(text) {
717
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
718
+ return [...new Uint8Array(digest).slice(0, 16)].map((b) => b.toString(16).padStart(2, "0")).join("");
719
+ }