Debian Codegraph @

pubsub/acks_test.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 package pubsub_test
15
16 import (
17 "context"
18 "errors"
19 "math/rand"
20 "sync"
21 "testing"
22 "time"
23
24 "gocloud.dev/gcerrors"
25 "gocloud.dev/internal/gcerr"
26 "gocloud.dev/pubsub"
27 "gocloud.dev/pubsub/driver"
28 )
29
30 type ackingDriverSub struct {
31 driver.Subscription
32 q []*driver.Message
33 sendAcks func(context.Context, []driver.AckID) error
34 }
35
36 func (s *ackingDriverSub) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) {
37 if len(s.q) <= maxMessages {
38 ms := s.q
39 s.q = nil
40 return ms, nil
41 }
42 ms := s.q[:maxMessages]
43 s.q = s.q[maxMessages:]
44 return ms, nil
45 }
46
47 func (s *ackingDriverSub) SendAcks(ctx context.Context, ackIDs []driver.AckID) error {
48 return s.sendAcks(ctx, ackIDs)
49 }
50
51 func (*ackingDriverSub) IsRetryable(error) bool { return false }
52 func (*ackingDriverSub) ErrorCode(error) gcerrors.ErrorCode { return gcerrors.Internal }
53 func (*ackingDriverSub) CanNack() bool { return false }
54 func (*ackingDriverSub) Close() error { return nil }
55
56 func TestAckTriggersDriverSendAcksForOneMessage(t *testing.T) {
57 ctx := context.Background()
58 var mu sync.Mutex
59 var sentAcks []driver.AckID
60 id := rand.Int()
61 m := &driver.Message{AckID: id}
62 ackChan := make(chan struct{})
63 ds := &ackingDriverSub{
64 q: []*driver.Message{m},
65 sendAcks: func(_ context.Context, ackIDs []driver.AckID) error {
66 mu.Lock()
67 defer mu.Unlock()
68 sentAcks = ackIDs
69 ackChan <- struct{}{}
70 return nil
71 },
72 }
73 sub := pubsub.NewSubscription(ds, nil, nil)
74 defer sub.Shutdown(ctx)
75 m2, err := sub.Receive(ctx)
76 if err != nil {
77 t.Fatal(err)
78 }
79 m2.Ack()
80 <-ackChan
81 if len(sentAcks) != 1 {
82 t.Fatalf("len(sentAcks) = %d, want exactly 1", len(sentAcks))
83 }
84 if sentAcks[0] != id {
85 t.Errorf("sentAcks[0] = %d, want %d", sentAcks[0], id)
86 }
87 }
88
89 func TestMultipleAcksCanGoIntoASingleBatch(t *testing.T) {
90 ctx := context.Background()
91 var wg sync.WaitGroup
92 var mu sync.Mutex
93 sentAcks := make(map[driver.AckID]int)
94 ids := []int{1, 2}
95 ds := &ackingDriverSub{
96 q: []*driver.Message{{AckID: ids[0]}, {AckID: ids[1]}},
97 sendAcks: func(_ context.Context, ackIDs []driver.AckID) error {
98 mu.Lock()
99 defer mu.Unlock()
100 for _, id := range ackIDs {
101 sentAcks[id]++
102 wg.Done()
103 }
104 return nil
105 },
106 }
107 sub := pubsub.NewSubscription(ds, nil, nil)
108 defer sub.Shutdown(ctx)
109
110 // Receive and ack the messages concurrently.
111 for range 2 {
112 wg.Add(1)
113 go func() {
114 mr, err := sub.Receive(ctx)
115 if err != nil {
116 t.Error(err)
117 return
118 }
119 mr.Ack()
120 }()
121 }
122 wg.Wait()
123
124 if len(sentAcks) != 2 {
125 t.Errorf("len(sentAcks) = %d, want exactly 2", len(sentAcks))
126 }
127 for _, id := range ids {
128 if sentAcks[id] != 1 {
129 t.Errorf("sentAcks[%v] = %d, want 1", id, sentAcks[id])
130 }
131 }
132 }
133
134 func TestTooManyAcksForASingleBatchGoIntoMultipleBatches(t *testing.T) {
135 ctx := context.Background()
136 var mu sync.Mutex
137 var wg sync.WaitGroup
138 var sentAckBatches [][]driver.AckID
139 // This value of n is chosen large enough that it should create more
140 // than one batch. Admittedly, there is currently no explicit guarantee
141 // of this.
142 n := 1000
143 var ms []*driver.Message
144 for i := range n {
145 ms = append(ms, &driver.Message{AckID: i})
146 }
147 ds := &ackingDriverSub{
148 q: ms,
149 sendAcks: func(_ context.Context, ackIDs []driver.AckID) error {
150 mu.Lock()
151 defer mu.Unlock()
152 sentAckBatches = append(sentAckBatches, ackIDs)
153 for range ackIDs {
154 wg.Done()
155 }
156 return nil
157 },
158 }
159 sub := pubsub.NewSubscription(ds, nil, nil)
160 defer sub.Shutdown(ctx)
161
162 errs := make(chan error, n)
163 // Receive and ack the messages concurrently.
164 recv := func() {
165 mr, err := sub.Receive(ctx)
166 if err != nil {
167 errs <- err
168 }
169 mr.Ack()
170 }
171 wg.Add(n)
172 for range n {
173 go recv()
174 }
175 wg.Wait()
176
177 close(errs)
178
179 if len(sentAckBatches) < 2 {
180 t.Errorf("got %d batches, want at least 2", len(sentAckBatches))
181 }
182
183 for err := range errs {
184 t.Fatalf("got error from goroutine: %v", err)
185 }
186 }
187
188 func TestAckDoesNotBlock(t *testing.T) {
189 ctx, cancel := context.WithCancel(context.Background())
190 m := &driver.Message{AckID: 0} // the batcher doesn't like nil interfaces
191 ds := &ackingDriverSub{
192 q: []*driver.Message{m},
193 sendAcks: func(_ context.Context, ackIDs []driver.AckID) error {
194 <-ctx.Done()
195 return nil
196 },
197 }
198 sub := pubsub.NewSubscription(ds, nil, nil)
199 defer sub.Shutdown(ctx)
200 defer cancel()
201 mr, err := sub.Receive(ctx)
202 if err != nil {
203 t.Fatal(err)
204 }
205 // If Ack blocks here, waiting for sendAcks to finish, then the
206 // deferred cancel() will never run, so sendAcks can never finish. That
207 // would cause the test to hang. Thus hanging is how this test signals
208 // failure.
209 mr.Ack()
210 }
211
212 func TestDoubleAckCausesPanic(t *testing.T) {
213 ctx := context.Background()
214 m := &driver.Message{AckID: 0} // the batcher doesn't like nil interfaces
215 ds := &ackingDriverSub{
216 q: []*driver.Message{m},
217 sendAcks: func(_ context.Context, ackIDs []driver.AckID) error {
218 return nil
219 },
220 }
221 sub := pubsub.NewSubscription(ds, nil, nil)
222 defer sub.Shutdown(ctx)
223 mr, err := sub.Receive(ctx)
224 if err != nil {
225 t.Fatal(err)
226 }
227 mr.Ack()
228 defer func() {
229 if r := recover(); r != nil {
230 // ok, panic was expected.
231 return
232 }
233 t.Errorf("second ack failed to panic")
234 }()
235 mr.Ack()
236 }
237
238 // For best results, run this test with -race.
239 func TestConcurrentDoubleAckCausesPanic(t *testing.T) {
240 ctx := context.Background()
241 m := &driver.Message{AckID: 0} // the batcher doesn't like nil interfaces
242 ds := &ackingDriverSub{
243 q: []*driver.Message{m},
244 sendAcks: func(_ context.Context, ackIDs []driver.AckID) error {
245 return nil
246 },
247 }
248 sub := pubsub.NewSubscription(ds, nil, nil)
249 defer sub.Shutdown(ctx)
250 mr, err := sub.Receive(ctx)
251 if err != nil {
252 t.Fatal(err)
253 }
254
255 // Spin up some goroutines to ack the message.
256 var mu sync.Mutex
257 panics := 0
258 var wg sync.WaitGroup
259 for range 2 {
260 wg.Add(1)
261 go func() {
262 defer wg.Done()
263 defer func() {
264 if r := recover(); r != nil {
265 mu.Lock()
266 defer mu.Unlock()
267 panics++
268 }
269 }()
270 mr.Ack()
271 }()
272 }
273 wg.Wait()
274
275 // Check that one of the goroutines panicked.
276 if panics != 1 {
277 t.Errorf("panics = %d, want %d", panics, 1)
278 }
279 }
280
281 func TestSubShutdownCanBeCanceledEvenWithHangingSendAcks(t *testing.T) {
282 ctx := context.Background()
283 m := &driver.Message{AckID: 0} // the batcher doesn't like nil interfaces
284 ds := &ackingDriverSub{
285 q: []*driver.Message{m},
286 sendAcks: func(ctx context.Context, ackIDs []driver.AckID) error {
287 <-ctx.Done()
288 return ctx.Err()
289 },
290 }
291 sub := pubsub.NewSubscription(ds, nil, nil)
292 mr, err := sub.Receive(ctx)
293 if err != nil {
294 t.Fatal(err)
295 }
296 mr.Ack()
297
298 done := make(chan struct{})
299 go func() {
300 ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
301 defer cancel()
302 sub.Shutdown(ctx)
303 close(done)
304 }()
305 tooLong := 5 * time.Second
306 select {
307 case <-done:
308 case <-time.After(tooLong):
309 t.Fatalf("waited too long (%v) for Shutdown to run", tooLong)
310 }
311 }
312
313 func TestReceiveReturnsErrorFromSendAcks(t *testing.T) {
314 // If SendAcks fails, the error is returned via receive.
315 ctx := context.Background()
316 serr := errors.New("SendAcks failed")
317 ackChan := make(chan struct{})
318 ds := &ackingDriverSub{
319 q: []*driver.Message{
320 {AckID: 0},
321 {AckID: 1},
322 {AckID: 2},
323 {AckID: 3},
324 },
325 sendAcks: func(context.Context, []driver.AckID) error {
326 close(ackChan)
327 return serr
328 },
329 }
330 sub := pubsub.NewSubscription(ds, nil, nil)
331 defer sub.Shutdown(ctx)
332 m, err := sub.Receive(ctx)
333 if err != nil {
334 t.Fatal(err)
335 }
336 m.Ack()
337 // Wait for the ack to be sent.
338 <-ackChan
339 // It might take a bit longer for the logic after SendAcks returns to happen, so
340 // keep calling Receive.
341 ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
342 defer cancel()
343 for {
344 _, err = sub.Receive(ctx)
345 if gcerrors.Code(err) == gcerrors.Internal && err.(*gcerr.Error).Unwrap() == serr {
346 break // success
347 }
348 if err != nil {
349 t.Fatalf("got %v, want %v", err, serr)
350 }
351 }
352 }
353
354 // callbackDriverSub implements driver.Subscription and allows something like
355 // monkey patching of both its ReceiveBatch and SendAcks methods.
356 type callbackDriverSub struct {
357 driver.Subscription
358 mu sync.Mutex
359 receiveBatch func(context.Context) ([]*driver.Message, error)
360 sendAcks func(context.Context, []driver.AckID) error
361 }
362
363 func (s *callbackDriverSub) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) {
364 return s.receiveBatch(ctx)
365 }
366
367 func (s *callbackDriverSub) SendAcks(ctx context.Context, acks []driver.AckID) error {
368 return s.sendAcks(ctx, acks)
369 }
370
371 func (*callbackDriverSub) IsRetryable(error) bool { return false }
372 func (*callbackDriverSub) ErrorCode(error) gcerrors.ErrorCode { return gcerrors.Internal }
373 func (*callbackDriverSub) CanNack() bool { return false }
374 func (*callbackDriverSub) Close() error { return nil }
375
376 // This test detects the root cause of
377 // https://github.com/google/go-cloud/issues/1238.
378 // If the issue is present, this test times out. The problem was that when
379 // there were no messages available from the driver,
380 // pubsub.Subscription.Receive would spin trying to get more messages without
381 // checking to see if an unrecoverable error had occurred while sending a batch
382 // of acks to the driver.
383 func TestReceiveReturnsAckErrorOnNoMoreMessages(t *testing.T) {
384 // If SendAcks fails, the error is returned via receive.
385 ctx := context.Background()
386 serr := errors.New("unrecoverable error")
387 receiveHappened := make(chan struct{})
388 ackHappened := make(chan struct{})
389 ds := &callbackDriverSub{
390 // First call to receiveBatch will return a single message.
391 receiveBatch: func(context.Context) ([]*driver.Message, error) {
392 ms := []*driver.Message{{AckID: 1}}
393 return ms, nil
394 },
395 sendAcks: func(context.Context, []driver.AckID) error {
396 ackHappened <- struct{}{}
397 return serr
398 },
399 }
400 sub := pubsub.NewSubscription(ds, nil, nil)
401 defer sub.Shutdown(ctx)
402 m, err := sub.Receive(ctx)
403 if err != nil {
404 t.Fatal(err)
405 }
406 m.Ack()
407
408 // Second call to receiveBatch will wait for the pull from the
409 // receiveHappened channel below, and return a nil slice of messages.
410 ds.mu.Lock()
411 ds.receiveBatch = func(context.Context) ([]*driver.Message, error) {
412 ds.mu.Lock()
413 // Subsequent calls to receiveBatch won't wait on receiveHappened,
414 // and will also return nil slices of messages.
415 ds.receiveBatch = func(context.Context) ([]*driver.Message, error) {
416 return nil, nil
417 }
418 ds.mu.Unlock()
419 receiveHappened <- struct{}{}
420 return nil, nil
421 }
422 ds.mu.Unlock()
423
424 errc := make(chan error)
425 go func() {
426 _, err := sub.Receive(ctx)
427 errc <- err
428 }()
429
430 // sub.Receive has to start running first and then we need to trigger the unrecoverable error.
431 <-receiveHappened
432
433 // Trigger the unrecoverable error.
434 <-ackHappened
435
436 // Wait for sub.Receive to return so we can check the error it returns against serr.
437 err = <-errc
438
439 // Check the error returned from sub.Receive.
440 if got := gcerrors.Code(err); got != gcerrors.Internal {
441 t.Fatalf("error code = %v; want %v", got, gcerrors.Internal)
442 }
443 if got := errors.Unwrap(err); got != serr {
444 t.Errorf("error = %v; want %v", got, serr)
445 }
446 }