@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
|
@@ -0,0 +1,716 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mesh-channel.mjs -- a message-oriented duplex channel between two mesh
|
|
3
|
+
* peers, for protocols that need more than `mesh-rpc`'s HTTP-shaped
|
|
4
|
+
* request/response.
|
|
5
|
+
*
|
|
6
|
+
* It sits beside `mesh-rpc` (which is untouched) on its own envelope type,
|
|
7
|
+
* `mesh-channel`. A link between two peers gives each side:
|
|
8
|
+
*
|
|
9
|
+
* - requests in BOTH directions, with ids unique per direction,
|
|
10
|
+
* - notifications (`notify` / `onNotification`),
|
|
11
|
+
* - progress per request (`ctx.progress(value)` -> `onProgress`),
|
|
12
|
+
* - cancel per request (the callee's handler gets an AbortSignal; the
|
|
13
|
+
* caller's late results are dropped),
|
|
14
|
+
* - native binary values (`Uint8Array` anywhere in a message),
|
|
15
|
+
* - a negotiated maximum message size, enforced from the first chunk's
|
|
16
|
+
* announced length, before a message is assembled,
|
|
17
|
+
* - byte-based credit flow control, so a slow reader bounds a sender's
|
|
18
|
+
* memory (the sender may have at most `window` unconsumed bytes in
|
|
19
|
+
* flight to that peer),
|
|
20
|
+
* - bounded in-flight requests per peer, and
|
|
21
|
+
* - a `close()` that rejects every pending request.
|
|
22
|
+
*
|
|
23
|
+
* Identity. A handler is handed `peer`, the public key the SESSION is bound
|
|
24
|
+
* to (the `pubKey` `PeerNode` reports for the transport the frame arrived
|
|
25
|
+
* on). Nothing inside a message is ever used to say who sent it. As with
|
|
26
|
+
* `mesh-rpc`, this layer does not authorise anything: each handler owns its
|
|
27
|
+
* own access check (`ctx.registry.checkAccess(peer, ...)`).
|
|
28
|
+
*
|
|
29
|
+
* Wire. Envelope `{ type: 'mesh-channel', k, ... }`, JSON-safe because real
|
|
30
|
+
* transports carry envelopes as JSON text. Frame kinds `k`:
|
|
31
|
+
* hello / hello-ack version + limits handshake (sent first; nothing else
|
|
32
|
+
* is sent to a peer until it has answered)
|
|
33
|
+
* d one chunk of an encoded message (`m` message id, `i`
|
|
34
|
+
* chunk index, `n` total encoded bytes on the first
|
|
35
|
+
* chunk, `f` base64 chunk bytes)
|
|
36
|
+
* c credit grant, `n` bytes
|
|
37
|
+
* a receiver refuses message `m` (over the size limit)
|
|
38
|
+
* x cancel request `id` (control frame, not credit-gated)
|
|
39
|
+
* close orderly close
|
|
40
|
+
* Messages are encoded with `internal/channel-codec.mjs` (a small
|
|
41
|
+
* self-contained binary-safe value codec) and split into chunks of at most
|
|
42
|
+
* `chunkBytes`; base64 is only the JSON-envelope carrier of those chunks and
|
|
43
|
+
* never appears in the API. Frames of one link must arrive in order (the
|
|
44
|
+
* default `control` data channel is ordered).
|
|
45
|
+
*
|
|
46
|
+
* Old peers. A peer that does not run this service ignores the envelope
|
|
47
|
+
* type; `open()` therefore sends exactly one small `hello` and nothing else,
|
|
48
|
+
* and rejects with `MeshChannelError` (code -32000, reason `unsupported`)
|
|
49
|
+
* if no `hello-ack` arrives within `handshakeTimeoutMs`. A peer that knows
|
|
50
|
+
* the channel but not the version answers with an error ack. Pass
|
|
51
|
+
* `peerSupports(peer)` to refuse without sending anything at all when the
|
|
52
|
+
* caller already knows (for example from a capability advertisement).
|
|
53
|
+
*
|
|
54
|
+
* Memory model. The receiver never holds more than `window` bytes it has not
|
|
55
|
+
* yet handed back as credit, and `maxMessageBytes` (<= `window`) bounds the
|
|
56
|
+
* single message under assembly. Credit for a request, response, progress
|
|
57
|
+
* or notification is returned as soon as it has been dispatched; credit for a
|
|
58
|
+
* raw `send()` message is returned when every `onMessage` callback has
|
|
59
|
+
* settled, so an `onMessage` callback that awaits slow work slows the sender
|
|
60
|
+
* down (and one that never settles stops it). Raw callbacks run one at a time
|
|
61
|
+
* in arrival order. Do not make a raw callback wait for a response from the
|
|
62
|
+
* same peer: that response may be queued behind the credit it holds.
|
|
63
|
+
*
|
|
64
|
+
* Error codes (JSON-RPC style): -32000 unsupported, -32001 cancelled /
|
|
65
|
+
* timed out / channel closed, -32002 too many requests in flight, -32003
|
|
66
|
+
* unauthorized (for handlers to throw), -32004 message too large, -32601
|
|
67
|
+
* unknown method, -32603 handler failed, -32600 invalid request.
|
|
68
|
+
*
|
|
69
|
+
* No browser-only imports.
|
|
70
|
+
*/
|
|
71
|
+
import { encodeValue, decodeValue, toBase64, fromBase64 } from './internal/channel-codec.mjs'
|
|
72
|
+
|
|
73
|
+
export const CHANNEL_ENVELOPE_TYPE = 'mesh-channel'
|
|
74
|
+
export const CHANNEL_VERSION = 1
|
|
75
|
+
export const CHANNEL_MIN_VERSION = 1
|
|
76
|
+
export const CHANNEL_DEFAULT_MAX_MESSAGE_BYTES = 1024 * 1024
|
|
77
|
+
export const CHANNEL_DEFAULT_WINDOW_BYTES = 4 * 1024 * 1024
|
|
78
|
+
export const CHANNEL_DEFAULT_CHUNK_BYTES = 16 * 1024
|
|
79
|
+
export const CHANNEL_DEFAULT_MAX_INFLIGHT = 64
|
|
80
|
+
export const CHANNEL_DEFAULT_REQUEST_TIMEOUT_MS = 30000
|
|
81
|
+
export const CHANNEL_DEFAULT_HANDSHAKE_TIMEOUT_MS = 5000
|
|
82
|
+
export const CHANNEL_DEFAULT_MAX_PEERS = 64
|
|
83
|
+
|
|
84
|
+
export const ChannelErrorCode = Object.freeze({
|
|
85
|
+
UNSUPPORTED: -32000,
|
|
86
|
+
CANCELLED: -32001,
|
|
87
|
+
BUSY: -32002,
|
|
88
|
+
UNAUTHORIZED: -32003,
|
|
89
|
+
TOO_LARGE: -32004,
|
|
90
|
+
INVALID: -32600,
|
|
91
|
+
METHOD_NOT_FOUND: -32601,
|
|
92
|
+
INTERNAL: -32603,
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
export class MeshChannelError extends Error {
|
|
96
|
+
/**
|
|
97
|
+
* @param {number} code
|
|
98
|
+
* @param {string} reason - short machine-readable reason (`cancelled`, `timeout`, `channel-closed`, ...)
|
|
99
|
+
* @param {string} [message]
|
|
100
|
+
* @param {*} [data]
|
|
101
|
+
*/
|
|
102
|
+
constructor(code, reason, message, data) {
|
|
103
|
+
super(message || reason)
|
|
104
|
+
this.name = 'MeshChannelError'
|
|
105
|
+
this.code = code
|
|
106
|
+
this.reason = reason
|
|
107
|
+
if (data !== undefined) this.data = data
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const err = (code, reason, message, data) => new MeshChannelError(code, reason, message, data)
|
|
112
|
+
const isPosInt = n => Number.isSafeInteger(n) && n > 0
|
|
113
|
+
const MAX_METHOD_LENGTH = 256
|
|
114
|
+
const MAX_REMOTE_WINDOW = 2 ** 31
|
|
115
|
+
|
|
116
|
+
function encodeError(e) {
|
|
117
|
+
if (e instanceof MeshChannelError) return { c: e.code, r: e.reason, m: e.message, d: e.data }
|
|
118
|
+
return { c: ChannelErrorCode.INTERNAL, r: 'handler-failed', m: e?.message || String(e) }
|
|
119
|
+
}
|
|
120
|
+
function decodeError(w) {
|
|
121
|
+
const c = Number.isSafeInteger(w?.c) ? w.c : ChannelErrorCode.INTERNAL
|
|
122
|
+
return err(c, typeof w?.r === 'string' ? w.r : 'error', typeof w?.m === 'string' ? w.m : 'remote error', w?.d)
|
|
123
|
+
}
|
|
124
|
+
/** Exact decoded length of base64 text, without decoding it. */
|
|
125
|
+
function base64Length(text) {
|
|
126
|
+
if (typeof text !== 'string' || text.length % 4) return -1
|
|
127
|
+
const pad = text.endsWith('==') ? 2 : text.endsWith('=') ? 1 : 0
|
|
128
|
+
return (text.length / 4) * 3 - pad
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Transport-neutral core of one link. It talks to the outside world through
|
|
133
|
+
* `sendFrame(frame) -> Promise` and `receive(frame)`, so it runs unchanged
|
|
134
|
+
* over a mesh session (see `createMeshChannelService`) or over any
|
|
135
|
+
* in-memory duplex.
|
|
136
|
+
*
|
|
137
|
+
* @param {object} opts
|
|
138
|
+
* @param {string} opts.peer - the verified identity of the other end
|
|
139
|
+
* @param {(frame: object) => (void|Promise<void>)} opts.sendFrame
|
|
140
|
+
* @param {(link: object) => void} [opts.onReady] - called synchronously the moment the other end's parameters are known
|
|
141
|
+
* @returns {object} `{ link, receive, open, close, remoteSid }`
|
|
142
|
+
*/
|
|
143
|
+
export function createChannelCore({
|
|
144
|
+
peer,
|
|
145
|
+
sendFrame,
|
|
146
|
+
maxMessageBytes = CHANNEL_DEFAULT_MAX_MESSAGE_BYTES,
|
|
147
|
+
window: windowBytes = CHANNEL_DEFAULT_WINDOW_BYTES,
|
|
148
|
+
maxInflight = CHANNEL_DEFAULT_MAX_INFLIGHT,
|
|
149
|
+
chunkBytes = CHANNEL_DEFAULT_CHUNK_BYTES,
|
|
150
|
+
requestTimeoutMs = CHANNEL_DEFAULT_REQUEST_TIMEOUT_MS,
|
|
151
|
+
handshakeTimeoutMs = CHANNEL_DEFAULT_HANDSHAKE_TIMEOUT_MS,
|
|
152
|
+
features = [],
|
|
153
|
+
onReady,
|
|
154
|
+
onLog,
|
|
155
|
+
} = {}) {
|
|
156
|
+
if (typeof peer !== 'string' || !peer) throw new TypeError('mesh-channel: peer must be a non-empty string')
|
|
157
|
+
if (typeof sendFrame !== 'function') throw new TypeError('mesh-channel: sendFrame must be a function')
|
|
158
|
+
for (const [name, value] of Object.entries({ maxMessageBytes, window: windowBytes, maxInflight, chunkBytes, requestTimeoutMs, handshakeTimeoutMs })) {
|
|
159
|
+
if (!isPosInt(value)) throw new TypeError(`mesh-channel: ${name} must be a positive integer`)
|
|
160
|
+
}
|
|
161
|
+
if (maxMessageBytes > windowBytes) throw new TypeError('mesh-channel: maxMessageBytes cannot exceed window (a message must fit in the receive window)')
|
|
162
|
+
if (chunkBytes > windowBytes) throw new TypeError('mesh-channel: chunkBytes cannot exceed window')
|
|
163
|
+
const log = onLog || (() => {})
|
|
164
|
+
const sid = Array.from(crypto.getRandomValues(new Uint8Array(8)), b => b.toString(16).padStart(2, '0')).join('')
|
|
165
|
+
const local = { maxMessageBytes, window: windowBytes, maxInflight, chunkBytes }
|
|
166
|
+
|
|
167
|
+
let remote = null // set by hello / hello-ack
|
|
168
|
+
let remoteSid = null
|
|
169
|
+
let version = CHANNEL_VERSION
|
|
170
|
+
let negotiatedFeatures = []
|
|
171
|
+
let closed = false
|
|
172
|
+
let closeError = null
|
|
173
|
+
let helloSent = false
|
|
174
|
+
let ready, rejectReady
|
|
175
|
+
let readySettled = false
|
|
176
|
+
const readyPromise = new Promise((res, rej) => { ready = res; rejectReady = rej })
|
|
177
|
+
readyPromise.catch(() => {})
|
|
178
|
+
|
|
179
|
+
// ---- sending side ----
|
|
180
|
+
let credit = 0
|
|
181
|
+
let nextMsg = 1
|
|
182
|
+
const sendQueue = [] // { m, bytes, offset, resolve, reject, signal, onAbort }
|
|
183
|
+
let pumping = false
|
|
184
|
+
|
|
185
|
+
// ---- receiving side ----
|
|
186
|
+
let held = 0 // bytes received and not yet handed back as credit
|
|
187
|
+
let asm = null // message under assembly
|
|
188
|
+
let refusing = null // message id being refused (over the size limit)
|
|
189
|
+
const rawQueue = []
|
|
190
|
+
let rawRunning = false
|
|
191
|
+
|
|
192
|
+
// ---- requests ----
|
|
193
|
+
let nextId = 1
|
|
194
|
+
const pending = new Map() // our requests awaiting a response
|
|
195
|
+
const incoming = new Map() // requests we are serving
|
|
196
|
+
const requestHandlers = new Map()
|
|
197
|
+
const notificationHandlers = new Map()
|
|
198
|
+
const messageListeners = new Set()
|
|
199
|
+
const closeListeners = new Set()
|
|
200
|
+
|
|
201
|
+
const effectiveMax = () => remote ? Math.min(local.maxMessageBytes, remote.maxMessageBytes) : local.maxMessageBytes
|
|
202
|
+
const frame = (k, rest) => ({ k, ...rest })
|
|
203
|
+
function transmit(f) {
|
|
204
|
+
return Promise.resolve().then(() => sendFrame(f))
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// ------------------------------------------------------------------ close
|
|
208
|
+
function close(reason, { notifyRemote = true } = {}) {
|
|
209
|
+
if (closed) return
|
|
210
|
+
closed = true
|
|
211
|
+
const why = reason instanceof Error ? reason : err(ChannelErrorCode.CANCELLED, 'channel-closed', typeof reason === 'string' ? reason : 'channel closed')
|
|
212
|
+
closeError = why
|
|
213
|
+
if (notifyRemote && readySettled) transmit(frame('close', { c: why.code, r: why.reason })).catch(() => {})
|
|
214
|
+
if (!readySettled) { readySettled = true; rejectReady(why) }
|
|
215
|
+
for (const [id, p] of [...pending]) {
|
|
216
|
+
pending.delete(id)
|
|
217
|
+
clearTimeout(p.timer)
|
|
218
|
+
p.signal?.removeEventListener('abort', p.onAbort)
|
|
219
|
+
p.reject(err(ChannelErrorCode.CANCELLED, 'channel-closed', 'channel closed while the request was pending'))
|
|
220
|
+
}
|
|
221
|
+
for (const a of incoming.values()) a.controller.abort(err(ChannelErrorCode.CANCELLED, 'channel-closed', 'channel closed'))
|
|
222
|
+
incoming.clear()
|
|
223
|
+
for (const item of sendQueue.splice(0)) {
|
|
224
|
+
item.signal?.removeEventListener('abort', item.onAbort)
|
|
225
|
+
item.reject(err(ChannelErrorCode.CANCELLED, 'channel-closed', 'channel closed before the message was sent'))
|
|
226
|
+
}
|
|
227
|
+
rawQueue.length = 0
|
|
228
|
+
asm = null
|
|
229
|
+
for (const cb of [...closeListeners]) { try { cb(why) } catch (e) { log('mesh-channel:close-listener-threw', { error: e?.message }) } }
|
|
230
|
+
closeListeners.clear()
|
|
231
|
+
}
|
|
232
|
+
const violation = message => {
|
|
233
|
+
log('mesh-channel:protocol-violation', { peer, message })
|
|
234
|
+
close(err(ChannelErrorCode.INVALID, 'protocol-violation', message))
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// ------------------------------------------------------------ flow control
|
|
238
|
+
function returnCredit(n) {
|
|
239
|
+
if (closed || n <= 0) return
|
|
240
|
+
transmit(frame('c', { n })).catch(e => close(e))
|
|
241
|
+
}
|
|
242
|
+
function grant(n) {
|
|
243
|
+
held -= n
|
|
244
|
+
returnCredit(n)
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function pump() {
|
|
248
|
+
if (pumping) return
|
|
249
|
+
pumping = true
|
|
250
|
+
try {
|
|
251
|
+
while (!closed && sendQueue.length) {
|
|
252
|
+
const item = sendQueue[0]
|
|
253
|
+
while (!closed && item.offset < item.bytes.byteLength) {
|
|
254
|
+
if (credit <= 0) return // resumed when a credit frame arrives
|
|
255
|
+
const size = Math.min(item.bytes.byteLength - item.offset, Math.min(local.chunkBytes, remote.chunkBytes), credit)
|
|
256
|
+
const chunk = item.bytes.subarray(item.offset, item.offset + size)
|
|
257
|
+
const f = frame('d', { m: item.m, i: item.index, f: toBase64(chunk) })
|
|
258
|
+
if (item.index === 0) f.n = item.bytes.byteLength
|
|
259
|
+
credit -= size
|
|
260
|
+
item.offset += size
|
|
261
|
+
item.index += 1
|
|
262
|
+
item.started = true
|
|
263
|
+
await transmit(f)
|
|
264
|
+
if (sendQueue[0] !== item) break // refused by the receiver while we were sending
|
|
265
|
+
}
|
|
266
|
+
if (sendQueue[0] === item) {
|
|
267
|
+
sendQueue.shift()
|
|
268
|
+
item.signal?.removeEventListener('abort', item.onAbort)
|
|
269
|
+
item.resolve()
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
} catch (e) {
|
|
273
|
+
close(e)
|
|
274
|
+
} finally {
|
|
275
|
+
pumping = false
|
|
276
|
+
if (!closed && sendQueue.length && credit > 0) pump()
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function enqueue(value, { signal } = {}) {
|
|
281
|
+
if (closed) return Promise.reject(closeError)
|
|
282
|
+
if (!remote) return Promise.reject(err(ChannelErrorCode.UNSUPPORTED, 'not-ready', 'channel is not open yet'))
|
|
283
|
+
if (signal?.aborted) return Promise.reject(err(ChannelErrorCode.CANCELLED, 'cancelled', 'send aborted'))
|
|
284
|
+
let bytes
|
|
285
|
+
try { bytes = encodeValue(value) } catch (e) { return Promise.reject(e) }
|
|
286
|
+
// Refused here, before a single byte of it reaches the wire.
|
|
287
|
+
if (bytes.byteLength > effectiveMax()) {
|
|
288
|
+
return Promise.reject(err(ChannelErrorCode.TOO_LARGE, 'message-too-large', `message of ${bytes.byteLength} bytes exceeds the negotiated maximum of ${effectiveMax()}`))
|
|
289
|
+
}
|
|
290
|
+
return new Promise((resolve, reject) => {
|
|
291
|
+
const item = { m: nextMsg++, bytes, offset: 0, index: 0, started: false, resolve, reject, signal }
|
|
292
|
+
item.onAbort = () => {
|
|
293
|
+
if (item.started) return // part of it is already out; it completes
|
|
294
|
+
const at = sendQueue.indexOf(item)
|
|
295
|
+
if (at >= 0) sendQueue.splice(at, 1)
|
|
296
|
+
reject(err(ChannelErrorCode.CANCELLED, 'cancelled', 'send aborted'))
|
|
297
|
+
}
|
|
298
|
+
signal?.addEventListener('abort', item.onAbort, { once: true })
|
|
299
|
+
sendQueue.push(item)
|
|
300
|
+
pump()
|
|
301
|
+
})
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// --------------------------------------------------------------- receiving
|
|
305
|
+
function onData(fr) {
|
|
306
|
+
if (!remote) return
|
|
307
|
+
const { m, i, f } = fr
|
|
308
|
+
if (!Number.isSafeInteger(m) || !Number.isSafeInteger(i) || i < 0) return violation('malformed data frame')
|
|
309
|
+
const len = base64Length(f)
|
|
310
|
+
if (len < 0) return violation('malformed data frame')
|
|
311
|
+
if (len > local.chunkBytes) return violation('chunk exceeds the advertised chunk size')
|
|
312
|
+
if (held + len > local.window) return violation('sender exceeded the credit it was granted')
|
|
313
|
+
if (i === 0) {
|
|
314
|
+
if (asm) return violation('a new message began before the previous one finished')
|
|
315
|
+
refusing = null
|
|
316
|
+
const n = fr.n
|
|
317
|
+
if (!isPosInt(n)) return violation('first chunk must announce a positive message length')
|
|
318
|
+
if (n > local.maxMessageBytes) {
|
|
319
|
+
// Refused from the announced length alone: nothing is allocated for it.
|
|
320
|
+
refusing = m
|
|
321
|
+
transmit(frame('a', { m, c: ChannelErrorCode.TOO_LARGE })).catch(() => {})
|
|
322
|
+
return returnCredit(len)
|
|
323
|
+
}
|
|
324
|
+
asm = { m, n, parts: [], got: 0, next: 0 }
|
|
325
|
+
} else if (m === refusing) {
|
|
326
|
+
return returnCredit(len) // the tail of a message we refused: dropped unbuffered
|
|
327
|
+
}
|
|
328
|
+
if (!asm || asm.m !== m || i !== asm.next) return violation('out-of-order data frame')
|
|
329
|
+
if (asm.got + len > asm.n) return violation('chunk overruns the announced message length')
|
|
330
|
+
let bytes
|
|
331
|
+
try { bytes = fromBase64(f, local.chunkBytes) } catch { return violation('invalid chunk encoding') }
|
|
332
|
+
held += bytes.byteLength
|
|
333
|
+
asm.parts.push(bytes)
|
|
334
|
+
asm.got += bytes.byteLength
|
|
335
|
+
asm.next += 1
|
|
336
|
+
if (asm.got < asm.n) return
|
|
337
|
+
const whole = new Uint8Array(asm.n)
|
|
338
|
+
let at = 0
|
|
339
|
+
for (const part of asm.parts) { whole.set(part, at); at += part.byteLength }
|
|
340
|
+
const size = asm.n
|
|
341
|
+
asm = null
|
|
342
|
+
let value
|
|
343
|
+
try { value = decodeValue(whole) } catch { return violation('undecodable message') }
|
|
344
|
+
dispatch(value, size)
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function dispatch(msg, size) {
|
|
348
|
+
let credited = false
|
|
349
|
+
const giveBack = () => { if (!credited) { credited = true; grant(size) } }
|
|
350
|
+
try {
|
|
351
|
+
if (!msg || typeof msg !== 'object') return giveBack()
|
|
352
|
+
switch (msg.t) {
|
|
353
|
+
case 'q': handleRequest(msg); return giveBack()
|
|
354
|
+
case 'r': handleResponse(msg); return giveBack()
|
|
355
|
+
case 'g': pending.get(msg.id)?.onProgress?.(msg.v); return giveBack()
|
|
356
|
+
case 'n': handleNotification(msg); return giveBack()
|
|
357
|
+
case 'm':
|
|
358
|
+
rawQueue.push({ value: msg.b, giveBack })
|
|
359
|
+
return drainRaw()
|
|
360
|
+
default: return giveBack()
|
|
361
|
+
}
|
|
362
|
+
} catch (e) {
|
|
363
|
+
log('mesh-channel:dispatch-threw', { peer, error: e?.message })
|
|
364
|
+
giveBack()
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async function drainRaw() {
|
|
369
|
+
if (rawRunning) return
|
|
370
|
+
rawRunning = true
|
|
371
|
+
try {
|
|
372
|
+
while (rawQueue.length && !closed) {
|
|
373
|
+
const { value, giveBack } = rawQueue.shift()
|
|
374
|
+
try { await Promise.all([...messageListeners].map(cb => cb(value, { peer }))) }
|
|
375
|
+
catch (e) { log('mesh-channel:message-listener-threw', { peer, error: e?.message }) }
|
|
376
|
+
giveBack()
|
|
377
|
+
}
|
|
378
|
+
} finally { rawRunning = false }
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function handleNotification(msg) {
|
|
382
|
+
if (typeof msg.m !== 'string') return
|
|
383
|
+
for (const cb of [...(notificationHandlers.get(msg.m) || [])]) {
|
|
384
|
+
Promise.resolve().then(() => cb(msg.p, { peer, method: msg.m })).catch(e => log('mesh-channel:notification-handler-threw', { peer, method: msg.m, error: e?.message }))
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function respond(id, body) {
|
|
389
|
+
if (closed) return
|
|
390
|
+
enqueue({ t: 'r', id, ...body }).catch(e => {
|
|
391
|
+
if (closed) return
|
|
392
|
+
// A result that cannot be sent (too large, not encodable) becomes an error the caller can read.
|
|
393
|
+
if (body.e) return
|
|
394
|
+
enqueue({ t: 'r', id, e: encodeError(e instanceof MeshChannelError ? e : err(ChannelErrorCode.INTERNAL, 'unsendable-result', e?.message)) }).catch(() => {})
|
|
395
|
+
})
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function handleRequest(msg) {
|
|
399
|
+
const { id, m: method } = msg
|
|
400
|
+
if (!isPosInt(id) || typeof method !== 'string' || !method || method.length > MAX_METHOD_LENGTH) return
|
|
401
|
+
if (incoming.has(id)) return
|
|
402
|
+
if (incoming.size >= local.maxInflight) return respond(id, { e: encodeError(err(ChannelErrorCode.BUSY, 'too-many-requests', 'too many requests in flight')) })
|
|
403
|
+
const handler = requestHandlers.get(method)
|
|
404
|
+
if (!handler) return respond(id, { e: encodeError(err(ChannelErrorCode.METHOD_NOT_FOUND, 'method-not-found', `no handler for ${method}`)) })
|
|
405
|
+
const controller = new AbortController()
|
|
406
|
+
incoming.set(id, { controller })
|
|
407
|
+
const progress = value => {
|
|
408
|
+
if (closed || controller.signal.aborted) return Promise.resolve()
|
|
409
|
+
return enqueue({ t: 'g', id, v: value }).catch(() => {})
|
|
410
|
+
}
|
|
411
|
+
Promise.resolve().then(() => handler(msg.p, { peer, id, method, signal: controller.signal, progress })).then(
|
|
412
|
+
result => { if (incoming.get(id)?.controller === controller) { incoming.delete(id); if (!controller.signal.aborted) respond(id, { v: result }) } },
|
|
413
|
+
error => {
|
|
414
|
+
if (incoming.get(id)?.controller !== controller) return
|
|
415
|
+
incoming.delete(id)
|
|
416
|
+
if (controller.signal.aborted) return
|
|
417
|
+
log('mesh-channel:handler-threw', { peer, method, error: error?.message })
|
|
418
|
+
respond(id, { e: encodeError(error) })
|
|
419
|
+
},
|
|
420
|
+
)
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function handleResponse(msg) {
|
|
424
|
+
const p = pending.get(msg.id)
|
|
425
|
+
if (!p) return // late result for a cancelled / unknown request: dropped
|
|
426
|
+
pending.delete(msg.id)
|
|
427
|
+
clearTimeout(p.timer)
|
|
428
|
+
p.signal?.removeEventListener('abort', p.onAbort)
|
|
429
|
+
if (msg.e) p.reject(decodeError(msg.e))
|
|
430
|
+
else p.resolve(msg.v)
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function onCancel(fr) {
|
|
434
|
+
const a = incoming.get(fr.id)
|
|
435
|
+
if (!a) return
|
|
436
|
+
incoming.delete(fr.id)
|
|
437
|
+
a.controller.abort(err(ChannelErrorCode.CANCELLED, 'cancelled', 'cancelled by the caller'))
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// --------------------------------------------------------------- handshake
|
|
441
|
+
function params() {
|
|
442
|
+
return { sid, v: CHANNEL_VERSION, min: CHANNEL_MIN_VERSION, maxMessageBytes: local.maxMessageBytes, window: local.window, maxInflight: local.maxInflight, chunkBytes: local.chunkBytes, features }
|
|
443
|
+
}
|
|
444
|
+
function adoptRemote(fr) {
|
|
445
|
+
const okInts = [fr.maxMessageBytes, fr.window, fr.maxInflight, fr.chunkBytes].every(isPosInt)
|
|
446
|
+
if (!okInts || !Number.isSafeInteger(fr.v) || fr.window > MAX_REMOTE_WINDOW || fr.maxMessageBytes > fr.window || fr.chunkBytes > fr.window) {
|
|
447
|
+
throw err(ChannelErrorCode.INVALID, 'bad-handshake', 'malformed handshake')
|
|
448
|
+
}
|
|
449
|
+
const min = Number.isSafeInteger(fr.min) ? fr.min : fr.v
|
|
450
|
+
if (fr.v < CHANNEL_MIN_VERSION || min > CHANNEL_VERSION) throw err(ChannelErrorCode.UNSUPPORTED, 'unsupported-version', `no common version (remote ${min}..${fr.v}, local ${CHANNEL_MIN_VERSION}..${CHANNEL_VERSION})`)
|
|
451
|
+
remote = { maxMessageBytes: fr.maxMessageBytes, window: fr.window, maxInflight: fr.maxInflight, chunkBytes: fr.chunkBytes }
|
|
452
|
+
remoteSid = typeof fr.sid === 'string' ? fr.sid : null
|
|
453
|
+
version = Math.min(fr.v, CHANNEL_VERSION)
|
|
454
|
+
negotiatedFeatures = Array.isArray(fr.features) ? fr.features.filter(f => typeof f === 'string' && features.includes(f)) : []
|
|
455
|
+
credit = remote.window
|
|
456
|
+
if (!readySettled) {
|
|
457
|
+
readySettled = true
|
|
458
|
+
ready()
|
|
459
|
+
// Synchronous, before any further frame is processed: handlers registered here cannot miss a request.
|
|
460
|
+
try { onReady?.(link) } catch (e) { log('mesh-channel:on-ready-threw', { peer, error: e?.message }) }
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function onHello(fr) {
|
|
465
|
+
try { if (!remote) adoptRemote(fr) }
|
|
466
|
+
catch (e) {
|
|
467
|
+
transmit(frame('hello-ack', { sid, error: { c: e.code, r: e.reason, m: e.message } })).catch(() => {})
|
|
468
|
+
return close(e, { notifyRemote: false })
|
|
469
|
+
}
|
|
470
|
+
transmit(frame('hello-ack', params())).catch(e => close(e))
|
|
471
|
+
}
|
|
472
|
+
function onHelloAck(fr) {
|
|
473
|
+
if (fr.error) return close(decodeError(fr.error), { notifyRemote: false })
|
|
474
|
+
if (remote) return
|
|
475
|
+
try { adoptRemote(fr) } catch (e) { close(e) }
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function receive(fr) {
|
|
479
|
+
if (closed || !fr || typeof fr !== 'object') return
|
|
480
|
+
switch (fr.k) {
|
|
481
|
+
case 'hello': return onHello(fr)
|
|
482
|
+
case 'hello-ack': return onHelloAck(fr)
|
|
483
|
+
case 'd': return onData(fr)
|
|
484
|
+
case 'c': {
|
|
485
|
+
if (!remote || !isPosInt(fr.n)) return
|
|
486
|
+
credit = Math.min(credit + fr.n, remote.window)
|
|
487
|
+
return void pump()
|
|
488
|
+
}
|
|
489
|
+
case 'a': {
|
|
490
|
+
const head = sendQueue[0]
|
|
491
|
+
if (head && head.m === fr.m) {
|
|
492
|
+
sendQueue.shift()
|
|
493
|
+
head.signal?.removeEventListener('abort', head.onAbort)
|
|
494
|
+
head.reject(err(Number.isSafeInteger(fr.c) ? fr.c : ChannelErrorCode.TOO_LARGE, 'message-refused', 'the receiver refused the message'))
|
|
495
|
+
}
|
|
496
|
+
return
|
|
497
|
+
}
|
|
498
|
+
case 'x': return onCancel(fr)
|
|
499
|
+
case 'close': return close(err(Number.isSafeInteger(fr.c) ? fr.c : ChannelErrorCode.CANCELLED, typeof fr.r === 'string' ? fr.r : 'channel-closed', 'closed by the peer'), { notifyRemote: false })
|
|
500
|
+
default: return
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** Send our hello (once) and resolve when the other end's parameters are known. */
|
|
505
|
+
function open({ timeoutMs = handshakeTimeoutMs } = {}) {
|
|
506
|
+
if (closed) return Promise.reject(closeError)
|
|
507
|
+
if (!helloSent) {
|
|
508
|
+
helloSent = true
|
|
509
|
+
transmit(frame('hello', params())).catch(e => close(e))
|
|
510
|
+
}
|
|
511
|
+
if (readySettled) return readyPromise
|
|
512
|
+
return new Promise((resolve, reject) => {
|
|
513
|
+
const timer = setTimeout(() => {
|
|
514
|
+
const e = err(ChannelErrorCode.UNSUPPORTED, 'unsupported', 'the peer did not answer the channel handshake (it may not support mesh-channel)')
|
|
515
|
+
close(e, { notifyRemote: false })
|
|
516
|
+
reject(e)
|
|
517
|
+
}, timeoutMs)
|
|
518
|
+
// Not unref'd: a caller awaiting open() must hear back even if nothing else keeps the process alive.
|
|
519
|
+
readyPromise.then(resolve, reject).finally(() => clearTimeout(timer))
|
|
520
|
+
})
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// -------------------------------------------------------------- public link
|
|
524
|
+
function request(method, params, { signal, onProgress, timeoutMs = requestTimeoutMs } = {}) {
|
|
525
|
+
if (closed) return Promise.reject(closeError)
|
|
526
|
+
if (typeof method !== 'string' || !method || method.length > MAX_METHOD_LENGTH) return Promise.reject(new TypeError('mesh-channel: method must be a non-empty string'))
|
|
527
|
+
if (!isPosInt(timeoutMs)) return Promise.reject(new TypeError('mesh-channel: timeoutMs must be a positive integer'))
|
|
528
|
+
if (signal?.aborted) return Promise.reject(err(ChannelErrorCode.CANCELLED, 'cancelled', 'request aborted'))
|
|
529
|
+
if (!remote) return Promise.reject(err(ChannelErrorCode.UNSUPPORTED, 'not-ready', 'channel is not open yet'))
|
|
530
|
+
if (pending.size >= Math.min(local.maxInflight, remote.maxInflight)) return Promise.reject(err(ChannelErrorCode.BUSY, 'too-many-requests', 'too many requests in flight'))
|
|
531
|
+
const id = nextId++
|
|
532
|
+
return new Promise((resolve, reject) => {
|
|
533
|
+
const fail = (e) => {
|
|
534
|
+
const p = pending.get(id)
|
|
535
|
+
if (!p) return
|
|
536
|
+
pending.delete(id)
|
|
537
|
+
clearTimeout(p.timer)
|
|
538
|
+
signal?.removeEventListener('abort', p.onAbort)
|
|
539
|
+
reject(e)
|
|
540
|
+
// The callee is told; a late result it sends anyway is dropped (unknown id).
|
|
541
|
+
transmit(frame('x', { id })).catch(() => {})
|
|
542
|
+
}
|
|
543
|
+
const onAbort = () => fail(err(ChannelErrorCode.CANCELLED, 'cancelled', 'request aborted'))
|
|
544
|
+
const timer = setTimeout(() => fail(err(ChannelErrorCode.CANCELLED, 'timeout', `request ${method} timed out after ${timeoutMs}ms`)), timeoutMs)
|
|
545
|
+
timer.unref?.()
|
|
546
|
+
pending.set(id, { resolve, reject, onProgress, timer, signal, onAbort })
|
|
547
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
548
|
+
enqueue({ t: 'q', id, m: method, p: params }).catch(e => {
|
|
549
|
+
const p = pending.get(id)
|
|
550
|
+
if (!p) return
|
|
551
|
+
pending.delete(id)
|
|
552
|
+
clearTimeout(timer)
|
|
553
|
+
signal?.removeEventListener('abort', onAbort)
|
|
554
|
+
reject(e)
|
|
555
|
+
})
|
|
556
|
+
})
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
const addTo = (map, key, cb) => {
|
|
560
|
+
let set = map.get(key)
|
|
561
|
+
if (!set) map.set(key, set = new Set())
|
|
562
|
+
set.add(cb)
|
|
563
|
+
return () => { set.delete(cb); if (!set.size) map.delete(key) }
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
const link = {
|
|
567
|
+
peer,
|
|
568
|
+
get maxMessageBytes() { return effectiveMax() },
|
|
569
|
+
get version() { return version },
|
|
570
|
+
get features() { return [...negotiatedFeatures] },
|
|
571
|
+
get closed() { return closed },
|
|
572
|
+
ready: readyPromise,
|
|
573
|
+
send(value, opts) { return enqueue({ t: 'm', b: value }, opts) },
|
|
574
|
+
onMessage(cb) {
|
|
575
|
+
if (typeof cb !== 'function') throw new TypeError('mesh-channel: onMessage needs a function')
|
|
576
|
+
messageListeners.add(cb)
|
|
577
|
+
return () => messageListeners.delete(cb)
|
|
578
|
+
},
|
|
579
|
+
request,
|
|
580
|
+
notify(method, params) {
|
|
581
|
+
if (typeof method !== 'string' || !method || method.length > MAX_METHOD_LENGTH) return Promise.reject(new TypeError('mesh-channel: method must be a non-empty string'))
|
|
582
|
+
return enqueue({ t: 'n', m: method, p: params })
|
|
583
|
+
},
|
|
584
|
+
onRequest(method, handler) {
|
|
585
|
+
if (typeof method !== 'string' || !method || typeof handler !== 'function') throw new TypeError('mesh-channel: onRequest(method, handler)')
|
|
586
|
+
if (requestHandlers.has(method)) throw new Error(`mesh-channel: a handler for ${method} is already registered`)
|
|
587
|
+
requestHandlers.set(method, handler)
|
|
588
|
+
return () => { if (requestHandlers.get(method) === handler) requestHandlers.delete(method) }
|
|
589
|
+
},
|
|
590
|
+
onNotification(method, handler) {
|
|
591
|
+
if (typeof method !== 'string' || !method || typeof handler !== 'function') throw new TypeError('mesh-channel: onNotification(method, handler)')
|
|
592
|
+
return addTo(notificationHandlers, method, handler)
|
|
593
|
+
},
|
|
594
|
+
onClose(cb) {
|
|
595
|
+
if (typeof cb !== 'function') throw new TypeError('mesh-channel: onClose needs a function')
|
|
596
|
+
if (closed) { queueMicrotask(() => cb(closeError)); return () => {} }
|
|
597
|
+
closeListeners.add(cb)
|
|
598
|
+
return () => closeListeners.delete(cb)
|
|
599
|
+
},
|
|
600
|
+
close(reason) { close(reason) },
|
|
601
|
+
/** Introspection for tests and dashboards. */
|
|
602
|
+
stats() {
|
|
603
|
+
return { creditBytes: credit, heldBytes: held, queuedMessages: sendQueue.length, queuedBytes: sendQueue.reduce((n, q) => n + q.bytes.byteLength - q.offset, 0), pendingRequests: pending.size, activeRequests: incoming.size }
|
|
604
|
+
},
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
return { link, receive, open, close, get remoteSid() { return remoteSid }, get helloSent() { return helloSent } }
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* MeshService descriptor: one channel link per peer over `ctx.sendTo` /
|
|
612
|
+
* `ctx.onIncomingData`.
|
|
613
|
+
*
|
|
614
|
+
* @param {object} [opts]
|
|
615
|
+
* @param {string} [opts.envelopeType='mesh-channel']
|
|
616
|
+
* @param {(peer: string) => (boolean|undefined)} [opts.peerSupports] - return false to refuse to open (nothing is sent)
|
|
617
|
+
* @param {(peer: string) => boolean} [opts.acceptPeer] - return false to refuse an inbound hello (default: accept)
|
|
618
|
+
* @param {number} [opts.maxPeers=64] - links held at once; a hello beyond it is refused
|
|
619
|
+
* @param {(link: object) => void} [opts.onLink] - called synchronously for each link, inbound or outbound, the moment it is ready:
|
|
620
|
+
* register `onRequest` / `onNotification` / `onMessage` handlers here, so no request can arrive before them
|
|
621
|
+
* Link limits (`maxMessageBytes`, `window`, `maxInflight`, `chunkBytes`,
|
|
622
|
+
* `requestTimeoutMs`, `handshakeTimeoutMs`, `features`) are passed to every link.
|
|
623
|
+
*/
|
|
624
|
+
export function createMeshChannelService({
|
|
625
|
+
envelopeType = CHANNEL_ENVELOPE_TYPE,
|
|
626
|
+
peerSupports,
|
|
627
|
+
acceptPeer,
|
|
628
|
+
maxPeers = CHANNEL_DEFAULT_MAX_PEERS,
|
|
629
|
+
onLink,
|
|
630
|
+
onLog,
|
|
631
|
+
...limits
|
|
632
|
+
} = {}) {
|
|
633
|
+
if (!isPosInt(maxPeers)) throw new TypeError('createMeshChannelService: maxPeers must be a positive integer')
|
|
634
|
+
// Fail on a bad limit at construction rather than at the first hello.
|
|
635
|
+
createChannelCore({ peer: 'validate', sendFrame() {}, ...limits })
|
|
636
|
+
const log = onLog || (() => {})
|
|
637
|
+
return {
|
|
638
|
+
name: 'mesh-channel',
|
|
639
|
+
attach(peerNode, ctx) {
|
|
640
|
+
let closed = false
|
|
641
|
+
const cores = new Map() // peer -> core
|
|
642
|
+
const linkListeners = new Set()
|
|
643
|
+
if (onLink) linkListeners.add(onLink)
|
|
644
|
+
|
|
645
|
+
function makeCore(peer) {
|
|
646
|
+
const core = createChannelCore({
|
|
647
|
+
peer,
|
|
648
|
+
sendFrame: f => ctx.sendTo(peer, envelopeType, f),
|
|
649
|
+
onLog: (event, data) => log(event, data),
|
|
650
|
+
onReady: link => {
|
|
651
|
+
for (const cb of [...linkListeners]) { try { cb(link) } catch (e) { log('mesh-channel:on-link-threw', { peer, error: e?.message }) } }
|
|
652
|
+
ctx.emit('mesh-channel:link-open', { peer })
|
|
653
|
+
},
|
|
654
|
+
...limits,
|
|
655
|
+
})
|
|
656
|
+
cores.set(peer, core)
|
|
657
|
+
core.link.onClose(() => { if (cores.get(peer) === core) cores.delete(peer) })
|
|
658
|
+
return core
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
const unsubscribe = ctx.onIncomingData(envelopeType, (from, msg) => {
|
|
662
|
+
if (closed || typeof from !== 'string' || !from) return
|
|
663
|
+
// `from` is the session's verified key; msg only ever carries frame fields.
|
|
664
|
+
let core = cores.get(from)
|
|
665
|
+
if (msg.k === 'hello') {
|
|
666
|
+
if (core && core.remoteSid && core.remoteSid !== msg.sid) {
|
|
667
|
+
// The peer restarted: the old link can never continue.
|
|
668
|
+
core.close(err(ChannelErrorCode.CANCELLED, 'channel-reset', 'the peer opened a new channel'), { notifyRemote: false })
|
|
669
|
+
core = undefined
|
|
670
|
+
}
|
|
671
|
+
if (!core) {
|
|
672
|
+
if (cores.size >= maxPeers || (acceptPeer && acceptPeer(from) === false)) {
|
|
673
|
+
ctx.sendTo(from, envelopeType, { k: 'hello-ack', error: { c: ChannelErrorCode.BUSY, r: 'refused', m: 'channel refused' } }).catch(() => {})
|
|
674
|
+
return
|
|
675
|
+
}
|
|
676
|
+
core = makeCore(from)
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
core?.receive(msg)
|
|
680
|
+
})
|
|
681
|
+
|
|
682
|
+
async function open(peer, { timeoutMs } = {}) {
|
|
683
|
+
if (closed) throw new Error('mesh-channel: service torn down')
|
|
684
|
+
if (typeof peer !== 'string' || !peer || peer.length > 512) throw new TypeError('mesh-channel: peer must identify one peer')
|
|
685
|
+
if (peerSupports && peerSupports(peer) === false) {
|
|
686
|
+
throw err(ChannelErrorCode.UNSUPPORTED, 'unsupported', 'the peer is known not to support mesh-channel; nothing was sent')
|
|
687
|
+
}
|
|
688
|
+
let core = cores.get(peer)
|
|
689
|
+
if (!core) {
|
|
690
|
+
if (cores.size >= maxPeers) throw err(ChannelErrorCode.BUSY, 'too-many-peers', 'too many channel links')
|
|
691
|
+
core = makeCore(peer)
|
|
692
|
+
}
|
|
693
|
+
await core.open(timeoutMs === undefined ? undefined : { timeoutMs })
|
|
694
|
+
return core.link
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
return {
|
|
698
|
+
api: {
|
|
699
|
+
open,
|
|
700
|
+
/** The ready link for a peer, if one exists. */
|
|
701
|
+
link: peer => { const c = cores.get(peer); return c && !c.link.closed ? c.link : undefined },
|
|
702
|
+
/** Subscribe to every link that becomes ready (inbound or outbound). */
|
|
703
|
+
onLink(cb) { linkListeners.add(cb); return () => linkListeners.delete(cb) },
|
|
704
|
+
get peers() { return [...cores.keys()] },
|
|
705
|
+
},
|
|
706
|
+
teardown() {
|
|
707
|
+
if (closed) return
|
|
708
|
+
closed = true
|
|
709
|
+
unsubscribe()
|
|
710
|
+
for (const core of [...cores.values()]) core.close(err(ChannelErrorCode.CANCELLED, 'channel-closed', 'service torn down'))
|
|
711
|
+
cores.clear()
|
|
712
|
+
},
|
|
713
|
+
}
|
|
714
|
+
},
|
|
715
|
+
}
|
|
716
|
+
}
|