|
| 1 | +//! VESPERA-04 before/after A/B benchmark for the `422 Unprocessable |
| 2 | +//! Entity` validation-envelope serialization. |
| 3 | +//! |
| 4 | +//! Both implementations serialize the **same** [`garde::Report`] to the |
| 5 | +//! **same** bytes (`{"errors":[{"message":...,"path":...},...]}`): |
| 6 | +//! |
| 7 | +//! - `before`: the original implementation — collect every error into an |
| 8 | +//! owned `Vec<ValidationErrorOut>` (two `String` allocations per error) |
| 9 | +//! and then `serde_json::to_vec`. |
| 10 | +//! - `after`: the shipped implementation — a fully-borrowing custom |
| 11 | +//! `Serialize` chain over `&garde::Report` (zero per-error `String` |
| 12 | +//! allocation, `collect_str` straight into the serializer). |
| 13 | +//! |
| 14 | +//! The delta is the per-error allocation cost VESPERA-04 removes. Both |
| 15 | +//! arms assert byte-identical output so the bench can never silently |
| 16 | +//! drift from the real envelope contract. |
| 17 | +
|
| 18 | +use std::fmt::Display; |
| 19 | + |
| 20 | +use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; |
| 21 | +use garde::Validate; |
| 22 | +use serde::{Serialize, Serializer, ser::SerializeStruct}; |
| 23 | + |
| 24 | +// ── Fixture: a struct whose validation fails on every field ────────── |
| 25 | + |
| 26 | +#[derive(Validate)] |
| 27 | +struct Sample { |
| 28 | + #[garde(length(min = 3, max = 32))] |
| 29 | + username: String, |
| 30 | + #[garde(email)] |
| 31 | + email: String, |
| 32 | + #[garde(range(min = 18, max = 120))] |
| 33 | + age: u8, |
| 34 | + #[garde(length(min = 10))] |
| 35 | + bio: String, |
| 36 | + #[garde(url)] |
| 37 | + homepage: String, |
| 38 | +} |
| 39 | + |
| 40 | +/// Produce a [`garde::Report`] with `n` failing fields by validating a |
| 41 | +/// deliberately-invalid `Sample` and truncating the report's iteration |
| 42 | +/// in the benchmarked closures (we just validate the whole struct; it |
| 43 | +/// yields 5 errors — representative of a realistic multi-error 422). |
| 44 | +fn failing_report() -> garde::Report { |
| 45 | + let sample = Sample { |
| 46 | + username: "x".to_owned(), // too short |
| 47 | + email: "not-an-email".to_owned(), // invalid |
| 48 | + age: 200, // out of range |
| 49 | + bio: "short".to_owned(), // too short |
| 50 | + homepage: "nope".to_owned(), // invalid url |
| 51 | + }; |
| 52 | + sample.validate().expect_err("sample must fail validation") |
| 53 | +} |
| 54 | + |
| 55 | +// ── AFTER: shipped borrowing Serialize chain (mirror of validated.rs) ─ |
| 56 | + |
| 57 | +fn serialize_after(report: &garde::Report) -> Vec<u8> { |
| 58 | + struct DisplayValue<T>(T); |
| 59 | + impl<T: Display> Serialize for DisplayValue<T> { |
| 60 | + fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { |
| 61 | + s.collect_str(&self.0) |
| 62 | + } |
| 63 | + } |
| 64 | + struct Envelope<'a>(&'a garde::Report); |
| 65 | + impl Serialize for Envelope<'_> { |
| 66 | + fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { |
| 67 | + let mut env = s.serialize_struct("ValidationEnvelope", 1)?; |
| 68 | + env.serialize_field("errors", &Errors(self.0))?; |
| 69 | + env.end() |
| 70 | + } |
| 71 | + } |
| 72 | + struct Errors<'a>(&'a garde::Report); |
| 73 | + impl Serialize for Errors<'_> { |
| 74 | + fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { |
| 75 | + s.collect_seq(self.0.iter().map(|(path, err)| OneError { path, err })) |
| 76 | + } |
| 77 | + } |
| 78 | + struct OneError<'a> { |
| 79 | + path: &'a garde::Path, |
| 80 | + err: &'a garde::Error, |
| 81 | + } |
| 82 | + impl Serialize for OneError<'_> { |
| 83 | + fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { |
| 84 | + let mut e = s.serialize_struct("ValidationError", 2)?; |
| 85 | + e.serialize_field("message", &DisplayValue(self.err.message()))?; |
| 86 | + e.serialize_field("path", &DisplayValue(self.path))?; |
| 87 | + e.end() |
| 88 | + } |
| 89 | + } |
| 90 | + serde_json::to_vec(&Envelope(report)).expect("infallible") |
| 91 | +} |
| 92 | + |
| 93 | +// ── BEFORE: original owned-Vec<String> implementation ──────────────── |
| 94 | + |
| 95 | +fn serialize_before(report: &garde::Report) -> Vec<u8> { |
| 96 | + #[derive(Serialize)] |
| 97 | + struct ValidationErrorOut { |
| 98 | + message: String, |
| 99 | + path: String, |
| 100 | + } |
| 101 | + #[derive(Serialize)] |
| 102 | + struct Envelope { |
| 103 | + errors: Vec<ValidationErrorOut>, |
| 104 | + } |
| 105 | + let errors: Vec<ValidationErrorOut> = report |
| 106 | + .iter() |
| 107 | + .map(|(path, err)| ValidationErrorOut { |
| 108 | + message: err.message().to_string(), |
| 109 | + path: path.to_string(), |
| 110 | + }) |
| 111 | + .collect(); |
| 112 | + serde_json::to_vec(&Envelope { errors }).expect("infallible") |
| 113 | +} |
| 114 | + |
| 115 | +fn bench_validation_envelope(c: &mut Criterion) { |
| 116 | + let report = failing_report(); |
| 117 | + |
| 118 | + // Guard: the two implementations MUST produce identical bytes, so |
| 119 | + // the A/B compares the same observable work — never a shortcut. |
| 120 | + assert_eq!( |
| 121 | + serialize_before(&report), |
| 122 | + serialize_after(&report), |
| 123 | + "before/after 422 envelope bytes diverged" |
| 124 | + ); |
| 125 | + |
| 126 | + let n_errors = report.iter().count(); |
| 127 | + let mut group = c.benchmark_group("validation_envelope"); |
| 128 | + |
| 129 | + group.bench_with_input( |
| 130 | + BenchmarkId::new("owned_vec_string_before", n_errors), |
| 131 | + &report, |
| 132 | + |b, report| b.iter(|| serialize_before(std::hint::black_box(report))), |
| 133 | + ); |
| 134 | + group.bench_with_input( |
| 135 | + BenchmarkId::new("borrowing_serialize_after", n_errors), |
| 136 | + &report, |
| 137 | + |b, report| b.iter(|| serialize_after(std::hint::black_box(report))), |
| 138 | + ); |
| 139 | + |
| 140 | + group.finish(); |
| 141 | +} |
| 142 | + |
| 143 | +criterion_group!(benches, bench_validation_envelope); |
| 144 | +criterion_main!(benches); |
0 commit comments