ferro-hgvs 0.4.0

HGVS variant normalizer - part of the ferro bioinformatics 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
//! Configuration for the HGVS web service

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// Main service configuration
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ServiceConfig {
    /// Server configuration
    pub server: ServerConfig,
    /// Tool configurations
    pub tools: ToolConfigs,
    /// Data source configurations
    #[serde(default)]
    pub data: DataConfig,
}

/// Data source configuration for advanced features
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct DataConfig {
    /// Path to cdot transcript JSON file (for coordinate conversion)
    pub cdot_path: Option<PathBuf>,
    /// Liftover chain file configuration
    pub liftover: Option<LiftoverConfig>,
}

/// Liftover chain file configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct LiftoverConfig {
    /// Path to hg19ToHg38.over.chain.gz (GRCh37 to GRCh38)
    pub grch37_to_38: PathBuf,
    /// Path to hg38ToHg19.over.chain.gz (GRCh38 to GRCh37)
    pub grch38_to_37: PathBuf,
}

/// Server configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct ServerConfig {
    /// Host to bind to (default: "0.0.0.0")
    pub host: String,
    /// Port to listen on (default: 3000)
    pub port: u16,
    /// Maximum request size (default: "10MB")
    pub max_request_size: String,
    /// Request timeout in seconds (default: 60)
    pub request_timeout_seconds: u64,
    /// Enable CORS (default: true)
    pub enable_cors: bool,
    /// Enable request tracing (default: true)
    pub enable_tracing: bool,
    /// Maximum concurrent batch processing tasks (default: 10)
    pub max_concurrent_batches: Option<usize>,
    /// Maximum variants per batch request (default: 1000)
    pub max_batch_size: Option<usize>,
}

/// Configuration for all tools
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ToolConfigs {
    /// Ferro tool configuration
    pub ferro: Option<FerroConfig>,
    /// Mutalyzer tool configuration
    pub mutalyzer: Option<MutalyzerConfig>,
    /// Biocommons tool configuration
    pub biocommons: Option<BiocommonsConfig>,
    /// HGVS-RS tool configuration
    pub hgvs_rs: Option<HgvsRsConfig>,
}

/// Ferro tool configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FerroConfig {
    /// Whether tool is enabled
    pub enabled: bool,
    /// Path to ferro reference data directory
    pub reference_dir: PathBuf,
    /// Number of parallel workers (default: number of CPU cores)
    pub parallel_workers: Option<usize>,
    /// Shuffle direction (3prime or 5prime, default: 3prime)
    pub shuffle_direction: Option<String>,
    /// Error handling mode (strict, lenient, silent, default: lenient)
    pub error_mode: Option<String>,
}

/// Mutalyzer operation mode
#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum MutalyzerMode {
    /// HTTP API mode (calls mutalyzer.nl or local mutalyzer server)
    #[default]
    Api,
    /// Local subprocess mode (uses Python mutalyzer package directly)
    Local,
}

/// Mutalyzer tool configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct MutalyzerConfig {
    /// Whether tool is enabled
    pub enabled: bool,
    /// Operation mode: "api" for HTTP API, "local" for Python subprocess
    #[serde(default)]
    pub mode: MutalyzerMode,
    /// Mutalyzer API URL (used in API mode)
    pub api_url: String,
    /// Request timeout in seconds (default: 30)
    pub timeout_seconds: u32,
    /// Rate limiting delay in milliseconds (default: 50, used in API mode)
    pub rate_limit_ms: Option<u64>,
    /// Health check interval in seconds (default: 60)
    pub health_check_interval: Option<u64>,
    /// Connection pool configuration (used in API mode)
    pub connection_pool: Option<ConnectionPoolConfig>,
    /// Circuit breaker configuration (used in API mode)
    pub circuit_breaker: Option<CircuitBreakerConfig>,
    /// Path to mutalyzer settings file (used in local mode)
    pub settings_file: Option<PathBuf>,
    /// Allow network access in local mode (default: false for offline/cache-only)
    #[serde(default)]
    pub allow_network: bool,
}

