Skip to content

Commit b591c0b

Browse files
Merge pull request #30 from hellofresh/patch/panic-on-cancel
Fix panic when BackgroundProcessor execute is cancelled
2 parents 68a5e2c + 71210a6 commit b591c0b

File tree

1 file changed

+14
-15
lines changed

1 file changed

+14
-15
lines changed

driver/sql/internal/background_processor.go

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,8 @@ func (b *BackgroundProcessor) Start(ctx context.Context, handler ProcessHandler)
9595

9696
return func() {
9797
close(b.done)
98-
close(b.queue)
9998
wg.Wait()
99+
close(b.queue)
100100
}
101101
}
102102

@@ -115,20 +115,20 @@ func (b *BackgroundProcessor) Queue(ctx context.Context, notification *sql.Proje
115115
}
116116

117117
func (b *BackgroundProcessor) startProcessor(ctx context.Context, handler ProcessHandler) {
118-
for notification := range b.queue {
118+
for {
119119
select {
120-
default:
120+
case <-b.done:
121+
return
121122
case <-ctx.Done():
122-
// Context is expired
123123
return
124-
}
125-
126-
// Execute the notification
127-
if err := handler(ctx, notification, b.Queue); err != nil {
128-
b.logger.
129-
WithError(err).
130-
WithField("notification", notification).
131-
Error("the ProcessHandler produced an error")
124+
case notification := <-b.queue:
125+
// Execute the notification
126+
if err := handler(ctx, notification, b.Queue); err != nil {
127+
b.logger.
128+
WithError(err).
129+
WithField("notification", notification).
130+
Error("the ProcessHandler produced an error")
131+
}
132132
}
133133
}
134134
}
@@ -150,21 +150,20 @@ func (b *BackgroundProcessor) wrapProcessHandlerForSingleRun(handler ProcessHand
150150
defer m.Unlock()
151151

152152
triggers--
153-
if triggers != 0 || done == nil {
153+
if triggers != 0 {
154154
return
155155
}
156156

157157
// Only close the done channel when the queue is empty or the context is closed
158158
select {
159+
case <-done:
159160
case <-ctx.Done():
160161
// Context is expired
161162
close(done)
162-
done = nil
163163
default:
164164
// No more queued messages to close the run
165165
if len(b.queue) == 0 {
166166
close(done)
167-
done = nil
168167
}
169168
}
170169
}()

0 commit comments

Comments
 (0)