@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,798 +1,798 @@
1
- /**
2
- * The pending-join retry loop: carries on a join this party asked for through another party's
3
- * invitation (`CadreControl.JoinRequest`, one row per invitation, with its outcome in
4
- * `JoinSuccess` / `JoinFailure`) in the background, on every owner machine of the party, until
5
- * the join works, the invitation is used up or expires, or the user dismisses it. The behaviour
6
- * is described in `docs/strands.md` → "Joining while the inviter is offline".
7
- *
8
- * `CadreNode` owns every side effect and hands this module plain functions
9
- * ({@link PendingJoinRunnerDeps}): read the joins, hear a change to the tables they are read
10
- * from, run one attempt (its own `formStrand`), write an outcome, say whether this machine is an
11
- * owner, and the clock. This module owns the policy: when to read the joins, when to attempt,
12
- * how to read an attempt's failure, and how to settle an outcome write that another machine's
13
- * write beat.
14
- *
15
- * Only owner machines run it, because every pending-join write is owner-signed. Letting a
16
- * machine without an owner key finish a join is `blocked/decide-non-owner-machine-completes-a-pending-join`;
17
- * that changes {@link PendingJoinRunnerDeps.isOwner} and the write functions, not this loop.
18
- */
19
-
20
- import debug from 'debug';
21
- import type {
22
- FormStrandResult,
23
- JoinOutcome,
24
- PendingJoin,
25
- PendingJoinStatus,
26
- StrandFormationDisclosure,
27
- StrandMembershipInvite
28
- } from './types.js';
29
- import { canonicalJson } from './canonical-json.js';
30
- import { PendingJoinChangedError, type JoinRequestFields, type PendingJoinFields } from './control-database.js';
31
- import { FormationPostApprovalError, FormationRejectedError, FormationUnreachableError } from './strand-formation-rejection.js';
32
- import { formationDeadlines } from './strand-formation-deadlines.js';
33
- import { MEMBERSHIP_INVITE_TTL_MS } from './strand-formation-manager.js';
34
- import { scheduleRuns, type TableChangeWatch, type TableChangeWatchOptions } from './table-change-watch.js';
35
- import { defaultTimeoutScheduler, type TimeoutScheduler } from './timeout-scheduler.js';
36
- import { describeThrown } from './describe-thrown.js';
37
-
38
- const log = debug('sereus:cadre:pending-join');
39
-
40
- /**
41
- * The longest an owner machine goes without re-reading the party's pending joins when no change
42
- * to their tables is heard. It covers a change that arrives without a storage event, and the
43
- * time-driven removal of a finished join, which lands up to this much late.
44
- *
45
- * NOTE: on a cadre larger than `CONTROL_REPLICATION_BREADTH` (16), a machine outside a join
46
- * table's cohort hears no change event, so a dismissal or another machine's outcome reaches it
47
- * up to this much late. The worst effect is one more attempt on a dismissed join, whose outcome
48
- * write then finds the request gone, or a `token-spent` answer whose re-read adopts the other
49
- * machine's outcome. A 30 s pass while any join is pending was declined: a join can stay pending
50
- * for {@link MAX_PENDING_JOIN_MS}, and those reads are what this backstop removes. Revisit if a
51
- * cadre above 16 machines is seen attempting dismissed joins.
52
- */
53
- export const PENDING_JOIN_BACKSTOP_MS = 10 * 60_000;
54
-
55
- /** How soon a pass runs again after one failed, or after an outcome write gave up to another machine's writes. */
56
- const PENDING_JOIN_PASS_RETRY_MS = 30_000;
57
-
58
- /** Ceiling on the wait between two attempts of one join on one machine, before jitter. */
59
- export const PENDING_JOIN_MAX_BACKOFF_MS = 10 * 60_000;
60
-
61
- /**
62
- * The longest a join is tried for. A request's `ExpiresAt` is the earlier of this and the
63
- * invitation's own expiration, which the inviter chose.
64
- */
65
- export const MAX_PENDING_JOIN_MS = 30 * 24 * 3600_000;
66
-
67
- /** Background attempts one machine runs at once. An explicit `requestJoin` does not wait for a slot. */
68
- const MAX_BACKGROUND_ATTEMPTS = 2;
69
-
70
- /** Each retry delay is moved by up to this fraction either way, so machines that failed together do not retry together. */
71
- const RETRY_JITTER = 0.2;
72
-
73
- /** Re-read-and-rewrite rounds after another machine's write won, before a pass {@link PENDING_JOIN_PASS_RETRY_MS} later decides instead. */
74
- const MAX_OUTCOME_WRITE_ROUNDS = 3;
75
-
76
- type AttemptError = NonNullable<PendingJoinStatus['lastError']>;
77
-
78
- /** Which pending-join write this machine made: the request itself (an insert or a rewrite), or an outcome row for it. */
79
- export type PendingJoinWrite = 'request' | 'outcome';
80
-
81
- export interface PendingJoinRunnerDeps {
82
- /** This machine's peer id; with the request id it fixes when this machine first tries a join it did not ask for. */
83
- selfId: string;
84
- /** `NetworkConfig.linkRoundTripMs`: the retry pace follows the formation deadlines it yields. */
85
- linkRoundTripMs?: number;
86
- /** Whether this machine may write pending joins now. Asked every pass. */
87
- isOwner(): Promise<boolean>;
88
- readRows(): Promise<PendingJoin[]>;
89
- /** Subscribe `onChange` to the tables a pass reads. Absent: passes come from `start`, `kick`, retries and the backstop only (tests). */
90
- watchChanges?(onChange: () => Promise<void>, options: TableChangeWatchOptions): TableChangeWatch;
91
- /** Run a pass at least this long after the last one settled; default {@link PENDING_JOIN_BACKSTOP_MS}. */
92
- backstopMs?: number;
93
- readRow(id: string): Promise<PendingJoin | null>;
94
- /** One formation attempt for the request's invitation and disclosure (`CadreNode.formStrand`). */
95
- attempt(join: PendingJoin): Promise<FormStrandResult>;
96
- /** `ControlDatabase.recordJoinOutcome`, owner-signed: throws `PendingJoinChangedError` when the live join is not `expected`. */
97
- record(expected: PendingJoin, outcome: JoinOutcome): Promise<PendingJoin>;
98
- /** `ControlDatabase.rewritePendingJoin`, owner-signed: throws `PendingJoinChangedError` when the live request is not `expectedStampId`. */
99
- rewrite(expectedStampId: string, next: PendingJoinFields): Promise<PendingJoin>;
100
- /** `ControlDatabase.deletePendingJoin`, owner-signed. */
101
- remove(id: string): Promise<boolean>;
102
- /** Whether this machine reaches no sibling now (`CadreNode.hasReachableControlSibling`), so a write it commits reaches no other machine. */
103
- isAlone(): boolean;
104
- /**
105
- * Whether a write nothing waits on must wait for a reachable sibling now
106
- * (`CadreNode.controlWriteCouldFork`): this machine reaches none while the party has other
107
- * machines, so another owner machine writing the same tables meanwhile would fork them.
108
- */
109
- deferBackgroundWrites(): Promise<boolean>;
110
- /** The sApp the request's invitation names. */
111
- sAppIdOf(join: PendingJoin): string;
112
- /** Every pass's joins, read by an owner machine; `CadreNode` stages the membership invitations they carry. */
113
- observeRows(joins: readonly PendingJoin[]): void;
114
- emit(status: PendingJoinStatus): void;
115
- now?: () => number;
116
- random?: () => number;
117
- scheduler?: TimeoutScheduler;
118
- }
119
-
120
- /** This machine's memory of one join. Nothing here survives a restart; the rows are the durable state. */
121
- interface TrackedJoin {
122
- row: PendingJoin;
123
- /** Retryable failures on this machine since the join was first seen or asked for again. */
124
- failures: number;
125
- timer?: unknown;
126
- /** Due, waiting for a background attempt slot. */
127
- queued: boolean;
128
- /** Set while an attempt (or a re-run of its outcome write) is running. */
129
- attempt?: Promise<'deferred' | undefined>;
130
- trying: boolean;
131
- nextAttemptAt?: number;
132
- lastError?: AttemptError;
133
- /** An earlier attempt here answered `token-spent`; the next such answer fails the join. */
134
- spentOnce: boolean;
135
- /** This machine's approved join, held until its outcome write lands, so a later pass rewrites it rather than attempting a spent token. */
136
- joinedHere?: JoinOutcome;
137
- lastEmitted?: string;
138
- }
139
-
140
- /** What to do after an outcome write found that another write had changed or removed the join. */
141
- type LostWriteResolution = 'gone' | 'adopt' | 'rewrite';
142
-
143
- /**
144
- * A `joined` outcome replaces anything still live, since a join that happened cannot be undone
145
- * by another machine's failure. A failure replaces a pending request of the same ask: only a
146
- * re-issue of a request written alone writes one, unchanged, so it decides nothing. Any other
147
- * live join wins, and a fresh request is then decided again by the loop.
148
- */
149
- function resolveLostWrite(live: PendingJoin | null, expected: PendingJoin, next: JoinOutcome): LostWriteResolution {
150
- if (live === null) return 'gone';
151
- if (live.outcome?.kind === 'joined') return 'adopt';
152
- if (next.kind === 'joined') return 'rewrite';
153
- return live.outcome === null && live.RequestedAt === expected.RequestedAt ? 'rewrite' : 'adopt';
154
- }
155
-
156
- /**
157
- * The request a `requestJoin` writes: tried until the invitation's own expiration or
158
- * {@link MAX_PENDING_JOIN_MS} from now, whichever comes first.
159
- */
160
- export function requestedPendingJoin(
161
- id: string,
162
- encodedInvitation: string,
163
- disclosure: StrandFormationDisclosure,
164
- invitationExpiresAt: number,
165
- now: number
166
- ): JoinRequestFields {
167
- return {
168
- Id: id,
169
- Invitation: encodedInvitation,
170
- Disclosure: canonicalJson(disclosure),
171
- RequestedAt: now,
172
- ExpiresAt: Math.min(invitationExpiresAt, now + MAX_PENDING_JOIN_MS),
173
- };
174
- }
175
-
176
- /** A request's stored disclosure, as the next attempt sends it. Owner-signed, so anything but an object is a bug. */
177
- export function parseStoredDisclosure(join: PendingJoin): StrandFormationDisclosure {
178
- const parsed: unknown = JSON.parse(join.Disclosure);
179
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
180
- throw new Error(`JoinRequest ${join.Id}: the stored disclosure is not a JSON object`);
181
- }
182
- return parsed as StrandFormationDisclosure;
183
- }
184
-
185
- /** A `JoinSuccess` row's `MembershipInvite` column, or null when it is not the `{inviteKey, invitePrivateKey}` JSON the loop writes. */
186
- export function parseStoredMembershipInvite(text: string): StrandMembershipInvite | null {
187
- let parsed: unknown;
188
- try {
189
- parsed = JSON.parse(text);
190
- } catch {
191
- return null;
192
- }
193
- if (typeof parsed !== 'object' || parsed === null) return null;
194
- const { inviteKey, invitePrivateKey } = parsed as Record<string, unknown>;
195
- return typeof inviteKey === 'string' && typeof invitePrivateKey === 'string' ? { inviteKey, invitePrivateKey } : null;
196
- }
197
-
198
- /**
199
- * The membership invitations joined requests carry that this process has not staged yet, so a
200
- * closed strand joined on one owner machine can be seated by whichever machine launches it
201
- * first. Joins older than {@link MEMBERSHIP_INVITE_TTL_MS} are skipped: their invitation is dead.
202
- * `alreadyStaged` holds invite keys; a malformed column is skipped and logged.
203
- */
204
- export function membershipInvitesToStage(
205
- joins: readonly PendingJoin[],
206
- alreadyStaged: ReadonlySet<string>,
207
- now: number
208
- ): Array<{ rowId: string; strandId: string; invite: StrandMembershipInvite }> {
209
- const toStage: Array<{ rowId: string; strandId: string; invite: StrandMembershipInvite }> = [];
210
- for (const join of joins) {
211
- const { outcome } = join;
212
- if (outcome?.kind !== 'joined' || outcome.MembershipInvite === null) continue;
213
- if (now >= outcome.RecordedAt + MEMBERSHIP_INVITE_TTL_MS) continue;
214
- const invite = parseStoredMembershipInvite(outcome.MembershipInvite);
215
- if (!invite) {
216
- log('pending join %s: its MembershipInvite column does not parse; not staged', join.Id);
217
- continue;
218
- }
219
- if (!alreadyStaged.has(invite.inviteKey)) {
220
- toStage.push({ rowId: join.Id, strandId: outcome.StrandId, invite });
221
- }
222
- }
223
- return toStage;
224
- }
225
-
226
- /** The join without its stamp, as a rewrite takes it. */
227
- function fieldsOf(join: PendingJoin): PendingJoinFields {
228
- const { StampId: _stampId, ...fields } = join;
229
- return fields;
230
- }
231
-
232
- function joinedOutcome(result: FormStrandResult, now: number): JoinOutcome {
233
- const invite = result.membershipInvite;
234
- return {
235
- kind: 'joined',
236
- RecordedAt: now,
237
- StrandId: result.strandId,
238
- MembershipInvite: invite ? JSON.stringify({ inviteKey: invite.inviteKey, invitePrivateKey: invite.invitePrivateKey }) : null,
239
- };
240
- }
241
-
242
- function failedOutcome(code: string, reason: string, now: number): JoinOutcome {
243
- return { kind: 'failed', RecordedAt: now, Code: code, Reason: reason };
244
- }
245
-
246
- /** A fraction in [0, 1) fixed by `key` (32-bit FNV-1a): the same machine staggers the same join the same way every time. */
247
- function stableFraction(key: string): number {
248
- let hash = 0x811c9dc5;
249
- for (let i = 0; i < key.length; i++) {
250
- hash ^= key.charCodeAt(i);
251
- hash = Math.imul(hash, 0x01000193);
252
- }
253
- return (hash >>> 0) / 0x1_0000_0000;
254
- }
255
-
256
- export class PendingJoinRunner {
257
- private readonly tracked = new Map<string, TrackedJoin>();
258
- /** Joins whose latest write by this machine committed with no sibling reachable: id → the request stamp written. */
259
- private readonly writtenAlone = new Map<string, string>();
260
- private readonly dueQueue: TrackedJoin[] = [];
261
- private readonly scheduler: TimeoutScheduler;
262
- private readonly now: () => number;
263
- private readonly random: () => number;
264
- /** First retry delay, and the window a join this machine did not ask for is first tried in. */
265
- private readonly baseDelayMs: number;
266
- /** How long a `token-spent` answer waits before its confirming attempt: long enough for a sibling's `joined` write to replicate. */
267
- private readonly spentConfirmDelayMs: number;
268
- private running = false;
269
- /** Every pass runs on it, one at a time; present between {@link start} and {@link stop}. */
270
- private watch: TableChangeWatch | null = null;
271
- private backgroundAttempts = 0;
272
- /** A background write was deferred ({@link PendingJoinRunnerDeps.deferBackgroundWrites}); {@link resumeDeferredWrites} runs a pass for it. */
273
- private deferredWrites = false;
274
-
275
- constructor(private readonly deps: PendingJoinRunnerDeps) {
276
- this.scheduler = deps.scheduler ?? defaultTimeoutScheduler;
277
- this.now = deps.now ?? Date.now;
278
- this.random = deps.random ?? Math.random;
279
- const deadlines = formationDeadlines(deps.linkRoundTripMs);
280
- this.baseDelayMs = 2 * deadlines.dialMs;
281
- this.spentConfirmDelayMs = 2 * deadlines.sessionMs;
282
- }
283
-
284
- /**
285
- * Start passes: one at once, then one whenever a table a pass reads changes, and at the latest
286
- * {@link PENDING_JOIN_BACKSTOP_MS} after the last. Throws when the change subscription cannot
287
- * be made.
288
- *
289
- * NOTE: a pass from before a {@link stop} that is still in flight runs alongside the new
290
- * watch's passes, since each watch keeps only its own runs to one at a time. `CadreNode` builds
291
- * a fresh runner per start, so nothing restarts one; if something comes to, make that pass
292
- * check which start it belongs to.
293
- */
294
- start(): void {
295
- if (this.running) return;
296
- this.watch = this.subscribe();
297
- this.running = true;
298
- this.watch.trigger(0);
299
- }
300
-
301
- /**
302
- * Stop scheduling. Clears every timer and starts no new attempt.
303
- *
304
- * NOTE: an attempt already in flight is not awaited, because `formStrand` takes no abort
305
- * signal. An approval that lands while the node stops can lose its local records; the request
306
- * then stays pending, and the next start's attempt answers `token-spent`, which fails it after
307
- * its confirming attempt. Honest and bounded; if it shows up in practice, give `formStrand` a
308
- * signal and abort it here.
309
- */
310
- stop(): void {
311
- this.running = false;
312
- // A pass already in flight finishes; `running` keeps it from scheduling anything further.
313
- this.watch?.dispose();
314
- this.watch = null;
315
- for (const entry of this.tracked.values()) this.cancelTimer(entry);
316
- this.tracked.clear();
317
- this.dueQueue.length = 0;
318
- this.writtenAlone.clear();
319
- this.deferredWrites = false;
320
- }
321
-
322
- /**
323
- * Run a pass now, for a change the watched tables do not show (this machine's owner signer was
324
- * just wired). A pass in flight is followed by one more.
325
- */
326
- kick(): void {
327
- this.watch?.trigger(0);
328
- }
329
-
330
- /**
331
- * Run a pass now if a background write was deferred while one could have forked the party
332
- * ({@link PendingJoinRunnerDeps.deferBackgroundWrites}), so the joins it left unscheduled are
333
- * scheduled again. Called on the control cohort's growth edge, when a sibling becomes reachable.
334
- */
335
- resumeDeferredWrites(): void {
336
- if (!this.deferredWrites) return;
337
- this.deferredWrites = false;
338
- this.kick();
339
- }
340
-
341
- /**
342
- * Try `join` on this machine at once, outside the background slots, and report the status
343
- * after the attempt. Joins an attempt already running for it.
344
- */
345
- async attemptNow(join: PendingJoin): Promise<PendingJoinStatus> {
346
- const entry = this.adopt(join);
347
- // A background attempt already running for it may defer instead of attempting.
348
- if (entry.row.outcome === null && await this.startAttempt(entry, false) === 'deferred') {
349
- await this.startAttempt(entry, false);
350
- }
351
- return this.describe(entry.row, entry);
352
- }
353
-
354
- /** This machine's view of `join`: its own state, with this machine's attempt state laid over a pending one. */
355
- statusOf(join: PendingJoin): PendingJoinStatus {
356
- return this.describe(join, this.tracked.get(join.Id));
357
- }
358
-
359
- /**
360
- * Record a pending-join write this machine made, for {@link reissueWritesMadeAlone}. A write
361
- * made alone marks the join. A request write made connected clears the mark, since it
362
- * carried the request; an outcome write made connected does not, since the request it names
363
- * may still be unknown to the other machines.
364
- */
365
- noteWritten(join: PendingJoin, write: PendingJoinWrite): void {
366
- if (this.deps.isAlone()) {
367
- this.writtenAlone.set(join.Id, join.StampId);
368
- } else if (write === 'request') {
369
- this.writtenAlone.delete(join.Id);
370
- }
371
- }
372
-
373
- /** Stop tracking a join the user dismissed. An attempt in flight finishes; its outcome write then finds the request gone. */
374
- forgetRow(id: string): void {
375
- const entry = this.tracked.get(id);
376
- if (entry) this.forget(entry);
377
- }
378
-
379
- /**
380
- * Re-write, with identical content under a fresh stamp, each join this machine last wrote while
381
- * no sibling was reachable, so the other machines receive it. Called on the control cohort's
382
- * growth edge, when a sibling becomes reachable. A join someone wrote since is left alone.
383
- *
384
- * NOTE: in memory only, so a join written alone by a process that stopped before it reconnected
385
- * reaches the party only with that join's next write. A sweep of every join this machine wrote,
386
- * on the first connection after start, would cover that, at the cost of one permanent
387
- * `Revocation` tombstone per join per start. Revisit if other machines are seen missing such joins.
388
- */
389
- async reissueWritesMadeAlone(): Promise<void> {
390
- if (this.writtenAlone.size === 0) return;
391
- if (!(await this.deps.isOwner())) {
392
- this.writtenAlone.clear();
393
- return;
394
- }
395
- for (const [id, stampId] of [...this.writtenAlone]) {
396
- try {
397
- const live = await this.deps.readRow(id);
398
- if (!live || live.StampId !== stampId) {
399
- this.writtenAlone.delete(id);
400
- continue;
401
- }
402
- const written = await this.deps.rewrite(stampId, fieldsOf(live));
403
- this.noteWritten(written, 'request');
404
- const entry = this.tracked.get(id);
405
- if (entry?.row.StampId === stampId) entry.row = written;
406
- log('pending join %s: re-issued the join written while alone', id);
407
- } catch (error) {
408
- log('pending join %s: re-issuing the join written while alone failed; kept for the next connection: %s', id, describeThrown(error));
409
- }
410
- }
411
- }
412
-
413
- /** The watch every pass runs on: the deps' change subscription, or a timer-only one. */
414
- private subscribe(): TableChangeWatch {
415
- const onChange = (): Promise<void> => this.pass();
416
- const options: TableChangeWatchOptions = {
417
- label: 'pending-join',
418
- backstopMs: this.deps.backstopMs ?? PENDING_JOIN_BACKSTOP_MS,
419
- scheduler: this.scheduler,
420
- };
421
- return this.deps.watchChanges?.(onChange, options) ?? scheduleRuns(onChange, options);
422
- }
423
-
424
- /** One pass; a failed one runs again {@link PENDING_JOIN_PASS_RETRY_MS} later. */
425
- private async pass(): Promise<void> {
426
- try {
427
- await this.runPass();
428
- } catch (error) {
429
- log('pending-join pass failed; retried in 30 s: %s', describeThrown(error));
430
- this.retryPass();
431
- }
432
- }
433
-
434
- private retryPass(): void {
435
- this.watch?.trigger(PENDING_JOIN_PASS_RETRY_MS);
436
- }
437
-
438
- private async runPass(): Promise<void> {
439
- if (!this.running) return;
440
- if (!(await this.deps.isOwner())) {
441
- log('pending-join pass skipped: this machine is not an enrolled owner');
442
- this.pauseAttempts();
443
- return;
444
- }
445
- const joins = await this.deps.readRows();
446
- if (!this.running) return;
447
- this.deps.observeRows(joins);
448
- const live = new Set(joins.map((join) => join.Id));
449
- for (const entry of [...this.tracked.values()]) {
450
- if (!live.has(entry.row.Id) && !entry.attempt) this.forget(entry);
451
- }
452
- for (const join of joins) {
453
- if (!this.running) return;
454
- try {
455
- await this.consider(join);
456
- } catch (error) {
457
- log('pending join %s: this pass could not handle it; retried in 30 s: %s', join.Id, describeThrown(error));
458
- this.retryPass();
459
- }
460
- }
461
- }
462
-
463
- /** Drop every scheduled attempt; the first pass that finds this machine an owner again schedules afresh. */
464
- private pauseAttempts(): void {
465
- for (const entry of this.tracked.values()) {
466
- this.cancelTimer(entry);
467
- entry.nextAttemptAt = undefined;
468
- }
469
- for (const entry of this.dueQueue) entry.queued = false;
470
- this.dueQueue.length = 0;
471
- }
472
-
473
- /** Bring one read join into this machine's schedule. */
474
- private async consider(join: PendingJoin): Promise<void> {
475
- const entry = this.adopt(join);
476
- if (entry.attempt) return;
477
- if (entry.row.outcome !== null) {
478
- this.emitIfChanged(entry);
479
- await this.ageOut(entry);
480
- return;
481
- }
482
- if (entry.joinedHere || this.now() >= entry.row.ExpiresAt) {
483
- await this.startAttempt(entry, true);
484
- return;
485
- }
486
- if (entry.timer === undefined && !entry.queued) {
487
- this.scheduleAttempt(entry, Math.floor(stableFraction(`${this.deps.selfId}|${entry.row.Id}`) * this.baseDelayMs));
488
- }
489
- this.emitIfChanged(entry);
490
- }
491
-
492
- /**
493
- * The tracked entry for `join`, updated to it. A join asked for again (`RequestedAt` changed)
494
- * starts this machine's counting over; a finished join stops its schedule.
495
- */
496
- private adopt(join: PendingJoin): TrackedJoin {
497
- const entry = this.tracked.get(join.Id);
498
- if (!entry) {
499
- const fresh: TrackedJoin = { row: join, failures: 0, queued: false, trying: false, spentOnce: false };
500
- this.tracked.set(join.Id, fresh);
501
- return fresh;
502
- }
503
- if (entry.row.StampId === join.StampId && entry.row.outcome?.kind === join.outcome?.kind) return entry;
504
- if (join.outcome !== null || entry.row.RequestedAt !== join.RequestedAt) {
505
- this.cancelTimer(entry);
506
- entry.failures = 0;
507
- entry.spentOnce = false;
508
- entry.lastError = undefined;
509
- entry.nextAttemptAt = undefined;
510
- }
511
- if (join.outcome?.kind === 'joined') entry.joinedHere = undefined;
512
- entry.row = join;
513
- return entry;
514
- }
515
-
516
- private scheduleAttempt(entry: TrackedJoin, delayMs: number): void {
517
- if (!this.running) return;
518
- this.cancelTimer(entry);
519
- const now = this.now();
520
- // A request already past its expiry keeps the full delay: its due attempt is an outcome
521
- // write, and clamping to a past expiry would retry a failing write with no wait at all.
522
- const at = now < entry.row.ExpiresAt ? Math.min(now + delayMs, entry.row.ExpiresAt) : now + delayMs;
523
- entry.nextAttemptAt = at;
524
- entry.timer = this.scheduler.setTimeout(() => {
525
- entry.timer = undefined;
526
- this.enqueue(entry);
527
- }, Math.max(0, at - this.now()));
528
- }
529
-
530
- private cancelTimer(entry: TrackedJoin): void {
531
- if (entry.timer !== undefined) {
532
- this.scheduler.clearTimeout(entry.timer);
533
- entry.timer = undefined;
534
- }
535
- }
536
-
537
- private enqueue(entry: TrackedJoin): void {
538
- if (!this.running || this.tracked.get(entry.row.Id) !== entry || entry.queued) return;
539
- entry.queued = true;
540
- this.dueQueue.push(entry);
541
- this.pump();
542
- }
543
-
544
- /** Start due attempts while background slots are free. */
545
- private pump(): void {
546
- while (this.running && this.backgroundAttempts < MAX_BACKGROUND_ATTEMPTS && this.dueQueue.length > 0) {
547
- const entry = this.dueQueue.shift()!;
548
- entry.queued = false;
549
- if (entry.attempt || this.tracked.get(entry.row.Id) !== entry) continue;
550
- this.backgroundAttempts++;
551
- void this.startAttempt(entry, true).finally(() => {
552
- this.backgroundAttempts--;
553
- this.pump();
554
- });
555
- }
556
- }
557
-
558
- /**
559
- * Run one attempt for `entry`, or join the one already running. A `background` attempt (one no
560
- * `requestJoin` asked for) is deferred while a write could fork the party ({@link attemptOnce}),
561
- * and then resolves `'deferred'`, also for a caller that joined it. Never rejects.
562
- */
563
- private startAttempt(entry: TrackedJoin, background: boolean): Promise<'deferred' | undefined> {
564
- if (entry.attempt) return entry.attempt;
565
- this.cancelTimer(entry);
566
- if (entry.queued) {
567
- entry.queued = false;
568
- this.dueQueue.splice(this.dueQueue.indexOf(entry), 1);
569
- }
570
- // NOTE: only a join is held for re-writing (`joinedHere`); a failed write of a final failure is
571
- // retried by attempting again, so a `local` failure whose write failed ends up recorded as
572
- // `token-spent`. If apps come to branch on that code, hold failures the same way.
573
- const run = this.attemptOnce(entry, background)
574
- .catch((error: unknown) => {
575
- entry.trying = false;
576
- log('pending join %s: attempt failed on this machine: %s', entry.row.Id, describeThrown(error));
577
- if (entry.row.outcome === null && this.tracked.get(entry.row.Id) === entry) {
578
- this.retryLater(entry, { code: 'local', reason: describeThrown(error) });
579
- }
580
- return undefined;
581
- })
582
- .finally(() => {
583
- entry.attempt = undefined;
584
- });
585
- entry.attempt = run;
586
- return run;
587
- }
588
-
589
- /**
590
- * One attempt, or the write it is due. A join this machine already made is recorded whatever
591
- * else holds: kept only in memory, it would be lost with a restart, and the next start's
592
- * attempt would fail the join as `token-spent`. Otherwise a background attempt, and the
593
- * `expired` outcome due in its place, are deferred while a write could fork the party.
594
- */
595
- private async attemptOnce(entry: TrackedJoin, background: boolean): Promise<'deferred' | undefined> {
596
- if (entry.row.outcome !== null) return;
597
- if (entry.joinedHere) {
598
- await this.writeOutcome(entry, entry.joinedHere);
599
- return;
600
- }
601
- if (background && await this.deps.deferBackgroundWrites()) {
602
- this.deferAttempt(entry);
603
- return 'deferred';
604
- }
605
- if (this.now() >= entry.row.ExpiresAt) {
606
- const reason = `No attempt starts after ${new Date(entry.row.ExpiresAt).toISOString()}`;
607
- await this.writeOutcome(entry, failedOutcome('expired', reason, this.now()));
608
- return;
609
- }
610
- entry.trying = true;
611
- entry.nextAttemptAt = undefined;
612
- this.emitIfChanged(entry);
613
- let result: FormStrandResult;
614
- try {
615
- result = await this.deps.attempt(entry.row);
616
- } catch (error) {
617
- entry.trying = false;
618
- await this.onAttemptFailed(entry, error);
619
- return;
620
- }
621
- entry.trying = false;
622
- log('pending join %s: approved, strand %s', entry.row.Id, result.strandId);
623
- entry.joinedHere = joinedOutcome(result, this.now());
624
- await this.writeOutcome(entry, entry.joinedHere);
625
- }
626
-
627
- /** Leave `entry` unscheduled; the pass {@link resumeDeferredWrites} runs schedules it again. */
628
- private deferAttempt(entry: TrackedJoin): void {
629
- entry.nextAttemptAt = undefined;
630
- this.deferredWrites = true;
631
- log('pending join %s: background attempt deferred until a sibling is reachable', entry.row.Id);
632
- this.emitIfChanged(entry);
633
- }
634
-
635
- /** Read a failed attempt: retry, confirm a spent token, or fail the join. */
636
- private async onAttemptFailed(entry: TrackedJoin, error: unknown): Promise<void> {
637
- const now = this.now();
638
- if (error instanceof FormationRejectedError && error.code === 'token-spent') {
639
- await this.onSpent(entry, error);
640
- } else if (error instanceof FormationPostApprovalError) {
641
- log('pending join %s: approved, then a step on this machine failed; failing the join', entry.row.Id);
642
- await this.writeOutcome(entry, failedOutcome('local', error.message, now));
643
- } else if (error instanceof FormationRejectedError && !error.retryable) {
644
- log('pending join %s: refused (%s); failing the join', entry.row.Id, error.code);
645
- await this.writeOutcome(entry, failedOutcome(error.code, error.reason, now));
646
- } else if (error instanceof FormationRejectedError) {
647
- this.retryLater(entry, { code: error.code, reason: error.reason });
648
- } else if (error instanceof FormationUnreachableError) {
649
- this.retryLater(entry, { code: 'unreachable', reason: error.message });
650
- } else {
651
- // Retrying is safe: nothing is attempted after the request's expiry.
652
- log('pending join %s: attempt threw an unexpected error; retrying: %s', entry.row.Id, describeThrown(error));
653
- this.retryLater(entry, { code: 'local', reason: describeThrown(error) });
654
- }
655
- }
656
-
657
- /**
658
- * A `token-spent` answer may mean another owner machine of this party won the same
659
- * invitation. Adopt its outcome if the join already shows one; otherwise confirm once, after
660
- * long enough for that machine's `joined` write to arrive, before failing the join.
661
- */
662
- private async onSpent(entry: TrackedJoin, error: FormationRejectedError): Promise<void> {
663
- const live = await this.deps.readRow(entry.row.Id);
664
- if (!live) {
665
- this.forget(entry);
666
- return;
667
- }
668
- this.adopt(live);
669
- if (live.outcome !== null) {
670
- this.emitIfChanged(entry);
671
- return;
672
- }
673
- if (entry.spentOnce) {
674
- log('pending join %s: token spent again after the confirming wait; failing the join', entry.row.Id);
675
- await this.writeOutcome(entry, failedOutcome('token-spent', error.reason, this.now()));
676
- return;
677
- }
678
- entry.spentOnce = true;
679
- entry.lastError = { code: 'token-spent', reason: error.reason };
680
- this.scheduleAttempt(entry, this.spentConfirmDelayMs);
681
- this.emitIfChanged(entry);
682
- }
683
-
684
- private retryLater(entry: TrackedJoin, lastError: AttemptError): void {
685
- entry.failures++;
686
- entry.lastError = lastError;
687
- this.scheduleAttempt(entry, this.backoffMs(entry.failures));
688
- this.emitIfChanged(entry);
689
- }
690
-
691
- /** `min(base × 2^(n−1), max)`, moved by up to ±{@link RETRY_JITTER}. */
692
- private backoffMs(failures: number): number {
693
- const capped = Math.min(this.baseDelayMs * 2 ** (failures - 1), PENDING_JOIN_MAX_BACKOFF_MS);
694
- return Math.round(capped * (1 + (this.random() * 2 - 1) * RETRY_JITTER));
695
- }
696
-
697
- /**
698
- * Record `next` on the join this machine last read. When another write got there first, settle
699
- * by {@link resolveLostWrite} from the live join the refusal carries. A join the user dismissed
700
- * meanwhile is not recreated; a join this machine made is still remembered machine-locally, as
701
- * every `formStrand` join is.
702
- */
703
- private async writeOutcome(entry: TrackedJoin, next: JoinOutcome): Promise<void> {
704
- let expected = entry.row;
705
- for (let round = 0; round < MAX_OUTCOME_WRITE_ROUNDS; round++) {
706
- let live: PendingJoin | null;
707
- try {
708
- const written = await this.deps.record(expected, next);
709
- this.noteWritten(written, 'outcome');
710
- this.settle(written);
711
- log('pending join %s: recorded %s', entry.row.Id, next.kind === 'failed' ? `failed (${next.Code})` : 'joined');
712
- return;
713
- } catch (error) {
714
- if (!(error instanceof PendingJoinChangedError)) throw error;
715
- live = error.live;
716
- }
717
- const resolution = resolveLostWrite(live, expected, next);
718
- if (resolution === 'gone') {
719
- log('pending join %s: dismissed while this machine was recording %s; not recreated', entry.row.Id, next.kind);
720
- this.forget(entry);
721
- return;
722
- }
723
- if (resolution === 'adopt') {
724
- this.settle(live!);
725
- return;
726
- }
727
- expected = live!;
728
- }
729
- log('pending join %s: another machine kept changing the join; a pass in 30 s decides', entry.row.Id);
730
- this.retryPass();
731
- }
732
-
733
- private settle(join: PendingJoin): void {
734
- const entry = this.adopt(join);
735
- if (join.outcome !== null) entry.joinedHere = undefined;
736
- this.emitIfChanged(entry);
737
- }
738
-
739
- /**
740
- * Remove a finished join {@link MEMBERSHIP_INVITE_TTL_MS} after its outcome: the membership
741
- * invitation it carries is dead by then, and an app that was not running has seen the strand
742
- * through `strand:discovered`. Deferred while a write could fork the party, like every write
743
- * nothing waits on.
744
- *
745
- * NOTE: `deletePendingJoin` removes whichever incarnation is live, so a `requestJoin` of the
746
- * same invitation landing on another machine in the same instant can be removed with it. The
747
- * user asks again; revisit if that is ever seen.
748
- */
749
- private async ageOut(entry: TrackedJoin): Promise<void> {
750
- const recordedAt = entry.row.outcome?.RecordedAt;
751
- if (recordedAt === undefined || this.now() < recordedAt + MEMBERSHIP_INVITE_TTL_MS) return;
752
- if (await this.deps.deferBackgroundWrites()) {
753
- this.deferredWrites = true;
754
- return;
755
- }
756
- await this.deps.remove(entry.row.Id);
757
- log('pending join %s: removed, %d days after its outcome', entry.row.Id, MEMBERSHIP_INVITE_TTL_MS / (24 * 3600_000));
758
- this.forget(entry);
759
- }
760
-
761
- private forget(entry: TrackedJoin): void {
762
- this.cancelTimer(entry);
763
- if (this.tracked.get(entry.row.Id) === entry) this.tracked.delete(entry.row.Id);
764
- }
765
-
766
- private emitIfChanged(entry: TrackedJoin): void {
767
- if (!this.running || this.tracked.get(entry.row.Id) !== entry) return;
768
- const status = this.describe(entry.row, entry);
769
- const key = JSON.stringify(status);
770
- if (key === entry.lastEmitted) return;
771
- entry.lastEmitted = key;
772
- this.deps.emit(status);
773
- }
774
-
775
- private describe(join: PendingJoin, entry: TrackedJoin | undefined): PendingJoinStatus {
776
- const base = {
777
- id: join.Id,
778
- sAppId: this.deps.sAppIdOf(join),
779
- requestedAt: join.RequestedAt,
780
- expiresAt: join.ExpiresAt,
781
- };
782
- const { outcome } = join;
783
- if (outcome?.kind === 'joined') {
784
- return { ...base, state: 'joined', strandId: outcome.StrandId };
785
- }
786
- if (outcome?.kind === 'failed') {
787
- return { ...base, state: 'failed', failure: { code: outcome.Code, reason: outcome.Reason } };
788
- }
789
- const local = entry && entry.row.outcome === null && entry.row.RequestedAt === join.RequestedAt ? entry : undefined;
790
- if (local?.trying) {
791
- return { ...base, state: 'trying' };
792
- }
793
- if (local?.lastError && local.nextAttemptAt !== undefined) {
794
- return { ...base, state: 'waiting', nextAttemptAt: local.nextAttemptAt, lastError: local.lastError };
795
- }
796
- return { ...base, state: 'pending' };
797
- }
798
- }
1
+ /**
2
+ * The pending-join retry loop: carries on a join this party asked for through another party's
3
+ * invitation (`CadreControl.JoinRequest`, one row per invitation, with its outcome in
4
+ * `JoinSuccess` / `JoinFailure`) in the background, on every owner machine of the party, until
5
+ * the join works, the invitation is used up or expires, or the user dismisses it. The behaviour
6
+ * is described in `docs/strands/formation.md` → "Joining while the inviter is offline".
7
+ *
8
+ * `CadreNode` owns every side effect and hands this module plain functions
9
+ * ({@link PendingJoinRunnerDeps}): read the joins, hear a change to the tables they are read
10
+ * from, run one attempt (its own `formStrand`), write an outcome, say whether this machine is an
11
+ * owner, and the clock. This module owns the policy: when to read the joins, when to attempt,
12
+ * how to read an attempt's failure, and how to settle an outcome write that another machine's
13
+ * write beat.
14
+ *
15
+ * Only owner machines run it, because every pending-join write is owner-signed. Letting a
16
+ * machine without an owner key finish a join is `blocked/decide-non-owner-machine-completes-a-pending-join`;
17
+ * that changes {@link PendingJoinRunnerDeps.isOwner} and the write functions, not this loop.
18
+ */
19
+
20
+ import debug from 'debug';
21
+ import type {
22
+ FormStrandResult,
23
+ JoinOutcome,
24
+ PendingJoin,
25
+ PendingJoinStatus,
26
+ StrandFormationDisclosure,
27
+ StrandMembershipInvite
28
+ } from './types.js';
29
+ import { canonicalJson } from './canonical-json.js';
30
+ import { PendingJoinChangedError, type JoinRequestFields, type PendingJoinFields } from './control-database.js';
31
+ import { FormationPostApprovalError, FormationRejectedError, FormationUnreachableError } from './strand-formation-rejection.js';
32
+ import { formationDeadlines } from './strand-formation-deadlines.js';
33
+ import { MEMBERSHIP_INVITE_TTL_MS } from './strand-formation-manager.js';
34
+ import { scheduleRuns, type TableChangeWatch, type TableChangeWatchOptions } from './table-change-watch.js';
35
+ import { defaultTimeoutScheduler, type TimeoutScheduler } from './timeout-scheduler.js';
36
+ import { describeThrown } from './describe-thrown.js';
37
+
38
+ const log = debug('sereus:cadre:pending-join');
39
+
40
+ /**
41
+ * The longest an owner machine goes without re-reading the party's pending joins when no change
42
+ * to their tables is heard. It covers a change that arrives without a storage event, and the
43
+ * time-driven removal of a finished join, which lands up to this much late.
44
+ *
45
+ * NOTE: on a cadre larger than `CONTROL_REPLICATION_BREADTH` (16), a machine outside a join
46
+ * table's cohort hears no change event, so a dismissal or another machine's outcome reaches it
47
+ * up to this much late. The worst effect is one more attempt on a dismissed join, whose outcome
48
+ * write then finds the request gone, or a `token-spent` answer whose re-read adopts the other
49
+ * machine's outcome. A 30 s pass while any join is pending was declined: a join can stay pending
50
+ * for {@link MAX_PENDING_JOIN_MS}, and those reads are what this backstop removes. Revisit if a
51
+ * cadre above 16 machines is seen attempting dismissed joins.
52
+ */
53
+ export const PENDING_JOIN_BACKSTOP_MS = 10 * 60_000;
54
+
55
+ /** How soon a pass runs again after one failed, or after an outcome write gave up to another machine's writes. */
56
+ const PENDING_JOIN_PASS_RETRY_MS = 30_000;
57
+
58
+ /** Ceiling on the wait between two attempts of one join on one machine, before jitter. */
59
+ export const PENDING_JOIN_MAX_BACKOFF_MS = 10 * 60_000;
60
+
61
+ /**
62
+ * The longest a join is tried for. A request's `ExpiresAt` is the earlier of this and the
63
+ * invitation's own expiration, which the inviter chose.
64
+ */
65
+ export const MAX_PENDING_JOIN_MS = 30 * 24 * 3600_000;
66
+
67
+ /** Background attempts one machine runs at once. An explicit `requestJoin` does not wait for a slot. */
68
+ const MAX_BACKGROUND_ATTEMPTS = 2;
69
+
70
+ /** Each retry delay is moved by up to this fraction either way, so machines that failed together do not retry together. */
71
+ const RETRY_JITTER = 0.2;
72
+
73
+ /** Re-read-and-rewrite rounds after another machine's write won, before a pass {@link PENDING_JOIN_PASS_RETRY_MS} later decides instead. */
74
+ const MAX_OUTCOME_WRITE_ROUNDS = 3;
75
+
76
+ type AttemptError = NonNullable<PendingJoinStatus['lastError']>;
77
+
78
+ /** Which pending-join write this machine made: the request itself (an insert or a rewrite), or an outcome row for it. */
79
+ export type PendingJoinWrite = 'request' | 'outcome';
80
+
81
+ export interface PendingJoinRunnerDeps {
82
+ /** This machine's peer id; with the request id it fixes when this machine first tries a join it did not ask for. */
83
+ selfId: string;
84
+ /** `NetworkConfig.linkRoundTripMs`: the retry pace follows the formation deadlines it yields. */
85
+ linkRoundTripMs?: number;
86
+ /** Whether this machine may write pending joins now. Asked every pass. */
87
+ isOwner(): Promise<boolean>;
88
+ readRows(): Promise<PendingJoin[]>;
89
+ /** Subscribe `onChange` to the tables a pass reads. Absent: passes come from `start`, `kick`, retries and the backstop only (tests). */
90
+ watchChanges?(onChange: () => Promise<void>, options: TableChangeWatchOptions): TableChangeWatch;
91
+ /** Run a pass at least this long after the last one settled; default {@link PENDING_JOIN_BACKSTOP_MS}. */
92
+ backstopMs?: number;
93
+ readRow(id: string): Promise<PendingJoin | null>;
94
+ /** One formation attempt for the request's invitation and disclosure (`CadreNode.formStrand`). */
95
+ attempt(join: PendingJoin): Promise<FormStrandResult>;
96
+ /** `ControlDatabase.recordJoinOutcome`, owner-signed: throws `PendingJoinChangedError` when the live join is not `expected`. */
97
+ record(expected: PendingJoin, outcome: JoinOutcome): Promise<PendingJoin>;
98
+ /** `ControlDatabase.rewritePendingJoin`, owner-signed: throws `PendingJoinChangedError` when the live request is not `expectedStampId`. */
99
+ rewrite(expectedStampId: string, next: PendingJoinFields): Promise<PendingJoin>;
100
+ /** `ControlDatabase.deletePendingJoin`, owner-signed. */
101
+ remove(id: string): Promise<boolean>;
102
+ /** Whether this machine reaches no sibling now (`CadreNode.hasReachableControlSibling`), so a write it commits reaches no other machine. */
103
+ isAlone(): boolean;
104
+ /**
105
+ * Whether a write nothing waits on must wait for a reachable sibling now
106
+ * (`CadreNode.controlWriteCouldFork`): this machine reaches none while the party has other
107
+ * machines, so another owner machine writing the same tables meanwhile would fork them.
108
+ */
109
+ deferBackgroundWrites(): Promise<boolean>;
110
+ /** The sApp the request's invitation names. */
111
+ sAppIdOf(join: PendingJoin): string;
112
+ /** Every pass's joins, read by an owner machine; `CadreNode` stages the membership invitations they carry. */
113
+ observeRows(joins: readonly PendingJoin[]): void;
114
+ emit(status: PendingJoinStatus): void;
115
+ now?: () => number;
116
+ random?: () => number;
117
+ scheduler?: TimeoutScheduler;
118
+ }
119
+
120
+ /** This machine's memory of one join. Nothing here survives a restart; the rows are the durable state. */
121
+ interface TrackedJoin {
122
+ row: PendingJoin;
123
+ /** Retryable failures on this machine since the join was first seen or asked for again. */
124
+ failures: number;
125
+ timer?: unknown;
126
+ /** Due, waiting for a background attempt slot. */
127
+ queued: boolean;
128
+ /** Set while an attempt (or a re-run of its outcome write) is running. */
129
+ attempt?: Promise<'deferred' | undefined>;
130
+ trying: boolean;
131
+ nextAttemptAt?: number;
132
+ lastError?: AttemptError;
133
+ /** An earlier attempt here answered `token-spent`; the next such answer fails the join. */
134
+ spentOnce: boolean;
135
+ /** This machine's approved join, held until its outcome write lands, so a later pass rewrites it rather than attempting a spent token. */
136
+ joinedHere?: JoinOutcome;
137
+ lastEmitted?: string;
138
+ }
139
+
140
+ /** What to do after an outcome write found that another write had changed or removed the join. */
141
+ type LostWriteResolution = 'gone' | 'adopt' | 'rewrite';
142
+
143
+ /**
144
+ * A `joined` outcome replaces anything still live, since a join that happened cannot be undone
145
+ * by another machine's failure. A failure replaces a pending request of the same ask: only a
146
+ * re-issue of a request written alone writes one, unchanged, so it decides nothing. Any other
147
+ * live join wins, and a fresh request is then decided again by the loop.
148
+ */
149
+ function resolveLostWrite(live: PendingJoin | null, expected: PendingJoin, next: JoinOutcome): LostWriteResolution {
150
+ if (live === null) return 'gone';
151
+ if (live.outcome?.kind === 'joined') return 'adopt';
152
+ if (next.kind === 'joined') return 'rewrite';
153
+ return live.outcome === null && live.RequestedAt === expected.RequestedAt ? 'rewrite' : 'adopt';
154
+ }
155
+
156
+ /**
157
+ * The request a `requestJoin` writes: tried until the invitation's own expiration or
158
+ * {@link MAX_PENDING_JOIN_MS} from now, whichever comes first.
159
+ */
160
+ export function requestedPendingJoin(
161
+ id: string,
162
+ encodedInvitation: string,
163
+ disclosure: StrandFormationDisclosure,
164
+ invitationExpiresAt: number,
165
+ now: number
166
+ ): JoinRequestFields {
167
+ return {
168
+ Id: id,
169
+ Invitation: encodedInvitation,
170
+ Disclosure: canonicalJson(disclosure),
171
+ RequestedAt: now,
172
+ ExpiresAt: Math.min(invitationExpiresAt, now + MAX_PENDING_JOIN_MS),
173
+ };
174
+ }
175
+
176
+ /** A request's stored disclosure, as the next attempt sends it. Owner-signed, so anything but an object is a bug. */
177
+ export function parseStoredDisclosure(join: PendingJoin): StrandFormationDisclosure {
178
+ const parsed: unknown = JSON.parse(join.Disclosure);
179
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
180
+ throw new Error(`JoinRequest ${join.Id}: the stored disclosure is not a JSON object`);
181
+ }
182
+ return parsed as StrandFormationDisclosure;
183
+ }
184
+
185
+ /** A `JoinSuccess` row's `MembershipInvite` column, or null when it is not the `{inviteKey, invitePrivateKey}` JSON the loop writes. */
186
+ export function parseStoredMembershipInvite(text: string): StrandMembershipInvite | null {
187
+ let parsed: unknown;
188
+ try {
189
+ parsed = JSON.parse(text);
190
+ } catch {
191
+ return null;
192
+ }
193
+ if (typeof parsed !== 'object' || parsed === null) return null;
194
+ const { inviteKey, invitePrivateKey } = parsed as Record<string, unknown>;
195
+ return typeof inviteKey === 'string' && typeof invitePrivateKey === 'string' ? { inviteKey, invitePrivateKey } : null;
196
+ }
197
+
198
+ /**
199
+ * The membership invitations joined requests carry that this process has not staged yet, so a
200
+ * closed strand joined on one owner machine can be seated by whichever machine launches it
201
+ * first. Joins older than {@link MEMBERSHIP_INVITE_TTL_MS} are skipped: their invitation is dead.
202
+ * `alreadyStaged` holds invite keys; a malformed column is skipped and logged.
203
+ */
204
+ export function membershipInvitesToStage(
205
+ joins: readonly PendingJoin[],
206
+ alreadyStaged: ReadonlySet<string>,
207
+ now: number
208
+ ): Array<{ rowId: string; strandId: string; invite: StrandMembershipInvite }> {
209
+ const toStage: Array<{ rowId: string; strandId: string; invite: StrandMembershipInvite }> = [];
210
+ for (const join of joins) {
211
+ const { outcome } = join;
212
+ if (outcome?.kind !== 'joined' || outcome.MembershipInvite === null) continue;
213
+ if (now >= outcome.RecordedAt + MEMBERSHIP_INVITE_TTL_MS) continue;
214
+ const invite = parseStoredMembershipInvite(outcome.MembershipInvite);
215
+ if (!invite) {
216
+ log('pending join %s: its MembershipInvite column does not parse; not staged', join.Id);
217
+ continue;
218
+ }
219
+ if (!alreadyStaged.has(invite.inviteKey)) {
220
+ toStage.push({ rowId: join.Id, strandId: outcome.StrandId, invite });
221
+ }
222
+ }
223
+ return toStage;
224
+ }
225
+
226
+ /** The join without its stamp, as a rewrite takes it. */
227
+ function fieldsOf(join: PendingJoin): PendingJoinFields {
228
+ const { StampId: _stampId, ...fields } = join;
229
+ return fields;
230
+ }
231
+
232
+ function joinedOutcome(result: FormStrandResult, now: number): JoinOutcome {
233
+ const invite = result.membershipInvite;
234
+ return {
235
+ kind: 'joined',
236
+ RecordedAt: now,
237
+ StrandId: result.strandId,
238
+ MembershipInvite: invite ? JSON.stringify({ inviteKey: invite.inviteKey, invitePrivateKey: invite.invitePrivateKey }) : null,
239
+ };
240
+ }
241
+
242
+ function failedOutcome(code: string, reason: string, now: number): JoinOutcome {
243
+ return { kind: 'failed', RecordedAt: now, Code: code, Reason: reason };
244
+ }
245
+
246
+ /** A fraction in [0, 1) fixed by `key` (32-bit FNV-1a): the same machine staggers the same join the same way every time. */
247
+ function stableFraction(key: string): number {
248
+ let hash = 0x811c9dc5;
249
+ for (let i = 0; i < key.length; i++) {
250
+ hash ^= key.charCodeAt(i);
251
+ hash = Math.imul(hash, 0x01000193);
252
+ }
253
+ return (hash >>> 0) / 0x1_0000_0000;
254
+ }
255
+
256
+ export class PendingJoinRunner {
257
+ private readonly tracked = new Map<string, TrackedJoin>();
258
+ /** Joins whose latest write by this machine committed with no sibling reachable: id → the request stamp written. */
259
+ private readonly writtenAlone = new Map<string, string>();
260
+ private readonly dueQueue: TrackedJoin[] = [];
261
+ private readonly scheduler: TimeoutScheduler;
262
+ private readonly now: () => number;
263
+ private readonly random: () => number;
264
+ /** First retry delay, and the window a join this machine did not ask for is first tried in. */
265
+ private readonly baseDelayMs: number;
266
+ /** How long a `token-spent` answer waits before its confirming attempt: long enough for a sibling's `joined` write to replicate. */
267
+ private readonly spentConfirmDelayMs: number;
268
+ private running = false;
269
+ /** Every pass runs on it, one at a time; present between {@link start} and {@link stop}. */
270
+ private watch: TableChangeWatch | null = null;
271
+ private backgroundAttempts = 0;
272
+ /** A background write was deferred ({@link PendingJoinRunnerDeps.deferBackgroundWrites}); {@link resumeDeferredWrites} runs a pass for it. */
273
+ private deferredWrites = false;
274
+
275
+ constructor(private readonly deps: PendingJoinRunnerDeps) {
276
+ this.scheduler = deps.scheduler ?? defaultTimeoutScheduler;
277
+ this.now = deps.now ?? Date.now;
278
+ this.random = deps.random ?? Math.random;
279
+ const deadlines = formationDeadlines(deps.linkRoundTripMs);
280
+ this.baseDelayMs = 2 * deadlines.dialMs;
281
+ this.spentConfirmDelayMs = 2 * deadlines.sessionMs;
282
+ }
283
+
284
+ /**
285
+ * Start passes: one at once, then one whenever a table a pass reads changes, and at the latest
286
+ * {@link PENDING_JOIN_BACKSTOP_MS} after the last. Throws when the change subscription cannot
287
+ * be made.
288
+ *
289
+ * NOTE: a pass from before a {@link stop} that is still in flight runs alongside the new
290
+ * watch's passes, since each watch keeps only its own runs to one at a time. `CadreNode` builds
291
+ * a fresh runner per start, so nothing restarts one; if something comes to, make that pass
292
+ * check which start it belongs to.
293
+ */
294
+ start(): void {
295
+ if (this.running) return;
296
+ this.watch = this.subscribe();
297
+ this.running = true;
298
+ this.watch.trigger(0);
299
+ }
300
+
301
+ /**
302
+ * Stop scheduling. Clears every timer and starts no new attempt.
303
+ *
304
+ * NOTE: an attempt already in flight is not awaited, because `formStrand` takes no abort
305
+ * signal. An approval that lands while the node stops can lose its local records; the request
306
+ * then stays pending, and the next start's attempt answers `token-spent`, which fails it after
307
+ * its confirming attempt. Honest and bounded; if it shows up in practice, give `formStrand` a
308
+ * signal and abort it here.
309
+ */
310
+ stop(): void {
311
+ this.running = false;
312
+ // A pass already in flight finishes; `running` keeps it from scheduling anything further.
313
+ this.watch?.dispose();
314
+ this.watch = null;
315
+ for (const entry of this.tracked.values()) this.cancelTimer(entry);
316
+ this.tracked.clear();
317
+ this.dueQueue.length = 0;
318
+ this.writtenAlone.clear();
319
+ this.deferredWrites = false;
320
+ }
321
+
322
+ /**
323
+ * Run a pass now, for a change the watched tables do not show (this machine's owner signer was
324
+ * just wired). A pass in flight is followed by one more.
325
+ */
326
+ kick(): void {
327
+ this.watch?.trigger(0);
328
+ }
329
+
330
+ /**
331
+ * Run a pass now if a background write was deferred while one could have forked the party
332
+ * ({@link PendingJoinRunnerDeps.deferBackgroundWrites}), so the joins it left unscheduled are
333
+ * scheduled again. Called on the control cohort's growth edge, when a sibling becomes reachable.
334
+ */
335
+ resumeDeferredWrites(): void {
336
+ if (!this.deferredWrites) return;
337
+ this.deferredWrites = false;
338
+ this.kick();
339
+ }
340
+
341
+ /**
342
+ * Try `join` on this machine at once, outside the background slots, and report the status
343
+ * after the attempt. Joins an attempt already running for it.
344
+ */
345
+ async attemptNow(join: PendingJoin): Promise<PendingJoinStatus> {
346
+ const entry = this.adopt(join);
347
+ // A background attempt already running for it may defer instead of attempting.
348
+ if (entry.row.outcome === null && await this.startAttempt(entry, false) === 'deferred') {
349
+ await this.startAttempt(entry, false);
350
+ }
351
+ return this.describe(entry.row, entry);
352
+ }
353
+
354
+ /** This machine's view of `join`: its own state, with this machine's attempt state laid over a pending one. */
355
+ statusOf(join: PendingJoin): PendingJoinStatus {
356
+ return this.describe(join, this.tracked.get(join.Id));
357
+ }
358
+
359
+ /**
360
+ * Record a pending-join write this machine made, for {@link reissueWritesMadeAlone}. A write
361
+ * made alone marks the join. A request write made connected clears the mark, since it
362
+ * carried the request; an outcome write made connected does not, since the request it names
363
+ * may still be unknown to the other machines.
364
+ */
365
+ noteWritten(join: PendingJoin, write: PendingJoinWrite): void {
366
+ if (this.deps.isAlone()) {
367
+ this.writtenAlone.set(join.Id, join.StampId);
368
+ } else if (write === 'request') {
369
+ this.writtenAlone.delete(join.Id);
370
+ }
371
+ }
372
+
373
+ /** Stop tracking a join the user dismissed. An attempt in flight finishes; its outcome write then finds the request gone. */
374
+ forgetRow(id: string): void {
375
+ const entry = this.tracked.get(id);
376
+ if (entry) this.forget(entry);
377
+ }
378
+
379
+ /**
380
+ * Re-write, with identical content under a fresh stamp, each join this machine last wrote while
381
+ * no sibling was reachable, so the other machines receive it. Called on the control cohort's
382
+ * growth edge, when a sibling becomes reachable. A join someone wrote since is left alone.
383
+ *
384
+ * NOTE: in memory only, so a join written alone by a process that stopped before it reconnected
385
+ * reaches the party only with that join's next write. A sweep of every join this machine wrote,
386
+ * on the first connection after start, would cover that, at the cost of one permanent
387
+ * `Revocation` tombstone per join per start. Revisit if other machines are seen missing such joins.
388
+ */
389
+ async reissueWritesMadeAlone(): Promise<void> {
390
+ if (this.writtenAlone.size === 0) return;
391
+ if (!(await this.deps.isOwner())) {
392
+ this.writtenAlone.clear();
393
+ return;
394
+ }
395
+ for (const [id, stampId] of [...this.writtenAlone]) {
396
+ try {
397
+ const live = await this.deps.readRow(id);
398
+ if (!live || live.StampId !== stampId) {
399
+ this.writtenAlone.delete(id);
400
+ continue;
401
+ }
402
+ const written = await this.deps.rewrite(stampId, fieldsOf(live));
403
+ this.noteWritten(written, 'request');
404
+ const entry = this.tracked.get(id);
405
+ if (entry?.row.StampId === stampId) entry.row = written;
406
+ log('pending join %s: re-issued the join written while alone', id);
407
+ } catch (error) {
408
+ log('pending join %s: re-issuing the join written while alone failed; kept for the next connection: %s', id, describeThrown(error));
409
+ }
410
+ }
411
+ }
412
+
413
+ /** The watch every pass runs on: the deps' change subscription, or a timer-only one. */
414
+ private subscribe(): TableChangeWatch {
415
+ const onChange = (): Promise<void> => this.pass();
416
+ const options: TableChangeWatchOptions = {
417
+ label: 'pending-join',
418
+ backstopMs: this.deps.backstopMs ?? PENDING_JOIN_BACKSTOP_MS,
419
+ scheduler: this.scheduler,
420
+ };
421
+ return this.deps.watchChanges?.(onChange, options) ?? scheduleRuns(onChange, options);
422
+ }
423
+
424
+ /** One pass; a failed one runs again {@link PENDING_JOIN_PASS_RETRY_MS} later. */
425
+ private async pass(): Promise<void> {
426
+ try {
427
+ await this.runPass();
428
+ } catch (error) {
429
+ log('pending-join pass failed; retried in 30 s: %s', describeThrown(error));
430
+ this.retryPass();
431
+ }
432
+ }
433
+
434
+ private retryPass(): void {
435
+ this.watch?.trigger(PENDING_JOIN_PASS_RETRY_MS);
436
+ }
437
+
438
+ private async runPass(): Promise<void> {
439
+ if (!this.running) return;
440
+ if (!(await this.deps.isOwner())) {
441
+ log('pending-join pass skipped: this machine is not an enrolled owner');
442
+ this.pauseAttempts();
443
+ return;
444
+ }
445
+ const joins = await this.deps.readRows();
446
+ if (!this.running) return;
447
+ this.deps.observeRows(joins);
448
+ const live = new Set(joins.map((join) => join.Id));
449
+ for (const entry of [...this.tracked.values()]) {
450
+ if (!live.has(entry.row.Id) && !entry.attempt) this.forget(entry);
451
+ }
452
+ for (const join of joins) {
453
+ if (!this.running) return;
454
+ try {
455
+ await this.consider(join);
456
+ } catch (error) {
457
+ log('pending join %s: this pass could not handle it; retried in 30 s: %s', join.Id, describeThrown(error));
458
+ this.retryPass();
459
+ }
460
+ }
461
+ }
462
+
463
+ /** Drop every scheduled attempt; the first pass that finds this machine an owner again schedules afresh. */
464
+ private pauseAttempts(): void {
465
+ for (const entry of this.tracked.values()) {
466
+ this.cancelTimer(entry);
467
+ entry.nextAttemptAt = undefined;
468
+ }
469
+ for (const entry of this.dueQueue) entry.queued = false;
470
+ this.dueQueue.length = 0;
471
+ }
472
+
473
+ /** Bring one read join into this machine's schedule. */
474
+ private async consider(join: PendingJoin): Promise<void> {
475
+ const entry = this.adopt(join);
476
+ if (entry.attempt) return;
477
+ if (entry.row.outcome !== null) {
478
+ this.emitIfChanged(entry);
479
+ await this.ageOut(entry);
480
+ return;
481
+ }
482
+ if (entry.joinedHere || this.now() >= entry.row.ExpiresAt) {
483
+ await this.startAttempt(entry, true);
484
+ return;
485
+ }
486
+ if (entry.timer === undefined && !entry.queued) {
487
+ this.scheduleAttempt(entry, Math.floor(stableFraction(`${this.deps.selfId}|${entry.row.Id}`) * this.baseDelayMs));
488
+ }
489
+ this.emitIfChanged(entry);
490
+ }
491
+
492
+ /**
493
+ * The tracked entry for `join`, updated to it. A join asked for again (`RequestedAt` changed)
494
+ * starts this machine's counting over; a finished join stops its schedule.
495
+ */
496
+ private adopt(join: PendingJoin): TrackedJoin {
497
+ const entry = this.tracked.get(join.Id);
498
+ if (!entry) {
499
+ const fresh: TrackedJoin = { row: join, failures: 0, queued: false, trying: false, spentOnce: false };
500
+ this.tracked.set(join.Id, fresh);
501
+ return fresh;
502
+ }
503
+ if (entry.row.StampId === join.StampId && entry.row.outcome?.kind === join.outcome?.kind) return entry;
504
+ if (join.outcome !== null || entry.row.RequestedAt !== join.RequestedAt) {
505
+ this.cancelTimer(entry);
506
+ entry.failures = 0;
507
+ entry.spentOnce = false;
508
+ entry.lastError = undefined;
509
+ entry.nextAttemptAt = undefined;
510
+ }
511
+ if (join.outcome?.kind === 'joined') entry.joinedHere = undefined;
512
+ entry.row = join;
513
+ return entry;
514
+ }
515
+
516
+ private scheduleAttempt(entry: TrackedJoin, delayMs: number): void {
517
+ if (!this.running) return;
518
+ this.cancelTimer(entry);
519
+ const now = this.now();
520
+ // A request already past its expiry keeps the full delay: its due attempt is an outcome
521
+ // write, and clamping to a past expiry would retry a failing write with no wait at all.
522
+ const at = now < entry.row.ExpiresAt ? Math.min(now + delayMs, entry.row.ExpiresAt) : now + delayMs;
523
+ entry.nextAttemptAt = at;
524
+ entry.timer = this.scheduler.setTimeout(() => {
525
+ entry.timer = undefined;
526
+ this.enqueue(entry);
527
+ }, Math.max(0, at - this.now()));
528
+ }
529
+
530
+ private cancelTimer(entry: TrackedJoin): void {
531
+ if (entry.timer !== undefined) {
532
+ this.scheduler.clearTimeout(entry.timer);
533
+ entry.timer = undefined;
534
+ }
535
+ }
536
+
537
+ private enqueue(entry: TrackedJoin): void {
538
+ if (!this.running || this.tracked.get(entry.row.Id) !== entry || entry.queued) return;
539
+ entry.queued = true;
540
+ this.dueQueue.push(entry);
541
+ this.pump();
542
+ }
543
+
544
+ /** Start due attempts while background slots are free. */
545
+ private pump(): void {
546
+ while (this.running && this.backgroundAttempts < MAX_BACKGROUND_ATTEMPTS && this.dueQueue.length > 0) {
547
+ const entry = this.dueQueue.shift()!;
548
+ entry.queued = false;
549
+ if (entry.attempt || this.tracked.get(entry.row.Id) !== entry) continue;
550
+ this.backgroundAttempts++;
551
+ void this.startAttempt(entry, true).finally(() => {
552
+ this.backgroundAttempts--;
553
+ this.pump();
554
+ });
555
+ }
556
+ }
557
+
558
+ /**
559
+ * Run one attempt for `entry`, or join the one already running. A `background` attempt (one no
560
+ * `requestJoin` asked for) is deferred while a write could fork the party ({@link attemptOnce}),
561
+ * and then resolves `'deferred'`, also for a caller that joined it. Never rejects.
562
+ */
563
+ private startAttempt(entry: TrackedJoin, background: boolean): Promise<'deferred' | undefined> {
564
+ if (entry.attempt) return entry.attempt;
565
+ this.cancelTimer(entry);
566
+ if (entry.queued) {
567
+ entry.queued = false;
568
+ this.dueQueue.splice(this.dueQueue.indexOf(entry), 1);
569
+ }
570
+ // NOTE: only a join is held for re-writing (`joinedHere`); a failed write of a final failure is
571
+ // retried by attempting again, so a `local` failure whose write failed ends up recorded as
572
+ // `token-spent`. If apps come to branch on that code, hold failures the same way.
573
+ const run = this.attemptOnce(entry, background)
574
+ .catch((error: unknown) => {
575
+ entry.trying = false;
576
+ log('pending join %s: attempt failed on this machine: %s', entry.row.Id, describeThrown(error));
577
+ if (entry.row.outcome === null && this.tracked.get(entry.row.Id) === entry) {
578
+ this.retryLater(entry, { code: 'local', reason: describeThrown(error) });
579
+ }
580
+ return undefined;
581
+ })
582
+ .finally(() => {
583
+ entry.attempt = undefined;
584
+ });
585
+ entry.attempt = run;
586
+ return run;
587
+ }
588
+
589
+ /**
590
+ * One attempt, or the write it is due. A join this machine already made is recorded whatever
591
+ * else holds: kept only in memory, it would be lost with a restart, and the next start's
592
+ * attempt would fail the join as `token-spent`. Otherwise a background attempt, and the
593
+ * `expired` outcome due in its place, are deferred while a write could fork the party.
594
+ */
595
+ private async attemptOnce(entry: TrackedJoin, background: boolean): Promise<'deferred' | undefined> {
596
+ if (entry.row.outcome !== null) return;
597
+ if (entry.joinedHere) {
598
+ await this.writeOutcome(entry, entry.joinedHere);
599
+ return;
600
+ }
601
+ if (background && await this.deps.deferBackgroundWrites()) {
602
+ this.deferAttempt(entry);
603
+ return 'deferred';
604
+ }
605
+ if (this.now() >= entry.row.ExpiresAt) {
606
+ const reason = `No attempt starts after ${new Date(entry.row.ExpiresAt).toISOString()}`;
607
+ await this.writeOutcome(entry, failedOutcome('expired', reason, this.now()));
608
+ return;
609
+ }
610
+ entry.trying = true;
611
+ entry.nextAttemptAt = undefined;
612
+ this.emitIfChanged(entry);
613
+ let result: FormStrandResult;
614
+ try {
615
+ result = await this.deps.attempt(entry.row);
616
+ } catch (error) {
617
+ entry.trying = false;
618
+ await this.onAttemptFailed(entry, error);
619
+ return;
620
+ }
621
+ entry.trying = false;
622
+ log('pending join %s: approved, strand %s', entry.row.Id, result.strandId);
623
+ entry.joinedHere = joinedOutcome(result, this.now());
624
+ await this.writeOutcome(entry, entry.joinedHere);
625
+ }
626
+
627
+ /** Leave `entry` unscheduled; the pass {@link resumeDeferredWrites} runs schedules it again. */
628
+ private deferAttempt(entry: TrackedJoin): void {
629
+ entry.nextAttemptAt = undefined;
630
+ this.deferredWrites = true;
631
+ log('pending join %s: background attempt deferred until a sibling is reachable', entry.row.Id);
632
+ this.emitIfChanged(entry);
633
+ }
634
+
635
+ /** Read a failed attempt: retry, confirm a spent token, or fail the join. */
636
+ private async onAttemptFailed(entry: TrackedJoin, error: unknown): Promise<void> {
637
+ const now = this.now();
638
+ if (error instanceof FormationRejectedError && error.code === 'token-spent') {
639
+ await this.onSpent(entry, error);
640
+ } else if (error instanceof FormationPostApprovalError) {
641
+ log('pending join %s: approved, then a step on this machine failed; failing the join', entry.row.Id);
642
+ await this.writeOutcome(entry, failedOutcome('local', error.message, now));
643
+ } else if (error instanceof FormationRejectedError && !error.retryable) {
644
+ log('pending join %s: refused (%s); failing the join', entry.row.Id, error.code);
645
+ await this.writeOutcome(entry, failedOutcome(error.code, error.reason, now));
646
+ } else if (error instanceof FormationRejectedError) {
647
+ this.retryLater(entry, { code: error.code, reason: error.reason });
648
+ } else if (error instanceof FormationUnreachableError) {
649
+ this.retryLater(entry, { code: 'unreachable', reason: error.message });
650
+ } else {
651
+ // Retrying is safe: nothing is attempted after the request's expiry.
652
+ log('pending join %s: attempt threw an unexpected error; retrying: %s', entry.row.Id, describeThrown(error));
653
+ this.retryLater(entry, { code: 'local', reason: describeThrown(error) });
654
+ }
655
+ }
656
+
657
+ /**
658
+ * A `token-spent` answer may mean another owner machine of this party won the same
659
+ * invitation. Adopt its outcome if the join already shows one; otherwise confirm once, after
660
+ * long enough for that machine's `joined` write to arrive, before failing the join.
661
+ */
662
+ private async onSpent(entry: TrackedJoin, error: FormationRejectedError): Promise<void> {
663
+ const live = await this.deps.readRow(entry.row.Id);
664
+ if (!live) {
665
+ this.forget(entry);
666
+ return;
667
+ }
668
+ this.adopt(live);
669
+ if (live.outcome !== null) {
670
+ this.emitIfChanged(entry);
671
+ return;
672
+ }
673
+ if (entry.spentOnce) {
674
+ log('pending join %s: token spent again after the confirming wait; failing the join', entry.row.Id);
675
+ await this.writeOutcome(entry, failedOutcome('token-spent', error.reason, this.now()));
676
+ return;
677
+ }
678
+ entry.spentOnce = true;
679
+ entry.lastError = { code: 'token-spent', reason: error.reason };
680
+ this.scheduleAttempt(entry, this.spentConfirmDelayMs);
681
+ this.emitIfChanged(entry);
682
+ }
683
+
684
+ private retryLater(entry: TrackedJoin, lastError: AttemptError): void {
685
+ entry.failures++;
686
+ entry.lastError = lastError;
687
+ this.scheduleAttempt(entry, this.backoffMs(entry.failures));
688
+ this.emitIfChanged(entry);
689
+ }
690
+
691
+ /** `min(base × 2^(n−1), max)`, moved by up to ±{@link RETRY_JITTER}. */
692
+ private backoffMs(failures: number): number {
693
+ const capped = Math.min(this.baseDelayMs * 2 ** (failures - 1), PENDING_JOIN_MAX_BACKOFF_MS);
694
+ return Math.round(capped * (1 + (this.random() * 2 - 1) * RETRY_JITTER));
695
+ }
696
+
697
+ /**
698
+ * Record `next` on the join this machine last read. When another write got there first, settle
699
+ * by {@link resolveLostWrite} from the live join the refusal carries. A join the user dismissed
700
+ * meanwhile is not recreated; a join this machine made is still remembered machine-locally, as
701
+ * every `formStrand` join is.
702
+ */
703
+ private async writeOutcome(entry: TrackedJoin, next: JoinOutcome): Promise<void> {
704
+ let expected = entry.row;
705
+ for (let round = 0; round < MAX_OUTCOME_WRITE_ROUNDS; round++) {
706
+ let live: PendingJoin | null;
707
+ try {
708
+ const written = await this.deps.record(expected, next);
709
+ this.noteWritten(written, 'outcome');
710
+ this.settle(written);
711
+ log('pending join %s: recorded %s', entry.row.Id, next.kind === 'failed' ? `failed (${next.Code})` : 'joined');
712
+ return;
713
+ } catch (error) {
714
+ if (!(error instanceof PendingJoinChangedError)) throw error;
715
+ live = error.live;
716
+ }
717
+ const resolution = resolveLostWrite(live, expected, next);
718
+ if (resolution === 'gone') {
719
+ log('pending join %s: dismissed while this machine was recording %s; not recreated', entry.row.Id, next.kind);
720
+ this.forget(entry);
721
+ return;
722
+ }
723
+ if (resolution === 'adopt') {
724
+ this.settle(live!);
725
+ return;
726
+ }
727
+ expected = live!;
728
+ }
729
+ log('pending join %s: another machine kept changing the join; a pass in 30 s decides', entry.row.Id);
730
+ this.retryPass();
731
+ }
732
+
733
+ private settle(join: PendingJoin): void {
734
+ const entry = this.adopt(join);
735
+ if (join.outcome !== null) entry.joinedHere = undefined;
736
+ this.emitIfChanged(entry);
737
+ }
738
+
739
+ /**
740
+ * Remove a finished join {@link MEMBERSHIP_INVITE_TTL_MS} after its outcome: the membership
741
+ * invitation it carries is dead by then, and an app that was not running has seen the strand
742
+ * through `strand:discovered`. Deferred while a write could fork the party, like every write
743
+ * nothing waits on.
744
+ *
745
+ * NOTE: `deletePendingJoin` removes whichever incarnation is live, so a `requestJoin` of the
746
+ * same invitation landing on another machine in the same instant can be removed with it. The
747
+ * user asks again; revisit if that is ever seen.
748
+ */
749
+ private async ageOut(entry: TrackedJoin): Promise<void> {
750
+ const recordedAt = entry.row.outcome?.RecordedAt;
751
+ if (recordedAt === undefined || this.now() < recordedAt + MEMBERSHIP_INVITE_TTL_MS) return;
752
+ if (await this.deps.deferBackgroundWrites()) {
753
+ this.deferredWrites = true;
754
+ return;
755
+ }
756
+ await this.deps.remove(entry.row.Id);
757
+ log('pending join %s: removed, %d days after its outcome', entry.row.Id, MEMBERSHIP_INVITE_TTL_MS / (24 * 3600_000));
758
+ this.forget(entry);
759
+ }
760
+
761
+ private forget(entry: TrackedJoin): void {
762
+ this.cancelTimer(entry);
763
+ if (this.tracked.get(entry.row.Id) === entry) this.tracked.delete(entry.row.Id);
764
+ }
765
+
766
+ private emitIfChanged(entry: TrackedJoin): void {
767
+ if (!this.running || this.tracked.get(entry.row.Id) !== entry) return;
768
+ const status = this.describe(entry.row, entry);
769
+ const key = JSON.stringify(status);
770
+ if (key === entry.lastEmitted) return;
771
+ entry.lastEmitted = key;
772
+ this.deps.emit(status);
773
+ }
774
+
775
+ private describe(join: PendingJoin, entry: TrackedJoin | undefined): PendingJoinStatus {
776
+ const base = {
777
+ id: join.Id,
778
+ sAppId: this.deps.sAppIdOf(join),
779
+ requestedAt: join.RequestedAt,
780
+ expiresAt: join.ExpiresAt,
781
+ };
782
+ const { outcome } = join;
783
+ if (outcome?.kind === 'joined') {
784
+ return { ...base, state: 'joined', strandId: outcome.StrandId };
785
+ }
786
+ if (outcome?.kind === 'failed') {
787
+ return { ...base, state: 'failed', failure: { code: outcome.Code, reason: outcome.Reason } };
788
+ }
789
+ const local = entry && entry.row.outcome === null && entry.row.RequestedAt === join.RequestedAt ? entry : undefined;
790
+ if (local?.trying) {
791
+ return { ...base, state: 'trying' };
792
+ }
793
+ if (local?.lastError && local.nextAttemptAt !== undefined) {
794
+ return { ...base, state: 'waiting', nextAttemptAt: local.nextAttemptAt, lastError: local.lastError };
795
+ }
796
+ return { ...base, state: 'pending' };
797
+ }
798
+ }