Files
Media-download-telegram-bot/cmd/worker/main.go
T
MichilisandClaude Opus 5.5 3c153af97f Phase 8: widgets and polish
- Live job card widget (progress bar, in-widget cancel via widget_query)
  and live invoice widget (QR drawn from a bitmap, countdown, paid state),
  Bot API 10.4 sendWidget, private chats only
- Automatic fallback to the ordinary message when sendWidget fails, with
  a breaker that pauses widgets after repeated failures or on servers
  without the method; TELEGRAM_WIDGETS
- Prometheus metrics on the core (/metrics) and on every worker: queue
  depth and wait, slots, heartbeats, job outcomes, errors per site,
  deliveries, cache, invoices, Lightning, ledger check, widgets
- Example Prometheus config and alert rules, Caddyfile, dashboard notes
- Load test: cmd/loadtest and deploy/loadtest (make loadtest)
- Browser check of the widgets' HTML, including decoding a drawn QR
- docs/DEPLOY.md (production in under an hour) and docs/MONITORING.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:24:36 +00:00

182 lines
4.8 KiB
Go

// Command worker is a stateless download worker. It connects out to the
// core, takes jobs, runs yt-dlp and ffmpeg, uploads the results and
// reports back. It opens no inbound port (apart from an optional local
// health endpoint) and never sees the bot token.
package main
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/noderunners/dlbot/internal/app"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/ffmpeg"
"github.com/noderunners/dlbot/internal/metrics"
"github.com/noderunners/dlbot/internal/worker"
"github.com/noderunners/dlbot/internal/workerproto"
"github.com/noderunners/dlbot/internal/ytdlp"
)
func main() {
cfg, err := config.LoadWorker()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
log := app.NewLogger(cfg.Log, cfg.Token)
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
runner := &ytdlp.Exec{
Path: cfg.YtDlpPath,
FfmpegPath: cfg.FfmpegPath,
ProbeTimeout: cfg.ProbeTimeout.D(),
DownloadTimeout: cfg.DownloadTimeout.D(),
ExtraArgs: cfg.ExtraArgs,
}
up := &updater{runner: runner, log: log}
up.refresh(ctx)
if up.get() == "" {
log.Error("yt-dlp does not run, downloads will fail", "path", cfg.YtDlpPath)
}
w := worker.New(worker.Config{
ID: "remote", // the core takes the identity from the token
Tags: cfg.Tags,
Concurrency: cfg.Concurrency,
TempDir: cfg.TempDir,
Heartbeat: cfg.Heartbeat.D(),
ClaimWait: 20 * time.Second,
ProbeSlots: cfg.ProbeSlots,
Version: up.get,
OnCommand: func(cmd string) {
if cmd == workerproto.CommandUpdateYtDlp {
go up.update(ctx)
}
},
}, worker.NewHTTPCoordinator(cfg.CoreURL, cfg.Token), runner, log)
w.SetTranscoder(&ffmpeg.Exec{Path: cfg.FfmpegPath, Timeout: cfg.DownloadTimeout.D()})
var wg sync.WaitGroup
if cfg.HealthListen != "" {
srv := healthServer(cfg.HealthListen, w, up.get)
wg.Add(1)
go func() {
defer wg.Done()
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Warn("health endpoint stopped", "err", err)
}
}()
go func() {
<-ctx.Done()
sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = srv.Shutdown(sctx)
}()
}
if every := cfg.AutoUpdate.D(); every > 0 {
go func() {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
up.update(ctx)
}
}
}()
}
log.Info("worker started", "core", cfg.CoreURL, "tags", cfg.Tags, "concurrency", cfg.Concurrency,
"ytdlp", up.get(), "probe_slots", cfg.ProbeSlots)
w.Run(ctx) // returns when every running job has been handed back
wg.Wait()
log.Info("worker stopped")
}
// healthServer answers /healthz and /metrics. The worker is healthy while
// the core keeps answering its claims and accepts its token.
func healthServer(addr string, w *worker.Worker, ytdlpVersion func() string) *http.Server {
mux := http.NewServeMux()
mux.Handle("GET /metrics", metrics.WorkerHandler(metrics.WorkerSource{
Active: w.Active, Capacity: w.Capacity, LastContact: w.LastContact, Outcomes: w.Outcomes, YtDlp: ytdlpVersion,
}))
mux.HandleFunc("GET /healthz", func(rw http.ResponseWriter, _ *http.Request) {
last, authFailed := w.LastContact()
age := time.Since(last)
status, code := "ok", http.StatusOK
switch {
case authFailed:
status, code = "token rejected by the core", http.StatusServiceUnavailable
case age > 2*time.Minute:
status, code = "core unreachable", http.StatusServiceUnavailable
}
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(code)
_ = json.NewEncoder(rw).Encode(map[string]any{
"status": status, "active_jobs": w.Active(), "seconds_since_core_contact": int(age.Seconds()),
})
})
return &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second}
}
// updater keeps yt-dlp current and remembers its version.
type updater struct {
runner *ytdlp.Exec
log *slog.Logger
mu sync.Mutex
busy bool
ver string
}
func (u *updater) get() string {
u.mu.Lock()
defer u.mu.Unlock()
return u.ver
}
func (u *updater) refresh(ctx context.Context) {
v, err := u.runner.Version(ctx)
if err != nil {
u.log.Warn("cannot read the yt-dlp version", "err", err)
return
}
u.mu.Lock()
u.ver = v
u.mu.Unlock()
}
func (u *updater) update(ctx context.Context) {
u.mu.Lock()
if u.busy {
u.mu.Unlock()
return
}
u.busy = true
u.mu.Unlock()
defer func() {
u.mu.Lock()
u.busy = false
u.mu.Unlock()
}()
before := u.get()
out, err := u.runner.Update(ctx)
u.refresh(ctx)
if err != nil {
u.log.Warn("yt-dlp update failed", "err", err, "output", out)
return
}
u.log.Info("yt-dlp update done", "before", before, "after", u.get())
}