oxirs-tdb 0.3.1

Apache Jena TDB/TDB2 compatible RDF storage engine with B+Tree indexes
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
//! Continuous WAL Shipping for Disaster Recovery
//!
//! Production Feature: Continuous WAL File Shipping
//!
//! This module provides continuous WAL shipping capabilities for:
//! - Disaster recovery and standby servers
//! - Geographic replication
//! - Point-in-time recovery across multiple locations
//! - Automated failover support
//!
//! ## Architecture
//!
//! WAL shipping continuously monitors for new WAL files and ships them to
//! configured destinations (filesystem, network shares, cloud storage, etc.).
//! This enables hot standby servers and disaster recovery scenarios.
//!
//! ## Usage
//!
//! ```rust,ignore
//! use oxirs_tdb::wal_shipping::{WalShipper, ShippingConfig, ShippingDestination};
//!
//! // Configure shipping destinations
//! let config = ShippingConfig {
//!     destinations: vec![
//!         ShippingDestination::FileSystem {
//!             path: "/standby/wal".into(),
//!             sync_interval: Duration::from_secs(10),
//!         },
//!     ],
//!     ..Default::default()
//! };
//!
//! // Create shipper
//! let shipper = WalShipper::new(config)?;
//!
//! // Start continuous shipping
//! shipper.start()?;
//!
//! // WAL files are automatically shipped to all destinations
//! ```

use crate::error::{Result, TdbError};
use parking_lot::RwLock;
use std::collections::{HashMap, VecDeque};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime};

/// Shipping destination type
#[derive(Debug, Clone)]
pub enum ShippingDestination {
    /// Local filesystem destination
    FileSystem {
        /// Destination path
        path: PathBuf,
        /// Sync interval
        sync_interval: Duration,
    },
    /// Network share (NFS, CIFS, etc.)
    NetworkShare {
        /// Mount point or UNC path
        path: PathBuf,
        /// Sync interval
        sync_interval: Duration,
    },
    /// Custom destination (future: S3, GCS, Azure, etc.)
    Custom {
        /// Custom destination identifier
        id: String,
        /// Configuration parameters
        params: HashMap<String, String>,
    },
}

impl ShippingDestination {
    /// Get destination identifier
    pub fn id(&self) -> String {
        match self {
            ShippingDestination::FileSystem { path, .. } => {
                format!("fs:{}", path.display())
            }
            ShippingDestination::NetworkShare { path, .. } => {
                format!("net:{}", path.display())
            }
            ShippingDestination::Custom { id, .. } => id.clone(),
        }
    }

    /// Get sync interval
    pub fn sync_interval(&self) -> Duration {
        match self {
            ShippingDestination::FileSystem { sync_interval, .. } => *sync_interval,
            ShippingDestination::NetworkShare { sync_interval, .. } => *sync_interval,
            ShippingDestination::Custom { .. } => Duration::from_secs(30),
        }
    }
}

/// Shipping configuration
#[derive(Debug, Clone)]
pub struct ShippingConfig {
    /// List of shipping destinations
    pub destinations: Vec<ShippingDestination>,
    /// Enable continuous shipping
    pub enable_shipping: bool,
    /// Compress WAL files during shipping
    pub compress_during_shipping: bool,
    /// Verify shipped files
    pub verify_after_shipping: bool,
    /// Maximum retry attempts for failed shipments
    pub max_retry_attempts: usize,
    /// Retry delay
    pub retry_delay: Duration,
    /// Shipping queue size
    pub queue_size: usize,
    /// WAL source directory
    pub wal_source_dir: PathBuf,
}

impl Default for ShippingConfig {
    fn default() -> Self {
        Self {
            destinations: Vec::new(),
            enable_shipping: false,
            compress_during_shipping: true,
            verify_after_shipping: true,
            max_retry_attempts: 3,
            retry_delay: Duration::from_secs(10),
            queue_size: 100,
            wal_source_dir: PathBuf::from("wal"),
        }
    }
}

