nim-libp2p/libp2p/stream/lpstream.nim

165 lines
5.0 KiB
Nim
Raw Normal View History

2019-09-01 17:31:24 +00:00
## Nim-LibP2P
2019-09-24 17:48:23 +00:00
## Copyright (c) 2019 Status Research & Development GmbH
2019-09-01 17:31:24 +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 oids
2020-05-08 20:58:23 +00:00
import chronicles, chronos, strformat
import ../varint,
../vbuffer
2019-09-01 17:31:24 +00:00
type
2019-09-01 17:31:24 +00:00
LPStream* = ref object of RootObj
isClosed*: bool
isEof*: bool
closeEvent*: AsyncEvent
when chronicles.enabledLogLevel == LogLevel.TRACE:
oid*: Oid
2019-09-01 17:31:24 +00:00
LPStreamError* = object of CatchableError
LPStreamIncompleteError* = object of LPStreamError
LPStreamIncorrectDefect* = object of Defect
2019-09-01 17:31:24 +00:00
LPStreamLimitError* = object of LPStreamError
LPStreamReadError* = object of LPStreamError
par*: ref Exception
LPStreamWriteError* = object of LPStreamError
par*: ref Exception
LPStreamEOFError* = object of LPStreamError
LPStreamClosedError* = object of LPStreamError
2019-09-01 17:31:24 +00:00
2020-05-08 20:58:23 +00:00
InvalidVarintError* = object of LPStreamError
MaxSizeError* = object of LPStreamError
proc newLPStreamReadError*(p: ref Exception): ref Exception =
2019-09-01 21:56:00 +00:00
var w = newException(LPStreamReadError, "Read stream failed")
2019-09-01 17:31:24 +00:00
w.msg = w.msg & ", originated from [" & $p.name & "] " & p.msg
w.par = p
result = w
proc newLPStreamReadError*(msg: string): ref Exception =
newException(LPStreamReadError, msg)
proc newLPStreamWriteError*(p: ref Exception): ref Exception =
2019-09-01 17:31:24 +00:00
var w = newException(LPStreamWriteError, "Write stream failed")
w.msg = w.msg & ", originated from [" & $p.name & "] " & p.msg
w.par = p
result = w
proc newLPStreamIncompleteError*(): ref Exception =
2019-09-01 17:31:24 +00:00
result = newException(LPStreamIncompleteError, "Incomplete data received")
proc newLPStreamLimitError*(): ref Exception =
2019-09-01 17:31:24 +00:00
result = newException(LPStreamLimitError, "Buffer limit reached")
proc newLPStreamIncorrectDefect*(m: string): ref Exception =
result = newException(LPStreamIncorrectDefect, m)
2019-09-01 17:31:24 +00:00
proc newLPStreamEOFError*(): ref Exception =
result = newException(LPStreamEOFError, "Stream EOF!")
2019-09-04 06:40:11 +00:00
proc newLPStreamClosedError*(): ref Exception =
result = newException(LPStreamClosedError, "Stream Closed!")
method closed*(s: LPStream): bool {.base, inline.} =
s.isClosed
method atEof*(s: LPStream): bool {.base, inline.} =
s.isEof
method readExactly*(s: LPStream,
pbytes: pointer,
nbytes: int):
Future[void] {.base, async.} =
2019-10-03 19:29:58 +00:00
doAssert(false, "not implemented!")
2019-09-01 17:31:24 +00:00
method readOnce*(s: LPStream,
pbytes: pointer,
nbytes: int):
Future[int]
{.base, async.} =
2019-10-03 19:29:58 +00:00
doAssert(false, "not implemented!")
2019-09-01 17:31:24 +00:00
proc readLine*(s: LPStream, limit = 0, sep = "\r\n"): Future[string] {.async, deprecated: "todo".} =
# TODO replace with something that exploits buffering better
var lim = if limit <= 0: -1 else: limit
var state = 0
try:
while true:
var ch: char
await readExactly(s, addr ch, 1)
if sep[state] == ch:
inc(state)
if state == len(sep):
break
else:
state = 0
if limit > 0:
let missing = min(state, lim - len(result) - 1)
result.add(sep[0 ..< missing])
else:
result.add(sep[0 ..< state])
result.add(ch)
if len(result) == lim:
break
except LPStreamIncompleteError, LPStreamReadError:
discard # EOF, in which case we should return whatever we read so far..
2019-09-01 17:31:24 +00:00
2020-05-08 20:58:23 +00:00
proc readVarint*(conn: LPStream): Future[uint64] {.async, gcsafe.} =
var
varint: uint64
length: int
buffer: array[10, byte]
for i in 0..<len(buffer):
await conn.readExactly(addr buffer[i], 1)
let res = PB.getUVarint(buffer.toOpenArray(0, i), length, varint)
if res.isOk():
2020-05-08 20:58:23 +00:00
return varint
if res.error() != VarintError.Incomplete:
2020-05-08 20:58:23 +00:00
break
if true: # can't end with a raise apparently
raise (ref InvalidVarintError)(msg: "Cannot parse varint")
proc readLp*(s: LPStream, maxSize: int): Future[seq[byte]] {.async, gcsafe.} =
## read length prefixed msg, with the length encoded as a varint
let
length = await s.readVarint()
maxLen = uint64(if maxSize < 0: int.high else: maxSize)
if length > maxLen:
raise (ref MaxSizeError)(msg: "Message exceeds maximum length")
if length == 0:
return
var res = newSeq[byte](length)
await s.readExactly(addr res[0], res.len)
return res
proc writeLp*(s: LPStream, msg: string | seq[byte]): Future[void] {.gcsafe.} =
## write length prefixed
var buf = initVBuffer()
buf.writeSeq(msg)
buf.finish()
s.write(buf.buffer)
method write*(s: LPStream, msg: seq[byte]) {.base, async.} =
2019-10-03 19:29:58 +00:00
doAssert(false, "not implemented!")
2019-09-01 17:31:24 +00:00
proc write*(s: LPStream, pbytes: pointer, nbytes: int): Future[void] {.deprecated: "seq".} =
s.write(@(toOpenArray(cast[ptr UncheckedArray[byte]](pbytes), 0, nbytes - 1)))
2019-09-01 17:31:24 +00:00
proc write*(s: LPStream, msg: string): Future[void] =
s.write(@(toOpenArrayByte(msg, 0, msg.high)))
2019-09-01 17:31:24 +00:00
method close*(s: LPStream)
{.base, async.} =
2019-10-03 19:29:58 +00:00
doAssert(false, "not implemented!")