cu29-unifiedlog 0.15.0

The super quick, linear, unified logging system (text + task data) used by Copper. This crate can be used independently from the Copper project.
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
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
//! This is the memory map file implementation for the unified logger for Copper.
//! It is std only.

use crate::{
    AllocatedSection, MAIN_MAGIC, MainHeader, SECTION_MAGIC, SectionHandle, SectionHeader,
    SectionStorage, UnifiedLogRead, UnifiedLogStatus, UnifiedLogWrite,
};

use crate::SECTION_HEADER_COMPACT_SIZE;

use AllocatedSection::Section;
use bincode::config::standard;
use bincode::enc::EncoderImpl;
use bincode::enc::write::SliceWriter;
use bincode::error::EncodeError;
use bincode::{Encode, decode_from_slice, encode_into_slice};
use core::slice::from_raw_parts_mut;
use cu29_traits::{
    CuError, CuResult, ObservedWriter, UnifiedLogType, abort_observed_encode,
    begin_observed_encode, finish_observed_encode,
};
use memmap2::{Mmap, MmapMut};
use std::fs::{File, OpenOptions};
use std::io::Read;
use std::mem::ManuallyDrop;
use std::path::{Path, PathBuf};
use std::{io, mem};

pub struct MmapSectionStorage {
    buffer: &'static mut [u8],
    offset: usize,
    block_size: usize,
}

impl MmapSectionStorage {
    pub fn new(buffer: &'static mut [u8], block_size: usize) -> Self {
        Self {
            buffer,
            offset: 0,
            block_size,
        }
    }

    pub fn buffer_ptr(&self) -> *const u8 {
        &self.buffer[0] as *const u8
    }
}

impl SectionStorage for MmapSectionStorage {
    fn initialize<E: Encode>(&mut self, header: &E) -> Result<usize, EncodeError> {
        self.post_update_header(header)?;
        self.offset = self.block_size;
        Ok(self.offset)
    }

    fn post_update_header<E: Encode>(&mut self, header: &E) -> Result<usize, EncodeError> {
        encode_into_slice(header, &mut self.buffer[0..], standard())
    }

    fn append<E: Encode>(&mut self, entry: &E) -> Result<usize, EncodeError> {
        begin_observed_encode();
        let result = (|| {
            let mut encoder = EncoderImpl::new(
                ObservedWriter::new(SliceWriter::new(&mut self.buffer[self.offset..])),
                standard(),
            );
            entry.encode(&mut encoder)?;
            Ok(encoder.into_writer().into_inner().bytes_written())
        })();
        let size = match result {
            Ok(size) => {
                debug_assert_eq!(size, finish_observed_encode());
                size
            }
            Err(err) => {
                abort_observed_encode();
                return Err(err);
            }
        };
        self.offset += size;
        Ok(size)
    }

    fn flush(&mut self) -> CuResult<usize> {
        // Flushing is handled at the slab level for mmap-backed storage.
        Ok(self.offset)
    }
}

///
/// Holds the read or write side of the datalogger.
pub enum MmapUnifiedLogger {
    Read(MmapUnifiedLoggerRead),
    Write(MmapUnifiedLoggerWrite),
}

/// Use this builder to create a new DataLogger.
pub struct MmapUnifiedLoggerBuilder {
    file_base_name: Option<PathBuf>,
    preallocated_size: Option<usize>,
    write: bool,
    create: bool,
}

impl Default for MmapUnifiedLoggerBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl MmapUnifiedLoggerBuilder {
    pub fn new() -> Self {
        Self {
            file_base_name: None,
            preallocated_size: None,
            write: false,
            create: false, // This is the safest default
        }
    }

    /// If "something/toto.copper" is given, it will find or create "something/toto_0.copper",  "something/toto_1.copper" etc.
    pub fn file_base_name(mut self, file_path: &Path) -> Self {
        self.file_base_name = Some(file_path.to_path_buf());
        self
    }

    pub fn preallocated_size(mut self, preallocated_size: usize) -> Self {
        self.preallocated_size = Some(preallocated_size);
        self
    }

    pub fn write(mut self, write: bool) -> Self {
        self.write = write;
        self
    }

    pub fn create(mut self, create: bool) -> Self {
        self.create = create;
        self
    }

    pub fn build(self) -> io::Result<MmapUnifiedLogger> {
        let page_size = page_size::get();

        if self.write && self.create {
            let file_path = self.file_base_name.ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "File path is required for write mode",
                )
            })?;
            let preallocated_size = self.preallocated_size.ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "Preallocated size is required for write mode",
                )
            })?;
            let ulw = MmapUnifiedLoggerWrite::new(&file_path, preallocated_size, page_size)?;
            Ok(MmapUnifiedLogger::Write(ulw))
        } else {
            let file_path = self.file_base_name.ok_or_else(|| {
                io::Error::new(io::ErrorKind::InvalidInput, "File path is required")
            })?;
            let ulr = MmapUnifiedLoggerRead::new(&file_path)?;
            Ok(MmapUnifiedLogger::Read(ulr))
        }
    }
}

struct SlabEntry {
    file: File,
    mmap_buffer: ManuallyDrop<MmapMut>,
    current_global_position: usize,
    sections_offsets_in_flight: Vec<usize>,
    flushed_until_offset: usize,
    page_size: usize,
    temporary_end_marker: Option<usize>,
    #[cfg(test)]
    closed_sections: Vec<(usize, usize)>,
    #[cfg(test)]
    flushed_ranges: Vec<(usize, usize)>,
    #[cfg(all(test, feature = "mmap-fsync"))]
    sync_call_count: usize,
}

impl Drop for SlabEntry {
    fn drop(&mut self) {
        self.flush_until(self.current_global_position);
        // SAFETY: We own the mapping and must drop it before trimming the file.
        unsafe { ManuallyDrop::drop(&mut self.mmap_buffer) };
        if let Err(error) = self.file.set_len(self.current_global_position as u64) {
            eprintln!("Failed to trim datalogger file: {}", error);
        }
        self.sync_file();

        if !self.sections_offsets_in_flight.is_empty() {
            eprintln!("Error: Slab not full flushed.");
        }
    }
}

