@serfab/cadre-client 0.0.0-stage → 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 +228 -0
- package/README.md +130 -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 +309 -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 +333 -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 +38 -0
- package/dist/stores.js +48 -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 +191 -0
- package/examples/react-native/useStore.ts +11 -0
- package/examples/svelte/CadronList.svelte +86 -0
- package/examples/svelte/InvitationPanel.svelte +97 -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 +327 -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 +359 -0
- package/src/sereus/node-code.ts +80 -0
- package/src/store.ts +61 -0
- package/src/stores.ts +62 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An invitation in words: what a person sees when they ask what is in the link they are about to
|
|
3
|
+
* hand out (or were handed). Pure: `/sereus` decodes the invitation, this describes it.
|
|
4
|
+
*
|
|
5
|
+
* Besides the addresses it names, it can say which machine each belongs to in the words the
|
|
6
|
+
* person's cadre screen uses (name, status dot, whether it is theirs), and which other addresses
|
|
7
|
+
* of theirs it could name instead, for a screen that lets the person change one invitation's list
|
|
8
|
+
* (`InvitationsModel.rebootstrap`).
|
|
9
|
+
*/
|
|
10
|
+
import { addressComponents, addressKind, reachesAnywhere, suggestedName, type CadronAddressKind } from './address.js';
|
|
11
|
+
import { cadronPresence, shortPeerId, type CadreMachine, type CadronPresence } from './model.js';
|
|
12
|
+
|
|
13
|
+
export interface InvitationAddressText {
|
|
14
|
+
/** The cadron's name the person gave it, else its host name, else its short peer id. */
|
|
15
|
+
label: string;
|
|
16
|
+
peerId: string;
|
|
17
|
+
/** This device's own address rather than one of its cadrons'. */
|
|
18
|
+
thisDevice: boolean;
|
|
19
|
+
/** Null for an address no phone can dial (plain TCP, unparsable). */
|
|
20
|
+
kind: CadronAddressKind | null;
|
|
21
|
+
reachesAnywhere: boolean;
|
|
22
|
+
/** The host a joiner dials: the cadron's own, or for a relayed address the relay's. */
|
|
23
|
+
host: string;
|
|
24
|
+
port: number | null;
|
|
25
|
+
/** `ws`, `wss`, `tcp`, or `relay` for an address reached through a relay. */
|
|
26
|
+
via: 'ws' | 'wss' | 'tcp' | 'relay';
|
|
27
|
+
addr: string;
|
|
28
|
+
/** The invitation names it; false for an address it could name instead (`others`). */
|
|
29
|
+
included: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** A machine an invitation names, or could: the addresses grouped by whose they are. */
|
|
33
|
+
export interface InvitationCadronText {
|
|
34
|
+
peerId: string;
|
|
35
|
+
/** As on each address: the person's name for it, else its host name, else its short peer id. */
|
|
36
|
+
label: string;
|
|
37
|
+
thisDevice: boolean;
|
|
38
|
+
/**
|
|
39
|
+
* One of the person's own cadrons (on their cadron list and not untrusted), or this device.
|
|
40
|
+
* False: a machine that is not theirs, or one since removed. Null when the list was not given.
|
|
41
|
+
*/
|
|
42
|
+
yours: boolean | null;
|
|
43
|
+
/** As on the cadre screen (`cadronPresence`); null when the machine is not on the list. */
|
|
44
|
+
presence: CadronPresence | null;
|
|
45
|
+
alwaysOn: boolean | null;
|
|
46
|
+
/** The ones the invitation names first, in its order, then the ones it could. */
|
|
47
|
+
addresses: InvitationAddressText[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface InvitationText {
|
|
51
|
+
expiresAt: string;
|
|
52
|
+
/** Length of the text shared (the link), in characters. */
|
|
53
|
+
linkLength: number;
|
|
54
|
+
/** The smallest QR version (1–40) holding the link at error correction M, or null past 40. */
|
|
55
|
+
qrVersion: number | null;
|
|
56
|
+
/** The addresses it names, in its order. */
|
|
57
|
+
addresses: InvitationAddressText[];
|
|
58
|
+
/** The same, and the `others`, grouped by machine: the ones it names first, in its order. */
|
|
59
|
+
cadrons: InvitationCadronText[];
|
|
60
|
+
/** The person's cap on addresses per invitation, when known. */
|
|
61
|
+
maxAddrs: number | null;
|
|
62
|
+
/** Usable addresses of the person's cadrons (not this device) it leaves out. 0: it names all there are. */
|
|
63
|
+
cadronAddrsLeftOut: number;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface DescribeOptions {
|
|
67
|
+
/** The text actually shared (the link), for its length. */
|
|
68
|
+
link: string;
|
|
69
|
+
/** The person's own names for their cadrons. */
|
|
70
|
+
names?: Record<string, string>;
|
|
71
|
+
thisDevicePeerId?: string | null;
|
|
72
|
+
/** The person's cadron list (`CadreStatus.machines`): whose each address is, and how each is. */
|
|
73
|
+
machines?: readonly CadreMachine[];
|
|
74
|
+
/** Other usable addresses it could name (`BootstrapPlan` entries and others), best first. */
|
|
75
|
+
others?: readonly string[];
|
|
76
|
+
maxAddrs?: number | null;
|
|
77
|
+
now?: number;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** QR byte-mode capacity at error correction level M, versions 1–40. */
|
|
81
|
+
const QR_CAPACITY_M = [14, 26, 42, 62, 84, 106, 122, 152, 180, 213, 251, 287, 331, 362, 412, 450, 504, 560, 624, 666, 711, 779,
|
|
82
|
+
857, 911, 997, 1059, 1125, 1190, 1264, 1370, 1452, 1538, 1628, 1722, 1809, 1911, 1989, 2099, 2213, 2331];
|
|
83
|
+
|
|
84
|
+
export function qrVersionFor(length: number): number | null {
|
|
85
|
+
const i = QR_CAPACITY_M.findIndex(cap => cap >= length);
|
|
86
|
+
return i < 0 ? null : i + 1;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The peer an address ends in (its last `/p2p/`), or '' when it names none or does not parse. */
|
|
90
|
+
export function destinationPeerId(addr: string): string {
|
|
91
|
+
const peers = (addressComponents(addr) ?? []).filter(c => c.name === 'p2p');
|
|
92
|
+
return peers[peers.length - 1]?.value ?? '';
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function hostAndPort(addr: string): { host: string; port: number | null; via: InvitationAddressText['via'] } {
|
|
96
|
+
const components = addressComponents(addr) ?? [];
|
|
97
|
+
const relayed = components.some(c => c.name === 'p2p-circuit');
|
|
98
|
+
const tcp = components.find(c => c.name === 'tcp');
|
|
99
|
+
const port = tcp?.value ? Number(tcp.value) : NaN;
|
|
100
|
+
const names = new Set(components.map(c => c.name));
|
|
101
|
+
const via = relayed ? 'relay' : names.has('wss') || names.has('tls') ? 'wss' : names.has('ws') ? 'ws' : 'tcp';
|
|
102
|
+
return { host: components[0]?.value ?? '', port: Number.isFinite(port) ? port : null, via };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function describeInvitation(
|
|
106
|
+
invitation: { expiration: Date | string; bootstrap: readonly string[] },
|
|
107
|
+
opts: DescribeOptions,
|
|
108
|
+
): InvitationText {
|
|
109
|
+
const names = opts.names ?? {};
|
|
110
|
+
const machines = new Map((opts.machines ?? []).map(m => [m.peerId, m]));
|
|
111
|
+
const included = new Set(invitation.bootstrap);
|
|
112
|
+
const others = (opts.others ?? []).filter(addr => !included.has(addr));
|
|
113
|
+
const all = [...invitation.bootstrap, ...others];
|
|
114
|
+
// A machine's host name: from its list entry, else from the addresses here.
|
|
115
|
+
const label = (peerId: string) => names[peerId]?.trim()
|
|
116
|
+
|| suggestedName(machines.get(peerId) ?? { addresses: all.filter(a => destinationPeerId(a) === peerId) })
|
|
117
|
+
|| shortPeerId(peerId);
|
|
118
|
+
const isThisDevice = (peerId: string) => !!opts.thisDevicePeerId && peerId === opts.thisDevicePeerId;
|
|
119
|
+
|
|
120
|
+
const text = (addr: string, inInvitation: boolean): InvitationAddressText => {
|
|
121
|
+
const peerId = destinationPeerId(addr);
|
|
122
|
+
const kind = addressKind(addr);
|
|
123
|
+
return {
|
|
124
|
+
label: label(peerId), peerId, thisDevice: isThisDevice(peerId), kind, reachesAnywhere: reachesAnywhere(kind),
|
|
125
|
+
...hostAndPort(addr), addr, included: inInvitation,
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
const addresses = invitation.bootstrap.map(addr => text(addr, true));
|
|
129
|
+
const extra = others.map(addr => text(addr, false));
|
|
130
|
+
|
|
131
|
+
const cadrons = new Map<string, InvitationCadronText>();
|
|
132
|
+
for (const a of [...addresses, ...extra]) {
|
|
133
|
+
let c = cadrons.get(a.peerId);
|
|
134
|
+
if (!c) {
|
|
135
|
+
const m = machines.get(a.peerId);
|
|
136
|
+
c = {
|
|
137
|
+
peerId: a.peerId, label: a.label, thisDevice: a.thisDevice,
|
|
138
|
+
yours: a.thisDevice ? true : opts.machines ? !!m && m.trusted !== false : null,
|
|
139
|
+
presence: m ? cadronPresence(m, opts.now) : null,
|
|
140
|
+
alwaysOn: m?.alwaysOn ?? null,
|
|
141
|
+
addresses: [],
|
|
142
|
+
};
|
|
143
|
+
cadrons.set(a.peerId, c);
|
|
144
|
+
}
|
|
145
|
+
c.addresses.push(a);
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
expiresAt: new Date(invitation.expiration).toISOString(),
|
|
149
|
+
linkLength: opts.link.length,
|
|
150
|
+
qrVersion: qrVersionFor(opts.link.length),
|
|
151
|
+
addresses,
|
|
152
|
+
cadrons: [...cadrons.values()],
|
|
153
|
+
maxAddrs: opts.maxAddrs ?? null,
|
|
154
|
+
cadronAddrsLeftOut: extra.filter(a => !a.thisDevice).length,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* background-runner.ts — owns a phone's {@link CadreNode} lifecycle across OS
|
|
3
|
+
* foreground/background transitions.
|
|
4
|
+
*
|
|
5
|
+
* This runner subscribes to `AppState` and drives the cadre-core background
|
|
6
|
+
* primitives (`hibernateAll`, the `control:*` readiness edges) so the footprint
|
|
7
|
+
* quiesces on background and a managed resume re-syncs the control network on
|
|
8
|
+
* foreground return.
|
|
9
|
+
*
|
|
10
|
+
* Scope is **AppState-driven lifecycle only** — a push wake (FCM/APNs receive path,
|
|
11
|
+
* native background task) is the app's. This file is platform-agnostic apart from
|
|
12
|
+
* the injectable {@link AppStateLike}: react-native's `AppState` is assignable to
|
|
13
|
+
* it, so the app passes that, tests pass a fake, and this module never imports
|
|
14
|
+
* `react-native`.
|
|
15
|
+
*
|
|
16
|
+
* State machine:
|
|
17
|
+
*
|
|
18
|
+
* FOREGROUND ──background──► BACKGROUND_CONNECTED ──control:disconnected──►
|
|
19
|
+
* BACKGROUND_HIBERNATING ──active──► (resume) ──► FOREGROUND
|
|
20
|
+
*
|
|
21
|
+
* BACKGROUND_CONNECTED is **best-effort**: iOS suspends sockets within seconds
|
|
22
|
+
* regardless of `hibernateAll`, Android (with the future foreground service) can
|
|
23
|
+
* hold it longer. We never assume the connection survived — the drop to
|
|
24
|
+
* BACKGROUND_HIBERNATING is driven by the real `control:disconnected` edge.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import type { CadreNode } from '@serfab/cadre-core';
|
|
28
|
+
|
|
29
|
+
// ── Public types ──────────────────────────────────────────────────────────────
|
|
30
|
+
|
|
31
|
+
export type RunnerState =
|
|
32
|
+
| 'foreground'
|
|
33
|
+
| 'background-connected'
|
|
34
|
+
| 'background-hibernating'
|
|
35
|
+
| 'terminated';
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Subset of an `AppState` event subscription we depend on. Matches the object
|
|
39
|
+
* react-native's `AppState.addEventListener` returns.
|
|
40
|
+
*/
|
|
41
|
+
export interface AppStateSubscription {
|
|
42
|
+
remove(): void;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** AppState status values the runner reacts to (others are ignored). */
|
|
46
|
+
export type AppStateValue = 'active' | 'background' | 'inactive' | string;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The part of react-native's `AppState` the runner uses. `AppState` itself is
|
|
50
|
+
* assignable to it; unit tests drive transitions with a fake and no device.
|
|
51
|
+
*/
|
|
52
|
+
export interface AppStateLike {
|
|
53
|
+
addEventListener(
|
|
54
|
+
type: 'change',
|
|
55
|
+
handler: (status: AppStateValue) => void,
|
|
56
|
+
): AppStateSubscription;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface BackgroundRunner {
|
|
60
|
+
/** Current lifecycle state. */
|
|
61
|
+
readonly state: RunnerState;
|
|
62
|
+
/** True while a foreground resume is settling (awaiting control reconnect). */
|
|
63
|
+
readonly resuming: boolean;
|
|
64
|
+
/**
|
|
65
|
+
* True after a resume settled without the control network reconnecting
|
|
66
|
+
* (bounded settle timeout fired) — the UI should show an offline/degraded
|
|
67
|
+
* hint rather than spin. Cleared whenever a fresh resume begins.
|
|
68
|
+
*/
|
|
69
|
+
readonly degraded: boolean;
|
|
70
|
+
/** Subscribe to AppState. Assumes the node is already (or will be) started. Idempotent. */
|
|
71
|
+
start(): void;
|
|
72
|
+
/** Unsubscribe and drop node listeners (component unmount / logout). Idempotent. */
|
|
73
|
+
stop(): void;
|
|
74
|
+
/**
|
|
75
|
+
* Observe state/resuming/degraded changes. The callback receives the current
|
|
76
|
+
* {@link RunnerState}; read `runner.resuming`/`runner.degraded` for the rest.
|
|
77
|
+
* Returns an unsubscribe fn.
|
|
78
|
+
*/
|
|
79
|
+
onStateChange(cb: (s: RunnerState) => void): () => void;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface BackgroundRunnerDeps {
|
|
83
|
+
/** Returns the live node (e.g. `PhoneNode.node`), or null if stopped. */
|
|
84
|
+
getNode: () => CadreNode | null;
|
|
85
|
+
/** Injectable AppState (react-native in prod, a fake in tests). */
|
|
86
|
+
appState: AppStateLike;
|
|
87
|
+
/**
|
|
88
|
+
* Cold-start hook: start the node again when a foreground return finds it
|
|
89
|
+
* stopped/killed (`phoneNodeLifecycle` in `./index.ts` provides one). Optional —
|
|
90
|
+
* without it the runner only awaits an already-present node's control
|
|
91
|
+
* connection. Must be idempotent.
|
|
92
|
+
*/
|
|
93
|
+
ensureNode?: () => Promise<void>;
|
|
94
|
+
/**
|
|
95
|
+
* Bounded resume settle: max wait for `control:connected` on foreground return
|
|
96
|
+
* before clearing `resuming` and surfacing a degraded state. Default 15s.
|
|
97
|
+
*/
|
|
98
|
+
settleTimeoutMs?: number;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const DEFAULT_SETTLE_TIMEOUT_MS = 15_000;
|
|
102
|
+
|
|
103
|
+
// ── Implementation ──────────────────────────────────────────────────────────────
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Create a {@link BackgroundRunner}. Construction is inert — call `start()` to
|
|
107
|
+
* subscribe to AppState.
|
|
108
|
+
*
|
|
109
|
+
* Concurrency model: every AppState transition bumps a monotonic `epoch`. Async
|
|
110
|
+
* handlers (hibernate sweep, resume settle) capture the epoch at entry and bail
|
|
111
|
+
* after each `await` if a newer transition has superseded them. This makes rapid
|
|
112
|
+
* foreground/background flapping deterministic — a late-completing resume can
|
|
113
|
+
* never clobber the state a subsequent background event already set.
|
|
114
|
+
*/
|
|
115
|
+
export function createBackgroundRunner(deps: BackgroundRunnerDeps): BackgroundRunner {
|
|
116
|
+
const settleTimeoutMs = deps.settleTimeoutMs ?? DEFAULT_SETTLE_TIMEOUT_MS;
|
|
117
|
+
|
|
118
|
+
let state: RunnerState = 'foreground';
|
|
119
|
+
let resuming = false;
|
|
120
|
+
let degraded = false;
|
|
121
|
+
let epoch = 0;
|
|
122
|
+
let active = false;
|
|
123
|
+
|
|
124
|
+
let subscription: AppStateSubscription | null = null;
|
|
125
|
+
let listenedNode: CadreNode | null = null;
|
|
126
|
+
const pendingTimers = new Set<ReturnType<typeof setTimeout>>();
|
|
127
|
+
// In-flight `awaitControlConnected` teardowns, so `stop()` can abort a settle
|
|
128
|
+
// mid-flight (removing its `control:connected` listener + timer) instead of
|
|
129
|
+
// orphaning them — `clearTimeout` alone would leave the listener attached.
|
|
130
|
+
const pendingSettles = new Set<(connected: boolean) => void>();
|
|
131
|
+
const stateListeners = new Set<(s: RunnerState) => void>();
|
|
132
|
+
|
|
133
|
+
// ── notification ────────────────────────────────────────────────────────────
|
|
134
|
+
|
|
135
|
+
function notify(): void {
|
|
136
|
+
for (const cb of stateListeners) {
|
|
137
|
+
try {
|
|
138
|
+
cb(state);
|
|
139
|
+
} catch (err) {
|
|
140
|
+
console.warn('[background-runner] state listener threw:', err);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function setState(next: RunnerState): void {
|
|
146
|
+
if (state === next) return;
|
|
147
|
+
state = next;
|
|
148
|
+
notify();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function setResuming(next: boolean): void {
|
|
152
|
+
if (resuming === next) return;
|
|
153
|
+
resuming = next;
|
|
154
|
+
notify();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function setDegraded(next: boolean): void {
|
|
158
|
+
if (degraded === next) return;
|
|
159
|
+
degraded = next;
|
|
160
|
+
notify();
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// ── node event listeners ──────────────────────────────────────────────────────
|
|
164
|
+
|
|
165
|
+
// A `control:disconnected` while backgrounded is the signal that the OS tore
|
|
166
|
+
// down sockets / suspended us — drop BACKGROUND_CONNECTED → BACKGROUND_HIBERNATING.
|
|
167
|
+
// While foreground it's transient churn the node will reconnect from; ignore it.
|
|
168
|
+
function onControlDisconnected(): void {
|
|
169
|
+
if (state === 'background-connected') {
|
|
170
|
+
setState('background-hibernating');
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// A `control:connected` that arrives while we are already foregrounded and
|
|
175
|
+
// degraded means the control network recovered on its own (no app-lifecycle
|
|
176
|
+
// transition to drive a fresh resume). Clear the stale degraded hint so the UI
|
|
177
|
+
// stops showing offline. During a resume settle, state is not yet 'foreground',
|
|
178
|
+
// so this no-ops and the settle's own one-shot listener owns the outcome.
|
|
179
|
+
function onControlConnected(): void {
|
|
180
|
+
if (state === 'foreground' && degraded) {
|
|
181
|
+
setDegraded(false);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function attachNodeListeners(): void {
|
|
186
|
+
const node = deps.getNode();
|
|
187
|
+
if (node === listenedNode) return;
|
|
188
|
+
detachNodeListeners();
|
|
189
|
+
if (!node) return;
|
|
190
|
+
node.on('control:disconnected', onControlDisconnected);
|
|
191
|
+
node.on('control:connected', onControlConnected);
|
|
192
|
+
listenedNode = node;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function detachNodeListeners(): void {
|
|
196
|
+
if (!listenedNode) return;
|
|
197
|
+
listenedNode.off('control:disconnected', onControlDisconnected);
|
|
198
|
+
listenedNode.off('control:connected', onControlConnected);
|
|
199
|
+
listenedNode = null;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ── settle helper ────────────────────────────────────────────────────────────
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Resolve when the node's control network connects, or after the bounded
|
|
206
|
+
* settle timeout — whichever first. Resolves to `true` if connected, `false`
|
|
207
|
+
* if it timed out (degraded). Always cleans up its listener + timer.
|
|
208
|
+
*/
|
|
209
|
+
function awaitControlConnected(node: CadreNode): Promise<boolean> {
|
|
210
|
+
if (node.controlConnected) return Promise.resolve(true);
|
|
211
|
+
return new Promise<boolean>((resolve) => {
|
|
212
|
+
let settled = false;
|
|
213
|
+
const finish = (connected: boolean) => {
|
|
214
|
+
if (settled) return;
|
|
215
|
+
settled = true;
|
|
216
|
+
node.off('control:connected', onConnected);
|
|
217
|
+
pendingTimers.delete(timer);
|
|
218
|
+
clearTimeout(timer);
|
|
219
|
+
pendingSettles.delete(finish);
|
|
220
|
+
resolve(connected);
|
|
221
|
+
};
|
|
222
|
+
const onConnected = () => finish(true);
|
|
223
|
+
node.on('control:connected', onConnected);
|
|
224
|
+
const timer = setTimeout(() => finish(false), settleTimeoutMs);
|
|
225
|
+
pendingTimers.add(timer);
|
|
226
|
+
pendingSettles.add(finish);
|
|
227
|
+
// Guard a connect that raced in between the initial check and subscribe.
|
|
228
|
+
if (node.controlConnected) finish(true);
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// ── transition handlers ────────────────────────────────────────────────────────
|
|
233
|
+
|
|
234
|
+
// active → background: quiesce non-realtime strands and move to
|
|
235
|
+
// BACKGROUND_CONNECTED. We do NOT stop the node — the control connection and
|
|
236
|
+
// realtime strands stay up for as long as the OS permits. A superseding
|
|
237
|
+
// foreground event (flap) bumps the epoch and owns state after our await.
|
|
238
|
+
async function handleBackground(): Promise<void> {
|
|
239
|
+
const myEpoch = ++epoch;
|
|
240
|
+
setResuming(false); // cancel any in-flight resume settle
|
|
241
|
+
setDegraded(false);
|
|
242
|
+
setState('background-connected');
|
|
243
|
+
|
|
244
|
+
const node = deps.getNode();
|
|
245
|
+
if (!node || !node.running) return; // node null/stopped → no-op safely
|
|
246
|
+
try {
|
|
247
|
+
await node.hibernateAll();
|
|
248
|
+
} catch (err) {
|
|
249
|
+
console.warn('[background-runner] hibernateAll failed:', err);
|
|
250
|
+
}
|
|
251
|
+
// No post-await state write: if a foreground flap superseded us
|
|
252
|
+
// (epoch changed), that handler now owns the state.
|
|
253
|
+
void myEpoch;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// background → active: full resume. Ensure the node is running (cold-start via
|
|
257
|
+
// `ensureNode`), await the control connection (bounded), then settle to
|
|
258
|
+
// FOREGROUND. Each await is epoch-guarded so a background flap mid-resume aborts
|
|
259
|
+
// cleanly rather than racing a hibernate.
|
|
260
|
+
async function handleForeground(): Promise<void> {
|
|
261
|
+
const myEpoch = ++epoch;
|
|
262
|
+
setDegraded(false);
|
|
263
|
+
setResuming(true);
|
|
264
|
+
|
|
265
|
+
if (!deps.getNode() && deps.ensureNode) {
|
|
266
|
+
await runEnsureNode();
|
|
267
|
+
if (epoch !== myEpoch) return; // superseded by a background flap
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const node = deps.getNode();
|
|
271
|
+
if (node && !node.running && deps.ensureNode) {
|
|
272
|
+
await runEnsureNode();
|
|
273
|
+
if (epoch !== myEpoch) return;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
attachNodeListeners();
|
|
277
|
+
|
|
278
|
+
const live = deps.getNode();
|
|
279
|
+
if (live) {
|
|
280
|
+
const connected = await awaitControlConnected(live);
|
|
281
|
+
if (epoch !== myEpoch) return;
|
|
282
|
+
setDegraded(!connected);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
setResuming(false);
|
|
286
|
+
setState('foreground');
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function runEnsureNode(): Promise<void> {
|
|
290
|
+
try {
|
|
291
|
+
await deps.ensureNode!();
|
|
292
|
+
} catch (err) {
|
|
293
|
+
console.warn('[background-runner] ensureNode (cold start) failed:', err);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// 'inactive' (iOS transient overlay: incoming call, control center, app
|
|
298
|
+
// switcher peek) is deliberately a no-op — hibernating on it would tear down
|
|
299
|
+
// strands during a brief overlay the user immediately dismisses. Only a real
|
|
300
|
+
// 'background' triggers the hibernate sweep.
|
|
301
|
+
function handleAppState(status: AppStateValue): void {
|
|
302
|
+
if (!active) return;
|
|
303
|
+
if (status === 'background') {
|
|
304
|
+
void handleBackground();
|
|
305
|
+
} else if (status === 'active') {
|
|
306
|
+
void handleForeground();
|
|
307
|
+
}
|
|
308
|
+
// 'inactive' and any other value: no-op.
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// ── public surface ──────────────────────────────────────────────────────────
|
|
312
|
+
|
|
313
|
+
function start(): void {
|
|
314
|
+
if (subscription) return; // idempotent
|
|
315
|
+
active = true;
|
|
316
|
+
subscription = deps.appState.addEventListener('change', handleAppState);
|
|
317
|
+
attachNodeListeners();
|
|
318
|
+
// Node is assumed already started (Settings start, or cold-start completed
|
|
319
|
+
// before the hook mounts the runner) → land in FOREGROUND.
|
|
320
|
+
setState('foreground');
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function stop(): void {
|
|
324
|
+
active = false;
|
|
325
|
+
epoch++; // invalidate any in-flight resume/hibernate
|
|
326
|
+
if (subscription) {
|
|
327
|
+
subscription.remove();
|
|
328
|
+
subscription = null;
|
|
329
|
+
}
|
|
330
|
+
detachNodeListeners();
|
|
331
|
+
// Abort any in-flight settle (removes its `control:connected` listener +
|
|
332
|
+
// timer and resolves it); the epoch bump above makes the resolved handler
|
|
333
|
+
// bail before touching state. Snapshot first — `finish` mutates the set.
|
|
334
|
+
for (const finish of [...pendingSettles]) finish(false);
|
|
335
|
+
pendingSettles.clear();
|
|
336
|
+
for (const timer of pendingTimers) clearTimeout(timer);
|
|
337
|
+
pendingTimers.clear();
|
|
338
|
+
setResuming(false);
|
|
339
|
+
setDegraded(false);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function onStateChange(cb: (s: RunnerState) => void): () => void {
|
|
343
|
+
stateListeners.add(cb);
|
|
344
|
+
return () => {
|
|
345
|
+
stateListeners.delete(cb);
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
return {
|
|
350
|
+
get state() {
|
|
351
|
+
return state;
|
|
352
|
+
},
|
|
353
|
+
get resuming() {
|
|
354
|
+
return resuming;
|
|
355
|
+
},
|
|
356
|
+
get degraded() {
|
|
357
|
+
return degraded;
|
|
358
|
+
},
|
|
359
|
+
start,
|
|
360
|
+
stop,
|
|
361
|
+
onStateChange,
|
|
362
|
+
};
|
|
363
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@serfab/cadre-client/lifecycle` — hibernate a device's node when the app goes to the background
|
|
3
|
+
* and resume it, bounded, when it returns (`createBackgroundRunner`).
|
|
4
|
+
*
|
|
5
|
+
* Platform-neutral: the app passes its platform's app-state events in (`AppStateLike`; React
|
|
6
|
+
* Native's `AppState` is one) and the node hooks. On React Native, `@serfab/cadre-rn/lifecycle`
|
|
7
|
+
* adds `phoneNodeLifecycle`, the hooks over a `PhoneNode`.
|
|
8
|
+
*/
|
|
9
|
+
export {
|
|
10
|
+
createBackgroundRunner,
|
|
11
|
+
type AppStateLike,
|
|
12
|
+
type AppStateSubscription,
|
|
13
|
+
type AppStateValue,
|
|
14
|
+
type BackgroundRunner,
|
|
15
|
+
type BackgroundRunnerDeps,
|
|
16
|
+
type RunnerState,
|
|
17
|
+
} from './background-runner.js';
|
package/src/loader.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The loader store: one load state machine for a cadre screen.
|
|
3
|
+
*
|
|
4
|
+
* { state: 'loading' } nothing read yet
|
|
5
|
+
* { state: 'ready', value, error? } read; `error` set when the LAST refresh
|
|
6
|
+
* failed and the value shown is the previous one
|
|
7
|
+
* { state: 'failed', error } the first read failed
|
|
8
|
+
*
|
|
9
|
+
* It reads when its first subscriber arrives, then again on each change signal it is
|
|
10
|
+
* given — debounced, one read at a time, one more read if a change arrives during a
|
|
11
|
+
* read — and on an optional backstop poll, for what no signal covers. It stops all of
|
|
12
|
+
* that when its last subscriber leaves.
|
|
13
|
+
*/
|
|
14
|
+
import { describeThrown, type CadreError, type CadreResult } from './result.js';
|
|
15
|
+
import { writable, type Readable } from './store.js';
|
|
16
|
+
|
|
17
|
+
export type LoadState<T> =
|
|
18
|
+
| { state: 'loading'; value?: undefined; error?: undefined; refreshing: boolean }
|
|
19
|
+
| { state: 'ready'; value: T; error?: CadreError; refreshing: boolean }
|
|
20
|
+
| { state: 'failed'; value?: undefined; error: CadreError; refreshing: boolean };
|
|
21
|
+
|
|
22
|
+
export interface LoaderOptions<T> {
|
|
23
|
+
load: () => Promise<CadreResult<T>>;
|
|
24
|
+
/** Subscribe to whatever should trigger a re-read; returns an unsubscribe. */
|
|
25
|
+
changes?: (onChange: () => void) => () => void;
|
|
26
|
+
/** Backstop poll, ms. */
|
|
27
|
+
pollMs?: number;
|
|
28
|
+
/** Coalesce a burst of change signals into one read. Default 500 ms. */
|
|
29
|
+
debounceMs?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface Loader<T> extends Readable<LoadState<T>> {
|
|
33
|
+
/** Read now (coalesced with a read in flight). */
|
|
34
|
+
reload(): void;
|
|
35
|
+
/** Read now and resolve when that read has settled. */
|
|
36
|
+
refresh(): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function loader<T>(opts: LoaderOptions<T>): Loader<T> {
|
|
40
|
+
const debounceMs = opts.debounceMs ?? 500;
|
|
41
|
+
let active = false;
|
|
42
|
+
let inFlight: Promise<void> | null = null;
|
|
43
|
+
let again = false;
|
|
44
|
+
let debounce: ReturnType<typeof setTimeout> | null = null;
|
|
45
|
+
let poll: ReturnType<typeof setTimeout> | null = null;
|
|
46
|
+
let unsubscribeChanges: (() => void) | null = null;
|
|
47
|
+
|
|
48
|
+
const store = writable<LoadState<T>>({ state: 'loading', refreshing: false }, () => {
|
|
49
|
+
active = true;
|
|
50
|
+
unsubscribeChanges = opts.changes?.(scheduleFromChange) ?? null;
|
|
51
|
+
void run();
|
|
52
|
+
return () => {
|
|
53
|
+
active = false;
|
|
54
|
+
unsubscribeChanges?.();
|
|
55
|
+
unsubscribeChanges = null;
|
|
56
|
+
if (debounce !== null) clearTimeout(debounce);
|
|
57
|
+
if (poll !== null) clearTimeout(poll);
|
|
58
|
+
debounce = poll = null;
|
|
59
|
+
};
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
function scheduleFromChange() {
|
|
63
|
+
if (!active || debounce !== null) return;
|
|
64
|
+
debounce = setTimeout(() => { debounce = null; void run(); }, debounceMs);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function schedulePoll() {
|
|
68
|
+
if (poll !== null) clearTimeout(poll);
|
|
69
|
+
poll = null;
|
|
70
|
+
if (active && opts.pollMs) poll = setTimeout(() => { poll = null; void run(); }, opts.pollMs);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function run(): Promise<void> {
|
|
74
|
+
if (inFlight) { again = true; return inFlight; }
|
|
75
|
+
store.update(s => (s.refreshing ? s : { ...s, refreshing: true }));
|
|
76
|
+
inFlight = (async () => {
|
|
77
|
+
let result: CadreResult<T>;
|
|
78
|
+
try {
|
|
79
|
+
result = await opts.load();
|
|
80
|
+
} catch (err) {
|
|
81
|
+
// Operations report failures as results; a throw is a defect, shown rather than lost.
|
|
82
|
+
result = { ok: false, error: { kind: 'unexpected', retryable: false, message: describeThrown(err), cause: err } };
|
|
83
|
+
}
|
|
84
|
+
store.update(s => {
|
|
85
|
+
if (result.ok) return { state: 'ready', value: result.value, refreshing: false };
|
|
86
|
+
if (s.state === 'ready') return { state: 'ready', value: s.value, error: result.error, refreshing: false };
|
|
87
|
+
return { state: 'failed', error: result.error, refreshing: false };
|
|
88
|
+
});
|
|
89
|
+
})().finally(() => {
|
|
90
|
+
inFlight = null;
|
|
91
|
+
if (again && active) { again = false; void run(); }
|
|
92
|
+
else { again = false; schedulePoll(); }
|
|
93
|
+
});
|
|
94
|
+
return inFlight;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
subscribe: store.subscribe,
|
|
99
|
+
get: store.get,
|
|
100
|
+
reload: () => { void run(); },
|
|
101
|
+
refresh: () => run(),
|
|
102
|
+
};
|
|
103
|
+
}
|