scheduler

package
v0.16.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 34 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package scheduler manages background job schedulers for checkin, balance, cleanup, and aggregation.

Package scheduler implements the 15+ background schedulers from. Each scheduler implements the Scheduler interface and is started/stopped by the registry on app startup/shutdown.

Index

Constants

View Source
const ScheduleSpecVersion = 1

ScheduleSpecVersion is the current version of the semantic schedule spec. Version is embedded in persisted JSON so future format changes can be detected instead of silently misinterpreting old documents.

Variables

This section is empty.

Functions

func ApplyProbeOutcome

func ApplyProbeOutcome(
	ctx context.Context,
	recorder ChannelHealthRecorder,
	target ProbeTarget,
	outcome ProbeOutcome,
) (string, error)

ApplyProbeOutcome is a pure helper used by tests and optional direct callers. It maps a ProbeOutcome onto the recorder without requiring a live DB target load.

func GetActiveChannelIDsFromProvider

func GetActiveChannelIDsFromProvider() []int64

GetActiveChannelIDsFromProvider returns IDs from the registered provider. Returns nil when no provider is registered.

func ParseCronExpr

func ParseCronExpr(expr string) error

ParseCronExpr tries to parse a cron expression. Auto-converts 5-field expressions to 6-field. Returns error if invalid.

func RandomCronInWindow

func RandomCronInWindow(start, end string) (string, error)

RandomCronInWindow picks a random HH:mm inside [start, end] and returns a daily cron expression "m h * * *" (5-field). Bounds are "HH:mm" in 24h format; start must be <= end. E1: the roll is re-done per scheduler start / schedule update, giving load spreading + anti- fingerprint behavior for daily tasks like check-in without a re-roll job.

func ResetLeasePressureForTest

func ResetLeasePressureForTest()

ResetLeasePressureForTest clears backoff state (tests only).

func ScheduleToCron added in v0.10.0

func ScheduleToCron(spec ScheduleSpec) (string, error)

ScheduleToCron converts a semantic ScheduleSpec back to a cron expression. When the spec's semantic fields still match the original expression it returns the original bytes unchanged; otherwise it generates a normalized expression. Type "window" has no deterministic cron (the runtime re-rolls a random time inside the window) and returns the preserved expression only.

func SetActiveChannelIDsProvider

func SetActiveChannelIDsProvider(fn func() []int64)

SetActiveChannelIDsProvider registers (or clears with nil) the active-channel ID source used by ChannelRecoveryScheduler.loadActiveCandidates.

func SetDefaultSiteAnnouncementSyncFunc

func SetDefaultSiteAnnouncementSyncFunc(fn SiteAnnouncementSyncFunc)

SetDefaultSiteAnnouncementSyncFunc installs the process-wide sync implementation used by NewSiteAnnouncementScheduler when no per-instance SyncFunc is set. Safe to call before StartBackgroundServices (routes register first).

func SetGlobalModelProbeScheduler

func SetGlobalModelProbeScheduler(s *ModelProbeScheduler)

SetGlobalModelProbeScheduler registers the running scheduler for admin triggers.

func ValidateCronExpr

func ValidateCronExpr(expr string) bool

ValidateCronExpr validates a cron expression using robfig/cron parser with seconds field. Auto-converts 5-field expressions to 6-field. Returns true if the expression is valid. Thin wrapper over config.ValidateCronExpr (the canonical implementation).

Types

type AdminBackgroundTaskRetentionScheduler added in v0.13.0

type AdminBackgroundTaskRetentionScheduler = RetentionScheduler

AdminBackgroundTaskRetentionScheduler periodically prunes terminal admin_background_tasks rows older than a 30-day window. Without this job the table grows unboundedly (no DELETE path existed), forcing full-scan + sort on every GET /api/tasks list. Implemented by the shared RetentionScheduler.

type AdminSnapshotScheduler

type AdminSnapshotScheduler struct {
	// contains filtered or unexported fields
}

AdminSnapshotScheduler periodically warms admin dashboard snapshots and prunes expired ones.

func NewAdminSnapshotScheduler

func NewAdminSnapshotScheduler(cfg *config.Config, usage *UsageAggregationScheduler) *AdminSnapshotScheduler

