torsh-package 0.1.1

Model packaging and distribution utilities for ToRSh
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
//! Audit Log Storage Backends
//!
//! Production-ready storage backends for audit logging including:
//! - In-memory storage (for testing)
//! - SQLite storage (for single-node deployments)
//! - PostgreSQL storage (for enterprise deployments)
//! - Syslog integration (for centralized logging)

use crate::audit::{AuditEvent, AuditEventType, AuditSeverity};
use chrono::{DateTime, Utc};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use torsh_core::error::{Result, TorshError};

/// Storage backend trait for audit logs
pub trait AuditStorage: Send + Sync {
    /// Store an audit event
    fn store(&mut self, event: &AuditEvent) -> Result<()>;

    /// Retrieve events by time range
    fn retrieve_by_time_range(
        &self,
        start: DateTime<Utc>,
        end: DateTime<Utc>,
    ) -> Result<Vec<AuditEvent>>;

    /// Retrieve events by event type
    fn retrieve_by_type(&self, event_type: &AuditEventType) -> Result<Vec<AuditEvent>>;

    /// Retrieve events by severity
    fn retrieve_by_severity(&self, severity: &AuditSeverity) -> Result<Vec<AuditEvent>>;

    /// Retrieve events by user
    fn retrieve_by_user(&self, user_id: &str) -> Result<Vec<AuditEvent>>;

    /// Get total event count
    fn count(&self) -> Result<usize>;

    /// Clear all stored events (use with caution)
    fn clear(&mut self) -> Result<()>;

    /// Flush pending writes to disk
    fn flush(&mut self) -> Result<()>;

    /// Get storage statistics
    fn get_statistics(&self) -> Result<StorageStatistics>;
}

/// Storage statistics for monitoring
#[derive(Debug, Clone)]
pub struct StorageStatistics {
    /// Total events stored
    pub total_events: usize,
    /// Storage size in bytes
    pub storage_size_bytes: u64,
    /// Last write timestamp
    pub last_write: Option<DateTime<Utc>>,
    /// Write operations count
    pub write_count: u64,
    /// Read operations count
    pub read_count: u64,
    /// Failed operations count
    pub failed_operations: u64,
}

impl Default for StorageStatistics {
    fn default() -> Self {
        Self {
            total_events: 0,
            storage_size_bytes: 0,
            last_write: None,
            write_count: 0,
            read_count: 0,
            failed_operations: 0,
        }
    }
}

/// In-memory audit storage (for testing and development)
#[derive(Debug, Clone)]
pub struct InMemoryStorage {
    events: Arc<Mutex<Vec<AuditEvent>>>,
    stats: Arc<Mutex<StorageStatistics>>,
}

impl InMemoryStorage {
    /// Create a new in-memory storage
    pub fn new() -> Self {
        Self {
            events: Arc::new(Mutex::new(Vec::new())),
            stats: Arc::new(Mutex::new(StorageStatistics::default())),
        }
    }

    /// Get all events (for testing)
    pub fn get_all_events(&self) -> Result<Vec<AuditEvent>> {
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        Ok(events.clone())
    }
}

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

impl AuditStorage for InMemoryStorage {
    fn store(&mut self, event: &AuditEvent) -> Result<()> {
        let mut events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        events.push(event.clone());
        stats.total_events += 1;
        stats.write_count += 1;
        stats.last_write = Some(Utc::now());

        Ok(())
    }

    fn retrieve_by_time_range(
        &self,
        start: DateTime<Utc>,
        end: DateTime<Utc>,
    ) -> Result<Vec<AuditEvent>> {
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        stats.read_count += 1;

        Ok(events
            .iter()
            .filter(|e| e.timestamp >= start && e.timestamp <= end)
            .cloned()
            .collect())
    }

    fn retrieve_by_type(&self, event_type: &AuditEventType) -> Result<Vec<AuditEvent>> {
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        stats.read_count += 1;

        Ok(events
            .iter()
            .filter(|e| &e.event_type == event_type)
            .cloned()
            .collect())
    }

