Files
Media-download-telegram-bot/internal/config/config.go
T
MichilisandClaude Fable 5.2 9c9d641eda Phase 3: cache
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>
2026-11-18 08:38:38 +00:00

597 lines
19 KiB
Go

// Package config loads the bot configuration.
//
// Order of precedence, lowest to highest: built-in defaults, an optional TOML
// file, environment variables. Secrets are expected to arrive through the
// environment (or a .env file that is not committed).
package config
import (
"bufio"
"errors"
"fmt"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/BurntSushi/toml"
)
// Duration is a time.Duration that can be read from TOML and env as "10m".
type Duration time.Duration
// UnmarshalText implements encoding.TextUnmarshaler.
func (d *Duration) UnmarshalText(b []byte) error {
v, err := time.ParseDuration(strings.TrimSpace(string(b)))
if err != nil {
return err
}
*d = Duration(v)
return nil
}
// D returns the value as a time.Duration.
func (d Duration) D() time.Duration { return time.Duration(d) }
// Config is the full configuration of the core binary.
type Config struct {
Telegram Telegram `toml:"telegram"`
HTTP HTTP `toml:"http"`
Database Database `toml:"database"`
Storage Storage `toml:"storage"`
Worker Worker `toml:"worker"`
Queue Queue `toml:"queue"`
Limits Limits `toml:"limits"`
LNbits LNbits `toml:"lnbits"`
Cache Cache `toml:"cache"`
Prices Prices `toml:"prices"`
Rate Rate `toml:"rate"`
Log Log `toml:"log"`
// PublicURL is the HTTPS base URL this server is reachable at from the
// internet, without a trailing slash. It is used for payment webhooks,
// "open in wallet" links and the Mini App.
PublicURL string `toml:"public_url" env:"PUBLIC_URL"`
// Owners are the Telegram user IDs allowed to use owner commands.
Owners []int64 `toml:"owners" env:"OWNER_IDS"`
}
// Telegram holds the Bot API settings.
type Telegram struct {
Token string `toml:"token" env:"BOT_TOKEN"`
// APIURL is the Bot API root. Point it at a local Bot API server to lift
// the upload limit to 2 GB.
APIURL string `toml:"api_url" env:"TELEGRAM_API_URL"`
// Mode is "polling" (default) or "webhook".
Mode string `toml:"mode" env:"TELEGRAM_MODE"`
WebhookURL string `toml:"webhook_url" env:"WEBHOOK_URL"`
WebhookSecret string `toml:"webhook_secret" env:"WEBHOOK_SECRET"`
// MaxUploadMB is the largest file the bot can send. 50 on the cloud Bot
// API, up to 2000 with a local Bot API server.
MaxUploadMB int64 `toml:"max_upload_mb" env:"TELEGRAM_MAX_UPLOAD_MB"`
// UpdateWorkers is the number of goroutines that handle updates.
UpdateWorkers int `toml:"update_workers" env:"TELEGRAM_UPDATE_WORKERS"`
}
// HTTP holds the settings of the embedded HTTP server.
type HTTP struct {
Listen string `toml:"listen" env:"HTTP_LISTEN"`
}
// Database selects the SQL backend.
type Database struct {
// Driver is "sqlite" or "postgres".
Driver string `toml:"driver" env:"DB_DRIVER"`
// DSN is a file path for sqlite or a connection URL for postgres.
DSN string `toml:"dsn" env:"DB_DSN"`
}
// Storage selects the file storage backend.
type Storage struct {
// Backend is "local" or "s3".
Backend string `toml:"backend" env:"STORAGE_BACKEND"`
LocalDir string `toml:"local_dir" env:"STORAGE_LOCAL_DIR"`
}
// Worker holds the settings of the download worker.
type Worker struct {
// Embedded runs a worker inside the core process.
Embedded bool `toml:"embedded" env:"WORKER_EMBEDDED"`
Concurrency int `toml:"concurrency" env:"WORKER_CONCURRENCY"`
TempDir string `toml:"temp_dir" env:"WORKER_TEMP_DIR"`
YtDlpPath string `toml:"ytdlp_path" env:"YTDLP_PATH"`
FfmpegPath string `toml:"ffmpeg_path" env:"FFMPEG_PATH"`
// DownloadTimeout is the hard cap for one download attempt.
DownloadTimeout Duration `toml:"download_timeout" env:"DOWNLOAD_TIMEOUT"`
// ProbeTimeout is the cap for one metadata lookup.
ProbeTimeout Duration `toml:"probe_timeout" env:"PROBE_TIMEOUT"`
ProbeConcurrency int `toml:"probe_concurrency" env:"PROBE_CONCURRENCY"`
}
// Queue holds scheduler settings.
type Queue struct {
// FreeMaxLen is the largest number of queued free jobs accepted.
FreeMaxLen int `toml:"free_max_len" env:"QUEUE_FREE_MAX_LEN"`
// Lease is how long a claimed job stays owned without a heartbeat.
Lease Duration `toml:"lease" env:"QUEUE_LEASE"`
// Heartbeat is how often a worker extends its lease.
Heartbeat Duration `toml:"heartbeat" env:"QUEUE_HEARTBEAT"`
// MaxAttempts is the number of tries per job (2 means one retry).
MaxAttempts int `toml:"max_attempts" env:"QUEUE_MAX_ATTEMPTS"`
}
// Tier is one set of limits.
type Tier struct {
MaxSizeMB int64 `toml:"max_size_mb"`
MaxDuration Duration `toml:"max_duration"`
ActiveJobs int `toml:"active_jobs"`
// DailyDownloads is the number of downloads per UTC day, 0 for no cap.
DailyDownloads int `toml:"daily_downloads"`
// DailyMB is the volume per UTC day in MB, 0 for no cap. It applies to
// paid users too, as a guard against abuse.
DailyMB int64 `toml:"daily_mb"`
// PlaylistItems is how many items of one playlist link are fetched.
PlaylistItems int `toml:"playlist_items"`
}
// Cache holds the smart cache settings.
type Cache struct {
Enabled bool `toml:"enabled" env:"CACHE_ENABLED"`
// BudgetMB caps the total size of stored copies. 0 means no cap.
BudgetMB int64 `toml:"budget_mb" env:"CACHE_BUDGET_MB"`
// TTLs by source class: how long a result is served before it is
// fetched again.
TTL Duration `toml:"ttl" env:"CACHE_TTL"`
TTLStable Duration `toml:"ttl_stable" env:"CACHE_TTL_STABLE"`
TTLEphemeral Duration `toml:"ttl_ephemeral" env:"CACHE_TTL_EPHEMERAL"`
// StableSites and EphemeralSites are yt-dlp extractor name prefixes.
StableSites []string `toml:"stable_sites" env:"CACHE_STABLE_SITES"`
EphemeralSites []string `toml:"ephemeral_sites" env:"CACHE_EPHEMERAL_SITES"`
// MetaTTL is how long link metadata is remembered, so cards for known
// links appear at once.
MetaTTL Duration `toml:"meta_ttl" env:"CACHE_META_TTL"`
// Derive makes lower profiles and audio from a stored higher profile
// with ffmpeg instead of downloading again.
Derive bool `toml:"derive" env:"CACHE_DERIVE"`
// SweepInterval is how often expiry, the size budget and orphan files
// are checked.
SweepInterval Duration `toml:"sweep_interval" env:"CACHE_SWEEP_INTERVAL"`
}
// Limits holds the per-tier limits. Free applies to everyone without a
// paid entitlement. Paid applies to passes, credits and one-off payments.
type Limits struct {
Free Tier `toml:"free"`
Paid Tier `toml:"paid"`
}
// LNbits holds the Lightning payment backend settings. Payments are
// enabled when both URL and InvoiceKey are set.
type LNbits struct {
URL string `toml:"url" env:"LNBITS_URL"`
// InvoiceKey is the wallet's invoice (read) key. The admin key is never
// needed and must not be given to the bot.
InvoiceKey string `toml:"invoice_key" env:"LNBITS_INVOICE_KEY"`
// WebhookSecret is a random string that becomes part of the webhook
// path, so only LNbits knows where to post.
WebhookSecret string `toml:"webhook_secret" env:"LNBITS_WEBHOOK_SECRET"`
// PollInterval is how often unsettled invoices are checked as a
// fallback for lost webhooks.
PollInterval Duration `toml:"poll_interval" env:"LNBITS_POLL_INTERVAL"`
// InvoiceExpiry is how long an invoice can be paid.
InvoiceExpiry Duration `toml:"invoice_expiry" env:"INVOICE_EXPIRY"`
}
// Enabled reports whether payments are configured.
func (l LNbits) Enabled() bool { return l.URL != "" && l.InvoiceKey != "" }
// Prices holds every price in sats. Nothing is hardcoded elsewhere.
type Prices struct {
PassDay int64 `toml:"pass_day" env:"PRICE_PASS_DAY"`
PassWeek int64 `toml:"pass_week" env:"PRICE_PASS_WEEK"`
PassMonth int64 `toml:"pass_month" env:"PRICE_PASS_MONTH"`
// CreditPerDownload is what one download costs when credits pay.
CreditPerDownload int64 `toml:"credit_per_download" env:"PRICE_CREDIT_DOWNLOAD"`
// OneOff is base plus a step per started 100 MB.
OneOffBase int64 `toml:"one_off_base" env:"PRICE_ONE_OFF_BASE"`
OneOffPer100MB int64 `toml:"one_off_per_100mb" env:"PRICE_ONE_OFF_PER_100MB"`
// SkipQueue moves one waiting free job to the paid lane.
SkipQueue int64 `toml:"skip_queue" env:"PRICE_SKIP_QUEUE"`
// CreditPacks are the top-up amounts offered.
CreditPacks []int64 `toml:"credit_packs" env:"CREDIT_PACKS"`
// DonationAmounts are the tip amounts offered by /donate.
DonationAmounts []int64 `toml:"donation_amounts" env:"DONATION_AMOUNTS"`
// ReferralReward is credited to the inviter when an invited user makes
// a first purchase. 0 turns the reward off.
ReferralReward int64 `toml:"referral_reward" env:"REFERRAL_REWARD"`
}
// Rate holds the request rate limits.
type Rate struct {
// UserPerMinute is how many links one user may send per minute.
UserPerMinute int `toml:"user_per_minute" env:"RATE_USER_PER_MINUTE"`
// GroupPerMinute is how many links one group may send per minute.
GroupPerMinute int `toml:"group_per_minute" env:"RATE_GROUP_PER_MINUTE"`
}
// Log holds logging settings.
type Log struct {
// Level is debug, info, warn or error.
Level string `toml:"level" env:"LOG_LEVEL"`
// Format is "json" or "text".
Format string `toml:"format" env:"LOG_FORMAT"`
}
// Default returns the configuration with all starting defaults applied.
func Default() Config {
return Config{
Telegram: Telegram{
APIURL: "https://api.telegram.org",
Mode: "polling",
MaxUploadMB: 50,
UpdateWorkers: 8,
},
HTTP: HTTP{Listen: ":8080"},
Database: Database{Driver: "sqlite", DSN: "data/dlbot.db"},
Storage: Storage{Backend: "local", LocalDir: "data/files"},
Worker: Worker{
Embedded: true,
Concurrency: 2,
TempDir: "data/tmp",
YtDlpPath: "yt-dlp",
FfmpegPath: "ffmpeg",
DownloadTimeout: Duration(30 * time.Minute),
ProbeTimeout: Duration(45 * time.Second),
ProbeConcurrency: 4,
},
Queue: Queue{
FreeMaxLen: 20,
Lease: Duration(30 * time.Second),
Heartbeat: Duration(10 * time.Second),
MaxAttempts: 2,
},
Limits: Limits{
Free: Tier{MaxSizeMB: 50, MaxDuration: Duration(10 * time.Minute), ActiveJobs: 1,
DailyDownloads: 5, DailyMB: 250, PlaylistItems: 3},
Paid: Tier{MaxSizeMB: 2000, MaxDuration: Duration(3 * time.Hour), ActiveJobs: 3,
DailyDownloads: 100, DailyMB: 20000, PlaylistItems: 25},
},
Cache: Cache{
Enabled: true,
BudgetMB: 20000,
TTL: Duration(7 * 24 * time.Hour),
TTLStable: Duration(30 * 24 * time.Hour),
TTLEphemeral: Duration(6 * time.Hour),
StableSites: []string{"youtube", "vimeo", "archive.org", "soundcloud", "dailymotion", "peertube", "bandcamp"},
EphemeralSites: []string{"twitter", "instagram", "tiktok", "facebook", "reddit", "twitch", "generic"},
MetaTTL: Duration(30 * time.Minute),
Derive: true,
SweepInterval: Duration(10 * time.Minute),
},
LNbits: LNbits{
PollInterval: Duration(5 * time.Second),
InvoiceExpiry: Duration(10 * time.Minute),
},
Prices: Prices{
PassDay: 700, PassWeek: 3000, PassMonth: 9000,
CreditPerDownload: 50,
OneOffBase: 100, OneOffPer100MB: 50,
SkipQueue: 50,
CreditPacks: []int64{1000, 5000, 20000},
DonationAmounts: []int64{500, 2100, 10000},
ReferralReward: 200,
},
Rate: Rate{UserPerMinute: 10, GroupPerMinute: 30},
Log: Log{Level: "info", Format: "json"},
}
}
// Load builds the configuration. path may be empty, in which case the
// DLBOT_CONFIG variable and then ./config.toml are tried. A missing default
// file is not an error. A .env file in the working directory is read first
// and never overrides variables that are already set.
func Load(path string) (Config, error) {
cfg := Default()
if err := loadDotEnv(".env"); err != nil {
return cfg, err
}
explicit := path != ""
if path == "" {
path = os.Getenv("DLBOT_CONFIG")
explicit = path != ""
}
if path == "" {
path = "config.toml"
}
if _, err := os.Stat(path); err == nil {
if _, err := toml.DecodeFile(path, &cfg); err != nil {
return cfg, fmt.Errorf("config file %s: %w", path, err)
}
} else if explicit {
return cfg, fmt.Errorf("config file %s: %w", path, err)
}
if err := applyEnv(reflect.ValueOf(&cfg).Elem(), os.LookupEnv); err != nil {
return cfg, err
}
// Tier limits are structured, so they get explicit env names.
if err := applyTierEnv("FREE", &cfg.Limits.Free, os.LookupEnv); err != nil {
return cfg, err
}
if err := applyTierEnv("PAID", &cfg.Limits.Paid, os.LookupEnv); err != nil {
return cfg, err
}
cfg.PublicURL = strings.TrimRight(cfg.PublicURL, "/")
cfg.LNbits.URL = strings.TrimRight(cfg.LNbits.URL, "/")
return cfg, cfg.Validate()
}
// Validate reports configuration mistakes that would break startup.
func (c Config) Validate() error {
var errs []string
if c.Telegram.Token == "" {
errs = append(errs, "BOT_TOKEN is required")
}
switch c.Telegram.Mode {
case "polling":
case "webhook":
if c.Telegram.WebhookURL == "" {
errs = append(errs, "WEBHOOK_URL is required when TELEGRAM_MODE=webhook")
}
default:
errs = append(errs, "TELEGRAM_MODE must be polling or webhook")
}
switch c.Database.Driver {
case "sqlite", "postgres":
default:
errs = append(errs, "DB_DRIVER must be sqlite or postgres")
}
switch c.Storage.Backend {
case "local", "s3":
default:
errs = append(errs, "STORAGE_BACKEND must be local or s3")
}
if c.Worker.Concurrency < 1 {
errs = append(errs, "WORKER_CONCURRENCY must be at least 1")
}
if c.Queue.MaxAttempts < 1 {
errs = append(errs, "QUEUE_MAX_ATTEMPTS must be at least 1")
}
if c.Queue.Heartbeat.D() >= c.Queue.Lease.D() {
errs = append(errs, "QUEUE_HEARTBEAT must be shorter than QUEUE_LEASE")
}
if (c.LNbits.URL == "") != (c.LNbits.InvoiceKey == "") {
errs = append(errs, "LNBITS_URL and LNBITS_INVOICE_KEY must be set together")
}
if c.LNbits.Enabled() {
if c.LNbits.InvoiceExpiry.D() < time.Minute {
errs = append(errs, "INVOICE_EXPIRY must be at least 1m")
}
if c.LNbits.PollInterval.D() <= 0 {
errs = append(errs, "LNBITS_POLL_INTERVAL must be positive")
}
for name, v := range map[string]int64{
"PRICE_PASS_DAY": c.Prices.PassDay, "PRICE_PASS_WEEK": c.Prices.PassWeek,
"PRICE_PASS_MONTH": c.Prices.PassMonth, "PRICE_CREDIT_DOWNLOAD": c.Prices.CreditPerDownload,
} {
if v <= 0 {
errs = append(errs, name+" must be positive")
}
}
}
if len(errs) > 0 {
return errors.New("config: " + strings.Join(errs, "; "))
}
return nil
}
// MaxUploadBytes is the Telegram upload ceiling in bytes.
func (c Config) MaxUploadBytes() int64 { return c.Telegram.MaxUploadMB << 20 }
// IsOwner reports whether the Telegram user is a configured owner.
func (c Config) IsOwner(userID int64) bool {
for _, id := range c.Owners {
if id == userID {
return true
}
}
return false
}
func applyTierEnv(prefix string, t *Tier, lookup func(string) (string, bool)) error {
if v, ok := lookup(prefix + "_MAX_SIZE_MB"); ok && v != "" {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return fmt.Errorf("config: %s_MAX_SIZE_MB: %w", prefix, err)
}
t.MaxSizeMB = n
}
if v, ok := lookup(prefix + "_MAX_DURATION"); ok && v != "" {
if err := t.MaxDuration.UnmarshalText([]byte(v)); err != nil {
return fmt.Errorf("config: %s_MAX_DURATION: %w", prefix, err)
}
}
if v, ok := lookup(prefix + "_ACTIVE_JOBS"); ok && v != "" {
n, err := strconv.Atoi(v)
if err != nil {
return fmt.Errorf("config: %s_ACTIVE_JOBS: %w", prefix, err)
}
t.ActiveJobs = n
}
if v, ok := lookup(prefix + "_DAILY_DOWNLOADS"); ok && v != "" {
n, err := strconv.Atoi(v)
if err != nil {
return fmt.Errorf("config: %s_DAILY_DOWNLOADS: %w", prefix, err)
}
t.DailyDownloads = n
}
if v, ok := lookup(prefix + "_PLAYLIST_ITEMS"); ok && v != "" {
n, err := strconv.Atoi(v)
if err != nil {
return fmt.Errorf("config: %s_PLAYLIST_ITEMS: %w", prefix, err)
}
t.PlaylistItems = n
}
if v, ok := lookup(prefix + "_DAILY_MB"); ok && v != "" {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return fmt.Errorf("config: %s_DAILY_MB: %w", prefix, err)
}
t.DailyMB = n
}
return nil
}
// PassPrice returns the price of a pass kind ("day", "week", "month").
func (p Prices) PassPrice(kind string) int64 {
switch kind {
case "day":
return p.PassDay
case "week":
return p.PassWeek
case "month":
return p.PassMonth
}
return 0
}
// OneOffPrice returns the price of a single download of the given size.
// An unknown size is priced as 200 MB.
func (p Prices) OneOffPrice(sizeBytes int64) int64 {
const step = 100 << 20
if sizeBytes <= 0 {
sizeBytes = 2 * step
}
steps := (sizeBytes + step - 1) / step
return p.OneOffBase + steps*p.OneOffPer100MB
}
var durationType = reflect.TypeOf(Duration(0))
// applyEnv walks the struct and overrides every field that has an env tag
// and a non-empty variable.
func applyEnv(v reflect.Value, lookup func(string) (string, bool)) error {
t := v.Type()
for i := 0; i < t.NumField(); i++ {
f := v.Field(i)
sf := t.Field(i)
name := sf.Tag.Get("env")
if name == "" {
if f.Kind() == reflect.Struct {
if err := applyEnv(f, lookup); err != nil {
return err
}
}
continue
}
raw, ok := lookup(name)
if !ok || raw == "" {
continue
}
if err := setField(f, raw); err != nil {
return fmt.Errorf("config: %s: %w", name, err)
}
}
return nil
}
func setField(f reflect.Value, raw string) error {
raw = strings.TrimSpace(raw)
if f.Type() == durationType {
d, err := time.ParseDuration(raw)
if err != nil {
return err
}
f.SetInt(int64(d))
return nil
}
switch f.Kind() {
case reflect.String:
f.SetString(raw)
case reflect.Bool:
b, err := strconv.ParseBool(raw)
if err != nil {
return err
}
f.SetBool(b)
case reflect.Int, reflect.Int64:
n, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return err
}
f.SetInt(n)
case reflect.Float64:
n, err := strconv.ParseFloat(raw, 64)
if err != nil {
return err
}
f.SetFloat(n)
case reflect.Slice:
parts := splitList(raw)
switch f.Type().Elem().Kind() {
case reflect.String:
f.Set(reflect.ValueOf(parts))
case reflect.Int64:
out := make([]int64, 0, len(parts))
for _, p := range parts {
n, err := strconv.ParseInt(p, 10, 64)
if err != nil {
return err
}
out = append(out, n)
}
f.Set(reflect.ValueOf(out))
default:
return fmt.Errorf("unsupported list type %s", f.Type())
}
default:
return fmt.Errorf("unsupported type %s", f.Type())
}
return nil
}
func splitList(raw string) []string {
var out []string
for _, p := range strings.FieldsFunc(raw, func(r rune) bool { return r == ',' || r == ' ' || r == ';' }) {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}
// loadDotEnv reads KEY=VALUE lines into the process environment without
// overriding existing variables. A missing file is fine.
func loadDotEnv(path string) error {
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
line = strings.TrimPrefix(line, "export ")
k, v, ok := strings.Cut(line, "=")
if !ok {
continue
}
k = strings.TrimSpace(k)
v = strings.TrimSpace(v)
if len(v) >= 2 && (v[0] == '"' && v[len(v)-1] == '"' || v[0] == '\'' && v[len(v)-1] == '\'') {
v = v[1 : len(v)-1]
}
if _, set := os.LookupEnv(k); !set {
_ = os.Setenv(k, v)
}
}
return sc.Err()
}