mira/tui/source.rs
1//! Where the TUI's answers come from.
2//!
3//! Two transports, one return type: a parsed response envelope. A local source
4//! calls `mira_core::query` on a block directory with no server anywhere in the
5//! picture — which is the whole reason the CLI is worth having, because it means
6//! a detached PVC or a dead pod's volume is still readable. A remote source
7//! POSTs the identical document to `/api/v1/*` on a running replica.
8//!
9//! Both go through `api.rs`'s parsers and `api.rs`'s envelope, so the query
10//! grammar is not reimplemented here — a filter that works against a server
11//! works against a directory because it is the same code deciding what it means.
12//!
13//! Responses are parsed with the KYAML loader, not a JSON parser. That is the
14//! KYAML-first principle paying for itself a second time: the API emits JSON,
15//! JSON is valid KYAML, and `yaml-rust2` is already in the tree for the config
16//! file. There is no JSON parsing dependency in this binary and this does not
17//! add one.
18
19use std::io::{Read, Write};
20use std::net::{TcpStream, ToSocketAddrs};
21use std::path::{Path, PathBuf};
22use std::time::Duration;
23
24use yaml_rust2::Yaml;
25
26use crate::api;
27
28pub enum Source {
29 /// A block directory, read in-process.
30 Local(PathBuf),
31 /// `host:port` of a running Mira's HTTP listener.
32 Remote(String),
33}
34
35pub const QUERY: &str = "/api/v1/query";
36pub const SERIES: &str = "/api/v1/metrics/query";
37pub const NAMES: &str = "/api/v1/metrics/names";
38pub const CORRELATE: &str = "/api/v1/correlate";
39pub const MAP: &str = "/api/v1/map";
40pub const ENTITIES: &str = "/api/v1/entities";
41/// The two read-only GETs. Both answer for the *process*, not for the blocks,
42/// which is why neither has a local arm: a directory has no uptime, no query
43/// counters and nobody evaluating rules against it.
44pub const STATS: &str = "/api/v1/stats";
45pub const ALERTS: &str = "/api/v1/alerts";
46
47impl Source {
48 pub fn label(&self) -> String {
49 match self {
50 Source::Local(p) => format!("local {}", p.display()),
51 Source::Remote(a) => format!("http {a}"),
52 }
53 }
54
55 /// Run one query and hand back the parsed envelope.
56 ///
57 /// Errors are `String` because every one of them ends up in the status bar
58 /// verbatim. A TUI that reports "query failed" and keeps the reason to
59 /// itself is worse than no TUI.
60 pub fn post(&self, route: &str, body: &str) -> Result<Yaml, String> {
61 let text = match self {
62 Source::Local(dir) => local(dir, route, body)?,
63 Source::Remote(addr) => http(addr, "POST", route, Some(body))?,
64 };
65 Self::envelope(&text)
66 }
67
68 /// Fetch one of the process-scoped documents.
69 ///
70 /// Separate from [`Source::post`] rather than a route arm inside it because
71 /// the local case is not "a route this transport does not implement" — it is
72 /// that the thing being asked about does not exist. A block directory is
73 /// readable without a server, which is the point of the local source; a node
74 /// that is not running has no counters and is not paging anyone.
75 pub fn get(&self, route: &str) -> Result<Yaml, String> {
76 let text = match self {
77 Source::Local(_) => {
78 return Err(format!(
79 "{} reports a running node; this is a directory, so open it with --addr",
80 route.rsplit('/').next().unwrap_or(route)
81 ));
82 }
83 Source::Remote(addr) => http(addr, "GET", route, None)?,
84 };
85 Self::envelope(&text)
86 }
87
88 fn envelope(text: &str) -> Result<Yaml, String> {
89 let doc = api::parse(text)?;
90 // The API answers errors as JSON too, so a 200 is not the only thing
91 // worth checking — and on the local path there is no status code at all.
92 match doc["error"].as_str() {
93 Some(e) => Err(e.to_owned()),
94 None => Ok(doc),
95 }
96 }
97}
98
99fn local(dir: &Path, route: &str, body: &str) -> Result<String, String> {
100 let now = api::now_nanos();
101 let t = std::time::Instant::now();
102 let run = |field, r: mira_core::error::Result<mira_core::query::Results>| match r {
103 Ok(r) => Ok(api::envelope(field, &r, t.elapsed())),
104 Err(e) => Err(e.to_string()),
105 };
106 match route {
107 QUERY => run(
108 "rows",
109 mira_core::query::search(dir, &api::parse_search(body, now)?),
110 ),
111 SERIES => run(
112 "series",
113 mira_core::series::series(dir, &api::parse_series(body, now)?),
114 ),
115 NAMES => {
116 let (from, to) = api::window(body, now)?;
117 run("names", mira_core::series::names(dir, from, to))
118 }
119 // The frame algebra, over a directory. `open` is empty on all three
120 // because nothing is writing here — an open block only exists inside the
121 // process that accepted the export, and this path has no ingest side.
122 CORRELATE => {
123 let (q, ops) = api::parse_correlate(body, now)?;
124 run("frame", api::correlate(dir, &q, &ops, &[], &[]))
125 }
126 MAP => {
127 let (from, to, max) = api::map_doc(&api::parse(body)?, now)?;
128 run("map", mira_core::frame::map(dir, from, to, max, &[]))
129 }
130 ENTITIES => {
131 let (from, to) = api::window(body, now)?;
132 run("entities", mira_core::frame::entities(dir, from, to, &[]))
133 }
134 other => Err(format!("no such route {other}")),
135 }
136}
137
138/// Long enough that a loaded node is not mistaken for an absent one, short
139/// enough that a wrong `--addr` is a message rather than a hang.
140const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
141
142/// HTTP/1.1 POST, one connection per request.
143///
144/// ponytail: `Connection: close` and `read_to_end`, which is what lets this
145/// skip chunked-transfer decoding and keep-alive bookkeeping entirely — the
146/// server closes the socket and EOF delimits the body. The ceiling is one TCP
147/// handshake per query, invisible next to the query itself; add pooling if the
148/// TUI ever polls faster than a human types. No TLS: Mira serves plain HTTP, and
149/// a TLS client is where the dependency budget would actually go.
150fn http(addr: &str, method: &str, path: &str, body: Option<&str>) -> Result<String, String> {
151 // Which half of the exchange failed is the diagnosis, and the errno alone
152 // does not carry it — ECONNRESET reads the same going out as coming back.
153 // A write that died is this end's socket going away mid-request; a read
154 // that died is the node. They send the operator to different machines.
155 let io = || -> Result<Vec<u8>, String> {
156 // `TcpStream::connect` has no timeout: the OS retries the SYN on its own
157 // schedule, 75 seconds on macOS and over two minutes on Linux. This is a
158 // blocking client on a single-threaded UI, so an `--addr` that
159 // blackholes — a node behind a firewall rule, a stale DNS answer, a
160 // NetworkPolicy — is not a slow query, it is a terminal that will not
161 // even take `q`. `connect_timeout` takes a `SocketAddr` and not a host
162 // string, so the resolution and the walk down the list are `connect`'s
163 // own, kept because `localhost` is `::1` before `127.0.0.1`.
164 let mut last = format!("{addr}: resolved to no address");
165 let mut sock = None;
166 for sa in addr.to_socket_addrs().map_err(|e| format!("{addr}: {e}"))? {
167 match TcpStream::connect_timeout(&sa, CONNECT_TIMEOUT) {
168 Ok(c) => {
169 sock = Some(c);
170 break;
171 }
172 Err(e) => last = format!("{addr}: {e}"),
173 }
174 }
175 let mut s = sock.ok_or(last)?;
176 s.set_read_timeout(Some(Duration::from_secs(60)))
177 .map_err(|e| format!("{addr}: {e}"))?;
178 // Beside the read timeout for the same reason: a peer that stops
179 // reading stalls the write, and this thread is drawing the screen.
180 s.set_write_timeout(Some(Duration::from_secs(60)))
181 .map_err(|e| format!("{addr}: {e}"))?;
182 let body = body.unwrap_or("");
183 write!(
184 s,
185 "{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\n\
186 Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
187 body.len()
188 )
189 .and_then(|()| s.flush())
190 .map_err(|e| format!("{addr}: sending the request: {e}"))?;
191 let mut buf = Vec::new();
192 s.read_to_end(&mut buf)
193 .map_err(|e| format!("{addr}: reading the response: {e}"))?;
194 Ok(buf)
195 };
196 let raw = io()?;
197 let split = raw
198 .windows(4)
199 .position(|w| w == b"\r\n\r\n")
200 .ok_or_else(|| format!("{addr}: response has no header terminator"))?;
201 let head = String::from_utf8_lossy(&raw[..split]);
202 let text = String::from_utf8_lossy(&raw[split + 4..]).into_owned();
203
204 let status = head
205 .lines()
206 .next()
207 .and_then(|l| l.split_whitespace().nth(1))
208 .unwrap_or("?");
209 match status {
210 "200" => Ok(text),
211 // The body is the JSON error envelope; hand it up so `post` can pull the
212 // message out of it rather than showing the caller a bare number.
213 _ if text.trim_start().starts_with('{') => Ok(text),
214 _ => Err(format!("{addr} returned HTTP {status}: {}", text.trim())),
215 }
216}
217
218/// Normalise what someone types after `--addr` into `host:port`.
219///
220/// `http://` because that is what they will copy out of a browser, and a bare
221/// host because that is what they will type. Port 4318 is where the query API
222/// lives, so it is the only sensible default.
223pub fn parse_addr(s: &str) -> Result<String, String> {
224 let s = s
225 .trim()
226 .trim_start_matches("http://")
227 .trim_end_matches('/')
228 .trim();
229 if s.starts_with("https://") {
230 return Err("--addr: Mira serves plain HTTP; there is no TLS client here".into());
231 }
232 if s.is_empty() {
233 return Err("--addr needs a host".into());
234 }
235 // Only a bare `host` needs the default appended. An IPv6 literal already
236 // carries colons inside its brackets, so counting them would be wrong.
237 Ok(
238 match s
239 .rsplit(':')
240 .next()
241 .is_some_and(|p| p.parse::<u16>().is_ok())
242 {
243 true => s.to_owned(),
244 false => format!("{s}:4318"),
245 },
246 )
247}
248
249/// A listener that answers each connection with the next canned reply, in
250/// order, and stops when they run out.
251///
252/// Out of the test module because the TUI's tests need it too: the alert and
253/// diagnostics panes only exist against a remote source, so there is no way to
254/// render them without something on a socket. A second copy of this would be a
255/// second set of HTTP framing bugs.
256#[cfg(test)]
257pub fn serve(replies: Vec<String>) -> String {
258 let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
259 let addr = l.local_addr().unwrap().to_string();
260 std::thread::spawn(move || {
261 for reply in replies {
262 let Ok((mut s, _)) = l.accept() else { return };
263 // The whole request, head then body. Replying while the body is
264 // still unread closes the socket with data in the receive queue,
265 // which is an RST on the client rather than the answer — a real
266 // server has the same obligation.
267 let mut head = Vec::new();
268 let mut byte = [0u8; 1];
269 while std::io::Read::read(&mut s, &mut byte).unwrap_or(0) == 1 {
270 head.push(byte[0]);
271 if head.ends_with(b"\r\n\r\n") {
272 break;
273 }
274 }
275 let len: usize = String::from_utf8_lossy(&head)
276 .lines()
277 .find_map(|l| l.strip_prefix("Content-Length: ")?.trim().parse().ok())
278 .unwrap_or(0);
279 let mut body = vec![0u8; len];
280 let _ = std::io::Read::read_exact(&mut s, &mut body);
281 let _ = s.write_all(reply.as_bytes());
282 }
283 });
284 addr
285}
286
287/// An HTTP/1.1 200 carrying `body`, for [`serve`].
288#[cfg(test)]
289pub fn ok(body: &str) -> String {
290 format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{body}")
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296
297 #[test]
298 fn addresses_normalise_to_host_port() {
299 assert_eq!(parse_addr("localhost").unwrap(), "localhost:4318");
300 assert_eq!(parse_addr("http://mira:4318/").unwrap(), "mira:4318");
301 assert_eq!(parse_addr("10.0.0.4:9000").unwrap(), "10.0.0.4:9000");
302 assert_eq!(parse_addr("[::1]:4318").unwrap(), "[::1]:4318");
303 // No port, and the last colon-segment is not a number: still a host.
304 assert_eq!(parse_addr("[::1]").unwrap(), "[::1]:4318");
305 assert!(parse_addr("https://mira").is_err());
306 assert!(parse_addr(" ").is_err());
307 }
308
309 /// The response the API emits has to survive the loader the config file
310 /// uses. This is the "JSON is valid KYAML" claim, checked on the exact
311 /// envelope rather than taken from the spec.
312 #[test]
313 fn a_response_envelope_parses_with_the_kyaml_loader() {
314 let text = r#"{"rows":[{"body":"line1\nline2 \"q\" \u0001","severity_number":17,
315 "ratio":0.5,"ok":true,"gone":null,
316 "attributes":{"service.name":"checkout"}}],
317 "stats":{"blocks_total":69,"blocks_scanned":1,
318 "rows_scanned":100,"rows_matched":2}}"#;
319 let d = api::parse(text).unwrap();
320 let row = &d["rows"][0];
321 assert_eq!(row["body"].as_str().unwrap(), "line1\nline2 \"q\" \u{1}");
322 assert_eq!(row["severity_number"].as_i64().unwrap(), 17);
323 assert_eq!(row["ratio"].as_f64().unwrap(), 0.5);
324 assert!(row["ok"].as_bool().unwrap());
325 assert!(row["gone"].is_null());
326 assert_eq!(
327 row["attributes"]["service.name"].as_str().unwrap(),
328 "checkout"
329 );
330 assert_eq!(d["stats"]["blocks_scanned"].as_i64().unwrap(), 1);
331 }
332
333 /// The claim that pays for this whole module: a block directory answers with
334 /// nothing running. No server, no port, no process that has to have survived
335 /// — a detached PVC is still readable.
336 ///
337 /// All four route arms go through here because the field name each one puts
338 /// in the envelope (`rows`, `series`, `names`) is what the TUI reads back
339 /// out, and a route that answered under the wrong key would look like an
340 /// empty result rather than an error.
341 #[test]
342 fn a_local_source_answers_out_of_a_directory_with_no_server() {
343 let dir = std::env::temp_dir().join(format!("mira-src-{}", std::process::id()));
344 let _ = std::fs::remove_dir_all(&dir);
345 std::fs::create_dir_all(&dir).unwrap();
346
347 let mut b = mira_core::logs::LogsBuilder::new();
348 b.append_request(&crate::e2e::logs_export("checkout", 1_000, 6))
349 .unwrap();
350 let sealed = b.finish().unwrap();
351 mira_core::block::publish(&dir, "logs", mira_core::block::node_id("a"), 0, 0, &sealed)
352 .unwrap();
353
354 let src = Source::Local(dir.clone());
355 assert!(src.label().starts_with("local "));
356
357 let d = src
358 .post(QUERY, r#"{"signal":"logs","from":0,"to":100000,"limit":2}"#)
359 .unwrap();
360 assert_eq!(d["rows"].as_vec().unwrap().len(), 2);
361 assert_eq!(d["stats"]["rows_matched"].as_i64().unwrap(), 6);
362
363 // No metrics in this directory, so these answer empty — which is the
364 // point: they answer, under their own key, rather than erroring.
365 // The name listing takes a window and nothing else — the same document
366 // the TUI sends it — because a key an endpoint does not implement is now
367 // an error rather than a silently dropped filter.
368 for (route, field, body) in [
369 (SERIES, "series", r#"{"name":"anything"}"#),
370 (NAMES, "names", "{}"),
371 ] {
372 let d = src.post(route, body).unwrap();
373 assert!(d[field].as_vec().unwrap().is_empty(), "{route}");
374 assert_eq!(d["stats"]["blocks_total"].as_i64().unwrap(), 0);
375 }
376
377 // The entity facet reads the resource tables of all three signals, so
378 // the one service in the logs block above is in it.
379 let d = src.post(ENTITIES, r#"{"from":0,"to":100000}"#).unwrap();
380 assert_eq!(d["entities"][0]["name"].as_str().unwrap(), "checkout");
381
382 // The frame algebra reads the same directory. Correlate anchors on the
383 // logs above, so it finds their entity; the map is built from spans and
384 // there are none, so it answers an empty graph rather than an error.
385 let d = src
386 .post(
387 CORRELATE,
388 r#"{"signal":"logs","from":0,"to":100000,"expand":["traces","peers"]}"#,
389 )
390 .unwrap();
391 assert_eq!(
392 d["frame"]["entities"][0]["name"].as_str().unwrap(),
393 "checkout"
394 );
395 assert!(!d["frame"]["truncated"].as_bool().unwrap());
396
397 let d = src.post(MAP, r#"{"from":0,"to":100000}"#).unwrap();
398 assert!(d["map"]["nodes"].as_vec().unwrap().is_empty());
399 assert_eq!(d["map"]["unresolved"].as_i64().unwrap(), 0);
400
401 // Every one of them is strict about its document, the same way the
402 // server is — a key an endpoint does not implement is an error, not a
403 // filter that was quietly dropped.
404 for (route, body, want) in [
405 (CORRELATE, r#"{"expand":["sideways"]}"#, "sideways"),
406 (MAP, r#"{"limit":5}"#, "unknown query key"),
407 (ENTITIES, r#"{"to":"soon"}"#, "soon"),
408 ] {
409 let e = src.post(route, body).unwrap_err();
410 assert!(e.contains(want), "{route}: {e}");
411 }
412
413 // A malformed document is the engine's error, reported verbatim rather
414 // than swallowed into "query failed".
415 let e = src.post(QUERY, r#"{"signal":"nope"}"#).unwrap_err();
416 assert!(e.contains("nope"), "{e}");
417 assert!(
418 src.post("/api/v1/nope", "{}")
419 .unwrap_err()
420 .contains("route")
421 );
422
423 let _ = std::fs::remove_dir_all(&dir);
424 }
425
426 /// Enough HTTP to read an answer, and no more — so what it does with the
427 /// three replies it can get has to be pinned down here.
428 ///
429 /// A non-200 carrying a JSON body is handed up rather than reported as a
430 /// number, because the body is the error envelope and the message inside it
431 /// is the only useful thing on the screen.
432 #[test]
433 fn a_remote_source_reports_what_the_server_actually_said() {
434 let ok = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"rows\":[],\
435 \"stats\":{\"blocks_total\":0,\"blocks_scanned\":0,\"rows_scanned\":0,\
436 \"rows_matched\":0}}";
437 let bad = "HTTP/1.1 400 Bad Request\r\n\r\n{\"error\":\"unknown signal \\\"nope\\\"\"}";
438 let plain = "HTTP/1.1 502 Bad Gateway\r\n\r\nupstream is down";
439 let truncated = "HTTP/1.1 200 OK\r\nContent-Type: application/json";
440
441 let src = Source::Remote(serve(
442 [ok, bad, plain, truncated].map(str::to_owned).to_vec(),
443 ));
444 assert!(src.label().starts_with("http "));
445
446 let d = src.post(QUERY, "{}").unwrap();
447 assert!(d["rows"].as_vec().unwrap().is_empty());
448 // 400, but the message is what reaches the status bar, not the number.
449 assert_eq!(
450 src.post(QUERY, "{}").unwrap_err(),
451 r#"unknown signal "nope""#
452 );
453 let e = src.post(QUERY, "{}").unwrap_err();
454 assert!(e.contains("502") && e.contains("upstream is down"), "{e}");
455 assert!(
456 src.post(QUERY, "{}").unwrap_err().contains("terminator"),
457 "a reply with no blank line is not an empty answer"
458 );
459
460 // Nothing listening at all. The address is in the message because the
461 // usual cause is a typo in `--addr`.
462 let dead = Source::Remote("127.0.0.1:1".into());
463 let e = dead.post(QUERY, "{}").unwrap_err();
464 assert!(e.starts_with("127.0.0.1:1: "), "{e}");
465 }
466
467 /// A connection that dies while the request is still going out says so, in
468 /// those words.
469 ///
470 /// Every other failure in `http` is read on the way back; this one happens
471 /// before a single byte of answer exists, and the `?` on the write is the
472 /// only thing between it and a `read_to_end` of nothing — which would reach
473 /// the caller as "the response has no header terminator", blaming the
474 /// server for a socket that died under this end. The message has to name
475 /// the send, because an operator reading it off the status bar decides from
476 /// it which machine to go and look at.
477 #[test]
478 fn a_request_that_cannot_be_written_reports_the_write_and_not_the_reply() {
479 let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
480 let addr = l.local_addr().unwrap().to_string();
481 std::thread::spawn(move || {
482 // Accepted and closed with the request unread, which is what a
483 // server being rolled does to every connection it is holding. Once
484 // per connection, because the body below may take more than one.
485 for s in l.incoming() {
486 match s {
487 Ok(s) => drop(s.shutdown(std::net::Shutdown::Both)),
488 Err(_) => return,
489 }
490 }
491 });
492 // The write has to still be running when the reset lands, and that is
493 // a property of this host's send buffer, not of a number picked here:
494 // a request that fits in it whole is written successfully and the
495 // failure moves to the read. So grow the body until it cannot fit.
496 // ponytail: `SO_SNDBUF` would answer directly instead of doubling, and
497 // reading it means `libc` — a dependency for one `getsockopt`, against
498 // a tree of 148.
499 let mut e = String::new();
500 for mib in [1usize, 8, 64] {
501 let body = format!(r#"{{"signal":"logs","q":"{}"}}"#, "x".repeat(mib << 20));
502 e = Source::Remote(addr.clone()).post(QUERY, &body).unwrap_err();
503 if e.contains("sending the request") {
504 break;
505 }
506 }
507 assert!(
508 e.starts_with(&format!("{addr}: sending the request: ")),
509 "the write failed and the message says which half died: {e}"
510 );
511 }
512
513 /// A name that resolves to more than one address is tried down the list.
514 ///
515 /// `TcpStream::connect` does that itself; `connect_timeout` takes one
516 /// `SocketAddr`, so bounding the connect meant resolving here and looping.
517 /// On a dual-stack host `localhost` is `::1` first and `127.0.0.1` second,
518 /// and a listener bound to `127.0.0.1` is only reachable through the
519 /// second — so taking `.next()` and stopping would make `--addr localhost`
520 /// stop working on exactly the machine a contributor runs this on.
521 ///
522 /// This is the regression guard for that change, not a test of the timeout:
523 /// making a host *drop* a SYN rather than refuse it needs a firewall rule,
524 /// and an unroutable literal is the routing table answering, not this code.
525 ///
526 /// Mutation check: `.next()` instead of the loop, and this fails wherever
527 /// `::1` sorts first.
528 #[test]
529 fn a_name_resolving_to_several_addresses_is_tried_down_the_list() {
530 let ok = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"rows\":[],\
531 \"stats\":{\"blocks_total\":0,\"blocks_scanned\":0,\"rows_scanned\":0,\
532 \"rows_matched\":0}}";
533 // `serve` binds 127.0.0.1, so reaching it through `localhost` is the
534 // whole assertion: the address that resolves first may be `::1`.
535 let bound = serve(vec![ok.into()]);
536 let port = bound.rsplit(':').next().unwrap();
537 let d = Source::Remote(format!("localhost:{port}"))
538 .post(QUERY, "{}")
539 .unwrap();
540 assert!(d["rows"].as_vec().unwrap().is_empty());
541 }
542}