Phase 1: core bot

Link in, card, download, send, in private chats and groups.

- cmd/core with an embedded download worker
- Telegram front end on telego v1.13.0 (Bot API 10.4): link card with
  thumbnail and format buttons, one live status message, /dl /audio /thumb
  /info /queue /cancel, group support with requester-only buttons
- Database backed queue: paid and free lanes, leases with heartbeats, one
  automatic retry, cancel, queue position and wait estimate
- yt-dlp and ffprobe behind a Runner interface with classified, redacted
  errors mapped to friendly messages
- SQLite via modernc with goose migrations, portable schema
- Local file storage behind a Storage interface
- go-i18n with an English catalog, no literal text in handlers
- Free tier limits enforced before queueing and again on the real file
- Bot token and webhook secret are stripped from all log output
- Tests: URL parsing, job lifecycle, worker, yt-dlp wrapper, and end to end
  flows against a fake Bot API server; opt-in test with the real yt-dlp

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 07:33:32 +00:00
co-authored by Claude Fable 5.2
commit 3b361c17a1
63 changed files with 10715 additions and 0 deletions
+79
View File
@@ -0,0 +1,79 @@
package sched
import (
"context"
"errors"
"os"
"time"
"github.com/noderunners/dlbot/internal/storage"
"github.com/noderunners/dlbot/internal/workerproto"
)
// Local is the in-process coordinator used by the embedded worker. It
// satisfies worker.Coordinator without any network hop.
type Local struct {
Sched *Scheduler
Storage storage.Storage
}
// Claim waits up to req.WaitSeconds for a job.
func (l *Local) Claim(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.Job, error) {
deadline := time.Now().Add(time.Duration(req.WaitSeconds) * time.Second)
for {
job, err := l.Sched.Claim(ctx, req)
if err != nil || job != nil {
return job, err
}
left := time.Until(deadline)
if left <= 0 || ctx.Err() != nil {
return nil, ctx.Err()
}
l.Sched.WaitWork(ctx, left)
}
}
// Heartbeat forwards to the scheduler.
func (l *Local) Heartbeat(ctx context.Context, req workerproto.HeartbeatRequest) (workerproto.HeartbeatResponse, error) {
resp, err := l.Sched.Heartbeat(ctx, req)
return resp, wrapLease(err)
}
// Complete forwards to the scheduler.
func (l *Local) Complete(ctx context.Context, req workerproto.CompleteRequest) error {
return wrapLease(l.Sched.Complete(ctx, req))
}
// Fail forwards to the scheduler.
func (l *Local) Fail(ctx context.Context, req workerproto.FailRequest) error {
return wrapLease(l.Sched.Fail(ctx, req))
}
// Upload copies the finished file into storage.
func (l *Local) Upload(ctx context.Context, job *workerproto.Job, path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return err
}
return l.Storage.Put(ctx, job.UploadKey, f, st.Size())
}
// leaseError marks ErrLeaseLost for the worker package, which cannot import
// this one.
type leaseError struct{ error }
func (leaseError) LeaseLost() bool { return true }
func (e leaseError) Unwrap() error { return e.error }
func wrapLease(err error) error {
if errors.Is(err, ErrLeaseLost) {
return leaseError{err}
}
return err
}
+550
View File
@@ -0,0 +1,550 @@
// 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{}
}
// 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{})}
}
// 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
}
// Enqueue adds a job with one delivery. 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.
func (s *Scheduler) Enqueue(ctx context.Context, p EnqueueParams) (*db.Job, *db.Delivery, error) {
now := s.now()
if p.Lane == "" {
p.Lane = db.LaneFree
}
job := &db.Job{
ID: ids.New(),
Kind: db.KindDownload,
URL: p.URL,
Extractor: p.Extractor,
VideoID: p.VideoID,
Profile: p.Profile,
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,
}
del := &db.Delivery{
ID: ids.New(),
JobID: job.ID,
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,
}
err := s.store.InTx(ctx, func(tx *db.Store) error {
if p.ActiveLimit > 0 {
n, err := tx.CountActiveDeliveries(ctx, p.UserID)
if err != nil {
return err
}
if n >= p.ActiveLimit {
return ErrTooManyActive
}
}
if p.Lane == db.LaneFree && s.cfg.FreeMaxLen > 0 {
n, err := tx.CountQueued(ctx, db.LaneFree)
if err != nil {
return err
}
if n >= s.cfg.FreeMaxLen {
return ErrQueueFull
}
}
if err := tx.InsertJob(ctx, job); err != nil {
return err
}
return tx.InsertDelivery(ctx, del)
})
if err != nil {
return nil, nil, err
}
s.log.Info("job queued", "job_id", job.ID, "delivery_id", del.ID, "user_id", p.UserID,
"profile", p.Profile, "lane", p.Lane)
s.emit(EventQueued, job.ID)
s.notifyWork()
return job, del, nil
}
// lanes is the claim order: paid jobs first, then free.
var lanes = []string{db.LanePaid, db.LaneFree}
// Claim hands the next queued job to a worker, or returns nil when there
// is nothing to do.
func (s *Scheduler) Claim(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.Job, error) {
now := s.now()
lease := now + s.cfg.Lease.Milliseconds()
var job *db.Job
err := s.store.InTx(ctx, func(tx *db.Store) error {
j, err := tx.NextQueuedJob(ctx, lanes)
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)
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,
UploadKey: UploadKey(job.ID),
Attempt: job.Attempts,
LeaseSeconds: int(s.cfg.Lease.Seconds()),
}, 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 {
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 {
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 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 {
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
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
}
// 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)
}
}
}
}
+457
View File
@@ -0,0 +1,457 @@
package sched_test
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/db/dbtest"
"github.com/noderunners/dlbot/internal/sched"
"github.com/noderunners/dlbot/internal/workerproto"
)
type fixture struct {
t *testing.T
store *db.Store
s *sched.Scheduler
now atomic.Int64 // unix ms, advanced by the test
mu sync.Mutex
events []sched.Event
}
func newFixture(t *testing.T, cfg sched.Config) *fixture {
t.Helper()
f := &fixture{t: t, store: dbtest.Open(t).Store()}
f.now.Store(time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC).UnixMilli())
cfg.Now = func() time.Time { return time.UnixMilli(f.now.Load()) }
if cfg.Lease == 0 {
cfg.Lease = 30 * time.Second
}
f.s = sched.New(f.store, cfg, nil)
f.s.Subscribe(func(ev sched.Event) {
f.mu.Lock()
f.events = append(f.events, ev)
f.mu.Unlock()
})
return f
}
func (f *fixture) advance(d time.Duration) { f.now.Add(d.Milliseconds()) }
func (f *fixture) enqueue(user int64, mut ...func(*sched.EnqueueParams)) (*db.Job, *db.Delivery) {
f.t.Helper()
p := sched.EnqueueParams{
URL: "https://example.com/v", Profile: "720", Title: "T",
UserID: user, ChatID: user, ChatType: "private", Lang: "en",
}
for _, m := range mut {
m(&p)
}
f.advance(time.Millisecond) // distinct queued_at keeps FIFO deterministic
j, d, err := f.s.Enqueue(context.Background(), p)
if err != nil {
f.t.Fatalf("enqueue: %v", err)
}
return j, d
}
func (f *fixture) claim(worker string) *workerproto.Job {
f.t.Helper()
j, err := f.s.Claim(context.Background(), workerproto.ClaimRequest{WorkerID: worker, Capacity: 1})
if err != nil {
f.t.Fatalf("claim: %v", err)
}
return j
}
func (f *fixture) job(id string) *db.Job {
f.t.Helper()
j, err := f.store.GetJob(context.Background(), id)
if err != nil {
f.t.Fatalf("get job: %v", err)
}
return j
}
func (f *fixture) eventTypes(jobID string) []sched.EventType {
f.mu.Lock()
defer f.mu.Unlock()
var out []sched.EventType
for _, e := range f.events {
if e.JobID == jobID {
out = append(out, e.Type)
}
}
return out
}
func wantEvents(t *testing.T, got []sched.EventType, want ...sched.EventType) {
t.Helper()
if len(got) != len(want) {
t.Fatalf("events = %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("events = %v, want %v", got, want)
}
}
}
func TestLifecycleSuccess(t *testing.T) {
ctx := context.Background()
f := newFixture(t, sched.Config{})
job, del := f.enqueue(1)
if job.Status != db.JobQueued || del.Status != db.DeliveryPending {
t.Fatalf("new job %s, delivery %s", job.Status, del.Status)
}
wj := f.claim("w1")
if wj == nil || wj.ID != job.ID {
t.Fatalf("claim = %+v, want job %s", wj, job.ID)
}
if wj.Attempt != 1 || wj.UploadKey != sched.UploadKey(job.ID) {
t.Fatalf("claimed job = %+v", wj)
}
if again := f.claim("w2"); again != nil {
t.Fatalf("a running job was claimed twice: %+v", again)
}
resp, err := f.s.Heartbeat(ctx, workerproto.HeartbeatRequest{
WorkerID: "w1", JobID: job.ID, Stage: "downloading", Downloaded: 50, Total: 100,
})
if err != nil || resp.Cancel {
t.Fatalf("heartbeat = %+v, %v", resp, err)
}
if got := f.job(job.ID); got.ProgressBytes != 50 || got.TotalBytes != 100 || got.Stage != "downloading" {
t.Fatalf("progress not stored: %+v", got)
}
if _, err := f.s.Heartbeat(ctx, workerproto.HeartbeatRequest{WorkerID: "intruder", JobID: job.ID}); !errors.Is(err, sched.ErrLeaseLost) {
t.Fatalf("heartbeat from another worker: %v, want ErrLeaseLost", err)
}
if err := f.s.Complete(ctx, workerproto.CompleteRequest{WorkerID: "intruder", JobID: job.ID}); !errors.Is(err, sched.ErrLeaseLost) {
t.Fatalf("complete from another worker: %v, want ErrLeaseLost", err)
}
err = f.s.Complete(ctx, workerproto.CompleteRequest{
WorkerID: "w1", JobID: job.ID, StorageKey: wj.UploadKey, Ext: "mp4", Size: 1234, Duration: 61,
Width: 1280, Height: 720, Title: "Real Title", Extractor: "youtube", VideoID: "abc",
})
if err != nil {
t.Fatalf("complete: %v", err)
}
got := f.job(job.ID)
if got.Status != db.JobDelivering || got.FileSize != 1234 || got.FileExt != "mp4" ||
got.Title != "Real Title" || got.Extractor != "youtube" || got.VideoID != "abc" {
t.Fatalf("after complete: %+v", got)
}
if err := f.s.FinishDelivered(ctx, job.ID); err != nil {
t.Fatal(err)
}
if got := f.job(job.ID); got.Status != db.JobDone {
t.Fatalf("status = %s, want done", got.Status)
}
wantEvents(t, f.eventTypes(job.ID), sched.EventQueued, sched.EventStarted, sched.EventProgress, sched.EventStored)
}
func TestFailRetriesOnceThenFails(t *testing.T) {
ctx := context.Background()
f := newFixture(t, sched.Config{MaxAttempts: 2})
job, _ := f.enqueue(1)
f.claim("w1")
if err := f.s.Fail(ctx, workerproto.FailRequest{WorkerID: "w1", JobID: job.ID, Code: "network", Retryable: true}); err != nil {
t.Fatal(err)
}
if got := f.job(job.ID); got.Status != db.JobQueued || got.Attempts != 1 || got.WorkerID != "" {
t.Fatalf("after first failure: status=%s attempts=%d worker=%q", got.Status, got.Attempts, got.WorkerID)
}
wj := f.claim("w2")
if wj == nil || wj.Attempt != 2 {
t.Fatalf("retry claim = %+v", wj)
}
if err := f.s.Fail(ctx, workerproto.FailRequest{WorkerID: "w2", JobID: job.ID, Code: "network", Retryable: true}); err != nil {
t.Fatal(err)
}
got := f.job(job.ID)
if got.Status != db.JobFailed || got.ErrorCode != "network" {
t.Fatalf("after second failure: status=%s code=%s", got.Status, got.ErrorCode)
}
wantEvents(t, f.eventTypes(job.ID), sched.EventQueued, sched.EventStarted, sched.EventRequeued,
sched.EventStarted, sched.EventFailed)
}
func TestFailNotRetryableFailsAtOnce(t *testing.T) {
ctx := context.Background()
f := newFixture(t, sched.Config{MaxAttempts: 2})
job, _ := f.enqueue(1)
f.claim("w1")
if err := f.s.Fail(ctx, workerproto.FailRequest{WorkerID: "w1", JobID: job.ID, Code: "private"}); err != nil {
t.Fatal(err)
}
if got := f.job(job.ID); got.Status != db.JobFailed || got.ErrorCode != "private" {
t.Fatalf("status=%s code=%s", got.Status, got.ErrorCode)
}
}
func TestWorkerShutdownDoesNotSpendAnAttempt(t *testing.T) {
ctx := context.Background()
f := newFixture(t, sched.Config{MaxAttempts: 2})
job, _ := f.enqueue(1)
for i := 0; i < 5; i++ { // more hand-backs than attempts
if wj := f.claim("w1"); wj == nil {
t.Fatalf("round %d: nothing to claim", i)
}
if err := f.s.Fail(ctx, workerproto.FailRequest{WorkerID: "w1", JobID: job.ID, Code: "worker_lost", Retryable: true}); err != nil {
t.Fatal(err)
}
}
if got := f.job(job.ID); got.Status != db.JobQueued || got.Attempts != 0 {
t.Fatalf("status=%s attempts=%d, want queued with 0 attempts", got.Status, got.Attempts)
}
}
func TestExpiredLeaseIsRequeuedThenFailed(t *testing.T) {
ctx := context.Background()
f := newFixture(t, sched.Config{Lease: 30 * time.Second, MaxAttempts: 2})
job, _ := f.enqueue(1)
f.claim("w1")
f.advance(20 * time.Second)
if n, err := f.s.RequeueExpired(ctx); err != nil || n != 0 {
t.Fatalf("lease still valid, requeued %d, err %v", n, err)
}
// A heartbeat extends the lease past the original expiry.
if _, err := f.s.Heartbeat(ctx, workerproto.HeartbeatRequest{WorkerID: "w1", JobID: job.ID}); err != nil {
t.Fatal(err)
}
f.advance(20 * time.Second)
if n, _ := f.s.RequeueExpired(ctx); n != 0 {
t.Fatalf("heartbeat should have extended the lease, requeued %d", n)
}
f.advance(31 * time.Second) // the worker died
if n, err := f.s.RequeueExpired(ctx); err != nil || n != 1 {
t.Fatalf("requeued %d, err %v, want 1", n, err)
}
if got := f.job(job.ID); got.Status != db.JobQueued {
t.Fatalf("status = %s, want queued", got.Status)
}
// The dead worker comes back late and must be turned away.
if err := f.s.Complete(ctx, workerproto.CompleteRequest{WorkerID: "w1", JobID: job.ID}); !errors.Is(err, sched.ErrLeaseLost) {
t.Fatalf("late complete: %v, want ErrLeaseLost", err)
}
if wj := f.claim("w2"); wj == nil || wj.Attempt != 2 {
t.Fatalf("second worker claim = %+v", wj)
}
f.advance(31 * time.Second)
if n, _ := f.s.RequeueExpired(ctx); n != 1 {
t.Fatalf("second expiry not handled")
}
if got := f.job(job.ID); got.Status != db.JobFailed || got.ErrorCode != "worker_lost" {
t.Fatalf("status=%s code=%s, want failed worker_lost", got.Status, got.ErrorCode)
}
}
func TestCancelQueuedJob(t *testing.T) {
ctx := context.Background()
f := newFixture(t, sched.Config{})
job, del := f.enqueue(7)
if _, err := f.s.CancelDelivery(ctx, del.ID, 999); !errors.Is(err, sched.ErrNotOwner) {
t.Fatalf("cancel by a stranger: %v, want ErrNotOwner", err)
}
d, err := f.s.CancelDelivery(ctx, del.ID, 7)
if err != nil || d.Status != db.DeliveryCancelled {
t.Fatalf("cancel = %+v, %v", d, err)
}
if got := f.job(job.ID); got.Status != db.JobCancelled {
t.Fatalf("job status = %s, want cancelled", got.Status)
}
if wj := f.claim("w1"); wj != nil {
t.Fatalf("a cancelled job was claimed: %+v", wj)
}
if _, err := f.s.CancelDelivery(ctx, del.ID, 7); !errors.Is(err, sched.ErrTooLate) {
t.Fatalf("second cancel: %v, want ErrTooLate", err)
}
}
func TestCancelRunningJobStopsAtHeartbeat(t *testing.T) {
ctx := context.Background()
f := newFixture(t, sched.Config{})
job, del := f.enqueue(7)
f.claim("w1")
if _, err := f.s.CancelDelivery(ctx, del.ID, 7); err != nil {
t.Fatal(err)
}
if got := f.job(job.ID); got.Status != db.JobRunning || !got.CancelRequested {
t.Fatalf("running job should be flagged, got status=%s flag=%v", got.Status, got.CancelRequested)
}
resp, err := f.s.Heartbeat(ctx, workerproto.HeartbeatRequest{WorkerID: "w1", JobID: job.ID})
if err != nil || !resp.Cancel {
t.Fatalf("heartbeat = %+v, %v, want cancel", resp, err)
}
if err := f.s.Fail(ctx, workerproto.FailRequest{WorkerID: "w1", JobID: job.ID, Code: "cancelled"}); err != nil {
t.Fatal(err)
}
if got := f.job(job.ID); got.Status != db.JobCancelled {
t.Fatalf("status = %s, want cancelled", got.Status)
}
}
func TestCompleteAfterCancelDoesNotDeliver(t *testing.T) {
ctx := context.Background()
f := newFixture(t, sched.Config{})
job, del := f.enqueue(7)
f.claim("w1")
if _, err := f.s.CancelDelivery(ctx, del.ID, 7); err != nil {
t.Fatal(err)
}
// The worker finished before it saw the cancel flag.
if err := f.s.Complete(ctx, workerproto.CompleteRequest{WorkerID: "w1", JobID: job.ID, StorageKey: "k"}); err != nil {
t.Fatal(err)
}
if got := f.job(job.ID); got.Status != db.JobCancelled {
t.Fatalf("status = %s, want cancelled", got.Status)
}
}
func TestActiveLimitAndQueueCap(t *testing.T) {
ctx := context.Background()
f := newFixture(t, sched.Config{FreeMaxLen: 2})
limit1 := func(p *sched.EnqueueParams) { p.ActiveLimit = 1 }
_, del := f.enqueue(1, limit1)
_, _, err := f.s.Enqueue(ctx, sched.EnqueueParams{URL: "u", Profile: "720", UserID: 1, ActiveLimit: 1})
if !errors.Is(err, sched.ErrTooManyActive) {
t.Fatalf("second job of a limited user: %v, want ErrTooManyActive", err)
}
// Cancelling frees the slot.
if _, err := f.s.CancelDelivery(ctx, del.ID, 1); err != nil {
t.Fatal(err)
}
f.enqueue(1, limit1)
f.enqueue(2)
_, _, err = f.s.Enqueue(ctx, sched.EnqueueParams{URL: "u", Profile: "720", UserID: 3})
if !errors.Is(err, sched.ErrQueueFull) {
t.Fatalf("third queued free job: %v, want ErrQueueFull", err)
}
// The cap only counts the free lane.
if _, _, err := f.s.Enqueue(ctx, sched.EnqueueParams{URL: "u", Profile: "720", UserID: 4, Lane: db.LanePaid}); err != nil {
t.Fatalf("paid job should bypass the free queue cap: %v", err)
}
}
func TestClaimOrderPaidFirstThenFIFO(t *testing.T) {
f := newFixture(t, sched.Config{})
paid := func(p *sched.EnqueueParams) { p.Lane = db.LanePaid }
free1, _ := f.enqueue(1)
free2, _ := f.enqueue(2)
paid1, _ := f.enqueue(3, paid)
paid2, _ := f.enqueue(4, paid)
urgent, _ := f.enqueue(5, paid, func(p *sched.EnqueueParams) { p.Priority = 10 })
want := []string{urgent.ID, paid1.ID, paid2.ID, free1.ID, free2.ID}
// Positions must agree with the claim order before anything is claimed.
for i, id := range want {
pos, err := f.s.Position(context.Background(), f.job(id), 1)
if err != nil {
t.Fatal(err)
}
if pos.Ahead != i {
t.Errorf("position of job %d = %d, want %d", i, pos.Ahead, i)
}
}
for i, id := range want {
wj := f.claim("w")
if wj == nil || wj.ID != id {
t.Fatalf("claim %d = %v, want %s", i, wj, id)
}
}
if wj := f.claim("w"); wj != nil {
t.Fatalf("queue should be empty, got %+v", wj)
}
}
func TestRetriedJobKeepsItsPlace(t *testing.T) {
ctx := context.Background()
f := newFixture(t, sched.Config{MaxAttempts: 2})
first, _ := f.enqueue(1)
second, _ := f.enqueue(2)
f.claim("w1") // takes first
if err := f.s.Fail(ctx, workerproto.FailRequest{WorkerID: "w1", JobID: first.ID, Code: "network", Retryable: true}); err != nil {
t.Fatal(err)
}
if wj := f.claim("w1"); wj == nil || wj.ID != first.ID {
t.Fatalf("retried job should go before %s, got %+v", second.ID, wj)
}
}
func TestConcurrentClaimsNeverShareAJob(t *testing.T) {
f := newFixture(t, sched.Config{})
const jobs = 40
for i := 0; i < jobs; i++ {
f.enqueue(int64(i + 1))
}
var (
mu sync.Mutex
seen = map[string]string{}
wg sync.WaitGroup
)
for w := 0; w < 8; w++ {
wg.Add(1)
go func(worker string) {
defer wg.Done()
for {
wj, err := f.s.Claim(context.Background(), workerproto.ClaimRequest{WorkerID: worker})
if err != nil {
t.Errorf("claim: %v", err)
return
}
if wj == nil {
return
}
mu.Lock()
if prev, dup := seen[wj.ID]; dup {
t.Errorf("job %s claimed by %s and %s", wj.ID, prev, worker)
}
seen[wj.ID] = worker
mu.Unlock()
}
}(string(rune('a' + w)))
}
wg.Wait()
if len(seen) != jobs {
t.Fatalf("claimed %d jobs, want %d", len(seen), jobs)
}
}
func TestWaitWorkWakesOnEnqueue(t *testing.T) {
f := newFixture(t, sched.Config{})
done := make(chan time.Duration, 1)
go func() {
start := time.Now()
f.s.WaitWork(context.Background(), 5*time.Second)
done <- time.Since(start)
}()
time.Sleep(50 * time.Millisecond)
f.enqueue(1)
select {
case d := <-done:
if d > 2*time.Second {
t.Fatalf("WaitWork returned after %s, expected a prompt wake-up", d)
}
case <-time.After(3 * time.Second):
t.Fatal("WaitWork did not wake up on enqueue")
}
}