Files
Media-download-telegram-bot/internal/app/app.go
T
MichilisandClaude Fable 5.2 7d4893bc3f Phase 4: scale out
Remote workers, Postgres and S3, all chosen by configuration.

- Pull-based worker protocol over HTTP: claim (long poll), heartbeat,
  complete, fail, upload, source, probe. Workers need no inbound ports
- cmd/worker: standalone stateless worker with health endpoint and
  scheduled yt-dlp self-update
- Per-worker bearer tokens, stored hashed, revocable; identity always
  taken from the token; actions only on jobs the worker holds a lease for
- Tags: site_tags routes a site's jobs and lookups to workers that carry
  the required tags
- Drain, /workers, /ytdlp update, and "core worker add|revoke|list"
- Link lookups can run on remote workers (PROBE_MODE), so the core needs
  no yt-dlp and no residential address
- Postgres backend with pgx, same schema and queries; per-user advisory
  lock and job row lock where SQLite's serial writes were relied on
- The whole test suite runs on SQLite and on Postgres
- S3 storage backend with presigned worker uploads, sharing a conformance
  suite with the local backend
- Dockerfile with core, worker and faketelegram targets, docker-compose
  with optional Postgres and local Bot API server, systemd units
- deploy/acceptance/kill-worker.sh: kills a worker mid-job and checks
  that the other one delivers the file
- Fixes found on the way: /cancel could let the next playlist item start;
  a refund note could be missing when the sweep refunded first

Docker was not available on the build machine: the compose files were
validated with "docker compose config" only. The acceptance scenario was
run with real processes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 09:27:11 +00:00

382 lines
12 KiB
Go

