@opendatalabs/personal-server-ts-core 1.43.1 → 1.43.2

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.
Files changed (71) hide show
  1. package/dist/api/owner-connector-delete.d.ts +20 -2
  2. package/dist/api/owner-connector-delete.d.ts.map +1 -1
  3. package/dist/api/owner-connector-delete.js +18 -6
  4. package/dist/api/owner-connector-delete.js.map +1 -1
  5. package/dist/localdb/cycle.d.ts +7 -4
  6. package/dist/localdb/cycle.d.ts.map +1 -1
  7. package/dist/localdb/cycle.js +51 -31
  8. package/dist/localdb/cycle.js.map +1 -1
  9. package/dist/localdb/delete-status.d.ts +53 -0
  10. package/dist/localdb/delete-status.d.ts.map +1 -0
  11. package/dist/localdb/delete-status.js +19 -0
  12. package/dist/localdb/delete-status.js.map +1 -0
  13. package/dist/localdb/delete.d.ts +48 -2
  14. package/dist/localdb/delete.d.ts.map +1 -1
  15. package/dist/localdb/delete.js +508 -42
  16. package/dist/localdb/delete.js.map +1 -1
  17. package/dist/localdb/index.d.ts +2 -0
  18. package/dist/localdb/index.d.ts.map +1 -1
  19. package/dist/localdb/index.js +1 -0
  20. package/dist/localdb/index.js.map +1 -1
  21. package/dist/localdb/legacy-delete.d.ts +89 -0
  22. package/dist/localdb/legacy-delete.d.ts.map +1 -0
  23. package/dist/localdb/legacy-delete.js +279 -0
  24. package/dist/localdb/legacy-delete.js.map +1 -0
  25. package/dist/localdb/log-erase.d.ts +55 -4
  26. package/dist/localdb/log-erase.d.ts.map +1 -1
  27. package/dist/localdb/log-erase.js +76 -8
  28. package/dist/localdb/log-erase.js.map +1 -1
  29. package/dist/localdb/purge.d.ts +42 -9
  30. package/dist/localdb/purge.d.ts.map +1 -1
  31. package/dist/localdb/purge.js +38 -4
  32. package/dist/localdb/purge.js.map +1 -1
  33. package/dist/localdb/schema.d.ts.map +1 -1
  34. package/dist/localdb/schema.js +39 -0
  35. package/dist/localdb/schema.js.map +1 -1
  36. package/dist/localdb/sync.d.ts +8 -0
  37. package/dist/localdb/sync.d.ts.map +1 -1
  38. package/dist/localdb/sync.js +30 -6
  39. package/dist/localdb/sync.js.map +1 -1
  40. package/dist/stream-sync/registry.d.ts.map +1 -1
  41. package/dist/stream-sync/registry.js +25 -0
  42. package/dist/stream-sync/registry.js.map +1 -1
  43. package/dist/sync/delete-data-port.d.ts +10 -0
  44. package/dist/sync/delete-data-port.d.ts.map +1 -1
  45. package/dist/sync/delete-data-port.js +70 -29
  46. package/dist/sync/delete-data-port.js.map +1 -1
  47. package/dist/sync/engine/sync-manager.d.ts +7 -2
  48. package/dist/sync/engine/sync-manager.d.ts.map +1 -1
  49. package/dist/sync/engine/sync-manager.js +6 -3
  50. package/dist/sync/engine/sync-manager.js.map +1 -1
  51. package/dist/sync/gateway-refusal.d.ts +36 -0
  52. package/dist/sync/gateway-refusal.d.ts.map +1 -0
  53. package/dist/sync/gateway-refusal.js +45 -0
  54. package/dist/sync/gateway-refusal.js.map +1 -0
  55. package/dist/sync/tombstone-resubmits.d.ts +3 -1
  56. package/dist/sync/tombstone-resubmits.d.ts.map +1 -1
  57. package/dist/sync/tombstone-resubmits.js.map +1 -1
  58. package/dist/sync/workers/delete.d.ts +6 -0
  59. package/dist/sync/workers/delete.d.ts.map +1 -1
  60. package/dist/sync/workers/delete.js +29 -30
  61. package/dist/sync/workers/delete.js.map +1 -1
  62. package/dist/test-utils/legacy-delete-ports.d.ts +24 -0
  63. package/dist/test-utils/legacy-delete-ports.d.ts.map +1 -0
  64. package/dist/test-utils/legacy-delete-ports.js +91 -0
  65. package/dist/test-utils/legacy-delete-ports.js.map +1 -0
  66. package/dist/test-utils/legacy-gateway-fake.d.ts +88 -0
  67. package/dist/test-utils/legacy-gateway-fake.d.ts.map +1 -0
  68. package/dist/test-utils/legacy-gateway-fake.js +243 -0
  69. package/dist/test-utils/legacy-gateway-fake.js.map +1 -0
  70. package/dist-test/tsconfig.tsbuildinfo +1 -1
  71. package/package.json +2 -2
@@ -15,9 +15,68 @@ import { keccakOf } from "../stream-sync/crypto-port.js";
15
15
  import { classifyControl, controlHashes, controlScope, deriveKeyCheck, parseScope, } from "@opendatalabs/personal-server-ts-stream-sync";
