Debian Codegraph @

src/retriever.rs

raw symbols SCIP
1 //! Logic for retrieving external resources.
2 use referencing::{Retrieve, Uri};
3 use serde_json::Value;
4
5 pub(crate) struct DefaultRetriever;
6
7 impl Retrieve for DefaultRetriever {
8 #[allow(unused)]
9 fn retrieve(
10 &self,
11 uri: &Uri<String>,
12 ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
13 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
14 {
15 Err("External references are not supported on wasm32-unknown-unknown".into())
16 }
17 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
18 match uri.scheme().as_str() {
19 "http" | "https" => {
20 #[cfg(all(feature = "resolve-http", not(target_arch = "wasm32")))]
21 {
22 Ok(reqwest::blocking::get(uri.as_str())?.json()?)
23 }
24 #[cfg(all(feature = "resolve-http", target_arch = "wasm32"))]
25 {
26 Err("Synchronous HTTP retrieval is not supported on wasm32 targets. Use async_validator_for with the resolve-async feature instead".into())
27 }
28 #[cfg(not(feature = "resolve-http"))]
29 {
30 Err("`resolve-http` feature or a custom resolver is required to resolve external schemas via HTTP".into())
31 }
32 }
33 "file" => {
34 #[cfg(feature = "resolve-file")]
35 {
36 let path = uri.path().as_str();
37 let path = {
38 #[cfg(windows)]
39 {
40 // Remove the leading slash and replace forward slashes with backslashes
41 let path = path.trim_start_matches('/').replace('/', "\\");
42 std::path::PathBuf::from(path)
43 }
44 #[cfg(not(windows))]
45 {
46 std::path::PathBuf::from(path)
47 }
48 };
49 let file = std::fs::File::open(path)?;
50 Ok(serde_json::from_reader(file)?)
51 }
52 #[cfg(not(feature = "resolve-file"))]
53 {
54 Err("`resolve-file` feature or a custom resolver is required to resolve external schemas via files".into())
55 }
56 }
57 scheme => Err(format!("Unknown scheme {scheme}").into()),
58 }
59 }
60 }
61
62 #[cfg(feature = "resolve-async")]
63 #[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
64 #[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
65 impl referencing::AsyncRetrieve for DefaultRetriever {
66 async fn retrieve(
67 &self,
68 uri: &Uri<String>,
69 ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
70 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
71 {
72 Err("External references are not supported on wasm32-unknown-unknown".into())
73 }
74 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
75 match uri.scheme().as_str() {
76 "http" | "https" => {
77 #[cfg(feature = "resolve-http")]
78 {
79 Ok(reqwest::get(uri.as_str()).await?.json().await?)
80 }
81 #[cfg(not(feature = "resolve-http"))]
82 Err("`resolve-http` feature or a custom resolver is required to resolve external schemas via HTTP".into())
83 }
84 "file" => {
85 #[cfg(feature = "resolve-file")]
86 {
87 // File operations are blocking, so we use tokio's spawn_blocking
88 let path = uri.path().as_str().to_string();
89 let contents = tokio::task::spawn_blocking(
90 move || -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
91 let path = {
92 #[cfg(windows)]
93 {
94 let path = path.trim_start_matches('/').replace('/', "\\");
95 std::path::PathBuf::from(path)
96 }
97 #[cfg(not(windows))]
98 {
99 std::path::PathBuf::from(path)
100 }
101 };
102 let file = std::fs::File::open(path)?;
103 Ok(serde_json::from_reader(file)?)
104 },
105 )
106 .await??;
107 Ok(contents)
108 }
109 #[cfg(not(feature = "resolve-file"))]
110 {
111 Err("`resolve-file` feature or a custom resolver is required to resolve external schemas via files".into())
112 }
113 }
114 scheme => Err(format!("Unknown scheme {scheme}").into()),
115 }
116 }
117 }
118
119 #[cfg(all(test, not(target_arch = "wasm32")))]
120 use percent_encoding::{AsciiSet, CONTROLS};
121
122 #[cfg(all(test, not(target_arch = "wasm32")))]
123 const URI_SEGMENT: &AsciiSet = &CONTROLS
124 .add(b' ')
125 .add(b'"')
126 .add(b'<')
127 .add(b'>')
128 .add(b'`')
129 .add(b'#')
130 .add(b'?')
131 .add(b'{')
132 .add(b'}')
133 .add(b'/')
134 .add(b'%');
135
136 #[cfg(all(test, not(target_arch = "wasm32"), not(target_os = "windows")))]
137 const UNIX_URI_SEGMENT: &AsciiSet = &URI_SEGMENT.add(b'\\');
138
139 #[cfg(all(test, not(target_arch = "wasm32")))]
140 pub(crate) fn path_to_uri(path: &std::path::Path) -> String {
141 use percent_encoding::percent_encode;
142
143 let mut result = "file://".to_owned();
144
145 #[cfg(not(target_os = "windows"))]
146 {
147 use std::os::unix::ffi::OsStrExt;
148
149 for component in path.components().skip(1) {
150 result.push('/');
151 result.extend(percent_encode(
152 component.as_os_str().as_bytes(),
153 UNIX_URI_SEGMENT,
154 ));
155 }
156 }
157 #[cfg(target_os = "windows")]
158 {
159 use std::path::{Component, Prefix};
160 let mut components = path.components();
161
162 match components.next() {
163 Some(Component::Prefix(ref p)) => match p.kind() {
164 Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => {
165 result.push('/');
166 result.push(letter as char);
167 result.push(':');
168 }
169 _ => panic!("Unexpected path"),
170 },
171 _ => panic!("Unexpected path"),
172 }
173
174 for component in components {
175 if component == Component::RootDir {
176 continue;
177 }
178
179 let component = component.as_os_str().to_str().expect("Unexpected path");
180
181 result.push('/');
182 result.extend(percent_encode(component.as_bytes(), URI_SEGMENT));
183 }
184 }
185 result
186 }
187
188 #[cfg(test)]
189 mod tests {
190 #[cfg(not(target_arch = "wasm32"))]
191 use super::path_to_uri;
192 use serde_json::json;
193 #[cfg(not(target_arch = "wasm32"))]
194 use std::io::Write;
195
196 #[test]
197 #[cfg(all(not(target_arch = "wasm32"), feature = "resolve-file"))]
198 fn test_retrieve_from_file() {
199 let mut temp_file = tempfile::NamedTempFile::new().expect("Failed to create temp file");
200 let external_schema = json!({
201 "type": "object",
202 "properties": {
203 "name": { "type": "string" }
204 },
205 "required": ["name"]
206 });
207 write!(temp_file, "{external_schema}").expect("Failed to write to temp file");
208
209 let uri = path_to_uri(temp_file.path());
210
211 let schema = json!({
212 "type": "object",
213 "properties": {
214 "user": { "$ref": uri }
215 }
216 });
217
218 let validator = crate::validator_for(&schema).expect("Schema compilation failed");
219
220 let valid = json!({"user": {"name": "John Doe"}});
221 assert!(validator.is_valid(&valid));
222
223 let invalid = json!({"user": {}});
224 assert!(!validator.is_valid(&invalid));
225 }
226
227 #[test]
228 fn test_unknown_scheme() {
229 let schema = json!({
230 "type": "object",
231 "properties": {
232 "test": { "$ref": "unknown-schema://test" }
233 }
234 });
235
236 let result = crate::validator_for(&schema);
237
238 assert!(result.is_err());
239 let error = result.unwrap_err().to_string();
240 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
241 assert!(error.contains("Unknown scheme"));
242 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
243 assert!(error.contains("External references are not supported on wasm32-unknown-unknown"));
244 }
245
246 #[cfg(not(target_arch = "wasm32"))]
247 fn create_temp_file(dir: &tempfile::TempDir, name: &str, content: &str) -> String {
248 let file_path = dir.path().join(name);
249 std::fs::write(&file_path, content).unwrap();
250 file_path.to_str().unwrap().to_string()
251 }
252
253 #[test]
254 #[cfg(all(not(target_arch = "wasm32"), feature = "resolve-file"))]
255 fn test_with_base_uri_resolution() {
256 let dir = tempfile::tempdir().unwrap();
257
258 let b_schema = r#"
259 {
260 "type": "object",
261 "properties": {
262 "age": { "type": "number" }
263 },
264 "required": ["age"]
265 }
266 "#;
267 let _b_path = create_temp_file(&dir, "b.json", b_schema);
268
269 let a_schema = r#"
270 {
271 "$schema": "https://json-schema.org/draft/2020-12/schema",
272 "$ref": "./b.json",
273 "type": "object"
274 }
275 "#;
276 let a_path = create_temp_file(&dir, "a.json", a_schema);
277
278 let valid_instance = serde_json::json!({ "age": 30 });
279
280 let schema_str = std::fs::read_to_string(&a_path).unwrap();
281 let schema_json: serde_json::Value = serde_json::from_str(&schema_str).unwrap();
282
283 let base_uri = path_to_uri(dir.path());
284 let validator = crate::options()
285 .with_base_uri(format!("{base_uri}/"))
286 .build(&schema_json)
287 .expect("Schema compilation failed");
288
289 assert!(validator.is_valid(&valid_instance));
290
291 let invalid_instance = serde_json::json!({ "age": "thirty" });
292 assert!(!validator.is_valid(&invalid_instance));
293 }
294 }
295
296 #[cfg(all(test, feature = "resolve-async", not(target_arch = "wasm32")))]
297 mod async_tests {
298 use super::*;
299 use crate::Registry;
300 use serde_json::json;
301 use std::io::Write;
302
303 #[tokio::test]
304 #[cfg(feature = "resolve-file")]
305 async fn test_async_retrieve_from_file() {
306 let mut temp_file = tempfile::NamedTempFile::new().expect("Failed to create temp file");
307 let external_schema = json!({
308 "type": "object",
309 "properties": {
310 "name": { "type": "string" }
311 },
312 "required": ["name"]
313 });
314 write!(temp_file, "{external_schema}").expect("Failed to write to temp file");
315
316 let uri = path_to_uri(temp_file.path());
317
318 let schema = json!({
319 "type": "object",
320 "properties": {
321 "user": { "$ref": uri }
322 }
323 });
324
325 // Create registry with default async retriever
326 let registry = Registry::options()
327 .async_retriever(DefaultRetriever)
328 .build([(
329 "http://example.com/schema",
330 crate::Draft::Draft202012.create_resource(schema.clone()),
331 )])
332 .await
333 .expect("Registry creation failed");
334
335 let validator = crate::options()
336 .with_registry(registry)
337 .build(&schema)
338 .expect("Invalid schema");
339
340 let valid = json!({"user": {"name": "John Doe"}});
341 assert!(validator.is_valid(&valid));
342
343 let invalid = json!({"user": {}});
344 assert!(!validator.is_valid(&invalid));
345 }
346
347 #[tokio::test]
348 async fn test_async_unknown_scheme() {
349 let schema = json!({
350 "type": "object",
351 "properties": {
352 "test": { "$ref": "unknown-schema://test" }
353 }
354 });
355
356 let result = Registry::options()
357 .async_retriever(DefaultRetriever)
358 .build([(
359 "http://example.com/schema",
360 crate::Draft::Draft202012.create_resource(schema),
361 )])
362 .await;
363
364 assert!(result.is_err());
365 let error = result.unwrap_err().to_string();
366 assert!(error.contains("Unknown scheme"));
367 }
368
369 #[tokio::test]
370 #[cfg(feature = "resolve-file")]
371 async fn test_async_concurrent_retrievals() {
372 let mut temp_files = vec![];
373 let mut uris = vec![];
374
375 // Create multiple temp files with different schemas
376 for i in 0..3 {
377 let mut temp_file = tempfile::NamedTempFile::new().expect("Failed to create temp file");
378 let schema = json!({
379 "type": "object",
380 "properties": {
381 "field": { "type": "string", "minLength": i }
382 }
383 });
384 write!(temp_file, "{schema}").expect("Failed to write to temp file");
385 uris.push(path_to_uri(temp_file.path()));
386 temp_files.push(temp_file);
387 }
388
389 // Create a schema that references all temp files
390 let schema = json!({
391 "type": "object",
392 "properties": {
393 "obj1": { "$ref": uris[0] },
394 "obj2": { "$ref": uris[1] },
395 "obj3": { "$ref": uris[2] }
396 }
397 });
398
399 let registry = Registry::options()
400 .async_retriever(DefaultRetriever)
401 .build([(
402 "http://example.com/schema",
403 crate::Draft::Draft202012.create_resource(schema.clone()),
404 )])
405 .await
406 .expect("Registry creation failed");
407
408 let validator = crate::options()
409 .with_registry(registry)
410 .build(&schema)
411 .expect("Invalid schema");
412
413 let valid = json!({
414 "obj1": { "field": "" }, // minLength: 0
415 "obj2": { "field": "a" }, // minLength: 1
416 "obj3": { "field": "ab" } // minLength: 2
417 });
418 assert!(validator.is_valid(&valid));
419
420 // Test invalid data
421 let invalid = json!({
422 "obj1": { "field": "" },
423 "obj2": { "field": "" }, // should be at least 1 char
424 "obj3": { "field": "a" } // should be at least 2 chars
425 });
426 assert!(!validator.is_valid(&invalid));
427 }
428 }