@peer2peer/relay 0.0.0-stage → 0.1.1
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 +201 -0
- package/README.md +19 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +88 -0
- package/dist/client.d.ts +3 -0
- package/dist/client.js +23 -0
- package/dist/config.d.ts +266 -0
- package/dist/config.js +326 -0
- package/dist/crypto.d.ts +159 -0
- package/dist/crypto.js +514 -0
- package/dist/identity.d.ts +84 -0
- package/dist/identity.js +386 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +14 -0
- package/dist/links.d.ts +29 -0
- package/dist/links.js +98 -0
- package/dist/log.d.ts +19 -0
- package/dist/log.js +35 -0
- package/dist/members.d.ts +109 -0
- package/dist/members.js +369 -0
- package/dist/metrics.d.ts +13 -0
- package/dist/metrics.js +66 -0
- package/dist/net.d.ts +23 -0
- package/dist/net.js +103 -0
- package/dist/ratelimit.d.ts +16 -0
- package/dist/ratelimit.js +70 -0
- package/dist/server.d.ts +271 -0
- package/dist/server.js +1951 -0
- package/dist/sqlite-store.d.ts +184 -0
- package/dist/sqlite-store.js +1068 -0
- package/dist/store.d.ts +368 -0
- package/dist/store.js +492 -0
- package/package.json +57 -4
|
@@ -0,0 +1,1068 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// The production Store, on node:sqlite (built into Node >= 22.13; no native
|
|
4
|
+
// dependency). WAL mode, and secure_delete so acked or expired envelopes are
|
|
5
|
+
// overwritten on disk rather than left in free pages.
|
|
6
|
+
//
|
|
7
|
+
// Nothing ever aggregates over `envelopes` while the relay serves (H-1,
|
|
8
|
+
// N-M1). Byte and count totals per mailbox, recipient, source, (recipient,
|
|
9
|
+
// source) and (source, mailbox), plus the grand total, live in the small
|
|
10
|
+
// `totals` table, updated in the same transaction as every insert and delete
|
|
11
|
+
// (including expiry, which deletes in small batches). They are rebuilt only in
|
|
12
|
+
// `init`, at startup, in chunks that yield. In `envelopes`, the 64 KiB `env`
|
|
13
|
+
// column is last, so reading routing columns and `size` never touches overflow
|
|
14
|
+
// pages, and every hot query is an index SEARCH.
|
|
15
|
+
//
|
|
16
|
+
// Source tags (N-M3, R-M1): the tag key lives only in the relay's memory. A
|
|
17
|
+
// row stored by an earlier process keeps its tag; with that process's key
|
|
18
|
+
// gone, the tag is an anonymous group that can't be linked to any network,
|
|
19
|
+
// but it still groups one sender's rows, so source-first eviction stays fair
|
|
20
|
+
// across restarts (a flooder's old rows remain the largest source).
|
|
21
|
+
//
|
|
22
|
+
// Device eviction (R-L2): `devices.evictable` is 1 when the binding has no
|
|
23
|
+
// stored envelopes and is in no held allowlist. It is kept current wherever a
|
|
24
|
+
// mailbox gains its first or loses its last envelope and wherever an allowlist
|
|
25
|
+
// changes, so the cap path reads the oldest evictable rows straight from a
|
|
26
|
+
// partial index with a keyset cursor.
|
|
27
|
+
import { DatabaseSync } from "node:sqlite";
|
|
28
|
+
import { readFileSync, statSync } from "node:fs";
|
|
29
|
+
import { Worker } from "node:worker_threads";
|
|
30
|
+
import { MAX_SEEN_PER_ISS, pickSource, totalKeys, } from "./store.js";
|
|
31
|
+
const SCHEMA_VERSION = 1;
|
|
32
|
+
const SCHEMA = `
|
|
33
|
+
CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT NOT NULL);
|
|
34
|
+
CREATE TABLE IF NOT EXISTS devices (
|
|
35
|
+
did TEXT PRIMARY KEY,
|
|
36
|
+
iss TEXT NOT NULL,
|
|
37
|
+
last_seen INTEGER NOT NULL,
|
|
38
|
+
evictable INTEGER NOT NULL DEFAULT 1
|
|
39
|
+
);
|
|
40
|
+
CREATE INDEX IF NOT EXISTS devices_seen ON devices (last_seen);
|
|
41
|
+
CREATE INDEX IF NOT EXISTS devices_evictable ON devices (last_seen, did) WHERE evictable = 1;
|
|
42
|
+
CREATE TABLE IF NOT EXISTS envelopes (
|
|
43
|
+
rid INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
44
|
+
mbox_to TEXT NOT NULL,
|
|
45
|
+
mbox_did TEXT NOT NULL,
|
|
46
|
+
src TEXT NOT NULL,
|
|
47
|
+
size INTEGER NOT NULL,
|
|
48
|
+
received_at INTEGER NOT NULL,
|
|
49
|
+
env TEXT NOT NULL
|
|
50
|
+
);
|
|
51
|
+
CREATE INDEX IF NOT EXISTS envelopes_mbox ON envelopes (mbox_to, mbox_did, rid);
|
|
52
|
+
CREATE INDEX IF NOT EXISTS envelopes_time ON envelopes (received_at);
|
|
53
|
+
CREATE INDEX IF NOT EXISTS envelopes_src_mbox ON envelopes (src, mbox_to, mbox_did, rid);
|
|
54
|
+
CREATE INDEX IF NOT EXISTS envelopes_to_src ON envelopes (mbox_to, src, rid);
|
|
55
|
+
CREATE TABLE IF NOT EXISTS totals (
|
|
56
|
+
kind TEXT NOT NULL,
|
|
57
|
+
key TEXT NOT NULL,
|
|
58
|
+
bytes INTEGER NOT NULL,
|
|
59
|
+
n INTEGER NOT NULL,
|
|
60
|
+
PRIMARY KEY (kind, key)
|
|
61
|
+
);
|
|
62
|
+
CREATE INDEX IF NOT EXISTS totals_bytes ON totals (kind, bytes);
|
|
63
|
+
CREATE TABLE IF NOT EXISTS caps (
|
|
64
|
+
key TEXT PRIMARY KEY,
|
|
65
|
+
revoked INTEGER NOT NULL DEFAULT 0,
|
|
66
|
+
uses INTEGER NOT NULL DEFAULT 0,
|
|
67
|
+
updated_at INTEGER NOT NULL
|
|
68
|
+
);
|
|
69
|
+
CREATE INDEX IF NOT EXISTS caps_time ON caps (updated_at);
|
|
70
|
+
CREATE TABLE IF NOT EXISTS identity_docs (
|
|
71
|
+
hash TEXT PRIMARY KEY,
|
|
72
|
+
iss TEXT NOT NULL,
|
|
73
|
+
ver INTEGER NOT NULL,
|
|
74
|
+
prev TEXT,
|
|
75
|
+
merge TEXT,
|
|
76
|
+
devices TEXT NOT NULL,
|
|
77
|
+
iat INTEGER NOT NULL,
|
|
78
|
+
exp INTEGER NOT NULL,
|
|
79
|
+
received_at INTEGER NOT NULL,
|
|
80
|
+
jws TEXT NOT NULL
|
|
81
|
+
);
|
|
82
|
+
CREATE INDEX IF NOT EXISTS identity_iss ON identity_docs (iss, ver);
|
|
83
|
+
CREATE INDEX IF NOT EXISTS identity_prev ON identity_docs (prev);
|
|
84
|
+
CREATE INDEX IF NOT EXISTS identity_merge ON identity_docs (merge);
|
|
85
|
+
CREATE INDEX IF NOT EXISTS identity_received ON identity_docs (received_at);
|
|
86
|
+
CREATE TABLE IF NOT EXISTS identity_index (
|
|
87
|
+
iss TEXT PRIMARY KEY,
|
|
88
|
+
head TEXT NOT NULL,
|
|
89
|
+
head_ver INTEGER NOT NULL,
|
|
90
|
+
head_exp INTEGER NOT NULL,
|
|
91
|
+
tips TEXT NOT NULL,
|
|
92
|
+
allowed TEXT NOT NULL,
|
|
93
|
+
cap TEXT,
|
|
94
|
+
left_at INTEGER
|
|
95
|
+
);
|
|
96
|
+
CREATE INDEX IF NOT EXISTS identity_index_exp ON identity_index (head_exp);
|
|
97
|
+
CREATE INDEX IF NOT EXISTS identity_index_left ON identity_index (left_at);
|
|
98
|
+
CREATE TABLE IF NOT EXISTS allowed_devices (
|
|
99
|
+
did TEXT NOT NULL,
|
|
100
|
+
iss TEXT NOT NULL,
|
|
101
|
+
PRIMARY KEY (did, iss)
|
|
102
|
+
);
|
|
103
|
+
CREATE INDEX IF NOT EXISTS allowed_devices_iss ON allowed_devices (iss);
|
|
104
|
+
CREATE TABLE IF NOT EXISTS identity_seen (
|
|
105
|
+
iss TEXT NOT NULL,
|
|
106
|
+
did TEXT NOT NULL,
|
|
107
|
+
at INTEGER NOT NULL,
|
|
108
|
+
PRIMARY KEY (iss, did)
|
|
109
|
+
);
|
|
110
|
+
CREATE INDEX IF NOT EXISTS identity_seen_at ON identity_seen (at);
|
|
111
|
+
CREATE TABLE IF NOT EXISTS invites (
|
|
112
|
+
lid TEXT PRIMARY KEY,
|
|
113
|
+
iss TEXT NOT NULL,
|
|
114
|
+
blob TEXT NOT NULL,
|
|
115
|
+
size INTEGER NOT NULL,
|
|
116
|
+
created_at INTEGER NOT NULL,
|
|
117
|
+
expires_at INTEGER NOT NULL,
|
|
118
|
+
src TEXT NOT NULL
|
|
119
|
+
);
|
|
120
|
+
CREATE INDEX IF NOT EXISTS invites_iss ON invites (iss, created_at);
|
|
121
|
+
CREATE INDEX IF NOT EXISTS invites_src ON invites (src);
|
|
122
|
+
-- Covers inviteBytesOfSrc (sum(size) per src) without reading the blobs' overflow pages.
|
|
123
|
+
CREATE INDEX IF NOT EXISTS invites_src_size ON invites (src, size);
|
|
124
|
+
CREATE TABLE IF NOT EXISTS invite_iss (iss TEXT PRIMARY KEY, bytes INTEGER NOT NULL);
|
|
125
|
+
CREATE INDEX IF NOT EXISTS invite_iss_bytes ON invite_iss (bytes);
|
|
126
|
+
CREATE TABLE IF NOT EXISTS invite_evicted (lid TEXT PRIMARY KEY, iss TEXT NOT NULL, expires_at INTEGER NOT NULL);
|
|
127
|
+
CREATE INDEX IF NOT EXISTS invite_evicted_iss ON invite_evicted (iss);
|
|
128
|
+
CREATE INDEX IF NOT EXISTS invites_exp ON invites (expires_at);
|
|
129
|
+
CREATE INDEX IF NOT EXISTS invite_evicted_exp ON invite_evicted (expires_at);
|
|
130
|
+
DROP TABLE IF EXISTS identity_revoked;
|
|
131
|
+
DROP TABLE IF EXISTS retired_devices;
|
|
132
|
+
`;
|
|
133
|
+
function docFromRow(r) {
|
|
134
|
+
return {
|
|
135
|
+
hash: r.hash,
|
|
136
|
+
iss: r.iss,
|
|
137
|
+
ver: Number(r.ver),
|
|
138
|
+
prev: r.prev,
|
|
139
|
+
merge: r.merge,
|
|
140
|
+
jws: r.jws,
|
|
141
|
+
devices: JSON.parse(r.devices),
|
|
142
|
+
iat: Number(r.iat),
|
|
143
|
+
exp: Number(r.exp),
|
|
144
|
+
receivedAt: Number(r.received_at),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
const CHECKPOINT_INTERVAL_MS = 100;
|
|
148
|
+
const CHECKPOINT_WATCHDOG_MS = 30_000;
|
|
149
|
+
/**
|
|
150
|
+
* A running backup (deploy/relay/backup.mjs) writes `<db>-backup`, JSON with
|
|
151
|
+
* `until` (ms since the epoch: its own deadline), and removes it when done.
|
|
152
|
+
* Its read snapshot holds checkpoints back by design, so while it runs the
|
|
153
|
+
* watchdog doesn't count that as a stall: re-enabling in-commit checkpoints
|
|
154
|
+
* then only made the first commit after the backup copy the whole grown WAL
|
|
155
|
+
* on the main thread (1-3.6 s on a 3 GiB database). A marker is honoured at
|
|
156
|
+
* most BACKUP_MARKER_MAX_MS after its file was written, whatever it claims,
|
|
157
|
+
* so a backup killed before cleaning up can't switch the watchdog off.
|
|
158
|
+
*/
|
|
159
|
+
export const BACKUP_MARKER_MAX_MS = 60 * 60 * 1000;
|
|
160
|
+
const WAL_LIMIT_BYTES = 256 * 1024 * 1024;
|
|
161
|
+
/** After a checkpoint, SQLite truncates the WAL file back to this size. */
|
|
162
|
+
const JOURNAL_SIZE_LIMIT = 64 * 1024 * 1024;
|
|
163
|
+
/**
|
|
164
|
+
* F-4: the WAL checkpointer, on its own thread and connection. SQLite's
|
|
165
|
+
* automatic checkpoint runs inside whichever commit crosses the threshold, on
|
|
166
|
+
* the main thread, copying WAL pages and syncing the database file: on slow
|
|
167
|
+
* disks that is a 20-30 ms stall every few hundred deletes. A PASSIVE
|
|
168
|
+
* checkpoint from another connection never blocks writers, so the main thread
|
|
169
|
+
* only ever appends to the WAL.
|
|
170
|
+
*/
|
|
171
|
+
const CHECKPOINT_WORKER = `
|
|
172
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
173
|
+
const { DatabaseSync } = require("node:sqlite");
|
|
174
|
+
const flags = new Int32Array(workerData.flags);
|
|
175
|
+
let db;
|
|
176
|
+
try {
|
|
177
|
+
db = new DatabaseSync(workerData.path);
|
|
178
|
+
} catch {
|
|
179
|
+
// The database is gone or unreadable (a store closed, and its directory removed, before this
|
|
180
|
+
// thread got to start): end quietly. The main thread sees the exit and, if the store is still
|
|
181
|
+
// open, turns SQLite's own checkpoints back on.
|
|
182
|
+
Atomics.store(flags, 0, 1);
|
|
183
|
+
Atomics.notify(flags, 0);
|
|
184
|
+
process.exit(0);
|
|
185
|
+
}
|
|
186
|
+
db.exec("PRAGMA busy_timeout = 1000");
|
|
187
|
+
db.exec("PRAGMA journal_size_limit = " + workerData.journalSizeLimit);
|
|
188
|
+
const checkpoint = db.prepare("PRAGMA wal_checkpoint(PASSIVE)");
|
|
189
|
+
// Every attempt is reported, so the main thread's watchdog sees a stall.
|
|
190
|
+
// A PASSIVE checkpoint copies the frames committed when it starts. Under a
|
|
191
|
+
// steady write load it rarely sees the WAL fully copied, and SQLite only
|
|
192
|
+
// rewinds the WAL to its start when a writer finds it fully copied, so the
|
|
193
|
+
// WAL would grow for as long as writes continue. While a pass leaves frames
|
|
194
|
+
// behind, the worker runs again right away (bounded), keeping the copy close
|
|
195
|
+
// behind the writer so the WAL keeps rewinding.
|
|
196
|
+
function pass(id) {
|
|
197
|
+
try {
|
|
198
|
+
let r;
|
|
199
|
+
for (let i = 0; i < 32; i++) {
|
|
200
|
+
r = checkpoint.all()[0];
|
|
201
|
+
if (Number(r.log) <= Number(r.checkpointed)) break;
|
|
202
|
+
}
|
|
203
|
+
parentPort.postMessage({ t: "ckpt", ok: true, busy: Number(r.busy), log: Number(r.log), checkpointed: Number(r.checkpointed), ...(id !== undefined ? { id } : {}) });
|
|
204
|
+
} catch (e) {
|
|
205
|
+
parentPort.postMessage({ t: "ckpt", ok: false, error: String(e && e.message), ...(id !== undefined ? { id } : {}) });
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
let timer = setInterval(pass, workerData.intervalMs);
|
|
209
|
+
parentPort.on("message", (m) => {
|
|
210
|
+
// Test hook: one pass now, its report tagged with the id (it sees every commit made before).
|
|
211
|
+
if (m && m.t === "pass") pass(m.id);
|
|
212
|
+
if (m === "stall") {
|
|
213
|
+
// Test hook: stop checkpointing, as a wedged worker would. The reply comes
|
|
214
|
+
// after every report already sent (the port keeps order).
|
|
215
|
+
clearInterval(timer);
|
|
216
|
+
timer = undefined;
|
|
217
|
+
parentPort.postMessage({ t: "stalled" });
|
|
218
|
+
}
|
|
219
|
+
if (m === "stop") {
|
|
220
|
+
clearInterval(timer);
|
|
221
|
+
try { db.close(); } catch {}
|
|
222
|
+
// Tell the (blocked) main thread this connection is gone.
|
|
223
|
+
Atomics.store(flags, 0, 1);
|
|
224
|
+
Atomics.notify(flags, 0);
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
`;
|
|
228
|
+
export class SqliteStore {
|
|
229
|
+
db;
|
|
230
|
+
q;
|
|
231
|
+
closed = false;
|
|
232
|
+
txDepth = 0;
|
|
233
|
+
checkpointer;
|
|
234
|
+
/** Shared with the checkpoint worker: [0] becomes 1 once its connection is closed. */
|
|
235
|
+
checkpointerFlags;
|
|
236
|
+
path;
|
|
237
|
+
opts;
|
|
238
|
+
watchdog;
|
|
239
|
+
/** When the worker last reported a completed checkpoint (wall-clock ms). */
|
|
240
|
+
lastCheckpointAt;
|
|
241
|
+
/** True while SQLite's in-commit autocheckpoint is back on (no healthy worker). */
|
|
242
|
+
autocheckpointOn = true;
|
|
243
|
+
/** Bytes across every invite: the sum of `invite_iss`, kept by issAdd (a counter read, not a scan of the blobs). */
|
|
244
|
+
inviteTotal = 0;
|
|
245
|
+
/** issAdd deltas of the open transaction, applied to inviteTotal on commit. */
|
|
246
|
+
inviteDelta = 0;
|
|
247
|
+
constructor(path, opts = {}) {
|
|
248
|
+
this.db = new DatabaseSync(path);
|
|
249
|
+
this.db.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA secure_delete = ON; PRAGMA busy_timeout = 5000;");
|
|
250
|
+
this.db.exec(SCHEMA);
|
|
251
|
+
this.db.exec(`PRAGMA journal_size_limit = ${Math.trunc(opts.journalSizeLimitBytes ?? JOURNAL_SIZE_LIMIT)}`);
|
|
252
|
+
this.path = path;
|
|
253
|
+
this.opts = opts;
|
|
254
|
+
this.lastCheckpointAt = this.now();
|
|
255
|
+
if (path !== ":memory:" && opts.backgroundCheckpoint !== false) {
|
|
256
|
+
this.startCheckpointer();
|
|
257
|
+
const every = Math.max(50, Math.min(1000, Math.floor((opts.checkpointWatchdogMs ?? CHECKPOINT_WATCHDOG_MS) / 3)));
|
|
258
|
+
this.watchdog = setInterval(() => this.checkWatchdog(), every);
|
|
259
|
+
this.watchdog.unref();
|
|
260
|
+
}
|
|
261
|
+
// One row per userId holding invites, not per invite; init() rebuilds it exactly.
|
|
262
|
+
this.inviteTotal = Number(this.db.prepare("SELECT coalesce(sum(bytes), 0) AS b FROM invite_iss").get().b);
|
|
263
|
+
const row = this.db.prepare("SELECT v FROM meta WHERE k = 'schema'").get();
|
|
264
|
+
if (!row)
|
|
265
|
+
this.db.prepare("INSERT INTO meta (k, v) VALUES ('schema', ?)").run(String(SCHEMA_VERSION));
|
|
266
|
+
else if (Number(row.v) !== SCHEMA_VERSION)
|
|
267
|
+
throw new Error(`relay db schema ${row.v}, this relay understands ${SCHEMA_VERSION}`);
|
|
268
|
+
const trace = opts.trace;
|
|
269
|
+
const p = (sql) => {
|
|
270
|
+
const st = this.db.prepare(sql);
|
|
271
|
+
if (!trace)
|
|
272
|
+
return st;
|
|
273
|
+
return {
|
|
274
|
+
run: (...a) => (trace(sql), st.run(...a)),
|
|
275
|
+
get: (...a) => (trace(sql), st.get(...a)),
|
|
276
|
+
all: (...a) => (trace(sql), st.all(...a)),
|
|
277
|
+
};
|
|
278
|
+
};
|
|
279
|
+
this.q = {
|
|
280
|
+
getMeta: p("SELECT v FROM meta WHERE k = ?"),
|
|
281
|
+
setMeta: p("INSERT OR REPLACE INTO meta (k, v) VALUES (?, ?)"),
|
|
282
|
+
deviceIssuer: p("SELECT iss FROM devices WHERE did = ?"),
|
|
283
|
+
touchDevice: p("INSERT INTO devices (did, iss, last_seen) VALUES (?, ?, ?) ON CONFLICT (did) DO UPDATE SET last_seen = excluded.last_seen WHERE devices.iss = excluded.iss"),
|
|
284
|
+
evictableDevices: p(`SELECT did, iss, last_seen FROM devices WHERE evictable = 1 AND (last_seen > ? OR (last_seen = ? AND did > ?))
|
|
285
|
+
ORDER BY last_seen ASC, did ASC LIMIT ?`),
|
|
286
|
+
refreshEvictable: p(`UPDATE devices SET evictable = (
|
|
287
|
+
NOT EXISTS (SELECT 1 FROM totals t WHERE t.kind = 'mbox' AND t.key = devices.iss || char(10) || devices.did)
|
|
288
|
+
AND NOT EXISTS (SELECT 1 FROM allowed_devices a WHERE a.did = devices.did AND a.iss = devices.iss))
|
|
289
|
+
WHERE did = ?`),
|
|
290
|
+
refreshEvictableRange: p(`UPDATE devices SET evictable = (
|
|
291
|
+
NOT EXISTS (SELECT 1 FROM totals t WHERE t.kind = 'mbox' AND t.key = devices.iss || char(10) || devices.did)
|
|
292
|
+
AND NOT EXISTS (SELECT 1 FROM allowed_devices a WHERE a.did = devices.did AND a.iss = devices.iss))
|
|
293
|
+
WHERE rowid > ? AND rowid <= ?`),
|
|
294
|
+
maxDeviceRowid: p("SELECT coalesce(max(rowid), 0) AS m FROM devices"),
|
|
295
|
+
allowedOf: p("SELECT did FROM allowed_devices WHERE iss = ?"),
|
|
296
|
+
clearAllowed: p("DELETE FROM allowed_devices WHERE iss = ?"),
|
|
297
|
+
addAllowed: p("INSERT OR IGNORE INTO allowed_devices (did, iss) VALUES (?, ?)"),
|
|
298
|
+
chunk: p("SELECT rid, mbox_to, mbox_did, src, size FROM envelopes WHERE rid > ? ORDER BY rid ASC LIMIT ?"),
|
|
299
|
+
expired: p("SELECT rid, mbox_to, mbox_did, src, size FROM envelopes WHERE received_at < ? ORDER BY received_at ASC LIMIT ?"),
|
|
300
|
+
deleteDevice: p("DELETE FROM devices WHERE did = ?"),
|
|
301
|
+
insertEnv: p("INSERT INTO envelopes (mbox_to, mbox_did, src, size, received_at, env) VALUES (?, ?, ?, ?, ?, ?)"),
|
|
302
|
+
envMeta: p("SELECT rid, mbox_to, mbox_did, src, size FROM envelopes WHERE rid = ?"),
|
|
303
|
+
deleteRid: p("DELETE FROM envelopes WHERE rid = ?"),
|
|
304
|
+
total: p("SELECT bytes, n FROM totals WHERE kind = ? AND key = ?"),
|
|
305
|
+
bump: p("INSERT INTO totals (kind, key, bytes, n) VALUES (?, ?, ?, ?) ON CONFLICT (kind, key) DO UPDATE SET bytes = bytes + excluded.bytes, n = n + excluded.n"),
|
|
306
|
+
dropEmpty: p("DELETE FROM totals WHERE kind = ? AND key = ? AND n <= 0"),
|
|
307
|
+
topSrc: p("SELECT key, bytes FROM totals WHERE kind = 'src' ORDER BY bytes DESC LIMIT 32"),
|
|
308
|
+
countSrc: p("SELECT count(*) AS n FROM totals WHERE kind = 'src'"),
|
|
309
|
+
rsrcOf: p("SELECT key, bytes FROM totals WHERE kind = 'rsrc' AND key > ? AND key < ?"),
|
|
310
|
+
largestUnder: p("SELECT key FROM totals WHERE kind = ? AND key > ? AND key < ? ORDER BY bytes DESC LIMIT 1"),
|
|
311
|
+
mboxOldest: p("SELECT rid, mbox_to, mbox_did, src, size FROM envelopes WHERE mbox_to = ? AND mbox_did = ? ORDER BY rid ASC LIMIT ?"),
|
|
312
|
+
srcMboxOldest: p("SELECT rid, mbox_to, mbox_did, src, size FROM envelopes WHERE src = ? AND mbox_to = ? AND mbox_did = ? ORDER BY rid ASC LIMIT 64"),
|
|
313
|
+
toSrcOldest: p("SELECT rid, mbox_to, mbox_did, src, size FROM envelopes WHERE mbox_to = ? AND src = ? ORDER BY rid ASC LIMIT 64"),
|
|
314
|
+
envAfter: p("SELECT rid, mbox_to, mbox_did, env, size, received_at FROM envelopes WHERE mbox_to = ? AND mbox_did = ? AND rid > ? AND received_at >= ? ORDER BY rid ASC LIMIT ?"),
|
|
315
|
+
capState: p("SELECT revoked, uses FROM caps WHERE key = ?"),
|
|
316
|
+
revokeCap: p("INSERT INTO caps (key, revoked, uses, updated_at) VALUES (?, 1, 0, ?) ON CONFLICT (key) DO UPDATE SET revoked = 1, updated_at = excluded.updated_at"),
|
|
317
|
+
useCap: p("INSERT INTO caps (key, revoked, uses, updated_at) VALUES (?, 0, 1, ?) ON CONFLICT (key) DO UPDATE SET uses = uses + 1, updated_at = excluded.updated_at"),
|
|
318
|
+
doc: p("SELECT * FROM identity_docs WHERE hash = ?"),
|
|
319
|
+
docs: p("SELECT * FROM identity_docs WHERE iss = ? ORDER BY ver ASC"),
|
|
320
|
+
putDoc: p("INSERT OR IGNORE INTO identity_docs (hash, iss, ver, prev, merge, devices, iat, exp, received_at, jws) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),
|
|
321
|
+
deleteDoc: p("DELETE FROM identity_docs WHERE hash = ?"),
|
|
322
|
+
index: p("SELECT * FROM identity_index WHERE iss = ?"),
|
|
323
|
+
putIndex: p("INSERT OR REPLACE INTO identity_index (iss, head, head_ver, head_exp, tips, allowed, cap, left_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),
|
|
324
|
+
deleteIdentityDocs: p("DELETE FROM identity_docs WHERE iss = ?"),
|
|
325
|
+
deleteIndex: p("DELETE FROM identity_index WHERE iss = ?"),
|
|
326
|
+
seenOf: p("SELECT did FROM identity_seen WHERE iss = ? AND at >= ?"),
|
|
327
|
+
addSeen: p("INSERT OR REPLACE INTO identity_seen (iss, did, at) VALUES (?, ?, ?)"),
|
|
328
|
+
trimSeen: p("DELETE FROM identity_seen WHERE iss = ? AND did NOT IN (SELECT did FROM identity_seen WHERE iss = ? ORDER BY at DESC, did LIMIT ?)"),
|
|
329
|
+
clearSeen: p("DELETE FROM identity_seen WHERE iss = ?"),
|
|
330
|
+
sweepSeen: p("DELETE FROM identity_seen WHERE rowid IN (SELECT rowid FROM identity_seen WHERE at < ? LIMIT ?)"),
|
|
331
|
+
expiredIdentities: p("SELECT iss FROM identity_index WHERE left_at IS NULL AND head_exp < ? LIMIT ?"),
|
|
332
|
+
staleTombstones: p("SELECT iss FROM identity_index WHERE left_at IS NOT NULL AND left_at < ? LIMIT ?"),
|
|
333
|
+
sweepCaps: p("DELETE FROM caps WHERE rowid IN (SELECT rowid FROM caps WHERE updated_at < ? LIMIT ?)"),
|
|
334
|
+
sweepDocCandidates: p(`SELECT d.hash, d.iss, d.devices FROM identity_docs d WHERE d.received_at < ? AND (
|
|
335
|
+
EXISTS (SELECT 1 FROM identity_docs c WHERE c.prev = d.hash)
|
|
336
|
+
OR EXISTS (SELECT 1 FROM identity_docs c WHERE c.merge = d.hash))
|
|
337
|
+
LIMIT ?`),
|
|
338
|
+
sweepDocs: p(`DELETE FROM identity_docs WHERE rowid IN (
|
|
339
|
+
SELECT d.rowid FROM identity_docs d WHERE d.received_at < ? AND (
|
|
340
|
+
EXISTS (SELECT 1 FROM identity_docs c WHERE c.prev = d.hash)
|
|
341
|
+
OR EXISTS (SELECT 1 FROM identity_docs c WHERE c.merge = d.hash))
|
|
342
|
+
LIMIT ?)`),
|
|
343
|
+
sweepDevices: p("DELETE FROM devices WHERE rowid IN (SELECT rowid FROM devices WHERE last_seen < ? LIMIT ?)"),
|
|
344
|
+
countDevices: p("SELECT count(*) AS n FROM devices"),
|
|
345
|
+
countDocs: p("SELECT count(*) AS n FROM identity_docs"),
|
|
346
|
+
ping: p("SELECT 1 AS ok"),
|
|
347
|
+
putInvite: p("INSERT OR IGNORE INTO invites (lid, iss, blob, size, created_at, expires_at, src) VALUES (?, ?, ?, ?, ?, ?, ?)"),
|
|
348
|
+
getInvite: p("SELECT lid, iss, blob, size, created_at, expires_at, src FROM invites WHERE lid = ?"),
|
|
349
|
+
inviteBytesOfSrc: p("SELECT coalesce(sum(size), 0) AS b FROM invites WHERE src = ?"),
|
|
350
|
+
inviteTopIss: p("SELECT iss FROM invite_iss ORDER BY bytes DESC, iss LIMIT 1"),
|
|
351
|
+
issAdd: p("INSERT INTO invite_iss (iss, bytes) VALUES (?, ?) ON CONFLICT (iss) DO UPDATE SET bytes = bytes + excluded.bytes"),
|
|
352
|
+
issClean: p("DELETE FROM invite_iss WHERE iss = ? AND bytes <= 0"),
|
|
353
|
+
issBytes: p("SELECT bytes FROM invite_iss WHERE iss = ?"),
|
|
354
|
+
inviteChunk: p("SELECT rowid AS rid, iss, size FROM invites WHERE rowid > ? ORDER BY rowid LIMIT ?"),
|
|
355
|
+
expiredInvites: p("SELECT lid, iss, size FROM invites WHERE expires_at <= ? ORDER BY expires_at, lid LIMIT ?"),
|
|
356
|
+
addEvicted: p("INSERT OR REPLACE INTO invite_evicted (lid, iss, expires_at) VALUES (?, ?, ?)"),
|
|
357
|
+
evictedOf: p("SELECT lid FROM invite_evicted WHERE iss = ? AND expires_at > ?"),
|
|
358
|
+
sweepEvicted: p("DELETE FROM invite_evicted WHERE rowid IN (SELECT rowid FROM invite_evicted WHERE expires_at <= ? ORDER BY expires_at LIMIT ?)"),
|
|
359
|
+
inviteNewestOf: p("SELECT lid, size, expires_at FROM invites WHERE iss = ? ORDER BY created_at DESC, lid DESC LIMIT 1"),
|
|
360
|
+
getInviteOwner: p("SELECT iss, size FROM invites WHERE lid = ? AND iss = ?"),
|
|
361
|
+
delInvite: p("DELETE FROM invites WHERE lid = ?"),
|
|
362
|
+
delInviteOf: p("DELETE FROM invites WHERE lid = ? AND iss = ?"),
|
|
363
|
+
invitesOf: p("SELECT lid FROM invites WHERE iss = ? AND expires_at > ? ORDER BY created_at, lid"),
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Startup (N-M1): rebuilds `totals`, `allowed_devices` and the devices'
|
|
368
|
+
* `evictable` flags, reading in chunks and yielding between them, so no
|
|
369
|
+
* single step blocks for long. Old rows keep their (now anonymous) source
|
|
370
|
+
* tags (R-M1). The relay calls this before it accepts connections.
|
|
371
|
+
*/
|
|
372
|
+
async init() {
|
|
373
|
+
const CHUNK = 2000;
|
|
374
|
+
// Earlier versions kept a persisted source key; never keep one (N-M3).
|
|
375
|
+
this.db.exec("DELETE FROM meta WHERE k IN ('src_key', 'src_key_at')");
|
|
376
|
+
const acc = new Map();
|
|
377
|
+
let after = 0;
|
|
378
|
+
for (;;) {
|
|
379
|
+
const rows = this.q.chunk.all(after, CHUNK);
|
|
380
|
+
if (rows.length === 0)
|
|
381
|
+
break;
|
|
382
|
+
for (const r of rows) {
|
|
383
|
+
for (const [kind, key] of totalKeys(r.mbox_to, r.mbox_did, r.src)) {
|
|
384
|
+
const k = `${kind}\u0000${key}`;
|
|
385
|
+
const t = acc.get(k) ?? { kind, key, bytes: 0, n: 0 };
|
|
386
|
+
t.bytes += Number(r.size);
|
|
387
|
+
t.n += 1;
|
|
388
|
+
acc.set(k, t);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
after = Number(rows[rows.length - 1].rid);
|
|
392
|
+
await new Promise((res) => setImmediate(res));
|
|
393
|
+
}
|
|
394
|
+
const entries = [...acc.values()];
|
|
395
|
+
this.tx(() => this.db.exec("DELETE FROM totals"));
|
|
396
|
+
for (let i = 0; i < entries.length; i += CHUNK) {
|
|
397
|
+
this.tx(() => {
|
|
398
|
+
for (const t of entries.slice(i, i + CHUNK))
|
|
399
|
+
this.q.bump.run(t.kind, t.key, t.bytes, t.n);
|
|
400
|
+
});
|
|
401
|
+
await new Promise((res) => setImmediate(res));
|
|
402
|
+
}
|
|
403
|
+
this.tx(() => {
|
|
404
|
+
this.db.exec("DELETE FROM allowed_devices");
|
|
405
|
+
const rows = this.db.prepare("SELECT iss, allowed FROM identity_index").all();
|
|
406
|
+
for (const r of rows)
|
|
407
|
+
for (const did of JSON.parse(r.allowed))
|
|
408
|
+
this.q.addAllowed.run(did, r.iss);
|
|
409
|
+
});
|
|
410
|
+
const maxRowid = Number(this.q.maxDeviceRowid.get().m);
|
|
411
|
+
for (let lo = 0; lo < maxRowid; lo += CHUNK) {
|
|
412
|
+
this.tx(() => this.q.refreshEvictableRange.run(lo, lo + CHUNK));
|
|
413
|
+
await new Promise((res) => setImmediate(res));
|
|
414
|
+
}
|
|
415
|
+
// Per-userId invite totals, rebuilt from the invites in chunks (every
|
|
416
|
+
// write keeps them after; this repairs anything a crash could leave).
|
|
417
|
+
const issAcc = new Map();
|
|
418
|
+
let inv = 0;
|
|
419
|
+
for (;;) {
|
|
420
|
+
const rows = this.q.inviteChunk.all(inv, CHUNK);
|
|
421
|
+
if (rows.length === 0)
|
|
422
|
+
break;
|
|
423
|
+
for (const r of rows)
|
|
424
|
+
issAcc.set(r.iss, (issAcc.get(r.iss) ?? 0) + Number(r.size));
|
|
425
|
+
inv = Number(rows[rows.length - 1].rid);
|
|
426
|
+
await new Promise((res) => setImmediate(res));
|
|
427
|
+
}
|
|
428
|
+
const issRows = [...issAcc];
|
|
429
|
+
this.tx(() => {
|
|
430
|
+
this.db.exec("DELETE FROM invite_iss");
|
|
431
|
+
for (const [iss, bytes] of issRows)
|
|
432
|
+
this.q.issAdd.run(iss, bytes);
|
|
433
|
+
});
|
|
434
|
+
this.inviteTotal = issRows.reduce((a, [, b]) => a + b, 0);
|
|
435
|
+
}
|
|
436
|
+
/** Re-entrant: an inner call joins the outer transaction. */
|
|
437
|
+
tx(fn) {
|
|
438
|
+
if (this.txDepth > 0) {
|
|
439
|
+
this.txDepth++;
|
|
440
|
+
try {
|
|
441
|
+
return fn();
|
|
442
|
+
}
|
|
443
|
+
finally {
|
|
444
|
+
this.txDepth--;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
448
|
+
this.txDepth = 1;
|
|
449
|
+
this.inviteDelta = 0;
|
|
450
|
+
try {
|
|
451
|
+
const out = fn();
|
|
452
|
+
this.db.exec("COMMIT");
|
|
453
|
+
this.inviteTotal += this.inviteDelta;
|
|
454
|
+
return out;
|
|
455
|
+
}
|
|
456
|
+
catch (e) {
|
|
457
|
+
this.db.exec("ROLLBACK");
|
|
458
|
+
throw e;
|
|
459
|
+
}
|
|
460
|
+
finally {
|
|
461
|
+
this.txDepth = 0;
|
|
462
|
+
this.inviteDelta = 0;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
transaction(fn) {
|
|
466
|
+
return this.tx(fn);
|
|
467
|
+
}
|
|
468
|
+
getMeta(key) {
|
|
469
|
+
return this.q.getMeta.get(key)?.v;
|
|
470
|
+
}
|
|
471
|
+
setMeta(key, value) {
|
|
472
|
+
this.q.setMeta.run(key, value);
|
|
473
|
+
}
|
|
474
|
+
deviceIssuer(did) {
|
|
475
|
+
const r = this.q.deviceIssuer.get(did);
|
|
476
|
+
return r?.iss;
|
|
477
|
+
}
|
|
478
|
+
touchDevice(did, iss, now) {
|
|
479
|
+
const existed = this.q.deviceIssuer.get(did) !== undefined;
|
|
480
|
+
this.q.touchDevice.run(did, iss, now);
|
|
481
|
+
if (!existed)
|
|
482
|
+
this.q.refreshEvictable.run(did);
|
|
483
|
+
return !existed;
|
|
484
|
+
}
|
|
485
|
+
evictableDevices(limit, after) {
|
|
486
|
+
const ls = after?.lastSeen ?? -1;
|
|
487
|
+
const rows = this.q.evictableDevices.all(ls, ls, after?.did ?? "", limit);
|
|
488
|
+
return rows.map((r) => ({ did: r.did, iss: r.iss, lastSeen: Number(r.last_seen) }));
|
|
489
|
+
}
|
|
490
|
+
deleteDevice(did) {
|
|
491
|
+
this.q.deleteDevice.run(did);
|
|
492
|
+
}
|
|
493
|
+
// -------------------------------------------------------------------------
|
|
494
|
+
// Envelopes and their totals
|
|
495
|
+
bumpTotals(to, tdid, src, size, sign) {
|
|
496
|
+
for (const [kind, key] of totalKeys(to, tdid, src)) {
|
|
497
|
+
this.q.bump.run(kind, key, sign * size, sign);
|
|
498
|
+
if (sign < 0)
|
|
499
|
+
this.q.dropEmpty.run(kind, key);
|
|
500
|
+
}
|
|
501
|
+
// R-L2: a mailbox gaining its first or losing its last envelope flips
|
|
502
|
+
// whether its device binding may be evicted.
|
|
503
|
+
const n = this.total("mbox", `${to}\n${tdid}`).n;
|
|
504
|
+
if ((sign > 0 && n === 1) || (sign < 0 && n === 0))
|
|
505
|
+
this.q.refreshEvictable.run(tdid);
|
|
506
|
+
}
|
|
507
|
+
total(kind, key) {
|
|
508
|
+
const r = this.q.total.get(kind, key);
|
|
509
|
+
return { bytes: Number(r?.bytes ?? 0), n: Number(r?.n ?? 0) };
|
|
510
|
+
}
|
|
511
|
+
deleteEnv(m) {
|
|
512
|
+
this.q.deleteRid.run(m.rid);
|
|
513
|
+
const size = Number(m.size);
|
|
514
|
+
this.bumpTotals(m.mbox_to, m.mbox_did, m.src, size, -1);
|
|
515
|
+
return size;
|
|
516
|
+
}
|
|
517
|
+
/** The oldest envelopes of source `src` in mailbox (to, tdid). */
|
|
518
|
+
srcMailboxOldest(src, to, tdid) {
|
|
519
|
+
return this.q.srcMboxOldest.all(src, to, tdid);
|
|
520
|
+
}
|
|
521
|
+
/** Frees bytes from source `src`'s largest mailbox; 0 when the source holds nothing. */
|
|
522
|
+
evictFromSource(src, bytes) {
|
|
523
|
+
const mbox = this.largestUnder("smbox", src);
|
|
524
|
+
if (mbox === undefined)
|
|
525
|
+
return 0;
|
|
526
|
+
const [to, tdid] = mbox.split("\n");
|
|
527
|
+
let freed = 0;
|
|
528
|
+
for (const r of this.srcMailboxOldest(src, to, tdid)) {
|
|
529
|
+
if (freed >= bytes)
|
|
530
|
+
break;
|
|
531
|
+
freed += this.deleteEnv(r);
|
|
532
|
+
}
|
|
533
|
+
return freed;
|
|
534
|
+
}
|
|
535
|
+
/** Largest key of `kind` starting with `prefix + "\n"`, by bytes. */
|
|
536
|
+
largestUnder(kind, prefix) {
|
|
537
|
+
const r = this.q.largestUnder.get(kind, `${prefix}\n`, `${prefix}\u000b`);
|
|
538
|
+
return r?.key.slice(prefix.length + 1);
|
|
539
|
+
}
|
|
540
|
+
putEnvelope(e, caps) {
|
|
541
|
+
return this.tx(() => {
|
|
542
|
+
const res = this.q.insertEnv.run(e.to, e.tdid, e.src, e.size, e.receivedAt, e.env);
|
|
543
|
+
const rid = Number(res.lastInsertRowid);
|
|
544
|
+
this.bumpTotals(e.to, e.tdid, e.src, e.size, 1);
|
|
545
|
+
let { n, bytes } = this.total("mbox", `${e.to}\n${e.tdid}`);
|
|
546
|
+
let dropped = 0;
|
|
547
|
+
let droppedBytes = 0;
|
|
548
|
+
while (n > caps.maxEnvelopes || bytes > caps.maxBytes) {
|
|
549
|
+
const rows = this.q.mboxOldest.all(e.to, e.tdid, 64);
|
|
550
|
+
if (rows.length === 0)
|
|
551
|
+
break;
|
|
552
|
+
for (const r of rows) {
|
|
553
|
+
if (n <= caps.maxEnvelopes && bytes <= caps.maxBytes)
|
|
554
|
+
break;
|
|
555
|
+
const size = this.deleteEnv(r);
|
|
556
|
+
n--;
|
|
557
|
+
bytes -= size;
|
|
558
|
+
droppedBytes += size;
|
|
559
|
+
dropped++;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
return { rid, dropped, droppedBytes };
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
envelopesAfter(to, tdid, afterRid, notBefore, limit) {
|
|
566
|
+
const rows = this.q.envAfter.all(to, tdid, afterRid, notBefore, limit);
|
|
567
|
+
return rows.map((r) => ({
|
|
568
|
+
rid: Number(r.rid),
|
|
569
|
+
to: r.mbox_to,
|
|
570
|
+
tdid: r.mbox_did,
|
|
571
|
+
env: r.env,
|
|
572
|
+
size: Number(r.size),
|
|
573
|
+
receivedAt: Number(r.received_at),
|
|
574
|
+
}));
|
|
575
|
+
}
|
|
576
|
+
ackEnvelopes(to, tdid, rids) {
|
|
577
|
+
if (rids.length === 0)
|
|
578
|
+
return { count: 0, bytes: 0 };
|
|
579
|
+
return this.tx(() => {
|
|
580
|
+
let count = 0;
|
|
581
|
+
let bytes = 0;
|
|
582
|
+
for (const rid of rids) {
|
|
583
|
+
const m = this.q.envMeta.get(rid);
|
|
584
|
+
if (!m || m.mbox_to !== to || m.mbox_did !== tdid)
|
|
585
|
+
continue;
|
|
586
|
+
bytes += this.deleteEnv(m);
|
|
587
|
+
count++;
|
|
588
|
+
}
|
|
589
|
+
return { count, bytes };
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
bytesForRecipient(to) {
|
|
593
|
+
return this.total("rcpt", to).bytes;
|
|
594
|
+
}
|
|
595
|
+
mailboxBytes(to, tdid) {
|
|
596
|
+
return this.total("mbox", `${to}\n${tdid}`).bytes;
|
|
597
|
+
}
|
|
598
|
+
evictRecipient(to, bytes, policy = {}) {
|
|
599
|
+
return this.tx(() => {
|
|
600
|
+
let freed = 0;
|
|
601
|
+
while (freed < bytes) {
|
|
602
|
+
// Per EvictPolicy (F-6): the sender if over its fair share, else the largest group above the floor, else the largest.
|
|
603
|
+
const rows = this.q.rsrcOf.all(`${to}\n`, `${to}\u000b`);
|
|
604
|
+
const src = pickSource(rows.map((r) => ({ src: r.key.slice(to.length + 1), bytes: Number(r.bytes) })), policy);
|
|
605
|
+
if (src === undefined)
|
|
606
|
+
break;
|
|
607
|
+
const victims = this.q.toSrcOldest.all(to, src);
|
|
608
|
+
if (victims.length === 0)
|
|
609
|
+
break;
|
|
610
|
+
for (const r of victims) {
|
|
611
|
+
if (freed >= bytes)
|
|
612
|
+
break;
|
|
613
|
+
freed += this.deleteEnv(r);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
return freed;
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* The source group to evict from, per EvictPolicy, from counters only: the
|
|
621
|
+
* largest groups by the bytes index, plus the sender's own total.
|
|
622
|
+
*/
|
|
623
|
+
pickGlobalSource(policy) {
|
|
624
|
+
const cands = this.q.topSrc.all().map((r) => ({ src: r.key, bytes: Number(r.bytes) }));
|
|
625
|
+
if (policy.sender !== undefined && !cands.some((c) => c.src === policy.sender)) {
|
|
626
|
+
cands.push({ src: policy.sender, bytes: this.total("src", policy.sender).bytes });
|
|
627
|
+
}
|
|
628
|
+
const groups = Number(this.q.countSrc.get().n);
|
|
629
|
+
return pickSource(cands, policy, groups);
|
|
630
|
+
}
|
|
631
|
+
evictGlobal(bytes, policy = {}) {
|
|
632
|
+
return this.tx(() => {
|
|
633
|
+
let freed = 0;
|
|
634
|
+
while (freed < bytes) {
|
|
635
|
+
// Per EvictPolicy (sender first, then the largest above the floor);
|
|
636
|
+
// within the chosen source, the oldest of its largest mailbox.
|
|
637
|
+
const src = this.pickGlobalSource(policy);
|
|
638
|
+
if (src === undefined)
|
|
639
|
+
break;
|
|
640
|
+
const got = this.evictFromSource(src, bytes - freed);
|
|
641
|
+
if (got === 0)
|
|
642
|
+
break;
|
|
643
|
+
freed += got;
|
|
644
|
+
}
|
|
645
|
+
return freed;
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
sourceBytes(src) {
|
|
649
|
+
return this.total("src", src).bytes;
|
|
650
|
+
}
|
|
651
|
+
evictSource(src, bytes) {
|
|
652
|
+
return this.tx(() => {
|
|
653
|
+
let freed = 0;
|
|
654
|
+
while (freed < bytes) {
|
|
655
|
+
const got = this.evictFromSource(src, bytes - freed);
|
|
656
|
+
if (got === 0)
|
|
657
|
+
break;
|
|
658
|
+
freed += got;
|
|
659
|
+
}
|
|
660
|
+
return freed;
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
expireBatch(before, limit) {
|
|
664
|
+
return this.tx(() => {
|
|
665
|
+
const rows = this.q.expired.all(before, limit);
|
|
666
|
+
let bytes = 0;
|
|
667
|
+
for (const r of rows)
|
|
668
|
+
bytes += this.deleteEnv(r);
|
|
669
|
+
return { count: rows.length, bytes };
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
// -------------------------------------------------------------------------
|
|
673
|
+
capState(key) {
|
|
674
|
+
const r = this.q.capState.get(key);
|
|
675
|
+
return { revoked: Number(r?.revoked ?? 0) === 1, uses: Number(r?.uses ?? 0) };
|
|
676
|
+
}
|
|
677
|
+
revokeCap(key, now) {
|
|
678
|
+
this.q.revokeCap.run(key, now);
|
|
679
|
+
}
|
|
680
|
+
useCap(key, now) {
|
|
681
|
+
this.q.useCap.run(key, now);
|
|
682
|
+
}
|
|
683
|
+
identityDoc(hash) {
|
|
684
|
+
const r = this.q.doc.get(hash);
|
|
685
|
+
return r ? docFromRow(r) : undefined;
|
|
686
|
+
}
|
|
687
|
+
identityDocs(iss) {
|
|
688
|
+
return this.q.docs.all(iss).map(docFromRow);
|
|
689
|
+
}
|
|
690
|
+
putIdentityDoc(d) {
|
|
691
|
+
const res = this.q.putDoc.run(d.hash, d.iss, d.ver, d.prev, d.merge, JSON.stringify(d.devices), d.iat, d.exp, d.receivedAt, d.jws);
|
|
692
|
+
return Number(res.changes) === 1;
|
|
693
|
+
}
|
|
694
|
+
deleteIdentityDocs(hashes) {
|
|
695
|
+
if (hashes.length === 0)
|
|
696
|
+
return;
|
|
697
|
+
this.tx(() => {
|
|
698
|
+
for (const h of hashes)
|
|
699
|
+
this.q.deleteDoc.run(h);
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
identityIndex(iss) {
|
|
703
|
+
const r = this.q.index.get(iss);
|
|
704
|
+
if (!r)
|
|
705
|
+
return undefined;
|
|
706
|
+
return {
|
|
707
|
+
iss: r.iss,
|
|
708
|
+
head: r.head,
|
|
709
|
+
headVer: Number(r.head_ver),
|
|
710
|
+
headExp: Number(r.head_exp),
|
|
711
|
+
tips: JSON.parse(r.tips),
|
|
712
|
+
allowed: JSON.parse(r.allowed),
|
|
713
|
+
cap: r.cap === null ? null : JSON.parse(r.cap),
|
|
714
|
+
leftAt: r.left_at === null ? null : Number(r.left_at),
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
putIdentityIndex(i) {
|
|
718
|
+
this.tx(() => {
|
|
719
|
+
const before = this.q.allowedOf.all(i.iss).map((r) => r.did);
|
|
720
|
+
this.q.clearAllowed.run(i.iss);
|
|
721
|
+
for (const did of i.allowed)
|
|
722
|
+
this.q.addAllowed.run(did, i.iss);
|
|
723
|
+
this.putIndexRow(i);
|
|
724
|
+
for (const did of new Set([...before, ...i.allowed]))
|
|
725
|
+
this.q.refreshEvictable.run(did);
|
|
726
|
+
});
|
|
727
|
+
}
|
|
728
|
+
putIndexRow(i) {
|
|
729
|
+
this.q.putIndex.run(i.iss, i.head, i.headVer, i.headExp, JSON.stringify(i.tips), JSON.stringify(i.allowed), i.cap === null ? null : JSON.stringify(i.cap), i.leftAt);
|
|
730
|
+
}
|
|
731
|
+
deleteIdentityDocsOf(iss) {
|
|
732
|
+
this.q.deleteIdentityDocs.run(iss);
|
|
733
|
+
}
|
|
734
|
+
deleteIdentity(iss) {
|
|
735
|
+
this.tx(() => {
|
|
736
|
+
const before = this.q.allowedOf.all(iss).map((r) => r.did);
|
|
737
|
+
this.q.deleteIdentityDocs.run(iss);
|
|
738
|
+
this.q.deleteIndex.run(iss);
|
|
739
|
+
this.q.clearAllowed.run(iss);
|
|
740
|
+
this.q.clearSeen.run(iss);
|
|
741
|
+
for (const did of before)
|
|
742
|
+
this.q.refreshEvictable.run(did);
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* Sweeps at most `limit` old non-tip versions (F-4: bounded steps); their
|
|
747
|
+
* dids outside the allowlist are remembered first (R4-M1).
|
|
748
|
+
*/
|
|
749
|
+
sweepIdentityDocs(c, limit) {
|
|
750
|
+
const rows = this.q.sweepDocCandidates.all(c.identityVersionsBefore, limit);
|
|
751
|
+
if (c.nowMs !== undefined) {
|
|
752
|
+
const byIss = new Map();
|
|
753
|
+
for (const r of rows) {
|
|
754
|
+
let set = byIss.get(r.iss);
|
|
755
|
+
if (!set)
|
|
756
|
+
byIss.set(r.iss, (set = new Set()));
|
|
757
|
+
for (const d of JSON.parse(r.devices))
|
|
758
|
+
set.add(d);
|
|
759
|
+
}
|
|
760
|
+
for (const [iss, dids] of byIss) {
|
|
761
|
+
const allowed = new Set(this.q.allowedOf.all(iss).map((r) => r.did));
|
|
762
|
+
const gone = [...dids].filter((d) => !allowed.has(d));
|
|
763
|
+
if (gone.length > 0)
|
|
764
|
+
this.addSeen(iss, gone, c.nowMs);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
for (const r of rows)
|
|
768
|
+
this.q.deleteDoc.run(r.hash);
|
|
769
|
+
return rows.length;
|
|
770
|
+
}
|
|
771
|
+
seenDevices(iss, sinceMs) {
|
|
772
|
+
return this.q.seenOf.all(iss, sinceMs).map((r) => r.did);
|
|
773
|
+
}
|
|
774
|
+
addSeen(iss, dids, at) {
|
|
775
|
+
if (dids.length === 0)
|
|
776
|
+
return;
|
|
777
|
+
this.tx(() => {
|
|
778
|
+
for (const d of dids)
|
|
779
|
+
this.q.addSeen.run(iss, d, at);
|
|
780
|
+
this.q.trimSeen.run(iss, iss, MAX_SEEN_PER_ISS);
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
expiredIdentities(headExpBeforeSec, limit) {
|
|
784
|
+
return this.q.expiredIdentities.all(headExpBeforeSec, limit).map((r) => r.iss);
|
|
785
|
+
}
|
|
786
|
+
staleTombstones(leftBefore, limit) {
|
|
787
|
+
return this.q.staleTombstones.all(leftBefore, limit).map((r) => r.iss);
|
|
788
|
+
}
|
|
789
|
+
issAdd(iss, d) {
|
|
790
|
+
this.q.issAdd.run(iss, d);
|
|
791
|
+
// Applied to inviteTotal only when the outermost transaction commits, so
|
|
792
|
+
// a rollback leaves the counter matching the table.
|
|
793
|
+
if (this.txDepth > 0)
|
|
794
|
+
this.inviteDelta += d;
|
|
795
|
+
else
|
|
796
|
+
this.inviteTotal += d;
|
|
797
|
+
if (d < 0)
|
|
798
|
+
this.q.issClean.run(iss);
|
|
799
|
+
}
|
|
800
|
+
putInvite(i) {
|
|
801
|
+
return this.tx(() => {
|
|
802
|
+
const ok = Number(this.q.putInvite.run(i.lid, i.iss, i.blob, i.size, i.createdAt, i.expiresAt, i.src).changes) === 1;
|
|
803
|
+
if (ok)
|
|
804
|
+
this.issAdd(i.iss, i.size);
|
|
805
|
+
return ok;
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
takeInvite(lid, now) {
|
|
809
|
+
return this.tx(() => {
|
|
810
|
+
const r = this.q.getInvite.get(lid);
|
|
811
|
+
if (!r)
|
|
812
|
+
return undefined;
|
|
813
|
+
this.q.delInvite.run(lid);
|
|
814
|
+
this.issAdd(r.iss, -Number(r.size));
|
|
815
|
+
const i = { lid: r.lid, iss: r.iss, blob: r.blob, size: Number(r.size), createdAt: Number(r.created_at), expiresAt: Number(r.expires_at), src: r.src };
|
|
816
|
+
return i.expiresAt > now ? i : undefined;
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
deleteInvite(lid, iss) {
|
|
820
|
+
return this.tx(() => {
|
|
821
|
+
const r = this.q.getInviteOwner.get(lid, iss);
|
|
822
|
+
if (!r)
|
|
823
|
+
return false;
|
|
824
|
+
this.q.delInviteOf.run(lid, iss);
|
|
825
|
+
this.issAdd(iss, -Number(r.size));
|
|
826
|
+
return true;
|
|
827
|
+
});
|
|
828
|
+
}
|
|
829
|
+
invitesOf(iss, now) {
|
|
830
|
+
return this.q.invitesOf.all(iss, now).map((r) => r.lid);
|
|
831
|
+
}
|
|
832
|
+
evictedInvitesOf(iss, now) {
|
|
833
|
+
return this.q.evictedOf.all(iss, now).map((r) => r.lid);
|
|
834
|
+
}
|
|
835
|
+
inviteBytes() {
|
|
836
|
+
return this.inviteTotal;
|
|
837
|
+
}
|
|
838
|
+
inviteBytesOfIss(iss) {
|
|
839
|
+
const r = this.q.issBytes.get(iss);
|
|
840
|
+
return r ? Number(r.bytes) : 0;
|
|
841
|
+
}
|
|
842
|
+
sweepInvites(now, limit) {
|
|
843
|
+
return this.tx(() => {
|
|
844
|
+
const rows = this.q.expiredInvites.all(now, limit);
|
|
845
|
+
for (const r of rows) {
|
|
846
|
+
this.q.delInvite.run(r.lid);
|
|
847
|
+
this.issAdd(r.iss, -Number(r.size));
|
|
848
|
+
}
|
|
849
|
+
return { invites: rows.length, evicted: Number(this.q.sweepEvicted.run(now, limit).changes) };
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
inviteBytesOfSrc(src) {
|
|
853
|
+
return Number(this.q.inviteBytesOfSrc.get(src).b);
|
|
854
|
+
}
|
|
855
|
+
evictInvites(bytes, now) {
|
|
856
|
+
return this.tx(() => {
|
|
857
|
+
let freed = 0;
|
|
858
|
+
// Already-expired invites first: one row per step, only as many as `bytes` needs.
|
|
859
|
+
while (now !== undefined && freed < bytes) {
|
|
860
|
+
const r = this.q.expiredInvites.get(now, 1);
|
|
861
|
+
if (!r)
|
|
862
|
+
break;
|
|
863
|
+
this.q.delInvite.run(r.lid);
|
|
864
|
+
this.issAdd(r.iss, -Number(r.size));
|
|
865
|
+
freed += Number(r.size);
|
|
866
|
+
}
|
|
867
|
+
while (freed < bytes) {
|
|
868
|
+
const top = this.q.inviteTopIss.get();
|
|
869
|
+
if (!top)
|
|
870
|
+
break;
|
|
871
|
+
const n = this.q.inviteNewestOf.get(top.iss);
|
|
872
|
+
if (!n) {
|
|
873
|
+
// A stale counter (can't happen while every write keeps it): drop it and go on.
|
|
874
|
+
this.issAdd(top.iss, -this.inviteBytesOfIss(top.iss));
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
877
|
+
this.q.delInvite.run(n.lid);
|
|
878
|
+
this.issAdd(top.iss, -Number(n.size));
|
|
879
|
+
this.q.addEvicted.run(n.lid, top.iss, Number(n.expires_at));
|
|
880
|
+
freed += Number(n.size);
|
|
881
|
+
}
|
|
882
|
+
return freed;
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
envelopeTotals() {
|
|
886
|
+
const t = this.total("all", "");
|
|
887
|
+
return { envelopes: t.n, bytes: t.bytes };
|
|
888
|
+
}
|
|
889
|
+
sweep(c, limit) {
|
|
890
|
+
// Envelopes expire separately, in batches (expireBatch).
|
|
891
|
+
return this.tx(() => ({
|
|
892
|
+
caps: Number(this.q.sweepCaps.run(c.capsBefore, limit).changes),
|
|
893
|
+
identityDocs: this.sweepIdentityDocs(c, limit),
|
|
894
|
+
...(c.seenBefore !== undefined ? { seen: Number(this.q.sweepSeen.run(c.seenBefore, limit).changes) } : {}),
|
|
895
|
+
devices: Number(this.q.sweepDevices.run(c.devicesBefore, limit).changes),
|
|
896
|
+
}));
|
|
897
|
+
}
|
|
898
|
+
counts() {
|
|
899
|
+
const e = this.total("all", "");
|
|
900
|
+
const d = this.q.countDevices.get();
|
|
901
|
+
const i = this.q.countDocs.get();
|
|
902
|
+
return { envelopes: e.n, envelopeBytes: e.bytes, devices: Number(d.n), identityDocs: Number(i.n) };
|
|
903
|
+
}
|
|
904
|
+
ping() {
|
|
905
|
+
const r = this.q.ping.get();
|
|
906
|
+
return Number(r?.ok) === 1;
|
|
907
|
+
}
|
|
908
|
+
setAutocheckpoint(on) {
|
|
909
|
+
if (this.closed || this.autocheckpointOn === on)
|
|
910
|
+
return;
|
|
911
|
+
this.db.exec(`PRAGMA wal_autocheckpoint = ${on ? 1000 : 0}`);
|
|
912
|
+
this.autocheckpointOn = on;
|
|
913
|
+
}
|
|
914
|
+
/**
|
|
915
|
+
* Starts the checkpoint worker. SQLite's in-commit autocheckpoint stays on
|
|
916
|
+
* until the worker reports its first completed checkpoint, and comes back
|
|
917
|
+
* whenever the worker dies or stalls, so the WAL is never left unchecked.
|
|
918
|
+
*/
|
|
919
|
+
startCheckpointer() {
|
|
920
|
+
const flags = new Int32Array(new SharedArrayBuffer(4));
|
|
921
|
+
this.checkpointerFlags = flags;
|
|
922
|
+
const w = new Worker(CHECKPOINT_WORKER, {
|
|
923
|
+
eval: true,
|
|
924
|
+
workerData: {
|
|
925
|
+
path: this.path,
|
|
926
|
+
intervalMs: this.opts.checkpointIntervalMs ?? CHECKPOINT_INTERVAL_MS,
|
|
927
|
+
journalSizeLimit: Math.trunc(this.opts.journalSizeLimitBytes ?? JOURNAL_SIZE_LIMIT),
|
|
928
|
+
flags: flags.buffer,
|
|
929
|
+
},
|
|
930
|
+
});
|
|
931
|
+
w.unref();
|
|
932
|
+
this.lastCheckpointAt = this.now();
|
|
933
|
+
let prev;
|
|
934
|
+
w.on("message", (m) => {
|
|
935
|
+
if (m?.t !== "ckpt" || this.checkpointer !== w)
|
|
936
|
+
return;
|
|
937
|
+
if (!m.ok)
|
|
938
|
+
return;
|
|
939
|
+
// A pass shows progress when it copied every frame, when it copied more
|
|
940
|
+
// than the pass before, or when the WAL rewound (everything before was
|
|
941
|
+
// copied). Under sustained writes a pass rarely ends fully caught up,
|
|
942
|
+
// but it keeps advancing; a reader pinning an old snapshot stops it at
|
|
943
|
+
// the same frame every time (L-3), which is a real stall. (A PASSIVE
|
|
944
|
+
// pass reports busy = 0 even when a reader stops it short.)
|
|
945
|
+
const log = Number(m.log);
|
|
946
|
+
const checkpointed = Number(m.checkpointed);
|
|
947
|
+
const progress = checkpointed === log || (prev !== undefined && (checkpointed > prev.checkpointed || log < prev.log));
|
|
948
|
+
prev = { log, checkpointed };
|
|
949
|
+
if (progress) {
|
|
950
|
+
this.lastCheckpointAt = this.now();
|
|
951
|
+
// Hand checkpoints back to the worker only while the WAL is in bounds.
|
|
952
|
+
if (this.walBytes() <= (this.opts.walLimitBytes ?? WAL_LIMIT_BYTES))
|
|
953
|
+
this.setAutocheckpoint(false);
|
|
954
|
+
}
|
|
955
|
+
});
|
|
956
|
+
const died = () => {
|
|
957
|
+
if (this.checkpointer !== w)
|
|
958
|
+
return;
|
|
959
|
+
// Never let the WAL grow unchecked: back to SQLite's own checkpoints.
|
|
960
|
+
this.checkpointer = undefined;
|
|
961
|
+
this.setAutocheckpoint(true);
|
|
962
|
+
this.opts.warn?.("relay checkpoint worker exited; SQLite autocheckpoint re-enabled");
|
|
963
|
+
};
|
|
964
|
+
w.on("error", died);
|
|
965
|
+
w.on("exit", died);
|
|
966
|
+
this.checkpointer = w;
|
|
967
|
+
}
|
|
968
|
+
walBytes() {
|
|
969
|
+
try {
|
|
970
|
+
return statSync(`${this.path}-wal`).size;
|
|
971
|
+
}
|
|
972
|
+
catch {
|
|
973
|
+
return 0;
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
/**
|
|
977
|
+
* pre-release review: if no checkpoint completed within the watchdog window, or the
|
|
978
|
+
* WAL grew past its limit, turn SQLite's autocheckpoint back on, warn, and
|
|
979
|
+
* restart the worker (it switches autocheckpoint off again once healthy).
|
|
980
|
+
*/
|
|
981
|
+
lastWarnAt = 0;
|
|
982
|
+
now() {
|
|
983
|
+
return this.opts.now ? this.opts.now() : Date.now();
|
|
984
|
+
}
|
|
985
|
+
warnOnce(msg, fields) {
|
|
986
|
+
const now = this.now();
|
|
987
|
+
if (now - this.lastWarnAt < (this.opts.checkpointWatchdogMs ?? CHECKPOINT_WATCHDOG_MS))
|
|
988
|
+
return;
|
|
989
|
+
this.lastWarnAt = now;
|
|
990
|
+
this.opts.warn?.(msg, fields);
|
|
991
|
+
}
|
|
992
|
+
/** A backup's marker that is still in force (see BACKUP_MARKER_MAX_MS), or undefined. */
|
|
993
|
+
backupRunning() {
|
|
994
|
+
const marker = `${this.path}-backup`;
|
|
995
|
+
try {
|
|
996
|
+
const st = statSync(marker);
|
|
997
|
+
if (!st.isFile() || st.size > 1024)
|
|
998
|
+
return undefined;
|
|
999
|
+
const until = Number(JSON.parse(readFileSync(marker, "utf8")).until);
|
|
1000
|
+
const now = this.now();
|
|
1001
|
+
if (!Number.isFinite(until) || now >= until || now - st.mtimeMs > BACKUP_MARKER_MAX_MS)
|
|
1002
|
+
return undefined;
|
|
1003
|
+
return { until };
|
|
1004
|
+
}
|
|
1005
|
+
catch {
|
|
1006
|
+
return undefined;
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
/** One watchdog check, as its timer runs it (tests call it after advancing their clock). */
|
|
1010
|
+
checkWatchdog() {
|
|
1011
|
+
if (this.closed)
|
|
1012
|
+
return;
|
|
1013
|
+
const limit = this.opts.walLimitBytes ?? WAL_LIMIT_BYTES;
|
|
1014
|
+
const stalledMs = this.now() - this.lastCheckpointAt;
|
|
1015
|
+
const wal = this.walBytes();
|
|
1016
|
+
const stalled = !this.checkpointer || stalledMs > (this.opts.checkpointWatchdogMs ?? CHECKPOINT_WATCHDOG_MS);
|
|
1017
|
+
if (this.checkpointer && (stalled || wal > limit) && this.backupRunning()) {
|
|
1018
|
+
// Held back by a backup's snapshot, not stalled: the worker keeps running and copies the
|
|
1019
|
+
// grown WAL off the main thread once the backup lets go. The time the backup held it is
|
|
1020
|
+
// excused, so the worker gets a full window after that.
|
|
1021
|
+
this.lastCheckpointAt = this.now();
|
|
1022
|
+
this.warnOnce("relay checkpoints held back by a running backup; the checkpoint worker catches up when it ends", { stalledMs, walBytes: wal });
|
|
1023
|
+
return;
|
|
1024
|
+
}
|
|
1025
|
+
if (stalled) {
|
|
1026
|
+
this.setAutocheckpoint(true);
|
|
1027
|
+
this.warnOnce("relay checkpoint worker stalled; autocheckpoint re-enabled, restarting the worker", { stalledMs, walBytes: wal });
|
|
1028
|
+
const old = this.checkpointer;
|
|
1029
|
+
this.checkpointer = undefined;
|
|
1030
|
+
if (old) {
|
|
1031
|
+
old.removeAllListeners();
|
|
1032
|
+
void old.terminate();
|
|
1033
|
+
}
|
|
1034
|
+
this.startCheckpointer();
|
|
1035
|
+
}
|
|
1036
|
+
else if (wal > limit) {
|
|
1037
|
+
// Checkpoints run but can't keep up (or a reader pins the WAL): let
|
|
1038
|
+
// commits checkpoint too until it is back under the limit.
|
|
1039
|
+
this.setAutocheckpoint(true);
|
|
1040
|
+
this.warnOnce("relay WAL over its limit; autocheckpoint re-enabled", { walBytes: wal, walLimitBytes: limit });
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
/** For tests: the worker's identity and whether autocheckpoint is on. */
|
|
1044
|
+
checkpointState() {
|
|
1045
|
+
return { worker: this.checkpointer, autocheckpoint: this.autocheckpointOn };
|
|
1046
|
+
}
|
|
1047
|
+
close() {
|
|
1048
|
+
if (this.closed)
|
|
1049
|
+
return;
|
|
1050
|
+
this.closed = true;
|
|
1051
|
+
if (this.watchdog)
|
|
1052
|
+
clearInterval(this.watchdog);
|
|
1053
|
+
const w = this.checkpointer;
|
|
1054
|
+
this.checkpointer = undefined;
|
|
1055
|
+
if (w) {
|
|
1056
|
+
w.removeAllListeners("exit");
|
|
1057
|
+
w.removeAllListeners("error");
|
|
1058
|
+
// Close the worker's connection first, synchronously, so this
|
|
1059
|
+
// connection is the last one: its close then checkpoints and removes
|
|
1060
|
+
// the WAL itself, and nothing touches the files after close() returns.
|
|
1061
|
+
w.postMessage("stop");
|
|
1062
|
+
if (this.checkpointerFlags)
|
|
1063
|
+
Atomics.wait(this.checkpointerFlags, 0, 0, 2000);
|
|
1064
|
+
void w.terminate();
|
|
1065
|
+
}
|
|
1066
|
+
this.db.close();
|
|
1067
|
+
}
|
|
1068
|
+
}
|