hyprstream_decision/error.rs
1//! Structured, positioned errors for question-spec authoring.
2//!
3//! Every error carries a machine-readable [`SpecErrorKind`], a document path
4//! ([`ErrorPath`], rendered JSON-pointer-style, e.g. `/questions/tone/criteria/2`), and
5//! for text-syntax errors a 1-based line/column. Authors of question specs need no Rust,
6//! capnp, or Arrow knowledge: the path points at the offending element of their YAML/JSON
7//! document and the message says what rule was violated.
8
9use std::fmt;
10
11/// Machine-readable category of an authoring/validation failure.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13pub enum SpecErrorKind {
14 /// The document text is not valid YAML/JSON. Carries line/column when known.
15 Syntax,
16 /// A document element has the wrong shape (e.g. a sequence where a mapping was
17 /// required).
18 Structure,
19 /// A required key is absent (e.g. `type`, or `criteria` on a choice/score question).
20 MissingField,
21 /// A key the profile does not define was present. Unknown fields are rejected
22 /// (parity with the upstream SDKs' `extra=forbid` behavior).
23 UnknownField,
24 /// `type` names no known question primitive.
25 UnknownQuestionType,
26 /// `type` names a reserved v2 primitive (`span`, `derived`) that v1 does not
27 /// implement. This is deliberately distinct from `UnknownQuestionType` so callers can
28 /// report "recognized but reserved" instead of "typo".
29 ReservedQuestionType,
30 /// A cardinality rule was violated: choice needs 2–255 options (D2), score needs ≥ 2
31 /// levels (D1), a request needs ≥ 1 question.
32 Cardinality,
33 /// A required string is empty (question id, option name).
34 EmptyName,
35 /// The same key appears twice in one mapping (question id or option name).
36 DuplicateKey,
37}
38
39impl SpecErrorKind {
40 /// Stable machine-readable code (snake_case), suitable for API error payloads.
41 pub fn code(self) -> &'static str {
42 match self {
43 Self::Syntax => "syntax",
44 Self::Structure => "structure",
45 Self::MissingField => "missing_field",
46 Self::UnknownField => "unknown_field",
47 Self::UnknownQuestionType => "unknown_question_type",
48 Self::ReservedQuestionType => "reserved_question_type",
49 Self::Cardinality => "cardinality",
50 Self::EmptyName => "empty_name",
51 Self::DuplicateKey => "duplicate_key",
52 }
53 }
54}
55
56/// A position inside an authored document: a sequence of mapping keys and array indices.
57///
58/// Renders as a JSON pointer (`/questions/tone/criteria/2`). The empty path (`/`) refers
59/// to the document root.
60#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
61pub struct ErrorPath {
62 segments: Vec<String>,
63}
64
65impl ErrorPath {
66 /// The document root.
67 pub fn root() -> Self {
68 Self::default()
69 }
70
71 /// Append a mapping-key segment.
72 pub fn key(&self, key: &str) -> Self {
73 let mut segments = self.segments.clone();
74 segments.push(key.to_owned());
75 Self { segments }
76 }
77
78 /// Append an array-index segment.
79 pub fn index(&self, index: usize) -> Self {
80 let mut segments = self.segments.clone();
81 segments.push(index.to_string());
82 Self { segments }
83 }
84}
85
86impl fmt::Display for ErrorPath {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 if self.segments.is_empty() {
89 return f.write_str("/");
90 }
91 for segment in &self.segments {
92 // JSON-pointer escaping (RFC 6901) so keys containing '/' or '~' stay exact.
93 f.write_str("/")?;
94 f.write_str(&segment.replace('~', "~0").replace('/', "~1"))?;
95 }
96 Ok(())
97 }
98}
99
100/// A single positioned authoring error.
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct SpecError {
103 /// Machine-readable category.
104 pub kind: SpecErrorKind,
105 /// Document position of the offending element.
106 pub path: ErrorPath,
107 /// 1-based line of a text-syntax error, when the parser reported one.
108 pub line: Option<usize>,
109 /// 1-based column of a text-syntax error, when the parser reported one.
110 pub column: Option<usize>,
111 /// Human-readable explanation of the violated rule.
112 pub message: String,
113}
114
115impl SpecError {
116 pub(crate) fn new(kind: SpecErrorKind, path: ErrorPath, message: impl Into<String>) -> Self {
117 Self {
118 kind,
119 path,
120 line: None,
121 column: None,
122 message: message.into(),
123 }
124 }
125
126 pub(crate) fn syntax(
127 message: impl Into<String>,
128 line: Option<usize>,
129 column: Option<usize>,
130 ) -> Self {
131 Self {
132 kind: SpecErrorKind::Syntax,
133 path: ErrorPath::root(),
134 line,
135 column,
136 message: message.into(),
137 }
138 }
139}
140
141impl fmt::Display for SpecError {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 write!(f, "{} at {}", self.kind.code(), self.path)?;
144 if let (Some(line), Some(column)) = (self.line, self.column) {
145 write!(f, " (line {line}, column {column})")?;
146 }
147 write!(f, ": {}", self.message)
148 }
149}
150
151impl std::error::Error for SpecError {}