nim-libp2p/libp2p/protocols/pubsub/pubsubpeer.nim

61 lines
1.8 KiB
Nim
Raw Normal View History

2019-09-10 02:15:52 +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.
import options
import chronos, chronicles
import ../../connection,
../../protobuf/minprotobuf,
../../peerinfo,
2019-09-12 02:10:38 +00:00
../../peer,
2019-09-12 05:46:08 +00:00
../../crypto/crypto,
2019-09-10 02:15:52 +00:00
rpcmsg
logScope:
topic = "PubSubPeer"
type
PubSubPeer* = ref object of RootObj
2019-09-12 02:10:38 +00:00
peerInfo*: PeerInfo
2019-09-10 02:15:52 +00:00
conn*: Connection
handler*: RPCHandler
topics*: seq[string]
2019-09-12 02:10:38 +00:00
id*: string # base58 peer id string
2019-09-10 02:15:52 +00:00
RPCHandler* = proc(peer: PubSubPeer, msg: seq[RPCMsg]): Future[void] {.gcsafe.}
proc handle*(p: PubSubPeer) {.async, gcsafe.} =
2019-09-12 05:46:08 +00:00
debug "handling pubsub rpc", peer = p.id
2019-09-10 02:15:52 +00:00
try:
while not p.conn.closed:
2019-09-12 02:10:38 +00:00
let data = await p.conn.readLp()
2019-09-12 05:46:08 +00:00
debug "Read data from peer", peer = p.peerInfo, data = data.toHex()
2019-09-12 02:10:38 +00:00
let msg = decodeRpcMsg(data)
debug "Decoded msg from peer", peer = p.peerInfo, msg = msg
2019-09-10 02:15:52 +00:00
await p.handler(p, @[msg])
except:
debug "An exception occured while processing pubsub rpc requests", exc = getCurrentExceptionMsg()
return
finally:
2019-09-12 02:10:38 +00:00
debug "closing connection to pubsub peer", peer = p.id
2019-09-10 02:15:52 +00:00
await p.conn.close()
proc send*(p: PubSubPeer, msgs: seq[RPCMsg]) {.async, gcsafe.} =
for m in msgs:
2019-09-12 02:10:38 +00:00
debug "sending msgs to peer", peer = p.id, msgs = msgs
let encoded = encodeRpcMsg(m)
if encoded.buffer.len > 0:
await p.conn.writeLp(encoded.buffer)
2019-09-10 02:15:52 +00:00
proc newPubSubPeer*(conn: Connection, handler: RPCHandler): PubSubPeer =
new result
result.handler = handler
result.conn = conn
2019-09-12 02:10:38 +00:00
result.peerInfo = conn.peerInfo
result.id = conn.peerInfo.peerId.get().pretty()