-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This helper provides a class that can be used to implement simple gossip behavior, where a node is picked at random at a certain interval. This can be used to broadcast certain messages, such as requests or updates of data in a way where it eventually reaches the entire group.
- Loading branch information
1 parent
31a0848
commit d5cc740
Showing
2 changed files
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import { Group } from './Group'; | ||
import { Node } from './Node'; | ||
|
||
export interface GossiperOptions<V extends object> { | ||
/** | ||
* The interval to gossip with. | ||
*/ | ||
intervalInMs: number; | ||
|
||
gossip: (node: Node<V>) => void; | ||
} | ||
|
||
export class Gossiper<V extends object> { | ||
private readonly group: Group<V>; | ||
private readonly timer: any; | ||
|
||
private readonly gossip: (node: Node<V>) => void; | ||
|
||
public constructor(group: Group<V>, options: GossiperOptions<V>) { | ||
this.group = group; | ||
this.timer = setInterval(this.findAndGossip.bind(this), options.intervalInMs); | ||
this.gossip = options.gossip; | ||
} | ||
|
||
public destroy(): void { | ||
clearInterval(this.timer); | ||
} | ||
|
||
private findAndGossip() { | ||
const nodes = this.group.nodes; | ||
const idx = Math.floor(Math.random() * nodes.length); | ||
|
||
const node = nodes[idx]; | ||
this.gossip(node); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters