ggen_core/validation/error.rs
1//! Error types for SHACL validation
2//!
3//! This module defines error types for the validation system following
4//! Constitution Principle VII (Error Handling Standards).
5//!
6//! ## Design Principles
7//!
8//! - ✓ Uses thiserror for ergonomic error definitions
9//! - ✓ Provides context-rich error messages
10//! - ✓ NO unwrap() or expect() in production code
11//! - ✓ All errors implement std::error::Error
12
13use std::path::PathBuf;
14use thiserror::Error;
15
16/// Result type alias for validation operations
17///
18/// Uses ValidationError as the error type for all validation operations.
19/// This follows Constitution Principle VII (Result<T,E> for all fallible operations).
20pub type Result<T> = std::result::Result<T, ValidationError>;
21
22/// Validation error types
23///
24/// Represents all possible errors that can occur during SHACL validation.
25/// Each variant provides context-specific information for debugging.
26///
27/// ## Constitution Compliance
28///
29/// - ✓ Principle VII: Result<T,E> error handling (no panic in production)
30/// - ✓ Uses thiserror for automatic Error trait implementation
31/// - ✓ Context-rich error messages with file paths and line numbers where applicable
32#[derive(Error, Debug)]
33pub enum ValidationError {
34 /// TTL syntax parsing error
35 ///
36 /// Occurs when loading TTL files (ontology or shapes) with invalid Turtle syntax.
37 ///
38 /// Example:
39 /// ```text
40 /// ParseError: Invalid Turtle syntax at line 42 in spec.ttl
41 /// Caused by: Unexpected token '<' expecting IRI or blank node
42 /// ```
43 #[error("TTL parse error in {file}: {message}")]
44 ParseError {
45 /// File path where the parse error occurred
46 file: PathBuf,
47 /// Detailed error message from the parser
48 message: String,
49 /// Line number if available (0 if unknown)
50 line: usize,
51 /// Column number if available (0 if unknown)
52 column: usize,
53 },
54
55 /// SHACL shapes file loading error
56 ///
57 /// Occurs when shapes.ttl file cannot be found, read, or contains invalid SHACL definitions.
58 ///
59 /// Example:
60 /// ```text
61 /// ShapeLoadError: Could not load SHACL shapes from shapes.ttl
62 /// Caused by: File not found
63 /// ```
64 #[error("Failed to load SHACL shapes from {file}: {reason}")]
65 ShapeLoadError {
66 /// Path to the shapes file that failed to load
67 file: PathBuf,
68 /// Reason for the failure (file not found, invalid SHACL, etc.)
69 reason: String,
70 },
71
72 /// SPARQL query execution error
73 ///
74 /// Occurs when a SPARQL query (generated from SHACL shapes) fails to execute
75 /// against the RDF graph.
76 ///
77 /// Example:
78 /// ```text
79 /// SparqlError: SPARQL query failed
80 /// Query: SELECT ?s WHERE { ?s a sk:UserStory }
81 /// Caused by: Unknown prefix 'sk'
82 /// ```
83 #[error("SPARQL query execution failed: {message}")]
84 SparqlError {
85 /// Error message from Oxigraph SPARQL engine
86 message: String,
87 /// The SPARQL query that failed (for debugging)
88 query: String,
89 },
90
91 /// I/O error (file system operations)
92 ///
93 /// Wraps std::io::Error for file operations (reading TTL files, writing reports).
94 ///
95 /// Example:
96 /// ```text
97 /// IoError: Failed to read file: Permission denied (os error 13)
98 /// ```
99 #[error("I/O error: {0}")]
100 IoError(#[from] std::io::Error),
101
102 /// Oxigraph-specific errors
103 ///
104 /// Wraps Oxigraph errors (graph operations, SPARQL parsing, etc.)
105 ///
106 /// Example:
107 /// ```text
108 /// OxigraphError: Failed to insert triple into graph
109 /// ```
110 #[error("Oxigraph error: {0}")]
111 OxigraphError(String),
112
113 /// Invalid SHACL constraint configuration
114 ///
115 /// Occurs when SHACL shapes contain unsupported or malformed constraints.
116 ///
117 /// Example:
118 /// ```text
119 /// InvalidConstraint: Unsupported constraint type 'sh:uniqueLang' in shape :UserStoryShape
120 /// Supported: sh:minCount, sh:maxCount, sh:datatype, sh:in, sh:pattern, sh:minLength, sh:maxLength
121 /// ```
122 #[error("Invalid SHACL constraint: {message}")]
123 InvalidConstraint {
124 /// Error message describing the invalid constraint
125 message: String,
126 /// Shape IRI that contains the invalid constraint
127 shape_iri: String,
128 },
129
130 /// Validation timeout
131 ///
132 /// Occurs when validation exceeds configured timeout threshold.
133 ///
134 /// Example:
135 /// ```text
136 /// TimeoutError: Validation exceeded 30s timeout
137 /// ```
138 #[error("Validation timeout after {duration_ms}ms (limit: {limit_ms}ms)")]
139 TimeoutError {
140 /// Actual duration in milliseconds
141 duration_ms: u64,
142 /// Configured timeout limit in milliseconds
143 limit_ms: u64,
144 },
145
146 /// Syntax validation failed for generated file
147 ///
148 /// Occurs when a generated file contains syntax errors (e.g., invalid Rust code,
149 /// malformed TOML, invalid JSON). Includes location information for debugging.
150 ///
151 /// Example:
152 /// ```text
153 /// SyntaxValidationFailed in src/main.rs:42:10 [Rust]: expected `{` found `;`
154 /// ```
155 #[error("Syntax validation failed in {file}:{line}:{column} [{language}]: {error}")]
156 SyntaxValidationFailed {
157 /// Path to file with syntax error (relative or absolute)
158 file: String,
159 /// Line number (1-based, 0 if unknown)
160 line: usize,
161 /// Column number (1-based, 0 if unknown)
162 column: usize,
163 /// Language/file type (e.g., "Rust", "TOML", "JSON")
164 language: String,
165 /// Parser error message
166 error: String,
167 },
168
169 /// General validation error (fallback)
170 ///
171 /// Occurs when validation fails but doesn't fit specific categories.
172 /// Used for conversion from other error types.
173 ///
174 /// Example:
175 /// ```text
176 /// General: Input validation error: Invalid email format
177 /// ```
178 #[error("General validation error: {message}")]
179 General {
180 /// Error message
181 message: String,
182 },
183}
184
185impl ValidationError {
186 /// Create a parse error from file path and message
187 pub fn parse_error(
188 file: impl Into<PathBuf>, message: impl Into<String>, line: usize, column: usize,
189 ) -> Self {
190 ValidationError::ParseError {
191 file: file.into(),
192 message: message.into(),
193 line,
194 column,
195 }
196 }
197
198 /// Create a shape load error
199 pub fn shape_load_error(file: impl Into<PathBuf>, reason: impl Into<String>) -> Self {
200 ValidationError::ShapeLoadError {
201 file: file.into(),
202 reason: reason.into(),
203 }
204 }
205
206 /// Create a SPARQL error
207 pub fn sparql_error(message: impl Into<String>, query: impl Into<String>) -> Self {
208 ValidationError::SparqlError {
209 message: message.into(),
210 query: query.into(),
211 }
212 }
213
214 /// Create an invalid constraint error
215 pub fn invalid_constraint(message: impl Into<String>, shape_iri: impl Into<String>) -> Self {
216 ValidationError::InvalidConstraint {
217 message: message.into(),
218 shape_iri: shape_iri.into(),
219 }
220 }
221
222 /// Create a timeout error
223 pub fn timeout_error(duration_ms: u64, limit_ms: u64) -> Self {
224 ValidationError::TimeoutError {
225 duration_ms,
226 limit_ms,
227 }
228 }
229
230 /// Create a timeout error with context (for validation rules)
231 pub fn timeout(context: impl Into<String>, limit_ms: u64) -> Self {
232 ValidationError::OxigraphError(format!(
233 "{} exceeded timeout of {}ms",
234 context.into(),
235 limit_ms
236 ))
237 }
238
239 /// Create an invalid query error (for SPARQL validation rules)
240 pub fn invalid_query(rule_id: &str, reason: &str) -> Self {
241 ValidationError::SparqlError {
242 message: format!("Invalid query for rule {}: {}", rule_id, reason),
243 query: String::new(),
244 }
245 }
246
247 /// Create a query execution error (for SPARQL validation rules)
248 pub fn query_execution(rule_id: &str, error: &str) -> Self {
249 ValidationError::SparqlError {
250 message: format!("Query execution failed for rule {}: {}", rule_id, error),
251 query: String::new(),
252 }
253 }
254
255 /// Create a syntax validation error
256 pub fn syntax_validation_failed(
257 file: impl Into<String>, line: usize, column: usize, language: impl Into<String>,
258 error: impl Into<String>,
259 ) -> Self {
260 ValidationError::SyntaxValidationFailed {
261 file: file.into(),
262 line,
263 column,
264 language: language.into(),
265 error: error.into(),
266 }
267 }
268}
269
270// Implement From<oxigraph::Error> for ValidationError
271impl From<oxigraph::store::LoaderError> for ValidationError {
272 fn from(err: oxigraph::store::LoaderError) -> Self {
273 ValidationError::OxigraphError(err.to_string())
274 }
275}
276
277impl From<oxigraph::sparql::QueryEvaluationError> for ValidationError {
278 fn from(err: oxigraph::sparql::QueryEvaluationError) -> Self {
279 ValidationError::SparqlError {
280 message: err.to_string(),
281 query: String::new(), // Query context added by caller
282 }
283 }
284}
285
286// Conversion from InputValidationError to ValidationError
287impl From<crate::validation::input::InputValidationError> for ValidationError {
288 fn from(error: crate::validation::input::InputValidationError) -> Self {
289 ValidationError::General {
290 message: format!("Input validation error: {}", error),
291 }
292 }
293}
294
295#[cfg(test)]
296mod tests {
297 use super::*;
298
299 #[test]
300 fn test_parse_error_construction() {
301 let err =
302 ValidationError::parse_error(PathBuf::from("test.ttl"), "Unexpected token", 42, 15);
303
304 match err {
305 ValidationError::ParseError {
306 file,
307 message,
308 line,
309 column,
310 } => {
311 assert_eq!(file, PathBuf::from("test.ttl"));
312 assert_eq!(message, "Unexpected token");
313 assert_eq!(line, 42);
314 assert_eq!(column, 15);
315 }
316 _ => panic!("Expected ParseError"),
317 }
318 }
319
320 #[test]
321 fn test_shape_load_error_display() {
322 let err = ValidationError::shape_load_error(PathBuf::from("shapes.ttl"), "File not found");
323
324 let display = format!("{}", err);
325 assert!(display.contains("shapes.ttl"));
326 assert!(display.contains("File not found"));
327 }
328
329 #[test]
330 fn test_sparql_error_construction() {
331 let err = ValidationError::sparql_error(
332 "Unknown prefix 'sk'",
333 "SELECT ?s WHERE { ?s a sk:UserStory }",
334 );
335
336 match err {
337 ValidationError::SparqlError { message, query } => {
338 assert_eq!(message, "Unknown prefix 'sk'");
339 assert!(query.contains("sk:UserStory"));
340 }
341 _ => panic!("Expected SparqlError"),
342 }
343 }
344
345 #[test]
346 fn test_invalid_constraint_error() {
347 let err = ValidationError::invalid_constraint("Unsupported constraint", ":UserStoryShape");
348
349 match err {
350 ValidationError::InvalidConstraint { message, shape_iri } => {
351 assert_eq!(message, "Unsupported constraint");
352 assert_eq!(shape_iri, ":UserStoryShape");
353 }
354 _ => panic!("Expected InvalidConstraint"),
355 }
356 }
357
358 #[test]
359 fn test_timeout_error() {
360 let err = ValidationError::timeout_error(35000, 30000);
361
362 match err {
363 ValidationError::TimeoutError {
364 duration_ms,
365 limit_ms,
366 } => {
367 assert_eq!(duration_ms, 35000);
368 assert_eq!(limit_ms, 30000);
369 }
370 _ => panic!("Expected TimeoutError"),
371 }
372 }
373
374 #[test]
375 fn test_result_type_alias() {
376 fn returns_result() -> Result<i32> {
377 Ok(42)
378 }
379
380 assert_eq!(returns_result().unwrap(), 42);
381 }
382
383 #[test]
384 fn test_error_propagation() {
385 fn inner() -> Result<()> {
386 Err(ValidationError::parse_error(
387 "test.ttl",
388 "Syntax error",
389 10,
390 5,
391 ))
392 }
393
394 fn outer() -> Result<()> {
395 inner()?; // Error propagates via ?
396 Ok(())
397 }
398
399 assert!(outer().is_err());
400 }
401}