-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathPublisherImplTest.java
1320 lines (1148 loc) · 50.9 KB
/
PublisherImplTest.java
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2016 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
*
* http://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
* limitations under the License.
*/
package com.google.cloud.pubsub.v1;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.api.core.ApiFuture;
import com.google.api.gax.batching.BatchingSettings;
import com.google.api.gax.batching.FlowControlSettings;
import com.google.api.gax.batching.FlowController;
import com.google.api.gax.core.ExecutorProvider;
import com.google.api.gax.core.FixedExecutorProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.GrpcTransportChannel;
import com.google.api.gax.grpc.testing.LocalChannelProvider;
import com.google.api.gax.rpc.DataLossException;
import com.google.api.gax.rpc.FixedTransportChannelProvider;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.cloud.pubsub.v1.Publisher.Builder;
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.ProjectTopicName;
import com.google.pubsub.v1.PublishRequest;
import com.google.pubsub.v1.PublishResponse;
import com.google.pubsub.v1.PubsubMessage;
import io.grpc.ManagedChannel;
import io.grpc.Server;
import io.grpc.Status;
import io.grpc.StatusException;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.threeten.bp.Duration;
@RunWith(JUnit4.class)
public class PublisherImplTest {
private static final ProjectTopicName TEST_TOPIC =
ProjectTopicName.of("test-project", "test-topic");
private static final ExecutorProvider SINGLE_THREAD_EXECUTOR =
InstantiatingExecutorProvider.newBuilder().setExecutorThreadCount(1).build();
private static final TransportChannelProvider TEST_CHANNEL_PROVIDER =
LocalChannelProvider.create("test-server");
private FakeScheduledExecutorService fakeExecutor;
private FakePublisherServiceImpl testPublisherServiceImpl;
private ManagedChannel testChannel;
private Server testServer;
@Before
public void setUp() throws Exception {
testPublisherServiceImpl = new FakePublisherServiceImpl();
InProcessServerBuilder serverBuilder = InProcessServerBuilder.forName("test-server");
serverBuilder.addService(testPublisherServiceImpl);
testServer = serverBuilder.build();
testChannel = InProcessChannelBuilder.forName("test-server").build();
testServer.start();
fakeExecutor = new FakeScheduledExecutorService();
}
@After
public void tearDown() throws Exception {
testServer.shutdownNow().awaitTermination();
testChannel.shutdown();
}
@Test
public void testPublishByDuration() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
// To demonstrate that reaching duration will trigger publish
.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setDelayThreshold(Duration.ofSeconds(5))
.setElementCountThreshold(10L)
.build())
.build();
testPublisherServiceImpl.addPublishResponse(
PublishResponse.newBuilder().addMessageIds("1").addMessageIds("2"));
ApiFuture<String> publishFuture1 = sendTestMessage(publisher, "A");
ApiFuture<String> publishFuture2 = sendTestMessage(publisher, "B");
assertFalse(publishFuture1.isDone());
assertFalse(publishFuture2.isDone());
fakeExecutor.advanceTime(Duration.ofSeconds(10));
assertEquals("1", publishFuture1.get());
assertEquals("2", publishFuture2.get());
assertEquals(2, testPublisherServiceImpl.getCapturedRequests().get(0).getMessagesCount());
shutdownTestPublisher(publisher);
}
@Test
public void testPublishByNumBatchedMessages() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(2L)
.setDelayThreshold(Duration.ofSeconds(100))
.build())
.build();
testPublisherServiceImpl
.addPublishResponse(PublishResponse.newBuilder().addMessageIds("1").addMessageIds("2"))
.addPublishResponse(PublishResponse.newBuilder().addMessageIds("3").addMessageIds("4"));
ApiFuture<String> publishFuture1 = sendTestMessage(publisher, "A");
ApiFuture<String> publishFuture2 = sendTestMessage(publisher, "B");
ApiFuture<String> publishFuture3 = sendTestMessage(publisher, "C");
// Note we are not advancing time but message should still get published
assertEquals("1", publishFuture1.get());
assertEquals("2", publishFuture2.get());
assertFalse(publishFuture3.isDone());
ApiFuture<String> publishFuture4 = sendTestMessage(publisher, "D");
assertEquals("3", publishFuture3.get());
assertEquals("4", publishFuture4.get());
assertEquals(2, testPublisherServiceImpl.getCapturedRequests().get(0).getMessagesCount());
assertEquals(2, testPublisherServiceImpl.getCapturedRequests().get(1).getMessagesCount());
fakeExecutor.advanceTime(Duration.ofSeconds(100));
shutdownTestPublisher(publisher);
}
@Test
public void testSinglePublishByNumBytes() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(2L)
.setDelayThreshold(Duration.ofSeconds(100))
.build())
.build();
testPublisherServiceImpl
.addPublishResponse(PublishResponse.newBuilder().addMessageIds("1").addMessageIds("2"))
.addPublishResponse(PublishResponse.newBuilder().addMessageIds("3").addMessageIds("4"));
ApiFuture<String> publishFuture1 = sendTestMessage(publisher, "A");
ApiFuture<String> publishFuture2 = sendTestMessage(publisher, "B");
ApiFuture<String> publishFuture3 = sendTestMessage(publisher, "C");
// Note we are not advancing time but message should still get published
assertEquals("1", publishFuture1.get());
assertEquals("2", publishFuture2.get());
assertFalse(publishFuture3.isDone());
ApiFuture<String> publishFuture4 = sendTestMessage(publisher, "D");
assertEquals("3", publishFuture3.get());
assertEquals("4", publishFuture4.get());
assertEquals(2, testPublisherServiceImpl.getCapturedRequests().size());
fakeExecutor.advanceTime(Duration.ofSeconds(100));
shutdownTestPublisher(publisher);
}
@Test
public void testPublishByShutdown() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setDelayThreshold(Duration.ofSeconds(100))
.setElementCountThreshold(10L)
.build())
.build();
testPublisherServiceImpl.addPublishResponse(
PublishResponse.newBuilder().addMessageIds("1").addMessageIds("2"));
ApiFuture<String> publishFuture1 = sendTestMessage(publisher, "A");
ApiFuture<String> publishFuture2 = sendTestMessage(publisher, "B");
// Note we are not advancing time or reaching the count threshold but messages should
// still get published by call to shutdown
publisher.shutdown();
// Verify the publishes completed
assertTrue(publishFuture1.isDone());
assertTrue(publishFuture2.isDone());
assertEquals("1", publishFuture1.get());
assertEquals("2", publishFuture2.get());
fakeExecutor.advanceTime(Duration.ofSeconds(100));
publisher.awaitTermination(1, TimeUnit.MINUTES);
}
@Test
public void testPublishMixedSizeAndDuration() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
// To demonstrate that reaching duration will trigger publish
.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(2L)
.setDelayThreshold(Duration.ofSeconds(5))
.build())
.build();
testPublisherServiceImpl.addPublishResponse(
PublishResponse.newBuilder().addMessageIds("1").addMessageIds("2"));
testPublisherServiceImpl.addPublishResponse(PublishResponse.newBuilder().addMessageIds("3"));
ApiFuture<String> publishFuture1 = sendTestMessage(publisher, "A");
fakeExecutor.advanceTime(Duration.ofSeconds(2));
assertFalse(publishFuture1.isDone());
ApiFuture<String> publishFuture2 = sendTestMessage(publisher, "B");
// Publishing triggered by batch size
assertEquals("1", publishFuture1.get());
assertEquals("2", publishFuture2.get());
ApiFuture<String> publishFuture3 = sendTestMessage(publisher, "C");
assertFalse(publishFuture3.isDone());
// Publishing triggered by time
fakeExecutor.advanceTime(Duration.ofSeconds(5));
assertEquals("3", publishFuture3.get());
assertEquals(2, testPublisherServiceImpl.getCapturedRequests().get(0).getMessagesCount());
assertEquals(1, testPublisherServiceImpl.getCapturedRequests().get(1).getMessagesCount());
shutdownTestPublisher(publisher);
}
@Test
public void testPublishWithCompression() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(2L)
.setDelayThreshold(Duration.ofSeconds(100))
.build())
.setEnableCompression(true)
.setCompressionBytesThreshold(100)
.build();
testPublisherServiceImpl.addPublishResponse(
PublishResponse.newBuilder().addMessageIds("1").addMessageIds("2"));
ApiFuture<String> publishFuture1 = sendTestMessage(publisher, "A");
ApiFuture<String> publishFuture2 = sendTestMessage(publisher, "B");
assertEquals("1", publishFuture1.get());
assertEquals("2", publishFuture2.get());
fakeExecutor.advanceTime(Duration.ofSeconds(100));
shutdownTestPublisher(publisher);
}
private ApiFuture<String> sendTestMessage(Publisher publisher, String data) {
return publisher.publish(
PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8(data)).build());
}
@Test
public void testBatchedMessagesWithOrderingKeyByNum() throws Exception {
// Limit the number of maximum elements in a single batch to 3.
Publisher publisher =
getTestPublisherBuilder()
.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(3L)
.setDelayThreshold(Duration.ofSeconds(100))
.build())
.setEnableMessageOrdering(true)
.build();
testPublisherServiceImpl.setAutoPublishResponse(true);
// Publish two messages with ordering key, "OrderA", and other two messages with "OrderB".
ApiFuture<String> publishFuture1 = sendTestMessageWithOrderingKey(publisher, "m1", "OrderA");
ApiFuture<String> publishFuture2 = sendTestMessageWithOrderingKey(publisher, "m2", "OrderB");
ApiFuture<String> publishFuture3 = sendTestMessageWithOrderingKey(publisher, "m3", "OrderA");
ApiFuture<String> publishFuture4 = sendTestMessageWithOrderingKey(publisher, "m4", "OrderB");
// Verify that none of them were published since the batching size is 3.
assertFalse(publishFuture1.isDone());
assertFalse(publishFuture2.isDone());
assertFalse(publishFuture3.isDone());
assertFalse(publishFuture4.isDone());
// One of the batches reaches the limit.
ApiFuture<String> publishFuture5 = sendTestMessageWithOrderingKey(publisher, "m5", "OrderA");
// Verify that they were delivered in order per ordering key.
assertTrue(Integer.parseInt(publishFuture1.get()) < Integer.parseInt(publishFuture3.get()));
assertTrue(Integer.parseInt(publishFuture3.get()) < Integer.parseInt(publishFuture5.get()));
// The other batch reaches the limit.
ApiFuture<String> publishFuture6 = sendTestMessageWithOrderingKey(publisher, "m6", "OrderB");
assertTrue(Integer.parseInt(publishFuture2.get()) < Integer.parseInt(publishFuture4.get()));
assertTrue(Integer.parseInt(publishFuture4.get()) < Integer.parseInt(publishFuture6.get()));
// Verify that every message within the same batch has the same ordering key.
List<PublishRequest> requests = testPublisherServiceImpl.getCapturedRequests();
for (PublishRequest request : requests) {
if (request.getMessagesCount() > 1) {
String orderingKey = request.getMessages(0).getOrderingKey();
for (PubsubMessage message : request.getMessagesList()) {
assertEquals(message.getOrderingKey(), orderingKey);
}
}
}
fakeExecutor.advanceTime(Duration.ofSeconds(100));
shutdownTestPublisher(publisher);
}
@Test
public void testBatchedMessagesWithOrderingKeyByDuration() throws Exception {
// Limit the batching timeout to 100 seconds.
Publisher publisher =
getTestPublisherBuilder()
.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(10L)
.setDelayThreshold(Duration.ofSeconds(100))
.build())
.setEnableMessageOrdering(true)
.build();
testPublisherServiceImpl.setAutoPublishResponse(true);
testPublisherServiceImpl.setExecutor(fakeExecutor);
testPublisherServiceImpl.setPublishResponseDelay(Duration.ofSeconds(300));
// Publish two messages with ordering key, "OrderA", and other two messages with "OrderB".
ApiFuture<String> publishFuture1 = sendTestMessageWithOrderingKey(publisher, "m1", "OrderA");
ApiFuture<String> publishFuture2 = sendTestMessageWithOrderingKey(publisher, "m2", "OrderB");
ApiFuture<String> publishFuture3 = sendTestMessageWithOrderingKey(publisher, "m3", "OrderA");
ApiFuture<String> publishFuture4 = sendTestMessageWithOrderingKey(publisher, "m4", "OrderB");
// Verify that none of them were published since the batching size is 10 and timeout has not
// been expired.
assertFalse(publishFuture1.isDone());
assertFalse(publishFuture2.isDone());
assertFalse(publishFuture3.isDone());
assertFalse(publishFuture4.isDone());
// The timeout expires.
fakeExecutor.advanceTime(Duration.ofSeconds(100));
// Publish one more message on "OrderA" while publishes are outstanding.
testPublisherServiceImpl.setPublishResponseDelay(Duration.ZERO);
ApiFuture<String> publishFuture5 = sendTestMessageWithOrderingKey(publisher, "m5", "OrderA");
// The second timeout expires.
fakeExecutor.advanceTime(Duration.ofSeconds(100));
// Publishing completes on the first four messages.
fakeExecutor.advanceTime(Duration.ofSeconds(200));
// Verify that they were delivered in order per ordering key.
assertTrue(Integer.parseInt(publishFuture1.get()) < Integer.parseInt(publishFuture3.get()));
assertTrue(Integer.parseInt(publishFuture2.get()) < Integer.parseInt(publishFuture4.get()));
// Verify that they were delivered in order per ordering key.
assertTrue(Integer.parseInt(publishFuture3.get()) < Integer.parseInt(publishFuture5.get()));
// Verify that every message within the same batch has the same ordering key.
List<PublishRequest> requests = testPublisherServiceImpl.getCapturedRequests();
for (PublishRequest request : requests) {
if (request.getMessagesCount() > 1) {
String orderingKey = request.getMessages(0).getOrderingKey();
for (PubsubMessage message : request.getMessagesList()) {
assertEquals(message.getOrderingKey(), orderingKey);
}
}
}
shutdownTestPublisher(publisher);
}
@Test
public void testLargeMessagesDoNotReorderBatches() throws Exception {
// Set the maximum batching size to 20 bytes.
Publisher publisher =
getTestPublisherBuilder()
.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(10L)
.setRequestByteThreshold(20L)
.setDelayThreshold(Duration.ofSeconds(100))
.build())
.setEnableMessageOrdering(true)
.build();
testPublisherServiceImpl.setAutoPublishResponse(true);
ApiFuture<String> publishFuture1 = sendTestMessageWithOrderingKey(publisher, "m1", "OrderA");
ApiFuture<String> publishFuture2 = sendTestMessageWithOrderingKey(publisher, "m2", "OrderB");
assertFalse(publishFuture1.isDone());
assertFalse(publishFuture2.isDone());
ApiFuture<String> publishFuture3 =
sendTestMessageWithOrderingKey(publisher, "VeryLargeMessage", "OrderB");
// Verify that messages with "OrderB" were delivered in order.
assertTrue(Integer.parseInt(publishFuture2.get()) < Integer.parseInt(publishFuture3.get()));
fakeExecutor.advanceTime(Duration.ofSeconds(100));
shutdownTestPublisher(publisher);
}
@Test
public void testOrderingKeyWhenDisabled_throwsException() throws Exception {
// Message ordering is disabled by default.
Publisher publisher = getTestPublisherBuilder().build();
try {
ApiFuture<String> publishFuture = sendTestMessageWithOrderingKey(publisher, "m1", "orderA");
fail("Should have thrown an IllegalStateException");
} catch (IllegalStateException expected) {
// expected
}
shutdownTestPublisher(publisher);
}
@Test
public void testEnableMessageOrdering_overwritesMaxAttempts() throws Exception {
// Set maxAttempts to 1 and enableMessageOrdering to true at the same time.
Publisher publisher =
getTestPublisherBuilder()
.setExecutorProvider(SINGLE_THREAD_EXECUTOR)
.setRetrySettings(
Publisher.Builder.DEFAULT_RETRY_SETTINGS
.toBuilder()
.setTotalTimeout(Duration.ofSeconds(10))
.setMaxAttempts(1)
.build())
.setEnableMessageOrdering(true)
.build();
// Although maxAttempts is 1, the publisher will retry until it succeeds since
// enableMessageOrdering is true.
testPublisherServiceImpl.addPublishError(new Throwable("Transiently failing"));
testPublisherServiceImpl.addPublishError(new Throwable("Transiently failing"));
testPublisherServiceImpl.addPublishError(new Throwable("Transiently failing"));
testPublisherServiceImpl.addPublishResponse(PublishResponse.newBuilder().addMessageIds("1"));
ApiFuture<String> publishFuture1 = sendTestMessageWithOrderingKey(publisher, "m1", "orderA");
assertEquals("1", publishFuture1.get());
assertEquals(4, testPublisherServiceImpl.getCapturedRequests().size());
publisher.shutdown();
assertTrue(publisher.awaitTermination(1, TimeUnit.MINUTES));
}
/**
* Make sure that resume publishing works as expected:
*
* <ol>
* <li>publish with key orderA which returns a failure.
* <li>publish with key orderA again, which should fail immediately
* <li>publish with key orderB, which should succeed
* <li>resume publishing on key orderA
* <li>publish with key orderA, which should now succeed
* </ol>
*/
/*
Temporarily disabled due to https://github.com/googleapis/java-pubsub/issues/1861.
TODO(maitrimangal): Enable once resolved.
@Test
public void testResumePublish() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(2L)
.build())
.setEnableMessageOrdering(true)
.build();
ApiFuture<String> future1 = sendTestMessageWithOrderingKey(publisher, "m1", "orderA");
ApiFuture<String> future2 = sendTestMessageWithOrderingKey(publisher, "m2", "orderA");
fakeExecutor.advanceTime(Duration.ZERO);
assertFalse(future1.isDone());
assertFalse(future2.isDone());
// This exception should stop future publishing to the same key
testPublisherServiceImpl.addPublishError(new StatusException(Status.INVALID_ARGUMENT));
fakeExecutor.advanceTime(Duration.ZERO);
try {
future1.get();
fail("This should fail.");
} catch (ExecutionException e) {
}
try {
future2.get();
fail("This should fail.");
} catch (ExecutionException e) {
}
// Submit new requests with orderA that should fail.
ApiFuture<String> future3 = sendTestMessageWithOrderingKey(publisher, "m3", "orderA");
ApiFuture<String> future4 = sendTestMessageWithOrderingKey(publisher, "m4", "orderA");
try {
future3.get();
fail("This should fail.");
} catch (ExecutionException e) {
assertEquals(SequentialExecutorService.CallbackExecutor.CANCELLATION_EXCEPTION, e.getCause());
}
try {
future4.get();
fail("This should fail.");
} catch (ExecutionException e) {
assertEquals(SequentialExecutorService.CallbackExecutor.CANCELLATION_EXCEPTION, e.getCause());
}
// Submit a new request with orderB, which should succeed
ApiFuture<String> future5 = sendTestMessageWithOrderingKey(publisher, "m5", "orderB");
ApiFuture<String> future6 = sendTestMessageWithOrderingKey(publisher, "m6", "orderB");
testPublisherServiceImpl.addPublishResponse(
PublishResponse.newBuilder().addMessageIds("5").addMessageIds("6"));
Assert.assertEquals("5", future5.get());
Assert.assertEquals("6", future6.get());
// Resume publishing of "orderA", which should now succeed
publisher.resumePublish("orderA");
ApiFuture<String> future7 = sendTestMessageWithOrderingKey(publisher, "m7", "orderA");
ApiFuture<String> future8 = sendTestMessageWithOrderingKey(publisher, "m8", "orderA");
testPublisherServiceImpl.addPublishResponse(
PublishResponse.newBuilder().addMessageIds("7").addMessageIds("8"));
Assert.assertEquals("7", future7.get());
Assert.assertEquals("8", future8.get());
shutdownTestPublisher(publisher);
}
@Test
public void testPublishThrowExceptionForUnsubmittedOrderingKeyMessage() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
.setExecutorProvider(SINGLE_THREAD_EXECUTOR)
.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(2L)
.setDelayThreshold(Duration.ofSeconds(500))
.build())
.setEnableMessageOrdering(true)
.build();
// Send two messages that will fulfill the first batch, which will return a failure.
testPublisherServiceImpl.addPublishError(new StatusException(Status.INVALID_ARGUMENT));
ApiFuture<String> publishFuture1 = sendTestMessageWithOrderingKey(publisher, "A", "a");
ApiFuture<String> publishFuture2 = sendTestMessageWithOrderingKey(publisher, "B", "a");
// A third message will fail because the first attempt to publish failed.
ApiFuture<String> publishFuture3 = sendTestMessageWithOrderingKey(publisher, "C", "a");
try {
publishFuture1.get();
fail("Should have failed.");
} catch (ExecutionException e) {
}
try {
publishFuture2.get();
fail("Should have failed.");
} catch (ExecutionException e) {
}
try {
publishFuture3.get();
fail("Should have failed.");
} catch (ExecutionException e) {
assertEquals(SequentialExecutorService.CallbackExecutor.CANCELLATION_EXCEPTION, e.getCause());
}
// A subsequent attempt fails immediately.
ApiFuture<String> publishFuture4 = sendTestMessageWithOrderingKey(publisher, "D", "a");
try {
publishFuture4.get();
fail("Should have failed.");
} catch (ExecutionException e) {
assertEquals(SequentialExecutorService.CallbackExecutor.CANCELLATION_EXCEPTION, e.getCause());
}
}
*/
private ApiFuture<String> sendTestMessageWithOrderingKey(
Publisher publisher, String data, String orderingKey) {
return publisher.publish(
PubsubMessage.newBuilder()
.setOrderingKey(orderingKey)
.setData(ByteString.copyFromUtf8(data))
.build());
}
@Test
public void testErrorPropagation() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
.setExecutorProvider(SINGLE_THREAD_EXECUTOR)
.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(1L)
.setDelayThreshold(Duration.ofSeconds(5))
.build())
.build();
testPublisherServiceImpl.addPublishError(Status.DATA_LOSS.asException());
try {
sendTestMessage(publisher, "A").get();
fail("should throw exception");
} catch (ExecutionException e) {
assertThat(e.getCause()).isInstanceOf(DataLossException.class);
}
}
@Test
public void testPublishFailureRetries() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
.setExecutorProvider(SINGLE_THREAD_EXECUTOR)
.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(1L)
.setDelayThreshold(Duration.ofSeconds(5))
.build())
.build(); // To demonstrate that reaching duration will trigger publish
testPublisherServiceImpl.addPublishError(new Throwable("Transiently failing"));
testPublisherServiceImpl.addPublishResponse(PublishResponse.newBuilder().addMessageIds("1"));
ApiFuture<String> publishFuture1 = sendTestMessage(publisher, "A");
assertEquals("1", publishFuture1.get());
assertEquals(2, testPublisherServiceImpl.getCapturedRequests().size());
shutdownTestPublisher(publisher);
}
@Test(expected = ExecutionException.class)
public void testPublishFailureRetries_retriesDisabled() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
.setExecutorProvider(SINGLE_THREAD_EXECUTOR)
.setRetrySettings(
Publisher.Builder.DEFAULT_RETRY_SETTINGS
.toBuilder()
.setTotalTimeout(Duration.ofSeconds(10))
.setMaxAttempts(1)
.build())
.build();
testPublisherServiceImpl.addPublishError(new Throwable("Transiently failing"));
ApiFuture<String> publishFuture1 = sendTestMessage(publisher, "A");
try {
publishFuture1.get();
} finally {
assertSame(testPublisherServiceImpl.getCapturedRequests().size(), 1);
shutdownTestPublisher(publisher);
}
}
@Test
public void testPublishFailureRetries_maxRetriesSetup() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
.setExecutorProvider(SINGLE_THREAD_EXECUTOR)
.setRetrySettings(
Publisher.Builder.DEFAULT_RETRY_SETTINGS
.toBuilder()
.setTotalTimeout(Duration.ofSeconds(10))
.setMaxAttempts(3)
.build())
.build();
testPublisherServiceImpl.addPublishError(new Throwable("Transiently failing"));
testPublisherServiceImpl.addPublishError(new Throwable("Transiently failing"));
testPublisherServiceImpl.addPublishResponse(PublishResponse.newBuilder().addMessageIds("1"));
ApiFuture<String> publishFuture1 = sendTestMessage(publisher, "A");
assertEquals("1", publishFuture1.get());
assertEquals(3, testPublisherServiceImpl.getCapturedRequests().size());
shutdownTestPublisher(publisher);
}
@Test
public void testPublishFailureRetries_maxRetriesSetUnlimited() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
.setExecutorProvider(SINGLE_THREAD_EXECUTOR)
.setRetrySettings(
Publisher.Builder.DEFAULT_RETRY_SETTINGS
.toBuilder()
.setTotalTimeout(Duration.ofSeconds(10))
.setMaxAttempts(0)
.build())
.build();
testPublisherServiceImpl.addPublishError(new Throwable("Transiently failing"));
testPublisherServiceImpl.addPublishError(new Throwable("Transiently failing"));
testPublisherServiceImpl.addPublishResponse(PublishResponse.newBuilder().addMessageIds("1"));
ApiFuture<String> publishFuture1 = sendTestMessage(publisher, "A");
assertEquals("1", publishFuture1.get());
assertEquals(3, testPublisherServiceImpl.getCapturedRequests().size());
publisher.shutdown();
assertTrue(publisher.awaitTermination(1, TimeUnit.MINUTES));
}
@Test(expected = ExecutionException.class)
public void testPublishFailureRetries_nonRetryableFailsImmediately() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
.setExecutorProvider(SINGLE_THREAD_EXECUTOR)
.setRetrySettings(
Publisher.Builder.DEFAULT_RETRY_SETTINGS
.toBuilder()
.setTotalTimeout(Duration.ofSeconds(10))
.build())
.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(1L)
.setDelayThreshold(Duration.ofSeconds(5))
.build())
.build(); // To demonstrate that reaching duration will trigger publish
testPublisherServiceImpl.addPublishError(new StatusException(Status.INVALID_ARGUMENT));
ApiFuture<String> publishFuture1 = sendTestMessage(publisher, "A");
try {
publishFuture1.get();
} finally {
assertTrue(testPublisherServiceImpl.getCapturedRequests().size() >= 1);
publisher.shutdown();
assertTrue(publisher.awaitTermination(1, TimeUnit.MINUTES));
}
}
@Test
public void testPublisherGetters() throws Exception {
Publisher.Builder builder = Publisher.newBuilder(TEST_TOPIC);
builder.setChannelProvider(
FixedTransportChannelProvider.create(GrpcTransportChannel.create(testChannel)));
builder.setExecutorProvider(SINGLE_THREAD_EXECUTOR);
builder.setBatchingSettings(
BatchingSettings.newBuilder()
.setRequestByteThreshold(10L)
.setDelayThreshold(Duration.ofMillis(11))
.setElementCountThreshold(12L)
.build());
builder.setCredentialsProvider(NoCredentialsProvider.create());
Publisher publisher = builder.build();
assertEquals(TEST_TOPIC, publisher.getTopicName());
assertEquals(10, (long) publisher.getBatchingSettings().getRequestByteThreshold());
assertEquals(Duration.ofMillis(11), publisher.getBatchingSettings().getDelayThreshold());
assertEquals(12, (long) publisher.getBatchingSettings().getElementCountThreshold());
publisher.shutdown();
assertTrue(publisher.awaitTermination(1, TimeUnit.MINUTES));
}
@Test
public void testBuilderParametersAndDefaults() {
Publisher.Builder builder = Publisher.newBuilder(TEST_TOPIC);
assertEquals(TEST_TOPIC.toString(), builder.topicName);
assertEquals(Publisher.Builder.DEFAULT_EXECUTOR_PROVIDER, builder.executorProvider);
assertEquals(
Publisher.Builder.DEFAULT_REQUEST_BYTES_THRESHOLD,
builder.batchingSettings.getRequestByteThreshold().longValue());
assertEquals(
Publisher.Builder.DEFAULT_DELAY_THRESHOLD, builder.batchingSettings.getDelayThreshold());
assertEquals(
Publisher.Builder.DEFAULT_ELEMENT_COUNT_THRESHOLD,
builder.batchingSettings.getElementCountThreshold().longValue());
assertEquals(Publisher.Builder.DEFAULT_RETRY_SETTINGS, builder.retrySettings);
}
@Test
public void testBuilderInvalidArguments() {
Publisher.Builder builder = Publisher.newBuilder(TEST_TOPIC);
try {
builder.setChannelProvider(null);
fail("Should have thrown an IllegalArgumentException");
} catch (NullPointerException expected) {
// Expected
}
try {
builder.setExecutorProvider(null);
fail("Should have thrown an IllegalArgumentException");
} catch (NullPointerException expected) {
// Expected
}
try {
builder.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setRequestByteThreshold(null)
.build());
fail("Should have thrown an NullPointerException");
} catch (NullPointerException expected) {
// Expected
}
try {
builder.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setRequestByteThreshold(0L)
.build());
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException expected) {
// Expected
}
try {
builder.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setRequestByteThreshold(-1L)
.build());
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException expected) {
// Expected
}
builder.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setDelayThreshold(Duration.ofMillis(1))
.build());
try {
builder.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS.toBuilder().setDelayThreshold(null).build());
fail("Should have thrown an NullPointerException");
} catch (NullPointerException expected) {
// Expected
}
try {
builder.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setDelayThreshold(Duration.ofMillis(-1))
.build());
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException expected) {
// Expected
}
builder.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(1L)
.build());
try {
builder.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(null)
.build());
fail("Should have thrown an NullPointerException");
} catch (NullPointerException expected) {
// Expected
}
try {
builder.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(0L)
.build());
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException expected) {
// Expected
}
try {
builder.setBatchingSettings(
Publisher.Builder.DEFAULT_BATCHING_SETTINGS
.toBuilder()
.setElementCountThreshold(-1L)
.build());
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException expected) {
// Expected
}
builder.setRetrySettings(
Publisher.Builder.DEFAULT_RETRY_SETTINGS
.toBuilder()
.setInitialRpcTimeout(Publisher.Builder.MIN_RPC_TIMEOUT)
.build());
try {
builder.setRetrySettings(
Publisher.Builder.DEFAULT_RETRY_SETTINGS
.toBuilder()
.setInitialRpcTimeout(Publisher.Builder.MIN_RPC_TIMEOUT.minusMillis(1))
.build());
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException expected) {
// Expected
}
builder.setRetrySettings(
Publisher.Builder.DEFAULT_RETRY_SETTINGS
.toBuilder()
.setTotalTimeout(Publisher.Builder.MIN_TOTAL_TIMEOUT)
.build());
try {
builder.setRetrySettings(
Publisher.Builder.DEFAULT_RETRY_SETTINGS
.toBuilder()
.setTotalTimeout(Publisher.Builder.MIN_TOTAL_TIMEOUT.minusMillis(1))
.build());
fail("Should have thrown an IllegalArgumentException");
} catch (IllegalArgumentException expected) {
// Expected
}
}
@Test
public void testPartialBatchingSettings() throws Exception {
Publisher publisher =
getTestPublisherBuilder()
.setBatchingSettings(
Publisher.Builder.getDefaultBatchingSettings()
.toBuilder()
.setRequestByteThreshold(5000L)
.build())
.build();
assertEquals((long) publisher.getBatchingSettings().getRequestByteThreshold(), 5000);
assertEquals(
publisher.getBatchingSettings().getElementCountThreshold(),
Publisher.Builder.DEFAULT_BATCHING_SETTINGS.getElementCountThreshold());