runner_client.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. #include "runner_client.hpp"
  2. #include <httplib.h>
  3. #include <spdlog/spdlog.h>
  4. #include <algorithm>
  5. namespace svapi {
  6. namespace {
  7. // Why no applyOutboundDefaults() here: that helper exists for calls that leave
  8. // our trust boundary (embedding providers, captcha verification), where a
  9. // provider must see our User-Agent and must not be able to bounce a
  10. // credentialed request elsewhere. A runner is a first-party process from this
  11. // repo, addressed by a configured host:port and speaking a private protocol -
  12. // not a provider. Treating it as one would also drag vectorapi_core's whole
  13. // dependency set into a client that deliberately needs nothing but httplib,
  14. // which is what keeps this file testable on a host with no database client. The
  15. // two properties of that helper that DO matter internally are set explicitly
  16. // below: redirects off, and TLS verification on for an https endpoint.
  17. template <class Opts>
  18. void configureClient(httplib::Client& cli, const Opts& o) {
  19. cli.set_connection_timeout(o.connectTimeoutSec, 0);
  20. cli.set_read_timeout(o.readTimeoutSec, 0);
  21. cli.set_write_timeout(o.readTimeoutSec, 0);
  22. // A runner has no business redirecting us anywhere, and following one would
  23. // turn a compromised or misconfigured runner into an SSRF primitive.
  24. cli.set_follow_location(false);
  25. cli.set_keep_alive(true);
  26. // The runner authenticates every route, /health included. Empty only for a
  27. // loopback runner, which is the one case it serves unauthenticated.
  28. if (!o.authToken.empty())
  29. cli.set_default_headers({{"Authorization", "Bearer " + o.authToken}});
  30. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  31. cli.enable_server_certificate_verification(true);
  32. #endif
  33. }
  34. /// "host:port" -> "http://host:port"; an explicit scheme is kept. Trailing
  35. /// slashes are dropped so the base concatenates cleanly with "/run".
  36. std::string normalizeBase(std::string e) {
  37. while (!e.empty() && e.back() == '/') e.pop_back();
  38. if (e.find("://") == std::string::npos) e = "http://" + e;
  39. return e;
  40. }
  41. /// httplib errors that prove the request never left us, so nothing ran and the
  42. /// next endpoint is safe to try. Everything else - a read timeout above all -
  43. /// means the runner may have received the request and executed the function.
  44. bool neverDelivered(httplib::Error e) {
  45. return e == httplib::Error::Connection || e == httplib::Error::ConnectionTimeout;
  46. }
  47. std::string errorText(httplib::Error e) { return httplib::to_string(e); }
  48. std::vector<std::string> consoleLines(const nlohmann::json& j) {
  49. std::vector<std::string> out;
  50. if (!j.contains("console") || !j["console"].is_array()) return out;
  51. const nlohmann::json& arr = j["console"]; // bind first: a range-for over a temporary dangles
  52. for (const nlohmann::json& line : arr)
  53. out.push_back(line.is_string() ? line.get<std::string>() : line.dump());
  54. return out;
  55. }
  56. // The three helpers below are templated only so they can name RunnerPool's
  57. // private Endpoint type by deduction: the seam header declares no private
  58. // helper methods and is not ours to change, so the shared state transitions
  59. // live here instead of being copy-pasted into each public method.
  60. /// Indices to try, in round-robin order, skipping endpoints still inside their
  61. /// backoff window. Advances the rotation by one so successive calls spread.
  62. template <class Eps>
  63. std::vector<size_t> pickCandidates(Eps& eps, size_t& next, std::mutex& mu) {
  64. const auto now = std::chrono::steady_clock::now();
  65. std::vector<size_t> out;
  66. std::lock_guard<std::mutex> lk(mu);
  67. if (eps.empty()) return out;
  68. const size_t start = next++ % eps.size();
  69. for (size_t n = 0; n < eps.size(); ++n) {
  70. const size_t i = (start + n) % eps.size();
  71. // An expired backoff puts an endpoint back in rotation even while the
  72. // flag still says unhealthy: the flag is a hint, the clock decides.
  73. if (eps[i].healthy || now >= eps[i].notBefore) out.push_back(i);
  74. }
  75. return out;
  76. }
  77. template <class Eps>
  78. void markHealthy(Eps& eps, size_t i, std::mutex& mu) {
  79. std::lock_guard<std::mutex> lk(mu);
  80. eps[i].healthy = true;
  81. eps[i].notBefore = {};
  82. eps[i].lastError.clear();
  83. }
  84. template <class Eps>
  85. void markUnhealthy(Eps& eps, size_t i, std::mutex& mu, uint32_t backoffSec,
  86. const std::string& why) {
  87. std::lock_guard<std::mutex> lk(mu);
  88. const bool wasHealthy = eps[i].healthy;
  89. eps[i].healthy = false;
  90. eps[i].lastError = why;
  91. eps[i].notBefore = std::chrono::steady_clock::now() + std::chrono::seconds(backoffSec);
  92. // Only on the transition, or a hard-down runner floods the log once per request.
  93. if (wasHealthy) spdlog::warn("runner {} marked unhealthy: {}", eps[i].base, why);
  94. }
  95. /// Turn a protocol response into a run result. NEVER a transport failure:
  96. /// reaching here means a runner answered, so whatever went wrong is the
  97. /// function's, not ours. A thrown exception, a wall-time timeout and an
  98. /// out-of-memory kill all arrive this way - the runner did its job and reported
  99. /// the outcome, which is precisely why none of them is retried.
  100. RunnerRunResult parseRun(const nlohmann::json& j) {
  101. RunnerRunResult out;
  102. out.transportFailure = false;
  103. out.timedOut = j.value("timed_out", false);
  104. out.outOfMemory = j.value("out_of_memory", false);
  105. out.error = j.value("error", std::string{});
  106. // `ok` is honoured when the runner sends it, so a runner can report a
  107. // failure that carries no message; otherwise it is derived.
  108. out.ok = j.contains("ok") && j["ok"].is_boolean()
  109. ? j["ok"].get<bool>()
  110. : (out.error.empty() && !out.timedOut && !out.outOfMemory);
  111. out.status = j.contains("status") && j["status"].is_number_integer()
  112. ? j["status"].get<int>() : 200;
  113. if (j.contains("headers") && j["headers"].is_object()) out.headers = j["headers"];
  114. if (j.contains("body")) out.body = j["body"];
  115. out.console = consoleLines(j);
  116. out.durationMs = j.value("duration_ms", static_cast<int64_t>(0));
  117. return out;
  118. }
  119. } // namespace
  120. RunnerPool::RunnerPool(Options opts) : opts_(std::move(opts)) {
  121. for (const std::string& e : opts_.endpoints) {
  122. Endpoint ep;
  123. ep.base = normalizeBase(e);
  124. // Optimistically healthy: with no probe yet, refusing to dispatch would
  125. // make a cold start look like an outage.
  126. ep.healthy = true;
  127. endpoints_.push_back(std::move(ep));
  128. }
  129. }
  130. bool RunnerPool::anyHealthy() {
  131. // Probes rather than trusting the cached flag: "answered /health recently"
  132. // is a claim about the runner now, and a stale true is the dangerous
  133. // direction - a function write would then be validated against nothing.
  134. for (size_t i : pickCandidates(endpoints_, next_, mu_)) {
  135. std::string base;
  136. { std::lock_guard<std::mutex> lk(mu_); base = endpoints_[i].base; }
  137. httplib::Client cli(base);
  138. configureClient(cli, opts_);
  139. httplib::Result r = cli.Get("/health");
  140. if (r && r->status == 200) {
  141. markHealthy(endpoints_, i, mu_);
  142. return true;
  143. }
  144. markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
  145. r ? ("health status " + std::to_string(r->status)) : errorText(r.error()));
  146. }
  147. return false;
  148. }
  149. RunnerRunResult RunnerPool::run(const std::string& project, const std::string& functionId,
  150. const nlohmann::json& trigger) {
  151. const nlohmann::json payload{{"project", project},
  152. {"function_id", functionId},
  153. {"trigger", trigger}};
  154. RunnerRunResult last;
  155. last.ok = false;
  156. last.transportFailure = true;
  157. last.status = 503;
  158. last.error = opts_.endpoints.empty() ? "no runner configured" : "no healthy runner";
  159. for (size_t i : pickCandidates(endpoints_, next_, mu_)) {
  160. std::string base;
  161. { std::lock_guard<std::mutex> lk(mu_); base = endpoints_[i].base; }
  162. httplib::Client cli(base);
  163. configureClient(cli, opts_);
  164. httplib::Result r = cli.Post("/run", payload.dump(), "application/json");
  165. if (!r) {
  166. const std::string why = errorText(r.error());
  167. markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec, why);
  168. last.transportFailure = true;
  169. last.status = 503;
  170. last.error = "runner unreachable: " + why;
  171. if (neverDelivered(r.error())) continue; // nothing ran; the next runner is safe
  172. // Delivered but unanswered: the handler may be running right now, so
  173. // the caller gets an error and NOBODY runs it again.
  174. spdlog::error("runner {} did not answer /run for {}/{}: {} - not retried, the run "
  175. "may already have had side effects", base, project, functionId, why);
  176. return last;
  177. }
  178. if (r->status != 200) {
  179. markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
  180. "run status " + std::to_string(r->status));
  181. last.transportFailure = true;
  182. last.status = 503;
  183. last.error = "runner returned HTTP " + std::to_string(r->status);
  184. return last; // off-protocol AFTER delivery: same reasoning as above
  185. }
  186. nlohmann::json j;
  187. try {
  188. j = nlohmann::json::parse(r->body);
  189. } catch (const std::exception& e) {
  190. markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
  191. std::string("unparseable /run response: ") + e.what());
  192. last.transportFailure = true;
  193. last.status = 503;
  194. last.error = "runner response was not JSON";
  195. return last;
  196. }
  197. if (!j.is_object()) {
  198. markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
  199. "non-object /run response");
  200. last.transportFailure = true;
  201. last.status = 503;
  202. last.error = "runner response was not an object";
  203. return last;
  204. }
  205. markHealthy(endpoints_, i, mu_);
  206. return parseRun(j);
  207. }
  208. return last;
  209. }
  210. RunnerValidateResult RunnerPool::validate(const std::string& source, const std::string& path) {
  211. const nlohmann::json payload{{"source", source}, {"path", path}};
  212. RunnerValidateResult last;
  213. last.ok = false;
  214. last.transportFailure = true;
  215. last.error = opts_.endpoints.empty() ? "no runner configured" : "no healthy runner";
  216. for (size_t i : pickCandidates(endpoints_, next_, mu_)) {
  217. std::string base;
  218. { std::lock_guard<std::mutex> lk(mu_); base = endpoints_[i].base; }
  219. httplib::Client cli(base);
  220. configureClient(cli, opts_);
  221. httplib::Result r = cli.Post("/validate", payload.dump(), "application/json");
  222. // Unlike run(), EVERY failure here is retryable. Compiling a script and
  223. // reading its `on` block has no side effects, so a second attempt
  224. // elsewhere can only turn a 503 into an answer; the double-execution
  225. // hazard that constrains run() does not exist on this path.
  226. if (!r) {
  227. markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec, errorText(r.error()));
  228. last.transportFailure = true;
  229. last.error = "runner unreachable: " + errorText(r.error());
  230. continue;
  231. }
  232. if (r->status != 200) {
  233. markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
  234. "validate status " + std::to_string(r->status));
  235. last.transportFailure = true;
  236. last.error = "runner returned HTTP " + std::to_string(r->status);
  237. continue;
  238. }
  239. nlohmann::json j;
  240. try {
  241. j = nlohmann::json::parse(r->body);
  242. } catch (const std::exception& e) {
  243. markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
  244. std::string("unparseable /validate response: ") + e.what());
  245. last.transportFailure = true;
  246. last.error = "runner response was not JSON";
  247. continue;
  248. }
  249. if (!j.is_object()) {
  250. markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
  251. "non-object /validate response");
  252. last.transportFailure = true;
  253. last.error = "runner response was not an object";
  254. continue;
  255. }
  256. markHealthy(endpoints_, i, mu_);
  257. RunnerValidateResult out;
  258. out.transportFailure = false;
  259. out.ok = j.value("ok", false);
  260. out.error = j.value("error", std::string{});
  261. if (j.contains("descriptor") && j["descriptor"].is_object())
  262. out.descriptor = j["descriptor"];
  263. return out;
  264. }
  265. return last;
  266. }
  267. nlohmann::json RunnerPool::statusJson() {
  268. const auto now = std::chrono::steady_clock::now();
  269. nlohmann::json arr = nlohmann::json::array();
  270. size_t healthyCount = 0;
  271. std::lock_guard<std::mutex> lk(mu_);
  272. for (const Endpoint& ep : endpoints_) {
  273. int64_t retryIn = 0;
  274. if (!ep.healthy && ep.notBefore > now)
  275. retryIn = std::chrono::duration_cast<std::chrono::seconds>(ep.notBefore - now).count();
  276. if (ep.healthy) ++healthyCount;
  277. arr.push_back({{"endpoint", ep.base},
  278. {"healthy", ep.healthy},
  279. {"last_error", ep.lastError},
  280. {"retry_in_sec", retryIn}});
  281. }
  282. return {{"runners", arr}, {"healthy", healthyCount}};
  283. }
  284. } // namespace svapi