@johnhenry/browsermesh-apps 0.2.0 → 0.4.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 +232 -1
  2. package/package.json +7 -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 +859 -0
  7. package/src/compat.mjs +98 -0
  8. package/src/grant-log.mjs +840 -0
  9. package/src/index.mjs +34 -2
  10. package/src/key-distribution.mjs +525 -0
  11. package/src/manifest-sync.mjs +363 -0
  12. package/src/mesh-agent-swarm.mjs +376 -0
  13. package/src/mesh-bootstrap.mjs +1131 -12
  14. package/src/mesh-compute.mjs +397 -0
  15. package/src/mesh-dht.mjs +182 -0
  16. package/src/mesh-fetch.mjs +246 -0
  17. package/src/mesh-hardening.mjs +226 -0
  18. package/src/mesh-health.mjs +282 -0
  19. package/src/mesh-keepalive.mjs +353 -0
  20. package/src/mesh-kv.mjs +673 -0
  21. package/src/mesh-orchestrator-tools.mjs +251 -0
  22. package/src/mesh-orchestrator.mjs +343 -0
  23. package/src/mesh-rpc.mjs +300 -0
  24. package/src/mesh-service.mjs +403 -0
  25. package/src/mesh-swarm.mjs +677 -0
  26. package/src/mesh-timestamp.mjs +265 -0
  27. package/src/mesh-torrent.mjs +683 -0
  28. package/src/mesh-verification.mjs +367 -0
  29. package/src/mesh-websocket.mjs +722 -0
  30. package/src/observability-bridge.mjs +453 -0
  31. package/src/orchestrator.mjs +18 -5
  32. package/src/peer-agent-swarm.mjs +12 -1
  33. package/src/peer-chat.mjs +230 -61
  34. package/src/peer-compute.mjs +66 -3
  35. package/src/peer-escrow.mjs +350 -1
  36. package/src/peer-files.mjs +362 -168
  37. package/src/peer-ipfs.mjs +205 -10
  38. package/src/peer-node.mjs +33 -2
  39. package/src/peer-routing.mjs +369 -5
  40. package/src/peer-terminal.mjs +400 -130
  41. package/src/serverless-executor-andbox.mjs +136 -0
  42. package/src/serverless-fetch.mjs +70 -0
  43. package/src/serverless-functions.mjs +67 -0
  44. package/src/serverless-peer-select.mjs +69 -0
  45. package/src/serverless-proxy.mjs +127 -0
  46. package/src/serverless-router.mjs +115 -0
  47. package/src/serverless-sites.mjs +116 -0
  48. package/src/serverless-static.mjs +202 -0
  49. package/src/serverless-wire.mjs +87 -0
  50. package/src/peer-session.mjs +0 -937
