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
//! Store parameters and configuration builder
//!
//! Provides comprehensive configuration management inspired by Apache Jena TDB2's StoreParams.
//! Supports:
//! - Builder pattern for flexible configuration
//! - Parameter validation and constraints
//! - Serialization/deserialization for configuration files
//! - Default presets (development, production, performance)
//! - Parameter inheritance and overlays

use crate::error::{Result, TdbError};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// Store parameters containing all configuration options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoreParams {
    // Storage configuration
    /// Directory for storing RDF data
    pub data_dir: PathBuf,
    /// Page size in bytes (must be power of 2)
    pub page_size: usize,
    /// Buffer pool size (number of pages to cache)
    pub buffer_pool_size: usize,

    // Index configuration
    /// Enable Subject-Predicate-Object index
    pub enable_spo_index: bool,
    /// Enable Predicate-Object-Subject index
    pub enable_pos_index: bool,
    /// Enable Object-Subject-Predicate index
    pub enable_osp_index: bool,
    /// Enable quad (named graph) indexes
    pub enable_quad_indexes: bool,

    // Dictionary configuration
    /// Enable inline storage of small values
    pub enable_inline_values: bool,
    /// Enable prefix compression for URIs
    pub enable_prefix_compression: bool,
    /// Dictionary cache size (number of entries)
    pub dictionary_cache_size: usize,

    // Transaction configuration
    /// Enable write-ahead logging for durability
    pub enable_wal: bool,
    /// Write-ahead log buffer size in bytes
    pub wal_buffer_size: usize,
    /// Maximum transaction size (number of triples)
    pub max_transaction_size: usize,
    /// Transaction timeout in seconds
    pub transaction_timeout_secs: u64,

    // Compression configuration
    /// Enable data compression
    pub enable_compression: bool,
    /// Compression algorithm to use
    pub compression_algorithm: CompressionAlgorithm,
    /// Compression level (algorithm-specific)
    pub compression_level: u32,

    // Bloom filter configuration
    /// Enable bloom filters for indexes
    pub enable_bloom_filters: bool,
    /// Bloom filter false positive rate (0.0 to 1.0)
    pub bloom_filter_fpr: f64,
    /// Bloom filter size per index
    pub bloom_filter_size_per_index: usize,

    // Query optimization
    /// Enable query result caching
    pub enable_query_cache: bool,
    /// Query cache size (number of cached queries)
    pub query_cache_size: usize,
    /// Enable statistics collection
    pub enable_statistics: bool,
    /// Statistics sampling rate (0.0 to 1.0)
    pub statistics_sample_rate: f64,

    // Query monitoring
    /// Enable query performance monitoring
    pub enable_query_monitoring: bool,
    /// Slow query threshold in milliseconds
    pub slow_query_threshold_ms: u64,
    /// Query timeout in milliseconds
    pub query_timeout_ms: u64,

    // Spatial indexing
    /// Enable spatial indexing for geospatial queries
    pub enable_spatial_indexing: bool,
    /// Maximum entries per spatial index node
    pub spatial_index_max_entries: usize,

    // Production features
    /// Enable diagnostic logging and error reporting
    pub enable_diagnostics: bool,
    /// Enable metrics collection and export
    pub enable_metrics: bool,
    /// Enable performance profiling
    pub enable_profiling: bool,

    // Connection pooling
    /// Minimum number of connections to maintain
    pub min_connections: usize,
    /// Maximum number of concurrent connections
    pub max_connections: usize,
    /// Connection timeout in seconds
    pub connection_timeout_secs: u64,

    // Backup configuration
    /// Enable online (hot) backups
    pub enable_online_backup: bool,
    /// Number of days to retain backups
    pub backup_retention_days: u32,
    /// Enable backup encryption
    pub enable_backup_encryption: bool,

    // Performance tuning
    /// Enable direct I/O bypassing OS cache
    pub enable_direct_io: bool,
    /// Enable asynchronous I/O operations
    pub enable_async_io: bool,
    /// Enable NUMA (Non-Uniform Memory Access) awareness
    pub enable_numa_awareness: bool,
    /// Enable GPU acceleration for computations
    pub enable_gpu_acceleration: bool,

    // Distributed systems
    /// Enable data replication
    pub enable_replication: bool,
    /// Replication mode (master-slave, master-master, etc.)
    pub replication_mode: ReplicationMode,
}

