fatedb 0.0.0-stage → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +264 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +3 -0
- package/dist/cli.d.ts +15 -0
- package/dist/cli.js +256 -0
- package/dist/client.d.ts +152 -0
- package/dist/client.js +416 -0
- package/dist/cloudflare.d.ts +197 -0
- package/dist/cloudflare.js +159 -0
- package/dist/datalog/ast.d.ts +35 -0
- package/dist/datalog/ast.js +40 -0
- package/dist/datalog/evaluator.d.ts +14 -0
- package/dist/datalog/evaluator.js +395 -0
- package/dist/datalog/fact-source.d.ts +30 -0
- package/dist/datalog/fact-source.js +1 -0
- package/dist/datalog/fingerprint.d.ts +12 -0
- package/dist/datalog/fingerprint.js +50 -0
- package/dist/datalog/parser.d.ts +3 -0
- package/dist/datalog/parser.js +302 -0
- package/dist/datalog/value.d.ts +34 -0
- package/dist/datalog/value.js +104 -0
- package/dist/domain/date-validation.d.ts +2 -0
- package/dist/domain/date-validation.js +32 -0
- package/dist/domain/fact-value.d.ts +91 -0
- package/dist/domain/fact-value.js +167 -0
- package/dist/domain/fact.d.ts +14 -0
- package/dist/domain/fact.js +47 -0
- package/dist/domain/failure.d.ts +44 -0
- package/dist/domain/failure.js +30 -0
- package/dist/domain/graph-id.d.ts +7 -0
- package/dist/domain/graph-id.js +10 -0
- package/dist/domain/histogram.d.ts +29 -0
- package/dist/domain/histogram.js +48 -0
- package/dist/domain/identifiers.d.ts +26 -0
- package/dist/domain/identifiers.js +75 -0
- package/dist/domain/numbers.d.ts +12 -0
- package/dist/domain/numbers.js +77 -0
- package/dist/domain/projection.d.ts +252 -0
- package/dist/domain/projection.js +51 -0
- package/dist/domain/query-metrics.d.ts +31 -0
- package/dist/domain/query-metrics.js +35 -0
- package/dist/domain/read-token.d.ts +37 -0
- package/dist/domain/read-token.js +93 -0
- package/dist/domain/result.d.ts +22 -0
- package/dist/domain/result.js +16 -0
- package/dist/domain/schema-observation.d.ts +20 -0
- package/dist/domain/schema-observation.js +61 -0
- package/dist/domain/string-order.d.ts +2 -0
- package/dist/domain/string-order.js +15 -0
- package/dist/domain/vocabulary.d.ts +101 -0
- package/dist/domain/vocabulary.js +276 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +14 -0
- package/dist/projection-config.d.ts +3 -0
- package/dist/projection-config.js +212 -0
- package/dist/server/access.d.ts +32 -0
- package/dist/server/access.js +117 -0
- package/dist/server/admin.d.ts +233 -0
- package/dist/server/admin.js +483 -0
- package/dist/server/authorization.d.ts +35 -0
- package/dist/server/authorization.js +76 -0
- package/dist/server/console-assets.d.ts +6 -0
- package/dist/server/console-assets.js +2 -0
- package/dist/server/console.d.ts +8 -0
- package/dist/server/console.js +301 -0
- package/dist/server/index.d.ts +122 -0
- package/dist/server/index.js +487 -0
- package/dist/server/mcp.d.ts +31 -0
- package/dist/server/mcp.js +169 -0
- package/dist/server/telemetry-do.d.ts +31 -0
- package/dist/server/telemetry-do.js +342 -0
- package/dist/server/telemetry.d.ts +27 -0
- package/dist/server/telemetry.js +191 -0
- package/dist/storage/constants.d.ts +20 -0
- package/dist/storage/constants.js +21 -0
- package/dist/storage/environment.d.ts +438 -0
- package/dist/storage/environment.js +145 -0
- package/dist/storage/facts.d.ts +41 -0
- package/dist/storage/facts.js +73 -0
- package/dist/storage/http.d.ts +55 -0
- package/dist/storage/http.js +169 -0
- package/dist/storage/keys.d.ts +50 -0
- package/dist/storage/keys.js +84 -0
- package/dist/storage/layout.d.ts +67 -0
- package/dist/storage/layout.js +134 -0
- package/dist/storage/log.d.ts +41 -0
- package/dist/storage/log.js +137 -0
- package/dist/storage/manifest.d.ts +26 -0
- package/dist/storage/manifest.js +206 -0
- package/dist/storage/operations.d.ts +303 -0
- package/dist/storage/operations.js +719 -0
- package/dist/storage/partition.d.ts +125 -0
- package/dist/storage/partition.js +816 -0
- package/dist/storage/projection.d.ts +72 -0
- package/dist/storage/projection.js +1349 -0
- package/dist/storage/root.d.ts +120 -0
- package/dist/storage/root.js +596 -0
- package/dist/storage/segment.d.ts +145 -0
- package/dist/storage/segment.js +451 -0
- package/dist/storage/shard.d.ts +82 -0
- package/dist/storage/shard.js +710 -0
- package/dist/storage/source.d.ts +60 -0
- package/dist/storage/source.js +199 -0
- package/dist/telemetry/model.d.ts +123 -0
- package/dist/telemetry/model.js +292 -0
- package/dist/version.d.ts +4 -0
- package/dist/version.js +6 -0
- package/package.json +82 -4
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ConsoleConfig, Viewer } from "./access.js";
|
|
2
|
+
import { type AdminEnv } from "./admin.js";
|
|
3
|
+
export declare function handleConsoleApi(request: Request, env: AdminEnv, config: ConsoleConfig, viewer: Viewer, ctx?: Pick<ExecutionContext, "waitUntil">): Promise<Response>;
|
|
4
|
+
/**
|
|
5
|
+
* The console's files, and its page for every other path: the app routes in the browser. The files
|
|
6
|
+
* load on the first request for one: they are most of the package, and the console's API needs none.
|
|
7
|
+
*/
|
|
8
|
+
export declare function serveConsole(request: Request): Promise<Response>;
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
// The console on the instance's hostname: its API under /api, and the app itself, built into the
|
|
2
|
+
// package (console-assets.ts is generated from packages/fatedb-console). Callers have passed
|
|
3
|
+
// Access already; they act as the console's client id, and the grants decide what they see.
|
|
4
|
+
//
|
|
5
|
+
// GET /api/instance the instance, the viewer and the grants
|
|
6
|
+
// GET /api/agents what /mcp offers agents: its tool, and the API their code sees
|
|
7
|
+
// GET /api/graphs the graphs the console may read
|
|
8
|
+
// PUT /api/graphs/:id { partitions? }: makes a graph, with the write grant
|
|
9
|
+
// GET /api/graphs/:id its layout, index and partitions
|
|
10
|
+
// GET /api/graphs/:id/schema its classes, fields and value types: declared, and in use
|
|
11
|
+
// GET /api/graphs/:id/schema/:term a class's instances, or a field's facts and how they fit
|
|
12
|
+
// POST /api/graphs/:id/query { query, consistency? }
|
|
13
|
+
// GET /api/graphs/:id/entities/:entity an entity's facts, and what references it
|
|
14
|
+
// GET /api/graphs/:id/projections the projections configured for this graph
|
|
15
|
+
// GET /api/graphs/:id/projections/:name/dead-letters dead-lettered batches for a projection
|
|
16
|
+
// POST /api/graphs/:id/projections/:name/start|stop|backfill|replay|dead-letters/discard
|
|
17
|
+
import { parseObservabilityDimension, parseObservabilityRange, } from "../telemetry/model.js";
|
|
18
|
+
import { GraphError } from "../storage/operations.js";
|
|
19
|
+
import { VERSION } from "../version.js";
|
|
20
|
+
import { backfillProjection, describeEntity, describeTerm, discardProjectionDeadLetters, graphDetail, graphSchema, grantsOf, listAllProjections, listGraphs, listProjections, makeGraph, projectionDeadLetters, projectionDetail, queryShapeStats, replayProjection, runQuery, startProjection, stopProjection, trafficStats, } from "./admin.js";
|
|
21
|
+
import { GraphAuthorizationError } from "./authorization.js";
|
|
22
|
+
import { API_TYPES, EXAMPLE, EXECUTE } from "./mcp.js";
|
|
23
|
+
import { outcomeOfError, recordCall } from "./telemetry.js";
|
|
24
|
+
const ROUTE = /^\/api\/graphs\/([^/]+)(?:\/(schema|query|entities|projections)(?:\/([^/]+)(?:\/([^/]+)(?:\/([^/]+))?)?)?)?$/;
|
|
25
|
+
const MAX_BODY_BYTES = 64_000;
|
|
26
|
+
function problem(status, message) {
|
|
27
|
+
return Response.json({ error: message }, { status, headers: { "cache-control": "no-store" } });
|
|
28
|
+
}
|
|
29
|
+
async function body(request) {
|
|
30
|
+
const text = await request.text();
|
|
31
|
+
if (text.length > MAX_BODY_BYTES)
|
|
32
|
+
throw new GraphError(413, `a request body is at most ${MAX_BODY_BYTES} bytes`);
|
|
33
|
+
if (text.trim() === "")
|
|
34
|
+
return {};
|
|
35
|
+
let value;
|
|
36
|
+
try {
|
|
37
|
+
value = JSON.parse(text);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw new GraphError(400, "the request body is not JSON");
|
|
41
|
+
}
|
|
42
|
+
if (!isPlainRecord(value))
|
|
43
|
+
throw new GraphError(400, "the request body must be a JSON object");
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
async function respond(run) {
|
|
47
|
+
try {
|
|
48
|
+
return Response.json(await run(), { headers: { "cache-control": "no-store" } });
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (error instanceof GraphError)
|
|
52
|
+
return problem(error.status, error.message);
|
|
53
|
+
if (error instanceof GraphAuthorizationError)
|
|
54
|
+
return problem(403, "The console's client id has no grant for this graph");
|
|
55
|
+
if (error instanceof RangeError)
|
|
56
|
+
return problem(400, error.message);
|
|
57
|
+
console.error(JSON.stringify({ event: "console.failed", error: error instanceof Error ? error.message : String(error) }));
|
|
58
|
+
return problem(503, "storage failed; try again");
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function decode(part) {
|
|
62
|
+
try {
|
|
63
|
+
return decodeURIComponent(part);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
throw new GraphError(400, "the path is not valid percent-encoding");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function isPlainRecord(value) {
|
|
70
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
71
|
+
}
|
|
72
|
+
function parseOptionalIdList(raw) {
|
|
73
|
+
if (raw === undefined)
|
|
74
|
+
return undefined;
|
|
75
|
+
if (!Array.isArray(raw))
|
|
76
|
+
throw new GraphError(400, "deliveryIds must be an array of non-empty strings");
|
|
77
|
+
const ids = [];
|
|
78
|
+
for (const item of raw) {
|
|
79
|
+
if (typeof item !== "string" || item === "")
|
|
80
|
+
throw new GraphError(400, "deliveryIds must be an array of non-empty strings");
|
|
81
|
+
ids.push(item);
|
|
82
|
+
}
|
|
83
|
+
return ids;
|
|
84
|
+
}
|
|
85
|
+
function parseObservabilityFilters(params) {
|
|
86
|
+
const graph = params.get("graph") || undefined;
|
|
87
|
+
const client = params.get("client") || undefined;
|
|
88
|
+
const operation = params.get("operation") || undefined;
|
|
89
|
+
const outcome = params.get("outcome") || undefined;
|
|
90
|
+
return {
|
|
91
|
+
...(graph === undefined ? {} : { graph }),
|
|
92
|
+
...(client === undefined ? {} : { client }),
|
|
93
|
+
...(operation === undefined ? {} : { operation }),
|
|
94
|
+
...(outcome === undefined ? {} : { outcome }),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
export async function handleConsoleApi(request, env, config, viewer, ctx) {
|
|
98
|
+
const url = new URL(request.url);
|
|
99
|
+
const path = url.pathname;
|
|
100
|
+
const method = request.method;
|
|
101
|
+
const client = config.clientId;
|
|
102
|
+
if (path === "/api/instance") {
|
|
103
|
+
if (method !== "GET")
|
|
104
|
+
return problem(405, "GET only");
|
|
105
|
+
return respond(async () => ({
|
|
106
|
+
name: config.name, version: VERSION, hostname: config.hostname, bucket: config.bucket, clientId: client, viewer, grants: grantsOf(env),
|
|
107
|
+
access: { teamDomain: config.teamDomain, aud: config.aud }, locationHint: env.LOCATION_HINT ?? null,
|
|
108
|
+
}));
|
|
109
|
+
}
|
|
110
|
+
if (path === "/api/agents") {
|
|
111
|
+
if (method !== "GET")
|
|
112
|
+
return problem(405, "GET only");
|
|
113
|
+
return respond(async () => ({ endpoint: `https://${config.hostname}/mcp`, clientId: client, tool: { name: EXECUTE.name, title: EXECUTE.title }, types: API_TYPES, example: EXAMPLE }));
|
|
114
|
+
}
|
|
115
|
+
if (path === "/api/graphs") {
|
|
116
|
+
if (method !== "GET")
|
|
117
|
+
return problem(405, "GET only");
|
|
118
|
+
return respond(() => listGraphs(env, client));
|
|
119
|
+
}
|
|
120
|
+
if (path === "/api/projections") {
|
|
121
|
+
if (method !== "GET")
|
|
122
|
+
return problem(405, "GET only");
|
|
123
|
+
return respond(() => listAllProjections(env, client));
|
|
124
|
+
}
|
|
125
|
+
if (path === "/api/observability/traffic") {
|
|
126
|
+
if (method !== "GET")
|
|
127
|
+
return problem(405, "GET only");
|
|
128
|
+
const range = parseObservabilityRange(url.searchParams.get("range"));
|
|
129
|
+
const by = parseObservabilityDimension(url.searchParams.get("by"));
|
|
130
|
+
const filters = parseObservabilityFilters(url.searchParams);
|
|
131
|
+
return respond(async () => {
|
|
132
|
+
const result = await trafficStats(env, client, range, by, filters);
|
|
133
|
+
if (result === null)
|
|
134
|
+
throw new GraphError(404, "observability is not enabled on this instance");
|
|
135
|
+
return result;
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
if (path === "/api/observability/queries") {
|
|
139
|
+
if (method !== "GET")
|
|
140
|
+
return problem(405, "GET only");
|
|
141
|
+
const range = parseObservabilityRange(url.searchParams.get("range"));
|
|
142
|
+
const filters = parseObservabilityFilters(url.searchParams);
|
|
143
|
+
return respond(async () => {
|
|
144
|
+
const result = await queryShapeStats(env, client, range, filters);
|
|
145
|
+
if (result === null)
|
|
146
|
+
throw new GraphError(404, "observability is not enabled on this instance");
|
|
147
|
+
return result;
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
const match = ROUTE.exec(path);
|
|
151
|
+
const rawGraph = match?.[1];
|
|
152
|
+
if (match === null || rawGraph === undefined)
|
|
153
|
+
return problem(404, "no such API route");
|
|
154
|
+
return respond(async () => {
|
|
155
|
+
const graph = decode(rawGraph);
|
|
156
|
+
const action = match[2];
|
|
157
|
+
if (action === undefined) {
|
|
158
|
+
if (method === "GET")
|
|
159
|
+
return graphDetail(env, client, graph);
|
|
160
|
+
if (method === "PUT") {
|
|
161
|
+
const { partitions } = await body(request);
|
|
162
|
+
if (partitions !== undefined && typeof partitions !== "number")
|
|
163
|
+
throw new GraphError(400, "partitions must be a number");
|
|
164
|
+
return makeGraph(env, client, graph, partitions);
|
|
165
|
+
}
|
|
166
|
+
throw new GraphError(405, "GET or PUT");
|
|
167
|
+
}
|
|
168
|
+
if (action === "schema" && method === "GET") {
|
|
169
|
+
const started = performance.now();
|
|
170
|
+
try {
|
|
171
|
+
const answer = match[3] === undefined ? await graphSchema(env, client, graph) : await describeTerm(env, client, graph, decode(match[3]));
|
|
172
|
+
recordCall(env, ctx, { graph, client, operation: "getSchema", outcome: "ok", durationMs: performance.now() - started });
|
|
173
|
+
return answer;
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
recordCall(env, ctx, { graph, client, operation: "getSchema", outcome: outcomeOfError(error), durationMs: performance.now() - started });
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (action === "query" && method === "POST" && match[3] === undefined) {
|
|
181
|
+
const started = performance.now();
|
|
182
|
+
let source = "";
|
|
183
|
+
try {
|
|
184
|
+
const { query, consistency, limit } = await body(request);
|
|
185
|
+
if (typeof query !== "string")
|
|
186
|
+
throw new GraphError(400, "query must be a Datalog string");
|
|
187
|
+
source = query;
|
|
188
|
+
if (consistency !== undefined && consistency !== "own-writes" && consistency !== "snapshot")
|
|
189
|
+
throw new GraphError(400, "consistency is own-writes or snapshot");
|
|
190
|
+
if (limit !== undefined && (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 10_000))
|
|
191
|
+
throw new GraphError(400, "limit is a whole number from 1 to 10,000");
|
|
192
|
+
const answer = await runQuery(env, client, graph, query, { ...(consistency === undefined ? {} : { consistency }), ...(limit === undefined ? {} : { limit }) });
|
|
193
|
+
recordCall(env, ctx, {
|
|
194
|
+
graph, client, operation: "query", outcome: "ok", durationMs: performance.now() - started,
|
|
195
|
+
query: { source, rows: answer.rows.length, tuples: answer.metrics.tuplesRead },
|
|
196
|
+
});
|
|
197
|
+
return answer;
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
recordCall(env, ctx, {
|
|
201
|
+
graph, client, operation: "query", outcome: outcomeOfError(error), durationMs: performance.now() - started,
|
|
202
|
+
...(source === "" ? {} : { query: { source, rows: 0, tuples: 0 } }),
|
|
203
|
+
});
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
if (action === "entities" && method === "GET" && match[3] !== undefined && match[4] === undefined) {
|
|
208
|
+
const started = performance.now();
|
|
209
|
+
try {
|
|
210
|
+
const answer = await describeEntity(env, client, graph, decode(match[3]));
|
|
211
|
+
recordCall(env, ctx, { graph, client, operation: "entity", outcome: "ok", durationMs: performance.now() - started });
|
|
212
|
+
return answer;
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
recordCall(env, ctx, { graph, client, operation: "entity", outcome: outcomeOfError(error), durationMs: performance.now() - started });
|
|
216
|
+
throw error;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if (action === "projections") {
|
|
220
|
+
if (match[3] === undefined) {
|
|
221
|
+
if (method === "GET")
|
|
222
|
+
return listProjections(env, client, graph);
|
|
223
|
+
throw new GraphError(405, "GET only");
|
|
224
|
+
}
|
|
225
|
+
const name = decode(match[3]);
|
|
226
|
+
const sub = match[4];
|
|
227
|
+
const sub2 = match[5];
|
|
228
|
+
if (sub === undefined && method === "GET") {
|
|
229
|
+
const limitParam = new URL(request.url).searchParams.get("limit");
|
|
230
|
+
const limit = limitParam === null ? undefined : Number(limitParam);
|
|
231
|
+
if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 200)) {
|
|
232
|
+
throw new GraphError(400, "limit must be an integer between 1 and 200");
|
|
233
|
+
}
|
|
234
|
+
return projectionDetail(env, client, graph, name, limit);
|
|
235
|
+
}
|
|
236
|
+
if (sub === "dead-letters" && sub2 === undefined && method === "GET") {
|
|
237
|
+
return projectionDeadLetters(env, client, graph, name);
|
|
238
|
+
}
|
|
239
|
+
if (sub === "dead-letters" && sub2 === "discard" && method === "POST") {
|
|
240
|
+
const payload = await body(request);
|
|
241
|
+
const deliveryIds = parseOptionalIdList(payload["deliveryIds"]);
|
|
242
|
+
return discardProjectionDeadLetters(env, client, graph, name, deliveryIds);
|
|
243
|
+
}
|
|
244
|
+
if (sub2 === undefined && method === "POST") {
|
|
245
|
+
if (sub === "start")
|
|
246
|
+
return startProjection(env, client, graph, name);
|
|
247
|
+
if (sub === "stop")
|
|
248
|
+
return stopProjection(env, client, graph, name);
|
|
249
|
+
if (sub === "backfill") {
|
|
250
|
+
const payload = await body(request);
|
|
251
|
+
const rawSince = payload["since"];
|
|
252
|
+
if (rawSince === undefined || rawSince === "current") {
|
|
253
|
+
return backfillProjection(env, client, graph, name, "current");
|
|
254
|
+
}
|
|
255
|
+
if (typeof rawSince === "number" && Number.isFinite(rawSince) && rawSince >= 0) {
|
|
256
|
+
return backfillProjection(env, client, graph, name, rawSince);
|
|
257
|
+
}
|
|
258
|
+
throw new GraphError(400, 'since must be "current" or a non-negative timestamp in milliseconds');
|
|
259
|
+
}
|
|
260
|
+
if (sub === "replay") {
|
|
261
|
+
const payload = await body(request);
|
|
262
|
+
const mode = payload["mode"] ?? "dead-letters";
|
|
263
|
+
if (mode === "from-start")
|
|
264
|
+
return replayProjection(env, client, graph, name, { mode: "from-start" });
|
|
265
|
+
if (mode === "dead-letters") {
|
|
266
|
+
const deliveryIds = parseOptionalIdList(payload["deliveryIds"]);
|
|
267
|
+
return replayProjection(env, client, graph, name, { mode: "dead-letters", ...(deliveryIds === undefined ? {} : { deliveryIds }) });
|
|
268
|
+
}
|
|
269
|
+
throw new GraphError(400, 'mode must be "dead-letters" or "from-start"');
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
throw new GraphError(405, "no such projection route or method");
|
|
273
|
+
}
|
|
274
|
+
throw new GraphError(405, "no such method on this route");
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
const SECURITY_HEADERS = {
|
|
278
|
+
"content-security-policy": "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
|
279
|
+
"x-content-type-options": "nosniff",
|
|
280
|
+
"referrer-policy": "same-origin",
|
|
281
|
+
};
|
|
282
|
+
function asset(assets, name) {
|
|
283
|
+
const file = assets[name];
|
|
284
|
+
if (file === undefined)
|
|
285
|
+
return null;
|
|
286
|
+
const bytes = file.base64 ? Uint8Array.from(atob(file.body), (c) => c.charCodeAt(0)) : file.body;
|
|
287
|
+
// Built files carry their hash in their names, so they never change under one.
|
|
288
|
+
const cache = name.startsWith("/assets/") ? "public, max-age=31536000, immutable" : "no-cache";
|
|
289
|
+
return new Response(bytes, { headers: { "content-type": file.type, "cache-control": cache, ...SECURITY_HEADERS } });
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* The console's files, and its page for every other path: the app routes in the browser. The files
|
|
293
|
+
* load on the first request for one: they are most of the package, and the console's API needs none.
|
|
294
|
+
*/
|
|
295
|
+
export async function serveConsole(request) {
|
|
296
|
+
if (request.method !== "GET" && request.method !== "HEAD")
|
|
297
|
+
return new Response("Method not allowed\n", { status: 405, headers: { allow: "GET, HEAD" } });
|
|
298
|
+
const path = new URL(request.url).pathname;
|
|
299
|
+
const { CONSOLE_ASSETS } = await import("./console-assets.js");
|
|
300
|
+
return asset(CONSOLE_ASSETS, path) ?? asset(CONSOLE_ASSETS, "/index.html") ?? new Response("The console was not built into this package\n", { status: 500 });
|
|
301
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { RpcTarget, WorkerEntrypoint } from "cloudflare:workers";
|
|
2
|
+
import { type FactInput, type GraphClient, type QueryAnswer, type QueryManyAnswer, type QueryOptions, type TransactionOptions, type TransactionReceipt } from "../client.js";
|
|
3
|
+
import { type ReadFailure, type WriteFailure } from "../domain/failure.js";
|
|
4
|
+
import { type Value } from "../domain/fact-value.js";
|
|
5
|
+
import { type Result } from "../domain/result.js";
|
|
6
|
+
import type { GraphSchemaObservation } from "../domain/schema-observation.js";
|
|
7
|
+
import type { StorageEnv } from "../storage/environment.js";
|
|
8
|
+
import { type GraphPermission } from "./authorization.js";
|
|
9
|
+
export { PartitionDO } from "../storage/partition.js";
|
|
10
|
+
export { IndexShardDO } from "../storage/shard.js";
|
|
11
|
+
export { GraphRootDO } from "../storage/root.js";
|
|
12
|
+
export { ProjectionDO } from "../storage/projection.js";
|
|
13
|
+
export { TelemetryDO } from "./telemetry-do.js";
|
|
14
|
+
export type { GraphGrants, GraphPermission } from "./authorization.js";
|
|
15
|
+
/**
|
|
16
|
+
* A graph handle reads its own writes for as long as the caller holds it. To read them in a later
|
|
17
|
+
* request, as an app's next page load does, pass back the readToken of an earlier answer.
|
|
18
|
+
*/
|
|
19
|
+
export type GraphReadOptions = Readonly<Pick<QueryOptions, "readToken" | "consistency" | "maxStalenessMs">>;
|
|
20
|
+
export type GraphWriteOptions = Readonly<Pick<TransactionOptions, "clientRequestToken" | "readToken">>;
|
|
21
|
+
/**
|
|
22
|
+
* What the instance's config binds (`fatedb/cloudflare`): the storage, the grants, the
|
|
23
|
+
* Worker Loader that runs agents' code, and the console's settings when it has one.
|
|
24
|
+
*/
|
|
25
|
+
export type ServiceEnv = StorageEnv & Readonly<{
|
|
26
|
+
GRAPH_GRANTS: unknown;
|
|
27
|
+
LOADER: WorkerLoader;
|
|
28
|
+
CONSOLE?: unknown;
|
|
29
|
+
}>;
|
|
30
|
+
/** What a handle may do: the graph's client, whether the app may write to it, and its caller identity. */
|
|
31
|
+
type Access = Result<Readonly<{
|
|
32
|
+
client: GraphClient;
|
|
33
|
+
write: boolean;
|
|
34
|
+
clientId: string;
|
|
35
|
+
}>, ReadFailure>;
|
|
36
|
+
type TelemetryContext = Readonly<{
|
|
37
|
+
env: StorageEnv;
|
|
38
|
+
ctx: Pick<ExecutionContext, "waitUntil">;
|
|
39
|
+
clientId: string;
|
|
40
|
+
}>;
|
|
41
|
+
/**
|
|
42
|
+
* A graph, for an app (RFD0015). Its operations answer results, and never throw for what they are
|
|
43
|
+
* given: a handle for a graph id that is not one answers `invalid`, one for a graph the app has no
|
|
44
|
+
* grant for answers `denied`, and one without the write grant answers `denied` from `transact`.
|
|
45
|
+
*/
|
|
46
|
+
export declare class Graph extends RpcTarget implements GraphClient {
|
|
47
|
+
#private;
|
|
48
|
+
constructor(id: string, access: Access, telemetry?: TelemetryContext);
|
|
49
|
+
get id(): string;
|
|
50
|
+
query(source: string, options?: GraphReadOptions): Promise<Result<QueryAnswer, ReadFailure>>;
|
|
51
|
+
queryMany(sources: readonly string[], options?: GraphReadOptions): Promise<Result<QueryManyAnswer, ReadFailure>>;
|
|
52
|
+
getSchema(options?: GraphReadOptions): Promise<Result<GraphSchemaObservation, ReadFailure>>;
|
|
53
|
+
transact(facts: readonly FactInput[], options?: GraphWriteOptions): Promise<Result<TransactionReceipt, WriteFailure>>;
|
|
54
|
+
}
|
|
55
|
+
export default class FateDBService extends WorkerEntrypoint<ServiceEnv> {
|
|
56
|
+
#private;
|
|
57
|
+
query(input: {
|
|
58
|
+
graphId: string;
|
|
59
|
+
query: string;
|
|
60
|
+
} & GraphReadOptions): Promise<Result<QueryAnswer, ReadFailure>>;
|
|
61
|
+
queryMany(input: {
|
|
62
|
+
graphId: string;
|
|
63
|
+
queries: readonly string[];
|
|
64
|
+
} & GraphReadOptions): Promise<Result<QueryManyAnswer, ReadFailure>>;
|
|
65
|
+
/** A handle for the graph, whatever it is given: its operations answer why they cannot run. */
|
|
66
|
+
getGraph(input: {
|
|
67
|
+
graphId: string;
|
|
68
|
+
}): Promise<Graph>;
|
|
69
|
+
fetch(request: Request): Promise<Response>;
|
|
70
|
+
}
|
|
71
|
+
/** The read-only API agents' code calls from its sandbox, as the client id in its props. */
|
|
72
|
+
export declare class CodemodeApi extends WorkerEntrypoint<ServiceEnv> {
|
|
73
|
+
#private;
|
|
74
|
+
graphs(): Promise<Readonly<{
|
|
75
|
+
id: string;
|
|
76
|
+
partitions: number;
|
|
77
|
+
shards: number;
|
|
78
|
+
facts: number;
|
|
79
|
+
segments: number;
|
|
80
|
+
watermark: number;
|
|
81
|
+
lagMs: number | null;
|
|
82
|
+
updatedAt: number;
|
|
83
|
+
permissions: readonly GraphPermission[];
|
|
84
|
+
}>[]>;
|
|
85
|
+
query(graphId: unknown, datalog: unknown, options?: unknown): Promise<{
|
|
86
|
+
rows: Record<string, Value>[];
|
|
87
|
+
truncated: boolean;
|
|
88
|
+
watermark: number;
|
|
89
|
+
metrics: {
|
|
90
|
+
totalMs: number;
|
|
91
|
+
manifestMs: number;
|
|
92
|
+
tailMs: number;
|
|
93
|
+
evaluationMs: number;
|
|
94
|
+
waitedMs: number;
|
|
95
|
+
restarts: number;
|
|
96
|
+
segmentsTouched: number;
|
|
97
|
+
tuplesRead: number;
|
|
98
|
+
};
|
|
99
|
+
}>;
|
|
100
|
+
schema(graphId: unknown): Promise<{
|
|
101
|
+
fields: readonly Readonly<{
|
|
102
|
+
field: string;
|
|
103
|
+
valueTags: readonly import("../client.js").ObservedValueTag[];
|
|
104
|
+
}>[];
|
|
105
|
+
watermark: number;
|
|
106
|
+
}>;
|
|
107
|
+
status(graphId: unknown): Promise<import("./admin.js").GraphDetail>;
|
|
108
|
+
entity(graphId: unknown, entity: unknown): Promise<{
|
|
109
|
+
facts: {
|
|
110
|
+
field: string;
|
|
111
|
+
value: Value;
|
|
112
|
+
}[];
|
|
113
|
+
id: string;
|
|
114
|
+
watermark: number;
|
|
115
|
+
referencedBy: readonly Readonly<{
|
|
116
|
+
field: string;
|
|
117
|
+
entity: string;
|
|
118
|
+
}>[];
|
|
119
|
+
truncated: boolean;
|
|
120
|
+
names: Readonly<Record<string, string>>;
|
|
121
|
+
}>;
|
|
122
|
+
}
|