@johnhenry/browsermesh-apps 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +443 -1
  2. package/package.json +18 -3
  3. package/src/agent-runtime.mjs +342 -0
  4. package/src/chunk-replication.mjs +751 -0
  5. package/src/cloud-storage-backend.mjs +932 -0
  6. package/src/cloud-storage.mjs +799 -0
  7. package/src/compat.mjs +98 -0
  8. package/src/gpu-kernel.mjs +242 -0
  9. package/src/gpu.mjs +101 -7
  10. package/src/grant-log.mjs +840 -0
  11. package/src/index.mjs +32 -2
  12. package/src/kernel-mesh.mjs +56 -0
  13. package/src/key-distribution.mjs +525 -0
  14. package/src/manifest-sync.mjs +363 -0
  15. package/src/mesh-agent-swarm.mjs +376 -0
  16. package/src/mesh-bootstrap.mjs +1481 -0
  17. package/src/mesh-compute.mjs +397 -0
  18. package/src/mesh-dht.mjs +182 -0
  19. package/src/mesh-fetch.mjs +246 -0
  20. package/src/mesh-hardening.mjs +226 -0
  21. package/src/mesh-health.mjs +282 -0
  22. package/src/mesh-keepalive.mjs +353 -0
  23. package/src/mesh-kv.mjs +673 -0
  24. package/src/mesh-orchestrator-tools.mjs +251 -0
  25. package/src/mesh-orchestrator.mjs +343 -0
  26. package/src/mesh-relay-backend.mjs +289 -0
  27. package/src/mesh-relay-host.mjs +362 -0
  28. package/src/mesh-rpc.mjs +300 -0
  29. package/src/mesh-service.mjs +403 -0
  30. package/src/mesh-swarm.mjs +677 -0
  31. package/src/mesh-sync.mjs +253 -0
  32. package/src/mesh-timestamp.mjs +265 -0
  33. package/src/mesh-torrent.mjs +683 -0
  34. package/src/mesh-verification.mjs +367 -0
  35. package/src/mesh-websocket.mjs +722 -0
  36. package/src/observability-bridge.mjs +453 -0
  37. package/src/orchestrator.mjs +18 -5
  38. package/src/peer-agent-swarm.mjs +12 -1
  39. package/src/peer-chat.mjs +230 -61
  40. package/src/peer-compute.mjs +66 -3
  41. package/src/peer-escrow.mjs +350 -1
  42. package/src/peer-files.mjs +362 -168
  43. package/src/peer-ipfs.mjs +205 -10
  44. package/src/peer-node.mjs +127 -19
  45. package/src/peer-registry.mjs +242 -18
  46. package/src/peer-routing.mjs +369 -5
  47. package/src/peer-terminal.mjs +400 -130
  48. package/src/signaling.mjs +231 -0
  49. package/src/webrtc-negotiator.mjs +209 -0
  50. package/src/peer-session.mjs +0 -937
