oxirs-vec 0.2.4

Vector index abstractions for semantic similarity and AI-augmented querying
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
//! Data isolation strategies for multi-tenancy

use crate::multi_tenancy::types::{MultiTenancyError, MultiTenancyResult};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

/// Level of tenant isolation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum IsolationLevel {
    /// Shared index with namespace prefixes (lowest isolation, highest efficiency)
    Namespace,

    /// Separate indices per tenant (medium isolation)
    SeparateIndex,

    /// Separate databases/instances per tenant (highest isolation, highest cost)
    Dedicated,
}

impl IsolationLevel {
    /// Get isolation strength (0-10, higher = stronger)
    pub fn strength(&self) -> u8 {
        match self {
            Self::Namespace => 3,
            Self::SeparateIndex => 7,
            Self::Dedicated => 10,
        }
    }

    /// Get performance efficiency (0-10, higher = more efficient)
    pub fn efficiency(&self) -> u8 {
        match self {
            Self::Namespace => 10,
            Self::SeparateIndex => 6,
            Self::Dedicated => 3,
        }
    }

    /// Recommended for tenant tier
    pub fn for_tier(tier: &str) -> Self {
        match tier {
            "free" | "trial" => Self::Namespace,
            "pro" | "business" => Self::SeparateIndex,
            "enterprise" | "dedicated" => Self::Dedicated,
            _ => Self::Namespace,
        }
    }
}

/// Isolation strategy configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IsolationStrategy {
    /// Base isolation level
    pub level: IsolationLevel,

    /// Whether to encrypt tenant data at rest
    pub encryption_at_rest: bool,

    /// Whether to encrypt tenant data in transit
    pub encryption_in_transit: bool,

    /// Custom namespace separator
    pub namespace_separator: String,

    /// Maximum namespace depth
    pub max_namespace_depth: usize,
}

impl IsolationStrategy {
    /// Create new isolation strategy
    pub fn new(level: IsolationLevel) -> Self {
        Self {
            level,
            encryption_at_rest: false,
            encryption_in_transit: true,
            namespace_separator: ":".to_string(),
            max_namespace_depth: 5,
        }
    }

    /// Create strategy for free tier
    pub fn free_tier() -> Self {
        Self::new(IsolationLevel::Namespace)
    }

    /// Create strategy for pro tier
    pub fn pro_tier() -> Self {
        let mut strategy = Self::new(IsolationLevel::SeparateIndex);
        strategy.encryption_at_rest = true;
        strategy
    }

    /// Create strategy for enterprise tier
    pub fn enterprise_tier() -> Self {
        let mut strategy = Self::new(IsolationLevel::Dedicated);
        strategy.encryption_at_rest = true;
        strategy
    }

    /// Enable encryption
    pub fn with_encryption(mut self, at_rest: bool, in_transit: bool) -> Self {
        self.encryption_at_rest = at_rest;
        self.encryption_in_transit = in_transit;
        self
    }

    /// Set custom namespace separator
    pub fn with_separator(mut self, separator: impl Into<String>) -> Self {
        self.namespace_separator = separator.into();
        self
    }
}

/// Namespace manager for tenant data isolation
pub struct NamespaceManager {
    /// Tenant namespaces
    namespaces: Arc<RwLock<HashMap<String, Namespace>>>,

    /// Isolation strategy
    strategy: IsolationStrategy,
}

/// Namespace for tenant data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Namespace {
    /// Tenant identifier
    pub tenant_id: String,

    /// Namespace prefix
    pub prefix: String,

    /// Sub-namespaces
    pub sub_namespaces: Vec<String>,

    /// Metadata
    pub metadata: HashMap<String, String>,
}

impl Namespace {
    /// Create new namespace
    pub fn new(tenant_id: impl Into<String>, prefix: impl Into<String>) -> Self {
        Self {
            tenant_id: tenant_id.into(),
            prefix: prefix.into(),
            sub_namespaces: Vec::new(),
            metadata: HashMap::new(),
        }
    }

