Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion pubsub/pubsub.go
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,8 @@ type Subscription struct {
canNack bool // true iff the driver supports Nack
backgroundCtx context.Context // for background SendAcks and ReceiveBatch calls
cancel func() // for canceling backgroundCtx
recvCtx context.Context // for background ReceiveBatch calls; child of backgroundCtx
recvCancel func() // for canceling recvCtx

recvBatchOpts *batcher.Options

Expand Down Expand Up @@ -704,7 +706,7 @@ type msgsOrError struct {
// messages as they come from each independent batch, or an operation error
func (s *Subscription) getNextBatch(batches []int) chan msgsOrError {
result := make(chan msgsOrError, len(batches))
g, ctx := errgroup.WithContext(s.backgroundCtx)
g, ctx := errgroup.WithContext(s.recvCtx)
for _, maxMessagesInBatch := range batches {
// Make a copy of the loop variable since it will be used by a goroutine.
curMaxMessagesInBatch := maxMessagesInBatch
Expand Down Expand Up @@ -748,6 +750,25 @@ func (s *Subscription) Shutdown(ctx context.Context) (err error) {
return s.err
}
s.err = errSubscriptionShutdown
if s.canNack && s.ackBatcher != nil {
// Stop in-flight ReceiveBatch calls and wait for their messages to land
// in s.q, then nack everything Receive never returned, so it is
// redelivered without waiting for the ack deadline to expire.
s.recvCancel()
for s.fetches > 0 && ctx.Err() == nil {
waitc := s.waitc
s.mu.Unlock()
select {
case <-waitc:
case <-ctx.Done():
}
s.mu.Lock()
}
for _, m := range s.q {
_ = s.ackBatcher.AddNoWait(&driver.AckInfo{AckID: m.AckID, IsAck: false})
}
s.q = nil
}
s.mu.Unlock()
c := make(chan struct{})
go func() {
Expand Down Expand Up @@ -803,11 +824,14 @@ var NewSubscription = newSubscription
// defaults.
func newSubscription(ds driver.Subscription, recvBatchOpts, ackBatcherOpts *batcher.Options) *Subscription {
ctx, cancel := context.WithCancel(context.Background())
recvCtx, recvCancel := context.WithCancel(ctx)
s := &Subscription{
driver: ds,
tracer: gcdkotel.NewTracer(pkgName, gcdkotel.ProviderName(ds)),
cancel: cancel,
backgroundCtx: ctx,
recvCtx: recvCtx,
recvCancel: recvCancel,
recvBatchOpts: recvBatchOpts,
runningBatchSize: initialBatchSize,
canNack: ds.CanNack(),
Expand Down
99 changes: 99 additions & 0 deletions pubsub/pubsub_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"time"

"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"gocloud.dev/gcerrors"
"gocloud.dev/internal/gcerr"
"gocloud.dev/internal/testing/oteltest"
Expand Down Expand Up @@ -338,6 +339,104 @@ func TestIndependentBatchReturn(t *testing.T) {
m.Ack()
}

// prefetchDriverSub returns all its messages on the first ReceiveBatch call
// and records what is acked and nacked. If late is set, that call returns only
// once its context is canceled, like a receive still in flight at Shutdown.
type prefetchDriverSub struct {
driver.Subscription
canNack bool
late bool
msgs []*driver.Message

mu sync.Mutex
calls int
acks []driver.AckID
nacks []driver.AckID
}

func (s *prefetchDriverSub) ReceiveBatch(ctx context.Context, _ int) ([]*driver.Message, error) {
s.mu.Lock()
s.calls++
first := s.calls == 1
s.mu.Unlock()
if !first || s.late {
<-ctx.Done()
}
if !first {
return nil, ctx.Err()
}
return s.msgs, nil
}

func (s *prefetchDriverSub) SendAcks(_ context.Context, ids []driver.AckID) error {
s.mu.Lock()
defer s.mu.Unlock()
s.acks = append(s.acks, ids...)
return nil
}

func (s *prefetchDriverSub) SendNacks(_ context.Context, ids []driver.AckID) error {
s.mu.Lock()
defer s.mu.Unlock()
s.nacks = append(s.nacks, ids...)
return nil
}

func (s *prefetchDriverSub) CanNack() bool { return s.canNack }
func (*prefetchDriverSub) IsRetryable(error) bool { return false }
func (*prefetchDriverSub) Close() error { return nil }

// TestShutdownNacksPrefetched verifies that Shutdown nacks messages that were
// prefetched but never returned by Receive, including ones from a ReceiveBatch
// call still in flight at Shutdown.
func TestShutdownNacksPrefetched(t *testing.T) {
for _, test := range []struct {
name string
canNack, late bool
wantAcks []driver.AckID
wantNacks []driver.AckID
}{
{name: "queued", canNack: true, wantAcks: []driver.AckID{0}, wantNacks: []driver.AckID{1, 2, 3, 4}},
{name: "in flight", canNack: true, late: true, wantNacks: []driver.AckID{0, 1, 2, 3, 4}},
{name: "can't nack", wantAcks: []driver.AckID{0}},
} {
t.Run(test.name, func(t *testing.T) {
ctx := context.Background()
ds := &prefetchDriverSub{canNack: test.canNack, late: test.late}
for i := 0; i < 5; i++ {
ds.msgs = append(ds.msgs, &driver.Message{AckID: i, Body: []byte("m")})
}
s := NewSubscription(ds, nil, nil)
if test.late {
rctx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
defer cancel()
if _, err := s.Receive(rctx); err != context.DeadlineExceeded {
t.Fatalf("Receive: got %v, want context.DeadlineExceeded", err)
}
} else {
m, err := s.Receive(ctx)
if err != nil {
t.Fatal(err)
}
m.Ack()
}
if err := s.Shutdown(ctx); err != nil {
t.Fatal(err)
}

ds.mu.Lock()
defer ds.mu.Unlock()
if diff := cmp.Diff(test.wantAcks, ds.acks, cmpopts.EquateEmpty()); diff != "" {
t.Errorf("acks (-want +got):\n%s", diff)
}
sortIDs := cmpopts.SortSlices(func(a, b driver.AckID) bool { return a.(int) < b.(int) })
if diff := cmp.Diff(test.wantNacks, ds.nacks, sortIDs, cmpopts.EquateEmpty()); diff != "" {
t.Errorf("nacks (-want +got):\n%s", diff)
}
})
}
}

func TestRetryTopic(t *testing.T) {
// Test that Send is retried if the driver returns a retryable error.
ctx := context.Background()
Expand Down
Loading