validation_result.h 11 KB

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