RPC controllers
Messages that answer their caller, events that answer nobody, payload extraction, error kinds and guards.
An RPC controller is a struct marked #[controller] whose methods carry #[ulo_rpc::message("pattern")] or #[ulo_rpc::event("pattern")], inside an impl marked #[handlers]. The example below is examples/25-rpc-basics.
use ulo::{Dep, controller, handlers, module};
use ulo_rpc::Payload;
#[controller]
pub struct Calculator {
journal: Dep<Journal>,
}
#[handlers]
#[guards(RoleGuard)]
impl Calculator {
#[ulo_rpc::message("calc.divide")]
async fn divide(&self, req: Payload<Divide>) -> Result<i64, CalcError> {
req.0.dividend.checked_div(req.0.divisor).ok_or(CalcError::DivideByZero)
}
#[ulo_rpc::message("calc.clear")]
#[meta(RequiresRole("admin"))]
async fn clear(&self) -> usize {
self.journal.clear()
}
#[ulo_rpc::event("calc.note")]
async fn note(&self, text: Payload<String>) -> Result<(), CalcError> {
self.journal.0.lock().expect("the journal is not poisoned").push(text.0);
Ok(())
}
}
#[module(providers = [Journal, RoleGuard], controllers = [Calculator])]
pub struct AppModule;The controller goes in controllers, its dependencies and guards in providers.
Messages and events
message | event | |
|---|---|---|
| Caller | request(..), send_stream(..), stream(..), duplex(..) | emit(..) |
| Answers the caller | with the handler's value or its error | never |
| Return type | a value, (), a stream, or a Result of any of those | Result<(), E> |
| Shapes | unary, streamed request, streamed reply, duplex | unary only |
A handler with a stream return or an Inbound<T> parameter on an #[event] is refused: the stream return fails to compile, and a handler mounted by hand with a streamed shape is refused when the server prepares. The shape of a message handler comes from its signature; see Streaming.
An event's emitter does not wait for the handler. emit(..) completes when the link has published the event, and the handler commonly runs after the emitter has finished.
An event reaches one server instance by default. #[ulo_rpc::event("pattern", every_instance)] declares an event every instance receives, such as a cache invalidation or a configuration reload. TCP and UDP refuse that declaration when the server prepares, since the caller names one server. every_instance on a #[message] is a compile error, since a request reaches one instance and its caller takes one reply. Redis delivers every event to every instance, and a server logs a warning for the ones left at the default. See Links.
A pattern belongs to one handler. Two handlers for one pattern are refused when the server prepares. A pattern is its own name, so a prefix a module gives a controller with .at(prefix) does not apply to it, and wire() refuses such a prefix on a controller whose handlers are all RPC handlers.
Parameters
Every parameter is extracted from the call, in any order:
| Parameter | Carries |
|---|---|
Payload<T> | the message or event body, decoded with the link's codec |
Inbound<T> | the caller's stream of items, for a streamed request |
CallHeaders | the headers the caller sent |
RpcCx | the call's context: pattern, headers, link name, peer, execution |
ExecutionRef | the call's execution, including its deadline |
Dep<T> | an injected dependency, as in any other handler |
A handler that needs no payload takes none, as clear does above. ExecutionRef is how a handler reads its deadline and forwards it; see Deadlines.
A payload that does not decode is answered bad_request. Payload<Bytes> carries raw bytes and needs a link configured with the CBOR codec; a JSON link refuses such a handler when the server prepares.
Errors
A handler fails with any error implementing Classify, which requires std::error::Error. The derive names the error's kind, and the error also implements Display and Error, by hand or with thiserror:
use ulo_rpc::Classify;
#[derive(Debug, Classify)]
pub enum CalcError {
#[classify(unprocessable)]
DivideByZero,
}
impl fmt::Display for CalcError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("the divisor is zero")
}
}
impl std::error::Error for CalcError {}The caller receives the kind, the error's Display text as the message, and any details the error carries. From examples/25-rpc-basics/tests/rpc.rs:
let error = client.request::<_, i64>("calc.divide", &Divide { dividend: 1, divisor: 0 }).await.expect_err("refused");
assert_eq!((error.kind(), error.message()), (ErrorKind::Unprocessable, "the divisor is zero"));An error that is not Classify and is not recognised by the framework is answered internal with the message withheld. The kind word in #[classify(..)] is the wire name:
ErrorKind | Wire kind and #[classify(..)] word |
|---|---|
BadRequest | bad_request |
Unauthorized | unauthorized |
Forbidden | forbidden |
NotFound | not_found |
Conflict | conflict |
Unprocessable | unprocessable |
TooManyRequests | too_many_requests |
Timeout | timeout |
Unavailable | unavailable |
Unimplemented | unimplemented |
Internal | internal |
On the wire a failed call is an err frame carrying {kind, message, details}. The caller reads it as an RpcError with kind(), message(), details() and reason(). Conditions the framework raises itself carry a reason: a handler that does not exist answers unavailable with pattern_unhandled (see Links for what brokers do instead), and a server over its in-flight limit answers unavailable with a RetryAfter detail.
Domain errors, error kinds and error handlers are shared with every transport; see Request lifecycle.
Guards
A guard for RPC implements Guard<Rpc> and reads the call through RpcCx. examples/25-rpc-basics/src/roles.rs admits a call whose x-role header names the role the handler declared with #[meta(..)]:
use ulo::{BoxError, Guard, injectable};
use ulo_rpc::{Rpc, RpcCx};
pub struct RequiresRole(pub &'static str);
#[injectable]
pub struct RoleGuard;
impl Guard<Rpc> for RoleGuard {
async fn can_activate(&self, cx: &RpcCx) -> Result<bool, BoxError> {
let needed = cx.exec().handler().and_then(|handler| handler.meta::<RequiresRole>()).map(|role| role.0);
Ok(needed.is_none_or(|needed| cx.headers().get("x-role") == Some(needed)))
}
}A guard that returns Ok(false) refuses the call with Forbidden and the message forbidden. The handler does not run. A guard that returns an error fails the call with that error's kind. The caller sets the header on the call: client.request::<_, usize>("calc.clear", &()).header("x-role", "admin").
#[guards(..)] accepts a transport selector, #[guards(rpc = ServiceTokenGuard)], for a guard that should apply to RPC handlers only on an impl that mixes transports. examples/41-one-guard-two-transports writes one guard generic over the transport and uses it on an HTTP route and an RPC message. Interceptors and error handlers attach the same way; see Request lifecycle.