@johnhenry/browsermesh-apps 0.14.0 → 0.16.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 CHANGED
@@ -600,6 +600,36 @@ layer.
600
600
 
601
601
  ### `browserMeshFetch`
602
602
 
603
+ `createBrowserMeshFetch(api, { bodyMode: 'http' })` accepts standard HTTP body
604
+ types and sends their exact bytes, including native multipart form headers.
605
+ Passing a `Request` also selects that behavior. The default `bodyMode:
606
+ 'structured'` retains the original JSON-oriented convention: JSON-looking
607
+ string inputs are parsed before the handler receives them. Both modes preserve
608
+ binary responses and return null bodies for HEAD and status 204, 205 or 304.
609
+ The factory runs in browsers without Node globals. Mesh IDs remain case
610
+ sensitive; prefer `mesh://` addresses when representing cryptographic IDs,
611
+ since ordinary HTTP URL hostname handling can lowercase them.
612
+
613
+ This is bounded, buffered RPC rather than a streaming HTTP tunnel. The default
614
+ body cap is 1 MiB; `maxBodyBytes` can narrow the fetch adapter's upload cap and
615
+ the RPC service's request/response cap. Transport message-size limits still
616
+ apply. Large file transfer needs chunking or a streaming transport.
617
+
618
+ `createMeshRpcService()` accepts `maxInflight` (64), `maxIncoming` (64),
619
+ `maxIncomingPerPeer` (8), `maxBodyBytes` (1 MiB), and `requestTimeoutMs`
620
+ (10 seconds). Call `api.request(peer, request, { signal, timeoutMs })` to cancel
621
+ or bound an individual call. Handlers receive `signal`; only the original
622
+ caller may cancel their work. A matching response ID from another peer is
623
+ ignored. Cancel and timeout end local waiting and request remote cancellation;
624
+ they do not undo side effects or force a handler that ignores its signal to
625
+ stop. An unfinished handler continues to count against receiver admission.
626
+
627
+ Top-level `Uint8Array`, other array-buffer views and `ArrayBuffer` bodies use
628
+ the additive wire field `bodyEncoding: 'base64'`; plain JSON bodies keep their
629
+ previous wire shape. Binary calls and remote cancellation require updated
630
+ responders; older responders still support existing structured calls. This
631
+ transport supplies no resource grants: handlers must authorize the caller.
632
+
603
633
  `createBrowserMeshFetch(meshRpcApi) -> (url, init) => Promise<Response>` binds
604
634
  once to a live `mesh-rpc` service's `api` (the `{ request }` object
605
635
  `attachService()` returns as `.api`) and hands back a plain function whose
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-apps",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "Application layer: marketplace, chat, payments, compute, orchestration, and agent tools for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -27,7 +27,7 @@
27
27
  "directory": "packages/browsermesh-apps"
28
28
  },
29
29
  "peerDependencies": {
30
- "@johnhenry/browsermesh-primitives": ">=0.2.0 <1.0.0",
30
+ "@johnhenry/browsermesh-primitives": ">=0.3.1 <1.0.0",
31
31
  "@johnhenry/browsermesh-pod": ">=0.1.0 <1.0.0",
32
32
  "@johnhenry/browsermesh-core": ">=0.5.0 <1.0.0",
33
33
  "@johnhenry/browsermesh-transport": ">=0.1.0 <1.0.0",
@@ -59,7 +59,7 @@
59
59
  },
