use std::sync::{Arc, Mutex};
use jsonschema::{Retrieve, Uri};
use serde_json::Value;
pub(super) struct Resolver {
refused: Arc<Mutex<Option<String>>>,
#[cfg(feature = "schema-remote-refs")]
http: jsonschema::HttpRetriever,
}
impl Resolver {
pub(super) fn new() -> (Self, Arc<Mutex<Option<String>>>) {
let refused = Arc::new(Mutex::new(None));
let resolver = Self {
refused: Arc::clone(&refused),
#[cfg(feature = "schema-remote-refs")]
http: jsonschema::HttpRetriever::new(
&jsonschema::HttpOptions::new().timeout(std::time::Duration::from_secs(15)),
)
.expect("an HTTP client with a timeout builds"),
};
(resolver, refused)
}
}
impl Retrieve for Resolver {
fn retrieve(
&self,
uri: &Uri<String>,
) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
match uri.scheme().as_str() {
"urn" => Ok(Value::Bool(true)),
#[cfg(feature = "schema-remote-refs")]
"http" | "https" => self.http.retrieve(uri),
#[cfg(feature = "schema-remote-refs")]
"file" => Ok(serde_json::from_slice(&std::fs::read(
uri.path().as_str(),
)?)?),
_ => {
*self.refused.lock().expect("lock is not poisoned") = Some(uri.to_string());
Err(format!(
"remote $ref {uri} is not resolved (enable the `schema-remote-refs` feature)"
)
.into())
}
}
}
}