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:
co-authored by
Claude Opus 5.5
parent
f1f9c6156c
commit
3c153af97f
@@ -0,0 +1,338 @@
|
||||
// Package metrics exposes the core's Prometheus metrics at /metrics.
|
||||
//
|
||||
// Two kinds: counters and histograms that code updates as things happen
|
||||
// (downloads finished, errors per site, widgets), and values read when
|
||||
// Prometheus scrapes (queue depth, worker heartbeats, cache and payment
|
||||
// counters), so they are never out of date and cost nothing in between.
|
||||
//
|
||||
// Every method is safe on a nil *Metrics, so code and tests that do not
|
||||
// care about metrics pass nil.
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/collectors"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
)
|
||||
|
||||
const ns = "dlbot"
|
||||
|
||||
// Queue is a snapshot of the queue.
|
||||
type Queue struct {
|
||||
Paid, Free int
|
||||
// OldestWait is how long the oldest queued job has waited.
|
||||
OldestWait time.Duration
|
||||
Running int
|
||||
Capacity int
|
||||
}
|
||||
|
||||
// Worker is what the core knows about one remote worker.
|
||||
type Worker struct {
|
||||
Name string
|
||||
State string // active, offline, draining, revoked
|
||||
LastSeen time.Time
|
||||
Capacity int
|
||||
}
|
||||
|
||||
// Sources are read at scrape time. Any of them may be nil.
|
||||
type Sources struct {
|
||||
Queue func(ctx context.Context) (Queue, error)
|
||||
Workers func(ctx context.Context) ([]Worker, error)
|
||||
// Cache returns hits, misses and bytes saved since the start.
|
||||
Cache func() (hits, misses, bytesSaved int64)
|
||||
// Invoices returns invoices created and settled since the start.
|
||||
Invoices func() (created, settled int64)
|
||||
// Lightning reports whether payments are set up, and whether the last
|
||||
// call to the backend worked.
|
||||
Lightning func() (enabled, reachable bool)
|
||||
// Books counts wallets whose balance disagrees with their ledger. It
|
||||
// reads every ledger row, so it runs at most every BooksEvery.
|
||||
Books func(ctx context.Context) (int, error)
|
||||
BooksEvery time.Duration
|
||||
}
|
||||
|
||||
// Metrics holds the collectors of the core.
|
||||
type Metrics struct {
|
||||
reg *prometheus.Registry
|
||||
|
||||
queueWait prometheus.Histogram
|
||||
jobs *prometheus.CounterVec
|
||||
errors *prometheus.CounterVec
|
||||
deliveries *prometheus.CounterVec
|
||||
widgets *prometheus.CounterVec
|
||||
updates *prometheus.CounterVec
|
||||
}
|
||||
|
||||
// New creates the metrics with their scrape-time sources.
|
||||
func New(src Sources) *Metrics {
|
||||
m := &Metrics{
|
||||
reg: prometheus.NewRegistry(),
|
||||
queueWait: prometheus.NewHistogram(prometheus.HistogramOpts{
|
||||
Namespace: ns, Name: "queue_wait_seconds",
|
||||
Help: "Time a job waited in the queue before a worker took it.",
|
||||
Buckets: []float64{1, 5, 15, 30, 60, 120, 300, 600, 1200, 3600},
|
||||
}),
|
||||
jobs: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: ns, Name: "jobs_finished_total",
|
||||
Help: "Jobs that ended, by outcome (done, failed, cancelled) and lane. A cache hit is a job done without a worker.",
|
||||
}, []string{"outcome", "lane"}),
|
||||
errors: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: ns, Name: "download_errors_total",
|
||||
Help: "Failed downloads by site and error class.",
|
||||
}, []string{"site", "code"}),
|
||||
deliveries: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: ns, Name: "deliveries_total",
|
||||
Help: "Files sent to Telegram, by how: upload, file_id (Telegram's copy), cache (a hit).",
|
||||
}, []string{"via"}),
|
||||
widgets: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: ns, Name: "widgets_total",
|
||||
Help: "HTML widgets sent, and ordinary messages used because sendWidget failed.",
|
||||
}, []string{"widget", "outcome"}),
|
||||
updates: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: ns, Name: "updates_total",
|
||||
Help: "Telegram updates handled, by type.",
|
||||
}, []string{"type"}),
|
||||
}
|
||||
m.reg.MustRegister(m.queueWait, m.jobs, m.errors, m.deliveries, m.widgets, m.updates,
|
||||
collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
||||
&scrape{src: src})
|
||||
return m
|
||||
}
|
||||
|
||||
// Handler serves the metrics in the Prometheus text format.
|
||||
func (m *Metrics) Handler() http.Handler {
|
||||
return promhttp.HandlerFor(m.reg, promhttp.HandlerOpts{Timeout: 10 * time.Second})
|
||||
}
|
||||
|
||||
// Registry is for tests.
|
||||
func (m *Metrics) Registry() *prometheus.Registry { return m.reg }
|
||||
|
||||
// QueueWait records how long a job waited before it started.
|
||||
func (m *Metrics) QueueWait(d time.Duration) {
|
||||
if m != nil && d >= 0 {
|
||||
m.queueWait.Observe(d.Seconds())
|
||||
}
|
||||
}
|
||||
|
||||
// JobFinished counts a job that ended.
|
||||
func (m *Metrics) JobFinished(outcome, lane string) {
|
||||
if m != nil {
|
||||
m.jobs.WithLabelValues(outcome, lane).Inc()
|
||||
}
|
||||
}
|
||||
|
||||
// DownloadError counts a failed download. site should be the host name,
|
||||
// without "www.", so the number of series stays bounded by the sites
|
||||
// people use.
|
||||
func (m *Metrics) DownloadError(site, code string) {
|
||||
if m == nil {
|
||||
return
|
||||
}
|
||||
if site == "" {
|
||||
site = "unknown"
|
||||
}
|
||||
m.errors.WithLabelValues(site, code).Inc()
|
||||
}
|
||||
|
||||
// Delivered counts a file sent to a requester.
|
||||
func (m *Metrics) Delivered(via string) {
|
||||
if m != nil {
|
||||
m.deliveries.WithLabelValues(via).Inc()
|
||||
}
|
||||
}
|
||||
|
||||
// Widget counts a widget sent, or a fallback to an ordinary message.
|
||||
func (m *Metrics) Widget(widget, outcome string) {
|
||||
if m != nil {
|
||||
m.widgets.WithLabelValues(widget, outcome).Inc()
|
||||
}
|
||||
}
|
||||
|
||||
// Update counts a Telegram update.
|
||||
func (m *Metrics) Update(kind string) {
|
||||
if m != nil {
|
||||
m.updates.WithLabelValues(kind).Inc()
|
||||
}
|
||||
}
|
||||
|
||||
// scrape reads the sources when Prometheus asks.
|
||||
type scrape struct {
|
||||
src Sources
|
||||
|
||||
mu sync.Mutex
|
||||
booksAt time.Time
|
||||
books float64
|
||||
}
|
||||
|
||||
var (
|
||||
descQueued = prometheus.NewDesc(ns+"_queue_jobs", "Jobs waiting in the queue, by lane.", []string{"lane"}, nil)
|
||||
descOldest = prometheus.NewDesc(ns+"_queue_oldest_wait_seconds", "How long the oldest queued job has waited.", nil, nil)
|
||||
descRunning = prometheus.NewDesc(ns+"_jobs_running", "Jobs a worker is working on.", nil, nil)
|
||||
descCapacity = prometheus.NewDesc(ns+"_worker_slots", "Download slots of all connected workers.", nil, nil)
|
||||
descHeartbeat = prometheus.NewDesc(ns+"_worker_heartbeat_age_seconds", "Time since a remote worker was last heard from.", []string{"worker", "state"}, nil)
|
||||
descHits = prometheus.NewDesc(ns+"_cache_hits_total", "Requests served from the cache.", nil, nil)
|
||||
descMisses = prometheus.NewDesc(ns+"_cache_misses_total", "Requests that needed a download.", nil, nil)
|
||||
descSaved = prometheus.NewDesc(ns+"_cache_bytes_saved_total", "Download volume the cache saved.", nil, nil)
|
||||
descCreated = prometheus.NewDesc(ns+"_invoices_created_total", "Lightning invoices created.", nil, nil)
|
||||
descSettled = prometheus.NewDesc(ns+"_invoices_settled_total", "Lightning invoices paid.", nil, nil)
|
||||
descLNUp = prometheus.NewDesc(ns+"_lightning_up", "1 when the last call to the payment backend worked. Absent when payments are off.", nil, nil)
|
||||
descBooks = prometheus.NewDesc(ns+"_wallets_mismatched", "Wallets whose cached balance disagrees with their ledger. Always 0 unless something is badly wrong.", nil, nil)
|
||||
descScrapeErr = prometheus.NewDesc(ns+"_scrape_errors", "Sources that could not be read in this scrape.", []string{"source"}, nil)
|
||||
)
|
||||
|
||||
func (s *scrape) Describe(ch chan<- *prometheus.Desc) {
|
||||
for _, d := range []*prometheus.Desc{descQueued, descOldest, descRunning, descCapacity, descHeartbeat,
|
||||
descHits, descMisses, descSaved, descCreated, descSettled, descLNUp, descBooks, descScrapeErr} {
|
||||
ch <- d
|
||||
}
|
||||
}
|
||||
|
||||
func (s *scrape) Collect(ch chan<- prometheus.Metric) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
gauge := func(d *prometheus.Desc, v float64, labels ...string) {
|
||||
ch <- prometheus.MustNewConstMetric(d, prometheus.GaugeValue, v, labels...)
|
||||
}
|
||||
counter := func(d *prometheus.Desc, v int64) {
|
||||
ch <- prometheus.MustNewConstMetric(d, prometheus.CounterValue, float64(v))
|
||||
}
|
||||
failed := func(source string) { gauge(descScrapeErr, 1, source) }
|
||||
|
||||
if s.src.Queue != nil {
|
||||
if q, err := s.src.Queue(ctx); err == nil {
|
||||
gauge(descQueued, float64(q.Paid), "paid")
|
||||
gauge(descQueued, float64(q.Free), "free")
|
||||
gauge(descOldest, q.OldestWait.Seconds())
|
||||
gauge(descRunning, float64(q.Running))
|
||||
gauge(descCapacity, float64(q.Capacity))
|
||||
} else {
|
||||
failed("queue")
|
||||
}
|
||||
}
|
||||
if s.src.Workers != nil {
|
||||
if ws, err := s.src.Workers(ctx); err == nil {
|
||||
now := time.Now()
|
||||
for _, w := range ws {
|
||||
age := now.Sub(w.LastSeen).Seconds()
|
||||
if w.LastSeen.IsZero() {
|
||||
age = -1
|
||||
}
|
||||
gauge(descHeartbeat, age, w.Name, w.State)
|
||||
}
|
||||
} else {
|
||||
failed("workers")
|
||||
}
|
||||
}
|
||||
if s.src.Cache != nil {
|
||||
h, mi, saved := s.src.Cache()
|
||||
counter(descHits, h)
|
||||
counter(descMisses, mi)
|
||||
counter(descSaved, saved)
|
||||
}
|
||||
if s.src.Invoices != nil {
|
||||
c, st := s.src.Invoices()
|
||||
counter(descCreated, c)
|
||||
counter(descSettled, st)
|
||||
}
|
||||
if s.src.Books != nil {
|
||||
s.mu.Lock()
|
||||
every := s.src.BooksEvery
|
||||
if every <= 0 {
|
||||
every = 10 * time.Minute
|
||||
}
|
||||
if s.booksAt.IsZero() || time.Since(s.booksAt) > every {
|
||||
if n, err := s.src.Books(ctx); err == nil {
|
||||
s.books, s.booksAt = float64(n), time.Now()
|
||||
} else {
|
||||
failed("books")
|
||||
}
|
||||
}
|
||||
if !s.booksAt.IsZero() {
|
||||
gauge(descBooks, s.books)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
if s.src.Lightning != nil {
|
||||
if enabled, up := s.src.Lightning(); enabled {
|
||||
v := 0.0
|
||||
if up {
|
||||
v = 1
|
||||
}
|
||||
gauge(descLNUp, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WorkerSource is what a standalone worker reports about itself.
|
||||
type WorkerSource struct {
|
||||
Active func() int
|
||||
Capacity func() int
|
||||
LastContact func() (time.Time, bool)
|
||||
Outcomes func() map[string]int64
|
||||
YtDlp func() string
|
||||
}
|
||||
|
||||
// WorkerHandler serves a worker's own metrics. A worker has no database
|
||||
// and no secrets beyond its token; these numbers are all it knows.
|
||||
func WorkerHandler(src WorkerSource) http.Handler {
|
||||
reg := prometheus.NewRegistry()
|
||||
reg.MustRegister(collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), &workerScrape{src})
|
||||
return promhttp.HandlerFor(reg, promhttp.HandlerOpts{Timeout: 5 * time.Second})
|
||||
}
|
||||
|
||||
var (
|
||||
descWActive = prometheus.NewDesc(ns+"_worker_active_jobs", "Downloads running on this worker.", nil, nil)
|
||||
descWCap = prometheus.NewDesc(ns+"_worker_capacity", "Downloads this worker runs at once.", nil, nil)
|
||||
descWContact = prometheus.NewDesc(ns+"_worker_core_contact_age_seconds", "Time since the core last answered this worker.", nil, nil)
|
||||
descWAuth = prometheus.NewDesc(ns+"_worker_token_rejected", "1 when the core rejected this worker's token.", nil, nil)
|
||||
descWJobs = prometheus.NewDesc(ns+"_worker_jobs_total", "Jobs this worker finished, by outcome.", []string{"outcome"}, nil)
|
||||
descWYtDlp = prometheus.NewDesc(ns+"_worker_ytdlp_info", "The yt-dlp version this worker runs.", []string{"version"}, nil)
|
||||
)
|
||||
|
||||
type workerScrape struct{ src WorkerSource }
|
||||
|
||||
func (s *workerScrape) Describe(ch chan<- *prometheus.Desc) {
|
||||
for _, d := range []*prometheus.Desc{descWActive, descWCap, descWContact, descWAuth, descWJobs, descWYtDlp} {
|
||||
ch <- d
|
||||
}
|
||||
}
|
||||
|
||||
func (s *workerScrape) Collect(ch chan<- prometheus.Metric) {
|
||||
g := func(d *prometheus.Desc, v float64, l ...string) {
|
||||
ch <- prometheus.MustNewConstMetric(d, prometheus.GaugeValue, v, l...)
|
||||
}
|
||||
if s.src.Active != nil {
|
||||
g(descWActive, float64(s.src.Active()))
|
||||
}
|
||||
if s.src.Capacity != nil {
|
||||
g(descWCap, float64(s.src.Capacity()))
|
||||
}
|
||||
if s.src.LastContact != nil {
|
||||
last, rejected := s.src.LastContact()
|
||||
age := -1.0
|
||||
if !last.IsZero() && last.Unix() > 0 {
|
||||
age = time.Since(last).Seconds()
|
||||
}
|
||||
g(descWContact, age)
|
||||
v := 0.0
|
||||
if rejected {
|
||||
v = 1
|
||||
}
|
||||
g(descWAuth, v)
|
||||
}
|
||||
if s.src.Outcomes != nil {
|
||||
for k, v := range s.src.Outcomes() {
|
||||
ch <- prometheus.MustNewConstMetric(descWJobs, prometheus.CounterValue, float64(v), k)
|
||||
}
|
||||
}
|
||||
if s.src.YtDlp != nil {
|
||||
if v := s.src.YtDlp(); v != "" {
|
||||
g(descWYtDlp, 1, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func get(t *testing.T, serve func(*httptest.ResponseRecorder)) string {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
serve(rec)
|
||||
body, _ := io.ReadAll(rec.Result().Body)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status %d: %s", rec.Code, body)
|
||||
}
|
||||
return string(body)
|
||||
}
|
||||
|
||||
func TestCoreMetrics(t *testing.T) {
|
||||
books := 0
|
||||
m := New(Sources{
|
||||
Queue: func(context.Context) (Queue, error) {
|
||||
return Queue{Paid: 2, Free: 5, OldestWait: 90 * time.Second, Running: 3, Capacity: 4}, nil
|
||||
},
|
||||
Workers: func(context.Context) ([]Worker, error) {
|
||||
return []Worker{{Name: "eu-1", State: "active", LastSeen: time.Now().Add(-7 * time.Second)}, {Name: "new", State: "offline"}}, nil
|
||||
},
|
||||
Cache: func() (int64, int64, int64) { return 8, 2, 1 << 20 },
|
||||
Invoices: func() (int64, int64) { return 5, 3 },
|
||||
Lightning: func() (bool, bool) { return true, false },
|
||||
Books: func(context.Context) (int, error) { books++; return 0, nil },
|
||||
})
|
||||
m.QueueWait(12 * time.Second)
|
||||
m.JobFinished("done", "paid")
|
||||
m.DownloadError("", "network")
|
||||
m.Widget("job", "fallback")
|
||||
body := get(t, func(r *httptest.ResponseRecorder) {
|
||||
m.Handler().ServeHTTP(r, httptest.NewRequest("GET", "/metrics", nil))
|
||||
})
|
||||
for _, want := range []string{
|
||||
`dlbot_queue_jobs{lane="paid"} 2`, `dlbot_queue_jobs{lane="free"} 5`, "dlbot_queue_oldest_wait_seconds 90",
|
||||
"dlbot_jobs_running 3", "dlbot_worker_slots 4",
|
||||
`dlbot_worker_heartbeat_age_seconds{state="active",worker="eu-1"} 7`,
|
||||
`dlbot_worker_heartbeat_age_seconds{state="offline",worker="new"} -1`,
|
||||
"dlbot_cache_hits_total 8", "dlbot_cache_misses_total 2", "dlbot_cache_bytes_saved_total 1.048576e+06",
|
||||
"dlbot_invoices_created_total 5", "dlbot_invoices_settled_total 3", "dlbot_lightning_up 0",
|
||||
`dlbot_queue_wait_seconds_bucket{le="15"} 1`, `dlbot_jobs_finished_total{lane="paid",outcome="done"} 1`,
|
||||
`dlbot_download_errors_total{code="network",site="unknown"} 1`, `dlbot_widgets_total{outcome="fallback",widget="job"} 1`,
|
||||
"dlbot_wallets_mismatched 0",
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("missing %q", want)
|
||||
}
|
||||
}
|
||||
|
||||
// The ledger check is expensive and is not repeated on every scrape.
|
||||
get(t, func(r *httptest.ResponseRecorder) {
|
||||
m.Handler().ServeHTTP(r, httptest.NewRequest("GET", "/metrics", nil))
|
||||
})
|
||||
if books != 1 {
|
||||
t.Fatalf("the ledger was checked %d times for two scrapes", books)
|
||||
}
|
||||
|
||||
// A source that fails does not break the scrape; it is reported.
|
||||
broken := New(Sources{
|
||||
Queue: func(context.Context) (Queue, error) { return Queue{}, errors.New("db down") },
|
||||
Lightning: func() (bool, bool) { return false, false },
|
||||
})
|
||||
body = get(t, func(r *httptest.ResponseRecorder) {
|
||||
broken.Handler().ServeHTTP(r, httptest.NewRequest("GET", "/metrics", nil))
|
||||
})
|
||||
if !strings.Contains(body, `dlbot_scrape_errors{source="queue"} 1`) || strings.Contains(body, "dlbot_lightning_up") {
|
||||
t.Fatalf("broken sources: %s", body)
|
||||
}
|
||||
|
||||
var none *Metrics
|
||||
none.QueueWait(time.Second)
|
||||
none.Widget("x", "y") // nil is a no-op
|
||||
}
|
||||
|
||||
func TestWorkerMetrics(t *testing.T) {
|
||||
h := WorkerHandler(WorkerSource{
|
||||
Active: func() int { return 1 }, Capacity: func() int { return 2 },
|
||||
LastContact: func() (time.Time, bool) { return time.Now().Add(-3 * time.Second), false },
|
||||
Outcomes: func() map[string]int64 { return map[string]int64{"done": 4, "failed": 1} },
|
||||
YtDlp: func() string { return "2026.10.26" },
|
||||
})
|
||||
body := get(t, func(r *httptest.ResponseRecorder) { h.ServeHTTP(r, httptest.NewRequest("GET", "/metrics", nil)) })
|
||||
for _, want := range []string{
|
||||
"dlbot_worker_active_jobs 1", "dlbot_worker_capacity 2", "dlbot_worker_core_contact_age_seconds 3",
|
||||
"dlbot_worker_token_rejected 0", `dlbot_worker_jobs_total{outcome="done"} 4`, `dlbot_worker_ytdlp_info{version="2026.10.26"} 1`,
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("missing %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user