diff --git a/internal/channels/telegram/ratelimit.go b/internal/channels/telegram/ratelimit.go new file mode 100644 index 000000000..35214b5df --- /dev/null +++ b/internal/channels/telegram/ratelimit.go @@ -0,0 +1,51 @@ +package telegram + +import ( + "context" + "errors" + "time" + + "github.com/go-telegram/bot" +) + +// maxRetryAfter bounds how long a 429 can park the update loop. Telegram's +// retry_after is normally single-digit seconds; the cap stops a hostile or +// buggy value from stalling the gateway indefinitely. +const maxRetryAfter = 60 * time.Second + +// pipelineErrorHandler logs update-loop failures and, on a rate limit, waits +// the interval Telegram asked for. +// +// go-telegram/bot backs off on its own schedule -- 100ms, doubling, capped at +// 5s (get_updates.go incErrTimeout) -- and never reads RetryAfter. Against a +// "retry_after: 5" that means roughly a dozen further requests inside the +// window Telegram told us to stay silent for, which is what escalates a brief +// 429 into sustained 429s, 502s and request timeouts. The library calls this +// handler synchronously from the polling loop before applying its own backoff, +// so blocking here is the supported way to honour the interval without +// patching the dependency. +func (g *Gateway) pipelineErrorHandler(ctx context.Context) func(error) { + return func(err error) { + // errors.As unwraps the library's fmt.Errorf("error get updates, %w"). + var tooMany *bot.TooManyRequestsError + if !errors.As(err, &tooMany) { + g.log.Error("telegram pipeline error", "error", err) + return + } + + wait := time.Duration(tooMany.RetryAfter) * time.Second + if wait <= 0 { + wait = time.Second + } + wait = min(wait, maxRetryAfter) + + g.log.Warn("telegram rate limited, pausing update loop", + "retry_after", wait.String(), + "component", "gateway-telegram") + + select { + case <-ctx.Done(): + case <-time.After(wait): + } + } +} diff --git a/internal/channels/telegram/ratelimit_test.go b/internal/channels/telegram/ratelimit_test.go new file mode 100644 index 000000000..1769a6c0a --- /dev/null +++ b/internal/channels/telegram/ratelimit_test.go @@ -0,0 +1,94 @@ +package telegram + +import ( + "context" + "errors" + "fmt" + "log/slog" + "testing" + "time" + + "github.com/go-telegram/bot" +) + +// TestPipelineErrorHandlerHonoursRetryAfter pins the fix for the carina +// incident: go-telegram/bot backs off 100ms and doubles, ignoring the +// retry_after Telegram sends, so a 429 was answered with a burst of further +// requests inside the window we were told to stay quiet for. +func TestPipelineErrorHandlerHonoursRetryAfter(t *testing.T) { + tests := []struct { + name string + err error + minWait time.Duration + maxWait time.Duration + }{ + { + name: "bare rate limit error waits the stated interval", + err: &bot.TooManyRequestsError{RetryAfter: 1}, + minWait: time.Second, + maxWait: 3 * time.Second, + }, + { + // The library wraps it: fmt.Errorf("error get updates, %w", err). + name: "wrapped rate limit error is still recognised", + err: fmt.Errorf("error get updates, %w", &bot.TooManyRequestsError{RetryAfter: 1}), + minWait: time.Second, + maxWait: 3 * time.Second, + }, + { + name: "zero retry_after still pauses rather than spinning", + err: &bot.TooManyRequestsError{RetryAfter: 0}, + minWait: time.Second, + maxWait: 3 * time.Second, + }, + { + name: "unrelated errors are logged without pausing", + err: errors.New("502 Bad Gateway"), + minWait: 0, + maxWait: 250 * time.Millisecond, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + g := &Gateway{log: slog.New(slog.DiscardHandler)} + handle := g.pipelineErrorHandler(context.Background()) + + start := time.Now() + handle(tc.err) + elapsed := time.Since(start) + + if elapsed < tc.minWait { + t.Errorf("returned after %s, want at least %s", elapsed, tc.minWait) + } + if elapsed > tc.maxWait { + t.Errorf("returned after %s, want at most %s", elapsed, tc.maxWait) + } + }) + } +} + +// TestPipelineErrorHandlerReleasesOnShutdown pins that a rate-limit pause does +// not hold the update loop open past cancellation -- otherwise a /restart or +// SIGTERM during a 429 would block for the full retry_after. +func TestPipelineErrorHandlerReleasesOnShutdown(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + g := &Gateway{log: slog.New(slog.DiscardHandler)} + handle := g.pipelineErrorHandler(ctx) + + cancel() + start := time.Now() + handle(&bot.TooManyRequestsError{RetryAfter: 30}) + + if elapsed := time.Since(start); elapsed > 250*time.Millisecond { + t.Errorf("blocked %s after cancellation, want immediate return", elapsed) + } +} + +// TestRetryAfterIsBounded pins the ceiling on how long a single 429 can park +// the loop, so an implausible retry_after cannot stall the gateway. +func TestRetryAfterIsBounded(t *testing.T) { + if maxRetryAfter > 5*time.Minute { + t.Errorf("maxRetryAfter = %s, too long to leave the gateway unresponsive", maxRetryAfter) + } +} diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index 5eec749dd..0c3974cd5 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -181,9 +181,7 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot, g.turns = gateway.NewTurns(g.log) opts := []bot.Option{ - bot.WithErrorsHandler(func(err error) { - g.log.Error("telegram pipeline error", "error", err) - }), + bot.WithErrorsHandler(g.pipelineErrorHandler(ctx)), bot.WithDebugHandler(func(format string, args ...any) { g.log.Debug("telegram debug", "message", fmt.Sprintf(format, args...)) }), @@ -474,10 +472,16 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc { // aimed at had already finished. func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Message, router *gateway.Router) { gm := gateway.Message{ + // Telegram's message ID makes persistence idempotent, so a + // redelivered update updates the stored turn instead of appending + // a duplicate. Date is the sender's clock reading for the message + // and is what history should be ordered by. + SourceID: fmt.Sprintf("%d", msg.ID), ChannelID: fmt.Sprintf("%d", msg.Chat.ID), ThreadID: threadIDString(msg.MessageThreadID), From: msg.From.Username, Text: msg.Text, + At: time.Unix(int64(msg.Date), 0).UTC(), } // The lane key must be the session, so that /stop -- which resolves