main.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. #include "auth.hpp"
  2. #include "collection_registry.hpp"
  3. #include "db_await.hpp"
  4. #include "config.hpp"
  5. #include "access_log.hpp"
  6. #include "function_events.hpp"
  7. #include "function_jobs.hpp"
  8. #include "function_scheduler.hpp"
  9. #include "project_secret_store.hpp"
  10. #include <memory>
  11. #include "db_gateway.hpp"
  12. #include "key_store.hpp"
  13. #include "server.hpp"
  14. #include "settings_store.hpp"
  15. #include <svapi/version.hpp>
  16. #include <spdlog/spdlog.h>
  17. #ifdef HAVE_SYSTEMD
  18. #include <systemd/sd-daemon.h>
  19. #else
  20. #define sd_notify(u, s) do {} while (0)
  21. #endif
  22. #include <atomic>
  23. #include <chrono>
  24. #include <csignal>
  25. #include <cstdlib>
  26. #include <cstring>
  27. #include <iostream>
  28. #include <thread>
  29. namespace {
  30. std::atomic<bool> g_running{true};
  31. void onSignal(int) { g_running = false; }
  32. std::string envOr(const char* k, const std::string& dflt = "") { const char* v = std::getenv(k); return v ? std::string(v) : dflt; }
  33. }
  34. int main(int argc, char** argv) {
  35. std::string configPath = "/etc/smartbotic-vectorapi/config.json";
  36. std::string webuiDirOverride;
  37. std::string shareDir = "/usr/share/smartbotic-vectorapi";
  38. for (int i = 1; i < argc; ++i) {
  39. if (std::strcmp(argv[i], "--config") == 0 && i + 1 < argc) configPath = argv[++i];
  40. else if (std::strcmp(argv[i], "--webui-dir") == 0 && i + 1 < argc) webuiDirOverride = argv[++i];
  41. else if (std::strcmp(argv[i], "--share-dir") == 0 && i + 1 < argc) shareDir = argv[++i];
  42. else if (std::strcmp(argv[i], "--version") == 0 || std::strcmp(argv[i], "-v") == 0) {
  43. std::cout << "smartbotic-vectorapi " << svapi::VERSION << " (" << svapi::GIT_COMMIT << ")\n";
  44. return 0;
  45. }
  46. }
  47. svapi::Config cfg;
  48. try { cfg = svapi::Config::load(configPath); }
  49. catch (const std::exception& e) { std::cerr << "config error: " << e.what() << "\n"; return 1; }
  50. spdlog::set_level(spdlog::level::from_str(cfg.logLevel));
  51. if (!webuiDirOverride.empty()) cfg.webuiDir = webuiDirOverride;
  52. // REFUSE TO START rather than run with a logging control that silently does
  53. // nothing. An operator who configured an access log did so to watch
  54. // something - most likely to point a ban tool at it - and a service that
  55. // came up healthy while writing no lines would make that monitor read as
  56. // "no abuse" forever. This repo already records what that costs: a control
  57. // nobody has seen fire is not a control.
  58. if (!svapi::accessLog().open(cfg.accessLogPath)) {
  59. std::cerr << "config error: access_log.path '" << cfg.accessLogPath
  60. << "' could not be opened for append\n";
  61. return 1;
  62. }
  63. if (svapi::accessLog().enabled())
  64. spdlog::info("access log: {}", svapi::accessLog().path());
  65. std::signal(SIGINT, onSignal); std::signal(SIGTERM, onSignal); std::signal(SIGPIPE, SIG_IGN);
  66. svapi::DbGateway db(cfg.dbAddress, cfg.dbTimeoutMs);
  67. spdlog::info("connecting to smartbotic-database at {}", cfg.dbAddress);
  68. // Bounded by WALL TIME, not by an attempt count - see db_await.hpp. 60 s
  69. // sits comfortably inside systemd's 90 s TimeoutStartSec, so an unreachable
  70. // database produces a clean diagnostic and exit 1 rather than being killed
  71. // mid-loop with a misleading "start operation timed out".
  72. svapi::awaitConnectable([&db] { return db.connect(); },
  73. [] { return std::chrono::steady_clock::now(); },
  74. [](std::chrono::milliseconds d) { std::this_thread::sleep_for(d); },
  75. std::chrono::seconds(60), std::chrono::seconds(1));
  76. if (!db.healthy()) { spdlog::error("database not reachable at {}", cfg.dbAddress); return 1; }
  77. svapi::SettingsStore settings(db);
  78. settings.bootstrap(envOr("OPENAI_API_KEY"));
  79. settings.startWatch();
  80. svapi::KeyStore keys(db);
  81. keys.bootstrap(envOr("SMARTBOTIC_VECTORAPI_KEY"));
  82. keys.startWatch();
  83. svapi::CollectionRegistry registry(db);
  84. const std::string defProj = settings.snapshot()->defaultProject;
  85. db.ensureProject(defProj);
  86. // Re-open EVERY project's collection registry at startup. The DB only
  87. // surfaces a collection via find()/list() once it has been opened in the
  88. // current process, so without this a restart makes all collections vanish
  89. // from the API (GET /collections empty, document ops 404) even though the
  90. // data survives on disk. KeyStore::bootstrap already does this for
  91. // vectorapi_keys, which is why keys survive but the registry didn't. (issue #1)
  92. const std::vector<std::string> projects = db.listProjects(); // includes the default
  93. registry.bootstrap(projects);
  94. spdlog::info("opened collection registry for {} project(s) at startup", projects.size());
  95. svapi::FunctionRegistry functions(db);
  96. svapi::FunctionRunLogStore functionRuns(db, cfg.functionRunsKept);
  97. // STATE THE EFFECTIVE VALUE, AND NAME THE OTHER ONE. Two settings trim this
  98. // one log: this (`functions.runs_kept`, for HTTP-triggered runs) and the
  99. // RUNNER's `function_runs_kept` in runner.json, for cron and job runs.
  100. // Neither process can see the other's config, so a divergence is invisible
  101. // - and on 2026-10-22 it cost a wrong answer to a consumer: this value was
  102. // raised to 500 and verified through the API, while their cron functions
  103. // went on being trimmed at 50 by the runner for twenty more minutes. A true
  104. // reading of the wrong component. Logging both makes the mismatch one grep
  105. // rather than a measurement.
  106. spdlog::info("function run log keeps {} run(s) per function here (functions.runs_kept, for "
  107. "HTTP runs); CRON AND JOB runs are trimmed by the runner's own "
  108. "function_runs_kept in runner.json - if the two differ, one log is trimmed to "
  109. "two depths", cfg.functionRunsKept);
  110. // Same reason CollectionRegistry::bootstrap exists: the database only
  111. // surfaces a collection through find() once it has been opened in this
  112. // process, so without this every project's function registry reads back
  113. // empty after a restart even though the rows are on disk.
  114. for (const std::string& project : projects) {
  115. functions.ensure(project);
  116. functionRuns.ensure(project);
  117. }
  118. // Null when no runners are configured, which the function routes report as
  119. // 503 rather than as a missing feature.
  120. std::unique_ptr<svapi::RunnerPool> runners;
  121. if (!cfg.runnerEndpoints.empty()) {
  122. svapi::RunnerPool::Options ro;
  123. ro.endpoints = cfg.runnerEndpoints;
  124. // Environment over config file: the token is a secret, and
  125. // vectorapi.env can be mode 0640 where config.json is a conffile.
  126. ro.authToken = cfg.runnerToken;
  127. if (const std::string fromEnv = envOr("SVAPI_RUNNER_TOKEN"); !fromEnv.empty())
  128. ro.authToken = fromEnv;
  129. if (ro.authToken.empty())
  130. spdlog::warn("no runner token configured - only a loopback runner will accept us");
  131. runners = std::make_unique<svapi::RunnerPool>(ro);
  132. spdlog::info("function runners configured: {}", cfg.runnerEndpoints.size());
  133. } else {
  134. spdlog::info("no function runners configured - function routes will answer 503");
  135. }
  136. // The queue has to exist and be re-opened before the watcher subscribes or
  137. // the scheduler ticks, or their first pass finds nothing and quietly does
  138. // nothing for a whole refresh interval.
  139. svapi::FunctionJobQueue jobQueue(db);
  140. jobQueue.ensure();
  141. // Secrets are per project and created on demand; ensuring them here only
  142. // re-opens what already exists so the runner's reads see it after a restart.
  143. svapi::ProjectSecretStore secrets(db);
  144. for (const std::string& project : projects) secrets.ensure(project);
  145. // Started only with runners configured: a queue nobody drains is worse than
  146. // no queue, because the jobs look like work in progress forever.
  147. std::unique_ptr<svapi::FunctionScheduler> scheduler;
  148. std::unique_ptr<svapi::FunctionEventWatcher> events;
  149. svapi::SessionStore sessions(std::chrono::minutes(settings.snapshot()->sessionTtlMinutes));
  150. svapi::ServerDeps deps{db, settings, keys, registry,
  151. sessions, functions, functionRuns, runners.get(),
  152. cfg.webuiDir, shareDir, &jobQueue};
  153. svapi::ApiServer server(std::move(deps));
  154. if (runners && cfg.schedulerEnabled) {
  155. svapi::FunctionSchedulerOptions so;
  156. so.tickIntervalSec = cfg.schedulerTickSec;
  157. so.reclaimIntervalSec = cfg.reclaimIntervalSec;
  158. so.claimTimeoutSec = cfg.claimTimeoutSec;
  159. so.maxAttempts = cfg.jobMaxAttempts;
  160. scheduler = std::make_unique<svapi::FunctionScheduler>(db, functions, jobQueue, so);
  161. scheduler->start();
  162. spdlog::info("cron scheduler started (tick {}s, reclaim {}s)", so.tickIntervalSec,
  163. so.reclaimIntervalSec);
  164. }
  165. if (runners && cfg.eventsEnabled) {
  166. svapi::FunctionEventWatcherOptions eo;
  167. eo.maxDepth = cfg.eventsMaxDepth;
  168. eo.refreshIntervalSec = cfg.eventsRefreshSec;
  169. eo.maxPendingEvents = cfg.eventsMaxPending;
  170. events = std::make_unique<svapi::FunctionEventWatcher>(db, functions, jobQueue, eo);
  171. events->start();
  172. spdlog::info("database event watcher started (max trigger depth {})", eo.maxDepth);
  173. }
  174. server.registerRoutes();
  175. // Before listen, or cpp-httplib has already built its queue and this is
  176. // silently ignored. Logged either way so the journal says which pool is in
  177. // force; "default" rather than a number, because the number belongs to
  178. // httplib and guessing it here is how a doc goes stale.
  179. server.setThreadPoolSize(cfg.httpThreadPoolSize);
  180. if (cfg.httpThreadPoolSize > 0)
  181. spdlog::info("http request threads: {}", cfg.httpThreadPoolSize);
  182. else
  183. spdlog::info("http request threads: cpp-httplib default (max(8, nproc-1)); "
  184. "set http.thread_pool_size to override");
  185. std::thread http([&] {
  186. spdlog::info("listening on {}:{}", cfg.httpBind, cfg.httpPort);
  187. if (!server.listen(cfg.httpBind, cfg.httpPort)) { spdlog::error("bind failed"); g_running = false; }
  188. });
  189. sd_notify(0, "READY=1");
  190. while (g_running) { sd_notify(0, "WATCHDOG=1"); std::this_thread::sleep_for(std::chrono::milliseconds(200)); }
  191. sd_notify(0, "STOPPING=1");
  192. // Background threads first, while the database is still reachable: the
  193. // scheduler and the watcher both write to the queue, and a thread still
  194. // running when the gateway is destroyed is a use-after-free. Both join.
  195. if (events) events->stop();
  196. if (scheduler) scheduler->stop();
  197. server.stop();
  198. if (http.joinable()) http.join();
  199. return 0;
  200. }