Skip to content

Commit

Permalink
feat: Add clearPeersInterval to automatically disconnect inactive peers
Browse files Browse the repository at this point in the history
  • Loading branch information
DimaDemchenko committed Jun 19, 2024
1 parent 1c7dd51 commit be047d4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/fast-tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,29 @@ export class FastTracker implements Tracker {
readonly #swarms = new Map<string, Swarm>();
readonly #peersContext = new Map<string, PeerContext>();

private clearPeersInterval?: NodeJS.Timeout;

public constructor(settings?: Partial<Settings>) {
this.settings = {
maxOffers: 20,
announceInterval: 120,
...settings,
};
this.startClearPeersInterval();
}

private startClearPeersInterval(): void {
if (this.clearPeersInterval === undefined) {
this.clearPeersInterval = setInterval(() => {
const now = performance.now();
for (const peer of this.#peersContext.values()) {
if (now - peer.lastAccessed > this.settings.announceInterval * 2) {
// TODO: disconnect only current peer
this.disconnectPeer(peer.ws as unknown as SocketContext);
}
}
}, this.settings.announceInterval * 1000);
}
}

public get swarms(): ReadonlyMap<string, { peers: readonly PeerContext[] }> {
Expand Down Expand Up @@ -146,6 +163,7 @@ export class FastTracker implements Tracker {
id: peerId,
sendMessage: peer.sendMessage,
ws: peer.ws,
lastAccessed: performance.now(),
};

this.#peersContext.set(peerId, peerContext);
Expand Down
1 change: 1 addition & 0 deletions lib/tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export interface PeerContext {
id: string;
sendMessage: (json: object, peer: SocketContext) => void;
ws: WebSocket<SocketContext>;
lastAccessed: number;
}

export interface Tracker {
Expand Down

0 comments on commit be047d4

Please sign in to comment.