/// Compression algorithm selection
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompressionAlgorithm {
    /// No compression
    None,
    /// LZ4 - fast compression
    Lz4,
    /// Zstandard - balanced compression
    Zstd,
    /// Brotli - high compression
    Brotli,
    /// Snappy - ultra-fast compression
    Snappy,
}

/// Replication mode
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReplicationMode {
    /// No replication
    None,
    /// Master-slave replication
    MasterSlave,
    /// Master-master replication
    MasterMaster,
}

impl StoreParams {
    /// Create new store parameters with minimal configuration
    pub fn new<P: AsRef<Path>>(data_dir: P) -> Self {
        Self {
            // Storage configuration
            data_dir: data_dir.as_ref().to_path_buf(),
            page_size: 4096,
            buffer_pool_size: 1000,

            // Index configuration
            enable_spo_index: true,
            enable_pos_index: true,
            enable_osp_index: true,
            enable_quad_indexes: false,

            // Dictionary configuration
            enable_inline_values: true,
            enable_prefix_compression: true,
            dictionary_cache_size: 10000,

            // Transaction configuration
            enable_wal: true,
            wal_buffer_size: 1024 * 1024, // 1MB
            max_transaction_size: 1_000_000,
            transaction_timeout_secs: 60,

            // Compression configuration
            enable_compression: true,
            compression_algorithm: CompressionAlgorithm::Lz4,
            compression_level: 3,

            // Bloom filter configuration
            enable_bloom_filters: true,
            bloom_filter_fpr: 0.01,
            bloom_filter_size_per_index: 1_000_000,

            // Query optimization
            enable_query_cache: true,
            query_cache_size: 1000,
            enable_statistics: true,
            statistics_sample_rate: 1.0,

            // Query monitoring
            enable_query_monitoring: true,
            slow_query_threshold_ms: 1000,
            query_timeout_ms: 30_000,

            // Spatial indexing
            enable_spatial_indexing: true,
            spatial_index_max_entries: 1000,

            // Production features
            enable_diagnostics: true,
            enable_metrics: true,
            enable_profiling: false,

            // Connection pooling
            min_connections: 2,
            max_connections: 10,
            connection_timeout_secs: 30,

            // Backup configuration
            enable_online_backup: true,
            backup_retention_days: 7,
            enable_backup_encryption: false,

            // Performance tuning
            enable_direct_io: false,
            enable_async_io: false,
            enable_numa_awareness: false,
            enable_gpu_acceleration: false,

            // Distributed systems
            enable_replication: false,
            replication_mode: ReplicationMode::None,
        }
    }

    /// Validate parameters and return errors if invalid
    pub fn validate(&self) -> Result<()> {
        // Page size must be power of 2 and >= 512
        if !self.page_size.is_power_of_two() || self.page_size < 512 {
            return Err(TdbError::InvalidConfiguration(format!(
                "Page size must be power of 2 and >= 512, got {}",
                self.page_size
            )));
        }

        // Buffer pool size must be > 0
        if self.buffer_pool_size == 0 {
            return Err(TdbError::InvalidConfiguration(
                "Buffer pool size must be > 0".to_string(),
            ));
        }

        // Bloom filter FPR must be between 0 and 1
        if self.bloom_filter_fpr <= 0.0 || self.bloom_filter_fpr >= 1.0 {
            return Err(TdbError::InvalidConfiguration(format!(
                "Bloom filter FPR must be between 0 and 1, got {}",
                self.bloom_filter_fpr
            )));
        }

        // Statistics sample rate must be between 0 and 1
        if self.statistics_sample_rate < 0.0 || self.statistics_sample_rate > 1.0 {
            return Err(TdbError::InvalidConfiguration(format!(
                "Statistics sample rate must be between 0 and 1, got {}",
                self.statistics_sample_rate
            )));
        }

        // Connection pool constraints
        if self.min_connections > self.max_connections {
            return Err(TdbError::InvalidConfiguration(format!(
                "Min connections ({}) > max connections ({})",
                self.min_connections, self.max_connections
            )));
        }

        Ok(())
    }

