fatedb 0.0.0-stage → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +264 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +3 -0
  5. package/dist/cli.d.ts +15 -0
  6. package/dist/cli.js +256 -0
  7. package/dist/client.d.ts +152 -0
  8. package/dist/client.js +416 -0
  9. package/dist/cloudflare.d.ts +197 -0
  10. package/dist/cloudflare.js +159 -0
  11. package/dist/datalog/ast.d.ts +35 -0
  12. package/dist/datalog/ast.js +40 -0
  13. package/dist/datalog/evaluator.d.ts +14 -0
  14. package/dist/datalog/evaluator.js +395 -0
  15. package/dist/datalog/fact-source.d.ts +30 -0
  16. package/dist/datalog/fact-source.js +1 -0
  17. package/dist/datalog/fingerprint.d.ts +12 -0
  18. package/dist/datalog/fingerprint.js +50 -0
  19. package/dist/datalog/parser.d.ts +3 -0
  20. package/dist/datalog/parser.js +302 -0
  21. package/dist/datalog/value.d.ts +34 -0
  22. package/dist/datalog/value.js +104 -0
  23. package/dist/domain/date-validation.d.ts +2 -0
  24. package/dist/domain/date-validation.js +32 -0
  25. package/dist/domain/fact-value.d.ts +91 -0
  26. package/dist/domain/fact-value.js +167 -0
  27. package/dist/domain/fact.d.ts +14 -0
  28. package/dist/domain/fact.js +47 -0
  29. package/dist/domain/failure.d.ts +44 -0
  30. package/dist/domain/failure.js +30 -0
  31. package/dist/domain/graph-id.d.ts +7 -0
  32. package/dist/domain/graph-id.js +10 -0
  33. package/dist/domain/histogram.d.ts +29 -0
  34. package/dist/domain/histogram.js +48 -0
  35. package/dist/domain/identifiers.d.ts +26 -0
  36. package/dist/domain/identifiers.js +75 -0
  37. package/dist/domain/numbers.d.ts +12 -0
  38. package/dist/domain/numbers.js +77 -0
  39. package/dist/domain/projection.d.ts +252 -0
  40. package/dist/domain/projection.js +51 -0
  41. package/dist/domain/query-metrics.d.ts +31 -0
  42. package/dist/domain/query-metrics.js +35 -0
  43. package/dist/domain/read-token.d.ts +37 -0
  44. package/dist/domain/read-token.js +93 -0
  45. package/dist/domain/result.d.ts +22 -0
  46. package/dist/domain/result.js +16 -0
  47. package/dist/domain/schema-observation.d.ts +20 -0
  48. package/dist/domain/schema-observation.js +61 -0
  49. package/dist/domain/string-order.d.ts +2 -0
  50. package/dist/domain/string-order.js +15 -0
  51. package/dist/domain/vocabulary.d.ts +101 -0
  52. package/dist/domain/vocabulary.js +276 -0
  53. package/dist/index.d.ts +15 -0
  54. package/dist/index.js +14 -0
  55. package/dist/projection-config.d.ts +3 -0
  56. package/dist/projection-config.js +212 -0
  57. package/dist/server/access.d.ts +32 -0
  58. package/dist/server/access.js +117 -0
  59. package/dist/server/admin.d.ts +233 -0
  60. package/dist/server/admin.js +483 -0
  61. package/dist/server/authorization.d.ts +35 -0
  62. package/dist/server/authorization.js +76 -0
  63. package/dist/server/console-assets.d.ts +6 -0
  64. package/dist/server/console-assets.js +2 -0
  65. package/dist/server/console.d.ts +8 -0
  66. package/dist/server/console.js +301 -0
  67. package/dist/server/index.d.ts +122 -0
  68. package/dist/server/index.js +487 -0
  69. package/dist/server/mcp.d.ts +31 -0
  70. package/dist/server/mcp.js +169 -0
  71. package/dist/server/telemetry-do.d.ts +31 -0
  72. package/dist/server/telemetry-do.js +342 -0
  73. package/dist/server/telemetry.d.ts +27 -0
  74. package/dist/server/telemetry.js +191 -0
  75. package/dist/storage/constants.d.ts +20 -0
  76. package/dist/storage/constants.js +21 -0
  77. package/dist/storage/environment.d.ts +438 -0
  78. package/dist/storage/environment.js +145 -0
  79. package/dist/storage/facts.d.ts +41 -0
  80. package/dist/storage/facts.js +73 -0
  81. package/dist/storage/http.d.ts +55 -0
  82. package/dist/storage/http.js +169 -0
  83. package/dist/storage/keys.d.ts +50 -0
  84. package/dist/storage/keys.js +84 -0
  85. package/dist/storage/layout.d.ts +67 -0
  86. package/dist/storage/layout.js +134 -0
  87. package/dist/storage/log.d.ts +41 -0
  88. package/dist/storage/log.js +137 -0
  89. package/dist/storage/manifest.d.ts +26 -0
  90. package/dist/storage/manifest.js +206 -0
  91. package/dist/storage/operations.d.ts +303 -0
  92. package/dist/storage/operations.js +719 -0
  93. package/dist/storage/partition.d.ts +125 -0
  94. package/dist/storage/partition.js +816 -0
  95. package/dist/storage/projection.d.ts +72 -0
  96. package/dist/storage/projection.js +1349 -0
  97. package/dist/storage/root.d.ts +120 -0
  98. package/dist/storage/root.js +596 -0
  99. package/dist/storage/segment.d.ts +145 -0
  100. package/dist/storage/segment.js +451 -0
  101. package/dist/storage/shard.d.ts +82 -0
  102. package/dist/storage/shard.js +710 -0
  103. package/dist/storage/source.d.ts +60 -0
  104. package/dist/storage/source.js +199 -0
  105. package/dist/telemetry/model.d.ts +123 -0
  106. package/dist/telemetry/model.js +292 -0
  107. package/dist/version.d.ts +4 -0
  108. package/dist/version.js +6 -0
  109. package/package.json +82 -4
