-
Notifications
You must be signed in to change notification settings - Fork 435
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
fix: prune connections based on stream counts and direction #2521
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
98 changes: 98 additions & 0 deletions
98
packages/libp2p/test/connection-manager/connection-pruner.spec.ts
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,98 @@ | ||
import { TypedEventEmitter } from '@libp2p/interface' | ||
import { defaultLogger } from '@libp2p/logger' | ||
import { PeerMap } from '@libp2p/peer-collections' | ||
import { createEd25519PeerId } from '@libp2p/peer-id-factory' | ||
import { expect } from 'aegir/chai' | ||
import { stubInterface } from 'sinon-ts' | ||
import { ConnectionPruner } from '../../src/connection-manager/connection-pruner.js' | ||
import type { Libp2pEvents, PeerStore, Stream, TypedEventTarget, Connection } from '@libp2p/interface' | ||
import type { ConnectionManager } from '@libp2p/interface-internal' | ||
import type { StubbedInstance } from 'sinon-ts' | ||
|
||
interface ConnectionPrunerComponents { | ||
connectionManager: StubbedInstance<ConnectionManager> | ||
peerStore: StubbedInstance<PeerStore> | ||
events: TypedEventTarget<Libp2pEvents> | ||
} | ||
|
||
describe('connection-pruner', () => { | ||
let pruner: ConnectionPruner | ||
let components: ConnectionPrunerComponents | ||
|
||
beforeEach(() => { | ||
components = { | ||
connectionManager: stubInterface<ConnectionManager>(), | ||
peerStore: stubInterface<PeerStore>(), | ||
events: new TypedEventEmitter() | ||
} | ||
|
||
pruner = new ConnectionPruner({ | ||
...components, | ||
logger: defaultLogger() | ||
}, {}) | ||
}) | ||
|
||
it('should sort connections for pruning', async () => { | ||
const tagged = ['tagged', 'untagged'] | ||
const streams = ['streams', 'no-streams'] | ||
const direction = ['inbound', 'outbound'] | ||
const age = ['old', 'new'] | ||
|
||
const connections = [] | ||
const peerValues = new PeerMap<number>() | ||
|
||
for (const t of tagged) { | ||
for (const s of streams) { | ||
for (const d of direction) { | ||
for (const a of age) { | ||
const connection = stubInterface<Connection>({ | ||
id: `${t}-${s}-${d}-${a}`, | ||
remotePeer: await createEd25519PeerId(), | ||
streams: s === 'streams' | ||
? [stubInterface<Stream>()] | ||
: [], | ||
direction: d === 'inbound' ? 'inbound' : 'outbound', | ||
timeline: { | ||
open: a === 'old' ? 0 : (Date.now() - 100) | ||
} | ||
}) | ||
|
||
// eslint-disable-next-line max-depth | ||
if (t === 'tagged') { | ||
peerValues.set(connection.remotePeer, 100) | ||
} | ||
|
||
connections.push( | ||
connection | ||
) | ||
} | ||
} | ||
} | ||
} | ||
|
||
// priority is: | ||
// 1. tagged peers | ||
// 2. connections with streams | ||
// 3. outbound connections | ||
maschad marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// 4. longer-lived connections | ||
expect(pruner.sortConnections(connections.sort((a, b) => Math.random() > 0.5 ? -1 : 1), peerValues).map(conn => conn.id)) | ||
.to.deep.equal([ | ||
'untagged-no-streams-inbound-new', | ||
'untagged-no-streams-inbound-old', | ||
'untagged-no-streams-outbound-new', | ||
'untagged-no-streams-outbound-old', | ||
'untagged-streams-inbound-new', | ||
'untagged-streams-inbound-old', | ||
'untagged-streams-outbound-new', | ||
'untagged-streams-outbound-old', | ||
'tagged-no-streams-inbound-new', | ||
'tagged-no-streams-inbound-old', | ||
'tagged-no-streams-outbound-new', | ||
'tagged-no-streams-outbound-old', | ||
'tagged-streams-inbound-new', | ||
'tagged-streams-inbound-old', | ||
'tagged-streams-outbound-new', | ||
'tagged-streams-outbound-old' | ||
]) | ||
}) | ||
}) |
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,20 @@ | ||
import { setMaxListeners } from '@libp2p/interface' | ||
import { anySignal } from 'any-signal' | ||
import type { AbortOptions } from '@libp2p/interface' | ||
import type { ClearableSignal } from 'any-signal' | ||
|
||
export function createTimeoutOptions (timeout: number): AbortOptions | ||
export function createTimeoutOptions (timeout: number, ...existingSignals: AbortSignal[]): { signal: ClearableSignal } | ||
export function createTimeoutOptions (timeout: number, ...existingSignals: AbortSignal[]): AbortOptions { | ||
let signal = AbortSignal.timeout(timeout) | ||
setMaxListeners(Infinity, signal) | ||
|
||
if (existingSignals.length > 0) { | ||
signal = anySignal([signal, ...existingSignals]) | ||
setMaxListeners(Infinity, signal) | ||
} | ||
|
||
return { | ||
signal | ||
} | ||
} |
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,65 @@ | ||
import type { Connection, Stream, AbortOptions } from '@libp2p/interface' | ||
|
||
/** | ||
* Close the passed stream, falling back to aborting the stream if closing | ||
* cleanly fails. | ||
*/ | ||
export async function safelyCloseStream (stream?: Stream, options?: AbortOptions): Promise<void> { | ||
try { | ||
await stream?.close(options) | ||
} catch (err: any) { | ||
stream?.abort(err) | ||
} | ||
} | ||
|
||
/** | ||
* These are speculative protocols that are run automatically on connection open | ||
* so are usually not the reason the connection was opened. | ||
* | ||
* Consequently when requested it should be safe to close connections that only | ||
* have these protocol streams open. | ||
*/ | ||
const DEFAULT_CLOSABLE_PROTOCOLS = [ | ||
// identify | ||
'/ipfs/id/1.0.0', | ||
|
||
// identify-push | ||
'/ipfs/id/push/1.0.0', | ||
|
||
// autonat | ||
'/libp2p/autonat/1.0.0', | ||
|
||
// dcutr | ||
'/libp2p/dcutr' | ||
] | ||
|
||
export interface SafelyCloseConnectionOptions extends AbortOptions { | ||
/** | ||
* Only close the stream if it either has no protocol streams open or only | ||
* ones in this list. | ||
* | ||
* @default ['/ipfs/id/1.0.0'] | ||
*/ | ||
closableProtocols?: string[] | ||
} | ||
|
||
/** | ||
* Close the passed connection if it has no streams, or only closable protocol | ||
* streams, falling back to aborting the connection if closing it cleanly fails. | ||
*/ | ||
export async function safelyCloseConnectionIfUnused (connection?: Connection, options?: SafelyCloseConnectionOptions): Promise<void> { | ||
const streamProtocols = connection?.streams?.map(stream => stream.protocol) ?? [] | ||
const closableProtocols = options?.closableProtocols ?? DEFAULT_CLOSABLE_PROTOCOLS | ||
|
||
// if the connection has protocols not in the closable protocols list, do not | ||
// close the connection | ||
if (streamProtocols.filter(proto => proto != null && !closableProtocols.includes(proto)).length > 0) { | ||
return | ||
} | ||
|
||
try { | ||
await connection?.close(options) | ||
} catch (err: any) { | ||
connection?.abort(err) | ||
} | ||
} |
Oops, something went wrong.
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.
I like the succinctness of this test but I do feel for readability it is at times better to be more explicit (at the expense of repetition). So a test would probably read as:
older connections with streams should be closed before tagged connections for example.
Otherwise debugging the sorting algorithm could become a bit cumbersome.