@ipab/ipfs-store 0.1.0-rc.6 → 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,99 +348,173 @@ 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
509
  decrementIntent(owner, root, intentTable = "intents") {
259
- const row = this.db
260
- .prepare(`SELECT count FROM ${intentTable} WHERE id=? AND cid=?`)
261
- .get(owner, root);
510
+ const row = this.queryGet(`SELECT count FROM ${intentTable} WHERE id=? AND cid=?`, owner, root);
262
511
  if (row && Number(row.count) > 1)
263
- this.db
264
- .prepare(`UPDATE ${intentTable} SET count=count-1 WHERE id=? AND cid=?`)
265
- .run(owner, root);
512
+ this.queryRun(`UPDATE ${intentTable} SET count=count-1 WHERE id=? AND cid=?`, owner, root);
266
513
  else
267
- this.db
268
- .prepare(`DELETE FROM ${intentTable} WHERE id=? AND cid=?`)
269
- .run(owner, root);
514
+ this.queryRun(`DELETE FROM ${intentTable} WHERE id=? AND cid=?`, owner, root);
270
515
  }
271
- confirmInTable(owner, roots, ownerTable, intentTable, signal) {
272
- return this.locked(signal, () => {
516
+ confirmInTable(op, owner, roots, ownerTable, intentTable, signal) {
517
+ return this.locked(op, signal, () => {
273
518
  this.transaction(() => {
274
519
  this.publish(owner, roots, false, ownerTable);
275
520
  for (const root of this.roots(roots)) {
@@ -279,146 +524,186 @@ export class Retention {
279
524
  });
280
525
  }
281
526
  intent(owner, root, table = "intents") {
282
- this.db
283
- .prepare(`INSERT INTO ${table} VALUES (?,?,1)
284
- ON CONFLICT(id,cid) DO UPDATE SET count=count+1`)
285
- .run(owner, root);
527
+ this.queryRun(`INSERT INTO ${table} VALUES (?,?,1)
528
+ ON CONFLICT(id,cid) DO UPDATE SET count=count+1`, owner, root);
286
529
  }
287
530
  discard(session, signal) {
288
- return this.locked(signal, () => {
289
- 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);
290
533
  });
291
534
  }
292
535
  recover(owner, roots, signal, isIdle) {
293
- return this.locked(signal, () => {
536
+ return this.locked("recover", signal, () => {
294
537
  if (isIdle && !isIdle())
295
538
  return;
296
539
  this.transaction(() => {
297
540
  this.publish(owner, typeof roots === "function" ? roots() : roots, true);
298
- this.db.prepare("DELETE FROM intents WHERE id=?").run(owner);
299
- for (const row of this.db
300
- .prepare("SELECT DISTINCT id FROM stages")
301
- .all())
541
+ this.queryRun("DELETE FROM intents WHERE id=?", owner);
542
+ for (const row of this.queryAll("SELECT DISTINCT id FROM stages"))
302
543
  if (String(row.id).startsWith(`${owner}/`))
303
- this.db
304
- .prepare("DELETE FROM stages WHERE id=?")
305
- .run(String(row.id));
544
+ this.queryRun("DELETE FROM stages WHERE id=?", String(row.id));
306
545
  });
307
546
  });
308
547
  }
309
- async stageEntries(session, entries, signal) {
310
- if (entries.length === 0)
311
- return;
312
- const uniqueRoots = [...new Set(entries.map((entry) => entry.root))];
313
- const alreadyPinned = new Set();
314
- for (const root of uniqueRoots) {
315
- if (this.db.prepare("SELECT phase FROM pins WHERE cid=?").get(root)
316
- ?.phase === "pinned") {
317
- alreadyPinned.add(root);
318
- }
548
+ async stageEntriesUnlocked(op, session, entries, signal) {
549
+ signal?.throwIfAborted();
550
+ if (entries.length === 0) {
551
+ return { uniqueRoots: [], alreadyPinned: new Set() };
319
552
  }
320
- this.transaction(() => {
321
- const insertStage = this.db.prepare("INSERT OR IGNORE INTO stages VALUES (?,?)");
322
- for (const root of uniqueRoots) {
323
- insertStage.run(session, root);
324
- this.phase(root, "stage-pending");
325
- }
553
+ const uniqueRoots = [...new Set(entries.map((entry) => entry.root))];
554
+ const alreadyPinned = await this.lock(op, signal, () => {
555
+ const pinned = new Set();
556
+ this.transaction(() => {
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
+ }
568
+ });
569
+ return pinned;
326
570
  });
327
571
  const written = new Set();
328
- let failedRoot;
329
572
  try {
330
573
  for (const entry of entries) {
331
574
  signal?.throwIfAborted();
332
- failedRoot = entry.root;
333
575
  written.delete(entry.root);
334
576
  await entry.write();
335
577
  written.add(entry.root);
336
- failedRoot = undefined;
337
578
  }
338
579
  }
339
580
  catch (error) {
340
- this.transaction(() => {
341
- for (const root of written) {
342
- this.phase(root, alreadyPinned.has(root) ? "pinned" : "staged");
343
- }
344
- for (const root of alreadyPinned) {
345
- if (!written.has(root) && root !== failedRoot) {
346
- this.phase(root, "pinned");
347
- }
348
- }
349
- });
350
- throw error;
351
- }
352
- this.transaction(() => {
353
- for (const root of uniqueRoots) {
354
- this.phase(root, alreadyPinned.has(root) ? "pinned" : "staged");
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(() => { });
355
593
  }
356
- });
594
+ this.wrapUnfinished(error, signal);
595
+ }
596
+ return { uniqueRoots, alreadyPinned };
357
597
  }
358
598
  stage(session, root, write, signal) {
359
599
  root = this.roots([root])[0];
360
- return this.locked(signal, () => this.stageEntries(session, [{ root, write }], signal));
600
+ return this.stageBatchInternal("stage", session, [{ root, write }], signal);
361
601
  }
362
602
  stageBatch(session, entries, signal) {
363
603
  const normalized = entries.map((entry) => ({
364
604
  root: this.roots([entry.cid])[0],
365
605
  write: entry.write,
366
606
  }));
367
- return this.locked(signal, () => this.stageEntries(session, normalized, signal));
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, () => {
615
+ this.transaction(() => {
616
+ for (const root of uniqueRoots) {
617
+ if (!alreadyPinned.has(root) &&
618
+ this.pinPhase(root, "pins") !== "pinned") {
619
+ this.phase(root, "staged");
620
+ }
621
+ }
622
+ });
623
+ });
624
+ })());
368
625
  }
369
- finish(session, root, owner, signal) {
626
+ finish(session, root, owner, signal, port) {
370
627
  root = this.roots([root])[0];
371
- return this.locked(signal, async () => {
372
- if (owner) {
628
+ return this.track((async () => {
629
+ await this.lock("finish", signal, () => {
373
630
  this.transaction(() => {
374
- this.publish(owner, [root]);
375
- this.intent(owner, root);
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
+ }
376
638
  });
377
- }
378
- await this.ensure(root, signal);
379
- this.db.prepare("DELETE FROM stages WHERE id=?").run(session);
380
- });
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
+ })());
381
650
  }
382
- importBatch(session, entries, root, owner, signal, onRetained) {
651
+ importBatch(session, entries, root, owner, signal, onRetained, port) {
383
652
  root = this.roots([root])[0];
384
653
  const normalized = entries.map((entry) => ({
385
654
  root: this.roots([entry.cid])[0],
386
655
  write: entry.write,
387
656
  }));
388
- return this.locked(signal, async () => {
389
- await this.stageEntries(session, normalized, signal);
657
+ return this.track((async () => {
658
+ const { uniqueRoots, alreadyPinned } = await this.stageEntriesUnlocked("importBatch", session, normalized, signal);
390
659
  signal?.throwIfAborted();
391
- if (owner) {
660
+ await this.lock("importBatch", signal, () => {
392
661
  this.transaction(() => {
393
- this.publish(owner, [root]);
394
- this.intent(owner, root);
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
+ }
395
675
  });
396
- }
397
- await this.ensure(root, signal);
398
- this.db.prepare("DELETE FROM stages WHERE id=?").run(session);
399
- if (owner && onRetained) {
400
- signal?.throwIfAborted();
401
- await onRetained();
676
+ });
677
+ await this.runPrepare("importBatch", root, signal, port, false);
678
+ await this.lock("importBatch", signal, async () => {
402
679
  this.transaction(() => {
403
- this.decrementIntent(owner, root);
680
+ if (!owner || this.allRoots().includes(root)) {
681
+ this.phase(root, "pinned");
682
+ }
683
+ this.queryRun("DELETE FROM stages WHERE id=?", session);
404
684
  });
405
- }
406
- });
685
+ if (owner && onRetained) {
686
+ signal?.throwIfAborted();
687
+ await onRetained();
688
+ this.transaction(() => {
689
+ this.decrementIntent(owner, root);
690
+ });
691
+ }
692
+ });
693
+ })());
407
694
  }
408
695
  remove(root, signal, table = "pins") {
409
- const record = this.db
410
- .prepare(`SELECT phase FROM ${table} WHERE cid=?`)
411
- .get(root);
696
+ const record = this.queryGet(`SELECT phase FROM ${table} WHERE cid=?`, root);
412
697
  if (!record)
413
698
  return false;
414
699
  this.phase(root, "unpin-pending", table);
415
700
  signal?.throwIfAborted();
416
- this.db.prepare(`DELETE FROM ${table} WHERE cid=?`).run(root);
701
+ this.queryRun(`DELETE FROM ${table} WHERE cid=?`, root);
417
702
  return true;
418
703
  }
419
704
  unpin(root, signal) {
420
705
  root = this.roots([root])[0];
421
- return this.locked(signal, () => {
706
+ return this.locked("unpin", signal, () => {
422
707
  if (this.allRoots().includes(root))
423
708
  throw new Error("A participating owner still retains this root.");
424
709
  this.remove(root, signal);
@@ -426,7 +711,7 @@ export class Retention {
426
711
  }
427
712
  unpinDirect(root, signal) {
428
713
  root = this.roots([root])[0];
429
- return this.locked(signal, () => {
714
+ return this.locked("unpinDirect", signal, () => {
430
715
  if (this.allDirectRoots().includes(root))
431
716
  throw new Error("A participating owner still retains this direct block.");
432
717
  this.remove(root, signal, "direct_pins");
@@ -434,112 +719,97 @@ export class Retention {
434
719
  }
435
720
  allRoots() {
436
721
  return this.roots([
437
- ...this.db
438
- .prepare("SELECT id FROM owners")
439
- .all()
440
- .flatMap((row) => this.readOwner(String(row.id))),
441
- ...this.db
442
- .prepare("SELECT cid FROM intents")
443
- .all()
444
- .map((row) => String(row.cid)),
445
- ...this.db
446
- .prepare("SELECT cid FROM stages")
447
- .all()
448
- .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)),
449
725
  ]);
450
726
  }
451
727
  allDirectRoots() {
452
728
  return this.roots([
453
- ...this.db
454
- .prepare("SELECT id FROM direct_owners")
455
- .all()
456
- .flatMap((row) => this.readOwner(String(row.id), "direct_owners")),
457
- ...this.db
458
- .prepare("SELECT cid FROM direct_intents")
459
- .all()
460
- .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)),
461
731
  ]);
462
732
  }
463
- reconcile(owner, roots, signal) {
464
- return this.locked(signal, async () => {
465
- this.publish(owner, typeof roots === "function" ? roots() : roots, true);
466
- const marked = new Set(this.allRoots());
467
- // Complete the entire mark before removing any hint. Recheck real blocks, not reader caches.
468
- for (const root of marked)
469
- await this.ensure(root, signal);
470
- let removed = 0;
471
- for (const row of this.db.prepare("SELECT cid FROM pins").all()) {
472
- const root = String(row.cid);
473
- if (!marked.has(root) && this.remove(root, signal))
474
- removed++;
475
- }
476
- return removed;
477
- });
478
- }
479
- reconcileDirect(owner, roots, signal) {
480
- return this.locked(signal, async () => {
481
- this.publish(owner, typeof roots === "function" ? roots() : roots, true, "direct_owners");
482
- const marked = new Set(this.allDirectRoots());
483
- for (const root of marked)
484
- await this.ensureDirect(root, signal);
485
- let removed = 0;
486
- for (const row of this.db.prepare("SELECT cid FROM direct_pins").all()) {
487
- const root = String(row.cid);
488
- if (!marked.has(root) && this.remove(root, signal, "direct_pins"))
489
- 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);
490
771
  }
491
- return removed;
492
- });
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
+ })());
493
790
  }
494
791
  pins() {
495
- return this.db
496
- .prepare("SELECT cid FROM pins WHERE phase='pinned' ORDER BY cid")
497
- .all()
498
- .map((row) => String(row.cid));
792
+ return this.queryAll("SELECT cid FROM pins WHERE phase='pinned' ORDER BY cid").map((row) => String(row.cid));
499
793
  }
500
794
  directPins() {
501
- return this.db
502
- .prepare("SELECT cid FROM direct_pins WHERE phase='pinned' ORDER BY cid")
503
- .all()
504
- .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));
505
796
  }
506
797
  maintain(action, signal) {
507
- return this.locked(signal, () => action({
798
+ return this.locked("maintain", signal, () => action({
508
799
  pinned: this.pins(),
509
800
  roots: this.roots([
510
- ...this.db
511
- .prepare("SELECT id FROM owners")
512
- .all()
513
- .flatMap((row) => this.readOwner(String(row.id))),
514
- ...this.db
515
- .prepare("SELECT cid FROM intents")
516
- .all()
517
- .map((row) => String(row.cid)),
518
- ...this.db
519
- .prepare("SELECT cid FROM pins WHERE phase NOT IN ('staged','stage-pending')")
520
- .all()
521
- .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)),
522
804
  ]),
523
805
  directPinned: this.directPins(),
524
806
  directRoots: this.roots([
525
- ...this.db
526
- .prepare("SELECT id FROM direct_owners")
527
- .all()
528
- .flatMap((row) => this.readOwner(String(row.id), "direct_owners")),
529
- ...this.db
530
- .prepare("SELECT cid FROM direct_intents")
531
- .all()
532
- .map((row) => String(row.cid)),
533
- ...this.db
534
- .prepare("SELECT cid FROM direct_pins WHERE phase NOT IN ('staged','stage-pending')")
535
- .all()
536
- .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)),
537
810
  ]),
538
811
  // Import parents may arrive before their children; protect staged blocks individually.
539
- staged: this.db
540
- .prepare("SELECT DISTINCT cid FROM stages")
541
- .all()
542
- .map((row) => String(row.cid)),
812
+ staged: this.queryAll("SELECT DISTINCT cid FROM stages").map((row) => String(row.cid)),
543
813
  }));
544
814
  }
545
815
  async close() {