// 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" "encoding/json" "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 // ProbeSlots is the number of extra claim loops that only take // metadata lookups. They need a Prober coordinator and are 0 for the // embedded worker, whose core runs lookups itself. ProbeSlots int // Version returns the yt-dlp version to report. It may be nil. Version func() string // OnCommand is called for instructions from the core. It may be nil. OnCommand func(cmd string) } // Prober is the part of a coordinator that hands out metadata lookups. // Only the HTTP coordinator implements it. type Prober interface { ClaimAny(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.ClaimResponse, error) ProbeResult(ctx context.Context, res workerproto.ProbeResult) error } // Worker runs download jobs. type Worker struct { cfg Config coord Coordinator runner ytdlp.Runner trans ffmpeg.Transcoder log *slog.Logger active atomic.Int32 // lastOK is the unix time of the last call the core answered. lastOK atomic.Int64 // authFailed is set when the core rejected the token. authFailed atomic.Bool } // LastContact returns when the core last answered a claim, and whether // the worker's token was rejected. func (w *Worker) LastContact() (time.Time, bool) { return time.Unix(w.lastOK.Load(), 0), w.authFailed.Load() } // 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() w.lastOK.Store(time.Now().Unix()) var wg sync.WaitGroup for i := 0; i < w.cfg.Concurrency; i++ { wg.Add(1) go func() { defer wg.Done() w.slot(ctx) }() } if prober, ok := w.coord.(Prober); ok { for i := 0; i < w.cfg.ProbeSlots; i++ { wg.Add(1) go func() { defer wg.Done() w.probeSlot(ctx, prober) }() } } wg.Wait() } func (w *Worker) claimRequest(probeOnly bool) workerproto.ClaimRequest { req := 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())), ProbeOnly: probeOnly, } if w.cfg.Version != nil { req.Version = w.cfg.Version() } return req } // noteClaim records the outcome of a claim for the health endpoint and // returns how long to wait before the next one after an error. func (w *Worker) noteClaim(err error, backoff *time.Duration) { if err == nil { w.lastOK.Store(time.Now().Unix()) w.authFailed.Store(false) *backoff = time.Second return } if IsUnauthorized(err) { // A revoked or wrong token will not start working by itself. Keep // asking, slowly, in case the owner issues the token again. w.authFailed.Store(true) *backoff = time.Minute } } // probeSlot takes metadata lookups from the core, one at a time. func (w *Worker) probeSlot(ctx context.Context, prober Prober) { backoff := time.Second for ctx.Err() == nil { resp, err := prober.ClaimAny(ctx, w.claimRequest(true)) w.noteClaim(err, &backoff) if err != nil { if ctx.Err() != nil { return } w.log.Warn("probe claim failed", "err", err, "retry_in", backoff.String()) sleep(ctx, backoff) if backoff < 30*time.Second { backoff *= 2 } continue } w.runCommands(resp.Commands) if resp.Probe == nil { continue } res := workerproto.ProbeResult{WorkerID: w.cfg.ID, ID: resp.Probe.ID} info, perr := w.runner.Probe(ctx, resp.Probe.URL) if perr != nil { var ye *ytdlp.Error if !errors.As(perr, &ye) { ye = &ytdlp.Error{Code: ytdlp.CodeUnknown, Retryable: true, Raw: perr.Error()} } res.Code, res.Retryable, res.Detail = string(ye.Code), ye.Retryable, ye.Raw } else if res.Info, err = json.Marshal(info); err != nil { res.Code, res.Detail = string(ytdlp.CodeInternal), err.Error() } rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second) if err := prober.ProbeResult(rctx, res); err != nil { w.log.Debug("probe result not accepted", "err", err) } cancel() } } func (w *Worker) runCommands(cmds []string) { if w.cfg.OnCommand == nil { return } for _, c := range cmds { w.cfg.OnCommand(c) } } // 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 { var ( job *workerproto.Job err error ) if prober, ok := w.coord.(Prober); ok { var resp *workerproto.ClaimResponse if resp, err = prober.ClaimAny(ctx, w.claimRequest(false)); err == nil { job = resp.Job w.runCommands(resp.Commands) } } else { job, err = w.coord.Claim(ctx, w.claimRequest(false)) } w.noteClaim(err, &backoff) 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 } 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() log.Info("job started", "kind", job.Kind, "profile", job.Profile) 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: } }