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

252 lines
8.2 KiB
Nim
Raw Normal View History

import asyncdispatch, asyncnet, json, tables, macros, strutils
export asyncdispatch, asyncnet, json
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
macro rpc*(prc: untyped): untyped =
## Converts a procedure into the following format:
## <proc name>*(params: JsonNode): Future[JsonNode] {.async.}
## This procedure is then added into a compile-time list
## so that it is automatically registered for every server that
## calls registerRpcs(server)
prc.expectKind nnkProcDef
result = prc
let
params = prc.params
procName = prc.name
procName.expectKind(nnkIdent)
# check there isn't already a result type
assert params[0].kind == nnkEmpty
# add parameter
params.add nnkIdentDefs.newTree(
newIdentNode("params"),
newIdentNode("JsonNode"),
newEmptyNode()
)
# set result type
params[0] = nnkBracketExpr.newTree(
newIdentNode("Future"),
newIdentNode("JsonNode")
)
# add async pragma; we can assume there isn't an existing .async.
# as this would mean there's a return type and fail the result check above.
prc.addPragma(newIdentNode("async"))
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 fromJson(n: JsonNode, argName: string, result: var bool) =
if n.kind != JBool: raise newException(ValueError, "Parameter \"" & argName & "\" expected JBool but got " & $n.kind)
result = n.getBool()
2018-05-08 11:51:24 +01:00
proc fromJson(n: JsonNode, argName: string, result: var int) =
if n.kind != JInt: raise newException(ValueError, "Parameter \"" & argName & "\" expected JInt but got " & $n.kind)
2018-05-08 11:51:24 +01:00
result = n.getInt()
proc fromJson(n: JsonNode, argName: string, result: var byte) =
if n.kind != JInt: raise newException(ValueError, "Parameter \"" & argName & "\" expected JInt but got " & $n.kind)
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)
proc fromJson(n: JsonNode, argName: string, result: var float) =
if n.kind != JFloat: raise newException(ValueError, "Parameter \"" & argName & "\" expected JFloat but got " & $n.kind)
2018-05-08 11:51:24 +01:00
result = n.getFloat()
proc fromJson(n: JsonNode, argName: string, result: var string) =
if n.kind != JString: raise newException(ValueError, "Parameter \"" & argName & "\" expected JString but got " & $n.kind)
2018-05-08 11:51:24 +01:00
result = n.getStr()
proc fromJson[T](n: JsonNode, argName: string, result: var seq[T]) =
if n.kind != JArray: raise newException(ValueError, "Parameter \"" & argName & "\" expected JArray but got " & $n.kind)
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]) =
if n.kind != JArray: raise newException(ValueError, "Parameter \"" & argName & "\" expected JArray but got " & $n.kind)
if n.len > result.len: raise newException(ValueError, "Parameter \"" & argName & "\" item count is too big for array")
for i in 0 ..< n.len:
fromJson(n[i], argName, result[i])
2018-05-08 11:51:24 +01:00
proc fromJson[T: object](n: JsonNode, argName: string, result: var T) =
if n.kind != JObject: raise newException(ValueError, "Parameter \"" & argName & "\" expected JObject but got " & $n.kind)
2018-05-08 11:51:24 +01:00
for k, v in fieldpairs(result):
fromJson(n[k], k, v)
2018-05-08 11:51:24 +01:00
proc unpackArg[T](argIdx: int, argName: string, argtype: typedesc[T], args: JsonNode): T =
fromJson(args[argIdx], argName, result)
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
var expectedLen = parameters.len - 1
let expectedStr = "Expected " & $expectedLen & " Json parameter(s) but got "
result.add(quote do:
if `paramsIdent`.kind != JArray:
raise newException(ValueError, "Parameter params expected JArray but got " & $`paramsIdent`.kind)
if `paramsIdent`.len != `expectedLen`:
raise newException(ValueError, `expectedStr` & $`paramsIdent`.len)
)
# 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
paramName = parameters[i][0]
pos = i - 1
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:
2018-05-08 11:51:24 +01:00
var `paramName` = `unpackArg`(`pos`, `paramNameStr`, `paramType`, `paramsIdent`)
2018-05-01 20:32:28 +01:00
)
else:
# no parameters expected
result.add(quote do:
if `paramsIdent`.len != 0:
raise newException(ValueError, "Expected no parameters but got " & $`paramsIdent`.len)
)
macro multiRemove(s: string, values: varargs[string]): untyped =
## Wrapper for multiReplace
var
body = newStmtList()
multiReplaceCall = newCall(ident"multiReplace", s)
body.add(newVarStmt(ident"eStr", newStrLitNode("")))
let emptyStr = ident"eStr"
for item in values:
# generate tuples of values with the empty string `eStr`
let sItem = $item
multiReplaceCall.add(newPar(newStrLitNode(sItem), emptyStr))
body.add multiReplaceCall
result = newBlockStmt(body)
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"
var setup = setupParams(parameters, paramsIdent)
2018-05-01 20:32:28 +01:00
# wrapping proc
let
pathStr = $path
procName = ident(pathStr.multiRemove(".", "/")) # TODO: Make this unique to avoid potential clashes, or allow people to know the name for calling?
var procBody: NimNode
if body.kind == nnkStmtList: procBody = body
else: procBody = body.body
result = quote do:
proc `procName`*(`paramsIdent`: JsonNode): Future[JsonNode] {.async.} =
2018-05-01 20:32:28 +01:00
`setup`
`procBody`
`server`.register(`path`, `procName`)
when defined(nimDumpRpcs):
2018-05-01 20:32:28 +01:00
echo pathStr, ": ", result.repr
when isMainModule:
import unittest
var s = newRpcServer("localhost")
2018-05-08 11:51:24 +01:00
s.on("rpc.simplepath"):
result = %1
s.on("rpc.returnint") do() -> int:
result = %2
s.on("rpc.differentparams") do(a: int, b: string):
var node = %"test"
result = node
s.on("rpc.arrayparam") do(arr: array[0..5, byte], b: string):
var res = newJArray()
2018-04-24 19:21:51 +01:00
for item in arr:
res.add %int(item)
res.add %b
result = %res
2018-05-01 20:32:28 +01:00
s.on("rpc.seqparam") do(a: string, s: seq[int]):
2018-04-24 19:21:51 +01:00
var res = newJArray()
2018-05-01 20:32:28 +01:00
res.add %a
for item in s:
res.add %int(item)
result = res
2018-05-02 16:21:05 +01:00
type
Test2 = object
2018-05-08 11:51:24 +01:00
x: array[0..2, int]
y: string
2018-05-02 16:21:05 +01:00
Test = object
2018-05-08 11:51:24 +01:00
a: array[0..1, int]
b: Test2
2018-05-01 20:32:28 +01:00
2018-05-08 11:51:24 +01:00
MyObject* = object
a: int
b: Test
c: float
let
testObj = %*{
"a": %1,
"b": %*{
"a": %[5, 0],
"b": %*{
"x": %[1, 2, 3],
"y": %"test"
}
},
"c": %1.23}
2018-05-03 20:20:10 +01:00
2018-05-01 20:32:28 +01:00
s.on("rpc.objparam") do(a: string, obj: MyObject):
result = %obj
suite "Server types":
2018-05-08 11:51:24 +01:00
test "On macro registration":
check s.procs.hasKey("rpc.simplepath")
check s.procs.hasKey("rpc.returnint")
check s.procs.hasKey("rpc.returnint")
2018-04-24 19:21:51 +01:00
test "Array/seq parameters":
let r1 = waitfor rpcArrayParam(%[%[1, 2, 3], %"hello"])
2018-04-24 19:21:51 +01:00
var ckR1 = %[1, 2, 3, 0, 0, 0]
ckR1.elems.add %"hello"
check r1 == ckR1
let r2 = waitfor rpcSeqParam(%[%"abc", %[1, 2, 3, 4, 5]])
2018-04-24 19:21:51 +01:00
var ckR2 = %["abc"]
for i in 0..4: ckR2.add %(i + 1)
check r2 == ckR2
test "Object parameters":
let r = waitfor rpcObjParam(%[%"abc", testObj])
check r == testObj
test "Runtime errors":
expect ValueError:
2018-05-01 20:32:28 +01:00
echo waitfor rpcArrayParam(%[%[0, 1, 2, 3, 4, 5, 6], %"hello"])
2018-05-08 11:51:24 +01:00