ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Protocols

OverviewQuick startCall shapesEnhancersErrors and statusClientOperations

Integrations

Operating

Reference

gRPC

Errors and status

How error kinds map to gRPC status codes, error details in grpc-status-details-bin, and errors that choose their own code.

A handler fails with an error implementing Classify, with a CallError, or with a tonic::Status. The kind of a Classify error decides the status code, its Display text is the status message, and its details() travel in grpc-status-details-bin.

Kinds to codes

ulo_grpc::code_for(kind) is the table:

ErrorKindgRPC code
BadRequestINVALID_ARGUMENT
UnprocessableINVALID_ARGUMENT
UnauthorizedUNAUTHENTICATED
ForbiddenPERMISSION_DENIED
NotFoundNOT_FOUND
ConflictABORTED
TooManyRequestsRESOURCE_EXHAUSTED
TimeoutDEADLINE_EXCEEDED
UnavailableUNAVAILABLE
UnimplementedUNIMPLEMENTED
Internal, and any error not recognisedINTERNAL, with the message withheld

A guard that returns Ok(false) is Forbidden and answers PERMISSION_DENIED. A framework event maps too: a panic is Internal, a payload that does not decode is BadRequest, a draining server is Unavailable.

A domain error

examples/29-grpc-service classifies an error and attaches details:

use std::collections::BTreeMap;
use ulo_grpc::{Classify, Detail, Details, ErrorKind, FieldViolation};

impl Classify for ItemError {
    fn classify(&self) -> ErrorKind {
        match self {
            ItemError::EmptyId => ErrorKind::BadRequest,
            ItemError::Missing(_) => ErrorKind::NotFound,
        }
    }

    fn details(&self) -> Details {
        match self {
            ItemError::EmptyId => Details::new().with(Detail::FieldViolations(vec![FieldViolation::new("id", "must not be empty")])),
            ItemError::Missing(id) => Details::new().with(Detail::ErrorInfo {
                reason: "ITEM_NOT_FOUND".to_owned(),
                domain: "catalog.example".to_owned(),
                metadata: BTreeMap::from([("id".to_owned(), id.clone())]),
            }),
        }
    }
}

#[derive(Classify)] with #[classify(not_found)] on the type or on each variant writes the classify method alone. An error that carries details or a public message different from its Display implements the trait by hand, as above.

The caller receives NOT_FOUND with the message "no item zz" and an ErrorInfo detail. From examples/29-grpc-service/tests/service.rs:

let status = client.get_item(authorized(GetItemRequest { id: "zz".into() })).await.expect_err("fails");
assert_eq!((status.code(), status.message()), (Code::NotFound, "no item `zz`"));
let details = status.get_error_details();
let info = details.error_info().expect("an ErrorInfo detail");
assert_eq!((info.reason.as_str(), info.domain.as_str()), ("ITEM_NOT_FOUND", "catalog.example"));

Details

Details is a list of typed entries that map onto google.rpc messages and are packed into a google.rpc.Status in grpc-status-details-bin:

DetailPacked as
FieldViolations(Vec<FieldViolation>)google.rpc.BadRequest
ErrorInfo { reason, domain, metadata }google.rpc.ErrorInfo
RetryAfter(Duration)google.rpc.RetryInfo
Help(Vec<Link>)google.rpc.Help
Json(Value)a google.protobuf.Struct for an object, otherwise a google.protobuf.Value, in an Any

An error with no details sends no grpc-status-details-bin. tonic-types holds one BadRequest, one ErrorInfo, one RetryInfo and one Help, so every FieldViolations detail's violations are merged into one BadRequest, every Help detail's links into one Help, and the first ErrorInfo and first RetryAfter are kept.

Choosing the code yourself

  • WithGrpcCode::with_grpc_code(Code) names a canonical code in place of the kind's, beside WithHttpStatus for HTTP and WithCloseCode for WebSocket. A resource that already exists writes CallError::new(ErrorKind::Conflict, ..).with_grpc_code(Code::AlreadyExists), where Conflict maps to ABORTED. The kind still decides the rendering on other transports. Code::Ok is not an error's code: it is ignored and logged at warn when the error is rendered.
  • A tonic::Status returned as the error reaches the wire as it stands, with its code, message, details and metadata as built, less any name gRPC reserves. No kind is consulted. It is the one way to name a code outside the eleven kinds without a CallError. Error handlers see it first. An OK status is not an error's and is sent as INTERNAL.
  • ulo_grpc::to_status(&CallError) renders an error as a tonic::Status, for a service that answers outside Ulo's dispatch.

Errors in streams

An Err item in a reply stream goes through the error handlers and is written as the trailers grpc-status, grpc-message and grpc-status-details-bin. Once data frames have been sent, the trailers are gRPC's only error form. An item that ends the stream with a status of its own, ulo_grpc::from_status(status), writes the status's metadata in those trailers with the trailers the reply set. A name gRPC reserves is dropped.

Deadlines and shutdown

A passed grpc-timeout cancels the call with the reason Deadline. Error handlers receive a Timeout and may reshape it, up to Server::timeout_grace (one second). An unclaimed Timeout is DEADLINE_EXCEEDED. A call over the server's in-flight limit gets UNAVAILABLE, "the server is at its in-flight limit". A call during the drain gets UNAVAILABLE, "the server is shutting down". Each is refused before an execution opens. Clients treat both as retryable. The in-flight refusal carries grpc-retry-pushback-ms, the server's shed_retry_after in whole milliseconds rounded up, which a client whose retry policy retries UNAVAILABLE waits instead of its own backoff. The drain refusal carries none.

A caller going through tonic's Channel enforces its own deadline and reads CANCELLED at the same instant, so it never sees what the handlers answered for a timeout.

Enhancers

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

Client

A tonic-generated client registered as an ordinary provider, a lazily connected channel, and deadlines forwarded with each call.

On this page

Kinds to codesA domain errorDetailsChoosing the code yourselfErrors in streamsDeadlines and shutdown