Skip to main content

wal_backup/
config.rs

1//! Configuration for the WAL replication layer.
2
3use std::path::PathBuf;
4use std::time::Duration;
5
6/// Controls when WAL frames are shipped to object storage.
7///
8/// - `SyncMode::Immediate`: Ship every WAL frame as soon as it is written.
9///   Best for providers with unmetered requests (OVH, Hetzner, etc.).
10/// - `SyncMode::Lazy`: Ship WAL frames on a periodic interval.
11///   Best for providers with per-request billing (AWS S3, GCS).
12#[non_exhaustive]
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
14pub enum SyncMode {
15    /// Ship WAL frames immediately on write. Zero latency, higher request frequency.
16    /// Use with providers that do not bill per request (OVH, Hetzner Box, etc.).
17    #[default]
18    Immediate,
19    /// Ship WAL frames on a configurable interval. Batched uploads, lower request count.
20    /// Use with providers that bill per request (AWS S3, GCS, etc.).
21    Lazy,
22}
23
24/// Controls what happens when a local DB is newer than the bucket manifest.
25#[non_exhaustive]
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum RestoreBehavior {
28    /// If the local DB is newer, upload it as the new snapshot.
29    UploadLocalIfNewer,
30    /// Always restore from the bucket, overwriting local data.
31    AlwaysRestoreFromBucket,
32    /// Return an error if local is newer than bucket.
33    ErrorIfConflict,
34    /// Restore from snapshot, logging but not failing on checksum mismatch
35    /// (e.g., due to bitrot or partial upload). Use with caution.
36    Recoverable,
37}
38
39/// Configuration for a [`DurabilityLayer`][crate::DurabilityLayer].
40#[derive(Clone)]
41pub struct Config {
42    /// Path to the SQLite database file.
43    pub(crate) db_path: PathBuf,
44    /// Path to the WAL file (usually `<db>-wal`).
45    pub(crate) wal_path: PathBuf,
46    /// How often to poll the WAL for new frames in Lazy sync mode.
47    /// In Immediate sync mode: max fallback wait time before re-checking WAL.
48    pub(crate) poll_interval: Duration,
49    /// WAL size threshold that triggers a snapshot.
50    pub(crate) snapshot_threshold_bytes: u64,
51    /// Minimum time between snapshots.
52    pub(crate) snapshot_interval: Duration,
53    /// Interval for checking WAL size to decide whether to trigger snapshot.
54    /// This controls how responsive the snapshot size check is.
55    pub(crate) snapshot_check_interval: Duration,
56    /// Behavior when local DB is newer than bucket manifest.
57    pub(crate) restore_behavior: RestoreBehavior,
58    /// Maximum frames to ship in a single segment.
59    pub(crate) max_frames_per_segment: u32,
60    /// When to ship WAL frames to object storage.
61    pub(crate) sync_mode: SyncMode,
62    /// Interval for file-change detection in Immediate sync mode.
63    /// Always clamped to 10–500ms regardless of set value.
64    pub(crate) immediate_poll_interval: Duration,
65    /// Maximum time since last sync before is_healthy() returns false.
66    pub(crate) health_timeout: Duration,
67    /// Maximum time to wait for sync_now() to complete.
68    pub(crate) sync_timeout: Duration,
69    /// Timeout for waiting for a snapshot to complete after WAL salt change or truncation.
70    /// If the snapshot doesn't complete within this time, the shipper retries.
71    /// Clamped to 1s–5min.
72    pub(crate) salt_change_timeout: Duration,
73    /// Interval between garbage collection runs.
74    /// GC deletes orphaned WAL segments no longer referenced by the manifest.
75    /// Set to None to disable GC. Default: disabled.
76    pub(crate) gc_interval: Option<Duration>,
77    /// Maximum WAL file size in bytes before backpressure is applied.
78    /// When the WAL exceeds this size, shipping pauses and a snapshot is forced.
79    /// This prevents unbounded WAL growth when shipping is slow or stalled.
80    /// Set to 0 to disable (WAL can grow without limit). Default: 50MB.
81    pub(crate) max_wal_size_bytes: u64,
82    /// Interval between compaction runs. Compaction merges multiple L0
83    /// segments into fewer L1 files for efficient restore.
84    /// Set to None to disable compaction. Default: disabled.
85    pub(crate) compaction_interval: Option<Duration>,
86    /// Minimum number of L0 segments required to trigger compaction.
87    /// Compaction only runs when at least this many L0 segments exist
88    /// under the current salt prefix. Default: 10.
89    pub(crate) compaction_min_segments: u32,
90    /// Whether to acquire a bucket replica lock (lock.json) on open.
91    /// Set to false for testing with shared buckets. Default: true.
92    pub(crate) replica_lock_enabled: bool,
93}
94
95impl Config {
96    /// Create a new Config for the database at `db_path`.
97    ///
98    /// The WAL path is automatically derived as `{db_path}-wal`.
99    /// Use builder methods to customize additional settings.
100    pub fn new(db_path: impl Into<PathBuf>) -> Self {
101        let db_path = db_path.into();
102        let wal_path = PathBuf::from(format!("{}-wal", db_path.display()));
103        Self {
104            db_path,
105            wal_path,
106            poll_interval: Duration::from_millis(100),
107            snapshot_threshold_bytes: 50 * 1024 * 1024,
108            snapshot_interval: Duration::from_secs(3600),
109            snapshot_check_interval: Duration::from_secs(10),
110            restore_behavior: RestoreBehavior::UploadLocalIfNewer,
111            max_frames_per_segment: 1000,
112            sync_mode: SyncMode::default(),
113            immediate_poll_interval: Duration::from_millis(50),
114            health_timeout: Duration::from_secs(30),
115            sync_timeout: Duration::from_secs(10),
116            salt_change_timeout: Duration::from_secs(60),
117            gc_interval: None,
118            max_wal_size_bytes: 50 * 1024 * 1024, // 50MB default
119            compaction_interval: None,
120            compaction_min_segments: 10,
121            replica_lock_enabled: true,
122        }
123    }
124
125    pub fn with_poll_interval(mut self, interval: Duration) -> Self {
126        self.poll_interval = interval;
127        self
128    }
129
130    pub fn with_snapshot_threshold(mut self, bytes: u64) -> Self {
131        self.snapshot_threshold_bytes = bytes;
132        self
133    }
134
135    pub fn with_snapshot_interval(mut self, interval: Duration) -> Self {
136        self.snapshot_interval = interval;
137        self
138    }
139
140    pub fn with_snapshot_check_interval(mut self, interval: Duration) -> Self {
141        self.snapshot_check_interval = interval;
142        self
143    }
144
145    pub fn with_restore_behavior(mut self, behavior: RestoreBehavior) -> Self {
146        self.restore_behavior = behavior;
147        self
148    }
149
150    pub fn with_max_frames_per_segment(mut self, max: u32) -> Self {
151        self.max_frames_per_segment = max;
152        self
153    }
154
155    pub fn with_sync_mode(mut self, mode: SyncMode) -> Self {
156        self.sync_mode = mode;
157        self
158    }
159
160    pub fn with_immediate_poll_interval(mut self, interval: Duration) -> Self {
161        self.immediate_poll_interval =
162            interval.clamp(Duration::from_millis(10), Duration::from_millis(500));
163        self
164    }
165
166    pub fn db_path(&self) -> &PathBuf {
167        &self.db_path
168    }
169    pub fn wal_path(&self) -> &PathBuf {
170        &self.wal_path
171    }
172    pub fn poll_interval(&self) -> Duration {
173        self.poll_interval
174    }
175    pub fn snapshot_threshold_bytes(&self) -> u64 {
176        self.snapshot_threshold_bytes
177    }
178    pub fn snapshot_interval(&self) -> Duration {
179        self.snapshot_interval
180    }
181    pub fn snapshot_check_interval(&self) -> Duration {
182        self.snapshot_check_interval
183    }
184    pub fn restore_behavior(&self) -> &RestoreBehavior {
185        &self.restore_behavior
186    }
187    pub fn max_frames_per_segment(&self) -> u32 {
188        self.max_frames_per_segment
189    }
190    pub fn sync_mode(&self) -> &SyncMode {
191        &self.sync_mode
192    }
193    pub fn immediate_poll_interval(&self) -> Duration {
194        self.immediate_poll_interval
195    }
196    pub fn health_timeout(&self) -> Duration {
197        self.health_timeout
198    }
199    pub fn sync_timeout(&self) -> Duration {
200        self.sync_timeout
201    }
202    pub fn salt_change_timeout(&self) -> Duration {
203        self.salt_change_timeout
204    }
205    pub fn gc_interval(&self) -> Option<Duration> {
206        self.gc_interval
207    }
208    pub fn max_wal_size_bytes(&self) -> u64 {
209        self.max_wal_size_bytes
210    }
211    pub fn compaction_interval(&self) -> Option<Duration> {
212        self.compaction_interval
213    }
214    pub fn compaction_min_segments(&self) -> u32 {
215        self.compaction_min_segments
216    }
217
218    /// Create a Config with all fields specified. For testing use.
219    ///
220    /// **Warning:** This bypasses builder validation. Production code should
221    /// use `Config::new()` with builder methods instead.
222    #[allow(clippy::too_many_arguments)]
223    /// For testing: set invalid sync_timeout.
224    #[allow(dead_code)]
225    pub fn with_invalid_sync_timeout(self, sync_timeout: Duration) -> Self {
226        Self {
227            sync_timeout,
228            ..self
229        }
230    }
231
232    /// For testing: set invalid health_timeout.
233    #[allow(dead_code)]
234    pub fn with_invalid_health_timeout(self, health_timeout: Duration) -> Self {
235        Self {
236            health_timeout,
237            ..self
238        }
239    }
240
241    /// For testing: set invalid snapshot_threshold_bytes.
242    #[allow(dead_code)]
243    pub fn with_invalid_snapshot_threshold(self, bytes: u64) -> Self {
244        Self {
245            snapshot_threshold_bytes: bytes,
246            ..self
247        }
248    }
249
250    /// For testing: set invalid snapshot_interval.
251    #[allow(dead_code)]
252    pub fn with_invalid_snapshot_interval(self, interval: Duration) -> Self {
253        Self {
254            snapshot_interval: interval,
255            ..self
256        }
257    }
258
259    /// For testing: set invalid poll_interval.
260    #[allow(dead_code)]
261    pub fn with_invalid_poll_interval(self, interval: Duration) -> Self {
262        Self {
263            poll_interval: interval,
264            ..self
265        }
266    }
267
268    /// For testing: set invalid max_frames_per_segment.
269    #[allow(dead_code)]
270    pub fn with_invalid_max_frames(self, max: u32) -> Self {
271        Self {
272            max_frames_per_segment: max,
273            ..self
274        }
275    }
276
277    /// For testing: set invalid salt_change_timeout.
278    #[allow(dead_code)]
279    pub fn with_invalid_salt_change_timeout(self, timeout: Duration) -> Self {
280        Self {
281            salt_change_timeout: timeout,
282            ..self
283        }
284    }
285
286    /// For testing: set invalid snapshot_check_interval.
287    #[allow(dead_code)]
288    pub fn with_invalid_snapshot_check_interval(self, interval: Duration) -> Self {
289        Self {
290            snapshot_check_interval: interval,
291            ..self
292        }
293    }
294
295    /// For testing: set invalid immediate_poll_interval (no clamping).
296    #[allow(dead_code)]
297    pub fn with_invalid_immediate_poll_interval(self, interval: Duration) -> Self {
298        Self {
299            immediate_poll_interval: interval,
300            ..self
301        }
302    }
303
304    pub fn with_health_timeout(mut self, timeout: Duration) -> Self {
305        self.health_timeout = timeout;
306        self
307    }
308
309    pub fn with_sync_timeout(mut self, timeout: Duration) -> Self {
310        self.sync_timeout = timeout;
311        self
312    }
313
314    pub fn with_salt_change_timeout(mut self, timeout: Duration) -> Self {
315        // Clamp to 1s–5min for safety
316        self.salt_change_timeout = timeout.clamp(Duration::from_secs(1), Duration::from_secs(300));
317        self
318    }
319
320    pub fn with_gc_interval(mut self, interval: Option<Duration>) -> Self {
321        self.gc_interval = interval;
322        self
323    }
324
325    pub fn with_max_wal_size_bytes(mut self, bytes: u64) -> Self {
326        self.max_wal_size_bytes = bytes;
327        self
328    }
329
330    /// Set the compaction interval. Compaction merges multiple L0 segments
331    /// into fewer L1 files for efficient restore. Set to None to disable.
332    pub fn with_compaction_interval(mut self, interval: Option<Duration>) -> Self {
333        self.compaction_interval = interval;
334        self
335    }
336
337    /// Set the minimum number of L0 segments required to trigger compaction.
338    pub fn with_compaction_min_segments(mut self, min: u32) -> Self {
339        self.compaction_min_segments = min;
340        self
341    }
342
343    /// Disable the bucket replica lock (lock.json).
344    /// Useful for testing with shared buckets where multiple
345    /// DurabilityLayer instances share the same prefix.
346    /// Default: true (lock enabled).
347    pub fn with_replica_lock_enabled(mut self, enabled: bool) -> Self {
348        self.replica_lock_enabled = enabled;
349        self
350    }
351
352    pub fn replica_lock_enabled(&self) -> bool {
353        self.replica_lock_enabled
354    }
355
356    pub fn validate(&self) -> crate::error::Result<()> {
357        if self.db_path.as_os_str().is_empty() {
358            return Err(crate::error::Error::Config(
359                "db_path must not be empty".into(),
360            ));
361        }
362        if self.snapshot_threshold_bytes == 0 {
363            return Err(crate::error::Error::Config(
364                "snapshot_threshold_bytes must be > 0".into(),
365            ));
366        }
367        if self.snapshot_interval.is_zero()
368            || self.snapshot_interval > Duration::from_secs(86400 * 365)
369        {
370            return Err(crate::error::Error::Config(
371                "snapshot_interval must be > 0 and <= 365 days".into(),
372            ));
373        }
374        if self.snapshot_check_interval.is_zero() {
375            return Err(crate::error::Error::Config(
376                "snapshot_check_interval must be > 0".into(),
377            ));
378        }
379        if self.max_frames_per_segment == 0 {
380            return Err(crate::error::Error::Config(
381                "max_frames_per_segment must be > 0".into(),
382            ));
383        }
384        if self.poll_interval.is_zero() {
385            return Err(crate::error::Error::Config(
386                "poll_interval must be > 0".into(),
387            ));
388        }
389        if self.health_timeout.is_zero() {
390            return Err(crate::error::Error::Config(
391                "health_timeout must be > 0".into(),
392            ));
393        }
394        if self.sync_timeout.is_zero() {
395            return Err(crate::error::Error::Config(
396                "sync_timeout must be > 0".into(),
397            ));
398        }
399        if self.salt_change_timeout.is_zero() || self.salt_change_timeout > Duration::from_secs(300)
400        {
401            return Err(crate::error::Error::Config(
402                "salt_change_timeout must be > 0 and <= 5 minutes".into(),
403            ));
404        }
405        let min_poll = Duration::from_millis(10);
406        let max_poll = Duration::from_millis(500);
407        if self.immediate_poll_interval < min_poll || self.immediate_poll_interval > max_poll {
408            return Err(crate::error::Error::Config(format!(
409                "immediate_poll_interval must be between {:?} and {:?}",
410                min_poll, max_poll
411            )));
412        }
413        Ok(())
414    }
415}