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
407
408
409
410
411
//! wal-backup CLI — Restore, verify, and inspect SQLite WAL backups on S3.
//!
//! Environment variables (WAL_BACKUP_* or AWS_* forms):
//!   WAL_BACKUP_ENDPOINT / AWS_ENDPOINT_URL     S3 endpoint URL
//!   WAL_BACKUP_REGION  / AWS_REGION            S3 region (default: us-east-1)
//!   WAL_BACKUP_BUCKET  / E2E_BUCKET_NAME       S3 bucket name
//!   WAL_BACKUP_ACCESS_KEY / AWS_ACCESS_KEY_ID  Access key
//!   WAL_BACKUP_SECRET_KEY / AWS_SECRET_ACCESS_KEY  Secret key
//!   WAL_BACKUP_PREFIX                            Object prefix (default: "")

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use clap::{Parser, Subcommand};
use wal_backup::{
    build_s3_store, BucketStore, Config, DurabilityLayer, ObjectStoreBucket, RestoreBehavior,
};

#[derive(Parser)]
#[command(name = "wal-backup")]
#[command(about = "Embedded SQLite WAL replication to S3-compatible object storage")]
#[command(version)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

/// Common S3 connection options
#[derive(clap::Args, Clone)]
struct S3Opts {
    /// S3 endpoint URL
    #[arg(long, env = "WAL_BACKUP_ENDPOINT")]
    endpoint: Option<String>,

    /// S3 region
    #[arg(long, env = "WAL_BACKUP_REGION", default_value = "")]
    region: String,

    /// S3 bucket name
    #[arg(long, env = "WAL_BACKUP_BUCKET")]
    bucket: Option<String>,

    /// Object prefix within the bucket
    #[arg(long, env = "WAL_BACKUP_PREFIX", default_value = "")]
    prefix: String,

    /// S3 access key ID
    #[arg(long, env = "WAL_BACKUP_ACCESS_KEY")]
    access_key: Option<String>,

    /// S3 secret access key
    #[arg(long, env = "WAL_BACKUP_SECRET_KEY")]
    secret_key: Option<String>,
}

impl S3Opts {
    fn resolve(&self) -> ResolvedOpts {
        ResolvedOpts {
            endpoint: self
                .endpoint
                .clone()
                .or_else(|| std::env::var("AWS_ENDPOINT_URL").ok())
                .expect("Missing --endpoint or WAL_BACKUP_ENDPOINT or AWS_ENDPOINT_URL"),
            region: if self.region.is_empty() {
                std::env::var("AWS_REGION").unwrap_or_else(|_| "us-east-1".into())
            } else {
                self.region.clone()
            },
            bucket: self
                .bucket
                .clone()
                .or_else(|| std::env::var("E2E_BUCKET_NAME").ok())
                .expect("Missing --bucket or WAL_BACKUP_BUCKET"),
            prefix: self.prefix.clone(),
            access_key: self
                .access_key
                .clone()
                .or_else(|| std::env::var("AWS_ACCESS_KEY_ID").ok())
                .expect("Missing --access-key or WAL_BACKUP_ACCESS_KEY or AWS_ACCESS_KEY_ID"),
            secret_key: self
                .secret_key
                .clone()
                .or_else(|| std::env::var("AWS_SECRET_ACCESS_KEY").ok())
                .expect("Missing --secret-key or WAL_BACKUP_SECRET_KEY or AWS_SECRET_ACCESS_KEY"),
        }
    }
}

struct ResolvedOpts {
    endpoint: String,
    region: String,
    bucket: String,
    prefix: String,
    access_key: String,
    secret_key: String,
}

#[derive(Subcommand)]
enum Commands {
    /// Restore a SQLite database from the bucket
    Restore {
        db_path: PathBuf,
        #[command(flatten)]
        s3: S3Opts,
        /// Overwrite local DB even if it exists and is newer
        #[arg(long)]
        force: bool,
        /// Delete writer.json and lock.json from the bucket before restoring.
        /// Use this when replacing a decommissioned server.
        #[arg(long)]
        force_takeover: bool,
    },
    /// Verify bucket integrity
    Verify {
        db_path: PathBuf,
        #[command(flatten)]
        s3: S3Opts,
    },
    /// Show manifest status
    Status {
        db_path: PathBuf,
        #[command(flatten)]
        s3: S3Opts,
    },
}

fn make_bucket(opts: &ResolvedOpts) -> Arc<ObjectStoreBucket> {
    let store = build_s3_store(
        &opts.endpoint,
        &opts.region,
        &opts.access_key,
        &opts.secret_key,
        &opts.bucket,
    )
    .expect("Failed to build S3 store");
    Arc::new(ObjectStoreBucket::new(store, opts.prefix.clone()).expect("Invalid prefix"))
}