    /// Save parameters to JSON file
    pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let json = serde_json::to_string_pretty(self)
            .map_err(|e| TdbError::Serialization(format!("Failed to serialize config: {}", e)))?;
        std::fs::write(path, json)?;
        Ok(())
    }

    /// Load parameters from JSON file
    pub fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let json = std::fs::read_to_string(path)?;
        let params: StoreParams = serde_json::from_str(&json)
            .map_err(|e| TdbError::Deserialization(format!("Failed to parse config: {}", e)))?;
        params.validate()?;
        Ok(params)
    }
}

/// Builder for store parameters with fluent API
pub struct StoreParamsBuilder {
    params: StoreParams,
}

impl StoreParamsBuilder {
    /// Create new builder with default parameters
    pub fn new<P: AsRef<Path>>(data_dir: P) -> Self {
        Self {
            params: StoreParams::new(data_dir),
        }
    }

    /// Create builder from existing parameters
    pub fn from_params(params: StoreParams) -> Self {
        Self { params }
    }

    /// Set page size (must be power of 2)
    pub fn page_size(mut self, size: usize) -> Self {
        self.params.page_size = size;
        self
    }

    /// Set buffer pool size
    pub fn buffer_pool_size(mut self, size: usize) -> Self {
        self.params.buffer_pool_size = size;
        self
    }

    /// Enable/disable triple indexes
    pub fn with_triple_indexes(mut self, spo: bool, pos: bool, osp: bool) -> Self {
        self.params.enable_spo_index = spo;
        self.params.enable_pos_index = pos;
        self.params.enable_osp_index = osp;
        self
    }

    /// Enable/disable quad indexes
    pub fn with_quad_indexes(mut self, enable: bool) -> Self {
        self.params.enable_quad_indexes = enable;
        self
    }

    /// Enable/disable inline values optimization
    pub fn with_inline_values(mut self, enable: bool) -> Self {
        self.params.enable_inline_values = enable;
        self
    }

    /// Enable/disable prefix compression
    pub fn with_prefix_compression(mut self, enable: bool) -> Self {
        self.params.enable_prefix_compression = enable;
        self
    }

    /// Set dictionary cache size
    pub fn dictionary_cache_size(mut self, size: usize) -> Self {
        self.params.dictionary_cache_size = size;
        self
    }

    /// Enable/disable write-ahead logging
    pub fn with_wal(mut self, enable: bool) -> Self {
        self.params.enable_wal = enable;
        self
    }

    /// Set WAL buffer size
    pub fn wal_buffer_size(mut self, size: usize) -> Self {
        self.params.wal_buffer_size = size;
        self
    }

    /// Set maximum transaction size
    pub fn max_transaction_size(mut self, size: usize) -> Self {
        self.params.max_transaction_size = size;
        self
    }

    /// Set transaction timeout
    pub fn transaction_timeout(mut self, seconds: u64) -> Self {
        self.params.transaction_timeout_secs = seconds;
        self
    }

    /// Configure compression
    pub fn with_compression(mut self, algorithm: CompressionAlgorithm, level: u32) -> Self {
        self.params.enable_compression = algorithm != CompressionAlgorithm::None;
        self.params.compression_algorithm = algorithm;
        self.params.compression_level = level;
        self
    }

    /// Configure bloom filters
    pub fn with_bloom_filters(mut self, enable: bool, fpr: f64, size: usize) -> Self {
        self.params.enable_bloom_filters = enable;
        self.params.bloom_filter_fpr = fpr;
        self.params.bloom_filter_size_per_index = size;
        self
    }

    /// Configure query cache
    pub fn with_query_cache(mut self, enable: bool, size: usize) -> Self {
        self.params.enable_query_cache = enable;
        self.params.query_cache_size = size;
        self
    }

    /// Configure statistics
    pub fn with_statistics(mut self, enable: bool, sample_rate: f64) -> Self {
        self.params.enable_statistics = enable;
        self.params.statistics_sample_rate = sample_rate;
        self
    }