/// HTTP connection pool configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ConnectionPoolConfig {
    /// Maximum number of connections in pool (default: 10)
    pub max_connections: Option<usize>,
    /// Connection idle timeout in seconds (default: 30)
    pub idle_timeout_seconds: Option<u64>,
    /// Keep-alive timeout in seconds (default: 90)
    pub keep_alive_seconds: Option<u64>,
    /// Enable HTTP/2 (default: true)
    pub enable_http2: Option<bool>,
}

/// Circuit breaker configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CircuitBreakerConfig {
    /// Failure threshold before opening circuit (default: 5)
    pub failure_threshold: Option<u32>,
    /// Recovery timeout in seconds (default: 60)
    pub recovery_timeout_seconds: Option<u64>,
    /// Success threshold for closing circuit (default: 3)
    pub success_threshold: Option<u32>,
}

/// Default UTA schema name
fn default_uta_schema() -> String {
    "uta_20210129b".to_string()
}

/// Biocommons tool configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BiocommonsConfig {
    /// Whether tool is enabled
    pub enabled: bool,
    /// UTA database URL
    pub uta_url: String,
    /// UTA database schema (default: "uta_20210129b")
    #[serde(default = "default_uta_schema")]
    pub uta_schema: String,
    /// SeqRepo directory path
    pub seqrepo_path: PathBuf,
    /// Docker container name for UTA (default: "ferro-uta")
    pub docker_container: Option<String>,
    /// Number of parallel workers (default: 1)
    pub parallel_workers: Option<usize>,
    /// Environment variables to pass to subprocess
    pub env_vars: Option<HashMap<String, String>>,
}

/// HGVS-RS tool configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct HgvsRsConfig {
    /// Whether tool is enabled
    pub enabled: bool,
    /// UTA database URL
    pub uta_url: String,
    /// UTA database schema (default: "uta_20210129b")
    pub uta_schema: String,
    /// SeqRepo directory path
    pub seqrepo_path: PathBuf,
    /// LRG mapping file path (optional)
    pub lrg_mapping_file: Option<PathBuf>,
    /// Number of parallel workers (default: number of CPU cores)
    pub parallel_workers: Option<usize>,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            host: "0.0.0.0".to_string(),
            port: 3000,
            max_request_size: "10MB".to_string(),
            request_timeout_seconds: 60,
            enable_cors: true,
            enable_tracing: true,
            max_concurrent_batches: Some(10),
            max_batch_size: Some(1000),
        }
    }
}

impl Default for ToolConfigs {
    fn default() -> Self {
        Self {
            ferro: Some(FerroConfig::default()),
            mutalyzer: Some(MutalyzerConfig::default()),
            biocommons: None, // Disabled by default (requires setup)
            hgvs_rs: None,    // Disabled by default (requires setup)
        }
    }
}

impl Default for FerroConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            reference_dir: PathBuf::from("./reference"),
            parallel_workers: None,
            shuffle_direction: Some("3prime".to_string()),
            error_mode: Some("lenient".to_string()),
        }
    }
}

impl Default for MutalyzerConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            mode: MutalyzerMode::default(),
            api_url: "http://localhost:8082".to_string(),
            timeout_seconds: 30,
            rate_limit_ms: Some(50),
            health_check_interval: Some(60),
            connection_pool: Some(ConnectionPoolConfig::default()),
            circuit_breaker: Some(CircuitBreakerConfig::default()),
            settings_file: None,
            allow_network: false,
        }
    }
}

impl Default for ConnectionPoolConfig {
    fn default() -> Self {
        Self {
            max_connections: Some(10),
            idle_timeout_seconds: Some(30),
            keep_alive_seconds: Some(90),
            enable_http2: Some(true),
        }
    }
}

impl Default for CircuitBreakerConfig {
    fn default() -> Self {
        Self {
            failure_threshold: Some(5),
            recovery_timeout_seconds: Some(60),
            success_threshold: Some(3),
        }
    }
}

