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
//! Ferro tool service implementation
use std::sync::Arc;
use crate::benchmark::types::ParseResult;
use crate::error_handling::{ErrorConfig, ErrorMode};
use crate::normalize::{NormalizeConfig, Normalizer, ShuffleDirection};
use crate::reference::MultiFastaProvider;
use crate::service::{
config::FerroConfig,
tools::HgvsToolService,
types::{extract_variant_details, health_check::HealthCheckResult, ServiceError, ToolName},
};
/// Ferro tool service
pub struct FerroService {
/// Normalizer instance with reference provider
normalizer: Arc<Normalizer<MultiFastaProvider>>,
/// Configuration
#[allow(dead_code)]
config: FerroConfig,
}
impl FerroService {
/// Create a new FerroService
pub fn new(config: &FerroConfig) -> Result<Self, ServiceError> {
// Load reference provider - prefer manifest if available (includes cdot CDS info)
let manifest_path = std::path::Path::new(&config.reference_dir).join("manifest.json");
let provider = if manifest_path.exists() {
MultiFastaProvider::from_manifest(&manifest_path).map_err(|e| {
ServiceError::ConfigError(format!(
"Failed to load ferro reference from manifest: {}",
e
))
})?
} else {
MultiFastaProvider::from_directory(&config.reference_dir).map_err(|e| {
ServiceError::ConfigError(format!("Failed to load ferro reference data: {}", e))
})?
};
// Create normalization config.
//
// The service used to read a `shuffle_direction` key here. It is gone:
// `README.md` rule 6 says there are no user options for normalization
// form, and a direction is not orthogonal to the form. The service
// normalizes 3', the only direction the HGVS recommendations describe.
// `FerroConfig` is `deny_unknown_fields` so a stale
// `shuffle_direction = "5prime"` in an operator's TOML fails the load
// rather than being ignored.
let shuffle_direction = ShuffleDirection::ThreePrime;
let error_mode = match config.error_mode.as_deref() {
Some("strict") => ErrorMode::Strict,
Some("lenient") | None => ErrorMode::Lenient,
Some("silent") => ErrorMode::Silent,
Some(other) => {
return Err(ServiceError::ConfigError(format!(
"Invalid error_mode '{}', must be 'strict', 'lenient', or 'silent'",
other
)));
}
};
let normalize_config = NormalizeConfig {
shuffle_direction,
cross_boundaries: false, // Keep default
error_config: ErrorConfig::new(error_mode),
window_size: 100, // Keep default
prevent_overlap: false, // Keep default
};
// Create normalizer
let normalizer = Arc::new(Normalizer::with_config(provider, normalize_config));
Ok(Self {
normalizer,
config: config.clone(),
})
}
/// Parse HGVS using ferro parser
async fn parse_hgvs(&self, hgvs: &str) -> Result<ParseResult, ServiceError> {
// Use ferro's parse functionality
// We'll run this in a blocking task since ferro is sync
let hgvs = hgvs.to_string();
tokio::task::spawn_blocking(move || {
// Parse the HGVS string
match crate::hgvs::parser::parse_hgvs_lenient(&hgvs) {
Ok(parse_result) => {
let success = true;
let output = Some(parse_result.result.to_string());
let error = if parse_result.warnings.is_empty() {
None
} else {
Some(format!("Warnings: {}", parse_result.warnings.len()))
};
// Extract parsed details
let details = extract_variant_details(&parse_result.result);
ParseResult {
input: hgvs,
success,
output,
error,
error_category: None,
ref_mismatch: None,
details,
}
}
Err(e) => ParseResult {
input: hgvs,
success: false,
output: None,
error: Some(e.to_string()),
error_category: None,
ref_mismatch: None,
details: None,
},
}
})
.await
.map_err(|e| ServiceError::InternalError(format!("Task join error: {}", e)))
}
/// Normalize HGVS using ferro normalizer
async fn normalize_hgvs(&self, hgvs: &str) -> Result<ParseResult, ServiceError> {
let hgvs = hgvs.to_string();
let normalizer = self.normalizer.clone();
tokio::task::spawn_blocking(move || {
// First parse the HGVS string
match crate::hgvs::parser::parse_hgvs_lenient(&hgvs) {
Ok(parse_result) => {
let original_str = parse_result.result.to_string();
// Then normalize it
match normalizer.normalize_with_diagnostics(&parse_result.result) {
Ok(normalize_result) => {
let success = true;
let normalized_str = normalize_result.result.to_string();
let output = Some(normalized_str.clone());
let error = if normalize_result.warnings.is_empty() {
None
} else {
Some(format!("Warnings: {}", normalize_result.warnings.len()))
};
// Extract details from normalized variant and detect shifting
let mut details = extract_variant_details(&normalize_result.result);
if let Some(ref mut d) = details {
// Detect if the variant was shifted
let was_shifted = normalized_str != original_str;
d.was_shifted = Some(was_shifted);
if was_shifted {
// Extract original position for display
if let Some(orig_details) =
extract_variant_details(&parse_result.result)
{
d.original_position = Some(orig_details.position.display);
}
}
}
ParseResult {
input: hgvs,
success,
output,
error,
error_category: None,
ref_mismatch: None,
details,
}
}
Err(e) => ParseResult {
input: hgvs,
success: false,
output: None,
error: Some(e.to_string()),
error_category: None,
ref_mismatch: None,
details: None,
},
}
}
Err(e) => ParseResult {
input: hgvs,
success: false,
output: None,
error: Some(e.to_string()),
error_category: None,
ref_mismatch: None,
details: None,
},
}
})
.await
.map_err(|e| ServiceError::InternalError(format!("Task join error: {}", e)))
}
}
#[async_trait::async_trait]
impl HgvsToolService for FerroService {
async fn parse(&self, hgvs: &str) -> Result<ParseResult, ServiceError> {
self.parse_hgvs(hgvs).await
}
async fn normalize(&self, hgvs: &str) -> Result<ParseResult, ServiceError> {
self.normalize_hgvs(hgvs).await
}
async fn health_check(&self) -> HealthCheckResult {
// Simple health check - try to parse a basic HGVS variant
// This tests that the ferro parser and normalizer are functioning
let result = tokio::task::spawn_blocking(move || {
// Try parsing a simple variant to verify ferro is working
crate::hgvs::parser::parse_hgvs("NM_000001.2:c.1A>G")
})
.await;
match result {
Ok(Ok(_)) => HealthCheckResult::Healthy,
Ok(Err(e)) => {
// Parse errors are expected if the variant is unknown, but parser is working
let error_msg = e.to_string();
if error_msg.contains("transcript") || error_msg.contains("not found") {
HealthCheckResult::Degraded {
reason: "Parser working but reference data may be incomplete".to_string(),
}
} else {
HealthCheckResult::Unhealthy {
reason: format!("Parser health check failed: {}", e),
}
}
}
Err(e) => HealthCheckResult::Unhealthy {
reason: format!("Health check task error: {}", e),
},
}
}
fn tool_name(&self) -> ToolName {
ToolName::Ferro
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
fn create_test_config() -> Result<(FerroConfig, TempDir), Box<dyn std::error::Error>> {
let temp_dir = TempDir::new()?;
// Create a minimal reference structure
fs::create_dir_all(temp_dir.path().join("transcripts"))?;
fs::write(
temp_dir.path().join("manifest.json"),
r#"{"version": "test", "files": []}"#,
)?;
let config = FerroConfig {
enabled: true,
reference_dir: temp_dir.path().to_path_buf(),
parallel_workers: Some(1),
error_mode: Some("lenient".to_string()),
};
Ok((config, temp_dir))
}
#[tokio::test]
async fn test_ferro_service_creation() {
let (config, _temp_dir) = create_test_config().expect("Failed to create test config");
// This might fail if reference data is not available, but the service should be creatable
let result = FerroService::new(&config);
// We expect this to fail in test environment without proper reference data
// but the error should be a config error, not a panic
if let Err(e) = result {
assert!(matches!(e, ServiceError::ConfigError(_)));
}
}
// Per-arm coverage of the shared `extract_variant_details` helper (including
// the RNA/Mt/Circular arms and the `Allele -> None` path) lives alongside the
// function in `crate::service::types`. The service exercises it end-to-end via
// `parse`/`normalize`, which populate `ParseResult::details`.
/// A malformed enumerated config value must be refused, not defaulted.
///
/// This used to key on `shuffle_direction: Some("invalid")`. That key was
/// removed with the rest of the public 5' surface, so the test now keys on
/// `error_mode`, which is the remaining enumerated string on `FerroConfig`
/// and has the identical reject-don't-guess contract.
#[test]
fn test_invalid_config() {
let config = FerroConfig {
enabled: true,
reference_dir: std::path::PathBuf::from("/nonexistent/path"),
parallel_workers: Some(1),
error_mode: Some("invalid".to_string()),
};
let result = FerroService::new(&config);
assert!(result.is_err());
}
/// A stale `shuffle_direction` key must fail the config load loudly.
///
/// The dangerous removal shape is the silent one: serde ignores unknown
/// fields by default, so an operator's `shuffle_direction = "5prime"` would
/// vanish and the service would 3'-shift while the file still asked for 5'.
/// `deny_unknown_fields` on `FerroConfig` turns that into a load error.
#[test]
fn a_removed_shuffle_direction_key_is_rejected_not_ignored() {
let toml = r#"
enabled = true
reference_dir = "/tmp/ferro-ref"
shuffle_direction = "5prime"
"#;
let err = toml::from_str::<FerroConfig>(toml)
.expect_err("a removed key must not be silently ignored");
assert!(
err.to_string().contains("shuffle_direction"),
"the error must name the offending key, got: {err}"
);
}
}