@johnhenry/browsermesh-primitives 0.0.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.
@@ -0,0 +1,474 @@
1
+ /**
2
+ * test-transport.mjs — In-memory transport for unit and integration testing.
3
+ *
4
+ * Provides LocalChannel (PodChannel implementation), TestMesh (multi-pod
5
+ * fully-connected topology), and DeterministicRNG (seeded mulberry32).
6
+ *
7
+ * No browser dependencies. Zero external imports.
8
+ *
9
+ * Run tests:
10
+ * node --test web/packages/mesh-primitives/test/test-transport.test.mjs
11
+ */
12
+
13
+ // ---------------------------------------------------------------------------
14
+ // Limits
15
+ // ---------------------------------------------------------------------------
16
+
17
+ export const TESTMESH_LIMITS = Object.freeze({
18
+ maxPods: 64,
19
+ maxQueueSize: 10_000,
20
+ maxLatencyMs: 10_000,
21
+ maxJitterMs: 5_000,
22
+ maxConcurrentMeshes: 8,
23
+ })
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // DeterministicRNG — mulberry32
27
+ // ---------------------------------------------------------------------------
28
+
29
+ export class DeterministicRNG {
30
+ #state
31
+
32
+ /** @param {number} [seed] */
33
+ constructor(seed) {
34
+ this.#state = seed ?? Date.now()
35
+ }
36
+
37
+ /** Return a pseudo-random float in [0, 1) */
38
+ next() {
39
+ this.#state |= 0
40
+ this.#state = (this.#state + 0x6d2b79f5) | 0
41
+ let t = Math.imul(this.#state ^ (this.#state >>> 15), 1 | this.#state)
42
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
43
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
44
+ }
45
+
46
+ /** Reset to a new seed for replay */
47
+ reset(seed) {
48
+ this.#state = seed
49
+ }
50
+ }
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // LocalChannelOptions defaults
54
+ // ---------------------------------------------------------------------------
55
+
56
+ const LOCAL_CHANNEL_DEFAULTS = Object.freeze({
57
+ latencyMs: 0,
58
+ jitterMs: 0,
59
+ dropRate: 0,
60
+ reorderRate: 0,
61
+ maxQueueSize: 1000,
62
+ seed: undefined, // will use Date.now() in DeterministicRNG
63
+ })
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // LocalChannel — in-memory PodChannel
67
+ // ---------------------------------------------------------------------------
68
+
69
+ /**
70
+ * In-memory implementation of the PodChannel interface.
71
+ * Paired via createLocalChannelPair(). Messages sent on one end are
72
+ * delivered to the peer's onmessage handler with configurable latency,
73
+ * jitter, drop rate, and reorder rate.
74
+ */
75
+ export class LocalChannel {
76
+ /** @type {string} */
77
+ id
78
+
79
+ /** @type {'message-port'} */
80
+ type = 'message-port'
81
+
82
+ /** @type {'connecting'|'open'|'closing'|'closed'} */
83
+ state = 'open'
84
+
85
+ /** @type {((event: {data: unknown, source?: LocalChannel}) => void)|null} */
86
+ onmessage = null
87
+
88
+ /** @type {((error: {code: string, message: string, fatal: boolean}) => void)|null} */
89
+ onerror = null
90
+
91
+ /** @type {(() => void)|null} */
92
+ onclose = null
93
+
94
+ /** @type {LocalChannel|null} */
95
+ #peer = null
96
+
97
+ /** @type {Array<{data: unknown, source?: LocalChannel}>} */
98
+ #queue = []
99
+
100
+ #options
101
+ #rng
102
+ #pendingTimers = new Set()
103
+
104
+ /**
105
+ * @param {string} [id]
106
+ * @param {object} [options]
107
+ */
108
+ constructor(id, options) {
109
+ this.id = id ?? `lc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`
110
+ this.#options = { ...LOCAL_CHANNEL_DEFAULTS, ...options }
111
+ this.#rng = new DeterministicRNG(this.#options.seed)
112
+ }
113
+
114
+ /** @internal Connect this channel to its peer */
115
+ _setPeer(peer) {
116
+ this.#peer = peer
117
+ }
118
+
119
+ /** @internal Expose options for fault injection */
120
+ get _options() {
121
+ return this.#options
122
+ }
123
+
124
+ /** Number of buffered messages */
125
+ get queueLength() {
126
+ return this.#queue.length
127
+ }
128
+
129
+ /**
130
+ * Send a message to the paired channel.
131
+ * Respects configured latency, jitter, drop rate, and reorder rate.
132
+ *
133
+ * @param {unknown} data
134
+ * @param {Transferable[]} [_transfer] - Ignored (for PodChannel compat)
135
+ */
136
+ send(data, _transfer) {
137
+ if (this.state !== 'open') {
138
+ this.onerror?.({
139
+ code: 'CHANNEL_CLOSED',
140
+ message: 'Cannot send on closed channel',
141
+ fatal: false,
142
+ })
143
+ return
144
+ }
145
+
146
+ if (!this.#peer || this.#peer.state !== 'open') {
147
+ this.onerror?.({
148
+ code: 'PEER_CLOSED',
149
+ message: 'Peer channel is closed',
150
+ fatal: false,
151
+ })
152
+ return
153
+ }
154
+
155
+ // Check queue capacity on peer
156
+ if (this.#peer.#queue.length >= this.#options.maxQueueSize) {
157
+ this.onerror?.({
158
+ code: 'QUEUE_FULL',
159
+ message: `Queue size exceeded (max: ${this.#options.maxQueueSize})`,
160
+ fatal: false,
161
+ })
162
+ return
163
+ }
164
+
165
+ // Simulate message drop
166
+ if (this.#rng.next() < this.#options.dropRate) {
167
+ return // Message silently dropped
168
+ }
169
+
170
+ const event = {
171
+ data: structuredClone(data),
172
+ source: this,
173
+ }
174
+
175
+ // Compute delivery delay
176
+ const baseLatency = this.#options.latencyMs
177
+ const jitter = this.#options.jitterMs * (this.#rng.next() * 2 - 1)
178
+ const delay = Math.max(0, baseLatency + jitter)
179
+
180
+ // Simulate reordering by adding extra random delay
181
+ const reorderDelay = this.#rng.next() < this.#options.reorderRate
182
+ ? this.#rng.next() * baseLatency * 2
183
+ : 0
184
+
185
+ const totalDelay = delay + reorderDelay
186
+
187
+ // Schedule delivery
188
+ if (totalDelay === 0) {
189
+ this.#peer.#deliver(event)
190
+ } else {
191
+ const peer = this.#peer
192
+ const timer = setTimeout(() => {
193
+ this.#pendingTimers.delete(timer)
194
+ if (peer.state === 'open') {
195
+ peer.#deliver(event)
196
+ }
197
+ }, totalDelay)
198
+ this.#pendingTimers.add(timer)
199
+ }
200
+ }
201
+
202
+ /** Close the channel and notify the peer */
203
+ close() {
204
+ if (this.state === 'closed') return
205
+ this.state = 'closed'
206
+ this.#queue.length = 0
207
+ // Clear pending timers
208
+ for (const timer of this.#pendingTimers) {
209
+ clearTimeout(timer)
210
+ }
211
+ this.#pendingTimers.clear()
212
+ this.onclose?.()
213
+ }
214
+
215
+ /** Async iterator for consuming messages in tests */
216
+ [Symbol.asyncIterator]() {
217
+ return new LocalChannelIterator(this, this.#queue)
218
+ }
219
+
220
+ /** @internal Deliver a message to this channel's handler */
221
+ #deliver(event) {
222
+ if (this.state !== 'open') return
223
+ this.#queue.push(event)
224
+ this.onmessage?.(event)
225
+ }
226
+ }
227
+
228
+ // ---------------------------------------------------------------------------
229
+ // LocalChannelIterator — AsyncIterator adapter
230
+ // ---------------------------------------------------------------------------
231
+
232
+ class LocalChannelIterator {
233
+ #buffer = []
234
+ #resolve = null
235
+ #done = false
236
+
237
+ constructor(channel, existingQueue) {
238
+ // Drain any already-buffered messages
239
+ if (existingQueue && existingQueue.length > 0) {
240
+ this.#buffer.push(...existingQueue)
241
+ }
242
+
243
+ const originalOnMessage = channel.onmessage
244
+ channel.onmessage = (event) => {
245
+ originalOnMessage?.(event)
246
+ if (this.#resolve) {
247
+ const r = this.#resolve
248
+ this.#resolve = null
249
+ r({ value: event, done: false })
250
+ } else {
251
+ this.#buffer.push(event)
252
+ }
253
+ }
254
+
255
+ const originalOnClose = channel.onclose
256
+ channel.onclose = () => {
257
+ originalOnClose?.()
258
+ this.#done = true
259
+ if (this.#resolve) {
260
+ const r = this.#resolve
261
+ this.#resolve = null
262
+ r({ value: undefined, done: true })
263
+ }
264
+ }
265
+ }
266
+
267
+ async next() {
268
+ if (this.#buffer.length > 0) {
269
+ return { value: this.#buffer.shift(), done: false }
270
+ }
271
+ if (this.#done) {
272
+ return { value: undefined, done: true }
273
+ }
274
+ return new Promise((resolve) => {
275
+ this.#resolve = resolve
276
+ })
277
+ }
278
+
279
+ [Symbol.asyncIterator]() {
280
+ return this
281
+ }
282
+ }
283
+
284
+ // ---------------------------------------------------------------------------
285
+ // createLocalChannelPair
286
+ // ---------------------------------------------------------------------------
287
+
288
+ /**
289
+ * Create two connected LocalChannel instances.
290
+ * Like MessageChannel, but fully in-memory with configurable faults.
291
+ *
292
+ * @param {object} [options] - LocalChannelOptions
293
+ * @returns {[LocalChannel, LocalChannel]}
294
+ */
295
+ export function createLocalChannelPair(options) {
296
+ const idA = `lc_a_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`
297
+ const idB = `lc_b_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`
298
+
299
+ const channelA = new LocalChannel(idA, options)
300
+ const channelB = new LocalChannel(idB, options)
301
+
302
+ channelA._setPeer(channelB)
303
+ channelB._setPeer(channelA)
304
+
305
+ return [channelA, channelB]
306
+ }
307
+
308
+ // ---------------------------------------------------------------------------
309
+ // TestMesh — multi-pod fully-connected topology
310
+ // ---------------------------------------------------------------------------
311
+
312
+ /**
313
+ * Creates a fully-connected mesh of test pods with LocalChannel pairs
314
+ * between every pod. Supports fault injection (partition, latency, drop).
315
+ */
316
+ export class TestMesh {
317
+ /** @type {Array<{id: string, kind: string, channels: Map<number, LocalChannel>}>} */
318
+ pods
319
+
320
+ /** @type {Map<string, LocalChannel>} */
321
+ #channels = new Map()
322
+
323
+ /** @type {object} */
324
+ #defaultOptions
325
+
326
+ /** @param {Array} pods */
327
+ constructor(pods, defaultOptions) {
328
+ this.pods = pods
329
+ this.#defaultOptions = defaultOptions || {}
330
+ }
331
+
332
+ /**
333
+ * Create a mesh of n pods with LocalChannel connections between all pairs.
334
+ * For n pods, creates n*(n-1)/2 channel pairs.
335
+ *
336
+ * @param {number} n - Number of pods (2-64)
337
+ * @param {object} [options]
338
+ * @returns {Promise<TestMesh>}
339
+ */
340
+ static async create(n, options) {
341
+ if (n < 2 || n > TESTMESH_LIMITS.maxPods) {
342
+ throw new Error(`Pod count must be between 2 and ${TESTMESH_LIMITS.maxPods}`)
343
+ }
344
+
345
+ const kinds = options?.kinds ?? ['worker']
346
+ const pods = []
347
+
348
+ for (let i = 0; i < n; i++) {
349
+ pods.push({
350
+ id: `test-pod-${i}`,
351
+ kind: kinds[i % kinds.length],
352
+ channels: new Map(),
353
+ })
354
+ }
355
+
356
+ const mesh = new TestMesh(pods, options)
357
+
358
+ // Create channel pairs between all pods
359
+ for (let i = 0; i < n; i++) {
360
+ for (let j = i + 1; j < n; j++) {
361
+ const [channelA, channelB] = createLocalChannelPair(options)
362
+ pods[i].channels.set(j, channelA)
363
+ pods[j].channels.set(i, channelB)
364
+ mesh.#channels.set(`${i}-${j}`, channelA)
365
+ mesh.#channels.set(`${j}-${i}`, channelB)
366
+ }
367
+ }
368
+
369
+ return mesh
370
+ }
371
+
372
+ /**
373
+ * Get the LocalChannel from pod at fromIndex to pod at toIndex.
374
+ *
375
+ * @param {number} fromIndex
376
+ * @param {number} toIndex
377
+ * @returns {LocalChannel}
378
+ */
379
+ getChannel(fromIndex, toIndex) {
380
+ const channel = this.#channels.get(`${fromIndex}-${toIndex}`)
381
+ if (!channel) {
382
+ throw new Error(`No channel from pod ${fromIndex} to pod ${toIndex}`)
383
+ }
384
+ return channel
385
+ }
386
+
387
+ /**
388
+ * Inject a fault into the mesh.
389
+ *
390
+ * @param {{ type: 'partition'|'latency'|'message-drop', [key: string]: * }} fault
391
+ */
392
+ injectFault(fault) {
393
+ switch (fault.type) {
394
+ case 'partition':
395
+ this.#injectPartition(fault)
396
+ break
397
+ case 'latency':
398
+ this.#injectLatency(fault)
399
+ break
400
+ case 'message-drop':
401
+ this.#injectMessageDrop(fault)
402
+ break
403
+ default:
404
+ throw new Error(`Unsupported fault type for TestMesh: ${fault.type}`)
405
+ }
406
+ }
407
+
408
+ #injectPartition(fault) {
409
+ for (const podA of this.pods) {
410
+ if (!fault.groupA.includes(podA.id)) continue
411
+ for (const podB of this.pods) {
412
+ if (!fault.groupB.includes(podB.id)) continue
413
+ const idxA = this.pods.indexOf(podA)
414
+ const idxB = this.pods.indexOf(podB)
415
+
416
+ // Close both directions
417
+ this.#channels.get(`${idxA}-${idxB}`)?.close()
418
+ this.#channels.get(`${idxB}-${idxA}`)?.close()
419
+ }
420
+ }
421
+
422
+ // Auto-heal after duration
423
+ if (fault.duration && fault.duration > 0) {
424
+ setTimeout(() => this.#healPartition(fault), fault.duration)
425
+ }
426
+ }
427
+
428
+ #healPartition(fault) {
429
+ for (const podA of this.pods) {
430
+ if (!fault.groupA.includes(podA.id)) continue
431
+ for (const podB of this.pods) {
432
+ if (!fault.groupB.includes(podB.id)) continue
433
+ const idxA = this.pods.indexOf(podA)
434
+ const idxB = this.pods.indexOf(podB)
435
+
436
+ const [channelA, channelB] = createLocalChannelPair(this.#defaultOptions)
437
+ podA.channels.set(idxB, channelA)
438
+ podB.channels.set(idxA, channelB)
439
+ this.#channels.set(`${idxA}-${idxB}`, channelA)
440
+ this.#channels.set(`${idxB}-${idxA}`, channelB)
441
+ }
442
+ }
443
+ }
444
+
445
+ #injectLatency(fault) {
446
+ for (const pod of this.pods) {
447
+ if (fault.targets[0] !== '*' && !fault.targets.includes(pod.id)) continue
448
+ for (const [_, channel] of pod.channels) {
449
+ channel._options.latencyMs = fault.delayMs
450
+ channel._options.jitterMs = fault.jitterMs ?? 0
451
+ }
452
+ }
453
+ }
454
+
455
+ #injectMessageDrop(fault) {
456
+ for (const pod of this.pods) {
457
+ if (!fault.targets.includes(pod.id)) continue
458
+ for (const [_, channel] of pod.channels) {
459
+ channel._options.dropRate = fault.dropRate
460
+ }
461
+ }
462
+ }
463
+
464
+ /** Shut down all pods and close all channels */
465
+ async shutdown() {
466
+ for (const [_, channel] of this.#channels) {
467
+ channel.close()
468
+ }
469
+ this.#channels.clear()
470
+ for (const pod of this.pods) {
471
+ pod.channels.clear()
472
+ }
473
+ }
474
+ }
package/src/trust.mjs ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Categories of trust relationships between pods.
3
+ *
4
+ * @enum {string}
5
+ */
6
+ export const TRUST_CATEGORIES = Object.freeze({
7
+ /** Direct interaction history */
8
+ DIRECT: "direct",
9
+ /** Vouched for by a trusted peer */
10
+ TRANSITIVE: "transitive",
11
+ /** Shared group or federation membership */
12
+ MEMBERSHIP: "membership",
13
+ /** Reputation from external attestations */
14
+ REPUTATION: "reputation",
15
+ });
16
+
17
+ /**
18
+ * @typedef {object} TrustEdge
19
+ * @property {string} from - Truster pod ID
20
+ * @property {string} to - Trustee pod ID
21
+ * @property {string} category - One of TRUST_CATEGORIES
22
+ * @property {number} value - Trust level in [0.0, 1.0]
23
+ * @property {number} timestamp - Unix timestamp of last update
24
+ */
25
+
26
+ /**
27
+ * Create a trust edge.
28
+ *
29
+ * @param {object} opts
30
+ * @param {string} opts.from
31
+ * @param {string} opts.to
32
+ * @param {string} opts.category - One of TRUST_CATEGORIES
33
+ * @param {number} opts.value - Must be in [0.0, 1.0]
34
+ * @param {number} [opts.timestamp=Date.now()]
35
+ * @returns {TrustEdge}
36
+ */
37
+ export function createTrustEdge({ from, to, category, value, timestamp = Date.now() }) {
38
+ if (value < 0 || value > 1) {
39
+ throw new RangeError(`Trust value must be in [0.0, 1.0], got ${value}`);
40
+ }
41
+ return Object.freeze({ from, to, category, value, timestamp });
42
+ }
43
+
44
+ /**
45
+ * Compute transitive trust from source to target through a trust graph.
46
+ * Uses multiplicative path aggregation with max over paths.
47
+ *
48
+ * @param {TrustEdge[]} edges - All known trust edges
49
+ * @param {string} source - Source pod ID
50
+ * @param {string} target - Target pod ID
51
+ * @param {number} [maxDepth=3] - Maximum path length
52
+ * @returns {number} Computed trust level in [0.0, 1.0]
53
+ */
54
+ export function computeTransitiveTrust(edges, source, target, maxDepth = 3) {
55
+ if (source === target) return 1.0;
56
+
57
+ // Build adjacency map: from -> [{to, value}]
58
+ const adj = new Map();
59
+ for (const edge of edges) {
60
+ if (edge.value <= 0) continue; // blocked edges never propagate
61
+ if (!adj.has(edge.from)) adj.set(edge.from, []);
62
+ adj.get(edge.from).push({ to: edge.to, value: edge.value });
63
+ }
64
+
65
+ // BFS with trust propagation
66
+ let bestTrust = 0;
67
+ // Queue entries: [node, currentTrust, depth, visited]
68
+ const queue = [[source, 1.0, 0, new Set([source])]];
69
+
70
+ while (queue.length > 0) {
71
+ const [node, trust, depth, visited] = queue.shift();
72
+ if (depth >= maxDepth) continue;
73
+
74
+ const neighbors = adj.get(node) || [];
75
+ for (const { to, value } of neighbors) {
76
+ if (visited.has(to)) continue;
77
+ const pathTrust = trust * value;
78
+ if (to === target) {
79
+ bestTrust = Math.max(bestTrust, pathTrust);
80
+ continue;
81
+ }
82
+ if (pathTrust > bestTrust) { // Only explore if could improve
83
+ const newVisited = new Set(visited);
84
+ newVisited.add(to);
85
+ queue.push([to, pathTrust, depth + 1, newVisited]);
86
+ }
87
+ }
88
+ }
89
+
90
+ return bestTrust;
91
+ }
package/src/wire.mjs ADDED
@@ -0,0 +1,80 @@
1
+ import { MESH_TYPE } from "./constants.mjs";
2
+ import { MeshProtocolError } from "./errors.mjs";
3
+
4
+ /**
5
+ * Registry of known mesh message types.
6
+ * Maps type code -> human-readable name.
7
+ *
8
+ * @type {Map<number, string>}
9
+ */
10
+ export const messageTypeRegistry = new Map(
11
+ Object.entries(MESH_TYPE).map(([name, code]) => [code, name])
12
+ );
13
+
14
+ /**
15
+ * Encode a mesh message to binary wire format.
16
+ *
17
+ * Format:
18
+ * - Byte 0: message type code
19
+ * - Bytes 1-4: payload length (big-endian uint32)
20
+ * - Bytes 5+: JSON-encoded payload
21
+ *
22
+ * @param {object} message
23
+ * @param {number} message.type - One of MESH_TYPE values
24
+ * @param {string} message.from - Sender pod ID
25
+ * @param {string} [message.to] - Recipient pod ID (omit for broadcast)
26
+ * @param {*} message.payload - Message payload (must be JSON-serializable)
27
+ * @param {number} [message.ttl] - Time-to-live in seconds
28
+ * @returns {Uint8Array} Encoded bytes
29
+ */
30
+ export function encodeMeshMessage(message) {
31
+ if (!messageTypeRegistry.has(message.type)) {
32
+ throw new MeshProtocolError(`Unknown message type: 0x${message.type.toString(16)}`);
33
+ }
34
+ const payload = JSON.stringify({
35
+ from: message.from,
36
+ to: message.to,
37
+ payload: message.payload,
38
+ ttl: message.ttl,
39
+ });
40
+ const payloadBytes = new TextEncoder().encode(payload);
41
+ const result = new Uint8Array(5 + payloadBytes.length);
42
+ result[0] = message.type;
43
+ const view = new DataView(result.buffer);
44
+ view.setUint32(1, payloadBytes.length, false); // big-endian
45
+ result.set(payloadBytes, 5);
46
+ return result;
47
+ }
48
+
49
+ /**
50
+ * Decode binary wire format bytes into a mesh message object.
51
+ *
52
+ * @param {Uint8Array} bytes - Encoded message
53
+ * @returns {object} Decoded message with type, from, to, payload, ttl fields
54
+ * @throws {MeshProtocolError} If bytes are not valid mesh wire format
55
+ */
56
+ export function decodeMeshMessage(bytes) {
57
+ if (!(bytes instanceof Uint8Array) || bytes.length < 5) {
58
+ throw new MeshProtocolError('Message too short');
59
+ }
60
+ const type = bytes[0];
61
+ if (!messageTypeRegistry.has(type)) {
62
+ throw new MeshProtocolError(`Unknown message type: 0x${type.toString(16)}`);
63
+ }
64
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
65
+ const payloadLength = view.getUint32(1, false);
66
+ if (bytes.length < 5 + payloadLength) {
67
+ throw new MeshProtocolError(
68
+ `Truncated message: expected ${5 + payloadLength} bytes, got ${bytes.length}`
69
+ );
70
+ }
71
+ const payloadStr = new TextDecoder().decode(bytes.subarray(5, 5 + payloadLength));
72
+ const parsed = JSON.parse(payloadStr);
73
+ return {
74
+ type,
75
+ from: parsed.from,
76
+ to: parsed.to,
77
+ payload: parsed.payload,
78
+ ttl: parsed.ttl,
79
+ };
80
+ }