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,252 @@
|
|
|
1
|
+
import type { FactValue } from "./fact-value.js";
|
|
2
|
+
export declare const PROJECTION_NAME: RegExp;
|
|
3
|
+
export declare const DEFAULT_MAX_ENTITIES = 100;
|
|
4
|
+
export declare const MAX_BATCH_ENTITIES = 1000;
|
|
5
|
+
export declare const DEFAULT_MAX_ATTEMPTS = 5;
|
|
6
|
+
export declare const MAX_RETRY_ATTEMPTS = 100;
|
|
7
|
+
export declare const DEFAULT_INITIAL_BACKOFF_MS = 1000;
|
|
8
|
+
export declare const DEFAULT_MAX_BACKOFF_MS = 60000;
|
|
9
|
+
/**
|
|
10
|
+
* Selects which entity changes a projection delivers. When multiple criteria are set, an entity
|
|
11
|
+
* must match all of them (intersection). Omit to deliver every entity touched by any fact change.
|
|
12
|
+
*/
|
|
13
|
+
export type ProjectionSelector = Readonly<{
|
|
14
|
+
/**
|
|
15
|
+
* Entity kind(s) to watch: matches entities that hold a type fact for one of these kinds at the
|
|
16
|
+
* watermark, or whose type fact for one of these kinds was asserted or retracted in the batch.
|
|
17
|
+
*/
|
|
18
|
+
entityKind?: string | readonly string[];
|
|
19
|
+
/**
|
|
20
|
+
* Explicit field that holds an entity's kind (e.g. `"type"` or `"schema:entity:type"`). When
|
|
21
|
+
* omitted, uses `schema:entity:type` plus any field declared `schema:field:subfield_of` it.
|
|
22
|
+
*/
|
|
23
|
+
typeField?: string;
|
|
24
|
+
/** Fact-based filter: matches entities touched by an assertion or retraction of any named field. */
|
|
25
|
+
fields?: readonly string[];
|
|
26
|
+
/**
|
|
27
|
+
* Datalog-like filter evaluated at the watermark. Must bind at least one variable (`E` if
|
|
28
|
+
* present, otherwise the first variable). Also fires when a fact matching one of its predicates
|
|
29
|
+
* is retracted on an entity.
|
|
30
|
+
*/
|
|
31
|
+
where?: string;
|
|
32
|
+
}>;
|
|
33
|
+
export type ProjectionWorkerSinkConfig = Readonly<{
|
|
34
|
+
kind: "worker";
|
|
35
|
+
/** Target Worker name, wired automatically as a Workers RPC service binding. */
|
|
36
|
+
worker: string;
|
|
37
|
+
/** Optional named WorkerEntrypoint export on the target Worker. */
|
|
38
|
+
entrypoint?: string;
|
|
39
|
+
}>;
|
|
40
|
+
export type ProjectionR2SinkConfig = Readonly<{
|
|
41
|
+
kind: "r2";
|
|
42
|
+
/** Target R2 bucket name, wired automatically as an R2 binding. */
|
|
43
|
+
bucket: string;
|
|
44
|
+
/** Key prefix before `<ns>/<kind>/<id>.json`. Default `"entities/"`. */
|
|
45
|
+
prefix?: string;
|
|
46
|
+
}>;
|
|
47
|
+
export type ProjectionSinkConfig = ProjectionWorkerSinkConfig | ProjectionR2SinkConfig;
|
|
48
|
+
export type ProjectionBatchOptions = Readonly<{
|
|
49
|
+
/** Max deduplicated entity IDs per delivery batch (1..1,000; default 100). */
|
|
50
|
+
maxEntities?: number;
|
|
51
|
+
}>;
|
|
52
|
+
export type ProjectionRetryOptions = Readonly<{
|
|
53
|
+
/** Max delivery attempts before dead-lettering or entering error state (1..100; default 5). */
|
|
54
|
+
maxAttempts?: number;
|
|
55
|
+
/** Initial retry delay in ms (100..60,000; default 1,000). */
|
|
56
|
+
initialBackoffMs?: number;
|
|
57
|
+
/** Maximum exponential backoff delay in ms (initialBackoffMs..3,600,000; default 60,000). */
|
|
58
|
+
maxBackoffMs?: number;
|
|
59
|
+
}>;
|
|
60
|
+
export type ProjectionConfig = Readonly<{
|
|
61
|
+
/** Graph(s) to watch: a graph ID, a list of graph IDs, or `"*"` for every graph. */
|
|
62
|
+
graph: string | readonly string[];
|
|
63
|
+
/** Optional selector narrowing which entity changes are delivered. */
|
|
64
|
+
select?: ProjectionSelector;
|
|
65
|
+
/** Where to deliver matching entity IDs. */
|
|
66
|
+
sink: ProjectionSinkConfig;
|
|
67
|
+
batch?: ProjectionBatchOptions;
|
|
68
|
+
retry?: ProjectionRetryOptions;
|
|
69
|
+
/** Park batches in the dead-letter queue after retries exhaust (default `true`). */
|
|
70
|
+
deadLetter?: boolean;
|
|
71
|
+
/** Start delivering automatically when the graph publishes watermarks (default `true`). */
|
|
72
|
+
autoStart?: boolean;
|
|
73
|
+
}>;
|
|
74
|
+
export type ProjectionDefinitions = Readonly<Record<string, ProjectionConfig>>;
|
|
75
|
+
export type ProjectionDeliveryReason = "live" | "backfill" | "replay";
|
|
76
|
+
/** Plain structured-cloneable batch delivered over Workers RPC to `ProjectionSink.onProjectionBatch`. */
|
|
77
|
+
export type ProjectionDelivery = Readonly<{
|
|
78
|
+
projection: string;
|
|
79
|
+
graph: string;
|
|
80
|
+
watermark: number;
|
|
81
|
+
deliveryId: string;
|
|
82
|
+
reason: ProjectionDeliveryReason;
|
|
83
|
+
entities: readonly string[];
|
|
84
|
+
}>;
|
|
85
|
+
/** Interface implemented by a bound WorkerEntrypoint receiving projection batches over RPC. */
|
|
86
|
+
export interface ProjectionSink {
|
|
87
|
+
onProjectionBatch(batch: ProjectionDelivery): Promise<void> | void;
|
|
88
|
+
}
|
|
89
|
+
/** Built-in R2 projection object written per entity. Retracted entities keep `facts: []` as a tombstone. */
|
|
90
|
+
export type ProjectionEntityDocument = Readonly<{
|
|
91
|
+
id: string;
|
|
92
|
+
graph: string;
|
|
93
|
+
watermark: number;
|
|
94
|
+
updatedAt: number;
|
|
95
|
+
facts: readonly Readonly<{
|
|
96
|
+
field: string;
|
|
97
|
+
value: FactValue;
|
|
98
|
+
source: string;
|
|
99
|
+
}>[];
|
|
100
|
+
}>;
|
|
101
|
+
export type ProjectionStatus = "running" | "stopped" | "error";
|
|
102
|
+
export type ProjectionBackfillStatus = "idle" | "running" | "completed";
|
|
103
|
+
export type ProjectionBackfillSince = "current" | number;
|
|
104
|
+
export type ProjectionEventKind = "started" | "stopped" | "backfill_started" | "backfill_page" | "backfill_completed" | "batch_delivered" | "batch_failed" | "batch_dead_lettered" | "dead_letters_replayed" | "dead_letters_discarded";
|
|
105
|
+
export type ProjectionEvent = Readonly<{
|
|
106
|
+
id: number;
|
|
107
|
+
at: number;
|
|
108
|
+
kind: ProjectionEventKind;
|
|
109
|
+
reason: ProjectionDeliveryReason | null;
|
|
110
|
+
deliveryId: string | null;
|
|
111
|
+
watermark: number | null;
|
|
112
|
+
entityCount: number | null;
|
|
113
|
+
sampleEntities: readonly string[];
|
|
114
|
+
durationMs: number | null;
|
|
115
|
+
attempt: number | null;
|
|
116
|
+
detail: string | null;
|
|
117
|
+
}>;
|
|
118
|
+
export type ProjectionPendingBatch = Readonly<{
|
|
119
|
+
deliveryId: string;
|
|
120
|
+
watermark: number;
|
|
121
|
+
reason: ProjectionDeliveryReason;
|
|
122
|
+
entityCount: number;
|
|
123
|
+
sampleEntities: readonly string[];
|
|
124
|
+
attempts: number;
|
|
125
|
+
nextAttemptAt: number;
|
|
126
|
+
lastError: string | null;
|
|
127
|
+
createdAt: number;
|
|
128
|
+
}>;
|
|
129
|
+
export type ProjectionPartitionCursor = Readonly<{
|
|
130
|
+
partition: number;
|
|
131
|
+
lastSeq: number;
|
|
132
|
+
lastTs: number;
|
|
133
|
+
lastChunkKey: string;
|
|
134
|
+
}>;
|
|
135
|
+
export type ProjectionDeadLetter = Readonly<{
|
|
136
|
+
deliveryId: string;
|
|
137
|
+
watermark: number;
|
|
138
|
+
reason: ProjectionDeliveryReason;
|
|
139
|
+
entities: readonly string[];
|
|
140
|
+
attempts: number;
|
|
141
|
+
lastError: string;
|
|
142
|
+
createdAt: number;
|
|
143
|
+
failedAt: number;
|
|
144
|
+
}>;
|
|
145
|
+
/** Normalized projection descriptor serialized into the instance Worker's `PROJECTIONS_CONFIG` binding. */
|
|
146
|
+
export type ResolvedProjectionSelector = Readonly<{
|
|
147
|
+
entityKinds: readonly string[];
|
|
148
|
+
typeField: string | null;
|
|
149
|
+
fields: readonly string[];
|
|
150
|
+
where: string | null;
|
|
151
|
+
whereEntityVar: string | null;
|
|
152
|
+
whereFields: readonly string[];
|
|
153
|
+
}>;
|
|
154
|
+
export type ResolvedProjectionWorkerSink = Readonly<{
|
|
155
|
+
kind: "worker";
|
|
156
|
+
binding: string;
|
|
157
|
+
worker: string;
|
|
158
|
+
entrypoint?: string;
|
|
159
|
+
}>;
|
|
160
|
+
export type ResolvedProjectionR2Sink = Readonly<{
|
|
161
|
+
kind: "r2";
|
|
162
|
+
binding: string;
|
|
163
|
+
bucket: string;
|
|
164
|
+
prefix: string;
|
|
165
|
+
}>;
|
|
166
|
+
export type ResolvedProjectionSink = ResolvedProjectionWorkerSink | ResolvedProjectionR2Sink;
|
|
167
|
+
export type ResolvedProjectionConfig = Readonly<{
|
|
168
|
+
name: string;
|
|
169
|
+
graphs: readonly string[];
|
|
170
|
+
select: ResolvedProjectionSelector;
|
|
171
|
+
sink: ResolvedProjectionSink;
|
|
172
|
+
batch: Readonly<{
|
|
173
|
+
maxEntities: number;
|
|
174
|
+
}>;
|
|
175
|
+
retry: Readonly<{
|
|
176
|
+
maxAttempts: number;
|
|
177
|
+
initialBackoffMs: number;
|
|
178
|
+
maxBackoffMs: number;
|
|
179
|
+
}>;
|
|
180
|
+
deadLetter: boolean;
|
|
181
|
+
autoStart: boolean;
|
|
182
|
+
}>;
|
|
183
|
+
export type ProjectionState = Readonly<{
|
|
184
|
+
name: string;
|
|
185
|
+
graph: string;
|
|
186
|
+
status: ProjectionStatus;
|
|
187
|
+
sink: ResolvedProjectionSink;
|
|
188
|
+
select: ResolvedProjectionSelector;
|
|
189
|
+
cursorWatermark: number;
|
|
190
|
+
graphWatermark: number;
|
|
191
|
+
lagMs: number | null;
|
|
192
|
+
backfill: Readonly<{
|
|
193
|
+
status: ProjectionBackfillStatus;
|
|
194
|
+
watermark: number;
|
|
195
|
+
processed: number;
|
|
196
|
+
startedAt: number | null;
|
|
197
|
+
finishedAt: number | null;
|
|
198
|
+
}>;
|
|
199
|
+
counters: Readonly<{
|
|
200
|
+
deliveredBatches: number;
|
|
201
|
+
deliveredEntities: number;
|
|
202
|
+
failedDeliveries: number;
|
|
203
|
+
pendingBatches: number;
|
|
204
|
+
deadLetters: number;
|
|
205
|
+
}>;
|
|
206
|
+
lastDeliveryAt: number | null;
|
|
207
|
+
lastError: string | null;
|
|
208
|
+
}>;
|
|
209
|
+
export type ProjectionDetail = Readonly<{
|
|
210
|
+
state: ProjectionState;
|
|
211
|
+
config: Readonly<{
|
|
212
|
+
graphs: readonly string[];
|
|
213
|
+
batch: Readonly<{
|
|
214
|
+
maxEntities: number;
|
|
215
|
+
}>;
|
|
216
|
+
retry: Readonly<{
|
|
217
|
+
maxAttempts: number;
|
|
218
|
+
initialBackoffMs: number;
|
|
219
|
+
maxBackoffMs: number;
|
|
220
|
+
}>;
|
|
221
|
+
deadLetter: boolean;
|
|
222
|
+
autoStart: boolean;
|
|
223
|
+
}>;
|
|
224
|
+
partitions: readonly ProjectionPartitionCursor[];
|
|
225
|
+
pending: readonly ProjectionPendingBatch[];
|
|
226
|
+
deadLetters: readonly ProjectionDeadLetter[];
|
|
227
|
+
events: readonly ProjectionEvent[];
|
|
228
|
+
}>;
|
|
229
|
+
export type ParsedProjections = Readonly<{
|
|
230
|
+
configs: readonly ResolvedProjectionConfig[];
|
|
231
|
+
workerBindings: Readonly<Record<string, {
|
|
232
|
+
type: "worker";
|
|
233
|
+
worker: string;
|
|
234
|
+
exportName?: string;
|
|
235
|
+
}>>;
|
|
236
|
+
r2Bindings: Readonly<Record<string, {
|
|
237
|
+
type: "r2";
|
|
238
|
+
name: string;
|
|
239
|
+
}>>;
|
|
240
|
+
}>;
|
|
241
|
+
export declare const DEFAULT_R2_PREFIX = "entities/";
|
|
242
|
+
/**
|
|
243
|
+
* Deterministic R2 object key for the built-in R2 entity projection.
|
|
244
|
+
* Default layout: `entities/{ns}/{kind}/{id}.json` (e.g. `onepiece:crew:luffy` ->
|
|
245
|
+
* `entities/onepiece/crew/luffy.json`). Two-part IDs (`crew:luffy`) use `graph` as `{ns}`;
|
|
246
|
+
* single-segment IDs (`luffy`) use `graph` as `{ns}` and `"entity"` as `{kind}`.
|
|
247
|
+
*/
|
|
248
|
+
export declare function projectionEntityKey(prefix: string, graph: string, entity: string): string;
|
|
249
|
+
/** Whether a resolved projection config applies to `graphId`. */
|
|
250
|
+
export declare function projectionMatchesGraph(config: Pick<ResolvedProjectionConfig, "graphs">, graphId: string): boolean;
|
|
251
|
+
/** Reads `PROJECTIONS_CONFIG` from Worker env (safe when unset or empty). */
|
|
252
|
+
export declare function readProjectionsConfig(input: unknown): readonly ResolvedProjectionConfig[];
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Projections (RFD0016): static configuration, selector definitions, sink contracts, and runtime
|
|
2
|
+
// state types. Runs in both Node (when `cf` loads cloudflare.config.ts) and Workers.
|
|
3
|
+
export const PROJECTION_NAME = /^[a-z0-9][a-z0-9_-]{0,62}$/;
|
|
4
|
+
export const DEFAULT_MAX_ENTITIES = 100;
|
|
5
|
+
export const MAX_BATCH_ENTITIES = 1_000;
|
|
6
|
+
export const DEFAULT_MAX_ATTEMPTS = 5;
|
|
7
|
+
export const MAX_RETRY_ATTEMPTS = 100;
|
|
8
|
+
export const DEFAULT_INITIAL_BACKOFF_MS = 1_000;
|
|
9
|
+
export const DEFAULT_MAX_BACKOFF_MS = 60_000;
|
|
10
|
+
export const DEFAULT_R2_PREFIX = "entities/";
|
|
11
|
+
function encodeKeySegment(segment) {
|
|
12
|
+
if (segment === ".")
|
|
13
|
+
return "%2E";
|
|
14
|
+
if (segment === "..")
|
|
15
|
+
return "%2E%2E";
|
|
16
|
+
return encodeURIComponent(segment);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Deterministic R2 object key for the built-in R2 entity projection.
|
|
20
|
+
* Default layout: `entities/{ns}/{kind}/{id}.json` (e.g. `onepiece:crew:luffy` ->
|
|
21
|
+
* `entities/onepiece/crew/luffy.json`). Two-part IDs (`crew:luffy`) use `graph` as `{ns}`;
|
|
22
|
+
* single-segment IDs (`luffy`) use `graph` as `{ns}` and `"entity"` as `{kind}`.
|
|
23
|
+
*/
|
|
24
|
+
export function projectionEntityKey(prefix, graph, entity) {
|
|
25
|
+
const cleanPrefix = prefix === "" ? "" : prefix.endsWith("/") ? prefix : `${prefix}/`;
|
|
26
|
+
if (!entity.includes("://")) {
|
|
27
|
+
const [p0, p1, ...rest] = entity.split(":");
|
|
28
|
+
if (p0 !== undefined && p1 !== undefined && rest.length > 0) {
|
|
29
|
+
const id = rest.join(":");
|
|
30
|
+
if (p0.length > 0 && p1.length > 0 && id.length > 0) {
|
|
31
|
+
return `${cleanPrefix}${encodeKeySegment(p0)}/${encodeKeySegment(p1)}/${encodeKeySegment(id)}.json`;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
else if (p0 !== undefined && p1 !== undefined && p0.length > 0 && p1.length > 0) {
|
|
35
|
+
return `${cleanPrefix}${encodeKeySegment(graph)}/${encodeKeySegment(p0)}/${encodeKeySegment(p1)}.json`;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return `${cleanPrefix}${encodeKeySegment(graph)}/entity/${encodeKeySegment(entity)}.json`;
|
|
39
|
+
}
|
|
40
|
+
/** Whether a resolved projection config applies to `graphId`. */
|
|
41
|
+
export function projectionMatchesGraph(config, graphId) {
|
|
42
|
+
return config.graphs.includes("*") || config.graphs.includes(graphId);
|
|
43
|
+
}
|
|
44
|
+
/** Reads `PROJECTIONS_CONFIG` from Worker env (safe when unset or empty). */
|
|
45
|
+
export function readProjectionsConfig(input) {
|
|
46
|
+
if (input === undefined || input === null)
|
|
47
|
+
return [];
|
|
48
|
+
if (!Array.isArray(input))
|
|
49
|
+
return [];
|
|
50
|
+
return input.filter((entry) => typeof entry === "object" && entry !== null && "name" in entry && "graphs" in entry && "sink" in entry);
|
|
51
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type ParseResult } from "./result.js";
|
|
2
|
+
/** What the query read: scans the engine made, fact writes they read, and what reading them took from R2 and caches. */
|
|
3
|
+
export type ReadCosts = Readonly<{
|
|
4
|
+
scans: number;
|
|
5
|
+
tuplesRead: number;
|
|
6
|
+
/** Segments a scan read blocks of, and point lookups that skipped a segment by its filter. */
|
|
7
|
+
segmentsTouched: number;
|
|
8
|
+
segmentsSkipped?: number;
|
|
9
|
+
blocksRead: number;
|
|
10
|
+
bytesRead: number;
|
|
11
|
+
/** Ranged R2 reads, reads answered by the colo's cache, and by the isolate's memory. */
|
|
12
|
+
r2Gets: number;
|
|
13
|
+
edgeHits: number;
|
|
14
|
+
cacheHits: number;
|
|
15
|
+
}>;
|
|
16
|
+
export type QueryMetrics = Readonly<{
|
|
17
|
+
/** From reading the request to the last row. */
|
|
18
|
+
totalMs: number;
|
|
19
|
+
/** Finding the watermark's manifest, reading the caller's writes above it, and evaluating. */
|
|
20
|
+
manifestMs: number;
|
|
21
|
+
tailMs: number;
|
|
22
|
+
evaluationMs: number;
|
|
23
|
+
/** How long a snapshot read waited for the watermark to reach the caller's writes. */
|
|
24
|
+
waitedMs: number;
|
|
25
|
+
/** Reads started again because a partition trimmed rows the read needed. */
|
|
26
|
+
restarts: number;
|
|
27
|
+
/** The caller's transactions above the watermark the answer includes. */
|
|
28
|
+
tailTxs: number;
|
|
29
|
+
source: ReadCosts;
|
|
30
|
+
}>;
|
|
31
|
+
export declare function parseQueryMetrics(input: unknown, path?: string): ParseResult<QueryMetrics>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// What a query cost, as the graph measured it: where its time went, and what it read.
|
|
2
|
+
import { isRecord, parsed, rejected } from "./result.js";
|
|
3
|
+
const TIMINGS = ["totalMs", "manifestMs", "tailMs", "evaluationMs", "waitedMs", "restarts", "tailTxs"];
|
|
4
|
+
const COSTS = ["scans", "tuplesRead", "segmentsTouched", "blocksRead", "bytesRead", "r2Gets", "edgeHits", "cacheHits"];
|
|
5
|
+
export function parseQueryMetrics(input, path = "metrics") {
|
|
6
|
+
if (!isRecord(input) || !isRecord(input["source"]))
|
|
7
|
+
return rejected(path, "expected query metrics with read costs");
|
|
8
|
+
const source = input["source"];
|
|
9
|
+
for (const name of TIMINGS)
|
|
10
|
+
if (!isCount(input[name]))
|
|
11
|
+
return rejected(`${path}.${name}`, "expected a non-negative integer");
|
|
12
|
+
for (const name of COSTS)
|
|
13
|
+
if (!isCount(source[name]))
|
|
14
|
+
return rejected(`${path}.source.${name}`, "expected a non-negative integer");
|
|
15
|
+
const skipped = source["segmentsSkipped"];
|
|
16
|
+
if (skipped !== undefined && !isCount(skipped))
|
|
17
|
+
return rejected(`${path}.source.segmentsSkipped`, "expected a non-negative integer");
|
|
18
|
+
const count = (record, name) => {
|
|
19
|
+
const value = record[name];
|
|
20
|
+
return isCount(value) ? value : 0;
|
|
21
|
+
};
|
|
22
|
+
return parsed(Object.freeze({
|
|
23
|
+
totalMs: count(input, "totalMs"), manifestMs: count(input, "manifestMs"), tailMs: count(input, "tailMs"),
|
|
24
|
+
evaluationMs: count(input, "evaluationMs"), waitedMs: count(input, "waitedMs"), restarts: count(input, "restarts"), tailTxs: count(input, "tailTxs"),
|
|
25
|
+
source: Object.freeze({
|
|
26
|
+
scans: count(source, "scans"), tuplesRead: count(source, "tuplesRead"), segmentsTouched: count(source, "segmentsTouched"),
|
|
27
|
+
...(skipped === undefined ? {} : { segmentsSkipped: skipped }),
|
|
28
|
+
blocksRead: count(source, "blocksRead"), bytesRead: count(source, "bytesRead"),
|
|
29
|
+
r2Gets: count(source, "r2Gets"), edgeHits: count(source, "edgeHits"), cacheHits: count(source, "cacheHits"),
|
|
30
|
+
}),
|
|
31
|
+
}));
|
|
32
|
+
}
|
|
33
|
+
function isCount(n) {
|
|
34
|
+
return typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
|
|
35
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type ParseResult } from "./result.js";
|
|
2
|
+
declare const readTokenBrand: unique symbol;
|
|
3
|
+
export type ReadToken = string & {
|
|
4
|
+
readonly [readTokenBrand]: "ReadToken";
|
|
5
|
+
};
|
|
6
|
+
export type ReadTokenState = Readonly<{
|
|
7
|
+
session: string;
|
|
8
|
+
/** The highest key time the session has seen. */
|
|
9
|
+
after: number;
|
|
10
|
+
/**
|
|
11
|
+
* The latest watermark the session has read at. Its reads take no older manifest, though an
|
|
12
|
+
* isolate may hold one: so they never go back in time, and the session's writes in partitions
|
|
13
|
+
* the token no longer names stay visible.
|
|
14
|
+
*/
|
|
15
|
+
watermark: number;
|
|
16
|
+
/** Partitions that may hold the session's writes above `watermark`, ascending. */
|
|
17
|
+
partitions: readonly number[];
|
|
18
|
+
}>;
|
|
19
|
+
export declare const MAX_READ_TOKEN_LENGTH = 4096;
|
|
20
|
+
/** Maximum opt-in manifest staleness (5 minutes) a reader may accept for stale-while-revalidate reads. */
|
|
21
|
+
export declare const MAX_STALENESS_MS = 300000;
|
|
22
|
+
/**
|
|
23
|
+
* How fresh a read is. "own-writes" (the default): the graph's latest watermark, plus the caller's
|
|
24
|
+
* own writes above it. "snapshot": the watermark alone, once it has passed the caller's writes.
|
|
25
|
+
*/
|
|
26
|
+
export type Consistency = "own-writes" | "snapshot";
|
|
27
|
+
export declare function parseConsistency(input: unknown, path?: string): ParseResult<Consistency>;
|
|
28
|
+
export declare function parseMaxStalenessMs(input: unknown, path?: string): ParseResult<number | undefined>;
|
|
29
|
+
/** A new session: 16 random bytes, base64url. */
|
|
30
|
+
export declare function newSession(): string;
|
|
31
|
+
export declare function newReadToken(session?: string): ReadTokenState;
|
|
32
|
+
export declare function encodeReadToken(state: ReadTokenState): ReadToken;
|
|
33
|
+
/** A token's fields, as the caller sent them; the graph checks its partitions against its own count. */
|
|
34
|
+
export declare function parseReadToken(input: unknown, path?: string): ParseResult<ReadTokenState>;
|
|
35
|
+
/** What a session has seen, from two of its tokens: the later clock and watermark, and every partition either names. */
|
|
36
|
+
export declare function mergeReadTokens(a: ReadTokenState, b: ReadTokenState): ReadTokenState;
|
|
37
|
+
export {};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Read tokens (RFD0008, "Reads"): what a caller sends so that it reads its own writes, and gets
|
|
2
|
+
// back with every answer.
|
|
3
|
+
//
|
|
4
|
+
// A token names the caller's session, the highest key time it has seen (its own writes, and the
|
|
5
|
+
// watermarks it read at), the latest watermark it read at, and the partitions that may hold its
|
|
6
|
+
// writes above that watermark. On the wire it is "rw1." and base64url JSON. A client that runs
|
|
7
|
+
// calls at once merges the tokens they return: two tokens of one session merge into one that has
|
|
8
|
+
// seen what both saw.
|
|
9
|
+
import { isRecord, parsed, rejected } from "./result.js";
|
|
10
|
+
const PREFIX = "rw1.";
|
|
11
|
+
const SESSION = /^[A-Za-z0-9_-]{8,64}$/;
|
|
12
|
+
export const MAX_READ_TOKEN_LENGTH = 4_096;
|
|
13
|
+
/** Maximum opt-in manifest staleness (5 minutes) a reader may accept for stale-while-revalidate reads. */
|
|
14
|
+
export const MAX_STALENESS_MS = 300_000;
|
|
15
|
+
export function parseConsistency(input, path = "consistency") {
|
|
16
|
+
if (input === undefined)
|
|
17
|
+
return parsed("own-writes");
|
|
18
|
+
if (input !== "own-writes" && input !== "snapshot")
|
|
19
|
+
return rejected(path, "consistency must be own-writes or snapshot");
|
|
20
|
+
return parsed(input);
|
|
21
|
+
}
|
|
22
|
+
export function parseMaxStalenessMs(input, path = "maxStalenessMs") {
|
|
23
|
+
if (input === undefined)
|
|
24
|
+
return parsed(undefined);
|
|
25
|
+
if (typeof input !== "number" || !Number.isSafeInteger(input) || input < 0 || input > MAX_STALENESS_MS) {
|
|
26
|
+
return rejected(path, `maxStalenessMs must be an integer between 0 and ${MAX_STALENESS_MS}`);
|
|
27
|
+
}
|
|
28
|
+
return parsed(input);
|
|
29
|
+
}
|
|
30
|
+
/** A new session: 16 random bytes, base64url. */
|
|
31
|
+
export function newSession() {
|
|
32
|
+
return base64url(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(16))));
|
|
33
|
+
}
|
|
34
|
+
export function newReadToken(session = newSession()) {
|
|
35
|
+
if (!SESSION.test(session))
|
|
36
|
+
throw new RangeError("a read token session is 8 to 64 base64url characters");
|
|
37
|
+
return Object.freeze({ session, after: 0, watermark: 0, partitions: Object.freeze([]) });
|
|
38
|
+
}
|
|
39
|
+
function isEncodedReadToken(value) {
|
|
40
|
+
return value.startsWith(PREFIX);
|
|
41
|
+
}
|
|
42
|
+
export function encodeReadToken(state) {
|
|
43
|
+
const encoded = `${PREFIX}${base64url(JSON.stringify({ s: state.session, a: state.after, w: state.watermark, p: state.partitions }))}`;
|
|
44
|
+
if (!isEncodedReadToken(encoded))
|
|
45
|
+
throw new Error("encoded read token missing prefix");
|
|
46
|
+
return encoded;
|
|
47
|
+
}
|
|
48
|
+
/** A token's fields, as the caller sent them; the graph checks its partitions against its own count. */
|
|
49
|
+
export function parseReadToken(input, path = "readToken") {
|
|
50
|
+
if (typeof input !== "string" || !input.startsWith(PREFIX) || input.length > MAX_READ_TOKEN_LENGTH) {
|
|
51
|
+
return rejected(path, "expected a read token from an earlier answer");
|
|
52
|
+
}
|
|
53
|
+
let raw;
|
|
54
|
+
try {
|
|
55
|
+
const b64 = input.slice(PREFIX.length).replaceAll("-", "+").replaceAll("_", "/");
|
|
56
|
+
raw = JSON.parse(atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4)));
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return rejected(path, "read token is not valid base64url JSON");
|
|
60
|
+
}
|
|
61
|
+
if (!isRecord(raw))
|
|
62
|
+
return rejected(path, "read token is not an object");
|
|
63
|
+
const { s, a, w, p } = raw;
|
|
64
|
+
if (typeof s !== "string" || !SESSION.test(s))
|
|
65
|
+
return rejected(path, "read token session is invalid");
|
|
66
|
+
if (typeof a !== "number" || !Number.isSafeInteger(a) || a < 0)
|
|
67
|
+
return rejected(path, "read token clock is invalid");
|
|
68
|
+
if (typeof w !== "number" || !Number.isSafeInteger(w) || w < 0)
|
|
69
|
+
return rejected(path, "read token watermark is invalid");
|
|
70
|
+
if (!Array.isArray(p))
|
|
71
|
+
return rejected(path, "read token partitions are invalid");
|
|
72
|
+
const partitions = new Set();
|
|
73
|
+
for (const n of p) {
|
|
74
|
+
if (typeof n !== "number" || !Number.isSafeInteger(n) || n < 0)
|
|
75
|
+
return rejected(path, "read token partitions are invalid");
|
|
76
|
+
partitions.add(n);
|
|
77
|
+
}
|
|
78
|
+
return parsed(Object.freeze({ session: s, after: a, watermark: w, partitions: Object.freeze([...partitions].sort((x, y) => x - y)) }));
|
|
79
|
+
}
|
|
80
|
+
/** What a session has seen, from two of its tokens: the later clock and watermark, and every partition either names. */
|
|
81
|
+
export function mergeReadTokens(a, b) {
|
|
82
|
+
if (a.session !== b.session)
|
|
83
|
+
throw new RangeError("read tokens of different sessions cannot be merged");
|
|
84
|
+
return Object.freeze({
|
|
85
|
+
session: a.session,
|
|
86
|
+
after: Math.max(a.after, b.after),
|
|
87
|
+
watermark: Math.max(a.watermark, b.watermark),
|
|
88
|
+
partitions: Object.freeze([...new Set([...a.partitions, ...b.partitions])].sort((x, y) => x - y)),
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
function base64url(binary) {
|
|
92
|
+
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
|
|
93
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export type ParseError = Readonly<{
|
|
2
|
+
path: string;
|
|
3
|
+
message: string;
|
|
4
|
+
offset?: number;
|
|
5
|
+
}>;
|
|
6
|
+
/**
|
|
7
|
+
* What an operation answers: its value, or why it has none. A plain object, so it is the same in
|
|
8
|
+
* process, over Workers RPC and from a Durable Object's method (RFD0015).
|
|
9
|
+
*/
|
|
10
|
+
export type Result<T, E> = Readonly<{
|
|
11
|
+
ok: true;
|
|
12
|
+
value: T;
|
|
13
|
+
}> | Readonly<{
|
|
14
|
+
ok: false;
|
|
15
|
+
error: E;
|
|
16
|
+
}>;
|
|
17
|
+
export type ParseResult<T> = Result<T, ParseError>;
|
|
18
|
+
export declare function ok<T>(value: T): Result<T, never>;
|
|
19
|
+
export declare function err<E>(error: E): Result<never, E>;
|
|
20
|
+
export declare function parsed<T>(value: T): ParseResult<T>;
|
|
21
|
+
export declare function rejected<T = never>(path: string, message: string, offset?: number): ParseResult<T>;
|
|
22
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export function ok(value) {
|
|
2
|
+
return { ok: true, value };
|
|
3
|
+
}
|
|
4
|
+
export function err(error) {
|
|
5
|
+
return { ok: false, error };
|
|
6
|
+
}
|
|
7
|
+
export function parsed(value) {
|
|
8
|
+
return { ok: true, value };
|
|
9
|
+
}
|
|
10
|
+
export function rejected(path, message, offset) {
|
|
11
|
+
const error = offset === undefined ? { path, message } : { path, message, offset };
|
|
12
|
+
return { ok: false, error };
|
|
13
|
+
}
|
|
14
|
+
export function isRecord(value) {
|
|
15
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
16
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { FactValue } from "./fact-value.js";
|
|
2
|
+
import { type Consistency, type ReadToken } from "./read-token.js";
|
|
3
|
+
import { type ParseResult } from "./result.js";
|
|
4
|
+
export type ObservedValueTag = FactValue["type"];
|
|
5
|
+
export type ObservedField = Readonly<{
|
|
6
|
+
field: string;
|
|
7
|
+
/** Ascending. */
|
|
8
|
+
valueTags: readonly ObservedValueTag[];
|
|
9
|
+
}>;
|
|
10
|
+
export type GraphSchemaObservation = Readonly<{
|
|
11
|
+
/** Every write in an epoch at or below this one is reflected, with the caller's own writes above it. */
|
|
12
|
+
watermark: number;
|
|
13
|
+
consistency: Consistency;
|
|
14
|
+
readToken: ReadToken;
|
|
15
|
+
/** Ascending by field. */
|
|
16
|
+
fields: readonly ObservedField[];
|
|
17
|
+
}>;
|
|
18
|
+
/** Fields one schema answer lists, at most. */
|
|
19
|
+
export declare const MAX_SCHEMA_FIELDS = 10000;
|
|
20
|
+
export declare function parseGraphSchemaObservation(input: unknown): ParseResult<GraphSchemaObservation>;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// The schema a graph shows: the fields its active facts use, and the tags of their values, at one
|
|
2
|
+
// read. It is observed: a graph registers nothing. What a graph declares of its fields and classes
|
|
3
|
+
// is facts in the schema:* vocabulary (vocabulary.ts), read apart from this.
|
|
4
|
+
import { parseUri } from "./identifiers.js";
|
|
5
|
+
import { encodeReadToken, parseConsistency, parseReadToken } from "./read-token.js";
|
|
6
|
+
import { isRecord, rejected } from "./result.js";
|
|
7
|
+
/** Fields one schema answer lists, at most. */
|
|
8
|
+
export const MAX_SCHEMA_FIELDS = 10_000;
|
|
9
|
+
const VALUE_TAG_MAP = new Map([
|
|
10
|
+
["null", "null"], ["text", "text"], ["number", "number"], ["decimal", "decimal"], ["boolean", "boolean"],
|
|
11
|
+
["bytes", "bytes"], ["reference", "reference"], ["date", "date"], ["date_time", "date_time"], ["list", "list"], ["map", "map"],
|
|
12
|
+
]);
|
|
13
|
+
export function parseGraphSchemaObservation(input) {
|
|
14
|
+
if (!isRecord(input))
|
|
15
|
+
return rejected("schema", "expected an observed graph schema object");
|
|
16
|
+
const watermark = input["watermark"];
|
|
17
|
+
if (typeof watermark !== "number" || !Number.isSafeInteger(watermark) || watermark < 0)
|
|
18
|
+
return rejected("schema.watermark", "expected a non-negative watermark");
|
|
19
|
+
const consistency = parseConsistency(input["consistency"], "schema.consistency");
|
|
20
|
+
if (!consistency.ok || input["consistency"] === undefined)
|
|
21
|
+
return rejected("schema.consistency", "expected own-writes or snapshot");
|
|
22
|
+
const readToken = parseReadToken(input["readToken"], "schema.readToken");
|
|
23
|
+
if (!readToken.ok)
|
|
24
|
+
return readToken;
|
|
25
|
+
const rawFields = input["fields"];
|
|
26
|
+
if (!Array.isArray(rawFields) || rawFields.length > MAX_SCHEMA_FIELDS)
|
|
27
|
+
return rejected("schema.fields", "expected a bounded observed field list");
|
|
28
|
+
const fields = [];
|
|
29
|
+
for (const [index, rawField] of rawFields.entries()) {
|
|
30
|
+
if (!isRecord(rawField))
|
|
31
|
+
return rejected(`schema.fields[${index}]`, "expected an observed field object");
|
|
32
|
+
const field = parseUri(rawField["field"], `schema.fields[${index}].field`);
|
|
33
|
+
if (!field.ok || field.value !== rawField["field"])
|
|
34
|
+
return rejected(`schema.fields[${index}].field`, "expected a canonical field identifier");
|
|
35
|
+
const previous = fields.at(-1)?.field;
|
|
36
|
+
if (previous !== undefined && !(previous < field.value))
|
|
37
|
+
return rejected(`schema.fields[${index}].field`, "fields must be unique and ascending");
|
|
38
|
+
const rawTags = rawField["valueTags"];
|
|
39
|
+
if (!Array.isArray(rawTags) || rawTags.length === 0)
|
|
40
|
+
return rejected(`schema.fields[${index}].valueTags`, "expected at least one observed value tag");
|
|
41
|
+
const tags = [];
|
|
42
|
+
for (const [tagIndex, rawTag] of rawTags.entries()) {
|
|
43
|
+
const previousTag = tags.at(-1);
|
|
44
|
+
const parsedTag = typeof rawTag === "string" ? VALUE_TAG_MAP.get(rawTag) : undefined;
|
|
45
|
+
if (parsedTag === undefined || (previousTag !== undefined && !(previousTag < parsedTag))) {
|
|
46
|
+
return rejected(`schema.fields[${index}].valueTags[${tagIndex}]`, "expected unique, ascending FactValue tags");
|
|
47
|
+
}
|
|
48
|
+
tags.push(parsedTag);
|
|
49
|
+
}
|
|
50
|
+
fields.push(Object.freeze({ field: field.value, valueTags: Object.freeze(tags) }));
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
ok: true,
|
|
54
|
+
value: Object.freeze({
|
|
55
|
+
watermark,
|
|
56
|
+
consistency: consistency.value,
|
|
57
|
+
readToken: encodeReadToken(readToken.value),
|
|
58
|
+
fields: Object.freeze(fields),
|
|
59
|
+
}),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export function compareCodeUnits(left, right) {
|
|
2
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
3
|
+
}
|
|
4
|
+
export function compareUnicodeScalars(left, right) {
|
|
5
|
+
const leftPoints = Array.from(left, (character) => character.codePointAt(0) ?? 0);
|
|
6
|
+
const rightPoints = Array.from(right, (character) => character.codePointAt(0) ?? 0);
|
|
7
|
+
const length = Math.min(leftPoints.length, rightPoints.length);
|
|
8
|
+
for (let index = 0; index < length; index += 1) {
|
|
9
|
+
const leftPoint = leftPoints[index] ?? 0;
|
|
10
|
+
const rightPoint = rightPoints[index] ?? 0;
|
|
11
|
+
if (leftPoint !== rightPoint)
|
|
12
|
+
return leftPoint < rightPoint ? -1 : 1;
|
|
13
|
+
}
|
|
14
|
+
return leftPoints.length < rightPoints.length ? -1 : leftPoints.length > rightPoints.length ? 1 : 0;
|
|
15
|
+
}
|