schema.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #pragma once
  2. #include <memory>
  3. #include <type_traits>
  4. #include <unordered_map>
  5. #include <vector>
  6. #include <jvalidate/adapter.h>
  7. #include <jvalidate/constraint.h>
  8. #include <jvalidate/detail/anchor.h>
  9. #include <jvalidate/detail/expect.h>
  10. #include <jvalidate/detail/on_block_exit.h>
  11. #include <jvalidate/detail/parser_context.h>
  12. #include <jvalidate/detail/pointer.h>
  13. #include <jvalidate/detail/reference.h>
  14. #include <jvalidate/document_cache.h>
  15. #include <jvalidate/enum.h>
  16. #include <jvalidate/forward.h>
  17. #include <jvalidate/reference_handler.h>
  18. namespace jvalidate::schema {
  19. class Node {
  20. private:
  21. std::string description_;
  22. std::unique_ptr<adapter::Const const> default_{nullptr};
  23. detail::Reference uri_;
  24. std::optional<std::string> rejects_all_;
  25. std::optional<schema::Node const *> reference_{};
  26. std::unordered_map<std::string, std::unique_ptr<constraint::Constraint>> constraints_{};
  27. std::unordered_map<std::string, std::unique_ptr<constraint::Constraint>> post_constraints_{};
  28. protected:
  29. static Version schema_version(std::string_view url);
  30. static Version schema_version(Adapter auto const & json);
  31. static Version schema_version(Adapter auto const & json, Version default_version);
  32. public:
  33. Node() = default;
  34. Node(std::string const & rejection_reason) : rejects_all_(rejection_reason) {}
  35. template <Adapter A> void construct(detail::ParserContext<A> context);
  36. bool is_pure_reference() const {
  37. return reference_ && constraints_.empty() && post_constraints_.empty() && not default_;
  38. }
  39. std::optional<std::string> const & rejects_all() const { return rejects_all_; }
  40. std::optional<schema::Node const *> reference_schema() const { return reference_; }
  41. bool requires_result_context() const { return not post_constraints_.empty(); }
  42. auto const & constraints() const { return constraints_; }
  43. auto const & post_constraints() const { return post_constraints_; }
  44. adapter::Const const * default_value() const { return default_.get(); }
  45. private:
  46. template <Adapter A> detail::OnBlockExit resolve_anchor(detail::ParserContext<A> & context);
  47. template <Adapter A> bool resolve_reference(detail::ParserContext<A> const & context);
  48. };
  49. inline Version Node::schema_version(std::string_view url) {
  50. static std::map<std::string_view, Version> const g_schema_ids{
  51. {"json-schema.org/draft-04/schema", Version::Draft04},
  52. {"json-schema.org/draft-06/schema", Version::Draft06},
  53. {"json-schema.org/draft-07/schema", Version::Draft07},
  54. {"json-schema.org/draft/2019-09/schema", Version::Draft2019_09},
  55. {"json-schema.org/draft/2020-12/schema", Version::Draft2020_12},
  56. };
  57. if (url.ends_with('#')) {
  58. url.remove_suffix(1);
  59. }
  60. if (url.starts_with("http://") || url.starts_with("https://")) {
  61. url.remove_prefix(url.find(':') + 3);
  62. }
  63. auto it = g_schema_ids.find(url);
  64. EXPECT_T(it != g_schema_ids.end(), std::invalid_argument, url);
  65. return it->second;
  66. }
  67. Version Node::schema_version(Adapter auto const & json) {
  68. EXPECT(json.type() == adapter::Type::Object);
  69. EXPECT(json.as_object().contains("$schema"));
  70. auto const & schema = json.as_object()["$schema"];
  71. EXPECT(schema.type() == adapter::Type::String);
  72. return schema_version(schema.as_string());
  73. }
  74. Version Node::schema_version(Adapter auto const & json, Version default_version) {
  75. RETURN_UNLESS(json.type() == adapter::Type::Object, default_version);
  76. RETURN_UNLESS(json.as_object().contains("$schema"), default_version);
  77. auto const & schema = json.as_object()["$schema"];
  78. RETURN_UNLESS(schema.type() == adapter::Type::String, default_version);
  79. return schema_version(schema.as_string());
  80. }
  81. }
  82. namespace jvalidate {
  83. class Schema : public schema::Node {
  84. private:
  85. friend class schema::Node;
  86. template <Adapter A> friend class detail::ParserContext;
  87. struct DynamicRef {
  88. template <typename F>
  89. DynamicRef(detail::Reference const & where, F const & reconstruct)
  90. : where(where), reconstruct(reconstruct) {}
  91. detail::Reference where;
  92. std::function<schema::Node const *()> reconstruct;
  93. };
  94. private:
  95. schema::Node accept_;
  96. schema::Node reject_{"always false"};
  97. // A map of anchors to DynamicRef info - note that DynamicRef.reconstruct is
  98. // an unsafe object, because it holds an object which may hold references to
  99. // temporary objects.
  100. // Nothing should be added to this object except through calling
  101. // {@see Node::resolve_anchor}, which returns a scope(exit) construct that
  102. // cleans up the element.
  103. std::map<detail::Anchor, DynamicRef> dynamic_anchors_;
  104. // An owning cache of all created schemas. Avoids storing duplicates such as
  105. // the "always-true" schema, "always-false" schema, and schemas whose only
  106. // meaningful field is "$ref", "$recursiveRef", or "$dynamicRef".
  107. std::map<detail::Reference, schema::Node> cache_;
  108. // A non-owning cache of all schemas, including duplcates where multiple
  109. // References map to the same underlying schema.
  110. std::map<detail::Reference, schema::Node const *> alias_cache_;
  111. public:
  112. /**
  113. * @brief Construct a new schema. All other constructors of this type may be
  114. * considered syntactic sugar for this constructor.
  115. *
  116. * As such, the true signature of this class's contructor is:
  117. *
  118. * Schema(Adapter| JSON
  119. * [, schema::Version]
  120. * [, URIResolver<A> | DocumentCache<A> &]
  121. * [, ConstraintFactory<A> const &])
  122. *
  123. * as long as the order of arguments is preserved - the constructor will work
  124. * no matter which arguments are ignored. The only required argument being
  125. * the JSON object/Adapter.
  126. *
  127. * @param json An adapter to a json object
  128. *
  129. * @param version The json-schema draft version that all schemas will prefer
  130. *
  131. * @param external An object capable of resolving URIs, and turning them into
  132. * Adapter objects. Holds a cache and so must be mutable.
  133. *
  134. * @param factory An object that manuafactures constraints - allows the user
  135. * to provide custom extensions or even modify the behavior of existing
  136. * keywords by overridding the virtual accessor function(s).
  137. */
  138. template <Adapter A>
  139. Schema(A const & json, schema::Version version, DocumentCache<A> & external,
  140. ConstraintFactory<A> const & factory = {}) {
  141. // Prevent unintialized data caches
  142. if (version >= schema::Version::Draft06 && json.type() == adapter::Type::Boolean) {
  143. schema::Node::operator=(std::move(json.as_boolean() ? accept_ : reject_));
  144. return;
  145. }
  146. ReferenceManager<A> ref(json, version, factory.keywords(version));
  147. detail::ParserContext<A> root{*this, json, version, factory, external, ref};
  148. construct(root);
  149. }
  150. /**
  151. * @param json An adapter to a json schema
  152. *
  153. * @param version The json-schema draft version that all schemas will prefer
  154. *
  155. * @param external An object capable of resolving URIs, and turning them into
  156. * Adapter objects. Holds a cache and so must be mutable. If this constructor
  157. * is called, then it means that the cache is a one-off object, and will not
  158. * be reused.
  159. */
  160. template <Adapter A, typename... Args>
  161. Schema(A const & json, schema::Version version, DocumentCache<A> && external, Args &&... args)
  162. : Schema(json, version, external, std::forward<Args>(args)...) {}
  163. /**
  164. * @param json An adapter to a json schema
  165. *
  166. * @param version The json-schema draft version that all schemas will prefer
  167. *
  168. * @param resolve A function capable of resolving URIs, and storing the
  169. * contents in a provided concrete JSON object.
  170. */
  171. template <Adapter A, typename... Args>
  172. Schema(A const & json, schema::Version version, URIResolver<A> resolve, Args &&... args)
  173. : Schema(json, version, DocumentCache<A>(resolve), std::forward<Args>(args)...) {}
  174. /**
  175. * @param json An adapter to a json schema
  176. *
  177. * @param version The json-schema draft version that all schemas will prefer
  178. */
  179. template <Adapter A, Not<DocumentCache<A>>... Args>
  180. Schema(A const & json, schema::Version version, Args &&... args)
  181. : Schema(json, version, DocumentCache<A>(), std::forward<Args>(args)...) {}
  182. /**
  183. * @param json An adapter to a json schema
  184. */
  185. template <Adapter A, Not<schema::Version>... Args>
  186. explicit Schema(A const & json, Args &&... args)
  187. : Schema(json, schema_version(json), std::forward<Args>(args)...) {}
  188. /**
  189. * @param json Any non-adapter (JSON) object. Will be immedately converted
  190. * into an Adapter object to allow us to walk through it w/o specialization.
  191. */
  192. template <typename JSON, typename... Args>
  193. explicit Schema(JSON const & json, Args &&... args)
  194. : Schema(adapter::AdapterFor<JSON const>(json), std::forward<Args>(args)...) {}
  195. private:
  196. template <Adapter A>
  197. void dynamic_anchor(detail::Anchor const & anchor, detail::ParserContext<A> const & context) {
  198. dynamic_anchors_.try_emplace(anchor, context.where,
  199. [this, context]() { return fetch_schema(context); });
  200. }
  201. void remove_dynamic_anchor(detail::Anchor const & anchor, detail::Reference const & where) {
  202. if (auto it = dynamic_anchors_.find(anchor);
  203. it != dynamic_anchors_.end() && it->second.where == where) {
  204. dynamic_anchors_.erase(it);
  205. }
  206. }
  207. schema::Node const * alias(detail::Reference const & where, schema::Node const * schema) {
  208. alias_cache_.emplace(where, schema);
  209. return schema;
  210. }
  211. std::optional<schema::Node const *> from_cache(detail::Reference const & ref) {
  212. if (auto it = alias_cache_.find(ref); it != alias_cache_.end()) {
  213. return it->second;
  214. }
  215. return std::nullopt;
  216. }
  217. template <Adapter A>
  218. schema::Node const * resolve(detail::Reference ref, detail::ParserContext<A> const & context) {
  219. ref = context.ref.canonicalize(ref, context.where);
  220. // Special case if the root-level document does not have an $id property
  221. if (std::optional root = context.ref.root(ref.root())) {
  222. return fetch_schema(context.rebind(ref.pointer().walk(*root), ref));
  223. }
  224. if (std::optional cached = from_cache(ref)) {
  225. return *cached;
  226. }
  227. std::optional schema = context.external.try_load(ref.uri());
  228. if (not schema.has_value()) {
  229. std::string error = "URIResolver could not resolve " + std::string(ref.uri());
  230. return alias(ref, &cache_.try_emplace(ref, error).first->second);
  231. }
  232. context.ref.prime(*schema, ref.root(), context.version,
  233. context.factory.keywords(context.version));
  234. ref = context.ref.canonicalize(ref, context.where);
  235. return fetch_schema(context.rebind(ref.pointer().walk(*schema), ref));
  236. }
  237. schema::Node const * resolve_dynamic(detail::Anchor const & ref) {
  238. auto it = dynamic_anchors_.find(ref);
  239. EXPECT_M(it != dynamic_anchors_.end(), "Unmatched $dynamicRef '" << ref << "'");
  240. return it->second.reconstruct();
  241. }
  242. template <Adapter A> schema::Node const * fetch_schema(detail::ParserContext<A> const & context) {
  243. // TODO(samjaffe): No longer promises uniqueness - instead track unique URI's
  244. if (std::optional cached = from_cache(context.where)) {
  245. return *cached;
  246. }
  247. adapter::Type const type = context.schema.type();
  248. if (type == adapter::Type::Boolean && context.version >= schema::Version::Draft06) {
  249. return alias(context.where, context.schema.as_boolean() ? &accept_ : &reject_);
  250. }
  251. EXPECT_M(type == adapter::Type::Object, "invalid schema at " << context.where);
  252. if (context.schema.object_size() == 0) {
  253. return alias(context.where, &accept_);
  254. }
  255. auto [it, created] = cache_.try_emplace(context.where);
  256. EXPECT_M(created, "creating duplicate schema at... " << context.where);
  257. // Do this here first in order to protect from infinite loops
  258. alias(context.where, &it->second);
  259. it->second.construct(context);
  260. if (not it->second.is_pure_reference()) {
  261. return &it->second;
  262. }
  263. // Special Case - if the only is the reference constraint, then we don't need
  264. // to store it uniquely. Draft2019_09 supports directly extending a $ref schema
  265. // in the same schema, instead of requiring an allOf clause.
  266. schema::Node const * node = *it->second.reference_schema();
  267. cache_.erase(it);
  268. return alias_cache_[context.where] = node;
  269. }
  270. };
  271. }
  272. namespace jvalidate::detail {
  273. template <Adapter A> schema::Node const * ParserContext<A>::node() const {
  274. return root.fetch_schema(*this);
  275. }
  276. template <Adapter A> schema::Node const * ParserContext<A>::always() const {
  277. return fixed_schema(schema.as_boolean());
  278. }
  279. template <Adapter A> schema::Node const * ParserContext<A>::fixed_schema(bool accept) const {
  280. return accept ? &root.accept_ : &root.reject_;
  281. }
  282. }
  283. namespace jvalidate::schema {
  284. template <Adapter A> detail::OnBlockExit Node::resolve_anchor(detail::ParserContext<A> & context) {
  285. auto const schema = context.schema.as_object();
  286. if (schema.contains("$anchor")) {
  287. return nullptr;
  288. }
  289. if (context.version == Version::Draft2019_09 && schema.contains("$recursiveAnchor")) {
  290. EXPECT_M(schema["$recursiveAnchor"].as_boolean(), "$recursiveAnchor MUST be 'true'");
  291. context.root.dynamic_anchor(detail::Anchor(), context);
  292. return [&context]() { context.root.remove_dynamic_anchor(detail::Anchor(), context.where); };
  293. }
  294. if (context.version > Version::Draft2019_09 && schema.contains("$dynamicAnchor")) {
  295. detail::Anchor anchor(schema["$dynamicAnchor"].as_string());
  296. context.root.dynamic_anchor(anchor, context);
  297. return [&context, anchor]() { context.root.remove_dynamic_anchor(anchor, context.where); };
  298. }
  299. return nullptr;
  300. }
  301. template <Adapter A> bool Node::resolve_reference(detail::ParserContext<A> const & context) {
  302. auto const schema = context.schema.as_object();
  303. if (schema.contains("$ref")) {
  304. detail::Reference ref(schema["$ref"].as_string());
  305. reference_ = context.root.resolve(ref, context);
  306. return true;
  307. }
  308. if (context.version < Version::Draft2019_09) {
  309. return false;
  310. }
  311. if (context.version == Version::Draft2019_09 && schema.contains("$recursiveRef")) {
  312. detail::Reference ref(schema["$recursiveRef"].as_string());
  313. EXPECT_M(ref == detail::Reference(), "Only the root schema is permitted as a $recursiveRef");
  314. reference_ = context.root.resolve_dynamic(detail::Anchor());
  315. return true;
  316. }
  317. if (context.version > Version::Draft2019_09 && schema.contains("$dynamicRef")) {
  318. detail::Reference ref(schema["$dynamicRef"].as_string());
  319. reference_ = context.root.resolve_dynamic(ref.anchor());
  320. return true;
  321. }
  322. return false;
  323. }
  324. template <Adapter A> void Node::construct(detail::ParserContext<A> context) {
  325. EXPECT(context.schema.type() == adapter::Type::Object);
  326. auto const schema = context.schema.as_object();
  327. if (schema.contains("$schema")) {
  328. // At any point in the schema, we're allowed to change versions
  329. // This means that we're not version-locked to the latest grammar
  330. // (which is especially important for some breaking changes)
  331. context.version = schema_version(context.schema);
  332. }
  333. [[maybe_unused]] auto _ = resolve_anchor(context);
  334. bool const has_reference = resolve_reference(context);
  335. if (schema.contains("default")) {
  336. default_ = schema["default"].freeze();
  337. }
  338. if (schema.contains("description")) {
  339. description_ = schema["description"].as_string();
  340. }
  341. // Prior to Draft 2019-09, reference keywords take precedence over everything
  342. // else (instead of allowing direct extensions).
  343. if (has_reference && context.version < Version::Draft2019_09) {
  344. return;
  345. }
  346. for (auto const & [key, subschema] : schema) {
  347. // Using a constraint store allows overriding certain rules, or the creation
  348. // of user-defined extention vocabularies.
  349. auto make_constraint = context.factory(key, context.version);
  350. if (not make_constraint) {
  351. continue;
  352. }
  353. // A constraint may return null if it is not applicable - but otherwise
  354. // well-formed. For example, before Draft-06 "exclusiveMaximum" was a
  355. // modifier property for "maximum", and not a unique constaint on its own.
  356. // Therefore, we parse it alongside parsing "maximum", and could return
  357. // nullptr when requesting a constraint pointer for "exclusiveMaximum".
  358. auto constraint = make_constraint(context.child(subschema, key));
  359. if (not constraint) {
  360. continue;
  361. }
  362. if (context.factory.is_post_constraint(key)) {
  363. post_constraints_.emplace(key, std::move(constraint));
  364. } else {
  365. constraints_.emplace(key, std::move(constraint));
  366. }
  367. }
  368. }
  369. }