openjd-model 0.1.0

Open Job Description model library — parsing, validation, and job creation
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Copyright by contributors to this project.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

//! Error types for the OpenJD model library.
//!
//! The primary error type is [`ModelError`], which covers all failure modes
//! during template parsing, validation, and job creation.

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ModelError {
    /// Structural deserialization failure (bad YAML/JSON, missing fields, wrong types).
    #[error("Validation error: {0}")]
    DecodeValidation(String),

    /// Semantic validation failure (template parsed but violates spec rules).
    /// Contains structured [`ValidationErrors`] with per-field paths.
    /// Use `Display` / `.to_string()` for the formatted message.
    #[error("Model validation error: {0}")]
    ModelValidation(ValidationErrors),

    /// Format string interpolation error with optional position info.
    #[error("{}", format_string_error(.message, .input, .start, .end))]
    FormatStringError {
        message: String,
        /// The raw format string that failed, if available.
        input: Option<String>,
        /// Byte offset of the failing interpolation start.
        start: Option<usize>,
        /// Byte offset of the failing interpolation end.
        end: Option<usize>,
    },

    /// Expression evaluation or symbol table error, preserving the full
    /// [`ExpressionError`](openjd_expr::ExpressionError) with its kind and
    /// source-location context.
    #[error("Expression error: {0}")]
    Expression(#[source] openjd_expr::ExpressionError),

    #[error("Compatibility error: {0}")]
    Compatibility(String),

    #[error("Unsupported schema version: {0}")]
    UnsupportedSchema(String),
}

fn format_string_error(
    message: &str,
    input: &Option<String>,
    start: &Option<usize>,
    end: &Option<usize>,
) -> String {
    match (input, start, end) {
        (Some(input), Some(s), Some(e)) => {
            format!("Failed to parse interpolation expression at [{s}, {e}]. {message}\n  {input}")
        }
        _ => format!("Format string error: {message}"),
    }
}

impl From<openjd_expr::SymbolTableError> for ModelError {
    fn from(e: openjd_expr::SymbolTableError) -> Self {
        ModelError::Expression(openjd_expr::ExpressionError::from(e))
    }
}

impl From<openjd_expr::FormatStringValidationError> for ModelError {
    fn from(e: openjd_expr::FormatStringValidationError) -> Self {
        ModelError::FormatStringError {
            message: e.message,
            input: Some(e.input),
            start: Some(e.start),
            end: Some(e.end),
        }
    }
}

/// An element in a validation error path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathElement {
    Field(String),
    Index(usize),
}

/// A single validation error with its location in the template.
#[derive(Debug, Clone)]
pub struct ValidationError {
    /// Location of the error in the template structure (e.g., which field
    /// in the JSON/YAML tree). Used by consumers to navigate to or annotate
    /// the affected node.
    pub path: Vec<PathElement>,
    /// Complete human-readable error text, suitable for direct display.
    /// Includes source pointers and span context where available.
    pub message: String,
    /// Structured diagnostic data decomposing the error into a summary
    /// and source spans. `None` for errors without source position info
    /// (e.g., duplicate names, missing required fields, limit violations).
    pub detail: Option<ErrorDetail>,
}

/// Structured diagnostic data for a validation error.
#[derive(Debug, Clone)]
pub struct ErrorDetail {
    /// Human-readable error summary without source pointers.
    pub summary: String,
    /// Diagnostic spans identifying specific character ranges in the
    /// source text where the error occurs.
    pub spans: Vec<DiagnosticSpan>,
}

/// A diagnostic span identifying a specific character range in source text.
#[derive(Debug, Clone)]
pub struct DiagnosticSpan {
    /// Human-readable description of the diagnostic at this source location.
    pub summary: String,
    /// The source text containing the error.
    pub source: String,
    /// Byte offset of the error start within source.
    pub start: usize,
    /// Byte offset of the error end within source.
    pub end: usize,
    /// Position of the caret (most relevant character) relative to start.
    pub caret: usize,
}

