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