nim-libp2p/libp2p/switch.nim

70 lines
2.3 KiB
Nim
Raw Normal View History

2019-08-27 21:46:12 +00:00
## Nim-LibP2P
## Copyright (c) 2018 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.
2019-08-31 17:58:49 +00:00
import tables, sequtils
2019-08-27 21:46:12 +00:00
import chronos
2019-09-01 17:31:24 +00:00
import connection, transport,
stream/lpstream,
2019-08-31 17:58:49 +00:00
multistream, protocol,
2019-08-30 05:17:07 +00:00
peerinfo, multiaddress
type
Switch* = ref object of RootObj
2019-08-30 05:17:07 +00:00
peerInfo*: PeerInfo
connections*: TableRef[string, Connection]
transports*: seq[Transport]
protocols*: seq[LPProtocol]
ms*: MultisteamSelect
2019-08-27 21:46:12 +00:00
2019-08-28 02:30:53 +00:00
proc newSwitch*(peerInfo: PeerInfo, transports: seq[Transport]): Switch =
new result
result.peerInfo = peerInfo
result.ms = newMultistream()
result.transports = transports
result.connections = newTable[string, Connection]()
2019-08-31 17:58:49 +00:00
result.protocols = newSeq[LPProtocol]()
proc secure(s: Switch, conn: Connection) {.async, gcsafe.} =
## secure the incoming connection
discard
proc dial*(s: Switch, peer: PeerInfo, proto: string = ""): Future[Connection] {.async.} =
for t in s.transports: # for each transport
for a in peer.addrs: # for each address
if t.handles(a): # check if it can dial it
result = await t.dial(a)
2019-08-31 18:52:56 +00:00
await s.secure(result)
if not await s.ms.select(result, proto):
raise newException(CatchableError,
"Unable to select protocol: " & proto)
2019-08-27 21:46:12 +00:00
2019-08-31 17:58:49 +00:00
proc mount*[T: LPProtocol](s: Switch, proto: T) =
if isNil(proto.handler):
raise newException(CatchableError,
"Protocol has to define a handle method or proc")
2019-08-27 21:46:12 +00:00
2019-08-31 18:52:56 +00:00
if len(proto.codec) <= 0:
raise newException(CatchableError,
"Protocol has to define a codec string")
2019-08-31 17:58:49 +00:00
s.ms.addHandler(proto.codec, proto)
2019-08-28 02:30:53 +00:00
proc start*(s: Switch) {.async.} =
2019-08-31 18:52:56 +00:00
proc handle(conn: Connection): Future[void] {.async, closure, gcsafe.} =
await s.secure(conn) # secure the connection
await s.ms.handle(conn) # fire up the ms handler
2019-08-27 21:46:12 +00:00
2019-08-28 02:30:53 +00:00
for t in s.transports: # for each transport
for a in s.peerInfo.addrs:
if t.handles(a): # check if it handles the multiaddr
await t.listen(a, handle) # listen for incoming connections
2019-08-27 21:46:12 +00:00
2019-08-28 02:30:53 +00:00
proc stop*(s: Switch) {.async.} =
2019-08-31 17:58:49 +00:00
await allFutures(s.transports.mapIt(it.close()))