rtemis-a3 0.2.0

Rust implementation of the A3 (Amino Acid Annotation) format — parse, validate, and inspect A3 JSON files
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! Diagnostic mode — full step-by-step A3 validation.
//!
//! Implements the 6-step plan from `specs/diagnostic.md`:
//!
//! 1. Valid JSON                                              \[fatal\]
//! 2. Envelope: `$schema` and `a3_version`
//! 3. Top-level field presence, types, no unknown keys       \[fatal per field\]
//! 4. Sequence value
//! 5. Annotation families: site, region, ptm, processing, variant
//! 6. Metadata fields
//!
//! Every non-fatal error is accumulated before returning, so the caller sees
//! all violations at once. Fatal errors halt only the steps that depend on
//! their output — unrelated checks still run.

use rtemis_a3::normalization::{normalize_positions, normalize_ranges, normalize_sequence};
use rtemis_a3::{A3, A3_SCHEMA_URI, A3_VERSION, a3_from_json};
use serde_json::{Map, Value};

const TOP_LEVEL_KEYS: &[&str] = &[
    "$schema",
    "a3_version",
    "sequence",
    "annotations",
    "metadata",
];
const ANN_FAMILIES: &[&str] = &["site", "region", "ptm", "processing", "variant"];
const METADATA_KEYS: &[&str] = &["uniprot_id", "description", "reference", "organism"];

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Typed diagnostic failure — distinguishes a fatal parse error (exit 2)
/// from A3 validation errors (exit 1).
pub enum DiagnoseError {
    /// Step 1 failed: the input is not valid JSON or not a JSON object.
    /// Callers should exit with code 2 (system/parse error).
    Fatal(Vec<String>),
    /// One or more A3 validation errors. Callers should exit with code 1.
    Invalid(Vec<String>),
}

/// Full diagnostic validation of an A3 JSON string.
///
/// Follows the 6-step plan in `specs/diagnostic.md`. Returns `Ok(A3)` when
/// every check passes, or `Err(DiagnoseError)` with every violation collected.
/// `DiagnoseError::Fatal` signals a JSON parse failure (exit 2);
/// `DiagnoseError::Invalid` signals A3 validation errors (exit 1).
///
/// On success the standard `a3_from_json` path is used to construct the `A3`,
/// so the returned value is identical to what the fast path would produce.
pub fn a3_diagnose(text: &str) -> Result<A3, DiagnoseError> {
    let mut errors: Vec<String> = Vec::new();

    // -----------------------------------------------------------------------
    // Step 1: Valid JSON  [fatal]
    // -----------------------------------------------------------------------

    let value: Value = match serde_json::from_str(text) {
        Ok(v) => v,
        Err(e) => return Err(DiagnoseError::Fatal(vec![format!("Invalid JSON: {e}")])),
    };

    let obj = match value.as_object() {
        Some(o) => o,
        None => {
            return Err(DiagnoseError::Fatal(vec![
                "Expected a JSON object at the top level".to_string(),
            ]));
        }
    };

    // -----------------------------------------------------------------------
    // Step 2: Envelope
    // -----------------------------------------------------------------------

    check_envelope(obj, &mut errors);

    // -----------------------------------------------------------------------
    // Step 3: Top-level field presence, types, unknown keys
    //
    // Each extraction returns `None` when the field is absent or has the wrong
    // type — that `None` propagates to disable the steps that depend on it.
    // -----------------------------------------------------------------------

    let seq_raw = require_string_field(obj, "sequence", &mut errors);

    // `annotations` and `metadata` are required even when empty (`{}`).
    let ann_obj = required_object_field(obj, "annotations", &mut errors);
    let meta_obj = required_object_field(obj, "metadata", &mut errors);

    for key in obj.keys() {
        if !TOP_LEVEL_KEYS.contains(&key.as_str()) {
            errors.push(format!("unknown top-level key '{key}'"));
        }
    }

    // -----------------------------------------------------------------------
    // Step 4: Sequence value
    //
    // Normalize the raw string (uppercase, character set, min length).
    // `seq_len` is `Some` only when this step fully passes — Step 5 needs it
    // for bounds checking.
    // -----------------------------------------------------------------------

    let seq_len: Option<u32> = seq_raw.and_then(|s| match normalize_sequence(s) {
        Ok(normalized) => Some(normalized.len() as u32),
        Err(e) => {
            errors.push(e);
            None
        }
    });

    // -----------------------------------------------------------------------
    // Step 5: Annotation families
    // -----------------------------------------------------------------------

    if let Some(ann) = ann_obj {
        check_annotations(ann, seq_len, &mut errors);
    }

    // -----------------------------------------------------------------------
    // Step 6: Metadata fields
    // -----------------------------------------------------------------------

    if let Some(meta) = meta_obj {
        check_metadata(meta, &mut errors);
    }

    // -----------------------------------------------------------------------
    // Return
    // -----------------------------------------------------------------------

    if errors.is_empty() {
        // All diagnostic checks passed — use the standard fast path to build
        // a validated A3. This should never fail: if it does, the diagnostic
        // checks have a gap that needs fixing.
        Ok(a3_from_json(text).expect("diagnostic passed but standard parse failed"))
    } else {
        Err(DiagnoseError::Invalid(errors))
    }
}

