Skip to main content

vld_openapi/
poem_openapi.rs

1//! poem-openapi 5: `vld` types as poem-openapi request bodies and schemas.
2//!
3//! - [`impl_type!`] implements poem-openapi's `Type` and `ParseFromJSON` for a
4//!   `vld::schema!` / `#[derive(Validate)]` type: its OpenAPI schema is the
5//!   vld `json_schema()` (a named component, nested `vld::nested!` types
6//!   included), and parsing validates with vld. `Json<User>` then works in
7//!   `#[oai]` operations; a failure is poem-openapi's own **400** with vld's
8//!   message.
9//! - [`VldJson<T>`] is a request payload for such a type that answers
10//!   **422** with every issue (`{"error": "Validation failed", "issues":
11//!   [{"path", "message", "code"}]}`, the body `vld_web` sends) instead of
12//!   one 400 text line. A wrong `Content-Type` stays poem-openapi's 415. As a
13//!   response, `VldJson<T>` serializes `T` (`T: serde::Serialize`).
14//! - [`json_schema_to_meta`] converts any vld JSON Schema to a `MetaSchemaRef`.
15//!
16//! The schema is converted to the OpenAPI 3.0 dialect
17//! ([`crate::validator::to_openapi3`]) first. Keywords poem-openapi's
18//! `MetaSchema` has no field for (`not`, `contains`, `propertyNames`, `x-*`,
19//! `additionalProperties: false`) are dropped from the document; validation
20//! still applies them.
21//!
22//! ```rust
23//! use poem_openapi::{OpenApi, payload::Json};
24//! use vld_openapi::poem_openapi::{VldJson, impl_type};
25//!
26//! vld::schema! {
27//!     #[derive(Debug, serde::Serialize)]
28//!     pub struct NewUser {
29//!         pub name: String => vld::string().min(2),
30//!         pub age: i64 => vld::number().int().min(18),
31//!     }
32//! }
33//! impl_type!(NewUser);
34//!
35//! struct Api;
36//!
37//! #[OpenApi]
38//! impl Api {
39//!     /// 422 with every issue on invalid input.
40//!     #[oai(path = "/users", method = "post")]
41//!     async fn create(&self, body: VldJson<NewUser>) -> Json<String> {
42//!         Json(body.0.name)
43//!     }
44//!
45//!     /// poem-openapi's 400 on invalid input.
46//!     #[oai(path = "/users/plain", method = "post")]
47//!     async fn create_plain(&self, body: Json<NewUser>) -> Json<i64> {
48//!         Json(body.0.age)
49//!     }
50//! }
51//!
52//! let service = poem_openapi::OpenApiService::new(Api, "Users", "1.0");
53//! assert!(service.spec().contains("\"minLength\": 2"));
54//! ```
55//!
56//! Guide: <https://s00d.github.io/vld/integrations/openapi/poem-openapi>
57
58pub use ::poem_openapi;
59
60use ::poem_openapi::ApiResponse;
61use ::poem_openapi::payload::{ParsePayload, Payload};
62use ::poem_openapi::registry::{
63    MetaMediaType, MetaResponse, MetaResponses, MetaSchema, MetaSchemaRef, Registry,
64};
65use ::poem_openapi::types::Type;
66use poem::{FromRequest, IntoResponse, Request, RequestBody, Response};
67use serde_json::{Map, Value, json};
68use std::collections::BTreeSet;
69use std::sync::Mutex;
70use vld::error::{IssueCode, VldError};
71use vld::schema::VldParse;
72
73/// Convert a vld JSON Schema to a poem-openapi schema (OpenAPI 3.0).
74///
75/// `{"$ref": "#/components/schemas/X"}` becomes a reference to `X`.
76/// Keywords `MetaSchema` cannot hold are dropped (see the [module docs](self)).
77pub fn json_schema_to_meta(value: &Value) -> MetaSchemaRef {
78    let mut value = value.clone();
79    crate::validator::to_openapi3(&mut value);
80    meta_ref(&value)
81}
82
83fn meta_ref(value: &Value) -> MetaSchemaRef {
84    let Value::Object(map) = value else {
85        return MetaSchemaRef::Inline(Box::new(MetaSchema::ANY));
86    };
87    if let Some(name) = map
88        .get("$ref")
89        .and_then(Value::as_str)
90        .and_then(|r| r.strip_prefix("#/components/schemas/"))
91    {
92        return MetaSchemaRef::Reference(name.to_string());
93    }
94    MetaSchemaRef::Inline(Box::new(meta_schema(map)))
95}
96
97fn meta_schema(map: &Map<String, Value>) -> MetaSchema {
98    let str_of = |k: &str| map.get(k).and_then(Value::as_str);
99    let f64_of = |k: &str| map.get(k).and_then(Value::as_f64);
100    let usize_of = |k: &str| map.get(k).and_then(Value::as_u64).map(|n| n as usize);
101    let bool_of = |k: &str| map.get(k).and_then(Value::as_bool);
102    let list = |k: &str| -> Vec<MetaSchemaRef> {
103        map.get(k)
104            .and_then(Value::as_array)
105            .map(|a| a.iter().map(meta_ref).collect())
106            .unwrap_or_default()
107    };
108    let ty = match map.get("type") {
109        Some(Value::String(t)) => intern(t),
110        // OpenAPI 3.0 has one `type`: a multi-type schema stays untyped.
111        _ => "",
112    };
113    MetaSchema {
114        ty,
115        format: str_of("format").map(intern),
116        title: str_of("title").map(str::to_owned),
117        description: str_of("description").map(intern),
118        default: map.get("default").cloned(),
119        required: map
120            .get("required")
121            .and_then(Value::as_array)
122            .map(|r| r.iter().filter_map(Value::as_str).map(intern).collect())
123            .unwrap_or_default(),
124        properties: map
125            .get("properties")
126            .and_then(Value::as_object)
127            .map(|p| p.iter().map(|(k, v)| (intern(k), meta_ref(v))).collect())
128            .unwrap_or_default(),
129        items: map.get("items").map(|i| Box::new(meta_ref(i))),
130        additional_properties: map
131            .get("additionalProperties")
132            .filter(|v| v.is_object())
133            .map(|v| Box::new(meta_ref(v))),
134        enum_items: match (map.get("enum"), map.get("const")) {
135            (Some(Value::Array(v)), _) => v.clone(),
136            (_, Some(c)) => vec![c.clone()],
137            _ => Vec::new(),
138        },
139        nullable: bool_of("nullable") == Some(true),
140        any_of: list("anyOf"),
141        one_of: list("oneOf"),
142        all_of: list("allOf"),
143        read_only: bool_of("readOnly") == Some(true),
144        write_only: bool_of("writeOnly") == Some(true),
145        deprecated: bool_of("deprecated") == Some(true),
146        example: map.get("example").cloned(),
147        multiple_of: f64_of("multipleOf"),
148        maximum: f64_of("maximum"),
149        exclusive_maximum: bool_of("exclusiveMaximum"),
150        minimum: f64_of("minimum"),
151        exclusive_minimum: bool_of("exclusiveMinimum"),
152        max_length: usize_of("maxLength"),
153        min_length: usize_of("minLength"),
154        pattern: str_of("pattern").map(str::to_owned),
155        max_items: usize_of("maxItems"),
156        min_items: usize_of("minItems"),
157        unique_items: bool_of("uniqueItems"),
158        max_properties: usize_of("maxProperties"),
159        min_properties: usize_of("minProperties"),
160        ..MetaSchema::ANY
161    }
162}
163
164/// `MetaSchema` holds `&'static str` names; each distinct text is leaked once.
165fn intern(s: &str) -> &'static str {
166    // ponytail: one global set; distinct names of the documented types only.
167    static POOL: Mutex<BTreeSet<&'static str>> = Mutex::new(BTreeSet::new());
168    let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
169    if let Some(s) = pool.get(s) {
170        return s;
171    }
172    let s: &'static str = Box::leak(s.to_owned().into_boxed_str());
173    pool.insert(s);
174    s
175}
176
177/// Register `T` under `name` and its nested components. Used by [`impl_type!`].
178#[doc(hidden)]
179pub fn __register<T>(
180    registry: &mut Registry,
181    name: &str,
182    schema: fn() -> Value,
183    nested: Vec<vld::openapi::NestedSchemaEntry>,
184) {
185    registry.create_schema::<T, _>(name.to_string(), |_| match json_schema_to_meta(&schema()) {
186        MetaSchemaRef::Inline(s) => *s,
187        r @ MetaSchemaRef::Reference(_) => MetaSchema {
188            all_of: vec![r],
189            ..MetaSchema::ANY
190        },
191    });
192    for (nested_name, schema) in nested {
193        if !registry.schemas.contains_key(nested_name) {
194            let MetaSchemaRef::Inline(s) = json_schema_to_meta(&schema()) else {
195                continue;
196            };
197            registry.schemas.insert(nested_name.to_string(), *s);
198        }
199    }
200}
201
202/// vld parse for [`impl_type!`]'s `ParseFromJSON`: a missing value is `null`.
203#[doc(hidden)]
204pub fn __parse<T: VldParse + Type>(value: Option<Value>) -> ::poem_openapi::types::ParseResult<T> {
205    T::vld_parse_value(&value.unwrap_or_default())
206        .map_err(::poem_openapi::types::ParseError::custom)
207}
208
209/// A JSON request body validated with vld: **422** with every issue on
210/// failure. See the [module docs](self).
211#[derive(Debug, Clone, PartialEq)]
212pub struct VldJson<T>(pub T);
213
214impl<T> std::ops::Deref for VldJson<T> {
215    type Target = T;
216    fn deref(&self) -> &T {
217        &self.0
218    }
219}
220
221impl<T: Type> Payload for VldJson<T> {
222    const CONTENT_TYPE: &'static str = "application/json; charset=utf-8";
223
224    fn check_content_type(content_type: &str) -> bool {
225        <::poem_openapi::payload::Json<T> as Payload>::check_content_type(content_type)
226    }
227
228    fn schema_ref() -> MetaSchemaRef {
229        T::schema_ref()
230    }
231
232    fn register(registry: &mut Registry) {
233        T::register(registry);
234    }
235}
236
237impl<T: Type + VldParse> ParsePayload for VldJson<T> {
238    const IS_REQUIRED: bool = true;
239
240    async fn from_request(request: &Request, body: &mut RequestBody) -> poem::Result<Self> {
241        let data = Vec::<u8>::from_request(request, body).await?;
242        let value: Value = serde_json::from_slice(&data).map_err(|e| {
243            validation_error(&VldError::single(
244                IssueCode::ParseError,
245                format!("Invalid JSON: {e}"),
246            ))
247        })?;
248        T::vld_parse_value(&value)
249            .map(Self)
250            .map_err(|e| validation_error(&e))
251    }
252}
253
254::poem_openapi::impl_apirequest_for_payload!(VldJson<T>, T: Type + VldParse);
255
256impl<T: serde::Serialize + Send> IntoResponse for VldJson<T> {
257    fn into_response(self) -> Response {
258        poem::web::Json(self.0).into_response()
259    }
260}
261
262impl<T: Type + serde::Serialize> ApiResponse for VldJson<T> {
263    fn meta() -> MetaResponses {
264        MetaResponses {
265            responses: vec![MetaResponse {
266                description: "",
267                status: Some(200),
268                status_range: None,
269                content: vec![MetaMediaType {
270                    content_type: Self::CONTENT_TYPE,
271                    schema: Self::schema_ref(),
272                }],
273                headers: vec![],
274            }],
275        }
276    }
277
278    fn register(registry: &mut Registry) {
279        T::register(registry);
280    }
281}
282
283/// The 422 response `VldJson` rejects with: `{"error": "Validation failed",
284/// "issues": [{"path": ".name", "message": "...", "code": "too_small"}]}`.
285pub fn validation_error(err: &VldError) -> poem::Error {
286    let issues: Vec<Value> = err
287        .issues
288        .iter()
289        .map(|i| json!({"path": i.path_string(), "message": i.message, "code": i.code.key()}))
290        .collect();
291    let body = json!({"error": "Validation failed", "issues": issues});
292    poem::Error::from_response(
293        Response::builder()
294            .status(poem::http::StatusCode::UNPROCESSABLE_ENTITY)
295            .content_type("application/json")
296            .body(body.to_string()),
297    )
298}
299
300/// Implement poem-openapi `Type` + `ParseFromJSON` for a vld type:
301/// `impl_type!(T)` or `impl_type!(T, "ComponentName")`. See the
302/// [module docs](self).
303#[doc(hidden)]
304#[macro_export]
305macro_rules! __poem_openapi_impl_type {
306    ($ty:ty) => {
307        $crate::__poem_openapi_impl_type!($ty, stringify!($ty));
308    };
309    ($ty:ty, $name:expr) => {
310        impl $crate::poem_openapi::poem_openapi::types::Type for $ty {
311            const IS_REQUIRED: bool = true;
312            type RawValueType = Self;
313            type RawElementValueType = Self;
314
315            fn name() -> ::std::borrow::Cow<'static, str> {
316                ::std::borrow::Cow::Borrowed($name)
317            }
318
319            fn schema_ref() -> $crate::poem_openapi::poem_openapi::registry::MetaSchemaRef {
320                $crate::poem_openapi::poem_openapi::registry::MetaSchemaRef::Reference(
321                    ::std::string::String::from($name),
322                )
323            }
324
325            fn register(registry: &mut $crate::poem_openapi::poem_openapi::registry::Registry) {
326                // Inherent `__vld_nested_schemas` (from `vld::schema!` / derive) wins
327                // over this trait fallback in `<T>::f()` path resolution.
328                #[allow(unused_imports)]
329                use $crate::__VldNestedSchemasFallback as _;
330                $crate::poem_openapi::__register::<Self>(
331                    registry,
332                    $name,
333                    <$ty>::json_schema,
334                    <$ty>::__vld_nested_schemas(),
335                );
336            }
337
338            fn as_raw_value(&self) -> ::std::option::Option<&Self> {
339                ::std::option::Option::Some(self)
340            }
341
342            fn raw_element_iter<'a>(
343                &'a self,
344            ) -> ::std::boxed::Box<dyn ::std::iter::Iterator<Item = &'a Self> + 'a> {
345                ::std::boxed::Box::new(::std::iter::once(self))
346            }
347        }
348
349        impl $crate::poem_openapi::poem_openapi::types::ParseFromJSON for $ty {
350            fn parse_from_json(
351                value: ::std::option::Option<$crate::poem_openapi::__Value>,
352            ) -> $crate::poem_openapi::poem_openapi::types::ParseResult<Self> {
353                $crate::poem_openapi::__parse(value)
354            }
355        }
356    };
357}
358#[doc(inline)]
359pub use crate::__poem_openapi_impl_type as impl_type;
360
361#[doc(hidden)]
362pub use serde_json::Value as __Value;
363
364/// [`impl_type!`], [`VldJson`], [`json_schema_to_meta`] and `vld::prelude`.
365pub mod prelude {
366    pub use super::{VldJson, impl_type, json_schema_to_meta};
367    pub use vld::prelude::*;
368}