ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Protocols

OverviewQuick startCall shapesEnhancersErrors and statusClientOperations

Integrations

Operating

Reference

gRPC

Call shapes

Unary, server-streaming, client-streaming and bidirectional handlers, the extractors they take and the replies they return.

The method marker fixes the call shape, and the handler's signature must agree with it. A mismatch is a compile error spelling what the handler declares beside what the marker requires.

ShapeProtoRequest parameterReturn
unaryrpc M(Req) returns (Res)Message<Req> or Request<Req>a reply, or a Result of one
server streamingrpc M(Req) returns (stream Res)Message<Req> or Request<Req>a stream of Result<Res, E>, or a Result of one
client streamingrpc M(stream Req) returns (Res)Streaming<Req>a reply, or a Result of one
bidirectionalrpc M(stream Req) returns (stream Res)Streaming<Req>a stream of Result<Res, E>

The handlers below are from crates/ulo-codegen-tests/tests/grpc.rs, which serves one method of each shape and calls it through the generated client. The proto:

service Counter {
  rpc Add(AddRequest) returns (Sum);
  rpc Count(CountRequest) returns (stream Number);
  rpc Total(stream Number) returns (Sum);
  rpc Double(stream Number) returns (stream Number);
}
use futures_util::{Stream, StreamExt, stream};
use ulo::handlers;
use ulo_grpc::{Message, Request, Response, Streaming};

#[handlers]
impl CounterService {
    #[ulo_grpc::method(pb::counter::Add)]
    async fn add(&self, req: Request<AddRequest>) -> Result<Response<Sum>, Refusal> {
        let AddRequest { a, b } = *req.message();
        if a < 0 || b < 0 {
            return Err(Refusal);
        }
        let echo = req.metadata().get(ECHO).unwrap_or("").to_owned();
        Ok(Response::new(Sum { sum: a + b }).metadata(ECHO, &echo))
    }

    #[ulo_grpc::method(pb::counter::Count)]
    async fn count(&self, req: Message<CountRequest>) -> impl Stream<Item = Result<Number, Refusal>> {
        stream::iter((1..=i64::from(req.0.up_to)).map(|value| Ok(Number { value })))
    }

    #[ulo_grpc::method(pb::counter::Total)]
    async fn total(&self, items: Streaming<Number>) -> Result<Sum, Refusal> {
        let mut items = items;
        let mut sum = 0;
        while let Some(item) = items.next().await {
            sum += item.map_err(|_| Refusal)?.value;
        }
        Ok(Sum { sum })
    }

    #[ulo_grpc::method(pb::counter::Double)]
    fn double(&self, items: Streaming<Number>) -> impl Stream<Item = Result<Number, Refusal>> {
        items.map(|item| item.map(|n| Number { value: n.value * 2 }).map_err(|_| Refusal))
    }
}

examples/29-grpc-service has the unary and server-streaming forms with a guard and error details.

Request parameters

TypeGives
Message<T>the request message, as req.0
Request<T>the message with its metadata: message() and metadata()
Streaming<T>the caller's stream of messages, each a Result
GrpcCxthe call's context: path, metadata, peer, execution
ExecutionRefthe call's execution, including its deadline
Dep<T>an injected dependency

Message, Request and Streaming are ulo_grpc types, and Request is not tonic::Request. Each consumes the request body, so a handler taking two of them fails to compile with both named. A handler that reads no message is accepted and leaves the request unread. GrpcCx, ExecutionRef and Dep may appear in any number and order.

A message over 4 MiB fails extraction and is answered INVALID_ARGUMENT.

Returns

A handler may return:

  • the reply message, or (), which is google.protobuf.Empty,
  • Response<T>, which adds reply headers with .metadata(key, value) and reply trailers with .trailer(key, value),
  • a stream of Result<M, E> for a streaming reply, or Response<S> around one,
  • a Result of any of those.

The error implements Classify, or is a tonic::Status, which is sent as it stands (an OK status is sent as INTERNAL). ulo_grpc::from_status(status) as a stream item's error ends the stream with that status and its metadata. A stream of bare items is not an answer. See Errors and status.

.metadata writes the reply's headers and .trailer its trailers, written with grpc-status when the reply ends. A unary reply's trailers follow its message. A stream's are written when it ends on its own. A stream the server ends, at the deadline, at the drain's end or after a panic, ends with the status alone.

MetadataEntry::ascii(key, value) and MetadataEntry::binary(key, bytes) build an entry checked where it is built, and Response::metadata_entry and Response::trailer_entry take one. A key ending -bin carries bytes, sent base64-encoded, and any other key carries printable ASCII. An entry is refused when its key is off gRPC's grammar, begins grpc-, is te, content-type, content-length or one of the connection-specific names HTTP/2 forbids, or when its value's form does not match the key's -bin suffix. .metadata and .trailer check their entry the same way. An entry they refuse fails the reply. The error handlers see a CallError of kind Internal, and if none claims it the call is answered INTERNAL with the message withheld.

let reply = Response::new(())
    .metadata("x-cache", "miss")
    .trailer("x-rows", "12")
    .trailer_entry(MetadataEntry::binary("x-digest-bin", vec![0x00, 0xff])?);

Streams in flight

An error item ends a reply stream: the status travels in the trailers, since data frames have already been sent. A reply stream reports its end where the dispatcher writes it, completed on grpc-status: 0 and cut off on any other status or a reset.

A caller that abandons a call cancels the handler's execution with the reason ClientCancelled, whether the call's future was dropped before it answered or a reply body was dropped before its end. The drain's end cancels a reply stream that is still open and ends it with UNAVAILABLE. A deadline that passes while a stream is open ends it with DEADLINE_EXCEEDED.

Without the attribute

A controller written without #[ulo_grpc::method] mounts ulo_grpc::GrpcHandler::new::<Marker, _, _>(call).spec(name), taking the path and shape from the marker. crates/ulo-codegen-tests/tests/grpc_hand_written.rs serves one beside its attribute-written twin. A hand-written handler gets none of the attribute's compile-time checks against the marker.

Quick start

A gRPC service from a .proto file to a running server, with a guard and a domain error.

Enhancers

Guards, interceptors, error handlers and pre-dispatch middleware on gRPC services.

On this page

Request parametersReturnsStreams in flightWithout the attribute