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