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