doublets/decorators/transactions/
log.rs1use std::{
4 fs::{File, OpenOptions},
5 io::{self, Read, Seek, SeekFrom, Write},
6 path::Path,
7};
8
9use data::LinkReference;
10
11use super::{JournalEntry, Transition, TransitionKind};
12use crate::Link;
13
14pub trait TransitionLog<T: LinkReference>: Send + Sync {
22 fn read_entries(&mut self) -> io::Result<Vec<JournalEntry<T>>>;
24 fn append(&mut self, entry: &JournalEntry<T>) -> io::Result<()>;
26}
27
28#[derive(Debug, Clone, Default)]
30pub struct MemoryTransitionLog<T: LinkReference> {
31 entries: Vec<JournalEntry<T>>,
32}
33
34impl<T: LinkReference> MemoryTransitionLog<T> {
35 #[must_use]
37 pub fn entries(&self) -> &[JournalEntry<T>] {
38 &self.entries
39 }
40}
41
42impl<T: LinkReference> TransitionLog<T> for MemoryTransitionLog<T> {
43 fn read_entries(&mut self) -> io::Result<Vec<JournalEntry<T>>> {
44 Ok(self.entries.clone())
45 }
46 fn append(&mut self, entry: &JournalEntry<T>) -> io::Result<()> {
47 self.entries.push(entry.clone());
48 Ok(())
49 }
50}
51
52#[derive(Debug)]
61pub struct FileTransitionLog<T: LinkReference> {
62 file: File,
63 marker: std::marker::PhantomData<T>,
64}
65
66impl<T: LinkReference> FileTransitionLog<T> {
67 pub fn open(path: impl AsRef<Path>) -> io::Result<Self> {
69 let file = OpenOptions::new()
70 .read(true)
71 .write(true)
72 .create(true)
73 .truncate(false)
74 .open(path)?;
75 let mut log = Self {
76 file,
77 marker: std::marker::PhantomData,
78 };
79 log.read_entries()?;
80 Ok(log)
81 }
82}
83
84impl<T: LinkReference> TransitionLog<T> for FileTransitionLog<T> {
85 fn read_entries(&mut self) -> io::Result<Vec<JournalEntry<T>>> {
86 self.file.seek(SeekFrom::Start(0))?;
87 let mut bytes = Vec::new();
88 self.file.read_to_end(&mut bytes)?;
89 let complete = bytes
90 .iter()
91 .rposition(|&byte| byte == b'\n')
92 .map_or(0, |i| i + 1);
93 let contents = std::str::from_utf8(&bytes[..complete]).map_err(invalid)?;
94 let entries = contents
95 .lines()
96 .map(decode)
97 .collect::<io::Result<Vec<_>>>()?;
98 if complete != bytes.len() {
99 self.file
100 .set_len(u64::try_from(complete).map_err(invalid)?)?;
101 self.file.sync_all()?;
102 }
103 self.file.seek(SeekFrom::End(0))?;
104 Ok(entries)
105 }
106
107 fn append(&mut self, entry: &JournalEntry<T>) -> io::Result<()> {
108 let payload = encode(entry);
109 writeln!(self.file, "{payload}#{:016x}", checksum(payload.as_bytes()))?;
110 self.file.sync_all()
111 }
112}
113
114fn invalid(error: impl std::fmt::Display) -> io::Error {
115 io::Error::new(io::ErrorKind::InvalidData, error.to_string())
116}
117
118fn checksum(bytes: &[u8]) -> u64 {
119 bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
120 (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3)
121 })
122}
123
124fn link_text<T: LinkReference>(link: &Link<T>) -> String {
125 format!("{},{},{}", link.index, link.source, link.target)
126}
127
128fn encode<T: LinkReference>(entry: &JournalEntry<T>) -> String {
129 let body = match entry {
130 JournalEntry::Begin {
131 transaction_id,
132 snapshot,
133 }
134 | JournalEntry::Commit {
135 transaction_id,
136 snapshot,
137 } => {
138 let kind = if matches!(entry, JournalEntry::Begin { .. }) {
139 "B"
140 } else {
141 "C"
142 };
143 let snapshot = snapshot.iter().map(link_text).collect::<Vec<_>>().join(";");
144 format!("{kind}|{transaction_id}|{snapshot}")
145 }
146 JournalEntry::Rollback { transaction_id } => format!("R|{transaction_id}"),
147 JournalEntry::Transition(t) => {
148 let kind = match t.kind {
149 TransitionKind::Create => "C",
150 TransitionKind::Update => "U",
151 TransitionKind::Delete => "D",
152 };
153 format!(
154 "T|{}|{}|{kind}|{}|{}",
155 t.transaction_id,
156 t.sequence,
157 link_text(&t.before),
158 link_text(&t.after)
159 )
160 }
161 };
162 format!("doublets-tx-v1|{body}")
163}
164
165fn parse_link<T: LinkReference>(text: &str) -> io::Result<Link<T>> {
166 let fields: Vec<_> = text.split(',').collect();
167 let [index, source, target] = fields.as_slice() else {
168 return Err(invalid("invalid link triple"));
169 };
170 let address = |text: &str| {
171 let value = text.parse::<u128>().map_err(invalid)?;
172 T::try_from(value)
173 .map_err(|_| invalid(format!("address {value} exceeds journal address type")))
174 };
175 Ok(Link::new(
176 address(index)?,
177 address(source)?,
178 address(target)?,
179 ))
180}
181
182fn decode<T: LinkReference>(line: &str) -> io::Result<JournalEntry<T>> {
183 let (payload, hash) = line
184 .rsplit_once('#')
185 .ok_or_else(|| invalid("missing journal checksum"))?;
186 if checksum(payload.as_bytes()) != u64::from_str_radix(hash, 16).map_err(invalid)? {
187 return Err(invalid("journal checksum mismatch"));
188 }
189 let fields: Vec<_> = payload.split('|').collect();
190 if fields.first() != Some(&"doublets-tx-v1") {
191 return Err(invalid("unsupported journal version"));
192 }
193 match &fields[1..] {
194 [kind @ ("B" | "C"), id, snapshot] => {
195 let transaction_id = id.parse().map_err(invalid)?;
196 let snapshot = if snapshot.is_empty() {
197 Vec::new()
198 } else {
199 snapshot
200 .split(';')
201 .map(parse_link)
202 .collect::<io::Result<Vec<_>>>()?
203 };
204 Ok(if *kind == "B" {
205 JournalEntry::Begin {
206 transaction_id,
207 snapshot,
208 }
209 } else {
210 JournalEntry::Commit {
211 transaction_id,
212 snapshot,
213 }
214 })
215 }
216 ["R", id] => Ok(JournalEntry::Rollback {
217 transaction_id: id.parse().map_err(invalid)?,
218 }),
219 ["T", id, sequence, kind, before, after] => {
220 let t = Transition::new(
221 id.parse().map_err(invalid)?,
222 sequence.parse().map_err(invalid)?,
223 parse_link(before)?,
224 parse_link(after)?,
225 );
226 let expected = match t.kind {
227 TransitionKind::Create => "C",
228 TransitionKind::Update => "U",
229 TransitionKind::Delete => "D",
230 };
231 if *kind != expected {
232 return Err(invalid("invalid transition kind"));
233 }
234 Ok(JournalEntry::Transition(t))
235 }
236 _ => Err(invalid("invalid journal record")),
237 }
238}