/
StreamWriterTest.java
1478 lines (1322 loc) · 61.1 KB
/
StreamWriterTest.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 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
* limitations under the License.
*/
package com.google.cloud.bigquery.storage.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.assertThrows;
import static org.junit.Assert.assertTrue;
import com.google.api.client.util.Sleeper;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.api.gax.batching.FlowController;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.api.gax.grpc.testing.MockServiceHelper;
import com.google.api.gax.rpc.AbortedException;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.api.gax.rpc.StatusCode.Code;
import com.google.api.gax.rpc.UnknownException;
import com.google.cloud.bigquery.storage.test.Test.FooType;
import com.google.cloud.bigquery.storage.v1.ConnectionWorkerPool.Settings;
import com.google.cloud.bigquery.storage.v1.StorageError.StorageErrorCode;
import com.google.cloud.bigquery.storage.v1.StreamWriter.SingleConnectionOrConnectionPool.Kind;
import com.google.common.base.Strings;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.protobuf.Any;
import com.google.protobuf.DescriptorProtos;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Descriptors.DescriptorValidationException;
import com.google.protobuf.Int64Value;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.threeten.bp.Duration;
@RunWith(JUnit4.class)
public class StreamWriterTest {
private static final Logger log = Logger.getLogger(StreamWriterTest.class.getName());
private static final String TEST_STREAM_1 = "projects/p/datasets/d1/tables/t1/streams/_default";
private static final String TEST_STREAM_2 = "projects/p/datasets/d2/tables/t2/streams/_default";
private static final String TEST_STREAM_3 = "projects/p/datasets/d3/tables/t3/streams/_default";
private static final String TEST_STREAM_SHORTEN = "projects/p/datasets/d2/tables/t2/_default";
private static final String EXPLICIT_STEAM = "projects/p/datasets/d1/tables/t1/streams/s1";
private static final String TEST_TRACE_ID = "DATAFLOW:job_id";
private FakeScheduledExecutorService fakeExecutor;
private FakeBigQueryWrite testBigQueryWrite;
private static MockServiceHelper serviceHelper;
private BigQueryWriteClient client;
private final TableFieldSchema FOO =
TableFieldSchema.newBuilder()
.setType(TableFieldSchema.Type.STRING)
.setMode(TableFieldSchema.Mode.NULLABLE)
.setName("foo")
.build();
private final TableFieldSchema BAR =
TableFieldSchema.newBuilder()
.setType(TableFieldSchema.Type.STRING)
.setMode(TableFieldSchema.Mode.NULLABLE)
.setName("bar")
.build();
private final TableSchema TABLE_SCHEMA = TableSchema.newBuilder().addFields(0, FOO).build();
private final ProtoSchema PROTO_SCHEMA =
ProtoSchemaConverter.convert(
BQTableSchemaToProtoDescriptor.convertBQTableSchemaToProtoDescriptor(TABLE_SCHEMA));
private final TableSchema UPDATED_TABLE_SCHEMA =
TableSchema.newBuilder().addFields(0, FOO).addFields(1, BAR).build();
private final ProtoSchema UPDATED_PROTO_SCHEMA =
ProtoSchemaConverter.convert(
BQTableSchemaToProtoDescriptor.convertBQTableSchemaToProtoDescriptor(
UPDATED_TABLE_SCHEMA));
public StreamWriterTest() throws DescriptorValidationException {}
@Before
public void setUp() throws Exception {
testBigQueryWrite = new FakeBigQueryWrite();
StreamWriter.setMaxRequestCallbackWaitTime(java.time.Duration.ofSeconds(10000));
ConnectionWorker.setMaxInflightQueueWaitTime(300000);
serviceHelper =
new MockServiceHelper(
UUID.randomUUID().toString(), Arrays.<MockGrpcService>asList(testBigQueryWrite));
serviceHelper.start();
fakeExecutor = new FakeScheduledExecutorService();
testBigQueryWrite.setExecutor(fakeExecutor);
client =
BigQueryWriteClient.create(
BigQueryWriteSettings.newBuilder()
.setCredentialsProvider(NoCredentialsProvider.create())
.setTransportChannelProvider(serviceHelper.createChannelProvider())
.build());
StreamWriter.cleanUp();
}
@After
public void tearDown() throws Exception {
log.info("tearDown called");
client.close();
serviceHelper.stop();
StreamWriter.cleanUp();
}
private StreamWriter getMultiplexingTestStreamWriter() throws IOException {
return StreamWriter.newBuilder(TEST_STREAM_1, client)
.setWriterSchema(createProtoSchema())
.setTraceId(TEST_TRACE_ID)
.setLocation("US")
.setEnableConnectionPool(true)
.setMaxRetryDuration(java.time.Duration.ofSeconds(5))
.build();
}
private StreamWriter getTestStreamWriter() throws IOException {
return StreamWriter.newBuilder(TEST_STREAM_1, client)
.setWriterSchema(createProtoSchema())
.setTraceId(TEST_TRACE_ID)
.setMaxRetryDuration(java.time.Duration.ofSeconds(5))
.build();
}
private ProtoSchema createProtoSchema() {
return createProtoSchema("foo");
}
private ProtoSchema createProtoSchema(String fieldName) {
return ProtoSchema.newBuilder()
.setProtoDescriptor(
DescriptorProtos.DescriptorProto.newBuilder()
.setName("Message")
.addField(
DescriptorProtos.FieldDescriptorProto.newBuilder()
.setName(fieldName)
.setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_STRING)
.setNumber(1)
.build())
.build())
.build();
}
private ProtoRows createProtoRows(String[] messages) {
ProtoRows.Builder rowsBuilder = ProtoRows.newBuilder();
for (String message : messages) {
FooType foo = FooType.newBuilder().setFoo(message).build();
rowsBuilder.addSerializedRows(foo.toByteString());
}
return rowsBuilder.build();
}
private AppendRowsResponse createAppendResponse(long offset) {
return AppendRowsResponse.newBuilder()
.setAppendResult(
AppendRowsResponse.AppendResult.newBuilder().setOffset(Int64Value.of(offset)).build())
.build();
}
private AppendRowsResponse createAppendResponseWithError(Status.Code code, String message) {
return AppendRowsResponse.newBuilder()
.setError(com.google.rpc.Status.newBuilder().setCode(code.value()).setMessage(message))
.build();
}
private ApiFuture<AppendRowsResponse> sendTestMessage(StreamWriter writer, String[] messages) {
return writer.append(createProtoRows(messages));
}
private ApiFuture<AppendRowsResponse> sendTestMessage(
StreamWriter writer, String[] messages, long offset) {
return writer.append(createProtoRows(messages), offset);
}
private static <T extends Throwable> T assertFutureException(
Class<T> expectedThrowable, final Future<?> future) {
return assertThrows(
expectedThrowable,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
try {
future.get();
} catch (ExecutionException ex) {
// Future wraps exception with ExecutionException. So unwrapper it here.
throw ex.getCause();
}
}
});
}
private void verifyAppendIsBlocked(final StreamWriter writer) throws Exception {
Thread appendThread =
new Thread(
new Runnable() {
@Override
public void run() {
sendTestMessage(writer, new String[] {"A"});
}
});
// Start a separate thread to append and verify that it is still alive after 2 seoncds.
appendThread.start();
TimeUnit.SECONDS.sleep(2);
assertTrue(appendThread.isAlive());
appendThread.interrupt();
}
private void verifyAppendRequests(long appendCount) {
assertEquals(appendCount, testBigQueryWrite.getAppendRequests().size());
for (int i = 0; i < appendCount; i++) {
AppendRowsRequest serverRequest = testBigQueryWrite.getAppendRequests().get(i);
assertTrue(serverRequest.getProtoRows().getRows().getSerializedRowsCount() > 0);
assertEquals(i, serverRequest.getOffset().getValue());
if (i == 0) {
// First request received by server should have schema and stream name.
assertTrue(serverRequest.getProtoRows().hasWriterSchema());
assertEquals(serverRequest.getWriteStream(), TEST_STREAM_1);
assertEquals(serverRequest.getTraceId(), TEST_TRACE_ID);
} else {
// Following request should not have schema and stream name.
assertFalse(serverRequest.getProtoRows().hasWriterSchema());
assertEquals(serverRequest.getWriteStream(), "");
assertEquals(serverRequest.getTraceId(), "");
}
}
}
public void testBuildBigQueryWriteClientInWriter() throws Exception {
StreamWriter writer =
StreamWriter.newBuilder(TEST_STREAM_1)
.setCredentialsProvider(NoCredentialsProvider.create())
.setChannelProvider(serviceHelper.createChannelProvider())
.setWriterSchema(createProtoSchema())
.build();
testBigQueryWrite.addResponse(createAppendResponse(0));
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
writer.close();
}
@Test
public void testAppendSuccess() throws Exception {
StreamWriter writer = getTestStreamWriter();
long appendCount = 100;
for (int i = 0; i < appendCount; i++) {
testBigQueryWrite.addResponse(createAppendResponse(i));
}
List<ApiFuture<AppendRowsResponse>> futures = new ArrayList<>();
for (int i = 0; i < appendCount; i++) {
futures.add(writer.append(createProtoRows(new String[] {String.valueOf(i)}), i));
}
for (int i = 0; i < appendCount; i++) {
assertEquals(i, futures.get(i).get().getAppendResult().getOffset().getValue());
}
verifyAppendRequests(appendCount);
writer.close();
}
@Test
public void testAppendSuccess_RetryDirectlyInCallback() throws Exception {
// Set a relatively small in flight request counts.
StreamWriter writer =
StreamWriter.newBuilder(TEST_STREAM_1, client)
.setWriterSchema(createProtoSchema())
.setTraceId(TEST_TRACE_ID)
.setMaxRetryDuration(java.time.Duration.ofSeconds(5))
.setMaxInflightRequests(5)
.build();
// Fail the first request, in the request callback of the first request we will insert another
// 10 requests. Those requests can't be processed until the previous request callback has
// been finished.
long appendCount = 20;
for (int i = 0; i < appendCount; i++) {
if (i == 0) {
testBigQueryWrite.addResponse(
createAppendResponseWithError(Status.INVALID_ARGUMENT.getCode(), "test message"));
}
testBigQueryWrite.addResponse(createAppendResponse(i));
}
// We will trigger 10 more requests in the request callback of the following request.
ProtoRows protoRows = createProtoRows(new String[] {String.valueOf(-1)});
ApiFuture<AppendRowsResponse> future = writer.append(protoRows, -1);
ApiFutures.addCallback(
future, new AppendCompleteCallback(writer, protoRows), MoreExecutors.directExecutor());
StatusRuntimeException actualError =
assertFutureException(StatusRuntimeException.class, future);
Sleeper.DEFAULT.sleep(1000);
writer.close();
}
static class AppendCompleteCallback implements ApiFutureCallback<AppendRowsResponse> {
private final StreamWriter mainStreamWriter;
private final ProtoRows protoRows;
private int retryCount = 0;
public AppendCompleteCallback(StreamWriter mainStreamWriter, ProtoRows protoRows) {
this.mainStreamWriter = mainStreamWriter;
this.protoRows = protoRows;
}
public void onSuccess(AppendRowsResponse response) {
// Donothing
}
public void onFailure(Throwable throwable) {
for (int i = 0; i < 10; i++) {
this.mainStreamWriter.append(protoRows);
}
}
}
@Test
public void testUpdatedSchemaFetch_multiplexing() throws Exception {
testUpdatedSchemaFetch(/*enableMultiplexing=*/ true);
}
@Test
public void testUpdatedSchemaFetch_nonMultiplexing() throws Exception {
testUpdatedSchemaFetch(/*enableMultiplexing=*/ false);
}
private void testUpdatedSchemaFetch(boolean enableMultiplexing)
throws IOException, ExecutionException, InterruptedException {
StreamWriter writer =
StreamWriter.newBuilder(TEST_STREAM_1)
.setCredentialsProvider(NoCredentialsProvider.create())
.setChannelProvider(serviceHelper.createChannelProvider())
.setWriterSchema(PROTO_SCHEMA)
.setEnableConnectionPool(enableMultiplexing)
.setLocation("us")
.build();
testBigQueryWrite.addResponse(
AppendRowsResponse.newBuilder()
.setAppendResult(
AppendRowsResponse.AppendResult.newBuilder().setOffset(Int64Value.of(0)).build())
.setUpdatedSchema(UPDATED_TABLE_SCHEMA)
.setWriteStream(TEST_STREAM_1)
.build());
assertEquals(writer.getUpdatedSchema(), null);
AppendRowsResponse response =
writer.append(createProtoRows(new String[] {String.valueOf(0)}), 0).get();
assertEquals(writer.getUpdatedSchema(), UPDATED_TABLE_SCHEMA);
// Create another writer, although it's the same stream name but the time stamp is newer, thus
// the old updated schema won't get returned.
StreamWriter writer2 =
StreamWriter.newBuilder(TEST_STREAM_1)
.setCredentialsProvider(NoCredentialsProvider.create())
.setChannelProvider(serviceHelper.createChannelProvider())
.setWriterSchema(PROTO_SCHEMA)
.setEnableConnectionPool(enableMultiplexing)
.setLocation("us")
.build();
assertEquals(writer2.getUpdatedSchema(), null);
}
@Test
public void testNoSchema() throws Exception {
StatusRuntimeException ex =
assertThrows(
StatusRuntimeException.class,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
StreamWriter.newBuilder(TEST_STREAM_1, client).build();
}
});
assertEquals(ex.getStatus().getCode(), Status.INVALID_ARGUMENT.getCode());
assertTrue(ex.getStatus().getDescription().contains("Writer schema must be provided"));
}
@Test
public void testInvalidTraceId() throws Exception {
assertThrows(
IllegalArgumentException.class,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
StreamWriter.newBuilder(TEST_STREAM_1).setTraceId("abc");
}
});
assertThrows(
IllegalArgumentException.class,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
StreamWriter.newBuilder(TEST_STREAM_1).setTraceId("abc:");
}
});
assertThrows(
IllegalArgumentException.class,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
StreamWriter.newBuilder(TEST_STREAM_1).setTraceId(":abc");
}
});
}
@Test
public void testEnableConnectionPoolOnExplicitStream() throws Exception {
IllegalArgumentException ex =
assertThrows(
IllegalArgumentException.class,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
StreamWriter.newBuilder(EXPLICIT_STEAM, client)
.setEnableConnectionPool(true)
.build();
}
});
assertTrue(ex.getMessage().contains("Trying to enable connection pool in non-default stream."));
}
@Test
public void testShortenStreamNameAllowed() throws Exception {
// no exception is thrown.
StreamWriter.newBuilder(TEST_STREAM_SHORTEN, client)
.setEnableConnectionPool(true)
.setLocation("us")
.build();
}
@Test
public void testAppendSuccessAndConnectionError() throws Exception {
StreamWriter writer =
StreamWriter.newBuilder(TEST_STREAM_1, client)
.setWriterSchema(createProtoSchema())
.setTraceId(TEST_TRACE_ID)
// Retry expire immediately.
.setMaxRetryDuration(java.time.Duration.ofMillis(1L))
.build();
testBigQueryWrite.addResponse(createAppendResponse(0));
testBigQueryWrite.addException(Status.INTERNAL.asException());
testBigQueryWrite.addException(Status.INTERNAL.asException());
testBigQueryWrite.addException(Status.INTERNAL.asException());
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
ApiFuture<AppendRowsResponse> appendFuture2 = sendTestMessage(writer, new String[] {"B"});
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
ApiException actualError = assertFutureException(ApiException.class, appendFuture2);
assertEquals(Code.INTERNAL, actualError.getStatusCode().getCode());
writer.close();
}
@Test
public void testAppendSuccessAndInStreamError() throws Exception {
StreamWriter writer = getTestStreamWriter();
testBigQueryWrite.addResponse(createAppendResponse(0));
testBigQueryWrite.addResponse(
createAppendResponseWithError(Status.INVALID_ARGUMENT.getCode(), "test message"));
testBigQueryWrite.addResponse(createAppendResponse(1));
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
ApiFuture<AppendRowsResponse> appendFuture2 = sendTestMessage(writer, new String[] {"B"});
ApiFuture<AppendRowsResponse> appendFuture3 = sendTestMessage(writer, new String[] {"C"});
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
StatusRuntimeException actualError =
assertFutureException(StatusRuntimeException.class, appendFuture2);
assertEquals(Status.Code.INVALID_ARGUMENT, actualError.getStatus().getCode());
assertEquals("test message", actualError.getStatus().getDescription());
assertEquals(1, appendFuture3.get().getAppendResult().getOffset().getValue());
writer.close();
}
@Test
public void testAppendFailedSchemaError() throws Exception {
StreamWriter writer = getTestStreamWriter();
StorageError storageError =
StorageError.newBuilder()
.setCode(StorageErrorCode.SCHEMA_MISMATCH_EXTRA_FIELDS)
.setEntity("foobar")
.build();
com.google.rpc.Status statusProto =
com.google.rpc.Status.newBuilder()
.setCode(Code.INVALID_ARGUMENT.getHttpStatusCode())
.addDetails(Any.pack(storageError))
.build();
testBigQueryWrite.addResponse(createAppendResponse(0));
testBigQueryWrite.addResponse(AppendRowsResponse.newBuilder().setError(statusProto).build());
testBigQueryWrite.addResponse(createAppendResponse(1));
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
ApiFuture<AppendRowsResponse> appendFuture2 = sendTestMessage(writer, new String[] {"B"});
ApiFuture<AppendRowsResponse> appendFuture3 = sendTestMessage(writer, new String[] {"C"});
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
Exceptions.SchemaMismatchedException actualError =
assertFutureException(Exceptions.SchemaMismatchedException.class, appendFuture2);
assertEquals("foobar", actualError.getStreamName());
assertEquals(1, appendFuture3.get().getAppendResult().getOffset().getValue());
writer.close();
}
@Test
public void testAppendFailRandomException() throws Exception {
StreamWriter writer = getTestStreamWriter();
// Trigger a non-StatusRuntimeException for append operation (although grpc API should not
// return anything other than StatusRuntimeException)
IllegalArgumentException illegalArgumentException =
new IllegalArgumentException("Illegal argument");
testBigQueryWrite.addException(illegalArgumentException);
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
UnknownException actualError = assertFutureException(UnknownException.class, appendFuture1);
assertEquals(Code.UNKNOWN, actualError.getStatusCode().getCode());
writer.close();
}
@Test
public void longIdleBetweenAppends() throws Exception {
StreamWriter writer = getTestStreamWriter();
testBigQueryWrite.addResponse(createAppendResponse(0));
testBigQueryWrite.addResponse(createAppendResponse(1));
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
// Sleep to create a long idle between appends.
TimeUnit.SECONDS.sleep(3);
ApiFuture<AppendRowsResponse> appendFuture2 = sendTestMessage(writer, new String[] {"B"});
assertEquals(1, appendFuture2.get().getAppendResult().getOffset().getValue());
writer.close();
}
@Test
public void testAppendAfterUserClose() throws Exception {
StreamWriter writer = getTestStreamWriter();
testBigQueryWrite.addResponse(createAppendResponse(0));
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
writer.close();
ApiFuture<AppendRowsResponse> appendFuture2 = sendTestMessage(writer, new String[] {"B"});
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
assertTrue(appendFuture2.isDone());
StatusRuntimeException actualError =
assertFutureException(StatusRuntimeException.class, appendFuture2);
assertEquals(Status.Code.FAILED_PRECONDITION, actualError.getStatus().getCode());
}
@Test
public void testAppendAfterServerClose() throws Exception {
StreamWriter writer = getTestStreamWriter();
testBigQueryWrite.addException(Status.INVALID_ARGUMENT.asException());
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
ApiException error1 = assertFutureException(ApiException.class, appendFuture1);
assertEquals(Code.INVALID_ARGUMENT, error1.getStatusCode().getCode());
ApiFuture<AppendRowsResponse> appendFuture2 = sendTestMessage(writer, new String[] {"B"});
assertTrue(appendFuture2.isDone());
StatusRuntimeException error2 =
assertFutureException(StatusRuntimeException.class, appendFuture2);
assertEquals(Status.Code.FAILED_PRECONDITION, error2.getStatus().getCode());
writer.close();
}
@Test
public void userCloseWhileRequestInflight() throws Exception {
final StreamWriter writer = getTestStreamWriter();
// Server will sleep 2 seconds before sending back the response.
testBigQueryWrite.setResponseSleep(Duration.ofSeconds(2));
testBigQueryWrite.addResponse(createAppendResponse(0));
// Send a request and close the stream in separate thread while the request is inflight.
final ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
Thread closeThread =
new Thread(
new Runnable() {
@Override
public void run() {
writer.close();
}
});
closeThread.start();
// Due to the sleep on server, the append won't finish within 1 second even though stream
// is being closed.
assertThrows(
TimeoutException.class,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
appendFuture1.get(1, TimeUnit.SECONDS);
}
});
// Within 2 seconds, the request should be done and stream should be closed.
closeThread.join(2000);
assertTrue(appendFuture1.isDone());
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
}
@Test
public void serverCloseWhileRequestsInflight() throws Exception {
StreamWriter writer = getTestStreamWriter();
// Server will sleep 2 seconds before closing the connection.
testBigQueryWrite.setResponseSleep(Duration.ofSeconds(2));
testBigQueryWrite.addException(Status.INVALID_ARGUMENT.asException());
// Send 10 requests, so that there are 10 inflight requests.
int appendCount = 10;
List<ApiFuture<AppendRowsResponse>> futures = new ArrayList<>();
for (int i = 0; i < appendCount; i++) {
futures.add(sendTestMessage(writer, new String[] {String.valueOf(i)}));
}
// Server close should properly handle all inflight requests.
for (int i = 0; i < appendCount; i++) {
ApiException actualError = assertFutureException(ApiException.class, futures.get(i));
assertEquals(Code.INVALID_ARGUMENT, actualError.getStatusCode().getCode());
}
writer.close();
}
@Test
public void testZeroMaxInflightRequests() throws Exception {
StreamWriter writer =
StreamWriter.newBuilder(TEST_STREAM_1, client)
.setWriterSchema(createProtoSchema())
.setMaxInflightRequests(0)
.build();
testBigQueryWrite.addResponse(createAppendResponse(0));
verifyAppendIsBlocked(writer);
writer.close();
}
@Test
public void testZeroMaxInflightBytes() throws Exception {
StreamWriter writer =
StreamWriter.newBuilder(TEST_STREAM_1, client)
.setWriterSchema(createProtoSchema())
.setMaxInflightBytes(0)
.build();
testBigQueryWrite.addResponse(createAppendResponse(0));
verifyAppendIsBlocked(writer);
writer.close();
}
@Test
public void testOneMaxInflightRequests() throws Exception {
StreamWriter writer =
StreamWriter.newBuilder(TEST_STREAM_1, client)
.setWriterSchema(createProtoSchema())
.setMaxInflightRequests(1)
.build();
// Server will sleep 1 second before every response.
testBigQueryWrite.setResponseSleep(Duration.ofSeconds(1));
testBigQueryWrite.addResponse(createAppendResponse(0));
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
assertTrue(writer.getInflightWaitSeconds() >= 1);
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
writer.close();
}
@Test
public void testOneMaxInflightRequests_MultiplexingCase() throws Exception {
ConnectionWorkerPool.setOptions(Settings.builder().setMaxConnectionsPerRegion(2).build());
StreamWriter writer1 =
StreamWriter.newBuilder(TEST_STREAM_1, client)
.setWriterSchema(createProtoSchema())
.setLocation("US")
.setEnableConnectionPool(true)
.setMaxInflightRequests(1)
.build();
StreamWriter writer2 =
StreamWriter.newBuilder(TEST_STREAM_2, client)
.setWriterSchema(createProtoSchema())
.setMaxInflightRequests(1)
.setEnableConnectionPool(true)
.setMaxInflightRequests(1)
.setLocation("US")
.build();
// Server will sleep 1 second before every response.
testBigQueryWrite.setResponseSleep(Duration.ofSeconds(1));
testBigQueryWrite.addResponse(createAppendResponse(0));
testBigQueryWrite.addResponse(createAppendResponse(1));
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer1, new String[] {"A"});
ApiFuture<AppendRowsResponse> appendFuture2 = sendTestMessage(writer2, new String[] {"A"});
assertTrue(writer1.getInflightWaitSeconds() >= 1);
assertTrue(writer2.getInflightWaitSeconds() >= 1);
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
assertEquals(1, appendFuture2.get().getAppendResult().getOffset().getValue());
writer1.close();
writer2.close();
}
@Test
public void testProtoSchemaPiping_nonMultiplexingCase() throws Exception {
ProtoSchema protoSchema = createProtoSchema();
StreamWriter writer =
StreamWriter.newBuilder(TEST_STREAM_1, client)
.setWriterSchema(protoSchema)
.setMaxInflightBytes(1)
.build();
long appendCount = 5;
for (int i = 0; i < appendCount; i++) {
testBigQueryWrite.addResponse(createAppendResponse(i));
}
List<ApiFuture<AppendRowsResponse>> futures = new ArrayList<>();
for (int i = 0; i < appendCount; i++) {
futures.add(writer.append(createProtoRows(new String[] {String.valueOf(i)}), i));
}
for (int i = 0; i < appendCount; i++) {
assertEquals(i, futures.get(i).get().getAppendResult().getOffset().getValue());
}
assertEquals(appendCount, testBigQueryWrite.getAppendRequests().size());
for (int i = 0; i < appendCount; i++) {
AppendRowsRequest appendRowsRequest = testBigQueryWrite.getAppendRequests().get(i);
assertEquals(i, appendRowsRequest.getOffset().getValue());
if (i == 0) {
appendRowsRequest.getProtoRows().getWriterSchema().equals(protoSchema);
assertEquals(appendRowsRequest.getWriteStream(), TEST_STREAM_1);
} else {
appendRowsRequest.getProtoRows().getWriterSchema().equals(ProtoSchema.getDefaultInstance());
}
}
writer.close();
}
@Test
public void testProtoSchemaPiping_multiplexingCase() throws Exception {
// Use the shared connection mode.
ConnectionWorkerPool.setOptions(
Settings.builder().setMinConnectionsPerRegion(1).setMaxConnectionsPerRegion(1).build());
ProtoSchema schema1 = createProtoSchema("Schema1");
ProtoSchema schema2 = createProtoSchema("Schema2");
StreamWriter writer1 =
StreamWriter.newBuilder(TEST_STREAM_1, client)
.setWriterSchema(schema1)
.setLocation("US")
.setEnableConnectionPool(true)
.setMaxInflightRequests(1)
.build();
StreamWriter writer2 =
StreamWriter.newBuilder(TEST_STREAM_2, client)
.setWriterSchema(schema2)
.setMaxInflightRequests(1)
.setEnableConnectionPool(true)
.setLocation("US")
.build();
long appendCountPerStream = 5;
for (int i = 0; i < appendCountPerStream * 4; i++) {
testBigQueryWrite.addResponse(createAppendResponse(i));
}
List<ApiFuture<AppendRowsResponse>> futures = new ArrayList<>();
// In total insert append `appendCountPerStream` * 4 requests.
// We insert using the pattern of streamWriter1, streamWriter1, streamWriter2, streamWriter2
for (int i = 0; i < appendCountPerStream; i++) {
futures.add(writer1.append(createProtoRows(new String[] {String.valueOf(i)}), i * 4));
futures.add(writer1.append(createProtoRows(new String[] {String.valueOf(i)}), i * 4 + 1));
futures.add(writer2.append(createProtoRows(new String[] {String.valueOf(i)}), i * 4 + 2));
futures.add(writer2.append(createProtoRows(new String[] {String.valueOf(i)}), i * 4 + 3));
}
for (int i = 0; i < appendCountPerStream * 4; i++) {
AppendRowsRequest appendRowsRequest = testBigQueryWrite.getAppendRequests().get(i);
assertEquals(i, appendRowsRequest.getOffset().getValue());
if (i % 4 == 0) {
assertEquals(appendRowsRequest.getProtoRows().getWriterSchema(), schema1);
assertEquals(appendRowsRequest.getWriteStream(), TEST_STREAM_1);
} else if (i % 4 == 1) {
assertEquals(
appendRowsRequest.getProtoRows().getWriterSchema(), ProtoSchema.getDefaultInstance());
// Before entering multiplexing (i == 1) case, the write stream won't be populated.
if (i == 1) {
assertEquals(appendRowsRequest.getWriteStream(), "");
} else {
assertEquals(appendRowsRequest.getWriteStream(), TEST_STREAM_1);
}
} else if (i % 4 == 2) {
assertEquals(appendRowsRequest.getProtoRows().getWriterSchema(), schema2);
assertEquals(appendRowsRequest.getWriteStream(), TEST_STREAM_2);
} else {
assertEquals(
appendRowsRequest.getProtoRows().getWriterSchema(), ProtoSchema.getDefaultInstance());
assertEquals(appendRowsRequest.getWriteStream(), TEST_STREAM_2);
}
}
writer1.close();
writer2.close();
}
@Test
public void testAppendsWithTinyMaxInflightBytes() throws Exception {
StreamWriter writer =
StreamWriter.newBuilder(TEST_STREAM_1, client)
.setWriterSchema(createProtoSchema())
.setMaxInflightBytes(1)
.build();
// Server will sleep 100ms before every response.
testBigQueryWrite.setResponseSleep(Duration.ofMillis(100));
long appendCount = 10;
for (int i = 0; i < appendCount; i++) {
testBigQueryWrite.addResponse(createAppendResponse(i));
}
List<ApiFuture<AppendRowsResponse>> futures = new ArrayList<>();
long appendStartTimeMs = System.currentTimeMillis();
for (int i = 0; i < appendCount; i++) {
futures.add(writer.append(createProtoRows(new String[] {String.valueOf(i)}), i));
}
long appendElapsedMs = System.currentTimeMillis() - appendStartTimeMs;
assertTrue(appendElapsedMs >= 1000);
for (int i = 0; i < appendCount; i++) {
assertEquals(i, futures.get(i).get().getAppendResult().getOffset().getValue());
}
assertEquals(appendCount, testBigQueryWrite.getAppendRequests().size());
for (int i = 0; i < appendCount; i++) {
assertEquals(i, testBigQueryWrite.getAppendRequests().get(i).getOffset().getValue());
}
writer.close();
}
@Test
public void testAppendsWithTinyMaxInflightBytesThrow() throws Exception {
StreamWriter writer =
StreamWriter.newBuilder(TEST_STREAM_1, client)
.setWriterSchema(createProtoSchema())
.setMaxInflightBytes(1)
.setLimitExceededBehavior(FlowController.LimitExceededBehavior.ThrowException)
.build();
Exceptions.InflightBytesLimitExceededException ex =
assertThrows(
Exceptions.InflightBytesLimitExceededException.class,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
writer.append(createProtoRows(new String[] {String.valueOf(10)}), -1);
}
});
assertEquals(ex.getStatus().getCode(), Status.RESOURCE_EXHAUSTED.getCode());
assertTrue(
ex.getStatus()
.getDescription()
.contains(
"Exceeds client side inflight buffer, consider add more buffer or open more connections"));
assertEquals(ex.getWriterId(), writer.getWriterId());
assertEquals(1, ex.getCurrentLimit());
writer.close();
}
@Test
public void testLimitBehaviorIgnoreNotAccepted() throws Exception {
StatusRuntimeException ex =
assertThrows(
StatusRuntimeException.class,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
StreamWriter writer =
StreamWriter.newBuilder(TEST_STREAM_1, client)
.setWriterSchema(createProtoSchema())
.setMaxInflightBytes(1)
.setLimitExceededBehavior(FlowController.LimitExceededBehavior.Ignore)
.build();
}
});
assertEquals(ex.getStatus().getCode(), Status.INVALID_ARGUMENT.getCode());
assertTrue(
ex.getStatus()
.getDescription()
.contains("LimitExceededBehavior.Ignore is not supported on StreamWriter."));
}
@Test
public void testMessageTooLarge() throws Exception {
StreamWriter writer = getTestStreamWriter();
String oversized = Strings.repeat("a", (int) (StreamWriter.getApiMaxRequestBytes() + 1));
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {oversized});
assertTrue(appendFuture1.isDone());
StatusRuntimeException actualError =
assertFutureException(StatusRuntimeException.class, appendFuture1);
assertEquals(Status.Code.INVALID_ARGUMENT, actualError.getStatus().getCode());
assertTrue(actualError.getStatus().getDescription().contains("MessageSize is too large"));
writer.close();
}
@Test
public void testThrowExceptionWhileWithinAppendLoop_MaxWaitTimeExceed() throws Exception {
ProtoSchema schema1 = createProtoSchema("foo");
StreamWriter.setMaxRequestCallbackWaitTime(java.time.Duration.ofSeconds(1));
StreamWriter writer =
StreamWriter.newBuilder(TEST_STREAM_1, client).setWriterSchema(schema1).build();
testBigQueryWrite.setResponseSleep(org.threeten.bp.Duration.ofSeconds(3));
long appendCount = 10;
for (int i = 0; i < appendCount; i++) {
testBigQueryWrite.addResponse(createAppendResponse(i));
}
// In total insert 5 requests,
List<ApiFuture<AppendRowsResponse>> futures = new ArrayList<>();
for (int i = 0; i < appendCount; i++) {
futures.add(writer.append(createProtoRows(new String[] {String.valueOf(i)}), i));
}
for (int i = 0; i < appendCount; i++) {
int finalI = i;
ExecutionException ex =
assertThrows(
ExecutionException.class,
() -> futures.get(finalI).get().getAppendResult().getOffset().getValue());
assertThat(ex.getCause()).hasMessageThat().contains("Request has waited in inflight queue");
}
}
@Test
public void testAppendWithResetSuccess() throws Exception {
try (StreamWriter writer = getTestStreamWriter()) {
testBigQueryWrite.setCloseEveryNAppends(113);
long appendCount = 10000;
for (long i = 0; i < appendCount; i++) {
testBigQueryWrite.addResponse(createAppendResponse(i));
}
List<ApiFuture<AppendRowsResponse>> futures = new ArrayList<>();
for (long i = 0; i < appendCount; i++) {
futures.add(sendTestMessage(writer, new String[] {String.valueOf(i)}, i));
}
for (int i = 0; i < appendCount; i++) {
assertEquals(futures.get(i).get().getAppendResult().getOffset().getValue(), (long) i);
}
assertTrue(testBigQueryWrite.getConnectionCount() >= (int) (appendCount / 113.0));
}
}
@Test