function_jobs.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. #include "function_jobs.hpp"
  2. #include "apikey.hpp"
  3. #include <ctime>
  4. #include <string>
  5. namespace svapi {
  6. namespace {
  7. /// The row version the client injects into every document it returns.
  8. /// 0 when absent or not a positive integer - a caller must then not attempt a
  9. /// compare-and-set, because there is nothing to compare against.
  10. uint64_t documentVersionOf(const nlohmann::json& doc) {
  11. if (!doc.is_object()) return 0;
  12. const auto it = doc.find("_version");
  13. if (it == doc.end() || !it->is_number_integer()) return 0;
  14. const int64_t v = it->get<int64_t>();
  15. return v > 0 ? static_cast<uint64_t>(v) : 0;
  16. }
  17. using Client = smartbotic::database::Client;
  18. uint64_t nowSec() { return static_cast<uint64_t>(std::time(nullptr)); }
  19. /// One reclaim pass touches at most this many rows. The pass is periodic, so a
  20. /// backlog - a runner host that died holding hundreds of jobs - drains over the
  21. /// following passes instead of turning one tick into hundreds of writes while
  22. /// nothing else gets scheduled. Same reasoning as FunctionRunLogStore's
  23. /// kMaxTrimPerAppend.
  24. constexpr uint32_t kMaxReclaimPerPass = 200;
  25. /// A project delete is rare and must be complete, so this bound is generous
  26. /// rather than drip-fed; it exists only so a corrupt queue cannot ask for an
  27. /// unbounded result set.
  28. constexpr uint32_t kMaxRemovePerPass = 100000;
  29. constexpr uint32_t kDefaultListLimit = 100;
  30. /// Claimable jobs, most overdue first.
  31. ///
  32. /// `run_after` is the sort key, not `created_at`, for three reasons. It is the
  33. /// field that says when the job became eligible, so "oldest first" by it means
  34. /// "longest overdue first", which is the queue order an operator expects of a
  35. /// scheduler. It is also the field being filtered, so the server sorts and
  36. /// filters on one field instead of two (the DB takes a single sort key, so a
  37. /// second-level tiebreak on created_at is not expressible anyway). And it keeps
  38. /// a backed-off retry honest: complete() pushes run_after into the future, so a
  39. /// repeatedly failing job queues behind work enqueued since instead of
  40. /// returning to the head of the queue on every pass and starving it. For a job
  41. /// that was never delayed run_after is its enqueue time, so the common case is
  42. /// still plain arrival order.
  43. Client::QueryOptions dueCandidates(uint64_t now, uint32_t limit) {
  44. Client::QueryOptions o;
  45. o.filters.push_back(Client::Filter::eq("state", "pending"));
  46. o.filters.push_back(Client::Filter::lte("run_after", now));
  47. o.sortField = "run_after";
  48. o.sortDescending = false;
  49. o.limit = limit;
  50. return o;
  51. }
  52. } // namespace
  53. FunctionJob FunctionJob::fromJson(const nlohmann::json& j) {
  54. FunctionJob job;
  55. job.jobId = j.value("job_id", "");
  56. job.project = j.value("project", "");
  57. job.functionId = j.value("function_id", "");
  58. job.trigger = j.value("trigger", "");
  59. // Bound to a named reference before use: a range-for or a reference into a
  60. // temporary parsed subobject dangles (CLAUDE.md).
  61. if (j.contains("payload") && j.at("payload").is_object()) {
  62. const nlohmann::json& payload = j.at("payload");
  63. job.payload = payload;
  64. }
  65. job.state = j.value("state", std::string("pending"));
  66. job.claimedBy = j.value("claimed_by", "");
  67. job.claimedAt = j.value("claimed_at", 0ull);
  68. job.attempts = j.value("attempts", 0u);
  69. job.depth = j.value("depth", 0u);
  70. job.runAfter = j.value("run_after", 0ull);
  71. job.createdAt = j.value("created_at", 0ull);
  72. job.lastError = j.value("last_error", "");
  73. return job;
  74. }
  75. nlohmann::json FunctionJob::toJson() const {
  76. // `job_id`, never `id`: the client strips a top-level `id` from stored
  77. // bodies, and a job with no readable identity could never be claimed
  78. // (claiming needs the id to compare-and-set on) or deleted.
  79. return {{"job_id", jobId},
  80. {"project", project},
  81. {"function_id", functionId},
  82. {"trigger", trigger},
  83. {"payload", payload},
  84. {"state", state},
  85. {"claimed_by", claimedBy},
  86. {"claimed_at", claimedAt},
  87. {"attempts", attempts},
  88. {"depth", depth},
  89. {"run_after", runAfter},
  90. {"created_at", createdAt},
  91. {"last_error", lastError}};
  92. }
  93. FunctionJobQueue::FunctionJobQueue(DbGateway& db) : db_(db) {}
  94. void FunctionJobQueue::ensure() {
  95. const std::string c = coll();
  96. if (!db_.client().getCollectionInfo(c).has_value())
  97. db_.client().createCollection(c, 0, /*encrypted*/ false, 0, 0);
  98. // Re-open the collection even when it already existed: a collection that
  99. // exists on disk but has not been touched since the server restarted does
  100. // not surface its rows to find() until something opens it, which is the
  101. // trap CollectionRegistry::bootstrap and KeyStore::bootstrap exist for.
  102. // Cheapest possible probe - one row, no filters.
  103. Client::QueryOptions probe;
  104. probe.limit = 1;
  105. (void)db_.client().find(c, probe);
  106. }
  107. std::string FunctionJobQueue::enqueue(const FunctionJob& job) {
  108. ensure();
  109. FunctionJob j = job;
  110. // The queue owns identity when the caller does not care: a scheduler tick
  111. // has no natural id for its job, and an empty id would store every job on
  112. // top of the last one.
  113. if (j.jobId.empty()) j.jobId = generateApiKey();
  114. if (j.createdAt == 0) j.createdAt = nowSec();
  115. if (j.state.empty()) j.state = "pending";
  116. const std::pair<std::string, bool> res = db_.client().upsert(coll(), j.toJson(), j.jobId);
  117. return res.first.empty() ? std::string() : j.jobId;
  118. }
  119. bool FunctionJobQueue::hasActive(const std::string& project, const std::string& functionId) {
  120. Client::QueryOptions o;
  121. o.filters.push_back(Client::Filter::eq("project", project));
  122. o.filters.push_back(Client::Filter::eq("function_id", functionId));
  123. // BOTH states, in one IN: a job that is pending has not run yet and a job
  124. // that is claimed is running right now, and single-flight has to refuse a
  125. // second copy in either case. Counting only one of them would let the
  126. // scheduler stack a second run exactly when the first is slowest.
  127. o.filters.push_back(Client::Filter::in("state", nlohmann::json::array({"pending", "claimed"})));
  128. o.limit = 1;
  129. return !db_.client().find(coll(), o).empty();
  130. }
  131. std::optional<FunctionJob> FunctionJobQueue::claimNext(const std::string& runnerId,
  132. uint32_t maxCandidates) {
  133. if (maxCandidates == 0) maxCandidates = 1;
  134. const std::string c = coll();
  135. const uint64_t now = nowSec();
  136. const std::vector<nlohmann::json> candidates =
  137. db_.client().find(c, dueCandidates(now, maxCandidates));
  138. for (const auto& doc : candidates) {
  139. FunctionJob job = FunctionJob::fromJson(doc);
  140. if (job.jobId.empty()) continue; // no identity, nothing to compare-and-set on
  141. // Compare-and-set on the version the read already gave us. The find
  142. // above is not a lock: between it and this write, any number of runners
  143. // may be looking at the same row, and the CAS is what settles it.
  144. //
  145. // `_version` is injected into every row the client returns, so asking
  146. // for it separately would be a third round trip for a number already
  147. // in hand. A row without one cannot be claimed safely, so it is skipped
  148. // rather than claimed with a guessed version.
  149. const uint64_t version = documentVersionOf(doc);
  150. if (version == 0) continue;
  151. job.state = "claimed";
  152. job.claimedBy = runnerId;
  153. job.claimedAt = now;
  154. job.attempts += 1;
  155. if (!db_.client().updateIfVersion(c, job.jobId, job.toJson(), version)) {
  156. // Another runner won this row - it may be executing the function at
  157. // this instant. Do NOT retry it: re-reading the version and writing
  158. // again is how two runners end up running one side-effecting job.
  159. // Move to the next candidate instead. (Same three-way reasoning as
  160. // RunnerPool's retry rule: "somebody answered" means hands off.)
  161. continue;
  162. }
  163. // The CAS moved the row on by one, and that is the version the caller
  164. // must present to complete() - otherwise its completion would be
  165. // refused as superseded by its own claim.
  166. job.version = version + 1;
  167. // Returned as stored, so the caller sees the real attempts count and
  168. // can decide whether this is a last chance.
  169. return job;
  170. }
  171. return std::nullopt;
  172. }
  173. bool FunctionJobQueue::complete(const FunctionJob& job, bool ok, const std::string& error,
  174. uint32_t retryAfterSec) {
  175. if (job.jobId.empty()) return false;
  176. FunctionJob next = job;
  177. if (ok) {
  178. next.state = "done";
  179. next.lastError.clear();
  180. } else if (retryAfterSec > 0) {
  181. next.state = "pending";
  182. next.lastError = error;
  183. next.runAfter = nowSec() + retryAfterSec;
  184. // Clear the claim: a pending row that still carries a claim timestamp
  185. // would be picked up by reclaimStale and have its backoff cancelled.
  186. next.claimedBy.clear();
  187. next.claimedAt = 0;
  188. } else {
  189. next.state = "failed";
  190. next.lastError = error;
  191. }
  192. // `attempts` is deliberately left as it is, including on success: it is the
  193. // history of the job, and the admin list shows "succeeded on attempt 3".
  194. // Compare-and-set, not a blind upsert. A claim that went stale can be
  195. // reclaimed and handed to another runner while the first is still working;
  196. // if that first runner then completed blindly it would overwrite the new
  197. // owner - marking `done` a job executing right now, or dragging it back to
  198. // `pending`. Refusing a job with no version keeps that path closed rather
  199. // than silently degrading to the unsafe write.
  200. // No version means the job did not come from claimNext, so there is nothing
  201. // to compare against. Refused rather than silently degrading to the unsafe
  202. // blind write. Reporting is the caller's: a storage class that logs makes
  203. // every test that drives it need a logger.
  204. if (job.version == 0) return false;
  205. // False here means "somebody else owns this row now", not "the database is
  206. // down" - the caller logs it and must NOT retry.
  207. return db_.client().updateIfVersion(coll(), job.jobId, next.toJson(), job.version);
  208. }
  209. uint32_t FunctionJobQueue::reclaimStale(uint32_t timeoutSec, uint32_t maxAttempts) {
  210. // 0 means "unlimited" in several places in this codebase (log retention,
  211. // TTLs). It must not mean that here: an unlimited retry budget is exactly
  212. // the loop this guard exists to stop, where one poisonous job takes down
  213. // every runner in turn. Treat it as a budget of one.
  214. if (maxAttempts == 0) maxAttempts = 1;
  215. const std::string c = coll();
  216. const uint64_t now = nowSec();
  217. const uint64_t cutoff = now > timeoutSec ? now - timeoutSec : 0;
  218. Client::QueryOptions o;
  219. o.filters.push_back(Client::Filter::eq("state", "claimed"));
  220. o.filters.push_back(Client::Filter::lte("claimed_at", cutoff));
  221. o.sortField = "claimed_at"; // the most abandoned first, so a bounded pass does the oldest
  222. o.sortDescending = false;
  223. o.limit = kMaxReclaimPerPass;
  224. uint32_t reclaimed = 0;
  225. const std::vector<nlohmann::json> stale = db_.client().find(c, o);
  226. for (const auto& doc : stale) {
  227. FunctionJob job = FunctionJob::fromJson(doc);
  228. if (job.jobId.empty()) continue;
  229. const uint64_t version = documentVersionOf(doc);
  230. if (version == 0) continue;
  231. const bool exhausted = job.attempts >= maxAttempts;
  232. if (exhausted) {
  233. // Retire it rather than hand it to the next runner. A job that kills
  234. // the process running it would otherwise kill every runner in turn,
  235. // and the queue would never drain.
  236. job.state = "failed";
  237. job.lastError = "abandoned by runner '" + job.claimedBy + "' after " +
  238. std::to_string(job.attempts) + " attempt(s)";
  239. } else {
  240. job.state = "pending";
  241. job.lastError = "reclaimed from runner '" + job.claimedBy +
  242. "': claim went stale";
  243. job.claimedBy.clear();
  244. job.claimedAt = 0;
  245. job.runAfter = now; // due immediately; attempts is NOT rewound
  246. }
  247. // Compare-and-set, not a plain write: the owning runner may be
  248. // finishing this job in the window between the find above and here, and
  249. // its verdict has to stand. Losing the race means the job was not
  250. // stale after all, so it is not counted and not touched.
  251. if (!db_.client().updateIfVersion(c, job.jobId, job.toJson(), version)) continue;
  252. if (!exhausted) ++reclaimed;
  253. }
  254. // Only rows actually returned to pending are counted: a retired job was not
  255. // recovered, and reporting it as such would make a stuck queue look busy.
  256. return reclaimed;
  257. }
  258. std::optional<FunctionJob> FunctionJobQueue::get(const std::string& jobId) {
  259. if (jobId.empty()) return std::nullopt;
  260. if (auto doc = db_.client().get(coll(), jobId)) {
  261. FunctionJob job = FunctionJob::fromJson(*doc);
  262. if (job.jobId.empty()) job.jobId = jobId; // the body never carries `id`
  263. return job;
  264. }
  265. return std::nullopt;
  266. }
  267. bool FunctionJobQueue::remove(const std::string& jobId) {
  268. if (jobId.empty()) return false;
  269. return db_.client().remove(coll(), jobId);
  270. }
  271. std::vector<FunctionJob> FunctionJobQueue::list(const std::string& project, uint32_t limit) {
  272. if (limit == 0) limit = kDefaultListLimit;
  273. Client::QueryOptions o;
  274. o.filters.push_back(Client::Filter::eq("project", project));
  275. o.sortField = "created_at"; // arrival order, not due order: this is a history view
  276. o.sortDescending = false;
  277. o.limit = limit;
  278. std::vector<FunctionJob> out;
  279. const std::vector<nlohmann::json> rows = db_.client().find(coll(), o);
  280. out.reserve(rows.size());
  281. for (const auto& doc : rows) out.push_back(FunctionJob::fromJson(doc));
  282. return out;
  283. }
  284. uint32_t FunctionJobQueue::removeForProject(const std::string& project) {
  285. const std::string c = coll();
  286. Client::QueryOptions o;
  287. o.filters.push_back(Client::Filter::eq("project", project));
  288. o.limit = kMaxRemovePerPass;
  289. uint32_t removed = 0;
  290. const std::vector<nlohmann::json> rows = db_.client().find(c, o);
  291. for (const auto& doc : rows) {
  292. // By the body's `job_id`: the client strips a top-level `id`, so the
  293. // document id is only readable because it is carried in the body.
  294. const std::string jobId = doc.value("job_id", std::string());
  295. if (!jobId.empty() && db_.client().remove(c, jobId)) ++removed;
  296. }
  297. return removed;
  298. }
  299. } // namespace svapi