impl SlabEntry {
    fn new(file: File, page_size: usize) -> io::Result<Self> {
        let mmap_buffer = ManuallyDrop::new(
            // SAFETY: The file descriptor is valid and mapping is confined to this struct.
            unsafe { MmapMut::map_mut(&file) }
                .map_err(|e| io::Error::new(e.kind(), format!("Failed to map file: {e}")))?,
        );
        Ok(Self {
            file,
            mmap_buffer,
            current_global_position: 0,
            sections_offsets_in_flight: Vec::with_capacity(16),
            flushed_until_offset: 0,
            page_size,
            temporary_end_marker: None,
            #[cfg(test)]
            closed_sections: Vec::new(),
            #[cfg(test)]
            flushed_ranges: Vec::new(),
            #[cfg(all(test, feature = "mmap-fsync"))]
            sync_call_count: 0,
        })
    }

    fn flush_range(&mut self, start: usize, len: usize) {
        if len == 0 {
            return;
        }
        self.mmap_buffer
            .flush_async_range(start, len)
            .expect("Failed to flush memory map");
        self.sync_file();
        #[cfg(test)]
        self.record_flushed_range(start, len);
    }

    fn sync_file(&mut self) {
        #[cfg(feature = "mmap-fsync")]
        {
            self.file.sync_all().expect("Failed to fsync log file");
            #[cfg(test)]
            {
                self.sync_call_count += 1;
            }
        }
    }
    /// Unsure the underlying mmap is flush to disk until the given position.
    fn flush_until(&mut self, until_position: usize) {
        // This is tolerated under linux, but crashes on macos
        if (self.flushed_until_offset == until_position) || (until_position == 0) {
            return;
        }
        self.flush_range(
            self.flushed_until_offset,
            until_position - self.flushed_until_offset,
        );
        self.flushed_until_offset = until_position;
    }

    fn clear_temporary_end_marker(&mut self) {
        if let Some(marker_start) = self.temporary_end_marker.take() {
            self.current_global_position = marker_start;
            if self.flushed_until_offset > marker_start {
                self.flushed_until_offset = marker_start;
            }
        }
    }

    fn write_end_marker(&mut self, temporary: bool) -> CuResult<()> {
        let block_size = SECTION_HEADER_COMPACT_SIZE as usize;
        let marker_start = self.align_to_next_page(self.current_global_position);
        let total_marker_size = block_size; // header only
        let marker_end = marker_start + total_marker_size;
        if marker_end > self.mmap_buffer.len() {
            return Err("Not enough space to write end-of-log marker".into());
        }

        let header = SectionHeader {
            magic: SECTION_MAGIC,
            block_size: SECTION_HEADER_COMPACT_SIZE,
            entry_type: UnifiedLogType::LastEntry,
            offset_to_next_section: total_marker_size as u32,
            used: 0,
            is_open: temporary,
        };

        encode_into_slice(
            &header,
            &mut self.mmap_buffer
                [marker_start..marker_start + SECTION_HEADER_COMPACT_SIZE as usize],
            standard(),
        )
        .map_err(|e| CuError::new_with_cause("Failed to encode end-of-log header", e))?;

        self.temporary_end_marker = Some(marker_start);
        self.current_global_position = marker_end;
        Ok(())
    }

    fn is_it_my_section(&self, section: &SectionHandle<MmapSectionStorage>) -> bool {
        let storage = section.get_storage();
        let ptr = storage.buffer_ptr();
        (ptr >= self.mmap_buffer.as_ptr())
            && (ptr as usize)
                < (self.mmap_buffer.as_ref().as_ptr() as usize + self.mmap_buffer.as_ref().len())
    }

    /// Flush the section to disk.
    /// the flushing is permanent and the section is considered closed.
    fn flush_section(&mut self, section: &mut SectionHandle<MmapSectionStorage>) {
        section
            .post_update_header()
            .expect("Failed to update section header");

        let storage = section.get_storage();
        let ptr = storage.buffer_ptr();

        if ptr < self.mmap_buffer.as_ptr()
            || ptr as usize > self.mmap_buffer.as_ptr() as usize + self.mmap_buffer.len()
        {
            panic!("Invalid section buffer, not in the slab");
        }

        let base = self.mmap_buffer.as_ptr() as usize;
        let section_start = ptr as usize - base;
        let section_len = section.header.offset_to_next_section as usize;
        #[cfg(test)]
        self.record_closed_section(section_start, section_len);
        self.sections_offsets_in_flight
            .retain(|&x| x != section_start);

        if self.sections_offsets_in_flight.is_empty() {
            self.flush_until(self.current_global_position);
            return;
        }
        let next_open_offset = self.sections_offsets_in_flight[0];
        if self.flushed_until_offset < next_open_offset {
            self.flush_until(next_open_offset);
        }
        if section_start + section_len > self.flushed_until_offset {
            // A long-lived early section can otherwise pin later closed sections
            // behind the prefix cursor until shutdown.
            self.flush_range(section_start, section_len);
        }
    }

    #[cfg(test)]
    fn record_closed_section(&mut self, start: usize, len: usize) {
        self.closed_sections.push((start, len));
    }

    #[cfg(test)]
    fn record_flushed_range(&mut self, start: usize, len: usize) {
        let mut merged_start = start;
        let mut merged_end = start + len;
        let mut merged_ranges = Vec::with_capacity(self.flushed_ranges.len() + 1);
        let mut inserted = false;

        for (range_start, range_len) in self.flushed_ranges.drain(..) {
            let range_end = range_start + range_len;
            if range_end < merged_start {
                merged_ranges.push((range_start, range_len));
                continue;
            }
            if merged_end < range_start {
                if !inserted {
                    merged_ranges.push((merged_start, merged_end - merged_start));
                    inserted = true;
                }
                merged_ranges.push((range_start, range_len));
                continue;
            }

            merged_start = merged_start.min(range_start);
            merged_end = merged_end.max(range_end);
        }

        if !inserted {
            merged_ranges.push((merged_start, merged_end - merged_start));
        }

        self.flushed_ranges = merged_ranges;
    }

