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 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 18:24:36 +00:00
co-authored by Claude Opus 5.5
parent f1f9c6156c
commit 3c153af97f
45 changed files with 3158 additions and 20 deletions
+61 -1
View File
@@ -24,6 +24,7 @@ import (
"github.com/noderunners/dlbot/internal/ffmpeg"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/links"
"github.com/noderunners/dlbot/internal/metrics"
"github.com/noderunners/dlbot/internal/probe"
"github.com/noderunners/dlbot/internal/sched"
"github.com/noderunners/dlbot/internal/service"
@@ -61,6 +62,7 @@ type App struct {
Service *service.Service
Bot *bot.Bot
HTTP *api.Server
Metrics *metrics.Metrics
tgBot *telego.Bot
runner ytdlp.Runner
@@ -258,7 +260,61 @@ func New(ctx context.Context, opts Options) (*App, error) {
if err := registerStaticWorkers(ctx, a.Store, cfg.WorkerTokens, log); err != nil {
return fail(err)
}
a.Metrics = metrics.New(metrics.Sources{
Queue: func(ctx context.Context) (metrics.Queue, error) {
paid, free, oldest, err := a.Store.QueueDepth(ctx, time.Now().UnixMilli())
if err != nil {
return metrics.Queue{}, err
}
running, err := a.Store.CountRunning(ctx)
return metrics.Queue{
Paid: paid, Free: free, OldestWait: time.Duration(oldest) * time.Millisecond,
Running: running, Capacity: a.Sched.Capacity(),
}, err
},
Workers: func(ctx context.Context) ([]metrics.Worker, error) {
ws, err := a.Store.ListWorkers(ctx)
if err != nil {
return nil, err
}
out := make([]metrics.Worker, 0, len(ws))
for _, w := range ws {
mw := metrics.Worker{Name: w.ID, Capacity: w.Capacity, State: "active"}
if w.LastSeenAt > 0 {
mw.LastSeen = time.UnixMilli(w.LastSeenAt)
}
switch {
case w.Revoked:
mw.State = "revoked"
case w.Draining:
mw.State = "draining"
case mw.LastSeen.IsZero() || time.Since(mw.LastSeen) > 2*time.Minute:
mw.State = "offline"
}
out = append(out, mw)
}
return out, nil
},
Cache: func() (int64, int64, int64) {
st := a.Cache.Stats()
return st.Hits, st.Misses, st.BytesSaved
},
Invoices: func() (int64, int64) {
st := a.Billing.Stats()
return st.InvoicesCreated, st.InvoicesSettled
},
Lightning: func() (bool, bool) { return a.Billing.Enabled(), a.Billing.Reachable() },
Books: func(ctx context.Context) (int, error) {
bad, err := a.Store.VerifyWallets(ctx)
if len(bad) > 0 {
log.Error("wallet balances disagree with the ledger", "wallets", len(bad))
}
return len(bad), err
},
})
a.Bot, err = bot.New(ctx, bot.Deps{
Metrics: a.Metrics,
API: a.tgBot,
Config: cfg,
Store: a.Store,
@@ -280,6 +336,9 @@ func New(ctx context.Context, opts Options) (*App, error) {
}
a.HTTP = api.New(cfg.HTTP.Listen, func(ctx context.Context) error { return a.DB.SQL.PingContext(ctx) }, log)
if cfg.HTTP.Metrics {
a.HTTP.Mux().Handle("GET /metrics", a.Metrics.Handler())
}
a.HTTP.RegisterPayments(api.Payments{
Billing: a.Billing, Store: a.Store, I18n: tr, Secret: cfg.LNbits.WebhookSecret,
})
@@ -312,7 +371,7 @@ func New(ctx context.Context, opts Options) (*App, error) {
}
// allowedUpdates is the list of update types the bot asks Telegram for.
var allowedUpdates = []string{"message", "callback_query", "my_chat_member"}
var allowedUpdates = []string{"message", "callback_query", "my_chat_member", "widget_query"}
// Run starts every loop and blocks until ctx ends. Shutdown is ordered:
// updates stop first, then the worker hands back its jobs, then the
@@ -357,6 +416,7 @@ func (a *App) Run(ctx context.Context) error {
run(func() { a.Sched.Run(ctx) })
run(func() { a.Billing.Run(ctx) })
run(func() { a.Cache.Run(ctx, a.cfg.Cache.SweepInterval.D()) })
run(func() { a.Bot.SweepWidgets(ctx, time.Hour) })
if a.worker != nil {
run(func() { a.worker.Run(ctx) })
}
+2
View File
@@ -74,6 +74,8 @@ 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"
// Widgets have their own tests; the others check ordinary messages.
cfg.Telegram.Widgets = false
cfg.Database.Driver, cfg.Database.DSN = dbtest.NewDSN(t)
cfg.Storage.LocalDir = filepath.Join(dir, "files")
cfg.Worker.TempDir = filepath.Join(dir, "tmp")
+341
View File
@@ -0,0 +1,341 @@
package app_test
import (
"encoding/base64"
"encoding/json"
"io"
"net/http"
"strconv"
"strings"
"testing"
"time"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/tg/fakeserver"
"github.com/noderunners/dlbot/internal/widget"
"github.com/noderunners/dlbot/internal/ytdlp"
"github.com/noderunners/dlbot/internal/ytdlp/ytdlptest"
)
func withWidgets(c *config.Config) { c.Telegram.Widgets = true }
func jobStateOf(t *testing.T, c fakeserver.Call) widget.Job {
t.Helper()
var s widget.Job
if err := json.Unmarshal([]byte(c.Params["chat_data"]), &s); err != nil {
t.Fatalf("chat_data %q: %v", c.Params["chat_data"], err)
}
return s
}
func isWidgetEdit(msgID int, pred func(widget.Job) bool) func(fakeserver.Call) bool {
return func(c fakeserver.Call) bool {
if c.MessageID != msgID {
return false
}
var s widget.Job
return json.Unmarshal([]byte(c.Params["chat_data"]), &s) == nil && pred(s)
}
}
// --- acceptance: the live job card -----------------------------------------
func TestJobWidgetShowsProgressAndCancels(t *testing.T) {
block := make(chan struct{})
defer close(block)
h := start(t, &ytdlptest.Fake{Block: block, FileSize: 4000}, withWidgets)
card := h.card(alice, alice, link)
seq := h.press(alice, alice, card, "dl:")
sent := h.wait(seq, "sendWidget", nil)
if sent.ChatID() != alice || sent.Params["html"] != widget.JobHTML() || sent.Params["allow_queries"] != "true" {
t.Fatalf("sendWidget = %+v", sent.Params)
}
if !strings.Contains(sent.Params["caption"], "Test Video") {
t.Fatalf("widget caption = %q", sent.Params["caption"])
}
first := jobStateOf(t, sent)
if first.Cancel != "Cancel" || first.Message == "" {
t.Fatalf("first state = %+v", first)
}
// The card made way for the widget.
h.wait(seq, "deleteMessage", func(c fakeserver.Call) bool { return c.Params["message_id"] == itoaInt(card.MessageID) })
// Progress arrives as widget state, not as message edits.
h.waitJobs(db.JobRunning, 1)
running := h.wait(seq, "editMessageWidgetData", isWidgetEdit(sent.MessageID, func(s widget.Job) bool {
return s.Kind == "running" && s.Message == "Downloading…"
}))
if s := jobStateOf(t, running); s.Progress < 0 && s.Detail == "" {
// The scripted download reports half of its size.
t.Logf("state without numbers yet: %+v", s)
}
h.never(seq, "editMessageCaption", func(c fakeserver.Call) bool { return strings.Contains(c.Text(), "Downloading") })
// Somebody else's request is refused.
q := h.srv.Seq()
h.srv.PushWidgetQuery(alice, bob, sent.MessageID, "cx")
h.wait(q, "answerWidgetQuery", func(c fakeserver.Call) bool { return strings.Contains(c.Params["data"], "belong to the person") })
if len(h.jobs(db.JobRunning)) != 1 {
t.Fatal("a stranger's request cancelled the download")
}
// The widget's Cancel button.
q = h.srv.Seq()
h.srv.PushWidgetQuery(alice, alice, sent.MessageID, "cx")
h.wait(q, "answerWidgetQuery", func(c fakeserver.Call) bool { return c.Params["data"] == "Cancelled." })
end := h.wait(q, "editMessageWidgetData", isWidgetEdit(sent.MessageID, func(s widget.Job) bool { return s.Kind == "end" }))
if s := jobStateOf(t, end); s.Message != "Cancelled." || s.Cancel != "" {
t.Fatalf("final state = %+v", s)
}
h.waitJobs(db.JobCancelled, 1)
h.never(seq, "sendVideo", nil)
// Unknown requests get an empty answer, as the widget expects one.
q = h.srv.Seq()
h.srv.PushWidgetQuery(alice, alice, sent.MessageID, "nonsense")
h.wait(q, "answerWidgetQuery", func(c fakeserver.Call) bool { return c.Params["data"] == "" })
}
func TestJobWidgetEndsWithTheFile(t *testing.T) {
h := start(t, &ytdlptest.Fake{FileSize: 4000, Delay: 300 * time.Millisecond}, withWidgets)
card := h.card(alice, alice, link)
seq := h.press(alice, alice, card, "dl:")
sent := h.wait(seq, "sendWidget", nil)
h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice && !c.Failed })
h.wait(seq, "editMessageWidgetData", isWidgetEdit(sent.MessageID, func(s widget.Job) bool {
return s.Kind == "end" && s.Message == "Done. Enjoy."
}))
// The file replies to the link, like without widgets.
h.waitJobs(db.JobDone, 1)
if n := len(h.srv.Calls("sendWidget")); n != 1 {
t.Fatalf("%d widgets for one download", n)
}
if body := scrapeMetrics(t, h); !strings.Contains(body, `dlbot_widgets_total{outcome="sent",widget="job"} 1`) {
t.Fatal("the widget was not counted")
}
}
// --- acceptance: fallback when sendWidget fails -----------------------------
func TestJobCardFallsBackWhenSendWidgetFails(t *testing.T) {
h := start(t, &ytdlptest.Fake{FileSize: 4000, Delay: 200 * time.Millisecond}, withWidgets)
h.srv.FailNext("sendWidget", 400, "Bad Request: WIDGET_NOT_ALLOWED")
card := h.card(alice, alice, link)
seq := h.press(alice, alice, card, "dl:")
failed := h.wait(seq, "sendWidget", nil)
if !failed.Failed {
t.Fatal("the scripted failure did not happen")
}
// The ordinary card carries on as if widgets did not exist.
h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice })
done := h.wait(seq, "editMessageCaption", textHas("Done"))
if done.MessageID != card.MessageID {
t.Fatalf("the status went to message %d, the card is %d", done.MessageID, card.MessageID)
}
if n := len(h.srv.Calls("sendWidget")); n != 1 {
t.Fatalf("sendWidget was tried %d times for one download", n)
}
h.never(seq, "deleteMessage", func(c fakeserver.Call) bool { return c.Params["message_id"] == itoaInt(card.MessageID) })
if body := scrapeMetrics(t, h); !strings.Contains(body, `dlbot_widgets_total{outcome="fallback",widget="status"} 1`) {
t.Fatal("the fallback was not counted")
}
// The next download tries again: one failure is not a pattern.
card = h.card(alice, alice, "https://example.com/second")
seq = h.press(alice, alice, card, "dl:")
if c := h.wait(seq, "sendWidget", nil); c.Failed {
t.Fatal("the second widget failed too")
}
}
func TestWidgetsPauseWhenTheServerHasNone(t *testing.T) {
h := start(t, &ytdlptest.Fake{FileSize: 4000}, withWidgets)
// What an older Bot API server answers for an unknown method.
h.srv.FailNext("sendWidget", 404, "Not Found: method not found")
card := h.card(alice, alice, link)
seq := h.press(alice, alice, card, "dl:")
h.wait(seq, "editMessageCaption", textHas("Done"))
card = h.card(alice, alice, "https://example.com/second")
seq = h.press(alice, alice, card, "dl:")
h.wait(seq, "editMessageCaption", textHas("Done"))
if n := len(h.srv.Calls("sendWidget")); n != 1 {
t.Fatalf("sendWidget tried %d times after the server said it has no such method", n)
}
}
func TestGroupsGetNoWidgets(t *testing.T) {
h := start(t, &ytdlptest.Fake{FileSize: 4000}, withWidgets)
card := h.card(group, alice, "/dl "+link)
seq := h.press(group, alice, card, "dl:")
h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == group })
if n := len(h.srv.Calls("sendWidget")); n != 0 {
t.Fatalf("%d widgets sent to a group; Telegram allows them in private chats only", n)
}
}
// --- acceptance: the live invoice ------------------------------------------
func TestInvoiceWidgetCountsDownAndShowsPaid(t *testing.T) {
h := startMoney(t, nil, withWidgets)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/buy")
menu := h.wait(seq, "sendMessage", textHas("Passes and credits"))
seq = h.press(alice, alice, menu, "by:pass_day")
inv, ok := h.ln.WaitInvoice(1, 5*time.Second)
if !ok {
t.Fatal("no invoice")
}
sent := h.wait(seq, "sendWidget", nil)
if sent.Params["html"] != widget.InvoiceHTML() || !strings.Contains(sent.Params["caption"], inv.Bolt11) {
t.Fatalf("invoice widget = %+v", sent.Params)
}
var info widget.InvoiceInfo
if err := json.Unmarshal([]byte(sent.Params["public_data"]), &info); err != nil {
t.Fatal(err)
}
if info.Amount != "700 sats" || info.Title != "Day pass" || !strings.Contains(info.Waiting, "{T}") || info.Expires < time.Now().Unix() {
t.Fatalf("invoice info = %+v", info)
}
if bits, err := base64.StdEncoding.DecodeString(info.QR); err != nil || info.N < 21 || len(bits) != (info.N*info.N+7)/8 {
t.Fatalf("QR: %d modules, %d bytes, %v", info.N, len(bits), err)
}
// The usual buttons stay under it, for apps without widgets.
if !strings.Contains(labels(sent), "Check payment") {
t.Fatalf("buttons = %q", labels(sent))
}
h.waitInvoiceSaved(inv)
h.pay(inv)
paid := h.wait(seq, "editMessageWidgetData", func(c fakeserver.Call) bool {
var s widget.InvoiceState
return c.MessageID == sent.MessageID && json.Unmarshal([]byte(c.Params["chat_data"]), &s) == nil && s.Status == "paid"
})
var st widget.InvoiceState
_ = json.Unmarshal([]byte(paid.Params["chat_data"]), &st)
if !strings.HasPrefix(st.Message, "Paid.") {
t.Fatalf("paid state = %+v", st)
}
h.wait(seq, "editMessageCaption", func(c fakeserver.Call) bool {
return c.MessageID == sent.MessageID && strings.Contains(c.Text(), "Paid.") && len(c.Buttons()) == 0
})
h.booksBalance()
}
func TestInvoiceFallsBackWhenSendWidgetFails(t *testing.T) {
h := startMoney(t, nil, withWidgets)
h.srv.FailNext("sendWidget", 400, "Bad Request: INPUT_MEDIA_WIDGET_TOO_LARGE")
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/buy")
menu := h.wait(seq, "sendMessage", textHas("Passes and credits"))
seq = h.press(alice, alice, menu, "by:pass_day")
inv, photo := h.invoice(seq, 1)
if photo.Method != "sendPhoto" || photo.Files["photo"].Size == 0 {
t.Fatalf("fallback invoice = %s %+v", photo.Method, photo.Params)
}
h.waitInvoiceSaved(inv)
h.pay(inv)
h.wait(seq, "editMessageCaption", func(c fakeserver.Call) bool {
return c.MessageID == photo.MessageID && strings.Contains(c.Text(), "Paid.")
})
}
// --- metrics -----------------------------------------------------------------
func scrapeMetrics(t *testing.T, h *harness) string {
t.Helper()
res, err := http.Get("http://" + h.app.HTTP.Addr() + "/metrics")
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
if res.StatusCode != 200 {
t.Fatalf("/metrics = %d", res.StatusCode)
}
return string(body)
}
func TestMetricsEndpoint(t *testing.T) {
h := startMoney(t, &ytdlptest.Fake{FileSize: 3000}, nil)
h.fetch(alice, link)
h.fetch(bob, link) // the same video: a cache hit
// A failure on a site of its own.
h.fake.DownloadErrs = map[string][]error{"https://broken.example.org/v": {errPrivate()}}
card := h.card(alice, alice, "https://broken.example.org/v")
seq := h.press(alice, alice, card, "dl:")
h.wait(seq, edits, textHas("That did not work"))
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/buy")
menu := h.wait(seq, "sendMessage", textHas("Passes and credits"))
h.press(alice, alice, menu, "by:pass_day")
h.ln.WaitInvoice(1, 5*time.Second)
// Events are counted by the bot's event loop, which can run a moment
// after the user already saw the outcome.
var body string
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(50 * time.Millisecond) {
body = scrapeMetrics(t, h.harness)
if strings.Contains(body, `outcome="failed"} 1`) && strings.Contains(body, "dlbot_queue_wait_seconds_count 2") || time.Now().After(deadline) {
break
}
}
if testing.Verbose() {
for _, l := range strings.Split(body, "\n") {
if strings.HasPrefix(l, "dlbot_") {
t.Log(l)
}
}
}
for _, want := range []string{
`dlbot_queue_jobs{lane="free"} 0`,
`dlbot_queue_jobs{lane="paid"} 0`,
"dlbot_queue_oldest_wait_seconds 0",
"dlbot_jobs_running 0",
"dlbot_worker_slots ",
"dlbot_cache_hits_total 1",
"dlbot_cache_bytes_saved_total 3000",
`dlbot_deliveries_total{via="cache"} 1`,
`dlbot_deliveries_total{via="upload"} 1`,
// The cache hit is a job of its own, finished without a worker.
`dlbot_jobs_finished_total{lane="free",outcome="done"} 2`,
`dlbot_jobs_finished_total{lane="free",outcome="failed"} 1`,
`dlbot_download_errors_total{code="private",site="broken.example.org"} 1`,
"dlbot_invoices_created_total 1",
"dlbot_invoices_settled_total 0",
"dlbot_lightning_up 1",
"dlbot_queue_wait_seconds_count 2",
`dlbot_updates_total{type="message"}`,
`dlbot_updates_total{type="callback_query"}`,
"go_goroutines",
} {
if !strings.Contains(body, want) {
t.Errorf("/metrics lacks %q", want)
}
}
// Nothing about users, links or tokens.
for _, bad := range []string{"example.com/watch", fakeserver.Token, "chat_id", "Test Video"} {
if strings.Contains(body, bad) {
t.Errorf("/metrics shows %q", bad)
}
}
}
func TestMetricsCanBeTurnedOff(t *testing.T) {
h := start(t, nil, func(c *config.Config) { c.HTTP.Metrics = false })
res, err := http.Get("http://" + h.app.HTTP.Addr() + "/metrics")
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if res.StatusCode != http.StatusNotFound {
t.Fatalf("/metrics with METRICS_ENABLED=false = %d", res.StatusCode)
}
}
func itoaInt(n int) string { return strconv.Itoa(n) }
func errPrivate() error { return &ytdlp.Error{Code: ytdlp.CodePrivate, Raw: "private"} }