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,60 @@
|
|
|
1
|
+
import type { FactLookup, FactSource, FactTuple, FieldIndex } from "../datalog/fact-source.js";
|
|
2
|
+
import type { Uri } from "../domain/identifiers.js";
|
|
3
|
+
import { type IndexedFact } from "./facts.js";
|
|
4
|
+
import { type ReadMetrics, type SegmentHeader, type SegmentRef, type SegmentStore } from "./segment.js";
|
|
5
|
+
export declare class TupleBudgetExceeded extends Error {
|
|
6
|
+
constructor();
|
|
7
|
+
}
|
|
8
|
+
/** `segmentsSkipped`: segments a point lookup did not read because their filter ruled its key out. */
|
|
9
|
+
export type SourceMetrics = ReadMetrics & {
|
|
10
|
+
scans: number;
|
|
11
|
+
tuplesRead: number;
|
|
12
|
+
segmentsTouched: number;
|
|
13
|
+
segmentsSkipped?: number;
|
|
14
|
+
};
|
|
15
|
+
/** Shared in-flight segment header and block reads, deduplicated across concurrent queries in a batch. */
|
|
16
|
+
export type SegmentFlight = Readonly<{
|
|
17
|
+
headers: Map<string, Promise<SegmentHeader>>;
|
|
18
|
+
blocks: Map<string, Promise<readonly unknown[]>>;
|
|
19
|
+
}>;
|
|
20
|
+
export declare function createSegmentFlight(): SegmentFlight;
|
|
21
|
+
export declare class SegmentFactSource implements FactSource {
|
|
22
|
+
private readonly store;
|
|
23
|
+
private readonly segments;
|
|
24
|
+
/** The caller's writes above the watermark. */
|
|
25
|
+
private readonly tail;
|
|
26
|
+
readonly metrics: SourceMetrics;
|
|
27
|
+
private readonly maxTs;
|
|
28
|
+
/** The fields this query has read whole, by entity, for joins. */
|
|
29
|
+
private readonly indexes;
|
|
30
|
+
/** Writes that scans in flight are sure to read, not counted in `tuplesRead` yet. */
|
|
31
|
+
private reading;
|
|
32
|
+
/** The headers and blocks this query (or batch) has asked for: scans in flight together share each read. */
|
|
33
|
+
private readonly headers;
|
|
34
|
+
private readonly blocks;
|
|
35
|
+
constructor(store: SegmentStore, segments: Readonly<Record<string, readonly SegmentRef[]>>, watermark: number,
|
|
36
|
+
/** The caller's writes above the watermark. */
|
|
37
|
+
tail: readonly IndexedFact[], metrics: SourceMetrics, flight?: SegmentFlight);
|
|
38
|
+
scan(lookup: FactLookup, signal?: AbortSignal): AsyncIterable<FactTuple>;
|
|
39
|
+
scanAll(lookup: FactLookup, signal?: AbortSignal): Promise<readonly FactTuple[]>;
|
|
40
|
+
fieldIndex(lookup: Readonly<{
|
|
41
|
+
field: Uri;
|
|
42
|
+
lookups: number;
|
|
43
|
+
}>, signal?: AbortSignal): Promise<FieldIndex | null>;
|
|
44
|
+
/** At most how many writes a whole scan of `field` reads: its blocks' entries, and the caller's writes. */
|
|
45
|
+
private entriesOf;
|
|
46
|
+
private readIndex;
|
|
47
|
+
/** A field's active facts at the watermark, with the caller's own writes: what the schema reads when tag counts leave a tag open. */
|
|
48
|
+
activeFacts(field: string, signal?: AbortSignal): Promise<IndexedFact[]>;
|
|
49
|
+
/** One entity's active facts in `field` at the watermark, using segment Bloom filters. */
|
|
50
|
+
entityFacts(field: string, entity: string, signal?: AbortSignal): Promise<IndexedFact[]>;
|
|
51
|
+
private read;
|
|
52
|
+
private header;
|
|
53
|
+
private block;
|
|
54
|
+
/** One read per key for the whole query; asking again counts as a cache hit. */
|
|
55
|
+
private shared;
|
|
56
|
+
/** The segments of the field's bucket that hold writes at or below the watermark. */
|
|
57
|
+
private refsOf;
|
|
58
|
+
private fromEav;
|
|
59
|
+
private fromAve;
|
|
60
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
// The Datalog engine's view of the graph at a watermark, plus the caller's own newer writes.
|
|
2
|
+
//
|
|
3
|
+
// Each scan reads the segments of its field's bucket: with an entity, the EAV blocks under
|
|
4
|
+
// (field, entity); with only a value, the AVE blocks under (field, value); with neither, every
|
|
5
|
+
// EAV block of the field. Blocks and the entries inside them are found by binary search. Every write of a tuple sorts under the same prefix, so a scan sees all
|
|
6
|
+
// of them and keeps each tuple whose last write in key order asserts it.
|
|
7
|
+
import { boundValue, factValueToDatalogValues, matchedItem, referenceValue, sameDatalogValue } from "../datalog/value.js";
|
|
8
|
+
import { MAX_QUERY_TUPLES } from "./constants.js";
|
|
9
|
+
import { BUCKETS, bucketOf, compareFacts, lastWrites, tupleKey } from "./facts.js";
|
|
10
|
+
import { epochOf, lastTsOf } from "./keys.js";
|
|
11
|
+
import { aveEntriesOf, aveEntry, avePrefix, blocksFor, BOUND_CHARS, eavFact, eavPrefix, entriesUnder, readBlock, readHeader, segmentMayHold, } from "./segment.js";
|
|
12
|
+
/**
|
|
13
|
+
* What a scan by entity costs, in entries of a whole-field scan: a field is read whole for a join
|
|
14
|
+
* when that reads fewer entries than this many per lookup it saves (measured on the onepiece index).
|
|
15
|
+
*/
|
|
16
|
+
const LOOKUP_ENTRIES = 3;
|
|
17
|
+
export class TupleBudgetExceeded extends Error {
|
|
18
|
+
constructor() {
|
|
19
|
+
super(`query reads more than ${MAX_QUERY_TUPLES} fact writes`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export function createSegmentFlight() {
|
|
23
|
+
return { headers: new Map(), blocks: new Map() };
|
|
24
|
+
}
|
|
25
|
+
export class SegmentFactSource {
|
|
26
|
+
store;
|
|
27
|
+
segments;
|
|
28
|
+
tail;
|
|
29
|
+
metrics;
|
|
30
|
+
maxTs;
|
|
31
|
+
/** The fields this query has read whole, by entity, for joins. */
|
|
32
|
+
indexes = new Map();
|
|
33
|
+
/** Writes that scans in flight are sure to read, not counted in `tuplesRead` yet. */
|
|
34
|
+
reading = 0;
|
|
35
|
+
/** The headers and blocks this query (or batch) has asked for: scans in flight together share each read. */
|
|
36
|
+
headers;
|
|
37
|
+
blocks;
|
|
38
|
+
constructor(store, segments, watermark,
|
|
39
|
+
/** The caller's writes above the watermark. */
|
|
40
|
+
tail, metrics, flight) {
|
|
41
|
+
this.store = store;
|
|
42
|
+
this.segments = segments;
|
|
43
|
+
this.tail = tail;
|
|
44
|
+
this.metrics = metrics;
|
|
45
|
+
this.maxTs = lastTsOf(watermark);
|
|
46
|
+
this.headers = flight?.headers ?? new Map();
|
|
47
|
+
this.blocks = flight?.blocks ?? new Map();
|
|
48
|
+
}
|
|
49
|
+
async *scan(lookup, signal) {
|
|
50
|
+
yield* await this.scanAll(lookup, signal);
|
|
51
|
+
}
|
|
52
|
+
async scanAll(lookup, signal) {
|
|
53
|
+
this.metrics.scans++;
|
|
54
|
+
const field = lookup.field;
|
|
55
|
+
if (lookup.entity !== undefined) {
|
|
56
|
+
if (lookup.entity.type !== "string")
|
|
57
|
+
return [];
|
|
58
|
+
const entity = lookup.entity.value;
|
|
59
|
+
return [...this.fromEav(await this.read("eav", field, eavPrefix(field, entity), signal, (f) => f.entity === entity, true), lookup)];
|
|
60
|
+
}
|
|
61
|
+
if (lookup.value !== undefined) {
|
|
62
|
+
const dv = lookup.value;
|
|
63
|
+
const entries = (await this.read("ave", field, avePrefix(field, dv), signal, undefined, true)).map(aveEntry).filter((e) => e.fact.field === field && sameDatalogValue(e.dv, dv));
|
|
64
|
+
const tail = this.tail.filter((f) => f.field === field).flatMap(aveEntriesOf).filter((e) => sameDatalogValue(e.dv, dv));
|
|
65
|
+
return [...this.fromAve([...entries.filter((e) => e.fact.ts <= this.maxTs), ...tail])];
|
|
66
|
+
}
|
|
67
|
+
return [...this.fromEav(await this.read("eav", field, eavPrefix(field), signal, () => true, false), lookup)];
|
|
68
|
+
}
|
|
69
|
+
async fieldIndex(lookup, signal) {
|
|
70
|
+
const field = lookup.field;
|
|
71
|
+
const held = this.indexes.get(field);
|
|
72
|
+
if (held !== undefined)
|
|
73
|
+
return held;
|
|
74
|
+
const entries = await this.entriesOf(field);
|
|
75
|
+
if (entries > lookup.lookups * LOOKUP_ENTRIES || this.metrics.tuplesRead + entries > MAX_QUERY_TUPLES)
|
|
76
|
+
return null;
|
|
77
|
+
const index = this.readIndex(field, signal);
|
|
78
|
+
this.indexes.set(field, index);
|
|
79
|
+
return index;
|
|
80
|
+
}
|
|
81
|
+
/** At most how many writes a whole scan of `field` reads: its blocks' entries, and the caller's writes. */
|
|
82
|
+
async entriesOf(field) {
|
|
83
|
+
const prefix = eavPrefix(field);
|
|
84
|
+
const headers = await Promise.all(this.refsOf(field).map((ref) => this.header(ref)));
|
|
85
|
+
const stored = headers.reduce((n, header) => n + blocksFor(header.eav, prefix).reduce((m, b) => m + b.entries, 0), 0);
|
|
86
|
+
return stored + this.tail.filter((f) => f.field === field).length;
|
|
87
|
+
}
|
|
88
|
+
async readIndex(field, signal) {
|
|
89
|
+
this.metrics.scans++;
|
|
90
|
+
const writes = await this.read("eav", field, eavPrefix(field), signal, () => true, false);
|
|
91
|
+
const index = new Map();
|
|
92
|
+
for (const tuple of this.fromEav(writes, {})) {
|
|
93
|
+
const tuples = index.get(tuple.entity.value);
|
|
94
|
+
if (tuples === undefined)
|
|
95
|
+
index.set(tuple.entity.value, [tuple]);
|
|
96
|
+
else
|
|
97
|
+
tuples.push(tuple);
|
|
98
|
+
}
|
|
99
|
+
return index;
|
|
100
|
+
}
|
|
101
|
+
/** A field's active facts at the watermark, with the caller's own writes: what the schema reads when tag counts leave a tag open. */
|
|
102
|
+
async activeFacts(field, signal) {
|
|
103
|
+
this.metrics.scans++;
|
|
104
|
+
return lastWrites(await this.read("eav", field, eavPrefix(field), signal, () => true, false)).filter((f) => !f.retraction);
|
|
105
|
+
}
|
|
106
|
+
/** One entity's active facts in `field` at the watermark, using segment Bloom filters. */
|
|
107
|
+
async entityFacts(field, entity, signal) {
|
|
108
|
+
this.metrics.scans++;
|
|
109
|
+
return lastWrites(await this.read("eav", field, eavPrefix(field, entity), signal, (f) => f.entity === entity, true)).filter((f) => !f.retraction);
|
|
110
|
+
}
|
|
111
|
+
async read(section, field, prefix, signal, keep, point) {
|
|
112
|
+
const refs = this.refsOf(field);
|
|
113
|
+
const plans = await Promise.all(refs.map(async (ref) => {
|
|
114
|
+
const header = await this.header(ref);
|
|
115
|
+
if (point && !segmentMayHold(header, section, prefix)) {
|
|
116
|
+
this.metrics.segmentsSkipped = (this.metrics.segmentsSkipped ?? 0) + 1;
|
|
117
|
+
return { ref, wanted: [] };
|
|
118
|
+
}
|
|
119
|
+
return { ref, wanted: blocksFor(header[section], prefix) };
|
|
120
|
+
}));
|
|
121
|
+
// Between a segment's first and last wanted block, every block holds only keys under the prefix
|
|
122
|
+
// (when the prefix fits in a block bound). If those alone pass the budget, so would the read: it
|
|
123
|
+
// stops before reading a block, so a scan of a big field never holds more than the budget. Scans
|
|
124
|
+
// in flight together hold their share until they count what they read, so together they stop too.
|
|
125
|
+
const surely = prefix.length > BOUND_CHARS ? 0 : plans.reduce((n, p) => n + p.wanted.slice(1, -1).reduce((m, b) => m + b.entries, 0), 0);
|
|
126
|
+
if (this.metrics.tuplesRead + this.reading + surely > MAX_QUERY_TUPLES)
|
|
127
|
+
throw new TupleBudgetExceeded();
|
|
128
|
+
this.reading += surely;
|
|
129
|
+
let blocks;
|
|
130
|
+
try {
|
|
131
|
+
blocks = await Promise.all(plans.map(async ({ ref, wanted }) => {
|
|
132
|
+
if (wanted.length > 0)
|
|
133
|
+
this.metrics.segmentsTouched++;
|
|
134
|
+
return Promise.all(wanted.map(async (b) => entriesUnder(section, await this.block(ref, section, b), prefix)));
|
|
135
|
+
}));
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
this.reading -= surely;
|
|
139
|
+
}
|
|
140
|
+
signal?.throwIfAborted();
|
|
141
|
+
// Only entries under the prefix count, and only they are decoded: the rest of a block is read, not scanned.
|
|
142
|
+
const entries = blocks.flat(2);
|
|
143
|
+
this.metrics.tuplesRead += entries.length;
|
|
144
|
+
if (this.metrics.tuplesRead > MAX_QUERY_TUPLES)
|
|
145
|
+
throw new TupleBudgetExceeded();
|
|
146
|
+
if (section === "ave" || keep === undefined)
|
|
147
|
+
return entries;
|
|
148
|
+
const facts = entries.map(eavFact).filter((f) => f.field === field && f.ts <= this.maxTs && keep(f));
|
|
149
|
+
return [...facts, ...this.tail.filter((f) => f.field === field && keep(f))];
|
|
150
|
+
}
|
|
151
|
+
header(ref) {
|
|
152
|
+
return this.shared(this.headers, ref.name, () => readHeader(this.store, ref, this.metrics));
|
|
153
|
+
}
|
|
154
|
+
block(ref, section, b) {
|
|
155
|
+
return this.shared(this.blocks, `${ref.name}#${section}#${b.offset}`, () => readBlock(this.store, ref, section, b, this.metrics));
|
|
156
|
+
}
|
|
157
|
+
/** One read per key for the whole query; asking again counts as a cache hit. */
|
|
158
|
+
shared(reads, key, read) {
|
|
159
|
+
const held = reads.get(key);
|
|
160
|
+
if (held !== undefined) {
|
|
161
|
+
this.metrics.cacheHits++;
|
|
162
|
+
return held;
|
|
163
|
+
}
|
|
164
|
+
const started = read();
|
|
165
|
+
reads.set(key, started);
|
|
166
|
+
return started;
|
|
167
|
+
}
|
|
168
|
+
/** The segments of the field's bucket that hold writes at or below the watermark. */
|
|
169
|
+
refsOf(field) {
|
|
170
|
+
return (this.segments[String(bucketOf(field, BUCKETS))] ?? []).filter((r) => r.minEpoch <= epochOf(this.maxTs));
|
|
171
|
+
}
|
|
172
|
+
*fromEav(writes, lookup) {
|
|
173
|
+
for (const f of lastWrites(writes)) {
|
|
174
|
+
if (f.retraction)
|
|
175
|
+
continue;
|
|
176
|
+
const entity = referenceValue(f.entity);
|
|
177
|
+
for (const value of factValueToDatalogValues(f.value)) {
|
|
178
|
+
if (lookup.value === undefined || sameDatalogValue(value, lookup.value))
|
|
179
|
+
yield { entity, value };
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
*fromAve(entries) {
|
|
184
|
+
const last = new Map();
|
|
185
|
+
for (const e of entries) {
|
|
186
|
+
const k = tupleKey(e.fact), prior = last.get(k);
|
|
187
|
+
if (prior === undefined || compareFacts(prior.fact, e.fact) < 0)
|
|
188
|
+
last.set(k, e);
|
|
189
|
+
}
|
|
190
|
+
for (const e of last.values()) {
|
|
191
|
+
if (e.fact.retraction)
|
|
192
|
+
continue;
|
|
193
|
+
const entity = referenceValue(e.fact.entity);
|
|
194
|
+
const value = boundValue(matchedItem(e.fact.value, e.dv));
|
|
195
|
+
for (let i = 0; i < e.count; i++)
|
|
196
|
+
yield { entity, value };
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
export type ObservabilityRange = "15m" | "1h" | "6h" | "24h" | "7d";
|
|
2
|
+
export type ObservabilityDimension = "graph" | "client" | "operation" | "outcome";
|
|
3
|
+
export type ObservabilityOutcome = "ok" | "invalid" | "denied" | "unavailable" | "failed";
|
|
4
|
+
export declare const OBSERVABILITY_OUTCOMES: readonly ObservabilityOutcome[];
|
|
5
|
+
/**
|
|
6
|
+
* Time-range windows and their display step size + backing storage tier.
|
|
7
|
+
* Fine tier (15 s) covers 15m and 1h; coarse tier (5 m = 300 s) covers 6h, 24h, and 7d.
|
|
8
|
+
*/
|
|
9
|
+
export declare const OBSERVABILITY_RANGES: Readonly<Record<ObservabilityRange, Readonly<{
|
|
10
|
+
ms: number;
|
|
11
|
+
stepMs: number;
|
|
12
|
+
tierSec: 15 | 300;
|
|
13
|
+
}>>>;
|
|
14
|
+
/** Retention windows for the two storage tiers in TelemetryDO. */
|
|
15
|
+
export declare const FINE_RETENTION_MS: number;
|
|
16
|
+
export declare const COARSE_RETENTION_MS: number;
|
|
17
|
+
/** Upper bounds of the 24 logarithmic latency buckets in milliseconds; the last is unbounded. */
|
|
18
|
+
export declare const LATENCY_BOUNDS: readonly number[];
|
|
19
|
+
export type TrafficPoint = Readonly<{
|
|
20
|
+
at: number;
|
|
21
|
+
requests: number;
|
|
22
|
+
errors: number;
|
|
23
|
+
p50: number | null;
|
|
24
|
+
p99: number | null;
|
|
25
|
+
}>;
|
|
26
|
+
export type TrafficGroup = Readonly<{
|
|
27
|
+
key: string;
|
|
28
|
+
requests: number;
|
|
29
|
+
errors: number;
|
|
30
|
+
facts: number;
|
|
31
|
+
p50: number | null;
|
|
32
|
+
p95: number | null;
|
|
33
|
+
p99: number | null;
|
|
34
|
+
points: readonly TrafficPoint[];
|
|
35
|
+
}>;
|
|
36
|
+
export type TrafficResponse = Readonly<{
|
|
37
|
+
from: number;
|
|
38
|
+
to: number;
|
|
39
|
+
stepMs: number;
|
|
40
|
+
by: ObservabilityDimension | null;
|
|
41
|
+
total: TrafficGroup;
|
|
42
|
+
groups: readonly TrafficGroup[];
|
|
43
|
+
dimensions: Readonly<Record<ObservabilityDimension, readonly string[]>>;
|
|
44
|
+
}>;
|
|
45
|
+
export type QueryStat = Readonly<{
|
|
46
|
+
id: string;
|
|
47
|
+
graph: string;
|
|
48
|
+
datalog: string;
|
|
49
|
+
example: string;
|
|
50
|
+
clients: readonly string[];
|
|
51
|
+
calls: number;
|
|
52
|
+
errors: number;
|
|
53
|
+
meanMs: number;
|
|
54
|
+
p50: number | null;
|
|
55
|
+
p99: number | null;
|
|
56
|
+
totalMs: number;
|
|
57
|
+
rows: number;
|
|
58
|
+
tuples: number;
|
|
59
|
+
}>;
|
|
60
|
+
export type QueryStatsResponse = Readonly<{
|
|
61
|
+
from: number;
|
|
62
|
+
to: number;
|
|
63
|
+
queries: readonly QueryStat[];
|
|
64
|
+
}>;
|
|
65
|
+
export type ObservabilityFilters = Readonly<{
|
|
66
|
+
graph?: string;
|
|
67
|
+
client?: string;
|
|
68
|
+
operation?: string;
|
|
69
|
+
outcome?: string;
|
|
70
|
+
}>;
|
|
71
|
+
/** Compact aggregated traffic cell shipped from a Worker isolate to TelemetryDO. */
|
|
72
|
+
export type TrafficCellDelta = Readonly<{
|
|
73
|
+
at: number;
|
|
74
|
+
graph: string;
|
|
75
|
+
client: string;
|
|
76
|
+
operation: string;
|
|
77
|
+
outcome: ObservabilityOutcome;
|
|
78
|
+
count: number;
|
|
79
|
+
facts: number;
|
|
80
|
+
hist: readonly number[];
|
|
81
|
+
}>;
|
|
82
|
+
/** Compact aggregated query-shape cell shipped from a Worker isolate to TelemetryDO. */
|
|
83
|
+
export type QueryShapeDelta = Readonly<{
|
|
84
|
+
at: number;
|
|
85
|
+
id: string;
|
|
86
|
+
graph: string;
|
|
87
|
+
datalog: string;
|
|
88
|
+
example: string;
|
|
89
|
+
clients: readonly string[];
|
|
90
|
+
calls: number;
|
|
91
|
+
errors: number;
|
|
92
|
+
totalMs: number;
|
|
93
|
+
rows: number;
|
|
94
|
+
tuples: number;
|
|
95
|
+
hist: readonly number[];
|
|
96
|
+
}>;
|
|
97
|
+
export type TelemetryBatch = Readonly<{
|
|
98
|
+
traffic: readonly TrafficCellDelta[];
|
|
99
|
+
queries: readonly QueryShapeDelta[];
|
|
100
|
+
}>;
|
|
101
|
+
export declare function parseObservabilityRange(value: string | null): ObservabilityRange;
|
|
102
|
+
export declare function parseObservabilityDimension(value: string | null): ObservabilityDimension | null;
|
|
103
|
+
export declare function isObservabilityOutcome(value: string): value is ObservabilityOutcome;
|
|
104
|
+
export declare function emptyLatencyHist(): number[];
|
|
105
|
+
/** Records one latency sample in milliseconds into a 24-bucket histogram. Ignores non-finite values. */
|
|
106
|
+
export declare function observeLatency(hist: number[], ms: number): void;
|
|
107
|
+
export declare function addLatencyHist(target: number[], source: readonly number[]): void;
|
|
108
|
+
export declare function mergeLatencyHists(hists: readonly (readonly number[])[]): number[];
|
|
109
|
+
/** Log-interpolated q-quantile (0..1) of a 24-bucket latency histogram. */
|
|
110
|
+
export declare function latencyQuantile(hist: readonly number[], q: number): number | null;
|
|
111
|
+
/** Computes [from, to) covering the range aligned to stepMs, including the current in-progress step. */
|
|
112
|
+
export declare function timeWindow(range: ObservabilityRange, now: number): Readonly<{
|
|
113
|
+
from: number;
|
|
114
|
+
to: number;
|
|
115
|
+
stepMs: number;
|
|
116
|
+
tierSec: 15 | 300;
|
|
117
|
+
}>;
|
|
118
|
+
export declare function bucketFloor(atMs: number, bucketMs: number): number;
|
|
119
|
+
export declare function parseHistogramJson(raw: string): number[];
|
|
120
|
+
/** Rolls stored traffic cells into the exact shape served by GET /api/observability/traffic. */
|
|
121
|
+
export declare function aggregateTraffic(cells: readonly TrafficCellDelta[], range: ObservabilityRange, by: ObservabilityDimension | null, filters: ObservabilityFilters, now: number): TrafficResponse;
|
|
122
|
+
/** Rolls stored query-shape cells into the exact shape served by GET /api/observability/queries. */
|
|
123
|
+
export declare function aggregateQueryStats(cells: readonly QueryShapeDelta[], range: ObservabilityRange, filters: ObservabilityFilters, now: number): QueryStatsResponse;
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
// Traffic and query-shape telemetry domain types, logarithmic latency histograms, and rollup
|
|
2
|
+
// aggregation. Pure and portable so it runs identically in Durable Objects, Workers, and Node tests.
|
|
3
|
+
import { compareCodeUnits } from "../domain/string-order.js";
|
|
4
|
+
export const OBSERVABILITY_OUTCOMES = [
|
|
5
|
+
"ok", "invalid", "denied", "unavailable", "failed",
|
|
6
|
+
];
|
|
7
|
+
/**
|
|
8
|
+
* Time-range windows and their display step size + backing storage tier.
|
|
9
|
+
* Fine tier (15 s) covers 15m and 1h; coarse tier (5 m = 300 s) covers 6h, 24h, and 7d.
|
|
10
|
+
*/
|
|
11
|
+
export const OBSERVABILITY_RANGES = {
|
|
12
|
+
"15m": { ms: 15 * 60_000, stepMs: 15_000, tierSec: 15 },
|
|
13
|
+
"1h": { ms: 3_600_000, stepMs: 60_000, tierSec: 15 },
|
|
14
|
+
"6h": { ms: 6 * 3_600_000, stepMs: 5 * 60_000, tierSec: 300 },
|
|
15
|
+
"24h": { ms: 86_400_000, stepMs: 15 * 60_000, tierSec: 300 },
|
|
16
|
+
"7d": { ms: 7 * 86_400_000, stepMs: 3_600_000, tierSec: 300 },
|
|
17
|
+
};
|
|
18
|
+
/** Retention windows for the two storage tiers in TelemetryDO. */
|
|
19
|
+
export const FINE_RETENTION_MS = 2 * 3_600_000;
|
|
20
|
+
export const COARSE_RETENTION_MS = 7 * 86_400_000 + 3_600_000;
|
|
21
|
+
/** Upper bounds of the 24 logarithmic latency buckets in milliseconds; the last is unbounded. */
|
|
22
|
+
export const LATENCY_BOUNDS = [
|
|
23
|
+
1, 2, 3, 5, 7, 10, 15, 20, 30, 50, 70, 100, 150, 200, 300, 500, 700, 1_000, 1_500, 2_000, 3_000, 5_000, 10_000, Infinity,
|
|
24
|
+
];
|
|
25
|
+
export function parseObservabilityRange(value) {
|
|
26
|
+
if (value === "15m" || value === "1h" || value === "6h" || value === "24h" || value === "7d")
|
|
27
|
+
return value;
|
|
28
|
+
return "1h";
|
|
29
|
+
}
|
|
30
|
+
export function parseObservabilityDimension(value) {
|
|
31
|
+
if (value === "none")
|
|
32
|
+
return null;
|
|
33
|
+
if (value === "graph" || value === "client" || value === "operation" || value === "outcome")
|
|
34
|
+
return value;
|
|
35
|
+
return "graph";
|
|
36
|
+
}
|
|
37
|
+
export function isObservabilityOutcome(value) {
|
|
38
|
+
return value === "ok" || value === "invalid" || value === "denied" || value === "unavailable" || value === "failed";
|
|
39
|
+
}
|
|
40
|
+
export function emptyLatencyHist() {
|
|
41
|
+
return LATENCY_BOUNDS.map(() => 0);
|
|
42
|
+
}
|
|
43
|
+
/** Records one latency sample in milliseconds into a 24-bucket histogram. Ignores non-finite values. */
|
|
44
|
+
export function observeLatency(hist, ms) {
|
|
45
|
+
if (!Number.isFinite(ms))
|
|
46
|
+
return;
|
|
47
|
+
const clamped = ms < 0 ? 0 : ms;
|
|
48
|
+
for (let i = 0; i < LATENCY_BOUNDS.length; i++) {
|
|
49
|
+
const bound = LATENCY_BOUNDS[i];
|
|
50
|
+
if (bound !== undefined && clamped <= bound) {
|
|
51
|
+
hist[i] = (hist[i] ?? 0) + 1;
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const last = LATENCY_BOUNDS.length - 1;
|
|
56
|
+
hist[last] = (hist[last] ?? 0) + 1;
|
|
57
|
+
}
|
|
58
|
+
export function addLatencyHist(target, source) {
|
|
59
|
+
for (let i = 0; i < LATENCY_BOUNDS.length; i++) {
|
|
60
|
+
target[i] = (target[i] ?? 0) + (source[i] ?? 0);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export function mergeLatencyHists(hists) {
|
|
64
|
+
const out = emptyLatencyHist();
|
|
65
|
+
for (const hist of hists)
|
|
66
|
+
addLatencyHist(out, hist);
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
/** Log-interpolated q-quantile (0..1) of a 24-bucket latency histogram. */
|
|
70
|
+
export function latencyQuantile(hist, q) {
|
|
71
|
+
let total = 0;
|
|
72
|
+
for (let i = 0; i < LATENCY_BOUNDS.length; i++)
|
|
73
|
+
total += hist[i] ?? 0;
|
|
74
|
+
if (total === 0)
|
|
75
|
+
return null;
|
|
76
|
+
const target = q * total;
|
|
77
|
+
let seen = 0;
|
|
78
|
+
for (let i = 0; i < LATENCY_BOUNDS.length; i++) {
|
|
79
|
+
const n = hist[i] ?? 0;
|
|
80
|
+
if (seen + n >= target && n > 0) {
|
|
81
|
+
const prevBound = i === 0 ? 0.5 : (LATENCY_BOUNDS[i - 1] ?? 0.5);
|
|
82
|
+
const curBound = LATENCY_BOUNDS[i] ?? Infinity;
|
|
83
|
+
const low = prevBound;
|
|
84
|
+
const high = curBound === Infinity ? prevBound * 2 : curBound;
|
|
85
|
+
const frac = Math.min(1, Math.max(0, (target - seen) / n));
|
|
86
|
+
return Math.exp(Math.log(low) + frac * (Math.log(high) - Math.log(low)));
|
|
87
|
+
}
|
|
88
|
+
seen += n;
|
|
89
|
+
}
|
|
90
|
+
return LATENCY_BOUNDS[LATENCY_BOUNDS.length - 2] ?? 10_000;
|
|
91
|
+
}
|
|
92
|
+
/** Computes [from, to) covering the range aligned to stepMs, including the current in-progress step. */
|
|
93
|
+
export function timeWindow(range, now) {
|
|
94
|
+
const spec = OBSERVABILITY_RANGES[range];
|
|
95
|
+
const to = Math.floor(now / spec.stepMs) * spec.stepMs + spec.stepMs;
|
|
96
|
+
const from = to - spec.ms;
|
|
97
|
+
return { from, to, stepMs: spec.stepMs, tierSec: spec.tierSec };
|
|
98
|
+
}
|
|
99
|
+
export function bucketFloor(atMs, bucketMs) {
|
|
100
|
+
return Math.floor(atMs / bucketMs) * bucketMs;
|
|
101
|
+
}
|
|
102
|
+
export function parseHistogramJson(raw) {
|
|
103
|
+
const out = emptyLatencyHist();
|
|
104
|
+
try {
|
|
105
|
+
const parsed = JSON.parse(raw);
|
|
106
|
+
if (!Array.isArray(parsed))
|
|
107
|
+
return out;
|
|
108
|
+
for (let i = 0; i < LATENCY_BOUNDS.length && i < parsed.length; i++) {
|
|
109
|
+
const v = parsed[i];
|
|
110
|
+
if (typeof v === "number" && Number.isFinite(v) && v >= 0)
|
|
111
|
+
out[i] = v;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
// Malformed histogram row falls back to zeroed buckets rather than failing the dashboard.
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
function matchesFilters(cell, filters) {
|
|
120
|
+
if (filters.graph !== undefined && cell.graph !== filters.graph)
|
|
121
|
+
return false;
|
|
122
|
+
if (filters.client !== undefined && cell.client !== filters.client)
|
|
123
|
+
return false;
|
|
124
|
+
if (filters.operation !== undefined && cell.operation !== filters.operation)
|
|
125
|
+
return false;
|
|
126
|
+
if (filters.outcome !== undefined && cell.outcome !== filters.outcome)
|
|
127
|
+
return false;
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
function dimensionValue(cell, by) {
|
|
131
|
+
switch (by) {
|
|
132
|
+
case "graph": return cell.graph;
|
|
133
|
+
case "client": return cell.client;
|
|
134
|
+
case "operation": return cell.operation;
|
|
135
|
+
case "outcome": return cell.outcome;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function distinctSorted(values) {
|
|
139
|
+
return [...new Set(values)].sort(compareCodeUnits);
|
|
140
|
+
}
|
|
141
|
+
function buildTrafficGroup(key, cells, steps, stepMs) {
|
|
142
|
+
const byStep = new Map();
|
|
143
|
+
let totalRequests = 0;
|
|
144
|
+
let totalErrors = 0;
|
|
145
|
+
let totalFacts = 0;
|
|
146
|
+
const groupHist = emptyLatencyHist();
|
|
147
|
+
for (const cell of cells) {
|
|
148
|
+
const stepAt = bucketFloor(cell.at, stepMs);
|
|
149
|
+
const list = byStep.get(stepAt);
|
|
150
|
+
if (list === undefined)
|
|
151
|
+
byStep.set(stepAt, [cell]);
|
|
152
|
+
else
|
|
153
|
+
list.push(cell);
|
|
154
|
+
totalRequests += cell.count;
|
|
155
|
+
if (cell.outcome !== "ok")
|
|
156
|
+
totalErrors += cell.count;
|
|
157
|
+
totalFacts += cell.facts;
|
|
158
|
+
addLatencyHist(groupHist, cell.hist);
|
|
159
|
+
}
|
|
160
|
+
const seconds = stepMs / 1_000;
|
|
161
|
+
const points = steps.map((at) => {
|
|
162
|
+
const stepCells = byStep.get(at);
|
|
163
|
+
if (stepCells === undefined || stepCells.length === 0) {
|
|
164
|
+
return { at, requests: 0, errors: 0, p50: null, p99: null };
|
|
165
|
+
}
|
|
166
|
+
let reqs = 0;
|
|
167
|
+
let errs = 0;
|
|
168
|
+
const stepHist = emptyLatencyHist();
|
|
169
|
+
for (const c of stepCells) {
|
|
170
|
+
reqs += c.count;
|
|
171
|
+
if (c.outcome !== "ok")
|
|
172
|
+
errs += c.count;
|
|
173
|
+
addLatencyHist(stepHist, c.hist);
|
|
174
|
+
}
|
|
175
|
+
return {
|
|
176
|
+
at,
|
|
177
|
+
requests: reqs / seconds,
|
|
178
|
+
errors: errs / seconds,
|
|
179
|
+
p50: latencyQuantile(stepHist, 0.5),
|
|
180
|
+
p99: latencyQuantile(stepHist, 0.99),
|
|
181
|
+
};
|
|
182
|
+
});
|
|
183
|
+
return {
|
|
184
|
+
key,
|
|
185
|
+
requests: totalRequests,
|
|
186
|
+
errors: totalErrors,
|
|
187
|
+
facts: totalFacts,
|
|
188
|
+
p50: latencyQuantile(groupHist, 0.5),
|
|
189
|
+
p95: latencyQuantile(groupHist, 0.95),
|
|
190
|
+
p99: latencyQuantile(groupHist, 0.99),
|
|
191
|
+
points,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
/** Rolls stored traffic cells into the exact shape served by GET /api/observability/traffic. */
|
|
195
|
+
export function aggregateTraffic(cells, range, by, filters, now) {
|
|
196
|
+
const { from, to, stepMs } = timeWindow(range, now);
|
|
197
|
+
const inRange = cells.filter((c) => c.at >= from && c.at < to);
|
|
198
|
+
const kept = inRange.filter((c) => matchesFilters(c, filters));
|
|
199
|
+
const stepCount = Math.max(1, Math.round((to - from) / stepMs));
|
|
200
|
+
const steps = Array.from({ length: stepCount }, (_, i) => from + i * stepMs);
|
|
201
|
+
const groups = [];
|
|
202
|
+
if (by !== null) {
|
|
203
|
+
const grouped = new Map();
|
|
204
|
+
for (const cell of kept) {
|
|
205
|
+
const k = dimensionValue(cell, by);
|
|
206
|
+
const list = grouped.get(k);
|
|
207
|
+
if (list === undefined)
|
|
208
|
+
grouped.set(k, [cell]);
|
|
209
|
+
else
|
|
210
|
+
list.push(cell);
|
|
211
|
+
}
|
|
212
|
+
for (const [key, list] of grouped) {
|
|
213
|
+
groups.push(buildTrafficGroup(key, list, steps, stepMs));
|
|
214
|
+
}
|
|
215
|
+
groups.sort((a, b) => b.requests - a.requests || compareCodeUnits(a.key, b.key));
|
|
216
|
+
}
|
|
217
|
+
return {
|
|
218
|
+
from,
|
|
219
|
+
to,
|
|
220
|
+
stepMs,
|
|
221
|
+
by,
|
|
222
|
+
total: buildTrafficGroup("all", kept, steps, stepMs),
|
|
223
|
+
groups,
|
|
224
|
+
dimensions: {
|
|
225
|
+
graph: distinctSorted(inRange.map((c) => c.graph)),
|
|
226
|
+
client: distinctSorted(inRange.map((c) => c.client)),
|
|
227
|
+
operation: distinctSorted(inRange.map((c) => c.operation)),
|
|
228
|
+
outcome: OBSERVABILITY_OUTCOMES,
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/** Rolls stored query-shape cells into the exact shape served by GET /api/observability/queries. */
|
|
233
|
+
export function aggregateQueryStats(cells, range, filters, now) {
|
|
234
|
+
const { from, to } = timeWindow(range, now);
|
|
235
|
+
const byKey = new Map();
|
|
236
|
+
for (const cell of cells) {
|
|
237
|
+
if (cell.at < from || cell.at >= to)
|
|
238
|
+
continue;
|
|
239
|
+
if (filters.graph !== undefined && cell.graph !== filters.graph)
|
|
240
|
+
continue;
|
|
241
|
+
if (filters.client !== undefined && !cell.clients.includes(filters.client))
|
|
242
|
+
continue;
|
|
243
|
+
const key = `${cell.graph}\0${cell.id}`;
|
|
244
|
+
let acc = byKey.get(key);
|
|
245
|
+
if (acc === undefined) {
|
|
246
|
+
acc = {
|
|
247
|
+
id: `${cell.graph}:${cell.id}`,
|
|
248
|
+
graph: cell.graph,
|
|
249
|
+
datalog: cell.datalog,
|
|
250
|
+
example: cell.example,
|
|
251
|
+
clients: new Set(),
|
|
252
|
+
calls: 0,
|
|
253
|
+
errors: 0,
|
|
254
|
+
totalMs: 0,
|
|
255
|
+
totalRows: 0,
|
|
256
|
+
totalTuples: 0,
|
|
257
|
+
hist: emptyLatencyHist(),
|
|
258
|
+
};
|
|
259
|
+
byKey.set(key, acc);
|
|
260
|
+
}
|
|
261
|
+
for (const c of cell.clients)
|
|
262
|
+
acc.clients.add(c);
|
|
263
|
+
acc.calls += cell.calls;
|
|
264
|
+
acc.errors += cell.errors;
|
|
265
|
+
acc.totalMs += cell.totalMs;
|
|
266
|
+
acc.totalRows += cell.rows;
|
|
267
|
+
acc.totalTuples += cell.tuples;
|
|
268
|
+
addLatencyHist(acc.hist, cell.hist);
|
|
269
|
+
}
|
|
270
|
+
const queries = [];
|
|
271
|
+
for (const acc of byKey.values()) {
|
|
272
|
+
if (acc.calls === 0)
|
|
273
|
+
continue;
|
|
274
|
+
queries.push({
|
|
275
|
+
id: acc.id,
|
|
276
|
+
graph: acc.graph,
|
|
277
|
+
datalog: acc.datalog,
|
|
278
|
+
example: acc.example,
|
|
279
|
+
clients: [...acc.clients].sort(compareCodeUnits),
|
|
280
|
+
calls: acc.calls,
|
|
281
|
+
errors: acc.errors,
|
|
282
|
+
meanMs: acc.totalMs / acc.calls,
|
|
283
|
+
p50: latencyQuantile(acc.hist, 0.5),
|
|
284
|
+
p99: latencyQuantile(acc.hist, 0.99),
|
|
285
|
+
totalMs: acc.totalMs,
|
|
286
|
+
rows: Math.round(acc.totalRows / acc.calls),
|
|
287
|
+
tuples: Math.round(acc.totalTuples / acc.calls),
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
queries.sort((a, b) => b.totalMs - a.totalMs || b.calls - a.calls || compareCodeUnits(a.id, b.id));
|
|
291
|
+
return { from, to, queries };
|
|
292
|
+
}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// The release, and the Workers compatibility date it is tested with. Shared by the config helper,
|
|
2
|
+
// which runs in Node, and the instance, which runs in Workers.
|
|
3
|
+
/** This package's version; tests/node/cloudflare.test.ts checks it against package.json. */
|
|
4
|
+
export const VERSION = "0.10.0";
|
|
5
|
+
/** The compatibility date this version of FateDB is tested with. */
|
|
6
|
+
export const COMPATIBILITY_DATE = "2026-10-13";
|