/// Collects multiple validation errors with structured paths.
#[derive(Debug, Default)]
pub struct ValidationErrors {
    pub errors: Vec<ValidationError>,
    /// Model name used for Display formatting (set by `into_result`).
    model_name: Option<String>,
}

impl std::fmt::Display for ValidationErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = self.model_name.as_deref().unwrap_or("Template");
        write!(f, "{}", self.format(name))
    }
}

impl ValidationErrors {
    /// Create a `ValidationErrors` with a single root-level message.
    pub fn single(msg: impl Into<String>) -> Self {
        let mut ve = Self::default();
        ve.add(&[], msg);
        ve
    }

    /// Add an error at the given path.
    pub fn add(&mut self, path: &[PathElement], msg: impl Into<String>) {
        self.errors.push(ValidationError {
            path: path.to_vec(),
            message: msg.into(),
            detail: None,
        });
    }

    /// Add an error at the given path with structured diagnostic detail.
    pub fn add_with_detail(
        &mut self,
        path: &[PathElement],
        msg: impl Into<String>,
        detail: ErrorDetail,
    ) {
        self.errors.push(ValidationError {
            path: path.to_vec(),
            message: msg.into(),
            detail: Some(detail),
        });
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.errors.len()
    }

    pub fn into_result(self, model_name: &str) -> Result<(), ModelError> {
        if self.errors.is_empty() {
            Ok(())
        } else {
            // Store the model name in the formatted output via Display
            // The ValidationErrors struct is moved into the enum variant
            Err(ModelError::ModelValidation(
                self.with_model_name(model_name),
            ))
        }
    }

    /// Set the model name for Display formatting and return self.
    fn with_model_name(mut self, name: &str) -> Self {
        self.model_name = Some(name.to_string());
        self
    }

    /// Format errors matching the Python Pydantic output format.
    pub fn format(&self, model_name: &str) -> String {
        let n = self.errors.len();
        let word = if n == 1 { "error" } else { "errors" };
        let mut out = format!("{n} validation {word} for {model_name}");
        for err in &self.errors {
            out.push('\n');
            if err.path.is_empty() {
                // Root-level error
                out.push_str(&format!("{model_name}: {}", err.message));
            } else {
                format_path(&err.path, &mut out);
                out.push_str(":\n\t");
                out.push_str(&err.message);
            }
        }
        out
    }
}

/// Format a path as `field[index] -> nested -> leaf`.
fn format_path(path: &[PathElement], out: &mut String) {
    let mut first = true;
    for elem in path {
        match elem {
            PathElement::Field(name) => {
                if !first {
                    out.push_str(" -> ");
                }
                out.push_str(name);
                first = false;
            }
            PathElement::Index(i) => {
                out.push_str(&format!("[{i}]"));
            }
        }
    }
}

/// Helper: extend a path with a field name.
#[must_use]
pub fn path_field(base: &[PathElement], field: &str) -> Vec<PathElement> {
    let mut p = base.to_vec();
    p.push(PathElement::Field(field.to_string()));
    p
}

