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:
@@ -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:
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user