Skip to main content

micromegas/servers/
otlp.rs

1//! OTLP/HTTP route registration for `telemetry-ingestion-srv`.
2//!
3//! Exposes three routes that match the OTLP/HTTP spec:
4//!  - `POST /ingestion/otlp/v1/logs`
5//!  - `POST /ingestion/otlp/v1/metrics`
6//!  - `POST /ingestion/otlp/v1/traces`
7//!
8//! The OTLP sub-router applies its own 20 MiB body limit (matching the OTel Collector
9//! `confighttp.max_request_body_size` default) plus gzip request decompression,
10//! independent of the parent router's 100 MiB limit on `/ingestion/insert_block`.
11//!
12//! Per OTLP/HTTP spec, success responses mirror the request encoding (JSON in → JSON out,
13//! proto in → proto out). Error responses (4xx/5xx) carry a `google.rpc.Status` body
14//! encoded in the same way, except 415 responses which always use protobuf because the
15//! request encoding is unknown at that point.
16
17use super::ingestion_limits::{RETRY_AFTER_SECONDS, apply_ingestion_body_limits};
18use super::write_audience::resolve_write_audience;
19use axum::Extension;
20use axum::Router;
21use axum::body::Body;
22use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
23use axum::response::Response;
24use axum::routing::post;
25use micromegas_auth::types::AuthContext;
26use micromegas_ingestion::web_ingestion_service::WebIngestionService;
27use micromegas_otel_ingestion::Encoding;
28use micromegas_otel_ingestion::error::OtelError;
29use micromegas_otel_ingestion::handler;
30use micromegas_tracing::prelude::*;
31use prost::Message;
32use std::sync::Arc;
33
34const OTLP_LOGS_PATH: &str = "/ingestion/otlp/v1/logs";
35const OTLP_METRICS_PATH: &str = "/ingestion/otlp/v1/metrics";
36const OTLP_TRACES_PATH: &str = "/ingestion/otlp/v1/traces";
37pub(crate) const OTLP_PATHS: [&str; 3] = [OTLP_LOGS_PATH, OTLP_METRICS_PATH, OTLP_TRACES_PATH];
38
39const CONTENT_TYPE_PROTOBUF: &str = "application/x-protobuf";
40const CONTENT_TYPE_JSON: &str = "application/json";
41
42/// Examines the `Content-Type` header and maps it to an `Encoding`. The spec allows
43/// parameters (e.g. `application/json; charset=utf-8`), so we parse rather than
44/// string-compare. Returns `Err(OtlpHttpError::WrongContentType)` for unknown types.
45pub(crate) fn content_type_encoding(headers: &HeaderMap) -> Result<Encoding, OtlpHttpError> {
46    let Some(ct) = headers.get(header::CONTENT_TYPE) else {
47        return Err(OtlpHttpError::WrongContentType);
48    };
49    let Ok(ct) = ct.to_str() else {
50        return Err(OtlpHttpError::WrongContentType);
51    };
52    let media = ct
53        .split(';')
54        .next()
55        .unwrap_or("")
56        .trim()
57        .to_ascii_lowercase();
58    match media.as_str() {
59        CONTENT_TYPE_PROTOBUF => Ok(Encoding::Protobuf),
60        CONTENT_TYPE_JSON => Ok(Encoding::Json),
61        _ => Err(OtlpHttpError::WrongContentType),
62    }
63}
64
65/// Internal error type covering both pre-handler validation failures (415) and
66/// post-handler `OtelError`s. Each variant maps to a single HTTP response shape
67/// (status code, optional `Retry-After`, `google.rpc.Status` body).
68pub(crate) enum OtlpHttpError {
69    WrongContentType,
70    Otel(OtelError),
71}
72
73impl OtlpHttpError {
74    fn into_otlp_response(self, encoding: Encoding) -> Response {
75        match self {
76            OtlpHttpError::WrongContentType => build_error_response(
77                StatusCode::UNSUPPORTED_MEDIA_TYPE,
78                3, // INVALID_ARGUMENT
79                "Content-Type must be application/x-protobuf or application/json",
80                false,
81                // encoding is unknown for 415; always emit proto Status (OTLP/HTTP default)
82                Encoding::Protobuf,
83            ),
84            OtlpHttpError::Otel(err) => {
85                let retryable = err.is_retryable();
86                let status = match err.http_status() {
87                    400 => StatusCode::BAD_REQUEST,
88                    503 => StatusCode::SERVICE_UNAVAILABLE,
89                    other => {
90                        StatusCode::from_u16(other).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
91                    }
92                };
93                let code = err.grpc_code();
94                // Detailed error (includes raw sqlx / object-store messages) is
95                // logged server-side; only the sanitized public form goes to the
96                // client to avoid leaking backend internals.
97                error!("OTLP error: {}", err);
98                build_error_response(status, code, &err.public_message(), retryable, encoding)
99            }
100        }
101    }
102}
103
104fn build_error_response(
105    status: StatusCode,
106    code: i32,
107    message: &str,
108    retryable: bool,
109    encoding: Encoding,
110) -> Response {
111    let proto_status = micromegas_otel_ingestion::proto::Status {
112        code,
113        message: message.to_string(),
114    };
115    let (body, content_type) = match encoding {
116        Encoding::Protobuf => (proto_status.encode_to_vec(), CONTENT_TYPE_PROTOBUF),
117        Encoding::Json => (
118            serde_json::to_vec(&proto_status).expect("serializing Status to JSON"),
119            CONTENT_TYPE_JSON,
120        ),
121    };
122    let mut response = Response::builder()
123        .status(status)
124        .header(header::CONTENT_TYPE, HeaderValue::from_static(content_type))
125        .body(Body::from(body))
126        .expect("building OTLP error response");
127    if retryable && let Ok(value) = HeaderValue::from_str(&RETRY_AFTER_SECONDS.to_string()) {
128        response.headers_mut().insert(header::RETRY_AFTER, value);
129    }
130    response
131}
132
133fn success_response<M: Message + serde::Serialize>(msg: M, encoding: Encoding) -> Response {
134    let (body, content_type) = match encoding {
135        Encoding::Protobuf => (msg.encode_to_vec(), CONTENT_TYPE_PROTOBUF),
136        Encoding::Json => (
137            serde_json::to_vec(&msg).expect("serializing OTLP response to JSON"),
138            CONTENT_TYPE_JSON,
139        ),
140    };
141    Response::builder()
142        .status(StatusCode::OK)
143        .header(header::CONTENT_TYPE, HeaderValue::from_static(content_type))
144        .body(Body::from(body))
145        .expect("building OTLP success response")
146}
147
148async fn logs_handler(
149    Extension(service): Extension<Arc<WebIngestionService>>,
150    ctx: Option<Extension<AuthContext>>,
151    headers: HeaderMap,
152    body: bytes::Bytes,
153) -> Response {
154    let encoding = match content_type_encoding(&headers) {
155        Ok(enc) => enc,
156        Err(e) => return e.into_otlp_response(Encoding::Protobuf),
157    };
158    let audience = resolve_write_audience(ctx.as_ref(), service.default_audience());
159    match handler::ingest_logs(service, body, encoding, &audience).await {
160        Ok(resp) => success_response(resp, encoding),
161        Err(e) => OtlpHttpError::Otel(e).into_otlp_response(encoding),
162    }
163}
164
165async fn metrics_handler(
166    Extension(service): Extension<Arc<WebIngestionService>>,
167    ctx: Option<Extension<AuthContext>>,
168    headers: HeaderMap,
169    body: bytes::Bytes,
170) -> Response {
171    let encoding = match content_type_encoding(&headers) {
172        Ok(enc) => enc,
173        Err(e) => return e.into_otlp_response(Encoding::Protobuf),
174    };
175    let audience = resolve_write_audience(ctx.as_ref(), service.default_audience());
176    match handler::ingest_metrics(service, body, encoding, &audience).await {
177        Ok(resp) => success_response(resp, encoding),
178        Err(e) => OtlpHttpError::Otel(e).into_otlp_response(encoding),
179    }
180}
181
182async fn traces_handler(
183    Extension(service): Extension<Arc<WebIngestionService>>,
184    ctx: Option<Extension<AuthContext>>,
185    headers: HeaderMap,
186    body: bytes::Bytes,
187) -> Response {
188    let encoding = match content_type_encoding(&headers) {
189        Ok(enc) => enc,
190        Err(e) => return e.into_otlp_response(Encoding::Protobuf),
191    };
192    let audience = resolve_write_audience(ctx.as_ref(), service.default_audience());
193    match handler::ingest_traces(service, body, encoding, &audience).await {
194        Ok(resp) => success_response(resp, encoding),
195        Err(e) => OtlpHttpError::Otel(e).into_otlp_response(encoding),
196    }
197}
198
199/// Builds a sub-Router carrying the three OTLP routes plus the shared body-limit and
200/// gzip-decompression layers scoped to those routes (see `ingestion_limits`).
201pub fn otlp_router() -> Router {
202    apply_ingestion_body_limits(
203        Router::new()
204            .route(OTLP_LOGS_PATH, post(logs_handler))
205            .route(OTLP_METRICS_PATH, post(metrics_handler))
206            .route(OTLP_TRACES_PATH, post(traces_handler)),
207    )
208}