/// Open a DurabilityLayer with a 30s timeout and slow poll interval (for CLI tools that just want restore/verify)
async fn open_with_timeout(config: Config, bucket: Arc<ObjectStoreBucket>) -> DurabilityLayer {
    tokio::time::timeout(
        Duration::from_secs(30),
        DurabilityLayer::open(config, bucket),
    )
    .await
    .expect("Timed out waiting for durability layer (30s)")
    .expect("Failed to open durability layer")
}

async fn shutdown_with_timeout(layer: DurabilityLayer) {
    let result = tokio::time::timeout(Duration::from_secs(15), layer.shutdown()).await;
    match result {
        Ok(Ok(())) => {}
        Ok(Err(e)) => eprintln!("Shutdown error: {e} — data will re-sync on next start"),
        Err(_) => eprintln!("Shutdown timed out (15s) — data will re-sync on next start"),
    }
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();
    let cli = Cli::parse();

    match cli.command {
        Commands::Restore {
            db_path,
            s3,
            force,
            force_takeover,
        } => cmd_restore(db_path, &s3.resolve(), force, force_takeover).await,
        Commands::Verify { db_path, s3 } => cmd_verify(db_path, &s3.resolve()).await,
        Commands::Status { db_path, s3 } => cmd_status(db_path, &s3.resolve()).await,
    }
}

async fn cmd_restore(db_path: PathBuf, opts: &ResolvedOpts, force: bool, force_takeover: bool) {
    eprintln!(
        "Restoring {} from s3://{}/{} ...",
        db_path.display(),
        opts.bucket,
        opts.prefix
    );

    let bucket = make_bucket(opts);

    // Force takeover: delete writer.json and lock.json from the bucket
    // so a new server can claim the prefix. This is done BEFORE opening
    // the DurabilityLayer to avoid the layer re-registering as writer.
    if force_takeover {
        eprintln!("Force takeover: deleting writer.json and lock.json from bucket...");
        if let Err(e) = bucket.delete("writer.json").await {
            eprintln!("  (writer.json: {e})");
        } else {
            eprintln!("  ✅ Deleted writer.json");
        }
        if let Err(e) = bucket.delete("lock.json").await {
            eprintln!("  (lock.json: {e})");
        } else {
            eprintln!("  ✅ Deleted lock.json");
        }
        // Also delete the local generation file so the next open
        // doesn't think the local DB is already synced
        let gen_path = db_path.with_extension("generation");
        if gen_path.exists() {
            std::fs::remove_file(&gen_path).ok();
            eprintln!("  ✅ Deleted local generation file");
        }
        // If force-takeover is the only intent (no DB file to restore),
        // just exit after cleanup — don't open a DurabilityLayer
        // which would re-register as writer.
        if !db_path.exists() {
            eprintln!("Force takeover complete. No local DB to restore — exiting.");
            return;
        }
        eprintln!("Proceeding with restore...");
    }
    let restore_behavior = if force {
        RestoreBehavior::AlwaysRestoreFromBucket
    } else {
        RestoreBehavior::UploadLocalIfNewer
    };

    let config = Config::new(&db_path)
        .with_restore_behavior(restore_behavior)
        .with_poll_interval(Duration::from_secs(1));

    let layer = open_with_timeout(config, bucket).await;

    {
        let conn = layer.conn().await;
        let tables: Vec<String> = conn
            .prepare("SELECT name FROM sqlite_master WHERE type='table'")
            .expect("Query sqlite_master")
            .query_map([], |row| row.get(0))
            .expect("Fetch rows")
            .filter_map(|r| r.ok())
            .collect();

        eprintln!("Restore complete. Tables: {:?}", tables);
        if let Some(table) = tables.first() {
            if let Ok(count) =
                conn.query_row(&format!("SELECT COUNT(*) FROM {}", table), [], |row| {
                    row.get::<_, i64>(0)
                })
            {
                eprintln!("  {}.rows = {}", table, count);
            }
        }
    } // drop conn guard

    shutdown_with_timeout(layer).await;
    eprintln!("Done.");
}

