use std::net::SocketAddr;
use std::sync::Arc;
use std::time::SystemTime;
use axum::extract::ConnectInfo;
use redup_bootstrap_grpc::diagnostics::{
BODY_LIMIT, DumpRecord, DumpRegistry, ExceptionInfo, PackedBody, code_name, unpack_body,
};
use tonic::Status;
use crate::grpc_server::capture::Capture;
pub(crate) struct DumpCapture {
pub(crate) registry: Arc<DumpRegistry>,
pub(crate) method: String,
pub(crate) remote: String,
pub(crate) started_at: SystemTime,
pub(crate) input_type: Option<String>,
pub(crate) output_type: Option<String>,
pub(crate) request: Option<Arc<Capture>>,
pub(crate) response: Option<Arc<Capture>>,
pub(crate) request_encoding: Option<String>,
pub(crate) response_encoding: Option<String>,
}
impl DumpCapture {
pub(crate) fn response_capture(&self) -> Option<&Arc<Capture>> {
self.response.as_ref()
}
pub(crate) fn record(self, failure: Option<&Status>) -> DumpRecord {
let end_date = SystemTime::now();
let exception = failure.map(exception_info);
let request = match &exception {
Some(_) => None,
None => self.packed(
self.request.as_ref(),
self.input_type.as_deref(),
self.request_encoding.as_deref(),
),
};
let response = match &exception {
Some(_) => None,
None => self.packed(
self.response.as_ref(),
self.output_type.as_deref(),
self.response_encoding.as_deref(),
),
};
let record = DumpRecord {
method: self.method,
remote_address: self.remote,
request,
start_date: self.started_at,
response,
end_date,
exception,
};
self.registry.record(&record);
record
}
fn packed(
&self,
capture: Option<&Arc<Capture>>,
message_type: Option<&str>,
encoding: Option<&str>,
) -> Option<PackedBody> {
let frames = capture?.take()?;
let body = unpack_body(&frames, encoding)?;
Some(PackedBody {
r#type: message_type.unwrap_or_default().to_owned(),
body,
})
}
}
fn exception_info(status: &Status) -> ExceptionInfo {
let parsed = redup_bootstrap_grpc::details(status);
let internal = parsed.domain.is_none();
let r#type = parsed
.reason
.as_deref()
.filter(|reason| !reason.is_empty())
.map_or_else(|| code_name(status.code()).to_owned(), str::to_owned);
ExceptionInfo {
r#type,
message: status.message().to_owned(),
stack_trace: parsed.debug,
internal,
}
}
pub(crate) const CAPTURE_LIMIT: usize = BODY_LIMIT;
pub(crate) fn peer(request: &http::Request<axum::body::Body>) -> String {
match request.extensions().get::<ConnectInfo<SocketAddr>>() {
Some(ConnectInfo(address)) => {
let family = if address.is_ipv4() { "ipv4" } else { "ipv6" };
format!("{family}:{address}")
}
None => String::new(),
}
}