wal-backup 0.8.11

Embedded SQLite WAL replication to S3-compatible object storage. Not a sidecar — a library. Like Litestream, but embedded.
Documentation
# Production Guide

## Health Monitoring

```rust
if !layer.is_healthy().await {
    // Replication is lagging or background tasks have crashed.
    // Last sync exceeded health_timeout (default 30s).
    log::error!("WAL replication unhealthy!");
}
```

`is_healthy()` returns `false` when:
- The shipper or snapshot background tasks have panicked/exited
- Time since last successful sync exceeds `health_timeout`

### Detailed Health Diagnostics

For programmatic monitoring, use `health_report()` which returns a `HealthReport` with individual fields:

```rust
let report = layer.health_report().await;
log::info!("healthy={} replicator={} snapshot={} last_sync_ago={:?}",
    report.healthy, report.replicator_alive, report.snapshot_alive, report.last_sync_ago);
```

### Scoped Connection Access

Use `with_conn()` for scoped, closure-based access to the underlying connection:

```rust
let count: i64 = layer.with_conn(|c| {
    c.query_row("SELECT COUNT(*) FROM my_table", [], |r| r.get(0))
}).await?;
```

The connection lock is automatically released when the closure returns, preventing accidental long-held locks.

## Synchronous Flush

Before critical operations, force WAL frames to the bucket:

```rust
layer.sync_now().await?;
// All committed WAL frames up to this point are now in object storage.
```

This blocks until the shipper confirms frames are uploaded, with a configurable timeout (default 10s, see `Config::with_sync_timeout`).

## Forced Snapshot

To immediately upload a full database snapshot regardless of size/time thresholds:

```rust
layer.force_snapshot().await?;
```

## Disaster Recovery

### Full Restore from Bucket

On a new host with no local data:

```rust
let layer = DurabilityLayer::open(config, bucket).await?;
// The library automatically:
// 1. Downloads the latest snapshot from the bucket
// 2. Verifies the snapshot SHA-256 checksum
// 3. Downloads and applies WAL segments on top
// 4. Opens the reconstructed database
```

### Manual Restore

If you need to restore outside this library:

1. Download `manifest.json` from the bucket
2. Download the snapshot file referenced in the manifest
3. Download all WAL segment files under `wal/<salt>/`
4. Reconstruct: write snapshot as `.db` file, then append WAL header + segments as `.db-wal`
5. Open with SQLite — it will replay the WAL automatically

### Verification

After restore, verify database integrity:

```sql
PRAGMA integrity_check;
```

The library automatically verifies snapshot checksums during restore. WAL frame checksums are also validated during both shipping and restore.

## Known Limitations

- **Single writer**: SQLite only allows one writer. This library assumes it has exclusive write access.
- **Encryption and compression not applied automatically**: Even when the `encryption` and `compression` features are enabled (they are by default), data in the bucket is unencrypted and uncompressed unless you explicitly wrap your bucket with `EncryptedBucketStore` and/or `CompressedBucketStore`. See "Encryption" and "Compression" below.
- **Clock skew**: `local_is_newer_than_manifest()` uses wall-clock time as a heuristic when `generation == 0`. Use `UploadLocalIfNewer` (default) for safe behavior.
- **Salt change latency**: When SQLite checkpoints and resets WAL salts values, a snapshot must complete before shipping resumes. The shipper waits up to 60s; if snapshot takes longer, it retries on the next cycle.

## Shutdown

Always call `shutdown()` before dropping to ensure a final WAL checkpoint:

```rust
layer.shutdown().await?;
```

This aborts background tasks and checkpoints the WAL so the local DB is consistent on disk.

If `shutdown()` is not called, the `Drop` implementation will attempt a best-effort checkpoint using `try_lock()` (non-blocking). If the lock is held, it logs a warning and skips the checkpoint. Background tasks are always aborted on drop.

## Encryption

Enable the `encryption` feature to encrypt all data at rest in the bucket:

```rust
use wal_backup::storage::encrypted::EncryptedBucketStore;

let encrypted_bucket = Arc::new(EncryptedBucketStore::new(bucket, &[0u8; 32]));
```

**Envelope format**: `[ENCR(4)][version(1)][nonce(12)][ciphertext+tag]`

- `CURRENT_VERSION = 1` — AES-256-GCM
- Breaking change: data encrypted with a previous version of this crate is **not compatible** with the current envelope format
- To rotate keys, use `add_past_key(version, &key)` to allow decryption of data encrypted with old keys
- `add_past_key` returns `Result<()>` — it propagates `RwLock` poisoning errors instead of silently ignoring them

## Compression

Enable the `compression` feature to gzip-compress all data in the bucket:

```rust
use wal_backup::storage::compressed::CompressedBucketStore;

let compressed_bucket = Arc::new(CompressedBucketStore::new(bucket, 6));
```

The compression level (0–9) trades speed for ratio; 6 is the default.

## Stacking Compression + Encryption

Wrap encryption inside compression (compress first, then encrypt) for both size reduction and confidentiality:

```rust
let encrypted = Arc::new(EncryptedBucketStore::new(bucket, &key));
let compressed = Arc::new(CompressedBucketStore::new(encrypted, 6));
```

With this wrapping order, `CompressedBucketStore` is the outer API layer you call `put`/`get` on. Data flows: plaintext → compress → encrypt → bucket. On read: bucket → decrypt → decompress → plaintext. The last transform applied before storage is encryption (confidential at rest), and data is compressed before encryption (efficient).