/
StreamWriterV2Test.java
308 lines (266 loc) · 11.7 KB
/
StreamWriterV2Test.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
/*
* 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.v1beta2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import com.google.api.core.ApiFuture;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.api.gax.grpc.testing.MockServiceHelper;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.StatusCode.Code;
import com.google.cloud.bigquery.storage.test.Test.FooType;
import com.google.common.base.Strings;
import com.google.protobuf.DescriptorProtos;
import com.google.protobuf.Int64Value;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
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.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 StreamWriterV2Test {
private static final Logger log = Logger.getLogger(StreamWriterV2Test.class.getName());
private static final String TEST_STREAM = "projects/p/datasets/d/tables/t/streams/s";
private FakeScheduledExecutorService fakeExecutor;
private FakeBigQueryWrite testBigQueryWrite;
private static MockServiceHelper serviceHelper;
private BigQueryWriteClient client;
@Before
public void setUp() throws Exception {
testBigQueryWrite = new FakeBigQueryWrite();
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());
}
@After
public void tearDown() throws Exception {
log.info("tearDown called");
client.close();
serviceHelper.stop();
}
private StreamWriterV2 getTestStreamWriterV2() {
return StreamWriterV2.newBuilder(TEST_STREAM, client).build();
}
private AppendRowsRequest createAppendRequest(String[] messages, long offset) {
AppendRowsRequest.Builder requestBuilder = AppendRowsRequest.newBuilder();
AppendRowsRequest.ProtoData.Builder dataBuilder = AppendRowsRequest.ProtoData.newBuilder();
dataBuilder.setWriterSchema(
ProtoSchema.newBuilder()
.setProtoDescriptor(
DescriptorProtos.DescriptorProto.newBuilder()
.setName("Message")
.addField(
DescriptorProtos.FieldDescriptorProto.newBuilder()
.setName("foo")
.setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_STRING)
.setNumber(1)
.build())
.build()));
ProtoRows.Builder rows = ProtoRows.newBuilder();
for (String message : messages) {
FooType foo = FooType.newBuilder().setFoo(message).build();
rows.addSerializedRows(foo.toByteString());
}
if (offset > 0) {
requestBuilder.setOffset(Int64Value.of(offset));
}
return requestBuilder
.setProtoRows(dataBuilder.setRows(rows.build()).build())
.setWriteStream(TEST_STREAM)
.build();
}
private AppendRowsResponse createAppendResponse(long offset) {
return AppendRowsResponse.newBuilder()
.setAppendResult(
AppendRowsResponse.AppendResult.newBuilder().setOffset(Int64Value.of(offset)).build())
.build();
}
private ApiFuture<AppendRowsResponse> sendTestMessage(StreamWriterV2 writer, String[] messages) {
return writer.append(createAppendRequest(messages, -1));
}
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();
}
}
});
}
@Test
public void testAppendSuccess() throws Exception {
StreamWriterV2 writer = getTestStreamWriterV2();
long appendCount = 1000;
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(sendTestMessage(writer, new String[] {String.valueOf(i)}));
}
for (int i = 0; i < appendCount; i++) {
assertEquals(i, futures.get(i).get().getAppendResult().getOffset().getValue());
}
assertEquals(appendCount, testBigQueryWrite.getAppendRequests().size());
writer.close();
}
@Test
public void testAppendSuccessAndError() throws Exception {
StreamWriterV2 writer = getTestStreamWriterV2();
testBigQueryWrite.addResponse(createAppendResponse(0));
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 longIdleBetweenAppends() throws Exception {
StreamWriterV2 writer = getTestStreamWriterV2();
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 {
StreamWriterV2 writer = getTestStreamWriterV2();
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 {
StreamWriterV2 writer = getTestStreamWriterV2();
testBigQueryWrite.addException(Status.INTERNAL.asException());
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
ApiException error1 = assertFutureException(ApiException.class, appendFuture1);
assertEquals(Code.INTERNAL, 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 StreamWriterV2 writer = getTestStreamWriterV2();
// 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 {
StreamWriterV2 writer = getTestStreamWriterV2();
// Server will sleep 2 seconds before closing the connection.
testBigQueryWrite.setResponseSleep(Duration.ofSeconds(2));
testBigQueryWrite.addException(Status.INTERNAL.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.INTERNAL, actualError.getStatusCode().getCode());
}
writer.close();
}
@Test
public void testMessageTooLarge() {
StreamWriterV2 writer = getTestStreamWriterV2();
String oversized = Strings.repeat("a", (int) (StreamWriterV2.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();
}
}