1use super::config::StorageConfig;
9use super::recovery::*;
10use super::stats::StorageStats;
11use super::types::*;
12
13use crate::network::LogEntry;
14use crate::raft::{OxirsNodeId, RdfApp, RdfCommand};
15use crate::shard::ShardId;
16
17use anyhow::{anyhow, Result};
18use async_trait::async_trait;
19use oxirs_core::model::Triple;
20use serde::{Deserialize, Serialize};
21use sha2::{Digest, Sha256};
22use std::fs;
23use std::fs::{File, OpenOptions};
24use std::io::{BufWriter, Write};
25use std::path::{Path, PathBuf};
26use std::sync::Arc;
27use std::time::{SystemTime, UNIX_EPOCH};
28use tokio::sync::RwLock;
29
30#[async_trait]
32pub trait StorageBackend: Send + Sync {
33 async fn create_shard(&self, shard_id: ShardId) -> Result<()>;
35
36 async fn delete_shard(&self, shard_id: ShardId) -> Result<()>;
38
39 async fn insert_triple_to_shard(&self, shard_id: ShardId, triple: Triple) -> Result<()>;
41
42 async fn delete_triple_from_shard(&self, shard_id: ShardId, triple: &Triple) -> Result<()>;
44
45 async fn query_shard(
47 &self,
48 shard_id: ShardId,
49 subject: Option<&str>,
50 predicate: Option<&str>,
51 object: Option<&str>,
52 ) -> Result<Vec<Triple>>;
53
54 async fn get_shard_size(&self, shard_id: ShardId) -> Result<u64>;
56
57 async fn get_shard_triple_count(&self, shard_id: ShardId) -> Result<usize>;
59
60 async fn export_shard(&self, shard_id: ShardId) -> Result<Vec<Triple>>;
62
63 async fn import_shard(&self, shard_id: ShardId, triples: Vec<Triple>) -> Result<()>;
65
66 async fn get_shard_triples(&self, shard_id: ShardId) -> Result<Vec<Triple>>;
68
69 async fn insert_triples_to_shard(&self, shard_id: ShardId, triples: Vec<Triple>) -> Result<()>;
71
72 async fn mark_shard_for_deletion(&self, shard_id: ShardId) -> Result<()>;
74}
75
76pub struct PersistentStorage {
78 pub(crate) data_dir: PathBuf,
80 pub(crate) node_id: OxirsNodeId,
82 pub(crate) raft_state: Arc<RwLock<RaftState>>,
84 pub(crate) app_state: Arc<RwLock<RdfApp>>,
86 pub(crate) config: StorageConfig,
88 pub(crate) wal_sequence: Arc<RwLock<u64>>,
90 pub(crate) wal_writer: Arc<RwLock<Option<BufWriter<File>>>>,
92}
93
94impl PersistentStorage {
95 pub async fn new(node_id: OxirsNodeId, config: StorageConfig) -> Result<Self> {
97 let data_dir = PathBuf::from(&config.data_dir).join(format!("node-{node_id}"));
98
99 if !data_dir.exists() {
100 std::fs::create_dir_all(&data_dir)?;
101 }
102
103 let storage = Self {
104 data_dir,
105 node_id,
106 raft_state: Arc::new(RwLock::new(RaftState::default())),
107 app_state: Arc::new(RwLock::new(RdfApp::default())),
108 config,
109 wal_sequence: Arc::new(RwLock::new(0)),
110 wal_writer: Arc::new(RwLock::new(None)),
111 };
112
113 if storage.config.enable_wal {
114 storage.init_wal().await?;
115 }
116
117 if storage.config.enable_crash_recovery {
118 storage.recover_from_crash().await?;
119 }
120
121 storage.load_state().await?;
122
123 Ok(storage)
124 }
125
126 async fn init_wal(&self) -> Result<()> {
128 let ctx = super::persistent_wal::WalContext {
129 data_dir: &self.data_dir,
130 node_id: self.node_id,
131 config: &self.config,
132 wal_sequence: &self.wal_sequence,
133 wal_writer: &self.wal_writer,
134 };
135 super::persistent_wal::init_wal(ctx).await
136 }
137
138 async fn write_wal_entry(&self, operation: WalOperation) -> Result<()> {
140 super::persistent_wal::write_wal_entry(
141 &self.config,
142 &self.wal_sequence,
143 &self.wal_writer,
144 operation,
145 )
146 .await
147 }
148
149 pub async fn get_current_term(&self) -> u64 {
151 self.raft_state.read().await.current_term
152 }
153
154 pub async fn set_current_term(&self, term: u64) -> Result<()> {
156 {
157 let mut state = self.raft_state.write().await;
158 state.current_term = term;
159 state.voted_for = None;
160 }
161 self.save_state().await
162 }
163
164 pub async fn get_voted_for(&self) -> Option<OxirsNodeId> {
166 self.raft_state.read().await.voted_for
167 }
168
169 pub async fn set_voted_for(&self, candidate_id: Option<OxirsNodeId>) -> Result<()> {
171 {
172 let mut state = self.raft_state.write().await;
173 state.voted_for = candidate_id;
174 }
175 self.save_state().await
176 }
177
178 pub async fn append_entries(&self, entries: Vec<LogEntry>) -> Result<()> {
180 {
181 let mut state = self.raft_state.write().await;
182 state.log.extend(entries);
183 }
184 self.save_state().await
185 }
186
187 pub async fn get_log_entries(&self, start: u64, end: u64) -> Vec<LogEntry> {
189 let state = self.raft_state.read().await;
190 state
191 .log
192 .iter()
193 .filter(|entry| entry.index >= start && entry.index < end)
194 .cloned()
195 .collect()
196 }
197
198 pub async fn get_log_entry(&self, index: u64) -> Option<LogEntry> {
200 let state = self.raft_state.read().await;
201 state.log.iter().find(|entry| entry.index == index).cloned()
202 }
203
204 pub async fn get_last_log_index(&self) -> u64 {
206 let state = self.raft_state.read().await;
207 state.log.last().map(|entry| entry.index).unwrap_or(0)
208 }
209
210 pub async fn get_last_log_term(&self) -> u64 {
212 let state = self.raft_state.read().await;
213 state.log.last().map(|entry| entry.term).unwrap_or(0)
214 }
215
216 pub async fn truncate_log(&self, from_index: u64) -> Result<()> {
218 {
219 let mut state = self.raft_state.write().await;
220 state.log.retain(|entry| entry.index < from_index);
221 }
222 self.save_state().await
223 }
224
225 pub async fn get_commit_index(&self) -> u64 {
227 self.raft_state.read().await.commit_index
228 }
229
230 pub async fn set_commit_index(&self, index: u64) -> Result<()> {
232 {
233 let mut state = self.raft_state.write().await;
234 state.commit_index = index;
235 }
236 self.save_state().await
237 }
238
239 pub async fn get_last_applied(&self) -> u64 {
241 self.raft_state.read().await.last_applied
242 }
243
244 pub async fn set_last_applied(&self, index: u64) -> Result<()> {
246 {
247 let mut state = self.raft_state.write().await;
248 state.last_applied = index;
249 }
250 self.save_state().await
251 }
252
253 pub async fn apply_command(&self, command: &RdfCommand) -> Result<()> {
255 let mut app_state = self.app_state.write().await;
256 app_state.apply_command(command);
257 self.save_app_state().await
258 }
259
260 pub async fn get_app_state(&self) -> RdfApp {
262 self.app_state.read().await.clone()
263 }
264
265 pub async fn create_snapshot(&self) -> Result<SnapshotMetadata> {
267 let raft_state = self.raft_state.read().await;
268 let app_state = self.app_state.read().await;
269
270 let last_log_entry = raft_state.log.last();
271 let snapshot_path = self.data_dir.join("snapshot.json");
272 let snapshot_data = serde_json::to_vec(&*app_state)?;
273 fs::write(&snapshot_path, &snapshot_data)?;
274
275 let mut hasher = Sha256::new();
276 hasher.update(&snapshot_data);
277 let checksum = hex::encode(hasher.finalize());
278
279 let metadata = SnapshotMetadata {
280 last_included_index: last_log_entry.map(|e| e.index).unwrap_or(0),
281 last_included_term: last_log_entry.map(|e| e.term).unwrap_or(0),
282 configuration: vec![self.node_id],
283 timestamp: std::time::SystemTime::now()
284 .duration_since(std::time::UNIX_EPOCH)
285 .expect("SystemTime should be after UNIX_EPOCH")
286 .as_secs(),
287 size: snapshot_data.len() as u64,
288 checksum,
289 };
290
291 let metadata_path = self.data_dir.join("snapshot_metadata.json");
292 let metadata_data = serde_json::to_vec(&metadata)?;
293 fs::write(&metadata_path, &metadata_data)?;
294
295 tracing::info!(
296 "Created snapshot for node {} at index {} with {} bytes",
297 self.node_id,
298 metadata.last_included_index,
299 metadata.size
300 );
301
302 Ok(metadata)
303 }
304
305 pub async fn load_snapshot(&self) -> Result<Option<(SnapshotMetadata, RdfApp)>> {
307 let snapshot_path = self.data_dir.join("snapshot.json");
308 let metadata_path = self.data_dir.join("snapshot_metadata.json");
309
310 if !snapshot_path.exists() || !metadata_path.exists() {
311 return Ok(None);
312 }
313
314 let metadata_data = fs::read(&metadata_path)?;
315 let metadata: SnapshotMetadata = serde_json::from_slice(&metadata_data)?;
316
317 let snapshot_data = fs::read(&snapshot_path)?;
318 let app_state: RdfApp = serde_json::from_slice(&snapshot_data)?;
319
320 Ok(Some((metadata, app_state)))
321 }
322
323 pub async fn compact_log(&self, until_index: u64) -> Result<()> {
325 {
326 let mut state = self.raft_state.write().await;
327 state.log.retain(|entry| entry.index > until_index);
328 }
329 self.save_state().await
330 }
331
332 pub async fn needs_compaction(&self) -> bool {
334 let state = self.raft_state.read().await;
335 state.log.len() > self.config.max_log_entries
336 }
337
338 async fn save_state(&self) -> Result<()> {
340 let state = self.raft_state.read().await;
341
342 if self.config.enable_wal {
343 self.write_wal_entry(WalOperation::WriteRaftState(state.clone()))
344 .await?;
345 }
346
347 self.atomic_write_with_checksum("raft_state.dat", &*state)
348 .await?;
349
350 if self.config.enable_wal {
351 let sequence = *self.wal_sequence.read().await;
352 self.write_wal_entry(WalOperation::Commit(sequence)).await?;
353 }
354
355 Ok(())
356 }
357
358 async fn atomic_write_with_checksum<T>(&self, filename: &str, data: &T) -> Result<()>
360 where
361 T: Serialize,
362 {
363 let path = self.data_dir.join(filename);
364 let temp_path = self.data_dir.join(format!("{filename}.tmp"));
365
366 let checksummed_data = if self.config.enable_corruption_detection {
367 ChecksummedData::new(data)?
368 } else {
369 ChecksummedData {
370 data,
371 checksum: String::new(),
372 timestamp: SystemTime::now()
373 .duration_since(UNIX_EPOCH)
374 .expect("SystemTime should be after UNIX_EPOCH")
375 .as_secs(),
376 }
377 };
378
379 let serialized =
380 oxicode::serde::encode_to_vec(&checksummed_data, oxicode::config::standard())?;
381
382 {
383 let temp_file = OpenOptions::new()
384 .write(true)
385 .create(true)
386 .truncate(true)
387 .open(&temp_path)?;
388
389 let mut writer = BufWriter::new(temp_file);
390 writer.write_all(&serialized)?;
391 writer.flush()?;
392
393 if self.config.sync_writes {
394 writer.get_mut().sync_all()?;
395 }
396 }
397
398 std::fs::rename(&temp_path, &path)?;
399
400 Ok(())
401 }
402
403 async fn load_state(&self) -> Result<()> {
405 let binary_path = self.data_dir.join("raft_state.dat");
406 if binary_path.exists() {
407 match self.load_with_checksum::<RaftState>(&binary_path).await {
408 Ok(state) => {
409 *self.raft_state.write().await = state;
410 tracing::info!("Loaded Raft state (binary) for node {}", self.node_id);
411 }
412 Err(e) => {
413 tracing::error!("Failed to load binary Raft state: {}", e);
414 if self.config.enable_corruption_detection {
415 return Err(anyhow!("Corrupted Raft state file"));
416 }
417 }
418 }
419 } else {
420 let json_path = self.data_dir.join("raft_state.json");
421 if json_path.exists() {
422 let data = std::fs::read(&json_path)?;
423 let state: RaftState = serde_json::from_slice(&data)?;
424 *self.raft_state.write().await = state;
425 tracing::info!("Loaded Raft state (legacy JSON) for node {}", self.node_id);
426 }
427 }
428
429 let app_binary_path = self.data_dir.join("app_state.dat");
430 if app_binary_path.exists() {
431 match self.load_with_checksum::<RdfApp>(&app_binary_path).await {
432 Ok(app_state) => {
433 *self.app_state.write().await = app_state;
434 tracing::info!(
435 "Loaded application state (binary) for node {}",
436 self.node_id
437 );
438 }
439 Err(e) => {
440 tracing::error!("Failed to load binary application state: {}", e);
441 if self.config.enable_corruption_detection {
442 return Err(anyhow!("Corrupted application state file"));
443 }
444 }
445 }
446 } else {
447 let app_json_path = self.data_dir.join("app_state.json");
448 if app_json_path.exists() {
449 let data = std::fs::read(&app_json_path)?;
450 let app_state: RdfApp = serde_json::from_slice(&data)?;
451 *self.app_state.write().await = app_state;
452 tracing::info!(
453 "Loaded application state (legacy JSON) for node {}",
454 self.node_id
455 );
456 }
457 }
458
459 Ok(())
460 }
461
462 async fn load_with_checksum<T>(&self, path: &Path) -> Result<T>
464 where
465 T: for<'de> Deserialize<'de> + Serialize,
466 {
467 let data = std::fs::read(path)?;
468 let (checksummed_data, _): (ChecksummedData<T>, _) =
469 oxicode::serde::decode_from_slice(&data, oxicode::config::standard())?;
470
471 if self.config.enable_corruption_detection && !checksummed_data.verify()? {
472 return Err(anyhow!("Checksum verification failed for {:?}", path));
473 }
474
475 Ok(checksummed_data.data)
476 }
477
478 async fn save_app_state(&self) -> Result<()> {
480 let app_state = self.app_state.read().await;
481
482 if self.config.enable_wal {
483 self.write_wal_entry(WalOperation::WriteAppState(app_state.clone()))
484 .await?;
485 }
486
487 self.atomic_write_with_checksum("app_state.dat", &*app_state)
488 .await?;
489
490 if self.config.enable_wal {
491 let sequence = *self.wal_sequence.read().await;
492 self.write_wal_entry(WalOperation::Commit(sequence)).await?;
493 }
494
495 Ok(())
496 }
497
498 pub async fn get_stats(&self) -> StorageStats {
500 let raft_state = self.raft_state.read().await;
501 let app_state = self.app_state.read().await;
502
503 let data_dir_size = self.calculate_directory_size(&self.data_dir).unwrap_or(0);
504
505 StorageStats {
506 node_id: self.node_id,
507 data_dir: self.data_dir.clone(),
508 log_entries: raft_state.log.len(),
509 current_term: raft_state.current_term,
510 commit_index: raft_state.commit_index,
511 last_applied: raft_state.last_applied,
512 triple_count: app_state.len(),
513 disk_usage_bytes: data_dir_size,
514 }
515 }
516
517 #[allow(clippy::only_used_in_recursion)]
519 fn calculate_directory_size(&self, dir: &Path) -> Result<u64> {
520 let mut size = 0;
521 if dir.is_dir() {
522 for entry in fs::read_dir(dir)? {
523 let entry = entry?;
524 let path = entry.path();
525 if path.is_file() {
526 size += fs::metadata(&path)?.len();
527 } else if path.is_dir() {
528 size += self.calculate_directory_size(&path)?;
529 }
530 }
531 }
532 Ok(size)
533 }
534
535 pub async fn backup(&self) -> Result<PathBuf> {
537 let timestamp = std::time::SystemTime::now()
538 .duration_since(std::time::UNIX_EPOCH)
539 .expect("SystemTime should be after UNIX_EPOCH")
540 .as_secs();
541 let backup_dir = self
542 .data_dir
543 .parent()
544 .expect("data_dir should have a parent directory")
545 .join(format!("backup-{}-{}", self.node_id, timestamp));
546
547 fs::create_dir_all(&backup_dir)?;
548
549 for entry in fs::read_dir(&self.data_dir)? {
550 let entry = entry?;
551 let source = entry.path();
552 let dest = backup_dir.join(entry.file_name());
553 fs::copy(&source, &dest)?;
554 }
555
556 tracing::info!("Created backup at {:?}", backup_dir);
557 Ok(backup_dir)
558 }
559
560 pub async fn rotate_wal(&self) -> Result<()> {
562 super::persistent_wal::rotate_wal(
563 &self.config,
564 &self.data_dir,
565 self.node_id,
566 &self.wal_sequence,
567 &self.wal_writer,
568 )
569 .await
570 }
571
572 pub async fn compact_wal(&self) -> Result<()> {
574 super::persistent_wal::compact_wal(
575 &self.config,
576 &self.data_dir,
577 self.node_id,
578 &self.wal_sequence,
579 &self.wal_writer,
580 )
581 .await
582 }
583
584 pub async fn verify_integrity(&self) -> Result<bool> {
586 super::persistent_integrity::verify_integrity(
587 &self.config,
588 &self.data_dir,
589 &self.raft_state,
590 &self.app_state,
591 )
592 .await
593 }
594
595 pub async fn cleanup_old_backups(&self) -> Result<()> {
597 let parent_dir = self
598 .data_dir
599 .parent()
600 .expect("data_dir should have a parent directory");
601 let backup_prefix = format!("backup-{}-", self.node_id);
602
603 let mut backups = Vec::new();
604 for entry in fs::read_dir(parent_dir)? {
605 let entry = entry?;
606 let name = entry.file_name();
607 if let Some(name_str) = name.to_str() {
608 if name_str.starts_with(&backup_prefix) {
609 backups.push((entry.path(), name_str.to_string()));
610 }
611 }
612 }
613
614 backups.sort_by(|a, b| b.1.cmp(&a.1));
615
616 for (path, _) in backups.iter().skip(self.config.backup_retention) {
617 fs::remove_dir_all(path)?;
618 tracing::info!("Removed old backup: {:?}", path);
619 }
620
621 Ok(())
622 }
623
624 pub async fn recover_from_crash(&self) -> Result<RecoveryReport> {
626 super::persistent_integrity::recover_from_crash(
627 &self.config,
628 &self.data_dir,
629 self.node_id,
630 &self.raft_state,
631 )
632 .await
633 }
634}
635
636#[async_trait]
637impl StorageBackend for PersistentStorage {
638 async fn create_shard(&self, shard_id: ShardId) -> Result<()> {
639 let mut app_state = self.app_state.write().await;
640 app_state.create_shard(shard_id);
641 self.save_app_state().await
642 }
643
644 async fn delete_shard(&self, shard_id: ShardId) -> Result<()> {
645 let mut app_state = self.app_state.write().await;
646 app_state.delete_shard(shard_id);
647 self.save_app_state().await
648 }
649
650 async fn insert_triple_to_shard(&self, shard_id: ShardId, triple: Triple) -> Result<()> {
651 let mut app_state = self.app_state.write().await;
652 app_state.insert_triple_to_shard(shard_id, triple);
653 self.save_app_state().await
654 }
655
656 async fn delete_triple_from_shard(&self, shard_id: ShardId, triple: &Triple) -> Result<()> {
657 let mut app_state = self.app_state.write().await;
658 app_state.delete_triple_from_shard(shard_id, triple);
659 self.save_app_state().await
660 }
661
662 async fn query_shard(
663 &self,
664 shard_id: ShardId,
665 subject: Option<&str>,
666 predicate: Option<&str>,
667 object: Option<&str>,
668 ) -> Result<Vec<Triple>> {
669 let app_state = self.app_state.read().await;
670 Ok(app_state.query_shard(shard_id, subject, predicate, object))
671 }
672
673 async fn get_shard_size(&self, shard_id: ShardId) -> Result<u64> {
674 let app_state = self.app_state.read().await;
675 Ok(app_state.get_shard_size(shard_id))
676 }
677
678 async fn get_shard_triple_count(&self, shard_id: ShardId) -> Result<usize> {
679 let app_state = self.app_state.read().await;
680 Ok(app_state.get_shard_triple_count(shard_id))
681 }
682
683 async fn export_shard(&self, shard_id: ShardId) -> Result<Vec<Triple>> {
684 let app_state = self.app_state.read().await;
685 Ok(app_state.export_shard(shard_id))
686 }
687
688 async fn import_shard(&self, shard_id: ShardId, triples: Vec<Triple>) -> Result<()> {
689 let mut app_state = self.app_state.write().await;
690 app_state.import_shard(shard_id, triples);
691 self.save_app_state().await
692 }
693
694 async fn get_shard_triples(&self, shard_id: ShardId) -> Result<Vec<Triple>> {
695 let app_state = self.app_state.read().await;
696 Ok(app_state.get_shard_triples(shard_id))
697 }
698
699 async fn insert_triples_to_shard(&self, shard_id: ShardId, triples: Vec<Triple>) -> Result<()> {
700 let mut app_state = self.app_state.write().await;
701 app_state.insert_triples_to_shard(shard_id, triples);
702 self.save_app_state().await
703 }
704
705 async fn mark_shard_for_deletion(&self, shard_id: ShardId) -> Result<()> {
706 let mut app_state = self.app_state.write().await;
707 app_state.mark_shard_for_deletion(shard_id);
708 self.save_app_state().await
709 }
710}