@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/src/retention.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { mkdirSync } from "node:fs";
2
2
  import { join, resolve } from "node:path";
3
- import type { DatabaseSync } from "node:sqlite";
3
+ import type { DatabaseSync, SQLInputValue, SQLOutputValue } from "node:sqlite";
4
4
  import type * as sqlite from "node:sqlite";
5
5
  import { createRequire } from "node:module";
6
6
  import { setTimeout as sleep } from "node:timers/promises";
@@ -30,30 +30,64 @@ function waitForTurn(
30
30
  });
31
31
  }
32
32
 
33
- interface RetentionPort {
33
+ export interface RetentionCoordinationEvent {
34
+ op: string;
35
+ phase: "wait" | "hold" | "prepare";
36
+ durationMs: number;
37
+ error?: string;
38
+ }
39
+
40
+ export interface RetentionSqlEvent {
41
+ db: "retention";
42
+ op: "exec" | "get" | "all" | "run" | "tx";
43
+ sql: string;
44
+ durationMs: number;
45
+ error?: string;
46
+ }
47
+
48
+ export interface RetentionTelemetry {
49
+ onCoordinationEvent?: (event: RetentionCoordinationEvent) => void;
50
+ onSqlEvent?: (event: RetentionSqlEvent) => void;
51
+ }
52
+
53
+ export interface RetentionOptions extends RetentionTelemetry {
54
+ singleProcessCoordination?: boolean;
55
+ }
56
+
57
+ export interface RetentionPort {
34
58
  prepare(root: string, signal?: AbortSignal): Promise<void>;
35
59
  prepareDirect?: (root: string, signal?: AbortSignal) => Promise<void>;
36
60
  }
61
+
37
62
  /** The separate SQLite mutex preserves durable intents during content acquisition. */
38
63
  export class Retention {
39
64
  private readonly Database: typeof DatabaseSync;
40
65
  private readonly db: DatabaseSync;
41
66
  private readonly mutexPath: string;
42
67
  private readonly queueKey: string;
68
+ private readonly singleProcessCoordination: boolean;
69
+ private readonly onCoordinationEvent:
70
+ ((event: RetentionCoordinationEvent) => void) | undefined;
71
+ private readonly onSqlEvent: ((event: RetentionSqlEvent) => void) | undefined;
43
72
  private readonly pending = new Set<Promise<unknown>>();
44
73
  private closed = false;
45
74
  constructor(
46
75
  directory: string,
47
76
  private readonly port: RetentionPort,
77
+ options: RetentionOptions = {},
48
78
  ) {
49
79
  this.Database = (
50
80
  createRequire(import.meta.url)("node:sqlite") as typeof sqlite
51
81
  ).DatabaseSync;
82
+ this.singleProcessCoordination = options.singleProcessCoordination ?? false;
83
+ this.onCoordinationEvent = options.onCoordinationEvent;
84
+ this.onSqlEvent = options.onSqlEvent;
52
85
  mkdirSync(directory, { recursive: true });
53
86
  this.db = new this.Database(join(directory, "retention.sqlite"));
54
87
  this.mutexPath = join(directory, "mutex.sqlite");
55
88
  this.queueKey = queueKeyFor(this.mutexPath);
56
- this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
89
+ this
90
+ .execSql(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
57
91
  CREATE TABLE IF NOT EXISTS owners (id TEXT PRIMARY KEY, roots TEXT NOT NULL);
58
92
  CREATE TABLE IF NOT EXISTS stages (id TEXT NOT NULL, cid TEXT NOT NULL, PRIMARY KEY(id,cid));
59
93
  CREATE TABLE IF NOT EXISTS intents (
@@ -64,6 +98,74 @@ export class Retention {
64
98
  id TEXT NOT NULL, cid TEXT NOT NULL, count INTEGER NOT NULL CHECK(count>0), PRIMARY KEY(id,cid));
65
99
  CREATE TABLE IF NOT EXISTS direct_pins (cid TEXT PRIMARY KEY, phase TEXT NOT NULL);`);
66
100
  }
101
+ private emitCoordination(event: RetentionCoordinationEvent): void {
102
+ try {
103
+ this.onCoordinationEvent?.(event);
104
+ } catch {
105
+ // Telemetry callbacks must never disrupt retention coordination.
106
+ }
107
+ }
108
+ private emitSql(event: RetentionSqlEvent): void {
109
+ try {
110
+ this.onSqlEvent?.(event);
111
+ } catch {
112
+ // Telemetry callbacks must never disrupt retention SQL.
113
+ }
114
+ }
115
+ private measureSql<T>(
116
+ op: RetentionSqlEvent["op"],
117
+ sql: string,
118
+ action: () => T,
119
+ ): T {
120
+ if (!this.onSqlEvent) return action();
121
+ const startedAt = performance.now();
122
+ const normalized = sql.replace(/\s+/g, " ").trim();
123
+ try {
124
+ const result = action();
125
+ this.emitSql({
126
+ db: "retention",
127
+ op,
128
+ sql: normalized,
129
+ durationMs: performance.now() - startedAt,
130
+ });
131
+ return result;
132
+ } catch (error) {
133
+ this.emitSql({
134
+ db: "retention",
135
+ op,
136
+ sql: normalized,
137
+ durationMs: performance.now() - startedAt,
138
+ error: error instanceof Error ? error.message : String(error),
139
+ });
140
+ throw error;
141
+ }
142
+ }
143
+ private execSql(sql: string): void {
144
+ this.measureSql("exec", sql, () => {
145
+ this.db.exec(sql);
146
+ });
147
+ }
148
+ private queryGet(
149
+ sql: string,
150
+ ...params: SQLInputValue[]
151
+ ): Record<string, SQLOutputValue> | undefined {
152
+ return this.measureSql("get", sql, () =>
153
+ this.db.prepare(sql).get(...params),
154
+ );
155
+ }
156
+ private queryAll(
157
+ sql: string,
158
+ ...params: SQLInputValue[]
159
+ ): Record<string, SQLOutputValue>[] {
160
+ return this.measureSql("all", sql, () =>
161
+ this.db.prepare(sql).all(...params),
162
+ );
163
+ }
164
+ private queryRun(sql: string, ...params: SQLInputValue[]): void {
165
+ this.measureSql("run", sql, () => {
166
+ this.db.prepare(sql).run(...params);
167
+ });
168
+ }
67
169
  private roots(values: readonly string[]): string[] {
68
170
  return [
69
171
  ...new Set(values.map((value) => CID.parse(value).toV1().toString())),
@@ -73,9 +175,7 @@ export class Retention {
73
175
  owner: string,
74
176
  table: "owners" | "direct_owners" = "owners",
75
177
  ): string[] {
76
- const row = this.db
77
- .prepare(`SELECT roots FROM ${table} WHERE id=?`)
78
- .get(owner);
178
+ const row = this.queryGet(`SELECT roots FROM ${table} WHERE id=?`, owner);
79
179
  if (!row) return [];
80
180
  const roots: unknown = JSON.parse(String(row.roots));
81
181
  if (!Array.isArray(roots) || roots.some((root) => typeof root !== "string"))
@@ -93,42 +193,46 @@ export class Retention {
93
193
  const values = this.roots(
94
194
  replace ? roots : [...this.readOwner(owner, table), ...roots],
95
195
  );
96
- this.db
97
- .prepare(
98
- `INSERT INTO ${table} VALUES (?,?)
196
+ this.queryRun(
197
+ `INSERT INTO ${table} VALUES (?,?)
99
198
  ON CONFLICT(id) DO UPDATE SET roots=excluded.roots
100
199
  WHERE ${table}.roots<>excluded.roots`,
101
- )
102
- .run(owner, JSON.stringify(values));
200
+ owner,
201
+ JSON.stringify(values),
202
+ );
103
203
  }
104
204
  private transaction<T>(action: () => T): T {
105
- this.db.exec("BEGIN IMMEDIATE");
106
- try {
107
- const result = action();
108
- this.db.exec("COMMIT");
109
- return result;
110
- } catch (error) {
111
- this.db.exec("ROLLBACK");
112
- throw error;
113
- }
205
+ return this.measureSql("tx", "BEGIN IMMEDIATE ... COMMIT", () => {
206
+ this.db.exec("BEGIN IMMEDIATE");
207
+ try {
208
+ const result = action();
209
+ this.db.exec("COMMIT");
210
+ return result;
211
+ } catch (error) {
212
+ this.db.exec("ROLLBACK");
213
+ throw error;
214
+ }
215
+ });
114
216
  }
115
217
  private begin(mutex: DatabaseSync): void {
116
218
  if (this.closed) throw new Error("Retention coordinator is closed.");
117
219
  mutex.exec("BEGIN IMMEDIATE");
118
220
  }
119
221
  register(owner: string, roots: readonly string[]): void {
120
- this.registerInTable(owner, roots, "owners");
222
+ this.registerInTable("register", owner, roots, "owners");
121
223
  }
122
224
  registerDirect(owner: string, roots: readonly string[]): void {
123
- this.registerInTable(owner, roots, "direct_owners");
225
+ this.registerInTable("registerDirect", owner, roots, "direct_owners");
124
226
  }
125
227
  registerAsync(
126
228
  owner: string,
127
229
  roots: readonly string[],
128
230
  signal?: AbortSignal,
129
231
  ): Promise<void> {
130
- return this.locked(signal, () => {
131
- this.publish(owner, roots, false, "owners");
232
+ return this.locked("registerAsync", signal, () => {
233
+ this.transaction(() => {
234
+ this.publish(owner, roots, false, "owners");
235
+ });
132
236
  });
133
237
  }
134
238
  registerDirectAsync(
@@ -136,49 +240,122 @@ export class Retention {
136
240
  roots: readonly string[],
137
241
  signal?: AbortSignal,
138
242
  ): Promise<void> {
139
- return this.locked(signal, () => {
140
- this.publish(owner, roots, false, "direct_owners");
243
+ return this.locked("registerDirectAsync", signal, () => {
244
+ this.transaction(() => {
245
+ this.publish(owner, roots, false, "direct_owners");
246
+ });
141
247
  });
142
248
  }
143
249
  private registerInTable(
250
+ op: string,
144
251
  owner: string,
145
252
  roots: readonly string[],
146
253
  table: "owners" | "direct_owners",
147
254
  ): void {
255
+ if (this.singleProcessCoordination) {
256
+ if (this.closed || coordinationQueues.has(this.queueKey))
257
+ throw new ContentError(
258
+ "retention_unfinished",
259
+ "Retention coordination is unavailable; retry.",
260
+ );
261
+ const holdStart = performance.now();
262
+ let errorMessage: string | undefined;
263
+ try {
264
+ this.transaction(() => {
265
+ this.publish(owner, roots, false, table);
266
+ });
267
+ } catch (error) {
268
+ errorMessage = error instanceof Error ? error.message : String(error);
269
+ throw error;
270
+ } finally {
271
+ this.emitCoordination({
272
+ op,
273
+ phase: "hold",
274
+ durationMs: performance.now() - holdStart,
275
+ ...(errorMessage !== undefined ? { error: errorMessage } : {}),
276
+ });
277
+ }
278
+ return;
279
+ }
280
+ const waitStart = performance.now();
148
281
  const mutex = new this.Database(this.mutexPath);
149
282
  mutex.exec("PRAGMA busy_timeout=0");
150
283
  try {
151
284
  this.begin(mutex);
152
285
  } catch {
153
286
  mutex.close();
287
+ this.emitCoordination({
288
+ op,
289
+ phase: "wait",
290
+ durationMs: performance.now() - waitStart,
291
+ error: "Retention coordination is unavailable; retry.",
292
+ });
154
293
  throw new ContentError(
155
294
  "retention_unfinished",
156
295
  "Retention coordination is unavailable; retry.",
157
296
  );
158
297
  }
298
+ this.emitCoordination({
299
+ op,
300
+ phase: "wait",
301
+ durationMs: performance.now() - waitStart,
302
+ });
303
+ const holdStart = performance.now();
304
+ let errorMessage: string | undefined;
159
305
  try {
160
306
  this.publish(owner, roots, false, table);
307
+ } catch (error) {
308
+ errorMessage = error instanceof Error ? error.message : String(error);
309
+ throw error;
161
310
  } finally {
162
311
  mutex.exec("ROLLBACK");
163
312
  mutex.close();
313
+ this.emitCoordination({
314
+ op,
315
+ phase: "hold",
316
+ durationMs: performance.now() - holdStart,
317
+ ...(errorMessage !== undefined ? { error: errorMessage } : {}),
318
+ });
164
319
  }
165
320
  }
166
- private async locked<T>(
167
- signal: AbortSignal | undefined,
168
- action: () => Promise<T> | T,
169
- ): Promise<T> {
170
- const operation = this.lock(signal, action);
321
+ private track<T>(operation: Promise<T>): Promise<T> {
171
322
  this.pending.add(operation);
172
323
  void operation
173
324
  .finally(() => this.pending.delete(operation))
174
325
  .catch(() => {});
175
326
  return operation;
176
327
  }
328
+ private wrapUnfinished(error: unknown, signal?: AbortSignal): never {
329
+ if (signal?.aborted) throw signal.reason;
330
+ if (error instanceof ContentError && error.code === "retention_unfinished")
331
+ throw error;
332
+ throw new ContentError(
333
+ "retention_unfinished",
334
+ `Retention hints are unfinished; durable intents remain for retry. ${
335
+ error instanceof ContentError
336
+ ? `${error.code}: ${error.message}`
337
+ : error instanceof Error &&
338
+ ["TimeoutError", "AbortError"].includes(error.name)
339
+ ? error.name
340
+ : "verification_or_storage_failure"
341
+ }`,
342
+ { cause: error },
343
+ );
344
+ }
345
+ private locked<T>(
346
+ op: string,
347
+ signal: AbortSignal | undefined,
348
+ action: () => Promise<T> | T,
349
+ ): Promise<T> {
350
+ return this.track(this.lock(op, signal, action));
351
+ }
177
352
  private async lock<T>(
353
+ op: string,
178
354
  signal: AbortSignal | undefined,
179
355
  action: () => Promise<T> | T,
180
356
  ): Promise<T> {
181
357
  signal?.throwIfAborted();
358
+ const waitStart = performance.now();
182
359
  const previous = coordinationQueues.get(this.queueKey) ?? Promise.resolve();
183
360
  let releaseTurn!: () => void;
184
361
  const current = new Promise<void>((resolveTurn) => {
@@ -186,19 +363,61 @@ export class Retention {
186
363
  });
187
364
  const tail = previous.then(() => current);
188
365
  coordinationQueues.set(this.queueKey, tail);
189
- const release = () => {
190
- releaseTurn();
366
+ void tail.finally(() => {
191
367
  if (coordinationQueues.get(this.queueKey) === tail) {
192
368
  coordinationQueues.delete(this.queueKey);
193
369
  }
370
+ });
371
+ const release = () => {
372
+ releaseTurn();
194
373
  };
195
374
  try {
196
375
  await waitForTurn(previous, signal);
197
376
  } catch (error) {
198
377
  release();
378
+ this.emitCoordination({
379
+ op,
380
+ phase: "wait",
381
+ durationMs: performance.now() - waitStart,
382
+ error: error instanceof Error ? error.message : String(error),
383
+ });
199
384
  throw error;
200
385
  }
201
386
  try {
387
+ if (this.singleProcessCoordination) {
388
+ if (this.closed) {
389
+ this.emitCoordination({
390
+ op,
391
+ phase: "wait",
392
+ durationMs: performance.now() - waitStart,
393
+ error: "Retention coordination is unavailable.",
394
+ });
395
+ throw new ContentError(
396
+ "retention_unfinished",
397
+ "Retention coordination is unavailable.",
398
+ );
399
+ }
400
+ this.emitCoordination({
401
+ op,
402
+ phase: "wait",
403
+ durationMs: performance.now() - waitStart,
404
+ });
405
+ const holdStart = performance.now();
406
+ let holdError: string | undefined;
407
+ try {
408
+ return await action();
409
+ } catch (error) {
410
+ holdError = error instanceof Error ? error.message : String(error);
411
+ return this.wrapUnfinished(error, signal);
412
+ } finally {
413
+ this.emitCoordination({
414
+ op,
415
+ phase: "hold",
416
+ durationMs: performance.now() - holdStart,
417
+ ...(holdError !== undefined ? { error: holdError } : {}),
418
+ });
419
+ }
420
+ }
202
421
  const mutex = new this.Database(this.mutexPath);
203
422
  mutex.exec("PRAGMA busy_timeout=0");
204
423
  const deadline = Date.now() + 30_000;
@@ -222,99 +441,229 @@ export class Retention {
222
441
  }
223
442
  } catch (error) {
224
443
  mutex.close();
444
+ this.emitCoordination({
445
+ op,
446
+ phase: "wait",
447
+ durationMs: performance.now() - waitStart,
448
+ error: error instanceof Error ? error.message : String(error),
449
+ });
225
450
  signal?.throwIfAborted();
226
451
  throw error;
227
452
  }
453
+ this.emitCoordination({
454
+ op,
455
+ phase: "wait",
456
+ durationMs: performance.now() - waitStart,
457
+ });
458
+ const holdStart = performance.now();
459
+ let holdError: string | undefined;
228
460
  try {
229
461
  return await action();
230
462
  } catch (error) {
231
- if (signal?.aborted) throw signal.reason;
232
- throw new ContentError(
233
- "retention_unfinished",
234
- `Retention hints are unfinished; durable intents remain for retry. ${
235
- error instanceof ContentError
236
- ? `${error.code}: ${error.message}`
237
- : error instanceof Error &&
238
- ["TimeoutError", "AbortError"].includes(error.name)
239
- ? error.name
240
- : "verification_or_storage_failure"
241
- }`,
242
- { cause: error },
243
- );
463
+ holdError = error instanceof Error ? error.message : String(error);
464
+ return this.wrapUnfinished(error, signal);
244
465
  } finally {
245
466
  mutex.exec("ROLLBACK");
246
467
  mutex.close();
468
+ this.emitCoordination({
469
+ op,
470
+ phase: "hold",
471
+ durationMs: performance.now() - holdStart,
472
+ ...(holdError !== undefined ? { error: holdError } : {}),
473
+ });
247
474
  }
248
475
  } finally {
249
476
  release();
250
477
  }
251
478
  }
479
+ private pinPhase(
480
+ root: string,
481
+ table: "pins" | "direct_pins" = "pins",
482
+ ): string | undefined {
483
+ const row = this.queryGet(`SELECT phase FROM ${table} WHERE cid=?`, root);
484
+ return row ? String(row.phase) : undefined;
485
+ }
486
+ private pinPhases(table: "pins" | "direct_pins"): Map<string, string> {
487
+ const phases = new Map<string, string>();
488
+ for (const row of this.queryAll(`SELECT cid, phase FROM ${table}`)) {
489
+ phases.set(String(row.cid), String(row.phase));
490
+ }
491
+ return phases;
492
+ }
252
493
  private phase(
253
494
  root: string,
254
495
  phase: string,
255
496
  table: "pins" | "direct_pins" = "pins",
256
497
  ): void {
257
- this.db
258
- .prepare(`INSERT OR REPLACE INTO ${table} VALUES (?,?)`)
259
- .run(root, phase);
260
- }
261
- private async ensure(root: string, signal?: AbortSignal): Promise<void> {
262
- this.phase(root, "pin-pending");
263
- await this.port.prepare(root, signal);
264
- this.phase(root, "pinned");
498
+ this.queryRun(`INSERT OR REPLACE INTO ${table} VALUES (?,?)`, root, phase);
265
499
  }
266
- private async ensureDirect(
500
+ private async runPrepare(
501
+ op: string,
267
502
  root: string,
268
- signal?: AbortSignal,
503
+ signal: AbortSignal | undefined,
504
+ port: RetentionPort | undefined,
505
+ direct: boolean,
269
506
  ): Promise<void> {
270
- this.phase(root, "pin-pending", "direct_pins");
271
- await (this.port.prepareDirect
272
- ? this.port.prepareDirect(root, signal)
273
- : this.port.prepare(root, signal));
274
- this.phase(root, "pinned", "direct_pins");
507
+ const activePort = port ?? this.port;
508
+ const startedAt = performance.now();
509
+ let errorMessage: string | undefined;
510
+ try {
511
+ signal?.throwIfAborted();
512
+ if (direct && activePort.prepareDirect) {
513
+ await activePort.prepareDirect(root, signal);
514
+ } else {
515
+ await activePort.prepare(root, signal);
516
+ }
517
+ } catch (error) {
518
+ errorMessage = error instanceof Error ? error.message : String(error);
519
+ this.wrapUnfinished(error, signal);
520
+ } finally {
521
+ this.emitCoordination({
522
+ op,
523
+ phase: "prepare",
524
+ durationMs: performance.now() - startedAt,
525
+ ...(errorMessage !== undefined ? { error: errorMessage } : {}),
526
+ });
527
+ }
275
528
  }
276
- pin(root: string, signal?: AbortSignal): Promise<void> {
529
+ pin(root: string, signal?: AbortSignal, port?: RetentionPort): Promise<void> {
277
530
  root = this.roots([root])[0]!;
278
- return this.locked(signal, () => this.ensure(root, signal));
531
+ return this.track(
532
+ (async () => {
533
+ await this.lock("pin", signal, () => {
534
+ this.transaction(() => {
535
+ this.phase(root, "pin-pending", "pins");
536
+ });
537
+ });
538
+ await this.runPrepare("pin", root, signal, port, false);
539
+ await this.lock("pin", signal, () => {
540
+ this.transaction(() => {
541
+ if (this.pinPhase(root, "pins") !== undefined) {
542
+ this.phase(root, "pinned", "pins");
543
+ }
544
+ });
545
+ });
546
+ })(),
547
+ );
279
548
  }
280
- pinDirect(root: string, signal?: AbortSignal): Promise<void> {
549
+ pinDirect(
550
+ root: string,
551
+ signal?: AbortSignal,
552
+ port?: RetentionPort,
553
+ ): Promise<void> {
281
554
  root = this.roots([root])[0]!;
282
- return this.locked(signal, () => this.ensureDirect(root, signal));
555
+ return this.track(
556
+ (async () => {
557
+ await this.lock("pinDirect", signal, () => {
558
+ this.transaction(() => {
559
+ this.phase(root, "pin-pending", "direct_pins");
560
+ });
561
+ });
562
+ await this.runPrepare("pinDirect", root, signal, port, true);
563
+ await this.lock("pinDirect", signal, () => {
564
+ this.transaction(() => {
565
+ if (this.pinPhase(root, "direct_pins") !== undefined) {
566
+ this.phase(root, "pinned", "direct_pins");
567
+ }
568
+ });
569
+ });
570
+ })(),
571
+ );
283
572
  }
284
573
  retain(
285
574
  owner: string,
286
575
  roots: readonly string[],
287
576
  signal?: AbortSignal,
577
+ port?: RetentionPort,
288
578
  ): Promise<void> {
289
- return this.locked(signal, async () => {
290
- this.transaction(() => {
291
- this.publish(owner, roots);
292
- for (const root of this.roots(roots)) this.intent(owner, root);
293
- });
294
- for (const root of this.roots(roots)) await this.ensure(root, signal);
295
- });
579
+ return this.retainInTable(
580
+ "retain",
581
+ owner,
582
+ roots,
583
+ "owners",
584
+ "intents",
585
+ "pins",
586
+ false,
587
+ signal,
588
+ port,
589
+ );
296
590
  }
297
591
  retainDirect(
298
592
  owner: string,
299
593
  roots: readonly string[],
300
594
  signal?: AbortSignal,
595
+ port?: RetentionPort,
301
596
  ): Promise<void> {
302
- return this.locked(signal, async () => {
303
- this.transaction(() => {
304
- this.publish(owner, roots, false, "direct_owners");
305
- for (const root of this.roots(roots))
306
- this.intent(owner, root, "direct_intents");
307
- });
308
- for (const root of this.roots(roots))
309
- await this.ensureDirect(root, signal);
310
- });
597
+ return this.retainInTable(
598
+ "retainDirect",
599
+ owner,
600
+ roots,
601
+ "direct_owners",
602
+ "direct_intents",
603
+ "direct_pins",
604
+ true,
605
+ signal,
606
+ port,
607
+ );
608
+ }
609
+ private retainInTable(
610
+ op: string,
611
+ owner: string,
612
+ roots: readonly string[],
613
+ ownerTable: "owners" | "direct_owners",
614
+ intentTable: "intents" | "direct_intents",
615
+ pinTable: "pins" | "direct_pins",
616
+ direct: boolean,
617
+ signal?: AbortSignal,
618
+ port?: RetentionPort,
619
+ ): Promise<void> {
620
+ return this.track(
621
+ (async () => {
622
+ const normalized = await this.lock(op, signal, () => {
623
+ const unique = this.roots(roots);
624
+ this.transaction(() => {
625
+ this.publish(owner, unique, false, ownerTable);
626
+ for (const root of unique) {
627
+ this.intent(owner, root, intentTable);
628
+ if (this.pinPhase(root, pinTable) !== "pinned") {
629
+ this.phase(root, "pin-pending", pinTable);
630
+ }
631
+ }
632
+ });
633
+ return unique;
634
+ });
635
+ for (const root of normalized) {
636
+ await this.runPrepare(op, root, signal, port, direct);
637
+ }
638
+ if (normalized.length === 0) return;
639
+ await this.lock(op, signal, () => {
640
+ this.transaction(() => {
641
+ const referenced = new Set(
642
+ direct ? this.allDirectRoots() : this.allRoots(),
643
+ );
644
+ for (const root of normalized) {
645
+ if (referenced.has(root)) {
646
+ this.phase(root, "pinned", pinTable);
647
+ }
648
+ }
649
+ });
650
+ });
651
+ })(),
652
+ );
311
653
  }
312
654
  confirm(
313
655
  owner: string,
314
656
  roots: readonly string[],
315
657
  signal?: AbortSignal,
316
658
  ): Promise<void> {
317
- return this.confirmInTable(owner, roots, "owners", "intents", signal);
659
+ return this.confirmInTable(
660
+ "confirm",
661
+ owner,
662
+ roots,
663
+ "owners",
664
+ "intents",
665
+ signal,
666
+ );
318
667
  }
319
668
  confirmDirect(
320
669
  owner: string,
@@ -322,6 +671,7 @@ export class Retention {
322
671
  signal?: AbortSignal,
323
672
  ): Promise<void> {
324
673
  return this.confirmInTable(
674
+ "confirmDirect",
325
675
  owner,
326
676
  roots,
327
677
  "direct_owners",
@@ -329,30 +679,42 @@ export class Retention {
329
679
  signal,
330
680
  );
331
681
  }
682
+ private decrementIntent(
683
+ owner: string,
684
+ root: string,
685
+ intentTable: "intents" | "direct_intents" = "intents",
686
+ ): void {
687
+ const row = this.queryGet(
688
+ `SELECT count FROM ${intentTable} WHERE id=? AND cid=?`,
689
+ owner,
690
+ root,
691
+ );
692
+ if (row && Number(row.count) > 1)
693
+ this.queryRun(
694
+ `UPDATE ${intentTable} SET count=count-1 WHERE id=? AND cid=?`,
695
+ owner,
696
+ root,
697
+ );
698
+ else
699
+ this.queryRun(
700
+ `DELETE FROM ${intentTable} WHERE id=? AND cid=?`,
701
+ owner,
702
+ root,
703
+ );
704
+ }
332
705
  private confirmInTable(
706
+ op: string,
333
707
  owner: string,
334
708
  roots: readonly string[],
335
709
  ownerTable: "owners" | "direct_owners",
336
710
  intentTable: "intents" | "direct_intents",
337
711
  signal?: AbortSignal,
338
712
  ): Promise<void> {
339
- return this.locked(signal, () => {
713
+ return this.locked(op, signal, () => {
340
714
  this.transaction(() => {
341
715
  this.publish(owner, roots, false, ownerTable);
342
716
  for (const root of this.roots(roots)) {
343
- const row = this.db
344
- .prepare(`SELECT count FROM ${intentTable} WHERE id=? AND cid=?`)
345
- .get(owner, root);
346
- if (row && Number(row.count) > 1)
347
- this.db
348
- .prepare(
349
- `UPDATE ${intentTable} SET count=count-1 WHERE id=? AND cid=?`,
350
- )
351
- .run(owner, root);
352
- else
353
- this.db
354
- .prepare(`DELETE FROM ${intentTable} WHERE id=? AND cid=?`)
355
- .run(owner, root);
717
+ this.decrementIntent(owner, root, intentTable);
356
718
  }
357
719
  });
358
720
  });
@@ -362,16 +724,16 @@ export class Retention {
362
724
  root: string,
363
725
  table: "intents" | "direct_intents" = "intents",
364
726
  ): void {
365
- this.db
366
- .prepare(
367
- `INSERT INTO ${table} VALUES (?,?,1)
727
+ this.queryRun(
728
+ `INSERT INTO ${table} VALUES (?,?,1)
368
729
  ON CONFLICT(id,cid) DO UPDATE SET count=count+1`,
369
- )
370
- .run(owner, root);
730
+ owner,
731
+ root,
732
+ );
371
733
  }
372
734
  discard(session: string, signal?: AbortSignal): Promise<void> {
373
- return this.locked(signal, () => {
374
- this.db.prepare("DELETE FROM stages WHERE id=?").run(session);
735
+ return this.locked("discard", signal, () => {
736
+ this.queryRun("DELETE FROM stages WHERE id=?", session);
375
737
  });
376
738
  }
377
739
  recover(
@@ -380,7 +742,7 @@ export class Retention {
380
742
  signal?: AbortSignal,
381
743
  isIdle?: () => boolean,
382
744
  ): Promise<void> {
383
- return this.locked(signal, () => {
745
+ return this.locked("recover", signal, () => {
384
746
  if (isIdle && !isIdle()) return;
385
747
  this.transaction(() => {
386
748
  this.publish(
@@ -388,16 +750,70 @@ export class Retention {
388
750
  typeof roots === "function" ? roots() : roots,
389
751
  true,
390
752
  );
391
- this.db.prepare("DELETE FROM intents WHERE id=?").run(owner);
392
- for (const row of this.db
393
- .prepare("SELECT DISTINCT id FROM stages")
394
- .all())
753
+ this.queryRun("DELETE FROM intents WHERE id=?", owner);
754
+ for (const row of this.queryAll("SELECT DISTINCT id FROM stages"))
395
755
  if (String(row.id).startsWith(`${owner}/`))
396
- this.db
397
- .prepare("DELETE FROM stages WHERE id=?")
398
- .run(String(row.id));
756
+ this.queryRun("DELETE FROM stages WHERE id=?", String(row.id));
757
+ });
758
+ });
759
+ }
760
+ private async stageEntriesUnlocked(
761
+ op: string,
762
+ session: string,
763
+ entries: readonly { root: string; write: () => Promise<unknown> }[],
764
+ signal?: AbortSignal,
765
+ ): Promise<{ uniqueRoots: string[]; alreadyPinned: Set<string> }> {
766
+ signal?.throwIfAborted();
767
+ if (entries.length === 0) {
768
+ return { uniqueRoots: [], alreadyPinned: new Set() };
769
+ }
770
+ const uniqueRoots = [...new Set(entries.map((entry) => entry.root))];
771
+ const alreadyPinned = await this.lock(op, signal, () => {
772
+ const pinned = new Set<string>();
773
+ this.transaction(() => {
774
+ for (const root of uniqueRoots) {
775
+ if (this.pinPhase(root, "pins") === "pinned") {
776
+ pinned.add(root);
777
+ }
778
+ }
779
+ for (const root of uniqueRoots) {
780
+ this.queryRun(
781
+ "INSERT OR IGNORE INTO stages VALUES (?,?)",
782
+ session,
783
+ root,
784
+ );
785
+ if (!pinned.has(root)) {
786
+ this.phase(root, "stage-pending");
787
+ }
788
+ }
399
789
  });
790
+ return pinned;
400
791
  });
792
+ const written = new Set<string>();
793
+ try {
794
+ for (const entry of entries) {
795
+ signal?.throwIfAborted();
796
+ written.delete(entry.root);
797
+ await entry.write();
798
+ written.add(entry.root);
799
+ }
800
+ } catch (error) {
801
+ if (written.size > 0) {
802
+ await this.lock(`${op}:rollback`, undefined, () => {
803
+ this.transaction(() => {
804
+ for (const root of written) {
805
+ if (!alreadyPinned.has(root)) {
806
+ if (this.pinPhase(root, "pins") !== "pinned") {
807
+ this.phase(root, "staged");
808
+ }
809
+ }
810
+ }
811
+ });
812
+ }).catch(() => {});
813
+ }
814
+ this.wrapUnfinished(error, signal);
815
+ }
816
+ return { uniqueRoots, alreadyPinned };
401
817
  }
402
818
  stage(
403
819
  session: string,
@@ -406,55 +822,161 @@ export class Retention {
406
822
  signal?: AbortSignal,
407
823
  ): Promise<void> {
408
824
  root = this.roots([root])[0]!;
409
- return this.locked(signal, async () => {
410
- const alreadyPinned =
411
- this.db.prepare("SELECT phase FROM pins WHERE cid=?").get(root)
412
- ?.phase === "pinned";
413
- this.transaction(() => {
414
- this.db
415
- .prepare("INSERT OR IGNORE INTO stages VALUES (?,?)")
416
- .run(session, root);
417
- this.phase(root, "stage-pending");
418
- });
419
- await write();
420
- this.phase(root, alreadyPinned ? "pinned" : "staged");
421
- });
825
+ return this.stageBatchInternal("stage", session, [{ root, write }], signal);
826
+ }
827
+ stageBatch(
828
+ session: string,
829
+ entries: readonly { cid: string; write: () => Promise<unknown> }[],
830
+ signal?: AbortSignal,
831
+ ): Promise<void> {
832
+ const normalized = entries.map((entry) => ({
833
+ root: this.roots([entry.cid])[0]!,
834
+ write: entry.write,
835
+ }));
836
+ return this.stageBatchInternal("stageBatch", session, normalized, signal);
837
+ }
838
+ private stageBatchInternal(
839
+ op: string,
840
+ session: string,
841
+ entries: readonly { root: string; write: () => Promise<unknown> }[],
842
+ signal?: AbortSignal,
843
+ ): Promise<void> {
844
+ return this.track(
845
+ (async () => {
846
+ const { uniqueRoots, alreadyPinned } = await this.stageEntriesUnlocked(
847
+ op,
848
+ session,
849
+ entries,
850
+ signal,
851
+ );
852
+ if (uniqueRoots.length === 0) return;
853
+ await this.lock(op, signal, () => {
854
+ this.transaction(() => {
855
+ for (const root of uniqueRoots) {
856
+ if (
857
+ !alreadyPinned.has(root) &&
858
+ this.pinPhase(root, "pins") !== "pinned"
859
+ ) {
860
+ this.phase(root, "staged");
861
+ }
862
+ }
863
+ });
864
+ });
865
+ })(),
866
+ );
422
867
  }
423
868
  finish(
424
869
  session: string,
425
870
  root: string,
426
871
  owner?: string,
427
872
  signal?: AbortSignal,
873
+ port?: RetentionPort,
428
874
  ): Promise<void> {
429
875
  root = this.roots([root])[0]!;
430
- return this.locked(signal, async () => {
431
- if (owner) {
432
- this.transaction(() => {
433
- this.publish(owner, [root]);
434
- this.intent(owner, root);
876
+ return this.track(
877
+ (async () => {
878
+ await this.lock("finish", signal, () => {
879
+ this.transaction(() => {
880
+ if (owner) {
881
+ this.publish(owner, [root]);
882
+ this.intent(owner, root);
883
+ }
884
+ if (this.pinPhase(root, "pins") !== "pinned") {
885
+ this.phase(root, "pin-pending");
886
+ }
887
+ });
435
888
  });
436
- }
437
- await this.ensure(root, signal);
438
- this.db.prepare("DELETE FROM stages WHERE id=?").run(session);
439
- });
889
+ await this.runPrepare("finish", root, signal, port, false);
890
+ await this.lock("finish", signal, () => {
891
+ this.transaction(() => {
892
+ if (!owner || this.allRoots().includes(root)) {
893
+ this.phase(root, "pinned");
894
+ }
895
+ this.queryRun("DELETE FROM stages WHERE id=?", session);
896
+ });
897
+ });
898
+ })(),
899
+ );
900
+ }
901
+ importBatch(
902
+ session: string,
903
+ entries: readonly { cid: string; write: () => Promise<unknown> }[],
904
+ root: string,
905
+ owner?: string,
906
+ signal?: AbortSignal,
907
+ onRetained?: () => Promise<void> | void,
908
+ port?: RetentionPort,
909
+ ): Promise<void> {
910
+ root = this.roots([root])[0]!;
911
+ const normalized = entries.map((entry) => ({
912
+ root: this.roots([entry.cid])[0]!,
913
+ write: entry.write,
914
+ }));
915
+ return this.track(
916
+ (async () => {
917
+ const { uniqueRoots, alreadyPinned } = await this.stageEntriesUnlocked(
918
+ "importBatch",
919
+ session,
920
+ normalized,
921
+ signal,
922
+ );
923
+ signal?.throwIfAborted();
924
+ await this.lock("importBatch", signal, () => {
925
+ this.transaction(() => {
926
+ for (const stagedRoot of uniqueRoots) {
927
+ if (
928
+ !alreadyPinned.has(stagedRoot) &&
929
+ this.pinPhase(stagedRoot, "pins") !== "pinned"
930
+ ) {
931
+ this.phase(stagedRoot, "staged");
932
+ }
933
+ }
934
+ if (owner) {
935
+ this.publish(owner, [root]);
936
+ this.intent(owner, root);
937
+ }
938
+ if (this.pinPhase(root, "pins") !== "pinned") {
939
+ this.phase(root, "pin-pending");
940
+ }
941
+ });
942
+ });
943
+ await this.runPrepare("importBatch", root, signal, port, false);
944
+ await this.lock("importBatch", signal, async () => {
945
+ this.transaction(() => {
946
+ if (!owner || this.allRoots().includes(root)) {
947
+ this.phase(root, "pinned");
948
+ }
949
+ this.queryRun("DELETE FROM stages WHERE id=?", session);
950
+ });
951
+ if (owner && onRetained) {
952
+ signal?.throwIfAborted();
953
+ await onRetained();
954
+ this.transaction(() => {
955
+ this.decrementIntent(owner, root);
956
+ });
957
+ }
958
+ });
959
+ })(),
960
+ );
440
961
  }
441
962
  private remove(
442
963
  root: string,
443
964
  signal?: AbortSignal,
444
965
  table: "pins" | "direct_pins" = "pins",
445
966
  ): boolean {
446
- const record = this.db
447
- .prepare(`SELECT phase FROM ${table} WHERE cid=?`)
448
- .get(root);
967
+ const record = this.queryGet(
968
+ `SELECT phase FROM ${table} WHERE cid=?`,
969
+ root,
970
+ );
449
971
  if (!record) return false;
450
972
  this.phase(root, "unpin-pending", table);
451
973
  signal?.throwIfAborted();
452
- this.db.prepare(`DELETE FROM ${table} WHERE cid=?`).run(root);
974
+ this.queryRun(`DELETE FROM ${table} WHERE cid=?`, root);
453
975
  return true;
454
976
  }
455
977
  unpin(root: string, signal?: AbortSignal): Promise<void> {
456
978
  root = this.roots([root])[0]!;
457
- return this.locked(signal, () => {
979
+ return this.locked("unpin", signal, () => {
458
980
  if (this.allRoots().includes(root))
459
981
  throw new Error("A participating owner still retains this root.");
460
982
  this.remove(root, signal);
@@ -462,7 +984,7 @@ export class Retention {
462
984
  }
463
985
  unpinDirect(root: string, signal?: AbortSignal): Promise<void> {
464
986
  root = this.roots([root])[0]!;
465
- return this.locked(signal, () => {
987
+ return this.locked("unpinDirect", signal, () => {
466
988
  if (this.allDirectRoots().includes(root))
467
989
  throw new Error(
468
990
  "A participating owner still retains this direct block.",
@@ -472,84 +994,137 @@ export class Retention {
472
994
  }
473
995
  private allRoots(): string[] {
474
996
  return this.roots([
475
- ...this.db
476
- .prepare("SELECT id FROM owners")
477
- .all()
478
- .flatMap((row) => this.readOwner(String(row.id))),
479
- ...this.db
480
- .prepare("SELECT cid FROM intents")
481
- .all()
482
- .map((row) => String(row.cid)),
483
- ...this.db
484
- .prepare("SELECT cid FROM stages")
485
- .all()
486
- .map((row) => String(row.cid)),
997
+ ...this.queryAll("SELECT id FROM owners").flatMap((row) =>
998
+ this.readOwner(String(row.id)),
999
+ ),
1000
+ ...this.queryAll("SELECT cid FROM intents").map((row) => String(row.cid)),
1001
+ ...this.queryAll("SELECT cid FROM stages").map((row) => String(row.cid)),
487
1002
  ]);
488
1003
  }
489
1004
  private allDirectRoots(): string[] {
490
1005
  return this.roots([
491
- ...this.db
492
- .prepare("SELECT id FROM direct_owners")
493
- .all()
494
- .flatMap((row) => this.readOwner(String(row.id), "direct_owners")),
495
- ...this.db
496
- .prepare("SELECT cid FROM direct_intents")
497
- .all()
498
- .map((row) => String(row.cid)),
1006
+ ...this.queryAll("SELECT id FROM direct_owners").flatMap((row) =>
1007
+ this.readOwner(String(row.id), "direct_owners"),
1008
+ ),
1009
+ ...this.queryAll("SELECT cid FROM direct_intents").map((row) =>
1010
+ String(row.cid),
1011
+ ),
499
1012
  ]);
500
1013
  }
501
1014
  reconcile(
502
1015
  owner: string,
503
1016
  roots: readonly string[] | (() => readonly string[]),
504
1017
  signal?: AbortSignal,
1018
+ port?: RetentionPort,
505
1019
  ): Promise<number> {
506
- return this.locked(signal, async () => {
507
- this.publish(owner, typeof roots === "function" ? roots() : roots, true);
508
- const marked = new Set(this.allRoots());
509
- // Complete the entire mark before removing any hint. Recheck real blocks, not reader caches.
510
- for (const root of marked) await this.ensure(root, signal);
511
- let removed = 0;
512
- for (const row of this.db.prepare("SELECT cid FROM pins").all()) {
513
- const root = String(row.cid);
514
- if (!marked.has(root) && this.remove(root, signal)) removed++;
515
- }
516
- return removed;
517
- });
1020
+ return this.reconcileInTable(
1021
+ "reconcile",
1022
+ owner,
1023
+ roots,
1024
+ "owners",
1025
+ "pins",
1026
+ false,
1027
+ signal,
1028
+ port,
1029
+ );
518
1030
  }
519
1031
  reconcileDirect(
520
1032
  owner: string,
521
1033
  roots: readonly string[] | (() => readonly string[]),
522
1034
  signal?: AbortSignal,
1035
+ port?: RetentionPort,
523
1036
  ): Promise<number> {
524
- return this.locked(signal, async () => {
525
- this.publish(
526
- owner,
527
- typeof roots === "function" ? roots() : roots,
528
- true,
529
- "direct_owners",
530
- );
531
- const marked = new Set(this.allDirectRoots());
532
- for (const root of marked) await this.ensureDirect(root, signal);
533
- let removed = 0;
534
- for (const row of this.db.prepare("SELECT cid FROM direct_pins").all()) {
535
- const root = String(row.cid);
536
- if (!marked.has(root) && this.remove(root, signal, "direct_pins"))
537
- removed++;
538
- }
539
- return removed;
540
- });
1037
+ return this.reconcileInTable(
1038
+ "reconcileDirect",
1039
+ owner,
1040
+ roots,
1041
+ "direct_owners",
1042
+ "direct_pins",
1043
+ true,
1044
+ signal,
1045
+ port,
1046
+ );
1047
+ }
1048
+ private reconcileInTable(
1049
+ op: string,
1050
+ owner: string,
1051
+ roots: readonly string[] | (() => readonly string[]),
1052
+ ownerTable: "owners" | "direct_owners",
1053
+ pinTable: "pins" | "direct_pins",
1054
+ direct: boolean,
1055
+ signal?: AbortSignal,
1056
+ port?: RetentionPort,
1057
+ ): Promise<number> {
1058
+ return this.track(
1059
+ (async () => {
1060
+ const phase1 = await this.lock(op, signal, () => {
1061
+ return this.transaction(() => {
1062
+ this.publish(
1063
+ owner,
1064
+ typeof roots === "function" ? roots() : roots,
1065
+ true,
1066
+ ownerTable,
1067
+ );
1068
+ const marked = direct ? this.allDirectRoots() : this.allRoots();
1069
+ const phases = this.pinPhases(pinTable);
1070
+ const toPrepare = marked.filter((root) => {
1071
+ const phase = phases.get(root);
1072
+ return phase !== "pinned" && phase !== "stage-pending";
1073
+ });
1074
+ if (toPrepare.length === 0) {
1075
+ const referenced = new Set(marked);
1076
+ let removed = 0;
1077
+ for (const row of this.queryAll(`SELECT cid FROM ${pinTable}`)) {
1078
+ const root = String(row.cid);
1079
+ if (
1080
+ !referenced.has(root) &&
1081
+ this.remove(root, signal, pinTable)
1082
+ )
1083
+ removed++;
1084
+ }
1085
+ return { toPrepare, removed };
1086
+ }
1087
+ for (const root of toPrepare) {
1088
+ this.phase(root, "pin-pending", pinTable);
1089
+ }
1090
+ return { toPrepare, removed: undefined };
1091
+ });
1092
+ });
1093
+ if (phase1.removed !== undefined) return phase1.removed;
1094
+ for (const root of phase1.toPrepare) {
1095
+ await this.runPrepare(op, root, signal, port, direct);
1096
+ }
1097
+ return this.lock(op, signal, () => {
1098
+ return this.transaction(() => {
1099
+ const referenced = new Set(
1100
+ direct ? this.allDirectRoots() : this.allRoots(),
1101
+ );
1102
+ for (const root of phase1.toPrepare) {
1103
+ if (referenced.has(root)) {
1104
+ this.phase(root, "pinned", pinTable);
1105
+ }
1106
+ }
1107
+ let removed = 0;
1108
+ for (const row of this.queryAll(`SELECT cid FROM ${pinTable}`)) {
1109
+ const root = String(row.cid);
1110
+ if (!referenced.has(root) && this.remove(root, signal, pinTable))
1111
+ removed++;
1112
+ }
1113
+ return removed;
1114
+ });
1115
+ });
1116
+ })(),
1117
+ );
541
1118
  }
542
1119
  pins(): string[] {
543
- return this.db
544
- .prepare("SELECT cid FROM pins WHERE phase='pinned' ORDER BY cid")
545
- .all()
546
- .map((row) => String(row.cid));
1120
+ return this.queryAll(
1121
+ "SELECT cid FROM pins WHERE phase='pinned' ORDER BY cid",
1122
+ ).map((row) => String(row.cid));
547
1123
  }
548
1124
  directPins(): string[] {
549
- return this.db
550
- .prepare("SELECT cid FROM direct_pins WHERE phase='pinned' ORDER BY cid")
551
- .all()
552
- .map((row) => String(row.cid));
1125
+ return this.queryAll(
1126
+ "SELECT cid FROM direct_pins WHERE phase='pinned' ORDER BY cid",
1127
+ ).map((row) => String(row.cid));
553
1128
  }
554
1129
  maintain<T>(
555
1130
  action: (references: {
@@ -561,47 +1136,36 @@ export class Retention {
561
1136
  }) => Promise<T>,
562
1137
  signal?: AbortSignal,
563
1138
  ): Promise<T> {
564
- return this.locked(signal, () =>
1139
+ return this.locked("maintain", signal, () =>
565
1140
  action({
566
1141
  pinned: this.pins(),
567
1142
  roots: this.roots([
568
- ...this.db
569
- .prepare("SELECT id FROM owners")
570
- .all()
571
- .flatMap((row) => this.readOwner(String(row.id))),
572
- ...this.db
573
- .prepare("SELECT cid FROM intents")
574
- .all()
575
- .map((row) => String(row.cid)),
576
- ...this.db
577
- .prepare(
578
- "SELECT cid FROM pins WHERE phase NOT IN ('staged','stage-pending')",
579
- )
580
- .all()
581
- .map((row) => String(row.cid)),
1143
+ ...this.queryAll("SELECT id FROM owners").flatMap((row) =>
1144
+ this.readOwner(String(row.id)),
1145
+ ),
1146
+ ...this.queryAll("SELECT cid FROM intents").map((row) =>
1147
+ String(row.cid),
1148
+ ),
1149
+ ...this.queryAll(
1150
+ "SELECT cid FROM pins WHERE phase NOT IN ('staged','stage-pending')",
1151
+ ).map((row) => String(row.cid)),
582
1152
  ]),
583
1153
  directPinned: this.directPins(),
584
1154
  directRoots: this.roots([
585
- ...this.db
586
- .prepare("SELECT id FROM direct_owners")
587
- .all()
588
- .flatMap((row) => this.readOwner(String(row.id), "direct_owners")),
589
- ...this.db
590
- .prepare("SELECT cid FROM direct_intents")
591
- .all()
592
- .map((row) => String(row.cid)),
593
- ...this.db
594
- .prepare(
595
- "SELECT cid FROM direct_pins WHERE phase NOT IN ('staged','stage-pending')",
596
- )
597
- .all()
598
- .map((row) => String(row.cid)),
1155
+ ...this.queryAll("SELECT id FROM direct_owners").flatMap((row) =>
1156
+ this.readOwner(String(row.id), "direct_owners"),
1157
+ ),
1158
+ ...this.queryAll("SELECT cid FROM direct_intents").map((row) =>
1159
+ String(row.cid),
1160
+ ),
1161
+ ...this.queryAll(
1162
+ "SELECT cid FROM direct_pins WHERE phase NOT IN ('staged','stage-pending')",
1163
+ ).map((row) => String(row.cid)),
599
1164
  ]),
600
1165
  // Import parents may arrive before their children; protect staged blocks individually.
601
- staged: this.db
602
- .prepare("SELECT DISTINCT cid FROM stages")
603
- .all()
604
- .map((row) => String(row.cid)),
1166
+ staged: this.queryAll("SELECT DISTINCT cid FROM stages").map((row) =>
1167
+ String(row.cid),
1168
+ ),
605
1169
  }),
606
1170
  );
607
1171
  }