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
+156
View File
@@ -0,0 +1,156 @@
# Monitoring
The core and every standalone worker serve Prometheus metrics. Logs go to
standard output as JSON. `/healthz` answers for load balancers and
container health checks.
## Endpoints
| Process | Health | Metrics |
| --- | --- | --- |
| core | `GET /healthz` on `HTTP_LISTEN` (200 while the database answers) | `GET /metrics` on `HTTP_LISTEN` |
| worker | `GET /healthz` on `WORKER_HEALTH_LISTEN` (503 when the core is unreachable or the token is rejected) | `GET /metrics` on `WORKER_HEALTH_LISTEN` |
`METRICS_ENABLED=false` removes `/metrics` from the core. The metrics
contain no user IDs, links, titles or tokens, but keep them on the private
network all the same: when the core sits behind a public reverse proxy,
do not forward `/metrics`.
`deploy/prometheus/prometheus.yml` is a scrape configuration to start from
and `deploy/prometheus/alerts.yml` a set of alert rules. Neither was
loaded into a real Prometheus while writing them; check them with
`promtool check config` and `promtool check rules` before relying on them.
## Core metrics
| Metric | Type | Meaning |
| --- | --- | --- |
| `dlbot_queue_jobs{lane}` | gauge | Jobs waiting, `paid` and `free` |
| `dlbot_queue_oldest_wait_seconds` | gauge | How long the oldest waiting job has waited |
| `dlbot_queue_wait_seconds` | histogram | Time from queued to started, per job |
| `dlbot_jobs_running` | gauge | Jobs a worker is working on |
| `dlbot_worker_slots` | gauge | Download slots of all connected workers |
| `dlbot_worker_heartbeat_age_seconds{worker,state}` | gauge | Time since each remote worker last checked in; -1 for never |
| `dlbot_jobs_finished_total{outcome,lane}` | counter | `done`, `failed`, `cancelled`. Cache hits count as done |
| `dlbot_download_errors_total{site,code}` | counter | Failed downloads by host and error class |
| `dlbot_deliveries_total{via}` | counter | Files sent: `upload` (a fresh file) or `cache` (Telegram's copy) |
| `dlbot_cache_hits_total`, `dlbot_cache_misses_total` | counter | Cache lookups since the start |
| `dlbot_cache_bytes_saved_total` | counter | Download volume the cache saved |
| `dlbot_invoices_created_total`, `dlbot_invoices_settled_total` | counter | Lightning invoices since the start |
| `dlbot_lightning_up` | gauge | 1 when the last call to LNbits worked; absent with payments off |
| `dlbot_widgets_total{widget,outcome}` | counter | HTML widgets `sent`, and `fallback` to ordinary messages |
| `dlbot_updates_total{type}` | counter | Telegram updates handled |
| `dlbot_wallets_mismatched` | gauge | Wallets whose balance disagrees with their ledger, checked every 10 minutes. Always 0 unless something is badly wrong |
| `dlbot_scrape_errors{source}` | gauge | A source that could not be read during this scrape |
Plus the standard `go_*` and `process_*` metrics.
Counters restart at zero when the process restarts. Use `rate()` and
`increase()`, which handle that.
## Worker metrics
| Metric | Type | Meaning |
| --- | --- | --- |
| `dlbot_worker_active_jobs` | gauge | Downloads running now |
| `dlbot_worker_capacity` | gauge | `WORKER_CONCURRENCY` |
| `dlbot_worker_core_contact_age_seconds` | gauge | Time since the core last answered |
| `dlbot_worker_token_rejected` | gauge | 1 when the core refused the token |
| `dlbot_worker_jobs_total{outcome}` | counter | `done`, `failed`, `cancelled`, `handed_back`, `lease_lost` |
| `dlbot_worker_ytdlp_info{version}` | gauge | Always 1; the label is the yt-dlp version |
## Dashboard notes
One dashboard covers a deployment. Suggested rows and panels, with the
query for each:
**Service**
- Up: `up{job=~"dlbot-.*"}` (stat, per instance)
- Updates per minute: `sum by (type) (rate(dlbot_updates_total[5m])) * 60`
- Memory: `process_resident_memory_bytes{job="dlbot-core"}`
**Queue**
- Waiting jobs, stacked by lane: `dlbot_queue_jobs`
- Slots busy and total: `dlbot_jobs_running` and `dlbot_worker_slots` on
one graph. Busy at the top for long means more workers would help.
- Wait time p50 and p95:
`histogram_quantile(0.95, sum by (le) (rate(dlbot_queue_wait_seconds_bucket[10m])))`
- Oldest waiting job: `dlbot_queue_oldest_wait_seconds`
**Downloads**
- Finished per minute by outcome:
`sum by (outcome) (rate(dlbot_jobs_finished_total[5m])) * 60`
- Failure share: `sum(rate(dlbot_jobs_finished_total{outcome="failed"}[30m])) / sum(rate(dlbot_jobs_finished_total[30m]))`
- Errors by site, top 10 (table):
`topk(10, sum by (site, code) (increase(dlbot_download_errors_total[1h])))`.
A site whose errors jump is the first sign that yt-dlp needs
`/ytdlp update` or that the site blocks the workers' network (see tags
in [WORKERS.md](WORKERS.md)).
**Cache**
- Hit rate: `rate(dlbot_cache_hits_total[1h]) / (rate(dlbot_cache_hits_total[1h]) + rate(dlbot_cache_misses_total[1h]))`
- Volume saved per day: `increase(dlbot_cache_bytes_saved_total[1d])`
**Workers**
- Heartbeat age per worker: `dlbot_worker_heartbeat_age_seconds`
(anything over 30 s while `active` deserves a look; the lease is 30 s)
- Jobs per worker by outcome: `sum by (instance, outcome) (rate(dlbot_worker_jobs_total[15m]))`.
Many `lease_lost` on one worker means it is overloaded or its network
is unreliable.
- yt-dlp versions: `dlbot_worker_ytdlp_info` (table of the labels). Workers
on different versions is normal for a few hours after a release.
**Payments**
- Lightning reachable: `dlbot_lightning_up`
- Invoices created and settled per hour:
`increase(dlbot_invoices_created_total[1h])`, `increase(dlbot_invoices_settled_total[1h])`.
A settled share that drops to zero while invoices are still created
points at the webhook or LNbits itself.
**Widgets**
- `sum by (widget, outcome) (increase(dlbot_widgets_total[1h]))`. Fallbacks
are harmless; a steady stream of them says the Bot API refuses widgets
(an old local Bot API server, for example).
## Logs
JSON lines on standard output (`LOG_FORMAT=text` for people). The fields
to filter on: `level`, `msg`, `job_id`, `delivery_id`, `purchase_id`,
`chat_id`, `worker_id`. Tokens, the webhook secret and LNbits keys are
removed from every line. URLs are logged without user info, and query
values that look like credentials (tokens, signatures, keys) are blanked.
Worth an alert in your log system:
- `level=ERROR` at all: each one is something the bot could not handle.
- `msg="wallet balances disagree with the ledger"`: never expected. It is
checked when Prometheus scrapes, at most every 10 minutes, and shows in
`dlbot_wallets_mismatched` and in the owner command `/stats`.
- `msg="widget refused, using an ordinary message"` in bulk.
## Load test
`make loadtest` (or `deploy/loadtest/run.sh` with settings) starts the
fake Telegram, a real core and optionally real remote workers, with a
yt-dlp stand-in that takes `LOAD_TIME` seconds per download and never
touches the network. Simulated users send links, press a format and wait
for the file. It prints throughput and the time from link to card and
from link to file, then the core's queue metrics.
```sh
USERS=80 LINKS=3 WORKERS=3 SLOTS=4 deploy/loadtest/run.sh
```
Measured on the development machine (8 cores, SQLite, 2 MB files, 2 s
per download):
| Setup | Requests | Delivered | Files per minute | Link to card p50 | Link to file p95 |
| --- | --- | --- | --- | --- | --- |
| embedded worker, 4 slots, 30 users | 90 | 90 | 106 | 310 ms | 20 s |
| 3 remote workers x 4 slots, 80 users | 240 | 240 | 224 | 330 ms | 25 s |
Four slots at 2 s per file allow at most 120 files a minute, so the first
row runs close to that limit: the time on top of the download is the
queue, which is the point of the test. Use it to size a deployment: run
it with your expected peak of users and the worker count you plan, and
look at the queue wait. It does not measure the sites or Telegram's own
upload speed, which dominate in production.