@serfab/cadre-client 2.0.0 → 2.1.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.
@@ -1,206 +1,359 @@
1
- /**
2
- * Invitations over a running node: which addresses one names (`bootstrap.ts` plans, this
3
- * gathers the evidence), whether it is ready to hand out, and what it says in words.
4
- *
5
- * The evidence for each cadron (each other machine of the party), best first:
6
- * - `connection`: a connection this device opened to it with no relay hop is open now;
7
- * - `record`: its signed, recently published record (`resolvePeerAddrs`), every address;
8
- * - `claim`: what this device was handed when it claimed it (cadre-core's bootstrap peer store),
9
- * which is all there is in the minute before the cadron's first record arrives. cadre-core's
10
- * own invitation leaves such a cadron out altogether.
11
- *
12
- * READINESS. A new strand's copy is on a cadron once a commit of the strand is held elsewhere
13
- * (`strand:commit-held`, or a commit reported `heldElsewhere`). The cadron may still be starting
14
- * then, but it holds the strand's data and finishes starting on its own. Its `StrandPeer` row is
15
- * not enough: it is written before the cadron's copy is live, and a join answered by a cadron
16
- * whose copy is not live is refused `host-strand-unavailable`.
17
- * WORKAROUND(sereus: a readiness signal for an invitation): read from commit durability.
18
- */
19
- import { multiaddr } from '@multiformats/multiaddr';
20
- import type { CadreNode } from '@serfab/cadre-core';
21
- import { CADRON_PREFERENCES_FORMAT, normalizePreferences, planBootstrap, type CadronCandidate, type CadronPreferences } from '../bootstrap.js';
22
- import { describeInvitation, destinationPeerId } from '../invitation-text.js';
23
- import type { CadreMachine, InvitationReadiness, InvitationsModel } from '../model.js';
24
- import { cadreAttempt, CadreFailure, describeThrown, withTimeout } from '../result.js';
25
- import type { CadreHost } from './host.js';
26
-
27
- /** `addr` ending in `/p2p/<peerId>` (a claim's or a connection's address may not); unchanged when it does not parse. */
28
- function withPeer(addr: string, peerId: string): string {
29
- try {
30
- const ma = multiaddr(addr);
31
- return ma.getComponents().at(-1)?.value === peerId ? ma.toString() : ma.encapsulate(`/p2p/${peerId}`).toString();
32
- } catch {
33
- return addr;
34
- }
35
- }
36
-
37
- export interface InvitationsDeps {
38
- host: CadreHost;
39
- /** The person's cadron list, as the cadre screen has it; empty when it cannot be read. */
40
- machines(): Promise<CadreMachine[]>;
41
- controlReadMs: number;
42
- log: { info(...args: unknown[]): void; warn(...args: unknown[]): void };
43
- }
44
-
45
- export function createInvitations({ host, machines, controlReadMs, log }: InvitationsDeps): {
46
- invitations: InvitationsModel;
47
- onChange(listener: () => void): () => void;
48
- } {
49
- const listeners = new Set<() => void>();
50
- const changed = () => { for (const l of [...listeners]) l(); };
51
-
52
- // Preferences: per device, in the host's slot. Without one, kept in memory for the session.
53
- let prefs: CadronPreferences | null = null;
54
- // One first read, however many callers ask at once.
55
- let loading: Promise<CadronPreferences> | null = null;
56
- function loadPrefs(): Promise<CadronPreferences> {
57
- if (prefs) return Promise.resolve(prefs);
58
- loading ??= (async () => {
59
- let raw: Partial<CadronPreferences> | null = null;
60
- try {
61
- const text = await host.preferences?.load();
62
- raw = text ? JSON.parse(text) as Partial<CadronPreferences> : null;
63
- } catch (err) {
64
- log.warn('[cadre-client] cadron preferences unreadable; using defaults:', describeThrown(err));
65
- }
66
- prefs ??= normalizePreferences(raw);
67
- return prefs;
68
- })();
69
- return loading;
70
- }
71
- // Writes one after another: each merges into the result of the one before, so two changes made
72
- // in quick succession (two stars) both stay.
73
- let writing: Promise<unknown> = Promise.resolve();
74
-
75
- // Strands with a commit held elsewhere this session.
76
- const held = new Set<string>();
77
- const markHeld = (strandId: string) => {
78
- if (held.has(strandId)) return;
79
- held.add(strandId);
80
- changed();
81
- };
82
- host.node.on('strand:commit-durability', d => { if (d.heldElsewhere) markHeld(d.strandId); });
83
- host.node.on('strand:commit-held', d => markHeld(d.strandId));
84
-
85
- // Established strands: how many other cadrons serve each (their `StrandPeer` rows), read in
86
- // the background and cached; null while unknown.
87
- const serving = new Map<string, number | null>();
88
- function servingOthers(node: CadreNode, strandId: string): number | null {
89
- if (!serving.has(strandId)) {
90
- serving.set(strandId, null);
91
- const self = node.peerId?.toString();
92
- void withTimeout(node.getControlDatabase()?.queryStrandPeers(strandId) ?? Promise.resolve([]), controlReadMs, 'queryStrandPeers')
93
- .then(rows => { serving.set(strandId, rows.filter(r => r.peerId !== self && r.role === null).length); changed(); })
94
- .catch(() => { serving.delete(strandId); });
95
- }
96
- return serving.get(strandId) ?? null;
97
- }
98
- // A cadron coming or going changes who serves: forget the cached counts.
99
- host.node.on('control:connected', () => { serving.clear(); changed(); });
100
-
101
- async function candidates(node: CadreNode): Promise<CadronCandidate[]> {
102
- const machines = await withTimeout(node.listMachines(), controlReadMs, 'listMachines').catch(() => []);
103
- const claimed = node.getBootstrapPeerStore()?.all() ?? new Map<string, { addrs: string[] }>();
104
- const connections = node.getControlNode()?.getConnections() ?? [];
105
- const others = machines.filter(m => !m.isSelf && m.trusted);
106
- return Promise.all(others.map(async (m): Promise<CadronCandidate> => {
107
- const addrs: CadronCandidate['addrs'][number][] = [];
108
- const record = await withTimeout(node.resolvePeerAddrs(m.peerId), controlReadMs, 'resolvePeerAddrs').catch(() => []);
109
- for (const a of record) addrs.push({ addr: withPeer(a.toString(), m.peerId), source: 'record' });
110
- // WORKAROUND(sereus: name a just-claimed machine): until its first record arrives, what its
111
- // node code carried. cadre-core's own invitation leaves such a machine out.
112
- for (const a of claimed.get(m.peerId)?.addrs ?? []) addrs.push({ addr: withPeer(a, m.peerId), source: 'claim' });
113
- for (const c of connections) {
114
- const remote = c.remoteAddr.toString();
115
- if (c.remotePeer.toString() !== m.peerId || c.direction !== 'outbound' || c.limits !== undefined || remote.includes('/p2p-circuit')) continue;
116
- addrs.push({ addr: withPeer(remote, m.peerId), source: 'connection' });
117
- }
118
- return { peerId: m.peerId, alwaysOn: m.alwaysOn === true, lastPublishedAt: m.lastPublishedAt, addrs };
119
- }));
120
- }
121
-
122
- const requireNode = (): CadreNode => {
123
- const node = host.node.node;
124
- if (!node) throw new CadreFailure('unavailable', 'The cadre node is not running yet.');
125
- return node;
126
- };
127
-
128
- async function plan() {
129
- const node = requireNode();
130
- return planBootstrap({
131
- cadrons: await candidates(node),
132
- thisDevice: { peerId: node.peerId?.toString() ?? '', addrs: node.getMultiaddrs().map(a => a.toString()) },
133
- prefs: await loadPrefs(),
134
- });
135
- }
136
-
137
- const invitations: InvitationsModel = {
138
- preferences: loadPrefs,
139
-
140
- setPreferences: changes => {
141
- const write = writing.then(() => cadreAttempt(async () => {
142
- const next = normalizePreferences({ ...(await loadPrefs()), ...changes });
143
- if (host.preferences) await host.preferences.save(JSON.stringify({ format: CADRON_PREFERENCES_FORMAT, ...next }));
144
- prefs = next;
145
- changed();
146
- return next;
147
- }));
148
- writing = write;
149
- return write;
150
- },
151
-
152
- bootstrapPlan: () => cadreAttempt(plan),
153
-
154
- // WORKAROUND(sereus: an option on `createOpenInvitation`): the list is replaced after minting,
155
- // before the app encodes it. It is not signed; the responder checks only the token.
156
- async withBootstrap(invitation) {
157
- try {
158
- const { entries, warnings } = await plan();
159
- if (entries.length === 0) return invitation;
160
- if (warnings.length) log.info('[cadre-client] invitation bootstrap:', warnings.join(', '));
161
- return { ...invitation, bootstrap: entries.map(e => e.addr) };
162
- } catch (err) {
163
- log.warn('[cadre-client] kept cadre-core\'s bootstrap list:', err instanceof Error ? err.message : err);
164
- return invitation;
165
- }
166
- },
167
-
168
- readiness(strandId, opts = {}): InvitationReadiness {
169
- if (held.has(strandId)) return 'ready';
170
- const node = host.node.node;
171
- if (!node) return 'waiting';
172
- const others = servingOthers(node, strandId);
173
- if (opts.newStrand) return others === 0 ? 'no-cadron' : 'waiting';
174
- if (others === null) return 'waiting';
175
- return others > 0 ? 'ready' : 'no-cadron';
176
- },
177
-
178
- describe: (token, link) => cadreAttempt(async () => {
179
- const node = requireNode();
180
- const decoded = node.decodeInvitation(token);
181
- const [{ names, maxAddrs }, list, now] = await Promise.all([
182
- loadPrefs(),
183
- machines(),
184
- plan().catch(() => ({ entries: [], others: [] })),
185
- ]);
186
- return describeInvitation(decoded, {
187
- link: link ?? token, names, thisDevicePeerId: node.peerId?.toString() ?? null,
188
- machines: list, others: [...now.entries, ...now.others].map(e => e.addr), maxAddrs,
189
- });
190
- }),
191
-
192
- // WORKAROUND(sereus: an option on `createOpenInvitation`), as `withBootstrap`.
193
- rebootstrap: (token, addrs) => cadreAttempt(async () => {
194
- const node = requireNode();
195
- if (addrs.length === 0) throw new CadreFailure('invalid-address', 'An invitation must name at least one address.');
196
- if (addrs.some(a => !destinationPeerId(a))) throw new CadreFailure('invalid-address', 'An address does not end in the peer it reaches.');
197
- return node.encodeInvitation({ ...node.decodeInvitation(token), bootstrap: [...new Set(addrs)] });
198
- }),
199
- };
200
-
201
- return {
202
- invitations,
203
- onChange(listener) { listeners.add(listener); return () => listeners.delete(listener); },
204
- };
205
- }
206
-
1
+ /**
2
+ * Invitations over a running node: which addresses one names (`bootstrap.ts` plans, this
3
+ * gathers the evidence), whether it is ready to hand out, and what it says in words.
4
+ *
5
+ * The evidence for each cadron (each other machine of the party), best first:
6
+ * - `connection`: a connection this device opened to it with no relay hop is open now;
7
+ * - `record`: its signed, recently published record (`resolvePeerAddrs`), every address;
8
+ * - `claim`: what this device was handed when it claimed it (cadre-core's bootstrap peer store),
9
+ * which is all there is in the minute before the cadron's first record arrives. cadre-core's
10
+ * own invitation leaves such a cadron out altogether.
11
+ *
12
+ * READINESS comes from cadre-core's probe of the machines an invitation names
13
+ * (`CadreNode.readInvitationReadiness`), which asks each of them whether it could answer a
14
+ * redemption of that invitation right now. Nothing here infers it from replication: this module
15
+ * keeps the probe's answer per token, asks again on cadre-core's ladder while the answer is
16
+ * still `waiting`, and reports which of the five things the machines said they are missing.
17
+ */
18
+ import { multiaddr } from '@multiformats/multiaddr';
19
+ import { nextFormationReadyPoll, type CadreNode, type FormationReadinessGap, type FormationReadinessReport, type MachineFormationReadiness } from '@serfab/cadre-core';
20
+ import { CADRON_PREFERENCES_FORMAT, normalizePreferences, planBootstrap, type CadronCandidate, type CadronPreferences } from '../bootstrap.js';
21
+ import { describeInvitation, destinationPeerId } from '../invitation-text.js';
22
+ import type { CadreMachine, InvitationReadiness, InvitationsModel } from '../model.js';
23
+ import { cadreAttempt, CadreFailure, describeThrown, withTimeout } from '../result.js';
24
+ import type { CadreHost } from './host.js';
25
+
26
+ /** `addr` ending in `/p2p/<peerId>` (a claim's or a connection's address may not); unchanged when it does not parse. */
27
+ function withPeer(addr: string, peerId: string): string {
28
+ try {
29
+ const ma = multiaddr(addr);
30
+ return ma.getComponents().at(-1)?.value === peerId ? ma.toString() : ma.encapsulate(`/p2p/${peerId}`).toString();
31
+ } catch {
32
+ return addr;
33
+ }
34
+ }
35
+
36
+ /** The answer before a probe has landed, and when there is no node to probe with. */
37
+ const NOT_YET: InvitationReadiness = { state: 'waiting', missing: [] };
38
+
39
+ /** Each gap the OTHER machines reported, once, in the order they reported it. */
40
+ function missingAcross(machines: readonly MachineFormationReadiness[]): FormationReadinessGap[] {
41
+ const gaps = new Set<FormationReadinessGap>();
42
+ for (const machine of machines) {
43
+ if (!machine.self) for (const gap of machine.gaps) gaps.add(gap);
44
+ }
45
+ return [...gaps];
46
+ }
47
+
48
+ /**
49
+ * cadre-core's per-machine report as one answer about the invitation.
50
+ *
51
+ * `spent` is read first: a machine holding the invitation's record and reading it dead settles
52
+ * the question, and a gap another machine reports cannot change that. `no-cadron` is the
53
+ * invitation naming no machine but this one, which is settled too — the machines probed are the
54
+ * ones its bootstrap list names, and that list cannot grow after minting.
55
+ */
56
+ function readinessOf(report: FormationReadinessReport): InvitationReadiness {
57
+ if (report.machines.some(m => m.outcome === 'spent')) return { state: 'spent', missing: [] };
58
+ if (report.answerable) return { state: 'ready', missing: [] };
59
+ if (!report.machines.some(m => !m.self)) return { state: 'no-cadron', missing: [] };
60
+ return { state: 'waiting', missing: missingAcross(report.machines) };
61
+ }
62
+
63
+ /** Two answers a screen would render identically, so the change signal can stay quiet. */
64
+ function sameReadiness(a: InvitationReadiness | null, b: InvitationReadiness): boolean {
65
+ return a !== null && a.state === b.state && a.missing.length === b.missing.length
66
+ && a.missing.every((gap, i) => gap === b.missing[i]);
67
+ }
68
+
69
+ /** One token's readiness: the last answer, and where its re-ask ladder stands. */
70
+ interface ReadinessProbe {
71
+ /** What the last probe answered; null until the first one lands. */
72
+ answer: InvitationReadiness | null;
73
+ /** Probes taken, which sets the ladder's next gap (`nextFormationReadyPoll`). */
74
+ asks: number;
75
+ /** A probe is in flight. */
76
+ asking: boolean;
77
+ /** The ladder's next ask, scheduled; null when none is. */
78
+ timer: ReturnType<typeof setTimeout> | null;
79
+ /** When the last probe landed (epoch ms); 0 before the first. */
80
+ at: number;
81
+ }
82
+
83
+ export interface InvitationsDeps {
84
+ host: CadreHost;
85
+ /** The person's cadron list, as the cadre screen has it; empty when it cannot be read. */
86
+ machines(): Promise<CadreMachine[]>;
87
+ controlReadMs: number;
88
+ log: { info(...args: unknown[]): void; warn(...args: unknown[]): void };
89
+ }
90
+
91
+ export function createInvitations({ host, machines, controlReadMs, log }: InvitationsDeps): {
92
+ invitations: InvitationsModel;
93
+ onChange(listener: () => void): () => void;
94
+ } {
95
+ const listeners = new Set<() => void>();
96
+ const changed = () => { for (const l of [...listeners]) l(); };
97
+
98
+ // Preferences: per device, in the host's slot. Without one, kept in memory for the session.
99
+ let prefs: CadronPreferences | null = null;
100
+ // One first read, however many callers ask at once.
101
+ let loading: Promise<CadronPreferences> | null = null;
102
+ function loadPrefs(): Promise<CadronPreferences> {
103
+ if (prefs) return Promise.resolve(prefs);
104
+ loading ??= (async () => {
105
+ let raw: Partial<CadronPreferences> | null = null;
106
+ try {
107
+ const text = await host.preferences?.load();
108
+ raw = text ? JSON.parse(text) as Partial<CadronPreferences> : null;
109
+ } catch (err) {
110
+ log.warn('[cadre-client] cadron preferences unreadable; using defaults:', describeThrown(err));
111
+ }
112
+ prefs ??= normalizePreferences(raw);
113
+ return prefs;
114
+ })();
115
+ return loading;
116
+ }
117
+ // Writes one after another: each merges into the result of the one before, so two changes made
118
+ // in quick succession (two stars) both stay.
119
+ let writing: Promise<unknown> = Promise.resolve();
120
+
121
+ // Readiness per encoded invitation: what cadre-core's probe last answered, read in the
122
+ // background and cached. Per token, because half of what it answers is whether that
123
+ // invitation's own record has reached the machine that would answer a join through it.
124
+ // NOTE: one ladder per token, and nothing coalesces two tokens of the same party — each costs
125
+ // one small control request per machine the invitation names, at most four a minute once the
126
+ // ladder tops out. Fine for an invitation screen, which shows one. If an app ever shows a list
127
+ // of pending invitations, share one ladder across them.
128
+ // NOTE: an entry is never evicted, so a session holds one small object per token it has read.
129
+ // A token is only ever re-minted by `rebootstrap`, so that is one per address the person
130
+ // toggled. If an app ever reads readiness for tokens it mints in a loop, evict by last read.
131
+ const probes = new Map<string, ReadinessProbe>();
132
+ /** `waiting` is the only answer a further probe can change. */
133
+ const settled = (probe: ReadinessProbe) => probe.answer !== null && probe.answer.state !== 'waiting';
134
+
135
+ /**
136
+ * cadre-core's probe for an encoded invitation, as a promise even for a token that will not decode.
137
+ *
138
+ * NOTE: no `withTimeout` here, unlike the control reads below. cadre-core bounds each dial it
139
+ * makes, and a probe that outran a bound of ours would still be in flight behind it; the one
140
+ * unbounded leg is its read of this machine's own control database. A probe that never settles
141
+ * leaves the token reading `waiting` with its ladder stopped. Bound it here if that is ever seen.
142
+ */
143
+ async function askReadiness(node: CadreNode, token: string): Promise<FormationReadinessReport> {
144
+ return await node.readInvitationReadiness(node.decodeInvitation(token));
145
+ }
146
+
147
+ /** The cached probe for `token`, carrying its ladder on before the answer is read. */
148
+ function probeFor(node: CadreNode, token: string): ReadinessProbe {
149
+ const probe = probes.get(token) ?? { answer: null, asks: 0, asking: false, timer: null, at: 0 };
150
+ probes.set(token, probe);
151
+ ladder(node, token, probe);
152
+ return probe;
153
+ }
154
+
155
+ /**
156
+ * Ask again while the answer is still `waiting`, each ask no sooner than cadre-core's own
157
+ * ladder allows (`nextFormationReadyPoll`: two seconds doubling to fifteen) — the one cadence
158
+ * there is, so the client adds none of its own. An ask the ladder allows now is made at once,
159
+ * which is what answers the first read for a token. A later one is scheduled only while
160
+ * something is watching, because an answer nothing listens for has nowhere to go; the next
161
+ * read, or the next listener, picks the ladder up where it stopped.
162
+ */
163
+ function ladder(node: CadreNode, token: string, probe: ReadinessProbe): void {
164
+ if (probe.asking || probe.timer !== null || settled(probe)) return;
165
+ const waitMs = Math.max(0, probe.at + nextFormationReadyPoll(probe.asks) - Date.now());
166
+ if (waitMs === 0) {
167
+ ask(node, token, probe);
168
+ return;
169
+ }
170
+ if (listeners.size === 0) return;
171
+ probe.timer = setTimeout(() => {
172
+ probe.timer = null;
173
+ if (probes.get(token) === probe && listeners.size > 0) ladder(node, token, probe);
174
+ }, waitMs);
175
+ }
176
+
177
+ /** Cancel a scheduled re-ask, so no timer outlives what wanted its answer. */
178
+ function unschedule(probe: ReadinessProbe): void {
179
+ if (probe.timer === null) return;
180
+ clearTimeout(probe.timer);
181
+ probe.timer = null;
182
+ }
183
+
184
+ function ask(node: CadreNode, token: string, probe: ReadinessProbe): void {
185
+ probe.asking = true;
186
+ void askReadiness(node, token).then(
187
+ report => keep(node, token, probe, readinessOf(report)),
188
+ err => {
189
+ // A failed read forgets its entry: the next read asks again, and a failure is never
190
+ // reported as an answer. Never log the token itself.
191
+ // NOTE: forgetting also drops the ladder's backoff, so a probe that keeps throwing is
192
+ // re-asked — and warns — once per read rather than on a climbing gap. Reads are driven
193
+ // by the change signal, so that is bounded in practice. If a persistent failure ever
194
+ // shows up as a run of warnings, keep the entry and carry `asks` on instead of deleting.
195
+ if (probes.get(token) === probe) probes.delete(token);
196
+ log.warn('[cadre-client] an invitation\'s readiness could not be read:', describeThrown(err));
197
+ },
198
+ );
199
+ }
200
+
201
+ /**
202
+ * Keep what a probe answered, and tell the app only when it differs from the answer before:
203
+ * the ladder asks every couple of seconds while a machine is still catching up, and a screen
204
+ * has nothing to re-render for an unchanged answer.
205
+ */
206
+ function keep(node: CadreNode, token: string, probe: ReadinessProbe, answer: InvitationReadiness): void {
207
+ if (probes.get(token) !== probe) return; // forgotten while the probe was in flight
208
+ const differs = !sameReadiness(probe.answer, answer);
209
+ probe.asking = false;
210
+ probe.asks += 1;
211
+ probe.at = Date.now();
212
+ if (differs) {
213
+ probe.answer = answer;
214
+ changed();
215
+ }
216
+ ladder(node, token, probe);
217
+ }
218
+
219
+ /** Something is watching again: carry on every ladder that stopped for want of a listener. */
220
+ function resumeLadders(): void {
221
+ const node = host.node.node;
222
+ if (!node) return;
223
+ for (const [token, probe] of probes) ladder(node, token, probe);
224
+ }
225
+
226
+ /** Put every token still waiting back at the foot of the ladder, so the next read asks at once. */
227
+ function restartLadders(): void {
228
+ for (const probe of probes.values()) {
229
+ if (settled(probe)) continue;
230
+ unschedule(probe);
231
+ probe.asks = 0;
232
+ probe.at = 0;
233
+ }
234
+ }
235
+
236
+ // A cadron coming or going may make a machine an invitation names reachable for the probe: ask
237
+ // again at once for the tokens still waiting. A settled answer is KEPT, where the serving counts
238
+ // this replaced were cleared wholesale: `ready` would otherwise read `waiting` again until the
239
+ // re-probe landed, so a screen already telling the person they may close the app would take it
240
+ // back for a second or two. Nor can a connection change the other two — `spent` is permanent,
241
+ // and `no-cadron` is the invitation's own bootstrap list, which does not grow after minting.
242
+ host.node.on('control:connected', () => { restartLadders(); changed(); });
243
+
244
+ async function candidates(node: CadreNode): Promise<CadronCandidate[]> {
245
+ const machines = await withTimeout(node.listMachines(), controlReadMs, 'listMachines').catch(() => []);
246
+ const claimed = node.getBootstrapPeerStore()?.all() ?? new Map<string, { addrs: string[] }>();
247
+ const connections = node.getControlNode()?.getConnections() ?? [];
248
+ const others = machines.filter(m => !m.isSelf && m.trusted);
249
+ return Promise.all(others.map(async (m): Promise<CadronCandidate> => {
250
+ const addrs: CadronCandidate['addrs'][number][] = [];
251
+ const record = await withTimeout(node.resolvePeerAddrs(m.peerId), controlReadMs, 'resolvePeerAddrs').catch(() => []);
252
+ for (const a of record) addrs.push({ addr: withPeer(a.toString(), m.peerId), source: 'record' });
253
+ // WORKAROUND(sereus: name a just-claimed machine): until its first record arrives, what its
254
+ // node code carried. cadre-core's own invitation leaves such a machine out.
255
+ for (const a of claimed.get(m.peerId)?.addrs ?? []) addrs.push({ addr: withPeer(a, m.peerId), source: 'claim' });
256
+ for (const c of connections) {
257
+ const remote = c.remoteAddr.toString();
258
+ if (c.remotePeer.toString() !== m.peerId || c.direction !== 'outbound' || c.limits !== undefined || remote.includes('/p2p-circuit')) continue;
259
+ addrs.push({ addr: withPeer(remote, m.peerId), source: 'connection' });
260
+ }
261
+ return { peerId: m.peerId, alwaysOn: m.alwaysOn === true, lastPublishedAt: m.lastPublishedAt, addrs };
262
+ }));
263
+ }
264
+
265
+ const requireNode = (): CadreNode => {
266
+ const node = host.node.node;
267
+ if (!node) throw new CadreFailure('unavailable', 'The cadre node is not running yet.');
268
+ return node;
269
+ };
270
+
271
+ async function plan() {
272
+ const node = requireNode();
273
+ return planBootstrap({
274
+ cadrons: await candidates(node),
275
+ thisDevice: { peerId: node.peerId?.toString() ?? '', addrs: node.getMultiaddrs().map(a => a.toString()) },
276
+ prefs: await loadPrefs(),
277
+ });
278
+ }
279
+
280
+ const invitations: InvitationsModel = {
281
+ preferences: loadPrefs,
282
+
283
+ setPreferences: changes => {
284
+ const write = writing.then(() => cadreAttempt(async () => {
285
+ const next = normalizePreferences({ ...(await loadPrefs()), ...changes });
286
+ if (host.preferences) await host.preferences.save(JSON.stringify({ format: CADRON_PREFERENCES_FORMAT, ...next }));
287
+ prefs = next;
288
+ changed();
289
+ return next;
290
+ }));
291
+ writing = write;
292
+ return write;
293
+ },
294
+
295
+ bootstrapPlan: () => cadreAttempt(plan),
296
+
297
+ // WORKAROUND(sereus: an option on `createOpenInvitation`): the list is replaced after minting,
298
+ // before the app encodes it. It is not signed; the responder checks only the token.
299
+ async withBootstrap(invitation) {
300
+ try {
301
+ const { entries, warnings } = await plan();
302
+ if (entries.length === 0) return invitation;
303
+ if (warnings.length) log.info('[cadre-client] invitation bootstrap:', warnings.join(', '));
304
+ return { ...invitation, bootstrap: entries.map(e => e.addr) };
305
+ } catch (err) {
306
+ log.warn('[cadre-client] kept cadre-core\'s bootstrap list:', err instanceof Error ? err.message : err);
307
+ return invitation;
308
+ }
309
+ },
310
+
311
+ readiness(token): InvitationReadiness {
312
+ const node = host.node.node;
313
+ // NOTE: with no node the question is dropped rather than remembered, so a store built
314
+ // while the node is stopped reads `waiting` until something else fires the change signal.
315
+ // Harmless as apps use it — a token exists only because a running node minted it. If an
316
+ // app ever reads readiness for a token it kept across a restart, queue the token here.
317
+ if (!node) return NOT_YET;
318
+ return probeFor(node, token).answer ?? NOT_YET;
319
+ },
320
+
321
+ describe: (token, link) => cadreAttempt(async () => {
322
+ const node = requireNode();
323
+ const decoded = node.decodeInvitation(token);
324
+ const [{ names, maxAddrs }, list, now] = await Promise.all([
325
+ loadPrefs(),
326
+ machines(),
327
+ plan().catch(() => ({ entries: [], others: [] })),
328
+ ]);
329
+ return describeInvitation(decoded, {
330
+ link: link ?? token, names, thisDevicePeerId: node.peerId?.toString() ?? null,
331
+ machines: list, others: [...now.entries, ...now.others].map(e => e.addr), maxAddrs,
332
+ });
333
+ }),
334
+
335
+ // WORKAROUND(sereus: an option on `createOpenInvitation`), as `withBootstrap`.
336
+ rebootstrap: (token, addrs) => cadreAttempt(async () => {
337
+ const node = requireNode();
338
+ if (addrs.length === 0) throw new CadreFailure('invalid-address', 'An invitation must name at least one address.');
339
+ if (addrs.some(a => !destinationPeerId(a))) throw new CadreFailure('invalid-address', 'An address does not end in the peer it reaches.');
340
+ return node.encodeInvitation({ ...node.decodeInvitation(token), bootstrap: [...new Set(addrs)] });
341
+ }),
342
+ };
343
+
344
+ return {
345
+ invitations,
346
+ onChange(listener) {
347
+ listeners.add(listener);
348
+ if (listeners.size === 1) resumeLadders();
349
+ return () => {
350
+ listeners.delete(listener);
351
+ // Nothing is watching: stop the ladders here rather than leave timers to fire into an
352
+ // empty listener set — under Node one would hold the process open for up to fifteen
353
+ // seconds. The next read, or the next listener, picks each one up where it stopped.
354
+ if (listeners.size === 0) for (const probe of probes.values()) unschedule(probe);
355
+ };
356
+ },
357
+ };
358
+ }
359
+