    #[cfg(test)]
    fn pending_closed_bytes(&self) -> usize {
        let mut pending = 0;

        for (section_start, section_len) in &self.closed_sections {
            let section_end = section_start + section_len;
            let mut cursor = *section_start;

            for (range_start, range_len) in &self.flushed_ranges {
                let range_end = range_start + range_len;
                if range_end <= cursor {
                    continue;
                }
                if *range_start >= section_end {
                    break;
                }
                if *range_start > cursor {
                    pending += *range_start - cursor;
                }
                cursor = cursor.max(range_end);
                if cursor >= section_end {
                    break;
                }
            }

            if cursor < section_end {
                pending += section_end - cursor;
            }
        }

        pending
    }

    #[inline]
    fn align_to_next_page(&self, ptr: usize) -> usize {
        (ptr + self.page_size - 1) & !(self.page_size - 1)
    }

    /// The returned slice is section_size or greater.
    fn add_section(
        &mut self,
        entry_type: UnifiedLogType,
        requested_section_size: usize,
    ) -> AllocatedSection<MmapSectionStorage> {
        // align current_position to the next page
        self.current_global_position = self.align_to_next_page(self.current_global_position);
        let section_size = self.align_to_next_page(requested_section_size) as u32;

        // We need to have enough space to store the section in that slab
        if self.current_global_position + section_size as usize > self.mmap_buffer.len() {
            return AllocatedSection::NoMoreSpace;
        }

        #[cfg(feature = "compact")]
        let block_size = SECTION_HEADER_COMPACT_SIZE;

        #[cfg(not(feature = "compact"))]
        let block_size = self.page_size as u16;

        let section_header = SectionHeader {
            magic: SECTION_MAGIC,
            block_size,
            entry_type,
            offset_to_next_section: section_size,
            used: 0u32,
            is_open: true,
        };

        // save the position to keep track for in flight sections
        self.sections_offsets_in_flight
            .push(self.current_global_position);
        let end_of_section = self.current_global_position + requested_section_size;
        let user_buffer = &mut self.mmap_buffer[self.current_global_position..end_of_section];

        // SAFETY: We have exclusive access to user_buffer for the handle's lifetime.
        let handle_buffer =
            unsafe { from_raw_parts_mut(user_buffer.as_mut_ptr(), user_buffer.len()) };
        let storage = MmapSectionStorage::new(handle_buffer, block_size as usize);

        self.current_global_position = end_of_section;

        Section(SectionHandle::create(section_header, storage).expect("Failed to create section"))
    }

    #[cfg(test)]
    fn used(&self) -> usize {
        self.current_global_position
    }
}

/// A write side of the datalogger.
pub struct MmapUnifiedLoggerWrite {
    /// the front slab is the current active slab for any new section.
    front_slab: SlabEntry,
    /// the back slab is the previous slab that is being flushed.
    back_slabs: Vec<SlabEntry>,
    /// base file path to create the backing files from.
    base_file_path: PathBuf,
    /// allocation size for the backing files.
    slab_size: usize,
    /// current suffix for the backing files.
    front_slab_suffix: usize,
}

fn build_slab_path(base_file_path: &Path, slab_index: usize) -> io::Result<PathBuf> {
    let mut file_path = base_file_path.to_path_buf();
    let stem = file_path.file_stem().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            "Base file path has no file name",
        )
    })?;
    let stem = stem.to_str().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            "Base file name is not valid UTF-8",
        )
    })?;
    let extension = file_path.extension().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            "Base file path has no extension",
        )
    })?;
    let extension = extension.to_str().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            "Base file extension is not valid UTF-8",
        )
    })?;
    if stem.is_empty() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "Base file name is empty",
        ));
    }
    let file_name = format!("{stem}_{slab_index}.{extension}");
    file_path.set_file_name(file_name);
    Ok(file_path)
}

fn make_slab_file(base_file_path: &Path, slab_size: usize, slab_suffix: usize) -> io::Result<File> {
    let file_path = build_slab_path(base_file_path, slab_suffix)?;
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        .open(&file_path)
        .map_err(|e| {
            io::Error::new(
                e.kind(),
                format!("Failed to open file {}: {e}", file_path.display()),
            )
        })?;
    file.set_len(slab_size as u64).map_err(|e| {
        io::Error::new(
            e.kind(),
            format!("Failed to set file length for {}: {e}", file_path.display()),
        )
    })?;
    Ok(file)
}

fn remove_existing_alias(base_file_path: &Path) -> io::Result<()> {
    match std::fs::symlink_metadata(base_file_path) {
        Ok(meta) => {
            if meta.is_dir() {
                return Err(io::Error::new(
                    io::ErrorKind::AlreadyExists,
                    format!(
                        "Cannot create base log alias at {} because a directory already exists there",
                        base_file_path.display()
                    ),
                ));
            }
            std::fs::remove_file(base_file_path).map_err(|e| {
                io::Error::new(
                    e.kind(),
                    format!(
                        "Failed to remove existing base log alias {}: {e}",
                        base_file_path.display()
                    ),
                )
            })
        }
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(io::Error::new(
            e.kind(),
            format!(
                "Failed to inspect existing base log alias {}: {e}",
                base_file_path.display()
            ),
        )),
    }
}