@@ -0,0 +1,677 @@
1
+ /**
2
+ * mesh-swarm.mjs -- wires `@johnhenry/browsermesh-discovery`'s `swarm.mjs`
3
+ * (issue #88): a complete, previously-unconstructed SWIM failure-detection +
4
+ * leader-election + task-distribution stack (`SwimMembership`,
5
+ * `SwarmCoordinator`, wrapping `LeaderElection`/`TaskDistributor`
6
+ * internally). Despite importing from the shared `MESH_TYPE` wire registry,
7
+ * nothing anywhere constructed any of these classes before this file -- see
8
+ * the issue for the full audit trail. Follows the exact `MeshService`
9
+ * `attach(peerNode, ctx)` convention every other service in this package
10
+ * uses (`peer-routing.mjs`'s `createMeshRoutingService()` is the closest,
11
+ * most recent template).
12
+ *
13
+ * ---------------------------------------------------------------------------
14
+ * SWIM BRIDGE -- mechanical, mirrors `peer-routing.mjs`'s `forwardFn`/
15
+ * `handleRoutedMessage` pattern exactly: `SwimMembership`'s only network
16
+ * side effect is `sendFn(targetId, msg)`; inbound wire traffic is fed in via
17
+ * `handleMessage(fromId, msg)`. One wrinkle `peer-routing.mjs` didn't have to
18
+ * deal with: `SwimMembership`'s own wire messages ALREADY carry a `type`
19
+ * field (`SWIM_PING`/`SWIM_ACK`/etc, numeric), and `ctx.sendTo(pubKey, type,
20
+ * payload)` builds `{ type, ...payload }` -- spreading `payload` LAST, so a
21
+ * bare `msg` passed as `payload` would silently overwrite the outer envelope
22
+ * `type` (a string, what `ctx.onIncomingData()` filters on) with SWIM's own
23
+ * numeric `type`, breaking dispatch entirely. This file nests SWIM's message
24
+ * under its own `msg` key (`ctx.sendTo(targetId, swimEnvelopeType, { msg })`)
25
+ * to avoid the collision, unwrapping on receipt (`envelope.msg`).
26
+ *
27
+ * `swim.start()` is called here (SwimMembership itself never starts its own
28
+ * ping loop); `swim.stop()` runs in `teardown()` -- this clears SWIM's
29
+ * internal ping/suspect timers, mirroring how issue #110's keepalive
30
+ * teardown was verified to leave no leaked timers.
31
+ *
32
+ * ---------------------------------------------------------------------------
33
+ * SINGLE-SLOT CALLBACK COMPOSITION -- `SwimMembership.onJoin`/`onDead`/
34
+ * `onSuspect`/`onLeave` are plain properties, not a real emitter (one
35
+ * listener each, last write wins). `new SwarmCoordinator(localPodId, {
36
+ * swim })` ALREADY assigns `swim.onJoin`/`swim.onDead` in its own
37
+ * constructor (to call `this.join(podId)`/`this.leave(podId)`, making
38
+ * membership genuinely SWIM-driven) -- so this file must WRAP those two,
39
+ * not overwrite them, or `SwarmCoordinator`'s own membership wiring breaks
40
+ * silently. `onSuspect` is untouched by `SwarmCoordinator` and is set
41
+ * directly.
42
+ *
43
+ * `onLeave`, however, ALSO needs to drive `coordinator.leave()`, even
44
+ * though `SwarmCoordinator`'s constructor never wires it: a 'left' state
45
+ * can reach a node two ways -- (a) its OWN local dead-detection
46
+ * (`#onSuspectTimeout` sets 'dead', fires `onDead`, and `coordinator
47
+ * .leave()` -- invoked by the wrapped `onDead` -- itself calls
48
+ * `swim.removeMember()`, which unconditionally overwrites state to 'left'
49
+ * and fires `onLeave` too, so BOTH `swarm:member-dead` and
50
+ * `swarm:member-left` fire for that node); or (b) purely via GOSSIP, when
51
+ * another peer's already-'left' update about a THIRD node arrives here
52
+ * first -- `SwimMembership`'s own `#fireStateCallbacks` fires only the
53
+ * callback matching the state it just applied, so a gossip-received 'left'
54
+ * fires `onLeave` alone, with `onDead` never called on THIS node's view at
55
+ * all. Without `onLeave` also driving `coordinator.leave()`, path (b) would
56
+ * leave that podId in this node's own election candidate pool and
57
+ * distributor member list forever (confirmed by testing: without this, two
58
+ * survivors could permanently disagree on whether a dead leader was still a
59
+ * candidate). Driving `coordinator.leave()` from `onLeave` reintroduces the
60
+ * same recursion hazard one level deeper, though: `coordinator.leave()`
61
+ * calls `swim.removeMember()`, which re-fires `onLeave` unconditionally (no
62
+ * "already left" guard of its own) -- so `onLeave` -> `coordinator.leave()`
63
+ * -> `removeMember()` -> `onLeave` again would recurse forever without a
64
+ * guard. `leaveHandled` (a `Set`, below) is that guard: whichever of
65
+ * `onDead`/`onLeave`/the explicit `'leave'` wire message (`handleLeave()`)
66
+ * observes a given podId's departure FIRST performs the real
67
+ * `coordinator.leave()` and marks it done; every later call for the same
68
+ * podId becomes a no-op, while `ctx.emit()` still fires exactly once per
69
+ * real transition from whichever wrapper actually ran the logic. Cleared on
70
+ * rejoin (`onJoin`) so a podId that leaves and later rejoins is handled
71
+ * again correctly.
72
+ *
73
+ * ---------------------------------------------------------------------------
74
+ * LEADER ELECTION HEARTBEAT PUMP -- genuinely new logic (nothing in
75
+ * `swarm.mjs` broadcasts a heartbeat or triggers re-election on its own;
76
+ * `LeaderElection.receiveHeartbeat()` is a plain method with no send side and
77
+ * `elect()` is never called automatically). Every `heartbeatMs` (default
78
+ * 5000, matching `LeaderElection`'s own default `heartbeatMs` so the
79
+ * broadcast cadence and its `electionTimeoutMs`-based staleness math line
80
+ * up) this node:
81
+ *
82
+ * 1. Refreshes its OWN heartbeat timestamp locally (`election
83
+ * .receiveHeartbeat(localPodId, now)`) -- without this, a node that
84
+ * becomes leader would only ever have the construction-time timestamp
85
+ * for itself and could spuriously self-declare stale.
86
+ * 2. Broadcasts `{ from, timestamp, meshType: SWARM_HEARTBEAT }` to every
87
+ * OTHER member of `coordinator.listMembers()` via
88
+ * `ctx.sendTo(memberId, 'swarm-heartbeat', ...)` -- giving
89
+ * `MESH_TYPE.SWARM_HEARTBEAT` (previously an unused re-export) its
90
+ * first real use. Every member broadcasts, not just the leader -- the
91
+ * only heartbeat that actually matters for `checkLeaderAlive()` is the
92
+ * CURRENT leader's, but broadcasting unconditionally means a node that
93
+ * later becomes leader has already been priming every other member's
94
+ * `#heartbeats` map, and it keeps the wire protocol symmetric/simple.
95
+ * 3. Unconditionally calls `election.elect()` -- the lowest-lexicographic-
96
+ * podId deterministic algorithm already in `LeaderElection` -- EVERY
97
+ * tick, not only when `checkLeaderAlive()` reports staleness. This is
98
+ * deliberate, not an oversight: `elect()` is a pure, idempotent
99
+ * recomputation over the CURRENT candidate set (no side effect beyond
100
+ * setting `#leader`), so calling it every tick is cheap and safe, and
101
+ * it is what actually makes independently-bootstrapped nodes converge.
102
+ * A node with no peers yet necessarily elects ITSELF on its very first
103
+ * tick (the only candidate it knows about); gating re-election behind
104
+ * "is the current leader stale" would leave that node stuck governing
105
+ * itself forever once its own heartbeat keeps refreshing (see point 1),
106
+ * even after real peers join and a lexicographically-lower candidate
107
+ * becomes known. Always recomputing self-heals that: the very next
108
+ * tick after membership changes, every node's `elect()` converges on
109
+ * the same answer, because `LeaderElection.elect()` depends only on
110
+ * the candidate SET, which is kept accurate by `coordinator.join()`/
111
+ * `coordinator.leave()` (called directly, and via the wrapped SWIM
112
+ * callbacks above). This composes correctly with SWIM for the "leader
113
+ * goes silent" case too: a genuinely dead leader is removed from the
114
+ * candidate pool by SWIM's own `suspectTimeoutMs` cascade (`onDead` ->
115
+ * wrapped -> `coordinator.leave()` -> `election.removeCandidate()`),
116
+ * so the very next tick's `elect()` picks a different, live leader.
117
+ * `election.checkLeaderAlive()` is still exposed on this file's `api`
118
+ * for a caller that wants to ask "is the leader I know about still
119
+ * heartbeating," but it no longer gates the election decision itself.
120
+ * `elect()` never throws in practice (the local pod is always its own
121
+ * candidate), but a throw is still guarded so it can never kill the
122
+ * interval.
123
+ *
124
+ * `heartbeatTick()` also runs once, synchronously, at `attach()` time (not
125
+ * waiting a full `heartbeatMs` for the very first election), and its
126
+ * `setInterval` handle is cleared in `teardown()`.
127
+ *
128
+ * ---------------------------------------------------------------------------
129
+ * SWARM_JOIN / SWARM_LEAVE -- REAL, DELIBERATE USE (not redundant with
130
+ * SWIM). SWIM's own protocol assumes membership is already decided
131
+ * elsewhere (`addMember()`/`removeMember()` are plain local calls); it has
132
+ * no ADMISSION-CONTROL concept of its own -- nothing stops any podId from
133
+ * being silently added. `SWARM_JOIN` backs a real, authorized handshake
134
+ * layered ON TOP of SWIM for exactly that gap: a remote peer sends a
135
+ * `'join-request'` on `membershipEnvelopeType` (default `'swarm-membership'`,
136
+ * carrying `meshType: SWARM_JOIN` in spirit -- see `accessResource`/`'join'`
137
+ * below), this node gates it via `ctx.registry.checkAccess(fromPubKey,
138
+ * accessResource, 'join')`, and only on success calls `swim.addMember()`
139
+ * (which cascades into `coordinator.join()` via the wrapped callback above)
140
+ * and replies `'join-response'`. `SWARM_LEAVE` backs a real, COURTESY
141
+ * departure announcement, semantically distinct from SWIM's own dead-via-
142
+ * timeout detection (`suspectTimeoutMs` later): a peer that is shutting down
143
+ * cleanly can tell everyone immediately via `announceLeave()` rather than
144
+ * making every other member wait out the full suspect/dead cascade. No
145
+ * separate `checkAccess()` gate is needed for an inbound `'leave'` message:
146
+ * the podId being removed is always the network-authenticated `fromPubKey`
147
+ * itself (never a value the sender supplies in the payload), so a peer can
148
+ * only ever announce its OWN departure -- there is no spoofing surface here
149
+ * the way there is for `'join-request'`/`'submit-task'`.
150
+ *
151
+ * ---------------------------------------------------------------------------
152
+ * SWARM_TASK_ASSIGN -- REAL NOTIFICATION, NOT LEFT AS AN UNUSED CONSTANT.
153
+ * `SwarmCoordinator.submitTask()`/`TaskDistributor.distribute()` are pure,
154
+ * synchronous, in-memory bookkeeping -- deciding WHO a task is assigned to,
155
+ * with no way for the assignee to ever find out short of being told.
156
+ * Leaving that silent would make `submitTask()` nearly useless for a real
157
+ * multi-peer swarm (the assignee has no queue to poll and no event to
158
+ * subscribe to), so this file's `api.submitTask()` wraps
159
+ * `coordinator.submitTask()` and, for every assignee that isn't the local
160
+ * pod, fires `ctx.sendTo(podId, 'swarm-task', { kind: 'assign', meshType:
161
+ * SWARM_TASK_ASSIGN, task: task.toJSON() })` -- fire-and-forget (matching
162
+ * `coordinator.submitTask()`'s own synchronous, non-blocking contract; a
163
+ * slow/unreachable assignee doesn't block the submitter). The receiving
164
+ * side stores the notification in a small local `assignedTasks` map
165
+ * (`api.listAssignedTasks()`/`api.getAssignedTask()`) and emits
166
+ * `swarm:task-received` -- deliberately NOT written into the receiver's own
167
+ * `SwarmCoordinator#tasks` map, since that map is scoped to tasks THIS
168
+ * coordinator itself submitted/owns, and (per the issue's own grounded
169
+ * facts) neither `SwarmCoordinator` nor `SwimMembership` execute a task --
170
+ * there is no "run untrusted code" boundary anywhere in `swarm.mjs`, so this
171
+ * file adds none either; a caller (an execution engine one layer up) is
172
+ * expected to consume `swarm:task-received`/`listAssignedTasks()` and decide
173
+ * what "running" a task even means, exactly the same restraint
174
+ * `mesh-compute.mjs`'s `executeFn` and `mesh-verification.mjs`'s `executeFn`
175
+ * already show for their own execution boundaries.
176
+ *
177
+ * `api.requestSubmitTask(targetPodId, {...})` is the complementary
178
+ * PEER-INITIATED direction: a node without swarm-distribution rights of its
179
+ * own (or that just wants a specific peer's swarm view to do the
180
+ * distributing) asks that peer to submit a task on its behalf, over a real
181
+ * `'submit-request'`/`'submit-response'` round trip on `taskEnvelopeType`
182
+ * (default `'swarm-task'`). Inbound `'submit-request'` is gated via
183
+ * `ctx.registry.checkAccess(fromPubKey, accessResource, 'submit-task')`,
184
+ * mirroring `mesh-compute.mjs`'s `'compute-request'` gate: an explicit
185
+ * `{error}` response on denial (not a silent drop), since the requester's
186
+ * promise is already open and waiting.
187
+ *
188
+ * ---------------------------------------------------------------------------
189
+ * Observability events (`ctx.emit()`, see `mesh-service.mjs`'s convention):
190
+ *
191
+ * - `swarm:member-joined`/`swarm:member-suspect`/`swarm:member-dead`/
192
+ * `swarm:member-left` `{podId}` -- bridged straight from `SwimMembership`'s
193
+ * own `onJoin`/`onSuspect`/`onDead`/`onLeave` (composed, not overwritten
194
+ * -- see above).
195
+ * - `swarm:leader-elected` `{leader, previousLeader}` -- fired only when
196
+ * `election.elect()` actually changes the leader.
197
+ * - `swarm:join-request-granted`/`swarm:join-request-denied` `{from,
198
+ * reason?}` -- an inbound `'join-request'`'s outcome.
199
+ * - `swarm:submit-task-denied` `{from, reason}` -- an inbound
200
+ * `'submit-request'` rejected before ever calling `submitTask()`.
201
+ * - `swarm:task-assigned` `{podId, taskId, task}` -- this node, as
202
+ * submitter, notified a remote assignee.
203
+ * - `swarm:task-received` `{from, task}` -- this node, as assignee,
204
+ * received a task notification from a remote submitter.
205
+ *
206
+ * No browser-only imports at module level.
207
+ */
208
+
209
+ import {
210
+ SwarmCoordinator,
211
+ SwimMembership,
212
+ SWARM_JOIN,
213
+ SWARM_LEAVE,
214
+ SWARM_HEARTBEAT,
215
+ SWARM_TASK_ASSIGN,
216
+ } from '@johnhenry/browsermesh-discovery'
217
+
218
+ const DEFAULT_SWIM_ENVELOPE_TYPE = 'swarm-swim'
219
+ const DEFAULT_HEARTBEAT_ENVELOPE_TYPE = 'swarm-heartbeat'
220
+ const DEFAULT_MEMBERSHIP_ENVELOPE_TYPE = 'swarm-membership'
221
+ const DEFAULT_TASK_ENVELOPE_TYPE = 'swarm-task'
222
+ /** Matches `LeaderElection`'s own default `heartbeatMs` -- see module doc comment. */
223
+ const DEFAULT_HEARTBEAT_MS = 5000
224
+ /** Matches `LeaderElection`'s own default `electionTimeoutMs`. */
225
+ const DEFAULT_ELECTION_TIMEOUT_MS = 15000
226
+ /** Default `resource` passed to `ctx.registry.checkAccess(fromPubKey, resource, action)` for both gated actions (`'join'`/`'submit-task'`). */
227
+ const DEFAULT_ACCESS_RESOURCE = 'swarm'
228
+ /** How long `requestJoin()`/`requestSubmitTask()` wait for a matching response before giving up. */
229
+ const DEFAULT_REQUEST_TIMEOUT_MS = 10000
230
+
231
+ /**
232
+ * Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) wrapping
233
+ * `SwarmCoordinator` + an internally-constructed `SwimMembership`. See this
234
+ * file's module doc comment for the full design (SWIM bridge, single-slot
235
+ * callback composition, heartbeat pump, SWARM_JOIN/LEAVE/TASK_ASSIGN use).
236
+ *
237
+ * @param {object} [opts]
238
+ * @param {number} [opts.heartbeatMs=5000] - Broadcast interval for this
239
+ * node's own leadership heartbeat, and the value passed straight through
240
+ * to `SwarmCoordinator`'s (and therefore `LeaderElection`'s) own
241
+ * `heartbeatMs` constructor option.
242
+ * @param {number} [opts.electionTimeoutMs=15000] - Passed straight through
243
+ * to `SwarmCoordinator`'s (and therefore `LeaderElection`'s) own
244
+ * `electionTimeoutMs` constructor option.
245
+ * @param {object} [opts.swimOptions] - Passed straight through to
246
+ * `new SwimMembership()` (`pingIntervalMs`/`pingTimeoutMs`/
247
+ * `suspectTimeoutMs`/`indirectPingCount`/`nowFn`). `localId`/`sendFn` are
248
+ * always supplied by this file and cannot be overridden here.
249
+ * @param {string} [opts.swimEnvelopeType='swarm-swim']
250
+ * @param {string} [opts.heartbeatEnvelopeType='swarm-heartbeat']
251
+ * @param {string} [opts.membershipEnvelopeType='swarm-membership']
252
+ * @param {string} [opts.taskEnvelopeType='swarm-task']
253
+ * @param {string} [opts.accessResource='swarm'] - `resource` passed to
254
+ * `ctx.registry.checkAccess()` for both inbound `'join-request'`
255
+ * (action `'join'`) and inbound `'submit-request'` (action `'submit-task'`).
256
+ * @param {number} [opts.requestTimeoutMs=10000] - Default timeout for
257
+ * `requestJoin()`/`requestSubmitTask()`.
258
+ * @param {Function} [opts.onLog]
259
+ * @returns {import('./mesh-service.mjs').MeshService}
260
+ */
261
+ export function createSwarmService(opts = {}) {
262
+ const {
263
+ heartbeatMs = DEFAULT_HEARTBEAT_MS,
264
+ electionTimeoutMs = DEFAULT_ELECTION_TIMEOUT_MS,
265
+ swimOptions,
266
+ swimEnvelopeType = DEFAULT_SWIM_ENVELOPE_TYPE,
267
+ heartbeatEnvelopeType = DEFAULT_HEARTBEAT_ENVELOPE_TYPE,
268
+ membershipEnvelopeType = DEFAULT_MEMBERSHIP_ENVELOPE_TYPE,
269
+ taskEnvelopeType = DEFAULT_TASK_ENVELOPE_TYPE,
270
+ accessResource = DEFAULT_ACCESS_RESOURCE,
271
+ requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
272
+ onLog,
273
+ } = opts
274
+ const log = onLog || (() => {})
275
+
276
+ return {
277
+ name: 'swarm',
278
+
279
+ attach(peerNode, ctx) {
280
+ const localPodId = peerNode.podId
281
+
282
+ // -----------------------------------------------------------------
283
+ // SwimMembership -- see module doc comment's "SWIM BRIDGE" section.
284
+ // -----------------------------------------------------------------
285
+ const swim = new SwimMembership({
286
+ ...swimOptions,
287
+ localId: localPodId,
288
+ sendFn: (targetId, msg) => {
289
+ ctx.sendTo(targetId, swimEnvelopeType, { msg }).catch((err) => {
290
+ log('mesh-swarm:swim-send-failed', { targetId, error: err?.message || String(err) })
291
+ })
292
+ },
293
+ })
294
+
295
+ // -----------------------------------------------------------------
296
+ // SwarmCoordinator -- constructing with { swim } wires
297
+ // swim.onJoin/swim.onDead to coordinator.join()/coordinator.leave()
298
+ // (SwarmCoordinator's own constructor does this).
299
+ // -----------------------------------------------------------------
300
+ const coordinator = new SwarmCoordinator(localPodId, { heartbeatMs, electionTimeoutMs, swim })
301
+
302
+ // Compose (not overwrite) the callbacks SwarmCoordinator's own
303
+ // constructor already assigned -- see module doc comment's
304
+ // "SINGLE-SLOT CALLBACK COMPOSITION" section.
305
+ const coordinatorOnJoin = swim.onJoin
306
+ const coordinatorOnDead = swim.onDead // === (podId) => coordinator.leave(podId)
307
+
308
+ // `coordinator.leave(podId)` must run exactly once per genuine
309
+ // departure, from WHICHEVER path first observes it -- but SWIM can
310
+ // reach a 'left' state on THIS node's own view two different ways:
311
+ // (a) local direct-detection (#onSuspectTimeout sets 'dead', fires
312
+ // onDead -- wrapped below); or (b) gossip delivering an
313
+ // ALREADY-'left' update from another peer's piggybacked
314
+ // removeMember() update, which skips 'dead' entirely on THIS node's
315
+ // view and fires ONLY onLeave, never onDead (see SwimMembership's own
316
+ // #fireStateCallbacks: a newState of 'left' calls onLeave, not
317
+ // onDead). Without also driving coordinator.leave() from onLeave, a
318
+ // node that only ever learns of a departure via gossip (b) would
319
+ // leave that podId in its own election candidate pool and
320
+ // distributor member list FOREVER, since SwarmCoordinator's own
321
+ // constructor only wires onDead, not onLeave, for removal.
322
+ //
323
+ // Calling coordinator.leave() from onLeave, however, reintroduces the
324
+ // exact recursion hazard "SINGLE-SLOT CALLBACK COMPOSITION" warns
325
+ // about one level deeper: coordinator.leave() itself calls
326
+ // swim.removeMember(), which UNCONDITIONALLY re-fires onLeave (no
327
+ // "already left" guard of its own) -- so onLeave -> coordinator.leave()
328
+ // -> removeMember() -> onLeave again would recurse forever without a
329
+ // guard here. `leaveHandled` is that guard: the first call for a
330
+ // given podId (from either onDead or onLeave) performs the real
331
+ // coordinator.leave() and marks it done; every re-entrant call
332
+ // (including handleLeave()'s own explicit courtesy-leave path,
333
+ // below) becomes a no-op past that point. Cleared on rejoin so a
334
+ // podId that leaves and later rejoins can be processed again.
335
+ const leaveHandled = new Set()
336
+ function ensureCoordinatorLeave(podId) {
337
+ if (leaveHandled.has(podId)) return
338
+ leaveHandled.add(podId)
339
+ coordinatorOnDead(podId)
340
+ }
341
+
342
+ swim.onJoin = (podId) => {
343
+ leaveHandled.delete(podId)
344
+ coordinatorOnJoin(podId)
345
+ ctx.emit('swarm:member-joined', { podId })
346
+ }
347
+ swim.onDead = (podId) => {
348
+ ensureCoordinatorLeave(podId)
349
+ ctx.emit('swarm:member-dead', { podId })
350
+ }
351
+ // SwarmCoordinator does not touch onSuspect -- safe to assign directly.
352
+ swim.onSuspect = (podId) => ctx.emit('swarm:member-suspect', { podId })
353
+ swim.onLeave = (podId) => {
354
+ ensureCoordinatorLeave(podId)
355
+ ctx.emit('swarm:member-left', { podId })
356
+ }
357
+
358
+ const unsubscribeSwim = ctx.onIncomingData(swimEnvelopeType, (fromPubKey, envelope) => {
359
+ swim.handleMessage(fromPubKey, envelope?.msg)
360
+ })
361
+
362
+ swim.start()
363
+
364
+ // -----------------------------------------------------------------
365
+ // Leader election heartbeat pump -- see module doc comment's
366
+ // "LEADER ELECTION HEARTBEAT PUMP" section.
367
+ // -----------------------------------------------------------------
368
+ function heartbeatTick() {
369
+ const now = Date.now()
370
+ coordinator.election.receiveHeartbeat(localPodId, now)
371
+ for (const podId of coordinator.listMembers()) {
372
+ if (podId === localPodId) continue
373
+ ctx.sendTo(podId, heartbeatEnvelopeType, {
374
+ from: localPodId,
375
+ timestamp: now,
376
+ meshType: SWARM_HEARTBEAT,
377
+ }).catch((err) => {
378
+ log('mesh-swarm:heartbeat-send-failed', { podId, error: err?.message || String(err) })
379
+ })
380
+ }
381
+ // Always recompute (not gated behind checkLeaderAlive()) -- see
382
+ // module doc comment's "LEADER ELECTION HEARTBEAT PUMP" section for
383
+ // why this is required for convergence, not just silence-detection.
384
+ const previousLeader = coordinator.election.leader
385
+ let newLeader = null
386
+ try {
387
+ newLeader = coordinator.election.elect()
388
+ } catch (err) {
389
+ log('mesh-swarm:election-failed', { error: err?.message || String(err) })
390
+ }
391
+ if (newLeader && newLeader !== previousLeader) {
392
+ ctx.emit('swarm:leader-elected', { leader: newLeader, previousLeader })
393
+ }
394
+ }
395
+ heartbeatTick()
396
+ let heartbeatTimer = setInterval(heartbeatTick, heartbeatMs)
397
+
398
+ const unsubscribeHeartbeat = ctx.onIncomingData(heartbeatEnvelopeType, (fromPubKey, msg) => {
399
+ coordinator.election.receiveHeartbeat(fromPubKey, msg?.timestamp)
400
+ })
401
+
402
+ // -----------------------------------------------------------------
403
+ // Membership admission control (SWARM_JOIN/SWARM_LEAVE) -- see
404
+ // module doc comment's "SWARM_JOIN / SWARM_LEAVE" section.
405
+ // -----------------------------------------------------------------
406
+ let joinReqSeq = 0
407
+ const nextJoinRequestId = () => `${localPodId}:${Date.now()}:${++joinReqSeq}`
408
+ /** @type {Map<string, {resolve: Function, reject: Function, timer: ReturnType<typeof setTimeout>}>} */
409
+ const pendingJoinRequests = new Map()
410
+
411
+ async function handleJoinRequest(fromPubKey, msg) {
412
+ const access = ctx.registry.checkAccess(fromPubKey, accessResource, 'join')
413
+ if (!access.allowed) {
414
+ // Fixed generic reason on both the emitted event and the wire
415
+ // response -- mirrors mesh-compute.mjs's own
416
+ // 'compute:chunk-request-denied' convention, deliberately not
417
+ // leaking the underlying ACL's internal reason (e.g.
418
+ // 'not_in_roster'/'entry_expired') to an unauthorized peer.
419
+ ctx.emit('swarm:join-request-denied', { from: fromPubKey, reason: 'access_denied' })
420
+ await ctx.sendTo(fromPubKey, membershipEnvelopeType, {
421
+ kind: 'join-response', requestId: msg.requestId, ok: false, reason: 'access_denied',
422
+ }).catch((err) => log('mesh-swarm:join-response-send-failed', { to: fromPubKey, error: err?.message || String(err) }))
423
+ return
424
+ }
425
+ swim.addMember(fromPubKey) // cascades: swim.onJoin -> coordinator.join() + ctx.emit('swarm:member-joined')
426
+ ctx.emit('swarm:join-request-granted', { from: fromPubKey })
427
+ await ctx.sendTo(fromPubKey, membershipEnvelopeType, {
428
+ kind: 'join-response', requestId: msg.requestId, ok: true, meshType: SWARM_JOIN,
429
+ }).catch((err) => log('mesh-swarm:join-response-send-failed', { to: fromPubKey, error: err?.message || String(err) }))
430
+ }
431
+
432
+ function handleJoinResponse(msg) {
433
+ const pending = pendingJoinRequests.get(msg.requestId)
434
+ if (!pending) return
435
+ pendingJoinRequests.delete(msg.requestId)
436
+ clearTimeout(pending.timer)
437
+ pending.resolve({ ok: !!msg.ok, reason: msg.reason })
438
+ }
439
+
440
+ function handleLeave(fromPubKey) {
441
+ // fromPubKey is the network-authenticated sender -- no spoofing
442
+ // surface, so no checkAccess() gate is needed (see module doc
443
+ // comment). Routed through the same ensureCoordinatorLeave() guard
444
+ // as swim.onDead/onLeave (not a direct coordinator.leave() call) so
445
+ // a peer that's ALSO independently detected via SWIM doesn't get a
446
+ // duplicate coordinator.leave() call or a duplicate
447
+ // swarm:member-left event.
448
+ ensureCoordinatorLeave(fromPubKey)
449
+ }
450
+
451
+ const unsubscribeMembership = ctx.onIncomingData(membershipEnvelopeType, (fromPubKey, msg) => {
452
+ if (!msg || typeof msg.kind !== 'string') return
453
+ if (msg.kind === 'join-request') {
454
+ handleJoinRequest(fromPubKey, msg).catch((err) => {
455
+ log('mesh-swarm:join-request-handling-failed', { from: fromPubKey, error: err?.message || String(err) })
456
+ })
457
+ } else if (msg.kind === 'join-response') {
458
+ handleJoinResponse(msg)
459
+ } else if (msg.kind === 'leave') {
460
+ handleLeave(fromPubKey)
461
+ }
462
+ })
463
+
464
+ async function requestJoin(targetPodId, timeoutMs = requestTimeoutMs) {
465
+ const requestId = nextJoinRequestId()
466
+ const promise = new Promise((resolve, reject) => {
467
+ const timer = setTimeout(() => {
468
+ pendingJoinRequests.delete(requestId)
469
+ reject(new Error(`mesh-swarm: join request to ${targetPodId} timed out after ${timeoutMs}ms`))
470
+ }, timeoutMs)
471
+ pendingJoinRequests.set(requestId, { resolve, reject, timer })
472
+ })
473
+ try {
474
+ await ctx.sendTo(targetPodId, membershipEnvelopeType, { kind: 'join-request', requestId, meshType: SWARM_JOIN })
475
+ } catch (err) {
476
+ const pending = pendingJoinRequests.get(requestId)
477
+ if (pending) {
478
+ clearTimeout(pending.timer)
479
+ pendingJoinRequests.delete(requestId)
480
+ }
481
+ throw err
482
+ }
483
+ return promise
484
+ }
485
+
486
+ function announceLeave() {
487
+ for (const podId of coordinator.listMembers()) {
488
+ if (podId === localPodId) continue
489
+ ctx.sendTo(podId, membershipEnvelopeType, { kind: 'leave', meshType: SWARM_LEAVE }).catch((err) => {
490
+ log('mesh-swarm:leave-announce-send-failed', { podId, error: err?.message || String(err) })
491
+ })
492
+ }
493
+ }
494
+
495
+ // -----------------------------------------------------------------
496
+ // Task submission / assignment notification (SWARM_TASK_ASSIGN) --
497
+ // see module doc comment's "SWARM_TASK_ASSIGN" section.
498
+ // -----------------------------------------------------------------
499
+ /** @type {Map<string, object>} taskId -> task JSON, for tasks assigned to THIS node by a remote submitter. */
500
+ const assignedTasks = new Map()
501
+
502
+ function notifyAssignees(task) {
503
+ for (const podId of task.assignedTo) {
504
+ if (podId === localPodId) continue
505
+ ctx.sendTo(podId, taskEnvelopeType, {
506
+ kind: 'assign', meshType: SWARM_TASK_ASSIGN, task: task.toJSON(),
507
+ }).catch((err) => {
508
+ log('mesh-swarm:task-assign-send-failed', { podId, taskId: task.taskId, error: err?.message || String(err) })
509
+ })
510
+ ctx.emit('swarm:task-assigned', { podId, taskId: task.taskId, task: task.toJSON() })
511
+ }
512
+ }
513
+
514
+ function submitTaskLocal(description, strategy, input, swarmId) {
515
+ const task = coordinator.submitTask(description, strategy, input, swarmId)
516
+ notifyAssignees(task)
517
+ return task
518
+ }
519
+
520
+ let taskReqSeq = 0
521
+ const nextTaskRequestId = () => `${localPodId}:${Date.now()}:${++taskReqSeq}`
522
+ /** @type {Map<string, {resolve: Function, reject: Function, timer: ReturnType<typeof setTimeout>}>} */
523
+ const pendingSubmitRequests = new Map()
524
+
525
+ async function handleSubmitRequest(fromPubKey, msg) {
526
+ const access = ctx.registry.checkAccess(fromPubKey, accessResource, 'submit-task')
527
+ if (!access.allowed) {
528
+ // Fixed generic reason/error -- see handleJoinRequest()'s own
529
+ // comment for why the underlying ACL reason is not put on the wire.
530
+ ctx.emit('swarm:submit-task-denied', { from: fromPubKey, reason: 'access_denied' })
531
+ await ctx.sendTo(fromPubKey, taskEnvelopeType, {
532
+ kind: 'submit-response', requestId: msg.requestId, error: 'access denied',
533
+ }).catch((err) => log('mesh-swarm:submit-response-send-failed', { to: fromPubKey, error: err?.message || String(err) }))
534
+ return
535
+ }
536
+ let response
537
+ try {
538
+ const task = submitTaskLocal(msg.description, msg.strategy, msg.input, msg.swarmId)
539
+ response = { kind: 'submit-response', requestId: msg.requestId, task: task.toJSON() }
540
+ } catch (err) {
541
+ response = { kind: 'submit-response', requestId: msg.requestId, error: err?.message || String(err) }
542
+ }
543
+ await ctx.sendTo(fromPubKey, taskEnvelopeType, response).catch((err) => {
544
+ log('mesh-swarm:submit-response-send-failed', { to: fromPubKey, error: err?.message || String(err) })
545
+ })
546
+ }
547
+
548
+ function handleSubmitResponse(msg) {
549
+ const pending = pendingSubmitRequests.get(msg.requestId)
550
+ if (!pending) return
551
+ pendingSubmitRequests.delete(msg.requestId)
552
+ clearTimeout(pending.timer)
553
+ if (msg.error) {
554
+ pending.reject(new Error(msg.error))
555
+ } else {
556
+ pending.resolve(msg.task)
557
+ }
558
+ }
559
+
560
+ function handleTaskAssign(fromPubKey, msg) {
561
+ assignedTasks.set(msg.task.taskId, { ...msg.task, assignedBy: fromPubKey })
562
+ ctx.emit('swarm:task-received', { from: fromPubKey, task: msg.task })
563
+ }
564
+
565
+ const unsubscribeTask = ctx.onIncomingData(taskEnvelopeType, (fromPubKey, msg) => {
566
+ if (!msg || typeof msg.kind !== 'string') return
567
+ if (msg.kind === 'assign') {
568
+ handleTaskAssign(fromPubKey, msg)
569
+ } else if (msg.kind === 'submit-request') {
570
+ handleSubmitRequest(fromPubKey, msg).catch((err) => {
571
+ log('mesh-swarm:submit-request-handling-failed', { from: fromPubKey, error: err?.message || String(err) })
572
+ })
573
+ } else if (msg.kind === 'submit-response') {
574
+ handleSubmitResponse(msg)
575
+ }
576
+ })
577
+
578
+ async function requestSubmitTask(targetPodId, { description, strategy, input, swarmId, timeoutMs = requestTimeoutMs } = {}) {
579
+ const requestId = nextTaskRequestId()
580
+ const promise = new Promise((resolve, reject) => {
581
+ const timer = setTimeout(() => {
582
+ pendingSubmitRequests.delete(requestId)
583
+ reject(new Error(`mesh-swarm: submit-task request to ${targetPodId} timed out after ${timeoutMs}ms`))
584
+ }, timeoutMs)
585
+ pendingSubmitRequests.set(requestId, { resolve, reject, timer })
586
+ })
587
+ try {
588
+ await ctx.sendTo(targetPodId, taskEnvelopeType, { kind: 'submit-request', requestId, description, strategy, input, swarmId })
589
+ } catch (err) {
590
+ const pending = pendingSubmitRequests.get(requestId)
591
+ if (pending) {
592
+ clearTimeout(pending.timer)
593
+ pendingSubmitRequests.delete(requestId)
594
+ }
595
+ throw err
596
+ }
597
+ return promise
598
+ }
599
+
600
+ // -----------------------------------------------------------------
601
+ // api
602
+ // -----------------------------------------------------------------
603
+ const api = {
604
+ // Local SwarmCoordinator surface (never wire-gated -- this node's
605
+ // own operator/application code).
606
+ createSwarm: (swarmId) => coordinator.createSwarm(swarmId),
607
+ disbandSwarm: (swarmId) => coordinator.disbandSwarm(swarmId),
608
+ hasSwarm: (swarmId) => coordinator.hasSwarm(swarmId),
609
+ listSwarms: () => coordinator.listSwarms(),
610
+ listMembers: (swarmId) => coordinator.listMembers(swarmId),
611
+ join: (podId, capabilities, swarmId) => coordinator.join(podId, capabilities, swarmId),
612
+ leave: (podId, swarmId) => coordinator.leave(podId, swarmId),
613
+ submitTask: (description, strategy, input, swarmId) => submitTaskLocal(description, strategy, input, swarmId),
614
+ getTask: (taskId) => coordinator.getTask(taskId),
615
+ completeTask: (taskId, output) => coordinator.completeTask(taskId, output),
616
+ failTask: (taskId, error) => coordinator.failTask(taskId, error),
617
+ cancelTask: (taskId) => coordinator.cancelTask(taskId),
618
+ listTasks: (listOpts) => coordinator.listTasks(listOpts),
619
+ isLeader: () => coordinator.isLeader,
620
+ getLeader: () => coordinator.election.leader,
621
+ checkLeaderAlive: (now) => coordinator.election.checkLeaderAlive(now),
622
+ getMemberState: (podId) => swim.getState(podId),
623
+ getCoordinator: () => coordinator,
624
+ getSwim: () => swim,
625
+
626
+ // Wire-level peer interactions (this node as requester).
627
+ requestJoin,
628
+ announceLeave,
629
+ requestSubmitTask,
630
+
631
+ // Tasks assigned to THIS node by a remote submitter.
632
+ listAssignedTasks: () => [...assignedTasks.values()],
633
+ getAssignedTask: (taskId) => assignedTasks.get(taskId) ?? null,
634
+ }
635
+
636
+ return {
637
+ api,
638
+ teardown() {
639
+ swim.stop()
640
+ if (heartbeatTimer) {
641
+ clearInterval(heartbeatTimer)
642
+ heartbeatTimer = null
643
+ }
644
+ swim.onJoin = null
645
+ swim.onSuspect = null
646
+ swim.onDead = null
647
+ swim.onLeave = null
648
+ unsubscribeSwim()
649
+ unsubscribeHeartbeat()
650
+ unsubscribeMembership()
651
+ unsubscribeTask()
652
+ for (const pending of pendingJoinRequests.values()) {
653
+ clearTimeout(pending.timer)
654
+ pending.reject(new Error('mesh-swarm: service torn down while a join request was still in flight'))
655
+ }
656
+ pendingJoinRequests.clear()
657
+ for (const pending of pendingSubmitRequests.values()) {
658
+ clearTimeout(pending.timer)
659
+ pending.reject(new Error('mesh-swarm: service torn down while a submit-task request was still in flight'))
660
+ }
661
+ pendingSubmitRequests.clear()
662
+ },
663
+ }
664
+ },
665
+ }
666
+ }
667
+
668
+ export {
669
+ DEFAULT_SWIM_ENVELOPE_TYPE,
670
+ DEFAULT_HEARTBEAT_ENVELOPE_TYPE,
671
+ DEFAULT_MEMBERSHIP_ENVELOPE_TYPE,
672
+ DEFAULT_TASK_ENVELOPE_TYPE,
673
+ DEFAULT_HEARTBEAT_MS,
674
+ DEFAULT_ELECTION_TIMEOUT_MS,
675
+ DEFAULT_ACCESS_RESOURCE,
676
+ DEFAULT_REQUEST_TIMEOUT_MS,
677
+ }