#include "collection_registry.hpp" #include "errors.hpp" #include "filters.hpp" #include "json_http.hpp" #include "server.hpp" #include #include #include #include #include namespace svapi { namespace { /// The document carried by a write request, accepting both shapes: /// /// {"data": {...}} a wrapper, unwrapped here /// {...} the document itself /// /// `id` is never a field: POST takes the document id from the body, PUT and /// PATCH from the URL, so it is removed either way. /// /// A `data` key next to any OTHER top-level key is refused. Taking body["data"] /// and discarding the siblings loses them silently, which is how a caller ends /// up missing fields with nothing in the response to say so. /// /// A document whose own top-level field is named `data` is still writable by /// nesting it once: {"data": {"data": ...}}. nlohmann::json documentBody(const nlohmann::json& body) { if (!body.is_object()) throw ApiError(ErrCode::Unprocessable, "validation", "body must be a JSON object"); if (body.contains("data")) { std::vector siblings; for (auto it = body.begin(); it != body.end(); ++it) if (it.key() != "data" && it.key() != "id") siblings.push_back(it.key()); if (!siblings.empty()) { std::string list; for (const auto& k : siblings) list += (list.empty() ? "" : ", ") + k; throw ApiError(ErrCode::Unprocessable, "ambiguous_body", "'data' is treated as a wrapper and must be the only top-level field, " "but found alongside: " + list + ". Send the document on its own, or nest it as {\"data\":{\"data\":...}}."); } nlohmann::json data = body["data"]; if (data.is_object() && data.contains("id")) data.erase("id"); return data; } nlohmann::json doc = body; if (doc.contains("id")) doc.erase("id"); return doc; } // Authorize + verify the collection exists; returns the qualified collection name. std::string scoped(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) { ApiKey k = requireKey(*d, req); std::string project = req.matches[projIdx], name = req.matches[collIdx]; requireCapability(*d, k, req, project, name, op); if (!d->registry.get(project, name)) throw ApiError(ErrCode::NotFound, "not_found", "no such collection"); return qualify(project, name); } // Parses ?ttl_seconds=. Returns nullopt when absent - the caller must // distinguish "not supplied" (leave expiry alone) from 0 (clear the expiry). std::optional 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::max()) throw ApiError(ErrCode::Unprocessable, "validation", "ttl_seconds must be a non-negative integer"); return (uint32_t)wide; } } 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) { std::string c = scoped(d, req, 1, 2, KeyOp::Insert); auto body = bodyJson(req); std::string id = body.value("id", ""); nlohmann::json data = documentBody(body); const uint32_t ttl = ttlParam(req).value_or(0); std::string newId = d->db.client().insert(c, data, id, ttl); 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) { std::string c = scoped(d, req, 1, 2, KeyOp::Read); auto doc = d->db.client().get(c, req.matches[3]); if (!doc) throw ApiError(ErrCode::NotFound, "not_found", "no such document"); sendJson(res, 200, *doc); }); svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) { std::string c = scoped(d, req, 1, 2, KeyOp::List); smartbotic::database::Client::QueryOptions opts; auto range = req.params.equal_range("filter"); for (auto it = range.first; it != range.second; ++it) opts.filters.push_back(parseFilter(it->second)); auto parseUInt = [](const std::string& v, const char* name) -> uint32_t { try { return (uint32_t)std::stoul(v); } catch (...) { throw ApiError(ErrCode::Unprocessable, "validation", std::string(name) + " must be a non-negative integer"); } }; if (req.has_param("limit")) opts.limit = parseUInt(req.get_param_value("limit"), "limit"); if (req.has_param("offset")) opts.offset = parseUInt(req.get_param_value("offset"), "offset"); if (req.has_param("sort")) opts.sortField = req.get_param_value("sort"); if (req.has_param("desc")) opts.sortDescending = (req.get_param_value("desc") == "true"); auto docs = d->db.client().find(c, opts); sendJson(res, 200, {{"documents", docs}, {"count", docs.size()}}); }); svr.Patch(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) { std::string c = scoped(d, req, 1, 2, KeyOp::Update); std::string id = req.matches[3]; if (!d->db.client().exists(c, id)) throw ApiError(ErrCode::NotFound, "not_found", "no such document"); nlohmann::json patchBody = documentBody(bodyJson(req)); const auto ttl = ttlParam(req); uint64_t v = ttl ? d->db.client().patchWithTtl(c, id, patchBody, *ttl) : d->db.client().patch(c, id, patchBody); if (v == 0) throw ApiError(ErrCode::Unavailable, "db_error", "patch failed"); sendJson(res, 200, {{"id", id}, {"version", v}}); }); svr.Put(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) { std::string c = scoped(d, req, 1, 2, KeyOp::Update); std::string id = req.matches[3]; if (!d->db.client().exists(c, id)) throw ApiError(ErrCode::NotFound, "not_found", "no such document"); if (!d->db.client().update(c, id, documentBody(bodyJson(req)))) throw ApiError(ErrCode::Unavailable, "db_error", "update failed"); sendJson(res, 200, {{"id", id}}); }); svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) { std::string c = scoped(d, req, 1, 2, KeyOp::Delete); std::string id = req.matches[3]; std::string project = req.matches[1]; std::string err; if (!d->db.client().remove(c, id, err)) { // 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. auto why = d->db.client().describeDelete(c, id); if (why.success && why.wouldBeBlocked) throw ApiError(ErrCode::Conflict, "relation_restricted", "delete blocked by a relation", {{"impacts", impactsJson(project, why)}}); throw ApiError(ErrCode::NotFound, "not_found", "no such document"); } sendJson(res, 200, {{"deleted", id}}); }); } }