2020-02-13 09:12:09 +08:00
|
|
|
// 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"
|
|
|
|
|
2020-02-13 09:12:09 +08:00
|
|
|
"github.com/hibiken/asynq/internal/base"
|
|
|
|
"github.com/hibiken/asynq/internal/rdb"
|
|
|
|
)
|
|
|
|
|
|
|
|
type subscriber struct {
|
2020-03-12 22:31:10 +08:00
|
|
|
logger Logger
|
2020-03-09 22:11:16 +08:00
|
|
|
rdb *rdb.RDB
|
2020-02-13 09:12:09 +08:00
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
2020-03-12 22:31:10 +08:00
|
|
|
func newSubscriber(l Logger, rdb *rdb.RDB, cancelations *base.Cancelations) *subscriber {
|
2020-02-13 09:12:09 +08:00
|
|
|
return &subscriber{
|
2020-03-09 22:11:16 +08:00
|
|
|
logger: l,
|
2020-02-13 09:12:09 +08:00
|
|
|
rdb: rdb,
|
|
|
|
done: make(chan struct{}),
|
|
|
|
cancelations: cancelations,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *subscriber) terminate() {
|
2020-03-09 22:11:16 +08:00
|
|
|
s.logger.Info("Subscriber shutting down...")
|
2020-02-13 09:12:09 +08:00
|
|
|
// Signal the subscriber goroutine to stop.
|
|
|
|
s.done <- struct{}{}
|
|
|
|
}
|
|
|
|
|
2020-02-16 15:14:30 +08:00
|
|
|
func (s *subscriber) start(wg *sync.WaitGroup) {
|
2020-02-13 09:12:09 +08:00
|
|
|
pubsub, err := s.rdb.CancelationPubSub()
|
|
|
|
cancelCh := pubsub.Channel()
|
|
|
|
if err != nil {
|
2020-03-09 22:11:16 +08:00
|
|
|
s.logger.Error("cannot subscribe to cancelation channel: %v", err)
|
2020-02-13 09:12:09 +08:00
|
|
|
return
|
|
|
|
}
|
2020-02-16 15:14:30 +08:00
|
|
|
wg.Add(1)
|
2020-02-13 09:12:09 +08:00
|
|
|
go func() {
|
2020-02-16 15:14:30 +08:00
|
|
|
defer wg.Done()
|
2020-02-13 09:12:09 +08:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-s.done:
|
|
|
|
pubsub.Close()
|
2020-03-09 22:11:16 +08:00
|
|
|
s.logger.Info("Subscriber done")
|
2020-02-13 09:12:09 +08:00
|
|
|
return
|
|
|
|
case msg := <-cancelCh:
|
2020-02-20 23:44:13 +08:00
|
|
|
cancel, ok := s.cancelations.Get(msg.Payload)
|
|
|
|
if ok {
|
2020-02-13 09:12:09 +08:00
|
|
|
cancel()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|