schema.h 16 KB

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