@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.
Files changed (55) hide show
  1. package/README.md +298 -17
  2. package/package.json +13 -9
  3. package/src/apps.mjs +4 -4
  4. package/src/audit.mjs +2 -2
  5. package/src/chat.mjs +3 -3
  6. package/src/cloud-storage-backend.mjs +5 -7
  7. package/src/cloud-storage.mjs +5 -4
  8. package/src/compat.mjs +2 -2
  9. package/src/consensus.mjs +7 -7
  10. package/src/devtools.mjs +3 -3
  11. package/src/gpu.mjs +2 -2
  12. package/src/index.mjs +12 -0
  13. package/src/internal/channel-codec.mjs +179 -0
  14. package/src/internal/json-message.mjs +49 -0
  15. package/src/internal/relay-flow.mjs +178 -0
  16. package/src/internal/request-target.mjs +280 -0
  17. package/src/internal/rpc-body.mjs +33 -0
  18. package/src/marketplace-ui.mjs +1 -1
  19. package/src/mesh-agent-swarm.mjs +1 -1
  20. package/src/mesh-bootstrap.mjs +47 -1
  21. package/src/mesh-channel.mjs +716 -0
  22. package/src/mesh-fetch.mjs +77 -263
  23. package/src/mesh-hardening.mjs +8 -1
  24. package/src/mesh-relay-backend.mjs +116 -22
  25. package/src/mesh-relay-host.mjs +296 -55
  26. package/src/mesh-rpc.mjs +126 -265
  27. package/src/mesh-sync.mjs +1 -1
  28. package/src/orchestrator.mjs +54 -29
  29. package/src/payments.mjs +56 -14
  30. package/src/peer-agent-swarm.mjs +2 -2
  31. package/src/peer-agent.mjs +7 -7
  32. package/src/peer-compute.mjs +2 -2
  33. package/src/peer-encrypted-store.mjs +3 -3
  34. package/src/peer-escrow.mjs +2 -2
  35. package/src/peer-health.mjs +3 -3
  36. package/src/peer-node.mjs +8 -5
  37. package/src/peer-payments.mjs +2 -2
  38. package/src/peer-registry.mjs +45 -3
  39. package/src/peer-routing.mjs +158 -21
  40. package/src/peer-services.mjs +3 -3
  41. package/src/peer-timestamp.mjs +3 -3
  42. package/src/peer-torrent.mjs +112 -47
  43. package/src/peer-verification.mjs +3 -3
  44. package/src/pod-host-service.mjs +48 -7
  45. package/src/pod-placement.mjs +582 -0
  46. package/src/pod-supervisor.mjs +9 -30
  47. package/src/protocol-channel.mjs +327 -0
  48. package/src/resources.mjs +2 -2
  49. package/src/restart-policy.mjs +67 -0
  50. package/src/scheduler.mjs +3 -3
  51. package/src/serverless-proxy.mjs +58 -7
  52. package/src/silent-catch.mjs +22 -9
  53. package/src/tools.mjs +3 -3
  54. package/src/visualizations.mjs +2 -2
  55. package/src/wsh-negotiator.mjs +97 -0
@@ -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
  }
@@ -254,5 +254,12 @@ export async function createHardenedNegotiator({ negotiator, retryOptions, onLog
254
254
  return instrumentTransport(transport, transportMetrics)
255
255
  }
256
256
 
257
- return { negotiate, metrics, failovers, retries }
257
+ return {
258
+ negotiate,
259
+ metrics,
260
+ failovers,
261
+ retries,
262
+ /** The wrapped negotiator's `require` (see `MeshTransportNegotiator`), so PeerNode still fails closed. */
263
+ get required() { return negotiator.required ?? null },
264
+ }
258
265
  }
@@ -52,6 +52,7 @@
52
52
 
53
53
  import { createLazyRequire } from './internal/lazy-node-require.mjs'
54
54
  import { decodeWireData } from './internal/wire-envelope.mjs'
55
+ import { CreditReceiver, CreditSender, resolveFlowOptions } from './internal/relay-flow.mjs'
55
56
 
56
57
  /** Default `envelope.type` used to route relay payloads on the shared `onIncomingData()` bus. */
57
58
  const DEFAULT_ENVELOPE_TYPE = 'mesh-relay'
