1use std::collections::VecDeque;
37use std::fs::{self, File, OpenOptions};
38use std::io::{Read, Write};
39use std::os::unix::fs::FileExt;
40use std::path::{Path, PathBuf};
41use std::sync::{Arc, Mutex, RwLock};
42
43use witness_core::ledger::HEADER_LEN;
44use witness_core::sha512_half;
45
46use crate::ledger::Ledger;
47
48const TX_MAGIC: &[u8; 6] = b"XWLT\x00\x01";
49const TX_IDX_MAGIC: &[u8; 6] = b"XWTI\x00\x01";
50const CH_MAGIC: &[u8; 6] = b"XWLC\x00\x01";
53const CH_MAGIC_DELTA: &[u8; 6] = b"XWLC\x00\x02";
54const CH_IDX_MAGIC: &[u8; 6] = b"XWCI\x00\x01";
55const TX_ENTRY: usize = 4 + 8 + 4;
56const CH_ENTRY: usize = 4 + 4 + 8 + 4;
57const NO_DICT: [u8; 32] = [0; 32];
58const TX_CACHE: usize = 64;
60const CH_CACHE: usize = 2;
61
62type Res<T> = Result<T, String>;
63
64fn io(e: std::io::Error) -> String {
65 e.to_string()
66}
67
68fn le32(b: &[u8], at: usize) -> u32 {
69 u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
70}
71
72fn rd32(b: &[u8], at: usize) -> Res<u32> {
74 b.get(at..at.saturating_add(4))
75 .map(|x| u32::from_le_bytes([x[0], x[1], x[2], x[3]]))
76 .ok_or_else(|| corrupt(format!("record truncated at {at}")))
77}
78
79fn corrupt(what: String) -> String {
81 format!("corrupt_history: {what}")
82}
83
84const MAX_DECODED: usize = 256 << 20;
87
88fn le64(b: &[u8], at: usize) -> u64 {
89 let mut a = [0u8; 8];
90 a.copy_from_slice(&b[at..at + 8]);
91 u64::from_le_bytes(a)
92}
93
94#[derive(Debug, Clone)]
96pub struct Dict {
97 pub id: [u8; 32],
98 pub bytes: Arc<Vec<u8>>,
99}
100
101fn dict_path(dir: &Path, id: &[u8; 32]) -> PathBuf {
102 dir.join("dicts")
103 .join(format!("{}.zdict", hex::encode_upper(id)))
104}
105
106impl Dict {
107 pub fn store(dir: &Path, bytes: Vec<u8>) -> Res<Dict> {
110 let id = sha512_half(&bytes);
111 let dicts = dir.join("dicts");
112 fs::create_dir_all(&dicts).map_err(io)?;
113 let path = dict_path(dir, &id);
114 if !path.exists() {
115 let tmp = dicts.join(".new.zdict");
116 let mut f = File::create(&tmp).map_err(io)?;
117 f.write_all(&bytes).map_err(io)?;
118 f.sync_all().map_err(io)?;
119 fs::rename(&tmp, &path).map_err(io)?;
120 }
121 let tmp = dicts.join(".current");
122 fs::write(&tmp, hex::encode_upper(id)).map_err(io)?;
123 fs::rename(&tmp, dicts.join("current")).map_err(io)?;
124 File::open(&dicts).and_then(|d| d.sync_all()).map_err(io)?;
125 Ok(Dict {
126 id,
127 bytes: Arc::new(bytes),
128 })
129 }
130
131 pub fn load(dir: &Path, id: &[u8; 32]) -> Res<Dict> {
133 let bytes = fs::read(dict_path(dir, id))
134 .map_err(|e| format!("dictionary {}: {e}", hex::encode_upper(id)))?;
135 if sha512_half(&bytes) != *id {
136 return Err(format!(
137 "dictionary {}: content does not match the hash",
138 hex::encode_upper(id)
139 ));
140 }
141 Ok(Dict {
142 id: *id,
143 bytes: Arc::new(bytes),
144 })
145 }
146
147 pub fn current(dir: &Path) -> Res<Option<Dict>> {
149 match fs::read_to_string(dir.join("dicts").join("current")) {
150 Ok(s) => {
151 let id: [u8; 32] = hex::decode(s.trim())
152 .ok()
153 .and_then(|b| b.try_into().ok())
154 .ok_or("dicts/current: not a hash")?;
155 Ok(Some(Dict::load(dir, &id)?))
156 }
157 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
158 Err(e) => Err(e.to_string()),
159 }
160 }
161}
162
163pub fn tx_frame(l: &Ledger) -> Vec<u8> {
165 let size: usize = l
166 .transactions
167 .iter()
168 .map(|(t, m)| t.len() + m.len() + 8)
169 .sum();
170 let mut out = Vec::with_capacity(HEADER_LEN + 4 + size);
171 out.extend_from_slice(&l.header);
172 out.extend_from_slice(&(l.transactions.len() as u32).to_le_bytes());
173 for (t, m) in &l.transactions {
174 out.extend_from_slice(&(t.len() as u32).to_le_bytes());
175 out.extend_from_slice(t);
176 out.extend_from_slice(&(m.len() as u32).to_le_bytes());
177 out.extend_from_slice(m);
178 }
179 out
180}
181
182fn changes_part(l: &Ledger) -> Vec<u8> {
184 let mut e = Ledger {
185 header: Vec::new(),
186 transactions: Vec::new(),
187 changes: l.changes.clone(),
188 }
189 .encode();
190 e.drain(..4);
192 e
193}
194
195fn assemble(frame: &[u8], changes: Option<&[u8]>) -> Res<Ledger> {
197 if frame.len() < HEADER_LEN + 4 {
198 return Err("transaction frame truncated".into());
199 }
200 let mut body = frame.to_vec();
201 match changes {
202 Some(c) => body.extend_from_slice(c),
203 None => body.extend_from_slice(&0u32.to_le_bytes()),
204 }
205 Ledger::decode(&body)
206}
207
208#[derive(Debug)]
209struct Writer {
210 tx: File,
211 tx_idx: File,
212 tx_offset: u64,
213 ch: File,
214 ch_idx: File,
215 ch_offset: u64,
216}
217
218pub struct HistoryWriter {
220 w: Writer,
221 tx_comp: zstd::bulk::Compressor<'static>,
222 changes_level: i32,
223 changes_group: u32,
224 delta: bool,
225 pending: Vec<(u32, Ledger, Vec<u8>)>,
227}
228
229pub type PrevAt = dyn Fn(&[u8; 32], u32) -> Res<Option<Vec<u8>>> + Send + Sync;
231
232impl std::fmt::Debug for HistoryWriter {
233 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234 f.debug_struct("HistoryWriter").finish_non_exhaustive()
235 }
236}
237
238fn create_new(path: &Path, magic: &[u8]) -> Res<File> {
239 let mut f = OpenOptions::new()
240 .create_new(true)
241 .write(true)
242 .open(path)
243 .map_err(io)?;
244 f.write_all(magic).map_err(io)?;
245 Ok(f)
246}
247
248fn sync_dir(dir: &Path) -> Res<()> {
249 File::open(dir).and_then(|d| d.sync_all()).map_err(io)
250}
251
252fn finish_swap(dir: &Path, ch_path: &Path) -> Res<()> {
255 for (new, to) in [
256 (ch_path.with_extension("xwlc.new"), ch_path.to_path_buf()),
257 (
258 ch_path.with_extension("xwlc.idx.new"),
259 ch_path.with_extension("xwlc.idx"),
260 ),
261 ] {
262 if new.exists() {
263 fs::rename(&new, &to).map_err(io)?;
264 }
265 }
266 sync_dir(dir)?;
267 fs::remove_file(ch_path.with_extension("swap")).map_err(io)?;
268 sync_dir(dir)
269}
270
271impl HistoryWriter {
272 pub fn create(
279 dir: &Path,
280 first: u32,
281 changes_group: u32,
282 tx_level: i32,
283 changes_level: i32,
284 dict: Option<&Dict>,
285 delta: bool,
286 ) -> Res<HistoryWriter> {
287 fs::create_dir_all(dir).map_err(io)?;
288 let base = |ext: &str| {
289 dir.join(format!(
290 "{}-{first:010}.{ext}",
291 if ext.starts_with("xwlt") {
292 "txl"
293 } else {
294 "chg"
295 }
296 ))
297 };
298 let (tx_path, tx_idx_path) = (base("xwlt"), base("xwlt.idx"));
299 let (ch_path, ch_idx_path) = (base("xwlc"), base("xwlc.idx"));
300 let no_group = fs::metadata(&ch_idx_path)
301 .map(|m| m.len() < (CH_IDX_MAGIC.len() + CH_ENTRY) as u64)
302 .unwrap_or(true);
303 if (tx_path.exists() || tx_idx_path.exists() || ch_path.exists() || ch_idx_path.exists())
304 && no_group
305 {
306 for p in [&tx_path, &tx_idx_path, &ch_path, &ch_idx_path] {
307 let _ = fs::remove_file(p);
308 }
309 }
310 let dict_id = dict.map_or(NO_DICT, |d| d.id);
311 let mut tx = create_new(&tx_path, TX_MAGIC)?;
312 tx.write_all(&dict_id).map_err(io)?;
313 let tx_idx = create_new(&tx_idx_path, TX_IDX_MAGIC)?;
314 let ch = create_new(&ch_path, if delta { CH_MAGIC_DELTA } else { CH_MAGIC })?;
315 let ch_idx = create_new(&ch_idx_path, CH_IDX_MAGIC)?;
316 sync_dir(dir)?;
317 let tx_comp = match dict {
318 Some(d) => zstd::bulk::Compressor::with_dictionary(tx_level, &d.bytes).map_err(io)?,
319 None => zstd::bulk::Compressor::new(tx_level).map_err(io)?,
320 };
321 Ok(HistoryWriter {
322 w: Writer {
323 tx,
324 tx_idx,
325 tx_offset: (TX_MAGIC.len() + 32) as u64,
326 ch,
327 ch_idx,
328 ch_offset: CH_MAGIC.len() as u64,
329 },
330 tx_comp,
331 changes_level,
332 changes_group: changes_group.max(1),
333 delta,
334 pending: Vec::new(),
335 })
336 }
337
338 pub fn append(&mut self, sequence: u32, body: Vec<u8>, prev: Option<&PrevAt>) -> Res<()> {
341 if let Some((last, ..)) = self.pending.last()
342 && sequence != last + 1
343 {
344 return Err(format!("ledgers out of sequence: {last} → {sequence}"));
345 }
346 let l = Ledger::decode(&body)?;
347 let record = if self.delta {
348 let prev = prev.ok_or("format 3 changes need the previous version of objects")?;
349 let at = sequence - 1;
350 crate::delta::encode(&l, sequence, &|k| prev(k, at))?.0
351 } else {
352 changes_part(&l)
353 };
354 self.pending.push((sequence, l, record));
355 if self.pending.len() as u32 >= self.changes_group {
356 self.flush()?;
357 }
358 Ok(())
359 }
360
361 pub fn buffered(&self) -> usize {
362 self.pending.len()
363 }
364
365 pub fn flush(&mut self) -> Res<()> {
367 if self.pending.is_empty() {
368 return Ok(());
369 }
370 let w = &mut self.w;
371 let mut idx = Vec::with_capacity(self.pending.len() * TX_ENTRY);
372 for (seq, l, _) in &self.pending {
373 let z = self.tx_comp.compress(&tx_frame(l)).map_err(io)?;
374 w.tx.write_all(&z).map_err(io)?;
375 idx.extend_from_slice(&seq.to_le_bytes());
376 idx.extend_from_slice(&w.tx_offset.to_le_bytes());
377 idx.extend_from_slice(&(z.len() as u32).to_le_bytes());
378 w.tx_offset += z.len() as u64;
379 }
380 w.tx.sync_data().map_err(io)?;
381 w.tx_idx.write_all(&idx).map_err(io)?;
382 w.tx_idx.sync_data().map_err(io)?;
383
384 let mut raw = (self.pending.len() as u32).to_le_bytes().to_vec();
385 for (seq, _, p) in &self.pending {
386 raw.extend_from_slice(&seq.to_le_bytes());
387 raw.extend_from_slice(&(p.len() as u32).to_le_bytes());
388 }
389 for (_, _, p) in &self.pending {
390 raw.extend_from_slice(p);
391 }
392 let z = zstd::bulk::compress(&raw, self.changes_level).map_err(io)?;
393 w.ch.write_all(&z).map_err(io)?;
394 w.ch.sync_data().map_err(io)?;
395 let mut e = Vec::with_capacity(CH_ENTRY);
396 e.extend_from_slice(&self.pending[0].0.to_le_bytes());
397 e.extend_from_slice(&(self.pending.len() as u32).to_le_bytes());
398 e.extend_from_slice(&w.ch_offset.to_le_bytes());
399 e.extend_from_slice(&(z.len() as u32).to_le_bytes());
400 w.ch_idx.write_all(&e).map_err(io)?;
401 w.ch_idx.sync_data().map_err(io)?;
402 w.ch_offset += z.len() as u64;
403 self.pending.clear();
404 Ok(())
405 }
406
407 pub fn finish(mut self) -> Res<()> {
408 self.flush()
409 }
410}
411
412#[derive(Debug)]
413struct Segment {
414 start: u32,
416 tx_path: PathBuf,
417 tx: File,
418 dict: Option<Dict>,
419 frames: Vec<(u32, u64, u32)>,
421 ch: File,
422 delta: bool,
424 blocks: Vec<(u32, u32, u64, u32)>,
426}
427
428impl Segment {
429 fn last(&self) -> Option<u32> {
430 let t = self.frames.last().map(|f| f.0)?;
431 let c = self.blocks.last().map(|b| b.0 + b.1 - 1)?;
432 Some(t.min(c))
433 }
434
435 fn first(&self) -> Option<u32> {
436 self.frames.first().map(|f| f.0)
437 }
438}
439
440fn scan(dir: &Path) -> Res<Vec<Arc<Segment>>> {
441 scan_with(dir, &[])
442}
443
444fn scan_with(dir: &Path, known: &[Dict]) -> Res<Vec<Arc<Segment>>> {
446 let mut out = Vec::new();
447 let Ok(entries) = fs::read_dir(dir) else {
448 return Ok(out);
449 };
450 for e in entries {
451 let tx_path = e.map_err(io)?.path();
452 if tx_path.extension().is_none_or(|x| x != "xwlt") {
453 continue;
454 }
455 let name = tx_path
456 .file_name()
457 .map(|n| n.to_string_lossy().into_owned())
458 .unwrap_or_default();
459 let ch_path = dir.join(name.replace("txl-", "chg-").replace(".xwlt", ".xwlc"));
460 let mut tx = File::open(&tx_path).map_err(io)?;
461 let mut head = [0u8; 6 + 32];
462 tx.read_exact(&mut head).map_err(io)?;
463 if &head[..6] != TX_MAGIC {
464 return Err(format!("{}: not a transaction segment", tx_path.display()));
465 }
466 let dict_id: [u8; 32] = head[6..].try_into().map_err(|_| "header")?;
467 let dict = (dict_id != NO_DICT)
468 .then(|| match known.iter().find(|d| d.id == dict_id) {
469 Some(d) => Ok(d.clone()),
470 None => Dict::load(dir, &dict_id),
471 })
472 .transpose()?;
473 let idx = fs::read(tx_path.with_extension("xwlt.idx")).map_err(io)?;
474 if !idx.starts_with(TX_IDX_MAGIC) {
475 return Err(format!("{}: not a transaction index", tx_path.display()));
476 }
477 let frames: Vec<(u32, u64, u32)> = idx[6..]
478 .as_chunks::<TX_ENTRY>()
479 .0
480 .iter()
481 .map(|c| (le32(c, 0), le64(c, 4), le32(c, 12)))
482 .collect();
483 let mut ch = File::open(&ch_path).map_err(io)?;
484 let mut magic = [0u8; 6];
485 ch.read_exact(&mut magic).map_err(io)?;
486 let delta = match &magic {
487 m if m == CH_MAGIC => false,
488 m if m == CH_MAGIC_DELTA => true,
489 _ => return Err(format!("{}: not a changes segment", ch_path.display())),
490 };
491 let cidx = fs::read(ch_path.with_extension("xwlc.idx")).map_err(io)?;
492 if !cidx.starts_with(CH_IDX_MAGIC) {
493 return Err(format!("{}: not a changes index", ch_path.display()));
494 }
495 let blocks: Vec<(u32, u32, u64, u32)> = cidx[6..]
496 .as_chunks::<CH_ENTRY>()
497 .0
498 .iter()
499 .map(|c| (le32(c, 0), le32(c, 4), le64(c, 8), le32(c, 16)))
500 .collect();
501 let start = name
502 .strip_prefix("txl-")
503 .and_then(|r| r.strip_suffix(".xwlt"))
504 .and_then(|f| f.parse::<u32>().ok())
505 .ok_or(format!("{name}: segment name has no ledger sequence"))?;
506 let tx_len = tx.metadata().map_err(io)?.len();
507 let ch_len = ch.metadata().map_err(io)?.len();
508 check_index(&name, start, &frames, tx_len, &blocks, ch_len)?;
509 out.push(Arc::new(Segment {
510 start,
511 tx_path,
512 tx,
513 dict,
514 frames,
515 ch,
516 delta,
517 blocks,
518 }));
519 }
520 out.sort_by_key(|s| s.first().unwrap_or(u32::MAX));
521 Ok(out)
522}
523
524fn check_index(
529 name: &str,
530 start: u32,
531 frames: &[(u32, u64, u32)],
532 tx_len: u64,
533 blocks: &[(u32, u32, u64, u32)],
534 ch_len: u64,
535) -> Res<()> {
536 let bad = |what: String| Err(corrupt(format!("{name}: {what}")));
537 let mut end = (TX_MAGIC.len() + 32) as u64;
538 for (j, &(seq, off, len)) in frames.iter().enumerate() {
539 if u64::from(seq) != u64::from(start) + j as u64 {
540 return bad(format!(
541 "frame {j} is ledger {seq}, expected {}",
542 u64::from(start) + j as u64
543 ));
544 }
545 if len == 0 || off < end || off + u64::from(len) > tx_len {
546 return bad(format!(
547 "frame of ledger {seq} is outside the file or overlaps"
548 ));
549 }
550 end = off + u64::from(len);
551 }
552 let mut end = CH_MAGIC.len() as u64;
553 let mut next = u64::from(start);
554 for &(first, n, off, len) in blocks {
555 if u64::from(first) != next || n == 0 {
556 return bad(format!(
557 "change group from {first} for {n} is not consecutive"
558 ));
559 }
560 if len == 0 || off < end || off + u64::from(len) > ch_len {
561 return bad(format!(
562 "change group from {first} is outside the file or overlaps"
563 ));
564 }
565 end = off + u64::from(len);
566 next = u64::from(first) + u64::from(n);
567 }
568 Ok(())
569}
570
571type Cache = Mutex<VecDeque<((usize, u32), Arc<Vec<u8>>)>>;
572
573pub struct HistoryReader {
576 dir: PathBuf,
577 segments: RwLock<Arc<Vec<Arc<Segment>>>>,
578 tx_cache: Cache,
579 ch_cache: Cache,
580 prev: Option<Arc<PrevAt>>,
582 cold: RwLock<Arc<crate::cold::Cold>>,
583 cold_index: RwLock<crate::coldindex::Shared>,
584 cold_first: bool,
585 cold_checked: Mutex<Option<std::time::Instant>>,
587 cold_refreshing: Mutex<()>,
589}
590
591impl std::fmt::Debug for HistoryReader {
592 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
593 f.debug_struct("HistoryReader")
594 .field("dir", &self.dir)
595 .finish_non_exhaustive()
596 }
597}
598
599fn cached(
600 cache: &Cache,
601 key: (usize, u32),
602 cap: usize,
603 load: impl FnOnce() -> Res<Vec<u8>>,
604) -> Res<Arc<Vec<u8>>> {
605 if let Some((_, v)) = cache
606 .lock()
607 .unwrap_or_else(|p| p.into_inner())
608 .iter()
609 .find(|(k, _)| *k == key)
610 {
611 return Ok(v.clone());
612 }
613 let v = Arc::new(load()?);
614 let mut c = cache.lock().unwrap_or_else(|p| p.into_inner());
615 c.push_front((key, v.clone()));
616 c.truncate(cap);
617 Ok(v)
618}
619
620impl HistoryReader {
621 pub fn open(dir: &Path) -> Res<HistoryReader> {
622 HistoryReader::recover_swaps(dir)?;
623 let cold_index = crate::coldindex::ColdIndexes::open(dir)?;
625 Ok(HistoryReader {
626 dir: dir.to_path_buf(),
627 segments: RwLock::new(Arc::new(scan(dir)?)),
628 tx_cache: Mutex::new(VecDeque::new()),
629 ch_cache: Mutex::new(VecDeque::new()),
630 prev: None,
631 cold: RwLock::new(Arc::new(crate::cold::Cold::open(dir)?)),
632 cold_index: RwLock::new(Arc::new(cold_index)),
633 cold_first: false,
634 cold_checked: Mutex::new(Some(std::time::Instant::now())),
635 cold_refreshing: Mutex::new(()),
636 })
637 }
638
639 pub fn cold_index(&self) -> crate::coldindex::Shared {
642 self.cold_index
643 .read()
644 .unwrap_or_else(|p| p.into_inner())
645 .clone()
646 }
647
648 pub fn with_cold_cache(self, bytes: usize) -> Res<HistoryReader> {
651 let cold = crate::cold::Cold::open(&self.dir)?.with_cache_budget(bytes);
652 *self.cold.write().unwrap_or_else(|p| p.into_inner()) = Arc::new(cold);
653 Ok(self)
654 }
655
656 pub fn with_cold_first(mut self, on: bool) -> HistoryReader {
659 self.cold_first = on;
660 self
661 }
662
663 fn cold(&self) -> Arc<crate::cold::Cold> {
664 self.cold.read().unwrap_or_else(|p| p.into_inner()).clone()
665 }
666
667 pub fn cold_info(&self) -> Vec<(u32, u32, serde_json::Value)> {
669 self.cold()
670 .segments()
671 .iter()
672 .map(|s| (s.first, s.last, s.manifest.clone()))
673 .collect()
674 }
675
676 pub fn with_prev(mut self, prev: Arc<PrevAt>) -> HistoryReader {
679 self.prev = Some(prev);
680 self
681 }
682
683 pub fn segments_info(&self) -> Vec<(u32, u32, bool)> {
686 self.segments()
687 .iter()
688 .map(|s| {
689 (
690 s.start,
691 s.last().unwrap_or(s.start.saturating_sub(1)),
692 s.delta,
693 )
694 })
695 .collect()
696 }
697
698 fn segments(&self) -> Arc<Vec<Arc<Segment>>> {
699 self.segments
700 .read()
701 .unwrap_or_else(|p| p.into_inner())
702 .clone()
703 }
704
705 pub fn refresh(&self) -> Res<()> {
706 let known: Vec<Dict> = self
707 .segments()
708 .iter()
709 .filter_map(|s| s.dict.clone())
710 .collect();
711 let fresh = Arc::new(scan_with(&self.dir, &known)?);
712 *self.segments.write().unwrap_or_else(|p| p.into_inner()) = fresh;
713 self.refresh_cold()
714 }
715
716 pub fn refresh_cold_every(&self, every: std::time::Duration) -> Res<()> {
721 {
722 let mut t = self.cold_checked.lock().unwrap_or_else(|p| p.into_inner());
723 if t.is_some_and(|t| t.elapsed() < every) {
724 return Ok(());
725 }
726 *t = Some(std::time::Instant::now());
727 }
728 self.refresh_cold()
729 }
730
731 fn refresh_cold(&self) -> Res<()> {
732 let _busy = match self.cold_refreshing.try_lock() {
735 Ok(g) => g,
736 Err(std::sync::TryLockError::Poisoned(p)) => p.into_inner(),
737 Err(std::sync::TryLockError::WouldBlock) => return Ok(()),
738 };
739 let (mut names, mut parts) = (0, 0);
742 if let Ok(d) = fs::read_dir(&self.dir) {
743 for e in d.filter_map(|e| e.ok()) {
744 let n = e.file_name();
745 let n = n.to_string_lossy();
746 if n.ends_with(".json") {
747 if n.starts_with("cold-") {
748 names += 1;
749 } else if n.starts_with("coldidx-") {
750 parts += 1;
751 }
752 }
753 }
754 }
755 let ix = self.cold_index();
760 let fresh_ix = if parts != ix.parts() {
761 Some(crate::coldindex::ColdIndexes::open_with(&self.dir, &ix)?)
762 } else {
763 None
764 };
765 let cold = self.cold();
766 if fresh_ix.is_some() || names != cold.segments().len() {
767 *self.cold.write().unwrap_or_else(|p| p.into_inner()) =
768 Arc::new(crate::cold::Cold::open_with(&self.dir, &cold)?);
769 }
770 if let Some(fresh) = fresh_ix {
771 *self.cold_index.write().unwrap_or_else(|p| p.into_inner()) = Arc::new(fresh);
772 }
773 Ok(())
774 }
775
776 pub fn first(&self) -> Option<u32> {
777 let hot = self.segments().iter().filter_map(|s| s.first()).min();
778 [hot, self.cold().first()].into_iter().flatten().min()
779 }
780
781 pub fn last(&self) -> Option<u32> {
783 let hot = self.segments().iter().filter_map(|s| s.last()).max();
784 [hot, self.cold().last()].into_iter().flatten().max()
785 }
786
787 fn find(&self, seq: u32) -> Option<(usize, Arc<Segment>, usize)> {
790 let segs = self.segments();
791 for (i, s) in segs.iter().enumerate().rev() {
792 if s.last().is_none_or(|l| seq > l) || s.first().is_none_or(|f| seq < f) {
793 continue;
794 }
795 let k = s.frames.partition_point(|f| f.0 < seq);
796 if s.frames.get(k).is_some_and(|f| f.0 == seq) {
797 return Some((i, s.clone(), k));
798 }
799 }
800 None
801 }
802
803 fn find_or_refresh(&self, seq: u32) -> Res<Option<(usize, Arc<Segment>, usize)>> {
804 if let Some(f) = self.find(seq) {
805 return Ok(Some(f));
806 }
807 if self.last().is_none_or(|l| seq > l) {
808 self.refresh()?;
809 return Ok(self.find(seq));
810 }
811 Ok(None)
812 }
813
814 fn frame(&self, i: usize, s: &Segment, k: usize) -> Res<Arc<Vec<u8>>> {
815 let (seq, off, len) = s.frames[k];
816 cached(&self.tx_cache, (i, seq), TX_CACHE, || {
817 let mut z = vec![0u8; len as usize];
818 s.tx.read_exact_at(&mut z, off).map_err(io)?;
819 match &s.dict {
820 Some(d) => zstd::bulk::Decompressor::with_dictionary(&d.bytes)
821 .and_then(|mut x| x.decompress(&z, 256 << 20))
822 .map_err(io),
823 None => zstd::bulk::decompress(&z, MAX_DECODED).map_err(io),
824 }
825 })
826 }
827
828 fn changes(&self, i: usize, s: &Segment, seq: u32) -> Res<Vec<u8>> {
829 let k = s.blocks.partition_point(|b| b.0 + b.1 <= seq);
830 let &(first, n, off, len) = s
831 .blocks
832 .get(k)
833 .filter(|b| b.0 <= seq)
834 .ok_or("no changes for the ledger")?;
835 let raw = cached(&self.ch_cache, (i, first), CH_CACHE, || {
836 let mut z = vec![0u8; len as usize];
837 s.ch.read_exact_at(&mut z, off).map_err(io)?;
838 zstd::bulk::decompress(&z, MAX_DECODED).map_err(|e| corrupt(e.to_string()))
839 })?;
840 let count = rd32(&raw, 0)? as usize;
841 if count != n as usize {
842 return Err(corrupt("changes block does not match the index".into()));
843 }
844 let mut at = count
845 .checked_mul(8)
846 .and_then(|x| x.checked_add(4))
847 .filter(|x| *x <= raw.len())
848 .ok_or_else(|| {
849 corrupt("changes block table of contents is longer than the block".into())
850 })?;
851 for j in 0..count {
852 let (s2, l) = (rd32(&raw, 4 + j * 8)?, rd32(&raw, 8 + j * 8)? as usize);
853 if s2 != first + j as u32 {
854 return Err(corrupt(format!(
855 "in the block from {first} at position {j} found ledger {s2}"
856 )));
857 }
858 let end = at
859 .checked_add(l)
860 .filter(|e| *e <= raw.len())
861 .ok_or_else(|| corrupt("changes block truncated".into()))?;
862 if s2 == seq {
863 return Ok(raw[at..end].to_vec());
864 }
865 at = end;
866 }
867 Err(corrupt(format!(
868 "ledger {seq} missing from its changes block"
869 )))
870 }
871
872 fn txs_at(&self, i: usize, s: &Segment, k: usize, seq: u32) -> Res<Ledger> {
876 let l = assemble(&self.frame(i, s, k)?, None).map_err(corrupt)?;
877 let got = l.header().map_err(corrupt)?.sequence;
878 if got != seq {
879 return Err(corrupt(format!(
880 "the address of ledger {seq} holds a frame of ledger {got}"
881 )));
882 }
883 Ok(l)
884 }
885
886 pub fn cold_header(&self, seq: u32) -> Res<Option<Vec<u8>>> {
889 self.cold().header(seq)
890 }
891
892 pub fn cold_transactions(
897 &self,
898 wants: &[(u32, u32)],
899 ) -> Res<std::collections::HashMap<u32, Ledger>> {
900 let cold: Vec<(u32, u32)> = wants
901 .iter()
902 .copied()
903 .filter(|&(s, _)| self.cold_first || self.find(s).is_none())
904 .collect();
905 self.cold().transactions(&cold)
906 }
907
908 pub fn ledgers_txs(&self, seqs: &[u32]) -> Res<Vec<Option<Ledger>>> {
911 let cold: Vec<u32> = seqs
912 .iter()
913 .copied()
914 .filter(|&s| self.cold_first || self.find(s).is_none())
915 .collect();
916 let mut got = self.cold().ledgers(&cold)?;
917 seqs.iter()
918 .map(|&s| match got.remove(&s) {
919 Some(l) => Ok(Some(l)),
920 None => self.get_txs_known(s),
921 })
922 .collect()
923 }
924
925 pub fn get_txs(&self, seq: u32) -> Res<Option<Ledger>> {
927 if self.cold_first
928 && let Some(l) = self.cold().ledger(seq, false)?
929 {
930 return Ok(Some(l));
931 }
932 let Some((i, s, k)) = self.find_or_refresh(seq)? else {
933 return self.cold().ledger(seq, false);
934 };
935 Ok(Some(self.txs_at(i, &s, k, seq)?))
936 }
937
938 pub fn get_txs_known(&self, seq: u32) -> Res<Option<Ledger>> {
942 if self.cold_first
943 && let Some(l) = self.cold().ledger(seq, false)?
944 {
945 return Ok(Some(l));
946 }
947 let Some((i, s, k)) = self.find(seq) else {
948 return self.cold().ledger(seq, false);
949 };
950 Ok(Some(self.txs_at(i, &s, k, seq)?))
951 }
952
953 pub fn get(&self, seq: u32) -> Res<Option<Vec<u8>>> {
955 if self.cold_first
956 && let Some(l) = self.cold().ledger(seq, true)?
957 {
958 return Ok(Some(l.encode()));
959 }
960 let Some((i, s, k)) = self.find_or_refresh(seq)? else {
961 return Ok(self.cold().ledger(seq, true)?.map(|l| l.encode()));
962 };
963 let mut l = self.txs_at(i, &s, k, seq)?;
964 let ch = self.changes(i, &s, seq)?;
965 if !s.delta {
966 let frame = self.frame(i, &s, k)?;
967 return Ok(Some(assemble(&frame, Some(&ch)).map_err(corrupt)?.encode()));
968 }
969 let prev = self.prev.as_ref().ok_or(
970 "format 3 changes need the previous version of objects: reader has no state store",
971 )?;
972 let at = seq - 1;
973 l.changes = crate::delta::decode(&l, seq, &ch, &|k| prev(k, at))?;
974 Ok(Some(l.encode()))
975 }
976
977 pub fn convert_changes(&self, first: u32, group: u32, level: i32) -> Res<(u64, u64)> {
982 let segs = self.segments();
983 let s = segs
984 .iter()
985 .find(|s| s.start == first)
986 .ok_or(format!("no segment starting at {first}"))?;
987 if s.delta {
988 return Err(format!("segment {first} is already in format 3"));
989 }
990 let prev = self
991 .prev
992 .as_ref()
993 .ok_or("needs the previous version of objects")?;
994 let last = s.last().ok_or("segment is empty")?;
995 let ch_path = self.dir.join(format!("chg-{first:010}.xwlc"));
996 let (new_path, new_idx) = (
997 ch_path.with_extension("xwlc.new"),
998 ch_path.with_extension("xwlc.idx.new"),
999 );
1000 let _ = fs::remove_file(&new_path);
1001 let _ = fs::remove_file(&new_idx);
1002 let mut ch = create_new(&new_path, CH_MAGIC_DELTA)?;
1003 let mut idx = create_new(&new_idx, CH_IDX_MAGIC)?;
1004 let mut offset = CH_MAGIC.len() as u64;
1005 let mut pending: Vec<(u32, Vec<u8>)> = Vec::new();
1006 let mut write = |pending: &mut Vec<(u32, Vec<u8>)>| -> Res<()> {
1007 if pending.is_empty() {
1008 return Ok(());
1009 }
1010 let mut raw = (pending.len() as u32).to_le_bytes().to_vec();
1011 for (seq, p) in pending.iter() {
1012 raw.extend_from_slice(&seq.to_le_bytes());
1013 raw.extend_from_slice(&(p.len() as u32).to_le_bytes());
1014 }
1015 for (_, p) in pending.iter() {
1016 raw.extend_from_slice(p);
1017 }
1018 let z = zstd::bulk::compress(&raw, level).map_err(io)?;
1019 ch.write_all(&z).map_err(io)?;
1020 let mut e = Vec::with_capacity(CH_ENTRY);
1021 e.extend_from_slice(&pending[0].0.to_le_bytes());
1022 e.extend_from_slice(&(pending.len() as u32).to_le_bytes());
1023 e.extend_from_slice(&offset.to_le_bytes());
1024 e.extend_from_slice(&(z.len() as u32).to_le_bytes());
1025 idx.write_all(&e).map_err(io)?;
1026 offset += z.len() as u64;
1027 pending.clear();
1028 Ok(())
1029 };
1030 let mut originals = Vec::new();
1031 for seq in first..=last {
1032 let body = self.get(seq)?.ok_or(format!("ledger {seq} not found"))?;
1033 let l = Ledger::decode(&body)?;
1034 let at = seq - 1;
1035 let (record, _) = crate::delta::encode(&l, seq, &|k| prev(k, at))?;
1036 pending.push((seq, record));
1037 originals.push(witness_core::sha512_half(&body));
1038 if pending.len() as u32 >= group {
1039 write(&mut pending)?;
1040 }
1041 }
1042 write(&mut pending)?;
1043 ch.sync_all().map_err(io)?;
1044 idx.sync_all().map_err(io)?;
1045 drop((ch, idx));
1046 let check = HistoryReader {
1048 dir: self.dir.clone(),
1049 segments: RwLock::new(Arc::new(vec![Arc::new(Segment {
1050 start: s.start,
1051 tx_path: s.tx_path.clone(),
1052 tx: File::open(&s.tx_path).map_err(io)?,
1053 dict: s.dict.clone(),
1054 frames: s.frames.clone(),
1055 ch: File::open(&new_path).map_err(io)?,
1056 delta: true,
1057 blocks: {
1058 let raw = fs::read(&new_idx).map_err(io)?;
1059 raw[6..]
1060 .as_chunks::<CH_ENTRY>()
1061 .0
1062 .iter()
1063 .map(|c| (le32(c, 0), le32(c, 4), le64(c, 8), le32(c, 16)))
1064 .collect()
1065 },
1066 })])),
1067 tx_cache: Mutex::new(VecDeque::new()),
1068 ch_cache: Mutex::new(VecDeque::new()),
1069 prev: self.prev.clone(),
1070 cold: RwLock::new(Arc::new(crate::cold::Cold::default())),
1071 cold_index: RwLock::new(Arc::new(crate::coldindex::ColdIndexes::default())),
1072 cold_first: false,
1073 cold_checked: Mutex::new(None),
1074 cold_refreshing: Mutex::new(()),
1075 };
1076 for (i, seq) in (first..=last).enumerate() {
1077 let got = check
1078 .get(seq)?
1079 .ok_or(format!("ledger {seq} missing from the new segment"))?;
1080 if witness_core::sha512_half(&got) != originals[i] {
1081 return Err(format!("ledger {seq}: differs in format 3, swap cancelled"));
1082 }
1083 }
1084 let old = fs::metadata(&ch_path).map_or(0, |m| m.len());
1085 let new = fs::metadata(&new_path).map_or(0, |m| m.len());
1086 Ok((old, new))
1087 }
1088
1089 pub fn swap_changes(dir: &Path, first: u32) -> Res<()> {
1098 let ch_path = dir.join(format!("chg-{first:010}.xwlc"));
1099 let (data, idx) = (
1100 ch_path.with_extension("xwlc.new"),
1101 ch_path.with_extension("xwlc.idx.new"),
1102 );
1103 if !data.exists() || !idx.exists() {
1104 return Err(format!(
1105 "segment {first}: the new changes pair is incomplete, swap not started"
1106 ));
1107 }
1108 let mark = ch_path.with_extension("swap");
1109 File::create(&mark).and_then(|f| f.sync_all()).map_err(io)?;
1110 sync_dir(dir)?;
1111 finish_swap(dir, &ch_path)
1112 }
1113
1114 pub fn recover_swaps(dir: &Path) -> Res<usize> {
1116 let Ok(entries) = fs::read_dir(dir) else {
1117 return Ok(0);
1118 };
1119 let mut done = 0;
1120 for e in entries {
1121 let p = e.map_err(io)?.path();
1122 if p.extension().is_some_and(|x| x == "swap") {
1123 finish_swap(dir, &p.with_extension("xwlc"))?;
1124 done += 1;
1125 }
1126 }
1127 Ok(done)
1128 }
1129
1130 pub fn bytes_on_disk(&self) -> u64 {
1132 let len = |p: &Path| fs::metadata(p).map_or(0, |m| m.len());
1133 let mut total = 0;
1134 for s in self.segments().iter() {
1135 let ch = PathBuf::from(
1136 s.tx_path
1137 .to_string_lossy()
1138 .replace("txl-", "chg-")
1139 .replace(".xwlt", ".xwlc"),
1140 );
1141 total += len(&s.tx_path)
1142 + len(&s.tx_path.with_extension("xwlt.idx"))
1143 + len(&ch)
1144 + len(&ch.with_extension("xwlc.idx"));
1145 }
1146 if let Ok(d) = fs::read_dir(self.dir.join("dicts")) {
1147 total += d.flatten().map(|e| len(&e.path())).sum::<u64>();
1148 }
1149 total
1150 }
1151}
1152
1153#[cfg(test)]
1154mod tests {
1155 use super::*;
1156 use crate::ledger::{Change, StateChange};
1157
1158 fn ledger(seq: u32) -> Ledger {
1159 let mut header = vec![0u8; HEADER_LEN];
1160 header[..4].copy_from_slice(&seq.to_be_bytes());
1161 Ledger {
1162 header,
1163 transactions: (0..(seq % 5))
1164 .map(|i| (vec![i as u8; 30 + i as usize], vec![seq as u8; 50]))
1165 .collect(),
1166 changes: (0..(seq % 3))
1167 .map(|i| StateChange {
1168 key: [i as u8; 32],
1169 change: if i == 1 {
1170 Change::Deleted
1171 } else {
1172 Change::Modified
1173 },
1174 data: if i == 1 {
1175 Vec::new()
1176 } else {
1177 vec![seq as u8; 40]
1178 },
1179 })
1180 .collect(),
1181 }
1182 }
1183
1184 #[test]
1185 fn roundtrip_with_rotating_dictionaries() {
1186 let dir = tempfile::tempdir().unwrap();
1187 let samples: Vec<Vec<u8>> = (0..300).map(|s| tx_frame(&ledger(s))).collect();
1188 let d1 = Dict::store(
1189 dir.path(),
1190 zstd::dict::from_samples(&samples, 4096).unwrap(),
1191 )
1192 .unwrap();
1193 let mut w = HistoryWriter::create(dir.path(), 100, 8, 3, 19, Some(&d1), false).unwrap();
1195 for s in 100..130 {
1196 w.append(s, ledger(s).encode(), None).unwrap();
1197 }
1198 w.finish().unwrap();
1199 let d2 = Dict::store(
1201 dir.path(),
1202 zstd::dict::from_samples(&samples[..200], 2048).unwrap(),
1203 )
1204 .unwrap();
1205 assert_ne!(d1.id, d2.id);
1206 assert_eq!(Dict::current(dir.path()).unwrap().unwrap().id, d2.id);
1207 let mut w = HistoryWriter::create(dir.path(), 130, 8, 3, 19, Some(&d2), false).unwrap();
1208 for s in 130..140 {
1209 w.append(s, ledger(s).encode(), None).unwrap();
1210 }
1211 w.finish().unwrap();
1212
1213 let r = HistoryReader::open(dir.path()).unwrap();
1214 assert_eq!((r.first(), r.last()), (Some(100), Some(139)));
1215 for s in 100..140 {
1216 assert_eq!(r.get(s).unwrap().unwrap(), ledger(s).encode(), "ledger {s}");
1217 let t = r.get_txs(s).unwrap().unwrap();
1218 assert_eq!(
1219 (t.header, t.transactions),
1220 (ledger(s).header, ledger(s).transactions)
1221 );
1222 }
1223 assert!(r.get(140).unwrap().is_none());
1224 }
1225
1226 #[test]
1227 fn substituted_dictionary_is_detected() {
1228 let dir = tempfile::tempdir().unwrap();
1229 let samples: Vec<Vec<u8>> = (0..300).map(|s| tx_frame(&ledger(s))).collect();
1230 let d = Dict::store(
1231 dir.path(),
1232 zstd::dict::from_samples(&samples, 4096).unwrap(),
1233 )
1234 .unwrap();
1235 let mut w = HistoryWriter::create(dir.path(), 1, 4, 3, 19, Some(&d), false).unwrap();
1236 for s in 1..5 {
1237 w.append(s, ledger(s).encode(), None).unwrap();
1238 }
1239 w.finish().unwrap();
1240 let path = dict_path(dir.path(), &d.id);
1241 let mut bytes = fs::read(&path).unwrap();
1242 bytes[100] ^= 1;
1243 fs::write(&path, bytes).unwrap();
1244 let e = HistoryReader::open(dir.path()).unwrap_err();
1245 assert!(e.contains("does not match the hash"), "{e}");
1246 }
1247
1248 #[test]
1249 fn half_written_group_is_not_read() {
1250 let dir = tempfile::tempdir().unwrap();
1251 let mut w = HistoryWriter::create(dir.path(), 1, 4, 3, 19, None, false).unwrap();
1252 for s in 1..=4 {
1253 w.append(s, ledger(s).encode(), None).unwrap();
1254 }
1255 w.finish().unwrap();
1256 let tx_path = dir.path().join("txl-0000000001.xwlt");
1260 let mut tx = OpenOptions::new().append(true).open(&tx_path).unwrap();
1261 let mut idx = OpenOptions::new()
1262 .append(true)
1263 .open(dir.path().join("txl-0000000001.xwlt.idx"))
1264 .unwrap();
1265 for s in 5..=6u32 {
1266 let off = fs::metadata(&tx_path).unwrap().len();
1267 let z = zstd::bulk::compress(&tx_frame(&ledger(s)), 3).unwrap();
1268 tx.write_all(&z).unwrap();
1269 idx.write_all(&s.to_le_bytes()).unwrap();
1270 idx.write_all(&off.to_le_bytes()).unwrap();
1271 idx.write_all(&(z.len() as u32).to_le_bytes()).unwrap();
1272 }
1273 let r = HistoryReader::open(dir.path()).unwrap();
1274 assert_eq!(r.last(), Some(4));
1275 assert!(r.get(5).unwrap().is_none());
1276 let mut w = HistoryWriter::create(dir.path(), 5, 4, 3, 19, None, false).unwrap();
1278 w.append(5, ledger(5).encode(), None).unwrap();
1279 w.finish().unwrap();
1280 r.refresh().unwrap();
1281 assert_eq!(r.get(5).unwrap().unwrap(), ledger(5).encode());
1282 }
1283
1284 #[test]
1288 fn cold_published_later_is_picked_up_without_restart() {
1289 let dir = tempfile::tempdir().unwrap();
1290 let r = HistoryReader::open(dir.path()).unwrap();
1291 assert!(r.cold().first().is_none());
1292 crate::cold::write(
1293 dir.path(),
1294 &crate::cold::tests::chain(500, 4),
1295 crate::cold::Kinds::Explicit,
1296 )
1297 .unwrap();
1298 r.refresh_cold_every(std::time::Duration::from_secs(3600))
1300 .unwrap();
1301 assert!(r.cold().first().is_none());
1302 r.refresh_cold_every(std::time::Duration::ZERO).unwrap();
1303 assert_eq!((r.cold().first(), r.cold().last()), (Some(500), Some(503)));
1304 assert!(r.get_txs(502).unwrap().is_some());
1305 }
1306
1307 #[test]
1308 fn interrupted_first_group_does_not_block_restart() {
1309 let dir = tempfile::tempdir().unwrap();
1310 let mut w = HistoryWriter::create(dir.path(), 1, 4, 3, 19, None, false).unwrap();
1311 for s in 1..=4 {
1312 w.append(s, ledger(s).encode(), None).unwrap();
1313 }
1314 w.finish().unwrap();
1315 for f in ["chg-0000000001.xwlc", "chg-0000000001.xwlc.idx"] {
1316 let p = dir.path().join(f);
1317 let magic = if f.ends_with("idx") {
1318 CH_IDX_MAGIC
1319 } else {
1320 CH_MAGIC
1321 };
1322 fs::write(&p, magic).unwrap();
1323 }
1324 let r = HistoryReader::open(dir.path()).unwrap();
1325 assert_eq!(r.last(), None);
1326 let mut w = HistoryWriter::create(dir.path(), 1, 4, 3, 19, None, false).unwrap();
1327 for s in 1..=4 {
1328 w.append(s, ledger(s).encode(), None).unwrap();
1329 }
1330 w.finish().unwrap();
1331 r.refresh().unwrap();
1332 assert_eq!(r.last(), Some(4));
1333 assert_eq!(r.get(3).unwrap().unwrap(), ledger(3).encode());
1334 }
1335
1336 #[test]
1339 fn corrupt_history_is_an_error() {
1340 let make = || {
1341 let dir = tempfile::tempdir().unwrap();
1342 let mut w = HistoryWriter::create(dir.path(), 1, 4, 3, 19, None, false).unwrap();
1343 for s in 1..=4 {
1344 w.append(s, ledger(s).encode(), None).unwrap();
1345 }
1346 w.finish().unwrap();
1347 dir
1348 };
1349 let dir = make();
1351 let ch = dir.path().join("chg-0000000001.xwlc");
1352 let z = zstd::bulk::compress(&[7], 3).unwrap();
1353 let mut data = CH_MAGIC.to_vec();
1354 data.extend(&z);
1355 fs::write(&ch, &data).unwrap();
1356 let mut idx = CH_IDX_MAGIC.to_vec();
1357 idx.extend(1u32.to_le_bytes());
1358 idx.extend(4u32.to_le_bytes());
1359 idx.extend((CH_MAGIC.len() as u64).to_le_bytes());
1360 idx.extend((z.len() as u32).to_le_bytes());
1361 fs::write(ch.with_extension("xwlc.idx"), &idx).unwrap();
1362 let r = HistoryReader::open(dir.path()).unwrap();
1363 assert!(r.get(2).unwrap_err().starts_with("corrupt_history"));
1364
1365 let dir = make();
1367 let p = dir.path().join("txl-0000000001.xwlt.idx");
1368 let mut idx = fs::read(&p).unwrap();
1369 let third = idx[6 + 2 * TX_ENTRY + 4..6 + 3 * TX_ENTRY].to_vec();
1370 idx[6 + TX_ENTRY + 4..6 + 2 * TX_ENTRY].copy_from_slice(&third);
1371 fs::write(&p, &idx).unwrap();
1372 assert!(
1373 HistoryReader::open(dir.path())
1374 .unwrap_err()
1375 .starts_with("corrupt_history")
1376 );
1377
1378 let dir = make();
1380 let p = dir.path().join("txl-0000000001.xwlt");
1381 let len = fs::metadata(&p).unwrap().len();
1382 OpenOptions::new()
1383 .write(true)
1384 .open(&p)
1385 .unwrap()
1386 .set_len(len - 3)
1387 .unwrap();
1388 assert!(
1389 HistoryReader::open(dir.path())
1390 .unwrap_err()
1391 .starts_with("corrupt_history")
1392 );
1393 }
1394
1395 #[test]
1398 fn swap_is_all_or_nothing() {
1399 let dir = tempfile::tempdir().unwrap();
1400 let mut w = HistoryWriter::create(dir.path(), 1, 4, 3, 19, None, false).unwrap();
1401 for s in 1..=4 {
1402 w.append(s, ledger(s).encode(), None).unwrap();
1403 }
1404 w.finish().unwrap();
1405 let ch = dir.path().join("chg-0000000001.xwlc");
1406 fs::copy(&ch, ch.with_extension("xwlc.new")).unwrap();
1408 let before = fs::read(&ch).unwrap();
1410 assert!(HistoryReader::swap_changes(dir.path(), 1).is_err());
1411 assert_eq!(fs::read(&ch).unwrap(), before);
1412 assert!(!ch.with_extension("swap").exists());
1413 fs::copy(
1416 ch.with_extension("xwlc.idx"),
1417 ch.with_extension("xwlc.idx.new"),
1418 )
1419 .unwrap();
1420 fs::write(ch.with_extension("swap"), b"").unwrap();
1421 fs::rename(ch.with_extension("xwlc.new"), &ch).unwrap();
1422 let r = HistoryReader::open(dir.path()).unwrap();
1423 assert!(!ch.with_extension("swap").exists());
1424 assert!(!ch.with_extension("xwlc.idx.new").exists());
1425 for s in 1..=4 {
1426 assert_eq!(r.get(s).unwrap().unwrap(), ledger(s).encode());
1427 }
1428 }
1429
1430 fn object(seq: u32, tag: u8) -> Vec<u8> {
1432 let mut v = vec![0x11, 0, 0x61, 0x22, 0, 0, 0, 0, 0x24];
1433 v.extend(seq.to_be_bytes());
1434 v.push(0x51);
1435 v.extend([tag; 32]);
1436 v
1437 }
1438
1439 fn evolving(seq: u32) -> Ledger {
1441 let mut header = vec![0u8; HEADER_LEN];
1442 header[..4].copy_from_slice(&seq.to_be_bytes());
1443 Ledger {
1444 header,
1445 transactions: Vec::new(),
1446 changes: vec![
1447 StateChange {
1448 key: [1; 32],
1449 change: Change::Modified,
1450 data: object(seq, 1),
1451 },
1452 StateChange {
1453 key: [seq as u8; 32],
1454 change: Change::Created,
1455 data: object(seq, 2),
1456 },
1457 ],
1458 }
1459 }
1460
1461 fn prev_versions() -> Arc<PrevAt> {
1463 Arc::new(|k: &[u8; 32], at: u32| -> Res<Option<Vec<u8>>> {
1464 Ok((*k == [1; 32] && at >= 9).then(|| object(at, 1)))
1465 })
1466 }
1467
1468 #[test]
1469 fn delta_changes_roundtrip_and_conversion() {
1470 let dir = tempfile::tempdir().unwrap();
1471 let prev = prev_versions();
1472 let mut w = HistoryWriter::create(dir.path(), 10, 4, 3, 19, None, false).unwrap();
1474 for s in 10..20 {
1475 w.append(s, evolving(s).encode(), None).unwrap();
1476 }
1477 w.finish().unwrap();
1478 let mut w = HistoryWriter::create(dir.path(), 20, 4, 3, 19, None, true).unwrap();
1479 assert!(
1480 w.append(20, evolving(20).encode(), None).is_err(),
1481 "format 3 needs the previous version"
1482 );
1483 for s in 20..30 {
1484 w.append(s, evolving(s).encode(), Some(&*prev)).unwrap();
1485 }
1486 w.finish().unwrap();
1487
1488 let r = HistoryReader::open(dir.path()).unwrap();
1489 assert!(
1490 r.get(25).is_err(),
1491 "format 3 cannot be read without previous versions"
1492 );
1493 let r = r.with_prev(prev.clone());
1494 for s in 10..30 {
1495 assert_eq!(
1496 r.get(s).unwrap().unwrap(),
1497 evolving(s).encode(),
1498 "ledger {s}"
1499 );
1500 }
1501 assert_eq!(r.segments_info(), vec![(10, 19, false), (20, 29, true)]);
1502
1503 r.convert_changes(10, 4, 19).unwrap();
1505 HistoryReader::swap_changes(dir.path(), 10).unwrap();
1506 let r = HistoryReader::open(dir.path()).unwrap().with_prev(prev);
1507 assert_eq!(r.segments_info(), vec![(10, 19, true), (20, 29, true)]);
1508 for s in 10..30 {
1509 assert_eq!(
1510 r.get(s).unwrap().unwrap(),
1511 evolving(s).encode(),
1512 "after rebuild, ledger {s}"
1513 );
1514 }
1515 }
1516}