2018-07-10 09:39:09 +00:00
|
|
|
import
|
2020-03-18 16:14:29 +00:00
|
|
|
json, tables, strutils, macros, options,
|
|
|
|
chronicles, chronos, json_serialization/writer,
|
|
|
|
jsonmarshal
|
|
|
|
|
|
|
|
export
|
|
|
|
chronos, json, jsonmarshal
|
2018-07-06 16:47:43 +00:00
|
|
|
|
|
|
|
type
|
2019-04-28 19:59:33 +00:00
|
|
|
RpcJsonError* = enum
|
|
|
|
rjeInvalidJson, rjeVersionError, rjeNoMethod, rjeNoId, rjeNoParams, rjeNoJObject
|
2018-07-10 09:39:09 +00:00
|
|
|
RpcJsonErrorContainer* = tuple[err: RpcJsonError, msg: string]
|
|
|
|
|
2020-03-18 16:14:29 +00:00
|
|
|
StringOfJson* = JsonString
|
2020-03-17 18:36:23 +00:00
|
|
|
|
2018-07-06 16:47:43 +00:00
|
|
|
# Procedure signature accepted as an RPC call by server
|
2020-03-17 18:36:23 +00:00
|
|
|
RpcProc* = proc(input: JsonNode): Future[StringOfJson] {.gcsafe.}
|
2019-02-06 17:27:58 +00:00
|
|
|
|
2018-07-10 09:39:09 +00:00
|
|
|
RpcProcError* = ref object of Exception
|
|
|
|
code*: int
|
|
|
|
data*: JsonNode
|
|
|
|
|
|
|
|
RpcBindError* = object of Exception
|
|
|
|
RpcAddressUnresolvableError* = object of Exception
|
2018-07-06 16:47:43 +00:00
|
|
|
|
|
|
|
RpcRouter* = object
|
|
|
|
procs*: TableRef[string, RpcProc]
|
2018-07-10 09:39:09 +00:00
|
|
|
|
2018-07-06 16:47:43 +00:00
|
|
|
const
|
|
|
|
methodField = "method"
|
|
|
|
paramsField = "params"
|
2018-07-10 09:39:09 +00:00
|
|
|
jsonRpcField = "jsonrpc"
|
|
|
|
idField = "id"
|
|
|
|
messageTerminator = "\c\l"
|
|
|
|
|
|
|
|
JSON_PARSE_ERROR* = -32700
|
|
|
|
INVALID_REQUEST* = -32600
|
|
|
|
METHOD_NOT_FOUND* = -32601
|
|
|
|
INVALID_PARAMS* = -32602
|
|
|
|
INTERNAL_ERROR* = -32603
|
|
|
|
SERVER_ERROR* = -32000
|
|
|
|
|
|
|
|
defaultMaxRequestLength* = 1024 * 128
|
|
|
|
jsonErrorMessages*: array[RpcJsonError, (int, string)] =
|
|
|
|
[
|
|
|
|
(JSON_PARSE_ERROR, "Invalid JSON"),
|
|
|
|
(INVALID_REQUEST, "JSON 2.0 required"),
|
|
|
|
(INVALID_REQUEST, "No method requested"),
|
|
|
|
(INVALID_REQUEST, "No id specified"),
|
2019-04-28 19:59:33 +00:00
|
|
|
(INVALID_PARAMS, "No parameters specified"),
|
|
|
|
(INVALID_PARAMS, "Invalid request object")
|
2018-07-10 09:39:09 +00:00
|
|
|
]
|
2018-07-06 16:47:43 +00:00
|
|
|
|
|
|
|
proc newRpcRouter*: RpcRouter =
|
|
|
|
result.procs = newTable[string, RpcProc]()
|
|
|
|
|
|
|
|
proc register*(router: var RpcRouter, path: string, call: RpcProc) =
|
|
|
|
router.procs.add(path, call)
|
|
|
|
|
|
|
|
proc clear*(router: var RpcRouter) = router.procs.clear
|
|
|
|
|
|
|
|
proc hasMethod*(router: RpcRouter, methodName: string): bool = router.procs.hasKey(methodName)
|
|
|
|
|
2018-08-29 12:44:30 +00:00
|
|
|
func isEmpty(node: JsonNode): bool = node.isNil or node.kind == JNull
|
2018-07-06 16:47:43 +00:00
|
|
|
|
2018-07-10 09:39:09 +00:00
|
|
|
# Json state checking
|
2018-07-06 16:47:43 +00:00
|
|
|
|
2018-07-10 09:39:09 +00:00
|
|
|
template jsonValid*(jsonString: string, node: var JsonNode): (bool, string) =
|
|
|
|
var
|
|
|
|
valid = true
|
|
|
|
msg = ""
|
2019-12-02 11:14:00 +00:00
|
|
|
try:
|
|
|
|
node = parseJson(line)
|
2021-02-07 19:27:34 +00:00
|
|
|
# Handle cases where params is omitted
|
|
|
|
if not node.hasKey(paramsField):
|
|
|
|
node.add(paramsField, newJArray())
|
2019-12-02 11:14:00 +00:00
|
|
|
except CatchableError as exc:
|
2018-07-10 09:39:09 +00:00
|
|
|
valid = false
|
2019-12-02 11:14:00 +00:00
|
|
|
msg = exc.msg
|
2018-07-10 09:39:09 +00:00
|
|
|
debug "Cannot process json", json = jsonString, msg = msg
|
|
|
|
(valid, msg)
|
2018-07-06 16:47:43 +00:00
|
|
|
|
2018-07-10 09:39:09 +00:00
|
|
|
proc checkJsonState*(line: string,
|
|
|
|
node: var JsonNode): Option[RpcJsonErrorContainer] =
|
|
|
|
## Tries parsing line into node, if successful checks required fields
|
|
|
|
## Returns: error state or none
|
|
|
|
let res = jsonValid(line, node)
|
|
|
|
if not res[0]:
|
|
|
|
return some((rjeInvalidJson, res[1]))
|
2019-04-28 19:59:33 +00:00
|
|
|
if node.kind != JObject:
|
|
|
|
return some((rjeNoJObject, ""))
|
2018-07-10 09:39:09 +00:00
|
|
|
if not node.hasKey(idField):
|
|
|
|
return some((rjeNoId, ""))
|
|
|
|
let jVer = node{jsonRpcField}
|
|
|
|
if jVer != nil and jVer.kind != JNull and jVer != %"2.0":
|
|
|
|
return some((rjeVersionError, ""))
|
2019-05-09 13:31:28 +00:00
|
|
|
if not node.hasKey(methodField) or node[methodField].kind != JString:
|
2018-07-10 09:39:09 +00:00
|
|
|
return some((rjeNoMethod, ""))
|
|
|
|
if not node.hasKey(paramsField):
|
|
|
|
return some((rjeNoParams, ""))
|
|
|
|
return none(RpcJsonErrorContainer)
|
|
|
|
|
|
|
|
# Json reply wrappers
|
|
|
|
|
2020-03-17 18:36:23 +00:00
|
|
|
proc wrapReply*(id: JsonNode, value, error: StringOfJson): StringOfJson =
|
|
|
|
return StringOfJson(
|
2020-03-17 20:05:42 +00:00
|
|
|
"""{"jsonrpc":"2.0","id":$1,"result":$2,"error":$3}""" % [
|
2020-03-17 18:36:23 +00:00
|
|
|
$id, string(value), string(error)
|
|
|
|
])
|
2018-07-10 09:39:09 +00:00
|
|
|
|
|
|
|
proc wrapError*(code: int, msg: string, id: JsonNode,
|
2020-03-17 18:36:23 +00:00
|
|
|
data: JsonNode = newJNull()): StringOfJson {.gcsafe.} =
|
2018-07-10 09:39:09 +00:00
|
|
|
# Create standardised error json
|
2020-03-17 18:36:23 +00:00
|
|
|
result = StringOfJson(
|
2020-03-17 20:05:42 +00:00
|
|
|
"""{"code":$1,"id":$2,"message":$3,"data":$4}""" % [
|
2020-03-17 18:36:23 +00:00
|
|
|
$code, $id, escapeJson(msg), $data
|
|
|
|
])
|
2018-07-10 09:39:09 +00:00
|
|
|
debug "Error generated", error = result, id = id
|
|
|
|
|
2020-03-17 18:36:23 +00:00
|
|
|
proc route*(router: RpcRouter, node: JsonNode): Future[StringOfJson] {.async, gcsafe.} =
|
2018-07-10 15:07:47 +00:00
|
|
|
## Assumes correct setup of node
|
|
|
|
let
|
|
|
|
methodName = node[methodField].str
|
|
|
|
id = node[idField]
|
|
|
|
rpcProc = router.procs.getOrDefault(methodName)
|
|
|
|
|
|
|
|
if rpcProc.isNil:
|
|
|
|
let
|
|
|
|
methodNotFound = %(methodName & " is not a registered RPC method.")
|
|
|
|
error = wrapError(METHOD_NOT_FOUND, "Method not found", id, methodNotFound)
|
2020-03-17 18:36:23 +00:00
|
|
|
result = wrapReply(id, StringOfJson("null"), error)
|
2018-07-10 15:07:47 +00:00
|
|
|
else:
|
2020-03-17 18:36:23 +00:00
|
|
|
try:
|
|
|
|
let jParams = node[paramsField]
|
|
|
|
let res = await rpcProc(jParams)
|
|
|
|
result = wrapReply(id, res, StringOfJson("null"))
|
|
|
|
except CatchableError as err:
|
|
|
|
debug "Error occurred within RPC", methodName, errorMessage = err.msg
|
|
|
|
let error = wrapError(SERVER_ERROR, methodName & " raised an exception",
|
|
|
|
id, newJString(err.msg))
|
|
|
|
result = wrapReply(id, StringOfJson("null"), error)
|
2018-07-10 15:07:47 +00:00
|
|
|
|
2018-07-10 09:39:09 +00:00
|
|
|
proc route*(router: RpcRouter, data: string): Future[string] {.async, gcsafe.} =
|
2018-07-10 15:07:47 +00:00
|
|
|
## Route to RPC from string data. Data is expected to be able to be converted to Json.
|
|
|
|
## Returns string of Json from RPC result/error node
|
2018-07-10 09:39:09 +00:00
|
|
|
var
|
|
|
|
node: JsonNode
|
|
|
|
# parse json node and/or flag missing fields and errors
|
|
|
|
jsonErrorState = checkJsonState(data, node)
|
|
|
|
|
|
|
|
if jsonErrorState.isSome:
|
|
|
|
let errState = jsonErrorState.get
|
|
|
|
var id =
|
2019-04-28 19:59:33 +00:00
|
|
|
if errState.err == rjeInvalidJson or
|
|
|
|
errState.err == rjeNoId or
|
|
|
|
errState.err == rjeNoJObject:
|
2018-07-10 09:39:09 +00:00
|
|
|
newJNull()
|
|
|
|
else:
|
|
|
|
node["id"]
|
|
|
|
let
|
2018-07-11 20:49:08 +00:00
|
|
|
# const error code and message
|
2018-07-11 17:27:50 +00:00
|
|
|
errKind = jsonErrorMessages[errState.err]
|
|
|
|
# pass on the actual error message
|
2019-02-06 17:27:58 +00:00
|
|
|
fullMsg = errKind[1] & " " & errState[1]
|
2018-07-11 17:27:50 +00:00
|
|
|
res = wrapError(code = errKind[0], msg = fullMsg, id = id)
|
2018-07-10 09:39:09 +00:00
|
|
|
# return error state as json
|
2020-03-17 18:36:23 +00:00
|
|
|
result = string(res) & messageTerminator
|
2018-07-06 16:47:43 +00:00
|
|
|
else:
|
2018-07-10 15:07:47 +00:00
|
|
|
let res = await router.route(node)
|
2020-03-17 18:36:23 +00:00
|
|
|
result = string(res) & messageTerminator
|
2018-07-06 16:47:43 +00:00
|
|
|
|
2020-03-17 18:36:23 +00:00
|
|
|
proc tryRoute*(router: RpcRouter, data: JsonNode, fut: var Future[StringOfJson]): bool =
|
2018-07-10 09:39:09 +00:00
|
|
|
## Route to RPC, returns false if the method or params cannot be found.
|
|
|
|
## Expects json input and returns json output.
|
2018-07-06 16:47:43 +00:00
|
|
|
let
|
2018-07-12 08:23:38 +00:00
|
|
|
jPath = data.getOrDefault(methodField)
|
|
|
|
jParams = data.getOrDefault(paramsField)
|
2018-07-06 16:47:43 +00:00
|
|
|
if jPath.isEmpty or jParams.isEmpty:
|
|
|
|
return false
|
|
|
|
|
|
|
|
let
|
|
|
|
path = jPath.getStr
|
|
|
|
rpc = router.procs.getOrDefault(path)
|
|
|
|
if rpc != nil:
|
|
|
|
fut = rpc(jParams)
|
|
|
|
return true
|
|
|
|
|
|
|
|
proc makeProcName(s: string): string =
|
|
|
|
result = ""
|
|
|
|
for c in s:
|
|
|
|
if c.isAlphaNumeric: result.add c
|
|
|
|
|
|
|
|
proc hasReturnType(params: NimNode): bool =
|
|
|
|
if params != nil and params.len > 0 and params[0] != nil and
|
|
|
|
params[0].kind != nnkEmpty:
|
|
|
|
result = true
|
|
|
|
|
|
|
|
macro rpc*(server: RpcRouter, path: string, body: untyped): untyped =
|
|
|
|
## Define a remote procedure call.
|
|
|
|
## Input and return parameters are defined using the ``do`` notation.
|
|
|
|
## For example:
|
|
|
|
## .. code-block:: nim
|
|
|
|
## myServer.rpc("path") do(param1: int, param2: float) -> string:
|
|
|
|
## result = $param1 & " " & $param2
|
|
|
|
## ```
|
|
|
|
## Input parameters are automatically marshalled from json to Nim types,
|
|
|
|
## and output parameters are automatically marshalled to json for transport.
|
|
|
|
result = newStmtList()
|
|
|
|
let
|
|
|
|
parameters = body.findChild(it.kind == nnkFormalParams)
|
|
|
|
# all remote calls have a single parameter: `params: JsonNode`
|
|
|
|
paramsIdent = newIdentNode"params"
|
|
|
|
# procs are generated from the stripped path
|
|
|
|
pathStr = $path
|
|
|
|
# strip non alphanumeric
|
|
|
|
procNameStr = pathStr.makeProcName
|
|
|
|
# public rpc proc
|
|
|
|
procName = newIdentNode(procNameStr)
|
|
|
|
# when parameters present: proc that contains our rpc body
|
|
|
|
doMain = newIdentNode(procNameStr & "DoMain")
|
|
|
|
# async result
|
|
|
|
res = newIdentNode("result")
|
2018-07-11 18:16:11 +00:00
|
|
|
errJson = newIdentNode("errJson")
|
2018-07-06 16:47:43 +00:00
|
|
|
var
|
|
|
|
setup = jsonToNim(parameters, paramsIdent)
|
|
|
|
procBody = if body.kind == nnkStmtList: body else: body.body
|
2018-07-11 20:49:08 +00:00
|
|
|
|
2020-03-17 20:05:42 +00:00
|
|
|
let ReturnType = if parameters.hasReturnType: parameters[0]
|
|
|
|
else: ident "JsonNode"
|
2018-07-06 16:47:43 +00:00
|
|
|
|
2020-03-17 20:05:42 +00:00
|
|
|
# delegate async proc allows return and setting of result as native type
|
|
|
|
result.add quote do:
|
|
|
|
proc `doMain`(`paramsIdent`: JsonNode): Future[`ReturnType`] {.async.} =
|
|
|
|
`setup`
|
|
|
|
`procBody`
|
|
|
|
|
|
|
|
if ReturnType == ident"JsonNode":
|
|
|
|
# `JsonNode` results don't need conversion
|
2020-01-21 16:49:52 +00:00
|
|
|
result.add quote do:
|
2020-03-17 20:05:42 +00:00
|
|
|
proc `procName`(`paramsIdent`: JsonNode): Future[StringOfJson] {.async, gcsafe.} =
|
|
|
|
return StringOfJson($(await `doMain`(`paramsIdent`)))
|
|
|
|
elif ReturnType == ident"StringOfJson":
|
|
|
|
result.add quote do:
|
|
|
|
proc `procName`(`paramsIdent`: JsonNode): Future[StringOfJson] {.async, gcsafe.} =
|
|
|
|
return await `doMain`(`paramsIdent`)
|
2018-07-06 16:47:43 +00:00
|
|
|
else:
|
2020-01-21 16:49:52 +00:00
|
|
|
result.add quote do:
|
2020-03-17 18:36:23 +00:00
|
|
|
proc `procName`(`paramsIdent`: JsonNode): Future[StringOfJson] {.async, gcsafe.} =
|
2020-03-17 20:05:42 +00:00
|
|
|
return StringOfJson($(%(await `doMain`(`paramsIdent`))))
|
2020-01-21 16:49:52 +00:00
|
|
|
|
|
|
|
result.add quote do:
|
2018-07-06 16:47:43 +00:00
|
|
|
`server`.register(`path`, `procName`)
|
|
|
|
|
|
|
|
when defined(nimDumpRpcs):
|
|
|
|
echo "\n", pathStr, ": ", result.repr
|