#include "function_scheduler.hpp" #include "db_gateway.hpp" #include "function_jobs.hpp" #include "function_record.hpp" #include "function_registry.hpp" #include "functions/cron.hpp" #include "functions/timezone.hpp" #include #include #include #include #include namespace svapi { namespace { /// The key under which a function's last fired minute is remembered. '\x1f' /// (unit separator) cannot appear in a project name - the project charset is /// restricted because /fn/{project}/* is unauthenticated - so two different /// (project, function) pairs cannot collide on one key. std::string lastFiredKey(const std::string& project, const std::string& functionId) { return project + '\x1f' + functionId; } } // namespace FunctionScheduler::FunctionScheduler(DbGateway& db, FunctionRegistry& registry, FunctionJobQueue& jobs, FunctionSchedulerOptions opts) : db_(db), registry_(registry), jobs_(jobs), opts_(opts) { // A tick interval of a minute or more silently drops schedules, so refuse to // carry a configured value that cannot work. Clamping loudly beats firing // "most" minutes and leaving an operator to wonder which ones. if (opts_.tickIntervalSec == 0 || opts_.tickIntervalSec >= 60) { spdlog::warn("function scheduler tick interval {}s cannot see every cron minute; " "using 20s", opts_.tickIntervalSec); opts_.tickIntervalSec = 20; } } FunctionScheduler::~FunctionScheduler() { stop(); } void FunctionScheduler::start() { { std::lock_guard lk(m_); if (started_) return; started_ = true; stop_ = false; } th_ = std::thread([this] { loop(); }); spdlog::info("function scheduler started (tick {}s, reclaim {}s, claim timeout {}s)", opts_.tickIntervalSec, opts_.reclaimIntervalSec, opts_.claimTimeoutSec); } void FunctionScheduler::stop() { { std::lock_guard lk(m_); if (!started_) return; stop_ = true; } cv_.notify_all(); if (th_.joinable()) th_.join(); std::lock_guard lk(m_); started_ = false; } bool FunctionScheduler::running() const { std::lock_guard lk(m_); return started_ && !stop_; } uint32_t FunctionScheduler::reclaimOnce() { std::lock_guard pass(passM_); try { const uint32_t n = jobs_.reclaimStale(opts_.claimTimeoutSec, opts_.maxAttempts); // Worth an info line: a non-zero count means a runner died holding work, // which is the kind of thing an operator wants to see in the journal // rather than infer from a job that ran twice. if (n > 0) spdlog::info("reclaimed {} stale function job(s)", n); return n; } catch (const std::exception& e) { spdlog::warn("function job reclaim failed: {}", e.what()); return 0; } } uint32_t FunctionScheduler::tickOnce(std::time_t now) { std::lock_guard pass(passM_); const std::time_t minute = minuteFloor(now); uint32_t enqueued = 0; std::unordered_map stillPresent; std::vector projects; try { projects = db_.listProjects(); } catch (const std::exception& e) { // No project list means no pass. Deliberately not fatal and deliberately // not remembered: the next tick tries again, and because nothing was // recorded in lastFired_, a minute lost to a database blip can still // fire on a later tick within the same minute. spdlog::warn("function scheduler could not list projects: {}", e.what()); return 0; } for (const std::string& project : projects) { std::vector rows; try { rows = registry_.list(project); } catch (const std::exception& e) { spdlog::warn("function scheduler could not read registry for '{}': {}", project, e.what()); // Keep this project's lastFired_ entries: dropping them on a // transient read failure would re-fire the current minute once the // read recovers. for (const auto& [key, when] : lastFired_) if (key.rfind(project + '\x1f', 0) == 0) stillPresent[key] = when; continue; } for (const FunctionRecord& row : rows) { // A disabled or invalid function does not run. Its lastFired_ entry // is dropped with it, so re-enabling starts from "has not fired", // which is the same thing a restart does. if (!row.enabled || !row.valid) continue; const functions::ParseResult parsed = functions::parseDescriptor(row.descriptor); if (!parsed.ok || parsed.descriptor.type != functions::TriggerType::Cron) continue; std::string cronError; const std::optional expr = functions::CronExpr::parse(parsed.descriptor.schedule, &cronError); if (!expr) { // The write path validates the schedule with this same parser, // so reaching here means a row was written by an older or // broken path. Say so once per tick rather than silently never // firing, which is indistinguishable from a broken scheduler. spdlog::warn("cron function {}/{} has an unusable schedule '{}': {}", project, row.functionId, parsed.descriptor.schedule, cronError); continue; } const std::string key = lastFiredKey(project, row.functionId); const auto it = lastFired_.find(key); const std::time_t last = it == lastFired_.end() ? 0 : it->second; stillPresent[key] = last; // The descriptor's `tz`, empty for a schedule that did not declare // one. It has to reach the matcher: evaluated in UTC instead, an // 08:00 Budapest schedule fires at 09:00 local in winter and 10:00 // in summer, and a schedule that drifts by an hour twice a year is // not something anybody notices quickly. const std::string& zone = parsed.descriptor.timezone; if (!zone.empty() && !functions::timezoneKnown(zone)) { // The write path validates `tz` against the same host tz // database, so reaching here means the row predates that check // or tzdata went away under us. Never firing is the safe // answer - a silent UTC fallback would move the author's 08:00 // report - but it must be said out loud, because "never fires" // and "broken scheduler" look identical from outside. spdlog::warn("cron function {}/{} declares time zone '{}', which this host " "does not know; it will not fire until tzdata provides it", project, row.functionId, zone); continue; } const functions::CronExpr e = *expr; if (!cronDue([&e, &zone](std::time_t t) { return e.matchesIn(t, zone); }, now, last)) continue; bool active = false; try { active = jobs_.hasActive(project, row.functionId); } catch (const std::exception& ex) { // Unknown whether a job is active. Treat it as active: skipping // a tick loses one run, queueing a second copy of a job that is // already running breaks the guarantee the author asked for. spdlog::warn("single-flight check failed for {}/{}, skipping this tick: {}", project, row.functionId, ex.what()); active = true; } if (skipForSingleFlight(parsed.descriptor.singleFlight, active)) { spdlog::info("cron tick skipped for {}/{}: previous job still pending or " "claimed (single flight)", project, row.functionId); // The minute is consumed even though nothing was queued, so the // next two ticks inside this minute do not re-log the same skip. stillPresent[key] = minute; continue; } FunctionJob job; // jobId is left empty: the queue assigns it and enqueue() returns it. job.project = project; job.functionId = row.functionId; job.trigger = "cron"; job.payload = nlohmann::json{{"schedule", parsed.descriptor.schedule}, {"scheduled_at", static_cast(minute)}}; // A cron run starts a trigger chain rather than continuing one, so it // is always depth 0. If it writes to a watched table, the event // watcher is what counts from here. job.depth = 0; job.runAfter = static_cast(minute); job.createdAt = static_cast(now); std::string jobId; try { jobId = jobs_.enqueue(job); } catch (const std::exception& ex) { spdlog::warn("could not enqueue cron job for {}/{}: {}", project, row.functionId, ex.what()); } if (jobId.empty()) { // Not recorded as fired, so a later tick in the same minute can // still get this run out. Losing a run to a database blip when a // retry was available would be our bug, not the database's. spdlog::warn("cron job for {}/{} was not enqueued; will retry this minute", project, row.functionId); continue; } stillPresent[key] = minute; ++enqueued; spdlog::debug("enqueued cron job {} for {}/{}", jobId, project, row.functionId); } } // Prune: a function that no longer exists, or is no longer an enabled valid // cron function, must not keep an entry forever. The map is rebuilt from // what this pass actually saw. lastFired_ = std::move(stillPresent); return enqueued; } void FunctionScheduler::loop() { std::time_t lastReclaim = 0; for (;;) { const std::time_t now = std::time(nullptr); try { tickOnce(now); } catch (const std::exception& e) { // The loop must outlive any single bad pass: a scheduler that dies // on one exception stops every schedule on the host, and nothing // restarts it short of a service restart. spdlog::warn("function scheduler tick failed: {}", e.what()); } if (lastReclaim == 0 || now - lastReclaim >= static_cast(opts_.reclaimIntervalSec)) { reclaimOnce(); lastReclaim = now; } std::unique_lock lk(m_); cv_.wait_for(lk, std::chrono::seconds(opts_.tickIntervalSec), [this] { return stop_; }); if (stop_) return; } } } // namespace svapi