@serfab/cadre-core 1.4.0 → 1.5.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 (63) hide show
  1. package/dist/cadre-node.d.ts +38 -15
  2. package/dist/cadre-node.js +77 -29
  3. package/dist/cadre-node.js.map +1 -1
  4. package/dist/control-database.d.ts +24 -10
  5. package/dist/control-database.js +48 -16
  6. package/dist/control-database.js.map +1 -1
  7. package/dist/control-read-retry.d.ts +12 -0
  8. package/dist/control-read-retry.js +12 -0
  9. package/dist/control-read-retry.js.map +1 -1
  10. package/dist/control-write-retry.d.ts +5 -4
  11. package/dist/control-write-retry.js +24 -7
  12. package/dist/control-write-retry.js.map +1 -1
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +5 -2
  15. package/dist/index.js.map +1 -1
  16. package/dist/link-budget.d.ts +182 -0
  17. package/dist/link-budget.js +195 -0
  18. package/dist/link-budget.js.map +1 -0
  19. package/dist/peer-dial.d.ts +36 -17
  20. package/dist/peer-dial.js +37 -17
  21. package/dist/peer-dial.js.map +1 -1
  22. package/dist/peer-join-backfill.d.ts +58 -4
  23. package/dist/peer-join-backfill.js +165 -20
  24. package/dist/peer-join-backfill.js.map +1 -1
  25. package/dist/relay-reservation.d.ts +59 -11
  26. package/dist/relay-reservation.js +169 -43
  27. package/dist/relay-reservation.js.map +1 -1
  28. package/dist/seed-bootstrap.js +2 -1
  29. package/dist/seed-bootstrap.js.map +1 -1
  30. package/dist/strand-first-sync-gate.d.ts +43 -5
  31. package/dist/strand-first-sync-gate.js +55 -7
  32. package/dist/strand-first-sync-gate.js.map +1 -1
  33. package/dist/strand-instance-manager.d.ts +27 -2
  34. package/dist/strand-instance-manager.js +56 -13
  35. package/dist/strand-instance-manager.js.map +1 -1
  36. package/dist/strand-membership-reconciler.d.ts +200 -45
  37. package/dist/strand-membership-reconciler.js +302 -86
  38. package/dist/strand-membership-reconciler.js.map +1 -1
  39. package/dist/strand-membership-writer.d.ts +3 -2
  40. package/dist/strand-membership-writer.js +67 -90
  41. package/dist/strand-membership-writer.js.map +1 -1
  42. package/dist/strand-network-config.d.ts +2 -2
  43. package/dist/strand-network-config.js +2 -2
  44. package/dist/types.d.ts +96 -9
  45. package/dist/types.js +14 -4
  46. package/dist/types.js.map +1 -1
  47. package/package.json +8 -8
  48. package/src/cadre-node.ts +7445 -7397
  49. package/src/control-database.ts +48 -16
  50. package/src/control-read-retry.ts +214 -202
  51. package/src/control-write-retry.ts +24 -7
  52. package/src/index.ts +581 -563
  53. package/src/link-budget.ts +217 -0
  54. package/src/peer-dial.ts +39 -17
  55. package/src/peer-join-backfill.ts +192 -23
  56. package/src/relay-reservation.ts +1119 -951
  57. package/src/seed-bootstrap.ts +2 -1
  58. package/src/strand-first-sync-gate.ts +55 -7
  59. package/src/strand-instance-manager.ts +1516 -1458
  60. package/src/strand-membership-reconciler.ts +334 -92
  61. package/src/strand-membership-writer.ts +1962 -1987
  62. package/src/strand-network-config.ts +2 -2
  63. package/src/types.ts +95 -8