async fn cmd_verify(db_path: PathBuf, opts: &ResolvedOpts) {
    eprintln!("Verifying s3://{}/{} ...", opts.bucket, opts.prefix);

    let bucket = make_bucket(opts);
    let config = Config::new(&db_path)
        .with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket)
        .with_poll_interval(Duration::from_secs(1));

    let layer = open_with_timeout(config, bucket.clone()).await;

    let manifest_bytes = match bucket.get("manifest.json").await {
        Ok(Some(data)) => data,
        Ok(None) => {
            eprintln!("❌ manifest.json not found in bucket!");
            shutdown_with_timeout(layer).await;
            return;
        }
        Err(e) => {
            eprintln!("❌ Failed to read manifest: {e}");
            shutdown_with_timeout(layer).await;
            return;
        }
    };

    let manifest: wal_backup::Manifest = match serde_json::from_slice(&manifest_bytes) {
        Ok(m) => m,
        Err(e) => {
            eprintln!("❌ Failed to parse manifest: {e}");
            shutdown_with_timeout(layer).await;
            return;
        }
    };

    let mut errors = 0u32;
    let mut warnings = 0u32;

    // 1. Snapshot
    if let Some(ref snap_key) = manifest.snapshot {
        eprintln!(
            "✅ Snapshot: {} (checksum: {:?})",
            snap_key, manifest.snapshot_checksum
        );
        match bucket.get(snap_key).await {
            Ok(Some(_)) => eprintln!("   ✅ Snapshot file exists"),
            Ok(None) => {
                eprintln!("   ❌ Snapshot file missing!");
                errors += 1;
            }
            Err(e) => {
                eprintln!("   ⚠️  Cannot verify snapshot: {e}");
                warnings += 1;
            }
        }
    } else {
        eprintln!("❌ No snapshot in manifest!");
        errors += 1;
    }

    // 2. L0 segments
    let salt_prefix = manifest.segment_prefix();
    let l0_keys = bucket.list(&salt_prefix).await.unwrap_or_default();
    let l0_count = l0_keys.iter().filter(|k| k.ends_with(".l0")).count();
    eprintln!("   L0 segments: {} (listed from bucket)", l0_count);

    // 3. L1 segments
    eprintln!("   L1 segments: {}", manifest.l1_files.len());
    for seg in &manifest.l1_files {
        match bucket.get(&seg.key).await {
            Ok(Some(_)) => {}
            Ok(None) => {
                eprintln!("   ❌ L1 missing: {}", seg.key);
                errors += 1;
            }
            Err(e) => {
                eprintln!("   ⚠️  Cannot verify L1 {}: {e}", seg.key);
                warnings += 1;
            }
        }
    }

    if errors == 0 && warnings == 0 {
        eprintln!(
            "✅ Bucket is healthy: {} L0, {} L1, snapshot present",
            l0_count,
            manifest.l1_files.len()
        );
    } else {
        eprintln!(
            "⚠️  Verify complete: {} errors, {} warnings",
            errors, warnings
        );
    }

    shutdown_with_timeout(layer).await;
}

async fn cmd_status(db_path: PathBuf, opts: &ResolvedOpts) {
    let bucket = make_bucket(opts);
    let config = Config::new(&db_path)
        .with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket)
        .with_poll_interval(Duration::from_secs(1));

    let layer = open_with_timeout(config, bucket.clone()).await;

    let manifest_bytes = match bucket.get("manifest.json").await {
        Ok(Some(data)) => data,
        Ok(None) => {
            eprintln!("No manifest found in s3://{}/{}", opts.bucket, opts.prefix);
            shutdown_with_timeout(layer).await;
            return;
        }
        Err(e) => {
            eprintln!("Failed to read manifest: {e}");
            shutdown_with_timeout(layer).await;
            return;
        }
    };

    let manifest: wal_backup::Manifest = match serde_json::from_slice(&manifest_bytes) {
        Ok(m) => m,
        Err(e) => {
            eprintln!("Failed to parse manifest: {e}");
            shutdown_with_timeout(layer).await;
            return;
        }
    };

    eprintln!("Bucket: s3://{}/{}", opts.bucket, opts.prefix);
    eprintln!("Database: {}", db_path.display());

    if let Some(ref snap_key) = manifest.snapshot {
        eprintln!("Snapshot:");
        eprintln!("  key:      {}", snap_key);
        eprintln!("  checksum: {:?}", manifest.snapshot_checksum);
        eprintln!("  db_size:  {} bytes", manifest.db_size);
    } else {
        eprintln!("Snapshot: (none)");
    }

    eprintln!(
        "Salt: {:08x}-{:08x}",
        manifest.current_salt_1, manifest.current_salt_2
    );
    eprintln!("Page size: {}", manifest.page_size);
    eprintln!("Shipped frames: {}", manifest.shipped_frames);
    eprintln!("L1 segments: {}", manifest.l1_files.len());
    eprintln!("Version: {}", manifest.version);
    eprintln!("Generation: {}", manifest.generation);
    eprintln!("Last updated: {}", manifest.last_updated);

    eprintln!();
    eprintln!("Healthy: {}", layer.is_healthy().await);
    eprintln!("Last sync: {:?}", layer.last_sync().await);

    shutdown_with_timeout(layer).await;
}