Files
Media-download-telegram-bot/internal/bot/status.go
T
MichilisandClaude Opus 5.5 3c153af97f 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>
2026-11-18 18:24:36 +00:00

302 lines
9.5 KiB
Go

package bot
import (
"context"
"strings"
"time"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/links"
"github.com/noderunners/dlbot/internal/sched"
"github.com/noderunners/dlbot/internal/tg"
"github.com/noderunners/dlbot/internal/ytdlp"
)
// statusState remembers what a status message shows, so edits that would
// change nothing or come too fast are skipped.
type statusState struct {
text string
buttons string
phase string
at time.Time
}
// keyboardSignature identifies a keyboard by the callback data and links
// of its buttons.
func keyboardSignature(kb *telego.InlineKeyboardMarkup) string {
if kb == nil {
return ""
}
var sb strings.Builder
for _, row := range kb.InlineKeyboard {
for _, btn := range row {
sb.WriteString(btn.CallbackData)
sb.WriteString(btn.URL)
sb.WriteByte('|')
}
}
return sb.String()
}
// eventLoop reacts to job events and periodically reconciles, which covers
// dropped events and work left over from before a restart.
func (b *Bot) eventLoop(ctx context.Context) {
b.safely("reconcile", func() { b.reconcile(ctx) })
t := time.NewTicker(b.reconcileEvery)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case ev := <-b.events:
b.safely("event", func() { b.handleEvent(ctx, ev) })
case ev := <-b.payEvents:
b.safely("payment", func() { b.handlePayEvent(ctx, ev) })
case <-b.pump:
b.safely("playlist", func() { b.pumpPlaylists(ctx) })
case <-t.C:
b.safely("reconcile", func() { b.reconcile(ctx) })
}
}
}
func (b *Bot) handleEvent(ctx context.Context, ev sched.Event) {
b.observe(ctx, ev)
switch ev.Type {
case sched.EventStarted, sched.EventProgress, sched.EventRequeued:
b.refreshStatus(ctx, ev.JobID)
case sched.EventStored:
b.goBG("deliver", func() { b.deliverJob(ctx, ev.JobID) })
case sched.EventFailed:
b.failJob(ctx, ev.JobID)
b.pumpSoon()
case sched.EventCancelled:
b.cleanupCancelled(ctx, ev.JobID)
b.pumpSoon()
}
}
// reconcile brings Telegram in line with the database: it resumes
// deliveries, reports failures, frees stuck uploads and refreshes the
// position shown on queued jobs.
func (b *Bot) reconcile(ctx context.Context) {
if ctx.Err() != nil {
return
}
stale, err := b.store.StaleSendingDeliveries(ctx, db.NowMilli()-staleSending.Milliseconds())
if err != nil {
b.log.Error("reconcile: stale deliveries", "err", err)
}
for _, d := range stale {
if _, err := b.store.TransitionDelivery(ctx, d.ID, db.DeliverySending, db.DeliveryPending, ""); err != nil {
b.log.Error("reconcile: reset delivery", "delivery_id", d.ID, "err", err)
}
}
each := func(status string, fn func(jobID string)) {
jobIDs, err := b.store.PendingDeliveryJobIDs(ctx, status, 200)
if err != nil {
b.log.Error("reconcile: list jobs", "status", status, "err", err)
return
}
for _, id := range jobIDs {
fn(id)
}
}
each(db.JobDelivering, func(id string) { b.goBG("deliver", func() { b.deliverJob(ctx, id) }) })
each(db.JobFailed, func(id string) { b.failJob(ctx, id) })
each(db.JobCancelled, func(id string) { b.cleanupCancelled(ctx, id) })
each(db.JobQueued, func(id string) { b.refreshStatus(ctx, id) })
each(db.JobRunning, func(id string) { b.refreshStatus(ctx, id) })
// Refunds and paid follow-ups that an interruption left undone.
b.svc.ReleasePending(ctx)
b.fulfilPending(ctx)
b.pumpPlaylists(ctx)
// Jobs whose requesters were all served but that were never closed.
delivering, err := b.store.JobsByStatus(ctx, db.JobDelivering, 200)
if err != nil {
b.log.Error("reconcile: delivering jobs", "err", err)
return
}
for _, j := range delivering {
b.finishIfServed(ctx, j)
}
}
// staleSending is how long a delivery may sit in "sending" before it is
// assumed to be left over from a crash.
const staleSending = 20 * time.Minute
// refreshStatus updates the status message of every waiting requester of
// a job.
func (b *Bot) refreshStatus(ctx context.Context, jobID string) {
job, err := b.store.GetJob(ctx, jobID)
if err != nil {
return
}
if job.Status != db.JobQueued && job.Status != db.JobRunning {
return
}
dels, err := b.store.DeliveriesForJob(ctx, jobID, db.DeliveryPending)
if err != nil {
b.log.Error("list deliveries", "job_id", jobID, "err", err)
return
}
for _, d := range dels {
text, kb, phase := b.renderStatus(ctx, d, job)
b.setStatus(ctx, d, text, kb, phase, false)
}
}
// renderStatus builds the live status text of a delivery. phase groups
// states that only differ in numbers, which is what throttling keys on.
func (b *Bot) renderStatus(ctx context.Context, d *db.Delivery, job *db.Job) (text string, kb *telego.InlineKeyboardMarkup, phase string) {
lang := d.Lang
head := titleLine(job.Title) + "\n"
cancel := b.cancelJobKeyboard(lang, d.ID)
switch job.Status {
case db.JobQueued:
kb := cancel
if job.Lane == db.LaneFree && b.bill.Enabled() && b.cfg.Prices.SkipQueue > 0 {
kb = b.queuedKeyboard(lang, d.ID)
}
pos, err := b.sched.Position(ctx, job, b.slots())
if err != nil {
b.log.Error("queue position", "job_id", job.ID, "err", err)
}
return head + b.tr.HTML(lang, "status.queued", i18n.Args{
"Position": pos.Ahead + 1,
"Wait": b.tr.Span(lang, pos.Wait),
}), kb, "queued"
case db.JobRunning:
switch job.Stage {
case ytdlp.StageProcessing:
return head + b.tr.HTML(lang, "status.processing", nil), cancel, "processing"
case ytdlp.StageUploading:
return head + b.tr.HTML(lang, "status.uploading", nil), cancel, "uploading"
}
switch {
case job.TotalBytes > 0:
ratio := float64(job.ProgressBytes) / float64(job.TotalBytes)
return head + b.tr.HTML(lang, "status.downloading_progress", i18n.Args{
"Bar": bar(ratio),
"Percent": b.tr.Percent(lang, ratio),
"Done": b.tr.Size(lang, job.ProgressBytes),
"Total": b.tr.Size(lang, job.TotalBytes),
}), cancel, "downloading"
case job.ProgressBytes > 0:
return head + b.tr.HTML(lang, "status.downloading_bytes", i18n.Args{
"Done": b.tr.Size(lang, job.ProgressBytes),
}), cancel, "downloading"
}
return head + b.tr.HTML(lang, "status.downloading", nil), cancel, "downloading"
case db.JobDelivering:
return head + b.tr.HTML(lang, "status.uploading", nil), nil, "uploading"
case db.JobDone:
return head + b.tr.HTML(lang, "status.done", nil), nil, "done"
case db.JobCancelled:
return head + b.tr.HTML(lang, "status.cancelled", nil), nil, "cancelled"
default:
return head + b.failureText(lang, job.ErrorCode), nil, "failed"
}
}
// failureText is the user-facing explanation of a failed job.
func (b *Bot) failureText(lang, code string) string {
if code == "" {
code = string(ytdlp.CodeUnknown)
}
return b.tr.HTML(lang, "status.failed", i18n.Args{"Reason": b.tr.T(lang, "error."+code, nil)})
}
// setStatus edits the status message unless nothing changed or the last
// edit of the same phase was too recent. Telegram limits how often a
// message may be edited, and progress numbers are not worth a flood wait.
func (b *Bot) setStatus(ctx context.Context, d *db.Delivery, text string, kb *telego.InlineKeyboardMarkup, phase string, force bool) {
if d.StatusMessageID == 0 {
return
}
now := time.Now()
// What the message shows is its text and its buttons. A change in
// either is worth an edit, for example "Skip the queue" disappearing.
shown := text + "\x00" + keyboardSignature(kb)
b.statusMu.Lock()
st := b.statuses[d.ID]
if st != nil {
sameButtons := keyboardSignature(kb) == st.buttons
if st.text == shown || (!force && sameButtons && st.phase == phase && now.Sub(st.at) < b.statusMinGap) {
b.statusMu.Unlock()
return
}
}
b.statuses[d.ID] = &statusState{text: shown, buttons: keyboardSignature(kb), phase: phase, at: now}
b.statusMu.Unlock()
if b.liveStatus(ctx, d, kb) {
return
}
if err := b.edit(ctx, d.ChatID, d.StatusMessageID, d.StatusIsPhoto, text, kb); err != nil {
if wait := tg.RetryAfter(err); wait > 0 {
// Back off this message for as long as Telegram asked.
b.statusMu.Lock()
if cur := b.statuses[d.ID]; cur != nil {
cur.text = ""
cur.at = now.Add(wait)
}
b.statusMu.Unlock()
}
}
}
// finalStatus writes the last state of a delivery and forgets its
// throttling state. When the status message is gone a new one is sent, so
// the requester always learns the outcome.
func (b *Bot) finalStatus(ctx context.Context, d *db.Delivery, text string) {
b.statusMu.Lock()
delete(b.statuses, d.ID)
b.statusMu.Unlock()
if b.liveFinal(ctx, d, text) {
return
}
if d.StatusMessageID != 0 {
err := b.edit(ctx, d.ChatID, d.StatusMessageID, d.StatusIsPhoto, text, nil)
if err == nil || !tg.IsMessageGone(err) {
return
}
}
_, _ = b.send(ctx, d.ChatID, d.ReplyToMessageID, text, nil)
}
// observe feeds the metrics from job events.
func (b *Bot) observe(ctx context.Context, ev sched.Event) {
if b.metrics == nil {
return
}
switch ev.Type {
case sched.EventStarted, sched.EventStored, sched.EventFailed, sched.EventCancelled:
default:
return
}
job, err := b.store.GetJob(ctx, ev.JobID)
if err != nil {
return
}
switch ev.Type {
case sched.EventStarted:
if job.QueuedAt > 0 && job.StartedAt >= job.QueuedAt {
b.metrics.QueueWait(time.Duration(job.StartedAt-job.QueuedAt) * time.Millisecond)
}
case sched.EventStored:
b.metrics.JobFinished("done", job.Lane)
case sched.EventFailed:
b.metrics.JobFinished("failed", job.Lane)
b.metrics.DownloadError(links.Site(job.URL), job.ErrorCode)
case sched.EventCancelled:
b.metrics.JobFinished("cancelled", job.Lane)
}
}