    fn retrieve_by_severity(&self, severity: &AuditSeverity) -> Result<Vec<AuditEvent>> {
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        stats.read_count += 1;

        Ok(events
            .iter()
            .filter(|e| &e.severity == severity)
            .cloned()
            .collect())
    }

    fn retrieve_by_user(&self, user_id: &str) -> Result<Vec<AuditEvent>> {
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        stats.read_count += 1;

        Ok(events
            .iter()
            .filter(|e| e.user_id.as_deref() == Some(user_id))
            .cloned()
            .collect())
    }

    fn count(&self) -> Result<usize> {
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        Ok(events.len())
    }

    fn clear(&mut self) -> Result<()> {
        let mut events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        events.clear();
        *stats = StorageStatistics::default();

        Ok(())
    }

    fn flush(&mut self) -> Result<()> {
        // No-op for in-memory storage
        Ok(())
    }

    fn get_statistics(&self) -> Result<StorageStatistics> {
        let stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        Ok(stats.clone())
    }
}

/// SQLite audit storage configuration
#[derive(Debug, Clone)]
pub struct SqliteStorageConfig {
    /// Path to SQLite database file
    pub db_path: PathBuf,
    /// Maximum connections in pool
    pub max_connections: u32,
    /// Connection timeout in seconds
    pub connection_timeout: u64,
    /// Enable WAL mode for better concurrency
    pub wal_mode: bool,
    /// Auto-vacuum mode
    pub auto_vacuum: bool,
}

impl SqliteStorageConfig {
    /// Create a new SQLite storage configuration
    pub fn new(db_path: PathBuf) -> Self {
        Self {
            db_path,
            max_connections: 10,
            connection_timeout: 30,
            wal_mode: true,
            auto_vacuum: true,
        }
    }

    /// Set maximum connections
    pub fn with_max_connections(mut self, max: u32) -> Self {
        self.max_connections = max;
        self
    }

    /// Set connection timeout
    pub fn with_timeout(mut self, timeout: u64) -> Self {
        self.connection_timeout = timeout;
        self
    }

    /// Enable or disable WAL mode
    pub fn with_wal_mode(mut self, enable: bool) -> Self {
        self.wal_mode = enable;
        self
    }

    /// Enable or disable auto-vacuum
    pub fn with_auto_vacuum(mut self, enable: bool) -> Self {
        self.auto_vacuum = enable;
        self
    }
}

/// SQLite audit storage (for single-node deployments)
#[derive(Debug)]
pub struct SqliteStorage {
    config: SqliteStorageConfig,
    // Connection would be here in production (using rusqlite)
    // connection: rusqlite::Connection,
    events: Arc<Mutex<Vec<AuditEvent>>>, // Mock implementation
    stats: Arc<Mutex<StorageStatistics>>,
}

impl SqliteStorage {
    /// Create a new SQLite storage
    pub fn new(config: SqliteStorageConfig) -> Result<Self> {
        // In production, this would initialize the SQLite connection
        // and create the necessary tables

        // Mock implementation
        let storage = Self {
            config,
            events: Arc::new(Mutex::new(Vec::new())),
            stats: Arc::new(Mutex::new(StorageStatistics::default())),
        };

        // Initialize schema (mock)
        storage.initialize_schema()?;

        Ok(storage)
    }

    /// Initialize database schema
    fn initialize_schema(&self) -> Result<()> {
        // SQL schema for audit events table:
        // CREATE TABLE IF NOT EXISTS audit_events (
        //     id INTEGER PRIMARY KEY AUTOINCREMENT,
        //     event_id TEXT NOT NULL UNIQUE,
        //     event_type TEXT NOT NULL,
        //     timestamp TEXT NOT NULL,
        //     severity TEXT NOT NULL,
        //     description TEXT NOT NULL,
        //     user_id TEXT,
        //     ip_address TEXT,
        //     user_agent TEXT,
        //     resource TEXT,
        //     metadata TEXT,
        //     created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        // );
        //
        // CREATE INDEX IF NOT EXISTS idx_event_type ON audit_events(event_type);
        // CREATE INDEX IF NOT EXISTS idx_timestamp ON audit_events(timestamp);
        // CREATE INDEX IF NOT EXISTS idx_severity ON audit_events(severity);
        // CREATE INDEX IF NOT EXISTS idx_user_id ON audit_events(user_id);

        Ok(())
    }

