diff --git a/Cargo.lock b/Cargo.lock index 83b8e638..bc605170 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2929,6 +2929,7 @@ dependencies = [ "tokio", "tower", "tower-http 0.7.0", + "tracing-subscriber", ] [[package]] diff --git a/objectstore-server/Cargo.toml b/objectstore-server/Cargo.toml index 6d7e7bf4..ee1cc168 100644 --- a/objectstore-server/Cargo.toml +++ b/objectstore-server/Cargo.toml @@ -63,9 +63,11 @@ profiling = ["dep:jemalloc_pprof", "tikv-jemallocator/profiling"] nix = { workspace = true, features = ["signal"] } objectstore-options = { workspace = true, features = ["testing"] } objectstore-test = { workspace = true } +sentry = { workspace = true, features = ["test"] } stresstest = { workspace = true } tempfile = { workspace = true } tokio = { workspace = true, features = ["test-util"] } +tracing-subscriber = { workspace = true } [[bin]] name = "objectstore" diff --git a/objectstore-server/src/web/app.rs b/objectstore-server/src/web/app.rs index 0bd7451d..5c8aebde 100644 --- a/objectstore-server/src/web/app.rs +++ b/objectstore-server/src/web/app.rs @@ -3,7 +3,7 @@ use std::net::SocketAddr; use anyhow::Result; use axum::ServiceExt; use axum::extract::Request; -use objectstore_log::Level; +use objectstore_log::{Level, tracing}; use sentry::integrations::tower::{NewSentryLayer, SentryHttpLayer}; use tokio::net::TcpListener; use tower::ServiceBuilder; @@ -46,7 +46,7 @@ impl App { .layer(m::set_server_header()) .layer( TraceLayer::new_for_http() - .make_span_with(m::make_http_span) + .make_span_with(tracing::Span::none()) .on_failure(DefaultOnFailure::new().level(Level::DEBUG)), ); @@ -93,3 +93,113 @@ impl App { Ok(()) } } + +#[cfg(test)] +mod tests { + use axum::body::{Body, to_bytes}; + use axum::http::StatusCode; + use objectstore_log::tracing; + use objectstore_service::backend::local_fs::FileSystemConfig; + use sentry::protocol::{Context, EnvelopeItem, TraceContext, Transaction}; + use tower::ServiceExt; + use tracing_subscriber::prelude::*; + + use super::*; + use crate::config::{AuthZ, Config, StorageConfig}; + use crate::state::Services; + + fn trace<'a>(transaction: &'a Transaction<'_>) -> &'a TraceContext { + let Some(Context::Trace(trace)) = transaction.contexts.get("trace") else { + panic!("transaction is missing its trace context"); + }; + trace + } + + #[test] + fn body_task_preserves_sentry_context() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let _subscriber = tracing_subscriber::registry() + .with( + sentry::integrations::tracing::layer() + .span_filter(|metadata| *metadata.level() != tracing::Level::TRACE), + ) + .set_default(); + let trace_id = "11111111111111111111111111111111"; + let caller_span = "aaaaaaaaaaaaaaaa"; + let envelopes = sentry::test::with_captured_envelopes_options( + || { + runtime.block_on(async { + let directory = tempfile::tempdir().unwrap(); + let state = Services::spawn(Config { + storage: StorageConfig::FileSystem(FileSystemConfig { + path: directory.path().into(), + cogs: None, + }), + auth: AuthZ { + enforce: false, + ..Default::default() + }, + ..Default::default() + }) + .await + .unwrap(); + let request = Request::builder() + .method("POST") + .uri("/v1/objects:batch/test/org=1/") + .header("sentry-trace", format!("{trace_id}-{caller_span}-1")) + .header("content-type", "multipart/form-data; boundary=boundary") + .body(Body::from(concat!( + "--boundary\r\n", + "x-sn-batch-operation-key: missing\r\n", + "x-sn-batch-operation-kind: head\r\n", + "\r\n\r\n--boundary--\r\n", + ))) + .unwrap(); + let response = App::new(state).router.oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + // Polling the batch body starts the task after the HTTP transaction ends. + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + assert!(String::from_utf8_lossy(&body).contains("404 Not Found")); + }) + }, + sentry::ClientOptions { + traces_sample_rate: 1.0, + ..Default::default() + }, + ); + let transactions: Vec<_> = envelopes + .iter() + .flat_map(|envelope| envelope.items()) + .filter_map(|item| match item { + EnvelopeItem::Transaction(transaction) => Some(transaction), + _ => None, + }) + .collect(); + let [http, task] = transactions.as_slice() else { + panic!("expected exactly one HTTP and one task transaction"); + }; + assert_eq!(trace(http).op.as_deref(), Some("http.server")); + assert_eq!(trace(task).op.as_deref(), Some("tokio.task")); + assert_eq!(task.name.as_deref(), Some("head")); + assert_eq!(trace(http).parent_span_id.unwrap().to_string(), caller_span); + assert_eq!( + trace(task).parent_span_id, + Some(trace(http).span_id), + "task parent must be the emitted HTTP span" + ); + for transaction in transactions { + assert_eq!(trace(transaction).trace_id.to_string(), trace_id); + assert_eq!( + transaction.tags.get("usecase").map(String::as_str), + Some("test") + ); + assert_eq!( + transaction.tags.get("scope.org").map(String::as_str), + Some("1") + ); + } + } +} diff --git a/objectstore-server/src/web/middleware.rs b/objectstore-server/src/web/middleware.rs index e85a886a..8390a3b4 100644 --- a/objectstore-server/src/web/middleware.rs +++ b/objectstore-server/src/web/middleware.rs @@ -1,13 +1,11 @@ use std::any::Any; -use std::net::SocketAddr; use axum::RequestExt; use axum::body::Body; -use axum::extract::{ConnectInfo, MatchedPath, RawPathParams, Request, State}; +use axum::extract::{MatchedPath, RawPathParams, Request, State}; use axum::http::{HeaderValue, StatusCode, header}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; -use objectstore_log::tracing; use tower_http::set_header::SetResponseHeaderLayer; use crate::endpoints; @@ -54,25 +52,6 @@ pub fn set_server_header() -> SetResponseHeaderLayer { SetResponseHeaderLayer::overriding(header::SERVER, HeaderValue::from_static(SERVER)) } -/// Create a tracing span for an HTTP request. -/// -/// As opposed to `DefaultMakeSpan`, this also records the client IP address if available. -pub fn make_http_span(request: &Request) -> tracing::Span { - let span = tracing::debug_span!( - "request", - method = %request.method(), - uri = %request.uri(), - version = ?request.version(), - client_addr = tracing::field::Empty, - ); - - if let Some(ConnectInfo(addr)) = request.extensions().get::>() { - span.record("client_addr", tracing::field::display(addr.ip())); - } - - span -} - /// A panic handler that logs the panic and turns it into a 500 response. /// /// Use with the [`CatchPanicLayer`](tower_http::catch_panic::CatchPanicLayer) middleware. @@ -91,7 +70,7 @@ pub fn handle_panic(err: Box) -> Response { response.into_response() } -/// Wraps the response body so the request's Sentry hub stays active during polling. +/// Wraps the response body with a fork of the request's Sentry hub for polling. /// /// Use this with [`from_fn`](axum::middleware::from_fn). Place it below the Sentry /// tower layers so that `Hub::current()` returns the request-scoped hub. @@ -99,7 +78,7 @@ pub async fn bind_sentry_body(request: Request, next: Next) -> Response { let hub = sentry::Hub::current(); next.run(request) .await - .map(|body| Body::new(SentryBody::new(hub, body))) + .map(|body| Body::new(SentryBody::new(sentry::Hub::new_from_top(hub).into(), body))) } async fn get_usecase(request: &mut Request) -> Option {