@serfab/cadre-core 1.22.0 → 1.24.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 (314) hide show
  1. package/README.md +216 -294
  2. package/dist/arachnode-stub.d.ts +12 -4
  3. package/dist/arachnode-stub.js +15 -8
  4. package/dist/arachnode-stub.js.map +1 -1
  5. package/dist/cadre-invite-protocol.js +5 -4
  6. package/dist/cadre-invite-protocol.js.map +1 -1
  7. package/dist/cadre-node.d.ts +159 -53
  8. package/dist/cadre-node.js +276 -89
  9. package/dist/cadre-node.js.map +1 -1
  10. package/dist/control-authorization.d.ts +14 -2
  11. package/dist/control-authorization.js +8 -3
  12. package/dist/control-authorization.js.map +1 -1
  13. package/dist/control-cohort.d.ts +27 -13
  14. package/dist/control-cohort.js +21 -14
  15. package/dist/control-cohort.js.map +1 -1
  16. package/dist/control-database.d.ts +18 -16
  17. package/dist/control-database.js +57 -22
  18. package/dist/control-database.js.map +1 -1
  19. package/dist/control-protocol-guard.d.ts +1 -1
  20. package/dist/control-protocol-guard.js +7 -3
  21. package/dist/control-protocol-guard.js.map +1 -1
  22. package/dist/control-read-retry.d.ts +49 -11
  23. package/dist/control-read-retry.js +56 -15
  24. package/dist/control-read-retry.js.map +1 -1
  25. package/dist/control-retry.d.ts +32 -3
  26. package/dist/control-retry.js +35 -4
  27. package/dist/control-retry.js.map +1 -1
  28. package/dist/control-schema-version.d.ts +5 -5
  29. package/dist/control-schema-version.js +5 -5
  30. package/dist/control-schema-version.js.map +1 -1
  31. package/dist/control-schema.d.ts +5 -5
  32. package/dist/control-schema.js +1032 -1011
  33. package/dist/control-schema.js.map +1 -1
  34. package/dist/control-write-retry.d.ts +54 -65
  35. package/dist/control-write-retry.js +134 -158
  36. package/dist/control-write-retry.js.map +1 -1
  37. package/dist/delegate-admission.d.ts +1 -1
  38. package/dist/delegate-admission.js +1 -1
  39. package/dist/edge-node/config.d.ts +4 -3
  40. package/dist/edge-node/config.js +11 -9
  41. package/dist/edge-node/config.js.map +1 -1
  42. package/dist/edge-node/dissolve.d.ts +4 -4
  43. package/dist/edge-node/dissolve.js +4 -4
  44. package/dist/edge-node/edge-join.d.ts +1 -1
  45. package/dist/edge-node/edge-join.js +1 -1
  46. package/dist/edge-node/edge-node.js +2 -2
  47. package/dist/edge-node/edge-node.js.map +1 -1
  48. package/dist/edge-node/index.d.ts +1 -0
  49. package/dist/edge-node/index.js +1 -0
  50. package/dist/edge-node/index.js.map +1 -1
  51. package/dist/edge-node/join-credential.d.ts +1 -1
  52. package/dist/edge-node/join-credential.js +1 -1
  53. package/dist/edge-node/lazy-raw-storage.js +12 -0
  54. package/dist/edge-node/lazy-raw-storage.js.map +1 -1
  55. package/dist/edge-node/listen-addrs.d.ts +21 -0
  56. package/dist/edge-node/listen-addrs.js +25 -0
  57. package/dist/edge-node/listen-addrs.js.map +1 -0
  58. package/dist/edge-node/owner-grant.d.ts +1 -1
  59. package/dist/edge-node/owner-grant.js +1 -1
  60. package/dist/edge-node/platform.d.ts +5 -4
  61. package/dist/edge-node/platform.js.map +1 -1
  62. package/dist/edge-node/strand-move.d.ts +1 -1
  63. package/dist/edge-node/strand-move.js +1 -1
  64. package/dist/edge-node/strands.js +27 -11
  65. package/dist/edge-node/strands.js.map +1 -1
  66. package/dist/index.d.ts +7 -5
  67. package/dist/index.js +18 -7
  68. package/dist/index.js.map +1 -1
  69. package/dist/invitation-bootstrap.d.ts +28 -5
  70. package/dist/invitation-bootstrap.js +41 -8
  71. package/dist/invitation-bootstrap.js.map +1 -1
  72. package/dist/link-budget.d.ts +53 -4
  73. package/dist/link-budget.js +58 -5
  74. package/dist/link-budget.js.map +1 -1
  75. package/dist/machine-removal.d.ts +2 -2
  76. package/dist/machine-removal.js +4 -3
  77. package/dist/machine-removal.js.map +1 -1
  78. package/dist/membership-connection-gater.d.ts +2 -2
  79. package/dist/membership-connection-gater.js +2 -2
  80. package/dist/membership-view.d.ts +2 -2
  81. package/dist/membership-view.js +6 -3
  82. package/dist/membership-view.js.map +1 -1
  83. package/dist/node-claim-payload.d.ts +15 -7
  84. package/dist/node-claim-payload.js +25 -9
  85. package/dist/node-claim-payload.js.map +1 -1
  86. package/dist/node-class.d.ts +36 -0
  87. package/dist/node-class.js +26 -0
  88. package/dist/node-class.js.map +1 -0
  89. package/dist/node-default-transports.d.ts +50 -3
  90. package/dist/node-default-transports.js +48 -3
  91. package/dist/node-default-transports.js.map +1 -1
  92. package/dist/node-roles.d.ts +118 -0
  93. package/dist/node-roles.js +142 -0
  94. package/dist/node-roles.js.map +1 -0
  95. package/dist/node-transports.d.ts +6 -2
  96. package/dist/node-transports.js +39 -7
  97. package/dist/node-transports.js.map +1 -1
  98. package/dist/owner-anchor-sync.js +1 -1
  99. package/dist/owner-key-export.js +1 -1
  100. package/dist/owner-key-flows.d.ts +1 -1
  101. package/dist/owner-key-store.js +1 -1
  102. package/dist/owner-signer.js +1 -1
  103. package/dist/peer-authorization.d.ts +3 -1
  104. package/dist/peer-authorization.js +3 -1
  105. package/dist/peer-authorization.js.map +1 -1
  106. package/dist/peer-dial.d.ts +74 -10
  107. package/dist/peer-dial.js +89 -17
  108. package/dist/peer-dial.js.map +1 -1
  109. package/dist/peer-join-backfill.js +4 -4
  110. package/dist/peer-join-backfill.js.map +1 -1
  111. package/dist/peer-record.d.ts +34 -9
  112. package/dist/peer-record.js +66 -13
  113. package/dist/peer-record.js.map +1 -1
  114. package/dist/pending-join-runner.d.ts +1 -1
  115. package/dist/pending-join-runner.js +1 -1
  116. package/dist/provider/client.d.ts +6 -5
  117. package/dist/provider/client.js +3 -3
  118. package/dist/provider/client.js.map +1 -1
  119. package/dist/provider/descriptor.d.ts +1 -1
  120. package/dist/provider/descriptor.js +1 -1
  121. package/dist/provider/oauth.d.ts +1 -1
  122. package/dist/provider/oauth.js +1 -1
  123. package/dist/provider/rent-node.d.ts +4 -3
  124. package/dist/provider/rent-node.js +3 -3
  125. package/dist/provider/rent-node.js.map +1 -1
  126. package/dist/relay-addrs.d.ts +62 -7
  127. package/dist/relay-addrs.js +74 -11
  128. package/dist/relay-addrs.js.map +1 -1
  129. package/dist/relay-reservation.d.ts +1 -1
  130. package/dist/relay-reservation.js +1 -1
  131. package/dist/relay-server.d.ts +6 -5
  132. package/dist/relay-server.js +5 -5
  133. package/dist/relay-server.js.map +1 -1
  134. package/dist/schema-verification.d.ts +13 -10
  135. package/dist/schema-verification.js +32 -24
  136. package/dist/schema-verification.js.map +1 -1
  137. package/dist/sealed-party-key.js +1 -1
  138. package/dist/seed-bootstrap.d.ts +4 -3
  139. package/dist/seed-bootstrap.js +6 -7
  140. package/dist/seed-bootstrap.js.map +1 -1
  141. package/dist/strand-addr-protocol.d.ts +8 -6
  142. package/dist/strand-addr-protocol.js +12 -10
  143. package/dist/strand-addr-protocol.js.map +1 -1
  144. package/dist/strand-app-schema-report.d.ts +16 -2
  145. package/dist/strand-app-schema-report.js +15 -0
  146. package/dist/strand-app-schema-report.js.map +1 -1
  147. package/dist/strand-cohort.d.ts +1 -4
  148. package/dist/strand-cohort.js.map +1 -1
  149. package/dist/strand-commit-durability.d.ts +1 -1
  150. package/dist/strand-database.d.ts +13 -6
  151. package/dist/strand-database.js +17 -9
  152. package/dist/strand-database.js.map +1 -1
  153. package/dist/strand-first-sync-gate.d.ts +3 -2
  154. package/dist/strand-first-sync-gate.js +3 -2
  155. package/dist/strand-first-sync-gate.js.map +1 -1
  156. package/dist/strand-formation-deadlines.d.ts +2 -2
  157. package/dist/strand-formation-deadlines.js +2 -2
  158. package/dist/strand-formation-protocol.d.ts +1 -1
  159. package/dist/strand-formation-protocol.js +51 -16
  160. package/dist/strand-formation-protocol.js.map +1 -1
  161. package/dist/strand-instance-manager.d.ts +134 -42
  162. package/dist/strand-instance-manager.js +331 -76
  163. package/dist/strand-instance-manager.js.map +1 -1
  164. package/dist/strand-membership-reconciler.d.ts +8 -3
  165. package/dist/strand-membership-reconciler.js +8 -3
  166. package/dist/strand-membership-reconciler.js.map +1 -1
  167. package/dist/strand-membership-writer.d.ts +2 -2
  168. package/dist/strand-membership-writer.js +41 -39
  169. package/dist/strand-membership-writer.js.map +1 -1
  170. package/dist/strand-move.js +1 -1
  171. package/dist/strand-network-config.d.ts +15 -5
  172. package/dist/strand-network-config.js +7 -6
  173. package/dist/strand-network-config.js.map +1 -1
  174. package/dist/strand-party-key-rotation.d.ts +7 -3
  175. package/dist/strand-party-key-rotation.js +7 -3
  176. package/dist/strand-party-key-rotation.js.map +1 -1
  177. package/dist/strand-party-machines.d.ts +19 -8
  178. package/dist/strand-party-machines.js +26 -11
  179. package/dist/strand-party-machines.js.map +1 -1
  180. package/dist/strand-party-peers.d.ts +36 -14
  181. package/dist/strand-party-peers.js +24 -15
  182. package/dist/strand-party-peers.js.map +1 -1
  183. package/dist/strand-peer-redial.d.ts +1 -1
  184. package/dist/strand-peer-redial.js +1 -1
  185. package/dist/strand-reactivity.d.ts +20 -17
  186. package/dist/strand-reactivity.js +31 -18
  187. package/dist/strand-reactivity.js.map +1 -1
  188. package/dist/strand-revocation-enforcer.d.ts +3 -3
  189. package/dist/strand-revocation-enforcer.js +3 -3
  190. package/dist/strand-wake-protocol.d.ts +19 -7
  191. package/dist/strand-wake-protocol.js +22 -10
  192. package/dist/strand-wake-protocol.js.map +1 -1
  193. package/dist/strand-watcher.d.ts +1 -1
  194. package/dist/strand-watcher.js +1 -1
  195. package/dist/table-change-watch.js +1 -1
  196. package/dist/types.d.ts +127 -57
  197. package/dist/types.js.map +1 -1
  198. package/dist/webrtc-upgrade.d.ts +254 -0
  199. package/dist/webrtc-upgrade.js +355 -0
  200. package/dist/webrtc-upgrade.js.map +1 -0
  201. package/package.json +9 -9
  202. package/src/announce-addrs.ts +93 -93
  203. package/src/arachnode-stub.ts +18 -10
  204. package/src/bootstrap-peer-store-file.ts +44 -44
  205. package/src/bootstrap-peer-store.ts +214 -214
  206. package/src/cadre-invite-protocol.ts +741 -740
  207. package/src/cadre-node.ts +12462 -12252
  208. package/src/claim-proof.ts +147 -147
  209. package/src/control-authorization.ts +290 -276
  210. package/src/control-cohort.ts +223 -204
  211. package/src/control-database.ts +72 -28
  212. package/src/control-formation-recorder.ts +359 -359
  213. package/src/control-protocol-guard.ts +370 -366
  214. package/src/control-read-retry.ts +222 -180
  215. package/src/control-retry.ts +36 -4
  216. package/src/control-schema-version.ts +301 -301
  217. package/src/control-schema.ts +1108 -1087
  218. package/src/control-write-retry.ts +639 -669
  219. package/src/delegate-admission.ts +351 -351
  220. package/src/describe-thrown.ts +60 -60
  221. package/src/ed25519-key.ts +185 -185
  222. package/src/edge-node/config.ts +13 -10
  223. package/src/edge-node/dissolve.ts +252 -252
  224. package/src/edge-node/edge-join.ts +320 -320
  225. package/src/edge-node/edge-node.ts +1095 -1095
  226. package/src/edge-node/index.ts +60 -59
  227. package/src/edge-node/join-credential.ts +16 -16
  228. package/src/edge-node/lazy-raw-storage.ts +194 -178
  229. package/src/edge-node/listen-addrs.ts +26 -0
  230. package/src/edge-node/node-local.ts +84 -84
  231. package/src/edge-node/options.ts +195 -195
  232. package/src/edge-node/owner-grant.ts +63 -63
  233. package/src/edge-node/platform.ts +5 -4
  234. package/src/edge-node/strand-move.ts +266 -266
  235. package/src/edge-node/strands.ts +27 -12
  236. package/src/enrolled-machine-store-file.ts +43 -43
  237. package/src/enrolled-machine-store.ts +280 -280
  238. package/src/fetch-impl.ts +23 -23
  239. package/src/file-durable-slot.ts +64 -64
  240. package/src/file-safe-name.ts +32 -32
  241. package/src/formation-approval.ts +604 -604
  242. package/src/formation-token.ts +63 -63
  243. package/src/fs-atomic.ts +92 -92
  244. package/src/index.ts +987 -957
  245. package/src/invitation-bootstrap.ts +152 -118
  246. package/src/joined-strand-store.ts +553 -553
  247. package/src/key-store-file.ts +142 -142
  248. package/src/link-budget.ts +61 -5
  249. package/src/machine-removal.ts +211 -210
  250. package/src/member-redemption.ts +643 -643
  251. package/src/membership-connection-gater.ts +650 -650
  252. package/src/membership-view.ts +147 -144
  253. package/src/node-claim-payload.ts +34 -12
  254. package/src/node-class.ts +47 -0
  255. package/src/node-default-transports.ts +65 -3
  256. package/src/node-roles.ts +220 -0
  257. package/src/node-transports.ts +86 -49
  258. package/src/owner-anchor-sync.ts +172 -172
  259. package/src/owner-grant-protocol.ts +547 -547
  260. package/src/owner-key-export.ts +348 -348
  261. package/src/owner-key-flows.ts +109 -109
  262. package/src/owner-key-store.ts +1 -1
  263. package/src/owner-keys.ts +179 -179
  264. package/src/owner-signer.ts +92 -92
  265. package/src/peer-addr-book.ts +252 -252
  266. package/src/peer-authorization.ts +584 -582
  267. package/src/peer-dial.ts +698 -605
  268. package/src/peer-join-backfill.ts +961 -961
  269. package/src/peer-record.ts +71 -16
  270. package/src/pending-join-runner.ts +798 -798
  271. package/src/primary-lan-address.ts +47 -47
  272. package/src/provider/client.ts +327 -326
  273. package/src/provider/descriptor.ts +129 -129
  274. package/src/provider/index.ts +59 -59
  275. package/src/provider/oauth.ts +285 -285
  276. package/src/provider/rent-node.ts +276 -275
  277. package/src/relay-addrs.ts +90 -12
  278. package/src/relay-reservation.ts +1 -1
  279. package/src/relay-server.ts +99 -98
  280. package/src/schema-verification.ts +38 -23
  281. package/src/sealed-party-key.ts +190 -190
  282. package/src/seed-bootstrap.ts +8 -11
  283. package/src/seed-trust-policy.ts +353 -353
  284. package/src/self-address-update.ts +19 -19
  285. package/src/strand-addr-protocol.ts +17 -14
  286. package/src/strand-app-schema-report.ts +147 -122
  287. package/src/strand-cohort.ts +1 -5
  288. package/src/strand-commit-durability.ts +165 -165
  289. package/src/strand-database.ts +522 -510
  290. package/src/strand-first-sync-gate.ts +3 -2
  291. package/src/strand-formation-deadlines.ts +227 -227
  292. package/src/strand-formation-manager.ts +731 -731
  293. package/src/strand-formation-protocol.ts +1174 -1138
  294. package/src/strand-fret-addrs.ts +179 -179
  295. package/src/strand-instance-manager.ts +381 -85
  296. package/src/strand-membership-reconciler.ts +1315 -1310
  297. package/src/strand-membership-writer.ts +2152 -2150
  298. package/src/strand-move.ts +1 -1
  299. package/src/strand-network-config.ts +16 -6
  300. package/src/strand-offline.ts +178 -178
  301. package/src/strand-party-key-rotation.ts +440 -436
  302. package/src/strand-party-machines.ts +308 -293
  303. package/src/strand-party-peers.ts +151 -129
  304. package/src/strand-peer-redial.ts +1 -1
  305. package/src/strand-reactivity.ts +36 -19
  306. package/src/strand-revocation-enforcer.ts +758 -758
  307. package/src/strand-wake-protocol.ts +406 -394
  308. package/src/strand-watcher.ts +1 -1
  309. package/src/table-change-watch.ts +285 -285
  310. package/src/timed-step.ts +28 -28
  311. package/src/timeout-scheduler.ts +29 -29
  312. package/src/trusted-owner-store.ts +242 -242
  313. package/src/types.ts +3182 -3112
  314. package/src/webrtc-upgrade.ts +439 -0
