1use std::collections::HashMap;
12use std::fmt::Write as _;
13use std::net::SocketAddr;
14use std::path::{Path, PathBuf};
15use std::sync::{Arc, Mutex, MutexGuard};
16use std::time::Duration;
17
18use tokio::io::{AsyncReadExt, AsyncWriteExt};
19use tokio::net::{TcpListener, TcpStream};
20use tokio::time::{sleep, timeout};
21use tracing::{info, warn};
22
23const ACTIVE_LEDGERS: u32 = 8;
26
27const FORGET_LEDGERS: u32 = 256;
29
30#[derive(Debug, Default)]
31pub struct Metrics {
32 pub source: String,
33 pub connected: bool,
34 pub validations: u64,
35 pub out_of_window: u64,
36 pub rejected: u64,
37 pub disconnects: u64,
38 pub last_validation_ms: u64,
39 pub network_ledger: u32,
41 pub sealed: u64,
42 pub last_seal_ms: u64,
43 pub last_seal_missing: u64,
44 pub missing_ledgers: u64,
46 pub archive_bytes: u64,
47 pub journal_bytes: u64,
48 pub manifests_stored: u64,
49 pub unl_dir: Option<PathBuf>,
51 pub(crate) validators: HashMap<String, u32>,
53}
54
55pub type Shared = Arc<Mutex<Metrics>>;
56
57pub fn lock(m: &Shared) -> MutexGuard<'_, Metrics> {
60 m.lock().unwrap_or_else(|p| p.into_inner())
61}
62
63impl Metrics {
64 pub fn saw_validator(&mut self, key: &str, ledger: u32) {
65 let e = self.validators.entry(key.to_owned()).or_insert(ledger);
66 *e = (*e).max(ledger);
67 }
68
69 pub fn active_validators(&self) -> usize {
71 self.validators
72 .values()
73 .filter(|l| l.saturating_add(ACTIVE_LEDGERS) >= self.network_ledger)
74 .count()
75 }
76
77 pub fn forget_silent(&mut self) {
78 let now = self.network_ledger;
79 self.validators
80 .retain(|_, l| l.saturating_add(FORGET_LEDGERS) >= now);
81 }
82
83 pub fn render(&self) -> String {
84 let mut out = String::new();
85 let _ = writeln!(
87 out,
88 "# HELP xrpl_witness_info Archiver version and the source name used in seals.\n\
89 # TYPE xrpl_witness_info gauge\n\
90 xrpl_witness_info{{version=\"{}\",source=\"{}\"}} 1",
91 env!("CARGO_PKG_VERSION"),
92 self.source.replace('\\', "\\\\").replace('"', "\\\"")
93 );
94 let mut put = |name: &str, kind: &str, help: &str, value: String| {
95 let _ = writeln!(out, "# HELP xrpl_witness_{name} {help}");
96 let _ = writeln!(out, "# TYPE xrpl_witness_{name} {kind}");
97 let _ = writeln!(out, "xrpl_witness_{name} {value}");
98 };
99 let secs = |ms: u64| format!("{:.3}", ms as f64 / 1000.0);
100 put(
101 "connected",
102 "gauge",
103 "The subscription to the node's validation stream is active.",
104 u8::from(self.connected).to_string(),
105 );
106 put(
107 "validations_total",
108 "counter",
109 "Validations written to the archive.",
110 self.validations.to_string(),
111 );
112 put(
113 "validations_out_of_window_total",
114 "counter",
115 "Of those, far from the current ledger: other networks and very late ones.",
116 self.out_of_window.to_string(),
117 );
118 put(
119 "rejected_total",
120 "counter",
121 "Messages that could not be parsed or written.",
122 self.rejected.to_string(),
123 );
124 put(
125 "disconnects_total",
126 "counter",
127 "Disconnects from the node.",
128 self.disconnects.to_string(),
129 );
130 put(
131 "last_validation_timestamp_seconds",
132 "gauge",
133 "When the last validation was written, Unix time.",
134 secs(self.last_validation_ms),
135 );
136 put(
137 "network_ledger",
138 "gauge",
139 "The network's current ledger, from the stream median.",
140 self.network_ledger.to_string(),
141 );
142 put(
143 "validators",
144 "gauge",
145 "Distinct validators over the last 8 ledgers.",
146 self.active_validators().to_string(),
147 );
148 put(
149 "segments_sealed_total",
150 "counter",
151 "Segments sealed since startup.",
152 self.sealed.to_string(),
153 );
154 put(
155 "last_seal_timestamp_seconds",
156 "gauge",
157 "When the last segment was sealed, Unix time.",
158 secs(self.last_seal_ms),
159 );
160 put(
161 "last_seal_missing_ledgers",
162 "gauge",
163 "Missing ledgers in the last seal.",
164 self.last_seal_missing.to_string(),
165 );
166 put(
167 "missing_ledgers_total",
168 "counter",
169 "Missing ledgers across all seals since startup.",
170 self.missing_ledgers.to_string(),
171 );
172 put(
173 "archive_bytes",
174 "gauge",
175 "Size of closed segments on disk.",
176 self.archive_bytes.to_string(),
177 );
178 put(
179 "journal_bytes",
180 "gauge",
181 "Size of the open segment's journal.",
182 self.journal_bytes.to_string(),
183 );
184 put(
185 "manifests_stored_total",
186 "counter",
187 "New validator manifests stored since startup.",
188 self.manifests_stored.to_string(),
189 );
190 if let Some(dir) = &self.unl_dir {
191 let _ = writeln!(
192 out,
193 "# HELP xrpl_witness_unl_last_success_timestamp_seconds Last successful poll of a UNL list publisher.\n\
194 # TYPE xrpl_witness_unl_last_success_timestamp_seconds gauge"
195 );
196 for (site, ms) in unl_last_success(&dir.join("observations.jsonl")) {
197 let _ = writeln!(
198 out,
199 "xrpl_witness_unl_last_success_timestamp_seconds{{site=\"{}\"}} {}",
200 site.replace('\\', "\\\\").replace('"', "\\\""),
201 secs(ms)
202 );
203 }
204 }
205 out
206 }
207}
208
209fn unl_last_success(path: &Path) -> Vec<(String, u64)> {
213 use std::io::{Read, Seek, SeekFrom};
214 const TAIL: u64 = 32 * 1024;
215 let mut buf = String::new();
216 let Ok(mut f) = std::fs::File::open(path) else {
217 return Vec::new();
218 };
219 let len = f.metadata().map(|m| m.len()).unwrap_or(0);
220 if f.seek(SeekFrom::Start(len.saturating_sub(TAIL))).is_err()
221 || f.read_to_string(&mut buf).is_err()
222 {
223 return Vec::new();
224 }
225 let mut best: HashMap<String, u64> = HashMap::new();
226 for line in buf.lines() {
227 let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
228 continue; };
230 let ok = v.get("status").and_then(|s| s.as_u64()) == Some(200) && v.get("error").is_none();
231 if let (true, Some(site), Some(at)) = (
232 ok,
233 v.get("site").and_then(|s| s.as_str()),
234 v.get("at_ms").and_then(|a| a.as_u64()),
235 ) {
236 let e = best.entry(site.to_owned()).or_insert(at);
237 *e = (*e).max(at);
238 }
239 }
240 let mut out: Vec<_> = best.into_iter().collect();
241 out.sort();
242 out
243}
244
245pub async fn serve(addr: SocketAddr, metrics: Shared) {
246 loop {
247 let listener = match TcpListener::bind(addr).await {
248 Ok(l) => l,
249 Err(e) => {
250 warn!("metrics: cannot listen on {addr}: {e}; retrying in 10 s");
251 sleep(Duration::from_secs(10)).await;
252 continue;
253 }
254 };
255 info!("metrics on http://{addr}/metrics");
256 loop {
257 match listener.accept().await {
258 Ok((stream, _)) => {
261 let _ = timeout(Duration::from_secs(5), answer(stream, &metrics)).await;
262 }
263 Err(e) => {
264 warn!("metrics: accept: {e}");
265 sleep(Duration::from_secs(1)).await;
266 }
267 }
268 }
269 }
270}
271
272async fn answer(mut stream: TcpStream, metrics: &Shared) -> std::io::Result<()> {
273 let mut buf = [0u8; 1024];
274 let n = stream.read(&mut buf).await?;
275 let head = String::from_utf8_lossy(&buf[..n]);
276 let (status, body) = if head.starts_with("GET /metrics ") || head.starts_with("GET /metrics?") {
277 let mut m = lock(metrics);
278 m.forget_silent();
279 ("200 OK", m.render())
280 } else {
281 ("404 Not Found", String::from("only /metrics\n"))
282 };
283 let reply = format!(
284 "HTTP/1.1 {status}\r\nContent-Type: text/plain; version=0.0.4; charset=utf-8\r\n\
285 Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
286 body.len()
287 );
288 stream.write_all(reply.as_bytes()).await?;
289 stream.shutdown().await
290}
291
292#[cfg(test)]
293mod tests {
294 use super::*;
295
296 #[test]
297 fn active_validators_follow_the_network() {
298 let mut m = Metrics {
299 network_ledger: 1000,
300 ..Metrics::default()
301 };
302 m.saw_validator("A", 1000);
303 m.saw_validator("B", 995);
304 m.saw_validator("C", 900); m.saw_validator("B", 999);
306 assert_eq!(m.active_validators(), 2);
307 m.network_ledger = 1500;
308 m.forget_silent();
309 assert_eq!(m.active_validators(), 0);
310 assert!(m.validators.is_empty());
311 }
312
313 #[test]
314 fn unl_freshness_comes_from_the_collector_log() {
315 let dir = tempfile::tempdir().unwrap();
316 let log = dir.path().join("observations.jsonl");
317 std::fs::write(
318 &log,
319 "{\"at_ms\":1000,\"site\":\"a\",\"status\":200}\n\
320 {\"at_ms\":2000,\"site\":\"a\",\"error\":\"timeout\"}\n\
321 {\"at_ms\":1500,\"site\":\"b\",\"status\":200}\n",
322 )
323 .unwrap();
324 assert_eq!(
325 unl_last_success(&log),
326 vec![("a".into(), 1000), ("b".into(), 1500)]
327 );
328 let m = Metrics {
329 unl_dir: Some(dir.path().to_owned()),
330 ..Metrics::default()
331 };
332 assert!(
333 m.render()
334 .contains("xrpl_witness_unl_last_success_timestamp_seconds{site=\"b\"} 1.500\n")
335 );
336 }
337
338 #[test]
339 fn render_is_valid_exposition() {
340 let m = Metrics {
341 source: "node-\"a\"".into(),
342 validations: 7,
343 last_validation_ms: 1_500,
344 ..Metrics::default()
345 };
346 let text = m.render();
347 assert!(text.contains("xrpl_witness_info{version=\""));
348 assert!(text.contains("source=\"node-\\\"a\\\"\"} 1\n"));
349 assert!(text.contains("\nxrpl_witness_validations_total 7\n"));
350 assert!(text.contains("\nxrpl_witness_last_validation_timestamp_seconds 1.500\n"));
351 for line in text.lines().filter(|l| !l.starts_with('#')) {
353 let (_, v) = line.rsplit_once(' ').unwrap();
354 assert!(v.parse::<f64>().is_ok(), "{line}");
355 }
356 }
357}