2
0
mirror of https://github.com/hibiken/asynq.git synced 2024-11-14 11:31:18 +08:00
asynq/subscriber.go

85 lines
1.8 KiB
Go
Raw Normal View History

// Copyright 2020 Kentaro Hibino. All rights reserved.
// Use of this source code is governed by a MIT license
// that can be found in the LICENSE file.
package asynq
import (
2020-02-16 15:14:30 +08:00
"sync"
"time"
2020-02-16 15:14:30 +08:00
"github.com/go-redis/redis/v7"
"github.com/hibiken/asynq/internal/base"
2020-05-06 13:10:11 +08:00
"github.com/hibiken/asynq/internal/log"
)
type subscriber struct {
2020-05-06 13:10:11 +08:00
logger *log.Logger
2020-04-18 22:55:10 +08:00
broker base.Broker
// channel to communicate back to the long running "subscriber" goroutine.
done chan struct{}
// cancelations hold cancel functions for all in-progress tasks.
cancelations *base.Cancelations
// time to wait before retrying to connect to redis.
retryTimeout time.Duration
}
2020-05-06 13:10:11 +08:00
func newSubscriber(l *log.Logger, b base.Broker, cancelations *base.Cancelations) *subscriber {
return &subscriber{
2020-03-09 22:11:16 +08:00
logger: l,
2020-04-17 21:56:44 +08:00
broker: b,
done: make(chan struct{}),
cancelations: cancelations,
retryTimeout: 5 * time.Second,
}
}
func (s *subscriber) terminate() {
2020-03-09 22:11:16 +08:00
s.logger.Info("Subscriber shutting down...")
// Signal the subscriber goroutine to stop.
s.done <- struct{}{}
}
2020-02-16 15:14:30 +08:00
func (s *subscriber) start(wg *sync.WaitGroup) {
wg.Add(1)
go func() {
2020-02-16 15:14:30 +08:00
defer wg.Done()
var (
pubsub *redis.PubSub
err error
)
// Try until successfully connect to Redis.
for {
2020-04-17 21:56:44 +08:00
pubsub, err = s.broker.CancelationPubSub()
if err != nil {
2020-05-06 13:10:11 +08:00
s.logger.Errorf("cannot subscribe to cancelation channel: %v", err)
select {
case <-time.After(s.retryTimeout):
continue
case <-s.done:
s.logger.Info("Subscriber done")
return
}
}
break
}
cancelCh := pubsub.Channel()
for {
select {
case <-s.done:
pubsub.Close()
2020-03-09 22:11:16 +08:00
s.logger.Info("Subscriber done")
return
case msg := <-cancelCh:
2020-02-20 23:44:13 +08:00
cancel, ok := s.cancelations.Get(msg.Payload)
if ok {
cancel()
}
}
}
}()
}