#include "collection_registry.hpp" #include "errors.hpp" #include "json_http.hpp" #include "server.hpp" #include #include namespace svapi { namespace { // Drop a collection AND the index declarations attached to its name. // // dropCollection() removes the documents and the collection's metadata but // leaves its declared indexes behind, including unique ones. A later collection // created under the same name therefore inherits constraints nobody asked for: // a write that should succeed is refused as a duplicate, and a unique index the // new owner declares reports already_existed instead of validating their data. // Undeclaring first is the only way to make a name reusable. void dropCollectionAndIndexes(DbGateway& db, const std::string& qc) { for (const auto& idx : db.client().listIndexes(qc)) db.client().dropIndex(qc, idx.field); for (const auto& fields : db.client().listCompositeUniqueIndexes(qc)) db.client().dropCompositeUniqueIndex(qc, fields); db.client().dropCollection(qc); } } // namespace void registerCollectionRoutes(ApiServer& s) { auto& svr = s.raw(); ServerDeps* d = &s.deps(); svr.Post(R"(/api/v1/projects/([^/]+)/collections)", [d](const httplib::Request& req, httplib::Response& res) { ApiKey k = requireKey(*d, req); std::string project = req.matches[1]; requireProjectManage(k, project); d->db.ensureProject(project); d->registry.ensure(project); auto body = bodyJson(req); std::string name = body.value("name", ""), kind = body.value("kind", "json"); if (name.empty()) throw ApiError(ErrCode::Unprocessable, "validation", "name is required"); if (name.rfind('_', 0) == 0 || name.rfind("vectorapi_", 0) == 0) throw ApiError(ErrCode::Unprocessable, "validation", "name may not start with '_' or the reserved 'vectorapi_' prefix"); if (kind != "json" && kind != "vector") throw ApiError(ErrCode::Unprocessable, "validation", "kind must be 'json' or 'vector'"); uint32_t dim = 0; std::string model; if (kind == "vector") { if (!body.contains("vector_dimension")) throw ApiError(ErrCode::Unprocessable, "validation", "vector_dimension required for vector collections"); dim = body.value("vector_dimension", 0u); if (dim == 0) throw ApiError(ErrCode::Unprocessable, "validation", "vector_dimension must be > 0"); model = body.value("embedding_model", ""); } if (d->registry.get(project, name)) throw ApiError(ErrCode::Unprocessable, "exists", "collection already exists"); // Drop any stale DB-layer collection (e.g. left from a prior dropProject that didn't // fully clean up its data - DB v2.3.1 Stage F caveat), indexes included, // so the new collection starts with no inherited constraints. if (d->db.client().getCollectionInfo(qualify(project, name))) dropCollectionAndIndexes(d->db, qualify(project, name)); if (!d->db.client().createCollection(qualify(project, name), 0, false, 0, dim)) throw ApiError(ErrCode::Unavailable, "db_error", "failed to create collection"); d->registry.add(project, {name, kind, dim, model, 0}); sendJson(res, 201, {{"name", name}, {"kind", kind}, {"vector_dimension", dim}}); }); svr.Get(R"(/api/v1/projects/([^/]+)/collections)", [d](const httplib::Request& req, httplib::Response& res) { ApiKey k = requireKey(*d, req); std::string project = req.matches[1]; requireProjectManage(k, project); auto lower = [](std::string s) { std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return (char)std::tolower(c); }); return s; }; const std::string q = lower(req.has_param("q") ? req.get_param_value("q") : ""); const std::string sort = req.has_param("sort") ? req.get_param_value("sort") : "name"; const bool desc = req.has_param("desc") && req.get_param_value("desc") == "true"; // Build the enriched list (metadata + live stats), filtering by name server-side. std::vector items; for (const auto& m : d->registry.list(project)) { if (!q.empty() && lower(m.name).find(q) == std::string::npos) continue; nlohmann::json e = m.toJson(); const std::string qc = qualify(project, m.name); // count() is the authoritative document count; getCollectionInfo()'s // documentCount can read back as 0 on some backends. e["document_count"] = d->db.client().count(qc); if (auto info = d->db.client().getCollectionInfo(qc)) e["size_bytes"] = info->sizeBytes; items.push_back(std::move(e)); } // Sort server-side. Unknown sort fields fall back to name; ties break by name. auto num = [](const nlohmann::json& e, const char* key) -> uint64_t { auto it = e.find(key); return (it != e.end() && it->is_number()) ? it->get() : 0; }; auto str = [](const nlohmann::json& e, const char* key) -> std::string { auto it = e.find(key); return (it != e.end() && it->is_string()) ? it->get() : std::string(); }; auto numCmp = [](uint64_t a, uint64_t b) { return a < b ? -1 : (a > b ? 1 : 0); }; std::sort(items.begin(), items.end(), [&](const nlohmann::json& a, const nlohmann::json& b) { int cmp; if (sort == "documents") cmp = numCmp(num(a, "document_count"), num(b, "document_count")); else if (sort == "size") cmp = numCmp(num(a, "size_bytes"), num(b, "size_bytes")); else if (sort == "created_at") cmp = numCmp(num(a, "created_at"), num(b, "created_at")); else if (sort == "kind") cmp = str(a, "kind").compare(str(b, "kind")); else cmp = str(a, "name").compare(str(b, "name")); if (cmp == 0) cmp = str(a, "name").compare(str(b, "name")); return desc ? cmp > 0 : cmp < 0; }); nlohmann::json out = nlohmann::json::array(); for (auto& e : items) out.push_back(std::move(e)); sendJson(res, 200, {{"collections", out}}); }); svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) { ApiKey k = requireKey(*d, req); std::string project = req.matches[1], name = req.matches[2]; requireProjectManage(k, project); auto m = d->registry.get(project, name); if (!m) throw ApiError(ErrCode::NotFound, "not_found", "no such collection"); nlohmann::json e = m->toJson(); const std::string qc = qualify(project, name); e["document_count"] = d->db.client().count(qc); if (auto info = d->db.client().getCollectionInfo(qc)) e["size_bytes"] = info->sizeBytes; // tryGetRelationsEnforced (client 2.11.4) declines to answer rather than // defaulting when the read fails, which is what a UI showing the setting // needs: omitted means "could not be determined", never "disabled". if (auto enforced = d->db.client().tryGetRelationsEnforced(qc)) e["relations_enforced"] = *enforced; sendJson(res, 200, e); }); svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) { ApiKey k = requireKey(*d, req); std::string project = req.matches[1], name = req.matches[2]; requireProjectManage(k, project); if (!d->registry.get(project, name)) throw ApiError(ErrCode::NotFound, "not_found", "no such collection"); const std::string qc = qualify(project, name); // dropCollection() clears the collection's metadata but does NOT purge the // underlying (vector) index - orphan rows survive and leak into a later // same-name collection (search returns them even though document_count is 0). // remove() per id DOES purge the index, so delete every document first, then // drop the now-empty collection. (See docs/bugs/2026-06-02-collection-delete-leaks-vectors.md) smartbotic::database::Client::QueryOptions opts; opts.limit = 1000000; auto docs = d->db.client().find(qc, opts); for (const auto& doc : docs) { std::string id = doc.value("_id", std::string()); if (id.empty()) id = doc.value("id", std::string()); if (!id.empty()) d->db.client().remove(qc, id); } dropCollectionAndIndexes(d->db, qc); d->registry.remove(project, name); sendJson(res, 200, {{"deleted", name}}); }); } }