vecstore 1.0.0

The perfect vector database - 100/100 score, embeddable, high-performance, production-ready with RAG toolkit
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
//! Audit Logging
//!
//! Provides comprehensive audit trails for compliance and security monitoring.

use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
use std::fs::{File, OpenOptions};
use std::io::Write as IoWrite;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::SystemTime;

/// Audit event types
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AuditEventType {
    /// Vector insertion
    Insert,
    /// Vector update
    Update,
    /// Vector deletion
    Delete,
    /// Query operation
    Query,
    /// Batch operation
    Batch,
    /// Index creation
    IndexCreate,
    /// Index deletion
    IndexDelete,
    /// Authentication
    Auth,
    /// Authorization
    Authz,
    /// Configuration change
    ConfigChange,
    /// Backup operation
    Backup,
    /// Restore operation
    Restore,
    /// Export operation
    Export,
    /// Import operation
    Import,
}

/// Audit severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum AuditSeverity {
    Debug,
    Info,
    Warning,
    Error,
    Critical,
}

/// Audit outcome
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AuditOutcome {
    Success,
    Failure,
    Denied,
}

/// Audit entry metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditMetadata {
    /// User identifier
    pub user_id: Option<String>,

    /// IP address
    pub ip_address: Option<String>,

    /// Session ID
    pub session_id: Option<String>,

    /// Request ID for tracing
    pub request_id: Option<String>,

    /// Additional custom fields
    #[serde(flatten)]
    pub custom: std::collections::HashMap<String, serde_json::Value>,
}

impl Default for AuditMetadata {
    fn default() -> Self {
        Self {
            user_id: None,
            ip_address: None,
            session_id: None,
            request_id: None,
            custom: std::collections::HashMap::new(),
        }
    }
}

/// Audit log entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEntry {
    /// Unique entry ID
    pub id: String,

    /// Timestamp
    pub timestamp: SystemTime,

    /// Event type
    pub event_type: AuditEventType,

    /// Severity level
    pub severity: AuditSeverity,

    /// Outcome
    pub outcome: AuditOutcome,

    /// Resource affected (e.g., vector ID, index name)
    pub resource: Option<String>,

    /// Action description
    pub action: String,

    /// Additional details
    pub details: Option<String>,

    /// Metadata (user, IP, etc.)
    pub metadata: AuditMetadata,

    /// Duration in milliseconds (for operations)
    pub duration_ms: Option<u64>,
}

impl AuditEntry {
    /// Create a new audit entry
    pub fn new(event_type: AuditEventType, action: impl Into<String>) -> Self {
        let timestamp = SystemTime::now();
        let micros = timestamp
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_micros();

        // Generate a simple unique ID based on timestamp and random component
        let random_component = (micros % 1000000) as u32;
        let id = format!("audit-{}-{}", micros, random_component);

        Self {
            id,
            timestamp,
            event_type,
            severity: AuditSeverity::Info,
            outcome: AuditOutcome::Success,
            resource: None,
            action: action.into(),
            details: None,
            metadata: AuditMetadata::default(),
            duration_ms: None,
        }
    }

    /// Set severity
    pub fn with_severity(mut self, severity: AuditSeverity) -> Self {
        self.severity = severity;
        self
    }

    /// Set outcome
    pub fn with_outcome(mut self, outcome: AuditOutcome) -> Self {
        self.outcome = outcome;
        self
    }

    /// Set resource
    pub fn with_resource(mut self, resource: impl Into<String>) -> Self {
        self.resource = Some(resource.into());
        self
    }

    /// Set details
    pub fn with_details(mut self, details: impl Into<String>) -> Self {
        self.details = Some(details.into());
        self
    }

    /// Set user ID
    pub fn with_user(mut self, user_id: impl Into<String>) -> Self {
        self.metadata.user_id = Some(user_id.into());
        self
    }

    /// Set IP address
    pub fn with_ip(mut self, ip: impl Into<String>) -> Self {
        self.metadata.ip_address = Some(ip.into());
        self
    }

    /// Set duration
    pub fn with_duration(mut self, duration_ms: u64) -> Self {
        self.duration_ms = Some(duration_ms);
        self
    }
}

/// Audit backend trait
pub trait AuditBackend: Send + Sync {
    /// Write an audit entry
    fn write(&mut self, entry: &AuditEntry) -> Result<(), String>;

    /// Flush any buffered entries
    fn flush(&mut self) -> Result<(), String>;
}

