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
+37
View File
@@ -0,0 +1,37 @@
<style>
body{margin:0;padding:10px 12px 0;text-align:center}
#t{color:var(--tg-theme-hint-color);font-size:13px}
#a{font-size:26px;font-weight:700;margin:2px 0 6px}
canvas{display:block;margin:4px auto;border-radius:8px;background:#fff}
#w{color:var(--tg-theme-hint-color);font-size:13px;font-variant-numeric:tabular-nums;margin:6px 0 0}
#k{display:none;width:56px;height:56px;margin:8px auto 4px;border-radius:50%;background:#2e9e5b;color:#fff;font-size:32px;line-height:56px}
#m{font-weight:600;white-space:pre-wrap}
.paid #k{display:block}.paid canvas,.paid #w,.closed canvas,.closed #w{display:none}
#e{padding-bottom:max(10px,env(safe-area-inset-bottom))}
</style>
<div id="t"></div><div id="a"></div><div id="k">&#10003;</div><canvas id="q" width="0" height="0"></canvas><div id="m"></div><div id="w"></div><div id="e"></div>
<script>
var W=window.TelegramWidget,$=function(i){return document.getElementById(i)},P={},C={},drawn=0;
function j(v){try{return JSON.parse(v)||{}}catch(e){return{}}}
function qr(){
if(drawn||!P.q||!P.n)return;drawn=1;
var n=P.n,s=Math.max(2,Math.floor(208/(n+4))),c=$("q"),x=c.getContext("2d"),b=atob(P.q);
c.width=c.height=(n+4)*s;x.fillStyle="#fff";x.fillRect(0,0,c.width,c.height);x.fillStyle="#000";
for(var r=0;r<n;r++){var run=-1;for(var k=0;k<=n;k++){var i=r*n+k,on=k<n&&(b.charCodeAt(i>>3)>>(7-(i&7))&1);
if(on&&run<0)run=k;if(!on&&run>=0){x.fillRect((run+2)*s,(r+2)*s,(k-run)*s,s);run=-1}}}
}
function tick(){
if(C.s&&C.s!=="pending")return;
var l=Math.max(0,Math.floor(P.e-Date.now()/1000)),m=Math.floor(l/60),z=l%60;
$("w").textContent=l>0?(P.w||"").replace("{T}",m+":"+(z<10?"0":"")+z):(P.c||"");
}
function draw(){
P=j(W.publicData);C=j(W.chatData);
document.documentElement.dir=P.r?"rtl":"ltr";
$("t").textContent=P.t||"";$("a").textContent=P.a||"";$("m").textContent=C.m||"";
document.body.className=C.s==="paid"?"paid":(C.s&&C.s!=="pending"?"closed":"");
qr();tick();
}
W.onEvent("chatDataChanged",draw);W.onEvent("publicDataChanged",draw);
draw();setInterval(tick,1000);W.ready();
</script>
+30
View File
@@ -0,0 +1,30 @@
<style>
body{margin:0;padding:10px 12px 0}
#m{font-weight:600;white-space:pre-wrap}
#d{color:var(--tg-theme-hint-color);font-size:13px;margin-top:2px;min-height:17px}
#t{height:6px;margin:8px 0 2px;border-radius:3px;background:var(--tg-theme-section-separator-color,rgba(128,128,128,.25));overflow:hidden}
#f{height:100%;width:0;border-radius:3px;background:var(--tg-theme-button-color,#2481cc);transition:width .5s}
.busy #f{width:35%;animation:s 1.2s ease-in-out infinite alternate}
@keyframes s{from{transform:translateX(0)}to{transform:translateX(186%)}}
#x{margin:10px 0 0;width:100%}
.end #t,.end #x{display:none}
#e{padding-bottom:max(10px,env(safe-area-inset-bottom))}
</style>
<div id="m"></div><div id="d"></div><div id="t"><div id="f"></div></div><button id="x"></button><div id="e"></div>
<script>
var W=window.TelegramWidget,$=function(i){return document.getElementById(i)},s={};
function draw(){
try{s=JSON.parse(W.chatData)||{}}catch(e){s={}}
document.documentElement.dir=s.r?"rtl":"ltr";
$("m").textContent=s.m||"";$("d").textContent=s.d||"";
var b=document.body;b.className=s.k==="end"?"end":(s.p<0?"busy":"");
$("f").style.width=s.p>0?Math.round(s.p*100)+"%":"";
$("t").style.display=s.k==="queued"?"none":"";
var x=$("x");x.textContent=s.x||"";x.style.display=s.x&&s.k!=="end"?"":"none";x.disabled=false;
}
$("x").addEventListener("click",function(){
var x=$("x");x.disabled=true;
W.request("cx").then(function(a){if(a&&a.result){$("d").textContent=a.result}},function(){x.disabled=false});
});
W.onEvent("chatDataChanged",draw);draw();W.ready();
</script>
+5
View File
@@ -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"
}
+229
View File
@@ -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()
}
+135
View File
@@ -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", "<input", "<select", "-inline", "inset-block", "-block-", "color-mix(", ":has(", "@import", "\u2014"} {
if strings.Contains(html, bad) {
t.Errorf("%s uses %q, which widgets do not support", name, bad)
}
}
if !strings.Contains(html, "TelegramWidget") || !strings.Contains(html, "chatDataChanged") {
t.Errorf("%s does not follow its state", name)
}
}
}
func TestCheckHTMLRefusesTooMuch(t *testing.T) {
if CheckHTML("") == nil || CheckHTML(strings.Repeat("a", MaxHTML+1)) == nil {
t.Fatal("empty or oversized html accepted")
}
// Random-looking text does not compress.
var sb strings.Builder
x := uint32(2463534242)
for i := 0; i < 12000; i++ {
x ^= x << 13
x ^= x >> 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)
}
}