Skip to content

Commit 7f6f09a

Browse files
committed
Iterator checks context
- Check context for error on each iteration. - Test that canceling context stops iteration.
1 parent 6d3c422 commit 7f6f09a

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

datastore.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,10 @@ func QueryIter(ctx context.Context, ds Read, q query.Query) iter.Seq2[query.Entr
124124
defer results.Close()
125125

126126
for result := range results.Next() {
127+
if ctx.Err() != nil {
128+
yield(query.Entry{}, ctx.Err())
129+
return
130+
}
127131
if result.Error != nil {
128132
yield(query.Entry{}, result.Error)
129133
return

test/basic_tests.go

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"context"
66
"crypto/rand"
7+
"errors"
78
"fmt"
89
"reflect"
910
"strings"
@@ -403,7 +404,7 @@ func randValue() []byte {
403404
}
404405

405406
func subtestQuery(t *testing.T, ds dstore.Datastore, q dsq.Query, count int) {
406-
ctx := context.Background()
407+
ctx, cancel := context.WithCancel(context.Background())
407408

408409
var input []dsq.Entry
409410
for i := 0; i < count; i++ {
@@ -538,6 +539,31 @@ func subtestQuery(t *testing.T, ds dstore.Datastore, q dsq.Query, count int) {
538539
}
539540
}
540541

542+
const cancelAt = 1
543+
if len(actual) > cancelAt {
544+
// Test that query iterator stops when context is canceled.
545+
var i int
546+
for ent, err := range dstore.QueryIter(ctx, ds, q) {
547+
if err != nil {
548+
if !errors.Is(err, context.Canceled) {
549+
t.Fatal("query result error: ", err)
550+
}
551+
t.Log("err at:", i, err)
552+
continue
553+
}
554+
if ent.Key == "" {
555+
t.Fatal("entry has empty key")
556+
}
557+
i++
558+
if i == cancelAt {
559+
cancel()
560+
}
561+
}
562+
if i != cancelAt {
563+
t.Fatal("expected iteration to be canceled at", cancelAt, "canceled at", i)
564+
}
565+
}
566+
541567
t.Log("deleting all keys")
542568
for _, e := range input {
543569
if err := ds.Delete(ctx, dstore.RawKey(e.Key)); err != nil {

0 commit comments

Comments
 (0)