1use bytes::Bytes;
21use std::sync::Arc;
22use tokio::sync::Mutex;
23
24use crate::config::Config;
25use crate::error::{Error, Result};
26use crate::metrics::Metrics;
27use crate::replication::manifest::{Manifest, MANIFEST_KEY};
28use crate::storage::BucketStore;
29use crate::wal::{WalFile, WalHeader};
30
31pub struct RestoreEngine {
32 config: Config,
33 bucket: Arc<dyn BucketStore>,
34 metrics: Option<Arc<dyn Metrics>>,
35}
36
37fn generation_path(db_path: &std::path::Path) -> std::path::PathBuf {
42 db_path.with_extension("generation")
43}
44
45pub(crate) async fn write_generation(
47 db_path: &std::path::Path,
48 generation: u64,
49) -> crate::error::Result<()> {
50 let path = generation_path(db_path);
51 tokio::fs::write(&path, generation.to_string())
52 .await
53 .map_err(|e| crate::error::Error::Other(format!("failed to write generation file: {e}")))
54}
55
56async fn read_generation(db_path: &std::path::Path) -> Result<Option<u64>> {
60 let path = generation_path(db_path);
61 match tokio::fs::read_to_string(&path).await {
62 Ok(content) => {
63 match content.trim().parse::<u64>() {
64 Ok(gen) => Ok(Some(gen)),
65 Err(e) => {
66 tracing::warn!(
67 "Corrupted generation file at {} — cannot parse '{}': {}. \
68 Treating as missing generation.",
69 path.display(), content.trim(), e
70 );
71 Ok(None)
74 }
75 }
76 }
77 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
78 Ok(None)
79 }
80 Err(e) => {
81 tracing::warn!(
82 "Cannot read generation file at {}: {}",
83 path.display(), e
84 );
85 Ok(None)
86 }
87 }
88}
89
90impl RestoreEngine {
91 pub fn new(config: Config, bucket: Arc<dyn BucketStore>) -> Self {
92 RestoreEngine {
93 config,
94 bucket,
95 metrics: None,
96 }
97 }
98
99 pub fn with_metrics(self, metrics: Arc<dyn Metrics>) -> Self {
100 Self {
101 metrics: Some(metrics),
102 ..self
103 }
104 }
105
106 async fn detect_local_salts(&self) -> (u32, u32, u32) {
107 let db_exists = tokio::fs::try_exists(self.config.db_path())
108 .await
109 .unwrap_or(false);
110 let wal_exists = tokio::fs::try_exists(self.config.wal_path())
111 .await
112 .unwrap_or(false);
113
114 if !db_exists && !wal_exists {
115 return (0, 0, 4096);
116 }
117
118 if wal_exists {
119 let wal_path = self.config.wal_path().clone();
120 let wal_result = tokio::task::spawn_blocking(move || WalFile::open(&wal_path))
121 .await
122 .ok()
123 .and_then(|r| r.ok());
124 if let Some(w) = wal_result {
125 let ps = if db_exists {
126 read_page_size_from_db_async(self.config.db_path())
127 .await
128 .unwrap_or_else(|_| {
129 tracing::warn!("failed to read page size from DB, using WAL page size");
130 w.page_size()
131 })
132 } else {
133 w.page_size()
134 };
135 return (w.header().salt_1, w.header().salt_2, ps);
136 }
137 }
138
139 if db_exists {
140 let db_page_size = read_page_size_from_db_async(self.config.db_path())
141 .await
142 .unwrap_or_else(|e| {
143 tracing::warn!("failed to read page size from DB: {e}");
144 0
145 });
146 let ps = if db_page_size > 0 { db_page_size } else { 4096 };
147 tracing::warn!("WAL file not found, using zero salts with page size {ps}");
148 return (0, 0, ps);
149 }
150
151 (0, 0, 4096)
152 }
153
154 pub async fn restore(&self) -> Result<Arc<Mutex<Manifest>>> {
155 let start = std::time::Instant::now();
156 let manifest_with_etag = self.bucket.get_with_etag(MANIFEST_KEY).await?;
157
158 let (mut manifest, from_bucket) = match manifest_with_etag {
159 Some((data, etag)) => {
160 let mut m = Manifest::deserialize(&data)?;
161 m.etag = Some(etag);
162 (m, true)
163 }
164 None => {
165 let (salt_1, salt_2, page_size) = self.detect_local_salts().await;
166 (Manifest::new(salt_1, salt_2, page_size), false)
167 }
168 };
169
170 if from_bucket {
171 let local_exists = match tokio::fs::try_exists(self.config.db_path()).await {
172 Ok(exists) => exists,
173 Err(e) => {
174 tracing::warn!("failed to check DB existence for restore: {e}");
175 false
176 }
177 };
178 let local_newer = local_exists && self.local_is_newer_than_manifest(&manifest).await;
179
180 let local_newer = if local_newer && (manifest.snapshot.is_some() || manifest.shipped_frames > 0) {
185 match self.is_db_empty().await {
186 Ok(true) => {
187 tracing::warn!(
188 "Local DB is empty but generation file says it was synced (gen {}). \
189 Restoring from bucket instead — the generation file may be stale.",
190 manifest.generation
191 );
192 false
193 }
194 Ok(false) => true,
195 Err(e) => {
196 tracing::warn!(
197 "Failed to check if local DB is empty: {e} — assuming not empty"
198 );
199 true
200 }
201 }
202 } else {
203 local_newer
204 };
205
206 match self.config.restore_behavior() {
207 crate::config::RestoreBehavior::UploadLocalIfNewer => {
208 if local_newer {
209 self.upload_local_as_snapshot(&mut manifest).await?;
210 } else {
211 self.download_and_reconstruct(&manifest).await?;
212 }
213 }
214 crate::config::RestoreBehavior::AlwaysRestoreFromBucket
215 | crate::config::RestoreBehavior::Recoverable => {
216 self.download_and_reconstruct(&manifest).await?;
217 }
218 crate::config::RestoreBehavior::ErrorIfConflict => {
219 if local_exists && local_newer {
220 return Err(Error::Restore(
221 "Local database is newer than bucket manifest. \
222 Set restore_behavior to UploadLocalIfNewer or AlwaysRestoreFromBucket \
223 to resolve."
224 .to_string(),
225 ));
226 }
227 self.download_and_reconstruct(&manifest).await?;
228 }
229 }
230 }
231
232 if from_bucket {
233 let elapsed = start.elapsed();
234 if let Some(ref metrics) = self.metrics {
235 metrics.restore_completed(elapsed.as_millis() as u64);
236 }
237 write_generation(self.config.db_path(), manifest.generation).await?;
240 }
241
242 Ok(Arc::new(Mutex::new(manifest)))
243 }
244
245 pub async fn local_is_newer_than_manifest(&self, manifest: &Manifest) -> bool {
246 if manifest.generation == 0 && manifest.snapshot.is_none() {
248 return true;
249 }
250
251 let local_exists = match tokio::fs::try_exists(self.config.db_path()).await {
252 Ok(exists) => exists,
253 Err(e) => {
254 tracing::warn!("failed to check DB existence for local_is_newer: {e}");
255 false
256 }
257 };
258 if !local_exists {
259 return false;
260 }
261
262 let local_gen = read_generation(self.config.db_path()).await.unwrap_or(None);
266 match local_gen {
267 Some(gen) => gen > manifest.generation,
268 None => {
269 let has_snapshot = manifest.snapshot.is_some();
270 if has_snapshot {
271 tracing::warn!(
275 "No generation file found but bucket has snapshot (gen {}) — assuming bucket is authoritative. \
276 Use `--force-takeover` or delete bucket data to upload local instead.",
277 manifest.generation
278 );
279 false
280 } else {
281 tracing::debug!(
284 "No generation file and no snapshot — assuming local DB is newer"
285 );
286 true
287 }
288 }
289 }
290 }
291
292 pub async fn is_db_empty(&self) -> Result<bool> {
296 let db_path = self.config.db_path().to_path_buf();
297 let is_empty = tokio::task::spawn_blocking(move || {
298 let conn = rusqlite::Connection::open_with_flags(
299 &db_path,
300 rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
301 )?;
302 let count: i64 = conn.query_row(
303 "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
304 [],
305 |row| row.get(0),
306 )?;
307 Ok::<bool, crate::error::Error>(count == 0)
308 })
309 .await
310 .map_err(|e| crate::error::Error::Other(format!("is_db_empty join: {e}")))??;
311 Ok(is_empty)
312 }
313
314 async fn upload_local_as_snapshot(&self, manifest: &mut Manifest) -> Result<()> {
315 let snapshot_path = format!(
316 "snapshots/{}.db",
317 chrono::Utc::now().format("%Y%m%d-%H%M%S%.6f")
318 );
319
320 let (local_bytes, page_size, salt_1, salt_2) = {
321 let db_path = self.config.db_path().clone();
322 let wal_path = self.config.wal_path().clone();
323 tokio::task::spawn_blocking(move || {
324 let (s1, s2) = match WalFile::open(&wal_path) {
325 Ok(w) => (w.header().salt_1, w.header().salt_2),
326 Err(_) => {
327 tracing::warn!(
328 "Cannot read WAL file for snapshot upload — using zero salts. \
329 The WAL may have been truncated by a concurrent checkpoint."
330 );
331 (0u32, 0u32)
332 }
333 };
334 let conn = rusqlite::Connection::open(&db_path)?;
335 conn.execute_batch("PRAGMA journal_mode = WAL")?;
336 conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?;
337 drop(conn);
338 let bytes = std::fs::read(&db_path)?;
339 let ps = read_page_size_from_db(&bytes)?;
340 Ok::<_, crate::error::Error>((bytes, ps, s1, s2))
341 })
342 .await??
343 };
344
345 let checksum = crate::util::compute_sha256(&local_bytes);
346
347 self.bucket
348 .put(&snapshot_path, Bytes::from(local_bytes))
349 .await?;
350
351 let db_size = tokio::fs::metadata(self.config.db_path())
352 .await
353 .map(|m| m.len())
354 .unwrap_or(0);
355
356 manifest.update_snapshot(snapshot_path, checksum, salt_1, salt_2, page_size, db_size);
357
358 let manifest_bytes = manifest.serialize()?;
361 match manifest.etag.clone() {
362 Some(etag) => {
363 self.bucket
364 .put_if_match(MANIFEST_KEY, Bytes::from(manifest_bytes), &etag)
365 .await?;
366 }
367 None => {
368 self.bucket
372 .put_if_not_exists(MANIFEST_KEY, Bytes::from(manifest_bytes))
373 .await?;
374 }
375 }
376
377 write_generation(self.config.db_path(), manifest.generation).await?;
380
381 Ok(())
382 }
383
384 async fn download_and_reconstruct(&self, manifest: &Manifest) -> Result<()> {
385 let db_path = self.config.db_path();
389 let marker_path = db_path.with_extension("db.restore-in-progress");
390 if tokio::fs::try_exists(&marker_path).await.unwrap_or(false) {
391 tracing::warn!(
392 "Found stale restore marker — previous restore may have crashed mid-rename. \
393 Cleaning up."
394 );
395 let wal_tmp = db_path.with_extension("wal.restore-tmp");
396 let db_tmp = db_path.with_extension("db.restore-tmp");
397 tokio::fs::remove_file(&wal_tmp).await.ok();
398 tokio::fs::remove_file(&db_tmp).await.ok();
399 tokio::fs::remove_file(&marker_path).await.ok();
400 }
401
402 if let Some(ref snapshot_key) = manifest.snapshot {
403 let tmp_path = self.config.db_path().with_extension("db.restore-tmp");
404 let tmp_path_for_cleanup = tmp_path.clone();
405
406 let result = self
407 .download_and_reconstruct_inner(manifest, snapshot_key, &tmp_path)
408 .await;
409 if result.is_err() {
410 tokio::fs::remove_file(&tmp_path_for_cleanup).await.ok();
411 let wal_tmp = self.config.wal_path().with_extension("wal.restore-tmp");
413 tokio::fs::remove_file(&wal_tmp).await.ok();
414 }
415 result
416 } else {
417 Err(Error::Restore(
418 "No snapshot found in bucket. Cannot restore without a base database.".to_string(),
419 ))
420 }
421 }
422
423 async fn download_and_reconstruct_inner(
424 &self,
425 manifest: &Manifest,
426 snapshot_key: &str,
427 tmp_path: &std::path::Path,
428 ) -> Result<()> {
429 let tmp_path_owned = tmp_path.to_path_buf();
430
431 self.bucket.get_file(snapshot_key, &tmp_path_owned).await?;
432
433 let (snapshot_page_size, checksum) = tokio::task::spawn_blocking({
434 let tmp_path = tmp_path_owned.clone();
435 move || {
436 let mut file = std::fs::File::open(&tmp_path)?;
437 let mut header = [0u8; 20];
438 std::io::Read::read_exact(&mut file, &mut header)?;
439 let page_size = read_page_size_from_db(&header)?;
440 drop(file);
441 let checksum = crate::util::compute_sha256_file(&tmp_path)?;
442 Ok::<_, crate::error::Error>((page_size, checksum))
443 }
444 })
445 .await??;
446
447 if let Some(ref expected_checksum) = manifest.snapshot_checksum {
448 if &checksum != expected_checksum {
449 let detail = format!(
450 "Snapshot checksum mismatch: expected {}, got {}",
451 expected_checksum, checksum
452 );
453 match self.config.restore_behavior {
454 crate::config::RestoreBehavior::Recoverable => {
455 tracing::warn!("{} — proceeding anyway (Recoverable mode)", detail);
456 if let Some(m) = self.metrics.as_ref() {
457 m.checksum_warning(&detail)
458 }
459 }
460 _ => {
461 return Err(Error::Restore(detail));
462 }
463 }
464 }
465 }
466
467 let page_size = snapshot_page_size;
471
472 let wal_tmp_path = self.config.wal_path().with_extension("wal.restore-tmp");
473
474 if manifest.shipped_frames > 0 {
475 self.download_wal_segments_to(manifest, page_size, &wal_tmp_path)
476 .await?;
477 } else {
478 use tokio::io::AsyncWriteExt;
480 let mut f = tokio::fs::File::create(&wal_tmp_path).await?;
481 f.flush().await?;
482 f.sync_all().await?;
483 }
484
485 let db_path = self.config.db_path();
495 let wal_path = self.config.wal_path();
496 let marker_path = db_path.with_extension("db.restore-in-progress");
497 let marker_body = format!("wal:{}", wal_tmp_path.display());
498
499 tokio::fs::write(&marker_path, &marker_body).await?;
501
502 tokio::fs::rename(&tmp_path_owned, db_path).await?;
504
505 tokio::fs::rename(&wal_tmp_path, wal_path).await?;
507
508 tokio::fs::remove_file(&marker_path).await?;
510
511 Ok(())
512 }
513
514 async fn download_wal_segments_to(
515 &self,
516 manifest: &Manifest,
517 page_size: u32,
518 tmp_wal_path: &std::path::Path,
519 ) -> Result<()> {
520 let prefix = manifest.segment_prefix();
521 let all_keys = self.bucket.list(&prefix).await?;
522
523 let mut l1_keys: Vec<String> = all_keys
525 .iter()
526 .filter(|k| k.ends_with(".l1"))
527 .cloned()
528 .collect();
529 let mut l0_keys: Vec<String> = all_keys
530 .iter()
531 .filter(|k| k.ends_with(".segment"))
532 .cloned()
533 .collect();
534
535 l1_keys.sort();
536 l0_keys.sort();
537
538 let l1_max = manifest.l1_max_frame_value();
540 let uncovered_l0_keys: Vec<String> = l0_keys
541 .into_iter()
542 .filter(|k| {
543 match extract_start_frame_from_key(k) {
551 Some(start) => start >= l1_max,
552 None => true, }
554 })
555 .collect();
556
557 if l1_keys.is_empty() && uncovered_l0_keys.is_empty() {
558 let wal_header =
561 WalHeader::synthetic(page_size, manifest.current_salt_1, manifest.current_salt_2);
562 let wal_header_data = serialize_header(&wal_header);
563 use tokio::io::AsyncWriteExt;
564 let mut file = tokio::fs::File::create(tmp_wal_path).await?;
565 file.write_all(&wal_header_data).await?;
566 file.flush().await?;
567 file.sync_all().await?;
568 return Ok(());
569 }
570
571 let wal_header_data = match self.read_wal_header_if_exists().await {
572 Some(header) => serialize_header(&header),
573 None => {
574 let header = WalHeader::synthetic(
575 page_size,
576 manifest.current_salt_1,
577 manifest.current_salt_2,
578 );
579 serialize_header(&header)
580 }
581 };
582
583 let mut file = tokio::fs::File::create(tmp_wal_path).await?;
584 use tokio::io::AsyncWriteExt;
585 file.write_all(&wal_header_data).await?;
586
587 for key in &l1_keys {
589 let data = self
590 .bucket
591 .get(key)
592 .await?
593 .ok_or_else(|| Error::Restore(format!("L1 file not found: {key}")))?;
594 if let Some(l1) = manifest.l1_files.iter().find(|l| &l.key == key) {
596 if let Some(ref expected) = l1.checksum {
597 let actual = crate::util::compute_sha256(&data);
598 if &actual != expected {
599 return Err(Error::Restore(format!(
600 "L1 file {key} checksum mismatch: expected {expected}, got {actual}"
601 )));
602 }
603 }
604 }
605 file.write_all(&data).await?;
606 }
607
608 for key in &uncovered_l0_keys {
610 let segment_data = self
611 .bucket
612 .get(key)
613 .await?
614 .ok_or_else(|| Error::Restore(format!("Segment not found: {key}")))?;
615 if let Some(expected) = manifest.segment_checksums.get(key) {
617 let actual = crate::util::compute_sha256(&segment_data);
618 if &actual != expected {
619 return Err(Error::Restore(format!(
620 "Segment {key} checksum mismatch: expected {expected}, got {actual}"
621 )));
622 }
623 } else {
624 tracing::debug!(
625 "No checksum in manifest for segment {key} — skipping verification"
626 );
627 }
628 file.write_all(&segment_data).await?;
629 }
630
631 file.flush().await?;
632 file.sync_all().await?; drop(file);
634
635 Ok(())
636 }
637
638 async fn read_wal_header_if_exists(&self) -> Option<crate::wal::WalHeader> {
639 let path = self.config.wal_path().clone();
640 tokio::task::spawn_blocking(move || {
641 if !path.exists() {
642 return None;
643 }
644 match crate::wal::WalFile::open(&path) {
645 Ok(w) => Some(w.header().clone()),
646 Err(_) => None,
647 }
648 })
649 .await
650 .ok()
651 .flatten()
652 }
653}
654
655fn serialize_header(header: &WalHeader) -> Vec<u8> {
656 let mut buf = Vec::with_capacity(32);
657 buf.extend_from_slice(&header.magic.to_be_bytes());
658 buf.extend_from_slice(&header.file_format.to_be_bytes());
659 buf.extend_from_slice(&header.page_size.to_be_bytes());
660 buf.extend_from_slice(&header.checkpoint_seq.to_be_bytes());
661 buf.extend_from_slice(&header.salt_1.to_be_bytes());
662 buf.extend_from_slice(&header.salt_2.to_be_bytes());
663 buf.extend_from_slice(&header.checksum_1.to_be_bytes());
664 buf.extend_from_slice(&header.checksum_2.to_be_bytes());
665 buf
666}
667
668pub fn read_page_size_from_db(data: &[u8]) -> Result<u32> {
669 if data.len() < 20 {
670 return Err(Error::Restore(
671 "snapshot too small to read page size".to_string(),
672 ));
673 }
674 let page_size = u16::from_be_bytes([data[16], data[17]]);
675 let page_size = if page_size == 1 {
676 65536
677 } else {
678 page_size as u32
679 };
680 Ok(page_size)
681}
682
683pub async fn read_page_size_from_db_async(path: &std::path::Path) -> Result<u32> {
684 let mut file = tokio::fs::File::open(path).await?;
685 let mut buf = [0u8; 20];
686 tokio::io::AsyncReadExt::read_exact(&mut file, &mut buf).await?;
687 drop(file);
688 read_page_size_from_db(&buf)
689}
690
691fn extract_start_frame_from_key(key: &str) -> Option<u32> {
694 let segments: Vec<&str> = key.rsplitn(2, '/').collect();
695 if segments.len() < 2 {
696 return None;
697 }
698 let filename = segments[0];
699 filename.split('-').next().and_then(|s| {
700 s.strip_suffix(".segment")
701 .or_else(|| s.strip_suffix(".l1"))
702 .unwrap_or(s)
703 .parse::<u32>()
704 .ok()
705 })
706}