Repository navigation
Expand file tree
/
Copy pathAsyncRunnerTest.java
More file actions
643 lines (612 loc) · 26.5 KB
/
Copy pathAsyncRunnerTest.java
File metadata and controls
643 lines (612 loc) · 26.5 KB
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
/*
* 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
*
* 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.spanner;
import static com.google.cloud.spanner.MockSpannerTestUtil.*;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.api.core.SettableApiFuture;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.AsyncResultSet.CallbackResponse;
import com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime;
import com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.spanner.v1.BatchCreateSessionsRequest;
import com.google.spanner.v1.BeginTransactionRequest;
import com.google.spanner.v1.CommitRequest;
import com.google.spanner.v1.CreateSessionRequest;
import com.google.spanner.v1.ExecuteBatchDmlRequest;
import com.google.spanner.v1.ExecuteSqlRequest;
import io.grpc.Status;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class AsyncRunnerTest extends AbstractAsyncTransactionTest {
@After
public void clearRequests() {
mockSpanner.clearRequests();
}
@Test
public void testAsyncRunner_doesNotReturnCommitTimestampBeforeCommit() {
AsyncRunner runner = client().runAsync();
if (isMultiplexedSessionsEnabledForRW()) {
Throwable e = assertThrows(Throwable.class, () -> runner.getCommitTimestamp().get());
// If the error occurs within the future, it gets wrapped in an ExecutionException.
// This happens when DelayedAsyncRunner is invoked while the multiplexed session is not yet
// created.
// If the error occurs before the future is created, it may throw an IllegalStateException
// instead.
assertTrue(e instanceof ExecutionException || e instanceof IllegalStateException);
if (e instanceof ExecutionException) {
Throwable cause = e.getCause();
assertTrue(cause instanceof IllegalStateException);
assertTrue(cause.getMessage().contains("runAsync() has not yet been called"));
} else {
assertTrue(e.getMessage().contains("runAsync() has not yet been called"));
}
} else {
IllegalStateException e =
assertThrows(IllegalStateException.class, () -> runner.getCommitTimestamp());
assertTrue(e.getMessage().contains("runAsync() has not yet been called"));
}
}
@Test
public void testAsyncRunner_doesNotReturnCommitResponseBeforeCommit() {
AsyncRunner runner = client().runAsync();
if (isMultiplexedSessionsEnabledForRW()) {
Throwable e = assertThrows(Throwable.class, () -> runner.getCommitResponse().get());
// If the error occurs within the future, it gets wrapped in an ExecutionException.
// This happens when DelayedAsyncRunner is invoked while the multiplexed session is not yet
// created.
// If the error occurs before the future is created, it may throw an IllegalStateException
// instead.
assertTrue(e instanceof ExecutionException || e instanceof IllegalStateException);
if (e instanceof ExecutionException) {
Throwable cause = e.getCause();
assertTrue(cause instanceof IllegalStateException);
assertTrue(cause.getMessage().contains("runAsync() has not yet been called"));
} else {
assertTrue(e.getMessage().contains("runAsync() has not yet been called"));
}
} else {
IllegalStateException e =
assertThrows(IllegalStateException.class, () -> runner.getCommitResponse());
assertTrue(e.getMessage().contains("runAsync() has not yet been called"));
}
}
@Test
public void asyncRunnerUpdate() throws Exception {
AsyncRunner runner = client().runAsync();
ApiFuture<Long> updateCount =
runner.runAsync(txn -> txn.executeUpdateAsync(UPDATE_STATEMENT), executor);
assertThat(updateCount.get()).isEqualTo(UPDATE_COUNT);
}
@Test
public void asyncRunnerIsNonBlocking() throws Exception {
mockSpanner.freeze();
AsyncRunner runner = client().runAsync();
ApiFuture<Void> res =
runner.runAsync(
txn -> {
txn.executeUpdateAsync(UPDATE_STATEMENT);
return ApiFutures.immediateFuture(null);
},
executor);
ApiFuture<Timestamp> ts = runner.getCommitTimestamp();
mockSpanner.unfreeze();
assertThat(res.get()).isNull();
assertThat(ts.get()).isNotNull();
}
@Test
public void asyncRunnerInvalidUpdate() throws Exception {
AsyncRunner runner = client().runAsync();
ApiFuture<Long> updateCount =
runner.runAsync(txn -> txn.executeUpdateAsync(INVALID_UPDATE_STATEMENT), executor);
ExecutionException e = assertThrows(ExecutionException.class, () -> updateCount.get());
assertThat(e.getCause()).isInstanceOf(SpannerException.class);
SpannerException se = SpannerExceptionFactory.asSpannerException(e.getCause());
assertThat(se.getErrorCode()).isEqualTo(ErrorCode.INVALID_ARGUMENT);
assertThat(se.getMessage()).contains("invalid statement");
}
@Test
public void asyncRunnerFireAndForgetInvalidUpdate() throws Exception {
AsyncRunner runner = client().runAsync();
ApiFuture<Long> res =
runner.runAsync(
txn -> {
txn.executeUpdateAsync(INVALID_UPDATE_STATEMENT);
return txn.executeUpdateAsync(UPDATE_STATEMENT);
},
executor);
assertThat(res.get()).isEqualTo(UPDATE_COUNT);
}
@Test
public void asyncRunnerUpdateAborted() throws Exception {
try {
// Temporarily set the result of the update to 2 rows.
mockSpanner.putStatementResult(StatementResult.update(UPDATE_STATEMENT, UPDATE_COUNT + 1L));
final AtomicInteger attempt = new AtomicInteger();
AsyncRunner runner = client().runAsync();
ApiFuture<Long> updateCount =
runner.runAsync(
txn -> {
if (attempt.incrementAndGet() == 1) {
mockSpanner.abortNextStatement();
} else {
// Set the result of the update statement back to 1 row.
mockSpanner.putStatementResult(
StatementResult.update(UPDATE_STATEMENT, UPDATE_COUNT));
}
return txn.executeUpdateAsync(UPDATE_STATEMENT);
},
executor);
assertThat(updateCount.get()).isEqualTo(UPDATE_COUNT);
assertThat(attempt.get()).isEqualTo(2);
} finally {
mockSpanner.putStatementResult(StatementResult.update(UPDATE_STATEMENT, UPDATE_COUNT));
}
}
@Test
public void asyncRunnerCommitAborted() throws Exception {
try {
// Temporarily set the result of the update to 2 rows.
mockSpanner.putStatementResult(StatementResult.update(UPDATE_STATEMENT, UPDATE_COUNT + 1L));
final AtomicInteger attempt = new AtomicInteger();
AsyncRunner runner = client().runAsync();
ApiFuture<Long> updateCount =
runner.runAsync(
txn -> {
if (attempt.get() > 0) {
// Set the result of the update statement back to 1 row.
mockSpanner.putStatementResult(
StatementResult.update(UPDATE_STATEMENT, UPDATE_COUNT));
}
ApiFuture<Long> updateCount1 = txn.executeUpdateAsync(UPDATE_STATEMENT);
if (attempt.incrementAndGet() == 1) {
mockSpanner.abortTransaction(txn);
}
return updateCount1;
},
executor);
assertThat(updateCount.get()).isEqualTo(UPDATE_COUNT);
assertThat(attempt.get()).isEqualTo(2);
} finally {
mockSpanner.putStatementResult(StatementResult.update(UPDATE_STATEMENT, UPDATE_COUNT));
}
}
@Test
public void asyncRunnerUpdateAbortedWithoutGettingResult() throws Exception {
final AtomicInteger attempt = new AtomicInteger();
AsyncRunner runner = client().runAsync();
ApiFuture<Void> result =
runner.runAsync(
txn -> {
if (attempt.incrementAndGet() == 1) {
mockSpanner.abortNextStatement();
}
// This update statement will be aborted, but the error will not propagated to the
// transaction runner and cause the transaction to retry. Instead, the commit call
// will do that.
txn.executeUpdateAsync(UPDATE_STATEMENT);
// Resolving this future will not resolve the result of the entire transaction. The
// transaction result will be resolved when the commit has actually finished
// successfully.
return ApiFutures.immediateFuture(null);
},
executor);
assertThat(result.get()).isNull();
assertThat(attempt.get()).isEqualTo(2);
if (isMultiplexedSessionsEnabledForRW()) {
assertThat(mockSpanner.getRequestTypes())
.containsExactly(
CreateSessionRequest.class,
ExecuteSqlRequest.class,
// The retry will use an explicit BeginTransaction RPC because the first statement of
// the transaction did not return a transaction id during the initial attempt.
BeginTransactionRequest.class,
ExecuteSqlRequest.class,
CommitRequest.class);
} else if (isMultiplexedSessionsEnabled()) {
assertThat(mockSpanner.getRequestTypes())
.containsExactly(
CreateSessionRequest.class,
BatchCreateSessionsRequest.class,
ExecuteSqlRequest.class,
// The retry will use an explicit BeginTransaction RPC because the first statement of
// the transaction did not return a transaction id during the initial attempt.
BeginTransactionRequest.class,
ExecuteSqlRequest.class,
CommitRequest.class);
} else {
assertThat(mockSpanner.getRequestTypes())
.containsExactly(
BatchCreateSessionsRequest.class,
ExecuteSqlRequest.class,
// The retry will use an explicit BeginTransaction RPC because the first statement of
// the transaction did not return a transaction id during the initial attempt.
BeginTransactionRequest.class,
ExecuteSqlRequest.class,
CommitRequest.class);
}
}
@Test
public void asyncRunnerCommitFails() throws Exception {
mockSpanner.setCommitExecutionTime(
SimulatedExecutionTime.ofException(
Status.INVALID_ARGUMENT
.withDescription("mutation limit exceeded")
.asRuntimeException()));
AsyncRunner runner = client().runAsync();
ApiFuture<Long> updateCount =
runner.runAsync(
txn -> {
// This statement will succeed, but the commit will fail. The error from the commit
// will bubble up to the future that is returned by the transaction, and the update
// count returned here will never reach the user application.
return txn.executeUpdateAsync(UPDATE_STATEMENT);
},
executor);
ExecutionException e = assertThrows(ExecutionException.class, () -> updateCount.get());
assertThat(e.getCause()).isInstanceOf(SpannerException.class);
SpannerException se = SpannerExceptionFactory.asSpannerException(e.getCause());
assertThat(se.getErrorCode()).isEqualTo(ErrorCode.INVALID_ARGUMENT);
assertThat(se.getMessage()).contains("mutation limit exceeded");
}
@Test
public void asyncRunnerWaitsUntilAsyncUpdateHasFinished() throws Exception {
AsyncRunner runner = client().runAsync();
ApiFuture<Void> res =
runner.runAsync(
txn -> {
txn.executeUpdateAsync(UPDATE_STATEMENT);
return ApiFutures.immediateFuture(null);
},
executor);
res.get();
if (isMultiplexedSessionsEnabledForRW()) {
assertThat(mockSpanner.getRequestTypes())
.containsAtLeast(
CreateSessionRequest.class, ExecuteSqlRequest.class, CommitRequest.class);
} else if (isMultiplexedSessionsEnabled()) {
// The mock server could have received a CreateSession request for a multiplexed session, but
// it could also be that that request has not yet reached the server.
assertThat(mockSpanner.getRequestTypes())
.containsAtLeast(
BatchCreateSessionsRequest.class, ExecuteSqlRequest.class, CommitRequest.class);
} else {
assertThat(mockSpanner.getRequestTypes())
.containsExactly(
BatchCreateSessionsRequest.class, ExecuteSqlRequest.class, CommitRequest.class);
}
}
@Test
public void asyncRunnerBatchUpdate() throws Exception {
AsyncRunner runner = client().runAsync();
ApiFuture<long[]> updateCount =
runner.runAsync(
txn -> txn.batchUpdateAsync(ImmutableList.of(UPDATE_STATEMENT, UPDATE_STATEMENT)),
executor);
assertThat(updateCount.get()).asList().containsExactly(UPDATE_COUNT, UPDATE_COUNT);
}
@Test
public void asyncRunnerIsNonBlockingWithBatchUpdate() throws Exception {
mockSpanner.freeze();
AsyncRunner runner = client().runAsync();
ApiFuture<Void> res =
runner.runAsync(
txn -> {
txn.batchUpdateAsync(ImmutableList.of(UPDATE_STATEMENT));
return ApiFutures.immediateFuture(null);
},
executor);
ApiFuture<Timestamp> ts = runner.getCommitTimestamp();
mockSpanner.unfreeze();
assertThat(res.get()).isNull();
assertThat(ts.get()).isNotNull();
}
@Test
public void asyncRunnerInvalidBatchUpdate() throws Exception {
AsyncRunner runner = client().runAsync();
ApiFuture<long[]> updateCount =
runner.runAsync(
txn ->
txn.batchUpdateAsync(ImmutableList.of(UPDATE_STATEMENT, INVALID_UPDATE_STATEMENT)),
executor);
ExecutionException e = assertThrows(ExecutionException.class, () -> updateCount.get());
assertThat(e.getCause()).isInstanceOf(SpannerException.class);
SpannerException se = SpannerExceptionFactory.asSpannerException(e.getCause());
assertThat(se.getErrorCode()).isEqualTo(ErrorCode.INVALID_ARGUMENT);
assertThat(se.getMessage()).contains("invalid statement");
}
@Test
public void asyncRunnerFireAndForgetInvalidBatchUpdate() throws Exception {
AsyncRunner runner = client().runAsync();
ApiFuture<long[]> res =
runner.runAsync(
txn -> {
txn.batchUpdateAsync(ImmutableList.of(UPDATE_STATEMENT, INVALID_UPDATE_STATEMENT));
return txn.batchUpdateAsync(ImmutableList.of(UPDATE_STATEMENT, UPDATE_STATEMENT));
},
executor);
assertThat(res.get()).asList().containsExactly(UPDATE_COUNT, UPDATE_COUNT);
}
@Test
public void asyncRunnerBatchUpdateAborted() throws Exception {
final AtomicInteger attempt = new AtomicInteger();
AsyncRunner runner = client().runAsync();
ApiFuture<long[]> updateCount =
runner.runAsync(
txn -> {
if (attempt.incrementAndGet() == 1) {
return txn.batchUpdateAsync(
ImmutableList.of(UPDATE_STATEMENT, UPDATE_ABORTED_STATEMENT));
} else {
return txn.batchUpdateAsync(ImmutableList.of(UPDATE_STATEMENT, UPDATE_STATEMENT));
}
},
executor);
assertThat(updateCount.get()).asList().containsExactly(UPDATE_COUNT, UPDATE_COUNT);
assertThat(attempt.get()).isEqualTo(2);
}
@Test
public void asyncRunnerWithBatchUpdateCommitAborted() throws Exception {
try {
// Temporarily set the result of the update to 2 rows.
mockSpanner.putStatementResult(StatementResult.update(UPDATE_STATEMENT, UPDATE_COUNT + 1L));
final AtomicInteger attempt = new AtomicInteger();
AsyncRunner runner = client().runAsync();
ApiFuture<long[]> updateCount =
runner.runAsync(
txn -> {
if (attempt.get() > 0) {
// Set the result of the update statement back to 1 row.
mockSpanner.putStatementResult(
StatementResult.update(UPDATE_STATEMENT, UPDATE_COUNT));
}
ApiFuture<long[]> updateCount1 =
txn.batchUpdateAsync(ImmutableList.of(UPDATE_STATEMENT, UPDATE_STATEMENT));
if (attempt.incrementAndGet() == 1) {
mockSpanner.abortTransaction(txn);
}
return updateCount1;
},
executor);
assertThat(updateCount.get()).asList().containsExactly(UPDATE_COUNT, UPDATE_COUNT);
assertThat(attempt.get()).isEqualTo(2);
} finally {
mockSpanner.putStatementResult(StatementResult.update(UPDATE_STATEMENT, UPDATE_COUNT));
}
}
@Test
public void asyncRunnerBatchUpdateAbortedWithoutGettingResult() throws Exception {
final AtomicInteger attempt = new AtomicInteger();
AsyncRunner runner = client().runAsync();
ApiFuture<Void> result =
runner.runAsync(
txn -> {
if (attempt.incrementAndGet() == 1) {
mockSpanner.abortNextTransaction();
}
// This statement will succeed and return a transaction id. The transaction will be
// marked as aborted on the mock server.
txn.executeUpdate(UPDATE_STATEMENT);
// This batch update statement will be aborted, but the error will not propagated to
// the
// transaction runner and cause the transaction to retry. Instead, the commit call
// will do that.
txn.batchUpdateAsync(ImmutableList.of(UPDATE_STATEMENT, UPDATE_STATEMENT));
// Resolving this future will not resolve the result of the entire transaction. The
// transaction result will be resolved when the commit has actually finished
// successfully.
return ApiFutures.immediateFuture(null);
},
executor);
assertThat(result.get()).isNull();
assertThat(attempt.get()).isEqualTo(2);
if (isMultiplexedSessionsEnabledForRW()) {
assertThat(mockSpanner.getRequestTypes())
.containsExactly(
CreateSessionRequest.class,
ExecuteSqlRequest.class,
ExecuteBatchDmlRequest.class,
CommitRequest.class,
ExecuteSqlRequest.class,
ExecuteBatchDmlRequest.class,
CommitRequest.class);
} else if (isMultiplexedSessionsEnabled()) {
assertThat(mockSpanner.getRequestTypes())
.containsExactly(
CreateSessionRequest.class,
BatchCreateSessionsRequest.class,
ExecuteSqlRequest.class,
ExecuteBatchDmlRequest.class,
CommitRequest.class,
ExecuteSqlRequest.class,
ExecuteBatchDmlRequest.class,
CommitRequest.class);
} else {
assertThat(mockSpanner.getRequestTypes())
.containsExactly(
BatchCreateSessionsRequest.class,
ExecuteSqlRequest.class,
ExecuteBatchDmlRequest.class,
CommitRequest.class,
ExecuteSqlRequest.class,
ExecuteBatchDmlRequest.class,
CommitRequest.class);
}
}
@Test
public void asyncRunnerWithBatchUpdateCommitFails() throws Exception {
mockSpanner.setCommitExecutionTime(
SimulatedExecutionTime.ofException(
Status.INVALID_ARGUMENT
.withDescription("mutation limit exceeded")
.asRuntimeException()));
AsyncRunner runner = client().runAsync();
ApiFuture<long[]> updateCount =
runner.runAsync(
txn -> {
// This statement will succeed, but the commit will fail. The error from the commit
// will bubble up to the future that is returned by the transaction, and the update
// count returned here will never reach the user application.
return txn.batchUpdateAsync(ImmutableList.of(UPDATE_STATEMENT, UPDATE_STATEMENT));
},
executor);
ExecutionException e = assertThrows(ExecutionException.class, () -> updateCount.get());
assertThat(e.getCause()).isInstanceOf(SpannerException.class);
SpannerException se = SpannerExceptionFactory.asSpannerException(e.getCause());
assertThat(se.getErrorCode()).isEqualTo(ErrorCode.INVALID_ARGUMENT);
assertThat(se.getMessage()).contains("mutation limit exceeded");
}
@Test
public void asyncRunnerWaitsUntilAsyncBatchUpdateHasFinished() throws Exception {
AsyncRunner runner = client().runAsync();
ApiFuture<Void> res =
runner.runAsync(
txn -> {
txn.batchUpdateAsync(ImmutableList.of(UPDATE_STATEMENT));
return ApiFutures.immediateFuture(null);
},
executor);
res.get();
if (isMultiplexedSessionsEnabledForRW()) {
assertThat(mockSpanner.getRequestTypes())
.containsExactly(
CreateSessionRequest.class, ExecuteBatchDmlRequest.class, CommitRequest.class);
} else if (isMultiplexedSessionsEnabled()) {
assertThat(mockSpanner.getRequestTypes())
.containsExactly(
CreateSessionRequest.class,
BatchCreateSessionsRequest.class,
ExecuteBatchDmlRequest.class,
CommitRequest.class);
} else {
assertThat(mockSpanner.getRequestTypes())
.containsExactly(
BatchCreateSessionsRequest.class, ExecuteBatchDmlRequest.class, CommitRequest.class);
}
}
@Test
public void closeTransactionBeforeEndOfAsyncQuery() throws Exception {
final BlockingQueue<String> results = new SynchronousQueue<>();
final SettableApiFuture<Boolean> finished = SettableApiFuture.create();
DatabaseClientImpl clientImpl = (DatabaseClientImpl) client();
AsyncRunner runner = clientImpl.runAsync();
final CountDownLatch dataReceived = new CountDownLatch(1);
final CountDownLatch dataChecked = new CountDownLatch(1);
ApiFuture<Void> res =
runner.runAsync(
txn -> {
try (AsyncResultSet rs =
txn.readAsync(
READ_TABLE_NAME, KeySet.all(), READ_COLUMN_NAMES, Options.bufferRows(1))) {
rs.setCallback(
Executors.newSingleThreadExecutor(),
resultSet -> {
dataReceived.countDown();
try {
while (true) {
switch (resultSet.tryNext()) {
case DONE:
finished.set(true);
return CallbackResponse.DONE;
case NOT_READY:
return CallbackResponse.CONTINUE;
case OK:
dataChecked.await();
results.put(resultSet.getString(0));
}
}
} catch (Throwable t) {
finished.setException(t);
return CallbackResponse.DONE;
}
});
}
try {
dataReceived.await();
return ApiFutures.immediateFuture(null);
} catch (InterruptedException e) {
return ApiFutures.immediateFailedFuture(
SpannerExceptionFactory.propagateInterrupt(e));
}
},
executor);
// Wait until at least one row has been fetched. At that moment there should be one session
// checked out.
dataReceived.await();
assertThat(res.isDone()).isFalse();
dataChecked.countDown();
// Get the data from the transaction.
List<String> resultList = new ArrayList<>();
do {
results.drainTo(resultList);
} while (!finished.isDone() || results.size() > 0);
assertThat(finished.get()).isTrue();
assertThat(resultList).containsExactly("k1", "k2", "k3");
assertThat(res.get()).isNull();
}
@Test
public void asyncRunnerReadRow() throws Exception {
AsyncRunner runner = client().runAsync();
ApiFuture<String> val =
runner.runAsync(
txn ->
ApiFutures.transform(
txn.readRowAsync(READ_TABLE_NAME, Key.of(1L), READ_COLUMN_NAMES),
input -> input.getString("Value"),
MoreExecutors.directExecutor()),
executor);
assertThat(val.get()).isEqualTo("v1");
}
@Test
public void asyncRunnerRead() throws Exception {
AsyncRunner runner = client().runAsync();
ApiFuture<List<String>> val =
runner.runAsync(
txn ->
txn.readAsync(READ_TABLE_NAME, KeySet.all(), READ_COLUMN_NAMES)
.toListAsync(input -> input.getString("Value"), MoreExecutors.directExecutor()),
executor);
assertThat(val.get()).containsExactly("v1", "v2", "v3");
}
private boolean isMultiplexedSessionsEnabled() {
if (spanner.getOptions() == null || spanner.getOptions().getSessionPoolOptions() == null) {
return false;
}
return spanner.getOptions().getSessionPoolOptions().getUseMultiplexedSession();
}
private boolean isMultiplexedSessionsEnabledForRW() {
if (spanner.getOptions() == null || spanner.getOptions().getSessionPoolOptions() == null) {
return false;
}
return spanner.getOptions().getSessionPoolOptions().getUseMultiplexedSessionForRW();
}
}