diff --git a/README.md b/README.md index ca19f28..42e34e1 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,19 @@ 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. +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() { ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) @@ -97,16 +110,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 8164d15..6a792e7 100644 --- a/bot.go +++ b/bot.go @@ -59,7 +59,9 @@ type Bot struct { allowedUpdates AllowedUpdates - updates chan *models.Update + updatesChanCap int + updatesMx sync.Mutex + updatesRun *updatesRun } // New creates new Bot instance @@ -81,12 +83,15 @@ func New(token string, options ...Option) (*Bot, error) { checkInitTimeout: defaultCheckInitTimeout, workers: defaultWorkers, - updates: make(chan *models.Update, defaultUpdatesChanCap), + updatesChanCap: defaultUpdatesChanCap, } 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() @@ -122,31 +127,36 @@ func (b *Bot) Token() string { return b.token } -// StartWebhook starts the Bot with webhook mode +// StartWebhook processes updates from WebhookHandler until ctx is canceled. +// 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) { - wg := sync.WaitGroup{} - - wg.Add(b.workers) - for i := 0; i < b.workers; i++ { - go b.waitUpdates(ctx, &wg) - } - - wg.Wait() + b.start(ctx, true) } -// 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. 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) { - 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) - } - - wg.Wait() + b.start(ctx, false) } func defaultErrorsHandler(err error) { diff --git a/bot_test.go b/bot_test.go index e8cb839..bfe9899 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() @@ -180,6 +187,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 +196,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 +211,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 +237,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 +246,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 +260,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 +278,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 +301,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 +310,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 ffee34e..0cf9ea5 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,7 @@ 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 + batch := make([]batchUpdate, 0, len(updates)) for _, raw := range updates { upd, errDecode := decodeUpdate(raw) @@ -92,21 +90,33 @@ func (b *Bot) getUpdates(ctx context.Context, wg *sync.WaitGroup) { } offsetStuck = false - atomic.StoreInt64(&b.lastUpdateID, 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.error("some updates lost, ctx done") + b.confirmDispatched(ctx, batch) return - case b.updates <- upd: + case queue <- queuedUpdate{update: upd, claim: claim}: + batch = append(batch, batchUpdate{id: upd.ID, claim: claim}) } } + if !b.confirmDispatched(ctx, batch) { + return + } + if offsetStuck { // Back off as on a failed request instead of re-requesting the same // batch at full speed. @@ -147,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 bc12161..3b16571 100644 --- a/get_updates_test.go +++ b/get_updates_test.go @@ -1,9 +1,14 @@ package bot import ( + "bytes" "context" + "fmt" "io" "net/http" + "reflect" + "runtime" + "strconv" "strings" "sync" "sync/atomic" @@ -16,12 +21,35 @@ 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, err := io.ReadAll(req.Body) _ = req.Body.Close() + if err != nil { + return nil, err + } + 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.claim.take() + } + }() + b.getUpdates(ctx, queue) + close(queue) + <-done + return delivered +} + func getUpdatesJSONResponse(body string) *http.Response { return &http.Response{ StatusCode: http.StatusOK, @@ -45,7 +73,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 +84,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 +114,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 +130,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 +151,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 +167,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 +220,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 +231,515 @@ 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) + } +} + +// 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() + + 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 { + 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() + })), + ) + 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 != "41" { + t.Errorf("resumed poll offset = %q, want 41", 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, 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() + 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") +} + +// 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), + 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) + } +} + +// 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 0530ab1..587f40d 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. @@ -104,10 +102,14 @@ func WithAllowedUpdates(params AllowedUpdates) Option { } } -// WithUpdatesChannelCap allows setting custom capacity for the Updates channel +// 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.updates = make(chan *models.Update, cap) + b.updatesChanCap = cap } } @@ -132,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/wait_updates.go b/wait_updates.go index 958b452..dae48e3 100644 --- a/wait_updates.go +++ b/wait_updates.go @@ -3,18 +3,138 @@ package bot import ( "context" "sync" + + "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() +type queuedUpdate 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 { + ctx context.Context + webhook bool + queue chan queuedUpdate + done chan struct{} +} + +func (b *Bot) start(ctx context.Context, webhook bool) { + if ctx.Err() != nil { + return + } + if b.workers <= 0 { + // 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 + } + + 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 { + run.queue = make(chan queuedUpdate, b.updatesChanCap) + b.updatesRun = run + b.updatesMx.Unlock() + return true + } + b.updatesMx.Unlock() + select { + case <-previous.done: + case <-run.ctx.Done(): + return false + } + } + return false +} + +func (b *Bot) endUpdates() { + b.updatesMx.Lock() + run := b.updatesRun + b.updatesRun = nil + b.updatesMx.Unlock() + close(run.done) +} + +func (b *Bot) waitUpdates(run *updatesRun, handlers *sync.WaitGroup) { for { select { - case <-ctx.Done(): + case <-run.ctx.Done(): return - case upd := <-b.updates: - b.ProcessUpdate(ctx, upd) + 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() + } } } } + +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 + } + + return applyMiddlewares(b.findHandler(item.update), b.middlewares...), true +} diff --git a/webhook_handler.go b/webhook_handler.go index 2cc5577..b46a1a4 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,14 @@ import ( "github.com/go-telegram/bot/models" ) +// WebhookHandler returns an HTTP handler for updates processed by StartWebhook. +// 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(_ 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 +25,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 +41,42 @@ 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") - } +func (b *Bot) queueWebhookUpdate(ctx context.Context, update *models.Update) bool { + 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 + } + + 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 20eff63..01a55ae 100644 --- a/webhook_handler_test.go +++ b/webhook_handler_test.go @@ -8,7 +8,12 @@ import ( "io" "net/http" "net/http/httptest" + "runtime" + "strconv" + "strings" + "sync" "testing" + "time" "github.com/go-telegram/bot/models" ) @@ -48,10 +53,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 +69,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,14 +84,15 @@ 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) { @@ -100,6 +114,9 @@ func TestWebhookHandler_ReadBodyError(t *testing.T) { handler := bot.WebhookHandler() handler(w, req) + 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") } @@ -139,18 +156,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 +182,473 @@ 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{}) + 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(), + 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) + // Pending requests must be released even while this handler is busy. + <-release + } + 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") + 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. + 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") + 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 := 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") + } + if len(reported) != 0 { + t.Errorf("unexpected error report: %v", <-reported) + } +} - 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") +} + +// 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 { + 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() +} + +func startWebhookForTest(t *testing.T, b *Bot, ctx context.Context) <-chan struct{} { + t.Helper() + stopped := make(chan struct{}) + go func() { + defer close(stopped) + b.StartWebhook(ctx) + }() + 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 { 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{}) + 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(), + 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): + } + + releaseHandler() + 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") +} + +// 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") + } +}