mira/config.rs
1//! Deployment configuration: KYAML with OmegaConf-style interpolation.
2//!
3//! # Why KYAML
4//!
5//! Principle 5 is KYAML-first, and this file is where it starts. KYAML is a
6//! strict subset of YAML 1.2 — explicit `{}` and `[]`, every string
7//! double-quoted, indentation carrying no meaning — so any YAML parser reads it
8//! and no YAML parser can guess wrong about it.
9//!
10//! The guessing is the point. An unquoted scalar is resolved by pattern-match
11//! against a table, and *which* table depends on the YAML version and the
12//! implementation. The famous case — a replica honestly named `no` becoming the
13//! boolean false — is YAML 1.1, and does not happen with the parser below.
14//! Measured against that parser, these do:
15//!
16//! * `node: False` → `Boolean(false)` → the string `"false"`, case flipped.
17//! * `node: 0x1f` → `Integer(31)` → the string `"31"`. The text changed.
18//! * `node: null` → `Null`, which reads as "key absent", so the default is used
19//! and nothing is reported.
20//!
21//! A different parser, or the same one a major version later, has a different
22//! list. That is the real argument: the correct reading of an unquoted scalar is
23//! not a property of the document. Quoting makes it one, for four characters,
24//! and a generating model gets the same guarantee a careful human would — which
25//! is why the principle exists.
26//!
27//! Enforcement is [`scalar`]: every value Mira reads out of this file is a
28//! string, so anything that arrived as another type is refused at boot with a
29//! message saying to quote it. A list or a map never reaches a value at all, so
30//! [`check_keys`] refuses those, by path — quoting is not the fix for a shape.
31//!
32//! # Why there is a config file at all
33//!
34//! Principle 2c is "self-driving, no tuning knobs", which this appears to
35//! violate and does not. The distinction that matters:
36//!
37//! * A **knob** is a number the engine could work out for itself and instead
38//! asks a human to guess — block size, buffer depth, flush interval, cache
39//! sizes, compaction thresholds. None of those are here, and none of them will
40//! be. They live in `pipeline::Config`, derived, with no path from this file.
41//! * **Deployment description** is what the engine cannot know: which addresses
42//! to listen on, which directory is the data directory, how long the retention
43//! policy is, what this replica is called. That is not tuning. Refusing to
44//! accept it does not make an engine self-driving, it makes it unusable.
45//!
46//! The boundary is structural rather than documentary: this struct has no field
47//! that affects how the engine performs, only where it runs — with one
48//! deliberate exception, `ingest.wal`, which is not a number to guess but a
49//! choice between two correct durability promises that no measurement can make
50//! for the operator. Its own doc comment argues that.
51//!
52//! # Interpolation
53//!
54//! ```yaml
55//! {
56//! "node": "${env:HOSTNAME,mira-0}", # env var, default after the comma
57//! "storage": {
58//! "dir": "/var/lib/${node}", # another key, by dotted path
59//! "retention": "7d",
60//! },
61//! }
62//! ```
63//!
64//! * `${env:NAME}` — required; a missing variable is a startup error, not an
65//! empty string. Silently defaulting is how a staging cluster ends up writing
66//! to a production bucket.
67//! * `${env:NAME,default}` — everything after the first comma is the default,
68//! verbatim, including further `${...}`.
69//! * `${dotted.path}` — another key in this file. Resolved recursively; a cycle
70//! is a startup error naming the cycle.
71//! * `$${` — a literal `${`.
72//!
73//! Resolution is lazy: only keys actually read are expanded, so an unused key
74//! with a broken reference cannot stop the process from booting.
75//!
76//! There is deliberately no second `MIRA_*` environment-override mechanism.
77//! `${env:...}` already covers every case, explicitly and visibly in one file,
78//! and two ways to set the same value is exactly the complexity this is meant to
79//! avoid.
80
81use std::net::SocketAddr;
82use std::path::{Path, PathBuf};
83use std::time::Duration;
84
85use yaml_rust2::{Yaml, YamlLoader};
86
87type Error = String;
88type Result<T> = std::result::Result<T, Error>;
89
90/// How `${env:NAME}` is resolved, handed to the parser rather than read out of
91/// the process.
92///
93/// Not an abstraction for its own sake — it is what lets the tests supply an
94/// environment without writing one. `std::env::set_var` is `unsafe` in edition
95/// 2024 because it can reallocate `environ` under a concurrent `getenv`, in any
96/// thread, including one inside libc; `cargo test` runs this binary's tests as
97/// threads of a single process, and at least two of them read: `term.rs` looks
98/// up `MIRA_PTY_CHILD`, and every `tui.rs` test that formats a timestamp reaches
99/// `localtime_r`, which reads `TZ`. No lock closes that, because the libc reader
100/// will not take it. Not writing does.
101type Env<'a> = &'a dyn Fn(&str) -> Option<String>;
102
103#[derive(Debug, Clone)]
104pub struct Config {
105 /// This replica's name. It is hashed into the name of every block
106 /// directory this node writes, so two replicas sharing a volume cannot
107 /// collide (see `mira_core::block`).
108 pub node: String,
109 /// The address OpenTelemetry exporters send to over gRPC.
110 pub grpc: SocketAddr,
111 /// The address for everything else: OpenTelemetry over HTTP, the query
112 /// API, the MCP endpoint and the web UI all answer on this one port.
113 pub http: SocketAddr,
114 /// Where the data goes. This directory is all the state there is: no
115 /// catalogue, no index file, nothing outside it to keep in sync.
116 pub data_dir: PathBuf,
117 /// How long data is kept. Deleting happens a whole block at a time, so the
118 /// oldest data goes in steps rather than row by row.
119 pub retention: Duration,
120 /// Where to copy a block before retention deletes it, or `None` to just
121 /// delete it. Off by default: deleting is the documented behaviour, and a
122 /// flag that silently started keeping everything would be a disk bill
123 /// nobody asked for.
124 ///
125 /// See `mira_core::offload`.
126 pub offload: Option<String>,
127 /// The largest single export either listener will accept.
128 ///
129 /// One number covers the HTTP body limit, the gRPC decode limit and the
130 /// ceiling on what a gzip body may inflate to. See
131 /// `receiver::Receivers::max_request_bytes` for why.
132 pub max_request_bytes: usize,
133 /// How many exports may wait for a writer before the next one is held
134 /// back — and refused with a 503 only if no slot frees up within
135 /// `pipeline::ADMIT_WAIT`.
136 ///
137 /// The concurrency limit Mira did not used to have. It was a fixed 128 and
138 /// a full queue meant an immediate 503, so a wide collector fleet spent
139 /// most of its time being told to retry: that sweep shed 93% of exports at
140 /// 96 connections and landed at a third of the two-connection rate. Waiting
141 /// briefly for a slot instead (`ADMIT_WAIT`, `pipeline.rs`) took the same
142 /// row to nothing shed and double the throughput, and twenty-one
143 /// consecutive runs of the whole sweep have refused nothing since. This
144 /// knob is the other half — an operator whose fleet is wide can buy queue
145 /// depth with memory they have spare.
146 ///
147 /// It buys queueing, not throughput: the flusher drains at the rate it
148 /// drains, and a queue deep enough to hide a permanently overloaded node
149 /// just moves the shed into a latency tail. Size it to absorb a burst, not
150 /// to avoid a 503. Each slot can hold a decoded export, so the worst case is
151 /// this times [`Config::max_request_bytes`] times three signals resident.
152 pub queue: usize,
153 /// How many writer tasks a signal runs, or 0 for one per two cores.
154 ///
155 /// One shard per core is the sanctioned unit (docs/architecture/ingest.md section 4);
156 /// this is only here so the number can be pinned when the machine lies
157 /// about its core count. `available_parallelism` honours cgroup v1 and v2
158 /// CPU quotas, so a container with a quota set needs no help here — but
159 /// `cpu.shares`/`cpu.weight` is a relative weight rather than a quota and
160 /// reads as the whole machine, a shared host often sets no quota at all, a
161 /// non-Linux container runtime leaves nothing to read, and hyperthreads
162 /// count as cores. A 96-core host running Mira on two cores' worth of any
163 /// of those would otherwise start the capped sixteen flushers per signal
164 /// and publish sixteen files per seal window. Set it to the cores the
165 /// process actually gets, or to 1 to get the pre-0.0.3 behaviour.
166 ///
167 /// Shards split `queue`, they do not multiply it: the resident worst case
168 /// is the same whatever this is. Capped at `pipeline::MAX_SHARDS`.
169 pub shards: usize,
170 /// Acknowledge an export once it has been written to the log, rather than
171 /// waiting for the block that holds it to be sealed.
172 ///
173 /// The one durability decision Mira does not make for the operator, and it
174 /// is not the tuning knob the module docs above rule out: both settings are
175 /// correct, they promise different things, and nothing the engine can
176 /// measure says which promise a deployment wants. On, the default, is the
177 /// log's: the export survives the process dying, `panic = "abort"`, SIGKILL
178 /// and the OOM killer, but not power loss in the last [`WAL_SYNC_PERIOD`],
179 /// at a p99 in the microseconds. Off is the block's — acknowledged means
180 /// fsynced and renamed, which survives power loss too, at a p99 of 2.6 s
181 /// because that is how long a lightly-loaded block takes to fill.
182 ///
183 /// Read-your-writes holds either way: the open block is queryable (section 4),
184 /// so a record is visible from the acknowledgement whether or not it has
185 /// been published yet.
186 ///
187 /// [`WAL_SYNC_PERIOD`]: crate::pipeline::WAL_SYNC_PERIOD
188 pub wal: bool,
189 /// Store this node's own telemetry in this node, as ordinary metrics.
190 ///
191 /// Mira already knows everything in `/api/v1/stats`; what it does not do by
192 /// default is remember it. On, a task samples those counters every
193 /// [`Config::telemetry_interval`] and submits them through the metrics
194 /// ingest path like any other exporter would — so `mira.ingest.rows`,
195 /// `mira.query.latency_ms` and the rest become series a chart, an alert rule
196 /// or an agent can read with no exporter, no scrape target and no second
197 /// system to stand up.
198 ///
199 /// Off by default, because it is not free and the operator should choose to
200 /// spend it: the samples are rows, they are subject to
201 /// [`Config::retention`] like everything else, and a node storing its own
202 /// telemetry is a node whose disk usage no longer goes to zero when nothing
203 /// is being sent to it.
204 ///
205 /// Self-import is the only destination. Shipping these somewhere else is
206 /// what an OTLP exporter is for, and Mira is not going to grow a second one
207 /// pointed at itself.
208 pub self_telemetry: bool,
209 /// How often self-telemetry samples this node's counters.
210 ///
211 /// A sample is one point per series, so this is the resolution of every
212 /// chart drawn from it and also its cost. The default matches what a
213 /// collector's own scrape interval usually is; below a second it is
214 /// measuring the sampler.
215 pub telemetry_interval: Duration,
216 /// A file of alerting rules ([`crate::alert`]), or none — and none means
217 /// Mira does not alert.
218 ///
219 /// Deployment description rather than a knob, and the same argument as the
220 /// data directory: what to page on is a thing the engine cannot know. It is
221 /// a path rather than an inline section for two reasons — a rules list is a
222 /// list of maps, which this file's closed-scalar shape refuses on purpose,
223 /// and rules change on a different cadence to addresses, so they belong in
224 /// a different file and a different review.
225 ///
226 /// Absent means alerting is off, which is also the coordination mechanism:
227 /// N replicas over one block directory would each page, so exactly one
228 /// replica gets this key. See [`crate::alert`].
229 pub alerts: Option<PathBuf>,
230
231 /// The storage nodes `mira proxy` sits in front of, and nothing else reads.
232 ///
233 /// Empty on a storage node, and [`crate::proxy`] refuses to start without
234 /// at least one — so the two modes cannot be confused for each other by a
235 /// config that half-says which one it meant.
236 pub replicas: Vec<String>,
237}
238
239impl Default for Config {
240 fn default() -> Self {
241 Self {
242 node: "mira".into(),
243 grpc: "0.0.0.0:4317".parse().unwrap(),
244 http: "0.0.0.0:4318".parse().unwrap(),
245 data_dir: PathBuf::from("./mira-data"),
246 retention: Duration::from_secs(7 * 24 * 3600),
247 offload: None,
248 // Eight times axum's default and four times tonic's. A stock
249 // collector batches 8192 records, which is already past 2 MiB of
250 // spans, and an exporter reads 413 as permanent — so the cost of
251 // this being too small is dropped data, while the cost of it being
252 // too large is bounded resident bytes per in-flight request.
253 max_request_bytes: 16 << 20,
254 // What it has always been, kept as the default so that raising it
255 // is a decision an operator makes with the sweep in front of them
256 // rather than a number that quietly moved under everyone.
257 queue: 128,
258 // Auto: `pipeline::shard_count` reads the core count at startup.
259 shards: 0,
260 // On, now that the open block is queryable (section 4). The reason it
261 // was off was that acking before the seal let a query miss data the
262 // sender had been told was stored; the snapshot closes that, so
263 // what is left is a three-orders-of-magnitude better ack latency
264 // against a strictly weaker crash promise. That is the trade the
265 // overwhelming majority of collectors already assume they have.
266 wal: true,
267 self_telemetry: false,
268 telemetry_interval: Duration::from_secs(15),
269 alerts: None,
270 replicas: Vec::new(),
271 }
272 }
273}
274
275impl Config {
276 pub fn load(path: &Path) -> Result<Self> {
277 let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
278 Self::parse(&text).map_err(|e| format!("{}: {e}", path.display()))
279 }
280
281 pub fn parse(text: &str) -> Result<Self> {
282 Self::parse_with(text, &|k| std::env::var(k).ok())
283 }
284
285 /// [`Config::parse`] against a supplied environment. See [`Env`].
286 fn parse_with(text: &str, env: Env) -> Result<Self> {
287 let docs = YamlLoader::load_from_str(text).map_err(|e| e.to_string())?;
288 let root = docs.into_iter().next().unwrap_or(Yaml::Null);
289 let mut cfg = Config::default();
290
291 if let Some(v) = get(&root, "node", env)? {
292 cfg.node = v;
293 }
294 if let Some(v) = get(&root, "listen.grpc", env)? {
295 cfg.grpc = v.parse().map_err(|e| format!("listen.grpc: {e}"))?;
296 }
297 if let Some(v) = get(&root, "listen.http", env)? {
298 cfg.http = v.parse().map_err(|e| format!("listen.http: {e}"))?;
299 }
300 if let Some(v) = get(&root, "storage.dir", env)? {
301 cfg.data_dir = PathBuf::from(v);
302 }
303 if let Some(v) = get(&root, "storage.retention", env)? {
304 cfg.retention = duration(&v).map_err(|e| format!("storage.retention: {e}"))?;
305 }
306 if let Some(v) = get(&root, "storage.offload", env)? {
307 cfg.offload = Some(v);
308 }
309 if let Some(v) = get(&root, "ingest.max_request_bytes", env)? {
310 cfg.max_request_bytes =
311 bytes(&v).map_err(|e| format!("ingest.max_request_bytes: {e}"))?;
312 }
313 if let Some(v) = get(&root, "ingest.queue", env)? {
314 cfg.queue = positive(&v).map_err(|e| format!("ingest.queue: {e}"))?;
315 }
316 if let Some(v) = get(&root, "ingest.shards", env)? {
317 cfg.shards = whole(&v).map_err(|e| format!("ingest.shards: {e}"))?;
318 }
319 if let Some(v) = get(&root, "ingest.wal", env)? {
320 cfg.wal = boolean(&v).map_err(|e| format!("ingest.wal: {e}"))?;
321 }
322 if let Some(v) = get(&root, "telemetry.self", env)? {
323 cfg.self_telemetry = boolean(&v).map_err(|e| format!("telemetry.self: {e}"))?;
324 }
325 if let Some(v) = get(&root, "telemetry.interval", env)? {
326 cfg.telemetry_interval =
327 duration(&v).map_err(|e| format!("telemetry.interval: {e}"))?;
328 }
329 if let Some(v) = get(&root, "alerts.rules", env)? {
330 cfg.alerts = Some(PathBuf::from(v));
331 }
332 if let Some(v) = get(&root, "proxy.replicas", env)? {
333 cfg.replicas = replicas(&v).map_err(|e| format!("proxy.replicas: {e}"))?;
334 }
335 check_keys(&root, "")?;
336 Ok(cfg)
337 }
338}
339
340/// Every path this file may contain, in the order [`Config::parse`] reads them.
341const KNOWN: [&str; 14] = [
342 "node",
343 "listen.grpc",
344 "listen.http",
345 "storage.dir",
346 "storage.retention",
347 "storage.offload",
348 "ingest.max_request_bytes",
349 "ingest.queue",
350 "ingest.shards",
351 "ingest.wal",
352 "telemetry.self",
353 "telemetry.interval",
354 "alerts.rules",
355 "proxy.replicas",
356];
357
358/// Refuse a key Mira does not read, or a shape it cannot read.
359///
360/// The `get`s above are silent about everything they do not name, so
361/// `storage.retension` and a `retention` nested one level too deep both boot
362/// happily on the 7-day default and surface a week later as a full disk. A flag
363/// Mira does not know is already `unknown flag --nope`; there is no reason a file
364/// should be the lenient half of the same interface.
365///
366/// `lookup` is just as silent about a value of the wrong *shape* — a list where
367/// a string belongs, a string where a section belongs — and the outcome is
368/// identical: the default, in silence. So the structure is checked here too,
369/// where the full path is in hand to name.
370///
371/// The closed set is also what makes deleting a setting safe: a key that no
372/// longer exists becomes a startup error naming it, rather than a value the
373/// operator still believes is in effect.
374fn check_keys(node: &Yaml, prefix: &str) -> Result<()> {
375 let Yaml::Hash(h) = node else { return Ok(()) };
376 for (k, v) in h {
377 // Keys obey the same rule as values, and for the same reason: `2: x` is
378 // a key nobody typed. `scalar` says it with the message that teaches it.
379 let path = match (prefix, scalar(k)?.unwrap_or_default()) {
380 ("", name) => name,
381 (p, name) => format!("{p}.{name}"),
382 };
383 // A name is acceptable as a whole key or as the *prefix* of one —
384 // `listen` is a section only because `listen.grpc` exists. Judging the
385 // name rather than waiting for a leaf under it is what makes the set
386 // closed: `{ "cluster": {} }` is exactly how an operator writes a
387 // section they are about to fill in, and testing leaves only would let
388 // it boot in silence and look accepted.
389 let known = KNOWN.iter().any(|k| {
390 *k == path
391 || k.strip_prefix(path.as_str())
392 .is_some_and(|r| r.starts_with('.'))
393 });
394 if !known {
395 return Err(format!(
396 "unknown key {path:?}. Mira reads exactly {}; see https://miradb.dev/config/",
397 KNOWN.join(", ")
398 ));
399 }
400 // Shape has to match the name: a section holds a map, a setting holds a
401 // scalar. `scalar` judges the scalar itself at read time; the two
402 // collection types never reach it, because `lookup` walks past a list
403 // and stops inside a map, returning "absent" for both.
404 let leaf = KNOWN.contains(&path.as_str());
405 match v {
406 Yaml::Hash(_) => {
407 // No known key is a prefix of another, so a map under a setting
408 // holds nothing but keys nested a level too deep, and the
409 // recursion is what names them. An empty one has nothing to
410 // name, which is why the check below is not unreachable.
411 check_keys(v, &path)?;
412 if leaf {
413 return Err(format!("{path}: expected a string, found a map"));
414 }
415 }
416 Yaml::Array(_) => return Err(format!("{path}: expected a string, found a list")),
417 // `null` is "absent, use the default" at every level, for the reason
418 // `scalar` gives: it is how a templating layer writes "not set".
419 Yaml::Null => {}
420 // A scalar where a section belongs: `{ "listen": "0.0.0.0:4317" }`
421 // reads as neither `listen.grpc` nor `listen.http`.
422 _ if !leaf => {
423 return Err(format!(
424 "{path}: expected a map of settings, found a value; see https://miradb.dev/config/"
425 ));
426 }
427 _ => {}
428 }
429 }
430 Ok(())
431}
432
433fn lookup<'a>(root: &'a Yaml, path: &str) -> Option<&'a Yaml> {
434 let mut node = root;
435 for segment in path.split('.') {
436 node = match node {
437 Yaml::Hash(h) => h.get(&Yaml::String(segment.to_owned()))?,
438 _ => return None,
439 };
440 }
441 Some(node)
442}
443
444/// Every value Mira reads from the config file is a string — an address, a
445/// path, a name, a duration. So the rule is simply that it must have arrived as
446/// one.
447///
448/// `Ok(None)` means "no scalar here": a missing key, an explicit `null`, or a
449/// collection — and a collection at a key Mira reads is refused by
450/// [`check_keys`], which knows the path to name it by. `Err`
451/// means the key is present and the parser resolved it to some other type,
452/// which is the ambiguity KYAML exists to remove. Coercing back with
453/// `to_string()` is what makes `0x1f` silently become `31`; refusing costs the
454/// author two quote characters and cannot be wrong.
455fn scalar(y: &Yaml) -> Result<Option<String>> {
456 match y {
457 Yaml::String(s) => Ok(Some(s.clone())),
458 // The source text is already gone by the time we see this — `0x1f` and
459 // `31` are the same `Integer(31)` — so the message teaches the rule
460 // instead of quoting text we no longer have.
461 Yaml::Integer(_) | Yaml::Real(_) | Yaml::Boolean(_) => Err(format!(
462 "YAML read this as a {}, not a string; quote it \
463 (KYAML quotes every string, and every value here is one)",
464 match y {
465 Yaml::Integer(_) => "number",
466 Yaml::Real(_) => "float",
467 _ => "boolean",
468 }
469 )),
470 _ => Ok(None),
471 }
472}
473
474fn get(root: &Yaml, path: &str, env: Env) -> Result<Option<String>> {
475 let found = match lookup(root, path) {
476 Some(y) => scalar(y).map_err(|e| format!("{path}: {e}"))?,
477 None => None,
478 };
479 match found {
480 None => Ok(None),
481 Some(raw) => resolve(root, &raw, &mut vec![path.to_owned()], env).map(Some),
482 }
483}
484
485/// Expand every `${...}` in `raw`. `stack` carries the config paths currently
486/// being resolved, so a reference cycle is reported rather than overflowing.
487fn resolve(root: &Yaml, raw: &str, stack: &mut Vec<String>, env: Env) -> Result<String> {
488 let mut out = String::with_capacity(raw.len());
489 let bytes = raw.as_bytes();
490 let mut i = 0;
491
492 while i < bytes.len() {
493 // `$${` is an escaped literal `${`.
494 if raw[i..].starts_with("$${") {
495 out.push_str("${");
496 i += 3;
497 continue;
498 }
499 if !raw[i..].starts_with("${") {
500 let ch = raw[i..].chars().next().unwrap();
501 out.push(ch);
502 i += ch.len_utf8();
503 continue;
504 }
505 let rest = &raw[i + 2..];
506 let end = closing_brace(rest).ok_or_else(|| format!("unterminated `${{` in {raw:?}"))?;
507 out.push_str(&expand(root, &rest[..end], stack, env)?);
508 i += 2 + end + 1;
509 }
510 Ok(out)
511}
512
513/// Offset of the `}` that closes a `${` already consumed.
514///
515/// The matching brace, not the first one. `${env:A,${env:B,fallback}}` is a
516/// documented shape — a default that is itself an expression — and taking
517/// `find('}')` splits it in the middle: with `A` unset it complains about a `${`
518/// the author did terminate, and with `A` set it yields the value with a stray
519/// `}` welded on. That second one is the failure that matters, because `node`
520/// ends up in every block directory name.
521fn closing_brace(s: &str) -> Option<usize> {
522 let b = s.as_bytes();
523 let (mut depth, mut i) = (0usize, 0);
524 while i < b.len() {
525 // A multi-byte character's continuation bytes are all ≥ 0x80, so
526 // scanning bytes for these three ASCII ones cannot land inside one.
527 match b[i] {
528 b'$' if b.get(i + 1) == Some(&b'{') => {
529 depth += 1;
530 i += 1;
531 }
532 b'}' if depth == 0 => return Some(i),
533 b'}' => depth -= 1,
534 _ => {}
535 }
536 i += 1;
537 }
538 None
539}
540
541fn expand(root: &Yaml, expr: &str, stack: &mut Vec<String>, env: Env) -> Result<String> {
542 if let Some(rest) = expr.strip_prefix("env:") {
543 let (name, default) = match rest.split_once(',') {
544 Some((n, d)) => (n.trim(), Some(d)),
545 None => (rest.trim(), None),
546 };
547 return match (env(name), default) {
548 (Some(v), _) => Ok(v),
549 (None, Some(d)) => resolve(root, d, stack, env),
550 (None, None) => Err(format!(
551 "${{env:{name}}} is not set and has no default (write `${{env:{name},<default>}}`)"
552 )),
553 };
554 }
555
556 let path = expr.trim();
557 if stack.iter().any(|p| p == path) {
558 stack.push(path.to_owned());
559 return Err(format!("reference cycle: {}", stack.join(" -> ")));
560 }
561 let raw = match lookup(root, path) {
562 Some(y) => scalar(y).map_err(|e| format!("${{{path}}}: {e}"))?,
563 None => None,
564 }
565 .ok_or_else(|| format!("${{{path}}} does not name a scalar key"))?;
566
567 stack.push(path.to_owned());
568 let v = resolve(root, &raw, stack, env)?;
569 stack.pop();
570 Ok(v)
571}
572
573/// `true` or `false`, and nothing else.
574///
575/// Not YAML 1.1's dozen spellings. `on`, `yes` and `y` are why a Norwegian
576/// country code parses as `false`, and a config file that accepts eleven ways
577/// to say the same thing has ten ways to typo it into the other one.
578pub fn boolean(s: &str) -> Result<bool> {
579 match s.trim() {
580 "true" => Ok(true),
581 "false" => Ok(false),
582 other => Err(format!("{other:?} is not `true` or `false`")),
583 }
584}
585
586/// A count of things, which must be at least one.
587///
588/// Not [`bytes()`]: a queue depth of `4k` would read as 4,096 there and mean 4,000
589/// to whoever typed it, and a slot is not a byte. Zero is refused rather than
590/// silently meaning "rendezvous channel", which is what `mpsc::channel(0)` would
591/// panic on and what an operator typing it would never intend.
592pub fn positive(s: &str) -> Result<usize> {
593 match whole(s)? {
594 0 => Err("must be at least 1".into()),
595 n => Ok(n),
596 }
597}
598
599/// A replica list: `"http://a:4318, http://b:4318"`.
600///
601/// One comma-separated string rather than a YAML sequence, which would read
602/// better and is the one shape this file cannot hold. Every value Mira reads
603/// from it is a string (see [`scalar`]), and [`check_keys`] refuses a list at
604/// every path precisely so that a list where a string belongs is an error
605/// instead of a silent default — one exception costs that rule. The flag form
606/// is `--replica URI`, repeated, which is what anyone types anyway.
607///
608/// `http://` only. A replica is this deployment's own node on its own network,
609/// and refusing the other scheme here is what keeps the proxy's client free of
610/// the eleven crates behind `webhook-tls` (see [`crate::proxy`]). The trailing
611/// slash is trimmed so that a pasted browser URL and a typed one produce the
612/// same request line.
613pub fn replicas(s: &str) -> Result<Vec<String>> {
614 s.split(',')
615 .map(str::trim)
616 .filter(|u| !u.is_empty())
617 .map(|u| match u.strip_prefix("http://") {
618 Some(rest) if !rest.is_empty() => Ok(u.trim_end_matches('/').to_owned()),
619 _ => Err(format!(
620 "{u:?} is not a replica address; expected http://host:port"
621 )),
622 })
623 .collect()
624}
625
626/// A count of things where zero is an answer rather than a mistake — see
627/// [`Config::shards`], where it means "ask the machine".
628pub fn whole(s: &str) -> Result<usize> {
629 s.trim()
630 .parse::<usize>()
631 .map_err(|_| format!("{s:?} is not a whole number"))
632}
633
634/// `500ms`, `30s`, `5m`, `2h`, `7d`. A bare number is seconds.
635pub fn duration(s: &str) -> Result<Duration> {
636 let s = s.trim();
637 let split = s.len()
638 - s.chars()
639 .rev()
640 .take_while(|c| c.is_ascii_alphabetic())
641 .count();
642 let (n, unit) = s.split_at(split);
643 let n: u64 = n
644 .trim()
645 .parse()
646 .map_err(|_| format!("{s:?} is not a duration like `7d` or `500ms`"))?;
647 let scale = match unit {
648 "ms" => return Ok(Duration::from_millis(n)),
649 "" | "s" => 1,
650 "m" => 60,
651 "h" => 3600,
652 "d" => 86_400,
653 other => return Err(format!("unknown duration unit {other:?} in {s:?}")),
654 };
655 // Checked, because this is reached from unauthenticated input: the query
656 // API's `time_field` hands it whatever string a `from:` or `to:` carried,
657 // and `"1000000000000000000d"` parses as a `u64` and then overflows the
658 // scale. A release build wraps it into a window nobody asked for and
659 // answers the query from that; a debug build panics, and `panic = "abort"`
660 // makes a panic on a request path the whole process. A parse error is the
661 // only honest answer, and it is the one every other bad duration gets.
662 let secs = n
663 .checked_mul(scale)
664 .ok_or_else(|| format!("{s:?} is a longer duration than this system can represent"))?;
665 Ok(Duration::from_secs(secs))
666}
667
668/// `4MiB`, `512k`, `1048576`. Binary units, because every other size in this
669/// system — page, block, mmap — is binary and a `MB` that meant 10^6 next to a
670/// block size that meant 2^20 would be a trap.
671pub fn bytes(s: &str) -> Result<usize> {
672 let s = s.trim();
673 let split = s.len()
674 - s.chars()
675 .rev()
676 .take_while(|c| c.is_ascii_alphabetic())
677 .count();
678 let (n, unit) = s.split_at(split);
679 let n: usize = n
680 .trim()
681 .parse()
682 .map_err(|_| format!("{s:?} is not a size like `4MiB` or `1048576`"))?;
683 let shift = match unit.to_ascii_lowercase().as_str() {
684 "" | "b" => 0,
685 "k" | "kb" | "kib" => 10,
686 "m" | "mb" | "mib" => 20,
687 "g" | "gb" | "gib" => 30,
688 other => return Err(format!("unknown size unit {other:?} in {s:?}")),
689 };
690 n.checked_shl(shift)
691 .filter(|v| v >> shift == n)
692 .ok_or_else(|| format!("{s:?} overflows a usize"))
693}
694
695#[cfg(test)]
696mod tests {
697 use super::*;
698
699 /// `duration` is not only a config parser. The query API's `time_field`
700 /// calls it on the `from:`/`to:` of an unauthenticated request, so a string
701 /// that parses as a `u64` and then overflows the unit scale is reachable
702 /// from the wire. It used to be `n * scale`: a release build wrapped and
703 /// answered the query from a window nobody asked for, and a debug build
704 /// panicked — which under `panic = "abort"` is the process.
705 #[test]
706 fn a_duration_too_large_to_represent_is_a_parse_error_not_a_wrap() {
707 for s in [
708 "1000000000000000000d",
709 "18446744073709551615h",
710 "999999999999999d",
711 ] {
712 assert!(duration(s).is_err(), "{s:?} must not wrap");
713 }
714 // The boundary still parses, so the check costs nothing real.
715 assert_eq!(
716 duration("106751991167d").unwrap().as_secs(),
717 9_223_372_036_828_800
718 );
719 assert_eq!(duration("7d").unwrap().as_secs(), 604_800);
720 }
721
722 /// The environment these tests parse against. A literal, not the process's:
723 /// see [`Env`] for why writing the real one is not an option.
724 fn env(k: &str) -> Option<String> {
725 match k {
726 "MIRA_TEST_HOST" => Some("node-7".to_owned()),
727 _ => None,
728 }
729 }
730
731 /// Written in KYAML, and deliberately so: this doubles as the check that
732 /// `yaml-rust2` really accepts the house format — explicit `{}` and `[]`,
733 /// every string quoted, trailing commas, indentation that means nothing.
734 /// The trailing commas are the part worth verifying rather than assuming;
735 /// YAML 1.2 permits them in flow collections but plenty of parsers do not.
736 #[test]
737 fn interpolation_covers_env_reference_default_and_escape() {
738 let cfg = Config::parse_with(
739 r#"{
740 "node": "${env:MIRA_TEST_HOST}",
741 "listen": { "grpc": "0.0.0.0:5317", },
742 "storage": {
743 "dir": "/var/lib/${node}/${env:MIRA_TEST_MISSING,fallback}",
744 "retention": "36h",
745 "offload": "file:///cold/${node}",
746 },
747 "alerts": { "rules": "/etc/${node}/rules.yaml" },
748}"#,
749 &env,
750 )
751 .unwrap();
752
753 assert_eq!(cfg.node, "node-7");
754 assert_eq!(cfg.grpc.port(), 5317);
755 assert_eq!(cfg.data_dir, PathBuf::from("/var/lib/node-7/fallback"));
756 assert_eq!(cfg.retention, Duration::from_secs(36 * 3600));
757 // A URI is a string to this layer and the scheme is `main`'s to
758 // refuse, but it interpolates like every other value — one image, one
759 // bucket prefix per replica.
760 assert_eq!(cfg.offload.as_deref(), Some("file:///cold/node-7"));
761 assert_eq!(Config::default().offload, None, "off by default");
762 // Every path in the file interpolates, including the one that is read
763 // last: a rules file under `/etc/${node}` is how one image serves a
764 // fleet, and a literal `${node}` there is a boot that finds no rules.
765 assert_eq!(
766 cfg.alerts,
767 Some(PathBuf::from("/etc/node-7/rules.yaml")),
768 "alerts.rules is read and interpolated"
769 );
770 assert_eq!(Config::default().alerts, None, "and is off by default");
771 // Unset keys keep their defaults rather than becoming empty.
772 assert_eq!(cfg.http.port(), 4318);
773
774 let esc = Config::parse_with(r#"{ "node": "$${env:NOPE}" }"#, &env).unwrap();
775 assert_eq!(esc.node, "${env:NOPE}");
776
777 // Defaults nest, which only works if the scan finds the *matching*
778 // brace. Taking the first one used to boot the node called `alpha}` —
779 // a stray character in every block directory this replica writes.
780 let chain = r#"{ "node": "${env:MIRA_TEST_MISSING,${env:MIRA_TEST_HOST,last}}" }"#;
781 assert_eq!(Config::parse_with(chain, &env).unwrap().node, "node-7");
782 let all_unset =
783 r#"{ "node": "${env:MIRA_TEST_MISSING,${env:MIRA_TEST_ALSO_MISSING,last}}" }"#;
784 assert_eq!(Config::parse_with(all_unset, &env).unwrap().node, "last");
785 // And the outer value still wins without picking up the inner brace.
786 let outer = r#"{ "node": "${env:MIRA_TEST_HOST,${env:MIRA_TEST_MISSING,last}}" }"#;
787 assert_eq!(Config::parse_with(outer, &env).unwrap().node, "node-7");
788 }
789
790 /// `ingest.wal` is the only setting that changes what an acknowledgement
791 /// promises, so it is the last one that should accept a fuzzy spelling.
792 /// KYAML has already made the value a quoted string by the time it gets
793 /// here; what is refused is YAML 1.1's other ten ways to write a boolean,
794 /// each of which is a way to typo the durability contract into its
795 /// opposite.
796 #[test]
797 fn the_log_is_on_unless_it_is_spelled_false() {
798 assert!(Config::default().wal);
799 assert!(
800 Config::parse_with(r#"{ "ingest": { "wal": "true" } }"#, &env)
801 .unwrap()
802 .wal
803 );
804 assert!(
805 !Config::parse_with(r#"{ "ingest": { "wal": "false" } }"#, &env)
806 .unwrap()
807 .wal
808 );
809 for fuzzy in [r#""yes""#, r#""on""#, r#""1""#, r#""True""#] {
810 let doc = format!(r#"{{ "ingest": {{ "wal": {fuzzy} }} }}"#);
811 let e = Config::parse_with(&doc, &env).unwrap_err();
812 assert!(e.contains("ingest.wal"), "{fuzzy} was accepted: {e}");
813 }
814 }
815
816 /// The coercions KYAML exists to kill. Each of these used to be accepted,
817 /// stringified back into a *different* word, and used as the node name and
818 /// therefore as part of the block directory path.
819 #[test]
820 fn scalars_yaml_guessed_at_are_refused_rather_than_stringified_back() {
821 // `0x1f` is the worst of them: it survives as the string "31".
822 let e = Config::parse("node: 0x1f").unwrap_err();
823 assert!(e.contains("node:") && e.contains("quote"), "{e}");
824
825 // `False` comes back as "false", with the case quietly changed.
826 let e = Config::parse("node: False").unwrap_err();
827 assert!(e.contains("boolean") && e.contains("quote"), "{e}");
828
829 let e = Config::parse("storage:\n dir: 1.10").unwrap_err();
830 assert!(e.contains("storage.dir:") && e.contains("quote"), "{e}");
831
832 // Quoted, each means exactly what it says.
833 assert_eq!(Config::parse(r#"{ "node": "0x1f" }"#).unwrap().node, "0x1f");
834
835 // This parser is YAML 1.2, so `no` was never the boolean anyway. Worth
836 // pinning: the reason to quote is that the rule varies by parser, not
837 // that this particular one gets `no` wrong.
838 assert_eq!(Config::parse("node: no").unwrap().node, "no");
839 }
840
841 #[test]
842 fn bad_config_fails_at_boot_rather_than_silently() {
843 // A missing env var with no default must not become "".
844 let e = Config::parse_with("node: ${env:MIRA_MISSING}", &env).unwrap_err();
845 assert!(e.contains("is not set"), "{e}");
846
847 let e = Config::parse("node: ${a}\na: ${node}").unwrap_err();
848 assert!(e.contains("cycle"), "{e}");
849
850 // A reference to a key that is not in the file, and one to a key that
851 // is a map rather than a scalar. Both used to interpolate to nothing,
852 // so `${storage.dr}` for `${storage.dir}` booted a node whose data
853 // directory was the empty string — the process's cwd.
854 for text in ["node: ${nope}", "node: ${storage}\nstorage:\n dir: /x"] {
855 let e = Config::parse(text).unwrap_err();
856 assert!(e.contains("does not name a scalar key"), "{text}: {e}");
857 }
858
859 let e = Config::parse("storage:\n retention: 7 fortnights").unwrap_err();
860 assert!(e.contains("duration"), "{e}");
861
862 assert!(
863 Config::parse("node: ${env:X")
864 .unwrap_err()
865 .contains("unterminated")
866 );
867 // A nested default that never closes is still unterminated, rather than
868 // swallowing the rest of the file quietly.
869 assert!(
870 Config::parse("node: ${env:X,${env:Y,z}")
871 .unwrap_err()
872 .contains("unterminated")
873 );
874 }
875
876 /// A key Mira does not read is a startup error, not a shrug.
877 ///
878 /// The failure this prevents is the quietest one in the system: `retension`
879 /// for `retention` keeps the 7-day default, says nothing, and is diagnosed
880 /// weeks later as a disk that will not stop growing.
881 #[test]
882 fn a_key_mira_does_not_read_refuses_to_start() {
883 let e = Config::parse(r#"{ "storage": { "retension": "30d" } }"#).unwrap_err();
884 assert!(e.contains("storage.retension"), "{e}");
885
886 // Right name, wrong depth. Reported by its full path, because that is
887 // the thing that is wrong about it.
888 let e = Config::parse(r#"{ "retention": "30d" }"#).unwrap_err();
889 assert!(e.contains("unknown key \"retention\""), "{e}");
890 let e = Config::parse(r#"{ "storage": { "dir": { "path": "/x" } } }"#).unwrap_err();
891 assert!(e.contains("storage.dir.path"), "{e}");
892
893 // A setting that was deleted becomes loud for free — no special case.
894 // The section is what no longer exists, so that is what the error names.
895 let e = Config::parse(r#"{ "cluster": { "peers": "a:1" } }"#).unwrap_err();
896 assert!(e.contains("unknown key \"cluster\""), "{e}");
897
898 // And with nothing in it yet, which is how an operator writes a section
899 // they are about to fill in — so it is the reading most likely to be
900 // believed, and it used to be the one that booted.
901 let e = Config::parse(r#"{ "cluster": {} }"#).unwrap_err();
902 assert!(e.contains("unknown key \"cluster\""), "{e}");
903
904 // Keys are held to the same quoting rule as values.
905 let e = Config::parse("2: x").unwrap_err();
906 assert!(e.contains("quote"), "{e}");
907
908 // And the shipped shape passes, including sections with nothing in them.
909 Config::parse(r#"{ "node": "a", "listen": {}, "ingest": { "max_request_bytes": "1k" } }"#)
910 .unwrap();
911 }
912
913 /// A list or a map where a value belongs is refused, not ignored.
914 ///
915 /// `lookup` returns "absent" for both — it walks past a list and stops
916 /// inside a map — so each of these used to boot on the default: the wrong
917 /// listen address, or worse, the wrong data directory, with nothing said.
918 #[test]
919 fn a_value_of_the_wrong_shape_refuses_to_start() {
920 let e = Config::parse(r#"{ "node": ["a"] }"#).unwrap_err();
921 assert!(e.contains("node: expected a string, found a list"), "{e}");
922
923 // The empty map is the one the leaf-only check missed.
924 let e = Config::parse(r#"{ "storage": { "dir": {} } }"#).unwrap_err();
925 assert!(
926 e.contains("storage.dir: expected a string, found a map"),
927 "{e}"
928 );
929
930 // A section given a value instead of its settings.
931 let e = Config::parse(r#"{ "listen": "0.0.0.0:4317" }"#).unwrap_err();
932 assert!(e.contains("listen: expected a map of settings"), "{e}");
933
934 // `null` still means "absent, use the default" — a key present-but-null
935 // is how a templating layer says "not set", at either level.
936 let cfg = Config::parse(r#"{ "node": null, "listen": null }"#).unwrap();
937 assert_eq!(cfg.node, "mira");
938 assert_eq!(cfg.http.port(), 4318);
939 }
940
941 /// Binary units throughout, and no silent second meaning for `MB`.
942 #[test]
943 fn sizes_parse_in_binary_units_or_not_at_all() {
944 assert_eq!(bytes("1048576"), Ok(1 << 20));
945 assert_eq!(bytes(" 512k "), Ok(512 << 10));
946 assert_eq!(bytes("4MiB"), Ok(4 << 20));
947 // `MB` is the same as `MiB` here rather than 10^6, because a config
948 // where `block: 4MiB` and `request: 4MB` differed by 5% would be read
949 // as equal by everyone.
950 assert_eq!(bytes("4MB"), bytes("4MiB"));
951 assert_eq!(bytes("2g"), Ok(2 << 30));
952
953 assert!(bytes("4 fortnights").unwrap_err().contains("unit"));
954 assert!(bytes("MiB").unwrap_err().contains("size"));
955 assert!(bytes("-1").unwrap_err().contains("size"));
956 // The shift is checked, so a plausible typo is an error and not a wrap
957 // to some small number that then silently truncates every export.
958 assert!(bytes("99999999999g").unwrap_err().contains("overflow"));
959
960 let cfg = Config::parse(r#"{ "ingest": { "max_request_bytes": "32MiB" } }"#).unwrap();
961 assert_eq!(cfg.max_request_bytes, 32 << 20);
962 let e = Config::parse(r#"{ "ingest": { "max_request_bytes": "big" } }"#).unwrap_err();
963 assert!(e.contains("ingest.max_request_bytes"), "{e}");
964 }
965
966 /// A queue depth is a count of slots, and the two ways of writing a number
967 /// that [`bytes`] accepts are both wrong for it: `4k` would be 4,096 slots
968 /// to the parser and 4,000 to whoever typed it, and zero would be a
969 /// rendezvous channel nobody asks for on purpose.
970 #[test]
971 fn a_queue_depth_is_a_count_of_slots_and_not_a_size() {
972 assert_eq!(positive("2048"), Ok(2048));
973 assert_eq!(positive(" 1 "), Ok(1));
974 assert!(positive("0").unwrap_err().contains("at least 1"));
975 assert!(positive("-1").unwrap_err().contains("whole number"));
976 assert!(positive("4k").unwrap_err().contains("whole number"));
977
978 let cfg = Config::parse(r#"{ "ingest": { "queue": "512" } }"#).unwrap();
979 assert_eq!(cfg.queue, 512);
980 assert_eq!(Config::default().queue, 128);
981 let e = Config::parse(r#"{ "ingest": { "queue": "0" } }"#).unwrap_err();
982 assert!(e.contains("ingest.queue"), "{e}");
983
984 // `ingest.shards` is the same count with one more spelling: zero is
985 // "ask the machine", so it goes through `whole` and not `positive`.
986 // Both parsers reject `4k` identically, which is why the key each one
987 // is wired to has to be asserted rather than assumed.
988 let cfg = Config::parse(r#"{ "ingest": { "shards": "4" } }"#).unwrap();
989 assert_eq!(cfg.shards, 4);
990 assert_eq!(
991 Config::parse(r#"{ "ingest": { "shards": "0" } }"#)
992 .unwrap()
993 .shards,
994 0
995 );
996 assert_eq!(Config::default().shards, 0, "one flusher per core");
997 let e = Config::parse(r#"{ "ingest": { "shards": "4k" } }"#).unwrap_err();
998 assert!(e.contains("ingest.shards"), "{e}");
999 }
1000
1001 /// Off by default: a node that stores its own telemetry is writing to the
1002 /// disk it is being measured on, and that is a decision, not a default.
1003 #[test]
1004 fn self_telemetry_is_off_until_it_is_turned_on() {
1005 let d = Config::default();
1006 assert!(!d.self_telemetry);
1007 assert_eq!(d.telemetry_interval, Duration::from_secs(15));
1008
1009 let cfg =
1010 Config::parse(r#"{ "telemetry": { "self": "true", "interval": "1m" } }"#).unwrap();
1011 assert!(cfg.self_telemetry);
1012 assert_eq!(cfg.telemetry_interval, Duration::from_secs(60));
1013
1014 // And `false` in a file has to be able to turn off what an inherited
1015 // file turned on, which is the reason it is a key and not only a flag.
1016 let cfg = Config::parse(r#"{ "telemetry": { "self": "false" } }"#).unwrap();
1017 assert!(!cfg.self_telemetry);
1018
1019 let e = Config::parse(r#"{ "telemetry": { "self": "yes please" } }"#).unwrap_err();
1020 assert!(e.contains("telemetry.self"), "{e}");
1021 let e = Config::parse(r#"{ "telemetry": { "interval": "soon" } }"#).unwrap_err();
1022 assert!(e.contains("telemetry.interval"), "{e}");
1023 }
1024
1025 /// One comma-separated scalar, `http://` only, and a refusal an operator can
1026 /// act on.
1027 ///
1028 /// The one key in this file that is a list, written as a scalar because
1029 /// `check_keys` refuses a YAML sequence at every path. So the splitting is
1030 /// this function's own and nothing else checks it — and the scheme rule is
1031 /// load-bearing rather than fussy: it is what keeps `proxy`'s client free of
1032 /// the eleven crates a TLS one would cost.
1033 #[test]
1034 fn a_replica_list_is_one_scalar_of_http_addresses() {
1035 let cfg = Config::parse(
1036 r#"{ "proxy": { "replicas": "http://a:4318, http://b:4318/ ,, http://c:4318" } }"#,
1037 )
1038 .unwrap();
1039 // Trimmed, de-slashed, empty pieces dropped — so a trailing comma and a
1040 // pasted browser URL both produce the same request line as a typed one.
1041 assert_eq!(
1042 cfg.replicas,
1043 ["http://a:4318", "http://b:4318", "http://c:4318"]
1044 );
1045 assert!(Config::default().replicas.is_empty());
1046 assert!(replicas("").unwrap().is_empty());
1047
1048 for bad in ["https://a:4318", "a:4318", "http://"] {
1049 let e =
1050 Config::parse(&format!(r#"{{ "proxy": {{ "replicas": "{bad}" }} }}"#)).unwrap_err();
1051 assert!(
1052 e.contains("proxy.replicas") && e.contains("http://host:port"),
1053 "{bad}: {e}"
1054 );
1055 }
1056 }
1057}