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,67 @@
|
|
|
1
|
+
export type Era = Readonly<{
|
|
2
|
+
/** The layout version that added it. */
|
|
3
|
+
version: number;
|
|
4
|
+
from: number;
|
|
5
|
+
count: number;
|
|
6
|
+
/** The first epoch its partitions may stamp. */
|
|
7
|
+
since: number;
|
|
8
|
+
/** When the root added it, in ms of its clock: how long a token may still be in an earlier home. */
|
|
9
|
+
at: number;
|
|
10
|
+
}>;
|
|
11
|
+
export type Leaf = Readonly<{
|
|
12
|
+
depth: number;
|
|
13
|
+
prefix: number;
|
|
14
|
+
}>;
|
|
15
|
+
/** `firstDepth`: the depth of the first layout's shards. A shard deeper than it was made by a split, from the shard it split from. */
|
|
16
|
+
export type Layout = Readonly<{
|
|
17
|
+
version: number;
|
|
18
|
+
eras: readonly Era[];
|
|
19
|
+
shards: readonly Leaf[];
|
|
20
|
+
firstDepth: number;
|
|
21
|
+
}>;
|
|
22
|
+
/** What a partition keeps of the layout: enough to know its homes and floors. */
|
|
23
|
+
export type PartitionLayout = Readonly<{
|
|
24
|
+
version: number;
|
|
25
|
+
eras: readonly Era[];
|
|
26
|
+
}>;
|
|
27
|
+
/** Buckets are 2^MAX_DEPTH, so a shard splits at most this deep. */
|
|
28
|
+
export declare const MAX_DEPTH: number;
|
|
29
|
+
/**
|
|
30
|
+
* A graph's first layout: `partitions` partitions and a full tree of `shards` index shards, a power
|
|
31
|
+
* of two. A graph laid out before layouts could change has the same, from time 0.
|
|
32
|
+
*/
|
|
33
|
+
export declare function initialLayout(partitions: number, shards: number, at: number): Layout;
|
|
34
|
+
/** Whether `shards` shards make a full tree of the layout: a power of two, up to one shard a bucket. */
|
|
35
|
+
export declare function isShardCount(shards: number): boolean;
|
|
36
|
+
export declare function partitionCount(layout: PartitionLayout): number;
|
|
37
|
+
export declare function eraOf(layout: PartitionLayout, partition: number): Era | undefined;
|
|
38
|
+
/** The first epoch a partition may stamp: its era's start (rule newPartitionsStartAtTheirEpoch). */
|
|
39
|
+
export declare function floorOf(layout: PartitionLayout, partition: number): number;
|
|
40
|
+
/**
|
|
41
|
+
* The epoch a shard that read `version` must stay below until it reads the partitions added since:
|
|
42
|
+
* the start of the first era it does not know, minus one. Infinity when it knows them all.
|
|
43
|
+
*/
|
|
44
|
+
export declare function capFor(layout: PartitionLayout, version: number): number;
|
|
45
|
+
/**
|
|
46
|
+
* Jump consistent hashing (Lamping and Veach, 2014) over a seed: as the count grows, a seed's home
|
|
47
|
+
* stays where it was or moves to one of the new partitions, never between old ones. The random
|
|
48
|
+
* steps are xorshift32 from the seed, so the same seed always takes the same jumps.
|
|
49
|
+
*/
|
|
50
|
+
export declare function homeOf(seed: number, count: number): number;
|
|
51
|
+
/**
|
|
52
|
+
* The partitions where a token may still be stored, other than its home now: its homes under the
|
|
53
|
+
* counts of eras that ended within the token window (`windowMs` before `now`). A write is stored
|
|
54
|
+
* at most once if its home asks these first (rule movedTokensAreClaimed).
|
|
55
|
+
*/
|
|
56
|
+
export declare function earlierHomes(layout: PartitionLayout, seed: number, now: number, windowMs: number): number[];
|
|
57
|
+
export declare function owns(leaf: Leaf, bucket: number): boolean;
|
|
58
|
+
export declare function ownerOf(layout: Layout, bucket: number): Leaf;
|
|
59
|
+
export declare function isLeaf(layout: Layout, leaf: Leaf): boolean;
|
|
60
|
+
/** The two halves of a leaf: the first keeps its object. */
|
|
61
|
+
export declare function halves(leaf: Leaf): readonly [Leaf, Leaf];
|
|
62
|
+
/** The layout with `count` partitions: an era of the new ones, which partition 0 gives its first epoch when it installs it. */
|
|
63
|
+
export declare function withEra(layout: Layout, count: number, at: number): Layout;
|
|
64
|
+
export declare function withSplit(layout: Layout, leaf: Leaf): Layout;
|
|
65
|
+
export declare function partitionLayout(layout: Layout): PartitionLayout;
|
|
66
|
+
/** The newer of two layouts; a partition's copy may be newer than a shard's, or the reverse. */
|
|
67
|
+
export declare function newer<L extends PartitionLayout>(a: L, b: L | null | undefined): L;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// A graph's layout (RFD0011, specs/growing-partitions.ts): its partitions, added in eras, and its
|
|
2
|
+
// index shards, the leaves of a tree of field-bucket bits.
|
|
3
|
+
//
|
|
4
|
+
// Partitions only grow. An era adds partitions [from, from + count) and starts at epoch `since`:
|
|
5
|
+
// those partitions never stamp a write below it, and partition 0 chose it, one past the last epoch
|
|
6
|
+
// it had closed. The root keeps the layout and partition 0 a copy, which is how index shards that
|
|
7
|
+
// read an older one learn it before their watermark passes `since` (rule layoutThroughPartitionZero).
|
|
8
|
+
//
|
|
9
|
+
// A shard is a leaf (depth, prefix): it owns the buckets b with b mod 2^depth = prefix. Splitting
|
|
10
|
+
// it makes (depth + 1, prefix), the same object, and (depth + 1, prefix + 2^depth), a new one. Leaf
|
|
11
|
+
// prefixes are unique, so a shard's object is named by its prefix alone: a graph with one shard,
|
|
12
|
+
// or 2^d shards from the start, has the names it always had.
|
|
13
|
+
import { BUCKETS } from "./facts.js";
|
|
14
|
+
/** Buckets are 2^MAX_DEPTH, so a shard splits at most this deep. */
|
|
15
|
+
export const MAX_DEPTH = Math.log2(BUCKETS);
|
|
16
|
+
/**
|
|
17
|
+
* A graph's first layout: `partitions` partitions and a full tree of `shards` index shards, a power
|
|
18
|
+
* of two. A graph laid out before layouts could change has the same, from time 0.
|
|
19
|
+
*/
|
|
20
|
+
export function initialLayout(partitions, shards, at) {
|
|
21
|
+
if (!isShardCount(shards))
|
|
22
|
+
throw new RangeError(`a graph's index shards are a power of two up to ${BUCKETS}, not ${shards}`);
|
|
23
|
+
const depth = Math.log2(shards);
|
|
24
|
+
return {
|
|
25
|
+
version: 1,
|
|
26
|
+
eras: [{ version: 1, from: 0, count: partitions, since: 0, at }],
|
|
27
|
+
shards: Array.from({ length: shards }, (_, prefix) => ({ depth, prefix })),
|
|
28
|
+
firstDepth: depth,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/** Whether `shards` shards make a full tree of the layout: a power of two, up to one shard a bucket. */
|
|
32
|
+
export function isShardCount(shards) {
|
|
33
|
+
return Number.isSafeInteger(shards) && shards >= 1 && shards <= BUCKETS && Number.isInteger(Math.log2(shards));
|
|
34
|
+
}
|
|
35
|
+
export function partitionCount(layout) {
|
|
36
|
+
const last = layout.eras[layout.eras.length - 1];
|
|
37
|
+
return last === undefined ? 0 : last.from + last.count;
|
|
38
|
+
}
|
|
39
|
+
export function eraOf(layout, partition) {
|
|
40
|
+
return layout.eras.find((era) => partition >= era.from && partition < era.from + era.count);
|
|
41
|
+
}
|
|
42
|
+
/** The first epoch a partition may stamp: its era's start (rule newPartitionsStartAtTheirEpoch). */
|
|
43
|
+
export function floorOf(layout, partition) {
|
|
44
|
+
return eraOf(layout, partition)?.since ?? 0;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The epoch a shard that read `version` must stay below until it reads the partitions added since:
|
|
48
|
+
* the start of the first era it does not know, minus one. Infinity when it knows them all.
|
|
49
|
+
*/
|
|
50
|
+
export function capFor(layout, version) {
|
|
51
|
+
const unknown = layout.eras.find((era) => era.version > version);
|
|
52
|
+
return unknown === undefined ? Infinity : unknown.since - 1;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Jump consistent hashing (Lamping and Veach, 2014) over a seed: as the count grows, a seed's home
|
|
56
|
+
* stays where it was or moves to one of the new partitions, never between old ones. The random
|
|
57
|
+
* steps are xorshift32 from the seed, so the same seed always takes the same jumps.
|
|
58
|
+
*/
|
|
59
|
+
export function homeOf(seed, count) {
|
|
60
|
+
let b = -1;
|
|
61
|
+
let j = 0;
|
|
62
|
+
let x = seed >>> 0 || 0x9e3779b9;
|
|
63
|
+
while (j < count) {
|
|
64
|
+
b = j;
|
|
65
|
+
x ^= x << 13;
|
|
66
|
+
x >>>= 0;
|
|
67
|
+
x ^= x >>> 17;
|
|
68
|
+
x ^= x << 5;
|
|
69
|
+
x >>>= 0;
|
|
70
|
+
j = Math.floor((b + 1) * (0x100000000 / (x + 1)));
|
|
71
|
+
}
|
|
72
|
+
return b;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The partitions where a token may still be stored, other than its home now: its homes under the
|
|
76
|
+
* counts of eras that ended within the token window (`windowMs` before `now`). A write is stored
|
|
77
|
+
* at most once if its home asks these first (rule movedTokensAreClaimed).
|
|
78
|
+
*/
|
|
79
|
+
export function earlierHomes(layout, seed, now, windowMs) {
|
|
80
|
+
const home = homeOf(seed, partitionCount(layout));
|
|
81
|
+
const homes = new Set();
|
|
82
|
+
for (let i = 0; i + 1 < layout.eras.length; i++) {
|
|
83
|
+
const current = layout.eras[i];
|
|
84
|
+
const next = layout.eras[i + 1];
|
|
85
|
+
if (current === undefined || next === undefined)
|
|
86
|
+
continue;
|
|
87
|
+
if (now - next.at > windowMs)
|
|
88
|
+
continue;
|
|
89
|
+
const count = current.from + current.count;
|
|
90
|
+
const earlier = homeOf(seed, count);
|
|
91
|
+
if (earlier !== home)
|
|
92
|
+
homes.add(earlier);
|
|
93
|
+
}
|
|
94
|
+
return [...homes].sort((a, b) => a - b);
|
|
95
|
+
}
|
|
96
|
+
export function owns(leaf, bucket) {
|
|
97
|
+
return bucket % 2 ** leaf.depth === leaf.prefix;
|
|
98
|
+
}
|
|
99
|
+
export function ownerOf(layout, bucket) {
|
|
100
|
+
const leaf = layout.shards.find((l) => owns(l, bucket));
|
|
101
|
+
if (leaf === undefined)
|
|
102
|
+
throw new Error(`no index shard owns bucket ${bucket}`);
|
|
103
|
+
return leaf;
|
|
104
|
+
}
|
|
105
|
+
export function isLeaf(layout, leaf) {
|
|
106
|
+
return layout.shards.some((l) => l.depth === leaf.depth && l.prefix === leaf.prefix);
|
|
107
|
+
}
|
|
108
|
+
/** The two halves of a leaf: the first keeps its object. */
|
|
109
|
+
export function halves(leaf) {
|
|
110
|
+
return [{ depth: leaf.depth + 1, prefix: leaf.prefix }, { depth: leaf.depth + 1, prefix: leaf.prefix + 2 ** leaf.depth }];
|
|
111
|
+
}
|
|
112
|
+
/** The layout with `count` partitions: an era of the new ones, which partition 0 gives its first epoch when it installs it. */
|
|
113
|
+
export function withEra(layout, count, at) {
|
|
114
|
+
const total = partitionCount(layout);
|
|
115
|
+
if (count <= total)
|
|
116
|
+
throw new RangeError(`a graph of ${total} partitions grows to more, not ${count}`);
|
|
117
|
+
const version = layout.version + 1;
|
|
118
|
+
return { ...layout, version, eras: [...layout.eras, { version, from: total, count: count - total, since: 0, at }] };
|
|
119
|
+
}
|
|
120
|
+
export function withSplit(layout, leaf) {
|
|
121
|
+
if (!isLeaf(layout, leaf))
|
|
122
|
+
throw new RangeError(`shard ${leaf.prefix} at depth ${leaf.depth} is not a leaf of the layout`);
|
|
123
|
+
if (leaf.depth >= MAX_DEPTH)
|
|
124
|
+
throw new RangeError(`shard ${leaf.prefix} owns one bucket and cannot split`);
|
|
125
|
+
const shards = layout.shards.flatMap((l) => (l.depth === leaf.depth && l.prefix === leaf.prefix ? [...halves(l)] : [l]));
|
|
126
|
+
return { ...layout, version: layout.version + 1, shards: shards.sort((a, b) => a.prefix - b.prefix) };
|
|
127
|
+
}
|
|
128
|
+
export function partitionLayout(layout) {
|
|
129
|
+
return { version: layout.version, eras: layout.eras };
|
|
130
|
+
}
|
|
131
|
+
/** The newer of two layouts; a partition's copy may be newer than a shard's, or the reverse. */
|
|
132
|
+
export function newer(a, b) {
|
|
133
|
+
return b !== null && b !== undefined && b.version > a.version ? b : a;
|
|
134
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type StorageEnv } from "./environment.js";
|
|
2
|
+
import type { StoredTx } from "./facts.js";
|
|
3
|
+
/** Bytes of row batches one chunk holds, at most (one row is up to 1.5 MB, and always fits). */
|
|
4
|
+
export declare const MAX_CHUNK_BYTES: number;
|
|
5
|
+
export type { LogRow, LogRows } from "./environment.js";
|
|
6
|
+
export type LogChunk = Readonly<{
|
|
7
|
+
graph: string;
|
|
8
|
+
partition: number;
|
|
9
|
+
first: number;
|
|
10
|
+
last: number;
|
|
11
|
+
txs: readonly StoredTx[];
|
|
12
|
+
}>;
|
|
13
|
+
export declare function logPrefix(graph: string, partition: number): string;
|
|
14
|
+
export declare function logKey(graph: string, partition: number, first: number): string;
|
|
15
|
+
/**
|
|
16
|
+
* Writes rows `first` to `last` as one chunk. `batches` are the rows' stored JSON arrays of
|
|
17
|
+
* transactions, in row order: they are joined as text, never parsed.
|
|
18
|
+
*/
|
|
19
|
+
export declare function writeLogChunk(bucket: R2Bucket, input: Readonly<{
|
|
20
|
+
graph: string;
|
|
21
|
+
partition: number;
|
|
22
|
+
first: number;
|
|
23
|
+
last: number;
|
|
24
|
+
batches: readonly string[];
|
|
25
|
+
}>): Promise<void>;
|
|
26
|
+
export type IndexedLogChunk = Readonly<{
|
|
27
|
+
key: string;
|
|
28
|
+
chunk: LogChunk;
|
|
29
|
+
}>;
|
|
30
|
+
/**
|
|
31
|
+
* Lists and reads archived chunks for one partition whose keys are strictly greater than
|
|
32
|
+
* `afterChunkKey` (empty string reads from the first chunk), bounded to at most `maxChunks`.
|
|
33
|
+
*/
|
|
34
|
+
export declare function readLogChunksAfter(bucket: R2Bucket, graph: string, partition: number, afterChunkKey: string, maxChunks?: number): Promise<Readonly<{
|
|
35
|
+
chunks: readonly IndexedLogChunk[];
|
|
36
|
+
more: boolean;
|
|
37
|
+
}>>;
|
|
38
|
+
/** One partition's whole log: its chunks, then the rows it still holds, checked to meet without gaps or overlaps. */
|
|
39
|
+
export declare function readPartitionLog(env: StorageEnv, graph: string, partition: number): Promise<StoredTx[]>;
|
|
40
|
+
/** The graph's whole log, in key order: what the index is a projection of. */
|
|
41
|
+
export declare function readLog(env: StorageEnv, graph: string): Promise<StoredTx[]>;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// The graph's log: every transaction a partition acknowledged, in the partition's order. Facts
|
|
2
|
+
// are the durable truth; the index is a projection of this log and could be rebuilt from it.
|
|
3
|
+
//
|
|
4
|
+
// A partition keeps its newest transactions in SQLite rows. Before it deletes rows that the index
|
|
5
|
+
// holds and the token window has passed, it writes them to R2 as one immutable chunk, keyed by the
|
|
6
|
+
// first row's number. A partition's chunks never overlap: the next one starts after the last row
|
|
7
|
+
// the previous one held, which the partition stores only once the PUT has succeeded, and a retry
|
|
8
|
+
// after a crash writes the same key again with at least the same rows. So a partition's chunks,
|
|
9
|
+
// then the rows it still holds, are its whole log, each transaction once.
|
|
10
|
+
import { partitionStub, rootStub } from "./environment.js";
|
|
11
|
+
import { partitionCount } from "./layout.js";
|
|
12
|
+
import { compareKeys } from "./keys.js";
|
|
13
|
+
/** Bytes of row batches one chunk holds, at most (one row is up to 1.5 MB, and always fits). */
|
|
14
|
+
export const MAX_CHUNK_BYTES = 8 * 2 ** 20;
|
|
15
|
+
/** Rows a reader asks a partition for at once. */
|
|
16
|
+
const ROWS_PER_PAGE = 64;
|
|
17
|
+
export function logPrefix(graph, partition) {
|
|
18
|
+
return `graphs/${graph}/log/${partition}/`;
|
|
19
|
+
}
|
|
20
|
+
export function logKey(graph, partition, first) {
|
|
21
|
+
return `${logPrefix(graph, partition)}${String(first).padStart(12, "0")}.json`;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Writes rows `first` to `last` as one chunk. `batches` are the rows' stored JSON arrays of
|
|
25
|
+
* transactions, in row order: they are joined as text, never parsed.
|
|
26
|
+
*/
|
|
27
|
+
export async function writeLogChunk(bucket, input) {
|
|
28
|
+
const txs = input.batches.map((batch) => batch.slice(1, -1)).filter((inner) => inner.length > 0).join(",");
|
|
29
|
+
const body = `{"graph":${JSON.stringify(input.graph)},"partition":${input.partition},"first":${input.first},"last":${input.last},"txs":[${txs}]}`;
|
|
30
|
+
await bucket.put(logKey(input.graph, input.partition, input.first), body, { httpMetadata: { contentType: "application/json" } });
|
|
31
|
+
}
|
|
32
|
+
function isLogChunk(input) {
|
|
33
|
+
if (typeof input !== "object" || input === null)
|
|
34
|
+
return false;
|
|
35
|
+
const g = "graph" in input ? input.graph : undefined;
|
|
36
|
+
const p = "partition" in input ? input.partition : undefined;
|
|
37
|
+
const f = "first" in input ? input.first : undefined;
|
|
38
|
+
const l = "last" in input ? input.last : undefined;
|
|
39
|
+
const t = "txs" in input ? input.txs : undefined;
|
|
40
|
+
return typeof g === "string"
|
|
41
|
+
&& typeof p === "number" && Number.isSafeInteger(p)
|
|
42
|
+
&& typeof f === "number" && Number.isSafeInteger(f) && f >= 1
|
|
43
|
+
&& typeof l === "number" && Number.isSafeInteger(l) && l >= f
|
|
44
|
+
&& Array.isArray(t);
|
|
45
|
+
}
|
|
46
|
+
function parseLogChunk(input, key) {
|
|
47
|
+
if (!isLogChunk(input))
|
|
48
|
+
throw new Error(`log chunk ${key} has invalid fields`);
|
|
49
|
+
return input;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Lists and reads archived chunks for one partition whose keys are strictly greater than
|
|
53
|
+
* `afterChunkKey` (empty string reads from the first chunk), bounded to at most `maxChunks`.
|
|
54
|
+
*/
|
|
55
|
+
export async function readLogChunksAfter(bucket, graph, partition, afterChunkKey, maxChunks = 8) {
|
|
56
|
+
const chunks = [];
|
|
57
|
+
let cursor;
|
|
58
|
+
let more = false;
|
|
59
|
+
do {
|
|
60
|
+
const listing = await bucket.list({
|
|
61
|
+
prefix: logPrefix(graph, partition),
|
|
62
|
+
...(afterChunkKey === "" ? {} : { startAfter: afterChunkKey }),
|
|
63
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
64
|
+
});
|
|
65
|
+
for (const object of listing.objects) {
|
|
66
|
+
if (chunks.length >= maxChunks) {
|
|
67
|
+
more = true;
|
|
68
|
+
return { chunks, more };
|
|
69
|
+
}
|
|
70
|
+
const body = await bucket.get(object.key);
|
|
71
|
+
if (body === null)
|
|
72
|
+
throw new Error(`log chunk ${object.key} is missing`);
|
|
73
|
+
chunks.push({ key: object.key, chunk: parseLogChunk(await body.json(), object.key) });
|
|
74
|
+
}
|
|
75
|
+
cursor = listing.truncated ? listing.cursor : undefined;
|
|
76
|
+
} while (cursor !== undefined);
|
|
77
|
+
return { chunks, more };
|
|
78
|
+
}
|
|
79
|
+
/** A partition's chunks, oldest first. Keys hold zero-padded row numbers, so R2's order is theirs. */
|
|
80
|
+
async function* chunksOf(bucket, graph, partition, after) {
|
|
81
|
+
let cursor;
|
|
82
|
+
do {
|
|
83
|
+
const listing = await bucket.list({ prefix: logPrefix(graph, partition), startAfter: logKey(graph, partition, after), ...(cursor === undefined ? {} : { cursor }) });
|
|
84
|
+
for (const object of listing.objects) {
|
|
85
|
+
const body = await bucket.get(object.key);
|
|
86
|
+
if (body === null)
|
|
87
|
+
throw new Error(`log chunk ${object.key} is missing`);
|
|
88
|
+
yield parseLogChunk(await body.json(), object.key);
|
|
89
|
+
}
|
|
90
|
+
cursor = listing.truncated ? listing.cursor : undefined;
|
|
91
|
+
} while (cursor !== undefined);
|
|
92
|
+
}
|
|
93
|
+
/** One partition's whole log: its chunks, then the rows it still holds, checked to meet without gaps or overlaps. */
|
|
94
|
+
export async function readPartitionLog(env, graph, partition) {
|
|
95
|
+
const txs = [];
|
|
96
|
+
let last = 0;
|
|
97
|
+
const stub = partitionStub(env, graph, partition);
|
|
98
|
+
for (;;) {
|
|
99
|
+
// Chunks first: the partition may archive and delete rows while this reads, and then the rows
|
|
100
|
+
// past `last` are in chunks this listing has not seen yet.
|
|
101
|
+
for await (const chunk of chunksOf(env.INDEX, graph, partition, last)) {
|
|
102
|
+
if (chunk.first !== last + 1)
|
|
103
|
+
throw new Error(`log of ${graph} partition ${partition} has a gap or overlap at row ${last + 1}`);
|
|
104
|
+
txs.push(...chunk.txs);
|
|
105
|
+
last = chunk.last;
|
|
106
|
+
}
|
|
107
|
+
let after = last, caughtUp = true;
|
|
108
|
+
for (;;) {
|
|
109
|
+
const page = await stub.logRows({ after, limit: ROWS_PER_PAGE });
|
|
110
|
+
const next = page.rows[0]?.seq;
|
|
111
|
+
if (next === undefined ? page.archived > after : next !== after + 1) {
|
|
112
|
+
if (page.archived <= after)
|
|
113
|
+
throw new Error(`log of ${graph} partition ${partition} has a gap after row ${after}`);
|
|
114
|
+
caughtUp = false; // rows this read needs were archived and deleted meanwhile: read the new chunks
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
for (const row of page.rows) {
|
|
118
|
+
if (row.seq !== after + 1)
|
|
119
|
+
throw new Error(`log of ${graph} partition ${partition} has a gap after row ${after}`);
|
|
120
|
+
txs.push(...row.txs);
|
|
121
|
+
after = row.seq;
|
|
122
|
+
}
|
|
123
|
+
if (page.rows.length < ROWS_PER_PAGE)
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
if (caughtUp)
|
|
127
|
+
return txs;
|
|
128
|
+
txs.length = 0;
|
|
129
|
+
last = 0;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** The graph's whole log, in key order: what the index is a projection of. */
|
|
133
|
+
export async function readLog(env, graph) {
|
|
134
|
+
const partitions = partitionCount(await rootStub(env, graph).layout({ graph }));
|
|
135
|
+
const all = (await Promise.all(Array.from({ length: partitions }, (_, p) => readPartitionLog(env, graph, p)))).flat();
|
|
136
|
+
return all.sort((a, b) => compareKeys(a.key, b.key));
|
|
137
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type StorageEnv } from "./environment.js";
|
|
2
|
+
import type { SegmentRef } from "./segment.js";
|
|
3
|
+
export type Manifest = Readonly<{
|
|
4
|
+
graph: string;
|
|
5
|
+
partitions: number;
|
|
6
|
+
shards: number;
|
|
7
|
+
/** Every write in an epoch at or below this one is in the segments named here. */
|
|
8
|
+
watermark: number;
|
|
9
|
+
/** Segments by field bucket, oldest first. A bucket belongs to one shard. */
|
|
10
|
+
buckets: Readonly<Record<string, readonly SegmentRef[]>>;
|
|
11
|
+
updatedAt: number;
|
|
12
|
+
}>;
|
|
13
|
+
/**
|
|
14
|
+
* The graph's manifest. `fresh` (or `maxStalenessMs === 0`) reads R2 now, past every cache and any
|
|
15
|
+
* read already under way, so it answers with every manifest written before the call. Otherwise:
|
|
16
|
+
* - within `min(MANIFEST_TTL_MS, staleLimit)`: answers immediately from the isolate cache;
|
|
17
|
+
* - within `staleLimit` (`MANIFEST_STALE_MS` by default, or opt-in `maxStalenessMs`): answers
|
|
18
|
+
* immediately from the isolate cache or colo cache while refreshing from R2 in the background
|
|
19
|
+
* via `cache.put()` overwrite;
|
|
20
|
+
* - older than `staleLimit`: waits for a fresh read, coalesced across concurrent callers.
|
|
21
|
+
*/
|
|
22
|
+
export declare function readManifest(env: StorageEnv, graph: string, fresh: boolean, maxStalenessMs?: number): Promise<Manifest | null>;
|
|
23
|
+
/** Tests only: make this isolate hold `manifest` for `graph`, as a reader that read it `ageMs` ago would. */
|
|
24
|
+
export declare function primeManifest(graph: string, manifest: Manifest | null, ageMs?: number): void;
|
|
25
|
+
/** Tests only: drop the isolate-cached manifest for `graph`, as a cold isolate would. */
|
|
26
|
+
export declare function forgetManifest(graph: string): void;
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// The manifest: the one R2 object that says what the index holds (RFD0008, "Watermark").
|
|
2
|
+
// The graph's root writes it at most once a second, after the segments it names. Readers cache it
|
|
3
|
+
// briefly, which is part of how stale a default read is: at most MANIFEST_STALE_MS, from the read
|
|
4
|
+
// that took it from R2, whichever isolate made that read.
|
|
5
|
+
import { MAX_STALENESS_MS } from "../domain/read-token.js";
|
|
6
|
+
import { cacheOrigin, inBackground, manifestKey } from "./environment.js";
|
|
7
|
+
import { isRecord } from "../domain/result.js";
|
|
8
|
+
/** How long an isolate answers with a manifest before it reads the graph's again. */
|
|
9
|
+
const MANIFEST_TTL_MS = 1_000;
|
|
10
|
+
/**
|
|
11
|
+
* How old a manifest may be and still answer a default read while the isolate reads a newer one in
|
|
12
|
+
* the background, as old as a colo cache entry read just before it expired and then held for 500 ms
|
|
13
|
+
* could be: reads wait for a manifest only after a pause in them, never under steady traffic.
|
|
14
|
+
*/
|
|
15
|
+
const MANIFEST_STALE_MS = 1_500;
|
|
16
|
+
/**
|
|
17
|
+
* Colo-wide Cache API TTL for manifest.json. Entries carry their R2 read timestamp in
|
|
18
|
+
* `READ_AT_HEADER`, so callers enforce their exact freshness bound (`MANIFEST_STALE_MS` by default,
|
|
19
|
+
* or opt-in `maxStalenessMs` up to `MAX_STALENESS_MS`) and background refreshes always overwrite
|
|
20
|
+
* via `cache.put()` instead of invalidating.
|
|
21
|
+
*/
|
|
22
|
+
const MANIFEST_COLO_CACHE_SECONDS = Math.floor(MAX_STALENESS_MS / 1_000);
|
|
23
|
+
/** The colo cache entry's header with when the manifest was read from R2, so its age carries over. */
|
|
24
|
+
const READ_AT_HEADER = "x-fatedb-read-at";
|
|
25
|
+
const held = new Map();
|
|
26
|
+
let readsStarted = 0;
|
|
27
|
+
/** The read of each graph's manifest this isolate is waiting for, which every reader that may share it shares. */
|
|
28
|
+
const reading = new Map();
|
|
29
|
+
/** Background R2 refreshes already in flight per graph, deduplicating concurrent SWR refreshes. */
|
|
30
|
+
const refreshing = new Set();
|
|
31
|
+
function coloCache() {
|
|
32
|
+
return typeof caches !== "undefined" && caches.default ? caches.default : null;
|
|
33
|
+
}
|
|
34
|
+
function manifestCacheUrl(env, graph) {
|
|
35
|
+
const origin = cacheOrigin(env);
|
|
36
|
+
return origin === null ? null : `${origin}/_manifests/${encodeURIComponent(graph)}`;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The graph's manifest. `fresh` (or `maxStalenessMs === 0`) reads R2 now, past every cache and any
|
|
40
|
+
* read already under way, so it answers with every manifest written before the call. Otherwise:
|
|
41
|
+
* - within `min(MANIFEST_TTL_MS, staleLimit)`: answers immediately from the isolate cache;
|
|
42
|
+
* - within `staleLimit` (`MANIFEST_STALE_MS` by default, or opt-in `maxStalenessMs`): answers
|
|
43
|
+
* immediately from the isolate cache or colo cache while refreshing from R2 in the background
|
|
44
|
+
* via `cache.put()` overwrite;
|
|
45
|
+
* - older than `staleLimit`: waits for a fresh read, coalesced across concurrent callers.
|
|
46
|
+
*/
|
|
47
|
+
export async function readManifest(env, graph, fresh, maxStalenessMs) {
|
|
48
|
+
const staleLimit = maxStalenessMs === undefined ? MANIFEST_STALE_MS : Math.min(Math.max(0, Math.floor(maxStalenessMs)), MAX_STALENESS_MS);
|
|
49
|
+
if (fresh || staleLimit === 0) {
|
|
50
|
+
// Its own read's, even when a later one answered first: the caller needs what R2 held when it called.
|
|
51
|
+
const read = await readFromR2(env, graph);
|
|
52
|
+
hold(graph, read);
|
|
53
|
+
return read.manifest;
|
|
54
|
+
}
|
|
55
|
+
const freshLimit = Math.min(MANIFEST_TTL_MS, staleLimit);
|
|
56
|
+
const cached = held.get(graph);
|
|
57
|
+
const age = cached === undefined ? Infinity : Date.now() - cached.readAt;
|
|
58
|
+
if (cached !== undefined && age < freshLimit)
|
|
59
|
+
return cached.manifest;
|
|
60
|
+
if (cached !== undefined && age < staleLimit) {
|
|
61
|
+
scheduleRefresh(env, graph);
|
|
62
|
+
return cached.manifest;
|
|
63
|
+
}
|
|
64
|
+
const resolved = await sharedRead(env, graph, staleLimit);
|
|
65
|
+
if (Date.now() - resolved.readAt >= staleLimit) {
|
|
66
|
+
return hold(graph, await readFromR2(env, graph)).manifest;
|
|
67
|
+
}
|
|
68
|
+
return resolved.manifest;
|
|
69
|
+
}
|
|
70
|
+
function sharedRead(env, graph, staleLimit) {
|
|
71
|
+
const underWay = reading.get(graph);
|
|
72
|
+
if (underWay !== undefined)
|
|
73
|
+
return underWay;
|
|
74
|
+
const read = readNewer(env, graph, staleLimit);
|
|
75
|
+
reading.set(graph, read);
|
|
76
|
+
return read;
|
|
77
|
+
}
|
|
78
|
+
function scheduleRefresh(env, graph) {
|
|
79
|
+
if (refreshing.has(graph))
|
|
80
|
+
return;
|
|
81
|
+
refreshing.add(graph);
|
|
82
|
+
inBackground(async () => {
|
|
83
|
+
try {
|
|
84
|
+
const than = held.get(graph)?.readAt ?? -Infinity;
|
|
85
|
+
const colo = await readFromColo(env, graph);
|
|
86
|
+
if (colo !== null && colo.readAt > than && Date.now() - colo.readAt < MANIFEST_TTL_MS) {
|
|
87
|
+
hold(graph, colo);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
hold(graph, await readFromR2(env, graph));
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
refreshing.delete(graph);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* A manifest acceptable for `staleLimit`: a fresh colo entry when another isolate read R2 recently,
|
|
99
|
+
* a stale-within-limit colo entry served immediately with a background R2 refresh (overwrite via
|
|
100
|
+
* `cache.put()`), or a direct R2 read that fills the colo cache.
|
|
101
|
+
*/
|
|
102
|
+
async function readNewer(env, graph, staleLimit) {
|
|
103
|
+
try {
|
|
104
|
+
const than = held.get(graph)?.readAt ?? -Infinity;
|
|
105
|
+
const colo = await readFromColo(env, graph);
|
|
106
|
+
if (colo !== null) {
|
|
107
|
+
const coloAge = Date.now() - colo.readAt;
|
|
108
|
+
const freshLimit = Math.min(MANIFEST_TTL_MS, staleLimit);
|
|
109
|
+
if (coloAge < freshLimit && colo.readAt > than)
|
|
110
|
+
return hold(graph, colo);
|
|
111
|
+
if (coloAge < staleLimit && colo.readAt >= than) {
|
|
112
|
+
const stored = hold(graph, colo);
|
|
113
|
+
if (coloAge >= freshLimit)
|
|
114
|
+
scheduleRefresh(env, graph);
|
|
115
|
+
return stored;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return hold(graph, await readFromR2(env, graph));
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
reading.delete(graph);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
async function readFromColo(env, graph) {
|
|
125
|
+
const cache = coloCache();
|
|
126
|
+
const url = manifestCacheUrl(env, graph);
|
|
127
|
+
if (cache === null || url === null)
|
|
128
|
+
return null;
|
|
129
|
+
try {
|
|
130
|
+
const hit = await cache.match(url);
|
|
131
|
+
if (hit === undefined)
|
|
132
|
+
return null;
|
|
133
|
+
// An entry without its read time is from before entries had one: at most MANIFEST_COLO_CACHE_SECONDS old.
|
|
134
|
+
const readAt = Number(hit.headers.get(READ_AT_HEADER) ?? Date.now() - MANIFEST_COLO_CACHE_SECONDS * 1_000);
|
|
135
|
+
return {
|
|
136
|
+
manifest: parseManifest(await hit.json()),
|
|
137
|
+
readAt: Number.isSafeInteger(readAt) ? Math.min(readAt, Date.now()) : Date.now() - MANIFEST_COLO_CACHE_SECONDS * 1_000,
|
|
138
|
+
order: 0,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
// The Cache API is best effort: R2 answers instead.
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** What R2 holds now; the colo cache gets it after the answer. */
|
|
147
|
+
async function readFromR2(env, graph) {
|
|
148
|
+
const readAt = Date.now();
|
|
149
|
+
const order = ++readsStarted;
|
|
150
|
+
const object = await env.INDEX.get(manifestKey(graph));
|
|
151
|
+
const manifest = object === null ? null : parseManifest(await object.json());
|
|
152
|
+
const cache = coloCache();
|
|
153
|
+
const url = manifestCacheUrl(env, graph);
|
|
154
|
+
if (manifest !== null && cache !== null && url !== null) {
|
|
155
|
+
inBackground(() => cache.put(url, new Response(JSON.stringify(manifest), {
|
|
156
|
+
headers: {
|
|
157
|
+
"content-type": "application/json",
|
|
158
|
+
"cache-control": `public, max-age=${MANIFEST_COLO_CACHE_SECONDS}`,
|
|
159
|
+
[READ_AT_HEADER]: String(readAt),
|
|
160
|
+
},
|
|
161
|
+
})));
|
|
162
|
+
}
|
|
163
|
+
return { manifest, readAt, order };
|
|
164
|
+
}
|
|
165
|
+
/** Holds `entry` unless the isolate holds one from a later read, and answers with what it holds. */
|
|
166
|
+
function hold(graph, entry) {
|
|
167
|
+
const current = held.get(graph);
|
|
168
|
+
if (current !== undefined && (current.readAt > entry.readAt || (current.readAt === entry.readAt && current.order > entry.order)))
|
|
169
|
+
return current;
|
|
170
|
+
held.set(graph, entry);
|
|
171
|
+
return entry;
|
|
172
|
+
}
|
|
173
|
+
function parseManifest(input) {
|
|
174
|
+
if (!isRecord(input))
|
|
175
|
+
throw new Error("manifest is not an object");
|
|
176
|
+
const { graph, partitions, shards, watermark, buckets, updatedAt } = input;
|
|
177
|
+
if (typeof graph !== "string" || !isCount(partitions) || !isCount(shards) || !isCount(watermark) || !isCount(updatedAt) || !isRecord(buckets)) {
|
|
178
|
+
throw new Error("manifest has invalid fields");
|
|
179
|
+
}
|
|
180
|
+
const parsed = {};
|
|
181
|
+
for (const [bucket, refs] of Object.entries(buckets)) {
|
|
182
|
+
if (!Array.isArray(refs))
|
|
183
|
+
throw new Error(`manifest bucket ${bucket} is not a list`);
|
|
184
|
+
parsed[bucket] = refs.map((ref) => {
|
|
185
|
+
if (!isRecord(ref))
|
|
186
|
+
throw new Error(`manifest bucket ${bucket} holds a segment that is not an object`);
|
|
187
|
+
const { name, facts, bytes, headerBytes, minEpoch, maxEpoch } = ref;
|
|
188
|
+
if (typeof name !== "string" || !isCount(facts) || !isCount(bytes) || !isCount(headerBytes) || !isCount(minEpoch) || !isCount(maxEpoch)) {
|
|
189
|
+
throw new Error(`manifest bucket ${bucket} holds an invalid segment`);
|
|
190
|
+
}
|
|
191
|
+
return { name, facts, bytes, headerBytes, minEpoch, maxEpoch };
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
return { graph, partitions, shards, watermark, buckets: parsed, updatedAt };
|
|
195
|
+
}
|
|
196
|
+
function isCount(n) {
|
|
197
|
+
return typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
|
|
198
|
+
}
|
|
199
|
+
/** Tests only: make this isolate hold `manifest` for `graph`, as a reader that read it `ageMs` ago would. */
|
|
200
|
+
export function primeManifest(graph, manifest, ageMs = 0) {
|
|
201
|
+
held.set(graph, { manifest, readAt: Date.now() - ageMs, order: ++readsStarted });
|
|
202
|
+
}
|
|
203
|
+
/** Tests only: drop the isolate-cached manifest for `graph`, as a cold isolate would. */
|
|
204
|
+
export function forgetManifest(graph) {
|
|
205
|
+
held.delete(graph);
|
|
206
|
+
}
|