ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Protocols

OverviewQuick startCall shapesEnhancersErrors and statusClientOperations

Integrations

Operating

Reference

gRPC

Quick start

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

This page builds examples/29-grpc-service: a Catalog service with a unary method, a server-streaming method, a guard that reads the call's metadata, and an error that reaches the caller as a status code plus google.rpc details.

1. Dependencies

Cargo.toml
[dependencies]
ulo = "=0.1.0-alpha.3"
ulo-grpc = "=0.1.0-alpha.3"
ulo-runtime-tokio = "=0.1.0-alpha.3"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
futures-util = "0.3"
# What the generated code names.
prost = "0.14"
tonic = { version = "0.14", default-features = false, features = ["channel", "codegen"] }
tonic-prost = "0.14"

[build-dependencies]
ulo-build = "=0.1.0-alpha.3"

2. The contract

proto/catalog.proto
syntax = "proto3";

package catalog.v1;

service Catalog {
  rpc GetItem(GetItemRequest) returns (Item);
  rpc ListItems(ListItemsRequest) returns (stream Item);
}

message GetItemRequest {
  string id = 1;
}

message ListItemsRequest {
  uint32 limit = 1;
}

message Item {
  string id = 1;
  string name = 2;
}

3. The build step

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 runs tonic's code generator with a vendored protoc, so none needs installing. A PROTOC environment variable wins when set. It writes the messages, a client per service and, beside them, a marker type per method under a module named after the service: pb::catalog::GetItem and pb::catalog::ListItems here, next to pb::catalog_client. No server trait is generated.

configure() also takes out_dir(..), build_client(false) and file_descriptor_set_path(..), which Operations uses for reflection.

4. The service

src/lib.rs
use futures_util::{Stream, stream};
use ulo::{controller, handlers, module};
use ulo_grpc::Message;

pub mod pb {
    ulo_grpc::include_proto!("catalog.v1");
}

#[controller]
pub struct CatalogService;

#[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> {
        let id = req.0.id;
        if id.is_empty() {
            return Err(ItemError::EmptyId);
        }
        ITEMS.iter().find(|(known, _)| *known == id).map(|(id, name)| item(id, name)).ok_or(ItemError::Missing(id))
    }

    #[ulo_grpc::method(pb::catalog::ListItems)]
    async fn list_items(&self, req: Message<pb::ListItemsRequest>) -> impl Stream<Item = Result<pb::Item, ItemError>> {
        let limit = if req.0.limit == 0 { ITEMS.len() } else { req.0.limit as usize };
        stream::iter(ITEMS.iter().take(limit).map(|(id, name)| Ok(item(id, name))))
    }
}

#[module(controllers = [CatalogService], providers = [TokenGuard])]
pub struct AppModule;

The attribute checks the handler's signature against the marker at compile time: a request type that is not the method's, or a unary handler returning a stream, does not compile. What a handler may return is covered in Call shapes.

The guard is an ordinary Guard<Grpc>:

src/lib.rs
use ulo::{BoxError, Guard};
use ulo_grpc::{CallError, Grpc, GrpcCx};

impl Guard<Grpc> for TokenGuard {
    async fn can_activate(&self, cx: &GrpcCx) -> Result<bool, BoxError> {
        match cx.metadata().get("authorization") {
            Some(TOKEN) => Ok(true),
            _ => Err(CallError::unauthorized("Bearer").into()),
        }
    }
}

See Enhancers and Errors and status.

5. Serving

src/main.rs
use ulo_grpc::Server;
use ulo_runtime_tokio::{Tokio, shutdown_signal};

let app = ex_29_grpc_service::builder()
    .runtime(Tokio::current())
    .wire()?
    .connect()
    .await?
    .bind(Server::new(format!("127.0.0.1:{port}")))
    .listen()
    .await?;
for bound in app.addresses() {
    println!("listening on http://{}", bound.addr);
}
app.serve(shutdown_signal()).await?;
cargo run -p ex-29-grpc-service
grpcurl -plaintext -H 'authorization: Bearer open' -d '{"id":"a1"}' \
  -import-path examples/29-grpc-service/proto -proto catalog.proto \
  127.0.0.1:50051 catalog.v1.Catalog/GetItem

The server listens on PORT, 50051 unless set. Any gRPC client reaches it. The example's tests call it through the generated CatalogClient; tests/service.rs covers replies, the guard on both methods and the details decoded from the trailer.

Where to go next

  • Call shapes: the other two shapes, whole-request access and reply metadata.
  • Operations: TLS, health, reflection and limits.
  • Client: calling another gRPC service from a handler.

Overview

Contract-first gRPC services from a .proto file, served over HTTP/2 with the same dependency injection and enhancers as every other transport.

Call shapes

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

On this page

1. Dependencies2. The contract3. The build step4. The service5. ServingWhere to go next