From bc2ad31bdc4fe36a4f948420939694d6b903050a Mon Sep 17 00:00:00 2001 From: InkCrow Date: Tue, 17 Nov 2026 17:01:53 +0800 Subject: [PATCH 1/3] fix(updates): preserve delivery during shutdown --- README.md | 25 +++- bot.go | 72 ++++++--- bot_test.go | 37 +++-- get_updates.go | 28 +++- get_updates_test.go | 256 ++++++++++++++++++++++++++++---- options.go | 4 +- process_update.go | 17 +++ wait_updates.go | 96 +++++++++++- webhook_handler.go | 48 ++++-- webhook_handler_test.go | 316 ++++++++++++++++++++++++++++++++++++---- 10 files changed, 777 insertions(+), 122 deletions(-) diff --git a/README.md b/README.md index ca19f283..97f1a8ad 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,15 @@ func handler(ctx context.Context, b *bot.Bot, update *models.Update) { If you want to use webhooks, instead of using `bot.Start`, you should use the `bot.StartWebhook` method to start the bot. Also, you should use `bot.WebhookHandler()` method as HTTP handler for your server. +`WebhookHandler` returns HTTP 503 until `StartWebhook` is accepting updates and +after shutdown begins, so Telegram retries those updates later. Cancel the +context passed to `StartWebhook` and wait for it to return: handlers receive +that context, no further updates are dispatched, and `StartWebhook` returns +once running handlers return. Handlers should return when the context is +canceled, otherwise `StartWebhook` does not return. Accepted updates still +queued at that point are dropped, since Telegram already received 200 for them, +and their count is reported to the errors handler. + ```go func main() { ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) @@ -97,16 +106,24 @@ func main() { opts := []bot.Option{ bot.WithDefaultHandler(handler), - bot.WithWebhookSecretToken(os.Getenv("EXAMPLE_TELEGRAM_WEBHOOK_SECRET_TOKEN")) + bot.WithWebhookSecretToken(os.Getenv("EXAMPLE_TELEGRAM_WEBHOOK_SECRET_TOKEN")), } - b, _ := bot.New(os.Getenv("EXAMPLE_TELEGRAM_BOT_TOKEN"), opts...) + b, err := bot.New(os.Getenv("EXAMPLE_TELEGRAM_BOT_TOKEN"), opts...) + if err != nil { + panic(err) + } // call methods.SetWebhook if needed - go b.StartWebhook(ctx) + go func() { + if err := http.ListenAndServe(":2000", b.WebhookHandler()); err != nil { + log.Printf("webhook server: %v", err) + cancel() + } + }() - http.ListenAndServe(":2000", b.WebhookHandler()) + b.StartWebhook(ctx) // call methods.DeleteWebhook if needed } diff --git a/bot.go b/bot.go index 8164d158..cf9125a1 100644 --- a/bot.go +++ b/bot.go @@ -8,6 +8,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "github.com/go-telegram/bot/models" @@ -59,7 +60,9 @@ type Bot struct { allowedUpdates AllowedUpdates - updates chan *models.Update + updatesChanCap int + updatesMx sync.Mutex + updatesRun *updatesRun } // New creates new Bot instance @@ -81,7 +84,7 @@ func New(token string, options ...Option) (*Bot, error) { checkInitTimeout: defaultCheckInitTimeout, workers: defaultWorkers, - updates: make(chan *models.Update, defaultUpdatesChanCap), + updatesChanCap: defaultUpdatesChanCap, } for _, o := range options { @@ -122,31 +125,64 @@ func (b *Bot) Token() string { return b.token } -// StartWebhook starts the Bot with webhook mode +// StartWebhook processes updates from WebhookHandler until ctx is canceled. +// Handlers receive ctx. On cancellation, WebhookHandler rejects new updates +// with 503 so Telegram retries them, workers stop dispatching, and +// StartWebhook returns once running handlers return. Accepted updates that +// were still queued are dropped and reported to the errors handler. Handlers +// should return when ctx is canceled: StartWebhook does not return until they +// do. If another Start or StartWebhook is running on the same Bot, it waits for +// that run to end first. Calling it from a handler of the running Bot therefore +// blocks until the ctx passed to that call is canceled. func (b *Bot) StartWebhook(ctx context.Context) { - wg := sync.WaitGroup{} + run := b.beginUpdates(ctx, true) + if run == nil { + return + } + defer b.endUpdates() + + workers := b.startUpdateWorkers(ctx, run) + <-ctx.Done() + + b.updatesMx.Lock() + run.webhookCtx = nil + b.updatesMx.Unlock() + run.senders.Wait() + close(run.queue) + workers.Wait() - wg.Add(b.workers) - for i := 0; i < b.workers; i++ { - go b.waitUpdates(ctx, &wg) + // A worker that exited early, such as through runtime.Goexit, can leave items behind. + for range run.queue { + atomic.AddInt64(&run.dropped, 1) } - wg.Wait() + if dropped := atomic.LoadInt64(&run.dropped); dropped > 0 { + b.error("webhook stopped before dispatching accepted updates, dropped %d", dropped) + } } -// Start the bot +// Start receives and processes updates by polling until ctx is canceled. +// A batch is confirmed once all its updates have been dispatched to handlers, +// so polling continues while asynchronous handlers run. With +// WithNotAsyncHandlers, a batch is dispatched only as fast as its handlers +// run. On cancellation, Start waits for dispatched handlers before returning. +// If cancellation comes before every update of a batch is dispatched, the +// whole batch, including updates already handled, may be delivered again when +// polling resumes. Handlers should return when ctx is canceled: Start does not +// return until they do. If another Start or StartWebhook is running on the same +// Bot, it waits for that run to end first. Calling it from a handler of the +// running Bot therefore blocks until the ctx passed to that call is canceled. func (b *Bot) Start(ctx context.Context) { - wg := sync.WaitGroup{} - - wg.Add(1) - go b.getUpdates(ctx, &wg) - - wg.Add(b.workers) - for i := 0; i < b.workers; i++ { - go b.waitUpdates(ctx, &wg) + run := b.beginUpdates(ctx, false) + if run == nil { + return } + defer b.endUpdates() - wg.Wait() + workers := b.startUpdateWorkers(ctx, run) + b.getUpdates(ctx, run.queue) + close(run.queue) + workers.Wait() } func defaultErrorsHandler(err error) { diff --git a/bot_test.go b/bot_test.go index e8cb8396..7fdc2be9 100644 --- a/bot_test.go +++ b/bot_test.go @@ -180,6 +180,7 @@ func TestBot_StartWebhookWithCorrectSecret(t *testing.T) { mx := sync.Mutex{} var called bool + handled := make(chan struct{}, 1) b.defaultHandlerFunc = func(ctx context.Context, bot *Bot, update *models.Update) { if update.Message.ID != 1 { @@ -188,14 +189,13 @@ func TestBot_StartWebhookWithCorrectSecret(t *testing.T) { mx.Lock() called = true mx.Unlock() + handled <- struct{}{} } ctx, cancel := context.WithCancel(context.Background()) defer cancel() - go b.StartWebhook(ctx) - - time.Sleep(time.Millisecond * 100) + stopped := startWebhookForTest(t, b, ctx) req, errReq := http.NewRequest(http.MethodPost, "", strings.NewReader(`{"update_id":1,"message":{"message_id":1}}`)) if errReq != nil { @@ -204,11 +204,12 @@ func TestBot_StartWebhookWithCorrectSecret(t *testing.T) { } req.Header.Set("X-Telegram-Bot-Api-Secret-Token", "zzzz") - b.WebhookHandler().ServeHTTP(nil, req) + b.WebhookHandler().ServeHTTP(httptest.NewRecorder(), req) + waitForUpdateTest(t, handled, "default handler to run") cancel() - time.Sleep(time.Millisecond * 100) + waitForUpdateTest(t, stopped, "webhook to stop") mx.Lock() if !called { @@ -229,6 +230,7 @@ func TestBot_StartWebhookWithNoSecret(t *testing.T) { mx := sync.Mutex{} var called bool + handled := make(chan struct{}, 1) b.defaultHandlerFunc = func(ctx context.Context, bot *Bot, update *models.Update) { if update.Message.ID != 1 { @@ -237,14 +239,13 @@ func TestBot_StartWebhookWithNoSecret(t *testing.T) { mx.Lock() called = true mx.Unlock() + handled <- struct{}{} } ctx, cancel := context.WithCancel(context.Background()) defer cancel() - go b.StartWebhook(ctx) - - time.Sleep(time.Millisecond * 100) + stopped := startWebhookForTest(t, b, ctx) req, errReq := http.NewRequest(http.MethodPost, "", strings.NewReader(`{"update_id":1,"message":{"message_id":1}}`)) if errReq != nil { @@ -252,11 +253,12 @@ func TestBot_StartWebhookWithNoSecret(t *testing.T) { return } - b.WebhookHandler().ServeHTTP(nil, req) + b.WebhookHandler().ServeHTTP(httptest.NewRecorder(), req) + waitForUpdateTest(t, handled, "default handler to run") cancel() - time.Sleep(time.Millisecond * 100) + waitForUpdateTest(t, stopped, "webhook to stop") mx.Lock() if !called { @@ -269,7 +271,9 @@ func TestBot_StartWebhookWithWrongSecret(t *testing.T) { s := newServerMock("xxx") defer s.Close() - opts := []Option{WithServerURL(s.URL()), WithWebhookSecretToken("zzzz")} + reported := make(chan error, 4) + opts := []Option{WithServerURL(s.URL()), WithWebhookSecretToken("zzzz"), + WithErrorsHandler(func(err error) { reported <- err })} b, err := New("xxx", opts...) if err != nil { t.Fatalf("unexpected error %q", err) @@ -290,9 +294,7 @@ func TestBot_StartWebhookWithWrongSecret(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - go b.StartWebhook(ctx) - - time.Sleep(time.Millisecond * 100) + stopped := startWebhookForTest(t, b, ctx) req, errReq := http.NewRequest(http.MethodPost, "", strings.NewReader(`{"update_id":1,"message":{"message_id":1}}`)) if errReq != nil { @@ -301,11 +303,14 @@ func TestBot_StartWebhookWithWrongSecret(t *testing.T) { } req.Header.Set("X-Telegram-Bot-Api-Secret-Token", "wrong_secret") - b.WebhookHandler().ServeHTTP(nil, req) + b.WebhookHandler().ServeHTTP(httptest.NewRecorder(), req) + if got := waitForUpdateTest(t, reported, "secret token rejection"); !strings.Contains(got.Error(), "invalid webhook secret token") { + t.Errorf("reported %v, want the secret token rejection", got) + } cancel() - time.Sleep(time.Millisecond * 100) + waitForUpdateTest(t, stopped, "webhook to stop") mx.Lock() if called { diff --git a/get_updates.go b/get_updates.go index ffee34e4..2c840c13 100644 --- a/get_updates.go +++ b/get_updates.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "errors" - "sync" "sync/atomic" "time" @@ -25,9 +24,7 @@ type getUpdatesParams struct { type AllowedUpdates []string // GetUpdates https://core.telegram.org/bots/api#getupdates -func (b *Bot) getUpdates(ctx context.Context, wg *sync.WaitGroup) { - defer wg.Done() - +func (b *Bot) getUpdates(ctx context.Context, queue chan<- queuedUpdate) { var timeoutAfterError time.Duration for { @@ -79,6 +76,9 @@ func (b *Bot) getUpdates(ctx context.Context, wg *sync.WaitGroup) { // offsetStuck is set when the last update of the batch left the offset where it // was, so the very same batch comes back on the next request. offsetStuck := false + lastID := atomic.LoadInt64(&b.lastUpdateID) + dispatched := make(chan struct{}, len(updates)) + pending := 0 for _, raw := range updates { upd, errDecode := decodeUpdate(raw) @@ -92,7 +92,7 @@ func (b *Bot) getUpdates(ctx context.Context, wg *sync.WaitGroup) { } offsetStuck = false - atomic.StoreInt64(&b.lastUpdateID, upd.ID) + lastID = upd.ID if errDecode != nil { b.error("error decode update %d, skipped, %s, %w", upd.ID, raw, errDecode) @@ -101,12 +101,26 @@ func (b *Bot) getUpdates(ctx context.Context, wg *sync.WaitGroup) { select { case <-ctx.Done(): - b.error("some updates lost, ctx done") return - case b.updates <- upd: + case queue <- queuedUpdate{update: upd, dispatched: dispatched}: + pending++ } } + // The next request acknowledges the whole batch, so keep the previous + // offset if cancellation comes before every update is dispatched. + for i := 0; i < pending; i++ { + select { + case <-ctx.Done(): + return + case <-dispatched: + } + } + if ctx.Err() != nil { + return + } + atomic.StoreInt64(&b.lastUpdateID, lastID) + if offsetStuck { // Back off as on a failed request instead of re-requesting the same // batch at full speed. diff --git a/get_updates_test.go b/get_updates_test.go index bc121617..bca62326 100644 --- a/get_updates_test.go +++ b/get_updates_test.go @@ -1,11 +1,12 @@ package bot import ( + "bytes" "context" "io" "net/http" + "reflect" "strings" - "sync" "sync/atomic" "testing" "time" @@ -16,12 +17,32 @@ import ( type getUpdatesClientFunc func(*http.Request) (*http.Response, error) func (f getUpdatesClientFunc) Do(req *http.Request) (*http.Response, error) { - // drain the multipart body so the request pipe writer can finish - _, _ = io.Copy(io.Discard, req.Body) + // keep the body readable for req.FormValue + body, _ := io.ReadAll(req.Body) _ = req.Body.Close() + req.Body = io.NopCloser(bytes.NewReader(body)) return f(req) } +// runGetUpdates polls like Start does and acts as the worker: it records every +// queued update and signals that it was dispatched. +func runGetUpdates(ctx context.Context, b *Bot) []*models.Update { + queue := make(chan queuedUpdate) + var delivered []*models.Update + done := make(chan struct{}) + go func() { + defer close(done) + for item := range queue { + delivered = append(delivered, item.update) + item.dispatched <- struct{}{} + } + }() + b.getUpdates(ctx, queue) + close(queue) + <-done + return delivered +} + func getUpdatesJSONResponse(body string) *http.Response { return &http.Response{ StatusCode: http.StatusOK, @@ -45,7 +66,6 @@ func Test_getUpdates_skipsUndecodableUpdate(t *testing.T) { var errs []string b := &Bot{ token: "XXX", - updates: make(chan *models.Update, 10), errorsHandler: func(handlerErr error) { errs = append(errs, handlerErr.Error()) }, debugHandler: func(string, ...any) {}, client: getUpdatesClientFunc(func(*http.Request) (*http.Response, error) { @@ -57,18 +77,15 @@ func Test_getUpdates_skipsUndecodableUpdate(t *testing.T) { }), } - wg := sync.WaitGroup{} - wg.Add(1) - b.getUpdates(ctx, &wg) - wg.Wait() + delivered := runGetUpdates(ctx, b) if got := atomic.LoadInt64(&b.lastUpdateID); got != 102 { t.Fatalf("offset must move past the bad update, lastUpdateID=%d", got) } - if len(b.updates) != 2 { - t.Fatalf("expected 2 delivered updates, got %d", len(b.updates)) + if len(delivered) != 2 { + t.Fatalf("expected 2 delivered updates, got %d", len(delivered)) } - if first, third := <-b.updates, <-b.updates; first.ID != 100 || third.ID != 102 { + if first, third := delivered[0], delivered[1]; first.ID != 100 || third.ID != 102 { t.Fatalf("expected updates 100 and 102, got %d and %d", first.ID, third.ID) } if len(errs) != 1 || !strings.Contains(errs[0], "101") || !strings.Contains(errs[0], "not an object") { @@ -90,7 +107,6 @@ func Test_getUpdates_backsOffWhenUpdateIDUnreadable(t *testing.T) { b := &Bot{ token: "XXX", - updates: make(chan *models.Update, 10), errorsHandler: func(error) {}, debugHandler: func(string, ...any) {}, client: getUpdatesClientFunc(func(*http.Request) (*http.Response, error) { @@ -107,10 +123,7 @@ func Test_getUpdates_backsOffWhenUpdateIDUnreadable(t *testing.T) { }), } - wg := sync.WaitGroup{} - wg.Add(1) - b.getUpdates(ctx, &wg) - wg.Wait() + runGetUpdates(ctx, b) if gap < 100*time.Millisecond { t.Fatalf("expected a backoff before the next request, got %v", gap) @@ -131,7 +144,6 @@ func pollGaps(t *testing.T, batch string, calls int) []time.Duration { b := &Bot{ token: "XXX", - updates: make(chan *models.Update, 100), errorsHandler: func(error) {}, debugHandler: func(string, ...any) {}, client: getUpdatesClientFunc(func(*http.Request) (*http.Response, error) { @@ -148,10 +160,7 @@ func pollGaps(t *testing.T, batch string, calls int) []time.Duration { }), } - wg := sync.WaitGroup{} - wg.Add(1) - b.getUpdates(ctx, &wg) - wg.Wait() + runGetUpdates(ctx, b) return gaps } @@ -204,7 +213,6 @@ func Test_getUpdates_ignoresUpdateWithoutID(t *testing.T) { var calls int32 b := &Bot{ token: "XXX", - updates: make(chan *models.Update, 10), errorsHandler: func(error) {}, debugHandler: func(string, ...any) {}, client: getUpdatesClientFunc(func(*http.Request) (*http.Response, error) { @@ -216,15 +224,207 @@ func Test_getUpdates_ignoresUpdateWithoutID(t *testing.T) { }), } - wg := sync.WaitGroup{} - wg.Add(1) - b.getUpdates(ctx, &wg) - wg.Wait() + delivered := runGetUpdates(ctx, b) if got := atomic.LoadInt64(&b.lastUpdateID); got != 500 { t.Fatalf("offset must stay at the last real update, lastUpdateID=%d", got) } - if len(b.updates) != 1 { - t.Fatalf("expected only the real update to be delivered, got %d", len(b.updates)) + if len(delivered) != 1 { + t.Fatalf("expected only the real update to be delivered, got %d", len(delivered)) + } +} + +func waitForUpdateTest[T any](t *testing.T, ch <-chan T, event string) T { + t.Helper() + select { + case value := <-ch: + return value + case <-time.After(5 * time.Second): + t.Fatalf("timed out waiting for %s", event) + var zero T + return zero + } +} + +// A batch is confirmed once its asynchronous handlers start, so a handler can +// wait for an update from a later batch. +func TestBot_StartPollsWhileHandlerRuns(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + secondHandled := make(chan struct{}) + firstSawSecond := make(chan bool, 1) + offsets := make(chan string, 3) + var calls int + b, err := New("xxx", WithSkipGetMe(), + WithDefaultHandler(func(_ context.Context, _ *Bot, update *models.Update) { + if update.ID == 2 { + close(secondHandled) + return + } + select { + case <-secondHandled: + firstSawSecond <- true + case <-time.After(2 * time.Second): + firstSawSecond <- false + } + }), + WithHTTPClient(time.Second, getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) { + calls++ + offsets <- req.FormValue("offset") + switch calls { + case 1: + return getUpdatesJSONResponse(`{"ok":true,"result":[{"update_id":1}]}`), nil + case 2: + return getUpdatesJSONResponse(`{"ok":true,"result":[{"update_id":2}]}`), nil + } + <-req.Context().Done() + return nil, req.Context().Err() + })), + ) + if err != nil { + t.Fatal(err) + } + + stopped := make(chan struct{}) + go func() { + defer close(stopped) + b.Start(ctx) + }() + if !waitForUpdateTest(t, firstSawSecond, "first handler to finish") { + t.Error("the second update was not dispatched while the first handler was running") + } + cancel() + waitForUpdateTest(t, stopped, "polling to stop") + if first, second := <-offsets, <-offsets; first != "1" || second != "2" { + t.Errorf("poll offsets = %q, %q, want 1, 2", first, second) + } +} + +// A batch canceled before every update is dispatched stays unconfirmed, so the +// whole batch, including handled updates, comes back. +func TestBot_StartReplaysBatchCanceledBeforeDispatch(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + resumeCtx, cancelResume := context.WithCancel(context.Background()) + defer cancelResume() + + batch := `{"ok":true,"result":[{"update_id":40},{"update_id":42}]}` + firstStarted := make(chan struct{}) + offsets := make(chan string, 4) + var handled []int64 + var calls int + var restarting bool + b, err := New("xxx", WithSkipGetMe(), WithNotAsyncHandlers(), + WithDefaultHandler(func(ctx context.Context, _ *Bot, update *models.Update) { + handled = append(handled, update.ID) + if !restarting && update.ID == 40 { + close(firstStarted) + <-ctx.Done() + } + }), + WithHTTPClient(time.Second, getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) { + calls++ + offsets <- req.FormValue("offset") + if calls == 1 { + return getUpdatesJSONResponse(batch), nil + } + <-req.Context().Done() + return nil, req.Context().Err() + })), + ) + if err != nil { + t.Fatal(err) + } + + stopped := make(chan struct{}) + go func() { + defer close(stopped) + b.Start(ctx) + }() + waitForUpdateTest(t, firstStarted, "first handler to start") + cancel() + waitForUpdateTest(t, stopped, "polling to stop") + if got := waitForUpdateTest(t, offsets, "first poll"); got != "1" { + t.Errorf("first poll offset = %q, want 1", got) + } + + restarting = true + calls = 0 + resumed := make(chan struct{}) + go func() { + defer close(resumed) + b.Start(resumeCtx) + }() + if got := waitForUpdateTest(t, offsets, "resumed poll"); got != "1" { + t.Errorf("resumed poll offset = %q, want 1", got) + } + if got := waitForUpdateTest(t, offsets, "poll after the replayed batch"); got != "43" { + t.Errorf("offset after the replayed batch = %q, want 43", got) + } + cancelResume() + waitForUpdateTest(t, resumed, "resumed polling to stop") + if want := []int64{40, 40, 42}; !reflect.DeepEqual(handled, want) { + t.Errorf("handled updates = %v, want %v", handled, want) + } +} + +func TestBot_StartWaitsForDispatchedHandlers(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + started := make(chan struct{}) + release := make(chan struct{}) + var calls int + b, err := New("xxx", WithSkipGetMe(), + WithDefaultHandler(func(context.Context, *Bot, *models.Update) { + close(started) + // The handler ignores cancellation on purpose. + <-release + }), + WithHTTPClient(time.Second, getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) { + calls++ + if calls == 1 { + return getUpdatesJSONResponse(`{"ok":true,"result":[{"update_id":1}]}`), nil + } + <-req.Context().Done() + return nil, req.Context().Err() + })), + ) + if err != nil { + t.Fatal(err) + } + + stopped := make(chan struct{}) + go func() { + defer close(stopped) + b.Start(ctx) + }() + waitForUpdateTest(t, started, "handler to start") + cancel() + select { + case <-stopped: + t.Fatal("Start returned while a dispatched handler was running") + case <-time.After(100 * time.Millisecond): + } + close(release) + waitForUpdateTest(t, stopped, "Start to return after the handler") +} + +func TestBot_StartWithoutWorkersReportsError(t *testing.T) { + reported := make(chan error, 2) + b, err := New("xxx", WithSkipGetMe(), WithWorkers(0), + WithErrorsHandler(func(err error) { reported <- err })) + if err != nil { + t.Fatal(err) + } + + stopped := make(chan struct{}) + go func() { + defer close(stopped) + b.Start(context.Background()) + }() + waitForUpdateTest(t, stopped, "Start without workers to return") + if got := waitForUpdateTest(t, reported, "workers error"); !strings.Contains(got.Error(), "without update workers") { + t.Errorf("reported %v, want the missing workers error", got) } } diff --git a/options.go b/options.go index 0530ab18..15c05a30 100644 --- a/options.go +++ b/options.go @@ -2,8 +2,6 @@ package bot import ( "time" - - "github.com/go-telegram/bot/models" ) // Option is a function that configures a bot. @@ -107,7 +105,7 @@ func WithAllowedUpdates(params AllowedUpdates) Option { // WithUpdatesChannelCap allows setting custom capacity for the Updates channel func WithUpdatesChannelCap(cap int) Option { return func(b *Bot) { - b.updates = make(chan *models.Update, cap) + b.updatesChanCap = cap } } diff --git a/process_update.go b/process_update.go index 88d56beb..1d0157cf 100644 --- a/process_update.go +++ b/process_update.go @@ -31,6 +31,23 @@ func (b *Bot) ProcessUpdate(ctx context.Context, upd *models.Update) { go r(ctx, b, upd) } +// dispatchUpdate runs the handler of a queued update and calls done when it +// returns. +func (b *Bot) dispatchUpdate(ctx context.Context, upd *models.Update, done func()) { + r := applyMiddlewares(b.findHandler(upd), b.middlewares...) + run := func() { + defer done() + r(ctx, b, upd) + } + + if b.notAsyncHandlers { + run() + return + } + + go run() +} + func (b *Bot) findHandler(upd *models.Update) HandlerFunc { b.handlersMx.RLock() defer b.handlersMx.RUnlock() diff --git a/wait_updates.go b/wait_updates.go index 958b4525..ae5135f2 100644 --- a/wait_updates.go +++ b/wait_updates.go @@ -3,18 +3,102 @@ package bot import ( "context" "sync" + "sync/atomic" + + "github.com/go-telegram/bot/models" ) -// waitUpdates listen Updates channel and run ProcessUpdate -func (b *Bot) waitUpdates(ctx context.Context, wg *sync.WaitGroup) { - defer wg.Done() +// queuedUpdate carries an update to a worker. dispatched, when set, receives a +// signal once the worker hands the update to its handler. It must be buffered +// for the whole batch because the worker signals without waiting. +type queuedUpdate struct { + update *models.Update + dispatched chan<- struct{} +} + +type updatesRun struct { + // dropped counts updates the workers discarded after cancellation. Only + // StartWebhook reports it: unconfirmed polled updates are delivered again. + // It stays first so 32-bit platforms align it for atomic access. + dropped int64 + + queue chan queuedUpdate + webhookCtx context.Context + senders sync.WaitGroup + // done is closed when the run ends, so a later Start can proceed. + done chan struct{} +} + +func (b *Bot) beginUpdates(ctx context.Context, webhook bool) *updatesRun { + if ctx.Err() != nil { + return nil + } + if b.workers <= 0 { + b.error("cannot start bot without update workers") + return nil + } for { + if ctx.Err() != nil { + return nil + } + b.updatesMx.Lock() + previous := b.updatesRun + if previous == nil { + run := &updatesRun{queue: make(chan queuedUpdate, b.updatesChanCap), done: make(chan struct{})} + if webhook { + run.webhookCtx = ctx + } + b.updatesRun = run + b.updatesMx.Unlock() + return run + } + b.updatesMx.Unlock() + // The previous run can still be waiting for its handlers. select { + case <-previous.done: case <-ctx.Done(): - return - case upd := <-b.updates: - b.ProcessUpdate(ctx, upd) + return nil + } + } +} + +func (b *Bot) endUpdates() { + b.updatesMx.Lock() + run := b.updatesRun + b.updatesRun = nil + b.updatesMx.Unlock() + close(run.done) +} + +func (b *Bot) startUpdateWorkers(ctx context.Context, run *updatesRun) *sync.WaitGroup { + workers := &sync.WaitGroup{} + workers.Add(b.workers) + for i := 0; i < b.workers; i++ { + go func() { + defer workers.Done() + b.waitUpdates(ctx, run) + }() + } + return workers +} + +// waitUpdates dispatches queued updates until the queue is closed, then waits +// for the handlers it started. +func (b *Bot) waitUpdates(ctx context.Context, run *updatesRun) { + var handlers sync.WaitGroup + defer handlers.Wait() + for item := range run.queue { + if ctx.Err() != nil { + // Keep draining so StartWebhook can report accepted updates that were never dispatched. + atomic.AddInt64(&run.dropped, 1) + continue + } + + if item.dispatched != nil { + item.dispatched <- struct{}{} } + handlers.Add(1) + b.dispatchUpdate(ctx, item.update, handlers.Done) } } diff --git a/webhook_handler.go b/webhook_handler.go index 2cc55779..407ecb30 100644 --- a/webhook_handler.go +++ b/webhook_handler.go @@ -1,6 +1,7 @@ package bot import ( + "context" "encoding/json" "io" "net/http" @@ -8,8 +9,11 @@ import ( "github.com/go-telegram/bot/models" ) +// WebhookHandler returns an HTTP handler for updates processed by StartWebhook. +// It returns 503 when StartWebhook is not accepting updates, so Telegram +// retries them later. An unreadable request body returns 400. func (b *Bot) WebhookHandler() http.HandlerFunc { - return func(_ http.ResponseWriter, req *http.Request) { + return func(w http.ResponseWriter, req *http.Request) { if b.webhookSecretToken != "" && req.Header.Get("X-Telegram-Bot-Api-Secret-Token") != b.webhookSecretToken { b.error("invalid webhook secret token received from update") return @@ -18,6 +22,7 @@ func (b *Bot) WebhookHandler() http.HandlerFunc { body, errReadBody := io.ReadAll(req.Body) if errReadBody != nil { b.error("error read request body, %w", errReadBody) + w.WriteHeader(http.StatusBadRequest) return } @@ -33,17 +38,38 @@ func (b *Bot) WebhookHandler() http.HandlerFunc { b.debugHandler("webhook request '%s'", body) } - select { - case <-req.Context().Done(): - b.error("some updates lost, ctx done") - return - default: + if !b.queueWebhookUpdate(req.Context(), update) { + w.WriteHeader(http.StatusServiceUnavailable) } + } +} - select { - case b.updates <- update: - case <-req.Context().Done(): - b.error("failed to send update, ctx done") - } +// queueWebhookUpdate reports whether the update was accepted. Registering as a +// sender under updatesMx lets StartWebhook wait for in-flight sends before it +// closes the queue. +func (b *Bot) queueWebhookUpdate(ctx context.Context, update *models.Update) bool { + b.updatesMx.Lock() + run := b.updatesRun + if run == nil { + b.updatesMx.Unlock() + b.error("webhook update rejected: StartWebhook is not running") + return false + } + if run.webhookCtx == nil || run.webhookCtx.Err() != nil || ctx.Err() != nil { + b.updatesMx.Unlock() + return false + } + stopping := run.webhookCtx.Done() + run.senders.Add(1) + b.updatesMx.Unlock() + defer run.senders.Done() + + select { + case <-ctx.Done(): + return false + case <-stopping: + return false + case run.queue <- queuedUpdate{update: update}: + return true } } diff --git a/webhook_handler_test.go b/webhook_handler_test.go index 20eff637..c1398925 100644 --- a/webhook_handler_test.go +++ b/webhook_handler_test.go @@ -8,7 +8,10 @@ import ( "io" "net/http" "net/http/httptest" + "strings" + "sync" "testing" + "time" "github.com/go-telegram/bot/models" ) @@ -48,10 +51,14 @@ func errReader(err error) io.ReadCloser { func TestWebhookHandler_Success(t *testing.T) { debugHandler := &mockDebugHandler{} errorsHandler := &mockErrorsHandler{} + delivered := make(chan *models.Update, 1) bot := &Bot{ - updates: make(chan *models.Update, 1), + workers: 1, isDebug: true, + defaultHandlerFunc: func(_ context.Context, _ *Bot, update *models.Update) { + delivered <- update + }, debugHandler: func(format string, args ...any) { debugHandler.Handle(format, args...) }, @@ -60,6 +67,10 @@ func TestWebhookHandler_Success(t *testing.T) { }, } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + stopped := startWebhookForTest(t, bot, ctx) + update := &models.Update{ ID: 12345, } @@ -71,34 +82,48 @@ func TestWebhookHandler_Success(t *testing.T) { handler := bot.WebhookHandler() handler(w, req) - select { - case upd := <-bot.updates: - if upd.ID != update.ID { - t.Fatalf("Expected update ID %d, got %d", update.ID, upd.ID) - } - default: - t.Fatal("Expected update to be sent to bot.updates channel") + if w.Code != http.StatusOK { + t.Fatalf("webhook status %d, want 200", w.Code) } + upd := waitForUpdateTest(t, delivered, "update to be delivered") + if upd.ID != update.ID { + t.Fatalf("Expected update ID %d, got %d", update.ID, upd.ID) + } + cancel() + waitForUpdateTest(t, stopped, "webhook to stop") } func TestWebhookHandler_ReadBodyError(t *testing.T) { - debugHandler := &mockDebugHandler{} errorsHandler := &mockErrorsHandler{} + delivered := make(chan *models.Update, 1) bot := &Bot{ - debugHandler: func(format string, args ...any) { - debugHandler.Handle(format, args...) + workers: 1, + defaultHandlerFunc: func(_ context.Context, _ *Bot, update *models.Update) { + delivered <- update }, errorsHandler: func(err error) { errorsHandler.Handle(err) }, } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + stopped := startWebhookForTest(t, bot, ctx) req := httptest.NewRequest(http.MethodPost, "/", errReader(errors.New("read error"))) w := httptest.NewRecorder() handler := bot.WebhookHandler() handler(w, req) + cancel() + waitForUpdateTest(t, stopped, "webhook to stop") + + if w.Code != http.StatusBadRequest { + t.Errorf("webhook status %d, want %d", w.Code, http.StatusBadRequest) + } + if len(delivered) != 0 { + t.Error("webhook delivered an update after the body read failed") + } if len(errorsHandler.errors) == 0 { t.Fatal("Expected an error, but none occurred") @@ -139,18 +164,17 @@ func TestWebhookHandler_DecodeError(t *testing.T) { } func TestWebhookHandler_ContextDone(t *testing.T) { - debugHandler := &mockDebugHandler{} - errorsHandler := &mockErrorsHandler{} - + delivered := make(chan struct{}, 1) bot := &Bot{ - updates: make(chan *models.Update, 1), - debugHandler: func(format string, args ...any) { - debugHandler.Handle(format, args...) - }, - errorsHandler: func(err error) { - errorsHandler.Handle(err) + workers: 1, + updatesChanCap: 1, + defaultHandlerFunc: func(context.Context, *Bot, *models.Update) { + delivered <- struct{}{} }, } + runCtx, stop := context.WithCancel(context.Background()) + defer stop() + stopped := startWebhookForTest(t, bot, runCtx) update := &models.Update{ ID: 12345, @@ -166,22 +190,256 @@ func TestWebhookHandler_ContextDone(t *testing.T) { handler := bot.WebhookHandler() handler(w, req) - select { - case <-bot.updates: - t.Fatal("Did not expect update to be sent to bot.updates channel") - default: - // Expected outcome, context was cancelled before sending the update + stop() + waitForUpdateTest(t, stopped, "webhook to stop") + if w.Code != http.StatusServiceUnavailable { + t.Errorf("webhook status %d, want 503", w.Code) + } + if len(delivered) != 0 { + t.Fatal("processed an update from a canceled request") } +} - if len(errorsHandler.errors) == 0 { - t.Fatal("Expected an error, but none occurred") +func TestWebhookHandler_StopsDispatchingOnShutdown(t *testing.T) { + type contextKey struct{} + parent := context.WithValue(context.Background(), contextKey{}, "value") + ctx, cancel := context.WithCancel(parent) + defer cancel() + firstStarted := make(chan struct{}) + delivered := make(chan int64, 6) + reported := make(chan error, 6) + b, err := New("xxx", WithSkipGetMe(), WithUpdatesChannelCap(1), WithNotAsyncHandlers(), + WithErrorsHandler(func(err error) { reported <- err }), + WithDefaultHandler(func(ctx context.Context, _ *Bot, update *models.Update) { + if ctx.Value(contextKey{}) != "value" { + t.Errorf("handler context lost its values: %v", ctx) + } + if update.ID == 1 { + close(firstStarted) + // A handler waiting for cancellation must not block shutdown. + <-ctx.Done() + } + delivered <- update.ID + })) + if err != nil { + t.Fatal(err) + } + handler := b.WebhookHandler() + request := func(body string, ctx context.Context) int { + w := httptest.NewRecorder() + handler(w, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)).WithContext(ctx)) + return w.Code + } + + if got := request(`{"update_id":99}`, context.Background()); got != http.StatusServiceUnavailable { + t.Fatalf("status before starting webhook = %d, want 503", got) + } + if got := waitForUpdateTest(t, reported, "report before start"); !strings.Contains(got.Error(), "StartWebhook is not running") { + t.Errorf("reported %v, want the not running report", got) + } + stopped := startWebhookForTest(t, b, ctx) + if got := request(`{"update_id":1}`, context.Background()); got != http.StatusOK { + t.Fatalf("status for first update = %d, want 200", got) + } + waitForUpdateTest(t, firstStarted, "first webhook handler to start") + if got := request(`{"update_id":2}`, context.Background()); got != http.StatusOK { + t.Fatalf("status for queued update = %d, want 200", got) + } + + // The worker is busy and its only queue slot is occupied. + blockedCtx, cancelBlocked := context.WithCancel(context.Background()) + defer cancelBlocked() + blocked := &observedDoneContext{Context: blockedCtx, observed: make(chan struct{})} + blockedStatus := make(chan int, 1) + go func() { + blockedStatus <- request(`{"update_id":3}`, blocked) + }() + waitForUpdateTest(t, blocked.observed, "request to wait for queue space") + cancel() + if got := waitForUpdateTest(t, blockedStatus, "blocked request to return"); got != http.StatusServiceUnavailable { + t.Errorf("status for blocked update = %d, want 503", got) + } + if got := request(`{"update_id":4}`, context.Background()); got != http.StatusServiceUnavailable { + t.Errorf("status during shutdown = %d, want 503", got) + } + waitForUpdateTest(t, stopped, "webhook to stop after cancellation") + if got := waitForUpdateTest(t, delivered, "first handler to return"); got != 1 { + t.Errorf("delivered update %d, want 1", got) } + if got := waitForUpdateTest(t, reported, "dropped update report"); !strings.Contains(got.Error(), "dropped 1") { + t.Errorf("reported %v, want the dropped queued update", got) + } + + if got := request(`{"update_id":5}`, context.Background()); got != http.StatusServiceUnavailable { + t.Errorf("status after shutdown = %d, want 503", got) + } + if got := waitForUpdateTest(t, reported, "report after shutdown"); !strings.Contains(got.Error(), "StartWebhook is not running") { + t.Errorf("reported %v, want the not running report", got) + } + restartCtx, cancelRestart := context.WithCancel(parent) + defer cancelRestart() + restarted := startWebhookForTest(t, b, restartCtx) + if got := request(`{"update_id":6}`, context.Background()); got != http.StatusOK { + t.Fatalf("status after restart = %d, want 200", got) + } + if got := waitForUpdateTest(t, delivered, "update after restart"); got != 6 { + t.Errorf("delivered update %d, want 6", got) + } + cancelRestart() + waitForUpdateTest(t, restarted, "restarted webhook to stop") + if len(delivered) != 0 { + t.Error("delivered a dropped or rejected webhook update") + } + // A request that arrives after shutdown finished reports that no webhook is + // running, which the request during shutdown may or may not hit. + for len(reported) != 0 { + if got := <-reported; !strings.Contains(got.Error(), "StartWebhook is not running") { + t.Errorf("unexpected error report: %v", got) + } + } +} - if capturedError := errorsHandler.errors[0]; capturedError == nil || !containsString(capturedError.Error(), "some updates lost, ctx done") { - t.Fatalf("Expected context done error, got %v", capturedError) +func TestStartWebhook_ReturnsWhenAsyncHandlerWaitsForCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + started := make(chan struct{}) + b, err := New("xxx", WithSkipGetMe(), + WithDefaultHandler(func(ctx context.Context, _ *Bot, _ *models.Update) { + close(started) + <-ctx.Done() + })) + if err != nil { + t.Fatal(err) + } + stopped := startWebhookForTest(t, b, ctx) + w := httptest.NewRecorder() + b.WebhookHandler()(w, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"update_id":1}`))) + if w.Code != http.StatusOK { + t.Fatalf("webhook status = %d, want 200", w.Code) } + waitForUpdateTest(t, started, "handler to start") + cancel() + waitForUpdateTest(t, stopped, "webhook to stop after cancellation") +} + +func TestWebhookHandler_NoWorkers(t *testing.T) { + b, err := New("xxx", WithSkipGetMe(), WithWorkers(0), WithErrorsHandler(func(error) {})) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + stopped := make(chan struct{}) + go func() { + defer close(stopped) + b.StartWebhook(ctx) + }() + waitForUpdateTest(t, stopped, "webhook with no workers to stop") + + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"update_id":1}`)) + b.WebhookHandler().ServeHTTP(w, req) + if w.Code != http.StatusServiceUnavailable { + t.Fatalf("webhook status without workers = %d, want 503", w.Code) + } +} + +type observedDoneContext struct { + context.Context + observed chan struct{} + once sync.Once +} + +func (ctx *observedDoneContext) Done() <-chan struct{} { + ctx.once.Do(func() { close(ctx.observed) }) + return ctx.Context.Done() +} + +// startWebhookForTest relies on StartWebhook calling ctx.Done only after it +// registered the run, which holds unless it waits for a previous run. Start +// such a second run in a plain goroutine instead. +func startWebhookForTest(t *testing.T, b *Bot, ctx context.Context) <-chan struct{} { + t.Helper() + observed := &observedDoneContext{Context: ctx, observed: make(chan struct{})} + stopped := make(chan struct{}) + go func() { + defer close(stopped) + b.StartWebhook(observed) + }() + waitForUpdateTest(t, observed.observed, "webhook to start") + return stopped } func containsString(s, substr string) bool { return bytes.Contains([]byte(s), []byte(substr)) } + +func TestStartWebhook_RestartWaitsForPreviousRun(t *testing.T) { + ctx1, cancel1 := context.WithCancel(context.Background()) + defer cancel1() + ctx2, cancel2 := context.WithCancel(context.Background()) + defer cancel2() + started := make(chan struct{}) + release := make(chan struct{}) + delivered := make(chan int64, 4) + reported := make(chan error, 8) + b, err := New("xxx", WithSkipGetMe(), + WithErrorsHandler(func(err error) { + // Many 503s can pile up in the handover window; never block a request. + select { + case reported <- err: + default: + } + }), + WithDefaultHandler(func(_ context.Context, _ *Bot, update *models.Update) { + if update.ID == 1 { + close(started) + // The handler ignores cancellation on purpose. + <-release + return + } + delivered <- update.ID + })) + if err != nil { + t.Fatal(err) + } + request := func(body string) int { + w := httptest.NewRecorder() + b.WebhookHandler()(w, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body))) + return w.Code + } + + firstStopped := startWebhookForTest(t, b, ctx1) + if got := request(`{"update_id":1}`); got != http.StatusOK { + t.Fatalf("status for first update = %d, want 200", got) + } + waitForUpdateTest(t, started, "first handler to start") + cancel1() + secondStopped := make(chan struct{}) + go func() { + defer close(secondStopped) + b.StartWebhook(ctx2) + }() + select { + case <-secondStopped: + t.Fatal("second StartWebhook returned while the previous run was still shutting down") + case err := <-reported: + t.Fatalf("unexpected error report: %v", err) + case <-time.After(100 * time.Millisecond): + } + + close(release) + waitForUpdateTest(t, firstStopped, "first webhook to stop") + deadline := time.Now().Add(5 * time.Second) + for request(`{"update_id":2}`) != http.StatusOK { + if time.Now().After(deadline) { + t.Fatal("second run never accepted an update") + } + time.Sleep(10 * time.Millisecond) + } + if got := waitForUpdateTest(t, delivered, "update from the second run"); got != 2 { + t.Errorf("delivered update %d, want 2", got) + } + cancel2() + waitForUpdateTest(t, secondStopped, "second webhook to stop") +} From 199094606778193c56de451432fbb5dc87b508ae Mon Sep 17 00:00:00 2001 From: InkCrow Date: Wed, 18 Nov 2026 18:58:30 +0800 Subject: [PATCH 2/3] fix(webhook): reject updates admitted during shutdown A request waiting for queue space could be acknowledged after StartWebhook's ctx was canceled: dropping a queued update freed space, and select could pick the send over the stop case. Admission now checks the run and sends under updatesMx with a reserved slot, and dropped updates do not free slots. --- bot.go | 1 - options.go | 3 +- wait_updates.go | 44 +++++++++++++++--- webhook_handler.go | 67 ++++++++++++++++++---------- webhook_handler_test.go | 98 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 182 insertions(+), 31 deletions(-) diff --git a/bot.go b/bot.go index cf9125a1..f0ad3819 100644 --- a/bot.go +++ b/bot.go @@ -147,7 +147,6 @@ func (b *Bot) StartWebhook(ctx context.Context) { b.updatesMx.Lock() run.webhookCtx = nil b.updatesMx.Unlock() - run.senders.Wait() close(run.queue) workers.Wait() diff --git a/options.go b/options.go index 15c05a30..feda3390 100644 --- a/options.go +++ b/options.go @@ -102,7 +102,8 @@ func WithAllowedUpdates(params AllowedUpdates) Option { } } -// WithUpdatesChannelCap allows setting custom capacity for the Updates channel +// WithUpdatesChannelCap allows setting custom capacity for the Updates channel. +// StartWebhook uses a capacity of at least 1. func WithUpdatesChannelCap(cap int) Option { return func(b *Bot) { b.updatesChanCap = cap diff --git a/wait_updates.go b/wait_updates.go index ae5135f2..9532ea7a 100644 --- a/wait_updates.go +++ b/wait_updates.go @@ -22,9 +22,17 @@ type updatesRun struct { // It stays first so 32-bit platforms align it for atomic access. dropped int64 - queue chan queuedUpdate - webhookCtx context.Context - senders sync.WaitGroup + queue chan queuedUpdate + isWebhook bool + + // The webhook admission fields are guarded by Bot.updatesMx. webhookCtx is + // nil once StartWebhook stops accepting updates. webhookQueued counts + // accepted updates that workers have not yet taken for dispatch. queueSpace, + // when set, is closed and cleared when a worker frees space. + webhookCtx context.Context + webhookQueued int + queueSpace chan struct{} + // done is closed when the run ends, so a later Start can proceed. done chan struct{} } @@ -45,7 +53,12 @@ func (b *Bot) beginUpdates(ctx context.Context, webhook bool) *updatesRun { b.updatesMx.Lock() previous := b.updatesRun if previous == nil { - run := &updatesRun{queue: make(chan queuedUpdate, b.updatesChanCap), done: make(chan struct{})} + queueCap := b.updatesChanCap + if webhook && queueCap < 1 { + // Webhook admission sends under updatesMx and needs buffer space. + queueCap = 1 + } + run := &updatesRun{queue: make(chan queuedUpdate, queueCap), isWebhook: webhook, done: make(chan struct{})} if webhook { run.webhookCtx = ctx } @@ -89,7 +102,7 @@ func (b *Bot) waitUpdates(ctx context.Context, run *updatesRun) { var handlers sync.WaitGroup defer handlers.Wait() for item := range run.queue { - if ctx.Err() != nil { + if !b.takeQueued(ctx, run) { // Keep draining so StartWebhook can report accepted updates that were never dispatched. atomic.AddInt64(&run.dropped, 1) continue @@ -102,3 +115,24 @@ func (b *Bot) waitUpdates(ctx context.Context, run *updatesRun) { b.dispatchUpdate(ctx, item.update, handlers.Done) } } + +// takeQueued reports whether a received update should be dispatched. A webhook +// update releases its slot only when it is dispatched, so shutdown does not wake +// waiting WebhookHandler requests just to reject them. +func (b *Bot) takeQueued(ctx context.Context, run *updatesRun) bool { + if !run.isWebhook { + return ctx.Err() == nil + } + + b.updatesMx.Lock() + defer b.updatesMx.Unlock() + if ctx.Err() != nil { + return false + } + run.webhookQueued-- + if run.queueSpace != nil { + close(run.queueSpace) + run.queueSpace = nil + } + return true +} diff --git a/webhook_handler.go b/webhook_handler.go index 407ecb30..2d25222f 100644 --- a/webhook_handler.go +++ b/webhook_handler.go @@ -44,32 +44,51 @@ func (b *Bot) WebhookHandler() http.HandlerFunc { } } -// queueWebhookUpdate reports whether the update was accepted. Registering as a -// sender under updatesMx lets StartWebhook wait for in-flight sends before it -// closes the queue. +// queueWebhookUpdate reports whether the update was accepted. It checks +// webhookCtx and sends under updatesMx, which StartWebhook also holds to stop +// admission, and a request woken while waiting for space checks again. So an +// update is never accepted after StartWebhook's ctx is canceled. func (b *Bot) queueWebhookUpdate(ctx context.Context, update *models.Update) bool { - b.updatesMx.Lock() - run := b.updatesRun - if run == nil { - b.updatesMx.Unlock() - b.error("webhook update rejected: StartWebhook is not running") - return false - } - if run.webhookCtx == nil || run.webhookCtx.Err() != nil || ctx.Err() != nil { + var waitedRun *updatesRun + for { + b.updatesMx.Lock() + run := b.updatesRun + if waitedRun != nil && run != waitedRun { + // The run this request waited on has ended; that is a shutdown, not a misconfiguration. + b.updatesMx.Unlock() + return false + } + if run == nil { + b.updatesMx.Unlock() + b.error("webhook update rejected: StartWebhook is not running") + return false + } + if run.webhookCtx == nil || run.webhookCtx.Err() != nil || ctx.Err() != nil { + b.updatesMx.Unlock() + return false + } + if run.webhookQueued < cap(run.queue) { + // The reservation guarantees buffer space, so the send does not block + // and StartWebhook can close the queue once it stops admission. + run.webhookQueued++ + run.queue <- queuedUpdate{update: update} + b.updatesMx.Unlock() + return true + } + if run.queueSpace == nil { + run.queueSpace = make(chan struct{}) + } + space := run.queueSpace + stopping := run.webhookCtx.Done() + waitedRun = run b.updatesMx.Unlock() - return false - } - stopping := run.webhookCtx.Done() - run.senders.Add(1) - b.updatesMx.Unlock() - defer run.senders.Done() - select { - case <-ctx.Done(): - return false - case <-stopping: - return false - case run.queue <- queuedUpdate{update: update}: - return true + select { + case <-ctx.Done(): + return false + case <-stopping: + return false + case <-space: + } } } diff --git a/webhook_handler_test.go b/webhook_handler_test.go index c1398925..eea4e696 100644 --- a/webhook_handler_test.go +++ b/webhook_handler_test.go @@ -299,6 +299,104 @@ func TestWebhookHandler_StopsDispatchingOnShutdown(t *testing.T) { } } +// errBeforeDoneContext reports cancellation through Err before it closes Done. +// It breaks the Context contract on purpose: with a real ctx, a request waiting +// for queue space can find both Done and the freed space ready and pick either. +// Holding Done open pins the case where it does not observe the cancellation. +type errBeforeDoneContext struct { + context.Context + done chan struct{} + mx sync.Mutex + canceled bool + errObserved chan struct{} +} + +func newErrBeforeDoneContext() *errBeforeDoneContext { + return &errBeforeDoneContext{Context: context.Background(), done: make(chan struct{}), errObserved: make(chan struct{})} +} + +func (ctx *errBeforeDoneContext) Done() <-chan struct{} { return ctx.done } + +func (ctx *errBeforeDoneContext) Err() error { + ctx.mx.Lock() + defer ctx.mx.Unlock() + if !ctx.canceled { + return nil + } + select { + case <-ctx.errObserved: + default: + close(ctx.errObserved) + } + return context.Canceled +} + +func (ctx *errBeforeDoneContext) cancelErr() { + ctx.mx.Lock() + ctx.canceled = true + ctx.mx.Unlock() +} + +func TestWebhookHandler_ShutdownDrainDoesNotAdmitWaitingUpdate(t *testing.T) { + ctx := newErrBeforeDoneContext() + firstStarted := make(chan struct{}) + release := make(chan struct{}) + delivered := make(chan int64, 3) + reported := make(chan error, 3) + b, err := New("xxx", WithSkipGetMe(), WithWorkers(1), WithUpdatesChannelCap(1), WithNotAsyncHandlers(), + WithErrorsHandler(func(err error) { reported <- err }), + WithDefaultHandler(func(_ context.Context, _ *Bot, update *models.Update) { + if update.ID == 1 { + close(firstStarted) + <-release + } + delivered <- update.ID + })) + if err != nil { + t.Fatal(err) + } + request := func(body string, ctx context.Context) int { + w := httptest.NewRecorder() + b.WebhookHandler()(w, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)).WithContext(ctx)) + return w.Code + } + + stopped := startWebhookForTest(t, b, ctx) + if got := request(`{"update_id":1}`, context.Background()); got != http.StatusOK { + t.Fatalf("status for first update = %d, want 200", got) + } + waitForUpdateTest(t, firstStarted, "first handler to start") + if got := request(`{"update_id":2}`, context.Background()); got != http.StatusOK { + t.Fatalf("status for queued update = %d, want 200", got) + } + blocked := &observedDoneContext{Context: context.Background(), observed: make(chan struct{})} + blockedStatus := make(chan int, 1) + go func() { + blockedStatus <- request(`{"update_id":3}`, blocked) + }() + waitForUpdateTest(t, blocked.observed, "request to wait for queue space") + + // The worker drops the queued update after cancellation. That must not make + // room for the waiting request before it observes the shutdown. + ctx.cancelErr() + close(release) + waitForUpdateTest(t, ctx.errObserved, "worker to see the cancellation") + close(ctx.done) + if got := waitForUpdateTest(t, blockedStatus, "blocked request to return"); got != http.StatusServiceUnavailable { + t.Errorf("status for blocked update = %d, want 503", got) + } + waitForUpdateTest(t, stopped, "webhook to stop after cancellation") + if got := waitForUpdateTest(t, reported, "dropped update report"); !strings.Contains(got.Error(), "dropped 1") { + t.Errorf("reported %v, want only the update accepted before shutdown", got) + } + if got := waitForUpdateTest(t, delivered, "first handler to return"); got != 1 { + t.Errorf("delivered update %d, want 1", got) + } + if len(delivered) != 0 || len(reported) != 0 { + t.Errorf("unexpected deliveries %d or reports %d", len(delivered), len(reported)) + } +} + func TestStartWebhook_ReturnsWhenAsyncHandlerWaitsForCancellation(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() From 9d7a554a3498cf4d5d776ecf65cddaa0929a7391 Mon Sep 17 00:00:00 2001 From: InkCrow Date: Thu, 19 Nov 2026 03:49:43 +0800 Subject: [PATCH 3/3] fix(updates): rework shutdown delivery for polling and webhook Polling: a worker claims each update before running any user code, and on cancellation only the updates before the first unclaimed one are confirmed. After a negative-offset request the cursor moves to the first update of the batch. Webhook: WebhookHandler returns 200 once a worker takes the update through an unbuffered handoff, 503 if StartWebhook is not running or the run stops or the request is canceled first, and 400 for an unreadable body. Each run has its own context and queue. Start and StartWebhook wait for running handlers and for a previous run on the same bot. --- README.md | 20 +- bot.go | 79 +++----- bot_test.go | 7 + get_updates.go | 91 ++++++++-- get_updates_test.go | 339 ++++++++++++++++++++++++++++++++-- options.go | 11 +- process_update.go | 17 -- wait_updates.go | 182 ++++++++++--------- webhook_handler.go | 80 ++++---- webhook_handler_test.go | 393 ++++++++++++++++++++++++++-------------- 10 files changed, 833 insertions(+), 386 deletions(-) diff --git a/README.md b/README.md index 97f1a8ad..42e34e19 100644 --- a/README.md +++ b/README.md @@ -90,14 +90,18 @@ func handler(ctx context.Context, b *bot.Bot, update *models.Update) { If you want to use webhooks, instead of using `bot.Start`, you should use the `bot.StartWebhook` method to start the bot. Also, you should use `bot.WebhookHandler()` method as HTTP handler for your server. -`WebhookHandler` returns HTTP 503 until `StartWebhook` is accepting updates and -after shutdown begins, so Telegram retries those updates later. Cancel the -context passed to `StartWebhook` and wait for it to return: handlers receive -that context, no further updates are dispatched, and `StartWebhook` returns -once running handlers return. Handlers should return when the context is -canceled, otherwise `StartWebhook` does not return. Accepted updates still -queued at that point are dropped, since Telegram already received 200 for them, -and their count is reported to the errors handler. +For a valid update, `WebhookHandler` returns HTTP 200 once a worker takes the +update, and the worker then runs its matchers, middlewares and handler. With +`bot.WithNotAsyncHandlers`, a request therefore waits for a free worker. If +`StartWebhook` is not running, or the run stops or the request is canceled +before a worker takes the update, it returns HTTP 503 so Telegram can retry, +and the update is not handled. An unreadable request body gets HTTP 400 for +the same reason. + +Cancel the context passed to `StartWebhook` to shut down. Handlers receive a +context derived from it that is canceled when the run stops. `StartWebhook` +waits for running handlers to return. Cancel it before shutting down the HTTP +server, so that requests still waiting for a worker get 503 right away. ```go func main() { diff --git a/bot.go b/bot.go index f0ad3819..6a792e7d 100644 --- a/bot.go +++ b/bot.go @@ -8,7 +8,6 @@ import ( "strconv" "strings" "sync" - "sync/atomic" "time" "github.com/go-telegram/bot/models" @@ -90,6 +89,9 @@ func New(token string, options ...Option) (*Bot, error) { for _, o := range options { o(b) } + if b.updatesChanCap < 0 { + return nil, fmt.Errorf("updates channel capacity must be non-negative") + } ctx, cancel := context.WithTimeout(context.Background(), b.checkInitTimeout) defer cancel() @@ -126,62 +128,35 @@ func (b *Bot) Token() string { } // StartWebhook processes updates from WebhookHandler until ctx is canceled. -// Handlers receive ctx. On cancellation, WebhookHandler rejects new updates -// with 503 so Telegram retries them, workers stop dispatching, and -// StartWebhook returns once running handlers return. Accepted updates that -// were still queued are dropped and reported to the errors handler. Handlers -// should return when ctx is canceled: StartWebhook does not return until they -// do. If another Start or StartWebhook is running on the same Bot, it waits for -// that run to end first. Calling it from a handler of the running Bot therefore +// WebhookHandler answers a valid update with HTTP 200 once a worker takes it, +// and with 503 if the run stops first. Handlers receive a context derived from +// ctx and canceled when the run stops. StartWebhook waits for running handlers +// to return. If every worker exits early, such as through runtime.Goexit in a +// matcher or in a handler run with WithNotAsyncHandlers, the run stops. If +// another Start or StartWebhook is running on the same Bot, it waits for that +// run to end first. Calling it from a handler of the running Bot therefore // blocks until the ctx passed to that call is canceled. func (b *Bot) StartWebhook(ctx context.Context) { - run := b.beginUpdates(ctx, true) - if run == nil { - return - } - defer b.endUpdates() - - workers := b.startUpdateWorkers(ctx, run) - <-ctx.Done() - - b.updatesMx.Lock() - run.webhookCtx = nil - b.updatesMx.Unlock() - close(run.queue) - workers.Wait() - - // A worker that exited early, such as through runtime.Goexit, can leave items behind. - for range run.queue { - atomic.AddInt64(&run.dropped, 1) - } - - if dropped := atomic.LoadInt64(&run.dropped); dropped > 0 { - b.error("webhook stopped before dispatching accepted updates, dropped %d", dropped) - } + b.start(ctx, true) } -// Start receives and processes updates by polling until ctx is canceled. -// A batch is confirmed once all its updates have been dispatched to handlers, -// so polling continues while asynchronous handlers run. With -// WithNotAsyncHandlers, a batch is dispatched only as fast as its handlers -// run. On cancellation, Start waits for dispatched handlers before returning. -// If cancellation comes before every update of a batch is dispatched, the -// whole batch, including updates already handled, may be delivered again when -// polling resumes. Handlers should return when ctx is canceled: Start does not -// return until they do. If another Start or StartWebhook is running on the same -// Bot, it waits for that run to end first. Calling it from a handler of the -// running Bot therefore blocks until the ctx passed to that call is canceled. +// Start receives and processes updates by polling until ctx is canceled. A +// batch is confirmed once all its updates have been dispatched to handlers, so +// polling continues while asynchronous handlers run. With WithNotAsyncHandlers, +// a batch is dispatched only as fast as its handlers run. On cancellation, +// Start waits for dispatched handlers before returning. When polling resumes +// after cancellation, it starts from the first update of the batch that was not +// dispatched, so updates handled after it may be delivered again. Telegram +// learns the new offset only from the next poll, so after a process restart it +// may deliver the last batch again: delivery is at least once. Handlers receive +// a context derived from ctx and canceled when the run stops. They should +// return when it is canceled. If every worker exits early, such as through +// runtime.Goexit in a matcher or in a handler run with WithNotAsyncHandlers, +// the run stops. If another Start or StartWebhook is running on the same Bot, +// it waits for that run to end first. Calling it from a handler of the running +// Bot therefore blocks until the ctx passed to that call is canceled. func (b *Bot) Start(ctx context.Context) { - run := b.beginUpdates(ctx, false) - if run == nil { - return - } - defer b.endUpdates() - - workers := b.startUpdateWorkers(ctx, run) - b.getUpdates(ctx, run.queue) - close(run.queue) - workers.Wait() + b.start(ctx, false) } func defaultErrorsHandler(err error) { diff --git a/bot_test.go b/bot_test.go index 7fdc2be9..bfe9899c 100644 --- a/bot_test.go +++ b/bot_test.go @@ -158,6 +158,13 @@ func TestNew_emptyToken(t *testing.T) { } } +func TestNewRejectsNegativeUpdatesChannelCap(t *testing.T) { + b, err := New("xxx", WithSkipGetMe(), WithUpdatesChannelCap(-1)) + if b != nil || err == nil { + t.Fatalf("New returned (%v, %v), want a configuration error", b, err) + } +} + func TestNew(t *testing.T) { s := newServerMock("xxx") defer s.Close() diff --git a/get_updates.go b/get_updates.go index 2c840c13..0cf9ea5d 100644 --- a/get_updates.go +++ b/get_updates.go @@ -76,9 +76,7 @@ func (b *Bot) getUpdates(ctx context.Context, queue chan<- queuedUpdate) { // offsetStuck is set when the last update of the batch left the offset where it // was, so the very same batch comes back on the next request. offsetStuck := false - lastID := atomic.LoadInt64(&b.lastUpdateID) - dispatched := make(chan struct{}, len(updates)) - pending := 0 + batch := make([]batchUpdate, 0, len(updates)) for _, raw := range updates { upd, errDecode := decodeUpdate(raw) @@ -92,34 +90,32 @@ func (b *Bot) getUpdates(ctx context.Context, queue chan<- queuedUpdate) { } offsetStuck = false - lastID = upd.ID + if params.Offset < 0 && len(batch) == 0 { + // Telegram has dropped the updates before this batch. Resume from + // it rather than from the negative offset, which would drop any + // update of the batch that was not dispatched. + atomic.StoreInt64(&b.lastUpdateID, upd.ID-1) + } if errDecode != nil { b.error("error decode update %d, skipped, %s, %w", upd.ID, raw, errDecode) + batch = append(batch, batchUpdate{id: upd.ID}) continue } + claim := &pollClaim{dispatched: make(chan struct{})} select { case <-ctx.Done(): + b.confirmDispatched(ctx, batch) return - case queue <- queuedUpdate{update: upd, dispatched: dispatched}: - pending++ + case queue <- queuedUpdate{update: upd, claim: claim}: + batch = append(batch, batchUpdate{id: upd.ID, claim: claim}) } } - // The next request acknowledges the whole batch, so keep the previous - // offset if cancellation comes before every update is dispatched. - for i := 0; i < pending; i++ { - select { - case <-ctx.Done(): - return - case <-dispatched: - } - } - if ctx.Err() != nil { + if !b.confirmDispatched(ctx, batch) { return } - atomic.StoreInt64(&b.lastUpdateID, lastID) if offsetStuck { // Back off as on a failed request instead of re-requesting the same @@ -161,3 +157,64 @@ func incErrTimeout(timeout time.Duration) time.Duration { } return timeout } + +// batchUpdate is an update of a polled batch. claim is nil for an update that +// was skipped and needs no dispatch. +type batchUpdate struct { + id int64 + claim *pollClaim +} + +const ( + claimPending int32 = iota + claimTaken + claimAbandoned +) + +// pollClaim settles whether a polled update reaches user code. A worker takes +// it before running any, and the poller abandons it on cancellation unless a +// worker took it first, so both sides agree on what was dispatched. +type pollClaim struct { + state int32 + dispatched chan struct{} +} + +func (c *pollClaim) take() bool { + if !atomic.CompareAndSwapInt32(&c.state, claimPending, claimTaken) { + return false + } + close(c.dispatched) + return true +} + +func (c *pollClaim) abandon() bool { + return atomic.CompareAndSwapInt32(&c.state, claimPending, claimAbandoned) +} + +// confirmDispatched confirms the batch once all of it is dispatched and +// reports whether it was. If ctx is canceled first, it confirms only the +// updates before the first one not yet dispatched, so polling resumes there. +func (b *Bot) confirmDispatched(ctx context.Context, batch []batchUpdate) bool { + settled := 0 + for settled < len(batch) && batch[settled].wait(ctx) { + settled++ + } + if settled > 0 { + atomic.StoreInt64(&b.lastUpdateID, batch[settled-1].id) + } + return settled == len(batch) +} + +// wait reports whether the update was dispatched. On cancellation it abandons +// the update unless a worker has already taken it. +func (u batchUpdate) wait(ctx context.Context) bool { + if u.claim == nil { + return true + } + select { + case <-u.claim.dispatched: + return true + case <-ctx.Done(): + return !u.claim.abandon() + } +} diff --git a/get_updates_test.go b/get_updates_test.go index bca62326..3b165719 100644 --- a/get_updates_test.go +++ b/get_updates_test.go @@ -3,10 +3,14 @@ package bot import ( "bytes" "context" + "fmt" "io" "net/http" "reflect" + "runtime" + "strconv" "strings" + "sync" "sync/atomic" "testing" "time" @@ -18,8 +22,11 @@ type getUpdatesClientFunc func(*http.Request) (*http.Response, error) func (f getUpdatesClientFunc) Do(req *http.Request) (*http.Response, error) { // keep the body readable for req.FormValue - body, _ := io.ReadAll(req.Body) + body, err := io.ReadAll(req.Body) _ = req.Body.Close() + if err != nil { + return nil, err + } req.Body = io.NopCloser(bytes.NewReader(body)) return f(req) } @@ -34,7 +41,7 @@ func runGetUpdates(ctx context.Context, b *Bot) []*models.Update { defer close(done) for item := range queue { delivered = append(delivered, item.update) - item.dispatched <- struct{}{} + item.claim.take() } }() b.getUpdates(ctx, queue) @@ -301,15 +308,14 @@ func TestBot_StartPollsWhileHandlerRuns(t *testing.T) { } } -// A batch canceled before every update is dispatched stays unconfirmed, so the -// whole batch, including handled updates, comes back. -func TestBot_StartReplaysBatchCanceledBeforeDispatch(t *testing.T) { +// Cancellation confirms the updates before the first undispatched one, so +// polling resumes there without replaying the handled update. +func TestBot_StartResumesFromFirstUndispatchedUpdate(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() resumeCtx, cancelResume := context.WithCancel(context.Background()) defer cancelResume() - batch := `{"ok":true,"result":[{"update_id":40},{"update_id":42}]}` firstStarted := make(chan struct{}) offsets := make(chan string, 4) var handled []int64 @@ -327,7 +333,10 @@ func TestBot_StartReplaysBatchCanceledBeforeDispatch(t *testing.T) { calls++ offsets <- req.FormValue("offset") if calls == 1 { - return getUpdatesJSONResponse(batch), nil + if req.FormValue("offset") == "41" { + return getUpdatesJSONResponse(`{"ok":true,"result":[{"update_id":42}]}`), nil + } + return getUpdatesJSONResponse(`{"ok":true,"result":[{"update_id":40},{"update_id":42}]}`), nil } <-req.Context().Done() return nil, req.Context().Err() @@ -356,19 +365,56 @@ func TestBot_StartReplaysBatchCanceledBeforeDispatch(t *testing.T) { defer close(resumed) b.Start(resumeCtx) }() - if got := waitForUpdateTest(t, offsets, "resumed poll"); got != "1" { - t.Errorf("resumed poll offset = %q, want 1", got) + if got := waitForUpdateTest(t, offsets, "resumed poll"); got != "41" { + t.Errorf("resumed poll offset = %q, want 41", got) } - if got := waitForUpdateTest(t, offsets, "poll after the replayed batch"); got != "43" { - t.Errorf("offset after the replayed batch = %q, want 43", got) + if got := waitForUpdateTest(t, offsets, "poll after the resumed batch"); got != "43" { + t.Errorf("offset after the resumed batch = %q, want 43", got) } cancelResume() waitForUpdateTest(t, resumed, "resumed polling to stop") - if want := []int64{40, 40, 42}; !reflect.DeepEqual(handled, want) { + if want := []int64{40, 42}; !reflect.DeepEqual(handled, want) { t.Errorf("handled updates = %v, want %v", handled, want) } } +func TestBot_StartKeepsOffsetWhenLastDispatchedHandlerCancels(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + offsets := make(chan string, 2) + var calls int + b, err := New("xxx", WithSkipGetMe(), WithNotAsyncHandlers(), + WithDefaultHandler(func(context.Context, *Bot, *models.Update) { + cancel() + }), + WithErrorsHandler(func(error) { + // The malformed record keeps the poller from reading the dispatch + // signal until after the valid update's handler cancels the run. + <-ctx.Done() + }), + WithHTTPClient(time.Second, getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) { + offsets <- req.FormValue("offset") + calls++ + if calls == 1 { + return getUpdatesJSONResponse(`{"ok":true,"result":[{"update_id":42},{"update_id":"invalid"}]}`), nil + } + return nil, context.Canceled + }))) + if err != nil { + t.Fatal(err) + } + + b.Start(ctx) + if got := waitForUpdateTest(t, offsets, "initial poll"); got != "1" { + t.Errorf("initial offset = %q, want 1", got) + } + + b.Start(context.Background()) + if got := waitForUpdateTest(t, offsets, "poll after restart"); got != "43" { + t.Errorf("offset after restart = %q, want 43", got) + } +} + func TestBot_StartWaitsForDispatchedHandlers(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -410,6 +456,197 @@ func TestBot_StartWaitsForDispatchedHandlers(t *testing.T) { waitForUpdateTest(t, stopped, "Start to return after the handler") } +// An update whose preparation exits counts as dispatched, so polling goes on +// with the remaining worker instead of replaying it. +func TestBot_StartConfirmsUpdateWhosePreparationExits(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + offsets := make(chan string, 4) + var calls int32 + b, err := New("xxx", WithSkipGetMe(), WithWorkers(2), WithErrorsHandler(func(error) {}), + WithDefaultHandler(func(context.Context, *Bot, *models.Update) {}), + WithHTTPClient(time.Second, getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) { + offsets <- req.FormValue("offset") + if atomic.AddInt32(&calls, 1) == 1 { + return getUpdatesJSONResponse(`{"ok":true,"result":[{"update_id":7},{"update_id":8}]}`), nil + } + <-req.Context().Done() + return nil, req.Context().Err() + }))) + if err != nil { + t.Fatal(err) + } + b.RegisterHandlerMatchFunc(func(update *models.Update) bool { + if update.ID == 8 { + runtime.Goexit() + } + return false + }, b.defaultHandlerFunc) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + b.Start(ctx) + }() + for _, want := range []string{"1", "9"} { + if got := waitForUpdateTest(t, offsets, "poll"); got != want { + t.Errorf("poll offset = %q, want %q", got, want) + } + } + cancel() + waitForUpdateTest(t, stopped, "polling to stop") +} + +// When the only worker exits during preparation the run stops, and the next +// run resumes after that update instead of replaying it forever. +func TestBot_StartResumesAfterUpdateWhosePreparationExits(t *testing.T) { + b, err := New("xxx", WithSkipGetMe(), WithWorkers(1), WithNotAsyncHandlers(), WithErrorsHandler(func(error) {}), + WithDefaultHandler(func(context.Context, *Bot, *models.Update) {}), + WithHTTPClient(time.Second, getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) { + if req.FormValue("offset") == "1" { + return getUpdatesJSONResponse(`{"ok":true,"result":[{"update_id":7},{"update_id":8},{"update_id":9}]}`), nil + } + <-req.Context().Done() + return nil, req.Context().Err() + }))) + if err != nil { + t.Fatal(err) + } + b.RegisterHandlerMatchFunc(func(update *models.Update) bool { + if update.ID == 8 { + runtime.Goexit() + } + return false + }, b.defaultHandlerFunc) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + b.Start(context.Background()) + }() + waitForUpdateTest(t, stopped, "polling to stop after its only worker exits") + if got := atomic.LoadInt64(&b.lastUpdateID); got != 8 { + t.Errorf("last update ID = %d, want 8", got) + } +} + +// A negative offset makes Telegram drop older updates. Polling must resume +// from the batch it got, so an update not dispatched before shutdown is +// delivered after a restart. +func TestBot_StartWithNegativeOffsetKeepsUndispatchedUpdate(t *testing.T) { + var mx sync.Mutex + pending := []int64{100, 101} + var handled []int64 + firstStarted := make(chan struct{}) + restarted := false + b, err := New("xxx", WithSkipGetMe(), WithNotAsyncHandlers(), WithInitialOffset(-3), WithErrorsHandler(func(error) {}), + WithDefaultHandler(func(ctx context.Context, _ *Bot, update *models.Update) { + mx.Lock() + handled = append(handled, update.ID) + first := !restarted && update.ID == 100 + mx.Unlock() + if first { + close(firstStarted) + <-ctx.Done() + } + }), + WithHTTPClient(time.Second, getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) { + offset, _ := strconv.ParseInt(req.FormValue("offset"), 10, 64) + mx.Lock() + // Follow the getUpdates offset rules of the Bot API. + if offset < 0 && len(pending) > int(-offset) { + pending = pending[len(pending)-int(-offset):] + } + var result []string + kept := pending[:0] + for _, id := range pending { + if offset <= 0 || id >= offset { + kept = append(kept, id) + result = append(result, fmt.Sprintf(`{"update_id":%d}`, id)) + } + } + pending = kept + mx.Unlock() + if len(result) == 0 { + <-req.Context().Done() + return nil, req.Context().Err() + } + return getUpdatesJSONResponse(`{"ok":true,"result":[` + strings.Join(result, ",") + `]}`), nil + }))) + if err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithCancel(context.Background()) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + b.Start(ctx) + }() + waitForUpdateTest(t, firstStarted, "first handler to start") + cancel() + waitForUpdateTest(t, stopped, "polling to stop") + + mx.Lock() + restarted = true + pending = append(pending, 102, 103) + mx.Unlock() + resumeCtx, cancelResume := context.WithCancel(context.Background()) + defer cancelResume() + resumed := make(chan struct{}) + go func() { + defer close(resumed) + b.Start(resumeCtx) + }() + deadline := time.Now().Add(5 * time.Second) + for { + mx.Lock() + n := len(handled) + mx.Unlock() + if n >= 4 || time.Now().After(deadline) { + break + } + time.Sleep(time.Millisecond) + } + cancelResume() + waitForUpdateTest(t, resumed, "resumed polling to stop") + mx.Lock() + defer mx.Unlock() + if want := []int64{100, 101, 102, 103}; !reflect.DeepEqual(handled, want) { + t.Errorf("handled updates = %v, want %v", handled, want) + } +} + +// A batch fetched with a negative offset moves the cursor to the batch before +// any update is dispatched. +func Test_getUpdates_negativeOffsetResumesFromBatch(t *testing.T) { + requested := make(chan struct{}) + b, err := New("xxx", WithSkipGetMe(), WithInitialOffset(-3), + WithHTTPClient(time.Second, getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) { + if req.FormValue("offset") != "-2" { + <-req.Context().Done() + return nil, req.Context().Err() + } + close(requested) + return getUpdatesJSONResponse(`{"ok":true,"result":[{"update_id":100},{"update_id":101}]}`), nil + }))) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + stopped := make(chan struct{}) + go func() { + defer close(stopped) + // Nobody reads the queue, so no update is dispatched. + b.getUpdates(ctx, make(chan queuedUpdate)) + }() + waitForUpdateTest(t, requested, "poll with the negative offset") + cancel() + waitForUpdateTest(t, stopped, "polling to stop") + if got := atomic.LoadInt64(&b.lastUpdateID); got != 99 { + t.Errorf("last update ID = %d, want 99", got) + } +} + func TestBot_StartWithoutWorkersReportsError(t *testing.T) { reported := make(chan error, 2) b, err := New("xxx", WithSkipGetMe(), WithWorkers(0), @@ -428,3 +665,81 @@ func TestBot_StartWithoutWorkersReportsError(t *testing.T) { t.Errorf("reported %v, want the missing workers error", got) } } + +// Cancellation while a matcher runs must not leave the update unconfirmed: +// its handler still runs, so replaying it would run it twice. +func TestBot_StartConfirmsUpdateCanceledDuringPreparation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + matching := make(chan struct{}) + release := make(chan struct{}) + var handled int32 + b, err := New("xxx", WithSkipGetMe(), WithWorkers(1), WithErrorsHandler(func(error) {}), + WithDefaultHandler(func(context.Context, *Bot, *models.Update) { atomic.AddInt32(&handled, 1) }), + WithHTTPClient(time.Second, getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) { + if req.FormValue("offset") == "1" { + return getUpdatesJSONResponse(`{"ok":true,"result":[{"update_id":7}]}`), nil + } + <-req.Context().Done() + return nil, req.Context().Err() + }))) + if err != nil { + t.Fatal(err) + } + b.RegisterHandlerMatchFunc(func(*models.Update) bool { + close(matching) + <-release + return false + }, b.defaultHandlerFunc) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + b.Start(ctx) + }() + waitForUpdateTest(t, matching, "matcher to run") + cancel() + close(release) + waitForUpdateTest(t, stopped, "polling to stop") + if got := atomic.LoadInt32(&handled); got != 1 { + t.Errorf("handled %d times, want 1", got) + } + if got := atomic.LoadInt64(&b.lastUpdateID); got != 7 { + t.Errorf("last update ID = %d, want 7", got) + } +} + +// Cancellation while the poller waits to queue the next update still confirms +// the updates already dispatched. +func TestBot_StartConfirmsDispatchedUpdatesWhenCanceledWhileQueuing(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + firstStarted := make(chan struct{}) + b, err := New("xxx", WithSkipGetMe(), WithWorkers(1), WithNotAsyncHandlers(), WithUpdatesChannelCap(0), + WithDefaultHandler(func(ctx context.Context, _ *Bot, update *models.Update) { + if update.ID == 1 { + close(firstStarted) + <-ctx.Done() + } + }), + WithHTTPClient(time.Second, getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) { + if req.FormValue("offset") == "1" { + return getUpdatesJSONResponse(`{"ok":true,"result":[{"update_id":1},{"update_id":2}]}`), nil + } + <-req.Context().Done() + return nil, req.Context().Err() + }))) + if err != nil { + t.Fatal(err) + } + stopped := make(chan struct{}) + go func() { + defer close(stopped) + b.Start(ctx) + }() + waitForUpdateTest(t, firstStarted, "first handler to start") + cancel() + waitForUpdateTest(t, stopped, "polling to stop") + if got := atomic.LoadInt64(&b.lastUpdateID); got != 1 { + t.Errorf("last update ID = %d, want 1", got) + } +} diff --git a/options.go b/options.go index feda3390..587f40db 100644 --- a/options.go +++ b/options.go @@ -102,8 +102,11 @@ func WithAllowedUpdates(params AllowedUpdates) Option { } } -// WithUpdatesChannelCap allows setting custom capacity for the Updates channel. -// StartWebhook uses a capacity of at least 1. +// WithUpdatesChannelCap sets the capacity of the queue between the update +// source and the workers. Start fetches the next batch only after the current +// one is dispatched, and a webhook request waits until a worker takes its +// update, so the capacity only bounds how many updates wait for a worker. +// New returns an error for a negative capacity. func WithUpdatesChannelCap(cap int) Option { return func(b *Bot) { b.updatesChanCap = cap @@ -131,7 +134,9 @@ func UseTestEnvironment() Option { } } -// WithNotAsyncHandlers allows to run handlers in the main goroutine +// WithNotAsyncHandlers runs each handler in its worker goroutine. +// A worker then takes the next update only after its handler returns, so a +// WebhookHandler request may wait for a busy worker. func WithNotAsyncHandlers() Option { return func(b *Bot) { b.notAsyncHandlers = true diff --git a/process_update.go b/process_update.go index 1d0157cf..88d56beb 100644 --- a/process_update.go +++ b/process_update.go @@ -31,23 +31,6 @@ func (b *Bot) ProcessUpdate(ctx context.Context, upd *models.Update) { go r(ctx, b, upd) } -// dispatchUpdate runs the handler of a queued update and calls done when it -// returns. -func (b *Bot) dispatchUpdate(ctx context.Context, upd *models.Update, done func()) { - r := applyMiddlewares(b.findHandler(upd), b.middlewares...) - run := func() { - defer done() - r(ctx, b, upd) - } - - if b.notAsyncHandlers { - run() - return - } - - go run() -} - func (b *Bot) findHandler(upd *models.Update) HandlerFunc { b.handlersMx.RLock() defer b.handlersMx.RUnlock() diff --git a/wait_updates.go b/wait_updates.go index 9532ea7a..dae48e3e 100644 --- a/wait_updates.go +++ b/wait_updates.go @@ -3,77 +3,88 @@ package bot import ( "context" "sync" - "sync/atomic" "github.com/go-telegram/bot/models" ) -// queuedUpdate carries an update to a worker. dispatched, when set, receives a -// signal once the worker hands the update to its handler. It must be buffered -// for the whole batch because the worker signals without waiting. type queuedUpdate struct { - update *models.Update - dispatched chan<- struct{} + update *models.Update + // claim is set for polled updates. + claim *pollClaim + // dispatched and requestDone are set for webhook updates. dispatched is an + // unbuffered handoff to the waiting request. + dispatched chan<- struct{} + requestDone <-chan struct{} } type updatesRun struct { - // dropped counts updates the workers discarded after cancellation. Only - // StartWebhook reports it: unconfirmed polled updates are delivered again. - // It stays first so 32-bit platforms align it for atomic access. - dropped int64 - - queue chan queuedUpdate - isWebhook bool - - // The webhook admission fields are guarded by Bot.updatesMx. webhookCtx is - // nil once StartWebhook stops accepting updates. webhookQueued counts - // accepted updates that workers have not yet taken for dispatch. queueSpace, - // when set, is closed and cleared when a worker frees space. - webhookCtx context.Context - webhookQueued int - queueSpace chan struct{} - - // done is closed when the run ends, so a later Start can proceed. - done chan struct{} + ctx context.Context + webhook bool + queue chan queuedUpdate + done chan struct{} } -func (b *Bot) beginUpdates(ctx context.Context, webhook bool) *updatesRun { +func (b *Bot) start(ctx context.Context, webhook bool) { if ctx.Err() != nil { - return nil + return } if b.workers <= 0 { - b.error("cannot start bot without update workers") - return nil + // The errors handler is user code. Run it apart so that a block or a + // runtime.Goexit there cannot hold up or end the caller. + go b.error("cannot start bot without update workers") + return } - for { - if ctx.Err() != nil { - return nil - } + runCtx, cancel := context.WithCancel(ctx) + defer cancel() + run := &updatesRun{ctx: runCtx, webhook: webhook, done: make(chan struct{})} + if !b.beginUpdates(run) { + return + } + defer b.endUpdates() + + var polling, workers, handlers sync.WaitGroup + if !webhook { + polling.Add(1) + go func() { + defer polling.Done() + defer cancel() + b.getUpdates(runCtx, run.queue) + }() + } + workers.Add(b.workers) + for i := 0; i < b.workers; i++ { + go func() { + defer workers.Done() + b.waitUpdates(run, &handlers) + }() + } + workers.Wait() + // The last worker may have exited through a user callback. Wake any + // producer waiting for a handoff before waiting for running handlers. + cancel() + polling.Wait() + handlers.Wait() +} + +func (b *Bot) beginUpdates(run *updatesRun) bool { + for run.ctx.Err() == nil { b.updatesMx.Lock() previous := b.updatesRun if previous == nil { - queueCap := b.updatesChanCap - if webhook && queueCap < 1 { - // Webhook admission sends under updatesMx and needs buffer space. - queueCap = 1 - } - run := &updatesRun{queue: make(chan queuedUpdate, queueCap), isWebhook: webhook, done: make(chan struct{})} - if webhook { - run.webhookCtx = ctx - } + run.queue = make(chan queuedUpdate, b.updatesChanCap) b.updatesRun = run b.updatesMx.Unlock() - return run + return true } b.updatesMx.Unlock() - // The previous run can still be waiting for its handlers. select { case <-previous.done: - case <-ctx.Done(): - return nil + case <-run.ctx.Done(): + return false } } + return false } func (b *Bot) endUpdates() { @@ -84,55 +95,46 @@ func (b *Bot) endUpdates() { close(run.done) } -func (b *Bot) startUpdateWorkers(ctx context.Context, run *updatesRun) *sync.WaitGroup { - workers := &sync.WaitGroup{} - workers.Add(b.workers) - for i := 0; i < b.workers; i++ { - go func() { - defer workers.Done() - b.waitUpdates(ctx, run) - }() - } - return workers -} - -// waitUpdates dispatches queued updates until the queue is closed, then waits -// for the handlers it started. -func (b *Bot) waitUpdates(ctx context.Context, run *updatesRun) { - var handlers sync.WaitGroup - defer handlers.Wait() - for item := range run.queue { - if !b.takeQueued(ctx, run) { - // Keep draining so StartWebhook can report accepted updates that were never dispatched. - atomic.AddInt64(&run.dropped, 1) - continue - } - - if item.dispatched != nil { - item.dispatched <- struct{}{} +func (b *Bot) waitUpdates(run *updatesRun, handlers *sync.WaitGroup) { + for { + select { + case <-run.ctx.Done(): + return + case item := <-run.queue: + handler, ok := b.prepareUpdate(run, item) + if !ok { + continue + } + invoke := func() { + defer handlers.Done() + handler(run.ctx, b, item.update) + } + handlers.Add(1) + if b.notAsyncHandlers { + invoke() + } else { + go invoke() + } } - handlers.Add(1) - b.dispatchUpdate(ctx, item.update, handlers.Done) } } -// takeQueued reports whether a received update should be dispatched. A webhook -// update releases its slot only when it is dispatched, so shutdown does not wake -// waiting WebhookHandler requests just to reject them. -func (b *Bot) takeQueued(ctx context.Context, run *updatesRun) bool { - if !run.isWebhook { - return ctx.Err() == nil +func (b *Bot) prepareUpdate(run *updatesRun, item queuedUpdate) (HandlerFunc, bool) { + if run.webhook { + // The request answers 200 once it receives this handoff, so from here + // on the update must reach its handler even if the run stops. + select { + case item.dispatched <- struct{}{}: + case <-run.ctx.Done(): + return nil, false + case <-item.requestDone: + return nil, false + } + } else if run.ctx.Err() != nil || !item.claim.take() { + // Leave it to be polled again: the run is stopping, or the poller has + // already given up on it. + return nil, false } - b.updatesMx.Lock() - defer b.updatesMx.Unlock() - if ctx.Err() != nil { - return false - } - run.webhookQueued-- - if run.queueSpace != nil { - close(run.queueSpace) - run.queueSpace = nil - } - return true + return applyMiddlewares(b.findHandler(item.update), b.middlewares...), true } diff --git a/webhook_handler.go b/webhook_handler.go index 2d25222f..b46a1a4d 100644 --- a/webhook_handler.go +++ b/webhook_handler.go @@ -10,8 +10,11 @@ import ( ) // WebhookHandler returns an HTTP handler for updates processed by StartWebhook. -// It returns 503 when StartWebhook is not accepting updates, so Telegram -// retries them later. An unreadable request body returns 400. +// For a valid update, it returns 200 once a worker takes the update, after +// which the worker runs its matchers, middlewares and handler. It returns 503 +// if StartWebhook is not running, or if no worker takes the update before the +// run stops or the request is canceled, and 400 if the request body cannot be +// read. Such an update is not handled, and Telegram sends it again. func (b *Bot) WebhookHandler() http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { if b.webhookSecretToken != "" && req.Header.Get("X-Telegram-Bot-Api-Secret-Token") != b.webhookSecretToken { @@ -44,51 +47,36 @@ func (b *Bot) WebhookHandler() http.HandlerFunc { } } -// queueWebhookUpdate reports whether the update was accepted. It checks -// webhookCtx and sends under updatesMx, which StartWebhook also holds to stop -// admission, and a request woken while waiting for space checks again. So an -// update is never accepted after StartWebhook's ctx is canceled. func (b *Bot) queueWebhookUpdate(ctx context.Context, update *models.Update) bool { - var waitedRun *updatesRun - for { - b.updatesMx.Lock() - run := b.updatesRun - if waitedRun != nil && run != waitedRun { - // The run this request waited on has ended; that is a shutdown, not a misconfiguration. - b.updatesMx.Unlock() - return false - } - if run == nil { - b.updatesMx.Unlock() - b.error("webhook update rejected: StartWebhook is not running") - return false - } - if run.webhookCtx == nil || run.webhookCtx.Err() != nil || ctx.Err() != nil { - b.updatesMx.Unlock() - return false - } - if run.webhookQueued < cap(run.queue) { - // The reservation guarantees buffer space, so the send does not block - // and StartWebhook can close the queue once it stops admission. - run.webhookQueued++ - run.queue <- queuedUpdate{update: update} - b.updatesMx.Unlock() - return true - } - if run.queueSpace == nil { - run.queueSpace = make(chan struct{}) - } - space := run.queueSpace - stopping := run.webhookCtx.Done() - waitedRun = run - b.updatesMx.Unlock() + b.updatesMx.Lock() + run := b.updatesRun + b.updatesMx.Unlock() + if run == nil { + b.error("webhook update rejected: StartWebhook is not running") + return false + } + if !run.webhook || run.ctx.Err() != nil || ctx.Err() != nil { + return false + } - select { - case <-ctx.Done(): - return false - case <-stopping: - return false - case <-space: - } + dispatched := make(chan struct{}) + requestDone := ctx.Done() + select { + case run.queue <- queuedUpdate{update: update, dispatched: dispatched, requestDone: requestDone}: + case <-requestDone: + return false + case <-run.ctx.Done(): + return false + } + + // The handoff is unbuffered, so the request and the worker agree on + // whether the worker took the update. + select { + case <-dispatched: + return true + case <-requestDone: + return false + case <-run.ctx.Done(): + return false } } diff --git a/webhook_handler_test.go b/webhook_handler_test.go index eea4e696..01a55ae9 100644 --- a/webhook_handler_test.go +++ b/webhook_handler_test.go @@ -8,6 +8,8 @@ import ( "io" "net/http" "net/http/httptest" + "runtime" + "strconv" "strings" "sync" "testing" @@ -94,37 +96,27 @@ func TestWebhookHandler_Success(t *testing.T) { } func TestWebhookHandler_ReadBodyError(t *testing.T) { + debugHandler := &mockDebugHandler{} errorsHandler := &mockErrorsHandler{} - delivered := make(chan *models.Update, 1) bot := &Bot{ - workers: 1, - defaultHandlerFunc: func(_ context.Context, _ *Bot, update *models.Update) { - delivered <- update + debugHandler: func(format string, args ...any) { + debugHandler.Handle(format, args...) }, errorsHandler: func(err error) { errorsHandler.Handle(err) }, } - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - stopped := startWebhookForTest(t, bot, ctx) req := httptest.NewRequest(http.MethodPost, "/", errReader(errors.New("read error"))) w := httptest.NewRecorder() handler := bot.WebhookHandler() handler(w, req) - cancel() - waitForUpdateTest(t, stopped, "webhook to stop") - if w.Code != http.StatusBadRequest { - t.Errorf("webhook status %d, want %d", w.Code, http.StatusBadRequest) - } - if len(delivered) != 0 { - t.Error("webhook delivered an update after the body read failed") + if got := w.Result().StatusCode; got != http.StatusBadRequest { + t.Errorf("status for unreadable request body = %d, want %d", got, http.StatusBadRequest) } - if len(errorsHandler.errors) == 0 { t.Fatal("Expected an error, but none occurred") } @@ -206,6 +198,11 @@ func TestWebhookHandler_StopsDispatchingOnShutdown(t *testing.T) { ctx, cancel := context.WithCancel(parent) defer cancel() firstStarted := make(chan struct{}) + release := make(chan struct{}) + var releaseOnce sync.Once + releaseHandler := func() { releaseOnce.Do(func() { close(release) }) } + // A failed check must not leave the handler blocked. + defer releaseHandler() delivered := make(chan int64, 6) reported := make(chan error, 6) b, err := New("xxx", WithSkipGetMe(), WithUpdatesChannelCap(1), WithNotAsyncHandlers(), @@ -216,8 +213,8 @@ func TestWebhookHandler_StopsDispatchingOnShutdown(t *testing.T) { } if update.ID == 1 { close(firstStarted) - // A handler waiting for cancellation must not block shutdown. - <-ctx.Done() + // Pending requests must be released even while this handler is busy. + <-release } delivered <- update.ID })) @@ -242,34 +239,39 @@ func TestWebhookHandler_StopsDispatchingOnShutdown(t *testing.T) { t.Fatalf("status for first update = %d, want 200", got) } waitForUpdateTest(t, firstStarted, "first webhook handler to start") - if got := request(`{"update_id":2}`, context.Background()); got != http.StatusOK { - t.Fatalf("status for queued update = %d, want 200", got) + queued := make(chan int, 1) + go func() { queued <- request(`{"update_id":2}`, context.Background()) }() + b.updatesMx.Lock() + queue := b.updatesRun.queue + b.updatesMx.Unlock() + deadline := time.Now().Add(5 * time.Second) + for len(queue) == 0 { + if time.Now().After(deadline) { + t.Fatal("second update did not enter the queue") + } + time.Sleep(time.Millisecond) } // The worker is busy and its only queue slot is occupied. - blockedCtx, cancelBlocked := context.WithCancel(context.Background()) - defer cancelBlocked() - blocked := &observedDoneContext{Context: blockedCtx, observed: make(chan struct{})} + blocked := &observedDoneContext{Context: context.Background(), observed: make(chan struct{})} blockedStatus := make(chan int, 1) - go func() { - blockedStatus <- request(`{"update_id":3}`, blocked) - }() + go func() { blockedStatus <- request(`{"update_id":3}`, blocked) }() waitForUpdateTest(t, blocked.observed, "request to wait for queue space") cancel() + if got := waitForUpdateTest(t, queued, "queued request to return"); got != http.StatusServiceUnavailable { + t.Errorf("status for queued update = %d, want 503", got) + } if got := waitForUpdateTest(t, blockedStatus, "blocked request to return"); got != http.StatusServiceUnavailable { t.Errorf("status for blocked update = %d, want 503", got) } if got := request(`{"update_id":4}`, context.Background()); got != http.StatusServiceUnavailable { t.Errorf("status during shutdown = %d, want 503", got) } + releaseHandler() waitForUpdateTest(t, stopped, "webhook to stop after cancellation") if got := waitForUpdateTest(t, delivered, "first handler to return"); got != 1 { t.Errorf("delivered update %d, want 1", got) } - if got := waitForUpdateTest(t, reported, "dropped update report"); !strings.Contains(got.Error(), "dropped 1") { - t.Errorf("reported %v, want the dropped queued update", got) - } - if got := request(`{"update_id":5}`, context.Background()); got != http.StatusServiceUnavailable { t.Errorf("status after shutdown = %d, want 503", got) } @@ -290,110 +292,8 @@ func TestWebhookHandler_StopsDispatchingOnShutdown(t *testing.T) { if len(delivered) != 0 { t.Error("delivered a dropped or rejected webhook update") } - // A request that arrives after shutdown finished reports that no webhook is - // running, which the request during shutdown may or may not hit. - for len(reported) != 0 { - if got := <-reported; !strings.Contains(got.Error(), "StartWebhook is not running") { - t.Errorf("unexpected error report: %v", got) - } - } -} - -// errBeforeDoneContext reports cancellation through Err before it closes Done. -// It breaks the Context contract on purpose: with a real ctx, a request waiting -// for queue space can find both Done and the freed space ready and pick either. -// Holding Done open pins the case where it does not observe the cancellation. -type errBeforeDoneContext struct { - context.Context - done chan struct{} - mx sync.Mutex - canceled bool - errObserved chan struct{} -} - -func newErrBeforeDoneContext() *errBeforeDoneContext { - return &errBeforeDoneContext{Context: context.Background(), done: make(chan struct{}), errObserved: make(chan struct{})} -} - -func (ctx *errBeforeDoneContext) Done() <-chan struct{} { return ctx.done } - -func (ctx *errBeforeDoneContext) Err() error { - ctx.mx.Lock() - defer ctx.mx.Unlock() - if !ctx.canceled { - return nil - } - select { - case <-ctx.errObserved: - default: - close(ctx.errObserved) - } - return context.Canceled -} - -func (ctx *errBeforeDoneContext) cancelErr() { - ctx.mx.Lock() - ctx.canceled = true - ctx.mx.Unlock() -} - -func TestWebhookHandler_ShutdownDrainDoesNotAdmitWaitingUpdate(t *testing.T) { - ctx := newErrBeforeDoneContext() - firstStarted := make(chan struct{}) - release := make(chan struct{}) - delivered := make(chan int64, 3) - reported := make(chan error, 3) - b, err := New("xxx", WithSkipGetMe(), WithWorkers(1), WithUpdatesChannelCap(1), WithNotAsyncHandlers(), - WithErrorsHandler(func(err error) { reported <- err }), - WithDefaultHandler(func(_ context.Context, _ *Bot, update *models.Update) { - if update.ID == 1 { - close(firstStarted) - <-release - } - delivered <- update.ID - })) - if err != nil { - t.Fatal(err) - } - request := func(body string, ctx context.Context) int { - w := httptest.NewRecorder() - b.WebhookHandler()(w, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)).WithContext(ctx)) - return w.Code - } - - stopped := startWebhookForTest(t, b, ctx) - if got := request(`{"update_id":1}`, context.Background()); got != http.StatusOK { - t.Fatalf("status for first update = %d, want 200", got) - } - waitForUpdateTest(t, firstStarted, "first handler to start") - if got := request(`{"update_id":2}`, context.Background()); got != http.StatusOK { - t.Fatalf("status for queued update = %d, want 200", got) - } - blocked := &observedDoneContext{Context: context.Background(), observed: make(chan struct{})} - blockedStatus := make(chan int, 1) - go func() { - blockedStatus <- request(`{"update_id":3}`, blocked) - }() - waitForUpdateTest(t, blocked.observed, "request to wait for queue space") - - // The worker drops the queued update after cancellation. That must not make - // room for the waiting request before it observes the shutdown. - ctx.cancelErr() - close(release) - waitForUpdateTest(t, ctx.errObserved, "worker to see the cancellation") - close(ctx.done) - if got := waitForUpdateTest(t, blockedStatus, "blocked request to return"); got != http.StatusServiceUnavailable { - t.Errorf("status for blocked update = %d, want 503", got) - } - waitForUpdateTest(t, stopped, "webhook to stop after cancellation") - if got := waitForUpdateTest(t, reported, "dropped update report"); !strings.Contains(got.Error(), "dropped 1") { - t.Errorf("reported %v, want only the update accepted before shutdown", got) - } - if got := waitForUpdateTest(t, delivered, "first handler to return"); got != 1 { - t.Errorf("delivered update %d, want 1", got) - } - if len(delivered) != 0 || len(reported) != 0 { - t.Errorf("unexpected deliveries %d or reports %d", len(delivered), len(reported)) + if len(reported) != 0 { + t.Errorf("unexpected error report: %v", <-reported) } } @@ -420,6 +320,96 @@ func TestStartWebhook_ReturnsWhenAsyncHandlerWaitsForCancellation(t *testing.T) waitForUpdateTest(t, stopped, "webhook to stop after cancellation") } +// A worker that takes an update has dispatched it, even if its matcher then +// exits, so Telegram does not keep resending an update that kills a worker. +func TestWebhookHandler_AcknowledgesUpdateWhosePreparationExits(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + delivered := make(chan int64, 2) + b, err := New("xxx", WithSkipGetMe(), WithWorkers(2), WithUpdatesChannelCap(0), + WithDefaultHandler(func(_ context.Context, _ *Bot, update *models.Update) { + delivered <- update.ID + })) + if err != nil { + t.Fatal(err) + } + b.RegisterHandlerMatchFunc(func(update *models.Update) bool { + if update.ID != 2 { + runtime.Goexit() + } + return false + }, b.defaultHandlerFunc) + stopped := startWebhookForTest(t, b, ctx) + request := func(body string) int { + w := httptest.NewRecorder() + b.WebhookHandler()(w, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body))) + return w.Code + } + if got := request(`{"update_id":1}`); got != http.StatusOK { + t.Errorf("status for interrupted preparation = %d, want 200", got) + } + if got := request(`{"update_id":2}`); got != http.StatusOK { + t.Errorf("status with surviving worker = %d, want 200", got) + } + if got := waitForUpdateTest(t, delivered, "surviving worker to handle update"); got != 2 { + t.Errorf("delivered update = %d, want 2", got) + } + if got := request(`{"update_id":3}`); got != http.StatusOK { + t.Errorf("status for last worker's interrupted preparation = %d, want 200", got) + } + waitForUpdateTest(t, stopped, "webhook to stop after its last worker exits") +} + +func TestWebhookHandler_CompletesClaimedMiddlewareAfterCancellation(t *testing.T) { + for _, stopRun := range []bool{false, true} { + ctx, stop := context.WithCancel(context.Background()) + requestCtx, cancelRequest := context.WithCancel(context.Background()) + preparing := make(chan struct{}) + releasePreparation := make(chan struct{}) + resource := make(chan struct{}, 1) + b, err := New("xxx", WithSkipGetMe(), WithUpdatesChannelCap(0), + WithMiddlewares(func(next HandlerFunc) HandlerFunc { + resource <- struct{}{} + close(preparing) + <-releasePreparation + return func(ctx context.Context, b *Bot, update *models.Update) { + defer func() { <-resource }() + next(ctx, b, update) + } + }), + WithDefaultHandler(func(context.Context, *Bot, *models.Update) {})) + if err != nil { + stop() + cancelRequest() + t.Fatal(err) + } + stopped := startWebhookForTest(t, b, ctx) + status := make(chan int, 1) + go func() { + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"update_id":1}`)).WithContext(requestCtx) + b.WebhookHandler()(w, req) + status <- w.Code + }() + waitForUpdateTest(t, preparing, "middleware to acquire the resource") + if stopRun { + stop() + } else { + cancelRequest() + } + close(releasePreparation) + if got := waitForUpdateTest(t, status, "claimed request to complete"); got != http.StatusOK { + t.Errorf("stopRun=%t: status = %d, want 200", stopRun, got) + } + stop() + cancelRequest() + waitForUpdateTest(t, stopped, "claimed handler to finish") + if len(resource) != 0 { + t.Errorf("stopRun=%t: middleware resource was not released", stopRun) + } + } +} + func TestWebhookHandler_NoWorkers(t *testing.T) { b, err := New("xxx", WithSkipGetMe(), WithWorkers(0), WithErrorsHandler(func(error) {})) if err != nil { @@ -453,19 +443,26 @@ func (ctx *observedDoneContext) Done() <-chan struct{} { return ctx.Context.Done() } -// startWebhookForTest relies on StartWebhook calling ctx.Done only after it -// registered the run, which holds unless it waits for a previous run. Start -// such a second run in a plain goroutine instead. func startWebhookForTest(t *testing.T, b *Bot, ctx context.Context) <-chan struct{} { t.Helper() - observed := &observedDoneContext{Context: ctx, observed: make(chan struct{})} stopped := make(chan struct{}) go func() { defer close(stopped) - b.StartWebhook(observed) + b.StartWebhook(ctx) }() - waitForUpdateTest(t, observed.observed, "webhook to start") - return stopped + deadline := time.Now().Add(5 * time.Second) + for { + b.updatesMx.Lock() + started := b.updatesRun != nil && b.updatesRun.webhook + b.updatesMx.Unlock() + if started { + return stopped + } + if time.Now().After(deadline) { + t.Fatal("webhook did not start") + } + time.Sleep(time.Millisecond) + } } func containsString(s, substr string) bool { @@ -479,6 +476,10 @@ func TestStartWebhook_RestartWaitsForPreviousRun(t *testing.T) { defer cancel2() started := make(chan struct{}) release := make(chan struct{}) + var releaseOnce sync.Once + releaseHandler := func() { releaseOnce.Do(func() { close(release) }) } + // A failed check must not leave the handler blocked. + defer releaseHandler() delivered := make(chan int64, 4) reported := make(chan error, 8) b, err := New("xxx", WithSkipGetMe(), @@ -526,7 +527,7 @@ func TestStartWebhook_RestartWaitsForPreviousRun(t *testing.T) { case <-time.After(100 * time.Millisecond): } - close(release) + releaseHandler() waitForUpdateTest(t, firstStopped, "first webhook to stop") deadline := time.Now().Add(5 * time.Second) for request(`{"update_id":2}`) != http.StatusOK { @@ -541,3 +542,113 @@ func TestStartWebhook_RestartWaitsForPreviousRun(t *testing.T) { cancel2() waitForUpdateTest(t, secondStopped, "second webhook to stop") } + +// Requests canceled while their updates wait in the queue get 503, and the +// worker skips those updates instead of handling them. A worker that could +// complete the handoff without its request would handle some of them, so +// many requests make that failure reliable. +func TestWebhookHandler_SkipsUpdatesOfCanceledRequests(t *testing.T) { + const canceledRequests = 20 + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + firstStarted := make(chan struct{}) + release := make(chan struct{}) + var releaseOnce sync.Once + releaseHandler := func() { releaseOnce.Do(func() { close(release) }) } + // A failed check must not leave the handler blocked. + defer releaseHandler() + delivered := make(chan int64, canceledRequests+2) + b, err := New("xxx", WithSkipGetMe(), WithWorkers(1), WithUpdatesChannelCap(canceledRequests), WithNotAsyncHandlers(), + WithDefaultHandler(func(_ context.Context, _ *Bot, update *models.Update) { + if update.ID == 1 { + close(firstStarted) + <-release + } + delivered <- update.ID + })) + if err != nil { + t.Fatal(err) + } + request := func(id int, ctx context.Context) int { + w := httptest.NewRecorder() + body := strings.NewReader(`{"update_id":` + strconv.Itoa(id) + `}`) + b.WebhookHandler()(w, httptest.NewRequest(http.MethodPost, "/", body).WithContext(ctx)) + return w.Code + } + stopped := startWebhookForTest(t, b, ctx) + if got := request(1, context.Background()); got != http.StatusOK { + t.Fatalf("status for first update = %d, want 200", got) + } + waitForUpdateTest(t, firstStarted, "first handler to start") + + requestCtx, cancelRequests := context.WithCancel(context.Background()) + defer cancelRequests() + statuses := make(chan int, canceledRequests) + for id := 2; id < canceledRequests+2; id++ { + go func(id int) { statuses <- request(id, requestCtx) }(id) + } + b.updatesMx.Lock() + queue := b.updatesRun.queue + b.updatesMx.Unlock() + deadline := time.Now().Add(5 * time.Second) + for len(queue) < canceledRequests { + if time.Now().After(deadline) { + t.Fatal("canceled updates did not enter the queue") + } + time.Sleep(time.Millisecond) + } + cancelRequests() + for i := 0; i < canceledRequests; i++ { + if got := waitForUpdateTest(t, statuses, "canceled request"); got != http.StatusServiceUnavailable { + t.Errorf("status for canceled request = %d, want 503", got) + } + } + + releaseHandler() + const lastID = 1000 + if got := request(lastID, context.Background()); got != http.StatusOK { + t.Fatalf("status after the canceled requests = %d, want 200", got) + } + for _, want := range []int64{1, lastID} { + if got := waitForUpdateTest(t, delivered, "handler"); got != want { + t.Errorf("delivered update %d, want %d", got, want) + } + } + cancel() + waitForUpdateTest(t, stopped, "webhook to stop") +} + +// A webhook request that arrives while Start is polling is rejected. +func TestWebhookHandler_RejectsUpdateWhilePolling(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + polling := make(chan struct{}) + var once sync.Once + handled := make(chan struct{}, 1) + b, err := New("xxx", WithSkipGetMe(), + WithDefaultHandler(func(context.Context, *Bot, *models.Update) { handled <- struct{}{} }), + WithHTTPClient(time.Second, getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) { + once.Do(func() { close(polling) }) + <-req.Context().Done() + return nil, req.Context().Err() + }))) + if err != nil { + t.Fatal(err) + } + stopped := make(chan struct{}) + go func() { + defer close(stopped) + b.Start(ctx) + }() + waitForUpdateTest(t, polling, "polling to start") + w := httptest.NewRecorder() + b.WebhookHandler()(w, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"update_id":1}`))) + if w.Code != http.StatusServiceUnavailable { + t.Errorf("webhook status while polling = %d, want 503", w.Code) + } + cancel() + waitForUpdateTest(t, stopped, "polling to stop") + if len(handled) != 0 { + t.Error("handled a webhook update while polling") + } +}