jsonrpc

package
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 19 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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.

View Source
const DefaultMaxInFlight = 32

DefaultMaxInFlight bounds a connection's concurrent requests; reading pauses until one finishes.

View Source
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.

View Source
const EventMethod = "event"

EventMethod is the method of the server's event notifications.

View Source
const MaxMessageSize = 16 << 20

MaxMessageSize bounds one newline-delimited JSON message in either direction: 16 MiB, as a lodge /api frame.

Variables

View Source
var ErrEventsOverflow = errors.New("jsonrpc: event buffer overflow")

ErrEventsOverflow means the caller stopped reading Client.Notifications.

Functions

func AfterReply

func AfterReply(ctx context.Context, fn func())

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

func DecodeParams[C Code](raw jsontext.Value, p any, required []string) error

DecodeParams strictly decodes params into p: unknown members, and missing or null required members, are invalidParams. Absent or null params decode as {}.

func Listen

func Listen(path string, log *slog.Logger) (net.Listener, error)

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

func NewClient[C Code](conn net.Conn) *Client[C]

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

func (c *Client[C]) Call(ctx context.Context, method string, params, result any) error

Call sends a request and decodes the result into result (unless nil). A server error is returned as *Error[C].

func (*Client[C]) Close

func (c *Client[C]) Close() error

Close ends the connection and fails pending calls.

func (*Client[C]) Done

func (c *Client[C]) Done() <-chan struct{}

Done is closed when the connection ends.

func (*Client[C]) Err

func (c *Client[C]) Err() error

Err is why the connection ended, or nil while it is open.

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 ConnFrom

func ConnFrom(ctx context.Context) *Conn

ConnFrom returns the connection a request arrived on, or nil outside the server.

func (*Conn) Client

func (c *Conn) Client() string

Client is the name the client gave its hello: "" until then.

func (*Conn) Close

func (c *Conn) Close() error

Close ends the connection, such as a subscriber that lags.

func (*Conn) Context

func (c *Conn) Context() context.Context

Context ends when the connection does.

func (*Conn) Done

func (c *Conn) Done() <-chan struct{}

Done is closed when the connection ends.

func (*Conn) Go

func (c *Conn) Go(fn func(ctx context.Context))

Go runs fn for the connection, with its context; the connection waits for fn before it finishes closing.

func (*Conn) Notify

func (c *Conn) Notify(method string, params any) error

Notify sends a notification, such as an event (EventMethod with an EventEnvelope). One over MaxMessageSize is not sent.

func (*Conn) OnClose

func (c *Conn) OnClose(fn func())

OnClose runs fn when the connection has ended and its requests and Go functions have returned, the last registered first. On a closed connection, fn runs at once.

func (*Conn) Ready

func (c *Conn) Ready() bool

Ready reports whether the connection is ready.

func (*Conn) SetReady

func (c *Conn) SetReady(client string)

SetReady readies the connection after a hello that named the client, such as "notesctl".

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].

func Errorf

func Errorf[C Code](code C, format string, args ...any) *Error[C]

Errorf returns an *Error with a formatted message.

func (*Error[C]) Error

func (e *Error[C]) Error() string

Error is the code, by its String when it has one, and the message.

func (*Error[C]) Is

func (e *Error[C]) Is(target error) bool

Is matches a sentinel (an app's Err*) with the same code.

type Event

type Event interface {
	EventName() string
	Durable() bool
}

Event is an app's generated event type.

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

type HandlerFunc func(ctx context.Context, params jsontext.Value) (any, error)

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.

func (*Router[K, C]) Handle

func (r *Router[K, C]) Handle(method string, rt Route[K])

Handle registers method, replacing any route it had.

func (*Router[K, C]) Route

func (r *Router[K, C]) Route(method string) (Route[K], bool)

Route returns method's route, for tests that check every method's callers.

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 NewServer

func NewServer[C Code](opts ServerOptions) *Server[C]

NewServer returns a Server.

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

func (s *Server[C]) ServeConn(ctx context.Context, nc net.Conn, d Dispatcher)

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL