collections.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. #include "collection_registry.hpp"
  2. #include "errors.hpp"
  3. #include "json_http.hpp"
  4. #include "server.hpp"
  5. #include <algorithm>
  6. #include <cctype>
  7. namespace svapi {
  8. namespace {
  9. // Drop a collection AND the index declarations attached to its name.
  10. //
  11. // dropCollection() removes the documents and the collection's metadata but
  12. // leaves its declared indexes behind, including unique ones. A later collection
  13. // created under the same name therefore inherits constraints nobody asked for:
  14. // a write that should succeed is refused as a duplicate, and a unique index the
  15. // new owner declares reports already_existed instead of validating their data.
  16. // Undeclaring first is the only way to make a name reusable.
  17. void dropCollectionAndIndexes(DbGateway& db, const std::string& qc) {
  18. for (const auto& idx : db.client().listIndexes(qc))
  19. db.client().dropIndex(qc, idx.field);
  20. for (const auto& fields : db.client().listCompositeUniqueIndexes(qc))
  21. db.client().dropCompositeUniqueIndex(qc, fields);
  22. db.client().dropCollection(qc);
  23. }
  24. } // namespace
  25. void registerCollectionRoutes(ApiServer& s) {
  26. auto& svr = s.raw(); ServerDeps* d = &s.deps();
  27. svr.Post(R"(/api/v1/projects/([^/]+)/collections)", [d](const httplib::Request& req, httplib::Response& res) {
  28. ApiKey k = requireKey(*d, req); std::string project = req.matches[1];
  29. requireProjectManage(k, project);
  30. d->db.ensureProject(project); d->registry.ensure(project);
  31. auto body = bodyJson(req);
  32. std::string name = body.value("name", ""), kind = body.value("kind", "json");
  33. if (name.empty()) throw ApiError(ErrCode::Unprocessable, "validation", "name is required");
  34. if (name.rfind('_', 0) == 0 || name.rfind("vectorapi_", 0) == 0)
  35. throw ApiError(ErrCode::Unprocessable, "validation", "name may not start with '_' or the reserved 'vectorapi_' prefix");
  36. if (kind != "json" && kind != "vector") throw ApiError(ErrCode::Unprocessable, "validation", "kind must be 'json' or 'vector'");
  37. uint32_t dim = 0; std::string model;
  38. if (kind == "vector") {
  39. if (!body.contains("vector_dimension")) throw ApiError(ErrCode::Unprocessable, "validation", "vector_dimension required for vector collections");
  40. dim = body.value("vector_dimension", 0u);
  41. if (dim == 0) throw ApiError(ErrCode::Unprocessable, "validation", "vector_dimension must be > 0");
  42. model = body.value("embedding_model", "");
  43. }
  44. if (d->registry.get(project, name)) throw ApiError(ErrCode::Unprocessable, "exists", "collection already exists");
  45. // Drop any stale DB-layer collection (e.g. left from a prior dropProject that didn't
  46. // fully clean up its data - DB v2.3.1 Stage F caveat), indexes included,
  47. // so the new collection starts with no inherited constraints.
  48. if (d->db.client().getCollectionInfo(qualify(project, name)))
  49. dropCollectionAndIndexes(d->db, qualify(project, name));
  50. if (!d->db.client().createCollection(qualify(project, name), 0, false, 0, dim))
  51. throw ApiError(ErrCode::Unavailable, "db_error", "failed to create collection");
  52. d->registry.add(project, {name, kind, dim, model, 0});
  53. sendJson(res, 201, {{"name", name}, {"kind", kind}, {"vector_dimension", dim}});
  54. });
  55. svr.Get(R"(/api/v1/projects/([^/]+)/collections)", [d](const httplib::Request& req, httplib::Response& res) {
  56. ApiKey k = requireKey(*d, req); std::string project = req.matches[1];
  57. requireProjectManage(k, project);
  58. auto lower = [](std::string s) {
  59. std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return (char)std::tolower(c); });
  60. return s;
  61. };
  62. const std::string q = lower(req.has_param("q") ? req.get_param_value("q") : "");
  63. const std::string sort = req.has_param("sort") ? req.get_param_value("sort") : "name";
  64. const bool desc = req.has_param("desc") && req.get_param_value("desc") == "true";
  65. // Build the enriched list (metadata + live stats), filtering by name server-side.
  66. std::vector<nlohmann::json> items;
  67. for (const auto& m : d->registry.list(project)) {
  68. if (!q.empty() && lower(m.name).find(q) == std::string::npos) continue;
  69. nlohmann::json e = m.toJson();
  70. const std::string qc = qualify(project, m.name);
  71. // count() is the authoritative document count; getCollectionInfo()'s
  72. // documentCount can read back as 0 on some backends.
  73. e["document_count"] = d->db.client().count(qc);
  74. if (auto info = d->db.client().getCollectionInfo(qc)) e["size_bytes"] = info->sizeBytes;
  75. items.push_back(std::move(e));
  76. }
  77. // Sort server-side. Unknown sort fields fall back to name; ties break by name.
  78. auto num = [](const nlohmann::json& e, const char* key) -> uint64_t {
  79. auto it = e.find(key);
  80. return (it != e.end() && it->is_number()) ? it->get<uint64_t>() : 0;
  81. };
  82. auto str = [](const nlohmann::json& e, const char* key) -> std::string {
  83. auto it = e.find(key);
  84. return (it != e.end() && it->is_string()) ? it->get<std::string>() : std::string();
  85. };
  86. auto numCmp = [](uint64_t a, uint64_t b) { return a < b ? -1 : (a > b ? 1 : 0); };
  87. std::sort(items.begin(), items.end(), [&](const nlohmann::json& a, const nlohmann::json& b) {
  88. int cmp;
  89. if (sort == "documents") cmp = numCmp(num(a, "document_count"), num(b, "document_count"));
  90. else if (sort == "size") cmp = numCmp(num(a, "size_bytes"), num(b, "size_bytes"));
  91. else if (sort == "created_at") cmp = numCmp(num(a, "created_at"), num(b, "created_at"));
  92. else if (sort == "kind") cmp = str(a, "kind").compare(str(b, "kind"));
  93. else cmp = str(a, "name").compare(str(b, "name"));
  94. if (cmp == 0) cmp = str(a, "name").compare(str(b, "name"));
  95. return desc ? cmp > 0 : cmp < 0;
  96. });
  97. nlohmann::json out = nlohmann::json::array();
  98. for (auto& e : items) out.push_back(std::move(e));
  99. sendJson(res, 200, {{"collections", out}});
  100. });
  101. svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
  102. ApiKey k = requireKey(*d, req); std::string project = req.matches[1], name = req.matches[2];
  103. requireProjectManage(k, project);
  104. auto m = d->registry.get(project, name);
  105. if (!m) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
  106. nlohmann::json e = m->toJson();
  107. const std::string qc = qualify(project, name);
  108. e["document_count"] = d->db.client().count(qc);
  109. if (auto info = d->db.client().getCollectionInfo(qc)) e["size_bytes"] = info->sizeBytes;
  110. // tryGetRelationsEnforced (client 2.11.4) declines to answer rather than
  111. // defaulting when the read fails, which is what a UI showing the setting
  112. // needs: omitted means "could not be determined", never "disabled".
  113. if (auto enforced = d->db.client().tryGetRelationsEnforced(qc))
  114. e["relations_enforced"] = *enforced;
  115. sendJson(res, 200, e);
  116. });
  117. svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
  118. ApiKey k = requireKey(*d, req); std::string project = req.matches[1], name = req.matches[2];
  119. requireProjectManage(k, project);
  120. if (!d->registry.get(project, name)) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
  121. const std::string qc = qualify(project, name);
  122. // dropCollection() clears the collection's metadata but does NOT purge the
  123. // underlying (vector) index - orphan rows survive and leak into a later
  124. // same-name collection (search returns them even though document_count is 0).
  125. // remove() per id DOES purge the index, so delete every document first, then
  126. // drop the now-empty collection. (See docs/bugs/2026-06-02-collection-delete-leaks-vectors.md)
  127. smartbotic::database::Client::QueryOptions opts; opts.limit = 1000000;
  128. auto docs = d->db.client().find(qc, opts);
  129. for (const auto& doc : docs) {
  130. std::string id = doc.value("_id", std::string());
  131. if (id.empty()) id = doc.value("id", std::string());
  132. if (!id.empty()) d->db.client().remove(qc, id);
  133. }
  134. dropCollectionAndIndexes(d->db, qc);
  135. d->registry.remove(project, name);
  136. sendJson(res, 200, {{"deleted", name}});
  137. });
  138. }
  139. }