api_fixture.hpp 8.1 KB

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