| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785 |
- // The function runner binary.
- //
- // It is the second process of the design in
- // docs/superpowers/specs/2026-10-06-function-runtime-design.md: vectorapi
- // routes and schedules, the runner executes. Everything interesting about the
- // protocol lives in run_service.{hpp,cpp}; this file is wiring - config,
- // logging, the database connection, the two seams RunService takes, and a
- // cpp-httplib server that does nothing but shuttle JSON between them.
- //
- // It deliberately holds the only code here that links vectorapi_core and the
- // database client, which is what keeps run_service testable on a host where
- // that client cannot compile at all (CLAUDE.md).
- #include "db_await.hpp"
- #include "net/mail_session.hpp"
- #include "db_gateway.hpp"
- #include "errors.hpp"
- #include "function_env.hpp"
- #include "function_jobs.hpp"
- #include "job_worker.hpp"
- #include "function_run_log.hpp"
- #include "project_secret_store.hpp"
- #include <mutex>
- #include <set>
- #include "function_record.hpp"
- #include "runner_auth.hpp"
- #include "function_registry.hpp"
- #include "project_settings.hpp"
- #include "run_service.hpp"
- #include "runner/host_context.hpp"
- #include "settings_store.hpp"
- #include <svapi/version.hpp>
- #include <httplib.h>
- #include <nlohmann/json.hpp>
- #include <spdlog/spdlog.h>
- #ifdef HAVE_SYSTEMD
- #include <systemd/sd-daemon.h>
- #else
- #define sd_notify(u, s) do {} while (0)
- #endif
- #include <atomic>
- #include <chrono>
- #include <csignal>
- #include <cstdlib>
- #include <cstring>
- #include <fstream>
- #include <iostream>
- #include <map>
- #include <memory>
- #include <mutex>
- #include <string>
- #include <thread>
- #include <vector>
- namespace {
- std::atomic<bool> g_running{true};
- void onSignal(int) { g_running = false; }
- /// The runner's own bootstrap config. Separate from svapi::Config because the
- /// two processes need different things: no web UI here, but the per-run
- /// ceilings and the pool size, which an operator sizes against the host.
- ///
- /// Same posture as the server's config though: minimal, and only what has to be
- /// known BEFORE the database is reachable. Anything that can hot-reload belongs
- /// in the database, not here.
- ///
- /// The `runtime` ceilings are deliberately BOOT-TIME ONLY, unlike every
- /// hot-reloading setting in the server. QuickJS fixes a runtime's memory limit
- /// when the runtime is created, so changing it live would mean draining and
- /// recreating every pooled runtime - real complexity for a knob that is a
- /// host-sizing decision, not something an operator tunes while watching a
- /// dashboard. Editing these means `systemctl restart
- /// smartbotic-vectorapi-runner`, which is cheap: vectorapi answers 503 for the
- /// moment the runner is down and nothing is stored unvalidated.
- ///
- /// The ONE value that has to stay in step with the server is
- /// `max_wall_time_ms`, the ceiling for HTTP-triggered runs: RunnerPool's
- /// readTimeoutSec must exceed it, or our read times out before the runner can
- /// report its own timeout and a caller gets a misleading 503 instead of a 504.
- /// The JOB ceiling is deliberately not bound by that number - a job run is
- /// claimed from the queue inside this process and no socket is waiting on it.
- struct RunnerConfig {
- std::string logLevel = "info";
- /// Loopback by default: the single-host deployment, where no token is
- /// needed because nothing else can reach the port. Binding anywhere else
- /// REQUIRES a token - see startupRefusal().
- std::string httpBind = "127.0.0.1";
- /// Shared secret vectorapi presents as `Authorization: Bearer`. Prefer
- /// SVAPI_RUNNER_TOKEN in runner.env, which can be mode 0640; this config
- /// file is a conffile and tends to be world-readable.
- std::string authToken;
- uint16_t httpPort = 8090;
- std::string dbAddress = "localhost:9004";
- size_t poolSize = 4;
- size_t memoryLimitBytes = 128u * 1024 * 1024;
- /// Ceiling for a run an HTTP request triggered. Kept at two seconds: a
- /// client is waiting on it, and vectorapi's read timeout is sized against
- /// this number.
- /// 15 s, not 2. A project cap can only NARROW this, so a 2000 ms ceiling
- /// made every per-project cap pointless: no project could raise its own
- /// limit at all, which is the opposite of what the cap is for. 15 s lets a
- /// voice tool that has to embed a query fit inside the ~20 s a caller
- /// typically waits.
- ///
- /// It is a CEILING, not a grant: a function gets it only by declaring
- /// timeoutMs, and defaultWallTimeMs decides what an undeclared one gets.
- int64_t maxWallTimeMs = 15000;
- /// Ceiling for a run the job queue triggered (cron, database events). Two
- /// minutes, because that is what the work is: an LLM call takes seconds to
- /// tens of seconds and an uncached embedding search has been measured at
- /// 26 s, and none of it has a client waiting on a socket.
- int64_t maxJobWallTimeMs = 120000;
- /// Applied when a descriptor declares no timeoutMs.
- ///
- /// Deliberately NOT "use the ceiling". Raising the HTTP ceiling to 15 s
- /// while this meant the ceiling would hand every existing function 15 s of
- /// runtime lease it never asked for, and a pool of 2 would be held by two
- /// slow requests. An undeclared function keeps 2 s; one that needs longer
- /// says so, and an admin caps the project.
- int64_t defaultWallTimeMs = 2000;
- /// How long a project's wall-time maximum is cached before it is re-read.
- /// Not subscribed to, unlike the server's settings: one read per project
- /// per interval is nothing, and a per-run read would put two round trips on
- /// the hot path for a number that changes by hand.
- size_t maxStackBytes = 512u * 1024;
- size_t bytecodeCacheEntries = 64;
- /// Runtimes reserved for job runs. A separate lane, so a cron job holding a
- /// runtime for its whole 120 s ceiling cannot take the one an interactive
- /// route is about to need. Costs memory: the per-run ceiling is per
- /// runtime, so this adds to poolSize rather than dividing it.
- size_t jobPoolSize = 4;
- /// Claiming queued work is OFF by default: a runner upgrade must not start
- /// draining a queue in a deployment whose server has no scheduler.
- bool jobsEnabled = false;
- uint32_t jobWorkers = 0; ///< 0 = jobPoolSize - 1, never below 1
- uint32_t jobMaxAttempts = 5;
- uint32_t staleClaimSec = 300;
- /// Runs kept per function by the JOB worker's log writes. Should match the
- /// server's functions.runs_kept, or the two trim one log to two depths.
- uint32_t functionRunsKept = 50;
- /// How long a single /run or /validate request may occupy a server thread.
- /// Above the wall-time ceiling on purpose: a run that is about to be killed
- /// should report its own timeout rather than have the socket cut first.
- int readTimeoutSec = 30;
- static RunnerConfig fromJson(const nlohmann::json& j) {
- RunnerConfig c;
- c.logLevel = j.value("log_level", c.logLevel);
- if (j.contains("http") && j["http"].is_object()) {
- const auto& h = j["http"];
- c.httpBind = h.value("bind_address", c.httpBind);
- c.httpPort = h.value("port", c.httpPort);
- c.readTimeoutSec = h.value("read_timeout_sec", c.readTimeoutSec);
- c.authToken = h.value("auth_token", c.authToken);
- }
- if (j.contains("jobs") && j["jobs"].is_object()) {
- const auto& jb = j["jobs"];
- c.jobsEnabled = jb.value("enabled", c.jobsEnabled);
- c.jobWorkers = jb.value("workers", c.jobWorkers);
- c.jobMaxAttempts = jb.value("max_attempts", c.jobMaxAttempts);
- c.staleClaimSec = jb.value("stale_claim_sec", c.staleClaimSec);
- }
- if (j.contains("function_runs_kept"))
- c.functionRunsKept = j.value("function_runs_kept", c.functionRunsKept);
- if (j.contains("database") && j["database"].is_object())
- c.dbAddress = j["database"].value("address", c.dbAddress);
- if (j.contains("runtime") && j["runtime"].is_object()) {
- const auto& r = j["runtime"];
- c.poolSize = r.value("pool_size", c.poolSize);
- c.memoryLimitBytes = r.value("memory_limit_bytes", c.memoryLimitBytes);
- // `max_wall_time_ms` keeps its old name and its old meaning - the
- // HTTP ceiling - so an existing conffile is not silently
- // reinterpreted. `max_http_wall_time_ms` is the clearer spelling
- // and wins when both are present.
- c.maxWallTimeMs = r.value("max_wall_time_ms", c.maxWallTimeMs);
- c.maxWallTimeMs = r.value("max_http_wall_time_ms", c.maxWallTimeMs);
- c.maxJobWallTimeMs = r.value("max_job_wall_time_ms", c.maxJobWallTimeMs);
- c.defaultWallTimeMs = r.value("default_wall_time_ms", c.defaultWallTimeMs);
- c.maxStackBytes = r.value("max_stack_bytes", c.maxStackBytes);
- c.bytecodeCacheEntries = r.value("bytecode_cache_entries", c.bytecodeCacheEntries);
- c.jobPoolSize = r.value("job_pool_size", c.jobPoolSize);
- }
- return c;
- }
- static RunnerConfig load(const std::string& path) {
- std::ifstream f(path);
- if (!f) throw std::runtime_error("cannot open config file: " + path);
- nlohmann::json j;
- f >> j;
- return fromJson(j);
- }
- };
- /// One project's admin-set wall-time maximums, per run kind.
- ///
- /// Backed by SettingsStore, which SUBSCRIBES: a change to a project's cap
- /// reaches the next run immediately instead of after a TTL. This used to be a
- /// hand-rolled cache polling the settings document every
- /// `project_budget_ttl_sec` seconds, which meant clearing a cap appeared not to
- /// work for up to 15 seconds and produced a bug report that cost real time to
- /// run down. The server already hot-reloads the same document off the same
- /// stream; there was no reason for the runner to be the one component guessing.
- ///
- /// reloadAll() rather than bootstrap(): bootstrap WRITES, seeding the settings
- /// document, and a runner must never author configuration it only reads.
- /// The precedence itself stays in the one pure maxFunctionWallTimeMsFor().
- class ProjectWallMax {
- public:
- explicit ProjectWallMax(svapi::DbGateway& db)
- : store_(db, svapi::kSettingsCollection, "current") {
- try {
- store_.reloadAll();
- } catch (const std::exception& e) {
- // Start anyway. An unreadable settings document means no project
- // cap is known, and a run then falls back to the configured
- // ceiling, which still bounds it - a project maximum can only
- // narrow. Refusing to start would be a worse trade.
- spdlog::warn("could not load project settings at startup - {}", e.what());
- }
- try {
- store_.startWatch();
- } catch (const std::exception& e) {
- spdlog::warn("could not subscribe to project settings - {}", e.what());
- }
- }
- int64_t get(const std::string& project, svapi::functions::RunKind kind) const {
- const std::shared_ptr<const svapi::ProjectSettings> p = store_.projectSnapshot(project);
- return svapi::maxFunctionWallTimeMsFor(p.get(), kind);
- }
- private:
- mutable svapi::SettingsStore store_;
- };
- /// RunService's registry seam, over the real FunctionRegistry.
- ///
- /// The whole adapter is this one translation, which is the point: the protocol
- /// layer never learns that a database exists, and this class holds no logic a
- /// test would want to reach.
- /// The job worker's queue port, over the real queue.
- ///
- /// Translates FunctionJob to the worker's JobView and back. The worker never
- /// sees the database, which is what keeps its decisions testable; `raw` carries
- /// the stored row so completing needs no state kept here.
- ///
- /// Nothing in here may throw: the worker's contract is that a transient read
- /// reports "nothing to do" rather than killing the loop, because a loop that a
- /// database blip can kill is a loop that stops doing cron.
- class WorkerQueuePort : public svapi::runner::JobQueuePort {
- public:
- explicit WorkerQueuePort(svapi::FunctionJobQueue& queue) : queue_(queue) {}
- std::optional<svapi::runner::JobView> claimNext(const std::string& runnerId) override {
- try {
- std::optional<svapi::FunctionJob> job = queue_.claimNext(runnerId);
- if (!job) return std::nullopt;
- svapi::runner::JobView v;
- v.jobId = job->jobId;
- v.project = job->project;
- v.functionId = job->functionId;
- v.trigger = job->trigger;
- v.payload = job->payload;
- // claimNext increments on claim, so this already counts the attempt
- // about to happen; 0 would mean the queue did not count it.
- v.attempts = job->attempts == 0 ? 1 : job->attempts;
- v.raw = job->toJson();
- v.raw["version"] = job->version; // toJson does not carry it
- return v;
- } catch (const std::exception& e) {
- spdlog::warn("claim failed: {}", e.what());
- return std::nullopt;
- }
- }
- bool complete(const svapi::runner::JobView& v, bool ok, const std::string& error,
- uint32_t retryAfterSec) override {
- try {
- svapi::FunctionJob job = svapi::FunctionJob::fromJson(v.raw);
- job.jobId = v.jobId; // the body never carries `id`
- job.version = v.raw.value("version", uint64_t{0});
- return queue_.complete(job, ok, error, retryAfterSec);
- } catch (const std::exception& e) {
- spdlog::warn("completing job {} failed: {}", v.jobId, e.what());
- return false;
- }
- }
- uint32_t reclaimStale(uint32_t timeoutSec, uint32_t maxAttempts) override {
- try {
- return queue_.reclaimStale(timeoutSec, maxAttempts);
- } catch (const std::exception& e) {
- spdlog::warn("reclaim failed: {}", e.what());
- return 0;
- }
- }
- private:
- svapi::FunctionJobQueue& queue_;
- };
- /// The job worker's run-log port. ensure() is remembered per project because
- /// the worker is multi-threaded, and a run log write must never change the
- /// outcome of the job it is recording.
- class WorkerRunLogPort : public svapi::runner::RunLogPort {
- public:
- explicit WorkerRunLogPort(svapi::FunctionRunLogStore& store) : store_(store) {}
- void record(const std::string& project, const svapi::runner::JobRunRecord& entry) override {
- try {
- {
- std::lock_guard<std::mutex> lock(mu_);
- if (ensured_.insert(project).second) store_.ensure(project);
- }
- svapi::FunctionRunLog row;
- row.runId = entry.runId;
- row.functionId = entry.functionId;
- row.trigger = entry.trigger;
- row.ok = entry.ok;
- row.status = entry.status;
- row.durationMs = entry.durationMs;
- row.error = entry.error;
- row.console = entry.console;
- row.headers = entry.headers;
- row.startedAt = entry.startedAt;
- store_.append(project, row);
- } catch (const std::exception& e) {
- spdlog::warn("run log write failed for {}/{}: {}", project, entry.functionId, e.what());
- }
- }
- private:
- svapi::FunctionRunLogStore& store_;
- std::mutex mu_;
- std::set<std::string> ensured_;
- };
- /// ctx.jobs, over the real queue.
- ///
- /// The authorization rule lives HERE rather than in the host context, because
- /// it needs the registry and the host context deliberately does not: a function
- /// may only enqueue something a caller could otherwise reach. Without this a
- /// script could schedule a disabled or invalid function, or name an id that
- /// does not exist and get a row nothing will ever drain.
- class QueueJobPort : public svapi::runner::JobPort {
- public:
- QueueJobPort(svapi::FunctionJobQueue& queue, svapi::FunctionRegistry& registry)
- : queue_(queue), registry_(registry) {}
- std::string enqueue(const std::string& project, const std::string& functionId,
- const nlohmann::json& trigger, uint64_t runAfterEpochSec, uint32_t depth,
- const std::string& jobId) override {
- // Same rule /fn/{project}/* applies: absent, disabled and invalid are
- // one answer to a caller, so a script learns nothing about which.
- const std::optional<svapi::FunctionRecord> target = registry_.get(project, functionId);
- if (!target || !target->enabled || !target->valid)
- throw svapi::ApiError(svapi::ErrCode::NotFound, "not_found",
- "no enabled function '" + functionId + "' in this project");
- svapi::FunctionJob job;
- job.jobId = jobId; // empty: the queue mints one
- job.project = project;
- job.functionId = functionId;
- job.trigger = "job";
- job.payload = trigger;
- job.depth = depth;
- job.runAfter = runAfterEpochSec;
- const std::string id = queue_.enqueue(job);
- if (id.empty())
- throw svapi::ApiError(svapi::ErrCode::Unavailable, "enqueue_failed",
- "the job could not be queued");
- return id;
- }
- bool cancel(const std::string& project, const std::string& jobId) override {
- const std::optional<svapi::FunctionJob> job = queue_.get(jobId);
- if (!job) return false;
- // Project checked against the ROW, not taken from the caller: a job id
- // is global, so a matching id in another tenant's queue must not be
- // cancellable from here.
- if (job->project != project) return false;
- // A claimed job may be executing this instant. Deleting the row would
- // not stop the run, and would leave the runner completing a job that no
- // longer exists.
- if (job->state == "claimed") return false;
- return queue_.remove(jobId);
- }
- private:
- svapi::FunctionJobQueue& queue_;
- svapi::FunctionRegistry& registry_;
- };
- class RegistryFunctionSource : public svapi::runner::FunctionSource {
- public:
- RegistryFunctionSource(svapi::FunctionRegistry& registry, ProjectWallMax& budgets)
- : registry_(registry), budgets_(budgets) {}
- svapi::runner::FunctionView lookup(const std::string& project,
- const std::string& functionId) override {
- svapi::runner::FunctionView view;
- std::optional<svapi::FunctionRecord> row;
- try {
- row = registry_.get(project, functionId);
- } catch (const std::exception& e) {
- // A database failure is not a missing function, but the /run
- // contract has no third answer. Logged loudly so the two are
- // distinguishable in the journal even though the caller sees a 404.
- spdlog::error("registry read failed for {}:{} - {}", project, functionId, e.what());
- return view;
- }
- if (!row) return view;
- view.found = true;
- view.source = row->source;
- view.contentHash = row->contentHash;
- view.descriptor = row->descriptor;
- view.policy = row->policy;
- view.enabled = row->enabled;
- view.valid = row->valid;
- view.lastError = row->lastError;
- view.projectMaxWallTimeHttpMs = budgets_.get(project, svapi::functions::RunKind::Http);
- view.projectMaxWallTimeJobMs = budgets_.get(project, svapi::functions::RunKind::Job);
- return view;
- }
- private:
- svapi::FunctionRegistry& registry_;
- ProjectWallMax& budgets_;
- };
- /// RunService's ctx seam, over the real HostContext.
- class GatewayHostBindings : public svapi::runner::HostBindingsFactory {
- public:
- GatewayHostBindings(svapi::DbGateway& db, std::vector<std::string> environment,
- std::shared_ptr<svapi::runner::JobPort> jobs)
- : db_(db), environment_(std::move(environment)), jobs_(std::move(jobs)) {}
- bool create(const Request& request, svapi::runner::HostBindingsLease& out,
- std::string& error) override {
- svapi::runner::HostContextConfig cfg;
- cfg.project = request.project;
- cfg.functionId = request.functionId;
- cfg.policy = request.policy;
- cfg.trigger = request.trigger;
- cfg.deadlineMs = request.deadlineMs;
- // Only this project's secrets, from the runner's own environment
- // (systemd loads runner.env). The project is part of each variable's
- // name, because one runner serves every project and nothing else would
- // keep one tenant's key away from another's script.
- // Read per run, not cached: a cached secret is a rotated credential
- // that keeps working. A database failure here throws, which create()
- // turns into "host context unavailable" - better than a run that
- // silently proceeds without its credentials.
- cfg.jobs = jobs_;
- cfg.env = svapi::runner::functionEnvFor(request.project, environment_,
- svapi::ProjectSecretStore(db_).valuesFor(
- request.project));
- try {
- auto host = std::make_unique<svapi::runner::HostContext>(db_, std::move(cfg));
- svapi::runner::HostContext* raw = host.get();
- out.bindings = std::move(host);
- out.collectConsole = [raw] {
- std::vector<std::string> lines = raw->logLines();
- // Refused egress is reported as console output rather than
- // swallowed: a blocked fetch otherwise reaches the author
- // looking like an ordinary network error he will debug forever.
- for (const auto& blocked : raw->blockedEgress())
- lines.push_back("egress blocked: " + blocked);
- return lines;
- };
- return true;
- } catch (const std::exception& e) {
- error = std::string("host context unavailable: ") + e.what();
- return false;
- }
- }
- private:
- svapi::DbGateway& db_;
- std::vector<std::string> environment_;
- /// Null when the queue is not available, which ctx.jobs reports as
- /// `jobs_unavailable` rather than pretending to enqueue.
- std::shared_ptr<svapi::runner::JobPort> jobs_;
- };
- /// Parse a request body, or answer 400 with the same error envelope the rest of
- /// the protocol uses.
- bool readJsonBody(const httplib::Request& req, httplib::Response& res, nlohmann::json& out) {
- try {
- out = nlohmann::json::parse(req.body.empty() ? "{}" : req.body);
- } catch (const std::exception& e) {
- res.status = 400;
- res.set_content(nlohmann::json{{"ok", false},
- {"error", std::string("invalid JSON body: ") + e.what()}}
- .dump(),
- "application/json");
- return false;
- }
- return true;
- }
- void reply(httplib::Response& res, const svapi::runner::ProtocolResponse& out) {
- res.status = out.httpStatus;
- res.set_content(out.body.dump(), "application/json");
- }
- } // namespace
- int main(int argc, char** argv) {
- std::string configPath = "/etc/smartbotic-vectorapi/runner.json";
- 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], "--version") == 0 || std::strcmp(argv[i], "-v") == 0) {
- std::cout << "smartbotic-vectorapi-runner " << svapi::VERSION << " ("
- << svapi::GIT_COMMIT << ")\n";
- return 0;
- }
- }
- RunnerConfig cfg;
- try { cfg = RunnerConfig::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));
- std::signal(SIGINT, onSignal); std::signal(SIGTERM, onSignal); std::signal(SIGPIPE, SIG_IGN);
- // Mail, before ANY worker thread exists. curl_global_init is not
- // thread-safe and curl's own lazy first-use initialisation from two pool
- // threads at once is a real race, not a theoretical one. It also verifies
- // libcurl was built thread-safe and REFUSES TO START otherwise, in the
- // same spirit as the runner refusing to start with no token on a
- // non-loopback bind: a curl without CURL_VERSION_THREADSAFE cannot be
- // driven safely from this pool, and finding that out from a crash under
- // load costs far more than failing here.
- if (const std::string why = svapi::runner::net::mailGlobalInit(); !why.empty()) {
- spdlog::error("refusing to start: {}", why);
- return 1;
- }
- svapi::DbGateway db(cfg.dbAddress);
- 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::FunctionRegistry registry(db);
- // Re-open every project's function collection. The database only surfaces a
- // collection through find()/list() once it has been opened in the current
- // process, so without this a restart leaves every function invisible even
- // though the rows survive - the same trap CollectionRegistry::bootstrap and
- // KeyStore::bootstrap exist for.
- {
- auto projects = db.listProjects();
- registry.bootstrap(projects);
- spdlog::info("opened the function registry for {} project(s)", projects.size());
- }
- svapi::runner::RunServiceOptions options;
- options.poolSize = cfg.poolSize;
- options.limits.memory_limit_bytes = cfg.memoryLimitBytes;
- options.httpWallCeilingMs = cfg.maxWallTimeMs;
- options.jobWallCeilingMs = cfg.maxJobWallTimeMs;
- // The engine's hard ceiling is raised to the highest of the two by
- // RunService itself; setting it from the HTTP ceiling here would cap every
- // job run at the HTTP budget.
- options.limits.wall_time_ms = cfg.maxWallTimeMs;
- options.limits.max_stack_bytes = cfg.maxStackBytes;
- options.defaultTimeoutMs = cfg.defaultWallTimeMs;
- options.bytecodeCacheEntries = cfg.bytecodeCacheEntries;
- options.version = svapi::VERSION;
- options.jobPoolSize = cfg.jobPoolSize;
- ProjectWallMax projectBudgets(db);
- RegistryFunctionSource source(registry, projectBudgets);
- // The queue has to exist before the bindings that enqueue into it. ensure()
- // is idempotent and also re-opens the collection, without which find()
- // cannot see existing rows in this process.
- svapi::FunctionJobQueue jobQueue(db);
- jobQueue.ensure();
- auto jobPort = std::make_shared<QueueJobPort>(jobQueue, registry);
- // Snapshot the environment once: it does not change under a running
- // process, and re-reading it per run would be work for no gain.
- GatewayHostBindings host(db, svapi::runner::processEnvironment(), jobPort);
- svapi::runner::RunService service(source, options, &host);
- // THE thing that drains the queue. Without it the scheduler enqueues a job,
- // nothing ever claims it, and single-flight then correctly refuses to stack
- // a second copy behind the stuck one - so cron produces exactly zero runs
- // and looks like a scheduler that never fires. 0.5.0 shipped without this.
- //
- // Off unless jobs.enabled, so a runner upgrade never starts draining a
- // queue in a deployment whose server has no scheduler.
- svapi::FunctionRunLogStore jobRunLog(db, cfg.functionRunsKept);
- WorkerQueuePort workerQueue(jobQueue);
- WorkerRunLogPort workerLog(jobRunLog);
- std::unique_ptr<svapi::runner::JobWorker> worker;
- if (cfg.jobsEnabled) {
- svapi::runner::JobWorkerOptions wo;
- wo.poolSize = cfg.jobPoolSize > 0 ? cfg.jobPoolSize : cfg.poolSize;
- wo.workers = cfg.jobWorkers;
- wo.maxAttempts = cfg.jobMaxAttempts;
- wo.staleClaimSec = cfg.staleClaimSec;
- worker = std::make_unique<svapi::runner::JobWorker>(service, workerQueue, workerLog, wo);
- }
- // The environment wins over the config file: a secret belongs in
- // runner.env, which systemd can keep at mode 0640, not in a conffile.
- std::string authToken = cfg.authToken;
- if (const char* fromEnv = std::getenv(svapi::runner::kRunnerTokenEnvVar);
- fromEnv != nullptr && *fromEnv != '\0') {
- authToken = fromEnv;
- }
- if (const auto refusal = svapi::runner::startupRefusal(cfg.httpBind, authToken)) {
- spdlog::critical("{}", *refusal);
- return 1;
- }
- if (authToken.empty()) {
- spdlog::warn("no runner token set; serving unauthenticated on {} - safe only"
- " because nothing off this host can reach it", cfg.httpBind);
- }
- httplib::Server server;
- server.set_read_timeout(cfg.readTimeoutSec, 0);
- server.set_write_timeout(cfg.readTimeoutSec, 0);
- // The pool already bounds concurrency; matching the thread count to it
- // keeps requests waiting in the accept queue instead of piling up threads
- // that all block on acquire().
- server.new_task_queue = [&cfg] {
- return new httplib::ThreadPool(static_cast<size_t>(cfg.poolSize) + 2);
- };
- // Authenticate everything, /health included. The health check is what
- // vectorapi uses to decide a runner is usable, and it reports the pool's
- // state - neither is something an unauthenticated caller should see.
- if (!authToken.empty()) {
- server.set_pre_routing_handler(
- [&authToken](const httplib::Request& req, httplib::Response& res) {
- const std::string presented =
- svapi::runner::bearerToken(req.get_header_value("Authorization"));
- if (svapi::runner::tokenMatches(authToken, presented))
- return httplib::Server::HandlerResponse::Unhandled;
- res.status = 401;
- res.set_content(R"({"error":{"code":"unauthorized","message":)"
- R"("missing or invalid runner token"}})",
- "application/json");
- return httplib::Server::HandlerResponse::Handled;
- });
- }
- server.Post("/run", [&service](const httplib::Request& req, httplib::Response& res) {
- nlohmann::json body;
- if (!readJsonBody(req, res, body)) return;
- // The kind of run is the caller's statement, not a guess: only the
- // caller knows whether a socket is waiting on this. Absent or
- // unrecognised means HTTP, the short budget, because that is the
- // mistake that costs a slow run rather than a pinned runtime. A
- // forged "job" buys nothing an attacker wants either, and this port is
- // token-authenticated and reachable only by vectorapi.
- const std::string kindName =
- body.is_object() && body.contains("kind") && body.at("kind").is_string()
- ? body.at("kind").get<std::string>()
- : std::string();
- reply(res, service.run(body, svapi::functions::parseRunKind(
- kindName, svapi::functions::RunKind::Http)));
- });
- server.Post("/validate", [&service](const httplib::Request& req, httplib::Response& res) {
- nlohmann::json body;
- if (!readJsonBody(req, res, body)) return;
- reply(res, service.validate(body));
- });
- server.Get("/health", [&service, &worker, &cfg](const httplib::Request&,
- httplib::Response& res) {
- svapi::runner::ProtocolResponse out = service.health();
- // The job worker's existence is REPORTED, not inferred from an empty
- // log. 0.5.0 shipped without a worker at all, and the only symptom was
- // a quiet log that read exactly like an idle one - so cron enqueued and
- // nothing ran, and a health check that said "ok" was telling the truth
- // about everything it knew to look at. Anything a deployment can forget
- // to wire has to be visible here.
- if (out.body.is_object()) {
- if (worker) {
- const svapi::runner::JobWorker::Stats s = worker->stats();
- out.body["jobs"] = {{"running", true},
- {"workers", cfg.jobWorkers},
- {"claimed", s.claimed},
- {"succeeded", s.succeeded},
- {"retried", s.retried},
- {"failed", s.failed},
- {"complete_failures", s.completeFailures},
- {"reclaimed", s.reclaimed}};
- } else {
- // Said plainly, because this state means queued cron and
- // database events will never run on this runner.
- out.body["jobs"] = {{"running", false},
- {"reason", "jobs.enabled is false in runner.json"}};
- }
- }
- reply(res, out);
- });
- // An unexpected throw must not take the process down: one bad function
- // would otherwise stop every other tenant's.
- server.set_exception_handler([](const httplib::Request& req, httplib::Response& res,
- std::exception_ptr ep) {
- std::string what = "unknown error";
- try { std::rethrow_exception(ep); }
- catch (const std::exception& e) { what = e.what(); }
- catch (...) {}
- spdlog::error("unhandled exception on {} {}: {}", req.method, req.path, what);
- res.status = 500;
- res.set_content(nlohmann::json{{"ok", false}, {"error", what}}.dump(), "application/json");
- });
- // Bind BEFORE notifying, on this thread. listen() binds and serves in one
- // call, so notifying after merely spawning the thread would tell systemd we
- // are ready while the bind was still pending - or had already failed. Under
- // Type=notify that makes a runner that is about to exit look started, and
- // anything ordered after it would briefly see success.
- if (!server.bind_to_port(cfg.httpBind, cfg.httpPort)) {
- spdlog::critical("cannot bind {}:{} - address in use, or not permitted", cfg.httpBind,
- cfg.httpPort);
- return 1;
- }
- std::atomic<bool> serveFailed{false};
- std::thread http([&] {
- if (!server.listen_after_bind()) {
- spdlog::error("the listener stopped unexpectedly");
- serveFailed = true;
- g_running = false;
- }
- });
- spdlog::info("runner listening on {}:{} (pool {}, wall limit {}ms http / {}ms job)",
- cfg.httpBind, cfg.httpPort, cfg.poolSize, cfg.maxWallTimeMs,
- cfg.maxJobWallTimeMs);
- // Only matters for a job-kind run REQUESTED OVER HTTP: the socket would be
- // cut before the runner could report its own timeout, and the caller would
- // read a 503 instead of a 504. Queue-claimed jobs are unaffected, which is
- // why this is a warning and not a refusal to start.
- if (cfg.maxJobWallTimeMs >= static_cast<int64_t>(cfg.readTimeoutSec) * 1000) {
- spdlog::warn("the job wall ceiling ({}ms) is at or above this server's read timeout"
- " ({}s); a job-kind run posted to /run would have its socket cut before"
- " it could report a timeout", cfg.maxJobWallTimeMs, cfg.readTimeoutSec);
- }
- // Started after READY so /health answers before any job runs, and a
- // deployment that is coming up does not begin side-effecting work before it
- // is reachable.
- if (worker) {
- worker->start();
- spdlog::info("job worker started (lane {}, workers {}, stale claim {}s)", cfg.jobPoolSize,
- cfg.jobWorkers, cfg.staleClaimSec);
- } else {
- spdlog::info("job worker disabled (jobs.enabled false) - queued cron and database "
- "events will NOT run on this runner");
- }
- 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");
- // Stop claiming while the database is still up, and before the service it
- // runs jobs through goes away. A job in flight runs to completion.
- if (worker) worker->stop();
- server.stop();
- if (http.joinable()) http.join();
- // Paired with mailGlobalInit, and deliberately AFTER the listener and the
- // job worker have stopped: curl_global_cleanup while a worker could still
- // be inside a mail call is a use-after-free.
- svapi::runner::net::mailGlobalCleanup();
- // Non-zero on a listener failure, so Restart=on-failure actually fires. A
- // signal-driven shutdown is a clean exit.
- return serveFailed ? 1 : 0;
- }
|