Debian Codegraph @

src/registry.rs

raw symbols SCIP
1 use std::{
2 collections::{hash_map::Entry, VecDeque},
3 num::NonZeroUsize,
4 pin::Pin,
5 sync::{Arc, LazyLock},
6 };
7
8 use ahash::{AHashMap, AHashSet};
9 use fluent_uri::{pct_enc::EStr, Uri};
10 use serde_json::Value;
11
12 use crate::{
13 anchors::{AnchorKey, AnchorKeyRef},
14 cache::{SharedUriCache, UriCache},
15 meta::{self, metas_for_draft},
16 resource::{unescape_segment, InnerResourcePtr, JsonSchemaResource},
17 uri,
18 vocabularies::{self, VocabularySet},
19 Anchor, DefaultRetriever, Draft, Error, Resolver, Resource, ResourceRef, Retrieve,
20 };
21
22 /// An owned-or-refstatic wrapper for JSON `Value`.
23 #[derive(Debug)]
24 pub(crate) enum ValueWrapper {
25 Owned(Value),
26 StaticRef(&'static Value),
27 }
28
29 impl AsRef<Value> for ValueWrapper {
30 fn as_ref(&self) -> &Value {
31 match self {
32 ValueWrapper::Owned(value) => value,
33 ValueWrapper::StaticRef(value) => value,
34 }
35 }
36 }
37
38 // SAFETY: `Pin` guarantees stable memory locations for resource pointers,
39 // while `Arc` enables cheap sharing between multiple registries
40 type DocumentStore = AHashMap<Arc<Uri<String>>, Pin<Arc<ValueWrapper>>>;
41 type ResourceMap = AHashMap<Arc<Uri<String>>, InnerResourcePtr>;
42
43 /// Pre-loaded registry containing all JSON Schema meta-schemas and their vocabularies
44 pub static SPECIFICATIONS: LazyLock<Registry> =
45 LazyLock::new(|| Registry::build_from_meta_schemas(meta::META_SCHEMAS_ALL.as_slice()));
46
47 /// A registry of JSON Schema resources, each identified by their canonical URIs.
48 ///
49 /// Registries store a collection of in-memory resources and their anchors.
50 /// They eagerly process all added resources, including their subresources and anchors.
51 /// This means that subresources contained within any added resources are immediately
52 /// discoverable and retrievable via their own IDs.
53 ///
54 /// # Resource Retrieval
55 ///
56 /// Registry supports both blocking and non-blocking retrieval of external resources.
57 ///
58 /// ## Blocking Retrieval
59 ///
60 /// ```rust
61 /// use referencing::{Registry, Resource, Retrieve, Uri};
62 /// use serde_json::{json, Value};
63 ///
64 /// struct ExampleRetriever;
65 ///
66 /// impl Retrieve for ExampleRetriever {
67 /// fn retrieve(
68 /// &self,
69 /// uri: &Uri<String>
70 /// ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
71 /// // Always return the same value for brevity
72 /// Ok(json!({"type": "string"}))
73 /// }
74 /// }
75 ///
76 /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
77 /// let registry = Registry::options()
78 /// .retriever(ExampleRetriever)
79 /// .build([
80 /// // Initial schema that might reference external schemas
81 /// (
82 /// "https://example.com/user.json",
83 /// Resource::from_contents(json!({
84 /// "type": "object",
85 /// "properties": {
86 /// // Should be retrieved by `ExampleRetriever`
87 /// "role": {"$ref": "https://example.com/role.json"}
88 /// }
89 /// }))
90 /// )
91 /// ])?;
92 /// # Ok(())
93 /// # }
94 /// ```
95 ///
96 /// ## Non-blocking Retrieval
97 ///
98 /// ```rust
99 /// # #[cfg(feature = "retrieve-async")]
100 /// # mod example {
101 /// use referencing::{Registry, Resource, AsyncRetrieve, Uri};
102 /// use serde_json::{json, Value};
103 ///
104 /// struct ExampleRetriever;
105 ///
106 /// #[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
107 /// #[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
108 /// impl AsyncRetrieve for ExampleRetriever {
109 /// async fn retrieve(
110 /// &self,
111 /// uri: &Uri<String>
112 /// ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
113 /// // Always return the same value for brevity
114 /// Ok(json!({"type": "string"}))
115 /// }
116 /// }
117 ///
118 /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
119 /// let registry = Registry::options()
120 /// .async_retriever(ExampleRetriever)
121 /// .build([
122 /// (
123 /// "https://example.com/user.json",
124 /// Resource::from_contents(json!({
125 /// // Should be retrieved by `ExampleRetriever`
126 /// "$ref": "https://example.com/common/user.json"
127 /// }))
128 /// )
129 /// ])
130 /// .await?;
131 /// # Ok(())
132 /// # }
133 /// # }
134 /// ```
135 ///
136 /// The registry will automatically:
137 ///
138 /// - Resolve external references
139 /// - Cache retrieved schemas
140 /// - Handle nested references
141 /// - Process JSON Schema anchors
142 ///
143 #[derive(Debug)]
144 pub struct Registry {
145 documents: DocumentStore,
146 pub(crate) resources: ResourceMap,
147 anchors: AHashMap<AnchorKey, Anchor>,
148 resolution_cache: SharedUriCache,
149 }
150
151 impl Clone for Registry {
152 fn clone(&self) -> Self {
153 Self {
154 documents: self.documents.clone(),
155 resources: self.resources.clone(),
156 anchors: self.anchors.clone(),
157 resolution_cache: self.resolution_cache.clone(),
158 }
159 }
160 }
161
162 /// Configuration options for creating a [`Registry`].
163 pub struct RegistryOptions<R> {
164 retriever: R,
165 draft: Draft,
166 }
167
168 impl<R> RegistryOptions<R> {
169 /// Set specification version under which the resources should be interpreted under.
170 #[must_use]
171 pub fn draft(mut self, draft: Draft) -> Self {
172 self.draft = draft;
173 self
174 }
175 }
176
177 impl RegistryOptions<Arc<dyn Retrieve>> {
178 /// Create a new [`RegistryOptions`] with default settings.
179 #[must_use]
180 pub fn new() -> Self {
181 Self {
182 retriever: Arc::new(DefaultRetriever),
183 draft: Draft::default(),
184 }
185 }
186 /// Set a custom retriever for the [`Registry`].
187 #[must_use]
188 pub fn retriever(mut self, retriever: impl IntoRetriever) -> Self {
189 self.retriever = retriever.into_retriever();
190 self
191 }
192 /// Set a custom async retriever for the [`Registry`].
193 #[cfg(feature = "retrieve-async")]
194 #[must_use]
195 pub fn async_retriever(
196 self,
197 retriever: impl IntoAsyncRetriever,
198 ) -> RegistryOptions<Arc<dyn crate::AsyncRetrieve>> {
199 RegistryOptions {
200 retriever: retriever.into_retriever(),
201 draft: self.draft,
202 }
203 }
204 /// Create a [`Registry`] from multiple resources using these options.
205 ///
206 /// # Errors
207 ///
208 /// Returns an error if:
209 /// - Any URI is invalid
210 /// - Any referenced resources cannot be retrieved
211 pub fn build(
212 self,
213 pairs: impl IntoIterator<Item = (impl AsRef<str>, Resource)>,
214 ) -> Result<Registry, Error> {
215 Registry::try_from_resources_impl(pairs, &*self.retriever, self.draft)
216 }
217 }
218
219 #[cfg(feature = "retrieve-async")]
220 impl RegistryOptions<Arc<dyn crate::AsyncRetrieve>> {
221 /// Create a [`Registry`] from multiple resources using these options with async retrieval.
222 ///
223 /// # Errors
224 ///
225 /// Returns an error if:
226 /// - Any URI is invalid
227 /// - Any referenced resources cannot be retrieved
228 pub async fn build(
229 self,
230 pairs: impl IntoIterator<Item = (impl AsRef<str>, Resource)>,
231 ) -> Result<Registry, Error> {
232 Registry::try_from_resources_async_impl(pairs, &*self.retriever, self.draft).await
233 }
234 }
235
236 pub trait IntoRetriever {
237 fn into_retriever(self) -> Arc<dyn Retrieve>;
238 }
239
240 impl<T: Retrieve + 'static> IntoRetriever for T {
241 fn into_retriever(self) -> Arc<dyn Retrieve> {
242 Arc::new(self)
243 }
244 }
245
246 impl IntoRetriever for Arc<dyn Retrieve> {
247 fn into_retriever(self) -> Arc<dyn Retrieve> {
248 self
249 }
250 }
251
252 #[cfg(feature = "retrieve-async")]
253 pub trait IntoAsyncRetriever {
254 fn into_retriever(self) -> Arc<dyn crate::AsyncRetrieve>;
255 }
256
257 #[cfg(feature = "retrieve-async")]
258 impl<T: crate::AsyncRetrieve + 'static> IntoAsyncRetriever for T {
259 fn into_retriever(self) -> Arc<dyn crate::AsyncRetrieve> {
260 Arc::new(self)
261 }
262 }
263
264 #[cfg(feature = "retrieve-async")]
265 impl IntoAsyncRetriever for Arc<dyn crate::AsyncRetrieve> {
266 fn into_retriever(self) -> Arc<dyn crate::AsyncRetrieve> {
267 self
268 }
269 }
270
271 impl Default for RegistryOptions<Arc<dyn Retrieve>> {
272 fn default() -> Self {
273 Self::new()
274 }
275 }
276
277 impl Registry {
278 /// Get [`RegistryOptions`] for configuring a new [`Registry`].
279 #[must_use]
280 pub fn options() -> RegistryOptions<Arc<dyn Retrieve>> {
281 RegistryOptions::new()
282 }
283 /// Create a new [`Registry`] with a single resource.
284 ///
285 /// # Arguments
286 ///
287 /// * `uri` - The URI of the resource.
288 /// * `resource` - The resource to add.
289 ///
290 /// # Errors
291 ///
292 /// Returns an error if the URI is invalid or if there's an issue processing the resource.
293 pub fn try_new(uri: impl AsRef<str>, resource: Resource) -> Result<Self, Error> {
294 Self::try_new_impl(uri, resource, &DefaultRetriever, Draft::default())
295 }
296 /// Create a new [`Registry`] from an iterator of (URI, Resource) pairs.
297 ///
298 /// # Arguments
299 ///
300 /// * `pairs` - An iterator of (URI, Resource) pairs.
301 ///
302 /// # Errors
303 ///
304 /// Returns an error if any URI is invalid or if there's an issue processing the resources.
305 pub fn try_from_resources(
306 pairs: impl IntoIterator<Item = (impl AsRef<str>, Resource)>,
307 ) -> Result<Self, Error> {
308 Self::try_from_resources_impl(pairs, &DefaultRetriever, Draft::default())
309 }
310 fn try_new_impl(
311 uri: impl AsRef<str>,
312 resource: Resource,
313 retriever: &dyn Retrieve,
314 draft: Draft,
315 ) -> Result<Self, Error> {
316 Self::try_from_resources_impl([(uri, resource)], retriever, draft)
317 }
318 fn try_from_resources_impl(
319 pairs: impl IntoIterator<Item = (impl AsRef<str>, Resource)>,
320 retriever: &dyn Retrieve,
321 draft: Draft,
322 ) -> Result<Self, Error> {
323 let mut documents = AHashMap::new();
324 let mut resources = ResourceMap::new();
325 let mut anchors = AHashMap::new();
326 let mut resolution_cache = UriCache::new();
327 let custom_metaschemas = process_resources(
328 pairs,
329 retriever,
330 &mut documents,
331 &mut resources,
332 &mut anchors,
333 &mut resolution_cache,
334 draft,
335 )?;
336
337 // Validate that all custom $schema references are registered
338 validate_custom_metaschemas(&custom_metaschemas, &resources)?;
339
340 Ok(Registry {
341 documents,
342 resources,
343 anchors,
344 resolution_cache: resolution_cache.into_shared(),
345 })
346 }
347 /// Create a new [`Registry`] from an iterator of (URI, Resource) pairs using an async retriever.
348 ///
349 /// # Arguments
350 ///
351 /// * `pairs` - An iterator of (URI, Resource) pairs.
352 ///
353 /// # Errors
354 ///
355 /// Returns an error if any URI is invalid or if there's an issue processing the resources.
356 #[cfg(feature = "retrieve-async")]
357 async fn try_from_resources_async_impl(
358 pairs: impl IntoIterator<Item = (impl AsRef<str>, Resource)>,
359 retriever: &dyn crate::AsyncRetrieve,
360 draft: Draft,
361 ) -> Result<Self, Error> {
362 let mut documents = AHashMap::new();
363 let mut resources = ResourceMap::new();
364 let mut anchors = AHashMap::new();
365 let mut resolution_cache = UriCache::new();
366
367 let custom_metaschemas = process_resources_async(
368 pairs,
369 retriever,
370 &mut documents,
371 &mut resources,
372 &mut anchors,
373 &mut resolution_cache,
374 draft,
375 )
376 .await?;
377
378 // Validate that all custom $schema references are registered
379 validate_custom_metaschemas(&custom_metaschemas, &resources)?;
380
381 Ok(Registry {
382 documents,
383 resources,
384 anchors,
385 resolution_cache: resolution_cache.into_shared(),
386 })
387 }
388 /// Create a new registry with a new resource.
389 ///
390 /// # Errors
391 ///
392 /// Returns an error if the URI is invalid or if there's an issue processing the resource.
393 pub fn try_with_resource(
394 self,
395 uri: impl AsRef<str>,
396 resource: Resource,
397 ) -> Result<Registry, Error> {
398 let draft = resource.draft();
399 self.try_with_resources([(uri, resource)], draft)
400 }
401 /// Create a new registry with new resources.
402 ///
403 /// # Errors
404 ///
405 /// Returns an error if any URI is invalid or if there's an issue processing the resources.
406 pub fn try_with_resources(
407 self,
408 pairs: impl IntoIterator<Item = (impl AsRef<str>, Resource)>,
409 draft: Draft,
410 ) -> Result<Registry, Error> {
411 self.try_with_resources_and_retriever(pairs, &DefaultRetriever, draft)
412 }
413 /// Create a new registry with new resources and using the given retriever.
414 ///
415 /// # Errors
416 ///
417 /// Returns an error if any URI is invalid or if there's an issue processing the resources.
418 pub fn try_with_resources_and_retriever(
419 self,
420 pairs: impl IntoIterator<Item = (impl AsRef<str>, Resource)>,
421 retriever: &dyn Retrieve,
422 draft: Draft,
423 ) -> Result<Registry, Error> {
424 let mut documents = self.documents;
425 let mut resources = self.resources;
426 let mut anchors = self.anchors;
427 let mut resolution_cache = self.resolution_cache.into_local();
428 let custom_metaschemas = process_resources(
429 pairs,
430 retriever,
431 &mut documents,
432 &mut resources,
433 &mut anchors,
434 &mut resolution_cache,
435 draft,
436 )?;
437 validate_custom_metaschemas(&custom_metaschemas, &resources)?;
438 Ok(Registry {
439 documents,
440 resources,
441 anchors,
442 resolution_cache: resolution_cache.into_shared(),
443 })
444 }
445 /// Create a new registry with new resources and using the given non-blocking retriever.
446 ///
447 /// # Errors
448 ///
449 /// Returns an error if any URI is invalid or if there's an issue processing the resources.
450 #[cfg(feature = "retrieve-async")]
451 pub async fn try_with_resources_and_retriever_async(
452 self,
453 pairs: impl IntoIterator<Item = (impl AsRef<str>, Resource)>,
454 retriever: &dyn crate::AsyncRetrieve,
455 draft: Draft,
456 ) -> Result<Registry, Error> {
457 let mut documents = self.documents;
458 let mut resources = self.resources;
459 let mut anchors = self.anchors;
460 let mut resolution_cache = self.resolution_cache.into_local();
461 let custom_metaschemas = process_resources_async(
462 pairs,
463 retriever,
464 &mut documents,
465 &mut resources,
466 &mut anchors,
467 &mut resolution_cache,
468 draft,
469 )
470 .await?;
471 validate_custom_metaschemas(&custom_metaschemas, &resources)?;
472 Ok(Registry {
473 documents,
474 resources,
475 anchors,
476 resolution_cache: resolution_cache.into_shared(),
477 })
478 }
479 /// Create a new [`Resolver`] for this registry with the given base URI.
480 ///
481 /// # Errors
482 ///
483 /// Returns an error if the base URI is invalid.
484 pub fn try_resolver(&self, base_uri: &str) -> Result<Resolver<'_>, Error> {
485 let base = uri::from_str(base_uri)?;
486 Ok(self.resolver(base))
487 }
488 /// Create a new [`Resolver`] for this registry with a known valid base URI.
489 #[must_use]
490 pub fn resolver(&self, base_uri: Uri<String>) -> Resolver<'_> {
491 Resolver::new(self, Arc::new(base_uri))
492 }
493 pub(crate) fn anchor<'a>(&self, uri: &'a Uri<String>, name: &'a str) -> Result<&Anchor, Error> {
494 let key = AnchorKeyRef::new(uri, name);
495 if let Some(value) = self.anchors.get(key.borrow_dyn()) {
496 return Ok(value);
497 }
498 let resource = &self.resources[uri];
499 if let Some(id) = resource.id() {
500 let uri = uri::from_str(id)?;
501 let key = AnchorKeyRef::new(&uri, name);
502 if let Some(value) = self.anchors.get(key.borrow_dyn()) {
503 return Ok(value);
504 }
505 }
506 if name.contains('/') {
507 Err(Error::invalid_anchor(name.to_string()))
508 } else {
509 Err(Error::no_such_anchor(name.to_string()))
510 }
511 }
512 /// Resolves a reference URI against a base URI using registry's cache.
513 ///
514 /// # Errors
515 ///
516 /// Returns an error if base has not schema or there is a fragment.
517 pub fn resolve_against(&self, base: &Uri<&str>, uri: &str) -> Result<Arc<Uri<String>>, Error> {
518 self.resolution_cache.resolve_against(base, uri)
519 }
520 /// Returns vocabulary set configured for given draft and contents.
521 ///
522 /// For custom meta-schemas (`Draft::Unknown`), looks up the meta-schema in the registry
523 /// and extracts its `$vocabulary` declaration. If the meta-schema is not registered,
524 /// returns the default Draft 2020-12 vocabularies.
525 #[must_use]
526 pub fn find_vocabularies(&self, draft: Draft, contents: &Value) -> VocabularySet {
527 match draft.detect(contents) {
528 Draft::Unknown => {
529 // Custom/unknown meta-schema - try to look it up in the registry
530 if let Some(specification) = contents
531 .as_object()
532 .and_then(|obj| obj.get("$schema"))
533 .and_then(|s| s.as_str())
534 {
535 if let Ok(mut uri) = uri::from_str(specification) {
536 // Remove fragment for lookup (e.g., "http://example.com/schema#" -> "http://example.com/schema")
537 // Resources are stored without fragments, so we must strip it to find the meta-schema
538 uri.set_fragment(None);
539 if let Some(resource) = self.resources.get(&uri) {
540 // Found the custom meta-schema - extract vocabularies
541 if let Ok(Some(vocabularies)) = vocabularies::find(resource.contents())
542 {
543 return vocabularies;
544 }
545 }
546 // Meta-schema not registered - this will be caught during compilation
547 // For now, return default vocabularies to allow resource creation
548 }
549 }
550 // Default to Draft 2020-12 vocabularies for unknown meta-schemas
551 Draft::Unknown.default_vocabularies()
552 }
553 draft => draft.default_vocabularies(),
554 }
555 }
556
557 /// Build a registry with all the given meta-schemas from specs.
558 pub(crate) fn build_from_meta_schemas(schemas: &[(&'static str, &'static Value)]) -> Self {
559 let schemas_count = schemas.len();
560 let pairs = schemas
561 .iter()
562 .map(|(uri, schema)| (uri, ResourceRef::from_contents(schema)));
563
564 let mut documents = DocumentStore::with_capacity(schemas_count);
565 let mut resources = ResourceMap::with_capacity(schemas_count);
566
567 // The actual number of anchors and cache-entries varies across
568 // drafts. We overshoot here to avoid reallocations, using the sum
569 // over all specifications.
570 let mut anchors = AHashMap::with_capacity(8);
571 let mut resolution_cache = UriCache::with_capacity(35);
572
573 process_meta_schemas(
574 pairs,
575 &mut documents,
576 &mut resources,
577 &mut anchors,
578 &mut resolution_cache,
579 )
580 .expect("Failed to process meta schemas");
581
582 Self {
583 documents,
584 resources,
585 anchors,
586 resolution_cache: resolution_cache.into_shared(),
587 }
588 }
589 }
590
591 fn process_meta_schemas(
592 pairs: impl IntoIterator<Item = (impl AsRef<str>, ResourceRef<'static>)>,
593 documents: &mut DocumentStore,
594 resources: &mut ResourceMap,
595 anchors: &mut AHashMap<AnchorKey, Anchor>,
596 resolution_cache: &mut UriCache,
597 ) -> Result<(), Error> {
598 let mut queue = VecDeque::with_capacity(32);
599
600 for (uri, resource) in pairs {
601 let uri = uri::from_str(uri.as_ref().trim_end_matches('#'))?;
602 let key = Arc::new(uri);
603 let contents: &'static Value = resource.contents();
604 let wrapped_value = Arc::pin(ValueWrapper::StaticRef(contents));
605 let resource = InnerResourcePtr::new((*wrapped_value).as_ref(), resource.draft());
606 documents.insert(Arc::clone(&key), wrapped_value);
607 resources.insert(Arc::clone(&key), resource.clone());
608 queue.push_back((key, resource));
609 }
610
611 // Process current queue and collect references to external resources
612 while let Some((mut base, resource)) = queue.pop_front() {
613 if let Some(id) = resource.id() {
614 base = resolution_cache.resolve_against(&base.borrow(), id)?;
615 resources.insert(base.clone(), resource.clone());
616 }
617
618 // Look for anchors
619 for anchor in resource.anchors() {
620 anchors.insert(AnchorKey::new(base.clone(), anchor.name()), anchor);
621 }
622
623 // Process subresources
624 for contents in resource.draft().subresources_of(resource.contents()) {
625 let subresource = InnerResourcePtr::new(contents, resource.draft());
626 queue.push_back((base.clone(), subresource));
627 }
628 }
629 Ok(())
630 }
631
632 #[derive(Hash, Eq, PartialEq)]
633 struct ReferenceKey {
634 base_ptr: NonZeroUsize,
635 reference: String,
636 }
637
638 impl ReferenceKey {
639 fn new(base: &Arc<Uri<String>>, reference: &str) -> Self {
640 Self {
641 base_ptr: NonZeroUsize::new(Arc::as_ptr(base) as usize)
642 .expect("Arc pointer should never be null"),
643 reference: reference.to_owned(),
644 }
645 }
646 }
647
648 type ReferenceTracker = AHashSet<ReferenceKey>;
649
650 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
651 enum ReferenceKind {
652 Ref,
653 Schema,
654 }
655
656 /// An entry in the processing queue.
657 /// The optional third element is the document root URI, used when the resource
658 /// was extracted from a fragment of a larger document. Local `$ref`s need to be
659 /// resolved against the document root, not just the fragment content.
660 type QueueEntry = (Arc<Uri<String>>, InnerResourcePtr, Option<Arc<Uri<String>>>);
661
662 struct ProcessingState {
663 queue: VecDeque<QueueEntry>,
664 seen: ReferenceTracker,
665 external: AHashSet<(String, Uri<String>, ReferenceKind)>,
666 scratch: String,
667 refers_metaschemas: bool,
668 custom_metaschemas: Vec<Arc<Uri<String>>>,
669 /// Tracks schema pointers we've visited during recursive external resource collection.
670 /// This prevents infinite recursion when schemas reference each other.
671 visited_schemas: AHashSet<usize>,
672 }
673
674 impl ProcessingState {
675 fn new() -> Self {
676 Self {
677 queue: VecDeque::with_capacity(32),
678 seen: ReferenceTracker::new(),
679 external: AHashSet::new(),
680 scratch: String::new(),
681 refers_metaschemas: false,
682 custom_metaschemas: Vec::new(),
683 visited_schemas: AHashSet::new(),
684 }
685 }
686 }
687
688 fn process_input_resources(
689 pairs: impl IntoIterator<Item = (impl AsRef<str>, Resource)>,
690 documents: &mut DocumentStore,
691 resources: &mut ResourceMap,
692 state: &mut ProcessingState,
693 ) -> Result<(), Error> {
694 for (uri, resource) in pairs {
695 let uri = uri::from_str(uri.as_ref().trim_end_matches('#'))?;
696 let key = Arc::new(uri);
697 match documents.entry(Arc::clone(&key)) {
698 Entry::Occupied(_) => {}
699 Entry::Vacant(entry) => {
700 let (draft, contents) = resource.into_inner();
701 let wrapped_value = Arc::pin(ValueWrapper::Owned(contents));
702 let resource = InnerResourcePtr::new((*wrapped_value).as_ref(), draft);
703 resources.insert(Arc::clone(&key), resource.clone());
704
705 // Track resources with custom meta-schemas for later validation
706 if draft == Draft::Unknown {
707 state.custom_metaschemas.push(Arc::clone(&key));
708 }
709
710 state.queue.push_back((key, resource, None));
711 entry.insert(wrapped_value);
712 }
713 }
714 }
715 Ok(())
716 }
717
718 fn process_queue(
719 state: &mut ProcessingState,
720 resources: &mut ResourceMap,
721 anchors: &mut AHashMap<AnchorKey, Anchor>,
722 resolution_cache: &mut UriCache,
723 ) -> Result<(), Error> {
724 while let Some((mut base, resource, document_root_uri)) = state.queue.pop_front() {
725 if let Some(id) = resource.id() {
726 base = resolve_id(&base, id, resolution_cache)?;
727 resources.insert(base.clone(), resource.clone());
728 }
729
730 for anchor in resource.anchors() {
731 anchors.insert(AnchorKey::new(base.clone(), anchor.name()), anchor);
732 }
733
734 // Determine the document root for resolving local $refs.
735 // If document_root_uri is set (e.g., for fragment-extracted resources),
736 // look up the full document. Otherwise, this resource IS the document root.
737 let root = document_root_uri
738 .as_ref()
739 .and_then(|uri| resources.get(uri))
740 .map_or_else(|| resource.contents(), InnerResourcePtr::contents);
741
742 // Skip if already visited during local $ref resolution
743 let contents_ptr = std::ptr::from_ref::<Value>(resource.contents()) as usize;
744 if state.visited_schemas.insert(contents_ptr) {
745 collect_external_resources(
746 &base,
747 root,
748 resource.contents(),
749 &mut state.external,
750 &mut state.seen,
751 resolution_cache,
752 &mut state.scratch,
753 &mut state.refers_metaschemas,
754 resource.draft(),
755 &mut state.visited_schemas,
756 )?;
757 }
758
759 // Subresources inherit the document root URI, or use the current base if none set
760 let subresource_root_uri = document_root_uri.or_else(|| Some(base.clone()));
761 for contents in resource.draft().subresources_of(resource.contents()) {
762 let subresource = InnerResourcePtr::new(contents, resource.draft());
763 state
764 .queue
765 .push_back((base.clone(), subresource, subresource_root_uri.clone()));
766 }
767 }
768 Ok(())
769 }
770
771 fn handle_fragment(
772 uri: &Uri<String>,
773 resource: &InnerResourcePtr,
774 key: &Arc<Uri<String>>,
775 default_draft: Draft,
776 queue: &mut VecDeque<QueueEntry>,
777 document_root_uri: Arc<Uri<String>>,
778 ) {
779 if let Some(fragment) = uri.fragment() {
780 if let Some(resolved) = pointer(resource.contents(), fragment.as_str()) {
781 let draft = default_draft.detect(resolved);
782 let contents = std::ptr::addr_of!(*resolved);
783 let resource = InnerResourcePtr::new(contents, draft);
784 queue.push_back((Arc::clone(key), resource, Some(document_root_uri)));
785 }
786 }
787 }
788
789 fn handle_metaschemas(
790 refers_metaschemas: bool,
791 resources: &mut ResourceMap,
792 anchors: &mut AHashMap<AnchorKey, Anchor>,
793 draft_version: Draft,
794 ) {
795 if refers_metaschemas {
796 let schemas = metas_for_draft(draft_version);
797 let draft_registry = Registry::build_from_meta_schemas(schemas);
798 resources.reserve(draft_registry.resources.len());
799 for (key, resource) in draft_registry.resources {
800 resources.insert(key, resource.clone());
801 }
802 anchors.reserve(draft_registry.anchors.len());
803 for (key, anchor) in draft_registry.anchors {
804 anchors.insert(key, anchor);
805 }
806 }
807 }
808
809 fn create_resource(
810 retrieved: Value,
811 fragmentless: Uri<String>,
812 default_draft: Draft,
813 documents: &mut DocumentStore,
814 resources: &mut ResourceMap,
815 custom_metaschemas: &mut Vec<Arc<Uri<String>>>,
816 ) -> (Arc<Uri<String>>, InnerResourcePtr) {
817 let draft = default_draft.detect(&retrieved);
818 let wrapped_value = Arc::pin(ValueWrapper::Owned(retrieved));
819 let resource = InnerResourcePtr::new((*wrapped_value).as_ref(), draft);
820 let key = Arc::new(fragmentless);
821 documents.insert(Arc::clone(&key), wrapped_value);
822 resources.insert(Arc::clone(&key), resource.clone());
823
824 // Track resources with custom meta-schemas for later validation
825 if draft == Draft::Unknown {
826 custom_metaschemas.push(Arc::clone(&key));
827 }
828
829 (key, resource)
830 }
831
832 fn process_resources(
833 pairs: impl IntoIterator<Item = (impl AsRef<str>, Resource)>,
834 retriever: &dyn Retrieve,
835 documents: &mut DocumentStore,
836 resources: &mut ResourceMap,
837 anchors: &mut AHashMap<AnchorKey, Anchor>,
838 resolution_cache: &mut UriCache,
839 default_draft: Draft,
840 ) -> Result<Vec<Arc<Uri<String>>>, Error> {
841 let mut state = ProcessingState::new();
842 process_input_resources(pairs, documents, resources, &mut state)?;
843
844 loop {
845 if state.queue.is_empty() && state.external.is_empty() {
846 break;
847 }
848
849 process_queue(&mut state, resources, anchors, resolution_cache)?;
850
851 // Retrieve external resources
852 for (original, uri, kind) in state.external.drain() {
853 let mut fragmentless = uri.clone();
854 fragmentless.set_fragment(None);
855 if !resources.contains_key(&fragmentless) {
856 let retrieved = match retriever.retrieve(&fragmentless) {
857 Ok(retrieved) => retrieved,
858 Err(error) => {
859 handle_retrieve_error(&uri, &original, &fragmentless, error, kind)?;
860 continue;
861 }
862 };
863
864 let (key, resource) = create_resource(
865 retrieved,
866 fragmentless,
867 default_draft,
868 documents,
869 resources,
870 &mut state.custom_metaschemas,
871 );
872 handle_fragment(
873 &uri,
874 &resource,
875 &key,
876 default_draft,
877 &mut state.queue,
878 Arc::clone(&key),
879 );
880 state.queue.push_back((key, resource, None));
881 }
882 }
883 }
884
885 handle_metaschemas(state.refers_metaschemas, resources, anchors, default_draft);
886
887 Ok(state.custom_metaschemas)
888 }
889
890 #[cfg(feature = "retrieve-async")]
891 async fn process_resources_async(
892 pairs: impl IntoIterator<Item = (impl AsRef<str>, Resource)>,
893 retriever: &dyn crate::AsyncRetrieve,
894 documents: &mut DocumentStore,
895 resources: &mut ResourceMap,
896 anchors: &mut AHashMap<AnchorKey, Anchor>,
897 resolution_cache: &mut UriCache,
898 default_draft: Draft,
899 ) -> Result<Vec<Arc<Uri<String>>>, Error> {
900 let mut state = ProcessingState::new();
901 process_input_resources(pairs, documents, resources, &mut state)?;
902
903 loop {
904 if state.queue.is_empty() && state.external.is_empty() {
905 break;
906 }
907
908 process_queue(&mut state, resources, anchors, resolution_cache)?;
909
910 if !state.external.is_empty() {
911 let data = state
912 .external
913 .drain()
914 .filter_map(|(original, uri, kind)| {
915 let mut fragmentless = uri.clone();
916 fragmentless.set_fragment(None);
917 if resources.contains_key(&fragmentless) {
918 None
919 } else {
920 Some((original, uri, kind, fragmentless))
921 }
922 })
923 .collect::<Vec<_>>();
924
925 let results = {
926 let futures = data
927 .iter()
928 .map(|(_, _, _, fragmentless)| retriever.retrieve(fragmentless));
929 futures::future::join_all(futures).await
930 };
931
932 for ((original, uri, kind, fragmentless), result) in data.iter().zip(results) {
933 let retrieved = match result {
934 Ok(retrieved) => retrieved,
935 Err(error) => {
936 handle_retrieve_error(uri, original, fragmentless, error, *kind)?;
937 continue;
938 }
939 };
940
941 let (key, resource) = create_resource(
942 retrieved,
943 fragmentless.clone(),
944 default_draft,
945 documents,
946 resources,
947 &mut state.custom_metaschemas,
948 );
949 handle_fragment(
950 uri,
951 &resource,
952 &key,
953 default_draft,
954 &mut state.queue,
955 Arc::clone(&key),
956 );
957 state.queue.push_back((key, resource, None));
958 }
959 }
960 }
961
962 handle_metaschemas(state.refers_metaschemas, resources, anchors, default_draft);
963
964 Ok(state.custom_metaschemas)
965 }
966
967 fn handle_retrieve_error(
968 uri: &Uri<String>,
969 original: &str,
970 fragmentless: &Uri<String>,
971 error: Box<dyn std::error::Error + Send + Sync>,
972 kind: ReferenceKind,
973 ) -> Result<(), Error> {
974 match kind {
975 ReferenceKind::Schema => {
976 // $schema fetch failures are non-fatal during resource processing
977 // Unregistered custom meta-schemas will be caught in validate_custom_metaschemas()
978 Ok(())
979 }
980 ReferenceKind::Ref => {
981 // $ref fetch failures are fatal - they're required for validation
982 if uri.scheme().as_str() == "json-schema" {
983 Err(Error::unretrievable(
984 original,
985 "No base URI is available".into(),
986 ))
987 } else {
988 Err(Error::unretrievable(fragmentless.as_str(), error))
989 }
990 }
991 }
992 }
993
994 fn validate_custom_metaschemas(
995 custom_metaschemas: &[Arc<Uri<String>>],
996 resources: &ResourceMap,
997 ) -> Result<(), Error> {
998 // Only validate resources with Draft::Unknown
999 for uri in custom_metaschemas {
1000 if let Some(resource) = resources.get(uri) {
1001 // Extract the $schema value from this resource
1002 if let Some(schema_uri) = resource
1003 .contents()
1004 .as_object()
1005 .and_then(|obj| obj.get("$schema"))
1006 .and_then(|s| s.as_str())
1007 {
1008 // Check if this meta-schema is registered
1009 match uri::from_str(schema_uri) {
1010 Ok(mut meta_uri) => {
1011 // Remove fragment for lookup (e.g., "http://example.com/schema#" -> "http://example.com/schema")
1012 meta_uri.set_fragment(None);
1013 if !resources.contains_key(&meta_uri) {
1014 return Err(Error::unknown_specification(schema_uri));
1015 }
1016 }
1017 Err(_) => {
1018 return Err(Error::unknown_specification(schema_uri));
1019 }
1020 }
1021 }
1022 }
1023 }
1024 Ok(())
1025 }
1026
1027 fn collect_external_resources(
1028 base: &Arc<Uri<String>>,
1029 root: &Value,
1030 contents: &Value,
1031 collected: &mut AHashSet<(String, Uri<String>, ReferenceKind)>,
1032 seen: &mut ReferenceTracker,
1033 resolution_cache: &mut UriCache,
1034 scratch: &mut String,
1035 refers_metaschemas: &mut bool,
1036 draft: Draft,
1037 visited: &mut AHashSet<usize>,
1038 ) -> Result<(), Error> {
1039 // URN schemes are not supported for external resolution
1040 if base.scheme().as_str() == "urn" {
1041 return Ok(());
1042 }
1043
1044 macro_rules! on_reference {
1045 ($reference:expr, $key:literal) => {
1046 // Skip well-known schema references
1047 if $reference.starts_with("https://json-schema.org/draft/")
1048 || $reference.starts_with("http://json-schema.org/draft-")
1049 || base.as_str().starts_with("https://json-schema.org/draft/")
1050 {
1051 if $key == "$ref" {
1052 *refers_metaschemas = true;
1053 }
1054 } else if $reference != "#" {
1055 if mark_reference(seen, base, $reference) {
1056 // Handle local references separately as they may have nested references to external resources
1057 if $reference.starts_with('#') {
1058 // Use the root document for pointer resolution since local refs are always
1059 // relative to the document root, not the current subschema.
1060 // Also track $id changes along the path to get the correct base URI.
1061 if let Some((referenced, resolved_base)) = pointer_with_base(
1062 root,
1063 $reference.trim_start_matches('#'),
1064 base,
1065 resolution_cache,
1066 draft,
1067 )? {
1068 // Recursively collect from the referenced schema and all its subresources
1069 collect_external_resources_recursive(
1070 &resolved_base,
1071 root,
1072 referenced,
1073 collected,
1074 seen,
1075 resolution_cache,
1076 scratch,
1077 refers_metaschemas,
1078 draft,
1079 visited,
1080 )?;
1081 }
1082 } else {
1083 let resolved = if base.has_fragment() {
1084 let mut base_without_fragment = base.as_ref().clone();
1085 base_without_fragment.set_fragment(None);
1086
1087 let (path, fragment) = match $reference.split_once('#') {
1088 Some((path, fragment)) => (path, Some(fragment)),
1089 None => ($reference, None),
1090 };
1091
1092 let mut resolved = (*resolution_cache
1093 .resolve_against(&base_without_fragment.borrow(), path)?)
1094 .clone();
1095 // Add the fragment back if present
1096 if let Some(fragment) = fragment {
1097 // It is cheaper to check if it is properly encoded than allocate given that
1098 // the majority of inputs do not need to be additionally encoded
1099 if let Some(encoded) = uri::EncodedString::new(fragment) {
1100 resolved = resolved.with_fragment(Some(encoded));
1101 } else {
1102 uri::encode_to(fragment, scratch);
1103 resolved = resolved.with_fragment(Some(
1104 uri::EncodedString::new_or_panic(scratch),
1105 ));
1106 scratch.clear();
1107 }
1108 }
1109 resolved
1110 } else {
1111 (*resolution_cache
1112 .resolve_against(&base.borrow(), $reference)?)
1113 .clone()
1114 };
1115
1116 let kind = if $key == "$schema" {
1117 ReferenceKind::Schema
1118 } else {
1119 ReferenceKind::Ref
1120 };
1121 collected.insert(($reference.to_string(), resolved, kind));
1122 }
1123 }
1124 }
1125 };
1126 }
1127
1128 if let Some(object) = contents.as_object() {
1129 if object.len() < 3 {
1130 for (key, value) in object {
1131 if key == "$ref" {
1132 if let Some(reference) = value.as_str() {
1133 on_reference!(reference, "$ref");
1134 }
1135 } else if key == "$schema" {
1136 if let Some(reference) = value.as_str() {
1137 on_reference!(reference, "$schema");
1138 }
1139 }
1140 }
1141 } else {
1142 if let Some(reference) = object.get("$ref").and_then(Value::as_str) {
1143 on_reference!(reference, "$ref");
1144 }
1145 if let Some(reference) = object.get("$schema").and_then(Value::as_str) {
1146 on_reference!(reference, "$schema");
1147 }
1148 }
1149 }
1150 Ok(())
1151 }
1152
1153 /// Recursively collect external resources from a schema and all its subresources.
1154 ///
1155 /// The `visited` set tracks schema pointers we've already processed to avoid infinite
1156 /// recursion when schemas reference each other (directly or through subresources).
1157 fn collect_external_resources_recursive(
1158 base: &Arc<Uri<String>>,
1159 root: &Value,
1160 contents: &Value,
1161 collected: &mut AHashSet<(String, Uri<String>, ReferenceKind)>,
1162 seen: &mut ReferenceTracker,
1163 resolution_cache: &mut UriCache,
1164 scratch: &mut String,
1165 refers_metaschemas: &mut bool,
1166 draft: Draft,
1167 visited: &mut AHashSet<usize>,
1168 ) -> Result<(), Error> {
1169 // Track by pointer address to avoid processing the same schema twice
1170 let ptr = std::ptr::from_ref::<Value>(contents) as usize;
1171 if !visited.insert(ptr) {
1172 return Ok(());
1173 }
1174
1175 let current_base = match draft.id_of(contents) {
1176 Some(id) => resolve_id(base, id, resolution_cache)?,
1177 None => Arc::clone(base),
1178 };
1179
1180 // First, collect from the current schema
1181 collect_external_resources(
1182 &current_base,
1183 root,
1184 contents,
1185 collected,
1186 seen,
1187 resolution_cache,
1188 scratch,
1189 refers_metaschemas,
1190 draft,
1191 visited,
1192 )?;
1193
1194 // Then recursively process all subresources
1195 for subresource in draft.subresources_of(contents) {
1196 collect_external_resources_recursive(
1197 &current_base,
1198 root,
1199 subresource,
1200 collected,
1201 seen,
1202 resolution_cache,
1203 scratch,
1204 refers_metaschemas,
1205 draft,
1206 visited,
1207 )?;
1208 }
1209 Ok(())
1210 }
1211
1212 fn mark_reference(seen: &mut ReferenceTracker, base: &Arc<Uri<String>>, reference: &str) -> bool {
1213 seen.insert(ReferenceKey::new(base, reference))
1214 }
1215
1216 /// Resolve an `$id` against a base URI, handling anchor-style IDs and empty fragments.
1217 ///
1218 /// Anchor-style `$id` values (starting with `#`) don't change the base URI.
1219 /// Empty fragments are stripped from the resolved URI.
1220 fn resolve_id(
1221 base: &Arc<Uri<String>>,
1222 id: &str,
1223 resolution_cache: &mut UriCache,
1224 ) -> Result<Arc<Uri<String>>, Error> {
1225 if id.starts_with('#') {
1226 return Ok(Arc::clone(base));
1227 }
1228 let mut resolved = (*resolution_cache.resolve_against(&base.borrow(), id)?).clone();
1229 if resolved.fragment().is_some_and(EStr::is_empty) {
1230 resolved.set_fragment(None);
1231 }
1232 Ok(Arc::new(resolved))
1233 }
1234
1235 /// Look up a value by a JSON Pointer.
1236 ///
1237 /// **NOTE**: A slightly faster version of pointer resolution based on `Value::pointer` from `serde_json`.
1238 pub fn pointer<'a>(document: &'a Value, pointer: &str) -> Option<&'a Value> {
1239 if pointer.is_empty() {
1240 return Some(document);
1241 }
1242 if !pointer.starts_with('/') {
1243 return None;
1244 }
1245 pointer.split('/').skip(1).map(unescape_segment).try_fold(
1246 document,
1247 |target, token| match target {
1248 Value::Object(map) => map.get(&*token),
1249 Value::Array(list) => parse_index(&token).and_then(|x| list.get(x)),
1250 _ => None,
1251 },
1252 )
1253 }
1254
1255 /// Look up a value by a JSON Pointer, tracking `$id` changes along the path.
1256 ///
1257 /// Returns both the resolved value and the accumulated base URI after processing
1258 /// any `$id` declarations encountered along the path. Note that anchor-style `$id`
1259 /// values (starting with `#`) don't change the base URI.
1260 #[allow(clippy::type_complexity)]
1261 fn pointer_with_base<'a>(
1262 document: &'a Value,
1263 pointer: &str,
1264 base: &Arc<Uri<String>>,
1265 resolution_cache: &mut UriCache,
1266 draft: Draft,
1267 ) -> Result<Option<(&'a Value, Arc<Uri<String>>)>, Error> {
1268 if pointer.is_empty() {
1269 return Ok(Some((document, Arc::clone(base))));
1270 }
1271 if !pointer.starts_with('/') {
1272 return Ok(None);
1273 }
1274
1275 let mut current = document;
1276 let mut current_base = Arc::clone(base);
1277
1278 for token in pointer.split('/').skip(1).map(unescape_segment) {
1279 // Check for $id in the current value before traversing deeper
1280 if let Some(id) = draft.id_of(current) {
1281 current_base = resolve_id(&current_base, id, resolution_cache)?;
1282 }
1283
1284 current = match current {
1285 Value::Object(map) => match map.get(&*token) {
1286 Some(v) => v,
1287 None => return Ok(None),
1288 },
1289 Value::Array(list) => match parse_index(&token).and_then(|x| list.get(x)) {
1290 Some(v) => v,
1291 None => return Ok(None),
1292 },
1293 _ => return Ok(None),
1294 };
1295 }
1296
1297 // Note: We don't check $id in the final value here because
1298 // `collect_external_resources_recursive` will handle it
1299 Ok(Some((current, current_base)))
1300 }
1301
1302 // Taken from `serde_json`.
1303 #[must_use]
1304 pub fn parse_index(s: &str) -> Option<usize> {
1305 if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
1306 return None;
1307 }
1308 s.parse().ok()
1309 }
1310
1311 #[cfg(test)]
1312 mod tests {
1313 use std::error::Error as _;
1314
1315 use ahash::AHashMap;
1316 use fluent_uri::Uri;
1317 use serde_json::{json, Value};
1318 use test_case::test_case;
1319
1320 use crate::{uri::from_str, Draft, Registry, Resource, Retrieve};
1321
1322 use super::{pointer, RegistryOptions, SPECIFICATIONS};
1323
1324 #[test]
1325 fn test_empty_pointer() {
1326 let document = json!({});
1327 assert_eq!(pointer(&document, ""), Some(&document));
1328 }
1329
1330 #[test]
1331 fn test_invalid_uri_on_registry_creation() {
1332 let schema = Draft::Draft202012.create_resource(json!({}));
1333 let result = Registry::try_new(":/example.com", schema);
1334 let error = result.expect_err("Should fail");
1335
1336 assert_eq!(
1337 error.to_string(),
1338 "Invalid URI reference ':/example.com': unexpected character at index 0"
1339 );
1340 let source_error = error.source().expect("Should have a source");
1341 let inner_source = source_error.source().expect("Should have a source");
1342 assert_eq!(inner_source.to_string(), "unexpected character at index 0");
1343 }
1344
1345 #[test]
1346 fn test_lookup_unresolvable_url() {
1347 // Create a registry with a single resource
1348 let schema = Draft::Draft202012.create_resource(json!({
1349 "type": "object",
1350 "properties": {
1351 "foo": { "type": "string" }
1352 }
1353 }));
1354 let registry =
1355 Registry::try_new("http://example.com/schema1", schema).expect("Invalid resources");
1356
1357 // Attempt to create a resolver for a URL not in the registry
1358 let resolver = registry
1359 .try_resolver("http://example.com/non_existent_schema")
1360 .expect("Invalid base URI");
1361
1362 let result = resolver.lookup("");
1363
1364 assert_eq!(
1365 result.unwrap_err().to_string(),
1366 "Resource 'http://example.com/non_existent_schema' is not present in a registry and retrieving it failed: Retrieving external resources is not supported once the registry is populated"
1367 );
1368 }
1369
1370 #[test]
1371 fn test_relative_uri_without_base() {
1372 let schema = Draft::Draft202012.create_resource(json!({"$ref": "./virtualNetwork.json"}));
1373 let error = Registry::try_new("json-schema:///", schema).expect_err("Should fail");
1374 assert_eq!(error.to_string(), "Resource './virtualNetwork.json' is not present in a registry and retrieving it failed: No base URI is available");
1375 }
1376
1377 #[test]
1378 fn test_try_with_resources_requires_registered_custom_meta_schema() {
1379 let base_registry = Registry::try_new(
1380 "http://example.com/root",
1381 Resource::from_contents(json!({"type": "object"})),
1382 )
1383 .expect("Base registry should be created");
1384
1385 let custom_schema = Resource::from_contents(json!({
1386 "$id": "http://example.com/custom",
1387 "$schema": "http://example.com/meta/custom",
1388 "type": "string"
1389 }));
1390
1391 let error = base_registry
1392 .try_with_resources(
1393 [("http://example.com/custom", custom_schema)],
1394 Draft::default(),
1395 )
1396 .expect_err("Extending registry must fail when the custom $schema is not registered");
1397
1398 let error_msg = error.to_string();
1399 assert_eq!(
1400 error_msg,
1401 "Unknown meta-schema: 'http://example.com/meta/custom'. Custom meta-schemas must be registered in the registry before use"
1402 );
1403 }
1404
1405 #[test]
1406 fn test_try_with_resources_accepts_registered_custom_meta_schema_fragment() {
1407 let meta_schema = Resource::from_contents(json!({
1408 "$id": "http://example.com/meta/custom#",
1409 "$schema": "https://json-schema.org/draft/2020-12/schema",
1410 "type": "object"
1411 }));
1412
1413 let registry = Registry::try_new("http://example.com/meta/custom#", meta_schema)
1414 .expect("Meta-schema should be registered successfully");
1415
1416 let schema = Resource::from_contents(json!({
1417 "$id": "http://example.com/schemas/my-schema",
1418 "$schema": "http://example.com/meta/custom#",
1419 "type": "string"
1420 }));
1421
1422 registry
1423 .clone()
1424 .try_with_resources(
1425 [("http://example.com/schemas/my-schema", schema)],
1426 Draft::default(),
1427 )
1428 .expect("Schema should accept registered meta-schema URI with trailing '#'");
1429 }
1430
1431 #[test]
1432 fn test_chained_custom_meta_schemas() {
1433 // Meta-schema B (uses standard Draft 2020-12)
1434 let meta_schema_b = json!({
1435 "$id": "json-schema:///meta/level-b",
1436 "$schema": "https://json-schema.org/draft/2020-12/schema",
1437 "$vocabulary": {
1438 "https://json-schema.org/draft/2020-12/vocab/core": true,
1439 "https://json-schema.org/draft/2020-12/vocab/validation": true,
1440 },
1441 "type": "object",
1442 "properties": {
1443 "customProperty": {"type": "string"}
1444 }
1445 });
1446
1447 // Meta-schema A (uses Meta-schema B)
1448 let meta_schema_a = json!({
1449 "$id": "json-schema:///meta/level-a",
1450 "$schema": "json-schema:///meta/level-b",
1451 "customProperty": "level-a-meta",
1452 "type": "object"
1453 });
1454
1455 // Schema (uses Meta-schema A)
1456 let schema = json!({
1457 "$id": "json-schema:///schemas/my-schema",
1458 "$schema": "json-schema:///meta/level-a",
1459 "customProperty": "my-schema",
1460 "type": "string"
1461 });
1462
1463 // Register all meta-schemas and schema in a chained manner
1464 // All resources are provided upfront, so no external retrieval should occur
1465 Registry::try_from_resources([
1466 (
1467 "json-schema:///meta/level-b",
1468 Resource::from_contents(meta_schema_b),
1469 ),
1470 (
1471 "json-schema:///meta/level-a",
1472 Resource::from_contents(meta_schema_a),
1473 ),
1474 (
1475 "json-schema:///schemas/my-schema",
1476 Resource::from_contents(schema),
1477 ),
1478 ])
1479 .expect("Chained custom meta-schemas should be accepted when all are registered");
1480 }
1481
1482 struct TestRetriever {
1483 schemas: AHashMap<String, Value>,
1484 }
1485
1486 impl TestRetriever {
1487 fn new(schemas: AHashMap<String, Value>) -> Self {
1488 TestRetriever { schemas }
1489 }
1490 }
1491
1492 impl Retrieve for TestRetriever {
1493 fn retrieve(
1494 &self,
1495 uri: &Uri<String>,
1496 ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
1497 if let Some(value) = self.schemas.get(uri.as_str()) {
1498 Ok(value.clone())
1499 } else {
1500 Err(format!("Failed to find {uri}").into())
1501 }
1502 }
1503 }
1504
1505 fn create_test_retriever(schemas: &[(&str, Value)]) -> TestRetriever {
1506 TestRetriever::new(
1507 schemas
1508 .iter()
1509 .map(|&(k, ref v)| (k.to_string(), v.clone()))
1510 .collect(),
1511 )
1512 }
1513
1514 struct TestCase {
1515 input_resources: Vec<(&'static str, Value)>,
1516 remote_resources: Vec<(&'static str, Value)>,
1517 expected_resolved_uris: Vec<&'static str>,
1518 }
1519
1520 #[test_case(
1521 TestCase {
1522 input_resources: vec![
1523 ("http://example.com/schema1", json!({"$ref": "http://example.com/schema2"})),
1524 ],
1525 remote_resources: vec![
1526 ("http://example.com/schema2", json!({"type": "object"})),
1527 ],
1528 expected_resolved_uris: vec!["http://example.com/schema1", "http://example.com/schema2"],
1529 }
1530 ;"External ref at top")]
1531 #[test_case(
1532 TestCase {
1533 input_resources: vec![
1534 ("http://example.com/schema1", json!({
1535 "$defs": {
1536 "subschema": {"type": "string"}
1537 },
1538 "$ref": "#/$defs/subschema"
1539 })),
1540 ],
1541 remote_resources: vec![],
1542 expected_resolved_uris: vec!["http://example.com/schema1"],
1543 }
1544 ;"Internal ref at top")]
1545 #[test_case(
1546 TestCase {
1547 input_resources: vec![
1548 ("http://example.com/schema1", json!({"$ref": "http://example.com/schema2"})),
1549 ("http://example.com/schema2", json!({"type": "object"})),
1550 ],
1551 remote_resources: vec![],
1552 expected_resolved_uris: vec!["http://example.com/schema1", "http://example.com/schema2"],
1553 }
1554 ;"Ref to later resource")]
1555 #[test_case(
1556 TestCase {
1557 input_resources: vec![
1558 ("http://example.com/schema1", json!({
1559 "type": "object",
1560 "properties": {
1561 "prop1": {"$ref": "http://example.com/schema2"}
1562 }
1563 })),
1564 ],
1565 remote_resources: vec![
1566 ("http://example.com/schema2", json!({"type": "string"})),
1567 ],
1568 expected_resolved_uris: vec!["http://example.com/schema1", "http://example.com/schema2"],
1569 }
1570 ;"External ref in subresource")]
1571 #[test_case(
1572 TestCase {
1573 input_resources: vec![
1574 ("http://example.com/schema1", json!({
1575 "type": "object",
1576 "properties": {
1577 "prop1": {"$ref": "#/$defs/subschema"}
1578 },
1579 "$defs": {
1580 "subschema": {"type": "string"}
1581 }
1582 })),
1583 ],
1584 remote_resources: vec![],
1585 expected_resolved_uris: vec!["http://example.com/schema1"],
1586 }
1587 ;"Internal ref in subresource")]
1588 #[test_case(
1589 TestCase {
1590 input_resources: vec![
1591 ("file:///schemas/main.json", json!({"$ref": "file:///schemas/external.json"})),
1592 ],
1593 remote_resources: vec![
1594 ("file:///schemas/external.json", json!({"type": "object"})),
1595 ],
1596 expected_resolved_uris: vec!["file:///schemas/main.json", "file:///schemas/external.json"],
1597 }
1598 ;"File scheme: external ref at top")]
1599 #[test_case(
1600 TestCase {
1601 input_resources: vec![
1602 ("file:///schemas/main.json", json!({"$ref": "subfolder/schema.json"})),
1603 ],
1604 remote_resources: vec![
1605 ("file:///schemas/subfolder/schema.json", json!({"type": "string"})),
1606 ],
1607 expected_resolved_uris: vec!["file:///schemas/main.json", "file:///schemas/subfolder/schema.json"],
1608 }
1609 ;"File scheme: relative path ref")]
1610 #[test_case(
1611 TestCase {
1612 input_resources: vec![
1613 ("file:///schemas/main.json", json!({
1614 "type": "object",
1615 "properties": {
1616 "local": {"$ref": "local.json"},
1617 "remote": {"$ref": "http://example.com/schema"}
1618 }
1619 })),
1620 ],
1621 remote_resources: vec![
1622 ("file:///schemas/local.json", json!({"type": "string"})),
1623 ("http://example.com/schema", json!({"type": "number"})),
1624 ],
1625 expected_resolved_uris: vec![
1626 "file:///schemas/main.json",
1627 "file:///schemas/local.json",
1628 "http://example.com/schema"
1629 ],
1630 }
1631 ;"File scheme: mixing with http scheme")]
1632 #[test_case(
1633 TestCase {
1634 input_resources: vec![
1635 ("file:///C:/schemas/main.json", json!({"$ref": "/D:/other_schemas/schema.json"})),
1636 ],
1637 remote_resources: vec![
1638 ("file:///D:/other_schemas/schema.json", json!({"type": "boolean"})),
1639 ],
1640 expected_resolved_uris: vec![
1641 "file:///C:/schemas/main.json",
1642 "file:///D:/other_schemas/schema.json"
1643 ],
1644 }
1645 ;"File scheme: absolute path in Windows style")]
1646 #[test_case(
1647 TestCase {
1648 input_resources: vec![
1649 ("http://example.com/schema1", json!({"$ref": "http://example.com/schema2"})),
1650 ],
1651 remote_resources: vec![
1652 ("http://example.com/schema2", json!({"$ref": "http://example.com/schema3"})),
1653 ("http://example.com/schema3", json!({"$ref": "http://example.com/schema4"})),
1654 ("http://example.com/schema4", json!({"$ref": "http://example.com/schema5"})),
1655 ("http://example.com/schema5", json!({"type": "object"})),
1656 ],
1657 expected_resolved_uris: vec![
1658 "http://example.com/schema1",
1659 "http://example.com/schema2",
1660 "http://example.com/schema3",
1661 "http://example.com/schema4",
1662 "http://example.com/schema5",
1663 ],
1664 }
1665 ;"Four levels of external references")]
1666 #[test_case(
1667 TestCase {
1668 input_resources: vec![
1669 ("http://example.com/schema1", json!({"$ref": "http://example.com/schema2"})),
1670 ],
1671 remote_resources: vec![
1672 ("http://example.com/schema2", json!({"$ref": "http://example.com/schema3"})),
1673 ("http://example.com/schema3", json!({"$ref": "http://example.com/schema4"})),
1674 ("http://example.com/schema4", json!({"$ref": "http://example.com/schema5"})),
1675 ("http://example.com/schema5", json!({"$ref": "http://example.com/schema6"})),
1676 ("http://example.com/schema6", json!({"$ref": "http://example.com/schema1"})),
1677 ],
1678 expected_resolved_uris: vec![
1679 "http://example.com/schema1",
1680 "http://example.com/schema2",
1681 "http://example.com/schema3",
1682 "http://example.com/schema4",
1683 "http://example.com/schema5",
1684 "http://example.com/schema6",
1685 ],
1686 }
1687 ;"Five levels of external references with circular reference")]
1688 fn test_references_processing(test_case: TestCase) {
1689 let retriever = create_test_retriever(&test_case.remote_resources);
1690
1691 let input_pairs = test_case
1692 .input_resources
1693 .clone()
1694 .into_iter()
1695 .map(|(uri, value)| (uri, Resource::from_contents(value)));
1696
1697 let registry = Registry::options()
1698 .retriever(retriever)
1699 .build(input_pairs)
1700 .expect("Invalid resources");
1701 // Verify that all expected URIs are resolved and present in resources
1702 for uri in test_case.expected_resolved_uris {
1703 let resolver = registry.try_resolver("").expect("Invalid base URI");
1704 assert!(resolver.lookup(uri).is_ok());
1705 }
1706 }
1707
1708 #[test]
1709 fn test_default_retriever_with_remote_refs() {
1710 let result = Registry::try_from_resources([(
1711 "http://example.com/schema1",
1712 Resource::from_contents(json!({"$ref": "http://example.com/schema2"})),
1713 )]);
1714 let error = result.expect_err("Should fail");
1715 assert_eq!(error.to_string(), "Resource 'http://example.com/schema2' is not present in a registry and retrieving it failed: Default retriever does not fetch resources");
1716 assert!(error.source().is_some());
1717 }
1718
1719 #[test]
1720 fn test_options() {
1721 let _registry = RegistryOptions::default()
1722 .build([("", Resource::from_contents(json!({})))])
1723 .expect("Invalid resources");
1724 }
1725
1726 #[test]
1727 fn test_registry_with_duplicate_input_uris() {
1728 let input_resources = vec![
1729 (
1730 "http://example.com/schema",
1731 json!({
1732 "type": "object",
1733 "properties": {
1734 "foo": { "type": "string" }
1735 }
1736 }),
1737 ),
1738 (
1739 "http://example.com/schema",
1740 json!({
1741 "type": "object",
1742 "properties": {
1743 "bar": { "type": "number" }
1744 }
1745 }),
1746 ),
1747 ];
1748
1749 let result = Registry::try_from_resources(
1750 input_resources
1751 .into_iter()
1752 .map(|(uri, value)| (uri, Draft::Draft202012.create_resource(value))),
1753 );
1754
1755 assert!(
1756 result.is_ok(),
1757 "Failed to create registry with duplicate input URIs"
1758 );
1759 let registry = result.unwrap();
1760
1761 let resource = registry
1762 .resources
1763 .get(&from_str("http://example.com/schema").expect("Invalid URI"))
1764 .unwrap();
1765 let properties = resource
1766 .contents()
1767 .get("properties")
1768 .and_then(|v| v.as_object())
1769 .unwrap();
1770
1771 assert!(
1772 !properties.contains_key("bar"),
1773 "Registry should contain the earliest added schema"
1774 );
1775 assert!(
1776 properties.contains_key("foo"),
1777 "Registry should contain the overwritten schema"
1778 );
1779 }
1780
1781 #[test]
1782 fn test_resolver_debug() {
1783 let registry = SPECIFICATIONS
1784 .clone()
1785 .try_with_resource("http://example.com", Resource::from_contents(json!({})))
1786 .expect("Invalid resource");
1787 let resolver = registry
1788 .try_resolver("http://127.0.0.1/schema")
1789 .expect("Invalid base URI");
1790 assert_eq!(
1791 format!("{resolver:?}"),
1792 "Resolver { base_uri: \"http://127.0.0.1/schema\", scopes: \"[]\" }"
1793 );
1794 }
1795
1796 #[test]
1797 fn test_try_with_resource() {
1798 let registry = SPECIFICATIONS
1799 .clone()
1800 .try_with_resource("http://example.com", Resource::from_contents(json!({})))
1801 .expect("Invalid resource");
1802 let resolver = registry.try_resolver("").expect("Invalid base URI");
1803 let resolved = resolver
1804 .lookup("http://json-schema.org/draft-06/schema#/definitions/schemaArray")
1805 .expect("Lookup failed");
1806 assert_eq!(
1807 resolved.contents(),
1808 &json!({
1809 "type": "array",
1810 "minItems": 1,
1811 "items": { "$ref": "#" }
1812 })
1813 );
1814 }
1815
1816 #[test]
1817 fn test_invalid_reference() {
1818 // Found via fuzzing
1819 let resource = Draft::Draft202012.create_resource(json!({"$schema": "$##"}));
1820 let _ = Registry::try_new("http://#/", resource);
1821 }
1822 }
1823
1824 #[cfg(all(test, feature = "retrieve-async"))]
1825 mod async_tests {
1826 use crate::{uri, DefaultRetriever, Draft, Registry, Resource, Uri};
1827 use ahash::AHashMap;
1828 use serde_json::{json, Value};
1829 use std::error::Error;
1830
1831 struct TestAsyncRetriever {
1832 schemas: AHashMap<String, Value>,
1833 }
1834
1835 impl TestAsyncRetriever {
1836 fn with_schema(uri: impl Into<String>, schema: Value) -> Self {
1837 TestAsyncRetriever {
1838 schemas: { AHashMap::from_iter([(uri.into(), schema)]) },
1839 }
1840 }
1841 }
1842
1843 #[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
1844 #[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
1845 impl crate::AsyncRetrieve for TestAsyncRetriever {
1846 async fn retrieve(
1847 &self,
1848 uri: &Uri<String>,
1849 ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
1850 self.schemas
1851 .get(uri.as_str())
1852 .cloned()
1853 .ok_or_else(|| "Schema not found".into())
1854 }
1855 }
1856
1857 #[tokio::test]
1858 async fn test_default_async_retriever_with_remote_refs() {
1859 let result = Registry::options()
1860 .async_retriever(DefaultRetriever)
1861 .build([(
1862 "http://example.com/schema1",
1863 Resource::from_contents(json!({"$ref": "http://example.com/schema2"})),
1864 )])
1865 .await;
1866
1867 let error = result.expect_err("Should fail");
1868 assert_eq!(error.to_string(), "Resource 'http://example.com/schema2' is not present in a registry and retrieving it failed: Default retriever does not fetch resources");
1869 assert!(error.source().is_some());
1870 }
1871
1872 #[tokio::test]
1873 async fn test_async_options() {
1874 let _registry = Registry::options()
1875 .async_retriever(DefaultRetriever)
1876 .build([("", Draft::default().create_resource(json!({})))])
1877 .await
1878 .expect("Invalid resources");
1879 }
1880
1881 #[tokio::test]
1882 async fn test_async_registry_with_duplicate_input_uris() {
1883 let input_resources = vec![
1884 (
1885 "http://example.com/schema",
1886 json!({
1887 "type": "object",
1888 "properties": {
1889 "foo": { "type": "string" }
1890 }
1891 }),
1892 ),
1893 (
1894 "http://example.com/schema",
1895 json!({
1896 "type": "object",
1897 "properties": {
1898 "bar": { "type": "number" }
1899 }
1900 }),
1901 ),
1902 ];
1903
1904 let result = Registry::options()
1905 .async_retriever(DefaultRetriever)
1906 .build(
1907 input_resources
1908 .into_iter()
1909 .map(|(uri, value)| (uri, Draft::Draft202012.create_resource(value))),
1910 )
1911 .await;
1912
1913 assert!(
1914 result.is_ok(),
1915 "Failed to create registry with duplicate input URIs"
1916 );
1917 let registry = result.unwrap();
1918
1919 let resource = registry
1920 .resources
1921 .get(&uri::from_str("http://example.com/schema").expect("Invalid URI"))
1922 .unwrap();
1923 let properties = resource
1924 .contents()
1925 .get("properties")
1926 .and_then(|v| v.as_object())
1927 .unwrap();
1928
1929 assert!(
1930 !properties.contains_key("bar"),
1931 "Registry should contain the earliest added schema"
1932 );
1933 assert!(
1934 properties.contains_key("foo"),
1935 "Registry should contain the overwritten schema"
1936 );
1937 }
1938
1939 #[tokio::test]
1940 async fn test_async_try_with_resource() {
1941 let retriever = TestAsyncRetriever::with_schema(
1942 "http://example.com/schema2",
1943 json!({"type": "object"}),
1944 );
1945
1946 let registry = Registry::options()
1947 .async_retriever(retriever)
1948 .build([(
1949 "http://example.com",
1950 Resource::from_contents(json!({"$ref": "http://example.com/schema2"})),
1951 )])
1952 .await
1953 .expect("Invalid resource");
1954
1955 let resolver = registry.try_resolver("").expect("Invalid base URI");
1956 let resolved = resolver
1957 .lookup("http://example.com/schema2")
1958 .expect("Lookup failed");
1959 assert_eq!(resolved.contents(), &json!({"type": "object"}));
1960 }
1961
1962 #[tokio::test]
1963 async fn test_async_registry_with_multiple_refs() {
1964 let retriever = TestAsyncRetriever {
1965 schemas: AHashMap::from_iter([
1966 (
1967 "http://example.com/schema2".to_string(),
1968 json!({"type": "object"}),
1969 ),
1970 (
1971 "http://example.com/schema3".to_string(),
1972 json!({"type": "string"}),
1973 ),
1974 ]),
1975 };
1976
1977 let registry = Registry::options()
1978 .async_retriever(retriever)
1979 .build([(
1980 "http://example.com/schema1",
1981 Resource::from_contents(json!({
1982 "type": "object",
1983 "properties": {
1984 "obj": {"$ref": "http://example.com/schema2"},
1985 "str": {"$ref": "http://example.com/schema3"}
1986 }
1987 })),
1988 )])
1989 .await
1990 .expect("Invalid resource");
1991
1992 let resolver = registry.try_resolver("").expect("Invalid base URI");
1993
1994 // Check both references are resolved correctly
1995 let resolved2 = resolver
1996 .lookup("http://example.com/schema2")
1997 .expect("Lookup failed");
1998 assert_eq!(resolved2.contents(), &json!({"type": "object"}));
1999
2000 let resolved3 = resolver
2001 .lookup("http://example.com/schema3")
2002 .expect("Lookup failed");
2003 assert_eq!(resolved3.contents(), &json!({"type": "string"}));
2004 }
2005
2006 #[tokio::test]
2007 async fn test_async_registry_with_nested_refs() {
2008 let retriever = TestAsyncRetriever {
2009 schemas: AHashMap::from_iter([
2010 (
2011 "http://example.com/address".to_string(),
2012 json!({
2013 "type": "object",
2014 "properties": {
2015 "street": {"type": "string"},
2016 "city": {"$ref": "http://example.com/city"}
2017 }
2018 }),
2019 ),
2020 (
2021 "http://example.com/city".to_string(),
2022 json!({
2023 "type": "string",
2024 "minLength": 1
2025 }),
2026 ),
2027 ]),
2028 };
2029
2030 let registry = Registry::options()
2031 .async_retriever(retriever)
2032 .build([(
2033 "http://example.com/person",
2034 Resource::from_contents(json!({
2035 "type": "object",
2036 "properties": {
2037 "name": {"type": "string"},
2038 "address": {"$ref": "http://example.com/address"}
2039 }
2040 })),
2041 )])
2042 .await
2043 .expect("Invalid resource");
2044
2045 let resolver = registry.try_resolver("").expect("Invalid base URI");
2046
2047 // Verify nested reference resolution
2048 let resolved = resolver
2049 .lookup("http://example.com/city")
2050 .expect("Lookup failed");
2051 assert_eq!(
2052 resolved.contents(),
2053 &json!({"type": "string", "minLength": 1})
2054 );
2055 }
2056 }