// ---------------------------------------------------------------------------
// Step implementations
// ---------------------------------------------------------------------------

fn check_envelope(obj: &Map<String, Value>, errors: &mut Vec<String>) {
    match obj.get("$schema") {
        None => errors.push(format!("'$schema' is required; must be '{A3_SCHEMA_URI}'")),
        Some(v) => match v.as_str() {
            None => errors.push(format!(
                "'$schema' must be a string; expected '{A3_SCHEMA_URI}'"
            )),
            Some(s) if s != A3_SCHEMA_URI => {
                errors.push(format!("'$schema' must be '{A3_SCHEMA_URI}', got '{s}'"))
            }
            _ => {}
        },
    }

    match obj.get("a3_version") {
        None => errors.push(format!("'a3_version' is required; must be '{A3_VERSION}'")),
        Some(v) => match v.as_str() {
            None => errors.push(format!(
                "'a3_version' must be a string; expected '{A3_VERSION}'"
            )),
            Some(s) if s != A3_VERSION => {
                errors.push(format!("'a3_version' must be '{A3_VERSION}', got '{s}'"))
            }
            _ => {}
        },
    }
}

fn check_annotations(ann: &Map<String, Value>, seq_len: Option<u32>, errors: &mut Vec<String>) {
    for key in ann.keys() {
        if !ANN_FAMILIES.contains(&key.as_str()) {
            errors.push(format!("annotations: unknown family '{key}'"));
        }
    }

    if let Some(v) = ann.get("site") {
        match v.as_object() {
            Some(o) => check_site_entries(o, seq_len, errors),
            None => errors.push("'annotations.site' must be an object".to_string()),
        }
    }

    if let Some(v) = ann.get("region") {
        match v.as_object() {
            Some(o) => check_region_entries(o, seq_len, errors),
            None => errors.push("'annotations.region' must be an object".to_string()),
        }
    }

    if let Some(v) = ann.get("ptm") {
        match v.as_object() {
            Some(o) => check_flex_entries(o, "ptm", seq_len, errors),
            None => errors.push("'annotations.ptm' must be an object".to_string()),
        }
    }

    if let Some(v) = ann.get("processing") {
        match v.as_object() {
            Some(o) => check_flex_entries(o, "processing", seq_len, errors),
            None => errors.push("'annotations.processing' must be an object".to_string()),
        }
    }

    if let Some(v) = ann.get("variant") {
        match v.as_array() {
            Some(a) => check_variant_entries(a, seq_len, errors),
            None => errors.push("'annotations.variant' must be an array".to_string()),
        }
    }
}

fn check_site_entries(
    entries: &Map<String, Value>,
    seq_len: Option<u32>,
    errors: &mut Vec<String>,
) {
    for (name, val) in entries {
        if name.is_empty() {
            errors.push("annotations.site: annotation name must not be empty".to_string());
            continue;
        }
        let field = format!("annotations.site.{name}");

        let Some(entry) = require_object(val, &field, errors) else {
            continue;
        };
        let Some(index_val) = require_field(entry, "index", &field, errors) else {
            continue;
        };
        let Some(arr) = require_array(index_val, &format!("{field}.index"), errors) else {
            continue;
        };
        let Some(positions) = parse_positions(arr, &format!("{field}.index"), errors) else {
            continue;
        };

        match normalize_positions(positions, &field) {
            Err(e) => errors.push(e),
            Ok(positions) => check_position_bounds(&positions, seq_len, &field, errors),
        }

        check_kind_field(entry, &field, errors);
    }
}

