import { ABANDONED_RESERVATION_MS, IDLE_EVICTION_MS, evictIdleCachesForRepo } from "../ci/cache-api";
import { JOB_TOKEN_MARKER_TTL_MS, purgeExpiredJobTokensForRepo } from "../ci/job-token";
import { reapStaleRunnerJobsForRepo, STALE_RUNNER_MS } from "../ci/runner-api";
import { fireDueSchedulesForRepo } from "../ci/workflow-index";
import { ATTACHMENT_ORPHAN_GRACE_MS, sweepOrphanedAttachmentsForRepo } from "../attachments";
import {
dropHiddenRefsForRepo,
MAX_CLEANUP_ATTEMPTS,
sweepClosedPullRefsForRepo,
UNSWEPT_CLOSED_PULLS,
} from "../git/pull-bridge";
import { WEBHOOK_DELIVERY_RETENTION_MS } from "../integrations/retention";
import type { ScopedValue } from "../scoped-db/types";
import { withJobPerf } from "../perf";
import { indexActivity } from "../activity-index";
import { publishScopeGauges } from "../metering/scope-gauges";
import { ROLLUP_GRACE_MS, rollupScopeSiteUsage } from "../sites/metering";
import { STALE_PULL_ALIASES, sweepClosedPullAliasesForScope } from "../sites/pr-aliases";
import { publishSiteDirectory } from "../sites/directory";
/** Never wake more often than this, however soon something is due (or if a task keeps failing). */
const MIN_INTERVAL_MS = 10 * 1000;
const WEBHOOK_PRUNE_BATCH = 500;
const PENDING_INDEX_BATCH = 200;
const CLOSED_PULL_GRACE_MS = 5 * 60 * 1000;
/** Garbage-collection tasks (expired tokens, idle caches, old deliveries) run at most this often. */
const GC_INTERVAL_MS = 60 * 60 * 1000;
/** A task that threw waits this long before its next attempt. */
const FAILURE_BACKOFF_MS = 5 * 60 * 1000;
type Sql = { exec<T extends Record<string, ScopedValue>>(sql: string, ...params: ScopedValue[]): { toArray(): T[] } };
/**
* Time-driven work of one repository, run by its RepoState alarm instead of crons that scan every repository:
* scheduled workflows, cache eviction, job token expiry, webhook delivery retention, orphaned attachments,
* hidden-ref cleanup retries and stale self-hosted runner jobs. A write to a task's table arms the alarm; the
* alarm runs the tasks that are due and re-arms for the earliest next one, so idle repositories cost nothing.
*/
type Task = {
name: string;