@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,144 +1,147 @@
1
- /**
2
- * An in-memory copy of one small control table's rows, kept until the table changes, so the
3
- * membership, owner, peer-record and admission-chain reads that every flow repeats cost nothing
4
- * after the first.
5
- * `ControlDatabase` keeps one per cached table and drops it from its table-change subscription
6
- * (`docs/architecture.md` → "Membership rows view"); this class holds only the caching rules, so
7
- * they are testable without a database.
8
- */
9
- /**
10
- * How long installed rows are served before the next read reloads them, change or no change.
11
- * The reload is the only path for a change that reaches this node with no storage event: a
12
- * machine outside the block's cohort (a cadre larger than its replication breadth), or one in
13
- * the cohort that the writer could not reach when it committed (one side of a NAT pair; the
14
- * cohort auto-connect scenarios). Longer than Optimystic's read-repair window
15
- * ({@link OPTIMYSTIC_READ_REPAIR_WINDOW_MS}), so the reload's storage read starts the cohort
16
- * consult that brings such a change in instead of being served from the local copy, and
17
- * shorter than any reconcile backstop (`DEFAULT_CONTROL_COHORT_RECONCILE_MS`, 2 minutes), so
18
- * the backstop pass, the only reader on an idle party, reloads rather than serving kept rows.
19
- * The reload rate on an idle party is therefore the pass rate, and the staleness bound for
20
- * such a change is the backstop, not this value.
21
- *
22
- * A machine that was offline when a sibling committed is covered sooner than either:
23
- * `CadreNode` drops every view when a sibling becomes reachable (its identify on a new
24
- * connection; `ControlDatabase.invalidateMembershipViews`), so the pass that starts then reads
25
- * storage.
26
- */
27
- export const MEMBERSHIP_VIEW_MAX_AGE_MS = 15_000;
28
-
29
- /**
30
- * Optimystic's lazy read-repair window (`clusterPolicy.readRepairWindowMs`, which cadre does
31
- * not set, so this is Optimystic's default): a read of a held block checked less than this
32
- * long ago is served from the local copy without asking the cohort. A read after it is
33
- * served locally too, but starts a cohort consult whose landing raises a table change.
34
- *
35
- * NOTE: a copy, since db-p2p exports no default for it. If cadre ever sets
36
- * `readRepairWindowMs` in its cluster policy, derive this from that value.
37
- */
38
- const OPTIMYSTIC_READ_REPAIR_WINDOW_MS = 10_000;
39
-
40
- /**
41
- * How long after a sibling becomes reachable (its identify on a new connection) `CadreNode`
42
- * drops the views a second time: one read-repair window, plus a second for timer slop. The
43
- * drop at the identify is not enough by itself. A node's reads before the sibling arrived
44
- * (its start pass, with no cohort to ask) stamp the window, so the reload the identify
45
- * starts is served from the local copy without a consult and the view would keep the
46
- * pre-connection rows until {@link MEMBERSHIP_VIEW_MAX_AGE_MS}. The reload past the window
47
- * starts the consults that bring in what the sibling committed while this node was away.
48
- */
49
- export const MEMBERSHIP_VIEW_RECONNECT_RELOAD_MS = OPTIMYSTIC_READ_REPAIR_WINDOW_MS + 1_000;
50
-
51
- /** One load's rows, and whether the view may keep them. */
52
- export interface MembershipViewLoad<Row> {
53
- rows: readonly Row[];
54
- /**
55
- * False when no later change event is guaranteed to reach the view for these rows (the
56
- * read that produced them did not arm the table's change bridge), so they serve only the
57
- * callers of this load.
58
- */
59
- installable: boolean;
60
- }
61
-
62
- /**
63
- * Reads the whole table. `retry` is the caller's: false from a caller holding the control
64
- * write lock, whose read must not sleep a retry backoff.
65
- */
66
- export type MembershipViewLoader<Row> = (retry: boolean) => Promise<MembershipViewLoad<Row>>;
67
-
68
- export interface MembershipViewOptions {
69
- /** Default {@link MEMBERSHIP_VIEW_MAX_AGE_MS}. */
70
- maxAgeMs?: number;
71
- /** Monotonic clock in milliseconds; default `performance.now`. */
72
- now?: () => number;
73
- }
74
-
75
- export class MembershipView<Row> {
76
- private rows: readonly Row[] | undefined;
77
- /** When the load that produced {@link rows} started: the rows are no older than this. */
78
- private loadedAt = 0;
79
- /** Bumped by every {@link invalidate}; a load installs only if it is unchanged since the load began. */
80
- private generation = 0;
81
- /**
82
- * The load each `retry` flag's callers share, current generation only. Separate per flag
83
- * so a caller under the write lock never awaits a retrying load's backoff sleep.
84
- */
85
- private readonly inFlight = new Map<boolean, Promise<readonly Row[]>>();
86
- private readonly maxAgeMs: number;
87
- private readonly now: () => number;
88
-
89
- constructor(private readonly loader: MembershipViewLoader<Row>, options: MembershipViewOptions = {}) {
90
- this.maxAgeMs = options.maxAgeMs ?? MEMBERSHIP_VIEW_MAX_AGE_MS;
91
- this.now = options.now ?? (() => performance.now());
92
- }
93
-
94
- /**
95
- * The table's rows: the installed copy while it is younger than the maximum age, otherwise a
96
- * load, shared with every caller of the same `retry` flag that arrives while it runs. A load
97
- * that raced an {@link invalidate} answers its own callers with what it read, as an uncached
98
- * read would have, and keeps nothing. A failed load keeps nothing and rejects.
99
- */
100
- read(retry: boolean): Promise<readonly Row[]> {
101
- if (this.rows !== undefined && this.now() - this.loadedAt < this.maxAgeMs) {
102
- return Promise.resolve(this.rows);
103
- }
104
- return this.inFlight.get(retry) ?? this.startLoad(retry);
105
- }
106
-
107
- /** Read the table without serving, joining or keeping anything. */
108
- async readThrough(retry: boolean): Promise<readonly Row[]> {
109
- return (await this.loader(retry)).rows;
110
- }
111
-
112
- /**
113
- * Drop the installed rows and every load in flight, so the next read loads afresh and no
114
- * earlier load installs. Synchronous and flag-setting only: the table-change handler calls
115
- * it inside the committing call.
116
- */
117
- invalidate(): void {
118
- this.generation++;
119
- this.rows = undefined;
120
- this.inFlight.clear();
121
- }
122
-
123
- private startLoad(retry: boolean): Promise<readonly Row[]> {
124
- const load = this.load(retry, this.generation, this.now());
125
- this.inFlight.set(retry, load);
126
- const forget = (): void => {
127
- if (this.inFlight.get(retry) === load) {
128
- this.inFlight.delete(retry);
129
- }
130
- };
131
- // Both arms handled, so a failed load rejects only for the callers awaiting it.
132
- void load.then(forget, forget);
133
- return load;
134
- }
135
-
136
- private async load(retry: boolean, generation: number, startedAt: number): Promise<readonly Row[]> {
137
- const { rows, installable } = await this.loader(retry);
138
- if (installable && generation === this.generation) {
139
- this.rows = rows;
140
- this.loadedAt = startedAt;
141
- }
142
- return rows;
143
- }
144
- }
1
+ /**
2
+ * An in-memory copy of one small control table's rows, kept until the table changes, so the
3
+ * membership, owner, peer-record and admission-chain reads that every flow repeats cost nothing
4
+ * after the first.
5
+ * `ControlDatabase` keeps one per cached table and drops it from its table-change subscription
6
+ * (`docs/cadre/control-convergence.md` → "Membership rows view"); this class holds only the
7
+ * caching rules, so they are testable without a database.
8
+ */
9
+ /**
10
+ * How long installed rows are served before the next read reloads them, change or no change.
11
+ * The reload is the only path for a change that reaches this node with no storage event: a
12
+ * machine outside the block's cohort (a cadre larger than its replication breadth), or one in
13
+ * the cohort that the writer could not reach when it committed (one side of a NAT pair; the
14
+ * cohort auto-connect scenarios). Longer than Optimystic's read-repair window
15
+ * ({@link OPTIMYSTIC_READ_REPAIR_WINDOW_MS}), so the reload's storage read starts the cohort
16
+ * consult that brings such a change in instead of being served from the local copy, and
17
+ * shorter than any reconcile backstop (`DEFAULT_CONTROL_COHORT_RECONCILE_MS`, 2 minutes), so
18
+ * the backstop pass, the only reader on an idle party, reloads rather than serving kept rows.
19
+ * The reload rate on an idle party is therefore the pass rate, and the staleness bound for
20
+ * such a change is the backstop, not this value.
21
+ *
22
+ * A machine that was offline when a sibling committed is covered sooner than either:
23
+ * `CadreNode` drops every view when a sibling becomes reachable (its identify on a new
24
+ * connection; `ControlDatabase.invalidateMembershipViews`), so the pass that starts then reads
25
+ * storage.
26
+ */
27
+ export const MEMBERSHIP_VIEW_MAX_AGE_MS = 15_000;
28
+
29
+ /**
30
+ * Optimystic's lazy read-repair window (`clusterPolicy.readRepairWindowMs`, which cadre does
31
+ * not set, so this is Optimystic's default): a read of a held block checked less than this
32
+ * long ago is served from the local copy without asking the cohort. A read after it is
33
+ * served locally too, but starts a cohort consult whose landing raises a table change, unless
34
+ * a cohort of two or three has stayed connected to this node since that block's last consult
35
+ * (Optimystic's quiet span). A sibling's new connection ends the span, so the reload below
36
+ * still consults.
37
+ *
38
+ * NOTE: a copy, since db-p2p exports no default for it. If cadre ever sets
39
+ * `readRepairWindowMs` in its cluster policy, derive this from that value.
40
+ */
41
+ const OPTIMYSTIC_READ_REPAIR_WINDOW_MS = 10_000;
42
+
43
+ /**
44
+ * How long after a sibling becomes reachable (its identify on a new connection) `CadreNode`
45
+ * drops the views a second time: one read-repair window, plus a second for timer slop. The
46
+ * drop at the identify is not enough by itself. A node's reads before the sibling arrived
47
+ * (its start pass, with no cohort to ask) stamp the window, so the reload the identify
48
+ * starts is served from the local copy without a consult and the view would keep the
49
+ * pre-connection rows until {@link MEMBERSHIP_VIEW_MAX_AGE_MS}. The reload past the window
50
+ * starts the consults that bring in what the sibling committed while this node was away.
51
+ */
52
+ export const MEMBERSHIP_VIEW_RECONNECT_RELOAD_MS = OPTIMYSTIC_READ_REPAIR_WINDOW_MS + 1_000;
53
+
54
+ /** One load's rows, and whether the view may keep them. */
55
+ export interface MembershipViewLoad<Row> {
56
+ rows: readonly Row[];
57
+ /**
58
+ * False when no later change event is guaranteed to reach the view for these rows (the
59
+ * read that produced them did not arm the table's change bridge), so they serve only the
60
+ * callers of this load.
61
+ */
62
+ installable: boolean;
63
+ }
64
+
65
+ /**
66
+ * Reads the whole table. `retry` is the caller's: false from a caller holding the control
67
+ * write lock, whose read must not sleep a retry backoff.
68
+ */
69
+ export type MembershipViewLoader<Row> = (retry: boolean) => Promise<MembershipViewLoad<Row>>;
70
+
71
+ export interface MembershipViewOptions {
72
+ /** Default {@link MEMBERSHIP_VIEW_MAX_AGE_MS}. */
73
+ maxAgeMs?: number;
74
+ /** Monotonic clock in milliseconds; default `performance.now`. */
75
+ now?: () => number;
76
+ }
77
+
78
+ export class MembershipView<Row> {
79
+ private rows: readonly Row[] | undefined;
80
+ /** When the load that produced {@link rows} started: the rows are no older than this. */
81
+ private loadedAt = 0;
82
+ /** Bumped by every {@link invalidate}; a load installs only if it is unchanged since the load began. */
83
+ private generation = 0;
84
+ /**
85
+ * The load each `retry` flag's callers share, current generation only. Separate per flag
86
+ * so a caller under the write lock never awaits a retrying load's backoff sleep.
87
+ */
88
+ private readonly inFlight = new Map<boolean, Promise<readonly Row[]>>();
89
+ private readonly maxAgeMs: number;
90
+ private readonly now: () => number;
91
+
92
+ constructor(private readonly loader: MembershipViewLoader<Row>, options: MembershipViewOptions = {}) {
93
+ this.maxAgeMs = options.maxAgeMs ?? MEMBERSHIP_VIEW_MAX_AGE_MS;
94
+ this.now = options.now ?? (() => performance.now());
95
+ }
96
+
97
+ /**
98
+ * The table's rows: the installed copy while it is younger than the maximum age, otherwise a
99
+ * load, shared with every caller of the same `retry` flag that arrives while it runs. A load
100
+ * that raced an {@link invalidate} answers its own callers with what it read, as an uncached
101
+ * read would have, and keeps nothing. A failed load keeps nothing and rejects.
102
+ */
103
+ read(retry: boolean): Promise<readonly Row[]> {
104
+ if (this.rows !== undefined && this.now() - this.loadedAt < this.maxAgeMs) {
105
+ return Promise.resolve(this.rows);
106
+ }
107
+ return this.inFlight.get(retry) ?? this.startLoad(retry);
108
+ }
109
+
110
+ /** Read the table without serving, joining or keeping anything. */
111
+ async readThrough(retry: boolean): Promise<readonly Row[]> {
112
+ return (await this.loader(retry)).rows;
113
+ }
114
+
115
+ /**
116
+ * Drop the installed rows and every load in flight, so the next read loads afresh and no
117
+ * earlier load installs. Synchronous and flag-setting only: the table-change handler calls
118
+ * it inside the committing call.
119
+ */
120
+ invalidate(): void {
121
+ this.generation++;
122
+ this.rows = undefined;
123
+ this.inFlight.clear();
124
+ }
125
+
126
+ private startLoad(retry: boolean): Promise<readonly Row[]> {
127
+ const load = this.load(retry, this.generation, this.now());
128
+ this.inFlight.set(retry, load);
129
+ const forget = (): void => {
130
+ if (this.inFlight.get(retry) === load) {
131
+ this.inFlight.delete(retry);
132
+ }
133
+ };
134
+ // Both arms handled, so a failed load rejects only for the callers awaiting it.
135
+ void load.then(forget, forget);
136
+ return load;
137
+ }
138
+
139
+ private async load(retry: boolean, generation: number, startedAt: number): Promise<readonly Row[]> {
140
+ const { rows, installable } = await this.loader(retry);
141
+ if (installable && generation === this.generation) {
142
+ this.rows = rows;
143
+ this.loadedAt = startedAt;
144
+ }
145
+ return rows;
146
+ }
147
+ }
@@ -9,8 +9,16 @@
9
9
  * carries no party id: the claim supplies it, and the node records it.