fn check_region_entries(
    entries: &Map<String, Value>,
    seq_len: Option<u32>,
    errors: &mut Vec<String>,
) {
    for (name, val) in entries {
        if name.is_empty() {
            errors.push("annotations.region: annotation name must not be empty".to_string());
            continue;
        }
        let field = format!("annotations.region.{name}");

        let Some(entry) = require_object(val, &field, errors) else {
            continue;
        };
        let Some(index_val) = require_field(entry, "index", &field, errors) else {
            continue;
        };
        let Some(arr) = require_array(index_val, &format!("{field}.index"), errors) else {
            continue;
        };
        let Some(ranges) = parse_ranges(arr, &format!("{field}.index"), errors) else {
            continue;
        };

        match normalize_ranges(ranges, &field) {
            Err(e) => errors.push(e),
            Ok(ranges) => check_range_bounds(&ranges, seq_len, &field, errors),
        }

        check_kind_field(entry, &field, errors);
    }
}

fn check_flex_entries(
    entries: &Map<String, Value>,
    family: &str,
    seq_len: Option<u32>,
    errors: &mut Vec<String>,
) {
    for (name, val) in entries {
        if name.is_empty() {
            errors.push(format!(
                "annotations.{family}: annotation name must not be empty"
            ));
            continue;
        }
        let field = format!("annotations.{family}.{name}");

        let Some(entry) = require_object(val, &field, errors) else {
            continue;
        };
        let Some(index_val) = require_field(entry, "index", &field, errors) else {
            continue;
        };
        let Some(arr) = require_array(index_val, &format!("{field}.index"), errors) else {
            continue;
        };

        // Detect positions vs ranges by the type of the first element.
        // Empty arrays are valid for either — treat as positions (no-op).
        let is_ranges = arr.first().map(|v| v.is_array()).unwrap_or(false);

        if is_ranges {
            let Some(ranges) = parse_ranges(arr, &format!("{field}.index"), errors) else {
                continue;
            };
            match normalize_ranges(ranges, &field) {
                Err(e) => errors.push(e),
                Ok(ranges) => check_range_bounds(&ranges, seq_len, &field, errors),
            }
        } else {
            let Some(positions) = parse_positions(arr, &format!("{field}.index"), errors) else {
                continue;
            };
            match normalize_positions(positions, &field) {
                Err(e) => errors.push(e),
                Ok(positions) => check_position_bounds(&positions, seq_len, &field, errors),
            }
        }

        check_kind_field(entry, &field, errors);
    }
}

fn check_variant_entries(entries: &[Value], seq_len: Option<u32>, errors: &mut Vec<String>) {
    for (i, val) in entries.iter().enumerate() {
        let field = format!("annotations.variant[{i}]");

        let Some(entry) = require_object(val, &field, errors) else {
            continue;
        };

        match entry.get("position") {
            None => errors.push(format!("{field}: missing required field 'position'")),
            Some(v) => match v.as_u64().and_then(|n| u32::try_from(n).ok()) {
                None => errors.push(format!("{field}.position: must be a positive integer")),
                Some(0) => errors.push(format!("{field}.position: must be ≥ 1 (1-based); got 0")),
                Some(pos) => {
                    if let Some(len) = seq_len
                        && pos > len
                    {
                        errors.push(format!(
                            "{field}.position: {pos} is out of bounds \
                             for sequence of length {len} (must be 1–{len})"
                        ));
                    }
                }
            },
        }
    }
}

fn check_metadata(meta: &Map<String, Value>, errors: &mut Vec<String>) {
    for key in meta.keys() {
        if !METADATA_KEYS.contains(&key.as_str()) {
            errors.push(format!("metadata: unknown field '{key}'"));
        }
    }
    for &key in METADATA_KEYS {
        if let Some(v) = meta.get(key)
            && !v.is_string()
        {
            errors.push(format!("metadata.{key}: must be a string"));
        }
    }
}

// ---------------------------------------------------------------------------
// Bounds helpers
// ---------------------------------------------------------------------------

fn check_position_bounds(
    positions: &[u32],
    seq_len: Option<u32>,
    field: &str,
    errors: &mut Vec<String>,
) {
    let Some(len) = seq_len else { return };
    for &pos in positions {
        if pos > len {
            errors.push(format!(
                "{field}.index: position {pos} is out of bounds \
                 for sequence of length {len} (must be 1–{len})"
            ));
        }
    }
}

fn check_range_bounds(
    ranges: &[[u32; 2]],
    seq_len: Option<u32>,
    field: &str,
    errors: &mut Vec<String>,
) {
    let Some(len) = seq_len else { return };
    for [_start, end] in ranges {
        if *end > len {
            errors.push(format!(
                "{field}.index: range endpoint {end} is out of bounds \
                 for sequence of length {len} (must be 1–{len})"
            ));
        }
    }
}

