#include "function_jobs.hpp" #include "apikey.hpp" #include #include namespace svapi { namespace { /// The row version the client injects into every document it returns. /// 0 when absent or not a positive integer - a caller must then not attempt a /// compare-and-set, because there is nothing to compare against. uint64_t documentVersionOf(const nlohmann::json& doc) { if (!doc.is_object()) return 0; const auto it = doc.find("_version"); if (it == doc.end() || !it->is_number_integer()) return 0; const int64_t v = it->get(); return v > 0 ? static_cast(v) : 0; } using Client = smartbotic::database::Client; uint64_t nowSec() { return static_cast(std::time(nullptr)); } /// One reclaim pass touches at most this many rows. The pass is periodic, so a /// backlog - a runner host that died holding hundreds of jobs - drains over the /// following passes instead of turning one tick into hundreds of writes while /// nothing else gets scheduled. Same reasoning as FunctionRunLogStore's /// kMaxTrimPerAppend. constexpr uint32_t kMaxReclaimPerPass = 200; /// A project delete is rare and must be complete, so this bound is generous /// rather than drip-fed; it exists only so a corrupt queue cannot ask for an /// unbounded result set. constexpr uint32_t kMaxRemovePerPass = 100000; constexpr uint32_t kDefaultListLimit = 100; /// Claimable jobs, most overdue first. /// /// `run_after` is the sort key, not `created_at`, for three reasons. It is the /// field that says when the job became eligible, so "oldest first" by it means /// "longest overdue first", which is the queue order an operator expects of a /// scheduler. It is also the field being filtered, so the server sorts and /// filters on one field instead of two (the DB takes a single sort key, so a /// second-level tiebreak on created_at is not expressible anyway). And it keeps /// a backed-off retry honest: complete() pushes run_after into the future, so a /// repeatedly failing job queues behind work enqueued since instead of /// returning to the head of the queue on every pass and starving it. For a job /// that was never delayed run_after is its enqueue time, so the common case is /// still plain arrival order. Client::QueryOptions dueCandidates(uint64_t now, uint32_t limit) { Client::QueryOptions o; o.filters.push_back(Client::Filter::eq("state", "pending")); o.filters.push_back(Client::Filter::lte("run_after", now)); o.sortField = "run_after"; o.sortDescending = false; o.limit = limit; return o; } } // namespace FunctionJob FunctionJob::fromJson(const nlohmann::json& j) { FunctionJob job; job.jobId = j.value("job_id", ""); job.project = j.value("project", ""); job.functionId = j.value("function_id", ""); job.trigger = j.value("trigger", ""); // Bound to a named reference before use: a range-for or a reference into a // temporary parsed subobject dangles (CLAUDE.md). if (j.contains("payload") && j.at("payload").is_object()) { const nlohmann::json& payload = j.at("payload"); job.payload = payload; } job.state = j.value("state", std::string("pending")); job.claimedBy = j.value("claimed_by", ""); job.claimedAt = j.value("claimed_at", 0ull); job.attempts = j.value("attempts", 0u); job.depth = j.value("depth", 0u); job.runAfter = j.value("run_after", 0ull); job.createdAt = j.value("created_at", 0ull); job.lastError = j.value("last_error", ""); return job; } nlohmann::json FunctionJob::toJson() const { // `job_id`, never `id`: the client strips a top-level `id` from stored // bodies, and a job with no readable identity could never be claimed // (claiming needs the id to compare-and-set on) or deleted. return {{"job_id", jobId}, {"project", project}, {"function_id", functionId}, {"trigger", trigger}, {"payload", payload}, {"state", state}, {"claimed_by", claimedBy}, {"claimed_at", claimedAt}, {"attempts", attempts}, {"depth", depth}, {"run_after", runAfter}, {"created_at", createdAt}, {"last_error", lastError}}; } FunctionJobQueue::FunctionJobQueue(DbGateway& db) : db_(db) {} void FunctionJobQueue::ensure() { const std::string c = coll(); if (!db_.client().getCollectionInfo(c).has_value()) db_.client().createCollection(c, 0, /*encrypted*/ false, 0, 0); // Re-open the collection even when it already existed: a collection that // exists on disk but has not been touched since the server restarted does // not surface its rows to find() until something opens it, which is the // trap CollectionRegistry::bootstrap and KeyStore::bootstrap exist for. // Cheapest possible probe - one row, no filters. Client::QueryOptions probe; probe.limit = 1; (void)db_.client().find(c, probe); } std::string FunctionJobQueue::enqueue(const FunctionJob& job) { ensure(); FunctionJob j = job; // The queue owns identity when the caller does not care: a scheduler tick // has no natural id for its job, and an empty id would store every job on // top of the last one. if (j.jobId.empty()) j.jobId = generateApiKey(); if (j.createdAt == 0) j.createdAt = nowSec(); if (j.state.empty()) j.state = "pending"; const std::pair res = db_.client().upsert(coll(), j.toJson(), j.jobId); return res.first.empty() ? std::string() : j.jobId; } bool FunctionJobQueue::hasActive(const std::string& project, const std::string& functionId) { Client::QueryOptions o; o.filters.push_back(Client::Filter::eq("project", project)); o.filters.push_back(Client::Filter::eq("function_id", functionId)); // BOTH states, in one IN: a job that is pending has not run yet and a job // that is claimed is running right now, and single-flight has to refuse a // second copy in either case. Counting only one of them would let the // scheduler stack a second run exactly when the first is slowest. o.filters.push_back(Client::Filter::in("state", nlohmann::json::array({"pending", "claimed"}))); o.limit = 1; return !db_.client().find(coll(), o).empty(); } std::optional FunctionJobQueue::claimNext(const std::string& runnerId, uint32_t maxCandidates) { if (maxCandidates == 0) maxCandidates = 1; const std::string c = coll(); const uint64_t now = nowSec(); const std::vector candidates = db_.client().find(c, dueCandidates(now, maxCandidates)); for (const auto& doc : candidates) { FunctionJob job = FunctionJob::fromJson(doc); if (job.jobId.empty()) continue; // no identity, nothing to compare-and-set on // Compare-and-set on the version the read already gave us. The find // above is not a lock: between it and this write, any number of runners // may be looking at the same row, and the CAS is what settles it. // // `_version` is injected into every row the client returns, so asking // for it separately would be a third round trip for a number already // in hand. A row without one cannot be claimed safely, so it is skipped // rather than claimed with a guessed version. const uint64_t version = documentVersionOf(doc); if (version == 0) continue; job.state = "claimed"; job.claimedBy = runnerId; job.claimedAt = now; job.attempts += 1; if (!db_.client().updateIfVersion(c, job.jobId, job.toJson(), version)) { // Another runner won this row - it may be executing the function at // this instant. Do NOT retry it: re-reading the version and writing // again is how two runners end up running one side-effecting job. // Move to the next candidate instead. (Same three-way reasoning as // RunnerPool's retry rule: "somebody answered" means hands off.) continue; } // The CAS moved the row on by one, and that is the version the caller // must present to complete() - otherwise its completion would be // refused as superseded by its own claim. job.version = version + 1; // Returned as stored, so the caller sees the real attempts count and // can decide whether this is a last chance. return job; } return std::nullopt; } bool FunctionJobQueue::complete(const FunctionJob& job, bool ok, const std::string& error, uint32_t retryAfterSec) { if (job.jobId.empty()) return false; FunctionJob next = job; if (ok) { next.state = "done"; next.lastError.clear(); } else if (retryAfterSec > 0) { next.state = "pending"; next.lastError = error; next.runAfter = nowSec() + retryAfterSec; // Clear the claim: a pending row that still carries a claim timestamp // would be picked up by reclaimStale and have its backoff cancelled. next.claimedBy.clear(); next.claimedAt = 0; } else { next.state = "failed"; next.lastError = error; } // `attempts` is deliberately left as it is, including on success: it is the // history of the job, and the admin list shows "succeeded on attempt 3". // Compare-and-set, not a blind upsert. A claim that went stale can be // reclaimed and handed to another runner while the first is still working; // if that first runner then completed blindly it would overwrite the new // owner - marking `done` a job executing right now, or dragging it back to // `pending`. Refusing a job with no version keeps that path closed rather // than silently degrading to the unsafe write. // No version means the job did not come from claimNext, so there is nothing // to compare against. Refused rather than silently degrading to the unsafe // blind write. Reporting is the caller's: a storage class that logs makes // every test that drives it need a logger. if (job.version == 0) return false; // False here means "somebody else owns this row now", not "the database is // down" - the caller logs it and must NOT retry. return db_.client().updateIfVersion(coll(), job.jobId, next.toJson(), job.version); } uint32_t FunctionJobQueue::reclaimStale(uint32_t timeoutSec, uint32_t maxAttempts) { // 0 means "unlimited" in several places in this codebase (log retention, // TTLs). It must not mean that here: an unlimited retry budget is exactly // the loop this guard exists to stop, where one poisonous job takes down // every runner in turn. Treat it as a budget of one. if (maxAttempts == 0) maxAttempts = 1; const std::string c = coll(); const uint64_t now = nowSec(); const uint64_t cutoff = now > timeoutSec ? now - timeoutSec : 0; Client::QueryOptions o; o.filters.push_back(Client::Filter::eq("state", "claimed")); o.filters.push_back(Client::Filter::lte("claimed_at", cutoff)); o.sortField = "claimed_at"; // the most abandoned first, so a bounded pass does the oldest o.sortDescending = false; o.limit = kMaxReclaimPerPass; uint32_t reclaimed = 0; const std::vector stale = db_.client().find(c, o); for (const auto& doc : stale) { FunctionJob job = FunctionJob::fromJson(doc); if (job.jobId.empty()) continue; const uint64_t version = documentVersionOf(doc); if (version == 0) continue; const bool exhausted = job.attempts >= maxAttempts; if (exhausted) { // Retire it rather than hand it to the next runner. A job that kills // the process running it would otherwise kill every runner in turn, // and the queue would never drain. job.state = "failed"; job.lastError = "abandoned by runner '" + job.claimedBy + "' after " + std::to_string(job.attempts) + " attempt(s)"; } else { job.state = "pending"; job.lastError = "reclaimed from runner '" + job.claimedBy + "': claim went stale"; job.claimedBy.clear(); job.claimedAt = 0; job.runAfter = now; // due immediately; attempts is NOT rewound } // Compare-and-set, not a plain write: the owning runner may be // finishing this job in the window between the find above and here, and // its verdict has to stand. Losing the race means the job was not // stale after all, so it is not counted and not touched. if (!db_.client().updateIfVersion(c, job.jobId, job.toJson(), version)) continue; if (!exhausted) ++reclaimed; } // Only rows actually returned to pending are counted: a retired job was not // recovered, and reporting it as such would make a stuck queue look busy. return reclaimed; } std::optional FunctionJobQueue::get(const std::string& jobId) { if (jobId.empty()) return std::nullopt; if (auto doc = db_.client().get(coll(), jobId)) { FunctionJob job = FunctionJob::fromJson(*doc); if (job.jobId.empty()) job.jobId = jobId; // the body never carries `id` return job; } return std::nullopt; } bool FunctionJobQueue::remove(const std::string& jobId) { if (jobId.empty()) return false; return db_.client().remove(coll(), jobId); } std::vector FunctionJobQueue::list(const std::string& project, uint32_t limit) { if (limit == 0) limit = kDefaultListLimit; Client::QueryOptions o; o.filters.push_back(Client::Filter::eq("project", project)); o.sortField = "created_at"; // arrival order, not due order: this is a history view o.sortDescending = false; o.limit = limit; std::vector out; const std::vector rows = db_.client().find(coll(), o); out.reserve(rows.size()); for (const auto& doc : rows) out.push_back(FunctionJob::fromJson(doc)); return out; } uint32_t FunctionJobQueue::removeForProject(const std::string& project) { const std::string c = coll(); Client::QueryOptions o; o.filters.push_back(Client::Filter::eq("project", project)); o.limit = kMaxRemovePerPass; uint32_t removed = 0; const std::vector rows = db_.client().find(c, o); for (const auto& doc : rows) { // By the body's `job_id`: the client strips a top-level `id`, so the // document id is only readable because it is carried in the body. const std::string jobId = doc.value("job_id", std::string()); if (!jobId.empty() && db_.client().remove(c, jobId)) ++removed; } return removed; } } // namespace svapi