allsource-core 0.29.0

High-performance event store core built in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
use crate::{
    domain::entities::Event,
    error::{AllSourceError, Result},
};
use chrono::{DateTime, Utc};
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::{
    collections::HashSet,
    fs::{self, File, OpenOptions},
    io::{BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write},
    path::{Path, PathBuf},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::SystemTime,
};

/// One WAL segment's identity as the filesystem reports it, so a reader can
/// tell whether anything was appended, rotated or truncated without opening it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalSegmentStamp {
    pub path: PathBuf,
    pub len: u64,
    pub modified: Option<SystemTime>,
}

/// A segment as a checkpoint saw it: every entry in its first `len` bytes
/// has a sequence at or below the checkpoint's.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CoveredSegment {
    pub name: String,
    pub len: u64,
}

/// Subdirectory of the WAL dir that holds retired segments containing lines
/// recovery could not read. Nothing lists, replays, or deletes it.
pub const QUARANTINE_DIR: &str = "quarantine";

/// Write-Ahead Log for durability and crash recovery.
///
/// Invariant: a segment is deleted only when every line in it is durable
/// elsewhere. A segment holding a line recovery could not parse or verify is
/// moved to [`QUARANTINE_DIR`] instead, so a format this binary cannot read is
/// never destroyed by it (#287).
pub struct WriteAheadLog {
    /// Directory where WAL files are stored
    wal_dir: PathBuf,

    /// Current active WAL file
    current_file: Arc<RwLock<WALFile>>,

    /// Configuration
    config: WALConfig,

    /// Statistics
    stats: Arc<RwLock<WALStats>>,

    /// Current sequence number
    sequence: Arc<RwLock<u64>>,

    /// Optional broadcast channel for replication — when set, each WAL append
    /// publishes the entry so the WAL shipper can stream it to followers.
    /// Wrapped in Mutex so it can be set at runtime (e.g. during follower → leader promotion).
    replication_tx: parking_lot::Mutex<Option<tokio::sync::broadcast::Sender<WALEntry>>>,

    /// Segments in which `recover()` met a line it could not read.
    unreadable_segments: parking_lot::Mutex<HashSet<PathBuf>>,
    erasure_floor_readable: AtomicBool,
}

#[derive(Debug, Clone)]
pub struct WALConfig {
    /// Maximum size of a single WAL file before rotation (in bytes)
    pub max_file_size: usize,

    /// Whether to sync to disk after each write (fsync)
    pub sync_on_write: bool,

    /// Maximum number of WAL files to keep
    pub max_wal_files: usize,

    /// Enable WAL compression
    pub compress: bool,

    /// Interval in milliseconds for background coalesced fsync.
    /// When set, a background task calls `flush() + sync_all()` every N ms,
    /// giving near-zero write latency with bounded data loss window.
    /// When `Some`, `sync_on_write` is forced to `false` to prevent double-fsync.
    pub fsync_interval_ms: Option<u64>,
}

