forked from googleapis/google-cloud-go
/
integration_test.go
663 lines (574 loc) · 23 KB
/
integration_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
package pscompat
import (
"context"
"errors"
"fmt"
"strings"
"sync/atomic"
"testing"
"time"
"cloud.google.com/go/internal/testutil"
"cloud.google.com/go/internal/uid"
"cloud.google.com/go/pubsub"
"cloud.google.com/go/pubsublite"
"cloud.google.com/go/pubsublite/internal/test"
"cloud.google.com/go/pubsublite/internal/wire"
"github.com/google/go-cmp/cmp/cmpopts"
"golang.org/x/sync/errgroup"
"google.golang.org/api/option"
vkit "cloud.google.com/go/pubsublite/apiv1"
pb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1"
)
const (
gibi = 1 << 30
defaultTestTimeout = 5 * time.Minute
)
var resourceIDs = uid.NewSpace("go-ps-test", nil)
func initIntegrationTest(t *testing.T) {
if testing.Short() {
t.Skip("Integration tests skipped in short mode")
}
if testutil.ProjID() == "" {
t.Skip("Integration tests skipped. See CONTRIBUTING.md for details")
}
}
func withGRPCHeadersAssertion(t *testing.T, opts ...option.ClientOption) []option.ClientOption {
grpcHeadersEnforcer := &testutil.HeadersEnforcer{
OnFailure: t.Errorf,
Checkers: []*testutil.HeaderChecker{
testutil.XGoogClientHeaderChecker,
},
}
return append(grpcHeadersEnforcer.CallOptions(), opts...)
}
func testOptions(ctx context.Context, t *testing.T, opts ...option.ClientOption) []option.ClientOption {
ts := testutil.TokenSource(ctx, vkit.DefaultAuthScopes()...)
if ts == nil {
t.Skip("Integration tests skipped. See CONTRIBUTING.md for details")
}
return append(withGRPCHeadersAssertion(t, option.WithTokenSource(ts)), opts...)
}
func adminClient(ctx context.Context, t *testing.T, region string, opts ...option.ClientOption) *pubsublite.AdminClient {
opts = testOptions(ctx, t, opts...)
admin, err := pubsublite.NewAdminClient(ctx, region, opts...)
if err != nil {
t.Fatalf("Failed to create admin client: %v", err)
}
return admin
}
func publisherClient(ctx context.Context, t *testing.T, settings PublishSettings, topic wire.TopicPath, opts ...option.ClientOption) *PublisherClient {
opts = testOptions(ctx, t, opts...)
pub, err := NewPublisherClientWithSettings(ctx, topic.String(), settings, opts...)
if err != nil {
t.Fatalf("Failed to create publisher client: %v", err)
}
return pub
}
func subscriberClient(ctx context.Context, t *testing.T, settings ReceiveSettings, subscription wire.SubscriptionPath, opts ...option.ClientOption) *SubscriberClient {
opts = testOptions(ctx, t, opts...)
sub, err := NewSubscriberClientWithSettings(ctx, subscription.String(), settings, opts...)
if err != nil {
t.Fatalf("Failed to create publisher client: %v", err)
}
return sub
}
func initResourcePaths(t *testing.T) (string, wire.TopicPath, wire.SubscriptionPath) {
initIntegrationTest(t)
proj := testutil.ProjID()
zone := test.RandomLiteZone()
region, _ := wire.ZoneToRegion(zone)
resourceID := resourceIDs.New()
topicPath := wire.TopicPath{Project: proj, Zone: zone, TopicID: resourceID}
subscriptionPath := wire.SubscriptionPath{Project: proj, Zone: zone, SubscriptionID: resourceID}
return region, topicPath, subscriptionPath
}
func createTopic(ctx context.Context, t *testing.T, admin *pubsublite.AdminClient, topic wire.TopicPath, partitionCount int) {
topicConfig := pubsublite.TopicConfig{
Name: topic.String(),
PartitionCount: partitionCount,
PublishCapacityMiBPerSec: 4,
SubscribeCapacityMiBPerSec: 8,
PerPartitionBytes: 30 * gibi,
RetentionDuration: 24 * time.Hour,
}
_, err := admin.CreateTopic(ctx, topicConfig)
if err != nil {
t.Fatalf("Failed to create topic %s: %v", topic, err)
} else {
t.Logf("Created topic %s", topic)
}
}
func cleanUpTopic(ctx context.Context, t *testing.T, admin *pubsublite.AdminClient, topic wire.TopicPath) {
if err := admin.DeleteTopic(ctx, topic.String()); err != nil {
t.Errorf("Failed to delete topic %s: %v", topic, err)
} else {
t.Logf("Deleted topic %s", topic)
}
}
func createSubscription(ctx context.Context, t *testing.T, admin *pubsublite.AdminClient, subscription wire.SubscriptionPath, topic wire.TopicPath) {
subConfig := &pubsublite.SubscriptionConfig{
Name: subscription.String(),
Topic: topic.String(),
DeliveryRequirement: pubsublite.DeliverImmediately,
}
_, err := admin.CreateSubscription(ctx, *subConfig)
if err != nil {
t.Fatalf("Failed to create subscription %s: %v", subscription, err)
} else {
t.Logf("Created subscription %s", subscription)
}
}
func cleanUpSubscription(ctx context.Context, t *testing.T, admin *pubsublite.AdminClient, subscription wire.SubscriptionPath) {
if err := admin.DeleteSubscription(ctx, subscription.String()); err != nil {
t.Errorf("Failed to delete subscription %s: %v", subscription, err)
} else {
t.Logf("Deleted subscription %s", subscription)
}
}
func partitionNumbers(partitionCount int) []int {
var partitions []int
for i := 0; i < partitionCount; i++ {
partitions = append(partitions, i)
}
return partitions
}
func publishMessages(t *testing.T, settings PublishSettings, topic wire.TopicPath, msgs ...*pubsub.Message) {
ctx := context.Background()
publisher := publisherClient(ctx, t, settings, topic)
defer publisher.Stop()
var pubResults []*pubsub.PublishResult
for _, msg := range msgs {
pubResults = append(pubResults, publisher.Publish(ctx, msg))
}
waitForPublishResults(t, pubResults)
}
func publishPrefixedMessages(t *testing.T, settings PublishSettings, topic wire.TopicPath, msgPrefix string, messageCount int) []string {
ctx := context.Background()
publisher := publisherClient(ctx, t, settings, topic)
defer publisher.Stop()
orderingSender := test.NewOrderingSender()
var pubResults []*pubsub.PublishResult
var msgs []string
for i := 0; i < messageCount; i++ {
data := orderingSender.Next(msgPrefix)
msgs = append(msgs, data)
pubResults = append(pubResults, publisher.Publish(ctx, &pubsub.Message{Data: []byte(data)}))
}
waitForPublishResults(t, pubResults)
return msgs
}
func waitForPublishResults(t *testing.T, pubResults []*pubsub.PublishResult) {
cctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
for i, result := range pubResults {
_, err := result.Get(cctx)
if err != nil {
t.Errorf("Publish(%d) got err: %v", i, err)
}
}
t.Logf("Published %d messages", len(pubResults))
cancel()
}
const maxPrintMsgLen = 70
func truncateMsg(msg string) string {
if len(msg) > maxPrintMsgLen {
return fmt.Sprintf("%s...", msg[0:maxPrintMsgLen])
}
return msg
}
func messageDiff(got, want *pubsub.Message) string {
return testutil.Diff(got, want, cmpopts.IgnoreUnexported(pubsub.Message{}), cmpopts.IgnoreFields(pubsub.Message{}, "ID", "PublishTime"), cmpopts.EquateEmpty())
}
type checkOrdering bool
func receiveAllMessages(t *testing.T, msgTracker *test.MsgTracker, settings ReceiveSettings, subscription wire.SubscriptionPath, checkOrder checkOrdering) {
cctx, stopSubscriber := context.WithTimeout(context.Background(), defaultTestTimeout)
orderingValidator := test.NewOrderingReceiver()
messageReceiver := func(ctx context.Context, msg *pubsub.Message) {
msg.Ack()
data := string(msg.Data)
if !msgTracker.Remove(data) {
// Prevent a flood of errors if a message for a previous test was found.
t.Fatalf("Received unexpected message: %q", truncateMsg(data))
return
}
if checkOrder {
if err := orderingValidator.Receive(data, msg.OrderingKey); err != nil {
t.Errorf("Received unordered message: %q", truncateMsg(data))
}
}
if msgTracker.Empty() {
stopSubscriber() // Stop the subscriber when all messages have been received
}
}
subscriber := subscriberClient(cctx, t, settings, subscription)
if err := subscriber.Receive(cctx, messageReceiver); err != nil {
t.Errorf("Receive() got err: %v", err)
}
if err := msgTracker.Status(); err != nil {
t.Error(err)
}
}
func receiveAndVerifyMessage(t *testing.T, want *pubsub.Message, settings ReceiveSettings, subscription wire.SubscriptionPath) {
cctx, stopSubscriber := context.WithTimeout(context.Background(), defaultTestTimeout)
messageReceiver := func(ctx context.Context, got *pubsub.Message) {
got.Ack()
stopSubscriber()
if diff := messageDiff(got, want); diff != "" {
t.Errorf("Received message got: -, want: +\n%s", diff)
}
if len(got.ID) == 0 {
t.Error("Received message missing ID")
}
if got.PublishTime.IsZero() {
t.Error("Received message missing PublishTime")
}
}
subscriber := subscriberClient(cctx, t, settings, subscription)
if err := subscriber.Receive(cctx, messageReceiver); err != nil {
t.Errorf("Receive() got err: %v", err)
}
}
func TestIntegration_PublishSubscribeSinglePartition(t *testing.T) {
region, topicPath, subscriptionPath := initResourcePaths(t)
ctx := context.Background()
const partitionCount = 1
recvSettings := DefaultReceiveSettings
recvSettings.Partitions = partitionNumbers(partitionCount)
admin := adminClient(ctx, t, region)
defer admin.Close()
createTopic(ctx, t, admin, topicPath, partitionCount)
defer cleanUpTopic(ctx, t, admin, topicPath)
createSubscription(ctx, t, admin, subscriptionPath, topicPath)
defer cleanUpSubscription(ctx, t, admin, subscriptionPath)
// The same topic and subscription resources are used for each subtest. This
// implicitly verifies commits. If cursors are not successfully committed at
// the end of each test, the next test will receive an incorrect message and
// fail. The subtests can also be run independently.
// Sets all fields for a message and ensures it is correctly received.
t.Run("AllFieldsRoundTrip", func(t *testing.T) {
msg := &pubsub.Message{
Data: []byte("round_trip"),
OrderingKey: "ordering_key",
Attributes: map[string]string{
"attr1": "value1",
"attr2": "value2",
},
}
publishMessages(t, DefaultPublishSettings, topicPath, msg)
receiveAndVerifyMessage(t, msg, recvSettings, subscriptionPath)
})
// Verifies custom message transformers.
t.Run("CustomMessageTransformers", func(t *testing.T) {
customPubSettings := DefaultPublishSettings
customPubSettings.MessageTransformer = func(from *pubsub.Message, to *pb.PubSubMessage) error {
to.Data = []byte(string(from.Data) + "_foo")
to.Key = []byte(from.OrderingKey + "_foo")
return nil
}
msg := &pubsub.Message{
Data: []byte("msg_transformers"),
OrderingKey: "ordering_key",
Attributes: map[string]string{
"attr1": "value1",
},
}
publishMessages(t, customPubSettings, topicPath, msg)
customRecvSettings := recvSettings
customRecvSettings.MessageTransformer = func(wireMsg *pb.SequencedMessage, msg *pubsub.Message) error {
// Swaps data and key.
msg.Data = wireMsg.GetMessage().GetKey()
msg.OrderingKey = string(wireMsg.GetMessage().GetData())
msg.ID = "FAKE_ID"
msg.PublishTime = time.Now()
return nil
}
want := &pubsub.Message{
Data: []byte("ordering_key_foo"),
OrderingKey: "msg_transformers_foo",
}
receiveAndVerifyMessage(t, want, customRecvSettings, subscriptionPath)
})
// Verifies that nacks are correctly handled.
t.Run("Nack", func(t *testing.T) {
msg1 := &pubsub.Message{Data: []byte("nack_msg1")}
msg2 := &pubsub.Message{Data: []byte("nack_msg2")}
publishMessages(t, DefaultPublishSettings, topicPath, msg1, msg2)
// Case A: Default nack handler. Terminates subscriber.
cctx, _ := context.WithTimeout(context.Background(), defaultTestTimeout)
messageReceiver1 := func(ctx context.Context, got *pubsub.Message) {
if diff := messageDiff(got, msg1); diff != "" {
t.Errorf("Received message got: -, want: +\n%s", diff)
}
got.Nack()
}
subscriber := subscriberClient(cctx, t, recvSettings, subscriptionPath)
if gotErr := subscriber.Receive(cctx, messageReceiver1); !test.ErrorEqual(gotErr, errNackCalled) {
t.Errorf("Receive() got err: (%v), want err: (%v)", gotErr, errNackCalled)
}
// Case B: Custom nack handler.
errCustomNack := errors.New("message nacked")
customSettings := recvSettings
customSettings.NackHandler = func(msg *pubsub.Message) error {
if string(msg.Data) == "nack_msg1" {
return nil // Causes msg1 to be acked
}
if string(msg.Data) == "nack_msg2" {
return errCustomNack // Terminates subscriber
}
return fmt.Errorf("Received unexpected message: %q", truncateMsg(string(msg.Data)))
}
subscriber = subscriberClient(cctx, t, customSettings, subscriptionPath)
messageReceiver2 := func(ctx context.Context, got *pubsub.Message) {
got.Nack()
}
if gotErr := subscriber.Receive(cctx, messageReceiver2); !test.ErrorEqual(gotErr, errCustomNack) {
t.Errorf("Receive() got err: (%v), want err: (%v)", gotErr, errCustomNack)
}
// Finally: receive and ack msg2.
receiveAndVerifyMessage(t, msg2, recvSettings, subscriptionPath)
})
// Verifies that SubscriberClient.Receive() can be invoked multiple times
// serially (note: parallel would error).
t.Run("SubscriberMultipleReceive", func(t *testing.T) {
msgs := []*pubsub.Message{
{Data: []byte("multiple_receive1")},
{Data: []byte("multiple_receive2")},
{Data: []byte("multiple_receive3")},
}
publishMessages(t, DefaultPublishSettings, topicPath, msgs...)
var cctx context.Context
var stopSubscriber context.CancelFunc
var gotReceivedCount int32
messageReceiver := func(ctx context.Context, got *pubsub.Message) {
currentIdx := atomic.AddInt32(&gotReceivedCount, 1) - 1
if diff := messageDiff(got, msgs[currentIdx]); diff != "" {
t.Errorf("Received message got: -, want: +\n%s", diff)
}
got.Ack()
stopSubscriber()
}
subscriber := subscriberClient(cctx, t, recvSettings, subscriptionPath)
// The message receiver stops the subscriber after receiving the first
// message. However, the subscriber isn't guaranteed to immediately stop, so
// allow up to `len(msgs)` iterations.
wantReceivedCount := len(msgs)
for i := 0; i < wantReceivedCount; i++ {
// New cctx must be created for each iteration as it is cancelled each
// time stopSubscriber is called.
cctx, stopSubscriber = context.WithTimeout(context.Background(), defaultTestTimeout)
if err := subscriber.Receive(cctx, messageReceiver); err != nil {
t.Errorf("Receive() got err: %v", err)
}
if int(gotReceivedCount) == wantReceivedCount {
t.Logf("Received %d messages in %d iterations", gotReceivedCount, i+1)
break
}
}
if int(gotReceivedCount) != wantReceivedCount {
t.Errorf("Received message count: got %d, want %d", gotReceivedCount, wantReceivedCount)
}
})
// Verifies that a blocking message receiver is notified of shutdown.
t.Run("BlockingMessageReceiver", func(t *testing.T) {
msg := &pubsub.Message{
Data: []byte("blocking_message_receiver"),
}
publishMessages(t, DefaultPublishSettings, topicPath, msg)
cctx, stopSubscriber := context.WithTimeout(context.Background(), defaultSubscriberTestTimeout)
messageReceiver := func(ctx context.Context, got *pubsub.Message) {
if diff := messageDiff(got, msg); diff != "" {
t.Errorf("Received message got: -, want: +\n%s", diff)
}
// Ensure the test is deterministic. Wait until the message is received,
// then stop the subscriber, which would cause `ctx` to be done below.
stopSubscriber()
select {
case <-time.After(defaultSubscriberTestTimeout):
t.Errorf("MessageReceiverFunc context not closed within %v", defaultSubscriberTestTimeout)
case <-ctx.Done():
}
// The commit offset for this ack should be processed since the subscriber
// is not shut down due to fatal error. Not actually detected until the
// next test, which would receive an incorrect message.
got.Ack()
}
subscriber := subscriberClient(cctx, t, recvSettings, subscriptionPath)
if err := subscriber.Receive(cctx, messageReceiver); err != nil {
t.Errorf("Receive() got err: %v", err)
}
})
// Checks that messages are published and received in order.
t.Run("Ordering", func(t *testing.T) {
const messageCount = 500
const publishBatchSize = 10
// Publish messages.
pubSettings := DefaultPublishSettings
pubSettings.CountThreshold = publishBatchSize
pubSettings.DelayThreshold = 100 * time.Millisecond
msgs := publishPrefixedMessages(t, pubSettings, topicPath, "ordering", messageCount)
// Receive messages.
msgTracker := test.NewMsgTracker()
msgTracker.Add(msgs...)
receiveAllMessages(t, msgTracker, recvSettings, subscriptionPath, checkOrdering(true))
})
// Checks that subscriber flow control works.
t.Run("SubscriberFlowControl", func(t *testing.T) {
const messageCount = 20
const maxOutstandingMessages = 2 // Receive small batches of messages
// Publish messages.
msgs := publishPrefixedMessages(t, DefaultPublishSettings, topicPath, "subscriber_flow_control", messageCount)
// Receive messages.
msgTracker := test.NewMsgTracker()
msgTracker.Add(msgs...)
customSettings := recvSettings
customSettings.MaxOutstandingMessages = maxOutstandingMessages
receiveAllMessages(t, msgTracker, customSettings, subscriptionPath, checkOrdering(true))
})
// Verifies that large messages can be sent and received.
t.Run("LargeMessages", func(t *testing.T) {
const messageCount = 3
const messageLen = MaxPublishRequestBytes - 50
// Publish messages.
msgTracker := test.NewMsgTracker()
var msgs []*pubsub.Message
for i := 0; i < messageCount; i++ {
data := strings.Repeat(fmt.Sprintf("%d", i), messageLen)
msgTracker.Add(data)
msgs = append(msgs, &pubsub.Message{Data: []byte(data)})
}
publishMessages(t, DefaultPublishSettings, topicPath, msgs...)
// Receive messages.
receiveAllMessages(t, msgTracker, recvSettings, subscriptionPath, checkOrdering(false))
})
}
func TestIntegration_PublishSubscribeMultiPartition(t *testing.T) {
const partitionCount = 3
region, topicPath, subscriptionPath := initResourcePaths(t)
ctx := context.Background()
recvSettings := DefaultReceiveSettings
recvSettings.Partitions = partitionNumbers(partitionCount)
admin := adminClient(ctx, t, region)
defer admin.Close()
createTopic(ctx, t, admin, topicPath, partitionCount)
defer cleanUpTopic(ctx, t, admin, topicPath)
createSubscription(ctx, t, admin, subscriptionPath, topicPath)
defer cleanUpSubscription(ctx, t, admin, subscriptionPath)
// The same topic and subscription resources are used for each subtest. This
// implicitly verifies commits. If cursors are not successfully committed at
// the end of each test, the next test will receive an incorrect message and
// fail. The subtests can also be run independently.
// Tests messages published without ordering key.
t.Run("PublishRoutingNoKey", func(t *testing.T) {
const messageCount = 50 * partitionCount
// Publish messages.
msgs := publishPrefixedMessages(t, DefaultPublishSettings, topicPath, "routing_no_key", messageCount)
// Receive messages, not checking for ordering since they do not have a key.
// However, they would still be ordered within their partition.
msgTracker := test.NewMsgTracker()
msgTracker.Add(msgs...)
receiveAllMessages(t, msgTracker, recvSettings, subscriptionPath, checkOrdering(false))
})
// Tests messages published with ordering key.
t.Run("PublishRoutingWithKey", func(t *testing.T) {
const messageCountPerPartition = 100
const publishBatchSize = 5 // Verifies ordering of batches
// Publish messages.
orderingSender := test.NewOrderingSender()
msgTracker := test.NewMsgTracker()
var msgs []*pubsub.Message
for partition := 0; partition < partitionCount; partition++ {
for i := 0; i < messageCountPerPartition; i++ {
data := orderingSender.Next("routing_with_key")
msgTracker.Add(data)
msg := &pubsub.Message{
Data: []byte(data),
OrderingKey: fmt.Sprintf("p%d", partition),
}
msgs = append(msgs, msg)
}
}
pubSettings := DefaultPublishSettings
pubSettings.CountThreshold = publishBatchSize
publishMessages(t, pubSettings, topicPath, msgs...)
// Receive messages.
receiveAllMessages(t, msgTracker, recvSettings, subscriptionPath, checkOrdering(true))
})
// Verifies usage of the partition assignment service.
t.Run("PartitionAssignment", func(t *testing.T) {
const messageCount = 100
const subscriberCount = 2 // Should be between [2, partitionCount]
// Publish messages.
msgs := publishPrefixedMessages(t, DefaultPublishSettings, topicPath, "partition_assignment", messageCount)
// Start multiple subscribers that use partition assignment.
msgTracker := test.NewMsgTracker()
msgTracker.Add(msgs...)
messageReceiver := func(ctx context.Context, msg *pubsub.Message) {
msg.Ack()
data := string(msg.Data)
if !msgTracker.Remove(data) {
t.Errorf("Received unexpected message: %q", truncateMsg(data))
}
}
cctx, stopSubscribers := context.WithTimeout(context.Background(), defaultTestTimeout)
g, _ := errgroup.WithContext(ctx)
for i := 0; i < subscriberCount; i++ {
// Subscribers must be started in a goroutine as Receive() blocks.
g.Go(func() error {
subscriber := subscriberClient(cctx, t, DefaultReceiveSettings, subscriptionPath)
err := subscriber.Receive(cctx, messageReceiver)
if err != nil {
t.Errorf("Receive() got err: %v", err)
}
return err
})
}
// Wait until all messages have been received.
msgTracker.Wait(defaultTestTimeout)
stopSubscribers()
// Wait until all subscribers have terminated.
g.Wait()
})
}
func TestIntegration_SubscribeFanOut(t *testing.T) {
// Creates multiple subscriptions for the same topic and ensures that each
// subscription receives the published messages. This must be a standalone
// test as the subscribers should not read from backlog.
const subscriberCount = 3
const partitionCount = 1
const messageCount = 100
region, topicPath, baseSubscriptionPath := initResourcePaths(t)
ctx := context.Background()
admin := adminClient(ctx, t, region)
defer admin.Close()
createTopic(ctx, t, admin, topicPath, partitionCount)
defer cleanUpTopic(ctx, t, admin, topicPath)
var subscriptionPaths []wire.SubscriptionPath
for i := 0; i < subscriberCount; i++ {
subscription := baseSubscriptionPath
subscription.SubscriptionID += fmt.Sprintf("%s-%d", baseSubscriptionPath.SubscriptionID, i)
subscriptionPaths = append(subscriptionPaths, subscription)
createSubscription(ctx, t, admin, subscription, topicPath)
defer cleanUpSubscription(ctx, t, admin, subscription)
}
// Publish messages.
msgs := publishPrefixedMessages(t, DefaultPublishSettings, topicPath, "fan_out", messageCount)
// Receive messages from multiple subscriptions.
recvSettings := DefaultReceiveSettings
recvSettings.Partitions = partitionNumbers(partitionCount)
for _, subscription := range subscriptionPaths {
msgTracker := test.NewMsgTracker()
msgTracker.Add(msgs...)
receiveAllMessages(t, msgTracker, recvSettings, subscription, checkOrdering(partitionCount == 1))
}
}