Skip to main content

navree_openapi/
lib.rs

1//! # navree-openapi
2//!
3//! The OpenAPI 3.1 document model and the [`ToSchema`] trait and derive that
4//! describe Rust types as JSON Schema (for the document, for AI tools and
5//! structured output, for MCP tools and for the automation editor).
6//!
7//! Items hidden from this documentation are not public API: Navree's own
8//! macros and crates use them, and they can change in any release.
9//!
10//! ```
11//! use navree_openapi::ToSchema;
12//! use serde_json::json;
13//!
14//! /// A note on a deal.
15//! #[derive(ToSchema)]
16//! #[schema(as = Note)]
17//! struct NoteResource {
18//!     /// The text.
19//!     body: String,
20//!     pinned: Option<bool>,
21//! }
22//!
23//! assert_eq!(NoteResource::name(), "Note");
24//! assert_eq!(
25//!     serde_json::to_value(NoteResource::schema()).unwrap(),
26//!     json!({
27//!         "type": "object",
28//!         "description": "A note on a deal.",
29//!         "required": ["body"],
30//!         "properties": {
31//!             "body": {"type": "string", "description": "The text."},
32//!             "pinned": {"type": ["boolean", "null"]},
33//!         },
34//!     })
35//! );
36//! ```
37#![forbid(unsafe_code)]
38#![cfg_attr(docsrs, feature(doc_cfg))]
39
40// The derive names this crate as `::navree_openapi`, in its own tests too.
41extern crate self as navree_openapi;
42
43mod component;
44mod document;
45mod schema;
46mod to_schema;
47
48pub use component::ComponentProperties;
49pub use document::{
50    Components, Document, Info, MediaType, Operation, Parameter, PathItem, RequestBody, Response,
51    SecurityScheme, Server, Tag,
52};
53#[doc(hidden)]
54pub use schema::RustType;
55pub use schema::{NotASchema, Schema, SchemaType, Subschema, Type};
56pub use to_schema::{Object, ToSchema, components_of};
57
58/// `#[derive(ToSchema)]`: see the macro's documentation in navree-macros.
59pub use navree_macros::ToSchema;
60
61/// What the derive's expansion names.
62#[doc(hidden)]
63pub mod __private {
64    use std::cell::RefCell;
65    use std::marker::PhantomData;
66
67    use serde::Serialize;
68    pub use serde_json;
69    use serde_json::{Map, Value};
70
71    use crate::Schema;
72
73    /// The member of a schema that carries the schemas it refers to.
74    pub const COMPONENTS: &str = "x-navree-components";
75    /// The member that says which Rust type each of those came from.
76    pub const COMPONENT_TYPES: &str = "x-navree-component-types";
77    /// The member listing different schemas that share a name:
78    /// `[name, first type, second type]`.
79    pub const COMPONENT_CONFLICTS: &str = "x-navree-component-conflicts";
80
81    /// Puts `referenced` (what [`ToSchema::schemas`](crate::ToSchema::schemas)
82    /// collected) in `schema`, for the document to read back. A different
83    /// schema of a name already there isn't lost: it is listed as a conflict.
84    pub fn attach_components(schema: &mut Value, referenced: Vec<(String, Schema)>) {
85        let Some(object) = schema.as_object_mut() else {
86            return;
87        };
88        if referenced.is_empty() {
89            return;
90        }
91        let mut components = Map::new();
92        let mut types = Map::new();
93        let mut conflicts = Vec::new();
94        let mut first_of: Vec<(String, Value, Option<&'static str>)> = Vec::new();
95        for (name, schema) in referenced {
96            let rust_type = schema.rust_type.0;
97            let value = schema.to_value();
98            match first_of.iter().find(|(first, _, _)| *first == name) {
99                Some((_, first, _)) if *first == value => {}
100                Some((_, _, first_type)) => {
101                    conflicts.push(serde_json::json!([name, first_type, rust_type]));
102                }
103                None => {
104                    if let Some(rust_type) = rust_type {
105                        types.insert(name.clone(), Value::from(rust_type));
106                    }
107                    components.insert(name.clone(), value.clone());
108                    first_of.push((name, value, rust_type));
109                }
110            }
111        }
112        object.insert(COMPONENTS.to_owned(), Value::Object(components));
113        if !types.is_empty() {
114            object.insert(COMPONENT_TYPES.to_owned(), Value::Object(types));
115        }
116        if !conflicts.is_empty() {
117            object.insert(COMPONENT_CONFLICTS.to_owned(), Value::Array(conflicts));
118        }
119    }
120
121    thread_local! {
122        static INLINING: RefCell<Vec<&'static str>> = const { RefCell::new(Vec::new()) };
123    }
124
125    /// Held while a type with `#[schema(inline)]` fields builds its schema, so
126    /// types that inline each other stop with a message.
127    pub struct InlineGuard;
128
129    impl InlineGuard {
130        /// Notes that `rust_type` is building its schema.
131        ///
132        /// # Panics
133        ///
134        /// When it is already: the schema would never end, and the document is
135        /// built at boot.
136        pub fn enter(rust_type: &'static str) -> InlineGuard {
137            INLINING.with(|inlining| {
138                let mut inlining = inlining.borrow_mut();
139                if inlining.contains(&rust_type) {
140                    let path = inlining.join(" -> ");
141                    inlining.clear();
142                    panic!(
143                        "#[schema(inline)] on a field of `{rust_type}` makes it contain itself ({path} -> {rust_type}): remove `inline` from one of the fields"
144                    );
145                }
146                inlining.push(rust_type);
147            });
148            InlineGuard
149        }
150    }
151
152    impl Drop for InlineGuard {
153        fn drop(&mut self) {
154            INLINING.with(|inlining| {
155                inlining.borrow_mut().pop();
156            });
157        }
158    }
159
160    /// `T::default()` when `T` has one: `(&DefaultOf::<T>::new()).get()`, with
161    /// both traits in scope, picks [`HasDefault`] if it applies.
162    pub struct DefaultOf<T>(PhantomData<T>);
163
164    impl<T> DefaultOf<T> {
165        #[allow(clippy::new_without_default)]
166        pub fn new() -> Self {
167            DefaultOf(PhantomData)
168        }
169    }
170
171    pub trait HasDefault<T> {
172        fn get(&self) -> Option<T>;
173    }
174
175    impl<T: Default> HasDefault<T> for DefaultOf<T> {
176        fn get(&self) -> Option<T> {
177            Some(T::default())
178        }
179    }
180
181    pub trait NoDefault<T> {
182        fn get(&self) -> Option<T> {
183            None
184        }
185    }
186
187    impl<T> NoDefault<T> for &DefaultOf<T> {}
188
189    /// `value` as JSON when it is `Serialize`:
190    /// `(&JsonOf(&value)).get()`, with both traits in scope.
191    pub struct JsonOf<'a, T: ?Sized>(pub &'a T);
192
193    pub trait HasJson {
194        fn get(&self) -> Option<Value>;
195    }
196
197    impl<T: Serialize + ?Sized> HasJson for JsonOf<'_, T> {
198        fn get(&self) -> Option<Value> {
199            Some(serde_json::to_value(self.0).unwrap_or_default())
200        }
201    }
202
203    pub trait NoJson {
204        fn get(&self) -> Option<Value> {
205            None
206        }
207    }
208
209    impl<T: ?Sized> NoJson for &JsonOf<'_, T> {}
210}