ruvector-collections 2.0.6

High-performance collection management for Ruvector vector databases
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
//! Collection manager for multi-collection operations

use dashmap::DashMap;
use parking_lot::RwLock;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use crate::collection::{Collection, CollectionConfig, CollectionStats};
use crate::error::{CollectionError, Result};

/// Metadata for persisting collections
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct CollectionMetadata {
    name: String,
    config: CollectionConfig,
    created_at: i64,
    updated_at: i64,
}

/// Manages multiple vector collections with alias support
#[derive(Debug)]
pub struct CollectionManager {
    /// Active collections
    collections: DashMap<String, Arc<RwLock<Collection>>>,

    /// Alias mappings (alias -> collection_name)
    aliases: DashMap<String, String>,

    /// Base path for storing collections
    base_path: PathBuf,
}

impl CollectionManager {
    /// Create a new collection manager
    ///
    /// # Arguments
    ///
    /// * `base_path` - Directory where collections will be stored
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ruvector_collections::CollectionManager;
    /// use std::path::PathBuf;
    ///
    /// let manager = CollectionManager::new(PathBuf::from("./collections")).unwrap();
    /// ```
    pub fn new(base_path: PathBuf) -> Result<Self> {
        // Create base directory if it doesn't exist
        std::fs::create_dir_all(&base_path)?;

        let manager = Self {
            collections: DashMap::new(),
            aliases: DashMap::new(),
            base_path,
        };

        // Load existing collections
        manager.load_collections()?;

        Ok(manager)
    }

    /// Create a new collection
    ///
    /// # Arguments
    ///
    /// * `name` - Collection name (must be unique)
    /// * `config` - Collection configuration
    ///
    /// # Errors
    ///
    /// Returns `CollectionAlreadyExists` if a collection with the same name exists
    pub fn create_collection(&self, name: &str, config: CollectionConfig) -> Result<()> {
        // Validate collection name
        Self::validate_name(name)?;

        // Check if collection already exists
        if self.collections.contains_key(name) {
            return Err(CollectionError::CollectionAlreadyExists {
                name: name.to_string(),
            });
        }

        // Check if an alias with this name exists
        if self.aliases.contains_key(name) {
            return Err(CollectionError::InvalidName {
                name: name.to_string(),
                reason: "An alias with this name already exists".to_string(),
            });
        }

        // Create storage path for this collection
        let storage_path = self.base_path.join(name);
        std::fs::create_dir_all(&storage_path)?;

        let db_path = storage_path
            .join("vectors.db")
            .to_string_lossy()
            .to_string();

        // Create collection
        let collection = Collection::new(name.to_string(), config, db_path)?;

        // Save metadata
        self.save_collection_metadata(&collection)?;

        // Add to collections map
        self.collections
            .insert(name.to_string(), Arc::new(RwLock::new(collection)));

        Ok(())
    }

    /// Delete a collection
    ///
    /// # Arguments
    ///
    /// * `name` - Collection name to delete
    ///
    /// # Errors
    ///
    /// Returns `CollectionNotFound` if collection doesn't exist
    /// Returns `CollectionHasAliases` if collection has active aliases
    pub fn delete_collection(&self, name: &str) -> Result<()> {
        // Check if collection exists
        if !self.collections.contains_key(name) {
            return Err(CollectionError::CollectionNotFound {
                name: name.to_string(),
            });
        }

        // Check for active aliases
        let active_aliases: Vec<String> = self
            .aliases
            .iter()
            .filter(|entry| entry.value() == name)
            .map(|entry| entry.key().clone())
            .collect();

        if !active_aliases.is_empty() {
            return Err(CollectionError::CollectionHasAliases {
                collection: name.to_string(),
                aliases: active_aliases,
            });
        }

        // Remove from collections map
        self.collections.remove(name);

        // Delete from disk
        let collection_path = self.base_path.join(name);
        if collection_path.exists() {
            std::fs::remove_dir_all(&collection_path)?;
        }

        Ok(())
    }

    /// Get a collection by name or alias
    ///
    /// # Arguments
    ///
    /// * `name` - Collection name or alias
    pub fn get_collection(&self, name: &str) -> Option<Arc<RwLock<Collection>>> {
        // Try to resolve as alias first
        let collection_name = self.resolve_alias(name).unwrap_or_else(|| name.to_string());

        self.collections
            .get(&collection_name)
            .map(|entry| entry.value().clone())
    }

    /// List all collection names
    pub fn list_collections(&self) -> Vec<String> {
        self.collections
            .iter()
            .map(|entry| entry.key().clone())
            .collect()
    }

