@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.
- package/README.md +232 -1
- package/package.json +7 -3
- package/src/agent-runtime.mjs +342 -0
- package/src/chunk-replication.mjs +751 -0
- package/src/cloud-storage-backend.mjs +932 -0
- package/src/cloud-storage.mjs +859 -0
- package/src/compat.mjs +98 -0
- package/src/grant-log.mjs +840 -0
- package/src/index.mjs +34 -2
- package/src/key-distribution.mjs +525 -0
- package/src/manifest-sync.mjs +363 -0
- package/src/mesh-agent-swarm.mjs +376 -0
- package/src/mesh-bootstrap.mjs +1131 -12
- package/src/mesh-compute.mjs +397 -0
- package/src/mesh-dht.mjs +182 -0
- package/src/mesh-fetch.mjs +246 -0
- package/src/mesh-hardening.mjs +226 -0
- package/src/mesh-health.mjs +282 -0
- package/src/mesh-keepalive.mjs +353 -0
- package/src/mesh-kv.mjs +673 -0
- package/src/mesh-orchestrator-tools.mjs +251 -0
- package/src/mesh-orchestrator.mjs +343 -0
- package/src/mesh-rpc.mjs +300 -0
- package/src/mesh-service.mjs +403 -0
- package/src/mesh-swarm.mjs +677 -0
- package/src/mesh-timestamp.mjs +265 -0
- package/src/mesh-torrent.mjs +683 -0
- package/src/mesh-verification.mjs +367 -0
- package/src/mesh-websocket.mjs +722 -0
- package/src/observability-bridge.mjs +453 -0
- package/src/orchestrator.mjs +18 -5
- package/src/peer-agent-swarm.mjs +12 -1
- package/src/peer-chat.mjs +230 -61
- package/src/peer-compute.mjs +66 -3
- package/src/peer-escrow.mjs +350 -1
- package/src/peer-files.mjs +362 -168
- package/src/peer-ipfs.mjs +205 -10
- package/src/peer-node.mjs +33 -2
- package/src/peer-routing.mjs +369 -5
- package/src/peer-terminal.mjs +400 -130
- package/src/serverless-executor-andbox.mjs +136 -0
- package/src/serverless-fetch.mjs +70 -0
- package/src/serverless-functions.mjs +67 -0
- package/src/serverless-peer-select.mjs +69 -0
- package/src/serverless-proxy.mjs +127 -0
- package/src/serverless-router.mjs +115 -0
- package/src/serverless-sites.mjs +116 -0
- package/src/serverless-static.mjs +202 -0
- package/src/serverless-wire.mjs +87 -0
- package/src/peer-session.mjs +0 -937
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mesh-fetch.mjs -- Phase 2 of the BrowserMeshFetch/BrowserMeshWebSocket plan
|
|
3
|
+
* (`browsermesh-fetch-websocket.md`): `browserMeshFetch(url, init)`, a
|
|
4
|
+
* standard-`fetch()`-shaped way to reach a mesh-addressable pod directly
|
|
5
|
+
* from application code, using Phase 1's `mesh-rpc.mjs` `request()` as the
|
|
6
|
+
* actual transport underneath.
|
|
7
|
+
*
|
|
8
|
+
* ---------------------------------------------------------------------------
|
|
9
|
+
* API SHAPE DECISION -- factory function, not a class, not a bare function.
|
|
10
|
+
*
|
|
11
|
+
* The user's original sketch (`new BrowserMeshFetch(credentials)`) and the
|
|
12
|
+
* plan's own wording both leave the exact shape open ("decide during
|
|
13
|
+
* implementation which fits better"). Three options were on the table:
|
|
14
|
+
*
|
|
15
|
+
* 1. A bare function that takes a bound RPC client as a 3rd argument on
|
|
16
|
+
* every call (`browserMeshFetch(url, init, meshRpcApi)`) -- rejected:
|
|
17
|
+
* it makes every call site thread the client through, unlike real
|
|
18
|
+
* `fetch()`, and doesn't match "a live mesh-rpc service's `api.request()`"
|
|
19
|
+
* being a long-lived binding, not a per-call parameter.
|
|
20
|
+
* 2. A class (`new BrowserMeshFetch(meshRpcApi)`, called as
|
|
21
|
+
* `instance.fetch(url, init)` or `instance(url, init)`) -- rejected:
|
|
22
|
+
* a class instance is not directly callable as `instance(url, init)`
|
|
23
|
+
* without `Function.prototype.bind`/`Proxy` tricks, so it can't match
|
|
24
|
+
* "the standard `fetch(url, init)` calling convention as closely as
|
|
25
|
+
* reasonably possible" as well as a plain function can. Calling it
|
|
26
|
+
* `instance.fetch(url, init)` is workable but reads as its own bespoke
|
|
27
|
+
* method, not really "shaped like `fetch()`".
|
|
28
|
+
* 3. `createBrowserMeshFetch(meshRpcApi) -> (url, init) => Promise<Response>`
|
|
29
|
+
* -- CHOSEN. The factory binds once to a live `mesh-rpc` service's
|
|
30
|
+
* `api` (the object `attachService(peerNode, network,
|
|
31
|
+
* createMeshRpcService(...))` returns as `.api`, i.e. `{ request }`),
|
|
32
|
+
* and returns a plain function whose call signature is *exactly*
|
|
33
|
+
* `fetch(url, init)` -- so existing code that expects "a fetch-shaped
|
|
34
|
+
* function" (e.g. passing it as a `fetch` option to some other library)
|
|
35
|
+
* can use it as a drop-in without any adapter. This also matches this
|
|
36
|
+
* package's own established convention of factories over classes for
|
|
37
|
+
* things that bind to a live service (`createMeshRpcService()` itself,
|
|
38
|
+
* `createMeshNode()`, etc.) -- `mesh-rpc.mjs`/`mesh-service.mjs` never
|
|
39
|
+
* introduce a class for a "callable bound to a live connection" shape.
|
|
40
|
+
*
|
|
41
|
+
* Usage:
|
|
42
|
+
* const { api } = attachService(peerNode, network, createMeshRpcService({ onRequest }))
|
|
43
|
+
* const browserMeshFetch = createBrowserMeshFetch(api)
|
|
44
|
+
* const res = await browserMeshFetch('mesh://somePod/api/v1', { method: 'POST', body: { x: 1 } })
|
|
45
|
+
* const data = await res.json()
|
|
46
|
+
*
|
|
47
|
+
* ---------------------------------------------------------------------------
|
|
48
|
+
* URL PARSING -- reuses `parseMeshRequest()` from
|
|
49
|
+
* `@johnhenry/browsermesh-discovery`'s `sw-routing.mjs` as-is (not
|
|
50
|
+
* reimplemented). `MeshFetchRouter` itself is NOT reused as the transport
|
|
51
|
+
* here: its `route()` method is shaped `Request -> Promise<Response|null>`,
|
|
52
|
+
* a Service-Worker-`fetch`-event-interceptor shape (return `null` for "not
|
|
53
|
+
* mine", a `Request` object as input) that doesn't fit a directly-callable
|
|
54
|
+
* `browserMeshFetch(url, init)` API -- callers here have a URL string and an
|
|
55
|
+
* options bag, not an already-constructed `Request`, and a non-mesh URL
|
|
56
|
+
* should throw (see below), not resolve `null`. Its body/header
|
|
57
|
+
* normalization and response-shaping conventions ARE mirrored below (see
|
|
58
|
+
* `extractBody()`/`buildResponse()`), since those parts fit regardless of
|
|
59
|
+
* the input/output shape wrapped around them.
|
|
60
|
+
*
|
|
61
|
+
* ---------------------------------------------------------------------------
|
|
62
|
+
* ERROR-VS-REJECT SEMANTICS -- deliberately follows real `fetch()`, not
|
|
63
|
+
* `MeshFetchRouter.route()`'s own convention (which turns an `onRpc` error
|
|
64
|
+
* into a resolved `502 Response` -- appropriate for a Service Worker
|
|
65
|
+
* interceptor, which must always produce SOME `Response` for the page it's
|
|
66
|
+
* intercepting on behalf of, but wrong for a directly-callable `fetch()`
|
|
67
|
+
* clone):
|
|
68
|
+
*
|
|
69
|
+
* - `parseMeshRequest(url)` returning `null` (not a `mesh://`/`*.mesh.local`
|
|
70
|
+
* URL) throws a `TypeError` SYNCHRONOUSLY, before any `Promise` is even
|
|
71
|
+
* created -- matching real `fetch()`'s own behavior for a malformed URL
|
|
72
|
+
* (`new Request(url)` throws synchronously inside `fetch()`'s body,
|
|
73
|
+
* which is not declared `async`, so the exception propagates immediately
|
|
74
|
+
* rather than becoming a rejected promise). This is why
|
|
75
|
+
* `browserMeshFetch` below is written as a plain (non-`async`) function
|
|
76
|
+
* that validates the URL up front and only THEN delegates to an inner
|
|
77
|
+
* `async` helper for the actual RPC round trip -- an `async function`
|
|
78
|
+
* can never throw synchronously (any throw inside one is always wrapped
|
|
79
|
+
* into a rejected `Promise`), so getting a genuine synchronous throw
|
|
80
|
+
* requires the outer function not be `async`.
|
|
81
|
+
* - A failure from Phase 1's `request()` (timeout, or `ctx.sendTo()`
|
|
82
|
+
* failing because the peer is unreachable) REJECTS the returned promise
|
|
83
|
+
* with that same error, unmodified -- it does NOT resolve with a
|
|
84
|
+
* 5xx-shaped `Response`. This matches web-standard `fetch()`: it only
|
|
85
|
+
* ever resolves with an error-status `Response` for an HTTP-level error
|
|
86
|
+
* from a server that actually responded (which here means the
|
|
87
|
+
* responding pod's `onRequest` ran and returned/threw -- `mesh-rpc.mjs`
|
|
88
|
+
* already turns THAT case into a `500`-shaped response that arrives as a
|
|
89
|
+
* normal, resolved RPC response, so it correctly becomes a resolved
|
|
90
|
+
* `Response` here too); it rejects for network-level failures where no
|
|
91
|
+
* server ever answered, which is exactly what a `mesh-rpc` timeout or
|
|
92
|
+
* send failure represents.
|
|
93
|
+
*
|
|
94
|
+
* No browser-only imports at module level.
|
|
95
|
+
*/
|
|
96
|
+
|
|
97
|
+
import { parseMeshRequest } from '@johnhenry/browsermesh-discovery'
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* @typedef {object} MeshRpcApi
|
|
101
|
+
* @property {(podId: string, req: {method?: string, path?: string, headers?: object, body?: *}) => Promise<{status: number, headers: object, body: *}>} request
|
|
102
|
+
* The `api.request()` method `attachService()` returns for a
|
|
103
|
+
* `createMeshRpcService()` descriptor (Phase 1, `mesh-rpc.mjs`).
|
|
104
|
+
*/
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Bind a `browserMeshFetch(url, init)` function to a live `mesh-rpc`
|
|
108
|
+
* service's `api`. See this file's module doc comment for the full
|
|
109
|
+
* "API SHAPE DECISION" writeup on why this is a factory rather than a class
|
|
110
|
+
* or a bare function.
|
|
111
|
+
*
|
|
112
|
+
* @param {MeshRpcApi} meshRpcApi - The `.api` returned by
|
|
113
|
+
* `attachService(peerNode, network, createMeshRpcService(...))`.
|
|
114
|
+
* @returns {(url: string, init?: {method?: string, headers?: object|Headers|[string,string][], body?: *}) => Promise<Response>}
|
|
115
|
+
*/
|
|
116
|
+
export function createBrowserMeshFetch(meshRpcApi) {
|
|
117
|
+
if (!meshRpcApi || typeof meshRpcApi.request !== 'function') {
|
|
118
|
+
throw new Error(
|
|
119
|
+
'createBrowserMeshFetch: a mesh-rpc api with a request(podId, {...}) method is required ' +
|
|
120
|
+
'(pass the .api returned by attachService(peerNode, network, createMeshRpcService(...)))',
|
|
121
|
+
)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* `browserMeshFetch()` itself -- deliberately NOT an `async function` (see
|
|
126
|
+
* the module doc comment's "ERROR-VS-REJECT SEMANTICS" section for why: a
|
|
127
|
+
* malformed URL must throw synchronously, matching real `fetch()`, which
|
|
128
|
+
* an `async function` body can never do).
|
|
129
|
+
*
|
|
130
|
+
* @param {string} url
|
|
131
|
+
* @param {{method?: string, headers?: object|Headers|[string,string][], body?: *}} [init]
|
|
132
|
+
* @returns {Promise<Response>}
|
|
133
|
+
*/
|
|
134
|
+
return function browserMeshFetch(url, init = {}) {
|
|
135
|
+
const urlStr = typeof url === 'string' ? url : String(url)
|
|
136
|
+
const parsed = parseMeshRequest(urlStr)
|
|
137
|
+
if (!parsed) {
|
|
138
|
+
throw new TypeError(
|
|
139
|
+
`browserMeshFetch: '${urlStr}' is not a valid mesh:// or *.mesh.local URL`,
|
|
140
|
+
)
|
|
141
|
+
}
|
|
142
|
+
return performMeshFetch(meshRpcApi, parsed, init || {})
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ---------------------------------------------------------------------------
|
|
147
|
+
// Internals
|
|
148
|
+
// ---------------------------------------------------------------------------
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The actual async RPC round trip, once the URL is known to be valid. Any
|
|
152
|
+
* rejection from `meshRpcApi.request()` (timeout, unreachable peer) is
|
|
153
|
+
* intentionally left to propagate unmodified -- see module doc comment.
|
|
154
|
+
*
|
|
155
|
+
* @param {MeshRpcApi} meshRpcApi
|
|
156
|
+
* @param {{podId: string, path: string}} parsed
|
|
157
|
+
* @param {{method?: string, headers?: object|Headers|[string,string][], body?: *}} init
|
|
158
|
+
* @returns {Promise<Response>}
|
|
159
|
+
*/
|
|
160
|
+
async function performMeshFetch(meshRpcApi, { podId, path }, init) {
|
|
161
|
+
const method = (init.method || 'GET').toUpperCase()
|
|
162
|
+
const headers = normalizeHeaders(init.headers)
|
|
163
|
+
const body = extractBody(init.body, method)
|
|
164
|
+
|
|
165
|
+
const result = await meshRpcApi.request(podId, { method, path, headers, body })
|
|
166
|
+
return buildResponse(result)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Normalize `init.headers` (a `Headers` instance, a plain object, or an
|
|
171
|
+
* array of `[key, value]` pairs -- the three shapes real `fetch()` accepts)
|
|
172
|
+
* into a plain `{lowercaseKey: value}` object, the shape `mesh-rpc.mjs`'s
|
|
173
|
+
* wire envelope expects. Mirrors `MeshFetchRouter.route()`'s own
|
|
174
|
+
* `Headers`-or-plain-object handling.
|
|
175
|
+
*
|
|
176
|
+
* @param {object|Headers|[string,string][]|undefined} headersInit
|
|
177
|
+
* @returns {object}
|
|
178
|
+
*/
|
|
179
|
+
function normalizeHeaders(headersInit) {
|
|
180
|
+
const headers = {}
|
|
181
|
+
if (!headersInit) return headers
|
|
182
|
+
|
|
183
|
+
if (typeof headersInit.forEach === 'function') {
|
|
184
|
+
// Real `Headers` instance (or anything Headers-shaped).
|
|
185
|
+
headersInit.forEach((v, k) => { headers[k.toLowerCase()] = v })
|
|
186
|
+
} else if (Array.isArray(headersInit)) {
|
|
187
|
+
for (const [k, v] of headersInit) headers[String(k).toLowerCase()] = v
|
|
188
|
+
} else if (typeof headersInit === 'object') {
|
|
189
|
+
for (const [k, v] of Object.entries(headersInit)) headers[k.toLowerCase()] = v
|
|
190
|
+
}
|
|
191
|
+
return headers
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Extract/normalize `init.body` the way `MeshFetchRouter.route()` extracts a
|
|
196
|
+
* body from a real `Request` (read as text, then try `JSON.parse` so a
|
|
197
|
+
* JSON-string body arrives at the responder's `onRequest` handler already
|
|
198
|
+
* parsed into a structured value) -- except here the body starts out as
|
|
199
|
+
* whatever `init.body` already is, not raw `Request` bytes, so a
|
|
200
|
+
* non-string body (already a plain object/array/etc, the common case for
|
|
201
|
+
* application code calling `browserMeshFetch(url, { body: {...} })`) is
|
|
202
|
+
* passed through unchanged.
|
|
203
|
+
*
|
|
204
|
+
* GET/HEAD requests never carry a body, matching real `fetch()` (which
|
|
205
|
+
* throws if you pass a `body` with `method: 'GET'`) -- here it's simply
|
|
206
|
+
* dropped rather than throwing, since a mesh-RPC request's `body` field is
|
|
207
|
+
* optional/advisory rather than spec-enforced.
|
|
208
|
+
*
|
|
209
|
+
* @param {*} rawBody
|
|
210
|
+
* @param {string} method
|
|
211
|
+
* @returns {*}
|
|
212
|
+
*/
|
|
213
|
+
function extractBody(rawBody, method) {
|
|
214
|
+
if (rawBody === undefined || rawBody === null) return undefined
|
|
215
|
+
if (method === 'GET' || method === 'HEAD') return undefined
|
|
216
|
+
|
|
217
|
+
if (typeof rawBody === 'string') {
|
|
218
|
+
try {
|
|
219
|
+
return JSON.parse(rawBody)
|
|
220
|
+
} catch {
|
|
221
|
+
return rawBody // keep as plain string, matching MeshFetchRouter.route()
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return rawBody
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Shape a `mesh-rpc` response (`{status, headers, body}`) into a real
|
|
229
|
+
* `Response`, mirroring `MeshFetchRouter.route()`'s own conventions:
|
|
230
|
+
* default status `200`, default `content-type: application/json` when no
|
|
231
|
+
* headers were supplied, and JSON-stringify a non-string body.
|
|
232
|
+
*
|
|
233
|
+
* @param {{status?: number, headers?: object, body?: *}} result
|
|
234
|
+
* @returns {Response}
|
|
235
|
+
*/
|
|
236
|
+
function buildResponse(result) {
|
|
237
|
+
const status = typeof result?.status === 'number' ? result.status : 200
|
|
238
|
+
const headers = result?.headers && typeof result.headers === 'object' && Object.keys(result.headers).length > 0
|
|
239
|
+
? result.headers
|
|
240
|
+
: { 'content-type': 'application/json' }
|
|
241
|
+
const body = result && 'body' in result ? result.body : undefined
|
|
242
|
+
const resBody = body === undefined
|
|
243
|
+
? null
|
|
244
|
+
: typeof body === 'string' ? body : JSON.stringify(body)
|
|
245
|
+
return new Response(resBody, { status, headers })
|
|
246
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mesh-hardening.mjs -- wires `@johnhenry/browsermesh-core`'s hardening.mjs
|
|
3
|
+
* primitives (`RetryWithBackoff`, `TransportFailover`, `TransportMetrics`,
|
|
4
|
+
* `MetricsRegistry`) around the `MeshTransportNegotiator` `mesh-bootstrap.mjs`
|
|
5
|
+
* constructs, so a transient WebRTC/ICE negotiation failure (the class of
|
|
6
|
+
* problem issue #26 documented, since fixed upstream via PR #53, but not
|
|
7
|
+
* the only source of transient failure a real mesh will see) is retried
|
|
8
|
+
* with backoff instead of failing `connectToPeer()` outright.
|
|
9
|
+
*
|
|
10
|
+
* ## The seam
|
|
11
|
+
* `PeerNode.connectToPeer(pubKey, endpoints, auth)` (peer-node.mjs) calls
|
|
12
|
+
* exactly one method on whatever `transportNegotiator` it was constructed
|
|
13
|
+
* with: `this.#transportNeg.negotiate(endpoints, auth)`. That is the only
|
|
14
|
+
* method `hardening.mjs`'s primitives need to intercept, and (per
|
|
15
|
+
* `hardening.mjs`'s own JSDoc `@example` on `RetryWithBackoff` --
|
|
16
|
+
* `retry.execute(() => negotiator.negotiate(endpoints))` -- and on
|
|
17
|
+
* `TransportFailover` -- `new TransportFailover({ negotiator, endpoints,
|
|
18
|
+
* ... })` / `failover.connect()`, both of which call
|
|
19
|
+
* `negotiator.negotiate(endpoints, auth)` internally) it is exactly what
|
|
20
|
+
* these primitives were built to wrap. `createHardenedNegotiator()` below
|
|
21
|
+
* returns an object shaped like a negotiator (just `negotiate()`) that is a
|
|
22
|
+
* drop-in replacement wherever `new PeerNode({ transportNegotiator })`
|
|
23
|
+
* expects one -- `registerAdapter()` keeps being called on the real,
|
|
24
|
+
* wrapped `MeshTransportNegotiator` directly (`mesh-bootstrap.mjs` does
|
|
25
|
+
* this, unchanged), since mutating that real instance is exactly what the
|
|
26
|
+
* wrapper's closed-over `negotiator` reference sees at call time regardless
|
|
27
|
+
* of registration order.
|
|
28
|
+
*
|
|
29
|
+
* ## What's wired, and how
|
|
30
|
+
* - `RetryWithBackoff`: one instance per distinct `endpoints` shape (see
|
|
31
|
+
* `#endpointsKey()`), lazily created on first `negotiate()` call and
|
|
32
|
+
* reused after that. Scoping the circuit breaker per-endpoints (in
|
|
33
|
+
* practice, per-peer -- `webrtc-negotiator.mjs`'s convention makes
|
|
34
|
+
* `endpoints.webrtc` the remote peer's podId) rather than sharing one
|
|
35
|
+
* instance node-wide is a deliberate choice: a single unreachable peer
|
|
36
|
+
* (bad NAT, offline) should trip *that* peer's circuit breaker, not
|
|
37
|
+
* start rejecting `connectToPeer()` calls to every other, perfectly
|
|
38
|
+
* reachable peer.
|
|
39
|
+
* - `TransportFailover`: likewise one instance per endpoints key, reused
|
|
40
|
+
* across calls -- `.connect()` on the first call, `.failover()` on any
|
|
41
|
+
* subsequent call once a transport is already active (a caller invoking
|
|
42
|
+
* `connectToPeer()` again for a peer that already has a live transport
|
|
43
|
+
* is asking for a fresh one), so `.failedTypes`/`.activeTransport`
|
|
44
|
+
* remain meaningful for a peer across repeated connection attempts.
|
|
45
|
+
* - `TransportMetrics` / `MetricsRegistry`: negotiation latency and
|
|
46
|
+
* negotiation errors are recorded per endpoints key; once a transport is
|
|
47
|
+
* live, its `send()` and inbound `onMessage()` are additionally
|
|
48
|
+
* instrumented for byte/message counters (errors surfaced via
|
|
49
|
+
* `onError()` too, where the transport supports it).
|
|
50
|
+
*
|
|
51
|
+
* ## What's *not* wired here, and why
|
|
52
|
+
* - `TransportHealthCheck`: a genuine ping/pong liveness probe needs a
|
|
53
|
+
* keepalive envelope type on `PeerNode`'s own dispatch bus (mirroring
|
|
54
|
+
* `mesh-sync.mjs`'s `envelopeType` convention) so the *far* side actually
|
|
55
|
+
* answers pings -- that's a real protocol addition (both peers need to
|
|
56
|
+
* speak it), out of scope for this pass. Wiring `TransportHealthCheck`
|
|
57
|
+
* here without a real peer-side pong responder would just be a timer
|
|
58
|
+
* that always reports "unhealthy" after `maxMissed` misses no matter how
|
|
59
|
+
* healthy the connection actually is -- worse than not wiring it.
|
|
60
|
+
* - `ConnectionPool`: `PeerNode` keeps exactly one active session per peer
|
|
61
|
+
* today (`#sessions` in peer-node.mjs, keyed by a fresh session per
|
|
62
|
+
* `connectToPeer()`/`adoptIncomingSession()` call) -- there is no
|
|
63
|
+
* multiple-connections-per-peer call site for `ConnectionPool`'s
|
|
64
|
+
* `add()`/`acquire()`/`release()` cycle to attach to without a deeper
|
|
65
|
+
* change to `PeerNode`'s session model itself.
|
|
66
|
+
* Both remain exported from `@johnhenry/browsermesh-core` for callers who
|
|
67
|
+
* want to build that wiring themselves.
|
|
68
|
+
*
|
|
69
|
+
* No browser-only imports at module level.
|
|
70
|
+
*/
|
|
71
|
+
|
|
72
|
+
import { RetryWithBackoff, TransportFailover, MetricsRegistry } from '@johnhenry/browsermesh-core'
|
|
73
|
+
|
|
74
|
+
const DEFAULT_METRICS_KEY = 'unknown'
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Derive a stable key for an `endpoints` map (`{ webrtc: 'peer-pod-id', ... }`)
|
|
78
|
+
* to scope per-peer `RetryWithBackoff`/`TransportFailover`/metrics state.
|
|
79
|
+
*
|
|
80
|
+
* Exported (not just used internally) so `mesh-keepalive.mjs` (issue #110)
|
|
81
|
+
* can derive the SAME key to look up this file's `failovers` map for a given
|
|
82
|
+
* peer's pubKey -- see that file's own header comment for why this is a
|
|
83
|
+
* best-effort, webrtc-convention-specific correlation rather than a real
|
|
84
|
+
* shared index keyed by pubKey.
|
|
85
|
+
*
|
|
86
|
+
* @param {object} [endpoints]
|
|
87
|
+
* @returns {string}
|
|
88
|
+
*/
|
|
89
|
+
export function endpointsKey(endpoints) {
|
|
90
|
+
if (!endpoints) return DEFAULT_METRICS_KEY
|
|
91
|
+
const values = Object.keys(endpoints)
|
|
92
|
+
.sort()
|
|
93
|
+
.map((type) => `${type}=${endpoints[type]}`)
|
|
94
|
+
return values.length > 0 ? values.join('&') : DEFAULT_METRICS_KEY
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Best-effort byte-length estimate for a `send()`/`onMessage()` payload,
|
|
99
|
+
* which may be a string (the common case -- `PeerNode.sendTo()`'s own JSDoc
|
|
100
|
+
* example calls it with `JSON.stringify(...)`), a typed array/ArrayBuffer,
|
|
101
|
+
* or a plain object.
|
|
102
|
+
*
|
|
103
|
+
* @param {*} data
|
|
104
|
+
* @returns {number}
|
|
105
|
+
*/
|
|
106
|
+
function estimateByteLength(data) {
|
|
107
|
+
if (typeof data === 'string') return data.length
|
|
108
|
+
if (data && typeof data.byteLength === 'number') return data.byteLength
|
|
109
|
+
try {
|
|
110
|
+
return JSON.stringify(data)?.length ?? 0
|
|
111
|
+
} catch {
|
|
112
|
+
return 0
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Instrument a live transport's `send()`/`onMessage()`/`onError()` (where
|
|
118
|
+
* present) to feed a `TransportMetrics` instance. Idempotent -- a transport
|
|
119
|
+
* is only instrumented once even if handed back through `negotiate()` more
|
|
120
|
+
* than once (e.g. `TransportFailover` returning the same still-open
|
|
121
|
+
* transport is not expected, but this guards it cheaply either way).
|
|
122
|
+
*
|
|
123
|
+
* @param {object} transport
|
|
124
|
+
* @param {import('@johnhenry/browsermesh-core').TransportMetrics} metrics
|
|
125
|
+
* @returns {object} The same transport, instrumented in place.
|
|
126
|
+
*/
|
|
127
|
+
function instrumentTransport(transport, metrics) {
|
|
128
|
+
if (!transport || transport.__hardeningInstrumented) return transport
|
|
129
|
+
transport.__hardeningInstrumented = true
|
|
130
|
+
|
|
131
|
+
if (typeof transport.send === 'function') {
|
|
132
|
+
const originalSend = transport.send.bind(transport)
|
|
133
|
+
transport.send = (data) => {
|
|
134
|
+
try {
|
|
135
|
+
const result = originalSend(data)
|
|
136
|
+
metrics.recordSend(estimateByteLength(data))
|
|
137
|
+
return result
|
|
138
|
+
} catch (err) {
|
|
139
|
+
metrics.recordError()
|
|
140
|
+
throw err
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (typeof transport.onMessage === 'function') {
|
|
146
|
+
transport.onMessage((data) => metrics.recordReceive(estimateByteLength(data)))
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (typeof transport.onError === 'function') {
|
|
150
|
+
transport.onError(() => metrics.recordError())
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return transport
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Wrap a real `MeshTransportNegotiator` with retry/backoff + failover +
|
|
158
|
+
* metrics (`@johnhenry/browsermesh-core`'s hardening.mjs), returning an
|
|
159
|
+
* object shaped like a negotiator -- `negotiate(endpoints, auth)` is the
|
|
160
|
+
* only method `PeerNode.connectToPeer()` calls, so this is a drop-in
|
|
161
|
+
* replacement for `new PeerNode({ transportNegotiator })`.
|
|
162
|
+
*
|
|
163
|
+
* @param {object} opts
|
|
164
|
+
* @param {import('@johnhenry/browsermesh-transport').MeshTransportNegotiator} opts.negotiator
|
|
165
|
+
* The real negotiator (adapters are still registered on this directly).
|
|
166
|
+
* @param {object} [opts.retryOptions] - Passed to each per-endpoints-key
|
|
167
|
+
* `new RetryWithBackoff()` (maxRetries/baseDelayMs/maxDelayMs/jitterFactor/
|
|
168
|
+
* resetTimeoutMs -- see hardening.mjs).
|
|
169
|
+
* @param {Function} [opts.onLog]
|
|
170
|
+
* @returns {{
|
|
171
|
+
* negotiate: (endpoints: object, auth?: object) => Promise<object>,
|
|
172
|
+
* metrics: import('@johnhenry/browsermesh-core').MetricsRegistry,
|
|
173
|
+
* failovers: Map<string, import('@johnhenry/browsermesh-core').TransportFailover>,
|
|
174
|
+
* retries: Map<string, import('@johnhenry/browsermesh-core').RetryWithBackoff>,
|
|
175
|
+
* }}
|
|
176
|
+
*/
|
|
177
|
+
export function createHardenedNegotiator({ negotiator, retryOptions, onLog }) {
|
|
178
|
+
if (!negotiator) {
|
|
179
|
+
throw new Error('createHardenedNegotiator: options.negotiator is required')
|
|
180
|
+
}
|
|
181
|
+
const log = onLog || (() => {})
|
|
182
|
+
const metrics = new MetricsRegistry()
|
|
183
|
+
const failovers = new Map()
|
|
184
|
+
const retries = new Map()
|
|
185
|
+
|
|
186
|
+
function getRetry(key) {
|
|
187
|
+
let retry = retries.get(key)
|
|
188
|
+
if (!retry) {
|
|
189
|
+
retry = new RetryWithBackoff(retryOptions)
|
|
190
|
+
retries.set(key, retry)
|
|
191
|
+
}
|
|
192
|
+
return retry
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function getFailover(key, endpoints, auth) {
|
|
196
|
+
let failover = failovers.get(key)
|
|
197
|
+
if (!failover) {
|
|
198
|
+
failover = new TransportFailover({ negotiator, endpoints, auth, retry: getRetry(key) })
|
|
199
|
+
failovers.set(key, failover)
|
|
200
|
+
}
|
|
201
|
+
return failover
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function negotiate(endpoints, auth) {
|
|
205
|
+
const key = endpointsKey(endpoints)
|
|
206
|
+
const failover = getFailover(key, endpoints, auth)
|
|
207
|
+
const transportMetrics = metrics.getOrCreate(key)
|
|
208
|
+
const startedAt = Date.now()
|
|
209
|
+
|
|
210
|
+
let transport
|
|
211
|
+
try {
|
|
212
|
+
transport = failover.activeTransport
|
|
213
|
+
? await failover.failover('mesh-hardening:reconnect')
|
|
214
|
+
: await failover.connect()
|
|
215
|
+
} catch (err) {
|
|
216
|
+
transportMetrics.recordError()
|
|
217
|
+
log('mesh-hardening:negotiate-failed', { key, error: err?.message || String(err) })
|
|
218
|
+
throw err
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
transportMetrics.recordLatency(Date.now() - startedAt)
|
|
222
|
+
return instrumentTransport(transport, transportMetrics)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
return { negotiate, metrics, failovers, retries }
|
|
226
|
+
}
|