1use std::fs::{File, OpenOptions};
12use std::io::{Read, Seek, SeekFrom, Write};
13use std::path::{Path, PathBuf};
14
15use crate::record::{MAX_DATA_LEN, Record};
16use crate::{Error, Result};
17
18pub const MAGIC: &[u8; 6] = b"XWVJ\x00\x01";
20
21#[derive(Debug)]
22pub struct Journal {
23 path: PathBuf,
24 file: File,
25 pending: Vec<u8>,
26 bytes: u64,
27}
28
29#[derive(Debug, Default)]
31pub struct Recovered {
32 pub records: Vec<Record>,
33 pub torn_bytes: u64,
35}
36
37impl Journal {
38 pub fn open(path: &Path) -> Result<(Journal, Recovered)> {
41 let mut file = OpenOptions::new()
42 .read(true)
43 .append(true)
44 .create(true)
45 .open(path)?;
46 let mut raw = Vec::new();
47 file.read_to_end(&mut raw)?;
48
49 let mut recovered = Recovered::default();
50 if raw.is_empty() {
51 file.write_all(MAGIC)?;
52 file.sync_data()?;
53 let bytes = MAGIC.len() as u64;
54 return Ok((
55 Journal {
56 path: path.to_owned(),
57 file,
58 pending: Vec::new(),
59 bytes,
60 },
61 recovered,
62 ));
63 }
64 if !raw.starts_with(MAGIC) {
65 return Err(Error::Format(format!(
66 "{}: not an xrpl-witness journal",
67 path.display()
68 )));
69 }
70
71 let mut at = MAGIC.len();
72 loop {
73 match Record::decode(&raw[at..]) {
74 Ok(Some((rec, used))) => {
75 recovered.records.push(rec);
76 at += used;
77 }
78 Ok(None) => break,
79 Err(e) => {
80 return Err(Error::Format(format!(
81 "{}: record at offset {at}: {e}",
82 path.display()
83 )));
84 }
85 }
86 }
87 if at < raw.len() {
88 recovered.torn_bytes = (raw.len() - at) as u64;
89 file.set_len(at as u64)?;
90 file.seek(SeekFrom::End(0))?;
91 file.sync_data()?;
92 }
93 Ok((
94 Journal {
95 path: path.to_owned(),
96 file,
97 pending: Vec::new(),
98 bytes: at as u64,
99 },
100 recovered,
101 ))
102 }
103
104 pub fn append(&mut self, rec: &Record) -> Result<()> {
105 if rec.data.len() > MAX_DATA_LEN {
106 return Err(Error::Format(format!(
107 "original of {} bytes exceeds the limit of {MAX_DATA_LEN}",
108 rec.data.len()
109 )));
110 }
111 rec.encode_into(&mut self.pending);
112 Ok(())
113 }
114
115 pub fn sync(&mut self) -> Result<()> {
117 if self.pending.is_empty() {
118 return Ok(());
119 }
120 self.file.write_all(&self.pending)?;
121 self.file.sync_data()?;
122 self.bytes += self.pending.len() as u64;
123 self.pending.clear();
124 Ok(())
125 }
126
127 pub fn len(&self) -> u64 {
129 self.bytes + self.pending.len() as u64
130 }
131
132 pub fn is_empty(&self) -> bool {
133 self.len() <= MAGIC.len() as u64
134 }
135
136 pub fn path(&self) -> &Path {
137 &self.path
138 }
139}
140
141#[cfg(test)]
142mod tests {
143 use super::*;
144
145 fn rec(i: u32) -> Record {
146 Record {
147 received_ms: u64::from(i),
148 ledger_index: 100 + i,
149 data: vec![i as u8; 233],
150 }
151 }
152
153 #[test]
154 fn records_survive_reopen() {
155 let dir = tempfile::tempdir().unwrap();
156 let path = dir.path().join("current.xwvj");
157 {
158 let (mut j, rec0) = Journal::open(&path).unwrap();
159 assert!(rec0.records.is_empty());
160 for i in 0..5 {
161 j.append(&rec(i)).unwrap();
162 }
163 j.sync().unwrap();
164 }
165 let (_, got) = Journal::open(&path).unwrap();
166 assert_eq!(got.records, (0..5).map(rec).collect::<Vec<_>>());
167 assert_eq!(got.torn_bytes, 0);
168 }
169
170 #[test]
171 fn unsynced_records_are_lost_but_journal_stays_valid() {
172 let dir = tempfile::tempdir().unwrap();
173 let path = dir.path().join("current.xwvj");
174 {
175 let (mut j, _) = Journal::open(&path).unwrap();
176 j.append(&rec(1)).unwrap();
177 j.sync().unwrap();
178 j.append(&rec(2)).unwrap(); }
180 let (_, got) = Journal::open(&path).unwrap();
181 assert_eq!(got.records, vec![rec(1)]);
182 }
183
184 #[test]
185 fn torn_tail_is_cut_and_writing_continues() {
186 let dir = tempfile::tempdir().unwrap();
187 let path = dir.path().join("current.xwvj");
188 {
189 let (mut j, _) = Journal::open(&path).unwrap();
190 j.append(&rec(1)).unwrap();
191 j.sync().unwrap();
192 }
193 let mut half = Vec::new();
195 rec(2).encode_into(&mut half);
196 OpenOptions::new()
197 .append(true)
198 .open(&path)
199 .unwrap()
200 .write_all(&half[..half.len() / 2])
201 .unwrap();
202
203 let (mut j, got) = Journal::open(&path).unwrap();
204 assert_eq!(got.records, vec![rec(1)]);
205 assert!(got.torn_bytes > 0);
206 j.append(&rec(3)).unwrap();
207 j.sync().unwrap();
208 let (_, got) = Journal::open(&path).unwrap();
209 assert_eq!(got.records, vec![rec(1), rec(3)]);
210 }
211
212 #[test]
213 fn foreign_file_is_refused() {
214 let dir = tempfile::tempdir().unwrap();
215 let path = dir.path().join("current.xwvj");
216 std::fs::write(&path, b"hello").unwrap();
217 assert!(Journal::open(&path).is_err());
218 }
219}