    /// Check if a collection exists
    ///
    /// # Arguments
    ///
    /// * `name` - Collection name (not alias)
    pub fn collection_exists(&self, name: &str) -> bool {
        self.collections.contains_key(name)
    }

    /// Get statistics for a collection
    pub fn collection_stats(&self, name: &str) -> Result<CollectionStats> {
        let collection =
            self.get_collection(name)
                .ok_or_else(|| CollectionError::CollectionNotFound {
                    name: name.to_string(),
                })?;

        let guard = collection.read();
        guard.stats()
    }

    // ===== Alias Management =====

    /// Create an alias for a collection
    ///
    /// # Arguments
    ///
    /// * `alias` - Alias name (must be unique)
    /// * `collection` - Target collection name
    ///
    /// # Errors
    ///
    /// Returns `AliasAlreadyExists` if alias already exists
    /// Returns `CollectionNotFound` if target collection doesn't exist
    pub fn create_alias(&self, alias: &str, collection: &str) -> Result<()> {
        // Validate alias name
        Self::validate_name(alias)?;

        // Check if alias already exists
        if self.aliases.contains_key(alias) {
            return Err(CollectionError::AliasAlreadyExists {
                alias: alias.to_string(),
            });
        }

        // Check if a collection with this name exists
        if self.collections.contains_key(alias) {
            return Err(CollectionError::InvalidName {
                name: alias.to_string(),
                reason: "A collection with this name already exists".to_string(),
            });
        }

        // Verify target collection exists
        if !self.collections.contains_key(collection) {
            return Err(CollectionError::CollectionNotFound {
                name: collection.to_string(),
            });
        }

        // Create alias
        self.aliases
            .insert(alias.to_string(), collection.to_string());

        // Save aliases
        self.save_aliases()?;

        Ok(())
    }

    /// Delete an alias
    ///
    /// # Arguments
    ///
    /// * `alias` - Alias name to delete
    ///
    /// # Errors
    ///
    /// Returns `AliasNotFound` if alias doesn't exist
    pub fn delete_alias(&self, alias: &str) -> Result<()> {
        if self.aliases.remove(alias).is_none() {
            return Err(CollectionError::AliasNotFound {
                alias: alias.to_string(),
            });
        }

        // Save aliases
        self.save_aliases()?;

        Ok(())
    }

    /// Switch an alias to point to a different collection
    ///
    /// # Arguments
    ///
    /// * `alias` - Alias name
    /// * `new_collection` - New target collection name
    ///
    /// # Errors
    ///
    /// Returns `AliasNotFound` if alias doesn't exist
    /// Returns `CollectionNotFound` if new collection doesn't exist
    pub fn switch_alias(&self, alias: &str, new_collection: &str) -> Result<()> {
        // Verify alias exists
        if !self.aliases.contains_key(alias) {
            return Err(CollectionError::AliasNotFound {
                alias: alias.to_string(),
            });
        }

        // Verify new collection exists
        if !self.collections.contains_key(new_collection) {
            return Err(CollectionError::CollectionNotFound {
                name: new_collection.to_string(),
            });
        }

        // Update alias
        self.aliases
            .insert(alias.to_string(), new_collection.to_string());

        // Save aliases
        self.save_aliases()?;

        Ok(())
    }

    /// Resolve an alias to a collection name
    ///
    /// # Arguments
    ///
    /// * `name_or_alias` - Collection name or alias
    ///
    /// # Returns
    ///
    /// `Some(collection_name)` if it's an alias, `None` if it's not an alias
    pub fn resolve_alias(&self, name_or_alias: &str) -> Option<String> {
        self.aliases
            .get(name_or_alias)
            .map(|entry| entry.value().clone())
    }

    /// List all aliases with their target collections
    pub fn list_aliases(&self) -> Vec<(String, String)> {
        self.aliases
            .iter()
            .map(|entry| (entry.key().clone(), entry.value().clone()))
            .collect()
    }

    /// Check if a name is an alias
    pub fn is_alias(&self, name: &str) -> bool {
        self.aliases.contains_key(name)
    }

    // ===== Internal Methods =====

    /// Validate a collection or alias name
    fn validate_name(name: &str) -> Result<()> {
        if name.is_empty() {
            return Err(CollectionError::InvalidName {
                name: name.to_string(),
                reason: "Name cannot be empty".to_string(),
            });
        }

        if name.len() > 255 {
            return Err(CollectionError::InvalidName {
                name: name.to_string(),
                reason: "Name too long (max 255 characters)".to_string(),
            });
        }

        // Only allow alphanumeric, hyphens, underscores
        if !name
            .chars()
            .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
        {
            return Err(CollectionError::InvalidName {
                name: name.to_string(),
                reason: "Name can only contain letters, numbers, hyphens, and underscores"
                    .to_string(),
            });
        }

        Ok(())
    }

