|
|
@@ -0,0 +1,258 @@
|
|
|
+#include "db_errors.hpp"
|
|
|
+#include "errors.hpp"
|
|
|
+#include "functions/known_keys.hpp"
|
|
|
+#include "json_http.hpp"
|
|
|
+#include "server.hpp"
|
|
|
+
|
|
|
+namespace svapi {
|
|
|
+namespace {
|
|
|
+
|
|
|
+using Db = smartbotic::database::Client;
|
|
|
+
|
|
|
+/// The capability check IS the right gate here, and that is the exact inverse
|
|
|
+/// of the rule for filtered similarity search - so the two must not be
|
|
|
+/// confused. `collection_schema` was introduced in database 2.16.0 and
|
|
|
+/// capability names gate features from 2.15.0 onward, so
|
|
|
+/// `serverSupports(kCollectionSchema)` answers correctly for it.
|
|
|
+/// `filtered_similarity` PREDATES the capability API: a 2.14.0 server reports
|
|
|
+/// no capabilities at all while fully supporting filters, so gating that on a
|
|
|
+/// name would silently drop onto the capped emulation against the very server
|
|
|
+/// we deployed for it. The rule: a capability name is sound for a feature
|
|
|
+/// introduced in 2.15.0 or later, and unsound for anything older.
|
|
|
+///
|
|
|
+/// Checked up front on every route rather than relying on the client's own
|
|
|
+/// refusal, for two reasons: we answer 501 with an operator-facing message
|
|
|
+/// instead of a translated FailedPrecondition, and a UI can ask once rather
|
|
|
+/// than discovering it per request.
|
|
|
+void requireSchemaSupport(ServerDeps& d) {
|
|
|
+ if (!d.db.client().serverSupports(Db::Capability::kCollectionSchema))
|
|
|
+ throw ApiError(ErrCode::NotImplemented, "server_unsupported",
|
|
|
+ "this database does not support collection schemas; they need "
|
|
|
+ "smartbotic-database 2.16.0 or later. Upgrading is an operator action - "
|
|
|
+ "nothing in the request needs changing.");
|
|
|
+}
|
|
|
+
|
|
|
+const char* modeName(Db::SchemaMode m) {
|
|
|
+ return m == Db::SchemaMode::Audit ? "audit" : "enforce";
|
|
|
+}
|
|
|
+
|
|
|
+/// The violating rows a refused or audited change reported, as the caller
|
|
|
+/// needs them: the PATHS that failed rather than the values, which the
|
|
|
+/// database deliberately does not echo.
|
|
|
+nlohmann::json examplesJson(const std::vector<Db::SchemaRowViolation>& examples) {
|
|
|
+ nlohmann::json out = nlohmann::json::array();
|
|
|
+ for (const auto& v : examples) {
|
|
|
+ nlohmann::json fields = nlohmann::json::array();
|
|
|
+ for (const auto& f : v.fields) fields.push_back(f);
|
|
|
+ out.push_back({{"id", v.id}, {"message", v.message}, {"fields", fields}});
|
|
|
+ }
|
|
|
+ return out;
|
|
|
+}
|
|
|
+
|
|
|
+/// Turn a refused schema change into the right slug.
|
|
|
+///
|
|
|
+/// THREE outcomes that would all be `validation` if folded together, and the
|
|
|
+/// remedies have nothing in common: fix your schema, fix your data, or upgrade
|
|
|
+/// the database. Folding them would send a caller hunting a typo in a schema
|
|
|
+/// that is correct.
|
|
|
+ApiError schemaChangeError(const Db::SchemaChangeResult& r) {
|
|
|
+ if (r.reason == "server_unsupported")
|
|
|
+ return ApiError(ErrCode::NotImplemented, "server_unsupported",
|
|
|
+ r.error.empty() ? "this database does not support collection schemas"
|
|
|
+ : r.error);
|
|
|
+ if (r.reason == "invalid_schema")
|
|
|
+ return ApiError(ErrCode::Unprocessable, "invalid_schema",
|
|
|
+ r.error.empty() ? "the schema is outside the supported subset" : r.error);
|
|
|
+ // Existing rows do not satisfy it. The counts and the examples are the
|
|
|
+ // whole value of this answer: a caller told only "refused" cannot act.
|
|
|
+ if (r.violatingRows > 0)
|
|
|
+ return ApiError(ErrCode::Unprocessable, "schema_violation",
|
|
|
+ r.error.empty()
|
|
|
+ ? "existing rows do not satisfy this schema, so it was not applied"
|
|
|
+ : r.error,
|
|
|
+ {{"rows_checked", r.rowsChecked},
|
|
|
+ {"violating_rows", r.violatingRows},
|
|
|
+ {"examples", examplesJson(r.examples)}});
|
|
|
+ // No reason and no violations: a genuine failure rather than a verdict.
|
|
|
+ // 503 rather than a guessed 422 - the same rule as a reason-less
|
|
|
+ // FailedPrecondition, where answering 422 told a caller a read-only
|
|
|
+ // database was its own validation mistake.
|
|
|
+ return ApiError(ErrCode::Unavailable, "db_error",
|
|
|
+ r.error.empty() ? "the database did not apply the schema" : r.error);
|
|
|
+}
|
|
|
+
|
|
|
+} // namespace
|
|
|
+
|
|
|
+void registerCollectionSchemaRoutes(ApiServer& s) {
|
|
|
+ auto& svr = s.raw();
|
|
|
+ ServerDeps* d = &s.deps();
|
|
|
+
|
|
|
+ // The schema as stored, with its mode and counters.
|
|
|
+ //
|
|
|
+ // A READ grant suffices, deliberately: a schema is the contract a caller
|
|
|
+ // must satisfy to write, so anyone who may read the collection may read
|
|
|
+ // what shape it expects. Withholding it would make a 422 unexplainable to
|
|
|
+ // the one principal most likely to hit it.
|
|
|
+ svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/schema)",
|
|
|
+ [d](const httplib::Request& req, httplib::Response& res) {
|
|
|
+ ApiKey k = requireKey(*d, req);
|
|
|
+ std::string project = req.matches[1], name = req.matches[2];
|
|
|
+ requireCapability(*d, k, req, project, name, KeyOp::Read);
|
|
|
+ requireSchemaSupport(*d);
|
|
|
+ if (!d->registry.get(project, name))
|
|
|
+ throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
|
|
|
+
|
|
|
+ const auto got = d->db.client().getCollectionSchema(qualify(project, name));
|
|
|
+ // 404 rather than 200 with a null: "this collection has no schema" is a
|
|
|
+ // DEFINITE answer about a sub-resource that does not exist, not an
|
|
|
+ // undetermined one, so there is no three-state problem to represent.
|
|
|
+ // A caller listing collections should read `has_schema` on the
|
|
|
+ // collection GET rather than probing this route per collection.
|
|
|
+ if (!got)
|
|
|
+ throw ApiError(ErrCode::NotFound, "no_schema",
|
|
|
+ "this collection has no schema; writes are not validated");
|
|
|
+
|
|
|
+ sendJson(res, 200,
|
|
|
+ {{"schema", got->schema},
|
|
|
+ {"mode", modeName(got->mode)},
|
|
|
+ // Counters since the schema was armed. `audit_violations`
|
|
|
+ // is the one that matters in audit mode: it is how an
|
|
|
+ // operator learns the data would fail enforcement.
|
|
|
+ {"audit_violations", got->auditViolations},
|
|
|
+ {"refusals", got->refusals},
|
|
|
+ // `armed: false` means the stored schema no longer compiles
|
|
|
+ // and NOTHING is being validated. Surfaced rather than
|
|
|
+ // hidden, because a schema that silently enforces nothing is
|
|
|
+ // worse than no schema - it reads as protection.
|
|
|
+ {"armed", got->armed}});
|
|
|
+ });
|
|
|
+
|
|
|
+ // Set or replace the schema.
|
|
|
+ //
|
|
|
+ // Project-manage rather than admin: a schema is a data contract on the
|
|
|
+ // tenant's own collection, the same category as an index, and not a
|
|
|
+ // security boundary. (Function POLICY is admin-only because it governs
|
|
|
+ // what one project may take from a runner every project shares.)
|
|
|
+ svr.Put(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/schema)",
|
|
|
+ [d](const httplib::Request& req, httplib::Response& res) {
|
|
|
+ ApiKey k = requireKey(*d, req);
|
|
|
+ std::string project = req.matches[1], name = req.matches[2];
|
|
|
+ requireProjectManage(k, project);
|
|
|
+ requireSchemaSupport(*d);
|
|
|
+ if (!d->registry.get(project, name))
|
|
|
+ throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
|
|
|
+
|
|
|
+ nlohmann::json body = bodyJson(req);
|
|
|
+
|
|
|
+ // An unknown key is REFUSED, not ignored. The lesson from the vector
|
|
|
+ // search body applies verbatim: an option accepted and silently
|
|
|
+ // dropped is worse than one refused, and `mode: "enfroce"` must not
|
|
|
+ // quietly apply the default.
|
|
|
+ static constexpr std::initializer_list<std::string_view> kSchemaKeys = {"schema", "mode"};
|
|
|
+ if (const auto unknown = functions::unknownKeys(body, kSchemaKeys); !unknown.empty())
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "unknown_option",
|
|
|
+ functions::unknownKeyMessage(unknown, kSchemaKeys));
|
|
|
+
|
|
|
+ if (!body.contains("schema") || !body.at("schema").is_object())
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
+ "'schema' is required and must be a JSON Schema object");
|
|
|
+
|
|
|
+ const std::string qc = qualify(project, name);
|
|
|
+
|
|
|
+ // The DEFAULT MODE depends on whether the collection holds data, and
|
|
|
+ // the asymmetry is deliberate. On an EMPTY collection enforce can
|
|
|
+ // never fail, and a live contract is what the caller wants. On a
|
|
|
+ // POPULATED one enforce usually REFUSES on real data, and the counts
|
|
|
+ // are what an operator actually needs first - so defaulting to enforce
|
|
|
+ // there would make the common case look like the feature is broken.
|
|
|
+ // Stated in the response as `mode_defaulted` so a caller never has to
|
|
|
+ // infer which rule applied.
|
|
|
+ bool defaulted = false;
|
|
|
+ Db::SchemaMode mode = Db::SchemaMode::Enforce;
|
|
|
+ if (body.contains("mode")) {
|
|
|
+ if (!body.at("mode").is_string())
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation", "'mode' must be a string");
|
|
|
+ const std::string m = body.at("mode").get<std::string>();
|
|
|
+ if (m == "audit") mode = Db::SchemaMode::Audit;
|
|
|
+ else if (m == "enforce") mode = Db::SchemaMode::Enforce;
|
|
|
+ else
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
+ "'mode' must be \"enforce\" or \"audit\", not \"" + m + "\"");
|
|
|
+ } else {
|
|
|
+ defaulted = true;
|
|
|
+ mode = d->db.client().count(qc) > 0 ? Db::SchemaMode::Audit : Db::SchemaMode::Enforce;
|
|
|
+ }
|
|
|
+
|
|
|
+ const auto r = d->db.client().setCollectionSchema(qc, body.at("schema"), mode);
|
|
|
+ if (!r.success) throw schemaChangeError(r);
|
|
|
+
|
|
|
+ // Reported on SUCCESS too, because audit mode succeeds while rows
|
|
|
+ // violate: `violating_rows` above zero here means the schema is armed
|
|
|
+ // and the data does not satisfy it, which is the whole point of audit
|
|
|
+ // and is invisible if only failures carry counts.
|
|
|
+ sendJson(res, 200,
|
|
|
+ {{"mode", modeName(mode)},
|
|
|
+ {"mode_defaulted", defaulted},
|
|
|
+ {"rows_checked", r.rowsChecked},
|
|
|
+ {"violating_rows", r.violatingRows},
|
|
|
+ {"examples", examplesJson(r.examples)}});
|
|
|
+ });
|
|
|
+
|
|
|
+ // Remove the schema; writes stop being validated.
|
|
|
+ svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/schema)",
|
|
|
+ [d](const httplib::Request& req, httplib::Response& res) {
|
|
|
+ ApiKey k = requireKey(*d, req);
|
|
|
+ std::string project = req.matches[1], name = req.matches[2];
|
|
|
+ requireProjectManage(k, project);
|
|
|
+ requireSchemaSupport(*d);
|
|
|
+ if (!d->registry.get(project, name))
|
|
|
+ throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
|
|
|
+
|
|
|
+ const auto r = d->db.client().removeCollectionSchema(qualify(project, name));
|
|
|
+ if (!r.success) throw schemaChangeError(r);
|
|
|
+ // Idempotent, like the index drop: removing a schema that is not there
|
|
|
+ // reaches the requested end state, so it is 200 rather than 404.
|
|
|
+ sendJson(res, 200, {{"removed", true}});
|
|
|
+ });
|
|
|
+
|
|
|
+ // A schema generated FROM the data, as a starting point.
|
|
|
+ //
|
|
|
+ // Project-manage rather than read: it scans the collection, and it exists
|
|
|
+ // to author a contract rather than to satisfy one.
|
|
|
+ //
|
|
|
+ // It NEVER applies what it suggests. The database's own note is the
|
|
|
+ // reason: lengths and ranges are only described, not enforced, so applying
|
|
|
+ // this unseen would arm something that looks stricter than what it
|
|
|
+ // actually checks. The caller edits and then PUTs.
|
|
|
+ svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/schema/suggest)",
|
|
|
+ [d](const httplib::Request& req, httplib::Response& res) {
|
|
|
+ ApiKey k = requireKey(*d, req);
|
|
|
+ std::string project = req.matches[1], name = req.matches[2];
|
|
|
+ requireProjectManage(k, project);
|
|
|
+ requireSchemaSupport(*d);
|
|
|
+ if (!d->registry.get(project, name))
|
|
|
+ throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
|
|
|
+
|
|
|
+ uint64_t sampleLimit = 0; // 0 = every row
|
|
|
+ if (req.has_param("sample_limit")) {
|
|
|
+ const unsigned long long wide =
|
|
|
+ std::strtoull(req.get_param_value("sample_limit").c_str(), nullptr, 10);
|
|
|
+ sampleLimit = static_cast<uint64_t>(wide);
|
|
|
+ }
|
|
|
+
|
|
|
+ const auto sug = d->db.client().suggestCollectionSchema(qualify(project, name), sampleLimit);
|
|
|
+ sendJson(res, 200,
|
|
|
+ {{"schema", sug.schema},
|
|
|
+ {"rows_scanned", sug.rowsScanned},
|
|
|
+ // `complete: false` means this was built from a SAMPLE, so a
|
|
|
+ // field absent from it may still exist in the data and the
|
|
|
+ // suggestion may be stricter than the collection. Emitted
|
|
|
+ // unconditionally, so absence means only "older server".
|
|
|
+ {"complete", sug.complete},
|
|
|
+ // Said in the payload rather than only in the docs: the one
|
|
|
+ // misreading that costs data is treating this as applied.
|
|
|
+ {"applied", false}});
|
|
|
+ });
|
|
|
+}
|
|
|
+
|
|
|
+} // namespace svapi
|