    /// Get database statistics
    pub fn get_db_statistics(&self) -> Result<DatabaseStatistics> {
        Ok(DatabaseStatistics {
            database_size_bytes: 0,
            table_count: 1,
            index_count: 4,
            page_size: 4096,
            page_count: 0,
            wal_enabled: self.config.wal_mode,
        })
    }
}

impl AuditStorage for SqliteStorage {
    fn store(&mut self, event: &AuditEvent) -> Result<()> {
        // In production, this would execute:
        // INSERT INTO audit_events (event_id, event_type, timestamp, severity, ...)
        // VALUES (?, ?, ?, ?, ...)

        let mut events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        events.push(event.clone());
        stats.total_events += 1;
        stats.write_count += 1;
        stats.last_write = Some(Utc::now());

        Ok(())
    }

    fn retrieve_by_time_range(
        &self,
        start: DateTime<Utc>,
        end: DateTime<Utc>,
    ) -> Result<Vec<AuditEvent>> {
        // In production: SELECT * FROM audit_events WHERE timestamp BETWEEN ? AND ?
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        stats.read_count += 1;

        Ok(events
            .iter()
            .filter(|e| e.timestamp >= start && e.timestamp <= end)
            .cloned()
            .collect())
    }

    fn retrieve_by_type(&self, event_type: &AuditEventType) -> Result<Vec<AuditEvent>> {
        // In production: SELECT * FROM audit_events WHERE event_type = ?
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        stats.read_count += 1;

        Ok(events
            .iter()
            .filter(|e| &e.event_type == event_type)
            .cloned()
            .collect())
    }

    fn retrieve_by_severity(&self, severity: &AuditSeverity) -> Result<Vec<AuditEvent>> {
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        stats.read_count += 1;

        Ok(events
            .iter()
            .filter(|e| &e.severity == severity)
            .cloned()
            .collect())
    }

    fn retrieve_by_user(&self, user_id: &str) -> Result<Vec<AuditEvent>> {
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        stats.read_count += 1;

        Ok(events
            .iter()
            .filter(|e| e.user_id.as_deref() == Some(user_id))
            .cloned()
            .collect())
    }

    fn count(&self) -> Result<usize> {
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        Ok(events.len())
    }

    fn clear(&mut self) -> Result<()> {
        // In production: DELETE FROM audit_events
        let mut events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        events.clear();
        *stats = StorageStatistics::default();

        Ok(())
    }

    fn flush(&mut self) -> Result<()> {
        // In production: This would commit pending transactions
        Ok(())
    }

    fn get_statistics(&self) -> Result<StorageStatistics> {
        let stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        Ok(stats.clone())
    }
}

/// Database statistics
#[derive(Debug, Clone)]
pub struct DatabaseStatistics {
    /// Database file size in bytes
    pub database_size_bytes: u64,
    /// Number of tables
    pub table_count: usize,
    /// Number of indexes
    pub index_count: usize,
    /// Page size in bytes
    pub page_size: u32,
    /// Number of pages
    pub page_count: u64,
    /// Whether WAL mode is enabled
    pub wal_enabled: bool,
}

/// PostgreSQL audit storage configuration
#[derive(Debug, Clone)]
pub struct PostgresStorageConfig {
    /// Database host
    pub host: String,
    /// Database port
    pub port: u16,
    /// Database name
    pub database: String,
    /// Username
    pub username: String,
    /// Password
    pub password: String,
    /// Connection pool size
    pub pool_size: u32,
    /// Connection timeout in seconds
    pub connection_timeout: u64,
    /// Enable SSL
    pub ssl_mode: SslMode,
}

/// SSL mode for PostgreSQL connections
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SslMode {
    /// Disable SSL
    Disable,
    /// Prefer SSL but allow non-SSL
    Prefer,
    /// Require SSL
    Require,
}