impl Default for WALConfig {
    fn default() -> Self {
        Self {
            max_file_size: 64 * 1024 * 1024, // 64 MB
            sync_on_write: true,
            max_wal_files: 10,
            compress: false,
            fsync_interval_ms: None,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct WALStats {
    pub total_entries: u64,
    pub total_bytes_written: u64,
    pub current_file_size: usize,
    pub files_rotated: u64,
    pub files_cleaned: u64,
    pub recovery_count: u64,
}

/// WAL entry wrapping an event
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WALEntry {
    /// Sequence number for ordering
    pub sequence: u64,

    /// Timestamp when written to WAL
    pub wal_timestamp: DateTime<Utc>,

    /// The event being logged
    pub event: Event,

    /// Checksum for integrity verification
    pub checksum: u32,
}

impl WALEntry {
    pub fn new(sequence: u64, event: Event) -> Self {
        let mut entry = Self {
            sequence,
            wal_timestamp: Utc::now(),
            event,
            checksum: 0,
        };
        entry.checksum = entry.calculate_checksum();
        entry
    }

    fn calculate_checksum(&self) -> u32 {
        // Simple CRC32 checksum
        let data = format!("{}{}{}", self.sequence, self.wal_timestamp, self.event.id);
        crc32fast::hash(data.as_bytes())
    }

    pub fn verify(&self) -> bool {
        self.checksum == self.calculate_checksum()
    }
}

fn ends_with_newline(file: &mut File) -> Result<bool> {
    let io_err = |e: std::io::Error| {
        AllSourceError::StorageError(format!("Failed to read WAL file tail: {e}"))
    };
    file.seek(SeekFrom::End(-1)).map_err(io_err)?;
    let mut last = [0u8; 1];
    file.read_exact(&mut last).map_err(io_err)?;
    Ok(last[0] == b'\n')
}

/// Represents an active WAL file
struct WALFile {
    path: PathBuf,
    writer: BufWriter<File>,
    size: usize,
    created_at: DateTime<Utc>,
}

impl WALFile {
    fn new(path: PathBuf) -> Result<Self> {
        let mut file = OpenOptions::new()
            .create(true)
            .read(true)
            .append(true)
            .open(&path)
            .map_err(|e| AllSourceError::StorageError(format!("Failed to open WAL file: {e}")))?;

        let mut size = file.metadata().map_or(0, |m| m.len() as usize);

        // A crash can leave a torn final line with no newline. Appending
        // straight after it would fuse the next entry onto the torn bytes and
        // make that entry unreadable too.
        if size > 0 && !ends_with_newline(&mut file)? {
            file.write_all(b"\n")
                .and_then(|()| file.sync_all())
                .map_err(|e| {
                    AllSourceError::StorageError(format!("Failed to terminate torn WAL line: {e}"))
                })?;
            size += 1;
        }

        Ok(Self {
            path,
            writer: BufWriter::new(file),
            size,
            created_at: Utc::now(),
        })
    }

    fn write_entry(&mut self, entry: &WALEntry, sync: bool) -> Result<usize> {
        // Serialize entry as JSON line
        let json = serde_json::to_string(entry)?;

        let line = format!("{json}\n");
        let bytes_written = line.len();

        self.writer
            .write_all(line.as_bytes())
            .map_err(|e| AllSourceError::StorageError(format!("Failed to write to WAL: {e}")))?;

        if sync {
            self.writer
                .flush()
                .map_err(|e| AllSourceError::StorageError(format!("Failed to flush WAL: {e}")))?;

            self.writer
                .get_ref()
                .sync_all()
                .map_err(|e| AllSourceError::StorageError(format!("Failed to sync WAL: {e}")))?;
        }

        self.size += bytes_written;
        Ok(bytes_written)
    }

    fn flush(&mut self) -> Result<()> {
        self.writer
            .flush()
            .map_err(|e| AllSourceError::StorageError(format!("Failed to flush WAL: {e}")))?;
        Ok(())
    }
}

impl WriteAheadLog {
    /// Create a new WAL
    pub fn new(wal_dir: impl Into<PathBuf>, config: WALConfig) -> Result<Self> {
        let wal_dir = wal_dir.into();

        // Create WAL directory if it doesn't exist
        fs::create_dir_all(&wal_dir).map_err(|e| {
            AllSourceError::StorageError(format!("Failed to create WAL directory: {e}"))
        })?;

        // Create initial WAL file
        let initial_file_path = Self::generate_wal_filename(&wal_dir, 0);
        let current_file = WALFile::new(initial_file_path)?;
        let erasure_floor = super::wal_sequence::read_floor(&wal_dir);
        let erasure_floor_readable = erasure_floor.is_ok();

        tracing::info!("✅ WAL initialized at: {}", wal_dir.display());

        Ok(Self {
            wal_dir,
            current_file: Arc::new(RwLock::new(current_file)),
            config,
            stats: Arc::new(RwLock::new(WALStats::default())),
            sequence: Arc::new(RwLock::new(erasure_floor.unwrap_or(0))),
            replication_tx: parking_lot::Mutex::new(None),
            unreadable_segments: parking_lot::Mutex::new(HashSet::new()),
            erasure_floor_readable: AtomicBool::new(erasure_floor_readable),
        })
    }

    /// Generate a WAL filename based on sequence
    fn generate_wal_filename(dir: &Path, sequence: u64) -> PathBuf {
        dir.join(format!("wal-{sequence:016x}.log"))
    }

    /// Write an event to the WAL
    #[cfg_attr(feature = "hotpath", hotpath::measure)]
    pub fn append(&self, event: Event) -> Result<u64> {
        // EventStore may remain open after a recovery error; sequence reuse must fail closed.
        if !self.erasure_floor_readable.load(Ordering::Acquire) {
            return Err(AllSourceError::StorageError(
                "WAL erasure sequence floor is unreadable; repair it before writing".into(),
            ));
        }
        // Get next sequence number
        let mut seq = self.sequence.write();
        *seq += 1;
        let sequence = *seq;
        drop(seq);

        // Create WAL entry
        let entry = WALEntry::new(sequence, event);

        // Write to current file
        let mut current = self.current_file.write();
        let bytes_written = current.write_entry(&entry, self.config.sync_on_write)?;

        // Update statistics
        let mut stats = self.stats.write();
        stats.total_entries += 1;
        stats.total_bytes_written += bytes_written as u64;
        stats.current_file_size = current.size;
        drop(stats);

        // Broadcast to replication channel (if enabled).
        // Errors are ignored: no receivers simply means no followers are connected.
        if let Some(ref tx) = *self.replication_tx.lock() {
            let _ = tx.send(entry);
        }

        // Check if we need to rotate
        let should_rotate = current.size >= self.config.max_file_size;
        drop(current);

        // The entry is already written, so a failed rotation must not report
        // the append as failed; the next append retries it.
        if should_rotate && let Err(e) = self.rotate() {
            tracing::error!("WAL rotation failed after sequence {sequence}: {e}");
        }

        tracing::trace!("WAL entry written: sequence={}", sequence);

        Ok(sequence)
    }

    /// Rotate to a new WAL file
    #[cfg_attr(feature = "hotpath", hotpath::measure)]
    fn rotate(&self) -> Result<()> {
        let seq = *self.sequence.read();
        let new_file_path = Self::generate_wal_filename(&self.wal_dir, seq);

        tracing::info!("🔄 Rotating WAL to new file: {:?}", new_file_path);

        let new_file = WALFile::new(new_file_path)?;

        let mut current = self.current_file.write();
        current.flush()?;
        *current = new_file;

        let mut stats = self.stats.write();
        stats.files_rotated += 1;
        stats.current_file_size = 0;
        drop(stats);

        self.warn_if_segments_accumulate()?;

        Ok(())
    }

    /// Rotation never deletes: a segment past `max_wal_files` may hold events
    /// no checkpoint has flushed yet. Only a checkpoint retires segments.
    fn warn_if_segments_accumulate(&self) -> Result<()> {
        let count = self.list_wal_files()?.len();
        if count > self.config.max_wal_files {
            tracing::warn!(
                "WAL holds {} segments (max_wal_files = {}); checkpoints are not keeping up, \
                 so the WAL keeps growing rather than dropping unflushed events",
                count,
                self.config.max_wal_files
            );
        }
        Ok(())
    }

    /// Delete a segment, or move it to quarantine if recovery could not read
    /// every line in it.
    fn retire_segment(&self, path: &Path) -> Result<()> {
        if !self.unreadable_segments.lock().remove(path) {
            fs::remove_file(path).map_err(|e| {
                AllSourceError::StorageError(format!("Failed to remove WAL file: {e}"))
            })?;
            tracing::debug!("Removed WAL file: {:?}", path);
            return Ok(());
        }

        let quarantine = self.wal_dir.join(QUARANTINE_DIR);
        fs::create_dir_all(&quarantine).map_err(|e| {
            AllSourceError::StorageError(format!("Failed to create WAL quarantine: {e}"))
        })?;
        let name = path.file_name().map_or_else(
            || "wal-unknown.log".into(),
            |n| n.to_string_lossy().into_owned(),
        );
        let target = quarantine.join(format!(
            "{}-{name}",
            Utc::now().format("%Y%m%dT%H%M%S%.6fZ")
        ));
        fs::rename(path, &target).map_err(|e| {
            AllSourceError::StorageError(format!("Failed to quarantine WAL file: {e}"))
        })?;
        tracing::warn!(
            "WAL segment {:?} held lines this binary could not read; kept at {:?} instead of \
             deleting it",
            path,
            target
        );
        Ok(())
    }

    /// Start a new segment so every entry appended so far sits in a segment
    /// older than the returned one. Pair with [`Self::remove_sealed`].
    ///
    /// The caller must stop appends to durable storage for the duration of
    /// this call; otherwise an entry can land in the sealed segment after the
    /// checkpoint's flush has already run.
    pub fn seal(&self) -> Result<PathBuf> {
        let seq = *self.sequence.read();
        let new_path = Self::generate_wal_filename(&self.wal_dir, seq);

        let mut current = self.current_file.write();
        current.flush()?;
        if current.path != new_path {
            *current = WALFile::new(new_path.clone())?;
            self.stats.write().current_file_size = current.size;
        }
        Ok(new_path)
    }

    /// Retire every segment older than `active`, the path [`Self::seal`]
    /// returned. Segments at or after it are kept.
    pub fn remove_sealed(&self, active: &Path) -> Result<()> {
        let Some(active_name) = active.file_name() else {
            return Ok(());
        };
        for path in self.list_wal_files()? {
            if path.file_name().is_some_and(|name| name < active_name) {
                self.retire_segment(&path)?;
            }
        }
        Ok(())
    }

    /// List all WAL files in the directory
    fn list_wal_files(&self) -> Result<Vec<PathBuf>> {
        let entries = fs::read_dir(&self.wal_dir).map_err(|e| {
            AllSourceError::StorageError(format!("Failed to read WAL directory: {e}"))
        })?;

        let mut wal_files = Vec::new();
        for entry in entries {
            let entry = entry.map_err(|e| {
                AllSourceError::StorageError(format!("Failed to read directory entry: {e}"))
            })?;

            let path = entry.path();
            if let Some(name) = path.file_name()
                && name.to_string_lossy().starts_with("wal-")
                && name.to_string_lossy().ends_with(".log")
            {
                wal_files.push(path);
            }
        }

        Ok(wal_files)
    }

    /// Stat every WAL segment, sorted by path. Reads no segment contents.
    pub fn segment_stamps(&self) -> Result<Vec<WalSegmentStamp>> {
        let mut stamps = Vec::new();
        for path in self.list_wal_files()? {
            // A segment unlinked between the listing and the stat is simply gone.
            let Ok(metadata) = fs::metadata(&path) else {
                continue;
            };
            stamps.push(WalSegmentStamp {
                path,
                len: metadata.len(),
                modified: metadata.modified().ok(),
            });
        }
        stamps.sort_by(|a, b| a.path.cmp(&b.path));
        Ok(stamps)
    }

    /// Recover events from WAL files in file order. Reads only: safe for a
    /// replica or a tail over a WAL another process is appending to.
    #[cfg_attr(feature = "hotpath", hotpath::measure)]
    pub fn recover(&self) -> Result<Vec<Event>> {
        Ok(self
            .recover_entries()?
            .into_iter()
            .map(|entry| entry.event)
            .collect())
    }

    /// Recover in sequence order, then move the writer past every recovered
    /// entry. Only for the single process that owns the WAL and appends to it.
    pub fn recover_for_append(&self) -> Result<Vec<Event>> {
        let mut recovered = self.recover_entries()?;
        // An older segment can end with entries appended after a restart.
        recovered.sort_by_key(|entry| entry.sequence);
        self.seal()?;
        Ok(recovered.into_iter().map(|entry| entry.event).collect())
    }

    /// Recover only what a system checkpoint does not cover, then move the
    /// writer past both. A segment listed in `covered` is read from its
    /// recorded length on, so an unchanged one is not opened at all.
    ///
    /// Fails with [`AllSourceError::StorageError`] when the WAL contradicts
    /// the checkpoint: a covered segment shorter than recorded, or an entry
    /// at or below `covered_seq` outside the covered bytes. The caller then
    /// replays the whole WAL instead.
    pub fn recover_for_append_after(
        &self,
        covered_seq: u64,
        covered: &[CoveredSegment],
    ) -> Result<Vec<WALEntry>> {
        let floor = match super::wal_sequence::read_floor(&self.wal_dir) {
            Ok(floor) => floor,
            Err(e) => {
                self.erasure_floor_readable.store(false, Ordering::Release);
                return Err(e);
            }
        };
        self.erasure_floor_readable.store(true, Ordering::Release);
        let mut wal_files = self.list_wal_files()?;
        wal_files.sort();
        let mut recovered = Vec::new();
        let mut max_sequence = covered_seq.max(floor);
        let mut skipped = 0usize;
        for path in &wal_files {
            let name = path
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_default();
            let len = fs::metadata(path)
                .map_err(|e| {
                    AllSourceError::StorageError(format!("Failed to stat WAL segment: {e}"))
                })?
                .len();
            let offset = match covered.iter().find(|segment| segment.name == name) {
                Some(segment) if len == segment.len => {
                    skipped += 1;
                    continue;
                }
                Some(segment) if len < segment.len => {
                    return Err(AllSourceError::StorageError(format!(
                        "WAL segment {name} is {len} bytes, shorter than the {} a checkpoint \
                         covered",
                        segment.len
                    )));
                }
                Some(segment) => segment.len,
                None => 0,
            };
            let (entries, corrupted) = Self::read_segment(path, offset)?;
            if corrupted > 0 {
                self.unreadable_segments.lock().insert(path.clone());
            }
            for entry in entries {
                if entry.sequence <= covered_seq {
                    return Err(AllSourceError::StorageError(format!(
                        "WAL segment {name} holds sequence {} at or below checkpoint \
                         sequence {covered_seq} outside the bytes it covered",
                        entry.sequence
                    )));
                }
                max_sequence = max_sequence.max(entry.sequence);
                recovered.push(entry);
            }
        }
        *self.sequence.write() = max_sequence;
        self.stats.write().recovery_count += 1;
        recovered.sort_by_key(|entry| entry.sequence);
        self.seal()?;
        tracing::info!(
            "✅ WAL recovery after checkpoint {covered_seq}: {} segments skipped, {} events \
             recovered",
            skipped,
            recovered.len()
        );
        Ok(recovered)
    }

    /// False once a recovery failed to read the erasure sequence floor.
    pub(crate) fn erasure_floor_readable(&self) -> bool {
        self.erasure_floor_readable.load(Ordering::Acquire)
    }

    /// [`Self::recover_for_append`], keeping each entry's sequence and
    /// `wal_timestamp`. The next sequence is above `floor` even if no entry
    /// reaches it.
    pub fn recover_entries_for_append(&self, floor: u64) -> Result<Vec<WALEntry>> {
        let mut recovered = self.recover_entries()?;
        {
            let mut sequence = self.sequence.write();
            *sequence = (*sequence).max(floor);
        }
        recovered.sort_by_key(|entry| entry.sequence);
        self.seal()?;
        Ok(recovered)
    }

    /// Every readable entry, in sequence order, without moving the writer or
    /// marking segments.
    pub fn read_all_entries(&self) -> Result<Vec<WALEntry>> {
        let mut wal_files = self.list_wal_files()?;
        wal_files.sort();
        let mut entries = Vec::new();
        for path in &wal_files {
            entries.extend(Self::read_segment(path, 0)?.0);
        }
        entries.sort_by_key(|entry| entry.sequence);
        Ok(entries)
    }

    /// Every segment with its current length, after making every segment and
    /// the directory durable, so no recorded length exceeds what a power loss
    /// leaves on disk.
    ///
    /// The caller must stop appends for the duration of this call and until
    /// it has read the sequence the stamps cover.
    pub fn covered_segments(&self) -> Result<Vec<CoveredSegment>> {
        self.sync()?;
        let sync_err = |e: std::io::Error| {
            AllSourceError::StorageError(format!("Failed to sync WAL segment: {e}"))
        };
        for path in self.list_wal_files()? {
            File::open(&path)
                .and_then(|f| f.sync_all())
                .map_err(sync_err)?;
        }
        File::open(&self.wal_dir)
            .and_then(|d| d.sync_all())
            .map_err(sync_err)?;
        Ok(self
            .segment_stamps()?
            .into_iter()
            .filter_map(|stamp| {
                Some(CoveredSegment {
                    name: stamp.path.file_name()?.to_string_lossy().into_owned(),
                    len: stamp.len,
                })
            })
            .collect())
    }

    /// Readable entries of one segment from `offset`, and how many lines
    /// could not be read.
    fn read_segment(path: &Path, offset: u64) -> Result<(Vec<WALEntry>, usize)> {
        let mut file = File::open(path).map_err(|e| {
            AllSourceError::StorageError(format!("Failed to open WAL file for recovery: {e}"))
        })?;
        if offset > 0 {
            file.seek(SeekFrom::Start(offset)).map_err(|e| {
                AllSourceError::StorageError(format!("Failed to seek WAL file: {e}"))
            })?;
        }
        let mut entries = Vec::new();
        let mut corrupted = 0;
        for (line_num, line) in BufReader::new(file).lines().enumerate() {
            let line = match line {
                Ok(l) => l,
                Err(e) => {
                    tracing::warn!(
                        "I/O error reading WAL line at {:?}:{}: {}",
                        path,
                        line_num + 1,
                        e
                    );
                    corrupted += 1;
                    continue;
                }
            };

            if line.trim().is_empty() {
                continue;
            }

            match serde_json::from_str::<WALEntry>(&line) {
                Ok(entry) if entry.verify() => entries.push(entry),
                Ok(_) => {
                    tracing::warn!(
                        "Corrupted WAL entry at {:?}:{} (checksum mismatch)",
                        path,
                        line_num + 1
                    );
                    corrupted += 1;
                }
                Err(e) => {
                    tracing::warn!(
                        "Failed to parse WAL entry at {:?}:{}: {}",
                        path,
                        line_num + 1,
                        e
                    );
                    corrupted += 1;
                }
            }
        }
        Ok((entries, corrupted))
    }

    fn recover_entries(&self) -> Result<Vec<WALEntry>> {
        tracing::info!("🔄 Starting WAL recovery...");

        let mut wal_files = self.list_wal_files()?;
        wal_files.sort();

        let mut recovered = Vec::new();
        let floor = super::wal_sequence::read_floor(&self.wal_dir);
        self.erasure_floor_readable
            .store(floor.is_ok(), Ordering::Release);
        let mut max_sequence = floor?;
        let mut corrupted_entries = 0;

        for wal_file_path in &wal_files {
            tracing::debug!("Reading WAL file: {:?}", wal_file_path);
            let (entries, corrupted) = Self::read_segment(wal_file_path, 0)?;
            if corrupted > 0 {
                self.unreadable_segments
                    .lock()
                    .insert(wal_file_path.clone());
            }
            corrupted_entries += corrupted;
            for entry in entries {
                max_sequence = max_sequence.max(entry.sequence);
                recovered.push(entry);
            }
        }

        // Update sequence counter
        let mut seq = self.sequence.write();
        *seq = max_sequence;
        drop(seq);

        // Update stats
        let mut stats = self.stats.write();
        stats.recovery_count += 1;
        drop(stats);

        tracing::info!(
            "✅ WAL recovery complete: {} events recovered, {} corrupted entries",
            recovered.len(),
            corrupted_entries
        );

        Ok(recovered)
    }

    /// Manually flush the current WAL file
    #[cfg_attr(feature = "hotpath", hotpath::measure)]
    pub fn flush(&self) -> Result<()> {
        let mut current = self.current_file.write();
        current.flush()?;
        Ok(())
    }

    /// Flush the BufWriter and fsync the current WAL file to disk.
    ///
    /// Called by the background interval-based fsync task. Acquires the write
    /// lock, flushes buffered data, then issues `sync_all()` to ensure the
    /// OS has persisted the data to durable storage.
    #[cfg_attr(feature = "hotpath", hotpath::measure)]
    pub fn sync(&self) -> Result<()> {
        let mut current = self.current_file.write();
        current
            .writer
            .flush()
            .map_err(|e| AllSourceError::StorageError(format!("Failed to flush WAL: {e}")))?;
        current
            .writer
            .get_ref()
            .sync_all()
            .map_err(|e| AllSourceError::StorageError(format!("Failed to sync WAL: {e}")))?;
        Ok(())
    }

    /// Get the configured fsync interval (if any).
    pub fn fsync_interval_ms(&self) -> Option<u64> {
        self.config.fsync_interval_ms
    }

    /// Truncate WAL after successful checkpoint
    #[cfg_attr(feature = "hotpath", hotpath::measure)]
    pub fn truncate(&self) -> Result<()> {
        tracing::info!("🧹 Truncating WAL after checkpoint");
        let mut floor = super::wal_sequence::read_floor(&self.wal_dir)?;
        if floor > 0 {
            floor = floor.max(self.current_sequence());
            super::wal_sequence::preserve_floor(&self.wal_dir, floor)?;
        }

        // Close current file
        let mut current = self.current_file.write();
        current.flush()?;

        let wal_files = self.list_wal_files()?;
        for file_path in wal_files {
            self.retire_segment(&file_path)?;
        }

        // Create new WAL file
        let new_file_path = Self::generate_wal_filename(&self.wal_dir, 0);
        *current = WALFile::new(new_file_path)?;

        let mut seq = self.sequence.write();
        *seq = floor;

        tracing::info!("✅ WAL truncated successfully");

        Ok(())
    }

    /// Get WAL statistics
    pub fn stats(&self) -> WALStats {
        (*self.stats.read()).clone()
    }

    /// Sum the on-disk size of all WAL segment files and count them.
    ///
    /// Walks the WAL directory and `fs::metadata`s each `wal-*.log` segment.
    /// Returns `(total_bytes, segment_count)`. Unlike `WALStats.total_bytes_written`
    /// (a monotonic write counter that ignores rotation/cleanup), this reflects the
    /// *current* on-disk footprint — what we want to report as storage size and as
    /// `allsource_wal_segments_total`.
    ///
    /// Cheap (one `statx` per segment; each checkpoint retires sealed segments,
    /// so the count stays small), so it's safe to call on the checkpoint cadence. Errors reading the directory
    /// surface as `Err`; a per-file metadata error skips that file rather than
    /// aborting the whole tally.
    pub fn on_disk_stats(&self) -> Result<(u64, usize)> {
        let wal_files = self.list_wal_files()?;
        let mut total_bytes = 0u64;
        for path in &wal_files {
            if let Ok(metadata) = fs::metadata(path) {
                total_bytes += metadata.len();
            }
        }
        Ok((total_bytes, wal_files.len()))
    }

    /// Get current sequence number
    pub fn current_sequence(&self) -> u64 {
        *self.sequence.read()
    }

    /// Get the oldest available WAL sequence number.
    ///
    /// Returns the first sequence found in the oldest WAL file, or `None`
    /// if no WAL entries exist. Used by the replication catch-up protocol
    /// to determine whether a follower can catch up from WAL alone.
    pub fn oldest_sequence(&self) -> Option<u64> {
        let Ok(mut wal_files) = self.list_wal_files() else {
            return None;
        };

        if wal_files.is_empty() {
            return None;
        }

        wal_files.sort();

        // Read the first entry from the oldest WAL file
        for wal_file_path in &wal_files {
            let Ok(file) = File::open(wal_file_path) else {
                continue;
            };
            let reader = BufReader::new(file);
            for line in reader.lines() {
                let Ok(line) = line else {
                    continue;
                };
                if line.trim().is_empty() {
                    continue;
                }
                if let Ok(entry) = serde_json::from_str::<WALEntry>(&line) {
                    return Some(entry.sequence);
                }
            }
        }

        None
    }

    /// Attach a broadcast sender for WAL replication.
    ///
    /// When set, every `append()` call will publish the WAL entry to this
    /// channel so the WAL shipper can stream it to connected followers.
    pub fn set_replication_tx(&self, tx: tokio::sync::broadcast::Sender<WALEntry>) {
        *self.replication_tx.lock() = Some(tx);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use tempfile::TempDir;
    use uuid::Uuid;

    fn create_test_event() -> Event {
        Event::reconstruct_from_strings(
            Uuid::new_v4(),
            "test.event".to_string(),
            "test-entity".to_string(),
            "default".to_string(),
            json!({"test": "data"}),
            Utc::now(),
            None,
            1,
        )
    }

    #[test]
    fn test_wal_creation() {
        let temp_dir = TempDir::new().unwrap();
        let wal = WriteAheadLog::new(temp_dir.path(), WALConfig::default());
        assert!(wal.is_ok());
    }

    #[test]
    fn test_wal_append() {
        let temp_dir = TempDir::new().unwrap();
        let wal = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();

        let event = create_test_event();
        let seq = wal.append(event);
        assert!(seq.is_ok());
        assert_eq!(seq.unwrap(), 1);

        let stats = wal.stats();
        assert_eq!(stats.total_entries, 1);
    }

    #[test]
    fn test_wal_on_disk_stats() {
        let temp_dir = TempDir::new().unwrap();
        let wal = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();

        // Empty WAL dir (the active segment is created lazily on first append):
        // zero or one segment, zero bytes.
        let (bytes0, segs0) = wal.on_disk_stats().unwrap();
        assert_eq!(bytes0, 0);
        assert!(segs0 <= 1);

        for _ in 0..5 {
            wal.append(create_test_event()).unwrap();
        }
        wal.flush().unwrap();

        let (bytes, segs) = wal.on_disk_stats().unwrap();
        assert!(segs >= 1, "expected at least one WAL segment, got {segs}");
        assert!(
            bytes > 0,
            "expected non-zero WAL bytes after appends, got {bytes}"
        );
    }

    #[test]
    fn test_wal_recovery() {
        let temp_dir = TempDir::new().unwrap();
        let wal = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();

        // Write some events
        for _ in 0..5 {
            wal.append(create_test_event()).unwrap();
        }

        wal.flush().unwrap();

        // Create new WAL instance (simulating restart)
        let wal2 = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
        let recovered = wal2.recover().unwrap();

        assert_eq!(recovered.len(), 5);
    }

    #[test]
    fn test_recovery_keeps_wal_timestamp() {
        let temp_dir = TempDir::new().unwrap();
        let wal = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
        for _ in 0..3 {
            wal.append(create_test_event()).unwrap();
        }
        wal.flush().unwrap();

        let written: Vec<WALEntry> =
            std::fs::read_to_string(temp_dir.path().join("wal-0000000000000000.log"))
                .unwrap()
                .lines()
                .map(|line| serde_json::from_str(line).unwrap())
                .collect();

        let wal2 = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
        let recovered = wal2.recover_entries_for_append(0).unwrap();

        assert_eq!(recovered.len(), 3);
        for (entry, on_disk) in recovered.iter().zip(&written) {
            assert_eq!(entry.sequence, on_disk.sequence);
            assert_eq!(entry.wal_timestamp, on_disk.wal_timestamp);
        }
    }

    #[test]
    fn test_wal_round_trips_valid_time_and_reads_pre_axis_lines() {
        let temp_dir = TempDir::new().unwrap();
        let valid_from = Utc::now() - chrono::Duration::days(3);
        let dated = create_test_event()
            .with_valid_time(Some(valid_from), None)
            .unwrap();

        let wal = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
        wal.append(create_test_event()).unwrap();
        wal.append(dated).unwrap();
        wal.flush().unwrap();

        let wal2 = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
        let recovered = wal2.recover_entries_for_append(0).unwrap();

        assert_eq!(recovered.len(), 2);
        assert_eq!(recovered[0].event.valid_from, None);
        assert_eq!(recovered[0].event.valid_to, None);
        assert_eq!(recovered[1].event.valid_from, Some(valid_from));
        assert_eq!(recovered[1].event.valid_to, None);
    }

    #[test]
    fn test_wal_recovery_with_partial_write() {
        let temp_dir = TempDir::new().unwrap();
        let wal = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();

        // Write 3 complete events
        for _ in 0..3 {
            wal.append(create_test_event()).unwrap();
        }
        wal.flush().unwrap();

        // Simulate a partial write by appending malformed data to the WAL file
        let wal_file_path = temp_dir.path().join("wal-0000000000000000.log");
        use std::io::Write as _;
        let mut f = std::fs::OpenOptions::new()
            .append(true)
            .open(&wal_file_path)
            .unwrap();
        f.write_all(b"{\"partial\": true, \"seq\"\n").unwrap(); // truncated JSON
        drop(f);

        // Recovery should succeed and return only the 3 valid events
        let wal2 = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
        let recovered = wal2.recover().unwrap();
        assert_eq!(
            recovered.len(),
            3,
            "Should recover only the 3 valid events, not the partial one"
        );
    }

    #[test]
    fn test_wal_rotation() {
        let temp_dir = TempDir::new().unwrap();
        let config = WALConfig {
            max_file_size: 1024, // Small size to trigger rotation
            ..Default::default()
        };

        let wal = WriteAheadLog::new(temp_dir.path(), config).unwrap();

        // Write enough events to trigger rotation
        for _ in 0..50 {
            wal.append(create_test_event()).unwrap();
        }

        let stats = wal.stats();
        assert!(stats.files_rotated > 0);
    }

    #[test]
    fn test_wal_recovery_keeps_append_order_across_restarts() {
        let temp_dir = TempDir::new().unwrap();
        let config = || WALConfig {
            max_file_size: 1,
            ..Default::default()
        };
        let mut appended = Vec::new();

        let first = WriteAheadLog::new(temp_dir.path(), config()).unwrap();
        for _ in 0..2 {
            let event = create_test_event();
            appended.push(event.id());
            first.append(event).unwrap();
        }
        drop(first);

        let second = WriteAheadLog::new(temp_dir.path(), config()).unwrap();
        second.recover_for_append().unwrap();
        let event = create_test_event();
        appended.push(event.id());
        second.append(event).unwrap();
        drop(second);

        let first_segment =
            std::fs::read_to_string(temp_dir.path().join("wal-0000000000000000.log")).unwrap();
        assert_eq!(
            first_segment
                .lines()
                .filter(|l| !l.trim().is_empty())
                .count(),
            1,
            "an append after recovery must not land in the oldest segment"
        );

        let third = WriteAheadLog::new(temp_dir.path(), config()).unwrap();
        let recovered: Vec<Uuid> = third
            .recover_for_append()
            .unwrap()
            .iter()
            .map(Event::id)
            .collect();
        assert_eq!(recovered, appended);
    }

    #[test]
    fn test_wal_recovery_orders_misplaced_entries_by_sequence() {
        let temp_dir = TempDir::new().unwrap();
        let older = create_test_event();
        let newer = create_test_event();
        let line = |sequence, event: &Event| {
            format!(
                "{}\n",
                serde_json::to_string(&WALEntry::new(sequence, event.clone())).unwrap()
            )
        };
        std::fs::write(
            temp_dir.path().join("wal-0000000000000000.log"),
            line(1, &older) + &line(3, &newer),
        )
        .unwrap();
        std::fs::write(
            temp_dir.path().join("wal-0000000000000001.log"),
            line(2, &create_test_event()),
        )
        .unwrap();

        let wal = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
        let recovered = wal.recover_for_append().unwrap();

        assert_eq!(recovered.len(), 3);
        assert_eq!(recovered[0].id(), older.id());
        assert_eq!(recovered[2].id(), newer.id());
    }

    #[test]
    fn test_wal_read_only_recovery_creates_no_segment() {
        let temp_dir = TempDir::new().unwrap();
        let writer = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
        for _ in 0..3 {
            writer.append(create_test_event()).unwrap();
        }
        writer.flush().unwrap();
        let listing = || {
            let mut names: Vec<_> = std::fs::read_dir(temp_dir.path())
                .unwrap()
                .map(|entry| entry.unwrap().file_name())
                .collect();
            names.sort();
            names
        };
        let before = listing();

        let reader = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
        assert_eq!(reader.recover().unwrap().len(), 3);
        assert_eq!(reader.recover().unwrap().len(), 3);

        assert_eq!(listing(), before);
    }

    #[test]
    fn test_wal_entry_checksum() {
        let event = create_test_event();
        let entry = WALEntry::new(1, event);

        assert!(entry.verify());

        // Modify and verify it fails
        let mut corrupted = entry.clone();
        corrupted.checksum = 0;
        assert!(!corrupted.verify());
    }

    #[test]
    fn test_wal_fsync_interval_config() {
        let config = WALConfig {
            fsync_interval_ms: Some(100),
            ..Default::default()
        };
        assert_eq!(config.fsync_interval_ms, Some(100));
        // Default should have no interval
        assert_eq!(WALConfig::default().fsync_interval_ms, None);
    }

    #[test]
    fn test_wal_sync_method() {
        let temp_dir = TempDir::new().unwrap();
        let config = WALConfig {
            sync_on_write: false, // Disable per-write sync to test explicit sync
            ..Default::default()
        };
        let wal = WriteAheadLog::new(temp_dir.path(), config).unwrap();

        // Write events without per-write fsync
        for _ in 0..5 {
            wal.append(create_test_event()).unwrap();
        }

        // Explicitly sync — should flush + fsync without error
        wal.sync().unwrap();

        // Verify data survives by recovering from a new WAL instance
        let wal2 = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
        let recovered = wal2.recover().unwrap();
        assert_eq!(recovered.len(), 5);
    }

    #[test]
    fn test_wal_truncate() {
        let temp_dir = TempDir::new().unwrap();
        let wal = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();

        // Write events
        for _ in 0..5 {
            wal.append(create_test_event()).unwrap();
        }

        // Truncate
        wal.truncate().unwrap();

        // Verify sequence is reset
        assert_eq!(wal.current_sequence(), 0);

        // Verify recovery returns empty
        let recovered = wal.recover().unwrap();
        assert_eq!(recovered.len(), 0);
    }

    #[test]
    fn valid_time_survives_a_restart() {
        let temp_dir = TempDir::new().unwrap();
        let wal = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();

        let mut event = create_test_event();
        let valid_from = Utc::now() - chrono::Duration::days(30);
        let valid_to = Utc::now() + chrono::Duration::days(1);
        event.valid_from = Some(valid_from);
        event.valid_to = Some(valid_to);
        wal.append(event.clone()).unwrap();
        wal.flush().unwrap();
        drop(wal);

        let wal2 = WriteAheadLog::new(temp_dir.path(), WALConfig::default()).unwrap();
        let recovered = wal2.recover().unwrap();
        assert_eq!(recovered.len(), 1);
        assert_eq!(recovered[0].valid_from, Some(valid_from));
        assert_eq!(recovered[0].valid_to, Some(valid_to));
        assert_eq!(recovered[0], event);
    }

    #[test]
    fn a_wal_line_without_valid_time_reads_back_unset() {
        let event = create_test_event();
        let line = serde_json::json!({
            "sequence": 1,
            "wal_timestamp": Utc::now(),
            "event": serde_json::to_value(&event).unwrap(),
            "checksum": 0,
        });
        assert!(
            line["event"].get("valid_from").is_none() && line["event"].get("valid_to").is_none(),
            "an event with no valid time must not write the keys"
        );

        let entry: WALEntry = serde_json::from_value(line).unwrap();
        assert_eq!(entry.event.valid_from, None);
        assert_eq!(entry.event.valid_to, None);
        assert_eq!(entry.event, event);
    }
}