| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396 |
- #include "collection_registry.hpp"
- #include "db_errors.hpp"
- #include "documents_util.hpp"
- #include "errors.hpp"
- #include "filters.hpp"
- #include "json_http.hpp"
- #include "server.hpp"
- #include <string>
- #include <vector>
- #include <cstdlib>
- #include <limits>
- #include <optional>
- namespace svapi {
- namespace {
- // Everything a document route needs about its target once the caller has been
- // authorized: the key (PUT re-checks it on the create branch), the unqualified
- // names for anything caller-facing, the qualified name for the database, and
- // the registry entry, which carries the collection's kind.
- struct Target {
- ApiKey key;
- std::string project;
- std::string name;
- std::string qualified;
- CollectionMeta meta;
- };
- // Authorize + verify the collection exists.
- Target scoped(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) {
- Target t;
- t.key = requireKey(*d, req);
- t.project = req.matches[projIdx];
- t.name = req.matches[collIdx];
- requireCapability(*d, t.key, req, t.project, t.name, op);
- auto meta = d->registry.get(t.project, t.name);
- if (!meta) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
- t.meta = *meta;
- t.qualified = qualify(t.project, t.name);
- return t;
- }
- // Parses ?ttl_seconds=. Returns nullopt when absent - the caller must
- // distinguish "not supplied" (leave expiry alone) from 0 (clear the expiry).
- std::optional<uint32_t> ttlParam(const httplib::Request& req) {
- if (!req.has_param("ttl_seconds")) return std::nullopt;
- const std::string raw = req.get_param_value("ttl_seconds");
- if (raw.empty() || raw.find_first_not_of("0123456789") != std::string::npos)
- throw ApiError(ErrCode::Unprocessable, "validation", "ttl_seconds must be a non-negative integer");
- unsigned long long wide = std::strtoull(raw.c_str(), nullptr, 10);
- if (wide > std::numeric_limits<uint32_t>::max())
- throw ApiError(ErrCode::Unprocessable, "validation", "ttl_seconds must be a non-negative integer");
- return (uint32_t)wide;
- }
- // Parses ?if_version=. Absent means an unconditional write.
- std::optional<uint64_t> ifVersionParam(const httplib::Request& req) {
- if (!req.has_param("if_version")) return std::nullopt;
- return parseVersionValue(req.get_param_value("if_version"));
- }
- // 409 for the one case the database cannot report: the version was already
- // wrong when we read it, so no write was attempted and there is no failure to
- // translate. A conflict the DATABASE refuses comes back as ErrorCode::Aborted
- // carrying the version it found, and goes through conditionalFailure() below.
- ApiError versionConflict(uint64_t expected, std::optional<uint64_t> current) {
- nlohmann::json det{{"expected_version", expected}};
- if (current) det["current_version"] = *current;
- return ApiError(ErrCode::Conflict, "version_conflict",
- "the document is not at the expected version", det);
- }
- // A failed conditional write, with both halves of the story.
- //
- // The database reports the version it FOUND; only the caller knows which
- // version it ASKED for. Neither alone lets a client decide what to do, so they
- // are merged here rather than leaving the caller to remember its own request.
- ApiError conditionalFailure(const smartbotic::database::Client::FailureDetail& detail,
- uint64_t expected) {
- ApiError e = apiErrorFor(detail, "no such document");
- e.details["expected_version"] = expected;
- return e;
- }
- } // namespace
- void registerDocumentRoutes(ApiServer& s) {
- auto& svr = s.raw(); ServerDeps* d = &s.deps();
- svr.Post(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
- Target t = scoped(d, req, 1, 2, KeyOp::Insert);
- auto body = bodyJson(req);
- std::string id = body.value("id", "");
- nlohmann::json data = documentBody(body);
- // The sibling of `vector_replace_unsafe` above, arriving through a
- // different door. A document inserted into a VECTOR collection with no
- // vector reads back perfectly and can never be found by any search - it
- // has no embedding, and no read path returns one, so nothing about it
- // looks wrong.
- //
- // Reported from production with the only symptom it has: a 12448-row
- // collection whose three indexed facets each summed to 12447, the extra
- // row being a query body posted to this route by mistake.
- //
- // `text` DOES NOT SATISFY THIS, and that is the whole subtlety. THIS
- // ROUTE DOES NOT EMBED - only the vectors route does. An earlier
- // version of this guard accepted `text` on the assumption that a row
- // with text becomes searchable, which is true of `.../vectors` and
- // false here: it would have stored the exact invisible row the guard
- // exists to refuse, while looking like it had allowed ordinary ingest.
- // Caught by a consumer asking whether an EMPTY text would satisfy it,
- // which made me check whether a NON-empty one should.
- //
- // So the rule is simply: a vector collection takes a vector. Text goes
- // to `.../vectors`, which embeds it.
- if (t.meta.kind == "vector" && !data.contains("_vector") && !data.contains("vector"))
- throw ApiError(ErrCode::Unprocessable, "vector_missing",
- "a document inserted into a vector collection must carry '_vector', or "
- "it can never be found by a search. This route does not embed: POST "
- ".../vectors with 'text' to have it embedded for you, or use a json "
- "collection if this row is not meant to be searchable");
- const uint32_t ttl = ttlParam(req).value_or(0);
- std::string newId;
- try {
- newId = d->db.client().insert(t.qualified, data, id, ttl);
- } catch (const smartbotic::database::Client::Error& e) {
- throw apiErrorFor(e);
- }
- if (newId.empty()) throw ApiError(ErrCode::Unavailable, "db_error", "insert failed");
- sendJson(res, 201, {{"id", newId}});
- });
- svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
- Target t = scoped(d, req, 1, 2, KeyOp::Read);
- auto doc = d->db.client().get(t.qualified, req.matches[3]);
- if (!doc) throw ApiError(ErrCode::NotFound, "not_found", "no such document");
- // The body is the stored document plus the database's read-only
- // metadata (`_id`, `_version`, `_created_at`, `_updated_at`,
- // `_created_by`, `_updated_by`). `_version` is the value `?if_version=`
- // takes, so it is also echoed as an ETag: that is where an HTTP client
- // or cache looks for a resource version, and it costs nothing here.
- if (auto v = documentVersion(*doc))
- res.set_header("ETag", "\"" + std::to_string(*v) + "\"");
- sendJson(res, 200, *doc);
- });
- svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
- Target t = scoped(d, req, 1, 2, KeyOp::List);
- smartbotic::database::Client::QueryOptions opts;
- auto range = req.params.equal_range("filter");
- for (auto it = range.first; it != range.second; ++it) opts.filters.push_back(parseFilter(it->second));
- auto parseUInt = [](const std::string& v, const char* name) -> uint32_t {
- try { return (uint32_t)std::stoul(v); }
- catch (...) { throw ApiError(ErrCode::Unprocessable, "validation", std::string(name) + " must be a non-negative integer"); }
- };
- if (req.has_param("limit")) opts.limit = parseUInt(req.get_param_value("limit"), "limit");
- if (req.has_param("offset")) opts.offset = parseUInt(req.get_param_value("offset"), "offset");
- if (req.has_param("sort")) opts.sortField = req.get_param_value("sort");
- if (req.has_param("desc")) opts.sortDescending = (req.get_param_value("desc") == "true");
- // Each listed document carries the same `_id`/`_version` metadata a
- // single GET returns, so a filtered listing is a usable starting point
- // for a conditional write without a second round trip per row.
- auto docs = d->db.client().find(t.qualified, opts);
- sendJson(res, 200, {{"documents", docs}, {"count", docs.size()}});
- });
- svr.Patch(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
- Target t = scoped(d, req, 1, 2, KeyOp::Update);
- std::string id = req.matches[3];
- const auto ttl = ttlParam(req);
- const auto ifVersion = ifVersionParam(req);
- nlohmann::json patchBody = documentBody(bodyJson(req));
- if (!ifVersion) {
- // A patch is a server-side merge: it reads nothing out and cannot
- // lose a concurrent writer's fields. The existence probe stays a
- // probe rather than a read, so the common path does not pay for
- // fetching a document it does not look at.
- if (!d->db.client().exists(t.qualified, id))
- throw ApiError(ErrCode::NotFound, "not_found", "no such document");
- smartbotic::database::Client::Failure failure;
- uint64_t v = ttl ? d->db.client().patchWithTtl(t.qualified, id, patchBody, *ttl, failure)
- : d->db.client().patch(t.qualified, id, patchBody, failure);
- if (v == 0) throw apiErrorFor(failure, "no such document");
- sendJson(res, 200, {{"id", id}, {"version", v}});
- return;
- }
- // Conditional patch, in ONE call. The database applies the merge and
- // checks the version server-side, so there is no window at all - not
- // even the narrow one a read-merge-write with a version check leaves,
- // and no need to reconstruct the server's merge semantics here.
- //
- // The one thing it cannot carry is an expiry: there is no conditional
- // patch-with-TTL, and silently dropping one of the two would be worse
- // than refusing.
- if (ttl)
- throw ApiError(ErrCode::Unprocessable, "conditional_unsupported",
- "if_version cannot be combined with ttl_seconds on PATCH: "
- "set the expiry in a separate unconditional request");
- smartbotic::database::Client::FailureDetail detail;
- const uint64_t newVersion =
- d->db.client().patchIfVersion(t.qualified, id, patchBody, *ifVersion, detail);
- // A stale version is Aborted with reason "version_conflict" and the
- // version it actually found, so the caller is told what to re-read
- // rather than being left to guess.
- if (newVersion == 0) throw conditionalFailure(detail, *ifVersion);
- sendJson(res, 200, {{"id", id}, {"version", newVersion}});
- });
- svr.Put(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
- Target t = scoped(d, req, 1, 2, KeyOp::Update);
- std::string id = req.matches[3];
- const auto ifVersion = ifVersionParam(req);
- nlohmann::json data = documentBody(bodyJson(req));
- // A REPLACE on a vector collection destroys the stored embedding, and
- // the caller cannot prevent it.
- //
- // Measured: on a kind=vector collection a merge PATCH preserves the
- // vector, while a whole-document update drops it - the call returns
- // success and the document stops being searchable. The database
- // consumes `_vector` into its index on write and returns it from
- // nothing (not get, not find, not similaritySearch), so a caller doing
- // read-modify-write CANNOT put it back: there is no way to read it.
- // That makes PUT an embedding-destroying operation that looks like an
- // ordinary write, on data that cost money to produce.
- //
- // So refuse it unless the body carries a vector, and name both ways
- // out. Not a silent repair: re-embedding here would spend the
- // project's embedding credit on a request that never asked for it.
- if (t.meta.kind == "vector" && !data.contains("_vector") && !data.contains("vector"))
- throw ApiError(ErrCode::Unprocessable, "vector_replace_unsafe",
- "replacing a document in a vector collection would discard its stored "
- "embedding, which cannot be read back to include here. Use PATCH to "
- "change fields without touching the vector, or POST .../vectors to "
- "store a document together with its vector");
- // PUT creates the document when it is absent, which is what the method
- // means and what this API has always documented. The alternative - 404
- // plus a separate upsert route - would give PUT a meaning HTTP does not
- // have and leave callers keyed by an id they receive from elsewhere (a
- // provider's call id, say) doing a probe request before every write.
- // It grants no new power either: POST already stores at a
- // caller-supplied id.
- //
- // PATCH deliberately keeps its 404: merging fields into a document that
- // does not exist has no defined result, and a PATCH body is not a whole
- // document, so creating from one would store something the caller never
- // described.
- for (int attempt = 0;; ++attempt) {
- // A read, not an exists() probe: the version comes out of the same
- // call, and the replace path needed a read anyway (Client::update
- // does one internally).
- auto current = d->db.client().get(t.qualified, id);
- if (!current) {
- if (ifVersion) {
- // A conditional write never creates: there is no version to
- // match, and answering 201 would make `?if_version=` look
- // like it had been honoured.
- throw ApiError(ErrCode::NotFound, "not_found", "no such document");
- }
- // Creating is an insert however it is spelled. A key whose
- // scope grants `update` but not `insert` must not gain the
- // ability to create rows by using PUT instead of POST. Checked
- // against the scope directly rather than through
- // requireCapability(), which also spends a rate-limit token:
- // this request already spent one, and one request must cost one
- // token however many rules it is measured against.
- if (t.key.scope && !t.key.scope->findRule(t.name, KeyOp::Insert))
- throw ApiError(ErrCode::Forbidden, "forbidden",
- "scope permits update but not insert, so PUT may only "
- "replace a document that already exists");
- try {
- d->db.client().insert(t.qualified, data, id, 0);
- } catch (const smartbotic::database::Client::Error& e) {
- // Another writer created this id between our read and the
- // insert. The request still means "make the document look
- // like this", so one retry takes the replace branch.
- //
- // Narrowly matched: an id collision reaches us as a generic
- // internal error naming the id, while a unique-index
- // collision is AlreadyExists and must surface at once -
- // retrying that would only refuse again, one 409 later.
- const bool idTaken =
- e.code() == smartbotic::database::Client::ErrorCode::Internal &&
- std::string(e.what()).find("already exists") != std::string::npos;
- if (idTaken && attempt == 0) continue;
- throw apiErrorFor(e);
- }
- // An insert always produces version 1.
- res.set_header("Location", req.path);
- sendJson(res, 201, {{"id", id}, {"created", true}, {"version", 1}});
- return;
- }
- auto have = documentVersion(*current);
- if (!have)
- throw ApiError(ErrCode::Unavailable, "db_error",
- "the database did not report a document version");
- if (ifVersion && *have != *ifVersion) throw versionConflict(*ifVersion, have);
- // Version-checked even when the caller named no version: that is
- // what Client::update() does internally, and doing it here means
- // the new version is known without a second read. Without a named
- // version a conflict is another writer and is retried; with one it
- // is the answer the caller asked for.
- const uint64_t expected = ifVersion.value_or(*have);
- smartbotic::database::Client::FailureDetail detail;
- if (d->db.client().updateIfVersion(t.qualified, id, data, expected, detail)) {
- sendJson(res, 200, {{"id", id}, {"created", false}, {"version", expected + 1}});
- return;
- }
- // Aborted is the database saying the version moved, and it reports
- // the version it actually found - no second read needed, and no
- // guessing from the message text.
- if (detail.code == smartbotic::database::Client::ErrorCode::Aborted) {
- // An explicit if_version is the caller's condition: tell it.
- if (ifVersion) throw conditionalFailure(detail, *ifVersion);
- // No if_version: the replace simply lost a race. Re-read and
- // write again, and after a bounded number of tries report the
- // conflict rather than blaming the database with a 503.
- if (attempt < 3) continue;
- throw conditionalFailure(detail, expected);
- }
- throw apiErrorFor(detail, "no such document");
- }
- });
- // Atomic counters: one locked server-side read-modify-write per call, so
- // concurrent increments cannot lose each other the way a read, add and
- // write-back does however carefully it is version-checked.
- //
- // POST on a sub-resource rather than a flag on PATCH, because a PATCH body
- // and an increment body look identical and mean opposite things: {"calls":1}
- // is "set calls to 1" on PATCH and "add 1 to calls" here. One body shape
- // with two meanings decided by a query parameter is the kind of API where a
- // forgotten parameter silently resets a counter to 1. It is also not
- // idempotent, which POST is allowed to be and PUT is not.
- //
- // KeyOp::Update: it is a write, so a scope granting only `read` never
- // reaches it, and it is specifically an update - the database requires the
- // document to exist and this route creates nothing. Not a new KeyOp of its
- // own: a key that may replace a document may already set any number to any
- // value, so increment grants no power `update` did not, and inventing an op
- // would silently strip the ability from every scope already granting it.
- svr.Post(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+)/increment)",
- [d](const httplib::Request& req, httplib::Response& res) {
- Target t = scoped(d, req, 1, 2, KeyOp::Update);
- const std::string id = req.matches[3];
- nlohmann::json deltas = incrementDeltas(bodyJson(req));
- smartbotic::database::Client::FailureDetail detail;
- auto values = d->db.client().increment(t.qualified, id, deltas, detail);
- // 404 on a missing document, deliberately not an implicit create: the
- // starting document is the caller's to describe, and a counter conjured
- // from a typo'd id is a counter nobody ever reads. The idiom is
- // increment, then on 404 POST the document at a fixed id, then on 409
- // increment again - which is safe because that POST is the only thing
- // that can create it.
- //
- // Everything else keeps the database's own classification: a field
- // holding a non-number is InvalidArgument and so 422, integer overflow
- // likewise, and nothing at all was applied in either case.
- if (!values) throw apiErrorFor(detail, "no such document");
- // The new values are the entire point of the call, so 200 with a body
- // rather than 204: a caller that has to re-read to learn what its
- // increment produced has lost the atomicity it came here for.
- sendJson(res, 200, {{"id", id}, {"values", *values}});
- });
- svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
- Target t = scoped(d, req, 1, 2, KeyOp::Delete);
- std::string id = req.matches[3];
- smartbotic::database::Client::Failure failure;
- if (!d->db.client().remove(t.qualified, id, failure)) {
- // A restrict relation is the one refusal a caller can act on, so it
- // gets 409 plus the impact list rather than a generic failure. Only
- // ask for the impacts when the database says a precondition failed;
- // previously every failure took this path and then answered 404,
- // which was wrong for a transport error.
- if (failure.code == smartbotic::database::Client::ErrorCode::FailedPrecondition) {
- auto why = d->db.client().describeDelete(t.qualified, id);
- if (why.success && why.wouldBeBlocked)
- throw ApiError(ErrCode::Conflict, "relation_restricted",
- "delete blocked by a relation",
- {{"impacts", impactsJson(t.project, why)}});
- }
- throw apiErrorFor(failure, "no such document");
- }
- sendJson(res, 200, {{"deleted", id}});
- });
- }
- }
|