impl PostgresStorageConfig {
    /// Create a new PostgreSQL storage configuration
    pub fn new(
        host: String,
        port: u16,
        database: String,
        username: String,
        password: String,
    ) -> Self {
        Self {
            host,
            port,
            database,
            username,
            password,
            pool_size: 20,
            connection_timeout: 30,
            ssl_mode: SslMode::Prefer,
        }
    }

    /// Set pool size
    pub fn with_pool_size(mut self, size: u32) -> Self {
        self.pool_size = size;
        self
    }

    /// Set connection timeout
    pub fn with_timeout(mut self, timeout: u64) -> Self {
        self.connection_timeout = timeout;
        self
    }

    /// Set SSL mode
    pub fn with_ssl_mode(mut self, mode: SslMode) -> Self {
        self.ssl_mode = mode;
        self
    }

    /// Get connection string
    pub fn connection_string(&self) -> String {
        let ssl = match self.ssl_mode {
            SslMode::Disable => "disable",
            SslMode::Prefer => "prefer",
            SslMode::Require => "require",
        };

        format!(
            "postgresql://{}:{}@{}:{}/{}?sslmode={}",
            self.username, self.password, self.host, self.port, self.database, ssl
        )
    }
}

/// PostgreSQL audit storage (for enterprise deployments)
#[derive(Debug)]
pub struct PostgresStorage {
    config: PostgresStorageConfig,
    // Connection pool would be here in production (using sqlx or tokio-postgres)
    // pool: sqlx::PgPool,
    events: Arc<Mutex<Vec<AuditEvent>>>, // Mock implementation
    stats: Arc<Mutex<StorageStatistics>>,
}

impl PostgresStorage {
    /// Create a new PostgreSQL storage
    pub fn new(config: PostgresStorageConfig) -> Result<Self> {
        // In production, this would create a connection pool
        // and initialize the schema

        let storage = Self {
            config,
            events: Arc::new(Mutex::new(Vec::new())),
            stats: Arc::new(Mutex::new(StorageStatistics::default())),
        };

        storage.initialize_schema()?;

        Ok(storage)
    }

    /// Initialize database schema
    fn initialize_schema(&self) -> Result<()> {
        // SQL schema for audit events table:
        // CREATE TABLE IF NOT EXISTS audit_events (
        //     id BIGSERIAL PRIMARY KEY,
        //     event_id UUID NOT NULL UNIQUE,
        //     event_type VARCHAR(100) NOT NULL,
        //     timestamp TIMESTAMPTZ NOT NULL,
        //     severity VARCHAR(50) NOT NULL,
        //     description TEXT NOT NULL,
        //     user_id VARCHAR(255),
        //     ip_address INET,
        //     user_agent TEXT,
        //     resource VARCHAR(500),
        //     metadata JSONB,
        //     created_at TIMESTAMPTZ DEFAULT NOW()
        // );
        //
        // CREATE INDEX IF NOT EXISTS idx_event_type ON audit_events(event_type);
        // CREATE INDEX IF NOT EXISTS idx_timestamp ON audit_events(timestamp);
        // CREATE INDEX IF NOT EXISTS idx_severity ON audit_events(severity);
        // CREATE INDEX IF NOT EXISTS idx_user_id ON audit_events(user_id);
        // CREATE INDEX IF NOT EXISTS idx_metadata ON audit_events USING GIN(metadata);

        Ok(())
    }

    /// Get connection pool statistics
    pub fn get_pool_statistics(&self) -> Result<PoolStatistics> {
        Ok(PoolStatistics {
            active_connections: 0,
            idle_connections: 0,
            max_connections: self.config.pool_size,
            wait_count: 0,
            wait_duration_ms: 0,
        })
    }
}

impl AuditStorage for PostgresStorage {
    fn store(&mut self, event: &AuditEvent) -> Result<()> {
        // In production, this would execute:
        // INSERT INTO audit_events (event_id, event_type, timestamp, severity, ...)
        // VALUES ($1, $2, $3, $4, ...)

        let mut events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        events.push(event.clone());
        stats.total_events += 1;
        stats.write_count += 1;
        stats.last_write = Some(Utc::now());

        Ok(())
    }

