rag-module 0.6.7

Enterprise RAG module with chat context storage, vector search, session management, and model downloading. Rust implementation with Node.js compatibility.
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
//! Configuration management for the RAG module

pub mod service_registry;

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use tokio::fs;

/// Main configuration structure matching JavaScript version
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    #[serde(rename = "embeddingModel")]
    pub embedding_model: String,

    #[serde(rename = "embeddingDimensions")]
    pub embedding_dimensions: u32,

    #[serde(rename = "vectorStore")]
    pub vector_store: VectorStoreConfig,

    #[serde(rename = "chunkSize")]
    pub chunk_size: usize,

    #[serde(rename = "searchTopK")]
    pub search_top_k: usize,

    #[serde(rename = "privacyLevel")]
    pub privacy_level: String,

    #[serde(rename = "backendMapping")]
    pub backend_mapping: bool,

    // Compatibility fields for existing code
    pub encryption: crate::types::EncryptionConfig,
    pub embedding: crate::types::EmbeddingConfig,
    pub privacy: PrivacyConfig,
    pub iam: IAMConfig,

    #[serde(rename = "s3Config")]
    pub s3_config: S3Config,

    #[serde(rename = "azureBlobConfig")]
    pub azure_blob_config: AzureBlobConfig,

    #[serde(rename = "gcsConfig")]
    pub gcs_config: GcsConfig,
}

/// Vector store configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorStoreConfig {
    pub backend: String,
    pub connection: crate::types::QdrantConnectionConfig,
    #[serde(rename = "storagePath")]
    pub storage_path: Option<String>,
    /// Server URL for syncing (when using embedded mode)
    #[serde(rename = "serverSyncUrl")]
    pub server_sync_url: Option<String>,
    /// Whether to enable dual mode (embedded + server sync)
    #[serde(rename = "enableServerSync")]
    pub enable_server_sync: bool,
}

impl Default for VectorStoreConfig {
    fn default() -> Self {
        Self {
            backend: "qdrant-embedded".to_string(),
            connection: crate::types::QdrantConnectionConfig {
                url: "http://localhost:6333".to_string(),
                api_key: None,
                timeout_secs: 30,
            },
            storage_path: Some("./qdrant-data".to_string()),
            server_sync_url: Some("http://dev-qdrant-nlb-e8c337edc3ee861b.elb.ap-south-1.amazonaws.com:6334".to_string()),
            enable_server_sync: true,
        }
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            embedding_model: "embaas/sentence-transformers-e5-large-v2".to_string(),
            embedding_dimensions: 1024,
            vector_store: VectorStoreConfig::default(),
            chunk_size: 1024,
            search_top_k: 10,
            privacy_level: "minimal-aws".to_string(),
            backend_mapping: false,
            // Compatibility fields
            encryption: crate::types::EncryptionConfig::default(),
            embedding: crate::types::EmbeddingConfig::default(),
            privacy: PrivacyConfig::default(),
            iam: IAMConfig::default(),
            // JavaScript-style configs
            s3_config: S3Config::default(),
            azure_blob_config: AzureBlobConfig::default(),
            gcs_config: GcsConfig::default(),
        }
    }
}

/// Encryption configuration matching JavaScript structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptionConfig {
    pub algorithm: String,

    #[serde(rename = "enableContentEncryption")]
    pub enable_content_encryption: bool,

    #[serde(rename = "enableEmbeddingEncryption")]
    pub enable_embedding_encryption: bool,

    #[serde(rename = "enableMetadataEncryption")]
    pub enable_metadata_encryption: bool,

    #[serde(rename = "enableIdHashing")]
    pub enable_id_hashing: bool,

    #[serde(rename = "keyRotationDays")]
    pub key_rotation_days: u32,
}

impl Default for EncryptionConfig {
    fn default() -> Self {
        Self {
            algorithm: "AES-256-GCM".to_string(),
            enable_content_encryption: false,
            enable_embedding_encryption: false,
            enable_metadata_encryption: false,
            enable_id_hashing: false,
            key_rotation_days: 90,
        }
    }
}

/// S3 configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct S3Config {
    pub enabled: bool,
    pub bucket: String,
    pub region: String,
    #[serde(rename = "encryptionEnabled")]
    pub encryption_enabled: bool,
    #[serde(rename = "endpointUrl")]
    pub endpoint_url: Option<String>,
}

impl Default for S3Config {
    fn default() -> Self {
        Self {
            enabled: false,
            bucket: String::new(),
            region: "us-east-1".to_string(),
            encryption_enabled: true,
            endpoint_url: None,
        }
    }
}

