@serfab/cadre-core 1.20.0 → 1.22.0

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 (113) hide show
  1. package/README.md +294 -294
  2. package/dist/cadre-node.d.ts +329 -53
  3. package/dist/cadre-node.js +767 -85
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-authorization.d.ts +32 -2
  6. package/dist/control-authorization.js +19 -0
  7. package/dist/control-authorization.js.map +1 -1
  8. package/dist/control-database.d.ts +236 -23
  9. package/dist/control-database.js +601 -178
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-schema.d.ts +3 -3
  12. package/dist/control-schema.js +71 -7
  13. package/dist/control-schema.js.map +1 -1
  14. package/dist/ed25519-key.d.ts +8 -0
  15. package/dist/ed25519-key.js +11 -1
  16. package/dist/ed25519-key.js.map +1 -1
  17. package/dist/index.d.ts +5 -1
  18. package/dist/index.js +13 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/machine-removal.d.ts +51 -1
  21. package/dist/machine-removal.js +42 -1
  22. package/dist/machine-removal.js.map +1 -1
  23. package/dist/membership-connection-gater.d.ts +8 -0
  24. package/dist/membership-connection-gater.js +13 -1
  25. package/dist/membership-connection-gater.js.map +1 -1
  26. package/dist/owner-keys.js +2 -1
  27. package/dist/owner-keys.js.map +1 -1
  28. package/dist/owner-signer.js +3 -4
  29. package/dist/owner-signer.js.map +1 -1
  30. package/dist/peer-authorization.d.ts +14 -2
  31. package/dist/peer-authorization.js +24 -1
  32. package/dist/peer-authorization.js.map +1 -1
  33. package/dist/relay-reservation.js +20 -1
  34. package/dist/relay-reservation.js.map +1 -1
  35. package/dist/sealed-party-key.d.ts +32 -0
  36. package/dist/sealed-party-key.js +162 -0
  37. package/dist/sealed-party-key.js.map +1 -0
  38. package/dist/seed-bootstrap.d.ts +10 -3
  39. package/dist/seed-bootstrap.js +12 -0
  40. package/dist/seed-bootstrap.js.map +1 -1
  41. package/dist/strand-addr-protocol.d.ts +56 -6
  42. package/dist/strand-addr-protocol.js +57 -5
  43. package/dist/strand-addr-protocol.js.map +1 -1
  44. package/dist/strand-app-schema-report.d.ts +6 -3
  45. package/dist/strand-app-schema-report.js +13 -7
  46. package/dist/strand-app-schema-report.js.map +1 -1
  47. package/dist/strand-commit-durability.d.ts +33 -2
  48. package/dist/strand-commit-durability.js +44 -4
  49. package/dist/strand-commit-durability.js.map +1 -1
  50. package/dist/strand-database.d.ts +36 -6
  51. package/dist/strand-database.js +35 -11
  52. package/dist/strand-database.js.map +1 -1
  53. package/dist/strand-instance-manager.d.ts +133 -9
  54. package/dist/strand-instance-manager.js +266 -42
  55. package/dist/strand-instance-manager.js.map +1 -1
  56. package/dist/strand-membership-reconciler.d.ts +250 -51
  57. package/dist/strand-membership-reconciler.js +410 -66
  58. package/dist/strand-membership-reconciler.js.map +1 -1
  59. package/dist/strand-membership-writer.d.ts +7 -0
  60. package/dist/strand-membership-writer.js +9 -0
  61. package/dist/strand-membership-writer.js.map +1 -1
  62. package/dist/strand-party-key-rotation.d.ts +177 -0
  63. package/dist/strand-party-key-rotation.js +340 -0
  64. package/dist/strand-party-key-rotation.js.map +1 -0
  65. package/dist/strand-party-machines.d.ts +111 -0
  66. package/dist/strand-party-machines.js +258 -0
  67. package/dist/strand-party-machines.js.map +1 -0
  68. package/dist/strand-party-peers.d.ts +101 -0
  69. package/dist/strand-party-peers.js +49 -0
  70. package/dist/strand-party-peers.js.map +1 -0
  71. package/dist/strand-peer-redial.d.ts +34 -7
  72. package/dist/strand-peer-redial.js +46 -13
  73. package/dist/strand-peer-redial.js.map +1 -1
  74. package/dist/strand-revocation-enforcer.d.ts +15 -1
  75. package/dist/strand-revocation-enforcer.js +16 -9
  76. package/dist/strand-revocation-enforcer.js.map +1 -1
  77. package/dist/strand-transport-key.js +3 -0
  78. package/dist/strand-transport-key.js.map +1 -1
  79. package/dist/strand-watcher.d.ts +7 -4
  80. package/dist/strand-watcher.js +12 -7
  81. package/dist/strand-watcher.js.map +1 -1
  82. package/dist/types.d.ts +165 -17
  83. package/dist/types.js.map +1 -1
  84. package/package.json +9 -8
  85. package/src/cadre-node.ts +12252 -11528
  86. package/src/control-authorization.ts +41 -1
  87. package/src/control-database.ts +6123 -5594
  88. package/src/control-schema.ts +71 -7
  89. package/src/ed25519-key.ts +12 -1
  90. package/src/index.ts +957 -924
  91. package/src/machine-removal.ts +80 -1
  92. package/src/membership-connection-gater.ts +13 -1
  93. package/src/owner-keys.ts +2 -1
  94. package/src/owner-signer.ts +92 -94
  95. package/src/peer-authorization.ts +27 -3
  96. package/src/relay-reservation.ts +28 -1
  97. package/src/sealed-party-key.ts +190 -0
  98. package/src/seed-bootstrap.ts +17 -3
  99. package/src/strand-addr-protocol.ts +67 -6
  100. package/src/strand-app-schema-report.ts +17 -10
  101. package/src/strand-commit-durability.ts +54 -5
  102. package/src/strand-database.ts +48 -12
  103. package/src/strand-instance-manager.ts +330 -42
  104. package/src/strand-membership-reconciler.ts +1310 -942
  105. package/src/strand-membership-writer.ts +10 -0
  106. package/src/strand-party-key-rotation.ts +436 -0
  107. package/src/strand-party-machines.ts +293 -0
  108. package/src/strand-party-peers.ts +129 -0
  109. package/src/strand-peer-redial.ts +61 -14
  110. package/src/strand-revocation-enforcer.ts +27 -9
  111. package/src/strand-transport-key.ts +3 -0
  112. package/src/strand-watcher.ts +12 -7
  113. package/src/types.ts +3112 -2962
