@johnhenry/browsermesh-apps 0.16.0 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +268 -17
- package/package.json +13 -9
- package/src/apps.mjs +4 -4
- package/src/audit.mjs +2 -2
- package/src/chat.mjs +3 -3
- package/src/cloud-storage-backend.mjs +5 -7
- package/src/cloud-storage.mjs +5 -4
- package/src/compat.mjs +2 -2
- package/src/consensus.mjs +7 -7
- package/src/devtools.mjs +3 -3
- package/src/gpu.mjs +2 -2
- package/src/index.mjs +12 -0
- package/src/internal/channel-codec.mjs +179 -0
- package/src/internal/json-message.mjs +49 -0
- package/src/internal/relay-flow.mjs +178 -0
- package/src/internal/request-target.mjs +280 -0
- package/src/marketplace-ui.mjs +1 -1
- package/src/mesh-agent-swarm.mjs +1 -1
- package/src/mesh-bootstrap.mjs +47 -1
- package/src/mesh-channel.mjs +716 -0
- package/src/mesh-hardening.mjs +8 -1
- package/src/mesh-relay-backend.mjs +116 -22
- package/src/mesh-relay-host.mjs +296 -55
- package/src/mesh-rpc.mjs +3 -1
- package/src/mesh-sync.mjs +1 -1
- package/src/orchestrator.mjs +54 -29
- package/src/payments.mjs +56 -14
- package/src/peer-agent-swarm.mjs +2 -2
- package/src/peer-agent.mjs +7 -7
- package/src/peer-compute.mjs +2 -2
- package/src/peer-encrypted-store.mjs +3 -3
- package/src/peer-escrow.mjs +2 -2
- package/src/peer-health.mjs +3 -3
- package/src/peer-node.mjs +8 -5
- package/src/peer-payments.mjs +2 -2
- package/src/peer-registry.mjs +45 -3
- package/src/peer-routing.mjs +158 -21
- package/src/peer-services.mjs +3 -3
- package/src/peer-timestamp.mjs +3 -3
- package/src/peer-torrent.mjs +112 -47
- package/src/peer-verification.mjs +3 -3
- package/src/pod-host-service.mjs +48 -7
- package/src/pod-placement.mjs +582 -0
- package/src/pod-supervisor.mjs +9 -30
- package/src/protocol-channel.mjs +327 -0
- package/src/resources.mjs +2 -2
- package/src/restart-policy.mjs +67 -0
- package/src/scheduler.mjs +3 -3
- package/src/serverless-proxy.mjs +58 -7
- package/src/silent-catch.mjs +22 -9
- package/src/tools.mjs +3 -3
- package/src/visualizations.mjs +2 -2
- package/src/wsh-negotiator.mjs +97 -0
package/src/mesh-relay-host.mjs
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
* on `browsermesh-netway`'s `GatewayBackend` connect/data/close/multiplex
|
|
18
18
|
* shape, carried over `PeerNode.sendTo()`/`onIncomingData()` (JSON envelopes,
|
|
19
19
|
* base64-encoded byte payloads) instead of wsh's binary control protocol --
|
|
20
|
-
* no new dependency
|
|
20
|
+
* no new dependency.
|
|
21
21
|
*
|
|
22
22
|
* `MeshRelayHost` never dials out over the mesh itself; it only responds to
|
|
23
23
|
* inbound `mesh-relay` envelopes. `exposeService()`/`hideService()` is a
|
|
@@ -28,13 +28,31 @@
|
|
|
28
28
|
* Authorization: each inbound `connect` is checked via
|
|
29
29
|
* `registry.checkAccess(fromPubKey, 'mesh-relay:' + service, 'connect')` --
|
|
30
30
|
* `PeerRegistry`'s existing `grantCapabilities()`/`revokeCapabilities()`/
|
|
31
|
-
* `checkAccess()
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
31
|
+
* `checkAccess()`. This composes a 3-segment `namespace:resource:action`
|
|
32
|
+
* scope (`mesh-relay:<service>:connect`) that the real `MeshACL`/
|
|
33
|
+
* `matchScope()` grammar already parses cleanly, wildcards included (e.g.
|
|
34
|
+
* `mesh-relay:*:connect`, `mesh-relay:s3-local:*`).
|
|
35
|
+
*
|
|
36
|
+
* Lifetime: an accepted connection lasts only as long as the permission that
|
|
37
|
+
* allowed it. The host re-checks every open connection when the registry
|
|
38
|
+
* announces an access change (`registry.onAccessChange()`), when
|
|
39
|
+
* `recheck()` is called, and every `recheckIntervalMs` (so expiry is
|
|
40
|
+
* noticed); never per packet. A connection is also closed when its service
|
|
41
|
+
* is hidden or the host is detached, and a connect that finishes after any of
|
|
42
|
+
* those is not acknowledged. A closed connection is closed in both
|
|
43
|
+
* directions, with a reason sent to the peer, and its resources are freed.
|
|
44
|
+
*
|
|
45
|
+
* Flow control: see `internal/relay-flow.mjs`. Each side advertises a window
|
|
46
|
+
* in `connect`/`ok`; the sender stops reading its local socket when the
|
|
47
|
+
* window is used and resumes when credit (`credit` frames) brings it under
|
|
48
|
+
* the low-water mark. Received bytes that are not yet consumed are bounded per
|
|
49
|
+
* connection and per peer; exceeding a bound closes the connection with a
|
|
50
|
+
* reason. A peer that advertises no window (an older version) is sent no
|
|
51
|
+
* credit frames and is held to the same bounds.
|
|
35
52
|
*
|
|
36
53
|
* Connections are keyed by `(fromPubKey, connId)` so concurrent peers can't
|
|
37
|
-
* collide or spoof-close each other's sessions
|
|
54
|
+
* collide or spoof-close each other's sessions; `fromPubKey` is the key of the
|
|
55
|
+
* session the envelope arrived on.
|
|
38
56
|
*
|
|
39
57
|
* Kernel involvement: explicitly none -- this is a peer-relationship
|
|
40
58
|
* decision ("Peer A trusts Peer B to relay to this service"), orthogonal to
|
|
@@ -45,6 +63,7 @@
|
|
|
45
63
|
|
|
46
64
|
/** Default `envelope.type` used to route relay payloads on the shared `onIncomingData()` bus. */
|
|
47
65
|
import { decodeWireData } from './internal/wire-envelope.mjs'
|
|
66
|
+
import { CreditReceiver, CreditSender, RELAY_FLOW_DEFAULTS, resolveFlowOptions } from './internal/relay-flow.mjs'
|
|
48
67
|
|
|
49
68
|
const DEFAULT_ENVELOPE_TYPE = 'mesh-relay'
|
|
50
69
|
|
|
@@ -59,7 +78,9 @@ function toBase64(bytes) {
|
|
|
59
78
|
if (typeof Buffer !== 'undefined') {
|
|
60
79
|
return Buffer.from(bytes).toString('base64')
|
|
61
80
|
}
|
|
62
|
-
|
|
81
|
+
let bin = ''
|
|
82
|
+
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i])
|
|
83
|
+
return btoa(bin)
|
|
63
84
|
}
|
|
64
85
|
|
|
65
86
|
/** @param {string} str @returns {Uint8Array} */
|
|
@@ -97,16 +118,32 @@ export class MeshRelayHost {
|
|
|
97
118
|
/** @type {Function} */
|
|
98
119
|
#onLog
|
|
99
120
|
|
|
121
|
+
/** @type {Readonly<typeof RELAY_FLOW_DEFAULTS>} */
|
|
122
|
+
#flow
|
|
123
|
+
|
|
100
124
|
/** @type {Map<string, string>} service name -> target address (e.g. `'mem://localhost:8080'`) */
|
|
101
125
|
#services = new Map()
|
|
102
126
|
|
|
103
|
-
/** @type {Map<string,
|
|
104
|
-
* key: `${fromPubKey}::${connId}` */
|
|
127
|
+
/** @type {Map<string, object>} key: `${fromPubKey}::${connId}` */
|
|
105
128
|
#connections = new Map()
|
|
106
129
|
|
|
130
|
+
/** Connects that are being opened, per peer (they count toward the per-peer limit). @type {Map<string, number>} */
|
|
131
|
+
#opening = new Map()
|
|
132
|
+
|
|
133
|
+
/** Bytes received and not yet consumed, per peer. @type {Map<string, number>} */
|
|
134
|
+
#peerBuffered = new Map()
|
|
135
|
+
|
|
107
136
|
/** @type {(() => void)|null} */
|
|
108
137
|
#unsubscribeIncoming = null
|
|
109
138
|
|
|
139
|
+
/** @type {(() => void)|null} */
|
|
140
|
+
#unsubscribeAccess = null
|
|
141
|
+
|
|
142
|
+
/** @type {ReturnType<typeof setInterval>|null} */
|
|
143
|
+
#recheckTimer = null
|
|
144
|
+
|
|
145
|
+
#detached = false
|
|
146
|
+
|
|
110
147
|
/**
|
|
111
148
|
* @param {object} opts
|
|
112
149
|
* @param {import('./peer-node.mjs').PeerNode} opts.node
|
|
@@ -116,12 +153,20 @@ export class MeshRelayHost {
|
|
|
116
153
|
* @param {import('./peer-registry.mjs').PeerRegistry} opts.registry
|
|
117
154
|
* @param {string} [opts.envelopeType='mesh-relay']
|
|
118
155
|
* @param {Function} [opts.onLog]
|
|
156
|
+
* @param {number} [opts.highWaterBytes=262144] - Receive window per connection; senders pause at it.
|
|
157
|
+
* @param {number} [opts.lowWaterBytes=65536] - Paused senders resume once this far back under it.
|
|
158
|
+
* @param {number} [opts.maxBufferedBytesPerConnection=1048576] - Hard cap on bytes received and not yet consumed, per connection.
|
|
159
|
+
* @param {number} [opts.maxBufferedBytesPerPeer=4194304] - The same, summed over one peer's connections.
|
|
160
|
+
* @param {number} [opts.maxConnectionsPerPeer=16]
|
|
161
|
+
* @param {number} [opts.maxFrameBytes=65536] - Largest data frame, before base64.
|
|
162
|
+
* @param {number} [opts.recheckIntervalMs=30000] - How often open connections are re-checked; 0 disables.
|
|
119
163
|
*/
|
|
120
|
-
constructor({ node, network, registry, envelopeType, onLog } = {}) {
|
|
164
|
+
constructor({ node, network, registry, envelopeType, onLog, ...flow } = {}) {
|
|
121
165
|
if (!node) throw new Error('node is required')
|
|
122
166
|
if (!network) throw new Error('network is required')
|
|
123
167
|
if (!registry) throw new Error('registry is required')
|
|
124
168
|
|
|
169
|
+
this.#flow = resolveFlowOptions(flow)
|
|
125
170
|
this.#node = node
|
|
126
171
|
this.#network = network
|
|
127
172
|
this.#registry = registry
|
|
@@ -133,6 +178,16 @@ export class MeshRelayHost {
|
|
|
133
178
|
this.#onLog('mesh-relay-host:handle-incoming-error', { error: err?.message || String(err) })
|
|
134
179
|
})
|
|
135
180
|
})
|
|
181
|
+
|
|
182
|
+
if (typeof registry.onAccessChange === 'function') {
|
|
183
|
+
this.#unsubscribeAccess = registry.onAccessChange(({ pubKey } = {}) => {
|
|
184
|
+
this.#recheckSync(pubKey)
|
|
185
|
+
})
|
|
186
|
+
}
|
|
187
|
+
if (this.#flow.recheckIntervalMs > 0) {
|
|
188
|
+
this.#recheckTimer = setInterval(() => this.#recheckSync(), this.#flow.recheckIntervalMs)
|
|
189
|
+
this.#recheckTimer.unref?.()
|
|
190
|
+
}
|
|
136
191
|
}
|
|
137
192
|
|
|
138
193
|
/** The `envelope.type` this host routes on the shared dispatch bus. */
|
|
@@ -164,15 +219,21 @@ export class MeshRelayHost {
|
|
|
164
219
|
}
|
|
165
220
|
|
|
166
221
|
/**
|
|
167
|
-
* Stop exposing a previously-exposed service.
|
|
168
|
-
*
|
|
222
|
+
* Stop exposing a previously-exposed service. New `connect` attempts are
|
|
223
|
+
* refused and every open connection to it is closed (reason
|
|
224
|
+
* `service hidden`).
|
|
169
225
|
*
|
|
170
226
|
* @param {string} name
|
|
171
227
|
* @returns {boolean} true if the service was exposed
|
|
172
228
|
*/
|
|
173
229
|
hideService(name) {
|
|
174
230
|
const had = this.#services.delete(name)
|
|
175
|
-
if (had)
|
|
231
|
+
if (had) {
|
|
232
|
+
this.#onLog('mesh-relay-host:service:hidden', { name })
|
|
233
|
+
for (const [key, conn] of [...this.#connections]) {
|
|
234
|
+
if (conn.service === name) this.#closeConnection(key, conn, { notifyPeer: true, reason: 'service hidden' })
|
|
235
|
+
}
|
|
236
|
+
}
|
|
176
237
|
return had
|
|
177
238
|
}
|
|
178
239
|
|
|
@@ -181,6 +242,77 @@ export class MeshRelayHost {
|
|
|
181
242
|
return [...this.#services.keys()]
|
|
182
243
|
}
|
|
183
244
|
|
|
245
|
+
// -----------------------------------------------------------------------
|
|
246
|
+
// Re-checking access
|
|
247
|
+
// -----------------------------------------------------------------------
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Check the access of every open connection (of one peer, or all) again and
|
|
251
|
+
* close those no longer allowed. Called by the registry's access-change
|
|
252
|
+
* event and by the interval; call it yourself after changing the ACL by a
|
|
253
|
+
* path the registry does not see.
|
|
254
|
+
*
|
|
255
|
+
* @param {string} [pubKey]
|
|
256
|
+
* @returns {Promise<void>}
|
|
257
|
+
*/
|
|
258
|
+
async recheck(pubKey) {
|
|
259
|
+
this.#recheckSync(pubKey)
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** @param {string} [pubKey] */
|
|
263
|
+
#recheckSync(pubKey) {
|
|
264
|
+
if (this.#detached) return
|
|
265
|
+
for (const [key, conn] of [...this.#connections]) {
|
|
266
|
+
if (pubKey !== undefined && conn.fromPubKey !== pubKey) continue
|
|
267
|
+
if (!this.#allowed(conn.fromPubKey, conn.service)) {
|
|
268
|
+
this.#onLog('mesh-relay-host:connection:revoked', { fromPubKey: conn.fromPubKey, connId: conn.connId, service: conn.service })
|
|
269
|
+
this.#closeConnection(key, conn, { notifyPeer: true, reason: 'access revoked' })
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** @param {string} fromPubKey @param {string} service @returns {boolean} */
|
|
275
|
+
#allowed(fromPubKey, service) {
|
|
276
|
+
try {
|
|
277
|
+
return this.#registry.checkAccess(fromPubKey, `mesh-relay:${service}`, 'connect')?.allowed === true
|
|
278
|
+
} catch {
|
|
279
|
+
return false
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// -----------------------------------------------------------------------
|
|
284
|
+
// Counters
|
|
285
|
+
// -----------------------------------------------------------------------
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Counters for what is held in memory on behalf of peers.
|
|
289
|
+
*
|
|
290
|
+
* `bufferedBytes` is bytes received from peers and not yet accepted by the
|
|
291
|
+
* service socket plus bytes the service wrote that the relay has not yet read;
|
|
292
|
+
* bytes the service socket holds in its own receive window (at most
|
|
293
|
+
* `windowBytes` per connection, 256 KiB by default) are not counted.
|
|
294
|
+
* `inFlightBytes` is bytes sent to peers and not yet credited back.
|
|
295
|
+
*
|
|
296
|
+
* @returns {{ connections: number, bufferedBytes: number, inFlightBytes: number,
|
|
297
|
+
* peers: Record<string, { connections: number, bufferedBytes: number }> }}
|
|
298
|
+
*/
|
|
299
|
+
stats() {
|
|
300
|
+
let bufferedBytes = 0
|
|
301
|
+
let inFlightBytes = 0
|
|
302
|
+
/** @type {Record<string, { connections: number, bufferedBytes: number }>} */
|
|
303
|
+
const peers = {}
|
|
304
|
+
for (const conn of this.#connections.values()) {
|
|
305
|
+
const queued = typeof conn.socket.readableLength === 'number' ? conn.socket.readableLength : 0
|
|
306
|
+
const held = conn.rx.outstanding + queued
|
|
307
|
+
bufferedBytes += held
|
|
308
|
+
inFlightBytes += conn.tx.inFlight
|
|
309
|
+
const p = (peers[conn.fromPubKey] ??= { connections: 0, bufferedBytes: 0 })
|
|
310
|
+
p.connections++
|
|
311
|
+
p.bufferedBytes += held
|
|
312
|
+
}
|
|
313
|
+
return { connections: this.#connections.size, bufferedBytes, inFlightBytes, peers }
|
|
314
|
+
}
|
|
315
|
+
|
|
184
316
|
// -----------------------------------------------------------------------
|
|
185
317
|
// Inbound envelope handling
|
|
186
318
|
// -----------------------------------------------------------------------
|
|
@@ -195,28 +327,33 @@ export class MeshRelayHost {
|
|
|
195
327
|
* @param {*} data
|
|
196
328
|
*/
|
|
197
329
|
async #handleIncoming(fromPubKey, data) {
|
|
330
|
+
if (this.#detached) return
|
|
198
331
|
data = decodeWireData(data)
|
|
199
332
|
if (!data || typeof data !== 'object' || data.type !== this.#envelopeType) return
|
|
200
333
|
const { op, connId } = data
|
|
201
334
|
if (!connId || typeof connId !== 'string') return
|
|
202
335
|
|
|
203
336
|
if (op === 'connect') {
|
|
204
|
-
await this.#handleConnect(fromPubKey, connId, data.service)
|
|
337
|
+
await this.#handleConnect(fromPubKey, connId, data.service, data.window)
|
|
205
338
|
return
|
|
206
339
|
}
|
|
207
340
|
|
|
208
|
-
// 'data' / 'close' only act on connections this host itself
|
|
209
|
-
// for this exact (fromPubKey, connId) pair -- unknown/foreign
|
|
210
|
-
// are silently ignored rather than acted on, so a peer can't
|
|
211
|
-
// or inject data into another peer's session.
|
|
341
|
+
// 'data' / 'credit' / 'close' only act on connections this host itself
|
|
342
|
+
// accepted for this exact (fromPubKey, connId) pair -- unknown/foreign
|
|
343
|
+
// connIds are silently ignored rather than acted on, so a peer can't
|
|
344
|
+
// spoof-close or inject data into another peer's session.
|
|
212
345
|
const key = this.#key(fromPubKey, connId)
|
|
213
346
|
const conn = this.#connections.get(key)
|
|
214
347
|
if (!conn) return
|
|
215
348
|
|
|
216
349
|
if (op === 'data') {
|
|
217
|
-
await this.#handleData(conn, data.data)
|
|
350
|
+
await this.#handleData(key, conn, data.data)
|
|
351
|
+
} else if (op === 'credit') {
|
|
352
|
+
if (conn.tx.enabled && !conn.tx.credit(data.bytes)) {
|
|
353
|
+
this.#closeConnection(key, conn, { notifyPeer: true, reason: 'flow control violation' })
|
|
354
|
+
}
|
|
218
355
|
} else if (op === 'close') {
|
|
219
|
-
await this.#closeConnection(key, conn, { notifyPeer: false })
|
|
356
|
+
await this.#closeConnection(key, conn, { notifyPeer: false, reason: 'closed by peer' })
|
|
220
357
|
}
|
|
221
358
|
}
|
|
222
359
|
|
|
@@ -224,15 +361,21 @@ export class MeshRelayHost {
|
|
|
224
361
|
* @param {string} fromPubKey
|
|
225
362
|
* @param {string} connId
|
|
226
363
|
* @param {*} service
|
|
364
|
+
* @param {*} peerWindow - the window the peer advertised, if any
|
|
227
365
|
*/
|
|
228
|
-
async #handleConnect(fromPubKey, connId, service) {
|
|
366
|
+
async #handleConnect(fromPubKey, connId, service, peerWindow) {
|
|
229
367
|
if (!service || typeof service !== 'string') {
|
|
230
368
|
await this.#refuse(fromPubKey, connId, 'invalid service')
|
|
231
369
|
return
|
|
232
370
|
}
|
|
233
371
|
|
|
234
|
-
const
|
|
235
|
-
if (
|
|
372
|
+
const key = this.#key(fromPubKey, connId)
|
|
373
|
+
if (this.#connections.has(key)) {
|
|
374
|
+
await this.#refuse(fromPubKey, connId, 'duplicate connection id')
|
|
375
|
+
return
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
if (!this.#allowed(fromPubKey, service)) {
|
|
236
379
|
this.#onLog('mesh-relay-host:connect:denied', { fromPubKey, service, connId })
|
|
237
380
|
await this.#refuse(fromPubKey, connId, 'access denied')
|
|
238
381
|
return
|
|
@@ -247,6 +390,15 @@ export class MeshRelayHost {
|
|
|
247
390
|
return
|
|
248
391
|
}
|
|
249
392
|
|
|
393
|
+
const open = [...this.#connections.values()].filter((c) => c.fromPubKey === fromPubKey).length
|
|
394
|
+
+ (this.#opening.get(fromPubKey) ?? 0)
|
|
395
|
+
if (open >= this.#flow.maxConnectionsPerPeer) {
|
|
396
|
+
this.#onLog('mesh-relay-host:connect:too-many', { fromPubKey, service, connId })
|
|
397
|
+
await this.#refuse(fromPubKey, connId, 'too many connections')
|
|
398
|
+
return
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
this.#opening.set(fromPubKey, (this.#opening.get(fromPubKey) ?? 0) + 1)
|
|
250
402
|
let socket
|
|
251
403
|
try {
|
|
252
404
|
socket = await this.#network.connect(targetAddress)
|
|
@@ -256,72 +408,152 @@ export class MeshRelayHost {
|
|
|
256
408
|
})
|
|
257
409
|
await this.#refuse(fromPubKey, connId, 'connect failed')
|
|
258
410
|
return
|
|
411
|
+
} finally {
|
|
412
|
+
const left = (this.#opening.get(fromPubKey) ?? 1) - 1
|
|
413
|
+
if (left > 0) this.#opening.set(fromPubKey, left)
|
|
414
|
+
else this.#opening.delete(fromPubKey)
|
|
259
415
|
}
|
|
260
416
|
|
|
261
|
-
|
|
262
|
-
|
|
417
|
+
// Whatever happened while the connect was in flight decides it: a host
|
|
418
|
+
// that was detached, a service that was hidden or re-pointed, or a grant
|
|
419
|
+
// that was revoked must not get a live connection.
|
|
420
|
+
if (this.#detached) {
|
|
421
|
+
try { await socket.close('service detached') } catch { /* already closed */ }
|
|
422
|
+
return
|
|
423
|
+
}
|
|
424
|
+
if (this.#services.get(service) !== targetAddress || !this.#allowed(fromPubKey, service)) {
|
|
425
|
+
try { await socket.close('access revoked') } catch { /* already closed */ }
|
|
426
|
+
await this.#refuse(fromPubKey, connId, 'access denied')
|
|
427
|
+
return
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const creditAware = Number.isInteger(peerWindow) && peerWindow > 0
|
|
431
|
+
const conn = {
|
|
432
|
+
socket, fromPubKey, connId, service, closed: false,
|
|
433
|
+
tx: new CreditSender({
|
|
434
|
+
window: creditAware ? Math.min(peerWindow, this.#flow.maxBufferedBytesPerConnection) : 0,
|
|
435
|
+
lowWater: this.#flow.lowWaterBytes,
|
|
436
|
+
}),
|
|
437
|
+
rx: new CreditReceiver({
|
|
438
|
+
window: this.#flow.highWaterBytes,
|
|
439
|
+
lowWater: this.#flow.lowWaterBytes,
|
|
440
|
+
maxBuffered: this.#flow.maxBufferedBytesPerConnection,
|
|
441
|
+
creditAware,
|
|
442
|
+
grant: (bytes) => {
|
|
443
|
+
if (!conn.closed) this.#send(fromPubKey, { op: 'credit', connId, bytes }).catch(() => {})
|
|
444
|
+
},
|
|
445
|
+
}),
|
|
446
|
+
}
|
|
263
447
|
this.#connections.set(key, conn)
|
|
264
448
|
this.#pumpToRemote(key, conn)
|
|
265
449
|
|
|
266
|
-
await this.#send(fromPubKey, { op: 'ok', connId })
|
|
450
|
+
await this.#send(fromPubKey, { op: 'ok', connId, window: this.#flow.highWaterBytes })
|
|
267
451
|
this.#onLog('mesh-relay-host:connect:ok', { fromPubKey, service, connId })
|
|
268
452
|
}
|
|
269
453
|
|
|
270
454
|
/**
|
|
271
|
-
* @param {
|
|
455
|
+
* @param {string} key
|
|
456
|
+
* @param {object} conn
|
|
272
457
|
* @param {*} base64Data
|
|
273
458
|
*/
|
|
274
|
-
async #handleData(conn, base64Data) {
|
|
459
|
+
async #handleData(key, conn, base64Data) {
|
|
275
460
|
if (typeof base64Data !== 'string') return
|
|
461
|
+
const approx = Math.floor((base64Data.length * 3) / 4)
|
|
462
|
+
if (approx > this.#flow.maxBufferedBytesPerConnection) {
|
|
463
|
+
this.#closeConnection(key, conn, { notifyPeer: true, reason: 'buffer limit exceeded' })
|
|
464
|
+
return
|
|
465
|
+
}
|
|
466
|
+
if (conn.rx.creditAware && approx > this.#flow.maxFrameBytes + 3) {
|
|
467
|
+
this.#closeConnection(key, conn, { notifyPeer: true, reason: 'flow control violation' })
|
|
468
|
+
return
|
|
469
|
+
}
|
|
470
|
+
const bytes = fromBase64(base64Data)
|
|
471
|
+
const n = bytes.length
|
|
472
|
+
|
|
473
|
+
const peerTotal = this.#peerBuffered.get(conn.fromPubKey) ?? 0
|
|
474
|
+
if (peerTotal + n > this.#flow.maxBufferedBytesPerPeer) {
|
|
475
|
+
this.#closeConnection(key, conn, { notifyPeer: true, reason: 'buffer limit exceeded' })
|
|
476
|
+
return
|
|
477
|
+
}
|
|
478
|
+
const verdict = conn.rx.receive(n)
|
|
479
|
+
if (verdict !== 'ok') {
|
|
480
|
+
this.#closeConnection(key, conn, {
|
|
481
|
+
notifyPeer: true,
|
|
482
|
+
reason: verdict === 'violation' ? 'flow control violation' : 'buffer limit exceeded',
|
|
483
|
+
})
|
|
484
|
+
return
|
|
485
|
+
}
|
|
486
|
+
this.#peerBuffered.set(conn.fromPubKey, peerTotal + n)
|
|
487
|
+
|
|
276
488
|
try {
|
|
277
|
-
await conn.socket.write(
|
|
489
|
+
await conn.socket.write(bytes)
|
|
278
490
|
} catch (err) {
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
491
|
+
if (!conn.closed) {
|
|
492
|
+
this.#onLog('mesh-relay-host:data:write-failed', {
|
|
493
|
+
connId: conn.connId, error: err?.message || String(err),
|
|
494
|
+
})
|
|
495
|
+
}
|
|
496
|
+
} finally {
|
|
497
|
+
const left = (this.#peerBuffered.get(conn.fromPubKey) ?? n) - n
|
|
498
|
+
if (left > 0) this.#peerBuffered.set(conn.fromPubKey, left)
|
|
499
|
+
else this.#peerBuffered.delete(conn.fromPubKey)
|
|
500
|
+
conn.rx.consumed(n) // credit is only sent while the connection is open
|
|
282
501
|
}
|
|
283
502
|
}
|
|
284
503
|
|
|
285
504
|
/**
|
|
286
505
|
* Pump bytes read from the local service socket back to the remote peer as
|
|
287
|
-
* `data` envelopes
|
|
288
|
-
* errors, at which point the remote
|
|
506
|
+
* `data` envelopes, no faster than the peer's credit allows. Runs until the
|
|
507
|
+
* local socket closes (natural EOF) or errors, at which point the remote
|
|
508
|
+
* peer is told via a `close` envelope.
|
|
289
509
|
*
|
|
290
510
|
* @param {string} key
|
|
291
|
-
* @param {
|
|
511
|
+
* @param {object} conn
|
|
292
512
|
*/
|
|
293
513
|
#pumpToRemote(key, conn) {
|
|
294
514
|
(async () => {
|
|
295
515
|
try {
|
|
296
|
-
while (
|
|
516
|
+
outer: while (!conn.closed) {
|
|
297
517
|
const chunk = await conn.socket.read()
|
|
298
518
|
if (chunk === null) break // local service closed the connection (EOF)
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
519
|
+
for (let off = 0; off < chunk.length;) {
|
|
520
|
+
const want = Math.min(chunk.length - off, this.#flow.maxFrameBytes)
|
|
521
|
+
const n = await conn.tx.reserve(want)
|
|
522
|
+
if (n === 0 || conn.closed) break outer
|
|
523
|
+
await this.#send(conn.fromPubKey, {
|
|
524
|
+
op: 'data',
|
|
525
|
+
connId: conn.connId,
|
|
526
|
+
data: toBase64(chunk.subarray(off, off + n)),
|
|
527
|
+
})
|
|
528
|
+
off += n
|
|
529
|
+
}
|
|
304
530
|
}
|
|
305
531
|
} catch (err) {
|
|
306
|
-
this.#onLog('mesh-relay-host:pump:error', { connId: conn.connId, error: err?.message || String(err) })
|
|
532
|
+
if (!conn.closed) this.#onLog('mesh-relay-host:pump:error', { connId: conn.connId, error: err?.message || String(err) })
|
|
307
533
|
}
|
|
308
|
-
await this.#closeConnection(key, conn, { notifyPeer: true })
|
|
534
|
+
await this.#closeConnection(key, conn, { notifyPeer: true, reason: 'service closed' })
|
|
309
535
|
})()
|
|
310
536
|
}
|
|
311
537
|
|
|
312
538
|
/**
|
|
539
|
+
* Close a connection in both directions and free what it holds. The
|
|
540
|
+
* connection is marked closed before anything is awaited, so no byte moves
|
|
541
|
+
* in either direction after this is called.
|
|
542
|
+
*
|
|
313
543
|
* @param {string} key
|
|
314
|
-
* @param {
|
|
315
|
-
* @param {{notifyPeer: boolean}} opts
|
|
544
|
+
* @param {object} conn
|
|
545
|
+
* @param {{notifyPeer: boolean, reason: string}} opts
|
|
316
546
|
*/
|
|
317
|
-
async #closeConnection(key, conn, { notifyPeer }) {
|
|
318
|
-
if (
|
|
547
|
+
async #closeConnection(key, conn, { notifyPeer, reason }) {
|
|
548
|
+
if (conn.closed) return
|
|
549
|
+
conn.closed = true
|
|
319
550
|
this.#connections.delete(key)
|
|
320
|
-
|
|
551
|
+
conn.tx.close()
|
|
552
|
+
try { await conn.socket.close(reason) } catch { /* already closed */ }
|
|
321
553
|
if (notifyPeer) {
|
|
322
|
-
await this.#send(conn.fromPubKey, { op: 'close', connId: conn.connId }).catch(() => {})
|
|
554
|
+
await this.#send(conn.fromPubKey, { op: 'close', connId: conn.connId, reason }).catch(() => {})
|
|
323
555
|
}
|
|
324
|
-
this.#onLog('mesh-relay-host:connection:closed', { connId: conn.connId, fromPubKey: conn.fromPubKey })
|
|
556
|
+
this.#onLog('mesh-relay-host:connection:closed', { connId: conn.connId, fromPubKey: conn.fromPubKey, reason })
|
|
325
557
|
}
|
|
326
558
|
|
|
327
559
|
/**
|
|
@@ -347,19 +579,28 @@ export class MeshRelayHost {
|
|
|
347
579
|
|
|
348
580
|
/**
|
|
349
581
|
* Detach from the `PeerNode` dispatch bus and close every currently
|
|
350
|
-
* relayed connection.
|
|
351
|
-
*
|
|
582
|
+
* relayed connection. After this the host neither accepts nor serves: a
|
|
583
|
+
* connect still in flight is not acknowledged and its socket is closed.
|
|
584
|
+
* Does not close `network` itself (the host doesn't own its lifecycle).
|
|
352
585
|
*/
|
|
353
586
|
async detach() {
|
|
587
|
+
this.#detached = true
|
|
354
588
|
if (this.#unsubscribeIncoming) {
|
|
355
589
|
this.#unsubscribeIncoming()
|
|
356
590
|
this.#unsubscribeIncoming = null
|
|
357
591
|
}
|
|
592
|
+
if (this.#unsubscribeAccess) {
|
|
593
|
+
this.#unsubscribeAccess()
|
|
594
|
+
this.#unsubscribeAccess = null
|
|
595
|
+
}
|
|
596
|
+
if (this.#recheckTimer) {
|
|
597
|
+
clearInterval(this.#recheckTimer)
|
|
598
|
+
this.#recheckTimer = null
|
|
599
|
+
}
|
|
358
600
|
for (const [key, conn] of [...this.#connections]) {
|
|
359
|
-
this.#
|
|
360
|
-
try { await conn.socket.close() } catch { /* already closed */ }
|
|
601
|
+
await this.#closeConnection(key, conn, { notifyPeer: true, reason: 'service detached' })
|
|
361
602
|
}
|
|
362
603
|
}
|
|
363
604
|
}
|
|
364
605
|
|
|
365
|
-
export { DEFAULT_ENVELOPE_TYPE }
|
|
606
|
+
export { DEFAULT_ENVELOPE_TYPE, RELAY_FLOW_DEFAULTS }
|
package/src/mesh-rpc.mjs
CHANGED
|
@@ -34,6 +34,8 @@ export function createMeshRpcService({
|
|
|
34
34
|
name: 'mesh-rpc',
|
|
35
35
|
attach(peerNode, ctx) {
|
|
36
36
|
let seq = 0, closed = false
|
|
37
|
+
// Per-attach random part: ids stay unique across restarts and reconnects, not only within one process.
|
|
38
|
+
const nonce = Array.from(crypto.getRandomValues(new Uint8Array(8)), b => b.toString(16).padStart(2, '0')).join('')
|
|
37
39
|
const pending = new Map()
|
|
38
40
|
const incoming = new Map()
|
|
39
41
|
const incomingCounts = new Map()
|
|
@@ -126,7 +128,7 @@ export function createMeshRpcService({
|
|
|
126
128
|
if (pending.size >= maxInflight) return Promise.reject(new Error('mesh-rpc: too many requests in flight'))
|
|
127
129
|
let encoded
|
|
128
130
|
try { encoded = encodeBody(body, maxBodyBytes) } catch (error) { return Promise.reject(error) }
|
|
129
|
-
const requestId = `${peerNode?.podId || 'local'}:${Date.now()}:${++seq}`
|
|
131
|
+
const requestId = `${peerNode?.podId || 'local'}:${Date.now()}:${nonce}:${++seq}`
|
|
130
132
|
return new Promise((resolve, reject) => {
|
|
131
133
|
const onAbort = () => cancel(requestId, abortError(signal.reason))
|
|
132
134
|
const timer = setTimeout(() => {
|
package/src/mesh-sync.mjs
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* underlying transport JSON-serializes them, see `WebRTCPeerConnection.send`),
|
|
10
10
|
* inbound via `onIncomingData()`, filtering by `envelope.type` (default
|
|
11
11
|
* `'mesh-sync'`) exactly the way `peer-node.mjs`'s own doc comments describe
|
|
12
|
-
* `
|
|
12
|
+
* `Pod.onMessage` routing "by `envelope.type`" -- multiple independent
|
|
13
13
|
* consumers of `onIncomingData()` can coexist on the same bus this way, each
|
|
14
14
|
* ignoring envelopes that aren't theirs.
|
|
15
15
|
*
|