documents.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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 "server.hpp"
  8. #include <string>
  9. #include <vector>
  10. #include <cstdlib>
  11. #include <limits>
  12. #include <optional>
  13. namespace svapi {
  14. namespace {
  15. // Everything a document route needs about its target once the caller has been
  16. // authorized: the key (PUT re-checks it on the create branch), the unqualified
  17. // names for anything caller-facing, the qualified name for the database, and
  18. // the registry entry, which carries the collection's kind.
  19. struct Target {
  20. ApiKey key;
  21. std::string project;
  22. std::string name;
  23. std::string qualified;
  24. CollectionMeta meta;
  25. };
  26. // Authorize + verify the collection exists.
  27. Target scoped(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) {
  28. Target t;
  29. t.key = requireKey(*d, req);
  30. t.project = req.matches[projIdx];
  31. t.name = req.matches[collIdx];
  32. requireCapability(*d, t.key, req, t.project, t.name, op);
  33. auto meta = d->registry.get(t.project, t.name);
  34. if (!meta) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
  35. t.meta = *meta;
  36. t.qualified = qualify(t.project, t.name);
  37. return t;
  38. }
  39. // Parses ?ttl_seconds=. Returns nullopt when absent - the caller must
  40. // distinguish "not supplied" (leave expiry alone) from 0 (clear the expiry).
  41. std::optional<uint32_t> ttlParam(const httplib::Request& req) {
  42. if (!req.has_param("ttl_seconds")) return std::nullopt;
  43. const std::string raw = req.get_param_value("ttl_seconds");
  44. if (raw.empty() || raw.find_first_not_of("0123456789") != std::string::npos)
  45. throw ApiError(ErrCode::Unprocessable, "validation", "ttl_seconds must be a non-negative integer");
  46. unsigned long long wide = std::strtoull(raw.c_str(), nullptr, 10);
  47. if (wide > std::numeric_limits<uint32_t>::max())
  48. throw ApiError(ErrCode::Unprocessable, "validation", "ttl_seconds must be a non-negative integer");
  49. return (uint32_t)wide;
  50. }
  51. // Parses ?if_version=. Absent means an unconditional write.
  52. std::optional<uint64_t> ifVersionParam(const httplib::Request& req) {
  53. if (!req.has_param("if_version")) return std::nullopt;
  54. return parseVersionValue(req.get_param_value("if_version"));
  55. }
  56. // 409 for the one case the database cannot report: the version was already
  57. // wrong when we read it, so no write was attempted and there is no failure to
  58. // translate. A conflict the DATABASE refuses comes back as ErrorCode::Aborted
  59. // carrying the version it found, and goes through conditionalFailure() below.
  60. ApiError versionConflict(uint64_t expected, std::optional<uint64_t> current) {
  61. nlohmann::json det{{"expected_version", expected}};
  62. if (current) det["current_version"] = *current;
  63. return ApiError(ErrCode::Conflict, "version_conflict",
  64. "the document is not at the expected version", det);
  65. }
  66. // A failed conditional write, with both halves of the story.
  67. //
  68. // The database reports the version it FOUND; only the caller knows which
  69. // version it ASKED for. Neither alone lets a client decide what to do, so they
  70. // are merged here rather than leaving the caller to remember its own request.
  71. ApiError conditionalFailure(const smartbotic::database::Client::FailureDetail& detail,
  72. uint64_t expected) {
  73. ApiError e = apiErrorFor(detail, "no such document");
  74. e.details["expected_version"] = expected;
  75. return e;
  76. }
  77. } // namespace
  78. void registerDocumentRoutes(ApiServer& s) {
  79. auto& svr = s.raw(); ServerDeps* d = &s.deps();
  80. svr.Post(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
  81. Target t = scoped(d, req, 1, 2, KeyOp::Insert);
  82. auto body = bodyJson(req);
  83. std::string id = body.value("id", "");
  84. nlohmann::json data = documentBody(body);
  85. // The sibling of `vector_replace_unsafe` above, arriving through a
  86. // different door. A document inserted into a VECTOR collection with no
  87. // vector reads back perfectly and can never be found by any search - it
  88. // has no embedding, and no read path returns one, so nothing about it
  89. // looks wrong.
  90. //
  91. // Reported from production with the only symptom it has: a 12448-row
  92. // collection whose three indexed facets each summed to 12447, the extra
  93. // row being a query body posted to this route by mistake.
  94. //
  95. // `text` DOES NOT SATISFY THIS, and that is the whole subtlety. THIS
  96. // ROUTE DOES NOT EMBED - only the vectors route does. An earlier
  97. // version of this guard accepted `text` on the assumption that a row
  98. // with text becomes searchable, which is true of `.../vectors` and
  99. // false here: it would have stored the exact invisible row the guard
  100. // exists to refuse, while looking like it had allowed ordinary ingest.
  101. // Caught by a consumer asking whether an EMPTY text would satisfy it,
  102. // which made me check whether a NON-empty one should.
  103. //
  104. // So the rule is simply: a vector collection takes a vector. Text goes
  105. // to `.../vectors`, which embeds it.
  106. if (t.meta.kind == "vector" && !data.contains("_vector") && !data.contains("vector"))
  107. throw ApiError(ErrCode::Unprocessable, "vector_missing",
  108. "a document inserted into a vector collection must carry '_vector', or "
  109. "it can never be found by a search. This route does not embed: POST "
  110. ".../vectors with 'text' to have it embedded for you, or use a json "
  111. "collection if this row is not meant to be searchable");
  112. const uint32_t ttl = ttlParam(req).value_or(0);
  113. std::string newId;
  114. try {
  115. newId = d->db.client().insert(t.qualified, data, id, ttl);
  116. } catch (const smartbotic::database::Client::Error& e) {
  117. throw apiErrorFor(e);
  118. }
  119. if (newId.empty()) throw ApiError(ErrCode::Unavailable, "db_error", "insert failed");
  120. sendJson(res, 201, {{"id", newId}});
  121. });
  122. svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
  123. Target t = scoped(d, req, 1, 2, KeyOp::Read);
  124. auto doc = d->db.client().get(t.qualified, req.matches[3]);
  125. if (!doc) throw ApiError(ErrCode::NotFound, "not_found", "no such document");
  126. // The body is the stored document plus the database's read-only
  127. // metadata (`_id`, `_version`, `_created_at`, `_updated_at`,
  128. // `_created_by`, `_updated_by`). `_version` is the value `?if_version=`
  129. // takes, so it is also echoed as an ETag: that is where an HTTP client
  130. // or cache looks for a resource version, and it costs nothing here.
  131. if (auto v = documentVersion(*doc))
  132. res.set_header("ETag", "\"" + std::to_string(*v) + "\"");
  133. sendJson(res, 200, *doc);
  134. });
  135. svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
  136. Target t = scoped(d, req, 1, 2, KeyOp::List);
  137. smartbotic::database::Client::QueryOptions opts;
  138. auto range = req.params.equal_range("filter");
  139. for (auto it = range.first; it != range.second; ++it) opts.filters.push_back(parseFilter(it->second));
  140. auto parseUInt = [](const std::string& v, const char* name) -> uint32_t {
  141. try { return (uint32_t)std::stoul(v); }
  142. catch (...) { throw ApiError(ErrCode::Unprocessable, "validation", std::string(name) + " must be a non-negative integer"); }
  143. };
  144. if (req.has_param("limit")) opts.limit = parseUInt(req.get_param_value("limit"), "limit");
  145. if (req.has_param("offset")) opts.offset = parseUInt(req.get_param_value("offset"), "offset");
  146. if (req.has_param("sort")) opts.sortField = req.get_param_value("sort");
  147. if (req.has_param("desc")) opts.sortDescending = (req.get_param_value("desc") == "true");
  148. // Each listed document carries the same `_id`/`_version` metadata a
  149. // single GET returns, so a filtered listing is a usable starting point
  150. // for a conditional write without a second round trip per row.
  151. auto docs = d->db.client().find(t.qualified, opts);
  152. sendJson(res, 200, {{"documents", docs}, {"count", docs.size()}});
  153. });
  154. svr.Patch(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
  155. Target t = scoped(d, req, 1, 2, KeyOp::Update);
  156. std::string id = req.matches[3];
  157. const auto ttl = ttlParam(req);
  158. const auto ifVersion = ifVersionParam(req);
  159. nlohmann::json patchBody = documentBody(bodyJson(req));
  160. if (!ifVersion) {
  161. // A patch is a server-side merge: it reads nothing out and cannot
  162. // lose a concurrent writer's fields. The existence probe stays a
  163. // probe rather than a read, so the common path does not pay for
  164. // fetching a document it does not look at.
  165. if (!d->db.client().exists(t.qualified, id))
  166. throw ApiError(ErrCode::NotFound, "not_found", "no such document");
  167. smartbotic::database::Client::Failure failure;
  168. uint64_t v = ttl ? d->db.client().patchWithTtl(t.qualified, id, patchBody, *ttl, failure)
  169. : d->db.client().patch(t.qualified, id, patchBody, failure);
  170. if (v == 0) throw apiErrorFor(failure, "no such document");
  171. sendJson(res, 200, {{"id", id}, {"version", v}});
  172. return;
  173. }
  174. // Conditional patch, in ONE call. The database applies the merge and
  175. // checks the version server-side, so there is no window at all - not
  176. // even the narrow one a read-merge-write with a version check leaves,
  177. // and no need to reconstruct the server's merge semantics here.
  178. //
  179. // The one thing it cannot carry is an expiry: there is no conditional
  180. // patch-with-TTL, and silently dropping one of the two would be worse
  181. // than refusing.
  182. if (ttl)
  183. throw ApiError(ErrCode::Unprocessable, "conditional_unsupported",
  184. "if_version cannot be combined with ttl_seconds on PATCH: "
  185. "set the expiry in a separate unconditional request");
  186. smartbotic::database::Client::FailureDetail detail;
  187. const uint64_t newVersion =
  188. d->db.client().patchIfVersion(t.qualified, id, patchBody, *ifVersion, detail);
  189. // A stale version is Aborted with reason "version_conflict" and the
  190. // version it actually found, so the caller is told what to re-read
  191. // rather than being left to guess.
  192. if (newVersion == 0) throw conditionalFailure(detail, *ifVersion);
  193. sendJson(res, 200, {{"id", id}, {"version", newVersion}});
  194. });
  195. svr.Put(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
  196. Target t = scoped(d, req, 1, 2, KeyOp::Update);
  197. std::string id = req.matches[3];
  198. const auto ifVersion = ifVersionParam(req);
  199. nlohmann::json data = documentBody(bodyJson(req));
  200. // A REPLACE on a vector collection destroys the stored embedding, and
  201. // the caller cannot prevent it.
  202. //
  203. // Measured: on a kind=vector collection a merge PATCH preserves the
  204. // vector, while a whole-document update drops it - the call returns
  205. // success and the document stops being searchable. The database
  206. // consumes `_vector` into its index on write and returns it from
  207. // nothing (not get, not find, not similaritySearch), so a caller doing
  208. // read-modify-write CANNOT put it back: there is no way to read it.
  209. // That makes PUT an embedding-destroying operation that looks like an
  210. // ordinary write, on data that cost money to produce.
  211. //
  212. // So refuse it unless the body carries a vector, and name both ways
  213. // out. Not a silent repair: re-embedding here would spend the
  214. // project's embedding credit on a request that never asked for it.
  215. if (t.meta.kind == "vector" && !data.contains("_vector") && !data.contains("vector"))
  216. throw ApiError(ErrCode::Unprocessable, "vector_replace_unsafe",
  217. "replacing a document in a vector collection would discard its stored "
  218. "embedding, which cannot be read back to include here. Use PATCH to "
  219. "change fields without touching the vector, or POST .../vectors to "
  220. "store a document together with its vector");
  221. // PUT creates the document when it is absent, which is what the method
  222. // means and what this API has always documented. The alternative - 404
  223. // plus a separate upsert route - would give PUT a meaning HTTP does not
  224. // have and leave callers keyed by an id they receive from elsewhere (a
  225. // provider's call id, say) doing a probe request before every write.
  226. // It grants no new power either: POST already stores at a
  227. // caller-supplied id.
  228. //
  229. // PATCH deliberately keeps its 404: merging fields into a document that
  230. // does not exist has no defined result, and a PATCH body is not a whole
  231. // document, so creating from one would store something the caller never
  232. // described.
  233. for (int attempt = 0;; ++attempt) {
  234. // A read, not an exists() probe: the version comes out of the same
  235. // call, and the replace path needed a read anyway (Client::update
  236. // does one internally).
  237. auto current = d->db.client().get(t.qualified, id);
  238. if (!current) {
  239. if (ifVersion) {
  240. // A conditional write never creates: there is no version to
  241. // match, and answering 201 would make `?if_version=` look
  242. // like it had been honoured.
  243. throw ApiError(ErrCode::NotFound, "not_found", "no such document");
  244. }
  245. // Creating is an insert however it is spelled. A key whose
  246. // scope grants `update` but not `insert` must not gain the
  247. // ability to create rows by using PUT instead of POST. Checked
  248. // against the scope directly rather than through
  249. // requireCapability(), which also spends a rate-limit token:
  250. // this request already spent one, and one request must cost one
  251. // token however many rules it is measured against.
  252. if (t.key.scope && !t.key.scope->findRule(t.name, KeyOp::Insert))
  253. throw ApiError(ErrCode::Forbidden, "forbidden",
  254. "scope permits update but not insert, so PUT may only "
  255. "replace a document that already exists");
  256. try {
  257. d->db.client().insert(t.qualified, data, id, 0);
  258. } catch (const smartbotic::database::Client::Error& e) {
  259. // Another writer created this id between our read and the
  260. // insert. The request still means "make the document look
  261. // like this", so one retry takes the replace branch.
  262. //
  263. // Narrowly matched: an id collision reaches us as a generic
  264. // internal error naming the id, while a unique-index
  265. // collision is AlreadyExists and must surface at once -
  266. // retrying that would only refuse again, one 409 later.
  267. const bool idTaken =
  268. e.code() == smartbotic::database::Client::ErrorCode::Internal &&
  269. std::string(e.what()).find("already exists") != std::string::npos;
  270. if (idTaken && attempt == 0) continue;
  271. throw apiErrorFor(e);
  272. }
  273. // An insert always produces version 1.
  274. res.set_header("Location", req.path);
  275. sendJson(res, 201, {{"id", id}, {"created", true}, {"version", 1}});
  276. return;
  277. }
  278. auto have = documentVersion(*current);
  279. if (!have)
  280. throw ApiError(ErrCode::Unavailable, "db_error",
  281. "the database did not report a document version");
  282. if (ifVersion && *have != *ifVersion) throw versionConflict(*ifVersion, have);
  283. // Version-checked even when the caller named no version: that is
  284. // what Client::update() does internally, and doing it here means
  285. // the new version is known without a second read. Without a named
  286. // version a conflict is another writer and is retried; with one it
  287. // is the answer the caller asked for.
  288. const uint64_t expected = ifVersion.value_or(*have);
  289. smartbotic::database::Client::FailureDetail detail;
  290. if (d->db.client().updateIfVersion(t.qualified, id, data, expected, detail)) {
  291. sendJson(res, 200, {{"id", id}, {"created", false}, {"version", expected + 1}});
  292. return;
  293. }
  294. // Aborted is the database saying the version moved, and it reports
  295. // the version it actually found - no second read needed, and no
  296. // guessing from the message text.
  297. if (detail.code == smartbotic::database::Client::ErrorCode::Aborted) {
  298. // An explicit if_version is the caller's condition: tell it.
  299. if (ifVersion) throw conditionalFailure(detail, *ifVersion);
  300. // No if_version: the replace simply lost a race. Re-read and
  301. // write again, and after a bounded number of tries report the
  302. // conflict rather than blaming the database with a 503.
  303. if (attempt < 3) continue;
  304. throw conditionalFailure(detail, expected);
  305. }
  306. throw apiErrorFor(detail, "no such document");
  307. }
  308. });
  309. // Atomic counters: one locked server-side read-modify-write per call, so
  310. // concurrent increments cannot lose each other the way a read, add and
  311. // write-back does however carefully it is version-checked.
  312. //
  313. // POST on a sub-resource rather than a flag on PATCH, because a PATCH body
  314. // and an increment body look identical and mean opposite things: {"calls":1}
  315. // is "set calls to 1" on PATCH and "add 1 to calls" here. One body shape
  316. // with two meanings decided by a query parameter is the kind of API where a
  317. // forgotten parameter silently resets a counter to 1. It is also not
  318. // idempotent, which POST is allowed to be and PUT is not.
  319. //
  320. // KeyOp::Update: it is a write, so a scope granting only `read` never
  321. // reaches it, and it is specifically an update - the database requires the
  322. // document to exist and this route creates nothing. Not a new KeyOp of its
  323. // own: a key that may replace a document may already set any number to any
  324. // value, so increment grants no power `update` did not, and inventing an op
  325. // would silently strip the ability from every scope already granting it.
  326. svr.Post(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+)/increment)",
  327. [d](const httplib::Request& req, httplib::Response& res) {
  328. Target t = scoped(d, req, 1, 2, KeyOp::Update);
  329. const std::string id = req.matches[3];
  330. nlohmann::json deltas = incrementDeltas(bodyJson(req));
  331. smartbotic::database::Client::FailureDetail detail;
  332. auto values = d->db.client().increment(t.qualified, id, deltas, detail);
  333. // 404 on a missing document, deliberately not an implicit create: the
  334. // starting document is the caller's to describe, and a counter conjured
  335. // from a typo'd id is a counter nobody ever reads. The idiom is
  336. // increment, then on 404 POST the document at a fixed id, then on 409
  337. // increment again - which is safe because that POST is the only thing
  338. // that can create it.
  339. //
  340. // Everything else keeps the database's own classification: a field
  341. // holding a non-number is InvalidArgument and so 422, integer overflow
  342. // likewise, and nothing at all was applied in either case.
  343. if (!values) throw apiErrorFor(detail, "no such document");
  344. // The new values are the entire point of the call, so 200 with a body
  345. // rather than 204: a caller that has to re-read to learn what its
  346. // increment produced has lost the atomicity it came here for.
  347. sendJson(res, 200, {{"id", id}, {"values", *values}});
  348. });
  349. svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
  350. Target t = scoped(d, req, 1, 2, KeyOp::Delete);
  351. std::string id = req.matches[3];
  352. smartbotic::database::Client::Failure failure;
  353. if (!d->db.client().remove(t.qualified, id, failure)) {
  354. // A restrict relation is the one refusal a caller can act on, so it
  355. // gets 409 plus the impact list rather than a generic failure. Only
  356. // ask for the impacts when the database says a precondition failed;
  357. // previously every failure took this path and then answered 404,
  358. // which was wrong for a transport error.
  359. if (failure.code == smartbotic::database::Client::ErrorCode::FailedPrecondition) {
  360. auto why = d->db.client().describeDelete(t.qualified, id);
  361. if (why.success && why.wouldBeBlocked)
  362. throw ApiError(ErrCode::Conflict, "relation_restricted",
  363. "delete blocked by a relation",
  364. {{"impacts", impactsJson(t.project, why)}});
  365. }
  366. throw apiErrorFor(failure, "no such document");
  367. }
  368. sendJson(res, 200, {{"deleted", id}});
  369. });
  370. }
  371. }