function_jobs.hpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. #pragma once
  2. #include "db_gateway.hpp"
  3. #include <nlohmann/json.hpp>
  4. #include <optional>
  5. #include <string>
  6. #include <vector>
  7. namespace svapi {
  8. /// One queued run of a function, for a trigger that is not an HTTP request.
  9. ///
  10. /// HTTP dispatch is synchronous - somebody is waiting on the socket - so it
  11. /// never goes through this queue. Cron and database events do, for three
  12. /// reasons: the work must survive the runner that was going to do it dying
  13. /// mid-job, several runners must be able to share the load without doing the
  14. /// same job twice, and a burst of events must not open a connection per event.
  15. ///
  16. /// ONE global collection (`vectorapi_function_jobs` in the default project)
  17. /// with a `project` field, not one per project: a runner claiming work has to
  18. /// scan a single place, and a per-project queue would make "claim the oldest
  19. /// due job anywhere" into N queries.
  20. struct FunctionJob {
  21. /// `job_id`, not `id`: the database client strips a top-level `id` from
  22. /// stored bodies - the same reason API keys store `key_id`.
  23. std::string jobId;
  24. std::string project;
  25. std::string functionId;
  26. /// "cron" or "db". Recorded on the run log so an operator can tell why a
  27. /// function ran.
  28. std::string trigger;
  29. /// What the function receives as ctx: for cron, the scheduled time; for a
  30. /// database event, the collection, document id, event type and the document.
  31. nlohmann::json payload = nlohmann::json::object();
  32. /// pending -> claimed -> done | failed. A claim that goes stale returns to
  33. /// pending, which is how a runner dying mid-job gets retried elsewhere.
  34. std::string state = "pending";
  35. std::string claimedBy; ///< runner id, for attribution and stale detection
  36. uint64_t claimedAt = 0;
  37. uint32_t attempts = 0;
  38. /// How many triggers deep this job is. A function that writes to a table it
  39. /// watches would otherwise enqueue itself forever; the watcher refuses past
  40. /// a configured maximum. Carried from day one on purpose - retrofitting a
  41. /// loop guard is how you get an infinite loop in production.
  42. uint32_t depth = 0;
  43. /// Epoch seconds before which this job must not be claimed. Used for the
  44. /// scheduled time and for backing off a retry.
  45. uint64_t runAfter = 0;
  46. uint64_t createdAt = 0;
  47. std::string lastError;
  48. /// The row version this job was claimed at. Set by claimNext, and what
  49. /// makes complete() safe.
  50. ///
  51. /// Without it completing is a blind upsert, and a late completion from a
  52. /// runner whose claim had already gone stale and been reclaimed would
  53. /// silently overwrite the runner now executing the job - marking `done`
  54. /// something still running, or resurrecting it to `pending`. Claiming was
  55. /// airtight and finishing was not.
  56. ///
  57. /// 0 means "not claimed through claimNext", and complete() refuses it.
  58. uint64_t version = 0;
  59. /// Attempts counts STARTS, not failures: claimNext increments it when it
  60. /// hands the job out, so the first run sees attempts == 1. Every retry
  61. /// budget is read against that, so a worker and the stale sweeper agree on
  62. /// when a job has had enough tries.
  63. static FunctionJob fromJson(const nlohmann::json& j);
  64. nlohmann::json toJson() const;
  65. };
  66. /// The job queue. Written by vectorapi (the scheduler and the event watcher),
  67. /// read and claimed by runners.
  68. class FunctionJobQueue {
  69. public:
  70. explicit FunctionJobQueue(DbGateway& db);
  71. /// Create the queue collection (idempotent), and re-open it so find()
  72. /// surfaces rows after a restart - the same trap CollectionRegistry::
  73. /// bootstrap exists for.
  74. void ensure();
  75. /// Enqueue. Returns the job id, or empty on failure.
  76. std::string enqueue(const FunctionJob& job);
  77. /// Is a job for this function already pending or claimed?
  78. ///
  79. /// This is what single-flight is built on: with it true, the scheduler
  80. /// skips the tick instead of stacking a second copy of a job whose last run
  81. /// has not finished.
  82. bool hasActive(const std::string& project, const std::string& functionId);
  83. /// Claim the oldest due job, atomically. Returns nullopt when there is
  84. /// nothing to do or when every candidate was won by another runner.
  85. ///
  86. /// Claiming is a compare-and-set on the job's version, so two runners
  87. /// racing for the same row cannot both win - the loser simply moves to the
  88. /// next candidate. The version comes from the `_version` the read already
  89. /// carried, so a claim costs two round trips (find, compare-and-set) rather
  90. /// than three.
  91. std::optional<FunctionJob> claimNext(const std::string& runnerId, uint32_t maxCandidates = 20);
  92. /// Mark a claimed job finished. `ok` false records lastError and, when
  93. /// `retryAfterSec` is non-zero, returns it to pending for another attempt
  94. /// instead of failing it outright.
  95. ///
  96. /// A compare-and-set on `job.version`, so it returns FALSE when the row has
  97. /// moved on - which is what stops a runner whose claim went stale from
  98. /// stamping its outcome over the runner that has since taken the job.
  99. /// A false return means "somebody else owns this now", not "the database
  100. /// is down"; the caller should log it rather than retry.
  101. bool complete(const FunctionJob& job, bool ok, const std::string& error,
  102. uint32_t retryAfterSec = 0);
  103. /// Return claims older than `timeoutSec` to pending. This is the only thing
  104. /// that recovers work from a runner that died holding a job, so it has to
  105. /// run periodically whether or not anything else is happening.
  106. /// Returns how many were reclaimed.
  107. uint32_t reclaimStale(uint32_t timeoutSec, uint32_t maxAttempts);
  108. /// One job by id, whatever its state. The caller must check `project`
  109. /// before acting on it: an id is global, so finding a row says nothing
  110. /// about who may touch it.
  111. std::optional<FunctionJob> get(const std::string& jobId);
  112. /// Delete one job by id. Returns false when there was nothing to delete.
  113. /// Says nothing about whether the job may be deleted - a claimed job may be
  114. /// executing right now, and that is the caller's check.
  115. bool remove(const std::string& jobId);
  116. /// Oldest-first view for the admin UI, newest state included.
  117. std::vector<FunctionJob> list(const std::string& project, uint32_t limit);
  118. /// Drop every job belonging to a project, for project deletion.
  119. uint32_t removeForProject(const std::string& project);
  120. private:
  121. DbGateway& db_;
  122. std::string coll() const { return qualify("default", "vectorapi_function_jobs"); }
  123. };
  124. } // namespace svapi