wal-backup 0.8.11

Embedded SQLite WAL replication to S3-compatible object storage. Not a sidecar — a library. Like Litestream, but embedded.
Documentation
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
//! Snapshot management for WAL replication.
//!
//! # Snapshot approach
//!
//! We take a snapshot by checkpointing the WAL (`PRAGMA wal_checkpoint(TRUNCATE)`) then
//! reading the database file directly, rather than using `VACUUM INTO`. This avoids:
//!
//! - `VACUUM INTO` failing with "output file already exists" on repeated calls
//! - File locking issues when opening a second connection while the main connection
//!   holds the WAL lock
//!
//! Trade-off: the snapshot includes free space from fragmented database pages (slightly
//! larger uploads). A future improvement could re-add `VACUUM INTO` with unique temp
//! paths if size is critical.
//!
//! # Concurrency note
//!
//! The snapshot opens a second SQLite connection to perform the checkpoint. If the main
//! connection is mid-transaction, `wal_checkpoint(TRUNCATE)` will block until the
//! transaction completes. This is acceptable because snapshots are infrequent and the
//! main connection's transactions are typically short-lived. If blocking becomes an
//! issue, consider using `wal_checkpoint(PASSIVE)` which is non-blocking but may not
//! checkpoint all frames.

use bytes::Bytes;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::sync::Notify;
use tokio::time::{sleep, Instant};
use tracing::{info, warn};

use crate::config::Config;
use crate::error::Result;
use crate::metrics::Metrics;
use crate::replication::manifest::{Manifest, MANIFEST_KEY};
use crate::storage::BucketStore;
use crate::wal::WalFile;

pub struct SnapshotManager {
    config: Config,
    bucket: Arc<dyn BucketStore>,
    manifest: Arc<Mutex<Manifest>>,
    last_snapshot_time: Arc<Mutex<Instant>>,
    trigger: Arc<Notify>,
    snapshot_version: Arc<AtomicU64>,
    force_next: Arc<AtomicBool>,
    metrics: Arc<dyn Metrics>,
    shutdown: Arc<Notify>,
    /// Reference to the main SQLite connection. Used for checkpointing
    /// the WAL before taking a snapshot. The main connection holds the
    /// WAL read lock, so checkpointing through it ensures all pages are
    /// moved from WAL to the main DB file.
    conn: Arc<Mutex<rusqlite::Connection>>,
}

impl SnapshotManager {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        config: Config,
        bucket: Arc<dyn BucketStore>,
        manifest: Arc<Mutex<Manifest>>,
        trigger: Arc<Notify>,
        snapshot_version: Arc<AtomicU64>,
        force_next: Arc<AtomicBool>,
        metrics: Arc<dyn Metrics>,
        conn: Arc<Mutex<rusqlite::Connection>>,
    ) -> Self {
        SnapshotManager {
            config,
            bucket,
            manifest,
            last_snapshot_time: Arc::new(Mutex::new(Instant::now())),
            trigger,
            snapshot_version,
            force_next,
            metrics,
            shutdown: Arc::new(Notify::new()),
            conn,
        }
    }

    pub fn trigger(&self) -> Arc<Notify> {
        self.trigger.clone()
    }

    pub fn force_next(&self) -> Arc<AtomicBool> {
        self.force_next.clone()
    }

    pub fn shutdown_notify(&self) -> Arc<Notify> {
        self.shutdown.clone()
    }

    pub fn bucket(&self) -> Arc<dyn BucketStore> {
        self.bucket.clone()
    }

    pub async fn run(&self) {
        loop {
            // Verify writer identity — catch if another process stole this prefix
            if let Err(e) = crate::connection::verify_writer_id(
                &self.bucket,
                self.bucket.prefix(),
                self.bucket.writer_id(),
            )
            .await
            {
                if e.is_wrong_writer() {
                    tracing::error!("WRITER IDENTITY LOST: {e} — stopping snapshot manager");
                    return;
                }
                warn!("Writer verification failed (will retry): {e}");
            }

            if let Err(e) = self.maybe_take_snapshot().await {
                warn!("Snapshot check failed: {e}");
            }
            tokio::select! {
                _ = sleep(self.config.snapshot_check_interval()) => {},
                _ = self.trigger.notified() => {},
                _ = self.shutdown.notified() => {
                    info!("SnapshotManager shutting down");
                    return;
                },
            }
        }
    }

    pub async fn maybe_take_snapshot(&self) -> Result<()> {
        let forced = self.force_next.swap(false, Ordering::Relaxed);

        if !forced {
            let wal_exists = match tokio::fs::try_exists(self.config.wal_path()).await {
                Ok(exists) => exists,
                Err(e) => {
                    warn!("Failed to check WAL existence for snapshot: {e}");
                    false
                }
            };
            if !wal_exists {
                return Ok(());
            }

            let wal_len = match tokio::fs::metadata(self.config.wal_path()).await {
                Ok(m) => m.len(),
                Err(e) => {
                    warn!("Failed to read WAL metadata for snapshot check: {e}");
                    return Ok(());
                }
            };

            let elapsed = self.last_snapshot_time.lock().await.elapsed();

            let should_snapshot = wal_len >= self.config.snapshot_threshold_bytes()
                || elapsed >= self.config.snapshot_interval();

            if !should_snapshot {
                return Ok(());
            }

            info!(
                "Taking snapshot: WAL size {wal_size}MB, elapsed {elapsed_sec}s",
                wal_size = wal_len / 1024 / 1024,
                elapsed_sec = elapsed.as_secs(),
            );
        } else {
            info!("Taking forced snapshot (salt-change trigger)");
        }

        self.take_snapshot().await?;

        Ok(())
    }

    pub async fn take_snapshot(&self) -> Result<()> {
        let snapshot_path = format!(
            "snapshots/{}.db",
            chrono::Utc::now().format("%Y%m%d-%H%M%S%.6f")
        );

        let db_path = self.config.db_path().clone();
        let temp_db_path = db_path
            .parent()
            .unwrap_or_else(|| std::path::Path::new("."))
            .join(".snapshot-temp.db");
        let temp_db_path_for_cleanup = temp_db_path.clone();

        let result = self
            .take_snapshot_inner(&snapshot_path, &db_path, &temp_db_path)
            .await;
        if result.is_err() {
            tokio::fs::remove_file(&temp_db_path_for_cleanup).await.ok();
        }
        result
    }

    async fn take_snapshot_inner(
        &self,
        snapshot_path: &str,
        db_path: &std::path::Path,
        temp_db_path: &std::path::Path,
    ) -> Result<()> {
        let db_path_owned = db_path.to_path_buf();
        let temp_db_path_owned = temp_db_path.to_path_buf();
        let snapshot_path_owned = snapshot_path.to_string();

        // Checkpoint through the main connection. This is critical because
        // the main connection holds the WAL read lock. A separate connection
        // can only do a partial checkpoint (moving unlocked pages), which
        // results in a snapshot that doesn't contain all data.
        //
        // We lock the connection in async context (no deadlock risk), then
        // pass the guard to spawn_blocking for the file copy.
        let main_size_after = {
            let guard = self.conn.lock().await;
            guard
                .execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")
                .map_err(|e| crate::error::Error::Snapshot(format!("checkpoint: {e}")))?;
            let db_path_clone = db_path_owned.clone();
            let main_size_after = tokio::task::spawn_blocking(move || {
                std::fs::metadata(&db_path_clone)
                    .map(|m| m.len())
                    .unwrap_or(0)
            })
            .await
            .unwrap_or(0);
            drop(guard);
            main_size_after
        };
        tracing::debug!(
            "snapshot: main db size after checkpoint={}",
            main_size_after
        );

        // Now copy the fully-checkpointed main db to temp file for upload.
        tokio::fs::copy(&db_path_owned, &temp_db_path_owned).await?;

        let (page_size, db_size) = {
            let temp_path = temp_db_path_owned.clone();
            tokio::task::spawn_blocking(move || {
                let conn = rusqlite::Connection::open(&temp_path)?;
                conn.execute_batch("PRAGMA journal_mode = WAL")?;
                conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?;
                drop(conn);
                let mut header = [0u8; 20];
                let mut file = std::fs::File::open(&temp_path)?;
                std::io::Read::read_exact(&mut file, &mut header)?;
                let ps = crate::restore::read_page_size_from_db(&header)?;
                let size = std::fs::metadata(&temp_path)?.len();
                Ok::<_, crate::error::Error>((ps, size))
            })
            .await??
        };

        // Compute checksum from the temp file. We read the file into memory
        // to avoid TOCTOU races with concurrent writes to the same path.
        let checksum = {
            let temp_path = temp_db_path_owned.clone();
            tokio::task::spawn_blocking(move || {
                let bytes = std::fs::read(&temp_path)?;
                Ok::<_, std::io::Error>(crate::util::compute_sha256(&bytes))
            })
            .await?
            .map_err(|e| crate::error::Error::Snapshot(format!("checksum failed: {e}")))?
        };

        self.bucket
            .put_file(&snapshot_path_owned, &temp_db_path_owned)
            .await?;

        tokio::fs::remove_file(&temp_db_path_owned).await.ok();

        let wal_len = tokio::fs::metadata(self.config.wal_path())
            .await
            .map(|m| m.len())
            .unwrap_or(0);
        self.metrics.snapshot_taken(db_size, wal_len);

        let wal = {
            let wal_path = self.config.wal_path().clone();
            tokio::task::spawn_blocking(move || WalFile::open(&wal_path).ok())
                .await
                .unwrap_or(None)
        };
        let wal = wal.unwrap_or_else(|| {
            warn!("WAL file not found or unreadable during snapshot, using synthetic header");
            let header = crate::wal::WalHeader::synthetic(page_size, 0, 0);
            crate::wal::WalFile::with_synthetic_header(header, page_size)
        });

        let mut manifest = self.manifest.lock().await;

        let old_salt_prefix = if manifest.current_salt_1 != 0 || manifest.current_salt_2 != 0 {
            if manifest.current_salt_1 != wal.header().salt_1
                || manifest.current_salt_2 != wal.header().salt_2
            {
                Some(manifest.segment_prefix())
            } else {
                None
            }
        } else {
            None
        };

        manifest.update_snapshot(
            snapshot_path.to_string(),
            checksum.clone(),
            wal.header().salt_1,
            wal.header().salt_2,
            page_size,
            db_size,
        );

        let manifest_bytes = manifest.serialize()?;
        let etag = manifest.etag.clone();
        if let Err(e) = async {
            if let Some(ref etag) = etag {
                self.bucket
                    .put_if_match(MANIFEST_KEY, Bytes::from(manifest_bytes), etag)
                    .await
            } else {
                self.bucket
                    .put(MANIFEST_KEY, Bytes::from(manifest_bytes))
                    .await
            }
        }
        .await
        {
            if matches!(e, crate::error::Error::PreconditionFailed { .. }) {
                warn!("Manifest precondition failed during snapshot — another writer updated it. Re-reading and retrying.");
                // Re-read remote manifest and update with our snapshot
                if let Ok(Some((remote_data, remote_etag))) =
                    self.bucket.get_with_etag(MANIFEST_KEY).await
                {
                    if let Ok(mut remote) = Manifest::deserialize(&remote_data) {
                        // Merge: take snapshot metadata from us, but preserve
                        // replication state (shipped_frames, l1_files, etc.)
                        // from remote in case the shipper advanced concurrently.
                        remote.snapshot = Some(snapshot_path.to_string());
                        remote.snapshot_checksum = Some(checksum.clone());
                        remote.current_salt_1 = wal.header().salt_1;
                        remote.current_salt_2 = wal.header().salt_2;
                        remote.page_size = page_size;
                        remote.db_size = db_size;
                        // Preserve remote replication state — do NOT reset
                        // shipped_frames or clear l1_files. The shipper may
                        // have shipped frames or compacted segments while we
                        // were creating the snapshot.
                        remote.etag = Some(remote_etag);
                        let updated_bytes = remote.serialize()?;
                        if let Err(e2) = self
                            .bucket
                            .put_if_match(
                                MANIFEST_KEY,
                                Bytes::from(updated_bytes),
                                remote.etag.as_deref().unwrap_or(""),
                            )
                            .await
                        {
                            warn!("Retry manifest write also failed: {e2}. Snapshot {snapshot_path} is uploaded but manifest not updated.");
                            return Err(e2);
                        }
                        info!("Successfully updated manifest on retry after precondition failure.");
                    } else {
                        return Err(e);
                    }
                } else {
                    return Err(e);
                }
            } else {
                return Err(e);
            }
        }

        drop(manifest);

        if let Some(old_prefix) = old_salt_prefix {
            match self.bucket.list(&old_prefix).await {
                Ok(keys) => {
                    for key in keys {
                        if key.ends_with(".segment") || key.ends_with(".l1") {
                            if let Err(e) = self.bucket.delete(&key).await {
                                warn!("Failed to delete old segment {}: {e}", key);
                            } else {
                                self.metrics.segment_deleted(&key);
                                info!("Deleted old salt segment: {key}");
                            }
                        }
                    }
                }
                Err(e) => {
                    warn!("Failed to list old salt segments for cleanup: {e}");
                }
            }
        }

        *self.last_snapshot_time.lock().await = Instant::now();

        self.snapshot_version.fetch_add(1, Ordering::Release);

        info!("Snapshot complete: {} ({} bytes)", snapshot_path, db_size);

        Ok(())
    }
}