16
16
  import { RegistryRefusedError } from "../stream-sync/ports.js";
17
17
  import { commitFences } from "./delete-batch.js";
18
- import { purgeConnection } from "./purge.js";
18
+ import { blocked, PART_DONE, PART_PENDING, } from "./delete-status.js";
19
+ import { retireLegacyOf } from "./legacy-delete.js";
20
+ import { KEEP_TOMBSTONE_CONFLICT, purgeConnection } from "./purge.js";
19
21
  import { ConnectionLifetimeChanged, formatLifetime, holdsLifetime, parseLifetime, } from "./delete-lifetime.js";
20
22
  export { ConnectionLifetimeChanged, InvalidConnectionLifetime, } from "./delete-lifetime.js";
23
+ /**
24
+ * The storage part of a delete from one erasure report. `done` only on this
25
+ * device's own evidence that every object of the deleted lifetime is gone: a
26
+ * complete enumeration it made before erasing, and every delete acknowledged,
27
+ * with no body piece left. Every other path says what stands in the way, and
28
+ * a tombstone the report never mentions is not judged yet.
29
+ */
30
+ function storagePartOf(report, tombstones) {
31
+ if (report.unavailable)
32
+ return blocked("needs_another_device");
33
+ // A scan that could not list the deleted connections (`pending` with no
34
+ // connection to show for it) has judged nothing: it is not "all erased".
35
+ let part = report.pending ? PART_PENDING : PART_DONE;
36
+ const worse = (next) => {
37
+ if (rankOf(next) > rankOf(part))
38
+ part = next;
39
+ };
40
+ // A namespace a local connection holds (a reconnect, or another lifetime)
41
+ // shares its log scope with the deleted one: nothing of it is erased, and
42
+ // nothing shows it gone. The report lists these, and they are final until a
43
+ // newer delete of the namespace.
44
+ for (const ns of report.skipped)
45
+ if (tombstones.has(ns))
46
+ worse(blocked("re_added"));
47
+ // A namespace whose delete this device confirmed is either judged or listed
48
+ // as skipped. One the report names neither way is not judged yet.
49
+ const named = new Set([
50
+ ...report.connections.map((c) => c.ns),
51
+ ...report.skipped,
52
+ ]);
53
+ for (const ns of tombstones.keys())
54
+ if (!named.has(ns))
55
+ worse(PART_PENDING);
56
+ for (const { outcome } of report.connections)
57
+ worse(outcome.kind === "pending"
58
+ ? PART_PENDING
59
+ : outcome.kind === "stopped"
60
+ ? outcome.why === "rolled-back"
61
+ ? blocked("tombstone_rolled_back")
62
+ : outcome.why === "head-unreadable"
63
+ ? blocked("log_unreadable")
64
+ : // A reconnect replaced the lifetime: its objects share the
65
+ // log scope with the new one and are not deleted.
66
+ blocked("re_added")
67
+ : outcome.retained > 0
68
+ ? blocked("body_pieces_retained")
69
+ : outcome.witnessed
70
+ ? PART_DONE
71
+ : blocked("erased_elsewhere"));
72
+ return part;
73
+ }
74
+ const rankOf = (p) => p.state === "blocked" ? 2 : p.state === "pending" ? 1 : 0;
75
+ const KEEP_TOMBSTONE_SQL = `INSERT INTO delete_tombstones(connector, ns, version) VALUES (?, ?, ?)
76
+ ${KEEP_TOMBSTONE_CONFLICT}`;
77
+ const BOTH = { legacy: true, storage: true };
78
+ const NONE = { legacy: false, storage: false };
79
+ const isRolledBack = (o) => o.kind === "stopped" && o.why === "rolled-back";
21
80
  export class ConnectionStoppedError extends Error {
22
81
  connector;
23
82
  constructor(connector) {
@@ -94,10 +153,108 @@ export function createConnectionDeleter(originalDeps, options = {}) {
94
153
  const requests = new Set();
95
154
  /** Erasures running, by connector: one at a time per connector. */
96
155
  const erasures = new Map();
97
- /** Connectors whose erasure ended `pending`, until a later pass finishes it. */
98
- const erasing = new Set();
156
+ /**
157
+ * Connectors whose erasure is owed, with the stages a later pass must run:
158
+ * fresh news (a delete settled) owes both, an unfinished pass owes only the
159
+ * stage that can still make progress. What a part shows is a separate fact
160
+ * (`judged`): a stage that ended `blocked` is not owed again.
161
+ *
162
+ * A part that reads `pending` always has a pass owed behind it: here while
163
+ * the process runs, and after a restart in the start sweep, which reads the
164
+ * tombstone rows with no verdict (`done_at`).
165
+ */
166
+ const erasing = new Map();
167
+ const owe = (connector, which = BOTH) => {
168
+ const held = erasing.get(connector);
169
+ erasing.set(connector, {
170
+ legacy: which.legacy || !!held?.legacy,
171
+ storage: which.storage || !!held?.storage,
172
+ });
173
+ };
174
+ /** What the legacy stage keeps between this device's passes (`LegacyMemory`). */
175
+ const refusals = new Map();
176
+ const erasedSlots = new Map();
99
177
  /** The start sweep (deletes settled before this process) is still owed. */
100
- let sweepOwed = options.eraseLogs !== undefined;
178
+ const owesErasure = options.eraseLogs !== undefined || !!options.legacy;
179
+ let sweepOwed = owesErasure;
180
+ /**
181
+ * What the last pass here judged of each connector's delete. Dropped when a
182
+ * newer delete's tombstone is learned (`learnTombstone`): the pass that
183
+ * follows judges it again.
184
+ */
185
+ const judged = new Map();
186
+ /**
187
+ * The delete a connector's cached verdict belongs to: the control tombstone
188
+ * each namespace's delete confirmed, by registry version. A tombstone moves
189
+ * only forward, so a higher one is a newer delete. The stages judge against
190
+ * these tombstones (`LegacyMemory.tombstones`), and so does the cache: a
191
+ * verdict is kept only under the tombstones it was judged for. One notion of
192
+ * "this delete" drives both.
193
+ */
194
+ const tombstones = new Map();
195
+ /** A copy: a pass judges the tombstones it started with, whatever is learned meanwhile. */
196
+ const tombstonesOf = (connector) => new Map(tombstones.get(connector));
197
+ const deleteKey = (connector) => [...tombstonesOf(connector)]
198
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
199
+ .map(([ns, version]) => `${ns}@${version}`)
200
+ .join(",");
201
+ /**
202
+ * A delete confirmed this tombstone: a higher one than known is a newer
203
+ * delete, and answers true. The same one again is news of nothing.
204
+ */
205
+ function learnTombstone(connector, ns, version) {
206
+ const held = tombstones.get(connector) ?? new Map();
207
+ if ((held.get(ns) ?? 0) >= version)
208
+ return false;
209
+ held.set(ns, version);
210
+ tombstones.set(connector, held);
211
+ // What an earlier pass judged, and what the gateway refused, say nothing
212
+ // of a newer delete: this is the only place either is dropped.
213
+ judged.delete(connector);
214
+ refusals.delete(connector);
215
+ return true;
216
+ }
217
+ /**
218
+ * The tombstones the local database holds (`delete_tombstones`), learned
219
+ * once before the first pass: what a restart finds of the deletes this
220
+ * device confirmed. Written by the transactions that learn them (a fence
221
+ * landing, a purge), so a restart never has to read the control head to
222
+ * tell which delete it is erasing.
223
+ */
224
+ const loadTombstones = async () => {
225
+ const rows = await deps.db.query("SELECT connector, ns, version FROM delete_tombstones");
226
+ for (const row of rows)
227
+ learnTombstone(row.connector, row.ns, Number(row.version));
228
+ };
229
+ let hydration = null;
230
+ const hydrated = () => (hydration ??= loadTombstones().catch((error) => {
231
+ hydration = null;
232
+ throw error;
233
+ }));
234
+ /**
235
+ * The delete's three parts are all done: its verdict is final. It is kept
236
+ * with the delete's identity (`done_at` on the tombstone rows, at the
237
+ * versions this pass judged), so a restart reads it back and a newer
238
+ * delete's tombstone, written meanwhile, is left without one.
239
+ */
240
+ async function recordVerdict(connector, status) {
241
+ if (stop.signal.aborted ||
242
+ erasing.has(connector) ||
243
+ flights.has(connector) ||
244
+ ![status.fence, status.legacy, status.storage].every((part) => part.state === "done"))
245
+ return;
246
+ const held = tombstonesOf(connector);
247
+ if (held.size === 0)
248
+ return;
249
+ await deps.db.batch([...held].map(([ns, version]) => ({
250
+ sql: "UPDATE delete_tombstones SET done_at = CAST(strftime('%s','now') AS INTEGER) * 1000 WHERE connector=? AND ns=? AND version=? AND done_at IS NULL",
251
+ params: [connector, ns, version],
252
+ })));
253
+ }
254
+ /** The durable rows of a connector's delete: its identity and whether it finished. */
255
+ const rowsOf = (connector) => deps.db.query("SELECT ns, version, done_at FROM delete_tombstones WHERE connector=?", [connector]);
256
+ /** Every row says the delete finished: all three parts were done at these versions. */
257
+ const finishedIn = (rows) => rows.length > 0 && rows.every((row) => row.done_at !== null);
101
258
  /**
102
259
  * The control rows the plan listed, by delete id, then by scope. Only a
103
260
  * delete this process just planned has one; the landing takes it. Each
@@ -127,11 +284,17 @@ export function createConnectionDeleter(originalDeps, options = {}) {
127
284
  id: row.delete_id,
128
285
  };
129
286
  };
287
+ // Each fence the intent holds is a tombstone the delete confirmed: written
288
+ // in the transaction that records the fence, so the two never part.
130
289
  const save = (connector, intent) => deps.db.batch([
131
290
  {
132
291
  sql: "INSERT OR REPLACE INTO delete_intents(connector,delete_id,intent) VALUES (?,?,?)",
133
292
  params: [connector, intent.id, JSON.stringify(intent)],
134
293
  },
294
+ ...(intent.fences ?? []).map((fence) => ({
295
+ sql: KEEP_TOMBSTONE_SQL,
296
+ params: [connector, fence.ns, fence.version],
297
+ })),
135
298
  ]);
136
299
  const clear = (connector, id) => deps.db.batch([
137
300
  {
@@ -139,6 +302,90 @@ export function createConnectionDeleter(originalDeps, options = {}) {
139
302
  params: [connector, id],
140
303
  },
141
304
  ]);
305
+ /** The connector's control rows in a listing, each read as the control head it is. */
306
+ function* controlRowsOf(connector, entries, hashes) {
307
+ for (const entry of entries) {
308
+ const parsed = parseScope(entry.scope);
309
+ if (parsed?.kind !== "control" || parsed.connector !== connector)
310
+ continue;
311
+ yield {
312
+ entry,
313
+ ns: parsed.ns,
314
+ current: classifyControl(entry.read, hashes),
315
+ };
316
+ }
317
+ }
318
+ /**
319
+ * The one comparison between a delete's verdict and the newest tombstone
320
+ * this device can see. `ended` is what a registry listing shows of the
321
+ * connector: a tombstone above the one held for its namespace is a newer
322
+ * delete. It is written down (the same statement as a landed fence, which
323
+ * clears the connector's verdicts), learned, and owed to both stages. Every
324
+ * path that reads a verdict (a status, a request, an erasure pass, the
325
+ * start sweep) calls this first, so none can answer for a delete the
326
+ * registry has already moved past. A connector with no delete known here
327
+ * is not this device's to adopt: a sync of the control row does that, and
328
+ * names the tombstone. For a connector with a delete on record, a tombstone
329
+ * in any namespace counts, one this device holds no row or connection for
330
+ * too: the connector's delete is what the verdict speaks for, and the
331
+ * erasure pass judges every deleted namespace the registry lists.
332
+ */
333
+ async function adoptEnded(connector, ended, options = {}) {
334
+ if (ended.size === 0)
335
+ return false;
336
+ await hydrated();
337
+ const held = tombstones.get(connector);
338
+ if (!held)
339
+ return false;
340
+ const newer = [...ended].filter(([ns, version]) => version > (held.get(ns) ?? 0));
341
+ if (newer.length === 0)
342
+ return false;
343
+ await deps.db.batch([
344
+ ...newer.map(([ns, version]) => ({
345
+ sql: KEEP_TOMBSTONE_SQL,
346
+ params: [connector, ns, version],
347
+ })),
348
+ {
349
+ sql: "UPDATE delete_tombstones SET done_at = NULL WHERE connector=?",
350
+ params: [connector],
351
+ },
352
+ ]);
353
+ for (const [ns, version] of newer)
354
+ learnTombstone(connector, ns, version);
355
+ if (owesErasure && options.owe !== false)
356
+ owe(connector);
357
+ return true;
358
+ }
359
+ /**
360
+ * `adoptEnded` for connectors whose delete is known here, from one fresh
361
+ * listing. A registry that cannot be listed leaves what is known standing:
362
+ * the newest tombstone this device can see is the one it already holds.
363
+ */
364
+ async function refreshTombstones(connectors, options = {}) {
365
+ const newer = new Set();
366
+ try {
367
+ await hydrated();
368
+ const known = [...connectors].filter((c) => tombstones.has(c));
369
+ if (known.length === 0)
370
+ return newer;
371
+ const [hashes, entries] = await Promise.all([
372
+ hashesOf(),
373
+ deps.registry.listControlRows(),
374
+ ]);
375
+ for (const connector of known) {
376
+ const ended = new Map();
377
+ for (const { ns, current } of controlRowsOf(connector, entries, hashes))
378
+ if (current.kind === "deleted")
379
+ ended.set(ns, current.version);
380
+ if (await adoptEnded(connector, ended, options))
381
+ newer.add(connector);
382
+ }
383
+ }
384
+ catch (error) {
385
+ deps.logger.warn({ error: error instanceof Error ? error.message : String(error) }, "stream sync: the registry's newest delete tombstones could not be read");
386
+ }
387
+ return newer;
388
+ }
142
389
  /**
143
390
  * The pins, from one listing of the control rows. A listing is as fresh as a
144
391
  * read of the row, and taken after this call; the row may still move before
@@ -159,22 +406,21 @@ export function createConnectionDeleter(originalDeps, options = {}) {
159
406
  const listing = new Map();
160
407
  // The control rows already tombstoned, by namespace: the end of a lifetime.
161
408
  const ended = new Map();
162
- for (const entry of entries) {
163
- const parsed = parseScope(entry.scope);
164
- if (parsed?.kind !== "control" || parsed.connector !== connector)
165
- continue;
166
- const current = classifyControl(entry.read, hashes);
409
+ for (const { entry, ns, current } of controlRowsOf(connector, entries, hashes)) {
167
410
  listing.set(entry.scope, { ...entry.read });
168
411
  if (current.kind === "deleted")
169
- ended.set(parsed.ns, current.version);
412
+ ended.set(ns, current.version);
170
413
  // A control row of another key ends the same way: its tombstone is the
171
414
  // same for every key.
172
415
  if (current.kind === "active" || current.kind === "foreign")
173
416
  pins.push({
174
- ns: parsed.ns,
417
+ ns,
175
418
  version: current.kind === "active" ? current.generation : current.version,
176
419
  });
177
420
  }
421
+ // A listing is the newest word on the delete: a tombstone newer than the
422
+ // one held ends the verdict held, whoever asked.
423
+ await adoptEnded(connector, ended);
178
424
  return { intent: { id: deps.newOp(), pins }, listing, ended };
179
425
  }
180
426
  async function readConnectionLifetime(connector) {
@@ -210,7 +456,9 @@ export function createConnectionDeleter(originalDeps, options = {}) {
210
456
  const rows = await deps.db.query("SELECT ns FROM connections WHERE connector=?", [connector]);
211
457
  return rows.some((row) => !intent.pins.some((p) => p.ns === row.ns));
212
458
  }
213
- async function purgeLocal(connector, intent, held = new Set()) {
459
+ async function purgeLocal(connector, intent, held = new Set(),
460
+ /** The tombstones the registry listing showed, by namespace. */
461
+ ended = new Map()) {
214
462
  const connections = await deps.db.query("SELECT connection_id,ns,generation,control_version FROM connections WHERE connector=?", [connector]);
215
463
  for (const connection of connections) {
216
464
  const pin = intent.pins.find((p) => p.ns === connection.ns);
@@ -234,9 +482,24 @@ export function createConnectionDeleter(originalDeps, options = {}) {
234
482
  : deps.queue.run(id, kind, work),
235
483
  },
236
484
  };
237
- await purgeConnection(nested, connection.connection_id, {
238
- controlVersion: pin ? pin.version + 1 : connection.control_version,
239
- });
485
+ // The purge may run ahead of its fence. Only a tombstone the delete
486
+ // confirmed is the delete's identity: a fence that landed, or one the
487
+ // registry listing shows. A version this purge expects, or the 0 of
488
+ // a connection no row names, is not written to the ledger.
489
+ const landed = pin
490
+ ? (intent.fences ?? []).find((f) => f.ns === pin.ns)?.version
491
+ : undefined;
492
+ const listed = ended.get(connection.ns);
493
+ await purgeConnection(nested, connection.connection_id, landed !== undefined
494
+ ? { controlVersion: landed }
495
+ : listed !== undefined && !pin
496
+ ? { controlVersion: listed }
497
+ : {
498
+ controlVersion: pin
499
+ ? pin.version + 1
500
+ : connection.control_version,
501
+ confirmed: false,
502
+ });
240
503
  await deps.db.batch([
241
504
  {
242
505
  sql: "UPDATE run_streams SET decision='discarded',reason='control_deleted',replace=0 WHERE run_id IN (SELECT run_id FROM runs WHERE connection_id=?)",
@@ -347,6 +610,8 @@ export function createConnectionDeleter(originalDeps, options = {}) {
347
610
  { ns: pin.ns, version: pin.version + 1 },
348
611
  ],
349
612
  }));
613
+ // The tombstone this delete confirmed: it is this delete's identity.
614
+ const confirmed = (pin) => learnTombstone(connector, pin.ns, pin.version + 1);
350
615
  try {
351
616
  const unfenced = intent.pins.filter((p) => !fenced(p.ns));
352
617
  if (unfenced.length > 0) {
@@ -373,8 +638,10 @@ export function createConnectionDeleter(originalDeps, options = {}) {
373
638
  rows,
374
639
  });
375
640
  for (const [i, pin] of unfenced.entries())
376
- if (turns[i] === "committed")
641
+ if (turns[i] === "committed") {
377
642
  await recordFence(pin);
643
+ confirmed(pin);
644
+ }
378
645
  }
379
646
  // The per-row pass: each fence the request did not store.
380
647
  await settleAll(intent.pins
@@ -382,6 +649,7 @@ export function createConnectionDeleter(originalDeps, options = {}) {
382
649
  .map(async (pin) => {
383
650
  await landFence(connector, pin, hashes);
384
651
  await recordFence(pin);
652
+ confirmed(pin);
385
653
  }));
386
654
  fencesEnded(true);
387
655
  await saved;
@@ -400,32 +668,112 @@ export function createConnectionDeleter(originalDeps, options = {}) {
400
668
  }
401
669
  /**
402
670
  * The namespaces of `connector` whose delete has not settled here: a local
403
- * connection in them is not purged (a connection added again, or one the
404
- * purge has not reached, is another lifetime). `null` while a delete of the
405
- * connector is in flight: nothing of it is settled. One namespace's live
406
- * connection never holds back another's erasure: a delete that names a
407
- * lifetime leaves a local connection no pin names, by design.
671
+ * connection in them is not purged and is not one the delete ended (a
672
+ * connection added again, or one registered after the tombstone, is another
673
+ * lifetime). `null` while a delete of the connector is in flight: nothing of
674
+ * it is settled. One namespace's live connection never holds back another's
675
+ * erasure: a delete that names a lifetime leaves a local connection no pin
676
+ * names, by design.
677
+ *
678
+ * A connection still `active` at a generation the held tombstone ended is
679
+ * stale, not a re-add: its purge is only waiting for the next sync of the
680
+ * control row (a status read or the start sweep can learn the tombstone
681
+ * first). A reconnect registers a higher generation, and one that never
682
+ * registered has no generation to compare: both still hold the namespace.
408
683
  */
409
684
  async function unsettledNamespaces(connector) {
410
685
  const [intent] = await deps.db.query("SELECT 1 FROM delete_intents WHERE connector=?", [connector]);
411
686
  if (intent)
412
687
  return null;
413
- const live = await deps.db.query("SELECT DISTINCT ns FROM connections WHERE connector=? AND control_state<>'deleted'", [connector]);
414
- return new Set(live.map((row) => row.ns));
688
+ const live = await deps.db.query("SELECT ns, control_state, generation FROM connections WHERE connector=? AND control_state<>'deleted'", [connector]);
689
+ const held = tombstonesOf(connector);
690
+ return new Set(live
691
+ .filter((row) => !(row.control_state === "active" &&
692
+ Number(row.generation) <= (held.get(row.ns) ?? 0)))
693
+ .map((row) => row.ns));
415
694
  }
416
695
  /**
417
696
  * One erasure pass for `connector`; answers whether it is unfinished. The
418
697
  * caller has consumed the connector's queue entry: what is queued after
419
698
  * that is news from while the pass runs, and this does not touch it.
420
699
  */
421
- async function eraseSettled(connector) {
700
+ async function eraseSettled(connector, owed) {
422
701
  try {
702
+ // What this device confirmed of the delete, before a restart too.
703
+ await hydrated();
423
704
  if (stop.signal.aborted)
424
- return false;
705
+ return NONE;
706
+ }
707
+ catch (error) {
708
+ deps.logger.warn({
709
+ connector,
710
+ error: error instanceof Error ? error.message : String(error),
711
+ }, "stream sync: the confirmed delete tombstones could not be read");
712
+ return owed;
713
+ }
714
+ // The newest tombstone the registry shows, before anything is judged by
715
+ // the one held: a newer delete is judged whole by this pass.
716
+ if ((await refreshTombstones([connector], { owe: false })).size > 0)
717
+ owed = BOTH;
718
+ const held = tombstonesOf(connector);
719
+ const key = deleteKey(connector);
720
+ const judge = (part) => judgeFor(connector, key, part);
721
+ try {
722
+ // A delete whose verdict is final has nothing left to judge: the same
723
+ // tombstone read again (a sync cycle, a restart) changes nothing.
724
+ if (finishedIn(await rowsOf(connector)))
725
+ return NONE;
425
726
  const skipNamespaces = await unsettledNamespaces(connector);
426
727
  if (skipNamespaces === null)
427
- return false;
428
- return (await options.eraseLogs(connector, stop.signal, { skipNamespaces })).pending;
728
+ return NONE;
729
+ // The legacy copy first: it needs no log port, so a device that cannot
730
+ // erase storage still retires it. A stage that is not owed keeps what
731
+ // its last pass judged and sends nothing.
732
+ let left = NONE;
733
+ if (options.legacy && owed.legacy) {
734
+ const legacy = options.legacy();
735
+ if (!legacy) {
736
+ judge({ legacy: blocked("needs_another_device") });
737
+ }
738
+ else {
739
+ let refused = refusals.get(connector);
740
+ if (!refused)
741
+ refusals.set(connector, (refused = new Map()));
742
+ const outcome = await retireLegacyOf({
743
+ ...deps,
744
+ memory: {
745
+ refused,
746
+ erased: erasedSlots,
747
+ tombstones: held,
748
+ },
749
+ }, legacy, connector, stop.signal);
750
+ judge({
751
+ legacy: outcome.part,
752
+ ...(outcome.rolledBack && { rolledBack: true }),
753
+ });
754
+ // Retry is decided by the part as well as by the stage's own flag:
755
+ // a part that reads pending always has a pass queued behind it.
756
+ left = {
757
+ ...left,
758
+ legacy: outcome.pending || outcome.part.state === "pending",
759
+ };
760
+ }
761
+ }
762
+ if (!options.eraseLogs || !owed.storage)
763
+ return left;
764
+ const report = await options.eraseLogs(connector, stop.signal, {
765
+ skipNamespaces,
766
+ tombstones: held,
767
+ });
768
+ const storage = storagePartOf(report, held);
769
+ judge({ storage });
770
+ if (report.connections.some((c) => isRolledBack(c.outcome)))
771
+ judge({ rolledBack: true });
772
+ // The same report drives the part and the retry.
773
+ return {
774
+ ...left,
775
+ storage: report.pending || storage.state === "pending",
776
+ };
429
777
  }
430
778
  catch (error) {
431
779
  // The eraser reports a failure as pending; this is its own bug or a
@@ -434,9 +782,39 @@ export function createConnectionDeleter(originalDeps, options = {}) {
434
782
  connector,
435
783
  error: error instanceof Error ? error.message : String(error),
436
784
  }, "stream sync: connection log erasure failed");
437
- return true;
785
+ return owed;
438
786
  }
439
787
  }
788
+ /**
789
+ * The stages of the delete known now that no pass has given a verdict a
790
+ * later pass cannot change: not judged yet, still pending, or waiting for
791
+ * a device that can (`needs_another_device`).
792
+ */
793
+ function unfinishedStages(connector) {
794
+ const seen = judged.get(connector);
795
+ const open = (part) => part === undefined ||
796
+ part.state === "pending" ||
797
+ (part.state === "blocked" && part.reason === "needs_another_device");
798
+ return { legacy: open(seen?.legacy), storage: open(seen?.storage) };
799
+ }
800
+ /**
801
+ * Forget a storage verdict of `blocked(re_added)`: it says a local
802
+ * connection held a namespace, and one was purged since.
803
+ */
804
+ function releaseReAdded(connector) {
805
+ const seen = judged.get(connector);
806
+ const storage = seen?.storage;
807
+ if (storage?.state !== "blocked" || storage.reason !== "re_added")
808
+ return;
809
+ const { storage: _released, ...rest } = seen;
810
+ judged.set(connector, rest);
811
+ }
812
+ /** Keeps a verdict only if the delete it judged is still the connector's newest. */
813
+ function judgeFor(connector, key, part) {
814
+ if (key !== deleteKey(connector))
815
+ return;
816
+ judged.set(connector, { ...judged.get(connector), ...part });
817
+ }
440
818
  /**
441
819
  * One erasure at a time per connector. A caller while one runs queues the
442
820
  * connector again, since what it knows (a delete settled) may be newer than
@@ -445,22 +823,35 @@ export function createConnectionDeleter(originalDeps, options = {}) {
445
823
  * entry the pass itself leaves (`pending`) waits for the retry loop.
446
824
  */
447
825
  function eraseLogsOf(connector) {
448
- if (!options.eraseLogs)
826
+ if (!owesErasure)
449
827
  return Promise.resolve();
450
828
  const held = erasures.get(connector);
451
829
  if (held) {
452
- erasing.add(connector);
830
+ owe(connector);
453
831
  return held;
454
832
  }
455
833
  const run = (async () => {
456
834
  let again;
457
835
  do {
836
+ const owed = erasing.get(connector) ?? BOTH;
458
837
  erasing.delete(connector);
459
- const unfinished = await eraseSettled(connector);
838
+ const unfinished = await eraseSettled(connector, owed);
460
839
  again = erasing.has(connector) && !stop.signal.aborted;
461
- if (unfinished)
462
- erasing.add(connector);
840
+ if (unfinished.legacy || unfinished.storage) {
841
+ owe(connector, unfinished);
842
+ options.onUnfinished?.();
843
+ }
463
844
  } while (again);
845
+ // Settled for good: the delete's tombstones are not needed any more.
846
+ try {
847
+ await recordVerdict(connector, await deleteStatus(connector));
848
+ }
849
+ catch (error) {
850
+ deps.logger.warn({
851
+ connector,
852
+ error: error instanceof Error ? error.message : String(error),
853
+ }, "stream sync: the settled delete's verdict could not be recorded");
854
+ }
464
855
  })().finally(() => {
465
856
  if (erasures.get(connector) === run)
466
857
  erasures.delete(connector);
@@ -468,6 +859,40 @@ export function createConnectionDeleter(originalDeps, options = {}) {
468
859
  erasures.set(connector, run);
469
860
  return run;
470
861
  }
862
+ /**
863
+ * The three parts of `connector`'s delete (`delete-status.ts`). While a
864
+ * delete is landing, or before a pass has judged a part, that part is
865
+ * `pending`: it is only `done` or `blocked` on a pass's word.
866
+ */
867
+ async function deleteStatus(connector) {
868
+ // A verdict speaks for the tombstone it was judged at: a newer one the
869
+ // registry shows ends it before it is read.
870
+ await refreshTombstones([connector]);
871
+ return deleteStatusSnapshot(connector);
872
+ }
873
+ async function deleteStatusSnapshot(connector) {
874
+ const [open] = await deps.db.query("SELECT 1 FROM delete_intents WHERE connector=?", [connector]);
875
+ if (open)
876
+ return {
877
+ fence: PART_PENDING,
878
+ legacy: PART_PENDING,
879
+ storage: PART_PENDING,
880
+ };
881
+ // A verdict that is final is read from the rows that hold it, so a
882
+ // restart, a reconnect or a sync cycle cannot turn it back into pending.
883
+ if (finishedIn(await rowsOf(connector)))
884
+ return { fence: PART_DONE, legacy: PART_DONE, storage: PART_DONE };
885
+ const seen = judged.get(connector);
886
+ // A host with no stage cannot do it: another device of the account must.
887
+ // A stage no pass has judged is not done: `done` is only ever a pass's
888
+ // word, from evidence it read.
889
+ const unjudged = (can) => !can ? blocked("needs_another_device") : PART_PENDING;
890
+ return {
891
+ fence: seen?.rolledBack ? blocked("tombstone_rolled_back") : PART_DONE,
892
+ legacy: seen?.legacy ?? unjudged(!!options.legacy),
893
+ storage: seen?.storage ?? unjudged(!!options.eraseLogs),
894
+ };
895
+ }
471
896
  function schedule(connector) {
472
897
  const held = flights.get(connector);
473
898
  if (held)
@@ -483,6 +908,10 @@ export function createConnectionDeleter(originalDeps, options = {}) {
483
908
  });
484
909
  const landing = { fenced, done };
485
910
  flights.set(connector, landing);
911
+ // Owed from the start, so a status read between the landing's end and
912
+ // the erasure's start does not call the connector settled.
913
+ if (owesErasure)
914
+ owe(connector);
486
915
  // A delete that settled is erased from storage, outside its own queue.
487
916
  void done.then(() => eraseLogsOf(connector), () => undefined);
488
917
  return landing;
@@ -531,7 +960,7 @@ export function createConnectionDeleter(originalDeps, options = {}) {
531
960
  if (open && (empty || samePlan(open, planned.intent)))
532
961
  return open;
533
962
  if (empty) {
534
- await purgeLocal(connector, planned.intent, held);
963
+ await purgeLocal(connector, planned.intent, held, planned.ended);
535
964
  await options.eraseLegacy?.(connector);
536
965
  return null;
537
966
  }
@@ -593,17 +1022,42 @@ export function createConnectionDeleter(originalDeps, options = {}) {
593
1022
  return (await Promise.all(rows.map(({ connector }) => resumeDelete(connector)))).filter((p) => p !== null);
594
1023
  },
595
1024
  resumeDelete,
596
- /** A connection of the connector was purged here: its erasure may be owed. */
597
- noteSettled(connector) {
598
- if (options.eraseLogs)
599
- erasing.add(connector);
1025
+ deleteStatus,
1026
+ deleteStatusSnapshot,
1027
+ /**
1028
+ * A connection of the connector was purged here: its erasure may be owed.
1029
+ * `tombstone` is the control tombstone that ended it (namespace and
1030
+ * registry version): the identity of the delete, which a delete of the
1031
+ * same connector later replaces. A purge that ran ahead of its fence has
1032
+ * none yet: it owes the stages with no verdict and learns nothing.
1033
+ */
1034
+ noteSettled(connector, tombstone) {
1035
+ // A higher tombstone is a newer delete: both stages judge it afresh and
1036
+ // the gateway is asked again. The same one again (a sync cycle reads the
1037
+ // deleted control row every time) is news of nothing: a final verdict
1038
+ // and a terminal refusal stand, and only a stage with none is owed.
1039
+ // A purge that ran ahead of its fence names no tombstone: nothing is
1040
+ // learned, and the stages with no final verdict are owed.
1041
+ const newer = tombstone
1042
+ ? learnTombstone(connector, tombstone.ns, tombstone.version)
1043
+ : false;
1044
+ if (!owesErasure)
1045
+ return;
1046
+ // A connection held a namespace back and is gone: what held it back is
1047
+ // no longer true, so the same tombstone is judged again. A connection
1048
+ // that still holds it (or another that does) holds it back again.
1049
+ if (!newer)
1050
+ releaseReAdded(connector);
1051
+ const owed = newer ? BOTH : unfinishedStages(connector);
1052
+ if (owed.legacy || owed.storage)
1053
+ owe(connector, owed);
600
1054
  },
601
1055
  /**
602
1056
  * A connection was purged and its connector is unknown: the sweep of
603
1057
  * every deleted connection is owed again.
604
1058
  */
605
1059
  noteSweepOwed() {
606
- if (options.eraseLogs)
1060
+ if (owesErasure)
607
1061
  sweepOwed = true;
608
1062
  },
609
1063
  /** Whether erasure work is owed: the start sweep, or an unfinished erasure. */
@@ -615,12 +1069,24 @@ export function createConnectionDeleter(originalDeps, options = {}) {
615
1069
  * Answers true while one is still unfinished, so the caller retries.
616
1070
  */
617
1071
  async resumeErasures() {
618
- if (!options.eraseLogs || stop.signal.aborted)
1072
+ if (!owesErasure || stop.signal.aborted)
619
1073
  return false;
620
1074
  if (sweepOwed) {
1075
+ // A purge whose connector lookup failed wrote its tombstone all the
1076
+ // same: read the table again.
1077
+ await loadTombstones();
1078
+ // A final verdict is read against the registry too: another device
1079
+ // may have deleted again while this process was off.
1080
+ await refreshTombstones(tombstones.keys());
621
1081
  const rows = await deps.db.query("SELECT DISTINCT connector FROM connections WHERE control_state='deleted' ORDER BY connector");
622
1082
  for (const { connector } of rows)
623
- erasing.add(connector);
1083
+ owe(connector);
1084
+ // A delete this device confirmed and has no final verdict for is
1085
+ // owed too, though a reconnect replaced its local connection: the
1086
+ // tombstone rows say it is unfinished, not the connection rows.
1087
+ const unfinished = await deps.db.query("SELECT DISTINCT connector FROM delete_tombstones WHERE done_at IS NULL ORDER BY connector");
1088
+ for (const { connector } of unfinished)
1089
+ owe(connector);
624
1090
  // Only once the rows are queued: a query that failed leaves it owed.
625
1091
  sweepOwed = false;
626
1092
  }
@@ -628,7 +1094,7 @@ export function createConnectionDeleter(originalDeps, options = {}) {
628
1094
  // unfinished is in `erasing` when it ends, and so is what arrived
629
1095
  // while it ran. Without this wait the loop would find the queue empty
630
1096
  // (a running pass has taken its entry) and stop with that work owed.
631
- await Promise.all([...new Set([...erasing, ...erasures.keys()])].map((connector) => erasures.get(connector) ?? eraseLogsOf(connector)));
1097
+ await Promise.all([...new Set([...erasing.keys(), ...erasures.keys()])].map((connector) => erasures.get(connector) ?? eraseLogsOf(connector)));
632
1098
  return erasing.size > 0;
633
1099
  },
634
1100
  async close() {