1use std::fs::{self, OpenOptions};
13use std::io::Write;
14use std::path::{Path, PathBuf};
15
16use serde_json::{Value, json};
17use witness_core::negative_unl::INDEX;
18
19const ID_PREFIX: &str = "nunl:";
25
26const SETTLE: u32 = 4;
28
29#[derive(Debug)]
30pub struct Watch {
31 path: PathBuf,
32 last_flag: Option<u32>,
33}
34
35impl Watch {
36 pub fn open(data_dir: &Path) -> std::io::Result<Watch> {
37 let dir = data_dir.join("negative_unl");
38 fs::create_dir_all(&dir)?;
39 Ok(Watch {
40 path: dir.join("observations.jsonl"),
41 last_flag: None,
42 })
43 }
44
45 pub fn request_for(&mut self, network_ledger: u32) -> Option<String> {
48 let flag = network_ledger.checked_sub(SETTLE)? / 256 * 256;
49 if flag == 0 || self.last_flag == Some(flag) {
50 return None;
51 }
52 self.last_flag = Some(flag);
53 Some(
54 json!({"id": format!("{ID_PREFIX}{flag}"), "command": "ledger_entry",
55 "index": INDEX, "ledger_index": flag, "binary": true})
56 .to_string(),
57 )
58 }
59
60 fn flag_of(v: &Value) -> Option<u64> {
61 v.get("id")?.as_str()?.strip_prefix(ID_PREFIX)?.parse().ok()
62 }
63
64 pub fn is_ours(v: &Value) -> bool {
65 v.get("type").and_then(Value::as_str) == Some("response") && Self::flag_of(v).is_some()
66 }
67
68 pub fn absorb(
71 &mut self,
72 v: &Value,
73 at_ms: u64,
74 ) -> std::io::Result<(u64, Result<usize, String>)> {
75 let flag = Self::flag_of(v).unwrap_or(0);
76 let result = v.get("result").cloned().unwrap_or(Value::Null);
77 let node_binary = result.get("node_binary").and_then(Value::as_str);
78 let field = |k: &str| result.get(k).or_else(|| v.get(k)).cloned();
80 let error = field("error");
81 let line = json!({
82 "at_ms": at_ms,
83 "flag_ledger": flag,
84 "ledger_index": field("ledger_index"),
85 "ledger_hash": field("ledger_hash"),
86 "validated": field("validated"),
87 "status": v.get("status"),
88 "error": error,
89 "node_binary": node_binary,
90 });
91 let mut f = OpenOptions::new()
92 .create(true)
93 .append(true)
94 .open(&self.path)?;
95 f.write_all(format!("{line}\n").as_bytes())?;
96 f.sync_data()?;
97 let outcome = match (node_binary, error.as_ref().and_then(Value::as_str)) {
98 (Some(b), _) => Ok(b.len() / 2),
99 (None, Some("entryNotFound")) => Ok(0),
100 (None, e) => Err(e.unwrap_or("response without an object").to_owned()),
101 };
102 Ok((flag, outcome))
103 }
104}
105
106#[cfg(test)]
107mod tests {
108 use super::*;
109
110 #[test]
111 fn asks_once_per_flag_ledger_after_it_settles() {
112 let dir = tempfile::tempdir().unwrap();
113 let mut w = Watch::open(dir.path()).unwrap();
114 assert!(w.request_for(107_854_851).unwrap().contains("107854592"));
116 assert!(w.request_for(107_854_852).unwrap().contains("107854848"));
117 assert!(w.request_for(107_854_900).is_none());
118 assert!(w.request_for(107_855_108).unwrap().contains("107855104"));
119 }
120
121 #[test]
122 fn empty_answer_is_recorded_too() {
123 let dir = tempfile::tempdir().unwrap();
124 let mut w = Watch::open(dir.path()).unwrap();
125 let v = json!({"id": "nunl:107854848", "type": "response", "status": "error",
126 "error": "entryNotFound", "result": {"ledger_index": 107_854_848}});
127 assert!(Watch::is_ours(&v));
128 assert_eq!(w.absorb(&v, 1).unwrap(), (107_854_848, Ok(0)));
129 let lost = json!({"id": "nunl:21767168", "type": "response", "status": "error",
130 "error": "lgrNotFound"});
131 assert_eq!(
132 w.absorb(&lost, 2).unwrap(),
133 (21_767_168, Err("lgrNotFound".into()))
134 );
135 let log = fs::read_to_string(dir.path().join("negative_unl/observations.jsonl")).unwrap();
136 assert!(log.contains("entryNotFound"));
137 assert!(!Watch::is_ours(&json!({"id": 1000, "type": "response"})));
138 }
139}