60
60
  "devDependencies": {
61
61
  "@johnhenry/andbox": ">=0.0.1 <1.0.0",
62
- "@johnhenry/browsermesh-pod": "^0.1.0",
62
+ "@johnhenry/browsermesh-pod": "^0.1.1",
63
63
  "node-datachannel": "^0.33.4",
64
64
  "fake-indexeddb": "^6.2.5",
65
65
  "webgpu": "^0.6.1"
@@ -0,0 +1,33 @@
1
+ // An explicit envelope field distinguishes bytes from ordinary JSON objects.
2
+ // This works across JSON-only transports without reserving user object keys.
3
+ const encoder = new TextEncoder()
4
+ const tooLarge = () => new RangeError('mesh-rpc: body exceeds maxBodyBytes')
5
+ const viewOf = value => value instanceof ArrayBuffer ? new Uint8Array(value)
6
+ : ArrayBuffer.isView(value) ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : null
7
+
8
+ export function encodeBody(body, limit) {
9
+ const bytes = viewOf(body)
10
+ if (bytes) {
11
+ if (bytes.byteLength > limit) throw tooLarge()
12
+ let text = ''
13
+ for (let i = 0; i < bytes.length; i += 8192) text += String.fromCharCode(...bytes.subarray(i, i + 8192))
14
+ return { body: btoa(text), bodyEncoding: 'base64' }
15
+ }
16
+ const text = JSON.stringify(body)
17
+ if (text !== undefined && encoder.encode(text).byteLength > limit) throw tooLarge()
18
+ return { body }
19
+ }
20
+
21
+ export function decodeBody(message, limit) {
22
+ if (message.bodyEncoding === undefined) {
23
+ encodeBody(message.body, limit)
24
+ return message.body
25
+ }
26
+ if (message.bodyEncoding !== 'base64' || typeof message.body !== 'string') throw new TypeError('mesh-rpc: invalid body encoding')
27
+ const text = message.body
28
+ if (text.length > 4 * Math.ceil(limit / 3)) throw tooLarge()
29
+ if (text.length % 4 || !/^[A-Za-z0-9+/]*={0,2}$/.test(text)) throw new TypeError('mesh-rpc: invalid base64 body')
30
+ const binary = atob(text)
31
+ if (binary.length > limit) throw tooLarge()
32
+ return Uint8Array.from(binary, ch => ch.charCodeAt(0))
33
+ }
@@ -1,279 +1,93 @@
1
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, and -- as of the fix for
95
- * issue #183 -- no Node-only imports at module level either:
96
- * `@johnhenry/browsermesh-discovery` (an optional peerDependency) is
97
- * lazily resolved via `createLazyRequire(import.meta.url)`
98
- * (`./internal/lazy-node-require.mjs`), which itself gets Node's
99
- * `require()` from `process.getBuiltinModule('module')` rather than a
100
- * static `import ... from 'node:module'`. This matters for two reasons:
101
- * first, `browserMeshFetch(url, init)` below is deliberately NOT async
102
- * (see "ERROR-VS-REJECT SEMANTICS" above -- it must throw a `TypeError`
103
- * *synchronously* for a malformed URL, matching real `fetch()`), and
104
- * `createBrowserMeshFetch()`'s own synchronous meshRpcApi-validation throw
105
- * is directly tested (`test/mesh-fetch.test.mjs`'s
106
- * `assert.throws(() => createBrowserMeshFetch(...))`) -- a dynamic
107
- * `import()` is inherently async and would have broken both of those.
108
- * Second, and the reason it's `createLazyRequire()` and not a top-level
109
- * `createRequire(import.meta.url)`: a *static* `import` of `node:module`
110
- * at this file's top level would fail immediately when this file is
111
- * loaded in a browser, even for callers who never call
112
- * `createBrowserMeshFetch()` at all -- since this file is re-exported from
113
- * the package root. `createLazyRequire()` resolves the module lazily
114
- * (only when `createBrowserMeshFetch()` is actually called, not at this
115
- * module's own load time) while staying fully synchronous, so neither
116
- * function's signature or throw semantics change at all. See the
117
- * CHANGELOG entry documenting this fix across the package for the sibling
118
- * files that use the same technique, and `mesh-websocket.mjs`'s module doc
119
- * comment for the one case (a constructor) where a dynamic `import()`
120
- * genuinely could not have worked even with an async rewrite, which is
121
- * what led to trying `require()` here in the first place.
2
+ * Fetch-shaped mesh access. The default bodyMode ('structured') retains the
3
+ * existing JSON-oriented API. Use bodyMode: 'http', or pass a Request, to send
4
+ * exact HTTP body bytes, including multipart forms. Bodies are buffered and
5
+ * bounded, not streamed. Resource authorization belongs in the responder.
122
6
  */
7
+ import { parseMeshRequest } from '@johnhenry/browsermesh-primitives'
8
+ import { DEFAULT_MAX_BODY_BYTES } from './mesh-rpc.mjs'
123
9
 
124
- import { createLazyRequire } from './internal/lazy-node-require.mjs'
10
+ const abortError = signal => signal?.reason instanceof Error ? signal.reason : new DOMException('The operation was aborted', 'AbortError')
125
11
 
126
- /**
127
- * @typedef {object} MeshRpcApi
128
- * @property {(podId: string, req: {method?: string, path?: string, headers?: object, body?: *}) => Promise<{status: number, headers: object, body: *}>} request
129
- * The `api.request()` method `attachService()` returns for a
130
- * `createMeshRpcService()` descriptor (Phase 1, `mesh-rpc.mjs`).
131
- */
132
-
133
- /**
134
- * Bind a `browserMeshFetch(url, init)` function to a live `mesh-rpc`
135
- * service's `api`. See this file's module doc comment for the full
136
- * "API SHAPE DECISION" writeup on why this is a factory rather than a class
137
- * or a bare function.
138
- *
139
- * @param {MeshRpcApi} meshRpcApi - The `.api` returned by
140
- * `attachService(peerNode, network, createMeshRpcService(...))`.
141
- * @returns {(url: string, init?: {method?: string, headers?: object|Headers|[string,string][], body?: *}) => Promise<Response>}
142
- */
143
- export function createBrowserMeshFetch(meshRpcApi) {
144
- if (!meshRpcApi || typeof meshRpcApi.request !== 'function') {
145
- throw new Error(
146
- 'createBrowserMeshFetch: a mesh-rpc api with a request(podId, {...}) method is required ' +
147
- '(pass the .api returned by attachService(peerNode, network, createMeshRpcService(...)))',
148
- )
149
- }
150
-
151
- // Lazy, synchronous (see module doc comment) -- only resolved once a
152
- // caller actually builds a browserMeshFetch, and cached by require()'s
153
- // own module cache for every subsequent call.
154
- const require = createLazyRequire(import.meta.url)
155
- const { parseMeshRequest } = require('@johnhenry/browsermesh-discovery')
156
-
157
- /**
158
- * `browserMeshFetch()` itself -- deliberately NOT an `async function` (see
159
- * the module doc comment's "ERROR-VS-REJECT SEMANTICS" section for why: a
160
- * malformed URL must throw synchronously, matching real `fetch()`, which
161
- * an `async function` body can never do).
162
- *
163
- * @param {string} url
164
- * @param {{method?: string, headers?: object|Headers|[string,string][], body?: *}} [init]
165
- * @returns {Promise<Response>}
166
- */
167
- return function browserMeshFetch(url, init = {}) {
168
- const urlStr = typeof url === 'string' ? url : String(url)
169
- const parsed = parseMeshRequest(urlStr)
170
- if (!parsed) {
171
- throw new TypeError(
172
- `browserMeshFetch: '${urlStr}' is not a valid mesh:// or *.mesh.local URL`,
173
- )
174
- }
175
- return performMeshFetch(meshRpcApi, parsed, init || {})
12
+ export function createBrowserMeshFetch(meshRpcApi, { bodyMode = 'structured', maxBodyBytes = DEFAULT_MAX_BODY_BYTES } = {}) {
13
+ if (!meshRpcApi || typeof meshRpcApi.request !== 'function') throw new Error('createBrowserMeshFetch: a mesh-rpc api with a request(podId, {...}) method is required')
14
+ if (!['structured', 'http'].includes(bodyMode)) throw new TypeError('createBrowserMeshFetch: bodyMode must be structured or http')
15
+ if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes <= 0) throw new TypeError('createBrowserMeshFetch: maxBodyBytes must be a positive integer')
16
+ return function browserMeshFetch(input, init = {}) {
17
+ const isRequest = typeof Request !== 'undefined' && input instanceof Request
18
+ const url = isRequest ? input.url : String(input)
19
+ const parsed = parseMeshRequest(url)
20
+ if (!parsed) throw new TypeError(`browserMeshFetch: '${url}' is not a valid mesh:// or *.mesh.local URL`)
21
+ return performMeshFetch(meshRpcApi, parsed, input, init || {}, { isRequest, bodyMode, maxBodyBytes })
176
22
  }
177
23
  }
178
24
 
179
- // ---------------------------------------------------------------------------
180
- // Internals
181
- // ---------------------------------------------------------------------------
182
-
183
- /**
184
- * The actual async RPC round trip, once the URL is known to be valid. Any
185
- * rejection from `meshRpcApi.request()` (timeout, unreachable peer) is
186
- * intentionally left to propagate unmodified -- see module doc comment.
187
- *
188
- * @param {MeshRpcApi} meshRpcApi
189
- * @param {{podId: string, path: string}} parsed
190
- * @param {{method?: string, headers?: object|Headers|[string,string][], body?: *}} init
191
- * @returns {Promise<Response>}
192
- */
193
- async function performMeshFetch(meshRpcApi, { podId, path }, init) {
194
- const method = (init.method || 'GET').toUpperCase()
195
- const headers = normalizeHeaders(init.headers)
196
- const body = extractBody(init.body, method)
197
-
198
- const result = await meshRpcApi.request(podId, { method, path, headers, body })
199
- return buildResponse(result)
200
- }
201
-
202
- /**
203
- * Normalize `init.headers` (a `Headers` instance, a plain object, or an
204
- * array of `[key, value]` pairs -- the three shapes real `fetch()` accepts)
205
- * into a plain `{lowercaseKey: value}` object, the shape `mesh-rpc.mjs`'s
206
- * wire envelope expects. Mirrors `MeshFetchRouter.route()`'s own
207
- * `Headers`-or-plain-object handling.
208
- *
209
- * @param {object|Headers|[string,string][]|undefined} headersInit
210
- * @returns {object}
211
- */
212
- function normalizeHeaders(headersInit) {
213
- const headers = {}
214
- if (!headersInit) return headers
215
-
216
- if (typeof headersInit.forEach === 'function') {
217
- // Real `Headers` instance (or anything Headers-shaped).
218
- headersInit.forEach((v, k) => { headers[k.toLowerCase()] = v })
219
- } else if (Array.isArray(headersInit)) {
220
- for (const [k, v] of headersInit) headers[String(k).toLowerCase()] = v
221
- } else if (typeof headersInit === 'object') {
222
- for (const [k, v] of Object.entries(headersInit)) headers[k.toLowerCase()] = v
25
+ async function performMeshFetch(api, { podId, path }, input, init, { isRequest, bodyMode, maxBodyBytes }) {
26
+ let method, headers, body, signal
27
+ if (isRequest || bodyMode === 'http') {
28
+ // Native Request constructs correct multipart headers and BodyInit bytes.
29
+ const request = new Request(input, { ...init, duplex: 'half' })
30
+ method = request.method
31
+ headers = Object.fromEntries(request.headers)
32
+ signal = request.signal
33
+ if (signal.aborted) throw abortError(signal)
34
+ body = request.body ? await readBody(request.body, maxBodyBytes, signal) : undefined
35
+ } else {
36
+ method = (init.method || 'GET').toUpperCase()
37
+ headers = normalizeHeaders(init.headers)
38
+ signal = init.signal
39
+ if (signal?.aborted) throw abortError(signal)
40
+ body = init.body
41
+ if (body === null || body === undefined || method === 'GET' || method === 'HEAD') body = undefined
42
+ else if (typeof body === 'string') { try { body = JSON.parse(body) } catch { /* existing structured-text convention */ } }
223
43
  }
224
- return headers
44
+ const result = await api.request(podId, { method, path, headers, body }, { signal })
45
+ return buildResponse(result, method)
225
46
  }
226
47
 
227
- /**
228
- * Extract/normalize `init.body` the way `MeshFetchRouter.route()` extracts a
229
- * body from a real `Request` (read as text, then try `JSON.parse` so a
230
- * JSON-string body arrives at the responder's `onRequest` handler already
231
- * parsed into a structured value) -- except here the body starts out as
232
- * whatever `init.body` already is, not raw `Request` bytes, so a
233
- * non-string body (already a plain object/array/etc, the common case for
234
- * application code calling `browserMeshFetch(url, { body: {...} })`) is
235
- * passed through unchanged.
236
- *
237
- * GET/HEAD requests never carry a body, matching real `fetch()` (which
238
- * throws if you pass a `body` with `method: 'GET'`) -- here it's simply
239
- * dropped rather than throwing, since a mesh-RPC request's `body` field is
240
- * optional/advisory rather than spec-enforced.
241
- *
242
- * @param {*} rawBody
243
- * @param {string} method
244
- * @returns {*}
245
- */
246
- function extractBody(rawBody, method) {
247
- if (rawBody === undefined || rawBody === null) return undefined
248
- if (method === 'GET' || method === 'HEAD') return undefined
249
-
250
- if (typeof rawBody === 'string') {
251
- try {
252
- return JSON.parse(rawBody)
253
- } catch {
254
- return rawBody // keep as plain string, matching MeshFetchRouter.route()
48
+ async function readBody(stream, limit, signal) {
49
+ const reader = stream.getReader(), parts = []
50
+ let size = 0
51
+ const onAbort = () => { reader.cancel(abortError(signal)).catch(() => {}) }
52
+ signal.addEventListener('abort', onAbort, { once: true })
53
+ try {
54
+ for (;;) {
55
+ if (signal.aborted) throw abortError(signal)
56
+ const { value, done } = await reader.read()
57
+ if (signal.aborted) throw abortError(signal)
58
+ if (done) break
59
+ if (!(value instanceof Uint8Array)) throw new TypeError('browserMeshFetch: body stream must contain bytes')
60
+ size += value.byteLength
61
+ if (size > limit) throw new RangeError('browserMeshFetch: body exceeds maxBodyBytes')
62
+ parts.push(value.slice())
255
63
  }
64
+ const body = new Uint8Array(size)
65
+ let offset = 0
66
+ for (const part of parts) { body.set(part, offset); offset += part.byteLength }
67
+ return body
68
+ } catch (error) {
69
+ // A producer may never finish its cancellation hook. Local rejection must
70
+ // not wait for cooperation from that producer.
71
+ reader.cancel(error).catch(() => {})
72
+ throw error
73
+ } finally {
74
+ signal.removeEventListener('abort', onAbort)
75
+ reader.releaseLock()
256
76
  }
257
- return rawBody
258
77
  }
259
78
 
260
- /**
261
- * Shape a `mesh-rpc` response (`{status, headers, body}`) into a real
262
- * `Response`, mirroring `MeshFetchRouter.route()`'s own conventions:
263
- * default status `200`, default `content-type: application/json` when no
264
- * headers were supplied, and JSON-stringify a non-string body.
265
- *
266
- * @param {{status?: number, headers?: object, body?: *}} result
267
- * @returns {Response}
268
- */
269
- function buildResponse(result) {
79
+ function normalizeHeaders(value) {
80
+ if (!value) return {}
81
+ return Object.fromEntries(new Headers(value))
82
+ }
83
+
84
+ function buildResponse(result, method) {
270
85
  const status = typeof result?.status === 'number' ? result.status : 200
271
- const headers = result?.headers && typeof result.headers === 'object' && Object.keys(result.headers).length > 0
272
- ? result.headers
273
- : { 'content-type': 'application/json' }
274
- const body = result && 'body' in result ? result.body : undefined
275
- const resBody = body === undefined
276
- ? null
277
- : typeof body === 'string' ? body : JSON.stringify(body)
278
- return new Response(resBody, { status, headers })
86
+ const body = result?.body
87
+ const binary = body instanceof ArrayBuffer || ArrayBuffer.isView(body)
88
+ const headers = result?.headers && Object.keys(result.headers).length
89
+ ? result.headers : { 'content-type': binary ? 'application/octet-stream' : 'application/json' }
90
+ const forbidden = method === 'HEAD' || [204, 205, 304].includes(status) || body === null || body === undefined
91
+ const bytes = ArrayBuffer.isView(body) ? new Uint8Array(body.buffer, body.byteOffset, body.byteLength) : body
92
+ return new Response(forbidden ? null : binary || typeof body === 'string' ? bytes : JSON.stringify(body), { status, headers })
279
93
  }
package/src/mesh-rpc.mjs CHANGED
@@ -1,300 +1,159 @@
1
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`.
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
- * 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.
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
- throw new Error('createMeshRpcService: onRequest must be a function if provided')
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 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)
36
+ let seq = 0, closed = false
37
+ const pending = new Map()
38
+ const incoming = new Map()
39
+ const incomingCounts = new Map()
40
+ const keyFor = (peer, id) => JSON.stringify([peer, id])
41
+ const send = (peer, message) => ctx.sendTo(peer, envelopeType, message)
42
+ function settle(id, error, result) {
43
+ const p = pending.get(id)
44
+ if (!p) return
45
+ pending.delete(id)
46
+ clearTimeout(p.timer)
47
+ p.signal?.removeEventListener('abort', p.onAbort)
48
+ if (error) p.reject(error)
49
+ else p.resolve(result)
50
+ }
51
+ function cancel(id, error) {
52
+ const p = pending.get(id)
53
+ if (!p) return
54
+ settle(id, error)
55
+ // Older responders ignore this new kind. The local promise still ends.
56
+ Promise.resolve().then(() => send(p.target, { kind: 'rpc-cancel', requestId: id })).catch(() => {})
57
+ }
58
+ async function handleRequest(from, msg) {
59
+ if (closed || !validId(msg.requestId)) return
60
+ const key = keyFor(from, msg.requestId)
61
+ if (incoming.has(key)) return
62
+ if (incoming.size >= maxIncoming || (incomingCounts.get(from) || 0) >= maxIncomingPerPeer) {
63
+ await send(from, { kind: 'rpc-response', requestId: msg.requestId, status: 429, body: { error: 'too many RPC requests' } })
64
+ return
188
65
  }
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
- }
66
+ let body
67
+ try { body = decodeBody(msg, maxBodyBytes) }
68
+ catch {
69
+ await send(from, { kind: 'rpc-response', requestId: msg.requestId, status: 400, body: { error: 'invalid or oversized RPC body' } })
70
+ return
222
71
  }
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
-
72
+ const controller = new AbortController()
73
+ const timer = setTimeout(() => controller.abort(new DOMException('RPC handler deadline exceeded', 'TimeoutError')), requestTimeoutMs)
74
+ timer.unref?.()
75
+ incoming.set(key, { controller, timer })
76
+ incomingCounts.set(from, (incomingCounts.get(from) || 0) + 1)
228
77
  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) })
78
+ let result
79
+ if (!onRequest) result = { status: 501, body: { error: 'no RPC handler registered' } }
80
+ else {
81
+ try {
82
+ const handled = await onRequest({ fromPubKey: from, method: msg.method, path: msg.path, headers: msg.headers, body, signal: controller.signal })
83
+ result = handled && typeof handled === 'object' ? handled : {}
84
+ } catch (error) {
85
+ if (controller.signal.aborted) return
86
+ log('mesh-rpc:handler-threw', { from, requestId: msg.requestId, error: error?.message || String(error) })
87
+ ctx.emit('mesh-rpc:handler-error', { from, method: msg.method, path: msg.path, error: error?.message || String(error) })
88
+ result = { status: 500, body: { error: error?.message || String(error) } }
89
+ }
90
+ }
91
+ if (closed || controller.signal.aborted) return
92
+ let status = Number.isInteger(result.status) ? result.status : 200
93
+ let encoded
94
+ try { encoded = encodeBody(result.body, maxBodyBytes) }
95
+ catch { encoded = { body: { error: 'invalid or oversized RPC response' } }; status = 500 }
96
+ await send(from, { kind: 'rpc-response', requestId: msg.requestId, status, headers: result.headers || {}, ...encoded })
97
+ ctx.emit('mesh-rpc:request-served', { from, method: msg.method, path: msg.path, status })
98
+ } finally {
99
+ clearTimeout(timer)
100
+ incoming.delete(key)
101
+ const count = (incomingCounts.get(from) || 1) - 1
102
+ if (count) incomingCounts.set(from, count)
103
+ else incomingCounts.delete(from)
233
104
  }
234
105
  }
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) => {
106
+ const unsubscribe = ctx.onIncomingData(envelopeType, (from, msg) => {
107
+ if (closed || !msg || !validId(msg.requestId)) return
108
+ if (msg.kind === 'rpc-request') {
109
+ handleRequest(from, msg).catch(error => log('mesh-rpc:response-send-failed', { to: from, error: error?.message || String(error) }))
110
+ } else if (msg.kind === 'rpc-cancel') {
111
+ const active = incoming.get(keyFor(from, msg.requestId))
112
+ if (active) { clearTimeout(active.timer); active.controller.abort(abortError()) }
113
+ } else if (msg.kind === 'rpc-response') {
114
+ const p = pending.get(msg.requestId)
115
+ // A request ID is correlation data, never proof of the responder.
116
+ if (!p || p.target !== from) return
117
+ try { settle(msg.requestId, null, { status: msg.status, headers: msg.headers || {}, body: decodeBody(msg, maxBodyBytes) }) }
118
+ catch (error) { settle(msg.requestId, error) }
119
+ }
120
+ })
121
+ function request(target, { method = 'GET', path = '/', headers = {}, body } = {}, { signal, timeoutMs = requestTimeoutMs } = {}) {
122
+ if (closed) return Promise.reject(new Error('mesh-rpc: service torn down'))
123
+ if (typeof target !== 'string' || !target || target.length > 512) return Promise.reject(new TypeError('mesh-rpc: target must identify one peer'))
124
+ if (signal?.aborted) return Promise.reject(abortError(signal.reason))
125
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) return Promise.reject(new TypeError('mesh-rpc: timeoutMs must be a positive integer'))
126
+ if (pending.size >= maxInflight) return Promise.reject(new Error('mesh-rpc: too many requests in flight'))
127
+ let encoded
128
+ try { encoded = encodeBody(body, maxBodyBytes) } catch (error) { return Promise.reject(error) }
129
+ const requestId = `${peerNode?.podId || 'local'}:${Date.now()}:${++seq}`
130
+ return new Promise((resolve, reject) => {
131
+ const onAbort = () => cancel(requestId, abortError(signal.reason))
261
132
  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 })
133
+ ctx.emit('mesh-rpc:request-timeout', { to: target, method, path })
134
+ cancel(requestId, new Error(`mesh-rpc: request ${method} ${path} to ${target} timed out after ${timeoutMs}ms`))
135
+ }, timeoutMs)
136
+ pending.set(requestId, { target, resolve, reject, signal, onAbort, timer })
137
+ signal?.addEventListener('abort', onAbort, { once: true })
138
+ // Return the promise before a slow send can time out or reject it.
139
+ Promise.resolve().then(() => {
140
+ if (!pending.has(requestId)) return
141
+ return send(target, { kind: 'rpc-request', requestId, method, path, headers, ...encoded })
142
+ }).catch(error => settle(requestId, error))
267
143
  })
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
144
  }
282
-
283
- const api = { request }
284
-
285
145
  return {
286
- api,
146
+ api: { request },
287
147
  teardown() {
148
+ if (closed) return
149
+ closed = true
288
150
  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()
151
+ for (const id of pending.keys()) settle(id, new Error('mesh-rpc: service torn down while a request was still in flight'))
152
+ for (const { controller, timer } of incoming.values()) { clearTimeout(timer); controller.abort(abortError()) }
294
153
  },
295
154
  }
296
155
  },
297
156
  }
298
157
  }
299
158
 
300
- export { DEFAULT_ENVELOPE_TYPE, DEFAULT_REQUEST_TIMEOUT_MS }
159
+ export { DEFAULT_ENVELOPE_TYPE, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_MAX_BODY_BYTES }
package/src/peer-node.mjs CHANGED
@@ -39,6 +39,11 @@ const DEFAULT_CONNECTION_ID = 'default'
39
39
  // PeerNode
40
40
  // ---------------------------------------------------------------------------
41
41
 
42
+ /** A syntactically valid named-channel name (see WebRTCPeerConnection#openChannel). */
43
+ function isChannelName(v) {
44
+ return typeof v === 'string' && /^[A-Za-z0-9._-]{1,64}$/.test(v);
45
+ }
46
+
42
47
  /**
43
48
  * Top-level orchestrator for a mesh peer. Manages the full lifecycle
44
49
  * from identity bootstrap through discovery, connection, and shutdown.
@@ -553,8 +558,10 @@ export class PeerNode {
553
558
  * @param {object} [opts]
554
559
  * @param {string} [opts.connectionId] - Target this specific connection's
555
560
  * session (issue #116) rather than "most recently created".
556
- * @param {'control'|'bulk'} [opts.channel] - Which of the transport's data
557
- * channels to send on. Omit (or pass `'control'`) for the ordered control
561
+ * @param {string} [opts.channel] - Which of the transport's data
562
+ * channels to send on. Besides 'control' and 'bulk' this may be the name of
563
+ * a channel opened with `transport.openChannel(name)` (#115); a name the
564
+ * session's transport has not opened throws a `TypeError`. Omit (or pass `'control'`) for the ordered control
558
565
  * lane; `'bulk'` selects the second, unordered `mesh-bulk` channel, so
559
566
  * large payloads (file/torrent chunks) cannot queue in front of control
560
567
  * traffic. Passed through as `transport.send(data, { channel })` only
@@ -570,8 +577,8 @@ export class PeerNode {
570
577
  */
571
578
  async sendTo(pubKey, data, { connectionId, channel } = {}) {
572
579
  this.#ensureRunning('sendTo');
573
- if (channel !== undefined && channel !== 'control' && channel !== 'bulk') {
574
- throw new TypeError(`PeerNode.sendTo: unknown channel ${JSON.stringify(channel)} (expected 'control' or 'bulk')`);
580
+ if (channel !== undefined && channel !== 'control' && channel !== 'bulk' && !isChannelName(channel)) {
581
+ throw new TypeError(`PeerNode.sendTo: unknown channel ${JSON.stringify(channel)} (expected 'control', 'bulk' or a named channel)`);
575
582
  }
576
583
  let session = null;
577
584
  for (const [, s] of this.#sessions) {
@@ -586,6 +593,13 @@ export class PeerNode {
586
593
  if (!session.transportInstance || typeof session.transportInstance.send !== 'function') {
587
594
  throw new Error(`PeerNode.sendTo: session for ${pubKey} has no transport.send`);
588
595
  }
596
+ if (channel !== undefined && channel !== 'control' && channel !== 'bulk') {
597
+ // A named channel (#115) must have been opened on this session's transport.
598
+ const open = session.transportInstance.channels;
599
+ if (!Array.isArray(open) || !open.includes(channel)) {
600
+ throw new TypeError(`PeerNode.sendTo: unknown channel ${JSON.stringify(channel)} for ${pubKey} (open it with transport.openChannel())`);
601
+ }
602
+ }
589
603
  return channel === undefined
590
604
  ? session.transportInstance.send(data)
591
605
  : session.transportInstance.send(data, { channel });
@@ -624,8 +638,8 @@ export class PeerNode {
624
638
  */
625
639
  async broadcast(data, { channel, exclude, concurrency = 8 } = {}) {
626
640
  this.#ensureRunning('broadcast');
627
- if (channel !== undefined && channel !== 'control' && channel !== 'bulk') {
628
- throw new TypeError(`PeerNode.broadcast: unknown channel ${JSON.stringify(channel)} (expected 'control' or 'bulk')`);
641
+ if (channel !== undefined && channel !== 'control' && channel !== 'bulk' && !isChannelName(channel)) {
642
+ throw new TypeError(`PeerNode.broadcast: unknown channel ${JSON.stringify(channel)} (expected 'control', 'bulk' or a named channel)`);
629
643
  }
630
644
  const skip = typeof exclude === 'function'
631
645
  ? exclude