@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.
- package/ADOPTING.md +12 -4
- package/README.md +2 -1
- package/dist/model.d.ts +38 -13
- package/dist/model.js.map +1 -1
- package/dist/sereus/client.d.ts +1 -1
- package/dist/sereus/invitations.js +177 -40
- package/dist/sereus/invitations.js.map +1 -1
- package/dist/stores.d.ts +6 -5
- package/dist/stores.js +7 -4
- package/dist/stores.js.map +1 -1
- package/examples/react-native/InvitationPanel.tsx +43 -14
- package/examples/svelte/InvitationPanel.svelte +28 -10
- package/package.json +3 -3
- package/src/model.ts +39 -11
- package/src/sereus/client.ts +1 -1
- package/src/sereus/invitations.ts +359 -206
- package/src/stores.ts +62 -59
|
@@ -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
|
|
13
|
-
* (`
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
import {
|
|
20
|
-
import type
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import
|
|
24
|
-
import {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
//
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
if (
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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
|
+
|