better exceptions and don't fail writes

This commit is contained in:
Dmitriy Ryajov 2020-05-23 10:52:33 -06:00
parent 74f8b5b5f1
commit d3b79b002e
1 changed files with 18 additions and 17 deletions

View File

@ -21,12 +21,12 @@ proc newChronosStream*(client: StreamTransport): ChronosStream =
result.client = client result.client = client
result.closeEvent = newAsyncEvent() result.closeEvent = newAsyncEvent()
template withExceptions(body: untyped) = template withExceptions(body: untyped) =
try: try:
body body
except TransportIncompleteError: except TransportIncompleteError:
raise newLPStreamIncompleteError() # for all intents and purposes this is an EOF
raise newLPStreamEOFError()
except TransportLimitError: except TransportLimitError:
raise newLPStreamLimitError() raise newLPStreamLimitError()
except TransportUseClosedError: except TransportUseClosedError:
@ -60,9 +60,12 @@ method write*(s: ChronosStream, msg: seq[byte]) {.async.} =
return return
withExceptions: withExceptions:
# Returns 0 sometimes when write fails - but there's not much we can do here? var writen = 0
if (await s.client.write(msg)) != msg.len: while not s.client.closed and writen < msg.len:
raise (ref LPStreamError)(msg: "Write couldn't finish writing") writen += await s.client.write(msg[writen..<msg.len])
if writen < msg.len:
raise (ref LPStreamClosedError)(msg: "Write couldn't finish writing")
method closed*(s: ChronosStream): bool {.inline.} = method closed*(s: ChronosStream): bool {.inline.} =
result = s.client.closed result = s.client.closed
@ -71,16 +74,14 @@ method atEof*(s: ChronosStream): bool {.inline.} =
s.client.atEof() s.client.atEof()
method close*(s: ChronosStream) {.async.} = method close*(s: ChronosStream) {.async.} =
try:
if not s.isClosed: if not s.isClosed:
s.isClosed = true s.isClosed = true
trace "shutting chronos stream", address = $s.client.remoteAddress()
trace "shutting down chronos stream", address = $s.client.remoteAddress()
if not s.client.closed(): if not s.client.closed():
try:
await s.client.closeWait() await s.client.closeWait()
except CancelledError as exc:
raise exc
except CatchableError as exc:
# Shouldn't happen, but we can't be sure
warn "error while closing connection", msg = exc.msg
s.closeEvent.fire() s.closeEvent.fire()
except CatchableError as exc:
trace "error closing chronosstream", exc = exc.msg