NewAdminSnapshotScheduler creates a new admin snapshot warm scheduler.

func (*AdminSnapshotScheduler) Name

func (s *AdminSnapshotScheduler) Name() string

func (*AdminSnapshotScheduler) Start

func (*AdminSnapshotScheduler) Stop

func (s *AdminSnapshotScheduler) Stop() error

func (*AdminSnapshotScheduler) WarmOnce

func (s *AdminSnapshotScheduler) WarmOnce()

WarmOnce performs a single warm pass. Safe to call externally. De-duplication happens under the mutex inside runWarm: reading inFlight here without the lock raced the ticker path's writes (observed under -race). Returns immediately when a pass is already in flight, same as before.

type BackupWebdavConfig

type BackupWebdavConfig struct {
	Enabled         bool   `json:"enabled"`
	FileURL         string `json:"fileUrl"`
	Username        string `json:"username"`
	Password        string `json:"password"`
	ExportType      string `json:"exportType"`
	AutoSyncEnabled bool   `json:"autoSyncEnabled"`
	AutoSyncCron    string `json:"autoSyncCron"`
}

BackupWebdavConfig holds the WebDAV backup configuration.

type BackupWebdavScheduler

type BackupWebdavScheduler struct {
	// contains filtered or unexported fields
}

BackupWebdavScheduler periodically exports backups to a WebDAV endpoint.

func NewBackupWebdavScheduler

func NewBackupWebdavScheduler(cfg *config.Config) *BackupWebdavScheduler

NewBackupWebdavScheduler creates a new WebDAV backup scheduler.

func (*BackupWebdavScheduler) Name

func (s *BackupWebdavScheduler) Name() string

func (*BackupWebdavScheduler) Reload

func (s *BackupWebdavScheduler) Reload() error

Reload reads the latest config and reschedules the cron job.

func (*BackupWebdavScheduler) Start

func (*BackupWebdavScheduler) Stop

func (s *BackupWebdavScheduler) Stop() error

type BalanceScheduler

type BalanceScheduler struct {
	// contains filtered or unexported fields
}

BalanceScheduler periodically refreshes account balances.

func NewBalanceScheduler

func NewBalanceScheduler(cfg *config.Config) *BalanceScheduler

NewBalanceScheduler creates a new balance refresh scheduler.

func (*BalanceScheduler) Name

func (s *BalanceScheduler) Name() string

Name returns "balance-refresh".

func (*BalanceScheduler) SetEnabled added in v0.16.19

func (s *BalanceScheduler) SetEnabled(enabled bool) error