fn create_base_alias_link(base_file_path: &Path) -> io::Result<()> {
    let first_slab_path = build_slab_path(base_file_path, 0)?;
    remove_existing_alias(base_file_path)?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::symlink;
        let relative_target = Path::new(first_slab_path.file_name().ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "First slab file has no name component",
            )
        })?);
        symlink(relative_target, base_file_path).map_err(|e| {
            io::Error::new(
                e.kind(),
                format!(
                    "Failed to create base log alias {} -> {}: {e}",
                    base_file_path.display(),
                    first_slab_path.display()
                ),
            )
        })
    }

    #[cfg(windows)]
    {
        use std::os::windows::fs::symlink_file;
        let relative_target = Path::new(first_slab_path.file_name().ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "First slab file has no name component",
            )
        })?);
        match symlink_file(relative_target, base_file_path) {
            Ok(()) => Ok(()),
            Err(symlink_err) => std::fs::hard_link(&first_slab_path, base_file_path).map_err(
                |hard_link_err| {
                    io::Error::other(format!(
                        "Failed to create base log alias {}. Symlink error: {symlink_err}. Hard-link fallback error: {hard_link_err}",
                        base_file_path.display()
                    ))
                },
            ),
        }?;
        Ok(())
    }

    #[cfg(not(any(unix, windows)))]
    {
        std::fs::hard_link(&first_slab_path, base_file_path).map_err(|e| {
            io::Error::new(
                e.kind(),
                format!(
                    "Failed to create base log alias {} -> {}: {e}",
                    base_file_path.display(),
                    first_slab_path.display()
                ),
            )
        })
    }
}

impl UnifiedLogWrite<MmapSectionStorage> for MmapUnifiedLoggerWrite {
    /// The returned slice is section_size or greater.
    fn add_section(
        &mut self,
        entry_type: UnifiedLogType,
        requested_section_size: usize,
    ) -> CuResult<SectionHandle<MmapSectionStorage>> {
        self.garbage_collect_backslabs(); // Take the opportunity to keep up and close stale back slabs.
        self.front_slab.clear_temporary_end_marker();
        let maybe_section = self
            .front_slab
            .add_section(entry_type, requested_section_size);

        match maybe_section {
            AllocatedSection::NoMoreSpace => {
                // move the front slab to the back slab.
                let new_slab = self.create_slab()?;
                // keep the slab until all its sections has been flushed.
                self.back_slabs
                    .push(mem::replace(&mut self.front_slab, new_slab));
                match self
                    .front_slab
                    .add_section(entry_type, requested_section_size)
                {
                    AllocatedSection::NoMoreSpace => Err(CuError::from("out of space")),
                    Section(section) => {
                        self.place_end_marker(true)?;
                        Ok(section)
                    }
                }
            }
            Section(section) => {
                self.place_end_marker(true)?;
                Ok(section)
            }
        }
    }

    fn flush_section(&mut self, section: &mut SectionHandle<MmapSectionStorage>) {
        section.mark_closed();
        for slab in self.back_slabs.iter_mut() {
            if slab.is_it_my_section(section) {
                slab.flush_section(section);
                return;
            }
        }
        self.front_slab.flush_section(section);
    }

    fn status(&self) -> UnifiedLogStatus {
        UnifiedLogStatus {
            total_used_space: self.front_slab.current_global_position,
            total_allocated_space: self.slab_size * self.front_slab_suffix,
        }
    }
}

impl MmapUnifiedLoggerWrite {
    fn next_slab(&mut self) -> io::Result<File> {
        let next_suffix = self.front_slab_suffix + 1;
        let file = make_slab_file(&self.base_file_path, self.slab_size, next_suffix)?;
        self.front_slab_suffix = next_suffix;
        Ok(file)
    }

    fn new(base_file_path: &Path, slab_size: usize, page_size: usize) -> io::Result<Self> {
        let file = make_slab_file(base_file_path, slab_size, 0)?;
        create_base_alias_link(base_file_path)?;
        let mut front_slab = SlabEntry::new(file, page_size)?;

        // This is the first slab so add the main header.
        let main_header = MainHeader {
            magic: MAIN_MAGIC,
            first_section_offset: page_size as u16,
            page_size: page_size as u16,
        };
        let nb_bytes = encode_into_slice(&main_header, &mut front_slab.mmap_buffer[..], standard())
            .map_err(|e| io::Error::other(format!("Failed to encode main header: {e}")))?;
        assert!(nb_bytes < page_size);
        front_slab.current_global_position = page_size; // align to the next page

        Ok(Self {
            front_slab,
            back_slabs: Vec::new(),
            base_file_path: base_file_path.to_path_buf(),
            slab_size,
            front_slab_suffix: 0,
        })
    }

    fn garbage_collect_backslabs(&mut self) {
        self.back_slabs
            .retain_mut(|slab| !slab.sections_offsets_in_flight.is_empty());
    }

    fn place_end_marker(&mut self, temporary: bool) -> CuResult<()> {
        match self.front_slab.write_end_marker(temporary) {
            Ok(_) => Ok(()),
            Err(_) => {
                // Not enough space in the current slab, roll to a new one.
                let new_slab = self.create_slab()?;
                self.back_slabs
                    .push(mem::replace(&mut self.front_slab, new_slab));
                self.front_slab.write_end_marker(temporary)
            }
        }
    }

    pub fn stats(&self) -> (usize, Vec<usize>, usize) {
        (
            self.front_slab.current_global_position,
            self.front_slab.sections_offsets_in_flight.clone(),
            self.back_slabs.len(),
        )
    }

    fn create_slab(&mut self) -> CuResult<SlabEntry> {
        let file = self
            .next_slab()
            .map_err(|e| CuError::new_with_cause("Failed to create slab file", e))?;
        SlabEntry::new(file, self.front_slab.page_size)
            .map_err(|e| CuError::new_with_cause("Failed to create slab memory map", e))
    }
}

impl Drop for MmapUnifiedLoggerWrite {
    fn drop(&mut self) {
        #[cfg(debug_assertions)]
        eprintln!("Flushing the unified Logger ... "); // Note this cannot be a structured log writing in this log.

        self.front_slab.clear_temporary_end_marker();
        if let Err(e) = self.place_end_marker(false) {
            panic!("Failed to flush the unified logger: {}", e);
        }
        self.front_slab
            .flush_until(self.front_slab.current_global_position);
        self.garbage_collect_backslabs();
        #[cfg(debug_assertions)]
        eprintln!("Unified Logger flushed."); // Note this cannot be a structured log writing in this log.
    }
}

