|
| 1 | +package nsq |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "runtime" |
| 7 | + "sync" |
| 8 | + "sync/atomic" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/golang-queue/queue" |
| 12 | + |
| 13 | + "github.com/nsqio/go-nsq" |
| 14 | +) |
| 15 | + |
| 16 | +var _ queue.Worker = (*Worker)(nil) |
| 17 | + |
| 18 | +// Option for queue system |
| 19 | +type Option func(*Worker) |
| 20 | + |
| 21 | +// Worker for NSQ |
| 22 | +type Worker struct { |
| 23 | + q *nsq.Consumer |
| 24 | + p *nsq.Producer |
| 25 | + startOnce sync.Once |
| 26 | + stopOnce sync.Once |
| 27 | + stop chan struct{} |
| 28 | + maxInFlight int |
| 29 | + addr string |
| 30 | + topic string |
| 31 | + channel string |
| 32 | + runFunc func(context.Context, queue.QueuedMessage) error |
| 33 | + logger queue.Logger |
| 34 | + stopFlag int32 |
| 35 | + startFlag int32 |
| 36 | +} |
| 37 | + |
| 38 | +// WithAddr setup the addr of NSQ |
| 39 | +func WithAddr(addr string) Option { |
| 40 | + return func(w *Worker) { |
| 41 | + w.addr = addr |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// WithTopic setup the topic of NSQ |
| 46 | +func WithTopic(topic string) Option { |
| 47 | + return func(w *Worker) { |
| 48 | + w.topic = topic |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +// WithChannel setup the channel of NSQ |
| 53 | +func WithChannel(channel string) Option { |
| 54 | + return func(w *Worker) { |
| 55 | + w.channel = channel |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +// WithRunFunc setup the run func of queue |
| 60 | +func WithRunFunc(fn func(context.Context, queue.QueuedMessage) error) Option { |
| 61 | + return func(w *Worker) { |
| 62 | + w.runFunc = fn |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +// WithMaxInFlight Maximum number of messages to allow in flight (concurrency knob) |
| 67 | +func WithMaxInFlight(num int) Option { |
| 68 | + return func(w *Worker) { |
| 69 | + w.maxInFlight = num |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +// WithLogger set custom logger |
| 74 | +func WithLogger(l queue.Logger) Option { |
| 75 | + return func(w *Worker) { |
| 76 | + w.logger = l |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +// NewWorker for struc |
| 81 | +func NewWorker(opts ...Option) *Worker { |
| 82 | + var err error |
| 83 | + w := &Worker{ |
| 84 | + addr: "127.0.0.1:4150", |
| 85 | + topic: "gorush", |
| 86 | + channel: "ch", |
| 87 | + maxInFlight: runtime.NumCPU(), |
| 88 | + stop: make(chan struct{}), |
| 89 | + logger: queue.NewLogger(), |
| 90 | + runFunc: func(context.Context, queue.QueuedMessage) error { |
| 91 | + return nil |
| 92 | + }, |
| 93 | + } |
| 94 | + |
| 95 | + // Loop through each option |
| 96 | + for _, opt := range opts { |
| 97 | + // Call the option giving the instantiated |
| 98 | + opt(w) |
| 99 | + } |
| 100 | + |
| 101 | + cfg := nsq.NewConfig() |
| 102 | + cfg.MaxInFlight = w.maxInFlight |
| 103 | + w.q, err = nsq.NewConsumer(w.topic, w.channel, cfg) |
| 104 | + if err != nil { |
| 105 | + panic(err) |
| 106 | + } |
| 107 | + |
| 108 | + w.p, err = nsq.NewProducer(w.addr, cfg) |
| 109 | + if err != nil { |
| 110 | + panic(err) |
| 111 | + } |
| 112 | + |
| 113 | + return w |
| 114 | +} |
| 115 | + |
| 116 | +// BeforeRun run script before start worker |
| 117 | +func (s *Worker) BeforeRun() error { |
| 118 | + return nil |
| 119 | +} |
| 120 | + |
| 121 | +// AfterRun run script after start worker |
| 122 | +func (s *Worker) AfterRun() error { |
| 123 | + s.startOnce.Do(func() { |
| 124 | + time.Sleep(100 * time.Millisecond) |
| 125 | + err := s.q.ConnectToNSQD(s.addr) |
| 126 | + if err != nil { |
| 127 | + panic("Could not connect nsq server: " + err.Error()) |
| 128 | + } |
| 129 | + |
| 130 | + atomic.CompareAndSwapInt32(&s.startFlag, 0, 1) |
| 131 | + }) |
| 132 | + |
| 133 | + return nil |
| 134 | +} |
| 135 | + |
| 136 | +func (s *Worker) handle(job queue.Job) error { |
| 137 | + // create channel with buffer size 1 to avoid goroutine leak |
| 138 | + done := make(chan error, 1) |
| 139 | + panicChan := make(chan interface{}, 1) |
| 140 | + startTime := time.Now() |
| 141 | + ctx, cancel := context.WithTimeout(context.Background(), job.Timeout) |
| 142 | + defer cancel() |
| 143 | + |
| 144 | + // run the job |
| 145 | + go func() { |
| 146 | + // handle panic issue |
| 147 | + defer func() { |
| 148 | + if p := recover(); p != nil { |
| 149 | + panicChan <- p |
| 150 | + } |
| 151 | + }() |
| 152 | + |
| 153 | + // run custom process function |
| 154 | + done <- s.runFunc(ctx, job) |
| 155 | + }() |
| 156 | + |
| 157 | + select { |
| 158 | + case p := <-panicChan: |
| 159 | + panic(p) |
| 160 | + case <-ctx.Done(): // timeout reached |
| 161 | + return ctx.Err() |
| 162 | + case <-s.stop: // shutdown service |
| 163 | + // cancel job |
| 164 | + cancel() |
| 165 | + |
| 166 | + leftTime := job.Timeout - time.Since(startTime) |
| 167 | + // wait job |
| 168 | + select { |
| 169 | + case <-time.After(leftTime): |
| 170 | + return context.DeadlineExceeded |
| 171 | + case err := <-done: // job finish |
| 172 | + return err |
| 173 | + case p := <-panicChan: |
| 174 | + panic(p) |
| 175 | + } |
| 176 | + case err := <-done: // job finish |
| 177 | + return err |
| 178 | + } |
| 179 | +} |
| 180 | + |
| 181 | +// Run start the worker |
| 182 | +func (s *Worker) Run() error { |
| 183 | + wg := &sync.WaitGroup{} |
| 184 | + panicChan := make(chan interface{}, 1) |
| 185 | + s.q.AddHandler(nsq.HandlerFunc(func(msg *nsq.Message) error { |
| 186 | + wg.Add(1) |
| 187 | + defer func() { |
| 188 | + wg.Done() |
| 189 | + if p := recover(); p != nil { |
| 190 | + panicChan <- p |
| 191 | + } |
| 192 | + }() |
| 193 | + if len(msg.Body) == 0 { |
| 194 | + // Returning nil will automatically send a FIN command to NSQ to mark the message as processed. |
| 195 | + // In this case, a message with an empty body is simply ignored/discarded. |
| 196 | + return nil |
| 197 | + } |
| 198 | + |
| 199 | + var data queue.Job |
| 200 | + _ = json.Unmarshal(msg.Body, &data) |
| 201 | + return s.handle(data) |
| 202 | + })) |
| 203 | + |
| 204 | + // wait close signal |
| 205 | + select { |
| 206 | + case <-s.stop: |
| 207 | + case err := <-panicChan: |
| 208 | + s.logger.Error(err) |
| 209 | + } |
| 210 | + |
| 211 | + // wait job completed |
| 212 | + wg.Wait() |
| 213 | + |
| 214 | + return nil |
| 215 | +} |
| 216 | + |
| 217 | +// Shutdown worker |
| 218 | +func (s *Worker) Shutdown() error { |
| 219 | + if !atomic.CompareAndSwapInt32(&s.stopFlag, 0, 1) { |
| 220 | + return queue.ErrQueueShutdown |
| 221 | + } |
| 222 | + |
| 223 | + s.stopOnce.Do(func() { |
| 224 | + if atomic.LoadInt32(&s.startFlag) == 1 { |
| 225 | + s.q.Stop() |
| 226 | + s.p.Stop() |
| 227 | + } |
| 228 | + |
| 229 | + close(s.stop) |
| 230 | + }) |
| 231 | + return nil |
| 232 | +} |
| 233 | + |
| 234 | +// Capacity for channel |
| 235 | +func (s *Worker) Capacity() int { |
| 236 | + return 0 |
| 237 | +} |
| 238 | + |
| 239 | +// Usage for count of channel usage |
| 240 | +func (s *Worker) Usage() int { |
| 241 | + return 0 |
| 242 | +} |
| 243 | + |
| 244 | +// Queue send notification to queue |
| 245 | +func (s *Worker) Queue(job queue.QueuedMessage) error { |
| 246 | + if atomic.LoadInt32(&s.stopFlag) == 1 { |
| 247 | + return queue.ErrQueueShutdown |
| 248 | + } |
| 249 | + |
| 250 | + err := s.p.Publish(s.topic, job.Bytes()) |
| 251 | + if err != nil { |
| 252 | + return err |
| 253 | + } |
| 254 | + |
| 255 | + return nil |
| 256 | +} |
0 commit comments