Skip to content

Commit

Permalink
Merge pull request #205 from shaazmik/main
Browse files Browse the repository at this point in the history
fix leaks in SendWithCallbacks function
  • Loading branch information
carlmontanari authored Dec 2, 2024
2 parents d216749 + 393c675 commit cb04adc
Showing 1 changed file with 28 additions and 21 deletions.
49 changes: 28 additions & 21 deletions driver/generic/sendwithcallbacks.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package generic

import (
"bytes"
"context"
"fmt"
"regexp"
"time"
Expand Down Expand Up @@ -164,50 +165,56 @@ func (d *Driver) handleCallbacks(
b, fb []byte,
timeout time.Duration,
) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

c := make(chan *callbackResult)

go func() {
defer close(c)

for {
rb, err := d.Channel.Read()
if err != nil {
c <- &callbackResult{
err: err,
}

select {
case <-ctx.Done():
return
}

b = append(b, rb...)
fb = append(fb, rb...)

for i, cb := range callbacks {
if cb.check(b) {
default:
rb, err := d.Channel.Read()
if err != nil {
c <- &callbackResult{
i: i,
callbacks: callbacks,
b: b,
fb: fb,
err: nil,
err: err,
}

return
}

b = append(b, rb...)
fb = append(fb, rb...)

for i, cb := range callbacks {
if cb.check(b) {
c <- &callbackResult{
i: i,
callbacks: callbacks,
b: b,
fb: fb,
err: nil,
}

return
}
}
}
}
}()

timer := time.NewTimer(timeout)

select {
case r := <-c:
if r.err != nil {
return nil, r.err
}

return d.executeCallback(r.i, r.callbacks, r.b, r.fb, timeout)
case <-timer.C:
case <-ctx.Done():
return nil, fmt.Errorf("%w: timeout handling callbacks", util.ErrTimeoutError)
}
}
Expand Down

0 comments on commit cb04adc

Please sign in to comment.