reference_manager.h 10 KB

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