/// Helper: extend a path with an index.
#[must_use]
pub fn path_index(base: &[PathElement], index: usize) -> Vec<PathElement> {
    let mut p = base.to_vec();
    p.push(PathElement::Index(index));
    p
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_unsupported_schema_msg() {
        let e = ModelError::UnsupportedSchema("version".into());
        assert_eq!(e.to_string(), "Unsupported schema version: version");
    }

    #[test]
    fn test_model_validation_msg() {
        let mut ve = ValidationErrors::default();
        ve.add(&[PathElement::Field("name".into())], "bad template");
        let e = ModelError::ModelValidation(ve.with_model_name("JobTemplate"));
        assert_eq!(
            e.to_string(),
            "Model validation error: 1 validation error for JobTemplate\nname:\n\tbad template"
        );
    }

    #[test]
    fn test_format_string_error_with_position() {
        let e = ModelError::FormatStringError {
            message: "Undefined variable 'Param.X'".into(),
            input: Some("Hello {{Param.X}}".into()),
            start: Some(6),
            end: Some(17),
        };
        let s = e.to_string();
        assert!(s.contains("Failed to parse interpolation expression at [6, 17]"));
        assert!(s.contains("Undefined variable 'Param.X'"));
        assert!(s.contains("Hello {{Param.X}}"));
    }

    #[test]
    fn test_format_string_error_without_position() {
        let e = ModelError::FormatStringError {
            message: "something went wrong".into(),
            input: None,
            start: None,
            end: None,
        };
        assert_eq!(e.to_string(), "Format string error: something went wrong");
    }

    #[test]
    fn test_empty_errors_ok() {
        let ve = ValidationErrors::default();
        assert!(ve.into_result("JobTemplate").is_ok());
    }

    #[test]
    fn test_single_field_error() {
        let mut ve = ValidationErrors::default();
        ve.add(&[PathElement::Field("name".into())], "must not be empty");
        let s = ve.format("JobTemplate");
        assert_eq!(
            s,
            "1 validation error for JobTemplate\nname:\n\tmust not be empty"
        );
    }

    #[test]
    fn test_into_result_uses_model_validation() {
        let mut ve = ValidationErrors::default();
        ve.add(&[PathElement::Field("name".into())], "too long");
        let result = ve.into_result("JobTemplate");
        assert!(matches!(result, Err(ModelError::ModelValidation(_))));
    }

    #[test]
    fn test_nested_path_error() {
        let mut ve = ValidationErrors::default();
        ve.add(
            &[
                PathElement::Field("steps".into()),
                PathElement::Index(0),
                PathElement::Field("parameterSpace".into()),
                PathElement::Field("combination".into()),
            ],
            "missing operator",
        );
        let s = ve.format("JobTemplate");
        assert!(s.contains("steps[0] -> parameterSpace -> combination:\n\tmissing operator"));
    }

    #[test]
    fn test_root_level_error() {
        let mut ve = ValidationErrors::default();
        ve.add(&[], "must have at least one step");
        let s = ve.format("JobTemplate");
        assert!(s.contains("JobTemplate: must have at least one step"));
    }

    #[test]
    fn test_multiple_errors() {
        let mut ve = ValidationErrors::default();
        ve.add(&[PathElement::Field("name".into())], "too long");
        ve.add(
            &[
                PathElement::Field("steps".into()),
                PathElement::Index(0),
                PathElement::Field("name".into()),
            ],
            "empty",
        );
        assert_eq!(ve.len(), 2);
        let result = ve.into_result("JobTemplate");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("2 validation errors"));
        assert!(msg.contains("name:\n\ttoo long"));
        assert!(msg.contains("steps[0] -> name:\n\tempty"));
    }

    #[test]
    fn test_path_helpers() {
        let base = vec![PathElement::Field("steps".into()), PathElement::Index(0)];
        let with_field = path_field(&base, "script");
        assert_eq!(with_field.len(), 3);
        let with_index = path_index(&base, 1);
        assert_eq!(with_index.len(), 3);
    }

    #[test]
    fn test_model_validation_structured_access() {
        let mut ve = ValidationErrors::default();
        ve.add(
            &[PathElement::Field("steps".into()), PathElement::Index(0)],
            "missing script",
        );
        ve.add(&[PathElement::Field("name".into())], "too long");
        let err = ve.into_result("JobTemplate").unwrap_err();
        let errors = match &err {
            ModelError::ModelValidation(e) => e,
            other => panic!("expected ModelValidation, got: {other}"),
        };
        assert_eq!(errors.len(), 2);
        assert_eq!(
            errors.errors[0].path,
            vec![PathElement::Field("steps".into()), PathElement::Index(0)]
        );
        assert_eq!(errors.errors[0].message, "missing script");
        assert_eq!(
            errors.errors[1].path,
            vec![PathElement::Field("name".into())]
        );
        assert_eq!(errors.errors[1].message, "too long");
        assert_eq!(
            err.to_string(),
            "Model validation error: 2 validation errors for JobTemplate\n\
             steps[0]:\n\tmissing script\n\
             name:\n\ttoo long"
        );
    }
}