// Package app wires the core together. cmd/core and the end-to-end tests
// both start the bot through it, so tests exercise the real startup path.
package app
import (
"context"
"fmt"
"log/slog"
"os"
"strings"
"sync"
"time"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/api"
"github.com/noderunners/dlbot/internal/billing"
"github.com/noderunners/dlbot/internal/billing/lnbits"
"github.com/noderunners/dlbot/internal/bot"
"github.com/noderunners/dlbot/internal/cache"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/ffmpeg"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/links"
"github.com/noderunners/dlbot/internal/probe"
"github.com/noderunners/dlbot/internal/sched"
"github.com/noderunners/dlbot/internal/service"
"github.com/noderunners/dlbot/internal/storage"
"github.com/noderunners/dlbot/internal/tg"
"github.com/noderunners/dlbot/internal/worker"
"github.com/noderunners/dlbot/internal/ytdlp"
"github.com/noderunners/dlbot/locales"
)
// Options configure a core instance.
type Options struct {
Config config.Config
Log *slog.Logger
// Runner replaces the real yt-dlp, for tests.
Runner ytdlp.Runner
// Transcoder replaces the real ffmpeg, for tests.
Transcoder ffmpeg.Transcoder
// Tune is called with the bot before it starts, for tests.
Tune func(*bot.Bot)
}
// App is a running core.
type App struct {
cfg config.Config
log *slog.Logger
DB *db.DB
Store *db.Store
Storage storage.Storage
Sched *sched.Scheduler
Billing *billing.Billing
Cache *cache.Cache
Broker *probe.Broker
Service *service.Service
Bot *bot.Bot
HTTP *api.Server
tgBot *telego.Bot
runner ytdlp.Runner
worker *worker.Worker
ready chan struct{}
}
// Ready is closed once the core is listening and receiving updates.
func (a *App) Ready() <-chan struct{} { return a.ready }
// NewLogger builds the process logger from the config. Every secret given
// is blanked out of all log output, whatever field it shows up in. This
// matters because HTTP client errors quote the request URL, and Bot API
// URLs contain the bot token.
func NewLogger(cfg config.Log, secrets ...string) *slog.Logger {
var level slog.Level
if err := level.UnmarshalText([]byte(cfg.Level)); err != nil {
level = slog.LevelInfo
}
opts := &slog.HandlerOptions{Level: level, ReplaceAttr: Redactor(secrets...)}
if strings.EqualFold(cfg.Format, "text") {
return slog.New(slog.NewTextHandler(os.Stderr, opts))
}
return slog.New(slog.NewJSONHandler(os.Stderr, opts))
}
// Redactor returns a slog ReplaceAttr function that removes the secrets
// from string and error values.
func Redactor(secrets ...string) func(groups []string, a slog.Attr) slog.Attr {
var pairs []string
for _, s := range secrets {
if len(s) >= 6 { // too short to be a secret, and it would mangle logs
pairs = append(pairs, s, "[REDACTED]")
}
}
if len(pairs) == 0 {
return nil
}
r := strings.NewReplacer(pairs...)
return func(_ []string, a slog.Attr) slog.Attr {
switch a.Value.Kind() {
case slog.KindString:
a.Value = slog.StringValue(r.Replace(a.Value.String()))
case slog.KindAny:
switch v := a.Value.Any().(type) {
case error:
a.Value = slog.StringValue(r.Replace(v.Error()))
case fmt.Stringer:
a.Value = slog.StringValue(r.Replace(v.String()))
}
}
return a
}
}
// Secrets lists the configured values that must never appear in logs.
func Secrets(cfg config.Config) []string {
out := []string{
cfg.Telegram.Token, cfg.Telegram.WebhookSecret,
cfg.LNbits.InvoiceKey, cfg.LNbits.WebhookSecret,
cfg.Storage.S3.SecretKey,
}
// Static worker tokens are secrets too.
for _, pair := range cfg.WorkerTokens {
if _, token, ok := strings.Cut(pair, ":"); ok {
out = append(out, token)
}
}
return out
}
// registerStaticWorkers makes sure the workers named in WORKER_TOKENS
// exist with those tokens. Only token hashes are stored.
func registerStaticWorkers(ctx context.Context, store *db.Store, pairs []string, log *slog.Logger) error {
for _, pair := range pairs {
name, token, ok := strings.Cut(pair, ":")
if !ok || name == "" || token == "" {
continue
}
if err := store.UpsertWorker(ctx, name, api.HashWorkerToken(token)); err != nil {
return fmt.Errorf("app: register worker %s: %w", name, err)
}
log.Info("worker registered from config", "worker_id", name)
}
return nil
}
// New opens the database and storage and builds every component. Nothing
// runs until Run is called.
func New(ctx context.Context, opts Options) (*App, error) {
cfg := opts.Config
log := opts.Log
if log == nil {
log = NewLogger(cfg.Log, Secrets(cfg)...)
}
a := &App{cfg: cfg, log: log, ready: make(chan struct{})}
var err error
if a.DB, err = db.Open(ctx, cfg.Database.Driver, cfg.Database.DSN); err != nil {
return nil, err
}
fail := func(err error) (*App, error) {
a.DB.Close()
return nil, err
}
if err := a.DB.Migrate(ctx); err != nil {
return fail(err)
}
a.Store = a.DB.Store()
switch cfg.Storage.Backend {
case "local":
if a.Storage, err = storage.NewLocal(cfg.Storage.LocalDir); err != nil {
return fail(err)
}
case "s3":
s3 := cfg.Storage.S3
a.Storage, err = storage.NewS3(ctx, storage.S3Config{
Endpoint: s3.Endpoint, Region: s3.Region, Bucket: s3.Bucket, AccessKey: s3.AccessKey,
SecretKey: s3.SecretKey, UseSSL: s3.UseSSL, PathStyle: s3.PathStyle, Prefix: s3.Prefix,
Presign: s3.Presign, PresignEndpoint: s3.PresignEndpoint,
})
if err != nil {
return fail(err)
}
default:
return fail(fmt.Errorf("app: unknown storage backend %q", cfg.Storage.Backend))
}
tr, err := i18n.Load(locales.FS, log)
if err != nil {
return fail(err)
}
a.runner = opts.Runner
if a.runner == nil {
a.runner = &ytdlp.Exec{
Path: cfg.Worker.YtDlpPath,
FfmpegPath: cfg.Worker.FfmpegPath,
ProbeTimeout: cfg.Worker.ProbeTimeout.D(),
DownloadTimeout: cfg.Worker.DownloadTimeout.D(),
}
}
a.Sched = sched.New(a.Store, sched.Config{
Lease: cfg.Queue.Lease.D(),
FreeMaxLen: cfg.Queue.FreeMaxLen,
MaxAttempts: cfg.Queue.MaxAttempts,
}, log)
var ln billing.Lightning
if cfg.LNbits.Enabled() {
ln = lnbits.New(cfg.LNbits.URL, cfg.LNbits.InvoiceKey)
}
a.Billing = billing.New(a.Store, ln, cfg, log)
if a.tgBot, err = tg.NewBot(cfg.Telegram.Token, cfg.Telegram.APIURL); err != nil {
return fail(fmt.Errorf("app: telegram client: %w", err))
}
// file_ids only work for the bot that got them, so the cache is keyed
// by the bot's ID, which is the number in front of the token.
a.Cache = cache.New(cache.Config{
Enabled: cfg.Cache.Enabled,
BudgetBytes: cfg.Cache.BudgetMB << 20,
TTLDefault: cfg.Cache.TTL.D(),
TTLStable: cfg.Cache.TTLStable.D(),
TTLEphemeral: cfg.Cache.TTLEphemeral.D(),
Stable: cfg.Cache.StableSites,
Ephemeral: cfg.Cache.EphemeralSites,
MetaTTL: cfg.Cache.MetaTTL.D(),
Derive: cfg.Cache.Derive,
}, a.tgBot.ID(), a.Store, a.Storage, log)
// Metadata lookups run on the core, or go to remote workers when the
// core has no yt-dlp of its own or sits on a network that sites refuse.
a.Broker = probe.NewBroker(cfg.Worker.ProbeTimeout.D(),
func(url string) string { return cfg.RequiredTags(links.Site(url)) }, a.Sched.NotifyWork)
var prober service.Prober = a.Broker
if cfg.ProbeLocally() {
prober = a.runner
}
a.Service = service.New(cfg, a.Store, a.Sched, a.Billing, a.Cache, prober, log)
if err := registerStaticWorkers(ctx, a.Store, cfg.WorkerTokens, log); err != nil {
return fail(err)
}
a.Bot, err = bot.New(ctx, bot.Deps{
API: a.tgBot,
Config: cfg,
Store: a.Store,
Sched: a.Sched,
Service: a.Service,
Billing: a.Billing,
Cache: a.Cache,
Storage: a.Storage,
I18n: tr,
Log: log,
WorkerSlots: func() int { return cfg.Worker.Concurrency },
})
if err != nil {
return fail(err)
}
if opts.Tune != nil {
opts.Tune(a.Bot)
}
a.HTTP = api.New(cfg.HTTP.Listen, func(ctx context.Context) error { return a.DB.SQL.PingContext(ctx) }, log)
a.HTTP.RegisterPayments(api.Payments{
Billing: a.Billing, Store: a.Store, I18n: tr, Secret: cfg.LNbits.WebhookSecret,
})
a.HTTP.RegisterWorkerAPI(&api.WorkerAPI{
Store: a.Store, Sched: a.Sched, Storage: a.Storage, Broker: a.Broker, Log: log,
})
if cfg.Worker.Embedded {
a.worker = worker.New(worker.Config{
ID: "embedded",
Tags: cfg.Worker.Tags,
Concurrency: cfg.Worker.Concurrency,
TempDir: cfg.Worker.TempDir,
Heartbeat: cfg.Queue.Heartbeat.D(),
ClaimWait: 5 * time.Second,
}, &sched.Local{Sched: a.Sched, Storage: a.Storage}, a.runner, log)
trans := opts.Transcoder
if trans == nil {
trans = &ffmpeg.Exec{Path: cfg.Worker.FfmpegPath, Timeout: cfg.Worker.DownloadTimeout.D()}
}
a.worker.SetTranscoder(trans)
}
return a, nil
}
// allowedUpdates is the list of update types the bot asks Telegram for.
var allowedUpdates = []string{"message", "callback_query"}
// Run starts every loop and blocks until ctx ends. Shutdown is ordered:
// updates stop first, then the worker hands back its jobs, then the
// database closes.
func (a *App) Run(ctx context.Context) error {
defer a.DB.Close()
if err := a.HTTP.Listen(); err != nil {
return fmt.Errorf("app: http listen: %w", err)
}
updates, err := a.updates(ctx)
if err != nil {
if ctx.Err() != nil {
return nil // asked to stop while still starting
}
return err
}
a.Bot.RegisterCommands(ctx)
close(a.ready)
a.log.Info("core started", "bot", a.Bot.Username(), "mode", a.cfg.Telegram.Mode,
"http", a.HTTP.Addr(), "db", a.cfg.Database.Driver, "storage", a.cfg.Storage.Backend,
"embedded_worker", a.cfg.Worker.Embedded, "payments", a.Billing.Enabled(),
"payment_webhook", a.Billing.WebhookURL() != "")
var wg sync.WaitGroup
run := func(fn func()) {
wg.Add(1)
go func() {
defer wg.Done()
fn()
}()
}
errc := make(chan error, 1)
run(func() {
if err := a.HTTP.Serve(ctx); err != nil {
select {
case errc <- fmt.Errorf("app: http: %w", err):
default:
}
}
})
run(func() { a.Sched.Run(ctx) })
run(func() { a.Billing.Run(ctx) })
run(func() { a.Cache.Run(ctx, a.cfg.Cache.SweepInterval.D()) })
if a.worker != nil {
run(func() { a.worker.Run(ctx) })
}
run(func() { a.Bot.Run(ctx, updates) })
var runErr error
select {
case <-ctx.Done():
case runErr = <-errc:
}
wg.Wait()
a.log.Info("core stopped")
return runErr
}
func (a *App) updates(ctx context.Context) (<-chan telego.Update, error) {
t := a.cfg.Telegram
if t.Mode == "webhook" {
hook := strings.TrimRight(t.WebhookURL, "/") + "/telegram/webhook"
var secret []string
if t.WebhookSecret != "" {
secret = append(secret, t.WebhookSecret)
}
ch, err := a.tgBot.UpdatesViaWebhook(ctx,
telego.WebhookHTTPServeMux(a.HTTP.Mux(), "POST /telegram/webhook", secret...),
telego.WithWebhookSet(ctx, &telego.SetWebhookParams{
URL: hook, SecretToken: t.WebhookSecret, AllowedUpdates: allowedUpdates,
}))
if err != nil {
return nil, fmt.Errorf("app: webhook: %w", err)
}
return ch, nil
}
// A webhook left over from an earlier run would make getUpdates fail.
if err := a.tgBot.DeleteWebhook(ctx, &telego.DeleteWebhookParams{}); err != nil {
return nil, fmt.Errorf("app: deleteWebhook: %w", err)
}
ch, err := a.tgBot.UpdatesViaLongPolling(ctx, &telego.GetUpdatesParams{
Timeout: 30, AllowedUpdates: allowedUpdates,
}, telego.WithLongPollingRetryTimeout(3*time.Second))
if err != nil {
return nil, fmt.Errorf("app: long polling: %w", err)
}
return ch, nil
}