@@ -1,8 +1,9 @@
1
1
  import debug from 'debug';
2
2
  import { createLibp2pNode } from '@optimystic/db-p2p';
3
- import { wrapStorageWithCache, disposeStorageCache } from '@serfab/quereus-plugin-sereus';
3
+ import { wrapStorageWithCache, disposeStorageCache, checkAppSchema, appSchemaRefusalOf } from '@serfab/quereus-plugin-sereus';
4
4
  import { StrandDatabase } from './strand-database.js';
5
5
  import { PeerJoinBackfill } from './peer-join-backfill.js';
6
+ import { WebrtcUpgradeService } from './webrtc-upgrade.js';
6
7
  import { strandNetworkStatePersistence } from './strand-network-state.js';
7
8
  import { StrandRevocationEnforcer, createRevocationConnectionGater, readStrandRevocationRows } from './strand-revocation-enforcer.js';
8
9
  import { StrandMembershipReconciler } from './strand-membership-reconciler.js';
@@ -14,19 +15,20 @@ import { assertStrandScopeKey } from './storage-scope.js';
14
15
  import { StrandFirstSyncGate, StrandAwaitingFirstSyncError, DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS } from './strand-first-sync-gate.js';
15
16
  import { DEFAULT_CONNECTION_MONITOR, resolveStrandClusterSize, strandClusterPolicy } from './types.js';