/// Azure Blob configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AzureBlobConfig {
    pub enabled: bool,
    #[serde(rename = "containerName")]
    pub container_name: String,
    #[serde(rename = "encryptionEnabled")]
    pub encryption_enabled: bool,
}

impl Default for AzureBlobConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            container_name: String::new(),
            encryption_enabled: true,
        }
    }
}

/// Google Cloud Storage configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GcsConfig {
    pub enabled: bool,
    #[serde(rename = "bucketName")]
    pub bucket_name: String,
    #[serde(rename = "encryptionEnabled")]
    pub encryption_enabled: bool,
}

impl Default for GcsConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            bucket_name: String::new(),
            encryption_enabled: true,
        }
    }
}

/// IAM configuration for backwards compatibility
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IAMConfig {
    pub enable_iam_analysis: bool,
    pub supported_services: Vec<String>,
    pub risk_assessment: bool,
}

impl Default for IAMConfig {
    fn default() -> Self {
        Self {
            enable_iam_analysis: true,
            supported_services: vec![
                "ec2".to_string(),
                "rds".to_string(),
                "s3".to_string(),
                "lambda".to_string(),
            ],
            risk_assessment: true,
        }
    }
}

/// Privacy configuration for backwards compatibility
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrivacyConfig {
    pub level: String,
    pub enable_data_filtering: bool,
    pub confidential_fields: Vec<String>,
    pub non_confidential_fields: Vec<String>,
}

impl Default for PrivacyConfig {
    fn default() -> Self {
        Self {
            level: "minimal-aws".to_string(),
            enable_data_filtering: true,
            confidential_fields: vec![
                "resource_id".to_string(),
                "arn".to_string(),
                "vpc_id".to_string(),
                "security_groups".to_string(),
                "iam_roles".to_string(),
            ],
            non_confidential_fields: vec![
                "account_id".to_string(),
                "region".to_string(),
                "service".to_string(),
                "instance_type".to_string(),
                "environment".to_string(),
            ],
        }
    }
}

/// Configuration manager matching JavaScript version
#[derive(Clone)]
pub struct ConfigManager {
    base_path: PathBuf,
    config_path: PathBuf,
    default_config: Config,
    config: Config,
}

impl ConfigManager {
    /// Create a new configuration manager
    pub async fn new(base_path: &Path) -> Result<Self> {
        let base_path = base_path.to_path_buf();
        let config_path = base_path.join("config").join("config.yaml");
        let default_config = Config::default();

        let mut manager = Self {
            base_path,
            config_path,
            default_config: default_config.clone(),
            config: default_config,
        };

        manager.initialize().await?;
        Ok(manager)
    }

    /// Initialize configuration manager
    pub async fn initialize(&mut self) -> Result<bool> {
        // Ensure config directory exists
        if let Some(parent) = self.config_path.parent() {
            fs::create_dir_all(parent).await?;
        }

        self.load_config().await?;
        Ok(true)
    }

    /// Load configuration from file
    pub async fn load_config(&mut self) -> Result<()> {
        if self.config_path.exists() {
            let config_text = fs::read_to_string(&self.config_path).await?;

            // Try YAML first, then JSON
            if let Ok(file_config) = serde_yaml::from_str::<Config>(&config_text) {
                // Merge with default config
                self.config = self.merge_configs(&self.default_config, &file_config);
            } else if let Ok(file_config) = serde_json::from_str::<Config>(&config_text) {
                self.config = self.merge_configs(&self.default_config, &file_config);
            } else {
                eprintln!("Failed to load config, using defaults");
                self.config = self.default_config.clone();
                self.save_config().await?;
            }
        } else {
            self.config = self.default_config.clone();
            self.save_config().await?;
        }

        Ok(())
    }

    /// Save configuration to file
    pub async fn save_config(&self) -> Result<()> {
        let config_text = serde_yaml::to_string(&self.config)?;
        fs::write(&self.config_path, config_text).await?;
        Ok(())
    }

    /// Update configuration (partial update)
    pub async fn update_config(&mut self, updates: Config) -> Result<()> {
        self.config = self.merge_configs(&self.config, &updates);
        self.save_config().await?;
        Ok(())
    }

    /// Get current configuration
    pub fn get_config(&self) -> Config {
        self.config.clone()
    }

