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
4 changes: 3 additions & 1 deletion crates/ourios-ingester/src/receiver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,7 @@ pub use commit::CommitCoordinator;
pub use decode::{DecodeError, decode_json, decode_protobuf};
pub use materialize::{materialize_record, materialize_resource_logs};
pub use pipeline::{IngestPipeline, Journal, ReceiveError, SharedPipeline};
pub use propagation::{HeaderExtractor, extract_context};
pub use propagation::{
HeaderExtractor, MetadataExtractor, extract_context, extract_context_from_metadata,
};
pub use tenant::{TenantResolutionError, TenantRule, fan_out};
12 changes: 11 additions & 1 deletion crates/ourios-ingester/src/receiver/grpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@ use opentelemetry_proto::tonic::collector::logs::v1::{
};
use tonic::{Request, Response, Status};

use opentelemetry::context::FutureExt as _;

use crate::receiver::auth::{AuthBinding, AuthResolver};
use crate::receiver::pipeline::{ReceiveError, SharedPipeline};
use crate::receiver::propagation::extract_context_from_metadata;

/// The authentication gate for the gRPC listener (RFC 0026 §3.2 /
/// RFC 0029 §3.3), applied as a tower layer on the tonic server. A tower
Expand Down Expand Up @@ -153,6 +156,12 @@ impl LogsService for LogsReceiver {
&self,
request: Request<ExportLogsServiceRequest>,
) -> Result<Response<ExportLogsServiceResponse>, Status> {
// RFC 0039 §3.3: the `ingest logs` span is born inside `ingest_bound`,
// past the `tokio::spawn` below — which ambient context does not cross.
// So the caller's context is extracted here, while the request (and its
// metadata) is still in hand, and re-attached inside the task where the
// span is actually created.
let parent = extract_context_from_metadata(request.metadata());
// The [`AuthInterceptor`]'s binding, when auth is enabled — the
// pipeline enforces the §3.2 tenant binding against it.
let binding = request.extensions().get::<AuthBinding>().cloned();
Expand All @@ -165,7 +174,8 @@ impl LogsService for LogsReceiver {
// so this is `spawn`, not `spawn_blocking`.
let pipeline = self.pipeline.clone();
match tokio::spawn(
async move { pipeline.ingest_bound(export, binding.as_ref(), false).await },
async move { pipeline.ingest_bound(export, binding.as_ref(), false).await }
.with_context(parent),
)
.await
{
Expand Down
20 changes: 15 additions & 5 deletions crates/ourios-ingester/src/receiver/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,12 @@ use axum::routing::post;
use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceResponse;
use prost::Message;

use opentelemetry::context::FutureExt as _;

use crate::receiver::auth::AuthResolver;
use crate::receiver::decode::{decode_json, decode_protobuf};
use crate::receiver::pipeline::{ReceiveError, SharedPipeline};
use crate::receiver::propagation::extract_context;

/// OTLP/HTTP listener configuration.
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -142,12 +145,19 @@ async fn handle_logs(State(state): State<AppState>, headers: HeaderMap, body: By
// handler just awaits. Run it on its own task so a panic in the
// pipeline/miner is contained as a 500 (the handler promises not to
// panic) rather than aborting the connection.
// RFC 0039 §3.3: as on the gRPC arm, the `ingest logs` span is created
// inside `ingest_bound` past this spawn, so the caller's context is
// extracted from the request headers here and re-attached inside the task.
let parent = extract_context(&headers);
let pipeline = state.pipeline.clone();
match tokio::spawn(async move {
pipeline
.ingest_bound(request, binding.as_ref(), lenient_json)
.await
})
match tokio::spawn(
async move {
pipeline
.ingest_bound(request, binding.as_ref(), lenient_json)
.await
}
.with_context(parent),
)
.await
{
Ok(Ok(_)) => success_response(format),
Expand Down
120 changes: 115 additions & 5 deletions crates/ourios-ingester/src/receiver/propagation.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
//! Inbound W3C trace-context extraction (RFC 0039).
//!
//! Every Ourios ingress — OTLP gRPC/HTTP, the query API, the MCP tools —
//! receives its caller's trace context as HTTP headers, so one
//! [`HeaderExtractor`] over [`http::HeaderMap`] serves all of them (the gRPC
//! path extracts from the raw HTTP headers at its tower layer, so no tonic
//! `MetadataMap` adapter is needed).
//! Every Ourios ingress receives its caller's trace context as HTTP headers, so
//! [`HeaderExtractor`] over [`http::HeaderMap`] serves the axum-side ingresses
//! (OTLP/HTTP, the query API, the MCP tools). gRPC metadata *is* HTTP/2 headers,
//! but tonic models it as `HeaderMap<MetadataValue>` rather than
//! `http::HeaderMap`, so the OTLP/gRPC ingress needs its own carrier adapter:
//! [`MetadataExtractor`]. Extraction happens in the handler that receives the
//! call, which is where OpenTelemetry puts it — "if you work on a library or a
//! service that receives upstream calls, extract context from the incoming
//! request", the one context on the wire becoming the parent of the span the
//! receiver creates (cf. the `OTel` Demo's `C++` `GrpcServerCarrier` over
//! `client_metadata()`).
//!
//! [`extract_context`] resolves the context through the globally installed
//! propagator (`ourios-telemetry` installs `TraceContextPropagator` in `init`).
Expand All @@ -17,6 +23,7 @@
use axum::http::HeaderMap;
use opentelemetry::Context;
use opentelemetry::propagation::Extractor;
use tonic::metadata::{KeyRef, MetadataMap};

/// Reads W3C trace-context headers out of an [`http::HeaderMap`].
pub struct HeaderExtractor<'a>(pub &'a HeaderMap);
Expand All @@ -42,6 +49,37 @@ pub fn extract_context(headers: &HeaderMap) -> Context {
})
}

/// Reads W3C trace-context entries out of tonic gRPC [`MetadataMap`].
pub struct MetadataExtractor<'a>(pub &'a MetadataMap);

impl Extractor for MetadataExtractor<'_> {
fn get(&self, key: &str) -> Option<&str> {
self.0.get(key).and_then(|value| value.to_str().ok())
}

fn keys(&self) -> Vec<&str> {
// Binary (`-bin`) metadata cannot hold a text-map entry, so those keys
// are not carrier candidates — only the ascii half is offered.
self.0
.keys()
.filter_map(|key| match key {
KeyRef::Ascii(key) => Some(key.as_str()),
KeyRef::Binary(_) => None,
})
.collect()
}
}

