/
ITTransactionTest.java
656 lines (596 loc) · 23.5 KB
/
ITTransactionTest.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
/*
* Copyright 2017 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.it;
import static com.google.cloud.spanner.SpannerExceptionFactory.newSpannerException;
import static com.google.cloud.spanner.TransactionRunner.TransactionCallable;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.AbortedException;
import com.google.cloud.spanner.BatchClient;
import com.google.cloud.spanner.BatchReadOnlyTransaction;
import com.google.cloud.spanner.Database;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.ErrorCode;
import com.google.cloud.spanner.IntegrationTestEnv;
import com.google.cloud.spanner.Key;
import com.google.cloud.spanner.KeySet;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.ParallelIntegrationTest;
import com.google.cloud.spanner.PartitionOptions;
import com.google.cloud.spanner.ReadContext;
import com.google.cloud.spanner.ReadOnlyTransaction;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.Struct;
import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.TransactionContext;
import com.google.cloud.spanner.TransactionRunner;
import com.google.cloud.spanner.TransactionRunner.TransactionCallable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.SettableFuture;
import com.google.common.util.concurrent.Uninterruptibles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
/** Integration tests for read-write transactions. */
@Category(ParallelIntegrationTest.class)
@RunWith(Parameterized.class)
public class ITTransactionTest {
@Parameter(0)
public boolean inlineBegin;
@Parameters(name = "inlineBegin = {0}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {{false}, {true}});
}
@ClassRule public static IntegrationTestEnv env = new IntegrationTestEnv();
private static Database db;
private Spanner spanner;
private DatabaseClient client;
/** Sequence for assigning unique keys to test cases. */
private static int seq;
@BeforeClass
public static void setUpDatabase() {
db =
env.getTestHelper()
.createTestDatabase(
"CREATE TABLE T ("
+ " K STRING(MAX) NOT NULL,"
+ " V INT64,"
+ ") PRIMARY KEY (K)");
}
@Before
public void setupClient() {
spanner =
env.getTestHelper()
.getOptions()
.toBuilder()
.setInlineBeginForReadWriteTransaction(inlineBegin)
.build()
.getService();
client = spanner.getDatabaseClient(db.getId());
}
@After
public void closeClient() {
client.writeAtLeastOnce(ImmutableList.of(Mutation.delete("T", KeySet.all())));
spanner.close();
}
private static String uniqueKey() {
return "k" + seq++;
}
private static interface ReadStrategy {
Struct read(ReadContext ctx, String key);
}
private void doBasicsTest(final ReadStrategy strategy) throws InterruptedException {
final String key = uniqueKey();
// Initial value.
client.write(
Arrays.asList(Mutation.newInsertBuilder("T").set("K").to(key).set("V").to(0).build()));
final int numThreads = 3;
final CountDownLatch commitBarrier = new CountDownLatch(numThreads);
final CountDownLatch complete = new CountDownLatch(numThreads);
final TransactionCallable<Long> callable =
new TransactionCallable<Long>() {
@Override
public Long run(TransactionContext transaction) throws SpannerException {
Struct row = strategy.read(transaction, key);
long newValue = row.getLong(0) + 1;
transaction.buffer(
Mutation.newUpdateBuilder("T").set("K").to(key).set("V").to(newValue).build());
commitBarrier.countDown();
// Synchronize so that all threads attempt to commit at the same time.
Uninterruptibles.awaitUninterruptibly(commitBarrier);
return newValue;
}
};
// We start multiple threads all attempting to update the same value concurrently. We expect
// to see at least some of the corresponding transactions abort.
final Vector<Long> results = new Vector<>();
final Vector<Timestamp> commitTimestamps = new Vector<>();
class TxnThread extends Thread {
@Override
public void run() {
TransactionRunner runner = client.readWriteTransaction();
Long result = runner.run(callable);
results.add(result);
commitTimestamps.add(runner.getCommitTimestamp());
complete.countDown();
}
}
for (int i = 0; i < numThreads; ++i) {
new TxnThread().start();
}
complete.await();
assertThat(results).hasSize(numThreads);
List<Long> expectedResults = new ArrayList<>();
for (int i = 0; i < numThreads; ++i) {
expectedResults.add(i + 1L);
}
assertThat(results).containsAtLeastElementsIn(expectedResults);
assertThat(Sets.newHashSet(commitTimestamps)).hasSize(numThreads);
assertThat(
client
.singleUse(TimestampBound.strong())
.readRow("T", Key.of(key), Arrays.asList("V"))
.getLong(0))
.isEqualTo(Long.valueOf(numThreads));
}
@Test
public void basicsUsingRead() throws InterruptedException {
assumeFalse(
"Emulator does not support multiple parallel transactions",
env.getTestHelper().isEmulator());
doBasicsTest(
new ReadStrategy() {
@Override
public Struct read(ReadContext ctx, String key) {
return ctx.readRow("T", Key.of(key), Arrays.asList("V"));
}
});
}
@Test
public void basicsUsingQuery() throws InterruptedException {
assumeFalse(
"Emulator does not support multiple parallel transactions",
env.getTestHelper().isEmulator());
doBasicsTest(
new ReadStrategy() {
@Override
public Struct read(ReadContext ctx, String key) {
ResultSet resultSet =
ctx.executeQuery(
Statement.newBuilder("SELECT V FROM T WHERE K = @key")
.bind("key")
.to(key)
.build());
assertThat(resultSet.next()).isTrue();
Struct row = resultSet.getCurrentRowAsStruct();
assertThat(resultSet.next()).isFalse();
return row;
}
});
}
@Test
public void userExceptionPreventsCommit() {
class UserException extends Exception {
UserException(String message) {
super(message);
}
}
final String key = uniqueKey();
TransactionCallable<Void> callable =
new TransactionCallable<Void>() {
@Override
public Void run(TransactionContext transaction) throws UserException {
transaction.buffer(Mutation.newInsertOrUpdateBuilder("T").set("K").to(key).build());
throw new UserException("User failure");
}
};
try {
client.readWriteTransaction().run(callable);
fail("Expected user exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.UNKNOWN);
assertThat(e.getMessage()).contains("User failure");
assertThat(e.getCause()).isInstanceOf(UserException.class);
}
Struct row =
client.singleUse(TimestampBound.strong()).readRow("T", Key.of(key), Arrays.asList("K"));
assertThat(row).isNull();
}
@Test
public void userExceptionIsSpannerException() {
final String key = uniqueKey();
TransactionCallable<Void> callable =
new TransactionCallable<Void>() {
@Override
public Void run(TransactionContext transaction) {
transaction.buffer(Mutation.newInsertOrUpdateBuilder("T").set("K").to(key).build());
throw newSpannerException(ErrorCode.OUT_OF_RANGE, "User failure");
}
};
try {
client.readWriteTransaction().run(callable);
fail("Expected user exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.OUT_OF_RANGE);
assertThat(e.getMessage()).contains("User failure");
}
Struct row =
client.singleUse(TimestampBound.strong()).readRow("T", Key.of(key), Arrays.asList("K"));
assertThat(row).isNull();
}
@Test
public void readAbort() throws Exception {
assumeFalse(
"Emulator does not support multiple parallel transactions",
env.getTestHelper().isEmulator());
final String key1 = uniqueKey();
final String key2 = uniqueKey();
client.write(
Arrays.asList(
Mutation.newInsertBuilder("T").set("K").to(key1).set("V").to(0).build(),
Mutation.newInsertBuilder("T").set("K").to(key2).set("V").to(1).build()));
final CountDownLatch t1Started = new CountDownLatch(1);
final CountDownLatch t1Done = new CountDownLatch(1);
final CountDownLatch t2Running = new CountDownLatch(1);
final CountDownLatch t2Done = new CountDownLatch(1);
final SettableFuture<Void> t1Result = SettableFuture.create();
final SettableFuture<Void> t2Result = SettableFuture.create();
// Thread 1 performs a read before notifying that it has started and allowing
// thread 2 to start. This ensures that it establishes a senior lock priority relative to
// thread 2. It then waits for thread 2 to read, so that both threads have shared locks on
// key1, before continuing to commit; the act of committing means that thread 1's lock is
// upgraded and thread 2's transaction is aborted. When thread 1 is done, thread 2 tries a
// second read, which will abort. Both threads will mask SpannerExceptions to ensure that
// the implementation does not require TransactionCallable to propagate them.
Thread t1 =
new Thread() {
@Override
public void run() {
try {
client
.readWriteTransaction()
.run(
new TransactionCallable<Void>() {
@Override
public Void run(TransactionContext transaction) throws SpannerException {
try {
Struct row = transaction.readRow("T", Key.of(key1), Arrays.asList("V"));
t1Started.countDown();
Uninterruptibles.awaitUninterruptibly(t2Running);
transaction.buffer(
Mutation.newUpdateBuilder("T")
.set("K")
.to(key1)
.set("V")
.to(row.getLong(0) + 1)
.build());
return null;
} catch (SpannerException e) {
if (e.getErrorCode() == ErrorCode.ABORTED) {
assertThat(e).isInstanceOf(AbortedException.class);
assertThat(((AbortedException) e).getRetryDelayInMillis())
.isNotEqualTo(-1L);
}
throw new RuntimeException("Swallowed exception: " + e.getMessage());
}
}
});
t1Result.set(null);
} catch (Throwable t) {
t1Result.setException(t);
} finally {
t1Done.countDown();
}
}
};
Thread t2 =
new Thread() {
@Override
public void run() {
try {
client
.readWriteTransaction()
.run(
new TransactionCallable<Void>() {
@Override
public Void run(TransactionContext transaction) throws SpannerException {
try {
Struct r1 = transaction.readRow("T", Key.of(key1), Arrays.asList("V"));
t2Running.countDown();
Uninterruptibles.awaitUninterruptibly(t1Done);
Struct r2 = transaction.readRow("T", Key.of(key2), Arrays.asList("V"));
transaction.buffer(
Mutation.newUpdateBuilder("T")
.set("K")
.to(key2)
.set("V")
.to(r1.getLong(0) + r2.getLong(0))
.build());
return null;
} catch (SpannerException e) {
if (e.getErrorCode() == ErrorCode.ABORTED) {
assertThat(e).isInstanceOf(AbortedException.class);
assertThat(((AbortedException) e).getRetryDelayInMillis())
.isNotEqualTo(-1L);
}
throw new RuntimeException("Swallowed exception: " + e.getMessage());
}
}
});
t2Result.set(null);
} catch (Throwable t) {
t2Result.setException(t);
} finally {
t2Done.countDown();
}
}
};
t1.start();
Uninterruptibles.awaitUninterruptibly(t1Started);
// Thread 2 will abort on the first attempt and should retry; wait for completion to confirm.
t2.start();
assertThat(t2Done.await(1, TimeUnit.MINUTES)).isTrue();
// Check that both transactions effects are visible.
assertThat(t1Result.get()).isNull();
assertThat(t2Result.get()).isNull();
assertThat(
client
.singleUse(TimestampBound.strong())
.readRow("T", Key.of(key1), Arrays.asList("V"))
.getLong(0))
.isEqualTo(1);
assertThat(
client
.singleUse(TimestampBound.strong())
.readRow("T", Key.of(key2), Arrays.asList("V"))
.getLong(0))
.isEqualTo(2);
}
private void doNestedRwTransaction() {
client
.readWriteTransaction()
.run(
new TransactionCallable<Void>() {
@Override
public Void run(TransactionContext transaction) throws SpannerException {
client
.readWriteTransaction()
.run(
new TransactionCallable<Void>() {
@Override
public Void run(TransactionContext transaction) {
return null;
}
});
return null;
}
});
}
@Test
public void nestedReadWriteTxnThrows() {
try {
doNestedRwTransaction();
fail("Expected exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.INTERNAL);
assertThat(e.getMessage()).contains("not supported");
}
}
@Test
public void nestedReadOnlyTxnThrows() {
try {
client
.readWriteTransaction()
.run(
new TransactionCallable<Void>() {
@Override
public Void run(TransactionContext transaction) throws SpannerException {
try (ReadOnlyTransaction tx = client.readOnlyTransaction()) {
tx.getReadTimestamp();
}
return null;
}
});
fail("Expected exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.INTERNAL);
assertThat(e.getMessage()).contains("not supported");
}
}
@Test
public void nestedBatchTxnThrows() {
try {
client
.readWriteTransaction()
.run(
new TransactionCallable<Void>() {
@Override
public Void run(TransactionContext transaction) throws SpannerException {
BatchClient batchClient = env.getTestHelper().getBatchClient(db);
BatchReadOnlyTransaction batchTxn =
batchClient.batchReadOnlyTransaction(TimestampBound.strong());
batchTxn.partitionReadUsingIndex(
PartitionOptions.getDefaultInstance(),
"Test",
"Index",
KeySet.all(),
Arrays.asList("Fingerprint"));
return null;
}
});
fail("Expected exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.INTERNAL);
assertThat(e.getMessage()).contains("not supported");
}
}
@Test
public void nestedSingleUseReadTxnThrows() {
try {
client
.readWriteTransaction()
.run(
new TransactionCallable<Void>() {
@Override
public Void run(TransactionContext transaction) throws SpannerException {
try (ResultSet rs =
client
.singleUseReadOnlyTransaction()
.executeQuery(Statement.of("SELECT 1"))) {
rs.next();
}
return null;
}
});
fail("Expected exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.INTERNAL);
assertThat(e.getMessage()).contains("not supported");
}
}
@Test
public void nestedTxnSucceedsWhenAllowed() {
assumeFalse(
"Emulator does not support multiple parallel transactions",
env.getTestHelper().isEmulator());
client
.readWriteTransaction()
.allowNestedTransaction()
.run(
new TransactionCallable<Void>() {
@Override
public Void run(TransactionContext transaction) throws SpannerException {
client.singleUseReadOnlyTransaction();
return null;
}
});
}
@Test
public void testTxWithCaughtError() {
assumeFalse(
"Emulator does not recover from an error within a transaction",
env.getTestHelper().isEmulator());
long updateCount =
client
.readWriteTransaction()
.run(
new TransactionCallable<Long>() {
@Override
public Long run(TransactionContext transaction) throws Exception {
try {
transaction.executeUpdate(Statement.of("UPDATE T SET V=2 WHERE"));
fail("missing expected exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.INVALID_ARGUMENT);
}
return transaction.executeUpdate(
Statement.of("INSERT INTO T (K, V) VALUES ('One', 1)"));
}
});
assertThat(updateCount).isEqualTo(1L);
}
@Test
public void testTxWithConstraintError() {
assumeFalse(
"Emulator does not recover from an error within a transaction",
env.getTestHelper().isEmulator());
// First insert a single row.
client.writeAtLeastOnce(
ImmutableList.of(
Mutation.newInsertOrUpdateBuilder("T").set("K").to("One").set("V").to(1L).build()));
long updateCount =
client
.readWriteTransaction()
.run(
new TransactionCallable<Long>() {
@Override
public Long run(TransactionContext transaction) throws Exception {
try {
// Try to insert a duplicate row. This statement will fail. When the statement
// is executed against an already existing transaction (i.e.
// inlineBegin=false), the entire transaction will remain invalid and cannot
// be committed. When it is executed as the first statement of a transaction
// that also tries to start a transaction, then no transaction will be started
// and the next statement will start the transaction. This will cause the
// transaction to succeed.
transaction.executeUpdate(
Statement.of("INSERT INTO T (K, V) VALUES ('One', 1)"));
fail("missing expected exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.ALREADY_EXISTS);
}
return transaction.executeUpdate(
Statement.of("INSERT INTO T (K, V) VALUES ('Two', 2)"));
}
});
assertThat(updateCount).isEqualTo(1L);
}
@Test
public void testTxWithUncaughtError() {
try {
client
.readWriteTransaction()
.run(
new TransactionCallable<Long>() {
@Override
public Long run(TransactionContext transaction) throws Exception {
return transaction.executeUpdate(Statement.of("UPDATE T SET V=2 WHERE"));
}
});
fail("missing expected exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.INVALID_ARGUMENT);
}
}
@Test
public void testTxWithUncaughtErrorAfterSuccessfulBegin() {
try {
client
.readWriteTransaction()
.run(
new TransactionCallable<Long>() {
@Override
public Long run(TransactionContext transaction) throws Exception {
transaction.executeUpdate(Statement.of("INSERT INTO T (K, V) VALUES ('One', 1)"));
return transaction.executeUpdate(Statement.of("UPDATE T SET V=2 WHERE"));
}
});
fail("missing expected exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.INVALID_ARGUMENT);
}
}
}