Phase 1: core bot

Link in, card, download, send, in private chats and groups.

- cmd/core with an embedded download worker
- Telegram front end on telego v1.13.0 (Bot API 10.4): link card with
  thumbnail and format buttons, one live status message, /dl /audio /thumb
  /info /queue /cancel, group support with requester-only buttons
- Database backed queue: paid and free lanes, leases with heartbeats, one
  automatic retry, cancel, queue position and wait estimate
- yt-dlp and ffprobe behind a Runner interface with classified, redacted
  errors mapped to friendly messages
- SQLite via modernc with goose migrations, portable schema
- Local file storage behind a Storage interface
- go-i18n with an English catalog, no literal text in handlers
- Free tier limits enforced before queueing and again on the real file
- Bot token and webhook secret are stripped from all log output
- Tests: URL parsing, job lifecycle, worker, yt-dlp wrapper, and end to end
  flows against a fake Bot API server; opt-in test with the real yt-dlp

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 07:33:32 +00:00
co-authored by Claude Fable 5.2
commit 3b361c17a1
63 changed files with 10715 additions and 0 deletions
+407
View File
@@ -0,0 +1,407 @@
// 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"`
Log Log `toml:"log"`
// 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 per-download limits.
type Tier struct {
MaxSizeMB int64 `toml:"max_size_mb"`
MaxDuration Duration `toml:"max_duration"`
ActiveJobs int `toml:"active_jobs"`
}
// Limits holds the per-tier limits.
type Limits struct {
Free Tier `toml:"free"`
}
// 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},
},
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
}
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 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
}
return nil
}
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()
}
+175
View File
@@ -0,0 +1,175 @@
package config
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
)
func lookup(env map[string]string) func(string) (string, bool) {
return func(k string) (string, bool) {
v, ok := env[k]
return v, ok
}
}
func TestDefaultsAreValidOnceTokenIsSet(t *testing.T) {
cfg := Default()
if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "BOT_TOKEN") {
t.Fatalf("missing token must be reported, got %v", err)
}
cfg.Telegram.Token = "x"
if err := cfg.Validate(); err != nil {
t.Fatalf("defaults should validate: %v", err)
}
if cfg.Limits.Free.MaxSizeMB != 50 || cfg.Limits.Free.MaxDuration.D() != 10*time.Minute ||
cfg.Limits.Free.ActiveJobs != 1 || cfg.Queue.FreeMaxLen != 20 {
t.Fatalf("free tier defaults changed: %+v %+v", cfg.Limits.Free, cfg.Queue)
}
}
func TestApplyEnv(t *testing.T) {
cfg := Default()
env := map[string]string{
"BOT_TOKEN": "123:abc",
"TELEGRAM_MODE": "webhook",
"WEBHOOK_URL": "https://bot.example.com",
"WORKER_EMBEDDED": "false",
"WORKER_CONCURRENCY": "5",
"DOWNLOAD_TIMEOUT": "45m",
"OWNER_IDS": "11, 22;33",
"DB_DRIVER": "postgres",
"LOG_LEVEL": "",
}
if err := applyEnv(reflect.ValueOf(&cfg).Elem(), lookup(env)); err != nil {
t.Fatal(err)
}
if cfg.Telegram.Token != "123:abc" || cfg.Telegram.Mode != "webhook" || cfg.Worker.Embedded ||
cfg.Worker.Concurrency != 5 || cfg.Worker.DownloadTimeout.D() != 45*time.Minute ||
cfg.Database.Driver != "postgres" {
t.Fatalf("env not applied: %+v", cfg)
}
if !reflect.DeepEqual(cfg.Owners, []int64{11, 22, 33}) {
t.Fatalf("owners = %v", cfg.Owners)
}
if cfg.Log.Level != "info" {
t.Fatalf("an empty variable must not override the default, got %q", cfg.Log.Level)
}
if !cfg.IsOwner(22) || cfg.IsOwner(44) {
t.Fatal("IsOwner is wrong")
}
if err := applyTierEnv("FREE", &cfg.Limits.Free, lookup(map[string]string{
"FREE_MAX_SIZE_MB": "25", "FREE_MAX_DURATION": "5m", "FREE_ACTIVE_JOBS": "2",
})); err != nil {
t.Fatal(err)
}
if cfg.Limits.Free.MaxSizeMB != 25 || cfg.Limits.Free.MaxDuration.D() != 5*time.Minute || cfg.Limits.Free.ActiveJobs != 2 {
t.Fatalf("tier env not applied: %+v", cfg.Limits.Free)
}
}
func TestApplyEnvRejectsBadValues(t *testing.T) {
for k, v := range map[string]string{
"WORKER_CONCURRENCY": "many", "WORKER_EMBEDDED": "maybe", "DOWNLOAD_TIMEOUT": "soon", "OWNER_IDS": "1,x",
} {
cfg := Default()
err := applyEnv(reflect.ValueOf(&cfg).Elem(), lookup(map[string]string{k: v}))
if err == nil || !strings.Contains(err.Error(), k) {
t.Errorf("%s=%s: error %v should name the variable", k, v, err)
}
}
}
func TestValidate(t *testing.T) {
bad := []func(*Config){
func(c *Config) { c.Telegram.Mode = "carrier-pigeon" },
func(c *Config) { c.Telegram.Mode = "webhook" }, // no URL
func(c *Config) { c.Database.Driver = "oracle" },
func(c *Config) { c.Storage.Backend = "tape" },
func(c *Config) { c.Worker.Concurrency = 0 },
func(c *Config) { c.Queue.MaxAttempts = 0 },
func(c *Config) { c.Queue.Heartbeat = c.Queue.Lease },
}
for i, mut := range bad {
cfg := Default()
cfg.Telegram.Token = "x"
mut(&cfg)
if err := cfg.Validate(); err == nil {
t.Errorf("case %d should not validate", i)
}
}
}
func TestLoadFileThenEnv(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.toml")
content := `
owners = [5, 6]
[telegram]
token = "from-file"
max_upload_mb = 2000
[worker]
concurrency = 3
download_timeout = "1h"
[limits.free]
max_size_mb = 30
max_duration = "7m"
active_jobs = 1
`
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
t.Chdir(dir) // keeps a developer's real .env out of the test
t.Setenv("BOT_TOKEN", "from-env")
t.Setenv("DLBOT_CONFIG", "")
cfg, err := Load(path)
if err != nil {
t.Fatal(err)
}
if cfg.Telegram.Token != "from-env" {
t.Errorf("env must override the file, token = %q", cfg.Telegram.Token)
}
if cfg.Worker.Concurrency != 3 || cfg.Worker.DownloadTimeout.D() != time.Hour ||
cfg.Limits.Free.MaxSizeMB != 30 || cfg.Limits.Free.MaxDuration.D() != 7*time.Minute {
t.Errorf("file values not loaded: %+v %+v", cfg.Worker, cfg.Limits.Free)
}
if cfg.MaxUploadBytes() != 2000<<20 || !reflect.DeepEqual(cfg.Owners, []int64{5, 6}) {
t.Errorf("upload cap or owners wrong: %d %v", cfg.MaxUploadBytes(), cfg.Owners)
}
if cfg.HTTP.Listen != ":8080" {
t.Errorf("unset values keep their defaults, listen = %q", cfg.HTTP.Listen)
}
if _, err := Load(filepath.Join(dir, "missing.toml")); err == nil {
t.Error("an explicit config path that does not exist must be an error")
}
}
func TestDotEnvDoesNotOverrideRealEnv(t *testing.T) {
dir := t.TempDir()
env := "# comment\nexport DLBOT_TEST_A=from-dotenv\nDLBOT_TEST_B=\"quoted value\"\nnot a pair\n"
path := filepath.Join(dir, ".env")
if err := os.WriteFile(path, []byte(env), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("DLBOT_TEST_A", "from-real-env")
os.Unsetenv("DLBOT_TEST_B")
t.Cleanup(func() { os.Unsetenv("DLBOT_TEST_B") })
if err := loadDotEnv(path); err != nil {
t.Fatal(err)
}
if got := os.Getenv("DLBOT_TEST_A"); got != "from-real-env" {
t.Errorf("A = %q", got)
}
if got := os.Getenv("DLBOT_TEST_B"); got != "quoted value" {
t.Errorf("B = %q", got)
}
if err := loadDotEnv(filepath.Join(dir, "absent")); err != nil {
t.Errorf("a missing .env is fine, got %v", err)
}
}