/// Shipping status for a WAL file
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShippingStatus {
    /// Pending shipment
    Pending,
    /// Currently shipping
    Shipping,
    /// Successfully shipped
    Shipped,
    /// Failed to ship
    Failed,
    /// Retrying after failure
    Retrying,
}

/// Shipping record for a WAL file
#[derive(Debug, Clone)]
pub struct ShippingRecord {
    /// WAL file name
    pub file_name: String,
    /// WAL file path
    pub file_path: PathBuf,
    /// File size
    pub file_size: u64,
    /// LSN range [start, end]
    pub lsn_range: (u64, u64),
    /// Shipping status per destination
    pub destination_status: HashMap<String, (ShippingStatus, Option<String>)>,
    /// Retry counts per destination
    pub retry_counts: HashMap<String, usize>,
    /// Created timestamp
    pub created_at: SystemTime,
    /// Last shipping attempt
    pub last_attempt: Option<SystemTime>,
}

/// WAL shipping statistics
#[derive(Debug, Clone, Default)]
pub struct ShippingStats {
    /// Total files shipped
    pub files_shipped: u64,
    /// Total bytes shipped
    pub bytes_shipped: u64,
    /// Pending shipments
    pub pending_shipments: usize,
    /// Failed shipments
    pub failed_shipments: u64,
    /// Retry attempts
    pub retry_attempts: u64,
    /// Average shipping time (milliseconds)
    pub avg_shipping_time_ms: u64,
    /// Last successful shipment
    pub last_shipment_time: Option<SystemTime>,
}

/// WAL shipper for continuous archiving
pub struct WalShipper {
    /// Configuration
    config: ShippingConfig,
    /// Shipping queue
    shipping_queue: Arc<RwLock<VecDeque<ShippingRecord>>>,
    /// Shipped files index
    shipped_files: Arc<RwLock<HashMap<String, ShippingRecord>>>,
    /// Whether shipper is active
    active: Arc<AtomicBool>,
    /// Statistics
    stats: Arc<RwLock<ShippingStats>>,
    /// Total files shipped counter
    total_shipped: Arc<AtomicU64>,
    /// Total bytes shipped counter
    total_bytes_shipped: Arc<AtomicU64>,
    /// Failed shipments counter
    failed_shipments: Arc<AtomicU64>,
}

impl WalShipper {
    /// Create a new WAL shipper
    pub fn new(config: ShippingConfig) -> Result<Self> {
        // Validate configuration
        if config.enable_shipping && config.destinations.is_empty() {
            return Err(TdbError::Other(
                "Shipping enabled but no destinations configured".to_string(),
            ));
        }

        // Create destination directories
        for dest in &config.destinations {
            match dest {
                ShippingDestination::FileSystem { path, .. }
                | ShippingDestination::NetworkShare { path, .. } => {
                    fs::create_dir_all(path).map_err(|e| {
                        TdbError::Other(format!("Failed to create destination directory: {}", e))
                    })?;
                }
                ShippingDestination::Custom { .. } => {
                    // Custom destinations handle their own setup
                }
            }
        }

        Ok(Self {
            config,
            shipping_queue: Arc::new(RwLock::new(VecDeque::new())),
            shipped_files: Arc::new(RwLock::new(HashMap::new())),
            active: Arc::new(AtomicBool::new(false)),
            stats: Arc::new(RwLock::new(ShippingStats::default())),
            total_shipped: Arc::new(AtomicU64::new(0)),
            total_bytes_shipped: Arc::new(AtomicU64::new(0)),
            failed_shipments: Arc::new(AtomicU64::new(0)),
        })
    }

    /// Start continuous shipping
    pub fn start(&self) -> Result<()> {
        if !self.config.enable_shipping {
            return Err(TdbError::Other(
                "Shipping is not enabled in configuration".to_string(),
            ));
        }

        if self.active.load(Ordering::Acquire) {
            return Err(TdbError::Other("Shipper is already active".to_string()));
        }

        self.active.store(true, Ordering::Release);
        Ok(())
    }

