JsonRpc

interface JsonRpc

A JSON-RPC 2.0 session between two peers.

Create an instance with JsonRpc.of, providing a JsonRpcTransportSession that handles the raw byte/string transport (WebSocket, TCP, stdio, SSE, etc.):

val jsonRpc = JsonRpc.of(myTransportSession)

Sending messages

  • request — sends a call and suspends until the remote peer replies or the timeout elapses.

  • notify — sends a fire-and-forget message; the remote peer MUST NOT reply.

Both functions are safe to call concurrently from multiple coroutines.

Receiving messages

Consume callsInbox to handle incoming requests and notifications from the remote peer. See callsInbox for the recommended consumption patterns.

Error observability

  • localErrors — protocol errors detected locally (e.g. malformed incoming JSON).

  • remoteErrors — error responses received from the remote peer that could not be correlated to a pending request (e.g. the remote could not parse the request ID).

Lifecycle

Call close to shut down the session. It cancels internal coroutines, drains pending requests with an error, closes callsInbox, and delegates to JsonRpcTransportSession.close.

Types

Link copied to clipboard
object Companion

Properties

Link copied to clipboard
abstract val callsInbox: ReceiveChannel<JsonRpcCall>

An unlimited channel that delivers incoming JsonRpcCalls from the remote peer.

Link copied to clipboard
abstract val localErrors: SharedFlow<JsonRpcException>

A SharedFlow of JsonRpcException that occurred locally for Observability purposes.

Link copied to clipboard
abstract val remoteErrors: SharedFlow<JsonRpcException>

A SharedFlow of JsonRpcException that originated from the remote peer and were not directly linked to a request.

Functions

Link copied to clipboard
abstract suspend fun close()

Closes the session and releases all associated resources.

Link copied to clipboard
abstract suspend fun notify(method: String, params: JsonElement)

Sends a notification to the remote peer without expecting a response.

Link copied to clipboard
abstract suspend fun request(method: String, params: JsonElement, timeout: Duration = 30.seconds): Result<JsonElement>

Sends a request to the remote peer and suspends until a response is received or timeout elapses.

Link copied to clipboard
suspend fun <I, O> JsonRpc.request(call: Pair<JsonRpcEndpoint.WithReply<I, O>, I>, json: Json = Json): O