Skip to main content

mira/
receiver.rs

1//! OTLP receivers.
2//!
3//! Two listeners, because OTLP is two protocols. 4317 is OTLP/gRPC and is served
4//! by tonic. 4318 is OTLP/HTTP — a plain HTTP/1.1 POST of protobuf to
5//! `/v1/{traces,metrics,logs}` — which tonic cannot serve; that one is axum,
6//! already in the tree via tonic's `router` feature, so it costs no dependency.
7
8use axum::Router;
9use axum::body::Bytes;
10use axum::http::{HeaderMap, StatusCode, header};
11use axum::response::{IntoResponse, Response};
12use axum::routing::post;
13use prost::Message;
14use tonic::codec::CompressionEncoding;
15use tonic::{Request, Status};
16use tonic_types::{ErrorDetails, StatusExt};
17
18use mira_proto::collector::logs::v1::logs_service_server::{LogsService, LogsServiceServer};
19use mira_proto::collector::logs::v1::{ExportLogsServiceRequest, ExportLogsServiceResponse};
20use mira_proto::collector::metrics::v1::metrics_service_server::{
21    MetricsService, MetricsServiceServer,
22};
23use mira_proto::collector::metrics::v1::{
24    ExportMetricsServiceRequest, ExportMetricsServiceResponse,
25};
26use mira_proto::collector::trace::v1::trace_service_server::{TraceService, TraceServiceServer};
27use mira_proto::collector::trace::v1::{ExportTraceServiceRequest, ExportTraceServiceResponse};
28
29use crate::pipeline::{Ingest, Rejected};
30
31/// One write handle per signal. The type parameter is what keeps a metrics
32/// request from being handed to the logs flusher; `Ingest` is generic precisely
33/// so that the mistake is a compile error rather than a corrupt block.
34#[derive(Clone)]
35pub struct Receivers {
36    pub logs: Ingest<ExportLogsServiceRequest>,
37    pub traces: Ingest<ExportTraceServiceRequest>,
38    pub metrics: Ingest<ExportMetricsServiceRequest>,
39    /// The largest export either listener will decode, in bytes.
40    ///
41    /// One number for both, because a batch that a collector sends happily over
42    /// 4317 and that fails over 4318 is the worst kind of bug to be handed: it
43    /// depends on a transport nobody changed. Applied three times — as the
44    /// axum body limit, as tonic's `max_decoding_message_size`, and as the
45    /// ceiling on what a gzip body may inflate to.
46    pub max_request_bytes: usize,
47}
48
49/// Map a rejection onto a gRPC status.
50///
51/// Overload is never a partial success: the OTLP spec says the client MUST NOT
52/// retry a partial success, so using it for backpressure destroys the data and
53/// records the failure as the sender's fault. It is always a status code, and
54/// always with `RetryInfo` attached — `grpc-retry-pushback-ms` alone is only
55/// honoured by clients that configured a gRPC retry policy, which OTLP
56/// exporters do not.
57///
58/// The retryable set is closed and `INTERNAL` is not in it, so it is reserved
59/// for the one refusal that really is permanent. A write that failed on a full
60/// disk answered `INTERNAL` would have the exporter drop the batch it is holding
61/// rather than send it again a second later, which is data loss chosen by a
62/// status code.
63fn status_for(r: Rejected) -> Status {
64    // 250ms for the queue, which drains in one block age; a second for a failed
65    // write, which is usually a disk needing longer than that anyway.
66    let retry = |ms| ErrorDetails::with_retry_info(Some(std::time::Duration::from_millis(ms)));
67    match r {
68        Rejected::Busy => {
69            Status::with_error_details(tonic::Code::Unavailable, "ingest queue full", retry(250))
70        }
71        Rejected::Closed => Status::unavailable("shutting down"),
72        Rejected::Unavailable(e) => {
73            Status::with_error_details(tonic::Code::Unavailable, e, retry(1_000))
74        }
75        Rejected::Failed(e) => Status::internal(e),
76    }
77}
78
79/// `accept_compressed` on every service, because the spec says MUST and the
80/// stock exporter says default.
81///
82/// Without it tonic answers a compressed request with `UNIMPLEMENTED`, and
83/// OTLP calls that a permanent failure: the exporter drops the batch instead of
84/// retrying it. `send_compressed` is deliberately absent — the response is an
85/// empty message, and gzipping nothing costs a round of deflate per export.
86///
87/// `max_decoding_message_size` is set from the same field the HTTP listener
88/// uses; tonic's own default is 4 MiB and axum's is 2 MiB, and leaving the two
89/// listeners disagreeing means a batch size that works on one port and fails
90/// on the other.
91impl Receivers {
92    pub fn logs_server(&self) -> LogsServiceServer<Self> {
93        LogsServiceServer::new(self.clone())
94            .accept_compressed(CompressionEncoding::Gzip)
95            .max_decoding_message_size(self.max_request_bytes)
96    }
97    pub fn traces_server(&self) -> TraceServiceServer<Self> {
98        TraceServiceServer::new(self.clone())
99            .accept_compressed(CompressionEncoding::Gzip)
100            .max_decoding_message_size(self.max_request_bytes)
101    }
102    pub fn metrics_server(&self) -> MetricsServiceServer<Self> {
103        MetricsServiceServer::new(self.clone())
104            .accept_compressed(CompressionEncoding::Gzip)
105            .max_decoding_message_size(self.max_request_bytes)
106    }
107}
108
109#[tonic::async_trait]
110impl LogsService for Receivers {
111    async fn export(
112        &self,
113        request: Request<ExportLogsServiceRequest>,
114    ) -> Result<tonic::Response<ExportLogsServiceResponse>, Status> {
115        self.logs
116            .submit(request.into_inner())
117            .await
118            .map_err(status_for)?;
119        // No partial_success: everything we accepted is durable by now, and
120        // anything we could not accept was reported as a status above.
121        Ok(tonic::Response::new(ExportLogsServiceResponse::default()))
122    }
123}
124
125#[tonic::async_trait]
126impl TraceService for Receivers {
127    async fn export(
128        &self,
129        request: Request<ExportTraceServiceRequest>,
130    ) -> Result<tonic::Response<ExportTraceServiceResponse>, Status> {
131        self.traces
132            .submit(request.into_inner())
133            .await
134            .map_err(status_for)?;
135        Ok(tonic::Response::new(ExportTraceServiceResponse::default()))
136    }
137}
138
139#[tonic::async_trait]
140impl MetricsService for Receivers {
141    async fn export(
142        &self,
143        request: Request<ExportMetricsServiceRequest>,
144    ) -> Result<tonic::Response<ExportMetricsServiceResponse>, Status> {
145        self.metrics
146            .submit(request.into_inner())
147            .await
148            .map_err(status_for)?;
149        Ok(tonic::Response::new(ExportMetricsServiceResponse::default()))
150    }
151}
152
153/// OTLP/HTTP on 4318.
154pub fn http_router(r: Receivers) -> Router {
155    // Each route is the same three lines with a different field and response
156    // type; a macro says that once instead of three times.
157    macro_rules! signal {
158        ($field:ident, $resp:ty, $json:path) => {
159            post(
160                |axum::extract::State(r): axum::extract::State<Receivers>,
161                 h: HeaderMap,
162                 b: Bytes| async move {
163                    let max = r.max_request_bytes;
164                    export(&r.$field, &h, b, max, <$resp>::default(), $json).await
165                },
166            )
167        };
168    }
169    let max = r.max_request_bytes;
170    Router::new()
171        // OTLP/HTTP log export. Protobuf or JSON, gzip either way.
172        .route(
173            "/v1/logs",
174            signal!(logs, ExportLogsServiceResponse, crate::json::logs),
175        )
176        // OTLP/HTTP trace export. Protobuf or JSON, gzip either way.
177        .route(
178            "/v1/traces",
179            signal!(traces, ExportTraceServiceResponse, crate::json::traces),
180        )
181        // OTLP/HTTP metric export. Protobuf or JSON, gzip either way.
182        .route(
183            "/v1/metrics",
184            signal!(metrics, ExportMetricsServiceResponse, crate::json::metrics),
185        )
186        // Explicit, because axum's default is 2 MiB and that is below what a
187        // stock collector's batch processor produces at its own default of
188        // 8192 records. The exporter treats 413 as permanent and drops the
189        // batch, so a limit set too low is data loss rather than a slow start.
190        .layer(axum::extract::DefaultBodyLimit::max(max))
191        .with_state(r)
192}
193
194/// Which body encoding the client sent.
195///
196/// OTLP/HTTP names exactly two, and a request that claims a third has to be
197/// refused rather than guessed at: `415` tells the exporter to stop, where
198/// mis-decoding it as protobuf produces a `400` that reads like corrupt data.
199/// A missing `content-type` is treated as protobuf, which is what every
200/// pre-JSON client that omitted it meant.
201enum Encoding {
202    Protobuf,
203    Json,
204}
205
206fn encoding(h: &HeaderMap) -> Option<Encoding> {
207    let Some(ct) = h.get(header::CONTENT_TYPE) else {
208        return Some(Encoding::Protobuf);
209    };
210    // Compare the media type only; charset and boundary parameters are the
211    // client's business.
212    let ct = ct.to_str().unwrap_or_default();
213    match ct.split(';').next().unwrap_or_default().trim() {
214        "application/x-protobuf" | "application/protobuf" | "" => Some(Encoding::Protobuf),
215        "application/json" => Some(Encoding::Json),
216        _ => None,
217    }
218}
219
220/// Undo `Content-Encoding` before anything tries to parse the body.
221///
222/// Returning the body untouched for a missing or `identity` header is the
223/// common path. An encoding we do not implement is `415`, not a decode failure:
224/// the exporter has to be told to stop offering it, and a protobuf parser fed
225/// deflate reports "invalid wire type" — a message that sends whoever reads it
226/// looking for corruption instead of a header.
227///
228/// `max` caps what comes *out*, which the body limit does not: a few kilobytes
229/// of gzipped zeros expand to gigabytes and `read_to_end` will allocate every
230/// one of them. It is the same number as the body limit rather than a multiple
231/// of it, because that makes one configured value mean one thing — the largest
232/// export Mira will decode — however it arrived. A ratio would be the obvious
233/// alternative and does not work: a real batch, the same attribute keys over
234/// and over, reaches about 35:1, and there is no ratio above that which a bomb
235/// cannot also sit under.
236fn inflate(h: &HeaderMap, body: Bytes, max: usize) -> Result<Bytes, (StatusCode, String)> {
237    let ce = h
238        .get(header::CONTENT_ENCODING)
239        .map(|v| v.to_str().unwrap_or_default().trim().to_ascii_lowercase());
240    match ce.as_deref() {
241        None | Some("") | Some("identity") => Ok(body),
242        Some("gzip") | Some("x-gzip") => {
243            use std::io::Read;
244            let mut out = Vec::new();
245            // `take` is the whole defence: one byte past the cap and the read
246            // stops, so the refusal costs the cap and not the bomb.
247            flate2::read::GzDecoder::new(&body[..])
248                .take(max as u64 + 1)
249                .read_to_end(&mut out)
250                .map_err(|e| {
251                    (
252                        StatusCode::BAD_REQUEST,
253                        format!("failed to decompress gzip body: {e}"),
254                    )
255                })?;
256            if out.len() > max {
257                return Err((
258                    StatusCode::PAYLOAD_TOO_LARGE,
259                    format!(
260                        "gzip body inflates past the {max} byte limit; \
261                         raise ingest.max_request_bytes or lower the sender's batch size"
262                    ),
263                ));
264            }
265            Ok(out.into())
266        }
267        Some(other) => Err((
268            StatusCode::UNSUPPORTED_MEDIA_TYPE,
269            format!("unsupported content-encoding {other}; expected gzip or identity"),
270        )),
271    }
272}
273
274/// Decode, submit, and answer. Generic over the signal because the three
275/// endpoints differ only in which types they name.
276///
277/// The response is echoed back in the request's own encoding, which the spec
278/// requires: a JSON client gets `{}`, not a protobuf empty message that its
279/// parser will choke on.
280async fn export<R: Message + Default, T: Message>(
281    ingest: &Ingest<R>,
282    headers: &HeaderMap,
283    body: Bytes,
284    max: usize,
285    ok: T,
286    from_json: fn(&yaml_rust2::Yaml) -> Result<R, String>,
287) -> Response {
288    let (json, req) = match decode(headers, body, max, from_json) {
289        Ok(v) => v,
290        Err((json, code, e)) => return fail(json, code, &e),
291    };
292
293    match ingest.submit(req).await {
294        Ok(()) if json => (
295            StatusCode::OK,
296            [(header::CONTENT_TYPE, "application/json")],
297            "{}",
298        )
299            .into_response(),
300        Ok(()) => (
301            StatusCode::OK,
302            [(header::CONTENT_TYPE, "application/x-protobuf")],
303            ok.encode_to_vec(),
304        )
305            .into_response(),
306        Err(Rejected::Busy) => (
307            [(header::RETRY_AFTER, "1")],
308            fail(json, StatusCode::SERVICE_UNAVAILABLE, "ingest queue full"),
309        )
310            .into_response(),
311        Err(Rejected::Closed) => fail(json, StatusCode::SERVICE_UNAVAILABLE, "shutting down"),
312        // 503 and not 500 for the same reason as `UNAVAILABLE` above: 500 is
313        // outside OTLP/HTTP's retryable set, so it drops the batch.
314        Err(Rejected::Unavailable(e)) => (
315            [(header::RETRY_AFTER, "1")],
316            fail(json, StatusCode::SERVICE_UNAVAILABLE, &e),
317        )
318            .into_response(),
319        Err(Rejected::Failed(e)) => fail(json, StatusCode::INTERNAL_SERVER_ERROR, &e),
320    }
321}
322
323/// An error in the encoding the client asked for.
324///
325/// OTLP wants a `google.rpc.Status`; for the JSON case that is a two-field
326/// object, and hand-writing it costs less than a serializer. The protobuf case
327/// keeps returning text — encoding a `Status` there means another generated type
328/// for a path no exporter parses.
329/// Content type, then content encoding, then the wire format. The `bool` is
330/// "the client speaks JSON", which every answer to it has to be written in.
331///
332/// Split out of [`export`] for `proxy`, which decodes the same three request
333/// types in order to split them by entity and forward the parts. One copy of
334/// the header handling, so a gzip or content-type rule fixed on one path is
335/// fixed on both.
336pub(crate) fn decode<R: Message + Default>(
337    headers: &HeaderMap,
338    body: Bytes,
339    max: usize,
340    from_json: fn(&yaml_rust2::Yaml) -> Result<R, String>,
341) -> Result<(bool, R), (bool, StatusCode, String)> {
342    let json = match encoding(headers) {
343        Some(Encoding::Protobuf) => false,
344        Some(Encoding::Json) => true,
345        // Answered as protobuf because the client has not said it speaks
346        // anything else — this is the one error where that is unknown.
347        None => {
348            return Err((
349                false,
350                StatusCode::UNSUPPORTED_MEDIA_TYPE,
351                "expected application/x-protobuf or application/json".to_owned(),
352            ));
353        }
354    };
355    let body = inflate(headers, body, max).map_err(|(code, e)| (json, code, e))?;
356    let decoded = if json {
357        std::str::from_utf8(&body)
358            .map_err(|e| e.to_string())
359            .and_then(crate::api::parse)
360            .and_then(|doc| from_json(&doc))
361    } else {
362        R::decode(body).map_err(|e| e.to_string())
363    };
364    decoded
365        .map(|r| (json, r))
366        .map_err(|e| (json, StatusCode::BAD_REQUEST, e))
367}
368
369pub(crate) fn fail(json: bool, code: StatusCode, message: &str) -> Response {
370    if !json {
371        return (code, message.to_owned()).into_response();
372    }
373    // The only characters a message here can contain that JSON forbids.
374    let escaped = message.replace('\\', "\\\\").replace('"', "\\\"");
375    (
376        code,
377        [(header::CONTENT_TYPE, "application/json")],
378        // code 2 is UNKNOWN in google.rpc.Code; the HTTP status carries the
379        // detail an exporter actually branches on.
380        format!(r#"{{"code":2,"message":"{escaped}"}}"#),
381    )
382        .into_response()
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388
389    use axum::body::Body;
390    use axum::http::{HeaderValue, Request};
391    use mira_core::wal;
392    use tokio::sync::mpsc;
393    use tower::ServiceExt;
394
395    /// Which encoding `encoding` picked, as something a table can compare.
396    /// `Encoding` deliberately has no `PartialEq` — nothing in production
397    /// compares two of them — so the test names them instead of widening the
398    /// type's API for its own convenience.
399    fn picked(h: &HeaderMap) -> &'static str {
400        match encoding(h) {
401            Some(Encoding::Protobuf) => "protobuf",
402            Some(Encoding::Json) => "json",
403            None => "refused",
404        }
405    }
406
407    /// The `content-type` is what decides whether the body is parsed as
408    /// protobuf, parsed as KYAML, or refused with a 415 — and getting it wrong
409    /// is never a clean failure: a JSON body handed to `prost` reports "invalid
410    /// wire type", which reads like corruption rather than a header. The
411    /// missing header in particular has to mean protobuf, because every OTLP
412    /// client that predates the JSON encoding omits it, and refusing those is a
413    /// silent outage for the oldest exporters in the fleet.
414    #[test]
415    fn the_content_type_decides_the_parser_and_a_missing_one_means_protobuf() {
416        let with = |v: Option<&[u8]>| {
417            let mut h = HeaderMap::new();
418            if let Some(v) = v {
419                h.insert(header::CONTENT_TYPE, HeaderValue::from_bytes(v).unwrap());
420            }
421            h
422        };
423        for (sent, want) in [
424            (None, "protobuf"),
425            (Some(&b"application/x-protobuf"[..]), "protobuf"),
426            (Some(&b"application/protobuf"[..]), "protobuf"),
427            (Some(&b""[..]), "protobuf"),
428            // The parameters are the client's business, not ours.
429            (Some(&b"application/json; charset=utf-8"[..]), "json"),
430            (Some(&b" application/json "[..]), "json"),
431            (Some(&b"text/plain"[..]), "refused"),
432            (Some(&b"application/x-thrift"[..]), "refused"),
433            // A header that is not UTF-8 is unreadable, not unknown: it is
434            // treated as absent rather than crashing the handler on `to_str`.
435            (Some(&[0xff][..]), "protobuf"),
436        ] {
437            assert_eq!(picked(&with(sent)), want, "content-type {sent:?}");
438        }
439    }
440
441    /// A queue in the state named, with no flusher behind it. Both of these
442    /// refusals are decided by `submit` before anything is dequeued, so a real
443    /// pipeline is not needed to reach them — and a queue filled by wedging a
444    /// live flusher would be a race rather than a state.
445    async fn refusing<R>(closed: bool) -> (Ingest<R>, Box<dyn std::any::Any>)
446    where
447        R: prost::Message + 'static,
448    {
449        let (tx, rx) = mpsc::channel(1);
450        // Capacity one, and the one permit taken: `try_reserve` then reports
451        // `Full`, which is what an ingest queue that is not draining looks like.
452        let held = tx.clone().reserve_owned().await.ok();
453        let ingest = Ingest {
454            tx: [tx].into(),
455            turn: std::sync::Arc::default(),
456            rejects: &crate::pipeline::REJECTS[0],
457            wal: None,
458            signal: wal::Signal::Logs,
459        };
460        // Closed is the flusher being gone: drop both ends of the queue and
461        // keep nothing alive.
462        let keep: Box<dyn std::any::Any> = if closed {
463            drop((rx, held));
464            Box::new(())
465        } else {
466            Box::new((rx, held))
467        };
468        (ingest, keep)
469    }
470
471    /// Neither refusal is the sender's fault, and OTLP/HTTP's retryable set is
472    /// closed: anything outside 429/502/503/504 has the exporter drop the batch
473    /// it is holding. A full queue answered 500 — or 200 — is data loss chosen
474    /// by a status code, and the `retry-after` is what stops a shedding node
475    /// being hammered by every exporter at once while it drains.
476    #[tokio::test]
477    async fn a_queue_that_cannot_take_an_export_answers_503_and_keeps_the_batch_alive() {
478        for (closed, want_body, want_retry) in [
479            (false, "ingest queue full", true),
480            (true, "shutting down", false),
481        ] {
482            let (logs, _keep) = refusing(closed).await;
483            let (traces, _keep_t) = refusing(closed).await;
484            let (metrics, _keep_m) = refusing(closed).await;
485            let app = http_router(Receivers {
486                logs,
487                traces,
488                metrics,
489                max_request_bytes: 1 << 20,
490            });
491            let res = app
492                .oneshot(
493                    Request::builder()
494                        .method("POST")
495                        .uri("/v1/logs")
496                        .header("content-type", "application/x-protobuf")
497                        .body(Body::from(
498                            ExportLogsServiceRequest::default().encode_to_vec(),
499                        ))
500                        .unwrap(),
501                )
502                .await
503                .unwrap();
504
505            assert_eq!(
506                res.status(),
507                StatusCode::SERVICE_UNAVAILABLE,
508                "closed={closed} must stay inside the retryable set"
509            );
510            assert_eq!(
511                res.headers().get(header::RETRY_AFTER).is_some(),
512                want_retry,
513                "closed={closed} pushback"
514            );
515            let body = axum::body::to_bytes(res.into_body(), 1 << 16)
516                .await
517                .unwrap();
518            assert_eq!(
519                String::from_utf8_lossy(&body),
520                want_body,
521                "the reason has to name which of the two it was"
522            );
523        }
524    }
525
526    /// The status is the retry policy. OTLP names the retryable codes exactly —
527    /// `UNAVAILABLE` is in the set, `INTERNAL` is not — so an exporter handed
528    /// `INTERNAL` for a full disk drops the batch instead of resending it thirty
529    /// seconds later when the disk has room. `RetryInfo` rides along because the
530    /// bare code leaves the backoff to the client.
531    #[test]
532    fn a_write_that_failed_is_retryable_and_an_impossible_export_is_not() {
533        for r in [Rejected::Busy, Rejected::Unavailable("no space".into())] {
534            let s = status_for(r);
535            assert_eq!(s.code(), tonic::Code::Unavailable);
536            assert!(
537                s.get_error_details().retry_info().is_some(),
538                "an exporter with no retry policy needs the pushback"
539            );
540        }
541        assert_eq!(
542            status_for(Rejected::Closed).code(),
543            tonic::Code::Unavailable,
544            "a draining node must be retried elsewhere, not written off"
545        );
546        assert_eq!(
547            status_for(Rejected::Failed("too wide".into())).code(),
548            tonic::Code::Internal,
549            "an export no block can hold must not be retried forever"
550        );
551    }
552}