nim-libp2p-experimental/libp2p/multistreamselect.nim

95 lines
2.6 KiB
Nim
Raw Normal View History

## 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-23 22:17:08 +00:00
import sequtils, strutils
2019-08-23 02:13:36 +00:00
import chronos
import connection, varint, vbuffer
2019-08-23 22:17:08 +00:00
const MsgSize* = 64*1024
2019-08-23 02:13:36 +00:00
const Codec* = "/multistream/1.0.0"
const MultiCodec* = "\x19" & Codec & "\n"
const Na = "\x3na\n"
const Ls = "\x3ls\n"
2019-08-23 02:13:36 +00:00
type
MultisteamSelectException = object of CatchableError
Handler* = proc (conn: Connection, proto: string): Future[void]
Matcher* = proc (proto: string): bool
HandlerHolder* = object
proto: string
handler: Handler
match: Matcher
MultisteamSelect* = ref object of RootObj
handlers*: seq[HandlerHolder]
codec*: string
na*: string
ls*: string
2019-08-23 02:13:36 +00:00
proc newMultistream*(): MultisteamSelect =
new result
result.codec = MultiCodec
result.ls = Ls
result.na = Na
2019-08-23 02:13:36 +00:00
proc select*(m: MultisteamSelect, conn: Connection, proto: string = ""): Future[bool] {.async.} =
2019-08-23 02:13:36 +00:00
## select a remote protocol
## TODO: select should support a list of protos to be selected
2019-08-23 22:17:08 +00:00
await conn.write(m.codec) # write handshake
await conn.writeLp(proto) # select proto
var ms = cast[string](await conn.readLp())
ms.removeSuffix("\n")
if ms != Codec:
2019-08-23 22:17:08 +00:00
raise newException(MultisteamSelectException,
"Error: invalid multistream codec " & "\"" & ms & "\"")
2019-08-23 02:13:36 +00:00
if proto.len() <= 0:
return true
2019-08-23 02:13:36 +00:00
ms = cast[string](await conn.readLp())
ms.removeSuffix("\n")
result = ms == proto
2019-08-23 22:17:08 +00:00
proc handle*(m: MultisteamSelect, conn: Connection) {.async.} =
## handle requests on connection
if not (await m.select(conn)):
return
2019-08-23 22:17:08 +00:00
block handleLoop:
var ms = cast[string](await conn.readLp())
ms.removeSuffix("\n")
if ms.len() <= 0:
await conn.writeLp(Na)
case ms:
of "ls":
for h in m.handlers:
await conn.writeLp(h.proto)
break handleLoop
else:
for h in m.handlers:
if (not isNil(h.match) and h.match(ms)) or ms == h.proto:
await h.handler(conn, ms)
break
else:
await conn.write(Na)
break handleLoop
2019-08-23 02:13:36 +00:00
2019-08-23 22:17:08 +00:00
proc addHandler*(m: MultisteamSelect,
proto: string,
handler: Handler,
matcher: Matcher = nil) =
2019-08-23 02:13:36 +00:00
## register a handler for the protocol
m.handlers.add(HandlerHolder(proto: proto,
handler: handler,
match: matcher))