Skip to content

Commit

Permalink
fix: use running promise
Browse files Browse the repository at this point in the history
  • Loading branch information
Maddiaa0 committed Jan 20, 2025
1 parent 4ef4acb commit 8f4ab29
Showing 1 changed file with 6 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createLogger } from '@aztec/foundation/log';
import { RunningPromise } from '@aztec/foundation/running-promise';

import { type Libp2p, type PeerId, type Stream } from '@libp2p/interface';

Expand All @@ -24,9 +25,10 @@ export class RandomSampler {
*/
export class ConnectionSampler {
private readonly logger = createLogger('p2p:reqresp:connection-sampler');
private cleanupJob?: RunningPromise;

private readonly activeConnectionsCount: Map<PeerId, number> = new Map();
private readonly streams: Map<string, StreamAndPeerId> = new Map();
private cleanupInterval?: NodeJS.Timeout;

constructor(
private readonly libp2p: Libp2p,
Expand All @@ -35,22 +37,15 @@ export class ConnectionSampler {
// Random sampler provided so that it can be mocked
private readonly sampler: RandomSampler = new RandomSampler(),
) {
this.startCleanupJob();
}

private startCleanupJob() {
this.cleanupInterval = setInterval(() => {
void this.cleanupStaleConnections();
}, this.cleanupIntervalMs);
this.cleanupJob = new RunningPromise(() => this.cleanupStaleConnections(), this.logger, this.cleanupIntervalMs);
this.cleanupJob.start();
}

/**
* Stops the cleanup job and closes all active connections
*/
async stop() {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval);
}
await this.cleanupJob?.stop();

// Close all active streams
const closePromises = Array.from(this.streams.keys()).map(streamId => this.close(streamId));
Expand Down

0 comments on commit 8f4ab29

Please sign in to comment.