| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606 |
- #include "collection_registry.hpp"
- #include "db_errors.hpp"
- #include "documents_util.hpp"
- #include "errors.hpp"
- #include "filters.hpp"
- #include "json_http.hpp"
- #include "query_params.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 only - everything `scoped()` does BEFORE the resource has to exist.
- //
- // Split out so a route can refuse a REQUEST-level fault BETWEEN authorization
- // and the 404, which is the one ordering rule this service holds everywhere:
- // authorize, then the server's own capability (501), then the REQUEST (422),
- // then the resource (404). A request-level fault that no amount of creating the
- // collection would fix must not hide behind the collection's absence.
- //
- // It exists because PUT's `ttl_seconds` refusal was on the wrong side of that
- // line and the defect was visible from outside: the SAME refused parameter
- // answered 422 on a collection that existed and 404 on one that did not, so a
- // caller who misspelled the collection never learned the parameter is
- // unsupported - they fixed the name, retried, and only then met the 422.
- Target authorized(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) {
- Target t;
- t.key = requireKey(*d, req);
- t.project = projectFor(*d, req, (size_t)projIdx);
- t.name = req.matches[collIdx];
- requireCapability(*d, t.key, req, t.project, t.name, op);
- t.qualified = qualify(t.project, t.name);
- return t;
- }
- // Fill in the collection metadata, 404 if there is no such collection.
- void requireCollection(ServerDeps* d, Target& t) {
- auto meta = d->registry.get(t.project, t.name);
- if (!meta) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
- t.meta = *meta;
- }
- // Authorize + verify the collection exists. The composition of the two above,
- // so there is ONE implementation of each step rather than a second copy in the
- // one route that needs them apart.
- Target scoped(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) {
- Target t = authorized(d, req, projIdx, collIdx, op);
- requireCollection(d, t);
- 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"))
- throw ApiError(
- ErrCode::Unprocessable, "vector_missing",
- // The EXPORT spelling, and the most dangerous misreading of
- // this error. An export taken with `vector_format=base64`
- // emits `vector_b64`, and feeding it straight back here used
- // to answer "a document must carry '_vector'" - which someone
- // restoring a large file under pressure reads as "my backup
- // has no vectors". That is indistinguishable from real data
- // loss and it will be believed. So when the row carries the
- // export's own field, say that the backup is fine and what to
- // do, rather than naming what is absent.
- (data.contains("vector_b64") || data.contains("_vector_b64"))
- ? "this row carries 'vector_b64', which is the EXPORT format and not a "
- "writable field - there is no base64 write form. YOUR BACKUP IS FINE: "
- "decode the base64 to float32 little-endian numbers and send them as a "
- "JSON array under '_vector'. The vector count in your export is not the "
- "problem and no data is missing"
- : data.contains("vector")
- // `vector` USED TO SATISFY THIS GUARD, and that was the bug
- // the guard exists to prevent, committed by the guard
- // itself: the body is stored verbatim while a search reads
- // `_vector`, so the row was accepted with a 201 and was
- // then invisible to every search. Measured: two rows
- // inserted with the same vector under the two spellings,
- // and only the underscored one came back.
- //
- // Refused rather than silently renamed. A caller who sent
- // `vector` has rows ALREADY stored and already unfindable,
- // and quietly fixing their next write would leave those
- // behind while making the problem look solved. The message
- // therefore says to rewrite them.
- ? "this row carries 'vector', which is not the field a search reads - the "
- "stored field must be '_vector'. A row written with 'vector' is accepted by "
- "the database and then found by NO search, so rename it here and rewrite "
- "any row already stored that way. POST .../vectors instead takes 'vector' "
- "(or 'text', which it embeds) and stores it correctly for you"
- : "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");
- // AND THE VECTOR HAS TO BE THE RIGHT SHAPE, which this route checked
- // nowhere while its two siblings both did. `POST .../vectors` and the
- // runner's `.store()` each compare the resolved vector against the
- // collection's pin and answer 422 `dimension_mismatch`; here the body
- // went straight to the database, which refuses it as a bare
- // `ErrorCode::Internal` carrying no `reason` - so `apiErrorFor` maps it
- // to **500 `internal`**, telling a caller their own permanent,
- // correctable mistake is our outage. Measured through the shipped debs:
- // a length-3 vector into a dim-4 collection answered 500
- // `internal` here and 422 `dimension_mismatch` on `.../vectors`, for
- // the same fault in the same collection.
- //
- // The fix belongs on OUR side rather than in the error mapping: we hold
- // the pin, so the length is answerable before the call, and the only
- // other way to classify the database's refusal would be to match on its
- // message text. The guard is the same CLASS as the presence check
- // directly above it - a vector collection takes a vector, and it takes
- // one of its own width - which is why it goes here and not behind a
- // database round trip.
- //
- // A non-array `_vector` is the same refusal rather than its own: the
- // caller's remedy is identical, and two slugs would send them looking
- // for two fixes.
- if (t.meta.kind == "vector") {
- const auto& v = data.at("_vector");
- if (!v.is_array() || v.size() != t.meta.vectorDimension)
- throw ApiError(ErrCode::Unprocessable, "dimension_mismatch",
- "'_vector' must be an array of " +
- std::to_string(t.meta.vectorDimension) +
- " numbers, which is this collection's pinned dimension; got " +
- (v.is_array() ? std::to_string(v.size()) + " elements"
- : std::string("a ") + v.type_name()));
- }
- 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);
- // The sibling routes' spellings are the ones worth refusing here:
- // `order=desc` is how the index-values route says it and `q=` is how
- // the collections listing says it, so a caller moving between our own
- // routes is the likeliest author of a parameter we would otherwise
- // accept and ignore. This route DOES implement `limit`, `offset`,
- // `sort` and `desc`, which is why accepting those is correct and
- // refusing them on index-values was not - the rule is "refuse what
- // you cannot honour", never a fixed list of names.
- requireHonourableParams(req,
- {{"order", "desc"}, {"asc", "desc"}, {"sort_by", "sort"},
- {"q", "filter"}, {"search", "filter"}, {"where", "filter"},
- {"page"}, {"cursor"}, {"after"}, {"skip"}, {"fields"}},
- {"filter", "limit", "offset", "sort", "desc"},
- "`filter` is repeatable and takes `field:op:value`");
- 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.
- //
- // `findWithMetrics` RATHER THAN `find`, AND IT COSTS NOTHING. Both
- // issue the identical single `Find` RPC with a byte-identical request
- // (client.cpp:964 against :1033 at the 2.20.0 pin); `find` simply drops
- // two fields of the response on the floor. The server computes both
- // BEFORE pagination, so `total` is the exact number of rows matching
- // the filters, not an estimate and not a page count.
- //
- // WHY IT MATTERS, measured with a consumer 2026-11-20: the only way to
- // learn that number was to page the whole matching set, and for one
- // real filter on a 13,093-row collection that is a full scan plus 1750
- // documents of encoding to obtain one integer. A customer-facing review
- // portal had just dropped its result count as unaffordable - for a
- // number that was arriving in every response it already made and being
- // discarded one frame short of the caller.
- //
- // `has_more` and `total`, matching the FILES listing (files.cpp) rather
- // than the database's own `total_count` wire name. Two spellings for one
- // concept across two of our own listing routes is exactly how the next
- // drift starts, and this file already records what it costs when a
- // caller learns a parameter's name on a sibling route.
- //
- // `count` is UNCHANGED and still the page size. Keeping it is the
- // additive discipline `details.unsupported` kept: callers parse it
- // today, and redefining a field in place is worse than adding two.
- //
- // Emitted UNCONDITIONALLY - unfiltered, empty, and on the last page -
- // so an absent field means exactly one thing, a server older than this
- // release. A flag present only when interesting is this codebase's most
- // repeated trap.
- //
- // One asymmetry worth knowing before anyone extends this route:
- // `findWithMetrics` has no `include_vector` parameter, where `find`
- // grew one in 2.13.0. Behaviour is identical today because the 2-arg
- // `find` defaults it to false and this listing never returned vectors,
- // but "also return the vectors" cannot be built on this overload.
- const auto page = d->db.client().findWithMetrics(t.qualified, opts);
- sendJson(res, 200, {{"documents", page.documents},
- {"count", page.documents.size()},
- {"has_more", page.hasMore},
- {"total", page.totalCount}});
- });
- 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.
- //
- // THERE USED TO BE AN `exists()` PROBE HERE AND IT WAS REMOVED,
- // because it could answer an UNRETRYABLE 404 for a document that
- // exists. `Client::exists` conflates "no such document" with "the
- // call failed" - the same defect `CollectionRegistry::get` records
- // and that cost a consumer a 6-minute ingest of an 8 GB mailbox
- // when a transport blip became "no such collection". A 404 is
- // unretryable BY DESIGN for a careful client, because adding it to
- // a retry set would retry every genuine absence, so a transient
- // failure here was permanent for the caller.
- //
- // Removing it is free, which is the part worth knowing rather than
- // rediscovering: `patch()` ALREADY reports the absent case through
- // its `Failure`, where code `Ok` on a call returning 0 means "did
- // not apply" and maps to 404, while a transport failure arrives as
- // Unavailable and maps to 503. So the probe bought nothing for
- // correctness, cost an extra round trip, and could only ever turn a
- // 503 into a 404. Measured before deleting it, with a control:
- // with no probe, PATCH of an absent document still answers 404
- // not_found, and PATCH of a document that exists still answers 200.
- //
- // It also made a live diagnosis harder than it needed to be. A
- // consumer met a document that reads fine and refuses every write,
- // and this probe was the obvious suspect precisely because it sits
- // on one of the three write paths - but PUT uses `get()` and DELETE
- // uses `remove()`, neither touches `exists()`, and all three answer
- // the same 404. The probe was never the cause and could not have
- // been; see the ghost-document note in CLAUDE.md.
- 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) {
- // AUTHORIZE first, then the REQUEST, then the RESOURCE - see
- // `authorized()` above. The parameter refusal below must come before
- // the collection's 404, or the same refused parameter answers 422 on a
- // collection that exists and 404 on one that does not.
- Target t = authorized(d, req, 1, 2, KeyOp::Update);
- std::string id = req.matches[3];
- // REFUSE `?ttl_seconds=` HERE, because this route CANNOT honour it and
- // was answering 201 as though it had.
- //
- // Reported by a consumer 2026-10-22, and the cost is the reason this
- // is a defect rather than an ergonomic wish: they PUT a row with
- // `?ttl_seconds=3600`, got a **201**, and read it back with no
- // `_expires_at` at all - i.e. PERMANENT. The whole point of their
- // change was to stop a restore recreating an immortal at-most-once
- // marker, so the silent drop produced exactly the bug the feature
- // existed to prevent, and their restore reported success either way.
- // Only a read-back caught it.
- //
- // It cannot be repaired by honouring it instead: the database client's
- // update path takes NO ttlSeconds (only insert, upsert and
- // `patchWithTtl` do), so a replace has nowhere to put an expiry. And
- // honouring it on the create half of this route while dropping it on
- // the replace half would be worse than either - a parameter that works
- // until the row exists.
- //
- // Scoped to `ttl_seconds` deliberately rather than refusing every
- // unknown parameter: a query string legitimately carries a
- // cache-buster or a proxy's addition, and this route's siblings POST
- // and PATCH both DO honour `ttl_seconds`, which is what makes a caller
- // reaching for it here non-hypothetical rather than invented.
- requireHonourableParams(
- req, {{"ttl_seconds"}}, {"if_version"},
- "a whole-document replace cannot carry an expiry - the database's update path takes "
- "no TTL. POST with an id to create a row WITH one, or PATCH to set or clear it on a "
- "row that already exists");
- // The resource LAST of the three.
- requireCollection(d, t);
- 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}});
- });
- }
- }
|