fn open_slab_index(
    base_file_path: &Path,
    slab_index: usize,
) -> io::Result<(File, Mmap, u16, Option<MainHeader>)> {
    let mut options = OpenOptions::new();
    let options = options.read(true);

    let file_path = build_slab_path(base_file_path, slab_index)?;
    let file = options.open(&file_path).map_err(|e| {
        io::Error::new(
            e.kind(),
            format!("Failed to open slab file {}: {e}", file_path.display()),
        )
    })?;
    // SAFETY: The file is kept open for the lifetime of the mapping.
    let mmap = unsafe { Mmap::map(&file) }
        .map_err(|e| io::Error::new(e.kind(), format!("Failed to map slab file: {e}")))?;
    let mut prolog = 0u16;
    let mut maybe_main_header: Option<MainHeader> = None;
    if slab_index == 0 {
        let main_header: MainHeader;
        let _read: usize;
        (main_header, _read) = decode_from_slice(&mmap[..], standard()).map_err(|e| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Failed to decode main header: {e}"),
            )
        })?;
        if main_header.magic != MAIN_MAGIC {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Invalid magic number in main header",
            ));
        }
        prolog = main_header.first_section_offset;
        maybe_main_header = Some(main_header);
    }
    Ok((file, mmap, prolog, maybe_main_header))
}

/// A read side of the memory map based unified logger.
pub struct MmapUnifiedLoggerRead {
    base_file_path: PathBuf,
    main_header: MainHeader,
    current_mmap_buffer: Mmap,
    current_file: File,
    current_slab_index: usize,
    current_reading_position: usize,
}

/// Absolute position inside a unified log (slab index + byte offset).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LogPosition {
    pub slab_index: usize,
    pub offset: usize,
}

impl UnifiedLogRead for MmapUnifiedLoggerRead {
    fn read_next_section_type(&mut self, datalogtype: UnifiedLogType) -> CuResult<Option<Vec<u8>>> {
        // TODO: eventually implement a 0 copy of this too.
        loop {
            if self.current_reading_position >= self.current_mmap_buffer.len() {
                self.next_slab().map_err(|e| {
                    CuError::new_with_cause("Failed to read next slab, is the log complete?", e)
                })?;
            }

            let header_result = self.read_section_header();
            let header = header_result.map_err(|error| {
                CuError::new_with_cause(
                    &format!(
                        "Could not read a sections header: {}/{}:{}",
                        self.base_file_path.as_os_str().to_string_lossy(),
                        self.current_slab_index,
                        self.current_reading_position,
                    ),
                    error,
                )
            })?;

            // Reached the end of file
            if header.entry_type == UnifiedLogType::LastEntry {
                return Ok(None);
            }

            // Found a section of the requested type
            if header.entry_type == datalogtype {
                let result = Some(self.read_section_content(&header)?);
                self.current_reading_position += header.offset_to_next_section as usize;
                return Ok(result);
            }

            // Keep reading until we find the requested type
            self.current_reading_position += header.offset_to_next_section as usize;
        }
    }

    /// Reads the section from the section header pos.
    fn raw_read_section(&mut self) -> CuResult<(SectionHeader, Vec<u8>)> {
        if self.current_reading_position >= self.current_mmap_buffer.len() {
            self.next_slab().map_err(|e| {
                CuError::new_with_cause("Failed to read next slab, is the log complete?", e)
            })?;
        }

        let read_result = self.read_section_header();

        match read_result {
            Err(error) => Err(CuError::new_with_cause(
                &format!(
                    "Could not read a sections header: {}/{}:{}",
                    self.base_file_path.as_os_str().to_string_lossy(),
                    self.current_slab_index,
                    self.current_reading_position,
                ),
                error,
            )),
            Ok(header) => {
                let data = self.read_section_content(&header)?;
                self.current_reading_position += header.offset_to_next_section as usize;
                Ok((header, data))
            }
        }
    }
}

impl MmapUnifiedLoggerRead {
    pub fn new(base_file_path: &Path) -> io::Result<Self> {
        let (file, mmap, prolog, header) = open_slab_index(base_file_path, 0)?;
        let main_header = header.ok_or_else(|| {
            io::Error::new(io::ErrorKind::InvalidData, "Missing main header in slab 0")
        })?;

        Ok(Self {
            base_file_path: base_file_path.to_path_buf(),
            main_header,
            current_file: file,
            current_mmap_buffer: mmap,
            current_slab_index: 0,
            current_reading_position: prolog as usize,
        })
    }

    /// Current cursor position (start of next section header).
    pub fn position(&self) -> LogPosition {
        LogPosition {
            slab_index: self.current_slab_index,
            offset: self.current_reading_position,
        }
    }

    /// Seek to an absolute position (start of a section header).
    pub fn seek(&mut self, pos: LogPosition) -> CuResult<()> {
        if pos.slab_index != self.current_slab_index {
            let (file, mmap, _prolog, _header) =
                open_slab_index(&self.base_file_path, pos.slab_index).map_err(|e| {
                    CuError::new_with_cause(
                        &format!("Failed to open slab {} for seek", pos.slab_index),
                        e,
                    )
                })?;
            self.current_file = file;
            self.current_mmap_buffer = mmap;
            self.current_slab_index = pos.slab_index;
        }
        self.current_reading_position = pos.offset;
        Ok(())
    }

    fn next_slab(&mut self) -> io::Result<()> {
        self.current_slab_index += 1;
        let (file, mmap, prolog, _) =
            open_slab_index(&self.base_file_path, self.current_slab_index)?;
        self.current_file = file;
        self.current_mmap_buffer = mmap;
        self.current_reading_position = prolog as usize;
        Ok(())
    }

    pub fn raw_main_header(&self) -> &MainHeader {
        &self.main_header
    }

    pub fn scan_section_bytes(&mut self, datalogtype: UnifiedLogType) -> CuResult<u64> {
        let mut total = 0u64;

        loop {
            if self.current_reading_position >= self.current_mmap_buffer.len() {
                self.next_slab().map_err(|e| {
                    CuError::new_with_cause("Failed to read next slab, is the log complete?", e)
                })?;
            }

            let header = self.read_section_header()?;

            if header.entry_type == UnifiedLogType::LastEntry {
                return Ok(total);
            }

            if header.entry_type == datalogtype {
                total = total.saturating_add(header.used as u64);
            }

            self.current_reading_position += header.offset_to_next_section as usize;
        }
    }

