#include "auth.hpp" #include "collection_registry.hpp" #include "db_await.hpp" #include "config.hpp" #include "access_log.hpp" #include "function_events.hpp" #include "function_jobs.hpp" #include "function_scheduler.hpp" #include "project_secret_store.hpp" #include #include "db_gateway.hpp" #include "key_store.hpp" #include "server.hpp" #include "settings_store.hpp" #include #include #ifdef HAVE_SYSTEMD #include #else #define sd_notify(u, s) do {} while (0) #endif #include #include #include #include #include #include #include namespace { std::atomic g_running{true}; void onSignal(int) { g_running = false; } std::string envOr(const char* k, const std::string& dflt = "") { const char* v = std::getenv(k); return v ? std::string(v) : dflt; } } int main(int argc, char** argv) { std::string configPath = "/etc/smartbotic-vectorapi/config.json"; std::string webuiDirOverride; std::string shareDir = "/usr/share/smartbotic-vectorapi"; for (int i = 1; i < argc; ++i) { if (std::strcmp(argv[i], "--config") == 0 && i + 1 < argc) configPath = argv[++i]; else if (std::strcmp(argv[i], "--webui-dir") == 0 && i + 1 < argc) webuiDirOverride = argv[++i]; else if (std::strcmp(argv[i], "--share-dir") == 0 && i + 1 < argc) shareDir = argv[++i]; else if (std::strcmp(argv[i], "--version") == 0 || std::strcmp(argv[i], "-v") == 0) { std::cout << "smartbotic-vectorapi " << svapi::VERSION << " (" << svapi::GIT_COMMIT << ")\n"; return 0; } } svapi::Config cfg; try { cfg = svapi::Config::load(configPath); } catch (const std::exception& e) { std::cerr << "config error: " << e.what() << "\n"; return 1; } spdlog::set_level(spdlog::level::from_str(cfg.logLevel)); if (!webuiDirOverride.empty()) cfg.webuiDir = webuiDirOverride; // REFUSE TO START rather than run with a logging control that silently does // nothing. An operator who configured an access log did so to watch // something - most likely to point a ban tool at it - and a service that // came up healthy while writing no lines would make that monitor read as // "no abuse" forever. This repo already records what that costs: a control // nobody has seen fire is not a control. if (!svapi::accessLog().open(cfg.accessLogPath)) { std::cerr << "config error: access_log.path '" << cfg.accessLogPath << "' could not be opened for append\n"; return 1; } if (svapi::accessLog().enabled()) spdlog::info("access log: {}", svapi::accessLog().path()); std::signal(SIGINT, onSignal); std::signal(SIGTERM, onSignal); std::signal(SIGPIPE, SIG_IGN); svapi::DbGateway db(cfg.dbAddress, cfg.dbTimeoutMs); spdlog::info("connecting to smartbotic-database at {}", cfg.dbAddress); // Bounded by WALL TIME, not by an attempt count - see db_await.hpp. 60 s // sits comfortably inside systemd's 90 s TimeoutStartSec, so an unreachable // database produces a clean diagnostic and exit 1 rather than being killed // mid-loop with a misleading "start operation timed out". svapi::awaitConnectable([&db] { return db.connect(); }, [] { return std::chrono::steady_clock::now(); }, [](std::chrono::milliseconds d) { std::this_thread::sleep_for(d); }, std::chrono::seconds(60), std::chrono::seconds(1)); if (!db.healthy()) { spdlog::error("database not reachable at {}", cfg.dbAddress); return 1; } svapi::SettingsStore settings(db); settings.bootstrap(envOr("OPENAI_API_KEY")); settings.startWatch(); svapi::KeyStore keys(db); keys.bootstrap(envOr("SMARTBOTIC_VECTORAPI_KEY")); keys.startWatch(); svapi::CollectionRegistry registry(db); const std::string defProj = settings.snapshot()->defaultProject; db.ensureProject(defProj); // Re-open EVERY project's collection registry at startup. The DB only // surfaces a collection via find()/list() once it has been opened in the // current process, so without this a restart makes all collections vanish // from the API (GET /collections empty, document ops 404) even though the // data survives on disk. KeyStore::bootstrap already does this for // vectorapi_keys, which is why keys survive but the registry didn't. (issue #1) const std::vector projects = db.listProjects(); // includes the default registry.bootstrap(projects); spdlog::info("opened collection registry for {} project(s) at startup", projects.size()); svapi::FunctionRegistry functions(db); svapi::FunctionRunLogStore functionRuns(db, cfg.functionRunsKept); // STATE THE EFFECTIVE VALUE, AND NAME THE OTHER ONE. Two settings trim this // one log: this (`functions.runs_kept`, for HTTP-triggered runs) and the // RUNNER's `function_runs_kept` in runner.json, for cron and job runs. // Neither process can see the other's config, so a divergence is invisible // - and on 2026-10-22 it cost a wrong answer to a consumer: this value was // raised to 500 and verified through the API, while their cron functions // went on being trimmed at 50 by the runner for twenty more minutes. A true // reading of the wrong component. Logging both makes the mismatch one grep // rather than a measurement. spdlog::info("function run log keeps {} run(s) per function here (functions.runs_kept, for " "HTTP runs); CRON AND JOB runs are trimmed by the runner's own " "function_runs_kept in runner.json - if the two differ, one log is trimmed to " "two depths", cfg.functionRunsKept); // Same reason CollectionRegistry::bootstrap exists: the database only // surfaces a collection through find() once it has been opened in this // process, so without this every project's function registry reads back // empty after a restart even though the rows are on disk. for (const std::string& project : projects) { functions.ensure(project); functionRuns.ensure(project); } // Null when no runners are configured, which the function routes report as // 503 rather than as a missing feature. std::unique_ptr runners; if (!cfg.runnerEndpoints.empty()) { svapi::RunnerPool::Options ro; ro.endpoints = cfg.runnerEndpoints; // Environment over config file: the token is a secret, and // vectorapi.env can be mode 0640 where config.json is a conffile. ro.authToken = cfg.runnerToken; if (const std::string fromEnv = envOr("SVAPI_RUNNER_TOKEN"); !fromEnv.empty()) ro.authToken = fromEnv; if (ro.authToken.empty()) spdlog::warn("no runner token configured - only a loopback runner will accept us"); runners = std::make_unique(ro); spdlog::info("function runners configured: {}", cfg.runnerEndpoints.size()); } else { spdlog::info("no function runners configured - function routes will answer 503"); } // The queue has to exist and be re-opened before the watcher subscribes or // the scheduler ticks, or their first pass finds nothing and quietly does // nothing for a whole refresh interval. svapi::FunctionJobQueue jobQueue(db); jobQueue.ensure(); // Secrets are per project and created on demand; ensuring them here only // re-opens what already exists so the runner's reads see it after a restart. svapi::ProjectSecretStore secrets(db); for (const std::string& project : projects) secrets.ensure(project); // Started only with runners configured: a queue nobody drains is worse than // no queue, because the jobs look like work in progress forever. std::unique_ptr scheduler; std::unique_ptr events; svapi::SessionStore sessions(std::chrono::minutes(settings.snapshot()->sessionTtlMinutes)); svapi::ServerDeps deps{db, settings, keys, registry, sessions, functions, functionRuns, runners.get(), cfg.webuiDir, shareDir, &jobQueue}; svapi::ApiServer server(std::move(deps)); if (runners && cfg.schedulerEnabled) { svapi::FunctionSchedulerOptions so; so.tickIntervalSec = cfg.schedulerTickSec; so.reclaimIntervalSec = cfg.reclaimIntervalSec; so.claimTimeoutSec = cfg.claimTimeoutSec; so.maxAttempts = cfg.jobMaxAttempts; scheduler = std::make_unique(db, functions, jobQueue, so); scheduler->start(); spdlog::info("cron scheduler started (tick {}s, reclaim {}s)", so.tickIntervalSec, so.reclaimIntervalSec); } if (runners && cfg.eventsEnabled) { svapi::FunctionEventWatcherOptions eo; eo.maxDepth = cfg.eventsMaxDepth; eo.refreshIntervalSec = cfg.eventsRefreshSec; eo.maxPendingEvents = cfg.eventsMaxPending; events = std::make_unique(db, functions, jobQueue, eo); events->start(); spdlog::info("database event watcher started (max trigger depth {})", eo.maxDepth); } server.registerRoutes(); // Before listen, or cpp-httplib has already built its queue and this is // silently ignored. Logged either way so the journal says which pool is in // force; "default" rather than a number, because the number belongs to // httplib and guessing it here is how a doc goes stale. server.setThreadPoolSize(cfg.httpThreadPoolSize); if (cfg.httpThreadPoolSize > 0) spdlog::info("http request threads: {}", cfg.httpThreadPoolSize); else spdlog::info("http request threads: cpp-httplib default (max(8, nproc-1)); " "set http.thread_pool_size to override"); std::thread http([&] { spdlog::info("listening on {}:{}", cfg.httpBind, cfg.httpPort); if (!server.listen(cfg.httpBind, cfg.httpPort)) { spdlog::error("bind failed"); g_running = false; } }); sd_notify(0, "READY=1"); while (g_running) { sd_notify(0, "WATCHDOG=1"); std::this_thread::sleep_for(std::chrono::milliseconds(200)); } sd_notify(0, "STOPPING=1"); // Background threads first, while the database is still reachable: the // scheduler and the watcher both write to the queue, and a thread still // running when the gateway is destroyed is a use-after-free. Both join. if (events) events->stop(); if (scheduler) scheduler->stop(); server.stop(); if (http.joinable()) http.join(); return 0; }