// 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/ffmpeg" "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 // Fetch copies the job's source file from storage to a local path. // It is only used by derive jobs. Fetch(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 trans ffmpeg.Transcoder log *slog.Logger active atomic.Int32 } // SetTranscoder gives the worker the means to run derive jobs. Without it // a derive job fails and the core falls back to a plain download. func (w *Worker) SetTranscoder(t ffmpeg.Transcoder) { w.trans = t } // 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 ) switch { case perr != nil: err = &ytdlp.Error{Code: ytdlp.CodeInternal, Raw: perr.Error()} case job.Kind == workerproto.KindDerive: res, err = w.derive(jobCtx, job, dir, profile, setStage) default: 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()} } } } // The file is in storage (or the job failed): the local copy has no // further use. Removing it now, before the outcome is reported, frees // the disk as early as possible. if rmErr := os.RemoveAll(dir); rmErr != nil { log.Warn("cannot remove temp dir", "err", rmErr) } 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, })) } // derive transcodes the job's stored source into the requested profile. func (w *Worker) derive(ctx context.Context, job *workerproto.Job, dir string, profile media.Profile, setStage func(string)) (*ytdlp.Result, error) { if w.trans == nil { return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: "this worker has no transcoder"} } if err := os.MkdirAll(dir, 0o750); err != nil { return nil, &ytdlp.Error{Code: ytdlp.CodeInternal, Retryable: true, Raw: err.Error()} } src := filepath.Join(dir, "source") if err := w.coord.Fetch(ctx, job, src); err != nil { if ctx.Err() != nil { return nil, &ytdlp.Error{Code: ytdlp.CodeCancelled, Raw: "cancelled"} } return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: "fetch source: " + err.Error()} } setStage(ytdlp.StageProcessing) res, err := w.trans.Derive(ctx, src, filepath.Join(dir, "out"), profile) if err != nil { return nil, err } if job.MaxSize > 0 && res.Size > job.MaxSize { return nil, &ytdlp.Error{Code: ytdlp.CodeTooLarge, Raw: "derived file is over the cap"} } return res, nil } 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: } }