|
@@ -0,0 +1,651 @@
|
|
|
|
|
+// v2.16.0 - see json_schema.hpp for the supported subset and why it is a subset.
|
|
|
|
|
+
|
|
|
|
|
+#include "schema/json_schema.hpp"
|
|
|
|
|
+
|
|
|
|
|
+#include <algorithm>
|
|
|
|
|
+#include <cctype>
|
|
|
|
|
+#include <cmath>
|
|
|
|
|
+#include <cstdint>
|
|
|
|
|
+#include <map>
|
|
|
|
|
+#include <optional>
|
|
|
|
|
+#include <set>
|
|
|
|
|
+
|
|
|
|
|
+#include <re2/re2.h>
|
|
|
|
|
+
|
|
|
|
|
+namespace smartbotic::db::schema {
|
|
|
|
|
+
|
|
|
|
|
+namespace {
|
|
|
|
|
+
|
|
|
|
|
+enum TypeBit : uint8_t {
|
|
|
|
|
+ kObject = 1, kArray = 2, kString = 4, kInteger = 8, kNumber = 16, kBoolean = 32, kNull = 64,
|
|
|
|
|
+};
|
|
|
|
|
+
|
|
|
|
|
+enum class Format { None, DateTime, Date, Email, Uuid };
|
|
|
|
|
+
|
|
|
|
|
+} // namespace
|
|
|
|
|
+
|
|
|
|
|
+struct Node {
|
|
|
|
|
+ bool alwaysFalse = false; // the boolean schema `false`
|
|
|
|
|
+ uint8_t typeMask = 0; // 0 = any type
|
|
|
|
|
+ std::map<std::string, std::shared_ptr<const Node>> properties;
|
|
|
|
|
+ std::vector<std::string> required;
|
|
|
|
|
+ enum class Extra { Allow, Deny, Schema } extra = Extra::Allow;
|
|
|
|
|
+ std::shared_ptr<const Node> extraSchema;
|
|
|
|
|
+ std::optional<uint64_t> minProperties, maxProperties;
|
|
|
|
|
+ std::optional<uint64_t> minLength, maxLength;
|
|
|
|
|
+ std::shared_ptr<RE2> pattern;
|
|
|
|
|
+ std::string patternSource;
|
|
|
|
|
+ Format format = Format::None;
|
|
|
|
|
+ std::optional<nlohmann::json> minimum, maximum, exclusiveMinimum, exclusiveMaximum;
|
|
|
|
|
+ std::shared_ptr<const Node> items;
|
|
|
|
|
+ std::optional<uint64_t> minItems, maxItems;
|
|
|
|
|
+ bool uniqueItems = false;
|
|
|
|
|
+ std::optional<nlohmann::json> enumValues; // an array
|
|
|
|
|
+ std::optional<nlohmann::json> constValue;
|
|
|
|
|
+};
|
|
|
|
|
+
|
|
|
|
|
+namespace {
|
|
|
|
|
+
|
|
|
|
|
+const std::set<std::string>& annotations() {
|
|
|
|
|
+ static const std::set<std::string> k = {"$schema", "$id", "$comment", "title", "description",
|
|
|
|
|
+ "default", "examples", "readOnly", "writeOnly",
|
|
|
|
|
+ "deprecated"};
|
|
|
|
|
+ return k;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+const std::set<std::string>& supported() {
|
|
|
|
|
+ static const std::set<std::string> k = {
|
|
|
|
|
+ "type", "properties", "required", "additionalProperties", "minProperties",
|
|
|
|
|
+ "maxProperties", "minLength", "maxLength", "pattern", "format", "minimum", "maximum",
|
|
|
|
|
+ "exclusiveMinimum", "exclusiveMaximum", "items", "minItems", "maxItems", "uniqueItems",
|
|
|
|
|
+ "enum", "const"};
|
|
|
|
|
+ return k;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+std::string at(const std::string& path) { return path.empty() ? "the schema root" : "'" + path + "'"; }
|
|
|
|
|
+
|
|
|
|
|
+struct CompileError {
|
|
|
|
|
+ std::string message;
|
|
|
|
|
+};
|
|
|
|
|
+
|
|
|
|
|
+uint64_t nonNegative(const nlohmann::json& v, const std::string& kw, const std::string& path) {
|
|
|
|
|
+ if (v.is_number_unsigned()) return v.get<uint64_t>();
|
|
|
|
|
+ if (v.is_number_integer() && v.get<int64_t>() >= 0) return static_cast<uint64_t>(v.get<int64_t>());
|
|
|
|
|
+ if (v.is_number_float()) {
|
|
|
|
|
+ const double d = v.get<double>();
|
|
|
|
|
+ if (d >= 0 && std::floor(d) == d && d < 1.8e19) return static_cast<uint64_t>(d);
|
|
|
|
|
+ }
|
|
|
|
|
+ throw CompileError{"'" + kw + "' at " + at(path) + " must be a non-negative integer"};
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+uint8_t typeBit(const std::string& t, const std::string& path) {
|
|
|
|
|
+ if (t == "object") return kObject;
|
|
|
|
|
+ if (t == "array") return kArray;
|
|
|
|
|
+ if (t == "string") return kString;
|
|
|
|
|
+ if (t == "integer") return kInteger;
|
|
|
|
|
+ if (t == "number") return kNumber;
|
|
|
|
|
+ if (t == "boolean") return kBoolean;
|
|
|
|
|
+ if (t == "null") return kNull;
|
|
|
|
|
+ throw CompileError{"unknown type '" + t + "' at " + at(path)};
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+std::shared_ptr<const Node> compileNode(const nlohmann::json& s, const std::string& path) {
|
|
|
|
|
+ auto n = std::make_shared<Node>();
|
|
|
|
|
+ if (s.is_boolean()) {
|
|
|
|
|
+ n->alwaysFalse = !s.get<bool>();
|
|
|
|
|
+ return n;
|
|
|
|
|
+ }
|
|
|
|
|
+ if (!s.is_object()) {
|
|
|
|
|
+ throw CompileError{"a schema must be an object or a boolean, at " + at(path)};
|
|
|
|
|
+ }
|
|
|
|
|
+ for (const auto& [kw, v] : s.items()) {
|
|
|
|
|
+ if (annotations().count(kw)) continue;
|
|
|
|
|
+ if (!supported().count(kw)) {
|
|
|
|
|
+ throw CompileError{"unsupported keyword '" + kw + "' at " + at(path) +
|
|
|
|
|
+ " (refused so a schema never looks stricter than what is "
|
|
|
|
|
+ "enforced; see the integration guide for the subset)"};
|
|
|
|
|
+ }
|
|
|
|
|
+ if (kw == "type") {
|
|
|
|
|
+ if (v.is_string()) {
|
|
|
|
|
+ n->typeMask = typeBit(v.get<std::string>(), path);
|
|
|
|
|
+ } else if (v.is_array() && !v.empty()) {
|
|
|
|
|
+ for (const auto& t : v) {
|
|
|
|
|
+ if (!t.is_string()) throw CompileError{"'type' entries must be strings, at " + at(path)};
|
|
|
|
|
+ n->typeMask |= typeBit(t.get<std::string>(), path);
|
|
|
|
|
+ }
|
|
|
|
|
+ } else {
|
|
|
|
|
+ throw CompileError{"'type' must be a string or a non-empty array, at " + at(path)};
|
|
|
|
|
+ }
|
|
|
|
|
+ } else if (kw == "properties") {
|
|
|
|
|
+ if (!v.is_object()) throw CompileError{"'properties' must be an object, at " + at(path)};
|
|
|
|
|
+ for (const auto& [name, sub] : v.items()) {
|
|
|
|
|
+ n->properties[name] = compileNode(sub, path.empty() ? name : path + "." + name);
|
|
|
|
|
+ }
|
|
|
|
|
+ } else if (kw == "required") {
|
|
|
|
|
+ if (!v.is_array()) throw CompileError{"'required' must be an array, at " + at(path)};
|
|
|
|
|
+ for (const auto& r : v) {
|
|
|
|
|
+ if (!r.is_string()) throw CompileError{"'required' entries must be strings, at " + at(path)};
|
|
|
|
|
+ n->required.push_back(r.get<std::string>());
|
|
|
|
|
+ }
|
|
|
|
|
+ } else if (kw == "additionalProperties") {
|
|
|
|
|
+ if (v.is_boolean()) {
|
|
|
|
|
+ n->extra = v.get<bool>() ? Node::Extra::Allow : Node::Extra::Deny;
|
|
|
|
|
+ } else if (v.is_object()) {
|
|
|
|
|
+ n->extra = Node::Extra::Schema;
|
|
|
|
|
+ n->extraSchema = compileNode(v, path);
|
|
|
|
|
+ } else {
|
|
|
|
|
+ throw CompileError{"'additionalProperties' must be a boolean or a schema, at " + at(path)};
|
|
|
|
|
+ }
|
|
|
|
|
+ } else if (kw == "minProperties") {
|
|
|
|
|
+ n->minProperties = nonNegative(v, kw, path);
|
|
|
|
|
+ } else if (kw == "maxProperties") {
|
|
|
|
|
+ n->maxProperties = nonNegative(v, kw, path);
|
|
|
|
|
+ } else if (kw == "minLength") {
|
|
|
|
|
+ n->minLength = nonNegative(v, kw, path);
|
|
|
|
|
+ } else if (kw == "maxLength") {
|
|
|
|
|
+ n->maxLength = nonNegative(v, kw, path);
|
|
|
|
|
+ } else if (kw == "pattern") {
|
|
|
|
|
+ if (!v.is_string()) throw CompileError{"'pattern' must be a string, at " + at(path)};
|
|
|
|
|
+ RE2::Options opt;
|
|
|
|
|
+ opt.set_log_errors(false);
|
|
|
|
|
+ auto re = std::make_shared<RE2>(v.get<std::string>(), opt);
|
|
|
|
|
+ if (!re->ok()) {
|
|
|
|
|
+ throw CompileError{"'pattern' at " + at(path) + " is not a valid RE2 pattern: " +
|
|
|
|
|
+ re->error()};
|
|
|
|
|
+ }
|
|
|
|
|
+ n->pattern = std::move(re);
|
|
|
|
|
+ n->patternSource = v.get<std::string>();
|
|
|
|
|
+ } else if (kw == "format") {
|
|
|
|
|
+ const std::string f = v.is_string() ? v.get<std::string>() : "";
|
|
|
|
|
+ if (f == "date-time") n->format = Format::DateTime;
|
|
|
|
|
+ else if (f == "date") n->format = Format::Date;
|
|
|
|
|
+ else if (f == "email") n->format = Format::Email;
|
|
|
|
|
+ else if (f == "uuid") n->format = Format::Uuid;
|
|
|
|
|
+ else throw CompileError{"unsupported format '" + f + "' at " + at(path) +
|
|
|
|
|
+ " (supported: date-time, date, email, uuid)"};
|
|
|
|
|
+ } else if (kw == "minimum" || kw == "maximum" || kw == "exclusiveMinimum" ||
|
|
|
|
|
+ kw == "exclusiveMaximum") {
|
|
|
|
|
+ if (!v.is_number()) throw CompileError{"'" + kw + "' must be a number, at " + at(path)};
|
|
|
|
|
+ if (kw == "minimum") n->minimum = v;
|
|
|
|
|
+ else if (kw == "maximum") n->maximum = v;
|
|
|
|
|
+ else if (kw == "exclusiveMinimum") n->exclusiveMinimum = v;
|
|
|
|
|
+ else n->exclusiveMaximum = v;
|
|
|
|
|
+ } else if (kw == "items") {
|
|
|
|
|
+ if (!v.is_object() && !v.is_boolean()) {
|
|
|
|
|
+ throw CompileError{"'items' must be one schema (the array form is not supported), at " + at(path)};
|
|
|
|
|
+ }
|
|
|
|
|
+ n->items = compileNode(v, path + "[]");
|
|
|
|
|
+ } else if (kw == "minItems") {
|
|
|
|
|
+ n->minItems = nonNegative(v, kw, path);
|
|
|
|
|
+ } else if (kw == "maxItems") {
|
|
|
|
|
+ n->maxItems = nonNegative(v, kw, path);
|
|
|
|
|
+ } else if (kw == "uniqueItems") {
|
|
|
|
|
+ if (!v.is_boolean()) throw CompileError{"'uniqueItems' must be a boolean, at " + at(path)};
|
|
|
|
|
+ n->uniqueItems = v.get<bool>();
|
|
|
|
|
+ } else if (kw == "enum") {
|
|
|
|
|
+ if (!v.is_array()) throw CompileError{"'enum' must be an array, at " + at(path)};
|
|
|
|
|
+ n->enumValues = v;
|
|
|
|
|
+ } else if (kw == "const") {
|
|
|
|
|
+ n->constValue = v;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return n;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ---------------------------------------------------------------- validation
|
|
|
|
|
+
|
|
|
|
|
+size_t codePoints(const std::string& s) {
|
|
|
|
|
+ size_t n = 0;
|
|
|
|
|
+ for (unsigned char c : s) {
|
|
|
|
|
+ if ((c & 0xC0) != 0x80) ++n;
|
|
|
|
|
+ }
|
|
|
|
|
+ return n;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+bool isIntegral(const nlohmann::json& v) {
|
|
|
|
|
+ if (v.is_number_integer() || v.is_number_unsigned()) return true;
|
|
|
|
|
+ if (v.is_number_float()) {
|
|
|
|
|
+ const double d = v.get<double>();
|
|
|
|
|
+ return std::isfinite(d) && std::floor(d) == d;
|
|
|
|
|
+ }
|
|
|
|
|
+ return false;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+bool typeMatches(uint8_t mask, const nlohmann::json& v) {
|
|
|
|
|
+ if (mask == 0) return true;
|
|
|
|
|
+ if ((mask & kObject) && v.is_object()) return true;
|
|
|
|
|
+ if ((mask & kArray) && v.is_array()) return true;
|
|
|
|
|
+ if ((mask & kString) && v.is_string()) return true;
|
|
|
|
|
+ if ((mask & kNumber) && v.is_number()) return true;
|
|
|
|
|
+ if ((mask & kInteger) && isIntegral(v)) return true;
|
|
|
|
|
+ if ((mask & kBoolean) && v.is_boolean()) return true;
|
|
|
|
|
+ if ((mask & kNull) && v.is_null()) return true;
|
|
|
|
|
+ return false;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+std::string typeNames(uint8_t mask) {
|
|
|
|
|
+ std::string out;
|
|
|
|
|
+ const std::pair<uint8_t, const char*> names[] = {{kObject, "object"}, {kArray, "array"},
|
|
|
|
|
+ {kString, "string"}, {kInteger, "integer"}, {kNumber, "number"}, {kBoolean, "boolean"},
|
|
|
|
|
+ {kNull, "null"}};
|
|
|
|
|
+ for (const auto& [bit, name] : names) {
|
|
|
|
|
+ if (mask & bit) out += (out.empty() ? "" : " or ") + std::string(name);
|
|
|
|
|
+ }
|
|
|
|
|
+ return out;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+const char* jsonTypeName(const nlohmann::json& v) {
|
|
|
|
|
+ if (v.is_object()) return "an object";
|
|
|
|
|
+ if (v.is_array()) return "an array";
|
|
|
|
|
+ if (v.is_string()) return "a string";
|
|
|
|
|
+ if (v.is_boolean()) return "a boolean";
|
|
|
|
|
+ if (v.is_null()) return "null";
|
|
|
|
|
+ return isIntegral(v) ? "an integer" : "a number";
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// JSON Schema equality: numbers compare by value (1 == 1.0), everything else
|
|
|
|
|
+// structurally. nlohmann's == already compares numbers across subtypes.
|
|
|
|
|
+bool jsonEqual(const nlohmann::json& a, const nlohmann::json& b) { return a == b; }
|
|
|
|
|
+
|
|
|
|
|
+bool digits(const std::string& s, size_t from, size_t count) {
|
|
|
|
|
+ if (from + count > s.size()) return false;
|
|
|
|
|
+ for (size_t i = from; i < from + count; ++i) {
|
|
|
|
|
+ if (s[i] < '0' || s[i] > '9') return false;
|
|
|
|
|
+ }
|
|
|
|
|
+ return true;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+int num(const std::string& s, size_t from, size_t count) {
|
|
|
|
|
+ return std::stoi(s.substr(from, count));
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+bool validDate(const std::string& s, size_t at) { // YYYY-MM-DD at s[at]
|
|
|
|
|
+ if (!digits(s, at, 4) || s.size() < at + 10 || s[at + 4] != '-' || !digits(s, at + 5, 2) ||
|
|
|
|
|
+ s[at + 7] != '-' || !digits(s, at + 8, 2)) {
|
|
|
|
|
+ return false;
|
|
|
|
|
+ }
|
|
|
|
|
+ const int y = num(s, at, 4), m = num(s, at + 5, 2), d = num(s, at + 8, 2);
|
|
|
|
|
+ static const int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
|
|
|
|
|
+ if (m < 1 || m > 12 || d < 1) return false;
|
|
|
|
|
+ const bool leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
|
|
|
|
|
+ return d <= days[m - 1] + ((m == 2 && leap) ? 1 : 0);
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+bool formatOk(Format f, const std::string& s) {
|
|
|
|
|
+ switch (f) {
|
|
|
|
|
+ case Format::None: return true;
|
|
|
|
|
+ case Format::Date: return s.size() == 10 && validDate(s, 0);
|
|
|
|
|
+ case Format::DateTime: {
|
|
|
|
|
+ // RFC 3339: date "T" hh:mm:ss[.frac] ("Z" / +hh:mm / -hh:mm)
|
|
|
|
|
+ if (s.size() < 20 || !validDate(s, 0) || (s[10] != 'T' && s[10] != 't')) return false;
|
|
|
|
|
+ if (!digits(s, 11, 2) || s[13] != ':' || !digits(s, 14, 2) || s[16] != ':' ||
|
|
|
|
|
+ !digits(s, 17, 2)) {
|
|
|
|
|
+ return false;
|
|
|
|
|
+ }
|
|
|
|
|
+ if (num(s, 11, 2) > 23 || num(s, 14, 2) > 59 || num(s, 17, 2) > 60) return false;
|
|
|
|
|
+ size_t i = 19;
|
|
|
|
|
+ if (i < s.size() && s[i] == '.') {
|
|
|
|
|
+ size_t j = i + 1;
|
|
|
|
|
+ while (j < s.size() && s[j] >= '0' && s[j] <= '9') ++j;
|
|
|
|
|
+ if (j == i + 1) return false;
|
|
|
|
|
+ i = j;
|
|
|
|
|
+ }
|
|
|
|
|
+ if (i < s.size() && (s[i] == 'Z' || s[i] == 'z')) return i + 1 == s.size();
|
|
|
|
|
+ if (i < s.size() && (s[i] == '+' || s[i] == '-')) {
|
|
|
|
|
+ return s.size() == i + 6 && digits(s, i + 1, 2) && s[i + 3] == ':' &&
|
|
|
|
|
+ digits(s, i + 4, 2) && num(s, i + 1, 2) <= 23 && num(s, i + 4, 2) <= 59;
|
|
|
|
|
+ }
|
|
|
|
|
+ return false;
|
|
|
|
|
+ }
|
|
|
|
|
+ case Format::Email: {
|
|
|
|
|
+ const auto atPos = s.find('@');
|
|
|
|
|
+ if (atPos == std::string::npos || atPos == 0 || s.find('@', atPos + 1) != std::string::npos) {
|
|
|
|
|
+ return false;
|
|
|
|
|
+ }
|
|
|
|
|
+ const std::string domain = s.substr(atPos + 1);
|
|
|
|
|
+ const auto dot = domain.rfind('.');
|
|
|
|
|
+ if (dot == std::string::npos || dot == 0 || dot + 1 >= domain.size()) return false;
|
|
|
|
|
+ for (unsigned char c : s) {
|
|
|
|
|
+ if (c <= ' ' || c == 0x7F) return false;
|
|
|
|
|
+ }
|
|
|
|
|
+ return true;
|
|
|
|
|
+ }
|
|
|
|
|
+ case Format::Uuid: {
|
|
|
|
|
+ if (s.size() != 36) return false;
|
|
|
|
|
+ for (size_t i = 0; i < 36; ++i) {
|
|
|
|
|
+ const bool dash = i == 8 || i == 13 || i == 18 || i == 23;
|
|
|
|
|
+ if (dash ? s[i] != '-' : !std::isxdigit(static_cast<unsigned char>(s[i]))) return false;
|
|
|
|
|
+ }
|
|
|
|
|
+ return true;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return true;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+const char* formatName(Format f) {
|
|
|
|
|
+ switch (f) {
|
|
|
|
|
+ case Format::DateTime: return "date-time";
|
|
|
|
|
+ case Format::Date: return "date";
|
|
|
|
|
+ case Format::Email: return "email";
|
|
|
|
|
+ case Format::Uuid: return "uuid";
|
|
|
|
|
+ default: return "";
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+std::string shortJson(const nlohmann::json& v) {
|
|
|
|
|
+ std::string s = v.dump();
|
|
|
|
|
+ if (s.size() > 40) s = s.substr(0, 37) + "...";
|
|
|
|
|
+ return s;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+struct Walker {
|
|
|
|
|
+ size_t max;
|
|
|
|
|
+ std::vector<Violation> out;
|
|
|
|
|
+ size_t total = 0;
|
|
|
|
|
+
|
|
|
|
|
+ void add(const std::string& path, const char* kw, std::string msg) {
|
|
|
|
|
+ ++total;
|
|
|
|
|
+ if (out.size() < max) out.push_back({path, kw, std::move(msg)});
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ void walk(const Node& n, const nlohmann::json& v, const std::string& path) {
|
|
|
|
|
+ if (n.alwaysFalse) {
|
|
|
|
|
+ add(path, "false", "is not allowed by the schema");
|
|
|
|
|
+ return;
|
|
|
|
|
+ }
|
|
|
|
|
+ if (!typeMatches(n.typeMask, v)) {
|
|
|
|
|
+ add(path, "type", std::string("is ") + jsonTypeName(v) + ", expected " + typeNames(n.typeMask));
|
|
|
|
|
+ return; // the remaining keywords would only repeat the type error
|
|
|
|
|
+ }
|
|
|
|
|
+ if (n.constValue && !jsonEqual(*n.constValue, v)) {
|
|
|
|
|
+ add(path, "const", "must equal " + shortJson(*n.constValue));
|
|
|
|
|
+ }
|
|
|
|
|
+ if (n.enumValues) {
|
|
|
|
|
+ bool found = false;
|
|
|
|
|
+ for (const auto& e : *n.enumValues) {
|
|
|
|
|
+ if (jsonEqual(e, v)) { found = true; break; }
|
|
|
|
|
+ }
|
|
|
|
|
+ // The value itself is not echoed: it may be a decrypted sensitive
|
|
|
|
|
+ // field, and this message reaches the caller and the log.
|
|
|
|
|
+ if (!found) add(path, "enum", "is not one of " + shortJson(*n.enumValues));
|
|
|
|
|
+ }
|
|
|
|
|
+ if (v.is_string()) {
|
|
|
|
|
+ const auto& s = v.get_ref<const std::string&>();
|
|
|
|
|
+ const size_t len = (n.minLength || n.maxLength) ? codePoints(s) : 0;
|
|
|
|
|
+ if (n.maxLength && len > *n.maxLength) {
|
|
|
|
|
+ add(path, "maxLength", "is " + std::to_string(len) + " characters, longer than maxLength " +
|
|
|
|
|
+ std::to_string(*n.maxLength));
|
|
|
|
|
+ }
|
|
|
|
|
+ if (n.minLength && len < *n.minLength) {
|
|
|
|
|
+ add(path, "minLength", "is " + std::to_string(len) + " characters, shorter than minLength " +
|
|
|
|
|
+ std::to_string(*n.minLength));
|
|
|
|
|
+ }
|
|
|
|
|
+ if (n.pattern && !RE2::PartialMatch(s, *n.pattern)) {
|
|
|
|
|
+ add(path, "pattern", "does not match pattern " + shortJson(n.patternSource));
|
|
|
|
|
+ }
|
|
|
|
|
+ if (n.format != Format::None && !formatOk(n.format, s)) {
|
|
|
|
|
+ add(path, "format", std::string("is not a valid ") + formatName(n.format));
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ if (v.is_number()) {
|
|
|
|
|
+ if (n.minimum && v < *n.minimum) add(path, "minimum", "is " + v.dump() + ", below minimum " + n.minimum->dump());
|
|
|
|
|
+ if (n.maximum && v > *n.maximum) add(path, "maximum", "is " + v.dump() + ", above maximum " + n.maximum->dump());
|
|
|
|
|
+ if (n.exclusiveMinimum && !(v > *n.exclusiveMinimum)) {
|
|
|
|
|
+ add(path, "exclusiveMinimum", "is " + v.dump() + ", not above " + n.exclusiveMinimum->dump());
|
|
|
|
|
+ }
|
|
|
|
|
+ if (n.exclusiveMaximum && !(v < *n.exclusiveMaximum)) {
|
|
|
|
|
+ add(path, "exclusiveMaximum", "is " + v.dump() + ", not below " + n.exclusiveMaximum->dump());
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ if (v.is_array()) {
|
|
|
|
|
+ if (n.maxItems && v.size() > *n.maxItems) {
|
|
|
|
|
+ add(path, "maxItems", "has " + std::to_string(v.size()) + " items, more than maxItems " +
|
|
|
|
|
+ std::to_string(*n.maxItems));
|
|
|
|
|
+ }
|
|
|
|
|
+ if (n.minItems && v.size() < *n.minItems) {
|
|
|
|
|
+ add(path, "minItems", "has " + std::to_string(v.size()) + " items, fewer than minItems " +
|
|
|
|
|
+ std::to_string(*n.minItems));
|
|
|
|
|
+ }
|
|
|
|
|
+ if (n.uniqueItems && v.size() > 1) {
|
|
|
|
|
+ // Sorted copy: O(n log n), not pairwise - an array is caller input.
|
|
|
|
|
+ std::vector<nlohmann::json> sorted(v.begin(), v.end());
|
|
|
|
|
+ std::sort(sorted.begin(), sorted.end());
|
|
|
|
|
+ for (size_t i = 1; i < sorted.size(); ++i) {
|
|
|
|
|
+ if (sorted[i - 1] == sorted[i]) {
|
|
|
|
|
+ add(path, "uniqueItems", "contains " + shortJson(sorted[i]) + " more than once");
|
|
|
|
|
+ break;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ if (n.items) {
|
|
|
|
|
+ for (size_t i = 0; i < v.size(); ++i) {
|
|
|
|
|
+ walk(*n.items, v[i], path + "[" + std::to_string(i) + "]");
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ if (v.is_object()) {
|
|
|
|
|
+ for (const auto& r : n.required) {
|
|
|
|
|
+ if (!v.contains(r)) add(path.empty() ? r : path + "." + r, "required", "is required");
|
|
|
|
|
+ }
|
|
|
|
|
+ if (n.maxProperties && v.size() > *n.maxProperties) {
|
|
|
|
|
+ add(path, "maxProperties", "has " + std::to_string(v.size()) + " properties, more than " +
|
|
|
|
|
+ std::to_string(*n.maxProperties));
|
|
|
|
|
+ }
|
|
|
|
|
+ if (n.minProperties && v.size() < *n.minProperties) {
|
|
|
|
|
+ add(path, "minProperties", "has " + std::to_string(v.size()) + " properties, fewer than " +
|
|
|
|
|
+ std::to_string(*n.minProperties));
|
|
|
|
|
+ }
|
|
|
|
|
+ for (const auto& [key, val] : v.items()) {
|
|
|
|
|
+ const std::string child = path.empty() ? key : path + "." + key;
|
|
|
|
|
+ if (auto it = n.properties.find(key); it != n.properties.end()) {
|
|
|
|
|
+ walk(*it->second, val, child);
|
|
|
|
|
+ } else if (n.extra == Node::Extra::Deny) {
|
|
|
|
|
+ add(child, "additionalProperties", "is not a property the schema allows");
|
|
|
|
|
+ } else if (n.extra == Node::Extra::Schema) {
|
|
|
|
|
+ walk(*n.extraSchema, val, child);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+};
|
|
|
|
|
+
|
|
|
|
|
+} // namespace
|
|
|
|
|
+
|
|
|
|
|
+std::vector<Violation> CompiledSchema::validate(const nlohmann::json& document,
|
|
|
|
|
+ size_t maxViolations, size_t* total) const {
|
|
|
|
|
+ Walker w{maxViolations, {}, 0};
|
|
|
|
|
+ w.walk(*root_, document, "");
|
|
|
|
|
+ if (total) *total = w.total;
|
|
|
|
|
+ return std::move(w.out);
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+CompileResult compile(const nlohmann::json& schema) {
|
|
|
|
|
+ CompileResult r;
|
|
|
|
|
+ try {
|
|
|
|
|
+ if (!schema.is_object()) {
|
|
|
|
|
+ r.error = "a collection schema must be a JSON object";
|
|
|
|
|
+ return r;
|
|
|
|
|
+ }
|
|
|
|
|
+ auto root = compileNode(schema, "");
|
|
|
|
|
+ if (root->typeMask != 0 && !(root->typeMask & kObject)) {
|
|
|
|
|
+ r.error = "the root of a collection schema must accept an object (a document is an object)";
|
|
|
|
|
+ return r;
|
|
|
|
|
+ }
|
|
|
|
|
+ r.schema = std::make_shared<CompiledSchema>(root);
|
|
|
|
|
+ } catch (const CompileError& e) {
|
|
|
|
|
+ r.error = e.message;
|
|
|
|
|
+ } catch (const std::exception& e) {
|
|
|
|
|
+ r.error = std::string("invalid schema: ") + e.what();
|
|
|
|
|
+ }
|
|
|
|
|
+ return r;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+std::string summarize(const std::vector<Violation>& violations, size_t total) {
|
|
|
|
|
+ std::string out;
|
|
|
|
|
+ for (const auto& v : violations) {
|
|
|
|
|
+ if (!out.empty()) out += "; ";
|
|
|
|
|
+ out += (v.path.empty() ? std::string("the document") : "'" + v.path + "'") + " " + v.message;
|
|
|
|
|
+ }
|
|
|
|
|
+ if (total > violations.size()) {
|
|
|
|
|
+ out += " (and " + std::to_string(total - violations.size()) + " more)";
|
|
|
|
|
+ }
|
|
|
|
|
+ return out;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+// ------------------------------------------------------------ suggestion
|
|
|
|
|
+
|
|
|
|
|
+struct SchemaSuggester::Inf {
|
|
|
|
|
+ uint64_t seen = 0; // values observed at this path
|
|
|
|
|
+ uint8_t types = 0; // TypeBit union (integer kept separate from number)
|
|
|
|
|
+ bool allIntegral = true;
|
|
|
|
|
+ // object
|
|
|
|
|
+ uint64_t objects = 0;
|
|
|
|
|
+ std::map<std::string, std::unique_ptr<Inf>> props;
|
|
|
|
|
+ // array
|
|
|
|
|
+ std::unique_ptr<Inf> items;
|
|
|
|
|
+ // string
|
|
|
|
|
+ uint64_t strings = 0;
|
|
|
|
|
+ size_t minLen = SIZE_MAX, maxLen = 0;
|
|
|
|
|
+ std::set<std::string> distinct;
|
|
|
|
|
+ bool distinctOverflow = false;
|
|
|
|
|
+ bool allDateTime = true, allDate = true, allEmail = true, allUuid = true;
|
|
|
|
|
+ // number
|
|
|
|
|
+ std::optional<nlohmann::json> minNum, maxNum;
|
|
|
|
|
+};
|
|
|
|
|
+
|
|
|
|
|
+namespace {
|
|
|
|
|
+
|
|
|
|
|
+constexpr size_t kMaxSuggestDepth = 8;
|
|
|
|
|
+constexpr size_t kEnumMax = 10;
|
|
|
|
|
+
|
|
|
|
|
+void observe(SchemaSuggester::Inf& n, const nlohmann::json& v, size_t depth);
|
|
|
|
|
+
|
|
|
|
|
+} // namespace
|
|
|
|
|
+
|
|
|
|
|
+SchemaSuggester::SchemaSuggester() : root_(std::make_unique<Inf>()) {}
|
|
|
|
|
+SchemaSuggester::~SchemaSuggester() = default;
|
|
|
|
|
+
|
|
|
|
|
+namespace {
|
|
|
|
|
+
|
|
|
|
|
+void observe(SchemaSuggester::Inf& n, const nlohmann::json& v, size_t depth) {
|
|
|
|
|
+ ++n.seen;
|
|
|
|
|
+ if (v.is_null()) { n.types |= kNull; return; }
|
|
|
|
|
+ if (v.is_boolean()) { n.types |= kBoolean; return; }
|
|
|
|
|
+ if (v.is_number()) {
|
|
|
|
|
+ n.types |= kNumber;
|
|
|
|
|
+ if (!isIntegral(v)) n.allIntegral = false;
|
|
|
|
|
+ if (!n.minNum || v < *n.minNum) n.minNum = v;
|
|
|
|
|
+ if (!n.maxNum || v > *n.maxNum) n.maxNum = v;
|
|
|
|
|
+ return;
|
|
|
|
|
+ }
|
|
|
|
|
+ if (v.is_string()) {
|
|
|
|
|
+ n.types |= kString;
|
|
|
|
|
+ ++n.strings;
|
|
|
|
|
+ const auto& s = v.get_ref<const std::string&>();
|
|
|
|
|
+ const size_t len = codePoints(s);
|
|
|
|
|
+ n.minLen = std::min(n.minLen, len);
|
|
|
|
|
+ n.maxLen = std::max(n.maxLen, len);
|
|
|
|
|
+ if (!n.distinctOverflow) {
|
|
|
|
|
+ n.distinct.insert(s);
|
|
|
|
|
+ if (n.distinct.size() > kEnumMax) { n.distinctOverflow = true; n.distinct.clear(); }
|
|
|
|
|
+ }
|
|
|
|
|
+ if (n.allDateTime && !formatOk(Format::DateTime, s)) n.allDateTime = false;
|
|
|
|
|
+ if (n.allDate && !formatOk(Format::Date, s)) n.allDate = false;
|
|
|
|
|
+ if (n.allEmail && !formatOk(Format::Email, s)) n.allEmail = false;
|
|
|
|
|
+ if (n.allUuid && !formatOk(Format::Uuid, s)) n.allUuid = false;
|
|
|
|
|
+ return;
|
|
|
|
|
+ }
|
|
|
|
|
+ if (depth >= kMaxSuggestDepth) {
|
|
|
|
|
+ n.types |= v.is_object() ? kObject : kArray; // recorded, not described
|
|
|
|
|
+ return;
|
|
|
|
|
+ }
|
|
|
|
|
+ if (v.is_object()) {
|
|
|
|
|
+ n.types |= kObject;
|
|
|
|
|
+ ++n.objects;
|
|
|
|
|
+ for (const auto& [k, sub] : v.items()) {
|
|
|
|
|
+ auto& child = n.props[k];
|
|
|
|
|
+ if (!child) child = std::make_unique<SchemaSuggester::Inf>();
|
|
|
|
|
+ observe(*child, sub, depth + 1);
|
|
|
|
|
+ }
|
|
|
|
|
+ return;
|
|
|
|
|
+ }
|
|
|
|
|
+ // array
|
|
|
|
|
+ n.types |= kArray;
|
|
|
|
|
+ if (!n.items) n.items = std::make_unique<SchemaSuggester::Inf>();
|
|
|
|
|
+ for (const auto& el : v) observe(*n.items, el, depth + 1);
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+nlohmann::json describe(const SchemaSuggester::Inf& n, size_t depth, const std::string& path,
|
|
|
|
|
+ const std::function<bool(const std::string&)>& noEnum) {
|
|
|
|
|
+ nlohmann::json out = nlohmann::json::object();
|
|
|
|
|
+ if (n.seen == 0) return out; // e.g. items of arrays that were always empty
|
|
|
|
|
+ std::vector<std::string> types;
|
|
|
|
|
+ const std::pair<uint8_t, const char*> order[] = {{kObject, "object"}, {kArray, "array"},
|
|
|
|
|
+ {kString, "string"}, {kNumber, "number"}, {kBoolean, "boolean"}, {kNull, "null"}};
|
|
|
|
|
+ for (const auto& [bit, name] : order) {
|
|
|
|
|
+ if (!(n.types & bit)) continue;
|
|
|
|
|
+ types.push_back(bit == kNumber && n.allIntegral ? "integer" : name);
|
|
|
|
|
+ }
|
|
|
|
|
+ if (types.size() == 1) out["type"] = types.front();
|
|
|
|
|
+ else out["type"] = types;
|
|
|
|
|
+
|
|
|
|
|
+ std::vector<std::string> notes;
|
|
|
|
|
+ if ((n.types & kObject) && depth < kMaxSuggestDepth && n.objects > 0) {
|
|
|
|
|
+ nlohmann::json props = nlohmann::json::object();
|
|
|
|
|
+ nlohmann::json required = nlohmann::json::array();
|
|
|
|
|
+ for (const auto& [k, child] : n.props) {
|
|
|
|
|
+ props[k] = describe(*child, depth + 1, path.empty() ? k : path + "." + k, noEnum);
|
|
|
|
|
+ // Present in every object seen here. A key whose value was null is
|
|
|
|
|
+ // still present.
|
|
|
|
|
+ if (child->seen == n.objects) required.push_back(k);
|
|
|
|
|
+ }
|
|
|
|
|
+ out["properties"] = props;
|
|
|
|
|
+ if (!required.empty()) out["required"] = required;
|
|
|
|
|
+ out["additionalProperties"] = false;
|
|
|
|
|
+ }
|
|
|
|
|
+ if ((n.types & kArray) && n.items && depth < kMaxSuggestDepth) {
|
|
|
|
|
+ out["items"] = describe(*n.items, depth + 1, path + "[]", noEnum);
|
|
|
|
|
+ }
|
|
|
|
|
+ if (n.types & kString) {
|
|
|
|
|
+ if (n.allDateTime) out["format"] = "date-time";
|
|
|
|
|
+ else if (n.allDate) out["format"] = "date";
|
|
|
|
|
+ else if (n.allUuid) out["format"] = "uuid";
|
|
|
|
|
+ else if (n.allEmail) out["format"] = "email";
|
|
|
|
|
+ else if (!(noEnum && noEnum(path)) && !n.distinctOverflow && !n.distinct.empty() &&
|
|
|
|
|
+ n.strings >= 3 * n.distinct.size() && !(n.types & ~(kString | kNull))) {
|
|
|
|
|
+ nlohmann::json e = nlohmann::json::array();
|
|
|
|
|
+ for (const auto& x : n.distinct) e.push_back(x);
|
|
|
|
|
+ if (n.types & kNull) e.push_back(nullptr);
|
|
|
|
|
+ out["enum"] = e;
|
|
|
|
|
+ }
|
|
|
|
|
+ notes.push_back("observed length " + std::to_string(n.minLen) + ".." + std::to_string(n.maxLen));
|
|
|
|
|
+ }
|
|
|
|
|
+ if ((n.types & kNumber) && n.minNum && n.maxNum) {
|
|
|
|
|
+ notes.push_back("observed range " + n.minNum->dump() + ".." + n.maxNum->dump());
|
|
|
|
|
+ }
|
|
|
|
|
+ if (!notes.empty()) {
|
|
|
|
|
+ std::string d;
|
|
|
|
|
+ for (const auto& x : notes) d += (d.empty() ? "" : "; ") + x;
|
|
|
|
|
+ out["description"] = d + " (not enforced)";
|
|
|
|
|
+ }
|
|
|
|
|
+ return out;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+} // namespace
|
|
|
|
|
+
|
|
|
|
|
+void SchemaSuggester::add(const nlohmann::json& document) {
|
|
|
|
|
+ ++rows_;
|
|
|
|
|
+ observe(*root_, document, 0);
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+nlohmann::json SchemaSuggester::result() const {
|
|
|
|
|
+ nlohmann::json s = describe(*root_, 0, "", noEnum_);
|
|
|
|
|
+ if (rows_ == 0) {
|
|
|
|
|
+ // Nothing to learn from: any object.
|
|
|
|
|
+ s = nlohmann::json{{"type", "object"}};
|
|
|
|
|
+ }
|
|
|
|
|
+ s["$schema"] = "https://json-schema.org/draft/2020-12/schema";
|
|
|
|
|
+ return s;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+} // namespace smartbotic::db::schema
|