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 /// `red.config.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("red.config.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 = self.config_string(
76 "red.config.backup.snapshot_prefix",
77 &default_snapshot_prefix,
78 );
79 let wal_prefix =
80 self.config_string("red.config.wal.archive.prefix", &default_wal_prefix);
81 let head_key = self.config_string("red.config.backup.head_key", &default_head_key);
82 let timeline_id = self.config_string("red.config.timeline.id", "main");
83 let snapshot_key = crate::storage::wal::archive_snapshot(
84 backend.as_ref(),
85 path,
86 snapshot.snapshot_id,
87 &snapshot_prefix,
88 )
89 .map_err(|err| RedDBError::Internal(err.to_string()))?;
90 let current_lsn = self
91 .inner
92 .db
93 .replication
94 .as_ref()
95 .map(|repl| {
96 repl.logical_wal_spool
97 .as_ref()
98 .map(|spool| spool.current_lsn())
99 .unwrap_or_else(|| repl.wal_buffer.current_lsn())
100 })
101 .unwrap_or_else(|| self.inner.cdc.current_lsn());
102 let last_archived_lsn = self.config_u64("red.config.timeline.last_archived_lsn", 0);
103 // Hash the local snapshot bytes so the manifest can carry
104 // the digest for restore-side verification (PLAN.md
105 // Phase 4). Failure to hash is non-fatal — we still
106 // publish the manifest, just without a checksum, so a
107 // future fix can backfill rather than losing the backup.
108 let snapshot_sha256 = reddb_file::SnapshotManifest::compute_snapshot_sha256(path)
109 .map_err(|err| {
110 tracing::warn!(
111 target: "reddb::backup",
112 error = %err,
113 snapshot_id = snapshot.snapshot_id,
114 "snapshot hash failed; manifest will lack checksum"
115 );
116 })
117 .ok();
118 let manifest = reddb_file::SnapshotManifest {
119 timeline_id: timeline_id.clone(),
120 snapshot_key: snapshot_key.clone(),
121 snapshot_id: snapshot.snapshot_id,
122 snapshot_time: snapshot.created_at_unix_ms as u64,
123 base_lsn: current_lsn,
124 schema_version: crate::api::REDDB_FORMAT_VERSION,
125 format_version: crate::api::REDDB_FORMAT_VERSION,
126 snapshot_sha256,
127 };
128 crate::storage::wal::publish_snapshot_manifest(backend.as_ref(), &manifest)
129 .map_err(|err| RedDBError::Internal(err.to_string()))?;
130
131 // PLAN.md Phase 11.3 — read the head of the WAL hash chain
132 // so the new segment can link back. `None` means we're
133 // starting a fresh timeline (after a clean restore or on
134 // first archive ever); the segment's `prev_hash` will be
135 // `None` and restore-side validation accepts that only for
136 // the first segment in `plan.wal_segments`.
137 let prev_segment_hash =
138 self.config_string("red.config.timeline.last_segment_hash", "");
139 let prev_hash_arg = if prev_segment_hash.is_empty() {
140 None
141 } else {
142 Some(prev_segment_hash)
143 };
144
145 let archived_lsn = if let Some(primary) = &self.inner.db.replication {
146 let oldest = primary
147 .logical_wal_spool
148 .as_ref()
149 .and_then(|spool| spool.oldest_lsn().ok().flatten())
150 .or_else(|| primary.wal_buffer.oldest_lsn())
151 .unwrap_or(last_archived_lsn);
152 if last_archived_lsn > 0 && last_archived_lsn < oldest.saturating_sub(1) {
153 return Err(RedDBError::Internal(format!(
154 "logical WAL gap detected: last_archived_lsn={last_archived_lsn}, oldest_available_lsn={oldest}"
155 )));
156 }
157 let records = if let Some(spool) = &primary.logical_wal_spool {
158 spool
159 .read_since(last_archived_lsn, usize::MAX)
160 .map_err(|err| RedDBError::Internal(err.to_string()))?
161 } else {
162 primary.wal_buffer.read_since(last_archived_lsn, usize::MAX)
163 };
164 if let Some(meta) = crate::storage::wal::archive_change_records(
165 backend.as_ref(),
166 &wal_prefix,
167 &records,
168 prev_hash_arg,
169 )
170 .map_err(|err| RedDBError::Internal(err.to_string()))?
171 {
172 let _ = primary.prune_retained_wal_through(meta.lsn_end);
173 if let Err(err) = self.prune_primary_replica_wal_segments() {
174 tracing::warn!(
175 error = %err,
176 "failed to prune primary-replica WAL segments"
177 );
178 }
179 // Advance the chain head so the next archive call
180 // links to this segment's hash. If the segment has
181 // no sha256 (legacy / hashing failed) we leave the
182 // head as-is — the next segment then carries the
183 // prior chain head, preserving continuity.
184 if let Some(sha) = &meta.sha256 {
185 self.inner.db.store().set_config_tree(
186 "red.config.timeline",
187 &crate::json!({ "last_segment_hash": sha }),
188 );
189 }
190 meta.lsn_end
191 } else {
192 last_archived_lsn
193 }
194 } else {
195 last_archived_lsn
196 };
197
198 let head = reddb_file::BackupHead {
199 timeline_id,
200 snapshot_key,
201 snapshot_id: snapshot.snapshot_id,
202 snapshot_time: snapshot.created_at_unix_ms as u64,
203 current_lsn,
204 last_archived_lsn: archived_lsn,
205 wal_prefix,
206 };
207 crate::storage::wal::publish_backup_head(backend.as_ref(), &head_key, &head)
208 .map_err(|err| RedDBError::Internal(err.to_string()))?;
209 self.inner.db.store().set_config_tree(
210 "red.config.timeline",
211 &crate::json!({
212 "last_archived_lsn": archived_lsn,
213 "id": head.timeline_id
214 }),
215 );
216
217 // PLAN.md Phase 2.4 — refresh the unified `MANIFEST.json`
218 // at the prefix root so external tooling sees a single
219 // catalog of every snapshot + WAL segment with their
220 // checksums. Best-effort: a manifest publish failure
221 // doesn't fail the backup (the per-artifact sidecars
222 // already give restore-side integrity), but it does log
223 // so dashboards can flag stale catalogs.
224 if let Err(err) = crate::storage::wal::publish_unified_manifest_for_prefix(
225 backend.as_ref(),
226 &snapshot_prefix,
227 ) {
228 tracing::warn!(
229 target: "reddb::backup",
230 error = %err,
231 snapshot_prefix = %snapshot_prefix,
232 "unified MANIFEST.json refresh failed; per-artifact sidecars unaffected"
233 );
234 }
235
236 // PLAN.md Phase 11.4 — when the operator picked a
237 // commit policy that demands replica durability, block
238 // until the configured count of replicas has acked the
239 // archived LSN (or the timeout fires). For backup the
240 // policy decides the *DR posture* — `local` returns
241 // immediately, `ack_n` ensures at least N replicas saw
242 // the new tail before we report success to the
243 // operator. A `TimedOut` is logged but does NOT fail
244 // the backup: the local WAL + remote upload are durable
245 // regardless; the missing acks are reported via
246 // /metrics and /admin/status so the operator can decide.
247 match self.commit_policy() {
248 crate::replication::CommitPolicy::AckN(n) if n > 0 => {
249 let timeout = std::env::var("RED_REPLICATION_ACK_TIMEOUT_MS")
250 .ok()
251 .and_then(|v| v.parse::<u64>().ok())
252 .unwrap_or(5_000);
253 let outcome = self.await_replica_acks(
254 archived_lsn,
255 n,
256 std::time::Duration::from_millis(timeout),
257 );
258 match outcome {
259 crate::replication::AwaitOutcome::Reached(count) => {
260 tracing::debug!(
261 target: "reddb::backup",
262 archived_lsn,
263 n,
264 count,
265 "ack_n: replicas synced before backup return"
266 );
267 }
268 crate::replication::AwaitOutcome::TimedOut { observed, required } => {
269 tracing::warn!(
270 target: "reddb::backup",
271 archived_lsn,
272 observed,
273 required,
274 timeout_ms = timeout,
275 "ack_n: timed out waiting for replicas; backup uploaded but DR posture degraded"
276 );
277 }
278 crate::replication::AwaitOutcome::NotRequired => {}
279 }
280 }
281 _ => {} // Local / RemoteWal / Quorum: no blocking yet
282 }
283
284 // Issue #148 follow-up — opt-in archive of the L2 Blob Cache
285 // directory tree. Default off so a standard backup stays
286 // small; flip via `red.config.backup.include_blob_cache=true`
287 // when warm-cache restore is required (per
288 // docs/operations/blob-cache-backup-restore.md §1).
289 //
290 // The L2 tree is *derived* state (ADR 0006) — its absence
291 // never causes data loss; it only affects post-restore
292 // p99 latency until the cache re-warms. We therefore log
293 // (not fail) on per-file upload errors so a partial L2
294 // upload never aborts a healthy snapshot+WAL backup.
295 if self.config_bool("red.config.backup.include_blob_cache", false) {
296 let blob_cache_prefix = self.config_string(
297 "red.config.backup.blob_cache_prefix",
298 &format!("{snapshot_prefix}blob_cache/"),
299 );
300 if let Some(l2_path) = self.inner.result_blob_cache.l2_path() {
301 match crate::storage::cache::archive_blob_cache_l2(
302 backend.as_ref(),
303 l2_path,
304 &blob_cache_prefix,
305 ) {
306 Ok(count) => {
307 tracing::info!(
308 target: "reddb::backup",
309 files_uploaded = count,
310 blob_cache_prefix = %blob_cache_prefix,
311 "include_blob_cache: archived L2 directory"
312 );
313 }
314 Err(err) => {
315 tracing::warn!(
316 target: "reddb::backup",
317 error = %err,
318 blob_cache_prefix = %blob_cache_prefix,
319 "include_blob_cache: L2 archive failed; backup proceeding (cache is derived state)"
320 );
321 }
322 }
323 } else {
324 tracing::debug!(
325 target: "reddb::backup",
326 "include_blob_cache=true but no L2 path configured; nothing to archive"
327 );
328 }
329 }
330
331 uploaded = true;
332 }
333
334 Ok(crate::replication::scheduler::BackupResult {
335 snapshot_id: snapshot.snapshot_id,
336 uploaded,
337 duration_ms: started.elapsed().as_millis() as u64,
338 timestamp: snapshot.created_at_unix_ms as u64,
339 })
340 })();
341
342 use crate::runtime::control_events::{EventKind, Outcome, Sensitivity};
343 let (current_lsn, last_archived_lsn) = self.wal_archive_progress();
344 let mut fields = vec![
345 (
346 "current_lsn".to_string(),
347 Sensitivity::raw(current_lsn.to_string()),
348 ),
349 (
350 "last_archived_lsn".to_string(),
351 Sensitivity::raw(last_archived_lsn.to_string()),
352 ),
353 ];
354 if let Ok(backup) = &result {
355 fields.push((
356 "snapshot_id".to_string(),
357 Sensitivity::raw(backup.snapshot_id.to_string()),
358 ));
359 fields.push((
360 "uploaded".to_string(),
361 Sensitivity::raw(backup.uploaded.to_string()),
362 ));
363 fields.push((
364 "duration_ms".to_string(),
365 Sensitivity::raw(backup.duration_ms.to_string()),
366 ));
367 fields.push((
368 "snapshot_time".to_string(),
369 Sensitivity::raw(backup.timestamp.to_string()),
370 ));
371 }
372 let outcome = match &result {
373 Ok(_) => Outcome::Allowed,
374 Err(err) => crate::runtime::impl_core::control_event_outcome_for_error(err),
375 };
376 let reason = result.as_ref().err().map(|err| err.to_string());
377 self.emit_control_event(
378 EventKind::BackupRun,
379 outcome,
380 "backup_trigger",
381 Some("backup:trigger".to_string()),
382 reason,
383 fields,
384 )?;
385 result
386 }
387}