    /// Stop continuous shipping
    pub fn stop(&self) -> Result<()> {
        self.active.store(false, Ordering::Release);
        Ok(())
    }

    /// Check if shipper is active
    pub fn is_active(&self) -> bool {
        self.active.load(Ordering::Acquire)
    }

    /// Ship a WAL file to all configured destinations
    pub fn ship_wal_file(&self, file_path: impl AsRef<Path>, lsn_range: (u64, u64)) -> Result<()> {
        let file_path = file_path.as_ref();

        if !file_path.exists() {
            return Err(TdbError::Other(format!(
                "WAL file does not exist: {:?}",
                file_path
            )));
        }

        // Get file metadata
        let file_name = file_path
            .file_name()
            .ok_or_else(|| TdbError::Other("Invalid file path".to_string()))?
            .to_string_lossy()
            .to_string();

        let metadata = fs::metadata(file_path).map_err(TdbError::Io)?;
        let file_size = metadata.len();

        // Create shipping record
        let mut destination_status = HashMap::new();
        let mut retry_counts = HashMap::new();

        for dest in &self.config.destinations {
            destination_status.insert(dest.id(), (ShippingStatus::Pending, None));
            retry_counts.insert(dest.id(), 0);
        }

        let record = ShippingRecord {
            file_name: file_name.clone(),
            file_path: file_path.to_path_buf(),
            file_size,
            lsn_range,
            destination_status,
            retry_counts,
            created_at: SystemTime::now(),
            last_attempt: None,
        };

        // Add to shipping queue
        {
            let mut queue = self.shipping_queue.write();
            if queue.len() >= self.config.queue_size {
                return Err(TdbError::Other(format!(
                    "Shipping queue full (max: {})",
                    self.config.queue_size
                )));
            }
            queue.push_back(record.clone());
        }

        // Process shipment immediately if active
        if self.is_active() {
            self.process_shipment(&file_name)?;
        }

        Ok(())
    }

    /// Process a pending shipment
    fn process_shipment(&self, file_name: &str) -> Result<()> {
        let start_time = SystemTime::now();

        // Get record from queue
        let mut record = {
            let queue = self.shipping_queue.write();
            queue
                .iter()
                .find(|r| r.file_name == file_name)
                .cloned()
                .ok_or_else(|| TdbError::Other(format!("File not in queue: {}", file_name)))?
        };

        // Ship to each destination
        for dest in &self.config.destinations {
            let dest_id = dest.id();
            let status = record.destination_status.get(&dest_id).map(|(s, _)| *s);

            // Skip if already shipped
            if status == Some(ShippingStatus::Shipped) {
                continue;
            }

            // Update status to shipping
            record
                .destination_status
                .insert(dest_id.clone(), (ShippingStatus::Shipping, None));

            // Perform shipment
            let result = self.ship_to_destination(&record, dest);

            match result {
                Ok(()) => {
                    // Success
                    record
                        .destination_status
                        .insert(dest_id.clone(), (ShippingStatus::Shipped, None));
                }
                Err(e) => {
                    // Failure
                    let retry_count = record.retry_counts.get(&dest_id).copied().unwrap_or(0);

                    if retry_count < self.config.max_retry_attempts {
                        // Schedule retry
                        record.destination_status.insert(
                            dest_id.clone(),
                            (ShippingStatus::Retrying, Some(e.to_string())),
                        );
                        record.retry_counts.insert(dest_id.clone(), retry_count + 1);
                    } else {
                        // Max retries exceeded
                        record.destination_status.insert(
                            dest_id.clone(),
                            (ShippingStatus::Failed, Some(e.to_string())),
                        );
                        self.failed_shipments.fetch_add(1, Ordering::Relaxed);
                    }
                }
            }
        }

        record.last_attempt = Some(SystemTime::now());

        // Check if all destinations shipped
        let all_shipped = record
            .destination_status
            .values()
            .all(|(status, _)| *status == ShippingStatus::Shipped);

        if all_shipped {
            // Remove from queue and add to shipped files
            {
                let mut queue = self.shipping_queue.write();
                queue.retain(|r| r.file_name != file_name);
            }

            self.shipped_files
                .write()
                .insert(file_name.to_string(), record.clone());

            // Update statistics
            self.total_shipped.fetch_add(1, Ordering::Relaxed);
            self.total_bytes_shipped
                .fetch_add(record.file_size, Ordering::Relaxed);

            let duration = start_time
                .elapsed()
                .unwrap_or(Duration::from_secs(0))
                .as_millis() as u64;

            let mut stats = self.stats.write();
            stats.files_shipped += 1;
            stats.bytes_shipped += record.file_size;
            stats.last_shipment_time = Some(SystemTime::now());

            // Update average shipping time
            if stats.files_shipped == 1 {
                stats.avg_shipping_time_ms = duration;
            } else {
                stats.avg_shipping_time_ms =
                    (stats.avg_shipping_time_ms * (stats.files_shipped - 1) + duration)
                        / stats.files_shipped;
            }
        }

        Ok(())
    }

