@johnhenry/browsermesh-apps 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +232 -1
- package/package.json +2 -2
- 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 +799 -0
- package/src/compat.mjs +98 -0
- package/src/grant-log.mjs +840 -0
- package/src/index.mjs +25 -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/peer-session.mjs +0 -937
package/src/mesh-rpc.mjs
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mesh-rpc.mjs -- Phase 1 of the BrowserMeshFetch/BrowserMeshWebSocket plan
|
|
3
|
+
* (`browsermesh-fetch-websocket.md`, a plan that runs in parallel with, and
|
|
4
|
+
* is NOT part of, the CloudStorage mesh-native-services plan that phases
|
|
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`.
|
|
13
|
+
*
|
|
14
|
+
* Built as a `MeshService` (Phase C, `mesh-service.mjs`), following
|
|
15
|
+
* `chunk-replication.mjs`'s `queryHave()`/`fetchFrom()` request-with-timeout
|
|
16
|
+
* pattern as the closest precedent: wire payloads travel over
|
|
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.
|
|
106
|
+
*/
|
|
107
|
+
|
|
108
|
+
/** Default `envelope.type` used to route mesh-RPC payloads on the shared `onIncomingData()` bus. */
|
|
109
|
+
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
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 10000
|
|
118
|
+
|
|
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
|
+
export function createMeshRpcService({
|
|
143
|
+
onRequest,
|
|
144
|
+
envelopeType = DEFAULT_ENVELOPE_TYPE,
|
|
145
|
+
requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
|
|
146
|
+
onLog,
|
|
147
|
+
} = {}) {
|
|
148
|
+
if (onRequest !== undefined && typeof onRequest !== 'function') {
|
|
149
|
+
throw new Error('createMeshRpcService: onRequest must be a function if provided')
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const log = onLog || (() => {})
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
name: 'mesh-rpc',
|
|
156
|
+
|
|
157
|
+
attach(peerNode, ctx) {
|
|
158
|
+
let reqSeq = 0
|
|
159
|
+
/** Monotonic-ish unique id for correlating a request with its eventual response. */
|
|
160
|
+
const nextRequestId = () => `${peerNode?.podId || 'local'}:${Date.now()}:${++reqSeq}`
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* @type {Map<string, {resolve: (res: {status: number, headers: object, body: *}) => void,
|
|
164
|
+
* reject: (err: Error) => void, timer: ReturnType<typeof setTimeout>}>}
|
|
165
|
+
* requestId -> in-flight outbound request tracking, see `request()`.
|
|
166
|
+
* Every entry is independent -- concurrent requests to the same or
|
|
167
|
+
* different peers never share state, so there is no crosstalk by
|
|
168
|
+
* construction.
|
|
169
|
+
*/
|
|
170
|
+
const pendingRequests = new Map()
|
|
171
|
+
|
|
172
|
+
// -----------------------------------------------------------------
|
|
173
|
+
// Inbound dispatch
|
|
174
|
+
// -----------------------------------------------------------------
|
|
175
|
+
const unsubscribe = ctx.onIncomingData(envelopeType, (fromPubKey, msg) => {
|
|
176
|
+
if (!msg || typeof msg.kind !== 'string') return
|
|
177
|
+
if (msg.kind === 'rpc-request') {
|
|
178
|
+
handleRequest(fromPubKey, msg).catch((err) => {
|
|
179
|
+
// handleRequest() itself already catches onRequest()'s own
|
|
180
|
+
// errors and turns them into a clean response -- reaching here
|
|
181
|
+
// would mean sendTo() itself failed (e.g. the peer disconnected
|
|
182
|
+
// mid-flight), which is logged, not rethrown, so it can never
|
|
183
|
+
// crash the shared onIncomingData() dispatch loop.
|
|
184
|
+
log('mesh-rpc:request-handling-failed', { from: fromPubKey, requestId: msg.requestId, error: err?.message || String(err) })
|
|
185
|
+
})
|
|
186
|
+
} else if (msg.kind === 'rpc-response') {
|
|
187
|
+
handleResponse(fromPubKey, msg)
|
|
188
|
+
}
|
|
189
|
+
})
|
|
190
|
+
|
|
191
|
+
// -----------------------------------------------------------------
|
|
192
|
+
// Responding side -- this peer receiving an inbound RPC request.
|
|
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
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const status = typeof result.status === 'number' ? result.status : 200
|
|
225
|
+
const headers = result.headers && typeof result.headers === 'object' ? result.headers : {}
|
|
226
|
+
const body = 'body' in result ? result.body : undefined
|
|
227
|
+
|
|
228
|
+
try {
|
|
229
|
+
await ctx.sendTo(fromPubKey, envelopeType, { kind: 'rpc-response', requestId, status, headers, body })
|
|
230
|
+
ctx.emit('mesh-rpc:request-served', { from: fromPubKey, method: msg.method, path: msg.path, status })
|
|
231
|
+
} catch (err) {
|
|
232
|
+
log('mesh-rpc:response-send-failed', { to: fromPubKey, requestId, error: err?.message || String(err) })
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// -----------------------------------------------------------------
|
|
237
|
+
// Calling side -- this peer awaiting a response to its own request.
|
|
238
|
+
// -----------------------------------------------------------------
|
|
239
|
+
|
|
240
|
+
/** @param {string} fromPubKey @param {object} msg */
|
|
241
|
+
function handleResponse(fromPubKey, msg) {
|
|
242
|
+
const pending = pendingRequests.get(msg.requestId)
|
|
243
|
+
if (!pending) return // no longer waiting (already timed out, or not ours) -- ignore
|
|
244
|
+
pendingRequests.delete(msg.requestId)
|
|
245
|
+
clearTimeout(pending.timer)
|
|
246
|
+
pending.resolve({ status: msg.status, headers: msg.headers || {}, body: msg.body })
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Send an RPC request to `podId` and await its response.
|
|
251
|
+
* @param {string} podId
|
|
252
|
+
* @param {{method?: string, path?: string, headers?: object, body?: *}} [req]
|
|
253
|
+
* @returns {Promise<{status: number, headers: object, body: *}>}
|
|
254
|
+
* Rejects if no matching response arrives within `requestTimeoutMs`,
|
|
255
|
+
* or if `ctx.sendTo()` itself fails (e.g. the peer is unreachable).
|
|
256
|
+
*/
|
|
257
|
+
async function request(podId, { method = 'GET', path = '/', headers = {}, body } = {}) {
|
|
258
|
+
const requestId = nextRequestId()
|
|
259
|
+
|
|
260
|
+
const promise = new Promise((resolve, reject) => {
|
|
261
|
+
const timer = setTimeout(() => {
|
|
262
|
+
pendingRequests.delete(requestId)
|
|
263
|
+
ctx.emit('mesh-rpc:request-timeout', { to: podId, method, path })
|
|
264
|
+
reject(new Error(`mesh-rpc: request ${method} ${path} to ${podId} timed out after ${requestTimeoutMs}ms`))
|
|
265
|
+
}, requestTimeoutMs)
|
|
266
|
+
pendingRequests.set(requestId, { resolve, reject, timer })
|
|
267
|
+
})
|
|
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
|
+
}
|
|
282
|
+
|
|
283
|
+
const api = { request }
|
|
284
|
+
|
|
285
|
+
return {
|
|
286
|
+
api,
|
|
287
|
+
teardown() {
|
|
288
|
+
unsubscribe()
|
|
289
|
+
for (const p of pendingRequests.values()) {
|
|
290
|
+
clearTimeout(p.timer)
|
|
291
|
+
p.reject(new Error('mesh-rpc: service torn down while a request was still in flight'))
|
|
292
|
+
}
|
|
293
|
+
pendingRequests.clear()
|
|
294
|
+
},
|
|
295
|
+
}
|
|
296
|
+
},
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export { DEFAULT_ENVELOPE_TYPE, DEFAULT_REQUEST_TIMEOUT_MS }
|