Skip to content

Commit

Permalink
chore(protocol): list raised exceptions (#1260)
Browse files Browse the repository at this point in the history
  • Loading branch information
vladopajic authored Feb 25, 2025
1 parent f4c94dd commit b07ec5c
Show file tree
Hide file tree
Showing 29 changed files with 407 additions and 250 deletions.
21 changes: 12 additions & 9 deletions examples/circuitrelay.nim
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,18 @@ proc main() {.async.} =
let customProtoCodec = "/test"
var proto = new LPProtocol
proto.codec = customProtoCodec
proto.handler = proc(conn: Connection, proto: string) {.async.} =
var msg = string.fromBytes(await conn.readLp(1024))
echo "1 - Dst Received: ", msg
assert "test1" == msg
await conn.writeLp("test2")
msg = string.fromBytes(await conn.readLp(1024))
echo "2 - Dst Received: ", msg
assert "test3" == msg
await conn.writeLp("test4")
proto.handler = proc(conn: Connection, proto: string) {.async: (raises: []).} =
try:
var msg = string.fromBytes(await conn.readLp(1024))
echo "1 - Dst Received: ", msg
assert "test1" == msg
await conn.writeLp("test2")
msg = string.fromBytes(await conn.readLp(1024))
echo "2 - Dst Received: ", msg
assert "test3" == msg
await conn.writeLp("test4")
except:
echo "exception in handler", getCurrentException().msg

let
relay = Relay.new()
Expand Down
15 changes: 9 additions & 6 deletions examples/directchat.nim
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,15 @@ proc new(T: typedesc[ChatProto], c: Chat): T =
let chatproto = T()

# create handler for incoming connection
proc handle(stream: Connection, proto: string) {.async.} =
if c.connected and not c.conn.closed:
c.writeStdout "a chat session is already in progress - refusing incoming peer!"
await stream.close()
else:
await c.handlePeer(stream)
proc handle(stream: Connection, proto: string) {.async: (raises: []).} =
try:
if c.connected and not c.conn.closed:
c.writeStdout "a chat session is already in progress - refusing incoming peer!"
else:
await c.handlePeer(stream)
except:
echo "exception in handler", getCurrentException().msg
finally:
await stream.close()

# assign the new handler
Expand Down
15 changes: 9 additions & 6 deletions examples/helloworld.nim
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,15 @@ type TestProto = ref object of LPProtocol # declare a custom protocol

proc new(T: typedesc[TestProto]): T =
# every incoming connections will be in handled in this closure
proc handle(conn: Connection, proto: string) {.async.} =
echo "Got from remote - ", string.fromBytes(await conn.readLp(1024))
await conn.writeLp("Roger p2p!")

# We must close the connections ourselves when we're done with it
await conn.close()
proc handle(conn: Connection, proto: string) {.async: (raises: []).} =
try:
echo "Got from remote - ", string.fromBytes(await conn.readLp(1024))
await conn.writeLp("Roger p2p!")
except:
echo "exception in handler", getCurrentException().msg
finally:
# We must close the connections ourselves when we're done with it
await conn.close()

return T.new(codecs = @[TestCodec], handler = handle)

Expand Down
11 changes: 7 additions & 4 deletions examples/tutorial_2_customproto.nim
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,15 @@ type TestProto = ref object of LPProtocol

proc new(T: typedesc[TestProto]): T =
# every incoming connections will in be handled in this closure
proc handle(conn: Connection, proto: string) {.async.} =
proc handle(conn: Connection, proto: string) {.async: (raises: []).} =
# Read up to 1024 bytes from this connection, and transform them into
# a string
echo "Got from remote - ", string.fromBytes(await conn.readLp(1024))
# We must close the connections ourselves when we're done with it
await conn.close()
try:
echo "Got from remote - ", string.fromBytes(await conn.readLp(1024))
except:
echo "exception in handler", getCurrentException().msg
finally:
await conn.close()

return T.new(codecs = @[TestCodec], handler = handle)

Expand Down
16 changes: 10 additions & 6 deletions examples/tutorial_3_protobuf.nim
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,16 @@ type

proc new(_: typedesc[MetricProto], cb: MetricCallback): MetricProto =
var res: MetricProto
proc handle(conn: Connection, proto: string) {.async.} =
let
metrics = await res.metricGetter()
asProtobuf = metrics.encode()
await conn.writeLp(asProtobuf.buffer)
await conn.close()
proc handle(conn: Connection, proto: string) {.async: (raises: []).} =
try:
let
metrics = await res.metricGetter()
asProtobuf = metrics.encode()
await conn.writeLp(asProtobuf.buffer)
except:
echo "exception in handler", getCurrentException().msg
finally:
await conn.close()

res = MetricProto.new(@["/metric-getter/1.0.0"], handle)
res.metricGetter = cb
Expand Down
10 changes: 7 additions & 3 deletions examples/tutorial_5_discovery.nim
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,13 @@ proc createSwitch(rdv: RendezVous = RendezVous.new()): Switch =
const DumbCodec = "/dumb/proto/1.0.0"
type DumbProto = ref object of LPProtocol
proc new(T: typedesc[DumbProto], nodeNumber: int): T =
proc handle(conn: Connection, proto: string) {.async.} =
echo "Node", nodeNumber, " received: ", string.fromBytes(await conn.readLp(1024))
await conn.close()
proc handle(conn: Connection, proto: string) {.async: (raises: []).} =
try:
echo "Node", nodeNumber, " received: ", string.fromBytes(await conn.readLp(1024))
except:
echo "exception in handler", getCurrentException().msg
finally:
await conn.close()

return T.new(codecs = @[DumbCodec], handler = handle)

Expand Down
29 changes: 16 additions & 13 deletions examples/tutorial_6_game.nim
Original file line number Diff line number Diff line change
Expand Up @@ -152,21 +152,24 @@ proc draw(g: Game) =
## peer know that we are available, check that he is also available,
## and launch the game.
proc new(T: typedesc[GameProto], g: Game): T =
proc handle(conn: Connection, proto: string) {.async.} =
proc handle(conn: Connection, proto: string) {.async: (raises: []).} =
defer:
await conn.closeWithEof()
if g.peerFound.finished or g.hasCandidate:
await conn.close()
return
g.hasCandidate = true
await conn.writeLp("ok")
if "ok" != string.fromBytes(await conn.readLp(1024)):
g.hasCandidate = false
return
g.peerFound.complete(conn)
# The handler of a protocol must wait for the stream to
# be finished before returning
await conn.join()
try:
if g.peerFound.finished or g.hasCandidate:
await conn.close()
return
g.hasCandidate = true
await conn.writeLp("ok")
if "ok" != string.fromBytes(await conn.readLp(1024)):
g.hasCandidate = false
return
g.peerFound.complete(conn)
# The handler of a protocol must wait for the stream to
# be finished before returning
await conn.join()
except:
echo "exception in handler", getCurrentException().msg

return T.new(codecs = @["/tron/1.0.0"], handler = handle)

Expand Down
6 changes: 4 additions & 2 deletions libp2p/protocols/connectivity/autonat/server.nim
Original file line number Diff line number Diff line change
Expand Up @@ -162,15 +162,17 @@ proc new*(
): T =
let autonat =
T(switch: switch, sem: newAsyncSemaphore(semSize), dialTimeout: dialTimeout)
proc handleStream(conn: Connection, proto: string) {.async.} =
proc handleStream(conn: Connection, proto: string) {.async: (raises: []).} =
try:
let msg = AutonatMsg.decode(await conn.readLp(1024)).valueOr:
raise newException(AutonatError, "Received malformed message")
if msg.msgType != MsgType.Dial:
raise newException(AutonatError, "Message type should be dial")
await autonat.handleDial(conn, msg)
except CancelledError as exc:
raise exc
trace "cancelled autonat handler"
except CatchableError as exc:
debug "exception in autonat handler", description = exc.msg, conn
finally:
trace "exiting autonat handler", conn
await conn.close()
Expand Down
4 changes: 2 additions & 2 deletions libp2p/protocols/connectivity/dcutr/server.nim
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ proc new*(
connectTimeout = 15.seconds,
maxDialableAddrs = 8,
): T =
proc handleStream(stream: Connection, proto: string) {.async.} =
proc handleStream(stream: Connection, proto: string) {.async: (raises: []).} =
var peerDialableAddrs: seq[MultiAddress]
try:
let connectMsg = DcutrMsg.decode(await stream.readLp(1024))
Expand Down Expand Up @@ -77,7 +77,7 @@ proc new*(
for fut in futs:
fut.cancel()
except CancelledError as err:
raise err
trace "cancelled Dcutr receiver"
except AllFuturesFailedError as err:
debug "Dcutr receiver could not connect to the remote peer, " &
"all connect attempts failed", peerDialableAddrs, description = err.msg
Expand Down
4 changes: 2 additions & 2 deletions libp2p/protocols/connectivity/relay/client.nim
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ proc new*(
msgSize: msgSize,
isCircuitRelayV1: circuitRelayV1,
)
proc handleStream(conn: Connection, proto: string) {.async.} =
proc handleStream(conn: Connection, proto: string) {.async: (raises: []).} =
try:
case proto
of RelayV1Codec:
Expand All @@ -300,7 +300,7 @@ proc new*(
of RelayV2HopCodec:
await cl.handleHopStreamV2(conn)
except CancelledError as exc:
raise exc
trace "cancelled client handler"
except CatchableError as exc:
trace "exception in client handler", description = exc.msg, conn
finally:
Expand Down
6 changes: 3 additions & 3 deletions libp2p/protocols/connectivity/relay/relay.nim
Original file line number Diff line number Diff line change
Expand Up @@ -359,15 +359,15 @@ proc new*(
isCircuitRelayV1: circuitRelayV1,
)

proc handleStream(conn: Connection, proto: string) {.async.} =
proc handleStream(conn: Connection, proto: string) {.async: (raises: []).} =
try:
case proto
of RelayV2HopCodec:
await r.handleHopStreamV2(conn)
of RelayV1Codec:
await r.handleStreamV1(conn)
except CancelledError as exc:
raise exc
except CancelledError:
trace "cancelled relayv2 handler"
except CatchableError as exc:
debug "exception in relayv2 handler", description = exc.msg, conn
finally:
Expand Down
10 changes: 5 additions & 5 deletions libp2p/protocols/identify.nim
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,13 @@ proc new*(
identify

method init*(p: Identify) =
proc handle(conn: Connection, proto: string) {.async.} =
proc handle(conn: Connection, proto: string) {.async: (raises: []).} =
try:
trace "handling identify request", conn
var pb = encodeMsg(p.peerInfo, conn.observedAddr, p.sendSignedPeerRecord)
await conn.writeLp(pb.buffer)
except CancelledError as exc:
raise exc
except CancelledError:
trace "cancelled identify handler"
except CatchableError as exc:
trace "exception in identify handler", description = exc.msg, conn
finally:
Expand Down Expand Up @@ -205,7 +205,7 @@ proc new*(T: typedesc[IdentifyPush], handler: IdentifyPushHandler = nil): T {.pu
identifypush

proc init*(p: IdentifyPush) =
proc handle(conn: Connection, proto: string) {.async.} =
proc handle(conn: Connection, proto: string) {.async: (raises: []).} =
trace "handling identify push", conn
try:
var message = await conn.readLp(64 * 1024)
Expand All @@ -224,7 +224,7 @@ proc init*(p: IdentifyPush) =
if not isNil(p.identifyHandler):
await p.identifyHandler(conn.peerId, identInfo)
except CancelledError as exc:
raise exc
trace "cancelled identify push handler"
except CatchableError as exc:
info "exception in identify push handler", description = exc.msg, conn
finally:
Expand Down
7 changes: 4 additions & 3 deletions libp2p/protocols/perf/server.nim
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type Perf* = ref object of LPProtocol

proc new*(T: typedesc[Perf]): T {.public.} =
var p = T()
proc handle(conn: Connection, proto: string) {.async.} =
proc handle(conn: Connection, proto: string) {.async: (raises: []).} =
var bytesRead = 0
try:
trace "Received benchmark performance check", conn
Expand All @@ -47,10 +47,11 @@ proc new*(T: typedesc[Perf]): T {.public.} =
await conn.write(buf[0 ..< toWrite])
size -= toWrite
except CancelledError as exc:
raise exc
trace "cancelled perf handler"
except CatchableError as exc:
trace "exception in perf handler", description = exc.msg, conn
await conn.close()
finally:
await conn.close()

p.handler = handle
p.codec = PerfCodec
Expand Down
4 changes: 2 additions & 2 deletions libp2p/protocols/ping.nim
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ proc new*(
ping

method init*(p: Ping) =
proc handle(conn: Connection, proto: string) {.async.} =
proc handle(conn: Connection, proto: string) {.async: (raises: []).} =
try:
trace "handling ping", conn
var buf: array[PingSize, byte]
Expand All @@ -61,7 +61,7 @@ method init*(p: Ping) =
if not isNil(p.pingHandler):
await p.pingHandler(conn.peerId)
except CancelledError as exc:
raise exc
trace "cancelled ping handler"
except CatchableError as exc:
trace "exception in ping handler", description = exc.msg, conn

Expand Down
3 changes: 2 additions & 1 deletion libp2p/protocols/protocol.nim
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ export results
const DefaultMaxIncomingStreams* = 10

type
LPProtoHandler* = proc(conn: Connection, proto: string): Future[void] {.async.}
LPProtoHandler* =
proc(conn: Connection, proto: string): Future[void] {.async: (raises: []).}

LPProtocol* = ref object of RootObj
codecs*: seq[string]
Expand Down
2 changes: 1 addition & 1 deletion libp2p/protocols/pubsub/floodsub.nim
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ method rpcHandler*(
f.updateMetrics(rpcMsg)

method init*(f: FloodSub) =
proc handler(conn: Connection, proto: string) {.async.} =
proc handler(conn: Connection, proto: string) {.async: (raises: []).} =
## main protocol handler that gets triggered on every
## connection for a protocol string
## e.g. ``/floodsub/1.0.0``, etc...
Expand Down
2 changes: 1 addition & 1 deletion libp2p/protocols/pubsub/gossipsub.nim
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ proc validateParameters*(parameters: TopicParams): Result[void, cstring] =
ok()

method init*(g: GossipSub) =
proc handler(conn: Connection, proto: string) {.async.} =
proc handler(conn: Connection, proto: string) {.async: (raises: []).} =
## main protocol handler that gets triggered on every
## connection for a protocol string
## e.g. ``/floodsub/1.0.0``, etc...
Expand Down
6 changes: 3 additions & 3 deletions libp2p/protocols/rendezvous.nim
Original file line number Diff line number Diff line change
Expand Up @@ -718,7 +718,7 @@ proc new*(
)
logScope:
topics = "libp2p discovery rendezvous"
proc handleStream(conn: Connection, proto: string) {.async.} =
proc handleStream(conn: Connection, proto: string) {.async: (raises: []).} =
try:
let
buf = await conn.readLp(4096)
Expand All @@ -734,8 +734,8 @@ proc new*(
await rdv.discover(conn, msg.discover.tryGet())
of MessageType.DiscoverResponse:
trace "Got an unexpected Discover Response", response = msg.discoverResponse
except CancelledError as exc:
raise exc
except CancelledError:
trace "cancelled rendezvous handler"
except CatchableError as exc:
trace "exception in rendezvous handler", description = exc.msg
finally:
Expand Down
2 changes: 1 addition & 1 deletion libp2p/protocols/secure/plaintext.nim
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const PlainTextCodec* = "/plaintext/1.0.0"
type PlainText* = ref object of Secure

method init(p: PlainText) {.gcsafe.} =
proc handle(conn: Connection, proto: string) {.async.} =
proc handle(conn: Connection, proto: string) {.async: (raises: []).} =
## plain text doesn't do anything
discard

Expand Down
Loading

0 comments on commit b07ec5c

Please sign in to comment.