    /// Ship a file to a specific destination
    fn ship_to_destination(
        &self,
        record: &ShippingRecord,
        destination: &ShippingDestination,
    ) -> Result<()> {
        match destination {
            ShippingDestination::FileSystem { path, .. }
            | ShippingDestination::NetworkShare { path, .. } => {
                let dest_path = path.join(&record.file_name);

                // Copy file to destination
                fs::copy(&record.file_path, &dest_path).map_err(|e| {
                    TdbError::Other(format!("Failed to copy file to destination: {}", e))
                })?;

                // Verify if enabled
                if self.config.verify_after_shipping {
                    self.verify_shipped_file(&record.file_path, &dest_path)?;
                }

                Ok(())
            }
            ShippingDestination::Custom { .. } => {
                // Custom destinations would implement their own shipping logic
                Err(TdbError::Other(
                    "Custom destinations not yet implemented".to_string(),
                ))
            }
        }
    }

    /// Verify a shipped file matches the original
    fn verify_shipped_file(&self, original: &Path, shipped: &Path) -> Result<()> {
        let original_meta = fs::metadata(original).map_err(TdbError::Io)?;
        let shipped_meta = fs::metadata(shipped).map_err(TdbError::Io)?;

        if original_meta.len() != shipped_meta.len() {
            return Err(TdbError::Other(format!(
                "File size mismatch: original={}, shipped={}",
                original_meta.len(),
                shipped_meta.len()
            )));
        }

        // Could add checksum verification here
        Ok(())
    }

    /// Get shipping statistics
    pub fn get_stats(&self) -> ShippingStats {
        let mut stats = self.stats.read().clone();
        stats.pending_shipments = self.shipping_queue.read().len();
        stats.failed_shipments = self.failed_shipments.load(Ordering::Relaxed);
        stats
    }

    /// List pending shipments
    pub fn list_pending(&self) -> Vec<ShippingRecord> {
        self.shipping_queue.read().iter().cloned().collect()
    }

    /// List shipped files
    pub fn list_shipped(&self) -> Vec<ShippingRecord> {
        self.shipped_files.read().values().cloned().collect()
    }

    /// Get shipping record by file name
    pub fn get_record(&self, file_name: &str) -> Option<ShippingRecord> {
        // Check shipped files first
        if let Some(record) = self.shipped_files.read().get(file_name) {
            return Some(record.clone());
        }

        // Check queue
        self.shipping_queue
            .read()
            .iter()
            .find(|r| r.file_name == file_name)
            .cloned()
    }