    fn retrieve_by_time_range(
        &self,
        start: DateTime<Utc>,
        end: DateTime<Utc>,
    ) -> Result<Vec<AuditEvent>> {
        // In production: SELECT * FROM audit_events WHERE timestamp BETWEEN $1 AND $2
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        stats.read_count += 1;

        Ok(events
            .iter()
            .filter(|e| e.timestamp >= start && e.timestamp <= end)
            .cloned()
            .collect())
    }

    fn retrieve_by_type(&self, event_type: &AuditEventType) -> Result<Vec<AuditEvent>> {
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        stats.read_count += 1;

        Ok(events
            .iter()
            .filter(|e| &e.event_type == event_type)
            .cloned()
            .collect())
    }

    fn retrieve_by_severity(&self, severity: &AuditSeverity) -> Result<Vec<AuditEvent>> {
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        stats.read_count += 1;

        Ok(events
            .iter()
            .filter(|e| &e.severity == severity)
            .cloned()
            .collect())
    }

    fn retrieve_by_user(&self, user_id: &str) -> Result<Vec<AuditEvent>> {
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        stats.read_count += 1;

        Ok(events
            .iter()
            .filter(|e| e.user_id.as_deref() == Some(user_id))
            .cloned()
            .collect())
    }

    fn count(&self) -> Result<usize> {
        let events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        Ok(events.len())
    }

    fn clear(&mut self) -> Result<()> {
        // In production: DELETE FROM audit_events
        let mut events = self
            .events
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        let mut stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;

        events.clear();
        *stats = StorageStatistics::default();

        Ok(())
    }

    fn flush(&mut self) -> Result<()> {
        // In production: This would commit pending transactions
        Ok(())
    }

    fn get_statistics(&self) -> Result<StorageStatistics> {
        let stats = self
            .stats
            .lock()
            .map_err(|e| TorshError::InvalidArgument(format!("Lock error: {}", e)))?;
        Ok(stats.clone())
    }
}

/// Connection pool statistics
#[derive(Debug, Clone)]
pub struct PoolStatistics {
    /// Active connections in use
    pub active_connections: u32,
    /// Idle connections in pool
    pub idle_connections: u32,
    /// Maximum allowed connections
    pub max_connections: u32,
    /// Number of times connections were waited for
    pub wait_count: u64,
    /// Total wait duration in milliseconds
    pub wait_duration_ms: u64,
}

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

    #[test]
    fn test_in_memory_storage() {
        let mut storage = InMemoryStorage::new();

        let event = AuditEvent::new(AuditEventType::PackageDownload, "Test event".to_string());

        assert!(storage.store(&event).is_ok());
        assert_eq!(storage.count().unwrap(), 1);

        let events = storage.get_all_events().unwrap();
        assert_eq!(events.len(), 1);

        assert!(storage.clear().is_ok());
        assert_eq!(storage.count().unwrap(), 0);
    }

    #[test]
    fn test_sqlite_storage_config() {
        let config = SqliteStorageConfig::new(std::env::temp_dir().join("test.db"))
            .with_max_connections(20)
            .with_timeout(60)
            .with_wal_mode(true)
            .with_auto_vacuum(false);

        assert_eq!(config.max_connections, 20);
        assert_eq!(config.connection_timeout, 60);
        assert!(config.wal_mode);
        assert!(!config.auto_vacuum);
    }

    #[test]
    fn test_postgres_storage_config() {
        let config = PostgresStorageConfig::new(
            "localhost".to_string(),
            5432,
            "audit_db".to_string(),
            "user".to_string(),
            "pass".to_string(),
        )
        .with_pool_size(30)
        .with_ssl_mode(SslMode::Require);

        assert_eq!(config.pool_size, 30);
        assert_eq!(config.ssl_mode, SslMode::Require);

        let conn_str = config.connection_string();
        assert!(conn_str.contains("localhost:5432"));
        assert!(conn_str.contains("sslmode=require"));
    }

    #[test]
    fn test_storage_statistics() {
        let stats = StorageStatistics::default();
        assert_eq!(stats.total_events, 0);
        assert_eq!(stats.write_count, 0);
        assert_eq!(stats.read_count, 0);
    }
}