| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309 |
- #include "runner_client.hpp"
- #include <httplib.h>
- #include <spdlog/spdlog.h>
- #include <algorithm>
- namespace svapi {
- namespace {
- // Why no applyOutboundDefaults() here: that helper exists for calls that leave
- // our trust boundary (embedding providers, captcha verification), where a
- // provider must see our User-Agent and must not be able to bounce a
- // credentialed request elsewhere. A runner is a first-party process from this
- // repo, addressed by a configured host:port and speaking a private protocol -
- // not a provider. Treating it as one would also drag vectorapi_core's whole
- // dependency set into a client that deliberately needs nothing but httplib,
- // which is what keeps this file testable on a host with no database client. The
- // two properties of that helper that DO matter internally are set explicitly
- // below: redirects off, and TLS verification on for an https endpoint.
- template <class Opts>
- void configureClient(httplib::Client& cli, const Opts& o) {
- cli.set_connection_timeout(o.connectTimeoutSec, 0);
- cli.set_read_timeout(o.readTimeoutSec, 0);
- cli.set_write_timeout(o.readTimeoutSec, 0);
- // A runner has no business redirecting us anywhere, and following one would
- // turn a compromised or misconfigured runner into an SSRF primitive.
- cli.set_follow_location(false);
- cli.set_keep_alive(true);
- // The runner authenticates every route, /health included. Empty only for a
- // loopback runner, which is the one case it serves unauthenticated.
- if (!o.authToken.empty())
- cli.set_default_headers({{"Authorization", "Bearer " + o.authToken}});
- #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
- cli.enable_server_certificate_verification(true);
- #endif
- }
- /// "host:port" -> "http://host:port"; an explicit scheme is kept. Trailing
- /// slashes are dropped so the base concatenates cleanly with "/run".
- std::string normalizeBase(std::string e) {
- while (!e.empty() && e.back() == '/') e.pop_back();
- if (e.find("://") == std::string::npos) e = "http://" + e;
- return e;
- }
- /// httplib errors that prove the request never left us, so nothing ran and the
- /// next endpoint is safe to try. Everything else - a read timeout above all -
- /// means the runner may have received the request and executed the function.
- bool neverDelivered(httplib::Error e) {
- return e == httplib::Error::Connection || e == httplib::Error::ConnectionTimeout;
- }
- std::string errorText(httplib::Error e) { return httplib::to_string(e); }
- std::vector<std::string> consoleLines(const nlohmann::json& j) {
- std::vector<std::string> out;
- if (!j.contains("console") || !j["console"].is_array()) return out;
- const nlohmann::json& arr = j["console"]; // bind first: a range-for over a temporary dangles
- for (const nlohmann::json& line : arr)
- out.push_back(line.is_string() ? line.get<std::string>() : line.dump());
- return out;
- }
- // The three helpers below are templated only so they can name RunnerPool's
- // private Endpoint type by deduction: the seam header declares no private
- // helper methods and is not ours to change, so the shared state transitions
- // live here instead of being copy-pasted into each public method.
- /// Indices to try, in round-robin order, skipping endpoints still inside their
- /// backoff window. Advances the rotation by one so successive calls spread.
- template <class Eps>
- std::vector<size_t> pickCandidates(Eps& eps, size_t& next, std::mutex& mu) {
- const auto now = std::chrono::steady_clock::now();
- std::vector<size_t> out;
- std::lock_guard<std::mutex> lk(mu);
- if (eps.empty()) return out;
- const size_t start = next++ % eps.size();
- for (size_t n = 0; n < eps.size(); ++n) {
- const size_t i = (start + n) % eps.size();
- // An expired backoff puts an endpoint back in rotation even while the
- // flag still says unhealthy: the flag is a hint, the clock decides.
- if (eps[i].healthy || now >= eps[i].notBefore) out.push_back(i);
- }
- return out;
- }
- template <class Eps>
- void markHealthy(Eps& eps, size_t i, std::mutex& mu) {
- std::lock_guard<std::mutex> lk(mu);
- eps[i].healthy = true;
- eps[i].notBefore = {};
- eps[i].lastError.clear();
- }
- template <class Eps>
- void markUnhealthy(Eps& eps, size_t i, std::mutex& mu, uint32_t backoffSec,
- const std::string& why) {
- std::lock_guard<std::mutex> lk(mu);
- const bool wasHealthy = eps[i].healthy;
- eps[i].healthy = false;
- eps[i].lastError = why;
- eps[i].notBefore = std::chrono::steady_clock::now() + std::chrono::seconds(backoffSec);
- // Only on the transition, or a hard-down runner floods the log once per request.
- if (wasHealthy) spdlog::warn("runner {} marked unhealthy: {}", eps[i].base, why);
- }
- /// Turn a protocol response into a run result. NEVER a transport failure:
- /// reaching here means a runner answered, so whatever went wrong is the
- /// function's, not ours. A thrown exception, a wall-time timeout and an
- /// out-of-memory kill all arrive this way - the runner did its job and reported
- /// the outcome, which is precisely why none of them is retried.
- RunnerRunResult parseRun(const nlohmann::json& j) {
- RunnerRunResult out;
- out.transportFailure = false;
- out.timedOut = j.value("timed_out", false);
- out.outOfMemory = j.value("out_of_memory", false);
- out.error = j.value("error", std::string{});
- // `ok` is honoured when the runner sends it, so a runner can report a
- // failure that carries no message; otherwise it is derived.
- out.ok = j.contains("ok") && j["ok"].is_boolean()
- ? j["ok"].get<bool>()
- : (out.error.empty() && !out.timedOut && !out.outOfMemory);
- out.status = j.contains("status") && j["status"].is_number_integer()
- ? j["status"].get<int>() : 200;
- if (j.contains("headers") && j["headers"].is_object()) out.headers = j["headers"];
- if (j.contains("body")) out.body = j["body"];
- out.console = consoleLines(j);
- out.durationMs = j.value("duration_ms", static_cast<int64_t>(0));
- return out;
- }
- } // namespace
- RunnerPool::RunnerPool(Options opts) : opts_(std::move(opts)) {
- for (const std::string& e : opts_.endpoints) {
- Endpoint ep;
- ep.base = normalizeBase(e);
- // Optimistically healthy: with no probe yet, refusing to dispatch would
- // make a cold start look like an outage.
- ep.healthy = true;
- endpoints_.push_back(std::move(ep));
- }
- }
- bool RunnerPool::anyHealthy() {
- // Probes rather than trusting the cached flag: "answered /health recently"
- // is a claim about the runner now, and a stale true is the dangerous
- // direction - a function write would then be validated against nothing.
- for (size_t i : pickCandidates(endpoints_, next_, mu_)) {
- std::string base;
- { std::lock_guard<std::mutex> lk(mu_); base = endpoints_[i].base; }
- httplib::Client cli(base);
- configureClient(cli, opts_);
- httplib::Result r = cli.Get("/health");
- if (r && r->status == 200) {
- markHealthy(endpoints_, i, mu_);
- return true;
- }
- markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
- r ? ("health status " + std::to_string(r->status)) : errorText(r.error()));
- }
- return false;
- }
- RunnerRunResult RunnerPool::run(const std::string& project, const std::string& functionId,
- const nlohmann::json& trigger) {
- const nlohmann::json payload{{"project", project},
- {"function_id", functionId},
- {"trigger", trigger}};
- RunnerRunResult last;
- last.ok = false;
- last.transportFailure = true;
- last.status = 503;
- last.error = opts_.endpoints.empty() ? "no runner configured" : "no healthy runner";
- for (size_t i : pickCandidates(endpoints_, next_, mu_)) {
- std::string base;
- { std::lock_guard<std::mutex> lk(mu_); base = endpoints_[i].base; }
- httplib::Client cli(base);
- configureClient(cli, opts_);
- httplib::Result r = cli.Post("/run", payload.dump(), "application/json");
- if (!r) {
- const std::string why = errorText(r.error());
- markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec, why);
- last.transportFailure = true;
- last.status = 503;
- last.error = "runner unreachable: " + why;
- if (neverDelivered(r.error())) continue; // nothing ran; the next runner is safe
- // Delivered but unanswered: the handler may be running right now, so
- // the caller gets an error and NOBODY runs it again.
- spdlog::error("runner {} did not answer /run for {}/{}: {} - not retried, the run "
- "may already have had side effects", base, project, functionId, why);
- return last;
- }
- if (r->status != 200) {
- markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
- "run status " + std::to_string(r->status));
- last.transportFailure = true;
- last.status = 503;
- last.error = "runner returned HTTP " + std::to_string(r->status);
- return last; // off-protocol AFTER delivery: same reasoning as above
- }
- nlohmann::json j;
- try {
- j = nlohmann::json::parse(r->body);
- } catch (const std::exception& e) {
- markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
- std::string("unparseable /run response: ") + e.what());
- last.transportFailure = true;
- last.status = 503;
- last.error = "runner response was not JSON";
- return last;
- }
- if (!j.is_object()) {
- markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
- "non-object /run response");
- last.transportFailure = true;
- last.status = 503;
- last.error = "runner response was not an object";
- return last;
- }
- markHealthy(endpoints_, i, mu_);
- return parseRun(j);
- }
- return last;
- }
- RunnerValidateResult RunnerPool::validate(const std::string& source, const std::string& path) {
- const nlohmann::json payload{{"source", source}, {"path", path}};
- RunnerValidateResult last;
- last.ok = false;
- last.transportFailure = true;
- last.error = opts_.endpoints.empty() ? "no runner configured" : "no healthy runner";
- for (size_t i : pickCandidates(endpoints_, next_, mu_)) {
- std::string base;
- { std::lock_guard<std::mutex> lk(mu_); base = endpoints_[i].base; }
- httplib::Client cli(base);
- configureClient(cli, opts_);
- httplib::Result r = cli.Post("/validate", payload.dump(), "application/json");
- // Unlike run(), EVERY failure here is retryable. Compiling a script and
- // reading its `on` block has no side effects, so a second attempt
- // elsewhere can only turn a 503 into an answer; the double-execution
- // hazard that constrains run() does not exist on this path.
- if (!r) {
- markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec, errorText(r.error()));
- last.transportFailure = true;
- last.error = "runner unreachable: " + errorText(r.error());
- continue;
- }
- if (r->status != 200) {
- markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
- "validate status " + std::to_string(r->status));
- last.transportFailure = true;
- last.error = "runner returned HTTP " + std::to_string(r->status);
- continue;
- }
- nlohmann::json j;
- try {
- j = nlohmann::json::parse(r->body);
- } catch (const std::exception& e) {
- markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
- std::string("unparseable /validate response: ") + e.what());
- last.transportFailure = true;
- last.error = "runner response was not JSON";
- continue;
- }
- if (!j.is_object()) {
- markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
- "non-object /validate response");
- last.transportFailure = true;
- last.error = "runner response was not an object";
- continue;
- }
- markHealthy(endpoints_, i, mu_);
- RunnerValidateResult out;
- out.transportFailure = false;
- out.ok = j.value("ok", false);
- out.error = j.value("error", std::string{});
- if (j.contains("descriptor") && j["descriptor"].is_object())
- out.descriptor = j["descriptor"];
- return out;
- }
- return last;
- }
- nlohmann::json RunnerPool::statusJson() {
- const auto now = std::chrono::steady_clock::now();
- nlohmann::json arr = nlohmann::json::array();
- size_t healthyCount = 0;
- std::lock_guard<std::mutex> lk(mu_);
- for (const Endpoint& ep : endpoints_) {
- int64_t retryIn = 0;
- if (!ep.healthy && ep.notBefore > now)
- retryIn = std::chrono::duration_cast<std::chrono::seconds>(ep.notBefore - now).count();
- if (ep.healthy) ++healthyCount;
- arr.push_back({{"endpoint", ep.base},
- {"healthy", ep.healthy},
- {"last_error", ep.lastError},
- {"retry_in_sec", retryIn}});
- }
- return {{"runners", arr}, {"healthy", healthyCount}};
- }
- } // namespace svapi
|