rpc
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.
import rpc
import encoding.value
mut todos := Vector {} as Vector<str>
func add_todo(c: i64):
title := rpc.CallParamStr(c, "title", 0)
if title == "":
rpc.FailInvalidParams(c, "title is required")
ret
end
todos.Push(title)
rpc.ReplyInt(c, todos.Len())
end
func list_todos(c: i64):
mut items := value.NewValueArray()
each t in todos:
value.ArrayPush(items, value.ValueString(t))
end
rpc.Reply(c, items)
end
func count_todos(c: i64):
rpc.ReplyInt(c, todos.Len())
end
func main:
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()
endEach 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.
import rpc
import encoding.value
import sync
mut server := rpc.NewServer(0, rpc.RPC_CODEC_JSON)
mut ready := sync.NewWaitGroup()
func convert(c: i64):
amount := rpc.CallParamFloat(c, "amount", 0)
currency := rpc.CallParamStr(c, "to", 1)
if currency == "EUR":
rpc.ReplyFloat(c, amount * 0.5)
ret
end
rpc.Fail(c, -32010, "unknown currency " + currency)
end
func run_server():
_ := rpc.Listen(server)
sync.Done(ready)
_ := rpc.ServeCount(server, 1)
end
func main:
rpc.Register("convert", convert)
sync.Add(ready, 1)
t := spawn(run_server)
sync.Wait(ready)
mut client := rpc.DialClient("127.0.0.1", rpc.Port(server), rpc.RPC_CODEC_JSON)
if not rpc.ClientOk(client):
println "cannot connect:", rpc.ClientError(client)
ret 1
end
mut params := value.NewValueObject()
value.ObjectSet(params, "amount", value.ValueFloat(40.0))
value.ObjectSet(params, "to", value.ValueString("EUR"))
ok := rpc.Call(client, "convert", params)
println "40 is", rpc.ResultFloat(ok), "EUR"
value.ObjectSet(params, "to", value.ValueString("XYZ"))
bad := rpc.Call(client, "convert", params)
if rpc.IsErrorResponse(bad):
println "error", rpc.ErrorCode(bad), rpc.ErrorMessage(bad)
end
rpc.CloseClient(client)
join(t)
rpc.StopServer(server)
ret 0
endA 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_HEADERdoes not yet work with real LSP clients. They end headers with\r\nand send no newline after the body, so the blank\rline 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.
import rpc
import str
import io
func word_count(c: i64):
words := str.Fields(rpc.CallParamStr(c, "text", 0))
rpc.ReplyInt(c, words.Len())
words.Free()
end
func shout(c: i64):
rpc.ReplyStr(c, str.Upper(rpc.CallParamStr(c, "text", 0)))
end
func main:
rpc.Register("words", word_count)
rpc.Register("shout", shout)
served := rpc.ServeStdio(rpc.RPC_FRAME_LINE)
io.EPrintln("answered " + served + " requests")
endThis program waits for input, so it is only compiled here. Build it and pipe two requests into it:
salam build rpc-guide-stdio.salam --output=tool
printf '%s\n' '{"jsonrpc":"2.0","method":"words","params":["one two three"],"id":1}' \
'{"jsonrpc":"2.0","method":"shout","params":{"text":"salam"},"id":2}' | ./tool
{"jsonrpc": "2.0", "id": 1, "result": 3}
{"jsonrpc": "2.0", "id": 2, "result": "SALAM"}
answered 2 requests
JSON-RPC behind an HTTP route
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.
import rpc
import net.http
import net.router
mut visits := 0
func hit(c: i64):
visits++
rpc.ReplyInt(c, visits)
end
func greet(c: i64):
rpc.ReplyStr(c, "salam, " + rpc.CallParamStr(c, "name", 0))
end
func endpoint(ctx: i64):
http.Json(ctx, rpc.HandleText(http.Body(ctx)))
end
func main:
rpc.Register("hit", hit)
rpc.Register("greet", greet)
mut r := router.NewRouter()
router.Post(r, "/rpc", endpoint)
mut s := http.NewServer(8090)
http.Use(s, r)
println "JSON-RPC on http://127.0.0.1:8090/rpc"
http.Run(s)
endRun the program, then call it from another terminal:
curl -X POST http://127.0.0.1:8090/rpc -d '{"jsonrpc":"2.0","method":"greet","params":{"name":"Sara"},"id":1}'
curl -X POST http://127.0.0.1:8090/rpc -d '[{"jsonrpc":"2.0","method":"hit","id":1},{"jsonrpc":"2.0","method":"hit","id":2}]'
{"jsonrpc": "2.0", "id": 1, "result": "salam, Sara"}
[{"jsonrpc": "2.0", "id": 1, "result": 1}, {"jsonrpc": "2.0", "id": 2, "result": 2}]
| Transport | Server side | Client side |
|---|---|---|
| None, inside one program or a test | HandleText, Invoke | build the request text yourself |
| TCP | NewServer, Listen, Serve | DialClient, Call, CallBatch, Notify |
| Standard input and output | ServeStdio | the parent process writes lines |
| HTTP | HandleText in a route | CallHTTP |
Types
Client
struct Client| Name | Type | Description |
|---|---|---|
conn | tcp.Conn | The connection. |
stream | Stream | The reading stream. |
codec | int = 0 | The codec. |
framing | int = 0 | The framing. |
next_id | i64 = 1 | The next request id. |
ok | bool = false | It is healthy. |
last_error | str = "" | The last error. |
import rpc
import encoding.value
import net.http
import net.router
import sync
mut server := rpc.NewServer(0, rpc.RPC_CODEC_JSON)
mut ready := sync.NewWaitGroup()
func add(c: i64):
rpc.ReplyInt(c, rpc.CallParamInt(c, "a", 0) + rpc.CallParamInt(c, "b", 1))
end
func clock(c: i64):
rpc.ReplyStr(c, "12:00")
end
func note(c: i64):
rpc.ReplyNull(c)
end
func run_server():
_ := rpc.Listen(server)
sync.Done(ready)
_ := rpc.ServeCount(server, 1)
end
func endpoint(ctx: i64):
http.Json(ctx, rpc.HandleText(http.Body(ctx)))
end
func main:
rpc.Register("add", add)
rpc.Register("time", clock)
rpc.Register("note", note)
rpc.SetFraming(server, rpc.RPC_FRAME_LINE)
sync.Add(ready, 1)
t := spawn(run_server)
sync.Wait(ready)
println rpc.Port(server) > 0
mut client := rpc.DialClient("127.0.0.1", rpc.Port(server), rpc.RPC_CODEC_JSON)
rpc.ClientSetFraming(client, rpc.RPC_FRAME_LINE)
println rpc.ClientOk(client)
mut params := value.NewValueArray()
value.ArrayPush(params, value.ValueInt(2))
value.ArrayPush(params, value.ValueInt(40))
println rpc.ResultInt(rpc.Call(client, "add", params))
println rpc.ResultStr(rpc.CallNoParams(client, "time"))
mut args := Vector {} as Vector<value.Value>
args.Push(value.ValueInt(1))
args.Push(value.ValueInt(2))
println rpc.ResultInt(rpc.CallArgs(client, "add", args))
println rpc.Notify(client, "note", value.NewValueArray())
mut batch := Vector {} as Vector<rpc.Request>
batch.Push(rpc.NewRequest("add", params, 10))
batch.Push(rpc.NewRequest("missing", value.NewValueArray(), 11))
answers := rpc.CallBatch(client, batch)
println answers.items.Len(), rpc.ResultInt(answers.items[0])
println rpc.IsErrorResponse(answers.items[1]), rpc.ErrorCode(answers.items[1]), rpc.ErrorMessage(answers.items[1])
rpc.CloseClient(client)
println rpc.ClientOk(client), rpc.ClientError(client).Len() >= 0
join(t)
rpc.StopServer(server)
mut r := router.NewRouter()
router.Post(r, "/rpc", endpoint)
mut s := http.NewServer(19631)
http.Use(s, r)
_ := http.RunBackground(s)
answer := rpc.CallHTTP("http://127.0.0.1:19631/rpc", "add", params, 7)
println rpc.ResultInt(answer)
endStream
struct Stream| Name | Type | Description |
|---|---|---|
fd | i64 = -1 | The socket. |
data | compress.ByteBuf | The data read. |
pos | int = 0 | The read position. |
closed | bool = false | The input is finished. |
has_fd | bool = false | It is over a socket. |
import rpc
import compress
func main:
line := rpc.FrameEncodeStr(rpc.RPC_FRAME_LINE, `{"a":1}`)
headed := rpc.FrameEncodeStr(rpc.RPC_FRAME_HEADER, `{"b":2}`)
sized := rpc.FrameEncode(rpc.RPC_FRAME_LENGTH, compress.BufFromStr(`{"c":3}`))
println line.len, headed.len, sized.len
println compress.BufToStrUnsafe(headed).Len() > 0
mut s := rpc.NewMemStream()
rpc.FeedStr(s, `{"x":1}` + "\n" + `{"x":2}` + "\n")
mut ok := false
println rpc.ReadFrameStr(s, rpc.RPC_FRAME_LINE, ok), ok
println rpc.StreamPending(s)
println rpc.ReadFrameStr(s, rpc.RPC_FRAME_LINE, ok)
_ := rpc.ReadFrameStr(s, rpc.RPC_FRAME_LINE, ok)
println ok, rpc.StreamClosed(s)
mut s2 := rpc.NewMemStream()
rpc.FeedBuf(s2, headed)
rpc.FeedBuf(s2, sized)
println rpc.ReadFrameStr(s2, rpc.RPC_FRAME_HEADER, ok)
b := rpc.ReadFrame(s2, rpc.RPC_FRAME_LENGTH, ok)
println compress.BufToStrUnsafe(b), ok
println rpc.RPC_READ_CHUNK, rpc.RPC_MAX_FRAME
rpc.FreeStream(s)
rpc.FreeStream(s2)
endServer
struct Server| Name | Type | Description |
|---|---|---|
port | int = 0 | The port; zero means a free port. |
codec | int = 0 | The codec. |
framing | int = 0 | The framing. |
listen_fd | i64 = -1 | The listening socket. |
running | bool = false | It is running. |
served | int = 0 | The number of connections answered. |
import rpc
import net.tcp
import compress
func echo(c: i64):
rpc.Reply(c, rpc.CallParams(c))
end
func main:
rpc.Register("echo", echo)
if rpc.HandleText("").Len() == 0:
_ := rpc.ServeStdio(rpc.RPC_FRAME_HEADER)
ret
end
mut s := rpc.NewServer(4000, rpc.RPC_CODEC_MSGPACK)
rpc.SetFraming(s, rpc.RPC_FRAME_LENGTH)
if rpc.Listen(s):
println "on port", rpc.Port(s), s.running
rpc.Serve(s)
end
conn := tcp.Dial("127.0.0.1", 4001)
_ := rpc.ServeConn(conn.fd, rpc.RPC_CODEC_JSON, rpc.RPC_FRAME_LINE)
c := tcp.Dial("127.0.0.1", 4002)
mut client := rpc.ClientFromFd(c.fd, rpc.RPC_CODEC_JSON)
println rpc.ResultStr(rpc.CallNoParams(client, "version"))
mut stream := rpc.NewStream(c.fd)
_ := rpc.WriteFrameStr(c.fd, rpc.RPC_FRAME_LINE, `{"jsonrpc":"2.0","method":"echo","params":[1],"id":1}`)
_ := rpc.WriteFrame(c.fd, rpc.RPC_FRAME_LINE, compress.BufFromStr(`{"jsonrpc":"2.0","method":"echo","id":2}`))
mut ok := false
println rpc.ReadFrameStr(stream, rpc.RPC_FRAME_LINE, ok)
answer := rpc.HandlePayload(rpc.RPC_CODEC_JSON, compress.BufFromStr(`{"jsonrpc":"2.0","method":"echo","params":[3],"id":3}`))
println compress.BufToStrUnsafe(answer)
rpc.FreeStream(stream)
rpc.StopServer(s)
endError
struct Error| Name | Type | Description |
|---|---|---|
code | int = 0 | The code. |
message | str = "" | The message. |
data | value.Value | The extra data. |
has_data | bool = false | It has data. |
import rpc
import encoding.value
import compress
func main:
mut params := value.NewValueArray()
value.ArrayPush(params, value.ValueInt(2))
value.ArrayPush(params, value.ValueString("hello"))
value.ArrayPush(params, value.ValueFloat(1.5))
value.ArrayPush(params, value.ValueBool(true))
req := rpc.NewRequest("calc", params, 1)
println rpc.JsonEncodeRequest(req)
println rpc.ParamCount(req), rpc.ParamInt(req, "a", 0), rpc.ParamStr(req, "b", 1)
println rpc.ParamFloat(req, "c", 2), rpc.ParamBool(req, "d", 3), rpc.HasParam(req, "e", 4)
println value.AsInt(rpc.ParamAt(req, 0)), value.AsInt(rpc.Param(req, "a", 0))
mut obj := value.NewValueObject()
value.ObjectSet(obj, "name", value.ValueString("Ali"))
req2 := rpc.NewRequestStrId("greet", obj, "req-1")
println rpc.JsonEncodeRequest(req2)
println value.AsString(rpc.ParamNamed(req2, "name"))
note := rpc.NewNotification("tick", value.NewValueArray())
println rpc.IsNotification(note), rpc.JsonEncodeRequest(note)
mut ok := false
read := rpc.JsonDecodeRequest(`{"jsonrpc":"2.0","method":"add","params":{"a":1,"b":2},"id":9}`, ok)
println ok, read.method, read.msgid, rpc.ParamInt(read, "b", 1)
answer := rpc.NewResponse(value.ValueInt(1), value.ValueString("ok"))
println rpc.JsonEncodeResponse(answer)
err := rpc.StdError(rpc.RPC_METHOD_NOT_FOUND)
println err.code, err.message
println rpc.JsonEncodeResponse(rpc.NewErrorResponse(value.ValueInt(2), rpc.NewError(-32000, "the server is busy")))
with_data := rpc.ErrorWithData(rpc.RPC_INVALID_PARAMS, "bad", value.ValueString("x"))
println with_data.has_data, rpc.JsonTopLevelError(rpc.StdError(rpc.RPC_PARSE_ERROR))
one := rpc.JsonDecodeResponse(`{"jsonrpc":"2.0","result":3.5,"id":1}`, ok)
println ok, rpc.ResultFloat(one), rpc.IsErrorResponse(one)
two := rpc.JsonDecodeResponse(`{"jsonrpc":"2.0","error":{"code":-32601,"message":"nope"},"id":2}`, ok)
println rpc.IsErrorResponse(two), rpc.ErrorCode(two), rpc.ErrorMessage(two)
all := rpc.JsonDecodeResponses(`[{"jsonrpc":"2.0","result":true,"id":1},{"jsonrpc":"2.0","result":"x","id":2}]`, ok)
println all.is_batch, all.items.Len(), rpc.ResultBool(all.items[0]), rpc.ResultStr(all.items[1])
println rpc.JsonEncodeResponses(all)
println rpc.CodecName(rpc.RPC_CODEC_JSON), rpc.CodecName(rpc.RPC_CODEC_MSGPACK)
println rpc.CodecDefaultFraming(rpc.RPC_CODEC_JSON) == rpc.RPC_FRAME_LINE, rpc.CodecDefaultFraming(rpc.RPC_CODEC_MSGPACK) == rpc.RPC_FRAME_LENGTH
packed := rpc.EncodeRequest(rpc.RPC_CODEC_MSGPACK, req)
println packed.len, compress.BufGet(packed, 0)
batch := rpc.DecodeBatch(rpc.RPC_CODEC_MSGPACK, packed)
println batch.ok, batch.items[0].method, batch.items[0].msgid
println rpc.MsgpackDecodeBatch(rpc.MsgpackEncodeRequest(req)).items[0].method
mp := rpc.MsgpackEncodeResponse(rpc.NewResponse(value.ValueInt(1), value.ValueInt(42)))
println rpc.ResultInt(rpc.MsgpackDecodeResponse(mp, ok)), ok
js := rpc.EncodeRequest(rpc.RPC_CODEC_JSON, req)
println rpc.ResultInt(rpc.DecodeResponse(rpc.RPC_CODEC_MSGPACK, mp, ok)), js.len > 0
println compress.BufToStrUnsafe(rpc.EncodeResponses(rpc.RPC_CODEC_JSON, all)).Len() > 0
println compress.BufToStrUnsafe(rpc.EncodeTopLevelError(rpc.RPC_CODEC_JSON, err))
println rpc.RPC_MP_REQUEST, rpc.RPC_MP_RESPONSE, rpc.RPC_MP_NOTIFY
println rpc.RPC_INVALID_REQUEST, rpc.RPC_INTERNAL_ERROR, rpc.RPC_SERVER_ERROR
println rpc.RPC_KIND_REQUEST, rpc.RPC_KIND_NOTIFICATION, rpc.RPC_KIND_RESPONSE
println compress.BufToStrUnsafe(compress.BufFromStr(rpc.JsonEncodeRequest(req))).Len() > 0
endRequest
struct Request| Name | Type | Description |
|---|---|---|
method | str = "" | The method name. |
params | value.Value | The parameters: an array or an object. |
has_params | bool = false | It has parameters. |
id | value.Value | The id; a number or a string. |
has_id | bool = false | It has an id; without one it is a notification. |
msgid | i64 = 0 | The numeric id. |
err_code | int = 0 | If the request could not be read, the error code. |
err_message | str = "" | That error's message. |
import rpc
import encoding.value
func add(c: i64):
a := rpc.CallParamInt(c, "a", 0)
b := rpc.CallParamInt(c, "b", 1)
rpc.ReplyInt(c, a + b)
end
func divide(c: i64):
divisor := rpc.CallParamFloat(c, "b", 1)
if divisor == 0.0:
rpc.FailInvalidParams(c, "division by zero")
ret
end
rpc.ReplyFloat(c, rpc.CallParamFloat(c, "a", 0) / divisor)
end
func hello(c: i64):
name := rpc.CallParamStr(c, "name", 0)
if name.Len() == 0:
rpc.Fail(c, -32001, "a name is needed")
ret
end
rpc.ReplyStr(c, "hello " + name)
end
func status(c: i64):
mut info := value.NewValueArray()
value.ArrayPush(info, value.ValueString(rpc.CallMethodName(c)))
value.ArrayPush(info, value.ValueInt(rpc.CallParamCount(c)))
value.ArrayPush(info, value.ValueBool(rpc.CallParamBool(c, "verbose", 0)))
rpc.Reply(c, info)
end
func log_event(c: i64):
println "event:", value.AsString(rpc.CallParam(c, "event", 0)), rpc.CallIsNotification(c)
_ := rpc.CallParams(c)
_ := rpc.CallRequest(c)
rpc.ReplyNull(c)
end
func forbidden(c: i64):
rpc.FailWithData(c, -32003, "you are not allowed", value.ValueString("admin"))
end
func always(c: i64):
rpc.ReplyBool(c, true)
end
func main:
rpc.RegisterDoc("add", add, "adds two numbers")
rpc.Register("divide", divide)
rpc.Register("hello", hello)
rpc.Register("status", status)
rpc.Register("log", log_event)
rpc.Register("admin", forbidden)
rpc.Register("ping", always)
println rpc.MethodCount(), rpc.HasMethod("add"), rpc.MethodDoc("add")
println rpc.ListMethods().Len()
println rpc.HandleText(`{"jsonrpc":"2.0","method":"add","params":[2,40],"id":1}`)
println rpc.HandleText(`{"jsonrpc":"2.0","method":"add","params":{"a":5,"b":6},"id":2}`)
println rpc.HandleText(`{"jsonrpc":"2.0","method":"divide","params":[1,0],"id":3}`)
println rpc.HandleText(`{"jsonrpc":"2.0","method":"hello","params":["Maryam"],"id":"x"}`)
println rpc.HandleText(`{"jsonrpc":"2.0","method":"hello","params":[],"id":4}`)
println rpc.HandleText(`{"jsonrpc":"2.0","method":"status","params":{"verbose":true},"id":5}`)
println rpc.HandleText(`{"jsonrpc":"2.0","method":"admin","id":6}`)
println rpc.HandleText(`{"jsonrpc":"2.0","method":"nope","id":7}`)
println rpc.HandleText(`{"jsonrpc":"2.0","method":"log","params":{"event":"start"}}`).Len()
println rpc.HandleText(`[{"jsonrpc":"2.0","method":"ping","id":8},{"jsonrpc":"2.0","method":"add","params":[1,1],"id":9}]`)
println rpc.HandleText(`{"jsonrpc":`)
mut ok := false
req := rpc.JsonDecodeRequest(`{"jsonrpc":"2.0","method":"add","params":[20,22],"id":10}`, ok)
answer := rpc.Invoke(req)
println rpc.ResultInt(answer)
batch := rpc.JsonDecodeBatch(`[{"jsonrpc":"2.0","method":"ping","id":1}]`)
println rpc.InvokeBatch(batch).items.Len()
println rpc.Unregister("ping"), rpc.HasMethod("ping")
rpc.ResetRegistry()
println rpc.MethodCount()
endResponse
struct Response| Name | Type | Description |
|---|---|---|
id | value.Value | The request's id. |
has_id | bool = false | It has an id. |
result | value.Value | The result. |
is_error | bool = false | It is an error. |
err | Error | The error. |
msgid | i64 = 0 | The numeric id. |
The example for this item is shown with the ones above: rpc-Methods.salam
Batch
struct Batch| Name | Type | Description |
|---|---|---|
items | Vector | The requests. |
is_batch | bool = false | It came in as an array. |
ok | bool = true | It was read correctly. |
err | Error | If it was not, the error. |
The example for this item is shown with the ones above: rpc-Methods.salam
Responses
struct Responses| Name | Type | Description |
|---|---|---|
items | Vector | The responses. |
is_batch | bool = false | Send it as an array. |
The example for this item is shown with the ones above: rpc-Messages.salam
Method
struct Method| Name | Type | Description |
|---|---|---|
name | str = "" | The name. |
fn | i64 = 0 | The routine. |
doc | str = "" | The description. |
The example for this item is shown with the ones above: rpc-Methods.salam
MethodTable
struct MethodTable| Name | Type | Description |
|---|---|---|
items | Vector | The methods. |
The example for this item is shown with the ones above: rpc-Methods.salam
CallSlot
struct CallSlot| Name | Type | Description |
|---|---|---|
req | Request | The request. |
result | value.Value | The result. |
err | Error | The error. |
is_error | bool = false | It is an error. |
replied | bool = false | It has been answered. |
busy | bool = false | It is in use. |
The example for this item is shown with the ones above: rpc-Methods.salam
SlotTable
struct SlotTable| Name | Type | Description |
|---|---|---|
items | Vector | The calls. |
The example for this item is shown with the ones above: rpc-Methods.salam
Constants and variables
RPC_MP_REQUEST
const RPC_MP_REQUEST: i32 = 0The example for this item is shown with the ones above: rpc-Messages.salam
RPC_MP_RESPONSE
const RPC_MP_RESPONSE: i32 = 1The example for this item is shown with the ones above: rpc-Messages.salam
RPC_MP_NOTIFY
const RPC_MP_NOTIFY: i32 = 2The example for this item is shown with the ones above: rpc-Messages.salam
RPC_READ_CHUNK
const RPC_READ_CHUNK: i32 = 4096The example for this item is shown with the ones above: rpc-Frames.salam
RPC_MAX_FRAME
const RPC_MAX_FRAME: i32 = 33554432The example for this item is shown with the ones above: rpc-Frames.salam
RPC_PARSE_ERROR
const RPC_PARSE_ERROR: i32 = -32700The example for this item is shown with the ones above: rpc-Messages.salam
RPC_INVALID_REQUEST
const RPC_INVALID_REQUEST: i32 = -32600The example for this item is shown with the ones above: rpc-Messages.salam
RPC_METHOD_NOT_FOUND
const RPC_METHOD_NOT_FOUND: i32 = -32601The example for this item is shown with the ones above: rpc-Messages.salam
RPC_INVALID_PARAMS
const RPC_INVALID_PARAMS: i32 = -32602The example for this item is shown with the ones above: rpc-Messages.salam
RPC_INTERNAL_ERROR
const RPC_INTERNAL_ERROR: i32 = -32603The example for this item is shown with the ones above: rpc-Messages.salam
RPC_SERVER_ERROR
const RPC_SERVER_ERROR: i32 = -32000The example for this item is shown with the ones above: rpc-Messages.salam
RPC_KIND_REQUEST
const RPC_KIND_REQUEST: i32 = 1The example for this item is shown with the ones above: rpc-Messages.salam
RPC_KIND_NOTIFICATION
const RPC_KIND_NOTIFICATION: i32 = 2The example for this item is shown with the ones above: rpc-Messages.salam
RPC_KIND_RESPONSE
const RPC_KIND_RESPONSE: i32 = 3The example for this item is shown with the ones above: rpc-Messages.salam
RPC_CODEC_JSON
const RPC_CODEC_JSON: i32 = 0The example for this item is shown with the ones above: rpc-Messages.salam
RPC_CODEC_MSGPACK
const RPC_CODEC_MSGPACK: i32 = 1The example for this item is shown with the ones above: rpc-Messages.salam
RPC_FRAME_LINE
const RPC_FRAME_LINE: i32 = 0The example for this item is shown with the ones above: rpc-Messages.salam
RPC_FRAME_HEADER
const RPC_FRAME_HEADER: i32 = 1Content-Length header, like LSP.The example for this item is shown with the ones above: rpc-Frames.salam
RPC_FRAME_LENGTH
const RPC_FRAME_LENGTH: i32 = 2The example for this item is shown with the ones above: rpc-Messages.salam
Functions
MsgpackEncodeRequest
func MsgpackEncodeRequest(r: Request): compress.ByteBufThe example for this item is shown with the ones above: rpc-Messages.salam
MsgpackEncodeResponse
func MsgpackEncodeResponse(r: Response): compress.ByteBufThe example for this item is shown with the ones above: rpc-Messages.salam
MsgpackDecodeBatch
func MsgpackDecodeBatch(b: compress.ByteBuf): BatchThe example for this item is shown with the ones above: rpc-Messages.salam
MsgpackDecodeResponse
func MsgpackDecodeResponse(b: compress.ByteBuf, ok &: bool): ResponseThe example for this item is shown with the ones above: rpc-Messages.salam
DialClient
func DialClient(host: str, port: int, codec: int): ClientThe example for this item is shown with the ones above: rpc-Client.salam
ClientFromFd
func ClientFromFd(fd: i64, codec: int): ClientThe example for this item is shown with the ones above: rpc-Serve.salam
ClientSetFraming
func ClientSetFraming(c &: Client, framing: int)The example for this item is shown with the ones above: rpc-Client.salam
ClientOk
func ClientOk(c: Client): boolThe example for this item is shown with the ones above: rpc-Client.salam
ClientError
func ClientError(c: Client): strThe example for this item is shown with the ones above: rpc-Client.salam
CloseClient
func CloseClient(c &: Client)The example for this item is shown with the ones above: rpc-Client.salam
Call
func Call(c &: Client, method: str, params: value.Value): ResponseThe example for this item is shown with the ones above: rpc-Methods.salam
CallNoParams
func CallNoParams(c &: Client, method: str): ResponseThe example for this item is shown with the ones above: rpc-Client.salam
CallArgs
func CallArgs(c &: Client, method: str, args: Vector<value.Value>): ResponseThe example for this item is shown with the ones above: rpc-Client.salam
Notify
func Notify(c &: Client, method: str, params: value.Value): boolThe example for this item is shown with the ones above: rpc-Methods.salam
CallBatch
func CallBatch(c &: Client, reqs: Vector<Request>): ResponsesThe example for this item is shown with the ones above: rpc-Client.salam
ResultInt
func ResultInt(r: Response): i64The example for this item is shown with the ones above: rpc-Methods.salam
ResultFloat
func ResultFloat(r: Response): f64The example for this item is shown with the ones above: rpc-Messages.salam
ResultStr
func ResultStr(r: Response): strThe example for this item is shown with the ones above: rpc-Messages.salam
ResultBool
func ResultBool(r: Response): boolThe example for this item is shown with the ones above: rpc-Messages.salam
IsErrorResponse
func IsErrorResponse(r: Response): boolThe example for this item is shown with the ones above: rpc-Messages.salam
ErrorCode
func ErrorCode(r: Response): intThe example for this item is shown with the ones above: rpc-Messages.salam
ErrorMessage
func ErrorMessage(r: Response): strThe example for this item is shown with the ones above: rpc-Messages.salam
CallHTTP
func CallHTTP(url: str, method: str, params: value.Value, id: i64): ResponseThe example for this item is shown with the ones above: rpc-Client.salam
CodecName
func CodecName(codec: int): strjson-rpc-2.0.The example for this item is shown with the ones above: rpc-Messages.salam
CodecDefaultFraming
func CodecDefaultFraming(codec: int): intThe example for this item is shown with the ones above: rpc-Messages.salam
EncodeRequest
func EncodeRequest(codec: int, r: Request): compress.ByteBufThe example for this item is shown with the ones above: rpc-Messages.salam
EncodeResponses
func EncodeResponses(codec: int, rs: Responses): compress.ByteBufThe example for this item is shown with the ones above: rpc-Messages.salam
DecodeBatch
func DecodeBatch(codec: int, payload: compress.ByteBuf): BatchThe example for this item is shown with the ones above: rpc-Methods.salam
DecodeResponse
func DecodeResponse(codec: int, payload: compress.ByteBuf, ok &: bool): ResponseThe example for this item is shown with the ones above: rpc-Messages.salam
EncodeTopLevelError
func EncodeTopLevelError(codec: int, e: Error): compress.ByteBufThe example for this item is shown with the ones above: rpc-Messages.salam
NewStream
func NewStream(fd: i64): StreamThe example for this item is shown with the ones above: rpc-Serve.salam
NewMemStream
func NewMemStream(): StreamThe example for this item is shown with the ones above: rpc-Frames.salam
FreeStream
func FreeStream(s &: Stream)The example for this item is shown with the ones above: rpc-Frames.salam
FeedStr
func FeedStr(s &: Stream, text: str)The example for this item is shown with the ones above: rpc-Frames.salam
FeedBuf
func FeedBuf(s &: Stream, b: compress.ByteBuf)The example for this item is shown with the ones above: rpc-Frames.salam
StreamPending
func StreamPending(s: Stream): intThe example for this item is shown with the ones above: rpc-Frames.salam
StreamClosed
func StreamClosed(s: Stream): boolThe example for this item is shown with the ones above: rpc-Frames.salam
FrameEncode
func FrameEncode(kind: int, payload: compress.ByteBuf): compress.ByteBufThe example for this item is shown with the ones above: rpc-Messages.salam
FrameEncodeStr
func FrameEncodeStr(kind: int, payload: str): compress.ByteBufThe example for this item is shown with the ones above: rpc-Frames.salam
ReadFrame
func ReadFrame(s &: Stream, kind: int, ok &: bool): compress.ByteBufThe example for this item is shown with the ones above: rpc-Frames.salam
ReadFrameStr
func ReadFrameStr(s &: Stream, kind: int, ok &: bool): strThe example for this item is shown with the ones above: rpc-Frames.salam
WriteFrame
func WriteFrame(fd: i64, kind: int, payload: compress.ByteBuf): boolThe example for this item is shown with the ones above: rpc-Serve.salam
WriteFrameStr
func WriteFrameStr(fd: i64, kind: int, payload: str): boolThe example for this item is shown with the ones above: rpc-Serve.salam
NewServer
func NewServer(port: int, codec: int): ServerThe example for this item is shown with the ones above: rpc-Client.salam
SetFraming
func SetFraming(s &: Server, framing: int)The example for this item is shown with the ones above: rpc-Client.salam
InvokeBatch
func InvokeBatch(b: Batch): ResponsesThe example for this item is shown with the ones above: rpc-Methods.salam
HandlePayload
func HandlePayload(codec: int, payload: compress.ByteBuf): compress.ByteBufThe example for this item is shown with the ones above: rpc-Serve.salam
HandleText
func HandleText(text: str): strThe example for this item is shown with the ones above: rpc-Methods.salam
ServeConn
func ServeConn(fd: i64, codec: int, framing: int): intThe example for this item is shown with the ones above: rpc-Serve.salam
Listen
func Listen(s &: Server): boolThe example for this item is shown with the ones above: rpc-Client.salam
Port
func Port(s: Server): intThe example for this item is shown with the ones above: rpc-Client.salam
ServeCount
func ServeCount(s &: Server, n: int): intListen first if needed.The example for this item is shown with the ones above: rpc-Client.salam
Serve
func Serve(s &: Server)StopServer is called. A client that keeps its connection open makes the others wait.The example for this item is shown with the ones above: rpc-Client.salam
StopServer
func StopServer(s &: Server)The example for this item is shown with the ones above: rpc-Client.salam
ServeStdio
func ServeStdio(framing: int): intThe example for this item is shown with the ones above: rpc-Serve.salam
NewError
func NewError(code: int, message: str): ErrorThe example for this item is shown with the ones above: rpc-Messages.salam
StdError
func StdError(code: int): ErrorThe example for this item is shown with the ones above: rpc-Messages.salam
ErrorWithData
func ErrorWithData(code: int, message: str, data: value.Value): ErrorThe example for this item is shown with the ones above: rpc-Messages.salam
NewRequest
func NewRequest(method: str, params: value.Value, id: i64): RequestThe example for this item is shown with the ones above: rpc-Messages.salam
NewRequestStrId
func NewRequestStrId(method: str, params: value.Value, id: str): RequestThe example for this item is shown with the ones above: rpc-Messages.salam
NewNotification
func NewNotification(method: str, params: value.Value): RequestThe example for this item is shown with the ones above: rpc-Messages.salam
IsNotification
func IsNotification(r: Request): boolThe example for this item is shown with the ones above: rpc-Methods.salam
NewResponse
func NewResponse(id: value.Value, result: value.Value): ResponseThe example for this item is shown with the ones above: rpc-Messages.salam
NewErrorResponse
func NewErrorResponse(id: value.Value, e: Error): ResponseThe example for this item is shown with the ones above: rpc-Messages.salam
ParamCount
func ParamCount(r: Request): intThe example for this item is shown with the ones above: rpc-Methods.salam
ParamAt
func ParamAt(r: Request, i: int): value.ValueThe example for this item is shown with the ones above: rpc-Messages.salam
ParamNamed
func ParamNamed(r: Request, key: str): value.ValueThe example for this item is shown with the ones above: rpc-Messages.salam
Param
func Param(r: Request, key: str, pos: int): value.ValueThe example for this item is shown with the ones above: rpc-Methods.salam
ParamInt
func ParamInt(r: Request, key: str, pos: int): i64The example for this item is shown with the ones above: rpc-Methods.salam
ParamFloat
func ParamFloat(r: Request, key: str, pos: int): f64The example for this item is shown with the ones above: rpc-Methods.salam
ParamStr
func ParamStr(r: Request, key: str, pos: int): strThe example for this item is shown with the ones above: rpc-Methods.salam
ParamBool
func ParamBool(r: Request, key: str, pos: int): boolThe example for this item is shown with the ones above: rpc-Methods.salam
HasParam
func HasParam(r: Request, key: str, pos: int): boolThe example for this item is shown with the ones above: rpc-Messages.salam
Register
func Register(name: str, fn: i64)The example for this item is shown with the ones above: rpc-Methods.salam
RegisterDoc
func RegisterDoc(name: str, fn: i64, doc: str)The example for this item is shown with the ones above: rpc-Methods.salam
Unregister
func Unregister(name: str): boolThe example for this item is shown with the ones above: rpc-Methods.salam
HasMethod
func HasMethod(name: str): boolThe example for this item is shown with the ones above: rpc-Methods.salam
MethodCount
func MethodCount(): intThe example for this item is shown with the ones above: rpc-Methods.salam
ListMethods
func ListMethods(): Vector<str>The example for this item is shown with the ones above: rpc-Methods.salam
MethodDoc
func MethodDoc(name: str): strThe example for this item is shown with the ones above: rpc-Methods.salam
ResetRegistry
func ResetRegistry()The example for this item is shown with the ones above: rpc-Methods.salam
CallRequest
func CallRequest(slot: i64): RequestThe example for this item is shown with the ones above: rpc-Methods.salam
CallMethodName
func CallMethodName(slot: i64): strThe example for this item is shown with the ones above: rpc-Methods.salam
CallParams
func CallParams(slot: i64): value.ValueThe example for this item is shown with the ones above: rpc-Methods.salam
CallIsNotification
func CallIsNotification(slot: i64): boolThe example for this item is shown with the ones above: rpc-Methods.salam
CallParamCount
func CallParamCount(slot: i64): intThe example for this item is shown with the ones above: rpc-Methods.salam
CallParam
func CallParam(slot: i64, key: str, pos: int): value.ValueThe example for this item is shown with the ones above: rpc-Methods.salam
CallParamInt
func CallParamInt(slot: i64, key: str, pos: int): i64The example for this item is shown with the ones above: rpc-Methods.salam
CallParamFloat
func CallParamFloat(slot: i64, key: str, pos: int): f64The example for this item is shown with the ones above: rpc-Methods.salam
CallParamStr
func CallParamStr(slot: i64, key: str, pos: int): strThe example for this item is shown with the ones above: rpc-Methods.salam
CallParamBool
func CallParamBool(slot: i64, key: str, pos: int): boolThe example for this item is shown with the ones above: rpc-Methods.salam
Reply
func Reply(slot: i64, result: value.Value)The example for this item is shown with the ones above: rpc-Methods.salam
ReplyInt
func ReplyInt(slot: i64, n: i64)The example for this item is shown with the ones above: rpc-Methods.salam
ReplyFloat
func ReplyFloat(slot: i64, n: f64)The example for this item is shown with the ones above: rpc-Methods.salam
ReplyStr
func ReplyStr(slot: i64, s: str)The example for this item is shown with the ones above: rpc-Methods.salam
ReplyBool
func ReplyBool(slot: i64, b: bool)The example for this item is shown with the ones above: rpc-Methods.salam
ReplyNull
func ReplyNull(slot: i64)The example for this item is shown with the ones above: rpc-Methods.salam
Fail
func Fail(slot: i64, code: int, message: str)The example for this item is shown with the ones above: rpc-Methods.salam
FailWithData
func FailWithData(slot: i64, code: int, message: str, data: value.Value)The example for this item is shown with the ones above: rpc-Methods.salam
FailInvalidParams
func FailInvalidParams(slot: i64, message: str)The example for this item is shown with the ones above: rpc-Methods.salam
Invoke
func Invoke(req: Request): ResponseThe example for this item is shown with the ones above: rpc-Methods.salam
JsonEncodeRequest
func JsonEncodeRequest(r: Request): strThe example for this item is shown with the ones above: rpc-Messages.salam
JsonEncodeResponse
func JsonEncodeResponse(r: Response): strThe example for this item is shown with the ones above: rpc-Messages.salam
JsonEncodeResponses
func JsonEncodeResponses(rs: Responses): strThe example for this item is shown with the ones above: rpc-Messages.salam
JsonDecodeBatch
func JsonDecodeBatch(text: str): BatchThe example for this item is shown with the ones above: rpc-Methods.salam
JsonDecodeRequest
func JsonDecodeRequest(text: str, ok &: bool): RequestThe example for this item is shown with the ones above: rpc-Methods.salam
JsonDecodeResponse
func JsonDecodeResponse(text: str, ok &: bool): ResponseThe example for this item is shown with the ones above: rpc-Messages.salam
JsonDecodeResponses
func JsonDecodeResponses(text: str, ok &: bool): ResponsesThe example for this item is shown with the ones above: rpc-Messages.salam
JsonTopLevelError
func JsonTopLevelError(e: Error): strThe example for this item is shown with the ones above: rpc-Messages.salam