@@ -0,0 +1,145 @@
1
+ import { type DatalogValue } from "../datalog/value.js";
2
+ import type { FactValue } from "../domain/fact-value.js";
3
+ import { type IndexedFact } from "./facts.js";
4
+ declare global {
5
+ interface CacheStorage {
6
+ /** The Workers runtime's cache in the colo serving the request (https://developers.cloudflare.com/workers/runtime-apis/cache/). */
7
+ readonly default: Cache;
8
+ }
9
+ }
10
+ export declare const SEGMENT_FORMAT = 3;
11
+ /** Block bounds keep this many characters of a key. */
12
+ export declare const BOUND_CHARS = 120;
13
+ export type BlockRef = Readonly<{
14
+ lo: string;
15
+ hi: string;
16
+ offset: number;
17
+ length: number;
18
+ entries: number;
19
+ }>;
20
+ /** A Bloom filter: `bits` bits, `hashes` probes a key, no false negatives. */
21
+ export type Filter = Readonly<{
22
+ bits: number;
23
+ hashes: number;
24
+ data: Uint8Array;
25
+ }>;
26
+ export type ValueTag = FactValue["type"];
27
+ export declare const VALUE_TAGS: readonly ValueTag[];
28
+ /** Tuples of one field and value tag whose last write in a segment asserts them, and those whose last write retracts them. */
29
+ export type TagCounts = Readonly<{
30
+ asserted: number;
31
+ retracted: number;
32
+ }>;
33
+ export type SegmentSchema = Readonly<Record<string, Readonly<Partial<Record<ValueTag, TagCounts>>>>>;
34
+ export type SegmentHeader = Readonly<{
35
+ format: typeof SEGMENT_FORMAT;
36
+ watermark: number;
37
+ minEpoch: number;
38
+ maxEpoch: number;
39
+ facts: number;
40
+ eav: readonly BlockRef[];
41
+ ave: readonly BlockRef[];
42
+ filters: Readonly<{
43
+ eav: Filter;
44
+ ave: Filter;
45
+ }>;
46
+ schema: SegmentSchema;
47
+ }>;
48
+ /** What a manifest says about a segment: enough to read its header in one ranged GET. */
49
+ export type SegmentRef = Readonly<{
50
+ name: string;
51
+ facts: number;
52
+ bytes: number;
53
+ headerBytes: number;
54
+ minEpoch: number;
55
+ maxEpoch: number;
56
+ }>;
57
+ /** One distinct Datalog value of a fact, and how many times the fact holds it (lists may repeat one). */
58
+ export type AveEntry = Readonly<{
59
+ dv: DatalogValue;
60
+ count: number;
61
+ fact: IndexedFact;
62
+ }>;
63
+ export type Section = "eav" | "ave";
64
+ export declare function dvKey(v: DatalogValue): string;
65
+ export declare function eavPrefix(field: string, entity?: string): string;
66
+ export declare function avePrefix(field: string, dv: DatalogValue): string;
67
+ export declare function aveEntriesOf(f: IndexedFact): AveEntry[];
68
+ /** Whether a block whose keys lie in [lo, hi] may hold a key starting with `prefix`. */
69
+ export declare function blockMayHold(block: Pick<BlockRef, "lo" | "hi">, prefix: string): boolean;
70
+ /**
71
+ * The blocks that may hold keys starting with `prefix`: a contiguous run, found by binary search.
72
+ * Blocks are sorted and their `hi` bounds never decrease, so the first candidate is the first block
73
+ * whose `hi` is not below the prefix.
74
+ */
75
+ export declare function blocksFor(blocks: readonly BlockRef[], prefix: string): readonly BlockRef[];
76
+ /**
77
+ * The entries of a block, as stored, whose sort key starts with `prefix`: a contiguous run, found by
78
+ * binary search on the key's leading part (field, then entity for EAV or value for AVE). Neither
79
+ * part holds the separator, so ordering by the leading part agrees with ordering by the whole key.
80
+ */
81
+ export declare function entriesUnder(section: Section, entries: readonly unknown[], prefix: string): readonly unknown[];
82
+ export declare function filterMayHold(filter: Filter, key: string): boolean;
83
+ /** Whether a segment may hold keys under a point prefix ((field, entity) or (field, value)). */
84
+ export declare function segmentMayHold(header: SegmentHeader, section: Section, prefix: string): boolean;
85
+ /** The tag counts of these writes: each tuple counts once, by its last write in key order. */
86
+ export declare function schemaOf(facts: Iterable<IndexedFact>): SegmentSchema;
87
+ export declare function encodeSegment(facts: readonly IndexedFact[], watermark: number): Readonly<{
88
+ bytes: Uint8Array;
89
+ ref: Omit<SegmentRef, "name">;
90
+ }>;
91
+ /** Where segments are read from: R2, behind the data center's cache when there is one. */
92
+ export type SegmentStore = Readonly<{
93
+ r2: R2Bucket;
94
+ /**
95
+ * The data center's cache: a URL on the Worker's zone per byte range, for the Cache API, and how
96
+ * to fill it after the answer. Segments never change, so entries never go stale.
97
+ */
98
+ colo: Readonly<{
99
+ key: (name: string, offset: number, length: number) => string;
100
+ fillLater: (fill: () => Promise<unknown>) => void;
101
+ }> | null;
102
+ }>;
103
+ /** `cacheHits`: this isolate's memory. `edgeHits`: the data center's cache. `r2Gets`: reads from R2. */
104
+ export type ReadMetrics = {
105
+ r2Gets: number;
106
+ edgeHits: number;
107
+ bytesRead: number;
108
+ blocksRead: number;
109
+ cacheHits: number;
110
+ };
111
+ export declare function emptyReadMetrics(): ReadMetrics;
112
+ /** Least recently used first out, bounded by the bytes its values were read from. */
113
+ export declare class ByteLru<V> {
114
+ private readonly limit;
115
+ private readonly entries;
116
+ private held;
117
+ evictions: number;
118
+ constructor(limit: number);
119
+ get(key: string): V | undefined;
120
+ set(key: string, value: V, bytes: number): void;
121
+ stats(): Readonly<{
122
+ entries: number;
123
+ bytes: number;
124
+ evictions: number;
125
+ }>;
126
+ }
127
+ export declare function segmentCacheStats(): {
128
+ headers: Readonly<{
129
+ entries: number;
130
+ bytes: number;
131
+ evictions: number;
132
+ }>;
133
+ blocks: Readonly<{
134
+ entries: number;
135
+ bytes: number;
136
+ evictions: number;
137
+ }>;
138
+ };
139
+ export declare function readHeader(store: SegmentStore, ref: SegmentRef, metrics: ReadMetrics): Promise<SegmentHeader>;
140
+ /** The entries of one block, as stored: WireFact for EAV, [value kind (DV_KINDS), value, count, WireFact] for AVE. */
141
+ export declare function readBlock(store: SegmentStore, ref: SegmentRef, section: Section, block: BlockRef, metrics: ReadMetrics): Promise<readonly unknown[]>;
142
+ export declare function eavFact(entry: unknown): IndexedFact;
143
+ export declare function aveEntry(entry: unknown): AveEntry;
144
+ /** Every fact in a segment, for compaction: its header, then its EAV blocks in one ranged GET, not the AVE half. */
145
+ export declare function readEavFacts(bucket: R2Bucket, ref: SegmentRef): Promise<IndexedFact[]>;
@@ -0,0 +1,451 @@
1
+ // Segments: the index's immutable R2 objects (RFD0008, "Index shards and R2").
2
+ //
3
+ // A segment holds the fact writes of one field bucket up to a watermark, in two sort orders:
4
+ // EAV (field, entity, value, source), then key: entity lookups and whole-field scans
5
+ // AVE (field, datalog value, entity, source), then key: value lookups
6
+ // Each order is cut into blocks of BLOCK_ENTRIES entries, and a header lists every block's first
7
+ // and last sort key, so a lookup reads only the blocks that can hold its prefix, by byte range.
8
+ //
9
+ // Layout: 10 ASCII digits (the header's length in bytes), the header JSON, then the blocks. Block
10
+ // offsets count from the end of the header. Segments are never rewritten, so any isolate may
11
+ // cache headers and blocks for as long as it likes.
12
+ //
13
+ // The header holds a Bloom filter per order, over the prefixes point lookups ask for ((field,
14
+ // entity) and (field, value)): a lookup skips a segment whose filter says it cannot hold its key,
15
+ // so it reads the few segments that do, not one block in every segment of the bucket. It also
16
+ // counts, by field and value tag, the tuples whose last write in the segment asserts them and
17
+ // those whose last write retracts them: what the graph's schema is read from (operations.ts).
18
+ import { factValueToDatalogValues } from "../datalog/value.js";
19
+ import { canonicalValue, compareFacts, fromWire, lastWrites, toWire } from "./facts.js";
20
+ import { epochOf } from "./keys.js";
21
+ export const SEGMENT_FORMAT = 3;
22
+ const FILTER_BITS_PER_KEY = 10;
23
+ const FILTER_HASHES = 7;
24
+ const BLOCK_ENTRIES = 256;
25
+ /** Block bounds keep this many characters of a key. */
26
+ export const BOUND_CHARS = 120;
27
+ const SEP = "\u0000";
28
+ const LENGTH_DIGITS = 10;
29
+ export const VALUE_TAGS = ["null", "text", "number", "decimal", "boolean", "bytes", "reference", "date", "date_time", "list", "map"];
30
+ /** How an AVE entry says what its value matches as. Format 3 had 0 and 1; decimals added 2, so older segments read as they were. */
31
+ const DV_KINDS = ["string", "integer", "decimal"];
32
+ /**
33
+ * Escapes NUL (`\u0000`, the key separator) and `\u0001` so every AVE key component is disjoint
34
+ * from `SEP` and preserves lexicographic order between `aveKey`, `avePrefix`, and `aveLead`.
35
+ */
36
+ function escapeValue(value) {
37
+ return value.includes("\u0000") || value.includes("\u0001")
38
+ ? value.replaceAll("\u0001", "\u0001\u0002").replaceAll("\u0000", "\u0001\u0001")
39
+ : value;
40
+ }
41
+ export function dvKey(v) {
42
+ return `${v.type === "integer" ? "i" : v.type === "decimal" ? "d" : "s"}:${escapeValue(v.value)}`;
43
+ }
44
+ export function eavPrefix(field, entity) {
45
+ return entity === undefined ? field + SEP : field + SEP + entity + SEP;
46
+ }
47
+ export function avePrefix(field, dv) {
48
+ return field + SEP + dvKey(dv) + SEP;
49
+ }
50
+ function eavKey(f) {
51
+ return f.field + SEP + f.entity + SEP + canonicalValue(f.value) + SEP + f.source;
52
+ }
53
+ function aveKey(e) {
54
+ return e.fact.field + SEP + dvKey(e.dv) + SEP + e.fact.entity + SEP + e.fact.source + SEP + canonicalValue(e.fact.value);
55
+ }
56
+ export function aveEntriesOf(f) {
57
+ const counts = new Map();
58
+ for (const dv of factValueToDatalogValues(f.value)) {
59
+ const k = dvKey(dv), c = counts.get(k);
60
+ if (c)
61
+ c.count++;
62
+ else
63
+ counts.set(k, { dv, count: 1 });
64
+ }
65
+ return [...counts.values()].map(({ dv, count }) => ({ dv, count, fact: f }));
66
+ }
67
+ // Truncated bounds stay bounds: a prefix of the first key is not above it, and a prefix followed by
68
+ // U+FFFF is not below the last key (unless the cut-off part holds U+FFFF, so then it is kept whole).
69
+ function loBound(key) {
70
+ return key.length <= BOUND_CHARS ? key : key.slice(0, BOUND_CHARS);
71
+ }
72
+ function hiBound(key) {
73
+ return key.length <= BOUND_CHARS || key.slice(BOUND_CHARS).includes("\uffff") ? key : `${key.slice(0, BOUND_CHARS)}\uffff`;
74
+ }
75
+ /** Whether a block whose keys lie in [lo, hi] may hold a key starting with `prefix`. */
76
+ export function blockMayHold(block, prefix) {
77
+ // Keys starting with `prefix` are contiguous; a key above `prefix` that does not start with it is above all of them.
78
+ return block.hi >= prefix && (block.lo <= prefix || block.lo.startsWith(prefix));
79
+ }
80
+ /**
81
+ * The blocks that may hold keys starting with `prefix`: a contiguous run, found by binary search.
82
+ * Blocks are sorted and their `hi` bounds never decrease, so the first candidate is the first block
83
+ * whose `hi` is not below the prefix.
84
+ */
85
+ export function blocksFor(blocks, prefix) {
86
+ let lo = 0, hi = blocks.length;
87
+ while (lo < hi) {
88
+ const mid = (lo + hi) >>> 1;
89
+ const block = blocks[mid];
90
+ if (block !== undefined && block.hi < prefix)
91
+ lo = mid + 1;
92
+ else
93
+ hi = mid;
94
+ }
95
+ let end = lo;
96
+ while (end < blocks.length) {
97
+ const block = blocks[end];
98
+ if (block === undefined || !blockMayHold(block, prefix))
99
+ break;
100
+ end++;
101
+ }
102
+ return blocks.slice(lo, end);
103
+ }
104
+ /**
105
+ * The entries of a block, as stored, whose sort key starts with `prefix`: a contiguous run, found by
106
+ * binary search on the key's leading part (field, then entity for EAV or value for AVE). Neither
107
+ * part holds the separator, so ordering by the leading part agrees with ordering by the whole key.
108
+ */
109
+ export function entriesUnder(section, entries, prefix) {
110
+ const lead = section === "eav" ? eavLead : aveLead;
111
+ let lo = 0, hi = entries.length;
112
+ while (lo < hi) {
113
+ const mid = (lo + hi) >>> 1;
114
+ if (lead(entries[mid]) < prefix)
115
+ lo = mid + 1;
116
+ else
117
+ hi = mid;
118
+ }
119
+ // The run under the prefix starts at lo, and ends at the first entry after it that is not under
120
+ // it: a binary search too, so a scan of a whole field builds a few leads a block, not one an entry.
121
+ let end = lo;
122
+ hi = entries.length;
123
+ while (end < hi) {
124
+ const mid = (end + hi) >>> 1;
125
+ if (lead(entries[mid]).startsWith(prefix))
126
+ end = mid + 1;
127
+ else
128
+ hi = mid;
129
+ }
130
+ return entries.slice(lo, end);
131
+ }
132
+ // The key's leading part, straight from a stored entry: field SEP entity SEP, or field SEP value SEP.
133
+ function eavLead(entry) {
134
+ if (!Array.isArray(entry))
135
+ throw new Error("segment EAV entry is not an array");
136
+ const field = entry[6], entity = entry[5];
137
+ if (typeof field !== "string" || typeof entity !== "string")
138
+ throw new Error("segment EAV entry has invalid lead");
139
+ return `${field}${SEP}${entity}${SEP}`;
140
+ }
141
+ function aveLead(entry) {
142
+ if (!Array.isArray(entry))
143
+ throw new Error("segment AVE entry is not an array");
144
+ const kind = entry[0], value = entry[1], w = entry[3];
145
+ if (typeof kind !== "number" || typeof value !== "string" || !Array.isArray(w) || typeof w[6] !== "string") {
146
+ throw new Error("segment AVE entry has invalid lead");
147
+ }
148
+ return `${w[6]}${SEP}${dvKey({ type: DV_KINDS[kind] ?? "string", value })}${SEP}`;
149
+ }
150
+ function hashPair(key) {
151
+ let a = 0x811c9dc5, b = 0x9747b28c;
152
+ for (let i = 0; i < key.length; i++) {
153
+ const c = key.charCodeAt(i);
154
+ a = Math.imul(a ^ c, 0x01000193);
155
+ b = Math.imul(b ^ c, 0x5bd1e995);
156
+ b ^= b >>> 15;
157
+ }
158
+ return [a >>> 0, (b >>> 0) | 1];
159
+ }
160
+ function buildFilter(keys) {
161
+ const bits = Math.max(64, Math.ceil(keys.size * FILTER_BITS_PER_KEY));
162
+ const data = new Uint8Array(Math.ceil(bits / 8));
163
+ for (const key of keys) {
164
+ const [h1, h2] = hashPair(key);
165
+ for (let i = 0; i < FILTER_HASHES; i++) {
166
+ const bit = ((h1 + Math.imul(i, h2)) >>> 0) % bits;
167
+ const idx = bit >>> 3;
168
+ data[idx] = (data[idx] ?? 0) | (1 << (bit & 7));
169
+ }
170
+ }
171
+ return { bits, hashes: FILTER_HASHES, data };
172
+ }
173
+ export function filterMayHold(filter, key) {
174
+ const [h1, h2] = hashPair(key);
175
+ for (let i = 0; i < filter.hashes; i++) {
176
+ const bit = ((h1 + Math.imul(i, h2)) >>> 0) % filter.bits;
177
+ if (((filter.data[bit >>> 3] ?? 0) & (1 << (bit & 7))) === 0)
178
+ return false;
179
+ }
180
+ return true;
181
+ }
182
+ /** Whether a segment may hold keys under a point prefix ((field, entity) or (field, value)). */
183
+ export function segmentMayHold(header, section, prefix) {
184
+ return filterMayHold(header.filters[section], prefix);
185
+ }
186
+ /** The tag counts of these writes: each tuple counts once, by its last write in key order. */
187
+ export function schemaOf(facts) {
188
+ const schema = {};
189
+ for (const f of lastWrites(facts)) {
190
+ const counts = ((schema[f.field] ??= {})[f.value.type] ??= { asserted: 0, retracted: 0 });
191
+ if (f.retraction)
192
+ counts.retracted++;
193
+ else
194
+ counts.asserted++;
195
+ }
196
+ return schema;
197
+ }
198
+ function toBase64(bytes) {
199
+ let text = "";
200
+ for (let i = 0; i < bytes.length; i += 0x8000)
201
+ text += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
202
+ return btoa(text);
203
+ }
204
+ function fromBase64(text) {
205
+ const raw = atob(text);
206
+ const bytes = new Uint8Array(raw.length);
207
+ for (let i = 0; i < raw.length; i++)
208
+ bytes[i] = raw.charCodeAt(i);
209
+ return bytes;
210
+ }
211
+ const storedFilter = (f) => ({ bits: f.bits, hashes: f.hashes, data: toBase64(f.data) });
212
+ export function encodeSegment(facts, watermark) {
213
+ const encoder = new TextEncoder();
214
+ const eav = facts.map((f) => ({ key: eavKey(f), f })).sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : compareFacts(a.f, b.f)));
215
+ const ave = facts.flatMap(aveEntriesOf).map((e) => ({ key: aveKey(e), e })).sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : compareFacts(a.e.fact, b.e.fact)));
216
+ const chunks = [];
217
+ let offset = 0;
218
+ const blocks = (rows, encode) => {
219
+ const out = [];
220
+ for (let i = 0; i < rows.length; i += BLOCK_ENTRIES) {
221
+ const slice = rows.slice(i, i + BLOCK_ENTRIES);
222
+ const firstRow = slice[0], lastRow = slice[slice.length - 1];
223
+ if (firstRow === undefined || lastRow === undefined)
224
+ continue;
225
+ const bytes = encoder.encode(JSON.stringify(slice.map(encode)));
226
+ out.push({ lo: loBound(firstRow.key), hi: hiBound(lastRow.key), offset, length: bytes.byteLength, entries: slice.length });
227
+ chunks.push(bytes);
228
+ offset += bytes.byteLength;
229
+ }
230
+ return out;
231
+ };
232
+ const eavBlocks = blocks(eav, (row) => toWire(row.f));
233
+ const aveBlocks = blocks(ave, (row) => [DV_KINDS.indexOf(row.e.dv.type), row.e.dv.value, row.e.count, toWire(row.e.fact)]);
234
+ let minEpoch = Infinity, maxEpoch = -Infinity;
235
+ for (const f of facts) {
236
+ const e = epochOf(f.ts);
237
+ if (e < minEpoch)
238
+ minEpoch = e;
239
+ if (e > maxEpoch)
240
+ maxEpoch = e;
241
+ }
242
+ const eavKeys = new Set(facts.map((f) => eavPrefix(f.field, f.entity)));
243
+ const aveKeys = new Set(ave.map((row) => avePrefix(row.e.fact.field, row.e.dv)));
244
+ const header = {
245
+ format: SEGMENT_FORMAT, watermark, minEpoch, maxEpoch, facts: facts.length, eav: eavBlocks, ave: aveBlocks,
246
+ filters: { eav: storedFilter(buildFilter(eavKeys)), ave: storedFilter(buildFilter(aveKeys)) }, schema: schemaOf(facts),
247
+ };
248
+ const headerBytes = encoder.encode(JSON.stringify(header));
249
+ const length = encoder.encode(String(headerBytes.byteLength).padStart(LENGTH_DIGITS, "0"));
250
+ const bytes = new Uint8Array(length.byteLength + headerBytes.byteLength + offset);
251
+ bytes.set(length, 0);
252
+ bytes.set(headerBytes, length.byteLength);
253
+ let at = length.byteLength + headerBytes.byteLength;
254
+ for (const chunk of chunks) {
255
+ bytes.set(chunk, at);
256
+ at += chunk.byteLength;
257
+ }
258
+ return { bytes, ref: { facts: facts.length, bytes: bytes.byteLength, headerBytes: headerBytes.byteLength, minEpoch: header.minEpoch, maxEpoch: header.maxEpoch } };
259
+ }
260
+ export function emptyReadMetrics() {
261
+ return { r2Gets: 0, edgeHits: 0, bytesRead: 0, blocksRead: 0, cacheHits: 0 };
262
+ }
263
+ async function readRange(store, name, offset, length, metrics) {
264
+ const cache = store.colo !== null && typeof caches !== "undefined" ? caches.default : null;
265
+ const key = store.colo?.key(name, offset, length);
266
+ if (cache && key) {
267
+ const hit = await cache.match(key);
268
+ if (hit) {
269
+ metrics.edgeHits++;
270
+ return hit.text();
271
+ }
272
+ }
273
+ const object = await store.r2.get(name, { range: { offset, length } });
274
+ if (object === null)
275
+ throw new Error(`segment ${name} is missing`);
276
+ const text = await object.text();
277
+ metrics.r2Gets++;
278
+ metrics.bytesRead += length;
279
+ if (cache && key) {
280
+ // After the answer: the query has the bytes, and a colo that misses them reads R2 again.
281
+ store.colo?.fillLater(() => cache.put(key, new Response(text, { headers: { "cache-control": "public, max-age=604800, immutable" } })));
282
+ }
283
+ return text;
284
+ }
285
+ /** Least recently used first out, bounded by the bytes its values were read from. */
286
+ export class ByteLru {
287
+ limit;
288
+ entries = new Map();
289
+ held = 0;
290
+ evictions = 0;
291
+ constructor(limit) {
292
+ this.limit = limit;
293
+ }
294
+ get(key) {
295
+ const entry = this.entries.get(key);
296
+ if (entry === undefined)
297
+ return undefined;
298
+ this.entries.delete(key);
299
+ this.entries.set(key, entry);
300
+ return entry.value;
301
+ }
302
+ set(key, value, bytes) {
303
+ if (bytes > this.limit)
304
+ return;
305
+ const prior = this.entries.get(key);
306
+ if (prior) {
307
+ this.entries.delete(key);
308
+ this.held -= prior.bytes;
309
+ }
310
+ this.entries.set(key, { value, bytes });
311
+ this.held += bytes;
312
+ for (const [oldest, entry] of this.entries) {
313
+ if (this.held <= this.limit)
314
+ break;
315
+ this.entries.delete(oldest);
316
+ this.held -= entry.bytes;
317
+ this.evictions++;
318
+ }
319
+ }
320
+ stats() {
321
+ return { entries: this.entries.size, bytes: this.held, evictions: this.evictions };
322
+ }
323
+ }
324
+ // Per-isolate caches; segments are immutable, so nothing here goes stale. Bounded in the bytes read,
325
+ // since an isolate has 128 MB and parsed JSON takes a few times its text: a cache counted in entries
326
+ // (200,000 of them, before) holds 80 MB or more of facts, and a busy isolate then spends its time
327
+ // collecting garbage.
328
+ const HEADER_CACHE_BYTES = 16 * 2 ** 20;
329
+ const BLOCK_CACHE_BYTES = 16 * 2 ** 20;
330
+ const headers = new ByteLru(HEADER_CACHE_BYTES);
331
+ const blockCache = new ByteLru(BLOCK_CACHE_BYTES);
332
+ export function segmentCacheStats() {
333
+ return { headers: headers.stats(), blocks: blockCache.stats() };
334
+ }
335
+ export async function readHeader(store, ref, metrics) {
336
+ const cached = headers.get(ref.name);
337
+ if (cached) {
338
+ metrics.cacheHits++;
339
+ return cached;
340
+ }
341
+ const text = await readRange(store, ref.name, 0, LENGTH_DIGITS + ref.headerBytes, metrics);
342
+ const header = parseHeader(JSON.parse(text.slice(LENGTH_DIGITS)));
343
+ headers.set(ref.name, header, ref.headerBytes);
344
+ return header;
345
+ }
346
+ function isCount(n) {
347
+ return typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
348
+ }
349
+ function isObjectRecord(value) {
350
+ return typeof value === "object" && value !== null && !Array.isArray(value);
351
+ }
352
+ const VALUE_TAG_SET = new Set(VALUE_TAGS);
353
+ function isSchema(input) {
354
+ if (!isObjectRecord(input))
355
+ return false;
356
+ return Object.values(input).every((tags) => isObjectRecord(tags)
357
+ && Object.entries(tags).every(([tag, counts]) => VALUE_TAG_SET.has(tag)
358
+ && isObjectRecord(counts)
359
+ && isCount(counts["asserted"]) && isCount(counts["retracted"])));
360
+ }
361
+ function isBlockRefArray(input) {
362
+ return Array.isArray(input);
363
+ }
364
+ function parseFilter(f) {
365
+ if (!isObjectRecord(f) || !isCount(f["bits"]) || f["bits"] < 8 || !isCount(f["hashes"]) || f["hashes"] < 1 || typeof f["data"] !== "string") {
366
+ throw new Error("segment filter is invalid");
367
+ }
368
+ const data = fromBase64(f["data"]);
369
+ if (data.length * 8 < f["bits"])
370
+ throw new Error("segment filter is short");
371
+ return { bits: f["bits"], hashes: f["hashes"], data };
372
+ }
373
+ function parseHeader(input) {
374
+ if (!isObjectRecord(input) || input["format"] !== SEGMENT_FORMAT || !isBlockRefArray(input["eav"]) || !isBlockRefArray(input["ave"])) {
375
+ throw new Error("segment header is invalid");
376
+ }
377
+ const watermark = input["watermark"], facts = input["facts"], minEpoch = input["minEpoch"], maxEpoch = input["maxEpoch"];
378
+ if (typeof watermark !== "number" || typeof facts !== "number" || typeof minEpoch !== "number" || typeof maxEpoch !== "number") {
379
+ throw new Error("segment header is invalid");
380
+ }
381
+ if (!isSchema(input["schema"]))
382
+ throw new Error("segment schema is invalid");
383
+ const rawFilters = isObjectRecord(input["filters"]) ? input["filters"] : undefined;
384
+ return {
385
+ format: SEGMENT_FORMAT,
386
+ watermark,
387
+ facts,
388
+ minEpoch,
389
+ maxEpoch,
390
+ eav: input["eav"],
391
+ ave: input["ave"],
392
+ schema: input["schema"],
393
+ filters: { eav: parseFilter(rawFilters?.["eav"]), ave: parseFilter(rawFilters?.["ave"]) },
394
+ };
395
+ }
396
+ /** The entries of one block, as stored: WireFact for EAV, [value kind (DV_KINDS), value, count, WireFact] for AVE. */
397
+ export async function readBlock(store, ref, section, block, metrics) {
398
+ const key = `${ref.name}#${section}#${block.offset}`;
399
+ const cached = blockCache.get(key);
400
+ if (cached) {
401
+ metrics.cacheHits++;
402
+ return cached;
403
+ }
404
+ const text = await readRange(store, ref.name, LENGTH_DIGITS + ref.headerBytes + block.offset, block.length, metrics);
405
+ metrics.blocksRead++;
406
+ const entries = JSON.parse(text);
407
+ if (!Array.isArray(entries) || entries.length !== block.entries)
408
+ throw new Error(`segment ${ref.name} has a damaged block`);
409
+ blockCache.set(key, entries, block.length);
410
+ return entries;
411
+ }
412
+ export function eavFact(entry) {
413
+ return fromWire(entry);
414
+ }
415
+ export function aveEntry(entry) {
416
+ if (!Array.isArray(entry) || entry.length !== 4)
417
+ throw new Error("segment AVE entry is not a 4-element array");
418
+ const [kind, value, count, wire] = entry;
419
+ if (typeof kind !== "number" || typeof value !== "string" || typeof count !== "number") {
420
+ throw new Error("segment AVE entry has invalid fields");
421
+ }
422
+ const type = DV_KINDS[kind];
423
+ if (type === undefined)
424
+ throw new Error(`segment AVE entry has an unknown value kind ${kind}`);
425
+ return { dv: { type, value }, count, fact: fromWire(wire) };
426
+ }
427
+ /** Every fact in a segment, for compaction: its header, then its EAV blocks in one ranged GET, not the AVE half. */
428
+ export async function readEavFacts(bucket, ref) {
429
+ const ranged = async (offset, length) => {
430
+ const object = await bucket.get(ref.name, { range: { offset, length } });
431
+ if (object === null)
432
+ throw new Error(`segment ${ref.name} is missing`);
433
+ return new Uint8Array(await object.arrayBuffer());
434
+ };
435
+ const decoder = new TextDecoder();
436
+ const header = parseHeader(JSON.parse(decoder.decode((await ranged(0, LENGTH_DIGITS + ref.headerBytes)).subarray(LENGTH_DIGITS))));
437
+ const last = header.eav[header.eav.length - 1];
438
+ if (last === undefined)
439
+ return [];
440
+ // Offsets count bytes, so decode from the bytes; EAV blocks come first, from offset 0.
441
+ const bytes = await ranged(LENGTH_DIGITS + ref.headerBytes, last.offset + last.length);
442
+ const facts = [];
443
+ for (const b of header.eav) {
444
+ const parsed = JSON.parse(decoder.decode(bytes.subarray(b.offset, b.offset + b.length)));
445
+ if (!Array.isArray(parsed))
446
+ throw new Error(`segment ${ref.name} has a damaged EAV block`);
447
+ for (const w of parsed)
448
+ facts.push(fromWire(w));
449
+ }
450
+ return facts;
451
+ }
@@ -0,0 +1,82 @@
1
+ import { DurableObject } from "cloudflare:workers";
2
+ import { type AdoptInput, type ShardInput, type ShardRpc, type ShardStatus, type StorageEnv } from "./environment.js";
3
+ import { type SegmentRef } from "./segment.js";
4
+ export type { AdoptInput, FlushStat, ShardInput, ShardStatus } from "./environment.js";
5
+ export declare class IndexShardDO extends DurableObject<StorageEnv> implements ShardRpc {
6
+ private readonly sql;
7
+ private meta;
8
+ private buckets;
9
+ /** Each live segment's place in its bucket: appended ones take their seq, a merge takes the place of the first segment it replaces. */
10
+ private readonly positions;
11
+ private graphWatermark;
12
+ private reportPending;
13
+ private readonly flushes;
14
+ private readonly errors;
15
+ private readonly compactions;
16
+ private behindStreak;
17
+ private partitionLoad;
18
+ /** The root's layout, once it shows this shard split. */
19
+ private splitDue;
20
+ constructor(ctx: DurableObjectState, env: StorageEnv);
21
+ private load;
22
+ /**
23
+ * A shard written before layouts could change kept its graph's fixed partitions and shard count
24
+ * in `meta`: its leaf is its number in a full tree of that many shards (layout.ts), and its
25
+ * layout the graph's first.
26
+ */
27
+ private adoptFixedLayout;
28
+ /** Stores the shard's metadata, then takes it: what the shard acts on is always what it stored. */
29
+ private storeMeta;
30
+ /**
31
+ * Writes the metadata inside a transaction, whose caller takes it once the transaction commits:
32
+ * a rolled-back flush that had already taken its watermark would hand off from past the facts it
33
+ * never stored, and they would be missing from the index for good.
34
+ */
35
+ private writeMeta;
36
+ /**
37
+ * The root starts the shards of its layout. A shard of the graph's first layout starts empty; a
38
+ * half made by a split has nothing until the shard it split from hands it its buckets (adopt).
39
+ */
40
+ start(input: ShardInput): Promise<void>;
41
+ private requireMeta;
42
+ /** Takes the partitions of a newer layout for the next flush, and notes when it shows this shard split. */
43
+ private takeLayout;
44
+ /**
45
+ * The half of a split shard takes over its buckets, once: a repeated call, from a shard whose
46
+ * call failed or that restarted mid-split, takes nothing again. Every call reports before it
47
+ * answers, since the root must name these buckets' segments from this shard before the one it
48
+ * split from stops reporting them: that one drops them as soon as this answers.
49
+ */
50
+ adopt(input: AdoptInput): Promise<void>;
51
+ /**
52
+ * Splits any packed L0 segment shared between kept and moved buckets during a shard split so
53
+ * each shard owns disjoint R2 objects and can garbage-collect retired segments locally.
54
+ */
55
+ private isolateMovedBuckets;
56
+ /** Hands one half of this shard's buckets to its new sibling object and commits the new depth. */
57
+ private splitHalf;
58
+ /** Hands the buckets of each new half to its object, until this shard is a leaf of the root's layout. */
59
+ private split;
60
+ alarm(): Promise<void>;
61
+ /** Returns whether a partition held back more than one flush takes, holds rows in an open epoch, and how many txs flushed. */
62
+ private flush;
63
+ /**
64
+ * Merges one run of segments, in the bucket with the most of them, if any bucket has a run, and
65
+ * reports it. The merged segment takes the place of the first one it replaces; the replaced ones
66
+ * are deleted RETIRE_AFTER_MS later, once readers holding an older manifest are done with them.
67
+ */
68
+ private compactOnce;
69
+ private put;
70
+ /** Tells the root this shard's watermark and segments; it answers with the graph's watermark and its layout. */
71
+ private report;
72
+ private hasUnconfirmedRetired;
73
+ private hasRetired;
74
+ /** Earliest wall time at which a retired segment becomes eligible for R2 deletion, or null. */
75
+ private nextRetiredDeleteAt;
76
+ private deleteRetired;
77
+ status(brief?: boolean): Promise<ShardStatus>;
78
+ }
79
+ export declare function compactionRun(refs: readonly SegmentRef[], graphWatermark: number): {
80
+ start: number;
81
+ end: number;
82
+ } | null;