use std::fmt;
use std::marker::PhantomData;
use std::path::Path;
use std::str::FromStr;
use std::time::Duration;
use serde::Deserialize;
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
use serde_json::Value;
use url::Url;
use crate::error::Error;
const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
pub(crate) const FETCH_MAX_BYTES: usize = 10 * 1024 * 1024;
#[derive(Debug, Clone)]
pub struct OpenApiSpec {
doc: Value,
order: Vec<(String, Vec<String>)>,
source_url: Option<Url>,
}
impl FromStr for OpenApiSpec {
type Err = Error;
fn from_str(text: &str) -> Result<Self, Error> {
Self::parse(text, None)
}
}
impl OpenApiSpec {
pub fn from_file(path: impl AsRef<Path>) -> Result<Self, Error> {
let path = path.as_ref();
let text = std::fs::read_to_string(path).map_err(|err| Error::Parse {
message: format!("cannot read {}: {err}", path.display()),
})?;
text.parse()
}
pub async fn fetch(url: &str) -> Result<Self, Error> {
let fetch_error = |message: String| Error::Fetch {
url: url.to_string(),
message,
};
let parsed = Url::parse(url).map_err(|err| fetch_error(format!("invalid URL: {err}")))?;
let client = reqwest::Client::builder()
.timeout(FETCH_TIMEOUT)
.build()
.map_err(|err| fetch_error(err.to_string()))?;
let mut response = client
.get(parsed)
.send()
.await
.map_err(|err| fetch_error(err.to_string()))?;
let status = response.status();
if !status.is_success() {
return Err(fetch_error(format!("HTTP status {status}")));
}
let final_url = response.url().clone();
let mut body = Vec::new();
while let Some(chunk) = response
.chunk()
.await
.map_err(|err| fetch_error(err.to_string()))?
{
if body.len() + chunk.len() > FETCH_MAX_BYTES {
return Err(fetch_error(format!(
"the document is larger than {FETCH_MAX_BYTES} bytes"
)));
}
body.extend_from_slice(&chunk);
}
let text = String::from_utf8(body)
.map_err(|err| fetch_error(format!("the document is not UTF-8: {err}")))?;
Self::parse(&text, Some(final_url))
}
pub fn document(&self) -> &Value {
&self.doc
}
pub fn version(&self) -> &str {
self.doc
.get("openapi")
.and_then(Value::as_str)
.unwrap_or_default()
}
pub fn source_url(&self) -> Option<&str> {
self.source_url.as_ref().map(Url::as_str)
}
pub(crate) fn parse(text: &str, source_url: Option<Url>) -> Result<Self, Error> {
let (doc, order) = match serde_json::from_str::<Value>(text) {
Ok(doc) => (doc, serde_json::from_str::<DocOrder>(text).ok()),
Err(json_err) => match serde_saphyr::from_str::<Value>(text) {
Ok(doc) => (doc, serde_saphyr::from_str::<DocOrder>(text).ok()),
Err(yaml_err) => {
let message = if text.trim_start().starts_with(['{', '[']) {
format!("invalid JSON: {json_err}")
} else {
format!("invalid YAML: {yaml_err}")
};
return Err(Error::Parse { message });
}
},
};
if !doc.is_object() {
return Err(Error::Parse {
message: "the document is not a JSON or YAML object".to_string(),
});
}
check_version(&doc)?;
let order = match order {
Some(order) => order
.paths
.0
.into_iter()
.map(|(path, item)| (path, item.0.into_iter().map(|(key, _)| key).collect()))
.collect(),
None => sorted_order(&doc),
};
Ok(Self {
doc,
order,
source_url,
})
}
pub(crate) fn is_3_0(&self) -> bool {
self.version().starts_with("3.0.")
}
pub(crate) fn path_order(&self) -> &[(String, Vec<String>)] {
&self.order
}
pub(crate) fn source(&self) -> Option<&Url> {
self.source_url.as_ref()
}
}
fn check_version(doc: &Value) -> Result<(), Error> {
let found = match doc.get("openapi") {
Some(Value::String(version))
if version.starts_with("3.0.") || version.starts_with("3.1.") =>
{
return Ok(());
}
Some(Value::String(version)) => version.clone(),
Some(other) => other.to_string(),
None => match doc.get("swagger") {
Some(Value::String(version)) => format!("swagger {version}"),
Some(other) => format!("swagger {other}"),
None => "no openapi field".to_string(),
},
};
Err(Error::UnsupportedVersion { found })
}
fn sorted_order(doc: &Value) -> Vec<(String, Vec<String>)> {
let Some(paths) = doc.get("paths").and_then(Value::as_object) else {
return Vec::new();
};
paths
.iter()
.map(|(path, item)| {
let keys = item
.as_object()
.map(|item| item.keys().cloned().collect())
.unwrap_or_default();
(path.clone(), keys)
})
.collect()
}
#[derive(Deserialize, Default)]
struct DocOrder {
#[serde(default)]
paths: Keys<Keys<IgnoredAny>>,
}
struct Keys<V>(Vec<(String, V)>);
impl<V> Default for Keys<V> {
fn default() -> Self {
Self(Vec::new())
}
}
impl<'de, V: Deserialize<'de>> Deserialize<'de> for Keys<V> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct KeysVisitor<V>(PhantomData<V>);
impl<'de, V: Deserialize<'de>> Visitor<'de> for KeysVisitor<V> {
type Value = Keys<V>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a map")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Keys<V>, A::Error> {
let mut entries = Vec::new();
while let Some(entry) = map.next_entry::<String, V>()? {
entries.push(entry);
}
Ok(Keys(entries))
}
}
deserializer.deserialize_map(KeysVisitor(PhantomData))
}
}
#[cfg(test)]
#[path = "spec_tests.rs"]
pub(crate) mod tests;