2019-09-10 02:15:52 +00:00
|
|
|
## Nim-LibP2P
|
2019-09-24 17:48:23 +00:00
|
|
|
## Copyright (c) 2019 Status Research & Development GmbH
|
2019-09-10 02:15:52 +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 options
|
|
|
|
import chronos, chronicles
|
2019-09-24 16:16:39 +00:00
|
|
|
import rpcmsg,
|
2019-09-12 02:10:38 +00:00
|
|
|
../../peer,
|
2019-09-24 16:16:39 +00:00
|
|
|
../../peerinfo,
|
|
|
|
../../connection,
|
2019-09-12 05:46:08 +00:00
|
|
|
../../crypto/crypto,
|
2019-09-24 16:16:39 +00:00
|
|
|
../../protobuf/minprotobuf
|
2019-09-10 02:15:52 +00:00
|
|
|
|
|
|
|
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-23 21:51:28 +00:00
|
|
|
trace "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-23 21:51:28 +00:00
|
|
|
trace "Read data from peer", peer = p.peerInfo, data = data.toHex()
|
2019-09-12 02:10:38 +00:00
|
|
|
let msg = decodeRpcMsg(data)
|
2019-09-23 21:51:28 +00:00
|
|
|
trace "Decoded msg from peer", peer = p.peerInfo, msg = msg
|
2019-09-10 02:15:52 +00:00
|
|
|
await p.handler(p, @[msg])
|
|
|
|
except:
|
2019-09-23 21:51:28 +00:00
|
|
|
error "An exception occured while processing pubsub rpc requests", exc = getCurrentExceptionMsg()
|
2019-09-10 02:15:52 +00:00
|
|
|
finally:
|
2019-09-23 21:51:28 +00:00
|
|
|
trace "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-23 21:51:28 +00:00
|
|
|
trace "sending msgs to peer", peer = p.id, msgs = msgs
|
2019-09-12 02:10:38 +00:00
|
|
|
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()
|