@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/index.mjs
CHANGED
|
@@ -26,6 +26,7 @@ export * from './peer-node.mjs';
|
|
|
26
26
|
export * from './peer-node-transport.mjs';
|
|
27
27
|
export * from './signaling.mjs';
|
|
28
28
|
export * from './webrtc-negotiator.mjs';
|
|
29
|
+
export * from './wsh-negotiator.mjs';
|
|
29
30
|
export * from './mesh-bootstrap.mjs';
|
|
30
31
|
export * from './mesh-sync.mjs';
|
|
31
32
|
export * from './mesh-dht.mjs';
|
|
@@ -47,6 +48,8 @@ export * from './key-distribution.mjs';
|
|
|
47
48
|
export * from './manifest-sync.mjs';
|
|
48
49
|
export * from './chunk-replication.mjs';
|
|
49
50
|
export * from './mesh-rpc.mjs';
|
|
51
|
+
export * from './mesh-channel.mjs';
|
|
52
|
+
export * from './protocol-channel.mjs';
|
|
50
53
|
export * from './mesh-keepalive.mjs';
|
|
51
54
|
export * from './mesh-fetch.mjs';
|
|
52
55
|
export * from './mesh-websocket.mjs';
|
|
@@ -66,6 +69,15 @@ export * from './pod-host-service.mjs';
|
|
|
66
69
|
export * from './pod-host-routes.mjs';
|
|
67
70
|
export * from './pod-host-gateway.mjs';
|
|
68
71
|
export * from './pod-supervisor.mjs';
|
|
72
|
+
export {
|
|
73
|
+
planPlacement,
|
|
74
|
+
HostHealth,
|
|
75
|
+
PlacementLedger,
|
|
76
|
+
createHostPool,
|
|
77
|
+
BOUNDARY as PLACEMENT_BOUNDARY,
|
|
78
|
+
TRUST as REQUESTER_TRUST,
|
|
79
|
+
} from './pod-placement.mjs';
|
|
80
|
+
export { decideRestart, restartDelayMs, policyWantsRestart } from './restart-policy.mjs';
|
|
69
81
|
export * from './peer-payments.mjs';
|
|
70
82
|
export * from './peer-registry.mjs';
|
|
71
83
|
export * from './peer-routing.mjs';
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small self-contained, binary-safe value codec for the message channel.
|
|
3
|
+
*
|
|
4
|
+
* Values: null, booleans, finite numbers, strings, Uint8Array (native bytes),
|
|
5
|
+
* arrays and plain objects (string keys). `undefined` object members are
|
|
6
|
+
* skipped; `undefined` inside an array becomes null. Anything else (functions,
|
|
7
|
+
* symbols, bigint, NaN/Infinity, cycles, class instances other than typed
|
|
8
|
+
* arrays/ArrayBuffer) throws a TypeError at encode time.
|
|
9
|
+
*
|
|
10
|
+
* Layout: one tag byte, then for ints a zigzag varint, for f64 8 big-endian
|
|
11
|
+
* bytes, for string/bytes a varint length plus the payload, for array/map a
|
|
12
|
+
* varint count followed by the items (map: key string, value). Every length
|
|
13
|
+
* is checked against the bytes actually remaining before anything is
|
|
14
|
+
* allocated, and depth is bounded, so a malformed frame cannot make the decoder
|
|
15
|
+
* allocate more than its own size.
|
|
16
|
+
*/
|
|
17
|
+
const T_NULL = 0, T_FALSE = 1, T_TRUE = 2, T_INT = 3, T_F64 = 4, T_STR = 5, T_BYTES = 6, T_ARR = 7, T_MAP = 8
|
|
18
|
+
const MAX_DEPTH = 32
|
|
19
|
+
const textEncoder = new TextEncoder()
|
|
20
|
+
const textDecoder = new TextDecoder('utf-8', { fatal: true })
|
|
21
|
+
|
|
22
|
+
function viewOf(value) {
|
|
23
|
+
if (value instanceof Uint8Array) return value
|
|
24
|
+
if (value instanceof ArrayBuffer) return new Uint8Array(value)
|
|
25
|
+
if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength)
|
|
26
|
+
return null
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
class Writer {
|
|
30
|
+
constructor() { this.parts = []; this.length = 0 }
|
|
31
|
+
byte(b) { this.parts.push(Uint8Array.of(b)); this.length += 1 }
|
|
32
|
+
raw(bytes) { this.parts.push(bytes); this.length += bytes.byteLength }
|
|
33
|
+
varint(n) {
|
|
34
|
+
const out = []
|
|
35
|
+
while (n >= 0x80) { out.push((n % 0x80) | 0x80); n = Math.floor(n / 0x80) }
|
|
36
|
+
out.push(n)
|
|
37
|
+
this.raw(Uint8Array.from(out))
|
|
38
|
+
}
|
|
39
|
+
done() {
|
|
40
|
+
const out = new Uint8Array(this.length)
|
|
41
|
+
let at = 0
|
|
42
|
+
for (const part of this.parts) { out.set(part, at); at += part.byteLength }
|
|
43
|
+
return out
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function write(w, value, depth, seen) {
|
|
48
|
+
if (depth > MAX_DEPTH) throw new TypeError('channel codec: value nested too deeply')
|
|
49
|
+
if (value === null || value === undefined) return w.byte(T_NULL)
|
|
50
|
+
if (value === true) return w.byte(T_TRUE)
|
|
51
|
+
if (value === false) return w.byte(T_FALSE)
|
|
52
|
+
if (typeof value === 'number') {
|
|
53
|
+
if (!Number.isFinite(value)) throw new TypeError('channel codec: numbers must be finite')
|
|
54
|
+
if (Number.isSafeInteger(value) && !Object.is(value, -0)) {
|
|
55
|
+
w.byte(T_INT)
|
|
56
|
+
return w.varint(value >= 0 ? value * 2 : -value * 2 - 1)
|
|
57
|
+
}
|
|
58
|
+
w.byte(T_F64)
|
|
59
|
+
const buf = new Uint8Array(8)
|
|
60
|
+
new DataView(buf.buffer).setFloat64(0, value)
|
|
61
|
+
return w.raw(buf)
|
|
62
|
+
}
|
|
63
|
+
if (typeof value === 'string') {
|
|
64
|
+
const bytes = textEncoder.encode(value)
|
|
65
|
+
w.byte(T_STR); w.varint(bytes.byteLength)
|
|
66
|
+
return w.raw(bytes)
|
|
67
|
+
}
|
|
68
|
+
const bytes = viewOf(value)
|
|
69
|
+
if (bytes) {
|
|
70
|
+
w.byte(T_BYTES); w.varint(bytes.byteLength)
|
|
71
|
+
return w.raw(bytes)
|
|
72
|
+
}
|
|
73
|
+
if (typeof value !== 'object') throw new TypeError(`channel codec: cannot encode a ${typeof value}`)
|
|
74
|
+
if (seen.has(value)) throw new TypeError('channel codec: cyclic value')
|
|
75
|
+
seen.add(value)
|
|
76
|
+
if (Array.isArray(value)) {
|
|
77
|
+
w.byte(T_ARR); w.varint(value.length)
|
|
78
|
+
for (let i = 0; i < value.length; i++) write(w, value[i], depth + 1, seen)
|
|
79
|
+
} else {
|
|
80
|
+
const proto = Object.getPrototypeOf(value)
|
|
81
|
+
if (proto !== Object.prototype && proto !== null) throw new TypeError('channel codec: only plain objects can be encoded')
|
|
82
|
+
const keys = Object.keys(value).filter(k => value[k] !== undefined)
|
|
83
|
+
w.byte(T_MAP); w.varint(keys.length)
|
|
84
|
+
for (const key of keys) {
|
|
85
|
+
const k = textEncoder.encode(key)
|
|
86
|
+
w.varint(k.byteLength); w.raw(k)
|
|
87
|
+
write(w, value[key], depth + 1, seen)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
seen.delete(value)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** @param {*} value @returns {Uint8Array} */
|
|
94
|
+
export function encodeValue(value) {
|
|
95
|
+
const w = new Writer()
|
|
96
|
+
write(w, value, 0, new Set())
|
|
97
|
+
return w.done()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
class Reader {
|
|
101
|
+
constructor(bytes) { this.bytes = bytes; this.at = 0 }
|
|
102
|
+
left() { return this.bytes.byteLength - this.at }
|
|
103
|
+
byte() {
|
|
104
|
+
if (this.at >= this.bytes.byteLength) throw new RangeError('channel codec: truncated value')
|
|
105
|
+
return this.bytes[this.at++]
|
|
106
|
+
}
|
|
107
|
+
varint() {
|
|
108
|
+
let n = 0, scale = 1
|
|
109
|
+
for (let i = 0; i < 8; i++) {
|
|
110
|
+
const b = this.byte()
|
|
111
|
+
n += (b & 0x7f) * scale
|
|
112
|
+
if (!(b & 0x80)) return n
|
|
113
|
+
scale *= 0x80
|
|
114
|
+
}
|
|
115
|
+
throw new RangeError('channel codec: varint too long')
|
|
116
|
+
}
|
|
117
|
+
take(len) {
|
|
118
|
+
if (!Number.isSafeInteger(len) || len < 0 || len > this.left()) throw new RangeError('channel codec: length exceeds the frame')
|
|
119
|
+
const out = this.bytes.subarray(this.at, this.at + len)
|
|
120
|
+
this.at += len
|
|
121
|
+
return out
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function read(r, depth) {
|
|
126
|
+
if (depth > MAX_DEPTH) throw new RangeError('channel codec: value nested too deeply')
|
|
127
|
+
switch (r.byte()) {
|
|
128
|
+
case T_NULL: return null
|
|
129
|
+
case T_FALSE: return false
|
|
130
|
+
case T_TRUE: return true
|
|
131
|
+
case T_INT: { const n = r.varint(); return n % 2 ? -(n + 1) / 2 : n / 2 }
|
|
132
|
+
case T_F64: return new DataView(r.take(8).slice().buffer).getFloat64(0)
|
|
133
|
+
case T_STR: return textDecoder.decode(r.take(r.varint()))
|
|
134
|
+
case T_BYTES: return r.take(r.varint()).slice()
|
|
135
|
+
case T_ARR: {
|
|
136
|
+
const count = r.varint()
|
|
137
|
+
if (count > r.left()) throw new RangeError('channel codec: count exceeds the frame')
|
|
138
|
+
const out = []
|
|
139
|
+
for (let i = 0; i < count; i++) out.push(read(r, depth + 1))
|
|
140
|
+
return out
|
|
141
|
+
}
|
|
142
|
+
case T_MAP: {
|
|
143
|
+
const count = r.varint()
|
|
144
|
+
if (count > r.left()) throw new RangeError('channel codec: count exceeds the frame')
|
|
145
|
+
const out = {}
|
|
146
|
+
for (let i = 0; i < count; i++) {
|
|
147
|
+
const key = textDecoder.decode(r.take(r.varint()))
|
|
148
|
+
// defineProperty so a "__proto__" key stays an own data member.
|
|
149
|
+
Object.defineProperty(out, key, { value: read(r, depth + 1), enumerable: true, writable: true, configurable: true })
|
|
150
|
+
}
|
|
151
|
+
return out
|
|
152
|
+
}
|
|
153
|
+
default: throw new TypeError('channel codec: unknown tag')
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** @param {Uint8Array} bytes @returns {*} */
|
|
158
|
+
export function decodeValue(bytes) {
|
|
159
|
+
const r = new Reader(bytes)
|
|
160
|
+
const value = read(r, 0)
|
|
161
|
+
if (r.left() !== 0) throw new RangeError('channel codec: trailing bytes')
|
|
162
|
+
return value
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Bytes -> base64 text; the wire envelope is JSON so this stays internal to the framing. */
|
|
166
|
+
export function toBase64(bytes) {
|
|
167
|
+
let text = ''
|
|
168
|
+
for (let i = 0; i < bytes.length; i += 8192) text += String.fromCharCode(...bytes.subarray(i, i + 8192))
|
|
169
|
+
return btoa(text)
|
|
170
|
+
}
|
|
171
|
+
/** Base64 text -> bytes, refusing anything over `maxBytes` before decoding. */
|
|
172
|
+
export function fromBase64(text, maxBytes) {
|
|
173
|
+
if (typeof text !== 'string') throw new TypeError('channel codec: expected base64 text')
|
|
174
|
+
if (text.length > 4 * Math.ceil(maxBytes / 3)) throw new RangeError('channel codec: chunk exceeds the limit')
|
|
175
|
+
if (text.length % 4 || !/^[A-Za-z0-9+/]*={0,2}$/.test(text)) throw new TypeError('channel codec: invalid base64')
|
|
176
|
+
const binary = atob(text)
|
|
177
|
+
if (binary.length > maxBytes) throw new RangeError('channel codec: chunk exceeds the limit')
|
|
178
|
+
return Uint8Array.from(binary, ch => ch.charCodeAt(0))
|
|
179
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read one JSON message from a netway `StreamSocket`.
|
|
3
|
+
*
|
|
4
|
+
* A socket is a byte stream: a socket with a receive window hands a write
|
|
5
|
+
* larger than that window to its reader in window-sized pieces, so one JSON
|
|
6
|
+
* message may arrive as several `read()` results. The request/response
|
|
7
|
+
* protocols in this package send one JSON document per write, so the reader
|
|
8
|
+
* puts the pieces back together: after a piece that fills the whole window
|
|
9
|
+
* (the only kind that can be followed by more of the same message) it reads
|
|
10
|
+
* on and parses the concatenation. A shorter piece, or a socket with no
|
|
11
|
+
* window, ends the message.
|
|
12
|
+
*
|
|
13
|
+
* @param {{ read(): Promise<Uint8Array|null>, windowBytes?: number }} socket
|
|
14
|
+
* @returns {Promise<{ eof: true } | { eof: false, text: string, value?: any, error?: Error }>}
|
|
15
|
+
* `eof` when the peer closed before sending anything; otherwise the decoded
|
|
16
|
+
* text and either the parsed `value` or the parse `error`.
|
|
17
|
+
*/
|
|
18
|
+
export async function readJsonMessage(socket) {
|
|
19
|
+
const first = await socket.read()
|
|
20
|
+
if (first === null) return { eof: true }
|
|
21
|
+
const window = socket.windowBytes ?? 0
|
|
22
|
+
const parts = [first]
|
|
23
|
+
let last = first
|
|
24
|
+
while (true) {
|
|
25
|
+
const bytes = parts.length === 1 ? first : concat(parts)
|
|
26
|
+
const text = new TextDecoder().decode(bytes)
|
|
27
|
+
try {
|
|
28
|
+
return { eof: false, text, value: JSON.parse(text) }
|
|
29
|
+
} catch (error) {
|
|
30
|
+
if (!(window > 0 && last.length >= window)) return { eof: false, text, error }
|
|
31
|
+
}
|
|
32
|
+
const next = await socket.read()
|
|
33
|
+
if (next === null) {
|
|
34
|
+
const text2 = new TextDecoder().decode(concat(parts))
|
|
35
|
+
return { eof: false, text: text2, error: new Error('socket closed in the middle of a message') }
|
|
36
|
+
}
|
|
37
|
+
parts.push(next)
|
|
38
|
+
last = next
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function concat(parts) {
|
|
43
|
+
let n = 0
|
|
44
|
+
for (const p of parts) n += p.length
|
|
45
|
+
const out = new Uint8Array(n)
|
|
46
|
+
let off = 0
|
|
47
|
+
for (const p of parts) { out.set(p, off); off += p.length }
|
|
48
|
+
return out
|
|
49
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* relay-flow.mjs -- byte credits for relayed connections.
|
|
3
|
+
*
|
|
4
|
+
* Each side of a relayed connection tells the other, when the connection is
|
|
5
|
+
* set up, how many bytes it is willing to have outstanding toward it (its
|
|
6
|
+
* window). The sender may have at most that many bytes sent and not yet
|
|
7
|
+
* credited. The receiver returns credit as it consumes bytes. A sender that
|
|
8
|
+
* has used its whole window stops reading from its local socket until the
|
|
9
|
+
* credit it holds is back above `window - lowWater` (pause at the high-water
|
|
10
|
+
* mark, resume under the low-water mark). Nothing is dropped; a peer that
|
|
11
|
+
* exceeds a bound has its connection closed with a reason.
|
|
12
|
+
*
|
|
13
|
+
* A peer that does not advertise a window (an older version) is not sent
|
|
14
|
+
* credit frames and cannot be paused; only the buffer bounds apply to it.
|
|
15
|
+
*
|
|
16
|
+
* No browser-only imports at module level.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** Defaults for relayed-connection flow control. All are options of `MeshRelayHost` / `createMeshRelayBackend`. */
|
|
20
|
+
export const RELAY_FLOW_DEFAULTS = Object.freeze({
|
|
21
|
+
/** Receive window per connection: bytes a peer may have outstanding toward us; pause point. */
|
|
22
|
+
highWaterBytes: 256 * 1024,
|
|
23
|
+
/** A paused sender resumes once its outstanding bytes are at or below this. */
|
|
24
|
+
lowWaterBytes: 64 * 1024,
|
|
25
|
+
/** Hard cap on bytes received and not yet consumed, per connection. */
|
|
26
|
+
maxBufferedBytesPerConnection: 1024 * 1024,
|
|
27
|
+
/** Hard cap on the same, summed over one peer's connections (host side). */
|
|
28
|
+
maxBufferedBytesPerPeer: 4 * 1024 * 1024,
|
|
29
|
+
/** Most connections (open or being opened) one peer may hold (host side). */
|
|
30
|
+
maxConnectionsPerPeer: 16,
|
|
31
|
+
/** Largest data frame we send, in bytes before base64. */
|
|
32
|
+
maxFrameBytes: 64 * 1024,
|
|
33
|
+
/** How often the host re-checks access of open connections, ms. 0 disables. */
|
|
34
|
+
recheckIntervalMs: 30_000,
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Merge options over the defaults and validate them.
|
|
39
|
+
* @param {object} [opts]
|
|
40
|
+
* @returns {typeof RELAY_FLOW_DEFAULTS}
|
|
41
|
+
*/
|
|
42
|
+
export function resolveFlowOptions(opts = {}) {
|
|
43
|
+
const out = { ...RELAY_FLOW_DEFAULTS }
|
|
44
|
+
for (const key of Object.keys(out)) {
|
|
45
|
+
if (opts[key] === undefined) continue
|
|
46
|
+
const v = opts[key]
|
|
47
|
+
const min = key === 'recheckIntervalMs' ? 0 : 1
|
|
48
|
+
if (!Number.isInteger(v) || v < min) throw new Error(`${key} must be an integer >= ${min}`)
|
|
49
|
+
out[key] = v
|
|
50
|
+
}
|
|
51
|
+
if (out.lowWaterBytes >= out.highWaterBytes) throw new Error('lowWaterBytes must be below highWaterBytes')
|
|
52
|
+
if (out.highWaterBytes > out.maxBufferedBytesPerConnection) {
|
|
53
|
+
throw new Error('highWaterBytes must not exceed maxBufferedBytesPerConnection')
|
|
54
|
+
}
|
|
55
|
+
return Object.freeze(out)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The sending side of one direction of one connection. */
|
|
59
|
+
export class CreditSender {
|
|
60
|
+
#window
|
|
61
|
+
#lowWater
|
|
62
|
+
#inFlight = 0
|
|
63
|
+
#paused = false
|
|
64
|
+
#closed = false
|
|
65
|
+
#waiters = []
|
|
66
|
+
|
|
67
|
+
/** @param {{ window: number, lowWater: number }} opts - `window` 0 or missing: no flow control */
|
|
68
|
+
constructor({ window, lowWater }) {
|
|
69
|
+
this.#window = Number.isInteger(window) && window > 0 ? window : 0
|
|
70
|
+
this.#lowWater = Math.min(lowWater, Math.max(0, this.#window - 1))
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
get enabled() { return this.#window > 0 }
|
|
74
|
+
get inFlight() { return this.#inFlight }
|
|
75
|
+
get paused() { return this.#paused }
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Wait until some bytes may be sent and reserve them.
|
|
79
|
+
* @param {number} want
|
|
80
|
+
* @returns {Promise<number>} bytes reserved (1..want), or 0 if closed
|
|
81
|
+
*/
|
|
82
|
+
async reserve(want) {
|
|
83
|
+
if (!this.enabled) return this.#closed ? 0 : want
|
|
84
|
+
for (;;) {
|
|
85
|
+
if (this.#closed) return 0
|
|
86
|
+
if (!this.#paused) {
|
|
87
|
+
const n = Math.min(want, this.#window - this.#inFlight)
|
|
88
|
+
if (n > 0) {
|
|
89
|
+
this.#inFlight += n
|
|
90
|
+
if (this.#inFlight >= this.#window) this.#paused = true
|
|
91
|
+
return n
|
|
92
|
+
}
|
|
93
|
+
this.#paused = true
|
|
94
|
+
}
|
|
95
|
+
await new Promise((resolve) => this.#waiters.push(resolve))
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Credit returned by the peer.
|
|
101
|
+
* @param {number} n
|
|
102
|
+
* @returns {boolean} false if the credit is invalid (more than is in flight)
|
|
103
|
+
*/
|
|
104
|
+
credit(n) {
|
|
105
|
+
if (!Number.isInteger(n) || n <= 0 || n > this.#inFlight) return false
|
|
106
|
+
this.#inFlight -= n
|
|
107
|
+
if (this.#paused && this.#inFlight <= this.#lowWater) {
|
|
108
|
+
this.#paused = false
|
|
109
|
+
this.#wake()
|
|
110
|
+
}
|
|
111
|
+
return true
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
close() {
|
|
115
|
+
this.#closed = true
|
|
116
|
+
this.#wake()
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
#wake() {
|
|
120
|
+
const waiters = this.#waiters.splice(0)
|
|
121
|
+
for (const w of waiters) w()
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The receiving side of one direction of one connection. */
|
|
126
|
+
export class CreditReceiver {
|
|
127
|
+
#window
|
|
128
|
+
#lowWater
|
|
129
|
+
#maxBuffered
|
|
130
|
+
#creditAware
|
|
131
|
+
#grant
|
|
132
|
+
#outstanding = 0
|
|
133
|
+
#pending = 0
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* @param {object} opts
|
|
137
|
+
* @param {number} opts.window - the window we advertised
|
|
138
|
+
* @param {number} opts.lowWater
|
|
139
|
+
* @param {number} opts.maxBuffered - hard cap on unconsumed bytes
|
|
140
|
+
* @param {boolean} opts.creditAware - the peer honours credit (it advertised a window or answered with one)
|
|
141
|
+
* @param {(bytes: number) => void} opts.grant - send a credit frame
|
|
142
|
+
*/
|
|
143
|
+
constructor({ window, lowWater, maxBuffered, creditAware, grant }) {
|
|
144
|
+
this.#window = window
|
|
145
|
+
this.#lowWater = lowWater
|
|
146
|
+
this.#maxBuffered = maxBuffered
|
|
147
|
+
this.#creditAware = creditAware
|
|
148
|
+
this.#grant = grant
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Bytes received and not yet consumed. */
|
|
152
|
+
get outstanding() { return this.#outstanding }
|
|
153
|
+
get creditAware() { return this.#creditAware }
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Account for `n` bytes that arrived.
|
|
157
|
+
* @param {number} n
|
|
158
|
+
* @returns {'ok'|'violation'|'overflow'} violation: a credit-aware peer went over its window
|
|
159
|
+
*/
|
|
160
|
+
receive(n) {
|
|
161
|
+
if (this.#creditAware && this.#outstanding + this.#pending + n > this.#window) return 'violation'
|
|
162
|
+
if (this.#outstanding + n > this.#maxBuffered) return 'overflow'
|
|
163
|
+
this.#outstanding += n
|
|
164
|
+
return 'ok'
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** `n` bytes have been handed on; return credit in batches. */
|
|
168
|
+
consumed(n) {
|
|
169
|
+
this.#outstanding -= n
|
|
170
|
+
if (!this.#creditAware) return
|
|
171
|
+
this.#pending += n
|
|
172
|
+
if (this.#pending >= this.#window - this.#lowWater) {
|
|
173
|
+
const give = this.#pending
|
|
174
|
+
this.#pending = 0
|
|
175
|
+
this.#grant(give)
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|