Skip to main content

allsource_core/infrastructure/persistence/
wal.rs

1use crate::{
2    domain::entities::Event,
3    error::{AllSourceError, Result},
4};
5use chrono::{DateTime, Utc};
6use parking_lot::RwLock;
7use serde::{Deserialize, Serialize};
8use std::{
9    fs::{self, File, OpenOptions},
10    io::{BufRead, BufReader, BufWriter, Write},
11    path::{Path, PathBuf},
12    sync::Arc,
13};
14
15/// Write-Ahead Log for durability and crash recovery
16pub struct WriteAheadLog {
17    /// Directory where WAL files are stored
18    wal_dir: PathBuf,
19
20    /// Current active WAL file
21    current_file: Arc<RwLock<WALFile>>,
22
23    /// Configuration
24    config: WALConfig,
25
26    /// Statistics
27    stats: Arc<RwLock<WALStats>>,
28
29    /// Current sequence number
30    sequence: Arc<RwLock<u64>>,
31
32    /// Optional broadcast channel for replication โ€” when set, each WAL append
33    /// publishes the entry so the WAL shipper can stream it to followers.
34    /// Wrapped in Mutex so it can be set at runtime (e.g. during follower โ†’ leader promotion).
35    replication_tx: parking_lot::Mutex<Option<tokio::sync::broadcast::Sender<WALEntry>>>,
36}
37
38#[derive(Debug, Clone)]
39pub struct WALConfig {
40    /// Maximum size of a single WAL file before rotation (in bytes)
41    pub max_file_size: usize,
42
43    /// Whether to sync to disk after each write (fsync)
44    pub sync_on_write: bool,
45
46    /// Maximum number of WAL files to keep
47    pub max_wal_files: usize,
48
49    /// Enable WAL compression
50    pub compress: bool,
51
52    /// Interval in milliseconds for background coalesced fsync.
53    /// When set, a background task calls `flush() + sync_all()` every N ms,
54    /// giving near-zero write latency with bounded data loss window.
55    /// When `Some`, `sync_on_write` is forced to `false` to prevent double-fsync.
56    pub fsync_interval_ms: Option<u64>,
57}
58
59impl Default for WALConfig {
60    fn default() -> Self {
61        Self {
62            max_file_size: 64 * 1024 * 1024, // 64 MB
63            sync_on_write: true,
64            max_wal_files: 10,
65            compress: false,
66            fsync_interval_ms: None,
67        }
68    }
69}
70
71#[derive(Debug, Clone, Default, Serialize)]
72pub struct WALStats {
73    pub total_entries: u64,
74    pub total_bytes_written: u64,
75    pub current_file_size: usize,
76    pub files_rotated: u64,
77    pub files_cleaned: u64,
78    pub recovery_count: u64,
79}
80
81/// WAL entry wrapping an event
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct WALEntry {
84    /// Sequence number for ordering
85    pub sequence: u64,
86
87    /// Timestamp when written to WAL
88    pub wal_timestamp: DateTime<Utc>,
89
90    /// The event being logged
91    pub event: Event,
92
93    /// Checksum for integrity verification
94    pub checksum: u32,
95}
96
97impl WALEntry {
98    pub fn new(sequence: u64, event: Event) -> Self {
99        let mut entry = Self {
100            sequence,
101            wal_timestamp: Utc::now(),
102            event,
103            checksum: 0,
104        };
105        entry.checksum = entry.calculate_checksum();
106        entry
107    }
108
109    fn calculate_checksum(&self) -> u32 {
110        // Simple CRC32 checksum
111        let data = format!("{}{}{}", self.sequence, self.wal_timestamp, self.event.id);
112        crc32fast::hash(data.as_bytes())
113    }
114
115    pub fn verify(&self) -> bool {
116        self.checksum == self.calculate_checksum()
117    }
118}
119
120/// Represents an active WAL file
121struct WALFile {
122    path: PathBuf,
123    writer: BufWriter<File>,
124    size: usize,
125    created_at: DateTime<Utc>,
126}
127
128impl WALFile {
129    fn new(path: PathBuf) -> Result<Self> {
130        let file = OpenOptions::new()
131            .create(true)
132            .append(true)
133            .open(&path)
134            .map_err(|e| AllSourceError::StorageError(format!("Failed to open WAL file: {e}")))?;
135
136        let size = file.metadata().map(|m| m.len() as usize).unwrap_or(0);
137
138        Ok(Self {
139            path,
140            writer: BufWriter::new(file),
141            size,
142            created_at: Utc::now(),
143        })
144    }
145
146    fn write_entry(&mut self, entry: &WALEntry, sync: bool) -> Result<usize> {
147        // Serialize entry as JSON line
148        let json = serde_json::to_string(entry)?;
149
150        let line = format!("{json}\n");
151        let bytes_written = line.len();
152
153        self.writer
154            .write_all(line.as_bytes())
155            .map_err(|e| AllSourceError::StorageError(format!("Failed to write to WAL: {e}")))?;
156
157        if sync {
158            self.writer
159                .flush()
160                .map_err(|e| AllSourceError::StorageError(format!("Failed to flush WAL: {e}")))?;
161
162            self.writer
163                .get_ref()
164                .sync_all()
165                .map_err(|e| AllSourceError::StorageError(format!("Failed to sync WAL: {e}")))?;
166        }
167
168        self.size += bytes_written;
169        Ok(bytes_written)
170    }
171
172    fn flush(&mut self) -> Result<()> {
173        self.writer
174            .flush()
175            .map_err(|e| AllSourceError::StorageError(format!("Failed to flush WAL: {e}")))?;
176        Ok(())
177    }
178}
179
180impl WriteAheadLog {
181    /// Create a new WAL
182    pub fn new(wal_dir: impl Into<PathBuf>, config: WALConfig) -> Result<Self> {
183        let wal_dir = wal_dir.into();
184
185        // Create WAL directory if it doesn't exist
186        fs::create_dir_all(&wal_dir).map_err(|e| {
187            AllSourceError::StorageError(format!("Failed to create WAL directory: {e}"))
188        })?;
189
190        // Create initial WAL file
191        let initial_file_path = Self::generate_wal_filename(&wal_dir, 0);
192        let current_file = WALFile::new(initial_file_path)?;
193
194        tracing::info!("โœ… WAL initialized at: {}", wal_dir.display());
195
196        Ok(Self {
197            wal_dir,
198            current_file: Arc::new(RwLock::new(current_file)),
199            config,
200            stats: Arc::new(RwLock::new(WALStats::default())),
201            sequence: Arc::new(RwLock::new(0)),
202            replication_tx: parking_lot::Mutex::new(None),
203        })
204    }
205
206    /// Generate a WAL filename based on sequence
207    fn generate_wal_filename(dir: &Path, sequence: u64) -> PathBuf {
208        dir.join(format!("wal-{sequence:016x}.log"))
209    }
210
211    /// Write an event to the WAL
212    #[cfg_attr(feature = "hotpath", hotpath::measure)]
213    pub fn append(&self, event: Event) -> Result<u64> {
214        // Get next sequence number
215        let mut seq = self.sequence.write();
216        *seq += 1;
217        let sequence = *seq;
218        drop(seq);
219
220        // Create WAL entry
221        let entry = WALEntry::new(sequence, event);
222
223        // Write to current file
224        let mut current = self.current_file.write();
225        let bytes_written = current.write_entry(&entry, self.config.sync_on_write)?;
226
227        // Update statistics
228        let mut stats = self.stats.write();
229        stats.total_entries += 1;
230        stats.total_bytes_written += bytes_written as u64;
231        stats.current_file_size = current.size;
232        drop(stats);
233
234        // Broadcast to replication channel (if enabled).
235        // Errors are ignored: no receivers simply means no followers are connected.
236        if let Some(ref tx) = *self.replication_tx.lock() {
237            let _ = tx.send(entry);
238        }
239
240        // Check if we need to rotate
241        let should_rotate = current.size >= self.config.max_file_size;
242        drop(current);
243
244        if should_rotate {
245            self.rotate()?;
246        }
247
248        tracing::trace!("WAL entry written: sequence={}", sequence);
249
250        Ok(sequence)
251    }
252
253    /// Rotate to a new WAL file
254    #[cfg_attr(feature = "hotpath", hotpath::measure)]
255    fn rotate(&self) -> Result<()> {
256        let seq = *self.sequence.read();
257        let new_file_path = Self::generate_wal_filename(&self.wal_dir, seq);
258
259        tracing::info!("๐Ÿ”„ Rotating WAL to new file: {:?}", new_file_path);
260
261        let new_file = WALFile::new(new_file_path)?;
262
263        let mut current = self.current_file.write();
264        current.flush()?;
265        *current = new_file;
266
267        let mut stats = self.stats.write();
268        stats.files_rotated += 1;
269        stats.current_file_size = 0;
270        drop(stats);
271
272        // Clean up old WAL files
273        self.cleanup_old_files()?;
274
275        Ok(())
276    }
277
278    /// Clean up old WAL files beyond the retention limit
279    #[cfg_attr(feature = "hotpath", hotpath::measure)]
280    fn cleanup_old_files(&self) -> Result<()> {
281        let mut wal_files = self.list_wal_files()?;
282        wal_files.sort();
283
284        if wal_files.len() > self.config.max_wal_files {
285            let to_remove = wal_files.len() - self.config.max_wal_files;
286            let files_to_delete = &wal_files[..to_remove];
287
288            for file_path in files_to_delete {
289                if let Err(e) = fs::remove_file(file_path) {
290                    tracing::warn!("Failed to remove old WAL file {:?}: {}", file_path, e);
291                } else {
292                    tracing::debug!("๐Ÿ—‘๏ธ Removed old WAL file: {:?}", file_path);
293                    let mut stats = self.stats.write();
294                    stats.files_cleaned += 1;
295                }
296            }
297        }
298
299        Ok(())
300    }
301
302    /// List all WAL files in the directory
303    fn list_wal_files(&self) -> Result<Vec<PathBuf>> {
304        let entries = fs::read_dir(&self.wal_dir).map_err(|e| {
305            AllSourceError::StorageError(format!("Failed to read WAL directory: {e}"))
306        })?;
307
308        let mut wal_files = Vec::new();
309        for entry in entries {
310            let entry = entry.map_err(|e| {
311                AllSourceError::StorageError(format!("Failed to read directory entry: {e}"))
312            })?;
313
314            let path = entry.path();
315            if let Some(name) = path.file_name()
316                && name.to_string_lossy().starts_with("wal-")
317                && name.to_string_lossy().ends_with(".log")
318            {
319                wal_files.push(path);
320            }
321        }
322
323        Ok(wal_files)
324    }
325
326    /// Recover events from WAL files
327    #[cfg_attr(feature = "hotpath", hotpath::measure)]
328    pub fn recover(&self) -> Result<Vec<Event>> {
329        tracing::info!("๐Ÿ”„ Starting WAL recovery...");
330
331        let mut wal_files = self.list_wal_files()?;
332        wal_files.sort();
333
334        let mut recovered_events = Vec::new();
335        let mut max_sequence = 0u64;
336        let mut corrupted_entries = 0;
337
338        for wal_file_path in &wal_files {
339            tracing::debug!("Reading WAL file: {:?}", wal_file_path);
340
341            let file = File::open(wal_file_path).map_err(|e| {
342                AllSourceError::StorageError(format!("Failed to open WAL file for recovery: {e}"))
343            })?;
344
345            let reader = BufReader::new(file);
346
347            for (line_num, line) in reader.lines().enumerate() {
348                let line = line.map_err(|e| {
349                    AllSourceError::StorageError(format!("Failed to read WAL line: {e}"))
350                })?;
351
352                if line.trim().is_empty() {
353                    continue;
354                }
355
356                match serde_json::from_str::<WALEntry>(&line) {
357                    Ok(entry) => {
358                        // Verify checksum
359                        if !entry.verify() {
360                            tracing::warn!(
361                                "Corrupted WAL entry at {:?}:{} (checksum mismatch)",
362                                wal_file_path,
363                                line_num + 1
364                            );
365                            corrupted_entries += 1;
366                            continue;
367                        }
368
369                        max_sequence = max_sequence.max(entry.sequence);
370                        recovered_events.push(entry.event);
371                    }
372                    Err(e) => {
373                        tracing::warn!(
374                            "Failed to parse WAL entry at {:?}:{}: {}",
375                            wal_file_path,
376                            line_num + 1,
377                            e
378                        );
379                        corrupted_entries += 1;
380                    }
381                }
382            }
383        }
384
385        // Update sequence counter
386        let mut seq = self.sequence.write();
387        *seq = max_sequence;
388        drop(seq);
389
390        // Update stats
391        let mut stats = self.stats.write();
392        stats.recovery_count += 1;
393        drop(stats);
394
395        tracing::info!(
396            "โœ… WAL recovery complete: {} events recovered, {} corrupted entries",
397            recovered_events.len(),
398            corrupted_entries
399        );
400
401        Ok(recovered_events)
402    }
403
404    /// Manually flush the current WAL file
405    #[cfg_attr(feature = "hotpath", hotpath::measure)]
406    pub fn flush(&self) -> Result<()> {
407        let mut current = self.current_file.write();
408        current.flush()?;
409        Ok(())
410    }
411
412    /// Flush the BufWriter and fsync the current WAL file to disk.
413    ///
414    /// Called by the background interval-based fsync task. Acquires the write
415    /// lock, flushes buffered data, then issues `sync_all()` to ensure the
416    /// OS has persisted the data to durable storage.
417    #[cfg_attr(feature = "hotpath", hotpath::measure)]
418    pub fn sync(&self) -> Result<()> {
419        let mut current = self.current_file.write();
420        current
421            .writer
422            .flush()
423            .map_err(|e| AllSourceError::StorageError(format!("Failed to flush WAL: {e}")))?;
424        current
425            .writer
426            .get_ref()
427            .sync_all()
428            .map_err(|e| AllSourceError::StorageError(format!("Failed to sync WAL: {e}")))?;
429        Ok(())
430    }
431
432    /// Get the configured fsync interval (if any).
433    pub fn fsync_interval_ms(&self) -> Option<u64> {
434        self.config.fsync_interval_ms
435    }
436
437    /// Truncate WAL after successful checkpoint
438    #[cfg_attr(feature = "hotpath", hotpath::measure)]
439    pub fn truncate(&self) -> Result<()> {
440        tracing::info!("๐Ÿงน Truncating WAL after checkpoint");
441
442        // Close current file
443        let mut current = self.current_file.write();
444        current.flush()?;
445
446        // Remove all WAL files
447        let wal_files = self.list_wal_files()?;
448        for file_path in wal_files {
449            fs::remove_file(&file_path).map_err(|e| {
450                AllSourceError::StorageError(format!("Failed to remove WAL file: {e}"))
451            })?;
452            tracing::debug!("Removed WAL file: {:?}", file_path);
453        }
454
455        // Create new WAL file
456        let new_file_path = Self::generate_wal_filename(&self.wal_dir, 0);
457        *current = WALFile::new(new_file_path)?;
458
459        // Reset sequence
460        let mut seq = self.sequence.write();
461        *seq = 0;
462
463        tracing::info!("โœ… WAL truncated successfully");
464
465        Ok(())
466    }
467
468    /// Get WAL statistics
469    pub fn stats(&self) -> WALStats {
470        (*self.stats.read()).clone()
471    }
472
473    /// Get current sequence number
474    pub fn current_sequence(&self) -> u64 {
475        *self.sequence.read()
476    }
477
478    /// Get the oldest available WAL sequence number.
479    ///
480    /// Returns the first sequence found in the oldest WAL file, or `None`
481    /// if no WAL entries exist. Used by the replication catch-up protocol
482    /// to determine whether a follower can catch up from WAL alone.
483    pub fn oldest_sequence(&self) -> Option<u64> {
484        let Ok(mut wal_files) = self.list_wal_files() else {
485            return None;
486        };
487
488        if wal_files.is_empty() {
489            return None;
490        }
491
492        wal_files.sort();
493
494        // Read the first entry from the oldest WAL file
495        for wal_file_path in &wal_files {
496            let Ok(file) = File::open(wal_file_path) else {
497                continue;
498            };
499            let reader = BufReader::new(file);
500            for line in reader.lines() {
501                let Ok(line) = line else {
502                    continue;
503                };
504                if line.trim().is_empty() {
505                    continue;
506                }
507                if let Ok(entry) = serde_json::from_str::<WALEntry>(&line) {
508                    return Some(entry.sequence);
509                }
510            }
511        }
512
513        None
514    }
515
516    /// Attach a broadcast sender for WAL replication.
517    ///
518    /// When set, every `append()` call will publish the WAL entry to this
519    /// channel so the WAL shipper can stream it to connected followers.
520    pub fn set_replication_tx(&self, tx: tokio::sync::broadcast::Sender<WALEntry>) {
521        *self.replication_tx.lock() = Some(tx);
522    }
523}
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528    use serde_json::json;
529    use tempfile::TempDir;
530    use uuid::Uuid;
531
532    fn create_test_event() -> Event {
533        Event::reconstruct_from_strings(
534            Uuid::new_v4(),
535            "test.event".to_string(),
536            "test-entity".to_string(),
537            "default".to_string(),
538            json!({"test": "data"}),
539            Utc::now(),
540            None,
541            1,
542        )
543    }
544
545    #[test]
546    fn test_wal_creation() {
547        let temp_dir = TempDir::new().unwrap();
548        let wal = WriteAheadLog::new(temp_dir.path(), WALConfig::default());
549        assert!(wal.is_ok());
550    }
551
552    #[test]
553    fn test_wal_append() {
554        let temp_dir = TempDir::new().unwrap();
555        let wal = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
556
557        let event = create_test_event();
558        let seq = wal.append(event);
559        assert!(seq.is_ok());
560        assert_eq!(seq.unwrap(), 1);
561
562        let stats = wal.stats();
563        assert_eq!(stats.total_entries, 1);
564    }
565
566    #[test]
567    fn test_wal_recovery() {
568        let temp_dir = TempDir::new().unwrap();
569        let wal = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
570
571        // Write some events
572        for _ in 0..5 {
573            wal.append(create_test_event()).unwrap();
574        }
575
576        wal.flush().unwrap();
577
578        // Create new WAL instance (simulating restart)
579        let wal2 = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
580        let recovered = wal2.recover().unwrap();
581
582        assert_eq!(recovered.len(), 5);
583    }
584
585    #[test]
586    fn test_wal_rotation() {
587        let temp_dir = TempDir::new().unwrap();
588        let config = WALConfig {
589            max_file_size: 1024, // Small size to trigger rotation
590            ..Default::default()
591        };
592
593        let wal = WriteAheadLog::new(temp_dir.path(), config).unwrap();
594
595        // Write enough events to trigger rotation
596        for _ in 0..50 {
597            wal.append(create_test_event()).unwrap();
598        }
599
600        let stats = wal.stats();
601        assert!(stats.files_rotated > 0);
602    }
603
604    #[test]
605    fn test_wal_entry_checksum() {
606        let event = create_test_event();
607        let entry = WALEntry::new(1, event);
608
609        assert!(entry.verify());
610
611        // Modify and verify it fails
612        let mut corrupted = entry.clone();
613        corrupted.checksum = 0;
614        assert!(!corrupted.verify());
615    }
616
617    #[test]
618    fn test_wal_fsync_interval_config() {
619        let config = WALConfig {
620            fsync_interval_ms: Some(100),
621            ..Default::default()
622        };
623        assert_eq!(config.fsync_interval_ms, Some(100));
624        // Default should have no interval
625        assert_eq!(WALConfig::default().fsync_interval_ms, None);
626    }
627
628    #[test]
629    fn test_wal_sync_method() {
630        let temp_dir = TempDir::new().unwrap();
631        let config = WALConfig {
632            sync_on_write: false, // Disable per-write sync to test explicit sync
633            ..Default::default()
634        };
635        let wal = WriteAheadLog::new(temp_dir.path(), config).unwrap();
636
637        // Write events without per-write fsync
638        for _ in 0..5 {
639            wal.append(create_test_event()).unwrap();
640        }
641
642        // Explicitly sync โ€” should flush + fsync without error
643        wal.sync().unwrap();
644
645        // Verify data survives by recovering from a new WAL instance
646        let wal2 = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
647        let recovered = wal2.recover().unwrap();
648        assert_eq!(recovered.len(), 5);
649    }
650
651    #[test]
652    fn test_wal_truncate() {
653        let temp_dir = TempDir::new().unwrap();
654        let wal = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
655
656        // Write events
657        for _ in 0..5 {
658            wal.append(create_test_event()).unwrap();
659        }
660
661        // Truncate
662        wal.truncate().unwrap();
663
664        // Verify sequence is reset
665        assert_eq!(wal.current_sequence(), 0);
666
667        // Verify recovery returns empty
668        let recovered = wal.recover().unwrap();
669        assert_eq!(recovered.len(), 0);
670    }
671}