forked from googleapis/java-bigtable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReadIT.java
479 lines (414 loc) · 16.9 KB
/
ReadIT.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
/*
* Copyright 2018 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.bigtable.data.v2.it;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import com.google.api.core.ApiFunction;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.api.core.SettableApiFuture;
import com.google.api.gax.batching.Batcher;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.rpc.ResponseObserver;
import com.google.api.gax.rpc.StreamController;
import com.google.cloud.bigtable.data.v2.BigtableDataClient;
import com.google.cloud.bigtable.data.v2.BigtableDataSettings;
import com.google.cloud.bigtable.data.v2.models.BulkMutation;
import com.google.cloud.bigtable.data.v2.models.Query;
import com.google.cloud.bigtable.data.v2.models.Range.ByteStringRange;
import com.google.cloud.bigtable.data.v2.models.Row;
import com.google.cloud.bigtable.data.v2.models.RowCell;
import com.google.cloud.bigtable.data.v2.models.RowMutation;
import com.google.cloud.bigtable.data.v2.models.RowMutationEntry;
import com.google.cloud.bigtable.test_helpers.env.EmulatorEnv;
import com.google.cloud.bigtable.test_helpers.env.TestEnvRule;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.protobuf.ByteString;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ManagedChannelBuilder;
import io.grpc.MethodDescriptor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class ReadIT {
private String prefix;
@ClassRule public static TestEnvRule testEnvRule = new TestEnvRule();
@Before
public void setUp() {
prefix = UUID.randomUUID().toString();
}
@Test
public void isRowExists() throws Exception {
String rowKey = prefix + "-test-row-key";
String tableId = testEnvRule.env().getTableId();
testEnvRule
.env()
.getDataClient()
.mutateRow(
RowMutation.create(tableId, rowKey)
.setCell(testEnvRule.env().getFamilyId(), "qualifier", "value"));
assertThat(testEnvRule.env().getDataClient().exists(tableId, rowKey)).isTrue();
String nonExistingKey = prefix + "non-existing-key";
assertThat(testEnvRule.env().getDataClient().exists(tableId, nonExistingKey)).isFalse();
// Async
assertThat(testEnvRule.env().getDataClient().existsAsync(tableId, rowKey).get()).isTrue();
}
@Test
public void readEmpty() throws Throwable {
String uniqueKey = prefix + "-readEmpty";
Query query = Query.create(testEnvRule.env().getTableId()).rowKey(uniqueKey);
// Sync
ArrayList<Row> rows = Lists.newArrayList(testEnvRule.env().getDataClient().readRows(query));
assertThat(rows).isEmpty();
// Async
AccumulatingObserver observer = new AccumulatingObserver();
testEnvRule.env().getDataClient().readRowsAsync(query, observer);
observer.awaitCompletion();
assertThat(observer.responses).isEmpty();
}
@Test
public void read() throws Throwable {
int numRows = 5;
List<Row> expectedRows = Lists.newArrayList();
String uniqueKey = prefix + "-read";
long timestampMicros = System.currentTimeMillis() * 1_000;
for (int i = 0; i < numRows; i++) {
testEnvRule
.env()
.getDataClient()
.mutateRowCallable()
.call(
RowMutation.create(testEnvRule.env().getTableId(), uniqueKey + "-" + i)
.setCell(testEnvRule.env().getFamilyId(), "q", timestampMicros, "my-value"));
expectedRows.add(
Row.create(
ByteString.copyFromUtf8(uniqueKey + "-" + i),
ImmutableList.of(
RowCell.create(
testEnvRule.env().getFamilyId(),
ByteString.copyFromUtf8("q"),
timestampMicros,
ImmutableList.<String>of(),
ByteString.copyFromUtf8("my-value")))));
}
String tableId = testEnvRule.env().getTableId();
// Sync
Query query = Query.create(tableId).range(uniqueKey + "-0", uniqueKey + "-" + numRows);
ArrayList<Row> actualResults =
Lists.newArrayList(testEnvRule.env().getDataClient().readRows(query));
assertThat(actualResults).containsExactlyElementsIn(expectedRows);
// Async
AccumulatingObserver observer = new AccumulatingObserver();
testEnvRule.env().getDataClient().readRowsAsync(query, observer);
observer.awaitCompletion();
assertThat(observer.responses).containsExactlyElementsIn(expectedRows);
// Point Sync
Row actualRow =
testEnvRule.env().getDataClient().readRow(tableId, expectedRows.get(0).getKey());
assertThat(actualRow).isEqualTo(expectedRows.get(0));
// Point Async
ApiFuture<Row> actualRowFuture =
testEnvRule.env().getDataClient().readRowAsync(tableId, expectedRows.get(0).getKey());
assertThat(actualRowFuture.get()).isEqualTo(expectedRows.get(0));
}
@Test
public void rangeQueries() {
BigtableDataClient client = testEnvRule.env().getDataClient();
String tableId = testEnvRule.env().getTableId();
String familyId = testEnvRule.env().getFamilyId();
String uniqueKey = prefix + "-range-queries";
String keyA = uniqueKey + "-" + "a";
String keyZ = uniqueKey + "-" + "z";
long timestampMicros = System.currentTimeMillis() * 1_000;
client.bulkMutateRows(
BulkMutation.create(tableId)
.add(RowMutationEntry.create(keyA).setCell(familyId, "", timestampMicros, "A"))
.add(RowMutationEntry.create(keyZ).setCell(familyId, "", timestampMicros, "Z")));
Row expectedRowA =
Row.create(
ByteString.copyFromUtf8(keyA),
ImmutableList.of(
RowCell.create(
testEnvRule.env().getFamilyId(),
ByteString.copyFromUtf8(""),
timestampMicros,
ImmutableList.<String>of(),
ByteString.copyFromUtf8("A"))));
Row expectedRowZ =
Row.create(
ByteString.copyFromUtf8(keyZ),
ImmutableList.of(
RowCell.create(
testEnvRule.env().getFamilyId(),
ByteString.copyFromUtf8(""),
timestampMicros,
ImmutableList.<String>of(),
ByteString.copyFromUtf8("Z"))));
// Closed/Open
assertThat(
ImmutableList.copyOf(
client.readRows(
Query.create(tableId)
.range(ByteStringRange.unbounded().startClosed(keyA).endOpen(keyZ)))))
.containsExactly(expectedRowA);
// Closed/Closed
assertThat(
ImmutableList.copyOf(
client.readRows(
Query.create(tableId)
.range(ByteStringRange.unbounded().startClosed(keyA).endClosed(keyZ)))))
.containsExactly(expectedRowA, expectedRowZ);
// Open/Closed
assertThat(
ImmutableList.copyOf(
client.readRows(
Query.create(tableId)
.range(ByteStringRange.unbounded().startOpen(keyA).endClosed(keyZ)))))
.containsExactly(expectedRowZ);
// Open/Open
assertThat(
ImmutableList.copyOf(
client.readRows(
Query.create(tableId)
.range(ByteStringRange.unbounded().startOpen(keyA).endOpen(keyZ)))))
.isEmpty();
}
@Test
public void reversed() {
assume()
.withMessage("reverse scans are not supported in the emulator")
.that(testEnvRule.env())
.isNotInstanceOf(EmulatorEnv.class);
BigtableDataClient client = testEnvRule.env().getDataClient();
String tableId = testEnvRule.env().getTableId();
String familyId = testEnvRule.env().getFamilyId();
String uniqueKey = prefix + "-rev-queries";
String keyA = uniqueKey + "-" + "a";
String keyB = uniqueKey + "-" + "b";
String keyC = uniqueKey + "-" + "c";
long timestampMicros = System.currentTimeMillis() * 1_000;
client.bulkMutateRows(
BulkMutation.create(tableId)
.add(RowMutationEntry.create(keyA).setCell(familyId, "", timestampMicros, "A"))
.add(RowMutationEntry.create(keyB).setCell(familyId, "", timestampMicros, "B"))
.add(RowMutationEntry.create(keyC).setCell(familyId, "", timestampMicros, "C")));
Row expectedRowA =
Row.create(
ByteString.copyFromUtf8(keyA),
ImmutableList.of(
RowCell.create(
testEnvRule.env().getFamilyId(),
ByteString.copyFromUtf8(""),
timestampMicros,
ImmutableList.<String>of(),
ByteString.copyFromUtf8("A"))));
Row expectedRowB =
Row.create(
ByteString.copyFromUtf8(keyB),
ImmutableList.of(
RowCell.create(
testEnvRule.env().getFamilyId(),
ByteString.copyFromUtf8(""),
timestampMicros,
ImmutableList.<String>of(),
ByteString.copyFromUtf8("B"))));
Row expectedRowC =
Row.create(
ByteString.copyFromUtf8(keyC),
ImmutableList.of(
RowCell.create(
testEnvRule.env().getFamilyId(),
ByteString.copyFromUtf8(""),
timestampMicros,
ImmutableList.<String>of(),
ByteString.copyFromUtf8("C"))));
assertThat(
ImmutableList.copyOf(
client.readRows(
Query.create(tableId).reversed(true).range(ByteStringRange.prefix(uniqueKey)))))
.containsExactly(expectedRowC, expectedRowB, expectedRowA)
.inOrder();
assertThat(
ImmutableList.copyOf(
client.readRows(
Query.create(tableId)
.reversed(true)
.range(ByteStringRange.prefix(uniqueKey))
.limit(2))))
.containsExactly(expectedRowC, expectedRowB)
.inOrder();
assertThat(
ImmutableList.copyOf(
client.readRows(
Query.create(tableId)
.reversed(true)
.range(ByteStringRange.unbounded().endOpen(keyC))
.limit(2))))
.containsExactly(expectedRowB, expectedRowA)
.inOrder();
}
@Test
@Ignore("Test taking too long to run, ignore for now")
public void reversedWithForcedResumption() throws IOException, InterruptedException {
assume()
.withMessage("reverse scans are not supported in the emulator")
.that(testEnvRule.env())
.isNotInstanceOf(EmulatorEnv.class);
BigtableDataClient client = testEnvRule.env().getDataClient();
String tableId = testEnvRule.env().getTableId();
String familyId = testEnvRule.env().getFamilyId();
String uniqueKey = prefix + "-rev-queries2";
// Add enough rows that ensures resumption logic is forced
Random random;
List<Row> expectedResults;
try (Batcher<RowMutationEntry, Void> batcher = client.newBulkMutationBatcher(tableId)) {
byte[] valueBytes = new byte[1024];
random = new Random();
expectedResults = new ArrayList<>();
for (int i = 0; i < 2 * 1024; i++) {
ByteString key = ByteString.copyFromUtf8(String.format("%s-%05d", uniqueKey, i));
ByteString qualifier = ByteString.copyFromUtf8("q");
long timestamp = System.currentTimeMillis() * 1000;
random.nextBytes(valueBytes);
ByteString value = ByteString.copyFrom(valueBytes);
batcher.add(RowMutationEntry.create(key).setCell(familyId, qualifier, timestamp, value));
expectedResults.add(
Row.create(
key,
ImmutableList.of(
RowCell.create(familyId, qualifier, timestamp, ImmutableList.of(), value))));
}
}
Collections.reverse(expectedResults);
BigtableDataSettings.Builder settingsBuilder =
testEnvRule.env().getDataClientSettings().toBuilder();
settingsBuilder.stubSettings().readRowsSettings().retrySettings().setMaxAttempts(100);
InstantiatingGrpcChannelProvider.Builder transport =
((InstantiatingGrpcChannelProvider)
settingsBuilder.stubSettings().getTransportChannelProvider())
.toBuilder();
ApiFunction<ManagedChannelBuilder, ManagedChannelBuilder> oldConfigurator =
transport.getChannelConfigurator();
// Randomly camp the deadline to force a timeout to force a retry
transport.setChannelConfigurator(
(ManagedChannelBuilder c) -> {
if (oldConfigurator != null) {
c = oldConfigurator.apply(c);
}
return c.intercept(
new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
if (method.getBareMethodName().equals("ReadRows")) {
callOptions =
callOptions.withDeadlineAfter(random.nextInt(200), TimeUnit.MILLISECONDS);
}
return next.newCall(method, callOptions);
}
});
});
settingsBuilder.stubSettings().setTransportChannelProvider(transport.build());
try (BigtableDataClient patchedClient = BigtableDataClient.create(settingsBuilder.build())) {
for (int i = 0; i < 10; i++) {
List<Row> actualResults = new ArrayList<>();
for (Row row :
patchedClient.readRows(Query.create(tableId).prefix(uniqueKey).reversed(true))) {
actualResults.add(row);
Thread.sleep(1);
}
assertThat(actualResults).containsExactlyElementsIn(expectedResults).inOrder();
}
}
}
@Test
public void readSingleNonexistentAsyncCallback() throws Exception {
ApiFuture<Row> future =
testEnvRule
.env()
.getDataClient()
.readRowAsync(testEnvRule.env().getTableId(), "somenonexistentkey");
final AtomicReference<Throwable> unexpectedError = new AtomicReference<>();
final AtomicBoolean found = new AtomicBoolean();
final CountDownLatch latch = new CountDownLatch(1);
ApiFutures.addCallback(
future,
new ApiFutureCallback<Row>() {
@Override
public void onFailure(Throwable t) {
unexpectedError.set(t);
latch.countDown();
}
@Override
public void onSuccess(Row result) {
found.set(true);
latch.countDown();
}
},
MoreExecutors.directExecutor());
latch.await(1, TimeUnit.MINUTES);
if (unexpectedError.get() != null) {
throw new RuntimeException("Unexpected async error", unexpectedError.get());
}
assertThat(found.get()).isTrue();
}
static class AccumulatingObserver implements ResponseObserver<Row> {
final List<Row> responses = Lists.newArrayList();
final SettableApiFuture<Void> completionFuture = SettableApiFuture.create();
void awaitCompletion() throws Throwable {
try {
completionFuture.get(10, TimeUnit.MINUTES);
} catch (ExecutionException e) {
throw e.getCause();
}
}
@Override
public void onStart(StreamController controller) {}
@Override
public void onResponse(Row row) {
responses.add(row);
}
@Override
public void onError(Throwable t) {
completionFuture.setException(t);
}
@Override
public void onComplete() {
completionFuture.set(null);
}
}
}