/// The caller's trace context from gRPC `metadata` — the [`extract_context`]
/// counterpart for the OTLP/gRPC ingress, with identical absent/malformed
/// behaviour (RFC0039.2 / RFC0039.5).
#[must_use]
pub fn extract_context_from_metadata(metadata: &MetadataMap) -> Context {
opentelemetry::global::get_text_map_propagator(|propagator| {
propagator.extract(&MetadataExtractor(metadata))
})
}

#[cfg(test)]
mod tests {
use opentelemetry::trace::TraceContextExt as _;
Expand Down Expand Up @@ -76,6 +114,56 @@ mod tests {
assert!(sc.is_remote(), "an extracted context is remote");
}

/// The gRPC carrier reaches the same remote `SpanContext` as the HTTP one:
/// a `traceparent` in tonic metadata extracts identically (RFC0039.1, gRPC
/// arm). Guards the `MetadataExtractor` adapter, which is the only reason
/// the gRPC ingress is not simply reusing `HeaderExtractor`.
#[test]
fn traceparent_in_grpc_metadata_round_trips_identically() {
use opentelemetry::propagation::TextMapPropagator as _;
use opentelemetry_sdk::propagation::TraceContextPropagator;
use tonic::metadata::MetadataMap;

let mut metadata = MetadataMap::new();
metadata.insert(
"traceparent",
"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
.parse()
.expect("valid metadata value"),
);
let cx = TraceContextPropagator::new().extract(&super::MetadataExtractor(&metadata));
let sc = cx.span().span_context().clone();
assert_eq!(
sc.trace_id().to_string(),
"4bf92f3577b34da6a3ce929d0e0e4736"
);
assert_eq!(sc.span_id().to_string(), "00f067aa0ba902b7");
assert!(sc.is_remote(), "an extracted context is remote");
}

/// A binary (`-bin`) metadata key cannot carry a text-map entry, so it must
/// not be offered as a carrier key — `keys()` returning it would hand the
/// propagator a key whose `get` can never resolve.
#[test]
fn binary_metadata_keys_are_not_offered_as_carrier_keys() {
use opentelemetry::propagation::Extractor as _;
use tonic::metadata::{MetadataMap, MetadataValue};

let mut metadata = MetadataMap::new();
metadata.insert("traceparent", "00-a-b-01".parse().expect("valid value"));
metadata.insert_bin(
"trace-proto-bin",
MetadataValue::from_bytes(b"\x00\x01\x02"),
);
let extractor = super::MetadataExtractor(&metadata);
let keys = extractor.keys();
assert!(keys.contains(&"traceparent"), "ascii keys are offered");
assert!(
!keys.iter().any(|key| key.ends_with("-bin")),
"binary keys are withheld, got {keys:?}",
);
}
Comment thread
jensholdgaard marked this conversation as resolved.
Resolved

/// No `traceparent` yields no remote span, so the span run under it roots
/// itself (RFC0039.2). Goes through the global propagator, which is a no-op
/// propagator unless something installed one — either way the result must
Expand Down Expand Up @@ -106,4 +194,26 @@ mod tests {
);
}
}