/// In-memory audit backend
pub struct MemoryBackend {
    entries: Arc<Mutex<VecDeque<AuditEntry>>>,
    max_size: usize,
}

impl MemoryBackend {
    pub fn new(max_size: usize) -> Self {
        Self {
            entries: Arc::new(Mutex::new(VecDeque::with_capacity(max_size))),
            max_size,
        }
    }

    pub fn get_entries(&self) -> Vec<AuditEntry> {
        self.entries.lock().unwrap().iter().cloned().collect()
    }

    pub fn clear(&self) {
        self.entries.lock().unwrap().clear();
    }
}

impl AuditBackend for MemoryBackend {
    fn write(&mut self, entry: &AuditEntry) -> Result<(), String> {
        let mut entries = self.entries.lock().unwrap();
        if entries.len() >= self.max_size {
            entries.pop_front();
        }
        entries.push_back(entry.clone());
        Ok(())
    }

    fn flush(&mut self) -> Result<(), String> {
        Ok(())
    }
}

/// File-based audit backend
pub struct FileBackend {
    file: Arc<Mutex<File>>,
    buffer: Arc<Mutex<Vec<String>>>,
    buffer_size: usize,
}

impl FileBackend {
    pub fn new(path: PathBuf) -> Result<Self, String> {
        let file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(path)
            .map_err(|e| format!("Failed to open audit log file: {}", e))?;

        Ok(Self {
            file: Arc::new(Mutex::new(file)),
            buffer: Arc::new(Mutex::new(Vec::new())),
            buffer_size: 100,
        })
    }

    pub fn with_buffer_size(mut self, size: usize) -> Self {
        self.buffer_size = size;
        self
    }
}

impl AuditBackend for FileBackend {
    fn write(&mut self, entry: &AuditEntry) -> Result<(), String> {
        let json = serde_json::to_string(entry)
            .map_err(|e| format!("Failed to serialize audit entry: {}", e))?;

        let mut buffer = self.buffer.lock().unwrap();
        buffer.push(json);

        if buffer.len() >= self.buffer_size {
            drop(buffer);
            self.flush()?;
        }

        Ok(())
    }

    fn flush(&mut self) -> Result<(), String> {
        let mut buffer = self.buffer.lock().unwrap();
        if buffer.is_empty() {
            return Ok(());
        }

        let mut file = self.file.lock().unwrap();

        for line in buffer.iter() {
            writeln!(file, "{}", line).map_err(|e| format!("Failed to write audit log: {}", e))?;
        }

        file.flush()
            .map_err(|e| format!("Failed to flush audit log: {}", e))?;

        buffer.clear();
        Ok(())
    }
}

/// Stdout audit backend (for development)
pub struct StdoutBackend;

impl AuditBackend for StdoutBackend {
    fn write(&mut self, entry: &AuditEntry) -> Result<(), String> {
        let json = serde_json::to_string(entry)
            .map_err(|e| format!("Failed to serialize audit entry: {}", e))?;
        println!("{}", json);
        Ok(())
    }

    fn flush(&mut self) -> Result<(), String> {
        Ok(())
    }
}

/// Audit logger configuration
#[derive(Debug, Clone)]
pub struct AuditConfig {
    /// Enable audit logging
    pub enabled: bool,

    /// Minimum severity level to log
    pub min_severity: AuditSeverity,

    /// Event types to log
    pub event_types: Vec<AuditEventType>,

    /// Include stack traces for errors
    pub include_stack_traces: bool,
}

impl Default for AuditConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            min_severity: AuditSeverity::Info,
            event_types: vec![
                AuditEventType::Insert,
                AuditEventType::Update,
                AuditEventType::Delete,
                AuditEventType::Query,
                AuditEventType::Auth,
                AuditEventType::Authz,
                AuditEventType::ConfigChange,
            ],
            include_stack_traces: false,
        }
    }
}

/// Audit logger
pub struct AuditLogger {
    config: AuditConfig,
    backends: Arc<Mutex<Vec<Box<dyn AuditBackend>>>>,
}

