-
Notifications
You must be signed in to change notification settings - Fork 445
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add connection monitor #2644
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
fa84233
feat: add connection monitor
achingbrain d0e50a5
chore: use adaptive timeout
achingbrain 6141c86
chore: add missing deps
achingbrain 978e221
chore: apply suggestions from code review
achingbrain f3221ce
chore: add flag to disable
achingbrain File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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
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,134 @@ | ||
import { serviceCapabilities } from '@libp2p/interface' | ||
import { AdaptiveTimeout } from '@libp2p/utils/adaptive-timeout' | ||
import { byteStream } from 'it-byte-stream' | ||
import type { ComponentLogger, Logger, Metrics, Startable } from '@libp2p/interface' | ||
import type { ConnectionManager } from '@libp2p/interface-internal' | ||
import type { AdaptiveTimeoutInit } from '@libp2p/utils/adaptive-timeout' | ||
|
||
const DEFAULT_PING_INTERVAL_MS = 10000 | ||
|
||
export interface ConnectionMonitorInit { | ||
/** | ||
* Whether the connection monitor is enabled | ||
* | ||
* @default true | ||
*/ | ||
enabled?: boolean | ||
|
||
/** | ||
* How often to ping remote peers in ms | ||
* | ||
* @default 10000 | ||
*/ | ||
pingInterval?: number | ||
|
||
/** | ||
* Timeout settings for how long the ping is allowed to take before the | ||
* connection will be judged inactive and aborted. | ||
* | ||
* The timeout is adaptive to cope with slower networks or nodes that | ||
* have changing network characteristics, such as mobile. | ||
*/ | ||
pingTimeout?: Omit<AdaptiveTimeoutInit, 'metricsName' | 'metrics'> | ||
|
||
/** | ||
* If true, any connection that fails the ping will be aborted | ||
* | ||
* @default true | ||
*/ | ||
abortConnectionOnPingFailure?: boolean | ||
} | ||
|
||
export interface ConnectionMonitorComponents { | ||
logger: ComponentLogger | ||
connectionManager: ConnectionManager | ||
metrics?: Metrics | ||
} | ||
|
||
export class ConnectionMonitor implements Startable { | ||
private readonly components: ConnectionMonitorComponents | ||
private readonly log: Logger | ||
private heartbeatInterval?: ReturnType<typeof setInterval> | ||
private readonly pingIntervalMs: number | ||
private abortController?: AbortController | ||
private readonly timeout: AdaptiveTimeout | ||
|
||
constructor (components: ConnectionMonitorComponents, init: ConnectionMonitorInit = {}) { | ||
this.components = components | ||
|
||
this.log = components.logger.forComponent('libp2p:connection-monitor') | ||
this.pingIntervalMs = init.pingInterval ?? DEFAULT_PING_INTERVAL_MS | ||
|
||
this.timeout = new AdaptiveTimeout({ | ||
...(init.pingTimeout ?? {}), | ||
metrics: components.metrics, | ||
metricName: 'libp2p_connection_monitor_ping_time_milliseconds' | ||
}) | ||
} | ||
|
||
readonly [Symbol.toStringTag] = '@libp2p/connection-monitor' | ||
|
||
readonly [serviceCapabilities]: string[] = [ | ||
'@libp2p/connection-monitor' | ||
] | ||
|
||
start (): void { | ||
this.abortController = new AbortController() | ||
|
||
this.heartbeatInterval = setInterval(() => { | ||
this.components.connectionManager.getConnections().forEach(conn => { | ||
Promise.resolve().then(async () => { | ||
let start = Date.now() | ||
try { | ||
const signal = this.timeout.getTimeoutSignal({ | ||
signal: this.abortController?.signal | ||
}) | ||
const stream = await conn.newStream('/ipfs/ping/1.0.0', { | ||
signal, | ||
runOnTransientConnection: true | ||
}) | ||
const bs = byteStream(stream) | ||
start = Date.now() | ||
|
||
await Promise.all([ | ||
bs.write(new Uint8Array(1), { | ||
signal | ||
}), | ||
bs.read(1, { | ||
signal | ||
}) | ||
]) | ||
|
||
conn.rtt = Date.now() - start | ||
|
||
await bs.unwrap().close({ | ||
signal | ||
}) | ||
} catch (err: any) { | ||
if (err.code !== 'ERR_UNSUPPORTED_PROTOCOL') { | ||
maschad marked this conversation as resolved.
Show resolved
Hide resolved
|
||
throw err | ||
} | ||
|
||
// protocol was unsupported, but that's ok as it means the remote | ||
// peer was still alive. We ran multistream-select which means two | ||
// round trips (e.g. 1x for the mss header, then another for the | ||
// protocol) so divide the time it took by two | ||
conn.rtt = (Date.now() - start) / 2 | ||
} | ||
}) | ||
.catch(err => { | ||
this.log.error('error during heartbeat, aborting connection', err) | ||
conn.abort(err) | ||
}) | ||
}) | ||
}, this.pingIntervalMs) | ||
} | ||
|
||
stop (): void { | ||
this.abortController?.abort() | ||
|
||
if (this.heartbeatInterval != null) { | ||
clearInterval(this.heartbeatInterval) | ||
} | ||
} | ||
} |
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
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
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,115 @@ | ||
/* eslint-env mocha */ | ||
|
||
import { CodeError, start, stop } from '@libp2p/interface' | ||
import { defaultLogger } from '@libp2p/logger' | ||
import { expect } from 'aegir/chai' | ||
import delay from 'delay' | ||
import { pair } from 'it-pair' | ||
import { type StubbedInstance, stubInterface } from 'sinon-ts' | ||
import { ConnectionMonitor } from '../../src/connection-monitor.js' | ||
import type { ComponentLogger, Stream, Connection } from '@libp2p/interface' | ||
import type { ConnectionManager } from '@libp2p/interface-internal' | ||
|
||
interface StubbedConnectionMonitorComponents { | ||
logger: ComponentLogger | ||
connectionManager: StubbedInstance<ConnectionManager> | ||
} | ||
|
||
describe('connection monitor', () => { | ||
let monitor: ConnectionMonitor | ||
let components: StubbedConnectionMonitorComponents | ||
|
||
beforeEach(() => { | ||
components = { | ||
logger: defaultLogger(), | ||
connectionManager: stubInterface<ConnectionManager>() | ||
} | ||
}) | ||
|
||
afterEach(async () => { | ||
await stop(monitor) | ||
}) | ||
|
||
it('should monitor the liveness of a connection', async () => { | ||
monitor = new ConnectionMonitor(components, { | ||
pingInterval: 10 | ||
}) | ||
|
||
await start(monitor) | ||
|
||
const connection = stubInterface<Connection>() | ||
const stream = stubInterface<Stream>({ | ||
...pair<any>() | ||
}) | ||
connection.newStream.withArgs('/ipfs/ping/1.0.0').resolves(stream) | ||
|
||
components.connectionManager.getConnections.returns([connection]) | ||
|
||
await delay(100) | ||
|
||
expect(connection.rtt).to.be.gte(0) | ||
}) | ||
|
||
it('should monitor the liveness of a connection that does not support ping', async () => { | ||
monitor = new ConnectionMonitor(components, { | ||
pingInterval: 10 | ||
}) | ||
|
||
await start(monitor) | ||
|
||
const connection = stubInterface<Connection>() | ||
connection.newStream.withArgs('/ipfs/ping/1.0.0').callsFake(async () => { | ||
await delay(10) | ||
throw new CodeError('Unsupported protocol', 'ERR_UNSUPPORTED_PROTOCOL') | ||
}) | ||
|
||
components.connectionManager.getConnections.returns([connection]) | ||
|
||
await delay(100) | ||
|
||
expect(connection.rtt).to.be.gte(0) | ||
}) | ||
|
||
it('should abort a connection that times out', async () => { | ||
monitor = new ConnectionMonitor(components, { | ||
pingInterval: 50, | ||
pingTimeout: { | ||
initialValue: 10 | ||
} | ||
}) | ||
|
||
await start(monitor) | ||
|
||
const connection = stubInterface<Connection>() | ||
connection.newStream.withArgs('/ipfs/ping/1.0.0').callsFake(async (protocols, opts) => { | ||
await delay(200) | ||
opts?.signal?.throwIfAborted() | ||
return stubInterface<Stream>() | ||
}) | ||
|
||
components.connectionManager.getConnections.returns([connection]) | ||
|
||
await delay(500) | ||
|
||
expect(connection.abort).to.have.property('called', true) | ||
}) | ||
|
||
it('should abort a connection that fails', async () => { | ||
monitor = new ConnectionMonitor(components, { | ||
pingInterval: 10 | ||
}) | ||
|
||
await start(monitor) | ||
|
||
const connection = stubInterface<Connection>() | ||
connection.newStream.withArgs('/ipfs/ping/1.0.0').callsFake(async (protocols, opts) => { | ||
throw new CodeError('Connection closed', 'ERR_CONNECTION_CLOSED') | ||
}) | ||
|
||
components.connectionManager.getConnections.returns([connection]) | ||
|
||
await delay(100) | ||
|
||
expect(connection.abort).to.have.property('called', true) | ||
}) | ||
}) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why is this not divided by 2 too?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This one times how long it takes to send and receive one byte, (e.g. one round trip) but after the stream has been opened (e.g. after multistream select has finished).
The
ERR_UNSUPPORTED_PROTOCOL
error is thrown by multistream select, which takes two round trips, so that needs dividing by two but the happy path here doesn't, because we reset thestart
variable before timing the single byte rtt.