2022-07-01 18:19:57 +00:00
|
|
|
# Nim-LibP2P
|
2023-01-20 14:47:40 +00:00
|
|
|
# Copyright (c) 2023 Status Research & Development GmbH
|
2022-07-01 18:19:57 +00:00
|
|
|
# Licensed under either of
|
|
|
|
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
# * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
# at your option.
|
|
|
|
# This file may not be copied, modified, or distributed except according to
|
|
|
|
# those terms.
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2022-08-03 11:33:19 +00:00
|
|
|
when (NimMajor, NimMinor) < (1, 4):
|
|
|
|
{.push raises: [Defect].}
|
|
|
|
else:
|
|
|
|
{.push raises: [].}
|
2021-05-21 16:27:01 +00:00
|
|
|
|
2020-08-01 20:50:40 +00:00
|
|
|
import std/[options, tables, sequtils, sets]
|
2021-05-25 17:06:04 +00:00
|
|
|
import pkg/[chronos, chronicles, metrics]
|
2020-07-17 15:36:48 +00:00
|
|
|
import peerinfo,
|
2021-09-08 09:07:46 +00:00
|
|
|
peerstore,
|
2020-07-17 15:36:48 +00:00
|
|
|
stream/connection,
|
2020-09-23 14:07:16 +00:00
|
|
|
muxers/muxer,
|
2021-01-21 04:00:24 +00:00
|
|
|
utils/semaphore,
|
2020-09-23 14:07:16 +00:00
|
|
|
errors
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2020-09-15 06:03:53 +00:00
|
|
|
logScope:
|
2020-12-01 17:34:27 +00:00
|
|
|
topics = "libp2p connmanager"
|
2020-09-15 06:03:53 +00:00
|
|
|
|
2020-07-17 15:36:48 +00:00
|
|
|
declareGauge(libp2p_peers, "total connected peers")
|
|
|
|
|
2021-01-04 18:59:05 +00:00
|
|
|
const
|
2021-01-21 04:00:24 +00:00
|
|
|
MaxConnections* = 50
|
2022-01-04 11:21:24 +00:00
|
|
|
MaxConnectionsPerPeer* = 1
|
2020-07-17 15:36:48 +00:00
|
|
|
|
|
|
|
type
|
2021-05-21 16:27:01 +00:00
|
|
|
TooManyConnectionsError* = object of LPError
|
2021-01-21 04:00:24 +00:00
|
|
|
|
2020-09-23 14:07:16 +00:00
|
|
|
ConnEventKind* {.pure.} = enum
|
|
|
|
Connected, # A connection was made and securely upgraded - there may be
|
|
|
|
# more than one concurrent connection thus more than one upgrade
|
|
|
|
# event per peer.
|
|
|
|
|
|
|
|
Disconnected # Peer disconnected - this event is fired once per upgrade
|
|
|
|
# when the associated connection is terminated.
|
|
|
|
|
|
|
|
ConnEvent* = object
|
|
|
|
case kind*: ConnEventKind
|
|
|
|
of ConnEventKind.Connected:
|
|
|
|
incoming*: bool
|
|
|
|
else:
|
|
|
|
discard
|
|
|
|
|
|
|
|
ConnEventHandler* =
|
2021-09-08 09:07:46 +00:00
|
|
|
proc(peerId: PeerId, event: ConnEvent): Future[void]
|
2021-05-21 16:27:01 +00:00
|
|
|
{.gcsafe, raises: [Defect].}
|
2020-09-23 14:07:16 +00:00
|
|
|
|
2020-11-28 16:59:47 +00:00
|
|
|
PeerEventKind* {.pure.} = enum
|
2020-09-23 14:07:16 +00:00
|
|
|
Left,
|
2021-06-08 16:55:24 +00:00
|
|
|
Identified,
|
2020-09-23 14:07:16 +00:00
|
|
|
Joined
|
|
|
|
|
2020-11-28 16:59:47 +00:00
|
|
|
PeerEvent* = object
|
|
|
|
case kind*: PeerEventKind
|
|
|
|
of PeerEventKind.Joined:
|
|
|
|
initiator*: bool
|
|
|
|
else:
|
|
|
|
discard
|
|
|
|
|
2020-09-23 14:07:16 +00:00
|
|
|
PeerEventHandler* =
|
2022-01-05 15:27:33 +00:00
|
|
|
proc(peerId: PeerId, event: PeerEvent): Future[void] {.gcsafe, raises: [Defect].}
|
2020-09-23 14:07:16 +00:00
|
|
|
|
2020-07-17 15:36:48 +00:00
|
|
|
MuxerHolder = object
|
|
|
|
muxer: Muxer
|
|
|
|
handle: Future[void]
|
|
|
|
|
|
|
|
ConnManager* = ref object of RootObj
|
2021-01-21 04:00:24 +00:00
|
|
|
maxConnsPerPeer: int
|
|
|
|
inSema*: AsyncSemaphore
|
|
|
|
outSema*: AsyncSemaphore
|
2021-12-16 10:05:20 +00:00
|
|
|
conns: Table[PeerId, HashSet[Connection]]
|
2020-07-17 15:36:48 +00:00
|
|
|
muxed: Table[Connection, MuxerHolder]
|
2021-05-19 06:49:55 +00:00
|
|
|
connEvents: array[ConnEventKind, OrderedSet[ConnEventHandler]]
|
|
|
|
peerEvents: array[PeerEventKind, OrderedSet[PeerEventHandler]]
|
2023-01-23 22:28:39 +00:00
|
|
|
expectedConnections: Table[PeerId, Future[Connection]]
|
2021-09-08 09:07:46 +00:00
|
|
|
peerStore*: PeerStore
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2022-08-03 14:48:19 +00:00
|
|
|
ConnectionSlot* = object
|
|
|
|
connManager: ConnManager
|
|
|
|
direction: Direction
|
|
|
|
|
2021-01-21 04:00:24 +00:00
|
|
|
proc newTooManyConnectionsError(): ref TooManyConnectionsError {.inline.} =
|
|
|
|
result = newException(TooManyConnectionsError, "Too many connections")
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2021-10-25 08:26:32 +00:00
|
|
|
proc new*(C: type ConnManager,
|
2021-01-21 04:00:24 +00:00
|
|
|
maxConnsPerPeer = MaxConnectionsPerPeer,
|
|
|
|
maxConnections = MaxConnections,
|
|
|
|
maxIn = -1,
|
|
|
|
maxOut = -1): ConnManager =
|
|
|
|
var inSema, outSema: AsyncSemaphore
|
2021-01-28 03:27:33 +00:00
|
|
|
if maxIn > 0 or maxOut > 0:
|
2021-01-21 04:00:24 +00:00
|
|
|
inSema = newAsyncSemaphore(maxIn)
|
|
|
|
outSema = newAsyncSemaphore(maxOut)
|
|
|
|
elif maxConnections > 0:
|
|
|
|
inSema = newAsyncSemaphore(maxConnections)
|
|
|
|
outSema = inSema
|
|
|
|
else:
|
|
|
|
raiseAssert "Invalid connection counts!"
|
|
|
|
|
|
|
|
C(maxConnsPerPeer: maxConnsPerPeer,
|
|
|
|
inSema: inSema,
|
|
|
|
outSema: outSema)
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2021-12-16 10:05:20 +00:00
|
|
|
proc connCount*(c: ConnManager, peerId: PeerId): int =
|
2020-09-23 14:07:16 +00:00
|
|
|
c.conns.getOrDefault(peerId).len
|
|
|
|
|
2022-12-16 11:32:00 +00:00
|
|
|
proc connectedPeers*(c: ConnManager, dir: Direction): seq[PeerId] =
|
|
|
|
var peers = newSeq[PeerId]()
|
|
|
|
for peerId, conns in c.conns:
|
|
|
|
if conns.anyIt(it.dir == dir):
|
|
|
|
peers.add(peerId)
|
|
|
|
return peers
|
|
|
|
|
2020-09-23 14:07:16 +00:00
|
|
|
proc addConnEventHandler*(c: ConnManager,
|
2020-11-28 16:59:47 +00:00
|
|
|
handler: ConnEventHandler,
|
|
|
|
kind: ConnEventKind) =
|
2020-09-23 14:07:16 +00:00
|
|
|
## Add peer event handler - handlers must not raise exceptions!
|
|
|
|
##
|
|
|
|
|
2021-05-21 16:27:01 +00:00
|
|
|
try:
|
|
|
|
if isNil(handler): return
|
|
|
|
c.connEvents[kind].incl(handler)
|
|
|
|
except Exception as exc:
|
|
|
|
# TODO: there is an Exception being raised
|
|
|
|
# somewhere in the depths of the std.
|
|
|
|
# Might be related to https://github.com/nim-lang/Nim/issues/17382
|
|
|
|
|
|
|
|
raiseAssert exc.msg
|
2020-09-23 14:07:16 +00:00
|
|
|
|
|
|
|
proc removeConnEventHandler*(c: ConnManager,
|
2020-11-28 16:59:47 +00:00
|
|
|
handler: ConnEventHandler,
|
|
|
|
kind: ConnEventKind) =
|
2021-05-21 16:27:01 +00:00
|
|
|
try:
|
|
|
|
c.connEvents[kind].excl(handler)
|
|
|
|
except Exception as exc:
|
|
|
|
# TODO: there is an Exception being raised
|
|
|
|
# somewhere in the depths of the std.
|
|
|
|
# Might be related to https://github.com/nim-lang/Nim/issues/17382
|
|
|
|
|
|
|
|
raiseAssert exc.msg
|
2020-09-23 14:07:16 +00:00
|
|
|
|
2020-11-28 16:59:47 +00:00
|
|
|
proc triggerConnEvent*(c: ConnManager,
|
2021-09-08 09:07:46 +00:00
|
|
|
peerId: PeerId,
|
2020-11-28 16:59:47 +00:00
|
|
|
event: ConnEvent) {.async, gcsafe.} =
|
2020-09-23 14:07:16 +00:00
|
|
|
try:
|
2021-09-08 09:07:46 +00:00
|
|
|
trace "About to trigger connection events", peer = peerId
|
2021-05-19 06:49:55 +00:00
|
|
|
if c.connEvents[event.kind].len() > 0:
|
2021-09-08 09:07:46 +00:00
|
|
|
trace "triggering connection events", peer = peerId, event = $event.kind
|
2020-09-23 14:07:16 +00:00
|
|
|
var connEvents: seq[Future[void]]
|
|
|
|
for h in c.connEvents[event.kind]:
|
2021-09-08 09:07:46 +00:00
|
|
|
connEvents.add(h(peerId, event))
|
2020-09-23 14:07:16 +00:00
|
|
|
|
|
|
|
checkFutures(await allFinished(connEvents))
|
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
2021-01-21 04:00:24 +00:00
|
|
|
except CatchableError as exc:
|
2020-09-23 14:07:16 +00:00
|
|
|
warn "Exception in triggerConnEvents",
|
2021-09-08 09:07:46 +00:00
|
|
|
msg = exc.msg, peer = peerId, event = $event
|
2020-09-23 14:07:16 +00:00
|
|
|
|
|
|
|
proc addPeerEventHandler*(c: ConnManager,
|
|
|
|
handler: PeerEventHandler,
|
2020-11-28 16:59:47 +00:00
|
|
|
kind: PeerEventKind) =
|
2020-09-23 14:07:16 +00:00
|
|
|
## Add peer event handler - handlers must not raise exceptions!
|
|
|
|
##
|
|
|
|
|
|
|
|
if isNil(handler): return
|
2021-05-21 16:27:01 +00:00
|
|
|
try:
|
|
|
|
c.peerEvents[kind].incl(handler)
|
|
|
|
except Exception as exc:
|
|
|
|
# TODO: there is an Exception being raised
|
|
|
|
# somewhere in the depths of the std.
|
|
|
|
# Might be related to https://github.com/nim-lang/Nim/issues/17382
|
|
|
|
|
|
|
|
raiseAssert exc.msg
|
2020-09-23 14:07:16 +00:00
|
|
|
|
|
|
|
proc removePeerEventHandler*(c: ConnManager,
|
|
|
|
handler: PeerEventHandler,
|
2020-11-28 16:59:47 +00:00
|
|
|
kind: PeerEventKind) =
|
2021-05-21 16:27:01 +00:00
|
|
|
try:
|
|
|
|
c.peerEvents[kind].excl(handler)
|
|
|
|
except Exception as exc:
|
|
|
|
# TODO: there is an Exception being raised
|
|
|
|
# somewhere in the depths of the std.
|
|
|
|
# Might be related to https://github.com/nim-lang/Nim/issues/17382
|
|
|
|
|
|
|
|
raiseAssert exc.msg
|
2020-09-23 14:07:16 +00:00
|
|
|
|
|
|
|
proc triggerPeerEvents*(c: ConnManager,
|
2021-09-08 09:07:46 +00:00
|
|
|
peerId: PeerId,
|
2020-09-23 14:07:16 +00:00
|
|
|
event: PeerEvent) {.async, gcsafe.} =
|
|
|
|
|
2021-09-08 09:07:46 +00:00
|
|
|
trace "About to trigger peer events", peer = peerId
|
2021-05-19 06:49:55 +00:00
|
|
|
if c.peerEvents[event.kind].len == 0:
|
2020-09-23 14:07:16 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
2021-09-08 09:07:46 +00:00
|
|
|
let count = c.connCount(peerId)
|
2020-11-28 16:59:47 +00:00
|
|
|
if event.kind == PeerEventKind.Joined and count != 1:
|
2021-09-08 09:07:46 +00:00
|
|
|
trace "peer already joined", peer = peerId, event = $event
|
2020-09-23 14:07:16 +00:00
|
|
|
return
|
2020-11-28 16:59:47 +00:00
|
|
|
elif event.kind == PeerEventKind.Left and count != 0:
|
2021-09-08 09:07:46 +00:00
|
|
|
trace "peer still connected or already left", peer = peerId, event = $event
|
2020-09-23 14:07:16 +00:00
|
|
|
return
|
|
|
|
|
2021-09-08 09:07:46 +00:00
|
|
|
trace "triggering peer events", peer = peerId, event = $event
|
2020-09-23 14:07:16 +00:00
|
|
|
|
|
|
|
var peerEvents: seq[Future[void]]
|
2020-11-28 16:59:47 +00:00
|
|
|
for h in c.peerEvents[event.kind]:
|
2021-09-08 09:07:46 +00:00
|
|
|
peerEvents.add(h(peerId, event))
|
2020-09-23 14:07:16 +00:00
|
|
|
|
|
|
|
checkFutures(await allFinished(peerEvents))
|
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
|
|
|
except CatchableError as exc: # handlers should not raise!
|
2021-09-08 09:07:46 +00:00
|
|
|
warn "Exception in triggerPeerEvents", exc = exc.msg, peer = peerId
|
2020-09-23 14:07:16 +00:00
|
|
|
|
2023-01-23 22:28:39 +00:00
|
|
|
proc expectConnection*(c: ConnManager, p: PeerId): Future[Connection] {.async.} =
|
|
|
|
## Wait for a peer to connect to us. This will bypass the `MaxConnectionsPerPeer`
|
|
|
|
if p in c.expectedConnections:
|
|
|
|
raise LPError.newException("Already expecting a connection from that peer")
|
|
|
|
|
|
|
|
let future = newFuture[Connection]()
|
|
|
|
c.expectedConnections[p] = future
|
|
|
|
|
|
|
|
try:
|
|
|
|
return await future
|
|
|
|
finally:
|
|
|
|
c.expectedConnections.del(p)
|
|
|
|
|
2020-07-17 15:36:48 +00:00
|
|
|
proc contains*(c: ConnManager, conn: Connection): bool =
|
|
|
|
## checks if a connection is being tracked by the
|
|
|
|
## connection manager
|
|
|
|
##
|
|
|
|
|
|
|
|
if isNil(conn):
|
|
|
|
return
|
|
|
|
|
2021-09-08 09:07:46 +00:00
|
|
|
return conn in c.conns.getOrDefault(conn.peerId)
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2021-12-16 10:05:20 +00:00
|
|
|
proc contains*(c: ConnManager, peerId: PeerId): bool =
|
2020-07-17 15:36:48 +00:00
|
|
|
peerId in c.conns
|
|
|
|
|
|
|
|
proc contains*(c: ConnManager, muxer: Muxer): bool =
|
|
|
|
## checks if a muxer is being tracked by the connection
|
|
|
|
## manager
|
|
|
|
##
|
|
|
|
|
|
|
|
if isNil(muxer):
|
|
|
|
return
|
|
|
|
|
|
|
|
let conn = muxer.connection
|
|
|
|
if conn notin c:
|
|
|
|
return
|
|
|
|
|
|
|
|
if conn notin c.muxed:
|
|
|
|
return
|
|
|
|
|
2021-05-21 16:27:01 +00:00
|
|
|
return muxer == c.muxed.getOrDefault(conn).muxer
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2020-08-01 20:50:40 +00:00
|
|
|
proc closeMuxerHolder(muxerHolder: MuxerHolder) {.async.} =
|
2020-09-08 06:24:28 +00:00
|
|
|
trace "Cleaning up muxer", m = muxerHolder.muxer
|
2020-08-01 20:50:40 +00:00
|
|
|
|
|
|
|
await muxerHolder.muxer.close()
|
|
|
|
if not(isNil(muxerHolder.handle)):
|
2021-01-21 04:00:24 +00:00
|
|
|
try:
|
|
|
|
await muxerHolder.handle # TODO noraises?
|
|
|
|
except CatchableError as exc:
|
|
|
|
trace "Exception in close muxer handler", exc = exc.msg
|
2020-09-08 06:24:28 +00:00
|
|
|
trace "Cleaned up muxer", m = muxerHolder.muxer
|
2020-08-01 20:50:40 +00:00
|
|
|
|
|
|
|
proc delConn(c: ConnManager, conn: Connection) =
|
2021-09-08 09:07:46 +00:00
|
|
|
let peerId = conn.peerId
|
2021-05-19 06:49:55 +00:00
|
|
|
c.conns.withValue(peerId, peerConns):
|
|
|
|
peerConns[].excl(conn)
|
2020-08-01 20:50:40 +00:00
|
|
|
|
2021-05-19 06:49:55 +00:00
|
|
|
if peerConns[].len == 0:
|
|
|
|
c.conns.del(peerId) # invalidates `peerConns`
|
2020-08-01 20:50:40 +00:00
|
|
|
|
2020-12-03 01:24:48 +00:00
|
|
|
libp2p_peers.set(c.conns.len.int64)
|
2020-09-08 06:24:28 +00:00
|
|
|
trace "Removed connection", conn
|
|
|
|
|
2020-07-17 15:36:48 +00:00
|
|
|
proc cleanupConn(c: ConnManager, conn: Connection) {.async.} =
|
|
|
|
## clean connection's resources such as muxers and streams
|
|
|
|
|
|
|
|
if isNil(conn):
|
2021-01-21 04:00:24 +00:00
|
|
|
trace "Wont cleanup a nil connection"
|
2020-07-17 15:36:48 +00:00
|
|
|
return
|
|
|
|
|
2020-08-01 20:50:40 +00:00
|
|
|
# Remove connection from all tables without async breaks
|
|
|
|
var muxer = some(MuxerHolder())
|
|
|
|
if not c.muxed.pop(conn, muxer.get()):
|
|
|
|
muxer = none(MuxerHolder)
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2020-08-01 20:50:40 +00:00
|
|
|
delConn(c, conn)
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2020-08-01 20:50:40 +00:00
|
|
|
try:
|
|
|
|
if muxer.isSome:
|
|
|
|
await closeMuxerHolder(muxer.get())
|
2020-07-17 15:36:48 +00:00
|
|
|
finally:
|
|
|
|
await conn.close()
|
|
|
|
|
2020-09-08 06:24:28 +00:00
|
|
|
trace "Connection cleaned up", conn
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2021-01-04 18:59:05 +00:00
|
|
|
proc onConnUpgraded(c: ConnManager, conn: Connection) {.async.} =
|
2020-11-02 20:35:26 +00:00
|
|
|
try:
|
2020-11-11 19:20:14 +00:00
|
|
|
trace "Triggering connect events", conn
|
2021-01-18 22:27:29 +00:00
|
|
|
conn.upgrade()
|
2021-01-04 18:59:05 +00:00
|
|
|
|
2021-09-08 09:07:46 +00:00
|
|
|
let peerId = conn.peerId
|
2020-11-28 16:59:47 +00:00
|
|
|
await c.triggerPeerEvents(
|
2021-09-08 09:07:46 +00:00
|
|
|
peerId, PeerEvent(kind: PeerEventKind.Joined, initiator: conn.dir == Direction.Out))
|
2021-01-04 18:59:05 +00:00
|
|
|
|
2020-11-02 20:35:26 +00:00
|
|
|
await c.triggerConnEvent(
|
2021-09-08 09:07:46 +00:00
|
|
|
peerId, ConnEvent(kind: ConnEventKind.Connected, incoming: conn.dir == Direction.In))
|
2020-11-02 20:35:26 +00:00
|
|
|
except CatchableError as exc:
|
|
|
|
# This is top-level procedure which will work as separate task, so it
|
|
|
|
# do not need to propagate CancelledError and should handle other errors
|
|
|
|
warn "Unexpected exception in switch peer connection cleanup",
|
|
|
|
conn, msg = exc.msg
|
|
|
|
|
|
|
|
proc peerCleanup(c: ConnManager, conn: Connection) {.async.} =
|
|
|
|
try:
|
2020-11-11 19:20:14 +00:00
|
|
|
trace "Triggering disconnect events", conn
|
2021-09-08 09:07:46 +00:00
|
|
|
let peerId = conn.peerId
|
2020-11-02 20:35:26 +00:00
|
|
|
await c.triggerConnEvent(
|
2021-09-08 09:07:46 +00:00
|
|
|
peerId, ConnEvent(kind: ConnEventKind.Disconnected))
|
|
|
|
await c.triggerPeerEvents(peerId, PeerEvent(kind: PeerEventKind.Left))
|
2022-05-25 10:12:57 +00:00
|
|
|
|
|
|
|
if not(c.peerStore.isNil):
|
|
|
|
c.peerStore.cleanup(peerId)
|
2020-11-02 20:35:26 +00:00
|
|
|
except CatchableError as exc:
|
|
|
|
# This is top-level procedure which will work as separate task, so it
|
|
|
|
# do not need to propagate CancelledError and should handle other errors
|
|
|
|
warn "Unexpected exception peer cleanup handler",
|
|
|
|
conn, msg = exc.msg
|
|
|
|
|
2020-07-17 15:36:48 +00:00
|
|
|
proc onClose(c: ConnManager, conn: Connection) {.async.} =
|
|
|
|
## connection close even handler
|
|
|
|
##
|
|
|
|
## triggers the connections resource cleanup
|
|
|
|
##
|
2020-09-04 16:30:45 +00:00
|
|
|
try:
|
|
|
|
await conn.join()
|
2020-09-08 06:24:28 +00:00
|
|
|
trace "Connection closed, cleaning up", conn
|
2020-09-04 16:30:45 +00:00
|
|
|
await c.cleanupConn(conn)
|
|
|
|
except CancelledError:
|
|
|
|
# This is top-level procedure which will work as separate task, so it
|
2020-11-02 20:35:26 +00:00
|
|
|
# do not need to propagate CancelledError.
|
2020-09-08 06:24:28 +00:00
|
|
|
debug "Unexpected cancellation in connection manager's cleanup", conn
|
2020-09-04 16:30:45 +00:00
|
|
|
except CatchableError as exc:
|
2020-09-08 06:24:28 +00:00
|
|
|
debug "Unexpected exception in connection manager's cleanup",
|
|
|
|
errMsg = exc.msg, conn
|
2020-11-02 20:35:26 +00:00
|
|
|
finally:
|
|
|
|
trace "Triggering peerCleanup", conn
|
|
|
|
asyncSpawn c.peerCleanup(conn)
|
2020-07-17 15:36:48 +00:00
|
|
|
|
|
|
|
proc selectConn*(c: ConnManager,
|
2021-12-16 10:05:20 +00:00
|
|
|
peerId: PeerId,
|
2020-07-17 15:36:48 +00:00
|
|
|
dir: Direction): Connection =
|
|
|
|
## Select a connection for the provided peer and direction
|
|
|
|
##
|
|
|
|
let conns = toSeq(
|
2020-08-01 20:50:40 +00:00
|
|
|
c.conns.getOrDefault(peerId))
|
2020-07-17 15:36:48 +00:00
|
|
|
.filterIt( it.dir == dir )
|
|
|
|
|
|
|
|
if conns.len > 0:
|
|
|
|
return conns[0]
|
|
|
|
|
2021-12-16 10:05:20 +00:00
|
|
|
proc selectConn*(c: ConnManager, peerId: PeerId): Connection =
|
2020-07-17 15:36:48 +00:00
|
|
|
## Select a connection for the provided giving priority
|
|
|
|
## to outgoing connections
|
|
|
|
##
|
|
|
|
|
2020-08-01 20:50:40 +00:00
|
|
|
var conn = c.selectConn(peerId, Direction.Out)
|
2020-07-17 15:36:48 +00:00
|
|
|
if isNil(conn):
|
2020-08-01 20:50:40 +00:00
|
|
|
conn = c.selectConn(peerId, Direction.In)
|
2020-08-15 19:50:31 +00:00
|
|
|
if isNil(conn):
|
|
|
|
trace "connection not found", peerId
|
2020-07-17 15:36:48 +00:00
|
|
|
|
|
|
|
return conn
|
|
|
|
|
|
|
|
proc selectMuxer*(c: ConnManager, conn: Connection): Muxer =
|
|
|
|
## select the muxer for the provided connection
|
|
|
|
##
|
|
|
|
|
|
|
|
if isNil(conn):
|
|
|
|
return
|
|
|
|
|
|
|
|
if conn in c.muxed:
|
2021-05-21 16:27:01 +00:00
|
|
|
return c.muxed.getOrDefault(conn).muxer
|
2020-08-15 19:50:31 +00:00
|
|
|
else:
|
2020-09-06 08:31:47 +00:00
|
|
|
debug "no muxer for connection", conn
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2021-05-21 16:27:01 +00:00
|
|
|
proc storeConn*(c: ConnManager, conn: Connection)
|
2021-06-02 13:39:10 +00:00
|
|
|
{.raises: [Defect, LPError].} =
|
2020-07-17 15:36:48 +00:00
|
|
|
## store a connection
|
|
|
|
##
|
|
|
|
|
|
|
|
if isNil(conn):
|
2021-06-02 13:39:10 +00:00
|
|
|
raise newException(LPError, "Connection cannot be nil")
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2021-01-21 04:00:24 +00:00
|
|
|
if conn.closed or conn.atEof:
|
2021-06-02 13:39:10 +00:00
|
|
|
raise newException(LPError, "Connection closed or EOF")
|
2020-12-03 01:24:48 +00:00
|
|
|
|
2021-09-08 09:07:46 +00:00
|
|
|
let peerId = conn.peerId
|
2023-01-23 22:28:39 +00:00
|
|
|
|
|
|
|
# we use getOrDefault in the if below instead of [] to avoid the KeyError
|
|
|
|
if peerId in c.expectedConnections and
|
|
|
|
not(c.expectedConnections.getOrDefault(peerId).finished):
|
|
|
|
c.expectedConnections.getOrDefault(peerId).complete(conn)
|
|
|
|
elif c.conns.getOrDefault(peerId).len > c.maxConnsPerPeer:
|
2021-01-21 04:00:24 +00:00
|
|
|
debug "Too many connections for peer",
|
2020-09-09 17:12:08 +00:00
|
|
|
conn, conns = c.conns.getOrDefault(peerId).len
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2021-01-21 04:00:24 +00:00
|
|
|
raise newTooManyConnectionsError()
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2021-05-19 06:49:55 +00:00
|
|
|
c.conns.mgetOrPut(peerId, HashSet[Connection]()).incl(conn)
|
2021-01-21 04:00:24 +00:00
|
|
|
libp2p_peers.set(c.conns.len.int64)
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2020-09-04 16:30:45 +00:00
|
|
|
# Launch on close listener
|
|
|
|
# All the errors are handled inside `onClose()` procedure.
|
|
|
|
asyncSpawn c.onClose(conn)
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2020-09-08 06:24:28 +00:00
|
|
|
trace "Stored connection",
|
2020-09-09 17:12:08 +00:00
|
|
|
conn, direction = $conn.dir, connections = c.conns.len
|
2020-08-15 19:50:31 +00:00
|
|
|
|
2022-08-03 14:48:19 +00:00
|
|
|
proc getIncomingSlot*(c: ConnManager): Future[ConnectionSlot] {.async.} =
|
|
|
|
await c.inSema.acquire()
|
|
|
|
return ConnectionSlot(connManager: c, direction: In)
|
2021-01-21 04:00:24 +00:00
|
|
|
|
2023-01-05 14:02:52 +00:00
|
|
|
proc getOutgoingSlot*(c: ConnManager, forceDial = false): ConnectionSlot {.raises: [Defect, TooManyConnectionsError].} =
|
2022-02-24 16:31:47 +00:00
|
|
|
if forceDial:
|
|
|
|
c.outSema.forceAcquire()
|
|
|
|
elif not c.outSema.tryAcquire():
|
2021-01-21 04:00:24 +00:00
|
|
|
trace "Too many outgoing connections!", count = c.outSema.count,
|
|
|
|
max = c.outSema.size
|
|
|
|
raise newTooManyConnectionsError()
|
2022-08-03 14:48:19 +00:00
|
|
|
return ConnectionSlot(connManager: c, direction: Out)
|
2021-01-21 04:00:24 +00:00
|
|
|
|
2023-01-24 16:04:42 +00:00
|
|
|
proc slotsAvailable*(c: ConnManager, dir: Direction): int =
|
|
|
|
case dir:
|
|
|
|
of Direction.In:
|
|
|
|
return c.inSema.count
|
|
|
|
of Direction.Out:
|
|
|
|
return c.outSema.count
|
|
|
|
|
2022-08-03 14:48:19 +00:00
|
|
|
proc release*(cs: ConnectionSlot) =
|
|
|
|
if cs.direction == In:
|
|
|
|
cs.connManager.inSema.release()
|
|
|
|
else:
|
|
|
|
cs.connManager.outSema.release()
|
2021-01-21 04:00:24 +00:00
|
|
|
|
2022-08-03 14:48:19 +00:00
|
|
|
proc trackConnection*(cs: ConnectionSlot, conn: Connection) =
|
|
|
|
if isNil(conn):
|
|
|
|
cs.release()
|
|
|
|
return
|
|
|
|
|
|
|
|
proc semaphoreMonitor() {.async.} =
|
|
|
|
try:
|
|
|
|
await conn.join()
|
|
|
|
except CatchableError as exc:
|
|
|
|
trace "Exception in semaphore monitor, ignoring", exc = exc.msg
|
|
|
|
|
|
|
|
cs.release()
|
|
|
|
|
|
|
|
asyncSpawn semaphoreMonitor()
|
2020-07-17 15:36:48 +00:00
|
|
|
|
|
|
|
proc storeMuxer*(c: ConnManager,
|
|
|
|
muxer: Muxer,
|
2021-05-21 16:27:01 +00:00
|
|
|
handle: Future[void] = nil)
|
|
|
|
{.raises: [Defect, CatchableError].} =
|
2020-07-17 15:36:48 +00:00
|
|
|
## store the connection and muxer
|
|
|
|
##
|
|
|
|
|
|
|
|
if isNil(muxer):
|
|
|
|
raise newException(CatchableError, "muxer cannot be nil")
|
|
|
|
|
|
|
|
if isNil(muxer.connection):
|
|
|
|
raise newException(CatchableError, "muxer's connection cannot be nil")
|
|
|
|
|
2020-12-03 01:24:48 +00:00
|
|
|
if muxer.connection notin c:
|
|
|
|
raise newException(CatchableError, "cant add muxer for untracked connection")
|
|
|
|
|
2020-07-17 15:36:48 +00:00
|
|
|
c.muxed[muxer.connection] = MuxerHolder(
|
|
|
|
muxer: muxer,
|
|
|
|
handle: handle)
|
|
|
|
|
2020-09-09 17:12:08 +00:00
|
|
|
trace "Stored muxer",
|
|
|
|
muxer, handle = not handle.isNil, connections = c.conns.len
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2021-01-04 18:59:05 +00:00
|
|
|
asyncSpawn c.onConnUpgraded(muxer.connection)
|
2020-11-02 20:35:26 +00:00
|
|
|
|
2020-11-24 06:37:45 +00:00
|
|
|
proc getStream*(c: ConnManager,
|
2021-12-16 10:05:20 +00:00
|
|
|
peerId: PeerId,
|
2021-01-21 04:00:24 +00:00
|
|
|
dir: Direction): Future[Connection] {.async, gcsafe.} =
|
2020-07-17 15:36:48 +00:00
|
|
|
## get a muxed stream for the provided peer
|
|
|
|
## with the given direction
|
|
|
|
##
|
|
|
|
|
2020-08-01 20:50:40 +00:00
|
|
|
let muxer = c.selectMuxer(c.selectConn(peerId, dir))
|
2020-07-17 15:36:48 +00:00
|
|
|
if not(isNil(muxer)):
|
|
|
|
return await muxer.newStream()
|
|
|
|
|
2020-11-24 06:37:45 +00:00
|
|
|
proc getStream*(c: ConnManager,
|
2021-12-16 10:05:20 +00:00
|
|
|
peerId: PeerId): Future[Connection] {.async, gcsafe.} =
|
2020-07-17 15:36:48 +00:00
|
|
|
## get a muxed stream for the passed peer from any connection
|
|
|
|
##
|
|
|
|
|
2020-08-01 20:50:40 +00:00
|
|
|
let muxer = c.selectMuxer(c.selectConn(peerId))
|
2020-07-17 15:36:48 +00:00
|
|
|
if not(isNil(muxer)):
|
|
|
|
return await muxer.newStream()
|
|
|
|
|
2020-11-24 06:37:45 +00:00
|
|
|
proc getStream*(c: ConnManager,
|
2021-01-21 04:00:24 +00:00
|
|
|
conn: Connection): Future[Connection] {.async, gcsafe.} =
|
2020-07-17 15:36:48 +00:00
|
|
|
## get a muxed stream for the passed connection
|
|
|
|
##
|
|
|
|
|
|
|
|
let muxer = c.selectMuxer(conn)
|
|
|
|
if not(isNil(muxer)):
|
|
|
|
return await muxer.newStream()
|
|
|
|
|
2021-12-16 10:05:20 +00:00
|
|
|
proc dropPeer*(c: ConnManager, peerId: PeerId) {.async.} =
|
2020-07-17 15:36:48 +00:00
|
|
|
## drop connections and cleanup resources for peer
|
|
|
|
##
|
2020-09-08 06:24:28 +00:00
|
|
|
trace "Dropping peer", peerId
|
2020-08-01 20:50:40 +00:00
|
|
|
let conns = c.conns.getOrDefault(peerId)
|
|
|
|
for conn in conns:
|
2020-09-15 20:19:22 +00:00
|
|
|
trace "Removing connection", conn
|
2020-08-01 20:50:40 +00:00
|
|
|
delConn(c, conn)
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2020-08-01 20:50:40 +00:00
|
|
|
var muxers: seq[MuxerHolder]
|
|
|
|
for conn in conns:
|
|
|
|
if conn in c.muxed:
|
|
|
|
muxers.add c.muxed[conn]
|
|
|
|
c.muxed.del(conn)
|
|
|
|
|
|
|
|
for muxer in muxers:
|
|
|
|
await closeMuxerHolder(muxer)
|
|
|
|
|
|
|
|
for conn in conns:
|
|
|
|
await conn.close()
|
2020-09-15 20:19:22 +00:00
|
|
|
trace "Dropped peer", peerId
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2020-11-11 19:20:14 +00:00
|
|
|
trace "Peer dropped", peerId
|
|
|
|
|
2020-07-17 15:36:48 +00:00
|
|
|
proc close*(c: ConnManager) {.async.} =
|
|
|
|
## cleanup resources for the connection
|
|
|
|
## manager
|
|
|
|
##
|
2020-09-09 17:12:08 +00:00
|
|
|
|
|
|
|
trace "Closing ConnManager"
|
2020-08-01 20:50:40 +00:00
|
|
|
let conns = c.conns
|
|
|
|
c.conns.clear()
|
|
|
|
|
|
|
|
let muxed = c.muxed
|
|
|
|
c.muxed.clear()
|
|
|
|
|
2023-01-23 22:28:39 +00:00
|
|
|
let expected = c.expectedConnections
|
|
|
|
c.expectedConnections.clear()
|
|
|
|
|
|
|
|
for _, fut in expected:
|
|
|
|
await fut.cancelAndWait()
|
|
|
|
|
2020-08-01 20:50:40 +00:00
|
|
|
for _, muxer in muxed:
|
|
|
|
await closeMuxerHolder(muxer)
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2020-08-01 20:50:40 +00:00
|
|
|
for _, conns2 in conns:
|
|
|
|
for conn in conns2:
|
|
|
|
await conn.close()
|
2020-09-09 17:12:08 +00:00
|
|
|
|
|
|
|
trace "Closed ConnManager"
|
2022-12-16 11:32:00 +00:00
|
|
|
|