- 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>
309 lines
8.4 KiB
Go
309 lines
8.4 KiB
Go
// 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)
|
|
}
|
|
}
|