/// The gRPC carrier rejects a malformed `traceparent` the same way the
/// `HeaderMap` one does (RFC0039.5, gRPC arm). Worth asserting separately:
/// the two carriers reach the propagator through different `Extractor`
/// impls, so a carrier-specific parsing difference would otherwise let a
/// bogus parent through on one transport only.
#[test]
fn malformed_traceparent_in_grpc_metadata_is_treated_as_absent() {
use opentelemetry::propagation::TextMapPropagator as _;
use opentelemetry_sdk::propagation::TraceContextPropagator;
use tonic::metadata::MetadataMap;

for bad in ["not-a-traceparent", "00-tooshort-00f067aa0ba902b7-01", ""] {
let mut metadata = MetadataMap::new();
metadata.insert("traceparent", bad.parse().expect("valid metadata value"));
let cx = TraceContextPropagator::new().extract(&super::MetadataExtractor(&metadata));
assert!(
!cx.span().span_context().is_valid(),
"malformed traceparent {bad:?} must not yield a parent over gRPC",
);
}
}
}
5 changes: 5 additions & 0 deletions crates/ourios-ingester/tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ one-per-binary:
a global (not scoped) tracer is required to capture the `ingest logs` /
`sweep partitions` spans across the receiver's `tokio::spawn` and the
compactor's `spawn_blocking` (RFC0038.3).
- `rfc0039_3_ingest_propagation.rs` — the same global **tracer** need, for the
inbound-`traceparent` half: that the batch span joins the *caller's* trace
across that spawn, on both OTLP transports (RFC0039.3). Separate from
`rfc0038_3` because a process holds one tracer install and that file owns
the no-inbound-context (root) case.

`fixtures/` holds the crash-fixture **`[[bin]]` targets** (SIGKILL'd by
harness tests via `CARGO_BIN_EXE_*`), not test binaries.
146 changes: 146 additions & 0 deletions crates/ourios-ingester/tests/rfc0039_3_ingest_propagation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
//! RFC0039.3 — the caller's trace context survives the ingest `tokio::spawn`.
//!
//! Harness-exempt (RFC0028.2, see `tests/README.md`): installs the
//! **process-global** `OTel` tracer, which cannot share a process with the
//! consolidated `it` harness or another global installer.
//!
//! The `ingest logs` span is created inside `ingest_bound`, *after* the
//! receivers' `tokio::spawn` — a boundary ambient context does not cross. Both
//! handlers therefore extract the caller's context while the request is still in
//! hand and re-attach it inside the spawned task (RFC 0039 §3.3). What follows
//! asserts the observable consequence for both OTLP transports: the batch span,
//! and the `commit wal` child minted under it, land in the *caller's* trace
//! rather than a fresh one.
//!
//! The two arms carry **different** traces so a single exporter can hold both
//! and each span still be attributed unambiguously.
//! `rfc0038_3_spawn_boundary.rs` covers this same boundary with no inbound
//! context (the root case, RFC0039.2) and is deliberately left untouched.

#[path = "it/ingest_support/mod.rs"]
mod ingest_support;

use axum::body::Body;
use axum::http::{Request, header};
use ingest_support::{request, resource_logs, shared_wal_pipeline};
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_proto::tonic::collector::logs::v1::logs_service_server::LogsService as _;
use opentelemetry_sdk::propagation::TraceContextPropagator;
use opentelemetry_sdk::trace::{InMemorySpanExporter, SdkTracerProvider, SpanData};
use ourios_ingester::receiver::grpc::LogsReceiver;
use ourios_ingester::receiver::http::{HttpConfig, router};
use prost::Message as _;
use tower::ServiceExt as _;
use tracing_subscriber::prelude::*;

