api_fixture.hpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. #pragma once
  2. #include "db_test_util.hpp"
  3. #include "file_store.hpp"
  4. #include "server.hpp"
  5. #include <gtest/gtest.h>
  6. #include <httplib.h>
  7. #include <chrono>
  8. #include <filesystem>
  9. #include <fstream>
  10. #include <memory>
  11. #include <thread>
  12. #include <vector>
  13. namespace svapi::testutil {
  14. class ApiFixture : public ::testing::Test {
  15. protected:
  16. std::unique_ptr<DbGateway> db_;
  17. std::unique_ptr<CollectionRegistry> registry_;
  18. std::unique_ptr<FunctionRegistry> functions_;
  19. std::unique_ptr<FunctionRunLogStore> functionRuns_;
  20. std::unique_ptr<SettingsStore> settings_;
  21. std::unique_ptr<KeyStore> keys_;
  22. std::unique_ptr<SessionStore> sessions_;
  23. std::unique_ptr<ApiServer> server_;
  24. std::thread serverThread_;
  25. int port_ = 0;
  26. std::string adminKey_;
  27. std::string project_; // a project the admin owns; tests create collections under it
  28. httplib::Server mockOpenAi_;
  29. std::thread mockThread_;
  30. int mockPort_ = 0, mockDim_ = 4;
  31. // What the last outbound embedding request actually carried, so tests can
  32. // assert on the request we send to a provider, not just on our own helpers.
  33. std::string lastEmbedUserAgent_, lastEmbedAuth_;
  34. nlohmann::json lastEmbedBody_ = nlohmann::json::object();
  35. std::string settingsColl_ = "svapitest_api_settings";
  36. std::string keysColl_ = "svapitest_api_keys";
  37. std::string webuiDir_ = "/tmp/svapi_webui_test"; // sentinel SPA root for fallback tests
  38. void SetUp() override {
  39. db_ = connectOrNull();
  40. if (!db_) GTEST_SKIP() << "smartbotic-database not reachable";
  41. project_ = tmpName("apiproj");
  42. db_->client().dropCollection(settingsColl_);
  43. db_->client().dropCollection(keysColl_);
  44. // Purge the previous run before dropping the project. Two database
  45. // caveats make this necessary, and both are invisible against a
  46. // throw-away database, which is why this only ever mattered once the
  47. // suite could run against a persistent one:
  48. // - dropProject does not delete collection data, so the collections
  49. // a previous run created still hold their documents; and
  50. // - dropCollection does not clear the collection's INDEX
  51. // declarations, so a unique index declared last run survives into
  52. // this one. A test that declares it again then gets
  53. // already_existed (success) where it expects a refusal.
  54. // Dropping each index before its collection is therefore the only way
  55. // to reach a clean slate. The project name is fixed, so without this
  56. // the suite is not idempotent.
  57. // Best-effort, and it has to be: on a database with no previous run
  58. // there is no registry collection to read and listing it throws, which
  59. // is every fresh container. Nothing here is required for correctness -
  60. // it only removes state a previous run on a PERSISTENT database left
  61. // behind - so a failure to find anything is the normal case.
  62. try {
  63. CollectionRegistry stale(*db_);
  64. for (const auto& m : stale.list(project_)) {
  65. const std::string qc = qualify(project_, m.name);
  66. for (const auto& idx : db_->client().listIndexes(qc))
  67. db_->client().dropIndex(qc, idx.field);
  68. for (const auto& fields : db_->client().listCompositeUniqueIndexes(qc))
  69. db_->client().dropCompositeUniqueIndex(qc, fields);
  70. db_->client().dropCollection(qc);
  71. }
  72. } catch (const std::exception&) {
  73. // No previous run to clean up.
  74. }
  75. // Files too. They live in the database's own file store rather than in
  76. // a collection, so dropping the project's collections does not touch
  77. // them - and against a persistent database the previous run's assets
  78. // would survive, which made a PUT of a "new" file answer 200 instead
  79. // of 201. Same lesson as the index declarations above: anything that
  80. // outlives a project has to be purged here explicitly.
  81. try {
  82. FileStore(*db_).dropAll(project_);
  83. } catch (const std::exception&) {
  84. // No previous run, or no file store to clean.
  85. }
  86. db_->dropProject(project_);
  87. db_->client().dropCollection(qualify(project_, "vectorapi_collections"));
  88. db_->ensureProject(project_);
  89. registry_ = std::make_unique<CollectionRegistry>(*db_);
  90. functions_ = std::make_unique<FunctionRegistry>(*db_);
  91. functionRuns_ = std::make_unique<FunctionRunLogStore>(*db_, 50);
  92. registry_->ensure(project_);
  93. settings_ = std::make_unique<SettingsStore>(*db_, settingsColl_, "current");
  94. settings_->bootstrap("");
  95. keys_ = std::make_unique<KeyStore>(*db_, keysColl_);
  96. keys_->bootstrap("");
  97. adminKey_ = keys_->list().at(0).key;
  98. sessions_ = std::make_unique<SessionStore>(std::chrono::minutes(60));
  99. mockOpenAi_.Post("/v1/embeddings", [this](const httplib::Request& req, httplib::Response& res) {
  100. lastEmbedUserAgent_ = req.get_header_value("User-Agent");
  101. lastEmbedAuth_ = req.get_header_value("Authorization");
  102. try { lastEmbedBody_ = nlohmann::json::parse(req.body); } catch (...) {}
  103. nlohmann::json emb = nlohmann::json::array();
  104. for (int i = 0; i < mockDim_; ++i) emb.push_back(0.1f * (i + 1));
  105. res.set_content(nlohmann::json{{"data", {{{"embedding", emb}}}}}.dump(), "application/json");
  106. });
  107. mockPort_ = mockOpenAi_.bind_to_any_port("127.0.0.1");
  108. mockThread_ = std::thread([this]{ mockOpenAi_.listen_after_bind(); });
  109. Settings s = *settings_->snapshot();
  110. s.openaiApiBase = "http://127.0.0.1:" + std::to_string(mockPort_);
  111. s.openaiApiKey = "test";
  112. settings_->save(s);
  113. std::filesystem::create_directories(webuiDir_);
  114. std::ofstream(webuiDir_ + "/index.html")
  115. << "<!doctype html><html><head><title>SVAPI_SPA_OK</title></head><body><div id=\"root\"></div></body></html>";
  116. // `runners` stays null: these tests have no function runner, and the
  117. // function routes answer 503 for that, which is itself worth asserting.
  118. ServerDeps deps{*db_, *settings_, *keys_, *registry_,
  119. *sessions_, *functions_, *functionRuns_, nullptr,
  120. webuiDir_, apiDocsDir()};
  121. server_ = std::make_unique<ApiServer>(std::move(deps));
  122. server_->registerRoutes();
  123. port_ = server_->bindToAnyPort("127.0.0.1");
  124. serverThread_ = std::thread([this]{ server_->listenAfterBind(); });
  125. httplib::Client probe("127.0.0.1", port_);
  126. for (int i = 0; i < 200; ++i) { if (probe.Get("/healthz")) break;
  127. std::this_thread::sleep_for(std::chrono::milliseconds(10)); }
  128. }
  129. void TearDown() override {
  130. if (server_) server_->stop();
  131. if (serverThread_.joinable()) serverThread_.join();
  132. mockOpenAi_.stop();
  133. if (mockThread_.joinable()) mockThread_.join();
  134. if (db_) { db_->client().dropCollection(settingsColl_);
  135. db_->client().dropCollection(keysColl_);
  136. db_->dropProject(project_); }
  137. }
  138. httplib::Client http(const std::string& bearer) {
  139. httplib::Client c("127.0.0.1", port_);
  140. c.set_default_headers({{"Authorization", "Bearer " + bearer}});
  141. return c;
  142. }
  143. httplib::Client admin() { return http(adminKey_); }
  144. httplib::Client noAuth() { return httplib::Client("127.0.0.1", port_); }
  145. static std::string apiDocsDir() { return SVAPI_API_DOCS_DIR; }
  146. // Send a single request with a specific key and extra headers (for origin/cache-control tests).
  147. // method: "GET", "POST", "PATCH", "PUT", "DELETE".
  148. // body/contentType: pass "" for requests without a body.
  149. httplib::Result request(const std::string& method, const std::string& path,
  150. const std::string& body, const std::string& contentType,
  151. const std::string& key,
  152. const httplib::Headers& extraHeaders = {}) {
  153. httplib::Headers hdrs = {{"Authorization", "Bearer " + key}};
  154. for (const auto& [k, v] : extraHeaders) hdrs.emplace(k, v);
  155. httplib::Client c("127.0.0.1", port_);
  156. c.set_default_headers(hdrs);
  157. if (method == "GET") return c.Get(path.c_str());
  158. if (method == "DELETE") return c.Delete(path.c_str());
  159. if (method == "POST") return c.Post(path.c_str(), body, contentType.c_str());
  160. if (method == "PUT") return c.Put(path.c_str(), body, contentType.c_str());
  161. if (method == "PATCH") return c.Patch(path.c_str(), body, contentType.c_str());
  162. throw std::invalid_argument("unsupported method: " + method);
  163. }
  164. };
  165. } // namespace svapi::testutil