From 3c153af97fe2b28efd19ba05aa5996cc6ff2b6c7 Mon Sep 17 00:00:00 2001 From: Michilis Date: Wed, 18 Nov 2026 18:24:36 +0000 Subject: [PATCH] Phase 8: widgets and polish - Live job card widget (progress bar, in-widget cancel via widget_query) and live invoice widget (QR drawn from a bitmap, countdown, paid state), Bot API 10.4 sendWidget, private chats only - Automatic fallback to the ordinary message when sendWidget fails, with a breaker that pauses widgets after repeated failures or on servers without the method; TELEGRAM_WIDGETS - Prometheus metrics on the core (/metrics) and on every worker: queue depth and wait, slots, heartbeats, job outcomes, errors per site, deliveries, cache, invoices, Lightning, ledger check, widgets - Example Prometheus config and alert rules, Caddyfile, dashboard notes - Load test: cmd/loadtest and deploy/loadtest (make loadtest) - Browser check of the widgets' HTML, including decoding a drawn QR - docs/DEPLOY.md (production in under an hour) and docs/MONITORING.md Co-Authored-By: Claude Opus 5.5 --- .env.example | 10 + Makefile | 7 +- README.md | 20 +- cmd/loadtest/main.go | 308 +++++++++++++++++ cmd/worker/main.go | 12 +- config.example.toml | 2 + deploy/caddy/Caddyfile | 15 + deploy/loadtest/fake-yt-dlp.sh | 40 +++ deploy/loadtest/run.sh | 102 ++++++ deploy/prometheus/alerts.yml | 75 +++++ deploy/prometheus/prometheus.yml | 21 ++ docs/ARCHITECTURE.md | 39 +++ docs/ASSUMPTIONS.md | 97 ++++++ docs/DEPLOY.md | 176 ++++++++++ docs/MONITORING.md | 156 +++++++++ docs/OPERATIONS.md | 22 +- docs/WORKERS.md | 2 +- go.mod | 7 + go.sum | 14 + internal/app/app.go | 62 +++- internal/app/app_test.go | 2 + internal/app/widgets_test.go | 341 +++++++++++++++++++ internal/bot/bot.go | 39 +++ internal/bot/deliver.go | 5 + internal/bot/live.go | 402 +++++++++++++++++++++++ internal/bot/money.go | 13 +- internal/bot/status.go | 37 +++ internal/config/config.go | 10 +- internal/db/migrations/00006_widgets.sql | 16 + internal/db/widgets.go | 47 +++ internal/metrics/metrics.go | 338 +++++++++++++++++++ internal/metrics/metrics_test.go | 102 ++++++ internal/tg/api.go | 3 + internal/tg/fakeserver/server.go | 26 +- internal/widget/invoice.html | 37 +++ internal/widget/job.html | 30 ++ internal/widget/testdata/qr.json | 5 + internal/widget/widget.go | 229 +++++++++++++ internal/widget/widget_test.go | 135 ++++++++ internal/worker/worker.go | 32 ++ web/miniapp/dist/source.sha256 | 2 +- web/miniapp/e2e/run.sh | 2 +- web/miniapp/e2e/widgets.mjs | 129 ++++++++ web/miniapp/package-lock.json | 8 + web/miniapp/package.json | 1 + 45 files changed, 3158 insertions(+), 20 deletions(-) create mode 100644 cmd/loadtest/main.go create mode 100644 deploy/caddy/Caddyfile create mode 100755 deploy/loadtest/fake-yt-dlp.sh create mode 100755 deploy/loadtest/run.sh create mode 100644 deploy/prometheus/alerts.yml create mode 100644 deploy/prometheus/prometheus.yml create mode 100644 docs/DEPLOY.md create mode 100644 docs/MONITORING.md create mode 100644 internal/app/widgets_test.go create mode 100644 internal/bot/live.go create mode 100644 internal/db/migrations/00006_widgets.sql create mode 100644 internal/db/widgets.go create mode 100644 internal/metrics/metrics.go create mode 100644 internal/metrics/metrics_test.go create mode 100644 internal/widget/invoice.html create mode 100644 internal/widget/job.html create mode 100644 internal/widget/testdata/qr.json create mode 100644 internal/widget/widget.go create mode 100644 internal/widget/widget_test.go create mode 100644 web/miniapp/e2e/widgets.mjs diff --git a/.env.example b/.env.example index b5e54a7..da7f53f 100644 --- a/.env.example +++ b/.env.example @@ -9,6 +9,10 @@ BOT_TOKEN= TELEGRAM_API_URL=https://api.telegram.org # polling (default) or webhook. TELEGRAM_MODE=polling +# Prometheus metrics at /metrics on HTTP_LISTEN. Keep the path off the +# public internet; see docs/MONITORING.md. +METRICS_ENABLED=true + # Public HTTPS base URL of this server. Only for webhook mode. Telegram will # call /telegram/webhook. WEBHOOK_URL= @@ -37,6 +41,12 @@ MINIAPP_ENABLED=false # set in @BotFather. TELEGRAM_SET_PROFILE=true +# Show the download status and invoices as live HTML widgets in private +# chats (Bot API 10.4 sendWidget): a progress bar with a cancel button, and +# an invoice with a QR code, a countdown and its paid state. If Telegram +# refuses a widget the bot sends the ordinary message instead, by itself. +TELEGRAM_WIDGETS=true + # Add the pseudo-locale en-XA (accented, bracketed English) for checking # that every text comes from the catalog. Only owners can pick it. I18N_PSEUDO=false diff --git a/Makefile b/Makefile index 6279171..76a5eef 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ GO ?= go BIN := bin VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev) -.PHONY: all build faketelegram miniapp miniapp-e2e i18n-check test test-postgres race vet fmt check run e2e acceptance clean +.PHONY: all build faketelegram miniapp miniapp-e2e i18n-check loadtest test test-postgres race vet fmt check run e2e acceptance clean all: check build @@ -54,6 +54,11 @@ 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 ./... +# Many simulated users against a real core and workers, on the fake Bot +# API and a yt-dlp stand-in. USERS, LINKS, WORKERS, SLOTS: see the script. +loadtest: + deploy/loadtest/run.sh + # Kill a worker mid-job and watch the other one finish it. MODE=compose # runs it in containers. acceptance: diff --git a/README.md b/README.md index afd35a6..9bc9e47 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,12 @@ and in groups. Written in Go on top of yt-dlp. the bot's profile texts and the Mini App, with numbers, sizes and dates in the language's own format. Each user's Telegram language is followed, and `/language` overrides it; `/grouplang` sets a group's. +- Live widgets in private chats (Bot API 10.4): the download status as a + progress bar with a cancel button, and the invoice with its QR code, a + countdown and the paid state. When Telegram refuses a widget the bot + uses the ordinary message, without anyone noticing. +- Prometheus metrics on the core and every worker, example alert rules, + dashboard notes and a load test. - Friendly, translated error messages. Raw tool output stays in the logs. ## Quick start with docker compose @@ -53,8 +59,10 @@ cp .env.example .env # set BOT_TOKEN, OWNER_IDS, WORKER_A_TOKEN, WORKER_B_TO 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. +This runs the core and two workers. [docs/DEPLOY.md](docs/DEPLOY.md) is a +step by step guide to a production setup with TLS, payments, the Mini App +and monitoring in under an hour; [docs/OPERATIONS.md](docs/OPERATIONS.md) +covers Postgres, S3, 2 GB uploads and the other choices. ## Quick start from source @@ -191,7 +199,8 @@ make test-postgres PG_DSN=postgres://... # the same suite on Postgres make acceptance # kill a worker mid-job, watch the other finish make i18n-check # translation completeness and consistency only make miniapp # rebuild the Mini App front end after changing web/miniapp -make miniapp-e2e # click through the Mini App in headless Chromium +make miniapp-e2e # click through the Mini App and the widgets in headless Chromium +make loadtest # many simulated users against a real core and workers ``` The tests need neither a bot token nor network access. They run the real @@ -204,7 +213,9 @@ change it. A test fails when `dist` is older than its sources. ## Documentation +- [docs/DEPLOY.md](docs/DEPLOY.md): from nothing to production in under an hour. - [docs/OPERATIONS.md](docs/OPERATIONS.md): deploying and running it. +- [docs/MONITORING.md](docs/MONITORING.md): metrics, dashboards, alerts, load test. - [docs/WORKERS.md](docs/WORKERS.md): adding download workers, tags, drain. - [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): how the pieces fit. - [docs/TRANSLATING.md](docs/TRANSLATING.md): editing a catalog, adding a language. @@ -216,6 +227,7 @@ change it. A test fails when `dist` is older than its sources. 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 +cmd/loadtest simulated users for load tests deploy Dockerfile, systemd units, acceptance script internal/bot Telegram handlers, cards, status, delivery internal/service download rules shared by all front ends @@ -229,6 +241,8 @@ internal/ytdlp yt-dlp and ffprobe wrapper internal/db migrations and queries internal/storage file storage backends internal/i18n translations and formatting +internal/widget the HTML widgets (status, invoice) and their limits +internal/metrics Prometheus metrics of the core and the worker internal/api HTTP: health, payment webhook, worker protocol, Mini App API web/miniapp the Mini App front end (Vite, React) and its embedded build locales translation catalogs diff --git a/cmd/loadtest/main.go b/cmd/loadtest/main.go new file mode 100644 index 0000000..2b4bd0e --- /dev/null +++ b/cmd/loadtest/main.go @@ -0,0 +1,308 @@ +// Command loadtest plays many Telegram users against a core that runs on +// the fake Bot API (cmd/faketelegram). Each user sends links, picks a +// format on the card and waits for the file. It reports how many files +// arrived, how long they took and what went wrong. +// +// deploy/loadtest/run.sh starts everything it needs; see docs/OPERATIONS.md. +// +// loadtest -fake http://127.0.0.1:18090 -users 50 -links 4 -ramp 20s +package main + +import ( + "bytes" + "encoding/json" + "flag" + "fmt" + "io" + "math/rand/v2" + "net/http" + "os" + "sort" + "strconv" + "strings" + "sync" + "time" +) + +type call struct { + Seq int `json:"seq"` + Method string `json:"method"` + MessageID int `json:"message_id"` + Text string `json:"text"` + Params map[string]string `json:"params"` + Buttons []string `json:"buttons"` + Failed bool `json:"failed"` +} + +// chat collects the calls the bot made to one chat. +type chat struct { + mu sync.Mutex + calls []call + wake chan struct{} +} + +type hub struct { + fake string + mu sync.Mutex + chats map[string]*chat +} + +func (h *hub) chat(id string) *chat { + h.mu.Lock() + defer h.mu.Unlock() + c := h.chats[id] + if c == nil { + c = &chat{wake: make(chan struct{}, 1)} + h.chats[id] = c + } + return c +} + +// poll fetches new calls from the fake server and files them by chat. +func (h *hub) poll(stop <-chan struct{}) { + after := 0 + for { + select { + case <-stop: + return + case <-time.After(150 * time.Millisecond): + } + res, err := http.Get(h.fake + "/control/calls?after=" + strconv.Itoa(after)) + if err != nil { + continue + } + var calls []call + _ = json.NewDecoder(res.Body).Decode(&calls) + res.Body.Close() + for _, c := range calls { + if c.Seq > after { + after = c.Seq + } + id := c.Params["chat_id"] + if id == "" { + continue + } + ch := h.chat(id) + ch.mu.Lock() + ch.calls = append(ch.calls, c) + ch.mu.Unlock() + select { + case ch.wake <- struct{}{}: + default: + } + } + } +} + +// waitFor returns the first call at or after index from that matches. +func (c *chat) waitFor(from int, timeout time.Duration, match func(call) bool) (call, int, bool) { + deadline := time.After(timeout) + for { + c.mu.Lock() + for i := from; i < len(c.calls); i++ { + if match(c.calls[i]) { + got := c.calls[i] + c.mu.Unlock() + return got, i + 1, true + } + } + from = len(c.calls) + c.mu.Unlock() + select { + case <-c.wake: + case <-deadline: + return call{}, from, false + } + } +} + +func post(fake, path string, body any) error { + b, _ := json.Marshal(body) + res, err := http.Post(fake+path, "application/json", bytes.NewReader(b)) + if err != nil { + return err + } + defer res.Body.Close() + if res.StatusCode != 200 { + msg, _ := io.ReadAll(res.Body) + return fmt.Errorf("%s: %d %s", path, res.StatusCode, msg) + } + return nil +} + +type result struct { + outcome string // delivered, failed, refused, timeout + reason string + card time.Duration + total time.Duration +} + +func main() { + fake := flag.String("fake", "http://127.0.0.1:18090", "address of cmd/faketelegram") + users := flag.Int("users", 20, "simulated users") + links := flag.Int("links", 3, "links each user downloads, one after another") + ramp := flag.Duration("ramp", 10*time.Second, "time over which the users start") + share := flag.Float64("share", 0.2, "share of requests for one popular link (cache hits and shared downloads)") + timeout := flag.Duration("timeout", 3*time.Minute, "how long a user waits for a file") + firstID := flag.Int64("first-id", 7_000_000, "Telegram ID of the first user") + flag.Parse() + + h := &hub{fake: strings.TrimRight(*fake, "/"), chats: map[string]*chat{}} + stop := make(chan struct{}) + go h.poll(stop) + + var ( + mu sync.Mutex + results []result + wg sync.WaitGroup + ) + started := time.Now() + for u := 0; u < *users; u++ { + wg.Add(1) + uid := *firstID + int64(u) + delay := time.Duration(0) + if *users > 1 { + delay = *ramp * time.Duration(u) / time.Duration(*users-1) + } + go func() { + defer wg.Done() + time.Sleep(delay) + c := h.chat(strconv.FormatInt(uid, 10)) + for l := 0; l < *links; l++ { + link := fmt.Sprintf("https://load.example.com/video/%d/%d", uid, l) + if rand.Float64() < *share { + link = "https://load.example.com/video/popular" + } + r := run(h.fake, c, uid, link, *timeout) + mu.Lock() + results = append(results, r) + mu.Unlock() + } + }() + } + wg.Wait() + close(stop) + report(results, time.Since(started), *users, *links) +} + +func run(fake string, c *chat, uid int64, link string, timeout time.Duration) result { + c.mu.Lock() + from := len(c.calls) + c.mu.Unlock() + t0 := time.Now() + if err := post(fake, "/control/message", map[string]any{"chat_id": uid, "user_id": uid, "text": link}); err != nil { + return result{outcome: "error", reason: err.Error()} + } + isCard := func(x call) bool { + for _, b := range x.Buttons { + if strings.HasPrefix(b, "dl:") && strings.HasSuffix(b, ":best") { + return true + } + } + return false + } + card, next, ok := c.waitFor(from, timeout, func(x call) bool { return isCard(x) || refusal(x) }) + if !ok { + return result{outcome: "timeout", reason: "no card"} + } + if !isCard(card) { + return result{outcome: "refused", reason: firstLine(card.Text)} + } + cardAt := time.Since(t0) + data := "" + for _, b := range card.Buttons { + if strings.HasSuffix(b, ":best") { + data = b + } + } + if err := post(fake, "/control/callback", map[string]any{"chat_id": uid, "user_id": uid, "message_id": card.MessageID, "data": data}); err != nil { + return result{outcome: "error", reason: err.Error()} + } + end, _, ok := c.waitFor(next, timeout, func(x call) bool { + return ((x.Method == "sendVideo" || x.Method == "sendDocument") && !x.Failed) || refusal(x) || + strings.Contains(x.Text, "That did not work") + }) + switch { + case !ok: + return result{outcome: "timeout", reason: "no file", card: cardAt} + case end.Method == "sendVideo" || end.Method == "sendDocument": + return result{outcome: "delivered", card: cardAt, total: time.Since(t0)} + case strings.Contains(end.Text, "That did not work"): + return result{outcome: "failed", reason: lastLine(end.Text), card: cardAt} + default: + return result{outcome: "refused", reason: firstLine(end.Text), card: cardAt} + } +} + +// refusal recognizes the bot's answers that end a request without a +// download: limits, a full queue, rate limiting. +func refusal(x call) bool { + if x.Method != "sendMessage" && x.Method != "editMessageText" && x.Method != "editMessageCaption" { + return false + } + for _, s := range []string{"limit", "queue is full", "a lot of links", "already have", "used your", "reached your"} { + if strings.Contains(x.Text, s) { + return true + } + } + return false +} + +func firstLine(s string) string { l, _, _ := strings.Cut(s, "\n"); return l } + +func lastLine(s string) string { + lines := strings.Split(strings.TrimSpace(s), "\n") + return lines[len(lines)-1] +} + +func pct(d []time.Duration, p float64) time.Duration { + if len(d) == 0 { + return 0 + } + i := int(float64(len(d)-1) * p) + return d[i] +} + +func report(rs []result, took time.Duration, users, links int) { + count := map[string]int{} + reasons := map[string]int{} + var cards, totals []time.Duration + for _, r := range rs { + count[r.outcome]++ + if r.reason != "" { + reasons[r.outcome+": "+r.reason]++ + } + if r.card > 0 { + cards = append(cards, r.card) + } + if r.outcome == "delivered" { + totals = append(totals, r.total) + } + } + sort.Slice(cards, func(i, j int) bool { return cards[i] < cards[j] }) + sort.Slice(totals, func(i, j int) bool { return totals[i] < totals[j] }) + r := func(d time.Duration) string { return d.Round(10 * time.Millisecond).String() } + + fmt.Printf("\n%d users x %d links = %d requests in %s\n", users, links, len(rs), r(took)) + fmt.Printf(" delivered %d, failed %d, refused %d, timed out %d, errors %d\n", + count["delivered"], count["failed"], count["refused"], count["timeout"], count["error"]) + if len(totals) > 0 { + fmt.Printf(" files per minute: %.1f\n", float64(len(totals))/took.Minutes()) + fmt.Printf(" link to card: p50 %s p95 %s max %s\n", r(pct(cards, .5)), r(pct(cards, .95)), r(pct(cards, 1))) + fmt.Printf(" link to file: p50 %s p95 %s p99 %s max %s\n", r(pct(totals, .5)), r(pct(totals, .95)), r(pct(totals, .99)), r(pct(totals, 1))) + } + if len(reasons) > 0 { + fmt.Println(" reasons:") + keys := make([]string, 0, len(reasons)) + for k := range reasons { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + fmt.Printf(" %4d %s\n", reasons[k], k) + } + } + if count["delivered"] < len(rs) { + os.Exit(1) + } +} diff --git a/cmd/worker/main.go b/cmd/worker/main.go index c258bdc..9a00990 100644 --- a/cmd/worker/main.go +++ b/cmd/worker/main.go @@ -19,6 +19,7 @@ import ( "github.com/noderunners/dlbot/internal/app" "github.com/noderunners/dlbot/internal/config" "github.com/noderunners/dlbot/internal/ffmpeg" + "github.com/noderunners/dlbot/internal/metrics" "github.com/noderunners/dlbot/internal/worker" "github.com/noderunners/dlbot/internal/workerproto" "github.com/noderunners/dlbot/internal/ytdlp" @@ -67,7 +68,7 @@ func main() { var wg sync.WaitGroup if cfg.HealthListen != "" { - srv := healthServer(cfg.HealthListen, w) + srv := healthServer(cfg.HealthListen, w, up.get) wg.Add(1) go func() { defer wg.Done() @@ -104,10 +105,13 @@ func main() { 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 { +// healthServer answers /healthz and /metrics. The worker is healthy while +// the core keeps answering its claims and accepts its token. +func healthServer(addr string, w *worker.Worker, ytdlpVersion func() string) *http.Server { mux := http.NewServeMux() + mux.Handle("GET /metrics", metrics.WorkerHandler(metrics.WorkerSource{ + Active: w.Active, Capacity: w.Capacity, LastContact: w.LastContact, Outcomes: w.Outcomes, YtDlp: ytdlpVersion, + })) mux.HandleFunc("GET /healthz", func(rw http.ResponseWriter, _ *http.Request) { last, authFailed := w.LastContact() age := time.Since(last) diff --git a/config.example.toml b/config.example.toml index fef2988..d1f07f7 100644 --- a/config.example.toml +++ b/config.example.toml @@ -25,9 +25,11 @@ webhook_url = "" max_upload_mb = 50 # 2000 with a local Bot API server update_workers = 8 set_profile = true # name and descriptions per language from the catalogs +widgets = true # live status and invoice widgets, with automatic fallback [http] listen = ":8080" +metrics = true # Prometheus metrics at /metrics [database] driver = "sqlite" # sqlite or postgres diff --git a/deploy/caddy/Caddyfile b/deploy/caddy/Caddyfile new file mode 100644 index 0000000..ee47caf --- /dev/null +++ b/deploy/caddy/Caddyfile @@ -0,0 +1,15 @@ +# Caddy in front of the core: TLS from Let's Encrypt, then everything to +# the core on localhost, except /metrics, which stays private. +# +# sudo apt install caddy +# sudo cp deploy/caddy/Caddyfile /etc/caddy/Caddyfile # set your domain +# sudo systemctl reload caddy +# +# Caddy has no request body limit and no read timeout by default, which +# suits worker uploads and the long-held claim requests of workers. +bot.example.com { + @private path /metrics + respond @private 404 + + reverse_proxy 127.0.0.1:8080 +} diff --git a/deploy/loadtest/fake-yt-dlp.sh b/deploy/loadtest/fake-yt-dlp.sh new file mode 100755 index 0000000..e9859c7 --- /dev/null +++ b/deploy/loadtest/fake-yt-dlp.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# A yt-dlp stand-in for load tests. It never touches the network. Every URL +# is its own video (the ID is a checksum of the URL), so the cache only +# helps where the load test asks for the same link twice. +# +# LOAD_SIZE bytes per file (default 2000000) +# LOAD_TIME seconds per download (default 2) +# LOAD_PROBE seconds per lookup (default 0.2) +set -u +args=("$@") +dir="" +probe=0 +url="${args[$((${#args[@]} - 1))]}" +for ((i = 0; i < ${#args[@]}; i++)); do + case "${args[$i]}" in + -P) dir="${args[$((i + 1))]}" ;; + -J) probe=1 ;; + --version) echo "2026.10.26"; exit 0 ;; + -U|--update) echo "yt-dlp is up to date"; exit 0 ;; + esac +done +id=$(printf '%s' "$url" | cksum | cut -d' ' -f1) +size=${LOAD_SIZE:-2000000} + +if [[ $probe -eq 1 ]]; then + sleep "${LOAD_PROBE:-0.2}" + echo '{"id": "v'"$id"'", "title": "Load test '"$id"'", "extractor": "loadtest", "extractor_key": "Loadtest", "webpage_url": "'"$url"'", "duration": 60, "uploader": "Load", "is_live": false, "formats": [{"format_id": "a", "ext": "m4a", "vcodec": "none", "acodec": "mp4a.40.2", "filesize": '"$((size / 4))"'}, {"format_id": "v", "ext": "mp4", "vcodec": "avc1", "acodec": "mp4a.40.2", "height": 720, "width": 1280, "filesize": '"$size"'}]}' + exit 0 +fi + +echo 'INFO|{"id": "v'"$id"'", "title": "Load test '"$id"'", "duration": 60, "extractor": "loadtest", "extractor_key": "Loadtest", "uploader": "Load", "is_live": false}' +echo "[download] Destination: $dir/media.mp4" +steps=4 +for ((s = 1; s <= steps; s++)); do + sleep "$(awk "BEGIN{print ${LOAD_TIME:-2}/$steps}")" + echo "DLP|downloading|$((size * s / steps))|$size|NA" +done +echo "DLP|finished|$size|$size|NA" +head -c "$size" /dev/zero > "$dir/media.mp4" +echo 'RESULT|{"width": 1280, "height": 720, "duration": 60, "ext": "mp4", "filepath": "'"$dir/media.mp4"'"}' diff --git a/deploy/loadtest/run.sh b/deploy/loadtest/run.sh new file mode 100755 index 0000000..2f23b90 --- /dev/null +++ b/deploy/loadtest/run.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +# Load test: many simulated users against a real core and real workers, +# with Telegram replaced by cmd/faketelegram and yt-dlp by a stand-in that +# takes a set time per download and never touches the network. What it +# measures is the bot itself: the queue, the workers, the cache, delivery. +# +# deploy/loadtest/run.sh # 50 users, embedded worker +# USERS=200 LINKS=5 WORKERS=4 deploy/loadtest/run.sh +# +# Settings (environment): +# USERS (50), LINKS (3), RAMP (20s), SHARE (0.2) the load +# WORKERS (0) remote workers; 0 uses the core's embedded worker +# SLOTS (4) downloads at once, per worker +# LOAD_TIME (2) seconds one download takes +# LOAD_SIZE (2000000) bytes per file +# DB (sqlite) or postgres, with PG_DSN set +# KEEP=1 keep logs and the database afterwards +# +# Needs: go, curl. Prints a summary, and the core's /metrics for the queue. +set -euo pipefail + +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +WORK=$(mktemp -d "${TMPDIR:-/tmp}/dlbot-load.XXXXXX") +FAKE_PORT=${FAKE_PORT:-18190} +CORE_PORT=${CORE_PORT:-18180} +USERS=${USERS:-50} +LINKS=${LINKS:-3} +RAMP=${RAMP:-20s} +SHARE=${SHARE:-0.2} +WORKERS=${WORKERS:-0} +SLOTS=${SLOTS:-4} +FAKE="http://127.0.0.1:$FAKE_PORT" +CORE="http://127.0.0.1:$CORE_PORT" +PIDS=() + +cleanup() { + for pid in "${PIDS[@]:-}"; do kill "$pid" 2>/dev/null || true; done + wait 2>/dev/null || true + if [ -n "${KEEP:-}" ]; then echo "logs kept in $WORK"; else rm -rf "$WORK"; fi +} +trap cleanup EXIT + +echo "==> building" +(cd "$ROOT" && go build -o "$WORK/bin/" ./cmd/core ./cmd/worker ./cmd/faketelegram ./cmd/loadtest) + +db_env=(DB_DRIVER=sqlite DB_DSN="$WORK/core.db") +if [ "${DB:-sqlite}" = postgres ]; then + : "${PG_DSN:?set PG_DSN to an empty Postgres database}" + db_env=(DB_DRIVER=postgres DB_DSN="$PG_DSN") +fi + +embedded=true +tokens="" +if [ "$WORKERS" -gt 0 ]; then + embedded=false + for i in $(seq 1 "$WORKERS"); do + tokens="${tokens:+$tokens,}load-$i:dlw_load_test_token_for_worker_${i}_0000000000" + done +fi + +echo "==> starting the fake Telegram and the core ($([ "$WORKERS" -gt 0 ] && echo "$WORKERS remote workers" || echo "embedded worker"), $SLOTS slots each)" +"$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_env[@]}" STORAGE_LOCAL_DIR="$WORK/files" \ + WORKER_EMBEDDED=$embedded WORKER_TOKENS="$tokens" WORKER_CONCURRENCY="$SLOTS" WORKER_TEMP_DIR="$WORK/tmp-core" \ + YTDLP_PATH="$ROOT/deploy/loadtest/fake-yt-dlp.sh" YTDLP_AUTO_UPDATE=0 PROBE_MODE=$([ "$WORKERS" -gt 0 ] && echo worker || echo local) \ + LOAD_TIME="${LOAD_TIME:-2}" LOAD_SIZE="${LOAD_SIZE:-2000000}" \ + FREE_DAILY_DOWNLOADS=100000 FREE_DAILY_MB=0 FREE_ACTIVE_JOBS=1 FREE_MAX_SIZE_MB=50 \ + RATE_USER_PER_MINUTE=600 RATE_GROUP_PER_MINUTE=600 QUEUE_FREE_MAX_LEN=100000 \ + TELEGRAM_UPDATE_WORKERS=32 TELEGRAM_WIDGETS=false TELEGRAM_SET_PROFILE=false \ + LOG_FORMAT=text LOG_LEVEL=warn \ + "$WORK/bin/core" >"$WORK/core.log" 2>&1) & +PIDS+=($!) + +for _ in $(seq 1 100); do curl -fsS "$CORE/healthz" >/dev/null 2>&1 && break; sleep 0.3; done +curl -fsS "$CORE/healthz" >/dev/null || { echo "the core did not start:"; tail -20 "$WORK/core.log"; exit 1; } + +for i in $(seq 1 "$WORKERS"); do + (cd "$WORK" && exec env -i PATH="$PATH" HOME="$WORK" \ + CORE_URL="$CORE" WORKER_TOKEN="dlw_load_test_token_for_worker_${i}_0000000000" WORKER_CONCURRENCY="$SLOTS" \ + WORKER_TEMP_DIR="$WORK/tmp-$i" WORKER_HEALTH_LISTEN=off YTDLP_PATH="$ROOT/deploy/loadtest/fake-yt-dlp.sh" \ + YTDLP_AUTO_UPDATE=0 LOAD_TIME="${LOAD_TIME:-2}" LOAD_SIZE="${LOAD_SIZE:-2000000}" LOG_FORMAT=text LOG_LEVEL=warn \ + "$WORK/bin/worker" >"$WORK/worker-$i.log" 2>&1) & + PIDS+=($!) +done + +echo "==> $USERS users, $LINKS links each, started over $RAMP, $(awk "BEGIN{print $SHARE*100}")% for one popular link" +status=0 +"$WORK/bin/loadtest" -fake "$FAKE" -users "$USERS" -links "$LINKS" -ramp "$RAMP" -share "$SHARE" || status=$? + +echo +echo "==> core metrics" +curl -fsS "$CORE/metrics" | grep -E '^dlbot_(queue_wait_seconds_(sum|count)|jobs_finished_total|cache_hits_total|cache_misses_total|deliveries_total|download_errors_total|worker_heartbeat_age_seconds)' || true +if grep -q 'level=ERROR' "$WORK/core.log"; then + echo + echo "==> errors in the core log" + grep 'level=ERROR' "$WORK/core.log" | head -20 + status=1 +fi +exit $status diff --git a/deploy/prometheus/alerts.yml b/deploy/prometheus/alerts.yml new file mode 100644 index 0000000..6449ba7 --- /dev/null +++ b/deploy/prometheus/alerts.yml @@ -0,0 +1,75 @@ +# Alert rules for the bot. Thresholds are starting points; tune them to +# your traffic. Written for Prometheus 2.x and 3.x rule files. +groups: + - name: dlbot + rules: + - alert: DlbotCoreDown + expr: up{job="dlbot-core"} == 0 + for: 2m + labels: {severity: page} + annotations: + summary: The bot's core is not answering /metrics. + + - alert: DlbotQueueStuck + # Jobs wait while no slot is busy: workers are gone or cannot claim. + expr: sum(dlbot_queue_jobs) > 0 and dlbot_jobs_running == 0 + for: 5m + labels: {severity: page} + annotations: + summary: Jobs are queued but nothing is downloading. + + - alert: DlbotQueueSlow + expr: dlbot_queue_oldest_wait_seconds > 900 + for: 10m + labels: {severity: warn} + annotations: + summary: The oldest queued job has waited over 15 minutes. Add workers or slots. + + - alert: DlbotBooksDisagree + expr: dlbot_wallets_mismatched > 0 + labels: {severity: page} + annotations: + summary: A wallet balance disagrees with its ledger. Stop and investigate before paying anything out. + + - alert: DlbotNoWorkers + expr: dlbot_worker_slots == 0 + for: 5m + labels: {severity: page} + annotations: + summary: No download slots are connected. + + - alert: DlbotWorkerSilent + expr: dlbot_worker_heartbeat_age_seconds{state="active"} > 120 + for: 2m + labels: {severity: warn} + annotations: + summary: Worker {{ $labels.worker }} has not checked in for two minutes. + + - alert: DlbotWorkerTokenRejected + expr: dlbot_worker_token_rejected == 1 + for: 1m + labels: {severity: page} + annotations: + summary: The core rejects the token of {{ $labels.instance }}. + + - alert: DlbotLightningDown + expr: dlbot_lightning_up == 0 + for: 5m + labels: {severity: page} + annotations: + summary: The payment backend (LNbits) is unreachable. Invoices cannot be created or confirmed. + + - alert: DlbotSiteFailing + # One site failing most downloads usually means yt-dlp needs an + # update or the site blocks the workers' network. + expr: sum by (site) (increase(dlbot_download_errors_total{code!~"private|login_required|not_found|too_large|too_long|cancelled"}[30m])) > 10 + for: 10m + labels: {severity: warn} + annotations: + summary: Downloads from {{ $labels.site }} keep failing. Try /ytdlp update, or route the site to other workers. + + - alert: DlbotWidgetsFallingBack + expr: sum(increase(dlbot_widgets_total{outcome="fallback"}[1h])) > 20 + labels: {severity: info} + annotations: + summary: sendWidget keeps failing; the bot is using ordinary messages. Nothing breaks, but check the logs. diff --git a/deploy/prometheus/prometheus.yml b/deploy/prometheus/prometheus.yml new file mode 100644 index 0000000..34bb213 --- /dev/null +++ b/deploy/prometheus/prometheus.yml @@ -0,0 +1,21 @@ +# Example Prometheus configuration for the bot. Copy it next to your +# Prometheus, adjust the targets, and load alerts.yml with it. +# +# The core serves /metrics on HTTP_LISTEN (8080). Each standalone worker +# serves /metrics on WORKER_HEALTH_LISTEN (8081). Scrape them over the +# private network; do not route /metrics through the public proxy. +global: + scrape_interval: 30s + evaluation_interval: 30s + +rule_files: + - alerts.yml + +scrape_configs: + - job_name: dlbot-core + static_configs: + - targets: ["core:8080"] + + - job_name: dlbot-worker + static_configs: + - targets: ["worker-a:8081", "worker-b:8081"] diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 52f2ee8..1becf8d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -50,6 +50,9 @@ phase; sections for later phases say so. | `internal/i18n` | go-i18n wrapper, locale aware formatting. | | `internal/tg` | Narrow Bot API interface, error helpers, the fake Bot API server. | | `internal/api` | HTTP server: health check, payment webhook, worker protocol, Mini App API. | +| `internal/widget` | The HTML widgets (status, invoice), their size limits, state encoding, the QR bitmap, the fallback breaker. | +| `internal/metrics` | Prometheus metrics of the core (read at scrape time where possible) and of the worker. | +| `cmd/loadtest` | Simulated users against a core on the fake Bot API. | | `web/miniapp` | The Mini App front end (Vite, React, TypeScript) and its build, embedded with `go:embed`. | | `locales` | Translation catalogs, embedded in the binary. | @@ -404,6 +407,42 @@ The build writes a hash of its sources next to its output and a Go test recomputes it, which catches a source change committed without a rebuild. The Docker image rebuilds the front end from source. +## Live widgets + +Widgets (Bot API 10.4 `sendWidget`) are an extra layer on top of the +ordinary messages, in `internal/bot/live.go`. Nothing else in the bot +knows about them: + +- `setStatus` first offers the status to `liveStatus`. In a private chat, + the first status of a delivery is sent as a widget; if that works, the + card is deleted and the widget becomes the delivery's status message + (recorded in `widget_messages`). Later statuses change only the + widget's state (`editMessageWidgetData`), throttled like edits. + `finalStatus` writes the end state. If `sendWidget` fails, `setStatus` + edits the card as it always did. +- `sendInvoice` first tries `sendInvoiceWidget`. The widget message keeps + the ordinary invoice's caption (with the copyable BOLT11) and buttons; + paid and expired are shown by editing the caption as before, plus the + widget's state. +- The widgets' HTML is the same for every language. All texts, the + direction and the button label travel in the state, already + translated. The invoice QR is packed as a bitmap in the public data and + drawn on a canvas, because a QR library would not fit the 4 KB limit. +- The status widget's Cancel sends a request (`widget_query`). The bot + finds the delivery by the message, checks that the person tapping owns + it, cancels through the same path as `/cancel`, and answers. +- `widget.Breaker` pauses attempts after repeated failures, so a Bot API + server without widgets costs one failed call per pause, not one per + message. + +## Metrics + +`internal/metrics` registers counters that code increments (job outcomes, +errors per site, deliveries, widgets, updates), a histogram of queue wait +and, at scrape time, gauges read from the database and the services +(queue depth, running jobs, slots, worker heartbeats, cache, invoices, +Lightning, ledger check). Every method is a no-op on a nil `*Metrics`. + ## Internationalization Handlers never contain user-facing text. They call `i18n.Bundle` with a diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index 1d23648..bf85708 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -770,3 +770,100 @@ Checked against https://core.telegram.org/bots/api (Bot API 10.4) on chat only. This is the likely cause of the one Postgres failure of `TestSkipTheQueueWithInvoice` reported in Phase 4, which uses the same helper. The bot itself was right in both cases. + +## Phase 8 + +### Verified widget facts + +Checked on 2026-11-18 against https://core.telegram.org/bots/api (Bot API +10.4, released 2026-11-09), https://core.telegram.org/bots/widgets, and +telego v1.13.0, which has `SendWidget`, `EditMessageWidgetData`, +`AnswerWidgetQuery` and `Update.WidgetQuery`. + +- `sendWidget` sends one HTML document: at most 32768 bytes, and at most + 4096 bytes after zlib at level 9. It takes `chat_data` and + `public_data` (1024 bytes each), a caption, `allow_queries` and the + usual `reply_markup`. +- In production, widgets work only in the private chat with the bot, and + cannot be forwarded. Groups, inline mode and forwards are test server + only. +- The widget runs in a sandbox (QuickJS), not a browser: no network at + all, no logical CSS properties, no `color-mix()`, no form controls but + `
+ diff --git a/internal/widget/testdata/qr.json b/internal/widget/testdata/qr.json new file mode 100644 index 0000000..3d970b4 --- /dev/null +++ b/internal/widget/testdata/qr.json @@ -0,0 +1,5 @@ +{ + "n": 53, + "q": "/k04wSpj/BdRfrDBkG6SR7p4NLt1z/d5ptXbpAhPklouwVfVxGnRB/qqqqqqr+AMXdFg1QD7jzL9+w1VIYcoulBtHqTkPe52BePZhqTFwm5mu4ZJ/TrI7TaBsHSf2Odzh7aSuDqhAC5Pcj9QRDP7Cp4FqcrisaeDw5I4XyWQavLxnUzzXbNbCY3eaUKbN3AItJBNuokyljCOGn3gDk9d/98y+6iP8cWHLETSRZKtfOpbJrNREckVCJFB/dkP/Mr+COKuegH5c0sHNxoewnIqsTaqa1jD8ETHZhPwr6nMANjNUYMKot+ofJqW8rYirWY16i3236q2EKTT0OMTyR6v2XuXIB9P2Dd64P/nMk9qJYsBhy0BwNh3yvz3fZv+wimDojq9MTVGT81++oBVZEWWHGP61Va4eauwQ8IRHyMeuvpF/MoPpdd5zUmm/q6mG8Qwi48FznAWSR1/69/GWZYXAA==", + "text": "LIGHTNING:LNBC7000N1PNXYZ3QPP5Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4Q8ZJ7W3KX4CQZPGXQYZ5VQSP5" +} diff --git a/internal/widget/widget.go b/internal/widget/widget.go new file mode 100644 index 0000000..58653ca --- /dev/null +++ b/internal/widget/widget.go @@ -0,0 +1,229 @@ +// Package widget holds the bot's HTML widgets (Bot API 10.4, sendWidget): +// small documents Telegram draws inside a message and runs in a sandbox +// without network access. The bot changes what they show by editing their +// state with editMessageWidgetData. +// +// There are two: the live status of a download (progress bar, cancel) and +// a Lightning invoice (QR code, countdown, paid state). Their HTML does not +// depend on the language: every text they show arrives in their state, +// already translated by the bot. +// +// Widgets are optional. Whatever goes wrong with one, the bot falls back +// to the ordinary message it would have sent anyway; Breaker decides when +// to stop trying for a while. +package widget + +import ( + "bytes" + "compress/zlib" + _ "embed" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "strings" + "sync" + "time" + "unicode/utf8" + + qrcode "github.com/skip2/go-qrcode" +) + +// Limits from the Bot API. +const ( + MaxHTML = 32768 // bytes of UTF-8 + MaxCompressedHTML = 4096 // bytes after zlib at level 9 + MaxData = 1024 // bytes of chat_data or public_data +) + +var ( + //go:embed job.html + jobHTML string + //go:embed invoice.html + invoiceHTML string +) + +// JobHTML is the download status widget. +func JobHTML() string { return jobHTML } + +// InvoiceHTML is the invoice widget. +func InvoiceHTML() string { return invoiceHTML } + +// CheckHTML reports whether a widget document is within Telegram's limits. +func CheckHTML(html string) error { + if len(html) == 0 || len(html) > MaxHTML || !utf8.ValidString(html) || strings.ContainsRune(html, 0) { + return fmt.Errorf("widget: html is %d bytes, or not valid UTF-8", len(html)) + } + if n := CompressedSize(html); n > MaxCompressedHTML { + return fmt.Errorf("widget: html is %d bytes compressed, the limit is %d", n, MaxCompressedHTML) + } + return nil +} + +// CompressedSize is the size of html after zlib at level 9, which is how +// Telegram counts. +func CompressedSize(html string) int { + var buf bytes.Buffer + w, _ := zlib.NewWriterLevel(&buf, zlib.BestCompression) + _, _ = w.Write([]byte(html)) + _ = w.Close() + return buf.Len() +} + +// Job is the state of the status widget. +type Job struct { + // Kind is "queued", "running" or "end". + Kind string `json:"k"` + // Message is the main line, Detail the smaller one under it. + Message string `json:"m,omitempty"` + Detail string `json:"d,omitempty"` + // Progress is 0 to 1, or below 0 when the amount is unknown, which + // shows a moving bar. + Progress float64 `json:"p"` + // Cancel is the label of the cancel button. Empty hides it. + Cancel string `json:"x,omitempty"` + RTL bool `json:"r,omitempty"` +} + +// InvoiceInfo is the fixed part of the invoice widget, its public data. +type InvoiceInfo struct { + Title string `json:"t"` + Amount string `json:"a"` + // Expires is a Unix time in seconds. + Expires int64 `json:"e"` + // Waiting is the countdown text, with {T} where the time goes. + Waiting string `json:"w"` + Checking string `json:"c"` + // QR is the code's modules, row by row, one bit each, in base64. N is + // the number of modules per side. Both are empty when the code does + // not fit. + QR string `json:"q,omitempty"` + N int `json:"n,omitempty"` + RTL bool `json:"r,omitempty"` +} + +// InvoiceState is the changing part of the invoice widget. +type InvoiceState struct { + // Status is "pending", "paid", "expired" or "cancelled". + Status string `json:"s"` + Message string `json:"m,omitempty"` +} + +// Encode turns a state into widget data. A text field too long for the +// limit is shortened rather than the update dropped. +func Encode(v any) (string, error) { + data, err := json.Marshal(v) + if err != nil { + return "", err + } + if len(data) <= MaxData { + return string(data), nil + } + switch s := v.(type) { + case Job: + s.Detail = "" + s.Message = clip(s.Message, 400) + return Encode(s) + case InvoiceState: + s.Message = clip(s.Message, 400) + return Encode(s) + case InvoiceInfo: + if s.QR != "" { + s.QR, s.N = "", 0 + return Encode(s) + } + } + return "", fmt.Errorf("widget: data is %d bytes, the limit is %d", len(data), MaxData) +} + +func clip(s string, max int) string { + if len(s) <= max { + return s + } + for max > 0 && !utf8.RuneStart(s[max]) { + max-- + } + return s[:max] + "…" +} + +// QRBits encodes text as a QR code and packs its modules for the invoice +// widget, which draws them on a canvas. Low error correction keeps the +// code small enough to fit the widget's data. +func QRBits(text string) (n int, b64 string, err error) { + q, err := qrcode.New(text, qrcode.Low) + if err != nil { + return 0, "", err + } + q.DisableBorder = true + bm := q.Bitmap() + n = len(bm) + packed := make([]byte, (n*n+7)/8) + for r, row := range bm { + for c, on := range row { + if on { + i := r*n + c + packed[i/8] |= 0x80 >> (i % 8) + } + } + } + return n, base64.StdEncoding.EncodeToString(packed), nil +} + +// Breaker stops widget attempts for a while after they keep failing, so a +// client or Bot API server without widgets does not cost a failed call in +// front of every message. +type Breaker struct { + mu sync.Mutex + failures int + until time.Time + now func() time.Time +} + +// NewBreaker returns a breaker that is closed (widgets allowed). +func NewBreaker() *Breaker { return &Breaker{now: time.Now} } + +// Allow reports whether a widget may be tried now. A nil breaker means +// widgets are turned off. +func (b *Breaker) Allow() bool { + if b == nil { + return false + } + b.mu.Lock() + defer b.mu.Unlock() + return !b.now().Before(b.until) +} + +// ErrUnsupported marks errors that mean the Bot API has no widgets at all. +var ErrUnsupported = errors.New("widget: not supported by this Bot API server") + +// Failed records a failed attempt. Unsupported switches widgets off for an +// hour; three failures in a row for ten minutes. +func (b *Breaker) Failed(unsupported bool) (pause time.Duration) { + if b == nil { + return 0 + } + b.mu.Lock() + defer b.mu.Unlock() + b.failures++ + switch { + case unsupported: + pause = time.Hour + case b.failures >= 3: + pause = 10 * time.Minute + default: + return 0 + } + b.failures = 0 + b.until = b.now().Add(pause) + return pause +} + +// Worked records a successful attempt. +func (b *Breaker) Worked() { + if b == nil { + return + } + b.mu.Lock() + b.failures = 0 + b.mu.Unlock() +} diff --git a/internal/widget/widget_test.go b/internal/widget/widget_test.go new file mode 100644 index 0000000..f309965 --- /dev/null +++ b/internal/widget/widget_test.go @@ -0,0 +1,135 @@ +package widget + +import ( + "encoding/base64" + "encoding/json" + "os" + "strings" + "testing" + "time" +) + +func TestHTMLIsWithinTelegramsLimits(t *testing.T) { + for name, html := range map[string]string{"job": JobHTML(), "invoice": InvoiceHTML()} { + if err := CheckHTML(html); err != nil { + t.Errorf("%s: %v", name, err) + } + t.Logf("%s: %d bytes, %d compressed", name, len(html), CompressedSize(html)) + // The sandbox has no network and no logical CSS properties, and + // draws no form controls but buttons. + for _, bad := range []string{"http://", "https://", "fetch(", "XMLHttpRequest", "> 17 + x ^= x << 5 + sb.WriteByte(byte('!' + x%90)) + } + if CheckHTML(sb.String()) == nil { + t.Fatal("html over the compressed limit accepted") + } +} + +func TestEncodeStaysWithinTheDataLimit(t *testing.T) { + long := strings.Repeat("ñ", 2000) + got, err := Encode(Job{Kind: "running", Message: long, Detail: long, Progress: 0.5}) + if err != nil || len(got) > MaxData { + t.Fatalf("job: %d bytes, %v", len(got), err) + } + var back Job + if err := json.Unmarshal([]byte(got), &back); err != nil || back.Kind != "running" || back.Progress != 0.5 { + t.Fatalf("job state did not survive: %+v %v", back, err) + } + info := InvoiceInfo{Title: "Day pass", Amount: "700 sats", QR: strings.Repeat("A", 1500), N: 99} + got, err = Encode(info) + if err != nil || strings.Contains(got, `"q"`) { + t.Fatalf("an oversized QR must be dropped, not the invoice: %q %v", got, err) + } +} + +// A real invoice must leave room for its QR code in the widget's data. +func TestQRFitsForARealInvoice(t *testing.T) { + bolt11 := "LNBC30U1PNXYZ3QPP5" + strings.Repeat("Q8ZJ7W3K", 33) + "CQZPGXQYZ5VQSP5" + n, b64, err := QRBits("LIGHTNING:" + bolt11) + if err != nil { + t.Fatal(err) + } + raw, _ := base64.StdEncoding.DecodeString(b64) + if len(raw) != (n*n+7)/8 { + t.Fatalf("%d bytes for %d modules", len(raw), n) + } + data, err := Encode(InvoiceInfo{ + Title: "Pase semanal", Amount: "3.000 sats", Expires: time.Now().Unix(), Waiting: "Esperando el pago · {T}", + Checking: "Verificando el pago…", QR: b64, N: n, + }) + if err != nil || !strings.Contains(data, `"q"`) { + t.Fatalf("a %d character invoice does not fit with its QR (%d modules): %d bytes, %v", len(bolt11), n, len(data), err) + } + t.Logf("%d modules, %d bytes of public data", n, len(data)) +} + +func TestBreaker(t *testing.T) { + var off *Breaker + if off.Allow() { + t.Fatal("a nil breaker means widgets are off") + } + now := time.Unix(1000, 0) + b := NewBreaker() + b.now = func() time.Time { return now } + b.Failed(false) + b.Failed(false) + b.Worked() + b.Failed(false) + if !b.Allow() { + t.Fatal("a success resets the count") + } + b.Failed(false) + if d := b.Failed(false); d != 10*time.Minute || b.Allow() { + t.Fatalf("three in a row: pause %s, allowed %v", d, b.Allow()) + } + now = now.Add(11 * time.Minute) + if !b.Allow() { + t.Fatal("the pause ends") + } + if d := b.Failed(true); d != time.Hour || b.Allow() { + t.Fatal("an unsupported server pauses for an hour") + } +} + +// testdata/qr.json is a real invoice QR as the widget receives it. The +// browser check (web/miniapp/e2e/widgets.mjs) draws it with the widget's +// own code and decodes the picture. This test keeps the file in step with +// QRBits; DLBOT_UPDATE_FIXTURES=1 rewrites it. +func TestQRFixture(t *testing.T) { + text := "LIGHTNING:LNBC7000N1PNXYZ3QPP5" + strings.Repeat("Q8ZJ7W3KX4", 24) + "CQZPGXQYZ5VQSP5" + n, b64, err := QRBits(text) + if err != nil { + t.Fatal(err) + } + want, _ := json.MarshalIndent(map[string]any{"text": text, "n": n, "q": b64}, "", " ") + if os.Getenv("DLBOT_UPDATE_FIXTURES") != "" { + if err := os.WriteFile("testdata/qr.json", append(want, '\n'), 0o644); err != nil { + t.Fatal(err) + } + } + got, err := os.ReadFile("testdata/qr.json") + if err != nil || strings.TrimSpace(string(got)) != string(want) { + t.Fatalf("testdata/qr.json is out of date; run with DLBOT_UPDATE_FIXTURES=1 (%v)", err) + } +} diff --git a/internal/worker/worker.go b/internal/worker/worker.go index 51cfd67..1313796 100644 --- a/internal/worker/worker.go +++ b/internal/worker/worker.go @@ -74,6 +74,9 @@ type Worker struct { active atomic.Int32 // runs numbers the jobs this process has started, for directory names. runs atomic.Uint64 + // outcomes counts finished jobs by outcome, for metrics. + outcomesMu sync.Mutex + outcomes map[string]int64 // lastOK is the unix time of the last call the core answered. lastOK atomic.Int64 // authFailed is set when the core rejected the token. @@ -110,6 +113,30 @@ func New(cfg Config, coord Coordinator, runner ytdlp.Runner, log *slog.Logger) * // Active returns the number of jobs running right now. func (w *Worker) Active() int { return int(w.active.Load()) } +func (w *Worker) count(outcome string) { + w.outcomesMu.Lock() + if w.outcomes == nil { + w.outcomes = map[string]int64{} + } + w.outcomes[outcome]++ + w.outcomesMu.Unlock() +} + +// Outcomes returns how many jobs ended in each way since the start: +// done, failed, cancelled, handed_back, lease_lost. +func (w *Worker) Outcomes() map[string]int64 { + w.outcomesMu.Lock() + defer w.outcomesMu.Unlock() + out := make(map[string]int64, len(w.outcomes)) + for k, v := range w.outcomes { + out[k] = v + } + return out +} + +// Capacity is the number of downloads the worker runs at once. +func (w *Worker) Capacity() int { return w.cfg.Concurrency } + // Run starts the worker slots and blocks until the context ends and every // running job has stopped. func (w *Worker) Run(ctx context.Context) { @@ -399,14 +426,17 @@ func (w *Worker) process(ctx context.Context, job *workerproto.Job) { switch { case leaseLost.Load(): log.Warn("lease lost, dropping job") + w.count("lease_lost") return case cancelled.Load(): + w.count("cancelled") w.report(log, w.coord.Fail(rctx, workerproto.FailRequest{ WorkerID: w.cfg.ID, JobID: job.ID, Code: string(ytdlp.CodeCancelled), })) return case ctx.Err() != nil: // Shutdown in the middle of a job: hand it back for another worker. + w.count("handed_back") w.report(log, w.coord.Fail(rctx, workerproto.FailRequest{ WorkerID: w.cfg.ID, JobID: job.ID, Code: string(ytdlp.CodeWorkerLost), Retryable: true, Detail: "worker shut down", @@ -418,12 +448,14 @@ func (w *Worker) process(ctx context.Context, job *workerproto.Job) { ye = &ytdlp.Error{Code: ytdlp.CodeUnknown, Retryable: true, Raw: err.Error()} } log.Info("job failed", "code", string(ye.Code), "retryable", ye.Retryable) + w.count("failed") w.report(log, w.coord.Fail(rctx, workerproto.FailRequest{ WorkerID: w.cfg.ID, JobID: job.ID, Code: string(ye.Code), Retryable: ye.Retryable, Detail: ye.Raw, })) return } + w.count("done") w.report(log, w.coord.Complete(rctx, workerproto.CompleteRequest{ WorkerID: w.cfg.ID, JobID: job.ID, diff --git a/web/miniapp/dist/source.sha256 b/web/miniapp/dist/source.sha256 index ad07685..f55a4bf 100644 --- a/web/miniapp/dist/source.sha256 +++ b/web/miniapp/dist/source.sha256 @@ -1 +1 @@ -4c14cc42a4c45e760e0f6a38118cf48fac686831914bdc7eb0712bd2c2580fcc +3bb88ab5f83794965a4194f6fe09f0869caf17ff82c4edd104ed989a0018daac diff --git a/web/miniapp/e2e/run.sh b/web/miniapp/e2e/run.sh index 89af9ae..7173b57 100755 --- a/web/miniapp/e2e/run.sh +++ b/web/miniapp/e2e/run.sh @@ -39,4 +39,4 @@ for _ in $(seq 1 600); do done [ -f "$stage/stage.json" ] || { echo "timed out waiting for the core" >&2; cat "$log" >&2; exit 1; } -(cd web/miniapp && node e2e/smoke.mjs "$stage" "$shots") +(cd web/miniapp && node e2e/smoke.mjs "$stage" "$shots" && node e2e/widgets.mjs "$shots") diff --git a/web/miniapp/e2e/widgets.mjs b/web/miniapp/e2e/widgets.mjs new file mode 100644 index 0000000..4006111 --- /dev/null +++ b/web/miniapp/e2e/widgets.mjs @@ -0,0 +1,129 @@ +// Renders the bot's HTML widgets (internal/widget/*.html) in headless +// Chromium with a stand-in for Telegram's TelegramWidget object, and +// checks what they draw for each state. Telegram runs widgets in its own +// sandbox, not a browser; this catches script errors and wrong output, +// not differences of that sandbox. +// +// Usage: node e2e/widgets.mjs [screenshot dir] + +import { chromium } from "playwright-core"; +import jsQR from "jsqr"; +import { mkdirSync, readFileSync } from "node:fs"; +import { join, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = join(dirname(fileURLToPath(import.meta.url)), "../../.."); +const shotDir = process.argv[2] || ""; +if (shotDir) mkdirSync(shotDir, { recursive: true }); +const html = (name) => readFileSync(join(root, "internal/widget", name + ".html"), "utf8"); + +const stub = (chat, pub) => ` + window.__requests = []; + window.__handlers = {}; + window.TelegramWidget = { + chatData: ${JSON.stringify(chat)}, publicData: ${JSON.stringify(pub)}, + onEvent(name, fn) { (window.__handlers[name] ||= []).push(fn); }, + request(data) { window.__requests.push(data); return Promise.resolve({ result: "Cancelled." }); }, + ready() { window.__ready = true; }, + }; + window.__set = (chat) => { TelegramWidget.chatData = chat; (window.__handlers.chatDataChanged || []).forEach((f) => f()); }; +`; + +const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || undefined }); +const problems = []; +const page = async (name, chat, pub) => { + const p = await browser.newPage({ viewport: { width: 340, height: 420 } }); + p.on("pageerror", (e) => problems.push(`${name}: ${e.message}`)); + p.on("console", (m) => m.type() === "error" && problems.push(`${name}: ${m.text()}`)); + await p.setContent("" + html(name)); + return p; +}; +const check = (cond, what) => { + if (!cond) problems.push(what); +}; +const shot = async (p, n) => shotDir && p.screenshot({ path: join(shotDir, n + ".png") }); + +// --- job card --------------------------------------------------------------- +{ + const p = await page("job", JSON.stringify({ k: "running", m: "Descargando…", d: "42 % · 4,2 MB de 10 MB", p: 0.42, x: "Cancelar" })); + check(await p.evaluate(() => window.__ready), "job: ready() not called"); + check((await p.textContent("#m")) === "Descargando…", "job: message not shown"); + check((await p.textContent("#x")) === "Cancelar" && (await p.isVisible("#x")), "job: no cancel button"); + const w = await p.evaluate(() => getComputedStyle(document.getElementById("f")).width); + check(w !== "0px", "job: progress bar is empty at 42%"); + await shot(p, "widget-job-running"); + + await p.click("#x"); + check((await p.evaluate(() => window.__requests)).join() === "cx", "job: cancel did not send the request"); + check(await p.isDisabled("#x"), "job: cancel stays enabled while waiting"); + await p.waitForFunction(() => document.getElementById("d").textContent === "Cancelled."); + + await p.evaluate(() => window.__set(JSON.stringify({ k: "queued", m: "Position 2, about 1 minute", p: -1, x: "Cancel" }))); + check(!(await p.isVisible("#t")), "job: progress bar shown while queued"); + await p.evaluate(() => window.__set(JSON.stringify({ k: "running", m: "Processing", p: -1, x: "Cancel" }))); + check((await p.getAttribute("body", "class")) === "busy", "job: unknown progress does not move"); + await p.evaluate(() => window.__set(JSON.stringify({ k: "end", m: "Done. Enjoy.", p: 0 }))); + check(!(await p.isVisible("#x")) && !(await p.isVisible("#t")), "job: controls left after the end"); + check((await p.textContent("#m")) === "Done. Enjoy.", "job: end message not shown"); + await shot(p, "widget-job-done"); + await p.evaluate(() => window.__set(JSON.stringify({ k: "running", m: "تنزيل", p: 0.5, x: "إلغاء", r: true }))); + check((await p.evaluate(() => document.documentElement.dir)) === "rtl", "job: right-to-left not applied"); + await p.close(); +} + +// --- invoice ---------------------------------------------------------------- +{ + // A real code from the Go side would be better; this is the shape: the + // 21x21 finder-only pattern is enough to see that modules are drawn. + const n = 21; + const bits = new Uint8Array(Math.ceil((n * n) / 8)); + for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) if ((r < 7 && c < 7) || (r + c) % 3 === 0) bits[(r * n + c) >> 3] |= 0x80 >> ((r * n + c) & 7); + const q = Buffer.from(bits).toString("base64"); + const pub = JSON.stringify({ + t: "Day pass", a: "700 sats", e: Math.floor(Date.now() / 1000) + 125, w: "Waiting for payment · {T}", c: "Checking for the payment…", q, n, + }); + const p = await page("invoice", JSON.stringify({ s: "pending" }), pub); + check((await p.textContent("#a")) === "700 sats", "invoice: amount not shown"); + check(/Waiting for payment · 2:0[0-5]/.test(await p.textContent("#w")), "invoice: countdown wrong: " + (await p.textContent("#w"))); + const size = await p.evaluate(() => document.getElementById("q").width); + check(size >= (n + 4) * 2, "invoice: QR canvas not drawn"); + const dark = await p.evaluate(() => { + const c = document.getElementById("q"); + const d = c.getContext("2d").getImageData(0, 0, c.width, c.height).data; + let k = 0; + for (let i = 0; i < d.length; i += 4) if (d[i] < 50) k++; + return k; + }); + check(dark > 0, "invoice: QR has no dark modules"); + await shot(p, "widget-invoice-pending"); + await p.evaluate(() => window.__set(JSON.stringify({ s: "paid", m: "Paid. Day pass · 700 sats" }))); + check(await p.isVisible("#k"), "invoice: no paid mark"); + check(!(await p.isVisible("#q")) && !(await p.isVisible("#w")), "invoice: QR or countdown left after payment"); + await shot(p, "widget-invoice-paid"); + await p.evaluate(() => window.__set(JSON.stringify({ s: "expired", m: "This invoice has expired." }))); + check(!(await p.isVisible("#k")) && !(await p.isVisible("#q")), "invoice: expired still shows QR or paid mark"); + await p.close(); + + // A real invoice code from the Go side, drawn by the widget, must scan. + const fx = JSON.parse(readFileSync(join(root, "internal/widget/testdata/qr.json"), "utf8")); + const real = await page("invoice", JSON.stringify({ s: "pending" }), JSON.stringify({ t: "x", a: "x", e: 0, w: "", c: "", q: fx.q, n: fx.n })); + const img = await real.evaluate(() => { + const c = document.getElementById("q"); + return { w: c.width, h: c.height, d: Array.from(c.getContext("2d").getImageData(0, 0, c.width, c.height).data) }; + }); + const decoded = jsQR(Uint8ClampedArray.from(img.d), img.w, img.h); + check(decoded && decoded.data === fx.text, "invoice: the drawn QR does not scan back to the invoice: " + (decoded && decoded.data)); + await shot(real, "widget-invoice-real-qr"); + await real.close(); + + const late = await page("invoice", JSON.stringify({ s: "pending" }), pub.replace(/"e":\d+/, '"e":1')); + check((await late.textContent("#w")) === "Checking for the payment…", "invoice: no checking text at zero"); + await late.close(); +} + +await browser.close(); +if (problems.length) { + console.error("FAILED:\n" + problems.join("\n")); + process.exit(1); +} +console.log("widgets render as expected"); diff --git a/web/miniapp/package-lock.json b/web/miniapp/package-lock.json index 93436eb..17feaf5 100644 --- a/web/miniapp/package-lock.json +++ b/web/miniapp/package-lock.json @@ -16,6 +16,7 @@ "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^6.3.0", + "jsqr": "^1.4.0", "playwright-core": "^1.65.1", "typescript": "^5.6.0", "vite": "^8.3.8" @@ -507,6 +508,13 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/jsqr": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/jsqr/-/jsqr-1.4.0.tgz", + "integrity": "sha512-dxLob7q65Xg2DvstYkRpkYtmKm2sPJ9oFhrhmudT1dZvNFFTlroai3AWSpLey/w5vMcLBXRgOJsbXpdN9HzU/A==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/lightningcss": { "version": "1.33.0", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", diff --git a/web/miniapp/package.json b/web/miniapp/package.json index 2b0e335..d4e8c35 100644 --- a/web/miniapp/package.json +++ b/web/miniapp/package.json @@ -17,6 +17,7 @@ "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^6.3.0", + "jsqr": "^1.4.0", "playwright-core": "^1.65.1", "typescript": "^5.6.0", "vite": "^8.3.8"