    /// Reads the section content from the section header pos.
    fn read_section_content(&mut self, header: &SectionHeader) -> CuResult<Vec<u8>> {
        // TODO: we could optimize by asking the buffer to fill
        let mut section_data = vec![0; header.used as usize];
        let start_of_data = self.current_reading_position + header.block_size as usize;
        section_data.copy_from_slice(
            &self.current_mmap_buffer[start_of_data..start_of_data + header.used as usize],
        );

        Ok(section_data)
    }

    fn read_section_header(&mut self) -> CuResult<SectionHeader> {
        let section_header: SectionHeader;
        (section_header, _) = decode_from_slice(
            &self.current_mmap_buffer[self.current_reading_position..],
            standard(),
        )
        .map_err(|e| {
            CuError::new_with_cause(
                &format!(
                    "Could not read a sections header: {}/{}:{}",
                    self.base_file_path.as_os_str().to_string_lossy(),
                    self.current_slab_index,
                    self.current_reading_position,
                ),
                e,
            )
        })?;
        if section_header.magic != SECTION_MAGIC {
            return Err("Invalid magic number in section header".into());
        }

        Ok(section_header)
    }
}

/// This a convenience wrapper around the UnifiedLoggerRead to implement the Read trait.
pub struct UnifiedLoggerIOReader {
    logger: MmapUnifiedLoggerRead,
    log_type: UnifiedLogType,
    buffer: Vec<u8>,
    buffer_pos: usize,
}

impl UnifiedLoggerIOReader {
    pub fn new(logger: MmapUnifiedLoggerRead, log_type: UnifiedLogType) -> Self {
        Self {
            logger,
            log_type,
            buffer: Vec::new(),
            buffer_pos: 0,
        }
    }

    /// returns true if there is more data to read.
    fn fill_buffer(&mut self) -> io::Result<bool> {
        match self.logger.read_next_section_type(self.log_type) {
            Ok(Some(section)) => {
                self.buffer = section;
                self.buffer_pos = 0;
                Ok(true)
            }
            Ok(None) => Ok(false), // No more sections of this type
            Err(e) => Err(io::Error::other(e.to_string())),
        }
    }
}

impl Read for UnifiedLoggerIOReader {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.buffer_pos >= self.buffer.len() && !self.fill_buffer()? {
            // This means we hit the last section.
            return Ok(0);
        }

        // If we still have no data after trying to fill the buffer, we're at EOF
        if self.buffer_pos >= self.buffer.len() {
            return Ok(0);
        }

        // Copy as much as we can from the buffer to `buf`
        let len = std::cmp::min(buf.len(), self.buffer.len() - self.buffer_pos);
        buf[..len].copy_from_slice(&self.buffer[self.buffer_pos..self.buffer_pos + len]);
        self.buffer_pos += len;
        Ok(len)
    }
}

#[cfg(feature = "std")]
#[cfg(test)]
mod tests {
    use super::*;
    use crate::stream_write;
    use bincode::de::read::SliceReader;
    use bincode::{Decode, Encode, decode_from_reader, decode_from_slice};
    use cu29_traits::WriteStream;
    use std::path::PathBuf;
    use std::sync::{Arc, Mutex};
    use tempfile::TempDir;

    const LARGE_SLAB: usize = 100 * 1024; // 100KB
    const SMALL_SLAB: usize = 16 * 2 * 1024; // 16KB is the page size on MacOS for example

    fn make_a_logger(
        tmp_dir: &TempDir,
        slab_size: usize,
    ) -> (Arc<Mutex<MmapUnifiedLoggerWrite>>, PathBuf) {
        let file_path = tmp_dir.path().join("test.bin");
        let MmapUnifiedLogger::Write(data_logger) = MmapUnifiedLoggerBuilder::new()
            .write(true)
            .create(true)
            .file_base_name(&file_path)
            .preallocated_size(slab_size)
            .build()
            .expect("Failed to create logger")
        else {
            panic!("Failed to create logger")
        };

        (Arc::new(Mutex::new(data_logger)), file_path)
    }

    #[test]
    fn test_truncation_and_sections_creations() {
        let tmp_dir = TempDir::new().expect("could not create a tmp dir");
        let file_path = tmp_dir.path().join("test.bin");
        let _used = {
            let MmapUnifiedLogger::Write(mut logger) = MmapUnifiedLoggerBuilder::new()
                .write(true)
                .create(true)
                .file_base_name(&file_path)
                .preallocated_size(100000)
                .build()
                .expect("Failed to create logger")
            else {
                panic!("Failed to create logger")
            };
            logger
                .add_section(UnifiedLogType::StructuredLogLine, 1024)
                .unwrap();
            logger
                .add_section(UnifiedLogType::CopperList, 2048)
                .unwrap();
            let used = logger.front_slab.used();
            assert!(used < 4 * page_size::get()); // ie. 3 headers, 1 page max per
            // logger drops

            used
        };

        let _file = OpenOptions::new()
            .read(true)
            .open(tmp_dir.path().join("test_0.bin"))
            .expect("Could not reopen the file");
        // Check if we have correctly truncated the file
        // TODO: recompute this math
        //assert_eq!(
        //    file.metadata().unwrap().len(),
        //    (used + size_of::<SectionHeader>()) as u64
        //);
    }

    #[test]
    fn test_base_alias_exists_and_matches_first_slab() {
        let tmp_dir = TempDir::new().expect("could not create a tmp dir");
        let file_path = tmp_dir.path().join("test.bin");
        let _logger = MmapUnifiedLoggerBuilder::new()
            .write(true)
            .create(true)
            .file_base_name(&file_path)
            .preallocated_size(LARGE_SLAB)
            .build()
            .expect("Failed to create logger");

        let first_slab = build_slab_path(&file_path, 0).expect("Failed to build first slab path");
        assert!(file_path.exists(), "base alias does not exist");
        assert!(first_slab.exists(), "first slab does not exist");

        let alias_bytes = std::fs::read(&file_path).expect("Failed to read base alias");
        let slab_bytes = std::fs::read(&first_slab).expect("Failed to read first slab");
        assert_eq!(alias_bytes, slab_bytes);
    }

