main.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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_await.hpp"
  14. #include "net/mail_session.hpp"
  15. #include "db_gateway.hpp"
  16. #include "errors.hpp"
  17. #include "function_env.hpp"
  18. #include "function_jobs.hpp"
  19. #include "job_worker.hpp"
  20. #include "function_run_log.hpp"
  21. #include "project_secret_store.hpp"
  22. #include <mutex>
  23. #include <set>
  24. #include "function_record.hpp"
  25. #include "runner_auth.hpp"
  26. #include "function_registry.hpp"
  27. #include "project_settings.hpp"
  28. #include "run_service.hpp"
  29. #include "runner/host_context.hpp"
  30. #include "settings_store.hpp"
  31. #include <svapi/version.hpp>
  32. #include <httplib.h>
  33. #include <nlohmann/json.hpp>
  34. #include <spdlog/spdlog.h>
  35. #ifdef HAVE_SYSTEMD
  36. #include <systemd/sd-daemon.h>
  37. #else
  38. #define sd_notify(u, s) do {} while (0)
  39. #endif
  40. #include <atomic>
  41. #include <chrono>
  42. #include <csignal>
  43. #include <cstdlib>
  44. #include <cstring>
  45. #include <fstream>
  46. #include <iostream>
  47. #include <map>
  48. #include <memory>
  49. #include <mutex>
  50. #include <string>
  51. #include <thread>
  52. #include <vector>
  53. namespace {
  54. std::atomic<bool> g_running{true};
  55. void onSignal(int) { g_running = false; }
  56. /// The runner's own bootstrap config. Separate from svapi::Config because the
  57. /// two processes need different things: no web UI here, but the per-run
  58. /// ceilings and the pool size, which an operator sizes against the host.
  59. ///
  60. /// Same posture as the server's config though: minimal, and only what has to be
  61. /// known BEFORE the database is reachable. Anything that can hot-reload belongs
  62. /// in the database, not here.
  63. ///
  64. /// The `runtime` ceilings are deliberately BOOT-TIME ONLY, unlike every
  65. /// hot-reloading setting in the server. QuickJS fixes a runtime's memory limit
  66. /// when the runtime is created, so changing it live would mean draining and
  67. /// recreating every pooled runtime - real complexity for a knob that is a
  68. /// host-sizing decision, not something an operator tunes while watching a
  69. /// dashboard. Editing these means `systemctl restart
  70. /// smartbotic-vectorapi-runner`, which is cheap: vectorapi answers 503 for the
  71. /// moment the runner is down and nothing is stored unvalidated.
  72. ///
  73. /// The ONE value that has to stay in step with the server is
  74. /// `max_wall_time_ms`, the ceiling for HTTP-triggered runs: RunnerPool's
  75. /// readTimeoutSec must exceed it, or our read times out before the runner can
  76. /// report its own timeout and a caller gets a misleading 503 instead of a 504.
  77. /// The JOB ceiling is deliberately not bound by that number - a job run is
  78. /// claimed from the queue inside this process and no socket is waiting on it.
  79. struct RunnerConfig {
  80. std::string logLevel = "info";
  81. /// Loopback by default: the single-host deployment, where no token is
  82. /// needed because nothing else can reach the port. Binding anywhere else
  83. /// REQUIRES a token - see startupRefusal().
  84. std::string httpBind = "127.0.0.1";
  85. /// Shared secret vectorapi presents as `Authorization: Bearer`. Prefer
  86. /// SVAPI_RUNNER_TOKEN in runner.env, which can be mode 0640; this config
  87. /// file is a conffile and tends to be world-readable.
  88. std::string authToken;
  89. uint16_t httpPort = 8090;
  90. std::string dbAddress = "localhost:9004";
  91. size_t poolSize = 4;
  92. size_t memoryLimitBytes = 128u * 1024 * 1024;
  93. /// Ceiling for a run an HTTP request triggered. Kept at two seconds: a
  94. /// client is waiting on it, and vectorapi's read timeout is sized against
  95. /// this number.
  96. /// 15 s, not 2. A project cap can only NARROW this, so a 2000 ms ceiling
  97. /// made every per-project cap pointless: no project could raise its own
  98. /// limit at all, which is the opposite of what the cap is for. 15 s lets a
  99. /// voice tool that has to embed a query fit inside the ~20 s a caller
  100. /// typically waits.
  101. ///
  102. /// It is a CEILING, not a grant: a function gets it only by declaring
  103. /// timeoutMs, and defaultWallTimeMs decides what an undeclared one gets.
  104. int64_t maxWallTimeMs = 15000;
  105. /// Ceiling for a run the job queue triggered (cron, database events). Two
  106. /// minutes, because that is what the work is: an LLM call takes seconds to
  107. /// tens of seconds and an uncached embedding search has been measured at
  108. /// 26 s, and none of it has a client waiting on a socket.
  109. int64_t maxJobWallTimeMs = 120000;
  110. /// Applied when a descriptor declares no timeoutMs.
  111. ///
  112. /// Deliberately NOT "use the ceiling". Raising the HTTP ceiling to 15 s
  113. /// while this meant the ceiling would hand every existing function 15 s of
  114. /// runtime lease it never asked for, and a pool of 2 would be held by two
  115. /// slow requests. An undeclared function keeps 2 s; one that needs longer
  116. /// says so, and an admin caps the project.
  117. int64_t defaultWallTimeMs = 2000;
  118. /// How long a project's wall-time maximum is cached before it is re-read.
  119. /// Not subscribed to, unlike the server's settings: one read per project
  120. /// per interval is nothing, and a per-run read would put two round trips on
  121. /// the hot path for a number that changes by hand.
  122. size_t maxStackBytes = 512u * 1024;
  123. size_t bytecodeCacheEntries = 64;
  124. /// Runtimes reserved for job runs. A separate lane, so a cron job holding a
  125. /// runtime for its whole 120 s ceiling cannot take the one an interactive
  126. /// route is about to need. Costs memory: the per-run ceiling is per
  127. /// runtime, so this adds to poolSize rather than dividing it.
  128. size_t jobPoolSize = 4;
  129. /// Claiming queued work is OFF by default: a runner upgrade must not start
  130. /// draining a queue in a deployment whose server has no scheduler.
  131. bool jobsEnabled = false;
  132. uint32_t jobWorkers = 0; ///< 0 = jobPoolSize - 1, never below 1
  133. uint32_t jobMaxAttempts = 5;
  134. uint32_t staleClaimSec = 300;
  135. /// Runs kept per function by the JOB worker's log writes. Should match the
  136. /// server's functions.runs_kept, or the two trim one log to two depths.
  137. uint32_t functionRunsKept = 50;
  138. /// How long a single /run or /validate request may occupy a server thread.
  139. /// Above the wall-time ceiling on purpose: a run that is about to be killed
  140. /// should report its own timeout rather than have the socket cut first.
  141. int readTimeoutSec = 30;
  142. static RunnerConfig fromJson(const nlohmann::json& j) {
  143. RunnerConfig c;
  144. c.logLevel = j.value("log_level", c.logLevel);
  145. if (j.contains("http") && j["http"].is_object()) {
  146. const auto& h = j["http"];
  147. c.httpBind = h.value("bind_address", c.httpBind);
  148. c.httpPort = h.value("port", c.httpPort);
  149. c.readTimeoutSec = h.value("read_timeout_sec", c.readTimeoutSec);
  150. c.authToken = h.value("auth_token", c.authToken);
  151. }
  152. if (j.contains("jobs") && j["jobs"].is_object()) {
  153. const auto& jb = j["jobs"];
  154. c.jobsEnabled = jb.value("enabled", c.jobsEnabled);
  155. c.jobWorkers = jb.value("workers", c.jobWorkers);
  156. c.jobMaxAttempts = jb.value("max_attempts", c.jobMaxAttempts);
  157. c.staleClaimSec = jb.value("stale_claim_sec", c.staleClaimSec);
  158. }
  159. if (j.contains("function_runs_kept"))
  160. c.functionRunsKept = j.value("function_runs_kept", c.functionRunsKept);
  161. if (j.contains("database") && j["database"].is_object())
  162. c.dbAddress = j["database"].value("address", c.dbAddress);
  163. if (j.contains("runtime") && j["runtime"].is_object()) {
  164. const auto& r = j["runtime"];
  165. c.poolSize = r.value("pool_size", c.poolSize);
  166. c.memoryLimitBytes = r.value("memory_limit_bytes", c.memoryLimitBytes);
  167. // `max_wall_time_ms` keeps its old name and its old meaning - the
  168. // HTTP ceiling - so an existing conffile is not silently
  169. // reinterpreted. `max_http_wall_time_ms` is the clearer spelling
  170. // and wins when both are present.
  171. c.maxWallTimeMs = r.value("max_wall_time_ms", c.maxWallTimeMs);
  172. c.maxWallTimeMs = r.value("max_http_wall_time_ms", c.maxWallTimeMs);
  173. c.maxJobWallTimeMs = r.value("max_job_wall_time_ms", c.maxJobWallTimeMs);
  174. c.defaultWallTimeMs = r.value("default_wall_time_ms", c.defaultWallTimeMs);
  175. c.maxStackBytes = r.value("max_stack_bytes", c.maxStackBytes);
  176. c.bytecodeCacheEntries = r.value("bytecode_cache_entries", c.bytecodeCacheEntries);
  177. c.jobPoolSize = r.value("job_pool_size", c.jobPoolSize);
  178. }
  179. return c;
  180. }
  181. static RunnerConfig load(const std::string& path) {
  182. std::ifstream f(path);
  183. if (!f) throw std::runtime_error("cannot open config file: " + path);
  184. nlohmann::json j;
  185. f >> j;
  186. return fromJson(j);
  187. }
  188. };
  189. /// One project's admin-set wall-time maximums, per run kind.
  190. ///
  191. /// Backed by SettingsStore, which SUBSCRIBES: a change to a project's cap
  192. /// reaches the next run immediately instead of after a TTL. This used to be a
  193. /// hand-rolled cache polling the settings document every
  194. /// `project_budget_ttl_sec` seconds, which meant clearing a cap appeared not to
  195. /// work for up to 15 seconds and produced a bug report that cost real time to
  196. /// run down. The server already hot-reloads the same document off the same
  197. /// stream; there was no reason for the runner to be the one component guessing.
  198. ///
  199. /// reloadAll() rather than bootstrap(): bootstrap WRITES, seeding the settings
  200. /// document, and a runner must never author configuration it only reads.
  201. /// The precedence itself stays in the one pure maxFunctionWallTimeMsFor().
  202. class ProjectWallMax {
  203. public:
  204. explicit ProjectWallMax(svapi::DbGateway& db)
  205. : store_(db, svapi::kSettingsCollection, "current") {
  206. try {
  207. store_.reloadAll();
  208. } catch (const std::exception& e) {
  209. // Start anyway. An unreadable settings document means no project
  210. // cap is known, and a run then falls back to the configured
  211. // ceiling, which still bounds it - a project maximum can only
  212. // narrow. Refusing to start would be a worse trade.
  213. spdlog::warn("could not load project settings at startup - {}", e.what());
  214. }
  215. try {
  216. store_.startWatch();
  217. } catch (const std::exception& e) {
  218. spdlog::warn("could not subscribe to project settings - {}", e.what());
  219. }
  220. }
  221. int64_t get(const std::string& project, svapi::functions::RunKind kind) const {
  222. const std::shared_ptr<const svapi::ProjectSettings> p = store_.projectSnapshot(project);
  223. return svapi::maxFunctionWallTimeMsFor(p.get(), kind);
  224. }
  225. private:
  226. mutable svapi::SettingsStore store_;
  227. };
  228. /// RunService's registry seam, over the real FunctionRegistry.
  229. ///
  230. /// The whole adapter is this one translation, which is the point: the protocol
  231. /// layer never learns that a database exists, and this class holds no logic a
  232. /// test would want to reach.
  233. /// The job worker's queue port, over the real queue.
  234. ///
  235. /// Translates FunctionJob to the worker's JobView and back. The worker never
  236. /// sees the database, which is what keeps its decisions testable; `raw` carries
  237. /// the stored row so completing needs no state kept here.
  238. ///
  239. /// Nothing in here may throw: the worker's contract is that a transient read
  240. /// reports "nothing to do" rather than killing the loop, because a loop that a
  241. /// database blip can kill is a loop that stops doing cron.
  242. class WorkerQueuePort : public svapi::runner::JobQueuePort {
  243. public:
  244. explicit WorkerQueuePort(svapi::FunctionJobQueue& queue) : queue_(queue) {}
  245. std::optional<svapi::runner::JobView> claimNext(const std::string& runnerId) override {
  246. try {
  247. std::optional<svapi::FunctionJob> job = queue_.claimNext(runnerId);
  248. if (!job) return std::nullopt;
  249. svapi::runner::JobView v;
  250. v.jobId = job->jobId;
  251. v.project = job->project;
  252. v.functionId = job->functionId;
  253. v.trigger = job->trigger;
  254. v.payload = job->payload;
  255. // claimNext increments on claim, so this already counts the attempt
  256. // about to happen; 0 would mean the queue did not count it.
  257. v.attempts = job->attempts == 0 ? 1 : job->attempts;
  258. v.raw = job->toJson();
  259. v.raw["version"] = job->version; // toJson does not carry it
  260. return v;
  261. } catch (const std::exception& e) {
  262. spdlog::warn("claim failed: {}", e.what());
  263. return std::nullopt;
  264. }
  265. }
  266. bool complete(const svapi::runner::JobView& v, bool ok, const std::string& error,
  267. uint32_t retryAfterSec) override {
  268. try {
  269. svapi::FunctionJob job = svapi::FunctionJob::fromJson(v.raw);
  270. job.jobId = v.jobId; // the body never carries `id`
  271. job.version = v.raw.value("version", uint64_t{0});
  272. return queue_.complete(job, ok, error, retryAfterSec);
  273. } catch (const std::exception& e) {
  274. spdlog::warn("completing job {} failed: {}", v.jobId, e.what());
  275. return false;
  276. }
  277. }
  278. uint32_t reclaimStale(uint32_t timeoutSec, uint32_t maxAttempts) override {
  279. try {
  280. return queue_.reclaimStale(timeoutSec, maxAttempts);
  281. } catch (const std::exception& e) {
  282. spdlog::warn("reclaim failed: {}", e.what());
  283. return 0;
  284. }
  285. }
  286. private:
  287. svapi::FunctionJobQueue& queue_;
  288. };
  289. /// The job worker's run-log port. ensure() is remembered per project because
  290. /// the worker is multi-threaded, and a run log write must never change the
  291. /// outcome of the job it is recording.
  292. class WorkerRunLogPort : public svapi::runner::RunLogPort {
  293. public:
  294. explicit WorkerRunLogPort(svapi::FunctionRunLogStore& store) : store_(store) {}
  295. void record(const std::string& project, const svapi::runner::JobRunRecord& entry) override {
  296. try {
  297. {
  298. std::lock_guard<std::mutex> lock(mu_);
  299. if (ensured_.insert(project).second) store_.ensure(project);
  300. }
  301. svapi::FunctionRunLog row;
  302. row.runId = entry.runId;
  303. row.functionId = entry.functionId;
  304. row.trigger = entry.trigger;
  305. row.ok = entry.ok;
  306. row.status = entry.status;
  307. row.durationMs = entry.durationMs;
  308. row.error = entry.error;
  309. row.console = entry.console;
  310. row.headers = entry.headers;
  311. row.startedAt = entry.startedAt;
  312. store_.append(project, row);
  313. } catch (const std::exception& e) {
  314. spdlog::warn("run log write failed for {}/{}: {}", project, entry.functionId, e.what());
  315. }
  316. }
  317. private:
  318. svapi::FunctionRunLogStore& store_;
  319. std::mutex mu_;
  320. std::set<std::string> ensured_;
  321. };
  322. /// ctx.jobs, over the real queue.
  323. ///
  324. /// The authorization rule lives HERE rather than in the host context, because
  325. /// it needs the registry and the host context deliberately does not: a function
  326. /// may only enqueue something a caller could otherwise reach. Without this a
  327. /// script could schedule a disabled or invalid function, or name an id that
  328. /// does not exist and get a row nothing will ever drain.
  329. class QueueJobPort : public svapi::runner::JobPort {
  330. public:
  331. QueueJobPort(svapi::FunctionJobQueue& queue, svapi::FunctionRegistry& registry)
  332. : queue_(queue), registry_(registry) {}
  333. std::string enqueue(const std::string& project, const std::string& functionId,
  334. const nlohmann::json& trigger, uint64_t runAfterEpochSec, uint32_t depth,
  335. const std::string& jobId) override {
  336. // Same rule /fn/{project}/* applies: absent, disabled and invalid are
  337. // one answer to a caller, so a script learns nothing about which.
  338. const std::optional<svapi::FunctionRecord> target = registry_.get(project, functionId);
  339. if (!target || !target->enabled || !target->valid)
  340. throw svapi::ApiError(svapi::ErrCode::NotFound, "not_found",
  341. "no enabled function '" + functionId + "' in this project");
  342. svapi::FunctionJob job;
  343. job.jobId = jobId; // empty: the queue mints one
  344. job.project = project;
  345. job.functionId = functionId;
  346. job.trigger = "job";
  347. job.payload = trigger;
  348. job.depth = depth;
  349. job.runAfter = runAfterEpochSec;
  350. const std::string id = queue_.enqueue(job);
  351. if (id.empty())
  352. throw svapi::ApiError(svapi::ErrCode::Unavailable, "enqueue_failed",
  353. "the job could not be queued");
  354. return id;
  355. }
  356. bool cancel(const std::string& project, const std::string& jobId) override {
  357. const std::optional<svapi::FunctionJob> job = queue_.get(jobId);
  358. if (!job) return false;
  359. // Project checked against the ROW, not taken from the caller: a job id
  360. // is global, so a matching id in another tenant's queue must not be
  361. // cancellable from here.
  362. if (job->project != project) return false;
  363. // A claimed job may be executing this instant. Deleting the row would
  364. // not stop the run, and would leave the runner completing a job that no
  365. // longer exists.
  366. if (job->state == "claimed") return false;
  367. return queue_.remove(jobId);
  368. }
  369. private:
  370. svapi::FunctionJobQueue& queue_;
  371. svapi::FunctionRegistry& registry_;
  372. };
  373. class RegistryFunctionSource : public svapi::runner::FunctionSource {
  374. public:
  375. RegistryFunctionSource(svapi::FunctionRegistry& registry, ProjectWallMax& budgets)
  376. : registry_(registry), budgets_(budgets) {}
  377. svapi::runner::FunctionView lookup(const std::string& project,
  378. const std::string& functionId) override {
  379. svapi::runner::FunctionView view;
  380. std::optional<svapi::FunctionRecord> row;
  381. try {
  382. row = registry_.get(project, functionId);
  383. } catch (const std::exception& e) {
  384. // A database failure is not a missing function, but the /run
  385. // contract has no third answer. Logged loudly so the two are
  386. // distinguishable in the journal even though the caller sees a 404.
  387. spdlog::error("registry read failed for {}:{} - {}", project, functionId, e.what());
  388. return view;
  389. }
  390. if (!row) return view;
  391. view.found = true;
  392. view.source = row->source;
  393. view.contentHash = row->contentHash;
  394. view.descriptor = row->descriptor;
  395. view.policy = row->policy;
  396. view.enabled = row->enabled;
  397. view.valid = row->valid;
  398. view.lastError = row->lastError;
  399. view.projectMaxWallTimeHttpMs = budgets_.get(project, svapi::functions::RunKind::Http);
  400. view.projectMaxWallTimeJobMs = budgets_.get(project, svapi::functions::RunKind::Job);
  401. return view;
  402. }
  403. private:
  404. svapi::FunctionRegistry& registry_;
  405. ProjectWallMax& budgets_;
  406. };
  407. /// RunService's ctx seam, over the real HostContext.
  408. class GatewayHostBindings : public svapi::runner::HostBindingsFactory {
  409. public:
  410. GatewayHostBindings(svapi::DbGateway& db, std::vector<std::string> environment,
  411. std::shared_ptr<svapi::runner::JobPort> jobs)
  412. : db_(db), environment_(std::move(environment)), jobs_(std::move(jobs)) {}
  413. bool create(const Request& request, svapi::runner::HostBindingsLease& out,
  414. std::string& error) override {
  415. svapi::runner::HostContextConfig cfg;
  416. cfg.project = request.project;
  417. cfg.functionId = request.functionId;
  418. cfg.policy = request.policy;
  419. cfg.trigger = request.trigger;
  420. cfg.deadlineMs = request.deadlineMs;
  421. // Only this project's secrets, from the runner's own environment
  422. // (systemd loads runner.env). The project is part of each variable's
  423. // name, because one runner serves every project and nothing else would
  424. // keep one tenant's key away from another's script.
  425. // Read per run, not cached: a cached secret is a rotated credential
  426. // that keeps working. A database failure here throws, which create()
  427. // turns into "host context unavailable" - better than a run that
  428. // silently proceeds without its credentials.
  429. cfg.jobs = jobs_;
  430. cfg.env = svapi::runner::functionEnvFor(request.project, environment_,
  431. svapi::ProjectSecretStore(db_).valuesFor(
  432. request.project));
  433. try {
  434. auto host = std::make_unique<svapi::runner::HostContext>(db_, std::move(cfg));
  435. svapi::runner::HostContext* raw = host.get();
  436. out.bindings = std::move(host);
  437. out.collectConsole = [raw] {
  438. std::vector<std::string> lines = raw->logLines();
  439. // Refused egress is reported as console output rather than
  440. // swallowed: a blocked fetch otherwise reaches the author
  441. // looking like an ordinary network error he will debug forever.
  442. for (const auto& blocked : raw->blockedEgress())
  443. lines.push_back("egress blocked: " + blocked);
  444. return lines;
  445. };
  446. return true;
  447. } catch (const std::exception& e) {
  448. error = std::string("host context unavailable: ") + e.what();
  449. return false;
  450. }
  451. }
  452. private:
  453. svapi::DbGateway& db_;
  454. std::vector<std::string> environment_;
  455. /// Null when the queue is not available, which ctx.jobs reports as
  456. /// `jobs_unavailable` rather than pretending to enqueue.
  457. std::shared_ptr<svapi::runner::JobPort> jobs_;
  458. };
  459. /// Parse a request body, or answer 400 with the same error envelope the rest of
  460. /// the protocol uses.
  461. bool readJsonBody(const httplib::Request& req, httplib::Response& res, nlohmann::json& out) {
  462. try {
  463. out = nlohmann::json::parse(req.body.empty() ? "{}" : req.body);
  464. } catch (const std::exception& e) {
  465. res.status = 400;
  466. res.set_content(nlohmann::json{{"ok", false},
  467. {"error", std::string("invalid JSON body: ") + e.what()}}
  468. .dump(),
  469. "application/json");
  470. return false;
  471. }
  472. return true;
  473. }
  474. void reply(httplib::Response& res, const svapi::runner::ProtocolResponse& out) {
  475. res.status = out.httpStatus;
  476. res.set_content(out.body.dump(), "application/json");
  477. }
  478. } // namespace
  479. int main(int argc, char** argv) {
  480. std::string configPath = "/etc/smartbotic-vectorapi/runner.json";
  481. for (int i = 1; i < argc; ++i) {
  482. if (std::strcmp(argv[i], "--config") == 0 && i + 1 < argc) configPath = argv[++i];
  483. else if (std::strcmp(argv[i], "--version") == 0 || std::strcmp(argv[i], "-v") == 0) {
  484. std::cout << "smartbotic-vectorapi-runner " << svapi::VERSION << " ("
  485. << svapi::GIT_COMMIT << ")\n";
  486. return 0;
  487. }
  488. }
  489. RunnerConfig cfg;
  490. try { cfg = RunnerConfig::load(configPath); }
  491. catch (const std::exception& e) { std::cerr << "config error: " << e.what() << "\n"; return 1; }
  492. spdlog::set_level(spdlog::level::from_str(cfg.logLevel));
  493. std::signal(SIGINT, onSignal); std::signal(SIGTERM, onSignal); std::signal(SIGPIPE, SIG_IGN);
  494. // Mail, before ANY worker thread exists. curl_global_init is not
  495. // thread-safe and curl's own lazy first-use initialisation from two pool
  496. // threads at once is a real race, not a theoretical one. It also verifies
  497. // libcurl was built thread-safe and REFUSES TO START otherwise, in the
  498. // same spirit as the runner refusing to start with no token on a
  499. // non-loopback bind: a curl without CURL_VERSION_THREADSAFE cannot be
  500. // driven safely from this pool, and finding that out from a crash under
  501. // load costs far more than failing here.
  502. if (const std::string why = svapi::runner::net::mailGlobalInit(); !why.empty()) {
  503. spdlog::error("refusing to start: {}", why);
  504. return 1;
  505. }
  506. svapi::DbGateway db(cfg.dbAddress);
  507. spdlog::info("connecting to smartbotic-database at {}", cfg.dbAddress);
  508. // Bounded by WALL TIME, not by an attempt count - see db_await.hpp. 60 s
  509. // sits comfortably inside systemd's 90 s TimeoutStartSec, so an unreachable
  510. // database produces a clean diagnostic and exit 1 rather than being killed
  511. // mid-loop with a misleading "start operation timed out".
  512. svapi::awaitConnectable([&db] { return db.connect(); },
  513. [] { return std::chrono::steady_clock::now(); },
  514. [](std::chrono::milliseconds d) { std::this_thread::sleep_for(d); },
  515. std::chrono::seconds(60), std::chrono::seconds(1));
  516. if (!db.healthy()) { spdlog::error("database not reachable at {}", cfg.dbAddress); return 1; }
  517. svapi::FunctionRegistry registry(db);
  518. // Re-open every project's function collection. The database only surfaces a
  519. // collection through find()/list() once it has been opened in the current
  520. // process, so without this a restart leaves every function invisible even
  521. // though the rows survive - the same trap CollectionRegistry::bootstrap and
  522. // KeyStore::bootstrap exist for.
  523. {
  524. auto projects = db.listProjects();
  525. registry.bootstrap(projects);
  526. spdlog::info("opened the function registry for {} project(s)", projects.size());
  527. }
  528. svapi::runner::RunServiceOptions options;
  529. options.poolSize = cfg.poolSize;
  530. options.limits.memory_limit_bytes = cfg.memoryLimitBytes;
  531. options.httpWallCeilingMs = cfg.maxWallTimeMs;
  532. options.jobWallCeilingMs = cfg.maxJobWallTimeMs;
  533. // The engine's hard ceiling is raised to the highest of the two by
  534. // RunService itself; setting it from the HTTP ceiling here would cap every
  535. // job run at the HTTP budget.
  536. options.limits.wall_time_ms = cfg.maxWallTimeMs;
  537. options.limits.max_stack_bytes = cfg.maxStackBytes;
  538. options.defaultTimeoutMs = cfg.defaultWallTimeMs;
  539. options.bytecodeCacheEntries = cfg.bytecodeCacheEntries;
  540. options.version = svapi::VERSION;
  541. options.jobPoolSize = cfg.jobPoolSize;
  542. ProjectWallMax projectBudgets(db);
  543. RegistryFunctionSource source(registry, projectBudgets);
  544. // The queue has to exist before the bindings that enqueue into it. ensure()
  545. // is idempotent and also re-opens the collection, without which find()
  546. // cannot see existing rows in this process.
  547. svapi::FunctionJobQueue jobQueue(db);
  548. jobQueue.ensure();
  549. auto jobPort = std::make_shared<QueueJobPort>(jobQueue, registry);
  550. // Snapshot the environment once: it does not change under a running
  551. // process, and re-reading it per run would be work for no gain.
  552. GatewayHostBindings host(db, svapi::runner::processEnvironment(), jobPort);
  553. svapi::runner::RunService service(source, options, &host);
  554. // THE thing that drains the queue. Without it the scheduler enqueues a job,
  555. // nothing ever claims it, and single-flight then correctly refuses to stack
  556. // a second copy behind the stuck one - so cron produces exactly zero runs
  557. // and looks like a scheduler that never fires. 0.5.0 shipped without this.
  558. //
  559. // Off unless jobs.enabled, so a runner upgrade never starts draining a
  560. // queue in a deployment whose server has no scheduler.
  561. svapi::FunctionRunLogStore jobRunLog(db, cfg.functionRunsKept);
  562. WorkerQueuePort workerQueue(jobQueue);
  563. WorkerRunLogPort workerLog(jobRunLog);
  564. std::unique_ptr<svapi::runner::JobWorker> worker;
  565. if (cfg.jobsEnabled) {
  566. svapi::runner::JobWorkerOptions wo;
  567. wo.poolSize = cfg.jobPoolSize > 0 ? cfg.jobPoolSize : cfg.poolSize;
  568. wo.workers = cfg.jobWorkers;
  569. wo.maxAttempts = cfg.jobMaxAttempts;
  570. wo.staleClaimSec = cfg.staleClaimSec;
  571. worker = std::make_unique<svapi::runner::JobWorker>(service, workerQueue, workerLog, wo);
  572. }
  573. // The environment wins over the config file: a secret belongs in
  574. // runner.env, which systemd can keep at mode 0640, not in a conffile.
  575. std::string authToken = cfg.authToken;
  576. if (const char* fromEnv = std::getenv(svapi::runner::kRunnerTokenEnvVar);
  577. fromEnv != nullptr && *fromEnv != '\0') {
  578. authToken = fromEnv;
  579. }
  580. if (const auto refusal = svapi::runner::startupRefusal(cfg.httpBind, authToken)) {
  581. spdlog::critical("{}", *refusal);
  582. return 1;
  583. }
  584. if (authToken.empty()) {
  585. spdlog::warn("no runner token set; serving unauthenticated on {} - safe only"
  586. " because nothing off this host can reach it", cfg.httpBind);
  587. }
  588. httplib::Server server;
  589. server.set_read_timeout(cfg.readTimeoutSec, 0);
  590. server.set_write_timeout(cfg.readTimeoutSec, 0);
  591. // The pool already bounds concurrency; matching the thread count to it
  592. // keeps requests waiting in the accept queue instead of piling up threads
  593. // that all block on acquire().
  594. server.new_task_queue = [&cfg] {
  595. return new httplib::ThreadPool(static_cast<size_t>(cfg.poolSize) + 2);
  596. };
  597. // Authenticate everything, /health included. The health check is what
  598. // vectorapi uses to decide a runner is usable, and it reports the pool's
  599. // state - neither is something an unauthenticated caller should see.
  600. if (!authToken.empty()) {
  601. server.set_pre_routing_handler(
  602. [&authToken](const httplib::Request& req, httplib::Response& res) {
  603. const std::string presented =
  604. svapi::runner::bearerToken(req.get_header_value("Authorization"));
  605. if (svapi::runner::tokenMatches(authToken, presented))
  606. return httplib::Server::HandlerResponse::Unhandled;
  607. res.status = 401;
  608. res.set_content(R"({"error":{"code":"unauthorized","message":)"
  609. R"("missing or invalid runner token"}})",
  610. "application/json");
  611. return httplib::Server::HandlerResponse::Handled;
  612. });
  613. }
  614. server.Post("/run", [&service](const httplib::Request& req, httplib::Response& res) {
  615. nlohmann::json body;
  616. if (!readJsonBody(req, res, body)) return;
  617. // The kind of run is the caller's statement, not a guess: only the
  618. // caller knows whether a socket is waiting on this. Absent or
  619. // unrecognised means HTTP, the short budget, because that is the
  620. // mistake that costs a slow run rather than a pinned runtime. A
  621. // forged "job" buys nothing an attacker wants either, and this port is
  622. // token-authenticated and reachable only by vectorapi.
  623. const std::string kindName =
  624. body.is_object() && body.contains("kind") && body.at("kind").is_string()
  625. ? body.at("kind").get<std::string>()
  626. : std::string();
  627. reply(res, service.run(body, svapi::functions::parseRunKind(
  628. kindName, svapi::functions::RunKind::Http)));
  629. });
  630. server.Post("/validate", [&service](const httplib::Request& req, httplib::Response& res) {
  631. nlohmann::json body;
  632. if (!readJsonBody(req, res, body)) return;
  633. reply(res, service.validate(body));
  634. });
  635. server.Get("/health", [&service, &worker, &cfg](const httplib::Request&,
  636. httplib::Response& res) {
  637. svapi::runner::ProtocolResponse out = service.health();
  638. // The job worker's existence is REPORTED, not inferred from an empty
  639. // log. 0.5.0 shipped without a worker at all, and the only symptom was
  640. // a quiet log that read exactly like an idle one - so cron enqueued and
  641. // nothing ran, and a health check that said "ok" was telling the truth
  642. // about everything it knew to look at. Anything a deployment can forget
  643. // to wire has to be visible here.
  644. if (out.body.is_object()) {
  645. if (worker) {
  646. const svapi::runner::JobWorker::Stats s = worker->stats();
  647. out.body["jobs"] = {{"running", true},
  648. {"workers", cfg.jobWorkers},
  649. {"claimed", s.claimed},
  650. {"succeeded", s.succeeded},
  651. {"retried", s.retried},
  652. {"failed", s.failed},
  653. {"complete_failures", s.completeFailures},
  654. {"reclaimed", s.reclaimed}};
  655. } else {
  656. // Said plainly, because this state means queued cron and
  657. // database events will never run on this runner.
  658. out.body["jobs"] = {{"running", false},
  659. {"reason", "jobs.enabled is false in runner.json"}};
  660. }
  661. }
  662. reply(res, out);
  663. });
  664. // An unexpected throw must not take the process down: one bad function
  665. // would otherwise stop every other tenant's.
  666. server.set_exception_handler([](const httplib::Request& req, httplib::Response& res,
  667. std::exception_ptr ep) {
  668. std::string what = "unknown error";
  669. try { std::rethrow_exception(ep); }
  670. catch (const std::exception& e) { what = e.what(); }
  671. catch (...) {}
  672. spdlog::error("unhandled exception on {} {}: {}", req.method, req.path, what);
  673. res.status = 500;
  674. res.set_content(nlohmann::json{{"ok", false}, {"error", what}}.dump(), "application/json");
  675. });
  676. // Bind BEFORE notifying, on this thread. listen() binds and serves in one
  677. // call, so notifying after merely spawning the thread would tell systemd we
  678. // are ready while the bind was still pending - or had already failed. Under
  679. // Type=notify that makes a runner that is about to exit look started, and
  680. // anything ordered after it would briefly see success.
  681. if (!server.bind_to_port(cfg.httpBind, cfg.httpPort)) {
  682. spdlog::critical("cannot bind {}:{} - address in use, or not permitted", cfg.httpBind,
  683. cfg.httpPort);
  684. return 1;
  685. }
  686. std::atomic<bool> serveFailed{false};
  687. std::thread http([&] {
  688. if (!server.listen_after_bind()) {
  689. spdlog::error("the listener stopped unexpectedly");
  690. serveFailed = true;
  691. g_running = false;
  692. }
  693. });
  694. spdlog::info("runner listening on {}:{} (pool {}, wall limit {}ms http / {}ms job)",
  695. cfg.httpBind, cfg.httpPort, cfg.poolSize, cfg.maxWallTimeMs,
  696. cfg.maxJobWallTimeMs);
  697. // Only matters for a job-kind run REQUESTED OVER HTTP: the socket would be
  698. // cut before the runner could report its own timeout, and the caller would
  699. // read a 503 instead of a 504. Queue-claimed jobs are unaffected, which is
  700. // why this is a warning and not a refusal to start.
  701. if (cfg.maxJobWallTimeMs >= static_cast<int64_t>(cfg.readTimeoutSec) * 1000) {
  702. spdlog::warn("the job wall ceiling ({}ms) is at or above this server's read timeout"
  703. " ({}s); a job-kind run posted to /run would have its socket cut before"
  704. " it could report a timeout", cfg.maxJobWallTimeMs, cfg.readTimeoutSec);
  705. }
  706. // Started after READY so /health answers before any job runs, and a
  707. // deployment that is coming up does not begin side-effecting work before it
  708. // is reachable.
  709. if (worker) {
  710. worker->start();
  711. spdlog::info("job worker started (lane {}, workers {}, stale claim {}s)", cfg.jobPoolSize,
  712. cfg.jobWorkers, cfg.staleClaimSec);
  713. } else {
  714. spdlog::info("job worker disabled (jobs.enabled false) - queued cron and database "
  715. "events will NOT run on this runner");
  716. }
  717. sd_notify(0, "READY=1");
  718. while (g_running) { sd_notify(0, "WATCHDOG=1"); std::this_thread::sleep_for(std::chrono::milliseconds(200)); }
  719. sd_notify(0, "STOPPING=1");
  720. // Stop claiming while the database is still up, and before the service it
  721. // runs jobs through goes away. A job in flight runs to completion.
  722. if (worker) worker->stop();
  723. server.stop();
  724. if (http.joinable()) http.join();
  725. // Paired with mailGlobalInit, and deliberately AFTER the listener and the
  726. // job worker have stopped: curl_global_cleanup while a worker could still
  727. // be inside a mail call is a use-after-free.
  728. svapi::runner::net::mailGlobalCleanup();
  729. // Non-zero on a listener failure, so Restart=on-failure actually fires. A
  730. // signal-driven shutdown is a clean exit.
  731. return serveFailed ? 1 : 0;
  732. }