    /// Retry failed shipments
    pub fn retry_failed(&self) -> Result<usize> {
        let pending: Vec<String> = self
            .shipping_queue
            .read()
            .iter()
            .filter(|r| {
                r.destination_status.values().any(|(status, _)| {
                    *status == ShippingStatus::Failed || *status == ShippingStatus::Retrying
                })
            })
            .map(|r| r.file_name.clone())
            .collect();

        for file_name in &pending {
            self.process_shipment(file_name)?;
        }

        Ok(pending.len())
    }

    /// Clear shipped files older than retention period
    pub fn cleanup_old_records(&self, retention: Duration) -> Result<usize> {
        let cutoff = SystemTime::now()
            .checked_sub(retention)
            .ok_or_else(|| TdbError::Other("Invalid retention period".to_string()))?;

        let mut shipped = self.shipped_files.write();
        let original_count = shipped.len();

        shipped.retain(|_, record| record.created_at >= cutoff);

        Ok(original_count - shipped.len())
    }
}

impl Default for WalShipper {
    fn default() -> Self {
        Self::new(ShippingConfig::default()).expect("Default config should be valid")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;

    #[test]
    fn test_create_shipper() {
        let temp_dir = env::temp_dir().join("oxirs_tdb_shipper_test");
        fs::remove_dir_all(&temp_dir).ok();

        let dest_dir = temp_dir.join("destination");

        let config = ShippingConfig {
            destinations: vec![ShippingDestination::FileSystem {
                path: dest_dir.clone(),
                sync_interval: Duration::from_secs(10),
            }],
            enable_shipping: true,
            ..Default::default()
        };

        let shipper = WalShipper::new(config).unwrap();
        assert!(!shipper.is_active());

        fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    fn test_start_stop_shipper() {
        let temp_dir = env::temp_dir().join("oxirs_tdb_shipper_startstop_test");
        fs::remove_dir_all(&temp_dir).ok();

        let dest_dir = temp_dir.join("destination");

        let config = ShippingConfig {
            destinations: vec![ShippingDestination::FileSystem {
                path: dest_dir,
                sync_interval: Duration::from_secs(10),
            }],
            enable_shipping: true,
            ..Default::default()
        };

        let shipper = WalShipper::new(config).unwrap();
        assert!(!shipper.is_active());

        shipper.start().unwrap();
        assert!(shipper.is_active());

        shipper.stop().unwrap();
        assert!(!shipper.is_active());

        fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    fn test_ship_wal_file() {
        let temp_dir = env::temp_dir().join("oxirs_tdb_ship_file_test");
        fs::remove_dir_all(&temp_dir).ok();

        let source_dir = temp_dir.join("source");
        let dest_dir = temp_dir.join("destination");

        fs::create_dir_all(&source_dir).unwrap();

        // Create test WAL file
        let wal_file = source_dir.join("wal_001.log");
        fs::write(&wal_file, b"WAL data for shipping").unwrap();

        let config = ShippingConfig {
            destinations: vec![ShippingDestination::FileSystem {
                path: dest_dir.clone(),
                sync_interval: Duration::from_secs(10),
            }],
            enable_shipping: true,
            wal_source_dir: source_dir.clone(),
            ..Default::default()
        };

        let shipper = WalShipper::new(config).unwrap();
        shipper.start().unwrap();

        // Ship the file
        shipper.ship_wal_file(&wal_file, (1, 100)).unwrap();

        // Verify file was shipped
        let shipped_file = dest_dir.join("wal_001.log");
        assert!(shipped_file.exists());

        let shipped_data = fs::read_to_string(&shipped_file).unwrap();
        assert_eq!(shipped_data, "WAL data for shipping");

        // Check statistics
        let stats = shipper.get_stats();
        assert_eq!(stats.files_shipped, 1);
        assert!(stats.bytes_shipped > 0);

        fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    fn test_multiple_destinations() {
        let temp_dir = env::temp_dir().join("oxirs_tdb_multi_dest_test");
        fs::remove_dir_all(&temp_dir).ok();

        let source_dir = temp_dir.join("source");
        let dest1 = temp_dir.join("dest1");
        let dest2 = temp_dir.join("dest2");

        fs::create_dir_all(&source_dir).unwrap();

        let wal_file = source_dir.join("wal_002.log");
        fs::write(&wal_file, b"Multi-destination WAL").unwrap();

        let config = ShippingConfig {
            destinations: vec![
                ShippingDestination::FileSystem {
                    path: dest1.clone(),
                    sync_interval: Duration::from_secs(10),
                },
                ShippingDestination::FileSystem {
                    path: dest2.clone(),
                    sync_interval: Duration::from_secs(10),
                },
            ],
            enable_shipping: true,
            ..Default::default()
        };

        let shipper = WalShipper::new(config).unwrap();
        shipper.start().unwrap();

        shipper.ship_wal_file(&wal_file, (1, 100)).unwrap();

        // Verify shipped to both destinations
        assert!(dest1.join("wal_002.log").exists());
        assert!(dest2.join("wal_002.log").exists());

        let stats = shipper.get_stats();
        assert_eq!(stats.files_shipped, 1);

        fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    fn test_shipping_queue() {
        let temp_dir = env::temp_dir().join("oxirs_tdb_queue_test");
        fs::remove_dir_all(&temp_dir).ok();

        let source_dir = temp_dir.join("source");
        let dest_dir = temp_dir.join("destination");

        fs::create_dir_all(&source_dir).unwrap();

        let config = ShippingConfig {
            destinations: vec![ShippingDestination::FileSystem {
                path: dest_dir,
                sync_interval: Duration::from_secs(10),
            }],
            enable_shipping: false, // Don't auto-ship
            queue_size: 5,
            ..Default::default()
        };

        let shipper = WalShipper::new(config).unwrap();

        // Add files to queue
        for i in 1..=3 {
            let wal_file = source_dir.join(format!("wal_{:03}.log", i));
            fs::write(&wal_file, format!("WAL {}", i)).unwrap();

            shipper
                .ship_wal_file(&wal_file, (i as u64, i as u64 * 100))
                .unwrap();
        }

        let pending = shipper.list_pending();
        assert_eq!(pending.len(), 3);

        fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    fn test_shipping_verification() {
        let temp_dir = env::temp_dir().join("oxirs_tdb_verify_test");
        fs::remove_dir_all(&temp_dir).ok();

        let source_dir = temp_dir.join("source");
        let dest_dir = temp_dir.join("destination");

        fs::create_dir_all(&source_dir).unwrap();

        let wal_file = source_dir.join("wal_verify.log");
        fs::write(&wal_file, b"Verified WAL data").unwrap();

        let config = ShippingConfig {
            destinations: vec![ShippingDestination::FileSystem {
                path: dest_dir.clone(),
                sync_interval: Duration::from_secs(10),
            }],
            enable_shipping: true,
            verify_after_shipping: true, // Enable verification
            ..Default::default()
        };

        let shipper = WalShipper::new(config).unwrap();
        shipper.start().unwrap();

        shipper.ship_wal_file(&wal_file, (1, 100)).unwrap();

        assert!(dest_dir.join("wal_verify.log").exists());

        fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    fn test_get_shipping_record() {
        let temp_dir = env::temp_dir().join("oxirs_tdb_record_test");
        fs::remove_dir_all(&temp_dir).ok();

        let source_dir = temp_dir.join("source");
        let dest_dir = temp_dir.join("destination");

        fs::create_dir_all(&source_dir).unwrap();

        let wal_file = source_dir.join("wal_record.log");
        fs::write(&wal_file, b"Record data").unwrap();

        let config = ShippingConfig {
            destinations: vec![ShippingDestination::FileSystem {
                path: dest_dir,
                sync_interval: Duration::from_secs(10),
            }],
            enable_shipping: true,
            ..Default::default()
        };

        let shipper = WalShipper::new(config).unwrap();
        shipper.start().unwrap();

        shipper.ship_wal_file(&wal_file, (10, 200)).unwrap();

        let record = shipper.get_record("wal_record.log").unwrap();
        assert_eq!(record.lsn_range, (10, 200));
        assert!(record.file_size > 0);

        fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    fn test_destination_id() {
        let dest = ShippingDestination::FileSystem {
            path: PathBuf::from("/test/path"),
            sync_interval: Duration::from_secs(10),
        };

        assert!(dest.id().contains("/test/path"));

        let net_dest = ShippingDestination::NetworkShare {
            path: PathBuf::from("//server/share"),
            sync_interval: Duration::from_secs(30),
        };

        assert!(net_dest.id().contains("//server/share"));
    }

    #[test]
    fn test_shipping_stats() {
        let temp_dir = env::temp_dir().join("oxirs_tdb_stats_test");
        fs::remove_dir_all(&temp_dir).ok();

        let source_dir = temp_dir.join("source");
        let dest_dir = temp_dir.join("destination");

        fs::create_dir_all(&source_dir).unwrap();

        let wal_file = source_dir.join("wal_stats.log");
        fs::write(&wal_file, b"Stats test data").unwrap();

        let config = ShippingConfig {
            destinations: vec![ShippingDestination::FileSystem {
                path: dest_dir,
                sync_interval: Duration::from_secs(10),
            }],
            enable_shipping: true,
            ..Default::default()
        };

        let shipper = WalShipper::new(config).unwrap();
        shipper.start().unwrap();

        shipper.ship_wal_file(&wal_file, (1, 100)).unwrap();

        let stats = shipper.get_stats();
        assert_eq!(stats.files_shipped, 1);
        assert!(stats.bytes_shipped > 0);
        assert_eq!(stats.pending_shipments, 0);
        assert!(stats.last_shipment_time.is_some());

        fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    fn test_list_shipped() {
        let temp_dir = env::temp_dir().join("oxirs_tdb_list_shipped_test");
        fs::remove_dir_all(&temp_dir).ok();

        let source_dir = temp_dir.join("source");
        let dest_dir = temp_dir.join("destination");

        fs::create_dir_all(&source_dir).unwrap();

        let config = ShippingConfig {
            destinations: vec![ShippingDestination::FileSystem {
                path: dest_dir,
                sync_interval: Duration::from_secs(10),
            }],
            enable_shipping: true,
            ..Default::default()
        };

        let shipper = WalShipper::new(config).unwrap();
        shipper.start().unwrap();

        // Ship multiple files
        for i in 1..=3 {
            let wal_file = source_dir.join(format!("wal_{:03}.log", i));
            fs::write(&wal_file, format!("WAL {}", i)).unwrap();
            shipper
                .ship_wal_file(&wal_file, (i as u64, i as u64 * 100))
                .unwrap();
        }

        let shipped = shipper.list_shipped();
        assert_eq!(shipped.len(), 3);

        fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    fn test_cleanup_old_records() {
        let temp_dir = env::temp_dir().join("oxirs_tdb_cleanup_test");
        fs::remove_dir_all(&temp_dir).ok();

        let source_dir = temp_dir.join("source");
        let dest_dir = temp_dir.join("destination");

        fs::create_dir_all(&source_dir).unwrap();

        let config = ShippingConfig {
            destinations: vec![ShippingDestination::FileSystem {
                path: dest_dir,
                sync_interval: Duration::from_secs(10),
            }],
            enable_shipping: true,
            ..Default::default()
        };

        let shipper = WalShipper::new(config).unwrap();
        shipper.start().unwrap();

        // Ship a file
        let wal_file = source_dir.join("wal_old.log");
        fs::write(&wal_file, b"Old WAL").unwrap();
        shipper.ship_wal_file(&wal_file, (1, 100)).unwrap();

        // Cleanup with very short retention (should remove nothing since file just created)
        let removed = shipper
            .cleanup_old_records(Duration::from_secs(3600))
            .unwrap();
        assert_eq!(removed, 0);

        fs::remove_dir_all(&temp_dir).ok();
    }
}