2020-07-17 15:36:48 +00:00
|
|
|
## Nim-LibP2P
|
|
|
|
## Copyright (c) 2020 Status Research & Development GmbH
|
|
|
|
## 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.
|
|
|
|
|
2021-05-21 16:27:01 +00:00
|
|
|
{.push raises: [Defect].}
|
|
|
|
|
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,
|
|
|
|
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
|
|
|
|
MaxConnectionsPerPeer* = 5
|
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
|
|
|
|
2021-05-21 16:27:01 +00:00
|
|
|
ConnProvider* = proc(): Future[Connection]
|
|
|
|
{.gcsafe, closure, raises: [Defect].}
|
2020-07-17 15:36:48 +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-06-08 16:55:24 +00:00
|
|
|
proc(peerInfo: PeerInfo, 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* =
|
2021-06-08 16:55:24 +00:00
|
|
|
proc(peerInfo: PeerInfo, event: PeerEvent): Future[void] {.gcsafe.}
|
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
|
2020-07-17 15:36:48 +00:00
|
|
|
conns: Table[PeerID, HashSet[Connection]]
|
|
|
|
muxed: Table[Connection, MuxerHolder]
|
2021-05-19 06:49:55 +00:00
|
|
|
connEvents: array[ConnEventKind, OrderedSet[ConnEventHandler]]
|
|
|
|
peerEvents: array[PeerEventKind, OrderedSet[PeerEventHandler]]
|
2020-07-17 15:36:48 +00:00
|
|
|
|
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
|
|
|
|
|
|
|
proc init*(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
|
|
|
|
2020-09-23 14:07:16 +00:00
|
|
|
proc connCount*(c: ConnManager, peerId: PeerID): int =
|
|
|
|
c.conns.getOrDefault(peerId).len
|
|
|
|
|
|
|
|
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-06-08 16:55:24 +00:00
|
|
|
peerInfo: PeerInfo,
|
2020-11-28 16:59:47 +00:00
|
|
|
event: ConnEvent) {.async, gcsafe.} =
|
2020-09-23 14:07:16 +00:00
|
|
|
try:
|
2021-06-08 16:55:24 +00:00
|
|
|
trace "About to trigger connection events", peer = peerInfo.peerId
|
2021-05-19 06:49:55 +00:00
|
|
|
if c.connEvents[event.kind].len() > 0:
|
2021-06-08 16:55:24 +00:00
|
|
|
trace "triggering connection events", peer = peerInfo.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-06-08 16:55:24 +00:00
|
|
|
connEvents.add(h(peerInfo, 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-06-08 16:55:24 +00:00
|
|
|
msg = exc.msg, peer = peerInfo.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-06-08 16:55:24 +00:00
|
|
|
peerInfo: PeerInfo,
|
2020-09-23 14:07:16 +00:00
|
|
|
event: PeerEvent) {.async, gcsafe.} =
|
|
|
|
|
2021-06-08 16:55:24 +00:00
|
|
|
trace "About to trigger peer events", peer = peerInfo.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-06-08 16:55:24 +00:00
|
|
|
let count = c.connCount(peerInfo.peerId)
|
2020-11-28 16:59:47 +00:00
|
|
|
if event.kind == PeerEventKind.Joined and count != 1:
|
2021-06-08 16:55:24 +00:00
|
|
|
trace "peer already joined", peer = peerInfo.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-06-08 16:55:24 +00:00
|
|
|
trace "peer still connected or already left", peer = peerInfo.peerId, event = $event
|
2020-09-23 14:07:16 +00:00
|
|
|
return
|
|
|
|
|
2021-06-08 16:55:24 +00:00
|
|
|
trace "triggering peer events", peer = peerInfo.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-06-08 16:55:24 +00:00
|
|
|
peerEvents.add(h(peerInfo, 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-06-08 16:55:24 +00:00
|
|
|
warn "Exception in triggerPeerEvents", exc = exc.msg, peer = peerInfo.peerId
|
2020-09-23 14:07:16 +00:00
|
|
|
|
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
|
|
|
|
|
|
|
|
if isNil(conn.peerInfo):
|
|
|
|
return
|
|
|
|
|
2020-11-18 00:48:26 +00:00
|
|
|
return conn in c.conns.getOrDefault(conn.peerInfo.peerId)
|
2020-07-17 15:36:48 +00:00
|
|
|
|
|
|
|
proc contains*(c: ConnManager, peerId: PeerID): bool =
|
|
|
|
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) =
|
|
|
|
let peerId = conn.peerInfo.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
|
|
|
|
|
|
|
|
if isNil(conn.peerInfo):
|
2021-01-21 04:00:24 +00:00
|
|
|
trace "No peer info for 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-06-08 16:55:24 +00:00
|
|
|
let peerInfo = conn.peerInfo
|
2020-11-28 16:59:47 +00:00
|
|
|
await c.triggerPeerEvents(
|
2021-06-08 16:55:24 +00:00
|
|
|
peerInfo, 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-06-08 16:55:24 +00:00
|
|
|
peerInfo, 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-06-08 16:55:24 +00:00
|
|
|
let peerInfo = conn.peerInfo
|
2020-11-02 20:35:26 +00:00
|
|
|
await c.triggerConnEvent(
|
2021-06-08 16:55:24 +00:00
|
|
|
peerInfo, ConnEvent(kind: ConnEventKind.Disconnected))
|
|
|
|
await c.triggerPeerEvents(peerInfo, PeerEvent(kind: PeerEventKind.Left))
|
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,
|
2020-08-01 20:50:40 +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]
|
|
|
|
|
2020-08-01 20:50:40 +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
|
|
|
|
2020-07-17 15:36:48 +00:00
|
|
|
if isNil(conn.peerInfo):
|
2021-06-02 13:39:10 +00:00
|
|
|
raise newException(LPError, "Empty peer info")
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2020-08-01 20:50:40 +00:00
|
|
|
let peerId = conn.peerInfo.peerId
|
2021-01-21 04:00:24 +00:00
|
|
|
if c.conns.getOrDefault(peerId).len > c.maxConnsPerPeer:
|
|
|
|
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
|
|
|
|
2021-01-21 04:00:24 +00:00
|
|
|
proc trackConn(c: ConnManager,
|
|
|
|
provider: ConnProvider,
|
|
|
|
sema: AsyncSemaphore):
|
|
|
|
Future[Connection] {.async.} =
|
|
|
|
var conn: Connection
|
|
|
|
try:
|
|
|
|
conn = await provider()
|
|
|
|
|
|
|
|
if isNil(conn):
|
|
|
|
return
|
|
|
|
|
|
|
|
trace "Got connection", conn
|
|
|
|
|
|
|
|
proc semaphoreMonitor() {.async.} =
|
|
|
|
try:
|
|
|
|
await conn.join()
|
|
|
|
except CatchableError as exc:
|
|
|
|
trace "Exception in semaphore monitor, ignoring", exc = exc.msg
|
|
|
|
|
|
|
|
sema.release()
|
|
|
|
|
|
|
|
asyncSpawn semaphoreMonitor()
|
|
|
|
except CatchableError as exc:
|
|
|
|
trace "Exception tracking connection", exc = exc.msg
|
|
|
|
if not isNil(conn):
|
|
|
|
await conn.close()
|
|
|
|
|
|
|
|
raise exc
|
|
|
|
|
|
|
|
return conn
|
2020-07-17 15:36:48 +00:00
|
|
|
|
2021-01-21 04:00:24 +00:00
|
|
|
proc trackIncomingConn*(c: ConnManager,
|
|
|
|
provider: ConnProvider):
|
|
|
|
Future[Connection] {.async.} =
|
|
|
|
## await for a connection slot before attempting
|
|
|
|
## to call the connection provider
|
|
|
|
##
|
|
|
|
|
|
|
|
var conn: Connection
|
|
|
|
try:
|
|
|
|
trace "Tracking incoming connection"
|
|
|
|
await c.inSema.acquire()
|
|
|
|
conn = await c.trackConn(provider, c.inSema)
|
|
|
|
if isNil(conn):
|
|
|
|
trace "Couldn't acquire connection, releasing semaphore slot", dir = $Direction.In
|
|
|
|
c.inSema.release()
|
|
|
|
|
|
|
|
return conn
|
|
|
|
except CatchableError as exc:
|
|
|
|
trace "Exception tracking connection", exc = exc.msg
|
|
|
|
c.inSema.release()
|
|
|
|
raise exc
|
|
|
|
|
|
|
|
proc trackOutgoingConn*(c: ConnManager,
|
|
|
|
provider: ConnProvider):
|
|
|
|
Future[Connection] {.async.} =
|
|
|
|
## try acquiring a connection if all slots
|
|
|
|
## are already taken, raise TooManyConnectionsError
|
|
|
|
## exception
|
|
|
|
##
|
|
|
|
|
|
|
|
trace "Tracking outgoing connection", count = c.outSema.count,
|
|
|
|
max = c.outSema.size
|
|
|
|
|
|
|
|
if not c.outSema.tryAcquire():
|
|
|
|
trace "Too many outgoing connections!", count = c.outSema.count,
|
|
|
|
max = c.outSema.size
|
|
|
|
raise newTooManyConnectionsError()
|
|
|
|
|
|
|
|
var conn: Connection
|
|
|
|
try:
|
|
|
|
conn = await c.trackConn(provider, c.outSema)
|
|
|
|
if isNil(conn):
|
|
|
|
trace "Couldn't acquire connection, releasing semaphore slot", dir = $Direction.Out
|
|
|
|
c.outSema.release()
|
|
|
|
|
|
|
|
return conn
|
|
|
|
except CatchableError as exc:
|
|
|
|
trace "Exception tracking connection", exc = exc.msg
|
|
|
|
c.outSema.release()
|
|
|
|
raise exc
|
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-01-21 04:00:24 +00:00
|
|
|
peerId: PeerID,
|
|
|
|
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-01-21 04:00:24 +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()
|
|
|
|
|
2020-08-01 20:50:40 +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()
|
|
|
|
|
|
|
|
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"
|