Files
Media-download-telegram-bot/internal/worker/worker_test.go
T
MichilisandClaude Fable 5.2 3b361c17a1 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>
2026-11-18 07:33:32 +00:00

283 lines
8.7 KiB
Go

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/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)
}
}
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)
}
}