JSON-RPC 2.0 for MoonBit: messages, a method table, two-way calls and framing.
moon add moonbitstack/moonjrpclet methods = @moonjrpc.Methods::new()
methods.typed("sum", (numbers : Array[Int32]) => {
numbers.fold(init=0, (a, b) => a + b)
})
let request =
#|{"jsonrpc":"2.0","id":1,"method":"sum","params":[1,2,3]}
let answer = methods.body(request)
let want = #|{"jsonrpc":"2.0","id":1,"result":6}
assert_eq(answer, Some(want))methods.call("no", _ => @moonjrpc.fail(7, "said no", data=Json::string("why")))
let refused =
#|{"jsonrpc":"2.0","id":1,"method":"no"}
let said = methods.body(refused)
let error = #|{"jsonrpc":"2.0","id":1,"error":{"code":7,"message":"said no","data":"why"}}
assert_eq(said, Some(error))| Input | Answer |
|---|---|
| Not JSON | -32700 |
| Not a message | -32600, with its identifier if one can be read |
| A method nobody registered | -32601 |
| Parameters typed cannot decode | -32602, with the reason in data |
| fail(code, message, data=...) | That error object |
| Any other error from a handler | -32603 with no detail; Methods::new(on_error=...) hears it |
| An array | A batch; batch=false refuses it with -32600 |
let (here_reads, there_writes) = @io.pipe()
let (there_reads, here_writes) = @io.pipe()
let here = @peer.Peer::new(@peer.lines(here_reads, here_writes), methods~)
let there = @peer.Peer::new(@peer.lines(there_reads, there_writes), methods~)
@async.with_task_group(async fn(group) {
group.spawn_bg(no_wait=true, () => here.run())
group.spawn_bg(no_wait=true, () => there.run())
let roots = there.call("sum", params=Json::array([Json::number(1.0), Json::number(2.0)]))
assert_eq(roots.stringify(), "3")
here_writes.close()
there_writes.close()
group.return_immediately(())
})| Error from Peer::call | Meaning |
|---|---|
| Failed(failure) | The other side answered with an error object |
| TimedOut(name~, limit~) | No answer in time. The default is 60 seconds; timeout_ms=None waits as long as it takes |
| Closed(name~) | The other side went away |
pub(open) trait Frames {
async fn read(Self) -> String?
async fn write(Self, String) -> Unit
}moonx moonbit-community/skills download moonbitstack/moonjrpc --extract ./moonjrpc-skilltype Methodslet internal_error : IntInstall
Download zipJSON-RPC 2.0 for MoonBit: messages, a method table, two-way calls and framing.