    /// Create sub-namespace
    pub fn create_sub_namespace(&mut self, name: impl Into<String>, separator: &str) -> String {
        let sub = format!("{}{}{}", self.prefix, separator, name.into());
        self.sub_namespaces.push(sub.clone());
        sub
    }

    /// Get fully qualified key
    pub fn qualify_key(&self, key: &str, separator: &str) -> String {
        format!("{}{}{}", self.prefix, separator, key)
    }

    /// Check if key belongs to this namespace
    pub fn owns_key(&self, key: &str) -> bool {
        key.starts_with(&self.prefix)
    }
}

impl NamespaceManager {
    /// Create new namespace manager
    pub fn new(strategy: IsolationStrategy) -> Self {
        Self {
            namespaces: Arc::new(RwLock::new(HashMap::new())),
            strategy,
        }
    }

    /// Register namespace for tenant
    pub fn register_tenant(&self, tenant_id: impl Into<String>) -> MultiTenancyResult<String> {
        let tenant_id = tenant_id.into();
        let prefix = self.generate_namespace_prefix(&tenant_id);

        let namespace = Namespace::new(tenant_id.clone(), prefix.clone());

        let mut namespaces =
            self.namespaces
                .write()
                .map_err(|e| MultiTenancyError::InternalError {
                    message: format!("Lock error: {}", e),
                })?;

        if namespaces.contains_key(&tenant_id) {
            return Err(MultiTenancyError::TenantAlreadyExists {
                tenant_id: tenant_id.clone(),
            });
        }

        namespaces.insert(tenant_id, namespace);

        Ok(prefix)
    }

    /// Unregister tenant namespace
    pub fn unregister_tenant(&self, tenant_id: &str) -> MultiTenancyResult<()> {
        let mut namespaces =
            self.namespaces
                .write()
                .map_err(|e| MultiTenancyError::InternalError {
                    message: format!("Lock error: {}", e),
                })?;

        namespaces
            .remove(tenant_id)
            .ok_or_else(|| MultiTenancyError::TenantNotFound {
                tenant_id: tenant_id.to_string(),
            })?;

        Ok(())
    }

    /// Get namespace prefix for tenant
    pub fn get_prefix(&self, tenant_id: &str) -> MultiTenancyResult<String> {
        let namespaces = self
            .namespaces
            .read()
            .map_err(|e| MultiTenancyError::InternalError {
                message: format!("Lock error: {}", e),
            })?;

        namespaces
            .get(tenant_id)
            .map(|ns| ns.prefix.clone())
            .ok_or_else(|| MultiTenancyError::TenantNotFound {
                tenant_id: tenant_id.to_string(),
            })
    }

    /// Qualify key with tenant namespace
    pub fn qualify_key(&self, tenant_id: &str, key: &str) -> MultiTenancyResult<String> {
        let namespaces = self
            .namespaces
            .read()
            .map_err(|e| MultiTenancyError::InternalError {
                message: format!("Lock error: {}", e),
            })?;

        let namespace =
            namespaces
                .get(tenant_id)
                .ok_or_else(|| MultiTenancyError::TenantNotFound {
                    tenant_id: tenant_id.to_string(),
                })?;

        Ok(namespace.qualify_key(key, &self.strategy.namespace_separator))
    }

    /// Extract tenant ID from namespaced key
    pub fn extract_tenant_id(&self, namespaced_key: &str) -> MultiTenancyResult<String> {
        let namespaces = self
            .namespaces
            .read()
            .map_err(|e| MultiTenancyError::InternalError {
                message: format!("Lock error: {}", e),
            })?;

        for (tenant_id, namespace) in namespaces.iter() {
            if namespace.owns_key(namespaced_key) {
                return Ok(tenant_id.clone());
            }
        }

        Err(MultiTenancyError::IsolationViolation {
            message: format!("No tenant owns key: {}", namespaced_key),
        })
    }

