Skip to content

Commit

Permalink
bot: block until poller exits
Browse files Browse the repository at this point in the history
  • Loading branch information
swithek committed Feb 5, 2022
1 parent f029113 commit 96c9c52
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
1 change: 0 additions & 1 deletion api.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,6 @@ func (b *Bot) getMe() (*User, error) {
return nil, wrapError(err)
}
return resp.Result, nil

}

func (b *Bot) getUpdates(offset, limit int, timeout time.Duration, allowed []string) ([]Update, error) {
Expand Down
21 changes: 15 additions & 6 deletions bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func NewBot(pref Settings) (*Bot, error) {

Updates: make(chan Update, pref.Updates),
handlers: make(map[string]HandlerFunc),
stop: make(chan struct{}),
stop: make(chan chan struct{}),

synchronous: pref.Synchronous,
verbose: pref.Verbose,
Expand Down Expand Up @@ -77,7 +77,7 @@ type Bot struct {
synchronous bool
verbose bool
parseMode ParseMode
stop chan struct{}
stop chan chan struct{}
client *http.Client
}

Expand Down Expand Up @@ -209,24 +209,33 @@ func (b *Bot) Start() {
}

stop := make(chan struct{})
go b.Poller.Poll(b, b.Updates, stop)
stopConfirm := make(chan struct{})

go func() {
b.Poller.Poll(b, b.Updates, stop)
close(stopConfirm)
}()

for {
select {
// handle incoming updates
case upd := <-b.Updates:
b.ProcessUpdate(upd)
// call to stop polling
case <-b.stop:
// call to stop polling
case confirm := <-b.stop:
close(stop)
<-stopConfirm
close(confirm)
return
}
}
}

// Stop gracefully shuts the poller down.
func (b *Bot) Stop() {
b.stop <- struct{}{}
confirm := make(chan struct{})
b.stop <- confirm
<-confirm
}

// NewMarkup simply returns newly created markup instance.
Expand Down
7 changes: 6 additions & 1 deletion poller.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,18 @@ func (p *MiddlewarePoller) Poll(b *Bot, dest chan Update, stop chan struct{}) {

middle := make(chan Update, p.Capacity)
stopPoller := make(chan struct{})
stopConfirm := make(chan struct{})

go p.Poller.Poll(b, middle, stopPoller)
go func() {
p.Poller.Poll(b, middle, stopPoller)
close(stopConfirm)
}()

for {
select {
case <-stop:
close(stopPoller)
<-stopConfirm
return
case upd := <-middle:
if p.Filter(&upd) {
Expand Down

0 comments on commit 96c9c52

Please sign in to comment.