@@ -0,0 +1,282 @@
1
+ /**
2
+ * mesh-health.mjs -- Phase 1 of the browsermesh-app-layer-migration plan
3
+ * (issue #120): wraps `peer-health.mjs`'s `HealthMonitor` (+ `AutoMigrator`,
4
+ * opt-in) as a `MeshService` (`mesh-service.mjs`, Phase C's `attach()`/`ctx`
5
+ * convention).
6
+ *
7
+ * ---------------------------------------------------------------------------
8
+ * WHY A SEPARATE FILE FROM `mesh-timestamp.mjs` (the plan's "could be one
9
+ * file or two -- your call, document why"): every existing `mesh-*.mjs`
10
+ * wrapper in this package corresponds to ONE cohesive wire-protocol/feature
11
+ * area (`mesh-rpc.mjs` is request/response only, `mesh-keepalive.mjs` is
12
+ * ping/pong liveness only). `mesh-kv.mjs` is the one file that composes two
13
+ * services together, but only because `MeshKv`'s `grant()`/`revoke()`
14
+ * genuinely has to sequence `GrantLog` + the KV sync engine together (a real
15
+ * coupling). `peer-timestamp.mjs` (signed consensus timestamping) and
16
+ * `peer-health.mjs` (heartbeat liveness/auto-migration) have no such
17
+ * coupling -- different wire protocols, different envelope types, different
18
+ * `createMeshNode()` opt-in options (`enableTimestamp` vs
19
+ * `enableHealthMonitor`) -- so combining them would just be arbitrary
20
+ * co-location with zero shared code. Two files, matching the family's
21
+ * default (one wrapper per cohesive feature), is the more legible choice.
22
+ *
23
+ * ---------------------------------------------------------------------------
24
+ * SESSIONS ADAPTER -- `HealthMonitor`'s own `#tick()` calls
25
+ * `sessions.listSessions()` and, UNLIKE `TimestampAuthority`, genuinely uses
26
+ * the result: it expects `{remotePodId, send(type, payload)}` entries (see
27
+ * `peer-health.mjs`'s own constructor doc comment). `PeerNode.listSessions()`
28
+ * (`peer-node.mjs`) returns real, live session entries, but shaped as
29
+ * `{pubKey, sessionId, transport, connectedAt, state}` -- `pubKey` instead of
30
+ * `remotePodId`, and no `send()` at all (`transportInstance` is stripped
31
+ * before the caller ever sees it, by design -- see that method's own doc
32
+ * comment). This file bridges the two with a small adapter, routing `send()`
33
+ * through `ctx.sendTo()` (the same dispatch bus every other `MeshService` in
34
+ * this family uses) rather than reaching for a raw transport:
35
+ *
36
+ * { remotePodId: session.pubKey, sessionId: session.sessionId,
37
+ * send: (type, payload) => ctx.sendTo(session.pubKey, type, payload) }
38
+ *
39
+ * `session.send('heartbeat:ping', {timestamp})` (the exact call
40
+ * `peer-health.mjs`'s `#tick()` already makes, hardcoded literal type
41
+ * string and all) is CALLED SYNCHRONOUSLY inside a `try/catch` there --
42
+ * but `ctx.sendTo()` is async, so a rejected promise cannot be caught by
43
+ * that synchronous `catch`. The adapter's own `send()` therefore swallows
44
+ * (and logs) any `ctx.sendTo()` rejection itself, so a transient
45
+ * send failure can never become an unhandled rejection escaping
46
+ * `HealthMonitor`'s own tick loop.
47
+ *
48
+ * ---------------------------------------------------------------------------
49
+ * WIRE PROTOCOL this file adds (not owned by `peer-health.mjs` itself,
50
+ * exactly like `mesh-timestamp.mjs`'s witness collection is not owned by
51
+ * `peer-timestamp.mjs`): `HealthMonitor` only ever SENDS `'heartbeat:ping'`
52
+ * envelopes and exposes `recordHeartbeat(podId, latencyMs)` for something
53
+ * else to call when a reply arrives -- it has no receiving-side logic of its
54
+ * own. This file supplies both missing halves via `ctx.onIncomingData()`:
55
+ *
56
+ * - Inbound `'heartbeat:ping'` -> reply with `'heartbeat:pong'`, echoing
57
+ * the ping's own `timestamp` back as `replyTo` (so the asking side can
58
+ * compute round-trip latency), mirroring `mesh-keepalive.mjs`'s own
59
+ * `replyTo` convention for the identical reason.
60
+ * - Inbound `'heartbeat:pong'` -> `monitor.recordHeartbeat(fromPubKey,
61
+ * latencyMs)`, `latencyMs = now - replyTo`.
62
+ *
63
+ * ---------------------------------------------------------------------------
64
+ * AUTO-MIGRATION (opt-in via `opts.orchestrator`) -- `AutoMigrator` is
65
+ * constructed and `.enable()`d only when the caller supplies a duck-typed
66
+ * `orchestrator` (`{drainPod(), deploySkill()?}`). Per the migration plan's
67
+ * own scoping note: this is NOT the unwired `MeshOrchestrator` class from
68
+ * issue #92 -- that class is a different, still-unwired thing, out of scope
69
+ * here. Any caller-supplied orchestrator-shaped object works, matching how
70
+ * every other `MeshService` in this family accepts duck-typed dependencies
71
+ * rather than reaching for one specific class.
72
+ *
73
+ * ---------------------------------------------------------------------------
74
+ * Observability events (`ctx.emit()`, see `mesh-service.mjs`'s module doc
75
+ * comment for the full convention). `HealthMonitor`'s own `on`/`off` events
76
+ * (`'healthy'`, `'degraded'`, `'failed'`, `'recovered'`) and, when
77
+ * `AutoMigrator` is active, its own (`'migrating'`, `'migrated'`,
78
+ * `'migration-failed'`) are bridged through 1:1, not dropped:
79
+ *
80
+ * - `health-monitor:peer-healthy` `PeerHealth.toJSON()` shape
81
+ * - `health-monitor:peer-degraded` `PeerHealth.toJSON()` shape
82
+ * - `health-monitor:peer-failed` `PeerHealth.toJSON()` shape
83
+ * - `health-monitor:peer-recovered` `PeerHealth.toJSON()` shape
84
+ * - `health-monitor:migrating` `{fromPod, toPod}`
85
+ * - `health-monitor:migrated` `MigrationResult.toJSON()` shape
86
+ * - `health-monitor:migration-failed` `MigrationResult.toJSON()` shape
87
+ *
88
+ * No browser-only imports at module level.
89
+ */
90
+
91
+ import { HealthMonitor, AutoMigrator } from './peer-health.mjs'
92
+
93
+ /** Envelope type `HealthMonitor` itself hardcodes for its outbound ping (see `peer-health.mjs`'s `#tick()`). */
94
+ const HEARTBEAT_PING_TYPE = 'heartbeat:ping'
95
+ /** Envelope type this file uses for the reply -- not owned by `peer-health.mjs`, see module doc comment. */
96
+ const HEARTBEAT_PONG_TYPE = 'heartbeat:pong'
97
+
98
+ /**
99
+ * Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) wrapping
100
+ * `HealthMonitor` (+ `AutoMigrator`, opt-in). See this file's module doc
101
+ * comment for the full design writeup.
102
+ *
103
+ * @param {object} [opts]
104
+ * @param {object} [opts.trust] - Passed through to `HealthMonitor` (object
105
+ * with `getReputation(podId)`).
106
+ * @param {object} [opts.orchestrator] - Duck-typed `{drainPod(podId),
107
+ * deploySkill(podId, skill)?}`. When supplied, an `AutoMigrator` is
108
+ * constructed and enabled, automatically migrating workloads off peers
109
+ * `HealthMonitor` reports `'failed'`. See module doc comment's
110
+ * "AUTO-MIGRATION" section for what this is and is not.
111
+ * @param {Function} [opts.resolveWorkload] - Passed through to
112
+ * `AutoMigrator`. Requires `opts.orchestrator.deploySkill` to also be
113
+ * supplied (enforced by `AutoMigrator`'s own constructor).
114
+ * @param {number} [opts.intervalMs] - Heartbeat tick interval, passed to
115
+ * `monitor.start()` (default 10000, see `HEALTH_DEFAULTS`).
116
+ * @param {object} [opts.thresholds] - Passed to `monitor.setThresholds()`
117
+ * before `start()` -- partial overrides of `HEALTH_DEFAULTS`
118
+ * (`heartbeatIntervalMs`/`heartbeatTimeoutMs`/`maxMissedHeartbeats`/
119
+ * `degradedThresholdMs`).
120
+ * @param {Function} [opts.onLog]
121
+ * @returns {import('./mesh-service.mjs').MeshService}
122
+ */
123
+ export function createHealthMonitorService({
124
+ trust,
125
+ orchestrator,
126
+ resolveWorkload,
127
+ intervalMs,
128
+ thresholds,
129
+ onLog,
130
+ } = {}) {
131
+ const log = onLog || (() => {})
132
+
133
+ return {
134
+ name: 'health-monitor',
135
+
136
+ attach(peerNode, ctx) {
137
+ if (typeof peerNode?.listSessions !== 'function') {
138
+ throw new Error(
139
+ 'mesh-health: peerNode must be a real PeerNode providing listSessions() ' +
140
+ '(a duck-typed {sendTo, onIncomingData} node, as other MeshServices in this ' +
141
+ 'family accept, is not enough here -- see module doc comment).',
142
+ )
143
+ }
144
+
145
+ // Bridges PeerNode.listSessions()'s {pubKey, sessionId, ...} shape to
146
+ // the {remotePodId, send(type, payload)} shape HealthMonitor's own
147
+ // #tick() genuinely calls -- see module doc comment's "SESSIONS ADAPTER".
148
+ const sessionsAdapter = {
149
+ listSessions() {
150
+ return peerNode.listSessions().map((session) => ({
151
+ sessionId: session.sessionId,
152
+ remotePodId: session.pubKey,
153
+ send: (type, payload) => {
154
+ ctx.sendTo(session.pubKey, type, payload).catch((err) => {
155
+ log('mesh-health:heartbeat-send-failed', { to: session.pubKey, error: err?.message || String(err) })
156
+ })
157
+ },
158
+ }))
159
+ },
160
+ }
161
+
162
+ const monitor = new HealthMonitor({
163
+ sessions: sessionsAdapter,
164
+ trust,
165
+ onLog: (level, msg) => log('mesh-health:internal', { level, msg }),
166
+ })
167
+
168
+ if (thresholds) monitor.setThresholds(thresholds)
169
+
170
+ // -----------------------------------------------------------------
171
+ // Bridge HealthMonitor's own on/off events into ctx.emit() -- see
172
+ // module doc comment's "Observability events".
173
+ // -----------------------------------------------------------------
174
+ const forwardHealthy = (health) => ctx.emit('health-monitor:peer-healthy', health.toJSON())
175
+ const forwardDegraded = (health) => ctx.emit('health-monitor:peer-degraded', health.toJSON())
176
+ const forwardFailed = (health) => ctx.emit('health-monitor:peer-failed', health.toJSON())
177
+ const forwardRecovered = (health) => ctx.emit('health-monitor:peer-recovered', health.toJSON())
178
+ monitor.on('healthy', forwardHealthy)
179
+ monitor.on('degraded', forwardDegraded)
180
+ monitor.on('failed', forwardFailed)
181
+ monitor.on('recovered', forwardRecovered)
182
+
183
+ // -----------------------------------------------------------------
184
+ // Wire protocol this file adds -- see module doc comment's "WIRE
185
+ // PROTOCOL".
186
+ // -----------------------------------------------------------------
187
+ const unsubscribe = ctx.onIncomingData([HEARTBEAT_PING_TYPE, HEARTBEAT_PONG_TYPE], (fromPubKey, msg) => {
188
+ if (msg.type === HEARTBEAT_PING_TYPE) {
189
+ ctx.sendTo(fromPubKey, HEARTBEAT_PONG_TYPE, { replyTo: msg.timestamp, timestamp: Date.now() }).catch((err) => {
190
+ log('mesh-health:pong-send-failed', { to: fromPubKey, error: err?.message || String(err) })
191
+ })
192
+ } else if (msg.type === HEARTBEAT_PONG_TYPE) {
193
+ const latencyMs = typeof msg.replyTo === 'number' ? Math.max(0, Date.now() - msg.replyTo) : 0
194
+ monitor.recordHeartbeat(fromPubKey, latencyMs)
195
+ }
196
+ })
197
+
198
+ // -----------------------------------------------------------------
199
+ // Auto-migration (opt-in) -- see module doc comment's "AUTO-MIGRATION".
200
+ // -----------------------------------------------------------------
201
+ let autoMigrator = null
202
+ let forwardMigrating, forwardMigrated, forwardMigrationFailed
203
+ if (orchestrator) {
204
+ autoMigrator = new AutoMigrator({
205
+ healthMonitor: monitor,
206
+ orchestrator,
207
+ resolveWorkload,
208
+ onLog: (level, msg) => log('mesh-health:auto-migrator', { level, msg }),
209
+ })
210
+ forwardMigrating = (data) => ctx.emit('health-monitor:migrating', data)
211
+ forwardMigrated = (result) => ctx.emit('health-monitor:migrated', result.toJSON())
212
+ forwardMigrationFailed = (result) => ctx.emit('health-monitor:migration-failed', result.toJSON())
213
+ autoMigrator.on('migrating', forwardMigrating)
214
+ autoMigrator.on('migrated', forwardMigrated)
215
+ autoMigrator.on('migration-failed', forwardMigrationFailed)
216
+ autoMigrator.enable()
217
+ }
218
+
219
+ monitor.start(intervalMs)
220
+
221
+ const api = {
222
+ /** @param {string} podId @returns {import('./peer-health.mjs').PeerHealth|null} */
223
+ getPeerHealth(podId) {
224
+ return monitor.getPeerHealth(podId)
225
+ },
226
+ /** @returns {Map<string, import('./peer-health.mjs').PeerHealth>} */
227
+ getStatus() {
228
+ return monitor.getStatus()
229
+ },
230
+ /** @param {object} partial */
231
+ setThresholds(partial) {
232
+ monitor.setThresholds(partial)
233
+ },
234
+ /** @returns {object} */
235
+ getThresholds() {
236
+ return monitor.getThresholds()
237
+ },
238
+ /** Stop the periodic heartbeat tick. */
239
+ stop() {
240
+ monitor.stop()
241
+ },
242
+ /** (Re)start the periodic heartbeat tick. @param {number} [ms] */
243
+ start(ms) {
244
+ monitor.start(ms)
245
+ },
246
+ /**
247
+ * @param {string} fromPodId
248
+ * @param {string} [toPodId]
249
+ * @returns {Promise<import('./peer-health.mjs').MigrationResult>}
250
+ */
251
+ migrateNow(fromPodId, toPodId) {
252
+ if (!autoMigrator) {
253
+ throw new Error('mesh-health: migrateNow() requires opts.orchestrator to have been supplied at attach time')
254
+ }
255
+ return autoMigrator.migrateNow(fromPodId, toPodId)
256
+ },
257
+ /** The underlying `AutoMigrator`, or `null` if `opts.orchestrator` was not supplied. */
258
+ autoMigrator,
259
+ }
260
+
261
+ return {
262
+ api,
263
+ teardown() {
264
+ monitor.stop()
265
+ monitor.off('healthy', forwardHealthy)
266
+ monitor.off('degraded', forwardDegraded)
267
+ monitor.off('failed', forwardFailed)
268
+ monitor.off('recovered', forwardRecovered)
269
+ if (autoMigrator) {
270
+ autoMigrator.disable()
271
+ autoMigrator.off('migrating', forwardMigrating)
272
+ autoMigrator.off('migrated', forwardMigrated)
273
+ autoMigrator.off('migration-failed', forwardMigrationFailed)
274
+ }
275
+ unsubscribe()
276
+ },
277
+ }
278
+ },
279
+ }
280
+ }
281
+
282
+ export { HEARTBEAT_PING_TYPE, HEARTBEAT_PONG_TYPE }
@@ -0,0 +1,353 @@
1
+ /**
2
+ * mesh-keepalive.mjs -- wires `@johnhenry/browsermesh-core`'s hardening.mjs
3
+ * `TransportHealthCheck` to a REAL keepalive envelope protocol on
4
+ * `PeerNode`'s own dispatch bus (issue #110, follow-up to #109's
5
+ * `mesh-hardening.mjs`, which deliberately left `TransportHealthCheck`
6
+ * unwired -- see that file's own header comment: "a genuine ping/pong
7
+ * liveness probe needs a keepalive envelope type on PeerNode's own dispatch
8
+ * bus... so the far side actually answers pings"). This file is that
9
+ * envelope type and that far-side responder.
10
+ *
11
+ * Built as a `MeshService` (`mesh-service.mjs`, Phase C's attach
12
+ * convention), NOT as a direct patch to `peer-node.mjs`, mirroring
13
+ * `mesh-rpc.mjs`'s closest precedent: wire payloads travel over
14
+ * `ctx.onIncomingData()`/`ctx.sendTo()`, filtered by envelope `type`, on the
15
+ * same dispatch bus every other `MeshService` in this family uses. Unlike
16
+ * `mesh-rpc.mjs`'s single envelope `type` with two `kind`s, this protocol
17
+ * uses two distinct envelope types directly (`'keepalive-ping'`/
18
+ * `'keepalive-pong'`) -- the shape issue #110 itself suggested, and a closer
19
+ * match for `TransportHealthCheck`'s own two-sided ping/pong vocabulary.
20
+ *
21
+ * ---------------------------------------------------------------------------
22
+ * WIRE PROTOCOL -- two envelope types on the shared `onIncomingData()` bus:
23
+ *
24
+ * Ping: `{ type: 'keepalive-ping', timestamp }`
25
+ * Pong: `{ type: 'keepalive-pong', replyTo, timestamp }`
26
+ *
27
+ * `replyTo` echoes the ping's own `timestamp` verbatim (not used for
28
+ * correlation here -- unlike `mesh-rpc.mjs`'s `requestId`, there is at most
29
+ * one ping in flight per peer at a time, enforced by
30
+ * `TransportHealthCheck`'s own `#waitingForPong` bookkeeping -- `replyTo` is
31
+ * carried through purely so a caller inspecting captured pongs can compute
32
+ * round-trip latency, matching the shape issue #110 itself proposed).
33
+ *
34
+ * ---------------------------------------------------------------------------
35
+ * INSTANCE LIFECYCLE -- one `TransportHealthCheck` PER PEER (keyed by
36
+ * `pubKey`), not literally per `sessionId`. This is a deliberate reading of
37
+ * issue #110's "one TransportHealthCheck instance per active session":
38
+ * `PeerNode` keeps at most one ACTIVE session per peer today (`ConnectionPool`
39
+ * is explicitly deferred -- see issue #110's own scoping and
40
+ * `mesh-hardening.mjs`'s header comment), so "per active session" and "per
41
+ * peer" are the same thing in practice. `pubKey` is also the only
42
+ * correlatable key actually available at both ends of this file's own
43
+ * lifecycle hooks: `PeerNode`'s `'peer:connect'`/`'peer:disconnect'` events
44
+ * carry `peer.fingerprint` (the pubKey), not a `sessionId`, and inbound
45
+ * `ctx.onIncomingData()` callbacks are keyed by `fromPubKey`, not by which
46
+ * session delivered the envelope. A future `ConnectionPool` (still
47
+ * deliberately unwired, per issue #110) would need this file revisited to
48
+ * key by session instead.
49
+ *
50
+ * Created on `'peer:connect'`, torn down (via `.stop()`) on
51
+ * `'peer:disconnect'` -- both real `PeerNode` events (`peer-node.mjs`,
52
+ * backed by `PeerRegistry.onPeerConnect()`/`onPeerDisconnect()`), the same
53
+ * hook point `observability-bridge.mjs` already uses for its own
54
+ * connect/disconnect wiring. Peers already connected at the moment this
55
+ * service attaches (e.g. `createMeshNode({ services: [...] })` attaching
56
+ * after some peers already connected) are picked up via a one-time
57
+ * `peerNode.listPeers({ status: 'connected' })` scan when `attach()` runs.
58
+ *
59
+ * ---------------------------------------------------------------------------
60
+ * HARDENING INTEGRATION (opt-in, degrades gracefully) -- an `'unhealthy'`
61
+ * transition ALSO triggers `mesh-hardening.mjs`'s `TransportFailover` for
62
+ * that peer, if `enableHardening` was also turned on for this node. The
63
+ * caller passes `mesh-hardening.mjs`'s `createHardenedNegotiator()` return
64
+ * value straight through as `opts.hardening` (`{ metrics, failovers, retries
65
+ * }` -- see `mesh-bootstrap.mjs`'s own `node.hardening`); this file looks up
66
+ * `hardening.failovers.get(endpointsKey({ webrtc: pubKey }))`, reusing
67
+ * `mesh-hardening.mjs`'s OWN exported `endpointsKey()` and
68
+ * `webrtc-negotiator.mjs`'s established convention that `endpoints.webrtc`
69
+ * IS the remote peer's podId (that file's own doc comment: "by convention
70
+ * here `endpoints.webrtc` is simply the remote peer's podId"). This is the
71
+ * only registered transport adapter in this repo today
72
+ * (`mesh-bootstrap.mjs` never registers anything else), so the convention
73
+ * holds in practice -- but it is a best-effort, webrtc-shaped guess, NOT a
74
+ * real pubKey-keyed index into `hardening.failovers` (that map is keyed by
75
+ * `endpointsKey()`'s hash of the exact `endpoints` object a given
76
+ * `connectToPeer()` call used, which this file never sees). If a peer was
77
+ * connected via a different transport type, or `enableHardening` is off, or
78
+ * no matching `TransportFailover` instance exists yet, `triggerFailover()`
79
+ * silently no-ops (logged via `onLog`, not thrown) -- this file's own
80
+ * liveness tracking and `ctx.emit()` events work identically either way.
81
+ *
82
+ * ---------------------------------------------------------------------------
83
+ * BONUS NATIVE-TRANSPORT-CLOSE WIRING (issue #110's "bonus" item) --
84
+ * `peer-node.mjs`'s `#createSession()` now also wires a session's
85
+ * `transportInstance.onClose()`/`.onError()` (duck-typed against
86
+ * `@johnhenry/browsermesh-transport`'s `MeshTransport` base class -- works
87
+ * for `WebRTCTransportAdapter`, whose `onClose`/`onError` ultimately derive
88
+ * from `RTCPeerConnection.connectionState`, but is not webrtc-specific) to
89
+ * two new `PeerNode`-level events: `'peer:transport-close'`/
90
+ * `'peer:transport-error'` (see `peer-node.mjs`'s own `on()` doc comment).
91
+ * This file subscribes to both as a STRONGER, IMMEDIATE complement to its
92
+ * own ping/pong escalation: rather than waiting out `maxMissed` missed pings
93
+ * (the default `TransportHealthCheck` timeline is ~15-30s), a
94
+ * `'peer:transport-close'` for a peer this file is tracking immediately
95
+ * emits `'keepalive:peer-unhealthy'` and triggers failover, without waiting
96
+ * for the next ping cycle. `TransportHealthCheck` itself has no public
97
+ * "force unhealthy now" method (its `on()`/`off()`/`recordPong()`/
98
+ * `start()`/`stop()` surface is the full public API -- see
99
+ * `hardening.mjs`), so this bypasses it rather than trying to fake a missed
100
+ * pong into it.
101
+ *
102
+ * ---------------------------------------------------------------------------
103
+ * Observability events (`ctx.emit()`, Phase 1 of the mesh-KV-and-
104
+ * observability plan -- see `mesh-service.mjs`'s module doc comment for the
105
+ * full convention). Curated vocabulary:
106
+ *
107
+ * - `keepalive:peer-healthy` `{pubKey}` -- a peer's `TransportHealthCheck`
108
+ * (re)entered `'healthy'` (first pong, or recovery from degraded/unhealthy).
109
+ * - `keepalive:peer-degraded` `{pubKey, missedCount}` -- 1..maxMissed-1
110
+ * consecutive missed pongs.
111
+ * - `keepalive:peer-unhealthy` `{pubKey, missedCount, reason}` -- `reason`
112
+ * is `'ping-timeout'` for the normal ping/pong escalation path, or
113
+ * `'transport-close'`/`'transport-error'` for the bonus wiring above.
114
+ * - `keepalive:failover-triggered` `{pubKey, reason}` -- this file
115
+ * successfully called `TransportFailover.failover()` for a peer (only
116
+ * possible when `enableHardening` is also on and a matching failover
117
+ * instance was found -- see "HARDENING INTEGRATION" above).
118
+ *
119
+ * No browser-only imports at module level.
120
+ */
121
+
122
+ import { TransportHealthCheck } from '@johnhenry/browsermesh-core'
123
+ import { endpointsKey } from './mesh-hardening.mjs'
124
+
125
+ /** Envelope type for the outbound liveness probe. */
126
+ const PING_TYPE = 'keepalive-ping'
127
+ /** Envelope type for the reply to a liveness probe. */
128
+ const PONG_TYPE = 'keepalive-pong'
129
+
130
+ /**
131
+ * Build a `MeshService` descriptor (`mesh-service.mjs`) that runs a real
132
+ * ping/pong keepalive protocol per connected peer, backed by
133
+ * `@johnhenry/browsermesh-core`'s `TransportHealthCheck`. See this file's
134
+ * module doc comment for the full wire-protocol/lifecycle/hardening-
135
+ * integration writeup.
136
+ *
137
+ * @param {object} [opts]
138
+ * @param {number} [opts.intervalMs] - Passed to each per-peer
139
+ * `TransportHealthCheck` (default 10000, see `hardening.mjs`).
140
+ * @param {number} [opts.timeoutMs] - Passed to each per-peer
141
+ * `TransportHealthCheck` (default 5000).
142
+ * @param {number} [opts.maxMissed] - Passed to each per-peer
143
+ * `TransportHealthCheck` (default 3).
144
+ * @param {Function} [opts.nowFn] - Clock override, for testing.
145
+ * @param {{failovers: Map<string, import('@johnhenry/browsermesh-core').TransportFailover>}} [opts.hardening]
146
+ * `createHardenedNegotiator()`'s return value (`mesh-bootstrap.mjs`'s
147
+ * `node.hardening`), or `undefined`/`null` to skip failover integration
148
+ * entirely (this file works fine without it -- see "HARDENING
149
+ * INTEGRATION" above).
150
+ * @param {Function} [opts.onLog]
151
+ * @returns {import('./mesh-service.mjs').MeshService}
152
+ */
153
+ export function createMeshKeepaliveService({
154
+ intervalMs,
155
+ timeoutMs,
156
+ maxMissed,
157
+ nowFn = Date.now,
158
+ hardening,
159
+ onLog,
160
+ } = {}) {
161
+ const log = onLog || (() => {})
162
+
163
+ return {
164
+ name: 'keepalive',
165
+
166
+ attach(peerNode, ctx) {
167
+ if (typeof peerNode?.on !== 'function' || typeof peerNode?.off !== 'function') {
168
+ throw new Error(
169
+ 'mesh-keepalive: peerNode must be a real PeerNode providing on()/off() ' +
170
+ '("peer:connect"/"peer:disconnect" -- a duck-typed {sendTo, onIncomingData} ' +
171
+ 'node, as other MeshServices in this family accept, is not enough here).',
172
+ )
173
+ }
174
+
175
+ /** @type {Map<string, import('@johnhenry/browsermesh-core').TransportHealthCheck>} pubKey -> health check */
176
+ const checks = new Map()
177
+
178
+ /**
179
+ * Best-effort lookup of the `TransportFailover` instance
180
+ * `mesh-hardening.mjs` scoped to this peer -- see module doc comment's
181
+ * "HARDENING INTEGRATION" section for why this is a webrtc-convention
182
+ * guess, not a real index.
183
+ * @param {string} pubKey
184
+ * @returns {import('@johnhenry/browsermesh-core').TransportFailover|null}
185
+ */
186
+ function getFailoverFor(pubKey) {
187
+ if (!hardening?.failovers) return null
188
+ return hardening.failovers.get(endpointsKey({ webrtc: pubKey })) || null
189
+ }
190
+
191
+ /**
192
+ * @param {string} pubKey
193
+ * @param {string} reason
194
+ */
195
+ async function triggerFailover(pubKey, reason) {
196
+ const failover = getFailoverFor(pubKey)
197
+ if (!failover) return
198
+ if (failover.failingOver) return
199
+ try {
200
+ await failover.failover(reason)
201
+ ctx.emit('keepalive:failover-triggered', { pubKey, reason })
202
+ } catch (err) {
203
+ log('mesh-keepalive:failover-failed', { pubKey, reason, error: err?.message || String(err) })
204
+ }
205
+ }
206
+
207
+ /** @param {string} pubKey */
208
+ function startCheckFor(pubKey) {
209
+ if (!pubKey || checks.has(pubKey)) return
210
+
211
+ const check = new TransportHealthCheck({
212
+ // TransportHealthCheck requires a truthy `transport` but only
213
+ // threads it through to pingFn/its own emitted event payloads --
214
+ // this file tracks liveness by pubKey, not by a real transport
215
+ // reference, so a small duck-typed placeholder is sufficient.
216
+ transport: { pubKey, type: 'mesh-keepalive' },
217
+ pingFn: () => {
218
+ ctx.sendTo(pubKey, PING_TYPE, { timestamp: nowFn() }).catch((err) => {
219
+ log('mesh-keepalive:ping-send-failed', { pubKey, error: err?.message || String(err) })
220
+ })
221
+ },
222
+ intervalMs,
223
+ timeoutMs,
224
+ maxMissed,
225
+ nowFn,
226
+ })
227
+
228
+ check.on('healthy', () => {
229
+ ctx.emit('keepalive:peer-healthy', { pubKey })
230
+ })
231
+ check.on('degraded', () => {
232
+ ctx.emit('keepalive:peer-degraded', { pubKey, missedCount: check.missedCount })
233
+ })
234
+ check.on('unhealthy', () => {
235
+ ctx.emit('keepalive:peer-unhealthy', { pubKey, missedCount: check.missedCount, reason: 'ping-timeout' })
236
+ triggerFailover(pubKey, 'keepalive:unhealthy').catch((err) => {
237
+ log('mesh-keepalive:trigger-failover-error', { pubKey, error: err?.message || String(err) })
238
+ })
239
+ })
240
+
241
+ checks.set(pubKey, check)
242
+ check.start()
243
+ }
244
+
245
+ /** @param {string} pubKey */
246
+ function stopCheckFor(pubKey) {
247
+ const check = checks.get(pubKey)
248
+ if (!check) return
249
+ check.stop()
250
+ checks.delete(pubKey)
251
+ }
252
+
253
+ // -----------------------------------------------------------------
254
+ // Instance lifecycle -- see module doc comment's "INSTANCE LIFECYCLE".
255
+ // -----------------------------------------------------------------
256
+
257
+ function handlePeerConnect(peer) {
258
+ if (peer?.fingerprint) startCheckFor(peer.fingerprint)
259
+ }
260
+ function handlePeerDisconnect(peer) {
261
+ if (peer?.fingerprint) stopCheckFor(peer.fingerprint)
262
+ }
263
+ // Bonus wiring (issue #110) -- see module doc comment's "BONUS
264
+ // NATIVE-TRANSPORT-CLOSE WIRING". A stronger, immediate signal than
265
+ // waiting out maxMissed ping/pong cycles.
266
+ function handleTransportClose({ pubKey } = {}) {
267
+ if (!pubKey || !checks.has(pubKey)) return
268
+ ctx.emit('keepalive:peer-unhealthy', { pubKey, missedCount: checks.get(pubKey).missedCount, reason: 'transport-close' })
269
+ triggerFailover(pubKey, 'keepalive:transport-close').catch((err) => {
270
+ log('mesh-keepalive:trigger-failover-error', { pubKey, error: err?.message || String(err) })
271
+ })
272
+ }
273
+ function handleTransportError({ pubKey, error } = {}) {
274
+ if (!pubKey || !checks.has(pubKey)) return
275
+ ctx.emit('keepalive:peer-unhealthy', { pubKey, missedCount: checks.get(pubKey).missedCount, reason: 'transport-error' })
276
+ log('mesh-keepalive:transport-error', { pubKey, error })
277
+ triggerFailover(pubKey, 'keepalive:transport-error').catch((err) => {
278
+ log('mesh-keepalive:trigger-failover-error', { pubKey, error: err?.message || String(err) })
279
+ })
280
+ }
281
+
282
+ peerNode.on('peer:connect', handlePeerConnect)
283
+ peerNode.on('peer:disconnect', handlePeerDisconnect)
284
+ peerNode.on('peer:transport-close', handleTransportClose)
285
+ peerNode.on('peer:transport-error', handleTransportError)
286
+
287
+ // Peers already connected before this service attached (e.g.
288
+ // createMeshNode({ services }) attaching after some connectToPeer()
289
+ // calls already happened) -- listPeers() is safe to call regardless
290
+ // of PeerNode's own lifecycle state (see peer-node.mjs).
291
+ if (typeof peerNode.listPeers === 'function') {
292
+ for (const peer of peerNode.listPeers({ status: 'connected' })) {
293
+ if (peer?.fingerprint) startCheckFor(peer.fingerprint)
294
+ }
295
+ }
296
+
297
+ // -----------------------------------------------------------------
298
+ // Inbound dispatch -- see module doc comment's "WIRE PROTOCOL".
299
+ // -----------------------------------------------------------------
300
+
301
+ const unsubscribeData = ctx.onIncomingData([PING_TYPE, PONG_TYPE], (fromPubKey, msg) => {
302
+ if (msg.type === PING_TYPE) {
303
+ // The far side answering a ping is the whole point of this file
304
+ // -- mesh-hardening.mjs's own header comment flagged this as the
305
+ // missing half of a genuine health check.
306
+ ctx.sendTo(fromPubKey, PONG_TYPE, { replyTo: msg.timestamp, timestamp: nowFn() }).catch((err) => {
307
+ log('mesh-keepalive:pong-send-failed', { to: fromPubKey, error: err?.message || String(err) })
308
+ })
309
+ } else if (msg.type === PONG_TYPE) {
310
+ const check = checks.get(fromPubKey)
311
+ if (check) check.recordPong()
312
+ }
313
+ })
314
+
315
+ const api = {
316
+ /**
317
+ * @param {string} pubKey
318
+ * @returns {'healthy'|'degraded'|'unhealthy'|null} `null` if this
319
+ * peer is not currently tracked (never connected, or already
320
+ * disconnected).
321
+ */
322
+ getStatus(pubKey) {
323
+ return checks.get(pubKey)?.status ?? null
324
+ },
325
+ /**
326
+ * @param {string} pubKey
327
+ * @returns {import('@johnhenry/browsermesh-core').TransportHealthCheck|null}
328
+ */
329
+ getCheck(pubKey) {
330
+ return checks.get(pubKey) || null
331
+ },
332
+ /** @returns {string[]} pubKeys currently tracked. */
333
+ listTracked() {
334
+ return [...checks.keys()]
335
+ },
336
+ }
337
+
338
+ return {
339
+ api,
340
+ teardown() {
341
+ peerNode.off('peer:connect', handlePeerConnect)
342
+ peerNode.off('peer:disconnect', handlePeerDisconnect)
343
+ peerNode.off('peer:transport-close', handleTransportClose)
344
+ peerNode.off('peer:transport-error', handleTransportError)
345
+ unsubscribeData()
346
+ for (const pubKey of [...checks.keys()]) stopCheckFor(pubKey)
347
+ },
348
+ }
349
+ },
350
+ }
351
+ }
352
+
353
+ export { PING_TYPE, PONG_TYPE }