documents.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. #include "collection_registry.hpp"
  2. #include "errors.hpp"
  3. #include "filters.hpp"
  4. #include "json_http.hpp"
  5. #include "server.hpp"
  6. #include <string>
  7. #include <vector>
  8. #include <cstdlib>
  9. #include <limits>
  10. #include <optional>
  11. namespace svapi {
  12. namespace {
  13. /// The document carried by a write request, accepting both shapes:
  14. ///
  15. /// {"data": {...}} a wrapper, unwrapped here
  16. /// {...} the document itself
  17. ///
  18. /// `id` is never a field: POST takes the document id from the body, PUT and
  19. /// PATCH from the URL, so it is removed either way.
  20. ///
  21. /// A `data` key next to any OTHER top-level key is refused. Taking body["data"]
  22. /// and discarding the siblings loses them silently, which is how a caller ends
  23. /// up missing fields with nothing in the response to say so.
  24. ///
  25. /// A document whose own top-level field is named `data` is still writable by
  26. /// nesting it once: {"data": {"data": ...}}.
  27. nlohmann::json documentBody(const nlohmann::json& body) {
  28. if (!body.is_object())
  29. throw ApiError(ErrCode::Unprocessable, "validation", "body must be a JSON object");
  30. if (body.contains("data")) {
  31. std::vector<std::string> siblings;
  32. for (auto it = body.begin(); it != body.end(); ++it)
  33. if (it.key() != "data" && it.key() != "id") siblings.push_back(it.key());
  34. if (!siblings.empty()) {
  35. std::string list;
  36. for (const auto& k : siblings) list += (list.empty() ? "" : ", ") + k;
  37. throw ApiError(ErrCode::Unprocessable, "ambiguous_body",
  38. "'data' is treated as a wrapper and must be the only top-level field, "
  39. "but found alongside: " + list +
  40. ". Send the document on its own, or nest it as {\"data\":{\"data\":...}}.");
  41. }
  42. nlohmann::json data = body["data"];
  43. if (data.is_object() && data.contains("id")) data.erase("id");
  44. return data;
  45. }
  46. nlohmann::json doc = body;
  47. if (doc.contains("id")) doc.erase("id");
  48. return doc;
  49. }
  50. // Authorize + verify the collection exists; returns the qualified collection name.
  51. std::string scoped(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) {
  52. ApiKey k = requireKey(*d, req);
  53. std::string project = req.matches[projIdx], name = req.matches[collIdx];
  54. requireCapability(*d, k, req, project, name, op);
  55. if (!d->registry.get(project, name)) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
  56. return qualify(project, name);
  57. }
  58. // Parses ?ttl_seconds=. Returns nullopt when absent - the caller must
  59. // distinguish "not supplied" (leave expiry alone) from 0 (clear the expiry).
  60. std::optional<uint32_t> ttlParam(const httplib::Request& req) {
  61. if (!req.has_param("ttl_seconds")) return std::nullopt;
  62. const std::string raw = req.get_param_value("ttl_seconds");
  63. if (raw.empty() || raw.find_first_not_of("0123456789") != std::string::npos)
  64. throw ApiError(ErrCode::Unprocessable, "validation", "ttl_seconds must be a non-negative integer");
  65. unsigned long long wide = std::strtoull(raw.c_str(), nullptr, 10);
  66. if (wide > std::numeric_limits<uint32_t>::max())
  67. throw ApiError(ErrCode::Unprocessable, "validation", "ttl_seconds must be a non-negative integer");
  68. return (uint32_t)wide;
  69. }
  70. }
  71. void registerDocumentRoutes(ApiServer& s) {
  72. auto& svr = s.raw(); ServerDeps* d = &s.deps();
  73. svr.Post(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
  74. std::string c = scoped(d, req, 1, 2, KeyOp::Insert);
  75. auto body = bodyJson(req);
  76. std::string id = body.value("id", "");
  77. nlohmann::json data = documentBody(body);
  78. const uint32_t ttl = ttlParam(req).value_or(0);
  79. std::string newId = d->db.client().insert(c, data, id, ttl);
  80. if (newId.empty()) throw ApiError(ErrCode::Unavailable, "db_error", "insert failed");
  81. sendJson(res, 201, {{"id", newId}});
  82. });
  83. svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
  84. std::string c = scoped(d, req, 1, 2, KeyOp::Read);
  85. auto doc = d->db.client().get(c, req.matches[3]);
  86. if (!doc) throw ApiError(ErrCode::NotFound, "not_found", "no such document");
  87. sendJson(res, 200, *doc);
  88. });
  89. svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
  90. std::string c = scoped(d, req, 1, 2, KeyOp::List);
  91. smartbotic::database::Client::QueryOptions opts;
  92. auto range = req.params.equal_range("filter");
  93. for (auto it = range.first; it != range.second; ++it) opts.filters.push_back(parseFilter(it->second));
  94. auto parseUInt = [](const std::string& v, const char* name) -> uint32_t {
  95. try { return (uint32_t)std::stoul(v); }
  96. catch (...) { throw ApiError(ErrCode::Unprocessable, "validation", std::string(name) + " must be a non-negative integer"); }
  97. };
  98. if (req.has_param("limit")) opts.limit = parseUInt(req.get_param_value("limit"), "limit");
  99. if (req.has_param("offset")) opts.offset = parseUInt(req.get_param_value("offset"), "offset");
  100. if (req.has_param("sort")) opts.sortField = req.get_param_value("sort");
  101. if (req.has_param("desc")) opts.sortDescending = (req.get_param_value("desc") == "true");
  102. auto docs = d->db.client().find(c, opts);
  103. sendJson(res, 200, {{"documents", docs}, {"count", docs.size()}});
  104. });
  105. svr.Patch(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
  106. std::string c = scoped(d, req, 1, 2, KeyOp::Update); std::string id = req.matches[3];
  107. if (!d->db.client().exists(c, id)) throw ApiError(ErrCode::NotFound, "not_found", "no such document");
  108. nlohmann::json patchBody = documentBody(bodyJson(req));
  109. const auto ttl = ttlParam(req);
  110. uint64_t v = ttl ? d->db.client().patchWithTtl(c, id, patchBody, *ttl)
  111. : d->db.client().patch(c, id, patchBody);
  112. if (v == 0) throw ApiError(ErrCode::Unavailable, "db_error", "patch failed");
  113. sendJson(res, 200, {{"id", id}, {"version", v}});
  114. });
  115. svr.Put(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
  116. std::string c = scoped(d, req, 1, 2, KeyOp::Update); std::string id = req.matches[3];
  117. if (!d->db.client().exists(c, id)) throw ApiError(ErrCode::NotFound, "not_found", "no such document");
  118. if (!d->db.client().update(c, id, documentBody(bodyJson(req))))
  119. throw ApiError(ErrCode::Unavailable, "db_error", "update failed");
  120. sendJson(res, 200, {{"id", id}});
  121. });
  122. svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
  123. std::string c = scoped(d, req, 1, 2, KeyOp::Delete); std::string id = req.matches[3];
  124. std::string project = req.matches[1];
  125. std::string err;
  126. if (!d->db.client().remove(c, id, err)) {
  127. // A restrict relation is the one refusal a caller can act on, so it
  128. // gets 409 plus the impact list rather than a generic failure.
  129. auto why = d->db.client().describeDelete(c, id);
  130. if (why.success && why.wouldBeBlocked)
  131. throw ApiError(ErrCode::Conflict, "relation_restricted",
  132. "delete blocked by a relation",
  133. {{"impacts", impactsJson(project, why)}});
  134. throw ApiError(ErrCode::NotFound, "not_found", "no such document");
  135. }
  136. sendJson(res, 200, {{"deleted", id}});
  137. });
  138. }
  139. }