@ipab/ipfs-store 0.1.0-rc.5 → 0.1.0-rc.7

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/dist/retention.js CHANGED
@@ -29,16 +29,23 @@ export class Retention {
29
29
  db;
30
30
  mutexPath;
31
31
  queueKey;
32
+ singleProcessCoordination;
33
+ onCoordinationEvent;
34
+ onSqlEvent;
32
35
  pending = new Set();
33
36
  closed = false;
34
- constructor(directory, port) {
37
+ constructor(directory, port, options = {}) {
35
38
  this.port = port;
36
39
  this.Database = createRequire(import.meta.url)("node:sqlite").DatabaseSync;
40
+ this.singleProcessCoordination = options.singleProcessCoordination ?? false;
41
+ this.onCoordinationEvent = options.onCoordinationEvent;
42
+ this.onSqlEvent = options.onSqlEvent;
37
43
  mkdirSync(directory, { recursive: true });
38
44
  this.db = new this.Database(join(directory, "retention.sqlite"));
39
45
  this.mutexPath = join(directory, "mutex.sqlite");
40
46
  this.queueKey = queueKeyFor(this.mutexPath);
41
- this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
47
+ this
48
+ .execSql(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
42
49
  CREATE TABLE IF NOT EXISTS owners (id TEXT PRIMARY KEY, roots TEXT NOT NULL);
43
50
  CREATE TABLE IF NOT EXISTS stages (id TEXT NOT NULL, cid TEXT NOT NULL, PRIMARY KEY(id,cid));
44
51
  CREATE TABLE IF NOT EXISTS intents (
@@ -49,15 +56,71 @@ export class Retention {
49
56
  id TEXT NOT NULL, cid TEXT NOT NULL, count INTEGER NOT NULL CHECK(count>0), PRIMARY KEY(id,cid));
50
57
  CREATE TABLE IF NOT EXISTS direct_pins (cid TEXT PRIMARY KEY, phase TEXT NOT NULL);`);
51
58
  }
59
+ emitCoordination(event) {
60
+ try {
61
+ this.onCoordinationEvent?.(event);
62
+ }
63
+ catch {
64
+ // Telemetry callbacks must never disrupt retention coordination.
65
+ }
66
+ }
67
+ emitSql(event) {
68
+ try {
69
+ this.onSqlEvent?.(event);
70
+ }
71
+ catch {
72
+ // Telemetry callbacks must never disrupt retention SQL.
73
+ }
74
+ }
75
+ measureSql(op, sql, action) {
76
+ if (!this.onSqlEvent)
77
+ return action();
78
+ const startedAt = performance.now();
79
+ const normalized = sql.replace(/\s+/g, " ").trim();
80
+ try {
81
+ const result = action();
82
+ this.emitSql({
83
+ db: "retention",
84
+ op,
85
+ sql: normalized,
86
+ durationMs: performance.now() - startedAt,
87
+ });
88
+ return result;
89
+ }
90
+ catch (error) {
91
+ this.emitSql({
92
+ db: "retention",
93
+ op,
94
+ sql: normalized,
95
+ durationMs: performance.now() - startedAt,
96
+ error: error instanceof Error ? error.message : String(error),
97
+ });
98
+ throw error;
99
+ }
100
+ }
101
+ execSql(sql) {
102
+ this.measureSql("exec", sql, () => {
103
+ this.db.exec(sql);
104
+ });
105
+ }
106
+ queryGet(sql, ...params) {
107
+ return this.measureSql("get", sql, () => this.db.prepare(sql).get(...params));
108
+ }
109
+ queryAll(sql, ...params) {
110
+ return this.measureSql("all", sql, () => this.db.prepare(sql).all(...params));
111
+ }
112
+ queryRun(sql, ...params) {
113
+ this.measureSql("run", sql, () => {
114
+ this.db.prepare(sql).run(...params);
115
+ });
116
+ }
52
117
  roots(values) {
53
118
  return [
54
119
  ...new Set(values.map((value) => CID.parse(value).toV1().toString())),
55
120
  ].sort();
56
121
  }
57
122
  readOwner(owner, table = "owners") {
58
- const row = this.db
59
- .prepare(`SELECT roots FROM ${table} WHERE id=?`)
60
- .get(owner);
123
+ const row = this.queryGet(`SELECT roots FROM ${table} WHERE id=?`, owner);
61
124
  if (!row)
62
125
  return [];
63
126
  const roots = JSON.parse(String(row.roots));
@@ -69,23 +132,23 @@ export class Retention {
69
132
  if (typeof owner !== "string" || !owner || owner.length > 4096)
70
133
  throw new Error("A stable retention owner is required.");
71
134
  const values = this.roots(replace ? roots : [...this.readOwner(owner, table), ...roots]);
72
- this.db
73
- .prepare(`INSERT INTO ${table} VALUES (?,?)
135
+ this.queryRun(`INSERT INTO ${table} VALUES (?,?)
74
136
  ON CONFLICT(id) DO UPDATE SET roots=excluded.roots
75
- WHERE ${table}.roots<>excluded.roots`)
76
- .run(owner, JSON.stringify(values));
137
+ WHERE ${table}.roots<>excluded.roots`, owner, JSON.stringify(values));
77
138
  }
78
139
  transaction(action) {
79
- this.db.exec("BEGIN IMMEDIATE");
80
- try {
81
- const result = action();
82
- this.db.exec("COMMIT");
83
- return result;
84
- }
85
- catch (error) {
86
- this.db.exec("ROLLBACK");
87
- throw error;
88
- }
140
+ return this.measureSql("tx", "BEGIN IMMEDIATE ... COMMIT", () => {
141
+ this.db.exec("BEGIN IMMEDIATE");
142
+ try {
143
+ const result = action();
144
+ this.db.exec("COMMIT");
145
+ return result;
146
+ }
147
+ catch (error) {
148
+ this.db.exec("ROLLBACK");
149
+ throw error;
150
+ }
151
+ });
89
152
  }
90
153
  begin(mutex) {
91
154
  if (this.closed)
@@ -93,22 +156,51 @@ export class Retention {
93
156
  mutex.exec("BEGIN IMMEDIATE");
94
157
  }
95
158
  register(owner, roots) {
96
- this.registerInTable(owner, roots, "owners");
159
+ this.registerInTable("register", owner, roots, "owners");
97
160
  }
98
161
  registerDirect(owner, roots) {
99
- this.registerInTable(owner, roots, "direct_owners");
162
+ this.registerInTable("registerDirect", owner, roots, "direct_owners");
100
163
  }
101
164
  registerAsync(owner, roots, signal) {
102
- return this.locked(signal, () => {
103
- this.publish(owner, roots, false, "owners");
165
+ return this.locked("registerAsync", signal, () => {
166
+ this.transaction(() => {
167
+ this.publish(owner, roots, false, "owners");
168
+ });
104
169
  });
105
170
  }
106
171
  registerDirectAsync(owner, roots, signal) {
107
- return this.locked(signal, () => {
108
- this.publish(owner, roots, false, "direct_owners");
172
+ return this.locked("registerDirectAsync", signal, () => {
173
+ this.transaction(() => {
174
+ this.publish(owner, roots, false, "direct_owners");
175
+ });
109
176
  });
110
177
  }
111
- registerInTable(owner, roots, table) {
178
+ registerInTable(op, owner, roots, table) {
179
+ if (this.singleProcessCoordination) {
180
+ if (this.closed || coordinationQueues.has(this.queueKey))
181
+ throw new ContentError("retention_unfinished", "Retention coordination is unavailable; retry.");
182
+ const holdStart = performance.now();
183
+ let errorMessage;
184
+ try {
185
+ this.transaction(() => {
186
+ this.publish(owner, roots, false, table);
187
+ });
188
+ }
189
+ catch (error) {
190
+ errorMessage = error instanceof Error ? error.message : String(error);
191
+ throw error;
192
+ }
193
+ finally {
194
+ this.emitCoordination({
195
+ op,
196
+ phase: "hold",
197
+ durationMs: performance.now() - holdStart,
198
+ ...(errorMessage !== undefined ? { error: errorMessage } : {}),
199
+ });
200
+ }
201
+ return;
202
+ }
203
+ const waitStart = performance.now();
112
204
  const mutex = new this.Database(this.mutexPath);
113
205
  mutex.exec("PRAGMA busy_timeout=0");
114
206
  try {
@@ -116,26 +208,64 @@ export class Retention {
116
208
  }
117
209
  catch {
118
210
  mutex.close();
211
+ this.emitCoordination({
212
+ op,
213
+ phase: "wait",
214
+ durationMs: performance.now() - waitStart,
215
+ error: "Retention coordination is unavailable; retry.",
216
+ });
119
217
  throw new ContentError("retention_unfinished", "Retention coordination is unavailable; retry.");
120
218
  }
219
+ this.emitCoordination({
220
+ op,
221
+ phase: "wait",
222
+ durationMs: performance.now() - waitStart,
223
+ });
224
+ const holdStart = performance.now();
225
+ let errorMessage;
121
226
  try {
122
227
  this.publish(owner, roots, false, table);
123
228
  }
229
+ catch (error) {
230
+ errorMessage = error instanceof Error ? error.message : String(error);
231
+ throw error;
232
+ }
124
233
  finally {
125
234
  mutex.exec("ROLLBACK");
126
235
  mutex.close();
236
+ this.emitCoordination({
237
+ op,
238
+ phase: "hold",
239
+ durationMs: performance.now() - holdStart,
240
+ ...(errorMessage !== undefined ? { error: errorMessage } : {}),
241
+ });
127
242
  }
128
243
  }
129
- async locked(signal, action) {
130
- const operation = this.lock(signal, action);
244
+ track(operation) {
131
245
  this.pending.add(operation);
132
246
  void operation
133
247
  .finally(() => this.pending.delete(operation))
134
248
  .catch(() => { });
135
249
  return operation;
136
250
  }
137
- async lock(signal, action) {
251
+ wrapUnfinished(error, signal) {
252
+ if (signal?.aborted)
253
+ throw signal.reason;
254
+ if (error instanceof ContentError && error.code === "retention_unfinished")
255
+ throw error;
256
+ throw new ContentError("retention_unfinished", `Retention hints are unfinished; durable intents remain for retry. ${error instanceof ContentError
257
+ ? `${error.code}: ${error.message}`
258
+ : error instanceof Error &&
259
+ ["TimeoutError", "AbortError"].includes(error.name)
260
+ ? error.name
261
+ : "verification_or_storage_failure"}`, { cause: error });
262
+ }
263
+ locked(op, signal, action) {
264
+ return this.track(this.lock(op, signal, action));
265
+ }
266
+ async lock(op, signal, action) {
138
267
  signal?.throwIfAborted();
268
+ const waitStart = performance.now();
139
269
  const previous = coordinationQueues.get(this.queueKey) ?? Promise.resolve();
140
270
  let releaseTurn;
141
271
  const current = new Promise((resolveTurn) => {
@@ -143,20 +273,61 @@ export class Retention {
143
273
  });
144
274
  const tail = previous.then(() => current);
145
275
  coordinationQueues.set(this.queueKey, tail);
146
- const release = () => {
147
- releaseTurn();
276
+ void tail.finally(() => {
148
277
  if (coordinationQueues.get(this.queueKey) === tail) {
149
278
  coordinationQueues.delete(this.queueKey);
150
279
  }
280
+ });
281
+ const release = () => {
282
+ releaseTurn();
151
283
  };
152
284
  try {
153
285
  await waitForTurn(previous, signal);
154
286
  }
155
287
  catch (error) {
156
288
  release();
289
+ this.emitCoordination({
290
+ op,
291
+ phase: "wait",
292
+ durationMs: performance.now() - waitStart,
293
+ error: error instanceof Error ? error.message : String(error),
294
+ });
157
295
  throw error;
158
296
  }
159
297
  try {
298
+ if (this.singleProcessCoordination) {
299
+ if (this.closed) {
300
+ this.emitCoordination({
301
+ op,
302
+ phase: "wait",
303
+ durationMs: performance.now() - waitStart,
304
+ error: "Retention coordination is unavailable.",
305
+ });
306
+ throw new ContentError("retention_unfinished", "Retention coordination is unavailable.");
307
+ }
308
+ this.emitCoordination({
309
+ op,
310
+ phase: "wait",
311
+ durationMs: performance.now() - waitStart,
312
+ });
313
+ const holdStart = performance.now();
314
+ let holdError;
315
+ try {
316
+ return await action();
317
+ }
318
+ catch (error) {
319
+ holdError = error instanceof Error ? error.message : String(error);
320
+ return this.wrapUnfinished(error, signal);
321
+ }
322
+ finally {
323
+ this.emitCoordination({
324
+ op,
325
+ phase: "hold",
326
+ durationMs: performance.now() - holdStart,
327
+ ...(holdError !== undefined ? { error: holdError } : {}),
328
+ });
329
+ }
330
+ }
160
331
  const mutex = new this.Database(this.mutexPath);
161
332
  mutex.exec("PRAGMA busy_timeout=0");
162
333
  const deadline = Date.now() + 30_000;
@@ -177,174 +348,362 @@ export class Retention {
177
348
  }
178
349
  catch (error) {
179
350
  mutex.close();
351
+ this.emitCoordination({
352
+ op,
353
+ phase: "wait",
354
+ durationMs: performance.now() - waitStart,
355
+ error: error instanceof Error ? error.message : String(error),
356
+ });
180
357
  signal?.throwIfAborted();
181
358
  throw error;
182
359
  }
360
+ this.emitCoordination({
361
+ op,
362
+ phase: "wait",
363
+ durationMs: performance.now() - waitStart,
364
+ });
365
+ const holdStart = performance.now();
366
+ let holdError;
183
367
  try {
184
368
  return await action();
185
369
  }
186
370
  catch (error) {
187
- if (signal?.aborted)
188
- throw signal.reason;
189
- throw new ContentError("retention_unfinished", `Retention hints are unfinished; durable intents remain for retry. ${error instanceof ContentError
190
- ? `${error.code}: ${error.message}`
191
- : error instanceof Error &&
192
- ["TimeoutError", "AbortError"].includes(error.name)
193
- ? error.name
194
- : "verification_or_storage_failure"}`, { cause: error });
371
+ holdError = error instanceof Error ? error.message : String(error);
372
+ return this.wrapUnfinished(error, signal);
195
373
  }
196
374
  finally {
197
375
  mutex.exec("ROLLBACK");
198
376
  mutex.close();
377
+ this.emitCoordination({
378
+ op,
379
+ phase: "hold",
380
+ durationMs: performance.now() - holdStart,
381
+ ...(holdError !== undefined ? { error: holdError } : {}),
382
+ });
199
383
  }
200
384
  }
201
385
  finally {
202
386
  release();
203
387
  }
204
388
  }
389
+ pinPhase(root, table = "pins") {
390
+ const row = this.queryGet(`SELECT phase FROM ${table} WHERE cid=?`, root);
391
+ return row ? String(row.phase) : undefined;
392
+ }
393
+ pinPhases(table) {
394
+ const phases = new Map();
395
+ for (const row of this.queryAll(`SELECT cid, phase FROM ${table}`)) {
396
+ phases.set(String(row.cid), String(row.phase));
397
+ }
398
+ return phases;
399
+ }
205
400
  phase(root, phase, table = "pins") {
206
- this.db
207
- .prepare(`INSERT OR REPLACE INTO ${table} VALUES (?,?)`)
208
- .run(root, phase);
209
- }
210
- async ensure(root, signal) {
211
- this.phase(root, "pin-pending");
212
- await this.port.prepare(root, signal);
213
- this.phase(root, "pinned");
214
- }
215
- async ensureDirect(root, signal) {
216
- this.phase(root, "pin-pending", "direct_pins");
217
- await (this.port.prepareDirect
218
- ? this.port.prepareDirect(root, signal)
219
- : this.port.prepare(root, signal));
220
- this.phase(root, "pinned", "direct_pins");
221
- }
222
- pin(root, signal) {
223
- root = this.roots([root])[0];
224
- return this.locked(signal, () => this.ensure(root, signal));
401
+ this.queryRun(`INSERT OR REPLACE INTO ${table} VALUES (?,?)`, root, phase);
402
+ }
403
+ async runPrepare(op, root, signal, port, direct) {
404
+ const activePort = port ?? this.port;
405
+ const startedAt = performance.now();
406
+ let errorMessage;
407
+ try {
408
+ signal?.throwIfAborted();
409
+ if (direct && activePort.prepareDirect) {
410
+ await activePort.prepareDirect(root, signal);
411
+ }
412
+ else {
413
+ await activePort.prepare(root, signal);
414
+ }
415
+ }
416
+ catch (error) {
417
+ errorMessage = error instanceof Error ? error.message : String(error);
418
+ this.wrapUnfinished(error, signal);
419
+ }
420
+ finally {
421
+ this.emitCoordination({
422
+ op,
423
+ phase: "prepare",
424
+ durationMs: performance.now() - startedAt,
425
+ ...(errorMessage !== undefined ? { error: errorMessage } : {}),
426
+ });
427
+ }
225
428
  }
226
- pinDirect(root, signal) {
429
+ pin(root, signal, port) {
227
430
  root = this.roots([root])[0];
228
- return this.locked(signal, () => this.ensureDirect(root, signal));
431
+ return this.track((async () => {
432
+ await this.lock("pin", signal, () => {
433
+ this.transaction(() => {
434
+ this.phase(root, "pin-pending", "pins");
435
+ });
436
+ });
437
+ await this.runPrepare("pin", root, signal, port, false);
438
+ await this.lock("pin", signal, () => {
439
+ this.transaction(() => {
440
+ if (this.pinPhase(root, "pins") !== undefined) {
441
+ this.phase(root, "pinned", "pins");
442
+ }
443
+ });
444
+ });
445
+ })());
229
446
  }
230
- retain(owner, roots, signal) {
231
- return this.locked(signal, async () => {
232
- this.transaction(() => {
233
- this.publish(owner, roots);
234
- for (const root of this.roots(roots))
235
- this.intent(owner, root);
447
+ pinDirect(root, signal, port) {
448
+ root = this.roots([root])[0];
449
+ return this.track((async () => {
450
+ await this.lock("pinDirect", signal, () => {
451
+ this.transaction(() => {
452
+ this.phase(root, "pin-pending", "direct_pins");
453
+ });
236
454
  });
237
- for (const root of this.roots(roots))
238
- await this.ensure(root, signal);
239
- });
455
+ await this.runPrepare("pinDirect", root, signal, port, true);
456
+ await this.lock("pinDirect", signal, () => {
457
+ this.transaction(() => {
458
+ if (this.pinPhase(root, "direct_pins") !== undefined) {
459
+ this.phase(root, "pinned", "direct_pins");
460
+ }
461
+ });
462
+ });
463
+ })());
240
464
  }
241
- retainDirect(owner, roots, signal) {
242
- return this.locked(signal, async () => {
243
- this.transaction(() => {
244
- this.publish(owner, roots, false, "direct_owners");
245
- for (const root of this.roots(roots))
246
- this.intent(owner, root, "direct_intents");
465
+ retain(owner, roots, signal, port) {
466
+ return this.retainInTable("retain", owner, roots, "owners", "intents", "pins", false, signal, port);
467
+ }
468
+ retainDirect(owner, roots, signal, port) {
469
+ return this.retainInTable("retainDirect", owner, roots, "direct_owners", "direct_intents", "direct_pins", true, signal, port);
470
+ }
471
+ retainInTable(op, owner, roots, ownerTable, intentTable, pinTable, direct, signal, port) {
472
+ return this.track((async () => {
473
+ const normalized = await this.lock(op, signal, () => {
474
+ const unique = this.roots(roots);
475
+ this.transaction(() => {
476
+ this.publish(owner, unique, false, ownerTable);
477
+ for (const root of unique) {
478
+ this.intent(owner, root, intentTable);
479
+ if (this.pinPhase(root, pinTable) !== "pinned") {
480
+ this.phase(root, "pin-pending", pinTable);
481
+ }
482
+ }
483
+ });
484
+ return unique;
247
485
  });
248
- for (const root of this.roots(roots))
249
- await this.ensureDirect(root, signal);
250
- });
486
+ for (const root of normalized) {
487
+ await this.runPrepare(op, root, signal, port, direct);
488
+ }
489
+ if (normalized.length === 0)
490
+ return;
491
+ await this.lock(op, signal, () => {
492
+ this.transaction(() => {
493
+ const referenced = new Set(direct ? this.allDirectRoots() : this.allRoots());
494
+ for (const root of normalized) {
495
+ if (referenced.has(root)) {
496
+ this.phase(root, "pinned", pinTable);
497
+ }
498
+ }
499
+ });
500
+ });
501
+ })());
251
502
  }
252
503
  confirm(owner, roots, signal) {
253
- return this.confirmInTable(owner, roots, "owners", "intents", signal);
504
+ return this.confirmInTable("confirm", owner, roots, "owners", "intents", signal);
254
505
  }
255
506
  confirmDirect(owner, roots, signal) {
256
- return this.confirmInTable(owner, roots, "direct_owners", "direct_intents", signal);
507
+ return this.confirmInTable("confirmDirect", owner, roots, "direct_owners", "direct_intents", signal);
257
508
  }
258
- confirmInTable(owner, roots, ownerTable, intentTable, signal) {
259
- return this.locked(signal, () => {
509
+ decrementIntent(owner, root, intentTable = "intents") {
510
+ const row = this.queryGet(`SELECT count FROM ${intentTable} WHERE id=? AND cid=?`, owner, root);
511
+ if (row && Number(row.count) > 1)
512
+ this.queryRun(`UPDATE ${intentTable} SET count=count-1 WHERE id=? AND cid=?`, owner, root);
513
+ else
514
+ this.queryRun(`DELETE FROM ${intentTable} WHERE id=? AND cid=?`, owner, root);
515
+ }
516
+ confirmInTable(op, owner, roots, ownerTable, intentTable, signal) {
517
+ return this.locked(op, signal, () => {
260
518
  this.transaction(() => {
261
519
  this.publish(owner, roots, false, ownerTable);
262
520
  for (const root of this.roots(roots)) {
263
- const row = this.db
264
- .prepare(`SELECT count FROM ${intentTable} WHERE id=? AND cid=?`)
265
- .get(owner, root);
266
- if (row && Number(row.count) > 1)
267
- this.db
268
- .prepare(`UPDATE ${intentTable} SET count=count-1 WHERE id=? AND cid=?`)
269
- .run(owner, root);
270
- else
271
- this.db
272
- .prepare(`DELETE FROM ${intentTable} WHERE id=? AND cid=?`)
273
- .run(owner, root);
521
+ this.decrementIntent(owner, root, intentTable);
274
522
  }
275
523
  });
276
524
  });
277
525
  }
278
526
  intent(owner, root, table = "intents") {
279
- this.db
280
- .prepare(`INSERT INTO ${table} VALUES (?,?,1)
281
- ON CONFLICT(id,cid) DO UPDATE SET count=count+1`)
282
- .run(owner, root);
527
+ this.queryRun(`INSERT INTO ${table} VALUES (?,?,1)
528
+ ON CONFLICT(id,cid) DO UPDATE SET count=count+1`, owner, root);
283
529
  }
284
530
  discard(session, signal) {
285
- return this.locked(signal, () => {
286
- this.db.prepare("DELETE FROM stages WHERE id=?").run(session);
531
+ return this.locked("discard", signal, () => {
532
+ this.queryRun("DELETE FROM stages WHERE id=?", session);
287
533
  });
288
534
  }
289
535
  recover(owner, roots, signal, isIdle) {
290
- return this.locked(signal, () => {
536
+ return this.locked("recover", signal, () => {
291
537
  if (isIdle && !isIdle())
292
538
  return;
293
539
  this.transaction(() => {
294
540
  this.publish(owner, typeof roots === "function" ? roots() : roots, true);
295
- this.db.prepare("DELETE FROM intents WHERE id=?").run(owner);
296
- for (const row of this.db
297
- .prepare("SELECT DISTINCT id FROM stages")
298
- .all())
541
+ this.queryRun("DELETE FROM intents WHERE id=?", owner);
542
+ for (const row of this.queryAll("SELECT DISTINCT id FROM stages"))
299
543
  if (String(row.id).startsWith(`${owner}/`))
300
- this.db
301
- .prepare("DELETE FROM stages WHERE id=?")
302
- .run(String(row.id));
544
+ this.queryRun("DELETE FROM stages WHERE id=?", String(row.id));
303
545
  });
304
546
  });
305
547
  }
306
- stage(session, root, write, signal) {
307
- root = this.roots([root])[0];
308
- return this.locked(signal, async () => {
309
- const alreadyPinned = this.db.prepare("SELECT phase FROM pins WHERE cid=?").get(root)
310
- ?.phase === "pinned";
548
+ async stageEntriesUnlocked(op, session, entries, signal) {
549
+ signal?.throwIfAborted();
550
+ if (entries.length === 0) {
551
+ return { uniqueRoots: [], alreadyPinned: new Set() };
552
+ }
553
+ const uniqueRoots = [...new Set(entries.map((entry) => entry.root))];
554
+ const alreadyPinned = await this.lock(op, signal, () => {
555
+ const pinned = new Set();
311
556
  this.transaction(() => {
312
- this.db
313
- .prepare("INSERT OR IGNORE INTO stages VALUES (?,?)")
314
- .run(session, root);
315
- this.phase(root, "stage-pending");
557
+ for (const root of uniqueRoots) {
558
+ if (this.pinPhase(root, "pins") === "pinned") {
559
+ pinned.add(root);
560
+ }
561
+ }
562
+ for (const root of uniqueRoots) {
563
+ this.queryRun("INSERT OR IGNORE INTO stages VALUES (?,?)", session, root);
564
+ if (!pinned.has(root)) {
565
+ this.phase(root, "stage-pending");
566
+ }
567
+ }
316
568
  });
317
- await write();
318
- this.phase(root, alreadyPinned ? "pinned" : "staged");
569
+ return pinned;
319
570
  });
571
+ const written = new Set();
572
+ try {
573
+ for (const entry of entries) {
574
+ signal?.throwIfAborted();
575
+ written.delete(entry.root);
576
+ await entry.write();
577
+ written.add(entry.root);
578
+ }
579
+ }
580
+ catch (error) {
581
+ if (written.size > 0) {
582
+ await this.lock(`${op}:rollback`, undefined, () => {
583
+ this.transaction(() => {
584
+ for (const root of written) {
585
+ if (!alreadyPinned.has(root)) {
586
+ if (this.pinPhase(root, "pins") !== "pinned") {
587
+ this.phase(root, "staged");
588
+ }
589
+ }
590
+ }
591
+ });
592
+ }).catch(() => { });
593
+ }
594
+ this.wrapUnfinished(error, signal);
595
+ }
596
+ return { uniqueRoots, alreadyPinned };
320
597
  }
321
- finish(session, root, owner, signal) {
598
+ stage(session, root, write, signal) {
322
599
  root = this.roots([root])[0];
323
- return this.locked(signal, async () => {
324
- if (owner) {
600
+ return this.stageBatchInternal("stage", session, [{ root, write }], signal);
601
+ }
602
+ stageBatch(session, entries, signal) {
603
+ const normalized = entries.map((entry) => ({
604
+ root: this.roots([entry.cid])[0],
605
+ write: entry.write,
606
+ }));
607
+ return this.stageBatchInternal("stageBatch", session, normalized, signal);
608
+ }
609
+ stageBatchInternal(op, session, entries, signal) {
610
+ return this.track((async () => {
611
+ const { uniqueRoots, alreadyPinned } = await this.stageEntriesUnlocked(op, session, entries, signal);
612
+ if (uniqueRoots.length === 0)
613
+ return;
614
+ await this.lock(op, signal, () => {
325
615
  this.transaction(() => {
326
- this.publish(owner, [root]);
327
- this.intent(owner, root);
616
+ for (const root of uniqueRoots) {
617
+ if (!alreadyPinned.has(root) &&
618
+ this.pinPhase(root, "pins") !== "pinned") {
619
+ this.phase(root, "staged");
620
+ }
621
+ }
328
622
  });
329
- }
330
- await this.ensure(root, signal);
331
- this.db.prepare("DELETE FROM stages WHERE id=?").run(session);
332
- });
623
+ });
624
+ })());
625
+ }
626
+ finish(session, root, owner, signal, port) {
627
+ root = this.roots([root])[0];
628
+ return this.track((async () => {
629
+ await this.lock("finish", signal, () => {
630
+ this.transaction(() => {
631
+ if (owner) {
632
+ this.publish(owner, [root]);
633
+ this.intent(owner, root);
634
+ }
635
+ if (this.pinPhase(root, "pins") !== "pinned") {
636
+ this.phase(root, "pin-pending");
637
+ }
638
+ });
639
+ });
640
+ await this.runPrepare("finish", root, signal, port, false);
641
+ await this.lock("finish", signal, () => {
642
+ this.transaction(() => {
643
+ if (!owner || this.allRoots().includes(root)) {
644
+ this.phase(root, "pinned");
645
+ }
646
+ this.queryRun("DELETE FROM stages WHERE id=?", session);
647
+ });
648
+ });
649
+ })());
650
+ }
651
+ importBatch(session, entries, root, owner, signal, onRetained, port) {
652
+ root = this.roots([root])[0];
653
+ const normalized = entries.map((entry) => ({
654
+ root: this.roots([entry.cid])[0],
655
+ write: entry.write,
656
+ }));
657
+ return this.track((async () => {
658
+ const { uniqueRoots, alreadyPinned } = await this.stageEntriesUnlocked("importBatch", session, normalized, signal);
659
+ signal?.throwIfAborted();
660
+ await this.lock("importBatch", signal, () => {
661
+ this.transaction(() => {
662
+ for (const stagedRoot of uniqueRoots) {
663
+ if (!alreadyPinned.has(stagedRoot) &&
664
+ this.pinPhase(stagedRoot, "pins") !== "pinned") {
665
+ this.phase(stagedRoot, "staged");
666
+ }
667
+ }
668
+ if (owner) {
669
+ this.publish(owner, [root]);
670
+ this.intent(owner, root);
671
+ }
672
+ if (this.pinPhase(root, "pins") !== "pinned") {
673
+ this.phase(root, "pin-pending");
674
+ }
675
+ });
676
+ });
677
+ await this.runPrepare("importBatch", root, signal, port, false);
678
+ await this.lock("importBatch", signal, async () => {
679
+ this.transaction(() => {
680
+ if (!owner || this.allRoots().includes(root)) {
681
+ this.phase(root, "pinned");
682
+ }
683
+ this.queryRun("DELETE FROM stages WHERE id=?", session);
684
+ });
685
+ if (owner && onRetained) {
686
+ signal?.throwIfAborted();
687
+ await onRetained();
688
+ this.transaction(() => {
689
+ this.decrementIntent(owner, root);
690
+ });
691
+ }
692
+ });
693
+ })());
333
694
  }
334
695
  remove(root, signal, table = "pins") {
335
- const record = this.db
336
- .prepare(`SELECT phase FROM ${table} WHERE cid=?`)
337
- .get(root);
696
+ const record = this.queryGet(`SELECT phase FROM ${table} WHERE cid=?`, root);
338
697
  if (!record)
339
698
  return false;
340
699
  this.phase(root, "unpin-pending", table);
341
700
  signal?.throwIfAborted();
342
- this.db.prepare(`DELETE FROM ${table} WHERE cid=?`).run(root);
701
+ this.queryRun(`DELETE FROM ${table} WHERE cid=?`, root);
343
702
  return true;
344
703
  }
345
704
  unpin(root, signal) {
346
705
  root = this.roots([root])[0];
347
- return this.locked(signal, () => {
706
+ return this.locked("unpin", signal, () => {
348
707
  if (this.allRoots().includes(root))
349
708
  throw new Error("A participating owner still retains this root.");
350
709
  this.remove(root, signal);
@@ -352,7 +711,7 @@ export class Retention {
352
711
  }
353
712
  unpinDirect(root, signal) {
354
713
  root = this.roots([root])[0];
355
- return this.locked(signal, () => {
714
+ return this.locked("unpinDirect", signal, () => {
356
715
  if (this.allDirectRoots().includes(root))
357
716
  throw new Error("A participating owner still retains this direct block.");
358
717
  this.remove(root, signal, "direct_pins");
@@ -360,112 +719,97 @@ export class Retention {
360
719
  }
361
720
  allRoots() {
362
721
  return this.roots([
363
- ...this.db
364
- .prepare("SELECT id FROM owners")
365
- .all()
366
- .flatMap((row) => this.readOwner(String(row.id))),
367
- ...this.db
368
- .prepare("SELECT cid FROM intents")
369
- .all()
370
- .map((row) => String(row.cid)),
371
- ...this.db
372
- .prepare("SELECT cid FROM stages")
373
- .all()
374
- .map((row) => String(row.cid)),
722
+ ...this.queryAll("SELECT id FROM owners").flatMap((row) => this.readOwner(String(row.id))),
723
+ ...this.queryAll("SELECT cid FROM intents").map((row) => String(row.cid)),
724
+ ...this.queryAll("SELECT cid FROM stages").map((row) => String(row.cid)),
375
725
  ]);
376
726
  }
377
727
  allDirectRoots() {
378
728
  return this.roots([
379
- ...this.db
380
- .prepare("SELECT id FROM direct_owners")
381
- .all()
382
- .flatMap((row) => this.readOwner(String(row.id), "direct_owners")),
383
- ...this.db
384
- .prepare("SELECT cid FROM direct_intents")
385
- .all()
386
- .map((row) => String(row.cid)),
729
+ ...this.queryAll("SELECT id FROM direct_owners").flatMap((row) => this.readOwner(String(row.id), "direct_owners")),
730
+ ...this.queryAll("SELECT cid FROM direct_intents").map((row) => String(row.cid)),
387
731
  ]);
388
732
  }
389
- reconcile(owner, roots, signal) {
390
- return this.locked(signal, async () => {
391
- this.publish(owner, typeof roots === "function" ? roots() : roots, true);
392
- const marked = new Set(this.allRoots());
393
- // Complete the entire mark before removing any hint. Recheck real blocks, not reader caches.
394
- for (const root of marked)
395
- await this.ensure(root, signal);
396
- let removed = 0;
397
- for (const row of this.db.prepare("SELECT cid FROM pins").all()) {
398
- const root = String(row.cid);
399
- if (!marked.has(root) && this.remove(root, signal))
400
- removed++;
401
- }
402
- return removed;
403
- });
404
- }
405
- reconcileDirect(owner, roots, signal) {
406
- return this.locked(signal, async () => {
407
- this.publish(owner, typeof roots === "function" ? roots() : roots, true, "direct_owners");
408
- const marked = new Set(this.allDirectRoots());
409
- for (const root of marked)
410
- await this.ensureDirect(root, signal);
411
- let removed = 0;
412
- for (const row of this.db.prepare("SELECT cid FROM direct_pins").all()) {
413
- const root = String(row.cid);
414
- if (!marked.has(root) && this.remove(root, signal, "direct_pins"))
415
- removed++;
733
+ reconcile(owner, roots, signal, port) {
734
+ return this.reconcileInTable("reconcile", owner, roots, "owners", "pins", false, signal, port);
735
+ }
736
+ reconcileDirect(owner, roots, signal, port) {
737
+ return this.reconcileInTable("reconcileDirect", owner, roots, "direct_owners", "direct_pins", true, signal, port);
738
+ }
739
+ reconcileInTable(op, owner, roots, ownerTable, pinTable, direct, signal, port) {
740
+ return this.track((async () => {
741
+ const phase1 = await this.lock(op, signal, () => {
742
+ return this.transaction(() => {
743
+ this.publish(owner, typeof roots === "function" ? roots() : roots, true, ownerTable);
744
+ const marked = direct ? this.allDirectRoots() : this.allRoots();
745
+ const phases = this.pinPhases(pinTable);
746
+ const toPrepare = marked.filter((root) => {
747
+ const phase = phases.get(root);
748
+ return phase !== "pinned" && phase !== "stage-pending";
749
+ });
750
+ if (toPrepare.length === 0) {
751
+ const referenced = new Set(marked);
752
+ let removed = 0;
753
+ for (const row of this.queryAll(`SELECT cid FROM ${pinTable}`)) {
754
+ const root = String(row.cid);
755
+ if (!referenced.has(root) &&
756
+ this.remove(root, signal, pinTable))
757
+ removed++;
758
+ }
759
+ return { toPrepare, removed };
760
+ }
761
+ for (const root of toPrepare) {
762
+ this.phase(root, "pin-pending", pinTable);
763
+ }
764
+ return { toPrepare, removed: undefined };
765
+ });
766
+ });
767
+ if (phase1.removed !== undefined)
768
+ return phase1.removed;
769
+ for (const root of phase1.toPrepare) {
770
+ await this.runPrepare(op, root, signal, port, direct);
416
771
  }
417
- return removed;
418
- });
772
+ return this.lock(op, signal, () => {
773
+ return this.transaction(() => {
774
+ const referenced = new Set(direct ? this.allDirectRoots() : this.allRoots());
775
+ for (const root of phase1.toPrepare) {
776
+ if (referenced.has(root)) {
777
+ this.phase(root, "pinned", pinTable);
778
+ }
779
+ }
780
+ let removed = 0;
781
+ for (const row of this.queryAll(`SELECT cid FROM ${pinTable}`)) {
782
+ const root = String(row.cid);
783
+ if (!referenced.has(root) && this.remove(root, signal, pinTable))
784
+ removed++;
785
+ }
786
+ return removed;
787
+ });
788
+ });
789
+ })());
419
790
  }
420
791
  pins() {
421
- return this.db
422
- .prepare("SELECT cid FROM pins WHERE phase='pinned' ORDER BY cid")
423
- .all()
424
- .map((row) => String(row.cid));
792
+ return this.queryAll("SELECT cid FROM pins WHERE phase='pinned' ORDER BY cid").map((row) => String(row.cid));
425
793
  }
426
794
  directPins() {
427
- return this.db
428
- .prepare("SELECT cid FROM direct_pins WHERE phase='pinned' ORDER BY cid")
429
- .all()
430
- .map((row) => String(row.cid));
795
+ return this.queryAll("SELECT cid FROM direct_pins WHERE phase='pinned' ORDER BY cid").map((row) => String(row.cid));
431
796
  }
432
797
  maintain(action, signal) {
433
- return this.locked(signal, () => action({
798
+ return this.locked("maintain", signal, () => action({
434
799
  pinned: this.pins(),
435
800
  roots: this.roots([
436
- ...this.db
437
- .prepare("SELECT id FROM owners")
438
- .all()
439
- .flatMap((row) => this.readOwner(String(row.id))),
440
- ...this.db
441
- .prepare("SELECT cid FROM intents")
442
- .all()
443
- .map((row) => String(row.cid)),
444
- ...this.db
445
- .prepare("SELECT cid FROM pins WHERE phase NOT IN ('staged','stage-pending')")
446
- .all()
447
- .map((row) => String(row.cid)),
801
+ ...this.queryAll("SELECT id FROM owners").flatMap((row) => this.readOwner(String(row.id))),
802
+ ...this.queryAll("SELECT cid FROM intents").map((row) => String(row.cid)),
803
+ ...this.queryAll("SELECT cid FROM pins WHERE phase NOT IN ('staged','stage-pending')").map((row) => String(row.cid)),
448
804
  ]),
449
805
  directPinned: this.directPins(),
450
806
  directRoots: this.roots([
451
- ...this.db
452
- .prepare("SELECT id FROM direct_owners")
453
- .all()
454
- .flatMap((row) => this.readOwner(String(row.id), "direct_owners")),
455
- ...this.db
456
- .prepare("SELECT cid FROM direct_intents")
457
- .all()
458
- .map((row) => String(row.cid)),
459
- ...this.db
460
- .prepare("SELECT cid FROM direct_pins WHERE phase NOT IN ('staged','stage-pending')")
461
- .all()
462
- .map((row) => String(row.cid)),
807
+ ...this.queryAll("SELECT id FROM direct_owners").flatMap((row) => this.readOwner(String(row.id), "direct_owners")),
808
+ ...this.queryAll("SELECT cid FROM direct_intents").map((row) => String(row.cid)),
809
+ ...this.queryAll("SELECT cid FROM direct_pins WHERE phase NOT IN ('staged','stage-pending')").map((row) => String(row.cid)),
463
810
  ]),
464
811
  // Import parents may arrive before their children; protect staged blocks individually.
465
- staged: this.db
466
- .prepare("SELECT DISTINCT cid FROM stages")
467
- .all()
468
- .map((row) => String(row.cid)),
812
+ staged: this.queryAll("SELECT DISTINCT cid FROM stages").map((row) => String(row.cid)),
469
813
  }));
470
814
  }
471
815
  async close() {