@johnhenry/browsermesh-apps 0.15.0 → 0.17.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 +298 -17
- package/package.json +13 -9
- package/src/apps.mjs +4 -4
- package/src/audit.mjs +2 -2
- package/src/chat.mjs +3 -3
- package/src/cloud-storage-backend.mjs +5 -7
- package/src/cloud-storage.mjs +5 -4
- package/src/compat.mjs +2 -2
- package/src/consensus.mjs +7 -7
- package/src/devtools.mjs +3 -3
- package/src/gpu.mjs +2 -2
- package/src/index.mjs +12 -0
- package/src/internal/channel-codec.mjs +179 -0
- package/src/internal/json-message.mjs +49 -0
- package/src/internal/relay-flow.mjs +178 -0
- package/src/internal/request-target.mjs +280 -0
- package/src/internal/rpc-body.mjs +33 -0
- package/src/marketplace-ui.mjs +1 -1
- package/src/mesh-agent-swarm.mjs +1 -1
- package/src/mesh-bootstrap.mjs +47 -1
- package/src/mesh-channel.mjs +716 -0
- package/src/mesh-fetch.mjs +77 -263
- package/src/mesh-hardening.mjs +8 -1
- package/src/mesh-relay-backend.mjs +116 -22
- package/src/mesh-relay-host.mjs +296 -55
- package/src/mesh-rpc.mjs +126 -265
- package/src/mesh-sync.mjs +1 -1
- package/src/orchestrator.mjs +54 -29
- package/src/payments.mjs +56 -14
- package/src/peer-agent-swarm.mjs +2 -2
- package/src/peer-agent.mjs +7 -7
- package/src/peer-compute.mjs +2 -2
- package/src/peer-encrypted-store.mjs +3 -3
- package/src/peer-escrow.mjs +2 -2
- package/src/peer-health.mjs +3 -3
- package/src/peer-node.mjs +8 -5
- package/src/peer-payments.mjs +2 -2
- package/src/peer-registry.mjs +45 -3
- package/src/peer-routing.mjs +158 -21
- package/src/peer-services.mjs +3 -3
- package/src/peer-timestamp.mjs +3 -3
- package/src/peer-torrent.mjs +112 -47
- package/src/peer-verification.mjs +3 -3
- package/src/pod-host-service.mjs +48 -7
- package/src/pod-placement.mjs +582 -0
- package/src/pod-supervisor.mjs +9 -30
- package/src/protocol-channel.mjs +327 -0
- package/src/resources.mjs +2 -2
- package/src/restart-policy.mjs +67 -0
- package/src/scheduler.mjs +3 -3
- package/src/serverless-proxy.mjs +58 -7
- package/src/silent-catch.mjs +22 -9
- package/src/tools.mjs +3 -3
- package/src/visualizations.mjs +2 -2
- package/src/wsh-negotiator.mjs +97 -0
package/src/mesh-rpc.mjs
CHANGED
|
@@ -1,300 +1,161 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* C-G of this package otherwise implement): the missing mesh-RPC transport
|
|
6
|
-
* that `packages/browsermesh-discovery/src/sw-routing.mjs`'s `MeshFetchRouter`
|
|
7
|
-
* has always expected to be handed as its `onRpc` callback
|
|
8
|
-
* (`onRpc({podId, method, path, headers, body}) -> Promise<{status?, headers?,
|
|
9
|
-
* body}>`) but that this repo never actually implemented. A LATER phase (2,
|
|
10
|
-
* not this one) wires this file's `request()` into that `onRpc` slot; this
|
|
11
|
-
* phase only builds the transport itself and does not import or touch
|
|
12
|
-
* `sw-routing.mjs`.
|
|
2
|
+
* Attachable, bounded request/response RPC over a MeshService context.
|
|
3
|
+
* The caller identity comes from the transport. Each service handler owns its
|
|
4
|
+
* resource authorization; this transport does not grant access to any resource.
|
|
13
5
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* `ctx.onIncomingData()`/`ctx.sendTo()`, filtered by `envelope.type` (default
|
|
18
|
-
* `'mesh-rpc'`), on the same dispatch bus every other `MeshService` in this
|
|
19
|
-
* family uses. Unlike `chunk-replication.mjs`, there is no fixed
|
|
20
|
-
* resource/scope here -- this is a general-purpose request/response
|
|
21
|
-
* envelope pair, not a chunk-store-specific protocol.
|
|
22
|
-
*
|
|
23
|
-
* ---------------------------------------------------------------------------
|
|
24
|
-
* Wire protocol -- two message kinds sharing one envelope `type` (default
|
|
25
|
-
* `'mesh-rpc'`):
|
|
26
|
-
*
|
|
27
|
-
* Request (caller -> responder):
|
|
28
|
-
* `{ type, kind: 'rpc-request', requestId, method, path, headers, body }`
|
|
29
|
-
*
|
|
30
|
-
* Response (responder -> caller), always sent back, even for an error:
|
|
31
|
-
* `{ type, kind: 'rpc-response', requestId, status, headers, body }`
|
|
32
|
-
*
|
|
33
|
-
* `requestId` is generated by the calling side (`nextRequestId()`, the same
|
|
34
|
-
* `${podId}:${Date.now()}:${seq}` shape `chunk-replication.mjs` uses) and
|
|
35
|
-
* echoed back verbatim by the responder, so multiple concurrent in-flight
|
|
36
|
-
* `request()` calls -- to the same peer or different peers -- are correlated
|
|
37
|
-
* independently via a `Map<requestId, {resolve, reject, timer}>` (see
|
|
38
|
-
* `pendingRequests` below); there is no shared mutable "current request"
|
|
39
|
-
* state anywhere in this file, so there is no crosstalk between concurrent
|
|
40
|
-
* callers by construction.
|
|
41
|
-
*
|
|
42
|
-
* ---------------------------------------------------------------------------
|
|
43
|
-
* AUTHORIZATION IS EXPLICITLY OUT OF SCOPE FOR THIS TRANSPORT (the plan's
|
|
44
|
-
* own "Design decisions" section, restated here because it's easy to miss):
|
|
45
|
-
* unlike `chunk-replication.mjs`/`manifest-sync.mjs`, this file does not
|
|
46
|
-
* check `ctx.registry.checkAccess()` against any resource/scope, and does
|
|
47
|
-
* not depend on `GrantLog` at all. A general-purpose RPC transport has no
|
|
48
|
-
* fixed resource to check a scope against -- deciding what `{method, path}`
|
|
49
|
-
* combinations are allowed for a given caller is the RESPONDING POD's own
|
|
50
|
-
* `onRequest` handler's job, exactly the way a real HTTP server's
|
|
51
|
-
* application code owns its own authorization, not its TCP/TLS transport
|
|
52
|
-
* layer. Callers that need authorization should implement it inside the
|
|
53
|
-
* `onRequest` handler they pass to `createMeshRpcService()`.
|
|
54
|
-
*
|
|
55
|
-
* ---------------------------------------------------------------------------
|
|
56
|
-
* NO HANDLER REGISTERED -- if a pod attaches this service with no
|
|
57
|
-
* `onRequest` (or attaches no `mesh-rpc` service at all), every inbound
|
|
58
|
-
* request still gets a clean, explicit `501`-shaped response
|
|
59
|
-
* (`{status: 501, body: {error: 'no RPC handler registered'}}`) rather than
|
|
60
|
-
* being silently dropped (which would leave the caller's `request()`
|
|
61
|
-
* waiting out the full timeout for no discoverable reason) or thrown
|
|
62
|
-
* (which would crash the shared `ctx.onIncomingData()` dispatch loop every
|
|
63
|
-
* other `MeshService` on this same `peerNode` also relies on).
|
|
64
|
-
*
|
|
65
|
-
* `onRequest` THROWING is handled the same defensive way: caught and turned
|
|
66
|
-
* into a clean `{status: 500, body: {error: err.message}}` response sent
|
|
67
|
-
* back to the caller, never an unhandled rejection and never a crash of the
|
|
68
|
-
* dispatch loop (see `handleRequest()`'s `try/catch` below).
|
|
69
|
-
*
|
|
70
|
-
* ---------------------------------------------------------------------------
|
|
71
|
-
* DEFAULT TIMEOUT: 10000ms (`DEFAULT_REQUEST_TIMEOUT_MS`). Chosen
|
|
72
|
-
* deliberately longer than `chunk-replication.mjs`'s timeouts
|
|
73
|
-
* (1.5-3s, tuned for one already-chunked, size-capped ciphertext blob over a
|
|
74
|
-
* single WebRTC/loopback hop) because this transport's `{method, path,
|
|
75
|
-
* headers, body}` shape is general-purpose -- a responding pod's own
|
|
76
|
-
* `onRequest` handler might do real work (a local disk/IndexedDB read, a
|
|
77
|
-
* nested mesh call of its own, etc.) before replying, and this file has no
|
|
78
|
-
* way to know how expensive that handler is ahead of time. 10s is a
|
|
79
|
-
* "generous enough that a legitimate slow handler doesn't get punished,
|
|
80
|
-
* short enough that a caller relying on this for something interactive
|
|
81
|
-
* (Phase 2's `browserMeshFetch()`) doesn't hang indefinitely" starting
|
|
82
|
-
* default, not a tuned constant -- callers with different latency
|
|
83
|
-
* expectations should override it via
|
|
84
|
-
* `createMeshRpcService({ requestTimeoutMs })`.
|
|
85
|
-
*
|
|
86
|
-
* ---------------------------------------------------------------------------
|
|
87
|
-
* Observability events (`ctx.emit()`, Phase 1 of the mesh-KV-and-
|
|
88
|
-
* observability plan -- see `mesh-service.mjs`'s module doc comment for the
|
|
89
|
-
* full convention this follows). Three curated events, not a mechanical
|
|
90
|
-
* conversion of this file's `onLog` calls:
|
|
91
|
-
*
|
|
92
|
-
* - `mesh-rpc:request-served` `{from, method, path, status}` -- this peer
|
|
93
|
-
* finished handling an inbound request and sent a response (whatever
|
|
94
|
-
* the status -- including the `501`/`500` fallback cases below).
|
|
95
|
-
* - `mesh-rpc:handler-error` `{from, method, path, error}` -- the
|
|
96
|
-
* registered `onRequest` threw/rejected; this is the one case this
|
|
97
|
-
* file's own doc comment calls out as needing to "never become an
|
|
98
|
-
* unhandled rejection or crash the dispatch loop", so it's worth a
|
|
99
|
-
* dashboard being able to see it happened even though the caller still
|
|
100
|
-
* got a clean `500`.
|
|
101
|
-
* - `mesh-rpc:request-timeout` `{to, method, path}` -- the CALLING side's
|
|
102
|
-
* `request()` gave up waiting after `requestTimeoutMs` with no matching
|
|
103
|
-
* response.
|
|
104
|
-
*
|
|
105
|
-
* No browser-only imports at module level.
|
|
6
|
+
* Structured bodies keep their existing JSON semantics. Top-level binary
|
|
7
|
+
* bodies use an explicit bodyEncoding field so they survive JSON transports.
|
|
8
|
+
* Cancellation is advisory: aborting does not undo side effects already made.
|
|
106
9
|
*/
|
|
10
|
+
import { encodeBody, decodeBody } from './internal/rpc-body.mjs'
|
|
107
11
|
|
|
108
|
-
/** Default `envelope.type` used to route mesh-RPC payloads on the shared `onIncomingData()` bus. */
|
|
109
12
|
const DEFAULT_ENVELOPE_TYPE = 'mesh-rpc'
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* How long `request()` waits for a matching `rpc-response` envelope before
|
|
113
|
-
* giving up and rejecting. See the module doc comment's "DEFAULT TIMEOUT"
|
|
114
|
-
* section for the full reasoning -- this is a starting default, not a tuned
|
|
115
|
-
* constant.
|
|
116
|
-
*/
|
|
117
13
|
const DEFAULT_REQUEST_TIMEOUT_MS = 10000
|
|
14
|
+
const DEFAULT_MAX_BODY_BYTES = 1024 * 1024
|
|
15
|
+
const abortError = reason => reason?.name === 'AbortError' ? reason : new DOMException(reason?.message || 'RPC request aborted', 'AbortError')
|
|
16
|
+
const validId = id => typeof id === 'string' && id.length > 0 && id.length <= 512
|
|
118
17
|
|
|
119
|
-
// ---------------------------------------------------------------------------
|
|
120
|
-
// createMeshRpcService
|
|
121
|
-
// ---------------------------------------------------------------------------
|
|
122
|
-
|
|
123
|
-
/**
|
|
124
|
-
* Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) that
|
|
125
|
-
* implements a general-purpose request/response RPC transport over
|
|
126
|
-
* `ctx.sendTo()`/`ctx.onIncomingData()`, addressed directly by podId. See
|
|
127
|
-
* this file's module doc comment for the full wire-protocol/authorization
|
|
128
|
-
* writeup.
|
|
129
|
-
*
|
|
130
|
-
* @param {object} [opts]
|
|
131
|
-
* @param {(req: {fromPubKey: string, method: string, path: string, headers: object, body: *}) => Promise<{status?: number, headers?: object, body?: *}>} [opts.onRequest]
|
|
132
|
-
* Optional. Called for every inbound RPC request this peer receives.
|
|
133
|
-
* If omitted, every inbound request gets a `501`-shaped response instead
|
|
134
|
-
* of being silently dropped -- see module doc comment. A thrown/rejected
|
|
135
|
-
* `onRequest` is caught and turned into a `500`-shaped response, never an
|
|
136
|
-
* unhandled rejection.
|
|
137
|
-
* @param {string} [opts.envelopeType='mesh-rpc']
|
|
138
|
-
* @param {number} [opts.requestTimeoutMs=10000] - See `DEFAULT_REQUEST_TIMEOUT_MS`'s doc comment.
|
|
139
|
-
* @param {Function} [opts.onLog]
|
|
140
|
-
* @returns {import('./mesh-service.mjs').MeshService}
|
|
141
|
-
*/
|
|
142
18
|
export function createMeshRpcService({
|
|
143
19
|
onRequest,
|
|
144
20
|
envelopeType = DEFAULT_ENVELOPE_TYPE,
|
|
145
21
|
requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
|
|
22
|
+
maxBodyBytes = DEFAULT_MAX_BODY_BYTES,
|
|
23
|
+
maxInflight = 64,
|
|
24
|
+
maxIncoming = 64,
|
|
25
|
+
maxIncomingPerPeer = 8,
|
|
146
26
|
onLog,
|
|
147
27
|
} = {}) {
|
|
148
|
-
if (onRequest !== undefined && typeof onRequest !== 'function')
|
|
149
|
-
|
|
28
|
+
if (onRequest !== undefined && typeof onRequest !== 'function') throw new TypeError('createMeshRpcService: onRequest must be a function if provided')
|
|
29
|
+
for (const [name, value] of Object.entries({ requestTimeoutMs, maxBodyBytes, maxInflight, maxIncoming, maxIncomingPerPeer })) {
|
|
30
|
+
if (!Number.isSafeInteger(value) || value <= 0) throw new TypeError(`createMeshRpcService: ${name} must be a positive integer`)
|
|
150
31
|
}
|
|
151
|
-
|
|
152
32
|
const log = onLog || (() => {})
|
|
153
|
-
|
|
154
33
|
return {
|
|
155
34
|
name: 'mesh-rpc',
|
|
156
|
-
|
|
157
35
|
attach(peerNode, ctx) {
|
|
158
|
-
let
|
|
159
|
-
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
if (
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
36
|
+
let seq = 0, closed = false
|
|
37
|
+
// Per-attach random part: ids stay unique across restarts and reconnects, not only within one process.
|
|
38
|
+
const nonce = Array.from(crypto.getRandomValues(new Uint8Array(8)), b => b.toString(16).padStart(2, '0')).join('')
|
|
39
|
+
const pending = new Map()
|
|
40
|
+
const incoming = new Map()
|
|
41
|
+
const incomingCounts = new Map()
|
|
42
|
+
const keyFor = (peer, id) => JSON.stringify([peer, id])
|
|
43
|
+
const send = (peer, message) => ctx.sendTo(peer, envelopeType, message)
|
|
44
|
+
function settle(id, error, result) {
|
|
45
|
+
const p = pending.get(id)
|
|
46
|
+
if (!p) return
|
|
47
|
+
pending.delete(id)
|
|
48
|
+
clearTimeout(p.timer)
|
|
49
|
+
p.signal?.removeEventListener('abort', p.onAbort)
|
|
50
|
+
if (error) p.reject(error)
|
|
51
|
+
else p.resolve(result)
|
|
52
|
+
}
|
|
53
|
+
function cancel(id, error) {
|
|
54
|
+
const p = pending.get(id)
|
|
55
|
+
if (!p) return
|
|
56
|
+
settle(id, error)
|
|
57
|
+
// Older responders ignore this new kind. The local promise still ends.
|
|
58
|
+
Promise.resolve().then(() => send(p.target, { kind: 'rpc-cancel', requestId: id })).catch(() => {})
|
|
59
|
+
}
|
|
60
|
+
async function handleRequest(from, msg) {
|
|
61
|
+
if (closed || !validId(msg.requestId)) return
|
|
62
|
+
const key = keyFor(from, msg.requestId)
|
|
63
|
+
if (incoming.has(key)) return
|
|
64
|
+
if (incoming.size >= maxIncoming || (incomingCounts.get(from) || 0) >= maxIncomingPerPeer) {
|
|
65
|
+
await send(from, { kind: 'rpc-response', requestId: msg.requestId, status: 429, body: { error: 'too many RPC requests' } })
|
|
66
|
+
return
|
|
188
67
|
}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
/** @param {string} fromPubKey @param {object} msg */
|
|
196
|
-
async function handleRequest(fromPubKey, msg) {
|
|
197
|
-
const { requestId } = msg
|
|
198
|
-
let result
|
|
199
|
-
|
|
200
|
-
if (typeof onRequest !== 'function') {
|
|
201
|
-
// No handler registered at all -- an explicit, discoverable
|
|
202
|
-
// 501, never a silent drop (see module doc comment).
|
|
203
|
-
result = { status: 501, body: { error: 'no RPC handler registered' } }
|
|
204
|
-
} else {
|
|
205
|
-
try {
|
|
206
|
-
const handled = await onRequest({
|
|
207
|
-
fromPubKey,
|
|
208
|
-
method: msg.method,
|
|
209
|
-
path: msg.path,
|
|
210
|
-
headers: msg.headers,
|
|
211
|
-
body: msg.body,
|
|
212
|
-
})
|
|
213
|
-
result = handled && typeof handled === 'object' ? handled : {}
|
|
214
|
-
} catch (err) {
|
|
215
|
-
// onRequest() throwing/rejecting must never become an
|
|
216
|
-
// unhandled rejection or crash the dispatch loop -- turn it
|
|
217
|
-
// into a clean error response instead.
|
|
218
|
-
log('mesh-rpc:handler-threw', { from: fromPubKey, requestId, error: err?.message || String(err) })
|
|
219
|
-
ctx.emit('mesh-rpc:handler-error', { from: fromPubKey, method: msg.method, path: msg.path, error: err?.message || String(err) })
|
|
220
|
-
result = { status: 500, body: { error: err?.message || String(err) } }
|
|
221
|
-
}
|
|
68
|
+
let body
|
|
69
|
+
try { body = decodeBody(msg, maxBodyBytes) }
|
|
70
|
+
catch {
|
|
71
|
+
await send(from, { kind: 'rpc-response', requestId: msg.requestId, status: 400, body: { error: 'invalid or oversized RPC body' } })
|
|
72
|
+
return
|
|
222
73
|
}
|
|
223
|
-
|
|
224
|
-
const
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
74
|
+
const controller = new AbortController()
|
|
75
|
+
const timer = setTimeout(() => controller.abort(new DOMException('RPC handler deadline exceeded', 'TimeoutError')), requestTimeoutMs)
|
|
76
|
+
timer.unref?.()
|
|
77
|
+
incoming.set(key, { controller, timer })
|
|
78
|
+
incomingCounts.set(from, (incomingCounts.get(from) || 0) + 1)
|
|
228
79
|
try {
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
80
|
+
let result
|
|
81
|
+
if (!onRequest) result = { status: 501, body: { error: 'no RPC handler registered' } }
|
|
82
|
+
else {
|
|
83
|
+
try {
|
|
84
|
+
const handled = await onRequest({ fromPubKey: from, method: msg.method, path: msg.path, headers: msg.headers, body, signal: controller.signal })
|
|
85
|
+
result = handled && typeof handled === 'object' ? handled : {}
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (controller.signal.aborted) return
|
|
88
|
+
log('mesh-rpc:handler-threw', { from, requestId: msg.requestId, error: error?.message || String(error) })
|
|
89
|
+
ctx.emit('mesh-rpc:handler-error', { from, method: msg.method, path: msg.path, error: error?.message || String(error) })
|
|
90
|
+
result = { status: 500, body: { error: error?.message || String(error) } }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (closed || controller.signal.aborted) return
|
|
94
|
+
let status = Number.isInteger(result.status) ? result.status : 200
|
|
95
|
+
let encoded
|
|
96
|
+
try { encoded = encodeBody(result.body, maxBodyBytes) }
|
|
97
|
+
catch { encoded = { body: { error: 'invalid or oversized RPC response' } }; status = 500 }
|
|
98
|
+
await send(from, { kind: 'rpc-response', requestId: msg.requestId, status, headers: result.headers || {}, ...encoded })
|
|
99
|
+
ctx.emit('mesh-rpc:request-served', { from, method: msg.method, path: msg.path, status })
|
|
100
|
+
} finally {
|
|
101
|
+
clearTimeout(timer)
|
|
102
|
+
incoming.delete(key)
|
|
103
|
+
const count = (incomingCounts.get(from) || 1) - 1
|
|
104
|
+
if (count) incomingCounts.set(from, count)
|
|
105
|
+
else incomingCounts.delete(from)
|
|
233
106
|
}
|
|
234
107
|
}
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
const requestId =
|
|
259
|
-
|
|
260
|
-
|
|
108
|
+
const unsubscribe = ctx.onIncomingData(envelopeType, (from, msg) => {
|
|
109
|
+
if (closed || !msg || !validId(msg.requestId)) return
|
|
110
|
+
if (msg.kind === 'rpc-request') {
|
|
111
|
+
handleRequest(from, msg).catch(error => log('mesh-rpc:response-send-failed', { to: from, error: error?.message || String(error) }))
|
|
112
|
+
} else if (msg.kind === 'rpc-cancel') {
|
|
113
|
+
const active = incoming.get(keyFor(from, msg.requestId))
|
|
114
|
+
if (active) { clearTimeout(active.timer); active.controller.abort(abortError()) }
|
|
115
|
+
} else if (msg.kind === 'rpc-response') {
|
|
116
|
+
const p = pending.get(msg.requestId)
|
|
117
|
+
// A request ID is correlation data, never proof of the responder.
|
|
118
|
+
if (!p || p.target !== from) return
|
|
119
|
+
try { settle(msg.requestId, null, { status: msg.status, headers: msg.headers || {}, body: decodeBody(msg, maxBodyBytes) }) }
|
|
120
|
+
catch (error) { settle(msg.requestId, error) }
|
|
121
|
+
}
|
|
122
|
+
})
|
|
123
|
+
function request(target, { method = 'GET', path = '/', headers = {}, body } = {}, { signal, timeoutMs = requestTimeoutMs } = {}) {
|
|
124
|
+
if (closed) return Promise.reject(new Error('mesh-rpc: service torn down'))
|
|
125
|
+
if (typeof target !== 'string' || !target || target.length > 512) return Promise.reject(new TypeError('mesh-rpc: target must identify one peer'))
|
|
126
|
+
if (signal?.aborted) return Promise.reject(abortError(signal.reason))
|
|
127
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) return Promise.reject(new TypeError('mesh-rpc: timeoutMs must be a positive integer'))
|
|
128
|
+
if (pending.size >= maxInflight) return Promise.reject(new Error('mesh-rpc: too many requests in flight'))
|
|
129
|
+
let encoded
|
|
130
|
+
try { encoded = encodeBody(body, maxBodyBytes) } catch (error) { return Promise.reject(error) }
|
|
131
|
+
const requestId = `${peerNode?.podId || 'local'}:${Date.now()}:${nonce}:${++seq}`
|
|
132
|
+
return new Promise((resolve, reject) => {
|
|
133
|
+
const onAbort = () => cancel(requestId, abortError(signal.reason))
|
|
261
134
|
const timer = setTimeout(() => {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
135
|
+
ctx.emit('mesh-rpc:request-timeout', { to: target, method, path })
|
|
136
|
+
cancel(requestId, new Error(`mesh-rpc: request ${method} ${path} to ${target} timed out after ${timeoutMs}ms`))
|
|
137
|
+
}, timeoutMs)
|
|
138
|
+
pending.set(requestId, { target, resolve, reject, signal, onAbort, timer })
|
|
139
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
140
|
+
// Return the promise before a slow send can time out or reject it.
|
|
141
|
+
Promise.resolve().then(() => {
|
|
142
|
+
if (!pending.has(requestId)) return
|
|
143
|
+
return send(target, { kind: 'rpc-request', requestId, method, path, headers, ...encoded })
|
|
144
|
+
}).catch(error => settle(requestId, error))
|
|
267
145
|
})
|
|
268
|
-
|
|
269
|
-
try {
|
|
270
|
-
await ctx.sendTo(podId, envelopeType, { kind: 'rpc-request', requestId, method, path, headers, body })
|
|
271
|
-
} catch (err) {
|
|
272
|
-
const pending = pendingRequests.get(requestId)
|
|
273
|
-
if (pending) {
|
|
274
|
-
clearTimeout(pending.timer)
|
|
275
|
-
pendingRequests.delete(requestId)
|
|
276
|
-
}
|
|
277
|
-
throw err
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
return promise
|
|
281
146
|
}
|
|
282
|
-
|
|
283
|
-
const api = { request }
|
|
284
|
-
|
|
285
147
|
return {
|
|
286
|
-
api,
|
|
148
|
+
api: { request },
|
|
287
149
|
teardown() {
|
|
150
|
+
if (closed) return
|
|
151
|
+
closed = true
|
|
288
152
|
unsubscribe()
|
|
289
|
-
for (const
|
|
290
|
-
|
|
291
|
-
p.reject(new Error('mesh-rpc: service torn down while a request was still in flight'))
|
|
292
|
-
}
|
|
293
|
-
pendingRequests.clear()
|
|
153
|
+
for (const id of pending.keys()) settle(id, new Error('mesh-rpc: service torn down while a request was still in flight'))
|
|
154
|
+
for (const { controller, timer } of incoming.values()) { clearTimeout(timer); controller.abort(abortError()) }
|
|
294
155
|
},
|
|
295
156
|
}
|
|
296
157
|
},
|
|
297
158
|
}
|
|
298
159
|
}
|
|
299
160
|
|
|
300
|
-
export { DEFAULT_ENVELOPE_TYPE, DEFAULT_REQUEST_TIMEOUT_MS }
|
|
161
|
+
export { DEFAULT_ENVELOPE_TYPE, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_MAX_BODY_BYTES }
|
package/src/mesh-sync.mjs
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* underlying transport JSON-serializes them, see `WebRTCPeerConnection.send`),
|
|
10
10
|
* inbound via `onIncomingData()`, filtering by `envelope.type` (default
|
|
11
11
|
* `'mesh-sync'`) exactly the way `peer-node.mjs`'s own doc comments describe
|
|
12
|
-
* `
|
|
12
|
+
* `Pod.onMessage` routing "by `envelope.type`" -- multiple independent
|
|
13
13
|
* consumers of `onIncomingData()` can coexist on the same bus this way, each
|
|
14
14
|
* ignoring envelopes that aren't theirs.
|
|
15
15
|
*
|
package/src/orchestrator.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* orchestrator.mjs --Pod orchestration engine + tools.
|
|
3
3
|
*
|
|
4
4
|
* MeshOrchestrator coordinates pods across the P2P mesh network.
|
|
5
5
|
* Each operation is also exposed as a BrowserTool subclass so the AI agent
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* No browser-only imports at module level.
|
|
9
9
|
*
|
|
10
10
|
* Run tests:
|
|
11
|
-
* node --import ./
|
|
11
|
+
* cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/orchestrator.test.mjs
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
14
|
import { MESH_TYPE } from '@johnhenry/browsermesh-primitives'
|
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
PodHostDriverError,
|
|
22
22
|
} from '@johnhenry/browsermesh-pod'
|
|
23
23
|
|
|
24
|
-
// A real browser environment (
|
|
24
|
+
// A real browser environment (the host application's tool layer) may already
|
|
25
25
|
// have defined a real, richer `globalThis.BrowserTool` -- honored first, as
|
|
26
26
|
// before. Otherwise (plain Node, e.g. this package's own tests, or any
|
|
27
27
|
// standalone use of this file), fall back to compat.mjs's real `BrowserTool`
|
|
@@ -497,13 +497,10 @@ export class MeshOrchestrator {
|
|
|
497
497
|
* matching `listHostedPods()`/`listPods()`.
|
|
498
498
|
*
|
|
499
499
|
* Deliberately NOT routed through `#collectComputeDescriptors()` /
|
|
500
|
-
* `listComputeCandidates()`: those drop any pod host with no
|
|
501
|
-
* (every ISOLATE-lane host, by lane definition
|
|
502
|
-
*
|
|
503
|
-
*
|
|
504
|
-
* a chance to filter on lane. Reading `#runtimeDescriptors()` directly
|
|
505
|
-
* sidesteps that filter, so an isolate host is listed here even though it
|
|
506
|
-
* is invisible to `listComputeCandidates()`.
|
|
500
|
+
* `listComputeCandidates()`: by default those drop any pod host with no
|
|
501
|
+
* `exec` (every ISOLATE-lane host, by lane definition) so nothing that
|
|
502
|
+
* needs a shell can reach one. Reading `#runtimeDescriptors()` directly
|
|
503
|
+
* lists every pod host regardless of verbs.
|
|
507
504
|
*
|
|
508
505
|
* @returns {Array<{podId: string, lane: string|null, verbs: string[], runtimeClasses: string[], shellBackend: string|null, resource: string, capabilities: string[], hostedBy: string|null}>}
|
|
509
506
|
*/
|
|
@@ -884,8 +881,17 @@ export class MeshOrchestrator {
|
|
|
884
881
|
return this.runComputeTask({ selector: podId, command })
|
|
885
882
|
}
|
|
886
883
|
|
|
887
|
-
|
|
888
|
-
|
|
884
|
+
/**
|
|
885
|
+
* @param {object} [constraints]
|
|
886
|
+
* @param {object} [opts]
|
|
887
|
+
* @param {boolean} [opts.includeSpawnHosts=false] - Also list pod hosts that
|
|
888
|
+
* can `spawn` pods but have no shell (the isolate and browser lanes).
|
|
889
|
+
* They carry `spawn` and `runtime:<lane>` but never `compute`, and are
|
|
890
|
+
* never returned unless this is set: everything that needs a shell
|
|
891
|
+
* (`runComputeTask()`, `execOnPod()`) keeps seeing exec-capable hosts only.
|
|
892
|
+
*/
|
|
893
|
+
async listComputeCandidates(constraints = {}, { includeSpawnHosts = false } = {}) {
|
|
894
|
+
return this.#collectComputeDescriptors(constraints, { includeSpawnHosts }).map((descriptor) => ({
|
|
889
895
|
podId: descriptor.podId,
|
|
890
896
|
resources: { ...descriptor.resources },
|
|
891
897
|
capabilities: [...descriptor.capabilities],
|
|
@@ -894,7 +900,7 @@ export class MeshOrchestrator {
|
|
|
894
900
|
}))
|
|
895
901
|
}
|
|
896
902
|
|
|
897
|
-
selectComputeTarget({ selector = null, constraints = {}, request = null } = {}) {
|
|
903
|
+
selectComputeTarget({ selector = null, constraints = {}, request = null, includeSpawnHosts = false } = {}) {
|
|
898
904
|
const nextRequest = request instanceof ComputeRequest
|
|
899
905
|
? request
|
|
900
906
|
: new ComputeRequest({
|
|
@@ -905,7 +911,14 @@ export class MeshOrchestrator {
|
|
|
905
911
|
requesterId: this.localPodId,
|
|
906
912
|
})
|
|
907
913
|
|
|
908
|
-
|
|
914
|
+
// A spawn-only host (no `compute`) is only a candidate while the scorer
|
|
915
|
+
// rates it above zero for this request: a request it cannot serve (a
|
|
916
|
+
// shell module, a lane it does not offer) must not fall through to it
|
|
917
|
+
// just because it is the only descriptor left.
|
|
918
|
+
const descriptors = this.#collectComputeDescriptors(nextRequest.constraints || {}, { includeSpawnHosts })
|
|
919
|
+
.filter((descriptor) => descriptor.capabilities.includes('compute')
|
|
920
|
+
|| selector
|
|
921
|
+
|| ResourceScorer.score(nextRequest, descriptor) > 0)
|
|
909
922
|
if (selector) {
|
|
910
923
|
const selected = descriptors.find((descriptor) => descriptor.podId === selector)
|
|
911
924
|
if (!selected) {
|
|
@@ -1276,7 +1289,7 @@ export class MeshOrchestrator {
|
|
|
1276
1289
|
return route ? 'online' : 'unknown'
|
|
1277
1290
|
}
|
|
1278
1291
|
|
|
1279
|
-
#collectComputeDescriptors(constraints = {}) {
|
|
1292
|
+
#collectComputeDescriptors(constraints = {}, { includeSpawnHosts = false } = {}) {
|
|
1280
1293
|
const merged = new Map()
|
|
1281
1294
|
const descriptors = []
|
|
1282
1295
|
|
|
@@ -1303,7 +1316,7 @@ export class MeshOrchestrator {
|
|
|
1303
1316
|
}
|
|
1304
1317
|
|
|
1305
1318
|
for (const peer of this.#runtimeDescriptors()) {
|
|
1306
|
-
const descriptor = runtimePeerToComputeDescriptor(peer)
|
|
1319
|
+
const descriptor = runtimePeerToComputeDescriptor(peer, { includeSpawnHosts })
|
|
1307
1320
|
if (!descriptor) continue
|
|
1308
1321
|
if (constraints && !descriptor.matches(constraints)) continue
|
|
1309
1322
|
descriptors.push(descriptor)
|
|
@@ -1318,7 +1331,18 @@ export class MeshOrchestrator {
|
|
|
1318
1331
|
}
|
|
1319
1332
|
}
|
|
1320
1333
|
|
|
1321
|
-
|
|
1334
|
+
/**
|
|
1335
|
+
* Whether a runtime-registry peer is a pod host that can `spawn` pods
|
|
1336
|
+
* (`podHostRuntimePeer()` records the verbs it serves).
|
|
1337
|
+
* @param {object} peer
|
|
1338
|
+
* @returns {boolean}
|
|
1339
|
+
*/
|
|
1340
|
+
function isSpawnHost(peer) {
|
|
1341
|
+
const verbs = peer?.metadata?.podHost?.verbs
|
|
1342
|
+
return Array.isArray(verbs) && verbs.includes('spawn') && peer?.metadata?.deploymentSupport?.canDeploy === true
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
function runtimePeerToComputeDescriptor(peer, { includeSpawnHosts = false } = {}) {
|
|
1322
1346
|
const podId = peer?.identity?.podId
|
|
1323
1347
|
|| peer?.identity?.fingerprint
|
|
1324
1348
|
|| peer?.identity?.canonicalId
|
|
@@ -1336,7 +1360,10 @@ function runtimePeerToComputeDescriptor(peer) {
|
|
|
1336
1360
|
: []),
|
|
1337
1361
|
])
|
|
1338
1362
|
if (!capabilities.includes('compute')) {
|
|
1339
|
-
|
|
1363
|
+
// A host with no shell can still place pods. It is only ever surfaced
|
|
1364
|
+
// for placement scoring (`includeSpawnHosts`), and never claims `compute`.
|
|
1365
|
+
if (!(includeSpawnHosts && isSpawnHost(peer))) return null
|
|
1366
|
+
capabilities.push('spawn')
|
|
1340
1367
|
}
|
|
1341
1368
|
const route = (peer.reachability || [])[0] || null
|
|
1342
1369
|
const availability = route?.health === 'offline'
|
|
@@ -1817,16 +1844,14 @@ function formatPodHostError(err, { host, verb } = {}) {
|
|
|
1817
1844
|
* Primary path: `orchestrator.listComputeCandidates()` (the same
|
|
1818
1845
|
* `ResourceScorer`-adjacent descriptor list `MeshctlComputeTool` reads),
|
|
1819
1846
|
* narrowed to hosts advertising `runtime:<lane>`, preferring one with
|
|
1820
|
-
* `availability: 'online'`.
|
|
1847
|
+
* `availability: 'online'`. Candidates are requested with
|
|
1848
|
+
* `includeSpawnHosts`, so an ISOLATE-lane host (no `exec`, by lane
|
|
1849
|
+
* definition -- same for `browser`) is a candidate too, without ever being
|
|
1850
|
+
* a `compute` one.
|
|
1821
1851
|
*
|
|
1822
|
-
* Fallback: `orchestrator.listPodHosts()
|
|
1823
|
-
*
|
|
1824
|
-
*
|
|
1825
|
-
* `listComputeCandidates()` derives its `compute` capability from `exec`,
|
|
1826
|
-
* so an ISOLATE-lane host (no `exec`, by lane definition -- same for
|
|
1827
|
-
* `browser`) never appears in it at all, regardless of lane filtering.
|
|
1828
|
-
* `listPodHosts()` reads the same runtime-registry peers directly, without
|
|
1829
|
-
* that filter, so it still finds such a host.
|
|
1852
|
+
* Fallback: `orchestrator.listPodHosts()`, for an orchestrator whose
|
|
1853
|
+
* `listComputeCandidates()` does not accept the option (a duck-typed
|
|
1854
|
+
* facade) or lists nothing: it reads the runtime-registry peers directly.
|
|
1830
1855
|
*
|
|
1831
1856
|
* @param {object} orchestrator - A `MeshOrchestrator` (or the tool facade
|
|
1832
1857
|
* `mesh-orchestrator-tools.mjs` builds around one).
|
|
@@ -1840,7 +1865,7 @@ export async function pickAutoHost(orchestrator, lane) {
|
|
|
1840
1865
|
? ISOLATION.MICROVM
|
|
1841
1866
|
: ISOLATION.ANY
|
|
1842
1867
|
const candidates = typeof orchestrator.listComputeCandidates === 'function'
|
|
1843
|
-
? await orchestrator.listComputeCandidates({ isolation })
|
|
1868
|
+
? await orchestrator.listComputeCandidates({ isolation }, { includeSpawnHosts: true })
|
|
1844
1869
|
: []
|
|
1845
1870
|
const laneCandidates = candidates.filter((c) => c.capabilities.includes(`runtime:${lane}`))
|
|
1846
1871
|
const best = laneCandidates.find((c) => c.availability === 'online') || laneCandidates[0] || null
|
|
@@ -2232,7 +2257,7 @@ function parseMeshctlFlags(args) {
|
|
|
2232
2257
|
* Subcommands: pods, status, exec, deploy, top, compute, expose, drain,
|
|
2233
2258
|
* spawn, snapshot, restore, hosted, hosts, supervise, supervised
|
|
2234
2259
|
*
|
|
2235
|
-
* @param {
|
|
2260
|
+
* @param {object} shellRegistry
|
|
2236
2261
|
* @param {MeshOrchestrator} orchestrator
|
|
2237
2262
|
*/
|
|
2238
2263
|
export function registerMeshctlBuiltins(shellRegistry, orchestrator) {
|