@@ -32,9 +32,9 @@ import type {
32
32
  PeerAddressRecord,
33
33
  DeviceTokenRecord,
34
34
  RevocationRow,
35
- MachineRemovalResult
35
+ MachineRemovalWrites
36
36
  } from './types.js';
37
- import type { CadrePeerRetouchMode, CadrePeerRetouchOutcome, ControlDatabase } from './control-database.js';
37
+ import type { CadrePeerRetouchMode, CadrePeerRetouchOutcome, ControlDatabase, StrandPartyKeySwap } from './control-database.js';
38
38
  import { generateStampId, ownerKeyLabel } from './control-database.js';
39
39
  import { canonicalJson } from './canonical-json.js';
40
40
  import { deviceTokenAddDigest } from './peer-authorization.js';
@@ -704,13 +704,27 @@ export class SeedBootstrapService {
704
704
  * transaction ({@link ControlDatabase.removeMachine}). What stays here is the owner-signer
705
705
  * precondition, checked before any read (see {@link removePeer}).
706
706
  */
707
- async removeMachine(target: Parameters<ControlDatabase['removeMachine']>[0], sign?: OwnerSign): Promise<MachineRemovalResult> {
707
+ async removeMachine(target: Parameters<ControlDatabase['removeMachine']>[0], sign?: OwnerSign): Promise<MachineRemovalWrites> {
708
708
  const ownerKey = this.requireOwnerSigner().publicKey;
709
709
  const controlDatabase = this.requireControlDatabase();
710
710
  return await this.withOwnerSign(`Remove the machine ${target.peerId} from the cadre`, sign, (approved) =>
711
711
  controlDatabase.removeMachine(target, ownerKey, approved));
712
712
  }
713
713
 
714
+ /**
715
+ * Move this party's membership key in each named strand from its old key to its new one in
716
+ * the control record, one transaction and one approval across all of them
717
+ * ({@link ControlDatabase.swapStrandPartyKeys}): the last step of a party key rotation
718
+ * (`strand-party-key-rotation.ts`). What stays here is the owner-signer precondition.
719
+ */
720
+ async swapStrandPartyKeys(entries: readonly StrandPartyKeySwap[], sign?: OwnerSign): Promise<string[]> {
721
+ const ownerKey = this.requireOwnerSigner().publicKey;
722
+ const controlDatabase = this.requireControlDatabase();
723
+ const where = entries.length === 1 ? `the strand ${entries[0]!.strandId}` : `${entries.length} strands`;
724
+ return await this.withOwnerSign(`Replace this cadre's membership key in ${where}`, sign, (approved) =>
725
+ controlDatabase.swapStrandPartyKeys(entries, ownerKey, approved));
726
+ }
727
+
714
728
  /**
715
729
  * Owner "re-touch" of an existing `CadrePeer` membership row, in one of two modes
716
730
  * ({@link CadrePeerRetouchMode}): `'rebroadcast'` bumps `UpdatedAt` and re-vouches the row so
@@ -175,8 +175,8 @@ export class StrandAddrService {
175
175
  * (over {@link maxConcurrent}, reply without looking up any address), a read
176
176
  * timeout (a peer that never half-closes is aborted inside {@link readFrame}/
177
177
  * `readStreamToEnd`), and the existing malformed/oversized-frame guard. A
178
- * lookup that throws is `unavailable` too, never an empty `ok` the asker would
179
- * wait ten minutes on.
178
+ * lookup that throws is `unavailable` too, never an empty `ok`, whose retries
179
+ * climb all the way to the asker's refresh interval.
180
180
  */
181
181
  private async handleStream(stream: ControlStream, remotePeerId: string): Promise<void> {
182
182
  log('Incoming strand-addr request from: %s', remotePeerId);
@@ -293,7 +293,9 @@ export interface CollectStrandAddrsOptions {
293
293
  *
294
294
  * - `answered` — status `ok` with at least one address.
295
295
  * - `empty` — status `ok` with no address: the sibling does not run the strand
296
- * right now, a normal steady state.
296
+ * right now. It cannot tell "not yet" from "never": a normal steady state looks the
297
+ * same as a node still starting, which answers this until its strand row arrives and
298
+ * the strand launches.
297
299
  * - `unavailable` — the sibling replied that it could not answer.
298
300
  * - `unsupported` — the peer was reached and its protocol negotiation refused
299
301
  * strand-addr: it registers no handler for it (a dedicated relay, an older
@@ -304,6 +306,65 @@ export interface CollectStrandAddrsOptions {
304
306
  */
305
307
  export type StrandAddrOutcome = 'answered' | 'empty' | 'unavailable' | 'unsupported' | 'unreachable';
306
308
 
309
+ /**
310
+ * The first wait after an ask that produced no address ({@link nextStrandAddrAsk}),
311
+ * doubling per further such ask. One second is the step `CLAIM_RESTART_REDIAL_STEP_MS`
312
+ * uses for the same restart on the control connection.
313
+ */
314
+ export const STRAND_PEER_ADDR_FIRST_RETRY_MS = 1_000;
315
+
316
+ /**
317
+ * The longest wait after a sibling did NOT answer — unreachable, `unavailable`, or
318
+ * `unsupported` ({@link nextStrandAddrAsk}). A refusal matters most: a phone asking
319
+ * before its `CadrePeer` row has replicated to the sibling is refused and its
320
+ * delegate grant goes unrecorded, and waiting the full refresh interval for the next
321
+ * try is the delay this bounds. A pass arms its own wake for the earliest due time it
322
+ * leaves behind (`nextReconcileWakeMs`), so a sibling that keeps failing costs one
323
+ * timed-out RPC a minute, with no pass in between.
324
+ */
325
+ export const STRAND_PEER_ADDR_RETRY_MS = 60 * 1000;
326
+
327
+ /**
328
+ * When to ask a (sibling, strand) for addresses again, from how the ask just made ended
329
+ * and `priorStreak`, the step of the climbing wait the asks before it reached. Returns the
330
+ * wait and the streak to remember.
331
+ *
332
+ * An answer with addresses waits `refreshMs` and ends the streak. Anything else waits
333
+ * {@link STRAND_PEER_ADDR_FIRST_RETRY_MS}, doubling along the streak: a sibling that is
334
+ * starting up fails, then answers `empty` until its strand launches, then answers with
335
+ * addresses, all within seconds, so `empty` and the failures share one streak and a retry
336
+ * landing in the `empty` stretch is followed by another within seconds.
337
+ *
338
+ * A failure stops climbing at {@link STRAND_PEER_ADDR_RETRY_MS}. `empty` climbs to
339
+ * `refreshMs`, because it is also a steady state that keeps one ask per refresh interval:
340
+ * a phone has no listening strand addresses and always answers it, and so does a
341
+ * hibernating sibling. `refreshMs` caps both, so a configured refresh shorter than the
342
+ * retry does not leave a failing sibling waiting longer than a healthy one.
343
+ *
344
+ * The streak stops growing when the wait does: failures that outlast the cap would otherwise
345
+ * send the first `empty` after them straight to `refreshMs`, however briefly that sibling
346
+ * then stays empty.
347
+ *
348
+ * NOTE: the `empty` climb is 10 asks in its first 17 minutes rather than 2 (counted from the
349
+ * steps, not measured), per (sibling, strand) and per new control connection, and its steps
350
+ * below the 2-minute backstop are 7 extra reconcile passes, each of which also redials any
351
+ * sibling left unconnected and advances the redial wait (`nextReconcileWakeMs`). If those wakes
352
+ * show up on a phone's battery or in pass counts, stop the `empty` steps from waking a pass and
353
+ * let them wait for the backstop.
354
+ */
355
+ export function nextStrandAddrAsk(
356
+ outcome: StrandAddrOutcome,
357
+ priorStreak: number,
358
+ refreshMs: number
359
+ ): { waitMs: number; streak: number } {
360
+ if (outcome === 'answered') {
361
+ return { waitMs: refreshMs, streak: 0 };
362
+ }
363
+ const capMs = outcome === 'empty' ? refreshMs : Math.min(refreshMs, STRAND_PEER_ADDR_RETRY_MS);
364
+ const stepMs = STRAND_PEER_ADDR_FIRST_RETRY_MS * 2 ** priorStreak;
365
+ return stepMs < capMs ? { waitMs: stepMs, streak: priorStreak + 1 } : { waitMs: capMs, streak: priorStreak };
366
+ }
367
+
307
368
  /** Result of {@link collectStrandAddrs}. */
308
369
  export interface StrandAddrCollection {
309
370
  /** Deduplicated union of every answer, signaling-first. */
@@ -326,9 +387,9 @@ interface SiblingAnswer {
326
387
  * Best-effort per peer: a failed/timed-out/empty sibling contributes no address
327
388
  * and never fails the collection — an empty union (no sibling online or running
328
389
  * the strand) is an acceptable seed that self-heals on the next resume/reconcile
329
- * pass. `outcomes` is what lets a caller retry the siblings that could not answer
330
- * sooner than the ones that answered with nothing. The local node (`node.peerId`)
331
- * is excluded so we never RPC ourselves or seed with our own strand address.
390
+ * pass. `outcomes` is what lets a caller schedule each sibling's next ask from how
391
+ * this one ended. The local node (`node.peerId`) is excluded so we never RPC ourselves
392
+ * or seed with our own strand address.
332
393
  *
333
394
  * Dials run concurrently but the union preserves candidate order, so the result
334
395
  * is deterministic regardless of which sibling answers first.
@@ -6,9 +6,10 @@ const log = debug('sereus:cadre:strand-app-schema');
6
6
 
7
7
  /**
8
8
  * `StrandDatabase.appSchemaState()`: whether the database runs the `App` schema its launch was
9
- * given. While the apply is held back the database runs the earlier schema: `'waiting-for-queue'`
10
- * while queued offline transactions refuse it, `'waiting-for-cohort'` while the strand's members
11
- * cannot be reached. `'failed'` when a later retry failed for another reason.
9
+ * given. `'waiting-for-queue'` while queued offline transactions refuse the apply (the database runs
10
+ * the earlier schema); `'waiting-for-cohort'` while the strand's members cannot be reached; `'failed'`
11
+ * when a later retry failed for another reason. docs/strands.md → "An app schema upgrade waits for the
12
+ * queue or the cohort" says what the database runs in the cohort case, and when `'applied'` is not yet true.
12
13
  */
13
14
  export type StrandAppSchemaState = 'applied' | 'waiting-for-queue' | 'waiting-for-cohort' | 'failed';
14
15
 
@@ -75,11 +76,8 @@ export class StrandAppSchemaReport {
75
76
  this.wasPublished = true;
76
77
  const waitingFor = this.result.appSchemaWaitingFor;
77
78
  if (waitingFor && this.state === WAITING_STATE[waitingFor]) {
78
- this.listeners.onAppSchemaDeferred?.({
79
- strandId: this.strandId,
80
- waitingFor,
81
- transactionIds: this.result.appSchemaDeferredBy ?? []
82
- });
79
+ const event = { strandId: this.strandId, waitingFor, transactionIds: this.result.appSchemaDeferredBy ?? [] };
80
+ this.forward('deferred', () => this.listeners.onAppSchemaDeferred?.(event));
83
81
  } else if (this.error) {
84
82
  this.reportFailed(this.error);
85
83
  }
@@ -97,7 +95,7 @@ export class StrandAppSchemaReport {
97
95
  if (outcome.state === 'applied') {
98
96
  this.state = 'applied';
99
97
  if (this.wasPublished) {
100
- this.listeners.onAppSchemaApplied?.({ strandId: this.strandId });
98
+ this.forward('applied', () => this.listeners.onAppSchemaApplied?.({ strandId: this.strandId }));
101
99
  }
102
100
  return;
103
101
  }
@@ -110,6 +108,15 @@ export class StrandAppSchemaReport {
110
108
  }
111
109
 
112
110
  private reportFailed(error: Error): void {
113
- this.listeners.onAppSchemaFailed?.({ strandId: this.strandId, error });
111
+ this.forward('failed', () => this.listeners.onAppSchemaFailed?.({ strandId: this.strandId, error }));
112
+ }
113
+
114
+ /** A listener's throw is logged, so it cannot stop {@link published}'s caller from finishing publication. */
115
+ private forward(what: string, deliver: () => void): void {
116
+ try {
117
+ deliver();
118
+ } catch (error) {
119
+ log('strand %s: an app schema %s listener threw: %O', this.strandId, what, error);
120
+ }
114
121
  }
115
122
  }
@@ -2,6 +2,7 @@ import debug from 'debug';
2
2
  import { durabilityRank } from '@optimystic/db-core';
3
3
  import type { WriteDurability } from '@optimystic/db-core';
4
4
  import type { CommitFullyHeld, SqlCommitDurability } from '@serfab/quereus-plugin-sereus';
5
+ import type { PartyStrandPeer } from './strand-party-peers.js';
5
6
 
6
7
  const log = debug('sereus:cadre:strand-commit-durability');
7
8
 
@@ -21,6 +22,13 @@ export interface StrandCommitDurability {
21
22
  * reaches the others while this database stays open. False means nothing will say so.
22
23
  */
23
24
  readonly followed: boolean;
25
+ /**
26
+ * The party's other machines known to hold this strand that do not hold this commit yet: those
27
+ * not in `report.durability.overall.cohortPeerIds`, or named in its `unconfirmed`. Empty when
28
+ * {@link heldElsewhere} is true. Absent on a node offering no offline mode, which does not track them.
29
+ * Empty with `heldElsewhere` false does not prove a cadre of one (docs/strands.md → "A commit's durability").
30
+ */
31
+ readonly awaitedMachines?: readonly PartyStrandPeer[];
24
32
  /** The plugin's report, for per-table detail. */
25
33
  readonly report: SqlCommitDurability;
26
34
  }
@@ -53,6 +61,26 @@ function isHeldElsewhere(overall: WriteDurability | undefined): boolean {
53
61
  && (overall.torn?.length ?? 0) === 0;
54
62
  }
55
63
 
64
+ const NO_MACHINES: readonly PartyStrandPeer[] = Object.freeze([]);
65
+
66
+ /**
67
+ * With no `cohortPeerIds` the answering layer could not name the cohort, so no machine is
68
+ * confirmed to hold the commit and every one is listed.
69
+ *
70
+ * NOTE: reads the scalars, which describe the weakest answer, and ignores `otherCohorts`, so a
71
+ * machine that another cohort's answer shows holding one block can be listed although that block
72
+ * reached it. The list over-reports; {@link isHeldElsewhere} stays the answer to survival. If an
73
+ * app ever needs the list per block, walk `otherCohorts` here.
74
+ */
75
+ function machinesAwaited(overall: WriteDurability | undefined, machines: readonly PartyStrandPeer[]): readonly PartyStrandPeer[] {
76
+ if (isHeldElsewhere(overall)) {
77
+ return NO_MACHINES;
78
+ }
79
+ const cohort = overall?.cohortPeerIds && new Set(overall.cohortPeerIds);
80
+ const unconfirmed = new Set(overall?.unconfirmed);
81
+ return Object.freeze(machines.filter(({ strandPeerId }) => !cohort?.has(strandPeerId) || unconfirmed.has(strandPeerId)));
82
+ }
83
+
56
84
  /**
57
85
  * The durability of the most recent commits on one strand database, by transaction id. The
58
86
  * plugin reports a commit — and a `covered` commit is held — before the statement that made it
@@ -65,7 +93,15 @@ export class StrandCommitRecord {
65
93
 
66
94
  constructor(
67
95
  private readonly strandId: string,
68
- private readonly listeners: StrandCommitListeners
96
+ private readonly listeners: StrandCommitListeners,
97
+ /**
98
+ * The tracker's last good answer: {@link reportCommit} runs inside the commit and cannot wait for a read.
99
+ *
100
+ * NOTE: a commit does not ask the tracker to retry a failed read; the offline gate's re-check and
101
+ * the next control-table change do. In online mode a failed read can therefore list nobody until
102
+ * the next change. If an app ever shows that, call `refresh()` here when `lastReadFailed()`.
103
+ */
104
+ private readonly partyMachines?: () => readonly PartyStrandPeer[]
69
105
  ) {}
70
106
 
71
107
  get(transactionId: string): StrandCommitDurability | undefined {
@@ -74,22 +110,35 @@ export class StrandCommitRecord {
74
110
 
75
111
  /** A plugin `onCommitDurability` report: record it, then forward it. */
76
112
  reportCommit(report: SqlCommitDurability): void {
77
- const commit = Object.freeze({
113
+ const { overall } = report.durability;
114
+ const commit: StrandCommitDurability = Object.freeze({
78
115
  strandId: this.strandId,
79
116
  transactionId: report.transactionId,
80
- heldElsewhere: isHeldElsewhere(report.durability.overall),
117
+ heldElsewhere: isHeldElsewhere(overall),
81
118
  followed: report.followed,
119
+ ...(this.partyMachines && { awaitedMachines: machinesAwaited(overall, this.partyMachines()) }),
82
120
  report
83
121
  });
84
122
  this.remember(commit);
85
123
  this.forward('durability', report.transactionId, () => this.listeners.onCommitDurability?.(commit));
86
124
  }
87
125
 
88
- /** A plugin `onCommitFullyHeld` event: mark the commit held, then forward it — also for one no longer recorded. */
126
+ /**
127
+ * A plugin `onCommitFullyHeld` event: mark the commit held, then forward it — also for one no longer recorded.
128
+ *
129
+ * NOTE: accepted tradeoff — the event fires when the under-replication drain settles the commit,
130
+ * so with two machines out the first to take the copies clears the list while the second still
131
+ * lacks them. The field answers "who was this commit waiting for" until another machine holds it;
132
+ * {@link StrandCommitDurability.heldElsewhere} is the survival answer.
133
+ */
89
134
  reportHeld({ transactionId }: CommitFullyHeld): void {
90
135
  const recorded = this.commits.get(transactionId);
91
136
  if (recorded) {
92
- this.commits.set(transactionId, Object.freeze({ ...recorded, heldElsewhere: true }));
137
+ this.commits.set(transactionId, Object.freeze({
138
+ ...recorded,
139
+ heldElsewhere: true,
140
+ ...(recorded.awaitedMachines && { awaitedMachines: NO_MACHINES })
141
+ }));
93
142
  }
94
143
  this.forward('held', transactionId, () => this.listeners.onCommitHeld?.({ strandId: this.strandId, transactionId }));
95
144
  }
@@ -3,9 +3,10 @@ import { Database } from '@quereus/quereus';
3
3
  import { applyAppSchema, connectToStrand } from '@serfab/quereus-plugin-sereus';
4
4
  import type { SereusPluginResult, StrandOfflineController } from '@serfab/quereus-plugin-sereus';
5
5
  import type { Libp2p } from '@libp2p/interface';
6
- import type { IRepo } from '@optimystic/db-core';
6
+ import type { ICohortReachability, IRepo } from '@optimystic/db-core';
7
7
  import type { IKVStore } from '@optimystic/db-p2p';
8
8
  import type { SAppConfig } from './types.js';
9
+ import type { PartyStrandPeer } from './strand-party-peers.js';
9
10
  import { bootstrapFounderMembership } from './strand-membership-writer.js';
10
11
  import { strandMemberKeyPair } from './strand-member-key.js';
11
12
  import { StrandCommitRecord } from './strand-commit-durability.js';
@@ -75,6 +76,12 @@ export interface StrandDatabaseConfig extends StrandCommitListeners {
75
76
  offline?: StrandDatabaseOffline;
76
77
  /** Where to report the `App` schema apply when it is held back (docs/strands.md → "An app schema upgrade waits for the queue or the cohort"). */
77
78
  appSchema?: StrandAppSchemaListeners;
79
+ /**
80
+ * The party's other machines known to hold the strand (`StrandPartyMachines.machines`), named in
81
+ * each commit's {@link StrandCommitDurability.awaitedMachines}. Absent on a node offering no
82
+ * offline mode, which does not track them.
83
+ */
84
+ partyMachines?: () => readonly PartyStrandPeer[];
78
85
  }
79
86
 
80
87
  /** {@link StrandDatabaseConfig.offline}: one build's journal, the strand's mode, and where to report. */
@@ -89,6 +96,12 @@ export interface StrandDatabaseOffline extends StrandOfflineListeners {
89
96
  * {@link StrandDatabase.applyOfflineMode}, never captured, so the newest choice wins.
90
97
  */
91
98
  mode: () => StrandOfflineMode;
99
+ /**
100
+ * The gate the queue and offline live reads ask in place of the strand node's own: the node's
101
+ * gate closed also while the party has machines holding the strand that this node is not in a
102
+ * cohort with (`strand-party-machines.ts`). Absent on a node whose strand node offers no gate.
103
+ */
104
+ cohortReachability?: ICohortReachability;
92
105
  }
93
106
 
94
107
  /**
@@ -124,7 +137,7 @@ export class StrandDatabase {
124
137
 
125
138
  constructor(config: StrandDatabaseConfig) {
126
139
  this.config = config;
127
- this.commits = new StrandCommitRecord(config.strandId, config);
140
+ this.commits = new StrandCommitRecord(config.strandId, config, config.partyMachines);
128
141
  }
129
142
 
130
143
  /**
@@ -149,6 +162,7 @@ export class StrandDatabase {
149
162
  sAppConfig ? `sApp: ${sAppConfig.id} v${sAppConfig.version}` : 'storage replica');
150
163
 
151
164
  const offline = this.config.offline && { journal: await this.config.offline.journal() };
165
+ const cohortReachability = this.config.offline?.cohortReachability;
152
166
  this.db = new Database();
153
167
 
154
168
  // Delegate to the shared composition. The node is injected, so:
@@ -171,6 +185,7 @@ export class StrandDatabase {
171
185
  coordinatedRepo: this.config.coordinatedRepo,
172
186
  enableCache: true,
173
187
  offline,
188
+ ...(cohortReachability && { cohortReachability }),
174
189
  });
175
190
  this.shutdownStrand = result.shutdown;
176
191
  this.resolvedTransactor = result.transactor;
@@ -401,7 +416,7 @@ export class StrandDatabase {
401
416
  /**
402
417
  * Whether this database runs the `App` schema its launch was given. `'waiting-for-queue'` or
403
418
  * `'waiting-for-cohort'` while the apply is held back, so `StrandInstance.sAppInfo` names a version
404
- * whose new tables or columns are not here yet; check this before relying on them.
419
+ * whose new tables or columns may not be usable yet; check this before relying on them.
405
420
  */
406
421
  appSchemaState(): StrandAppSchemaState {
407
422
  this.ensureInitialized();
@@ -436,10 +451,27 @@ export class StrandDatabase {
436
451
  }
437
452
 
438
453
  /**
439
- * Close the database and cleanup resources. Runs the strand-connection
440
- * shutdown (collection-factory teardown; the injected node keeps running),
441
- * then closes the `Database`. Safe on an instance whose {@link initialize}
442
- * failed part-way.
454
+ * Close the database and cleanup resources. Closes the Quereus `Database` and waits for it
455
+ * (it stops every running statement and open iterator and resolves once nothing reads or
456
+ * writes), then runs the strand-connection shutdown (collection-factory teardown; the
457
+ * injected node keeps running), so no statement reaches released storage. Safe on an
458
+ * instance whose {@link initialize} failed part-way.
459
+ *
460
+ * The handle stays set across the awaits, so a second, concurrent close (a build released
461
+ * part-way closes its database again) awaits the same Quereus teardown rather than skipping
462
+ * ahead to the strand shutdown, which is safe to run twice (each release it makes is
463
+ * idempotent, and the storage-cache release is latched). A rejected Quereus close is logged and the
464
+ * teardown goes on, because callers stop the strand's node once this resolves.
465
+ *
466
+ * NOTE: this makes `close()` wait on a statement in a network wait, bounded by Optimystic's
467
+ * RPC deadlines; the strand shutdown aborts no in-flight request, so closing it first never
468
+ * cut that wait short. Revisit (abort in-flight collection work before closing Quereus) if
469
+ * strand stops show up slow.
470
+ *
471
+ * NOTE: the plugin raises the commit-durability and commit-held reports from inside the
472
+ * committing statement, but through listeners nobody awaits, so an app handler that starts
473
+ * `stopStrand` does not make the statement wait for this close. If a delivery path ever
474
+ * awaits its listeners, a stop started from one waits for itself and never resolves.
443
475
  */
444
476
  async close(): Promise<void> {
445
477
  // First, so an event from the closing connection reaches no app handler or table watch.
@@ -451,16 +483,20 @@ export class StrandDatabase {
451
483
  this.appSchemaReport = null;
452
484
  this.offlineQueue = null;
453
485
  this.tableWatches.disposeAll();
486
+ if (this.db) {
487
+ try {
488
+ await this.db.close();
489
+ } catch (err) {
490
+ log('Closing the Quereus database for strand %s failed; shutting the strand connection down anyway: %O', this.config.strandId, err);
491
+ }
492
+ }
454
493
  if (this.shutdownStrand) {
455
494
  await this.shutdownStrand();
456
495
  this.shutdownStrand = null;
457
496
  }
458
- // Again: a subscription taken during the await above would keep its timers past close.
497
+ // Again: a subscription taken during the awaits above would keep its timers past close.
459
498
  this.tableWatches.disposeAll();
460
- if (this.db) {
461
- void this.db.close();
462
- this.db = null;
463
- }
499
+ this.db = null;
464
500
  this.resolvedTransactor = null;
465
501
  this.initialized = false;
466
502
  log('StrandDatabase for strand %s closed', this.config.strandId);