postmortem 0.1.1

A validation library that accumulates all errors for comprehensive feedback
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
//! Schema combinators for composing validation logic.
//!
//! This module provides combinators that allow schemas to be composed in different ways:
//! - `one_of`: Exactly one schema must match (discriminated unions)
//! - `any_of`: At least one schema must match (flexible unions)
//! - `all_of`: All schemas must match (intersection/merging)
//! - `optional`: Value can be null
//!
//! # Example
//!
//! ```rust
//! use postmortem::{Schema, ValueValidator, JsonPath};
//! use serde_json::json;
//!
//! // Discriminated union - either a circle or rectangle
//! let shape = Schema::one_of(vec![
//!     Box::new(Schema::object()
//!         .field("type", Schema::string())
//!         .field("radius", Schema::integer().positive())) as Box<dyn ValueValidator>,
//!     Box::new(Schema::object()
//!         .field("type", Schema::string())
//!         .field("width", Schema::integer().positive())
//!         .field("height", Schema::integer().positive())) as Box<dyn ValueValidator>,
//! ]);
//!
//! // Flexible type - string or integer ID
//! let id = Schema::any_of(vec![
//!     Box::new(Schema::string().min_len(1)) as Box<dyn ValueValidator>,
//!     Box::new(Schema::integer().positive()) as Box<dyn ValueValidator>,
//! ]);
//! ```

use serde_json::{json, Value};
use std::sync::Arc;
use stillwater::Validation;

use crate::error::{SchemaError, SchemaErrors};
use crate::interop::ToJsonSchema;
use crate::path::JsonPath;
use crate::schema::traits::{SchemaLike, ValueValidator};
use crate::validation::ValidationContext;

/// Type alias for validation function stored in combinators.
pub(crate) type ValidatorFn =
    Arc<dyn Fn(&Value, &JsonPath) -> Validation<Value, SchemaErrors> + Send + Sync>;

/// Schema combinators for composing validation logic.
///
/// `CombinatorSchema` provides four composition patterns:
/// - `OneOf`: Exactly one schema must match (discriminated unions)
/// - `AnyOf`: At least one schema must match (flexible unions)
/// - `AllOf`: All schemas must match (intersection)
/// - `Optional`: Value can be null
///
/// Each combinator implements `SchemaLike` and can be used anywhere a schema is expected.
#[derive(Clone)]
pub enum CombinatorSchema {
    /// Exactly one schema must match.
    ///
    /// Validates the value against all schemas. Succeeds if exactly one matches,
    /// fails if none or multiple match. Ideal for discriminated unions where
    /// a value must be one of several distinct types.
    OneOf {
        schemas: Vec<ValidatorFn>,
        validators: Vec<Arc<dyn ValueValidator>>,
    },

    /// At least one schema must match.
    ///
    /// Validates the value against schemas in order, short-circuiting on the
    /// first match. Fails only if none match. More permissive than `OneOf`.
    AnyOf {
        schemas: Vec<ValidatorFn>,
        validators: Vec<Arc<dyn ValueValidator>>,
    },

    /// All schemas must match.
    ///
    /// Validates the value against all schemas. Succeeds only if all pass,
    /// accumulating errors from any that fail. Useful for schema composition
    /// and intersection.
    AllOf {
        schemas: Vec<ValidatorFn>,
        validators: Vec<Arc<dyn ValueValidator>>,
    },

    /// Value can be null.
    ///
    /// Null values pass validation. Non-null values are validated against
    /// the inner schema.
    Optional {
        inner: ValidatorFn,
        validator: Arc<dyn ValueValidator>,
    },
}

impl CombinatorSchema {
    /// Validates a value against exactly one of the provided schemas.
    ///
    /// Returns success if exactly one schema matches, failure if none or multiple match.
    fn validate_one_of(
        schemas: &[ValidatorFn],
        value: &Value,
        path: &JsonPath,
    ) -> Validation<Value, SchemaErrors> {
        let results: Vec<_> = schemas
            .iter()
            .enumerate()
            .map(|(i, validator)| (i, validator(value, path)))
            .collect();

        let valid: Vec<_> = results.iter().filter(|(_, r)| r.is_success()).collect();

        match valid.len() {
            0 => {
                // None matched - report with count
                let error = SchemaError::new(
                    path.clone(),
                    format!("value did not match any of {} schemas", schemas.len()),
                )
                .with_code("one_of_none_matched");

                Validation::Failure(SchemaErrors::single(error))
            }
            1 => {
                // Exactly one matched - success
                let (_, result) = valid.into_iter().next().unwrap();
                // Extract the value from the successful result
                match result {
                    Validation::Success(v) => Validation::Success(v.clone()),
                    _ => unreachable!(),
                }
            }
            n => {
                // Multiple matched - ambiguous
                let indices: Vec<_> = valid.iter().map(|(i, _)| i).collect();
                let error = SchemaError::new(
                    path.clone(),
                    format!(
                        "value matched {} schemas (indices {:?}), expected exactly one",
                        n, indices
                    ),
                )
                .with_code("one_of_multiple_matched");

                Validation::Failure(SchemaErrors::single(error))
            }
        }
    }