impl AuditLogger {
    /// Create a new audit logger
    pub fn new(config: AuditConfig) -> Self {
        Self {
            config,
            backends: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// Create with default configuration
    pub fn default() -> Self {
        Self::new(AuditConfig::default())
    }

    /// Add a backend
    pub fn add_backend(&self, backend: Box<dyn AuditBackend>) {
        self.backends.lock().unwrap().push(backend);
    }

    /// Log an audit entry
    pub fn log(&self, entry: AuditEntry) -> Result<(), String> {
        if !self.config.enabled {
            return Ok(());
        }

        // Check severity filter
        if entry.severity < self.config.min_severity {
            return Ok(());
        }

        // Check event type filter
        if !self.config.event_types.is_empty()
            && !self.config.event_types.contains(&entry.event_type)
        {
            return Ok(());
        }

        // Write to all backends
        let mut backends = self.backends.lock().unwrap();
        for backend in backends.iter_mut() {
            backend.write(&entry)?;
        }

        Ok(())
    }

    /// Flush all backends
    pub fn flush(&self) -> Result<(), String> {
        let mut backends = self.backends.lock().unwrap();
        for backend in backends.iter_mut() {
            backend.flush()?;
        }
        Ok(())
    }

    /// Log an insert operation
    pub fn log_insert(&self, resource: &str, user_id: Option<&str>) -> Result<(), String> {
        let mut entry = AuditEntry::new(AuditEventType::Insert, "insert vector");
        entry = entry.with_resource(resource);
        if let Some(user) = user_id {
            entry = entry.with_user(user);
        }
        self.log(entry)
    }

    /// Log a query operation
    pub fn log_query(
        &self,
        query_type: &str,
        duration_ms: u64,
        user_id: Option<&str>,
    ) -> Result<(), String> {
        let mut entry = AuditEntry::new(AuditEventType::Query, format!("query: {}", query_type));
        entry = entry.with_duration(duration_ms);
        if let Some(user) = user_id {
            entry = entry.with_user(user);
        }
        self.log(entry)
    }

    /// Log a delete operation
    pub fn log_delete(&self, resource: &str, user_id: Option<&str>) -> Result<(), String> {
        let mut entry = AuditEntry::new(AuditEventType::Delete, "delete vector");
        entry = entry
            .with_resource(resource)
            .with_severity(AuditSeverity::Warning);
        if let Some(user) = user_id {
            entry = entry.with_user(user);
        }
        self.log(entry)
    }

    /// Log an authentication event
    pub fn log_auth(&self, user_id: &str, ip: &str, outcome: AuditOutcome) -> Result<(), String> {
        let entry = AuditEntry::new(AuditEventType::Auth, "authentication attempt")
            .with_user(user_id)
            .with_ip(ip)
            .with_outcome(outcome)
            .with_severity(if outcome == AuditOutcome::Success {
                AuditSeverity::Info
            } else {
                AuditSeverity::Warning
            });
        self.log(entry)
    }

    /// Log an authorization event
    pub fn log_authz(
        &self,
        user_id: &str,
        resource: &str,
        action: &str,
        outcome: AuditOutcome,
    ) -> Result<(), String> {
        let entry = AuditEntry::new(AuditEventType::Authz, format!("authz: {}", action))
            .with_user(user_id)
            .with_resource(resource)
            .with_outcome(outcome)
            .with_severity(if outcome == AuditOutcome::Denied {
                AuditSeverity::Warning
            } else {
                AuditSeverity::Info
            });
        self.log(entry)
    }
}

impl Drop for AuditLogger {
    fn drop(&mut self) {
        let _ = self.flush();
    }
}

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

    #[test]
    fn test_audit_entry_creation() {
        let entry = AuditEntry::new(AuditEventType::Insert, "test action");
        assert_eq!(entry.event_type, AuditEventType::Insert);
        assert_eq!(entry.action, "test action");
        assert_eq!(entry.severity, AuditSeverity::Info);
        assert_eq!(entry.outcome, AuditOutcome::Success);
    }

    #[test]
    fn test_audit_entry_builder() {
        let entry = AuditEntry::new(AuditEventType::Query, "test query")
            .with_severity(AuditSeverity::Warning)
            .with_outcome(AuditOutcome::Failure)
            .with_resource("vector_123")
            .with_user("user_456")
            .with_ip("192.168.1.1")
            .with_duration(100);

        assert_eq!(entry.severity, AuditSeverity::Warning);
        assert_eq!(entry.outcome, AuditOutcome::Failure);
        assert_eq!(entry.resource, Some("vector_123".to_string()));
        assert_eq!(entry.metadata.user_id, Some("user_456".to_string()));
        assert_eq!(entry.metadata.ip_address, Some("192.168.1.1".to_string()));
        assert_eq!(entry.duration_ms, Some(100));
    }

    #[test]
    fn test_memory_backend() {
        let mut backend = MemoryBackend::new(10);

        let entry = AuditEntry::new(AuditEventType::Insert, "test");
        backend.write(&entry).unwrap();

        let entries = backend.get_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].action, "test");
    }

    #[test]
    fn test_memory_backend_overflow() {
        let mut backend = MemoryBackend::new(3);

        for i in 0..5 {
            let entry = AuditEntry::new(AuditEventType::Insert, format!("action_{}", i));
            backend.write(&entry).unwrap();
        }

        let entries = backend.get_entries();
        assert_eq!(entries.len(), 3);
        // Should have the last 3 entries
        assert_eq!(entries[0].action, "action_2");
        assert_eq!(entries[2].action, "action_4");
    }

    #[test]
    fn test_audit_logger() {
        let logger = AuditLogger::default();
        let backend = Box::new(MemoryBackend::new(100));
        let backend_ref = unsafe {
            let ptr = &*backend as *const MemoryBackend;
            &*ptr
        };
        logger.add_backend(backend);

        let entry = AuditEntry::new(AuditEventType::Query, "test query");
        logger.log(entry).unwrap();

        let entries = backend_ref.get_entries();
        assert_eq!(entries.len(), 1);
    }

    #[test]
    fn test_severity_filtering() {
        let mut config = AuditConfig::default();
        config.min_severity = AuditSeverity::Warning;

        let logger = AuditLogger::new(config);
        let backend = Box::new(MemoryBackend::new(100));
        let backend_ref = unsafe {
            let ptr = &*backend as *const MemoryBackend;
            &*ptr
        };
        logger.add_backend(backend);

        // Info level - should be filtered
        let entry1 =
            AuditEntry::new(AuditEventType::Query, "info entry").with_severity(AuditSeverity::Info);
        logger.log(entry1).unwrap();

        // Warning level - should be logged
        let entry2 = AuditEntry::new(AuditEventType::Query, "warning entry")
            .with_severity(AuditSeverity::Warning);
        logger.log(entry2).unwrap();

        let entries = backend_ref.get_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].action, "warning entry");
    }

    #[test]
    fn test_event_type_filtering() {
        let mut config = AuditConfig::default();
        config.event_types = vec![AuditEventType::Insert, AuditEventType::Delete];

        let logger = AuditLogger::new(config);
        let backend = Box::new(MemoryBackend::new(100));
        let backend_ref = unsafe {
            let ptr = &*backend as *const MemoryBackend;
            &*ptr
        };
        logger.add_backend(backend);

        // Insert - should be logged
        logger.log_insert("vec_1", Some("user_1")).unwrap();

        // Query - should be filtered
        logger.log_query("knn", 100, Some("user_1")).unwrap();

        // Delete - should be logged
        logger.log_delete("vec_2", Some("user_1")).unwrap();

        let entries = backend_ref.get_entries();
        assert_eq!(entries.len(), 2);
    }

    #[test]
    fn test_helper_methods() {
        let logger = AuditLogger::default();
        let backend = Box::new(MemoryBackend::new(100));
        let backend_ref = unsafe {
            let ptr = &*backend as *const MemoryBackend;
            &*ptr
        };
        logger.add_backend(backend);

        logger.log_insert("vec_1", Some("user_1")).unwrap();
        logger.log_query("knn", 50, Some("user_2")).unwrap();
        logger.log_delete("vec_3", Some("user_3")).unwrap();
        logger
            .log_auth("user_4", "192.168.1.1", AuditOutcome::Success)
            .unwrap();
        logger
            .log_authz("user_5", "vec_5", "read", AuditOutcome::Denied)
            .unwrap();

        let entries = backend_ref.get_entries();
        assert_eq!(entries.len(), 5);
    }

    #[test]
    fn test_disabled_logger() {
        let mut config = AuditConfig::default();
        config.enabled = false;

        let logger = AuditLogger::new(config);
        let backend = Box::new(MemoryBackend::new(100));
        let backend_ref = unsafe {
            let ptr = &*backend as *const MemoryBackend;
            &*ptr
        };
        logger.add_backend(backend);

        logger.log_insert("vec_1", Some("user_1")).unwrap();

        let entries = backend_ref.get_entries();
        assert_eq!(entries.len(), 0);
    }
}