reference_manager.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. #pragma once
  2. #include <functional>
  3. #include <map>
  4. #include <set>
  5. #include <unordered_map>
  6. #include <jvalidate/detail/anchor.h>
  7. #include <jvalidate/detail/dynamic_reference_context.h>
  8. #include <jvalidate/detail/expect.h>
  9. #include <jvalidate/detail/on_block_exit.h>
  10. #include <jvalidate/detail/out.h>
  11. #include <jvalidate/detail/parser_context.h>
  12. #include <jvalidate/detail/pointer.h>
  13. #include <jvalidate/detail/reference.h>
  14. #include <jvalidate/detail/reference_cache.h>
  15. #include <jvalidate/detail/vocabulary.h>
  16. #include <jvalidate/document_cache.h>
  17. #include <jvalidate/enum.h>
  18. #include <jvalidate/forward.h>
  19. #include <jvalidate/uri.h>
  20. #include <unordered_set>
  21. namespace jvalidate::detail {
  22. template <Adapter A> class ReferenceManager {
  23. public:
  24. using Keywords = std::unordered_map<std::string_view, std::set<schema::Wraps>>;
  25. private:
  26. static inline std::map<std::string_view, schema::Version> const g_schema_ids{
  27. {"json-schema.org/draft-03/schema", schema::Version::Draft03},
  28. {"json-schema.org/draft-04/schema", schema::Version::Draft04},
  29. {"json-schema.org/draft-06/schema", schema::Version::Draft06},
  30. {"json-schema.org/draft-07/schema", schema::Version::Draft07},
  31. {"json-schema.org/draft/2019-09/schema", schema::Version::Draft2019_09},
  32. {"json-schema.org/draft/2020-12/schema", schema::Version::Draft2020_12},
  33. };
  34. ConstraintFactory<A> const & constraints_;
  35. DocumentCache<A> & external_;
  36. ReferenceCache references_;
  37. std::map<schema::Version, Vocabulary<A>> vocabularies_;
  38. std::map<URI, Vocabulary<A>> user_vocabularies_;
  39. std::map<RootReference, A> roots_;
  40. std::map<URI, std::map<Anchor, Reference>> dynamic_anchors_;
  41. DynamicReferenceContext active_dynamic_anchors_;
  42. public:
  43. ReferenceManager(DocumentCache<A> & external, A const & root, schema::Version version,
  44. ConstraintFactory<A> const & constraints)
  45. : external_(external), constraints_(constraints), roots_{{{}, root}} {
  46. prime(root, {}, &vocab(version));
  47. }
  48. Vocabulary<A> const & vocab(schema::Version version) {
  49. if (not vocabularies_.contains(version)) {
  50. vocabularies_.emplace(version, constraints_.keywords(version));
  51. }
  52. return vocabularies_.at(version);
  53. }
  54. Vocabulary<A> const & vocab(URI schema) {
  55. if (auto it = g_schema_ids.find(schema.resource()); it != g_schema_ids.end()) {
  56. return vocab(it->second);
  57. }
  58. if (auto it = user_vocabularies_.find(schema); it != user_vocabularies_.end()) {
  59. return it->second;
  60. }
  61. std::optional<A> external = external_.try_load(schema);
  62. EXPECT_M(external.has_value(), "Unable to load external meta-schema " << schema);
  63. EXPECT_M(external->type() == adapter::Type::Object, "meta-schema must be an object");
  64. auto metaschema = external->as_object();
  65. EXPECT_M(metaschema.contains("$schema"), "meta-schema must reference an");
  66. // Initialize first to prevent recursion
  67. Vocabulary<A> & parent = user_vocabularies_[schema];
  68. parent = vocab(URI(metaschema["$schema"].as_string()));
  69. if (metaschema.contains("$vocabulary")) {
  70. auto [keywords, vocabularies] = extract_keywords(metaschema["$vocabulary"].as_object());
  71. parent.restrict(keywords, vocabularies);
  72. }
  73. return parent;
  74. }
  75. auto dynamic_scope(Reference const & ref) {
  76. URI const uri =
  77. ref.pointer().empty() ? ref.uri() : references_.relative_to_nearest_anchor(ref).uri();
  78. return active_dynamic_anchors_.scope(uri, dynamic_anchors_[uri]);
  79. }
  80. std::optional<A> load(Reference const & ref, schema::Version version) {
  81. if (auto it = roots_.find(ref.root()); it != roots_.end()) {
  82. return ref.pointer().walk(it->second);
  83. }
  84. std::optional<A> external = external_.try_load(ref.uri());
  85. if (not external) {
  86. return std::nullopt;
  87. }
  88. // TODO(samjaffe): Change Versions if needed...
  89. references_.emplace(ref.uri());
  90. prime(*external, ref, &vocab(version));
  91. // May have a sub-id that we map to
  92. if (auto it = roots_.find(ref.root()); it != roots_.end()) {
  93. return ref.pointer().walk(it->second);
  94. }
  95. // Will get called if the external schema does not declare a root document id?
  96. return ref.pointer().walk(*external);
  97. }
  98. Reference canonicalize(Reference const & ref, Reference const & parent,
  99. inout<bool> dynamic_reference) {
  100. URI const uri = [this, &ref, &parent]() {
  101. if (ref.uri().empty() && parent.uri().empty()) {
  102. return references_.actual_parent_uri(parent);
  103. }
  104. URI uri = ref.uri().empty() ? parent.uri() : ref.uri();
  105. if (not uri.is_rootless()) {
  106. return uri;
  107. }
  108. URI base = references_.actual_parent_uri(parent);
  109. EXPECT_M(base.resource().rfind('/') != std::string::npos,
  110. "Unable to deduce root for relative uri " << uri << " (" << base << ")");
  111. if (not uri.is_relative()) {
  112. return base.root() / uri;
  113. }
  114. if (auto br = base.resource(), ur = uri.resource();
  115. br.ends_with(ur) && br[br.size() - ur.size() - 1] == '/') {
  116. return base;
  117. }
  118. return base.parent() / uri;
  119. }();
  120. URI const dyn_uri = ref.uri().empty() ? ref.uri() : uri;
  121. if (std::optional dynref = dynamic(dyn_uri, ref, dynamic_reference)) {
  122. return *dynref;
  123. }
  124. dynamic_reference = dynamic_reference || active_dynamic_anchors_.empty();
  125. // Relative URI, not in the HEREDOC (or we set an $id)
  126. if (ref.uri().empty() and ref.anchor().empty()) {
  127. return Reference(references_.relative_to_nearest_anchor(parent).root(), ref.pointer());
  128. }
  129. return Reference(uri, ref.anchor(), ref.pointer());
  130. }
  131. private:
  132. std::optional<Reference> dynamic(URI const & uri, Reference const & ref,
  133. inout<bool> dynamic_reference) {
  134. bool const anchor_is_dynamic = active_dynamic_anchors_.contains(ref.anchor());
  135. if (not dynamic_reference) {
  136. // A normal $ref to an $anchor that matches a $dynamicAnchor breaks the
  137. // dynamic recursion pattern. This requires that we are not looking for a
  138. // subschema of the anchor AND that we are not targetting an anchor in a
  139. // different root document.
  140. dynamic_reference = (anchor_is_dynamic && ref.uri().empty() && ref.pointer().empty());
  141. return std::nullopt;
  142. }
  143. OnBlockExit scope;
  144. if (not ref.uri().empty() && anchor_is_dynamic) {
  145. // Register the scope of this (potential) $dynamicAnchor BEFORE we attempt
  146. // to enter the reference, in case we end up pointing to an otherwise
  147. // suppressed $dynamicAnchor in a higher scope.
  148. scope = dynamic_scope(Reference(uri));
  149. }
  150. return active_dynamic_anchors_.lookup(uri, ref.anchor());
  151. }
  152. void prime(Adapter auto const & json, Reference where, Vocabulary<A> const * vocab) {
  153. if (json.type() != adapter::Type::Object) {
  154. return;
  155. }
  156. canonicalize(where, vocab->version(), json);
  157. auto schema = json.as_object();
  158. if (schema.contains("$schema")) {
  159. vocab = &this->vocab(URI(schema["$schema"].as_string()));
  160. }
  161. for (auto const & [key, value] : schema) {
  162. if (not vocab->is_keyword(key)) {
  163. continue;
  164. }
  165. switch (value.type()) {
  166. case adapter::Type::Array: {
  167. size_t index = 0;
  168. for (auto const & elem : value.as_array()) {
  169. prime(elem, where / key / index, vocab);
  170. ++index;
  171. }
  172. break;
  173. }
  174. case adapter::Type::Object:
  175. if (not vocab->is_property_keyword(key)) {
  176. prime(value, where / key, vocab);
  177. break;
  178. }
  179. for (auto const & [prop, elem] : value.as_object()) {
  180. prime(elem, where / key / prop, vocab);
  181. }
  182. default:
  183. break;
  184. }
  185. }
  186. }
  187. void canonicalize(Reference & where, schema::Version version, A const & json) {
  188. std::string const id = version <= schema::Version::Draft04 ? "id" : "$id";
  189. auto const schema = json.as_object();
  190. RootReference root = where.root();
  191. if (schema.contains(id)) {
  192. root = RootReference(schema[id].as_string());
  193. if (root.uri().empty()) {
  194. root = RootReference(where.uri(), root.anchor());
  195. } else if (not root.uri().is_rootless() || where.uri().empty()) {
  196. // By definition - rootless URIs cannot be relative
  197. } else if (root.uri().is_relative()) {
  198. root = RootReference(where.uri().parent() / root.uri(), root.anchor());
  199. } else {
  200. root = RootReference(where.uri().root() / root.uri(), root.anchor());
  201. }
  202. roots_.emplace(root, json);
  203. where = references_.emplace(where, root);
  204. }
  205. // $anchor and its related keywords were introduced in Draft 2019-09
  206. if (version < schema::Version::Draft2019_09) {
  207. return;
  208. }
  209. if (schema.contains("$anchor")) {
  210. root = RootReference(root.uri(), Anchor(schema["$anchor"].as_string()));
  211. roots_.emplace(root, json);
  212. where = references_.emplace(where, root);
  213. }
  214. if (version == schema::Version::Draft2019_09 && schema.contains("$recursiveAnchor") &&
  215. schema["$recursiveAnchor"].as_boolean()) {
  216. Anchor anchor;
  217. root = RootReference(root.uri(), anchor);
  218. roots_.emplace(root, json);
  219. where = references_.emplace(where, root);
  220. if (Reference & dynamic = dynamic_anchors_[root.uri()][anchor];
  221. dynamic == Reference() || where < dynamic) {
  222. dynamic = where;
  223. }
  224. }
  225. if (schema.contains("$dynamicAnchor") && version > schema::Version::Draft2019_09) {
  226. Anchor anchor(schema["$dynamicAnchor"].as_string());
  227. root = RootReference(root.uri(), anchor);
  228. roots_.emplace(root, json);
  229. where = references_.emplace(where, root);
  230. if (Reference & dynamic = dynamic_anchors_[root.uri()][anchor];
  231. dynamic == Reference() || where < dynamic) {
  232. dynamic = where;
  233. }
  234. }
  235. }
  236. auto extract_keywords(ObjectAdapter auto const & vocabularies) const
  237. -> std::pair<std::unordered_set<std::string>, std::unordered_set<std::string>> {
  238. std::unordered_set<std::string> keywords;
  239. std::unordered_set<std::string> vocab_docs;
  240. for (auto [vocab, enabled] : vocabularies) {
  241. if (not enabled.as_boolean()) {
  242. continue;
  243. }
  244. size_t n = vocab.find("/vocab/");
  245. vocab_docs.emplace(vocab.substr(n));
  246. vocab.replace(n, 7, "/meta/");
  247. auto vocab_object = external_.try_load(URI(vocab));
  248. for (auto const & [keyword, _] : vocab_object->as_object()["properties"].as_object()) {
  249. keywords.insert(keyword);
  250. }
  251. }
  252. return std::make_pair(keywords, vocab_docs);
  253. }
  254. };
  255. }