@@ -29,6 +29,17 @@ export interface PubsubPeerDiscoveryInit {
2929 * If true, we will not broadcast our peer data
3030 */
3131 listenOnly ?: boolean
32+
33+ /**
34+ * If true, we will broadcast our data when we see new peers on the peer discovery topic (default: false).
35+ * listenOnly must not be set to false for this capability to be applied.
36+ */
37+ broadcastOnSubscribe ?: boolean
38+
39+ /**
40+ * Randomized backoff in milliseconds to wait before broadcasting on seeing a new subscription (default: 0.1 * interval).
41+ */
42+ backoffOnSubscribe ?: number
3243}
3344
3445export interface PubSubPeerDiscoveryComponents {
@@ -44,6 +55,8 @@ export class PubSubPeerDiscovery extends EventEmitter<PeerDiscoveryEvents> imple
4455 private readonly interval : number
4556 private readonly listenOnly : boolean
4657 private readonly topics : string [ ]
58+ private readonly broadcastOnSubscribe : boolean
59+ private readonly backoffOnSubscribe : number
4760 private intervalId ?: ReturnType < typeof setInterval >
4861 private readonly components : PubSubPeerDiscoveryComponents
4962
@@ -53,12 +66,16 @@ export class PubSubPeerDiscovery extends EventEmitter<PeerDiscoveryEvents> imple
5366 const {
5467 interval,
5568 topics,
56- listenOnly
69+ listenOnly,
70+ broadcastOnSubscribe,
71+ backoffOnSubscribe,
5772 } = init
5873
5974 this . components = components
6075 this . interval = interval ?? 10000
6176 this . listenOnly = listenOnly ?? false
77+ this . broadcastOnSubscribe = broadcastOnSubscribe ?? false
78+ this . backoffOnSubscribe = backoffOnSubscribe ?? this . interval * 0.1 ;
6279
6380 // Ensure we have topics
6481 if ( Array . isArray ( topics ) && topics . length > 0 ) {
@@ -112,6 +129,20 @@ export class PubSubPeerDiscovery extends EventEmitter<PeerDiscoveryEvents> imple
112129 return
113130 }
114131
132+ // Broadcast on Subscribe from other peers
133+ if ( this . broadcastOnSubscribe ) {
134+ pubsub . addEventListener ( 'subscription-change' , subChangeEvt => {
135+ // Check if the PubSub peer cares about PubSub Peer Discovery
136+ const discoverySubs = subChangeEvt . detail . subscriptions . filter ( sub => this . topics . includes ( sub . topic ) ) ;
137+
138+ // The Peer is interested in PubSub Peer Discovery -> broadcast
139+ if ( discoverySubs . length > 0 ) {
140+ const backoff = this . backoffOnSubscribe * Math . random ( )
141+ setTimeout ( ( ) => { this . _broadcast ( ) } , backoff )
142+ }
143+ } )
144+ }
145+
115146 // Broadcast immediately, and then run on interval
116147 this . _broadcast ( )
117148
0 commit comments