Skip to main content

navree_openapi/
to_schema.rs

1//! [`ToSchema`] and its implementations for the types of the standard library,
2//! navree-datetime, uuid and serde_json.
3
4use std::borrow::{Cow, ToOwned};
5use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
6use std::rc::Rc;
7use std::sync::Arc;
8
9use navree_datetime::{Date, DateTime, Time, Timestamp, Zoned};
10use serde_json::{Value, json};
11use uuid::Uuid;
12
13use crate::{Schema, Type};
14
15/// A type described by a JSON Schema: `#[derive(ToSchema)]`, or by hand.
16///
17/// The derive reads the type's serde attributes, so the schema matches the JSON
18/// serde reads and writes, and `#[schema(..)]` for what serde doesn't say.
19/// Written by hand, [`schema`](ToSchema::schema) is the only method a type
20/// needs:
21///
22/// ```
23/// use navree_openapi::{Schema, ToSchema};
24///
25/// struct Zone(String);
26///
27/// impl ToSchema for Zone {
28///     fn schema() -> Schema {
29///         Schema::string().description("An IANA time zone name.")
30///     }
31/// }
32///
33/// assert_eq!(Zone::name(), "Zone");
34/// ```
35pub trait ToSchema {
36    /// The name of the type's component schema: the last segment of its Rust
37    /// path unless `#[schema(as = Name)]` says otherwise, followed by the names
38    /// of its generic arguments (`Page<Note>` is `Page_Note`).
39    fn name() -> Cow<'static, str> {
40        let name = std::any::type_name::<Self>();
41        let name = name.split('<').next().unwrap_or(name);
42        Cow::Borrowed(name.rsplit("::").next().unwrap_or(name))
43    }
44
45    /// The type's schema.
46    fn schema() -> Schema;
47
48    /// What a field or an element of this type says: a `$ref` to the component,
49    /// or for a type with no component of its own (`String`, `Vec<T>`) its
50    /// schema.
51    fn reference() -> Schema {
52        Schema::reference_to(&Self::name())
53    }
54
55    /// Adds the component schemas [`schema`](ToSchema::schema) refers to.
56    fn schemas(out: &mut Vec<(String, Schema)>) {
57        let _ = out;
58    }
59
60    /// Adds the component schemas [`reference`](ToSchema::reference) refers to:
61    /// this type's and what it refers to. A type already in `out` isn't walked
62    /// again, so a type that contains itself ends. Another type of the same name
63    /// is walked as well, even with the same schema, since what its `$ref`s mean
64    /// may differ: a different schema of one name goes in beside the first, for
65    /// the document to refuse.
66    fn components(out: &mut Vec<(String, Schema)>) {
67        let name = Self::name();
68        let rust_type = std::any::type_name::<Self>();
69        let schema = Schema {
70            rust_type: crate::schema::RustType(Some(rust_type)),
71            ..Self::schema()
72        };
73        let walked = out
74            .iter()
75            .any(|(existing, other)| *existing == name && other.rust_type.0 == Some(rust_type));
76        if walked {
77            let same = out
78                .iter()
79                .any(|(existing, other)| *existing == name && *other == schema);
80            if !same {
81                out.push((name.into_owned(), schema));
82            }
83            return;
84        }
85        out.push((name.into_owned(), schema));
86        Self::schemas(out);
87    }
88}
89
90/// The component schemas `T` refers to, one for each name: what a schema that
91/// stands alone puts under `$defs`.
92///
93/// # Panics
94///
95/// When two different schemas have one name, since a `$ref` could only mean one
96/// of them and a tool's caller or a model would be told the wrong shape. The
97/// message names both types; `#[schema(as = Name)]` renames one.
98///
99/// ```
100/// use navree_openapi::{ToSchema, components_of};
101///
102/// #[derive(ToSchema)]
103/// #[allow(dead_code)]
104/// struct Stage {
105///     name: String,
106/// }
107///
108/// #[derive(ToSchema)]
109/// #[allow(dead_code)]
110/// struct Deal {
111///     stage: Stage,
112/// }
113///
114/// assert!(components_of::<Deal>().contains_key("Stage"));
115/// ```
116pub fn components_of<T: ToSchema + ?Sized>() -> BTreeMap<String, Schema> {
117    let mut referenced = Vec::new();
118    T::schemas(&mut referenced);
119    let mut components: BTreeMap<String, Schema> = BTreeMap::new();
120    for (name, schema) in referenced {
121        match components.get(&name) {
122            Some(first) if *first == schema => {}
123            Some(first) => panic!(
124                "`{name}` names two different schemas under `{}`: `{}` and `{}`; give one of them another name with #[schema(as = Name)]",
125                std::any::type_name::<T>(),
126                first.rust_type.0.unwrap_or("a schema written by hand"),
127                schema.rust_type.0.unwrap_or("a schema written by hand"),
128            ),
129            None => {
130                components.insert(name, schema);
131            }
132        }
133    }
134    components
135}
136
137/// `#[schema(value_type = Object)]`: `{"type": "object"}`, whatever the field's
138/// Rust type is.
139#[derive(Clone, Copy, Debug)]
140pub struct Object;
141
142/// A type with no component: fields inline its schema.
143macro_rules! inline_schema {
144    ($(impl[$($generics:tt)*] $ty:ty => $schema:expr;)+) => {$(
145        impl<$($generics)*> ToSchema for $ty {
146            fn schema() -> Schema {
147                $schema
148            }
149
150            fn reference() -> Schema {
151                Self::schema()
152            }
153
154            fn components(_out: &mut Vec<(String, Schema)>) {}
155        }
156    )+};
157}
158
159fn integer(format: Option<&str>, unsigned: bool) -> Schema {
160    Schema {
161        format: format.map(str::to_owned),
162        minimum: unsigned.then(|| json!(0)),
163        ..Schema::of_type(Type::Integer)
164    }
165}
166
167fn number(format: &str) -> Schema {
168    Schema {
169        format: Some(format.to_owned()),
170        ..Schema::of_type(Type::Number)
171    }
172}
173
174fn formatted(format: &str) -> Schema {
175    Schema {
176        format: Some(format.to_owned()),
177        ..Schema::string()
178    }
179}
180
181inline_schema! {
182    impl[] String => Schema::string();
183    impl[] str => Schema::string();
184    impl[] char => Schema::string();
185    impl[] bool => Schema::of_type(Type::Boolean);
186    impl[] i8 => integer(Some("int32"), false);
187    impl[] i16 => integer(Some("int32"), false);
188    impl[] i32 => integer(Some("int32"), false);
189    impl[] i64 => integer(Some("int64"), false);
190    impl[] i128 => integer(None, false);
191    impl[] isize => integer(None, false);
192    impl[] u8 => integer(Some("int32"), true);
193    impl[] u16 => integer(Some("int32"), true);
194    impl[] u32 => integer(Some("int32"), true);
195    impl[] u64 => integer(Some("int64"), true);
196    impl[] u128 => integer(None, true);
197    impl[] usize => integer(None, true);
198    impl[] f32 => number("float");
199    impl[] f64 => number("double");
200    impl[] Uuid => formatted("uuid");
201    impl[] Timestamp => formatted("date-time");
202    impl[] Zoned => formatted("date-time");
203    impl[] DateTime => formatted("date-time");
204    impl[] Date => formatted("date");
205    impl[] Time => Schema::string();
206    impl[] Value => Schema::default();
207    impl[] serde_json::Map<String, Value> => Schema::map(Schema::string(), Schema::default());
208    impl[] Object => Schema::object();
209}
210
211impl ToSchema for () {
212    fn name() -> Cow<'static, str> {
213        Cow::Borrowed("TupleUnit")
214    }
215
216    fn schema() -> Schema {
217        Schema::default().default_value(Value::Null)
218    }
219
220    fn reference() -> Schema {
221        Self::schema()
222    }
223
224    fn components(_out: &mut Vec<(String, Schema)>) {}
225}
226
227/// A wrapper that serializes as `T`: its schema and what it refers to are `T`'s.
228macro_rules! transparent {
229    ($(impl[$($generics:tt)*] $ty:ty => $inner:ty;)+) => {$(
230        impl<$($generics)*> ToSchema for $ty {
231            fn name() -> Cow<'static, str> {
232                <$inner>::name()
233            }
234
235            fn schema() -> Schema {
236                <$inner>::schema()
237            }
238
239            fn reference() -> Schema {
240                <$inner>::reference()
241            }
242
243            fn schemas(out: &mut Vec<(String, Schema)>) {
244                <$inner>::schemas(out);
245            }
246
247            fn components(out: &mut Vec<(String, Schema)>) {
248                <$inner>::components(out);
249            }
250        }
251    )+};
252}
253
254transparent! {
255    impl[T: ToSchema + ?Sized] Box<T> => T;
256    impl[T: ToSchema + ?Sized] Rc<T> => T;
257    impl[T: ToSchema + ?Sized] Arc<T> => T;
258    impl['a, T: ToSchema + ToOwned + ?Sized] Cow<'a, T> => T;
259}
260
261/// A reference is the referent's.
262macro_rules! reference {
263    ($(impl[$($generics:tt)*] $ty:ty;)+) => {$(
264        impl<$($generics)*> ToSchema for $ty {
265            fn name() -> Cow<'static, str> {
266                T::name()
267            }
268
269            fn schema() -> Schema {
270                T::schema()
271            }
272
273            fn reference() -> Schema {
274                T::reference()
275            }
276
277            fn schemas(out: &mut Vec<(String, Schema)>) {
278                T::schemas(out);
279            }
280
281            fn components(out: &mut Vec<(String, Schema)>) {
282                T::components(out);
283            }
284        }
285    )+};
286}
287
288reference! {
289    impl['a, T: ToSchema + ?Sized] &'a T;
290    impl['a, T: ToSchema + ?Sized] &'a mut T;
291}
292
293/// `Option<T>` on its own is `{"oneOf": [{"type": "null"}, T's schema]}`; as a
294/// field it's what `T` says, nullable.
295impl<T: ToSchema> ToSchema for Option<T> {
296    fn name() -> Cow<'static, str> {
297        Cow::Owned(format!("Option_{}", T::name()))
298    }
299
300    fn schema() -> Schema {
301        Schema::one_of(vec![Schema::null(), T::schema()])
302    }
303
304    fn reference() -> Schema {
305        T::reference().nullable()
306    }
307
308    fn schemas(out: &mut Vec<(String, Schema)>) {
309        T::schemas(out);
310    }
311
312    fn components(out: &mut Vec<(String, Schema)>) {
313        T::components(out);
314    }
315}
316
317/// A list: `{"type": "array", "items": ..}`, with `T`'s schema on its own and
318/// what `T` says as a field.
319macro_rules! list {
320    ($(impl[$($generics:tt)*] $ty:ty => $unique:expr;)+) => {$(
321        impl<$($generics)*> ToSchema for $ty {
322            fn name() -> Cow<'static, str> {
323                let list = if ($unique as Option<bool>).is_some() { "Set" } else { "Vec" };
324                Cow::Owned(format!("{list}_{}", T::name()))
325            }
326
327            fn schema() -> Schema {
328                Schema {
329                    unique_items: $unique,
330                    ..Schema::array(T::schema())
331                }
332            }
333
334            fn reference() -> Schema {
335                Schema {
336                    unique_items: $unique,
337                    ..Schema::array(T::reference())
338                }
339            }
340
341            fn schemas(out: &mut Vec<(String, Schema)>) {
342                T::schemas(out);
343            }
344
345            fn components(out: &mut Vec<(String, Schema)>) {
346                T::components(out);
347            }
348        }
349    )+};
350}
351
352list! {
353    impl[T: ToSchema] Vec<T> => None;
354    impl[T: ToSchema] [T] => None;
355    impl[T: ToSchema, const N: usize] [T; N] => None;
356    impl[T: ToSchema] std::collections::LinkedList<T> => None;
357    impl[T: ToSchema] std::collections::VecDeque<T> => None;
358    impl[T: ToSchema, S] HashSet<T, S> => Some(true);
359    impl[T: ToSchema] BTreeSet<T> => Some(true);
360}
361
362/// A map: `{"type": "object", "additionalProperties": .., "propertyNames": ..}`,
363/// with `V`'s schema on its own and what `V` says as a field.
364macro_rules! map {
365    ($(impl[$($generics:tt)*] $ty:ty;)+) => {$(
366        impl<$($generics)*> ToSchema for $ty {
367            fn name() -> Cow<'static, str> {
368                Cow::Owned(format!("Map_{}_{}", K::name(), V::name()))
369            }
370
371            fn schema() -> Schema {
372                Schema::map(K::schema(), V::schema())
373            }
374
375            fn reference() -> Schema {
376                Schema::map(K::reference(), V::reference())
377            }
378
379            fn schemas(out: &mut Vec<(String, Schema)>) {
380                K::schemas(out);
381                V::schemas(out);
382            }
383
384            fn components(out: &mut Vec<(String, Schema)>) {
385                K::components(out);
386                V::components(out);
387            }
388        }
389    )+};
390}
391
392map! {
393    impl[K: ToSchema, V: ToSchema] BTreeMap<K, V>;
394    impl[K: ToSchema, V: ToSchema, S] HashMap<K, V, S>;
395    impl[K: ToSchema, V: ToSchema, S] indexmap::IndexMap<K, V, S>;
396}
397
398#[cfg(test)]
399mod tests {
400    use serde_json::json;
401
402    use super::*;
403
404    struct Deal;
405
406    impl ToSchema for Deal {
407        fn schema() -> Schema {
408            Schema::object()
409        }
410    }
411
412    fn value<T: ToSchema + ?Sized>() -> Value {
413        T::reference().to_value()
414    }
415
416    #[test]
417    fn primitives_are_inline() {
418        assert_eq!(value::<String>(), json!({"type": "string"}));
419        assert_eq!(value::<&'static str>(), json!({"type": "string"}));
420        assert_eq!(value::<Cow<'static, str>>(), json!({"type": "string"}));
421        assert_eq!(
422            value::<u64>(),
423            json!({"type": "integer", "format": "int64", "minimum": 0})
424        );
425        assert_eq!(
426            value::<i32>(),
427            json!({"type": "integer", "format": "int32"})
428        );
429        assert_eq!(value::<usize>(), json!({"type": "integer", "minimum": 0}));
430        assert_eq!(
431            value::<f64>(),
432            json!({"type": "number", "format": "double"})
433        );
434        assert_eq!(value::<Uuid>(), json!({"type": "string", "format": "uuid"}));
435        assert_eq!(
436            value::<Timestamp>(),
437            json!({"type": "string", "format": "date-time"})
438        );
439        assert_eq!(
440            value::<Zoned>(),
441            json!({"type": "string", "format": "date-time"})
442        );
443        assert_eq!(
444            value::<DateTime>(),
445            json!({"type": "string", "format": "date-time"})
446        );
447        assert_eq!(value::<Date>(), json!({"type": "string", "format": "date"}));
448        assert_eq!(value::<Time>(), json!({"type": "string"}));
449        assert_eq!(value::<Value>(), json!({}));
450    }
451
452    #[test]
453    fn options_are_nullable() {
454        assert_eq!(
455            value::<Option<bool>>(),
456            json!({"type": ["boolean", "null"]})
457        );
458        assert_eq!(
459            value::<Option<Option<String>>>(),
460            json!({"type": ["string", "null"]})
461        );
462        assert_eq!(
463            value::<Option<Deal>>(),
464            json!({"oneOf": [{"$ref": "#/components/schemas/Deal"}, {"type": "null"}]})
465        );
466        assert_eq!(value::<Option<Value>>(), json!({}));
467    }
468
469    #[test]
470    fn lists_and_maps_compose() {
471        assert_eq!(
472            value::<Vec<Deal>>(),
473            json!({"type": "array", "items": {"$ref": "#/components/schemas/Deal"}})
474        );
475        assert_eq!(
476            value::<BTreeSet<String>>(),
477            json!({"type": "array", "items": {"type": "string"}, "uniqueItems": true})
478        );
479        assert_eq!(
480            value::<BTreeMap<String, Deal>>(),
481            json!({
482                "type": "object",
483                "additionalProperties": {"$ref": "#/components/schemas/Deal"},
484                "propertyNames": {"type": "string"},
485            })
486        );
487    }
488
489    #[test]
490    fn components_reach_through_wrappers_and_stop_at_primitives() {
491        let mut out = Vec::new();
492        <Option<Vec<BTreeMap<String, Box<Deal>>>>>::components(&mut out);
493        assert_eq!(out.len(), 1);
494        assert_eq!(out[0].0, "Deal");
495        let mut out = Vec::new();
496        <Vec<String>>::components(&mut out);
497        assert!(out.is_empty());
498    }
499
500    #[test]
501    fn a_type_containing_itself_ends() {
502        struct Tree;
503        impl ToSchema for Tree {
504            fn schema() -> Schema {
505                Schema::object().property("children", <Vec<Tree>>::reference(), true)
506            }
507            fn schemas(out: &mut Vec<(String, Schema)>) {
508                <Vec<Tree>>::components(out);
509            }
510        }
511        let mut out = Vec::new();
512        Tree::components(&mut out);
513        assert_eq!(out.len(), 1);
514    }
515}