// 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/config" "github.com/noderunners/dlbot/internal/db" "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 // 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 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) a.Service = service.New(cfg, a.Store, a.Sched, a.Billing, a.runner, log) if a.tgBot, err = tg.NewBot(cfg.Telegram.Token, cfg.Telegram.APIURL); err != nil { return fail(fmt.Errorf("app: telegram client: %w", 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, 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) } 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) }) 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 }