16
17
  import { strandNodeAddrs } from './strand-network-config.js';
18
+ import { listenTransportNodeOptions } from './relay-addrs.js';
17
19
  import { nodeTransportsOption } from './node-transports.js';
18
20
  import { resolveRelayServer } from './relay-server.js';
19
21
  import { strandCohortTopicOption } from './strand-reactivity.js';
20
22
  import { superviseRelayReservation } from './relay-reservation.js';
21
23
  import { strandRedialTimings, superviseStrandPeerRedial } from './strand-peer-redial.js';
22
24
  import { groupAddrsByPeerId } from './peer-addr-book.js';
23
- import { isCohortUnreachableRead } from './control-read-retry.js';
24
- import { declaredCohortReadDeadlineMs, optimysticDialLimits, peerJoinPushBudget, relayReservationBudgetMs, resolveLinkRoundTripMs } from './link-budget.js';
25
+ import { isCohortUnreachableRead, isNoCoordinatorResolved } from './control-read-retry.js';
26
+ import { declaredCohortReadDeadlineMs, optimysticDialLimits, peerJoinPushBudget, relayReservationBudgetMs, resolveLinkRoundTripMs, webrtcUpgradeDialBudgetMs } from './link-budget.js';
25
27
  import { describeThrown } from './describe-thrown.js';
26
28
  const log = debug('sereus:cadre:strand-manager');
27
29
  /**
28
- * How often a joining launch that could not build its database, because no seed peer had
29
- * answered, retries the build on its running libp2p node
30
+ * How often a launch that could not build its database, because no machine that can answer for
31
+ * the strand's blocks was reachable, retries the build on its running libp2p node
30
32
  * (`StrandInstanceManager.deferUnreachableJoin`). Each attempt composes a fresh database and
31
33
  * re-reads the schema catalog over the network, so it is spaced well above the first-sync
32
34
  * gate's probe cadence.
@@ -128,6 +130,7 @@ function verifiedSAppInfo(strandId, sAppConfig, requireSignedSchemas) {
128
130
  return {
129
131
  id: sAppConfig.id,
130
132
  version: sAppConfig.version,
133
+ schemaVersion: sAppConfig.schemaVersion,
131
134
  schema: sAppConfig.schema,
132
135
  signature: sAppConfig.signature
133
136
  };
@@ -146,7 +149,7 @@ export class StrandInstanceManager {
146
149
  /**
147
150
  * Retained launch config per strand, captured in `startStrand` and cleared in
148
151
  * `stopStrand`. `resumeStrand` reuses it to rebuild a quiesced strand's runtime
149
- * without the caller re-threading storage/network/profile/key/sApp config.
152
+ * without the caller re-threading storage/network/node-class/key/sApp config.
150
153
  */
151
154
  this.launchConfigs = new Map();
152
155
  /**
@@ -212,6 +215,13 @@ export class StrandInstanceManager {
212
215
  * nobody and a resume redials over the new node.
213
216
  */
214
217
  this.peerRedials = new Map();
218
+ /**
219
+ * The per-strand background WebRTC upgrade of relayed connections (`webrtc-upgrade.ts`), keyed
220
+ * by strand id. Same lifecycle as {@link peerRedials}: started in `buildStrandRuntime` once
221
+ * the libp2p node exists, stopped first in `releaseRuntime`, so a hibernating strand dials no
222
+ * upgrade and a resume judges the new node's connections with no backoff carried over.
223
+ */
224
+ this.webrtcUpgrades = new Map();
215
225
  /**
216
226
  * The party's other machines known to hold each strand (`strand-party-machines.ts`), keyed
217
227
  * by strand id, on a node offering offline mode for a launch with a party-machine seam. Same
@@ -267,10 +277,19 @@ export class StrandInstanceManager {
267
277
  this.transitions = new Map();
268
278
  /**
269
279
  * The pending database retry per strand id of a launch whose database could not be built
270
- * because no seed peer had answered yet ({@link deferUnreachableJoin}). Cleared by
280
+ * because no machine that can answer for the strand's blocks was reachable yet
281
+ * ({@link deferUnreachableJoin}). Cleared by
271
282
  * {@link releaseRuntime}, so a stop or a quiesce cancels it.
272
283
  */
273
284
  this.unreachableJoinRetries = new Map();
