// Package sched is the job queue: enqueueing, claiming with leases, // heartbeats, completion, failure with retry, cancellation and positions. // All state lives in the database, so any number of workers can pull from // it and the core can restart without losing work. package sched import ( "context" "errors" "log/slog" "sync" "time" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/ids" "github.com/noderunners/dlbot/internal/workerproto" "github.com/noderunners/dlbot/internal/ytdlp" ) // Errors returned by the scheduler. var ( ErrTooManyActive = errors.New("sched: user has too many active jobs") ErrQueueFull = errors.New("sched: free queue is full") ErrLeaseLost = errors.New("sched: job is not owned by this worker") ErrNotOwner = errors.New("sched: delivery belongs to another user") ErrTooLate = errors.New("sched: delivery can no longer be cancelled") ) // EventType says what happened to a job. type EventType string // The job events. const ( EventQueued EventType = "queued" EventStarted EventType = "started" EventProgress EventType = "progress" EventStored EventType = "stored" // worker finished, ready to deliver EventFailed EventType = "failed" EventCancelled EventType = "cancelled" EventRequeued EventType = "requeued" ) // Event is sent to listeners after the change is committed. type Event struct { Type EventType JobID string } // Config holds the queue settings. type Config struct { Lease time.Duration FreeMaxLen int MaxAttempts int // Now can be replaced in tests. Now func() time.Time } // Scheduler is the queue API used by the bot and by workers. type Scheduler struct { store *db.Store cfg Config log *slog.Logger mu sync.Mutex listeners []func(Event) wake chan struct{} workers map[string]workerSeen } // workerSeen is what the scheduler remembers about a worker between // claims. It is enough to know the total capacity of the fleet. type workerSeen struct { capacity int at time.Time // commands are pending instructions, delivered with the next claim. commands []string } // workerTTL is how long a worker counts toward capacity after its last // claim. Workers claim at least every 20 seconds while idle. const workerTTL = 90 * time.Second // New creates a scheduler on top of a store. func New(store *db.Store, cfg Config, log *slog.Logger) *Scheduler { if cfg.Lease <= 0 { cfg.Lease = 30 * time.Second } if cfg.MaxAttempts <= 0 { cfg.MaxAttempts = 2 } if cfg.Now == nil { cfg.Now = time.Now } if log == nil { log = slog.Default() } return &Scheduler{store: store, cfg: cfg, log: log, wake: make(chan struct{}), workers: map[string]workerSeen{}} } // Subscribe registers a listener for job events. Listeners are called // synchronously and must not block. func (s *Scheduler) Subscribe(fn func(Event)) { s.mu.Lock() defer s.mu.Unlock() s.listeners = append(s.listeners, fn) } func (s *Scheduler) emit(t EventType, jobID string) { s.mu.Lock() ls := s.listeners s.mu.Unlock() for _, fn := range ls { fn(Event{Type: t, JobID: jobID}) } } // notifyWork wakes every claimer waiting in WaitWork. func (s *Scheduler) notifyWork() { s.mu.Lock() close(s.wake) s.wake = make(chan struct{}) s.mu.Unlock() } // WaitWork blocks until new work may be available, the timeout passes or // the context ends. func (s *Scheduler) WaitWork(ctx context.Context, timeout time.Duration) { s.mu.Lock() ch := s.wake s.mu.Unlock() t := time.NewTimer(timeout) defer t.Stop() select { case <-ch: case <-t.C: case <-ctx.Done(): } } func (s *Scheduler) now() int64 { return s.cfg.Now().UnixMilli() } // EnqueueParams describes a new job and the requester waiting for it. type EnqueueParams struct { URL string Extractor string VideoID string Profile string Title string Uploader string Lane string Priority int MaxSize int64 MaxDuration int64 // seconds RequestID string UserID int64 ChatID int64 ChatType string ReplyToMessageID int64 StatusMessageID int64 StatusIsPhoto bool Lang string // ActiveLimit is the most active jobs the user may have, 0 for no limit. ActiveLimit int // What pays for the download. These are stored with the delivery so a // failure can give back exactly what was taken. Source string WalletID string ChargeSats int64 QuotaDay int // Kind is the job kind, download by default. Kind string // CacheKey identifies the result, so a second requester for the same // result can share the job. CacheKey string // Cacheable says the result may be kept in the cache. Cacheable bool // SourceKey is the stored copy a derive job transcodes from. SourceKey string // Hit, when set, makes the job a cache hit: it is created already // finished and never waits for a worker. Hit *CacheHit // RequiredTags is a comma separated list of tags a worker must have to // take the job, for example "residential". RequiredTags string } // CacheHit describes a cached result a job is served from. type CacheHit struct { StorageKey string TgFileID string FileExt string FileSize int64 Duration int64 Width int Height int Title string Uploader string } // Enqueue adds a job with one delivery in its own transaction. func (s *Scheduler) Enqueue(ctx context.Context, p EnqueueParams) (*db.Job, *db.Delivery, error) { var ( job *db.Job del *db.Delivery ) err := s.store.InTx(ctx, func(tx *db.Store) error { var err error job, del, err = s.EnqueueTx(ctx, tx, p) return err }) if err != nil { return nil, nil, err } s.Announce(job, del) return job, del, nil } // EnqueueTx adds a job with one delivery inside the caller's transaction, // so that charging a wallet and queueing the job commit or fail together. // The per-user limit and the free queue cap are checked in the same // transaction as the insert, so two fast button presses cannot both slip // through. The caller must call Announce after the transaction commits. func (s *Scheduler) EnqueueTx(ctx context.Context, tx *db.Store, p EnqueueParams) (*db.Job, *db.Delivery, error) { now := s.now() if p.Lane == "" { p.Lane = db.LaneFree } if p.Kind == "" { p.Kind = db.KindDownload } job := &db.Job{ ID: ids.New(), Kind: p.Kind, URL: p.URL, Extractor: p.Extractor, VideoID: p.VideoID, Profile: p.Profile, CacheKey: p.CacheKey, Cacheable: p.Cacheable, SourceKey: p.SourceKey, RequiredTags: p.RequiredTags, Status: db.JobQueued, Lane: p.Lane, Priority: p.Priority, MaxSize: p.MaxSize, MaxDuration: p.MaxDuration, MaxAttempts: s.cfg.MaxAttempts, Title: p.Title, Uploader: p.Uploader, CreatedAt: now, QueuedAt: now, } if h := p.Hit; h != nil { // Served from the cache: the result exists, so the job starts in // the state a worker would have left it in. job.Status = db.JobDelivering job.CacheHit = true job.StorageKey, job.TgFileID, job.FileExt = h.StorageKey, h.TgFileID, h.FileExt job.FileSize, job.Duration, job.Width, job.Height = h.FileSize, h.Duration, h.Width, h.Height if h.Title != "" { job.Title = h.Title } if h.Uploader != "" { job.Uploader = h.Uploader } job.StartedAt, job.FinishedAt = now, now } del := s.newDelivery(job.ID, p, now) if p.ActiveLimit > 0 { // Count and insert must not interleave with another request of // the same user. if err := tx.LockUser(ctx, p.UserID); err != nil { return nil, nil, err } n, err := tx.CountActiveDeliveries(ctx, p.UserID) if err != nil { return nil, nil, err } if n >= p.ActiveLimit { return nil, nil, ErrTooManyActive } } if p.Lane == db.LaneFree && s.cfg.FreeMaxLen > 0 { n, err := tx.CountQueued(ctx, db.LaneFree) if err != nil { return nil, nil, err } if n >= s.cfg.FreeMaxLen { return nil, nil, ErrQueueFull } } if err := tx.InsertJob(ctx, job); err != nil { return nil, nil, err } if err := tx.InsertDelivery(ctx, del); err != nil { return nil, nil, err } return job, del, nil } func (s *Scheduler) newDelivery(jobID string, p EnqueueParams, now int64) *db.Delivery { return &db.Delivery{ ID: ids.New(), JobID: jobID, RequestID: p.RequestID, UserID: p.UserID, ChatID: p.ChatID, ChatType: p.ChatType, ReplyToMessageID: p.ReplyToMessageID, StatusMessageID: p.StatusMessageID, StatusIsPhoto: p.StatusIsPhoto, Lang: p.Lang, Status: db.DeliveryPending, CreatedAt: now, Source: p.Source, WalletID: p.WalletID, ChargeSats: p.ChargeSats, QuotaDay: p.QuotaDay, MaxSize: p.MaxSize, MaxDuration: p.MaxDuration, } } // covers reports whether a job cap is at least as loose as a requester's // cap, where 0 means "no cap". func covers(jobCap, myCap int64) bool { return jobCap == 0 || (myCap != 0 && jobCap >= myCap) } // AttachTx adds a requester to a job that is already queued or running // for the same result, so the file is fetched once and everyone is // notified when it is done. It reports false when the job cannot be // shared: a running job was started under tighter caps than this // requester has, and would fail or fall short for them. // // A queued job is lifted instead: its caps become the looser of the two // and it moves to the paid lane when the newcomer pays, which also speeds // it up for whoever asked first. func (s *Scheduler) AttachTx(ctx context.Context, tx *db.Store, job *db.Job, p EnqueueParams) (*db.Delivery, bool, error) { if p.ActiveLimit > 0 { if err := tx.LockUser(ctx, p.UserID); err != nil { return nil, false, err } n, err := tx.CountActiveDeliveries(ctx, p.UserID) if err != nil { return nil, false, err } if n >= p.ActiveLimit { return nil, false, ErrTooManyActive } } // The job was found a moment ago. Lock it and look again: it may have // been claimed, finished or cancelled since. if err := tx.LockJob(ctx, job.ID); err != nil { return nil, false, err } cur, err := tx.GetJob(ctx, job.ID) if err != nil { return nil, false, err } if cur.Status != db.JobQueued && cur.Status != db.JobRunning { return nil, false, nil } *job = *cur shared := covers(job.MaxSize, p.MaxSize) && covers(job.MaxDuration, p.MaxDuration) if job.Status == db.JobQueued { raised, err := tx.RaiseJob(ctx, job.ID, p.MaxSize, p.MaxDuration, p.Lane) if err != nil { return nil, false, err } shared = shared || raised } if !shared { return nil, false, nil } del := s.newDelivery(job.ID, p, s.now()) if err := tx.InsertDelivery(ctx, del); err != nil { return nil, false, err } return del, true, nil } // Announce tells listeners and waiting workers about a committed job. func (s *Scheduler) Announce(job *db.Job, del *db.Delivery) { s.log.Info("job queued", "job_id", job.ID, "delivery_id", del.ID, "user_id", del.UserID, "profile", job.Profile, "lane", job.Lane, "source", del.Source, "kind", job.Kind, "cache_hit", job.CacheHit) if job.CacheHit { s.emit(EventStored, job.ID) // nothing to wait for: deliver now return } s.emit(EventQueued, job.ID) s.notifyWork() } // AnnounceAttached tells listeners that a requester joined a job. func (s *Scheduler) AnnounceAttached(job *db.Job, del *db.Delivery) { s.log.Info("requester attached to job", "job_id", job.ID, "delivery_id", del.ID, "user_id", del.UserID) s.emit(EventRequeued, job.ID) // refreshes status messages s.notifyWork() } // Redownload turns a job that was meant to be served from the cache into // a plain download, when the cached file turned out to be unusable. func (s *Scheduler) Redownload(ctx context.Context, jobID string) (bool, error) { ok, err := s.store.RedownloadJob(ctx, jobID, []string{db.JobDelivering}, s.now()) if err != nil || !ok { return false, err } s.log.Info("cached file unusable, downloading again", "job_id", jobID) s.emit(EventRequeued, jobID) s.notifyWork() return true, nil } // Claim order: paid jobs first, then free. var ( allLanes = []string{db.LanePaid, db.LaneFree} freeOnly = []string{db.LaneFree} ) // seen records a worker's capacity and returns the capacity of all // workers that claimed recently. func (s *Scheduler) seen(workerID string, capacity int) (total int) { if capacity < 1 { capacity = 1 } now := s.cfg.Now() s.mu.Lock() defer s.mu.Unlock() prev := s.workers[workerID] s.workers[workerID] = workerSeen{capacity: capacity, at: now, commands: prev.commands} for id, w := range s.workers { if now.Sub(w.at) > workerTTL { delete(s.workers, id) continue } total += w.capacity } return total } // Command queues an instruction for every live worker. Each worker gets // it with its next claim. It returns how many workers were addressed. func (s *Scheduler) Command(cmd string) int { now := s.cfg.Now() s.mu.Lock() defer s.mu.Unlock() n := 0 for id, w := range s.workers { if now.Sub(w.at) > workerTTL { continue } w.commands = append(w.commands, cmd) s.workers[id] = w n++ } return n } // TakeCommands returns and clears the pending instructions of a worker. func (s *Scheduler) TakeCommands(workerID string) []string { s.mu.Lock() defer s.mu.Unlock() w, ok := s.workers[workerID] if !ok || len(w.commands) == 0 { return nil } cmds := w.commands w.commands = nil s.workers[workerID] = w return cmds } // Seen records that a worker is alive without claiming anything, so that // a worker which only polls for probes still counts toward capacity. func (s *Scheduler) Seen(workerID string, capacity int) { s.seen(workerID, capacity) } // NotifyWork wakes claimers that are waiting, for work that arrives // outside the job queue, such as a probe request. func (s *Scheduler) NotifyWork() { s.notifyWork() } // Capacity returns the number of download slots of all live workers. func (s *Scheduler) Capacity() int { now := s.cfg.Now() s.mu.Lock() defer s.mu.Unlock() total := 0 for _, w := range s.workers { if now.Sub(w.at) <= workerTTL { total += w.capacity } } return total } // Claim hands the next queued job to a worker, or returns nil when there // is nothing to do. // // Paid jobs go first. One slot of the fleet is reserved for the free lane // so free users never starve behind a stream of paid jobs: when this claim // would take the last idle slot and no free job is running, a waiting free // job is served first. The reservation costs nothing when no free job // waits, and it needs at least two slots, since a single slot cannot be // both reserved and useful to paying users. func (s *Scheduler) Claim(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.Job, error) { capacity := s.seen(req.WorkerID, req.Capacity) now := s.now() lease := now + s.cfg.Lease.Milliseconds() var job *db.Job err := s.store.InTx(ctx, func(tx *db.Store) error { var j *db.Job if capacity >= 2 { total, free, err := tx.CountRunningByLane(ctx) if err != nil { return err } if idle := capacity - total; idle <= 1 && free == 0 { j, err = tx.NextQueuedJob(ctx, freeOnly, req.Tags) if err != nil && !errors.Is(err, db.ErrNotFound) { return err } } } if j == nil { var err error j, err = tx.NextQueuedJob(ctx, allLanes, req.Tags) if errors.Is(err, db.ErrNotFound) { return nil } if err != nil { return err } } ok, err := tx.MarkJobRunning(ctx, j.ID, req.WorkerID, lease, now) if err != nil || !ok { return err } j.Attempts++ job = j return nil }) if err != nil || job == nil { return nil, err } s.log.Info("job claimed", "job_id", job.ID, "worker_id", req.WorkerID, "attempt", job.Attempts, "lane", job.Lane) s.emit(EventStarted, job.ID) return &workerproto.Job{ ID: job.ID, Kind: job.Kind, URL: job.URL, Profile: job.Profile, MaxSize: job.MaxSize, MaxDuration: job.MaxDuration, SourceKey: job.SourceKey, UploadKey: UploadKey(job.ID), Attempt: job.Attempts, LeaseSeconds: int(s.cfg.Lease.Seconds()), }, nil } // Promote moves a waiting free job to the paid lane ("skip the queue"). // It reports false when the job is no longer waiting in the free lane. func (s *Scheduler) Promote(ctx context.Context, jobID string) (bool, error) { ok, err := s.store.PromoteJob(ctx, jobID) if err != nil || !ok { return false, err } s.log.Info("job promoted to the paid lane", "job_id", jobID) s.emit(EventRequeued, jobID) // refreshes the position shown to the user s.notifyWork() return true, nil } // UploadKey is the storage key a job result is written to. func UploadKey(jobID string) string { return "jobs/" + jobID + "/media" } // Heartbeat extends a lease and stores progress. It returns ErrLeaseLost // when the job was taken away, in which case the worker must stop. func (s *Scheduler) Heartbeat(ctx context.Context, req workerproto.HeartbeatRequest) (workerproto.HeartbeatResponse, error) { lease := s.now() + s.cfg.Lease.Milliseconds() ok, err := s.store.HeartbeatJob(ctx, req.JobID, req.WorkerID, lease, req.Stage, req.Downloaded, req.Total) if err != nil { return workerproto.HeartbeatResponse{}, err } if !ok { return workerproto.HeartbeatResponse{Cancel: true}, ErrLeaseLost } job, err := s.store.GetJob(ctx, req.JobID) if err != nil { return workerproto.HeartbeatResponse{}, err } s.emit(EventProgress, req.JobID) return workerproto.HeartbeatResponse{Cancel: job.CancelRequested}, nil } // Complete records a successful result. The file must already be in // storage under the reported key. func (s *Scheduler) Complete(ctx context.Context, req workerproto.CompleteRequest) error { var cancelled bool err := s.store.InTx(ctx, func(tx *db.Store) error { if err := tx.LockJob(ctx, req.JobID); err != nil { return err } job, err := tx.GetJob(ctx, req.JobID) if err != nil { return err } if job.Status != db.JobRunning || job.WorkerID != req.WorkerID { return ErrLeaseLost } if job.CancelRequested { // The last requester left while the worker was finishing. cancelled = true _, err := tx.FinishJob(ctx, job.ID, db.JobCancelled, string(ytdlp.CodeCancelled), "", []string{db.JobRunning}, s.now()) return err } ok, err := tx.CompleteJob(ctx, req.JobID, req.WorkerID, db.JobResult{ StorageKey: req.StorageKey, FileExt: req.Ext, FileSize: req.Size, Duration: req.Duration, Width: req.Width, Height: req.Height, Title: req.Title, Uploader: req.Uploader, Extractor: req.Extractor, VideoID: req.VideoID, }, s.now()) if err == nil && !ok { return ErrLeaseLost } return err }) if err != nil { return err } if cancelled { s.log.Info("job finished after cancel", "job_id", req.JobID) s.emit(EventCancelled, req.JobID) return nil } s.log.Info("job stored", "job_id", req.JobID, "worker_id", req.WorkerID, "size", req.Size) s.emit(EventStored, req.JobID) return nil } // Fail records a failed attempt. A retryable failure goes back to the // queue while attempts remain; anything else ends the job. func (s *Scheduler) Fail(ctx context.Context, req workerproto.FailRequest) error { var ev EventType err := s.store.InTx(ctx, func(tx *db.Store) error { if err := tx.LockJob(ctx, req.JobID); err != nil { return err } job, err := tx.GetJob(ctx, req.JobID) if err != nil { return err } if job.Status != db.JobRunning || job.WorkerID != req.WorkerID { return ErrLeaseLost } switch { case job.CancelRequested || req.Code == string(ytdlp.CodeCancelled): ev = EventCancelled _, err = tx.FinishJob(ctx, job.ID, db.JobCancelled, string(ytdlp.CodeCancelled), req.Detail, []string{db.JobRunning}, s.now()) case job.Kind == db.KindDerive && req.Code != string(ytdlp.CodeWorkerLost): // Transcoding from the stored copy did not work. Downloading // the profile directly is the fallback, at no cost in attempts. ev = EventRequeued _, err = tx.RedownloadJob(ctx, job.ID, []string{db.JobRunning}, s.now()) case req.Retryable && req.Code == string(ytdlp.CodeWorkerLost): // A clean worker shutdown is not the job's fault: hand it to // another worker without spending an attempt. ev = EventRequeued _, err = tx.RequeueJob(ctx, job.ID, req.Code, req.Detail, true) case req.Retryable && job.Attempts < job.MaxAttempts: ev = EventRequeued _, err = tx.RequeueJob(ctx, job.ID, req.Code, req.Detail, false) default: ev = EventFailed _, err = tx.FinishJob(ctx, job.ID, db.JobFailed, req.Code, req.Detail, []string{db.JobRunning}, s.now()) } return err }) if err != nil { return err } // The raw detail is owner-only diagnostics and is already redacted. s.log.Warn("job attempt failed", "job_id", req.JobID, "worker_id", req.WorkerID, "code", req.Code, "retryable", req.Retryable, "outcome", string(ev), "detail", req.Detail) s.emit(ev, req.JobID) if ev == EventRequeued { s.notifyWork() } return nil } // RequeueExpired returns jobs whose worker stopped sending heartbeats to // the queue, or fails them when no attempts remain. func (s *Scheduler) RequeueExpired(ctx context.Context) (int, error) { expired, err := s.store.ExpiredJobs(ctx, s.now()) if err != nil || len(expired) == 0 { return 0, err } n := 0 for _, j := range expired { var ev EventType err := s.store.InTx(ctx, func(tx *db.Store) error { if err := tx.LockJob(ctx, j.ID); err != nil { return err } cur, err := tx.GetJob(ctx, j.ID) if err != nil { return err } if cur.Status != db.JobRunning || cur.LeaseExpiresAt >= s.now() { return nil // the worker came back in time } switch { case cur.CancelRequested: ev = EventCancelled _, err = tx.FinishJob(ctx, cur.ID, db.JobCancelled, string(ytdlp.CodeCancelled), "", []string{db.JobRunning}, s.now()) case cur.Attempts < cur.MaxAttempts: ev = EventRequeued _, err = tx.RequeueJob(ctx, cur.ID, string(ytdlp.CodeWorkerLost), "lease expired on "+cur.WorkerID, false) default: ev = EventFailed _, err = tx.FinishJob(ctx, cur.ID, db.JobFailed, string(ytdlp.CodeWorkerLost), "lease expired on "+cur.WorkerID, []string{db.JobRunning}, s.now()) } return err }) if err != nil { return n, err } if ev == "" { continue } n++ s.log.Warn("lease expired", "job_id", j.ID, "worker_id", j.WorkerID, "outcome", string(ev)) s.emit(ev, j.ID) } if n > 0 { s.notifyWork() } return n, nil } // CancelDelivery withdraws one requester. When nobody else waits for the // job, the job itself is cancelled: at once if it is still queued, at the // worker's next heartbeat if it is running. func (s *Scheduler) CancelDelivery(ctx context.Context, deliveryID string, userID int64) (*db.Delivery, error) { var del *db.Delivery var cancelledJob bool err := s.store.InTx(ctx, func(tx *db.Store) error { d, err := tx.GetDelivery(ctx, deliveryID) if err != nil { return err } if d.UserID != userID { return ErrNotOwner } ok, err := tx.TransitionDelivery(ctx, d.ID, db.DeliveryPending, db.DeliveryCancelled, "") if err != nil { return err } if !ok { return ErrTooLate } d.Status = db.DeliveryCancelled del = d // Lock the job before looking at it: a worker may be claiming it // right now, and the decision below depends on its status. if err := tx.LockJob(ctx, d.JobID); err != nil { return err } left, err := tx.CountDeliveriesInStatus(ctx, d.JobID, db.DeliveryPending, db.DeliverySending) if err != nil || left > 0 { return err } job, err := tx.GetJob(ctx, d.JobID) if err != nil { return err } switch job.Status { case db.JobQueued, db.JobDelivering: cancelledJob, err = tx.FinishJob(ctx, job.ID, db.JobCancelled, string(ytdlp.CodeCancelled), "", []string{db.JobQueued, db.JobDelivering}, s.now()) case db.JobRunning: err = tx.RequestJobCancel(ctx, job.ID) } return err }) if err != nil { return nil, err } s.log.Info("delivery cancelled", "delivery_id", del.ID, "job_id", del.JobID, "user_id", userID) if cancelledJob { s.emit(EventCancelled, del.JobID) } return del, nil } // FinishDelivered marks a delivering job as done once every requester has // been served. func (s *Scheduler) FinishDelivered(ctx context.Context, jobID string) error { _, err := s.store.FinishJob(ctx, jobID, db.JobDone, "", "", []string{db.JobDelivering}, s.now()) return err } // Position describes where a queued job stands. type Position struct { // Ahead is the number of jobs that will be claimed first. Ahead int // Wait is a rough estimate of the time until a worker picks it up. Wait time.Duration } // defaultJobSeconds is the wait estimate used before there is any history. const defaultJobSeconds = 45 // Position estimates the queue position and wait of a job. workers is the // number of worker slots serving the queue. func (s *Scheduler) Position(ctx context.Context, job *db.Job, workers int) (Position, error) { ahead, err := s.store.QueuePosition(ctx, job) if err != nil { return Position{}, err } avg, err := s.store.AvgJobSeconds(ctx, 20) if err != nil { return Position{}, err } if avg <= 0 { avg = defaultJobSeconds } if workers < 1 { workers = 1 } running, err := s.store.CountRunning(ctx) if err != nil { return Position{}, err } // The job may have been claimed since the caller loaded it; it then // waits for nothing, and must not count itself as running ahead. if cur, err := s.store.GetJob(ctx, job.ID); err == nil && cur.Status != db.JobQueued { return Position{}, nil } // A free slot takes the job at once. if ahead < workers-running { return Position{Ahead: ahead}, nil } // Jobs ahead plus the ones running now, spread over the worker slots. // Running jobs are counted as half done on average. load := float64(ahead) + float64(running)/2 wait := time.Duration(load / float64(workers) * avg * float64(time.Second)) return Position{Ahead: ahead, Wait: wait.Round(time.Second)}, nil } // Run requeues expired leases until the context ends. func (s *Scheduler) Run(ctx context.Context) { interval := s.cfg.Lease / 3 if interval < 50*time.Millisecond { interval = 50 * time.Millisecond } t := time.NewTicker(interval) defer t.Stop() for { select { case <-ctx.Done(): return case <-t.C: if _, err := s.RequeueExpired(ctx); err != nil && ctx.Err() == nil { s.log.Error("requeue expired leases", "err", err) } } } }