Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,23 +90,44 @@ 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)
defer cancel()

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
}
Expand Down
56 changes: 33 additions & 23 deletions bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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()
Expand Down Expand Up @@ -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) {
Expand Down
44 changes: 28 additions & 16 deletions bot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -237,26 +246,26 @@ 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 {
t.Error(errReq)
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 {
Expand All @@ -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)
Expand All @@ -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 {
Expand All @@ -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 {
Expand Down
85 changes: 78 additions & 7 deletions get_updates.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"sync"
"sync/atomic"
"time"

Expand All @@ -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 {
Expand Down Expand Up @@ -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)
Expand All @@ -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.
Expand Down Expand Up @@ -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()
}
}
Loading
Loading