@@ -127,9 +128,12 @@ function resolveMeshRelayBackendClass() {
127
128
  /** @type {Map<string, {resolve: Function, reject: Function, service: string}>} connId -> pending connect */
128
129
  #pending = new Map()
129
130
 
130
- /** @type {Map<string, import('@johnhenry/browsermesh-netway').StreamSocket>} connId -> relay-side socket */
131
+ /** @type {Map<string, {socket: import('@johnhenry/browsermesh-netway').StreamSocket, tx: CreditSender, rx: CreditReceiver, closed: boolean}>} connId -> relay-side connection */
131
132
  #connections = new Map()
132
133
 
134
+ /** @type {Readonly<import('./internal/relay-flow.mjs').RELAY_FLOW_DEFAULTS>} */
135
+ #flow
136
+
133
137
  /** @type {(() => void)|null} */
134
138
  #unsubscribeIncoming = null
135
139
 
@@ -140,14 +144,19 @@ function resolveMeshRelayBackendClass() {
140
144
  * @param {string} [opts.envelopeType='mesh-relay']
141
145
  * @param {number} [opts.connectTimeoutMs=15000] - `0` disables the timeout.
142
146
  * @param {Function} [opts.onLog]
147
+ * @param {number} [opts.highWaterBytes=262144] - Receive window per connection; the host pauses at it.
148
+ * @param {number} [opts.lowWaterBytes=65536]
149
+ * @param {number} [opts.maxBufferedBytesPerConnection=1048576] - Hard cap on bytes received and not yet consumed.
150
+ * @param {number} [opts.maxFrameBytes=65536]
143
151
  */
144
- constructor({ node, relayPeerPubKey, envelopeType, connectTimeoutMs, onLog } = {}) {
152
+ constructor({ node, relayPeerPubKey, envelopeType, connectTimeoutMs, onLog, ...flow } = {}) {
145
153
  super()
146
154
  if (!node) throw new Error('node is required')
147
155
  if (!relayPeerPubKey || typeof relayPeerPubKey !== 'string') {
148
156
  throw new Error('relayPeerPubKey is required')
149
157
  }
150
158
 
159
+ this.#flow = resolveFlowOptions(flow)
151
160
  this.#node = node
152
161
  this.#relayPeerPubKey = relayPeerPubKey
153
162
  this.#envelopeType = envelopeType || DEFAULT_ENVELOPE_TYPE
@@ -197,7 +206,7 @@ function resolveMeshRelayBackendClass() {
197
206
  this.#pending.set(connId, { resolve, reject, service: host })
198
207
  })
199
208
 
200
- await this.#send({ op: 'connect', connId, service: host })
209
+ await this.#send({ op: 'connect', connId, service: host, window: this.#flow.highWaterBytes })
201
210
 
202
211
  if (!this.#connectTimeoutMs) return pending
203
212
 
@@ -234,8 +243,28 @@ function resolveMeshRelayBackendClass() {
234
243
  this.#pending.delete(connId)
235
244
 
236
245
  const [userSocket, relaySocket] = StreamSocket.createPair()
237
- this.#connections.set(connId, relaySocket)
238
- this.#pumpToRemote(connId, relaySocket)
246
+ // The host advertises a window only if it understands credit; an older
247
+ // host is sent no credit frames and is held to the buffer bound only.
248
+ const creditAware = Number.isInteger(data.window) && data.window > 0
249
+ const conn = {
250
+ socket: relaySocket,
251
+ closed: false,
252
+ tx: new CreditSender({
253
+ window: creditAware ? Math.min(data.window, this.#flow.maxBufferedBytesPerConnection) : 0,
254
+ lowWater: this.#flow.lowWaterBytes,
255
+ }),
256
+ rx: new CreditReceiver({
257
+ window: this.#flow.highWaterBytes,
258
+ lowWater: this.#flow.lowWaterBytes,
259
+ maxBuffered: this.#flow.maxBufferedBytesPerConnection,
260
+ creditAware,
261
+ grant: (bytes) => {
262
+ if (!conn.closed) this.#send({ op: 'credit', connId, bytes }).catch(() => {})
263
+ },
264
+ }),
265
+ }
266
+ this.#connections.set(connId, conn)
267
+ this.#pumpToRemote(connId, conn)
239
268
  pending.resolve(userSocket)
240
269
  return
241
270
  }
@@ -252,23 +281,85 @@ function resolveMeshRelayBackendClass() {
252
281
 
253
282
  // 'data' / 'close' only act on connIds this backend itself originated
254
283
  // and that are still open -- unrecognized connIds are ignored.
255
- const relaySocket = this.#connections.get(connId)
256
- if (!relaySocket) return
284
+ const conn = this.#connections.get(connId)
285
+ if (!conn) return
257
286
 
258
287
  if (op === 'data') {
259
288
  if (typeof data.data !== 'string') return
289
+ const approx = Math.floor((data.data.length * 3) / 4)
290
+ if (approx > this.#flow.maxBufferedBytesPerConnection
291
+ || (conn.rx.creditAware && approx > this.#flow.maxFrameBytes + 3)) {
292
+ this.#closeConnection(connId, conn, { notifyHost: true, reason: 'buffer limit exceeded' })
293
+ return
294
+ }
295
+ const bytes = fromBase64(data.data)
296
+ const verdict = conn.rx.receive(bytes.length)
297
+ if (verdict !== 'ok') {
298
+ this.#closeConnection(connId, conn, {
299
+ notifyHost: true,
300
+ reason: verdict === 'violation' ? 'flow control violation' : 'buffer limit exceeded',
301
+ })
302
+ return
303
+ }
260
304
  try {
261
- await relaySocket.write(fromBase64(data.data))
305
+ await conn.socket.write(bytes)
262
306
  } catch (err) {
263
- this.#onLog('mesh-relay-backend:data:write-failed', { connId, error: err?.message || String(err) })
307
+ if (!conn.closed) this.#onLog('mesh-relay-backend:data:write-failed', { connId, error: err?.message || String(err) })
308
+ } finally {
309
+ conn.rx.consumed(bytes.length)
310
+ }
311
+ return
312
+ }
313
+
314
+ if (op === 'credit') {
315
+ if (conn.tx.enabled && !conn.tx.credit(data.bytes)) {
316
+ this.#closeConnection(connId, conn, { notifyHost: true, reason: 'flow control violation' })
264
317
  }
265
318
  return
266
319
  }
267
320
 
268
321
  if (op === 'close') {
269
- this.#connections.delete(connId)
270
- try { await relaySocket.close() } catch { /* already closed */ }
322
+ await this.#closeConnection(connId, conn, {
323
+ notifyHost: false,
324
+ reason: typeof data.reason === 'string' ? data.reason.slice(0, 200) : 'closed by host',
325
+ })
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Close a relayed connection: both endpoints of the local socket pair see
331
+ * end of stream and `closeReason`.
332
+ *
333
+ * @param {string} connId
334
+ * @param {{socket: object, tx: CreditSender, closed: boolean}} conn
335
+ * @param {{notifyHost: boolean, reason: string}} opts
336
+ */
337
+ async #closeConnection(connId, conn, { notifyHost, reason }) {
338
+ if (conn.closed) return
339
+ conn.closed = true
340
+ this.#connections.delete(connId)
341
+ conn.tx.close()
342
+ try { await conn.socket.close(reason) } catch { /* already closed */ }
343
+ if (notifyHost) await this.#send({ op: 'close', connId, reason }).catch(() => {})
344
+ }
345
+
346
+ /**
347
+ * Counters for bytes held for relayed connections.
348
+ * `bufferedBytes`: received and not yet accepted by the user-facing socket,
349
+ * plus bytes the user wrote that the relay has not yet read (bytes held in
350
+ * the user-facing socket's own receive window are not counted);
351
+ * `inFlightBytes`: sent to the host and not yet credited back.
352
+ *
353
+ * @returns {{ connections: number, bufferedBytes: number, inFlightBytes: number }}
354
+ */
355
+ stats() {
356
+ let bufferedBytes = 0
357
+ let inFlightBytes = 0
358
+ for (const conn of this.#connections.values()) {
359
+ bufferedBytes += conn.rx.outstanding + (conn.socket.readableLength ?? 0)
360
+ inFlightBytes += conn.tx.inFlight
271
361
  }
362
+ return { connections: this.#connections.size, bufferedBytes, inFlightBytes }
272
363
  }
273
364
 
274
365
  /**
@@ -279,20 +370,24 @@ function resolveMeshRelayBackendClass() {
279
370
  * @param {string} connId
280
371
  * @param {import('@johnhenry/browsermesh-netway').StreamSocket} relaySocket
281
372
  */
282
- #pumpToRemote(connId, relaySocket) {
373
+ #pumpToRemote(connId, conn) {
283
374
  (async () => {
284
375
  try {
285
- while (true) {
286
- const chunk = await relaySocket.read()
376
+ outer: while (!conn.closed) {
377
+ const chunk = await conn.socket.read()
287
378
  if (chunk === null) break
288
- await this.#send({ op: 'data', connId, data: toBase64(chunk) })
379
+ for (let off = 0; off < chunk.length;) {
380
+ const want = Math.min(chunk.length - off, this.#flow.maxFrameBytes)
381
+ const n = await conn.tx.reserve(want)
382
+ if (n === 0 || conn.closed) break outer
383
+ await this.#send({ op: 'data', connId, data: toBase64(chunk.subarray(off, off + n)) })
384
+ off += n
385
+ }
289
386
  }
290
387
  } catch (err) {
291
- this.#onLog('mesh-relay-backend:pump:error', { connId, error: err?.message || String(err) })
292
- }
293
- if (this.#connections.delete(connId)) {
294
- await this.#send({ op: 'close', connId }).catch(() => {})
388
+ if (!conn.closed) this.#onLog('mesh-relay-backend:pump:error', { connId, error: err?.message || String(err) })
295
389
  }
390
+ await this.#closeConnection(connId, conn, { notifyHost: true, reason: 'closed by client' })
296
391
  })()
297
392
  }
298
393
 
@@ -316,9 +411,8 @@ function resolveMeshRelayBackendClass() {
316
411
  this.#unsubscribeIncoming()
317
412
  this.#unsubscribeIncoming = null
318
413
  }
319
- for (const [connId, socket] of [...this.#connections]) {
320
- this.#connections.delete(connId)
321
- try { await socket.close() } catch { /* already closed */ }
414
+ for (const [connId, conn] of [...this.#connections]) {
415
+ await this.#closeConnection(connId, conn, { notifyHost: false, reason: 'relay backend closed' })
322
416
  }
323
417
  for (const [connId, pending] of [...this.#pending]) {
324
418
  this.#pending.delete(connId)