/// The trace the gRPC caller claims to be inside.
const GRPC_TRACE: &str = "4bf92f3577b34da6a3ce929d0e0e4736";
const GRPC_SPAN: &str = "00f067aa0ba902b7";
/// …and the HTTP caller's, distinct from it.
const HTTP_TRACE: &str = "0af7651916cd43dd8448eb211c80319c";
const HTTP_SPAN: &str = "b7ad6b7169203331";

fn traceparent(trace: &str, span: &str) -> String {
format!("00-{trace}-{span}-01")
}

/// The spans named `name` that resolved into trace `trace`.
fn spans_in_trace<'a>(spans: &'a [SpanData], trace: &str, name: &str) -> Vec<&'a SpanData> {
spans
.iter()
.filter(|s| s.name.as_ref() == name && s.span_context.trace_id().to_string() == trace)
.collect()
}

/// Assert that one `ingest logs` span joined `trace` as a child of `parent_span`,
/// and that its `commit wal` child nests under it inside that same trace.
fn assert_batch_joined_caller_trace(spans: &[SpanData], trace: &str, parent_span: &str, arm: &str) {
let batch = spans_in_trace(spans, trace, "ingest logs");
assert_eq!(
batch.len(),
1,
"{arm}: exactly one `ingest logs` span in the caller's trace, got {:?}",
spans
.iter()
.map(|s| (s.name.clone(), s.span_context.trace_id().to_string()))
.collect::<Vec<_>>(),
);
assert_eq!(
batch[0].parent_span_id.to_string(),
parent_span,
"{arm}: the batch span is parented to the caller's span across the spawn",
);

let commit = spans_in_trace(spans, trace, "commit wal");
assert_eq!(
commit.len(),
1,
"{arm}: exactly one `commit wal` span in the caller's trace",
);
assert_eq!(
commit[0].parent_span_id,
batch[0].span_context.span_id(),
"{arm}: `commit wal` still nests under `ingest logs` once the batch span has a remote parent",
);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn rfc0039_3_extracted_context_survives_the_ingest_spawn() {
// The global tracer, as in `rfc0038_3_spawn_boundary.rs`: only the global
// default reaches a span opened inside a spawned task. The global
// *propagator* is what the handlers' extraction resolves through — in
// production `ourios_telemetry::init` installs it (RFC 0039 §3.1).
let exporter = InMemorySpanExporter::default();
let provider = SdkTracerProvider::builder()
.with_simple_exporter(exporter.clone())
.build();
tracing_subscriber::registry()
.with(tracing_opentelemetry::layer().with_tracer(provider.tracer("ourios-test")))
.try_init()
.expect("install global subscriber");
opentelemetry::global::set_tracer_provider(provider.clone());
opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());

// --- Arm A: OTLP/gRPC. The spawn is inside `export`, which awaits it, so
// the batch span is finished by the time this returns. ---
let grpc_tmp = tempfile::tempdir().expect("temp");
let receiver = LogsReceiver::new(shared_wal_pipeline(grpc_tmp.path()));
let mut grpc_request =
tonic::Request::new(request(vec![resource_logs("checkout", &["alpha", "beta"])]));
grpc_request.metadata_mut().insert(
"traceparent",
traceparent(GRPC_TRACE, GRPC_SPAN)
.parse()
.expect("valid metadata value"),
);
receiver.export(grpc_request).await.expect("export acks");

// --- Arm B: OTLP/HTTP, driven in-process through the real router. ---
let http_tmp = tempfile::tempdir().expect("temp");
let config = HttpConfig::default();
let app = router(shared_wal_pipeline(http_tmp.path()), &config);
let body = request(vec![resource_logs("payments", &["gamma"])]).encode_to_vec();
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri(&config.path)
.header(header::CONTENT_TYPE, "application/x-protobuf")
.header("traceparent", traceparent(HTTP_TRACE, HTTP_SPAN))
.body(Body::from(body))
.expect("build request"),
)
.await
.expect("oneshot");
assert!(
response.status().is_success(),
"the HTTP export should be acked, got {}",
response.status(),
);

provider.force_flush().expect("spans flush");
let spans = exporter.get_finished_spans().expect("spans exported");

assert_batch_joined_caller_trace(&spans, GRPC_TRACE, GRPC_SPAN, "gRPC");
assert_batch_joined_caller_trace(&spans, HTTP_TRACE, HTTP_SPAN, "HTTP");
}
Loading