Documentation
¶
Overview ¶
Package jsonrpc is the apps' JSON-RPC 2.0 runtime, one message per line: the server's connection loop, the router with caller kinds, the client, and the private socket. It is generic over an app's own types, the generated ErrorCode (C) and its caller kind (K), so an app's generated api package sits on it unchanged (https://github.com/frostyard/lodge/blob/main/docs/adr/0012-the-kit-shares-the-rpc-runtime-not-the-generator.md).
An app's hand-written api runtime names the kit's types:
type ErrorCode int // the generated constants and String name it
type Error = jsonrpc.Error[ErrorCode]
type Frame = jsonrpc.Frame[ErrorCode]
type Event = jsonrpc.Event
type EventEnvelope = jsonrpc.EventEnvelope
type Router struct{ *jsonrpc.Router[Caller, ErrorCode] }
type Client struct{ *jsonrpc.Client[ErrorCode] }
func (r *Router) handle(method string, callers []Caller, writes bool, h jsonrpc.HandlerFunc) {
r.Handle(method, jsonrpc.Route[Caller]{Callers: callers, Writes: writes, Handler: h})
}
func decodeParams(raw jsontext.Value, p any, required []string) error {
return jsonrpc.DecodeParams[ErrorCode](raw, p, required)
}
and its rpcserver serves its router on the kit:
rpc := jsonrpc.NewServer[api.ErrorCode](jsonrpc.ServerOptions{Hello: "rpc.hello"})
ln, err := jsonrpc.ListenWith(socket, jsonrpc.ListenOptions{Name: "notesd", Logger: log}) // same uid only
err = rpc.Serve(ctx, ln, router, asLocal) // asLocal puts the caller in each connection's context
rpc.ServeConn(asSession(ctx), nc, router) // lodge's /api (lodgeapp.Server.API)
Its NewClient names the daemon in the client's errors: jsonrpc.NewClientWith[ErrorCode](conn, jsonrpc.ClientOptions{Name: "notesd"}). Its rpc.hello calls ConnFrom(ctx).SetReady(client). Its events.subscribe starts delivery with AfterReply and Conn.Go, and sends with Conn.Notify(EventMethod, envelope).
Index ¶
- Constants
- Variables
- func AfterReply(ctx context.Context, fn func())
- func DecodeParams[C Code](raw jsontext.Value, p any, required []string) error
- func Listen(path string, log *slog.Logger) (net.Listener, error)
- func ListenWith(path string, opts ListenOptions) (net.Listener, error)
- type Client
- type ClientOptions
- type Code
- type Conn
- func (c *Conn) Client() string
- func (c *Conn) Close() error
- func (c *Conn) Context() context.Context
- func (c *Conn) Done() <-chan struct{}
- func (c *Conn) Go(fn func(ctx context.Context))
- func (c *Conn) Notify(method string, params any) error
- func (c *Conn) OnClose(fn func())
- func (c *Conn) Ready() bool
- func (c *Conn) SetReady(client string)
- type Dispatcher
- type Error
- type Event
- type EventEnvelope
- type Frame
- type HandlerFunc
- type ListenOptions
- type Route
- type Router
- type RouterOptions
- type Server
- type ServerOptions
Constants ¶
const ( CodeParseError = -32700 CodeInvalidRequest = -32600 CodeMethodNotFound = -32601 CodeInvalidParams = -32602 CodeInternal = -32603 // CodeNotReady is the apps' notReady: a call before the connection's // hello (ServerOptions.Hello). CodeNotReady = 1004 )
The JSON-RPC 2.0 error codes, and the one code of the apps' own that the server answers itself.
const DefaultMaxInFlight = 32
DefaultMaxInFlight bounds a connection's concurrent requests; reading pauses until one finishes.
const EventBuffer = 1024
EventBuffer is how many undelivered events a Client holds before it fails the connection with ErrEventsOverflow; the caller then reconnects and resubscribes with its last seq.
const EventMethod = "event"
EventMethod is the method of the server's event notifications.
const MaxMessageSize = 16 << 20
MaxMessageSize bounds one newline-delimited JSON message in either direction: 16 MiB, as a lodge /api frame.
Variables ¶
var ErrEventsOverflow = errors.New("jsonrpc: event buffer overflow")
ErrEventsOverflow means the caller stopped reading Client.Notifications.
Functions ¶
func AfterReply ¶
AfterReply runs fn once the successful reply to ctx's request is on the wire, such as event delivery after events.subscribe answers; it does not run when the request fails. Outside a request, fn runs at once.
func DecodeParams ¶
DecodeParams strictly decodes params into p: unknown members, and missing or null required members, are invalidParams. Absent or null params decode as {}.
func Listen ¶
Listen creates an app's private socket at path, mode 0600, in a directory that must be private (0700 and owned by the user; it is created if missing): the socket its CLI and desktop app use. A stale socket is replaced; a live one means the daemon is already running. Accept admits only processes of the same user (SO_PEERCRED), and closes the rest, logged to log when it is not nil. ListenWith names the daemon in its errors.
func ListenWith ¶
func ListenWith(path string, opts ListenOptions) (net.Listener, error)
ListenWith is Listen with options.
Types ¶
type Client ¶
type Client[C Code] struct { // contains filtered or unexported fields }
Client is a connection to a Server, with error codes of type C. It is safe for concurrent use; calls are multiplexed by request ID. An app's api package embeds it in its own Client, on which the generated domain clients hang.
func NewClient ¶
NewClient starts a client on an established connection. The caller makes the server's hello first, if it has one.
func NewClientWith ¶
func NewClientWith[C Code](conn net.Conn, opts ClientOptions) *Client[C]
NewClientWith is NewClient with options.
func (*Client[C]) Call ¶
Call sends a request and decodes the result into result (unless nil). A server error is returned as *Error[C].
func (*Client[C]) Done ¶
func (c *Client[C]) Done() <-chan struct{}
Done is closed when the connection ends.
func (*Client[C]) Notifications ¶
func (c *Client[C]) Notifications() <-chan EventEnvelope
Notifications delivers server events. It is closed when the connection ends; Err then says why.
type ClientOptions ¶
type ClientOptions struct {
// Name is the server's, such as "notesd", for the client's errors:
// "notesd: connection closed", "write to notesd: …". Empty names the
// kit and "the server".
Name string
}
ClientOptions configures NewClientWith.
type Code ¶
type Code interface{ ~int }
Code is an app's error-code type, such as its generated api.ErrorCode: an int whose String names the code.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is one connection a Server serves. Handlers reach it with ConnFrom, to notify the client, to keep state for the connection's lifetime, or to ready it after hello.
func (*Conn) Go ¶
Go runs fn for the connection, with its context; the connection waits for fn before it finishes closing.
func (*Conn) Notify ¶
Notify sends a notification, such as an event (EventMethod with an EventEnvelope). One over MaxMessageSize is not sent.
type Dispatcher ¶
type Dispatcher interface {
Dispatch(ctx context.Context, method string, params jsontext.Value) (any, error)
}
Dispatcher runs one method: a Router, or an app's type that embeds one.
type Error ¶
type Error[C Code] struct { Code C `json:"code"` Message string `json:"message"` Data jsontext.Value `json:"data,omitzero"` }
Error is a JSON-RPC error object, with the app's code type. Handlers return one to choose the code; the server answers any other error as internal. An app's api package names it: type Error = jsonrpc.Error[ErrorCode].
type EventEnvelope ¶
type EventEnvelope struct {
Seq int64 `json:"seq,omitzero"`
Event string `json:"event"`
Data jsontext.Value `json:"data"`
}
EventEnvelope is the params of an "event" notification. Seq is set for durable events only.
func NewEnvelope ¶
func NewEnvelope(seq int64, ev Event) (EventEnvelope, error)
NewEnvelope encodes ev for delivery.
type Frame ¶
type Frame[C Code] struct { JSONRPC string `json:"jsonrpc"` ID jsontext.Value `json:"id,omitzero"` Method string `json:"method,omitzero"` Params jsontext.Value `json:"params,omitzero"` Result jsontext.Value `json:"result,omitzero"` Error *Error[C] `json:"error,omitzero"` }
Frame is one JSON-RPC 2.0 message in either direction: a request (ID and Method), a notification (Method, no ID) or a response (ID with Result or Error).
type HandlerFunc ¶
HandlerFunc decodes params, calls the service and returns the result.
type ListenOptions ¶
type ListenOptions struct {
// Name is the daemon's, such as "notesd": "notesd is already listening
// on PATH". Empty says "another server".
Name string
// Logger receives refused connections. Nil discards them.
Logger *slog.Logger
}
ListenOptions configures ListenWith.
type Route ¶
type Route[K comparable] struct { Callers []K // Writes marks a method that changes state, which RouterOptions.Admit // may refuse, such as under an agent's read scope. Writes bool Handler HandlerFunc }
Route is one method: the caller kinds it admits, whether it writes, and its handler.
type Router ¶
type Router[K comparable, C Code] struct { // contains filtered or unexported fields }
Router maps wire method names to handlers, with the caller kinds of type K each admits. An app's api package embeds it in its own Router, so the generated code registers through the app's unexported handle.
func NewRouter ¶
func NewRouter[K comparable, C Code](opts RouterOptions[K]) *Router[K, C]
NewRouter returns an empty Router.
func (*Router[K, C]) Dispatch ¶
func (r *Router[K, C]) Dispatch(ctx context.Context, method string, params jsontext.Value) (any, error)
Dispatch runs one method for the caller in ctx. A method that does not exist, that does not admit the caller's kind, or that Admit refuses, answers methodNotFound alike, so a caller cannot learn what it may not call.
type RouterOptions ¶
type RouterOptions[K comparable] struct { // Caller returns a request's caller kind, which a method must list. It // is required. Caller func(ctx context.Context) K // Admit, when set, may refuse a call its method's callers admit, such // as a write under a read scope. Admit func(ctx context.Context, method string, r Route[K]) bool }
RouterOptions configures a Router.
type Server ¶
type Server[C Code] struct { // contains filtered or unexported fields }
Server serves newline-delimited JSON-RPC 2.0 on connections, with error codes of type C:
- each line is one message of at most MaxMessageSize;
- requests run concurrently, MaxInFlight at a time, behind Hello;
- a handler that panics answers internal and is logged, and the connection lives on;
- a handler's *Error[C] is sent as is, and any other error answers internal;
- a reply over MaxMessageSize, which the client could not read, answers internal instead;
- client notifications are ignored, since the protocol defines none.
func (*Server[C]) Serve ¶
func (s *Server[C]) Serve(ctx context.Context, ln net.Listener, d Dispatcher, conn func(context.Context) context.Context) error
Serve accepts connections on ln until ctx ends, and serves each with ServeConn, in the context conn returns for it (ctx when conn is nil), which carries what the app's handlers know of the connection, such as its caller. It then waits for every connection to end. The listener checks who may connect (Listen, lodgeapp.Env.Listen).
func (*Server[C]) ServeConn ¶
ServeConn serves one connection whose listener has authenticated it, until it ends or ctx does, and then closes it: a socket connection from Serve, lodge's /api (lodgeapp.Server.API), or a development gateway's. ctx carries what the app's handlers know of the connection, and each request's context also carries the Conn (ConnFrom).
type ServerOptions ¶
type ServerOptions struct {
// Hello is the method that readies a connection, such as rpc.hello:
// until its handler calls Conn.SetReady, every other request answers
// notReady, and the hello runs inline, so a call pipelined after it
// sees the connection ready. Empty readies every connection at once.
Hello string
// MaxInFlight bounds each connection's concurrent requests:
// DefaultMaxInFlight when 0.
MaxInFlight int
// Logger receives panics, failed requests and dropped replies. Nil
// discards them.
Logger *slog.Logger
}
ServerOptions configures a Server.