documents.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. #include "collection_registry.hpp"
  2. #include "db_errors.hpp"
  3. #include "documents_util.hpp"
  4. #include "errors.hpp"
  5. #include "filters.hpp"
  6. #include "json_http.hpp"
  7. #include "query_params.hpp"
  8. #include "server.hpp"
  9. #include <string>
  10. #include <vector>
  11. #include <cstdlib>
  12. #include <limits>
  13. #include <optional>
  14. namespace svapi {
  15. namespace {
  16. // Everything a document route needs about its target once the caller has been
  17. // authorized: the key (PUT re-checks it on the create branch), the unqualified
  18. // names for anything caller-facing, the qualified name for the database, and
  19. // the registry entry, which carries the collection's kind.
  20. struct Target {
  21. ApiKey key;
  22. std::string project;
  23. std::string name;
  24. std::string qualified;
  25. CollectionMeta meta;
  26. };
  27. // Authorize only - everything `scoped()` does BEFORE the resource has to exist.
  28. //
  29. // Split out so a route can refuse a REQUEST-level fault BETWEEN authorization
  30. // and the 404, which is the one ordering rule this service holds everywhere:
  31. // authorize, then the server's own capability (501), then the REQUEST (422),
  32. // then the resource (404). A request-level fault that no amount of creating the
  33. // collection would fix must not hide behind the collection's absence.
  34. //
  35. // It exists because PUT's `ttl_seconds` refusal was on the wrong side of that
  36. // line and the defect was visible from outside: the SAME refused parameter
  37. // answered 422 on a collection that existed and 404 on one that did not, so a
  38. // caller who misspelled the collection never learned the parameter is
  39. // unsupported - they fixed the name, retried, and only then met the 422.
  40. Target authorized(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) {
  41. Target t;
  42. t.key = requireKey(*d, req);
  43. t.project = projectFor(*d, req, (size_t)projIdx);
  44. t.name = req.matches[collIdx];
  45. requireCapability(*d, t.key, req, t.project, t.name, op);
  46. t.qualified = qualify(t.project, t.name);
  47. return t;
  48. }
  49. // Fill in the collection metadata, 404 if there is no such collection.
  50. void requireCollection(ServerDeps* d, Target& t) {
  51. auto meta = d->registry.get(t.project, t.name);
  52. if (!meta) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
  53. t.meta = *meta;
  54. }
  55. // Authorize + verify the collection exists. The composition of the two above,
  56. // so there is ONE implementation of each step rather than a second copy in the
  57. // one route that needs them apart.
  58. Target scoped(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) {
  59. Target t = authorized(d, req, projIdx, collIdx, op);
  60. requireCollection(d, t);
  61. return t;
  62. }
  63. // Parses ?ttl_seconds=. Returns nullopt when absent - the caller must
  64. // distinguish "not supplied" (leave expiry alone) from 0 (clear the expiry).
  65. std::optional<uint32_t> ttlParam(const httplib::Request& req) {
  66. if (!req.has_param("ttl_seconds")) return std::nullopt;
  67. const std::string raw = req.get_param_value("ttl_seconds");
  68. if (raw.empty() || raw.find_first_not_of("0123456789") != std::string::npos)
  69. throw ApiError(ErrCode::Unprocessable, "validation", "ttl_seconds must be a non-negative integer");
  70. unsigned long long wide = std::strtoull(raw.c_str(), nullptr, 10);
  71. if (wide > std::numeric_limits<uint32_t>::max())
  72. throw ApiError(ErrCode::Unprocessable, "validation", "ttl_seconds must be a non-negative integer");
  73. return (uint32_t)wide;
  74. }
  75. // Parses ?if_version=. Absent means an unconditional write.
  76. std::optional<uint64_t> ifVersionParam(const httplib::Request& req) {
  77. if (!req.has_param("if_version")) return std::nullopt;
  78. return parseVersionValue(req.get_param_value("if_version"));
  79. }
  80. // 409 for the one case the database cannot report: the version was already
  81. // wrong when we read it, so no write was attempted and there is no failure to
  82. // translate. A conflict the DATABASE refuses comes back as ErrorCode::Aborted
  83. // carrying the version it found, and goes through conditionalFailure() below.
  84. ApiError versionConflict(uint64_t expected, std::optional<uint64_t> current) {
  85. nlohmann::json det{{"expected_version", expected}};
  86. if (current) det["current_version"] = *current;
  87. return ApiError(ErrCode::Conflict, "version_conflict",
  88. "the document is not at the expected version", det);
  89. }
  90. // A failed conditional write, with both halves of the story.
  91. //
  92. // The database reports the version it FOUND; only the caller knows which
  93. // version it ASKED for. Neither alone lets a client decide what to do, so they
  94. // are merged here rather than leaving the caller to remember its own request.
  95. ApiError conditionalFailure(const smartbotic::database::Client::FailureDetail& detail,
  96. uint64_t expected) {
  97. ApiError e = apiErrorFor(detail, "no such document");
  98. e.details["expected_version"] = expected;
  99. return e;
  100. }
  101. } // namespace
  102. void registerDocumentRoutes(ApiServer& s) {
  103. auto& svr = s.raw(); ServerDeps* d = &s.deps();
  104. svr.Post(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
  105. Target t = scoped(d, req, 1, 2, KeyOp::Insert);
  106. auto body = bodyJson(req);
  107. std::string id = body.value("id", "");
  108. nlohmann::json data = documentBody(body);
  109. // The sibling of `vector_replace_unsafe` above, arriving through a
  110. // different door. A document inserted into a VECTOR collection with no
  111. // vector reads back perfectly and can never be found by any search - it
  112. // has no embedding, and no read path returns one, so nothing about it
  113. // looks wrong.
  114. //
  115. // Reported from production with the only symptom it has: a 12448-row
  116. // collection whose three indexed facets each summed to 12447, the extra
  117. // row being a query body posted to this route by mistake.
  118. //
  119. // `text` DOES NOT SATISFY THIS, and that is the whole subtlety. THIS
  120. // ROUTE DOES NOT EMBED - only the vectors route does. An earlier
  121. // version of this guard accepted `text` on the assumption that a row
  122. // with text becomes searchable, which is true of `.../vectors` and
  123. // false here: it would have stored the exact invisible row the guard
  124. // exists to refuse, while looking like it had allowed ordinary ingest.
  125. // Caught by a consumer asking whether an EMPTY text would satisfy it,
  126. // which made me check whether a NON-empty one should.
  127. //
  128. // So the rule is simply: a vector collection takes a vector. Text goes
  129. // to `.../vectors`, which embeds it.
  130. if (t.meta.kind == "vector" && !data.contains("_vector"))
  131. throw ApiError(
  132. ErrCode::Unprocessable, "vector_missing",
  133. // The EXPORT spelling, and the most dangerous misreading of
  134. // this error. An export taken with `vector_format=base64`
  135. // emits `vector_b64`, and feeding it straight back here used
  136. // to answer "a document must carry '_vector'" - which someone
  137. // restoring a large file under pressure reads as "my backup
  138. // has no vectors". That is indistinguishable from real data
  139. // loss and it will be believed. So when the row carries the
  140. // export's own field, say that the backup is fine and what to
  141. // do, rather than naming what is absent.
  142. (data.contains("vector_b64") || data.contains("_vector_b64"))
  143. ? "this row carries 'vector_b64', which is the EXPORT format and not a "
  144. "writable field - there is no base64 write form. YOUR BACKUP IS FINE: "
  145. "decode the base64 to float32 little-endian numbers and send them as a "
  146. "JSON array under '_vector'. The vector count in your export is not the "
  147. "problem and no data is missing"
  148. : data.contains("vector")
  149. // `vector` USED TO SATISFY THIS GUARD, and that was the bug
  150. // the guard exists to prevent, committed by the guard
  151. // itself: the body is stored verbatim while a search reads
  152. // `_vector`, so the row was accepted with a 201 and was
  153. // then invisible to every search. Measured: two rows
  154. // inserted with the same vector under the two spellings,
  155. // and only the underscored one came back.
  156. //
  157. // Refused rather than silently renamed. A caller who sent
  158. // `vector` has rows ALREADY stored and already unfindable,
  159. // and quietly fixing their next write would leave those
  160. // behind while making the problem look solved. The message
  161. // therefore says to rewrite them.
  162. ? "this row carries 'vector', which is not the field a search reads - the "
  163. "stored field must be '_vector'. A row written with 'vector' is accepted by "
  164. "the database and then found by NO search, so rename it here and rewrite "
  165. "any row already stored that way. POST .../vectors instead takes 'vector' "
  166. "(or 'text', which it embeds) and stores it correctly for you"
  167. : "a document inserted into a vector collection must carry '_vector', or "
  168. "it can never be found by a search. This route does not embed: POST "
  169. ".../vectors with 'text' to have it embedded for you, or use a json "
  170. "collection if this row is not meant to be searchable");
  171. // AND THE VECTOR HAS TO BE THE RIGHT SHAPE, which this route checked
  172. // nowhere while its two siblings both did. `POST .../vectors` and the
  173. // runner's `.store()` each compare the resolved vector against the
  174. // collection's pin and answer 422 `dimension_mismatch`; here the body
  175. // went straight to the database, which refuses it as a bare
  176. // `ErrorCode::Internal` carrying no `reason` - so `apiErrorFor` maps it
  177. // to **500 `internal`**, telling a caller their own permanent,
  178. // correctable mistake is our outage. Measured through the shipped debs:
  179. // a length-3 vector into a dim-4 collection answered 500
  180. // `internal` here and 422 `dimension_mismatch` on `.../vectors`, for
  181. // the same fault in the same collection.
  182. //
  183. // The fix belongs on OUR side rather than in the error mapping: we hold
  184. // the pin, so the length is answerable before the call, and the only
  185. // other way to classify the database's refusal would be to match on its
  186. // message text. The guard is the same CLASS as the presence check
  187. // directly above it - a vector collection takes a vector, and it takes
  188. // one of its own width - which is why it goes here and not behind a
  189. // database round trip.
  190. //
  191. // A non-array `_vector` is the same refusal rather than its own: the
  192. // caller's remedy is identical, and two slugs would send them looking
  193. // for two fixes.
  194. if (t.meta.kind == "vector") {
  195. const auto& v = data.at("_vector");
  196. if (!v.is_array() || v.size() != t.meta.vectorDimension)
  197. throw ApiError(ErrCode::Unprocessable, "dimension_mismatch",
  198. "'_vector' must be an array of " +
  199. std::to_string(t.meta.vectorDimension) +
  200. " numbers, which is this collection's pinned dimension; got " +
  201. (v.is_array() ? std::to_string(v.size()) + " elements"
  202. : std::string("a ") + v.type_name()));
  203. }
  204. const uint32_t ttl = ttlParam(req).value_or(0);
  205. std::string newId;
  206. try {
  207. newId = d->db.client().insert(t.qualified, data, id, ttl);
  208. } catch (const smartbotic::database::Client::Error& e) {
  209. throw apiErrorFor(e);
  210. }
  211. if (newId.empty()) throw ApiError(ErrCode::Unavailable, "db_error", "insert failed");
  212. sendJson(res, 201, {{"id", newId}});
  213. });
  214. svr.Get(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
  215. Target t = scoped(d, req, 1, 2, KeyOp::Read);
  216. auto doc = d->db.client().get(t.qualified, req.matches[3]);
  217. if (!doc) throw ApiError(ErrCode::NotFound, "not_found", "no such document");
  218. // The body is the stored document plus the database's read-only
  219. // metadata (`_id`, `_version`, `_created_at`, `_updated_at`,
  220. // `_created_by`, `_updated_by`). `_version` is the value `?if_version=`
  221. // takes, so it is also echoed as an ETag: that is where an HTTP client
  222. // or cache looks for a resource version, and it costs nothing here.
  223. if (auto v = documentVersion(*doc))
  224. res.set_header("ETag", "\"" + std::to_string(*v) + "\"");
  225. sendJson(res, 200, *doc);
  226. });
  227. svr.Get(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
  228. Target t = scoped(d, req, 1, 2, KeyOp::List);
  229. // The sibling routes' spellings are the ones worth refusing here:
  230. // `order=desc` is how the index-values route says it and `q=` is how
  231. // the collections listing says it, so a caller moving between our own
  232. // routes is the likeliest author of a parameter we would otherwise
  233. // accept and ignore. This route DOES implement `limit`, `offset`,
  234. // `sort` and `desc`, which is why accepting those is correct and
  235. // refusing them on index-values was not - the rule is "refuse what
  236. // you cannot honour", never a fixed list of names.
  237. requireHonourableParams(req,
  238. {{"order", "desc"}, {"asc", "desc"}, {"sort_by", "sort"},
  239. {"q", "filter"}, {"search", "filter"}, {"where", "filter"},
  240. {"page"}, {"cursor"}, {"after"}, {"skip"}, {"fields"}},
  241. {"filter", "limit", "offset", "sort", "desc"},
  242. "`filter` is repeatable and takes `field:op:value`");
  243. smartbotic::database::Client::QueryOptions opts;
  244. auto range = req.params.equal_range("filter");
  245. for (auto it = range.first; it != range.second; ++it) opts.filters.push_back(parseFilter(it->second));
  246. auto parseUInt = [](const std::string& v, const char* name) -> uint32_t {
  247. try { return (uint32_t)std::stoul(v); }
  248. catch (...) { throw ApiError(ErrCode::Unprocessable, "validation", std::string(name) + " must be a non-negative integer"); }
  249. };
  250. if (req.has_param("limit")) opts.limit = parseUInt(req.get_param_value("limit"), "limit");
  251. if (req.has_param("offset")) opts.offset = parseUInt(req.get_param_value("offset"), "offset");
  252. if (req.has_param("sort")) opts.sortField = req.get_param_value("sort");
  253. if (req.has_param("desc")) opts.sortDescending = (req.get_param_value("desc") == "true");
  254. // Each listed document carries the same `_id`/`_version` metadata a
  255. // single GET returns, so a filtered listing is a usable starting point
  256. // for a conditional write without a second round trip per row.
  257. //
  258. // `findWithMetrics` RATHER THAN `find`, AND IT COSTS NOTHING. Both
  259. // issue the identical single `Find` RPC with a byte-identical request
  260. // (client.cpp:964 against :1033 at the 2.20.0 pin); `find` simply drops
  261. // two fields of the response on the floor. The server computes both
  262. // BEFORE pagination, so `total` is the exact number of rows matching
  263. // the filters, not an estimate and not a page count.
  264. //
  265. // WHY IT MATTERS, measured with a consumer 2026-11-20: the only way to
  266. // learn that number was to page the whole matching set, and for one
  267. // real filter on a 13,093-row collection that is a full scan plus 1750
  268. // documents of encoding to obtain one integer. A customer-facing review
  269. // portal had just dropped its result count as unaffordable - for a
  270. // number that was arriving in every response it already made and being
  271. // discarded one frame short of the caller.
  272. //
  273. // `has_more` and `total`, matching the FILES listing (files.cpp) rather
  274. // than the database's own `total_count` wire name. Two spellings for one
  275. // concept across two of our own listing routes is exactly how the next
  276. // drift starts, and this file already records what it costs when a
  277. // caller learns a parameter's name on a sibling route.
  278. //
  279. // `count` is UNCHANGED and still the page size. Keeping it is the
  280. // additive discipline `details.unsupported` kept: callers parse it
  281. // today, and redefining a field in place is worse than adding two.
  282. //
  283. // Emitted UNCONDITIONALLY - unfiltered, empty, and on the last page -
  284. // so an absent field means exactly one thing, a server older than this
  285. // release. A flag present only when interesting is this codebase's most
  286. // repeated trap.
  287. //
  288. // One asymmetry worth knowing before anyone extends this route:
  289. // `findWithMetrics` has no `include_vector` parameter, where `find`
  290. // grew one in 2.13.0. Behaviour is identical today because the 2-arg
  291. // `find` defaults it to false and this listing never returned vectors,
  292. // but "also return the vectors" cannot be built on this overload.
  293. const auto page = d->db.client().findWithMetrics(t.qualified, opts);
  294. sendJson(res, 200, {{"documents", page.documents},
  295. {"count", page.documents.size()},
  296. {"has_more", page.hasMore},
  297. {"total", page.totalCount}});
  298. });
  299. svr.Patch(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
  300. Target t = scoped(d, req, 1, 2, KeyOp::Update);
  301. std::string id = req.matches[3];
  302. const auto ttl = ttlParam(req);
  303. const auto ifVersion = ifVersionParam(req);
  304. nlohmann::json patchBody = documentBody(bodyJson(req));
  305. if (!ifVersion) {
  306. // A patch is a server-side merge: it reads nothing out and cannot
  307. // lose a concurrent writer's fields.
  308. //
  309. // THERE USED TO BE AN `exists()` PROBE HERE AND IT WAS REMOVED,
  310. // because it could answer an UNRETRYABLE 404 for a document that
  311. // exists. `Client::exists` conflates "no such document" with "the
  312. // call failed" - the same defect `CollectionRegistry::get` records
  313. // and that cost a consumer a 6-minute ingest of an 8 GB mailbox
  314. // when a transport blip became "no such collection". A 404 is
  315. // unretryable BY DESIGN for a careful client, because adding it to
  316. // a retry set would retry every genuine absence, so a transient
  317. // failure here was permanent for the caller.
  318. //
  319. // Removing it is free, which is the part worth knowing rather than
  320. // rediscovering: `patch()` ALREADY reports the absent case through
  321. // its `Failure`, where code `Ok` on a call returning 0 means "did
  322. // not apply" and maps to 404, while a transport failure arrives as
  323. // Unavailable and maps to 503. So the probe bought nothing for
  324. // correctness, cost an extra round trip, and could only ever turn a
  325. // 503 into a 404. Measured before deleting it, with a control:
  326. // with no probe, PATCH of an absent document still answers 404
  327. // not_found, and PATCH of a document that exists still answers 200.
  328. //
  329. // It also made a live diagnosis harder than it needed to be. A
  330. // consumer met a document that reads fine and refuses every write,
  331. // and this probe was the obvious suspect precisely because it sits
  332. // on one of the three write paths - but PUT uses `get()` and DELETE
  333. // uses `remove()`, neither touches `exists()`, and all three answer
  334. // the same 404. The probe was never the cause and could not have
  335. // been; see the ghost-document note in CLAUDE.md.
  336. smartbotic::database::Client::Failure failure;
  337. uint64_t v = ttl ? d->db.client().patchWithTtl(t.qualified, id, patchBody, *ttl, failure)
  338. : d->db.client().patch(t.qualified, id, patchBody, failure);
  339. if (v == 0) throw apiErrorFor(failure, "no such document");
  340. sendJson(res, 200, {{"id", id}, {"version", v}});
  341. return;
  342. }
  343. // Conditional patch, in ONE call. The database applies the merge and
  344. // checks the version server-side, so there is no window at all - not
  345. // even the narrow one a read-merge-write with a version check leaves,
  346. // and no need to reconstruct the server's merge semantics here.
  347. //
  348. // The one thing it cannot carry is an expiry: there is no conditional
  349. // patch-with-TTL, and silently dropping one of the two would be worse
  350. // than refusing.
  351. if (ttl)
  352. throw ApiError(ErrCode::Unprocessable, "conditional_unsupported",
  353. "if_version cannot be combined with ttl_seconds on PATCH: "
  354. "set the expiry in a separate unconditional request");
  355. smartbotic::database::Client::FailureDetail detail;
  356. const uint64_t newVersion =
  357. d->db.client().patchIfVersion(t.qualified, id, patchBody, *ifVersion, detail);
  358. // A stale version is Aborted with reason "version_conflict" and the
  359. // version it actually found, so the caller is told what to re-read
  360. // rather than being left to guess.
  361. if (newVersion == 0) throw conditionalFailure(detail, *ifVersion);
  362. sendJson(res, 200, {{"id", id}, {"version", newVersion}});
  363. });
  364. svr.Put(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
  365. // AUTHORIZE first, then the REQUEST, then the RESOURCE - see
  366. // `authorized()` above. The parameter refusal below must come before
  367. // the collection's 404, or the same refused parameter answers 422 on a
  368. // collection that exists and 404 on one that does not.
  369. Target t = authorized(d, req, 1, 2, KeyOp::Update);
  370. std::string id = req.matches[3];
  371. // REFUSE `?ttl_seconds=` HERE, because this route CANNOT honour it and
  372. // was answering 201 as though it had.
  373. //
  374. // Reported by a consumer 2026-10-22, and the cost is the reason this
  375. // is a defect rather than an ergonomic wish: they PUT a row with
  376. // `?ttl_seconds=3600`, got a **201**, and read it back with no
  377. // `_expires_at` at all - i.e. PERMANENT. The whole point of their
  378. // change was to stop a restore recreating an immortal at-most-once
  379. // marker, so the silent drop produced exactly the bug the feature
  380. // existed to prevent, and their restore reported success either way.
  381. // Only a read-back caught it.
  382. //
  383. // It cannot be repaired by honouring it instead: the database client's
  384. // update path takes NO ttlSeconds (only insert, upsert and
  385. // `patchWithTtl` do), so a replace has nowhere to put an expiry. And
  386. // honouring it on the create half of this route while dropping it on
  387. // the replace half would be worse than either - a parameter that works
  388. // until the row exists.
  389. //
  390. // Scoped to `ttl_seconds` deliberately rather than refusing every
  391. // unknown parameter: a query string legitimately carries a
  392. // cache-buster or a proxy's addition, and this route's siblings POST
  393. // and PATCH both DO honour `ttl_seconds`, which is what makes a caller
  394. // reaching for it here non-hypothetical rather than invented.
  395. requireHonourableParams(
  396. req, {{"ttl_seconds"}}, {"if_version"},
  397. "a whole-document replace cannot carry an expiry - the database's update path takes "
  398. "no TTL. POST with an id to create a row WITH one, or PATCH to set or clear it on a "
  399. "row that already exists");
  400. // The resource LAST of the three.
  401. requireCollection(d, t);
  402. const auto ifVersion = ifVersionParam(req);
  403. nlohmann::json data = documentBody(bodyJson(req));
  404. // A REPLACE on a vector collection destroys the stored embedding, and
  405. // the caller cannot prevent it.
  406. //
  407. // Measured: on a kind=vector collection a merge PATCH preserves the
  408. // vector, while a whole-document update drops it - the call returns
  409. // success and the document stops being searchable. The database
  410. // consumes `_vector` into its index on write and returns it from
  411. // nothing (not get, not find, not similaritySearch), so a caller doing
  412. // read-modify-write CANNOT put it back: there is no way to read it.
  413. // That makes PUT an embedding-destroying operation that looks like an
  414. // ordinary write, on data that cost money to produce.
  415. //
  416. // So refuse it unless the body carries a vector, and name both ways
  417. // out. Not a silent repair: re-embedding here would spend the
  418. // project's embedding credit on a request that never asked for it.
  419. if (t.meta.kind == "vector" && !data.contains("_vector") && !data.contains("vector"))
  420. throw ApiError(ErrCode::Unprocessable, "vector_replace_unsafe",
  421. "replacing a document in a vector collection would discard its stored "
  422. "embedding, which cannot be read back to include here. Use PATCH to "
  423. "change fields without touching the vector, or POST .../vectors to "
  424. "store a document together with its vector");
  425. // PUT creates the document when it is absent, which is what the method
  426. // means and what this API has always documented. The alternative - 404
  427. // plus a separate upsert route - would give PUT a meaning HTTP does not
  428. // have and leave callers keyed by an id they receive from elsewhere (a
  429. // provider's call id, say) doing a probe request before every write.
  430. // It grants no new power either: POST already stores at a
  431. // caller-supplied id.
  432. //
  433. // PATCH deliberately keeps its 404: merging fields into a document that
  434. // does not exist has no defined result, and a PATCH body is not a whole
  435. // document, so creating from one would store something the caller never
  436. // described.
  437. for (int attempt = 0;; ++attempt) {
  438. // A read, not an exists() probe: the version comes out of the same
  439. // call, and the replace path needed a read anyway (Client::update
  440. // does one internally).
  441. auto current = d->db.client().get(t.qualified, id);
  442. if (!current) {
  443. if (ifVersion) {
  444. // A conditional write never creates: there is no version to
  445. // match, and answering 201 would make `?if_version=` look
  446. // like it had been honoured.
  447. throw ApiError(ErrCode::NotFound, "not_found", "no such document");
  448. }
  449. // Creating is an insert however it is spelled. A key whose
  450. // scope grants `update` but not `insert` must not gain the
  451. // ability to create rows by using PUT instead of POST. Checked
  452. // against the scope directly rather than through
  453. // requireCapability(), which also spends a rate-limit token:
  454. // this request already spent one, and one request must cost one
  455. // token however many rules it is measured against.
  456. if (t.key.scope && !t.key.scope->findRule(t.name, KeyOp::Insert))
  457. throw ApiError(ErrCode::Forbidden, "forbidden",
  458. "scope permits update but not insert, so PUT may only "
  459. "replace a document that already exists");
  460. try {
  461. d->db.client().insert(t.qualified, data, id, 0);
  462. } catch (const smartbotic::database::Client::Error& e) {
  463. // Another writer created this id between our read and the
  464. // insert. The request still means "make the document look
  465. // like this", so one retry takes the replace branch.
  466. //
  467. // Narrowly matched: an id collision reaches us as a generic
  468. // internal error naming the id, while a unique-index
  469. // collision is AlreadyExists and must surface at once -
  470. // retrying that would only refuse again, one 409 later.
  471. const bool idTaken =
  472. e.code() == smartbotic::database::Client::ErrorCode::Internal &&
  473. std::string(e.what()).find("already exists") != std::string::npos;
  474. if (idTaken && attempt == 0) continue;
  475. throw apiErrorFor(e);
  476. }
  477. // An insert always produces version 1.
  478. res.set_header("Location", req.path);
  479. sendJson(res, 201, {{"id", id}, {"created", true}, {"version", 1}});
  480. return;
  481. }
  482. auto have = documentVersion(*current);
  483. if (!have)
  484. throw ApiError(ErrCode::Unavailable, "db_error",
  485. "the database did not report a document version");
  486. if (ifVersion && *have != *ifVersion) throw versionConflict(*ifVersion, have);
  487. // Version-checked even when the caller named no version: that is
  488. // what Client::update() does internally, and doing it here means
  489. // the new version is known without a second read. Without a named
  490. // version a conflict is another writer and is retried; with one it
  491. // is the answer the caller asked for.
  492. const uint64_t expected = ifVersion.value_or(*have);
  493. smartbotic::database::Client::FailureDetail detail;
  494. if (d->db.client().updateIfVersion(t.qualified, id, data, expected, detail)) {
  495. sendJson(res, 200, {{"id", id}, {"created", false}, {"version", expected + 1}});
  496. return;
  497. }
  498. // Aborted is the database saying the version moved, and it reports
  499. // the version it actually found - no second read needed, and no
  500. // guessing from the message text.
  501. if (detail.code == smartbotic::database::Client::ErrorCode::Aborted) {
  502. // An explicit if_version is the caller's condition: tell it.
  503. if (ifVersion) throw conditionalFailure(detail, *ifVersion);
  504. // No if_version: the replace simply lost a race. Re-read and
  505. // write again, and after a bounded number of tries report the
  506. // conflict rather than blaming the database with a 503.
  507. if (attempt < 3) continue;
  508. throw conditionalFailure(detail, expected);
  509. }
  510. throw apiErrorFor(detail, "no such document");
  511. }
  512. });
  513. // Atomic counters: one locked server-side read-modify-write per call, so
  514. // concurrent increments cannot lose each other the way a read, add and
  515. // write-back does however carefully it is version-checked.
  516. //
  517. // POST on a sub-resource rather than a flag on PATCH, because a PATCH body
  518. // and an increment body look identical and mean opposite things: {"calls":1}
  519. // is "set calls to 1" on PATCH and "add 1 to calls" here. One body shape
  520. // with two meanings decided by a query parameter is the kind of API where a
  521. // forgotten parameter silently resets a counter to 1. It is also not
  522. // idempotent, which POST is allowed to be and PUT is not.
  523. //
  524. // KeyOp::Update: it is a write, so a scope granting only `read` never
  525. // reaches it, and it is specifically an update - the database requires the
  526. // document to exist and this route creates nothing. Not a new KeyOp of its
  527. // own: a key that may replace a document may already set any number to any
  528. // value, so increment grants no power `update` did not, and inventing an op
  529. // would silently strip the ability from every scope already granting it.
  530. svr.Post(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents/([^/]+)/increment)",
  531. [d](const httplib::Request& req, httplib::Response& res) {
  532. Target t = scoped(d, req, 1, 2, KeyOp::Update);
  533. const std::string id = req.matches[3];
  534. nlohmann::json deltas = incrementDeltas(bodyJson(req));
  535. smartbotic::database::Client::FailureDetail detail;
  536. auto values = d->db.client().increment(t.qualified, id, deltas, detail);
  537. // 404 on a missing document, deliberately not an implicit create: the
  538. // starting document is the caller's to describe, and a counter conjured
  539. // from a typo'd id is a counter nobody ever reads. The idiom is
  540. // increment, then on 404 POST the document at a fixed id, then on 409
  541. // increment again - which is safe because that POST is the only thing
  542. // that can create it.
  543. //
  544. // Everything else keeps the database's own classification: a field
  545. // holding a non-number is InvalidArgument and so 422, integer overflow
  546. // likewise, and nothing at all was applied in either case.
  547. if (!values) throw apiErrorFor(detail, "no such document");
  548. // The new values are the entire point of the call, so 200 with a body
  549. // rather than 204: a caller that has to re-read to learn what its
  550. // increment produced has lost the atomicity it came here for.
  551. sendJson(res, 200, {{"id", id}, {"values", *values}});
  552. });
  553. svr.Delete(R"(/api/v1(?:/projects/([^/]+))?/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
  554. Target t = scoped(d, req, 1, 2, KeyOp::Delete);
  555. std::string id = req.matches[3];
  556. smartbotic::database::Client::Failure failure;
  557. if (!d->db.client().remove(t.qualified, id, failure)) {
  558. // A restrict relation is the one refusal a caller can act on, so it
  559. // gets 409 plus the impact list rather than a generic failure. Only
  560. // ask for the impacts when the database says a precondition failed;
  561. // previously every failure took this path and then answered 404,
  562. // which was wrong for a transport error.
  563. if (failure.code == smartbotic::database::Client::ErrorCode::FailedPrecondition) {
  564. auto why = d->db.client().describeDelete(t.qualified, id);
  565. if (why.success && why.wouldBeBlocked)
  566. throw ApiError(ErrCode::Conflict, "relation_restricted",
  567. "delete blocked by a relation",
  568. {{"impacts", impactsJson(t.project, why)}});
  569. }
  570. throw apiErrorFor(failure, "no such document");
  571. }
  572. sendJson(res, 200, {{"deleted", id}});
  573. });
  574. }
  575. }