Skip to main content

mira/
proxy.rs

1//! `mira proxy`: one read and write surface in front of N storage nodes.
2//!
3//! # Why this can hold no state
4//!
5//! The thing that usually forces a coordinator on a fan-out query is paging: N
6//! nodes each answer "the newest 100" and the merger has to remember, for every
7//! reader, how far into each node's stream it had got. Mira does not need that,
8//! and the reason is [`Cursor`]. A cursor is `(ts, node, seq, row)` where `node`
9//! is [`mira_core::block::node_id`] — so it is already a *global* total order
10//! over every row on every replica, with no coordination anywhere, and it was
11//! that before this file existed.
12//!
13//! So the whole protocol is: send the same `after` cursor to every replica, ask
14//! each for the newest `limit` rows behind it, merge the answers on that same
15//! order, drop repeated cursors, cut to `limit`, and hand back the cursor of
16//! the last row emitted. Every row not emitted sorts strictly after that cursor
17//! on every replica, so the next page is exact — no duplicates, no gaps — and
18//! the proxy has forgotten the reader by the time the response is written.
19//! Principle 4 is satisfied by construction rather than by care.
20//!
21//! The repeats are not a paging failure but a placement one, and they are
22//! expected rather than exceptional. `node` in a cursor names the *writer*, so
23//! one block reachable from two replicas is answered for twice with the same
24//! cursor: that is the steady state of shared-volume mode (section 12.5), where
25//! every replica's `scan` sees every writer's blocks, and the transient state of
26//! a block being re-homed (section 6.1). Equal cursors are the same row and
27//! never a collision, so `merge` keeps one and the promise above holds.
28//!
29//! # What it refuses
30//!
31//! `/api/v1/query` and the three OTLP endpoints, and nothing else. `correlate`,
32//! `map`, `metrics/query`, `metrics/names` and `entities` all answer with
33//! something built by walking one node's blocks — a trace assembled from the spans that are local,
34//! a service map from the edges that are local. Merging those is not "sort and
35//! cut": two nodes each holding half a trace produce two partial frames, and
36//! there is no cursor to interleave them on. So this proxy answers 501 and says
37//! which endpoint to call directly. A plausible subset is the failure mode
38//! `identity.rs` refuses a hash for, and it would be worse here, because
39//! nothing in the response would say it was partial.
40//!
41//! # Where the reads are not merged, the writes are placed
42//!
43//! Ingest routes on [`resource_key`], the same 64-bit entity identity the
44//! storage layer already joins on, so one entity's records land on one replica.
45//! That is not for the query path above — that one fans out regardless — it is
46//! so each replica's blocks stay entity-local: the `_entity` block filter keeps
47//! its selectivity, and "everything this pod emitted" remains a question one
48//! node can answer completely, which is what the 501 above is holding the door
49//! open for.
50
51use std::sync::Arc;
52use std::time::{Duration, Instant};
53
54use axum::Router;
55use axum::body::Bytes;
56use axum::extract::State;
57use axum::http::{HeaderMap, StatusCode, header};
58use axum::response::{IntoResponse, Response};
59use axum::routing::{get, post};
60use http_body_util::{BodyExt, Full};
61use prost::Message;
62
63use mira_core::identity::resource_key;
64use mira_core::query::{self, Cursor};
65
66use mira_proto::collector::logs::v1::{ExportLogsServiceRequest, ExportLogsServiceResponse};
67use mira_proto::collector::metrics::v1::{
68    ExportMetricsServiceRequest, ExportMetricsServiceResponse,
69};
70use mira_proto::collector::trace::v1::{ExportTraceServiceRequest, ExportTraceServiceResponse};
71
72use crate::api;
73
74/// The replica list, resolved once at startup and never revisited.
75///
76/// Static on purpose. A membership protocol is the one mechanism principle 4
77/// names, and the thing it would buy — a replica joining without a restart —
78/// is not worth a second consensus implementation in a binary whose whole claim
79/// is that it has none. The list is a config key and a rolling restart.
80#[derive(Clone)]
81pub struct Proxy {
82    replicas: Arc<[String]>,
83    max_request_bytes: usize,
84}
85
86impl Proxy {
87    pub fn new(replicas: Vec<String>, max_request_bytes: usize) -> Result<Proxy, String> {
88        if replicas.is_empty() {
89            return Err("mira proxy needs at least one --replica URI".into());
90        }
91        Ok(Proxy {
92            replicas: replicas.into(),
93            max_request_bytes,
94        })
95    }
96}
97
98pub fn router(p: Proxy) -> Router {
99    let max = p.max_request_bytes;
100    Router::new()
101        // The probes. Without them a proxy pod never becomes Ready, its Service
102        // never gets an endpoint, and the whole tier is unreachable behind a
103        // container that is running perfectly — which is what a 404 on
104        // `/readyz` cost the first Kubernetes end-to-end run.
105        //
106        // Both a constant 200, unlike the storage node's, and the difference is
107        // the point. A node's readiness asks "can I make an export durable",
108        // which has a real answer because it owns a disk. This owns nothing: it
109        // is ready the moment it is listening. Gating it on the replicas would
110        // be strictly worse — one replica restarting would deregister the only
111        // address the exporters have and take the tier down to protect it.
112        .route("/health", get(up))
113        .route("/readyz", get(up))
114        .route("/api/v1/query", post(query_handler))
115        .route("/v1/logs", post(logs_handler))
116        .route("/v1/traces", post(traces_handler))
117        .route("/v1/metrics", post(metrics_handler))
118        // Every read this proxy cannot merge, named rather than 404'd: a 404
119        // reads as "old build" and sends whoever hit it looking at versions.
120        .route("/api/v1/correlate", post(unmergeable))
121        .route("/api/v1/map", post(unmergeable))
122        .route("/api/v1/metrics/query", post(unmergeable))
123        .route("/api/v1/metrics/names", post(unmergeable))
124        .route("/api/v1/entities", post(unmergeable))
125        .layer(axum::extract::DefaultBodyLimit::max(max))
126        .with_state(p)
127}
128
129/// Liveness and readiness, which for a stateless fan-out are the same answer.
130async fn up() -> Response {
131    let mut j = mira_core::json::Json::new();
132    j.obj(|j| {
133        j.key("status");
134        j.str("ok");
135    });
136    api::json_ok(j.into_string())
137}
138
139async fn unmergeable(uri: axum::http::Uri) -> Response {
140    let path = uri.path().to_owned();
141    fail(
142        StatusCode::NOT_IMPLEMENTED,
143        &format!(
144            "{path} is answered from one node's blocks and cannot be merged across replicas; \
145             query a replica directly. See `mira proxy` in the usage."
146        ),
147    )
148}
149
150// ---------------------------------------------------------------- reads
151
152/// Fan a record search out to every replica and merge the pages.
153async fn query_handler(State(p): State<Proxy>, body: String) -> Response {
154    let t = Instant::now();
155    // Parsed before anything is spliced, so a document this proxy then rewrites
156    // is still reported back to the caller in the words of what they sent.
157    let caller = match api::parse(&body) {
158        Ok(d) => d,
159        Err(e) => return fail(StatusCode::BAD_REQUEST, &e),
160    };
161    // `with_cursors` can add the key and cannot replace one: a mapping carrying
162    // it twice is not a document at all, and splicing blind turns a caller who
163    // asked for cursors — the one who most obviously meant to — into a KYAML
164    // duplicate-key error from a replica. So a caller who spelled it out has
165    // their bytes forwarded unaltered, whichever way they spelled it; `"false"`
166    // is then refused below rather than silently overridden.
167    let doc = match caller["cursors"].is_badvalue() {
168        true => with_cursors(&body),
169        false => body.clone(),
170    };
171    // Parsed here as well as on the replicas, for two things that are only
172    // knowable locally: `limit`, which is where the merged page is cut, and
173    // whether the line above actually did what it says. A document that reached
174    // the replicas without `cursors` set would come back without them and the
175    // merge would fall back to whatever order the replicas answered in — the
176    // one failure this file must not have, so it is an assertion and not a
177    // comment.
178    let q = match api::parse(&doc).and_then(|d| api::search_doc(&d, api::now_nanos())) {
179        Ok(q) if q.cursors => q,
180        Ok(_) => {
181            return fail(
182                StatusCode::BAD_REQUEST,
183                "the query document set `cursors` to false; the proxy needs them to merge",
184            );
185        }
186        Err(e) => return fail(StatusCode::BAD_REQUEST, &e),
187    };
188    // Whether the *caller* wanted them, which is a different question: the
189    // proxy always asks the replicas, and passes them on only if asked itself.
190    let wanted = api::search_doc(&caller, api::now_nanos()).is_ok_and(|c: query::Search| c.cursors);
191
192    let answers = match fanout(&p, "/api/v1/query", TEXT, doc.into_bytes()).await {
193        Ok(a) => a,
194        Err(e) => return fail(StatusCode::BAD_GATEWAY, &e),
195    };
196    let bodies: Vec<String> = answers.into_iter().map(|(_, b)| b).collect();
197    match merge(&bodies, q.limit, wanted) {
198        Ok(r) => json_ok(api::envelope("rows", &r, t.elapsed())),
199        Err(e) => fail(StatusCode::BAD_GATEWAY, &e),
200    }
201}
202
203/// Interleave the replicas' pages on the cursor order and cut to `limit`.
204///
205/// The rows are moved as the bytes the replica sent. Re-serialising them would
206/// mean a second renderer to keep in step with `api::envelope`, and the first
207/// one is the specification — a proxy that reformats what it forwards is a
208/// place for the two to drift.
209fn merge(bodies: &[String], limit: usize, keep_cursors: bool) -> Result<query::Results, String> {
210    let mut stats = query::Stats::default();
211    let mut more = false;
212    let mut rows: Vec<(Cursor, &str)> = Vec::new();
213    for body in bodies {
214        let fields = object(body)?;
215        let page = pieces(field(&fields, "rows")?)?;
216        let cursors = match field(&fields, "cursors") {
217            Ok(cs) => pieces(cs)?,
218            // A page with no rows has no cursors, and `api::envelope` leaves
219            // the key out rather than writing `[]` — see its doc. So a missing
220            // key is only evidence of a mismatched build when there were rows
221            // to place, and treating it as one otherwise would let any replica
222            // holding nothing for this window fail the whole read.
223            Err(_) if page.is_empty() => Vec::new(),
224            Err(_) => {
225                return Err(
226                    "a replica answered without `cursors`; every node behind one \
227                            proxy has to be the same build"
228                        .into(),
229                );
230            }
231        };
232        if page.len() != cursors.len() {
233            return Err("a replica's `rows` and `cursors` disagree in length".into());
234        }
235        for (row, c) in page.into_iter().zip(cursors) {
236            rows.push((unquote(c)?.parse()?, row));
237        }
238        let s = object(field(&fields, "stats")?)?;
239        stats.blocks_total += count(&s, "blocks_total")?;
240        stats.blocks_scanned += count(&s, "blocks_scanned")?;
241        stats.rows_scanned += count(&s, "rows_scanned")?;
242        stats.rows_matched += count(&s, "rows_matched")?;
243        more |= field(&fields, "next").is_ok();
244    }
245
246    // Sorted, then cut — and `more` is set by the cut as well as by any replica
247    // that said it was holding more. Both have to count: N short pages can
248    // still exceed `limit` between them, and one full page means that replica
249    // has more even when the merged set does not overflow.
250    rows.sort_unstable_by_key(|(c, _)| c.key());
251    // A cursor is `(ts, node, seq, row)` where `node` is the *writer* and not
252    // the replica that answered, so two replicas holding one block hand back
253    // byte-identical cursors for the same row. Equal keys are therefore always
254    // the same row and never two rows that collided, which is what makes
255    // dropping one of them safe rather than lossy.
256    //
257    // Two supported shapes produce it. Shared-volume mode (section 12.5) is the
258    // permanent one: every replica's `scan` sees every writer's blocks, so
259    // without this line a two-replica proxy returns every row twice. The other
260    // is the window while a block is being re-homed, when it is deliberately
261    // present on both its old node and its new one (section 6.1).
262    //
263    // Before the cut, not after. Duplicates left in the count report a `more`
264    // that is not there, and they spend the reader's `limit` on rows it has
265    // already been handed: across N replicas sharing a volume, a page of 100
266    // comes back carrying 100/N distinct rows and the reader has no way to tell.
267    rows.dedup_by_key(|(c, _)| c.key());
268    more |= rows.len() > limit;
269    rows.truncate(limit);
270
271    let mut json = String::from("[");
272    for (i, (_, row)) in rows.iter().enumerate() {
273        if i > 0 {
274            json.push(',');
275        }
276        json.push_str(row);
277    }
278    json.push(']');
279    Ok(query::Results {
280        json,
281        stats,
282        // The cursor of the last row emitted, which every unemitted row on
283        // every replica sorts strictly after. That is what makes the next page
284        // exact without the proxy remembering anything: see the module docs.
285        next: more.then(|| rows.last().map(|(c, _)| *c)).flatten(),
286        cursors: match keep_cursors {
287            true => rows.iter().map(|(c, _)| *c).collect(),
288            false => Vec::new(),
289        },
290    })
291}
292
293/// The caller's document with `cursors` added.
294///
295/// Textual because the alternative is a KYAML writer for `Search`, and a round
296/// trip through one would normalise whatever the caller wrote — including the
297/// `where` terms, which is the part most likely to have a spelling this file
298/// has not thought of. The caller's bytes are left exactly as they arrived and
299/// one key is added; `query_handler` then parses the result and refuses it if
300/// this did not take.
301///
302/// Added, never replaced, so the caller's document must not carry the key
303/// already — `query_handler` checks that, because a mapping with `cursors`
304/// twice is not a document and the replica rejects the whole read.
305fn with_cursors(body: &str) -> String {
306    let b = body.trim();
307    match b.strip_prefix('{') {
308        // A flow mapping: splice the key in behind the brace. `{}` has no entry
309        // to separate from, so no comma.
310        Some(rest) if rest.trim_start().starts_with('}') => {
311            format!("{{\"cursors\": \"true\"{rest}")
312        }
313        Some(rest) => format!("{{\"cursors\": \"true\", {rest}"),
314        // A block mapping, or an empty body, which is a valid empty search.
315        None => format!("{b}\n\"cursors\": \"true\"\n"),
316    }
317}
318
319// ---------------------------------------------------------------- writes
320
321/// The three OTLP endpoints differ only in which types they name.
322macro_rules! ingest {
323    ($name:ident, $path:literal, $field:ident, $req:ident, $resp:ident, $json:path) => {
324        async fn $name(State(p): State<Proxy>, h: HeaderMap, b: Bytes) -> Response {
325            let (json, req) =
326                match crate::receiver::decode::<$req>(&h, b, p.max_request_bytes, $json) {
327                    Ok(v) => v,
328                    Err((json, code, e)) => return crate::receiver::fail(json, code, &e),
329                };
330            // One sub-export per replica, each holding the resource entries
331            // whose entity hashes to it. Empty ones are not sent: a replica
332            // that received nothing from this batch has nothing to acknowledge,
333            // and an empty export is a round trip for no rows.
334            let n = p.replicas.len();
335            let mut parts: Vec<Vec<_>> = (0..n).map(|_| Vec::new()).collect();
336            for (i, e) in req.$field.into_iter().enumerate() {
337                let attrs = e.resource.as_ref().map_or(&[][..], |r| &r.attributes);
338                parts[slot(attrs, i, n)].push(e);
339            }
340            let bodies: Vec<(usize, Vec<u8>)> = parts
341                .into_iter()
342                .enumerate()
343                .filter(|(_, part)| !part.is_empty())
344                .map(|(i, part)| (i, $req { $field: part }.encode_to_vec()))
345                .collect();
346            match scatter(&p, $path, bodies).await {
347                Ok(()) => accepted(json, &$resp::default()),
348                // Retryable refusals carry the same `Retry-After` a node's own
349                // would, so an exporter behind the proxy backs off exactly as it
350                // does in front of one.
351                Err((code, e)) if code == StatusCode::SERVICE_UNAVAILABLE => (
352                    [(header::RETRY_AFTER, "1")],
353                    crate::receiver::fail(json, code, &e),
354                )
355                    .into_response(),
356                Err((code, e)) => crate::receiver::fail(json, code, &e),
357            }
358        }
359    };
360}
361
362ingest!(
363    logs_handler,
364    "/v1/logs",
365    resource_logs,
366    ExportLogsServiceRequest,
367    ExportLogsServiceResponse,
368    crate::json::logs
369);
370ingest!(
371    traces_handler,
372    "/v1/traces",
373    resource_spans,
374    ExportTraceServiceRequest,
375    ExportTraceServiceResponse,
376    crate::json::traces
377);
378ingest!(
379    metrics_handler,
380    "/v1/metrics",
381    resource_metrics,
382    ExportMetricsServiceRequest,
383    ExportMetricsServiceResponse,
384    crate::json::metrics
385);
386
387/// Which replica a resource's records belong on.
388///
389/// The identity hash, so every record describing one entity lands on one node
390/// whatever batch it arrived in and whatever order the batches came in — that
391/// is the whole property, and it holds without the proxy remembering a thing.
392///
393/// [`mira_core::identity::NO_IDENTITY`] is spread by position instead. A
394/// resource with no identifying attribute has no entity to keep together, by
395/// the argument in `identity.rs`, so hashing it to a fixed slot would pile
396/// every unidentified sender in a deployment onto replica zero and buy nothing
397/// for it.
398fn slot(attrs: &[mira_proto::common::v1::KeyValue], i: usize, n: usize) -> usize {
399    match resource_key(attrs) {
400        mira_core::identity::NO_IDENTITY => i % n,
401        // Modulo and not consistent hashing: the replica list is static (see
402        // `Proxy`), so the only event that remaps keys is an operator editing
403        // it and restarting, and at that point the blocks already written do
404        // not move either way. Consistent hashing buys a smaller remap for a
405        // rebalance this design does not have.
406        //
407        // ponytail: `% n` over a static list. If replicas ever join without a
408        // restart, this is the line that has to become a ring — and the
409        // membership protocol it would need is the thing principle 4 refuses,
410        // so the upgrade is the whole design, not this expression.
411        k => (k % n as u64) as usize,
412    }
413}
414
415/// Send each sub-export to its replica and answer once they all have.
416///
417/// All of them, not a quorum: a 200 to an OTLP exporter means the batch is
418/// stored, and there is no second place for the part that was not. A partial
419/// failure is a 503 for the whole export, so the exporter retries the whole
420/// batch — which re-delivers the sub-exports that did land.
421///
422/// ponytail: at-least-once on a partial failure, which is what OTLP already is
423/// end to end (a collector that times out on a 200 in flight does the same
424/// thing). Making it exactly-once needs an idempotency key on the export and a
425/// seen-set on the node, which is per-reader coordination state — principle 4
426/// again — for a duplicate the query layer is already built to tolerate.
427async fn scatter(p: &Proxy, path: &str, bodies: Vec<(usize, Vec<u8>)>) -> Result<(), Status> {
428    let mut set = tokio::task::JoinSet::new();
429    for (i, body) in bodies {
430        let url = format!("{}{path}", p.replicas[i]);
431        set.spawn(async move {
432            let r = send(&url, PROTOBUF, body).await;
433            (url, r)
434        });
435    }
436    let mut worst: Option<Status> = None;
437    while let Some(joined) = set.join_next().await {
438        let (url, r) = joined.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
439        let bad = match r {
440            Err(e) => Some((StatusCode::SERVICE_UNAVAILABLE, format!("{url}: {e}"))),
441            Ok((s, _)) if s.is_success() => None,
442            Ok((s, b)) => Some((
443                retryable(s),
444                format!("{url}: HTTP {} {}", s.as_u16(), text(&b)),
445            )),
446        };
447        // The most retryable failure wins, because the exporter's decision is
448        // about the whole batch: one replica's 400 next to another's 503 has to
449        // come back as the 503, or a transient overload on one node is reported
450        // as a permanent error and the batch is dropped.
451        if let Some(bad) = bad {
452            worst = Some(match worst {
453                Some(w) if w.0 == StatusCode::SERVICE_UNAVAILABLE => w,
454                _ => bad,
455            });
456        }
457    }
458    match worst {
459        Some(w) => Err(w),
460        None => Ok(()),
461    }
462}
463
464type Status = (StatusCode, String);
465
466/// A replica's status, mapped to what this proxy should tell the exporter.
467///
468/// Anything that is not the sender's fault becomes a 503, which is in OTLP's
469/// retryable set; a 400 or a 413 is passed through, because retrying those
470/// produces the same answer forever.
471fn retryable(s: StatusCode) -> StatusCode {
472    match s.as_u16() {
473        400 | 413 | 415 => s,
474        _ => StatusCode::SERVICE_UNAVAILABLE,
475    }
476}
477
478// ---------------------------------------------------------------- transport
479
480const TEXT: &str = "text/plain; charset=utf-8";
481const PROTOBUF: &str = "application/x-protobuf";
482
483/// The same body to every replica, concurrently.
484async fn fanout(
485    p: &Proxy,
486    path: &str,
487    ct: &'static str,
488    body: Vec<u8>,
489) -> Result<Vec<(String, String)>, String> {
490    let mut set = tokio::task::JoinSet::new();
491    for r in p.replicas.iter() {
492        let url = format!("{r}{path}");
493        let body = body.clone();
494        set.spawn(async move {
495            let out = send(&url, ct, body).await;
496            (url, out)
497        });
498    }
499    let mut out = Vec::with_capacity(p.replicas.len());
500    while let Some(joined) = set.join_next().await {
501        let (url, r) = joined.map_err(|e| e.to_string())?;
502        // Every replica or none. Dropping the one that did not answer and
503        // merging the rest would return a page that is silently missing
504        // whatever that node held — and nothing in the response would say so.
505        // A read that cannot be complete is an error, not a shorter list.
506        let (status, body) = r.map_err(|e| format!("{url}: {e}"))?;
507        if !status.is_success() {
508            return Err(format!(
509                "{url}: HTTP {} {}",
510                status.as_u16(),
511                text(body.as_ref())
512            ));
513        }
514        out.push((
515            url,
516            String::from_utf8(body.into()).map_err(|e| e.to_string())?,
517        ));
518    }
519    Ok(out)
520}
521
522/// How long a replica has to answer.
523///
524/// Generous because a cold wide scan on a replica is seconds and the caller
525/// asked for it; the bound exists so that a wedged node fails the request
526/// rather than holding the connection until the client gives up, which is the
527/// failure that looks like the proxy is broken.
528const REPLICA_TIMEOUT: Duration = Duration::from_secs(60);
529
530async fn send(url: &str, ct: &'static str, body: Vec<u8>) -> Result<(StatusCode, Bytes), String> {
531    let req = hyper::Request::builder()
532        .method(hyper::Method::POST)
533        .uri(url)
534        .header(hyper::header::CONTENT_TYPE, ct)
535        .body(Full::new(Bytes::from(body)))
536        .map_err(|e| e.to_string())?;
537    let resp = tokio::time::timeout(REPLICA_TIMEOUT, client().request(req))
538        .await
539        .map_err(|_| format!("no answer in {}s", REPLICA_TIMEOUT.as_secs()))?
540        .map_err(|e| e.to_string())?;
541    let status = resp.status();
542    let body = resp
543        .into_body()
544        .collect()
545        .await
546        .map_err(|e| e.to_string())?
547        .to_bytes();
548    Ok((status, body))
549}
550
551type Client = hyper_util::client::legacy::Client<
552    hyper_util::client::legacy::connect::HttpConnector,
553    Full<Bytes>,
554>;
555
556/// One pooled client for the process, keep-alive included: a fresh TCP
557/// handshake per replica per query is most of the latency of a small one.
558///
559/// Plain HTTP with no TLS option, unlike the webhook dispatcher. A replica is
560/// this deployment's own node on its own network, and `--replica` refuses any
561/// other scheme at load — so there is no second place where the eleven crates
562/// behind `webhook-tls` have to be argued about.
563fn client() -> &'static Client {
564    static C: std::sync::OnceLock<Client> = std::sync::OnceLock::new();
565    C.get_or_init(|| {
566        hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())
567            .build_http()
568    })
569}
570
571// ---------------------------------------------------------------- JSON, read only
572
573/// Split a JSON object into its keys and the raw text of their values.
574///
575/// Not a JSON parser and not trying to be: it finds boundaries and hands back
576/// slices of the input, because the rows have to leave this process as the
577/// bytes that entered it. Every byte it is pointed at came out of
578/// `api::envelope`, so the shapes it refuses are the ones that say a replica is
579/// running a build this one does not understand — which is worth an error and
580/// not a guess.
581///
582/// ponytail: enough of a scanner to walk one envelope. It is not a general JSON
583/// reader and must not grow into one — if something here ever needs the values
584/// themselves, `api::parse` already reads JSON as the KYAML subset it is
585/// (principle 5), and the reason this does not use it is only that a round trip
586/// through `Yaml` would re-render the rows.
587fn object(s: &str) -> Result<Vec<(&str, &str)>, String> {
588    pieces(s)?.into_iter().map(field_of).collect()
589}
590
591/// The comma-separated pieces inside one `[...]` or `{...}`, as slices.
592fn pieces(s: &str) -> Result<Vec<&str>, String> {
593    let s = s.trim();
594    let inner = s
595        .strip_prefix(['[', '{'])
596        .and_then(|r| r.strip_suffix([']', '}']))
597        .ok_or_else(|| format!("expected a JSON array or object, got {s:.40}"))?;
598    let (mut out, mut depth, mut start) = (Vec::new(), 0i32, 0usize);
599    let (mut quoted, mut escaped) = (false, false);
600    for (i, b) in inner.bytes().enumerate() {
601        match b {
602            _ if escaped => escaped = false,
603            b'\\' if quoted => escaped = true,
604            b'"' => quoted = !quoted,
605            _ if quoted => {}
606            b'[' | b'{' => depth += 1,
607            b']' | b'}' => depth -= 1,
608            b',' if depth == 0 => {
609                out.push(inner[start..i].trim());
610                start = i + 1;
611            }
612            _ => {}
613        }
614    }
615    if depth != 0 || quoted {
616        return Err("unbalanced JSON in a replica's answer".into());
617    }
618    let last = inner[start..].trim();
619    // An empty collection has no last piece; anything else does, even if the
620    // producer left a trailing comma.
621    if !last.is_empty() || !out.is_empty() {
622        out.push(last);
623    }
624    Ok(out)
625}
626
627/// One `"key": value` piece of an object.
628fn field_of(p: &str) -> Result<(&str, &str), String> {
629    let bad = || format!("expected a JSON member, got {p:.40}");
630    let rest = p.strip_prefix('"').ok_or_else(bad)?;
631    // The keys in an envelope are `blocks_total` and friends, so there is no
632    // escape to step over — and a key that needed one did not come from Mira.
633    let end = rest.find('"').ok_or_else(bad)?;
634    let value = rest[end + 1..]
635        .trim_start()
636        .strip_prefix(':')
637        .ok_or_else(bad)?;
638    Ok((&rest[..end], value.trim()))
639}
640
641fn field<'a>(fields: &[(&'a str, &'a str)], key: &str) -> Result<&'a str, String> {
642    fields
643        .iter()
644        .find(|(k, _)| *k == key)
645        .map(|(_, v)| *v)
646        .ok_or_else(|| format!("a replica's answer has no {key:?}"))
647}
648
649fn count(fields: &[(&str, &str)], key: &str) -> Result<usize, String> {
650    field(fields, key)?
651        .parse()
652        .map_err(|e| format!("{key}: {e}"))
653}
654
655fn unquote(s: &str) -> Result<&str, String> {
656    s.strip_prefix('"')
657        .and_then(|r| r.strip_suffix('"'))
658        .ok_or_else(|| format!("expected a quoted cursor, got {s:.40}"))
659}
660
661/// A replica's error body, for quoting back inside this proxy's own.
662fn text(b: &[u8]) -> String {
663    String::from_utf8_lossy(b).chars().take(200).collect()
664}
665
666// ---------------------------------------------------------------- responses
667
668fn json_ok(body: String) -> Response {
669    (
670        StatusCode::OK,
671        [(header::CONTENT_TYPE, "application/json")],
672        body,
673    )
674        .into_response()
675}
676
677fn accepted<T: Message>(json: bool, ok: &T) -> Response {
678    match json {
679        true => (
680            StatusCode::OK,
681            [(header::CONTENT_TYPE, "application/json")],
682            "{}",
683        )
684            .into_response(),
685        false => (
686            StatusCode::OK,
687            [(header::CONTENT_TYPE, "application/x-protobuf")],
688            ok.encode_to_vec(),
689        )
690            .into_response(),
691    }
692}
693
694/// The same JSON error body a node returns, under a status this file picks.
695fn fail(code: StatusCode, msg: &str) -> Response {
696    api::error(code, msg)
697}
698
699#[cfg(test)]
700mod tests {
701    use super::*;
702
703    /// A replica's answer, rendered by the renderer a replica actually uses.
704    ///
705    /// Hand-written JSON here would check this file against my idea of the
706    /// envelope; `api::envelope` checks it against the envelope, so a key that
707    /// moves or a quote that changes fails the merge rather than passing both
708    /// sides of a copy.
709    ///
710    /// Each row carries its own cursor as its only field, which is what makes
711    /// the assertions below readable: the merged `rows` array says, in order,
712    /// exactly which row came from where.
713    fn page(rows: &[(i64, u32, u64)], more: bool) -> String {
714        let cursors: Vec<Cursor> = rows
715            .iter()
716            .map(|&(ts, node, seq)| Cursor {
717                ts,
718                node,
719                seq,
720                row: 0,
721            })
722            .collect();
723        let mut json = String::from("[");
724        for (i, c) in cursors.iter().enumerate() {
725            if i > 0 {
726                json.push(',');
727            }
728            json.push_str(&format!("{{\"body\":\"{c}\"}}"));
729        }
730        json.push(']');
731        api::envelope(
732            "rows",
733            &query::Results {
734                json,
735                stats: query::Stats {
736                    blocks_total: 4,
737                    blocks_scanned: 1,
738                    rows_scanned: 10,
739                    rows_matched: rows.len(),
740                    dropped_series: 0,
741                },
742                next: more.then(|| *cursors.last().unwrap()),
743                cursors,
744            },
745            Duration::from_micros(7),
746        )
747    }
748
749    fn bodies(cursor: &str) -> Vec<String> {
750        vec![cursor.to_owned()]
751    }
752
753    /// The claim in the module docs, on the smallest case that can break it:
754    /// two replicas whose pages interleave rather than concatenate.
755    #[test]
756    fn a_merged_page_is_the_replicas_rows_in_the_global_cursor_order() {
757        let a = page(&[(100, 1, 9), (80, 1, 9), (60, 1, 8)], false);
758        let b = page(&[(90, 2, 3), (70, 2, 3), (50, 2, 1)], false);
759        let r = merge(&[a, b], 10, false).unwrap();
760        assert_eq!(
761            r.json,
762            "[{\"body\":\"100.1.9.0\"},{\"body\":\"90.2.3.0\"},{\"body\":\"80.1.9.0\"},\
763             {\"body\":\"70.2.3.0\"},{\"body\":\"60.1.8.0\"},{\"body\":\"50.2.1.0\"}]"
764        );
765        // Both replicas said they were done and the merged set fits, so this is
766        // the last page. `next: Some` here is the bug that makes a reader poll
767        // forever.
768        assert!(r.next.is_none());
769        // Summed, not taken from one answer: the cost of the query is what all
770        // the replicas spent on it.
771        assert_eq!(r.stats.blocks_total, 8);
772        assert_eq!(r.stats.rows_scanned, 20);
773        assert_eq!(r.stats.rows_matched, 6);
774        // Not asked for, so not carried: a caller who did not ask sees the same
775        // body a single node would have sent.
776        assert!(r.cursors.is_empty());
777    }
778
779    /// One block seen by two replicas is one row, not two.
780    ///
781    /// `node` in a cursor is the writer, never the replica that answered, so a
782    /// block reachable from two places yields byte-identical cursors and equal
783    /// keys are always the same row. That is the *steady state* of shared-volume
784    /// mode (section 12.5), where every replica's `scan` sees every writer's
785    /// blocks — so without the dedup a two-replica proxy returns the whole
786    /// dataset twice and the module's "no duplicates" promise is false for a
787    /// configuration the chart documents. It is also the deliberate state of a
788    /// block part-way through being re-homed (section 6.1).
789    ///
790    /// The cut matters as much as the rows: duplicates spend the reader's
791    /// `limit`, so the second half asserts a page of two carries two *distinct*
792    /// rows rather than one row twice.
793    #[test]
794    fn one_block_seen_by_two_replicas_is_not_two_copies_of_every_row() {
795        let shared = [(100, 1, 9), (80, 1, 9), (60, 1, 8)];
796        let both = || [page(&shared, false), page(&shared, false)];
797
798        let r = merge(&both(), 10, false).unwrap();
799        assert_eq!(
800            r.json,
801            "[{\"body\":\"100.1.9.0\"},{\"body\":\"80.1.9.0\"},{\"body\":\"60.1.8.0\"}]"
802        );
803        // Three distinct rows fit under ten, so there is nothing behind them.
804        // Un-deduplicated this is six and the reader is told to come back.
805        assert!(r.next.is_none());
806
807        let cut = merge(&both(), 2, false).unwrap();
808        assert_eq!(
809            cut.json, "[{\"body\":\"100.1.9.0\"},{\"body\":\"80.1.9.0\"}]",
810            "a page of two is two rows, not one row twice"
811        );
812        assert_eq!(cut.next.unwrap().to_string(), "80.1.9.0");
813    }
814
815    /// A tie on `ts` across two nodes is the case a per-node order cannot
816    /// resolve and `Cursor::key` can. Without `node` in the key these two rows
817    /// sort by whichever replica answered first, which is a different page on
818    /// every request.
819    #[test]
820    fn rows_sharing_a_nanosecond_on_different_nodes_still_have_one_order() {
821        let a = page(&[(100, 7, 1)], false);
822        let b = page(&[(100, 3, 1)], false);
823        let one = merge(&[a.clone(), b.clone()], 10, false).unwrap();
824        let other = merge(&[b, a], 10, false).unwrap();
825        assert_eq!(one.json, other.json);
826        assert_eq!(
827            one.json,
828            "[{\"body\":\"100.7.1.0\"},{\"body\":\"100.3.1.0\"}]"
829        );
830    }
831
832    /// `limit` cuts the merged set, and the cut is what makes `next` the last
833    /// *emitted* row rather than the last row anyone held.
834    #[test]
835    fn the_page_is_cut_at_limit_and_next_is_the_last_row_emitted() {
836        let a = page(&[(100, 1, 9), (80, 1, 9)], false);
837        let b = page(&[(90, 2, 3), (70, 2, 3)], false);
838        let r = merge(&[a, b], 3, false).unwrap();
839        assert_eq!(
840            r.json,
841            "[{\"body\":\"100.1.9.0\"},{\"body\":\"90.2.3.0\"},{\"body\":\"80.1.9.0\"}]"
842        );
843        assert_eq!(r.next.unwrap().to_string(), "80.1.9.0");
844    }
845
846    /// The other way a page is not the last one: nothing overflowed here, but a
847    /// replica said it was holding more. Missing this is a reader that stops
848    /// three pages early and never learns it did.
849    #[test]
850    fn a_replica_holding_more_makes_the_merged_page_not_the_last_one() {
851        let a = page(&[(100, 1, 9)], true);
852        let b = page(&[(90, 2, 3)], false);
853        let r = merge(&[a, b], 10, false).unwrap();
854        assert_eq!(r.json.matches("body").count(), 2);
855        assert_eq!(r.next.unwrap().to_string(), "90.2.3.0");
856    }
857
858    /// Asked for, so carried — and index-aligned with the merged rows, not with
859    /// the order any one replica sent.
860    #[test]
861    fn cursors_are_passed_on_only_when_the_caller_asked_and_match_the_merged_rows() {
862        let a = page(&[(100, 1, 9), (60, 1, 8)], false);
863        let b = page(&[(90, 2, 3)], false);
864        let r = merge(&[a, b], 10, true).unwrap();
865        let got: Vec<String> = r.cursors.iter().map(Cursor::to_string).collect();
866        assert_eq!(got, ["100.1.9.0", "90.2.3.0", "60.1.8.0"]);
867    }
868
869    /// Every answer, or an error. A replica running a build without the
870    /// `cursors` key would otherwise contribute rows in whatever order it sent
871    /// them, which is the one failure this file must not have.
872    #[test]
873    fn an_answer_this_proxy_cannot_place_is_an_error_and_not_a_guess() {
874        let without = api::envelope(
875            "rows",
876            &query::Results {
877                json: "[{\"body\":\"x\"}]".into(),
878                stats: query::Stats::default(),
879                next: None,
880                cursors: Vec::new(),
881            },
882            Duration::ZERO,
883        );
884        let why = |body: &str| merge(&bodies(body), 10, false).err().expect("accepted");
885        assert!(why(&without).contains("the same build"));
886
887        // Rows and cursors that disagree: index alignment is the whole contract
888        // between the two arrays, and a shorter one silently drops rows.
889        let short = page(&[(100, 1, 9), (80, 1, 9)], false).replace(
890            ",\"cursors\":[\"100.1.9.0\",\"80.1.9.0\"]",
891            ",\"cursors\":[\"100.1.9.0\"]",
892        );
893        assert!(why(&short).contains("disagree in length"));
894
895        // A statistic that is not a number. Every one of these is summed across
896        // the replicas, so a replica from a build that renders them differently
897        // has to stop the read rather than contribute a zero.
898        let odd =
899            page(&[(100, 1, 9)], false).replace("\"rows_matched\":1", "\"rows_matched\":\"1\"");
900        assert!(why(&odd).contains("rows_matched"), "{odd}");
901
902        for broken in ["", "{}", "not json", "{\"rows\":[]}"] {
903            assert!(merge(&bodies(broken), 10, false).is_err(), "{broken:?}");
904        }
905    }
906
907    /// An empty page is a page. `pieces` has to tell `[]` from `[x]` or the
908    /// first replica with nothing to say takes the request down.
909    #[test]
910    fn a_replica_with_no_rows_contributes_none_and_breaks_nothing() {
911        let r = merge(&[page(&[], false), page(&[(90, 2, 3)], false)], 10, false).unwrap();
912        assert_eq!(r.json, "[{\"body\":\"90.2.3.0\"}]");
913        assert!(r.next.is_none());
914    }
915
916    /// `with_cursors` has one job and `query_handler` refuses the request if it
917    /// did not do it — so the check is that the document *parses back* with the
918    /// flag set, on every shape a caller can send.
919    #[test]
920    fn every_document_shape_comes_back_with_cursors_on() {
921        let docs = [
922            // Flow mapping, the shape the docs and the UI send.
923            r#"{"signal":"logs","limit":5}"#,
924            // Empty flow mapping: valid, and the one with no entry to separate
925            // the new key from.
926            "{}",
927            "{ }",
928            // Block mapping, which is what a human writing KYAML by hand sends.
929            "signal: \"traces\"\nlimit: 5",
930            // No document at all, which `search_doc` reads as every default.
931            "",
932            "  \n",
933        ];
934        for doc in docs {
935            let out = with_cursors(doc);
936            let q = api::parse(&out).and_then(|d| api::search_doc(&d, 0));
937            // One assertion rather than an unwrap and then a check: the failure
938            // that matters here is "the splice produced something unreadable",
939            // and that wants the same message as "it parsed but lost the key".
940            assert!(
941                q.as_ref().is_ok_and(|q| q.cursors),
942                "{doc:?} became {out:?}: {q:?}"
943            );
944        }
945        // And the rest of the document survives the splice.
946        let q = api::parse(&with_cursors(r#"{"signal":"traces","limit":7}"#))
947            .and_then(|d| api::search_doc(&d, 0))
948            .unwrap();
949        assert_eq!(q.limit, 7);
950        assert!(matches!(q.signal, query::Signal::Traces));
951    }
952
953    /// The placement property, stated as the test: one entity, one replica,
954    /// whatever batch it arrives in and whatever else is in that batch.
955    #[test]
956    fn one_entity_lands_on_one_replica_from_any_position_in_any_batch() {
957        let kv = |k: &str, v: &str| mira_proto::common::v1::KeyValue {
958            key: k.into(),
959            value: Some(mira_proto::common::v1::AnyValue {
960                value: Some(mira_proto::common::v1::any_value::Value::StringValue(
961                    v.into(),
962                )),
963            }),
964        };
965        let pod = [
966            kv("service.name", "checkout"),
967            kv("service.instance.id", "7"),
968        ];
969        // Reordered and with a non-identifying attribute added, which is the
970        // drift `identity.rs` is built to see through — the point being that
971        // placement inherits that property rather than re-deriving it.
972        let drifted = [
973            kv("k8s.node.name", "node-4"),
974            kv("service.instance.id", "7"),
975            kv("service.name", "checkout"),
976        ];
977        for n in 1..8 {
978            let want = slot(&pod, 0, n);
979            assert!(want < n);
980            for i in 0..5 {
981                assert_eq!(slot(&pod, i, n), want, "n={n} i={i}");
982                assert_eq!(slot(&drifted, i, n), want, "n={n} i={i} drifted");
983            }
984        }
985
986        // Nothing identifying: spread by position, so a deployment of
987        // unidentified senders does not pile onto one node.
988        let n = 3;
989        let spread: Vec<usize> = (0..6).map(|i| slot(&[], i, n)).collect();
990        assert_eq!(spread, [0, 1, 2, 0, 1, 2]);
991    }
992
993    /// The scanner, on the shapes an envelope actually contains — a row whose
994    /// string value holds the characters it splits on being the one that turns
995    /// a merge into nonsense rather than into an error.
996    #[test]
997    fn the_scanner_splits_on_structure_and_not_on_punctuation_inside_strings() {
998        assert_eq!(pieces("[]").unwrap(), Vec::<&str>::new());
999        assert_eq!(pieces("{ }").unwrap(), Vec::<&str>::new());
1000        assert_eq!(pieces("[1, 2]").unwrap(), ["1", "2"]);
1001        assert_eq!(
1002            pieces(r#"[{"a":{"b":[1,2]}},{"c":"x,y"}]"#).unwrap(),
1003            [r#"{"a":{"b":[1,2]}}"#, r#"{"c":"x,y"}"#]
1004        );
1005        // A log body with a brace and an escaped quote in it, which is most log
1006        // bodies that were ever worth reading.
1007        assert_eq!(
1008            pieces(r#"[{"body":"{\"level\": \"warn\"}, retrying"},{"body":"ok"}]"#).unwrap(),
1009            [
1010                r#"{"body":"{\"level\": \"warn\"}, retrying"}"#,
1011                r#"{"body":"ok"}"#
1012            ]
1013        );
1014        for bad in ["", "[1,2", "{\"a\":1", "[\"unterminated]"] {
1015            assert!(pieces(bad).is_err(), "{bad:?}");
1016        }
1017
1018        let o = object(r#"{"rows":[{"a":1}],"stats":{"n":2},"next":"1.2.3.4"}"#).unwrap();
1019        assert_eq!(field(&o, "rows").unwrap(), "[{\"a\":1}]");
1020        assert_eq!(
1021            count(&object(field(&o, "stats").unwrap()).unwrap(), "n").unwrap(),
1022            2
1023        );
1024        assert_eq!(unquote(field(&o, "next").unwrap()).unwrap(), "1.2.3.4");
1025        assert!(field(&o, "cursors").is_err());
1026        assert!(unquote("1.2.3.4").is_err());
1027        assert!(field_of("\"a\" 1").is_err());
1028    }
1029
1030    /// A proxy with no replicas answers nothing, so it is refused at startup
1031    /// rather than at the first query.
1032    #[test]
1033    fn a_proxy_with_no_replicas_is_refused_where_the_operator_can_see_it() {
1034        assert!(Proxy::new(Vec::new(), 1).is_err());
1035        assert!(Proxy::new(vec!["http://127.0.0.1:1".into()], 1).is_ok());
1036    }
1037
1038    /// What the exporter is told to do about each kind of refusal. The 503s are
1039    /// the ones that matter: reporting a transient overload as permanent drops
1040    /// the batch.
1041    #[test]
1042    fn only_the_senders_own_fault_is_passed_back_unretryable() {
1043        for pass in [400u16, 413, 415] {
1044            let s = StatusCode::from_u16(pass).unwrap();
1045            assert_eq!(retryable(s), s);
1046        }
1047        for retry in [429u16, 500, 502, 503, 504] {
1048            assert_eq!(
1049                retryable(StatusCode::from_u16(retry).unwrap()),
1050                StatusCode::SERVICE_UNAVAILABLE
1051            );
1052        }
1053    }
1054
1055    /// The three ways a replica can fail that are not a status code.
1056    ///
1057    /// A refused connection is the one every other test in this file exercises.
1058    /// These are the rest of `send`: an address that is not a URL, a node that
1059    /// accepts the connection and then says nothing, and one that announces a
1060    /// body longer than the one it sends before hanging up. Each has to come
1061    /// back as an error naming itself — a `None` or an empty page here is a
1062    /// silently short answer, which is the failure mode this whole file exists
1063    /// to not have.
1064    #[tokio::test(start_paused = true)]
1065    async fn a_replica_that_answers_badly_is_an_error_and_not_a_short_page() {
1066        // Refused before a socket is opened: a space is not a URI.
1067        let e = send("http://exa mple/v1/logs", PROTOBUF, Vec::new())
1068            .await
1069            .expect_err("a malformed address was accepted");
1070        assert!(!e.is_empty());
1071
1072        // `start_paused` is what makes the 60s bound a test and not a wait:
1073        // tokio advances its clock as soon as nothing is runnable, so the timer
1074        // fires the moment this task is the only thing left.
1075        let (_deaf, url) = deaf();
1076        let e = send(&url, PROTOBUF, Vec::new())
1077            .await
1078            .expect_err("silence was read as an answer");
1079        assert!(e.contains("no answer in 60s"), "{e}");
1080
1081        // Ten bytes promised, three sent, socket closed. hyper reports a body
1082        // that stops halfway on the request rather than on the body — the two
1083        // share one connection error — so this lands on the same line of `send`
1084        // as a refusal. It is here for the wire shape, which is the one a
1085        // replica killed mid-response actually produces.
1086        let e = send(
1087            &raw(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc"),
1088            PROTOBUF,
1089            Vec::new(),
1090        )
1091        .await
1092        .expect_err("a truncated body was read as an answer");
1093        assert!(!e.is_empty());
1094    }
1095
1096    /// A port the kernel accepts a connection on and nothing ever answers.
1097    ///
1098    /// Silence has to be a listener nobody accepts from, not a server that
1099    /// writes nothing: writing nothing still drops the socket, dropping it
1100    /// sends a FIN, and a client that reads EOF reports a dead connection
1101    /// rather than waiting out its timeout. Which of the two won used to be a
1102    /// race between the kernel's delivery and the paused clock, and it lost on
1103    /// Linux under coverage instrumentation. The handshake completes into the
1104    /// backlog with no `accept`, so the connection is open and mute for as long
1105    /// as the caller holds the listener.
1106    fn deaf() -> (std::net::TcpListener, String) {
1107        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1108        let addr = l.local_addr().unwrap();
1109        (l, format!("http://{addr}"))
1110    }
1111
1112    /// A listener that writes one canned reply to one connection and closes.
1113    ///
1114    /// Not an `axum::Router`: what these need is a server that is *wrong* at the
1115    /// HTTP level, which a correct server cannot be asked to be.
1116    fn raw(reply: &'static [u8]) -> String {
1117        use std::io::Write;
1118        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1119        let addr = l.local_addr().unwrap();
1120        std::thread::spawn(move || {
1121            let Ok((mut s, _)) = l.accept() else { return };
1122            // Not reading the request first: the reply is canned either way, and
1123            // a read that blocks on a client which has already sent everything
1124            // is a hang rather than a test.
1125            let _ = s.write_all(reply);
1126        });
1127        format!("http://{addr}")
1128    }
1129}