SetEnabled hot-toggles the global balance-refresh switch (#1027). Disabling stops the running cron job entirely; enabling (re)resolves the cron from DB settings (same contract as Start) and schedules it. Callers serialize this against other scheduler updates via app.updateMu.

func (*BalanceScheduler) Start

func (s *BalanceScheduler) Start(ctx context.Context) error

Start begins periodic balance refresh. Loads the cron expression from DB settings or falls back to config default. Honors the global kill switch (env BALANCE_REFRESH_ENABLED / runtime setting balanceRefreshEnabled, issue #1027): when disabled, no cron job is scheduled at all.

func (*BalanceScheduler) Stop

func (s *BalanceScheduler) Stop() error

Stop halts the balance refresh scheduler.

func (*BalanceScheduler) UpdateCron

func (s *BalanceScheduler) UpdateCron(cronExpr string) error

UpdateCron updates the cron expression at runtime.

type BatchProbeResult

type BatchProbeResult struct {
	Target        ProbeTarget
	Outcome       ProbeOutcome
	HealthApplied bool
}

BatchProbeResult is one row of an operator-initiated batch verification . HealthApplied reports whether the outcome was recorded into routing health/cooldown; a nil recorder leaves it false.

type ChannelHealthProbe

type ChannelHealthProbe interface {
	ProbeChannel(ctx context.Context, target ProbeTarget) (ProbeOutcome, error)
}

ChannelHealthProbe executes one lightweight request against a channel/model. Implementations live outside scheduler (proxy/platform) and are injected at boot. Returning an error is treated as an inconclusive outcome (no health mutation).

type ChannelHealthRecorder

type ChannelHealthRecorder interface {
	RecordProbeSuccess(ctx context.Context, channelID int64, latencyMs float64, modelName *string, actualAccountID *int64) error
	RecordProbeFailure(ctx context.Context, channelID int64, httpStatus *int, errorText *string, modelName *string, actualAccountID *int64) error
}

ChannelHealthRecorder applies probe outcomes to routing health/cooldown. Implementations wrap routing.TokenRouter.RecordProbeSuccess/RecordProbeFailure. Must never mark credentials/accounts expired.

type ChannelRecoveryScheduler

type ChannelRecoveryScheduler struct {
	// contains filtered or unexported fields
}

ChannelRecoveryScheduler periodically sweeps channels that are in cooldown or active to probe if they have recovered.

func NewChannelRecoveryScheduler

func NewChannelRecoveryScheduler(cfg *config.Config) *ChannelRecoveryScheduler

NewChannelRecoveryScheduler creates a new channel recovery probe scheduler.

func (*ChannelRecoveryScheduler) Name

func (s *ChannelRecoveryScheduler) Name() string

func (*ChannelRecoveryScheduler) Start

func (*ChannelRecoveryScheduler) Stop

func (s *ChannelRecoveryScheduler) Stop() error

type CheckinScheduler

type CheckinScheduler struct {
	// contains filtered or unexported fields
}

CheckinScheduler implements dual-mode (cron + interval) checkin scheduling. Mirrors TS checkinScheduler.ts.

func NewCheckinScheduler

func NewCheckinScheduler(cfg *config.Config) *CheckinScheduler

NewCheckinScheduler creates a new checkin scheduler.

func (*CheckinScheduler) Name

func (s *CheckinScheduler) Name() string

Name returns "checkin".

func (*CheckinScheduler) ResetAttempts

func (s *CheckinScheduler) ResetAttempts()

ResetAttempts clears the interval attempt map (for tests).

func (*CheckinScheduler) SetEnabled added in v0.16.19

func (s *CheckinScheduler) SetEnabled(enabled bool)

SetEnabled hot-toggles the global check-in switch (#1027). Disabling stops the running cron/interval schedule; enabling restarts with the current mode and schedule (same behavior as a fresh Start, including catch-up). Callers serialize this against other scheduler updates via app.updateMu.

func (*CheckinScheduler) Start

func (s *CheckinScheduler) Start(ctx context.Context) error

Start starts the checkin scheduler. Loads settings from DB, applies fallbacks, and runs the selected mode.

func (*CheckinScheduler) Stop

func (s *CheckinScheduler) Stop() error

Stop stops the checkin scheduler.

func (*CheckinScheduler) UpdateCheckinSchedule

func (s *CheckinScheduler) UpdateCheckinSchedule(mode, cronExpr string, intervalHours int, windowStart, windowEnd string) error

UpdateCheckinSchedule updates the checkin configuration at runtime. Mirrors TS updateCheckinSchedule(). windowStart/windowEnd are HH:mm bounds for E1 window mode (ignored in cron/interval modes).

type DailySummaryScheduler

type DailySummaryScheduler struct {
	// contains filtered or unexported fields
}

DailySummaryScheduler sends a daily summary notification at 23:58 daily.

func NewDailySummaryScheduler

func NewDailySummaryScheduler() *DailySummaryScheduler

NewDailySummaryScheduler creates a new daily summary scheduler.

func (*DailySummaryScheduler) Name

func (s *DailySummaryScheduler) Name() string

func (*DailySummaryScheduler) Start

func (*DailySummaryScheduler) Stop

func (s *DailySummaryScheduler) Stop() error

type LogCleanupScheduler

type LogCleanupScheduler struct {
	// contains filtered or unexported fields
}

LogCleanupScheduler cleans up proxy log records and event records.

func NewLogCleanupScheduler

func NewLogCleanupScheduler(cfg *config.Config) *LogCleanupScheduler

func (*LogCleanupScheduler) Name

func (s *LogCleanupScheduler) Name() string

func (*LogCleanupScheduler) Start

func (s *LogCleanupScheduler) Start(ctx context.Context) error

func (*LogCleanupScheduler) Stop

func (s *LogCleanupScheduler) Stop() error

func (*LogCleanupScheduler) UpdateSettings

func (s *LogCleanupScheduler) UpdateSettings(cronExpr string, usageEnabled, programEnabled bool, retentionDays int) error

type ModelProbeScheduler

type ModelProbeScheduler struct {
	// contains filtered or unexported fields
}

ModelProbeScheduler periodically probes model/channel availability with a lightweight request so routing can avoid dead channels before user traffic fails. Supports account-level lease to prevent concurrent probes on the same account.

func GetGlobalModelProbeScheduler

func GetGlobalModelProbeScheduler() *ModelProbeScheduler

GetGlobalModelProbeScheduler returns the registered scheduler (may be nil).

func NewModelProbeScheduler

func NewModelProbeScheduler(cfg *config.Config) *ModelProbeScheduler

NewModelProbeScheduler creates a new model availability probe scheduler.

func (*ModelProbeScheduler) LastRunSummary

func (s *ModelProbeScheduler) LastRunSummary() ProbeRunSummary

LastRunSummary returns a copy of the most recent probe pass summary.

func (*ModelProbeScheduler) Name

func (s *ModelProbeScheduler) Name() string

func (*ModelProbeScheduler) ProbeBatch

func (s *ModelProbeScheduler) ProbeBatch(ctx context.Context, targets []ProbeTarget, timeoutMs int) []BatchProbeResult

ProbeBatch runs immediate lightweight probes for explicit targets (admin batch model verification, It reuses the injected probe executor and, when a recorder is wired, applies health outcomes — but never acquires account leases: this is a one-shot operator action, not a background pass. A nil scheduler or missing executor yields skipped results with no health mutation.

func (*ModelProbeScheduler) ProbeSite

func (s *ModelProbeScheduler) ProbeSite(siteID int64) (results []ProbeSiteResult, available, unavailable int)

ProbeSite runs probes for active channels on a site (bounded to 32) and returns the aggregated results. It is a thin wrapper around ProbeSiteIncremental that collects every result under a non-cancellable background context. Kept for callers that want a single batch response (app probe-wire tests, recovery paths).

func (*ModelProbeScheduler) ProbeSiteIncremental added in v0.13.0

func (s *ModelProbeScheduler) ProbeSiteIncremental(ctx context.Context, siteID int64, onResult func(ProbeSiteResult)) error

ProbeSiteIncremental runs probes for active channels on a site (bounded to 32 targets) with bounded concurrency and streams each result to onResult as soon as it completes. It respects ctx cancellation: on cancel it stops scheduling new probes and returns ctx.Err(). In-flight probes are allowed to finish (they carry their own per-target timeout via probeOne) but their results are not streamed to a cancelled caller.

onResult may be nil. A nil scheduler, non-positive siteID, or missing DB yields a no-op (returns nil). A target-load error is delivered as a single ProbeSiteResult{Status:"error"} and also returned as err.

func (*ModelProbeScheduler) RecentRunSummaries added in v0.16.8

func (s *ModelProbeScheduler) RecentRunSummaries() []ProbeRunSummary

RecentRunSummaries returns up to probeRunHistoryDepth completed passes, newest first. Only background passes (runProbe) land in the ring buffer — one-shot site probe-now passes are not scheduler runs and are excluded.

func (*ModelProbeScheduler) ReleaseAccountLease

func (s *ModelProbeScheduler) ReleaseAccountLease(accountID int64)

ReleaseAccountLease releases the lease for an account.

func (*ModelProbeScheduler) ResetLeases

func (s *ModelProbeScheduler) ResetLeases()

ResetLeases clears all account leases (for tests).

func (*ModelProbeScheduler) SetEnabled added in v0.16.19

func (s *ModelProbeScheduler) SetEnabled(enabled bool) error

SetEnabled hot-toggles the model availability probe at runtime (#1027). Mirrors the boolean-feature-toggle contract: the caller has already persisted cfg.ModelAvailabilityProbeEnabled + the DB setting; this applies the change to the running ticker without a restart. Disabling stops the background probe loop; enabling restarts it (no immediate first run, same as Start). Admin probe-now paths stay available either way.

func (*ModelProbeScheduler) SetHealthRecorder

func (s *ModelProbeScheduler) SetHealthRecorder(recorder ChannelHealthRecorder)

SetHealthRecorder injects the routing health/cooldown recorder.

func (*ModelProbeScheduler) SetProbeExecutor

func (s *ModelProbeScheduler) SetProbeExecutor(probe ChannelHealthProbe)

SetProbeExecutor injects the lightweight probe implementation.

func (*ModelProbeScheduler) Start

func (s *ModelProbeScheduler) Start(ctx context.Context) error

func (*ModelProbeScheduler) Stop

func (s *ModelProbeScheduler) Stop() error

func (*ModelProbeScheduler) TriggerNow

func (s *ModelProbeScheduler) TriggerNow(sync bool) ProbeRunSummary

TriggerNow runs one probe pass asynchronously (or sync if sync=true). Used by admin /api/models/probe and site probe-now.

func (*ModelProbeScheduler) TryAcquireAccountLease

func (s *ModelProbeScheduler) TryAcquireAccountLease(accountID int64) bool

TryAcquireAccountLease attempts to acquire a lease for probing a specific account. Returns true if the lease was acquired.

type ModelSyncScheduler added in v0.16.16

type ModelSyncScheduler struct {
	// contains filtered or unexported fields
}

ModelSyncScheduler periodically refreshes upstream model lists for all candidate accounts (#1005). Structure mirrors BalanceScheduler: DB setting model_sync_cron overrides the env default; UpdateCron hot-reloads the running runner; the job runs under the cluster-wide scheduler lease.

func NewModelSyncScheduler added in v0.16.16

func NewModelSyncScheduler() *ModelSyncScheduler

NewModelSyncScheduler creates a new model sync scheduler. The cron state lives in the runtime-settings snapshot (hot-updated by settings apply).

func (*ModelSyncScheduler) Name added in v0.16.16

func (s *ModelSyncScheduler) Name() string

Name returns "model-sync".

func (*ModelSyncScheduler) Start added in v0.16.16

func (s *ModelSyncScheduler) Start(ctx context.Context) error

Start begins periodic model sync. Loads the cron expression from DB settings or falls back to config default.

func (*ModelSyncScheduler) Stop added in v0.16.16

func (s *ModelSyncScheduler) Stop() error

Stop halts the model sync scheduler.

func (*ModelSyncScheduler) UpdateCron added in v0.16.16

func (s *ModelSyncScheduler) UpdateCron(cronExpr string) error

UpdateCron updates the cron expression at runtime.

type OAuthRefreshResult

type OAuthRefreshResult struct {
	Scanned             int
	Refreshed           int
	Failed              int
	Skipped             int
	RefreshedAccountIDs []int64
	FailedAccountIDs    []int64
}

OAuthRefreshResult is the outcome of a single refresh pass.

type OAuthRefreshScheduler

type OAuthRefreshScheduler struct {
	// contains filtered or unexported fields
}

OAuthRefreshScheduler periodically scans OAuth accounts and refreshes tokens nearing expiry. Mirrors the TS oauthRefreshScheduler.ts.

func NewOAuthRefreshScheduler

func NewOAuthRefreshScheduler(cfg *config.Config) *OAuthRefreshScheduler

NewOAuthRefreshScheduler creates a new OAuth token refresh scheduler.

func (*OAuthRefreshScheduler) Name

func (s *OAuthRefreshScheduler) Name() string

func (*OAuthRefreshScheduler) Start

func (*OAuthRefreshScheduler) Stop

func (s *OAuthRefreshScheduler) Stop() error

type ProbeOutcome

type ProbeOutcome struct {
	Status    string
	LatencyMs float64
	// HTTPStatus is optional; 0 means unknown / transport error.
	HTTPStatus int
	ErrorText  string
}

ProbeOutcome is the result of a single lightweight probe attempt. Status is one of: success | failure | inconclusive | skipped.

type ProbeRunSummary

type ProbeRunSummary struct {
	AccountsConsidered int
	AccountsProbed     int
	TargetsScanned     int
	Success            int
	Failed             int
	Inconclusive       int
	Skipped            int
	StartedAtMs        int64
	CompletedAtMs      int64
}

ProbeRunSummary summarizes one background probe pass.

type ProbeSiteResult

type ProbeSiteResult struct {
	ChannelID int64   `json:"channelId"`
	AccountID int64   `json:"accountId"`
	Model     string  `json:"model"`
	Status    string  `json:"status"`
	LatencyMs float64 `json:"latencyMs"`
	Error     string  `json:"error,omitempty"`
}

ProbeSiteResult is one model outcome for admin probe-now.

type ProbeTarget

type ProbeTarget struct {
	ChannelID int64
	AccountID int64
	SiteID    int64
	ModelName string
}

ProbeTarget is one lightweight channel/model pair the background probe may hit.

type ProjectionPassResult

type ProjectionPassResult struct {
	ProcessedLogs int
	OrphanLogs    int
	WatermarkID   int64
	Recomputed    bool
}

OrphanLogs counts proxy_logs without a site join (missing account/site). They still advance the watermark so projection does not stall, but they do not contribute to site/model aggregates (known limitation).

type ProxyFileRetentionScheduler

type ProxyFileRetentionScheduler = RetentionScheduler

ProxyFileRetentionScheduler periodically prunes expired proxy files. Implemented by the shared RetentionScheduler.

type ProxyLogRetentionScheduler

type ProxyLogRetentionScheduler = RetentionScheduler

ProxyLogRetentionScheduler is a legacy fallback for cleaning up proxy logs when the main log_cleanup system is not configured (logCleanupConfigured=false). Implemented by the shared RetentionScheduler.

type ProxyVideoTaskRetentionScheduler

type ProxyVideoTaskRetentionScheduler = RetentionScheduler

ProxyVideoTaskRetentionScheduler periodically prunes aged proxy_video_tasks rows. Disabled when ProxyVideoTaskRetentionDays <= 0 (default). Implemented by the shared RetentionScheduler.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry manages all registered schedulers.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new empty scheduler registry.

func (*Registry) List

func (r *Registry) List() []string

List returns the names of all registered schedulers.

func (*Registry) Register

func (r *Registry) Register(s Scheduler)

Register adds a scheduler to the registry.

func (*Registry) StartAll

func (r *Registry) StartAll(ctx context.Context)

StartAll starts all registered schedulers. Each runs in its own goroutine with panic recovery so a single scheduler panic does not affect others.

func (*Registry) StopAll

func (r *Registry) StopAll()

StopAll stops all registered schedulers, logging errors but continuing through all schedulers. Stops run concurrently and the call is bounded by registryStopBudget so a stuck Stop cannot stall graceful shutdown.

func (*Registry) StopAllWithTimeout added in v0.16.8

func (r *Registry) StopAllWithTimeout(budget time.Duration)

StopAllWithTimeout stops all registered schedulers concurrently, waiting up to budget for every Stop to return. Each scheduler's Stop is internally bounded (see cron.go), so this outer deadline only matters if a Stop hangs outright. Stops still running when the budget expires are logged and left to finish on their own (process exit follows shortly after).

type RetentionScheduler added in v0.12.0

type RetentionScheduler struct {
	// contains filtered or unexported fields
}

RetentionScheduler prunes rows older than a per-config retention window on a fixed interval, under a scheduler lease (multi-instance safe).

func NewAdminBackgroundTaskRetentionScheduler added in v0.13.0

func NewAdminBackgroundTaskRetentionScheduler(cfg *config.Config) *RetentionScheduler

NewAdminBackgroundTaskRetentionScheduler creates the admin background task retention scheduler. It deletes only rows whose status is 'succeeded' or 'failed' and whose created_at is older than the 30-day cutoff, so pending and running tasks are always retained.

func NewProxyFileRetentionScheduler

func NewProxyFileRetentionScheduler(cfg *config.Config) *RetentionScheduler

NewProxyFileRetentionScheduler creates a new proxy file retention scheduler.

func NewProxyLogRetentionScheduler

func NewProxyLogRetentionScheduler(cfg *config.Config) *RetentionScheduler

NewProxyLogRetentionScheduler creates a new proxy log retention scheduler.

func NewProxyVideoTaskRetentionScheduler

func NewProxyVideoTaskRetentionScheduler(cfg *config.Config) *RetentionScheduler

NewProxyVideoTaskRetentionScheduler creates a video task retention scheduler.

func NewRetentionScheduler added in v0.12.0

func NewRetentionScheduler(cfg *config.Config, opts RetentionSchedulerOptions) *RetentionScheduler

NewRetentionScheduler builds a generic retention scheduler.

func (*RetentionScheduler) Name added in v0.12.0

func (s *RetentionScheduler) Name() string

func (*RetentionScheduler) Start added in v0.12.0

func (s *RetentionScheduler) Start(ctx context.Context) error

func (*RetentionScheduler) Stop added in v0.12.0

func (s *RetentionScheduler) Stop() error

type RetentionSchedulerOptions added in v0.12.0

type RetentionSchedulerOptions struct {
	// Name is the scheduler/lease/log-prefix name.
	Name string
	// Table is pruned via DELETE FROM <table> WHERE created_at < ?
	Table string
	// ExtraWhere is appended after "created_at < ?" (e.g. " AND deleted_at IS NULL").
	ExtraWhere string
	// UseUTC computes the cutoff with time.Now().UTC() instead of local time.
	UseUTC bool
	// DefaultIntervalMin applies when IntervalMinFn yields a non-positive value.
	DefaultIntervalMin int
	// RetentionDaysFn / IntervalMinFn read the per-job config values.
	RetentionDaysFn func(cfg *config.Config) int
	IntervalMinFn   func(cfg *config.Config) int
	// DisabledFn reports whether Start should no-op, with a log reason.
	DisabledFn func(cfg *config.Config) (disabled bool, reason string)
	// StartLogSuffix is appended to the "started" log message ("" for none).
	StartLogSuffix string
}

RetentionSchedulerOptions configures a single retention job. The three production instances (proxy logs / proxy files / proxy video tasks) were ~95% identical and are collapsed onto one implementation.

type ScheduleSpec added in v0.10.0

type ScheduleSpec struct {
	Version     int    `json:"version"`
	Type        string `json:"kind"` // daily | interval | window | custom
	Time        string `json:"time,omitempty"`
	EveryHours  int    `json:"everyHours,omitempty"`
	WindowStart string `json:"windowStart,omitempty"`
	WindowEnd   string `json:"windowEnd,omitempty"`
	Cron        string `json:"cron,omitempty"`
}

ScheduleSpec is a versioned, JSON-serializable semantic description of a cron schedule. The original cron expression is preserved verbatim in Cron (including 5/6-field form and original whitespace) so that reverse mapping is lossless whenever the semantic fields are unchanged. Expressions that cannot be mapped without losing information become Type "custom" and keep the raw expression as the single source of truth.

func CronToSchedule added in v0.10.0

func CronToSchedule(expr string) ScheduleSpec

CronToSchedule maps a cron expression to a semantic ScheduleSpec without modifying the expression. The original bytes are preserved in spec.Cron. Unparseable or unmappable expressions become Type "custom".

func (ScheduleSpec) Validate added in v0.10.0

func (s ScheduleSpec) Validate() error

Validate checks that a ScheduleSpec is well-formed and self-consistent. Version must match ScheduleSpecVersion so stale documents cannot be applied silently.

type Scheduler

type Scheduler interface {
	Name() string
	Start(ctx context.Context) error
	Stop() error
}

Scheduler is the interface for all background schedulers.

type SiteAnnouncementScheduler

type SiteAnnouncementScheduler struct {
	// contains filtered or unexported fields
}

SiteAnnouncementScheduler polls site announcements periodically.

func NewSiteAnnouncementScheduler

func NewSiteAnnouncementScheduler(cfg *config.Config) *SiteAnnouncementScheduler

NewSiteAnnouncementScheduler creates a new site announcement poller. Picks up any process-wide SyncFunc installed via SetDefaultSiteAnnouncementSyncFunc.

func (*SiteAnnouncementScheduler) Name

func (*SiteAnnouncementScheduler) SetSyncFunc

SetSyncFunc injects (or clears) the real sync implementation for this instance. When fn is nil, the scheduler keeps scan-only behavior.

func (*SiteAnnouncementScheduler) Start

func (*SiteAnnouncementScheduler) Stop

func (s *SiteAnnouncementScheduler) Stop() error

type SiteAnnouncementSyncFunc

type SiteAnnouncementSyncFunc func(db *sqlx.DB) SiteAnnouncementSyncResult

SiteAnnouncementSyncFunc runs a full announcement sync against the given DB. Implementations must call real platform adapters (no invented success counts). Injected from app/admin composition root so scheduler does not import handler/admin.

type SiteAnnouncementSyncResult

type SiteAnnouncementSyncResult struct {
	ScannedSites  int
	Inserted      int
	Updated       int
	Unsupported   int
	Notifications int
	Events        int
	Failed        int
}

SiteAnnouncementSyncResult is the honest outcome of a real announcement sync pass. Field names mirror admin SyncSiteAnnouncements / TS syncSiteAnnouncements.

type Sub2APIRefreshScheduler

type Sub2APIRefreshScheduler struct {
	// contains filtered or unexported fields
}

Sub2APIRefreshScheduler periodically refreshes Sub2API managed authentication tokens for eligible accounts via balance.RefreshBalance.

func NewSub2APIRefreshScheduler

func NewSub2APIRefreshScheduler(cfg *config.Config) *Sub2APIRefreshScheduler

NewSub2APIRefreshScheduler creates a new Sub2API refresh scheduler.

func (*Sub2APIRefreshScheduler) Name

func (s *Sub2APIRefreshScheduler) Name() string

func (*Sub2APIRefreshScheduler) Start

func (*Sub2APIRefreshScheduler) Stop

func (s *Sub2APIRefreshScheduler) Stop() error

type Sub2ApiRefreshResult

type Sub2ApiRefreshResult struct {
	Scanned             int
	Eligible            int
	Refreshed           int
	Failed              int
	Skipped             int
	RefreshedAccountIDs []int64
	FailedAccountIDs    []int64
}

Sub2ApiRefreshResult is the result of a refresh pass.

type UpdateCenterScheduler

type UpdateCenterScheduler struct {
	// contains filtered or unexported fields
}

UpdateCenterScheduler is a ticker for update-center honesty.

It does NOT poll a remote registry/helper, invent updateAvailable, or trigger deploy/rollback. Product path remains external CI/CD / helper. See limitation-update-center.md and /.

func NewUpdateCenterScheduler

func NewUpdateCenterScheduler(cfg *config.Config) *UpdateCenterScheduler

NewUpdateCenterScheduler creates the update-center ticker.

func (*UpdateCenterScheduler) Name

func (s *UpdateCenterScheduler) Name() string

func (*UpdateCenterScheduler) Start

func (*UpdateCenterScheduler) Stop

func (s *UpdateCenterScheduler) Stop() error

type UsageAggregationScheduler

type UsageAggregationScheduler struct {
	// contains filtered or unexported fields
}

UsageAggregationScheduler incrementally projects proxy_logs into site_day_usage, site_hour_usage, and model_day_usage tables. Uses a database lease for multi-instance safety.

func NewUsageAggregationScheduler

func NewUsageAggregationScheduler(cfg *config.Config) *UsageAggregationScheduler

NewUsageAggregationScheduler creates a new usage aggregation scheduler.

func (*UsageAggregationScheduler) Name

func (*UsageAggregationScheduler) RequestRecompute

func (s *UsageAggregationScheduler) RequestRecompute(fromLogID int64)

RequestRecompute requests a recompute of usage aggregates starting from fromLogID. When a recompute is already pending, the earlier (smaller) log id is kept so the rewind window is never silently reduced.

func (*UsageAggregationScheduler) RunProjectionPass

func (s *UsageAggregationScheduler) RunProjectionPass() *ProjectionPassResult

RunProjectionPass executes a single projection pass. Safe to call externally (e.g., from admin snapshot). De-duplication happens under the mutex inside runPass: reading projectionInFlight here without the lock raced the ticker path's writes (observed under -race). Returns nil when a pass is already in flight, same as before.

func (*UsageAggregationScheduler) Start

func (*UsageAggregationScheduler) Stop

func (s *UsageAggregationScheduler) Stop() error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL