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

72 lines
2.3 KiB
Nim
Raw Normal View History

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.
2019-09-28 19:55:35 +00:00
import options, sets, hashes, strutils
2019-09-10 02:15:52 +00:00
import chronos, chronicles
import rpcmsg,
2019-09-12 02:10:38 +00:00
../../peer,
../../peerinfo,
../../connection,
2019-09-12 05:46:08 +00:00
../../crypto/crypto,
../../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-28 19:55:35 +00:00
seen: HashSet[string] # list of messages forwarded to peers
2019-09-10 02:15:52 +00:00
RPCHandler* = proc(peer: PubSubPeer, msg: seq[RPCMsg]): Future[void] {.gcsafe.}
proc handle*(p: PubSubPeer) {.async, gcsafe.} =
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()
trace "Read data from peer", peer = p.peerInfo, data = data.toHex()
2019-09-12 02:10:38 +00:00
let msg = decodeRpcMsg(data)
trace "Decoded msg from peer", peer = p.peerInfo, msg = msg
2019-09-10 02:15:52 +00:00
await p.handler(p, @[msg])
except:
error "An exception occured while processing pubsub rpc requests", exc = getCurrentExceptionMsg()
2019-09-10 02:15:52 +00:00
finally:
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:
trace "sending msgs to peer", peer = p.id, msgs = msgs
2019-09-12 02:10:38 +00:00
let encoded = encodeRpcMsg(m)
2019-09-28 19:55:35 +00:00
if encoded.buffer.len <= 0:
trace "empty message, skipping", peer = p.id
return
let encodedHex = encoded.buffer.toHex()
trace "sending encoded msgs to peer", peer = p.id, encoded = encodedHex
if p.seen.contains(encodedHex):
trace "message already sent to peer, skipping", peer = p.id
continue
await p.conn.writeLp(encoded.buffer)
p.seen.incl(encodedHex)
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()
2019-09-28 19:55:35 +00:00
result.seen = initSet[string]()