@@ -1,1458 +1,1516 @@
1
- import debug from 'debug';
2
- import type { PrivateKey } from '@libp2p/interface';
3
- import { createLibp2pNode, type IRawStorage } from '@optimystic/db-p2p';
4
- import { wrapStorageWithCache, disposeStorageCache } from '@serfab/quereus-plugin-sereus';
5
- import { StrandDatabase } from './strand-database.js';
6
- import { PeerJoinBackfill, type PeerJoinBackfillConfig } from './peer-join-backfill.js';
7
- import {
8
- StrandRevocationEnforcer,
9
- createRevocationConnectionGater,
10
- readStrandRevocationRows,
11
- type StrandRevocationEnforcementConfig
12
- } from './strand-revocation-enforcer.js';
13
- import {
14
- StrandMembershipReconciler,
15
- type PendingMembershipInviteSource,
16
- type StrandMembershipReconciliationConfig
17
- } from './strand-membership-reconciler.js';
18
- import { removeMemberPeer } from './strand-membership-writer.js';
19
- import { strandMemberKeyPair } from './strand-member-key.js';
20
- import { assertSchemaSignature } from './schema-verification.js';
21
- import { assertStrandScopeKey } from './storage-scope.js';
22
- import {
23
- StrandFirstSyncGate,
24
- StrandAwaitingFirstSyncError,
25
- strandFirstSyncComplete,
26
- DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS,
27
- type StrandFirstSyncConfig
28
- } from './strand-first-sync-gate.js';
29
- import type {
30
- StrandInstance,
31
- StrandRow,
32
- StorageConfig,
33
- NetworkConfig,
34
- LatencyHint,
35
- NodeProfile,
36
- SAppConfig,
37
- SAppInfo,
38
- RawStorageProvider,
39
- Libp2pNodeWithRepo
40
- } from './types.js';
41
- import { DEFAULT_CONNECTION_MONITOR, resolveStrandClusterSize, strandClusterPolicy } from './types.js';
42
- import { strandNodeAddrs } from './strand-network-config.js';
43
- import { superviseRelayReservation, type RelayReservationSupervisor } from './relay-reservation.js';
44
-
45
- const log = debug('sereus:cadre:strand-manager');
46
- const timing = debug('sereus:cadre:timing');
47
-
48
- /** One caller blocked in {@link StrandInstanceManager.whenWritable}. */
49
- interface WritableWaiter {
50
- resolve: () => void;
51
- reject: (error: Error) => void;
52
- }
53
-
54
- /**
55
- * Whether a tracked instance is launched but waiting for its first sync: the runtime is
56
- * up (`libp2pNode` set) while the database is still withheld (`database` unset). That
57
- * is the first-sync gate's state regardless of what `status` says — the hibernation
58
- * manager's idle timer can flip a long-gated joiner to `'idle'` without changing it.
59
- *
60
- * NOTE: `status` is therefore not the source of truth for "gated": a joiner that reaches
61
- * nobody for `idleTimeout` (5 min at the interactive hint) reads `'idle'`, then
62
- * `'hibernating'`, while still holding no database. Harmless today — every decision the
63
- * runtime makes goes through this predicate, {@link StrandInstanceManager.publishDatabase}
64
- * announces on the idle-flipped instance exactly as on a `'syncing'` one, and an app that
65
- * shows "waiting for the other member" on `'syncing'` merely sees "idle" instead after
66
- * five minutes. If an app ever needs the gated LABEL to survive the idle flip, make the
67
- * hibernation manager's idle transition preserve `'syncing'` rather than adding a flag.
68
- */
69
- export function isAwaitingFirstSync(instance: StrandInstance): boolean {
70
- return instance.libp2pNode !== undefined && instance.database === undefined;
71
- }
72
-
73
- /**
74
- * The status a LIVE instance (runtime rebuilt or woken) should report: `'active'` once its
75
- * database is published, `'syncing'` while the first-sync gate still withholds it. Every
76
- * site that would otherwise write `'active'` after a build or a wake goes through this,
77
- * so a gated joiner never reads as writable.
78
- */
79
- export function liveStrandStatus(instance: StrandInstance): 'active' | 'syncing' {
80
- return instance.database ? 'active' : 'syncing';
81
- }
82
-
83
- /**
84
- * Configuration for starting a strand instance
85
- */
86
- export interface StartStrandConfig {
87
- strandRow: StrandRow;
88
- /** sApp configuration provided by the hosting application */
89
- sAppConfig: SAppConfig;
90
- storage?: StorageConfig;
91
- network?: NetworkConfig;
92
- profile: NodeProfile;
93
- defaultLatencyHint: LatencyHint;
94
- privateKey?: PrivateKey;
95
- /** Cohort-derived discovery seed (multiaddr strings). Defaults to [] when omitted. */
96
- bootstrapNodes?: string[];
97
- /**
98
- * Require a valid author signature on the sApp schema before bring-up.
99
- * Defaults to true (fail closed) when omitted; set false only for dev/test
100
- * with unsigned demo schemas. Mirrors {@link CadreNodeConfig.requireSignedSchemas}.
101
- */
102
- requireSignedSchemas?: boolean;
103
- /**
104
- * Whether this node founds the strand (vs. joins it). Forwarded to the
105
- * StrandDatabase so the founder bootstrap (Header, founding Member/Manager)
106
- * runs once at bring-up. Joiners leave this unset and write nothing. Callers
107
- * resolve it BEFORE calling `startStrand` (`CadreNode.launchStrand` derives it
108
- * from the row's `FounderOwnerKey` when no explicit flag is given — see
109
- * {@link StrandConfig.founder}); a founder request that arrives while the
110
- * instance is already tracked goes through {@link StrandInstanceManager.foundExistingStrand},
111
- * never through a repeat `startStrand`.
112
- */
113
- founder?: boolean;
114
- /**
115
- * THIS party's own strand membership private key (base64 protobuf) for a closed
116
- * strand — the identity the founder bootstrap derives `Member.Key` /
117
- * `Manager.MemberKey` from. Resolved by the caller (`CadreNode.launchStrand`: an
118
- * explicit attach-time key, else the control-layer `StrandPartyKey` row, healed by
119
- * mint-on-launch for the founding machine) and retained with the launch config, so a
120
- * hibernation wake rebuilds under the same identity. Deliberately NOT the strand
121
- * row's shared `MemberPrivateKey` (see `StrandDatabaseConfig.partyMemberPrivateKey`).
122
- * Absent for open strands, and for joiners with no persisted party key.
123
- */
124
- partyMemberPrivateKey?: string;
125
- /**
126
- * Number of nodes Optimystic is told this strand's replication cluster should
127
- * have. Same rule as {@link CadreNodeConfig.strandClusterSize}, which CadreNode
128
- * forwards here: every node on the strand should use the same value, and it is
129
- * frozen when the strand's libp2p node is created. Defaults to
130
- * `DEFAULT_STRAND_CLUSTER_SIZE` (4); values below `MIN_CLUSTER_SIZE` (2) are
131
- * rejected by `resolveStrandClusterSize`. Strand-only — the
132
- * control network's breadth is the fixed `CONTROL_REPLICATION_BREADTH`.
133
- */
134
- clusterSize?: number;
135
- /**
136
- * Machines that SERVE THIS STRAND (this node included), for the strand node's
137
- * block-repair corroboration yardstick — see `resolveRepairYardstick`. It must be
138
- * an authenticated per-strand count: the machines that actually run a node for this
139
- * strand, not the machines that exist.
140
- *
141
- * **The party's enrolled-machine count is NOT this number and must never be passed
142
- * here.** A strand launches only on machines whose embedding app registered its sApp
143
- * config (`CadreNode.addStrand`), so a closed strand shared by two machines of a
144
- * three-machine party is served by two. Passing three over-declares, and
145
- * over-declaring is the unsafe direction: at a declaration of 3 or more Optimystic
146
- * pins the repair corroboration floor at two corroborating peers, which a cohort
147
- * that can only ever field one peer can never reach — so the strand can never repair
148
- * a block (`cluster-fetch:no-quorum`, surfacing as reads failing with `Missing
149
- * block`). That regression is why this field was renamed off "enrolledMachines":
150
- * `bug-strand-yardstick-counts-party-machines`.
151
- *
152
- * **Nothing feeds it in production today.** No authenticated per-strand serving count
153
- * exists yet, so `CadreNode` passes nothing and the strand node runs the frozen
154
- * `STRAND_CLUSTER_POLICY` — declaring no yardstick, which leaves the known,
155
- * upstream-tracked single-voter exposure
156
- * (`backlog/debt-read-repair-single-voter-corroboration`). Building the count is
157
- * `backlog/feat-strand-yardstick-from-serving-machines`; this field and its
158
- * threading are the seam it plugs into.
159
- *
160
- * Volatile when a source does exist: re-resolve it on every resume beside the cohort
161
- * seed, since machines join and leave a strand while it hibernates. Omitting it means
162
- * "this node does not know", which declares nothing.
163
- */
164
- servingMachines?: number;
165
- /**
166
- * Tuning for the strand peer-join block catch-up ({@link PeerJoinBackfill}),
167
- * forwarded from {@link CadreNodeConfig.strandBackfill}. When the strand's
168
- * libp2p node connects to a peer this runtime has not yet caught up, every
169
- * block in the strand's own raw store is pushed to it. Runs only on strands
170
- * with per-strand storage; `{ enabled: false }` restores the pre-existing
171
- * no-backfill behaviour.
172
- */
173
- backfill?: PeerJoinBackfillConfig;
174
- /**
175
- * Tuning for the CLOSED-strand revoked-peer gate
176
- * ({@link StrandRevocationEnforcer}), forwarded from
177
- * {@link CadreNodeConfig.strandRevocationEnforcement}. Armed only for
178
- * `strandRow.Type === 'c'` (an open strand has no membership rows to derive a
179
- * deny set from); `{ enabled: false }` restores the pre-existing behaviour
180
- * (a removed party's peers keep being served).
181
- */
182
- revocationEnforcement?: StrandRevocationEnforcementConfig;
183
-
184
- /**
185
- * The staged formation membership invitation for THIS strand — the seam the
186
- * bring-up membership reconciler (`strand-membership-reconciler.ts`) reads to
187
- * redeem the party's `Strand.Member` seat, and clears once the invitation is
188
- * spent, burned, or dead. `CadreNode.launchStrand` wires it over its in-memory
189
- * `pendingMembershipInvites` map; read lazily per pass, so a re-formation that
190
- * replaces the entry between passes is picked up. Only consulted for closed
191
- * strands launched with a {@link partyMemberPrivateKey}; harmless otherwise.
192
- */
193
- pendingMembershipInvite?: PendingMembershipInviteSource;
194
-
195
- /**
196
- * Tuning for the CLOSED-strand membership reconciler, forwarded from
197
- * {@link CadreNodeConfig.strandMembershipReconciliation}. Armed only for
198
- * closed strands launched with a {@link partyMemberPrivateKey};
199
- * `{ enabled: false }` disarms the loop (test fixtures that hand-drive the
200
- * membership writers). When it names no `pollIntervalMs` the reconciler
201
- * mirrors {@link revocationEnforcement}'s cadence — as its IDLE cadence and
202
- * the cap of its unfinished-join retry ladder, not as a flat retry interval.
203
- */
204
- membershipReconciliation?: StrandMembershipReconciliationConfig;
205
-
206
- /**
207
- * Called when THIS node's own peer id turns up in the strand's revoked set —
208
- * this node's party was removed from the closed strand, or left it. Fires once
209
- * per removal (re-armed if the party is re-admitted; a resume also rebuilds the
210
- * enforcer and may legitimately re-fire), and only for closed strands with the
211
- * gate armed. `CadreNode`
212
- * wires it to its `strand:revoked` event; nothing is stopped or torn down on
213
- * this node's behalf — what to do about it is the app's call.
214
- */
215
- onSelfRevoked?: (strandId: string) => void;
216
-
217
- /**
218
- * Tuning for the JOINING machine's first-sync write gate (`strand-first-sync-gate.ts`),
219
- * forwarded from {@link CadreNodeConfig.strandFirstSync}: the Header probe cadence while
220
- * a non-founder launch is `'syncing'`, and the default budget {@link whenWritable} waits
221
- * before rejecting. Founders and machines that already hold the Header are never gated.
222
- */
223
- firstSync?: StrandFirstSyncConfig;
224
-
225
- /**
226
- * Called when a launch that came up `'syncing'` (see {@link firstSync}) becomes
227
- * writable: the strand's `Strand.Header` arrived from a peer — or a founder request
228
- * ran the bootstrap against the gated database — and `instance.database` is now set.
229
- * Never called for a launch that was writable when `startStrand`/`resumeStrand`
230
- * resolved. `CadreNode` wires it to its `strand:writable` event. Retained with the
231
- * launch config, so a hibernation resume that comes up gated announces too.
232
- */
233
- onWritable?: (strandId: string) => void;
234
-
235
- /**
236
- * Re-announce this strand's delegate peer id (`delegatePeerId` — the strand
237
- * node's own transport peer id) to ONE relay (`relayAddr`, a direct dial addr
238
- * with a trailing `/p2p/<relayPeerId>`), unthrottled. Awaited before every
239
- * relay-reservation RE-drive of that relay — never before the first attempt,
240
- * which the launch/resume seed pass has already announced for.
241
- *
242
- * Why: a party control node running the relay server admits the strand node on
243
- * an in-memory delegate grant that a relay restart drops, so a re-drive that did
244
- * not re-announce first would be denied at the relay's gate. `CadreNode` wires
245
- * its own control-mesh announce here; a throw or rejection is logged by the
246
- * supervisor and the re-drive still runs. Retained with the launch config, so a
247
- * hibernation wake's rebuilt supervisors carry it too.
248
- */
249
- announceDelegateToRelay?: (strandId: string, relayAddr: string, delegatePeerId: string) => Promise<void>;
250
- }
251
-
252
- /**
253
- * Volatile inputs re-resolved when resuming a quiesced strand — the ones that can
254
- * have moved since it last ran, and that the rebuilt libp2p node freezes again. Each
255
- * one omitted keeps the value the retained launch config already holds, so a resume
256
- * that passes nothing rebuilds the strand exactly as it last ran.
257
- */
258
- export interface ResumeStrandOverrides {
259
- /**
260
- * Freshly-resolved cohort discovery seed (multiaddr strings). Grows as peers are
261
- * learned since the strand first launched.
262
- */
263
- bootstrapNodes?: string[];
264
- /**
265
- * Freshly-read count of the machines serving this strand, for the repair yardstick
266
- * (see {@link StartStrandConfig.servingMachines} — including why the party's
267
- * enrolled-machine count is not it). Moves whenever a machine starts or stops
268
- * serving the strand, which a hibernating strand does not otherwise notice. Nothing
269
- * passes it today. Omitting it here does NOT mean "unknown" the way omitting it from
270
- * {@link StartStrandConfig} does — it retains the last value; see `resumeStrand`.
271
- */
272
- servingMachines?: number;
273
- }
274
-
275
- /**
276
- * Get the isolated storage path for a specific strand.
277
- *
278
- * @deprecated This helper is Node-only and throws in React Native (it assumes a
279
- * filesystem layout). Use a storage provider factory function instead, which
280
- * receives the strandId and can create strand-specific storage paths using
281
- * platform-appropriate methods.
282
- *
283
- * @example
284
- * // Instead of using getStrandStoragePath, use a storage provider factory:
285
- * const storage = {
286
- * provider: (strandId: string) => new FileRawStorage(`./data/strands/${strandId}`)
287
- * };
288
- */
289
- export function getStrandStoragePath(basePath: string, strandId: string): string {
290
- // Check if we're in a Node.js environment
291
- if (typeof process === 'undefined' || !process.versions?.node) {
292
- throw new Error(
293
- 'getStrandStoragePath is not available in React Native. ' +
294
- 'Use a storage provider factory function instead.'
295
- );
296
- }
297
-
298
- // Sanitize strandId for filesystem safety (UUIDs should be safe, but just in case)
299
- const safeId = strandId.replace(/[^a-zA-Z0-9-]/g, '_');
300
-
301
- // Build the path with plain string joins rather than the Node `path` module.
302
- // A static `require('path')` forces RN bundlers (e.g. Metro) to *resolve* the
303
- // module at bundle time even though this Node-only helper throws above before
304
- // ever reaching here — joining by hand keeps the module free of any Node
305
- // built-in reference, so RN bundles need no `path` shim.
306
- const trimmedBase = basePath.replace(/[\\/]+$/, '');
307
- return `${trimmedBase}/strands/${safeId}`;
308
- }
309
-
310
- /**
311
- * Resolve a storage provider for a specific strand.
312
- * If the provider is a factory function, call it with the strandId.
313
- *
314
- * Called only from {@link StrandInstanceManager.startStrand}, which owns the result
315
- * for the instance's lifetime — see `strandStorages`, and which has already asserted
316
- * the id is usable as a scope key. Do not move that assertion here: this function
317
- * returns early when no provider is configured, and the id becomes a libp2p protocol
318
- * prefix on that path too.
319
- *
320
- * @param provider - Storage provider (instance or factory)
321
- * @param strandId - The strand ID to create storage for
322
- * @returns The resolved IRawStorage instance, or undefined if no provider
323
- */
324
- function resolveStrandStorage(
325
- provider: RawStorageProvider | undefined,
326
- strandId: string
327
- ): IRawStorage | undefined {
328
- if (!provider) {
329
- return undefined;
330
- }
331
- const storage = typeof provider === 'function' ? provider(strandId) : provider;
332
- // Wrapped in the write-through raw-storage cache (quereus-plugin-sereus's cached-storage.ts).
333
- // Called ONCE per strand launch — `startStrand` keeps the result for the instance's
334
- // lifetime — so the wrap survives every runtime rebuild the instance goes through.
335
- return wrapStorageWithCache(storage, strandId);
336
- }
337
-
338
- /**
339
- * Manages individual strand instances - creates and destroys isolated libp2p nodes
340
- * for each strand the cadre participates in.
341
- */
342
- export class StrandInstanceManager {
343
- private instances: Map<string, StrandInstance> = new Map();
344
- /**
345
- * Retained launch config per strand, captured in `startStrand` and cleared in
346
- * `stopStrand`. `resumeStrand` reuses it to rebuild a quiesced strand's runtime
347
- * without the caller re-threading storage/network/profile/key/sApp config.
348
- */
349
- private launchConfigs: Map<string, StartStrandConfig> = new Map();
350
- /**
351
- * The per-strand peer-join block catch-up, keyed by strand id. Private (not on
352
- * the public {@link StrandInstance}) because it is runtime plumbing with the
353
- * same lifetime as the strand's libp2p node: created in `buildStrandRuntime`,
354
- * stopped and dropped in `releaseRuntime` — so quiesce → resume rebuilds it
355
- * with a fresh caught-up-peer memo, which is intended (a resumed node may have
356
- * missed writes).
357
- */
358
- private backfills: Map<string, PeerJoinBackfill> = new Map();
359
- /**
360
- * The per-strand revoked-peer enforcer (closed strands only), keyed by strand
361
- * id. Same lifecycle rationale as {@link backfills}: created in
362
- * `buildStrandRuntime`, stopped and dropped in `releaseRuntime`, so quiesce →
363
- * resume rebuilds it with a fresh (initially empty, fail-open) snapshot.
364
- */
365
- private revocationEnforcers: Map<string, StrandRevocationEnforcer> = new Map();
366
- /**
367
- * The per-strand membership reconciler (closed strands launched with a party
368
- * key only), keyed by strand id. Same lifecycle rationale as {@link backfills}:
369
- * created in `buildStrandRuntime`, stopped and dropped in `releaseRuntime`, so
370
- * quiesce → resume rebuilds it and re-runs the idempotent join ladder (redeem a
371
- * staged invitation, write this machine's own `MemberPeer` binding) from scratch.
372
- */
373
- private membershipReconcilers: Map<string, StrandMembershipReconciler> = new Map();
374
- /**
375
- * The per-strand first-sync gate (`strand-first-sync-gate.ts`), keyed by strand id:
376
- * holds a launch's `StrandDatabase` while it is NOT yet published on the instance.
377
- * Present from the moment the database object exists in `buildStrandRuntime` until
378
- * {@link publishDatabase} hands it to the app — so it doubles as the rollback handle
379
- * for a failed `initialize()` — and, for a joiner that holds no `Strand.Header` yet,
380
- * for as long as the launch stays `'syncing'`. Same lifecycle as {@link backfills}:
381
- * stopped (its database closed) and dropped in `releaseRuntime`, so a quiesce →
382
- * resume rebuild re-probes over the same store. An entry and `instance.database`
383
- * are mutually exclusive.
384
- */
385
- private firstSyncGates: Map<string, StrandFirstSyncGate> = new Map();
386
- /**
387
- * Callers blocked in {@link whenWritable}, keyed by strand id. Resolved by
388
- * {@link publishDatabase}, rejected by {@link stopStrand}; each waiter also carries
389
- * its own timeout. Deliberately NOT cleared by `releaseRuntime`: a waiter outlives a
390
- * quiesce → resume cycle, since the rebuild is what may finally publish the database.
391
- */
392
- private writableWaiters: Map<string, Set<WritableWaiter>> = new Map();
393
- /**
394
- * The per-strand relay-reservation supervisors — ONE PER CONFIGURED RELAY, each
395
- * over the node's own bare `/p2p-circuit` listener for that relay
396
- * (`strand-network-config.ts`) — keyed by strand id. Same lifecycle rationale as
397
- * {@link backfills}: started in `buildStrandRuntime` right after the libp2p node
398
- * exists, stopped FIRST and dropped in `releaseRuntime` (before the database
399
- * closes and the node stops, so no re-drive dials a node being torn down), so
400
- * quiesce → resume rebuilds them over the new node. What makes a strand node's
401
- * lost relay slot come back on its own — the control node has the same loop in
402
- * `CadreNode.reserveRelays`.
403
- */
404
- private relaySupervisors: Map<string, RelayReservationSupervisor[]> = new Map();
405
- /**
406
- * The resolved (cache-wrapped) raw storage per strand id — the instance's OWN
407
- * store, resolved once in `startStrand` and held until `stopStrand` disposes it.
408
- * Private for the same reason `backfills` is: runtime plumbing, not part of the
409
- * public {@link StrandInstance}.
410
- *
411
- * Deliberately NOT touched by `releaseRuntime`: that is what lets a quiesce →
412
- * resume cycle rebuild the libp2p node over the SAME store, keeping its
413
- * write-through cache warm (and, on an in-memory backend, keeping the strand's
414
- * blocks at all). An entry exists iff `instances` does AND the launch config
415
- * supplied a storage provider.
416
- *
417
- * NOTE: a hibernating strand therefore keeps its store — and its share of the
418
- * process-wide cache pool — resident for as long as the instance is tracked. That
419
- * is the point (a warm wake), and the pool evicts under pressure, so the cost is
420
- * one map entry per hibernating strand today. If a device ever hibernates strands
421
- * by the hundred, revisit: dropping the store at quiesce and paying for a cold
422
- * wake becomes the better trade.
423
- */
424
- private strandStorages: Map<string, IRawStorage> = new Map();
425
- private stopping = false;
426
-
427
- constructor() {
428
- log('StrandInstanceManager created');
429
- }
430
-
431
- /**
432
- * Get all current strand instances
433
- */
434
- getInstances(): Map<string, StrandInstance> {
435
- return new Map(this.instances);
436
- }
437
-
438
- /**
439
- * Get a specific strand instance
440
- */
441
- getInstance(strandId: string): StrandInstance | undefined {
442
- return this.instances.get(strandId);
443
- }
444
-
445
- /**
446
- * Check if a strand is currently running
447
- */
448
- hasStrand(strandId: string): boolean {
449
- return this.instances.has(strandId);
450
- }
451
-
452
- /**
453
- * Start a new strand instance.
454
- *
455
- * A failed launch leaves NOTHING tracked: the instance and its retained launch
456
- * config are both dropped before the error is rethrown, so the strand id is
457
- * free for a genuine retry. This matches the pre-registration failure path
458
- * (a rejected schema signature, which throws before anything is recorded) —
459
- * both failure modes of this call leave the same residue: none. Callers learn
460
- * of the failure from the rejected promise (and, on the control-discovered
461
- * path, from CadreNode's `strand:error` event), not from an error record left
462
- * behind in `instances`.
463
- *
464
- * The strand's raw storage is resolved HERE, once, and held for the instance's
465
- * lifetime (see `strandStorages`) — `buildStrandRuntime` only reads it, so a
466
- * hibernation wake never re-enters the embedder's provider.
467
- */
468
- async startStrand(config: StartStrandConfig): Promise<StrandInstance> {
469
- const { strandRow, sAppConfig } = config;
470
- const strandId = strandRow.Id;
471
-
472
- if (this.stopping) {
473
- throw new Error('StrandInstanceManager is stopping');
474
- }
475
-
476
- if (this.instances.has(strandId)) {
477
- // Callers resolve founder-ness BEFORE reaching here (CadreNode.launchStrand) and
478
- // honor a founder request on a tracked instance via foundExistingStrand — so a
479
- // founder flag arriving at this early return against a non-founder retained
480
- // config is a dropped bootstrap, and must never again be silent.
481
- if (config.founder === true && this.launchConfigs.get(strandId)?.founder !== true) {
482
- log('startStrand: strand %s is already running but was NOT launched as founder — ' +
483
- 'this early return DROPS the founder request; use foundExistingStrand', strandId);
484
- }
485
- log('Strand %s already running', strandId);
486
- return this.instances.get(strandId)!;
487
- }
488
-
489
- log('Starting strand instance: %s (sApp: %s v%s)', strandId, sAppConfig.id, sAppConfig.version);
490
- const tTotal = performance.now();
491
-
492
- // The id becomes two names below: the storage scope key the embedder's provider
493
- // turns into a directory or database name, and `networkName` in buildStrandRuntime,
494
- // from which the libp2p protocol prefix `/optimystic/strand-<id>` is built. A
495
- // replicated strand row carries whatever id the founding node wrote, so neither is
496
- // safe unchecked. Asserted HERE rather than in `resolveStrandStorage` because that
497
- // function returns early when no provider is configured — a node with no storage
498
- // still reaches buildStrandRuntime and still mints the protocol prefix.
499
- assertStrandScopeKey(strandId);
500
-
501
- // Verify schema signature before proceeding (fail-closed by default)
502
- const requireSignature = config.requireSignedSchemas ?? true;
503
- assertSchemaSignature(sAppConfig, { requireSignature });
504
- log('Strand %s sApp schema signature verified (author: %s)', strandId, sAppConfig.id);
505
-
506
- // Convert SAppConfig to SAppInfo for the instance
507
- const sAppInfo: SAppInfo = {
508
- id: sAppConfig.id,
509
- version: sAppConfig.version,
510
- schema: sAppConfig.schema,
511
- signature: sAppConfig.signature
512
- };
513
-
514
- // Resolve this strand's storage ONCE, before anything is recorded. If a factory
515
- // function is provided, it is called with the strandId to create strand-specific
516
- // storage (e.g. strand-isolated directories). A provider that throws therefore
517
- // fails the launch alongside the schema-signature check, leaving nothing tracked.
518
- const strandStorage = resolveStrandStorage(config.storage?.provider, strandId);
519
- if (strandStorage) {
520
- log('Strand %s using provided storage provider', strandId);
521
- }
522
-
523
- // Determine latency hint: sApp config > default
524
- const latencyHint = sAppConfig.latencyHint ?? config.defaultLatencyHint;
525
-
526
- const instance: StrandInstance = {
527
- strandId,
528
- status: 'starting',
529
- sAppInfo,
530
- memberPrivateKey: strandRow.MemberPrivateKey ?? undefined,
531
- connectedPeers: 0,
532
- lastActivity: new Date(),
533
- latencyHint
534
- };
535
-
536
- this.instances.set(strandId, instance);
537
- this.launchConfigs.set(strandId, config);
538
- if (strandStorage) {
539
- this.strandStorages.set(strandId, strandStorage);
540
- }
541
-
542
- try {
543
- await this.buildStrandRuntime(instance, config);
544
- timing('[startStrand:%s] total: %dms', strandId, Math.round(performance.now() - tTotal));
545
- log('Strand %s started successfully with sApp %s', strandId, sAppConfig.id);
546
- return instance;
547
- } catch (error) {
548
- // Status/error first — the (now discarded) record is still what `log` reports on.
549
- instance.status = 'error';
550
- instance.error = error instanceof Error ? error.message : String(error);
551
- log('Failed to start strand %s: %s', strandId, instance.error);
552
- // Drop the dead record so this strand id can be launched again. Keep the
553
- // `launchConfigs` has an entry iff `instances` does invariant — resumeStrand
554
- // reads both, and a config without an instance would strand the config.
555
- this.instances.delete(strandId);
556
- this.launchConfigs.delete(strandId);
557
- // The store this launch resolved goes with it: nothing owns it any more, and a
558
- // retained cache wrapper would be handed back (already retired) on a retry.
559
- await this.disposeStrandStorage(strandId);
560
- throw error;
561
- }
562
- }
563
-
564
- /**
565
- * Build (or rebuild) the libp2p node + StrandDatabase for an instance and
566
- * attach them, transitioning it to `active`. Shared by `startStrand` (fresh
567
- * launch) and `resumeStrand` (rehydrating a quiesced instance). Reads all
568
- * volatile inputs (bootstrapNodes, servingMachines, network, profile,
569
- * privateKey, sApp config) from `config`, so the caller controls the
570
- * cohort-derived values. Storage is the
571
- * one input it does NOT re-read from `config`: that belongs to the instance and
572
- * comes from `strandStorages`.
573
- */
574
- private async buildStrandRuntime(instance: StrandInstance, config: StartStrandConfig): Promise<void> {
575
- const strandId = instance.strandId;
576
- const { sAppConfig } = config;
577
-
578
- // The store the instance OWNS (resolved once in `startStrand`), not a fresh
579
- // resolution: a rebuild must reach the same backend through the same warm cache.
580
- const strandStorage = this.strandStorages.get(strandId);
581
-
582
- // db-p2p namespaces every one of the node's protocol ids by network name
583
- // (`/optimystic/<networkName>/...`), so anything dialing this node's own
584
- // services must derive its prefix from the SAME string the node was built
585
- // with — hence one binding for both, not two literals that can drift.
586
- const networkName = `strand-${strandId}`;
587
- const protocolPrefix = `/optimystic/${networkName}`;
588
-
589
- // Determine relay mode: if explicitly set in config, use that;
590
- // otherwise default to true for storage profile nodes.
591
- const enableRelay = config.network?.enableRelay ?? (config.profile === 'storage');
592
- // The strand-node VIEW of the machine's one `NetworkConfig`, not the control
593
- // node's resolution: fixed direct listen ports become ephemeral (two nodes cannot
594
- // bind one port), the announce config is dropped (it names the control node's
595
- // address), and every configured relay becomes one bare `/p2p-circuit` SEARCH
596
- // listener plus a dial addr in `relayAddrs` for the per-relay supervisor started
597
- // below — the same route the control node takes, because the configured
598
- // `<relay>/p2p-circuit` shape loses its address on a relay restart, a hangup, or
599
- // libp2p's own reservation refresh and recovers from none of them. See
600
- // `strand-network-config.ts` for all three, and `relay-reservation.ts`.
601
- //
602
- // `relayAddrs` is destructured OFF: it is not a `createLibp2pNode` option, and
603
- // spreading it would hand db-p2p a key it does not know.
604
- const { relayAddrs: relayDialAddrs = [], ...addrOptions } = strandNodeAddrs(config.network);
605
-
606
- // The CLOSED-strand revoked-peer gate (see strand-revocation-enforcer.ts).
607
- // Constructed BEFORE the libp2p node because the node's options embed its
608
- // predicates; its deny set starts empty (admit everything — fail-open, same
609
- // posture as bring-up everywhere here) and is first populated after the
610
- // strand database initializes below. Registered in the map immediately so
611
- // the failure rollback (releaseRuntime) tears it down like every other
612
- // runtime component. Open strands skip it entirely: their Member/MemberPeer
613
- // tables are empty by schema (`OnlyClosed`), so there is nothing to derive
614
- // a deny set from — arming would be pointless polling.
615
- const revocationEnforcer =
616
- config.strandRow.Type === 'c' && config.revocationEnforcement?.enabled !== false
617
- ? new StrandRevocationEnforcer({
618
- label: strandId,
619
- readRows: () => {
620
- const database = instance.database;
621
- if (!database) {
622
- throw new Error(`strand ${strandId} has no live database`);
623
- }
624
- return readStrandRevocationRows(database.getDatabase());
625
- },
626
- // Read per sweep, never captured: this closure is built BEFORE the
627
- // libp2p node exists (its options embed the enforcer's predicates),
628
- // and `releaseRuntime` clears the field again on quiesce. Undefined
629
- // therefore means "no transport right now", which the enforcer
630
- // treats as "nothing to tear down".
631
- getNetwork: () => instance.libp2pNode,
632
- onSelfRevoked: () => config.onSelfRevoked?.(strandId)
633
- }, config.revocationEnforcement)
634
- : undefined;
635
- if (revocationEnforcer) {
636
- this.revocationEnforcers.set(strandId, revocationEnforcer);
637
- }
638
-
639
- // Closed strands compose revoked-peer denial onto the caller's gater and arm
640
- // the fail-closed per-stream gate; open strands keep the raw configured gater
641
- // (their peers are legitimately cross-party and nothing is ever revoked).
642
- const revocationGateOptions = revocationEnforcer
643
- ? {
644
- connectionGater: createRevocationConnectionGater(revocationEnforcer, config.network?.connectionGater),
645
- authorizeInboundStream: (remotePeerId: string, protocol: string) =>
646
- revocationEnforcer.authorizeStream(remotePeerId, protocol)
647
- }
648
- : config.network?.connectionGater
649
- ? { connectionGater: config.network.connectionGater }
650
- : {};
651
-
652
- try {
653
- // Bound once: the breadth is also the ceiling on the repair yardstick below, and the
654
- // two must be derived from the same resolution. Inside the `try` deliberately — a
655
- // rejected clusterSize is a build failure that runs the same cleanup as any other.
656
- const strandClusterSize = resolveStrandClusterSize(config.clusterSize);
657
-
658
- let t0 = performance.now();
659
- const node = await createLibp2pNode({
660
- port: 0, // Random port
661
- bootstrapNodes: config.bootstrapNodes ?? [],
662
- networkName,
663
- storage: strandStorage,
664
- fretProfile: config.profile === 'storage' ? 'core' : 'edge',
665
- relay: enableRelay,
666
- clusterSize: strandClusterSize,
667
- // Deliberately NOT CONTROL_CLUSTER_POLICY: a strand is application data with its own
668
- // breadth reasoning, and the shape match with the control policy is a coincidence.
669
- //
670
- // The builder declares this node's block-repair corroboration yardstick from the
671
- // count of machines SERVING this strand, capped at the breadth above (a block
672
- // never lives on more machines than the cohort is wide). Given no count — the
673
- // production path today, since no per-strand serving count exists yet — it
674
- // returns the frozen STRAND_CLUSTER_POLICY itself, declaring nothing. Resolved
675
- // HERE rather than at `startStrand`, so a wake from hibernation would pick up a
676
- // serving set that changed while the strand slept.
677
- clusterPolicy: strandClusterPolicy(strandClusterSize, config.servingMachines),
678
- arachnode: {
679
- enableRingZulu: config.profile === 'storage'
680
- },
681
- ...(config.privateKey && { privateKey: config.privateKey }),
682
- ...(config.network?.transports && { transports: config.network.transports }),
683
- ...(config.network?.noiseCrypto && { noiseCrypto: config.network.noiseCrypto }),
684
- // Unconditional, and the same default the control node takes: every node of
685
- // every party runs the monitor over its connection to a slow phone, so the
686
- // widened ping deadline has to reach the strand nodes too (see
687
- // DEFAULT_CONNECTION_MONITOR).
688
- connectionMonitor: config.network?.connectionMonitor ?? DEFAULT_CONNECTION_MONITOR,
689
- // Listen entries plus the WebSocket transport switch they imply — a strand node
690
- // announces nothing the operator configured (`strand-network-config.ts`), and
691
- // spreads AFTER `transports` above because the switch is a no-op whenever the
692
- // embedder supplied its own factories. The bare `/p2p-circuit` entries (one per
693
- // relay) open no connection here; each registers a pending reservation that the
694
- // matching supervisor below fills, which is what gives a NAT'd strand node a
695
- // reachable relay slot — and works against a party-run relay because the launch
696
- // path announced this strand's derived peerId to it first (delegate admission;
697
- // see cadre-node.ts).
698
- ...addrOptions,
699
- // The raw configured gater (open strands), or the revocation-composed
700
- // gater plus the fail-closed per-stream revoked-peer gate (closed
701
- // strands) — resolved above, before the try.
702
- ...revocationGateOptions
703
- }) as Libp2pNodeWithRepo;
704
- timing('[buildStrandRuntime:%s] createLibp2pNode: %dms', strandId, Math.round(performance.now() - t0));
705
-
706
- instance.libp2pNode = node;
707
-
708
- // One reservation supervisor PER RELAY, started now so the first attempts
709
- // overlap the database bring-up below (the relay is never in a strand's
710
- // Optimystic cohort — its protocol ids are namespaced `/optimystic/strand-<id>/…`
711
- // — so an open relay connection cannot disturb that bring-up). Their first
712
- // attempts are awaited before the strand goes `active`, below. Registered in the
713
- // map immediately so the failure rollback (releaseRuntime) stops them like every
714
- // other runtime component.
715
- this.relaySupervisors.set(strandId, this.startRelaySupervisors(strandId, node, relayDialAddrs, config));
716
-
717
- // Create and initialize the StrandDatabase.
718
- //
719
- // Held by the first-sync gate (registered before initialize) rather than attached
720
- // to the instance: a failed init is then cleaned up by releaseRuntime below through
721
- // the gate (close() is safe on a partially-initialized db), and the app only ever
722
- // sees `instance.database` once this machine is allowed to write to the strand.
723
- t0 = performance.now();
724
- const strandDb = new StrandDatabase({
725
- strandId,
726
- sAppConfig,
727
- libp2pNode: node,
728
- coordinatedRepo: node.coordinatedRepo,
729
- // Founder bootstrap inputs: the strand's type drives which membership rows
730
- // are written, and the PARTY's own key (partyMemberPrivateKey, resolved by the
731
- // caller from the control-layer StrandPartyKey row) derives the founding
732
- // Member/Manager key. The row's shared MemberPrivateKey rides along as the
733
- // read-gating secret only — it derives nobody's identity.
734
- strandType: config.strandRow.Type,
735
- memberPrivateKey: config.strandRow.MemberPrivateKey ?? undefined,
736
- partyMemberPrivateKey: config.partyMemberPrivateKey,
737
- founder: config.founder
738
- });
739
- const gate = new StrandFirstSyncGate({
740
- label: strandId,
741
- database: strandDb,
742
- onHeaderHeld: () => this.publishDatabase(instance, strandDb)
743
- }, config.firstSync);
744
- this.firstSyncGates.set(strandId, gate);
745
- await strandDb.initialize();
746
- timing('[buildStrandRuntime:%s] strandDatabase.initialize: %dms', strandId, Math.round(performance.now() - t0));
747
-
748
- // The first-sync write gate. A founder just wrote the Header in its bootstrap; any
749
- // other machine may commit only once it holds the Header — which it can only have
750
- // received from a peer (now, or on an earlier run over the same store) — and has read
751
- // each App table once, so their collections are fetched too. Publishing the database
752
- // is what makes the strand writable to the app; until then the instance stays
753
- // `'syncing'` and the gate re-probes on its cadence. Everything armed below reads
754
- // `instance.database` lazily, so the reconciler and enforcer wait with it — and
755
- // `publishDatabase` kicks the reconciler when the wait ends, so a joiner's membership
756
- // rows land with the strand rather than one retry later.
757
- t0 = performance.now();
758
- if (config.founder === true || await strandFirstSyncComplete(strandDb.getDatabase(), strandId)) {
759
- this.publishDatabase(instance, strandDb);
760
- } else {
761
- gate.start();
762
- }
763
- timing('[buildStrandRuntime:%s] first-sync probe: %dms', strandId, Math.round(performance.now() - t0));
764
-
765
- // The membership reconciler: finish this party's join on every machine —
766
- // redeem a staged formation invitation if one is pending, then write the
767
- // durable machine→party binding (Strand.MemberPeer). Armed here, the one
768
- // seam where the strand's transport peer id and a live Database both exist
769
- // for launch AND hibernation resume, for closed strands that carry the
770
- // party's own membership key. start() kicks an immediate pass WITHOUT
771
- // awaiting it — a joiner at this instant has not synced the founder's rows
772
- // and may lack write quorum, so bring-up is never blocked; an unfinished join
773
- // then retries on a short doubling ladder capped at the configured
774
- // pollIntervalMs (which is also the flat cadence while nobody has admitted this
775
- // party yet), and the loop stops once the member row and this machine's own
776
- // binding are both in place. Armed AFTER the gate above, so a gated launch
777
- // always has a reconciler registered by the time the gate can publish.
778
- if (config.strandRow.Type === 'c' && config.partyMemberPrivateKey
779
- && config.membershipReconciliation?.enabled !== false) {
780
- const reconciler = new StrandMembershipReconciler({
781
- label: strandId,
782
- partyMemberPrivateKey: config.partyMemberPrivateKey,
783
- // Read per pass, never captured — same lifecycle argument as the
784
- // enforcer's getNetwork: quiesce drops both handles.
785
- getDatabase: () => instance.database?.getDatabase(),
786
- getOwnPeerId: () => instance.libp2pNode?.peerId.toString(),
787
- pendingInvite: config.pendingMembershipInvite,
788
- // The enforcer's CURRENT snapshot view of this node's own peer id — the
789
- // reconciler stops rather than fight a self-revocation. Absent when the
790
- // gate is disarmed (fail-open: the loop just runs).
791
- isSelfRevoked: revocationEnforcer
792
- ? () => {
793
- const ownPeerId = instance.libp2pNode?.peerId.toString();
794
- return ownPeerId !== undefined && revocationEnforcer.isRevoked(ownPeerId);
795
- }
796
- : undefined
797
- }, {
798
- pollIntervalMs: config.membershipReconciliation?.pollIntervalMs
799
- ?? config.revocationEnforcement?.pollIntervalMs
800
- });
801
- this.membershipReconcilers.set(strandId, reconciler);
802
- reconciler.start();
803
- }
804
-
805
- // Arm the revoked-peer deny-set poll now that the database it reads
806
- // exists. start() kicks an immediate refresh WITHOUT awaiting it —
807
- // bring-up and resume are never blocked on a membership read; until the
808
- // first read lands the empty snapshot admits everyone (fail-open).
809
- revocationEnforcer?.start();
810
-
811
- // Peer-join block catch-up: push this strand's own blocks to each newly
812
- // connected peer, so a machine that joined after blocks were committed
813
- // still ends up physically holding them (without per-strand storage there
814
- // is nothing to copy). Armed for EVERY stored strand: `PeerJoinBackfill`
815
- // only does work when the strand's libp2p node reports a peer connection,
816
- // so on a device that is genuinely alone it is inert, and arming it at
817
- // launch is what closes the "founded alone, never replicates" hole — a
818
- // peer that joins later gets the founder's blocks without any relaunch.
819
- // No `authorizePeer` gate, deliberately — see the module comment in
820
- // peer-join-backfill.ts for the strand-side argument (and why the control
821
- // network, which DOES gate, is different).
822
- //
823
- // NOTE: cost is one PeerJoinBackfill object + one `connection:open` listener
824
- // per running strand — linear in strand count, negligible at the handful a
825
- // device or host runs today. If a node ever hosts strands by the hundred,
826
- // move to one shared listener that dispatches by strand id.
827
- if (strandStorage && config.backfill?.enabled !== false) {
828
- if (node.keyNetwork) {
829
- const backfill = new PeerJoinBackfill({
830
- label: strandId,
831
- libp2p: node,
832
- peerNetwork: node.keyNetwork,
833
- storage: strandStorage,
834
- // The same prefix the receiver registered its block-transfer handler
835
- // under — derived from networkName above, never re-spelled here.
836
- protocolPrefix
837
- }, config.backfill);
838
- backfill.start();
839
- this.backfills.set(strandId, backfill);
840
- } else {
841
- log('Strand %s: libp2p node exposes no keyNetwork; peer-join block catch-up is inert', strandId);
842
- }
843
- }
844
-
845
- // The relay supervisors' FIRST attempts, all of them, before `active`: the happy
846
- // path still publishes its circuit addr before `addStrand` resolves (the
847
- // strand-addr RPC answers read it, and the same-party circuit scenario asserts
848
- // it). Fail-SOFT — a first attempt that lands nothing does not fail the launch.
849
- // The strand's database is up, and the supervisor keeps trying on its backoff;
850
- // failing here would only trade that for `StrandWatcher`'s full-rebuild retry.
851
- //
852
- // NOTE: a relay that is down costs this launch one full drive (10 s), and
853
- // `StrandWatcher` launches strands one at a time — so N strands cost N × 10 s
854
- // of bring-up during a relay outage. If that ever matters, stop awaiting here
855
- // (the circuit addr then lands after `active`) rather than shortening the drive.
856
- t0 = performance.now();
857
- await this.awaitFirstRelayAttempts(strandId);
858
- timing('[buildStrandRuntime:%s] relay first attempts: %dms', strandId, Math.round(performance.now() - t0));
859
-
860
- instance.status = liveStrandStatus(instance);
861
- instance.lastActivity = new Date();
862
- if (instance.status === 'syncing') {
863
- log('Strand %s launched as a joiner with no Strand.Header held yet — writes are withheld until ' +
864
- 'a member of the strand is reached', strandId);
865
- }
866
- } catch (error) {
867
- // Roll back any partially-attached runtime so the instance is left with
868
- // NEITHER handle. Otherwise the `libp2pNode || database` "already live"
869
- // guard in resumeStrand/handleStrandWake would treat a half-built strand
870
- // as healthy — leaking the libp2p node and never retrying the rebuild.
871
- await this.releaseRuntime(instance).catch((cleanupErr) => {
872
- log('buildStrandRuntime cleanup for strand %s also failed: %o', strandId, cleanupErr);
873
- });
874
- throw error;
875
- }
876
- }
877
-
878
- /**
879
- * Release an instance's strand-network runtime: stop the relay supervisors and
880
- * the other background loops, close the StrandDatabase, then stop the libp2p
881
- * node (construction order in reverse), clearing both fields and zeroing
882
- * connectedPeers. Tolerant of partially-built state — either handle may be
883
- * absent — so it doubles as rollback for a failed `buildStrandRuntime`. Shared
884
- * by `quiesceStrand`, `stopStrand`, and that rollback path.
885
- *
886
- * Leaves `strandStorages` untouched by design — the store outlives the runtime it
887
- * was built into, which is what makes a resume warm. Only `stopStrand` disposes it.
888
- */
889
- private async releaseRuntime(instance: StrandInstance): Promise<void> {
890
- // Relay supervisors FIRST of all — before anything below is torn down — so no
891
- // re-drive is scheduled against a node being stopped. `stop()` is synchronous
892
- // and never awaits a drive, so a relay that is down cannot delay this teardown.
893
- // NOTE: a drive ALREADY in flight cannot be aborted (the drive takes no
894
- // AbortSignal — `backlog/bug-relay-drive-not-cancellable`); it fails soft
895
- // against the stopped node within its own 10 s deadline and its result is
896
- // discarded.
897
- const relaySupervisors = this.relaySupervisors.get(instance.strandId);
898
- if (relaySupervisors) {
899
- relaySupervisors.forEach((supervisor) => supervisor.stop());
900
- this.relaySupervisors.delete(instance.strandId);
901
- }
902
- // Backfill next — before the database closes and the libp2p node stops — so
903
- // no NEW catch-up push is issued against a torn-down transport. A push already
904
- // in flight is not awaited; it fails into the module's own per-chunk catch.
905
- const backfill = this.backfills.get(instance.strandId);
906
- if (backfill) {
907
- backfill.stop();
908
- this.backfills.delete(instance.strandId);
909
- }
910
- // The revoked-peer enforcer goes with the runtime it gated: a resume
911
- // rebuilds it with a fresh (initially empty, fail-open) snapshot.
912
- const revocationEnforcer = this.revocationEnforcers.get(instance.strandId);
913
- if (revocationEnforcer) {
914
- revocationEnforcer.stop();
915
- this.revocationEnforcers.delete(instance.strandId);
916
- }
917
- // The membership reconciler likewise: a resume rebuilds it and re-runs the
918
- // idempotent ladder, which is what makes resume-after-partial-join heal.
919
- const membershipReconciler = this.membershipReconcilers.get(instance.strandId);
920
- if (membershipReconciler) {
921
- membershipReconciler.stop();
922
- this.membershipReconcilers.delete(instance.strandId);
923
- }
924
- // A still-gated database (a joiner that never received the Header, or a launch whose
925
- // initialize() failed) is closed through its gate; a published one through the
926
- // instance. Never both — publishing moves the handle from the gate to the instance.
927
- const gate = this.firstSyncGates.get(instance.strandId);
928
- if (gate) {
929
- gate.stop();
930
- this.firstSyncGates.delete(instance.strandId);
931
- await gate.database.close();
932
- }
933
- if (instance.database) {
934
- await instance.database.close();
935
- instance.database = undefined;
936
- }
937
- if (instance.libp2pNode) {
938
- await instance.libp2pNode.stop();
939
- instance.libp2pNode = undefined;
940
- }
941
- instance.connectedPeers = 0;
942
- }
943
-
944
- /**
945
- * One {@link superviseRelayReservation} per relay dial addr, each over exactly
946
- * that relay so "held" is judged per relay (`circuitMultiaddrsVia`) and losing
947
- * one relay re-drives only that one. Default timings — the control node's (2 s
948
- * doubling to 60 s between failed attempts, a 5 s liveness check while held).
949
- *
950
- * Each supervisor's `beforeRedrive` is the caller's
951
- * {@link StartStrandConfig.announceDelegateToRelay} for THIS relay and THIS
952
- * node's peer id, so a re-drive after a relay restart is preceded by a fresh
953
- * delegate grant on the relay about to be dialed. Returns `[]` when no relay is
954
- * configured — the strand then simply has no circuit listener to fill.
955
- */
956
- private startRelaySupervisors(
957
- strandId: string,
958
- node: Libp2pNodeWithRepo,
959
- relayDialAddrs: readonly string[],
960
- config: StartStrandConfig
961
- ): RelayReservationSupervisor[] {
962
- if (relayDialAddrs.length === 0) {
963
- return [];
964
- }
965
- const announce = config.announceDelegateToRelay;
966
- const delegatePeerId = node.peerId.toString();
967
- return relayDialAddrs.map((relayAddr) => superviseRelayReservation(node, [relayAddr], {
968
- ...(announce && { beforeRedrive: () => announce(strandId, relayAddr, delegatePeerId) })
969
- }));
970
- }
971
-
972
- /**
973
- * Wait for every relay supervisor's first attempt to settle, concurrently, and log
974
- * the ones that landed nothing. Never throws — a strand whose relay is unreachable
975
- * at launch still comes up, with its supervisors retrying in the background.
976
- */
977
- private async awaitFirstRelayAttempts(strandId: string): Promise<void> {
978
- const supervisors = this.relaySupervisors.get(strandId) ?? [];
979
- if (supervisors.length === 0) {
980
- return;
981
- }
982
- await Promise.all(supervisors.map((supervisor) => supervisor.firstAttempt));
983
- supervisors.forEach((supervisor) => {
984
- if (supervisor.lastError !== null) {
985
- log('Strand %s: relay reservation not held after the first attempt (retrying in the background): %s',
986
- strandId, supervisor.lastError);
987
- }
988
- });
989
- }
990
-
991
- /**
992
- * Drop the strand's owned store and release this strand's claim on its cache. The
993
- * wrapper counts holders, so the cache is emptied and unregistered from the shared
994
- * pool only if no other scope still holds it. Called only where the strand's whole
995
- * lifetime ends (`stopStrand`, and the failed-launch rollback) — never on a quiesce.
996
- *
997
- * A dispose failure is logged, not thrown: the store is already unreferenced here,
998
- * and failing the stop over a cache-bookkeeping error would leave the caller unable
999
- * to tear the strand down. `disposeStorageCache` no-ops for an unwrapped store
1000
- * (e.g. `MemoryRawStorage`), so no instanceof test is needed.
1001
- */
1002
- private async disposeStrandStorage(strandId: string): Promise<void> {
1003
- const storage = this.strandStorages.get(strandId);
1004
- if (!storage) {
1005
- return;
1006
- }
1007
- this.strandStorages.delete(strandId);
1008
- try {
1009
- await disposeStorageCache(storage);
1010
- } catch (error) {
1011
- log('Failed to dispose storage cache for strand %s: %o', strandId, error);
1012
- }
1013
- }
1014
-
1015
- /**
1016
- * Refresh a strand's revoked-peer deny set NOW — and, with it, run the
1017
- * teardown sweep that hangs up every connected revoked peer.
1018
- *
1019
- * The gate is otherwise poll-driven (default
1020
- * `DEFAULT_REVOCATION_POLL_INTERVAL_MS`), because neither a replicated
1021
- * revocation nor a local `revokeMember`/`leaveStrand` raises anything this
1022
- * runtime can hook. A caller that just wrote a revocation against the
1023
- * strand's database should follow it with this call, which makes the cut
1024
- * immediate instead of waiting out the interval.
1025
- *
1026
- * Quiet no-op — matching `quiesceStrand`'s posture — when the strand is not
1027
- * tracked, is quiesced, is open, or has the gate disabled: in every one of
1028
- * those cases there is no enforcer to refresh. Never rejects (the enforcer's
1029
- * refresh contains its own failures), and resolves only once the sweep has
1030
- * finished.
1031
- */
1032
- async refreshRevocationEnforcement(strandId: string): Promise<void> {
1033
- const enforcer = this.revocationEnforcers.get(strandId);
1034
- if (!enforcer) {
1035
- log('refreshRevocationEnforcement: strand %s has no armed revocation enforcer', strandId);
1036
- return;
1037
- }
1038
- await enforcer.refresh();
1039
- }
1040
-
1041
- /**
1042
- * Best-effort removal of THIS machine's own `Strand.MemberPeer` binding — the
1043
- * self arm of `removeMemberPeer`, signed with the retained launch config's party
1044
- * key. Called by `CadreNode.unpublishStrand` BEFORE the local stop, while the
1045
- * strand database and transport are still live: after the unpublish commits, the
1046
- * party's `StrandPartyKey` control row is gone, so no restart could ever sign
1047
- * this removal again — the in-memory retained key is the last chance.
1048
- *
1049
- * Never throws. Quiet no-op for a strand that is untracked, open, or launched
1050
- * without a party key; a quiesced (hibernating) strand, or a strand whose write
1051
- * quorum is already unreachable, leaves the stale binding behind with a log —
1052
- * it grants nothing today (admission is not allowlist-gated) and only
1053
- * mis-credits diversity. The strand's own membership reconciler is stopped —
1054
- * and its in-flight pass awaited — FIRST, so a pass that was already past its
1055
- * own stopped check cannot re-register the binding this is about to clear.
1056
- *
1057
- * NOTE: deliberately NOT handled here (or anywhere yet): clearing the bindings
1058
- * of a machine removed from the CADRE at the control layer, or of a party's
1059
- * OTHER machines when the party unpublishes — the party still holds the key on
1060
- * every surviving machine and can clear from any of them, and the stale rows
1061
- * grant nothing while admission is deny-list only. Revisit when
1062
- * `feat-strand-member-allowlist-admission` lands and a stale binding starts
1063
- * granting admission rather than merely mis-crediting diversity.
1064
- */
1065
- async clearOwnMemberPeerBinding(strandId: string): Promise<void> {
1066
- const instance = this.instances.get(strandId);
1067
- const config = this.launchConfigs.get(strandId);
1068
- if (!instance || !config || config.strandRow.Type !== 'c' || !config.partyMemberPrivateKey) {
1069
- return;
1070
- }
1071
- const reconciler = this.membershipReconcilers.get(strandId);
1072
- if (reconciler) {
1073
- reconciler.stop();
1074
- await reconciler.settle();
1075
- }
1076
- const db = instance.database?.getDatabase();
1077
- const peerId = instance.libp2pNode?.peerId.toString();
1078
- if (!db || !peerId) {
1079
- log('clearOwnMemberPeerBinding: strand %s has no live runtime — own MemberPeer binding left in place', strandId);
1080
- return;
1081
- }
1082
- try {
1083
- // Background write on the app's database: never join a transaction the app has open.
1084
- await removeMemberPeer(db, {
1085
- memberKeyPair: strandMemberKeyPair(config.partyMemberPrivateKey),
1086
- peerId
1087
- }, { joinOpenTransaction: false });
1088
- log('clearOwnMemberPeerBinding: strand %s — own binding for peer %s cleared', strandId, peerId);
1089
- } catch (error) {
1090
- log('clearOwnMemberPeerBinding: strand %s — best-effort clear failed (strand may already be unreachable): %o',
1091
- strandId, error);
1092
- }
1093
- }
1094
-
1095
- /**
1096
- * Quiesce a strand: release its strand-network resources (stop the libp2p node,
1097
- * close the StrandDatabase) while RETAINING the instance record — identity,
1098
- * sAppInfo, keys, latency hint, metadata — and its launch config so it can be
1099
- * resumed later. Mechanically this is `stopStrand` minus the instance/config
1100
- * deletion. The caller sets the post-quiesce status (e.g. `hibernating`).
1101
- * No-ops when the strand is missing or already quiesced.
1102
- */
1103
- async quiesceStrand(strandId: string): Promise<void> {
1104
- const instance = this.instances.get(strandId);
1105
- if (!instance) {
1106
- log('quiesceStrand: strand %s not found', strandId);
1107
- return;
1108
- }
1109
- if (!instance.libp2pNode && !instance.database) {
1110
- log('quiesceStrand: strand %s already quiesced', strandId);
1111
- return;
1112
- }
1113
-
1114
- log('Quiescing strand instance: %s', strandId);
1115
- await this.releaseRuntime(instance);
1116
- log('Strand %s quiesced (resources released, instance retained)', strandId);
1117
- }
1118
-
1119
- /**
1120
- * Resume a previously-quiesced strand: rebuild its libp2p node + StrandDatabase
1121
- * from the retained launch config and re-attach them, transitioning it back to
1122
- * `active`. `overrides` re-applies volatile inputs that may have changed since
1123
- * launch (the cohort `bootstrapNodes` seed and the strand's `servingMachines`
1124
- * count) and updates the retained config so a later resume reuses the latest
1125
- * values. Returns the live instance unchanged if it is already running.
1126
- */
1127
- async resumeStrand(strandId: string, overrides?: ResumeStrandOverrides): Promise<StrandInstance> {
1128
- if (this.stopping) {
1129
- throw new Error('StrandInstanceManager is stopping');
1130
- }
1131
- const instance = this.instances.get(strandId);
1132
- if (!instance) {
1133
- throw new Error(`Cannot resume strand ${strandId}: not tracked`);
1134
- }
1135
- const launchConfig = this.launchConfigs.get(strandId);
1136
- if (!launchConfig) {
1137
- throw new Error(`Cannot resume strand ${strandId}: no retained launch config`);
1138
- }
1139
- if (instance.libp2pNode || instance.database) {
1140
- log('resumeStrand: strand %s already live', strandId);
1141
- return instance;
1142
- }
1143
-
1144
- log('Resuming strand instance: %s', strandId);
1145
- const tTotal = performance.now();
1146
-
1147
- // Re-apply volatile inputs and persist them so a subsequent resume reuses them.
1148
- // Each `??` matters: a resume that passes no override must keep the retained value,
1149
- // and a resume that passes one must leave it retained for the next resume — otherwise
1150
- // a later no-override wake silently reverts to whatever launch time saw.
1151
- const resumeConfig: StartStrandConfig = {
1152
- ...launchConfig,
1153
- bootstrapNodes: overrides?.bootstrapNodes ?? launchConfig.bootstrapNodes,
1154
- // NOTE: `??` retains, so an override can raise or lower the count but cannot CLEAR it
1155
- // back to "this node no longer knows" — the direction that would declare nothing. Moot
1156
- // while nothing feeds `servingMachines` at all; if a source lands
1157
- // (`backlog/feat-strand-yardstick-from-serving-machines`) that can legitimately lose the
1158
- // count — a strand whose member rows became unreadable — this merge must gain an explicit
1159
- // clear rather than silently declaring a stale number over a serving set it can no longer
1160
- // see. Same applies to `bootstrapNodes` above, where a stale seed is harmless.
1161
- servingMachines: overrides?.servingMachines ?? launchConfig.servingMachines
1162
- };
1163
- this.launchConfigs.set(strandId, resumeConfig);
1164
-
1165
- instance.status = 'starting';
1166
- try {
1167
- await this.buildStrandRuntime(instance, resumeConfig);
1168
- timing('[resumeStrand:%s] total: %dms', strandId, Math.round(performance.now() - tTotal));
1169
- log('Strand %s resumed successfully', strandId);
1170
- return instance;
1171
- } catch (error) {
1172
- instance.status = 'error';
1173
- instance.error = error instanceof Error ? error.message : String(error);
1174
- log('Failed to resume strand %s: %s', strandId, instance.error);
1175
- throw error;
1176
- }
1177
- }
1178
-
1179
- /**
1180
- * Honor a founder request against an ALREADY-TRACKED strand — the seam that
1181
- * closes the "whoever launches first decides whether the bootstrap runs" gap:
1182
- * an instance first launched as a joiner (an app's own attach, or a watcher
1183
- * poll winning the launch race) used to swallow a later founder request
1184
- * silently, leaving the strand active with no `Strand.Header`.
1185
- *
1186
- * Flips the RETAINED launch config's `founder` to true, so every later
1187
- * quiesce → resume rebuild founds as well (the bootstrap is insert-if-absent —
1188
- * {@link StrandDatabase.ensureFounderBootstrap} — so re-running it per rebuild
1189
- * writes nothing twice), and runs the bootstrap against the live database now.
1190
- *
1191
- * @returns how the request resolved:
1192
- * - `'already-founder'` — the retained config already founds; nothing to do.
1193
- * - `'bootstrapped'` — config flipped and the live database ran the bootstrap.
1194
- * - `'needs-resume'` — config flipped, but the instance is quiesced (no live
1195
- * database), so the bootstrap could not run here: the CALLER must wake the
1196
- * strand (`CadreNode.wakeStrand`, which owns the hibernation bookkeeping this
1197
- * manager does not) so the rebuild — which now founds — runs it.
1198
- * @param resolvePartyKey - Asked for the party's own membership key when (and only
1199
- * when) a CLOSED strand's retained config carries none — the instance was launched
1200
- * as a joiner before its `StrandPartyKey` row existed or replicated. The resolved
1201
- * key is retained alongside the founder flip so the bootstrap (now, or on the
1202
- * caller's wake for `'needs-resume'`) can seat the founding Member/Manager.
1203
- * @throws when the strand is not tracked — this seam exists only for the
1204
- * tracked-instance launch path; an untracked id is a caller bug.
1205
- * @throws whatever the live bootstrap throws (e.g. `PreSplitStrandIdentityError`),
1206
- * after {@link withdrawFounderRequest} — so a retry re-attempts the founding rather
1207
- * than resolving `'already-founder'` over an instance that never founded. A caller
1208
- * whose `'needs-resume'` wake fails owes the same withdrawal.
1209
- */
1210
- async foundExistingStrand(
1211
- strandId: string,
1212
- resolvePartyKey?: () => Promise<string | undefined>
1213
- ): Promise<'already-founder' | 'bootstrapped' | 'needs-resume'> {
1214
- const instance = this.instances.get(strandId);
1215
- const config = this.launchConfigs.get(strandId);
1216
- if (!instance || !config) {
1217
- throw new Error(`Cannot found strand ${strandId}: not tracked`);
1218
- }
1219
- if (config.founder === true) {
1220
- return 'already-founder';
1221
- }
1222
- const partyMemberPrivateKey =
1223
- config.partyMemberPrivateKey
1224
- ?? (config.strandRow.Type === 'c' ? await resolvePartyKey?.() : undefined);
1225
- // A fresh object rather than mutating in place: startStrand retains the CALLER'S
1226
- // config object, which is not ours to rewrite.
1227
- this.launchConfigs.set(strandId, { ...config, founder: true, partyMemberPrivateKey });
1228
- if (!instance.database && !this.firstSyncGates.has(strandId)) {
1229
- return 'needs-resume';
1230
- }
1231
- try {
1232
- await this.ensureFounderBootstrap(strandId);
1233
- } catch (error) {
1234
- this.withdrawFounderRequest(strandId);
1235
- throw error;
1236
- }
1237
- return 'bootstrapped';
1238
- }
1239
-
1240
- /**
1241
- * Whether `strandId` is launched but still waiting for its first sync — a joiner whose
1242
- * runtime is up while its database is withheld (status `'syncing'`, or `'idle'` after
1243
- * the hibernation manager's idle timer fired on it). `false` for a writable, quiesced,
1244
- * or untracked strand. The predicate {@link whenWritable}'s callers gate on.
1245
- */
1246
- isAwaitingFirstSync(strandId: string): boolean {
1247
- const instance = this.instances.get(strandId);
1248
- return instance !== undefined && isAwaitingFirstSync(instance);
1249
- }
1250
-
1251
- /**
1252
- * Resolve once the strand's database is published to the app — immediately for a
1253
- * writable strand — or reject with {@link StrandAwaitingFirstSyncError} after
1254
- * `timeoutMs` (default: the retained launch config's `firstSync.timeoutMs`, else
1255
- * {@link DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS}). The rejection is RETRYABLE: nothing is
1256
- * torn down, the gate keeps probing, and a later call waits afresh. A quiesced
1257
- * (hibernating) strand is not woken here — the wait spans a resume, so a caller that
1258
- * wants one wakes it (`CadreNode.wakeStrand`) and waits. Rejects immediately for an
1259
- * untracked strand, and whenever the strand is stopped while a wait is pending.
1260
- */
1261
- whenWritable(strandId: string, options?: { timeoutMs?: number }): Promise<StrandInstance> {
1262
- const instance = this.instances.get(strandId);
1263
- if (!instance) {
1264
- return Promise.reject(new Error(`Cannot wait for strand ${strandId} to become writable: not tracked`));
1265
- }
1266
- if (instance.database) {
1267
- return Promise.resolve(instance);
1268
- }
1269
- const timeoutMs = options?.timeoutMs
1270
- ?? this.launchConfigs.get(strandId)?.firstSync?.timeoutMs
1271
- ?? DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS;
1272
- const startedAt = Date.now();
1273
- return new Promise<StrandInstance>((resolve, reject) => {
1274
- const waiters = this.writableWaiters.get(strandId) ?? new Set<WritableWaiter>();
1275
- this.writableWaiters.set(strandId, waiters);
1276
- const settle = (): void => {
1277
- clearTimeout(timer);
1278
- waiters.delete(waiter);
1279
- if (waiters.size === 0) {
1280
- this.writableWaiters.delete(strandId);
1281
- }
1282
- };
1283
- const waiter: WritableWaiter = {
1284
- resolve: () => { settle(); resolve(instance); },
1285
- reject: (error) => { settle(); reject(error); }
1286
- };
1287
- const timer = setTimeout(
1288
- () => waiter.reject(new StrandAwaitingFirstSyncError(strandId, Date.now() - startedAt)),
1289
- timeoutMs);
1290
- (timer as { unref?: () => void }).unref?.();
1291
- waiters.add(waiter);
1292
- });
1293
- }
1294
-
1295
- /**
1296
- * Hand a launch's database to the app: set `instance.database`, retire the gate that
1297
- * held it, release every {@link whenWritable} waiter, and — when the launch had already
1298
- * been reported gated — flip it `'active'` and announce it through the retained config's
1299
- * `onWritable`. "Reported gated" is any status but `'starting'`: `'syncing'`, or the
1300
- * `'idle'` the hibernation manager's idle timer flips a long-gated joiner to (see
1301
- * {@link isAwaitingFirstSync}) — the Header arriving after that flip must announce too,
1302
- * or an app hanging on `strand:writable` never learns the strand opened. A publish that
1303
- * lands while the instance is still `'starting'` (the Header arrived during the rest of
1304
- * bring-up) announces nothing: `startStrand` / `resumeStrand` are about to report the
1305
- * strand `'active'`, and `strand:writable` is defined as the follow-up to a gated
1306
- * launch, never a duplicate of `strand:started`.
1307
- *
1308
- * It is also the one seam where a WITHHELD database becomes available, so it kicks the
1309
- * membership reconciler: on a gated launch that loop's own immediate pass ran while
1310
- * `instance.database` was still unset, found no database, and would otherwise not try
1311
- * again until its retry timer fired. A launch that was never gated publishes here BEFORE
1312
- * the reconciler is constructed, so there is nothing registered to kick and the loop's own
1313
- * immediate pass already sees the database — which is why the kick needs no `wasGated`
1314
- * test of its own.
1315
- */
1316
- private publishDatabase(instance: StrandInstance, database: StrandDatabase): void {
1317
- const strandId = instance.strandId;
1318
- const gate = this.firstSyncGates.get(strandId);
1319
- if (gate) {
1320
- gate.open();
1321
- this.firstSyncGates.delete(strandId);
1322
- }
1323
- instance.database = database;
1324
- instance.lastActivity = new Date();
1325
- const wasGated = instance.status !== 'starting';
1326
- if (wasGated) {
1327
- instance.status = 'active';
1328
- log('Strand %s is now writable: Strand.Header held', strandId);
1329
- }
1330
- const waiters = this.writableWaiters.get(strandId);
1331
- if (waiters) {
1332
- this.writableWaiters.delete(strandId);
1333
- waiters.forEach((waiter) => waiter.resolve());
1334
- }
1335
- if (wasGated) {
1336
- this.launchConfigs.get(strandId)?.onWritable?.(strandId);
1337
- }
1338
- // Not awaited: publishing must stay synchronous, and the pass chains on the loop's own
1339
- // tail, so it cannot overlap a pass already in flight.
1340
- void this.membershipReconcilers.get(strandId)?.reconcile();
1341
- }
1342
-
1343
- /** Reject every {@link whenWritable} waiter for a strand that is going away. */
1344
- private rejectWritableWaiters(strandId: string, reason: string): void {
1345
- const waiters = this.writableWaiters.get(strandId);
1346
- if (!waiters) {
1347
- return;
1348
- }
1349
- this.writableWaiters.delete(strandId);
1350
- waiters.forEach((waiter) => waiter.reject(new Error(`Strand ${strandId} ${reason} before becoming writable`)));
1351
- }
1352
-
1353
- /**
1354
- * Undo {@link foundExistingStrand}'s founder flip after the founding it promised
1355
- * failed, so the retained config again says what this instance actually runs as (a
1356
- * joiner) and the next founder request re-attempts the bootstrap. The resolved party
1357
- * key stays retained — it is this party's identity for the strand either way. No-op
1358
- * when the strand is untracked or its config does not found.
1359
- */
1360
- withdrawFounderRequest(strandId: string): void {
1361
- const config = this.launchConfigs.get(strandId);
1362
- if (config?.founder === true) {
1363
- this.launchConfigs.set(strandId, { ...config, founder: false });
1364
- }
1365
- }
1366
-
1367
- /**
1368
- * Run the (idempotent) founder bootstrap against a tracked strand's LIVE
1369
- * database, independently of what the retained launch config says.
1370
- *
1371
- * Separate from {@link foundExistingStrand} because a caller that resolved
1372
- * `'needs-resume'` and woke the strand must not assume the wake's own rebuild
1373
- * founded it: `HibernationManager` COALESCES wakes, so a wake already in flight
1374
- * when the config flipped had already read the PRE-flip config and rebuilt as a
1375
- * joiner. Re-running the bootstrap costs one insert-if-absent probe per table
1376
- * and is the only thing that makes "founding resolves once the Header is
1377
- * written" true on that path.
1378
- *
1379
- * A strand still `'syncing'` (its database withheld behind the first-sync gate) is
1380
- * founded through the gate: the bootstrap writes the Header this machine was waiting
1381
- * to receive, so a successful run publishes the database and the strand goes
1382
- * `'active'` — the one legitimate way a joiner launch becomes writable without a peer.
1383
- *
1384
- * @throws when the strand is not tracked, or is still quiesced (no live
1385
- * database) — both mean the bootstrap did NOT run, which a founder request
1386
- * must never swallow.
1387
- */
1388
- async ensureFounderBootstrap(strandId: string): Promise<void> {
1389
- const instance = this.instances.get(strandId);
1390
- if (!instance) {
1391
- throw new Error(`Cannot run the founder bootstrap for strand ${strandId}: not tracked`);
1392
- }
1393
- const gate = this.firstSyncGates.get(strandId);
1394
- const database = instance.database ?? gate?.database;
1395
- if (!database) {
1396
- throw new Error(
1397
- `Cannot run the founder bootstrap for strand ${strandId}: it is quiesced, so there ` +
1398
- 'is no live database to write to — resume it first.'
1399
- );
1400
- }
1401
- // Forward the RETAINED config's party key: a foundExistingStrand that flipped a
1402
- // joiner launch to founder may have resolved a key the live database's captured
1403
- // config (built at the original launch) never saw.
1404
- await database.ensureFounderBootstrap(this.launchConfigs.get(strandId)?.partyMemberPrivateKey);
1405
- if (!instance.database) {
1406
- this.publishDatabase(instance, database);
1407
- }
1408
- }
1409
-
1410
- /**
1411
- * Stop a strand instance
1412
- */
1413
- async stopStrand(strandId: string): Promise<void> {
1414
- const instance = this.instances.get(strandId);
1415
- if (!instance) {
1416
- log('Strand %s not found', strandId);
1417
- return;
1418
- }
1419
-
1420
- log('Stopping strand instance: %s', strandId);
1421
- instance.status = 'stopping';
1422
- this.rejectWritableWaiters(strandId, 'was stopped');
1423
-
1424
- try {
1425
- await this.releaseRuntime(instance);
1426
- instance.status = 'stopped';
1427
- this.instances.delete(strandId);
1428
- this.launchConfigs.delete(strandId);
1429
- // Storage is released only here — NOT in releaseRuntime, which a quiesce shares.
1430
- await this.disposeStrandStorage(strandId);
1431
- log('Strand %s stopped successfully', strandId);
1432
- } catch (error) {
1433
- instance.status = 'error';
1434
- instance.error = error instanceof Error ? error.message : String(error);
1435
- log('Error stopping strand %s: %s', strandId, instance.error);
1436
- throw error;
1437
- }
1438
- }
1439
-
1440
- /**
1441
- * Stop all strand instances
1442
- */
1443
- async stopAll(): Promise<void> {
1444
- this.stopping = true;
1445
- log('Stopping all strand instances (%d)', this.instances.size);
1446
-
1447
- const stopPromises = Array.from(this.instances.keys()).map(id =>
1448
- this.stopStrand(id).catch(err => {
1449
- log('Error stopping strand %s during shutdown: %s', id, err);
1450
- })
1451
- );
1452
-
1453
- await Promise.all(stopPromises);
1454
- this.stopping = false;
1455
- log('All strand instances stopped');
1456
- }
1457
- }
1458
-
1
+ import debug from 'debug';
2
+ import type { PrivateKey } from '@libp2p/interface';
3
+ import { createLibp2pNode, type IRawStorage } from '@optimystic/db-p2p';
4
+ import { wrapStorageWithCache, disposeStorageCache } from '@serfab/quereus-plugin-sereus';
5
+ import { StrandDatabase } from './strand-database.js';
6
+ import { PeerJoinBackfill, type PeerJoinBackfillConfig } from './peer-join-backfill.js';
7
+ import {
8
+ StrandRevocationEnforcer,
9
+ createRevocationConnectionGater,
10
+ readStrandRevocationRows,
11
+ type StrandRevocationEnforcementConfig
12
+ } from './strand-revocation-enforcer.js';
13
+ import {
14
+ StrandMembershipReconciler,
15
+ type PendingMembershipInviteSource,
16
+ type StrandMembershipReconciliationConfig
17
+ } from './strand-membership-reconciler.js';
18
+ import { removeMemberPeer } from './strand-membership-writer.js';
19
+ import { strandMemberKeyPair } from './strand-member-key.js';
20
+ import { assertSchemaSignature } from './schema-verification.js';
21
+ import { assertStrandScopeKey } from './storage-scope.js';
22
+ import {
23
+ StrandFirstSyncGate,
24
+ StrandAwaitingFirstSyncError,
25
+ strandFirstSyncComplete,
26
+ DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS,
27
+ type StrandFirstSyncConfig
28
+ } from './strand-first-sync-gate.js';
29
+ import type {
30
+ StrandInstance,
31
+ StrandRow,
32
+ StorageConfig,
33
+ NetworkConfig,
34
+ LatencyHint,
35
+ NodeProfile,
36
+ SAppConfig,
37
+ SAppInfo,
38
+ RawStorageProvider,
39
+ Libp2pNodeWithRepo
40
+ } from './types.js';
41
+ import { DEFAULT_CONNECTION_MONITOR, resolveStrandClusterSize, strandClusterPolicy } from './types.js';
42
+ import { strandNodeAddrs } from './strand-network-config.js';
43
+ import { superviseRelayReservation, type RelayReservationSupervisor } from './relay-reservation.js';
44
+ import { peerJoinPushBudget, relayReservationBudgetMs, resolveLinkRoundTripMs } from './link-budget.js';
45
+
46
+ const log = debug('sereus:cadre:strand-manager');
47
+ const timing = debug('sereus:cadre:timing');
48
+
49
+ /** One caller blocked in {@link StrandInstanceManager.whenWritable}. */
50
+ interface WritableWaiter {
51
+ resolve: () => void;
52
+ reject: (error: Error) => void;
53
+ }
54
+
55
+ /**
56
+ * Whether a tracked instance is launched but waiting for its first sync: the runtime is
57
+ * up (`libp2pNode` set) while the database is still withheld (`database` unset). That
58
+ * is the first-sync gate's state regardless of what `status` says — the hibernation
59
+ * manager's idle timer can flip a long-gated joiner to `'idle'` without changing it.
60
+ *
61
+ * NOTE: `status` is therefore not the source of truth for "gated": a joiner that reaches
62
+ * nobody for `idleTimeout` (5 min at the interactive hint) reads `'idle'`, then
63
+ * `'hibernating'`, while still holding no database. Harmless today — every decision the
64
+ * runtime makes goes through this predicate, {@link StrandInstanceManager.publishDatabase}
65
+ * announces on the idle-flipped instance exactly as on a `'syncing'` one, and an app that
66
+ * shows "waiting for the other member" on `'syncing'` merely sees "idle" instead after
67
+ * five minutes. If an app ever needs the gated LABEL to survive the idle flip, make the
68
+ * hibernation manager's idle transition preserve `'syncing'` rather than adding a flag.
69
+ */
70
+ export function isAwaitingFirstSync(instance: StrandInstance): boolean {
71
+ return instance.libp2pNode !== undefined && instance.database === undefined;
72
+ }
73
+
74
+ /**
75
+ * The status a LIVE instance (runtime rebuilt or woken) should report: `'active'` once its
76
+ * database is published, `'syncing'` while the first-sync gate still withholds it. Every
77
+ * site that would otherwise write `'active'` after a build or a wake goes through this,
78
+ * so a gated joiner never reads as writable.
79
+ */
80
+ export function liveStrandStatus(instance: StrandInstance): 'active' | 'syncing' {
81
+ return instance.database ? 'active' : 'syncing';
82
+ }
83
+
84
+ /**
85
+ * Configuration for starting a strand instance
86
+ */
87
+ export interface StartStrandConfig {
88
+ strandRow: StrandRow;
89
+ /** sApp configuration provided by the hosting application */
90
+ sAppConfig: SAppConfig;
91
+ storage?: StorageConfig;
92
+ network?: NetworkConfig;
93
+ profile: NodeProfile;
94
+ defaultLatencyHint: LatencyHint;
95
+ privateKey?: PrivateKey;
96
+ /** Cohort-derived discovery seed (multiaddr strings). Defaults to [] when omitted. */
97
+ bootstrapNodes?: string[];
98
+ /**
99
+ * Require a valid author signature on the sApp schema before bring-up.
100
+ * Defaults to true (fail closed) when omitted; set false only for dev/test
101
+ * with unsigned demo schemas. Mirrors {@link CadreNodeConfig.requireSignedSchemas}.
102
+ */
103
+ requireSignedSchemas?: boolean;
104
+ /**
105
+ * Whether this node founds the strand (vs. joins it). Forwarded to the
106
+ * StrandDatabase so the founder bootstrap (Header, founding Member/Manager)
107
+ * runs once at bring-up. Joiners leave this unset and write nothing. Callers
108
+ * resolve it BEFORE calling `startStrand` (`CadreNode.launchStrand` derives it
109
+ * from the row's `FounderOwnerKey` when no explicit flag is given — see
110
+ * {@link StrandConfig.founder}); a founder request that arrives while the
111
+ * instance is already tracked goes through {@link StrandInstanceManager.foundExistingStrand},
112
+ * never through a repeat `startStrand`.
113
+ */
114
+ founder?: boolean;
115
+ /**
116
+ * THIS party's own strand membership private key (base64 protobuf) for a closed
117
+ * strand — the identity the founder bootstrap derives `Member.Key` /
118
+ * `Manager.MemberKey` from. Resolved by the caller (`CadreNode.launchStrand`: an
119
+ * explicit attach-time key, else the control-layer `StrandPartyKey` row, healed by
120
+ * mint-on-launch for the founding machine) and retained with the launch config, so a
121
+ * hibernation wake rebuilds under the same identity. Deliberately NOT the strand
122
+ * row's shared `MemberPrivateKey` (see `StrandDatabaseConfig.partyMemberPrivateKey`).
123
+ * Absent for open strands, and for joiners with no persisted party key.
124
+ */
125
+ partyMemberPrivateKey?: string;
126
+ /**
127
+ * Number of nodes Optimystic is told this strand's replication cluster should
128
+ * have. Same rule as {@link CadreNodeConfig.strandClusterSize}, which CadreNode
129
+ * forwards here: every node on the strand should use the same value, and it is
130
+ * frozen when the strand's libp2p node is created. Defaults to
131
+ * `DEFAULT_STRAND_CLUSTER_SIZE` (4); values below `MIN_CLUSTER_SIZE` (2) are
132
+ * rejected by `resolveStrandClusterSize`. Strand-only — the
133
+ * control network's breadth is the fixed `CONTROL_REPLICATION_BREADTH`.
134
+ */
135
+ clusterSize?: number;
136
+ /**
137
+ * Machines that SERVE THIS STRAND (this node included), for the strand node's
138
+ * block-repair corroboration yardstick — see `resolveRepairYardstick`. It must be
139
+ * an authenticated per-strand count: the machines that actually run a node for this
140
+ * strand, not the machines that exist.
141
+ *
142
+ * **The party's enrolled-machine count is NOT this number and must never be passed
143
+ * here.** A strand launches only on machines whose embedding app registered its sApp
144
+ * config (`CadreNode.addStrand`), so a closed strand shared by two machines of a
145
+ * three-machine party is served by two. Passing three over-declares, and
146
+ * over-declaring is the unsafe direction: at a declaration of 3 or more Optimystic
147
+ * pins the repair corroboration floor at two corroborating peers, which a cohort
148
+ * that can only ever field one peer can never reach — so the strand can never repair
149
+ * a block (`cluster-fetch:no-quorum`, surfacing as reads failing with `Missing
150
+ * block`). That regression is why this field was renamed off "enrolledMachines":
151
+ * `bug-strand-yardstick-counts-party-machines`.
152
+ *
153
+ * **Nothing feeds it in production today.** No authenticated per-strand serving count
154
+ * exists yet, so `CadreNode` passes nothing and the strand node runs the frozen
155
+ * `STRAND_CLUSTER_POLICY` — declaring no yardstick, which leaves the known,
156
+ * upstream-tracked single-voter exposure
157
+ * (`backlog/debt-read-repair-single-voter-corroboration`). Building the count is
158
+ * `backlog/feat-strand-yardstick-from-serving-machines`; this field and its
159
+ * threading are the seam it plugs into.
160
+ *
161
+ * Volatile when a source does exist: re-resolve it on every resume beside the cohort
162
+ * seed, since machines join and leave a strand while it hibernates. Omitting it means
163
+ * "this node does not know", which declares nothing.
164
+ */
165
+ servingMachines?: number;
166
+ /**
167
+ * Tuning for the strand peer-join block catch-up ({@link PeerJoinBackfill}),
168
+ * forwarded from {@link CadreNodeConfig.strandBackfill}. When the strand's
169
+ * libp2p node connects to a peer this runtime has not yet caught up, every
170
+ * block in the strand's own raw store is pushed to it. Runs only on strands
171
+ * with per-strand storage; `{ enabled: false }` restores the pre-existing
172
+ * no-backfill behaviour.
173
+ */
174
+ backfill?: PeerJoinBackfillConfig;
175
+ /**
176
+ * Tuning for the CLOSED-strand revoked-peer gate
177
+ * ({@link StrandRevocationEnforcer}), forwarded from
178
+ * {@link CadreNodeConfig.strandRevocationEnforcement}. Armed only for
179
+ * `strandRow.Type === 'c'` (an open strand has no membership rows to derive a
180
+ * deny set from); `{ enabled: false }` restores the pre-existing behaviour
181
+ * (a removed party's peers keep being served).
182
+ */
183
+ revocationEnforcement?: StrandRevocationEnforcementConfig;
184
+
185
+ /**
186
+ * The staged formation membership invitation for THIS strand — the seam the
187
+ * bring-up membership reconciler (`strand-membership-reconciler.ts`) reads to
188
+ * redeem the party's `Strand.Member` seat, and clears once the invitation is
189
+ * spent, burned, or dead. `CadreNode.launchStrand` wires it over its in-memory
190
+ * `pendingMembershipInvites` map; read lazily per pass, so a re-formation that
191
+ * replaces the entry between passes is picked up. Only consulted for closed
192
+ * strands launched with a {@link partyMemberPrivateKey}; harmless otherwise.
193
+ */
194
+ pendingMembershipInvite?: PendingMembershipInviteSource;
195
+
196
+ /**
197
+ * Tuning for the CLOSED-strand membership reconciler, forwarded from
198
+ * {@link CadreNodeConfig.strandMembershipReconciliation}. Armed only for
199
+ * closed strands launched with a {@link partyMemberPrivateKey};
200
+ * `{ enabled: false }` disarms the loop (test fixtures that hand-drive the
201
+ * membership writers). When it names no `pollIntervalMs` the reconciler
202
+ * mirrors {@link revocationEnforcement}'s cadence — as its IDLE cadence and
203
+ * the cap of its unfinished-join retry ladder, not as a flat retry interval.
204
+ */
205
+ membershipReconciliation?: StrandMembershipReconciliationConfig;
206
+
207
+ /**
208
+ * Called when THIS node's own peer id turns up in the strand's revoked set —
209
+ * this node's party was removed from the closed strand, or left it. Fires once
210
+ * per removal (re-armed if the party is re-admitted; a resume also rebuilds the
211
+ * enforcer and may legitimately re-fire), and only for closed strands with the
212
+ * gate armed. `CadreNode`
213
+ * wires it to its `strand:revoked` event; nothing is stopped or torn down on
214
+ * this node's behalf — what to do about it is the app's call.
215
+ */
216
+ onSelfRevoked?: (strandId: string) => void;
217
+
218
+ /**
219
+ * Called when the membership reconciler reports a blocked re-join — this node holds a
220
+ * staged membership invitation for the strand that its writes cannot redeem, which is
221
+ * what a REMOVED party handed a fresh invitation hits (see "Reporting a blocked
222
+ * re-join" in `strand-membership-reconciler.ts` for the two triggers, one of them a
223
+ * suspicion rather than a verdict). At most once per re-arm of the loop — a further
224
+ * invitation staged while the loop is still running does not reset the report — and
225
+ * only for closed strands with a party key. `CadreNode` wires it to its `strand:rejoin-blocked`
226
+ * event; nothing is stopped or torn down — a remaining manager admitting this party's
227
+ * key directly is the remedy, and the loop finishes the join by itself once that lands.
228
+ */
229
+ onRejoinBlocked?: (strandId: string) => void;
230
+
231
+ /**
232
+ * Tuning for the JOINING machine's first-sync write gate (`strand-first-sync-gate.ts`),
233
+ * forwarded from {@link CadreNodeConfig.strandFirstSync}: the Header probe cadence while
234
+ * a non-founder launch is `'syncing'`, and the default budget {@link whenWritable} waits
235
+ * before rejecting. Founders and machines that already hold the Header are never gated.
236
+ */
237
+ firstSync?: StrandFirstSyncConfig;
238
+
239
+ /**
240
+ * Called when a launch that came up `'syncing'` (see {@link firstSync}) becomes
241
+ * writable: the strand's `Strand.Header` arrived from a peer — or a founder request
242
+ * ran the bootstrap against the gated database — and `instance.database` is now set.
243
+ * Never called for a launch that was writable when `startStrand`/`resumeStrand`
244
+ * resolved. `CadreNode` wires it to its `strand:writable` event. Retained with the
245
+ * launch config, so a hibernation resume that comes up gated announces too.
246
+ */
247
+ onWritable?: (strandId: string) => void;
248
+
249
+ /**
250
+ * Re-announce this strand's delegate peer id (`delegatePeerId` — the strand
251
+ * node's own transport peer id) to ONE relay (`relayAddr`, a direct dial addr
252
+ * with a trailing `/p2p/<relayPeerId>`), unthrottled. Awaited before every
253
+ * relay-reservation RE-drive of that relay — never before the first attempt,
254
+ * which the launch/resume seed pass has already announced for.
255
+ *
256
+ * Why: a party control node running the relay server admits the strand node on
257
+ * an in-memory delegate grant that a relay restart drops, so a re-drive that did
258
+ * not re-announce first would be denied at the relay's gate. `CadreNode` wires
259
+ * its own control-mesh announce here; a throw or rejection is logged by the
260
+ * supervisor and the re-drive still runs. Retained with the launch config, so a
261
+ * hibernation wake's rebuilt supervisors carry it too.
262
+ */
263
+ announceDelegateToRelay?: (strandId: string, relayAddr: string, delegatePeerId: string) => Promise<void>;
264
+ }
265
+
266
+ /**
267
+ * Volatile inputs re-resolved when resuming a quiesced strand — the ones that can
268
+ * have moved since it last ran, and that the rebuilt libp2p node freezes again. Each
269
+ * one omitted keeps the value the retained launch config already holds, so a resume
270
+ * that passes nothing rebuilds the strand exactly as it last ran.
271
+ */
272
+ export interface ResumeStrandOverrides {
273
+ /**
274
+ * Freshly-resolved cohort discovery seed (multiaddr strings). Grows as peers are
275
+ * learned since the strand first launched.
276
+ */
277
+ bootstrapNodes?: string[];
278
+ /**
279
+ * Freshly-read count of the machines serving this strand, for the repair yardstick
280
+ * (see {@link StartStrandConfig.servingMachines} — including why the party's
281
+ * enrolled-machine count is not it). Moves whenever a machine starts or stops
282
+ * serving the strand, which a hibernating strand does not otherwise notice. Nothing
283
+ * passes it today. Omitting it here does NOT mean "unknown" the way omitting it from
284
+ * {@link StartStrandConfig} does — it retains the last value; see `resumeStrand`.
285
+ */
286
+ servingMachines?: number;
287
+ }
288
+
289
+ /**
290
+ * Get the isolated storage path for a specific strand.
291
+ *
292
+ * @deprecated This helper is Node-only and throws in React Native (it assumes a
293
+ * filesystem layout). Use a storage provider factory function instead, which
294
+ * receives the strandId and can create strand-specific storage paths using
295
+ * platform-appropriate methods.
296
+ *
297
+ * @example
298
+ * // Instead of using getStrandStoragePath, use a storage provider factory:
299
+ * const storage = {
300
+ * provider: (strandId: string) => new FileRawStorage(`./data/strands/${strandId}`)
301
+ * };
302
+ */
303
+ export function getStrandStoragePath(basePath: string, strandId: string): string {
304
+ // Check if we're in a Node.js environment
305
+ if (typeof process === 'undefined' || !process.versions?.node) {
306
+ throw new Error(
307
+ 'getStrandStoragePath is not available in React Native. ' +
308
+ 'Use a storage provider factory function instead.'
309
+ );
310
+ }
311
+
312
+ // Sanitize strandId for filesystem safety (UUIDs should be safe, but just in case)
313
+ const safeId = strandId.replace(/[^a-zA-Z0-9-]/g, '_');
314
+
315
+ // Build the path with plain string joins rather than the Node `path` module.
316
+ // A static `require('path')` forces RN bundlers (e.g. Metro) to *resolve* the
317
+ // module at bundle time even though this Node-only helper throws above before
318
+ // ever reaching here — joining by hand keeps the module free of any Node
319
+ // built-in reference, so RN bundles need no `path` shim.
320
+ const trimmedBase = basePath.replace(/[\\/]+$/, '');
321
+ return `${trimmedBase}/strands/${safeId}`;
322
+ }
323
+
324
+ /**
325
+ * Resolve a storage provider for a specific strand.
326
+ * If the provider is a factory function, call it with the strandId.
327
+ *
328
+ * Called only from {@link StrandInstanceManager.startStrand}, which owns the result
329
+ * for the instance's lifetime — see `strandStorages`, and which has already asserted
330
+ * the id is usable as a scope key. Do not move that assertion here: this function
331
+ * returns early when no provider is configured, and the id becomes a libp2p protocol
332
+ * prefix on that path too.
333
+ *
334
+ * @param provider - Storage provider (instance or factory)
335
+ * @param strandId - The strand ID to create storage for
336
+ * @returns The resolved IRawStorage instance, or undefined if no provider
337
+ */
338
+ function resolveStrandStorage(
339
+ provider: RawStorageProvider | undefined,
340
+ strandId: string
341
+ ): IRawStorage | undefined {
342
+ if (!provider) {
343
+ return undefined;
344
+ }
345
+ const storage = typeof provider === 'function' ? provider(strandId) : provider;
346
+ // Wrapped in the write-through raw-storage cache (quereus-plugin-sereus's cached-storage.ts).
347
+ // Called ONCE per strand launch — `startStrand` keeps the result for the instance's
348
+ // lifetime — so the wrap survives every runtime rebuild the instance goes through.
349
+ return wrapStorageWithCache(storage, strandId);
350
+ }
351
+
352
+ /**
353
+ * Manages individual strand instances - creates and destroys isolated libp2p nodes
354
+ * for each strand the cadre participates in.
355
+ */
356
+ export class StrandInstanceManager {
357
+ private instances: Map<string, StrandInstance> = new Map();
358
+ /**
359
+ * Retained launch config per strand, captured in `startStrand` and cleared in
360
+ * `stopStrand`. `resumeStrand` reuses it to rebuild a quiesced strand's runtime
361
+ * without the caller re-threading storage/network/profile/key/sApp config.
362
+ */
363
+ private launchConfigs: Map<string, StartStrandConfig> = new Map();
364
+ /**
365
+ * The per-strand peer-join block catch-up, keyed by strand id. Private (not on
366
+ * the public {@link StrandInstance}) because it is runtime plumbing with the
367
+ * same lifetime as the strand's libp2p node: created in `buildStrandRuntime`,
368
+ * stopped and dropped in `releaseRuntime` — so quiesce → resume rebuilds it
369
+ * with a fresh caught-up-peer memo, which is intended (a resumed node may have
370
+ * missed writes).
371
+ */
372
+ private backfills: Map<string, PeerJoinBackfill> = new Map();
373
+ /**
374
+ * The per-strand revoked-peer enforcer (closed strands only), keyed by strand
375
+ * id. Same lifecycle rationale as {@link backfills}: created in
376
+ * `buildStrandRuntime`, stopped and dropped in `releaseRuntime`, so quiesce →
377
+ * resume rebuilds it with a fresh (initially empty, fail-open) snapshot.
378
+ */
379
+ private revocationEnforcers: Map<string, StrandRevocationEnforcer> = new Map();
380
+ /**
381
+ * The per-strand membership reconciler (closed strands launched with a party
382
+ * key only), keyed by strand id. Same lifecycle rationale as {@link backfills}:
383
+ * created in `buildStrandRuntime`, stopped and dropped in `releaseRuntime`, so
384
+ * quiesce → resume rebuilds it and re-runs the idempotent join ladder (redeem a
385
+ * staged invitation, write this machine's own `MemberPeer` binding) from scratch.
386
+ */
387
+ private membershipReconcilers: Map<string, StrandMembershipReconciler> = new Map();
388
+ /**
389
+ * The per-strand first-sync gate (`strand-first-sync-gate.ts`), keyed by strand id:
390
+ * holds a launch's `StrandDatabase` while it is NOT yet published on the instance.
391
+ * Present from the moment the database object exists in `buildStrandRuntime` until
392
+ * {@link publishDatabase} hands it to the app — so it doubles as the rollback handle
393
+ * for a failed `initialize()` — and, for a joiner that holds no `Strand.Header` yet,
394
+ * for as long as the launch stays `'syncing'`. Same lifecycle as {@link backfills}:
395
+ * stopped (its database closed) and dropped in `releaseRuntime`, so a quiesce →
396
+ * resume rebuild re-probes over the same store. An entry and `instance.database`
397
+ * are mutually exclusive.
398
+ */
399
+ private firstSyncGates: Map<string, StrandFirstSyncGate> = new Map();
400
+ /**
401
+ * Callers blocked in {@link whenWritable}, keyed by strand id. Resolved by
402
+ * {@link publishDatabase}, rejected by {@link stopStrand}; each waiter also carries
403
+ * its own timeout. Deliberately NOT cleared by `releaseRuntime`: a waiter outlives a
404
+ * quiesce → resume cycle, since the rebuild is what may finally publish the database.
405
+ */
406
+ private writableWaiters: Map<string, Set<WritableWaiter>> = new Map();
407
+ /**
408
+ * The per-strand relay-reservation supervisors — ONE PER CONFIGURED RELAY, each
409
+ * over the node's own bare `/p2p-circuit` listener for that relay
410
+ * (`strand-network-config.ts`) — keyed by strand id. Same lifecycle rationale as
411
+ * {@link backfills}: started in `buildStrandRuntime` right after the libp2p node
412
+ * exists, stopped FIRST and dropped in `releaseRuntime` (before the database
413
+ * closes and the node stops, so no re-drive dials a node being torn down), so
414
+ * quiesce → resume rebuilds them over the new node. What makes a strand node's
415
+ * lost relay slot come back on its own — the control node has the same loop in
416
+ * `CadreNode.reserveRelays`.
417
+ */
418
+ private relaySupervisors: Map<string, RelayReservationSupervisor[]> = new Map();
419
+ /**
420
+ * The resolved (cache-wrapped) raw storage per strand id — the instance's OWN
421
+ * store, resolved once in `startStrand` and held until `stopStrand` disposes it.
422
+ * Private for the same reason `backfills` is: runtime plumbing, not part of the
423
+ * public {@link StrandInstance}.
424
+ *
425
+ * Deliberately NOT touched by `releaseRuntime`: that is what lets a quiesce →
426
+ * resume cycle rebuild the libp2p node over the SAME store, keeping its
427
+ * write-through cache warm (and, on an in-memory backend, keeping the strand's
428
+ * blocks at all). An entry exists iff `instances` does AND the launch config
429
+ * supplied a storage provider.
430
+ *
431
+ * NOTE: a hibernating strand therefore keeps its store — and its share of the
432
+ * process-wide cache pool — resident for as long as the instance is tracked. That
433
+ * is the point (a warm wake), and the pool evicts under pressure, so the cost is
434
+ * one map entry per hibernating strand today. If a device ever hibernates strands
435
+ * by the hundred, revisit: dropping the store at quiesce and paying for a cold
436
+ * wake becomes the better trade.
437
+ */
438
+ private strandStorages: Map<string, IRawStorage> = new Map();
439
+ private stopping = false;
440
+
441
+ constructor() {
442
+ log('StrandInstanceManager created');
443
+ }
444
+
445
+ /**
446
+ * Get all current strand instances
447
+ */
448
+ getInstances(): Map<string, StrandInstance> {
449
+ return new Map(this.instances);
450
+ }
451
+
452
+ /**
453
+ * Get a specific strand instance
454
+ */
455
+ getInstance(strandId: string): StrandInstance | undefined {
456
+ return this.instances.get(strandId);
457
+ }
458
+
459
+ /**
460
+ * Check if a strand is currently running
461
+ */
462
+ hasStrand(strandId: string): boolean {
463
+ return this.instances.has(strandId);
464
+ }
465
+
466
+ /**
467
+ * Start a new strand instance.
468
+ *
469
+ * A failed launch leaves NOTHING tracked: the instance and its retained launch
470
+ * config are both dropped before the error is rethrown, so the strand id is
471
+ * free for a genuine retry. This matches the pre-registration failure path
472
+ * (a rejected schema signature, which throws before anything is recorded) —
473
+ * both failure modes of this call leave the same residue: none. Callers learn
474
+ * of the failure from the rejected promise (and, on the control-discovered
475
+ * path, from CadreNode's `strand:error` event), not from an error record left
476
+ * behind in `instances`.
477
+ *
478
+ * The strand's raw storage is resolved HERE, once, and held for the instance's
479
+ * lifetime (see `strandStorages`) — `buildStrandRuntime` only reads it, so a
480
+ * hibernation wake never re-enters the embedder's provider.
481
+ */
482
+ async startStrand(config: StartStrandConfig): Promise<StrandInstance> {
483
+ const { strandRow, sAppConfig } = config;
484
+ const strandId = strandRow.Id;
485
+
486
+ if (this.stopping) {
487
+ throw new Error('StrandInstanceManager is stopping');
488
+ }
489
+
490
+ if (this.instances.has(strandId)) {
491
+ // Callers resolve founder-ness BEFORE reaching here (CadreNode.launchStrand) and
492
+ // honor a founder request on a tracked instance via foundExistingStrand — so a
493
+ // founder flag arriving at this early return against a non-founder retained
494
+ // config is a dropped bootstrap, and must never again be silent.
495
+ if (config.founder === true && this.launchConfigs.get(strandId)?.founder !== true) {
496
+ log('startStrand: strand %s is already running but was NOT launched as founder — ' +
497
+ 'this early return DROPS the founder request; use foundExistingStrand', strandId);
498
+ }
499
+ log('Strand %s already running', strandId);
500
+ return this.instances.get(strandId)!;
501
+ }
502
+
503
+ log('Starting strand instance: %s (sApp: %s v%s)', strandId, sAppConfig.id, sAppConfig.version);
504
+ const tTotal = performance.now();
505
+
506
+ // The id becomes two names below: the storage scope key the embedder's provider
507
+ // turns into a directory or database name, and `networkName` in buildStrandRuntime,
508
+ // from which the libp2p protocol prefix `/optimystic/strand-<id>` is built. A
509
+ // replicated strand row carries whatever id the founding node wrote, so neither is
510
+ // safe unchecked. Asserted HERE rather than in `resolveStrandStorage` because that
511
+ // function returns early when no provider is configured — a node with no storage
512
+ // still reaches buildStrandRuntime and still mints the protocol prefix.
513
+ assertStrandScopeKey(strandId);
514
+
515
+ // Verify schema signature before proceeding (fail-closed by default)
516
+ const requireSignature = config.requireSignedSchemas ?? true;
517
+ assertSchemaSignature(sAppConfig, { requireSignature });
518
+ log('Strand %s sApp schema signature verified (author: %s)', strandId, sAppConfig.id);
519
+
520
+ // Convert SAppConfig to SAppInfo for the instance
521
+ const sAppInfo: SAppInfo = {
522
+ id: sAppConfig.id,
523
+ version: sAppConfig.version,
524
+ schema: sAppConfig.schema,
525
+ signature: sAppConfig.signature
526
+ };
527
+
528
+ // Resolve this strand's storage ONCE, before anything is recorded. If a factory
529
+ // function is provided, it is called with the strandId to create strand-specific
530
+ // storage (e.g. strand-isolated directories). A provider that throws therefore
531
+ // fails the launch alongside the schema-signature check, leaving nothing tracked.
532
+ const strandStorage = resolveStrandStorage(config.storage?.provider, strandId);
533
+ if (strandStorage) {
534
+ log('Strand %s using provided storage provider', strandId);
535
+ }
536
+
537
+ // Determine latency hint: sApp config > default
538
+ const latencyHint = sAppConfig.latencyHint ?? config.defaultLatencyHint;
539
+
540
+ const instance: StrandInstance = {
541
+ strandId,
542
+ status: 'starting',
543
+ sAppInfo,
544
+ memberPrivateKey: strandRow.MemberPrivateKey ?? undefined,
545
+ connectedPeers: 0,
546
+ lastActivity: new Date(),
547
+ latencyHint
548
+ };
549
+
550
+ this.instances.set(strandId, instance);
551
+ this.launchConfigs.set(strandId, config);
552
+ if (strandStorage) {
553
+ this.strandStorages.set(strandId, strandStorage);
554
+ }
555
+
556
+ try {
557
+ await this.buildStrandRuntime(instance, config);
558
+ timing('[startStrand:%s] total: %dms', strandId, Math.round(performance.now() - tTotal));
559
+ log('Strand %s started successfully with sApp %s', strandId, sAppConfig.id);
560
+ return instance;
561
+ } catch (error) {
562
+ // Status/error first — the (now discarded) record is still what `log` reports on.
563
+ instance.status = 'error';
564
+ instance.error = error instanceof Error ? error.message : String(error);
565
+ log('Failed to start strand %s: %s', strandId, instance.error);
566
+ // Drop the dead record so this strand id can be launched again. Keep the
567
+ // `launchConfigs` has an entry iff `instances` does invariant — resumeStrand
568
+ // reads both, and a config without an instance would strand the config.
569
+ this.instances.delete(strandId);
570
+ this.launchConfigs.delete(strandId);
571
+ // The store this launch resolved goes with it: nothing owns it any more, and a
572
+ // retained cache wrapper would be handed back (already retired) on a retry.
573
+ await this.disposeStrandStorage(strandId);
574
+ throw error;
575
+ }
576
+ }
577
+
578
+ /**
579
+ * Build (or rebuild) the libp2p node + StrandDatabase for an instance and
580
+ * attach them, transitioning it to `active`. Shared by `startStrand` (fresh
581
+ * launch) and `resumeStrand` (rehydrating a quiesced instance). Reads all
582
+ * volatile inputs (bootstrapNodes, servingMachines, network, profile,
583
+ * privateKey, sApp config) from `config`, so the caller controls the
584
+ * cohort-derived values. Storage is the
585
+ * one input it does NOT re-read from `config`: that belongs to the instance and
586
+ * comes from `strandStorages`.
587
+ */
588
+ private async buildStrandRuntime(instance: StrandInstance, config: StartStrandConfig): Promise<void> {
589
+ const strandId = instance.strandId;
590
+ const { sAppConfig } = config;
591
+
592
+ // Refuse a bad `linkRoundTripMs` before any strand bring-up, for the reason
593
+ // `CadreNode.start()` does: every budget derived from it here is behind a condition
594
+ // (backfill disabled, no relay addrs), so a zero or NaN declaration would otherwise
595
+ // surface later inside a path that logs and carries on. `link-budget.ts`.
596
+ resolveLinkRoundTripMs(config.network?.linkRoundTripMs);
597
+
598
+ // The store the instance OWNS (resolved once in `startStrand`), not a fresh
599
+ // resolution: a rebuild must reach the same backend through the same warm cache.
600
+ const strandStorage = this.strandStorages.get(strandId);
601
+
602
+ // db-p2p namespaces every one of the node's protocol ids by network name
603
+ // (`/optimystic/<networkName>/...`), so anything dialing this node's own
604
+ // services must derive its prefix from the SAME string the node was built
605
+ // with — hence one binding for both, not two literals that can drift.
606
+ const networkName = `strand-${strandId}`;
607
+ const protocolPrefix = `/optimystic/${networkName}`;
608
+
609
+ // Determine relay mode: if explicitly set in config, use that;
610
+ // otherwise default to true for storage profile nodes.
611
+ const enableRelay = config.network?.enableRelay ?? (config.profile === 'storage');
612
+ // The strand-node VIEW of the machine's one `NetworkConfig`, not the control
613
+ // node's resolution: fixed direct listen ports become ephemeral (two nodes cannot
614
+ // bind one port), the announce config is dropped (it names the control node's
615
+ // address), and every configured relay becomes one bare `/p2p-circuit` SEARCH
616
+ // listener plus a dial addr in `relayAddrs` for the per-relay supervisor started
617
+ // below — the same route the control node takes, because the configured
618
+ // `<relay>/p2p-circuit` shape loses its address on a relay restart, a hangup, or
619
+ // libp2p's own reservation refresh and recovers from none of them. See
620
+ // `strand-network-config.ts` for all three, and `relay-reservation.ts`.
621
+ //
622
+ // `relayAddrs` is destructured OFF: it is not a `createLibp2pNode` option, and
623
+ // spreading it would hand db-p2p a key it does not know.
624
+ const { relayAddrs: relayDialAddrs = [], ...addrOptions } = strandNodeAddrs(config.network);
625
+
626
+ // The CLOSED-strand revoked-peer gate (see strand-revocation-enforcer.ts).
627
+ // Constructed BEFORE the libp2p node because the node's options embed its
628
+ // predicates; its deny set starts empty (admit everything — fail-open, same
629
+ // posture as bring-up everywhere here) and is first populated after the
630
+ // strand database initializes below. Registered in the map immediately so
631
+ // the failure rollback (releaseRuntime) tears it down like every other
632
+ // runtime component. Open strands skip it entirely: their Member/MemberPeer
633
+ // tables are empty by schema (`OnlyClosed`), so there is nothing to derive
634
+ // a deny set from — arming would be pointless polling.
635
+ const revocationEnforcer =
636
+ config.strandRow.Type === 'c' && config.revocationEnforcement?.enabled !== false
637
+ ? new StrandRevocationEnforcer({
638
+ label: strandId,
639
+ readRows: () => {
640
+ const database = instance.database;
641
+ if (!database) {
642
+ throw new Error(`strand ${strandId} has no live database`);
643
+ }
644
+ return readStrandRevocationRows(database.getDatabase());
645
+ },
646
+ // Read per sweep, never captured: this closure is built BEFORE the
647
+ // libp2p node exists (its options embed the enforcer's predicates),
648
+ // and `releaseRuntime` clears the field again on quiesce. Undefined
649
+ // therefore means "no transport right now", which the enforcer
650
+ // treats as "nothing to tear down".
651
+ getNetwork: () => instance.libp2pNode,
652
+ onSelfRevoked: () => config.onSelfRevoked?.(strandId)
653
+ }, config.revocationEnforcement)
654
+ : undefined;
655
+ if (revocationEnforcer) {
656
+ this.revocationEnforcers.set(strandId, revocationEnforcer);
657
+ }
658
+
659
+ // Closed strands compose revoked-peer denial onto the caller's gater and arm
660
+ // the fail-closed per-stream gate; open strands keep the raw configured gater
661
+ // (their peers are legitimately cross-party and nothing is ever revoked).
662
+ const revocationGateOptions = revocationEnforcer
663
+ ? {
664
+ connectionGater: createRevocationConnectionGater(revocationEnforcer, config.network?.connectionGater),
665
+ authorizeInboundStream: (remotePeerId: string, protocol: string) =>
666
+ revocationEnforcer.authorizeStream(remotePeerId, protocol)
667
+ }
668
+ : config.network?.connectionGater
669
+ ? { connectionGater: config.network.connectionGater }
670
+ : {};
671
+
672
+ try {
673
+ // Bound once: the breadth is also the ceiling on the repair yardstick below, and the
674
+ // two must be derived from the same resolution. Inside the `try` deliberately — a
675
+ // rejected clusterSize is a build failure that runs the same cleanup as any other.
676
+ const strandClusterSize = resolveStrandClusterSize(config.clusterSize);
677
+
678
+ let t0 = performance.now();
679
+ const node = await createLibp2pNode({
680
+ port: 0, // Random port
681
+ bootstrapNodes: config.bootstrapNodes ?? [],
682
+ networkName,
683
+ storage: strandStorage,
684
+ fretProfile: config.profile === 'storage' ? 'core' : 'edge',
685
+ relay: enableRelay,
686
+ clusterSize: strandClusterSize,
687
+ // Deliberately NOT CONTROL_CLUSTER_POLICY: a strand is application data with its own
688
+ // breadth reasoning, and the shape match with the control policy is a coincidence.
689
+ //
690
+ // The builder declares this node's block-repair corroboration yardstick from the
691
+ // count of machines SERVING this strand, capped at the breadth above (a block
692
+ // never lives on more machines than the cohort is wide). Given no count — the
693
+ // production path today, since no per-strand serving count exists yet — it
694
+ // returns the frozen STRAND_CLUSTER_POLICY itself, declaring nothing. Resolved
695
+ // HERE rather than at `startStrand`, so a wake from hibernation would pick up a
696
+ // serving set that changed while the strand slept.
697
+ // The read deadline is the same field the control node reads, because the two
698
+ // networks ride one link; absent, the base policy's COHORT_READ_DEADLINE_MS stands.
699
+ clusterPolicy: strandClusterPolicy(strandClusterSize, {
700
+ servingMachines: config.servingMachines,
701
+ cohortQueryTimeoutMs: config.network?.cohortQueryTimeoutMs
702
+ }),
703
+ arachnode: {
704
+ enableRingZulu: config.profile === 'storage'
705
+ },
706
+ ...(config.privateKey && { privateKey: config.privateKey }),
707
+ ...(config.network?.transports && { transports: config.network.transports }),
708
+ ...(config.network?.noiseCrypto && { noiseCrypto: config.network.noiseCrypto }),
709
+ // Unconditional, and the same default the control node takes: every node of
710
+ // every party runs the monitor over its connection to a slow phone, so the
711
+ // widened ping deadline has to reach the strand nodes too (see
712
+ // DEFAULT_CONNECTION_MONITOR).
713
+ connectionMonitor: config.network?.connectionMonitor ?? DEFAULT_CONNECTION_MONITOR,
714
+ // Listen entries plus the WebSocket transport switch they imply — a strand node
715
+ // announces nothing the operator configured (`strand-network-config.ts`), and
716
+ // spreads AFTER `transports` above because the switch is a no-op whenever the
717
+ // embedder supplied its own factories. The bare `/p2p-circuit` entries (one per
718
+ // relay) open no connection here; each registers a pending reservation that the
719
+ // matching supervisor below fills, which is what gives a NAT'd strand node a
720
+ // reachable relay slot — and works against a party-run relay because the launch
721
+ // path announced this strand's derived peerId to it first (delegate admission;
722
+ // see cadre-node.ts).
723
+ ...addrOptions,
724
+ // The raw configured gater (open strands), or the revocation-composed
725
+ // gater plus the fail-closed per-stream revoked-peer gate (closed
726
+ // strands) — resolved above, before the try.
727
+ ...revocationGateOptions
728
+ }) as Libp2pNodeWithRepo;
729
+ timing('[buildStrandRuntime:%s] createLibp2pNode: %dms', strandId, Math.round(performance.now() - t0));
730
+
731
+ instance.libp2pNode = node;
732
+
733
+ // One reservation supervisor PER RELAY, started now so the first attempts
734
+ // overlap the database bring-up below (the relay is never in a strand's
735
+ // Optimystic cohort — its protocol ids are namespaced `/optimystic/strand-<id>/…`
736
+ // — so an open relay connection cannot disturb that bring-up). Their first
737
+ // attempts are awaited before the strand goes `active`, below. Registered in the
738
+ // map immediately so the failure rollback (releaseRuntime) stops them like every
739
+ // other runtime component.
740
+ this.relaySupervisors.set(strandId, this.startRelaySupervisors(strandId, node, relayDialAddrs, config));
741
+
742
+ // Create and initialize the StrandDatabase.
743
+ //
744
+ // Held by the first-sync gate (registered before initialize) rather than attached
745
+ // to the instance: a failed init is then cleaned up by releaseRuntime below through
746
+ // the gate (close() is safe on a partially-initialized db), and the app only ever
747
+ // sees `instance.database` once this machine is allowed to write to the strand.
748
+ t0 = performance.now();
749
+ const strandDb = new StrandDatabase({
750
+ strandId,
751
+ sAppConfig,
752
+ libp2pNode: node,
753
+ coordinatedRepo: node.coordinatedRepo,
754
+ // Founder bootstrap inputs: the strand's type drives which membership rows
755
+ // are written, and the PARTY's own key (partyMemberPrivateKey, resolved by the
756
+ // caller from the control-layer StrandPartyKey row) derives the founding
757
+ // Member/Manager key. The row's shared MemberPrivateKey rides along as the
758
+ // read-gating secret only — it derives nobody's identity.
759
+ strandType: config.strandRow.Type,
760
+ memberPrivateKey: config.strandRow.MemberPrivateKey ?? undefined,
761
+ partyMemberPrivateKey: config.partyMemberPrivateKey,
762
+ founder: config.founder
763
+ });
764
+ const gate = new StrandFirstSyncGate({
765
+ label: strandId,
766
+ database: strandDb,
767
+ onHeaderHeld: () => this.publishDatabase(instance, strandDb)
768
+ }, config.firstSync);
769
+ this.firstSyncGates.set(strandId, gate);
770
+ await strandDb.initialize();
771
+ timing('[buildStrandRuntime:%s] strandDatabase.initialize: %dms', strandId, Math.round(performance.now() - t0));
772
+
773
+ // The first-sync write gate. A founder just wrote the Header in its bootstrap; any
774
+ // other machine may commit only once it holds the Header — which it can only have
775
+ // received from a peer (now, or on an earlier run over the same store) — and has read
776
+ // each App table once, so their collections are fetched too. Publishing the database
777
+ // is what makes the strand writable to the app; until then the instance stays
778
+ // `'syncing'` and the gate re-probes on its cadence. Everything armed below reads
779
+ // `instance.database` lazily, so the reconciler and enforcer wait with it — and
780
+ // `publishDatabase` kicks the reconciler when the wait ends, so a joiner's membership
781
+ // rows land with the strand rather than one retry later.
782
+ t0 = performance.now();
783
+ if (config.founder === true || await strandFirstSyncComplete(strandDb.getDatabase(), strandId)) {
784
+ this.publishDatabase(instance, strandDb);
785
+ } else {
786
+ gate.start();
787
+ }
788
+ timing('[buildStrandRuntime:%s] first-sync probe: %dms', strandId, Math.round(performance.now() - t0));
789
+
790
+ // The membership reconciler: finish this party's join on every machine —
791
+ // redeem a staged formation invitation if one is pending, then write the
792
+ // durable machine→party binding (Strand.MemberPeer). Armed here, the one
793
+ // seam where the strand's transport peer id and a live Database both exist
794
+ // for launch AND hibernation resume, for closed strands that carry the
795
+ // party's own membership key. start() kicks an immediate pass WITHOUT
796
+ // awaiting it — a joiner at this instant has not synced the founder's rows
797
+ // and may lack write quorum, so bring-up is never blocked; an unfinished join
798
+ // then retries on a short doubling ladder capped at the configured
799
+ // pollIntervalMs (which is also the flat cadence while nobody has admitted this
800
+ // party yet), and the loop stops once the member row and this machine's own
801
+ // binding are both in place. Armed AFTER the gate above, so a gated launch
802
+ // always has a reconciler registered by the time the gate can publish.
803
+ if (config.strandRow.Type === 'c' && config.partyMemberPrivateKey
804
+ && config.membershipReconciliation?.enabled !== false) {
805
+ const reconciler = new StrandMembershipReconciler({
806
+ label: strandId,
807
+ partyMemberPrivateKey: config.partyMemberPrivateKey,
808
+ // Read per pass, never captured — same lifecycle argument as the
809
+ // enforcer's getNetwork: quiesce drops both handles.
810
+ getDatabase: () => instance.database?.getDatabase(),
811
+ getOwnPeerId: () => instance.libp2pNode?.peerId.toString(),
812
+ pendingInvite: config.pendingMembershipInvite,
813
+ // The enforcer's CURRENT snapshot view of this node's own peer id — the
814
+ // reconciler stops rather than fight a self-revocation. Absent when the
815
+ // gate is disarmed (fail-open: the loop just runs).
816
+ isSelfRevoked: revocationEnforcer
817
+ ? () => {
818
+ const ownPeerId = instance.libp2pNode?.peerId.toString();
819
+ return ownPeerId !== undefined && revocationEnforcer.isRevoked(ownPeerId);
820
+ }
821
+ : undefined,
822
+ onRejoinBlocked: () => config.onRejoinBlocked?.(strandId)
823
+ }, {
824
+ pollIntervalMs: config.membershipReconciliation?.pollIntervalMs
825
+ ?? config.revocationEnforcement?.pollIntervalMs
826
+ });
827
+ this.membershipReconcilers.set(strandId, reconciler);
828
+ reconciler.start();
829
+ }
830
+
831
+ // Arm the revoked-peer deny-set poll now that the database it reads
832
+ // exists. start() kicks an immediate refresh WITHOUT awaiting it —
833
+ // bring-up and resume are never blocked on a membership read; until the
834
+ // first read lands the empty snapshot admits everyone (fail-open).
835
+ revocationEnforcer?.start();
836
+
837
+ // Peer-join block catch-up: push this strand's own blocks to each newly
838
+ // connected peer, so a machine that joined after blocks were committed
839
+ // still ends up physically holding them (without per-strand storage there
840
+ // is nothing to copy). Armed for EVERY stored strand: `PeerJoinBackfill`
841
+ // only does work when the strand's libp2p node reports a peer connection,
842
+ // so on a device that is genuinely alone it is inert, and arming it at
843
+ // launch is what closes the "founded alone, never replicates" hole — a
844
+ // peer that joins later gets the founder's blocks without any relaunch.
845
+ // No `authorizePeer` gate, deliberately — see the module comment in
846
+ // peer-join-backfill.ts for the strand-side argument (and why the control
847
+ // network, which DOES gate, is different).
848
+ //
849
+ // NOTE: cost is one PeerJoinBackfill object + one `connection:open` listener
850
+ // per running strand — linear in strand count, negligible at the handful a
851
+ // device or host runs today. If a node ever hosts strands by the hundred,
852
+ // move to one shared listener that dispatches by strand id.
853
+ if (strandStorage && config.backfill?.enabled !== false) {
854
+ if (node.keyNetwork) {
855
+ const backfill = new PeerJoinBackfill({
856
+ label: strandId,
857
+ libp2p: node,
858
+ peerNetwork: node.keyNetwork,
859
+ storage: strandStorage,
860
+ // The same prefix the receiver registered its block-transfer handler
861
+ // under — derived from networkName above, never re-spelled here.
862
+ protocolPrefix
863
+ }, {
864
+ // Dial and response deadlines counted in link round trips, not fixed milliseconds:
865
+ // a relayed dial costs a fixed number of exchanges, so a fixed budget has a link
866
+ // speed above which this catch-up can never reach the peer at all. See
867
+ // `link-budget.ts`. Spread BEFORE the host's own config so an explicit
868
+ // `strandBackfill.dialTimeoutMs` still wins.
869
+ ...peerJoinPushBudget(config.network?.linkRoundTripMs),
870
+ ...config.backfill
871
+ });
872
+ backfill.start();
873
+ this.backfills.set(strandId, backfill);
874
+ } else {
875
+ log('Strand %s: libp2p node exposes no keyNetwork; peer-join block catch-up is inert', strandId);
876
+ }
877
+ }
878
+
879
+ // The relay supervisors' FIRST attempts, all of them, before `active`: the happy
880
+ // path still publishes its circuit addr before `addStrand` resolves (the
881
+ // strand-addr RPC answers read it, and the same-party circuit scenario asserts
882
+ // it). Fail-SOFT — a first attempt that lands nothing does not fail the launch.
883
+ // The strand's database is up, and the supervisor keeps trying on its backoff;
884
+ // failing here would only trade that for `StrandWatcher`'s full-rebuild retry.
885
+ //
886
+ // NOTE: a relay that is down costs this launch one full drive — the reservation budget
887
+ // counted from the declared link round trip, 8 s at its default (`link-budget.ts`) — and
888
+ // `StrandWatcher` launches strands one at a time, so N strands cost N of those in
889
+ // bring-up during a relay outage, and MORE on a host that declared a slower link. If that
890
+ // ever matters, stop awaiting here (the circuit addr then lands after `active`) rather
891
+ // than shortening the drive.
892
+ t0 = performance.now();
893
+ await this.awaitFirstRelayAttempts(strandId);
894
+ timing('[buildStrandRuntime:%s] relay first attempts: %dms', strandId, Math.round(performance.now() - t0));
895
+
896
+ instance.status = liveStrandStatus(instance);
897
+ instance.lastActivity = new Date();
898
+ if (instance.status === 'syncing') {
899
+ log('Strand %s launched as a joiner with no Strand.Header held yet — writes are withheld until ' +
900
+ 'a member of the strand is reached', strandId);
901
+ }
902
+ } catch (error) {
903
+ // Roll back any partially-attached runtime so the instance is left with
904
+ // NEITHER handle. Otherwise the `libp2pNode || database` "already live"
905
+ // guard in resumeStrand/handleStrandWake would treat a half-built strand
906
+ // as healthy — leaking the libp2p node and never retrying the rebuild.
907
+ await this.releaseRuntime(instance).catch((cleanupErr) => {
908
+ log('buildStrandRuntime cleanup for strand %s also failed: %o', strandId, cleanupErr);
909
+ });
910
+ throw error;
911
+ }
912
+ }
913
+
914
+ /**
915
+ * Release an instance's strand-network runtime: stop the relay supervisors and
916
+ * the other background loops, close the StrandDatabase, then stop the libp2p
917
+ * node (construction order in reverse), clearing both fields and zeroing
918
+ * connectedPeers. Tolerant of partially-built state — either handle may be
919
+ * absent — so it doubles as rollback for a failed `buildStrandRuntime`. Shared
920
+ * by `quiesceStrand`, `stopStrand`, and that rollback path.
921
+ *
922
+ * Leaves `strandStorages` untouched by design — the store outlives the runtime it
923
+ * was built into, which is what makes a resume warm. Only `stopStrand` disposes it.
924
+ */
925
+ private async releaseRuntime(instance: StrandInstance): Promise<void> {
926
+ // Relay supervisors FIRST of all — before anything below is torn down — so no
927
+ // re-drive is scheduled against a node being stopped. `stop()` is synchronous
928
+ // and never awaits a drive, so a relay that is down cannot delay this teardown.
929
+ // `stop()` also cancels the drive already in flight, so an attempt started
930
+ // moments before this does not keep dialing and polling the node the lines
931
+ // below are stopping; its result is discarded either way.
932
+ const relaySupervisors = this.relaySupervisors.get(instance.strandId);
933
+ if (relaySupervisors) {
934
+ relaySupervisors.forEach((supervisor) => supervisor.stop());
935
+ this.relaySupervisors.delete(instance.strandId);
936
+ }
937
+ // Backfill next — before the database closes and the libp2p node stops — so
938
+ // no NEW catch-up push is issued against a torn-down transport. A push already
939
+ // in flight is not awaited; it fails into the module's own per-chunk catch.
940
+ const backfill = this.backfills.get(instance.strandId);
941
+ if (backfill) {
942
+ backfill.stop();
943
+ this.backfills.delete(instance.strandId);
944
+ }
945
+ // The revoked-peer enforcer goes with the runtime it gated: a resume
946
+ // rebuilds it with a fresh (initially empty, fail-open) snapshot.
947
+ const revocationEnforcer = this.revocationEnforcers.get(instance.strandId);
948
+ if (revocationEnforcer) {
949
+ revocationEnforcer.stop();
950
+ this.revocationEnforcers.delete(instance.strandId);
951
+ }
952
+ // The membership reconciler likewise: a resume rebuilds it and re-runs the
953
+ // idempotent ladder, which is what makes resume-after-partial-join heal.
954
+ const membershipReconciler = this.membershipReconcilers.get(instance.strandId);
955
+ if (membershipReconciler) {
956
+ membershipReconciler.stop();
957
+ this.membershipReconcilers.delete(instance.strandId);
958
+ }
959
+ // A still-gated database (a joiner that never received the Header, or a launch whose
960
+ // initialize() failed) is closed through its gate; a published one through the
961
+ // instance. Never both — publishing moves the handle from the gate to the instance.
962
+ const gate = this.firstSyncGates.get(instance.strandId);
963
+ if (gate) {
964
+ gate.stop();
965
+ this.firstSyncGates.delete(instance.strandId);
966
+ await gate.database.close();
967
+ }
968
+ if (instance.database) {
969
+ await instance.database.close();
970
+ instance.database = undefined;
971
+ }
972
+ if (instance.libp2pNode) {
973
+ await instance.libp2pNode.stop();
974
+ instance.libp2pNode = undefined;
975
+ }
976
+ instance.connectedPeers = 0;
977
+ }
978
+
979
+ /**
980
+ * One {@link superviseRelayReservation} per relay dial addr, each over exactly
981
+ * that relay so "held" is judged per relay (`circuitMultiaddrsVia`) and losing
982
+ * one relay re-drives only that one. Default retry timings — the control node's (2 s
983
+ * doubling to 60 s between failed attempts, a 5 s liveness check while held). Each DRIVE's
984
+ * own deadline is counted in link round trips at this host's declared
985
+ * `network.linkRoundTripMs` (`link-budget.ts`), so the same declaration that lengthens the
986
+ * control node's drive lengthens these.
987
+ *
988
+ * Each supervisor's `beforeRedrive` is the caller's
989
+ * {@link StartStrandConfig.announceDelegateToRelay} for THIS relay and THIS
990
+ * node's peer id, so a re-drive after a relay restart is preceded by a fresh
991
+ * delegate grant on the relay about to be dialed. Returns `[]` when no relay is
992
+ * configured — the strand then simply has no circuit listener to fill.
993
+ */
994
+ private startRelaySupervisors(
995
+ strandId: string,
996
+ node: Libp2pNodeWithRepo,
997
+ relayDialAddrs: readonly string[],
998
+ config: StartStrandConfig
999
+ ): RelayReservationSupervisor[] {
1000
+ if (relayDialAddrs.length === 0) {
1001
+ return [];
1002
+ }
1003
+ const announce = config.announceDelegateToRelay;
1004
+ const delegatePeerId = node.peerId.toString();
1005
+ const timeoutMs = relayReservationBudgetMs(config.network?.linkRoundTripMs);
1006
+ return relayDialAddrs.map((relayAddr) => superviseRelayReservation(node, [relayAddr], {
1007
+ timeoutMs,
1008
+ ...(announce && { beforeRedrive: () => announce(strandId, relayAddr, delegatePeerId) })
1009
+ }));
1010
+ }
1011
+
1012
+ /**
1013
+ * Wait for every relay supervisor's first attempt to settle, concurrently, and log
1014
+ * the ones that landed nothing. Never throws — a strand whose relay is unreachable
1015
+ * at launch still comes up, with its supervisors retrying in the background.
1016
+ */
1017
+ private async awaitFirstRelayAttempts(strandId: string): Promise<void> {
1018
+ const supervisors = this.relaySupervisors.get(strandId) ?? [];
1019
+ if (supervisors.length === 0) {
1020
+ return;
1021
+ }
1022
+ await Promise.all(supervisors.map((supervisor) => supervisor.firstAttempt));
1023
+ supervisors.forEach((supervisor) => {
1024
+ if (supervisor.lastError !== null) {
1025
+ log('Strand %s: relay reservation not held after the first attempt (retrying in the background): %s',
1026
+ strandId, supervisor.lastError);
1027
+ }
1028
+ });
1029
+ }
1030
+
1031
+ /**
1032
+ * Drop the strand's owned store and release this strand's claim on its cache. The
1033
+ * wrapper counts holders, so the cache is emptied and unregistered from the shared
1034
+ * pool only if no other scope still holds it. Called only where the strand's whole
1035
+ * lifetime ends (`stopStrand`, and the failed-launch rollback) — never on a quiesce.
1036
+ *
1037
+ * A dispose failure is logged, not thrown: the store is already unreferenced here,
1038
+ * and failing the stop over a cache-bookkeeping error would leave the caller unable
1039
+ * to tear the strand down. `disposeStorageCache` no-ops for an unwrapped store
1040
+ * (e.g. `MemoryRawStorage`), so no instanceof test is needed.
1041
+ */
1042
+ private async disposeStrandStorage(strandId: string): Promise<void> {
1043
+ const storage = this.strandStorages.get(strandId);
1044
+ if (!storage) {
1045
+ return;
1046
+ }
1047
+ this.strandStorages.delete(strandId);
1048
+ try {
1049
+ await disposeStorageCache(storage);
1050
+ } catch (error) {
1051
+ log('Failed to dispose storage cache for strand %s: %o', strandId, error);
1052
+ }
1053
+ }
1054
+
1055
+ /**
1056
+ * Refresh a strand's revoked-peer deny set NOW — and, with it, run the
1057
+ * teardown sweep that hangs up every connected revoked peer.
1058
+ *
1059
+ * The gate is otherwise poll-driven (default
1060
+ * `DEFAULT_REVOCATION_POLL_INTERVAL_MS`), because neither a replicated
1061
+ * revocation nor a local `revokeMember`/`leaveStrand` raises anything this
1062
+ * runtime can hook. A caller that just wrote a revocation against the
1063
+ * strand's database should follow it with this call, which makes the cut
1064
+ * immediate instead of waiting out the interval.
1065
+ *
1066
+ * Quiet no-op — matching `quiesceStrand`'s posture — when the strand is not
1067
+ * tracked, is quiesced, is open, or has the gate disabled: in every one of
1068
+ * those cases there is no enforcer to refresh. Never rejects (the enforcer's
1069
+ * refresh contains its own failures), and resolves only once the sweep has
1070
+ * finished.
1071
+ */
1072
+ async refreshRevocationEnforcement(strandId: string): Promise<void> {
1073
+ const enforcer = this.revocationEnforcers.get(strandId);
1074
+ if (!enforcer) {
1075
+ log('refreshRevocationEnforcement: strand %s has no armed revocation enforcer', strandId);
1076
+ return;
1077
+ }
1078
+ await enforcer.refresh();
1079
+ }
1080
+
1081
+ /**
1082
+ * A fresh membership invitation was staged for `strandId` (`CadreNode`'s
1083
+ * `adoptFormationMembershipInvite`): re-arm the strand's membership reconciler so the
1084
+ * invitation is attempted now rather than never — the loop finished during the first
1085
+ * join and would otherwise stay stopped until a relaunch. Quiet no-op when no reconciler
1086
+ * is armed: a first formation stages before the strand is added, and bring-up then arms
1087
+ * a loop that finds the invitation by itself. Returns at once; the pass runs on the
1088
+ * loop's own serialized chain and never rejects.
1089
+ */
1090
+ notifyMembershipInviteStaged(strandId: string): void {
1091
+ const reconciler = this.membershipReconcilers.get(strandId);
1092
+ if (!reconciler) {
1093
+ log('notifyMembershipInviteStaged: strand %s has no armed membership reconciler — bring-up will find the invitation', strandId);
1094
+ return;
1095
+ }
1096
+ void reconciler.rearm();
1097
+ }
1098
+
1099
+ /**
1100
+ * Best-effort removal of THIS machine's own `Strand.MemberPeer` binding — the
1101
+ * self arm of `removeMemberPeer`, signed with the retained launch config's party
1102
+ * key. Called by `CadreNode.unpublishStrand` BEFORE the local stop, while the
1103
+ * strand database and transport are still live: after the unpublish commits, the
1104
+ * party's `StrandPartyKey` control row is gone, so no restart could ever sign
1105
+ * this removal again — the in-memory retained key is the last chance.
1106
+ *
1107
+ * Never throws. Quiet no-op for a strand that is untracked, open, or launched
1108
+ * without a party key; a quiesced (hibernating) strand, or a strand whose write
1109
+ * quorum is already unreachable, leaves the stale binding behind with a log —
1110
+ * it grants nothing today (admission is not allowlist-gated) and only
1111
+ * mis-credits diversity. The strand's own membership reconciler is stopped —
1112
+ * and its in-flight pass awaited — FIRST, so a pass that was already past its
1113
+ * own stopped check cannot re-register the binding this is about to clear.
1114
+ *
1115
+ * NOTE: deliberately NOT handled here (or anywhere yet): clearing the bindings
1116
+ * of a machine removed from the CADRE at the control layer, or of a party's
1117
+ * OTHER machines when the party unpublishes — the party still holds the key on
1118
+ * every surviving machine and can clear from any of them, and the stale rows
1119
+ * grant nothing while admission is deny-list only. Revisit when
1120
+ * `feat-strand-member-allowlist-admission` lands and a stale binding starts
1121
+ * granting admission rather than merely mis-crediting diversity.
1122
+ */
1123
+ async clearOwnMemberPeerBinding(strandId: string): Promise<void> {
1124
+ const instance = this.instances.get(strandId);
1125
+ const config = this.launchConfigs.get(strandId);
1126
+ if (!instance || !config || config.strandRow.Type !== 'c' || !config.partyMemberPrivateKey) {
1127
+ return;
1128
+ }
1129
+ const reconciler = this.membershipReconcilers.get(strandId);
1130
+ if (reconciler) {
1131
+ reconciler.stop();
1132
+ await reconciler.settle();
1133
+ }
1134
+ const db = instance.database?.getDatabase();
1135
+ const peerId = instance.libp2pNode?.peerId.toString();
1136
+ if (!db || !peerId) {
1137
+ log('clearOwnMemberPeerBinding: strand %s has no live runtime — own MemberPeer binding left in place', strandId);
1138
+ return;
1139
+ }
1140
+ try {
1141
+ // Background write on the app's database: never join a transaction the app has open.
1142
+ await removeMemberPeer(db, {
1143
+ memberKeyPair: strandMemberKeyPair(config.partyMemberPrivateKey),
1144
+ peerId
1145
+ }, { joinOpenTransaction: false });
1146
+ log('clearOwnMemberPeerBinding: strand %s — own binding for peer %s cleared', strandId, peerId);
1147
+ } catch (error) {
1148
+ log('clearOwnMemberPeerBinding: strand %s — best-effort clear failed (strand may already be unreachable): %o',
1149
+ strandId, error);
1150
+ }
1151
+ }
1152
+
1153
+ /**
1154
+ * Quiesce a strand: release its strand-network resources (stop the libp2p node,
1155
+ * close the StrandDatabase) while RETAINING the instance record — identity,
1156
+ * sAppInfo, keys, latency hint, metadata — and its launch config so it can be
1157
+ * resumed later. Mechanically this is `stopStrand` minus the instance/config
1158
+ * deletion. The caller sets the post-quiesce status (e.g. `hibernating`).
1159
+ * No-ops when the strand is missing or already quiesced.
1160
+ */
1161
+ async quiesceStrand(strandId: string): Promise<void> {
1162
+ const instance = this.instances.get(strandId);
1163
+ if (!instance) {
1164
+ log('quiesceStrand: strand %s not found', strandId);
1165
+ return;
1166
+ }
1167
+ if (!instance.libp2pNode && !instance.database) {
1168
+ log('quiesceStrand: strand %s already quiesced', strandId);
1169
+ return;
1170
+ }
1171
+
1172
+ log('Quiescing strand instance: %s', strandId);
1173
+ await this.releaseRuntime(instance);
1174
+ log('Strand %s quiesced (resources released, instance retained)', strandId);
1175
+ }
1176
+
1177
+ /**
1178
+ * Resume a previously-quiesced strand: rebuild its libp2p node + StrandDatabase
1179
+ * from the retained launch config and re-attach them, transitioning it back to
1180
+ * `active`. `overrides` re-applies volatile inputs that may have changed since
1181
+ * launch (the cohort `bootstrapNodes` seed and the strand's `servingMachines`
1182
+ * count) and updates the retained config so a later resume reuses the latest
1183
+ * values. Returns the live instance unchanged if it is already running.
1184
+ */
1185
+ async resumeStrand(strandId: string, overrides?: ResumeStrandOverrides): Promise<StrandInstance> {
1186
+ if (this.stopping) {
1187
+ throw new Error('StrandInstanceManager is stopping');
1188
+ }
1189
+ const instance = this.instances.get(strandId);
1190
+ if (!instance) {
1191
+ throw new Error(`Cannot resume strand ${strandId}: not tracked`);
1192
+ }
1193
+ const launchConfig = this.launchConfigs.get(strandId);
1194
+ if (!launchConfig) {
1195
+ throw new Error(`Cannot resume strand ${strandId}: no retained launch config`);
1196
+ }
1197
+ if (instance.libp2pNode || instance.database) {
1198
+ log('resumeStrand: strand %s already live', strandId);
1199
+ return instance;
1200
+ }
1201
+
1202
+ log('Resuming strand instance: %s', strandId);
1203
+ const tTotal = performance.now();
1204
+
1205
+ // Re-apply volatile inputs and persist them so a subsequent resume reuses them.
1206
+ // Each `??` matters: a resume that passes no override must keep the retained value,
1207
+ // and a resume that passes one must leave it retained for the next resume — otherwise
1208
+ // a later no-override wake silently reverts to whatever launch time saw.
1209
+ const resumeConfig: StartStrandConfig = {
1210
+ ...launchConfig,
1211
+ bootstrapNodes: overrides?.bootstrapNodes ?? launchConfig.bootstrapNodes,
1212
+ // NOTE: `??` retains, so an override can raise or lower the count but cannot CLEAR it
1213
+ // back to "this node no longer knows" — the direction that would declare nothing. Moot
1214
+ // while nothing feeds `servingMachines` at all; if a source lands
1215
+ // (`backlog/feat-strand-yardstick-from-serving-machines`) that can legitimately lose the
1216
+ // count — a strand whose member rows became unreadable — this merge must gain an explicit
1217
+ // clear rather than silently declaring a stale number over a serving set it can no longer
1218
+ // see. Same applies to `bootstrapNodes` above, where a stale seed is harmless.
1219
+ servingMachines: overrides?.servingMachines ?? launchConfig.servingMachines
1220
+ };
1221
+ this.launchConfigs.set(strandId, resumeConfig);
1222
+
1223
+ instance.status = 'starting';
1224
+ try {
1225
+ await this.buildStrandRuntime(instance, resumeConfig);
1226
+ timing('[resumeStrand:%s] total: %dms', strandId, Math.round(performance.now() - tTotal));
1227
+ log('Strand %s resumed successfully', strandId);
1228
+ return instance;
1229
+ } catch (error) {
1230
+ instance.status = 'error';
1231
+ instance.error = error instanceof Error ? error.message : String(error);
1232
+ log('Failed to resume strand %s: %s', strandId, instance.error);
1233
+ throw error;
1234
+ }
1235
+ }
1236
+
1237
+ /**
1238
+ * Honor a founder request against an ALREADY-TRACKED strand — the seam that
1239
+ * closes the "whoever launches first decides whether the bootstrap runs" gap:
1240
+ * an instance first launched as a joiner (an app's own attach, or a watcher
1241
+ * poll winning the launch race) used to swallow a later founder request
1242
+ * silently, leaving the strand active with no `Strand.Header`.
1243
+ *
1244
+ * Flips the RETAINED launch config's `founder` to true, so every later
1245
+ * quiesce → resume rebuild founds as well (the bootstrap is insert-if-absent —
1246
+ * {@link StrandDatabase.ensureFounderBootstrap} — so re-running it per rebuild
1247
+ * writes nothing twice), and runs the bootstrap against the live database now.
1248
+ *
1249
+ * @returns how the request resolved:
1250
+ * - `'already-founder'` — the retained config already founds; nothing to do.
1251
+ * - `'bootstrapped'` — config flipped and the live database ran the bootstrap.
1252
+ * - `'needs-resume'` — config flipped, but the instance is quiesced (no live
1253
+ * database), so the bootstrap could not run here: the CALLER must wake the
1254
+ * strand (`CadreNode.wakeStrand`, which owns the hibernation bookkeeping this
1255
+ * manager does not) so the rebuild — which now founds — runs it.
1256
+ * @param resolvePartyKey - Asked for the party's own membership key when (and only
1257
+ * when) a CLOSED strand's retained config carries none — the instance was launched
1258
+ * as a joiner before its `StrandPartyKey` row existed or replicated. The resolved
1259
+ * key is retained alongside the founder flip so the bootstrap (now, or on the
1260
+ * caller's wake for `'needs-resume'`) can seat the founding Member/Manager.
1261
+ * @throws when the strand is not tracked — this seam exists only for the
1262
+ * tracked-instance launch path; an untracked id is a caller bug.
1263
+ * @throws whatever the live bootstrap throws (e.g. `PreSplitStrandIdentityError`),
1264
+ * after {@link withdrawFounderRequest} — so a retry re-attempts the founding rather
1265
+ * than resolving `'already-founder'` over an instance that never founded. A caller
1266
+ * whose `'needs-resume'` wake fails owes the same withdrawal.
1267
+ */
1268
+ async foundExistingStrand(
1269
+ strandId: string,
1270
+ resolvePartyKey?: () => Promise<string | undefined>
1271
+ ): Promise<'already-founder' | 'bootstrapped' | 'needs-resume'> {
1272
+ const instance = this.instances.get(strandId);
1273
+ const config = this.launchConfigs.get(strandId);
1274
+ if (!instance || !config) {
1275
+ throw new Error(`Cannot found strand ${strandId}: not tracked`);
1276
+ }
1277
+ if (config.founder === true) {
1278
+ return 'already-founder';
1279
+ }
1280
+ const partyMemberPrivateKey =
1281
+ config.partyMemberPrivateKey
1282
+ ?? (config.strandRow.Type === 'c' ? await resolvePartyKey?.() : undefined);
1283
+ // A fresh object rather than mutating in place: startStrand retains the CALLER'S
1284
+ // config object, which is not ours to rewrite.
1285
+ this.launchConfigs.set(strandId, { ...config, founder: true, partyMemberPrivateKey });
1286
+ if (!instance.database && !this.firstSyncGates.has(strandId)) {
1287
+ return 'needs-resume';
1288
+ }
1289
+ try {
1290
+ await this.ensureFounderBootstrap(strandId);
1291
+ } catch (error) {
1292
+ this.withdrawFounderRequest(strandId);
1293
+ throw error;
1294
+ }
1295
+ return 'bootstrapped';
1296
+ }
1297
+
1298
+ /**
1299
+ * Whether `strandId` is launched but still waiting for its first sync — a joiner whose
1300
+ * runtime is up while its database is withheld (status `'syncing'`, or `'idle'` after
1301
+ * the hibernation manager's idle timer fired on it). `false` for a writable, quiesced,
1302
+ * or untracked strand. The predicate {@link whenWritable}'s callers gate on.
1303
+ */
1304
+ isAwaitingFirstSync(strandId: string): boolean {
1305
+ const instance = this.instances.get(strandId);
1306
+ return instance !== undefined && isAwaitingFirstSync(instance);
1307
+ }
1308
+
1309
+ /**
1310
+ * Resolve once the strand's database is published to the app — immediately for a
1311
+ * writable strand — or reject with {@link StrandAwaitingFirstSyncError} after
1312
+ * `timeoutMs` (default: the retained launch config's `firstSync.timeoutMs`, else
1313
+ * {@link DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS}). The rejection is RETRYABLE: nothing is
1314
+ * torn down, the gate keeps probing, and a later call waits afresh. A quiesced
1315
+ * (hibernating) strand is not woken here — the wait spans a resume, so a caller that
1316
+ * wants one wakes it (`CadreNode.wakeStrand`) and waits. Rejects immediately for an
1317
+ * untracked strand, and whenever the strand is stopped while a wait is pending.
1318
+ */
1319
+ whenWritable(strandId: string, options?: { timeoutMs?: number }): Promise<StrandInstance> {
1320
+ const instance = this.instances.get(strandId);
1321
+ if (!instance) {
1322
+ return Promise.reject(new Error(`Cannot wait for strand ${strandId} to become writable: not tracked`));
1323
+ }
1324
+ if (instance.database) {
1325
+ return Promise.resolve(instance);
1326
+ }
1327
+ const timeoutMs = options?.timeoutMs
1328
+ ?? this.launchConfigs.get(strandId)?.firstSync?.timeoutMs
1329
+ ?? DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS;
1330
+ const startedAt = Date.now();
1331
+ return new Promise<StrandInstance>((resolve, reject) => {
1332
+ const waiters = this.writableWaiters.get(strandId) ?? new Set<WritableWaiter>();
1333
+ this.writableWaiters.set(strandId, waiters);
1334
+ const settle = (): void => {
1335
+ clearTimeout(timer);
1336
+ waiters.delete(waiter);
1337
+ if (waiters.size === 0) {
1338
+ this.writableWaiters.delete(strandId);
1339
+ }
1340
+ };
1341
+ const waiter: WritableWaiter = {
1342
+ resolve: () => { settle(); resolve(instance); },
1343
+ reject: (error) => { settle(); reject(error); }
1344
+ };
1345
+ const timer = setTimeout(
1346
+ () => waiter.reject(new StrandAwaitingFirstSyncError(strandId, Date.now() - startedAt)),
1347
+ timeoutMs);
1348
+ (timer as { unref?: () => void }).unref?.();
1349
+ waiters.add(waiter);
1350
+ });
1351
+ }
1352
+
1353
+ /**
1354
+ * Hand a launch's database to the app: set `instance.database`, retire the gate that
1355
+ * held it, release every {@link whenWritable} waiter, and — when the launch had already
1356
+ * been reported gated — flip it `'active'` and announce it through the retained config's
1357
+ * `onWritable`. "Reported gated" is any status but `'starting'`: `'syncing'`, or the
1358
+ * `'idle'` the hibernation manager's idle timer flips a long-gated joiner to (see
1359
+ * {@link isAwaitingFirstSync}) — the Header arriving after that flip must announce too,
1360
+ * or an app hanging on `strand:writable` never learns the strand opened. A publish that
1361
+ * lands while the instance is still `'starting'` (the Header arrived during the rest of
1362
+ * bring-up) announces nothing: `startStrand` / `resumeStrand` are about to report the
1363
+ * strand `'active'`, and `strand:writable` is defined as the follow-up to a gated
1364
+ * launch, never a duplicate of `strand:started`.
1365
+ *
1366
+ * It is also the one seam where a WITHHELD database becomes available, so it kicks the
1367
+ * membership reconciler: on a gated launch that loop's own immediate pass ran while
1368
+ * `instance.database` was still unset, found no database, and would otherwise not try
1369
+ * again until its retry timer fired. A launch that was never gated publishes here BEFORE
1370
+ * the reconciler is constructed, so there is nothing registered to kick and the loop's own
1371
+ * immediate pass already sees the database — which is why the kick needs no `wasGated`
1372
+ * test of its own.
1373
+ */
1374
+ private publishDatabase(instance: StrandInstance, database: StrandDatabase): void {
1375
+ const strandId = instance.strandId;
1376
+ const gate = this.firstSyncGates.get(strandId);
1377
+ if (gate) {
1378
+ gate.open();
1379
+ this.firstSyncGates.delete(strandId);
1380
+ }
1381
+ instance.database = database;
1382
+ instance.lastActivity = new Date();
1383
+ const wasGated = instance.status !== 'starting';
1384
+ if (wasGated) {
1385
+ instance.status = 'active';
1386
+ log('Strand %s is now writable: Strand.Header held', strandId);
1387
+ }
1388
+ const waiters = this.writableWaiters.get(strandId);
1389
+ if (waiters) {
1390
+ this.writableWaiters.delete(strandId);
1391
+ waiters.forEach((waiter) => waiter.resolve());
1392
+ }
1393
+ if (wasGated) {
1394
+ this.launchConfigs.get(strandId)?.onWritable?.(strandId);
1395
+ }
1396
+ // Not awaited: publishing must stay synchronous, and the pass chains on the loop's own
1397
+ // tail, so it cannot overlap a pass already in flight.
1398
+ void this.membershipReconcilers.get(strandId)?.reconcile();
1399
+ }
1400
+
1401
+ /** Reject every {@link whenWritable} waiter for a strand that is going away. */
1402
+ private rejectWritableWaiters(strandId: string, reason: string): void {
1403
+ const waiters = this.writableWaiters.get(strandId);
1404
+ if (!waiters) {
1405
+ return;
1406
+ }
1407
+ this.writableWaiters.delete(strandId);
1408
+ waiters.forEach((waiter) => waiter.reject(new Error(`Strand ${strandId} ${reason} before becoming writable`)));
1409
+ }
1410
+
1411
+ /**
1412
+ * Undo {@link foundExistingStrand}'s founder flip after the founding it promised
1413
+ * failed, so the retained config again says what this instance actually runs as (a
1414
+ * joiner) and the next founder request re-attempts the bootstrap. The resolved party
1415
+ * key stays retained — it is this party's identity for the strand either way. No-op
1416
+ * when the strand is untracked or its config does not found.
1417
+ */
1418
+ withdrawFounderRequest(strandId: string): void {
1419
+ const config = this.launchConfigs.get(strandId);
1420
+ if (config?.founder === true) {
1421
+ this.launchConfigs.set(strandId, { ...config, founder: false });
1422
+ }
1423
+ }
1424
+
1425
+ /**
1426
+ * Run the (idempotent) founder bootstrap against a tracked strand's LIVE
1427
+ * database, independently of what the retained launch config says.
1428
+ *
1429
+ * Separate from {@link foundExistingStrand} because a caller that resolved
1430
+ * `'needs-resume'` and woke the strand must not assume the wake's own rebuild
1431
+ * founded it: `HibernationManager` COALESCES wakes, so a wake already in flight
1432
+ * when the config flipped had already read the PRE-flip config and rebuilt as a
1433
+ * joiner. Re-running the bootstrap costs one insert-if-absent probe per table
1434
+ * and is the only thing that makes "founding resolves once the Header is
1435
+ * written" true on that path.
1436
+ *
1437
+ * A strand still `'syncing'` (its database withheld behind the first-sync gate) is
1438
+ * founded through the gate: the bootstrap writes the Header this machine was waiting
1439
+ * to receive, so a successful run publishes the database and the strand goes
1440
+ * `'active'` — the one legitimate way a joiner launch becomes writable without a peer.
1441
+ *
1442
+ * @throws when the strand is not tracked, or is still quiesced (no live
1443
+ * database) — both mean the bootstrap did NOT run, which a founder request
1444
+ * must never swallow.
1445
+ */
1446
+ async ensureFounderBootstrap(strandId: string): Promise<void> {
1447
+ const instance = this.instances.get(strandId);
1448
+ if (!instance) {
1449
+ throw new Error(`Cannot run the founder bootstrap for strand ${strandId}: not tracked`);
1450
+ }
1451
+ const gate = this.firstSyncGates.get(strandId);
1452
+ const database = instance.database ?? gate?.database;
1453
+ if (!database) {
1454
+ throw new Error(
1455
+ `Cannot run the founder bootstrap for strand ${strandId}: it is quiesced, so there ` +
1456
+ 'is no live database to write to — resume it first.'
1457
+ );
1458
+ }
1459
+ // Forward the RETAINED config's party key: a foundExistingStrand that flipped a
1460
+ // joiner launch to founder may have resolved a key the live database's captured
1461
+ // config (built at the original launch) never saw.
1462
+ await database.ensureFounderBootstrap(this.launchConfigs.get(strandId)?.partyMemberPrivateKey);
1463
+ if (!instance.database) {
1464
+ this.publishDatabase(instance, database);
1465
+ }
1466
+ }
1467
+
1468
+ /**
1469
+ * Stop a strand instance
1470
+ */
1471
+ async stopStrand(strandId: string): Promise<void> {
1472
+ const instance = this.instances.get(strandId);
1473
+ if (!instance) {
1474
+ log('Strand %s not found', strandId);
1475
+ return;
1476
+ }
1477
+
1478
+ log('Stopping strand instance: %s', strandId);
1479
+ instance.status = 'stopping';
1480
+ this.rejectWritableWaiters(strandId, 'was stopped');
1481
+
1482
+ try {
1483
+ await this.releaseRuntime(instance);
1484
+ instance.status = 'stopped';
1485
+ this.instances.delete(strandId);
1486
+ this.launchConfigs.delete(strandId);
1487
+ // Storage is released only here — NOT in releaseRuntime, which a quiesce shares.
1488
+ await this.disposeStrandStorage(strandId);
1489
+ log('Strand %s stopped successfully', strandId);
1490
+ } catch (error) {
1491
+ instance.status = 'error';
1492
+ instance.error = error instanceof Error ? error.message : String(error);
1493
+ log('Error stopping strand %s: %s', strandId, instance.error);
1494
+ throw error;
1495
+ }
1496
+ }
1497
+
1498
+ /**
1499
+ * Stop all strand instances
1500
+ */
1501
+ async stopAll(): Promise<void> {
1502
+ this.stopping = true;
1503
+ log('Stopping all strand instances (%d)', this.instances.size);
1504
+
1505
+ const stopPromises = Array.from(this.instances.keys()).map(id =>
1506
+ this.stopStrand(id).catch(err => {
1507
+ log('Error stopping strand %s during shutdown: %s', id, err);
1508
+ })
1509
+ );
1510
+
1511
+ await Promise.all(stopPromises);
1512
+ this.stopping = false;
1513
+ log('All strand instances stopped');
1514
+ }
1515
+ }
1516
+