Diffinery

homeflare/celldpublic

celld/crates/ltx/src/compactor.rs
225 lines · 7.0 KBRaw History
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
6use crate::codec::{Decoder, Encoder};
7use crate::error::{Error, Result};
8use crate::ltx::{Header, PageHeader, Trailer, VERSION};
9use crate::TXID;
10use std::io::{Read, Write};
11use std::sync::atomic::{AtomicU32, Ordering};
12
13/// The current progress of a compaction.
14#[derive(Debug, Clone, Copy, PartialEq)]
15pub 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
22impl 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.
37pub 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
49impl<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 self.compact_inner(None)
97 }
98
99 /// A drained source can include transactions already in the destination.
100 /// Repeating its pages is safe, but repeating its transaction range would
101 /// break destination continuity. Validate every source key before changing
102 /// the output range; a rebased checksum cannot be inferred from the input.
103 pub(crate) fn compact_from(&mut self, min: TXID, ranges: &[(TXID, TXID)]) -> Result<()> {
104 self.compact_inner(Some((min, ranges)))
105 }
106
107 fn compact_inner(&mut self, range: Option<(TXID, &[(TXID, TXID)])>) -> Result<()> {
108 if self.inputs.is_empty() {
109 return Err(Error::LTXCorrupted);
110 }
111
112 for input in &mut self.inputs {
113 input.decoder.decode_header()?;
114 }
115
116 if let Some((min, ranges)) = range {
117 let first = self.inputs[0].decoder.header;
118 if ranges.len() != self.inputs.len()
119 || min < first.min_txid
120 || min > first.max_txid
121 || (min != first.min_txid
122 && self.header_flags & crate::ltx::HEADER_FLAG_NO_CHECKSUM == 0)
123 || self.inputs.iter().zip(ranges).any(|(input, expected)| {
124 let header = input.decoder.header;
125 (header.min_txid, header.max_txid) != *expected
126 })
127 {
128 return Err(Error::LTXCorrupted);
129 }
130 }
131
132 for index in 1..self.inputs.len() {
133 let previous = self.inputs[index - 1].decoder.header;
134 let current = self.inputs[index].decoder.header;
135 if previous.page_size != current.page_size {
136 return Err(Error::LTXCorrupted);
137 }
138 if !self.allow_non_contiguous_txids
139 && !is_contiguous(previous.max_txid, current.min_txid, current.max_txid)
140 {
141 return Err(Error::LTXCorrupted);
142 }
143 }
144
145 let first = self.inputs[0].decoder.header;
146 let last = self.inputs[self.inputs.len() - 1].decoder.header;
147 self.encoder.encode_header(Header {
148 version: VERSION,
149 flags: self.header_flags,
150 page_size: first.page_size,
151 commit: last.commit,
152 min_txid: range.map_or(first.min_txid, |(min, _)| min),
153 max_txid: last.max_txid,
154 timestamp: last.timestamp,
155 pre_apply_checksum: first.pre_apply_checksum,
156 ..Header::default()
157 })?;
158 self.total.store(last.commit, Ordering::Relaxed);
159
160 for input in &mut self.inputs {
161 input.data.resize(first.page_size as usize, 0);
162 }
163
164 loop {
165 let Some(page_number) = self.fill_page_buffers()? else {
166 break;
167 };
168 self.write_page_buffer(page_number)?;
169 self.page_number.store(page_number, Ordering::Relaxed);
170 }
171
172 for input in &mut self.inputs {
173 input.decoder.close()?;
174 }
175
176 let post_apply_checksum = self.inputs[self.inputs.len() - 1]
177 .decoder
178 .trailer
179 .post_apply_checksum;
180 self.encoder.close(post_apply_checksum)
181 }
182
183 fn fill_page_buffers(&mut self) -> Result<Option<u32>> {
184 let mut minimum = None;
185 for input in &mut self.inputs {
186 if input.page.is_none() {
187 input.page = input.decoder.decode_page(&mut input.data)?;
188 }
189 if let Some(page) = input.page {
190 minimum = Some(minimum.map_or(page.pgno, |value: u32| value.min(page.pgno)));
191 }
192 }
193 Ok(minimum)
194 }
195
196 fn write_page_buffer(&mut self, page_number: u32) -> Result<()> {
197 let commit = self.encoder.header.commit;
198 let mut written = false;
199 for input in self.inputs.iter_mut().rev() {
200 let Some(page) = input.page else {
201 continue;
202 };
203 if page.pgno != page_number {
204 continue;
205 }
206 input.page = None;
207 if written || page_number > commit {
208 continue;
209 }
210 written = true;
211 self.encoder.encode_page(page, &input.data)?;
212 }
213 Ok(())
214 }
215}
216
217fn is_contiguous(previous_max: TXID, min: TXID, max: TXID) -> bool {
218 min.0 <= previous_max.0.wrapping_add(1) && max > previous_max
219}
220
221struct CompactorInput<R> {
222 decoder: Decoder<R>,
223 page: Option<PageHeader>,
224 data: Vec<u8>,
225}