Skip to main content

gadk_openapi/
spec.rs

1// Copyright 2026 Chris Olson
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! A loaded OpenAPI document ([`OpenApiSpec`]).
16
17use std::fmt;
18use std::marker::PhantomData;
19use std::path::Path;
20use std::str::FromStr;
21use std::time::Duration;
22
23use serde::Deserialize;
24use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
25use serde_json::Value;
26use url::Url;
27
28use crate::error::Error;
29
30/// How long [`OpenApiSpec::fetch`] waits for the whole download.
31const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
32/// The largest document [`OpenApiSpec::fetch`] accepts, in bytes (10 MiB).
33pub(crate) const FETCH_MAX_BYTES: usize = 10 * 1024 * 1024;
34
35/// An OpenAPI 3.0 or 3.1 document, parsed from JSON or YAML.
36///
37/// Build it with [`str::parse`] (through [`FromStr`]), [`from_file`](OpenApiSpec::from_file) or
38/// [`fetch`](OpenApiSpec::fetch), then turn it into tools with `OpenApiToolset::new`.
39#[derive(Debug, Clone)]
40pub struct OpenApiSpec {
41    doc: Value,
42    /// Each path with its keys, both in document order.
43    order: Vec<(String, Vec<String>)>,
44    source_url: Option<Url>,
45}
46
47impl FromStr for OpenApiSpec {
48    type Err = Error;
49
50    /// Parses `text` as JSON, or as YAML when it is not JSON, and checks the version.
51    fn from_str(text: &str) -> Result<Self, Error> {
52        Self::parse(text, None)
53    }
54}
55
56impl OpenApiSpec {
57    /// Reads the file at `path` and parses it as [`FromStr`] does. A read failure is
58    /// [`Error::Parse`] naming the path.
59    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, Error> {
60        let path = path.as_ref();
61        let text = std::fs::read_to_string(path).map_err(|err| Error::Parse {
62            message: format!("cannot read {}: {err}", path.display()),
63        })?;
64        text.parse()
65    }
66
67    /// Downloads the document at `url` (30 s timeout, at most 10 MiB) and parses it as
68    /// [`FromStr`] does. A non-2xx status, a transport failure or a larger body is
69    /// [`Error::Fetch`]. The URL is kept as the base for a relative server URL.
70    pub async fn fetch(url: &str) -> Result<Self, Error> {
71        let fetch_error = |message: String| Error::Fetch {
72            url: url.to_string(),
73            message,
74        };
75        let parsed = Url::parse(url).map_err(|err| fetch_error(format!("invalid URL: {err}")))?;
76        let client = reqwest::Client::builder()
77            .timeout(FETCH_TIMEOUT)
78            .build()
79            .map_err(|err| fetch_error(err.to_string()))?;
80        let mut response = client
81            .get(parsed)
82            .send()
83            .await
84            .map_err(|err| fetch_error(err.to_string()))?;
85        let status = response.status();
86        if !status.is_success() {
87            return Err(fetch_error(format!("HTTP status {status}")));
88        }
89        let final_url = response.url().clone();
90        let mut body = Vec::new();
91        while let Some(chunk) = response
92            .chunk()
93            .await
94            .map_err(|err| fetch_error(err.to_string()))?
95        {
96            if body.len() + chunk.len() > FETCH_MAX_BYTES {
97                return Err(fetch_error(format!(
98                    "the document is larger than {FETCH_MAX_BYTES} bytes"
99                )));
100            }
101            body.extend_from_slice(&chunk);
102        }
103        let text = String::from_utf8(body)
104            .map_err(|err| fetch_error(format!("the document is not UTF-8: {err}")))?;
105        Self::parse(&text, Some(final_url))
106    }
107
108    /// The whole document as JSON.
109    pub fn document(&self) -> &Value {
110        &self.doc
111    }
112
113    /// The document's `openapi` version string.
114    pub fn version(&self) -> &str {
115        self.doc
116            .get("openapi")
117            .and_then(Value::as_str)
118            .unwrap_or_default()
119    }
120
121    /// The URL the document was fetched from, for a document loaded by
122    /// [`fetch`](OpenApiSpec::fetch).
123    pub fn source_url(&self) -> Option<&str> {
124        self.source_url.as_ref().map(Url::as_str)
125    }
126
127    /// Parses `text` and records `source_url` as the document's origin.
128    pub(crate) fn parse(text: &str, source_url: Option<Url>) -> Result<Self, Error> {
129        let (doc, order) = match serde_json::from_str::<Value>(text) {
130            Ok(doc) => (doc, serde_json::from_str::<DocOrder>(text).ok()),
131            Err(json_err) => match serde_saphyr::from_str::<Value>(text) {
132                Ok(doc) => (doc, serde_saphyr::from_str::<DocOrder>(text).ok()),
133                Err(yaml_err) => {
134                    let message = if text.trim_start().starts_with(['{', '[']) {
135                        format!("invalid JSON: {json_err}")
136                    } else {
137                        format!("invalid YAML: {yaml_err}")
138                    };
139                    return Err(Error::Parse { message });
140                }
141            },
142        };
143        if !doc.is_object() {
144            return Err(Error::Parse {
145                message: "the document is not a JSON or YAML object".to_string(),
146            });
147        }
148        check_version(&doc)?;
149        let order = match order {
150            Some(order) => order
151                .paths
152                .0
153                .into_iter()
154                .map(|(path, item)| (path, item.0.into_iter().map(|(key, _)| key).collect()))
155                .collect(),
156            None => sorted_order(&doc),
157        };
158        Ok(Self {
159            doc,
160            order,
161            source_url,
162        })
163    }
164
165    /// Whether the document is OpenAPI 3.0 (whose `nullable` is rewritten into `type`).
166    pub(crate) fn is_3_0(&self) -> bool {
167        self.version().starts_with("3.0.")
168    }
169
170    /// Each path with its keys, both in document order.
171    pub(crate) fn path_order(&self) -> &[(String, Vec<String>)] {
172        &self.order
173    }
174
175    /// The URL the document was fetched from.
176    pub(crate) fn source(&self) -> Option<&Url> {
177        self.source_url.as_ref()
178    }
179}
180
181/// Accepts only a string `openapi` field starting with `3.0.` or `3.1.`.
182fn check_version(doc: &Value) -> Result<(), Error> {
183    let found = match doc.get("openapi") {
184        Some(Value::String(version))
185            if version.starts_with("3.0.") || version.starts_with("3.1.") =>
186        {
187            return Ok(());
188        }
189        Some(Value::String(version)) => version.clone(),
190        Some(other) => other.to_string(),
191        None => match doc.get("swagger") {
192            Some(Value::String(version)) => format!("swagger {version}"),
193            Some(other) => format!("swagger {other}"),
194            None => "no openapi field".to_string(),
195        },
196    };
197    Err(Error::UnsupportedVersion { found })
198}
199
200/// The path order when the document's paths cannot be read in order (a malformed path item):
201/// sorted key order, since `serde_json::Map` (built without `preserve_order`) keeps its keys
202/// sorted.
203fn sorted_order(doc: &Value) -> Vec<(String, Vec<String>)> {
204    let Some(paths) = doc.get("paths").and_then(Value::as_object) else {
205        return Vec::new();
206    };
207    paths
208        .iter()
209        .map(|(path, item)| {
210            let keys = item
211                .as_object()
212                .map(|item| item.keys().cloned().collect())
213                .unwrap_or_default();
214            (path.clone(), keys)
215        })
216        .collect()
217}
218
219/// The parts of the document whose key order matters: `paths` and each path item's keys.
220#[derive(Deserialize, Default)]
221struct DocOrder {
222    #[serde(default)]
223    paths: Keys<Keys<IgnoredAny>>,
224}
225
226/// A map's entries in document order.
227struct Keys<V>(Vec<(String, V)>);
228
229impl<V> Default for Keys<V> {
230    fn default() -> Self {
231        Self(Vec::new())
232    }
233}
234
235impl<'de, V: Deserialize<'de>> Deserialize<'de> for Keys<V> {
236    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
237        struct KeysVisitor<V>(PhantomData<V>);
238
239        impl<'de, V: Deserialize<'de>> Visitor<'de> for KeysVisitor<V> {
240            type Value = Keys<V>;
241
242            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243                f.write_str("a map")
244            }
245
246            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Keys<V>, A::Error> {
247                let mut entries = Vec::new();
248                while let Some(entry) = map.next_entry::<String, V>()? {
249                    entries.push(entry);
250                }
251                Ok(Keys(entries))
252            }
253        }
254
255        deserializer.deserialize_map(KeysVisitor(PhantomData))
256    }
257}
258
259#[cfg(test)]
260#[path = "spec_tests.rs"]
261pub(crate) mod tests;