nim-libp2p-experimental/libp2p/muxers/muxer.nim

73 lines
2.2 KiB
Nim
Raw Normal View History

2019-09-03 20:40:51 +00:00
## Nim-LibP2P
2019-09-24 17:48:23 +00:00
## Copyright (c) 2019 Status Research & Development GmbH
2019-09-03 20:40:51 +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.
import chronos, chronicles
2019-09-12 17:07:34 +00:00
import ../protocols/protocol,
2019-09-06 06:51:19 +00:00
../connection
2019-09-03 20:40:51 +00:00
logScope:
topic = "Muxer"
2019-09-03 20:40:51 +00:00
type
StreamHandler* = proc(conn: Connection): Future[void] {.gcsafe.}
MuxerHandler* = proc(muxer: Muxer): Future[void] {.gcsafe.}
2019-09-03 20:40:51 +00:00
Muxer* = ref object of RootObj
streamHandler*: StreamHandler
2019-09-03 20:40:51 +00:00
connection*: Connection
MuxerCreator* = proc(conn: Connection): Muxer {.gcsafe, closure.}
# this wraps a creator proc that knows how to make muxers
MuxerProvider* = ref object of LPProtocol
newMuxer*: MuxerCreator
2019-09-06 06:51:19 +00:00
streamHandler*: StreamHandler
muxerHandler*: MuxerHandler
2019-09-06 06:51:19 +00:00
2019-09-06 21:27:55 +00:00
method newStream*(m: Muxer, name: string = ""): Future[Connection] {.base, async, gcsafe.} = discard
2019-09-06 06:51:19 +00:00
method close*(m: Muxer) {.base, async, gcsafe.} = discard
method handle*(m: Muxer): Future[void] {.base, async, gcsafe.} = discard
2019-09-12 17:07:34 +00:00
method `streamHandler=`*(m: Muxer, handler: StreamHandler) {.base, gcsafe.} =
2019-09-06 06:51:19 +00:00
m.streamHandler = handler
2019-09-03 20:40:51 +00:00
proc newMuxerProvider*(creator: MuxerCreator, codec: string): MuxerProvider {.gcsafe.} =
new result
result.newMuxer = creator
result.codec = codec
2019-09-06 06:51:19 +00:00
result.init()
2019-09-12 17:07:34 +00:00
method `streamHandler=`*(m: MuxerProvider, handler: StreamHandler) {.base, gcsafe.} =
## new stream (channels) handler
##
## triggered every time there is a new
## stream (channel) oppened over a muxed
## connection
##
2019-09-06 06:51:19 +00:00
m.streamHandler = handler
2019-09-12 17:07:34 +00:00
method `muxerHandler=`*(m: MuxerProvider, handler: MuxerHandler) {.base, gcsafe.} =
## new muxer (muxed connections) handler
##
## triggered every time there is a new muxed
## connection created
##
m.muxerHandler = handler
2019-09-03 20:40:51 +00:00
method init(c: MuxerProvider) =
proc handler(conn: Connection, proto: string) {.async, gcsafe, closure.} =
let muxer = c.newMuxer(conn)
if not isNil(c.muxerHandler):
asyncCheck c.muxerHandler(muxer)
2019-09-06 06:51:19 +00:00
if not isNil(c.streamHandler):
muxer.streamHandler = c.streamHandler
await muxer.handle()
2019-09-03 20:40:51 +00:00
c.handler = handler