1use std::collections::BTreeMap;
14use std::fmt::Write as _;
15use std::net::SocketAddr;
16use std::sync::{Arc, Mutex, MutexGuard};
17use std::time::Duration;
18
19use tokio::io::{AsyncReadExt, AsyncWriteExt};
20use tokio::net::{TcpListener, TcpStream};
21use tokio::time::{sleep, timeout};
22use tracing::{info, warn};
23
24const RIPPLE_EPOCH: u64 = 946_684_800;
26
27#[derive(Debug, Default)]
28pub struct Metrics {
29 pub connected: bool,
31 pub tip_ledger: u32,
33 pub last_ledger: u32,
35 pub last_close_time: u32,
37 pub last_commit_ms: u64,
38 pub ledgers: u64,
39 pub transactions: u64,
40 pub changes: u64,
41 pub commit_seconds: f64,
43 pub source_errors: u64,
44 pub unknown_findings: u64,
48 pub unknown_last_ledger: u32,
49 pub unknown_amendments_enabled: u64,
50 pub unknown_amendments_majority: u64,
51 pub missing_retries: u64,
53 pub pending_ledgers: u64,
54 pub blocks_bytes: u64,
55 pub state_bytes: u64,
56 pub confirmed_ledger: u32,
58 pub validations_connected: bool,
59 pub validations: u64,
60 pub validations_rejected: u64,
61 pub manifests: u64,
62 pub evidence_ledger: u32,
64 pub quorum_signers: usize,
67 pub quorum_needed: usize,
68 pub unl_size: usize,
69 pub unl_lists: Vec<UnlList>,
71 pub coverage: Coverage,
72 pub api: Api,
73}
74
75#[derive(Debug, Clone, Default, PartialEq, Eq)]
77pub struct UnlList {
78 pub publisher: String,
80 pub sequence: u64,
81 pub validators: usize,
82 pub expiration: u64,
84}
85
86#[derive(Debug, Default)]
88pub struct Coverage {
89 pub first_ledger: u32,
91 pub last_ledger: u32,
92 pub state_first_ledger: u32,
95 pub tree_history_first_ledger: u32,
96 pub cold_segments: u64,
97 pub cold_transactions: u64,
98 pub bytes: BTreeMap<&'static str, u64>,
100}
101
102pub fn unix_of_ripple(t: u32) -> u64 {
104 if t == 0 {
105 0
106 } else {
107 u64::from(t) + RIPPLE_EPOCH
108 }
109}
110
111pub const LATENCY_BUCKETS: [f64; 9] = [0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.5, 2.5];
113
114#[derive(Debug, Default)]
118pub struct Api {
119 pub requests: BTreeMap<(&'static str, String, String), u64>,
122 pub latency: BTreeMap<String, ([u64; LATENCY_BUCKETS.len()], u64, f64)>,
124 pub ws_sessions: u64,
126 pub ws_sessions_total: u64,
127 pub forwarded: BTreeMap<String, u64>,
129 pub response_bytes: BTreeMap<String, u64>,
131 pub proofs: BTreeMap<(String, String), u64>,
133 pub proof_cache_hits: u64,
134 pub inflight: u64,
136 pub inflight_proofs: u64,
137 pub inflight_forwards: u64,
138 pub public_inflight: u64,
140 pub public_inflight_proofs: u64,
141 pub public_inflight_forwards: u64,
142 pub public_sessions: u64,
143 pub subscribers: BTreeMap<&'static str, u64>,
145 pub subscribed_accounts: u64,
146 pub ws_dropped: u64,
148 pub rejected: BTreeMap<(&'static str, &'static str), u64>,
150}
151
152impl Api {
153 pub fn record(
154 &mut self,
155 transport: &'static str,
156 method: &str,
157 status: &str,
158 seconds: f64,
159 bytes: usize,
160 forwarded: bool,
161 ) {
162 *self
163 .requests
164 .entry((transport, method.to_owned(), status.to_owned()))
165 .or_default() += 1;
166 *self.response_bytes.entry(method.to_owned()).or_default() += bytes as u64;
167 if forwarded {
168 *self.forwarded.entry(method.to_owned()).or_default() += 1;
169 }
170 let (buckets, count, sum) = self.latency.entry(method.to_owned()).or_default();
171 if let Some(i) = LATENCY_BUCKETS.iter().position(|&b| seconds <= b) {
172 buckets[i] += 1;
173 }
174 *count += 1;
175 *sum += seconds;
176 }
177
178 fn render(&self, out: &mut String) {
179 let _ = writeln!(
180 out,
181 "# HELP astraea_api_requests_total API requests by transport, method and status.\n\
182 # TYPE astraea_api_requests_total counter"
183 );
184 for ((transport, method, status), n) in &self.requests {
185 let _ = writeln!(
186 out,
187 "astraea_api_requests_total{{transport=\"{transport}\",method=\"{method}\",status=\"{status}\"}} {n}"
188 );
189 }
190 let _ = writeln!(
191 out,
192 "# HELP astraea_api_request_duration_seconds Time to answer an API request.\n\
193 # TYPE astraea_api_request_duration_seconds histogram"
194 );
195 for (method, (buckets, count, sum)) in &self.latency {
196 let mut below = 0;
197 for (b, n) in LATENCY_BUCKETS.iter().zip(buckets) {
198 below += n;
199 let _ = writeln!(
200 out,
201 "astraea_api_request_duration_seconds_bucket{{method=\"{method}\",le=\"{b}\"}} {below}"
202 );
203 }
204 let _ = writeln!(
205 out,
206 "astraea_api_request_duration_seconds_bucket{{method=\"{method}\",le=\"+Inf\"}} {count}\n\
207 astraea_api_request_duration_seconds_sum{{method=\"{method}\"}} {sum:.6}\n\
208 astraea_api_request_duration_seconds_count{{method=\"{method}\"}} {count}"
209 );
210 }
211 let _ = writeln!(
212 out,
213 "# HELP astraea_api_ws_sessions Open WebSocket sessions.\n\
214 # TYPE astraea_api_ws_sessions gauge\n\
215 astraea_api_ws_sessions {}\n\
216 # HELP astraea_api_ws_sessions_total WebSocket sessions opened since start.\n\
217 # TYPE astraea_api_ws_sessions_total counter\n\
218 astraea_api_ws_sessions_total {}",
219 self.ws_sessions, self.ws_sessions_total
220 );
221 family(
222 out,
223 "astraea_api_forwarded_total",
224 "counter",
225 "Requests answered by the node rather than from our own data, by method.",
226 self.forwarded
227 .iter()
228 .map(|(m, n)| (format!("method=\"{m}\""), n.to_string())),
229 );
230 family(
231 out,
232 "astraea_api_response_bytes_total",
233 "counter",
234 "Bytes of API responses, by method.",
235 self.response_bytes
236 .iter()
237 .map(|(m, n)| (format!("method=\"{m}\""), n.to_string())),
238 );
239 family(
240 out,
241 "astraea_proof_bundles_total",
242 "counter",
243 "Evidence bundles built, by method and how the target ledger was confirmed (quorum, hash-chain, skip-list).",
244 self.proofs.iter().map(|((m, by), n)| {
245 (
246 format!("method=\"{m}\",confirmed_by=\"{by}\""),
247 n.to_string(),
248 )
249 }),
250 );
251 family(
252 out,
253 "astraea_proof_cache_hits_total",
254 "counter",
255 "Evidence bundles served from the cache of bundles that never change.",
256 [(String::new(), self.proof_cache_hits.to_string())],
257 );
258 family(
259 out,
260 "astraea_api_public_sessions",
261 "gauge",
262 "WebSocket sessions open on the public listeners.",
263 [(String::new(), self.public_sessions.to_string())],
264 );
265 family(
266 out,
267 "astraea_api_inflight",
268 "gauge",
269 "Requests being served now, by pool: regular requests and proof bundles.",
270 [
271 ("pool=\"api\"".to_owned(), self.inflight.to_string()),
272 (
273 "pool=\"proof\"".to_owned(),
274 self.inflight_proofs.to_string(),
275 ),
276 (
277 "pool=\"forward\"".to_owned(),
278 self.inflight_forwards.to_string(),
279 ),
280 (
281 "pool=\"public_api\"".to_owned(),
282 self.public_inflight.to_string(),
283 ),
284 (
285 "pool=\"public_proof\"".to_owned(),
286 self.public_inflight_proofs.to_string(),
287 ),
288 (
289 "pool=\"public_forward\"".to_owned(),
290 self.public_inflight_forwards.to_string(),
291 ),
292 ],
293 );
294 family(
295 out,
296 "astraea_api_subscribers",
297 "gauge",
298 "WebSocket sessions subscribed to each stream.",
299 self.subscribers
300 .iter()
301 .map(|(s, n)| (format!("stream=\"{s}\""), n.to_string())),
302 );
303 family(
304 out,
305 "astraea_api_subscribed_accounts",
306 "gauge",
307 "Accounts subscribed to, over all sessions.",
308 [(String::new(), self.subscribed_accounts.to_string())],
309 );
310 family(
311 out,
312 "astraea_api_ws_dropped_total",
313 "counter",
314 "WebSocket sessions disconnected for not reading their messages.",
315 [(String::new(), self.ws_dropped.to_string())],
316 );
317 family(
318 out,
319 "astraea_api_rejected_total",
320 "counter",
321 "Requests refused to protect the server, by door (own, public) and reason: connections, budget (requests, bytes or work), sessions (all public sessions), busy (no free slot in time).",
322 self.rejected
323 .iter()
324 .map(|((d, r), n)| (format!("door=\"{d}\",reason=\"{r}\""), n.to_string())),
325 );
326 }
327}
328
329fn family(
332 out: &mut String,
333 name: &str,
334 kind: &str,
335 help: &str,
336 samples: impl IntoIterator<Item = (String, String)>,
337) {
338 let _ = writeln!(out, "# HELP {name} {help}\n# TYPE {name} {kind}");
339 for (labels, value) in samples {
340 if labels.is_empty() {
341 let _ = writeln!(out, "{name} {value}");
342 } else {
343 let _ = writeln!(out, "{name}{{{labels}}} {value}");
344 }
345 }
346}
347
348fn process(out: &mut String) {
351 const TICKS: f64 = 100.0;
353 let Ok(stat) = std::fs::read_to_string("/proc/self/stat") else {
354 return;
355 };
356 let Some(rest) = stat.rfind(')').map(|i| &stat[i + 2..]) else {
358 return;
359 };
360 let f: Vec<&str> = rest.split_whitespace().collect();
361 let num = |i: usize| f.get(i).and_then(|v| v.parse::<f64>().ok()).unwrap_or(0.0);
362 let cpu = (num(11) + num(12)) / TICKS;
364 let boot = std::fs::read_to_string("/proc/stat")
365 .ok()
366 .and_then(|s| {
367 s.lines()
368 .find_map(|l| l.strip_prefix("btime ")?.trim().parse::<f64>().ok())
369 })
370 .unwrap_or(0.0);
371 let rss = std::fs::read_to_string("/proc/self/status")
372 .ok()
373 .and_then(|s| {
374 s.lines().find_map(|l| {
375 l.strip_prefix("VmRSS:")?
376 .trim()
377 .trim_end_matches(" kB")
378 .parse::<u64>()
379 .ok()
380 })
381 })
382 .unwrap_or(0)
383 * 1024;
384 let fds = std::fs::read_dir("/proc/self/fd").map_or(0, |d| d.count());
385 let one = |v: String| [(String::new(), v)];
386 family(
387 out,
388 "process_cpu_seconds_total",
389 "counter",
390 "User and system CPU time.",
391 one(format!("{cpu:.2}")),
392 );
393 family(
394 out,
395 "process_resident_memory_bytes",
396 "gauge",
397 "Resident memory.",
398 one(rss.to_string()),
399 );
400 family(
401 out,
402 "process_open_fds",
403 "gauge",
404 "Open file descriptors.",
405 one(fds.to_string()),
406 );
407 family(
408 out,
409 "process_threads",
410 "gauge",
411 "Threads.",
412 one(format!("{}", num(17))),
413 );
414 family(
415 out,
416 "process_start_time_seconds",
417 "gauge",
418 "Start time, Unix time.",
419 one(format!("{:.0}", boot + num(19) / TICKS)),
420 );
421}
422
423impl Coverage {
424 fn render(&self, out: &mut String) {
425 let one = |v: String| [(String::new(), v)];
426 family(
427 out,
428 "astraea_history_first_ledger",
429 "gauge",
430 "First ledger the API serves.",
431 one(self.first_ledger.to_string()),
432 );
433 family(
434 out,
435 "astraea_history_last_ledger",
436 "gauge",
437 "Last ledger the API serves.",
438 one(self.last_ledger.to_string()),
439 );
440 family(
441 out,
442 "astraea_state_first_ledger",
443 "gauge",
444 "First ledger with state (the snapshot): state methods start here.",
445 one(self.state_first_ledger.to_string()),
446 );
447 family(
448 out,
449 "astraea_tree_history_first_ledger",
450 "gauge",
451 "First ledger with tree history: proof_entry starts here.",
452 one(self.tree_history_first_ledger.to_string()),
453 );
454 family(
455 out,
456 "astraea_cold_segments",
457 "gauge",
458 "Cold history segments.",
459 one(self.cold_segments.to_string()),
460 );
461 family(
462 out,
463 "astraea_cold_transactions",
464 "gauge",
465 "Transactions in cold history.",
466 one(self.cold_transactions.to_string()),
467 );
468 family(
469 out,
470 "astraea_storage_bytes",
471 "gauge",
472 "Bytes on disk by part: the state store (its indexes and tree history are in it, and also shown on their own), hot history, cold segments, cold indexes.",
473 self.bytes
474 .iter()
475 .map(|(p, n)| (format!("part=\"{p}\""), n.to_string())),
476 );
477 }
478}
479
480pub type Shared = Arc<Mutex<Metrics>>;
481
482pub fn lock(m: &Shared) -> MutexGuard<'_, Metrics> {
484 m.lock().unwrap_or_else(|p| p.into_inner())
485}
486
487impl Metrics {
488 pub fn render(&self) -> String {
489 let mut out = String::new();
490 let _ = writeln!(
491 out,
492 "# HELP astraea_ingest_info Loader version.\n\
493 # TYPE astraea_ingest_info gauge\n\
494 astraea_ingest_info{{version=\"{}\"}} 1",
495 env!("CARGO_PKG_VERSION"),
496 );
497 let mut put = |name: &str, kind: &str, help: &str, value: String| {
498 let _ = writeln!(out, "# HELP astraea_ingest_{name} {help}");
499 let _ = writeln!(out, "# TYPE astraea_ingest_{name} {kind}");
500 let _ = writeln!(out, "astraea_ingest_{name} {value}");
501 };
502 put(
503 "connected",
504 "gauge",
505 "The last tip request to the node succeeded.",
506 u8::from(self.connected).to_string(),
507 );
508 put(
509 "tip_ledger",
510 "gauge",
511 "Last validated ledger according to the node.",
512 self.tip_ledger.to_string(),
513 );
514 put(
515 "last_ledger",
516 "gauge",
517 "Last applied ledger.",
518 self.last_ledger.to_string(),
519 );
520 let close = if self.last_close_time == 0 {
521 0
522 } else {
523 u64::from(self.last_close_time) + RIPPLE_EPOCH
524 };
525 put(
526 "last_ledger_close_timestamp_seconds",
527 "gauge",
528 "When the network closed the last applied ledger, Unix time.",
529 close.to_string(),
530 );
531 put(
532 "last_commit_timestamp_seconds",
533 "gauge",
534 "When the last ledger was written, Unix time.",
535 format!("{:.3}", self.last_commit_ms as f64 / 1000.0),
536 );
537 put(
538 "ledgers_total",
539 "counter",
540 "Ledgers written since start.",
541 self.ledgers.to_string(),
542 );
543 put(
544 "transactions_total",
545 "counter",
546 "Transactions in written ledgers.",
547 self.transactions.to_string(),
548 );
549 put(
550 "state_changes_total",
551 "counter",
552 "State changes in written ledgers.",
553 self.changes.to_string(),
554 );
555 put(
556 "commit_seconds_total",
557 "counter",
558 "Time spent writing ledgers: verification, state, blocks.",
559 format!("{:.6}", self.commit_seconds),
560 );
561 put(
562 "source_errors_total",
563 "counter",
564 "Failed requests to the node.",
565 self.source_errors.to_string(),
566 );
567 put(
568 "unknown_findings_total",
569 "counter",
570 "Fields, transaction or object types and result codes in written ledgers that this build does not know; such ledgers are stored as they are.",
571 self.unknown_findings.to_string(),
572 );
573 put(
574 "unknown_last_ledger",
575 "gauge",
576 "Last written ledger with something this build does not know; 0 if none since start.",
577 self.unknown_last_ledger.to_string(),
578 );
579 put(
580 "unknown_amendments_enabled",
581 "gauge",
582 "Amendments enabled on the network that this build does not know.",
583 self.unknown_amendments_enabled.to_string(),
584 );
585 put(
586 "unknown_amendments_majority",
587 "gauge",
588 "Amendments with a validator majority (enabled in two weeks unless it is lost) that this build does not know.",
589 self.unknown_amendments_majority.to_string(),
590 );
591 put(
592 "missing_retries_total",
593 "counter",
594 "Retries because the node does not have the needed ledger.",
595 self.missing_retries.to_string(),
596 );
597 put(
598 "pending_ledgers",
599 "gauge",
600 "Ledgers waiting for their block.",
601 self.pending_ledgers.to_string(),
602 );
603 put(
604 "blocks_bytes",
605 "gauge",
606 "Size of the block history on disk.",
607 self.blocks_bytes.to_string(),
608 );
609 put(
610 "confirmed_ledger",
611 "gauge",
612 "Last ledger confirmed by a quorum of UNL validators.",
613 self.confirmed_ledger.to_string(),
614 );
615 put(
616 "validations_connected",
617 "gauge",
618 "The node's validation stream is connected.",
619 u8::from(self.validations_connected).to_string(),
620 );
621 put(
622 "validations_total",
623 "counter",
624 "Validations received with a valid signature.",
625 self.validations.to_string(),
626 );
627 put(
628 "validations_rejected_total",
629 "counter",
630 "Validations rejected: unparsable or bad signature.",
631 self.validations_rejected.to_string(),
632 );
633 put(
634 "evidence_ledger",
635 "gauge",
636 "Last ledger with stored anchor evidence (quorum validations).",
637 self.evidence_ledger.to_string(),
638 );
639 put(
640 "manifests_total",
641 "counter",
642 "Manifests received from the node.",
643 self.manifests.to_string(),
644 );
645 put(
646 "state_bytes",
647 "gauge",
648 "Size of the state store on disk.",
649 self.state_bytes.to_string(),
650 );
651 let one = |v: usize| [(String::new(), v.to_string())];
652 family(
653 &mut out,
654 "astraea_quorum_signers",
655 "gauge",
656 "UNL validators that signed the last confirmed ledger.",
657 one(self.quorum_signers),
658 );
659 family(
660 &mut out,
661 "astraea_quorum_needed",
662 "gauge",
663 "Signatures the quorum rule needed for the last confirmed ledger.",
664 one(self.quorum_needed),
665 );
666 family(
667 &mut out,
668 "astraea_unl_size",
669 "gauge",
670 "Validators in the UNL the last confirmation was decided with.",
671 one(self.unl_size),
672 );
673 let lists = |f: fn(&UnlList) -> String| {
674 self.unl_lists
675 .iter()
676 .map(move |l| (format!("publisher=\"{}\"", l.publisher), f(l)))
677 };
678 family(
679 &mut out,
680 "astraea_unl_list_sequence",
681 "gauge",
682 "Sequence of the publisher's latest UNL list.",
683 lists(|l| l.sequence.to_string()),
684 );
685 family(
686 &mut out,
687 "astraea_unl_list_validators",
688 "gauge",
689 "Validators in the publisher's latest UNL list.",
690 lists(|l| l.validators.to_string()),
691 );
692 family(
693 &mut out,
694 "astraea_unl_list_expiration_timestamp_seconds",
695 "gauge",
696 "When the publisher's latest UNL list expires, Unix time.",
697 lists(|l| l.expiration.to_string()),
698 );
699 self.coverage.render(&mut out);
700 self.api.render(&mut out);
701 process(&mut out);
702 out
703 }
704}
705
706pub fn dir_bytes(dir: &std::path::Path) -> u64 {
708 let Ok(entries) = std::fs::read_dir(dir) else {
709 return 0;
710 };
711 entries
712 .filter_map(Result::ok)
713 .map(|e| match e.metadata() {
714 Ok(m) if m.is_dir() => dir_bytes(&e.path()),
715 Ok(m) => m.len(),
716 Err(_) => 0,
717 })
718 .sum()
719}
720
721pub async fn serve(addr: SocketAddr, metrics: Shared) {
722 loop {
723 let listener = match TcpListener::bind(addr).await {
724 Ok(l) => l,
725 Err(e) => {
726 warn!("metrics: cannot listen on {addr}: {e}; retrying in 10 s");
727 sleep(Duration::from_secs(10)).await;
728 continue;
729 }
730 };
731 info!("metrics on http://{addr}/metrics");
732 loop {
733 match listener.accept().await {
734 Ok((stream, _)) => {
735 let _ = timeout(Duration::from_secs(5), answer(stream, &metrics)).await;
736 }
737 Err(e) => {
738 warn!("metrics: accept: {e}");
739 sleep(Duration::from_secs(1)).await;
740 }
741 }
742 }
743 }
744}
745
746async fn answer(mut stream: TcpStream, metrics: &Shared) -> std::io::Result<()> {
747 let mut buf = [0u8; 1024];
748 let n = stream.read(&mut buf).await?;
749 let head = String::from_utf8_lossy(&buf[..n]);
750 let (status, body) = if head.starts_with("GET /metrics ") || head.starts_with("GET /metrics?") {
751 ("200 OK", lock(metrics).render())
752 } else {
753 ("404 Not Found", String::from("only /metrics\n"))
754 };
755 let reply = format!(
756 "HTTP/1.1 {status}\r\nContent-Type: text/plain; version=0.0.4; charset=utf-8\r\n\
757 Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
758 body.len()
759 );
760 stream.write_all(reply.as_bytes()).await?;
761 stream.shutdown().await
762}
763
764#[cfg(test)]
765mod tests {
766 use super::*;
767
768 #[test]
769 fn render_is_valid_exposition() {
770 let m = Metrics {
771 last_ledger: 107_875_645,
772 last_close_time: 1_000,
773 last_commit_ms: 1_500,
774 ..Metrics::default()
775 };
776 let text = m.render();
777 assert!(text.contains("\nastraea_ingest_last_ledger 107875645\n"));
778 assert!(text.contains("\nastraea_ingest_last_ledger_close_timestamp_seconds 946685800\n"));
779 assert!(text.contains("\nastraea_ingest_last_commit_timestamp_seconds 1.500\n"));
780 for line in text.lines().filter(|l| !l.starts_with('#')) {
781 let (_, v) = line.rsplit_once(' ').unwrap();
782 assert!(v.parse::<f64>().is_ok(), "{line}");
783 }
784 }
785
786 #[test]
787 fn api_requests_render_as_a_histogram() {
788 let mut m = Metrics::default();
789 m.api
790 .record("ws", "account_tx", "success", 0.003, 1000, false);
791 m.api
792 .record("http", "account_tx", "actNotFound", 0.2, 200, false);
793 m.api
794 .record("ws", "account_tx", "success", 9.0, 1000, false);
795 m.api.record("http", "fee", "success", 0.01, 300, true);
796 m.api.ws_sessions = 2;
797 let text = m.render();
798 for line in [
799 "astraea_api_requests_total{transport=\"ws\",method=\"account_tx\",status=\"success\"} 2",
800 "astraea_api_requests_total{transport=\"http\",method=\"account_tx\",status=\"actNotFound\"} 1",
801 "astraea_api_request_duration_seconds_bucket{method=\"account_tx\",le=\"0.0025\"} 0",
802 "astraea_api_request_duration_seconds_bucket{method=\"account_tx\",le=\"0.005\"} 1",
803 "astraea_api_request_duration_seconds_bucket{method=\"account_tx\",le=\"2.5\"} 2",
804 "astraea_api_request_duration_seconds_bucket{method=\"account_tx\",le=\"+Inf\"} 3",
805 "astraea_api_request_duration_seconds_count{method=\"account_tx\"} 3",
806 "astraea_api_ws_sessions 2",
807 "astraea_api_response_bytes_total{method=\"account_tx\"} 2200",
808 "astraea_api_forwarded_total{method=\"fee\"} 1",
809 ] {
810 assert!(text.contains(&format!("\n{line}\n")), "{line}");
811 }
812 for line in text.lines().filter(|l| !l.starts_with('#')) {
813 let (_, v) = line.rsplit_once(' ').unwrap();
814 assert!(v.parse::<f64>().is_ok(), "{line}");
815 }
816 }
817
818 #[test]
819 fn trust_and_coverage_render() {
820 let mut m = Metrics {
821 quorum_signers: 33,
822 quorum_needed: 28,
823 unl_size: 35,
824 unl_lists: vec![UnlList {
825 publisher: "ED2677ABFFD1B33A".into(),
826 sequence: 2026,
827 validators: 35,
828 expiration: unix_of_ripple(1_000),
829 }],
830 ..Metrics::default()
831 };
832 m.coverage.first_ledger = 86_339_141;
833 m.coverage.bytes.insert("cold", 466_000_000_000);
834 m.api
835 .proofs
836 .insert(("proof_tx".into(), "skip-list".into()), 4);
837 m.api.subscribers.insert("ledger", 2);
838 let text = m.render();
839 for line in [
840 "astraea_quorum_signers 33",
841 "astraea_quorum_needed 28",
842 "astraea_unl_list_expiration_timestamp_seconds{publisher=\"ED2677ABFFD1B33A\"} 946685800",
843 "astraea_history_first_ledger 86339141",
844 "astraea_storage_bytes{part=\"cold\"} 466000000000",
845 "astraea_proof_bundles_total{method=\"proof_tx\",confirmed_by=\"skip-list\"} 4",
846 "astraea_api_subscribers{stream=\"ledger\"} 2",
847 "astraea_api_inflight{pool=\"proof\"} 0",
848 ] {
849 assert!(text.contains(&format!("\n{line}\n")), "{line}");
850 }
851 let mut seen = std::collections::BTreeSet::new();
853 for line in text.lines() {
854 if let Some(rest) = line.strip_prefix("# TYPE ") {
855 assert!(
856 seen.insert(rest.split(' ').next().unwrap().to_owned()),
857 "{line}"
858 );
859 } else if !line.starts_with('#') {
860 let (_, v) = line.rsplit_once(' ').unwrap();
861 assert!(v.parse::<f64>().is_ok(), "{line}");
862 }
863 }
864 }
865
866 #[test]
867 fn dir_bytes_counts_nested_files() {
868 let dir = tempfile::tempdir().unwrap();
869 std::fs::write(dir.path().join("a"), [0u8; 10]).unwrap();
870 std::fs::create_dir(dir.path().join("sub")).unwrap();
871 std::fs::write(dir.path().join("sub/b"), [0u8; 5]).unwrap();
872 assert_eq!(dir_bytes(dir.path()), 15);
873 }
874}