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
+316
View File
@@ -0,0 +1,316 @@
// Package worker is the stateless download worker. It pulls jobs from a
// Coordinator, runs yt-dlp, uploads the result and reports back. It never
// sees the bot token.
package worker
import (
"context"
"errors"
"log/slog"
"math"
"os"
"path/filepath"
"sync"
"sync/atomic"
"time"
"github.com/noderunners/dlbot/internal/ids"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/workerproto"
"github.com/noderunners/dlbot/internal/ytdlp"
)
// Coordinator is the worker's view of the core. The embedded worker calls
// the scheduler directly; remote workers use the HTTPS client.
type Coordinator interface {
Claim(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.Job, error)
Heartbeat(ctx context.Context, req workerproto.HeartbeatRequest) (workerproto.HeartbeatResponse, error)
Complete(ctx context.Context, req workerproto.CompleteRequest) error
Fail(ctx context.Context, req workerproto.FailRequest) error
// Upload stores the finished file under the job's upload key.
Upload(ctx context.Context, job *workerproto.Job, path string) error
}
// Config holds the worker settings.
type Config struct {
ID string
Tags []string
Concurrency int
TempDir string
// Heartbeat is how often the lease is extended. Defaults to 10 seconds.
Heartbeat time.Duration
// ClaimWait is how long one claim call may wait for work.
ClaimWait time.Duration
}
// Worker runs download jobs.
type Worker struct {
cfg Config
coord Coordinator
runner ytdlp.Runner
log *slog.Logger
active atomic.Int32
}
// New creates a worker.
func New(cfg Config, coord Coordinator, runner ytdlp.Runner, log *slog.Logger) *Worker {
if cfg.Concurrency < 1 {
cfg.Concurrency = 1
}
if cfg.Heartbeat <= 0 {
cfg.Heartbeat = 10 * time.Second
}
if cfg.ClaimWait <= 0 {
cfg.ClaimWait = 20 * time.Second
}
if log == nil {
log = slog.Default()
}
return &Worker{cfg: cfg, coord: coord, runner: runner, log: log.With("worker_id", cfg.ID)}
}
// Active returns the number of jobs running right now.
func (w *Worker) Active() int { return int(w.active.Load()) }
// Run starts the worker slots and blocks until the context ends and every
// running job has stopped.
func (w *Worker) Run(ctx context.Context) {
if err := os.MkdirAll(w.cfg.TempDir, 0o750); err != nil {
w.log.Error("cannot create temp dir", "dir", w.cfg.TempDir, "err", err)
}
w.sweepOrphans()
var wg sync.WaitGroup
for i := 0; i < w.cfg.Concurrency; i++ {
wg.Add(1)
go func() {
defer wg.Done()
w.slot(ctx)
}()
}
wg.Wait()
}
// sweepOrphans removes job directories left behind by a crash. A worker is
// stateless, so nothing in its temp dir is valid at startup. Only names
// that look like job IDs are touched, and every worker process must have
// its own temp dir.
func (w *Worker) sweepOrphans() {
entries, err := os.ReadDir(w.cfg.TempDir)
if err != nil {
return
}
for _, e := range entries {
if !e.IsDir() || !ids.Valid(e.Name()) {
continue
}
if err := os.RemoveAll(filepath.Join(w.cfg.TempDir, e.Name())); err != nil {
w.log.Warn("cannot remove orphan temp dir", "name", e.Name(), "err", err)
continue
}
w.log.Info("removed orphan temp dir", "name", e.Name())
}
}
func (w *Worker) slot(ctx context.Context) {
backoff := time.Second
for ctx.Err() == nil {
job, err := w.coord.Claim(ctx, workerproto.ClaimRequest{
WorkerID: w.cfg.ID,
Tags: w.cfg.Tags,
Capacity: w.cfg.Concurrency,
Active: w.Active(),
WaitSeconds: int(math.Ceil(w.cfg.ClaimWait.Seconds())),
})
if err != nil {
if ctx.Err() != nil {
return
}
w.log.Warn("claim failed", "err", err, "retry_in", backoff.String())
sleep(ctx, backoff)
if backoff < 30*time.Second {
backoff *= 2
}
continue
}
backoff = time.Second
if job == nil {
continue // the coordinator already waited for ClaimWait
}
w.active.Add(1)
w.process(ctx, job)
w.active.Add(-1)
}
}
// process runs one job to completion and always reports an outcome.
func (w *Worker) process(ctx context.Context, job *workerproto.Job) {
log := w.log.With("job_id", job.ID, "attempt", job.Attempt)
dir := filepath.Join(w.cfg.TempDir, job.ID)
defer func() {
if err := os.RemoveAll(dir); err != nil {
log.Warn("cannot remove temp dir", "err", err)
}
}()
jobCtx, cancel := context.WithCancel(ctx)
defer cancel()
var (
mu sync.Mutex
progress = ytdlp.Progress{Stage: ytdlp.StageDownloading}
cancelled atomic.Bool
leaseLost atomic.Bool
)
setStage := func(stage string) {
mu.Lock()
progress.Stage = stage
mu.Unlock()
}
beat := func() {
mu.Lock()
p := progress
mu.Unlock()
// Reports use their own short deadline so a shutdown still gets
// through, and a hung core cannot block the job forever.
hctx, hcancel := context.WithTimeout(context.WithoutCancel(ctx), w.cfg.Heartbeat)
defer hcancel()
resp, err := w.coord.Heartbeat(hctx, workerproto.HeartbeatRequest{
WorkerID: w.cfg.ID, JobID: job.ID, Stage: p.Stage, Downloaded: p.Downloaded, Total: p.Total,
})
switch {
case isLeaseLost(err):
leaseLost.Store(true)
cancel()
case err != nil:
log.Warn("heartbeat failed", "err", err)
case resp.Cancel:
cancelled.Store(true)
cancel()
}
}
hbDone := make(chan struct{})
go func() {
defer close(hbDone)
t := time.NewTicker(w.cfg.Heartbeat)
defer t.Stop()
for {
select {
case <-jobCtx.Done():
return
case <-t.C:
beat()
}
}
}()
stopHeartbeat := func() {
cancel()
<-hbDone
}
profile, perr := media.Parse(job.Profile)
var (
res *ytdlp.Result
err error
)
if perr != nil {
err = &ytdlp.Error{Code: ytdlp.CodeInternal, Raw: perr.Error()}
} else {
res, err = w.runner.Download(jobCtx, ytdlp.DownloadRequest{
URL: job.URL,
Profile: profile,
Dir: dir,
MaxSize: job.MaxSize,
MaxDuration: time.Duration(job.MaxDuration) * time.Second,
}, func(p ytdlp.Progress) {
mu.Lock()
if p.Stage == ytdlp.StageProcessing {
progress.Stage = p.Stage
} else {
progress = p
}
mu.Unlock()
})
}
if err == nil {
setStage(ytdlp.StageUploading)
beat()
if jobCtx.Err() == nil {
if uerr := w.coord.Upload(jobCtx, job, res.Path); uerr != nil {
err = &ytdlp.Error{Code: ytdlp.CodeInternal, Retryable: true, Raw: "upload: " + uerr.Error()}
}
}
}
stopHeartbeat()
// Outcome reports must go out even when the worker is shutting down.
rctx, rcancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer rcancel()
switch {
case leaseLost.Load():
log.Warn("lease lost, dropping job")
return
case cancelled.Load():
w.report(log, w.coord.Fail(rctx, workerproto.FailRequest{
WorkerID: w.cfg.ID, JobID: job.ID, Code: string(ytdlp.CodeCancelled),
}))
return
case ctx.Err() != nil:
// Shutdown in the middle of a job: hand it back for another worker.
w.report(log, w.coord.Fail(rctx, workerproto.FailRequest{
WorkerID: w.cfg.ID, JobID: job.ID, Code: string(ytdlp.CodeWorkerLost), Retryable: true,
Detail: "worker shut down",
}))
return
case err != nil:
var ye *ytdlp.Error
if !errors.As(err, &ye) {
ye = &ytdlp.Error{Code: ytdlp.CodeUnknown, Retryable: true, Raw: err.Error()}
}
log.Info("job failed", "code", string(ye.Code), "retryable", ye.Retryable)
w.report(log, w.coord.Fail(rctx, workerproto.FailRequest{
WorkerID: w.cfg.ID, JobID: job.ID, Code: string(ye.Code), Retryable: ye.Retryable, Detail: ye.Raw,
}))
return
}
w.report(log, w.coord.Complete(rctx, workerproto.CompleteRequest{
WorkerID: w.cfg.ID,
JobID: job.ID,
StorageKey: job.UploadKey,
Ext: res.Ext,
Size: res.Size,
Duration: int64(math.Round(res.Duration)),
Width: res.Width,
Height: res.Height,
Title: res.Title,
Uploader: res.Uploader,
Extractor: res.Extractor,
VideoID: res.ID,
}))
}
func (w *Worker) report(log *slog.Logger, err error) {
if err != nil && !isLeaseLost(err) {
log.Error("cannot report job outcome", "err", err)
}
}
// LeaseLost is implemented by coordinator errors that mean the job was
// taken away from this worker.
type LeaseLost interface{ LeaseLost() bool }
func isLeaseLost(err error) bool {
var ll LeaseLost
return err != nil && errors.As(err, &ll) && ll.LeaseLost()
}
func sleep(ctx context.Context, d time.Duration) {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
case <-t.C:
}
}
+282
View File
@@ -0,0 +1,282 @@
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)
}
}