    /// Validate that a key belongs to a tenant
    pub fn validate_access(&self, tenant_id: &str, key: &str) -> MultiTenancyResult<bool> {
        let namespaces = self
            .namespaces
            .read()
            .map_err(|e| MultiTenancyError::InternalError {
                message: format!("Lock error: {}", e),
            })?;

        let namespace =
            namespaces
                .get(tenant_id)
                .ok_or_else(|| MultiTenancyError::TenantNotFound {
                    tenant_id: tenant_id.to_string(),
                })?;

        Ok(namespace.owns_key(key))
    }

    /// Create sub-namespace for tenant
    pub fn create_sub_namespace(
        &self,
        tenant_id: &str,
        name: impl Into<String>,
    ) -> MultiTenancyResult<String> {
        let mut namespaces =
            self.namespaces
                .write()
                .map_err(|e| MultiTenancyError::InternalError {
                    message: format!("Lock error: {}", e),
                })?;

        let namespace =
            namespaces
                .get_mut(tenant_id)
                .ok_or_else(|| MultiTenancyError::TenantNotFound {
                    tenant_id: tenant_id.to_string(),
                })?;

        if namespace.sub_namespaces.len() >= self.strategy.max_namespace_depth {
            return Err(MultiTenancyError::InvalidConfiguration {
                message: "Maximum namespace depth exceeded".to_string(),
            });
        }

        Ok(namespace.create_sub_namespace(name, &self.strategy.namespace_separator))
    }

    /// Get all namespaces
    pub fn list_namespaces(&self) -> MultiTenancyResult<Vec<String>> {
        let namespaces = self
            .namespaces
            .read()
            .map_err(|e| MultiTenancyError::InternalError {
                message: format!("Lock error: {}", e),
            })?;

        Ok(namespaces.keys().cloned().collect())
    }

    /// Generate namespace prefix from tenant ID
    fn generate_namespace_prefix(&self, tenant_id: &str) -> String {
        // Sanitize tenant ID for use as namespace
        let sanitized: String = tenant_id
            .chars()
            .map(|c| match c {
                '-' | '.' | '/' => '_',
                c => c,
            })
            .collect();

        format!("tenant_{}", sanitized)
    }

    /// Get isolation strategy
    pub fn strategy(&self) -> &IsolationStrategy {
        &self.strategy
    }
}

#[cfg(test)]
mod tests {
    type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
    use super::*;

    #[test]
    fn test_isolation_levels() {
        assert_eq!(IsolationLevel::Namespace.strength(), 3);
        assert_eq!(IsolationLevel::SeparateIndex.strength(), 7);
        assert_eq!(IsolationLevel::Dedicated.strength(), 10);

        assert_eq!(IsolationLevel::Namespace.efficiency(), 10);
        assert_eq!(IsolationLevel::Dedicated.efficiency(), 3);
    }

    #[test]
    fn test_isolation_level_for_tier() {
        assert_eq!(IsolationLevel::for_tier("free"), IsolationLevel::Namespace);
        assert_eq!(
            IsolationLevel::for_tier("pro"),
            IsolationLevel::SeparateIndex
        );
        assert_eq!(
            IsolationLevel::for_tier("enterprise"),
            IsolationLevel::Dedicated
        );
    }

    #[test]
    fn test_isolation_strategy() {
        let strategy = IsolationStrategy::free_tier();
        assert_eq!(strategy.level, IsolationLevel::Namespace);
        assert!(!strategy.encryption_at_rest);

        let strategy = IsolationStrategy::pro_tier();
        assert_eq!(strategy.level, IsolationLevel::SeparateIndex);
        assert!(strategy.encryption_at_rest);

        let strategy = IsolationStrategy::enterprise_tier();
        assert_eq!(strategy.level, IsolationLevel::Dedicated);
        assert!(strategy.encryption_at_rest);
    }

