Pyjo.JSON.RPC - JSON-RPC 2.0

from Pyjo.JSON.RPC import RPC

rpc = RPC()

@rpc.method
def subtract(minuend: int, subtrahend: int) -> int:
    """Subtract two numbers."""
    return minuend - subtrahend

# {'jsonrpc': '2.0', 'result': 19, 'id': 1}
rpc.dispatch_p({'jsonrpc': '2.0', 'method': 'subtract', 'params': [42, 23], 'id': 1}).then(print).wait()

# Or import the module, as in Google Python Style Guide

import Pyjo.JSON.RPC

rpc = Pyjo.JSON.RPC.new()
rpc.method('subtract', lambda minuend, subtrahend: minuend - subtrahend)

# A route of an application of Pyjoyment.Lite
post('/rpc', rpc.to_action())

# A client, which sends its requests with a user agent
client = Pyjo.JSON.RPC.Client.new(lambda request: ua.post_p('/rpc', json=request).then(lambda tx: tx.res.json()))
client.call_p('subtract', 42, 23).then(print).wait()

Pyjo.JSON.RPC is an implementation of JSON-RPC 2.0, the requests, the notifications, the responses and the batches of a server, which calls the methods that it has, and of a client. It knows the messages, not how they travel: a message is a value as Pyjo.JSON decodes it, or the JSON of one, and a server or a client carries it over HTTP, as to_action() does for a route of Pyjoyment, or over a stream of messages in both directions, as serve() does for the standard input and output of Pyjo.IOLoop.Stdio or a WebSocket, where both peers are servers and clients.

A method gets the params of a request, the members of an array as its positional arguments and those of an object as its keyword arguments, and returns the result of the response, as a value, a Pyjo.Promise of it, or a coroutine, of an async def. A method that raises Error gives that error, and one that raises another exception gives -32603, Internal error, without its message, which the event exception gets. The params that the parameters of a method do not take give -32602, Invalid params, and so do those that its JSON Schema does not validate, with the errors of Pyjo.JSON.Schema as its data.

# {'jsonrpc': '2.0', 'error': {'code': -32602, 'message': 'Invalid params',
#  'data': '/subtrahend: Expected integer - got string.'}, 'id': 2}
@rpc.method('subtract', schema=True)
def subtract(minuend: int, subtrahend: int) -> int:
    return minuend - subtrahend

rpc.dispatch_p({'jsonrpc': '2.0', 'method': 'subtract', 'params': [42, 'x'], 'id': 2}).then(print).wait()

A notification, a request without an id, gets no response, also when it fails, and neither does a batch of notifications. A batch is answered with the responses of its requests in one array, once the last of them is there.

See also

Pyjo.JSON, Pyjo.JSON.Schema, https://mojolicious.org.

It has no counterpart in Mojolicious, and is written from the specification of JSON-RPC 2.0.

Classes

class Pyjo.JSON.RPC.Client(send: Callable[[dict[str, Any]], Any] | None = None)[source]

A client of JSON-RPC, which sends its requests with a function of the transport, and settles the promise of a call with the response that comes back, from what the function returns or from receive().

# HTTP, whose response comes back from the request
client = Pyjo.JSON.RPC.Client.new(lambda request: ua.post_p(url, json=request).then(lambda tx: tx.res.json()))

# A WebSocket, whose responses come back on their own
client = Pyjo.JSON.RPC.Client.new(lambda request: ws.send({'json': request}))
ws.on('json', lambda ws, message: client.receive(message))
__init__(send: Callable[[dict[str, Any]], Any] | None = None) → None[source]
client = Pyjo.JSON.RPC.Client.new()
client = Pyjo.JSON.RPC.Client.new(send)

Construct a new Client object.

call_p(method: str, *args: Any, **kwargs: Any) → Pyjo_Promise[source]
promise = client.call_p('subtract', 42, 23)
promise = client.call_p('subtract', minuend=42, subtrahend=23)

Call a method, with its positional or its keyword arguments as the params, and return a Pyjo.Promise of the result, which an error of the response rejects with an Error.

client.call_p('subtract', 42, 23).then(print).catch(lambda e: print(f'{e.code}: {e.message}')).wait()
fail(e: Any) → None[source]
client.fail(Pyjo.Exception.new('Connection closed'))

