Debian Codegraph @

src/retriever.rs

raw symbols SCIP
1 //! Logic for retrieving external resources.
2 use referencingrust-analyzer cargo referencing 0.37.4 crate/::{Retrieverust-analyzer cargo referencing 0.37.4 retriever/Retrieve#, Urirust-analyzer cargo fluent-uri 0.4.1 imp/Uri#};
3 use serde_jsonrust-analyzer cargo serde_json 1.0.145 crate/::Valuerust-analyzer cargo serde_json 1.0.145 value/Value#;
4
5 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) struct DefaultRetrieverrust-analyzer cargo jsonschema 0.37.4 retriever/DefaultRetriever#;
6
7 impl Retrieverust-analyzer cargo referencing 0.37.4 retriever/Retrieve# for DefaultRetrieverrust-analyzer cargo jsonschema 0.37.4 retriever/DefaultRetriever# {
8 #[allow(unused)]
9 fn retrieverust-analyzer cargo jsonschema 0.37.4 retriever/impl#[DefaultRetriever][Retrieve]retrieve().(
10 &self,
11 uri: &Urirust-analyzer cargo fluent-uri 0.4.1 imp/Uri#<Stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/String#>,
12 ) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Valuerust-analyzer cargo serde_json 1.0.145 value/Value#, Boxrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc boxed/Box#<dyn stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::errorrust-analyzer cargo std https://github.com/rust-lang/rust/library/std error/::Errorrust-analyzer cargo core https://github.com/rust-lang/rust/library/core error/Error# + Sendrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Send# + Syncrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Sync#>> {
13 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
14 {
15 Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#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.schemerust-analyzer cargo fluent-uri 0.4.1 imp/impl#[`Uri<T>`]scheme().().as_strrust-analyzer cargo fluent-uri 0.4.1 component/impl#[Scheme]as_str().() {
19 "http" | "https" => {
20 #[cfg(all(feature = "resolve-http", not(target_arch = "wasm32")))]
21 {
22 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(reqwestrust-analyzer cargo reqwest 0.12.24 crate/::blockingrust-analyzer cargo reqwest 0.12.24 blocking/::getrust-analyzer cargo reqwest 0.12.24 blocking/get().(uri.as_strrust-analyzer cargo fluent-uri 0.4.1 imp/impl#[`Uri<T>`]as_str().())?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch()..jsonrust-analyzer cargo reqwest 0.12.24 blocking/response/impl#[Response]json().()?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().)
23 }
24 #[cfg(all(feature = "resolve-http", target_arch = "wasm32"))]
25 {
26 Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#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 Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#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.pathrust-analyzer cargo fluent-uri 0.4.1 imp/impl#[`Uri<T>`]path().().as_strrust-analyzer cargo fluent-uri 0.4.1 pct_enc/impl#[`EStr<E>`]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 stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::pathrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/::PathBufrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/PathBuf#::from(path)
43 }
44 #[cfg(not(windows))]
45 {
46 stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::pathrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/::PathBufrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/PathBuf#::fromrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/impl#[PathBuf][`From<&T>`]from().(path)
47 }
48 };
49 let file = stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::fsrust-analyzer cargo std https://github.com/rust-lang/rust/library/std fs/::Filerust-analyzer cargo std https://github.com/rust-lang/rust/library/std fs/File#::openrust-analyzer cargo std https://github.com/rust-lang/rust/library/std fs/impl#[File]open().(path)?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().;
50 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(serde_jsonrust-analyzer cargo serde_json 1.0.145 crate/::from_readerrust-analyzer cargo serde_json 1.0.145 de/from_reader().(file)?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().)
51 }
52 #[cfg(not(feature = "resolve-file"))]
53 {
54 Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#("`resolve-file` feature or a custom resolver is required to resolve external schemas via files".into())
55 }
56 }
57 scheme => Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(formatrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc macros/format!!("Unknown scheme {scheme}").intorust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/impl#[T][`Into<U>`]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 referencingrust-analyzer cargo referencing 0.37.4 crate/::AsyncRetrieverust-analyzer cargo referencing 0.37.4 retriever/AsyncRetrieve# for DefaultRetrieverrust-analyzer cargo jsonschema 0.37.4 retriever/DefaultRetriever# {
66 async fn retrieverust-analyzer cargo jsonschema 0.37.4 retriever/impl#[DefaultRetriever][AsyncRetrieve]retrieve().(
67 &self,
68 uri: &Urirust-analyzer cargo fluent-uri 0.4.1 imp/Uri#<Stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/String#>,
69 ) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Valuerust-analyzer cargo serde_json 1.0.145 value/Value#, Boxrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc boxed/Box#<dyn stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::errorrust-analyzer cargo std https://github.com/rust-lang/rust/library/std error/::Errorrust-analyzer cargo core https://github.com/rust-lang/rust/library/core error/Error# + Sendrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Send# + Syncrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Sync#>> {
70 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
71 {
72 Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#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.schemerust-analyzer cargo fluent-uri 0.4.1 imp/impl#[`Uri<T>`]scheme().().as_strrust-analyzer cargo fluent-uri 0.4.1 component/impl#[Scheme]as_str().() {
76 "http" | "https" => {
77 #[cfg(feature = "resolve-http")]
78 {
79 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(reqwestrust-analyzer cargo reqwest 0.12.24 crate/::getrust-analyzer cargo reqwest 0.12.24 get().(uri.as_strrust-analyzer cargo fluent-uri 0.4.1 imp/impl#[`Uri<T>`]as_str().()).rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch()..jsonrust-analyzer cargo reqwest 0.12.24 async_impl/response/impl#[Response]json().().rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().)
80 }
81 #[cfg(not(feature = "resolve-http"))]
82 Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#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.pathrust-analyzer cargo fluent-uri 0.4.1 imp/impl#[`Uri<T>`]path().().as_strrust-analyzer cargo fluent-uri 0.4.1 pct_enc/impl#[`EStr<E>`]as_str().().to_stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[T][ToString]to_string().();
89 let contents = tokiorust-analyzer cargo tokio 1.48.0 crate/::taskrust-analyzer cargo tokio 1.48.0 task/::spawn_blockingrust-analyzer cargo tokio 1.48.0 task/blocking/spawn_blocking().(
90 move || -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Valuerust-analyzer cargo serde_json 1.0.145 value/Value#, Boxrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc boxed/Box#<dyn stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::errorrust-analyzer cargo std https://github.com/rust-lang/rust/library/std error/::Errorrust-analyzer cargo core https://github.com/rust-lang/rust/library/core error/Error# + Sendrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Send# + Syncrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Sync#>> {
91 let path = {
92 #[cfg(windows)]
93 {
94 let path = path.trim_start_matches('/').replace('/', "\\");
95 stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::pathrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/::PathBufrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/PathBuf#::from(path)
96 }
97 #[cfg(not(windows))]
98 {
99 stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::pathrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/::PathBufrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/PathBuf#::fromrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/impl#[PathBuf][`From<String>`]from().(path)
100 }
101 };
102 let file = stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::fsrust-analyzer cargo std https://github.com/rust-lang/rust/library/std fs/::Filerust-analyzer cargo std https://github.com/rust-lang/rust/library/std fs/File#::openrust-analyzer cargo std https://github.com/rust-lang/rust/library/std fs/impl#[File]open().(path)?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().;
103 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(serde_jsonrust-analyzer cargo serde_json 1.0.145 crate/::from_readerrust-analyzer cargo serde_json 1.0.145 de/from_reader().(file)?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().)
104 },
105 )
106 .rust-analyzer cargo tokio 1.48.0 runtime/task/join/impl#[`JoinHandle<T>`][Future]poll().awaitrust-analyzer cargo tokio 1.48.0 runtime/task/join/impl#[`JoinHandle<T>`][Future]poll().?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().;
107 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(contents)
108 }
109 #[cfg(not(feature = "resolve-file"))]
110 {
111 Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#("`resolve-file` feature or a custom resolver is required to resolve external schemas via files".into())
112 }
113 }
114 scheme => Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(formatrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc macros/format!!("Unknown scheme {scheme}").intorust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/impl#[T][`Into<U>`]into().()),
115 }
116 }
117 }
118
119 #[cfg(all(test, not(target_arch = "wasm32")))]
120 use percent_encodingrust-analyzer cargo percent-encoding 2.3.2 crate/::{AsciiSetrust-analyzer cargo percent-encoding 2.3.2 ascii_set/AsciiSet#, CONTROLSrust-analyzer cargo percent-encoding 2.3.2 ascii_set/CONTROLS.};
121
122 #[cfg(all(test, not(target_arch = "wasm32")))]
123 const URI_SEGMENTrust-analyzer cargo jsonschema 0.37.4 retriever/URI_SEGMENT.: &AsciiSetrust-analyzer cargo percent-encoding 2.3.2 ascii_set/AsciiSet# = &CONTROLSrust-analyzer cargo percent-encoding 2.3.2 ascii_set/CONTROLS.
124 .addrust-analyzer cargo percent-encoding 2.3.2 ascii_set/impl#[AsciiSet]add().(b' ')
125 .addrust-analyzer cargo percent-encoding 2.3.2 ascii_set/impl#[AsciiSet]add().(b'"')
126 .addrust-analyzer cargo percent-encoding 2.3.2 ascii_set/impl#[AsciiSet]add().(b'<')
127 .addrust-analyzer cargo percent-encoding 2.3.2 ascii_set/impl#[AsciiSet]add().(b'>')
128 .addrust-analyzer cargo percent-encoding 2.3.2 ascii_set/impl#[AsciiSet]add().(b'`')
129 .addrust-analyzer cargo percent-encoding 2.3.2 ascii_set/impl#[AsciiSet]add().(b'#')
130 .addrust-analyzer cargo percent-encoding 2.3.2 ascii_set/impl#[AsciiSet]add().(b'?')
131 .addrust-analyzer cargo percent-encoding 2.3.2 ascii_set/impl#[AsciiSet]add().(b'{')
132 .addrust-analyzer cargo percent-encoding 2.3.2 ascii_set/impl#[AsciiSet]add().(b'}')
133 .addrust-analyzer cargo percent-encoding 2.3.2 ascii_set/impl#[AsciiSet]add().(b'/')
134 .addrust-analyzer cargo percent-encoding 2.3.2 ascii_set/impl#[AsciiSet]add().(b'%');
135
136 #[cfg(all(test, not(target_arch = "wasm32"), not(target_os = "windows")))]
137 const UNIX_URI_SEGMENTrust-analyzer cargo jsonschema 0.37.4 retriever/UNIX_URI_SEGMENT.: &AsciiSetrust-analyzer cargo percent-encoding 2.3.2 ascii_set/AsciiSet# = &URI_SEGMENTrust-analyzer cargo jsonschema 0.37.4 retriever/URI_SEGMENT..addrust-analyzer cargo percent-encoding 2.3.2 ascii_set/impl#[AsciiSet]add().(b'\\');
138
139 #[cfg(all(test, not(target_arch = "wasm32")))]
140 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) fn path_to_urirust-analyzer cargo jsonschema 0.37.4 retriever/path_to_uri().(path: &stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::pathrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/::Pathrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/Path#) -> Stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/String# {
141 use percent_encodingrust-analyzer cargo percent-encoding 2.3.2 crate/::percent_encoderust-analyzer cargo percent-encoding 2.3.2 percent_encode().;
142
143 let mut result = "file://".to_ownedrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc str/impl#[str][ToOwned]to_owned().();
144
145 #[cfg(not(target_os = "windows"))]
146 {
147 use stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::osrust-analyzer cargo std https://github.com/rust-lang/rust/library/std os/::unixrust-analyzer cargo std https://github.com/rust-lang/rust/library/std os/unix/::ffirust-analyzer cargo std https://github.com/rust-lang/rust/library/std os/unix/ffi/::OsStrExtrust-analyzer cargo std https://github.com/rust-lang/rust/library/std os/unix/ffi/os_str/OsStrExt#;
148
149 for component in path.componentsrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/impl#[Path]components().().skiprust-analyzer cargo core https://github.com/rust-lang/rust/library/core iter/traits/iterator/Iterator#skip().(1) {
150 result.pushrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[String]push().('/');
151 result.extendrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[String][`Extend<&'a str>`]extend().(percent_encoderust-analyzer cargo percent-encoding 2.3.2 percent_encode().(
152 component.as_os_strrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/impl#[`Component<'a>`]as_os_str().().as_bytesrust-analyzer cargo std https://github.com/rust-lang/rust/library/std os/unix/ffi/os_str/impl#[OsStr][OsStrExt]as_bytes().(),
153 UNIX_URI_SEGMENTrust-analyzer cargo jsonschema 0.37.4 retriever/UNIX_URI_SEGMENT.,
154 ));
155 }
156 }
157 #[cfg(target_os = "windows")]
158 {
159 use stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::pathrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/::{Componentrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/Component#, Prefixrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/Prefix#};
160 let mut components = path.components();
161
162 match components.next() {
163 Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#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 _ => panicrust-analyzer cargo std https://github.com/rust-lang/rust/library/std macros/panic!!("Unexpected path"),
170 },
171 _ => panicrust-analyzer cargo std https://github.com/rust-lang/rust/library/std macros/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_encoderust-analyzer cargo percent-encoding 2.3.2 percent_encode().(component.as_bytes(), URI_SEGMENTrust-analyzer cargo jsonschema 0.37.4 retriever/URI_SEGMENT.));
183 }
184 }
185 result
186 }
187
188 #[cfg(test)]
189 mod testsrust-analyzer cargo jsonschema 0.37.4 retriever/tests/ {
190 #[cfg(not(target_arch = "wasm32"))]
191 use superrust-analyzer cargo jsonschema 0.37.4 retriever/::path_to_urirust-analyzer cargo jsonschema 0.37.4 retriever/path_to_uri().;
192 use serde_jsonrust-analyzer cargo serde_json 1.0.145 crate/::jsonrust-analyzer cargo serde_json 1.0.145 macros/json!;
193 #[cfg(not(target_arch = "wasm32"))]
194 use stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::iorust-analyzer cargo std https://github.com/rust-lang/rust/library/std io/::Writerust-analyzer cargo std https://github.com/rust-lang/rust/library/std io/Write#;
195
196 #[testrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/test:]
197 #[cfg(all(not(target_arch = "wasm32"), feature = "resolve-file"))]
198 fn test_retrieve_from_filerust-analyzer cargo jsonschema 0.37.4 retriever/tests/test_retrieve_from_file().() {
199 let mut temp_file = tempfilerust-analyzer cargo tempfile 3.23.0 crate/::NamedTempFilerust-analyzer cargo tempfile 3.23.0 file/NamedTempFile#::newrust-analyzer cargo tempfile 3.23.0 file/impl#[NamedTempFile]new().().expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Failed to create temp file");
200 let external_schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({
201 "type": "object",
202 "properties": {
203 "name": { "type": "string" }
204 },
205 "required": ["name"]
206 });
207 writerust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/write!!(temp_file, "{external_schema}").expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Failed to write to temp file");
208
209 let uri = path_to_urirust-analyzer cargo jsonschema 0.37.4 retriever/path_to_uri().(temp_file.pathrust-analyzer cargo tempfile 3.23.0 file/impl#[`NamedTempFile<F>`]path().());
210
211 let schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({
212 "type": "object",
213 "properties": {
214 "user": { "$ref": uri }
215 }
216 });
217
218 let validator = craterust-analyzer cargo jsonschema 0.37.4 crate/::validator_forrust-analyzer cargo jsonschema 0.37.4 validator_for().(&schema).expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Schema compilation failed");
219
220 let valid = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({"user": {"name": "John Doe"}});
221 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&valid));
222
223 let invalid = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({"user": {}});
224 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(!rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&invalid));
225 }
226
227 #[testrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/test:]
228 fn test_unknown_schemerust-analyzer cargo jsonschema 0.37.4 retriever/tests/test_unknown_scheme().() {
229 let schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({
230 "type": "object",
231 "properties": {
232 "test": { "$ref": "unknown-schema://test" }
233 }
234 });
235
236 let result = craterust-analyzer cargo jsonschema 0.37.4 crate/::validator_forrust-analyzer cargo jsonschema 0.37.4 validator_for().(&schema);
237
238 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(result.is_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]is_err().());
239 let error = result.unwrap_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap_err().().to_stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[T][ToString]to_string().();
240 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
241 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(error.containsrust-analyzer cargo core https://github.com/rust-lang/rust/library/core str/impl#[str]contains().("Unknown scheme"));
242 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
243 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(error.contains("External references are not supported on wasm32-unknown-unknown"));
244 }
245
246 #[cfg(not(target_arch = "wasm32"))]
247 fn create_temp_filerust-analyzer cargo jsonschema 0.37.4 retriever/tests/create_temp_file().(dir: &tempfilerust-analyzer cargo tempfile 3.23.0 crate/::TempDirrust-analyzer cargo tempfile 3.23.0 dir/TempDir#, name: &str, content: &str) -> Stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/String# {
248 let file_path = dir.pathrust-analyzer cargo tempfile 3.23.0 dir/impl#[TempDir]path().().joinrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/impl#[Path]join().(name);
249 stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::fsrust-analyzer cargo std https://github.com/rust-lang/rust/library/std fs/::writerust-analyzer cargo std https://github.com/rust-lang/rust/library/std fs/write().(&file_path, content).unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().();
250 file_path.to_strrust-analyzer cargo std https://github.com/rust-lang/rust/library/std path/impl#[Path]to_str().().unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]unwrap().().to_stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[T][ToString]to_string().()
251 }
252
253 #[testrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/test:]
254 #[cfg(all(not(target_arch = "wasm32"), feature = "resolve-file"))]
255 fn test_with_base_uri_resolutionrust-analyzer cargo jsonschema 0.37.4 retriever/tests/test_with_base_uri_resolution().() {
256 let dir = tempfilerust-analyzer cargo tempfile 3.23.0 crate/::tempdirrust-analyzer cargo tempfile 3.23.0 dir/tempdir().().unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]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_filerust-analyzer cargo jsonschema 0.37.4 retriever/tests/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_filerust-analyzer cargo jsonschema 0.37.4 retriever/tests/create_temp_file().(&dir, "a.json", a_schema);
277
278 let valid_instance = serde_jsonrust-analyzer cargo serde_json 1.0.145 crate/::jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({ "age": 30 });
279
280 let schema_str = stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::fsrust-analyzer cargo std https://github.com/rust-lang/rust/library/std fs/::read_to_stringrust-analyzer cargo std https://github.com/rust-lang/rust/library/std fs/read_to_string().(&a_path).unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().();
281 let schema_json: serde_jsonrust-analyzer cargo serde_json 1.0.145 crate/::Valuerust-analyzer cargo serde_json 1.0.145 value/Value# = serde_jsonrust-analyzer cargo serde_json 1.0.145 crate/::from_strrust-analyzer cargo serde_json 1.0.145 de/from_str().(&schema_str).unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().();
282
283 let base_uri = path_to_urirust-analyzer cargo jsonschema 0.37.4 retriever/path_to_uri().(dir.pathrust-analyzer cargo tempfile 3.23.0 dir/impl#[TempDir]path().());
284 let validator = craterust-analyzer cargo jsonschema 0.37.4 crate/::optionsrust-analyzer cargo jsonschema 0.37.4 options().()
285 .with_base_urirust-analyzer cargo jsonschema 0.37.4 options/impl#[`ValidationOptions<R>`]with_base_uri().(formatrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc macros/format!!("{base_uri}/"))
286 .buildrust-analyzer cargo jsonschema 0.37.4 options/impl#[ValidationOptions]build().(&schema_json)
287 .expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Schema compilation failed");
288
289 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&valid_instance));
290
291 let invalid_instance = serde_jsonrust-analyzer cargo serde_json 1.0.145 crate/::jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({ "age": "thirty" });
292 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(!rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&invalid_instance));
293 }
294 }
295
296 #[cfg(all(test, feature = "resolve-async", not(target_arch = "wasm32")))]
297 mod async_testsrust-analyzer cargo jsonschema 0.37.4 retriever/async_tests/ {
298 use superrust-analyzer cargo jsonschema 0.37.4 retriever/::*;
299 use craterust-analyzer cargo jsonschema 0.37.4 crate/::Registryrust-analyzer cargo referencing 0.37.4 registry/Registry#;
300 use serde_jsonrust-analyzer cargo serde_json 1.0.145 crate/::jsonrust-analyzer cargo serde_json 1.0.145 macros/json!;
301 use stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::iorust-analyzer cargo std https://github.com/rust-lang/rust/library/std io/::Writerust-analyzer cargo std https://github.com/rust-lang/rust/library/std io/Write#;
302
303 #[tokiorust-analyzer cargo tokio 1.48.0 crate/::testrust-analyzer cargo tokio-macros 2.6.0 test_rt:]
304 #[cfg(feature = "resolve-file")]
305 async fn test_async_retrieve_from_filerust-analyzer cargo jsonschema 0.37.4 retriever/async_tests/test_async_retrieve_from_file().() {
306 let mut temp_file = tempfilerust-analyzer cargo tempfile 3.23.0 crate/::NamedTempFilerust-analyzer cargo tempfile 3.23.0 file/NamedTempFile#::newrust-analyzer cargo tempfile 3.23.0 file/impl#[NamedTempFile]new().().expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Failed to create temp file");
307 let external_schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({
308 "type": "object",
309 "properties": {
310 "name": { "type": "string" }
311 },
312 "required": ["name"]
313 });
314 writerust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/write!!(temp_file, "{external_schema}").expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Failed to write to temp file");
315
316 let uri = path_to_urirust-analyzer cargo jsonschema 0.37.4 retriever/path_to_uri().(temp_file.pathrust-analyzer cargo tempfile 3.23.0 file/impl#[`NamedTempFile<F>`]path().());
317
318 let schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({
319 "type": "object",
320 "properties": {
321 "user": { "$ref": uri }
322 }
323 });
324
325 // Create registry with default async retriever
326 let registry = Registryrust-analyzer cargo referencing 0.37.4 registry/Registry#::optionsrust-analyzer cargo referencing 0.37.4 registry/impl#[Registry]options().()
327 .async_retrieverrust-analyzer cargo referencing 0.37.4 registry/impl#[`RegistryOptions<Arc<dyn Retrieve + 'static>>`]async_retriever().(DefaultRetrieverrust-analyzer cargo jsonschema 0.37.4 retriever/DefaultRetriever#)
328 .buildrust-analyzer cargo referencing 0.37.4 registry/impl#[`RegistryOptions<Arc<dyn AsyncRetrieve + 'static>>`]build().([(
329 "http://example.com/schema",
330 craterust-analyzer cargo jsonschema 0.37.4 crate/::Draftrust-analyzer cargo referencing 0.37.4 specification/Draft#::Draft202012rust-analyzer cargo referencing 0.37.4 specification/Draft#Draft202012#.create_resourcerust-analyzer cargo referencing 0.37.4 specification/impl#[Draft]create_resource().(schema.clonerust-analyzer cargo serde_json 1.0.145 value/impl#[Value][Clone]clone().()),
331 )])
332 .rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().
333 .expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Registry creation failed");
334
335 let validator = craterust-analyzer cargo jsonschema 0.37.4 crate/::optionsrust-analyzer cargo jsonschema 0.37.4 options().()
336 .with_registryrust-analyzer cargo jsonschema 0.37.4 options/impl#[`ValidationOptions<R>`]with_registry().(registry)
337 .buildrust-analyzer cargo jsonschema 0.37.4 options/impl#[ValidationOptions]build().(&schema)
338 .expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Invalid schema");
339
340 let valid = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({"user": {"name": "John Doe"}});
341 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&valid));
342
343 let invalid = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({"user": {}});
344 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(!rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&invalid));
345 }
346
347 #[tokiorust-analyzer cargo tokio 1.48.0 crate/::testrust-analyzer cargo tokio-macros 2.6.0 test_rt:]
348 async fn test_async_unknown_schemerust-analyzer cargo jsonschema 0.37.4 retriever/async_tests/test_async_unknown_scheme().() {
349 let schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({
350 "type": "object",
351 "properties": {
352 "test": { "$ref": "unknown-schema://test" }
353 }
354 });
355
356 let result = Registryrust-analyzer cargo referencing 0.37.4 registry/Registry#::optionsrust-analyzer cargo referencing 0.37.4 registry/impl#[Registry]options().()
357 .async_retrieverrust-analyzer cargo referencing 0.37.4 registry/impl#[`RegistryOptions<Arc<dyn Retrieve + 'static>>`]async_retriever().(DefaultRetrieverrust-analyzer cargo jsonschema 0.37.4 retriever/DefaultRetriever#)
358 .buildrust-analyzer cargo referencing 0.37.4 registry/impl#[`RegistryOptions<Arc<dyn AsyncRetrieve + 'static>>`]build().([(
359 "http://example.com/schema",
360 craterust-analyzer cargo jsonschema 0.37.4 crate/::Draftrust-analyzer cargo referencing 0.37.4 specification/Draft#::Draft202012rust-analyzer cargo referencing 0.37.4 specification/Draft#Draft202012#.create_resourcerust-analyzer cargo referencing 0.37.4 specification/impl#[Draft]create_resource().(schema),
361 )])
362 .rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().;
363
364 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(result.is_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]is_err().());
365 let error = result.unwrap_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap_err().().to_stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[T][ToString]to_string().();
366 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(error.containsrust-analyzer cargo core https://github.com/rust-lang/rust/library/core str/impl#[str]contains().("Unknown scheme"));
367 }
368
369 #[tokiorust-analyzer cargo tokio 1.48.0 crate/::testrust-analyzer cargo tokio-macros 2.6.0 test_rt:]
370 #[cfg(feature = "resolve-file")]
371 async fn test_async_concurrent_retrievalsrust-analyzer cargo jsonschema 0.37.4 retriever/async_tests/test_async_concurrent_retrievals().() {
372 let mut temp_files = vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc macros/vec!![];
373 let mut uris = vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc macros/vec!![];
374
375 // Create multiple temp files with different schemas
376 for i in 0..rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/Range#3 {
377 let mut temp_file = tempfilerust-analyzer cargo tempfile 3.23.0 crate/::NamedTempFilerust-analyzer cargo tempfile 3.23.0 file/NamedTempFile#::newrust-analyzer cargo tempfile 3.23.0 file/impl#[NamedTempFile]new().().expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Failed to create temp file");
378 let schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({
379 "type": "object",
380 "properties": {
381 "field": { "type": "string", "minLength": i }
382 }
383 });
384 writerust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/write!!(temp_file, "{schema}").expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Failed to write to temp file");
385 uris.pushrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]push().(path_to_urirust-analyzer cargo jsonschema 0.37.4 retriever/path_to_uri().(temp_file.pathrust-analyzer cargo tempfile 3.23.0 file/impl#[`NamedTempFile<F>`]path().()));
386 temp_files.pushrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]push().(temp_file);
387 }
388
389 // Create a schema that references all temp files
390 let schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({
391 "type": "object",
392 "properties": {
393 "obj1": { "$ref": uris[rust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`][`Index<I>`]index().0]rust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`][`Index<I>`]index(). },
394 "obj2": { "$ref": uris[rust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`][`Index<I>`]index().1]rust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`][`Index<I>`]index(). },
395 "obj3": { "$ref": uris[rust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`][`Index<I>`]index().2]rust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`][`Index<I>`]index(). }
396 }
397 });
398
399 let registry = Registryrust-analyzer cargo referencing 0.37.4 registry/Registry#::optionsrust-analyzer cargo referencing 0.37.4 registry/impl#[Registry]options().()
400 .async_retrieverrust-analyzer cargo referencing 0.37.4 registry/impl#[`RegistryOptions<Arc<dyn Retrieve + 'static>>`]async_retriever().(DefaultRetrieverrust-analyzer cargo jsonschema 0.37.4 retriever/DefaultRetriever#)
401 .buildrust-analyzer cargo referencing 0.37.4 registry/impl#[`RegistryOptions<Arc<dyn AsyncRetrieve + 'static>>`]build().([(
402 "http://example.com/schema",
403 craterust-analyzer cargo jsonschema 0.37.4 crate/::Draftrust-analyzer cargo referencing 0.37.4 specification/Draft#::Draft202012rust-analyzer cargo referencing 0.37.4 specification/Draft#Draft202012#.create_resourcerust-analyzer cargo referencing 0.37.4 specification/impl#[Draft]create_resource().(schema.clonerust-analyzer cargo serde_json 1.0.145 value/impl#[Value][Clone]clone().()),
404 )])
405 .rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().
406 .expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Registry creation failed");
407
408 let validator = craterust-analyzer cargo jsonschema 0.37.4 crate/::optionsrust-analyzer cargo jsonschema 0.37.4 options().()
409 .with_registryrust-analyzer cargo jsonschema 0.37.4 options/impl#[`ValidationOptions<R>`]with_registry().(registry)
410 .buildrust-analyzer cargo jsonschema 0.37.4 options/impl#[ValidationOptions]build().(&schema)
411 .expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Invalid schema");
412
413 let valid = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({
414 "obj1": { "field": "" }, // minLength: 0
415 "obj2": { "field": "a" }, // minLength: 1
416 "obj3": { "field": "ab" } // minLength: 2
417 });
418 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&valid));
419
420 // Test invalid data
421 let invalid = jsonrust-analyzer cargo serde_json 1.0.145 macros/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 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(!rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&invalid));
427 }
428 }