    /// Get specific config value by key (simplified version)
    pub fn get(&self, key: &str) -> Option<serde_yaml::Value> {
        let config_value = serde_yaml::to_value(&self.config).ok()?;
        if let serde_yaml::Value::Mapping(map) = config_value {
            map.get(&serde_yaml::Value::String(key.to_string())).cloned()
        } else {
            None
        }
    }

    /// Set specific config value by key (simplified version)
    pub async fn set(&mut self, key: &str, value: serde_yaml::Value) -> Result<()> {
        let mut config_value = serde_yaml::to_value(&self.config)?;

        if let serde_yaml::Value::Mapping(ref mut map) = config_value {
            map.insert(serde_yaml::Value::String(key.to_string()), value);
            self.config = serde_yaml::from_value(config_value)?;
            self.save_config().await?;
        }

        Ok(())
    }

    /// Get encryption configuration (returns types::EncryptionConfig for compatibility)
    pub fn get_encryption_config(&self) -> &crate::types::EncryptionConfig {
        &self.config.encryption
    }

    /// Get S3 configuration
    pub fn get_s3_config(&self) -> &S3Config {
        &self.config.s3_config
    }

    /// Get Azure Blob configuration
    pub fn get_azure_blob_config(&self) -> &AzureBlobConfig {
        &self.config.azure_blob_config
    }

    /// Get GCS configuration
    pub fn get_gcs_config(&self) -> &GcsConfig {
        &self.config.gcs_config
    }

    /// Merge configurations (second config overrides first)
    fn merge_configs(&self, base: &Config, updates: &Config) -> Config {
        // For simplicity, just clone the updates
        // In a more sophisticated implementation, you could do field-by-field merging
        updates.clone()
    }
}

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

    #[tokio::test]
    async fn test_config_manager_creation() {
        let temp_dir = TempDir::new().unwrap();
        let config_manager = ConfigManager::new(temp_dir.path()).await.unwrap();

        let config = config_manager.get_config();
        assert_eq!(config.embedding_model, "BAAI/bge-m3");
        assert_eq!(config.embedding_dimensions, 1024);
        assert_eq!(config.privacy_level, "minimal-aws");
    }

    #[tokio::test]
    async fn test_config_save_load() {
        let temp_dir = TempDir::new().unwrap();
        let mut config_manager = ConfigManager::new(temp_dir.path()).await.unwrap();

        let mut new_config = Config::default();
        new_config.embedding_model = "test-model".to_string();
        new_config.chunk_size = 2048;

        config_manager.update_config(new_config).await.unwrap();

        // Create new manager to test loading
        let new_config_manager = ConfigManager::new(temp_dir.path()).await.unwrap();
        let config = new_config_manager.get_config();
        assert_eq!(config.embedding_model, "test-model");
        assert_eq!(config.chunk_size, 2048);
    }

    #[tokio::test]
    async fn test_config_get_set() {
        let temp_dir = TempDir::new().unwrap();
        let mut config_manager = ConfigManager::new(temp_dir.path()).await.unwrap();

        // Test get
        let chunk_size = config_manager.get("chunkSize");
        assert!(chunk_size.is_some());

        // Test set
        let new_value = serde_yaml::Value::Number(serde_yaml::Number::from(2048));
        config_manager.set("chunkSize", new_value).await.unwrap();

        let config = config_manager.get_config();
        assert_eq!(config.chunk_size, 2048);
    }

    #[tokio::test]
    async fn test_encryption_config() {
        let temp_dir = TempDir::new().unwrap();
        let config_manager = ConfigManager::new(temp_dir.path()).await.unwrap();

        let encryption_config = config_manager.get_encryption_config();
        assert_eq!(encryption_config.algorithm, "AES-256-GCM");
        assert_eq!(encryption_config.enable_content_encryption, true);
        assert_eq!(encryption_config.enable_metadata_encryption, true);
        assert_eq!(encryption_config.key_rotation_days, Some(90));
    }

    #[tokio::test]
    async fn test_cloud_configs() {
        let temp_dir = TempDir::new().unwrap();
        let config_manager = ConfigManager::new(temp_dir.path()).await.unwrap();

        let s3_config = config_manager.get_s3_config();
        assert_eq!(s3_config.enabled, false);
        assert_eq!(s3_config.region, "us-east-1");
        assert_eq!(s3_config.encryption_enabled, true);

        let azure_config = config_manager.get_azure_blob_config();
        assert_eq!(azure_config.enabled, false);
        assert_eq!(azure_config.encryption_enabled, true);

        let gcs_config = config_manager.get_gcs_config();
        assert_eq!(gcs_config.enabled, false);
        assert_eq!(gcs_config.encryption_enabled, true);
    }
}