    /// Configure query monitoring
    pub fn with_query_monitoring(
        mut self,
        enable: bool,
        slow_threshold_ms: u64,
        timeout_ms: u64,
    ) -> Self {
        self.params.enable_query_monitoring = enable;
        self.params.slow_query_threshold_ms = slow_threshold_ms;
        self.params.query_timeout_ms = timeout_ms;
        self
    }

    /// Configure spatial indexing
    pub fn with_spatial_indexing(mut self, enable: bool, max_entries: usize) -> Self {
        self.params.enable_spatial_indexing = enable;
        self.params.spatial_index_max_entries = max_entries;
        self
    }

    /// Configure production features
    pub fn with_production_features(
        mut self,
        diagnostics: bool,
        metrics: bool,
        profiling: bool,
    ) -> Self {
        self.params.enable_diagnostics = diagnostics;
        self.params.enable_metrics = metrics;
        self.params.enable_profiling = profiling;
        self
    }

    /// Configure connection pooling
    pub fn with_connection_pool(mut self, min: usize, max: usize, timeout_secs: u64) -> Self {
        self.params.min_connections = min;
        self.params.max_connections = max;
        self.params.connection_timeout_secs = timeout_secs;
        self
    }

    /// Configure backup
    pub fn with_backup(mut self, enable_online: bool, retention_days: u32, encrypt: bool) -> Self {
        self.params.enable_online_backup = enable_online;
        self.params.backup_retention_days = retention_days;
        self.params.enable_backup_encryption = encrypt;
        self
    }

    /// Configure performance features
    pub fn with_performance_features(
        mut self,
        direct_io: bool,
        async_io: bool,
        numa: bool,
        gpu: bool,
    ) -> Self {
        self.params.enable_direct_io = direct_io;
        self.params.enable_async_io = async_io;
        self.params.enable_numa_awareness = numa;
        self.params.enable_gpu_acceleration = gpu;
        self
    }

    /// Configure replication
    pub fn with_replication(mut self, mode: ReplicationMode) -> Self {
        self.params.enable_replication = mode != ReplicationMode::None;
        self.params.replication_mode = mode;
        self
    }

    /// Build and validate parameters
    pub fn build(self) -> Result<StoreParams> {
        self.params.validate()?;
        Ok(self.params)
    }

    /// Build without validation (use with caution)
    pub fn build_unchecked(self) -> StoreParams {
        self.params
    }
}

/// Preset configurations for common use cases
pub struct StorePresets;

impl StorePresets {
    /// Development preset - optimized for fast iteration
    pub fn development<P: AsRef<Path>>(data_dir: P) -> StoreParamsBuilder {
        StoreParamsBuilder::new(data_dir)
            .buffer_pool_size(100)
            .with_compression(CompressionAlgorithm::None, 0)
            .with_statistics(false, 0.0)
            .with_production_features(false, false, false)
            .with_performance_features(false, false, false, false)
    }

    /// Production preset - balanced for production workloads
    pub fn production<P: AsRef<Path>>(data_dir: P) -> StoreParamsBuilder {
        StoreParamsBuilder::new(data_dir)
            .buffer_pool_size(10000)
            .with_compression(CompressionAlgorithm::Lz4, 3)
            .with_statistics(true, 1.0)
            .with_production_features(true, true, false)
            .with_backup(true, 30, true)
            .with_connection_pool(5, 50, 60)
    }

    /// Performance preset - optimized for maximum throughput
    pub fn performance<P: AsRef<Path>>(data_dir: P) -> StoreParamsBuilder {
        StoreParamsBuilder::new(data_dir)
            .buffer_pool_size(50000)
            .with_compression(CompressionAlgorithm::Snappy, 1)
            .with_bloom_filters(true, 0.001, 10_000_000)
            .with_performance_features(true, true, true, true)
            .with_query_cache(true, 10000)
    }

