main.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. // The function runner binary.
  2. //
  3. // It is the second process of the design in
  4. // docs/superpowers/specs/2026-10-06-function-runtime-design.md: vectorapi
  5. // routes and schedules, the runner executes. Everything interesting about the
  6. // protocol lives in run_service.{hpp,cpp}; this file is wiring - config,
  7. // logging, the database connection, the two seams RunService takes, and a
  8. // cpp-httplib server that does nothing but shuttle JSON between them.
  9. //
  10. // It deliberately holds the only code here that links vectorapi_core and the
  11. // database client, which is what keeps run_service testable on a host where
  12. // that client cannot compile at all (CLAUDE.md).
  13. #include "db_gateway.hpp"
  14. #include "errors.hpp"
  15. #include "function_env.hpp"
  16. #include "function_jobs.hpp"
  17. #include "job_worker.hpp"
  18. #include "project_secret_store.hpp"
  19. #include "function_record.hpp"
  20. #include "runner_auth.hpp"
  21. #include "function_registry.hpp"
  22. #include "project_settings.hpp"
  23. #include "run_service.hpp"
  24. #include "runner/host_context.hpp"
  25. #include "settings_store.hpp"
  26. #include <svapi/version.hpp>
  27. #include <httplib.h>
  28. #include <nlohmann/json.hpp>
  29. #include <spdlog/spdlog.h>
  30. #ifdef HAVE_SYSTEMD
  31. #include <systemd/sd-daemon.h>
  32. #else
  33. #define sd_notify(u, s) do {} while (0)
  34. #endif
  35. #include <atomic>
  36. #include <chrono>
  37. #include <csignal>
  38. #include <cstdlib>
  39. #include <cstring>
  40. #include <fstream>
  41. #include <iostream>
  42. #include <map>
  43. #include <memory>
  44. #include <mutex>
  45. #include <string>
  46. #include <thread>
  47. #include <vector>
  48. namespace {
  49. std::atomic<bool> g_running{true};
  50. void onSignal(int) { g_running = false; }
  51. /// The runner's own bootstrap config. Separate from svapi::Config because the
  52. /// two processes need different things: no web UI here, but the per-run
  53. /// ceilings and the pool size, which an operator sizes against the host.
  54. ///
  55. /// Same posture as the server's config though: minimal, and only what has to be
  56. /// known BEFORE the database is reachable. Anything that can hot-reload belongs
  57. /// in the database, not here.
  58. ///
  59. /// The `runtime` ceilings are deliberately BOOT-TIME ONLY, unlike every
  60. /// hot-reloading setting in the server. QuickJS fixes a runtime's memory limit
  61. /// when the runtime is created, so changing it live would mean draining and
  62. /// recreating every pooled runtime - real complexity for a knob that is a
  63. /// host-sizing decision, not something an operator tunes while watching a
  64. /// dashboard. Editing these means `systemctl restart
  65. /// smartbotic-vectorapi-runner`, which is cheap: vectorapi answers 503 for the
  66. /// moment the runner is down and nothing is stored unvalidated.
  67. ///
  68. /// The ONE value that has to stay in step with the server is
  69. /// `max_wall_time_ms`, the ceiling for HTTP-triggered runs: RunnerPool's
  70. /// readTimeoutSec must exceed it, or our read times out before the runner can
  71. /// report its own timeout and a caller gets a misleading 503 instead of a 504.
  72. /// The JOB ceiling is deliberately not bound by that number - a job run is
  73. /// claimed from the queue inside this process and no socket is waiting on it.
  74. struct RunnerConfig {
  75. std::string logLevel = "info";
  76. /// Loopback by default: the single-host deployment, where no token is
  77. /// needed because nothing else can reach the port. Binding anywhere else
  78. /// REQUIRES a token - see startupRefusal().
  79. std::string httpBind = "127.0.0.1";
  80. /// Shared secret vectorapi presents as `Authorization: Bearer`. Prefer
  81. /// SVAPI_RUNNER_TOKEN in runner.env, which can be mode 0640; this config
  82. /// file is a conffile and tends to be world-readable.
  83. std::string authToken;
  84. uint16_t httpPort = 8090;
  85. std::string dbAddress = "localhost:9004";
  86. size_t poolSize = 4;
  87. size_t memoryLimitBytes = 128u * 1024 * 1024;
  88. /// Ceiling for a run an HTTP request triggered. Kept at two seconds: a
  89. /// client is waiting on it, and vectorapi's read timeout is sized against
  90. /// this number.
  91. int64_t maxWallTimeMs = 2000;
  92. /// Ceiling for a run the job queue triggered (cron, database events). Two
  93. /// minutes, because that is what the work is: an LLM call takes seconds to
  94. /// tens of seconds and an uncached embedding search has been measured at
  95. /// 26 s, and none of it has a client waiting on a socket.
  96. int64_t maxJobWallTimeMs = 120000;
  97. /// Applied when a descriptor declares no timeoutMs. 0 = use whichever
  98. /// ceiling applies to the run.
  99. int64_t defaultWallTimeMs = 0;
  100. /// How long a project's wall-time maximum is cached before it is re-read.
  101. /// Not subscribed to, unlike the server's settings: one read per project
  102. /// per interval is nothing, and a per-run read would put two round trips on
  103. /// the hot path for a number that changes by hand.
  104. int projectBudgetTtlSec = 15;
  105. size_t maxStackBytes = 512u * 1024;
  106. size_t bytecodeCacheEntries = 64;
  107. /// Runtimes reserved for job runs. A separate lane, so a cron job holding a
  108. /// runtime for its whole 120 s ceiling cannot take the one an interactive
  109. /// route is about to need. Costs memory: the per-run ceiling is per
  110. /// runtime, so this adds to poolSize rather than dividing it.
  111. size_t jobPoolSize = 4;
  112. /// Claiming queued work is OFF by default: a runner upgrade must not start
  113. /// draining a queue in a deployment whose server has no scheduler.
  114. bool jobsEnabled = false;
  115. uint32_t jobWorkers = 0; ///< 0 = jobPoolSize - 1, never below 1
  116. uint32_t jobMaxAttempts = 5;
  117. uint32_t staleClaimSec = 300;
  118. /// How long a single /run or /validate request may occupy a server thread.
  119. /// Above the wall-time ceiling on purpose: a run that is about to be killed
  120. /// should report its own timeout rather than have the socket cut first.
  121. int readTimeoutSec = 30;
  122. static RunnerConfig fromJson(const nlohmann::json& j) {
  123. RunnerConfig c;
  124. c.logLevel = j.value("log_level", c.logLevel);
  125. if (j.contains("http") && j["http"].is_object()) {
  126. const auto& h = j["http"];
  127. c.httpBind = h.value("bind_address", c.httpBind);
  128. c.httpPort = h.value("port", c.httpPort);
  129. c.readTimeoutSec = h.value("read_timeout_sec", c.readTimeoutSec);
  130. c.authToken = h.value("auth_token", c.authToken);
  131. }
  132. if (j.contains("jobs") && j["jobs"].is_object()) {
  133. const auto& jb = j["jobs"];
  134. c.jobsEnabled = jb.value("enabled", c.jobsEnabled);
  135. c.jobWorkers = jb.value("workers", c.jobWorkers);
  136. c.jobMaxAttempts = jb.value("max_attempts", c.jobMaxAttempts);
  137. c.staleClaimSec = jb.value("stale_claim_sec", c.staleClaimSec);
  138. }
  139. if (j.contains("database") && j["database"].is_object())
  140. c.dbAddress = j["database"].value("address", c.dbAddress);
  141. if (j.contains("runtime") && j["runtime"].is_object()) {
  142. const auto& r = j["runtime"];
  143. c.poolSize = r.value("pool_size", c.poolSize);
  144. c.memoryLimitBytes = r.value("memory_limit_bytes", c.memoryLimitBytes);
  145. // `max_wall_time_ms` keeps its old name and its old meaning - the
  146. // HTTP ceiling - so an existing conffile is not silently
  147. // reinterpreted. `max_http_wall_time_ms` is the clearer spelling
  148. // and wins when both are present.
  149. c.maxWallTimeMs = r.value("max_wall_time_ms", c.maxWallTimeMs);
  150. c.maxWallTimeMs = r.value("max_http_wall_time_ms", c.maxWallTimeMs);
  151. c.maxJobWallTimeMs = r.value("max_job_wall_time_ms", c.maxJobWallTimeMs);
  152. c.defaultWallTimeMs = r.value("default_wall_time_ms", c.defaultWallTimeMs);
  153. c.projectBudgetTtlSec = r.value("project_budget_ttl_sec", c.projectBudgetTtlSec);
  154. c.maxStackBytes = r.value("max_stack_bytes", c.maxStackBytes);
  155. c.bytecodeCacheEntries = r.value("bytecode_cache_entries", c.bytecodeCacheEntries);
  156. c.jobPoolSize = r.value("job_pool_size", c.jobPoolSize);
  157. }
  158. return c;
  159. }
  160. static RunnerConfig load(const std::string& path) {
  161. std::ifstream f(path);
  162. if (!f) throw std::runtime_error("cannot open config file: " + path);
  163. nlohmann::json j;
  164. f >> j;
  165. return fromJson(j);
  166. }
  167. };
  168. /// One project's admin-set wall-time maximum, cached for a few seconds.
  169. ///
  170. /// Read straight through the gateway rather than through SettingsStore, for the
  171. /// reason HostContext gives for doing the same: the store's bootstrap() WRITES,
  172. /// seeding the settings document, which a runner must never do to configuration
  173. /// it is only reading. The precedence itself stays in the one pure
  174. /// maxFunctionWallTimeMsFor().
  175. class ProjectWallMaxCache {
  176. public:
  177. ProjectWallMaxCache(svapi::DbGateway& db, int ttlSec)
  178. : db_(db), ttl_(std::chrono::seconds(ttlSec < 1 ? 1 : ttlSec)) {}
  179. int64_t get(const std::string& project) {
  180. const auto now = std::chrono::steady_clock::now();
  181. {
  182. std::lock_guard<std::mutex> lock(mu_);
  183. auto it = entries_.find(project);
  184. if (it != entries_.end() && now < it->second.expires) return it->second.valueMs;
  185. }
  186. int64_t valueMs = 0;
  187. bool read = false;
  188. try {
  189. const std::string coll = svapi::qualify("default", svapi::kSettingsCollection);
  190. if (auto doc = db_.client().get(coll, svapi::projectSettingsDocId(project))) {
  191. const svapi::ProjectSettings p = svapi::ProjectSettings::fromJson(*doc);
  192. valueMs = svapi::maxFunctionWallTimeMsFor(&p);
  193. }
  194. read = true;
  195. } catch (const std::exception& e) {
  196. // A failed read must not silently remove a project's cap, so the
  197. // last known value is kept and only its expiry is pushed out. With
  198. // nothing known yet the run falls back to the configured ceiling,
  199. // which still bounds it - the project maximum can only narrow.
  200. spdlog::warn("could not read the wall-time maximum for project {} - {}", project,
  201. e.what());
  202. }
  203. std::lock_guard<std::mutex> lock(mu_);
  204. auto it = entries_.find(project);
  205. if (!read && it != entries_.end()) {
  206. it->second.expires = now + ttl_;
  207. return it->second.valueMs;
  208. }
  209. entries_[project] = Entry{valueMs, now + ttl_};
  210. return valueMs;
  211. }
  212. private:
  213. struct Entry {
  214. int64_t valueMs = 0;
  215. std::chrono::steady_clock::time_point expires{};
  216. };
  217. svapi::DbGateway& db_;
  218. std::chrono::steady_clock::duration ttl_;
  219. std::mutex mu_;
  220. std::map<std::string, Entry> entries_;
  221. };
  222. /// RunService's registry seam, over the real FunctionRegistry.
  223. ///
  224. /// The whole adapter is this one translation, which is the point: the protocol
  225. /// layer never learns that a database exists, and this class holds no logic a
  226. /// test would want to reach.
  227. /// ctx.jobs, over the real queue.
  228. ///
  229. /// The authorization rule lives HERE rather than in the host context, because
  230. /// it needs the registry and the host context deliberately does not: a function
  231. /// may only enqueue something a caller could otherwise reach. Without this a
  232. /// script could schedule a disabled or invalid function, or name an id that
  233. /// does not exist and get a row nothing will ever drain.
  234. class QueueJobPort : public svapi::runner::JobPort {
  235. public:
  236. QueueJobPort(svapi::FunctionJobQueue& queue, svapi::FunctionRegistry& registry)
  237. : queue_(queue), registry_(registry) {}
  238. std::string enqueue(const std::string& project, const std::string& functionId,
  239. const nlohmann::json& trigger, uint64_t runAfterEpochSec, uint32_t depth,
  240. const std::string& jobId) override {
  241. // Same rule /fn/{project}/* applies: absent, disabled and invalid are
  242. // one answer to a caller, so a script learns nothing about which.
  243. const std::optional<svapi::FunctionRecord> target = registry_.get(project, functionId);
  244. if (!target || !target->enabled || !target->valid)
  245. throw svapi::ApiError(svapi::ErrCode::NotFound, "not_found",
  246. "no enabled function '" + functionId + "' in this project");
  247. svapi::FunctionJob job;
  248. job.jobId = jobId; // empty: the queue mints one
  249. job.project = project;
  250. job.functionId = functionId;
  251. job.trigger = "job";
  252. job.payload = trigger;
  253. job.depth = depth;
  254. job.runAfter = runAfterEpochSec;
  255. const std::string id = queue_.enqueue(job);
  256. if (id.empty())
  257. throw svapi::ApiError(svapi::ErrCode::Unavailable, "enqueue_failed",
  258. "the job could not be queued");
  259. return id;
  260. }
  261. bool cancel(const std::string& project, const std::string& jobId) override {
  262. const std::optional<svapi::FunctionJob> job = queue_.get(jobId);
  263. if (!job) return false;
  264. // Project checked against the ROW, not taken from the caller: a job id
  265. // is global, so a matching id in another tenant's queue must not be
  266. // cancellable from here.
  267. if (job->project != project) return false;
  268. // A claimed job may be executing this instant. Deleting the row would
  269. // not stop the run, and would leave the runner completing a job that no
  270. // longer exists.
  271. if (job->state == "claimed") return false;
  272. return queue_.remove(jobId);
  273. }
  274. private:
  275. svapi::FunctionJobQueue& queue_;
  276. svapi::FunctionRegistry& registry_;
  277. };
  278. class RegistryFunctionSource : public svapi::runner::FunctionSource {
  279. public:
  280. RegistryFunctionSource(svapi::FunctionRegistry& registry, ProjectWallMaxCache& budgets)
  281. : registry_(registry), budgets_(budgets) {}
  282. svapi::runner::FunctionView lookup(const std::string& project,
  283. const std::string& functionId) override {
  284. svapi::runner::FunctionView view;
  285. std::optional<svapi::FunctionRecord> row;
  286. try {
  287. row = registry_.get(project, functionId);
  288. } catch (const std::exception& e) {
  289. // A database failure is not a missing function, but the /run
  290. // contract has no third answer. Logged loudly so the two are
  291. // distinguishable in the journal even though the caller sees a 404.
  292. spdlog::error("registry read failed for {}:{} - {}", project, functionId, e.what());
  293. return view;
  294. }
  295. if (!row) return view;
  296. view.found = true;
  297. view.source = row->source;
  298. view.contentHash = row->contentHash;
  299. view.descriptor = row->descriptor;
  300. view.policy = row->policy;
  301. view.enabled = row->enabled;
  302. view.valid = row->valid;
  303. view.lastError = row->lastError;
  304. view.projectMaxWallTimeMs = budgets_.get(project);
  305. return view;
  306. }
  307. private:
  308. svapi::FunctionRegistry& registry_;
  309. ProjectWallMaxCache& budgets_;
  310. };
  311. /// RunService's ctx seam, over the real HostContext.
  312. class GatewayHostBindings : public svapi::runner::HostBindingsFactory {
  313. public:
  314. GatewayHostBindings(svapi::DbGateway& db, std::vector<std::string> environment,
  315. std::shared_ptr<svapi::runner::JobPort> jobs)
  316. : db_(db), environment_(std::move(environment)), jobs_(std::move(jobs)) {}
  317. bool create(const Request& request, svapi::runner::HostBindingsLease& out,
  318. std::string& error) override {
  319. svapi::runner::HostContextConfig cfg;
  320. cfg.project = request.project;
  321. cfg.functionId = request.functionId;
  322. cfg.policy = request.policy;
  323. cfg.trigger = request.trigger;
  324. cfg.deadlineMs = request.deadlineMs;
  325. // Only this project's secrets, from the runner's own environment
  326. // (systemd loads runner.env). The project is part of each variable's
  327. // name, because one runner serves every project and nothing else would
  328. // keep one tenant's key away from another's script.
  329. // Read per run, not cached: a cached secret is a rotated credential
  330. // that keeps working. A database failure here throws, which create()
  331. // turns into "host context unavailable" - better than a run that
  332. // silently proceeds without its credentials.
  333. cfg.jobs = jobs_;
  334. cfg.env = svapi::runner::functionEnvFor(request.project, environment_,
  335. svapi::ProjectSecretStore(db_).valuesFor(
  336. request.project));
  337. try {
  338. auto host = std::make_unique<svapi::runner::HostContext>(db_, std::move(cfg));
  339. svapi::runner::HostContext* raw = host.get();
  340. out.bindings = std::move(host);
  341. out.collectConsole = [raw] {
  342. std::vector<std::string> lines = raw->logLines();
  343. // Refused egress is reported as console output rather than
  344. // swallowed: a blocked fetch otherwise reaches the author
  345. // looking like an ordinary network error he will debug forever.
  346. for (const auto& blocked : raw->blockedEgress())
  347. lines.push_back("egress blocked: " + blocked);
  348. return lines;
  349. };
  350. return true;
  351. } catch (const std::exception& e) {
  352. error = std::string("host context unavailable: ") + e.what();
  353. return false;
  354. }
  355. }
  356. private:
  357. svapi::DbGateway& db_;
  358. std::vector<std::string> environment_;
  359. /// Null when the queue is not available, which ctx.jobs reports as
  360. /// `jobs_unavailable` rather than pretending to enqueue.
  361. std::shared_ptr<svapi::runner::JobPort> jobs_;
  362. };
  363. /// Parse a request body, or answer 400 with the same error envelope the rest of
  364. /// the protocol uses.
  365. bool readJsonBody(const httplib::Request& req, httplib::Response& res, nlohmann::json& out) {
  366. try {
  367. out = nlohmann::json::parse(req.body.empty() ? "{}" : req.body);
  368. } catch (const std::exception& e) {
  369. res.status = 400;
  370. res.set_content(nlohmann::json{{"ok", false},
  371. {"error", std::string("invalid JSON body: ") + e.what()}}
  372. .dump(),
  373. "application/json");
  374. return false;
  375. }
  376. return true;
  377. }
  378. void reply(httplib::Response& res, const svapi::runner::ProtocolResponse& out) {
  379. res.status = out.httpStatus;
  380. res.set_content(out.body.dump(), "application/json");
  381. }
  382. } // namespace
  383. int main(int argc, char** argv) {
  384. std::string configPath = "/etc/smartbotic-vectorapi/runner.json";
  385. for (int i = 1; i < argc; ++i) {
  386. if (std::strcmp(argv[i], "--config") == 0 && i + 1 < argc) configPath = argv[++i];
  387. else if (std::strcmp(argv[i], "--version") == 0 || std::strcmp(argv[i], "-v") == 0) {
  388. std::cout << "smartbotic-vectorapi-runner " << svapi::VERSION << " ("
  389. << svapi::GIT_COMMIT << ")\n";
  390. return 0;
  391. }
  392. }
  393. RunnerConfig cfg;
  394. try { cfg = RunnerConfig::load(configPath); }
  395. catch (const std::exception& e) { std::cerr << "config error: " << e.what() << "\n"; return 1; }
  396. spdlog::set_level(spdlog::level::from_str(cfg.logLevel));
  397. std::signal(SIGINT, onSignal); std::signal(SIGTERM, onSignal); std::signal(SIGPIPE, SIG_IGN);
  398. svapi::DbGateway db(cfg.dbAddress);
  399. spdlog::info("connecting to smartbotic-database at {}", cfg.dbAddress);
  400. for (int i = 0; i < 30 && !db.connect(); ++i) std::this_thread::sleep_for(std::chrono::seconds(1));
  401. if (!db.healthy()) { spdlog::error("database not reachable at {}", cfg.dbAddress); return 1; }
  402. svapi::FunctionRegistry registry(db);
  403. // Re-open every project's function collection. The database only surfaces a
  404. // collection through find()/list() once it has been opened in the current
  405. // process, so without this a restart leaves every function invisible even
  406. // though the rows survive - the same trap CollectionRegistry::bootstrap and
  407. // KeyStore::bootstrap exist for.
  408. {
  409. auto projects = db.listProjects();
  410. registry.bootstrap(projects);
  411. spdlog::info("opened the function registry for {} project(s)", projects.size());
  412. }
  413. svapi::runner::RunServiceOptions options;
  414. options.poolSize = cfg.poolSize;
  415. options.limits.memory_limit_bytes = cfg.memoryLimitBytes;
  416. options.httpWallCeilingMs = cfg.maxWallTimeMs;
  417. options.jobWallCeilingMs = cfg.maxJobWallTimeMs;
  418. // The engine's hard ceiling is raised to the highest of the two by
  419. // RunService itself; setting it from the HTTP ceiling here would cap every
  420. // job run at the HTTP budget.
  421. options.limits.wall_time_ms = cfg.maxWallTimeMs;
  422. options.limits.max_stack_bytes = cfg.maxStackBytes;
  423. options.defaultTimeoutMs = cfg.defaultWallTimeMs;
  424. options.bytecodeCacheEntries = cfg.bytecodeCacheEntries;
  425. options.version = svapi::VERSION;
  426. options.jobPoolSize = cfg.jobPoolSize;
  427. ProjectWallMaxCache projectBudgets(db, cfg.projectBudgetTtlSec);
  428. RegistryFunctionSource source(registry, projectBudgets);
  429. // The queue has to exist before the bindings that enqueue into it. ensure()
  430. // is idempotent and also re-opens the collection, without which find()
  431. // cannot see existing rows in this process.
  432. svapi::FunctionJobQueue jobQueue(db);
  433. jobQueue.ensure();
  434. auto jobPort = std::make_shared<QueueJobPort>(jobQueue, registry);
  435. // Snapshot the environment once: it does not change under a running
  436. // process, and re-reading it per run would be work for no gain.
  437. GatewayHostBindings host(db, svapi::runner::processEnvironment(), jobPort);
  438. svapi::runner::RunService service(source, options, &host);
  439. // The environment wins over the config file: a secret belongs in
  440. // runner.env, which systemd can keep at mode 0640, not in a conffile.
  441. std::string authToken = cfg.authToken;
  442. if (const char* fromEnv = std::getenv(svapi::runner::kRunnerTokenEnvVar);
  443. fromEnv != nullptr && *fromEnv != '\0') {
  444. authToken = fromEnv;
  445. }
  446. if (const auto refusal = svapi::runner::startupRefusal(cfg.httpBind, authToken)) {
  447. spdlog::critical("{}", *refusal);
  448. return 1;
  449. }
  450. if (authToken.empty()) {
  451. spdlog::warn("no runner token set; serving unauthenticated on {} - safe only"
  452. " because nothing off this host can reach it", cfg.httpBind);
  453. }
  454. httplib::Server server;
  455. server.set_read_timeout(cfg.readTimeoutSec, 0);
  456. server.set_write_timeout(cfg.readTimeoutSec, 0);
  457. // The pool already bounds concurrency; matching the thread count to it
  458. // keeps requests waiting in the accept queue instead of piling up threads
  459. // that all block on acquire().
  460. server.new_task_queue = [&cfg] {
  461. return new httplib::ThreadPool(static_cast<size_t>(cfg.poolSize) + 2);
  462. };
  463. // Authenticate everything, /health included. The health check is what
  464. // vectorapi uses to decide a runner is usable, and it reports the pool's
  465. // state - neither is something an unauthenticated caller should see.
  466. if (!authToken.empty()) {
  467. server.set_pre_routing_handler(
  468. [&authToken](const httplib::Request& req, httplib::Response& res) {
  469. const std::string presented =
  470. svapi::runner::bearerToken(req.get_header_value("Authorization"));
  471. if (svapi::runner::tokenMatches(authToken, presented))
  472. return httplib::Server::HandlerResponse::Unhandled;
  473. res.status = 401;
  474. res.set_content(R"({"error":{"code":"unauthorized","message":)"
  475. R"("missing or invalid runner token"}})",
  476. "application/json");
  477. return httplib::Server::HandlerResponse::Handled;
  478. });
  479. }
  480. server.Post("/run", [&service](const httplib::Request& req, httplib::Response& res) {
  481. nlohmann::json body;
  482. if (!readJsonBody(req, res, body)) return;
  483. // The kind of run is the caller's statement, not a guess: only the
  484. // caller knows whether a socket is waiting on this. Absent or
  485. // unrecognised means HTTP, the short budget, because that is the
  486. // mistake that costs a slow run rather than a pinned runtime. A
  487. // forged "job" buys nothing an attacker wants either, and this port is
  488. // token-authenticated and reachable only by vectorapi.
  489. const std::string kindName =
  490. body.is_object() && body.contains("kind") && body.at("kind").is_string()
  491. ? body.at("kind").get<std::string>()
  492. : std::string();
  493. reply(res, service.run(body, svapi::functions::parseRunKind(
  494. kindName, svapi::functions::RunKind::Http)));
  495. });
  496. server.Post("/validate", [&service](const httplib::Request& req, httplib::Response& res) {
  497. nlohmann::json body;
  498. if (!readJsonBody(req, res, body)) return;
  499. reply(res, service.validate(body));
  500. });
  501. server.Get("/health", [&service](const httplib::Request&, httplib::Response& res) {
  502. reply(res, service.health());
  503. });
  504. // An unexpected throw must not take the process down: one bad function
  505. // would otherwise stop every other tenant's.
  506. server.set_exception_handler([](const httplib::Request& req, httplib::Response& res,
  507. std::exception_ptr ep) {
  508. std::string what = "unknown error";
  509. try { std::rethrow_exception(ep); }
  510. catch (const std::exception& e) { what = e.what(); }
  511. catch (...) {}
  512. spdlog::error("unhandled exception on {} {}: {}", req.method, req.path, what);
  513. res.status = 500;
  514. res.set_content(nlohmann::json{{"ok", false}, {"error", what}}.dump(), "application/json");
  515. });
  516. // Bind BEFORE notifying, on this thread. listen() binds and serves in one
  517. // call, so notifying after merely spawning the thread would tell systemd we
  518. // are ready while the bind was still pending - or had already failed. Under
  519. // Type=notify that makes a runner that is about to exit look started, and
  520. // anything ordered after it would briefly see success.
  521. if (!server.bind_to_port(cfg.httpBind, cfg.httpPort)) {
  522. spdlog::critical("cannot bind {}:{} - address in use, or not permitted", cfg.httpBind,
  523. cfg.httpPort);
  524. return 1;
  525. }
  526. std::atomic<bool> serveFailed{false};
  527. std::thread http([&] {
  528. if (!server.listen_after_bind()) {
  529. spdlog::error("the listener stopped unexpectedly");
  530. serveFailed = true;
  531. g_running = false;
  532. }
  533. });
  534. spdlog::info("runner listening on {}:{} (pool {}, wall limit {}ms http / {}ms job)",
  535. cfg.httpBind, cfg.httpPort, cfg.poolSize, cfg.maxWallTimeMs,
  536. cfg.maxJobWallTimeMs);
  537. // Only matters for a job-kind run REQUESTED OVER HTTP: the socket would be
  538. // cut before the runner could report its own timeout, and the caller would
  539. // read a 503 instead of a 504. Queue-claimed jobs are unaffected, which is
  540. // why this is a warning and not a refusal to start.
  541. if (cfg.maxJobWallTimeMs >= static_cast<int64_t>(cfg.readTimeoutSec) * 1000) {
  542. spdlog::warn("the job wall ceiling ({}ms) is at or above this server's read timeout"
  543. " ({}s); a job-kind run posted to /run would have its socket cut before"
  544. " it could report a timeout", cfg.maxJobWallTimeMs, cfg.readTimeoutSec);
  545. }
  546. sd_notify(0, "READY=1");
  547. while (g_running) { sd_notify(0, "WATCHDOG=1"); std::this_thread::sleep_for(std::chrono::milliseconds(200)); }
  548. sd_notify(0, "STOPPING=1");
  549. server.stop();
  550. if (http.joinable()) http.join();
  551. // Non-zero on a listener failure, so Restart=on-failure actually fires. A
  552. // signal-driven shutdown is a clean exit.
  553. return serveFailed ? 1 : 0;
  554. }