@peer2peer/relay 0.0.0-stage → 0.1.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.
@@ -0,0 +1,184 @@
1
+ import { Worker } from "node:worker_threads";
2
+ import { type EvictPolicy, type CapState, type IdentityIndex, type MailboxCaps, type NewEnvelope, type Store, type StoreCounts, type StoredEnvelope, type StoredInvite, type StoredIdentityDoc, type SweepCutoffs, type SweepResult } from "./store.js";
3
+ export interface SqliteStoreOptions {
4
+ /** Called with the SQL of every statement run (tests use it to prove hot paths are aggregate-free). */
5
+ trace?: (sql: string) => void;
6
+ /**
7
+ * Run WAL checkpoints on a worker thread (default for file databases). When
8
+ * false, SQLite's automatic checkpoint runs inside commits on the main thread.
9
+ */
10
+ backgroundCheckpoint?: boolean;
11
+ /** How often the worker checkpoints (default 100 ms). */
12
+ checkpointIntervalMs?: number;
13
+ /** No completed checkpoint for this long means the worker is stalled (default 30 s). */
14
+ checkpointWatchdogMs?: number;
15
+ /** A WAL larger than this means checkpoints aren't keeping up (default 256 MiB). */
16
+ walLimitBytes?: number;
17
+ /** After a checkpoint, SQLite truncates the WAL file back to this size (default 64 MiB). */
18
+ journalSizeLimitBytes?: number;
19
+ /**
20
+ * The watchdog's clock (default Date.now). Tests pass a virtual one, so the
21
+ * stall rule is judged by the time they advance, not by how fast a loaded
22
+ * machine schedules the worker thread.
23
+ */
24
+ now?: () => number;
25
+ /** Receives warnings (the relay passes its logger). */
26
+ warn?: (msg: string, fields?: Record<string, string | number | boolean>) => void;
27
+ }
28
+ /**
29
+ * A running backup (deploy/relay/backup.mjs) writes `<db>-backup`, JSON with
30
+ * `until` (ms since the epoch: its own deadline), and removes it when done.
31
+ * Its read snapshot holds checkpoints back by design, so while it runs the
32
+ * watchdog doesn't count that as a stall: re-enabling in-commit checkpoints
33
+ * then only made the first commit after the backup copy the whole grown WAL
34
+ * on the main thread (1-3.6 s on a 3 GiB database). A marker is honoured at
35
+ * most BACKUP_MARKER_MAX_MS after its file was written, whatever it claims,
36
+ * so a backup killed before cleaning up can't switch the watchdog off.
37
+ */
38
+ export declare const BACKUP_MARKER_MAX_MS: number;
39
+ export declare class SqliteStore implements Store {
40
+ private readonly db;
41
+ private readonly q;
42
+ private closed;
43
+ private txDepth;
44
+ private checkpointer?;
45
+ /** Shared with the checkpoint worker: [0] becomes 1 once its connection is closed. */
46
+ private checkpointerFlags?;
47
+ private readonly path;
48
+ private readonly opts;
49
+ private watchdog?;
50
+ /** When the worker last reported a completed checkpoint (wall-clock ms). */
51
+ private lastCheckpointAt;
52
+ /** True while SQLite's in-commit autocheckpoint is back on (no healthy worker). */
53
+ private autocheckpointOn;
54
+ /** Bytes across every invite: the sum of `invite_iss`, kept by issAdd (a counter read, not a scan of the blobs). */
55
+ private inviteTotal;
56
+ /** issAdd deltas of the open transaction, applied to inviteTotal on commit. */
57
+ private inviteDelta;
58
+ constructor(path: string, opts?: SqliteStoreOptions);
59
+ /**
60
+ * Startup (N-M1): rebuilds `totals`, `allowed_devices` and the devices'
61
+ * `evictable` flags, reading in chunks and yielding between them, so no
62
+ * single step blocks for long. Old rows keep their (now anonymous) source
63
+ * tags (R-M1). The relay calls this before it accepts connections.
64
+ */
65
+ init(): Promise<void>;
66
+ /** Re-entrant: an inner call joins the outer transaction. */
67
+ private tx;
68
+ transaction<T>(fn: () => T): T;
69
+ getMeta(key: string): string | undefined;
70
+ setMeta(key: string, value: string): void;
71
+ deviceIssuer(did: string): string | undefined;
72
+ touchDevice(did: string, iss: string, now: number): boolean;
73
+ evictableDevices(limit: number, after?: {
74
+ lastSeen: number;
75
+ did: string;
76
+ }): {
77
+ did: string;
78
+ iss: string;
79
+ lastSeen: number;
80
+ }[];
81
+ deleteDevice(did: string): void;
82
+ private bumpTotals;
83
+ private total;
84
+ private deleteEnv;
85
+ /** The oldest envelopes of source `src` in mailbox (to, tdid). */
86
+ private srcMailboxOldest;
87
+ /** Frees bytes from source `src`'s largest mailbox; 0 when the source holds nothing. */
88
+ private evictFromSource;
89
+ /** Largest key of `kind` starting with `prefix + "\n"`, by bytes. */
90
+ private largestUnder;
91
+ putEnvelope(e: NewEnvelope, caps: MailboxCaps): {
92
+ rid: number;
93
+ dropped: number;
94
+ droppedBytes: number;
95
+ };
96
+ envelopesAfter(to: string, tdid: string, afterRid: number, notBefore: number, limit: number): StoredEnvelope[];
97
+ ackEnvelopes(to: string, tdid: string, rids: readonly number[]): {
98
+ count: number;
99
+ bytes: number;
100
+ };
101
+ bytesForRecipient(to: string): number;
102
+ mailboxBytes(to: string, tdid: string): number;
103
+ evictRecipient(to: string, bytes: number, policy?: EvictPolicy): number;
104
+ /**
105
+ * The source group to evict from, per EvictPolicy, from counters only: the
106
+ * largest groups by the bytes index, plus the sender's own total.
107
+ */
108
+ private pickGlobalSource;
109
+ evictGlobal(bytes: number, policy?: EvictPolicy): number;
110
+ sourceBytes(src: string): number;
111
+ evictSource(src: string, bytes: number): number;
112
+ expireBatch(before: number, limit: number): {
113
+ count: number;
114
+ bytes: number;
115
+ };
116
+ capState(key: string): CapState;
117
+ revokeCap(key: string, now: number): void;
118
+ useCap(key: string, now: number): void;
119
+ identityDoc(hash: string): StoredIdentityDoc | undefined;
120
+ identityDocs(iss: string): StoredIdentityDoc[];
121
+ putIdentityDoc(d: StoredIdentityDoc): boolean;
122
+ deleteIdentityDocs(hashes: readonly string[]): void;
123
+ identityIndex(iss: string): IdentityIndex | undefined;
124
+ putIdentityIndex(i: IdentityIndex): void;
125
+ private putIndexRow;
126
+ deleteIdentityDocsOf(iss: string): void;
127
+ deleteIdentity(iss: string): void;
128
+ /**
129
+ * Sweeps at most `limit` old non-tip versions (F-4: bounded steps); their
130
+ * dids outside the allowlist are remembered first (R4-M1).
131
+ */
132
+ private sweepIdentityDocs;
133
+ seenDevices(iss: string, sinceMs: number): string[];
134
+ addSeen(iss: string, dids: readonly string[], at: number): void;
135
+ expiredIdentities(headExpBeforeSec: number, limit: number): string[];
136
+ staleTombstones(leftBefore: number, limit: number): string[];
137
+ private issAdd;
138
+ putInvite(i: StoredInvite): boolean;
139
+ takeInvite(lid: string, now: number): StoredInvite | undefined;
140
+ deleteInvite(lid: string, iss: string): boolean;
141
+ invitesOf(iss: string, now: number): string[];
142
+ evictedInvitesOf(iss: string, now: number): string[];
143
+ inviteBytes(): number;
144
+ inviteBytesOfIss(iss: string): number;
145
+ sweepInvites(now: number, limit: number): {
146
+ invites: number;
147
+ evicted: number;
148
+ };
149
+ inviteBytesOfSrc(src: string): number;
150
+ evictInvites(bytes: number, now?: number): number;
151
+ envelopeTotals(): {
152
+ envelopes: number;
153
+ bytes: number;
154
+ };
155
+ sweep(c: SweepCutoffs, limit: number): SweepResult;
156
+ counts(): StoreCounts;
157
+ ping(): boolean;
158
+ private setAutocheckpoint;
159
+ /**
160
+ * Starts the checkpoint worker. SQLite's in-commit autocheckpoint stays on
161
+ * until the worker reports its first completed checkpoint, and comes back
162
+ * whenever the worker dies or stalls, so the WAL is never left unchecked.
163
+ */
164
+ private startCheckpointer;
165
+ private walBytes;
166
+ /**
167
+ * pre-release review: if no checkpoint completed within the watchdog window, or the
168
+ * WAL grew past its limit, turn SQLite's autocheckpoint back on, warn, and
169
+ * restart the worker (it switches autocheckpoint off again once healthy).
170
+ */
171
+ private lastWarnAt;
172
+ private now;
173
+ private warnOnce;
174
+ /** A backup's marker that is still in force (see BACKUP_MARKER_MAX_MS), or undefined. */
175
+ private backupRunning;
176
+ /** One watchdog check, as its timer runs it (tests call it after advancing their clock). */
177
+ checkWatchdog(): void;
178
+ /** For tests: the worker's identity and whether autocheckpoint is on. */
179
+ checkpointState(): {
180
+ worker: Worker | undefined;
181
+ autocheckpoint: boolean;
182
+ };
183
+ close(): void;
184
+ }