Skip to content

Commit

Permalink
feat(core): Add Gossiper helper
Browse files Browse the repository at this point in the history
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
aholstenson committed Dec 18, 2021
1 parent 31a0848 commit d5cc740
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
36 changes: 36 additions & 0 deletions packages/core/src/Gossiper.ts
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);
}
}
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,5 @@ export * from './Group';
export * from './group/NamedGroup';
export * from './RequestReplyHelper';

export * from './Gossiper';
export * from './SynchronizedValues';

0 comments on commit d5cc740

Please sign in to comment.