-
Notifications
You must be signed in to change notification settings - Fork 451
/
topology-listener.ts
72 lines (60 loc) · 1.78 KB
/
topology-listener.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { CustomEvent, TypedEventEmitter } from '@libp2p/interface'
import type { KadDHTComponents } from '.'
import type { Logger, PeerId, Startable } from '@libp2p/interface'
export interface TopologyListenerInit {
protocol: string
logPrefix: string
}
export interface TopologyListenerEvents {
'peer': CustomEvent<PeerId>
}
/**
* Receives notifications of new peers joining the network that support the DHT protocol
*/
export class TopologyListener extends TypedEventEmitter<TopologyListenerEvents> implements Startable {
private readonly log: Logger
private readonly components: KadDHTComponents
private readonly protocol: string
private running: boolean
private registrarId?: string
constructor (components: KadDHTComponents, init: TopologyListenerInit) {
super()
const { protocol, logPrefix } = init
this.components = components
this.log = components.logger.forComponent(`${logPrefix}:topology-listener`)
this.running = false
this.protocol = protocol
}
isStarted (): boolean {
return this.running
}
/**
* Start the network
*/
async start (): Promise<void> {
if (this.running) {
return
}
this.running = true
// register protocol with topology
this.registrarId = await this.components.registrar.register(this.protocol, {
onConnect: (peerId) => {
this.log('observed peer %p with protocol %s', peerId, this.protocol)
this.dispatchEvent(new CustomEvent('peer', {
detail: peerId
}))
}
})
}
/**
* Stop all network activity
*/
async stop (): Promise<void> {
this.running = false
// unregister protocol and handlers
if (this.registrarId != null) {
this.components.registrar.unregister(this.registrarId)
this.registrarId = undefined
}
}
}