Skip to main content

reddb_server/runtime/
impl_backup.rs

1use super::*;
2
3impl RedDBRuntime {
4    /// Get backup scheduler status.
5    pub fn backup_status(&self) -> crate::replication::scheduler::BackupStatus {
6        self.inner.backup_scheduler.status()
7    }
8
9    /// Borrow the runtime's result Blob Cache.
10    ///
11    /// Wired for the `/admin/blob_cache/sweep` and
12    /// `/admin/blob_cache/flush_namespace` HTTP handlers (issue #148
13    /// follow-up): both delegate to
14    /// `crate::storage::cache::sweeper::BlobCacheSweeper`, which takes a
15    /// `&BlobCache`. Also used by `trigger_backup` when
16    /// `backup.include_blob_cache=true` to locate the L2
17    /// directory for archival.
18    pub fn result_blob_cache(&self) -> &crate::storage::cache::BlobCache {
19        &self.inner.result_blob_cache
20    }
21
22    /// Current local LSN paired with the LSN of the most recently
23    /// archived WAL segment. The difference is the replication /
24    /// archive lag operators alert on (PLAN.md Phase 5.1). Returns
25    /// `(0, 0)` when neither replication nor archiving is configured.
26    pub fn wal_archive_progress(&self) -> (u64, u64) {
27        let current_lsn = self
28            .inner
29            .db
30            .replication
31            .as_ref()
32            .map(|repl| {
33                repl.logical_wal_spool
34                    .as_ref()
35                    .map(|spool| spool.current_lsn())
36                    .unwrap_or_else(|| repl.wal_buffer.current_lsn())
37            })
38            .unwrap_or_else(|| self.inner.cdc.current_lsn());
39        let last_archived_lsn = self.config_u64("timeline.last_archived_lsn", 0);
40        (current_lsn, last_archived_lsn)
41    }
42
43    /// Trigger an immediate backup.
44    pub fn trigger_backup(&self) -> RedDBResult<crate::replication::scheduler::BackupResult> {
45        let result = (|| {
46            self.check_write(crate::runtime::write_gate::WriteKind::Backup)?;
47            // Defense in depth — check_write above already rejects when
48            // the lease is NotHeld, but log + audit the lease angle here
49            // explicitly so dashboards distinguish "lease lost" from a
50            // generic read-only refusal.
51            self.assert_remote_write_allowed("admin/backup")?;
52            // This transport archives only the main file. Paged stores need
53            // metadata sidecars even when opened with embedded options, and
54            // operational stores also own manifest/collection/index files in
55            // .ops. Reporting success here would publish an unrestorable snapshot.
56            // A checkpoint-consistent physical bundle is required before this
57            // online path can support operational-directory packaging.
58            if self.inner.db.remote_backend.is_some()
59                && (!self.inner.embedded_single_file || self.inner.db.is_paged())
60            {
61                return Err(RedDBError::InvalidOperation(
62                    "online backup of paged or operational-directory stores requires a checkpoint-consistent physical bundle; use a fenced offline backup of the complete store layout".into(),
63                ));
64            }
65            let started = std::time::Instant::now();
66            let snapshot = self.create_snapshot()?;
67            let mut uploaded = false;
68
69            if let (Some(backend), Some(path)) =
70                (&self.inner.db.remote_backend, self.inner.db.path())
71            {
72                let default_snapshot_prefix = self.inner.db.options().default_snapshot_prefix();
73                let default_wal_prefix = self.inner.db.options().default_wal_archive_prefix();
74                let default_head_key = self.inner.db.options().default_backup_head_key();
75                let snapshot_prefix =
76                    self.config_string("backup.snapshot_prefix", &default_snapshot_prefix);
77                let wal_prefix = self.config_string("wal.archive.prefix", &default_wal_prefix);
78                let head_key = self.config_string("backup.head_key", &default_head_key);
79                let timeline_id = self.config_string("timeline.id", "main");
80                let snapshot_key = crate::storage::wal::archive_snapshot(
81                    backend.as_ref(),
82                    path,
83                    snapshot.snapshot_id,
84                    &snapshot_prefix,
85                )
86                .map_err(|err| RedDBError::Internal(err.to_string()))?;
87                let current_lsn = self
88                    .inner
89                    .db
90                    .replication
91                    .as_ref()
92                    .map(|repl| {
93                        repl.logical_wal_spool
94                            .as_ref()
95                            .map(|spool| spool.current_lsn())
96                            .unwrap_or_else(|| repl.wal_buffer.current_lsn())
97                    })
98                    .unwrap_or_else(|| self.inner.cdc.current_lsn());
99                let last_archived_lsn = self.config_u64("timeline.last_archived_lsn", 0);
100                // Hash the local snapshot bytes so the manifest can carry
101                // the digest for restore-side verification (PLAN.md
102                // Phase 4). Failure to hash is non-fatal — we still
103                // publish the manifest, just without a checksum, so a
104                // future fix can backfill rather than losing the backup.
105                let snapshot_sha256 = reddb_file::SnapshotManifest::compute_snapshot_sha256(path)
106                    .map_err(|err| {
107                        tracing::warn!(
108                            target: "reddb::backup",
109                            error = %err,
110                            snapshot_id = snapshot.snapshot_id,
111                            "snapshot hash failed; manifest will lack checksum"
112                        );
113                    })
114                    .ok();
115                let manifest = reddb_file::SnapshotManifest {
116                    timeline_id: timeline_id.clone(),
117                    snapshot_key: snapshot_key.clone(),
118                    snapshot_id: snapshot.snapshot_id,
119                    snapshot_time: snapshot.created_at_unix_ms as u64,
120                    base_lsn: current_lsn,
121                    schema_version: crate::api::REDDB_FORMAT_VERSION,
122                    format_version: crate::api::REDDB_FORMAT_VERSION,
123                    snapshot_sha256,
124                };
125                crate::storage::wal::publish_snapshot_manifest(backend.as_ref(), &manifest)
126                    .map_err(|err| RedDBError::Internal(err.to_string()))?;
127
128                // PLAN.md Phase 11.3 — read the head of the WAL hash chain
129                // so the new segment can link back. `None` means we're
130                // starting a fresh timeline (after a clean restore or on
131                // first archive ever); the segment's `prev_hash` will be
132                // `None` and restore-side validation accepts that only for
133                // the first segment in `plan.wal_segments`.
134                let prev_segment_hash = self.config_string("timeline.last_segment_hash", "");
135                let prev_hash_arg = if prev_segment_hash.is_empty() {
136                    None
137                } else {
138                    Some(prev_segment_hash)
139                };
140
141                let archived_lsn = if let Some(primary) = &self.inner.db.replication {
142                    let oldest = primary
143                        .logical_wal_spool
144                        .as_ref()
145                        .and_then(|spool| spool.oldest_lsn().ok().flatten())
146                        .or_else(|| primary.wal_buffer.oldest_lsn())
147                        .unwrap_or(last_archived_lsn);
148                    if last_archived_lsn > 0 && last_archived_lsn < oldest.saturating_sub(1) {
149                        return Err(RedDBError::Internal(format!(
150                            "logical WAL gap detected: last_archived_lsn={last_archived_lsn}, oldest_available_lsn={oldest}"
151                        )));
152                    }
153                    let records = if let Some(spool) = &primary.logical_wal_spool {
154                        spool
155                            .read_since(last_archived_lsn, usize::MAX)
156                            .map_err(|err| RedDBError::Internal(err.to_string()))?
157                    } else {
158                        primary.wal_buffer.read_since(last_archived_lsn, usize::MAX)
159                    };
160                    if let Some(meta) = crate::storage::wal::archive_change_records(
161                        backend.as_ref(),
162                        &wal_prefix,
163                        &records,
164                        prev_hash_arg,
165                    )
166                    .map_err(|err| RedDBError::Internal(err.to_string()))?
167                    {
168                        let _ = primary.prune_retained_wal_through(meta.lsn_end);
169                        if let Err(err) = self.prune_primary_replica_wal_segments() {
170                            tracing::warn!(
171                                error = %err,
172                                "failed to prune primary-replica WAL segments"
173                            );
174                        }
175                        // Advance the chain head so the next archive call
176                        // links to this segment's hash. If the segment has
177                        // no sha256 (legacy / hashing failed) we leave the
178                        // head as-is — the next segment then carries the
179                        // prior chain head, preserving continuity.
180                        if let Some(sha) = &meta.sha256 {
181                            self.inner.db.store().set_config_tree(
182                                "timeline",
183                                &crate::json!({ "last_segment_hash": sha }),
184                            );
185                        }
186                        meta.lsn_end
187                    } else {
188                        last_archived_lsn
189                    }
190                } else {
191                    last_archived_lsn
192                };
193
194                let head = reddb_file::BackupHead {
195                    timeline_id,
196                    snapshot_key,
197                    snapshot_id: snapshot.snapshot_id,
198                    snapshot_time: snapshot.created_at_unix_ms as u64,
199                    current_lsn,
200                    last_archived_lsn: archived_lsn,
201                    wal_prefix,
202                };
203                crate::storage::wal::publish_backup_head(backend.as_ref(), &head_key, &head)
204                    .map_err(|err| RedDBError::Internal(err.to_string()))?;
205                self.inner.db.store().set_config_tree(
206                    "timeline",
207                    &crate::json!({
208                        "last_archived_lsn": archived_lsn,
209                        "id": head.timeline_id
210                    }),
211                );
212
213                // PLAN.md Phase 2.4 — refresh the unified `MANIFEST.json`
214                // at the prefix root so external tooling sees a single
215                // catalog of every snapshot + WAL segment with their
216                // checksums. Best-effort: a manifest publish failure
217                // doesn't fail the backup (the per-artifact sidecars
218                // already give restore-side integrity), but it does log
219                // so dashboards can flag stale catalogs.
220                if let Err(err) = crate::storage::wal::publish_unified_manifest_for_prefix(
221                    backend.as_ref(),
222                    &snapshot_prefix,
223                ) {
224                    tracing::warn!(
225                        target: "reddb::backup",
226                        error = %err,
227                        snapshot_prefix = %snapshot_prefix,
228                        "unified MANIFEST.json refresh failed; per-artifact sidecars unaffected"
229                    );
230                }
231
232                // PLAN.md Phase 11.4 — when the operator picked a
233                // commit policy that demands replica durability, block
234                // until the configured count of replicas has acked the
235                // archived LSN (or the timeout fires). For backup the
236                // policy decides the *DR posture* — `local` returns
237                // immediately, `ack_n` ensures at least N replicas saw
238                // the new tail before we report success to the
239                // operator. A `TimedOut` is logged but does NOT fail
240                // the backup: the local WAL + remote upload are durable
241                // regardless; the missing acks are reported via
242                // /metrics and /admin/status so the operator can decide.
243                match self.commit_policy() {
244                    crate::replication::CommitPolicy::AckN(n) if n > 0 => {
245                        let timeout = std::env::var("RED_REPLICATION_ACK_TIMEOUT_MS")
246                            .ok()
247                            .and_then(|v| v.parse::<u64>().ok())
248                            .unwrap_or(5_000);
249                        let outcome = self.await_replica_acks(
250                            archived_lsn,
251                            n,
252                            std::time::Duration::from_millis(timeout),
253                        );
254                        match outcome {
255                            crate::replication::AwaitOutcome::Reached(count) => {
256                                tracing::debug!(
257                                    target: "reddb::backup",
258                                    archived_lsn,
259                                    n,
260                                    count,
261                                    "ack_n: replicas synced before backup return"
262                                );
263                            }
264                            crate::replication::AwaitOutcome::TimedOut { observed, required } => {
265                                tracing::warn!(
266                                    target: "reddb::backup",
267                                    archived_lsn,
268                                    observed,
269                                    required,
270                                    timeout_ms = timeout,
271                                    "ack_n: timed out waiting for replicas; backup uploaded but DR posture degraded"
272                                );
273                            }
274                            crate::replication::AwaitOutcome::NotRequired => {}
275                        }
276                    }
277                    _ => {} // Local / RemoteWal / Quorum: no blocking yet
278                }
279
280                // Compatibility path for the legacy standalone L2 pager.
281                // The server's single-file L2 is an internal collection in
282                // the primary snapshot and therefore has no separate path
283                // to archive here.
284                //
285                // The L2 tree is *derived* state (ADR 0006) — its absence
286                // never causes data loss; it only affects post-restore
287                // p99 latency until the cache re-warms. We therefore log
288                // (not fail) on per-file upload errors so a partial L2
289                // upload never aborts a healthy snapshot+WAL backup.
290                if self.config_bool("backup.include_blob_cache", false) {
291                    let blob_cache_prefix = self.config_string(
292                        "backup.blob_cache_prefix",
293                        &format!("{snapshot_prefix}blob_cache/"),
294                    );
295                    if let Some(l2_path) = self.inner.result_blob_cache.l2_path() {
296                        match crate::storage::cache::archive_blob_cache_l2(
297                            backend.as_ref(),
298                            l2_path,
299                            &blob_cache_prefix,
300                        ) {
301                            Ok(count) => {
302                                tracing::info!(
303                                    target: "reddb::backup",
304                                    files_uploaded = count,
305                                    blob_cache_prefix = %blob_cache_prefix,
306                                    "include_blob_cache: archived L2 directory"
307                                );
308                            }
309                            Err(err) => {
310                                tracing::warn!(
311                                    target: "reddb::backup",
312                                    error = %err,
313                                    blob_cache_prefix = %blob_cache_prefix,
314                                    "include_blob_cache: L2 archive failed; backup proceeding (cache is derived state)"
315                                );
316                            }
317                        }
318                    } else {
319                        tracing::debug!(
320                            target: "reddb::backup",
321                            "include_blob_cache=true but no legacy standalone L2 path is configured"
322                        );
323                    }
324                }
325
326                uploaded = true;
327            }
328
329            Ok(crate::replication::scheduler::BackupResult {
330                snapshot_id: snapshot.snapshot_id,
331                uploaded,
332                duration_ms: started.elapsed().as_millis() as u64,
333                timestamp: snapshot.created_at_unix_ms as u64,
334            })
335        })();
336
337        use crate::runtime::control_events::{EventKind, Outcome, Sensitivity};
338        let (current_lsn, last_archived_lsn) = self.wal_archive_progress();
339        let mut fields = vec![
340            (
341                "current_lsn".to_string(),
342                Sensitivity::raw(current_lsn.to_string()),
343            ),
344            (
345                "last_archived_lsn".to_string(),
346                Sensitivity::raw(last_archived_lsn.to_string()),
347            ),
348        ];
349        if let Ok(backup) = &result {
350            fields.push((
351                "snapshot_id".to_string(),
352                Sensitivity::raw(backup.snapshot_id.to_string()),
353            ));
354            fields.push((
355                "uploaded".to_string(),
356                Sensitivity::raw(backup.uploaded.to_string()),
357            ));
358            fields.push((
359                "duration_ms".to_string(),
360                Sensitivity::raw(backup.duration_ms.to_string()),
361            ));
362            fields.push((
363                "snapshot_time".to_string(),
364                Sensitivity::raw(backup.timestamp.to_string()),
365            ));
366        }
367        let outcome = match &result {
368            Ok(_) => Outcome::Allowed,
369            Err(err) => crate::runtime::impl_core::control_event_outcome_for_error(err),
370        };
371        let reason = result.as_ref().err().map(|err| err.to_string());
372        self.emit_control_event(
373            EventKind::BackupRun,
374            outcome,
375            "backup_trigger",
376            Some("backup:trigger".to_string()),
377            reason,
378            fields,
379        )?;
380        result
381    }
382}