pub(crate) mod body;
mod capture;
mod dump;
pub(crate) mod providers;
use std::convert::Infallible;
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::{Instant, SystemTime};
use axum::Router;
use axum::body::Body;
use axum::extract::{Request, State as AxumState};
use axum::middleware::Next;
use axum::response::Response;
use futures_util::FutureExt as _;
use redup_bootstrap_grpc::diagnostics::{DumpRegistry, MessageTypes};
use redup_bootstrap_grpc::{
Binder, CallContext, CallKind, Exposure, INSTANCE_HEADER, ResponseTrailers, decorate,
};
use tokio::sync::OwnedSemaphorePermit;
use tokio_util::sync::CancellationToken;
use tonic::Status;
use tracing::Instrument as _;
use crate::grpc_server::body::{CallState, TrackedBody, deadline};
use crate::grpc_server::capture::{Capture, TeeBody};
use crate::grpc_server::dump::{CAPTURE_LIMIT, DumpCapture, peer};
use crate::guard::CallGuard;
use crate::telemetry::Telemetry;
use crate::telemetry::load::LoadKind;
use crate::telemetry::load::Work;
use crate::telemetry::request;
#[derive(Clone)]
pub(crate) struct State {
pub(crate) binder: Binder,
pub(crate) telemetry: Arc<Telemetry>,
pub(crate) service_name: String,
pub(crate) instance_id: String,
pub(crate) exposure: Exposure,
pub(crate) debug_info: bool,
pub(crate) token: CancellationToken,
pub(crate) guards: Vec<Arc<dyn CallGuard>>,
pub(crate) dumps: Arc<DumpRegistry>,
pub(crate) types: Arc<MessageTypes>,
}
pub(crate) fn router(routes: tonic::service::Routes, state: State) -> Router {
routes
.into_axum_router()
.layer(axum::middleware::from_fn_with_state(state, handle))
}
async fn handle(
AxumState(mut state): AxumState<State>,
mut request: Request,
next: Next,
) -> Response {
if request
.extensions()
.get::<redup_bootstrap_grpc::InternalCall>()
.is_some()
{
state.exposure = Exposure::Full;
state.debug_info = true;
}
let path = request.uri().path().to_owned();
let method = state.binder.method(&path);
let opened = request::open(request.headers(), &path, "POST");
let span = opened.span;
let correlation_id = opened.correlation_id;
let token = state.token.child_token();
request.extensions_mut().insert(token.clone());
if let Some(deadline) = CallContext::deadline_from(request.headers()) {
let token = token.clone();
tokio::spawn(async move {
tokio::select! {
_ = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)) => token.cancel(),
_ = token.cancelled() => {}
}
});
}
for guard in &state.guards {
match AssertUnwindSafe(guard.guard(&mut request))
.catch_unwind()
.await
{
Ok(Ok(())) => {}
Ok(Err(status)) => {
let response = error_response(&state, &correlation_id, status.clone());
state.telemetry.grpc_handled(
method.map_or(path.as_str(), |method| method.path),
status.code(),
);
return response;
}
Err(panic) => {
tracing::warn!(
path,
error = %crate::panic_error::Panic::from_payload(Some(panic)),
"the call guard failed after a panic recorded above"
);
let status = Status::internal("the call guard panicked");
let response = error_response(&state, &correlation_id, status.clone());
state.telemetry.grpc_handled(
method.map_or(path.as_str(), |method| method.path),
status.code(),
);
return response;
}
}
}
let context = CallContext::from_headers_with(request.headers(), opened.trace, token.clone());
let service = state.binder.service_of(&path);
let permit = match service
.as_ref()
.map(redup_bootstrap_grpc::ServiceInfo::try_acquire)
{
Some(Err(_limit)) => {
let limit = service
.as_ref()
.and_then(redup_bootstrap_grpc::ServiceInfo::limit_size)
.unwrap_or_default();
let status = Status::resource_exhausted(format!(
"Incoming request to method {} reached limit ({limit}).",
method.map_or(path.as_str(), |method| method.path)
));
let response = error_response(&state, &correlation_id, status);
state.telemetry.grpc_handled(
method.map_or(path.as_str(), |method| method.path),
tonic::Code::ResourceExhausted,
);
return response;
}
Some(Ok(permit)) => permit,
None => None,
};
let counter = service
.as_ref()
.map(redup_bootstrap_grpc::ServiceInfo::counter);
if let Some(counter) = &counter {
counter.fetch_add(1, Ordering::Relaxed);
}
if let Some(method) = method {
state.telemetry.grpc_started(method.kind);
}
request.extensions_mut().insert(context.clone());
let started = Instant::now();
let dump = capture_dump(&state, method, &path, &mut request);
let guard = state.telemetry.load().work(LoadKind::Incoming);
let outcome = AssertUnwindSafe(next.run(request).instrument(span.clone()))
.catch_unwind()
.await;
let response = match outcome {
Ok(response) => response,
Err(panic) => {
tracing::warn!(
path,
error = %crate::panic_error::Panic::from_payload(Some(panic)),
"the incoming call failed after a panic recorded above"
);
let status = Status::internal("the handler panicked");
let response = error_response(&state, &correlation_id, status.clone());
let call = call_state(
&state,
method,
&path,
&correlation_id,
&span,
started,
guard,
counter,
permit,
dump,
None,
);
call.finish(None, Some(status));
return response;
}
};
if let Some(status) = Status::from_header_map(response.headers()) {
let trailers = response.extensions().get::<ResponseTrailers>().cloned();
let (mut parts, inner) = response.into_parts();
if status.code() != tonic::Code::Ok {
let decorated = decorate(
&status,
&state.service_name,
state.exposure,
state.debug_info,
&correlation_id,
);
let headers = decorated.into_http::<()>();
for (name, value) in headers.headers() {
if name != http::header::CONTENT_TYPE {
parts.headers.insert(name.clone(), value.clone());
}
}
}
if let Ok(value) = state.instance_id.parse() {
parts.headers.insert(INSTANCE_HEADER, value);
}
let response = Response::from_parts(parts, inner);
let call = call_state(
&state,
method,
&path,
&correlation_id,
&span,
started,
guard,
counter,
permit,
dump,
trailers,
);
call.finish(None, Some(status));
return response;
}
let trailers = response.extensions().get::<ResponseTrailers>().cloned();
let (parts, inner) = response.into_parts();
let dump = dump.map(|mut dump| {
dump.response_encoding = encoding(&parts.headers);
dump
});
let call = call_state(
&state,
method,
&path,
&correlation_id,
&span,
started,
guard,
counter,
permit,
dump,
trailers,
);
let tracked = TrackedBody::new(inner, call, deadline(&context));
Response::from_parts(parts, axum::body::Body::new(tracked))
}
fn capture_dump(
state: &State,
method: Option<redup_bootstrap_grpc::MethodInfo>,
path: &str,
request: &mut Request,
) -> Option<DumpCapture> {
let method = method?;
if !state.dumps.is_active() {
return None;
}
let needs = state.dumps.needs(path);
let request_needed =
needs.request && matches!(method.kind, CallKind::Unary | CallKind::ServerStreaming);
let response_needed =
needs.response && matches!(method.kind, CallKind::Unary | CallKind::ClientStreaming);
if !request_needed && !response_needed {
return None;
}
let request_encoding = encoding(request.headers());
let remote = peer(request);
let request_capture = request_needed.then(|| Capture::new(CAPTURE_LIMIT));
if let Some(capture) = &request_capture {
let empty = Request::new(Body::empty());
let (parts, body) = std::mem::replace(request, empty).into_parts();
*request = Request::from_parts(parts, Body::new(TeeBody::new(body, Arc::clone(capture))));
}
Some(DumpCapture {
registry: Arc::clone(&state.dumps),
method: path.to_owned(),
remote,
started_at: SystemTime::now(),
input_type: state.types.input(path).map(str::to_owned),
output_type: state.types.output(path).map(str::to_owned),
request: request_capture,
response: response_needed.then(|| Capture::new(CAPTURE_LIMIT)),
request_encoding,
response_encoding: None,
})
}
fn encoding(headers: &http::HeaderMap) -> Option<String> {
headers
.get("grpc-encoding")
.and_then(|value| value.to_str().ok())
.map(str::to_owned)
}
#[allow(clippy::too_many_arguments)]
fn call_state(
state: &State,
method: Option<redup_bootstrap_grpc::MethodInfo>,
path: &str,
correlation_id: &str,
span: &tracing::Span,
started: Instant,
guard: Work,
counter: Option<Arc<std::sync::atomic::AtomicU64>>,
permit: Option<OwnedSemaphorePermit>,
dump: Option<DumpCapture>,
trailers: Option<ResponseTrailers>,
) -> CallState {
CallState {
method,
path: path.to_owned(),
telemetry: Arc::clone(&state.telemetry),
service_name: state.service_name.clone(),
instance_id: state.instance_id.clone(),
exposure: state.exposure,
debug_info: state.debug_info,
correlation_id: correlation_id.to_owned(),
started,
guard: Some(guard),
counter,
permit,
span: span.clone(),
dump,
trailers,
}
}
fn error_response(state: &State, correlation_id: &str, status: Status) -> Response {
let status = decorate(
&status,
&state.service_name,
state.exposure,
state.debug_info,
correlation_id,
);
let response = status.into_http::<tonic::body::Body>();
let (parts, inner) = response.into_parts();
Response::from_parts(parts, axum::body::Body::new(inner))
}
const _: fn(Result<Response, Infallible>) = |_| {};