@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,403 @@
1
+ /**
2
+ * mesh-service.mjs -- the generic `MeshService` attach convention (Phase C
3
+ * of the CloudStorage plan; see the plan's "Design decisions" section,
4
+ * "`MeshService` is a minimal attach contract, not a `Backend` factory").
5
+ *
6
+ * This generalizes the pattern `mesh-sync.mjs` (`MeshSyncBinding`) and
7
+ * `mesh-relay-host.mjs` (`MeshRelayHost`) already both hand-roll: subscribe
8
+ * to `PeerNode.onIncomingData()`, filter on `envelope.type`, reply via
9
+ * `node.sendTo()`. Rather than making every future mesh-native service
10
+ * reimplement that filtering (and rather than forcing every such service to
11
+ * produce a `browsermesh-netway` `Backend`, which doesn't generalize to
12
+ * publish/subscribe-shaped services -- see the design review), this file
13
+ * defines:
14
+ *
15
+ * - `MeshService` -- a plain-object descriptor convention (NOT a class to
16
+ * instantiate): `{ name, attach(peerNode, ctx) -> teardown, createBackend?,
17
+ * backendScheme? }`.
18
+ * - `attachService(peerNode, network, descriptor)` -- the composition-root
19
+ * function that builds a `ctx` for a descriptor, calls `descriptor.attach()`,
20
+ * and (only if `descriptor.createBackend` is present) registers the
21
+ * returned `Backend` onto `network` under `descriptor.backendScheme`
22
+ * (default `'svc'`).
23
+ *
24
+ * `ctx` gives a service everything it needs without requiring it to know
25
+ * `PeerNode` internals:
26
+ * - `ctx.onIncomingData(types, callback)` -- wraps `peerNode.onIncomingData()`,
27
+ * invoking `callback(pubKey, envelope)` only for envelopes whose `.type`
28
+ * matches `types` (a single string or an array of strings). Returns an
29
+ * unsubscribe function, exactly like the underlying `onIncomingData()`.
30
+ * - `ctx.sendTo(pubKey, type, payload)` -- wraps `peerNode.sendTo()`,
31
+ * merging `{ type, ...payload }` into the envelope sent, matching the
32
+ * `{ type: envelopeType, ...payload }` shape both `mesh-sync.mjs` and
33
+ * `mesh-relay-host.mjs` already send.
34
+ * - `ctx.registry` -- the node's `PeerRegistry`, for `checkAccess()`.
35
+ * - `ctx.peerNode` -- the raw `PeerNode`, for anything not covered above.
36
+ * - `ctx.network` -- the `VirtualNetwork` passed to `attachService()`, if
37
+ * any (services that don't use `createBackend` may still want direct
38
+ * `network.connect()` access, e.g. to reach another exposed service).
39
+ *
40
+ * `createBackend(ctx) -> Backend` is OPTIONAL on a descriptor. When present,
41
+ * `attachService()` requires `network` to have been supplied (throws
42
+ * otherwise -- a service that declares `createBackend` but is attached with
43
+ * no `network` is a caller error, not a silent no-op) and calls
44
+ * `network.addBackend(backendScheme, backend)`.
45
+ *
46
+ * Known limitation: `VirtualNetwork` (`browsermesh-netway`) has no
47
+ * `removeBackend()` -- backend registration is permanent for the network's
48
+ * lifetime, matching how `network.close()` (not per-backend removal) is
49
+ * that class's only network-level teardown primitive today. `teardown()`
50
+ * therefore only reverses what `descriptor.attach()` itself did (unsubscribe
51
+ * from `onIncomingData()`, release any internal state); a registered
52
+ * `Backend` stays routable on `network` until `network.close()`.
53
+ *
54
+ * ---------------------------------------------------------------------------
55
+ * Observability events (`ctx.emit()`) -- Phase 1 of the mesh-KV-and-
56
+ * observability plan (`mesh-kv-and-observability.md`, "Design decisions").
57
+ *
58
+ * `ctx.emit(event, data)` is a NEW hook, separate from and additional to
59
+ * `onLog` (which every service already accepts as its own constructor
60
+ * option and which stays exactly what it is: free-form, mostly error/
61
+ * reject-path debug logging with no fixed vocabulary). `emit` is for a
62
+ * small, curated set of MEANINGFUL STATE TRANSITIONS a service deliberately
63
+ * chooses to publish for something else to consume (a dashboard,
64
+ * `visualizations.mjs` in a later phase, a test assertion) -- not every
65
+ * debug line. Event names follow the same `<service>:<kebab-description>`
66
+ * grammar `onLog` already established (e.g. `grant-log:grant-applied`,
67
+ * `chunk-replication:chunk-replicated`); each service documents its own
68
+ * chosen vocabulary in its own module doc comment, exactly like `onLog`'s
69
+ * existing per-service convention.
70
+ *
71
+ * The event bus lives on `attachService()`'s handle, NOT on
72
+ * `createMeshNode()`'s aggregate: each attached service gets its own
73
+ * independent bus (mirroring how each service already gets its own `ctx`),
74
+ * and a caller that wants a node-wide view subscribes to each service's
75
+ * handle individually (or a later composition layer, e.g. Phase 2's
76
+ * observability bridge, does that fan-in) rather than this file inventing a
77
+ * global event namespace up front.
78
+ *
79
+ * Subscription API, on the object `attachService()` returns:
80
+ * - `handle.on(event, callback)` -- `callback(data)` fires only for that
81
+ * exact `event` string. Returns an unsubscribe function.
82
+ * - `handle.onEvent(callback)` -- `callback(event, data)` fires for EVERY
83
+ * event this service emits, regardless of name (a "firehose"
84
+ * subscription, useful for a generic bridge/dashboard that doesn't want
85
+ * to enumerate every event name a service might ever add). Also returns
86
+ * an unsubscribe function.
87
+ *
88
+ * `ctx.emit()` fires SYNCHRONOUSLY: calling it invokes every
89
+ * currently-registered `on()`/`onEvent()` callback immediately, in
90
+ * registration order, before `emit()` returns -- there is no queueing or
91
+ * microtask hop, matching `ctx.onIncomingData()`'s own synchronous dispatch
92
+ * (a service reacting to an emitted event sees it happen exactly when the
93
+ * emitting code ran, not "eventually").
94
+ *
95
+ * A THROWING SUBSCRIBER never crashes the emitting service, the shared
96
+ * `onIncomingData()` dispatch loop, or any OTHER subscriber: each
97
+ * callback invocation is individually wrapped in try/catch and swallowed.
98
+ * This mirrors two already-established precedents in this exact family
99
+ * rather than inventing a third convention: `mesh-rpc.mjs`'s `onRequest`
100
+ * handler is caught and turned into a clean response so a throwing handler
101
+ * can never become an unhandled rejection or break request/response
102
+ * correlation for other in-flight callers, and `mesh-websocket.mjs`'s
103
+ * `#dispatch()` (its `onopen`/`onmessage`/`onerror`/`onclose`/
104
+ * `addEventListener()` fan-out) wraps every individual handler call in its
105
+ * own try/catch specifically so "a throwing listener does not stop other
106
+ * listeners" (that file's own comment, quoted because it's the same
107
+ * property this bus needs). There is no `onLog` hook available inside the
108
+ * bus itself to report a swallowed subscriber error -- `ctx.emit()` has no
109
+ * log sink of its own, by design (see the module's overall `onLog`/`emit`
110
+ * split above) -- a subscriber that needs to observe its own failures must
111
+ * catch internally.
112
+ *
113
+ * `handle.teardown()` also stops all further event delivery: it clears
114
+ * every registered `on()`/`onEvent()` subscriber and makes subsequent
115
+ * `ctx.emit()` calls (if a torn-down service's own code somehow still calls
116
+ * one) a silent no-op rather than reaching stale subscriber references.
117
+ *
118
+ * `createEventBus()` (below, exported) is the small, dependency-free helper
119
+ * backing all of the above. It is exported so a composed, non-`MeshService`
120
+ * class that has no `ctx` of its own -- e.g. `cloud-storage.mjs`'s
121
+ * `CloudStorage`, which calls `attachService()` internally four times but
122
+ * is not itself attached by anything -- can build a bus with the exact same
123
+ * `{emit, on, onEvent, closeAll}` shape for its OWN higher-level events,
124
+ * rather than that file reinventing a differently-shaped emitter.
125
+ *
126
+ * No browser-only imports at module level.
127
+ */
128
+
129
+ /** Default scheme a descriptor's `createBackend` backend is registered under, if `backendScheme` is omitted. */
130
+ const DEFAULT_BACKEND_SCHEME = 'svc'
131
+
132
+ // ---------------------------------------------------------------------------
133
+ // Event bus -- backs ctx.emit() / attachService()'s handle.on()/.onEvent().
134
+ // See module doc comment's "Observability events" section for the full
135
+ // design (synchronous dispatch, throwing-subscriber isolation, teardown
136
+ // semantics). Exported standalone (not only used internally) so a composed,
137
+ // non-MeshService class with no ctx of its own can build one with the same
138
+ // shape -- see cloud-storage.mjs's own use of this for its higher-level
139
+ // put/get/grant events.
140
+ // ---------------------------------------------------------------------------
141
+
142
+ /**
143
+ * @typedef {object} EventBus
144
+ * @property {(event: string, data?: object) => void} emit - Synchronous
145
+ * fan-out to every current `on(event, ...)` and `onEvent(...)` subscriber.
146
+ * No-op once `closeAll()` has been called.
147
+ * @property {(event: string, callback: (data: object) => void) => (() => void)} on
148
+ * Subscribe to exactly one event name. Returns an unsubscribe function.
149
+ * @property {(callback: (event: string, data: object) => void) => (() => void)} onEvent
150
+ * Subscribe to every event this bus ever emits, regardless of name.
151
+ * Returns an unsubscribe function.
152
+ * @property {() => void} closeAll - Clears every subscriber and makes all
153
+ * future `emit()` calls silent no-ops. Idempotent.
154
+ */
155
+
156
+ /**
157
+ * @returns {EventBus}
158
+ */
159
+ function createEventBus() {
160
+ /** @type {Map<string, Set<Function>>} */
161
+ const byEvent = new Map()
162
+ /** @type {Set<Function>} */
163
+ const wildcard = new Set()
164
+ let closed = false
165
+
166
+ /**
167
+ * Invoke one subscriber, swallowing anything it throws -- see module doc
168
+ * comment: a throwing subscriber must never crash the emitting service,
169
+ * the shared dispatch loop, or any other subscriber. There is no log sink
170
+ * available at this layer (see doc comment for why); a subscriber that
171
+ * needs to observe its own failures must catch internally.
172
+ * @param {Function} callback
173
+ * @param {*[]} args
174
+ */
175
+ function safeInvoke(callback, args) {
176
+ try {
177
+ callback(...args)
178
+ } catch {
179
+ // Deliberately swallowed -- see this function's own doc comment.
180
+ }
181
+ }
182
+
183
+ return {
184
+ emit(event, data) {
185
+ if (closed) return
186
+ const specific = byEvent.get(event)
187
+ if (specific) {
188
+ for (const callback of [...specific]) safeInvoke(callback, [data, event])
189
+ }
190
+ for (const callback of [...wildcard]) safeInvoke(callback, [event, data])
191
+ },
192
+ on(event, callback) {
193
+ if (typeof callback !== 'function') return () => {}
194
+ let set = byEvent.get(event)
195
+ if (!set) {
196
+ set = new Set()
197
+ byEvent.set(event, set)
198
+ }
199
+ set.add(callback)
200
+ return () => { set.delete(callback) }
201
+ },
202
+ onEvent(callback) {
203
+ if (typeof callback !== 'function') return () => {}
204
+ wildcard.add(callback)
205
+ return () => { wildcard.delete(callback) }
206
+ },
207
+ closeAll() {
208
+ closed = true
209
+ byEvent.clear()
210
+ wildcard.clear()
211
+ },
212
+ }
213
+ }
214
+
215
+ // ---------------------------------------------------------------------------
216
+ // Typedefs (documentation only -- `MeshService` is a plain-object
217
+ // convention, not a class to instantiate)
218
+ // ---------------------------------------------------------------------------
219
+
220
+ /**
221
+ * @typedef {object} MeshServiceContext
222
+ * @property {import('./peer-node.mjs').PeerNode} peerNode - The raw `PeerNode`.
223
+ * @property {import('./peer-registry.mjs').PeerRegistry} registry - `peerNode.registry`, for `checkAccess()`.
224
+ * @property {import('@johnhenry/browsermesh-netway').VirtualNetwork} [network] - The
225
+ * `VirtualNetwork` passed to `attachService()`, if any.
226
+ * @property {(types: string|string[], callback: (pubKey: string, envelope: object) => void) => (() => void)} onIncomingData
227
+ * Envelope-type-filtered subscription. `callback` only fires for envelopes
228
+ * whose `.type` is in `types`. Returns an unsubscribe function.
229
+ * @property {(pubKey: string, type: string, payload?: object) => Promise<void>} sendTo
230
+ * Sends `{ type, ...payload }` to `pubKey` via `peerNode.sendTo()`.
231
+ * @property {(event: string, data?: object) => void} emit
232
+ * Publishes a curated, meaningful state-transition event for anything
233
+ * subscribed via `attachService()`'s returned handle (`handle.on()`/
234
+ * `handle.onEvent()`). Fires synchronously; a throwing subscriber is
235
+ * caught and never propagates back into the emitting service. See the
236
+ * module doc comment's "Observability events" section for the full
237
+ * design (separate from, and additional to, `onLog`).
238
+ */
239
+
240
+ /**
241
+ * @typedef {object} MeshService
242
+ * @property {string} name - Unique service name (used as the lookup key in
243
+ * `createMeshNode({ services })`'s resulting `node.services` map).
244
+ * @property {(peerNode: import('./peer-node.mjs').PeerNode, ctx: MeshServiceContext) => (MeshServiceAttachResult)} attach
245
+ * Wire the service to `peerNode`/`ctx`. May return either a bare
246
+ * `teardown()` function (the original shape, still supported) or
247
+ * `{ teardown?, api? }`, where `api` is whatever handle/instance the
248
+ * service wants exposed to its own caller later (e.g. a class instance
249
+ * with methods beyond attach/teardown) -- surfaced on `attachService()`'s
250
+ * returned handle as `.api`. Added after Phase D (`grant-log.mjs`) needed
251
+ * to hand back a live `GrantLog` instance and had no field for it; that
252
+ * phase's own `onReady(api)` callback workaround still works unmodified
253
+ * (this is additive, not breaking), but new services should prefer
254
+ * returning `{ teardown, api }` directly. NOTE: `attach()`'s return value
255
+ * is read synchronously by `attachService()` -- it is NOT awaited. A
256
+ * service needing async setup (e.g. signing that requires
257
+ * `crypto.subtle`) should expose that as a separately-awaitable method on
258
+ * `api`, not assume `attach()` itself is ever awaited by callers.
259
+ * @property {(ctx: MeshServiceContext) => import('@johnhenry/browsermesh-netway').Backend} [createBackend]
260
+ * OPTIONAL. If present, `attachService()` registers the returned `Backend`
261
+ * onto the supplied `network` under `backendScheme`.
262
+ * @property {string} [backendScheme='svc'] - URI scheme the `createBackend`
263
+ * backend is registered under. Only consulted when `createBackend` is present.
264
+ */
265
+
266
+ /**
267
+ * @typedef {(() => (void|Promise<void>))|{teardown?: (() => (void|Promise<void>)), api?: object}} MeshServiceAttachResult
268
+ */
269
+
270
+ // ---------------------------------------------------------------------------
271
+ // ctx construction
272
+ // ---------------------------------------------------------------------------
273
+
274
+ /**
275
+ * @param {object} opts
276
+ * @param {import('./peer-node.mjs').PeerNode} opts.peerNode
277
+ * @param {import('@johnhenry/browsermesh-netway').VirtualNetwork} [opts.network]
278
+ * @param {EventBus} opts.eventBus
279
+ * @returns {MeshServiceContext}
280
+ */
281
+ function createServiceContext({ peerNode, network, eventBus }) {
282
+ return {
283
+ peerNode,
284
+ registry: peerNode.registry,
285
+ network,
286
+
287
+ onIncomingData(types, callback) {
288
+ const typeSet = new Set(Array.isArray(types) ? types : [types])
289
+ return peerNode.onIncomingData((pubKey, data) => {
290
+ if (!data || typeof data !== 'object' || !typeSet.has(data.type)) return
291
+ // `peerNode.onIncomingData()`'s own dispatch loop only catches a
292
+ // SYNCHRONOUS throw from this callback. Every real handler in this
293
+ // family is `async`, so a rejection never throws synchronously --
294
+ // it resolves to a rejected Promise instead, which the outer catch
295
+ // structurally cannot see. Without catching it here too, a failing
296
+ // async handler becomes an unhandled promise rejection instead of
297
+ // the isolated, logged failure every other error path in this file
298
+ // already guarantees (see the module doc comment's "A THROWING
299
+ // SUBSCRIBER never crashes..." paragraph -- this closes the one
300
+ // gap that guarantee didn't actually cover).
301
+ try {
302
+ const result = callback(pubKey, data)
303
+ if (result && typeof result.catch === 'function') result.catch(() => {})
304
+ } catch {
305
+ // Synchronous throw: peerNode.onIncomingData()'s own dispatch
306
+ // loop already catches and logs this case -- nothing more to do.
307
+ }
308
+ })
309
+ },
310
+
311
+ async sendTo(pubKey, type, payload = {}) {
312
+ await peerNode.sendTo(pubKey, { type, ...payload })
313
+ },
314
+
315
+ emit(event, data) {
316
+ if (typeof event !== 'string' || !event) return
317
+ eventBus.emit(event, data)
318
+ },
319
+ }
320
+ }
321
+
322
+ // ---------------------------------------------------------------------------
323
+ // attachService
324
+ // ---------------------------------------------------------------------------
325
+
326
+ /**
327
+ * Attach one `MeshService` descriptor to `peerNode`.
328
+ *
329
+ * @param {import('./peer-node.mjs').PeerNode} peerNode
330
+ * @param {import('@johnhenry/browsermesh-netway').VirtualNetwork} [network]
331
+ * Required only if `descriptor.createBackend` is present.
332
+ * @param {MeshService} descriptor
333
+ * @returns {{ name: string, backendScheme: string|null, api: object|undefined,
334
+ * on: (event: string, callback: (data: object) => void) => (() => void),
335
+ * onEvent: (callback: (event: string, data: object) => void) => (() => void),
336
+ * teardown: () => Promise<void> }}
337
+ * `api` is `descriptor.attach()`'s returned `{api}` field, if it returned
338
+ * that shape (undefined otherwise). `on()`/`onEvent()` subscribe to this
339
+ * service's `ctx.emit()` output -- see module doc comment's "Observability
340
+ * events" section. `teardown()` calls whatever teardown function
341
+ * `descriptor.attach()` returned (bare-function or `{teardown}` shape) and
342
+ * then stops all further event delivery via `on()`/`onEvent()`. Does not
343
+ * (cannot -- see module doc comment) remove a registered `createBackend`
344
+ * backend from `network`.
345
+ */
346
+ export function attachService(peerNode, network, descriptor) {
347
+ if (!peerNode) throw new Error('attachService: peerNode is required')
348
+ if (!descriptor || typeof descriptor !== 'object') {
349
+ throw new Error('attachService: descriptor is required')
350
+ }
351
+ if (typeof descriptor.attach !== 'function') {
352
+ throw new Error(`attachService: descriptor '${descriptor.name || '(unnamed)'}'.attach() is required`)
353
+ }
354
+ if (!descriptor.name || typeof descriptor.name !== 'string') {
355
+ throw new Error('attachService: descriptor.name is required')
356
+ }
357
+
358
+ const eventBus = createEventBus()
359
+ const ctx = createServiceContext({ peerNode, network, eventBus })
360
+ const attachResult = descriptor.attach(peerNode, ctx)
361
+
362
+ let attachTeardown
363
+ let api
364
+ if (typeof attachResult === 'function') {
365
+ attachTeardown = attachResult
366
+ } else if (attachResult && typeof attachResult === 'object') {
367
+ attachTeardown = attachResult.teardown
368
+ api = attachResult.api
369
+ }
370
+
371
+ let backendScheme = null
372
+ if (typeof descriptor.createBackend === 'function') {
373
+ if (!network) {
374
+ throw new Error(
375
+ `attachService: descriptor '${descriptor.name}' has createBackend but no network was supplied ` +
376
+ '(pass a VirtualNetwork as attachService\'s second argument)',
377
+ )
378
+ }
379
+ backendScheme = descriptor.backendScheme || DEFAULT_BACKEND_SCHEME
380
+ const backend = descriptor.createBackend(ctx)
381
+ network.addBackend(backendScheme, backend)
382
+ }
383
+
384
+ return {
385
+ name: descriptor.name,
386
+ backendScheme,
387
+ api,
388
+ on(event, callback) {
389
+ return eventBus.on(event, callback)
390
+ },
391
+ onEvent(callback) {
392
+ return eventBus.onEvent(callback)
393
+ },
394
+ async teardown() {
395
+ if (typeof attachTeardown === 'function') {
396
+ await attachTeardown()
397
+ }
398
+ eventBus.closeAll()
399
+ },
400
+ }
401
+ }
402
+
403
+ export { DEFAULT_BACKEND_SCHEME, createEventBus }