nim-json-rpc/eth-rpc/server/servertypes.nim

197 lines
6.8 KiB
Nim
Raw Normal View History

import asyncdispatch, asyncnet, json, tables, macros, strutils, jsonconverters, stint
export asyncdispatch, asyncnet, json, jsonconverters
2018-03-02 11:46:59 +00:00
type
2018-04-11 20:08:12 +01:00
RpcProc* = proc (params: JsonNode): Future[JsonNode]
2018-03-02 11:46:59 +00:00
RpcServer* = ref object
socket*: AsyncSocket
port*: Port
address*: string
procs*: TableRef[string, RpcProc]
RpcProcError* = ref object of Exception
code*: int
data*: JsonNode
proc register*(server: RpcServer, name: string, rpc: RpcProc) =
server.procs[name] = rpc
proc unRegisterAll*(server: RpcServer) = server.procs.clear
proc newRpcServer*(address = "localhost", port: Port = Port(8545)): RpcServer =
result = RpcServer(
2018-03-02 11:46:59 +00:00
socket: newAsyncSocket(),
port: port,
address: address,
procs: newTable[string, RpcProc]()
)
var sharedServer: RpcServer
proc sharedRpcServer*(): RpcServer =
if sharedServer.isNil: sharedServer = newRpcServer("")
result = sharedServer
proc `$`*(port: Port): string = $int(port)
2018-05-09 14:26:28 +01:00
template expect*(actual, expected: JsonNodeKind, argName: string) =
if actual != expected: raise newException(ValueError, "Parameter \"" & argName & "\" expected " & $expected & " but got " & $actual)
proc fromJson(n: JsonNode, argName: string, result: var bool) =
2018-05-09 14:26:28 +01:00
n.kind.expect(JBool, argName)
result = n.getBool()
2018-05-08 11:51:24 +01:00
proc fromJson(n: JsonNode, argName: string, result: var int) =
2018-05-09 14:26:28 +01:00
n.kind.expect(JInt, argName)
2018-05-08 11:51:24 +01:00
result = n.getInt()
2018-05-10 14:09:44 +01:00
# TODO: Why does compiler complain that result cannot be assigned to when using result: var int|var int64
# TODO: Compiler requires forward decl when processing out of module
proc fromJson(n: JsonNode, argName: string, result: var byte)
proc fromJson(n: JsonNode, argName: string, result: var float)
proc fromJson(n: JsonNode, argName: string, result: var string)
proc fromJson[T](n: JsonNode, argName: string, result: var seq[T])
proc fromJson[N, T](n: JsonNode, argName: string, result: var array[N, T])
proc fromJson(n: JsonNode, argName: string, result: var UInt256)
2018-05-10 14:09:44 +01:00
# TODO: Why can't this be forward declared? Complains of lack of definition
proc fromJson[T: enum](n: JsonNode, argName: string, result: var T) =
n.kind.expect(JInt, argName)
result = n.getInt().T
# TODO: Why can't this be forward declared? Complains of lack of definition
proc fromJson[T: object](n: JsonNode, argName: string, result: var T) =
for k, v in fieldpairs(result):
fromJson(n[k], k, v)
proc fromJson(n: JsonNode, argName: string, result: var int64) =
n.kind.expect(JInt, argName)
result = n.getInt()
proc fromJson(n: JsonNode, argName: string, result: var byte) =
2018-05-09 14:26:28 +01:00
n.kind.expect(JInt, argName)
2018-05-08 11:51:24 +01:00
let v = n.getInt()
if v > 255 or v < 0: raise newException(ValueError, "Parameter \"" & argName & "\" value out of range for byte: " & $v)
2018-05-08 11:51:24 +01:00
result = byte(v)
2018-05-10 14:09:44 +01:00
proc fromJson(n: JsonNode, argName: string, result: var UInt256) =
n.kind.expect(JString, argName)
result = n.getStr().parse(StUint[256]) # TODO: Requires error checking?
2018-05-10 14:09:44 +01:00
proc fromJson(n: JsonNode, argName: string, result: var float) =
2018-05-09 14:26:28 +01:00
n.kind.expect(JFloat, argName)
2018-05-08 11:51:24 +01:00
result = n.getFloat()
proc fromJson(n: JsonNode, argName: string, result: var string) =
2018-05-09 14:26:28 +01:00
n.kind.expect(JString, argName)
2018-05-08 11:51:24 +01:00
result = n.getStr()
proc fromJson[T](n: JsonNode, argName: string, result: var seq[T]) =
2018-05-08 11:51:24 +01:00
result = newSeq[T](n.len)
for i in 0 ..< n.len:
fromJson(n[i], argName, result[i])
2018-05-08 11:51:24 +01:00
proc fromJson[N, T](n: JsonNode, argName: string, result: var array[N, T]) =
for i in 0 ..< n.len:
fromJson(n[i], argName, result[i])
2018-05-08 11:51:24 +01:00
proc unpackArg[T](argIdx: int, argName: string, argtype: typedesc[T], args: JsonNode): T =
when argType is array or argType is seq:
2018-05-09 14:26:28 +01:00
args[argIdx].kind.expect(JArray, argName)
when argType is array:
if args[argIdx].len > result.len: raise newException(ValueError, "Parameter \"" & argName & "\" item count is too big for array")
when argType is object:
2018-05-09 14:26:28 +01:00
args[argIdx].kind.expect(JObject, argName)
fromJson(args[argIdx], argName, result)
proc expectArrayLen(node: NimNode, paramsIdent: untyped, length: int) =
2018-05-09 14:26:28 +01:00
let
identStr = paramsIdent.repr
expectedStr = "Expected " & $length & " Json parameter(s) but got "
node.add(quote do:
2018-05-09 14:26:28 +01:00
`paramsIdent`.kind.expect(JArray, `identStr`)
if `paramsIdent`.len != `length`:
raise newException(ValueError, `expectedStr` & $`paramsIdent`.len)
)
proc setupParams(parameters, paramsIdent: NimNode): NimNode =
# Add code to verify input and load parameters into Nim types
result = newStmtList()
if not parameters.isNil:
# initial parameter array length check
result.expectArrayLen(paramsIdent, parameters.len - 1)
# unpack each parameter and provide assignments
2018-05-08 11:51:24 +01:00
for i in 1 ..< parameters.len:
2018-05-01 20:32:28 +01:00
let
pos = i - 1
paramName = parameters[i][0]
2018-05-08 11:51:24 +01:00
paramNameStr = $paramName
2018-05-01 20:32:28 +01:00
paramType = parameters[i][1]
result.add(quote do:
var `paramName` = `unpackArg`(`pos`, `paramNameStr`, type(`paramType`), `paramsIdent`)
2018-05-01 20:32:28 +01:00
)
proc makeProcName(s: string): string =
# only alpha
result = ""
for c in s:
if c.isAlphaAscii: result.add c
proc hasReturnType(params: NimNode): bool =
if params.len > 0 and params[0] != nil and params[0].kind != nnkEmpty:
result = true
2018-05-01 20:32:28 +01:00
macro on*(server: var RpcServer, path: string, body: untyped): untyped =
result = newStmtList()
let
parameters = body.findChild(it.kind == nnkFormalParams)
paramsIdent = ident"params" # all remote calls have a single parameter: `params: JsonNode`
pathStr = $path # procs are generated from the stripped path
procName = ident(pathStr.makeProcName)
doMain = genSym(nskProc) # proc that contains our rpc body
res = ident"result" # async result
2018-05-08 16:03:28 +01:00
var
setup = setupParams(parameters, paramsIdent)
procBody: NimNode
2018-05-08 17:29:23 +01:00
if body.kind == nnkStmtList: procBody = body
else: procBody = body.body
2018-05-08 17:29:23 +01:00
if parameters.hasReturnType:
let returnType = parameters[0]
# `doMain` is outside of async transformation,
# allowing natural `return`
result.add(quote do:
proc `doMain`(`paramsIdent`: JsonNode): `returnType` {.inline.} =
`setup`
2018-05-08 17:29:23 +01:00
`procBody`
)
# Note ``res` =` (which becomes `result = `) will be transformed by {.async.} to `complete`
if returnType == ident"JsonNode":
# `JsonNode` results don't need conversion
result.add( quote do:
proc `procName`*(`paramsIdent`: JsonNode): Future[JsonNode] {.async.} =
`res` = `doMain`(`paramsIdent`)
)
else:
result.add( quote do:
proc `procName`*(`paramsIdent`: JsonNode): Future[JsonNode] {.async.} =
`res` = %`doMain`(`paramsIdent`)
)
2018-05-08 17:29:23 +01:00
else:
# no return types, inline contents
result.add( quote do:
2018-05-08 17:29:23 +01:00
proc `procName`*(`paramsIdent`: JsonNode): Future[JsonNode] {.async.} =
`setup`
`procBody`
)
result.add( quote do:
`server`.register(`path`, `procName`)
)
when defined(nimDumpRpcs):
2018-05-08 16:03:28 +01:00
echo "\n", pathStr, ": ", result.repr