| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143 |
- #pragma once
- #include "db_gateway.hpp"
- #include <nlohmann/json.hpp>
- #include <optional>
- #include <string>
- #include <vector>
- namespace svapi {
- /// One queued run of a function, for a trigger that is not an HTTP request.
- ///
- /// HTTP dispatch is synchronous - somebody is waiting on the socket - so it
- /// never goes through this queue. Cron and database events do, for three
- /// reasons: the work must survive the runner that was going to do it dying
- /// mid-job, several runners must be able to share the load without doing the
- /// same job twice, and a burst of events must not open a connection per event.
- ///
- /// ONE global collection (`vectorapi_function_jobs` in the default project)
- /// with a `project` field, not one per project: a runner claiming work has to
- /// scan a single place, and a per-project queue would make "claim the oldest
- /// due job anywhere" into N queries.
- struct FunctionJob {
- /// `job_id`, not `id`: the database client strips a top-level `id` from
- /// stored bodies - the same reason API keys store `key_id`.
- std::string jobId;
- std::string project;
- std::string functionId;
- /// "cron" or "db". Recorded on the run log so an operator can tell why a
- /// function ran.
- std::string trigger;
- /// What the function receives as ctx: for cron, the scheduled time; for a
- /// database event, the collection, document id, event type and the document.
- nlohmann::json payload = nlohmann::json::object();
- /// pending -> claimed -> done | failed. A claim that goes stale returns to
- /// pending, which is how a runner dying mid-job gets retried elsewhere.
- std::string state = "pending";
- std::string claimedBy; ///< runner id, for attribution and stale detection
- uint64_t claimedAt = 0;
- uint32_t attempts = 0;
- /// How many triggers deep this job is. A function that writes to a table it
- /// watches would otherwise enqueue itself forever; the watcher refuses past
- /// a configured maximum. Carried from day one on purpose - retrofitting a
- /// loop guard is how you get an infinite loop in production.
- uint32_t depth = 0;
- /// Epoch seconds before which this job must not be claimed. Used for the
- /// scheduled time and for backing off a retry.
- uint64_t runAfter = 0;
- uint64_t createdAt = 0;
- std::string lastError;
- /// The row version this job was claimed at. Set by claimNext, and what
- /// makes complete() safe.
- ///
- /// Without it completing is a blind upsert, and a late completion from a
- /// runner whose claim had already gone stale and been reclaimed would
- /// silently overwrite the runner now executing the job - marking `done`
- /// something still running, or resurrecting it to `pending`. Claiming was
- /// airtight and finishing was not.
- ///
- /// 0 means "not claimed through claimNext", and complete() refuses it.
- uint64_t version = 0;
- /// Attempts counts STARTS, not failures: claimNext increments it when it
- /// hands the job out, so the first run sees attempts == 1. Every retry
- /// budget is read against that, so a worker and the stale sweeper agree on
- /// when a job has had enough tries.
- static FunctionJob fromJson(const nlohmann::json& j);
- nlohmann::json toJson() const;
- };
- /// The job queue. Written by vectorapi (the scheduler and the event watcher),
- /// read and claimed by runners.
- class FunctionJobQueue {
- public:
- explicit FunctionJobQueue(DbGateway& db);
- /// Create the queue collection (idempotent), and re-open it so find()
- /// surfaces rows after a restart - the same trap CollectionRegistry::
- /// bootstrap exists for.
- void ensure();
- /// Enqueue. Returns the job id, or empty on failure.
- std::string enqueue(const FunctionJob& job);
- /// Is a job for this function already pending or claimed?
- ///
- /// This is what single-flight is built on: with it true, the scheduler
- /// skips the tick instead of stacking a second copy of a job whose last run
- /// has not finished.
- bool hasActive(const std::string& project, const std::string& functionId);
- /// Claim the oldest due job, atomically. Returns nullopt when there is
- /// nothing to do or when every candidate was won by another runner.
- ///
- /// Claiming is a compare-and-set on the job's version, so two runners
- /// racing for the same row cannot both win - the loser simply moves to the
- /// next candidate. The version comes from the `_version` the read already
- /// carried, so a claim costs two round trips (find, compare-and-set) rather
- /// than three.
- std::optional<FunctionJob> claimNext(const std::string& runnerId, uint32_t maxCandidates = 20);
- /// Mark a claimed job finished. `ok` false records lastError and, when
- /// `retryAfterSec` is non-zero, returns it to pending for another attempt
- /// instead of failing it outright.
- ///
- /// A compare-and-set on `job.version`, so it returns FALSE when the row has
- /// moved on - which is what stops a runner whose claim went stale from
- /// stamping its outcome over the runner that has since taken the job.
- /// A false return means "somebody else owns this now", not "the database
- /// is down"; the caller should log it rather than retry.
- bool complete(const FunctionJob& job, bool ok, const std::string& error,
- uint32_t retryAfterSec = 0);
- /// Return claims older than `timeoutSec` to pending. This is the only thing
- /// that recovers work from a runner that died holding a job, so it has to
- /// run periodically whether or not anything else is happening.
- /// Returns how many were reclaimed.
- uint32_t reclaimStale(uint32_t timeoutSec, uint32_t maxAttempts);
- /// One job by id, whatever its state. The caller must check `project`
- /// before acting on it: an id is global, so finding a row says nothing
- /// about who may touch it.
- std::optional<FunctionJob> get(const std::string& jobId);
- /// Delete one job by id. Returns false when there was nothing to delete.
- /// Says nothing about whether the job may be deleted - a claimed job may be
- /// executing right now, and that is the caller's check.
- bool remove(const std::string& jobId);
- /// Oldest-first view for the admin UI, newest state included.
- std::vector<FunctionJob> list(const std::string& project, uint32_t limit);
- /// Drop every job belonging to a project, for project deletion.
- uint32_t removeForProject(const std::string& project);
- private:
- DbGateway& db_;
- std::string coll() const { return qualify("default", "vectorapi_function_jobs"); }
- };
- } // namespace svapi
|