Skip to main content

langfuse_client_base/models/
validation.rs

1#![allow(deprecated)]
2/*
3 * server
4 *
5 * ## Real-time data  The only real-time path to get tracing data is to ingest via OpenTelemetry (`POST /api/public/otel/v1/traces`) and retrieve via Observations API v2 (`GET /api/public/v2/observations`) and Metrics API v2 (`GET /api/public/v2/metrics`). Other public API write and read endpoints can delay data by about 10 minutes. Direct OpenTelemetry exporters must send the `x-langfuse-ingestion-version: 4` header; current Python and JS SDKs already do. See the [Public API docs](https://langfuse.com/docs/api-and-data-platform/features/public-api) and [real-time ingestion](https://langfuse.com/integrations/native/opentelemetry.md#real-time-ingestion).  ## Authentication  Authenticate with the API using [Basic Auth](https://en.wikipedia.org/wiki/Basic_access_authentication), get API keys in the project settings:  - username: Langfuse Public Key - password: Langfuse Secret Key  ## Exports  - OpenAPI spec: https://cloud.langfuse.com/generated/api/openapi.yml - Self-hosted deployments: interactive API reference at `/api/docs` and OpenAPI spec at `/api/openapi.yaml`
6 *
7 * The version of the OpenAPI document:
8 *
9 * Generated by: https://openapi-generator.tech
10 */
11
12//! Checks a model against the validation keywords of its schema.
13//!
14//! Every model implements [`Validate`]. Nothing in this crate calls it: validating a request before sending it, or a
15//! response after decoding it, is the caller's choice. `validate()` returns every value that breaks a rule, as
16//! [`ValidationErrors`], each with the path to it in wire names (`messages[2].content`, `metadata["key"]`): in the
17//! order of the fields, nested values depth-first, the entries of a map ordered by their rendered (escaped) key. A
18//! valid value allocates nothing.
19//!
20//! What is checked: `minLength` and `maxLength` (in characters), `pattern`, `minimum`, `maximum`, `exclusiveMinimum`,
21//! `exclusiveMaximum`, `multipleOf`, `minItems`, `maxItems`, `uniqueItems` (by equality), `minProperties` and
22//! `maxProperties` of maps, in every nested model, list, map and union variant. A `pattern` is matched with the
23//! [`regex`](https://docs.rs/regex) crate, whose classes such as `\d` and `\w` are Unicode-aware; a pattern that uses a
24//! construct the crate does not support or reads differently from ECMA-262 is not checked (the generator warns).
25
26use std::fmt;
27
28/// A model that can check itself against the validation keywords of its schema.
29///
30/// The generated models implement it. To implement it by hand, for a type of your own that holds generated models,
31/// implement [`validate_into`](Validate::validate_into): push a [`ValidationError`] for each value that breaks a rule,
32/// with `path` set to where the value is, and call `validate_into` on the values it holds with their [`Path`]:
33///
34/// ```ignore
35/// use my_client::models::validation::{Path, Rule, Validate, ValidationError};
36///
37/// struct Order {
38///     note: String,
39///     items: Vec<my_client::models::Item>,
40/// }
41///
42/// impl Validate for Order {
43///     fn validate_into(&self, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
44///         let length = self.note.chars().count() as u64;
45///         if length > 100 {
46///             let mut error = ValidationError::new(Rule::MaxLength(100), format!("length {length}"));
47///             error.path = path.field("note").to_string();
48///             errors.push(error);
49///         }
50///         self.items.validate_into(&path.field("items"), errors);
51///     }
52/// }
53/// ```
54///
55/// `validate()` then returns what `validate_into` pushed, from [`Path::root`].
56pub trait Validate {
57    /// Every value that breaks a validation keyword of the schema; `Ok(())` when none does.
58    fn validate(&self) -> Result<(), ValidationErrors> {
59        let mut errors = Vec::new();
60        self.validate_into(&Path::root(), &mut errors);
61        if errors.is_empty() {
62            Ok(())
63        } else {
64            Err(ValidationErrors(errors))
65        }
66    }
67
68    /// Pushes every value that breaks a keyword onto `errors`, with its path below `path`, and nothing when the value
69    /// is valid. `validate()` calls it with [`Path::root`]; a model calls it on the models it holds with their path.
70    fn validate_into(&self, path: &Path<'_>, errors: &mut Vec<ValidationError>);
71}
72
73/// Every value that breaks a validation keyword, in the order `validate()` found them; never empty.
74#[derive(Clone, Debug, PartialEq)]
75pub struct ValidationErrors(Vec<ValidationError>);
76
77impl ValidationErrors {
78    /// How many values break a keyword.
79    pub fn len(&self) -> usize {
80        self.0.len()
81    }
82
83    /// Always `false`: `validate()` returns `Ok(())` when nothing breaks a keyword.
84    pub fn is_empty(&self) -> bool {
85        self.0.is_empty()
86    }
87
88    /// The errors, in order.
89    pub fn iter(&self) -> std::slice::Iter<'_, ValidationError> {
90        self.0.iter()
91    }
92
93    /// The errors, as a `Vec`.
94    pub fn into_vec(self) -> Vec<ValidationError> {
95        self.0
96    }
97}
98
99impl IntoIterator for ValidationErrors {
100    type Item = ValidationError;
101    type IntoIter = std::vec::IntoIter<ValidationError>;
102
103    fn into_iter(self) -> Self::IntoIter {
104        self.0.into_iter()
105    }
106}
107
108impl<'a> IntoIterator for &'a ValidationErrors {
109    type Item = &'a ValidationError;
110    type IntoIter = std::slice::Iter<'a, ValidationError>;
111
112    fn into_iter(self) -> Self::IntoIter {
113        self.0.iter()
114    }
115}
116
117/// One line per error.
118impl fmt::Display for ValidationErrors {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        for (index, error) in self.0.iter().enumerate() {
121            if index > 0 {
122                f.write_str("\n")?;
123            }
124            write!(f, "{error}")?;
125        }
126        Ok(())
127    }
128}
129
130impl std::error::Error for ValidationErrors {}
131
132/// Where a value is, in wire names, built on the stack while `validate()` descends: `path.field("items").index(2)`.
133/// It is written out (`to_string()`, `messages[2].content`) only for an error.
134#[derive(Clone, Copy, Debug)]
135pub struct Path<'a> {
136    parent: Option<&'a Path<'a>>,
137    segment: Segment<'a>,
138}
139
140#[derive(Clone, Copy, Debug)]
141enum Segment<'a> {
142    Root,
143    Field(&'a str),
144    Index(usize),
145    Key(&'a str),
146}
147
148impl<'a> Path<'a> {
149    /// The value `validate()` was called on.
150    pub fn root() -> Path<'static> {
151        Path {
152            parent: None,
153            segment: Segment::Root,
154        }
155    }
156
157    /// The value of the field `name`.
158    pub fn field(&'a self, name: &'a str) -> Path<'a> {
159        Path {
160            parent: Some(self),
161            segment: Segment::Field(name),
162        }
163    }
164
165    /// The item at `index`.
166    pub fn index(&'a self, index: usize) -> Path<'a> {
167        Path {
168            parent: Some(self),
169            segment: Segment::Index(index),
170        }
171    }
172
173    /// The value under `key`.
174    pub fn key(&'a self, key: &'a str) -> Path<'a> {
175        Path {
176            parent: Some(self),
177            segment: Segment::Key(key),
178        }
179    }
180
181    fn write(&self, out: &mut String) {
182        if let Some(parent) = self.parent {
183            parent.write(out);
184        }
185        match self.segment {
186            Segment::Root => {}
187            Segment::Field(name) => {
188                if !out.is_empty() {
189                    out.push('.');
190                }
191                out.push_str(name);
192            }
193            Segment::Index(index) => out.push_str(&format!("[{index}]")),
194            Segment::Key(key) => out.push_str(&format!("[{key:?}]")),
195        }
196    }
197}
198
199impl fmt::Display for Path<'_> {
200    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201        let mut out = String::new();
202        self.write(&mut out);
203        f.write_str(&out)
204    }
205}
206
207/// Pushes the error of a check, if any, at `path`.
208fn push(result: Result<(), ValidationError>, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
209    if let Err(mut error) = result {
210        error.path = path.to_string();
211        errors.push(error);
212    }
213}
214
215/// Sorts the errors a map's entries pushed from `start` on by their rendered (escaped) key, as a map iterates in no
216/// fixed order.
217#[doc(hidden)]
218pub fn sort_by_key(errors: &mut [ValidationError], start: usize, path: &Path<'_>) {
219    if errors.len() <= start + 1 {
220        return;
221    }
222    let prefix = path.to_string().len();
223    errors[start..].sort_by(|a, b| key_of(&a.path, prefix).cmp(key_of(&b.path, prefix)));
224}
225
226/// The `["key"]` segment that follows the map's own path.
227fn key_of(path: &str, prefix: usize) -> &str {
228    let rest = path.get(prefix..).unwrap_or("");
229    let mut escaped = false;
230    for (at, c) in rest.char_indices().skip(2) {
231        match c {
232            '\\' if !escaped => escaped = true,
233            '"' if !escaped => return &rest[..at],
234            _ => escaped = false,
235        }
236    }
237    rest
238}
239
240/// A validation keyword of the schema, with the limit it sets. A number limit is an `f64`, so an integer limit
241/// beyond 2^53 shows rounded (the check itself compares integers exactly).
242#[derive(Clone, Debug, PartialEq)]
243#[non_exhaustive]
244pub enum Rule {
245    /// `minLength`: the least number of characters.
246    MinLength(u64),
247    /// `maxLength`: the greatest number of characters.
248    MaxLength(u64),
249    /// `pattern`: a regular expression the string must contain a match of.
250    Pattern(&'static str),
251    /// `minimum`
252    Minimum(f64),
253    /// `exclusiveMinimum`
254    ExclusiveMinimum(f64),
255    /// `maximum`
256    Maximum(f64),
257    /// `exclusiveMaximum`
258    ExclusiveMaximum(f64),
259    /// `multipleOf`
260    MultipleOf(f64),
261    /// `minItems`
262    MinItems(u64),
263    /// `maxItems`
264    MaxItems(u64),
265    /// `uniqueItems`: no two items are equal.
266    UniqueItems,
267    /// `minProperties` of a map.
268    MinProperties(u64),
269    /// `maxProperties` of a map.
270    MaxProperties(u64),
271}
272
273impl fmt::Display for Rule {
274    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275        match self {
276            Rule::MinLength(n) => write!(f, "minLength {n}"),
277            Rule::MaxLength(n) => write!(f, "maxLength {n}"),
278            Rule::Pattern(p) => write!(f, "pattern {p:?}"),
279            Rule::Minimum(n) => write!(f, "minimum {n}"),
280            Rule::ExclusiveMinimum(n) => write!(f, "exclusiveMinimum {n}"),
281            Rule::Maximum(n) => write!(f, "maximum {n}"),
282            Rule::ExclusiveMaximum(n) => write!(f, "exclusiveMaximum {n}"),
283            Rule::MultipleOf(n) => write!(f, "multipleOf {n}"),
284            Rule::MinItems(n) => write!(f, "minItems {n}"),
285            Rule::MaxItems(n) => write!(f, "maxItems {n}"),
286            Rule::UniqueItems => write!(f, "uniqueItems"),
287            Rule::MinProperties(n) => write!(f, "minProperties {n}"),
288            Rule::MaxProperties(n) => write!(f, "maxProperties {n}"),
289        }
290    }
291}
292
293/// A value that breaks a validation keyword of its schema.
294#[derive(Clone, Debug, PartialEq)]
295pub struct ValidationError {
296    /// Where the value is, in wire names: `messages[2].content`, `metadata["key"]`; empty for the value itself.
297    pub path: String,
298    /// The keyword it breaks.
299    pub rule: Rule,
300    /// What breaks it: the value (a number, or a string for `pattern`), its size (`length 0`, `3 items`,
301    /// `0 properties`), or the equal items for `uniqueItems`.
302    pub actual: String,
303}
304
305impl ValidationError {
306    /// An error with an empty path; set `path` to where the value is (`path.to_string()` in `validate_into`).
307    pub fn new(rule: Rule, actual: impl Into<String>) -> Self {
308        ValidationError {
309            path: String::new(),
310            rule,
311            actual: actual.into(),
312        }
313    }
314}
315
316impl fmt::Display for ValidationError {
317    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318        if self.path.is_empty() {
319            write!(f, "{} breaks {}", self.actual, self.rule)
320        } else {
321            write!(f, "{}: {} breaks {}", self.path, self.actual, self.rule)
322        }
323    }
324}
325
326impl std::error::Error for ValidationError {}
327
328impl<T: Validate + ?Sized> Validate for Box<T> {
329    fn validate_into(&self, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
330        (**self).validate_into(path, errors);
331    }
332}
333
334impl<T: Validate> Validate for Option<T> {
335    fn validate_into(&self, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
336        if let Some(value) = self {
337            value.validate_into(path, errors);
338        }
339    }
340}
341
342impl<T: Validate> Validate for Vec<T> {
343    fn validate_into(&self, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
344        for (index, item) in self.iter().enumerate() {
345            item.validate_into(&path.index(index), errors);
346        }
347    }
348}
349
350impl<T: Validate, S> Validate for std::collections::HashMap<String, T, S> {
351    fn validate_into(&self, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
352        let start = errors.len();
353        for (key, value) in self {
354            value.validate_into(&path.key(key), errors);
355        }
356        sort_by_key(errors, start, path);
357    }
358}
359
360/// A number type a bound can apply to.
361pub trait Number: Copy + PartialOrd + fmt::Display {
362    /// The value as `f64`, to report a limit.
363    fn as_f64(self) -> f64;
364    /// Whether the value is a multiple of `factor`; for floating point numbers, within a relative tolerance.
365    fn is_multiple(self, factor: Self) -> bool;
366}
367
368macro_rules! integer {
369    ($($t:ty),*) => {$(
370        impl Number for $t {
371            fn as_f64(self) -> f64 {
372                self as f64
373            }
374            fn is_multiple(self, factor: Self) -> bool {
375                self.checked_rem(factor).is_none_or(|rest| rest == 0)
376            }
377        }
378    )*};
379}
380
381integer!(i8, i16, i32, i64, u8, u16, u32, u64);
382
383macro_rules! float {
384    ($($t:ty => $tolerance:expr),*) => {$(
385        impl Number for $t {
386            fn as_f64(self) -> f64 {
387                f64::from(self)
388            }
389            fn is_multiple(self, factor: Self) -> bool {
390                let quotient = self / factor;
391                (quotient - quotient.round()).abs() <= $tolerance * quotient.abs().max(1.0)
392            }
393        }
394    )*};
395}
396
397float!(f32 => 1e-5, f64 => 1e-9);
398
399/// `minLength` and `maxLength`, in characters.
400fn check_length(value: &str, min: Option<u64>, max: Option<u64>) -> Result<(), ValidationError> {
401    let length = value.chars().count() as u64;
402    if let Some(min) = min.filter(|min| length < *min) {
403        return Err(ValidationError::new(
404            Rule::MinLength(min),
405            format!("length {length}"),
406        ));
407    }
408    if let Some(max) = max.filter(|max| length > *max) {
409        return Err(ValidationError::new(
410            Rule::MaxLength(max),
411            format!("length {length}"),
412        ));
413    }
414    Ok(())
415}
416
417/// `minimum`
418fn check_minimum<T: Number>(value: T, bound: T) -> Result<(), ValidationError> {
419    if value < bound {
420        return Err(ValidationError::new(
421            Rule::Minimum(bound.as_f64()),
422            value.to_string(),
423        ));
424    }
425    Ok(())
426}
427
428/// `exclusiveMinimum`
429fn check_exclusive_minimum<T: Number>(value: T, bound: T) -> Result<(), ValidationError> {
430    if value <= bound {
431        return Err(ValidationError::new(
432            Rule::ExclusiveMinimum(bound.as_f64()),
433            value.to_string(),
434        ));
435    }
436    Ok(())
437}
438
439/// `maximum`
440fn check_maximum<T: Number>(value: T, bound: T) -> Result<(), ValidationError> {
441    if value > bound {
442        return Err(ValidationError::new(
443            Rule::Maximum(bound.as_f64()),
444            value.to_string(),
445        ));
446    }
447    Ok(())
448}
449
450/// `exclusiveMaximum`
451fn check_exclusive_maximum<T: Number>(value: T, bound: T) -> Result<(), ValidationError> {
452    if value >= bound {
453        return Err(ValidationError::new(
454            Rule::ExclusiveMaximum(bound.as_f64()),
455            value.to_string(),
456        ));
457    }
458    Ok(())
459}
460
461/// `multipleOf`
462fn check_multiple_of<T: Number>(value: T, factor: T) -> Result<(), ValidationError> {
463    if !value.is_multiple(factor) {
464        return Err(ValidationError::new(
465            Rule::MultipleOf(factor.as_f64()),
466            value.to_string(),
467        ));
468    }
469    Ok(())
470}
471
472/// `minItems` and `maxItems`.
473fn check_items(count: usize, min: Option<u64>, max: Option<u64>) -> Result<(), ValidationError> {
474    let count = count as u64;
475    if let Some(min) = min.filter(|min| count < *min) {
476        return Err(ValidationError::new(
477            Rule::MinItems(min),
478            format!("{count} items"),
479        ));
480    }
481    if let Some(max) = max.filter(|max| count > *max) {
482        return Err(ValidationError::new(
483            Rule::MaxItems(max),
484            format!("{count} items"),
485        ));
486    }
487    Ok(())
488}
489
490/// `uniqueItems`: no two items are equal.
491fn check_unique_items<T: PartialEq>(items: &[T]) -> Result<(), ValidationError> {
492    for (index, item) in items.iter().enumerate() {
493        if let Some(first) = items[..index].iter().position(|earlier| earlier == item) {
494            return Err(ValidationError::new(
495                Rule::UniqueItems,
496                format!("items {first} and {index} are equal"),
497            ));
498        }
499    }
500    Ok(())
501}
502
503/// `minProperties` and `maxProperties` of a map.
504fn check_properties(
505    count: usize,
506    min: Option<u64>,
507    max: Option<u64>,
508) -> Result<(), ValidationError> {
509    let count = count as u64;
510    if let Some(min) = min.filter(|min| count < *min) {
511        return Err(ValidationError::new(
512            Rule::MinProperties(min),
513            format!("{count} properties"),
514        ));
515    }
516    if let Some(max) = max.filter(|max| count > *max) {
517        return Err(ValidationError::new(
518            Rule::MaxProperties(max),
519            format!("{count} properties"),
520        ));
521    }
522    Ok(())
523}
524
525#[doc(hidden)]
526pub fn length(
527    value: &str,
528    min: Option<u64>,
529    max: Option<u64>,
530    path: &Path<'_>,
531    errors: &mut Vec<ValidationError>,
532) {
533    push(check_length(value, min, max), path, errors);
534}
535
536#[doc(hidden)]
537pub fn minimum<T: Number>(value: T, bound: T, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
538    push(check_minimum(value, bound), path, errors);
539}
540
541#[doc(hidden)]
542pub fn exclusive_minimum<T: Number>(
543    value: T,
544    bound: T,
545    path: &Path<'_>,
546    errors: &mut Vec<ValidationError>,
547) {
548    push(check_exclusive_minimum(value, bound), path, errors);
549}
550
551#[doc(hidden)]
552pub fn maximum<T: Number>(value: T, bound: T, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
553    push(check_maximum(value, bound), path, errors);
554}
555
556#[doc(hidden)]
557pub fn exclusive_maximum<T: Number>(
558    value: T,
559    bound: T,
560    path: &Path<'_>,
561    errors: &mut Vec<ValidationError>,
562) {
563    push(check_exclusive_maximum(value, bound), path, errors);
564}
565
566#[doc(hidden)]
567pub fn multiple_of<T: Number>(
568    value: T,
569    factor: T,
570    path: &Path<'_>,
571    errors: &mut Vec<ValidationError>,
572) {
573    push(check_multiple_of(value, factor), path, errors);
574}
575
576#[doc(hidden)]
577pub fn items(
578    count: usize,
579    min: Option<u64>,
580    max: Option<u64>,
581    path: &Path<'_>,
582    errors: &mut Vec<ValidationError>,
583) {
584    push(check_items(count, min, max), path, errors);
585}
586
587#[doc(hidden)]
588pub fn unique_items<T: PartialEq>(items: &[T], path: &Path<'_>, errors: &mut Vec<ValidationError>) {
589    push(check_unique_items(items), path, errors);
590}
591
592#[doc(hidden)]
593pub fn properties(
594    count: usize,
595    min: Option<u64>,
596    max: Option<u64>,
597    path: &Path<'_>,
598    errors: &mut Vec<ValidationError>,
599) {
600    push(check_properties(count, min, max), path, errors);
601}