From 7d4893bc3f0bd248282e291e5bfb4e4697622116 Mon Sep 17 00:00:00 2001 From: Michilis Date: Wed, 18 Nov 2026 09:27:11 +0000 Subject: [PATCH] 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 --- .env.example | 39 +- .env.worker.example | 33 ++ Makefile | 19 +- README.md | 30 +- cmd/core/main.go | 18 + cmd/faketelegram/main.go | 110 ++++ cmd/worker/main.go | 177 +++++++ config.example.toml | 20 + deploy/Dockerfile | 85 ++++ deploy/acceptance/compose.yml | 46 ++ deploy/acceptance/kill-worker.sh | 202 ++++++++ deploy/systemd/dlbot-core.service | 48 ++ deploy/systemd/dlbot-worker.service | 51 ++ docker-compose.yml | 116 +++++ docs/ARCHITECTURE.md | 59 ++- docs/ASSUMPTIONS.md | 86 ++++ docs/OPERATIONS.md | 186 +++++++ docs/WORKERS.md | 246 +++++++++ go.mod | 25 +- go.sum | 80 ++- internal/api/worker.go | 355 +++++++++++++ internal/app/admin.go | 88 ++++ internal/app/app.go | 58 ++- internal/app/app_test.go | 3 +- internal/app/money_test.go | 2 +- internal/app/workers_test.go | 607 +++++++++++++++++++++++ internal/billing/billing_test.go | 2 +- internal/bot/bot.go | 4 + internal/bot/commands.go | 34 +- internal/bot/extras.go | 99 ++++ internal/config/config.go | 149 +++++- internal/config/config_test.go | 105 ++++ internal/config/worker.go | 105 ++++ internal/db/db.go | 5 + internal/db/dbtest/dbtest.go | 58 ++- internal/db/jobs.go | 58 ++- internal/db/migrations/00004_workers.sql | 18 + internal/db/postgres.go | 68 ++- internal/db/workers.go | 140 ++++++ internal/probe/broker.go | 149 ++++++ internal/sched/sched.go | 126 ++++- internal/service/service.go | 29 +- internal/storage/local_test.go | 197 +++++++- internal/storage/s3.go | 247 +++++++++ internal/storage/storage.go | 10 + internal/tg/fakeserver/server.go | 20 +- internal/worker/httpcoord.go | 208 ++++++++ internal/worker/worker.go | 140 +++++- internal/workerproto/proto.go | 43 +- internal/ytdlp/exec.go | 17 + locales/en.toml | 20 + 51 files changed, 4732 insertions(+), 108 deletions(-) create mode 100644 .env.worker.example create mode 100644 cmd/faketelegram/main.go create mode 100644 cmd/worker/main.go create mode 100644 deploy/Dockerfile create mode 100644 deploy/acceptance/compose.yml create mode 100755 deploy/acceptance/kill-worker.sh create mode 100644 deploy/systemd/dlbot-core.service create mode 100644 deploy/systemd/dlbot-worker.service create mode 100644 docker-compose.yml create mode 100644 docs/OPERATIONS.md create mode 100644 docs/WORKERS.md create mode 100644 internal/api/worker.go create mode 100644 internal/app/admin.go create mode 100644 internal/app/workers_test.go create mode 100644 internal/config/worker.go create mode 100644 internal/db/migrations/00004_workers.sql create mode 100644 internal/db/workers.go create mode 100644 internal/probe/broker.go create mode 100644 internal/storage/s3.go create mode 100644 internal/worker/httpcoord.go diff --git a/.env.example b/.env.example index d4e4705..5b7c0e9 100644 --- a/.env.example +++ b/.env.example @@ -42,9 +42,46 @@ DB_DSN=data/dlbot.db STORAGE_BACKEND=local STORAGE_LOCAL_DIR=data/files -# --- Worker ----------------------------------------------------------------- +# S3 compatible bucket (AWS S3, Garage, MinIO). Only for STORAGE_BACKEND=s3. +# The bucket must exist. +S3_ENDPOINT= +S3_BUCKET= +S3_ACCESS_KEY= +S3_SECRET_KEY= +S3_REGION=garage +S3_USE_SSL=true +# /bucket/key addressing. Garage and MinIO: true. AWS: false. +S3_PATH_STYLE=true +# Optional key prefix, to share a bucket. +S3_PREFIX= +# Workers upload straight to the bucket with presigned URLs. +S3_PRESIGN=true +# Address workers reach the bucket at, if not S3_ENDPOINT. +S3_PRESIGN_ENDPOINT= + +# --- Scale out -------------------------------------------------------------- +# Remote workers registered at startup, as name:token pairs. Tokens are any +# random string of 16 characters or more. docker-compose.yml builds this +# from WORKER_A_TOKEN and WORKER_B_TOKEN. "core worker add " creates +# tokens without a restart. See docs/WORKERS.md. +WORKER_TOKENS= +# Tokens of the two workers in docker-compose.yml: openssl rand -hex 24 +WORKER_A_TOKEN= +WORKER_B_TOKEN= +# Their tags, for example residential,eu. +WORKER_A_TAGS= +WORKER_B_TAGS= +# Which worker tags a site requires: host=tag,tag;host=tag +# A host covers its subdomains. Example: youtube.com=residential +SITE_TAGS= +# Who looks links up for the card: auto, local (the core) or worker. +PROBE_MODE=auto + +# --- Worker (the one inside the core) --------------------------------------- # Run a download worker inside the core process. WORKER_EMBEDDED=true +# Tags of the embedded worker. +WORKER_TAGS= # Downloads running at the same time. WORKER_CONCURRENCY=2 # Scratch space for downloads. Each worker process needs its own directory. diff --git a/.env.worker.example b/.env.worker.example new file mode 100644 index 0000000..a2139bc --- /dev/null +++ b/.env.worker.example @@ -0,0 +1,33 @@ +# Configuration of a standalone worker (the "worker" binary). Copy to .env +# on the worker machine. A worker needs nothing from the core's .env. +# See docs/WORKERS.md. + +# Base URL of the core. Use https across the internet. +CORE_URL=https://bot.example.com +# This worker's token, from "core worker add " on the core. +WORKER_TOKEN= + +# What this worker can do or where it runs, for example residential,eu. +WORKER_TAGS= +# Downloads at the same time. +WORKER_CONCURRENCY=2 +# Scratch space. Each worker process needs its own directory. +WORKER_TEMP_DIR=data/worker-tmp +# Link lookups running next to the downloads. +WORKER_PROBE_SLOTS=2 +# Must be well under the core's QUEUE_LEASE (30s by default). +WORKER_HEARTBEAT=10s +# Local health endpoint, or "off". +WORKER_HEALTH_LISTEN=:8081 + +YTDLP_PATH=yt-dlp +FFMPEG_PATH=ffmpeg +# Added to every yt-dlp call, for example a proxy. +YTDLP_EXTRA_ARGS= +# How often yt-dlp updates itself. 0 turns it off. +YTDLP_AUTO_UPDATE=24h +DOWNLOAD_TIMEOUT=30m +PROBE_TIMEOUT=45s + +LOG_LEVEL=info +LOG_FORMAT=json diff --git a/Makefile b/Makefile index 0b88627..b6358c5 100644 --- a/Makefile +++ b/Makefile @@ -2,12 +2,17 @@ GO ?= go BIN := bin VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev) -.PHONY: all build test race vet fmt check run e2e clean +.PHONY: all build faketelegram test test-postgres race vet fmt check run e2e acceptance clean all: check build build: $(GO) build -trimpath -ldflags "-s -w" -o $(BIN)/core ./cmd/core + $(GO) build -trimpath -ldflags "-s -w" -o $(BIN)/worker ./cmd/worker + +# Fake Telegram Bot API, for trying the bot without a token. +faketelegram: + $(GO) build -o $(BIN)/faketelegram ./cmd/faketelegram test: $(GO) test ./... @@ -27,6 +32,18 @@ check: fmt vet race run: build ./$(BIN)/core +# The same test suite against Postgres. Point PG_DSN at an empty database; +# each test creates and drops its own schema in it. +# make test-postgres PG_DSN=postgres://user:pass@127.0.0.1:5432/dlbot_test?sslmode=disable +test-postgres: + @test -n "$(PG_DSN)" || { echo "set PG_DSN, see the comment in the Makefile"; exit 1; } + DLBOT_TEST_DB=postgres DLBOT_TEST_PG_DSN="$(PG_DSN)" $(GO) test -count=1 ./... + +# Kill a worker mid-job and watch the other one finish it. MODE=compose +# runs it in containers. +acceptance: + deploy/acceptance/kill-worker.sh + # End-to-end test with the real yt-dlp and ffmpeg. Needs network access. e2e: DLBOT_E2E_YTDLP=$${YTDLP_PATH:-$$(command -v yt-dlp)} $(GO) test -count=1 -v -run TestRealYtDlp ./internal/app diff --git a/README.md b/README.md index 34ea3ec..9e4cd8b 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ A Telegram bot that downloads video and audio from links, in private chats and in groups. Written in Go on top of yt-dlp. -> Status: Phase 3 of 8 (core bot, payments, cache). Remote workers, group +> Status: Phase 4 of 8 (core bot, payments, cache, scale-out). Group > settings, the Mini App and more languages follow. See > [docs/ASSUMPTIONS.md](docs/ASSUMPTIONS.md) for the decisions made so far. @@ -29,9 +29,23 @@ and in groups. Written in Go on top of yt-dlp. copy. A cache hit is checked against exactly the same limits as a fresh download. - Playlists (each item its own job), subtitles, download history. +- Scale out: stateless workers that pull jobs over HTTPS with no inbound + ports, per-worker revocable tokens, tags to route sites to the right + network, drain, automatic requeue when a worker dies. +- SQLite or Postgres, local disk or S3, chosen by configuration. - Friendly, translated error messages. Raw tool output stays in the logs. -## Quick start +## Quick start with docker compose + +```sh +cp .env.example .env # set BOT_TOKEN, OWNER_IDS, WORKER_A_TOKEN, WORKER_B_TOKEN +docker compose up -d --build +``` + +This runs the core and two workers. [docs/OPERATIONS.md](docs/OPERATIONS.md) +covers Postgres, S3, 2 GB uploads and TLS. + +## Quick start from source You need Go 1.26.11 or newer (older Go toolchains download it on their own), plus `yt-dlp` and `ffmpeg` on the PATH. @@ -87,6 +101,9 @@ Owner commands (private chat, only for the IDs in `OWNER_IDS`): | --- | --- | | `/purge ` | Take a video down: delete its files, block it for good | | `/cache` | Cache size, hit rate and volume saved | +| `/workers` | Workers, their state, load, tags and yt-dlp version | +| `/drain ` | Let a worker finish its jobs and take no new ones | +| `/ytdlp update` | Update yt-dlp on every worker now | ### Turning on payments @@ -133,6 +150,8 @@ The settings you are most likely to touch: make check # gofmt, go vet, tests with the race detector make test # tests only make e2e # real yt-dlp against a public test file, needs network +make test-postgres PG_DSN=postgres://... # the same suite on Postgres +make acceptance # kill a worker mid-job, watch the other finish ``` The tests need neither a bot token nor network access. They run the real @@ -141,13 +160,18 @@ yt-dlp. ## Documentation +- [docs/OPERATIONS.md](docs/OPERATIONS.md): deploying and running it. +- [docs/WORKERS.md](docs/WORKERS.md): adding download workers, tags, drain. - [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): how the pieces fit. - [docs/ASSUMPTIONS.md](docs/ASSUMPTIONS.md): decisions and verified facts. ## Layout ``` -cmd/core the bot gateway (and, for now, the embedded worker) +cmd/core the bot gateway, with an embedded worker by default +cmd/worker the standalone download worker +cmd/faketelegram a fake Bot API for development and acceptance runs +deploy Dockerfile, systemd units, acceptance script internal/bot Telegram handlers, cards, status, delivery internal/service download rules shared by all front ends internal/entitle who pays and which limits apply (pure function) diff --git a/cmd/core/main.go b/cmd/core/main.go index 787d647..712da30 100644 --- a/cmd/core/main.go +++ b/cmd/core/main.go @@ -1,6 +1,11 @@ // Command core is the bot gateway: it talks to Telegram, owns the queue and // the database, serves the HTTP API and, by default, runs an embedded // download worker. +// +// core run the bot +// core worker add register a remote worker and print its token +// core worker revoke revoke a worker's token +// core worker list list workers package main import ( @@ -29,6 +34,19 @@ func main() { ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() + // "core worker ..." manages worker tokens and exits. + if args := flag.Args(); len(args) > 0 { + if args[0] != "worker" { + fmt.Fprintf(os.Stderr, "unknown command %q\n", args[0]) + os.Exit(2) + } + if err := app.WorkerAdmin(ctx, cfg, args[1:], os.Stdout); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + return + } + a, err := app.New(ctx, app.Options{Config: cfg, Log: log}) if err != nil { log.Error("startup failed", "err", err) diff --git a/cmd/faketelegram/main.go b/cmd/faketelegram/main.go new file mode 100644 index 0000000..2d5643a --- /dev/null +++ b/cmd/faketelegram/main.go @@ -0,0 +1,110 @@ +// Command faketelegram is a stand-in for the Telegram Bot API, for trying +// the bot without a real bot token: local development, the acceptance +// scripts and load tests. +// +// It serves the Bot API methods the bot uses on -listen, for the token +// printed at startup, plus a small control API to play the user: +// +// POST /control/message {"chat_id":1,"user_id":1,"text":"https://..."} +// POST /control/callback {"chat_id":1,"user_id":1,"message_id":7,"data":"dl:..."} +// GET /control/calls?method=sendVideo&after=0 +// +// It must never face the internet: it accepts anything from anyone. +package main + +import ( + "encoding/json" + "flag" + "fmt" + "log" + "net/http" + "strconv" + + "github.com/noderunners/dlbot/internal/tg/fakeserver" +) + +func main() { + listen := flag.String("listen", "127.0.0.1:8090", "address to listen on") + flag.Parse() + + fake := fakeserver.NewHandler() + mux := http.NewServeMux() + mux.Handle("/bot"+fakeserver.Token+"/", fake) + + mux.HandleFunc("POST /control/message", func(w http.ResponseWriter, r *http.Request) { + var in struct { + ChatID int64 `json:"chat_id"` + UserID int64 `json:"user_id"` + Text string `json:"text"` + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Text == "" { + http.Error(w, "need chat_id, user_id and text", http.StatusBadRequest) + return + } + if in.UserID == 0 { + in.UserID = in.ChatID + } + id := fake.PushMessage(in.ChatID, in.UserID, in.Text) + writeJSON(w, map[string]int{"message_id": id}) + }) + + mux.HandleFunc("POST /control/callback", func(w http.ResponseWriter, r *http.Request) { + var in struct { + ChatID int64 `json:"chat_id"` + UserID int64 `json:"user_id"` + MessageID int `json:"message_id"` + Data string `json:"data"` + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Data == "" { + http.Error(w, "need chat_id, user_id, message_id and data", http.StatusBadRequest) + return + } + if in.UserID == 0 { + in.UserID = in.ChatID + } + writeJSON(w, map[string]string{"callback_id": fake.PushCallback(in.ChatID, in.UserID, in.MessageID, in.Data)}) + }) + + mux.HandleFunc("GET /control/calls", func(w http.ResponseWriter, r *http.Request) { + after, _ := strconv.Atoi(r.URL.Query().Get("after")) + type call struct { + Seq int `json:"seq"` + Method string `json:"method"` + MessageID int `json:"message_id,omitempty"` + Text string `json:"text,omitempty"` + Params map[string]string `json:"params"` + Files map[string]int64 `json:"files,omitempty"` + Buttons []string `json:"buttons,omitempty"` + Failed bool `json:"failed,omitempty"` + } + out := []call{} + for _, c := range fake.Calls(r.URL.Query().Get("method")) { + if c.Seq <= after { + continue + } + item := call{Seq: c.Seq, Method: c.Method, MessageID: c.MessageID, Text: c.Text(), Params: c.Params, Failed: c.Failed} + if len(c.Files) > 0 { + item.Files = map[string]int64{} + for field, f := range c.Files { + item.Files[field] = f.Size + } + } + for _, b := range c.Buttons() { + if b.Data != "" { + item.Buttons = append(item.Buttons, b.Data) + } + } + out = append(out, item) + } + writeJSON(w, out) + }) + + fmt.Printf("fake Telegram Bot API on http://%s\n", *listen) + fmt.Printf(" BOT_TOKEN=%s\n TELEGRAM_API_URL=http://%s\n", fakeserver.Token, *listen) + log.Fatal(http.ListenAndServe(*listen, mux)) +} + +func writeJSON(w http.ResponseWriter, v any) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(v) +} diff --git a/cmd/worker/main.go b/cmd/worker/main.go new file mode 100644 index 0000000..c258bdc --- /dev/null +++ b/cmd/worker/main.go @@ -0,0 +1,177 @@ +// Command worker is a stateless download worker. It connects out to the +// core, takes jobs, runs yt-dlp and ffmpeg, uploads the results and +// reports back. It opens no inbound port (apart from an optional local +// health endpoint) and never sees the bot token. +package main + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "os" + "os/signal" + "sync" + "syscall" + "time" + + "github.com/noderunners/dlbot/internal/app" + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/ffmpeg" + "github.com/noderunners/dlbot/internal/worker" + "github.com/noderunners/dlbot/internal/workerproto" + "github.com/noderunners/dlbot/internal/ytdlp" +) + +func main() { + cfg, err := config.LoadWorker() + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + log := app.NewLogger(cfg.Log, cfg.Token) + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + + runner := &ytdlp.Exec{ + Path: cfg.YtDlpPath, + FfmpegPath: cfg.FfmpegPath, + ProbeTimeout: cfg.ProbeTimeout.D(), + DownloadTimeout: cfg.DownloadTimeout.D(), + ExtraArgs: cfg.ExtraArgs, + } + up := &updater{runner: runner, log: log} + up.refresh(ctx) + if up.get() == "" { + log.Error("yt-dlp does not run, downloads will fail", "path", cfg.YtDlpPath) + } + + w := worker.New(worker.Config{ + ID: "remote", // the core takes the identity from the token + Tags: cfg.Tags, + Concurrency: cfg.Concurrency, + TempDir: cfg.TempDir, + Heartbeat: cfg.Heartbeat.D(), + ClaimWait: 20 * time.Second, + ProbeSlots: cfg.ProbeSlots, + Version: up.get, + OnCommand: func(cmd string) { + if cmd == workerproto.CommandUpdateYtDlp { + go up.update(ctx) + } + }, + }, worker.NewHTTPCoordinator(cfg.CoreURL, cfg.Token), runner, log) + w.SetTranscoder(&ffmpeg.Exec{Path: cfg.FfmpegPath, Timeout: cfg.DownloadTimeout.D()}) + + var wg sync.WaitGroup + if cfg.HealthListen != "" { + srv := healthServer(cfg.HealthListen, w) + wg.Add(1) + go func() { + defer wg.Done() + if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Warn("health endpoint stopped", "err", err) + } + }() + go func() { + <-ctx.Done() + sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = srv.Shutdown(sctx) + }() + } + if every := cfg.AutoUpdate.D(); every > 0 { + go func() { + t := time.NewTicker(every) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + up.update(ctx) + } + } + }() + } + + log.Info("worker started", "core", cfg.CoreURL, "tags", cfg.Tags, "concurrency", cfg.Concurrency, + "ytdlp", up.get(), "probe_slots", cfg.ProbeSlots) + w.Run(ctx) // returns when every running job has been handed back + wg.Wait() + log.Info("worker stopped") +} + +// healthServer answers /healthz. The worker is healthy while the core +// keeps answering its claims and accepts its token. +func healthServer(addr string, w *worker.Worker) *http.Server { + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", func(rw http.ResponseWriter, _ *http.Request) { + last, authFailed := w.LastContact() + age := time.Since(last) + status, code := "ok", http.StatusOK + switch { + case authFailed: + status, code = "token rejected by the core", http.StatusServiceUnavailable + case age > 2*time.Minute: + status, code = "core unreachable", http.StatusServiceUnavailable + } + rw.Header().Set("Content-Type", "application/json") + rw.WriteHeader(code) + _ = json.NewEncoder(rw).Encode(map[string]any{ + "status": status, "active_jobs": w.Active(), "seconds_since_core_contact": int(age.Seconds()), + }) + }) + return &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second} +} + +// updater keeps yt-dlp current and remembers its version. +type updater struct { + runner *ytdlp.Exec + log *slog.Logger + mu sync.Mutex + busy bool + ver string +} + +func (u *updater) get() string { + u.mu.Lock() + defer u.mu.Unlock() + return u.ver +} + +func (u *updater) refresh(ctx context.Context) { + v, err := u.runner.Version(ctx) + if err != nil { + u.log.Warn("cannot read the yt-dlp version", "err", err) + return + } + u.mu.Lock() + u.ver = v + u.mu.Unlock() +} + +func (u *updater) update(ctx context.Context) { + u.mu.Lock() + if u.busy { + u.mu.Unlock() + return + } + u.busy = true + u.mu.Unlock() + defer func() { + u.mu.Lock() + u.busy = false + u.mu.Unlock() + }() + before := u.get() + out, err := u.runner.Update(ctx) + u.refresh(ctx) + if err != nil { + u.log.Warn("yt-dlp update failed", "err", err, "output", out) + return + } + u.log.Info("yt-dlp update done", "before", before, "after", u.get()) +} diff --git a/config.example.toml b/config.example.toml index e8200ad..bf9e0ea 100644 --- a/config.example.toml +++ b/config.example.toml @@ -9,6 +9,9 @@ owners = [] # Public HTTPS base URL of this server, without a trailing slash. public_url = "" +# Who looks links up for the card: "auto", "local" or "worker". +probe_mode = "auto" + [telegram] api_url = "https://api.telegram.org" mode = "polling" # polling or webhook @@ -27,8 +30,25 @@ dsn = "data/dlbot.db" backend = "local" # local or s3 local_dir = "data/files" +# Only for backend = "s3". Put the keys in S3_ACCESS_KEY and S3_SECRET_KEY +# in the environment, not here. +[storage.s3] +endpoint = "" +bucket = "" +region = "garage" +use_ssl = true +path_style = true # Garage and MinIO: true. AWS: false. +prefix = "" +presign = true # workers upload straight to the bucket +presign_endpoint = "" + +# Which worker tags a site requires. A host covers its subdomains. +# [site_tags] +# "youtube.com" = ["residential"] + [worker] embedded = true +tags = [] # tags of the embedded worker concurrency = 2 temp_dir = "data/tmp" ytdlp_path = "yt-dlp" diff --git a/deploy/Dockerfile b/deploy/Dockerfile new file mode 100644 index 0000000..f14dfa6 --- /dev/null +++ b/deploy/Dockerfile @@ -0,0 +1,85 @@ +# syntax=docker/dockerfile:1 +# +# One Dockerfile, three targets: +# +# docker build -f deploy/Dockerfile --target core -t dlbot-core . +# docker build -f deploy/Dockerfile --target worker -t dlbot-worker . +# docker build -f deploy/Dockerfile --target faketelegram -t dlbot-faketelegram . +# +# docker-compose.yml builds core and worker for you. + +ARG GO_VERSION=1.26 +ARG DEBIAN_VERSION=bookworm + +# --- build ------------------------------------------------------------------- +FROM golang:${GO_VERSION}-${DEBIAN_VERSION} AS build +WORKDIR /src +# go.mod asks for a specific Go patch release. Let the toolchain fetch it +# when the image is a little older. +ENV GOTOOLCHAIN=auto CGO_ENABLED=0 +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN go build -trimpath -ldflags "-s -w" -o /out/core ./cmd/core \ + && go build -trimpath -ldflags "-s -w" -o /out/worker ./cmd/worker \ + && go build -trimpath -ldflags "-s -w" -o /out/faketelegram ./cmd/faketelegram + +# --- runtime base: ffmpeg and yt-dlp ----------------------------------------- +FROM debian:${DEBIAN_VERSION}-slim AS runtime +ARG TARGETARCH +# "latest", or a release tag such as 2026.10.26 to pin the version. +ARG YTDLP_VERSION=latest +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl ffmpeg tini \ + && rm -rf /var/lib/apt/lists/* \ + && useradd --system --uid 10001 --home-dir /data --shell /usr/sbin/nologin dlbot \ + && mkdir -p /data /opt/dlbot/bin \ + && case "${TARGETARCH:-amd64}" in \ + arm64) asset=yt-dlp_linux_aarch64 ;; \ + *) asset=yt-dlp_linux ;; \ + esac \ + && if [ "$YTDLP_VERSION" = "latest" ]; then \ + url="https://github.com/yt-dlp/yt-dlp/releases/latest/download/$asset"; \ + else \ + url="https://github.com/yt-dlp/yt-dlp/releases/download/$YTDLP_VERSION/$asset"; \ + fi \ + && curl -fsSL -o /opt/dlbot/bin/yt-dlp "$url" \ + && chmod 0755 /opt/dlbot/bin/yt-dlp \ + # yt-dlp updates itself in place, so its directory belongs to the service user. + && chown -R dlbot:dlbot /data /opt/dlbot +ENV PATH="/opt/dlbot/bin:${PATH}" \ + YTDLP_PATH=/opt/dlbot/bin/yt-dlp \ + FFMPEG_PATH=ffmpeg +USER dlbot +WORKDIR /data +ENTRYPOINT ["/usr/bin/tini", "--"] + +# --- core -------------------------------------------------------------------- +FROM runtime AS core +COPY --from=build /out/core /usr/local/bin/core +ENV HTTP_LISTEN=:8080 \ + DB_DSN=/data/dlbot.db \ + STORAGE_LOCAL_DIR=/data/files \ + WORKER_TEMP_DIR=/data/tmp +VOLUME ["/data"] +EXPOSE 8080 +HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=3 \ + CMD curl -fsS http://127.0.0.1:8080/healthz || exit 1 +CMD ["core"] + +# --- worker ------------------------------------------------------------------ +FROM runtime AS worker +COPY --from=build /out/worker /usr/local/bin/worker +ENV WORKER_TEMP_DIR=/data/tmp \ + WORKER_HEALTH_LISTEN=:8081 +VOLUME ["/data"] +HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=3 \ + CMD curl -fsS http://127.0.0.1:8081/healthz || exit 1 +CMD ["worker"] + +# --- fake Telegram, for trying the bot without a token ----------------------- +FROM debian:${DEBIAN_VERSION}-slim AS faketelegram +COPY --from=build /out/faketelegram /usr/local/bin/faketelegram +USER 10001 +EXPOSE 8090 +CMD ["faketelegram", "-listen", ":8090"] diff --git a/deploy/acceptance/compose.yml b/deploy/acceptance/compose.yml new file mode 100644 index 0000000..65923ed --- /dev/null +++ b/deploy/acceptance/compose.yml @@ -0,0 +1,46 @@ +# Overlay for the kill-a-worker acceptance run. It swaps the real Telegram +# for the fake one, so no bot token is needed, and slows downloads down so +# there is time to kill a worker in the middle of one. +# +# deploy/acceptance/kill-worker.sh # MODE=compose uses this file +# +# Never expose this setup to the internet: the fake Telegram accepts +# anything from anyone. + +services: + faketelegram: + build: + # Paths in an overlay are relative to the first compose file, which + # is the one in the repository root. + context: . + dockerfile: deploy/Dockerfile + target: faketelegram + image: dlbot-faketelegram:local + ports: + - "127.0.0.1:${FAKE_PORT:-8090}:8090" + + core: + depends_on: + - faketelegram + environment: + BOT_TOKEN: "123456789:FAKEfakeFAKEfakeFAKEfakeFAKEfake-01" + TELEGRAM_API_URL: http://faketelegram:8090 + QUEUE_LEASE: 12s + QUEUE_HEARTBEAT: 4s + LOG_FORMAT: text + + worker-a: + environment: + WORKER_CONCURRENCY: "1" + WORKER_HEARTBEAT: 4s + YTDLP_EXTRA_ARGS: "--limit-rate ${RATE:-50K}" + YTDLP_AUTO_UPDATE: "0" + LOG_FORMAT: text + + worker-b: + environment: + WORKER_CONCURRENCY: "1" + WORKER_HEARTBEAT: 4s + YTDLP_EXTRA_ARGS: "--limit-rate ${RATE:-50K}" + YTDLP_AUTO_UPDATE: "0" + LOG_FORMAT: text diff --git a/deploy/acceptance/kill-worker.sh b/deploy/acceptance/kill-worker.sh new file mode 100755 index 0000000..08d81b6 --- /dev/null +++ b/deploy/acceptance/kill-worker.sh @@ -0,0 +1,202 @@ +#!/usr/bin/env bash +# Acceptance check for scale-out: kill a worker in the middle of a job and +# watch the job go back to the queue and get finished by the other worker. +# +# deploy/acceptance/kill-worker.sh # plain processes +# MODE=compose deploy/acceptance/kill-worker.sh # docker compose +# +# Both modes run the real core and two real workers, talking over the HTTP +# worker protocol, with the real yt-dlp downloading a small public test +# file slowly enough to be interrupted. Telegram is replaced by the fake +# server in cmd/faketelegram, so no bot token is needed. +# +# Needs: bash, curl, python3. Process mode also needs go, yt-dlp, ffmpeg. +# Compose mode needs docker compose. Both need internet access for URL. +set -euo pipefail + +MODE=${MODE:-process} +URL=${URL:-https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4} +RATE=${RATE:-50K} # download speed limit, so the job lasts a while +FAKE_PORT=${FAKE_PORT:-18090} +CORE_PORT=${CORE_PORT:-18080} +CHAT=4242 +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +WORK=$(mktemp -d "${TMPDIR:-/tmp}/dlbot-accept.XXXXXX") +TOKEN_A=dlw_acceptance_token_for_worker_a_000000 +TOKEN_B=dlw_acceptance_token_for_worker_b_000000 +FAKE="http://127.0.0.1:$FAKE_PORT" +PIDS=() + +say() { printf '\n==> %s\n' "$*"; } +fail() { printf '\nFAIL: %s\n' "$*" >&2; dump; exit 1; } + +dump() { + if [ "$MODE" = compose ]; then + compose logs --no-color --tail 40 core worker-a worker-b 2>/dev/null || true + else + for f in core worker-a worker-b; do + [ -f "$WORK/$f.log" ] && { echo "--- $f.log (tail)"; tail -n 15 "$WORK/$f.log"; } + done + fi +} + +compose() { + WORKER_A_TOKEN=$TOKEN_A WORKER_B_TOKEN=$TOKEN_B RATE=$RATE FAKE_PORT=$FAKE_PORT CORE_PORT=$CORE_PORT \ + docker compose -p dlbot-accept --env-file /dev/null \ + -f "$ROOT/docker-compose.yml" -f "$ROOT/deploy/acceptance/compose.yml" "$@" +} + +cleanup() { + if [ "$MODE" = compose ]; then + compose down -v --remove-orphans >/dev/null 2>&1 || true + else + for pid in "${PIDS[@]:-}"; do kill "$pid" 2>/dev/null || true; done + wait 2>/dev/null || true + fi + if [ -n "${KEEP:-}" ]; then echo "logs kept in $WORK"; else rm -rf "$WORK"; fi +} +trap cleanup EXIT + +# calls prints the fake server's recorded calls as JSON. +calls() { curl -fsS "$FAKE/control/calls?method=$1"; } + +# wait_for polls until the command +# prints something, and prints that. +wait_for() { + local secs=$1 what=$2; shift 2 + local deadline=$((SECONDS + secs)) out + while [ $SECONDS -lt $deadline ]; do + out=$("$@" 2>/dev/null || true) + if [ -n "$out" ]; then printf '%s' "$out"; return 0; fi + sleep 1 + done + fail "timed out after ${secs}s waiting for $what" +} + +card_button() { # the "best" button of the newest card + { calls sendPhoto; calls editMessageText; } | python3 -I -c ' +import json, sys +best = None +for line in sys.stdin: + for c in json.loads(line): + for b in c.get("buttons") or []: + if b.startswith("dl:") and b.endswith(":best"): + best = (c["seq"], c["message_id"], b) +if best: print(best[1], best[2])' +} + +delivered() { # size of the file the bot sent, if it did + { calls sendVideo; calls sendDocument; } | python3 -I -c ' +import json, sys +for line in sys.stdin: + for c in json.loads(line): + if not c.get("failed") and c.get("files"): + print(list(c["files"].values())[0]); sys.exit()' +} + +# busy_worker prints a or b once that worker has started the job. +busy_worker() { + for w in a b; do + if [ "$MODE" = compose ]; then + compose logs --no-color "worker-$w" 2>/dev/null | grep -q 'msg="job started"' && { echo "$w"; return; } + else + grep -q 'msg="job started"' "$WORK/worker-$w.log" 2>/dev/null && { echo "$w"; return; } + fi + done +} + +started_count() { # how many times worker $1 started a job + if [ "$MODE" = compose ]; then + compose logs --no-color "worker-$1" 2>/dev/null | grep -c 'msg="job started"' || true + else + grep -c 'msg="job started"' "$WORK/worker-$1.log" 2>/dev/null || true + fi +} + +say "mode: $MODE, download: $URL at $RATE/s" +if [ "$MODE" = compose ]; then + say "building and starting core, worker-a, worker-b and the fake Telegram" + compose up -d --build +else + say "building binaries" + (cd "$ROOT" && go build -o "$WORK/bin/" ./cmd/core ./cmd/worker ./cmd/faketelegram) + + say "starting the fake Telegram, the core and two workers" + "$WORK/bin/faketelegram" -listen "127.0.0.1:$FAKE_PORT" >"$WORK/fake.log" 2>&1 & + PIDS+=($!) + + (cd "$WORK" && exec env -i PATH="$PATH" HOME="$WORK" \ + BOT_TOKEN="123456789:FAKEfakeFAKEfakeFAKEfakeFAKEfake-01" TELEGRAM_API_URL="$FAKE" \ + HTTP_LISTEN="127.0.0.1:$CORE_PORT" DB_DSN="$WORK/core.db" STORAGE_LOCAL_DIR="$WORK/files" \ + WORKER_EMBEDDED=false WORKER_TOKENS="worker-a:$TOKEN_A,worker-b:$TOKEN_B" \ + QUEUE_LEASE=12s QUEUE_HEARTBEAT=4s LOG_FORMAT=text \ + "$WORK/bin/core" >"$WORK/core.log" 2>&1) & + PIDS+=($!) + + start_worker() { # name token + (cd "$WORK" && exec env -i PATH="$PATH" HOME="$WORK" \ + CORE_URL="http://127.0.0.1:$CORE_PORT" WORKER_TOKEN="$2" WORKER_CONCURRENCY=1 \ + WORKER_TEMP_DIR="$WORK/tmp-$1" WORKER_HEARTBEAT=4s WORKER_HEALTH_LISTEN=off \ + YTDLP_PATH="${YTDLP_PATH:-yt-dlp}" YTDLP_EXTRA_ARGS="--limit-rate $RATE" YTDLP_AUTO_UPDATE=0 \ + LOG_FORMAT=text "$WORK/bin/worker" >"$WORK/worker-$1.log" 2>&1) & + echo $! >"$WORK/worker-$1.pid" + PIDS+=($!) + } +fi + +# Fail early when something else already listens on our ports. +if [ "$MODE" != compose ]; then + sleep 1 + for pid in "${PIDS[@]}"; do + kill -0 "$pid" 2>/dev/null || fail "a process exited right after start (are ports $FAKE_PORT and $CORE_PORT free?)" + done +fi +wait_for 60 "the fake Telegram" curl -fsS "$FAKE/control/calls?method=getMe" >/dev/null +wait_for 90 "the core to become healthy" curl -fsS "http://127.0.0.1:$CORE_PORT/healthz" >/dev/null +if [ "$MODE" != compose ]; then + start_worker a "$TOKEN_A" + start_worker b "$TOKEN_B" +fi + +say "a user sends the link" +curl -fsS -X POST "$FAKE/control/message" -H 'Content-Type: application/json' \ + -d "{\"chat_id\": $CHAT, \"user_id\": $CHAT, \"text\": \"$URL\"}" >/dev/null +CARD=$(wait_for 120 "the card (a worker has to look the link up)" card_button) +read -r MSG_ID BUTTON <<<"$CARD" +echo "card is message $MSG_ID, pressing $BUTTON" + +say "the user picks Best" +curl -fsS -X POST "$FAKE/control/callback" -H 'Content-Type: application/json' \ + -d "{\"chat_id\": $CHAT, \"user_id\": $CHAT, \"message_id\": $MSG_ID, \"data\": \"$BUTTON\"}" >/dev/null + +VICTIM=$(wait_for 60 "a worker to start the job" busy_worker) +if [ "$VICTIM" = a ]; then SURVIVOR=b; else SURVIVOR=a; fi +echo "worker-$VICTIM has the job" +sleep 4 # let it get well into the download + +say "killing worker-$VICTIM with SIGKILL, mid-download" +if [ "$MODE" = compose ]; then + compose kill -s SIGKILL "worker-$VICTIM" +else + # The worker and the yt-dlp it started: a machine that dies takes both. + WPID=$(cat "$WORK/worker-$VICTIM.pid") + pkill -KILL -P "$WPID" 2>/dev/null || true + kill -KILL "$WPID" 2>/dev/null || true + pkill -KILL -f "$WORK/tmp-$VICTIM" 2>/dev/null || true +fi +[ -z "$(delivered)" ] || fail "the file was delivered before the kill; lower RATE to make the job last longer" + +say "waiting for the core to notice, requeue, and for worker-$SURVIVOR to finish the job" +SIZE=$(wait_for 240 "the file to be delivered" delivered) + +[ "$(started_count "$SURVIVOR")" -ge 1 ] || fail "worker-$SURVIVOR never started the job" +if [ "$MODE" = compose ]; then + compose logs --no-color core | grep -q 'msg="lease expired"' || fail "the core did not log an expired lease" +else + grep -q 'msg="lease expired"' "$WORK/core.log" || fail "the core did not log an expired lease" + echo + grep -E 'msg="(job queued|job claimed|lease expired|job stored|file delivered)"' "$WORK/core.log" \ + | sed -E 's/^time=[^ ]+ //; s/ delivery_id=[^ ]+//; s/ user_id=[^ ]+//' | sed 's/^/ core: /' +fi + +say "PASS: worker-$VICTIM was killed mid-job, the job was re-queued and worker-$SURVIVOR delivered the file ($SIZE bytes)" diff --git a/deploy/systemd/dlbot-core.service b/deploy/systemd/dlbot-core.service new file mode 100644 index 0000000..73acbcd --- /dev/null +++ b/deploy/systemd/dlbot-core.service @@ -0,0 +1,48 @@ +# The Noderunners Download Bot: core. +# +# install -m 0755 bin/core /usr/local/bin/dlbot-core +# useradd --system --home-dir /var/lib/dlbot --create-home dlbot +# install -d -m 0750 -o dlbot -g dlbot /etc/dlbot +# install -m 0640 -o dlbot -g dlbot .env /etc/dlbot/core.env +# systemctl enable --now dlbot-core +# +# Paths in core.env should be absolute, for example +# DB_DSN=/var/lib/dlbot/dlbot.db +# STORAGE_LOCAL_DIR=/var/lib/dlbot/files +# WORKER_TEMP_DIR=/var/lib/dlbot/tmp + +[Unit] +Description=The Noderunners Download Bot (core) +Documentation=https://github.com/noderunners/dlbot +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=dlbot +Group=dlbot +WorkingDirectory=/var/lib/dlbot +EnvironmentFile=/etc/dlbot/core.env +ExecStart=/usr/local/bin/dlbot-core +Restart=on-failure +RestartSec=5 +# The core hands running jobs back to the queue on SIGTERM. +TimeoutStopSec=30 +KillSignal=SIGTERM + +# Hardening. The core only writes below /var/lib/dlbot. +NoNewPrivileges=true +ProtectSystem=strict +ProtectHome=true +PrivateTmp=true +PrivateDevices=true +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectControlGroups=true +RestrictSUIDSGID=true +LockPersonality=true +ReadWritePaths=/var/lib/dlbot +UMask=0027 + +[Install] +WantedBy=multi-user.target diff --git a/deploy/systemd/dlbot-worker.service b/deploy/systemd/dlbot-worker.service new file mode 100644 index 0000000..19e2032 --- /dev/null +++ b/deploy/systemd/dlbot-worker.service @@ -0,0 +1,51 @@ +# The Noderunners Download Bot: download worker. +# +# A worker needs outbound access to the core and to the sites it downloads +# from. It needs no inbound port and no secrets other than its own token. +# +# install -m 0755 bin/worker /usr/local/bin/dlbot-worker +# useradd --system --home-dir /var/lib/dlbot-worker --create-home dlbot +# install -d -m 0750 -o dlbot -g dlbot /etc/dlbot +# printf 'CORE_URL=https://bot.example.com\nWORKER_TOKEN=dlw_...\nWORKER_TEMP_DIR=/var/lib/dlbot-worker/tmp\n' \ +# > /etc/dlbot/worker.env && chmod 0640 /etc/dlbot/worker.env && chown dlbot:dlbot /etc/dlbot/worker.env +# systemctl enable --now dlbot-worker +# +# yt-dlp updates itself, so install it somewhere the service user can +# write, for example /var/lib/dlbot-worker/bin/yt-dlp, and set YTDLP_PATH. +# To run several workers on one machine, copy this unit and give each its +# own token and its own WORKER_TEMP_DIR. + +[Unit] +Description=The Noderunners Download Bot (worker) +Documentation=https://github.com/noderunners/dlbot +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=dlbot +Group=dlbot +WorkingDirectory=/var/lib/dlbot-worker +EnvironmentFile=/etc/dlbot/worker.env +ExecStart=/usr/local/bin/dlbot-worker +Restart=on-failure +RestartSec=5 +# On SIGTERM the worker stops its downloads and hands the jobs back. +TimeoutStopSec=30 +KillSignal=SIGTERM + +NoNewPrivileges=true +ProtectSystem=strict +ProtectHome=true +PrivateTmp=true +PrivateDevices=true +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectControlGroups=true +RestrictSUIDSGID=true +LockPersonality=true +ReadWritePaths=/var/lib/dlbot-worker +UMask=0027 + +[Install] +WantedBy=multi-user.target diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..d4766e4 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,116 @@ +# The Noderunners Download Bot: core, two workers, and two optional services. +# +# cp .env.example .env # set BOT_TOKEN, WORKER_A_TOKEN, WORKER_B_TOKEN +# docker compose up -d --build +# +# Optional services are behind profiles: +# +# docker compose --profile postgres up -d # Postgres instead of SQLite +# docker compose --profile local-api up -d # local Bot API server, 2 GB uploads +# +# See docs/OPERATIONS.md for what to put in .env for each of them. + +name: dlbot + +x-worker: &worker + build: + context: . + dockerfile: deploy/Dockerfile + target: worker + image: dlbot-worker:local + restart: unless-stopped + depends_on: + core: + condition: service_healthy + # A worker has no inbound ports. It only needs to reach the core and the + # sites it downloads from. + environment: &worker-env + CORE_URL: http://core:8080 + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} + WORKER_TEMP_DIR: /data/tmp + YTDLP_EXTRA_ARGS: ${YTDLP_EXTRA_ARGS:-} + LOG_LEVEL: ${LOG_LEVEL:-info} + stop_grace_period: 30s + +services: + core: + build: + context: . + dockerfile: deploy/Dockerfile + target: core + image: dlbot-core:local + restart: unless-stopped + # Everything from .env.example can go in .env. The core refuses to + # start without BOT_TOKEN, so a missing file is noticed at once. + env_file: + - path: .env + required: false + environment: + HTTP_LISTEN: ":8080" + # Downloads run on the workers below, not inside the core. + WORKER_EMBEDDED: "false" + WORKER_TOKENS: "worker-a:${WORKER_A_TOKEN:?set WORKER_A_TOKEN in .env},worker-b:${WORKER_B_TOKEN:?set WORKER_B_TOKEN in .env}" + volumes: + - core-data:/data + ports: + # Bound to localhost. Put a TLS reverse proxy in front for PUBLIC_URL. + - "127.0.0.1:${CORE_PORT:-8080}:8080" + stop_grace_period: 30s + + worker-a: + <<: *worker + environment: + <<: *worker-env + WORKER_TOKEN: ${WORKER_A_TOKEN:?set WORKER_A_TOKEN in .env} + WORKER_TAGS: ${WORKER_A_TAGS:-} + volumes: + - worker-a-data:/data + + worker-b: + <<: *worker + environment: + <<: *worker-env + WORKER_TOKEN: ${WORKER_B_TOKEN:?set WORKER_B_TOKEN in .env} + WORKER_TAGS: ${WORKER_B_TAGS:-} + volumes: + - worker-b-data:/data + + # Optional: Postgres. In .env set + # DB_DRIVER=postgres + # DB_DSN=postgres://dlbot:@postgres:5432/dlbot?sslmode=disable + postgres: + profiles: ["postgres"] + image: postgres:16-alpine + restart: unless-stopped + environment: + POSTGRES_USER: dlbot + POSTGRES_DB: dlbot + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-change-me} + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U dlbot -d dlbot"] + interval: 10s + timeout: 5s + retries: 5 + + # Optional: local Bot API server, for files up to 2 GB. In .env set + # TELEGRAM_API_URL=http://telegram-bot-api:8081 + # TELEGRAM_MAX_UPLOAD_MB=2000 + # and TELEGRAM_API_ID / TELEGRAM_API_HASH from https://my.telegram.org. + telegram-bot-api: + profiles: ["local-api"] + image: aiogram/telegram-bot-api:latest + restart: unless-stopped + environment: + TELEGRAM_API_ID: ${TELEGRAM_API_ID:-} + TELEGRAM_API_HASH: ${TELEGRAM_API_HASH:-} + volumes: + - telegram-bot-api-data:/var/lib/telegram-bot-api + +volumes: + core-data: + worker-a-data: + worker-b-data: + postgres-data: + telegram-bot-api-data: diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8f171d4..f8b9a1d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -8,23 +8,27 @@ phase; sections for later phases say so. ``` Telegram <----> core <---- claim / heartbeat / complete / fail ---- worker(s) | \ | - | \__ storage (local disk today, S3 in Phase 4) <___/ + | \__ storage (local disk or S3) <__________________/ | - database (SQLite today, Postgres in Phase 4) + database (SQLite or Postgres) ``` - **core** (`cmd/core`) talks to Telegram, owns the database and the queue, serves HTTP and sends finished files. It is the only process that holds the bot token. - **worker** pulls jobs, runs yt-dlp and ffmpeg, uploads the result to - storage and reports back. It is stateless. Today it runs inside the core - process; the code is already split along the future network boundary. + storage and reports back. It is stateless. One runs inside the core + process by default (`WORKER_EMBEDDED`); any number of others run as the + `cmd/worker` binary anywhere that can reach the core over HTTPS. ## Packages | Package | Role | | --- | --- | -| `cmd/core` | Process entry point. Loads config, starts `internal/app`. | +| `cmd/core` | Process entry point. Loads config, starts `internal/app`. Also `core worker add/revoke/list`. | +| `cmd/worker` | The standalone download worker. | +| `cmd/faketelegram` | A fake Bot API with a control API, for development and the acceptance script. | +| `internal/probe` | Hands link lookups to remote workers and waits for the answer. | | `internal/app` | Wires everything together. Tests start the bot through it too. | | `internal/config` | Defaults, optional TOML file, environment overrides, validation. | | `internal/bot` | Telegram front end: update routing, cards, live status, delivery. | @@ -119,6 +123,51 @@ that a file is sent by one goroutine only. - A worker that loses its lease is told so on its next call and drops the job without reporting a result. +## Scale out + +### Two transports, one protocol + +The worker loop talks to a `Coordinator` interface: claim, heartbeat, +complete, fail, upload, fetch. `sched.Local` implements it with direct +calls for the embedded worker. `worker.HTTPCoordinator` implements it over +the core's `/worker/v1/` routes for remote workers. Both carry the same +`workerproto` messages, so the scheduler does not know or care where a +worker runs. + +### Trust + +A remote worker is authenticated by a bearer token that only exists hashed +in the database. The API handler resolves the token to a worker and +overwrites the `worker_id` of every request with it. A job action is only +accepted for a job whose lease is held by that worker, and a completed +job's storage key is derived by the core from the job ID. A worker can +therefore fail or stall its own jobs, which the lease handles, but cannot +touch anyone else's. + +### Tags + +`site_tags` maps hosts to the worker tags they require. `service.Start` +writes the required tags on the job; a claim only returns jobs whose tags +the claiming worker has. The same rule routes link lookups. + +### Link lookups without yt-dlp on the core + +`probe.Broker` implements the same `Probe` call as the local yt-dlp +runner. It parks the request, wakes waiting claim calls, and a worker that +asked with `probe_only` takes it, runs yt-dlp and posts the info JSON +back. The service does not know which of the two it is talking to. + +### Databases + +`internal/db` has one set of queries. Three things differ by dialect: +placeholders (`?` rewritten to `$n`), claiming (`FOR UPDATE SKIP LOCKED` on +Postgres, an immediate transaction on SQLite), and two locks Postgres +needs because it runs transactions concurrently: `LockUser` (advisory) and +`LockJob` (row). Both are no-ops on SQLite. + +The test suite runs unchanged on both: `dbtest` gives each test a SQLite +file or, with `DLBOT_TEST_DB=postgres`, its own Postgres schema. + ## Events and reconciliation The scheduler notifies the bot through an in-process callback after each diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index ea940d8..dccc10a 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -366,3 +366,89 @@ Read from the LNbits source at `v0.12.12` (the target) and `v1.7.1` (current). - `/subs` lists written subtitles before automatic captions, with the requester's language first and marked. At most 24 languages are shown. - `/history` shows the last 10 delivered files. + +## Phase 4 + +### What could and could not be run here + +- **Docker was not available on the build machine.** The user that built + this has no access to the Docker socket, and rootless Docker is missing + its helpers. So `deploy/Dockerfile` and `docker-compose.yml` were written + and checked with `docker compose config` (which parses, merges and + interpolates them without a daemon), but **no image was built and no + container was run**. Treat the first `docker compose up --build` as the + real test of those files. +- **The acceptance scenario itself was run for real**, with the same + binaries as separate OS processes: one core, two workers over the HTTP + worker protocol, the real yt-dlp downloading a rate-limited public file, + and `kill -9` on the worker that held the job. The core logged the + expired lease, requeued the job, and the second worker delivered the + file. `deploy/acceptance/kill-worker.sh` does this in both modes; + `MODE=compose` is the untested one. +- **Postgres was tested against a real Postgres 15**, started as a private + instance. The whole test suite, end-to-end flows included, passes on + SQLite and on Postgres. +- **S3 was tested against an in-memory S3 server** (`gofakes3`), not + against Garage, MinIO or AWS. The client is `minio-go`, which those + servers are routinely used with. +- **The local Bot API server was not run.** Support for it is + configuration: `TELEGRAM_API_URL` and `TELEGRAM_MAX_UPLOAD_MB`. Uploads + are streamed, never buffered, so a 2 GB file does not need 2 GB of RAM. + +### Database + +- One schema and one set of queries for both engines. Queries use `?` + placeholders that are rewritten to `$n` for Postgres. +- **Postgres needed two explicit locks that SQLite gives for free.** + SQLite runs write transactions one at a time; Postgres runs them side by + side. A per-user advisory lock guards "count active jobs, then insert + one", and a row lock on the job guards every "read the status, then act + on it". Without the second, cancelling a job could cross with a worker + claiming it and leave a job running for nobody. The test suite found + that on its first Postgres run. +- One core per database. Nothing coordinates two cores. +- No data migration between SQLite and Postgres. + +### Workers + +- **Tokens** are random, per worker, stored as SHA-256 hashes, and + revocable. They are created with `core worker add ` (a CLI + subcommand rather than a bot command, so a token never passes through + Telegram) or listed in `WORKER_TOKENS` for fixed setups. +- A worker's identity comes from its token. The `worker_id` field in a + request body is ignored. +- **Scope:** a token can claim, heartbeat, complete, fail and upload, and + only for jobs leased to that worker. The storage key of a result is + chosen by the core. +- **Tags** are matched exactly: a job goes to a worker that has all of the + site's tags. A claim looks at the first 25 queued jobs to find one the + worker qualifies for, so a job waiting for a rare tag does not block the + queue behind it. +- **Draining** is a flag on the core, checked on every claim. A draining + worker gets neither jobs nor lookups. +- **Lease expiry counts as an attempt; a clean shutdown does not.** +- **Fleet capacity** for the reserved free slot is still counted in memory + from recent claims. + +### Link lookups + +- With remote workers only, the core has no yt-dlp, so lookups for cards + are handed to workers through their claim calls (`PROBE_MODE`). They are + held in memory: a core restart drops a pending lookup and the user sends + the link again. Workers keep two extra claim requests open for lookups, + so cards stay quick when all download slots are busy. +- Lookups follow the same tag rules as downloads. + +### Storage + +- With S3, workers upload through presigned URLs and the core is not in + the data path. With local disk, they stream the file to the core. +- An upload of unknown size is spooled to a temp file first, to avoid + chunked streaming uploads that not every S3 compatible server accepts. +- The core's upload endpoint enforces the job's size cap while receiving. + +### yt-dlp updates + +- Each worker updates its own yt-dlp on a schedule (`yt-dlp -U`). + `/ytdlp update` is delivered to workers with their next claim, so it + reaches every connected worker within seconds. diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md new file mode 100644 index 0000000..fd105b7 --- /dev/null +++ b/docs/OPERATIONS.md @@ -0,0 +1,186 @@ +# Operations + +How to deploy, scale and look after the bot. For workers see +[WORKERS.md](WORKERS.md). + +## Deploy with docker compose + +You need Docker with the compose plugin, and a bot token from @BotFather. + +```sh +git clone dlbot && cd dlbot +cp .env.example .env +``` + +Edit `.env`. The minimum is: + +```sh +BOT_TOKEN=123456:ABC... +OWNER_IDS= +WORKER_A_TOKEN= +WORKER_B_TOKEN= +``` + +Then: + +```sh +docker compose up -d --build +docker compose ps # core, worker-a, worker-b should be healthy +curl localhost:8080/healthz # {"status":"ok"} +``` + +Open the bot in Telegram, press Start, send a link. As an owner, `/workers` +shows both workers. + +The compose file runs the core without an embedded worker and two separate +workers. For a single small machine you can instead run only the core with +`WORKER_EMBEDDED=true` and no remote workers. + +## Deploy without Docker + +Build `bin/core` and `bin/worker` with `make build`, install `yt-dlp` and +`ffmpeg`, and use the units in `deploy/systemd/`. Each unit file starts +with the commands to install it. + +## Choosing the database + +**SQLite** is the default and needs nothing. It is a file +(`DB_DSN=data/dlbot.db`) and handles a busy bot on one machine. Back it up +with `sqlite3 dlbot.db ".backup backup.db"`, not with `cp`. + +**Postgres** is for when the core should be restartable on another machine, +or when you want the database on managed infrastructure. + +```sh +DB_DRIVER=postgres +DB_DSN=postgres://dlbot:@postgres:5432/dlbot?sslmode=disable +POSTGRES_PASSWORD= +docker compose --profile postgres up -d +``` + +The schema is the same on both and migrations run at startup. There is no +tool to move data from one to the other; choose before you have users, or +accept starting fresh. + +Run only **one core** per database. Workers scale out; the core does not. + +## Choosing storage + +**Local disk** (default): files live under `STORAGE_LOCAL_DIR`. Workers +send finished files through the core. + +**S3 compatible** (AWS S3, Garage, MinIO): set + +```sh +STORAGE_BACKEND=s3 +S3_ENDPOINT=https://s3.example.com +S3_BUCKET=dlbot +S3_ACCESS_KEY=... +S3_SECRET_KEY=... +S3_REGION=garage # whatever your server expects +S3_PATH_STYLE=true # Garage and MinIO: true. AWS: false. +``` + +The bucket must exist. With `S3_PRESIGN=true` (default) workers upload +straight to the bucket with presigned URLs. If workers reach the bucket +under another address than the core, set `S3_PRESIGN_ENDPOINT`. + +Storage holds the cache's stored copies. `CACHE_BUDGET_MB` caps it; the +sweeper evicts the least used files when it is exceeded. + +## Files up to 2 GB: the local Bot API server + +The cloud Bot API accepts uploads up to 50 MB. A local Bot API server +lifts that to 2000 MB. + +1. Get `api_id` and `api_hash` at https://my.telegram.org. +2. If the bot ever ran against the cloud API, log it out there once: + `curl https://api.telegram.org/bot/logOut`. A bot can be logged + in to one server at a time. +3. In `.env`: + + ```sh + TELEGRAM_API_ID=... + TELEGRAM_API_HASH=... + TELEGRAM_API_URL=http://telegram-bot-api:8081 + TELEGRAM_MAX_UPLOAD_MB=2000 + ``` + +4. `docker compose --profile local-api up -d` + +`TELEGRAM_MAX_UPLOAD_MB` is the ceiling for everyone. Passes allow up to +`PAID_MAX_SIZE_MB` (2000) but never more than this. + +## Public address, webhooks and TLS + +The core listens on `HTTP_LISTEN` (`:8080`). Compose binds it to localhost. +Put a TLS reverse proxy (Caddy, nginx, Traefik) in front and set +`PUBLIC_URL=https://bot.example.com` when you want any of: + +- instant payment settlement (LNbits webhook) and the "Open in wallet" button +- remote workers across the internet +- Telegram webhooks instead of long polling (`TELEGRAM_MODE=webhook`, + `WEBHOOK_URL`, `WEBHOOK_SECRET`) + +Routes the proxy must pass through: + +| Path | Who calls it | +| --- | --- | +| `/telegram/webhook` | Telegram (webhook mode only) | +| `/lnbits/webhook/` | LNbits | +| `/pay/` | Users pressing "Open in wallet" | +| `/worker/v1/...` | Remote workers. Allow long requests (30 s) and large uploads. | +| `/healthz` | Your monitoring | + +Without `PUBLIC_URL` the bot still works: long polling for Telegram, +polling for payments, workers on the same network. + +## Health and logs + +- `GET /healthz` on the core answers 200 while the database is reachable. +- `GET /healthz` on a worker (`WORKER_HEALTH_LISTEN`, `:8081`) answers 200 + while the core accepts its token and answers its calls. +- Logs are JSON on stderr, one object per line (`LOG_FORMAT=text` for + reading by eye). Every job line carries `job_id`. The bot token, payment + keys and worker tokens are removed from all log output, and URLs are + logged without credentials or signed parameters. +- Raw yt-dlp errors are in the log under `detail`. Users only ever see the + friendly message. + +## Owner commands + +Only in a private chat, only for the user IDs in `OWNER_IDS`. + +| Command | What it does | +| --- | --- | +| `/workers` | Workers, their state, load, tags and yt-dlp version | +| `/drain ` | Finish current jobs, take no new ones. `/drain off` undoes it. | +| `/ytdlp update` | Update yt-dlp on every worker now | +| `/cache` | Cache size, hit rate, volume saved | +| `/purge ` | Take a video down: delete its files and block it for good | + +## Backups + +Back up the database. It holds wallets and the ledger, which are money. +Storage only holds cached files and can be lost without harm: the bot +downloads again. + +## Updating + +```sh +git pull +docker compose up -d --build +``` + +The core stops cleanly on SIGTERM: workers hand their running jobs back to +the queue, and the next start resumes deliveries, refunds and unsettled +invoices from the database. + +## Checking a deployment + +```sh +make acceptance # or MODE=compose make acceptance +``` + +runs the core with two workers against a fake Telegram, kills a worker in +the middle of a download and checks that the other one delivers the file. diff --git a/docs/WORKERS.md b/docs/WORKERS.md new file mode 100644 index 0000000..7e742d1 --- /dev/null +++ b/docs/WORKERS.md @@ -0,0 +1,246 @@ +# Workers + +A worker downloads. It runs yt-dlp and ffmpeg, uploads the result and +reports back. Capacity grows by starting more workers, on the same machine +as the core or anywhere else. + +## What a worker is, and is not + +- **Stateless.** Nothing on a worker matters after a job is done. Its temp + directory is wiped at startup. +- **Outbound only.** A worker calls the core over HTTPS. The core never + connects to a worker, so workers need no inbound ports, no public address + and no VPN. A machine behind home NAT works. +- **Unprivileged.** A worker has one secret: its own token. It never sees + the bot token, the database, or the payment key. The token lets it claim + jobs, report on its own jobs, and upload their results. Nothing else. + +By default the core runs one worker inside its own process +(`WORKER_EMBEDDED=true`). That is all a small bot needs. Read on when you +want more capacity, or downloads from a different network than the core's. + +## Add a remote worker + +### 1. Create a token on the core + +```sh +core worker add eu-1 +``` + +``` +Worker "eu-1" is registered. Its token is shown once, store it now: + + WORKER_TOKEN=dlw_3f9c... +``` + +Only a hash of the token is stored. Run the command on the machine (or in +the container) of the core; it only needs the database, so the core can +keep running. + +With docker compose the two bundled workers get their tokens from `.env` +instead (`WORKER_A_TOKEN`, `WORKER_B_TOKEN`), which the core registers at +startup through `WORKER_TOKENS`. Any random string of 16 characters or more +works: `openssl rand -hex 24`. + +### 2. Start the worker + +The worker needs `yt-dlp` and `ffmpeg`, the URL of the core, and its token. + +```sh +CORE_URL=https://bot.example.com \ +WORKER_TOKEN=dlw_3f9c... \ +WORKER_TAGS=residential,eu \ +WORKER_TEMP_DIR=/var/lib/dlbot-worker/tmp \ +worker +``` + +Or as a container: + +```sh +docker build -f deploy/Dockerfile --target worker -t dlbot-worker . +docker run -d --name dlbot-worker --restart unless-stopped \ + -e CORE_URL=https://bot.example.com \ + -e WORKER_TOKEN=dlw_3f9c... \ + -e WORKER_TAGS=residential,eu \ + dlbot-worker +``` + +Or with systemd: see `deploy/systemd/dlbot-worker.service`. + +`CORE_URL` must reach the core's HTTP port (`HTTP_LISTEN`, 8080 by default). +Across the internet, put the core behind a TLS reverse proxy and use +`https://`. The token travels in a header and must not cross the internet +in the clear. + +### 3. Check that it arrived + +Send `/workers` to the bot as an owner, or run `core worker list`: + +``` +NAME STATE CAPACITY SEEN YT-DLP TAGS +eu-1 active 2 3s 2026.10.26 eu,residential +``` + +## Worker settings + +| Variable | Default | Meaning | +| --- | --- | --- | +| `CORE_URL` | none | Base URL of the core. Required. | +| `WORKER_TOKEN` | none | This worker's token. Required. | +| `WORKER_TAGS` | none | Comma separated tags, see below. | +| `WORKER_CONCURRENCY` | `2` | Downloads at the same time. | +| `WORKER_TEMP_DIR` | `data/worker-tmp` | Scratch space. One per worker process. | +| `WORKER_PROBE_SLOTS` | `2` | Link lookups running next to the downloads. | +| `WORKER_HEARTBEAT` | `10s` | Must be well under the core's `QUEUE_LEASE`. | +| `WORKER_HEALTH_LISTEN` | `:8081` | Health endpoint, or `off`. | +| `YTDLP_PATH` | `yt-dlp` | | +| `FFMPEG_PATH` | `ffmpeg` | `ffprobe` is expected next to it. | +| `YTDLP_EXTRA_ARGS` | none | Added to every yt-dlp call, for example `--proxy socks5://127.0.0.1:1080`. | +| `YTDLP_AUTO_UPDATE` | `24h` | How often yt-dlp updates itself. `0` turns it off. | +| `DOWNLOAD_TIMEOUT` | `30m` | Hard cap for one download. | +| `PROBE_TIMEOUT` | `45s` | Cap for one link lookup. | +| `LOG_LEVEL`, `LOG_FORMAT` | `info`, `json` | | + +Several workers on one machine each need their own token, their own +`WORKER_TEMP_DIR` and their own `WORKER_HEALTH_LISTEN` port (or `off`). + +## Tags: routing sites to the right network + +Some sites refuse downloads from datacenter addresses. YouTube answers +"Sign in to confirm you are not a bot" there. The fix is a worker on a +network the site accepts, and a rule that sends that site's jobs to it. + +1. Start a worker on a home connection with `WORKER_TAGS=residential`. +2. On the core, say which sites need the tag: + + ```sh + SITE_TAGS="youtube.com=residential;x.com=residential" + ``` + + or in `config.toml`: + + ```toml + [site_tags] + "youtube.com" = ["residential"] + "x.com" = ["residential"] + ``` + +A rule for a host covers its subdomains. A job for a listed site is only +given to workers that advertise every tag of the rule. This also applies +to the link lookup that builds the card. Sites without a rule go to any +worker. + +Tags are free-form: `residential`, `eu`, `us`, `fast`, `bigdisk`. A worker +with more tags than a job needs still qualifies. + +If no connected worker has a required tag, jobs for that site wait in the +queue and lookups time out. `/workers` shows the tags of each worker. + +## Where link lookups run + +A card needs yt-dlp metadata before any job exists. `PROBE_MODE` on the +core decides who fetches it: + +| Value | Who looks links up | +| --- | --- | +| `auto` (default) | The core itself when `WORKER_EMBEDDED=true`, remote workers otherwise. | +| `local` | Always the core. It needs yt-dlp. | +| `worker` | Always remote workers. The core needs no yt-dlp. | + +Use `worker` when the core sits on a network sites refuse but you still +keep the embedded worker for other sites. + +## Draining and removing a worker + +To take a worker out for maintenance without losing its downloads, as an +owner in the bot: + +``` +/drain eu-1 it finishes its jobs and gets no new ones +/drain eu-1 off it takes jobs again +``` + +Stopping a worker with SIGTERM (`systemctl stop`, `docker stop`) is also +safe: it stops its downloads and hands the jobs back to the queue at once, +and another worker picks them up without the retry being used up. + +To lock a worker out for good: + +```sh +core worker revoke eu-1 +``` + +Its token stops working immediately. `core worker add eu-1` issues a new +token and brings it back. + +## What happens when a worker dies + +A claimed job is on lease. The worker extends the lease with a heartbeat +every 10 seconds. When heartbeats stop (power cut, crash, lost network) the +lease runs out after `QUEUE_LEASE` (30 seconds), the core puts the job back +in the queue, and another worker takes it. The requester sees the status +go back to "queued" and then on to "done". A worker that comes back late is +told the job is no longer its own and drops it. + +A lost lease counts as an attempt, so a job that keeps killing workers is +given up on after `QUEUE_MAX_ATTEMPTS` (2). + +You can watch all of this happen: + +```sh +make acceptance # real processes +MODE=compose make acceptance # the same in containers +``` + +The script starts the core and two workers, has a user ask for a file, +kills the worker that is downloading it with SIGKILL, and waits for the +other worker to deliver it. + +## How files get from a worker to Telegram + +The worker uploads the finished file to storage, the core sends it to +Telegram. + +- **Local disk storage:** the worker streams the file to the core + (`PUT /worker/v1/upload/`), which writes it to its disk. +- **S3 storage:** the core gives the worker a presigned URL with the job, + and the file goes straight to the bucket. The core is not in the data + path. Workers must be able to reach the bucket; if they reach it under a + different address than the core does, set `S3_PRESIGN_ENDPOINT`. Set + `S3_PRESIGN=false` to route files through the core anyway. + +## Keeping yt-dlp current + +Sites change and yt-dlp follows weekly. Each worker updates its own yt-dlp +every `YTDLP_AUTO_UPDATE` (24 hours). For an urgent fix, as an owner: + +``` +/ytdlp update +``` + +Every connected worker updates when it next checks for work, which is +within seconds. `/workers` shows the version each one runs. + +Self-update works for the standalone yt-dlp binaries (what the Docker +image uses). A yt-dlp installed by a package manager is updated by that +package manager instead. + +## The protocol + +All calls are HTTPS POST with JSON bodies and +`Authorization: Bearer `, except the two file routes. + +| Route | Purpose | +| --- | --- | +| `POST /worker/v1/claim` | Take a job or a lookup. Held open up to 25 seconds when there is none. The worker sends its tags and capacity. | +| `POST /worker/v1/heartbeat` | Extend the lease, report progress. The answer says whether to cancel. | +| `POST /worker/v1/complete` | Report a result that is already uploaded. | +| `POST /worker/v1/fail` | Report a failure with an error class and whether it is worth retrying. | +| `PUT /worker/v1/upload/` | Send the result file (local disk storage). | +| `GET /worker/v1/source/` | Fetch the stored file a transcode job starts from. | +| `POST /worker/v1/probe` | Answer a link lookup. | + +Status `401` means the token is unknown or revoked. Status `409` means the +job is not (or no longer) leased to this worker, and the worker drops it. +The worker's identity always comes from its token, never from the request +body, and the storage key of a result is fixed by the core. diff --git a/go.mod b/go.mod index dfc9e3b..ac8127b 100644 --- a/go.mod +++ b/go.mod @@ -4,9 +4,13 @@ go 1.26.11 require ( github.com/BurntSushi/toml v1.6.0 + github.com/jackc/pgx/v5 v5.13.0 + github.com/johannesboyne/gofakes3 v1.2.0 + github.com/minio/minio-go/v7 v7.4.1 github.com/mymmrac/telego v1.13.0 github.com/nicksnyder/go-i18n/v2 v2.7.0 github.com/pressly/goose/v3 v3.30.1 + github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e golang.org/x/text v0.44.0 modernc.org/sqlite v1.62.0 ) @@ -15,27 +19,44 @@ require ( github.com/bytedance/gopkg v0.1.3 // indirect github.com/bytedance/sonic v1.15.5 // indirect github.com/bytedance/sonic/loader v0.5.3 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/dustin/go-humanize v1.1.0 // indirect github.com/goccy/go-json v0.12.0 // indirect github.com/google/uuid v1.6.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.3 // indirect github.com/klauspost/compress v1.20.4 // indirect - github.com/klauspost/cpuid/v2 v2.2.9 // indirect + github.com/klauspost/cpuid/v2 v2.4.0 // indirect + github.com/klauspost/crc32 v1.3.0 // indirect github.com/mattn/go-isatty v0.0.24 // indirect github.com/mfridman/interpolate v0.2.0 // indirect + github.com/minio/crc64nvme v1.1.1 // indirect + github.com/minio/md5-simd v1.1.2 // indirect github.com/molecule-man/go-brrr v1.3.1 // indirect github.com/ncruces/go-strftime v1.1.0 // indirect + github.com/philhofer/fwd v1.2.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/rs/xid v1.6.0 // indirect + github.com/ryszard/goskiplist v0.0.0-20150312221310-2dfbae5fcf46 // indirect github.com/sethvargo/go-retry v0.5.0 // indirect - github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e // indirect + github.com/tinylib/msgp v1.6.4 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasthttp v1.78.0 // indirect github.com/valyala/fastjson v1.6.10 // indirect + github.com/zeebo/xxh3 v1.1.0 // indirect + go.shabbyrobe.org/gocovmerge v0.0.0-20230507111327-fa4f82cfbf4d // indirect go.uber.org/multierr v1.11.0 // indirect + go.yaml.in/yaml/v3 v3.0.6 // indirect golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect + golang.org/x/crypto v0.58.0 // indirect + golang.org/x/net v0.62.0 // indirect golang.org/x/sync v0.25.0 // indirect golang.org/x/sys v0.50.0 // indirect + golang.org/x/tools v0.52.0 // indirect + gopkg.in/ini.v1 v1.67.3 // indirect modernc.org/libc v1.80.2 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.12.1 // indirect diff --git a/go.sum b/go.sum index c342f82..e57a01c 100644 --- a/go.sum +++ b/go.sum @@ -1,11 +1,41 @@ github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV/yY= +github.com/aws/aws-sdk-go-v2 v1.41.5/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 h1:eBMB84YGghSocM7PsjmmPffTa+1FBUeNvGvFou6V/4o= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8/go.mod h1:lyw7GFp3qENLh7kwzf7iMzAxDn+NzjXEAGjKS2UOKqI= +github.com/aws/aws-sdk-go-v2/credentials v1.17.67 h1:9KxtdcIA/5xPNQyZRgUSpYOE6j9Bc4+D7nZua0KGYOM= +github.com/aws/aws-sdk-go-v2/credentials v1.17.67/go.mod h1:p3C44m+cfnbv763s52gCqrjaqyPikj9Sg47kUVaNZQQ= +github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.75 h1:S61/E3N01oral6B3y9hZ2E1iFDqCZPPOBoBQretCnBI= +github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.75/go.mod h1:bDMQbkI1vJbNjnvJYpPTSNYBkI/VIv18ngWb/K84tkk= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 h1:Rgg6wvjjtX8bNHcvi9OnXWwcE0a2vGpbwmtICOsvcf4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21/go.mod h1:A/kJFst/nm//cyqonihbdpQZwiUhhzpqTsdbhDdRF9c= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 h1:PEgGVtPoB6NTpPrBgqSE5hE/o47Ij9qk/SEZFbUOe9A= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21/go.mod h1:p+hz+PRAYlY3zcpJhPwXlLC4C+kqn70WIHwnzAfs6ps= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22 h1:rWyie/PxDRIdhNf4DzRk0lvjVOqFJuNnO8WwaIRVxzQ= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22/go.mod h1:zd/JsJ4P7oGfUhXn1VyLqaRZwPmZwg44Jf2dS84Dm3Y= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7 h1:5EniKhLZe4xzL7a+fU3C2tfUN4nWIqlLesfrjkuPFTY= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7/go.mod h1:x0nZssQ3qZSnIcePWLvcoFisRXJzcTVvYpAAdYX8+GI= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 h1:JRaIgADQS/U6uXDqlPiefP32yXTda7Kqfx+LgspooZM= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13/go.mod h1:CEuVn5WqOMilYl+tbccq8+N2ieCy0gVn3OtRb0vBNNM= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21 h1:c31//R3xgIJMSC8S6hEVq+38DcvUlgFY0FM6mSI5oto= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21/go.mod h1:r6+pf23ouCB718FUxaqzZdbpYFyDtehyZcmP5KL9FkA= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 h1:ZlvrNcHSFFWURB8avufQq9gFsheUgjVD9536obIknfM= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21/go.mod h1:cv3TNhVrssKR0O/xxLJVRfd2oazSnZnkUeTf6ctUwfQ= +github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3 h1:HwxWTbTrIHm5qY+CAEur0s/figc3qwvLWsNkF4RPToo= +github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3/go.mod h1:uoA43SdFwacedBfSgfFSjjCvYe8aYBS7EnU5GZ/YKMM= +github.com/aws/smithy-go v1.24.2 h1:FzA3bu/nt/vDvmnkg+R8Xl46gmzEDam6mZ1hzmwXFng= +github.com/aws/smithy-go v1.24.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= github.com/bytedance/sonic v1.15.5 h1:gKWTBfYCIQpQHZ7LpwGf9Gj3N88ZN0G/GaB3EQhiGXE= github.com/bytedance/sonic v1.15.5/go.mod h1:nn7CoK5W+LKbl22XGJrXg6SwzaFAcVs89miqzkqDwOU= github.com/bytedance/sonic/loader v0.5.3 h1:ziVGAbXQtLoaot/M6YQxntGkekxz6B/DyuJVwnTbMAA= github.com/bytedance/sonic/loader v0.5.3/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cevatbarisyilmaz/ara v0.0.4 h1:SGH10hXpBJhhTlObuZzTuFn1rrdmjQImITXnZVPSodc= +github.com/cevatbarisyilmaz/ara v0.0.4/go.mod h1:BfFOxnUd6Mj6xmcvRxHN3Sr21Z1T3U2MYkYOmoQe4Ts= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -21,14 +51,33 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4= +github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= +github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= +github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/johannesboyne/gofakes3 v1.2.0 h1:I9VEzPWvvAUAGzDlhYFoZjF0AXMlkcEyZlmBwiI6Oms= +github.com/johannesboyne/gofakes3 v1.2.0/go.mod h1:UHhRZRod9rENGFrUWTYnQHZqlNgSmjOq8DaD/ATQYRM= github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI= github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= -github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY= -github.com/klauspost/cpuid/v2 v2.2.9/go.mod h1:rqkxqrZ1EhYM9G+hXH7YdowN5R5RGN6NK4QwQ3WMXF8= +github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= +github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= +github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM= +github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg= github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q= +github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI= +github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg= +github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= +github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= +github.com/minio/minio-go/v7 v7.4.1 h1:PtU/zIOfQRWZ+QydXAZysc+xZYHdG+BBR4Z6TUvy73w= +github.com/minio/minio-go/v7 v7.4.1/go.mod h1:nQnQi7zTfXR4lREtYXZQWqo5aw0Rqv+ZqCGrTORygRk= github.com/molecule-man/go-brrr v1.3.1 h1:EwaJUzRIlp/dFmIpzq4J17CA5Zi5OHo2vOGmu09hF1w= github.com/molecule-man/go-brrr v1.3.1/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4= github.com/mymmrac/telego v1.13.0 h1:1sz4F5bstBJYjZNPPJykYBT0HHIIKvPLvARZt45swM0= @@ -37,25 +86,38 @@ github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= github.com/nicksnyder/go-i18n/v2 v2.7.0 h1:oiVQUmuCeNggvm/fUVb6/R0aP82BDVphZnmVHwut+J0= github.com/nicksnyder/go-i18n/v2 v2.7.0/go.mod h1:ZMYiWg8ndQSGNk4zbzbyJjrrVjQjuQ8pERFrnBik+c8= +github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= +github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE= github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= +github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= +github.com/ryszard/goskiplist v0.0.0-20150312221310-2dfbae5fcf46 h1:GHRpF1pTW19a8tTFrMLUcfWwyC0pnifVo2ClaLq+hP8= +github.com/ryszard/goskiplist v0.0.0-20150312221310-2dfbae5fcf46/go.mod h1:uAQ5PCi+MFsC7HjREoAz1BU+Mq60+05gifQSsHSDG/8= github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= +github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= +github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ= +github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= @@ -64,6 +126,14 @@ github.com/valyala/fasthttp v1.78.0 h1:tKfLdx7cD8HZOTP1wc2OpbQMbgO1HP12J0y/XMdyW github.com/valyala/fasthttp v1.78.0/go.mod h1:8NXUY/ZXyjqEWN5cbfIdAAv+ES+5yfcl2EGNo872KzQ= github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADTh4= github.com/valyala/fastjson v1.6.10/go.mod h1:e6FubmQouUNP73jtMLmcbxS6ydWIpOfhz34TSfO3JaE= +github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ= +github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.etcd.io/bbolt v1.3.5 h1:XAzx9gjCb0Rxj7EoqcClPD1d5ZBxZJk0jbuoPHenBt0= +go.etcd.io/bbolt v1.3.5/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= +go.shabbyrobe.org/gocovmerge v0.0.0-20230507111327-fa4f82cfbf4d h1:Ns9kd1Rwzw7t0BR8XMphenji4SmIoNZPn8zhYmaVKP8= +go.shabbyrobe.org/gocovmerge v0.0.0-20230507111327-fa4f82cfbf4d/go.mod h1:92Uoe3l++MlthCm+koNi0tcUCX3anayogF0Pa/sp24k= go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= @@ -72,6 +142,8 @@ go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/arch v0.0.0-20210923205945-b76863e36670 h1:18EFjUmQOcUvxNYSkA6jO9VAiXCnxFY6NyDX0bHDmkU= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= @@ -85,6 +157,10 @@ golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/ini.v1 v1.67.3 h1:iM9Lhz5MRSGhHVGGwCuzG9KO8PoirCXj/m/qTmOJJQw= +gopkg.in/ini.v1 v1.67.3/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss= +gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce h1:xcEWjVhvbDy+nHP67nPDDpbYrY+ILlfndk4bRioVHaU= +gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b h1:WE5SLOURcNd8s6uPR/n4WV4weQxxYKi5OpEZkfNVvdE= diff --git a/internal/api/worker.go b/internal/api/worker.go new file mode 100644 index 0000000..b4b2ddb --- /dev/null +++ b/internal/api/worker.go @@ -0,0 +1,355 @@ +package api + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "encoding/json" + "errors" + "io" + "log/slog" + "net/http" + "sort" + "strconv" + "strings" + "time" + + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/probe" + "github.com/noderunners/dlbot/internal/sched" + "github.com/noderunners/dlbot/internal/storage" + "github.com/noderunners/dlbot/internal/workerproto" +) + +// WorkerAPI is the pull protocol for remote workers. Workers call in; the +// core never connects out to a worker, so workers need no inbound ports. +// +// POST /worker/v1/claim take a job or a probe task (long poll) +// POST /worker/v1/heartbeat extend the lease, report progress +// POST /worker/v1/complete report a stored result +// POST /worker/v1/fail report a failure +// PUT /worker/v1/upload/{job} send the result file (local storage) +// GET /worker/v1/source/{job} fetch a derive job's source file +// POST /worker/v1/probe answer a probe task +// +// Every call carries "Authorization: Bearer ". A token belongs to +// one worker, is stored as a hash, and can be revoked. It grants exactly +// these calls and only for the worker's own jobs. +type WorkerAPI struct { + Store *db.Store + Sched *sched.Scheduler + Storage storage.Storage + Broker *probe.Broker + Log *slog.Logger + // PresignTTL is how long presigned upload and source URLs are valid. + PresignTTL time.Duration + // MaxWait caps how long a claim is held open. + MaxWait time.Duration +} + +// NewWorkerToken returns a random bearer token and the hash to store. +func NewWorkerToken() (token, hash string) { + var raw [32]byte + if _, err := rand.Read(raw[:]); err != nil { + panic("api: no entropy: " + err.Error()) + } + token = "dlw_" + hex.EncodeToString(raw[:]) + return token, HashWorkerToken(token) +} + +// HashWorkerToken returns the stored form of a token. +func HashWorkerToken(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} + +// RegisterWorkerAPI adds the worker routes to the server. +func (s *Server) RegisterWorkerAPI(w *WorkerAPI) { + if w.Log == nil { + w.Log = s.log + } + if w.MaxWait <= 0 { + w.MaxWait = 25 * time.Second + } + if w.PresignTTL <= 0 { + w.PresignTTL = time.Hour + } + s.mux.HandleFunc("POST /worker/v1/claim", w.auth(w.claim)) + s.mux.HandleFunc("POST /worker/v1/heartbeat", w.auth(w.heartbeat)) + s.mux.HandleFunc("POST /worker/v1/complete", w.auth(w.complete)) + s.mux.HandleFunc("POST /worker/v1/fail", w.auth(w.fail)) + s.mux.HandleFunc("PUT /worker/v1/upload/{job}", w.auth(w.upload)) + s.mux.HandleFunc("GET /worker/v1/source/{job}", w.auth(w.source)) + s.mux.HandleFunc("POST /worker/v1/probe", w.auth(w.probeResult)) +} + +type workerHandler func(rw http.ResponseWriter, r *http.Request, wk *db.Worker) + +// auth resolves the bearer token to a worker. Unknown and revoked tokens +// get the same 401, so a revoked worker learns nothing more than "no". +func (a *WorkerAPI) auth(next workerHandler) http.HandlerFunc { + return func(rw http.ResponseWriter, r *http.Request) { + token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") + if !ok || token == "" { + writeError(rw, http.StatusUnauthorized, "missing bearer token") + return + } + hash := HashWorkerToken(strings.TrimSpace(token)) + wk, err := a.Store.WorkerByToken(r.Context(), hash) + if err != nil || wk.Revoked || subtle.ConstantTimeCompare([]byte(wk.TokenHash), []byte(hash)) != 1 { + writeError(rw, http.StatusUnauthorized, "invalid token") + return + } + next(rw, r, wk) + } +} + +func writeError(rw http.ResponseWriter, code int, msg string) { + rw.Header().Set("Content-Type", "application/json") + rw.WriteHeader(code) + _ = json.NewEncoder(rw).Encode(map[string]string{"error": msg}) +} + +func writeJSON(rw http.ResponseWriter, v any) { + rw.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(rw).Encode(v) +} + +func readJSON(r *http.Request, v any) error { + return json.NewDecoder(io.LimitReader(r.Body, 8<<20)).Decode(v) +} + +// normalizeTags lower-cases, de-duplicates and sorts tags. +func normalizeTags(tags []string) []string { + seen := map[string]bool{} + var out []string + for _, t := range tags { + t = strings.ToLower(strings.TrimSpace(t)) + if t != "" && !seen[t] && !strings.Contains(t, ",") { + seen[t] = true + out = append(out, t) + } + } + sort.Strings(out) + return out +} + +func (a *WorkerAPI) claim(rw http.ResponseWriter, r *http.Request, wk *db.Worker) { + var req workerproto.ClaimRequest + if err := readJSON(r, &req); err != nil { + writeError(rw, http.StatusBadRequest, "bad json") + return + } + // The identity comes from the token, never from the body. + req.WorkerID = wk.ID + req.Tags = normalizeTags(req.Tags) + ctx := r.Context() + if err := a.Store.TouchWorker(ctx, wk.ID, strings.Join(req.Tags, ","), req.Capacity, req.Version, db.NowMilli()); err != nil { + a.Log.Error("touch worker", "worker_id", wk.ID, "err", err) + } + a.Sched.Seen(wk.ID, req.Capacity) + resp := workerproto.ClaimResponse{Commands: a.Sched.TakeCommands(wk.ID)} + + // A draining worker finishes what it has and is given nothing new. + if wk.Draining { + writeJSON(rw, resp) + return + } + wait := time.Duration(req.WaitSeconds) * time.Second + if wait > a.MaxWait { + wait = a.MaxWait + } + deadline := time.Now().Add(wait) + for { + if req.ProbeOnly { + if a.Broker != nil { + resp.Probe = a.Broker.Take(req.Tags) + } + } else { + job, err := a.Sched.Claim(ctx, req) + if err != nil { + a.Log.Error("claim", "worker_id", wk.ID, "err", err) + writeError(rw, http.StatusInternalServerError, "claim failed") + return + } + if job != nil { + a.presign(ctx, job) + resp.Job = job + } + } + left := time.Until(deadline) + if resp.Job != nil || resp.Probe != nil || len(resp.Commands) > 0 || left <= 0 || ctx.Err() != nil { + writeJSON(rw, resp) + return + } + a.Sched.WaitWork(ctx, left) + } +} + +// presign adds direct storage URLs to a job when the backend can make +// them, so the file bytes go straight to storage and not through the core. +func (a *WorkerAPI) presign(ctx context.Context, job *workerproto.Job) { + ps, ok := a.Storage.(storage.Presigner) + if !ok { + return + } + if sw, ok := a.Storage.(interface{ Presigning() bool }); ok && !sw.Presigning() { + return + } + if u, err := ps.PresignPut(ctx, job.UploadKey, a.PresignTTL); err == nil { + job.UploadURL = u + } else { + a.Log.Warn("presign upload", "job_id", job.ID, "err", err) + } + if job.SourceKey != "" { + if u, err := ps.PresignGet(ctx, job.SourceKey, a.PresignTTL); err == nil { + job.SourceURL = u + } else { + a.Log.Warn("presign source", "job_id", job.ID, "err", err) + } + } +} + +// leaseStatus maps scheduler errors to HTTP: 409 tells a worker that the +// job is no longer its own and must be dropped. +func leaseStatus(rw http.ResponseWriter, err error) bool { + switch { + case err == nil: + return true + case errors.Is(err, sched.ErrLeaseLost), errors.Is(err, db.ErrNotFound): + writeError(rw, http.StatusConflict, "lease lost") + default: + writeError(rw, http.StatusInternalServerError, "internal error") + } + return false +} + +func (a *WorkerAPI) heartbeat(rw http.ResponseWriter, r *http.Request, wk *db.Worker) { + var req workerproto.HeartbeatRequest + if err := readJSON(r, &req); err != nil { + writeError(rw, http.StatusBadRequest, "bad json") + return + } + req.WorkerID = wk.ID + resp, err := a.Sched.Heartbeat(r.Context(), req) + if leaseStatus(rw, err) { + writeJSON(rw, resp) + } +} + +func (a *WorkerAPI) complete(rw http.ResponseWriter, r *http.Request, wk *db.Worker) { + var req workerproto.CompleteRequest + if err := readJSON(r, &req); err != nil { + writeError(rw, http.StatusBadRequest, "bad json") + return + } + req.WorkerID = wk.ID + // The storage key is fixed by the core. A worker cannot point a job at + // somebody else's file. + req.StorageKey = sched.UploadKey(req.JobID) + if _, err := a.Storage.Stat(r.Context(), req.StorageKey); err != nil { + writeError(rw, http.StatusUnprocessableEntity, "the result was not uploaded") + return + } + if leaseStatus(rw, a.Sched.Complete(r.Context(), req)) { + writeJSON(rw, map[string]bool{"ok": true}) + } +} + +func (a *WorkerAPI) fail(rw http.ResponseWriter, r *http.Request, wk *db.Worker) { + var req workerproto.FailRequest + if err := readJSON(r, &req); err != nil { + writeError(rw, http.StatusBadRequest, "bad json") + return + } + req.WorkerID = wk.ID + if len(req.Detail) > 2000 { + req.Detail = req.Detail[:2000] + } + if leaseStatus(rw, a.Sched.Fail(r.Context(), req)) { + writeJSON(rw, map[string]bool{"ok": true}) + } +} + +// ownsJob checks that a job is running and leased to this worker. +func (a *WorkerAPI) ownsJob(ctx context.Context, jobID string, wk *db.Worker) (*db.Job, bool) { + job, err := a.Store.GetJob(ctx, jobID) + if err != nil || job.Status != db.JobRunning || job.WorkerID != wk.ID { + return nil, false + } + return job, true +} + +// upload streams the result of a job into storage. It is used when the +// storage backend cannot hand out presigned URLs (local disk). +func (a *WorkerAPI) upload(rw http.ResponseWriter, r *http.Request, wk *db.Worker) { + job, ok := a.ownsJob(r.Context(), r.PathValue("job"), wk) + if !ok { + writeError(rw, http.StatusConflict, "lease lost") + return + } + body := io.Reader(r.Body) + if job.MaxSize > 0 { + // One byte over the cap is enough to know the file is too large. + body = io.LimitReader(r.Body, job.MaxSize+1) + } + counted := &countingReader{r: body} + if err := a.Storage.Put(r.Context(), sched.UploadKey(job.ID), counted, r.ContentLength); err != nil { + a.Log.Error("store upload", "job_id", job.ID, "worker_id", wk.ID, "err", err) + writeError(rw, http.StatusInternalServerError, "upload failed") + return + } + if job.MaxSize > 0 && counted.n > job.MaxSize { + _ = a.Storage.Delete(context.WithoutCancel(r.Context()), sched.UploadKey(job.ID)) + writeError(rw, http.StatusRequestEntityTooLarge, "file is over the job's size cap") + return + } + writeJSON(rw, map[string]int64{"size": counted.n}) +} + +// source streams the stored file a derive job transcodes from. +func (a *WorkerAPI) source(rw http.ResponseWriter, r *http.Request, wk *db.Worker) { + job, ok := a.ownsJob(r.Context(), r.PathValue("job"), wk) + if !ok || job.SourceKey == "" { + writeError(rw, http.StatusConflict, "lease lost") + return + } + rc, size, err := a.Storage.Open(r.Context(), job.SourceKey) + if err != nil { + writeError(rw, http.StatusNotFound, "source is gone") + return + } + defer rc.Close() + rw.Header().Set("Content-Type", "application/octet-stream") + if size > 0 { + rw.Header().Set("Content-Length", strconv.FormatInt(size, 10)) + } + _, _ = io.Copy(rw, rc) +} + +func (a *WorkerAPI) probeResult(rw http.ResponseWriter, r *http.Request, wk *db.Worker) { + var res workerproto.ProbeResult + if err := readJSON(r, &res); err != nil { + writeError(rw, http.StatusBadRequest, "bad json") + return + } + res.WorkerID = wk.ID + if a.Broker == nil || a.Broker.Resolve(&res) != nil { + writeError(rw, http.StatusGone, "nobody waits for this probe anymore") + return + } + writeJSON(rw, map[string]bool{"ok": true}) +} + +type countingReader struct { + r io.Reader + n int64 +} + +func (c *countingReader) Read(p []byte) (int, error) { + n, err := c.r.Read(p) + c.n += int64(n) + return n, err +} diff --git a/internal/app/admin.go b/internal/app/admin.go new file mode 100644 index 0000000..248f359 --- /dev/null +++ b/internal/app/admin.go @@ -0,0 +1,88 @@ +package app + +import ( + "context" + "errors" + "fmt" + "io" + "regexp" + "time" + + "github.com/noderunners/dlbot/internal/api" + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/db" +) + +var workerNameRe = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,39}$`) + +// WorkerAdmin runs the "core worker ..." subcommands. They only need the +// database, so they work while the core is running. +// +// core worker add create a worker and print its token once +// core worker revoke make its token useless +// core worker list show all workers +func WorkerAdmin(ctx context.Context, cfg config.Config, args []string, out io.Writer) error { + usage := errors.New("usage: core worker add | revoke | list") + if len(args) == 0 { + return usage + } + d, err := db.Open(ctx, cfg.Database.Driver, cfg.Database.DSN) + if err != nil { + return err + } + defer d.Close() + if err := d.Migrate(ctx); err != nil { + return err + } + store := d.Store() + switch { + case args[0] == "add" && len(args) == 2: + name := args[1] + if !workerNameRe.MatchString(name) { + return errors.New("worker names are lowercase letters, digits, dot, dash and underscore, at most 40 characters") + } + token, hash := api.NewWorkerToken() + if err := store.UpsertWorker(ctx, name, hash); err != nil { + return err + } + fmt.Fprintf(out, "Worker %q is registered. Its token is shown once, store it now:\n\n WORKER_TOKEN=%s\n\n", name, token) + fmt.Fprintln(out, "Adding a worker that already exists replaces its token.") + return nil + case args[0] == "revoke" && len(args) == 2: + ok, err := store.RevokeWorker(ctx, args[1]) + if err != nil { + return err + } + if !ok { + return fmt.Errorf("no worker named %q", args[1]) + } + fmt.Fprintf(out, "Worker %q is revoked. Its running jobs return to the queue when their lease ends.\n", args[1]) + return nil + case args[0] == "list" && len(args) == 1: + ws, err := store.ListWorkers(ctx) + if err != nil { + return err + } + if len(ws) == 0 { + fmt.Fprintln(out, "No workers are registered.") + return nil + } + fmt.Fprintf(out, "%-24s %-10s %-9s %-8s %-14s %s\n", "NAME", "STATE", "CAPACITY", "SEEN", "YT-DLP", "TAGS") + for _, w := range ws { + state := "active" + switch { + case w.Revoked: + state = "revoked" + case w.Draining: + state = "draining" + } + seen := "never" + if w.LastSeenAt > 0 { + seen = time.Since(time.UnixMilli(w.LastSeenAt)).Round(time.Second).String() + } + fmt.Fprintf(out, "%-24s %-10s %-9d %-8s %-14s %s\n", w.ID, state, w.Capacity, seen, w.Version, w.Tags) + } + return nil + } + return usage +} diff --git a/internal/app/app.go b/internal/app/app.go index 3403414..3d595f2 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -22,6 +22,8 @@ import ( "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" @@ -53,6 +55,7 @@ type App struct { Sched *sched.Scheduler Billing *billing.Billing Cache *cache.Cache + Broker *probe.Broker Service *service.Service Bot *bot.Bot HTTP *api.Server @@ -113,10 +116,34 @@ func Redactor(secrets ...string) func(groups []string, a slog.Attr) slog.Attr { // Secrets lists the configured values that must never appear in logs. func Secrets(cfg config.Config) []string { - return []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 @@ -147,8 +174,18 @@ func New(ctx context.Context, opts Options) (*App, error) { 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: storage backend %q is not available in this version", cfg.Storage.Backend)) + return fail(fmt.Errorf("app: unknown storage backend %q", cfg.Storage.Backend)) } tr, err := i18n.Load(locales.FS, log) @@ -193,7 +230,18 @@ func New(ctx context.Context, opts Options) (*App, error) { 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) + // 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, @@ -218,10 +266,14 @@ func New(ctx context.Context, opts Options) (*App, error) { 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(), diff --git a/internal/app/app_test.go b/internal/app/app_test.go index a454a22..3355890 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -17,6 +17,7 @@ import ( "github.com/noderunners/dlbot/internal/bot" "github.com/noderunners/dlbot/internal/config" "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/db/dbtest" "github.com/noderunners/dlbot/internal/ffmpeg" "github.com/noderunners/dlbot/internal/storage" "github.com/noderunners/dlbot/internal/tg/fakeserver" @@ -73,7 +74,7 @@ func startWithRunner(t *testing.T, runner ytdlp.Runner, mut func(*config.Config) cfg.Telegram.Token = fakeserver.Token cfg.Telegram.APIURL = srv.URL() cfg.HTTP.Listen = "127.0.0.1:0" - cfg.Database.DSN = filepath.Join(dir, "bot.db") + cfg.Database.Driver, cfg.Database.DSN = dbtest.NewDSN(t) cfg.Storage.LocalDir = filepath.Join(dir, "files") cfg.Worker.TempDir = filepath.Join(dir, "tmp") cfg.Queue.Lease = config.Duration(2 * time.Second) diff --git a/internal/app/money_test.go b/internal/app/money_test.go index 27723c7..5673fae 100644 --- a/internal/app/money_test.go +++ b/internal/app/money_test.go @@ -132,7 +132,7 @@ func (h *moneyHarness) booksBalance() { func (h *moneyHarness) deliveriesOf(user int64, status string) []*db.Delivery { h.t.Helper() - rows, err := h.app.DB.SQL.Query(`SELECT id FROM deliveries WHERE user_id = ? AND status = ? ORDER BY id`, user, status) + rows, err := h.app.DB.SQL.Query(h.app.DB.Rebind(`SELECT id FROM deliveries WHERE user_id = ? AND status = ? ORDER BY id`), user, status) if err != nil { h.t.Fatal(err) } diff --git a/internal/app/workers_test.go b/internal/app/workers_test.go new file mode 100644 index 0000000..4ada076 --- /dev/null +++ b/internal/app/workers_test.go @@ -0,0 +1,607 @@ +package app_test + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/johannesboyne/gofakes3" + "github.com/johannesboyne/gofakes3/backend/s3mem" + + "github.com/noderunners/dlbot/internal/app" + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/storage" + "github.com/noderunners/dlbot/internal/tg/fakeserver" + "github.com/noderunners/dlbot/internal/worker" + "github.com/noderunners/dlbot/internal/workerproto" + "github.com/noderunners/dlbot/internal/ytdlp" + "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" +) + +const ( + tokenW1 = "dlw_test_token_for_worker_one_0001" + tokenW2 = "dlw_test_token_for_worker_two_0002" +) + +// fleet is a core without an embedded worker plus remote workers that +// talk to it over real HTTP, the way separate machines would. +type fleet struct { + *harness + base string +} + +func startFleet(t *testing.T, mut func(*config.Config)) *fleet { + t.Helper() + addr := freePort(t) + h := start(t, nil, func(c *config.Config) { + c.HTTP.Listen = addr + c.Worker.Embedded = false + c.WorkerTokens = []string{"w1:" + tokenW1, "w2:" + tokenW2} + c.Worker.ProbeTimeout = config.Duration(3 * time.Second) + if mut != nil { + mut(c) + } + }) + return &fleet{harness: h, base: "http://" + addr} +} + +// remote is one running remote worker. +type remote struct { + fake *ytdlptest.Fake + commands chan string + cancel context.CancelFunc + done chan struct{} + crashed *atomic.Bool +} + +// crashable drops every call once the worker "died", which is what the +// core sees when a machine loses power: silence. +type crashable struct { + *worker.HTTPCoordinator + dead *atomic.Bool +} + +var errDead = errors.New("worker is dead") + +func (c *crashable) ClaimAny(ctx context.Context, r workerproto.ClaimRequest) (*workerproto.ClaimResponse, error) { + if c.dead.Load() { + return nil, errDead + } + return c.HTTPCoordinator.ClaimAny(ctx, r) +} + +func (c *crashable) Claim(ctx context.Context, r workerproto.ClaimRequest) (*workerproto.Job, error) { + if c.dead.Load() { + return nil, errDead + } + return c.HTTPCoordinator.Claim(ctx, r) +} + +func (c *crashable) Heartbeat(ctx context.Context, r workerproto.HeartbeatRequest) (workerproto.HeartbeatResponse, error) { + if c.dead.Load() { + return workerproto.HeartbeatResponse{}, errDead + } + return c.HTTPCoordinator.Heartbeat(ctx, r) +} + +func (c *crashable) Complete(ctx context.Context, r workerproto.CompleteRequest) error { + if c.dead.Load() { + return errDead + } + return c.HTTPCoordinator.Complete(ctx, r) +} + +func (c *crashable) Fail(ctx context.Context, r workerproto.FailRequest) error { + if c.dead.Load() { + return errDead + } + return c.HTTPCoordinator.Fail(ctx, r) +} + +func (c *crashable) ProbeResult(ctx context.Context, r workerproto.ProbeResult) error { + if c.dead.Load() { + return errDead + } + return c.HTTPCoordinator.ProbeResult(ctx, r) +} + +func (f *fleet) worker(token string, tags []string, fake *ytdlptest.Fake) *remote { + f.t.Helper() + if fake == nil { + fake = &ytdlptest.Fake{} + } + r := &remote{fake: fake, commands: make(chan string, 8), done: make(chan struct{}), crashed: &atomic.Bool{}} + coord := &crashable{HTTPCoordinator: worker.NewHTTPCoordinator(f.base, token), dead: r.crashed} + w := worker.New(worker.Config{ + ID: "remote", Tags: tags, Concurrency: 1, TempDir: filepath.Join(f.t.TempDir(), "tmp"), + Heartbeat: 40 * time.Millisecond, ClaimWait: time.Second, ProbeSlots: 1, + Version: func() string { return "2026.01.01" }, + OnCommand: func(c string) { r.commands <- c }, + }, coord, fake, slog.New(slog.NewTextHandler(io.Discard, nil))) + w.SetTranscoder(&fakeTranscoder{}) + ctx, cancel := context.WithCancel(context.Background()) + r.cancel = cancel + go func() { + defer close(r.done) + w.Run(ctx) + }() + f.t.Cleanup(r.stop) + return r +} + +// stop shuts the worker down cleanly: it hands its job back. +func (r *remote) stop() { + r.cancel() + select { + case <-r.done: + case <-time.After(10 * time.Second): + } +} + +// kill simulates a machine that dies: no goodbye, no more heartbeats. +func (r *remote) kill() { + r.crashed.Store(true) + r.cancel() +} + +func (f *fleet) jobOf(status string) *db.Job { + f.t.Helper() + js := f.waitJobs(status, 1) + return js[0] +} + +func (f *fleet) post(path, token string, body any) (int, string) { + f.t.Helper() + data, _ := json.Marshal(body) + req, _ := http.NewRequest(http.MethodPost, f.base+path, bytes.NewReader(data)) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + req.Header.Set("Content-Type", "application/json") + resp, err := http.DefaultClient.Do(req) + if err != nil { + f.t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return resp.StatusCode, string(b) +} + +func TestRemoteWorkerDoesEverythingOverHTTP(t *testing.T) { + f := startFleet(t, nil) + w1 := f.worker(tokenW1, []string{"eu"}, &ytdlptest.Fake{FileSize: 5000}) + + // Even the card depends on the worker: the core has no yt-dlp here. + card := f.card(alice, alice, link) + if n := len(w1.fake.Probes()); n != 1 { + t.Fatalf("the worker ran %d probes, want 1", n) + } + seq := f.press(alice, alice, card, "dl:") + video := f.wait(seq, "sendVideo", nil) + if video.Files["video"].Size != 5000 { + t.Fatalf("the file that went through the worker upload is wrong: %+v", video.Files) + } + f.wait(seq, edits, textHas("Done")) + job := f.jobOf(db.JobDone) + if job.WorkerID != "w1" || job.Attempts != 1 { + t.Fatalf("job worker=%q attempts=%d", job.WorkerID, job.Attempts) + } + // The core recorded what the worker advertised. + wk, err := f.app.Store.GetWorker(context.Background(), "w1") + if err != nil || wk.Tags != "eu" || wk.Capacity != 1 || wk.Version != "2026.01.01" || wk.LastSeenAt == 0 { + t.Fatalf("worker row = %+v, %v", wk, err) + } + if got := f.app.Sched.Capacity(); got != 1 { + t.Fatalf("fleet capacity = %d", got) + } +} + +// Acceptance: kill a worker mid-job, the job is re-queued and finished by +// the other worker. +func TestKilledWorkerJobIsRequeuedAndFinishedByTheOther(t *testing.T) { + f := startFleet(t, nil) + stuck := make(chan struct{}) + defer close(stuck) + w1 := f.worker(tokenW1, nil, &ytdlptest.Fake{Block: stuck}) + + card := f.card(alice, alice, link) + seq := f.press(alice, alice, card, "dl:") + running := f.jobOf(db.JobRunning) + if running.WorkerID != "w1" { + t.Fatalf("the job should be on w1, is on %q", running.WorkerID) + } + f.wait(seq, edits, textHas("Downloading")) + + // A second worker comes online, and the first one dies mid-download. + w2 := f.worker(tokenW2, nil, &ytdlptest.Fake{FileSize: 7777}) + w1.kill() + + // Nobody tells the core. It notices the missing heartbeats, puts the + // job back in the queue, and the surviving worker finishes it. + video := f.wait(seq, "sendVideo", nil) + if video.Files["video"].Size != 7777 { + t.Fatalf("the delivered file did not come from the second worker: %+v", video.Files) + } + f.wait(seq, edits, textHas("Done")) + done := f.jobOf(db.JobDone) + if done.ID != running.ID || done.WorkerID != "w2" || done.Attempts != 2 { + t.Fatalf("job id=%s worker=%q attempts=%d, want the same job finished by w2 on attempt 2", + done.ID, done.WorkerID, done.Attempts) + } + if n := len(w2.fake.Downloads()); n != 1 { + t.Fatalf("w2 downloads = %d", n) + } + // The requester got the file exactly once. + if n := len(f.srv.Calls("sendVideo")); n != 1 { + t.Fatalf("sendVideo calls = %d, want 1", n) + } + // The dead worker coming back with a late report is turned away. + code, _ := f.post("/worker/v1/complete", tokenW1, workerproto.CompleteRequest{JobID: done.ID}) + if code != http.StatusConflict && code != http.StatusUnprocessableEntity { + t.Fatalf("late complete from the dead worker answered %d", code) + } +} + +func TestCleanWorkerShutdownHandsTheJobOverAtOnce(t *testing.T) { + f := startFleet(t, func(c *config.Config) { c.Queue.Lease = config.Duration(time.Hour) }) + stuck := make(chan struct{}) + defer close(stuck) + w1 := f.worker(tokenW1, nil, &ytdlptest.Fake{Block: stuck}) + card := f.card(alice, alice, link) + seq := f.press(alice, alice, card, "dl:") + f.jobOf(db.JobRunning) + + f.worker(tokenW2, nil, nil) + w1.stop() // SIGTERM, not a crash + // With a one hour lease only an explicit hand-back explains this. + f.wait(seq, "sendVideo", nil) + if done := f.jobOf(db.JobDone); done.WorkerID != "w2" || done.Attempts != 1 { + t.Fatalf("worker=%q attempts=%d, want w2 with the attempt refunded", done.WorkerID, done.Attempts) + } +} + +func TestJobsForTaggedSitesOnlyGoToWorkersWithTheTag(t *testing.T) { + f := startFleet(t, func(c *config.Config) { + c.SiteTags = map[string][]string{"example.com": {"residential"}} + c.Worker.ProbeTimeout = config.Duration(600 * time.Millisecond) + }) + plain := f.worker(tokenW1, []string{"datacenter"}, nil) + + // The only worker lacks the tag: not even the lookup is given to it. + seq := f.srv.Seq() + f.srv.PushMessage(alice, alice, link) + f.wait(seq, "editMessageText", textHas("took too long")) + if n := len(plain.fake.Probes()); n != 0 { + t.Fatalf("a worker without the tag ran %d probes", n) + } + + residential := f.worker(tokenW2, []string{"residential", "eu"}, nil) + card := f.card(bob, bob, "https://www.example.com/other") + seq = f.press(bob, bob, card, "dl:") + f.wait(seq, "sendVideo", nil) + job := f.jobOf(db.JobDone) + if job.WorkerID != "w2" || job.RequiredTags != "residential" { + t.Fatalf("job worker=%q required_tags=%q", job.WorkerID, job.RequiredTags) + } + if len(plain.fake.Downloads()) != 0 || len(residential.fake.Downloads()) != 1 { + t.Fatalf("downloads plain=%d residential=%d", len(plain.fake.Downloads()), len(residential.fake.Downloads())) + } + // A site without a rule can use any worker. + if got := f.cfg.RequiredTags("other.org"); got != "" { + t.Fatalf("RequiredTags(other.org) = %q", got) + } +} + +func TestDrainAndWorkersCommands(t *testing.T) { + f := startFleet(t, func(c *config.Config) { c.Owners = []int64{alice} }) + w1 := f.worker(tokenW1, []string{"eu"}, nil) + w2 := f.worker(tokenW2, nil, nil) + f.card(bob, bob, link) // makes sure both workers have checked in + + // Only the owner may drain. + seq := f.srv.Seq() + f.srv.PushMessage(bob, bob, "/drain w1") + f.never(seq, "sendMessage", textHas("draining")) + + seq = f.srv.Seq() + f.srv.PushMessage(alice, alice, "/drain w1") + f.wait(seq, "sendMessage", textHas("is draining")) + time.Sleep(1200 * time.Millisecond) // let w1's open claim run out + + for i := 0; i < 3; i++ { + card := f.card(bob, bob, fmt.Sprintf("https://example.com/d%d", i)) + seq := f.press(bob, bob, card, "dl:") + f.wait(seq, edits, textHas("Done")) + } + if n := len(w1.fake.Downloads()); n != 0 { + t.Fatalf("a draining worker took %d jobs", n) + } + if n := len(w2.fake.Downloads()); n != 3 { + t.Fatalf("w2 took %d jobs, want 3", n) + } + + seq = f.srv.Seq() + f.srv.PushMessage(alice, alice, "/workers") + list := f.wait(seq, "sendMessage", textHas("Workers")) + for _, want := range []string{"w1 · draining", "w2 · active", "tags: eu", "yt-dlp 2026.01.01", "2 remote workers registered"} { + if !strings.Contains(list.Text(), want) { + t.Errorf("/workers lacks %q:\n%s", want, list.Text()) + } + } + + seq = f.srv.Seq() + f.srv.PushMessage(alice, alice, "/drain w1 off") + f.wait(seq, "sendMessage", textHas("takes jobs again")) + seq = f.srv.Seq() + f.srv.PushMessage(alice, alice, "/drain nobody") + f.wait(seq, "sendMessage", textHas("no worker named")) + + // /ytdlp update reaches the workers with their next claim. + seq = f.srv.Seq() + f.srv.PushMessage(alice, alice, "/ytdlp update") + f.wait(seq, "sendMessage", textHas("Asked 2 workers")) + for _, w := range []*remote{w1, w2} { + select { + case cmd := <-w.commands: + if cmd != workerproto.CommandUpdateYtDlp { + t.Fatalf("command = %q", cmd) + } + case <-time.After(5 * time.Second): + t.Fatal("a worker never got the update command") + } + } +} + +func TestWorkerAPIAuthAndOwnership(t *testing.T) { + f := startFleet(t, nil) + stuck := make(chan struct{}) + defer close(stuck) + f.worker(tokenW1, nil, &ytdlptest.Fake{Block: stuck}) + card := f.card(alice, alice, link) + f.press(alice, alice, card, "dl:") + job := f.jobOf(db.JobRunning) // owned by w1 + + claim := workerproto.ClaimRequest{Capacity: 1} + for name, token := range map[string]string{"no token": "", "unknown token": "dlw_nope", "garbage": "x y z"} { + if code, _ := f.post("/worker/v1/claim", token, claim); code != http.StatusUnauthorized { + t.Errorf("%s: claim answered %d, want 401", name, code) + } + } + // A worker cannot act on another worker's job, whatever ID it sends. + hb := workerproto.HeartbeatRequest{WorkerID: "w1", JobID: job.ID} + if code, _ := f.post("/worker/v1/heartbeat", tokenW2, hb); code != http.StatusConflict { + t.Errorf("heartbeat for a foreign job answered %d, want 409", code) + } + if code, _ := f.post("/worker/v1/fail", tokenW2, workerproto.FailRequest{WorkerID: "w1", JobID: job.ID, Code: "unknown"}); code != http.StatusConflict { + t.Errorf("fail for a foreign job answered %d, want 409", code) + } + put := func(token, jobID string, body []byte) int { + req, _ := http.NewRequest(http.MethodPut, f.base+"/worker/v1/upload/"+jobID, bytes.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+token) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + return resp.StatusCode + } + if code := put(tokenW2, job.ID, []byte("stolen")); code != http.StatusConflict { + t.Errorf("upload to a foreign job answered %d, want 409", code) + } + // Completing without an upload is refused: the core checks storage. + if code, _ := f.post("/worker/v1/complete", tokenW1, workerproto.CompleteRequest{JobID: job.ID, StorageKey: "jobs/other/media"}); code != http.StatusUnprocessableEntity { + t.Errorf("complete without a file answered %d, want 422", code) + } + // The owner of the job can upload, but not past the job's size cap. + if code := put(tokenW1, job.ID, []byte("fine")); code != http.StatusOK { + t.Errorf("upload by the owner answered %d", code) + } + big := make([]byte, int(job.MaxSize)+10) + if code := put(tokenW1, job.ID, big); code != http.StatusRequestEntityTooLarge { + t.Errorf("oversized upload answered %d, want 413", code) + } + if n := f.storedFiles(); n != 0 { + t.Errorf("an oversized upload left %d files behind", n) + } + if got := f.jobOf(db.JobRunning); got.WorkerID != "w1" { + t.Fatalf("the job changed hands: %+v", got) + } + + // Revoking a token locks the worker out at once. + if ok, err := f.app.Store.RevokeWorker(context.Background(), "w2"); err != nil || !ok { + t.Fatal(err) + } + if code, _ := f.post("/worker/v1/claim", tokenW2, claim); code != http.StatusUnauthorized { + t.Errorf("a revoked worker's claim answered %d, want 401", code) + } + if code, _ := f.post("/worker/v1/probe", tokenW1, workerproto.ProbeResult{ID: "nope"}); code != http.StatusGone { + t.Errorf("an answer to an unknown probe answered %d, want 410", code) + } +} + +func TestWorkerAdminCLI(t *testing.T) { + f := startFleet(t, nil) + ctx := context.Background() + var out bytes.Buffer + if err := app.WorkerAdmin(ctx, f.cfg, []string{"add", "eu-3"}, &out); err != nil { + t.Fatal(err) + } + i := strings.Index(out.String(), "WORKER_TOKEN=") + if i < 0 { + t.Fatalf("no token in output: %s", out.String()) + } + token := strings.Fields(out.String()[i+len("WORKER_TOKEN="):])[0] + if !strings.HasPrefix(token, "dlw_") || len(token) < 40 { + t.Fatalf("token = %q", token) + } + // Only the hash is stored. + wk, err := f.app.Store.GetWorker(ctx, "eu-3") + if err != nil || wk.TokenHash == token || strings.Contains(wk.TokenHash, "dlw_") { + t.Fatalf("stored worker = %+v, %v", wk, err) + } + claim := workerproto.ClaimRequest{Capacity: 1} + if code, _ := f.post("/worker/v1/claim", token, claim); code != http.StatusOK { + t.Fatalf("the new token was not accepted: %d", code) + } + + out.Reset() + if err := app.WorkerAdmin(ctx, f.cfg, []string{"list"}, &out); err != nil { + t.Fatal(err) + } + for _, want := range []string{"eu-3", "w1", "w2", "active"} { + if !strings.Contains(out.String(), want) { + t.Errorf("list lacks %q:\n%s", want, out.String()) + } + } + if err := app.WorkerAdmin(ctx, f.cfg, []string{"revoke", "eu-3"}, &out); err != nil { + t.Fatal(err) + } + if code, _ := f.post("/worker/v1/claim", token, claim); code != http.StatusUnauthorized { + t.Fatalf("a revoked token still works: %d", code) + } + // Adding the worker again issues a new token and lifts the revocation. + out.Reset() + if err := app.WorkerAdmin(ctx, f.cfg, []string{"add", "eu-3"}, &out); err != nil { + t.Fatal(err) + } + i = strings.Index(out.String(), "WORKER_TOKEN=") + token2 := strings.Fields(out.String()[i+len("WORKER_TOKEN="):])[0] + if token2 == token { + t.Fatal("re-adding must issue a new token") + } + if code, _ := f.post("/worker/v1/claim", token2, claim); code != http.StatusOK { + t.Fatalf("the re-issued token was not accepted: %d", code) + } + if code, _ := f.post("/worker/v1/claim", token, claim); code != http.StatusUnauthorized { + t.Fatal("the old token must stay dead") + } + for _, bad := range [][]string{{}, {"add"}, {"add", "Bad Name"}, {"revoke", "ghost"}, {"explode"}} { + if err := app.WorkerAdmin(ctx, f.cfg, bad, io.Discard); err == nil { + t.Errorf("WorkerAdmin(%v) should fail", bad) + } + } +} + +func TestDeriveOverHTTPFetchesTheSourceFromTheCore(t *testing.T) { + hd := ytdlptest.DefaultInfo(link) + hd.Formats = append(hd.Formats, ytdlp.Format{FormatID: "v1080", Ext: "mp4", VCodec: "avc1", ACodec: "none", Height: 1080, Filesize: 20 << 20}) + f := startFleet(t, nil) + w1 := f.worker(tokenW1, nil, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{link: hd}}) + f.fetch(alice, link) + + card := f.card(bob, bob, link) + seq := f.press(bob, bob, card, "dl:"+strings.Split(card.Buttons()[0].Data, ":")[1]+":480") + video := f.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == bob }) + if video.Files["video"].Size != 500 || video.Params["height"] != "480" { + t.Fatalf("derived video = %+v %+v", video.Params, video.Files) + } + if n := len(w1.fake.Downloads()); n != 1 { + t.Fatalf("yt-dlp ran %d times, the 480p file should be transcoded from the stored copy", n) + } +} + +func TestManyJobsAcrossTwoWorkersEachRunOnce(t *testing.T) { + f := startFleet(t, func(c *config.Config) { + c.Limits.Free.ActiveJobs = 50 + c.Limits.Free.DailyDownloads = 100 + c.Queue.FreeMaxLen = 100 + c.Rate.UserPerMinute = 0 + }) + w1 := f.worker(tokenW1, nil, &ytdlptest.Fake{Delay: 20 * time.Millisecond}) + w2 := f.worker(tokenW2, nil, &ytdlptest.Fake{Delay: 20 * time.Millisecond}) + const n = 12 + var wg sync.WaitGroup + for i := 0; i < n; i++ { + card := f.card(alice, alice, fmt.Sprintf("https://example.com/many%d", i)) + wg.Add(1) + go func() { + defer wg.Done() + f.press(alice, alice, card, "dl:") + }() + } + wg.Wait() + f.waitJobs(db.JobDone, n) + a, b := len(w1.fake.Downloads()), len(w2.fake.Downloads()) + if a+b != n || a == 0 || b == 0 { + t.Fatalf("downloads w1=%d w2=%d, want %d in total, shared by both", a, b, n) + } + if got := len(f.srv.Calls("sendVideo")); got != n { + t.Fatalf("sendVideo calls = %d, want %d", got, n) + } + _ = os.Getenv // keep the import for the opt-in tests below +} + +// fakeS3Server starts an in-memory S3 with one bucket and returns its URL. +func fakeS3Server(t *testing.T, bucket string) string { + t.Helper() + backend := s3mem.New() + if err := backend.CreateBucket(bucket); err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(gofakes3.New(backend).Server()) + t.Cleanup(srv.Close) + return srv.URL +} + +func TestS3StorageWithPresignedWorkerUploads(t *testing.T) { + endpoint := fakeS3Server(t, "dlbot") + f := startFleet(t, func(c *config.Config) { + c.Storage.Backend = "s3" + c.Storage.S3 = config.S3{ + Endpoint: endpoint, Bucket: "dlbot", AccessKey: "key", SecretKey: "secret-secret", Region: "us-east-1", + PathStyle: true, Presign: true, Prefix: "bot1", + } + }) + if _, ok := f.app.Storage.(*storage.S3); !ok { + t.Fatalf("storage backend is %T, want S3", f.app.Storage) + } + hd := ytdlptest.DefaultInfo(link) + hd.Formats = append(hd.Formats, ytdlp.Format{FormatID: "v1080", Ext: "mp4", VCodec: "avc1", ACodec: "none", Height: 1080, Filesize: 20 << 20}) + w1 := f.worker(tokenW1, nil, &ytdlptest.Fake{FileSize: 6000, Infos: map[string]*ytdlp.Info{link: hd}}) + + // The worker uploads straight to the bucket; the core reads it from + // there and streams it to Telegram. + video := f.fetch(alice, link) + if video.Files["video"].Size != 6000 { + t.Fatalf("file delivered from S3 = %+v", video.Files) + } + job := f.jobOf(db.JobDone) + obj, err := f.app.Storage.Stat(context.Background(), job.StorageKey) + if err != nil || obj.Size != 6000 { + t.Fatalf("object in the bucket = %+v, %v", obj, err) + } + // The core's own upload endpoint was not involved. + if n := f.storedFiles(); n != 1 { + t.Fatalf("objects in the bucket = %d, want the cached copy", n) + } + + // A cache hit is served from S3 metadata, and a derive job fetches its + // source from the bucket by presigned URL. + again := f.fetch(bob, link) + if uploaded(again, "video") { + t.Fatal("the second request should be a cache hit") + } + card := f.card(carol, carol, link) + seq := f.press(carol, carol, card, "dl:"+strings.Split(card.Buttons()[0].Data, ":")[1]+":480") + derived := f.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == carol }) + if derived.Files["video"].Size != 500 { + t.Fatalf("derived file = %+v", derived.Files) + } + if n := len(w1.fake.Downloads()); n != 1 { + t.Fatalf("downloads = %d, want 1", n) + } +} diff --git a/internal/billing/billing_test.go b/internal/billing/billing_test.go index 9b19f3c..ff8ce4a 100644 --- a/internal/billing/billing_test.go +++ b/internal/billing/billing_test.go @@ -609,7 +609,7 @@ func TestLedgerRules(t *testing.T) { r.booksBalance() // The check catches a balance that was changed behind the ledger. - if _, err := r.sqldb.SQL.ExecContext(ctx, `UPDATE wallets SET balance = balance + 1 WHERE id = ?`, w.ID); err != nil { + if _, err := r.sqldb.SQL.ExecContext(ctx, r.sqldb.Rebind(`UPDATE wallets SET balance = balance + 1 WHERE id = ?`), w.ID); err != nil { t.Fatal(err) } bad, err := r.store.VerifyWallets(ctx) diff --git a/internal/bot/bot.go b/internal/bot/bot.go index a9c30b1..686fca8 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -72,6 +72,9 @@ type Bot struct { statuses map[string]*statusState // by delivery ID sending map[string]bool // jobs being delivered right now pumping map[int64]bool // users whose next playlist item is being started + // cancelledAt is when each user last sent /cancel. A playlist item + // that was already being looked up at that moment must not start. + cancelledAt map[int64]time.Time // Tunables, shortened in tests. reconcileEvery time.Duration @@ -118,6 +121,7 @@ func New(ctx context.Context, d Deps) (*Bot, error) { statuses: map[string]*statusState{}, sending: map[string]bool{}, pumping: map[int64]bool{}, + cancelledAt: map[int64]time.Time{}, reconcileEvery: 5 * time.Second, statusMinGap: 3 * time.Second, invoiceGrace: 5 * time.Second, diff --git a/internal/bot/commands.go b/internal/bot/commands.go index feba7de..8d89796 100644 --- a/internal/bot/commands.go +++ b/internal/bot/commands.go @@ -5,6 +5,7 @@ import ( "errors" "strconv" "strings" + "time" "github.com/mymmrac/telego" @@ -62,6 +63,18 @@ func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) { if b.isOwner(m) { b.cmdCache(ctx, m, act) } + case "workers": + if b.isOwner(m) { + b.cmdWorkers(ctx, m, act) + } + case "drain": + if b.isOwner(m) { + b.cmdDrain(ctx, m, act) + } + case "ytdlp": + if b.isOwner(m) { + b.cmdYtDlp(ctx, m, act) + } case "info": b.cmdInfo(ctx, m, act) case "queue": @@ -297,21 +310,25 @@ func (b *Bot) cmdQueue(ctx context.Context, m *telego.Message, act actor) { } func (b *Bot) cmdCancel(ctx context.Context, m *telego.Message, act actor) { + n := 0 + // Playlist items that have not started go first. Cancelling a running + // download frees a slot, and the next waiting item would take it. + b.statusMu.Lock() + b.cancelledAt[act.user.ID] = time.Now() + b.statusMu.Unlock() + if waiting, err := b.store.CancelWaitingRequests(ctx, act.user.ID); err == nil { + n += int(waiting) + } dels, err := b.store.ActiveDeliveriesForUser(ctx, act.user.ID) if err != nil { b.log.Error("list deliveries", "err", err) return } - n := 0 for _, d := range dels { if b.cancelDelivery(ctx, d.ID, act.user.ID) == nil { n++ } } - // Playlist items that have not started yet are cancelled too. - if waiting, err := b.store.CancelWaitingRequests(ctx, act.user.ID); err == nil { - n += int(waiting) - } key := "cancel.done" if n == 0 { key = "cancel.nothing" @@ -337,11 +354,16 @@ func (b *Bot) cancelDelivery(ctx context.Context, deliveryID string, userID int6 // release gives back what an undelivered download took and returns a line // to append to the status when sats were refunded. func (b *Bot) release(ctx context.Context, d *db.Delivery) string { - refunded, err := b.svc.Release(context.WithoutCancel(ctx), d.ID) + bg := context.WithoutCancel(ctx) + refunded, err := b.svc.Release(bg, d.ID) if err != nil { b.log.Error("release delivery", "delivery_id", d.ID, "err", err) return "" } + if refunded <= 0 { + // Another path may have released it a moment ago. + refunded = b.svc.Refunded(bg, d.ID) + } if refunded <= 0 { return "" } diff --git a/internal/bot/extras.go b/internal/bot/extras.go index 4209f61..639ce8e 100644 --- a/internal/bot/extras.go +++ b/internal/bot/extras.go @@ -16,6 +16,7 @@ import ( "github.com/noderunners/dlbot/internal/ids" "github.com/noderunners/dlbot/internal/media" "github.com/noderunners/dlbot/internal/service" + "github.com/noderunners/dlbot/internal/workerproto" ) const ( @@ -176,10 +177,19 @@ func (b *Bot) startPlaylistItem(ctx context.Context, item *db.Request) bool { return false // no free slot yet: stay in line } } + began := time.Now() took, err := b.store.TransitionRequest(ctx, item.ID, db.RequestWaiting, db.RequestChosen) if err != nil || !took { return false } + // cancelledSince reports a /cancel that arrived while this item was + // being prepared. The item was no longer "waiting", so the command + // could not see it. + cancelledSince := func() bool { + b.statusMu.Lock() + defer b.statusMu.Unlock() + return b.cancelledAt[item.UserID].After(began) + } lang := item.Lang fail := func(title, reason string) bool { if _, err := b.store.TransitionRequest(context.WithoutCancel(ctx), item.ID, db.RequestChosen, db.RequestFailed); err != nil { @@ -204,6 +214,10 @@ func (b *Bot) startPlaylistItem(ctx context.Context, item *db.Request) bool { case probed.Info == nil: return fail(item.URL, b.tr.T(lang, "error.playlist_nested", nil)) } + if cancelledSince() { + _, _ = b.store.TransitionRequest(context.WithoutCancel(ctx), item.ID, db.RequestChosen, db.RequestCancelled) + return false + } info := probed.Info if err := b.store.SetRequestInfo(ctx, item.ID, info.JSON()); err != nil { b.log.Error("save playlist item info", "err", err) @@ -451,3 +465,88 @@ func (b *Bot) cmdCache(ctx context.Context, m *telego.Message, act actor) { "Since": strconv.FormatInt(st.Hits+st.Misses, 10), }), nil) } + +// --- owner: workers ---------------------------------------------------------- + +func (b *Bot) cmdWorkers(ctx context.Context, m *telego.Message, act actor) { + lang := act.lang + ws, err := b.store.ListWorkers(ctx) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + running, _ := b.store.RunningByWorker(ctx) + var sb strings.Builder + sb.WriteString(b.tr.HTML(lang, "owner.workers_header", i18n.Args{ + "Slots": b.sched.Capacity(), "Count": len(ws), + })) + if b.cfg.Worker.Embedded { + sb.WriteString("\n") + sb.WriteString(b.tr.HTML(lang, "owner.worker_embedded", i18n.Args{ + "Capacity": b.cfg.Worker.Concurrency, "Running": running["embedded"], + })) + } + now := time.Now() + for _, w := range ws { + state := "owner.state_active" + switch { + case w.Revoked: + state = "owner.state_revoked" + case w.Draining: + state = "owner.state_draining" + case w.LastSeenAt == 0 || now.Sub(time.UnixMilli(w.LastSeenAt)) > 2*time.Minute: + state = "owner.state_offline" + } + seen := b.tr.T(lang, "owner.never", nil) + if w.LastSeenAt > 0 { + seen = b.tr.Span(lang, now.Sub(time.UnixMilli(w.LastSeenAt))) + } + tags := w.Tags + if tags == "" { + tags = "-" + } + sb.WriteString("\n") + sb.WriteString(b.tr.HTML(lang, "owner.worker_line", i18n.Args{ + "Name": w.ID, "State": b.tr.T(lang, state, nil), "Running": running[w.ID], "Capacity": w.Capacity, + "Seen": seen, "Tags": tags, "Version": w.Version, + })) + } + _, _ = b.send(ctx, m.Chat.ID, 0, sb.String(), nil) +} + +// cmdDrain handles /drain and /drain off. A draining +// worker finishes its jobs and is given no new ones. +func (b *Bot) cmdDrain(ctx context.Context, m *telego.Message, act actor) { + lang := act.lang + fields := strings.Fields(commandArgs(m)) + if len(fields) == 0 || len(fields) > 2 || (len(fields) == 2 && fields[1] != "off" && fields[1] != "on") { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "owner.drain_usage", nil), nil) + return + } + drain := len(fields) == 1 || fields[1] == "on" + ok, err := b.store.SetWorkerDraining(ctx, fields[0], drain) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + key := "owner.drain_on" + switch { + case !ok: + key = "owner.worker_unknown" + case !drain: + key = "owner.drain_off" + } + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, key, i18n.Args{"Name": fields[0]}), nil) +} + +// cmdYtDlp handles /ytdlp update: every live worker updates yt-dlp when +// it next asks for work. +func (b *Bot) cmdYtDlp(ctx context.Context, m *telego.Message, act actor) { + lang := act.lang + if strings.TrimSpace(commandArgs(m)) != "update" { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "owner.ytdlp_usage", nil), nil) + return + } + n := b.sched.Command(workerproto.CommandUpdateYtDlp) + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "owner.ytdlp_update", i18n.Args{"Count": n}), nil) +} diff --git a/internal/config/config.go b/internal/config/config.go index c3be281..15f57c6 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -11,6 +11,7 @@ import ( "fmt" "os" "reflect" + "sort" "strconv" "strings" "time" @@ -49,6 +50,27 @@ type Config struct { Rate Rate `toml:"rate"` Log Log `toml:"log"` + // SiteTags says which worker tags a site requires. A job for a listed + // site is only given to workers that advertise all of its tags. The + // usual case is a site that refuses datacenter addresses: + // + // [site_tags] + // "youtube.com" = ["residential"] + // + // A host also covers its subdomains. In the environment the same map + // is SITE_TAGS="youtube.com=residential;example.com=eu,residential". + SiteTags map[string][]string `toml:"site_tags"` + + // WorkerTokens registers remote workers at startup, as "name:token" + // pairs. It is the simple way for a fixed setup such as docker + // compose. "core worker add" creates tokens without a restart. + WorkerTokens []string `toml:"worker_tokens" env:"WORKER_TOKENS"` + + // ProbeMode says who runs metadata lookups: "local" (the core runs + // yt-dlp), "worker" (remote workers do), or "auto", which is local + // when the embedded worker is on and worker otherwise. + ProbeMode string `toml:"probe_mode" env:"PROBE_MODE"` + // 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. @@ -93,16 +115,40 @@ type Storage struct { // Backend is "local" or "s3". Backend string `toml:"backend" env:"STORAGE_BACKEND"` LocalDir string `toml:"local_dir" env:"STORAGE_LOCAL_DIR"` + S3 S3 `toml:"s3"` +} + +// S3 holds the settings of an S3 compatible bucket (AWS, Garage, MinIO). +type S3 struct { + // Endpoint is host:port or a URL, for example https://s3.example.com. + Endpoint string `toml:"endpoint" env:"S3_ENDPOINT"` + Region string `toml:"region" env:"S3_REGION"` + Bucket string `toml:"bucket" env:"S3_BUCKET"` + AccessKey string `toml:"access_key" env:"S3_ACCESS_KEY"` + SecretKey string `toml:"secret_key" env:"S3_SECRET_KEY"` + UseSSL bool `toml:"use_ssl" env:"S3_USE_SSL"` + // PathStyle addresses the bucket as /bucket/key. Garage and MinIO need + // it; AWS prefers it off. + PathStyle bool `toml:"path_style" env:"S3_PATH_STYLE"` + Prefix string `toml:"prefix" env:"S3_PREFIX"` + // Presign lets workers upload straight to the bucket with presigned + // URLs. When off, files pass through the core. + Presign bool `toml:"presign" env:"S3_PRESIGN"` + // PresignEndpoint is the address workers reach the bucket at, when it + // is not the one the core uses. + PresignEndpoint string `toml:"presign_endpoint" env:"S3_PRESIGN_ENDPOINT"` } // 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"` + Embedded bool `toml:"embedded" env:"WORKER_EMBEDDED"` + Concurrency int `toml:"concurrency" env:"WORKER_CONCURRENCY"` + // Tags are the tags of the embedded worker. + Tags []string `toml:"tags" env:"WORKER_TAGS"` + 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. @@ -233,9 +279,11 @@ func Default() Config { MaxUploadMB: 50, UpdateWorkers: 8, }, - HTTP: HTTP{Listen: ":8080"}, - Database: Database{Driver: "sqlite", DSN: "data/dlbot.db"}, - Storage: Storage{Backend: "local", LocalDir: "data/files"}, + ProbeMode: "auto", + HTTP: HTTP{Listen: ":8080"}, + Database: Database{Driver: "sqlite", DSN: "data/dlbot.db"}, + Storage: Storage{Backend: "local", LocalDir: "data/files", + S3: S3{Region: "garage", UseSSL: true, PathStyle: true, Presign: true}}, Worker: Worker{ Embedded: true, Concurrency: 2, @@ -322,6 +370,13 @@ func Load(path string) (Config, error) { if err := applyTierEnv("PAID", &cfg.Limits.Paid, os.LookupEnv); err != nil { return cfg, err } + if raw, ok := os.LookupEnv("SITE_TAGS"); ok && raw != "" { + m, err := ParseSiteTags(raw) + if err != nil { + return cfg, err + } + cfg.SiteTags = m + } cfg.PublicURL = strings.TrimRight(cfg.PublicURL, "/") cfg.LNbits.URL = strings.TrimRight(cfg.LNbits.URL, "/") return cfg, cfg.Validate() @@ -361,6 +416,25 @@ func (c Config) Validate() error { if c.Queue.Heartbeat.D() >= c.Queue.Lease.D() { errs = append(errs, "QUEUE_HEARTBEAT must be shorter than QUEUE_LEASE") } + if c.Storage.Backend == "s3" { + if c.Storage.S3.Endpoint == "" || c.Storage.S3.Bucket == "" { + errs = append(errs, "S3_ENDPOINT and S3_BUCKET are required when STORAGE_BACKEND=s3") + } + if c.Storage.S3.AccessKey == "" || c.Storage.S3.SecretKey == "" { + errs = append(errs, "S3_ACCESS_KEY and S3_SECRET_KEY are required when STORAGE_BACKEND=s3") + } + } + switch c.ProbeMode { + case "auto", "local", "worker": + default: + errs = append(errs, "PROBE_MODE must be auto, local or worker") + } + for _, pair := range c.WorkerTokens { + if name, token, ok := strings.Cut(pair, ":"); !ok || name == "" || len(token) < 16 { + errs = append(errs, "WORKER_TOKENS entries must be name:token with a token of at least 16 characters") + break + } + } if (c.LNbits.URL == "") != (c.LNbits.InvoiceKey == "") { errs = append(errs, "LNBITS_URL and LNBITS_INVOICE_KEY must be set together") } @@ -386,6 +460,65 @@ func (c Config) Validate() error { return nil } +// ParseSiteTags reads "host=tag,tag;host=tag". +func ParseSiteTags(raw string) (map[string][]string, error) { + out := map[string][]string{} + for _, part := range strings.Split(raw, ";") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + host, tags, ok := strings.Cut(part, "=") + host = strings.ToLower(strings.TrimSpace(host)) + if !ok || host == "" { + return nil, fmt.Errorf("config: SITE_TAGS: %q is not host=tag,tag", part) + } + for _, t := range strings.Split(tags, ",") { + if t = strings.ToLower(strings.TrimSpace(t)); t != "" { + out[host] = append(out[host], t) + } + } + } + return out, nil +} + +// RequiredTags returns the worker tags a site requires, sorted and comma +// separated, or "" when any worker will do. A rule for a host also covers +// its subdomains, and the rules of a host and of its parents add up. +func (c Config) RequiredTags(site string) string { + if len(c.SiteTags) == 0 || site == "" { + return "" + } + seen := map[string]bool{} + var tags []string + for host := strings.ToLower(site); host != ""; { + for _, t := range c.SiteTags[host] { + if t = strings.ToLower(strings.TrimSpace(t)); t != "" && !seen[t] { + seen[t] = true + tags = append(tags, t) + } + } + i := strings.IndexByte(host, '.') + if i < 0 { + break + } + host = host[i+1:] + } + sort.Strings(tags) + return strings.Join(tags, ",") +} + +// ProbeLocally reports whether the core itself runs metadata lookups. +func (c Config) ProbeLocally() bool { + switch c.ProbeMode { + case "local": + return true + case "worker": + return false + } + return c.Worker.Embedded +} + // MaxUploadBytes is the Telegram upload ceiling in bytes. func (c Config) MaxUploadBytes() int64 { return c.Telegram.MaxUploadMB << 20 } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 0fccd70..8af3169 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -248,3 +248,108 @@ func TestDotEnvDoesNotOverrideRealEnv(t *testing.T) { t.Errorf("a missing .env is fine, got %v", err) } } + +func TestSiteTagsAndRequiredTags(t *testing.T) { + m, err := ParseSiteTags(" YouTube.com = residential ; example.com=eu, residential ;; x.com=residential") + if err != nil { + t.Fatal(err) + } + cfg := Default() + cfg.SiteTags = m + tests := map[string]string{ + "youtube.com": "residential", + "music.youtube.com": "residential", // a rule covers subdomains + "example.com": "eu,residential", + "cdn.eu.example.com": "eu,residential", + "notyoutube.com": "", + "com": "", + "": "", + "vimeo.com": "", + "YOUTUBE.COM": "residential", + } + for site, want := range tests { + if got := cfg.RequiredTags(site); got != want { + t.Errorf("RequiredTags(%q) = %q, want %q", site, got, want) + } + } + // Rules of a host and of its parent add up. + cfg.SiteTags["eu.example.com"] = []string{"fast"} + if got := cfg.RequiredTags("cdn.eu.example.com"); got != "eu,fast,residential" { + t.Errorf("combined rules = %q", got) + } + if _, err := ParseSiteTags("no-equals-sign"); err == nil { + t.Error("a malformed SITE_TAGS must be rejected") + } + if got := Default().RequiredTags("youtube.com"); got != "" { + t.Errorf("without rules nothing is required, got %q", got) + } +} + +func TestProbeModeAndScaleOutValidation(t *testing.T) { + cfg := Default() + cfg.Telegram.Token = "x" + if !cfg.ProbeLocally() { + t.Fatal("with the embedded worker, the core probes by itself") + } + cfg.Worker.Embedded = false + if cfg.ProbeLocally() { + t.Fatal("without the embedded worker, probes go to remote workers") + } + cfg.ProbeMode = "local" + if !cfg.ProbeLocally() { + t.Fatal("PROBE_MODE=local forces local probing") + } + cfg.ProbeMode = "sometimes" + if err := cfg.Validate(); err == nil { + t.Fatal("an unknown PROBE_MODE must be rejected") + } + cfg.ProbeMode = "auto" + + cfg.WorkerTokens = []string{"eu-1:short"} + if err := cfg.Validate(); err == nil { + t.Fatal("a short worker token must be rejected") + } + cfg.WorkerTokens = []string{"eu-1:dlw_0123456789abcdef"} + if err := cfg.Validate(); err != nil { + t.Fatalf("a good worker token entry: %v", err) + } + + cfg.Storage.Backend = "s3" + if err := cfg.Validate(); err == nil { + t.Fatal("s3 without endpoint, bucket and keys must be rejected") + } + cfg.Storage.S3 = S3{Endpoint: "https://s3.example.com", Bucket: "b", AccessKey: "k", SecretKey: "s"} + if err := cfg.Validate(); err != nil { + t.Fatalf("complete s3 settings: %v", err) + } +} + +func TestWorkerConfig(t *testing.T) { + cfg := DefaultWorker() + if err := cfg.Validate(); err == nil { + t.Fatal("a worker needs CORE_URL and WORKER_TOKEN") + } + cfg.CoreURL, cfg.Token = "bot.example.com", "dlw_x" + if err := cfg.Validate(); err == nil { + t.Fatal("CORE_URL needs a scheme") + } + cfg.CoreURL = "https://bot.example.com" + if err := cfg.Validate(); err != nil { + t.Fatalf("a complete worker config: %v", err) + } + if cfg.Heartbeat.D() != 10*time.Second || cfg.Concurrency != 2 || cfg.ProbeSlots != 2 { + t.Fatalf("worker defaults changed: %+v", cfg) + } + env := map[string]string{ + "CORE_URL": "https://core.example.com/", "WORKER_TOKEN": "dlw_abc", "WORKER_TAGS": "residential, eu", + "YTDLP_EXTRA_ARGS": "--limit-rate 1M", "WORKER_HEALTH_LISTEN": "off", "YTDLP_AUTO_UPDATE": "0", + } + w := DefaultWorker() + if err := applyEnv(reflect.ValueOf(&w).Elem(), lookup(env)); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(w.Tags, []string{"residential", "eu"}) || !reflect.DeepEqual(w.ExtraArgs, []string{"--limit-rate", "1M"}) || + w.AutoUpdate.D() != 0 { + t.Fatalf("worker env not applied: %+v", w) + } +} diff --git a/internal/config/worker.go b/internal/config/worker.go new file mode 100644 index 0000000..af87e5d --- /dev/null +++ b/internal/config/worker.go @@ -0,0 +1,105 @@ +package config + +import ( + "errors" + "os" + "reflect" + "strings" + "time" +) + +// WorkerConfig is the configuration of the standalone worker binary. A +// worker knows the core's URL and its own token, and nothing else about +// the system: no bot token, no database, no payment keys. +type WorkerConfig struct { + // CoreURL is the base URL of the core, for example + // https://bot.example.com. + CoreURL string `env:"CORE_URL"` + // Token is this worker's bearer token, created on the core with + // "core worker add ". + Token string `env:"WORKER_TOKEN"` + // Tags describe what this worker can do or where it runs, for example + // "residential,eu". Jobs for sites that require a tag only go to + // workers that have it. + Tags []string `env:"WORKER_TAGS"` + Concurrency int `env:"WORKER_CONCURRENCY"` + // TempDir is scratch space. Each worker process needs its own. + TempDir string `env:"WORKER_TEMP_DIR"` + YtDlpPath string `env:"YTDLP_PATH"` + FfmpegPath string `env:"FFMPEG_PATH"` + // ExtraArgs are appended to every yt-dlp call, for example + // "--proxy socks5://127.0.0.1:1080". + ExtraArgs []string `env:"YTDLP_EXTRA_ARGS"` + DownloadTimeout Duration `env:"DOWNLOAD_TIMEOUT"` + ProbeTimeout Duration `env:"PROBE_TIMEOUT"` + // ProbeSlots is how many metadata lookups run next to the downloads. + ProbeSlots int `env:"WORKER_PROBE_SLOTS"` + // Heartbeat must be well under the core's QUEUE_LEASE. + Heartbeat Duration `env:"WORKER_HEARTBEAT"` + // AutoUpdate is how often yt-dlp updates itself. 0 turns it off. + AutoUpdate Duration `env:"YTDLP_AUTO_UPDATE"` + // HealthListen is the address of the health endpoint, or "off". It is + // the only port a worker opens and it is not needed by the core. Several + // workers on one machine need different ports. + HealthListen string `env:"WORKER_HEALTH_LISTEN"` + Log Log +} + +// DefaultWorker returns the worker defaults. +func DefaultWorker() WorkerConfig { + return WorkerConfig{ + Concurrency: 2, + TempDir: "data/worker-tmp", + YtDlpPath: "yt-dlp", + FfmpegPath: "ffmpeg", + DownloadTimeout: Duration(30 * time.Minute), + ProbeTimeout: Duration(45 * time.Second), + ProbeSlots: 2, + Heartbeat: Duration(10 * time.Second), + AutoUpdate: Duration(24 * time.Hour), + HealthListen: ":8081", + Log: Log{Level: "info", Format: "json"}, + } +} + +// LoadWorker reads the worker configuration from the environment, after +// loading a .env file from the working directory if there is one. +func LoadWorker() (WorkerConfig, error) { + cfg := DefaultWorker() + if err := loadDotEnv(".env"); err != nil { + return cfg, err + } + if err := applyEnv(reflect.ValueOf(&cfg).Elem(), os.LookupEnv); err != nil { + return cfg, err + } + cfg.CoreURL = strings.TrimRight(cfg.CoreURL, "/") + // An empty variable keeps the default, so "off" is how to say no. + switch strings.ToLower(cfg.HealthListen) { + case "off", "none", "false", "-": + cfg.HealthListen = "" + } + return cfg, cfg.Validate() +} + +// Validate reports configuration mistakes. +func (c WorkerConfig) Validate() error { + var errs []string + if c.CoreURL == "" { + errs = append(errs, "CORE_URL is required") + } else if !strings.HasPrefix(c.CoreURL, "http://") && !strings.HasPrefix(c.CoreURL, "https://") { + errs = append(errs, "CORE_URL must start with http:// or https://") + } + if c.Token == "" { + errs = append(errs, "WORKER_TOKEN is required") + } + if c.Concurrency < 1 { + errs = append(errs, "WORKER_CONCURRENCY must be at least 1") + } + if c.Heartbeat.D() <= 0 { + errs = append(errs, "WORKER_HEARTBEAT must be positive") + } + if len(errs) > 0 { + return errors.New("config: " + strings.Join(errs, "; ")) + } + return nil +} diff --git a/internal/db/db.go b/internal/db/db.go index fd0586c..56759ec 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -143,6 +143,11 @@ func (s *Store) InTx(ctx context.Context, fn func(tx *Store) error) error { return tx.Commit() } +// Rebind turns "?" placeholders into the form the database expects. Code +// outside this package that runs its own SQL, mostly tests, uses it to stay +// portable. +func (d *DB) Rebind(query string) string { return (&Store{db: d}).rebind(query) } + // rebind turns "?" placeholders into "$1, $2, ..." for Postgres. func (s *Store) rebind(query string) string { if s.db.Dialect != Postgres { diff --git a/internal/db/dbtest/dbtest.go b/internal/db/dbtest/dbtest.go index 6f14412..ae7846e 100644 --- a/internal/db/dbtest/dbtest.go +++ b/internal/db/dbtest/dbtest.go @@ -1,19 +1,75 @@ // Package dbtest opens throwaway databases for tests. +// +// By default every test gets its own SQLite file. To run the same tests +// against Postgres, point them at a server: +// +// DLBOT_TEST_DB=postgres \ +// DLBOT_TEST_PG_DSN=postgres://user@127.0.0.1:5432/dlbot_test \ +// go test ./... +// +// Each test then gets its own schema, which is dropped afterwards. package dbtest import ( "context" + "crypto/rand" + "database/sql" + "encoding/hex" + "net/url" + "os" "path/filepath" "testing" + _ "github.com/jackc/pgx/v5/stdlib" // for schema setup + "github.com/noderunners/dlbot/internal/db" ) +// Postgres reports whether tests run against Postgres. +func Postgres() bool { return os.Getenv("DLBOT_TEST_DB") == "postgres" } + +// NewDSN returns the driver and DSN of a fresh, empty database for one +// test. It is removed when the test ends. +func NewDSN(t testing.TB) (driver, dsn string) { + t.Helper() + if !Postgres() { + return "sqlite", filepath.Join(t.TempDir(), "test.db") + } + base := os.Getenv("DLBOT_TEST_PG_DSN") + if base == "" { + t.Fatal("DLBOT_TEST_DB=postgres needs DLBOT_TEST_PG_DSN") + } + var raw [6]byte + _, _ = rand.Read(raw[:]) + schema := "t_" + hex.EncodeToString(raw[:]) + admin, err := sql.Open("pgx", base) + if err != nil { + t.Fatalf("open postgres: %v", err) + } + if _, err := admin.Exec(`CREATE SCHEMA ` + schema); err != nil { + admin.Close() + t.Fatalf("create schema: %v", err) + } + t.Cleanup(func() { + _, _ = admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`) + admin.Close() + }) + u, err := url.Parse(base) + if err != nil { + t.Fatalf("bad DLBOT_TEST_PG_DSN: %v", err) + } + q := u.Query() + q.Set("search_path", schema) + u.RawQuery = q.Encode() + return "postgres", u.String() +} + // Open returns a migrated database that is removed when the test ends. func Open(t testing.TB) *db.DB { t.Helper() ctx := context.Background() - d, err := db.Open(ctx, "sqlite", filepath.Join(t.TempDir(), "test.db")) + driver, dsn := NewDSN(t) + d, err := db.Open(ctx, driver, dsn) if err != nil { t.Fatalf("open db: %v", err) } diff --git a/internal/db/jobs.go b/internal/db/jobs.go index 5ef78ce..c7a9eb9 100644 --- a/internal/db/jobs.go +++ b/internal/db/jobs.go @@ -4,6 +4,8 @@ import ( "context" "database/sql" "errors" + "strconv" + "strings" ) const jobCols = `id, kind, url, extractor, video_id, profile, cache_key, status, lane, priority, @@ -66,21 +68,63 @@ const laneRank = `CASE lane WHEN 'paid' THEN 0 ELSE 1 END` // queueOrder is the one ordering used for claiming and for positions. const queueOrder = laneRank + ` ASC, priority DESC, queued_at ASC, id ASC` -// NextQueuedJob returns the first queued job in the given lanes, locking it -// against other claimers. It must run inside a transaction. On Postgres the -// lock is FOR UPDATE SKIP LOCKED; on SQLite the immediate transaction -// already serializes writers. -func (s *Store) NextQueuedJob(ctx context.Context, lanes []string) (*Job, error) { +// claimWindow is how many queued jobs a claim looks at to find one whose +// required tags the worker has. +const claimWindow = 25 + +// NextQueuedJob returns the first queued job in the given lanes that the +// worker's tags qualify for, locking it against other claimers. It must +// run inside a transaction. On Postgres the lock is FOR UPDATE SKIP +// LOCKED; on SQLite the immediate transaction already serializes writers. +// +// A job with required tags is skipped by workers that lack one of them. +// The claim looks at the head of the queue, so a job that needs a rare tag +// waits its turn there without blocking the jobs behind it. +func (s *Store) NextQueuedJob(ctx context.Context, lanes []string, tags []string) (*Job, error) { if !s.inTx { return nil, errors.New("db: NextQueuedJob needs a transaction") } ph, args := in(lanes) q := `SELECT ` + jobCols + ` FROM jobs WHERE status = 'queued' AND lane IN (` + ph + `) - ORDER BY ` + queueOrder + ` LIMIT 1` + ORDER BY ` + queueOrder + ` LIMIT ` + strconv.Itoa(claimWindow) if s.db.Dialect == Postgres { q += ` FOR UPDATE SKIP LOCKED` } - return scanJob(s.row(ctx, q, args...)) + jobs, err := scanJobs(s.rows(ctx, q, args...)) + if err != nil { + return nil, err + } + for _, j := range jobs { + if HasTags(tags, j.RequiredTags) { + return j, nil + } + } + return nil, ErrNotFound +} + +// HasTags reports whether a worker's tags include every required tag. +// required is a comma separated list; empty means "any worker". +func HasTags(have []string, required string) bool { + if required == "" { + return true + } + for _, need := range strings.Split(required, ",") { + need = strings.TrimSpace(need) + if need == "" { + continue + } + found := false + for _, h := range have { + if h == need { + found = true + break + } + } + if !found { + return false + } + } + return true } // MarkJobRunning hands a queued job to a worker. diff --git a/internal/db/migrations/00004_workers.sql b/internal/db/migrations/00004_workers.sql new file mode 100644 index 0000000..924bef2 --- /dev/null +++ b/internal/db/migrations/00004_workers.sql @@ -0,0 +1,18 @@ +-- +goose Up +-- Remote download workers. A worker authenticates with a bearer token of +-- which only the SHA-256 hash is stored. Tokens are per worker and can be +-- revoked without touching the others. +CREATE TABLE workers ( + id TEXT PRIMARY KEY, + token_hash TEXT NOT NULL UNIQUE, + tags TEXT NOT NULL DEFAULT '', + capacity INTEGER NOT NULL DEFAULT 0, + draining BOOLEAN NOT NULL DEFAULT FALSE, + revoked BOOLEAN NOT NULL DEFAULT FALSE, + version TEXT NOT NULL DEFAULT '', + last_seen_at BIGINT NOT NULL DEFAULT 0, + created_at BIGINT NOT NULL +); + +-- +goose Down +DROP TABLE workers; diff --git a/internal/db/postgres.go b/internal/db/postgres.go index 4741049..5b6a5f4 100644 --- a/internal/db/postgres.go +++ b/internal/db/postgres.go @@ -2,11 +2,71 @@ package db import ( "context" + "database/sql" "errors" + "fmt" + + _ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" driver ) -// openPostgres is replaced by the real implementation in Phase 4. Keeping -// the entry point here means the driver switch in Open never changes. -func openPostgres(_ context.Context, _ string) (*DB, error) { - return nil, errors.New("db: the postgres backend is not built into this version yet") +// openPostgres connects with pgx. The DSN is a connection URL such as +// postgres://user:pass@host:5432/dbname?sslmode=require. +func openPostgres(ctx context.Context, dsn string) (*DB, error) { + if dsn == "" { + return nil, errors.New("db: postgres needs a connection URL") + } + sqldb, err := sql.Open("pgx", dsn) + if err != nil { + return nil, err + } + sqldb.SetMaxOpenConns(20) + sqldb.SetMaxIdleConns(10) + if err := sqldb.PingContext(ctx); err != nil { + sqldb.Close() + // The driver's error can quote the DSN, which holds the password. + return nil, fmt.Errorf("db: cannot connect to postgres: %s", redactDSN(err.Error(), dsn)) + } + return &DB{SQL: sqldb, Dialect: Postgres}, nil +} + +// redactDSN removes the connection string from an error message. +func redactDSN(msg, dsn string) string { + out := msg + for i := 0; i+len(dsn) <= len(out); { + if out[i:i+len(dsn)] == dsn { + out = out[:i] + "[dsn]" + out[i+len(dsn):] + continue + } + i++ + } + return out +} + +// LockUser serializes transactions that check and then change a user's +// rows, such as "count active jobs, then insert one". SQLite does this by +// itself, because every transaction holds the write lock. Postgres runs +// transactions side by side, so two fast requests could both pass the +// check. The advisory lock is held until the transaction ends. +func (s *Store) LockUser(ctx context.Context, userID int64) error { + if s.db.Dialect != Postgres || !s.inTx { + return nil + } + _, err := s.q.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1)`, userID) + return err +} + +// LockJob takes a row lock on a job until the transaction ends, so that +// its status cannot change between reading it and acting on it. Without +// it Postgres lets, for example, a worker claim a job in the moment a +// requester cancels it. SQLite needs nothing: its transactions are serial. +func (s *Store) LockJob(ctx context.Context, jobID string) error { + if s.db.Dialect != Postgres || !s.inTx { + return nil + } + var id string + err := s.q.QueryRowContext(ctx, `SELECT id FROM jobs WHERE id = $1 FOR UPDATE`, jobID).Scan(&id) + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + return err } diff --git a/internal/db/workers.go b/internal/db/workers.go new file mode 100644 index 0000000..1e65ccd --- /dev/null +++ b/internal/db/workers.go @@ -0,0 +1,140 @@ +package db + +import ( + "context" + "database/sql" +) + +// Worker is a registered download worker. +type Worker struct { + ID string + TokenHash string + Tags string // comma separated, as last advertised + Capacity int + Draining bool + Revoked bool + Version string // yt-dlp version, as last reported + LastSeenAt int64 + CreatedAt int64 +} + +const workerCols = `id, token_hash, tags, capacity, draining, revoked, version, last_seen_at, created_at` + +func scanWorker(sc interface{ Scan(...any) error }) (*Worker, error) { + var w Worker + err := sc.Scan(&w.ID, &w.TokenHash, &w.Tags, &w.Capacity, &w.Draining, &w.Revoked, &w.Version, + &w.LastSeenAt, &w.CreatedAt) + if err != nil { + return nil, notFound(err) + } + return &w, nil +} + +// UpsertWorker registers a worker or replaces its token. Replacing the +// token also lifts a revocation: issuing a new token is how a worker is +// brought back. +func (s *Store) UpsertWorker(ctx context.Context, id, tokenHash string) error { + _, err := s.exec(ctx, `INSERT INTO workers (id, token_hash, created_at) VALUES (?, ?, ?) + ON CONFLICT (id) DO UPDATE SET token_hash = excluded.token_hash, revoked = ?`, + id, tokenHash, NowMilli(), false) + if isUniqueViolation(err) { + return ErrDuplicate + } + return err +} + +// WorkerByToken finds the worker a token hash belongs to. +func (s *Store) WorkerByToken(ctx context.Context, tokenHash string) (*Worker, error) { + return scanWorker(s.row(ctx, `SELECT `+workerCols+` FROM workers WHERE token_hash = ?`, tokenHash)) +} + +// GetWorker loads a worker by ID. +func (s *Store) GetWorker(ctx context.Context, id string) (*Worker, error) { + return scanWorker(s.row(ctx, `SELECT `+workerCols+` FROM workers WHERE id = ?`, id)) +} + +// ListWorkers returns all workers, most recently seen first. +func (s *Store) ListWorkers(ctx context.Context) ([]*Worker, error) { + rows, err := s.rows(ctx, `SELECT `+workerCols+` FROM workers ORDER BY last_seen_at DESC, id`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*Worker + for rows.Next() { + w, err := scanWorker(rows) + if err != nil { + return nil, err + } + out = append(out, w) + } + return out, rows.Err() +} + +// TouchWorker records what a worker advertised in its latest call. +func (s *Store) TouchWorker(ctx context.Context, id, tags string, capacity int, version string, now int64) error { + _, err := s.exec(ctx, `UPDATE workers SET tags = ?, capacity = ?, + version = CASE WHEN ? <> '' THEN ? ELSE version END, last_seen_at = ? WHERE id = ?`, + tags, capacity, version, version, now, id) + return err +} + +// SetWorkerDraining turns draining on or off and reports whether the +// worker exists. +func (s *Store) SetWorkerDraining(ctx context.Context, id string, draining bool) (bool, error) { + n, err := s.exec(ctx, `UPDATE workers SET draining = ? WHERE id = ?`, draining, id) + return n == 1, err +} + +// RevokeWorker makes a worker's token useless and reports whether the +// worker exists. +func (s *Store) RevokeWorker(ctx context.Context, id string) (bool, error) { + n, err := s.exec(ctx, `UPDATE workers SET revoked = ? WHERE id = ?`, true, id) + return n == 1, err +} + +// RunningByWorker counts running jobs per worker. +func (s *Store) RunningByWorker(ctx context.Context) (map[string]int, error) { + rows, err := s.rows(ctx, `SELECT worker_id, COUNT(*) FROM jobs WHERE status = 'running' GROUP BY worker_id`) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]int{} + for rows.Next() { + var id string + var n int + if err := rows.Scan(&id, &n); err != nil { + return nil, err + } + out[id] = n + } + return out, rows.Err() +} + +// QueueDepth counts queued jobs per lane and returns the age in +// milliseconds of the oldest one. +func (s *Store) QueueDepth(ctx context.Context, now int64) (paid, free int, oldestMS int64, err error) { + rows, err := s.rows(ctx, `SELECT lane, COUNT(*), MIN(queued_at) FROM jobs WHERE status = 'queued' GROUP BY lane`) + if err != nil { + return 0, 0, 0, err + } + defer rows.Close() + for rows.Next() { + var lane string + var n int + var oldest sql.NullInt64 + if err := rows.Scan(&lane, &n, &oldest); err != nil { + return 0, 0, 0, err + } + if lane == LanePaid { + paid = n + } else { + free += n + } + if oldest.Valid && now-oldest.Int64 > oldestMS { + oldestMS = now - oldest.Int64 + } + } + return paid, free, oldestMS, rows.Err() +} diff --git a/internal/probe/broker.go b/internal/probe/broker.go new file mode 100644 index 0000000..48ef8b6 --- /dev/null +++ b/internal/probe/broker.go @@ -0,0 +1,149 @@ +// Package probe sends metadata lookups to remote workers. +// +// The core needs yt-dlp metadata to show a card, but it may run somewhere +// that sites refuse to answer (a datacenter), or without yt-dlp at all. +// The broker hands such lookups to workers through their claim calls and +// waits for the answer. Requests live in memory only: if the core restarts +// while one is pending, the user just sends the link again. +package probe + +import ( + "context" + "encoding/json" + "errors" + "sync" + "time" + + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/ids" + "github.com/noderunners/dlbot/internal/workerproto" + "github.com/noderunners/dlbot/internal/ytdlp" +) + +type task struct { + id string + url string + required string + taken bool + done chan *workerproto.ProbeResult +} + +// Broker queues probe requests for workers. +type Broker struct { + // Timeout bounds one lookup, including the wait for a free worker. + Timeout time.Duration + // Tags returns the worker tags a URL requires, as a comma separated + // list. It may be nil. + Tags func(url string) string + // Notify wakes workers that wait in a claim call. + Notify func() + + mu sync.Mutex + tasks []*task + byID map[string]*task +} + +// NewBroker creates a broker. +func NewBroker(timeout time.Duration, tags func(string) string, notify func()) *Broker { + if timeout <= 0 { + timeout = 45 * time.Second + } + return &Broker{Timeout: timeout, Tags: tags, Notify: notify, byID: map[string]*task{}} +} + +// Probe asks a worker for the metadata of a URL and waits for the answer. +// It has the same contract as ytdlp.Runner.Probe. +func (b *Broker) Probe(ctx context.Context, url string) (*ytdlp.Info, error) { + t := &task{id: ids.New(), url: url, done: make(chan *workerproto.ProbeResult, 1)} + if b.Tags != nil { + t.required = b.Tags(url) + } + b.mu.Lock() + b.tasks = append(b.tasks, t) + b.byID[t.id] = t + b.mu.Unlock() + defer b.forget(t) + if b.Notify != nil { + b.Notify() + } + + timer := time.NewTimer(b.Timeout) + defer timer.Stop() + select { + case <-ctx.Done(): + return nil, &ytdlp.Error{Code: ytdlp.CodeCancelled, Raw: "probe cancelled"} + case <-timer.C: + // No worker answered in time: none is connected, none has the + // tags, or the lookup itself hung. + return nil, &ytdlp.Error{Code: ytdlp.CodeTimeout, Retryable: true, Raw: "no worker answered the probe"} + case res := <-t.done: + if res.Code != "" { + return nil, &ytdlp.Error{Code: ytdlp.Code(res.Code), Retryable: res.Retryable, Raw: res.Detail} + } + var info ytdlp.Info + if err := json.Unmarshal(res.Info, &info); err != nil { + return nil, &ytdlp.Error{Code: ytdlp.CodeUnknown, Retryable: true, Raw: "bad probe result: " + err.Error()} + } + if info.Type == "" { + info.Type = "video" + } + return &info, nil + } +} + +func (b *Broker) forget(t *task) { + b.mu.Lock() + defer b.mu.Unlock() + delete(b.byID, t.id) + for i, x := range b.tasks { + if x == t { + b.tasks = append(b.tasks[:i], b.tasks[i+1:]...) + break + } + } +} + +// Take hands the oldest waiting request to a worker with the given tags, +// or returns nil. +func (b *Broker) Take(tags []string) *workerproto.ProbeTask { + b.mu.Lock() + defer b.mu.Unlock() + for _, t := range b.tasks { + if !t.taken && db.HasTags(tags, t.required) { + t.taken = true + return &workerproto.ProbeTask{ID: t.id, URL: t.url} + } + } + return nil +} + +// Pending returns how many requests wait for a worker. +func (b *Broker) Pending() int { + b.mu.Lock() + defer b.mu.Unlock() + n := 0 + for _, t := range b.tasks { + if !t.taken { + n++ + } + } + return n +} + +// ErrUnknownProbe is returned for an answer nobody waits for anymore. +var ErrUnknownProbe = errors.New("probe: unknown or expired probe id") + +// Resolve delivers a worker's answer to the waiting request. +func (b *Broker) Resolve(res *workerproto.ProbeResult) error { + b.mu.Lock() + t, ok := b.byID[res.ID] + b.mu.Unlock() + if !ok { + return ErrUnknownProbe + } + select { + case t.done <- res: + default: // a second answer for the same request is dropped + } + return nil +} diff --git a/internal/sched/sched.go b/internal/sched/sched.go index addb726..a23f600 100644 --- a/internal/sched/sched.go +++ b/internal/sched/sched.go @@ -72,6 +72,8 @@ type Scheduler struct { type workerSeen struct { capacity int at time.Time + // commands are pending instructions, delivered with the next claim. + commands []string } // workerTTL is how long a worker counts toward capacity after its last @@ -181,6 +183,9 @@ type EnqueueParams struct { // Hit, when set, makes the job a cache hit: it is created already // finished and never waits for a worker. Hit *CacheHit + // RequiredTags is a comma separated list of tags a worker must have to + // take the job, for example "residential". + RequiredTags string } // CacheHit describes a cached result a job is served from. @@ -228,25 +233,26 @@ func (s *Scheduler) EnqueueTx(ctx context.Context, tx *db.Store, p EnqueueParams p.Kind = db.KindDownload } job := &db.Job{ - ID: ids.New(), - Kind: p.Kind, - URL: p.URL, - Extractor: p.Extractor, - VideoID: p.VideoID, - Profile: p.Profile, - CacheKey: p.CacheKey, - Cacheable: p.Cacheable, - SourceKey: p.SourceKey, - Status: db.JobQueued, - Lane: p.Lane, - Priority: p.Priority, - MaxSize: p.MaxSize, - MaxDuration: p.MaxDuration, - MaxAttempts: s.cfg.MaxAttempts, - Title: p.Title, - Uploader: p.Uploader, - CreatedAt: now, - QueuedAt: now, + ID: ids.New(), + Kind: p.Kind, + URL: p.URL, + Extractor: p.Extractor, + VideoID: p.VideoID, + Profile: p.Profile, + CacheKey: p.CacheKey, + Cacheable: p.Cacheable, + SourceKey: p.SourceKey, + RequiredTags: p.RequiredTags, + Status: db.JobQueued, + Lane: p.Lane, + Priority: p.Priority, + MaxSize: p.MaxSize, + MaxDuration: p.MaxDuration, + MaxAttempts: s.cfg.MaxAttempts, + Title: p.Title, + Uploader: p.Uploader, + CreatedAt: now, + QueuedAt: now, } if h := p.Hit; h != nil { // Served from the cache: the result exists, so the job starts in @@ -265,6 +271,11 @@ func (s *Scheduler) EnqueueTx(ctx context.Context, tx *db.Store, p EnqueueParams } del := s.newDelivery(job.ID, p, now) if p.ActiveLimit > 0 { + // Count and insert must not interleave with another request of + // the same user. + if err := tx.LockUser(ctx, p.UserID); err != nil { + return nil, nil, err + } n, err := tx.CountActiveDeliveries(ctx, p.UserID) if err != nil { return nil, nil, err @@ -331,6 +342,9 @@ func covers(jobCap, myCap int64) bool { // it up for whoever asked first. func (s *Scheduler) AttachTx(ctx context.Context, tx *db.Store, job *db.Job, p EnqueueParams) (*db.Delivery, bool, error) { if p.ActiveLimit > 0 { + if err := tx.LockUser(ctx, p.UserID); err != nil { + return nil, false, err + } n, err := tx.CountActiveDeliveries(ctx, p.UserID) if err != nil { return nil, false, err @@ -339,6 +353,19 @@ func (s *Scheduler) AttachTx(ctx context.Context, tx *db.Store, job *db.Job, p E return nil, false, ErrTooManyActive } } + // The job was found a moment ago. Lock it and look again: it may have + // been claimed, finished or cancelled since. + if err := tx.LockJob(ctx, job.ID); err != nil { + return nil, false, err + } + cur, err := tx.GetJob(ctx, job.ID) + if err != nil { + return nil, false, err + } + if cur.Status != db.JobQueued && cur.Status != db.JobRunning { + return nil, false, nil + } + *job = *cur shared := covers(job.MaxSize, p.MaxSize) && covers(job.MaxDuration, p.MaxDuration) if job.Status == db.JobQueued { raised, err := tx.RaiseJob(ctx, job.ID, p.MaxSize, p.MaxDuration, p.Lane) @@ -404,7 +431,8 @@ func (s *Scheduler) seen(workerID string, capacity int) (total int) { now := s.cfg.Now() s.mu.Lock() defer s.mu.Unlock() - s.workers[workerID] = workerSeen{capacity: capacity, at: now} + prev := s.workers[workerID] + s.workers[workerID] = workerSeen{capacity: capacity, at: now, commands: prev.commands} for id, w := range s.workers { if now.Sub(w.at) > workerTTL { delete(s.workers, id) @@ -415,6 +443,46 @@ func (s *Scheduler) seen(workerID string, capacity int) (total int) { return total } +// Command queues an instruction for every live worker. Each worker gets +// it with its next claim. It returns how many workers were addressed. +func (s *Scheduler) Command(cmd string) int { + now := s.cfg.Now() + s.mu.Lock() + defer s.mu.Unlock() + n := 0 + for id, w := range s.workers { + if now.Sub(w.at) > workerTTL { + continue + } + w.commands = append(w.commands, cmd) + s.workers[id] = w + n++ + } + return n +} + +// TakeCommands returns and clears the pending instructions of a worker. +func (s *Scheduler) TakeCommands(workerID string) []string { + s.mu.Lock() + defer s.mu.Unlock() + w, ok := s.workers[workerID] + if !ok || len(w.commands) == 0 { + return nil + } + cmds := w.commands + w.commands = nil + s.workers[workerID] = w + return cmds +} + +// Seen records that a worker is alive without claiming anything, so that +// a worker which only polls for probes still counts toward capacity. +func (s *Scheduler) Seen(workerID string, capacity int) { s.seen(workerID, capacity) } + +// NotifyWork wakes claimers that are waiting, for work that arrives +// outside the job queue, such as a probe request. +func (s *Scheduler) NotifyWork() { s.notifyWork() } + // Capacity returns the number of download slots of all live workers. func (s *Scheduler) Capacity() int { now := s.cfg.Now() @@ -451,7 +519,7 @@ func (s *Scheduler) Claim(ctx context.Context, req workerproto.ClaimRequest) (*w return err } if idle := capacity - total; idle <= 1 && free == 0 { - j, err = tx.NextQueuedJob(ctx, freeOnly) + j, err = tx.NextQueuedJob(ctx, freeOnly, req.Tags) if err != nil && !errors.Is(err, db.ErrNotFound) { return err } @@ -459,7 +527,7 @@ func (s *Scheduler) Claim(ctx context.Context, req workerproto.ClaimRequest) (*w } if j == nil { var err error - j, err = tx.NextQueuedJob(ctx, allLanes) + j, err = tx.NextQueuedJob(ctx, allLanes, req.Tags) if errors.Is(err, db.ErrNotFound) { return nil } @@ -534,6 +602,9 @@ func (s *Scheduler) Heartbeat(ctx context.Context, req workerproto.HeartbeatRequ func (s *Scheduler) Complete(ctx context.Context, req workerproto.CompleteRequest) error { var cancelled bool err := s.store.InTx(ctx, func(tx *db.Store) error { + if err := tx.LockJob(ctx, req.JobID); err != nil { + return err + } job, err := tx.GetJob(ctx, req.JobID) if err != nil { return err @@ -583,6 +654,9 @@ func (s *Scheduler) Complete(ctx context.Context, req workerproto.CompleteReques func (s *Scheduler) Fail(ctx context.Context, req workerproto.FailRequest) error { var ev EventType err := s.store.InTx(ctx, func(tx *db.Store) error { + if err := tx.LockJob(ctx, req.JobID); err != nil { + return err + } job, err := tx.GetJob(ctx, req.JobID) if err != nil { return err @@ -639,6 +713,9 @@ func (s *Scheduler) RequeueExpired(ctx context.Context) (int, error) { for _, j := range expired { var ev EventType err := s.store.InTx(ctx, func(tx *db.Store) error { + if err := tx.LockJob(ctx, j.ID); err != nil { + return err + } cur, err := tx.GetJob(ctx, j.ID) if err != nil { return err @@ -700,6 +777,11 @@ func (s *Scheduler) CancelDelivery(ctx context.Context, deliveryID string, userI } d.Status = db.DeliveryCancelled del = d + // Lock the job before looking at it: a worker may be claiming it + // right now, and the decision below depends on its status. + if err := tx.LockJob(ctx, d.JobID); err != nil { + return err + } left, err := tx.CountDeliveriesInStatus(ctx, d.JobID, db.DeliveryPending, db.DeliverySending) if err != nil || left > 0 { return err diff --git a/internal/service/service.go b/internal/service/service.go index 3e57c1f..c4e64e0 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -167,20 +167,26 @@ type Service struct { sched *sched.Scheduler billing *billing.Billing cache *cache.Cache - runner ytdlp.Runner + prober Prober log *slog.Logger probes chan struct{} now func() time.Time } +// Prober looks up the metadata of a link. It is yt-dlp on the core, or the +// broker that hands lookups to remote workers. +type Prober interface { + Probe(ctx context.Context, url string) (*ytdlp.Info, error) +} + // New creates the service. -func New(cfg config.Config, store *db.Store, sch *sched.Scheduler, bill *billing.Billing, ch *cache.Cache, runner ytdlp.Runner, log *slog.Logger) *Service { +func New(cfg config.Config, store *db.Store, sch *sched.Scheduler, bill *billing.Billing, ch *cache.Cache, prober Prober, log *slog.Logger) *Service { n := cfg.Worker.ProbeConcurrency if n < 1 { n = 1 } return &Service{ - cfg: cfg, store: store, sched: sch, billing: bill, cache: ch, runner: runner, log: log, + cfg: cfg, store: store, sched: sch, billing: bill, cache: ch, prober: prober, log: log, probes: make(chan struct{}, n), now: time.Now, } } @@ -218,7 +224,7 @@ func (s *Service) ProbeAny(ctx context.Context, url string) (*Probed, error) { case <-ctx.Done(): return nil, ctx.Err() } - info, err := s.runner.Probe(ctx, url) + info, err := s.prober.Probe(ctx, url) if err != nil { var ye *ytdlp.Error if errors.As(err, &ye) { @@ -496,6 +502,9 @@ func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Jo QuotaDay: day, CacheKey: cache.JobKey(r.extractor, r.videoID, string(p.Profile)), Cacheable: r.cacheable, + // Sites that refuse some networks are routed to workers that carry + // the tags the owner configured for them. + RequiredTags: s.cfg.RequiredTags(p.Info.Site), } if p.OneOff != nil { // Prepaid by invoice. Remember the amount and the payer's wallet so @@ -622,6 +631,18 @@ func (s *Service) Release(ctx context.Context, deliveryID string) (refunded int6 return refunded, err } +// Refunded returns the sats that were given back for a delivery, whoever +// did it and whenever. Several paths can release a delivery (the cancel +// handler, the failure handler, the periodic sweep) and only one of them +// wins; the message to the user should mention the refund regardless. +func (s *Service) Refunded(ctx context.Context, deliveryID string) int64 { + d, err := s.store.GetDelivery(ctx, deliveryID) + if err != nil || !d.Released || d.Status == db.DeliverySent || d.WalletID == "" { + return 0 + } + return d.ChargeSats +} + // RecordDelivered adds the delivered bytes to the requester's daily volume. func (s *Service) RecordDelivered(ctx context.Context, d *db.Delivery, bytes int64) error { day := d.QuotaDay diff --git a/internal/storage/local_test.go b/internal/storage/local_test.go index f3bc418..24615e5 100644 --- a/internal/storage/local_test.go +++ b/internal/storage/local_test.go @@ -1,24 +1,43 @@ package storage import ( + "bytes" "context" "errors" "io" + "net/http" + "net/http/httptest" "os" + "sort" "strings" "testing" + "time" + + "github.com/johannesboyne/gofakes3" + "github.com/johannesboyne/gofakes3/backend/s3mem" ) -func TestLocalRoundTrip(t *testing.T) { +// conformance is the behavior every backend must show. It runs against +// the local disk and against S3. +func conformance(t *testing.T, st Storage) { + t.Helper() ctx := context.Background() - st, err := NewLocal(t.TempDir()) - if err != nil { + key := "jobs/a/media" + + if _, _, err := st.Open(ctx, key); !errors.Is(err, ErrNotFound) { + t.Fatalf("Open of a missing key: %v, want ErrNotFound", err) + } + if _, err := st.Stat(ctx, key); !errors.Is(err, ErrNotFound) { + t.Fatalf("Stat of a missing key: %v, want ErrNotFound", err) + } + if err := st.Delete(ctx, key); err != nil { + t.Fatalf("Delete of a missing key must be a no-op: %v", err) + } + + if err := st.Put(ctx, key, strings.NewReader("hello"), 5); err != nil { t.Fatal(err) } - if err := st.Put(ctx, "jobs/a/media.mp4", strings.NewReader("hello"), 5); err != nil { - t.Fatal(err) - } - rc, size, err := st.Open(ctx, "jobs/a/media.mp4") + rc, size, err := st.Open(ctx, key) if err != nil { t.Fatal(err) } @@ -27,42 +46,176 @@ func TestLocalRoundTrip(t *testing.T) { if string(b) != "hello" || size != 5 { t.Fatalf("got %q size %d", b, size) } - obj, err := st.Stat(ctx, "jobs/a/media.mp4") - if err != nil || obj.Size != 5 { + obj, err := st.Stat(ctx, key) + if err != nil || obj.Size != 5 || obj.Key != key || time.Since(obj.ModTime) > time.Hour { t.Fatalf("Stat = %+v, %v", obj, err) } + // Put replaces, and works without a known size. + if err := st.Put(ctx, key, io.MultiReader(strings.NewReader("new "), strings.NewReader("content")), -1); err != nil { + t.Fatal(err) + } + rc, size, err = st.Open(ctx, key) + if err != nil { + t.Fatal(err) + } + b, _ = io.ReadAll(rc) + rc.Close() + if string(b) != "new content" || size != 11 { + t.Fatalf("after replace got %q size %d", b, size) + } + + for _, k := range []string{"jobs/b/media", "cache/x"} { + if err := st.Put(ctx, k, strings.NewReader("x"), 1); err != nil { + t.Fatal(err) + } + } var keys []string if err := st.List(ctx, "jobs/", func(o Object) error { keys = append(keys, o.Key); return nil }); err != nil { t.Fatal(err) } - if len(keys) != 1 || keys[0] != "jobs/a/media.mp4" { - t.Fatalf("List = %v", keys) + sort.Strings(keys) + if strings.Join(keys, ",") != "jobs/a/media,jobs/b/media" { + t.Fatalf("List(jobs/) = %v", keys) + } + stop := errors.New("stop") + if err := st.List(ctx, "", func(Object) error { return stop }); !errors.Is(err, stop) { + t.Fatalf("List must pass the callback's error on: %v", err) } - if err := st.Delete(ctx, "jobs/a/media.mp4"); err != nil { + if err := st.Delete(ctx, key); err != nil { t.Fatal(err) } - if _, _, err := st.Open(ctx, "jobs/a/media.mp4"); !errors.Is(err, ErrNotFound) { + if _, _, err := st.Open(ctx, key); !errors.Is(err, ErrNotFound) { t.Fatalf("Open after delete: %v", err) } - if err := st.Delete(ctx, "jobs/a/media.mp4"); err != nil { - t.Fatalf("second delete should be a no-op: %v", err) - } - if _, err := os.Stat(st.root + "/jobs"); !os.IsNotExist(err) { - t.Fatalf("empty parent directories should be removed") + for _, bad := range []string{"", "/abs", "../x", "a/../../x"} { + if err := st.Put(ctx, bad, strings.NewReader("x"), 1); err == nil { + t.Errorf("Put(%q) should fail", bad) + } } } -func TestLocalRejectsEscapingKeys(t *testing.T) { - ctx := context.Background() +func TestLocalConformance(t *testing.T) { st, err := NewLocal(t.TempDir()) if err != nil { t.Fatal(err) } - for _, key := range []string{"", "/abs", "../x", "a/../../x", "a//b", "a/./b", `a\b`} { - if err := st.Put(ctx, key, strings.NewReader("x"), 1); err == nil { + conformance(t, st) + // Local specifics: empty parent directories are removed, and keys + // cannot be used to walk out of the root. + if _, err := os.Stat(st.root + "/jobs/a"); !os.IsNotExist(err) { + t.Fatal("empty parent directories should be removed") + } + for _, key := range []string{"a//b", "a/./b", `a\b`} { + if err := st.Put(context.Background(), key, strings.NewReader("x"), 1); err == nil { t.Errorf("Put(%q) should fail", key) } } + if _, ok := Storage(st).(Presigner); ok { + t.Fatal("local storage has no presigned URLs") + } +} + +// fakeS3 starts an in-memory S3 server with one bucket. +func fakeS3(t *testing.T, bucket string) string { + t.Helper() + backend := s3mem.New() + if err := backend.CreateBucket(bucket); err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(gofakes3.New(backend).Server()) + t.Cleanup(srv.Close) + return srv.URL +} + +func TestS3Conformance(t *testing.T) { + endpoint := fakeS3(t, "dlbot") + for _, prefix := range []string{"", "tenant-a"} { + st, err := NewS3(context.Background(), S3Config{ + Endpoint: endpoint, Bucket: "dlbot", AccessKey: "k", SecretKey: "s", Region: "us-east-1", + PathStyle: true, Prefix: prefix, Presign: true, + }) + if err != nil { + t.Fatal(err) + } + conformance(t, st) + } +} + +func TestS3PresignedURLs(t *testing.T) { + endpoint := fakeS3(t, "dlbot") + ctx := context.Background() + st, err := NewS3(ctx, S3Config{ + Endpoint: endpoint, Bucket: "dlbot", AccessKey: "k", SecretKey: "s", Region: "us-east-1", + PathStyle: true, Prefix: "p", Presign: true, + }) + if err != nil { + t.Fatal(err) + } + putURL, err := st.PresignPut(ctx, "jobs/z/media", time.Minute) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(putURL, "/dlbot/p/jobs/z/media") || !strings.Contains(putURL, "X-Amz-Signature=") { + t.Fatalf("presigned PUT url = %s", putURL) + } + // A worker uploads with nothing but the URL: no keys, no bearer token. + req, _ := http.NewRequest(http.MethodPut, putURL, bytes.NewReader([]byte("from a worker"))) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("presigned PUT answered %d", resp.StatusCode) + } + obj, err := st.Stat(ctx, "jobs/z/media") + if err != nil || obj.Size != 13 { + t.Fatalf("object after presigned PUT = %+v, %v", obj, err) + } + getURL, err := st.PresignGet(ctx, "jobs/z/media", time.Minute) + if err != nil { + t.Fatal(err) + } + resp, err = http.Get(getURL) + if err != nil { + t.Fatal(err) + } + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + if string(body) != "from a worker" { + t.Fatalf("presigned GET returned %q", body) + } + + // Presigning can be off, and a separate endpoint can be used for it. + off, _ := NewS3(ctx, S3Config{Endpoint: endpoint, Bucket: "dlbot", AccessKey: "k", SecretKey: "s", PathStyle: true}) + if _, err := off.PresignPut(ctx, "k", time.Minute); err == nil || off.Presigning() { + t.Fatal("presigning should be off by default") + } + pub, err := NewS3(ctx, S3Config{ + Endpoint: endpoint, Bucket: "dlbot", AccessKey: "k", SecretKey: "s", Region: "us-east-1", PathStyle: true, + Presign: true, PresignEndpoint: "https://files.example.com", + }) + if err != nil { + t.Fatal(err) + } + if u, _ := pub.PresignGet(ctx, "k", time.Minute); !strings.HasPrefix(u, "https://files.example.com/dlbot/k?") { + t.Fatalf("presign endpoint not used: %s", u) + } +} + +func TestS3ReportsMissingBucketAndBadConfig(t *testing.T) { + endpoint := fakeS3(t, "dlbot") + ctx := context.Background() + if _, err := NewS3(ctx, S3Config{Endpoint: endpoint, Bucket: "nope", AccessKey: "k", SecretKey: "s", PathStyle: true}); err == nil || + !strings.Contains(err.Error(), "does not exist") { + t.Fatalf("missing bucket: %v", err) + } + if _, err := NewS3(ctx, S3Config{Bucket: "dlbot"}); err == nil { + t.Fatal("an empty endpoint must be rejected") + } + if _, err := NewS3(ctx, S3Config{Endpoint: endpoint}); err == nil { + t.Fatal("an empty bucket must be rejected") + } } diff --git a/internal/storage/s3.go b/internal/storage/s3.go new file mode 100644 index 0000000..2faea8b --- /dev/null +++ b/internal/storage/s3.go @@ -0,0 +1,247 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "time" + + "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7/pkg/credentials" +) + +// S3Config describes an S3 compatible bucket (AWS S3, Garage, MinIO, ...). +type S3Config struct { + // Endpoint is host:port, or a URL whose scheme decides TLS. + Endpoint string + Region string + Bucket string + AccessKey string + SecretKey string + // UseSSL is used when Endpoint has no scheme. + UseSSL bool + // PathStyle addresses the bucket as /bucket/key instead of as a + // subdomain. Garage and MinIO need it. + PathStyle bool + // Prefix is put in front of every key, to share a bucket. + Prefix string + // Presign turns on presigned URLs, so workers send files straight to + // the bucket instead of through the core. + Presign bool + // PresignEndpoint is the endpoint workers reach the bucket at, when it + // differs from the one the core uses (for example a public hostname + // versus a private network address). Empty means Endpoint. + PresignEndpoint string +} + +// S3 stores files in an S3 compatible bucket. +type S3 struct { + client *minio.Client + signer *minio.Client + bucket string + prefix string + presign bool +} + +var _ Storage = (*S3)(nil) + +func newS3Client(cfg S3Config, endpoint string) (*minio.Client, error) { + secure := cfg.UseSSL + if u, err := url.Parse(endpoint); err == nil && u.Scheme != "" && u.Host != "" { + secure = u.Scheme == "https" + endpoint = u.Host + } + lookup := minio.BucketLookupAuto + if cfg.PathStyle { + lookup = minio.BucketLookupPath + } + return minio.New(endpoint, &minio.Options{ + Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""), + Secure: secure, + Region: cfg.Region, + BucketLookup: lookup, + }) +} + +// NewS3 connects to the bucket and checks that it is reachable. +func NewS3(ctx context.Context, cfg S3Config) (*S3, error) { + if cfg.Endpoint == "" || cfg.Bucket == "" { + return nil, errors.New("storage: s3 needs an endpoint and a bucket") + } + client, err := newS3Client(cfg, cfg.Endpoint) + if err != nil { + return nil, fmt.Errorf("storage: s3: %w", err) + } + s := &S3{ + client: client, signer: client, bucket: cfg.Bucket, presign: cfg.Presign, + prefix: strings.Trim(cfg.Prefix, "/"), + } + if s.prefix != "" { + s.prefix += "/" + } + if cfg.PresignEndpoint != "" { + if s.signer, err = newS3Client(cfg, cfg.PresignEndpoint); err != nil { + return nil, fmt.Errorf("storage: s3 presign endpoint: %w", err) + } + } + cctx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + ok, err := client.BucketExists(cctx, cfg.Bucket) + if err != nil { + return nil, fmt.Errorf("storage: s3 bucket %q: %w", cfg.Bucket, err) + } + if !ok { + return nil, fmt.Errorf("storage: s3 bucket %q does not exist", cfg.Bucket) + } + return s, nil +} + +func (s *S3) key(key string) (string, error) { + if key == "" || strings.HasPrefix(key, "/") || strings.Contains(key, "..") || strings.ContainsRune(key, 0) { + return "", fmt.Errorf("storage: bad key %q", key) + } + return s.prefix + key, nil +} + +func notFoundS3(err error) error { + if err == nil { + return nil + } + resp := minio.ToErrorResponse(err) + if resp.StatusCode == http.StatusNotFound || resp.Code == "NoSuchKey" || resp.Code == "NotFound" { + return ErrNotFound + } + return err +} + +// Put implements Storage. The body is streamed; an unknown size (-1) makes +// the client upload in parts. +func (s *S3) Put(ctx context.Context, key string, r io.Reader, size int64) error { + k, err := s.key(key) + if err != nil { + return err + } + if size < 0 { + // Without a size the client would use a chunked streaming upload, + // which not every S3 compatible server understands. Spooling to a + // temp file first costs local disk and gives a plain upload that + // works everywhere. Callers normally know the size. + tmp, err := os.CreateTemp("", "dlbot-s3-*") + if err != nil { + return err + } + defer os.Remove(tmp.Name()) + defer tmp.Close() + if size, err = io.Copy(tmp, r); err != nil { + return err + } + if _, err := tmp.Seek(0, io.SeekStart); err != nil { + return err + } + r = tmp + } + _, err = s.client.PutObject(ctx, s.bucket, k, r, size, minio.PutObjectOptions{ContentType: "application/octet-stream"}) + return err +} + +// Open implements Storage. +func (s *S3) Open(ctx context.Context, key string) (io.ReadCloser, int64, error) { + k, err := s.key(key) + if err != nil { + return nil, 0, err + } + obj, err := s.client.GetObject(ctx, s.bucket, k, minio.GetObjectOptions{}) + if err != nil { + return nil, 0, notFoundS3(err) + } + st, err := obj.Stat() + if err != nil { + obj.Close() + return nil, 0, notFoundS3(err) + } + return obj, st.Size, nil +} + +// Stat implements Storage. +func (s *S3) Stat(ctx context.Context, key string) (Object, error) { + k, err := s.key(key) + if err != nil { + return Object{}, err + } + st, err := s.client.StatObject(ctx, s.bucket, k, minio.StatObjectOptions{}) + if err != nil { + return Object{}, notFoundS3(err) + } + return Object{Key: key, Size: st.Size, ModTime: st.LastModified}, nil +} + +// Delete implements Storage. +func (s *S3) Delete(ctx context.Context, key string) error { + k, err := s.key(key) + if err != nil { + return err + } + if err := s.client.RemoveObject(ctx, s.bucket, k, minio.RemoveObjectOptions{}); err != nil { + if errors.Is(notFoundS3(err), ErrNotFound) { + return nil + } + return err + } + return nil +} + +// List implements Storage. +func (s *S3) List(ctx context.Context, prefix string, fn func(Object) error) error { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + for info := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: s.prefix + prefix, Recursive: true}) { + if info.Err != nil { + return info.Err + } + if err := fn(Object{Key: strings.TrimPrefix(info.Key, s.prefix), Size: info.Size, ModTime: info.LastModified}); err != nil { + return err + } + } + return nil +} + +// Presigning reports whether presigned URLs are turned on. The worker API +// asks before it hands URLs to workers. +func (s *S3) Presigning() bool { return s.presign } + +// PresignPut implements Presigner. +func (s *S3) PresignPut(ctx context.Context, key string, ttl time.Duration) (string, error) { + if !s.presign { + return "", errors.New("storage: presigned urls are off") + } + k, err := s.key(key) + if err != nil { + return "", err + } + u, err := s.signer.PresignedPutObject(ctx, s.bucket, k, ttl) + if err != nil { + return "", err + } + return u.String(), nil +} + +// PresignGet implements Presigner. +func (s *S3) PresignGet(ctx context.Context, key string, ttl time.Duration) (string, error) { + if !s.presign { + return "", errors.New("storage: presigned urls are off") + } + k, err := s.key(key) + if err != nil { + return "", err + } + u, err := s.signer.PresignedGetObject(ctx, s.bucket, k, ttl, nil) + if err != nil { + return "", err + } + return u.String(), nil +} diff --git a/internal/storage/storage.go b/internal/storage/storage.go index be6f953..6a1185f 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -34,3 +34,13 @@ type Storage interface { // List calls fn for every object whose key starts with prefix. List(ctx context.Context, prefix string, fn func(Object) error) error } + +// Presigner is implemented by backends that can hand out time-limited +// URLs, so a worker or a browser can move file bytes directly to and from +// storage without passing through the core. +type Presigner interface { + // PresignPut returns a URL that accepts one HTTP PUT of the object. + PresignPut(ctx context.Context, key string, ttl time.Duration) (string, error) + // PresignGet returns a URL that serves the object to HTTP GET. + PresignGet(ctx context.Context, key string, ttl time.Duration) (string, error) +} diff --git a/internal/tg/fakeserver/server.go b/internal/tg/fakeserver/server.go index 3ce9107..a3093ba 100644 --- a/internal/tg/fakeserver/server.go +++ b/internal/tg/fakeserver/server.go @@ -120,8 +120,16 @@ type Server struct { closed bool } -// New starts a fake server. +// New starts a fake server on a random local port. func New() *Server { + s := NewHandler() + s.HTTP = httptest.NewServer(s) + return s +} + +// NewHandler returns a fake server that is not listening yet. It is an +// http.Handler, so a program can serve it on an address of its choice. +func NewHandler() *Server { s := &Server{ msgID: 1000, failures: map[string][]scriptedError{}, @@ -129,10 +137,12 @@ func New() *Server { sent: map[int]map[string]any{}, } s.cond = sync.NewCond(&s.mu) - s.HTTP = httptest.NewServer(http.HandlerFunc(s.handle)) return s } +// ServeHTTP implements http.Handler. +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.handle(w, r) } + // URL returns the API root to pass to the bot as TELEGRAM_API_URL. func (s *Server) URL() string { return s.HTTP.URL } @@ -142,8 +152,10 @@ func (s *Server) Close() { s.closed = true s.cond.Broadcast() s.mu.Unlock() - s.HTTP.CloseClientConnections() - s.HTTP.Close() + if s.HTTP != nil { + s.HTTP.CloseClientConnections() + s.HTTP.Close() + } } // FailNext makes the next call of a method fail with a Bot API error. diff --git a/internal/worker/httpcoord.go b/internal/worker/httpcoord.go new file mode 100644 index 0000000..285316f --- /dev/null +++ b/internal/worker/httpcoord.go @@ -0,0 +1,208 @@ +package worker + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "strings" + "time" + + "github.com/noderunners/dlbot/internal/workerproto" +) + +// HTTPCoordinator talks to the core's worker API. It is the Coordinator +// of the standalone worker binary. +type HTTPCoordinator struct { + base string + token string + // api is for the small JSON calls, files for uploads and downloads, + // which have no overall timeout and rely on the context instead. + api *http.Client + files *http.Client +} + +var _ Coordinator = (*HTTPCoordinator)(nil) + +// NewHTTPCoordinator creates a client for the core at baseURL. +func NewHTTPCoordinator(baseURL, token string) *HTTPCoordinator { + return &HTTPCoordinator{ + base: strings.TrimRight(baseURL, "/"), + token: token, + api: &http.Client{Timeout: 90 * time.Second}, + files: &http.Client{}, + } +} + +// StatusError is a non-2xx answer from the core. +type StatusError struct { + Code int + Msg string +} + +func (e *StatusError) Error() string { return fmt.Sprintf("core answered %d: %s", e.Code, e.Msg) } + +// LeaseLost reports that the core no longer considers the job ours. +func (e *StatusError) LeaseLost() bool { return e.Code == http.StatusConflict } + +// Unauthorized reports that the core rejected the worker's token. +func (e *StatusError) Unauthorized() bool { return e.Code == http.StatusUnauthorized } + +// IsUnauthorized reports whether err means the token was rejected, which +// no amount of retrying fixes. +func IsUnauthorized(err error) bool { + var se *StatusError + return errors.As(err, &se) && se.Unauthorized() +} + +func (c *HTTPCoordinator) call(ctx context.Context, path string, in, out any) error { + body, err := json.Marshal(in) + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.base+path, bytes.NewReader(body)) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+c.token) + req.Header.Set("Content-Type", "application/json") + resp, err := c.api.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + return decode(resp, out) +} + +func decode(resp *http.Response, out any) error { + data, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20)) + if err != nil { + return err + } + if resp.StatusCode < 200 || resp.StatusCode > 299 { + var e struct { + Error string `json:"error"` + } + _ = json.Unmarshal(data, &e) + if e.Error == "" { + e.Error = http.StatusText(resp.StatusCode) + } + return &StatusError{Code: resp.StatusCode, Msg: e.Error} + } + if out == nil || len(data) == 0 { + return nil + } + return json.Unmarshal(data, out) +} + +// ClaimAny asks for work and returns the whole response: a job, a probe +// task, and any commands for the worker. +func (c *HTTPCoordinator) ClaimAny(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.ClaimResponse, error) { + var resp workerproto.ClaimResponse + if err := c.call(ctx, "/worker/v1/claim", req, &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// Claim implements Coordinator. +func (c *HTTPCoordinator) Claim(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.Job, error) { + resp, err := c.ClaimAny(ctx, req) + if err != nil { + return nil, err + } + return resp.Job, nil +} + +// Heartbeat implements Coordinator. +func (c *HTTPCoordinator) Heartbeat(ctx context.Context, req workerproto.HeartbeatRequest) (workerproto.HeartbeatResponse, error) { + var resp workerproto.HeartbeatResponse + err := c.call(ctx, "/worker/v1/heartbeat", req, &resp) + return resp, err +} + +// Complete implements Coordinator. +func (c *HTTPCoordinator) Complete(ctx context.Context, req workerproto.CompleteRequest) error { + return c.call(ctx, "/worker/v1/complete", req, nil) +} + +// Fail implements Coordinator. +func (c *HTTPCoordinator) Fail(ctx context.Context, req workerproto.FailRequest) error { + return c.call(ctx, "/worker/v1/fail", req, nil) +} + +// ProbeResult answers a probe task. +func (c *HTTPCoordinator) ProbeResult(ctx context.Context, res workerproto.ProbeResult) error { + return c.call(ctx, "/worker/v1/probe", res, nil) +} + +// Upload implements Coordinator. With a presigned URL the file goes +// straight to storage; otherwise it is streamed to the core. Either way +// it is never read into memory. +func (c *HTTPCoordinator) Upload(ctx context.Context, job *workerproto.Job, path string) error { + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() + st, err := f.Stat() + if err != nil { + return err + } + url, direct := job.UploadURL, job.UploadURL != "" + if !direct { + url = c.base + "/worker/v1/upload/" + job.ID + } + req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, f) + if err != nil { + return err + } + req.ContentLength = st.Size() + req.Header.Set("Content-Type", "application/octet-stream") + if !direct { + // The bearer token is only ever sent to the core, never to storage. + req.Header.Set("Authorization", "Bearer "+c.token) + } + resp, err := c.files.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + return decode(resp, nil) +} + +// Fetch implements Coordinator. +func (c *HTTPCoordinator) Fetch(ctx context.Context, job *workerproto.Job, path string) error { + url, direct := job.SourceURL, job.SourceURL != "" + if !direct { + url = c.base + "/worker/v1/source/" + job.ID + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return err + } + if !direct { + req.Header.Set("Authorization", "Bearer "+c.token) + } + resp, err := c.files.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return decode(resp, nil) + } + out, err := os.Create(path) + if err != nil { + return err + } + if _, err := io.Copy(out, resp.Body); err != nil { + out.Close() + return err + } + return out.Close() +} diff --git a/internal/worker/worker.go b/internal/worker/worker.go index c3c60cb..f161acf 100644 --- a/internal/worker/worker.go +++ b/internal/worker/worker.go @@ -5,6 +5,7 @@ package worker import ( "context" + "encoding/json" "errors" "log/slog" "math" @@ -45,6 +46,21 @@ type Config struct { Heartbeat time.Duration // ClaimWait is how long one claim call may wait for work. ClaimWait time.Duration + // ProbeSlots is the number of extra claim loops that only take + // metadata lookups. They need a Prober coordinator and are 0 for the + // embedded worker, whose core runs lookups itself. + ProbeSlots int + // Version returns the yt-dlp version to report. It may be nil. + Version func() string + // OnCommand is called for instructions from the core. It may be nil. + OnCommand func(cmd string) +} + +// Prober is the part of a coordinator that hands out metadata lookups. +// Only the HTTP coordinator implements it. +type Prober interface { + ClaimAny(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.ClaimResponse, error) + ProbeResult(ctx context.Context, res workerproto.ProbeResult) error } // Worker runs download jobs. @@ -55,6 +71,16 @@ type Worker struct { trans ffmpeg.Transcoder log *slog.Logger active atomic.Int32 + // lastOK is the unix time of the last call the core answered. + lastOK atomic.Int64 + // authFailed is set when the core rejected the token. + authFailed atomic.Bool +} + +// LastContact returns when the core last answered a claim, and whether +// the worker's token was rejected. +func (w *Worker) LastContact() (time.Time, bool) { + return time.Unix(w.lastOK.Load(), 0), w.authFailed.Load() } // SetTranscoder gives the worker the means to run derive jobs. Without it @@ -88,6 +114,7 @@ func (w *Worker) Run(ctx context.Context) { w.log.Error("cannot create temp dir", "dir", w.cfg.TempDir, "err", err) } w.sweepOrphans() + w.lastOK.Store(time.Now().Unix()) var wg sync.WaitGroup for i := 0; i < w.cfg.Concurrency; i++ { wg.Add(1) @@ -96,9 +123,99 @@ func (w *Worker) Run(ctx context.Context) { w.slot(ctx) }() } + if prober, ok := w.coord.(Prober); ok { + for i := 0; i < w.cfg.ProbeSlots; i++ { + wg.Add(1) + go func() { + defer wg.Done() + w.probeSlot(ctx, prober) + }() + } + } wg.Wait() } +func (w *Worker) claimRequest(probeOnly bool) workerproto.ClaimRequest { + req := workerproto.ClaimRequest{ + WorkerID: w.cfg.ID, + Tags: w.cfg.Tags, + Capacity: w.cfg.Concurrency, + Active: w.Active(), + WaitSeconds: int(math.Ceil(w.cfg.ClaimWait.Seconds())), + ProbeOnly: probeOnly, + } + if w.cfg.Version != nil { + req.Version = w.cfg.Version() + } + return req +} + +// noteClaim records the outcome of a claim for the health endpoint and +// returns how long to wait before the next one after an error. +func (w *Worker) noteClaim(err error, backoff *time.Duration) { + if err == nil { + w.lastOK.Store(time.Now().Unix()) + w.authFailed.Store(false) + *backoff = time.Second + return + } + if IsUnauthorized(err) { + // A revoked or wrong token will not start working by itself. Keep + // asking, slowly, in case the owner issues the token again. + w.authFailed.Store(true) + *backoff = time.Minute + } +} + +// probeSlot takes metadata lookups from the core, one at a time. +func (w *Worker) probeSlot(ctx context.Context, prober Prober) { + backoff := time.Second + for ctx.Err() == nil { + resp, err := prober.ClaimAny(ctx, w.claimRequest(true)) + w.noteClaim(err, &backoff) + if err != nil { + if ctx.Err() != nil { + return + } + w.log.Warn("probe claim failed", "err", err, "retry_in", backoff.String()) + sleep(ctx, backoff) + if backoff < 30*time.Second { + backoff *= 2 + } + continue + } + w.runCommands(resp.Commands) + if resp.Probe == nil { + continue + } + res := workerproto.ProbeResult{WorkerID: w.cfg.ID, ID: resp.Probe.ID} + info, perr := w.runner.Probe(ctx, resp.Probe.URL) + if perr != nil { + var ye *ytdlp.Error + if !errors.As(perr, &ye) { + ye = &ytdlp.Error{Code: ytdlp.CodeUnknown, Retryable: true, Raw: perr.Error()} + } + res.Code, res.Retryable, res.Detail = string(ye.Code), ye.Retryable, ye.Raw + } else if res.Info, err = json.Marshal(info); err != nil { + res.Code, res.Detail = string(ytdlp.CodeInternal), err.Error() + } + rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second) + if err := prober.ProbeResult(rctx, res); err != nil { + w.log.Debug("probe result not accepted", "err", err) + } + cancel() + } +} + +func (w *Worker) runCommands(cmds []string) { + if w.cfg.OnCommand == nil { + return + } + for _, c := range cmds { + w.cfg.OnCommand(c) + } +} + // sweepOrphans removes job directories left behind by a crash. A worker is // stateless, so nothing in its temp dir is valid at startup. Only names // that look like job IDs are touched, and every worker process must have @@ -123,13 +240,20 @@ func (w *Worker) sweepOrphans() { func (w *Worker) slot(ctx context.Context) { backoff := time.Second for ctx.Err() == nil { - job, err := w.coord.Claim(ctx, workerproto.ClaimRequest{ - WorkerID: w.cfg.ID, - Tags: w.cfg.Tags, - Capacity: w.cfg.Concurrency, - Active: w.Active(), - WaitSeconds: int(math.Ceil(w.cfg.ClaimWait.Seconds())), - }) + var ( + job *workerproto.Job + err error + ) + if prober, ok := w.coord.(Prober); ok { + var resp *workerproto.ClaimResponse + if resp, err = prober.ClaimAny(ctx, w.claimRequest(false)); err == nil { + job = resp.Job + w.runCommands(resp.Commands) + } + } else { + job, err = w.coord.Claim(ctx, w.claimRequest(false)) + } + w.noteClaim(err, &backoff) if err != nil { if ctx.Err() != nil { return @@ -141,7 +265,6 @@ func (w *Worker) slot(ctx context.Context) { } continue } - backoff = time.Second if job == nil { continue // the coordinator already waited for ClaimWait } @@ -163,6 +286,7 @@ func (w *Worker) process(ctx context.Context, job *workerproto.Job) { jobCtx, cancel := context.WithCancel(ctx) defer cancel() + log.Info("job started", "kind", job.Kind, "profile", job.Profile) var ( mu sync.Mutex diff --git a/internal/workerproto/proto.go b/internal/workerproto/proto.go index 754ac59..9a0810c 100644 --- a/internal/workerproto/proto.go +++ b/internal/workerproto/proto.go @@ -20,8 +20,37 @@ type ClaimRequest struct { Active int `json:"active"` // WaitSeconds lets the core hold the request until work arrives. WaitSeconds int `json:"wait_seconds,omitempty"` + // ProbeOnly asks for a metadata lookup instead of a download job. + // Workers keep a few extra requests of this kind open so that cards + // appear quickly even when all download slots are busy. + ProbeOnly bool `json:"probe_only,omitempty"` + // Version is the worker's yt-dlp version, for the owner's overview. + Version string `json:"version,omitempty"` } +// ProbeTask asks a worker to look up the metadata of a URL. +type ProbeTask struct { + ID string `json:"id"` + URL string `json:"url"` +} + +// ProbeResult is the answer to a ProbeTask: the yt-dlp info JSON, or a +// failure class. +type ProbeResult struct { + WorkerID string `json:"worker_id"` + ID string `json:"id"` + Info []byte `json:"info,omitempty"` + Code string `json:"code,omitempty"` + Retryable bool `json:"retryable,omitempty"` + Detail string `json:"detail,omitempty"` +} + +// Commands the core can give a worker in a claim response. +const ( + // CommandUpdateYtDlp asks the worker to update yt-dlp now. + CommandUpdateYtDlp = "ytdlp_update" +) + // Job is the work handed to a worker. type Job struct { ID string `json:"id"` @@ -37,14 +66,24 @@ type Job struct { SourceKey string `json:"source_key,omitempty"` // UploadKey is the storage key the result must be uploaded to. UploadKey string `json:"upload_key"` + // UploadURL, when set, is a presigned URL to PUT the result to. Without + // it the worker streams the file to the core's upload endpoint. + UploadURL string `json:"upload_url,omitempty"` + // SourceURL, when set, is a presigned URL to GET a derive job's source + // from. Without it the worker asks the core's source endpoint. + SourceURL string `json:"source_url,omitempty"` Attempt int `json:"attempt"` // LeaseSeconds is how long the job stays owned without a heartbeat. LeaseSeconds int `json:"lease_seconds"` } -// ClaimResponse carries a job, or nil when the queue has nothing suitable. +// ClaimResponse carries a job or a probe task, or neither when there is +// nothing suitable. type ClaimResponse struct { - Job *Job `json:"job"` + Job *Job `json:"job"` + Probe *ProbeTask `json:"probe,omitempty"` + // Commands are instructions for the worker itself. + Commands []string `json:"commands,omitempty"` } // HeartbeatRequest extends the lease and reports progress. diff --git a/internal/ytdlp/exec.go b/internal/ytdlp/exec.go index 82fe48f..4852359 100644 --- a/internal/ytdlp/exec.go +++ b/internal/ytdlp/exec.go @@ -70,6 +70,23 @@ func (e *Exec) Version(ctx context.Context) (string, error) { return strings.TrimSpace(string(out)), nil } +// Update asks yt-dlp to update itself and returns its output. It works +// for the standalone release binaries; a yt-dlp installed by a package +// manager refuses and says how it should be updated instead. +func (e *Exec) Update(ctx context.Context) (string, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Minute) + defer cancel() + out, err := exec.CommandContext(ctx, e.bin(), "-U").CombinedOutput() + text := strings.TrimSpace(string(out)) + if len(text) > 500 { + text = text[len(text)-500:] + } + if err != nil { + return text, fmt.Errorf("ytdlp: update: %w", err) + } + return text, nil +} + // Probe implements Runner. It asks for one JSON document, which is either a // single video or a flat playlist listing. func (e *Exec) Probe(ctx context.Context, url string) (*Info, error) { diff --git a/locales/en.toml b/locales/en.toml index c0b162e..fc3c987 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -354,6 +354,18 @@ line = "{{.N}}. {{.Title}} · {{.Label}}" # --- Owner commands --------------------------------------------------------- [owner] +never = "never" +state_active = "active" +state_offline = "offline" +state_draining = "draining" +state_revoked = "revoked" +worker_embedded = "embedded · {{.Running}} of {{.Capacity}} slots busy" +worker_line = "{{.Name}} · {{.State}} · {{.Running}} of {{.Capacity}} slots busy · seen {{.Seen}} ago\ntags: {{.Tags}} · yt-dlp {{.Version}}" +worker_unknown = "There is no worker named {{.Name}}." +drain_usage = "Name the worker.\nExample: /drain eu-1, and /drain eu-1 off to bring it back." +drain_on = "Worker {{.Name}} is draining. It finishes its jobs and gets no new ones." +drain_off = "Worker {{.Name}} takes jobs again." +ytdlp_usage = "Use /ytdlp update to update yt-dlp on every worker." purge_usage = "Send a link, or a key as extractor:video_id.\nExample: /purge https://example.com/video copyright notice" cache = """ Cache @@ -366,6 +378,14 @@ Taken down: {{.Blocked}} Hit rate: {{.Rate}} of {{.Since}} requests Download volume saved: {{.Saved}}""" +[owner.workers_header] +one = "Workers\n{{.Slots}} download slots online, {{.Count}} remote worker registered." +other = "Workers\n{{.Slots}} download slots online, {{.Count}} remote workers registered." + +[owner.ytdlp_update] +one = "Asked {{.Count}} worker to update yt-dlp. It does so when it next checks for work." +other = "Asked {{.Count}} workers to update yt-dlp. They do so when they next check for work." + [owner.purged] one = "Taken down: {{.Key}}\n{{.Count}} cached file was removed. The key is blocked." other = "Taken down: {{.Key}}\n{{.Count}} cached files were removed. The key is blocked."