Skip to main content

qualia_core_db/q42/chebi_parse/
error.rs

1//! Parse and quarantine errors for ChEBI `compounds.tsv` (AST-03).
2
3use std::fmt;
4
5/// Fail-closed errors for the cold-construction ChEBI TSV parser.
6#[derive(Debug)]
7pub enum ParseError {
8    /// Header row missing or column names do not match the documented layout.
9    BadHeader,
10    /// Whole input exceeds [`super::ParseBudgets::max_bytes`].
11    ByteBudgetExceeded { size: u64, max: u64 },
12    /// A single line exceeds [`super::ParseBudgets::max_line_bytes`].
13    LineTooLong {
14        source_line: u64,
15        len: u64,
16        max: u64,
17    },
18    /// Accepted + quarantined rows would exceed [`super::ParseBudgets::max_records`].
19    RecordBudgetExceeded { used: u64, max: u64 },
20    /// Budget fields must be strictly positive.
21    InvalidBudgets,
22    /// Caller set the cancel flag mid-parse.
23    Cancelled,
24    /// Local filesystem read failed (path helper only; no network).
25    Io(std::io::Error),
26}
27
28impl PartialEq for ParseError {
29    fn eq(&self, other: &Self) -> bool {
30        use ParseError::*;
31        match (self, other) {
32            (BadHeader, BadHeader) | (InvalidBudgets, InvalidBudgets) | (Cancelled, Cancelled) => {
33                true
34            }
35            (ByteBudgetExceeded { size: a, max: b }, ByteBudgetExceeded { size: c, max: d }) => {
36                a == c && b == d
37            }
38            (
39                LineTooLong {
40                    source_line: a,
41                    len: b,
42                    max: c,
43                },
44                LineTooLong {
45                    source_line: d,
46                    len: e,
47                    max: f,
48                },
49            ) => a == d && b == e && c == f,
50            (
51                RecordBudgetExceeded { used: a, max: b },
52                RecordBudgetExceeded { used: c, max: d },
53            ) => a == c && b == d,
54            (Io(a), Io(b)) => a.kind() == b.kind(),
55            _ => false,
56        }
57    }
58}
59
60impl Eq for ParseError {}
61
62impl fmt::Display for ParseError {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        match self {
65            Self::BadHeader => write!(f, "compounds.tsv header missing or mismatched"),
66            Self::ByteBudgetExceeded { size, max } => {
67                write!(f, "input exceeds max_bytes (size={size}, max={max})")
68            }
69            Self::LineTooLong {
70                source_line,
71                len,
72                max,
73            } => write!(
74                f,
75                "line {source_line} exceeds max_line_bytes (len={len}, max={max})"
76            ),
77            Self::RecordBudgetExceeded { used, max } => {
78                write!(f, "record budget exceeded (used={used}, max={max})")
79            }
80            Self::InvalidBudgets => write!(f, "parse budgets must be positive"),
81            Self::Cancelled => write!(f, "chebi parse cancelled"),
82            Self::Io(e) => write!(f, "chebi parse i/o: {e}"),
83        }
84    }
85}
86
87impl std::error::Error for ParseError {
88    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
89        match self {
90            Self::Io(e) => Some(e),
91            _ => None,
92        }
93    }
94}
95
96impl From<std::io::Error> for ParseError {
97    fn from(value: std::io::Error) -> Self {
98        Self::Io(value)
99    }
100}
101
102/// One quarantined source row (not accepted into the normalized set).
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct QuarantinedRow {
105    /// 1-based file line number (header is line 1).
106    pub source_line: u64,
107    /// Stable reason code for deterministic reports.
108    pub reason: &'static str,
109    /// Bounded UTF-8 preview of the raw line (lossy if needed).
110    pub raw_preview: String,
111}
112
113/// Maximum bytes retained in [`QuarantinedRow::raw_preview`].
114pub const RAW_PREVIEW_MAX: usize = 160;
115
116/// Build a bounded preview from a raw line (no NUL expansion; chars truncated).
117pub fn bounded_preview(raw: &str) -> String {
118    let mut out = String::new();
119    for ch in raw.chars() {
120        if out.len() + ch.len_utf8() > RAW_PREVIEW_MAX {
121            break;
122        }
123        out.push(ch);
124    }
125    out
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn preview_respects_byte_budget() {
134        let long = "x".repeat(RAW_PREVIEW_MAX + 40);
135        let p = bounded_preview(&long);
136        assert!(p.len() <= RAW_PREVIEW_MAX);
137        assert_eq!(p.len(), RAW_PREVIEW_MAX);
138    }
139}