Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions objectstore-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
114 changes: 112 additions & 2 deletions objectstore-server/src/web/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)),
);

Expand Down Expand Up @@ -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() {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test is pretty verbose and detailed in what it asserts but I think it's good to have to pin and document the effect of this change.

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")
);
}
}
}
27 changes: 3 additions & 24 deletions objectstore-server/src/web/middleware.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -54,25 +52,6 @@ pub fn set_server_header() -> SetResponseHeaderLayer<HeaderValue> {
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::<ConnectInfo<SocketAddr>>() {
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.
Expand All @@ -91,15 +70,15 @@ pub fn handle_panic(err: Box<dyn Any + Send + 'static>) -> 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.
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<String> {
Expand Down
Loading