Skip to content

Commit 6c6f10e

Browse files
committed
ResultBuilder and ResultsWithContext take a parent context to cancel results
1 parent 65c4f51 commit 6c6f10e

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

query/query.go

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ func (rb *ResultBuilder) Results() Results {
221221
const NormalBufSize = 1
222222
const KeysOnlyBufSize = 128
223223

224-
func NewResultBuilder(q Query) *ResultBuilder {
224+
func NewResultBuilder(ctx context.Context, q Query) *ResultBuilder {
225225
bufSize := NormalBufSize
226226
if q.KeysOnly {
227227
bufSize = KeysOnlyBufSize
@@ -230,7 +230,7 @@ func NewResultBuilder(q Query) *ResultBuilder {
230230
Query: q,
231231
Output: make(chan Result, bufSize),
232232
}
233-
b.ctx, b.cancel = context.WithCancel(context.Background())
233+
b.ctx, b.cancel = context.WithCancel(ctx)
234234
context.AfterFunc(b.ctx, func() {
235235
close(b.Output)
236236
})
@@ -243,7 +243,7 @@ func NewResultBuilder(q Query) *ResultBuilder {
243243
// DEPRECATED: This iterator is impossible to cancel correctly. Canceling it
244244
// will leave anything trying to write to the result channel hanging.
245245
func ResultsWithChan(q Query, res <-chan Result) Results {
246-
return ResultsWithContext(q, func(ctx context.Context, out chan<- Result) {
246+
return ResultsWithContext(context.Background(), q, func(ctx context.Context, out chan<- Result) {
247247
for {
248248
select {
249249
case <-ctx.Done(): // client told us to close early
@@ -263,10 +263,12 @@ func ResultsWithChan(q Query, res <-chan Result) Results {
263263
})
264264
}
265265

266-
// ResultsWithCtxs returns a Results object with the results generated by the
267-
// passed proc function called in a separate goroutine.
268-
func ResultsWithContext(q Query, proc func(context.Context, chan<- Result)) Results {
269-
b := NewResultBuilder(q)
266+
// ResultsWithContext returns a Results object with the results generated by
267+
// the passed proc function called in a separate goroutine. The context passed
268+
// into the proc function is cancelled when the returned Results is closed, or
269+
// when the parent context, ctx, is canceled.
270+
func ResultsWithContext(ctx context.Context, q Query, proc func(context.Context, chan<- Result)) Results {
271+
b := NewResultBuilder(ctx, q)
270272

271273
go func() {
272274
defer b.cancel()
@@ -386,7 +388,7 @@ func (r *resultsIter) useLegacyResults() {
386388
return
387389
}
388390

389-
b := NewResultBuilder(r.query)
391+
b := NewResultBuilder(context.Background(), r.query)
390392

391393
// go consume all the entries and add them to the results.
392394
go func(ctx context.Context, cancel context.CancelFunc, out chan<- Result) {

0 commit comments

Comments
 (0)