@serfab/cadre-client 0.0.0-stage → 2.0.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 +220 -0
- package/README.md +129 -3
- package/dist/address.d.ts +45 -0
- package/dist/address.js +109 -0
- package/dist/address.js.map +1 -0
- package/dist/app-link/index.d.ts +16 -0
- package/dist/app-link/index.js +17 -0
- package/dist/app-link/index.js.map +1 -0
- package/dist/app-link/join-response.d.ts +31 -0
- package/dist/app-link/join-response.js +87 -0
- package/dist/app-link/join-response.js.map +1 -0
- package/dist/app-link/known-apps.d.ts +32 -0
- package/dist/app-link/known-apps.js +51 -0
- package/dist/app-link/known-apps.js.map +1 -0
- package/dist/app-link/link-request-store.d.ts +50 -0
- package/dist/app-link/link-request-store.js +101 -0
- package/dist/app-link/link-request-store.js.map +1 -0
- package/dist/app-link/links.d.ts +47 -0
- package/dist/app-link/links.js +76 -0
- package/dist/app-link/links.js.map +1 -0
- package/dist/app-link/recommend-links.d.ts +30 -0
- package/dist/app-link/recommend-links.js +33 -0
- package/dist/app-link/recommend-links.js.map +1 -0
- package/dist/app-link/recommendation-store.d.ts +54 -0
- package/dist/app-link/recommendation-store.js +99 -0
- package/dist/app-link/recommendation-store.js.map +1 -0
- package/dist/bootstrap.d.ts +106 -0
- package/dist/bootstrap.js +106 -0
- package/dist/bootstrap.js.map +1 -0
- package/dist/inbox.d.ts +10 -0
- package/dist/inbox.js +28 -0
- package/dist/inbox.js.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/invitation-text.d.ts +81 -0
- package/dist/invitation-text.js +80 -0
- package/dist/invitation-text.js.map +1 -0
- package/dist/lifecycle/background-runner.d.ts +94 -0
- package/dist/lifecycle/background-runner.js +278 -0
- package/dist/lifecycle/background-runner.js.map +1 -0
- package/dist/lifecycle/index.d.ts +9 -0
- package/dist/lifecycle/index.js +10 -0
- package/dist/lifecycle/index.js.map +1 -0
- package/dist/loader.d.ts +47 -0
- package/dist/loader.js +93 -0
- package/dist/loader.js.map +1 -0
- package/dist/model.d.ts +284 -0
- package/dist/model.js +22 -0
- package/dist/model.js.map +1 -0
- package/dist/node-code-text.d.ts +10 -0
- package/dist/node-code-text.js +30 -0
- package/dist/node-code-text.js.map +1 -0
- package/dist/result.d.ts +79 -0
- package/dist/result.js +84 -0
- package/dist/result.js.map +1 -0
- package/dist/sereus/client.d.ts +49 -0
- package/dist/sereus/client.js +420 -0
- package/dist/sereus/client.js.map +1 -0
- package/dist/sereus/edge-host.d.ts +22 -0
- package/dist/sereus/edge-host.js +61 -0
- package/dist/sereus/edge-host.js.map +1 -0
- package/dist/sereus/host.d.ts +57 -0
- package/dist/sereus/host.js +2 -0
- package/dist/sereus/host.js.map +1 -0
- package/dist/sereus/index.d.ts +8 -0
- package/dist/sereus/index.js +9 -0
- package/dist/sereus/index.js.map +1 -0
- package/dist/sereus/invitations.d.ts +16 -0
- package/dist/sereus/invitations.js +196 -0
- package/dist/sereus/invitations.js.map +1 -0
- package/dist/sereus/node-code.d.ts +52 -0
- package/dist/sereus/node-code.js +51 -0
- package/dist/sereus/node-code.js.map +1 -0
- package/dist/store.d.ts +27 -0
- package/dist/store.js +51 -0
- package/dist/store.js.map +1 -0
- package/dist/stores.d.ts +37 -0
- package/dist/stores.js +45 -0
- package/dist/stores.js.map +1 -0
- package/examples/README.md +20 -0
- package/examples/nativescript/cadrons-page.xml +24 -0
- package/examples/nativescript/cadrons-view-model.ts +68 -0
- package/examples/react-native/CadronList.tsx +204 -0
- package/examples/react-native/InvitationPanel.tsx +162 -0
- package/examples/react-native/useStore.ts +11 -0
- package/examples/svelte/CadronList.svelte +86 -0
- package/examples/svelte/InvitationPanel.svelte +79 -0
- package/package.json +65 -3
- package/src/address.ts +125 -0
- package/src/app-link/index.ts +45 -0
- package/src/app-link/join-response.ts +109 -0
- package/src/app-link/known-apps.ts +70 -0
- package/src/app-link/link-request-store.ts +129 -0
- package/src/app-link/links.ts +90 -0
- package/src/app-link/recommend-links.ts +49 -0
- package/src/app-link/recommendation-store.ts +132 -0
- package/src/bootstrap.ts +184 -0
- package/src/globals.d.ts +26 -0
- package/src/inbox.ts +36 -0
- package/src/index.ts +15 -0
- package/src/invitation-text.ts +156 -0
- package/src/lifecycle/background-runner.ts +363 -0
- package/src/lifecycle/index.ts +17 -0
- package/src/loader.ts +103 -0
- package/src/model.ts +299 -0
- package/src/node-code-text.ts +25 -0
- package/src/result.ts +131 -0
- package/src/sereus/client.ts +454 -0
- package/src/sereus/edge-host.ts +81 -0
- package/src/sereus/host.ts +56 -0
- package/src/sereus/index.ts +8 -0
- package/src/sereus/invitations.ts +206 -0
- package/src/sereus/node-code.ts +80 -0
- package/src/store.ts +61 -0
- package/src/stores.ts +59 -0
|
@@ -0,0 +1,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. 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
|
+
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Node codes: the `sereus-join:1.…` text a cadre node shows (as a QR code, a link or plain
|
|
3
|
+
* text) while it waits to be claimed, and how to read one and sort a claim's failure.
|
|
4
|
+
*
|
|
5
|
+
* Descends from reference-app-rn's `src/node-claim.ts`; this one returns codes rather than
|
|
6
|
+
* English, so each app words them in its own catalog.
|
|
7
|
+
*
|
|
8
|
+
* SECURITY: a code carries the node's one-time claim secret. Never log the code text, a
|
|
9
|
+
* link containing one, or a decoded payload — log the peer id only.
|
|
10
|
+
*/
|
|
11
|
+
import {
|
|
12
|
+
ClaimRefusedError,
|
|
13
|
+
NODE_CLAIM_PAYLOAD_PREFIX,
|
|
14
|
+
PeerUnreachableError,
|
|
15
|
+
decodeNodeClaimPayload,
|
|
16
|
+
describeThrown,
|
|
17
|
+
type NodeClaimPayload,
|
|
18
|
+
} from '@serfab/cadre-core';
|
|
19
|
+
import type { NodeReach } from '../model.js';
|
|
20
|
+
import { NODE_CODE_SCHEME, nodeCodeFromUrl } from '../node-code-text.js';
|
|
21
|
+
import { nodeReach } from '../address.js';
|
|
22
|
+
|
|
23
|
+
/** A code with a version this build does not read: `sereus-join:<n>.` with n ≠ 1. */
|
|
24
|
+
const VERSIONED_NODE_CODE = /^sereus-join:(\d+)\./;
|
|
25
|
+
|
|
26
|
+
export type NodeCodeProblem =
|
|
27
|
+
/** Does not start with `sereus-join:` — some other QR, link or text. */
|
|
28
|
+
| 'not-node-code'
|
|
29
|
+
/** A node code from a newer node than this build reads: the app needs updating. */
|
|
30
|
+
| 'newer-version'
|
|
31
|
+
/** Right prefix, but cut short or corrupted. */
|
|
32
|
+
| 'damaged';
|
|
33
|
+
|
|
34
|
+
export type NodeCodeReading =
|
|
35
|
+
| { ok: true; payload: NodeClaimPayload }
|
|
36
|
+
| { ok: false; problem: NodeCodeProblem; /** The decoder's words (never the secret), for logs. */ detail?: string };
|
|
37
|
+
|
|
38
|
+
/** Decode scanned or pasted text, or say which problem it has. */
|
|
39
|
+
export function readNodeCode(text: string): NodeCodeReading {
|
|
40
|
+
const trimmed = (nodeCodeFromUrl(text) ?? text).trim();
|
|
41
|
+
if (!trimmed.startsWith(NODE_CODE_SCHEME)) return { ok: false, problem: 'not-node-code' };
|
|
42
|
+
if (!trimmed.startsWith(NODE_CLAIM_PAYLOAD_PREFIX) && VERSIONED_NODE_CODE.test(trimmed)) {
|
|
43
|
+
return { ok: false, problem: 'newer-version' };
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
return { ok: true, payload: decodeNodeClaimPayload(trimmed) };
|
|
47
|
+
} catch (err) {
|
|
48
|
+
// The decoder never echoes the secret, so its message is safe to keep.
|
|
49
|
+
return { ok: false, problem: 'damaged', detail: describeThrown(err) };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Refusals after which the same code can still succeed. */
|
|
54
|
+
const RETRYABLE_REFUSALS: ReadonlySet<string> = new Set(['claim-rate-limited', 'claim-not-persisted']);
|
|
55
|
+
|
|
56
|
+
export type ClaimFailure =
|
|
57
|
+
/** No connection formed from any address; nothing was sent. */
|
|
58
|
+
| { kind: 'node-unreachable'; reach: NodeReach; retryable: true; detail: string }
|
|
59
|
+
/** The node answered and said no. `refusal` is absent when it gave no (known) code. */
|
|
60
|
+
| { kind: 'claim-refused'; refusal?: string; retryable: boolean; detail: string }
|
|
61
|
+
/** Reached, then the exchange or a local step failed. Repeating with the same code is safe. */
|
|
62
|
+
| { kind: 'claim-failed'; retryable: true; detail: string };
|
|
63
|
+
|
|
64
|
+
/** Sort an error thrown by `CadreNode.claimNode(payload)` into what to say and whether to keep the code. */
|
|
65
|
+
export function classifyClaimFailure(error: unknown, payload: NodeClaimPayload): ClaimFailure {
|
|
66
|
+
const detail = describeThrown(error);
|
|
67
|
+
if (error instanceof PeerUnreachableError) {
|
|
68
|
+
return { kind: 'node-unreachable', reach: nodeReach(payload.multiaddrs), retryable: true, detail };
|
|
69
|
+
}
|
|
70
|
+
if (error instanceof ClaimRefusedError) {
|
|
71
|
+
const refusal = error.code;
|
|
72
|
+
return {
|
|
73
|
+
kind: 'claim-refused',
|
|
74
|
+
refusal,
|
|
75
|
+
retryable: refusal !== undefined && RETRYABLE_REFUSALS.has(refusal),
|
|
76
|
+
detail: error.reason ?? detail,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
return { kind: 'claim-failed', retryable: true, detail };
|
|
80
|
+
}
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The store primitive cadre screens bind to: the Svelte store contract — `subscribe(fn)`
|
|
3
|
+
* calls `fn` at once with the current value and returns an unsubscribe function — plus
|
|
4
|
+
* `get()`, with two rules:
|
|
5
|
+
*
|
|
6
|
+
* - `get()` returns the same object until the value changes. React's
|
|
7
|
+
* `useSyncExternalStore` re-renders whenever the snapshot is a new object, so a store
|
|
8
|
+
* that rebuilt its value on every read would loop.
|
|
9
|
+
* - Reference-counted: `start` runs when the first subscriber arrives and the function it
|
|
10
|
+
* returns runs when the last one leaves, so a store costs nothing while nothing shows it.
|
|
11
|
+
*
|
|
12
|
+
* Binding: Svelte uses a store directly (`$store`); React through
|
|
13
|
+
* `useSyncExternalStore(store.subscribe, store.get)`; NativeScript by copying each value
|
|
14
|
+
* into an `Observable` from `subscribe`. Self-contained on purpose, so the package
|
|
15
|
+
* depends on nothing but cadre-core; an app with its own store type of the same contract
|
|
16
|
+
* binds these the same way.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export interface Readable<T> {
|
|
20
|
+
subscribe(run: (value: T) => void): () => void;
|
|
21
|
+
get(): T;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface Writable<T> extends Readable<T> {
|
|
25
|
+
set(value: T): void;
|
|
26
|
+
update(fn: (value: T) => T): void;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export type StartStop<T> = (set: (value: T) => void, update: (fn: (value: T) => T) => void) => void | (() => void);
|
|
30
|
+
|
|
31
|
+
export function writable<T>(initial: T, start?: StartStop<T>): Writable<T> {
|
|
32
|
+
let value = initial;
|
|
33
|
+
let stop: (() => void) | void = undefined;
|
|
34
|
+
const subscribers = new Set<(value: T) => void>();
|
|
35
|
+
|
|
36
|
+
const set = (next: T) => {
|
|
37
|
+
if (Object.is(next, value)) return;
|
|
38
|
+
value = next;
|
|
39
|
+
for (const run of [...subscribers]) run(value);
|
|
40
|
+
};
|
|
41
|
+
const update = (fn: (value: T) => T) => set(fn(value));
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
get: () => value,
|
|
45
|
+
set,
|
|
46
|
+
update,
|
|
47
|
+
subscribe(run) {
|
|
48
|
+
subscribers.add(run);
|
|
49
|
+
if (subscribers.size === 1 && start) stop = start(set, update);
|
|
50
|
+
run(value);
|
|
51
|
+
return () => {
|
|
52
|
+
if (!subscribers.delete(run)) return;
|
|
53
|
+
if (subscribers.size === 0 && stop) {
|
|
54
|
+
const halt = stop;
|
|
55
|
+
stop = undefined;
|
|
56
|
+
halt();
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
package/src/stores.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The stores a cadre screen binds to. Each reads through a view (`CadreView`,
|
|
3
|
+
* `ReachabilityView`), so it works over the Sereus client, an app's mock, or an app's
|
|
4
|
+
* whole model when that has the same two members.
|
|
5
|
+
*/
|
|
6
|
+
import type { CadreStatus, CadreView, InvitationReadiness, InvitationsView, Reachability, ReachabilityView } from './model.js';
|
|
7
|
+
import { writable, type Readable } from './store.js';
|
|
8
|
+
import { cadreOk } from './result.js';
|
|
9
|
+
import { loader, type Loader } from './loader.js';
|
|
10
|
+
|
|
11
|
+
/** How often a store re-reads with nothing announcing a change, while subscribed. */
|
|
12
|
+
export interface StoreOptions {
|
|
13
|
+
/** Milliseconds; 0 turns the poll off. Default 30 s. */
|
|
14
|
+
pollMs?: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The cadre: this device, its cadrons, and whether it is an enrolled owner. Re-read on every
|
|
19
|
+
* change that has an event: this node starting or stopping, a cadron connecting or dropping, the
|
|
20
|
+
* cadron preferences. The poll catches what has none: a cadron added or removed on another
|
|
21
|
+
* device (it arrives by control replication), and a cadron's `lastSeenAt` ageing, so its
|
|
22
|
+
* presence turns from recent to quiet. A store kept subscribed app-wide (a status badge) can poll
|
|
23
|
+
* less often, or not at all if those can wait for the next screen.
|
|
24
|
+
*/
|
|
25
|
+
export function cadreStore(view: CadreView, opts: StoreOptions = {}): Loader<CadreStatus> {
|
|
26
|
+
return loader({
|
|
27
|
+
load: () => view.cadre.status(),
|
|
28
|
+
changes: onChange => view.changes.cadre(onChange),
|
|
29
|
+
pollMs: opts.pollMs ?? 30_000,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Reachability: can anybody answer an invitation from this device, which relays it is
|
|
35
|
+
* configured with, and whether the relay reservation holds — read live, because a
|
|
36
|
+
* configured relay is not a working one and a reservation can be lost after it was
|
|
37
|
+
* granted. Re-read when this device's addresses change; a slow backstop poll covers a
|
|
38
|
+
* change no event announces (a machine of the party's coming up or going quiet).
|
|
39
|
+
*/
|
|
40
|
+
export function reachabilityStore(view: ReachabilityView, opts: StoreOptions = {}): Loader<Reachability> {
|
|
41
|
+
return loader({
|
|
42
|
+
load: async () => cadreOk(await view.reachability.get()),
|
|
43
|
+
changes: onChange => view.changes.reachability(onChange),
|
|
44
|
+
debounceMs: 250,
|
|
45
|
+
pollMs: opts.pollMs ?? 30_000,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Whether a new invitation to `strandId` is ready to hand out (`InvitationReadiness`), live: it
|
|
51
|
+
* turns `ready` when a cadron comes to hold the strand.
|
|
52
|
+
*/
|
|
53
|
+
export function invitationReadinessStore(view: InvitationsView, strandId: string, opts: { newStrand?: boolean } = {}): Readable<InvitationReadiness> {
|
|
54
|
+
const read = () => view.invitations.readiness(strandId, opts);
|
|
55
|
+
return writable<InvitationReadiness>(read(), set => {
|
|
56
|
+
set(read());
|
|
57
|
+
return view.changes.invitations(() => set(read()));
|
|
58
|
+
});
|
|
59
|
+
}
|