| 1 | //! A streaming port of `superfly/ltx` v0.5.2 `Compactor`. |
| 2 | //! |
| 3 | //! The compactor keeps one decompressed page per input. It does not build a |
| 4 | //! database-sized page map. Inputs must be ordered by transaction range. |
| 5 | |
| 6 | use crate::codec::{Decoder, Encoder}; |
| 7 | use crate::error::{Error, Result}; |
| 8 | use crate::ltx::{Header, PageHeader, Trailer, VERSION}; |
| 9 | use crate::TXID; |
| 10 | use std::io::{Read, Write}; |
| 11 | use std::sync::atomic::{AtomicU32, Ordering}; |
| 12 | |
| 13 | /// The current progress of a compaction. |
| 14 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 15 | pub struct CompactorStatus { |
| 16 | /// The last page number processed by the merge. |
| 17 | pub page_number: u32, |
| 18 | /// The final input's commit page count. |
| 19 | pub total: u32, |
| 20 | } |
| 21 | |
| 22 | impl CompactorStatus { |
| 23 | pub fn is_zero(self) -> bool { |
| 24 | self.page_number == 0 && self.total == 0 |
| 25 | } |
| 26 | |
| 27 | pub fn fraction(self) -> f64 { |
| 28 | if self.total == 0 { |
| 29 | 0.0 |
| 30 | } else { |
| 31 | f64::from(self.page_number) / f64::from(self.total) |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | /// Merges ordered LTX inputs into one byte-compatible LTX output. |
| 37 | pub struct Compactor<W, R> { |
| 38 | encoder: Encoder<W>, |
| 39 | inputs: Vec<CompactorInput<R>>, |
| 40 | page_number: AtomicU32, |
| 41 | total: AtomicU32, |
| 42 | |
| 43 | /// Flags to set on the compacted LTX header. |
| 44 | pub header_flags: u32, |
| 45 | /// Allows gaps in the ordered input transaction ranges. |
| 46 | pub allow_non_contiguous_txids: bool, |
| 47 | } |
| 48 | |
| 49 | impl<W: Write, R: Read> Compactor<W, R> { |
| 50 | pub fn new(writer: W, readers: Vec<R>) -> Self { |
| 51 | Self { |
| 52 | encoder: Encoder::new_block(writer), |
| 53 | inputs: readers |
| 54 | .into_iter() |
| 55 | .map(|reader| CompactorInput { |
| 56 | decoder: Decoder::new(reader), |
| 57 | page: None, |
| 58 | data: Vec::new(), |
| 59 | }) |
| 60 | .collect(), |
| 61 | page_number: AtomicU32::new(0), |
| 62 | total: AtomicU32::new(0), |
| 63 | header_flags: 0, |
| 64 | allow_non_contiguous_txids: false, |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | pub fn header(&self) -> Header { |
| 69 | self.encoder.header |
| 70 | } |
| 71 | |
| 72 | pub fn trailer(&self) -> Trailer { |
| 73 | self.encoder.trailer |
| 74 | } |
| 75 | |
| 76 | pub fn status(&self) -> CompactorStatus { |
| 77 | CompactorStatus { |
| 78 | page_number: self.page_number.load(Ordering::Relaxed), |
| 79 | total: self.total.load(Ordering::Relaxed), |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | pub fn writer(&self) -> &W { |
| 84 | &self.encoder.writer |
| 85 | } |
| 86 | |
| 87 | pub fn writer_mut(&mut self) -> &mut W { |
| 88 | &mut self.encoder.writer |
| 89 | } |
| 90 | |
| 91 | pub fn into_writer(self) -> W { |
| 92 | self.encoder.writer |
| 93 | } |
| 94 | |
| 95 | pub fn compact(&mut self) -> Result<()> { |
| 96 | if self.inputs.is_empty() { |
| 97 | return Err(Error::LTXCorrupted); |
| 98 | } |
| 99 | |
| 100 | for input in &mut self.inputs { |
| 101 | input.decoder.decode_header()?; |
| 102 | } |
| 103 | |
| 104 | for index in 1..self.inputs.len() { |
| 105 | let previous = self.inputs[index - 1].decoder.header; |
| 106 | let current = self.inputs[index].decoder.header; |
| 107 | if previous.page_size != current.page_size { |
| 108 | return Err(Error::LTXCorrupted); |
| 109 | } |
| 110 | if !self.allow_non_contiguous_txids |
| 111 | && !is_contiguous(previous.max_txid, current.min_txid, current.max_txid) |
| 112 | { |
| 113 | return Err(Error::LTXCorrupted); |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | let first = self.inputs[0].decoder.header; |
| 118 | let last = self.inputs[self.inputs.len() - 1].decoder.header; |
| 119 | self.encoder.encode_header(Header { |
| 120 | version: VERSION, |
| 121 | flags: self.header_flags, |
| 122 | page_size: first.page_size, |
| 123 | commit: last.commit, |
| 124 | min_txid: first.min_txid, |
| 125 | max_txid: last.max_txid, |
| 126 | timestamp: last.timestamp, |
| 127 | pre_apply_checksum: first.pre_apply_checksum, |
| 128 | ..Header::default() |
| 129 | })?; |
| 130 | self.total.store(last.commit, Ordering::Relaxed); |
| 131 | |
| 132 | for input in &mut self.inputs { |
| 133 | input.data.resize(first.page_size as usize, 0); |
| 134 | } |
| 135 | |
| 136 | loop { |
| 137 | let Some(page_number) = self.fill_page_buffers()? else { |
| 138 | break; |
| 139 | }; |
| 140 | self.write_page_buffer(page_number)?; |
| 141 | self.page_number.store(page_number, Ordering::Relaxed); |
| 142 | } |
| 143 | |
| 144 | for input in &mut self.inputs { |
| 145 | input.decoder.close()?; |
| 146 | } |
| 147 | |
| 148 | let post_apply_checksum = self.inputs[self.inputs.len() - 1] |
| 149 | .decoder |
| 150 | .trailer |
| 151 | .post_apply_checksum; |
| 152 | self.encoder.close(post_apply_checksum) |
| 153 | } |
| 154 | |
| 155 | fn fill_page_buffers(&mut self) -> Result<Option<u32>> { |
| 156 | let mut minimum = None; |
| 157 | for input in &mut self.inputs { |
| 158 | if input.page.is_none() { |
| 159 | input.page = input.decoder.decode_page(&mut input.data)?; |
| 160 | } |
| 161 | if let Some(page) = input.page { |
| 162 | minimum = Some(minimum.map_or(page.pgno, |value: u32| value.min(page.pgno))); |
| 163 | } |
| 164 | } |
| 165 | Ok(minimum) |
| 166 | } |
| 167 | |
| 168 | fn write_page_buffer(&mut self, page_number: u32) -> Result<()> { |
| 169 | let commit = self.encoder.header.commit; |
| 170 | let mut written = false; |
| 171 | for input in self.inputs.iter_mut().rev() { |
| 172 | let Some(page) = input.page else { |
| 173 | continue; |
| 174 | }; |
| 175 | if page.pgno != page_number { |
| 176 | continue; |
| 177 | } |
| 178 | input.page = None; |
| 179 | if written || page_number > commit { |
| 180 | continue; |
| 181 | } |
| 182 | written = true; |
| 183 | self.encoder.encode_page(page, &input.data)?; |
| 184 | } |
| 185 | Ok(()) |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | fn is_contiguous(previous_max: TXID, min: TXID, max: TXID) -> bool { |
| 190 | min.0 <= previous_max.0.wrapping_add(1) && max > previous_max |
| 191 | } |
| 192 | |
| 193 | struct CompactorInput<R> { |
| 194 | decoder: Decoder<R>, |
| 195 | page: Option<PageHeader>, |
| 196 | data: Vec<u8>, |
| 197 | } |
| 198 | |
| 199 | #[cfg(test)] |
| 200 | // Unit tests inspect materialized file-format fixtures outside production. |
| 201 | #[allow(clippy::disallowed_methods)] |
| 202 | mod tests { |
| 203 | use super::*; |
| 204 | use crate::ltx::{ |
| 205 | checksum_page, decode_file, decode_file_pages, encode_file_v0_5_2, HEADER_FLAG_NO_CHECKSUM, |
| 206 | }; |
| 207 | use crate::CHECKSUM_FLAG; |
| 208 | use std::io::Cursor; |
| 209 | |
| 210 | fn header( |
| 211 | page_size: u32, |
| 212 | commit: u32, |
| 213 | min_txid: u64, |
| 214 | max_txid: u64, |
| 215 | timestamp: i64, |
| 216 | pre_apply_checksum: u64, |
| 217 | ) -> Header { |
| 218 | Header { |
| 219 | version: VERSION, |
| 220 | page_size, |
| 221 | commit, |
| 222 | min_txid: TXID(min_txid), |
| 223 | max_txid: TXID(max_txid), |
| 224 | timestamp, |
| 225 | pre_apply_checksum, |
| 226 | ..Header::default() |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | fn input(header: Header, pages: &[(u32, u8)], post_apply_checksum: u64) -> Vec<u8> { |
| 231 | let pages = pages |
| 232 | .iter() |
| 233 | .map(|&(page_number, byte)| (page_number, vec![byte; header.page_size as usize])) |
| 234 | .collect::<Vec<_>>(); |
| 235 | encode_file_v0_5_2(&header, &pages, post_apply_checksum).expect("encode input") |
| 236 | } |
| 237 | |
| 238 | fn snapshot_checksum(page_size: usize, pages: &[(u32, u8)]) -> u64 { |
| 239 | pages.iter().fold(CHECKSUM_FLAG, |rolling, &(pgno, byte)| { |
| 240 | CHECKSUM_FLAG | (rolling ^ checksum_page(pgno, &vec![byte; page_size])) |
| 241 | }) |
| 242 | } |
| 243 | |
| 244 | fn compact(inputs: Vec<Vec<u8>>) -> Result<Vec<u8>> { |
| 245 | let readers = inputs.into_iter().map(Cursor::new).collect(); |
| 246 | let mut compactor = Compactor::new(Vec::new(), readers); |
| 247 | compactor.compact()?; |
| 248 | Ok(compactor.into_writer()) |
| 249 | } |
| 250 | |
| 251 | #[test] |
| 252 | fn single_file_is_an_exact_copy() { |
| 253 | let source = input( |
| 254 | header(512, 1, 1, 1, 1000, 0), |
| 255 | &[(1, b'1')], |
| 256 | 0xeb1a999231044ddd, |
| 257 | ); |
| 258 | assert_eq!(compact(vec![source.clone()]).unwrap(), source); |
| 259 | } |
| 260 | |
| 261 | #[test] |
| 262 | fn newest_page_wins_and_output_header_spans_inputs() { |
| 263 | let checksum1 = 0x8a249272ad9f7dea; |
| 264 | let first = input( |
| 265 | header(1024, 3, 1, 1, 1000, 0), |
| 266 | &[(1, 0x81), (2, 0x82), (3, 0x83)], |
| 267 | checksum1, |
| 268 | ); |
| 269 | let second = input( |
| 270 | header(1024, 3, 2, 2, 2000, checksum1), |
| 271 | &[(1, 0x91), (3, 0x93)], |
| 272 | checksum1, |
| 273 | ); |
| 274 | |
| 275 | let output = compact(vec![first, second]).unwrap(); |
| 276 | let expected = hex::decode(concat!( |
| 277 | "4c54583100000000000004000000000300000000000000010000000000000002", |
| 278 | "00000000000007d0000000000000000000000000000000000000000000000000", |
| 279 | "0000000000000000000000000000000000000000000000000000000000000000", |
| 280 | "000000000000000100010000001a1f910100ffffffdc000200000200b0919191", |
| 281 | "91919191919191910000000200010000001a1f820100ffffffdc000200000200", |
| 282 | "b082828282828282828282820000000300010000001a1f930100ffffffdc0002", |
| 283 | "00000200b093939393939393939393930000000000000164240288012403ac01", |
| 284 | "2400000000000000000c8a249272ad9f7dea91206f60138b3298", |
| 285 | )) |
| 286 | .expect("fixture hex"); |
| 287 | assert_eq!(output, expected, "complete output must match Go v0.5.2"); |
| 288 | let decoded = decode_file(&output).unwrap(); |
| 289 | assert_eq!(decoded.header.min_txid, TXID(1)); |
| 290 | assert_eq!(decoded.header.max_txid, TXID(2)); |
| 291 | assert_eq!(decoded.header.timestamp, 2000); |
| 292 | assert_eq!( |
| 293 | decode_file_pages(&output).unwrap(), |
| 294 | vec![ |
| 295 | (1, vec![0x91; 1024]), |
| 296 | (2, vec![0x82; 1024]), |
| 297 | (3, vec![0x93; 1024]), |
| 298 | ] |
| 299 | ); |
| 300 | } |
| 301 | |
| 302 | #[test] |
| 303 | fn pages_beyond_the_final_commit_are_dropped() { |
| 304 | let first = input( |
| 305 | header(1024, 3, 2, 3, 1000, CHECKSUM_FLAG | 2), |
| 306 | &[(3, 0x83)], |
| 307 | CHECKSUM_FLAG | 3, |
| 308 | ); |
| 309 | let second = input( |
| 310 | header(1024, 2, 4, 5, 2000, CHECKSUM_FLAG | 4), |
| 311 | &[(1, 0x91)], |
| 312 | CHECKSUM_FLAG | 5, |
| 313 | ); |
| 314 | |
| 315 | let output = compact(vec![first, second]).unwrap(); |
| 316 | assert_eq!(decode_file(&output).unwrap().header.commit, 2); |
| 317 | assert_eq!( |
| 318 | decode_file_pages(&output).unwrap(), |
| 319 | vec![(1, vec![0x91; 1024])] |
| 320 | ); |
| 321 | } |
| 322 | |
| 323 | #[test] |
| 324 | fn rejects_missing_mismatched_and_non_contiguous_inputs() { |
| 325 | let mut empty = Compactor::<Vec<u8>, Cursor<Vec<u8>>>::new(Vec::new(), Vec::new()); |
| 326 | assert!(empty.compact().is_err()); |
| 327 | |
| 328 | let mut missing_header = Compactor::new(Vec::new(), vec![Cursor::new(Vec::new())]); |
| 329 | assert!(missing_header.compact().is_err()); |
| 330 | |
| 331 | let a = input( |
| 332 | header(512, 1, 1, 1, 1000, 0), |
| 333 | &[(1, 0x81)], |
| 334 | CHECKSUM_FLAG | 1, |
| 335 | ); |
| 336 | let b = input( |
| 337 | header(1024, 1, 2, 2, 1000, CHECKSUM_FLAG | 1), |
| 338 | &[(1, 0x91)], |
| 339 | CHECKSUM_FLAG | 2, |
| 340 | ); |
| 341 | assert!(compact(vec![a, b]).is_err()); |
| 342 | |
| 343 | let a = input( |
| 344 | header(1024, 1, 1, 2, 1000, 0), |
| 345 | &[(1, 0x81)], |
| 346 | snapshot_checksum(1024, &[(1, 0x81)]), |
| 347 | ); |
| 348 | let b = input( |
| 349 | header(1024, 1, 4, 4, 1000, CHECKSUM_FLAG | 2), |
| 350 | &[(1, 0x91)], |
| 351 | CHECKSUM_FLAG | 1, |
| 352 | ); |
| 353 | let readers = vec![Cursor::new(a), Cursor::new(b)]; |
| 354 | let mut strict = Compactor::new(Vec::new(), readers); |
| 355 | assert!(strict.compact().is_err()); |
| 356 | } |
| 357 | |
| 358 | #[test] |
| 359 | fn rejects_an_input_with_an_invalid_trailer() { |
| 360 | let mut source = input( |
| 361 | header(512, 1, 1, 1, 1000, 0), |
| 362 | &[(1, b'1')], |
| 363 | 0xeb1a999231044ddd, |
| 364 | ); |
| 365 | source.pop(); |
| 366 | |
| 367 | let mut compactor = Compactor::new(Vec::new(), vec![Cursor::new(source)]); |
| 368 | assert!(compactor.compact().is_err()); |
| 369 | } |
| 370 | |
| 371 | #[test] |
| 372 | fn can_allow_non_contiguous_inputs() { |
| 373 | let a = input( |
| 374 | header(1024, 1, 1, 2, 1000, 0), |
| 375 | &[(1, 0x81)], |
| 376 | snapshot_checksum(1024, &[(1, 0x81)]), |
| 377 | ); |
| 378 | let b = input( |
| 379 | header(1024, 1, 4, 4, 1000, CHECKSUM_FLAG | 2), |
| 380 | &[(1, 0x91)], |
| 381 | CHECKSUM_FLAG | 1, |
| 382 | ); |
| 383 | let readers = vec![Cursor::new(a), Cursor::new(b)]; |
| 384 | let mut compactor = Compactor::new(Vec::new(), readers); |
| 385 | compactor.allow_non_contiguous_txids = true; |
| 386 | compactor.compact().unwrap(); |
| 387 | } |
| 388 | |
| 389 | #[test] |
| 390 | fn reports_progress() { |
| 391 | let source = input( |
| 392 | header(1024, 3, 1, 1, 1000, 0), |
| 393 | &[(1, 0x81), (2, 0x82), (3, 0x83)], |
| 394 | 0x8a249272ad9f7dea, |
| 395 | ); |
| 396 | let mut compactor = Compactor::new(Vec::new(), vec![Cursor::new(source)]); |
| 397 | assert!(compactor.status().is_zero()); |
| 398 | assert_eq!(compactor.status().fraction(), 0.0); |
| 399 | compactor.compact().unwrap(); |
| 400 | assert_eq!( |
| 401 | compactor.status(), |
| 402 | CompactorStatus { |
| 403 | page_number: 3, |
| 404 | total: 3, |
| 405 | } |
| 406 | ); |
| 407 | assert_eq!(compactor.status().fraction(), 1.0); |
| 408 | } |
| 409 | |
| 410 | #[test] |
| 411 | fn compacts_legacy_frame_inputs() { |
| 412 | let fixture_dir = format!( |
| 413 | "{}/tests/fixtures/golden/replica/ltx/0", |
| 414 | env!("CARGO_MANIFEST_DIR") |
| 415 | ); |
| 416 | let inputs = (1..=6) |
| 417 | .map(|txid| { |
| 418 | std::fs::read(format!("{fixture_dir}/{txid:016x}-{txid:016x}.ltx")) |
| 419 | .expect("read legacy fixture") |
| 420 | }) |
| 421 | .collect::<Vec<_>>(); |
| 422 | |
| 423 | // Litestream v0.5.11 wrote the pre-v0.5.2 frame representation. |
| 424 | let first_page_flags = u16::from_be_bytes([inputs[0][104], inputs[0][105]]); |
| 425 | assert_eq!(first_page_flags, 0); |
| 426 | |
| 427 | let readers = inputs.into_iter().map(Cursor::new).collect(); |
| 428 | let mut compactor = Compactor::new(Vec::new(), readers); |
| 429 | compactor.header_flags = HEADER_FLAG_NO_CHECKSUM; |
| 430 | compactor.compact().expect("compact legacy inputs"); |
| 431 | let output = compactor.into_writer(); |
| 432 | let decoded = decode_file(&output).expect("verify v0.5.2 output"); |
| 433 | assert_eq!(decoded.header.min_txid, TXID(1)); |
| 434 | assert_eq!(decoded.header.max_txid, TXID(6)); |
| 435 | assert!(!decoded.pgnos.is_empty()); |
| 436 | } |
| 437 | } |