|
| 1 | +// |
| 2 | +// JSONSchema.hh |
| 3 | +// |
| 4 | +// Copyright 2025-Present Couchbase, Inc. |
| 5 | +// |
| 6 | +// Use of this software is governed by the Business Source License included |
| 7 | +// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified |
| 8 | +// in that file, in accordance with the Business Source License, use of this |
| 9 | +// software will be governed by the Apache License, Version 2.0, included in |
| 10 | +// the file licenses/APL2.txt. |
| 11 | +// |
| 12 | + |
| 13 | +#pragma once |
| 14 | +#ifndef _FLEECE_JSONSCHEMA_HH |
| 15 | +#define _FLEECE_JSONSCHEMA_HH |
| 16 | +#include "fleece/Fleece.hh" |
| 17 | +#include "fleece/Mutable.hh" |
| 18 | +#include <stdexcept> |
| 19 | +#include <string> |
| 20 | +#include <string_view> |
| 21 | + |
| 22 | +FL_ASSUME_NONNULL_BEGIN |
| 23 | + |
| 24 | +namespace fleece { |
| 25 | + |
| 26 | + /** Validates Values against a JSON Schema. (See https://json-schema.org ) |
| 27 | + * |
| 28 | + * Unsupported features (will throw an `unsupported_schema` exception if detected): |
| 29 | + * - Path-relative `$ref`s (URIs that start with `/`) |
| 30 | + * - `$dynamicRef`, `$dynamicAnchor`, `$vocabulary` |
| 31 | + * - `format`, `contentEncoding`, `contentMediaType` |
| 32 | + * - `dependencies`, `dependentRequired`, `dependentSchemas`, `extends` |
| 33 | + * - `unevaluatedItems`, `unevaluatedProperties` |
| 34 | + * |
| 35 | + * Known bugs: |
| 36 | + * - JSON Schema's equality comparisons do not distinguish between integers and floats, |
| 37 | + * so `7` is equal to `7.0`. However, Fleece considers ints and floats distinct types. |
| 38 | + * This implementation conforms to JSON Schema equality when making direct comparisons |
| 39 | + * between numeric Values, bbut _not_ when the numbers are nested in collections. |
| 40 | + * So for example `[7]` will not match `[7.0]`. |
| 41 | + * |
| 42 | + * @note This class does not download schemas on demand; it does no I/O at all. |
| 43 | + * See the docs of \ref unknownSchemaID to see how to handle external schema refs. |
| 44 | + * @note This class is thread-safe. |
| 45 | + */ |
| 46 | + class JSONSchema { |
| 47 | + public: |
| 48 | + |
| 49 | + /** Thrown if errors are discovered in a schema. */ |
| 50 | + class invalid_schema : public std::runtime_error { using runtime_error::runtime_error; }; |
| 51 | + /** Thrown if a schema is found to use unsupported/unimplemented features. */ |
| 52 | + class unsupported_schema : public std::runtime_error { using runtime_error::runtime_error; }; |
| 53 | + |
| 54 | + class Validation; |
| 55 | + |
| 56 | + |
| 57 | + /// Constructor that takes a parsed JSON schema object. |
| 58 | + /// @note The Value will be retained, so the caller doesn't need to keep a reference. |
| 59 | + /// @param schemaRoot The parsed schema. |
| 60 | + /// @param id_uri The absolute URI identifying this schema. Optional. |
| 61 | + /// @throws invalid_schema if the schema is invalid. |
| 62 | + /// @throws unsupported_schema if the schema uses unsupported features. |
| 63 | + explicit JSONSchema(Value schemaRoot, std::string_view id_uri = ""); |
| 64 | + |
| 65 | + /// Convenience constructor that takes a JSON schema string and parses it. |
| 66 | + /// @param json The schema as JSON data. |
| 67 | + /// @param id_uri The absolute URI identifying this schema. Optional. |
| 68 | + /// @throws invalid_schema if the schema is invalid. |
| 69 | + /// @throws unsupported_schema if the schema uses unsupported features. |
| 70 | + explicit JSONSchema(std::string_view json, std::string_view id_uri = ""); |
| 71 | + |
| 72 | + ~JSONSchema(); |
| 73 | + |
| 74 | + /// The root of the parsed schema. (Almost always a Dict.) |
| 75 | + Value schema() const; |
| 76 | + |
| 77 | + /// Registers an external schema that the main schema may refer to. |
| 78 | + /// @note The Dict will be retained, so the caller doesn't need to keep a reference. |
| 79 | + /// @param schemaRoot The parsed schema. |
| 80 | + /// @param id_uri The absolute URI identifying this schema. |
| 81 | + /// @throws invalid_schema if the schema is invalid. |
| 82 | + /// @throws unsupported_schema if the schema uses unsupported features. |
| 83 | + void addSchema(Dict schemaRoot, std::string_view id_uri); |
| 84 | + |
| 85 | + /// Validates a parsed Fleece value against the schema. |
| 86 | + /// @returns A \ref Validation object describing the result. |
| 87 | + /// @throws invalid_schema if the schema itself is invalid. |
| 88 | + /// @throws unsupported_schema if the schema uses unsupported features. |
| 89 | + Validation validate(Value value) const LIFETIMEBOUND; |
| 90 | + |
| 91 | + /// Convenience method that parses JSON and then validates it against the schema. |
| 92 | + /// @returns A \ref Validation object describing the result. |
| 93 | + /// @throws std::invalid_argument if the JSON fails to parse. |
| 94 | + /// @throws invalid_schema if the schema itself is invalid. |
| 95 | + /// @throws unsupported_schema if the schema uses unsupported features. |
| 96 | + Validation validate(std::string_view json) const LIFETIMEBOUND; |
| 97 | + Validation validate(std::string_view json, SharedKeys) const LIFETIMEBOUND; |
| 98 | + |
| 99 | + |
| 100 | + /** Errors that can occur during validation. */ |
| 101 | + enum class Error : unsigned { |
| 102 | + ok = 0, |
| 103 | + invalid, // value matched against a "false" in the schema |
| 104 | + typeMismatch, // value doesn't match "type" property in schema |
| 105 | + outOfRange, // Number is out of range of "minimum", etc. |
| 106 | + notMultiple, // Number is not a multiple of the "multipleOf" |
| 107 | + tooShort, // String is too short or collection has too few items |
| 108 | + tooLong, // String is too long or collection has too many items |
| 109 | + patternMismatch, // String doesn't match regex pattern |
| 110 | + missingProperty, // Dict is missing a required property |
| 111 | + unknownProperty, // Dict has an invalid property |
| 112 | + notEnum, // Value doesn't match any "enum" or "const" value |
| 113 | + tooFew, // Value doesn't match anything in an "anyOf" or "oneOf" array |
| 114 | + tooMany, // "oneOf" or "maxContains" failed |
| 115 | + notNot, // Value matched a "not" schema |
| 116 | + notUnique, // Array items are not unique |
| 117 | + invalidUTF8, // A string's length could not be checked because of invalid UTF-8 |
| 118 | + unknownSchemaRef, // Reference to a schema URI that's not registered |
| 119 | + }; |
| 120 | + |
| 121 | + static bool ok(Error e) noexcept {return e == Error::ok;} |
| 122 | + static std::string_view errorString(Error) noexcept; |
| 123 | + |
| 124 | + private: |
| 125 | + struct Impl; |
| 126 | + std::unique_ptr<Impl> _impl; |
| 127 | + }; |
| 128 | + |
| 129 | + |
| 130 | + /** The result of validating against a JSONSchema. */ |
| 131 | + class JSONSchema::Validation { |
| 132 | + public: |
| 133 | + /// True if validation succeeded. |
| 134 | + bool ok() const noexcept {return _result.error == Error::ok;} |
| 135 | + explicit operator bool() const {return ok();} |
| 136 | + |
| 137 | + /// The specific error. (Will be `Error::ok` if there was no error.) |
| 138 | + Error error() const noexcept { return _result.error; } |
| 139 | + |
| 140 | + /// The specific error, as a string. |
| 141 | + std::string errorString() const noexcept; |
| 142 | + |
| 143 | + /// The detected invalid Value; either the one passed to \ref validate |
| 144 | + /// or something nested in it. (Will be nullptr if there was no error.) |
| 145 | + Value errorValue() const noexcept {return _result.value;} |
| 146 | + |
| 147 | + /// On error, this is the path to the detected invalid Value, in \ref KeyPath syntax. |
| 148 | + std::string errorPath() const noexcept; |
| 149 | + |
| 150 | + /// The key and value of the item in the schema that caused the failure; |
| 151 | + /// e.g. `{"maxLength", 5}`. |
| 152 | + std::pair<slice,Value> errorSchema() const noexcept; |
| 153 | + |
| 154 | + /// A URI pointing to the item in the schema that caused the failure. |
| 155 | + std::string errorSchemaURI() const noexcept; |
| 156 | + |
| 157 | + /// If the error is `Error::unknownSchemaRef`, this is the URI of the unknown schema. |
| 158 | + /// If you can download or otherwise look up the schema, you can call \ref addSchema |
| 159 | + /// to register it, then call \ref validate again to retry. |
| 160 | + std::string const& unknownSchemaID() const noexcept {return _unknownSchema;} |
| 161 | + |
| 162 | + struct Result {Error error; Value value; Value schema; slice schemaKey;}; |
| 163 | + static bool ok(Result const& e) noexcept {return e.error == Error::ok;} |
| 164 | + private: |
| 165 | + friend class JSONSchema; |
| 166 | + |
| 167 | + Validation(JSONSchema const& schema, Value value); |
| 168 | + Result check(Value value, Value schema, Dict schemaBase); |
| 169 | + Result checkValue(Value value, Dict schema, Dict schemaBase); |
| 170 | + Result checkNumber(Value value, Dict schema, Dict schemaBase); |
| 171 | + Result checkString(Value value, Dict schema, Dict schemaBase); |
| 172 | + Result checkArray(Array, Dict schema, Dict schemaBase); |
| 173 | + Result checkDict(Dict, Dict schema, Dict schemaBase); |
| 174 | + |
| 175 | + static bool isType(Value value, Value typeVal); |
| 176 | + static bool isType(Value value, slice schemaType); |
| 177 | + |
| 178 | + Impl const& _schemaImpl; // The guts of the owning JSONSchema |
| 179 | + RetainedValue _value; // The root Value being validated (only after failure) |
| 180 | + Result _result {}; // Details of validation error |
| 181 | + std::string _unknownSchema; // Unknown schema ID found during validation |
| 182 | + }; |
| 183 | + |
| 184 | +} |
| 185 | + |
| 186 | +FL_ASSUME_NONNULL_END |
| 187 | + |
| 188 | +#endif // _FLEECE_JSONSCHEMA_HH |
0 commit comments