validation_result.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. #pragma once
  2. #include <algorithm>
  3. #include <cstdlib>
  4. #include <map>
  5. #include <ostream>
  6. #include <string>
  7. #include <unordered_map>
  8. #include <utility>
  9. #include <variant>
  10. #include <vector>
  11. #include <jvalidate/detail/pointer.h>
  12. #include <jvalidate/forward.h>
  13. namespace jvalidate {
  14. class ValidationResult {
  15. public:
  16. // Only allow ValidationVisitor to construct the elements of a validation result
  17. template <Adapter, RegexEngine, typename> friend class ValidationVisitor;
  18. using DocPointer = detail::Pointer;
  19. using SchemaPointer = detail::Pointer;
  20. using Annotation = std::variant<std::string, std::vector<std::string>>;
  21. /**
  22. * @brief The result info at any given (DocPointer, SchemaPointer) path.
  23. * The key for errors/annotations represents the leaf element of SchemaPointer
  24. * instead of including it in the map.
  25. *
  26. * This allows better locality of error info. For example:
  27. * {
  28. * "valid": false,
  29. * "evaluationPath": "/definitions/EvenPercent",
  30. * "instanceLocation": "/foo/bar/percentages/2",
  31. * "errors": {
  32. * "max": "105 > 100",
  33. * "multipleOf": "105 is not a multiple of 2"
  34. * }
  35. * }
  36. */
  37. struct LocalResult {
  38. bool valid = true;
  39. std::unordered_map<std::string, Annotation> errors;
  40. std::unordered_map<std::string, Annotation> annotations;
  41. };
  42. static auto indent(size_t depth) { return std::string(depth * 2, ' '); }
  43. private:
  44. bool valid_;
  45. std::unordered_map<DocPointer, std::unordered_map<SchemaPointer, LocalResult>> results_;
  46. public:
  47. /**
  48. * @brief Writes this object to an osteam in the list format as described in
  49. * https://json-schema.org/blog/posts/interpreting-output
  50. * This means that the json-schema for a ValidationResult looks like this:
  51. * {
  52. * "$defs": {
  53. * "Pointer": {
  54. * "format": "json-pointer",
  55. * "type": "string"
  56. * },
  57. * "Annotation": {
  58. * "items": { "type": "string" },
  59. * "type": [ "string", "array" ]
  60. * }
  61. * },
  62. * "properties": {
  63. * "valid": { "type": "boolean" },
  64. * "details": {
  65. * "items": {
  66. * "properties": {
  67. * "valid": { "type": "boolean" },
  68. * "evaluationPath": { "$ref": "#/$defs/Pointer" },
  69. * "instanceLocation": { "$ref": "#/$defs/Pointer" },
  70. * "annotations": { "$ref": "#/$defs/Annotation" },
  71. * "errors": { "$ref": "#/$defs/Annotation" }
  72. * }
  73. * "type": "object"
  74. * },
  75. * "type": "array"
  76. * }
  77. * }
  78. * "type": "object"
  79. * }
  80. */
  81. friend std::ostream & operator<<(std::ostream & os, ValidationResult const & result) {
  82. auto sorted = []<typename K, typename V>(std::unordered_map<K, V> const & container) {
  83. return std::map<K, V const &>(container.begin(), container.end());
  84. };
  85. char const * div = "\n";
  86. os << "{\n" << indent(1) << R"("valid": )" << (result.valid_ ? "true" : "false") << ',' << '\n';
  87. os << indent(1) << R"("details": [)";
  88. for (auto const & [doc_path, by_schema] : sorted(result.results_)) {
  89. for (auto const & [schema_path, local] : sorted(by_schema)) {
  90. os << std::exchange(div, ",\n") << indent(2) << '{' << '\n';
  91. os << indent(3) << R"("valid": )" << (local.valid ? "true" : "false") << ',' << '\n';
  92. os << indent(3) << R"("evaluationPath": ")" << schema_path << '"' << ',' << '\n';
  93. os << indent(3) << R"("instanceLocation": ")" << doc_path << '"';
  94. print(os, local.annotations, "annotations", 3);
  95. print(os, local.errors, "errors", 3);
  96. os << '\n' << indent(2) << '}';
  97. }
  98. }
  99. return os << '\n' << indent(1) << ']' << '\n' << '}';
  100. }
  101. static void print(std::ostream & os, auto const & named, std::string_view name, int const depth) {
  102. if (named.empty()) {
  103. return;
  104. }
  105. os << ',' << '\n';
  106. os << indent(depth) << '"' << name << '"' << ':' << ' ' << '{' << '\n';
  107. char const * odiv = "";
  108. for (auto const & [key, anno] : named) {
  109. os << std::exchange(odiv, ",\n") << indent(depth + 1) << '"' << key << '"' << ':' << ' ';
  110. if (auto const * str = std::get_if<0>(&anno)) {
  111. os << '"' << *str << '"';
  112. } else if (std::vector<std::string> const * vec = std::get_if<1>(&anno)) {
  113. os << '[';
  114. char const * div = "\n";
  115. for (std::string const & elem : *vec) {
  116. os << std::exchange(div, ",\n") << indent(depth + 2) << '"' << elem << '"';
  117. }
  118. os << '\n' << indent(depth + 1) << ']';
  119. }
  120. }
  121. os << '\n' << indent(depth) << '}';
  122. }
  123. bool valid() const { return valid_; }
  124. /**
  125. * @brief Are there any validation details associated with the given document
  126. * location and schema section.
  127. *
  128. * @param where A path into the document being validated
  129. * @param schema_path The schema path (not counting the leaf element that
  130. * actually evaluates the document)
  131. *
  132. * @return true if the schema path has produced an annotation or error for the
  133. * document path
  134. */
  135. bool has(detail::Pointer const & where, detail::Pointer const & schema_path) const {
  136. return has(where) && results_.at(where).contains(schema_path);
  137. }
  138. /**
  139. * @brief Are there any validation details associated with the given document
  140. * location
  141. *
  142. * @param where A path into the document being validated
  143. *
  144. * @return true if any rule has produced an annotation or error for the
  145. * document path
  146. */
  147. bool has(detail::Pointer const & where) const { return results_.contains(where); }
  148. /**
  149. * @brief Extracts the annotation for requested document and schema location, if it exists
  150. *
  151. * @param where A path into the document being validated
  152. * @param schema_path The schema path, without its leaf element
  153. * @param name The leaf schema path (i.e. the rule being evaluated).
  154. * @pre name.empty() == schema_path.empty()
  155. *
  156. * @returns An Annotation for the given path info provided, or nullptr if no annotation exists
  157. */
  158. Annotation const * annotation(detail::Pointer const & where, detail::Pointer const & schema_path,
  159. std::string const & name) const {
  160. if (not results_.contains(where)) {
  161. return nullptr;
  162. }
  163. auto const & by_schema = results_.at(where);
  164. if (not by_schema.contains(schema_path)) {
  165. return nullptr;
  166. }
  167. auto const & local = by_schema.at(schema_path);
  168. if (not local.annotations.contains(name)) {
  169. return nullptr;
  170. }
  171. return &local.annotations.at(name);
  172. }
  173. /**
  174. * @brief Extracts the error for requested document and schema location, if it exists
  175. *
  176. * @param where A path into the document being validated
  177. * @param schema_path The schema path, without its leaf element
  178. * @param name The leaf schema path (i.e. the rule being evaluated).
  179. * @pre name.empty() == schema_path.empty()
  180. *
  181. * @returns An Annotation for the given path info provided, or nullptr if no annotation exists
  182. */
  183. Annotation const * error(detail::Pointer const & where, detail::Pointer const & schema_path,
  184. std::string const & name) const {
  185. if (not results_.contains(where)) {
  186. return nullptr;
  187. }
  188. auto const & by_schema = results_.at(where);
  189. if (not by_schema.contains(schema_path)) {
  190. return nullptr;
  191. }
  192. auto const & local = by_schema.at(schema_path);
  193. if (not local.errors.contains(name)) {
  194. return nullptr;
  195. }
  196. return &local.errors.at(name);
  197. }
  198. ValidationResult only_errors() const {
  199. ValidationResult rval;
  200. rval.valid_ = valid_;
  201. for (auto const & [doc, results] : results_) {
  202. for (auto const & [schema, result] : results) {
  203. if (!result.errors.empty()) {
  204. rval.results_[doc][schema] = result;
  205. }
  206. }
  207. }
  208. return rval;
  209. }
  210. private:
  211. /**
  212. * @brief Transfer the contents of another ValidationResult into this one using
  213. * {@see std::map::merge} to transfer the data minimizing the need for copy/move.
  214. *
  215. * @param result The ValidationResult being consumed
  216. */
  217. void merge(ValidationResult && result) & {
  218. for (auto && [where, by_schema] : std::move(result).results_) {
  219. for (auto && [schema_path, local] : by_schema) {
  220. results_[where][schema_path].valid &= local.valid;
  221. results_[where][schema_path].annotations.merge(local.annotations);
  222. results_[where][schema_path].errors.merge(local.errors);
  223. }
  224. }
  225. }
  226. /**
  227. * @brief Declare that the document is accepted/rejected by the given schema
  228. *
  229. * @param where A path into the document being validated
  230. * @param schema_path The schema path
  231. * @param valid Is this location valid according to the schema
  232. */
  233. void valid(detail::Pointer const & where, detail::Pointer const & schema_path, bool valid) {
  234. if (has(where, schema_path)) {
  235. results_[where][schema_path].valid = valid;
  236. }
  237. if (where.empty() && schema_path.empty()) {
  238. valid_ = valid;
  239. }
  240. }
  241. /**
  242. * @brief Attach an error message for part of the document.
  243. * Because of the existance of things like "not" schemas, error() can also be
  244. * called to add an Annotation for a gate that is passed, but was within a
  245. * "not" schema.
  246. *
  247. * @param where A path into the document being validated
  248. * @param schema_path The schema path, without its leaf element
  249. * @param name The leaf schema path (i.e. the rule being evaluated).
  250. * @pre name.empty() == schema_path.empty()
  251. * @param message The annotation(s) being placed as an error
  252. */
  253. void error(detail::Pointer const & where, detail::Pointer const & schema_path,
  254. std::string const & name, Annotation message) {
  255. if (std::visit([](auto const & val) { return val.empty(); }, message)) {
  256. return;
  257. }
  258. std::visit([](auto & msg) { sanitize(msg); }, message);
  259. results_[where][schema_path].errors.emplace(name, std::move(message));
  260. }
  261. /**
  262. * @brief Attach some contextual annotations for part of the document
  263. *
  264. * @param where A path into the document being validated
  265. * @param schema_path The schema path, without its leaf element
  266. * @param name The leaf schema path (i.e. the rule being evaluated).
  267. * @pre name.empty() == schema_path.empty()
  268. * @param message The annotation(s) being placed for context
  269. */
  270. void annotate(detail::Pointer const & where, detail::Pointer const & schema_path,
  271. std::string const & name, Annotation message) {
  272. if (std::visit([](auto const & val) { return val.empty(); }, message)) {
  273. return;
  274. }
  275. std::visit([](auto & msg) { sanitize(msg); }, message);
  276. results_[where][schema_path].annotations.emplace(name, std::move(message));
  277. }
  278. /**
  279. * @brief Remove annotations that we added without knowing if they were
  280. * needed, now that we know that they are not required.
  281. *
  282. * @param where A path into the document being validated
  283. * @param schema_path The schema path to remove
  284. */
  285. void unannotate(detail::Pointer const & where, detail::Pointer const & schema_path) {
  286. results_[where].erase(schema_path);
  287. }
  288. static void sanitize(std::string & message) {
  289. for (auto it = message.begin(); it != message.end(); ++it) {
  290. if (*it == '"' || *it == '\\') {
  291. it = ++message.insert(it, '\\');
  292. }
  293. }
  294. }
  295. static void sanitize(std::vector<std::string> & message) {
  296. std::ranges::for_each(message, [](std::string & val) { sanitize(val); });
  297. }
  298. };
  299. }