1use 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
30const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
32pub(crate) const FETCH_MAX_BYTES: usize = 10 * 1024 * 1024;
34
35#[derive(Debug, Clone)]
40pub struct OpenApiSpec {
41 doc: Value,
42 order: Vec<(String, Vec<String>)>,
44 source_url: Option<Url>,
45}
46
47impl FromStr for OpenApiSpec {
48 type Err = Error;
49
50 fn from_str(text: &str) -> Result<Self, Error> {
52 Self::parse(text, None)
53 }
54}
55
56impl OpenApiSpec {
57 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 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 pub fn document(&self) -> &Value {
110 &self.doc
111 }
112
113 pub fn version(&self) -> &str {
115 self.doc
116 .get("openapi")
117 .and_then(Value::as_str)
118 .unwrap_or_default()
119 }
120
121 pub fn source_url(&self) -> Option<&str> {
124 self.source_url.as_ref().map(Url::as_str)
125 }
126
127 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 pub(crate) fn is_3_0(&self) -> bool {
167 self.version().starts_with("3.0.")
168 }
169
170 pub(crate) fn path_order(&self) -> &[(String, Vec<String>)] {
172 &self.order
173 }
174
175 pub(crate) fn source(&self) -> Option<&Url> {
177 self.source_url.as_ref()
178 }
179}
180
181fn 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
200fn 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#[derive(Deserialize, Default)]
221struct DocOrder {
222 #[serde(default)]
223 paths: Keys<Keys<IgnoredAny>>,
224}
225
226struct 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;