    /// Validates a value against at least one of the provided schemas.
    ///
    /// Short-circuits on the first match. Returns failure only if none match.
    fn validate_any_of(
        schemas: &[ValidatorFn],
        value: &Value,
        path: &JsonPath,
    ) -> Validation<Value, SchemaErrors> {
        for validator in schemas {
            match validator(value, path) {
                Validation::Success(v) => return Validation::Success(v),
                Validation::Failure(_) => continue,
            }
        }

        // None matched
        let error = SchemaError::new(
            path.clone(),
            format!("value did not match any of {} schemas", schemas.len()),
        )
        .with_code("any_of_none_matched");

        Validation::Failure(SchemaErrors::single(error))
    }

    /// Validates a value against all of the provided schemas.
    ///
    /// Returns success only if all schemas pass, accumulating errors from failures.
    fn validate_all_of(
        schemas: &[ValidatorFn],
        value: &Value,
        path: &JsonPath,
    ) -> Validation<Value, SchemaErrors> {
        let mut all_errors = Vec::new();
        let mut last_valid = None;

        for validator in schemas {
            match validator(value, path) {
                Validation::Success(v) => last_valid = Some(v),
                Validation::Failure(e) => all_errors.extend(e.into_iter()),
            }
        }

        if all_errors.is_empty() {
            Validation::Success(last_valid.unwrap_or_else(|| value.clone()))
        } else {
            Validation::Failure(SchemaErrors::from_vec(all_errors))
        }
    }

    /// Validates a value as optional (can be null).
    ///
    /// Null values pass. Non-null values are validated against the inner schema.
    fn validate_optional(
        inner: &ValidatorFn,
        value: &Value,
        path: &JsonPath,
    ) -> Validation<Value, SchemaErrors> {
        if value.is_null() {
            Validation::Success(Value::Null)
        } else {
            inner(value, path)
        }
    }

    /// Validates a value against exactly one of the provided schemas with context.
    fn validate_one_of_with_context(
        validators: &[Arc<dyn ValueValidator>],
        value: &Value,
        path: &JsonPath,
        context: &ValidationContext,
    ) -> Validation<Value, SchemaErrors> {
        let results: Vec<_> = validators
            .iter()
            .enumerate()
            .map(|(i, validator)| {
                (
                    i,
                    validator.validate_value_with_context(value, path, context),
                )
            })
            .collect();

        let valid: Vec<_> = results.iter().filter(|(_, r)| r.is_success()).collect();

        match valid.len() {
            0 => {
                let error = SchemaError::new(
                    path.clone(),
                    format!("value did not match any of {} schemas", validators.len()),
                )
                .with_code("one_of_none_matched");

                Validation::Failure(SchemaErrors::single(error))
            }
            1 => {
                let (_, result) = valid.into_iter().next().unwrap();
                match result {
                    Validation::Success(v) => Validation::Success(v.clone()),
                    _ => unreachable!(),
                }
            }
            n => {
                let indices: Vec<_> = valid.iter().map(|(i, _)| i).collect();
                let error = SchemaError::new(
                    path.clone(),
                    format!(
                        "value matched {} schemas (indices {:?}), expected exactly one",
                        n, indices
                    ),
                )
                .with_code("one_of_multiple_matched");

                Validation::Failure(SchemaErrors::single(error))
            }
        }
    }

    /// Validates a value against at least one of the provided schemas with context.
    fn validate_any_of_with_context(
        validators: &[Arc<dyn ValueValidator>],
        value: &Value,
        path: &JsonPath,
        context: &ValidationContext,
    ) -> Validation<Value, SchemaErrors> {
        for validator in validators {
            match validator.validate_value_with_context(value, path, context) {
                Validation::Success(v) => return Validation::Success(v),
                Validation::Failure(_) => continue,
            }
        }

        let error = SchemaError::new(
            path.clone(),
            format!("value did not match any of {} schemas", validators.len()),
        )
        .with_code("any_of_none_matched");

        Validation::Failure(SchemaErrors::single(error))
    }