Reject the calls that wait for their responses, as the transport does when no response can come anymore, as at its end.

notify(method: str, *args: Any, **kwargs: Any) → Any[source]
client.notify('update', 1, 2, 3)
client.notify('update', values=[1, 2, 3])

Send a notification, a request without a response, and return what send returns.

receive(message: Any) → bool[source]
boolean = client.receive({'jsonrpc': '2.0', 'result': 19, 'id': 1})
boolean = client.receive(b'{"jsonrpc": "2.0", "result": 19, "id": 1}')

Settle the calls of a response or of a batch of them, as Pyjo.JSON decodes it, or the JSON of one, and return whether it was a response to a call, so that another message, as a request of the server on the same stream, goes elsewhere.

send
send = client.send
client.send = lambda request: ...

The function of the transport, which gets a request or a notification, and returns the response, as receive() takes it, or a Pyjo.Promise of it, or anything else, as None, when the response comes back to receive().

exception Pyjo.JSON.RPC.Error(code: int = -32603, message: str | None = None, data: Any = <object object>)[source]

An error of JSON-RPC, which a method raises for the response of its request, and which rejects the promise of a call of Client.

raise Pyjo.JSON.RPC.Error.new(-32000, 'Not enough credit', {'balance': 3})
__init__(code: int = -32603, message: str | None = None, data: Any = <object object>) → None[source]
e = Pyjo.JSON.RPC.Error.new(-32000, 'Not enough credit')
e = Pyjo.JSON.RPC.Error.new(-32000, 'Not enough credit', {'balance': 3})
e = Pyjo.JSON.RPC.Error.new(Pyjo.JSON.RPC.INVALID_PARAMS)

Construct a new Error object, with the message of the specification for one of its codes by default.

__json__() → dict[str, Any][source]
error = e.__json__()

The error object of a response, as Pyjo.JSON encodes it, with code, message and data, where it has one.

code
code = e.code

The code of the error, an integer.

data
data = e.data

What the server tells about the error, None if it tells nothing.

classmethod from_json(error: Any) → Self[source]
e = Pyjo.JSON.RPC.Error.from_json({'code': -32601, 'message': 'Method not found'})

The Error of the error object of a response.

Pyjo.JSON.RPC.INTERNAL_ERROR = -32603

The code of the error of a method that fails.

Pyjo.JSON.RPC.INVALID_PARAMS = -32602

The code of the error of parameters that the method does not take.

Pyjo.JSON.RPC.INVALID_REQUEST = -32600

The code of the error of a message that is not a request.

Pyjo.JSON.RPC.METHOD_NOT_FOUND = -32601

The code of the error of a method that the server does not have.

Pyjo.JSON.RPC.PARSE_ERROR = -32700

The code of the error of a message that is not JSON.

class Pyjo.JSON.RPC.Pyjo_JSON_RPC[source]

Pyjo.JSON.RPC inherits all events and methods from Pyjo.EventEmitter and implements the following new ones.

Events

exception

@rpc.on('exception')
def exception(rpc, e, context):
    ...

Emitted when a method raises an exception that is not an Error, which the response does not tell, with the context of the request.

rpc.on('exception', lambda rpc, e, context: print(f'Failed: {e}'))
__init__() → None[source]
rpc = Pyjo.JSON.RPC.new()

Construct a new Pyjo.JSON.RPC object.

dispatch_p(message: Any, context: Any = None) → Pyjo_Promise[source]
promise = rpc.dispatch_p({'jsonrpc': '2.0', 'method': 'subtract', 'params': [42, 23], 'id': 1})
promise = rpc.dispatch_p(b'{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}')
promise = rpc.dispatch_p(request, context=c)

Dispatch a request, a notification or a batch, as Pyjo.JSON decodes it, or the JSON of one, as bytes or str, to the methods, and return a Pyjo.Promise of the response, or of None for a notification or a batch of notifications. The promise is not rejected: an error is a response. context is what a method that asks for it gets, as the controller of to_action().

