Enhancers
Guards, interceptors, error handlers and pre-dispatch middleware on gRPC services.
Enhancers are the same roles as on every transport, written over the gRPC context: Guard<Grpc>, Interceptor<Grpc> and ErrorHandler<Grpc>. Their order and scoping rules are shared with the other transports; see Request lifecycle.
Where they attach
The attributes go on the #[handlers] impl, which covers every method of the service, or on one method. The grpc selector names the transport on an impl that mixes transports. From crates/ulo-codegen-tests/tests/enhancers.rs:
use ulo::handlers;
use ulo_grpc::Message;
#[handlers]
#[guards(grpc = TokenGuard)]
#[interceptors(grpc(value = Header("x-served-by", "vault")))]
impl Vault {
#[ulo_grpc::method(probe::vault::Open)]
fn open(&self, req: Message<Ticks>) -> Tick { /* .. */ }
#[ulo_grpc::method(probe::vault::Sealed)]
#[guards(value = Deny)]
fn sealed(&self, req: Message<Ticks>) -> Tick { /* .. */ }
#[ulo_grpc::method(probe::vault::Fragile)]
#[interceptors(value = Header("x-stamped", "yes"))]
#[error_handlers(value = Mend)]
fn fragile(&self, req: Message<Ticks>) -> Result<Tick, Refusal> { /* .. */ }
}value = expr builds the enhancer once and shares it. A type name resolves it from the container. Enhancers attached to the impl run for every method; those on a method add to them.
Guards
A guard reads the call through GrpcCx: cx.metadata().get("authorization"), cx.path(), cx.peer(), cx.exec(). It runs before the request message is decoded.
Ok(false) refuses the call with PERMISSION_DENIED. Returning a CallError chooses the kind: examples/29-grpc-service returns CallError::unauthorized("Bearer"), which is UNAUTHENTICATED.
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()),
}
}
}Interceptors
An interceptor wraps the handler. It reads and writes reply metadata through the reply's headers and cannot read the message. That is what lets one interceptor list serve every method of a service. From tests/enhancers.rs:
use http::HeaderValue;
use ulo::{BoxError, Interceptor, Next};
use ulo_grpc::{Grpc, GrpcCx, Reply};
impl Interceptor<Grpc> for Header {
async fn intercept(&self, _cx: &GrpcCx, next: Next<'_, Grpc>) -> Result<Reply, BoxError> {
let mut reply = next.run().await?;
reply.headers_mut().insert(self.0, HeaderValue::from_static(self.1));
Ok(reply)
}
}An interceptor cannot forge a status. Every reply the framework builds records its grpc- headers before an interceptor sees it. Afterwards a grpc- name the interceptor added is dropped, and one it changed or removed is written back as the framework wrote it. Each name is logged at warn the first time it is screened.
Error handlers
An error handler sees every error: a handler's own error, a guard's refusal, an interceptor's failure and a panic. It claims an error by returning Ok(reply) and passes it on by returning Err. A handler claims through the context, which builds the reply:
| Method | Builds |
|---|---|
cx.reply(value) | a Result of a reply message, or of Response<T> with metadata |
cx.reply_stream(stream) | a Result of a reply stream; an Err item is written to the trailers |
cx.reply_status(status) | a trailers-only reply for a tonic::Status |
reply and reply_stream return Result<Reply, IntoReplyError>, which fails when a Response contains a metadata entry its builder refused. An error handler writes Ok(cx.reply(..)?), since its error type is BoxError.
From crates/ulo-codegen-tests/tests/grpc_interceptor_headers.rs:
use tonic::Status;
use ulo::{BoxError, ErrorHandler};
impl ErrorHandler<Grpc> for Mend {
async fn handle(&self, err: BoxError, cx: &GrpcCx) -> Result<Reply, BoxError> {
let refused = err.downcast_ref::<ulo_transport::CallError>().and_then(|error| error.source_as::<Refusal>()).is_some();
if refused { Ok(cx.reply_status(Status::failed_precondition("mended"))) } else { Err(err) }
}
}An error returned as a tonic::Status reaches the next handler and, if none claims it, is sent as it stands, with its metadata in the trailers-only reply. An OK status is sent as INTERNAL.
Pre-dispatch middleware
gRPC is HTTP/2, so http::Request and http::Response are its types. ulo_grpc::PreDispatch takes apply, apply_value, apply_for and exclude as HTTP does, scoped by method path such as /codegen.probe.v1.Known/*. From tests/grpc_scope_by_path.rs:
m.meta::<ulo_grpc::PreDispatch>()
.apply_value(Mark)
.apply_for::<RequireKey>(["/codegen.probe.v1.Known/*"])
.exclude(["/codegen.probe.v1.Known/Ping"]);A scope is matched against the call's path, including a path no handler answers, so an anonymous caller is refused the same way whether or not the method exists. Scoped entries run before reflection. They never run before health, which Kubernetes probes and load balancers call without credentials. A layer that answers a non-200 HTTP status is translated by the specification's table: 400 INTERNAL, 401 UNAUTHENTICATED, 403 PERMISSION_DENIED, 404 UNIMPLEMENTED, 429, 502, 503 and 504 UNAVAILABLE, anything else UNKNOWN.
The middleware API is shared with HTTP; see Request lifecycle.