    /// Load existing collections from disk
    fn load_collections(&self) -> Result<()> {
        if !self.base_path.exists() {
            return Ok(());
        }

        // Load aliases
        self.load_aliases()?;

        // Scan for collection directories
        for entry in std::fs::read_dir(&self.base_path)? {
            let entry = entry?;
            let path = entry.path();

            if path.is_dir() {
                let name = path
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("")
                    .to_string();

                // Skip special directories
                if name.starts_with('.') || name == "aliases.json" {
                    continue;
                }

                // Try to load collection metadata
                if let Ok(metadata) = self.load_collection_metadata(&name) {
                    let db_path = path.join("vectors.db").to_string_lossy().to_string();

                    // Recreate collection
                    if let Ok(mut collection) =
                        Collection::new(metadata.name.clone(), metadata.config, db_path)
                    {
                        collection.created_at = metadata.created_at;
                        collection.updated_at = metadata.updated_at;

                        self.collections
                            .insert(name.clone(), Arc::new(RwLock::new(collection)));
                    }
                }
            }
        }

        Ok(())
    }

    /// Save collection metadata to disk
    fn save_collection_metadata(&self, collection: &Collection) -> Result<()> {
        let metadata = CollectionMetadata {
            name: collection.name.clone(),
            config: collection.config.clone(),
            created_at: collection.created_at,
            updated_at: collection.updated_at,
        };

        let metadata_path = self.base_path.join(&collection.name).join("metadata.json");

        let json = serde_json::to_string_pretty(&metadata)?;
        std::fs::write(metadata_path, json)?;

        Ok(())
    }

    /// Load collection metadata from disk
    fn load_collection_metadata(&self, name: &str) -> Result<CollectionMetadata> {
        let metadata_path = self.base_path.join(name).join("metadata.json");
        let json = std::fs::read_to_string(metadata_path)?;
        let metadata: CollectionMetadata = serde_json::from_str(&json)?;
        Ok(metadata)
    }

    /// Save aliases to disk
    fn save_aliases(&self) -> Result<()> {
        let aliases: HashMap<String, String> = self
            .aliases
            .iter()
            .map(|entry| (entry.key().clone(), entry.value().clone()))
            .collect();

        let aliases_path = self.base_path.join("aliases.json");
        let json = serde_json::to_string_pretty(&aliases)?;
        std::fs::write(aliases_path, json)?;

        Ok(())
    }

    /// Load aliases from disk
    fn load_aliases(&self) -> Result<()> {
        let aliases_path = self.base_path.join("aliases.json");

        if !aliases_path.exists() {
            return Ok(());
        }

        let json = std::fs::read_to_string(aliases_path)?;
        let aliases: HashMap<String, String> = serde_json::from_str(&json)?;

        for (alias, collection) in aliases {
            self.aliases.insert(alias, collection);
        }

        Ok(())
    }
}

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

    #[test]
    fn test_validate_name() {
        assert!(CollectionManager::validate_name("valid-name_123").is_ok());
        assert!(CollectionManager::validate_name("").is_err());
        assert!(CollectionManager::validate_name("invalid name").is_err());
        assert!(CollectionManager::validate_name("invalid/name").is_err());
    }

    #[test]
    fn test_collection_manager() -> Result<()> {
        let temp_dir = std::env::temp_dir().join("ruvector_test_collections");
        let _ = std::fs::remove_dir_all(&temp_dir);

        let manager = CollectionManager::new(temp_dir.clone())?;

        // Create collection
        let config = CollectionConfig::with_dimensions(128);
        manager.create_collection("test", config)?;

        assert!(manager.collection_exists("test"));
        assert_eq!(manager.list_collections().len(), 1);

        // Create alias
        manager.create_alias("test_alias", "test")?;
        assert!(manager.is_alias("test_alias"));
        assert_eq!(
            manager.resolve_alias("test_alias"),
            Some("test".to_string())
        );

        // Get collection by alias
        assert!(manager.get_collection("test_alias").is_some());

        // Cleanup
        manager.delete_alias("test_alias")?;
        manager.delete_collection("test")?;
        let _ = std::fs::remove_dir_all(&temp_dir);

        Ok(())
    }
}