// ---------------------------------------------------------------------------
// Field extraction helpers
// ---------------------------------------------------------------------------

/// Require a string field in `obj`. Pushes an error and returns `None` if
/// absent or not a string.
fn require_string_field<'a>(
    obj: &'a Map<String, Value>,
    key: &str,
    errors: &mut Vec<String>,
) -> Option<&'a str> {
    match obj.get(key) {
        None => {
            errors.push(format!("'{key}' is required"));
            None
        }
        Some(v) => match v.as_str() {
            Some(s) => Some(s),
            None => {
                errors.push(format!("'{key}' must be a string"));
                None
            }
        },
    }
}

/// Require an object field in `obj`. Pushes an error and returns `None` if
/// absent or not an object.
fn required_object_field<'a>(
    obj: &'a Map<String, Value>,
    key: &str,
    errors: &mut Vec<String>,
) -> Option<&'a Map<String, Value>> {
    match obj.get(key) {
        None => {
            errors.push(format!("'{key}' is required"));
            None
        }
        Some(v) => match v.as_object() {
            Some(o) => Some(o),
            None => {
                errors.push(format!("'{key}' must be an object"));
                None
            }
        },
    }
}

fn require_object<'a>(
    val: &'a Value,
    field: &str,
    errors: &mut Vec<String>,
) -> Option<&'a Map<String, Value>> {
    match val.as_object() {
        Some(o) => Some(o),
        None => {
            errors.push(format!("{field}: must be an object"));
            None
        }
    }
}

fn require_field<'a>(
    obj: &'a Map<String, Value>,
    key: &str,
    field: &str,
    errors: &mut Vec<String>,
) -> Option<&'a Value> {
    match obj.get(key) {
        Some(v) => Some(v),
        None => {
            errors.push(format!("{field}: missing required field '{key}'"));
            None
        }
    }
}

fn require_array<'a>(
    val: &'a Value,
    field: &str,
    errors: &mut Vec<String>,
) -> Option<&'a Vec<Value>> {
    match val.as_array() {
        Some(a) => Some(a),
        None => {
            errors.push(format!("{field}: must be an array"));
            None
        }
    }
}

/// Parse an array of JSON values as `Vec<u32>` positions.
///
/// Returns `None` if any element is not a non-negative integer that fits in
/// `u32` — all bad elements are reported before returning.
fn parse_positions(arr: &[Value], field: &str, errors: &mut Vec<String>) -> Option<Vec<u32>> {
    let mut positions = Vec::with_capacity(arr.len());
    let mut ok = true;
    for (i, v) in arr.iter().enumerate() {
        match v.as_u64().and_then(|n| u32::try_from(n).ok()) {
            Some(pos) => positions.push(pos),
            None => {
                errors.push(format!("{field}[{i}]: must be a positive integer"));
                ok = false;
            }
        }
    }
    ok.then_some(positions)
}

/// Parse an array of JSON values as `Vec<[u32; 2]>` ranges.
///
/// Each element must be a 2-element array of non-negative integers that fit in
/// `u32`. All bad elements are reported before returning `None`.
fn parse_ranges(arr: &[Value], field: &str, errors: &mut Vec<String>) -> Option<Vec<[u32; 2]>> {
    let mut ranges = Vec::with_capacity(arr.len());
    let mut ok = true;
    for (i, v) in arr.iter().enumerate() {
        let elem = format!("{field}[{i}]");
        match v.as_array() {
            None => {
                errors.push(format!("{elem}: must be a [start, end] array"));
                ok = false;
            }
            Some(pair) if pair.len() != 2 => {
                errors.push(format!(
                    "{elem}: must be a 2-element [start, end] array, got {} elements",
                    pair.len()
                ));
                ok = false;
            }
            Some(pair) => {
                let s = pair[0].as_u64().and_then(|n| u32::try_from(n).ok());
                let e = pair[1].as_u64().and_then(|n| u32::try_from(n).ok());
                match (s, e) {
                    (Some(s), Some(e)) => ranges.push([s, e]),
                    _ => {
                        errors.push(format!("{elem}: start and end must be positive integers"));
                        ok = false;
                    }
                }
            }
        }
    }
    ok.then_some(ranges)
}

/// Check that the optional `"type"` field in an annotation entry is a string.
fn check_kind_field(entry: &Map<String, Value>, field: &str, errors: &mut Vec<String>) {
    if let Some(v) = entry.get("type")
        && !v.is_string()
    {
        errors.push(format!("{field}.type: must be a string"));
    }
}