From 96c9c520b3a9ac2faa2b6f2f21def19d0e292c63 Mon Sep 17 00:00:00 2001 From: swithek Date: Fri, 4 Feb 2022 17:53:28 +0000 Subject: [PATCH] bot: block until poller exits --- api.go | 1 - bot.go | 21 +++++++++++++++------ poller.go | 7 ++++++- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/api.go b/api.go index 4deb4175..f283ec41 100644 --- a/api.go +++ b/api.go @@ -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) { diff --git a/bot.go b/bot.go index cd16ab43..ae6f7349 100644 --- a/bot.go +++ b/bot.go @@ -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, @@ -77,7 +77,7 @@ type Bot struct { synchronous bool verbose bool parseMode ParseMode - stop chan struct{} + stop chan chan struct{} client *http.Client } @@ -209,16 +209,23 @@ 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 } } @@ -226,7 +233,9 @@ func (b *Bot) Start() { // 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. diff --git a/poller.go b/poller.go index f21e9e49..ec696ba1 100644 --- a/poller.go +++ b/poller.go @@ -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) {