2019-08-20 16:18:15 +00:00
|
|
|
## Nim-LibP2P
|
|
|
|
## Copyright (c) 2018 Status Research & Development GmbH
|
|
|
|
## 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 chronos, peerinfo, multiaddress
|
|
|
|
|
|
|
|
const DefaultReadSize = 1024
|
|
|
|
|
|
|
|
type
|
|
|
|
Connection* = ref object of RootObj
|
|
|
|
reader: AsyncStreamReader
|
2019-08-21 22:53:16 +00:00
|
|
|
writer: AsyncStreamWriter
|
2019-08-21 19:15:51 +00:00
|
|
|
server: StreamServer
|
|
|
|
client: StreamTransport
|
2019-08-21 22:53:16 +00:00
|
|
|
isOpen*: bool
|
2019-08-20 16:18:15 +00:00
|
|
|
|
2019-08-21 19:15:51 +00:00
|
|
|
proc newConnection*(server: StreamServer,
|
|
|
|
client: StreamTransport): Connection =
|
2019-08-21 22:53:16 +00:00
|
|
|
## create a new Connection for the specified async stream reader/writer
|
2019-08-20 16:18:15 +00:00
|
|
|
new result
|
2019-08-21 22:53:16 +00:00
|
|
|
result.isOpen = false
|
2019-08-21 19:15:51 +00:00
|
|
|
result.server = server
|
|
|
|
result.client = client
|
|
|
|
|
|
|
|
result.reader = newAsyncStreamReader(client)
|
2019-08-21 22:53:16 +00:00
|
|
|
result.writer = newAsyncStreamWriter(client)
|
2019-08-20 16:18:15 +00:00
|
|
|
|
2019-08-21 04:58:12 +00:00
|
|
|
method read* (c: Connection, size: int = DefaultReadSize): Future[seq[byte]] {.base, async, gcsafe.} =
|
2019-08-20 16:18:15 +00:00
|
|
|
## read DefaultReadSize (1024) bytes or `size` bytes if specified
|
|
|
|
result = await c.reader.read(size)
|
|
|
|
|
|
|
|
method write* (c: Connection, data: pointer, size: int): Future[void] {.base, async.} =
|
|
|
|
## write bytes pointed to by `data` up to `size` size
|
2019-08-21 22:53:16 +00:00
|
|
|
discard c.writer.write(data, size)
|
2019-08-20 16:18:15 +00:00
|
|
|
|
|
|
|
method close* (c: Connection): Future[void] {.base, async.} =
|
|
|
|
## close connection
|
2019-08-21 22:53:16 +00:00
|
|
|
await c.reader.closeWait()
|
|
|
|
|
|
|
|
await c.writer.finish()
|
|
|
|
await c.writer.closeWait()
|
|
|
|
|
|
|
|
await c.client.closeWait()
|
|
|
|
c.server.stop()
|
|
|
|
c.server.close()
|
2019-08-20 16:18:15 +00:00
|
|
|
|
|
|
|
method getPeerInfo* (c: Connection): Future[PeerInfo] {.base, async.} =
|
|
|
|
## get up to date peer info
|
|
|
|
## TODO: implement PeerInfo refresh over identify
|
|
|
|
discard
|
|
|
|
|
|
|
|
method getObservedAddrs(c: Connection): Future[seq[MultiAddress]] {.base, async.} =
|
|
|
|
## get resolved multiaddresses for the connection
|
|
|
|
discard
|