use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::task::{Context, Poll};
use std::time::Instant;
use axum::body::Body;
use bytes::Bytes;
use http::HeaderMap;
use http_body::Frame;
use redup_bootstrap_grpc::{
CallContext, Exposure, MethodInfo, ResponseTrailers, decorate, details,
};
use tokio::sync::OwnedSemaphorePermit;
use tokio::time::Sleep;
use tonic::Status;
use crate::grpc_server::dump::DumpCapture;
use crate::telemetry::Telemetry;
use crate::telemetry::load::Work;
const INSTANCE_HEADER: &str = "redup-bootstrap-instance-id";
const CLIENT_CODES: [tonic::Code; 9] = [
tonic::Code::Cancelled,
tonic::Code::InvalidArgument,
tonic::Code::NotFound,
tonic::Code::AlreadyExists,
tonic::Code::PermissionDenied,
tonic::Code::ResourceExhausted,
tonic::Code::FailedPrecondition,
tonic::Code::OutOfRange,
tonic::Code::Unauthenticated,
];
pub(crate) struct CallState {
pub(crate) method: Option<MethodInfo>,
pub(crate) path: String,
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) correlation_id: String,
pub(crate) started: Instant,
pub(crate) guard: Option<Work>,
pub(crate) counter: Option<Arc<AtomicU64>>,
pub(crate) permit: Option<OwnedSemaphorePermit>,
pub(crate) span: tracing::Span,
pub(crate) dump: Option<DumpCapture>,
pub(crate) trailers: Option<ResponseTrailers>,
}
impl CallState {
pub(crate) fn finish(mut self, trailers: Option<&mut HeaderMap>, status: Option<Status>) {
let mut failure = status.filter(|status| status.code() != tonic::Code::Ok);
let mut final_code = failure
.as_ref()
.map_or(tonic::Code::Ok, tonic::Status::code);
let mut decorated = None;
if let Some(map) = trailers {
if let Some(status) = Status::from_header_map(map) {
final_code = status.code();
if final_code != tonic::Code::Ok {
let decorated_status = decorate(
&status,
&self.service_name,
self.exposure,
self.debug_info,
&self.correlation_id,
);
merge_status(map, &decorated_status);
decorated = Some(decorated_status);
failure = Some(status);
}
}
if let Some(extra) = &self.trailers {
merge_extra(map, extra);
}
if let Ok(value) = self.instance_id.parse() {
map.insert(INSTANCE_HEADER, value);
}
}
if let Some(dump) = self.dump.take() {
let _ = dump.record(failure.as_ref());
}
self.record(final_code, decorated.as_ref());
}
fn record(&mut self, code: tonic::Code, decorated: Option<&Status>) {
let elapsed = self.started.elapsed();
let method = self
.method
.map_or_else(|| self.path.clone(), |method| method.path.to_owned());
self.telemetry.grpc_handled(&method, code);
self.telemetry
.http_request("POST", 200, &method, "2", elapsed);
let elapsed_ms = u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX);
let _entered = self.span.enter();
if code == tonic::Code::Ok {
tracing::debug!(method, elapsed_ms, "incoming call handled");
} else {
let parsed = decorated.map(details).unwrap_or_default();
let local = parsed
.path
.as_deref()
.is_none_or(|path| !path.contains('/'));
if CLIENT_CODES.contains(&code) {
tracing::warn!(
method,
code = redup_bootstrap_client::code_name(code),
reason = parsed.reason.as_deref().unwrap_or(""),
path = parsed.path.as_deref().unwrap_or(""),
elapsed_ms,
"incoming call failed"
);
} else if local && let Some(stack) = parsed.debug {
tracing::error!(
method,
code = redup_bootstrap_client::code_name(code),
reason = parsed.reason.as_deref().unwrap_or(""),
elapsed_ms,
stack = %stack,
"incoming call failed"
);
} else {
tracing::error!(
method,
code = redup_bootstrap_client::code_name(code),
reason = parsed.reason.as_deref().unwrap_or(""),
path = parsed.path.as_deref().unwrap_or(""),
elapsed_ms,
"incoming call failed on transit"
);
}
}
if let Some(counter) = &self.counter {
counter.fetch_sub(1, Ordering::Relaxed);
}
self.permit.take();
self.guard.take();
}
}
impl Drop for CallState {
fn drop(&mut self) {
if let Some(counter) = &self.counter {
counter.fetch_sub(1, Ordering::Relaxed);
}
}
}
fn merge_status(map: &mut HeaderMap, status: &Status) {
let headers = status.clone().into_http::<()>();
for (name, value) in headers.headers() {
if name == http::header::CONTENT_TYPE {
continue;
}
map.insert(name.clone(), value.clone());
}
}
pub(crate) struct TrackedBody {
inner: Body,
state: Option<CallState>,
deadline: Option<Pin<Box<Sleep>>>,
finished: bool,
}
impl TrackedBody {
pub(crate) fn new(
inner: Body,
state: CallState,
deadline: Option<tokio::time::Instant>,
) -> Self {
Self {
inner,
state: Some(state),
deadline: deadline.map(|deadline| Box::pin(tokio::time::sleep_until(deadline))),
finished: false,
}
}
fn finish(&mut self, trailers: Option<&mut HeaderMap>, status: Option<Status>) {
if self.finished {
return;
}
self.finished = true;
if let Some(state) = self.state.take() {
state.finish(trailers, status);
}
}
}
impl http_body::Body for TrackedBody {
type Data = Bytes;
type Error = axum::Error;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
let this = self.get_mut();
if this.finished {
return Poll::Ready(None);
}
if let Some(deadline) = this.deadline.as_mut()
&& deadline.as_mut().poll(cx).is_ready()
{
let mut trailers = HeaderMap::new();
let status = Status::deadline_exceeded("the call deadline is exceeded");
merge_status(&mut trailers, &status);
this.finish(Some(&mut trailers), None);
return Poll::Ready(Some(Ok(Frame::trailers(trailers))));
}
match Pin::new(&mut this.inner).poll_frame(cx) {
Poll::Ready(Some(Ok(frame))) => {
if let Some(data) = frame.data_ref()
&& let Some(state) = &this.state
&& let Some(dump) = &state.dump
&& let Some(capture) = dump.response_capture()
{
capture.push(data);
}
if let Some(trailers) = frame.trailers_ref() {
let mut trailers = trailers.clone();
this.finish(Some(&mut trailers), None);
return Poll::Ready(Some(Ok(Frame::trailers(trailers))));
}
Poll::Ready(Some(Ok(frame)))
}
Poll::Ready(Some(Err(error))) => {
this.finish(None, Some(Status::unavailable("the response body failed")));
Poll::Ready(Some(Err(error)))
}
Poll::Ready(None) => {
this.finish(None, None);
Poll::Ready(None)
}
Poll::Pending => Poll::Pending,
}
}
fn is_end_stream(&self) -> bool {
self.finished || self.inner.is_end_stream()
}
fn size_hint(&self) -> http_body::SizeHint {
self.inner.size_hint()
}
}
impl Drop for TrackedBody {
fn drop(&mut self) {
if !self.finished {
self.finish(
None,
Some(Status::cancelled("the client cancelled the call")),
);
}
}
}
fn merge_extra(map: &mut HeaderMap, extra: &ResponseTrailers) {
for (name, value) in extra.entries() {
if name.starts_with("grpc-") || name.eq_ignore_ascii_case("content-type") {
continue;
}
let Ok(name) = name.parse::<http::header::HeaderName>() else {
continue;
};
let Ok(value) = http::header::HeaderValue::from_str(value) else {
continue;
};
map.insert(name, value);
}
}
pub(crate) fn deadline(context: &CallContext) -> Option<tokio::time::Instant> {
context.deadline().map(tokio::time::Instant::from_std)
}