    /// Minimal preset - bare minimum configuration
    pub fn minimal<P: AsRef<Path>>(data_dir: P) -> StoreParamsBuilder {
        StoreParamsBuilder::new(data_dir)
            .buffer_pool_size(10)
            .with_compression(CompressionAlgorithm::None, 0)
            .with_bloom_filters(false, 0.01, 0)
            .with_query_cache(false, 0)
            .with_statistics(false, 0.0)
            .with_production_features(false, false, false)
    }
}

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

    /// Temp directory path used as the store base path in tests. The path is
    /// only stored on the params struct (never written to), so a shared temp
    /// path is sufficient and collision-safe.
    fn test_store_path() -> PathBuf {
        env::temp_dir().join("oxirs_tdb_store_params_test")
    }

    #[test]
    fn test_store_params_new() {
        let params = StoreParams::new(test_store_path());
        assert_eq!(params.page_size, 4096);
        assert_eq!(params.buffer_pool_size, 1000);
        assert!(params.enable_spo_index);
    }

    #[test]
    fn test_store_params_validation() {
        let params = StoreParams::new(test_store_path());
        assert!(params.validate().is_ok());

        let mut invalid_params = params.clone();
        invalid_params.page_size = 1000; // Not power of 2
        assert!(invalid_params.validate().is_err());

        let mut invalid_params2 = params.clone();
        invalid_params2.bloom_filter_fpr = 1.5; // Out of range
        assert!(invalid_params2.validate().is_err());
    }

    #[test]
    fn test_builder_basic() {
        let params = StoreParamsBuilder::new(test_store_path())
            .page_size(8192)
            .buffer_pool_size(2000)
            .build()
            .unwrap();

        assert_eq!(params.page_size, 8192);
        assert_eq!(params.buffer_pool_size, 2000);
    }

    #[test]
    fn test_builder_compression() {
        let params = StoreParamsBuilder::new(test_store_path())
            .with_compression(CompressionAlgorithm::Zstd, 5)
            .build()
            .unwrap();

        assert!(params.enable_compression);
        assert_eq!(params.compression_algorithm, CompressionAlgorithm::Zstd);
        assert_eq!(params.compression_level, 5);
    }

    #[test]
    fn test_builder_bloom_filters() {
        let params = StoreParamsBuilder::new(test_store_path())
            .with_bloom_filters(true, 0.001, 5_000_000)
            .build()
            .unwrap();

        assert!(params.enable_bloom_filters);
        assert_eq!(params.bloom_filter_fpr, 0.001);
        assert_eq!(params.bloom_filter_size_per_index, 5_000_000);
    }

    #[test]
    fn test_presets_development() {
        let params = StorePresets::development(test_store_path())
            .build()
            .unwrap();
        assert_eq!(params.buffer_pool_size, 100);
        assert_eq!(params.compression_algorithm, CompressionAlgorithm::None);
        assert!(!params.enable_statistics);
    }

    #[test]
    fn test_presets_production() {
        let params = StorePresets::production(test_store_path()).build().unwrap();
        assert_eq!(params.buffer_pool_size, 10000);
        assert!(params.enable_diagnostics);
        assert!(params.enable_backup_encryption);
    }

    #[test]
    fn test_presets_performance() {
        let params = StorePresets::performance(test_store_path())
            .build()
            .unwrap();
        assert_eq!(params.buffer_pool_size, 50000);
        assert!(params.enable_direct_io);
        assert!(params.enable_gpu_acceleration);
    }

    #[test]
    fn test_save_load_params() {
        let temp_dir = env::temp_dir();
        let config_file = temp_dir.join("test_store_params.json");

        let params = StoreParamsBuilder::new(&temp_dir)
            .page_size(8192)
            .buffer_pool_size(5000)
            .build()
            .unwrap();

        params.save_to_file(&config_file).unwrap();
        let loaded_params = StoreParams::load_from_file(&config_file).unwrap();

        assert_eq!(params.page_size, loaded_params.page_size);
        assert_eq!(params.buffer_pool_size, loaded_params.buffer_pool_size);
    }

    #[test]
    fn test_replication_config() {
        let params = StoreParamsBuilder::new(test_store_path())
            .with_replication(ReplicationMode::MasterSlave)
            .build()
            .unwrap();

        assert!(params.enable_replication);
        assert_eq!(params.replication_mode, ReplicationMode::MasterSlave);
    }

    #[test]
    fn test_connection_pool_validation() {
        let result = StoreParamsBuilder::new(test_store_path())
            .with_connection_pool(10, 5, 30) // min > max (invalid)
            .build();

        assert!(result.is_err());
    }
}