    #[test]
    fn test_one_section_self_cleaning() {
        let tmp_dir = TempDir::new().expect("could not create a tmp dir");
        let (logger, _) = make_a_logger(&tmp_dir, LARGE_SLAB);
        {
            let _stream = stream_write::<(), MmapSectionStorage>(
                logger.clone(),
                UnifiedLogType::StructuredLogLine,
                1024,
            );
            assert_eq!(
                logger
                    .lock()
                    .unwrap()
                    .front_slab
                    .sections_offsets_in_flight
                    .len(),
                1
            );
        }
        assert_eq!(
            logger
                .lock()
                .unwrap()
                .front_slab
                .sections_offsets_in_flight
                .len(),
            0
        );
        let logger = logger.lock().unwrap();
        assert_eq!(
            logger.front_slab.flushed_until_offset,
            logger.front_slab.current_global_position
        );
    }

    #[test]
    fn test_temporary_end_marker_is_created() {
        let tmp_dir = TempDir::new().expect("could not create a tmp dir");
        let (logger, _) = make_a_logger(&tmp_dir, LARGE_SLAB);
        {
            let mut stream = stream_write::<u32, MmapSectionStorage>(
                logger.clone(),
                UnifiedLogType::StructuredLogLine,
                1024,
            )
            .unwrap();
            stream.log(&42u32).unwrap();
        }

        let logger_guard = logger.lock().unwrap();
        let slab = &logger_guard.front_slab;
        let marker_start = slab
            .temporary_end_marker
            .expect("temporary end-of-log marker missing");
        let (eof_header, _) =
            decode_from_slice::<SectionHeader, _>(&slab.mmap_buffer[marker_start..], standard())
                .expect("Could not decode end-of-log marker header");
        assert_eq!(eof_header.entry_type, UnifiedLogType::LastEntry);
        assert!(eof_header.is_open);
        assert_eq!(eof_header.used, 0);
    }

    #[test]
    fn test_final_end_marker_is_not_temporary() {
        let tmp_dir = TempDir::new().expect("could not create a tmp dir");
        let (logger, f) = make_a_logger(&tmp_dir, LARGE_SLAB);
        {
            let mut stream = stream_write::<u32, MmapSectionStorage>(
                logger.clone(),
                UnifiedLogType::CopperList,
                1024,
            )
            .unwrap();
            stream.log(&1u32).unwrap();
        }
        drop(logger);

        let MmapUnifiedLogger::Read(mut reader) = MmapUnifiedLoggerBuilder::new()
            .file_base_name(&f)
            .build()
            .expect("Failed to build reader")
        else {
            panic!("Failed to create reader");
        };

        loop {
            let (header, _data) = reader
                .raw_read_section()
                .expect("Failed to read section while searching for EOF");
            if header.entry_type == UnifiedLogType::LastEntry {
                assert!(!header.is_open);
                break;
            }
        }
    }

    #[test]
    fn test_two_sections_self_cleaning_in_order() {
        let tmp_dir = TempDir::new().expect("could not create a tmp dir");
        let (logger, _) = make_a_logger(&tmp_dir, LARGE_SLAB);
        let s1 = stream_write::<(), MmapSectionStorage>(
            logger.clone(),
            UnifiedLogType::StructuredLogLine,
            1024,
        );
        assert_eq!(
            logger
                .lock()
                .unwrap()
                .front_slab
                .sections_offsets_in_flight
                .len(),
            1
        );
        let s2 = stream_write::<(), MmapSectionStorage>(
            logger.clone(),
            UnifiedLogType::StructuredLogLine,
            1024,
        );
        assert_eq!(
            logger
                .lock()
                .unwrap()
                .front_slab
                .sections_offsets_in_flight
                .len(),
            2
        );
        drop(s2);
        assert_eq!(
            logger
                .lock()
                .unwrap()
                .front_slab
                .sections_offsets_in_flight
                .len(),
            1
        );
        drop(s1);
        let lg = logger.lock().unwrap();
        assert_eq!(lg.front_slab.sections_offsets_in_flight.len(), 0);
        assert_eq!(
            lg.front_slab.flushed_until_offset,
            lg.front_slab.current_global_position
        );
    }

    #[test]
    fn test_two_sections_self_cleaning_out_of_order() {
        let tmp_dir = TempDir::new().expect("could not create a tmp dir");
        let (logger, _) = make_a_logger(&tmp_dir, LARGE_SLAB);
        let s1 = stream_write::<(), MmapSectionStorage>(
            logger.clone(),
            UnifiedLogType::StructuredLogLine,
            1024,
        );
        assert_eq!(
            logger
                .lock()
                .unwrap()
                .front_slab
                .sections_offsets_in_flight
                .len(),
            1
        );
        let s2 = stream_write::<(), MmapSectionStorage>(
            logger.clone(),
            UnifiedLogType::StructuredLogLine,
            1024,
        );
        assert_eq!(
            logger
                .lock()
                .unwrap()
                .front_slab
                .sections_offsets_in_flight
                .len(),
            2
        );
        drop(s1);
        assert_eq!(
            logger
                .lock()
                .unwrap()
                .front_slab
                .sections_offsets_in_flight
                .len(),
            1
        );
        drop(s2);
        let lg = logger.lock().unwrap();
        assert_eq!(lg.front_slab.sections_offsets_in_flight.len(), 0);
        assert_eq!(
            lg.front_slab.flushed_until_offset,
            lg.front_slab.current_global_position
        );
    }