285
+ /**
286
+ * Per strand id, the sApp claim ({@link attachSApp}) whose schema the retained launch config
287
+ * carries but no apply has landed yet: the claim found no live database, or its live apply failed
288
+ * for a reason that may pass. Lets a build that refuses that schema fall back to the replica
289
+ * ({@link revertRefusedAttach}). Deleted when a database applies the schema, by that fallback,
290
+ * and when {@link stopStrand} begins.
291
+ */
292
+ this.unappliedAttaches = new Map();
274
293
  /**
275
294
  * The offline mode set per strand id ({@link setOfflineMode}); a strand absent here runs in its
276
295
  * launch's `initialMode`. Never cleared: the mode belongs to the strand, not to one database, so
@@ -306,6 +325,10 @@ export class StrandInstanceManager {
306
325
  hasStrand(strandId) {
307
326
  return this.instances.has(strandId);
308
327
  }
328
+ /** The sApp config the tracked strand's next build applies (its retained launch config's), or `undefined` for a replica or an untracked strand. */
329
+ launchedSAppConfig(strandId) {
330
+ return this.launchConfigs.get(strandId)?.sAppConfig;
331
+ }
309
332
  /**
310
333
  * Start a new strand instance.
311
334
  *
@@ -355,10 +378,21 @@ export class StrandInstanceManager {
355
378
  // function is provided, it is called with the strandId to create strand-specific
356
379
  // storage (e.g. strand-isolated directories). A provider that throws therefore
357
380
  // fails the launch alongside the schema-signature check, leaving nothing tracked.
358
- const strandStorage = resolveStrandStorage(config.storage?.provider, strandId);
381
+ //
382
+ // Never on a client (`roles.strandCohortMember: false`, built so in `buildStrandRuntime`):
383
+ // it stores no blocks, and the provider call itself has a side effect — a per-strand
384
+ // database on a phone, a per-strand directory on a node — so it is not made. Nothing is
385
+ // recorded in `strandStorages`, and every reader of that map (the join catch-up, the
386
+ // first-join test, the storage dispose) already handles the absent store.
387
+ const strandStorage = config.roles.strandCohortMember
388
+ ? resolveStrandStorage(config.storage?.provider, strandId)
389
+ : undefined;
359
390
  if (strandStorage) {
360
391
  log('Strand %s using provided storage provider', strandId);
361
392
  }
393
+ else if (!config.roles.strandCohortMember) {
394
+ log('Strand %s runs as a client: no store is resolved, its blocks live on the serving machines', strandId);
395
+ }
362
396
  // Determine latency hint: sApp config > default
363
397
  const latencyHint = sAppConfig?.latencyHint ?? config.defaultLatencyHint;
364
398
  const instance = {
@@ -432,15 +466,15 @@ export class StrandInstanceManager {
432
466
  * Build (or rebuild) the libp2p node + StrandDatabase for an instance and
433
467
  * attach them, transitioning it to `active`. Shared by `startStrand` (fresh
434
468
  * launch) and `resumeStrand` (rehydrating a quiesced instance). Reads all
435
- * volatile inputs (bootstrapNodes, servingMachines, network, profile,
469
+ * volatile inputs (bootstrapNodes, servingMachines, network, roles,
436
470
  * privateKey, sApp config) from `config`, so the caller controls the
437
471
  * cohort-derived values. Storage is the
438
472
  * one input it does NOT re-read from `config`: that belongs to the instance and
439
473
  * comes from `strandStorages`.
440
474
  *
441
- * A database that cannot be built because no seed peer has answered yet does not fail the
442
- * build: the runtime comes up `'syncing'` without it and the database phase alone is
443
- * retried on the same node ({@link deferUnreachableJoin}).
475
+ * A database that cannot be built because no machine that can answer for the strand's blocks
476
+ * was reachable does not fail the build: the runtime comes up `'syncing'` without it and the
477
+ * database phase alone is retried on the same node ({@link deferUnreachableJoin}).
444
478
  */
