JSON-RPC 2.0 and MessagePack-RPC: a server, a client and registering methods.
import rpc
With a remote procedure call one program calls another program's methods as if they were its own routines. On the server side you tie each method to a routine with Register; that routine takes the call's number, reads the parameters with CallParamInt and the like, and answers with Reply... or Fail.
The messages are exchanged with the JSON codec (JSON-RPC 2.0) or MessagePack, and over TCP they are separated by one of three framings, line, header (like LSP) or length prefixed; the client and the server must have the same framing. HandleText does the same thing without a network, so you can put RPC behind an net.http route.
A small service without a network
The quickest way to design an RPC API is to build it with HandleText: it takes one JSON-RPC request (or a batch) as text and returns the answer as text, without any network. Every method is an ordinary function that receives a call slot c; it reads parameters with CallParamStr, CallParamInt and their siblings, and must answer exactly once, with a Reply... function or with Fail.
rpc-guide-todo.salam
import rpc
import encoding.value
mut todos := Vector {} asVector<str>
funcadd_todo(c: i64):
title := rpc.CallParamStr(c, "title", 0)
if title == "":
rpc.FailInvalidParams(c, "title is required")
retend
todos.Push(title)
rpc.ReplyInt(c, todos.Len())
endfunclist_todos(c: i64):
mut items := value.NewValueArray()
each t in todos:
value.ArrayPush(items, value.ValueString(t))
end
rpc.Reply(c, items)
endfunccount_todos(c: i64):
rpc.ReplyInt(c, todos.Len())
endfuncmain:
rpc.RegisterDoc("todo.add", add_todo, "adds a todo and returns how many there are")
rpc.RegisterDoc("todo.list", list_todos, "returns every todo")
rpc.Register("todo.count", count_todos)
println rpc.HandleText(
`{"jsonrpc":"2.0","method":"todo.add","params":{"title":"buy bread"},"id":1}`
)
println rpc.HandleText(`{"jsonrpc":"2.0","method":"todo.add","params":["call Sara"],"id":2}`)
println rpc.HandleText(`{"jsonrpc":"2.0","method":"todo.add","params":{},"id":3}`)
println rpc.HandleText(`{"jsonrpc":"2.0","method":"todo.list","id":4}`)
println rpc.HandleText(
`[{"jsonrpc":"2.0","method":"todo.count","id":5},{"jsonrpc":"2.0","method":"todo.delete","id":6}]`
)
println rpc.MethodDoc("todo.add")
todos.Free()
end
Output
{"jsonrpc": "2.0", "result": 1, "id": 1}
{"jsonrpc": "2.0", "result": 2, "id": 2}
{"jsonrpc": "2.0", "error": {"code": -32602, "message": "title is required"}, "id": 3}
{"jsonrpc": "2.0", "result": ["buy bread", "call Sara"], "id": 4}
[{"jsonrpc": "2.0", "result": 2, "id": 5}, {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": 6}]
adds a todo and returns how many there are
Each parameter is looked up by name and by position at the same time: CallParamStr(c, "title", 0) finds {"title": ...} as well as the first element of [...], so clients can use either style. FailInvalidParams answers with the standard code -32602, and a method that was never registered gets -32601 without any code of yours. Inside a batch, each request gets its own answer, failures included.
The registry is global for the whole program, so method state, such as the todo list here, lives in a global variable or behind one. If several connections are served in parallel threads, protect that state with a lock from sync.
A server and a client over TCP
For two programs, NewServer with port 0 lets the system pick a free port and Port reports it after Listen. ServeCount serves a fixed number of connections and returns, which suits tests; Serve runs until StopServer. Both answer one connection at a time: while a client stays connected, the next one waits in the queue. When several clients must be served at once, accept the connections yourself with net.tcp (tcp.Bind, then tcp.Accept in a loop) and pass each connection's fd to ServeConn in its own thread from thread. On the other side, DialClient connects, Call sends one request and waits for its answer.
A failed call does not crash anything. Check IsErrorResponse first and then read ErrorCode and ErrorMessage; reading ResultFloat on an error response returns 0. Your own error codes should stay outside the range -32768 to -32000 that JSON-RPC reserves, except for the -32000 to -32099 block meant for server errors, which is where -32010 comes from.
Client and server must agree on the codec and the framing. JSON with line framing is the default and easy to debug with a terminal. RPC_CODEC_MSGPACK is smaller and faster and uses length prefixed frames; set both ends with SetFraming and ClientSetFraming.
Talking over standard input and output
Editor tools, language servers and plugins often run as a child process and exchange messages over standard input and output. ServeStdio reads one request per line (or LSP style Content-Length frames with RPC_FRAME_HEADER), answers each on standard output, and returns the number of requests when the input ends. Logs must go to standard error, as here, or they would corrupt the answers.
Two limits of ServeStdio to know before you build on it:
•
With line framing, an empty line counts as the end of the input, so the service stops there.
•
RPC_FRAME_HEADER does not yet work with real LSP clients. They end headers with \r\n and send no newline after the body, so the blank \r line is answered with a parse error and the next header is read as part of the body. It also never returns at the end of the input. Use line framing over standard input and output for now.
rpc-guide-stdio.salam
import rpc
importstrimport io
funcword_count(c: i64):
words := str.Fields(rpc.CallParamStr(c, "text", 0))
rpc.ReplyInt(c, words.Len())
words.Free()
endfuncshout(c: i64):
rpc.ReplyStr(c, str.Upper(rpc.CallParamStr(c, "text", 0)))
endfuncmain:
rpc.Register("words", word_count)
rpc.Register("shout", shout)
served := rpc.ServeStdio(rpc.RPC_FRAME_LINE)
io.EPrintln("answered " + served + " requests")
end
This program waits for input, so it is only compiled here. Build it and pipe two requests into it:
Because HandleText only needs text, putting the same methods behind a web server takes one route. The handler passes the request body in and sends the answer back as JSON with net.http; batches work too. Other programs can then call it with CallHTTP, or with any HTTP client.
Reads requests from standard input, one per line, and writes each answer to standard output; returns the number of requests at the end of input or at the first empty line. Header framing does not yet handle real LSP traffic; see the note in the guide above.
The example for this item is shown with the ones above: rpc-Serve.salam