    #[test]
    fn test_closed_section_flushes_behind_open_earlier_section() {
        let tmp_dir = TempDir::new().expect("could not create a tmp dir");
        let (logger, _) = make_a_logger(&tmp_dir, LARGE_SLAB);
        let s1 = stream_write::<(), MmapSectionStorage>(
            logger.clone(),
            UnifiedLogType::StructuredLogLine,
            1024,
        )
        .unwrap();
        {
            let mut s2 = stream_write::<u32, MmapSectionStorage>(
                logger.clone(),
                UnifiedLogType::CopperList,
                1024,
            )
            .unwrap();
            s2.log(&42u32).unwrap();
        }

        let logger_guard = logger.lock().unwrap();
        assert_eq!(logger_guard.front_slab.sections_offsets_in_flight.len(), 1);
        assert!(
            logger_guard.front_slab.flushed_until_offset
                < logger_guard.front_slab.current_global_position
        );
        assert_eq!(logger_guard.front_slab.pending_closed_bytes(), 0);
        drop(logger_guard);
        drop(s1);
    }

    #[test]
    fn test_write_then_read_one_section() {
        let tmp_dir = TempDir::new().expect("could not create a tmp dir");
        let (logger, f) = make_a_logger(&tmp_dir, LARGE_SLAB);
        {
            let mut stream =
                stream_write(logger.clone(), UnifiedLogType::StructuredLogLine, 1024).unwrap();
            stream.log(&1u32).unwrap();
            stream.log(&2u32).unwrap();
            stream.log(&3u32).unwrap();
        }
        drop(logger);
        let MmapUnifiedLogger::Read(mut dl) = MmapUnifiedLoggerBuilder::new()
            .file_base_name(&f)
            .build()
            .expect("Failed to build logger")
        else {
            panic!("Failed to build logger");
        };
        let section = dl
            .read_next_section_type(UnifiedLogType::StructuredLogLine)
            .expect("Failed to read section");
        assert!(section.is_some());
        let section = section.unwrap();
        let mut reader = SliceReader::new(&section[..]);
        let v1: u32 = decode_from_reader(&mut reader, standard()).unwrap();
        let v2: u32 = decode_from_reader(&mut reader, standard()).unwrap();
        let v3: u32 = decode_from_reader(&mut reader, standard()).unwrap();
        assert_eq!(v1, 1);
        assert_eq!(v2, 2);
        assert_eq!(v3, 3);
    }

    #[cfg(feature = "mmap-fsync")]
    #[test]
    fn test_fsync_feature_syncs_on_section_flush() {
        let tmp_dir = TempDir::new().expect("could not create a tmp dir");
        let (logger, _) = make_a_logger(&tmp_dir, LARGE_SLAB);
        {
            let mut stream =
                stream_write(logger.clone(), UnifiedLogType::StructuredLogLine, 1024).unwrap();
            stream.log(&1u32).unwrap();
        }

        let logger = logger.lock().unwrap();
        assert!(
            logger.front_slab.sync_call_count > 0,
            "expected mmap-fsync to issue at least one sync_all call"
        );
    }

    /// Mimic a basic CopperList implementation.

    #[derive(Debug, Encode, Decode)]
    enum CopperListStateMock {
        Free,
        ProcessingTasks,
        BeingSerialized,
    }

    #[derive(Encode, Decode)]
    struct CopperList<P: bincode::enc::Encode> {
        state: CopperListStateMock,
        payload: P, // This is generated from the runtime.
    }

    #[test]
    fn test_copperlist_list_like_logging() {
        let tmp_dir = TempDir::new().expect("could not create a tmp dir");
        let (logger, f) = make_a_logger(&tmp_dir, LARGE_SLAB);
        {
            let mut stream =
                stream_write(logger.clone(), UnifiedLogType::CopperList, 1024).unwrap();
            let cl0 = CopperList {
                state: CopperListStateMock::Free,
                payload: (1u32, 2u32, 3u32),
            };
            let cl1 = CopperList {
                state: CopperListStateMock::ProcessingTasks,
                payload: (4u32, 5u32, 6u32),
            };
            stream.log(&cl0).unwrap();
            stream.log(&cl1).unwrap();
        }
        drop(logger);

        let MmapUnifiedLogger::Read(mut dl) = MmapUnifiedLoggerBuilder::new()
            .file_base_name(&f)
            .build()
            .expect("Failed to build logger")
        else {
            panic!("Failed to build logger");
        };
        let section = dl
            .read_next_section_type(UnifiedLogType::CopperList)
            .expect("Failed to read section");
        assert!(section.is_some());
        let section = section.unwrap();

        let mut reader = SliceReader::new(&section[..]);
        let cl0: CopperList<(u32, u32, u32)> = decode_from_reader(&mut reader, standard()).unwrap();
        let cl1: CopperList<(u32, u32, u32)> = decode_from_reader(&mut reader, standard()).unwrap();
        assert_eq!(cl0.payload.1, 2);
        assert_eq!(cl1.payload.2, 6);
    }

    #[test]
    fn test_multi_slab_end2end() {
        let tmp_dir = TempDir::new().expect("could not create a tmp dir");
        let (logger, f) = make_a_logger(&tmp_dir, SMALL_SLAB);
        {
            let mut stream =
                stream_write(logger.clone(), UnifiedLogType::CopperList, 1024).unwrap();
            let cl0 = CopperList {
                state: CopperListStateMock::Free,
                payload: (1u32, 2u32, 3u32),
            };
            // large enough so we are sure to create a few slabs
            for _ in 0..10000 {
                stream.log(&cl0).unwrap();
            }
        }
        drop(logger);

        let MmapUnifiedLogger::Read(mut dl) = MmapUnifiedLoggerBuilder::new()
            .file_base_name(&f)
            .build()
            .expect("Failed to build logger")
        else {
            panic!("Failed to build logger");
        };
        let mut total_readback = 0;
        loop {
            let section = dl.read_next_section_type(UnifiedLogType::CopperList);
            if section.is_err() {
                break;
            }
            let section = section.unwrap();
            if section.is_none() {
                break;
            }
            let section = section.unwrap();

            let mut reader = SliceReader::new(&section[..]);
            loop {
                let maybe_cl: Result<CopperList<(u32, u32, u32)>, _> =
                    decode_from_reader(&mut reader, standard());
                if maybe_cl.is_ok() {
                    total_readback += 1;
                } else {
                    break;
                }
            }
        }
        assert_eq!(total_readback, 10000);
    }
}