nim-json-rpc/eth-rpc/client/clientdispatch.nim

114 lines
4.2 KiB
Nim
Raw Normal View History

2018-03-02 11:46:59 +00:00
import asyncnet, asyncdispatch, tables, json, oids, ethcalls, macros
type
RpcClient* = ref object
socket: AsyncSocket
awaiting: Table[string, Future[Response]]
address: string
port: Port
Response* = tuple[error: bool, result: JsonNode]
proc newRpcClient*(): RpcClient =
## Creates a new ``RpcClient`` instance.
RpcClient(
socket: newAsyncSocket(),
awaiting: initTable[string, Future[Response]]()
)
proc call*(self: RpcClient, name: string, params: JsonNode): Future[Response] {.async.} =
## Remotely calls the specified RPC method.
2018-04-11 15:34:49 +03:00
# REVIEW: is there a reason why a simple counter is not used here?
# genOid takes CPU cycles and the output is larger
2018-03-22 17:27:28 +00:00
let id = $genOid()
2018-03-02 11:46:59 +00:00
let msg = %{"jsonrpc": %"2.0", "method": %name, "params": params, "id": %id}
2018-04-11 15:34:49 +03:00
# REVIEW: it would be more efficient if you append the terminating new line to
# the `msg` variable in-place. This way, a copy won't be performed most of the
# time because the string is likely to have 2 bytes of unused capacity.
2018-03-02 11:46:59 +00:00
await self.socket.send($msg & "\c\l")
2018-03-22 17:27:28 +00:00
# Completed by processMessage.
var newFut = newFuture[Response]()
self.awaiting[id] = newFut # add to awaiting responses
result = await newFut
2018-03-02 11:46:59 +00:00
proc isNull(node: JsonNode): bool = node.kind == JNull
proc processMessage(self: RpcClient, line: string) =
let node = parseJson(line)
2018-04-11 15:34:49 +03:00
# REVIEW: These shouldn't be just asserts. You cannot count
# that the other side implements the protocol correctly, so
# you must perform validation even in release builds.
2018-03-02 11:46:59 +00:00
assert node.hasKey("jsonrpc")
assert node["jsonrpc"].str == "2.0"
assert node.hasKey("id")
assert self.awaiting.hasKey(node["id"].str)
if node["error"].kind == JNull:
self.awaiting[node["id"].str].complete((false, node["result"]))
self.awaiting.del(node["id"].str)
else:
2018-03-22 17:27:28 +00:00
# If the node id is null, we cannot complete the future.
2018-03-02 11:46:59 +00:00
if not node["id"].isNull:
self.awaiting[node["id"].str].complete((true, node["error"]))
# TODO: Safe to delete here?
self.awaiting.del(node["id"].str)
proc connect*(self: RpcClient, address: string, port: Port): Future[void]
proc processData(self: RpcClient) {.async.} =
while true:
# read until no data
let line = await self.socket.recvLine()
if line == "":
# transmission ends
self.socket.close() # TODO: Do we need to drop/reacquire sockets?
self.socket = newAsyncSocket()
break
processMessage(self, line)
# async loop reconnection and waiting
await connect(self, self.address, self.port)
proc connect*(self: RpcClient, address: string, port: Port) {.async.} =
await self.socket.connect(address, port)
self.address = address
self.port = port
asyncCheck processData(self)
2018-03-22 17:27:28 +00:00
proc makeTemplate(name: string, params: NimNode, body: NimNode, starred: bool): NimNode =
2018-03-02 11:46:59 +00:00
# set up template AST
result = newNimNode(nnkTemplateDef)
2018-03-22 17:27:28 +00:00
if starred: result.add postFix(ident(name), "*")
else: result.add ident(name)
2018-03-02 11:46:59 +00:00
result.add newEmptyNode(), newEmptyNode(), params, newEmptyNode(), newEmptyNode(), body
proc appendFormalParam(formalParams: NimNode, identName, typeName: string) =
# set up formal params AST
formalParams.expectKind(nnkFormalParams)
if formalParams.len == 0: formalParams.add newEmptyNode()
var identDef = newIdentDefs(ident(identName), ident(typeName))
formalParams.add identDef
macro generateCalls: untyped =
## Generate templates for client calls so that:
## client.call("web3_clientVersion", params)
## can be written as:
## client.web3_clientVersion(params)
result = newStmtList()
for callName in ETHEREUM_RPC_CALLS:
2018-04-11 15:34:49 +03:00
# REVIEW: `macros.quote` would have worked well here to make the code easier to understand/maintain
2018-03-02 11:46:59 +00:00
var
params = newNimNode(nnkFormalParams)
2018-03-22 17:27:28 +00:00
call = newCall(newDotExpr(ident("client"), ident("call")), newStrLitNode(callName), ident("params"))
2018-03-02 11:46:59 +00:00
body = newStmtList().add call
templ = makeTemplate(callName, params, body, true)
params.add newNimNode(nnkBracketExpr).add(ident("Future"), ident("Response"))
params.appendFormalParam("client", "RpcClient")
params.appendFormalParam("params", "JsonNode")
result.add templ
# generate all client ethereum rpc calls
generateCalls()