impl ServiceConfig {
    /// Load configuration from TOML file
    pub fn from_file(path: &std::path::Path) -> Result<Self, Box<dyn std::error::Error>> {
        let content = std::fs::read_to_string(path)?;
        let config: ServiceConfig = toml::from_str(&content)?;
        Ok(config)
    }

    /// Save configuration to TOML file
    pub fn to_file(&self, path: &std::path::Path) -> Result<(), Box<dyn std::error::Error>> {
        let content = toml::to_string_pretty(self)?;
        std::fs::write(path, content)?;
        Ok(())
    }

    /// Get list of enabled tools
    pub fn enabled_tools(&self) -> Vec<String> {
        let mut tools = Vec::new();

        if let Some(ferro) = &self.tools.ferro {
            if ferro.enabled {
                tools.push("ferro".to_string());
            }
        }

        if let Some(mutalyzer) = &self.tools.mutalyzer {
            if mutalyzer.enabled {
                tools.push("mutalyzer".to_string());
            }
        }

        if let Some(biocommons) = &self.tools.biocommons {
            if biocommons.enabled {
                tools.push("biocommons".to_string());
            }
        }

        if let Some(hgvs_rs) = &self.tools.hgvs_rs {
            if hgvs_rs.enabled {
                tools.push("hgvs-rs".to_string());
            }
        }

        tools
    }

    /// Check if a tool is enabled
    pub fn is_tool_enabled(&self, tool: &str) -> bool {
        match tool {
            "ferro" => self.tools.ferro.as_ref().is_some_and(|c| c.enabled),
            "mutalyzer" => self.tools.mutalyzer.as_ref().is_some_and(|c| c.enabled),
            "biocommons" => self.tools.biocommons.as_ref().is_some_and(|c| c.enabled),
            "hgvs-rs" => self.tools.hgvs_rs.as_ref().is_some_and(|c| c.enabled),
            _ => false,
        }
    }

    /// Validate configuration
    pub fn validate(&self) -> Result<(), String> {
        // Validate server config
        if self.server.port == 0 {
            return Err("Server port must be greater than 0".to_string());
        }

        // Validate at least one tool is enabled
        if self.enabled_tools().is_empty() {
            return Err("At least one tool must be enabled".to_string());
        }

        // Validate ferro config
        if let Some(ferro) = &self.tools.ferro {
            if ferro.enabled && !ferro.reference_dir.exists() {
                return Err(format!(
                    "Ferro reference directory does not exist: {}",
                    ferro.reference_dir.display()
                ));
            }
        }

        // Validate biocommons config
        if let Some(biocommons) = &self.tools.biocommons {
            if biocommons.enabled && !biocommons.seqrepo_path.exists() {
                return Err(format!(
                    "Biocommons seqrepo directory does not exist: {}",
                    biocommons.seqrepo_path.display()
                ));
            }
        }

        // Validate hgvs-rs config
        if let Some(hgvs_rs) = &self.tools.hgvs_rs {
            if hgvs_rs.enabled && !hgvs_rs.seqrepo_path.exists() {
                return Err(format!(
                    "HGVS-RS seqrepo directory does not exist: {}",
                    hgvs_rs.seqrepo_path.display()
                ));
            }
        }

        Ok(())
    }
}

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

    #[test]
    fn test_default_config() {
        let config = ServiceConfig::default();
        assert_eq!(config.server.host, "0.0.0.0");
        assert_eq!(config.server.port, 3000);
        assert!(!config.enabled_tools().is_empty());
    }

    #[test]
    fn test_enabled_tools() {
        let mut config = ServiceConfig::default();

        // Disable all tools
        config.tools.ferro = Some(FerroConfig {
            enabled: false,
            ..FerroConfig::default()
        });
        config.tools.mutalyzer = Some(MutalyzerConfig {
            enabled: false,
            ..MutalyzerConfig::default()
        });
        config.tools.biocommons = None;
        config.tools.hgvs_rs = None;

        assert!(config.enabled_tools().is_empty());

        // Enable ferro
        config.tools.ferro = Some(FerroConfig {
            enabled: true,
            ..FerroConfig::default()
        });
        assert_eq!(config.enabled_tools(), vec!["ferro"]);
    }
}