Handler attributes
The attributes each transport crate adds for its handlers, the arguments they take and what each refuses at compile time.
A handler is a method of a #[handlers] impl marked with its transport's attribute. One impl may mix transports. Each attribute is a thin layer over ulo-handler-codegen and lowers to Mount::handler(HandlerSpec::<T, _>::new(name, value).route(..)..). It builds the same handler value a hand-written controller builds: ulo_http::HttpHandler, ulo_rpc::RpcHandler, ulo_ws::WsHandler and ulo_grpc::GrpcHandler.
| Attribute | Re-exported by | Transport key | Handler value |
|---|---|---|---|
#[get], #[post], #[put], #[patch], #[delete], #[head], #[options] | ulo-http | http | HttpHandler |
#[message], #[event] | ulo-rpc | rpc | RpcHandler |
#[gateway], #[message] | ulo-ws | ws, and ws_connect for connect_guards | WsHandler, GatewayHooks |
#[method] | ulo-grpc | grpc | GrpcHandler |
The attribute is written by its crate's path, as #[ulo_http::get("/")]. The transport key is what a transport-scoped enhancer entry names: #[guards(http = AuthGuard)].
Each handler parameter is either a FromContainer type (Dep, Many, Ext, ModuleRef, ExecutionRef, Option of those), which every transport accepts, or a FromCall<T> type the transport defines. At most one parameter consumes the body or payload, and the macro checks that at compile time. A handler may return (), a value, a stream or any of those inside a Result; the error side always reaches the error handlers. The spelling of the return type decides nothing, so a type alias for a Result behaves as the Result.
A streaming handler's return type gains + use<> on every opaque type in its return position, so the stream does not capture &self. A stream that needs the controller takes self: Arc<Self>.
HTTP
ulo-http exports seven verb attributes. Each takes one argument, the route pattern.
#[handlers]
impl HelloController {
#[ulo_http::get("/")]
fn hello(&self) -> &'static str {
"Hello, ulo!"
}
}From examples/01-hello. Handlers with parameters, from examples/15-http-requests:
#[ulo_http::post("/notes")]
fn create(&self, Valid(Json(new)): Valid<Json<NewNote>>) -> Created<Json<Note>> {
#[ulo_http::get("/notes/{id}")]
fn find(&self, Path(id): Path<u32>) -> Found {Route pattern grammar. Static text, {name} segments, and an optional final {*name} that matches the rest of the path. The pattern starts with /. One trailing slash is insignificant, so /files/{*rest}/ ends in its rest segment. A parameter name is non-empty, starts with _ or a letter, continues with _, letters and digits, and appears once.
{name} is the only parameter syntax. The same grammar is parsed again at prepare, so a route written without the macro is checked against it.
| Verb | Behaviour beyond the method |
|---|---|
#[get] | A HEAD request on the path is answered from it with the body omitted, unless a #[head] route exists. |
#[options] | Without one, OPTIONS on a matching path answers 204 with Allow. A CORS preflight never reaches routing. |
Refused:
| Input | Diagnostic |
|---|---|
| no argument | #[get] takes the route pattern, as in #[get("/users/{id}")] |
| a malformed literal | invalid route pattern: followed by one reason from the list below, spanned on the literal |
outside a #[handlers] impl | #[get] goes on a method of a `#[handlers]` impl, which hands it the handler's enhancers; if this method is in one, `#[handlers]` took another attribute for its transport attribute: a method has one, and when every attribute macro on it sits inside `cfg_attr`, the first is taken |
Reasons a pattern is refused:
a pattern starts with `/`a segment between two `/` is emptya `{` opens a segment that does not end with `}``{*name}` is the last segment onlya parameter name appears twicea brace appears outside a whole `{name}` segmenta parameter name is emptya parameter name starts with `_` or a lettera parameter name holds only `_`, letters and digits
RPC
#[message("pattern")] is a request-reply handler in any of the four call shapes. #[event("pattern")] is a fire-and-forget handler. An event reaches one instance of the server by default, and #[event("pattern", every_instance)] reaches every instance. Redis delivers every event to every subscribed instance and logs a warn. TCP and UDP refuse every_instance at prepare. every_instance is written bare, last, and only on #[event]. The call shape is read from the signature: an Inbound<T> parameter is a streamed request and a stream return is a streamed reply, recorded with HandlerSpec::shape. An #[event] refuses a stream return at compile time and an Inbound<T> parameter at prepare.
From examples/25-rpc-basics:
#[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::event("calc.note")]
async fn note(&self, text: Payload<String>) -> Result<(), CalcError> {A pattern is non-empty and contains no whitespace or control character. A controller's .at(prefix) is not read by RPC: Transport::READS_PREFIX is false, and wire() refuses a prefix on a controller none of whose handlers read one.
| Input | Diagnostic |
|---|---|
| no argument | #[message] takes the pattern, as in #[message("invoices.create")] (#[event] likewise) |
| an empty pattern | invalid pattern: a pattern is not empty |
| whitespace or a control character | invalid pattern: a pattern holds no whitespace or control character |
every_instance on #[message] | `every_instance` is an `#[event]` option: a request reaches one instance, and its caller takes one reply |
an option other than every_instance, on #[event] | unknown option `x`; the one option is `every_instance`, on `#[event]` |
outside a #[handlers] impl | the text of the HTTP verbs, with #[message] or #[event] as the name |
WebSocket
#[gateway(..)] goes on a #[handlers] impl and turns it into impl GatewayConfig. #[message("event")] goes on its handler methods, one execution per message.
From examples/23-ws-gateway:
#[handlers]
#[ulo_ws::gateway(
path = "/chat",
port = own,
session_with = |head: Dep<UpgradeHead>| Visitor {
name: head.headers().get(NAME).and_then(|name| name.to_str().ok()).unwrap_or("anonymous").to_owned(),
badge: OnceLock::new(),
},
connect_guards(value = Admit),
)]
#[guards(value = Stamp)]
impl Chat {
#[ulo_ws::message("say")]
fn say(&self, text: Payload<String>, speaker: Ext<Speaker>) -> String {#[gateway] also probes the connection hooks at the concrete type: OnConnect, OnDisconnect and AfterInit, each registered when the type implements it.
Gateway settings, each at most once:
| Setting | Value | Lowers to |
|---|---|---|
path | a string starting with /; required | GatewaySettings::at(path) |
namespace, event | a string | .namespace(..), .event(..); event names the envelope field that carries the event name |
codec | json or msgpack | .codec(Codec::Json), .codec(Codec::MsgPack) |
subprotocols | a list of strings | .subprotocols([..]) |
session | a type | SessionFactory::default_of::<T>() |
session_with | a closure whose parameters are injection points | SessionFactory::with(closure); a gateway takes either this or session, not both |
connect_guards(..) | the entry forms of #[guards], without a transport key | Guard<WsConnect> entries on the connect phase |
refuse | close or handshake | .refuse(Refuse::..) |
overflow | close or drop_oldest | .overflow(Overflow::..) |
port | http or own | .port(Port::Http), .port(Port::Own); own needs a standalone server such as ulo-ws-hyper |
max_message | an expression | .max_message(..) |
max_connections, max_inflight, max_outbound | an integer literal, or a Count expression | .max_connections(Count::Max(n)) and kin |
ping_interval, pong_timeout | an expression | .ping_interval(..), .pong_timeout(..) |
#[message("cancel")] is refused: cancel is the envelope's reserved event, which a client sends as {"event":"cancel","id":..} to cancel a message.
| Input | Diagnostic |
|---|---|
#[gateway] on a trait impl | #[ulo_ws::gateway] goes on the `#[handlers]` impl holding the `#[ulo_ws::message]` handlers, not on a trait impl |
a gateway with no #[message] handler | a gateway with no `#[ulo_ws::message]` handler mounts nothing; add one, or implement `ulo_ws::Gateway` by hand for a gateway that reads every message raw |
no path | a gateway takes its path, as in `#[ulo_ws::gateway(path = "/chat")]` |
a path not starting with / | a gateway path starts with `/` |
| a setting twice | `path` is written twice (the name varies) |
session and session_with together | `session` and `session_with` are two spellings of one setting; write one |
| a word setting with another word | `codec` takes `json` or `msgpack` (the setting varies) |
| an unknown setting | expected `path`, `namespace`, `event`, `codec`, `subprotocols`, `session`, `session_with`, `connect_guards(..)`, `refuse`, `overflow`, `port`, `max_message`, `max_connections`, `max_inflight`, `max_outbound`, `ping_interval` or `pong_timeout` |
a connect_guards entry with a transport key | every `connect_guards(..)` entry is a `Guard<WsConnect>`; it takes no transport key |
#[message] with no argument | #[message] takes the event, as in #[message("chat.send")] |
| an empty event name | an event name is not empty |
the event cancel | `cancel` is the envelope's reserved event: a client sends `{"event":"cancel","id":..}` to cancel a message |
gRPC
#[method(Marker)] binds a handler to a method marker that ulo-build generated from the .proto. The marker supplies the path (Marker::PATH), the request and response types and the call shape (Marker::SHAPE). The attribute checks the handler's signature against the marker through trait bounds at the concrete site, so a mismatch fails to compile.
From examples/29-grpc-service:
#[handlers]
#[guards(grpc = TokenGuard)]
impl CatalogService {
#[ulo_grpc::method(pb::catalog::GetItem)]
async fn get_item(&self, req: Message<pb::GetItemRequest>) -> Result<pb::Item, ItemError> {
#[ulo_grpc::method(pb::catalog::ListItems)]
async fn list_items(&self, req: Message<pb::ListItemsRequest>) -> impl Stream<Item = Result<pb::Item, ItemError>> {The build script, from examples/29-grpc-service/build.rs:
fn main() -> Result<(), Box<dyn std::error::Error>> {
ulo_build::configure().compile(&["proto/catalog.proto"], &["proto"])?;
println!("cargo::rerun-if-changed=proto/catalog.proto");
Ok(())
}ulo_build::configure() returns a Builder with out_dir, file_descriptor_set_path and build_client. compile(protos, includes) runs tonic-prost-build over a vendored protoc (the default-on vendored-protoc feature; a PROTOC environment variable wins) and writes one marker type per RPC method under the service's module. ulo_grpc::include_proto!("catalog.v1") includes the output. The crate running the build step depends on tonic (with channel and codegen), tonic-prost and prost beside ulo-grpc, and on prost-types where a proto uses a well-known type other than Empty.
| Input | Diagnostic |
|---|---|
| no argument | #[method] takes the method marker ulo-build generated, as in #[method(pb::user_service::GetUser)] |
| a request parameter whose message differs from the marker's | rustc E0599 no method named `__ulo_matches` found for struct `ParamCheck<(Shaped<false>, Number), (Shaped<false>, AddRequest)>` |
| a reply whose message differs from the marker's | rustc E0599 no method named `__ulo_checked` found for struct `Checked<..>` |
| a streamed request for a unary method, or the reverse | the same E0599 on ParamCheck<(Shaped<true>, ..), (Shaped<false>, ..)> |
| a unary reply for a streaming method, or the reverse | the same E0599 on Checked<(Shaped<false>, ..), (Shaped<true>, ..)> |
| a generic handler | refused when the mount function is emitted |
The E0599 diagnostics name private probe types. The Shaped<bool> parameter is the call shape, true for a stream, and the two type arguments of ParamCheck and Checked are what the signature has and what the marker expects.