Repeat downloads are instant, and the cache never bypasses a limit. - internal/cache: canonical key (extractor + video id + profile, URL hash fallback), per-bot file_id layer, stored copy layer, metadata layer, TTL by source type, LRU-plus-hits eviction that keeps file_ids, orphan sweeper, takedown that deletes, invalidates and blocks - One admission gate: a cache hit passes the same size, duration, quota, volume, active job and queue checks as a fresh download, is judged by the real cached file, and costs the same. It only skips the worker - Singleflight: a second requester joins the job that is queued or running for the same result. Each keeps their own caps, checked at delivery - Derive: lower profiles and audio are transcoded from a stored copy with ffmpeg; a higher profile that already fits is served as an alias; a failed derive falls back to a download - Self-healing: a rejected file_id falls back to the stored copy, then to a fresh download, and the entry is updated either way - Private or login-gated content and live streams are never cached - Playlists as per-item jobs started in turn, /subs, /history with resend, /fresh, owner /purge and /cache - Worker removes its temp files right after the upload Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
330 lines
9.6 KiB
Go
330 lines
9.6 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/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
|
|
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 {
|
|
return []string{
|
|
cfg.Telegram.Token, cfg.Telegram.WebhookSecret,
|
|
cfg.LNbits.InvoiceKey, cfg.LNbits.WebhookSecret,
|
|
}
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
default:
|
|
return fail(fmt.Errorf("app: storage backend %q is not available in this version", 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)
|
|
a.Service = service.New(cfg, a.Store, a.Sched, a.Billing, a.Cache, a.runner, log)
|
|
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,
|
|
})
|
|
|
|
if cfg.Worker.Embedded {
|
|
a.worker = worker.New(worker.Config{
|
|
ID: "embedded",
|
|
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
|
|
}
|