@johnhenry/browsermesh-discovery 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.
- package/LICENSE +21 -0
- package/README.md +35 -0
- package/package.json +31 -0
- package/src/dht.mjs +875 -0
- package/src/discovery.mjs +1584 -0
- package/src/index.mjs +7 -0
- package/src/naming.mjs +393 -0
- package/src/silent-catch.mjs +55 -0
- package/src/stealth.mjs +450 -0
- package/src/sw-routing.mjs +126 -0
- package/src/swarm.mjs +1440 -0
package/src/dht.mjs
ADDED
|
@@ -0,0 +1,875 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* clawser-mesh-dht.js -- DHT/Gossip protocol for BrowserMesh.
|
|
3
|
+
*
|
|
4
|
+
* Provides Kademlia-style distributed hash table with XOR-based routing,
|
|
5
|
+
* epidemic gossip protocol for state dissemination, and a DHT-backed
|
|
6
|
+
* discovery strategy.
|
|
7
|
+
*
|
|
8
|
+
* KBucket is a fixed-size (k=20) peer bucket with LRU eviction.
|
|
9
|
+
* RoutingTable provides 160-bit XOR-based routing with multiple buckets.
|
|
10
|
+
* DhtNode implements Kademlia operations (ping, findNode, findValue, store).
|
|
11
|
+
* GossipProtocol provides epidemic state dissemination with push/pull/digest.
|
|
12
|
+
* DhtDiscoveryStrategy extends DiscoveryStrategy for DHT-based peer discovery.
|
|
13
|
+
*
|
|
14
|
+
* No browser-only imports at module level.
|
|
15
|
+
*
|
|
16
|
+
* Run tests:
|
|
17
|
+
* node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-dht.test.mjs
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { DiscoveryStrategy } from './discovery.mjs'
|
|
21
|
+
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
// Wire Constants
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
/** DHT ping message type. */
|
|
27
|
+
export const DHT_PING = 0xE8
|
|
28
|
+
|
|
29
|
+
/** DHT find node message type. */
|
|
30
|
+
export const DHT_FIND_NODE = 0xE9
|
|
31
|
+
|
|
32
|
+
/** DHT find value message type. */
|
|
33
|
+
export const DHT_FIND_VALUE = 0xEA
|
|
34
|
+
|
|
35
|
+
/** DHT store message type. */
|
|
36
|
+
export const DHT_STORE = 0xEB
|
|
37
|
+
|
|
38
|
+
/** Gossip push message type. */
|
|
39
|
+
export const GOSSIP_PUSH = 0xEC
|
|
40
|
+
|
|
41
|
+
/** Gossip pull message type. */
|
|
42
|
+
export const GOSSIP_PULL = 0xED
|
|
43
|
+
|
|
44
|
+
/** Gossip digest message type. */
|
|
45
|
+
export const GOSSIP_DIGEST = 0xEE
|
|
46
|
+
|
|
47
|
+
/** Stealth shard message type. */
|
|
48
|
+
export const STEALTH_SHARD = 0xEF
|
|
49
|
+
|
|
50
|
+
// ---------------------------------------------------------------------------
|
|
51
|
+
// XOR Distance Helpers
|
|
52
|
+
// ---------------------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Compute XOR distance between two string IDs.
|
|
56
|
+
* Returns an array of XOR'd char codes.
|
|
57
|
+
* @param {string} a
|
|
58
|
+
* @param {string} b
|
|
59
|
+
* @returns {number[]}
|
|
60
|
+
*/
|
|
61
|
+
function xorDistance(a, b) {
|
|
62
|
+
const len = Math.max(a.length, b.length)
|
|
63
|
+
const result = []
|
|
64
|
+
for (let i = 0; i < len; i++) {
|
|
65
|
+
const ca = i < a.length ? a.charCodeAt(i) : 0
|
|
66
|
+
const cb = i < b.length ? b.charCodeAt(i) : 0
|
|
67
|
+
result.push(ca ^ cb)
|
|
68
|
+
}
|
|
69
|
+
return result
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Compare two XOR distance arrays. Returns negative if a < b, positive if a > b, 0 if equal.
|
|
74
|
+
* @param {number[]} a
|
|
75
|
+
* @param {number[]} b
|
|
76
|
+
* @returns {number}
|
|
77
|
+
*/
|
|
78
|
+
function compareDistance(a, b) {
|
|
79
|
+
const len = Math.max(a.length, b.length)
|
|
80
|
+
for (let i = 0; i < len; i++) {
|
|
81
|
+
const va = i < a.length ? a[i] : 0
|
|
82
|
+
const vb = i < b.length ? b[i] : 0
|
|
83
|
+
if (va !== vb) return va - vb
|
|
84
|
+
}
|
|
85
|
+
return 0
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Find the index of the highest differing bit between two string IDs.
|
|
90
|
+
* Returns 0 if the IDs are identical.
|
|
91
|
+
* @param {string} a
|
|
92
|
+
* @param {string} b
|
|
93
|
+
* @returns {number}
|
|
94
|
+
*/
|
|
95
|
+
function highestBitIndex(a, b) {
|
|
96
|
+
const dist = xorDistance(a, b)
|
|
97
|
+
for (let i = 0; i < dist.length; i++) {
|
|
98
|
+
if (dist[i] !== 0) {
|
|
99
|
+
// Find highest set bit in this byte
|
|
100
|
+
let byte = dist[i]
|
|
101
|
+
let bit = 7
|
|
102
|
+
while (bit >= 0 && !(byte & (1 << bit))) {
|
|
103
|
+
bit--
|
|
104
|
+
}
|
|
105
|
+
return i * 8 + (7 - bit)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return 0
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ---------------------------------------------------------------------------
|
|
112
|
+
// KBucket
|
|
113
|
+
// ---------------------------------------------------------------------------
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Fixed-size peer bucket for Kademlia routing table.
|
|
117
|
+
* Contacts are stored in an array, most-recently-seen at the end.
|
|
118
|
+
*/
|
|
119
|
+
export class KBucket {
|
|
120
|
+
/** @type {number} */
|
|
121
|
+
#k
|
|
122
|
+
|
|
123
|
+
/** @type {Array<{podId: string, address?: string, lastSeen?: number}>} */
|
|
124
|
+
#contacts = []
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* @param {number} [k=20] - Maximum bucket size
|
|
128
|
+
*/
|
|
129
|
+
constructor(k = 20) {
|
|
130
|
+
this.#k = k
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Add a contact to the bucket.
|
|
135
|
+
* If the contact already exists, move it to the end (most recent).
|
|
136
|
+
* If full, evict the LRU (oldest, index 0) contact.
|
|
137
|
+
*
|
|
138
|
+
* @param {{podId: string, address?: string, lastSeen?: number}} contact
|
|
139
|
+
* @returns {{podId: string, address?: string, lastSeen?: number}|null} Evicted contact or null
|
|
140
|
+
*/
|
|
141
|
+
add(contact) {
|
|
142
|
+
// If already present, move to end
|
|
143
|
+
const idx = this.#contacts.findIndex(c => c.podId === contact.podId)
|
|
144
|
+
if (idx !== -1) {
|
|
145
|
+
this.#contacts.splice(idx, 1)
|
|
146
|
+
this.#contacts.push(contact)
|
|
147
|
+
return null
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// If full, evict LRU (oldest = index 0)
|
|
151
|
+
let evicted = null
|
|
152
|
+
if (this.#contacts.length >= this.#k) {
|
|
153
|
+
evicted = this.#contacts.shift()
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
this.#contacts.push(contact)
|
|
157
|
+
return evicted
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Remove a contact by podId.
|
|
162
|
+
* @param {string} podId
|
|
163
|
+
* @returns {boolean} true if found and removed
|
|
164
|
+
*/
|
|
165
|
+
remove(podId) {
|
|
166
|
+
const idx = this.#contacts.findIndex(c => c.podId === podId)
|
|
167
|
+
if (idx === -1) return false
|
|
168
|
+
this.#contacts.splice(idx, 1)
|
|
169
|
+
return true
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Find a contact by podId.
|
|
174
|
+
* @param {string} podId
|
|
175
|
+
* @returns {{podId: string, address?: string, lastSeen?: number}|null}
|
|
176
|
+
*/
|
|
177
|
+
get(podId) {
|
|
178
|
+
return this.#contacts.find(c => c.podId === podId) ?? null
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Return up to `count` contacts sorted by XOR distance to targetId.
|
|
183
|
+
* @param {string} targetId
|
|
184
|
+
* @param {number} count
|
|
185
|
+
* @returns {Array<{podId: string, address?: string, lastSeen?: number}>}
|
|
186
|
+
*/
|
|
187
|
+
closest(targetId, count) {
|
|
188
|
+
const sorted = [...this.#contacts].sort((a, b) => {
|
|
189
|
+
const da = xorDistance(a.podId, targetId)
|
|
190
|
+
const db = xorDistance(b.podId, targetId)
|
|
191
|
+
return compareDistance(da, db)
|
|
192
|
+
})
|
|
193
|
+
return sorted.slice(0, count)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** @returns {boolean} Whether the bucket is full */
|
|
197
|
+
get isFull() {
|
|
198
|
+
return this.#contacts.length >= this.#k
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** @returns {number} Number of contacts */
|
|
202
|
+
get size() {
|
|
203
|
+
return this.#contacts.length
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** @returns {Array<{podId: string, address?: string, lastSeen?: number}>} Copy of contacts array */
|
|
207
|
+
get contacts() {
|
|
208
|
+
return [...this.#contacts]
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// ---------------------------------------------------------------------------
|
|
213
|
+
// RoutingTable
|
|
214
|
+
// ---------------------------------------------------------------------------
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 160-bit XOR-based routing table composed of KBuckets.
|
|
218
|
+
*/
|
|
219
|
+
export class RoutingTable {
|
|
220
|
+
/** @type {string} */
|
|
221
|
+
#localId
|
|
222
|
+
|
|
223
|
+
/** @type {number} */
|
|
224
|
+
#k
|
|
225
|
+
|
|
226
|
+
/** @type {KBucket[]} */
|
|
227
|
+
#buckets
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* @param {string} localId - This node's identifier
|
|
231
|
+
* @param {number} [k=20] - Bucket size
|
|
232
|
+
* @param {number} [bucketCount=160] - Number of buckets
|
|
233
|
+
*/
|
|
234
|
+
constructor(localId, k = 20, bucketCount = 160) {
|
|
235
|
+
if (!localId || typeof localId !== 'string') {
|
|
236
|
+
throw new Error('localId is required and must be a non-empty string')
|
|
237
|
+
}
|
|
238
|
+
this.#localId = localId
|
|
239
|
+
this.#k = k
|
|
240
|
+
this.#buckets = []
|
|
241
|
+
for (let i = 0; i < bucketCount; i++) {
|
|
242
|
+
this.#buckets.push(new KBucket(k))
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Compute the bucket index for a given targetId.
|
|
248
|
+
* Uses XOR distance and finds the highest differing bit.
|
|
249
|
+
* If targetId equals localId, returns 0.
|
|
250
|
+
*
|
|
251
|
+
* @param {string} targetId
|
|
252
|
+
* @returns {number}
|
|
253
|
+
*/
|
|
254
|
+
getBucketIndex(targetId) {
|
|
255
|
+
if (targetId === this.#localId) return 0
|
|
256
|
+
const idx = highestBitIndex(this.#localId, targetId)
|
|
257
|
+
return Math.min(idx, this.#buckets.length - 1)
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Add a contact to the appropriate bucket.
|
|
262
|
+
* @param {{podId: string, address?: string, lastSeen?: number}} contact
|
|
263
|
+
* @returns {{podId: string, address?: string, lastSeen?: number}|null} Evicted contact or null
|
|
264
|
+
*/
|
|
265
|
+
addContact(contact) {
|
|
266
|
+
const idx = this.getBucketIndex(contact.podId)
|
|
267
|
+
return this.#buckets[idx].add(contact)
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Remove a contact by podId from the appropriate bucket.
|
|
272
|
+
* @param {string} podId
|
|
273
|
+
* @returns {boolean}
|
|
274
|
+
*/
|
|
275
|
+
removeContact(podId) {
|
|
276
|
+
const idx = this.getBucketIndex(podId)
|
|
277
|
+
return this.#buckets[idx].remove(podId)
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Find the closest contacts to a target across all buckets.
|
|
282
|
+
* @param {string} targetId
|
|
283
|
+
* @param {number} [count=20]
|
|
284
|
+
* @returns {Array<{podId: string, address?: string, lastSeen?: number}>}
|
|
285
|
+
*/
|
|
286
|
+
findClosest(targetId, count = 20) {
|
|
287
|
+
const all = []
|
|
288
|
+
for (const bucket of this.#buckets) {
|
|
289
|
+
all.push(...bucket.contacts)
|
|
290
|
+
}
|
|
291
|
+
all.sort((a, b) => {
|
|
292
|
+
const da = xorDistance(a.podId, targetId)
|
|
293
|
+
const db = xorDistance(b.podId, targetId)
|
|
294
|
+
return compareDistance(da, db)
|
|
295
|
+
})
|
|
296
|
+
return all.slice(0, count)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Return list of bucket indices that have no contacts (stale/empty).
|
|
301
|
+
* @returns {number[]}
|
|
302
|
+
*/
|
|
303
|
+
refresh() {
|
|
304
|
+
const stale = []
|
|
305
|
+
for (let i = 0; i < this.#buckets.length; i++) {
|
|
306
|
+
if (this.#buckets[i].size === 0) {
|
|
307
|
+
stale.push(i)
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return stale
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Total contacts across all buckets.
|
|
315
|
+
* @returns {number}
|
|
316
|
+
*/
|
|
317
|
+
get size() {
|
|
318
|
+
let total = 0
|
|
319
|
+
for (const bucket of this.#buckets) {
|
|
320
|
+
total += bucket.size
|
|
321
|
+
}
|
|
322
|
+
return total
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// ---------------------------------------------------------------------------
|
|
327
|
+
// DhtNode
|
|
328
|
+
// ---------------------------------------------------------------------------
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Kademlia DHT node implementing core operations.
|
|
332
|
+
*/
|
|
333
|
+
export class DhtNode {
|
|
334
|
+
/** @type {string} */
|
|
335
|
+
#localId
|
|
336
|
+
|
|
337
|
+
/** @type {RoutingTable} */
|
|
338
|
+
#routingTable
|
|
339
|
+
|
|
340
|
+
/** @type {Map<string, {value: *, ttl: number, storedAt: number}>} */
|
|
341
|
+
#store
|
|
342
|
+
|
|
343
|
+
/** @type {Function} */
|
|
344
|
+
#sendFn
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* @param {object} opts
|
|
348
|
+
* @param {string} opts.localId - This node's identifier
|
|
349
|
+
* @param {RoutingTable} [opts.routingTable] - Routing table instance
|
|
350
|
+
* @param {Map} [opts.store] - Local key-value store
|
|
351
|
+
* @param {Function} [opts.sendFn] - Function to send messages: (targetId, msg) => {}
|
|
352
|
+
*/
|
|
353
|
+
constructor({ localId, routingTable, store, sendFn }) {
|
|
354
|
+
if (!localId || typeof localId !== 'string') {
|
|
355
|
+
throw new Error('localId is required and must be a non-empty string')
|
|
356
|
+
}
|
|
357
|
+
this.#localId = localId
|
|
358
|
+
this.#routingTable = routingTable ?? new RoutingTable(localId)
|
|
359
|
+
this.#store = store ?? new Map()
|
|
360
|
+
this.#sendFn = sendFn ?? (() => {})
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** @returns {string} */
|
|
364
|
+
get localId() {
|
|
365
|
+
return this.#localId
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** @returns {RoutingTable} */
|
|
369
|
+
get routingTable() {
|
|
370
|
+
return this.#routingTable
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Ping a target node. Simulates liveness check.
|
|
375
|
+
* @param {string} targetId
|
|
376
|
+
* @returns {boolean}
|
|
377
|
+
*/
|
|
378
|
+
ping(targetId) {
|
|
379
|
+
this.#sendFn(targetId, { type: DHT_PING, from: this.#localId })
|
|
380
|
+
return true
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Find the closest nodes to a given targetId.
|
|
385
|
+
* @param {string} targetId
|
|
386
|
+
* @returns {Array<{podId: string, address?: string, lastSeen?: number}>}
|
|
387
|
+
*/
|
|
388
|
+
findNode(targetId) {
|
|
389
|
+
return this.#routingTable.findClosest(targetId)
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Find a value by key. Checks local store first, then returns closest nodes.
|
|
394
|
+
* @param {string} key
|
|
395
|
+
* @returns {{found: boolean, value?: *, closest?: Array}}
|
|
396
|
+
*/
|
|
397
|
+
findValue(key) {
|
|
398
|
+
const entry = this.#store.get(key)
|
|
399
|
+
if (entry) {
|
|
400
|
+
// Check TTL
|
|
401
|
+
if (entry.ttl > 0 && Date.now() > entry.storedAt + entry.ttl) {
|
|
402
|
+
this.#store.delete(key)
|
|
403
|
+
} else {
|
|
404
|
+
return { found: true, value: entry.value }
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return { found: false, closest: this.findNode(key) }
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Store a key-value pair locally and replicate to closest nodes.
|
|
412
|
+
* @param {string} key
|
|
413
|
+
* @param {*} value
|
|
414
|
+
* @param {number} [ttl=0] - Time-to-live in ms (0 = no expiry)
|
|
415
|
+
*/
|
|
416
|
+
store(key, value, ttl = 0) {
|
|
417
|
+
this.#store.set(key, { value, ttl, storedAt: Date.now() })
|
|
418
|
+
|
|
419
|
+
// Replicate to closest nodes
|
|
420
|
+
const closest = this.#routingTable.findClosest(key)
|
|
421
|
+
for (const contact of closest) {
|
|
422
|
+
this.#sendFn(contact.podId, {
|
|
423
|
+
type: DHT_STORE,
|
|
424
|
+
from: this.#localId,
|
|
425
|
+
key,
|
|
426
|
+
value,
|
|
427
|
+
ttl,
|
|
428
|
+
})
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Handle an incoming DHT message. Always adds sender to routing table.
|
|
434
|
+
* @param {string} fromId - Sender's ID
|
|
435
|
+
* @param {object} msg - Message object with `type` field
|
|
436
|
+
* @returns {*} Response depending on message type
|
|
437
|
+
*/
|
|
438
|
+
handleMessage(fromId, msg) {
|
|
439
|
+
// Always add sender to routing table
|
|
440
|
+
this.#routingTable.addContact({ podId: fromId, lastSeen: Date.now() })
|
|
441
|
+
|
|
442
|
+
switch (msg.type) {
|
|
443
|
+
case DHT_PING:
|
|
444
|
+
return { type: DHT_PING, from: this.#localId, pong: true }
|
|
445
|
+
|
|
446
|
+
case DHT_FIND_NODE:
|
|
447
|
+
return {
|
|
448
|
+
type: DHT_FIND_NODE,
|
|
449
|
+
from: this.#localId,
|
|
450
|
+
closest: this.findNode(msg.targetId ?? fromId),
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
case DHT_FIND_VALUE:
|
|
454
|
+
return {
|
|
455
|
+
type: DHT_FIND_VALUE,
|
|
456
|
+
from: this.#localId,
|
|
457
|
+
...this.findValue(msg.key),
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
case DHT_STORE:
|
|
461
|
+
if (msg.key !== undefined && msg.value !== undefined) {
|
|
462
|
+
this.#store.set(msg.key, {
|
|
463
|
+
value: msg.value,
|
|
464
|
+
ttl: msg.ttl ?? 0,
|
|
465
|
+
storedAt: Date.now(),
|
|
466
|
+
})
|
|
467
|
+
}
|
|
468
|
+
return { type: DHT_STORE, from: this.#localId, stored: true }
|
|
469
|
+
|
|
470
|
+
default:
|
|
471
|
+
return null
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Get a value from the local store. Checks TTL expiry.
|
|
477
|
+
* @param {string} key
|
|
478
|
+
* @returns {*|undefined}
|
|
479
|
+
*/
|
|
480
|
+
get(key) {
|
|
481
|
+
const entry = this.#store.get(key)
|
|
482
|
+
if (!entry) return undefined
|
|
483
|
+
if (entry.ttl > 0 && Date.now() > entry.storedAt + entry.ttl) {
|
|
484
|
+
this.#store.delete(key)
|
|
485
|
+
return undefined
|
|
486
|
+
}
|
|
487
|
+
return entry.value
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Bootstrap the node with seed contacts. Adds each to the routing table,
|
|
492
|
+
* then does a findNode(localId) to populate nearby buckets.
|
|
493
|
+
* @param {Array<{podId: string, address?: string}>} seedContacts
|
|
494
|
+
* @returns {Array<{podId: string, address?: string, lastSeen?: number}>}
|
|
495
|
+
*/
|
|
496
|
+
bootstrap(seedContacts) {
|
|
497
|
+
for (const contact of seedContacts) {
|
|
498
|
+
this.#routingTable.addContact({ ...contact, lastSeen: Date.now() })
|
|
499
|
+
}
|
|
500
|
+
return this.findNode(this.#localId)
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// ---------------------------------------------------------------------------
|
|
505
|
+
// GossipProtocol
|
|
506
|
+
// ---------------------------------------------------------------------------
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* Epidemic gossip protocol for state dissemination.
|
|
510
|
+
*/
|
|
511
|
+
export class GossipProtocol {
|
|
512
|
+
/** @type {string} */
|
|
513
|
+
#localId
|
|
514
|
+
|
|
515
|
+
/** @type {number} */
|
|
516
|
+
#fanout
|
|
517
|
+
|
|
518
|
+
/** @type {number} */
|
|
519
|
+
#interval
|
|
520
|
+
|
|
521
|
+
/** @type {Function} */
|
|
522
|
+
#sendFn
|
|
523
|
+
|
|
524
|
+
/** @type {Map<string, {value: *, version: number, origin: string}>} */
|
|
525
|
+
#state = new Map()
|
|
526
|
+
|
|
527
|
+
/** @type {number} */
|
|
528
|
+
#version = 0
|
|
529
|
+
|
|
530
|
+
/** @type {boolean} */
|
|
531
|
+
#active = false
|
|
532
|
+
|
|
533
|
+
/** @type {*} */
|
|
534
|
+
#timer = null
|
|
535
|
+
|
|
536
|
+
/** @type {string[]} */
|
|
537
|
+
#peers = []
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* @param {object} opts
|
|
541
|
+
* @param {string} opts.localId - This node's identifier
|
|
542
|
+
* @param {number} [opts.fanout=3] - Number of peers to gossip to per round
|
|
543
|
+
* @param {number} [opts.interval=5000] - Gossip interval in ms
|
|
544
|
+
* @param {Function} [opts.sendFn] - Function to send messages: (targetId, msg) => {}
|
|
545
|
+
*/
|
|
546
|
+
constructor({ localId, fanout = 3, interval = 5000, sendFn }) {
|
|
547
|
+
if (!localId || typeof localId !== 'string') {
|
|
548
|
+
throw new Error('localId is required and must be a non-empty string')
|
|
549
|
+
}
|
|
550
|
+
this.#localId = localId
|
|
551
|
+
this.#fanout = fanout
|
|
552
|
+
this.#interval = interval
|
|
553
|
+
this.#sendFn = sendFn ?? (() => {})
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* Set a local state value. Bumps version and marks origin.
|
|
558
|
+
* @param {string} key
|
|
559
|
+
* @param {*} value
|
|
560
|
+
*/
|
|
561
|
+
set(key, value) {
|
|
562
|
+
this.#version++
|
|
563
|
+
this.#state.set(key, { value, version: this.#version, origin: this.#localId })
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* Get a local state value.
|
|
568
|
+
* @param {string} key
|
|
569
|
+
* @returns {*|undefined}
|
|
570
|
+
*/
|
|
571
|
+
get(key) {
|
|
572
|
+
const entry = this.#state.get(key)
|
|
573
|
+
return entry ? entry.value : undefined
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* Push a digest (version vector) to a target peer.
|
|
578
|
+
* @param {string} targetId
|
|
579
|
+
*/
|
|
580
|
+
pushDigest(targetId) {
|
|
581
|
+
const digest = {}
|
|
582
|
+
for (const [key, entry] of this.#state) {
|
|
583
|
+
digest[key] = entry.version
|
|
584
|
+
}
|
|
585
|
+
this.#sendFn(targetId, {
|
|
586
|
+
type: GOSSIP_DIGEST,
|
|
587
|
+
from: this.#localId,
|
|
588
|
+
digest,
|
|
589
|
+
})
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Handle a push message with entries. Keep entries with newer versions.
|
|
594
|
+
* @param {string} fromId
|
|
595
|
+
* @param {Array<{key: string, value: *, version: number, origin: string}>} entries
|
|
596
|
+
*/
|
|
597
|
+
handlePush(fromId, entries) {
|
|
598
|
+
for (const entry of entries) {
|
|
599
|
+
const local = this.#state.get(entry.key)
|
|
600
|
+
if (!local || entry.version > local.version) {
|
|
601
|
+
this.#state.set(entry.key, {
|
|
602
|
+
value: entry.value,
|
|
603
|
+
version: entry.version,
|
|
604
|
+
origin: entry.origin,
|
|
605
|
+
})
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
// Track peer
|
|
609
|
+
if (!this.#peers.includes(fromId)) {
|
|
610
|
+
this.#peers.push(fromId)
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* Handle a pull request. Compare with local state and send back
|
|
616
|
+
* entries that are newer locally.
|
|
617
|
+
* @param {string} fromId
|
|
618
|
+
* @param {object} digest - key -> version map
|
|
619
|
+
* @returns {Array<{key: string, value: *, version: number, origin: string}>}
|
|
620
|
+
*/
|
|
621
|
+
handlePull(fromId, digest) {
|
|
622
|
+
const newer = []
|
|
623
|
+
for (const [key, entry] of this.#state) {
|
|
624
|
+
const remoteVersion = digest[key] ?? 0
|
|
625
|
+
if (entry.version > remoteVersion) {
|
|
626
|
+
newer.push({
|
|
627
|
+
key,
|
|
628
|
+
value: entry.value,
|
|
629
|
+
version: entry.version,
|
|
630
|
+
origin: entry.origin,
|
|
631
|
+
})
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
this.#sendFn(fromId, {
|
|
635
|
+
type: GOSSIP_PUSH,
|
|
636
|
+
from: this.#localId,
|
|
637
|
+
entries: newer,
|
|
638
|
+
})
|
|
639
|
+
// Track peer
|
|
640
|
+
if (!this.#peers.includes(fromId)) {
|
|
641
|
+
this.#peers.push(fromId)
|
|
642
|
+
}
|
|
643
|
+
return newer
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* Handle a digest message. Compare with local state and request
|
|
648
|
+
* missing/newer entries via pull.
|
|
649
|
+
* @param {string} fromId
|
|
650
|
+
* @param {object} digest - key -> version map
|
|
651
|
+
*/
|
|
652
|
+
handleDigest(fromId, digest) {
|
|
653
|
+
const localDigest = {}
|
|
654
|
+
for (const [key, entry] of this.#state) {
|
|
655
|
+
localDigest[key] = entry.version
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// Check if remote has anything newer
|
|
659
|
+
let needPull = false
|
|
660
|
+
for (const key of Object.keys(digest)) {
|
|
661
|
+
const localVersion = localDigest[key] ?? 0
|
|
662
|
+
if (digest[key] > localVersion) {
|
|
663
|
+
needPull = true
|
|
664
|
+
break
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
if (needPull) {
|
|
669
|
+
this.#sendFn(fromId, {
|
|
670
|
+
type: GOSSIP_PULL,
|
|
671
|
+
from: this.#localId,
|
|
672
|
+
digest: localDigest,
|
|
673
|
+
})
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// Also send our newer entries as a push
|
|
677
|
+
const newer = []
|
|
678
|
+
for (const [key, entry] of this.#state) {
|
|
679
|
+
const remoteVersion = digest[key] ?? 0
|
|
680
|
+
if (entry.version > remoteVersion) {
|
|
681
|
+
newer.push({
|
|
682
|
+
key,
|
|
683
|
+
value: entry.value,
|
|
684
|
+
version: entry.version,
|
|
685
|
+
origin: entry.origin,
|
|
686
|
+
})
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
if (newer.length > 0) {
|
|
690
|
+
this.#sendFn(fromId, {
|
|
691
|
+
type: GOSSIP_PUSH,
|
|
692
|
+
from: this.#localId,
|
|
693
|
+
entries: newer,
|
|
694
|
+
})
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// Track peer
|
|
698
|
+
if (!this.#peers.includes(fromId)) {
|
|
699
|
+
this.#peers.push(fromId)
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/**
|
|
704
|
+
* Add a peer to the gossip network.
|
|
705
|
+
* @param {string} peerId
|
|
706
|
+
*/
|
|
707
|
+
addPeer(peerId) {
|
|
708
|
+
if (!this.#peers.includes(peerId)) {
|
|
709
|
+
this.#peers.push(peerId)
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* Start the gossip protocol. Periodically pushes digests to random peers.
|
|
715
|
+
*/
|
|
716
|
+
start() {
|
|
717
|
+
if (this.#active) return
|
|
718
|
+
this.#active = true
|
|
719
|
+
this.#timer = setInterval(() => {
|
|
720
|
+
this.#gossipRound()
|
|
721
|
+
}, this.#interval)
|
|
722
|
+
if (this.#timer && typeof this.#timer === 'object' && this.#timer.unref) {
|
|
723
|
+
this.#timer.unref()
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* Stop the gossip protocol.
|
|
729
|
+
*/
|
|
730
|
+
stop() {
|
|
731
|
+
if (!this.#active) return
|
|
732
|
+
this.#active = false
|
|
733
|
+
if (this.#timer !== null) {
|
|
734
|
+
clearInterval(this.#timer)
|
|
735
|
+
this.#timer = null
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/**
|
|
740
|
+
* Get a copy of the full state map.
|
|
741
|
+
* @returns {Map<string, {value: *, version: number, origin: string}>}
|
|
742
|
+
*/
|
|
743
|
+
getState() {
|
|
744
|
+
return new Map(this.#state)
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/**
|
|
748
|
+
* Whether the gossip protocol is active.
|
|
749
|
+
* @returns {boolean}
|
|
750
|
+
*/
|
|
751
|
+
get active() {
|
|
752
|
+
return this.#active
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/**
|
|
756
|
+
* Perform one gossip round: pick `fanout` random peers and push digest.
|
|
757
|
+
* @private
|
|
758
|
+
*/
|
|
759
|
+
#gossipRound() {
|
|
760
|
+
if (this.#peers.length === 0) return
|
|
761
|
+
const targets = this.#pickRandom(this.#peers, this.#fanout)
|
|
762
|
+
for (const targetId of targets) {
|
|
763
|
+
this.pushDigest(targetId)
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/**
|
|
768
|
+
* Pick up to `count` random elements from an array.
|
|
769
|
+
* @param {Array} arr
|
|
770
|
+
* @param {number} count
|
|
771
|
+
* @returns {Array}
|
|
772
|
+
* @private
|
|
773
|
+
*/
|
|
774
|
+
#pickRandom(arr, count) {
|
|
775
|
+
if (arr.length <= count) return [...arr]
|
|
776
|
+
const shuffled = [...arr]
|
|
777
|
+
for (let i = shuffled.length - 1; i > 0; i--) {
|
|
778
|
+
const j = Math.floor(Math.random() * (i + 1))
|
|
779
|
+
;[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
|
|
780
|
+
}
|
|
781
|
+
return shuffled.slice(0, count)
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// ---------------------------------------------------------------------------
|
|
786
|
+
// DhtDiscoveryStrategy
|
|
787
|
+
// ---------------------------------------------------------------------------
|
|
788
|
+
|
|
789
|
+
/**
|
|
790
|
+
* DHT-backed discovery strategy.
|
|
791
|
+
* Extends DiscoveryStrategy to use Kademlia DHT for peer discovery.
|
|
792
|
+
*/
|
|
793
|
+
export class DhtDiscoveryStrategy extends DiscoveryStrategy {
|
|
794
|
+
/** @type {DhtNode} */
|
|
795
|
+
#dhtNode
|
|
796
|
+
|
|
797
|
+
/** @type {Array<{podId: string}>} */
|
|
798
|
+
#bootstrapContacts
|
|
799
|
+
|
|
800
|
+
/**
|
|
801
|
+
* @param {object} opts
|
|
802
|
+
* @param {string} opts.localId - This node's identifier
|
|
803
|
+
* @param {Function} [opts.sendFn] - Function to send messages
|
|
804
|
+
* @param {number} [opts.k=20] - Bucket size
|
|
805
|
+
* @param {Array<{podId: string}>} [opts.bootstrapContacts=[]] - Initial seed contacts
|
|
806
|
+
*/
|
|
807
|
+
constructor({ localId, sendFn, k = 20, bootstrapContacts = [] }) {
|
|
808
|
+
super({ type: 'dht' })
|
|
809
|
+
this.#dhtNode = new DhtNode({ localId, sendFn })
|
|
810
|
+
this.#bootstrapContacts = bootstrapContacts
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/** @returns {DhtNode} The underlying DHT node */
|
|
814
|
+
get dhtNode() {
|
|
815
|
+
return this.#dhtNode
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/**
|
|
819
|
+
* Start the DHT discovery strategy.
|
|
820
|
+
* Bootstraps with seed contacts if provided.
|
|
821
|
+
* @returns {Promise<void>}
|
|
822
|
+
*/
|
|
823
|
+
async start() {
|
|
824
|
+
if (this.active) return
|
|
825
|
+
if (this.#bootstrapContacts.length > 0) {
|
|
826
|
+
this.#dhtNode.bootstrap(this.#bootstrapContacts)
|
|
827
|
+
}
|
|
828
|
+
this._active = true
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
/**
|
|
832
|
+
* Stop the DHT discovery strategy.
|
|
833
|
+
* @returns {Promise<void>}
|
|
834
|
+
*/
|
|
835
|
+
async stop() {
|
|
836
|
+
if (!this.active) return
|
|
837
|
+
this._active = false
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
/**
|
|
841
|
+
* Announce a record by storing it in the DHT.
|
|
842
|
+
* @param {object} record - Record with at least a podId field
|
|
843
|
+
* @returns {Promise<void>}
|
|
844
|
+
*/
|
|
845
|
+
async announce(record) {
|
|
846
|
+
if (!this.active) return
|
|
847
|
+
const key = record.podId ?? record.key
|
|
848
|
+
this.#dhtNode.store(key, record)
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* Query the DHT for a value. Optionally apply a filter.
|
|
853
|
+
* @param {object} [filter]
|
|
854
|
+
* @returns {Promise<Array>}
|
|
855
|
+
*/
|
|
856
|
+
async query(filter) {
|
|
857
|
+
if (!this.active) return []
|
|
858
|
+
const results = []
|
|
859
|
+
|
|
860
|
+
// If filter has a key/podId, look it up directly
|
|
861
|
+
if (filter && filter.podId) {
|
|
862
|
+
const result = this.#dhtNode.findValue(filter.podId)
|
|
863
|
+
if (result.found) {
|
|
864
|
+
results.push(result.value)
|
|
865
|
+
}
|
|
866
|
+
} else if (filter && filter.key) {
|
|
867
|
+
const result = this.#dhtNode.findValue(filter.key)
|
|
868
|
+
if (result.found) {
|
|
869
|
+
results.push(result.value)
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
return results
|
|
874
|
+
}
|
|
875
|
+
}
|