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,145 @@
1
+ // What storage needs from the Worker that hosts it, its Durable Object RPC contracts,
2
+ // and where a graph's objects live. Kept free of imports from DO implementation files
3
+ // so storage modules form a strict acyclic dependency graph.
4
+ import { waitUntil } from "cloudflare:workers";
5
+ const HINTS = new Map([
6
+ ["wnam", "wnam"],
7
+ ["enam", "enam"],
8
+ ["sam", "sam"],
9
+ ["weur", "weur"],
10
+ ["eeur", "eeur"],
11
+ ["apac", "apac"],
12
+ ["oc", "oc"],
13
+ ["afr", "afr"],
14
+ ["me", "me"],
15
+ ]);
16
+ /** The most partitions a graph grows to: what one root notifies, and every index shard reads, each second. */
17
+ export const MAX_PARTITIONS = 512;
18
+ const INITIAL_PARTITIONS = 1;
19
+ const GROW_ABOVE_CALLS = 1_000;
20
+ const DEFAULT_TOKEN_WINDOW_MS = 5 * 60_000;
21
+ const DEFAULT_INDEX_CHECK_MS = 30_000;
22
+ const DEFAULT_FLUSH_MS = 2_000;
23
+ const DEFAULT_COMMIT_LINGER_MS = 10;
24
+ function integerSetting(input, fallback, name, min, max) {
25
+ if (input === undefined || input === "")
26
+ return fallback;
27
+ const value = Number(input);
28
+ if (!Number.isSafeInteger(value) || value < min || value > max)
29
+ throw new Error(`${name} must be an integer from ${min} to ${max}`);
30
+ return value;
31
+ }
32
+ export function settings(env) {
33
+ const rawHint = env.LOCATION_HINT ?? "";
34
+ let locationHint;
35
+ if (rawHint !== "") {
36
+ const parsed = HINTS.get(rawHint);
37
+ if (parsed === undefined)
38
+ throw new Error("LOCATION_HINT must be a Durable Object location hint");
39
+ locationHint = parsed;
40
+ }
41
+ return {
42
+ locationHint,
43
+ tokenWindowMs: integerSetting(env.TOKEN_WINDOW_MS, DEFAULT_TOKEN_WINDOW_MS, "TOKEN_WINDOW_MS", 1_000, 24 * 60 * 60_000),
44
+ indexCheckMs: integerSetting(env.INDEX_CHECK_MS, DEFAULT_INDEX_CHECK_MS, "INDEX_CHECK_MS", 1_000, 60 * 60_000),
45
+ initialPartitions: integerSetting(env.INITIAL_PARTITIONS, INITIAL_PARTITIONS, "INITIAL_PARTITIONS", 1, MAX_PARTITIONS),
46
+ growAboveCalls: integerSetting(env.GROW_ABOVE_CALLS, GROW_ABOVE_CALLS, "GROW_ABOVE_CALLS", 1, 100_000),
47
+ flushMs: integerSetting(env.FLUSH_MS, DEFAULT_FLUSH_MS, "FLUSH_MS", 100, 300_000),
48
+ commitLingerMs: integerSetting(env.COMMIT_LINGER_MS, DEFAULT_COMMIT_LINGER_MS, "COMMIT_LINGER_MS", 0, 50),
49
+ };
50
+ }
51
+ function options(env) {
52
+ const hint = settings(env).locationHint;
53
+ return hint === undefined ? {} : { locationHint: hint };
54
+ }
55
+ export function partitionStub(env, graph, partition) {
56
+ return env.PARTITIONS.get(env.PARTITIONS.idFromName(`${graph}/partition/${partition}`), options(env));
57
+ }
58
+ /** A shard's object is named by its leaf's prefix alone (layout.ts). */
59
+ export function shardStub(env, graph, prefix) {
60
+ return env.SHARDS.get(env.SHARDS.idFromName(`${graph}/shard/${prefix}`), options(env));
61
+ }
62
+ export function rootStub(env, graph) {
63
+ return env.ROOTS.get(env.ROOTS.idFromName(`${graph}/root`), options(env));
64
+ }
65
+ export function projectionStub(env, graph, projection) {
66
+ if (env.PROJECTIONS === undefined)
67
+ throw new Error("PROJECTIONS Durable Object namespace is not bound");
68
+ return env.PROJECTIONS.get(env.PROJECTIONS.idFromName(`${graph}/projection/${projection}`), options(env));
69
+ }
70
+ export function telemetryStub(env) {
71
+ if (env.TELEMETRY === undefined)
72
+ return null;
73
+ return env.TELEMETRY.get(env.TELEMETRY.idFromName("instance"), options(env));
74
+ }
75
+ export function segmentStore(env) {
76
+ const origin = env.CACHE_ORIGIN ?? "";
77
+ return {
78
+ r2: env.INDEX,
79
+ colo: origin === "" ? null : { key: (name, offset, length) => `${origin}/_segments/${encodeURIComponent(name)}?o=${offset}&l=${length}`, fillLater: inBackground },
80
+ };
81
+ }
82
+ export function manifestKey(graph) {
83
+ return `graphs/${graph}/manifest.json`;
84
+ }
85
+ export function cacheOrigin(env) {
86
+ const origin = env.CACHE_ORIGIN ?? "";
87
+ return origin === "" ? null : origin;
88
+ }
89
+ // Work a read starts and does not wait for: filling the colo cache, reading a newer manifest than
90
+ // the one it served. The request's context keeps it running after the answer (`waitUntil`), and a
91
+ // failure changes nothing: the next read does the same work again.
92
+ const pending = new Set();
93
+ /** Runs `work` after the answer, best effort. */
94
+ export function inBackground(work) {
95
+ const task = bestEffort(work);
96
+ pending.add(task);
97
+ keepAlive(forget(task));
98
+ }
99
+ async function bestEffort(work) {
100
+ try {
101
+ await work();
102
+ }
103
+ catch {
104
+ // A cache fill or a refresh that failed: the next read does it again.
105
+ }
106
+ }
107
+ async function forget(task) {
108
+ await task;
109
+ pending.delete(task);
110
+ }
111
+ function keepAlive(task) {
112
+ try {
113
+ waitUntil(task);
114
+ }
115
+ catch {
116
+ // Outside a request there is no context to extend: the isolate runs the work while it lives.
117
+ }
118
+ }
119
+ /** Tests only: waits for the background work this isolate has started, and what that started. */
120
+ export async function backgroundSettled() {
121
+ if (pending.size === 0)
122
+ return;
123
+ await Promise.all([...pending]);
124
+ await backgroundSettled();
125
+ }
126
+ /**
127
+ * Emit a live runtime protocol event to `env.SPOCK_TRACE` during conformance tests.
128
+ * Call sites guard on `env.SPOCK_TRACE !== undefined`, so production pays zero allocation or I/O.
129
+ */
130
+ export async function traceSpock(env, graph, action, state) {
131
+ const binding = env.SPOCK_TRACE;
132
+ const origin = cacheOrigin(env);
133
+ if (binding === undefined || origin === null)
134
+ return;
135
+ try {
136
+ await binding.fetch(`${origin}/emit`, {
137
+ method: "POST",
138
+ headers: { "content-type": "application/json" },
139
+ body: JSON.stringify({ session: `runtime:${graph}`, line: { action, state } }),
140
+ });
141
+ }
142
+ catch {
143
+ // Trace collection is test-only and must never alter runtime execution.
144
+ }
145
+ }
@@ -0,0 +1,41 @@
1
+ import type { FactDraft } from "../domain/fact.js";
2
+ import type { TransactionId } from "../domain/identifiers.js";
3
+ import type { FactValue } from "../domain/fact-value.js";
4
+ import { type Key } from "./keys.js";
5
+ /** One fact of one transaction, at the transaction's key; `index` is its place in the transaction. */
6
+ export type IndexedFact = Readonly<{
7
+ ts: number;
8
+ partition: number;
9
+ offset: number;
10
+ index: number;
11
+ source: string;
12
+ entity: string;
13
+ field: string;
14
+ value: FactValue;
15
+ retraction: boolean;
16
+ }>;
17
+ /** A stored transaction, as partitions hand it to the indexer and to tail reads. */
18
+ export type StoredTx = Readonly<{
19
+ txId: TransactionId;
20
+ key: Key;
21
+ session: string;
22
+ facts: readonly FactDraft[];
23
+ }>;
24
+ export declare function factsOf(tx: StoredTx): IndexedFact[];
25
+ export declare function compareFacts(a: IndexedFact, b: IndexedFact): number;
26
+ /** Facts sorted the way segments keep them: by field, entity, value, source, then key. */
27
+ export declare function compareForSegment(a: IndexedFact, b: IndexedFact): number;
28
+ /** A value's identity: map keys in sorted order, so equal maps are one tuple. */
29
+ export declare function canonicalValue(value: FactValue): string;
30
+ /** A tuple's identity, for telling its writes apart in memory: each part after its length, so no two tuples share one. */
31
+ export declare function tupleKey(f: Pick<IndexedFact, "source" | "entity" | "field" | "value">): string;
32
+ /** Each tuple's last write in key order, retractions included. */
33
+ export declare function lastWrites(facts: Iterable<IndexedFact>): IndexedFact[];
34
+ /** The active facts among these writes: each tuple whose last write in key order asserts it. */
35
+ export declare function resolveActive(facts: Iterable<IndexedFact>): IndexedFact[];
36
+ /** Field buckets per graph: a bucket's segments belong to one index shard, bucket mod shards. */
37
+ export declare const BUCKETS = 64;
38
+ export declare function bucketOf(field: string, buckets: number): number;
39
+ export type WireFact = [number, number, number, number, string, string, string, FactValue, 0 | 1];
40
+ export declare function toWire(f: IndexedFact): WireFact;
41
+ export declare function fromWire(w: unknown): IndexedFact;
@@ -0,0 +1,73 @@
1
+ // Facts as the index holds them, and how a read turns them into the graph's state.
2
+ //
3
+ // A tuple (source, entity, field, value) is active when its last write in key order asserts it
4
+ // (RFD0008, "Retraction and limits"): retracting an inactive tuple does nothing.
5
+ import { hash32 } from "./keys.js";
6
+ export function factsOf(tx) {
7
+ return tx.facts.map((f, index) => ({
8
+ ts: tx.key.ts, partition: tx.key.partition, offset: tx.key.offset, index,
9
+ source: f.source, entity: f.entity, field: f.field, value: f.value, retraction: f.retraction,
10
+ }));
11
+ }
12
+ export function compareFacts(a, b) {
13
+ return a.ts - b.ts || a.partition - b.partition || a.offset - b.offset || a.index - b.index;
14
+ }
15
+ /** Facts sorted the way segments keep them: by field, entity, value, source, then key. */
16
+ export function compareForSegment(a, b) {
17
+ return cmp(a.field, b.field) || cmp(a.entity, b.entity) || cmp(canonicalValue(a.value), canonicalValue(b.value)) || cmp(a.source, b.source) || compareFacts(a, b);
18
+ }
19
+ function cmp(a, b) {
20
+ return a < b ? -1 : a > b ? 1 : 0;
21
+ }
22
+ /** A value's identity: map keys in sorted order, so equal maps are one tuple. */
23
+ export function canonicalValue(value) {
24
+ return JSON.stringify(canonical(value));
25
+ }
26
+ function canonical(value) {
27
+ switch (value.type) {
28
+ case "list": return { type: "list", value: value.value.map(canonical) };
29
+ case "map": return { type: "map", value: Object.entries(value.value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([k, v]) => [k, canonical(v)]) };
30
+ case "null": return { type: "null" };
31
+ default: return { type: value.type, value: value.value };
32
+ }
33
+ }
34
+ /** A tuple's identity, for telling its writes apart in memory: each part after its length, so no two tuples share one. */
35
+ export function tupleKey(f) {
36
+ return `${f.source.length}:${f.source}${f.entity.length}:${f.entity}${f.field.length}:${f.field}${canonicalValue(f.value)}`;
37
+ }
38
+ /** Each tuple's last write in key order, retractions included. */
39
+ export function lastWrites(facts) {
40
+ const last = new Map();
41
+ for (const f of facts) {
42
+ const k = tupleKey(f), prior = last.get(k);
43
+ if (prior === undefined || compareFacts(prior, f) < 0)
44
+ last.set(k, f);
45
+ }
46
+ return [...last.values()];
47
+ }
48
+ /** The active facts among these writes: each tuple whose last write in key order asserts it. */
49
+ export function resolveActive(facts) {
50
+ return lastWrites(facts).filter((f) => !f.retraction);
51
+ }
52
+ /** Field buckets per graph: a bucket's segments belong to one index shard, bucket mod shards. */
53
+ export const BUCKETS = 64;
54
+ export function bucketOf(field, buckets) {
55
+ return hash32(field) % buckets;
56
+ }
57
+ export function toWire(f) {
58
+ return [f.ts, f.partition, f.offset, f.index, f.source, f.entity, f.field, f.value, f.retraction ? 1 : 0];
59
+ }
60
+ function isFactValueShape(value) {
61
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
62
+ }
63
+ export function fromWire(w) {
64
+ if (!Array.isArray(w) || w.length !== 9)
65
+ throw new Error("segment fact is not a 9-element array");
66
+ const [ts, partition, offset, index, source, entity, field, value, retraction] = w;
67
+ if (typeof ts !== "number" || typeof partition !== "number" || typeof offset !== "number" || typeof index !== "number"
68
+ || !Number.isSafeInteger(ts) || !Number.isSafeInteger(partition) || !Number.isSafeInteger(offset) || !Number.isSafeInteger(index)
69
+ || typeof source !== "string" || typeof entity !== "string" || typeof field !== "string" || !isFactValueShape(value)) {
70
+ throw new Error("segment fact has invalid fields");
71
+ }
72
+ return { ts, partition, offset, index, source, entity, field, value, retraction: retraction === 1 };
73
+ }
@@ -0,0 +1,55 @@
1
+ import { type ReadFailure } from "../domain/failure.js";
2
+ import type { Consistency } from "../domain/read-token.js";
3
+ import { type ParseError, type Result } from "../domain/result.js";
4
+ import type { StorageEnv } from "./environment.js";
5
+ import { type QueryAnswer, type QueryManyAnswer } from "./operations.js";
6
+ /** Answers a graph route, or undefined when `request` is for none. */
7
+ export declare function handleGraphRequest(request: Request, env: StorageEnv): Promise<Response | undefined>;
8
+ /** Runs an operation and answers with its result, or with the failure as `graphFailure` describes it. */
9
+ export declare function respond<T>(run: () => Promise<T>, operation?: "read" | "write"): Promise<Response>;
10
+ /** A query as the in-process client sends it: the body the query route reads, without its encoding. */
11
+ export type InProcessQueryBody = Readonly<{
12
+ query: string;
13
+ readToken: string;
14
+ consistency?: Consistency;
15
+ maxStalenessMs?: number;
16
+ }>;
17
+ /** A `queryMany` batch as the in-process client sends it. */
18
+ export type InProcessQueryManyBody = Readonly<{
19
+ queries: readonly string[];
20
+ readToken: string;
21
+ consistency?: Consistency;
22
+ maxStalenessMs?: number;
23
+ }>;
24
+ /**
25
+ * The query route, for the instance's own Worker: the same refusals and answer, without encoding
26
+ * the request and the answer as JSON and parsing them back. A failure is what the route's status
27
+ * and message mean to the client (`httpFailure`), so both paths answer alike.
28
+ */
29
+ export declare function queryInProcess(env: StorageEnv, graph: string, body: InProcessQueryBody): Promise<Result<QueryAnswer, ReadFailure>>;
30
+ /** The `query-many` route, in process: shares one manifest read and skips JSON round-tripping. */
31
+ export declare function queryManyInProcess(env: StorageEnv, graph: string, body: InProcessQueryManyBody): Promise<Result<QueryManyAnswer, ReadFailure>>;
32
+ export type GraphFailure = Readonly<{
33
+ status: number;
34
+ message: string;
35
+ retryable: boolean;
36
+ }>;
37
+ /**
38
+ * How a failed operation is answered. A refusal as itself; a layout out of range as 400; anything
39
+ * else as a retryable 503 that says no more than that storage failed, since a write may or may not
40
+ * be stored.
41
+ */
42
+ export declare function graphFailure(error: unknown, operation: "read" | "write"): GraphFailure;
43
+ export type JsonBody = Readonly<{
44
+ ok: true;
45
+ value: unknown;
46
+ }> | Readonly<{
47
+ ok: false;
48
+ status: 400 | 413;
49
+ error: ParseError;
50
+ }>;
51
+ /** Reads a JSON body of at most `maxBytes`, cancelling a longer one unread, and always releases the reader. */
52
+ export declare function readJsonBody(request: Request, maxBytes: number): Promise<JsonBody>;
53
+ export declare function jsonResponse(body: unknown, status?: number, extraHeaders?: HeadersInit): Response;
54
+ /** A JSON response from text already serialized. */
55
+ export declare function jsonTextResponse(text: string, status?: number, extraHeaders?: HeadersInit): Response;
@@ -0,0 +1,169 @@
1
+ // The graph's HTTP routes, for the Worker that hosts storage:
2
+ //
3
+ // POST /v1/graphs/:id/transactions { facts, clientRequestToken?, readToken? }
4
+ // → { txId, key, replayed, readToken }
5
+ // POST /v1/graphs/:id/query { query, readToken?, consistency?: "own-writes" | "snapshot" }
6
+ // → { rows, watermark, consistency, readToken, metrics }
7
+ // POST /v1/graphs/:id/schema { readToken?, consistency? }
8
+ // → { fields: [{ field, valueTags }], watermark, consistency, readToken }
9
+ // GET /v1/graphs/:id/status → the root, every index shard and every partition
10
+ // PUT /v1/graphs/:id { partitions?, shards? }
11
+ // → { graph, created, partitions, shards }: makes the graph before its first write
12
+ //
13
+ // Callers pass the readToken of their last answer to read their own writes.
14
+ import { forRead, httpFailure } from "../domain/failure.js";
15
+ import { err, isRecord, ok } from "../domain/result.js";
16
+ import { MAX_REQUEST_BYTES } from "./constants.js";
17
+ import { answerJson, createGraph, GraphError, queryMany, schema, serveQuery, status, transact, } from "./operations.js";
18
+ const ROUTE = /^\/v1\/graphs\/([^/]+)(?:\/(transactions|query|query-many|schema|status))?$/;
19
+ /** Answers a graph route, or undefined when `request` is for none. */
20
+ export async function handleGraphRequest(request, env) {
21
+ const match = ROUTE.exec(new URL(request.url).pathname);
22
+ const rawGraph = match?.[1];
23
+ if (match === null || rawGraph === undefined)
24
+ return undefined;
25
+ let graph;
26
+ try {
27
+ graph = decodeURIComponent(rawGraph);
28
+ }
29
+ catch {
30
+ return jsonResponse({ error: "graph id is not valid percent-encoding", retryable: false }, 400);
31
+ }
32
+ const action = match[2] ?? "graph";
33
+ if (action === "status") {
34
+ if (request.method !== "GET")
35
+ return jsonResponse({ error: "method not allowed", retryable: false }, 405, { allow: "GET" });
36
+ return respond(() => status(env, graph));
37
+ }
38
+ const method = action === "graph" ? "PUT" : "POST";
39
+ if (request.method !== method)
40
+ return jsonResponse({ error: "method not allowed", retryable: false }, 405, { allow: method });
41
+ const body = await readJsonBody(request, MAX_REQUEST_BYTES);
42
+ if (!body.ok)
43
+ return jsonResponse({ error: body.error.message, retryable: false }, body.status);
44
+ if (!isRecord(body.value))
45
+ return jsonResponse({ error: "request body must be a JSON object", retryable: false }, 400);
46
+ const input = body.value;
47
+ if (action === "graph")
48
+ return respond(() => createGraph(env, graph, input));
49
+ if (action === "transactions")
50
+ return respond(() => transact(env, graph, input), "write");
51
+ if (action === "query") {
52
+ try {
53
+ const { answer, rowsJson } = await serveQuery(env, graph, input);
54
+ return jsonTextResponse(answerJson(rowsJson ?? JSON.stringify(answer.rows), answer));
55
+ }
56
+ catch (error) {
57
+ return failureResponse(error, "read");
58
+ }
59
+ }
60
+ if (action === "query-many")
61
+ return respond(() => queryMany(env, graph, input));
62
+ return respond(() => schema(env, graph, input));
63
+ }
64
+ /** Runs an operation and answers with its result, or with the failure as `graphFailure` describes it. */
65
+ export async function respond(run, operation = "read") {
66
+ try {
67
+ return jsonResponse(await run());
68
+ }
69
+ catch (error) {
70
+ return failureResponse(error, operation);
71
+ }
72
+ }
73
+ function failureResponse(error, operation) {
74
+ const failure = graphFailure(error, operation);
75
+ return jsonResponse({ error: failure.message, retryable: failure.retryable }, failure.status, failure.retryable ? { "retry-after": "1" } : undefined);
76
+ }
77
+ /**
78
+ * The query route, for the instance's own Worker: the same refusals and answer, without encoding
79
+ * the request and the answer as JSON and parsing them back. A failure is what the route's status
80
+ * and message mean to the client (`httpFailure`), so both paths answer alike.
81
+ */
82
+ export async function queryInProcess(env, graph, body) {
83
+ const bytes = new TextEncoder().encode(JSON.stringify(body)).byteLength;
84
+ if (bytes > MAX_REQUEST_BYTES)
85
+ return err(forRead(httpFailure("read", 413, `request body exceeds the ${MAX_REQUEST_BYTES}-byte limit`, null)));
86
+ try {
87
+ const served = await serveQuery(env, graph, body);
88
+ return ok(served.answer);
89
+ }
90
+ catch (error) {
91
+ const failure = graphFailure(error, "read");
92
+ return err(forRead(httpFailure("read", failure.status, failure.message, failure.retryable ? "1" : null)));
93
+ }
94
+ }
95
+ /** The `query-many` route, in process: shares one manifest read and skips JSON round-tripping. */
96
+ export async function queryManyInProcess(env, graph, body) {
97
+ const bytes = new TextEncoder().encode(JSON.stringify(body)).byteLength;
98
+ if (bytes > MAX_REQUEST_BYTES)
99
+ return err(forRead(httpFailure("read", 413, `request body exceeds the ${MAX_REQUEST_BYTES}-byte limit`, null)));
100
+ try {
101
+ return ok(await queryMany(env, graph, body));
102
+ }
103
+ catch (error) {
104
+ const failure = graphFailure(error, "read");
105
+ return err(forRead(httpFailure("read", failure.status, failure.message, failure.retryable ? "1" : null)));
106
+ }
107
+ }
108
+ /**
109
+ * How a failed operation is answered. A refusal as itself; a layout out of range as 400; anything
110
+ * else as a retryable 503 that says no more than that storage failed, since a write may or may not
111
+ * be stored.
112
+ */
113
+ export function graphFailure(error, operation) {
114
+ if (error instanceof GraphError)
115
+ return { status: error.status, message: error.message, retryable: error.retryable };
116
+ if (error instanceof RangeError)
117
+ return { status: 400, message: error.message, retryable: false };
118
+ console.error(JSON.stringify({ event: "graph.failed", error: error instanceof Error ? error.message : String(error) }));
119
+ const message = operation === "write"
120
+ ? "storage failed; the write may have been stored: replay it with the same client request token and facts"
121
+ : "storage failed; try the read again";
122
+ return { status: 503, message, retryable: true };
123
+ }
124
+ /** Reads a JSON body of at most `maxBytes`, cancelling a longer one unread, and always releases the reader. */
125
+ export async function readJsonBody(request, maxBytes) {
126
+ if (request.body === null)
127
+ return { ok: false, status: 400, error: { path: "body", message: "request body is required" } };
128
+ const reader = request.body.getReader();
129
+ const decoder = new TextDecoder();
130
+ let text = "";
131
+ let size = 0;
132
+ try {
133
+ while (true) {
134
+ const chunk = await reader.read();
135
+ if (chunk.done)
136
+ break;
137
+ size += chunk.value.byteLength;
138
+ if (size > maxBytes) {
139
+ await reader.cancel();
140
+ return { ok: false, status: 413, error: { path: "body", message: `request body exceeds the ${maxBytes}-byte limit` } };
141
+ }
142
+ text += decoder.decode(chunk.value, { stream: true });
143
+ }
144
+ text += decoder.decode();
145
+ }
146
+ catch {
147
+ return { ok: false, status: 400, error: { path: "body", message: "could not read the request body" } };
148
+ }
149
+ finally {
150
+ reader.releaseLock();
151
+ }
152
+ try {
153
+ const parsed = JSON.parse(text);
154
+ return { ok: true, value: parsed };
155
+ }
156
+ catch {
157
+ return { ok: false, status: 400, error: { path: "body", message: "request body must be valid JSON" } };
158
+ }
159
+ }
160
+ export function jsonResponse(body, status = 200, extraHeaders) {
161
+ return jsonTextResponse(JSON.stringify(body), status, extraHeaders);
162
+ }
163
+ /** A JSON response from text already serialized. */
164
+ export function jsonTextResponse(text, status = 200, extraHeaders) {
165
+ const headers = new Headers(extraHeaders);
166
+ headers.set("content-type", "application/json; charset=utf-8");
167
+ headers.set("cache-control", "no-store");
168
+ return new Response(text, { status, headers });
169
+ }
@@ -0,0 +1,50 @@
1
+ import { type ReadTokenState } from "../domain/read-token.js";
2
+ import { type ParseResult } from "../domain/result.js";
3
+ export declare const EPOCH_MS = 50;
4
+ export declare const COUNTER = 65536;
5
+ export type Ts = number;
6
+ export declare function epochOf(ts: Ts): number;
7
+ export declare function firstTsOf(epoch: number): Ts;
8
+ /** The highest ts in an epoch: a reader at watermark w has seen everything up to lastTsOf(w). */
9
+ export declare function lastTsOf(epoch: number): Ts;
10
+ export declare function wallEpoch(nowMs: number): number;
11
+ export declare function epochEndMs(epoch: number): number;
12
+ export type Key = Readonly<{
13
+ ts: Ts;
14
+ partition: number;
15
+ offset: number;
16
+ }>;
17
+ export declare function compareKeys(a: Key, b: Key): number;
18
+ /**
19
+ * The ts a partition stamps a write with: not below its last stamp (offsets then order its writes),
20
+ * not below its clock, after what the caller has seen (rule dependentWritesAfter), and after the
21
+ * last epoch it handed off as closed (rule closedEpochsStayClosed).
22
+ */
23
+ export declare function stampTs(input: Readonly<{
24
+ lastTs: Ts;
25
+ nowMs: number;
26
+ after: Ts;
27
+ closedEpoch: number;
28
+ }>): Ts;
29
+ /**
30
+ * A read token sent to a graph of `partitionCount` partitions: well formed, and naming only its
31
+ * partitions. A token from another graph, or from before a resize, is refused, not trusted.
32
+ */
33
+ export declare function decodeToken(input: unknown, partitionCount: number): ParseResult<ReadTokenState>;
34
+ /** After a write at `key`: the session has seen it, and its partition holds a write of the session above any watermark read. */
35
+ export declare function afterWrite(token: ReadTokenState, key: Key): ReadTokenState;
36
+ /**
37
+ * After a read at `watermark`: the session has seen everything up to it, reads at it or later from
38
+ * now on, and keeps only the partitions still holding its writes above it. The watermark is the
39
+ * read's own. Below the token's, it is a graph that went back, as a deleted and recreated one does,
40
+ * and the token follows the graph.
41
+ */
42
+ export declare function afterRead(token: ReadTokenState, watermark: number, stillAbove: readonly number[]): ReadTokenState;
43
+ /**
44
+ * After another session's write at `key` was replayed to this one, once the watermark had covered
45
+ * it: the session has seen the write and reads at `watermark` or later. The write's partition holds
46
+ * none of this session's writes, so the token does not name it.
47
+ */
48
+ export declare function afterReplay(token: ReadTokenState, key: Key, watermark: number): ReadTokenState;
49
+ /** FNV-1a, for routing a client request token to a partition and a field to an index bucket. */
50
+ export declare function hash32(text: string): number;
@@ -0,0 +1,84 @@
1
+ // Keys, epochs, and how writes and reads move a read token (RFD0008, specs/partitioned-writes.ts).
2
+ //
3
+ // A key is (ts, partition, offset). `ts` is a hybrid logical clock packed in one number:
4
+ // epoch × 2^16 + counter, where an epoch is a 50 ms slot of the partition's wall clock and the
5
+ // counter orders dependent writes inside one slot. Keys order every transaction of a graph.
6
+ import { parseReadToken } from "../domain/read-token.js";
7
+ import { rejected } from "../domain/result.js";
8
+ export const EPOCH_MS = 50;
9
+ export const COUNTER = 65_536;
10
+ export function epochOf(ts) {
11
+ return Math.floor(ts / COUNTER);
12
+ }
13
+ export function firstTsOf(epoch) {
14
+ return epoch * COUNTER;
15
+ }
16
+ /** The highest ts in an epoch: a reader at watermark w has seen everything up to lastTsOf(w). */
17
+ export function lastTsOf(epoch) {
18
+ return epoch * COUNTER + (COUNTER - 1);
19
+ }
20
+ export function wallEpoch(nowMs) {
21
+ return Math.floor(nowMs / EPOCH_MS);
22
+ }
23
+ export function epochEndMs(epoch) {
24
+ return (epoch + 1) * EPOCH_MS;
25
+ }
26
+ export function compareKeys(a, b) {
27
+ return a.ts - b.ts || a.partition - b.partition || a.offset - b.offset;
28
+ }
29
+ /**
30
+ * The ts a partition stamps a write with: not below its last stamp (offsets then order its writes),
31
+ * not below its clock, after what the caller has seen (rule dependentWritesAfter), and after the
32
+ * last epoch it handed off as closed (rule closedEpochsStayClosed).
33
+ */
34
+ export function stampTs(input) {
35
+ return Math.max(input.lastTs, firstTsOf(wallEpoch(input.nowMs)), input.after + 1, firstTsOf(input.closedEpoch + 1));
36
+ }
37
+ /**
38
+ * A read token sent to a graph of `partitionCount` partitions: well formed, and naming only its
39
+ * partitions. A token from another graph, or from before a resize, is refused, not trusted.
40
+ */
41
+ export function decodeToken(input, partitionCount) {
42
+ const token = parseReadToken(input);
43
+ if (!token.ok)
44
+ return token;
45
+ if (token.value.partitions.some((p) => p >= partitionCount))
46
+ return rejected("readToken", "read token names partitions this graph does not have");
47
+ return token;
48
+ }
49
+ /** After a write at `key`: the session has seen it, and its partition holds a write of the session above any watermark read. */
50
+ export function afterWrite(token, key) {
51
+ const partitions = token.partitions.includes(key.partition) ? token.partitions : [...token.partitions, key.partition].sort((x, y) => x - y);
52
+ return Object.freeze({ session: token.session, after: Math.max(token.after, key.ts), watermark: token.watermark, partitions: Object.freeze(partitions) });
53
+ }
54
+ /**
55
+ * After a read at `watermark`: the session has seen everything up to it, reads at it or later from
56
+ * now on, and keeps only the partitions still holding its writes above it. The watermark is the
57
+ * read's own. Below the token's, it is a graph that went back, as a deleted and recreated one does,
58
+ * and the token follows the graph.
59
+ */
60
+ export function afterRead(token, watermark, stillAbove) {
61
+ return Object.freeze({
62
+ session: token.session,
63
+ after: Math.max(token.after, lastTsOf(watermark)),
64
+ watermark,
65
+ partitions: Object.freeze(token.partitions.filter((p) => stillAbove.includes(p))),
66
+ });
67
+ }
68
+ /**
69
+ * After another session's write at `key` was replayed to this one, once the watermark had covered
70
+ * it: the session has seen the write and reads at `watermark` or later. The write's partition holds
71
+ * none of this session's writes, so the token does not name it.
72
+ */
73
+ export function afterReplay(token, key, watermark) {
74
+ return Object.freeze({ session: token.session, after: Math.max(token.after, key.ts), watermark: Math.max(token.watermark, watermark), partitions: token.partitions });
75
+ }
76
+ /** FNV-1a, for routing a client request token to a partition and a field to an index bucket. */
77
+ export function hash32(text) {
78
+ let h = 0x811c9dc5;
79
+ for (let i = 0; i < text.length; i++) {
80
+ h ^= text.charCodeAt(i);
81
+ h = Math.imul(h, 0x01000193) >>> 0;
82
+ }
83
+ return h >>> 0;
84
+ }