    #[test]
    fn test_namespace_creation() {
        let ns = Namespace::new("tenant1", "tenant_tenant1");
        assert_eq!(ns.tenant_id, "tenant1");
        assert_eq!(ns.prefix, "tenant_tenant1");
        assert!(ns.sub_namespaces.is_empty());
    }

    #[test]
    fn test_namespace_qualification() {
        let ns = Namespace::new("tenant1", "tenant_tenant1");
        let qualified = ns.qualify_key("vector123", ":");
        assert_eq!(qualified, "tenant_tenant1:vector123");
        assert!(ns.owns_key(&qualified));
        assert!(!ns.owns_key("other_tenant:vector123"));
    }

    #[test]
    fn test_namespace_manager() -> Result<()> {
        let strategy = IsolationStrategy::new(IsolationLevel::Namespace);
        let manager = NamespaceManager::new(strategy);

        // Register tenant
        let prefix = manager.register_tenant("tenant1")?;
        assert!(prefix.contains("tenant_tenant1"));

        // Get prefix
        let retrieved_prefix = manager.get_prefix("tenant1")?;
        assert_eq!(prefix, retrieved_prefix);

        // Qualify key
        let qualified = manager.qualify_key("tenant1", "vector123")?;
        assert!(qualified.starts_with(&prefix));
        assert!(qualified.contains("vector123"));

        // Validate access
        let __val = manager.validate_access("tenant1", &qualified)?;
        assert!(__val);
        assert!(!manager.validate_access("tenant1", "other_tenant:key")?);

        // Extract tenant ID
        let extracted = manager.extract_tenant_id(&qualified)?;
        assert_eq!(extracted, "tenant1");

        // Unregister tenant
        manager.unregister_tenant("tenant1")?;
        assert!(manager.get_prefix("tenant1").is_err());
        Ok(())
    }

    #[test]
    fn test_sub_namespaces() -> Result<()> {
        let strategy = IsolationStrategy::new(IsolationLevel::Namespace);
        let manager = NamespaceManager::new(strategy);

        manager.register_tenant("tenant1")?;

        // Create sub-namespace
        let sub = manager.create_sub_namespace("tenant1", "vectors")?;
        assert!(sub.contains("tenant_tenant1"));
        assert!(sub.contains("vectors"));

        // Create another sub-namespace
        let sub2 = manager.create_sub_namespace("tenant1", "embeddings")?;
        assert!(sub2.contains("embeddings"));
        assert_ne!(sub, sub2);
        Ok(())
    }

    #[test]
    fn test_namespace_manager_errors() -> Result<()> {
        let strategy = IsolationStrategy::new(IsolationLevel::Namespace);
        let manager = NamespaceManager::new(strategy);

        // Getting prefix for non-existent tenant should fail
        assert!(manager.get_prefix("nonexistent").is_err());

        // Qualifying key for non-existent tenant should fail
        assert!(manager.qualify_key("nonexistent", "key").is_err());

        // Registering same tenant twice should fail
        manager.register_tenant("tenant1")?;
        assert!(manager.register_tenant("tenant1").is_err());

        // Unregistering non-existent tenant should fail
        assert!(manager.unregister_tenant("nonexistent").is_err());
        Ok(())
    }

    #[test]
    fn test_list_namespaces() -> Result<()> {
        let strategy = IsolationStrategy::new(IsolationLevel::Namespace);
        let manager = NamespaceManager::new(strategy);

        assert_eq!(manager.list_namespaces().expect("test value").len(), 0);

        manager.register_tenant("tenant1")?;
        manager.register_tenant("tenant2")?;

        let namespaces = manager.list_namespaces()?;
        assert_eq!(namespaces.len(), 2);
        assert!(namespaces.contains(&"tenant1".to_string()));
        assert!(namespaces.contains(&"tenant2".to_string()));
        Ok(())
    }
}