# {'jsonrpc': '2.0', 'error': {'code': -32601, 'message': 'Method not found'}, 'id': 1}
rpc.dispatch_p({'jsonrpc': '2.0', 'method': 'foobar', 'id': 1}).then(print).wait()
method(name: F, cb: None = None) → F[source]
method(name: str | None = None, cb: None = None, *, context: bool = False, schema: bool | dict[str, Any] | Pyjo_JSON_Schema | None = None) → Callable[[F], F]
method(name: str, cb: F, *, context: bool = False, schema: bool | dict[str, Any] | Pyjo_JSON_Schema | None = None) → F
cb = rpc.method('subtract', lambda minuend, subtrahend: minuend - subtrahend)
cb = rpc.method('whoami', lambda c: c.req.headers.user_agent, context=True)
cb = rpc.method('subtract', subtract, schema=True)
cb = rpc.method('subtract', subtract, schema={'type': 'object'})

Add a method, and return its callback. Without a callback, it is a decorator, with the name of the method or of the function.

@rpc.method
def subtract(minuend: int, subtrahend: int) -> int:
    return minuend - subtrahend

@rpc.method('math.add', schema=True)
def add(a: int, b: int) -> int:
    return a + b

With context, the method gets the context of the request before its parameters, as the controller of to_action(). schema validates the parameters with a Pyjo.JSON.Schema object or a schema of its own, or, with True, with parameters() of the function, the schema of its type hints. Positional parameters are validated as the members of an object that the names of the parameters of the function have.

property methods: list[str][source]
names = rpc.methods

The names of the methods, in the order that they were added.

serve(peer: Any, context: Any = None, *, dispatch_p: Callable[[Any, Client], Any] | None = None) → Client[source]
client = rpc.serve(messages)
client = rpc.serve(messages, context=app)
client = rpc.serve(messages, dispatch_p=lambda message, client: rpc.dispatch_p(message, {'client': client}))

Serve the methods to a peer on a stream of messages in both directions, as a Pyjo.IOLoop.Messages object, a Pyjo.Transaction.WebSocket object or the controller of a WebSocket, anything with the event message and the method send, and return the Client of the peer, whose requests go on the same stream, so that both peers are servers and clients.

A message that is a response to a call of the client settles it, and a response to no call is dropped, as an error of it would go back and forth between two peers. Any other message is dispatched, with context, the client by default, so that a method that asks for it calls the peer back, and its response is sent once it is there: the requests are served at the same time, and their responses may go out in another order.

The event end of the peer, the end of its input, rejects the calls of the client, which get no response anymore, and closes the peer gracefully once the requests in progress have their responses, and the events close and finish reject them too.

dispatch_p is a function that dispatches each message in the place of dispatch_p() with context, which the function chooses itself, so it is an error to give both. It gets the message, as Pyjo.JSON decodes it, which is not a response, and the client, and returns the response, a Pyjo.Promise of it, or a coroutine, or None for a notification, so that a protocol on JSON-RPC gives each request a context of its own or rules of its own. A function that raises, or whose promise is rejected, gives -32603, Internal error, to the requests of the message that have an id, and the event exception, with the client as the context.

# Standard input and output, whose method asks the client
@rpc.method(context=True)
def greet(client, name):
    return client.call_p('confirm', f'Greet {name}?').then(lambda yes: f'Hello, {name}!' if yes else 'Bye')

messages = Pyjo.IOLoop.Messages.new(Pyjo.IOLoop.Stdio.new())
rpc.serve(messages)
messages.start()

# A WebSocket of Pyjoyment.Lite
websocket('/rpc', lambda c: rpc.serve(c))

# A context of its own for each request, and no batches
def dispatch_p(message, client):
    if isinstance(message, list):
        return {'jsonrpc': '2.0', 'error': {'code': -32600, 'message': 'No batches'}, 'id': None}
    return rpc.dispatch_p(message, {'client': client})

rpc.serve(messages, dispatch_p=dispatch_p)
to_action() → Callable[[Pyjoyment.Controller.object], Pyjo_Promise][source]
action = rpc.to_action()

The action of a route of Pyjoyment, which dispatches the body of the request, with the controller as the context, and renders the response in JSON, 202 Accepted without a body for a notification or a batch of notifications, and 400 Bad Request for a body that is not JSON or not a request. A method that fails is logged.

# Pyjoyment.Lite
post('/rpc', rpc.to_action())

# Pyjoyment
app.routes.post('/rpc').to(cb=rpc.to_action())