10
10
  *
11
11
  * The decoder lives here, beside the encoder, because the phone and the host both need
12
- * it and neither depends on the other. Imports only `@multiformats/multiaddr`,
13
- * `@libp2p/peer-id` and `uint8arrays`, so it loads on React Native and in the browser.
12
+ * it and neither depends on the other. Its own code is pure, and it imports only
13
+ * `@multiformats/multiaddr`, `@libp2p/peer-id` and `uint8arrays` — nothing platform-bound —
14
+ * so it loads on React Native and in the browser.
15
+ *
16
+ * The one exception is {@link addrKindOfComponents} from `peer-dial.ts`, taken rather than
17
+ * restated so that "does this address need ICE after its relay hop" has ONE answer in the
18
+ * package (`docs/network/relay.md` → "Direct connections over WebRTC" is the rule it serves).
19
+ * That import's own graph reaches `link-budget.ts` and therefore `@optimystic/db-p2p`, which is
20
+ * heavier than anything else here but is not platform-bound either, and this module is reachable
21
+ * only through the package index, which loads it regardless.
14
22
  */
15
23
  import { peerIdFromString } from '@libp2p/peer-id';
16
24
  import {
@@ -30,6 +38,7 @@ import {
30
38
  import { fromString as uint8ArrayFromString, toString as uint8ArrayToString } from 'uint8arrays';
31
39
  import { canonicalJson } from './canonical-json.js';
32
40
  import { parseClaimSecret } from './claim-proof.js';
41
+ import { addrKindOfComponents } from './peer-dial.js';
33
42
 
34
43
  /** Version 1 of the payload; the only one either side reads. */
35
44
  export const NODE_CLAIM_PAYLOAD_PREFIX = 'sereus-join:1.';
@@ -102,23 +111,25 @@ export interface NodeClaimAddressOptions {
102
111
  * unparsable ones are dropped, and so is plain TCP unless `includeTcp`.
103
112
  * - Public names (`/dns*`) come first: they work away from home. Public IP addresses are
104
113
  * kept only when there is no public name, since they reach the same machine.
105
- * - Private addresses follow, narrowed by {@link NodeClaimAddressOptions.lan}; relay
106
- * addresses last.
114
+ * - Private addresses follow, narrowed by {@link NodeClaimAddressOptions.lan}; then relay
115
+ * addresses, and last of all a relayed address that needs ICE after its hop (`webrtc`),
116
+ * which answers nothing for about 23 s when ICE cannot connect.
107
117
  *
108
- * Pure and dependency-light, like the codec beside it, so it loads on React Native too.
109
- * Finding the LAN address is the caller's (Node: `@serfab/cadre-core/primary-lan-address`).
118
+ * Pure, like the codec beside it, so it loads on React Native too. Finding the LAN address is
119
+ * the caller's (Node: `@serfab/cadre-core/primary-lan-address`).
110
120
  */
111
121
  export function selectNodeClaimAddresses(reported: readonly string[], peerId: string, options: NodeClaimAddressOptions = {}): string[] {
112
122
  const names: string[] = [];
113
123
  const publicIps: string[] = [];
114
124
  const privates: string[] = [];
115
125
  const relayed: string[] = [];
126
+ const webrtc: string[] = [];
116
127
  for (const raw of reported) {
117
128
  const classified = classifyClaimAddress(raw.trim(), peerId, options);
118
129
  if (!classified) continue;
119
- ({ name: names, public: publicIps, private: privates, relay: relayed })[classified.kind].push(classified.addr);
130
+ ({ name: names, public: publicIps, private: privates, relay: relayed, webrtc })[classified.kind].push(classified.addr);
120
131
  }
121
- return [...new Set([...names, ...(names.length > 0 ? [] : publicIps), ...privates, ...relayed])];
132
+ return [...new Set([...names, ...(names.length > 0 ? [] : publicIps), ...privates, ...relayed, ...webrtc])];
122
133
  }
123
134
 
124
135
  /**
@@ -133,10 +144,17 @@ export function withClaimDestination(addr: string, peerId: string): string {
133
144
  }
134
145
 
135
146
  /**
136
- * Where a phone could dial an address from: a relayed address (`/p2p-circuit`), a public name,
137
- * a public IP, a private (LAN, VPN, link-local) IP, or this machine's own loopback.
147
+ * Where a phone could dial an address from: a relayed address (`/p2p-circuit`), a relayed
148
+ * address carrying WebRTC signalling, a public name, a public IP, a private (LAN, VPN,
149
+ * link-local) IP, or this machine's own loopback.
150
+ *
151
+ * `webrtc` is not restricted to the phone's own network — the relay carries its signalling from
152
+ * anywhere — but the connection itself opens only if ICE finds a path between the two networks,
153
+ * and otherwise answers nothing for about 23 s. So it is kept apart from `relay`, and everything
154
+ * that ranks these kinds puts it below the plain relayed address published beside it: see
155
+ * `docs/network/relay.md` → "Direct connections over WebRTC".
138
156
  */
139
- export type DialAddressKind = 'relay' | 'name' | 'public' | 'private' | 'loopback';
157
+ export type DialAddressKind = 'relay' | 'webrtc' | 'name' | 'public' | 'private' | 'loopback';
140
158
 
141
159
  /**
142
160
  * Classify `addr` for a phone dialing it, or undefined when no phone can dial it at all: it
@@ -160,7 +178,11 @@ function componentsOf(addr: string): AddressComponents | undefined {
160
178
 
161
179
  /** {@link classifyDialAddress}, keeping the IP for a caller that narrows private addresses by it. */
162
180
  function classifyComponents(components: AddressComponents, includeTcp: boolean): { kind: DialAddressKind; ip?: string } | undefined {
163
- if (components.some((c) => c.code === CODE_P2P_CIRCUIT)) return { kind: 'relay' };
181
+ // One answer to "does this need a relay hop, and does it need ICE after that hop"; the
182
+ // `CODE_P2P_CIRCUIT` test below in `destinationIn` asks a different question.
183
+ const relayHop = addrKindOfComponents(components);
184
+ if (relayHop === 'relayed') return { kind: 'relay' };
185
+ if (relayHop === 'webrtc') return { kind: 'webrtc' };
164
186
  if (!includeTcp && !components.some((c) => c.code === CODE_WS || c.code === CODE_WSS)) return undefined;
165
187
  const host = components[0];
166
188
  if (!host?.value) return undefined;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * What kind of machine a node runs on, and the stored form of that fact the control network
3
+ * replicates.
4
+ *
5
+ * Two separate vocabularies on purpose. {@link NodeClass} is what an embedder sets and what
6
+ * every reader in this repository reasons about. {@link PublishedProfile} is the older pair of
7
+ * codes the `CadrePeer.Profile` column holds, kept because the control store is the one place
8
+ * backwards compatibility applies (`docs/cadre/control-schema.md` → "Schema versions and
9
+ * migrations"): a column rename cannot be migrated, and a party's machines update one at a
10
+ * time, so an older build's `KnownProfile` check would refuse a value replicated from an
11
+ * updated sibling. This module is the only place the two meet — nothing else writes or
12
+ * compares the stored codes.
13
+ */
14
+
15
+ /**
16
+ * What kind of machine a node runs on.
17
+ *
18
+ * `'device'` is a phone, laptop or browser running an app: intermittently connected, asleep or
19
+ * closed much of the time. `'server'` is an always-on node — a cadre-host child, a cadre-cli
20
+ * drone, a provider container. Both transact and both store; the class says how reachable the
21
+ * machine is, which is what the defaults derived from it (relay server, hosting unclaimed
22
+ * strands, the FRET profile db-p2p builds the node with) actually turn on.
23
+ *
24
+ * See `docs/cadre/node.md` → "Node classes".
25
+ */
26
+ export type NodeClass = 'device' | 'server';
27
+
28
+ /**
29
+ * The stored form of `CadrePeer.Profile`. Kept as-is for control-store compatibility; it
30
+ * encodes only whether the machine is always on.
31
+ */
32
+ export type PublishedProfile = 'transaction' | 'storage';
33
+
34
+ /** The stored form a machine publishes for whether it is always on. */
35
+ export function encodeAlwaysOn(alwaysOn: boolean): PublishedProfile {
36
+ return alwaysOn ? 'storage' : 'transaction';
37
+ }
38
+
39
+ /** Whether the machine that published `stored` is always on; null on a row it has not published. */
40
+ export function decodeAlwaysOn(stored: PublishedProfile | null): boolean | null {
41
+ return stored === null ? null : stored === 'storage';
42
+ }
43
+
44
+ /** Whether `value` is a stored `CadrePeer.Profile` the schema's `KnownProfile` check admits. */
45
+ export function isPublishedProfile(value: unknown): value is PublishedProfile {
46
+ return value === 'transaction' || value === 'storage';
47
+ }
@@ -7,6 +7,11 @@
7
7
  * built. A subpath module (`@serfab/cadre-core/node-default-transports`), like `push-node`,
8
8
  * because it names `@libp2p/tcp`: some bundlers (the NativeScript reference app's webpack) take
9
9
  * its Node implementation rather than its browser stub, and that needs `net`, `os` and `path`.
10
+ *
11
+ * It is also the only module in this repo that can give a Node host WebRTC, which is why
12
+ * `relay-addrs.ts` accepts a `/webrtc` listen entry only from a node that passed this function.
13
+ * See {@link loadNodeWebrtcTransport} for why that transport is loaded on demand and not
14
+ * imported here.
10
15
  */
11
16
 
12
17
  import { tcp } from '@libp2p/tcp';
@@ -14,25 +19,82 @@ import { webSockets } from '@libp2p/websockets';
14
19
  import { circuitRelayTransport } from '@libp2p/circuit-relay-v2';
15
20
  import type { Libp2pTransports } from '@optimystic/db-p2p';
16
21
  import type { ListenTransportOptions } from './relay-addrs.js';
22
+ import type { StunServer } from './relay-stun.js';
23
+
24
+ /** One entry of a libp2p transport list — what `tcp()`, `webSockets()` or `webRTC()` returns. */
25
+ type TransportFactory = Libp2pTransports[number];
17
26
 
18
27
  /**
19
- * TCP, WebSocket exactly when the node's listen entries switch it on, and the circuit-relay
20
- * transport.
28
+ * Builds `@libp2p/webrtc`'s Node transport over a set of STUN servers: what
29
+ * {@link loadNodeWebrtcTransport} resolves to, and what {@link nodeDefaultTransports} takes so
30
+ * that it stays synchronous.
31
+ */
32
+ export type NodeWebrtcTransport = (iceServers: readonly StunServer[]) => TransportFactory;
33
+
34
+ /**
35
+ * Load `@libp2p/webrtc`'s Node transport factory. Call it once, at start, on the branch that
36
+ * asked for WebRTC, and hand the result to {@link nodeDefaultTransports}.
37
+ *
38
+ * A RUN-TIME import, deliberately — the one in this package. `@libp2p/webrtc`'s Node build
39
+ * reaches `node-datachannel`, which loads a native addon as its module is evaluated and throws
40
+ * when the running platform has no prebuilt binary for it. A node that did not ask for WebRTC
41
+ * must neither pay that load nor fail on it, and a static import would do both. The throw, when
42
+ * it comes, names `node-datachannel`, the platform and the architecture, which is what an
43
+ * operator on an unsupported platform needs to read.
44
+ *
45
+ * The STUN servers are supplied per call rather than baked in, because the resolved set depends
46
+ * on the node's relays (`relay-stun.ts` → `resolveStunServers`) and one process may build
47
+ * several nodes. No TURN server is configured anywhere: a WebRTC path that ICE cannot find stays
48
+ * on the circuit relay. See `docs/network/relay.md` → "Direct connections over WebRTC".
49
+ *
50
+ * NOTE: the load is conditional but the INSTALL is not. `@libp2p/webrtc` is a plain dependency
51
+ * of this package, so its 55-package closure — the `node-datachannel` prebuilt binary (about
52
+ * 19 MiB on Alpine x64) plus `react-native-webrtc`, `@peculiar/x509` and the rest — ships in
53
+ * every cadre-cli image whether any node turns WebRTC on; measured at about 33 MiB over
54
+ * cadre-cli's production closure without it. Fine while that is a third of a node image; if it
55
+ * ever has to come off the images that do not use it, move the dependency and this loader into
56
+ * a package of their own that a host installs on purpose.
57
+ */
58
+ export async function loadNodeWebrtcTransport(): Promise<NodeWebrtcTransport> {
59
+ const { webRTC } = await import('@libp2p/webrtc');
60
+ return (iceServers) => webRTC({ rtcConfiguration: { iceServers: [...iceServers] } });
61
+ }
62
+
63
+ /**
64
+ * TCP, WebSocket exactly when the node's listen entries switch it on, WebRTC when they switch
65
+ * that on and `webrtc` was loaded, and the circuit-relay transport.
21
66
  *
22
67
  * Passing an explicit list makes db-p2p ignore `wsPort` for transports, which is why WebSocket is
23
68
  * decided here from the same switch. Its other use of `wsPort`, a default WebSocket listen
24
69
  * address, never applies: a node with configured relays always has explicit listen entries.
25
70
  *
71
+ * `webrtc` is a parameter rather than a static import so the native addon behind it is loaded
72
+ * only by a host that asked for WebRTC ({@link loadNodeWebrtcTransport}). Omitting it while a
73
+ * listen entry names `/webrtc` THROWS: that pairing is the silent-listener defect
74
+ * `resolveTransportOptions` exists to prevent (`relay-addrs.ts`), and libp2p would just drop the
75
+ * address. The usual caller is `cadre-cli`, which loads the factory and sets the listen entry
76
+ * from one setting.
77
+ *
26
78
  * NOTE: mirrors `createLibp2pNode`'s default list in
27
79
  * `../optimystic/packages/db-p2p/src/libp2p-node.ts` (cadre never sets its `disableTcp`). That file
28
80
  * is the source of truth; if its defaults change, this list has to follow. If db-p2p ever takes an
29
81
  * option to build its default list with relay discovery off, use that and drop this module and
30
82
  * `NetworkConfig.defaultTransports`.
31
83
  */
32
- export function nodeDefaultTransports({ wsPort }: ListenTransportOptions): Libp2pTransports {
84
+ export function nodeDefaultTransports(
85
+ { wsPort, webrtcIceServers }: ListenTransportOptions,
86
+ webrtc?: NodeWebrtcTransport
87
+ ): Libp2pTransports {
88
+ if (webrtcIceServers !== undefined && webrtc === undefined) {
89
+ throw new Error(
90
+ 'A /webrtc listen entry was resolved but no WebRTC transport was loaded. Pass the result of '
91
+ + 'loadNodeWebrtcTransport() to nodeDefaultTransports, or drop the /webrtc listen entry.'
92
+ );
93
+ }
33
94
  return [
34
95
  tcp(),
35
96
  ...(wsPort === undefined ? [] : [webSockets()]),
97
+ ...(webrtcIceServers === undefined || webrtc === undefined ? [] : [webrtc(webrtcIceServers)]),
36
98
  circuitRelayTransport()
37
99
  ];
38
100
  }