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,483 @@
1
+ // What the console and agents read about an instance: its graphs, each graph's layout and index,
2
+ // schema, queries and entities. Every call acts as one client id, and the grants decide what it
3
+ // sees, as they do for apps. Only making a graph writes, and it needs the write grant.
4
+ import { parseGraphId } from "../domain/graph-id.js";
5
+ import { projectionMatchesGraph, readProjectionsConfig, } from "../domain/projection.js";
6
+ import { ANNOTATIONS, below, DEFINITIONS, KINDS, labelFields, SCHEMA, schemaTerms, typeFields, VALUE_TAGS, valueType } from "../domain/vocabulary.js";
7
+ import { latencyOf } from "../domain/histogram.js";
8
+ import { epochEndMs } from "../storage/keys.js";
9
+ import { projectionStub, telemetryStub } from "../storage/environment.js";
10
+ import { flushTelemetry } from "./telemetry.js";
11
+ import { readManifest } from "../storage/manifest.js";
12
+ import { createGraph, GraphError, query, schema, status } from "../storage/operations.js";
13
+ import { ALL_GRAPHS, authorizeGraph, GraphAuthorizationError, parseGrants, staticAuthorizer } from "./authorization.js";
14
+ const MAX_GRAPHS = 1_000;
15
+ /**
16
+ * While a graph's index works, its root publishes a manifest about once a second; the index stops
17
+ * once it has had nothing to index for a while (IDLE_STOP_MS in storage/shard.ts). A manifest older
18
+ * than this is an index that has stopped.
19
+ */
20
+ const WORKING_MS = 10_000;
21
+ const DEFAULT_LIMIT = 1_000;
22
+ async function permissions(env, clientId, graphId) {
23
+ const graph = parseGraphId(graphId);
24
+ if (!graph.ok)
25
+ throw new GraphError(400, graph.error.message);
26
+ return authorizeGraph(staticAuthorizer(env.GRAPH_GRANTS), { clientId }, { graphId: graph.value });
27
+ }
28
+ /** The graphs this client may read: every graph with an index, found from the bucket. */
29
+ export async function listGraphs(env, clientId) {
30
+ const authorizer = staticAuthorizer(env.GRAPH_GRANTS);
31
+ const ids = [];
32
+ let cursor;
33
+ do {
34
+ const page = await env.INDEX.list({ prefix: "graphs/", delimiter: "/", ...(cursor === undefined ? {} : { cursor }) });
35
+ for (const prefix of page.delimitedPrefixes)
36
+ ids.push(prefix.slice("graphs/".length, -1));
37
+ cursor = page.truncated ? page.cursor : undefined;
38
+ } while (cursor !== undefined && ids.length < MAX_GRAPHS);
39
+ const summaries = await Promise.all(ids.map(async (id) => {
40
+ const graph = parseGraphId(id);
41
+ if (!graph.ok)
42
+ return null;
43
+ const granted = await authorizer.permissionsFor({ clientId, graphId: graph.value });
44
+ if (!granted.includes("read"))
45
+ return null;
46
+ return summaryOf(env, id, granted);
47
+ }));
48
+ return summaries.filter((s) => s !== null).sort((a, b) => a.id.localeCompare(b.id));
49
+ }
50
+ async function summaryOf(env, id, granted) {
51
+ const manifest = await readManifest(env, id, false);
52
+ if (manifest === null)
53
+ return null;
54
+ let facts = 0, segments = 0;
55
+ for (const refs of Object.values(manifest.buckets)) {
56
+ segments += refs.length;
57
+ for (const ref of refs)
58
+ facts += ref.facts;
59
+ }
60
+ return {
61
+ id, partitions: manifest.partitions, shards: manifest.shards, facts, segments, watermark: manifest.watermark,
62
+ lagMs: manifest.watermark === 0 ? null : Date.now() - manifest.updatedAt > WORKING_MS ? 0 : Math.max(0, manifest.updatedAt - epochEndMs(manifest.watermark)),
63
+ updatedAt: manifest.updatedAt,
64
+ permissions: [...granted],
65
+ };
66
+ }
67
+ /** One graph's layout, index and partitions, as its root, shards and partitions report them. */
68
+ function flushSummary(flushes) {
69
+ const times = flushes.map((f) => f.totalMs).sort((a, b) => a - b);
70
+ return {
71
+ count: flushes.length, lastAt: flushes.at(-1)?.at ?? null, p50Ms: times[Math.floor((times.length - 1) / 2)] ?? null, maxMs: times.at(-1) ?? null,
72
+ behind: flushes.filter((f) => f.behind).length,
73
+ };
74
+ }
75
+ export async function graphDetail(env, clientId, graphId) {
76
+ const granted = await permissions(env, clientId, graphId);
77
+ const [summary, s] = await Promise.all([summaryOf(env, graphId, granted), status(env, graphId)]);
78
+ const root = s.root;
79
+ const now = Date.now();
80
+ // While the index works, a watermark's lag is how far it trails real time. Once the index has
81
+ // stopped, it is caught up, unless a partition holds a write newer than the watermark.
82
+ const working = summary !== null && now - summary.updatedAt <= WORKING_MS;
83
+ const lastWrite = Math.max(0, ...s.partitions.map((p) => p.lastEpoch));
84
+ const behind = (watermark) => (watermark === 0 ? null : !working && lastWrite <= watermark ? 0 : Math.max(0, now - epochEndMs(watermark)));
85
+ const base = summary ?? {
86
+ id: graphId, partitions: root.partitions, shards: root.shards, facts: 0, segments: 0, watermark: root.watermark, lagMs: null, updatedAt: 0, permissions: [...granted],
87
+ };
88
+ return {
89
+ ...base,
90
+ lagMs: working ? base.lagMs : behind(base.watermark),
91
+ layout: root.layout === null ? null : { version: root.layout.version, eras: root.layout.eras, shards: root.layout.shards },
92
+ growth: { installing: root.growth.installing, lastGrewAt: root.growth.lastGrewAt, callsPerSecond: root.growth.callsPerSecond },
93
+ shardStatus: s.shards.map((sh) => ({
94
+ shard: sh.shard, depth: sh.depth, watermark: sh.watermark, lagMs: behind(sh.watermark), facts: sh.liveFacts, segments: sh.segments, bytes: sh.bytes, errors: sh.errors.length,
95
+ flushes: flushSummary(sh.flushes), compactions: { runs: sh.compactions.runs, lastMs: sh.compactions.lastMs, maxMs: sh.compactions.maxMs },
96
+ })),
97
+ partitionStatus: s.partitions.map((p) => ({
98
+ partition: p.partition, calls: p.calls, layoutVersion: p.layoutVersion, startedAt: p.startedAt, rows: p.rows, archived: p.archived, commits: p.commits,
99
+ txs: p.txs, replays: p.replays, conflicts: p.conflicts, colo: p.colo, lastWriteAt: p.lastEpoch === 0 ? null : epochEndMs(p.lastEpoch),
100
+ service: p.service.buckets.length === 0 ? null : latencyOf(p.service),
101
+ })),
102
+ };
103
+ }
104
+ /** The first `limit` rows (1,000 by default, at most 10,000), and whether there were more. */
105
+ export async function runQuery(env, clientId, graphId, datalog, options = {}) {
106
+ await permissions(env, clientId, graphId);
107
+ const answer = await query(env, graphId, { query: datalog, ...(options.consistency === undefined ? {} : { consistency: options.consistency }) }, { limit: options.limit ?? DEFAULT_LIMIT });
108
+ const m = answer.metrics;
109
+ return {
110
+ rows: answer.rows, truncated: answer.truncated === true, watermark: answer.watermark,
111
+ metrics: { totalMs: m.totalMs, manifestMs: m.manifestMs, tailMs: m.tailMs, evaluationMs: m.evaluationMs, waitedMs: m.waitedMs, restarts: m.restarts, segmentsTouched: m.source.segmentsTouched, tuplesRead: m.source.tuplesRead },
112
+ };
113
+ }
114
+ /** The fields a graph's active facts use, and their values' tags: what agents' `schema()` returns. */
115
+ export async function observedSchema(env, clientId, graphId) {
116
+ await permissions(env, clientId, graphId);
117
+ const answer = await schema(env, graphId, {});
118
+ return { fields: answer.fields, watermark: answer.watermark };
119
+ }
120
+ /** The graph's classes, fields and value types: what its schema facts declare, and the fields its facts use. */
121
+ export async function graphSchema(env, clientId, graphId) {
122
+ await permissions(env, clientId, graphId);
123
+ return readSchema(env, graphId);
124
+ }
125
+ /** Schema terms one graph declares, at most, and facts one check reads. */
126
+ const MAX_TERMS = 10_000;
127
+ const MAX_CHECKED = 10_000;
128
+ const SAMPLE = 25;
129
+ async function readSchema(env, graphId) {
130
+ const rows = async (datalog) => (await query(env, graphId, { query: datalog }, { limit: MAX_TERMS })).rows;
131
+ const typed = (kind) => `'${SCHEMA.type}'(T, ${JSON.stringify(kind)})`;
132
+ const read = async (datalog, field, kind) => (await rows(datalog)).flatMap((row) => {
133
+ const entity = idOf(row["T"]);
134
+ const value = kind === undefined ? row["V"] : { type: "reference", value: kind };
135
+ return entity === null || value === undefined ? [] : [{ entity, field, value }];
136
+ });
137
+ // Labels and docs are read on typed terms only: instances may carry labels too, by the million.
138
+ const kinds = Object.keys(KINDS);
139
+ const [observed, statements] = await Promise.all([
140
+ schema(env, graphId, {}),
141
+ Promise.all([
142
+ ...kinds.map((kind) => read(typed(kind), SCHEMA.type, kind)),
143
+ ...kinds.flatMap((kind) => ANNOTATIONS.map((field) => read(`${typed(kind)}, '${field}'(T, V)`, field))),
144
+ ...DEFINITIONS.map((field) => read(`'${field}'(T, V)`, field)),
145
+ ]),
146
+ ]);
147
+ return { watermark: observed.watermark, terms: schemaTerms(statements.flat(), observed.fields) };
148
+ }
149
+ /** What a class or field holds: a class's instances, a field's facts, and how they fit its domain and range. */
150
+ export async function describeTerm(env, clientId, graphId, termId) {
151
+ await permissions(env, clientId, graphId);
152
+ const { watermark, terms } = await readSchema(env, graphId);
153
+ const term = terms.find((t) => t.id === termId);
154
+ const read = (datalog, limit = MAX_CHECKED) => query(env, graphId, { query: datalog }, { limit });
155
+ const id = JSON.stringify(termId);
156
+ const types = typeFields(terms).filter((f) => isUsed(terms, f));
157
+ const labels = namingFields(terms);
158
+ const names = {};
159
+ const name = async (pattern, variable) => {
160
+ await Promise.all(labels.map(async (label) => {
161
+ for (const row of (await read(`${pattern}, '${label}'(${variable}, N)`)).rows) {
162
+ const at = idOf(row[variable]), text = row["N"]?.type === "text" ? row["N"].value : null;
163
+ if (at !== null && text !== null)
164
+ names[at] ??= text;
165
+ }
166
+ }));
167
+ };
168
+ const none = { id: termId, watermark, count: 0, direct: 0, truncated: false, sample: [], names, domainFit: null, rangeFit: null, repeated: null, shared: null };
169
+ if (term === undefined || term.kind === "value" || termId.includes("'"))
170
+ return none;
171
+ if (term.kind === "class") {
172
+ // An instance of a subclass is an instance of the class too.
173
+ const subclasses = below(terms, termId, (t) => t.subclassOf);
174
+ const patterns = types.flatMap((f) => subclasses.map((c) => ({ c, pattern: `'${f}'(E, ${JSON.stringify(c)})` })));
175
+ const answers = await Promise.all(patterns.map(async ({ c, pattern }) => ({ c, answer: await read(pattern) })));
176
+ const of = (list) => {
177
+ const ids = new Set();
178
+ for (const { answer } of list) {
179
+ for (const row of answer.rows) {
180
+ const id = idOf(row["E"]);
181
+ if (id !== null)
182
+ ids.add(id);
183
+ }
184
+ }
185
+ return ids;
186
+ };
187
+ const entities = [...of(answers)];
188
+ await Promise.all(patterns.map(({ pattern }) => name(pattern, "E")));
189
+ const sample = entities.sort((a, b) => (names[a] ?? `~${a}`).localeCompare(names[b] ?? `~${b}`)).slice(0, SAMPLE);
190
+ return {
191
+ ...none, count: entities.length, direct: of(answers.filter((a) => a.c === termId)).size,
192
+ truncated: answers.some(({ answer }) => answer.truncated === true), sample: sample.map((entity) => ({ entity, value: null })),
193
+ };
194
+ }
195
+ const pattern = `'${termId}'(E, V)`;
196
+ const facts = await read(pattern);
197
+ const refs = term.observed.includes("reference");
198
+ await Promise.all([name(pattern, "E"), refs ? name(pattern, "V") : null]);
199
+ const kindOf = (id) => terms.find((t) => t.id === id)?.kind;
200
+ const fit = async (end, allowed) => {
201
+ // A graph's own value types name no tag a value could have, so nothing can be checked against them.
202
+ if (allowed.length === 0 || allowed.some((id) => kindOf(id) === "value" && !VALUE_TYPE_IDS.has(id)))
203
+ return null;
204
+ const tags = new Set(allowed.filter((id) => VALUE_TYPE_IDS.has(id)));
205
+ const classes = allowed.filter((id) => !VALUE_TYPE_IDS.has(id));
206
+ const anyEntity = classes.includes(SCHEMA.entity);
207
+ const subclassOf = (t) => t.subclassOf;
208
+ const within = new Set(classes.flatMap((c) => below(terms, c, subclassOf)));
209
+ const classesOf = new Map();
210
+ let truncated = facts.truncated === true;
211
+ if (classes.length > 0 && !anyEntity) {
212
+ for (const answer of await Promise.all(types.map((f) => read(`${pattern}, '${f}'(${end}, K)`)))) {
213
+ truncated ||= answer.truncated === true;
214
+ for (const row of answer.rows) {
215
+ const at = idOf(row[end]), kind = idOf(row["K"]);
216
+ if (at !== null && kind !== null)
217
+ classesOf.set(at, [...(classesOf.get(at) ?? []), kind]);
218
+ }
219
+ }
220
+ }
221
+ let fits = 0, untyped = 0;
222
+ const outside = new Map();
223
+ const misfit = (by, entity, value) => {
224
+ const entry = outside.get(by) ?? { facts: 0, sample: [] };
225
+ entry.facts++;
226
+ if (entry.sample.length < 5)
227
+ entry.sample.push({ entity, value });
228
+ outside.set(by, entry);
229
+ };
230
+ for (const row of facts.rows) {
231
+ const entity = idOf(row["E"]) ?? "", at = row[end], v = row["V"];
232
+ if (at === undefined || v === undefined)
233
+ continue;
234
+ if (tags.has(valueType(at.type)))
235
+ fits++;
236
+ else if (at.type !== "reference" || classes.length === 0)
237
+ misfit(valueType(at.type), entity, v);
238
+ else if (anyEntity)
239
+ fits++;
240
+ else {
241
+ const kinds = classesOf.get(at.value);
242
+ const firstKind = kinds?.[0];
243
+ if (kinds === undefined || firstKind === undefined)
244
+ untyped++;
245
+ else if (kinds.some((k) => within.has(k)))
246
+ fits++;
247
+ else
248
+ misfit(firstKind, entity, v);
249
+ }
250
+ }
251
+ return { checked: facts.rows.length, truncated, fits, untyped, outside: [...outside].sort(([, a], [, b]) => b.facts - a.facts).map(([c, e]) => ({ class: c, facts: e.facts, sample: e.sample })) };
252
+ };
253
+ const [domainFit, rangeFit] = await Promise.all([fit("E", term.domain), fit("V", term.range)]);
254
+ /** The values at one end that more than one fact holds. */
255
+ const many = (key) => {
256
+ const seen = new Map();
257
+ for (const row of facts.rows) {
258
+ const value = row[key];
259
+ if (value === undefined)
260
+ continue;
261
+ const k = JSON.stringify(value), entry = seen.get(k);
262
+ if (entry === undefined)
263
+ seen.set(k, { value, n: 1 });
264
+ else
265
+ entry.n++;
266
+ }
267
+ return [...seen.values()].filter((e) => e.n > 1).map((e) => e.value);
268
+ };
269
+ const repeated = term.functional ? many("E").flatMap((v) => idOf(v) ?? []) : null;
270
+ const shared = term.inverseFunctional ? many("V") : null;
271
+ return {
272
+ ...none, count: facts.rows.length, direct: facts.rows.length, truncated: facts.truncated === true,
273
+ sample: facts.rows.slice(0, SAMPLE).flatMap((row) => row["V"] === undefined ? [] : [{ entity: idOf(row["E"]) ?? "", value: row["V"] }]),
274
+ domainFit, rangeFit,
275
+ repeated: repeated === null ? null : { count: repeated.length, sample: repeated.slice(0, 5) },
276
+ shared: shared === null ? null : { count: shared.length, sample: shared.slice(0, 5) },
277
+ };
278
+ }
279
+ /** An id a value holds: a reference's, or text holding one, as queries match them. */
280
+ const idOf = (value) => value !== undefined && (value.type === "reference" || value.type === "text") ? value.value : null;
281
+ const VALUE_TYPE_IDS = new Set(VALUE_TAGS.map(valueType));
282
+ const isUsed = (terms, field) => (terms.find((t) => t.id === field)?.observed.length ?? 0) > 0;
283
+ /** The fields entities are named by: Label and the graph's fields below it, else a field that reads as a name. */
284
+ function namingFields(terms) {
285
+ const declared = labelFields(terms).filter((f) => isUsed(terms, f) && !f.includes("'"));
286
+ if (declared.length > 0)
287
+ return declared;
288
+ const named = nameField(terms.filter((t) => t.kind === "field" && !t.builtIn && t.observed.length > 0).map((t) => t.id));
289
+ return named === undefined || named.includes("'") ? [] : [named];
290
+ }
291
+ /** A field as a Datalog predicate: quoted, since fields are URIs. */
292
+ const predicate = (field) => (field.includes("'") ? null : `'${field}'`);
293
+ /** The field entities are known by: a name, else a title. The console picks it the same way. */
294
+ export function nameField(fields) {
295
+ return fields.find((f) => /(^|[:/._-])name$/i.test(f)) ?? fields.find((f) => /(^|[:/._-])title$/i.test(f));
296
+ }
297
+ const MAX_PER_FIELD = 500;
298
+ const MAX_NAMED = 200;
299
+ /** An entity's facts, field by field, the facts whose reference values name it, and the names of both ends. */
300
+ export async function describeEntity(env, clientId, graphId, entity) {
301
+ await permissions(env, clientId, graphId);
302
+ const observed = await schema(env, graphId, {});
303
+ const id = JSON.stringify(entity);
304
+ const read = (datalog) => query(env, graphId, { query: datalog }, { limit: MAX_PER_FIELD });
305
+ const named = nameField(observed.fields.map((f) => f.field));
306
+ const nameP = named === undefined ? null : predicate(named);
307
+ const references = new Set(observed.fields.filter((f) => f.valueTags.includes("reference")).map((f) => f.field));
308
+ let truncated = false;
309
+ const names = {};
310
+ const own = await Promise.all(observed.fields.map(async ({ field }) => {
311
+ const p = predicate(field);
312
+ if (p === null)
313
+ return [];
314
+ const answer = await read(`${p}(${id}, Value)`);
315
+ truncated ||= answer.truncated === true;
316
+ return answer.rows.flatMap((row) => row["Value"] === undefined ? [] : [{ field, value: row["Value"] }]);
317
+ }));
318
+ const incoming = await Promise.all([...references].map(async (field) => {
319
+ const p = predicate(field);
320
+ if (p === null)
321
+ return [];
322
+ const [answer, withNames] = await Promise.all([
323
+ read(`${p}(Entity, ${id})`),
324
+ nameP === null ? null : read(`${p}(Entity, ${id}), ${nameP}(Entity, Name)`),
325
+ ]);
326
+ truncated ||= answer.truncated === true;
327
+ for (const row of withNames?.rows ?? []) {
328
+ const at = idOf(row["Entity"]), name = row["Name"]?.type === "text" ? row["Name"].value : null;
329
+ if (at !== null && name !== null)
330
+ names[at] ??= name;
331
+ }
332
+ return answer.rows.flatMap((row) => idOf(row["Entity"]) ?? []).map((entity) => ({ field, entity }));
333
+ }));
334
+ const facts = own.flat();
335
+ if (nameP !== null) {
336
+ const targets = [...new Set(facts.flatMap((f) => (f.value.type === "reference" ? [f.value.value] : [])))].slice(0, MAX_NAMED);
337
+ await Promise.all(targets.map(async (target) => {
338
+ const answer = await query(env, graphId, { query: `${nameP}(${JSON.stringify(target)}, Name)` }, { limit: 1 });
339
+ const name = answer.rows[0]?.["Name"];
340
+ if (name?.type === "text")
341
+ names[target] = name.value;
342
+ }));
343
+ }
344
+ return { id: entity, watermark: observed.watermark, facts, referencedBy: incoming.flat(), truncated, names };
345
+ }
346
+ /** Makes a graph before its first write, which needs the write grant for it. */
347
+ export async function makeGraph(env, clientId, graphId, partitions) {
348
+ if (!(await permissions(env, clientId, graphId)).includes("write"))
349
+ throw new GraphAuthorizationError();
350
+ return createGraph(env, graphId, partitions === undefined ? {} : { partitions });
351
+ }
352
+ /** The deployed grants, client by client. A malformed policy, which denies everything, shows as none. */
353
+ export function grantsOf(env) {
354
+ try {
355
+ const grants = parseGrants(env.GRAPH_GRANTS);
356
+ return Object.fromEntries([...grants].map(([client, graphs]) => [client, Object.fromEntries([...graphs].map(([graph, p]) => [graph, [...p]]))]));
357
+ }
358
+ catch {
359
+ return {};
360
+ }
361
+ }
362
+ export { ALL_GRAPHS };
363
+ function requireProjectionConfig(env, graphId, name) {
364
+ const configs = readProjectionsConfig(env.PROJECTIONS_CONFIG);
365
+ const found = configs.find((c) => c.name === name && projectionMatchesGraph(c, graphId));
366
+ if (found === undefined)
367
+ throw new GraphError(404, `projection ${JSON.stringify(name)} is not configured for graph ${graphId}`);
368
+ return found;
369
+ }
370
+ async function requireWrite(env, clientId, graphId) {
371
+ if (!(await permissions(env, clientId, graphId)).includes("write"))
372
+ throw new GraphAuthorizationError();
373
+ }
374
+ /** All projections configured for `graphId`, with their live state from ProjectionDO. */
375
+ export async function listProjections(env, clientId, graphId) {
376
+ await permissions(env, clientId, graphId);
377
+ const matching = readProjectionsConfig(env.PROJECTIONS_CONFIG).filter((c) => projectionMatchesGraph(c, graphId));
378
+ if (matching.length === 0 || env.PROJECTIONS === undefined)
379
+ return [];
380
+ return Promise.all(matching.map((c) => projectionStub(env, graphId, c.name).status({ graph: graphId, projection: c.name })));
381
+ }
382
+ /** All projections across every graph this client may read (for the top-level Console Projections page). */
383
+ export async function listAllProjections(env, clientId) {
384
+ const configs = readProjectionsConfig(env.PROJECTIONS_CONFIG);
385
+ if (configs.length === 0 || env.PROJECTIONS === undefined)
386
+ return [];
387
+ const authorizer = staticAuthorizer(env.GRAPH_GRANTS);
388
+ const existing = await listGraphs(env, clientId);
389
+ const graphIds = new Set(existing.map((g) => g.id));
390
+ for (const config of configs) {
391
+ for (const g of config.graphs) {
392
+ if (g === "*")
393
+ continue;
394
+ const parsed = parseGraphId(g);
395
+ if (!parsed.ok)
396
+ continue;
397
+ const granted = await authorizer.permissionsFor({ clientId, graphId: parsed.value });
398
+ if (granted.includes("read"))
399
+ graphIds.add(parsed.value);
400
+ }
401
+ }
402
+ const pairs = [];
403
+ for (const graph of [...graphIds].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {
404
+ for (const config of configs) {
405
+ if (projectionMatchesGraph(config, graph))
406
+ pairs.push({ graph, name: config.name });
407
+ }
408
+ }
409
+ return Promise.all(pairs.map(({ graph, name }) => projectionStub(env, graph, name).status({ graph, projection: name })));
410
+ }
411
+ export async function projectionDetail(env, clientId, graphId, name, limit) {
412
+ await permissions(env, clientId, graphId);
413
+ requireProjectionConfig(env, graphId, name);
414
+ return projectionStub(env, graphId, name).detail({ graph: graphId, projection: name, ...(limit === undefined ? {} : { limit }) });
415
+ }
416
+ export async function projectionDeadLetters(env, clientId, graphId, name, limit) {
417
+ await permissions(env, clientId, graphId);
418
+ requireProjectionConfig(env, graphId, name);
419
+ return projectionStub(env, graphId, name).deadLetters({ graph: graphId, projection: name, ...(limit === undefined ? {} : { limit }) });
420
+ }
421
+ export async function startProjection(env, clientId, graphId, name) {
422
+ await requireWrite(env, clientId, graphId);
423
+ requireProjectionConfig(env, graphId, name);
424
+ return projectionStub(env, graphId, name).start({ graph: graphId, projection: name });
425
+ }
426
+ export async function stopProjection(env, clientId, graphId, name) {
427
+ await requireWrite(env, clientId, graphId);
428
+ requireProjectionConfig(env, graphId, name);
429
+ return projectionStub(env, graphId, name).stop({ graph: graphId, projection: name });
430
+ }
431
+ export async function backfillProjection(env, clientId, graphId, name, since) {
432
+ await requireWrite(env, clientId, graphId);
433
+ requireProjectionConfig(env, graphId, name);
434
+ return projectionStub(env, graphId, name).backfill({ graph: graphId, projection: name, ...(since === undefined ? {} : { since }) });
435
+ }
436
+ export async function replayProjection(env, clientId, graphId, name, input) {
437
+ await requireWrite(env, clientId, graphId);
438
+ requireProjectionConfig(env, graphId, name);
439
+ const stub = projectionStub(env, graphId, name);
440
+ if (input.mode === "from-start") {
441
+ return { state: await stub.replayFromStart({ graph: graphId, projection: name }) };
442
+ }
443
+ return stub.replayDeadLetters({ graph: graphId, projection: name, ...(input.deliveryIds === undefined ? {} : { deliveryIds: input.deliveryIds }) });
444
+ }
445
+ export async function discardProjectionDeadLetters(env, clientId, graphId, name, deliveryIds) {
446
+ await requireWrite(env, clientId, graphId);
447
+ requireProjectionConfig(env, graphId, name);
448
+ return projectionStub(env, graphId, name).discardDeadLetters({
449
+ graph: graphId, projection: name, ...(deliveryIds === undefined ? {} : { deliveryIds }),
450
+ });
451
+ }
452
+ function readableGraphsFor(env, clientId) {
453
+ const clientGrants = parseGrants(env.GRAPH_GRANTS).get(clientId);
454
+ if (clientGrants === undefined)
455
+ return [];
456
+ const wildcard = clientGrants.get(ALL_GRAPHS);
457
+ if (wildcard !== undefined && wildcard.includes("read"))
458
+ return "*";
459
+ const allowed = [];
460
+ for (const [graph, perms] of clientGrants) {
461
+ if (graph !== ALL_GRAPHS && perms.includes("read"))
462
+ allowed.push(graph);
463
+ }
464
+ if (allowed.length > 0)
465
+ allowed.push("_instance");
466
+ return allowed;
467
+ }
468
+ /** Traffic rollups for the graphs this client may read, or null when telemetry is not bound. */
469
+ export async function trafficStats(env, clientId, range, by, filters) {
470
+ const stub = telemetryStub(env);
471
+ if (stub === null)
472
+ return null;
473
+ await flushTelemetry(env);
474
+ return stub.queryTraffic({ range, by, filters, allowedGraphs: readableGraphsFor(env, clientId) });
475
+ }
476
+ /** Query-shape rollups for the graphs this client may read, or null when telemetry is not bound. */
477
+ export async function queryShapeStats(env, clientId, range, filters) {
478
+ const stub = telemetryStub(env);
479
+ if (stub === null)
480
+ return null;
481
+ await flushTelemetry(env);
482
+ return stub.queryQueries({ range, filters, allowedGraphs: readableGraphsFor(env, clientId) });
483
+ }
@@ -0,0 +1,35 @@
1
+ import { type GraphId } from "../domain/graph-id.js";
2
+ export type ClientIdentity = Readonly<{
3
+ clientId: string;
4
+ }>;
5
+ export type GraphRequest = Readonly<{
6
+ graphId: GraphId;
7
+ }>;
8
+ export type GraphPermission = "read" | "write";
9
+ /**
10
+ * Which apps may use which graphs: client id (the binding's `props.clientId`), then graph id, or
11
+ * "*" for every graph the client has no entry of its own for. Writing requires reading.
12
+ */
13
+ export type GraphGrants = Readonly<Record<string, Readonly<Record<string, readonly GraphPermission[]>>>>;
14
+ /** The grant key that covers every graph without a grant of its own. */
15
+ export declare const ALL_GRAPHS = "*";
16
+ export interface GraphAuthorizer {
17
+ permissionsFor(input: ClientIdentity & Readonly<{
18
+ graphId: GraphId;
19
+ }>): Promise<readonly GraphPermission[]>;
20
+ }
21
+ export declare class GraphAuthorizationError extends Error {
22
+ constructor();
23
+ }
24
+ export declare const CLIENT_ID: RegExp;
25
+ export declare function parseIdentity(props: unknown): ClientIdentity;
26
+ type ParsedGrants = ReadonlyMap<string, ReadonlyMap<string, readonly GraphPermission[]>>;
27
+ /**
28
+ * The whole deployment policy, parsed and snapshotted: no prototype lookups and no caller arrays.
29
+ * Throws a RangeError naming the first bad entry; the config helper surfaces it at deploy time.
30
+ */
31
+ export declare function parseGrants(input: unknown): ParsedGrants;
32
+ /** Grants checked at every call; a malformed policy denies everything rather than part of it. */
33
+ export declare function staticAuthorizer(input: unknown): GraphAuthorizer;
34
+ export declare function authorizeGraph(authorizer: GraphAuthorizer, identity: ClientIdentity, request: GraphRequest): Promise<readonly GraphPermission[]>;
35
+ export {};
@@ -0,0 +1,76 @@
1
+ import { parseGraphId } from "../domain/graph-id.js";
2
+ /** The grant key that covers every graph without a grant of its own. */
3
+ export const ALL_GRAPHS = "*";
4
+ export class GraphAuthorizationError extends Error {
5
+ constructor() { super("Graph access denied"); this.name = "GraphAuthorizationError"; }
6
+ }
7
+ function isRecord(value) {
8
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9
+ }
10
+ export const CLIENT_ID = /^[a-z0-9][a-z0-9._:-]{0,127}$/;
11
+ function clientId(value) {
12
+ if (typeof value !== "string" || !CLIENT_ID.test(value))
13
+ throw new GraphAuthorizationError();
14
+ return value;
15
+ }
16
+ export function parseIdentity(props) {
17
+ if (!isRecord(props) || Object.keys(props).length !== 1 || !Object.hasOwn(props, "clientId"))
18
+ throw new GraphAuthorizationError();
19
+ return Object.freeze({ clientId: clientId(props["clientId"]) });
20
+ }
21
+ /**
22
+ * The whole deployment policy, parsed and snapshotted: no prototype lookups and no caller arrays.
23
+ * Throws a RangeError naming the first bad entry; the config helper surfaces it at deploy time.
24
+ */
25
+ export function parseGrants(input) {
26
+ if (!isRecord(input))
27
+ throw new RangeError("grants must be an object of client ids");
28
+ const grants = new Map();
29
+ for (const [client, rawGraphs] of Object.entries(input)) {
30
+ if (!CLIENT_ID.test(client))
31
+ throw new RangeError(`grants: ${JSON.stringify(client)} is not a client id (${CLIENT_ID.source})`);
32
+ if (!isRecord(rawGraphs))
33
+ throw new RangeError(`grants.${client} must be an object of graph ids`);
34
+ const graphs = new Map();
35
+ for (const [rawGraph, rawPermissions] of Object.entries(rawGraphs)) {
36
+ const at = `grants.${client}.${rawGraph}`;
37
+ if (rawGraph !== ALL_GRAPHS && !parseGraphId(rawGraph).ok)
38
+ throw new RangeError(`${at}: ${JSON.stringify(rawGraph)} is not a graph id or "${ALL_GRAPHS}"`);
39
+ if (!Array.isArray(rawPermissions))
40
+ throw new RangeError(`${at} must be a list of "read" and "write"`);
41
+ const permissions = [];
42
+ for (const permission of rawPermissions) {
43
+ if ((permission !== "read" && permission !== "write") || permissions.includes(permission))
44
+ throw new RangeError(`${at} must be a list of "read" and "write", each once`);
45
+ permissions.push(permission);
46
+ }
47
+ if (permissions.includes("write") && !permissions.includes("read"))
48
+ throw new RangeError(`${at}: writing requires "read" too`);
49
+ graphs.set(rawGraph, Object.freeze(permissions));
50
+ }
51
+ grants.set(client, graphs);
52
+ }
53
+ return grants;
54
+ }
55
+ /** Grants checked at every call; a malformed policy denies everything rather than part of it. */
56
+ export function staticAuthorizer(input) {
57
+ let grants;
58
+ try {
59
+ grants = parseGrants(input);
60
+ }
61
+ catch {
62
+ throw new GraphAuthorizationError();
63
+ }
64
+ return Object.freeze({
65
+ async permissionsFor({ clientId, graphId }) {
66
+ const graphs = grants.get(clientId);
67
+ return graphs?.get(graphId) ?? graphs?.get(ALL_GRAPHS) ?? Object.freeze([]);
68
+ },
69
+ });
70
+ }
71
+ export async function authorizeGraph(authorizer, identity, request) {
72
+ const permissions = await authorizer.permissionsFor({ ...identity, graphId: request.graphId });
73
+ if (!permissions.includes("read") || permissions.some(permission => permission !== "read" && permission !== "write"))
74
+ throw new GraphAuthorizationError();
75
+ return Object.freeze([...permissions]);
76
+ }
@@ -0,0 +1,6 @@
1
+ export type ConsoleAsset = Readonly<{
2
+ type: string;
3
+ body: string;
4
+ base64: boolean;
5
+ }>;
6
+ export declare const CONSOLE_ASSETS: Readonly<Record<string, ConsoleAsset>>;