package app_test import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "log/slog" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "sync" "sync/atomic" "testing" "time" "github.com/johannesboyne/gofakes3" "github.com/johannesboyne/gofakes3/backend/s3mem" "github.com/noderunners/dlbot/internal/app" "github.com/noderunners/dlbot/internal/config" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/storage" "github.com/noderunners/dlbot/internal/tg/fakeserver" "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" ) const ( tokenW1 = "dlw_test_token_for_worker_one_0001" tokenW2 = "dlw_test_token_for_worker_two_0002" ) // fleet is a core without an embedded worker plus remote workers that // talk to it over real HTTP, the way separate machines would. type fleet struct { *harness base string } func startFleet(t *testing.T, mut func(*config.Config)) *fleet { t.Helper() addr := freePort(t) h := start(t, nil, func(c *config.Config) { c.HTTP.Listen = addr c.Worker.Embedded = false c.WorkerTokens = []string{"w1:" + tokenW1, "w2:" + tokenW2} c.Worker.ProbeTimeout = config.Duration(3 * time.Second) if mut != nil { mut(c) } }) return &fleet{harness: h, base: "http://" + addr} } // remote is one running remote worker. type remote struct { fake *ytdlptest.Fake commands chan string cancel context.CancelFunc done chan struct{} crashed *atomic.Bool } // crashable drops every call once the worker "died", which is what the // core sees when a machine loses power: silence. type crashable struct { *worker.HTTPCoordinator dead *atomic.Bool } var errDead = errors.New("worker is dead") func (c *crashable) ClaimAny(ctx context.Context, r workerproto.ClaimRequest) (*workerproto.ClaimResponse, error) { if c.dead.Load() { return nil, errDead } return c.HTTPCoordinator.ClaimAny(ctx, r) } func (c *crashable) Claim(ctx context.Context, r workerproto.ClaimRequest) (*workerproto.Job, error) { if c.dead.Load() { return nil, errDead } return c.HTTPCoordinator.Claim(ctx, r) } func (c *crashable) Heartbeat(ctx context.Context, r workerproto.HeartbeatRequest) (workerproto.HeartbeatResponse, error) { if c.dead.Load() { return workerproto.HeartbeatResponse{}, errDead } return c.HTTPCoordinator.Heartbeat(ctx, r) } func (c *crashable) Complete(ctx context.Context, r workerproto.CompleteRequest) error { if c.dead.Load() { return errDead } return c.HTTPCoordinator.Complete(ctx, r) } func (c *crashable) Fail(ctx context.Context, r workerproto.FailRequest) error { if c.dead.Load() { return errDead } return c.HTTPCoordinator.Fail(ctx, r) } func (c *crashable) ProbeResult(ctx context.Context, r workerproto.ProbeResult) error { if c.dead.Load() { return errDead } return c.HTTPCoordinator.ProbeResult(ctx, r) } func (f *fleet) worker(token string, tags []string, fake *ytdlptest.Fake) *remote { f.t.Helper() if fake == nil { fake = &ytdlptest.Fake{} } r := &remote{fake: fake, commands: make(chan string, 8), done: make(chan struct{}), crashed: &atomic.Bool{}} coord := &crashable{HTTPCoordinator: worker.NewHTTPCoordinator(f.base, token), dead: r.crashed} w := worker.New(worker.Config{ ID: "remote", Tags: tags, Concurrency: 1, TempDir: filepath.Join(f.t.TempDir(), "tmp"), Heartbeat: 40 * time.Millisecond, ClaimWait: time.Second, ProbeSlots: 1, Version: func() string { return "2026.01.01" }, OnCommand: func(c string) { r.commands <- c }, }, coord, fake, slog.New(slog.NewTextHandler(io.Discard, nil))) w.SetTranscoder(&fakeTranscoder{}) ctx, cancel := context.WithCancel(context.Background()) r.cancel = cancel go func() { defer close(r.done) w.Run(ctx) }() f.t.Cleanup(r.stop) return r } // stop shuts the worker down cleanly: it hands its job back. func (r *remote) stop() { r.cancel() select { case <-r.done: case <-time.After(10 * time.Second): } } // kill simulates a machine that dies: no goodbye, no more heartbeats. func (r *remote) kill() { r.crashed.Store(true) r.cancel() } func (f *fleet) jobOf(status string) *db.Job { f.t.Helper() js := f.waitJobs(status, 1) return js[0] } func (f *fleet) post(path, token string, body any) (int, string) { f.t.Helper() data, _ := json.Marshal(body) req, _ := http.NewRequest(http.MethodPost, f.base+path, bytes.NewReader(data)) if token != "" { req.Header.Set("Authorization", "Bearer "+token) } req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { f.t.Fatal(err) } defer resp.Body.Close() b, _ := io.ReadAll(resp.Body) return resp.StatusCode, string(b) } func TestRemoteWorkerDoesEverythingOverHTTP(t *testing.T) { f := startFleet(t, nil) w1 := f.worker(tokenW1, []string{"eu"}, &ytdlptest.Fake{FileSize: 5000}) // Even the card depends on the worker: the core has no yt-dlp here. card := f.card(alice, alice, link) if n := len(w1.fake.Probes()); n != 1 { t.Fatalf("the worker ran %d probes, want 1", n) } seq := f.press(alice, alice, card, "dl:") video := f.wait(seq, "sendVideo", nil) if video.Files["video"].Size != 5000 { t.Fatalf("the file that went through the worker upload is wrong: %+v", video.Files) } f.wait(seq, edits, textHas("Done")) job := f.jobOf(db.JobDone) if job.WorkerID != "w1" || job.Attempts != 1 { t.Fatalf("job worker=%q attempts=%d", job.WorkerID, job.Attempts) } // The core recorded what the worker advertised. wk, err := f.app.Store.GetWorker(context.Background(), "w1") if err != nil || wk.Tags != "eu" || wk.Capacity != 1 || wk.Version != "2026.01.01" || wk.LastSeenAt == 0 { t.Fatalf("worker row = %+v, %v", wk, err) } if got := f.app.Sched.Capacity(); got != 1 { t.Fatalf("fleet capacity = %d", got) } } // Acceptance: kill a worker mid-job, the job is re-queued and finished by // the other worker. func TestKilledWorkerJobIsRequeuedAndFinishedByTheOther(t *testing.T) { f := startFleet(t, nil) stuck := make(chan struct{}) defer close(stuck) w1 := f.worker(tokenW1, nil, &ytdlptest.Fake{Block: stuck}) card := f.card(alice, alice, link) seq := f.press(alice, alice, card, "dl:") running := f.jobOf(db.JobRunning) if running.WorkerID != "w1" { t.Fatalf("the job should be on w1, is on %q", running.WorkerID) } f.wait(seq, edits, textHas("Downloading")) // A second worker comes online, and the first one dies mid-download. w2 := f.worker(tokenW2, nil, &ytdlptest.Fake{FileSize: 7777}) w1.kill() // Nobody tells the core. It notices the missing heartbeats, puts the // job back in the queue, and the surviving worker finishes it. video := f.wait(seq, "sendVideo", nil) if video.Files["video"].Size != 7777 { t.Fatalf("the delivered file did not come from the second worker: %+v", video.Files) } f.wait(seq, edits, textHas("Done")) done := f.jobOf(db.JobDone) if done.ID != running.ID || done.WorkerID != "w2" || done.Attempts != 2 { t.Fatalf("job id=%s worker=%q attempts=%d, want the same job finished by w2 on attempt 2", done.ID, done.WorkerID, done.Attempts) } if n := len(w2.fake.Downloads()); n != 1 { t.Fatalf("w2 downloads = %d", n) } // The requester got the file exactly once. if n := len(f.srv.Calls("sendVideo")); n != 1 { t.Fatalf("sendVideo calls = %d, want 1", n) } // The dead worker coming back with a late report is turned away. code, _ := f.post("/worker/v1/complete", tokenW1, workerproto.CompleteRequest{JobID: done.ID}) if code != http.StatusConflict && code != http.StatusUnprocessableEntity { t.Fatalf("late complete from the dead worker answered %d", code) } } func TestCleanWorkerShutdownHandsTheJobOverAtOnce(t *testing.T) { f := startFleet(t, func(c *config.Config) { c.Queue.Lease = config.Duration(time.Hour) }) stuck := make(chan struct{}) defer close(stuck) w1 := f.worker(tokenW1, nil, &ytdlptest.Fake{Block: stuck}) card := f.card(alice, alice, link) seq := f.press(alice, alice, card, "dl:") f.jobOf(db.JobRunning) f.worker(tokenW2, nil, nil) w1.stop() // SIGTERM, not a crash // With a one hour lease only an explicit hand-back explains this. f.wait(seq, "sendVideo", nil) if done := f.jobOf(db.JobDone); done.WorkerID != "w2" || done.Attempts != 1 { t.Fatalf("worker=%q attempts=%d, want w2 with the attempt refunded", done.WorkerID, done.Attempts) } } func TestJobsForTaggedSitesOnlyGoToWorkersWithTheTag(t *testing.T) { f := startFleet(t, func(c *config.Config) { c.SiteTags = map[string][]string{"example.com": {"residential"}} c.Worker.ProbeTimeout = config.Duration(600 * time.Millisecond) }) plain := f.worker(tokenW1, []string{"datacenter"}, nil) // The only worker lacks the tag: not even the lookup is given to it. seq := f.srv.Seq() f.srv.PushMessage(alice, alice, link) f.wait(seq, "editMessageText", textHas("took too long")) if n := len(plain.fake.Probes()); n != 0 { t.Fatalf("a worker without the tag ran %d probes", n) } residential := f.worker(tokenW2, []string{"residential", "eu"}, nil) card := f.card(bob, bob, "https://www.example.com/other") seq = f.press(bob, bob, card, "dl:") f.wait(seq, "sendVideo", nil) job := f.jobOf(db.JobDone) if job.WorkerID != "w2" || job.RequiredTags != "residential" { t.Fatalf("job worker=%q required_tags=%q", job.WorkerID, job.RequiredTags) } if len(plain.fake.Downloads()) != 0 || len(residential.fake.Downloads()) != 1 { t.Fatalf("downloads plain=%d residential=%d", len(plain.fake.Downloads()), len(residential.fake.Downloads())) } // A site without a rule can use any worker. if got := f.cfg.RequiredTags("other.org"); got != "" { t.Fatalf("RequiredTags(other.org) = %q", got) } } func TestDrainAndWorkersCommands(t *testing.T) { f := startFleet(t, func(c *config.Config) { c.Owners = []int64{alice} }) w1 := f.worker(tokenW1, []string{"eu"}, nil) w2 := f.worker(tokenW2, nil, nil) f.card(bob, bob, link) // makes sure both workers have checked in // Only the owner may drain. seq := f.srv.Seq() f.srv.PushMessage(bob, bob, "/drain w1") f.never(seq, "sendMessage", textHas("draining")) seq = f.srv.Seq() f.srv.PushMessage(alice, alice, "/drain w1") f.wait(seq, "sendMessage", textHas("is draining")) time.Sleep(1200 * time.Millisecond) // let w1's open claim run out for i := 0; i < 3; i++ { card := f.card(bob, bob, fmt.Sprintf("https://example.com/d%d", i)) seq := f.press(bob, bob, card, "dl:") f.wait(seq, edits, textHas("Done")) } if n := len(w1.fake.Downloads()); n != 0 { t.Fatalf("a draining worker took %d jobs", n) } if n := len(w2.fake.Downloads()); n != 3 { t.Fatalf("w2 took %d jobs, want 3", n) } seq = f.srv.Seq() f.srv.PushMessage(alice, alice, "/workers") list := f.wait(seq, "sendMessage", textHas("Workers")) for _, want := range []string{"w1 · draining", "w2 · active", "tags: eu", "yt-dlp 2026.01.01", "2 remote workers registered"} { if !strings.Contains(list.Text(), want) { t.Errorf("/workers lacks %q:\n%s", want, list.Text()) } } seq = f.srv.Seq() f.srv.PushMessage(alice, alice, "/drain w1 off") f.wait(seq, "sendMessage", textHas("takes jobs again")) seq = f.srv.Seq() f.srv.PushMessage(alice, alice, "/drain nobody") f.wait(seq, "sendMessage", textHas("no worker named")) // /ytdlp update reaches the workers with their next claim. seq = f.srv.Seq() f.srv.PushMessage(alice, alice, "/ytdlp update") f.wait(seq, "sendMessage", textHas("Asked 2 workers")) for _, w := range []*remote{w1, w2} { select { case cmd := <-w.commands: if cmd != workerproto.CommandUpdateYtDlp { t.Fatalf("command = %q", cmd) } case <-time.After(5 * time.Second): t.Fatal("a worker never got the update command") } } } func TestWorkerAPIAuthAndOwnership(t *testing.T) { f := startFleet(t, nil) stuck := make(chan struct{}) defer close(stuck) f.worker(tokenW1, nil, &ytdlptest.Fake{Block: stuck}) card := f.card(alice, alice, link) f.press(alice, alice, card, "dl:") job := f.jobOf(db.JobRunning) // owned by w1 claim := workerproto.ClaimRequest{Capacity: 1} for name, token := range map[string]string{"no token": "", "unknown token": "dlw_nope", "garbage": "x y z"} { if code, _ := f.post("/worker/v1/claim", token, claim); code != http.StatusUnauthorized { t.Errorf("%s: claim answered %d, want 401", name, code) } } // A worker cannot act on another worker's job, whatever ID it sends. hb := workerproto.HeartbeatRequest{WorkerID: "w1", JobID: job.ID} if code, _ := f.post("/worker/v1/heartbeat", tokenW2, hb); code != http.StatusConflict { t.Errorf("heartbeat for a foreign job answered %d, want 409", code) } if code, _ := f.post("/worker/v1/fail", tokenW2, workerproto.FailRequest{WorkerID: "w1", JobID: job.ID, Code: "unknown"}); code != http.StatusConflict { t.Errorf("fail for a foreign job answered %d, want 409", code) } put := func(token, jobID string, body []byte) int { req, _ := http.NewRequest(http.MethodPut, f.base+"/worker/v1/upload/"+jobID, bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+token) resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } resp.Body.Close() return resp.StatusCode } if code := put(tokenW2, job.ID, []byte("stolen")); code != http.StatusConflict { t.Errorf("upload to a foreign job answered %d, want 409", code) } // Completing without an upload is refused: the core checks storage. if code, _ := f.post("/worker/v1/complete", tokenW1, workerproto.CompleteRequest{JobID: job.ID, StorageKey: "jobs/other/media"}); code != http.StatusUnprocessableEntity { t.Errorf("complete without a file answered %d, want 422", code) } // The owner of the job can upload, but not past the job's size cap. if code := put(tokenW1, job.ID, []byte("fine")); code != http.StatusOK { t.Errorf("upload by the owner answered %d", code) } big := make([]byte, int(job.MaxSize)+10) if code := put(tokenW1, job.ID, big); code != http.StatusRequestEntityTooLarge { t.Errorf("oversized upload answered %d, want 413", code) } if n := f.storedFiles(); n != 0 { t.Errorf("an oversized upload left %d files behind", n) } if got := f.jobOf(db.JobRunning); got.WorkerID != "w1" { t.Fatalf("the job changed hands: %+v", got) } // Revoking a token locks the worker out at once. if ok, err := f.app.Store.RevokeWorker(context.Background(), "w2"); err != nil || !ok { t.Fatal(err) } if code, _ := f.post("/worker/v1/claim", tokenW2, claim); code != http.StatusUnauthorized { t.Errorf("a revoked worker's claim answered %d, want 401", code) } if code, _ := f.post("/worker/v1/probe", tokenW1, workerproto.ProbeResult{ID: "nope"}); code != http.StatusGone { t.Errorf("an answer to an unknown probe answered %d, want 410", code) } } func TestWorkerAdminCLI(t *testing.T) { f := startFleet(t, nil) ctx := context.Background() var out bytes.Buffer if err := app.WorkerAdmin(ctx, f.cfg, []string{"add", "eu-3"}, &out); err != nil { t.Fatal(err) } i := strings.Index(out.String(), "WORKER_TOKEN=") if i < 0 { t.Fatalf("no token in output: %s", out.String()) } token := strings.Fields(out.String()[i+len("WORKER_TOKEN="):])[0] if !strings.HasPrefix(token, "dlw_") || len(token) < 40 { t.Fatalf("token = %q", token) } // Only the hash is stored. wk, err := f.app.Store.GetWorker(ctx, "eu-3") if err != nil || wk.TokenHash == token || strings.Contains(wk.TokenHash, "dlw_") { t.Fatalf("stored worker = %+v, %v", wk, err) } claim := workerproto.ClaimRequest{Capacity: 1} if code, _ := f.post("/worker/v1/claim", token, claim); code != http.StatusOK { t.Fatalf("the new token was not accepted: %d", code) } out.Reset() if err := app.WorkerAdmin(ctx, f.cfg, []string{"list"}, &out); err != nil { t.Fatal(err) } for _, want := range []string{"eu-3", "w1", "w2", "active"} { if !strings.Contains(out.String(), want) { t.Errorf("list lacks %q:\n%s", want, out.String()) } } if err := app.WorkerAdmin(ctx, f.cfg, []string{"revoke", "eu-3"}, &out); err != nil { t.Fatal(err) } if code, _ := f.post("/worker/v1/claim", token, claim); code != http.StatusUnauthorized { t.Fatalf("a revoked token still works: %d", code) } // Adding the worker again issues a new token and lifts the revocation. out.Reset() if err := app.WorkerAdmin(ctx, f.cfg, []string{"add", "eu-3"}, &out); err != nil { t.Fatal(err) } i = strings.Index(out.String(), "WORKER_TOKEN=") token2 := strings.Fields(out.String()[i+len("WORKER_TOKEN="):])[0] if token2 == token { t.Fatal("re-adding must issue a new token") } if code, _ := f.post("/worker/v1/claim", token2, claim); code != http.StatusOK { t.Fatalf("the re-issued token was not accepted: %d", code) } if code, _ := f.post("/worker/v1/claim", token, claim); code != http.StatusUnauthorized { t.Fatal("the old token must stay dead") } for _, bad := range [][]string{{}, {"add"}, {"add", "Bad Name"}, {"revoke", "ghost"}, {"explode"}} { if err := app.WorkerAdmin(ctx, f.cfg, bad, io.Discard); err == nil { t.Errorf("WorkerAdmin(%v) should fail", bad) } } } func TestDeriveOverHTTPFetchesTheSourceFromTheCore(t *testing.T) { hd := ytdlptest.DefaultInfo(link) hd.Formats = append(hd.Formats, ytdlp.Format{FormatID: "v1080", Ext: "mp4", VCodec: "avc1", ACodec: "none", Height: 1080, Filesize: 20 << 20}) f := startFleet(t, nil) w1 := f.worker(tokenW1, nil, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{link: hd}}) f.fetch(alice, link) card := f.card(bob, bob, link) seq := f.press(bob, bob, card, "dl:"+strings.Split(card.Buttons()[0].Data, ":")[1]+":480") video := f.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == bob }) if video.Files["video"].Size != 500 || video.Params["height"] != "480" { t.Fatalf("derived video = %+v %+v", video.Params, video.Files) } if n := len(w1.fake.Downloads()); n != 1 { t.Fatalf("yt-dlp ran %d times, the 480p file should be transcoded from the stored copy", n) } } func TestManyJobsAcrossTwoWorkersEachRunOnce(t *testing.T) { f := startFleet(t, func(c *config.Config) { c.Limits.Free.ActiveJobs = 50 c.Limits.Free.DailyDownloads = 100 c.Queue.FreeMaxLen = 100 c.Rate.UserPerMinute = 0 }) w1 := f.worker(tokenW1, nil, &ytdlptest.Fake{Delay: 20 * time.Millisecond}) w2 := f.worker(tokenW2, nil, &ytdlptest.Fake{Delay: 20 * time.Millisecond}) const n = 12 var wg sync.WaitGroup for i := 0; i < n; i++ { card := f.card(alice, alice, fmt.Sprintf("https://example.com/many%d", i)) wg.Add(1) go func() { defer wg.Done() f.press(alice, alice, card, "dl:") }() } wg.Wait() f.waitJobs(db.JobDone, n) a, b := len(w1.fake.Downloads()), len(w2.fake.Downloads()) if a+b != n || a == 0 || b == 0 { t.Fatalf("downloads w1=%d w2=%d, want %d in total, shared by both", a, b, n) } if got := len(f.srv.Calls("sendVideo")); got != n { t.Fatalf("sendVideo calls = %d, want %d", got, n) } _ = os.Getenv // keep the import for the opt-in tests below } // fakeS3Server starts an in-memory S3 with one bucket and returns its URL. func fakeS3Server(t *testing.T, bucket string) string { t.Helper() backend := s3mem.New() if err := backend.CreateBucket(bucket); err != nil { t.Fatal(err) } srv := httptest.NewServer(gofakes3.New(backend).Server()) t.Cleanup(srv.Close) return srv.URL } func TestS3StorageWithPresignedWorkerUploads(t *testing.T) { endpoint := fakeS3Server(t, "dlbot") f := startFleet(t, func(c *config.Config) { c.Storage.Backend = "s3" c.Storage.S3 = config.S3{ Endpoint: endpoint, Bucket: "dlbot", AccessKey: "key", SecretKey: "secret-secret", Region: "us-east-1", PathStyle: true, Presign: true, Prefix: "bot1", } }) if _, ok := f.app.Storage.(*storage.S3); !ok { t.Fatalf("storage backend is %T, want S3", f.app.Storage) } hd := ytdlptest.DefaultInfo(link) hd.Formats = append(hd.Formats, ytdlp.Format{FormatID: "v1080", Ext: "mp4", VCodec: "avc1", ACodec: "none", Height: 1080, Filesize: 20 << 20}) w1 := f.worker(tokenW1, nil, &ytdlptest.Fake{FileSize: 6000, Infos: map[string]*ytdlp.Info{link: hd}}) // The worker uploads straight to the bucket; the core reads it from // there and streams it to Telegram. video := f.fetch(alice, link) if video.Files["video"].Size != 6000 { t.Fatalf("file delivered from S3 = %+v", video.Files) } job := f.jobOf(db.JobDone) obj, err := f.app.Storage.Stat(context.Background(), job.StorageKey) if err != nil || obj.Size != 6000 { t.Fatalf("object in the bucket = %+v, %v", obj, err) } // The core's own upload endpoint was not involved. if n := f.storedFiles(); n != 1 { t.Fatalf("objects in the bucket = %d, want the cached copy", n) } // A cache hit is served from S3 metadata, and a derive job fetches its // source from the bucket by presigned URL. again := f.fetch(bob, link) if uploaded(again, "video") { t.Fatal("the second request should be a cache hit") } card := f.card(carol, carol, link) seq := f.press(carol, carol, card, "dl:"+strings.Split(card.Buttons()[0].Data, ":")[1]+":480") derived := f.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == carol }) if derived.Files["video"].Size != 500 { t.Fatalf("derived file = %+v", derived.Files) } if n := len(w1.fake.Downloads()); n != 1 { t.Fatalf("downloads = %d, want 1", n) } }