package worker_test import ( "context" "os" "path/filepath" "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/storage" "github.com/noderunners/dlbot/internal/worker" "github.com/noderunners/dlbot/internal/workerproto" "github.com/noderunners/dlbot/internal/ytdlp" "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" ) type rig struct { t *testing.T store *db.Store sched *sched.Scheduler storage *storage.Local fake *ytdlptest.Fake tmp string cancel context.CancelFunc done chan struct{} } // newRig starts one worker against a real scheduler, SQLite and local // storage, with a scripted yt-dlp. func newRig(t *testing.T, fake *ytdlptest.Fake, maxAttempts int) *rig { t.Helper() st, err := storage.NewLocal(filepath.Join(t.TempDir(), "files")) if err != nil { t.Fatal(err) } r := &rig{ t: t, store: dbtest.Open(t).Store(), storage: st, fake: fake, tmp: filepath.Join(t.TempDir(), "tmp"), done: make(chan struct{}), } r.sched = sched.New(r.store, sched.Config{Lease: 2 * time.Second, MaxAttempts: maxAttempts}, nil) w := worker.New(worker.Config{ ID: "w1", Concurrency: 2, TempDir: r.tmp, Heartbeat: 30 * time.Millisecond, ClaimWait: 100 * time.Millisecond, }, &sched.Local{Sched: r.sched, Storage: st}, fake, nil) ctx, cancel := context.WithCancel(context.Background()) r.cancel = cancel go func() { defer close(r.done) w.Run(ctx) }() t.Cleanup(r.stop) return r } func (r *rig) stop() { r.cancel() select { case <-r.done: case <-time.After(10 * time.Second): r.t.Error("worker did not stop") } } func (r *rig) enqueue(url, profile string) (*db.Job, *db.Delivery) { r.t.Helper() j, d, err := r.sched.Enqueue(context.Background(), sched.EnqueueParams{ URL: url, Profile: profile, UserID: 1, ChatID: 1, MaxSize: 10 << 20, }) if err != nil { r.t.Fatal(err) } return j, d } // waitStatus polls until the job reaches one of the statuses. func (r *rig) waitStatus(id string, statuses ...string) *db.Job { r.t.Helper() deadline := time.Now().Add(10 * time.Second) for { j, err := r.store.GetJob(context.Background(), id) if err != nil { r.t.Fatal(err) } for _, s := range statuses { if j.Status == s { return j } } if time.Now().After(deadline) { r.t.Fatalf("job %s stuck in %s, wanted %v", id, j.Status, statuses) } time.Sleep(10 * time.Millisecond) } } func (r *rig) tempDirEmpty() bool { entries, err := os.ReadDir(r.tmp) return err != nil || len(entries) == 0 } func TestWorkerDownloadsAndStores(t *testing.T) { r := newRig(t, &ytdlptest.Fake{FileSize: 2048}, 2) job, _ := r.enqueue("https://example.com/v", "720") got := r.waitStatus(job.ID, db.JobDelivering, db.JobFailed) if got.Status != db.JobDelivering { t.Fatalf("status = %s (%s), want delivering", got.Status, got.ErrorCode) } if got.FileSize != 2048 || got.FileExt != "mp4" || got.Title != "Test Video" || got.Width != 1280 { t.Fatalf("result not recorded: %+v", got) } obj, err := r.storage.Stat(context.Background(), got.StorageKey) if err != nil || obj.Size != 2048 { t.Fatalf("stored object = %+v, %v", obj, err) } if !r.tempDirEmpty() { t.Fatal("the temp dir must be removed after the upload") } // The limits given at enqueue time must reach yt-dlp. dl := r.fake.Downloads() if len(dl) != 1 || dl[0].MaxSize != 10<<20 || string(dl[0].Profile) != "720" { t.Fatalf("download request = %+v", dl) } } func TestWorkerRetriesOnceAfterRetryableFailure(t *testing.T) { url := "https://example.com/flaky" fake := &ytdlptest.Fake{DownloadErrs: map[string][]error{ url: {&ytdlp.Error{Code: ytdlp.CodeNetwork, Retryable: true, Raw: "connection reset"}}, }} r := newRig(t, fake, 2) job, _ := r.enqueue(url, "best") got := r.waitStatus(job.ID, db.JobDelivering, db.JobFailed) if got.Status != db.JobDelivering || got.Attempts != 2 { t.Fatalf("status=%s attempts=%d, want delivering after 2 attempts", got.Status, got.Attempts) } if n := len(fake.Downloads()); n != 2 { t.Fatalf("downloads = %d, want 2", n) } } // slowFail is a coordinator whose Fail call returns late: the core has // already put the job back in the queue, but the worker slot that reported // the failure is still busy with the answer. type slowFail struct { *sched.Local failed chan struct{} // closed when Fail may return uploaded chan struct{} } func (c *slowFail) Fail(ctx context.Context, req workerproto.FailRequest) error { err := c.Local.Fail(ctx, req) <-c.failed return err } func (c *slowFail) Upload(ctx context.Context, job *workerproto.Job, path string) error { // The retry has its file. Now let the first attempt finish and clean // up after itself, and only then upload. close(c.failed) time.Sleep(150 * time.Millisecond) defer close(c.uploaded) return c.Local.Upload(ctx, job, path) } // A retry can start on another slot of the same worker while the slot // that failed is still wrapping up. The cleanup of the failed attempt must // not remove the files of the retry. func TestWorkerRetryDoesNotLoseItsFileToTheFailedAttempt(t *testing.T) { url := "https://example.com/flaky" fake := &ytdlptest.Fake{FileSize: 4096, DownloadErrs: map[string][]error{ url: {&ytdlp.Error{Code: ytdlp.CodeNetwork, Retryable: true, Raw: "connection reset"}}, }} st, err := storage.NewLocal(filepath.Join(t.TempDir(), "files")) if err != nil { t.Fatal(err) } store := dbtest.Open(t).Store() sc := sched.New(store, sched.Config{Lease: 5 * time.Second, MaxAttempts: 2}, nil) coord := &slowFail{Local: &sched.Local{Sched: sc, Storage: st}, failed: make(chan struct{}), uploaded: make(chan struct{})} w := worker.New(worker.Config{ ID: "w1", Concurrency: 2, TempDir: filepath.Join(t.TempDir(), "tmp"), Heartbeat: 30 * time.Millisecond, ClaimWait: 100 * time.Millisecond, }, coord, fake, nil) ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { defer close(done); w.Run(ctx) }() defer func() { cancel(); <-done }() job, _, err := sc.Enqueue(ctx, sched.EnqueueParams{URL: url, Profile: "best", UserID: 1, ChatID: 1, MaxSize: 10 << 20}) if err != nil { t.Fatal(err) } select { case <-coord.uploaded: case <-time.After(10 * time.Second): t.Fatal("the retry never reached its upload") } deadline := time.Now().Add(5 * time.Second) for { got, err := store.GetJob(ctx, job.ID) if err != nil { t.Fatal(err) } if got.Status == db.JobDelivering { if obj, err := st.Stat(ctx, got.StorageKey); err != nil || obj.Size != 4096 { t.Fatalf("stored object = %+v, %v", obj, err) } return } if got.Status == db.JobFailed || time.Now().After(deadline) { t.Fatalf("job is %s (%s): the retry lost its file to the cleanup of the first attempt", got.Status, got.ErrorCode) } time.Sleep(10 * time.Millisecond) } } func TestWorkerGivesUpAfterSecondFailure(t *testing.T) { url := "https://example.com/down" netErr := &ytdlp.Error{Code: ytdlp.CodeNetwork, Retryable: true, Raw: "boom"} fake := &ytdlptest.Fake{DownloadErrs: map[string][]error{url: {netErr, netErr, netErr}}} r := newRig(t, fake, 2) job, _ := r.enqueue(url, "best") got := r.waitStatus(job.ID, db.JobFailed, db.JobDelivering) if got.Status != db.JobFailed || got.ErrorCode != string(ytdlp.CodeNetwork) || got.Attempts != 2 { t.Fatalf("status=%s code=%s attempts=%d", got.Status, got.ErrorCode, got.Attempts) } if !r.tempDirEmpty() { t.Fatal("the temp dir must be removed after a failure") } } func TestWorkerDoesNotRetryPermanentFailure(t *testing.T) { url := "https://example.com/private" fake := &ytdlptest.Fake{DownloadErrs: map[string][]error{ url: {&ytdlp.Error{Code: ytdlp.CodePrivate, Raw: "Private video"}}, }} r := newRig(t, fake, 2) job, _ := r.enqueue(url, "best") got := r.waitStatus(job.ID, db.JobFailed, db.JobDelivering) if got.Status != db.JobFailed || got.ErrorCode != string(ytdlp.CodePrivate) || got.Attempts != 1 { t.Fatalf("status=%s code=%s attempts=%d", got.Status, got.ErrorCode, got.Attempts) } } func TestWorkerEnforcesSizeCap(t *testing.T) { r := newRig(t, &ytdlptest.Fake{FileSize: 11 << 20}, 2) // cap is 10 MB job, _ := r.enqueue("https://example.com/big", "best") got := r.waitStatus(job.ID, db.JobFailed, db.JobDelivering) if got.Status != db.JobFailed || got.ErrorCode != string(ytdlp.CodeTooLarge) { t.Fatalf("status=%s code=%s, want failed too_large", got.Status, got.ErrorCode) } } func TestWorkerStopsWhenRequesterCancels(t *testing.T) { block := make(chan struct{}) defer close(block) r := newRig(t, &ytdlptest.Fake{Block: block}, 2) job, del := r.enqueue("https://example.com/slow", "best") r.waitStatus(job.ID, db.JobRunning) if _, err := r.sched.CancelDelivery(context.Background(), del.ID, 1); err != nil { t.Fatal(err) } got := r.waitStatus(job.ID, db.JobCancelled, db.JobDelivering, db.JobFailed) if got.Status != db.JobCancelled { t.Fatalf("status = %s, want cancelled", got.Status) } if !r.tempDirEmpty() { t.Fatal("the temp dir must be removed after a cancel") } } func TestWorkerShutdownHandsJobBack(t *testing.T) { block := make(chan struct{}) defer close(block) r := newRig(t, &ytdlptest.Fake{Block: block}, 2) job, _ := r.enqueue("https://example.com/slow", "best") r.waitStatus(job.ID, db.JobRunning) r.stop() got, err := r.store.GetJob(context.Background(), job.ID) if err != nil { t.Fatal(err) } if got.Status != db.JobQueued || got.Attempts != 0 { t.Fatalf("status=%s attempts=%d, want queued with the attempt refunded", got.Status, got.Attempts) } } func TestWorkerKeepsLeaseAliveDuringLongDownload(t *testing.T) { // The lease is 2 seconds and the download takes longer than that; only // heartbeats keep the job from being requeued. fake := &ytdlptest.Fake{Delay: 2500 * time.Millisecond} r := newRig(t, fake, 1) stop := make(chan struct{}) go func() { for { select { case <-stop: return case <-time.After(100 * time.Millisecond): _, _ = r.sched.RequeueExpired(context.Background()) } } }() defer close(stop) job, _ := r.enqueue("https://example.com/long", "best") got := r.waitStatus(job.ID, db.JobDelivering, db.JobFailed) if got.Status != db.JobDelivering || got.Attempts != 1 { t.Fatalf("status=%s attempts=%d code=%s, want delivering on the first attempt", got.Status, got.Attempts, got.ErrorCode) } } func TestWorkerSweepsOrphanTempDirsOnStart(t *testing.T) { tmp := filepath.Join(t.TempDir(), "tmp") orphan := filepath.Join(tmp, "01m7prt365sxa914sf593cc7dq") // shaped like a job ID keep := filepath.Join(tmp, "not-a-job") for _, d := range []string{orphan, keep} { if err := os.MkdirAll(d, 0o750); err != nil { t.Fatal(err) } } st, err := storage.NewLocal(filepath.Join(t.TempDir(), "files")) if err != nil { t.Fatal(err) } s := sched.New(dbtest.Open(t).Store(), sched.Config{}, nil) w := worker.New(worker.Config{ID: "w", TempDir: tmp, ClaimWait: 50 * time.Millisecond}, &sched.Local{Sched: s, Storage: st}, &ytdlptest.Fake{}, nil) ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { defer close(done); w.Run(ctx) }() deadline := time.Now().Add(5 * time.Second) for { if _, err := os.Stat(orphan); os.IsNotExist(err) { break } if time.Now().After(deadline) { t.Fatal("the orphan job dir was not removed") } time.Sleep(10 * time.Millisecond) } cancel() <-done if _, err := os.Stat(keep); err != nil { t.Fatalf("a directory that is not a job dir must be left alone: %v", err) } }