    /// Validates a value against all of the provided schemas with context.
    fn validate_all_of_with_context(
        validators: &[Arc<dyn ValueValidator>],
        value: &Value,
        path: &JsonPath,
        context: &ValidationContext,
    ) -> Validation<Value, SchemaErrors> {
        let mut all_errors = Vec::new();
        let mut last_valid = None;

        for validator in validators {
            match validator.validate_value_with_context(value, path, context) {
                Validation::Success(v) => last_valid = Some(v),
                Validation::Failure(e) => all_errors.extend(e.into_iter()),
            }
        }

        if all_errors.is_empty() {
            Validation::Success(last_valid.unwrap_or_else(|| value.clone()))
        } else {
            Validation::Failure(SchemaErrors::from_vec(all_errors))
        }
    }

    /// Validates a value as optional with context.
    fn validate_optional_with_context(
        validator: &Arc<dyn ValueValidator>,
        value: &Value,
        path: &JsonPath,
        context: &ValidationContext,
    ) -> Validation<Value, SchemaErrors> {
        if value.is_null() {
            Validation::Success(Value::Null)
        } else {
            validator.validate_value_with_context(value, path, context)
        }
    }
}

impl SchemaLike for CombinatorSchema {
    type Output = Value;

    fn validate(&self, value: &Value, path: &JsonPath) -> Validation<Value, SchemaErrors> {
        match self {
            CombinatorSchema::OneOf { schemas, .. } => Self::validate_one_of(schemas, value, path),
            CombinatorSchema::AnyOf { schemas, .. } => Self::validate_any_of(schemas, value, path),
            CombinatorSchema::AllOf { schemas, .. } => Self::validate_all_of(schemas, value, path),
            CombinatorSchema::Optional { inner, .. } => Self::validate_optional(inner, value, path),
        }
    }

    fn validate_to_value(&self, value: &Value, path: &JsonPath) -> Validation<Value, SchemaErrors> {
        self.validate(value, path)
    }

    fn validate_with_context(
        &self,
        value: &Value,
        path: &JsonPath,
        context: &ValidationContext,
    ) -> Validation<Value, SchemaErrors> {
        match self {
            CombinatorSchema::OneOf { validators, .. } => {
                Self::validate_one_of_with_context(validators, value, path, context)
            }
            CombinatorSchema::AnyOf { validators, .. } => {
                Self::validate_any_of_with_context(validators, value, path, context)
            }
            CombinatorSchema::AllOf { validators, .. } => {
                Self::validate_all_of_with_context(validators, value, path, context)
            }
            CombinatorSchema::Optional { validator, .. } => {
                Self::validate_optional_with_context(validator, value, path, context)
            }
        }
    }

    fn validate_to_value_with_context(
        &self,
        value: &Value,
        path: &JsonPath,
        context: &ValidationContext,
    ) -> Validation<Value, SchemaErrors> {
        self.validate_with_context(value, path, context)
    }

    fn collect_refs(&self, refs: &mut Vec<String>) {
        match self {
            CombinatorSchema::OneOf { validators, .. } => {
                for validator in validators {
                    validator.collect_refs(refs);
                }
            }
            CombinatorSchema::AnyOf { validators, .. } => {
                for validator in validators {
                    validator.collect_refs(refs);
                }
            }
            CombinatorSchema::AllOf { validators, .. } => {
                for validator in validators {
                    validator.collect_refs(refs);
                }
            }
            CombinatorSchema::Optional { validator, .. } => {
                validator.collect_refs(refs);
            }
        }
    }
}

impl ToJsonSchema for CombinatorSchema {
    fn to_json_schema(&self) -> Value {
        match self {
            CombinatorSchema::OneOf { validators, .. } => {
                json!({
                    "oneOf": validators.iter().map(|v| v.to_json_schema()).collect::<Vec<_>>()
                })
            }
            CombinatorSchema::AnyOf { validators, .. } => {
                json!({
                    "anyOf": validators.iter().map(|v| v.to_json_schema()).collect::<Vec<_>>()
                })
            }
            CombinatorSchema::AllOf { validators, .. } => {
                json!({
                    "allOf": validators.iter().map(|v| v.to_json_schema()).collect::<Vec<_>>()
                })
            }
            CombinatorSchema::Optional { validator, .. } => {
                json!({
                    "oneOf": [
                        json!({ "type": "null" }),
                        validator.to_json_schema()
                    ]
                })
            }
        }
    }
}