Skip to main content

witness_archiver/
main.rs

1//! Archiver of signed XRPL validations.
2//!
3//! Subscribes to the node's validation stream through its local admin port
4//! and writes the originals (raw signed validations) into archive segments.
5//! It exposes nothing to the outside.
6//!
7//! Resilience:
8//! - the journal is flushed to disk once a second, so a crash loses at most
9//!   that much;
10//! - on disconnect it reconnects with a growing pause of up to 5 s: the node
11//!   is local, an attempt costs nothing, and every extra second of waiting
12//!   is validations that cannot be recovered. After a successful connection
13//!   the pause starts from one second again;
14//! - if the connection is up but no validations arrive for longer than
15//!   `--stall-secs`, that also counts as a disconnect: the node may have hung
16//!   while leaving the socket open;
17//! - every disconnect and recovery is written to `gaps.jsonl` as one line,
18//!   with the last and first ledger around it, so gaps are visible instead
19//!   of guessed. Failed reconnect attempts only go to the process log.
20//!   Shutdown is logged too, so downtime during a restart can be explained
21//!   from the journal.
22//!
23//! Metrics are served on `--metrics-addr`, see the `metrics` module.
24//! Validator manifests: see the `manifests` module.
25
26mod manifests;
27mod metrics;
28mod nunl;
29
30use std::fs::OpenOptions;
31use std::io::Write;
32use std::net::SocketAddr;
33use std::path::{Path, PathBuf};
34use std::sync::{Arc, Mutex};
35use std::time::Duration;
36
37use clap::Parser;
38use futures_util::{SinkExt, StreamExt};
39use serde_json::{Value, json};
40use tokio::time::{Instant, interval, sleep};
41use tokio_tungstenite::{connect_async, tungstenite::Message};
42use tracing::{error, info, warn};
43use witness_core::util::now_ms;
44use witness_store::segment::latest_seal;
45use witness_store::{Record, SegmentConfig, SegmentWriter};
46
47use crate::manifests::{Book, Outcome};
48use crate::metrics::{Metrics, Shared, lock};
49
50#[derive(Debug, Parser)]
51#[command(version, about = "Archiver of signed XRPL validations")]
52struct Args {
53    /// The node's admin WebSocket. Local address only: the archiver must not
54    /// reach the node over the network.
55    #[arg(long, env = "WITNESS_URL", default_value = "ws://127.0.0.1:6006")]
56    url: String,
57    /// Archive directory.
58    #[arg(long, env = "WITNESS_DATA_DIR")]
59    data_dir: PathBuf,
60    /// Source name in seals: which of our machines received the validations.
61    #[arg(long, env = "WITNESS_SOURCE")]
62    source: String,
63    /// Nominal segment size in ledgers; 1024 is about an hour.
64    #[arg(long, default_value_t = 1024)]
65    segment_ledgers: u32,
66    /// Margin for late validations before a segment is closed.
67    #[arg(long, default_value_t = 32)]
68    grace_ledgers: u32,
69    /// zstd level used when closing a segment. Going above 9 makes no sense:
70    /// validations are mostly signatures and keys, i.e. noise, and level 19 on
71    /// live data gains about one percent at 30 times the time. Compression
72    /// also runs on the same thread that reads the subscription.
73    #[arg(long, default_value_t = 9)]
74    zstd_level: i32,
75    /// How many seconds of silence on a live connection count as a disconnect.
76    #[arg(long, default_value_t = 60)]
77    stall_secs: u64,
78    /// Where to serve metrics, for example an address inside the monitoring
79    /// tunnel. If unset, there are no metrics.
80    #[arg(long, env = "WITNESS_METRICS_ADDR")]
81    metrics_addr: Option<SocketAddr>,
82    /// Directory of the UNL list collector on the same machine, used to report
83    /// in metrics when it last saw each publisher.
84    #[arg(long, env = "WITNESS_UNL_DIR")]
85    unl_dir: Option<PathBuf>,
86}
87
88/// Supporting evidence the archiver requests from the node over the same
89/// connection: validator manifests and the Negative UNL.
90struct Side {
91    book: Book,
92    nunl: nunl::Watch,
93}
94
95/// How a single connection session ended.
96enum SessionEnd {
97    Shutdown,
98    /// Connection lost. `was_connected` tells whether this session got connected
99    /// at all: a failed reconnect attempt is not a new disconnect.
100    Lost {
101        reason: String,
102        was_connected: bool,
103    },
104}
105
106fn lost(reason: impl Into<String>, was_connected: bool) -> SessionEnd {
107    SessionEnd::Lost {
108        reason: reason.into(),
109        was_connected,
110    }
111}
112
113const MAX_BACKOFF: Duration = Duration::from_secs(5);
114
115#[derive(Default)]
116struct Stats {
117    received: u64,
118    bad: u64,
119    window: u64,
120    sealed: u64,
121}
122
123#[tokio::main(flavor = "current_thread")]
124async fn main() {
125    tracing_subscriber::fmt()
126        .with_env_filter(
127            tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()),
128        )
129        .without_time() // journald adds the timestamp
130        // Colors only in a terminal: in journald the color codes are just garbage.
131        .with_ansi(std::io::IsTerminal::is_terminal(&std::io::stderr()))
132        .init();
133
134    let args = Args::parse();
135    if let Err(e) = run(args).await {
136        error!("stopped with error: {e}");
137        std::process::exit(1);
138    }
139}
140
141async fn run(args: Args) -> Result<(), Box<dyn std::error::Error>> {
142    if !args.url.starts_with("ws://127.0.0.1:") && !args.url.starts_with("ws://[::1]:") {
143        warn!(
144            "address {} is not local: the archiver is meant to connect to its own node",
145            args.url
146        );
147    }
148    let mut writer = SegmentWriter::open(SegmentConfig {
149        dir: args.data_dir.clone(),
150        source: args.source.clone(),
151        segment_ledgers: args.segment_ledgers,
152        grace_ledgers: args.grace_ledgers,
153        zstd_level: args.zstd_level,
154    })?;
155    if writer.torn_bytes_at_start > 0 {
156        warn!(
157            "cut off a torn journal tail at startup: {} bytes",
158            writer.torn_bytes_at_start
159        );
160    }
161    if let Some((first, n)) = writer.current() {
162        info!("continuing the open segment from ledger {first}, {n} records in it");
163    }
164    let gaps = args.data_dir.join("gaps.jsonl");
165    let metrics = start_metrics(&args, &writer)?;
166    let mut side = Side {
167        book: Book::open(&args.data_dir)?,
168        nunl: nunl::Watch::open(&args.data_dir)?,
169    };
170    let mut stats = Stats::default();
171    let mut backoff = Duration::from_secs(1);
172    let mut shutdown = Box::pin(shutdown_signal());
173
174    loop {
175        let end = session(
176            &args,
177            &mut writer,
178            &mut side,
179            &mut stats,
180            &metrics,
181            &gaps,
182            &mut shutdown,
183        )
184        .await;
185        lock(&metrics).connected = false;
186        match end {
187            SessionEnd::Shutdown => break,
188            SessionEnd::Lost {
189                reason,
190                was_connected,
191            } => {
192                writer.sync()?;
193                if was_connected {
194                    lock(&metrics).disconnects += 1;
195                    backoff = Duration::from_secs(1);
196                    log_gap(
197                        &gaps,
198                        json!({
199                            "event": "disconnected",
200                            "at_ms": now_ms(),
201                            "last_ledger": writer.last_ledger(),
202                            "reason": reason,
203                        }),
204                    );
205                }
206                warn!(
207                    "connection lost: {reason}; retrying in {} s",
208                    backoff.as_secs()
209                );
210            }
211        }
212        tokio::select! {
213            _ = sleep(backoff) => {}
214            _ = &mut shutdown => break,
215        }
216        backoff = (backoff * 2).min(MAX_BACKOFF);
217    }
218
219    writer.sync()?;
220    log_gap(
221        &gaps,
222        json!({"event": "stopped", "at_ms": now_ms(), "last_ledger": writer.last_ledger()}),
223    );
224    info!(
225        "stopped; received {}, rejected {}, segments sealed {}",
226        stats.received, stats.bad, stats.sealed
227    );
228    Ok(())
229}
230
231/// Initial metrics state, from what is already on disk, plus the server.
232fn start_metrics(
233    args: &Args,
234    writer: &SegmentWriter,
235) -> Result<Shared, Box<dyn std::error::Error>> {
236    let segments = args.data_dir.join("segments");
237    let mut archive_bytes = 0;
238    for entry in std::fs::read_dir(&segments)? {
239        let path = entry?.path();
240        if path.to_string_lossy().ends_with(".xwv.zst") {
241            archive_bytes += std::fs::metadata(&path)?.len();
242        }
243    }
244    let last = latest_seal(&segments)?;
245    let metrics: Shared = Arc::new(Mutex::new(Metrics {
246        source: args.source.clone(),
247        unl_dir: args.unl_dir.clone(),
248        archive_bytes,
249        journal_bytes: writer.journal_bytes(),
250        last_seal_ms: last.as_ref().map_or(0, |s| s.sealed_ms),
251        last_seal_missing: last
252            .as_ref()
253            .map_or(0, |s| missing_count(&s.missing_ledgers)),
254        ..Metrics::default()
255    }));
256    if let Some(addr) = args.metrics_addr {
257        tokio::spawn(metrics::serve(addr, metrics.clone()));
258    }
259    Ok(metrics)
260}
261
262fn missing_count(ranges: &[[u32; 2]]) -> u64 {
263    ranges
264        .iter()
265        .map(|[a, b]| u64::from(b.saturating_sub(*a)) + 1)
266        .sum()
267}
268
269async fn session(
270    args: &Args,
271    writer: &mut SegmentWriter,
272    side: &mut Side,
273    stats: &mut Stats,
274    metrics: &Shared,
275    gaps: &Path,
276    shutdown: &mut std::pin::Pin<Box<impl std::future::Future<Output = ()>>>,
277) -> SessionEnd {
278    let Side { book, nunl } = side;
279    let (mut ws, _) = tokio::select! {
280        r = connect_async(args.url.as_str()) => match r {
281            Ok(x) => x,
282            Err(e) => return lost(format!("connect: {e}"), false),
283        },
284        _ = &mut *shutdown => return SessionEnd::Shutdown,
285    };
286    let subscribe = json!({"id": 1, "command": "subscribe", "streams": ["validations"]});
287    if let Err(e) = ws.send(Message::text(subscribe.to_string())).await {
288        return lost(format!("subscribe: {e}"), true);
289    }
290    info!("connected to {}, validation subscription sent", args.url);
291    lock(metrics).connected = true;
292    log_gap(
293        gaps,
294        json!({"event": "connected", "at_ms": now_ms(), "last_ledger": writer.last_ledger()}),
295    );
296
297    let mut tick = interval(Duration::from_secs(1));
298    let mut report = interval(Duration::from_secs(60));
299    report.tick().await;
300    let stall = Duration::from_secs(args.stall_secs);
301    let mut last_validation = Instant::now();
302    let mut first_after_connect = true;
303
304    loop {
305        tokio::select! {
306            msg = ws.next() => {
307                let text = match msg {
308                    Some(Ok(Message::Text(t))) => t,
309                    Some(Ok(Message::Close(c))) => return lost(format!("node closed the connection: {c:?}"), true),
310                    Some(Ok(_)) => continue, // ping/pong/binary: the library answers pings itself
311                    Some(Err(e)) => return lost(format!("read: {e}"), true),
312                    None => return lost("stream ended", true),
313                };
314                let v: Value = match serde_json::from_str(&text) {
315                    Ok(v) => v,
316                    Err(e) => {
317                        stats.bad += 1;
318                        lock(metrics).rejected += 1;
319                        warn!("message is not json: {e}");
320                        continue;
321                    }
322                };
323                if Book::is_ours(&v) {
324                    match book.absorb(&v, now_ms()) {
325                        Ok(Outcome::Stored { master_key, seq }) => {
326                            lock(metrics).manifests_stored = book.stored_total;
327                            info!("manifest stored: {master_key}, seq {seq}");
328                        }
329                        Ok(_) => {}
330                        Err(e) => error!("writing manifest: {e}"),
331                    }
332                    continue;
333                }
334                if nunl::Watch::is_ours(&v) {
335                    match nunl.absorb(&v, now_ms()) {
336                        Ok((flag, Ok(0))) => info!("Negative UNL at flag ledger {flag}: empty"),
337                        Ok((flag, Ok(n))) => info!("Negative UNL at flag ledger {flag}: object of {n} bytes"),
338                        Ok((flag, Err(e))) => warn!("Negative UNL at flag ledger {flag}: node answered {e}"),
339                        Err(e) => error!("writing Negative UNL: {e}"),
340                    }
341                    continue;
342                }
343                match parse_validation_value(&v) {
344                    Ok(Some(Parsed { rec, key })) => {
345                        if first_after_connect {
346                            first_after_connect = false;
347                            log_gap(gaps, json!({"event": "first_validation", "at_ms": now_ms(), "ledger": rec.ledger_index}));
348                        }
349                        last_validation = Instant::now();
350                        let appended = writer.append(&rec);
351                        // The metrics lock is held only inside this block: the
352                        // socket send comes next, and the lock must not be held
353                        // across an await. None means the write failed and the
354                        // validation is not counted.
355                        let ask = {
356                            let mut m = lock(metrics);
357                            if let Some(net) = writer.network_ledger() {
358                                m.network_ledger = net;
359                            }
360                            match appended {
361                                Ok(sealed) => {
362                                    if let Some(sealed) = sealed {
363                                        stats.sealed += 1;
364                                        let s = &sealed.seal;
365                                        let missing = missing_count(&s.missing_ledgers);
366                                        m.sealed += 1;
367                                        m.last_seal_ms = s.sealed_ms;
368                                        m.last_seal_missing = missing;
369                                        m.missing_ledgers += missing;
370                                        m.archive_bytes += sealed.zst_bytes;
371                                        info!(
372                                            "segment sealed: {}..{} records {} gaps {} compressed {} -> {} bytes",
373                                            s.coverage_first, s.coverage_last, s.records,
374                                            s.missing_ledgers.len(), s.raw_bytes, sealed.zst_bytes
375                                        );
376                                    }
377                                    m.validations += 1;
378                                    m.last_validation_ms = rec.received_ms;
379                                    m.journal_bytes = writer.journal_bytes();
380                                    if writer.is_out_of_window(rec.ledger_index) {
381                                        m.out_of_window += 1;
382                                        Some(None)
383                                    } else if let Some(key) = &key {
384                                        m.saw_validator(key, rec.ledger_index);
385                                        // Only ask for manifests on our own network:
386                                        // the node does not know foreign validators anyway.
387                                        Some(book.request_for(key, rec.received_ms))
388                                    } else {
389                                        Some(None)
390                                    }
391                                }
392                                Err(e) => {
393                                    // A write error is no reason to drop the connection,
394                                    // but it must not go unreported either.
395                                    error!("writing to archive: {e}");
396                                    stats.bad += 1;
397                                    m.rejected += 1;
398                                    None
399                                }
400                            }
401                        };
402                        let Some(ask) = ask else { continue };
403                        if let Some(req) = ask
404                            && let Err(e) = ws.send(Message::text(req)).await
405                        {
406                            return lost(format!("manifest request: {e}"), true);
407                        }
408                        // Only after warmup: until a segment is open the reference is not reliable yet.
409                        if let Some(req) = writer.current().and(writer.network_ledger()).and_then(|n| nunl.request_for(n))
410                            && let Err(e) = ws.send(Message::text(req)).await
411                        {
412                            return lost(format!("Negative UNL request: {e}"), true);
413                        }
414                        stats.received += 1;
415                        stats.window += 1;
416                    }
417                    Ok(None) => {}
418                    Err(e) => {
419                        stats.bad += 1;
420                        lock(metrics).rejected += 1;
421                        warn!("could not parse message: {e}");
422                    }
423                }
424            }
425            _ = tick.tick() => {
426                if let Err(e) = writer.sync() {
427                    error!("journal flush: {e}");
428                }
429                if let Err(e) = ws.flush().await {
430                    return lost(format!("send: {e}"), true);
431                }
432                if last_validation.elapsed() > stall {
433                    return lost(format!("no validations for {} s on a live connection", stall.as_secs()), true);
434                }
435            }
436            _ = report.tick() => {
437                let cur = writer.current().map(|(f, n)| format!("segment from {f}, {n} records")).unwrap_or_default();
438                info!("{} validations in the last minute; total {}, rejected {}; {cur}", stats.window, stats.received, stats.bad);
439                stats.window = 0;
440            }
441            _ = &mut *shutdown => {
442                ws.close(None).await.ok();
443                return SessionEnd::Shutdown;
444            }
445        }
446    }
447}
448
449/// A validation from the stream: the archive record and the signer's key, for
450/// counting validators. The key may be missing; the record is just as good.
451struct Parsed {
452    rec: Record,
453    key: Option<String>,
454}
455
456/// Extracts the original validation and the ledger index from a stream message.
457/// `Ok(None)` means the message is not a validation (for example, the
458/// subscription response).
459#[cfg(test)]
460fn parse_validation(text: &str) -> Result<Option<Parsed>, String> {
461    let v: Value = serde_json::from_str(text).map_err(|e| format!("json: {e}"))?;
462    parse_validation_value(&v)
463}
464
465fn parse_validation_value(v: &Value) -> Result<Option<Parsed>, String> {
466    if v.get("type").and_then(Value::as_str) != Some("validationReceived") {
467        return Ok(None);
468    }
469    let data_hex = v
470        .get("data")
471        .and_then(Value::as_str)
472        .ok_or("no data field")?;
473    let data = hex::decode(data_hex).map_err(|e| format!("data is not hex: {e}"))?;
474    let ledger_index = match v.get("ledger_index") {
475        Some(Value::Number(n)) => n.as_u64(),
476        Some(Value::String(s)) => s.parse().ok(),
477        _ => None,
478    }
479    .and_then(|n| u32::try_from(n).ok())
480    .ok_or("missing or invalid ledger_index")?;
481    let key = v
482        .get("validation_public_key")
483        .and_then(Value::as_str)
484        .map(str::to_owned);
485    Ok(Some(Parsed {
486        rec: Record {
487            received_ms: now_ms(),
488            ledger_index,
489            data,
490        },
491        key,
492    }))
493}
494
495fn log_gap(path: &Path, event: Value) {
496    let line = format!("{event}\n");
497    let res = OpenOptions::new()
498        .create(true)
499        .append(true)
500        .open(path)
501        .and_then(|mut f| f.write_all(line.as_bytes()).and_then(|()| f.sync_data()));
502    if let Err(e) = res {
503        error!("gap log {}: {e}", path.display());
504    }
505}
506
507async fn shutdown_signal() {
508    #[cfg(unix)]
509    {
510        use tokio::signal::unix::{SignalKind, signal};
511        match signal(SignalKind::terminate()) {
512            Ok(mut term) => {
513                tokio::select! {
514                    _ = term.recv() => {}
515                    _ = tokio::signal::ctrl_c() => {}
516                }
517            }
518            Err(_) => {
519                tokio::signal::ctrl_c().await.ok();
520            }
521        }
522    }
523    #[cfg(not(unix))]
524    {
525        tokio::signal::ctrl_c().await.ok();
526    }
527    info!("received shutdown signal");
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533
534    #[test]
535    fn parses_a_real_shaped_message() {
536        let msg = r#"{"type":"validationReceived","data":"2280000001","ledger_index":107834197,"ledger_hash":"EC","validation_public_key":"n9K"}"#;
537        let p = parse_validation(msg).unwrap().unwrap();
538        assert_eq!(p.rec.ledger_index, 107_834_197);
539        assert_eq!(p.rec.data, vec![0x22, 0x80, 0x00, 0x00, 0x01]);
540        assert_eq!(p.key.as_deref(), Some("n9K"));
541    }
542
543    #[test]
544    fn string_ledger_index_is_accepted() {
545        let msg = r#"{"type":"validationReceived","data":"22","ledger_index":"42"}"#;
546        assert_eq!(parse_validation(msg).unwrap().unwrap().rec.ledger_index, 42);
547    }
548
549    #[test]
550    fn other_messages_are_skipped() {
551        assert!(
552            parse_validation(r#"{"type":"response","result":{}}"#)
553                .unwrap()
554                .is_none()
555        );
556    }
557
558    #[test]
559    fn missing_ranges_are_counted_inclusive() {
560        assert_eq!(missing_count(&[[10, 10], [20, 24]]), 6);
561        assert_eq!(missing_count(&[]), 0);
562    }
563
564    #[test]
565    fn broken_validation_is_an_error() {
566        assert!(
567            parse_validation(r#"{"type":"validationReceived","data":"zz","ledger_index":1}"#)
568                .is_err()
569        );
570        assert!(parse_validation(r#"{"type":"validationReceived","ledger_index":1}"#).is_err());
571    }
572}