Skip to content

Commit

Permalink
Fix potential races in createWaitForEvent*
Browse files Browse the repository at this point in the history
It is possible (and noticed in the real world) that the goroutine might
enter the out select and then by the time get to writing to the channel
back for the event handling to have been canceled.
  • Loading branch information
mstoykov committed Jul 1, 2024
1 parent c3f099a commit 29f6ef3
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions common/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,16 +144,25 @@ func createWaitForEventHandler(
if stringSliceContains(events, ev.typ) {
if predicateFn != nil {
if predicateFn(ev.data) {
ch <- ev.data
select {
case ch <- ev.data:
case <-evCancelCtx.Done():
return
}
}
} else {
ch <- nil
select {
case ch <- nil:
case <-evCancelCtx.Done():
return
}
}
close(ch)

// We wait for one matching event only,
// then remove event handler by cancelling context and stopping goroutine.
evCancelFn()

return
}
}
Expand Down Expand Up @@ -185,9 +194,12 @@ func createWaitForEventPredicateHandler(
case ev := <-chEvHandler:
if stringSliceContains(events, ev.typ) &&
predicateFn != nil && predicateFn(ev.data) {
ch <- ev.data
close(ch)
evCancelFn()
select {
case ch <- ev.data:
close(ch)
evCancelFn()
case <-evCancelCtx.Done():
}
return
}
}
Expand Down

0 comments on commit 29f6ef3

Please sign in to comment.