445
479
  async buildStrandRuntime(instance, config) {
446
480
  const strandId = instance.strandId;
@@ -449,6 +483,12 @@ export class StrandInstanceManager {
449
483
  // (backfill disabled, no relay addrs), so a zero or NaN declaration would otherwise
450
484
  // surface later inside a path that logs and carries on. `link-budget.ts`.
451
485
  resolveLinkRoundTripMs(config.network?.linkRoundTripMs);
486
+ // Whether this strand node stores and signs the strand's blocks, or is a CLIENT that reads
487
+ // and writes through the machines that do (`NodeRoles.strandCohortMember`). The one place
488
+ // the role is turned into a node: everything below that differs on a client follows from
489
+ // this binding, and `startStrand` resolved no store for one, so `strandStorage` is undefined
490
+ // there and `backfillArms` is false with it.
491
+ const servesBlocks = config.roles.strandCohortMember;
452
492
  // The store the instance OWNS (resolved once in `startStrand`), not a fresh
453
493
  // resolution: a rebuild must reach the same backend through the same warm cache.
454
494
  const strandStorage = this.strandStorages.get(strandId);
@@ -464,7 +504,7 @@ export class StrandInstanceManager {
464
504
  const protocolPrefix = `/optimystic/${networkName}`;
465
505
  // Whether this node runs the circuit-relay server, and its init — the same
466
506
  // resolution the control node takes from the same config (`relay-server.ts`).
467
- const relayServer = resolveRelayServer(config.network, config.profile);
507
+ const relayServer = resolveRelayServer(config.network, config.roles);
468
508
  // The strand-node VIEW of the machine's one `NetworkConfig`, not the control
469
509
  // node's resolution: fixed direct listen ports become ephemeral (two nodes cannot
470
510
  // bind one port), the announce config is dropped (it names the control node's
@@ -476,8 +516,10 @@ export class StrandInstanceManager {
476
516
  // `strand-network-config.ts` for all three, and `relay-reservation.ts`.
477
517
  //
478
518
  // `relayAddrs` is destructured OFF: it is not a `createLibp2pNode` option, and
479
- // spreading it would hand db-p2p a key it does not know.
480
- const { relayAddrs: relayDialAddrs = [], ...addrOptions } = strandNodeAddrs(config.network);
519
+ // spreading it would hand db-p2p a key it does not know. `listenTransports` is split out
520
+ // for the same reason — `wsPort` is db-p2p's switch but the WebRTC ICE servers beside it
521
+ // are read only by `network.defaultTransports` (`listenTransportNodeOptions` drops them).
522
+ const { relayAddrs: relayDialAddrs = [], listenAddrs, ...listenTransports } = strandNodeAddrs(config.network);
481
523
  // Bound once, before anything is built — so, like the round-trip check above, a
482
524
  // rejected clusterSize fails the build with nothing to release. The breadth is also
483
525
  // the ceiling on the repair yardstick and the revocation enforcer's wide-strand
@@ -533,9 +575,9 @@ export class StrandInstanceManager {
533
575
  : config.network?.connectionGater
534
576
  ? { connectionGater: config.network.connectionGater }
535
577
  : {};
536
- const reactivityOption = strandCohortTopicOption(config.reactivity, strandId);
578
+ const reactivityOption = strandCohortTopicOption(config.reactivity, strandId, config.roles.reactivity);
537
579
  if (reactivityOption.cohortTopic) {
538
- log('strand %s: change notifications on', strandId);
580
+ log('strand %s: change notifications on, as %s', strandId, config.roles.reactivity);
539
581
  }
540
582
  // The party's other machines holding this strand, for the offline queue's gate, each commit's
541
583
  // durability record and the redial loop below (`strand-party-machines.ts`). Only a node offering offline mode pays
@@ -567,8 +609,16 @@ export class StrandInstanceManager {
567
609
  // sibling recorded is never read as removed. If a peer is ever seen left out of cohorts
568
610
  // this way, the row needs a proof that the id it states is the machine's own.
569
611
  ...(partyMachines && { isNetworkMember: (peerId) => !partyMachines.removed().has(peerId) }),
612
+ // A client registers none of the four storage protocol services, so every other machine
613
+ // classifies it from its identify list as not serving and leaves it out of every cohort,
614
+ // its own view of itself included; its reads and writes go to a coordinator among the
615
+ // strand's serving machines (`../optimystic/docs/internals.md` → "Client nodes"). The
616
+ // serving-only options Optimystic would ignore on a client stay off it below: `storage`
617
+ // is undefined here on a client (`startStrand`), `arachnode` is behind this flag, and
618
+ // `rebalance` is behind `backfillArms`, which the absent store already made false.
619
+ servesBlocks,
570
620
  storage: strandStorage,
571
- fretProfile: config.profile === 'storage' ? 'core' : 'edge',
621
+ fretProfile: config.roles.overlayTier,
572
622
  relay: relayServer.enabled,
573
623
  // NOTE: unlike the control node, a strand node has no unauthorized-reservation budget,
574
624
  // so with the per-connection cap off any peer that reaches this node can hold one of
@@ -593,10 +643,15 @@ export class StrandInstanceManager {
593
643
  servingMachines: config.servingMachines,
594
644
  cohortQueryTimeoutMs: declaredCohortReadDeadlineMs(config.network)
595
645
  }),
596
- arachnode: {
597
- enableRingZulu: config.profile === 'storage'
598
- },
599
- // One join catch-up per node. On a storage-profile node Optimystic's rebalance growth
646
+ // A client builds no Arachnode at all, so the option is not stated for one.
647
+ ...(servesBlocks && {
648
+ arachnode: {
649
+ // Follows `alwaysOn`, for the control node's reason (`cadre-node.ts`): the storage
650
+ // rings Ring Zulu hints at are unimplemented, so there is no second role to set.
651
+ enableRingZulu: config.roles.alwaysOn
652
+ }
653
+ }),
654
+ // One join catch-up per node. On an always-on node Optimystic's rebalance growth
600
655
  // arm pushes a joiner every block whose cohort it entered, one request per block, and
601
656
  // it never hears of the peer-join catch-up's pushes, so each block would go twice. The
602
657
  // catch-up pushes every block to every peer it serves, the growth arm's targets
@@ -629,7 +684,7 @@ export class StrandInstanceManager {
629
684
  // that fills the bare `/p2p-circuit` slots: otherwise a cohort seed running the relay
630
685
  // server takes one as soon as it connects (`relay-reservation.ts`, "WHY LIBP2P'S
631
686
  // RELAY DISCOVERY IS SWITCHED OFF").
632
- ...nodeTransportsOption(config.network, addrOptions, relayDialAddrs.length > 0),
687
+ ...nodeTransportsOption(config.network, listenTransports, relayDialAddrs.length > 0),
633
688
  ...(config.network?.noiseCrypto && { noiseCrypto: config.network.noiseCrypto }),
634
689
  // Unconditional, and the same default the control node takes: every node of
635
690
  // every party runs the monitor over its connection to a slow phone, so the
@@ -651,7 +706,8 @@ export class StrandInstanceManager {
651
706
  // supervisor below fills. That is what gives a NAT'd strand node a reachable relay
652
707
  // slot — and works against a party-run relay because the launch path announced
653
708
  // this strand's derived peerId to it first (delegate admission; see cadre-node.ts).
654
- ...addrOptions,
709
+ ...(listenAddrs && { listenAddrs }),
710
+ ...listenTransportNodeOptions(listenTransports),
655
711
  // The raw configured gater (open strands), or the revocation-composed
656
712
  // gater plus the fail-closed per-stream revoked-peer gate (closed
657
713
  // strands) — resolved above, before the try.
@@ -665,7 +721,14 @@ export class StrandInstanceManager {
665
721
  // database (`StrandPeer`): a background write that never fails or delays the launch.
666
722
  // The seam defers it while a write could fork the party and retries it on cohort
667
723
  // growth and from every membership reconciler pass, so a refusal here is not final.
668
- // Written for open strands too: their row is what a sibling's offline queue waits for.
724
+ //
725
+ // Written by EVERY machine, client or serving, and for an open strand as well as a closed
726
+ // one: in a closed strand the row is how a sibling and the party key replacement bind this
727
+ // machine, which a client needs as much as a server, and an open strand's row is what a
728
+ // sibling's offline queue waits for (docs/strands/membership.md → "Binding the party's
729
+ // machines"). Whether this machine serves is the row's role column, which
730
+ // `CadreNode.publishStrandPeer` fills from the node's own role; the one reader that must
731
+ // skip a client filters on it (`strand-party-machines.ts`).
669
732
  if (config.partyPeers) {
670
733
  void config.partyPeers.publishOwn(node.peerId.toString()).catch((error) => {
671
734
  log('Strand %s: publishing this machine\'s StrandPeer row threw (retried later): %o', strandId, error);
@@ -698,6 +761,18 @@ export class StrandInstanceManager {
698
761
  }),
699
762
  ...(partyMachines && { partyMachines: () => partyMachines.machines().map((machine) => machine.strandPeerId) })
700
763
  }, strandRedialTimings(config.network?.linkRoundTripMs)));
764
+ // Try a direct WebRTC connection in the background for each member this node ends up
765
+ // reaching through a relay, which on a strand is the normal case: a strand's peers are
766
+ // other parties' machines, so both sides are often behind NAT. Armed here rather than
767
+ // after the database phase, so a direct path can be in place by the time the first sync's
768
+ // reads run. Inert unless the embedder passed a WebRTC transport (`webrtc-upgrade.ts`).
769
+ const webrtcUpgrade = new WebrtcUpgradeService({
770
+ label: strandId,
771
+ node,
772
+ dialTimeoutMs: webrtcUpgradeDialBudgetMs(config.network?.linkRoundTripMs)
773
+ });
774
+ this.webrtcUpgrades.set(strandId, webrtcUpgrade);
775
+ webrtcUpgrade.start();
701
776
  const databaseBuild = await this.buildStrandDatabase(instance, config, node);
702
777
  if (!this.isCurrentRuntime(instance, node)) {
703
778
  // A stop released this runtime during the database phase (`stopStrand` does not
@@ -733,6 +808,9 @@ export class StrandInstanceManager {
733
808
  // peer-join-backfill.ts for the strand-side argument (and why the control
734
809
  // network, which DOES gate, is different).
735
810
  //
811
+ // Never on a client: it holds no blocks to push, and `startStrand` resolved it no store,
812
+ // which is what `backfillArms` reads.
813
+ //
736
814
  // NOTE: cost is one PeerJoinBackfill object + one `peer:identify` listener
737
815
  // per running strand — linear in strand count, negligible at the handful a
738
816
  // device or host runs today. If a node ever hosts strands by the hundred,
@@ -783,7 +861,7 @@ export class StrandInstanceManager {
783
861
  // No `lastActivity` stamp: bringing a runtime up is not activity. A check-in marks
784
862
  // activity before its resume and must see only what landed while the strand was up.
785
863
  instance.status = liveStrandStatus(instance);
786
- if (databaseBuild === 'awaiting-seed') {
864
+ if (databaseBuild === 'awaiting-peer') {
787
865
  // Armed only now that the build is over: a retry firing mid-build would find the
788
866
  // build in flight.
789
867
  this.deferUnreachableJoin(instance);
@@ -810,10 +888,13 @@ export class StrandInstanceManager {
810
888
  * {@link buildStrandRuntime} and again by each {@link retryUnreachableJoin}, with a new
811
889
  * StrandDatabase per attempt.
812
890
  *
813
- * Returns `'awaiting-seed'` when initialize failed only because no seed peer has answered
814
- * (`cohort-unreachable`): that attempt's database is closed and the node keeps running. Any
815
- * other failure throws, with the attempt's database left with its gate for
891
+ * Returns `'awaiting-peer'` when initialize failed only because no machine that can answer for
892
+ * the strand's blocks was reachable: that attempt's database is closed and the node keeps
893
+ * running. Any other failure throws, with the attempt's database left with its gate for
816
894
  * {@link releaseRuntime} to close.
895
+ *
896
+ * A client node's database (`roles.strandCohortMember: false`) is published as soon as it
897
+ * initializes, like a founder's: see the first-sync decision below.
817
898
  */
818
899
  async buildStrandDatabase(instance, config, node) {
819
900
  const strandId = instance.strandId;
@@ -827,6 +908,7 @@ export class StrandInstanceManager {
827
908
  strandId,
828
909
  sAppConfig: config.sAppConfig,
829
910
  libp2pNode: node,
911
+ // Absent on a client, which coordinates no writes; the database then connects without one.
830
912
  coordinatedRepo: node.coordinatedRepo,
831
913
  // Founder bootstrap inputs: the strand's type drives which membership rows
832
914
  // are written, and the PARTY's own key (partyMemberPrivateKey, resolved by the
@@ -867,13 +949,19 @@ export class StrandInstanceManager {
867
949
  await strandDb.initialize();
868
950
  }
869
951
  catch (error) {
870
- if (!isCohortUnreachableRead(error)) {
952
+ // The two shapes of "nobody who can answer for this strand's blocks is reachable yet": a
953
+ // cohort member that could not be asked (a joining replica whose seed is silent, a founder
954
+ // whose cohort is), and no coordinator resolvable at all (a client, whose own cohort is
955
+ // empty by construction, so every block falls through to `findCoordinator`). Any other
956
+ // failure — a schema that cannot apply here, a refused signature — fails the launch, which
957
+ // is what matching one error class by type each buys over reading the message.
958
+ if (!isCohortUnreachableRead(error) && !isNoCoordinatorResolved(error)) {
871
959
  throw error;
872
960
  }
873
961
  await this.discardDatabaseAttempt(strandId, gate);
874
- log('Strand %s: no seed peer has answered yet, so this joiner cannot build its database (%s); ' +
875
- 'its runtime stays up and the build is retried every %dms', strandId, describeThrown(error), UNREACHABLE_JOIN_RETRY_MS);
876
- return 'awaiting-seed';
962
+ log('Strand %s: no machine that can answer for this strand is reachable yet, so this launch ' +
963
+ 'cannot build its database (%s); its runtime stays up and the build is retried every %dms', strandId, describeThrown(error), UNREACHABLE_JOIN_RETRY_MS);
964
+ return 'awaiting-peer';
877
965
  }
878
966
  timing('[buildStrandRuntime:%s] strandDatabase.initialize: %dms', strandId, Math.round(performance.now() - t0));
879
967
  if (this.firstSyncGates.get(strandId) !== gate) {
@@ -882,6 +970,7 @@ export class StrandInstanceManager {
882
970
  await strandDb.close();
883
971
  return 'released';
884
972
  }
973
+ this.forgetAppliedAttach(strandId, config.sAppConfig, strandDb);
885
974
  // The first-sync write gate. A founder just wrote the Header in its bootstrap; any
886
975
  // other machine may commit only once it holds the Header — which it can only have
887
976
  // received from a peer (now, or on an earlier run over the same store) — and has read
@@ -903,7 +992,18 @@ export class StrandInstanceManager {
903
992
  if (awaitPush) {
904
993
  log('Strand %s: first join over an empty store; waiting for a member\'s push before the first sync probe', strandId);
905
994
  }
906
- const synced = config.founder === true || (!awaitPush && await gate.probeOnce());
995
+ // A client is treated as synced, like a founder. The gate stops a joining machine inventing a
996
+ // collection while it is the whole cohort for every block; a client is in no cohort, so a
997
+ // write with no serving machine reachable resolves no coordinator and fails instead of
998
+ // committing locally — there is no fork to prevent. Gating it would also be wrong in itself:
999
+ // its probe reads would be remote reads repeated on the backstop (it has no storage change
1000
+ // feed to wake it), and while the database was withheld the app could neither write nor
1001
+ // queue. So on a client `addStrand` resolving means the database is open, not that a member
1002
+ // has been reached: the first read or write fails, retryably, until a serving machine is
1003
+ // reachable (docs/strands/formation.md → "Joining: no writes before the first sync"). The
1004
+ // gate object stays as the handle `releaseRuntime` closes the database through.
1005
+ const client = !config.roles.strandCohortMember;
1006
+ const synced = config.founder === true || client || (!awaitPush && await gate.probeOnce());
907
1007
  timing('[buildStrandRuntime:%s] first-sync probe: %dms', strandId, Math.round(performance.now() - t0));
908
1008
  if (this.firstSyncGates.get(strandId) !== gate) {
909
1009
  // A stop released the runtime during the probe and closed this database through its gate.
@@ -967,9 +1067,10 @@ export class StrandInstanceManager {
967
1067
  watchRemovedMachinesInSeed(machines, seedPeers, announced, () => onRemovedMachineInSeed(strandId), strandId);
968
1068
  }
969
1069
  /**
970
- * The party's other machines known to hold `strandId` with no open connection from its strand
1070
+ * The party's other machines known to STORE `strandId` ({@link StrandPartyMachines.machines},
1071
+ * clients already dropped) with no open connection from its strand
971
1072
  * node: what an offline queue reporting `waitingFor: 'cohort'` may be waiting for
972
- * (`docs/strands.md` → "Waiting for the party's own machines"). Empty for a strand not tracked
1073
+ * (`docs/strands/writes.md` → "Waiting for the party's own machines"). Empty for a strand not tracked
973
1074
  * or not running here, and on a launch that tracks no party machines.
974
1075
  */
975
1076
  unreachedPartyMachines(strandId) {
@@ -1011,22 +1112,31 @@ export class StrandInstanceManager {
1011
1112
  await gate.database.close();
1012
1113
  }
1013
1114
  /**
1014
- * Keep a launch `'syncing'` when its database could not be built because no seed peer has
1015
- * answered yet, and retry the database build every {@link UNREACHABLE_JOIN_RETRY_MS} on the
1016
- * runtime already up.
1115
+ * Keep a launch `'syncing'` when its database could not be built because no machine that can
1116
+ * answer for the strand's blocks was reachable, and retry the database build every
1117
+ * {@link UNREACHABLE_JOIN_RETRY_MS} on the runtime already up. Which launches reach here and
1118
+ * why waiting beats refusing: `docs/strands/lifecycle.md` → "A launch with nobody to answer
1119
+ * waits". What makes each of them unable to build:
1017
1120
  *
1018
- * Optimystic (since 1.11.0) will not rule a block never-created while any of a node's
1019
- * `bootstrapNodes` is unheard, so a joiner alone with an unreachable seed cannot build even
1020
- * the schema catalog: `strandDb.initialize()` fails with `cohort-unreachable`. A founder
1021
- * given a seed is refused the same way (normally it has none: no sibling runs the strand yet). Refusing is
1022
- * right (building it alone would fork the catalog), but failing the launch would drop the
1023
- * strand until the watcher relaunched it, and `addStrand` would reject with a raw Optimystic
1024
- * error. Deferring gives a joiner the same contract the first-sync gate gives one that did
1121
+ * - **A joining storage replica whose seed is silent.** Optimystic (since 1.11.0) will not rule
1122
+ * a block never-created while any of a node's `bootstrapNodes` is unheard, so a joiner alone
1123
+ * with an unreachable seed cannot build even the schema catalog: `strandDb.initialize()` fails
1124
+ * `cohort-unreachable`.
1125
+ * - **A founder whose cohort is unreachable.** Its membership writes run inside `initialize()`
1126
+ * and fail the same way. Normally a founder has no seed (no sibling runs the strand yet) and
1127
+ * commits alone, so this is the founder given one.
1128
+ * - **A client** (`roles.strandCohortMember: false`) with no serving machine reachable. Its own
1129
+ * cohort is empty by construction, so every block its launch touches falls through to
1130
+ * `findCoordinator`, which resolves nobody at all: the schema catalog it opens first, and a
1131
+ * client founder's membership writes. A node that serves no storage never coordinates a key,
1132
+ * however isolated it is, so founding alone is not open to it either.
1133
+ *
1134
+ * Deferring gives every one of them the contract the first-sync gate gives a joiner that did
1025
1135
  * build: the strand stays tracked, {@link whenWritable} waits and rejects with the retryable
1026
- * `StrandAwaitingFirstSyncError`, and the launch proceeds once a seed peer answers.
1136
+ * `StrandAwaitingFirstSyncError`, and the launch proceeds once a machine answers.
1027
1137
  *
1028
- * The libp2p node, its connections and the background loops stay up meanwhile. A seed peer
1029
- * can answer just after the schema read gave up on it — on a slow link it connects and its
1138
+ * The libp2p node, its connections and the background loops stay up meanwhile. A peer can
1139
+ * answer just after the schema read gave up on it — on a slow link it connects and its
1030
1140
  * peer-join backfill delivers the whole store — and the retry then builds the database, and
1031
1141
  * runs the first-sync probe, while that peer is still connected.
1032
1142
  */
@@ -1043,13 +1153,15 @@ export class StrandInstanceManager {
1043
1153
  * One retry scheduled by {@link deferUnreachableJoin}: the database phase again, on the
1044
1154
  * runtime still attached. Skipped when the strand was stopped or released since — a quiesce
1045
1155
  * releases it and the resume after rebuilds the whole runtime — or already has a database.
1046
- * A failure other than an unanswered seed releases the runtime and marks the strand
1047
- * `'error'`, as a failed resume does.
1156
+ * A failure other than an unreachable machine releases the runtime and marks the strand
1157
+ * `'error'`, as a failed resume does, unless it is a refusal of a claim's schema the replica
1158
+ * can fall back from ({@link buildJoinDatabaseOrReplica}).
1048
1159
  */
1049
1160
  async retryUnreachableJoin(instance) {
1050
1161
  const strandId = instance.strandId;
1051
1162
  const config = this.launchConfigs.get(strandId);
1052
- // Every strand node is built by `buildStrandRuntime`, as a node with its coordinated repo.
1163
+ // Every strand node is built by `buildStrandRuntime`, as a node carrying db-p2p's attachments
1164
+ // (a client's without a coordinated repo).
1053
1165
  const node = instance.libp2pNode;
1054
1166
  if (!config || !node || !this.isCurrentRuntime(instance, node) || instance.database
1055
1167
  || this.firstSyncGates.has(strandId) || this.isQuiescing(strandId)) {
@@ -1059,7 +1171,7 @@ export class StrandInstanceManager {
1059
1171
  try {
1060
1172
  // Tracked like any runtime build, so a wake, a quiesce or an sApp attach waits for it
1061
1173
  // rather than acting on a database that is still initializing.
1062
- build = await this.trackRuntimeBuild(strandId, this.buildStrandDatabase(instance, config, node));
1174
+ build = await this.trackRuntimeBuild(strandId, this.buildJoinDatabaseOrReplica(instance, config, node));
1063
1175
  }
1064
1176
  catch (error) {
1065
1177
  if (!this.isCurrentRuntime(instance, node)) {
@@ -1071,13 +1183,42 @@ export class StrandInstanceManager {
1071
1183
  });
1072
1184
  instance.status = 'error';
1073
1185
  instance.error = describeThrown(error);
1074
- log('Strand %s: building the database of a joiner that was waiting for a seed peer failed: %s', strandId, instance.error);
1186
+ log('Strand %s: building the database of a launch that was waiting for a reachable machine failed: %s', strandId, instance.error);
1075
1187
  return;
1076
1188
  }
1077
- if (build === 'awaiting-seed' && this.isCurrentRuntime(instance, node) && !this.isQuiescing(strandId)) {
1189
+ if (build === 'awaiting-peer' && this.isCurrentRuntime(instance, node) && !this.isQuiescing(strandId)) {
1078
1190
  this.deferUnreachableJoin(instance);
1079
1191
  }
1080
1192
  }
1193
+ /**
1194
+ * A deferred join's database phase ({@link buildStrandDatabase}), run once more as the replica
1195
+ * when it fails on the schema of a claim that has not applied yet ({@link revertRefusedAttach}).
1196
+ * The failed attempt's database is closed first: a failure leaves it registered with its gate.
1197
+ * `'released'` when a stop began while it closed.
1198
+ */
1199
+ async buildJoinDatabaseOrReplica(instance, config, node) {
1200
+ try {
1201
+ return await this.buildStrandDatabase(instance, config, node);
1202
+ }
1203
+ catch (error) {
1204
+ const replicaConfig = this.isCurrentRuntime(instance, node)
1205
+ ? this.revertRefusedAttach(instance, config.sAppConfig, error)
1206
+ : undefined;
1207
+ if (!replicaConfig) {
1208
+ throw error;
1209
+ }
1210
+ const failedAttempt = this.firstSyncGates.get(instance.strandId);
1211
+ if (failedAttempt) {
1212
+ await this.discardDatabaseAttempt(instance.strandId, failedAttempt);
1213
+ }
1214
+ if (!this.isCurrentRuntime(instance, node) || instance.status === 'stopping') {
1215
+ // A stop that began while the failed attempt closed found no gate to release, so a
1216
+ // database built now would outlive the stop, open and unreleased.
1217
+ return 'released';
1218
+ }
1219
+ return await this.buildStrandDatabase(instance, replicaConfig, node);
1220
+ }
1221
+ }
1081
1222
  /** Whether `instance` is still tracked, with `node` still its runtime's libp2p node. */
1082
1223
  isCurrentRuntime(instance, node) {
1083
1224
  return !this.stopping && this.instances.get(instance.strandId) === instance && instance.libp2pNode === node;
@@ -1112,6 +1253,10 @@ export class StrandInstanceManager {
1112
1253
  }
1113
1254
  this.peerRedials.get(instance.strandId)?.stop();
1114
1255
  this.peerRedials.delete(instance.strandId);
1256
+ // The WebRTC upgrade service before the node it dials on: its stop() also aborts the attempt
1257
+ // in flight, so a hibernating strand holds no ICE negotiation open.
1258
+ this.webrtcUpgrades.get(instance.strandId)?.stop();
1259
+ this.webrtcUpgrades.delete(instance.strandId);
1115
1260
  // The party-machine tracker with the loop and gate that read it; a resume reads afresh.
1116
1261
  this.partyMachines.get(instance.strandId)?.stop();
1117
1262
  this.partyMachines.delete(instance.strandId);
@@ -1596,7 +1741,7 @@ export class StrandInstanceManager {
1596
1741
  this.launchConfigs.set(strandId, resumeConfig);
1597
1742
  instance.status = 'starting';
1598
1743
  try {
1599
- await this.trackRuntimeBuild(strandId, this.buildStrandRuntime(instance, resumeConfig));
1744
+ await this.trackRuntimeBuild(strandId, this.buildRuntimeOrReplica(instance, resumeConfig));
1600
1745
  timing('[resumeStrand:%s] total: %dms', strandId, Math.round(performance.now() - tTotal));
1601
1746
  log('Strand %s resumed successfully', strandId);
1602
1747
  return instance;
@@ -1608,6 +1753,60 @@ export class StrandInstanceManager {
1608
1753
  throw error;
1609
1754
  }
1610
1755
  }
1756
+ /**
1757
+ * {@link buildStrandRuntime}, run once more as the replica when it fails on the schema of a
1758
+ * claim that has not applied yet ({@link revertRefusedAttach}). Safe to run twice: a failed
1759
+ * build releases both handles before it rejects.
1760
+ */
1761
+ async buildRuntimeOrReplica(instance, config) {
1762
+ try {
1763
+ await this.buildStrandRuntime(instance, config);
1764
+ }
1765
+ catch (error) {
1766
+ const replicaConfig = this.revertRefusedAttach(instance, config.sAppConfig, error);
1767
+ if (!replicaConfig) {
1768
+ throw error;
1769
+ }
1770
+ await this.buildStrandRuntime(instance, replicaConfig);
1771
+ }
1772
+ }
1773
+ /**
1774
+ * Undo a claim of a storage replica ({@link attachSApp}) after an apply of its schema was refused
1775
+ * (`AppSchemaRefusedError`): the retained launch config drops the sApp, so later rebuilds run the
1776
+ * replica, and the instance gets back the replica's unset `sAppInfo` and its latency hint. Only
1777
+ * when `error` is such a refusal, `refused` is the claim the strand has not applied yet, and the
1778
+ * retained config still carries it, so a config rewritten since is left alone.
1779
+ *
1780
+ * @returns the replica's launch config, or `undefined` when nothing was undone.
1781
+ */
1782
+ revertRefusedAttach(instance, refused, error) {
1783
+ const strandId = instance.strandId;
1784
+ const unapplied = this.unappliedAttaches.get(strandId);
1785
+ const config = this.launchConfigs.get(strandId);
1786
+ const refusal = appSchemaRefusalOf(error);
1787
+ if (!refusal || !unapplied || !config || this.stopping || this.instances.get(strandId) !== instance
1788
+ || refused !== unapplied.sAppConfig || config.sAppConfig !== refused) {
1789
+ return undefined;
1790
+ }
1791
+ this.unappliedAttaches.delete(strandId);
1792
+ const { sAppConfig: _refused, ...replicaConfig } = config;
1793
+ this.launchConfigs.set(strandId, replicaConfig);
1794
+ instance.sAppInfo = undefined;
1795
+ instance.latencyHint = unapplied.latencyHint;
1796
+ log('Strand %s: the schema of sApp %s, which claimed this storage replica, was refused here; ' +
1797
+ 'the strand runs as a replica again: %s', strandId, refused.id, refusal.message);
1798
+ return replicaConfig;
1799
+ }
1800
+ /**
1801
+ * Forget the unapplied claim of `strandId` once `database`, given the claim's sApp config as
1802
+ * `applied`, has applied its schema. An apply still deferred keeps it, since its retry can still be
1803
+ * refused by the strand's rows.
1804
+ */
1805
+ forgetAppliedAttach(strandId, applied, database) {
1806
+ if (applied && this.unappliedAttaches.get(strandId)?.sAppConfig === applied && database.appSchemaState() === 'applied') {
1807
+ this.unappliedAttaches.delete(strandId);
1808
+ }
1809
+ }
1611
1810
  /**
1612
1811
  * Honor a founder request against an ALREADY-TRACKED strand — the seam that
1613
1812
  * closes the "whoever launches first decides whether the bootstrap runs" gap:
@@ -1676,19 +1875,24 @@ export class StrandInstanceManager {
1676
1875
  *
1677
1876
  * A runtime build in flight (the replica's launch, or a hibernation wake) is waited out
1678
1877
  * first, so the attach acts on the database that build produced. Then, in order: the
1679
- * schema signature is checked before anything changes; the retained launch config takes
1680
- * the sApp, so every later rebuild applies it through `composeStrand`; the live database —
1681
- * published, or still held by the first-sync gate — gets the schema; and only then does
1682
- * the instance record `sAppInfo` and the sApp's latency hint. An instance with no live
1683
- * database gets the config alone: a quiesced one applies the schema at its next resume, a
1684
- * launch waiting for a seed peer at its next database retry.
1878
+ * schema signature, and the refusals the schema's text alone decides (`checkAppSchema`: a
1879
+ * `seed` item, an item the parser skipped, a syntax error), are checked before anything
1880
+ * changes; the retained launch config takes the sApp, so every later rebuild applies it
1881
+ * through `composeStrand`; the live database — published, or still held by the first-sync
1882
+ * gate — gets the schema; and only then does the instance record `sAppInfo` and the sApp's
1883
+ * latency hint. An instance with no live database gets the config alone: a quiesced one
1884
+ * applies the schema at its next resume, a launch waiting for a seed peer at its next
1885
+ * database retry, and that build falls back to the replica if the strand's tables and rows
1886
+ * refuse the schema ({@link revertRefusedAttach}).
1685
1887
  *
1686
1888
  * @returns `'already-attached'` when the instance already runs an sApp — a DIFFERENT one
1687
1889
  * is logged and left as it is, as a second claim of a claimed strand always has been —
1688
1890
  * else `'attached'`.
1689
1891
  * @throws when the strand is not tracked (a caller bug, or a launch that failed while
1690
- * this waited on it); when the schema signature is refused, having changed nothing; and
1691
- * whatever the live apply throws (e.g. a quiesce closed the database mid-apply) — the
1892
+ * this waited on it); when the schema signature or the schema's text is refused, having
1893
+ * changed nothing; `AppSchemaRefusedError` when the live apply refuses the schema against
1894
+ * the replica's tables and rows, having put the retained config back to the replica's; and
1895
+ * whatever else the live apply throws (e.g. a quiesce closed the database mid-apply) — the
1692
1896
  * retained config then still carries the sApp and `sAppInfo` stays unset, so the next
1693
1897
  * claim retries the apply.
1694
1898
  *
@@ -1699,26 +1903,35 @@ export class StrandInstanceManager {
1699
1903
  */
1700
1904
  async attachSApp(strandId, sAppConfig, options = {}) {
1701
1905
  await this.settleRuntimeBuilds(strandId);
1702
- const instance = this.instances.get(strandId);
1703
- const config = this.launchConfigs.get(strandId);
1704
- if (!instance || !config) {
1705
- throw new Error(`Cannot attach an sApp to strand ${strandId}: not tracked`);
1706
- }
1707
- if (instance.sAppInfo) {
1708
- if (instance.sAppInfo.id !== sAppConfig.id) {
1709
- log('attachSApp: strand %s already runs sApp %s — the claim for sApp %s is ignored', strandId, instance.sAppInfo.id, sAppConfig.id);
1710
- }
1906
+ if (this.claimTarget(strandId, sAppConfig) === 'already-attached') {
1711
1907
  return 'already-attached';
1712
1908
  }
1713
1909
  const sAppInfo = verifiedSAppInfo(strandId, sAppConfig, options.requireSignedSchemas);
1910
+ await checkAppSchema(sAppConfig);
1911
+ // The check yielded, so a wake or another claim may have started meanwhile: wait out its build
1912
+ // and read the instance and config again, or the config written below would drop what a
1913
+ // resume just retained (its fresh `bootstrapNodes`).
1914
+ await this.settleRuntimeBuilds(strandId);
1915
+ const target = this.claimTarget(strandId, sAppConfig);
1916
+ if (target === 'already-attached') {
1917
+ return target;
1918
+ }
1919
+ const { instance, config } = target;
1714
1920
  // A fresh object rather than mutating in place: startStrand retains the CALLER'S
1715
1921
  // config object, which is not ours to rewrite.
1716
1922
  this.launchConfigs.set(strandId, { ...config, sAppConfig });
1923
+ this.unappliedAttaches.set(strandId, { sAppConfig, latencyHint: instance.latencyHint });
1717
1924
  const database = instance.database ?? this.firstSyncGates.get(strandId)?.database;
1718
1925
  if (database) {
1719
- await database.attachAppSchema(sAppConfig);
1926
+ await this.applyClaimedSchema(instance, database, sAppConfig);
1720
1927
  }
1721
1928
  else {
1929
+ // NOTE: accepted gap — this claim resolves `'attached'` before any apply, so the app learns of
1930
+ // a refusal by the strand's rows only from the log and from `sAppInfo` going back to unset when
1931
+ // the build falls back to the replica; `CadreNode.sAppConfigs` keeps the claim, so a restart's
1932
+ // launch with it is refused and suppressed (`suppressIfAppSchemaRefused`). Failing the claim
1933
+ // instead would mean waking a quiesced replica to apply now, and would still not cover a
1934
+ // launch waiting for a seed peer.
1722
1935
  log('attachSApp: strand %s has no live database — its next build applies the sApp schema', strandId);
1723
1936
  }
1724
1937
  instance.sAppInfo = sAppInfo;
@@ -1731,11 +1944,49 @@ export class StrandInstanceManager {
1731
1944
  log('Strand %s upgraded from storage replica to %s', strandId, describeSApp(sAppConfig));
1732
1945
  return 'attached';
1733
1946
  }
1947
+ /**
1948
+ * The tracked instance and retained config an {@link attachSApp} claim acts on, or
1949
+ * `'already-attached'` when the instance already runs an sApp (a claim for a different one is
1950
+ * logged and ignored).
1951
+ *
1952
+ * @throws when the strand is not tracked.
1953
+ */
1954
+ claimTarget(strandId, sAppConfig) {
1955
+ const instance = this.instances.get(strandId);
1956
+ const config = this.launchConfigs.get(strandId);
1957
+ if (!instance || !config) {
1958
+ throw new Error(`Cannot attach an sApp to strand ${strandId}: not tracked`);
1959
+ }
1960
+ if (!instance.sAppInfo) {
1961
+ return { instance, config };
1962
+ }
1963
+ if (instance.sAppInfo.id !== sAppConfig.id) {
1964
+ log('attachSApp: strand %s already runs sApp %s — the claim for sApp %s is ignored', strandId, instance.sAppInfo.id, sAppConfig.id);
1965
+ }
1966
+ return 'already-attached';
1967
+ }
1968
+ /**
1969
+ * Apply a claim's schema to the replica's live database. A refusal by the replica's tables and
1970
+ * rows puts the retained config back to the replica's ({@link revertRefusedAttach}): the replica
1971
+ * holds no `App` schema, so the refused apply left nothing to drop. Any other failure leaves the
1972
+ * claim retained and unapplied, for the next claim or build to retry.
1973
+ */
1974
+ async applyClaimedSchema(instance, database, sAppConfig) {
1975
+ try {
1976
+ await database.attachAppSchema(sAppConfig);
1977
+ }
1978
+ catch (error) {
1979
+ this.revertRefusedAttach(instance, sAppConfig, error);
1980
+ throw error;
1981
+ }
1982
+ this.forgetAppliedAttach(instance.strandId, sAppConfig, database);
1983
+ }
1734
1984
  /**
1735
1985
  * Whether `strandId` is launched but still waiting for its first sync — a joiner whose
1736
1986
  * runtime is up while its database is withheld (status `'syncing'`, or `'idle'` after
1737
1987
  * the hibernation manager's idle timer fired on it), including one whose database build
1738
- * waits for a seed peer to answer ({@link deferUnreachableJoin}). `false` for a writable,
1988
+ * waits for a machine that can answer for the strand to be reachable
1989
+ * ({@link deferUnreachableJoin}). `false` for a writable,
1739
1990
  * quiesced, or untracked strand. The predicate {@link whenWritable}'s callers gate on.
1740
1991
  */
1741
1992
  isAwaitingFirstSync(strandId) {
@@ -1833,7 +2084,9 @@ export class StrandInstanceManager {
1833
2084
  // (see the build's end in `buildStrandRuntime`).
1834
2085
  instance.lastActivity = new Date();
1835
2086
  instance.status = 'active';
1836
- log('Strand %s is now writable: Strand.Header held', strandId);
2087
+ // No reason given here: the gate logs what its probe found when it opens, and a database
2088
+ // published by a deferred build held no Header at all — it had nobody to read one from.
2089
+ log('Strand %s is now writable', strandId);
1837
2090
  }
1838
2091
  const waiters = this.writableWaiters.get(strandId);
1839
2092
  if (waiters) {
@@ -1986,6 +2239,8 @@ export class StrandInstanceManager {
1986
2239
  }
1987
2240
  log('Stopping strand instance: %s', strandId);
1988
2241
  instance.status = 'stopping';
2242
+ // Before the release awaits, so a build failing meanwhile does not rebuild as the replica.
2243
+ this.unappliedAttaches.delete(strandId);
1989
2244
  this.rejectWritableWaiters(strandId, 'was stopped');
1990
2245
  try {
1991
2246
  await this.releaseRuntime(instance);