Diffinery

homeflare/celldpublic

celld/crates/ltx/src/compaction_level.rs
199 lines · 6.3 KBRaw History
1//! Litestream-compatible LTX compaction-level definitions.
2
3use crate::error::{Error, Result};
4use std::time::{Duration, SystemTime, UNIX_EPOCH};
5
6/// The level that contains complete database snapshots.
7pub const SNAPSHOT_LEVEL: i32 = 9;
8
9/// One non-snapshot compaction level.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub struct CompactionLevel {
12 /// The numeric level, which must match its position in the level list.
13 pub level: i32,
14 /// The interval for compaction from the preceding level.
15 pub interval: Duration,
16}
17
18impl CompactionLevel {
19 /// Returns the start of the current interval in UTC time.
20 pub fn previous_compaction_at(self, now: SystemTime) -> SystemTime {
21 if self.interval.is_zero() {
22 return now;
23 }
24 let elapsed = now.duration_since(UNIX_EPOCH).unwrap_or_default();
25 let interval = self.interval.as_nanos();
26 let truncated = elapsed.as_nanos() - elapsed.as_nanos() % interval;
27 UNIX_EPOCH + Duration::from_nanos(truncated.min(u128::from(u64::MAX)) as u64)
28 }
29
30 /// Returns the start of the next interval in UTC time.
31 pub fn next_compaction_at(self, now: SystemTime) -> SystemTime {
32 self.previous_compaction_at(now) + self.interval
33 }
34}
35
36/// The canonical Litestream v0.5.16 non-snapshot levels.
37pub const DEFAULT_COMPACTION_LEVELS: [CompactionLevel; 4] = [
38 CompactionLevel {
39 level: 0,
40 interval: Duration::ZERO,
41 },
42 CompactionLevel {
43 level: 1,
44 interval: Duration::from_secs(30),
45 },
46 CompactionLevel {
47 level: 2,
48 interval: Duration::from_secs(5 * 60),
49 },
50 CompactionLevel {
51 level: 3,
52 interval: Duration::from_secs(60 * 60),
53 },
54];
55
56/// A validated ordered collection of non-snapshot levels.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct CompactionLevels(Vec<CompactionLevel>);
59
60impl CompactionLevels {
61 /// Creates and validates an ordered level collection.
62 pub fn new(levels: Vec<CompactionLevel>) -> Result<Self> {
63 let levels = Self(levels);
64 levels.validate()?;
65 Ok(levels)
66 }
67
68 /// Returns the canonical Litestream v0.5.16 levels.
69 pub fn defaults() -> Self {
70 Self(DEFAULT_COMPACTION_LEVELS.to_vec())
71 }
72
73 /// Returns the ordered level slice.
74 pub fn as_slice(&self) -> &[CompactionLevel] {
75 &self.0
76 }
77
78 /// Returns a non-snapshot level by its numeric index.
79 pub fn level(&self, level: i32) -> Result<CompactionLevel> {
80 if level == SNAPSHOT_LEVEL {
81 return Err(invalid("the snapshot level is not a compaction level"));
82 }
83 self.0
84 .get(usize::try_from(level).map_err(|_| invalid("level is out of bounds"))?)
85 .copied()
86 .ok_or_else(|| invalid("level is out of bounds"))
87 }
88
89 /// Returns the highest non-snapshot level.
90 pub fn max_level(&self) -> i32 {
91 self.0.len() as i32 - 1
92 }
93
94 /// Returns whether a level exists or is the snapshot level.
95 pub fn is_valid_level(&self, level: i32) -> bool {
96 level == SNAPSHOT_LEVEL || (0..=self.max_level()).contains(&level)
97 }
98
99 /// Returns the preceding level, including the level before a snapshot.
100 pub fn previous_level(&self, level: i32) -> Option<i32> {
101 if level == SNAPSHOT_LEVEL {
102 Some(self.max_level())
103 } else {
104 level.checked_sub(1).filter(|level| *level >= 0)
105 }
106 }
107
108 /// Returns the following level, including the snapshot transition.
109 pub fn next_level(&self, level: i32) -> Option<i32> {
110 if level == SNAPSHOT_LEVEL {
111 None
112 } else if level == self.max_level() {
113 Some(SNAPSHOT_LEVEL)
114 } else {
115 level
116 .checked_add(1)
117 .filter(|level| self.is_valid_level(*level))
118 }
119 }
120
121 fn validate(&self) -> Result<()> {
122 if self.0.is_empty() {
123 return Err(invalid("at least one compaction level is required"));
124 }
125 for (index, level) in self.0.iter().enumerate() {
126 if level.level != index as i32 {
127 return Err(invalid("compaction levels are out of order"));
128 }
129 if level.level >= SNAPSHOT_LEVEL {
130 return Err(invalid("a compaction level exceeds the maximum"));
131 }
132 if (level.level == 0) != level.interval.is_zero() {
133 return Err(invalid("a compaction interval is invalid"));
134 }
135 }
136 Ok(())
137 }
138}
139
140fn invalid(message: &'static str) -> Error {
141 Error::Other(message.into())
142}
143
144#[cfg(test)]
145mod tests {
146 use super::*;
147
148 #[test]
149 fn defaults_match_litestream_v0_5_16() {
150 let levels = CompactionLevels::defaults();
151 assert_eq!(levels.max_level(), 3);
152 assert_eq!(levels.level(1).unwrap().interval, Duration::from_secs(30));
153 assert_eq!(levels.level(2).unwrap().interval, Duration::from_secs(300));
154 assert_eq!(levels.level(3).unwrap().interval, Duration::from_secs(3600));
155 assert_eq!(levels.previous_level(SNAPSHOT_LEVEL), Some(3));
156 assert_eq!(levels.next_level(3), Some(SNAPSHOT_LEVEL));
157 assert_eq!(levels.next_level(SNAPSHOT_LEVEL), None);
158 }
159
160 #[test]
161 fn validation_rejects_missing_reordered_and_invalid_intervals() {
162 assert!(CompactionLevels::new(Vec::new()).is_err());
163 assert!(CompactionLevels::new(vec![CompactionLevel {
164 level: 1,
165 interval: Duration::ZERO,
166 }])
167 .is_err());
168 assert!(CompactionLevels::new(vec![CompactionLevel {
169 level: 0,
170 interval: Duration::from_secs(1),
171 }])
172 .is_err());
173 assert!(CompactionLevels::new(vec![
174 CompactionLevel {
175 level: 0,
176 interval: Duration::ZERO,
177 },
178 CompactionLevel {
179 level: 1,
180 interval: Duration::ZERO,
181 },
182 ])
183 .is_err());
184 }
185
186 #[test]
187 fn interval_boundaries_match_litestream() {
188 let level = DEFAULT_COMPACTION_LEVELS[1];
189 let now = UNIX_EPOCH + Duration::from_secs(95);
190 assert_eq!(
191 level.previous_compaction_at(now),
192 UNIX_EPOCH + Duration::from_secs(90)
193 );
194 assert_eq!(
195 level.next_compaction_at(now),
196 UNIX_EPOCH + Duration::from_secs(120)
197 );
198 }
199}