This repository was archived by the owner on Apr 7, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathReadWriteTransaction.java
More file actions
1402 lines (1301 loc) · 54.5 KB
/
Copy pathReadWriteTransaction.java
File metadata and controls
1402 lines (1301 loc) · 54.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
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 2019 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.connection;
import static com.google.cloud.spanner.SpannerApiFutures.get;
import static com.google.cloud.spanner.connection.AbstractStatementParser.BEGIN_STATEMENT;
import static com.google.cloud.spanner.connection.AbstractStatementParser.COMMIT_STATEMENT;
import static com.google.cloud.spanner.connection.AbstractStatementParser.ROLLBACK_STATEMENT;
import static com.google.cloud.spanner.connection.AbstractStatementParser.RUN_BATCH_STATEMENT;
import static com.google.cloud.spanner.connection.ConnectionOptions.tryParseLong;
import static com.google.common.base.Preconditions.checkNotNull;
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.cloud.Timestamp;
import com.google.cloud.Tuple;
import com.google.cloud.spanner.AbortedDueToConcurrentModificationException;
import com.google.cloud.spanner.AbortedException;
import com.google.cloud.spanner.CommitResponse;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.Dialect;
import com.google.cloud.spanner.ErrorCode;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.Options;
import com.google.cloud.spanner.Options.QueryOption;
import com.google.cloud.spanner.Options.TransactionOption;
import com.google.cloud.spanner.Options.UpdateOption;
import com.google.cloud.spanner.ProtobufResultSet;
import com.google.cloud.spanner.ReadContext;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.SpannerExceptionFactory;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.ThreadFactoryUtil;
import com.google.cloud.spanner.TransactionContext;
import com.google.cloud.spanner.TransactionManager;
import com.google.cloud.spanner.connection.AbstractStatementParser.ParsedStatement;
import com.google.cloud.spanner.connection.AbstractStatementParser.StatementType;
import com.google.cloud.spanner.connection.TransactionRetryListener.RetryResult;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.spanner.v1.SpannerGrpc;
import com.google.spanner.v1.TransactionOptions.IsolationLevel;
import com.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
import io.grpc.Deadline;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.context.Scope;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Transaction that is used when a {@link Connection} is normal read/write mode (i.e. not autocommit
* and not read-only). These transactions can be automatically retried if an {@link
* AbortedException} is thrown. The transaction will keep track of a running checksum of all {@link
* ResultSet}s that have been returned, and the update counts returned by any DML statement executed
* during the transaction. As long as these checksums and update counts are equal for both the
* original transaction and the retried transaction, the retry can safely be assumed to have the
* exact same results as the original transaction.
*/
class ReadWriteTransaction extends AbstractMultiUseTransaction {
private static final AttributeKey<Boolean> TRANSACTION_RETRIED =
AttributeKey.booleanKey("transaction.retried");
private static final Logger logger = Logger.getLogger(ReadWriteTransaction.class.getName());
private static final ThreadFactory KEEP_ALIVE_THREAD_FACTORY =
ThreadFactoryUtil.createVirtualOrPlatformDaemonThreadFactory(
"read-write-transaction-keep-alive", true);
private static final ScheduledExecutorService KEEP_ALIVE_SERVICE =
Executors.newSingleThreadScheduledExecutor(KEEP_ALIVE_THREAD_FACTORY);
private static final ParsedStatement SELECT1_STATEMENT =
AbstractStatementParser.getInstance(Dialect.GOOGLE_STANDARD_SQL)
.parse(Statement.of("SELECT 1"));
private static final long DEFAULT_KEEP_ALIVE_INTERVAL_MILLIS = 8000L;
private static final AtomicLong ID_GENERATOR = new AtomicLong();
private static final String MAX_INTERNAL_RETRIES_EXCEEDED =
"Internal transaction retry maximum exceeded";
private static final int DEFAULT_MAX_INTERNAL_RETRIES = 50;
/**
* A reference to the currently active transaction on the emulator that was started by the same
* thread. This reference is only used when running on the emulator, and enables the Connection
* API to manually abort the current transaction on the emulator, so other transactions can try to
* make progress.
*/
private static final ThreadLocal<ReadWriteTransaction> CURRENT_ACTIVE_TRANSACTION =
new ThreadLocal<>();
/**
* The name of the automatic savepoint that is generated by the Connection API if automatically
* aborting the current active transaction on the emulator is enabled.
*/
private static final String AUTO_SAVEPOINT_NAME = "_auto_savepoint";
private final boolean usesEmulator;
/**
* Indicates whether an automatic savepoint should be generated after each statement, so the
* transaction can be manually aborted and retried by the Connection API when connected to the
* emulator. This feature is only intended for use with the Spanner emulator. When connected to
* real Spanner, the decision whether to abort a transaction or not should be delegated to
* Spanner.
*/
private final boolean useAutoSavepointsForEmulator;
/**
* The savepoint that was automatically generated after executing the last statement. This is used
* to abort transactions on the emulator, if one thread tries to execute concurrent transactions
* on the emulator, and would otherwise be deadlocked.
*/
private Savepoint autoSavepoint;
private final int maxInternalRetries;
private final ReentrantLock abortedLock = new ReentrantLock();
private final long transactionId;
private final DatabaseClient dbClient;
private final TransactionOption[] transactionOptions;
private TransactionManager txManager;
private final boolean retryAbortsInternally;
private final boolean delayTransactionStartUntilFirstWrite;
private final boolean keepTransactionAlive;
private final long keepAliveIntervalMillis;
private final ReentrantLock keepAliveLock;
private final SavepointSupport savepointSupport;
@Nonnull private final IsolationLevel isolationLevel;
private final ReadLockMode readLockMode;
private final Deadline deadline;
private int transactionRetryAttempts;
private int successfulRetries;
private volatile ApiFuture<TransactionContext> txContextFuture;
private boolean canUseSingleUseRead;
private volatile SettableApiFuture<CommitResponse> commitResponseFuture;
private volatile UnitOfWorkState state = UnitOfWorkState.STARTED;
private volatile AbortedException abortedException;
private AbortedException rolledBackToSavepointException;
private boolean timedOutOrCancelled = false;
private final List<RetriableStatement> statements = new ArrayList<>();
private final List<Mutation> mutations = new ArrayList<>();
private Timestamp transactionStarted;
private ScheduledFuture<?> keepAliveFuture;
private static final class RollbackToSavepointException extends Exception {
private final Savepoint savepoint;
RollbackToSavepointException(Savepoint savepoint) {
this.savepoint = Preconditions.checkNotNull(savepoint);
}
Savepoint getSavepoint() {
return this.savepoint;
}
}
private final class StatementResultCallback<V> implements ApiFutureCallback<V> {
@Override
public void onFailure(Throwable t) {
if (t instanceof SpannerException) {
handlePossibleInvalidatingException((SpannerException) t);
}
maybeScheduleKeepAlivePing();
}
@Override
public void onSuccess(V result) {
maybeScheduleKeepAlivePing();
}
}
static class Builder extends AbstractMultiUseTransaction.Builder<Builder, ReadWriteTransaction> {
private boolean usesEmulator;
private boolean useAutoSavepointsForEmulator;
private DatabaseClient dbClient;
private Boolean retryAbortsInternally;
private boolean delayTransactionStartUntilFirstWrite;
private boolean keepTransactionAlive;
private boolean returnCommitStats;
private Duration maxCommitDelay;
private SavepointSupport savepointSupport;
private IsolationLevel isolationLevel;
private ReadLockMode readLockMode = ReadLockMode.READ_LOCK_MODE_UNSPECIFIED;
private Deadline deadline;
private Builder() {}
Builder setUsesEmulator(boolean usesEmulator) {
this.usesEmulator = usesEmulator;
return this;
}
Builder setUseAutoSavepointsForEmulator(boolean useAutoSavepoints) {
this.useAutoSavepointsForEmulator = useAutoSavepoints;
return this;
}
Builder setDatabaseClient(DatabaseClient client) {
Preconditions.checkNotNull(client);
this.dbClient = client;
return this;
}
Builder setDelayTransactionStartUntilFirstWrite(boolean delayTransactionStartUntilFirstWrite) {
this.delayTransactionStartUntilFirstWrite = delayTransactionStartUntilFirstWrite;
return this;
}
Builder setKeepTransactionAlive(boolean keepTransactionAlive) {
this.keepTransactionAlive = keepTransactionAlive;
return this;
}
Builder setRetryAbortsInternally(boolean retryAbortsInternally) {
this.retryAbortsInternally = retryAbortsInternally;
return this;
}
Builder setReturnCommitStats(boolean returnCommitStats) {
this.returnCommitStats = returnCommitStats;
return this;
}
Builder setMaxCommitDelay(Duration maxCommitDelay) {
this.maxCommitDelay = maxCommitDelay;
return this;
}
Builder setSavepointSupport(SavepointSupport savepointSupport) {
this.savepointSupport = savepointSupport;
return this;
}
Builder setIsolationLevel(IsolationLevel isolationLevel) {
this.isolationLevel = Preconditions.checkNotNull(isolationLevel);
return this;
}
Builder setReadLockMode(ReadLockMode readLockMode) {
this.readLockMode = Preconditions.checkNotNull(readLockMode);
return this;
}
Builder setDeadline(Deadline deadline) {
this.deadline = deadline;
return this;
}
@Override
ReadWriteTransaction build() {
Preconditions.checkState(dbClient != null, "No DatabaseClient client specified");
Preconditions.checkState(
retryAbortsInternally != null, "RetryAbortsInternally is not specified");
Preconditions.checkState(
hasTransactionRetryListeners(), "TransactionRetryListeners are not specified");
Preconditions.checkState(savepointSupport != null, "SavepointSupport is not specified");
Preconditions.checkState(isolationLevel != null, "IsolationLevel is not specified");
return new ReadWriteTransaction(this);
}
}
static Builder newBuilder() {
return new Builder();
}
private ReadWriteTransaction(Builder builder) {
super(builder);
this.transactionId = ID_GENERATOR.incrementAndGet();
this.usesEmulator = builder.usesEmulator;
this.useAutoSavepointsForEmulator = builder.useAutoSavepointsForEmulator;
// Use a higher max for internal retries if auto-savepoints have been enabled for the emulator.
// This can cause a larger number of transactions to be aborted and retried, and retrying on the
// emulator is fast, so increasing the limit is reasonable.
this.maxInternalRetries =
builder.usesEmulator && builder.retryAbortsInternally
? DEFAULT_MAX_INTERNAL_RETRIES * 50
: DEFAULT_MAX_INTERNAL_RETRIES;
this.dbClient = builder.dbClient;
this.delayTransactionStartUntilFirstWrite = builder.delayTransactionStartUntilFirstWrite;
this.keepTransactionAlive = builder.keepTransactionAlive;
this.keepAliveIntervalMillis =
this.keepTransactionAlive
? tryParseLong(
System.getProperty(
"spanner.connection.keep_alive_interval_millis",
String.valueOf(DEFAULT_KEEP_ALIVE_INTERVAL_MILLIS)),
DEFAULT_KEEP_ALIVE_INTERVAL_MILLIS)
: 0L;
this.keepAliveLock = this.keepTransactionAlive ? new ReentrantLock() : null;
this.retryAbortsInternally = builder.retryAbortsInternally;
this.savepointSupport = builder.savepointSupport;
this.isolationLevel = Preconditions.checkNotNull(builder.isolationLevel);
this.readLockMode = Preconditions.checkNotNull(builder.readLockMode);
this.deadline = builder.deadline;
this.transactionOptions = extractOptions(builder);
}
private TransactionOption[] extractOptions(Builder builder) {
int numOptions = 0;
if (builder.returnCommitStats) {
numOptions++;
}
if (builder.maxCommitDelay != null) {
numOptions++;
}
if (this.transactionTag != null) {
numOptions++;
}
if (this.excludeTxnFromChangeStreams) {
numOptions++;
}
if (this.rpcPriority != null) {
numOptions++;
}
if (this.isolationLevel != IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED) {
numOptions++;
}
if (this.readLockMode != ReadLockMode.READ_LOCK_MODE_UNSPECIFIED) {
numOptions++;
}
TransactionOption[] options = new TransactionOption[numOptions];
int index = 0;
if (builder.returnCommitStats) {
options[index++] = Options.commitStats();
}
if (builder.maxCommitDelay != null) {
options[index++] = Options.maxCommitDelay(builder.maxCommitDelay);
}
if (this.transactionTag != null) {
options[index++] = Options.tag(this.transactionTag);
}
if (this.excludeTxnFromChangeStreams) {
options[index++] = Options.excludeTxnFromChangeStreams();
}
if (this.rpcPriority != null) {
options[index++] = Options.priority(this.rpcPriority);
}
if (this.isolationLevel != IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED) {
options[index++] = Options.isolationLevel(this.isolationLevel);
}
if (this.readLockMode != ReadLockMode.READ_LOCK_MODE_UNSPECIFIED) {
options[index++] = Options.readLockMode(this.readLockMode);
}
return options;
}
@Override
public String toString() {
return new StringBuilder()
.append("ReadWriteTransaction - ID: ")
.append(transactionId)
.append("; Delay tx start: ")
.append(delayTransactionStartUntilFirstWrite)
.append("; Tag: ")
.append(Strings.nullToEmpty(transactionTag))
.append("; Status: ")
.append(internalGetStateName())
.append("; Started: ")
.append(internalGetTimeStarted())
.append("; Retry attempts: ")
.append(transactionRetryAttempts)
.append("; Successful retries: ")
.append(successfulRetries)
.toString();
}
private String internalGetStateName() {
return transactionStarted == null ? "Not yet started" : getState().toString();
}
private String internalGetTimeStarted() {
return transactionStarted == null ? "Not yet started" : transactionStarted.toString();
}
@Override
public UnitOfWorkState getState() {
return this.state;
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
void checkOrCreateValidTransaction(ParsedStatement statement, CallType callType) {
checkValidStateAndMarkStarted();
if (txContextFuture == null
&& (!delayTransactionStartUntilFirstWrite
|| (statement != null && statement.isUpdate())
|| (statement == COMMIT_STATEMENT && !mutations.isEmpty()))) {
txManager = dbClient.transactionManager(this.transactionOptions);
canUseSingleUseRead = false;
txContextFuture =
executeStatementAsync(
callType, BEGIN_STATEMENT, txManager::begin, SpannerGrpc.getBeginTransactionMethod());
} else if (txContextFuture == null && delayTransactionStartUntilFirstWrite) {
canUseSingleUseRead = true;
}
maybeUpdateActiveTransaction();
}
private void checkValidStateAndMarkStarted() {
ConnectionPreconditions.checkState(
this.state == UnitOfWorkState.STARTED || this.state == UnitOfWorkState.ABORTED,
"This transaction has status "
+ this.state.name()
+ ", only "
+ UnitOfWorkState.STARTED
+ "or "
+ UnitOfWorkState.ABORTED
+ " is allowed.");
ConnectionPreconditions.checkState(
this.retryAbortsInternally || this.rolledBackToSavepointException == null,
"Cannot resume execution after rolling back to a savepoint if internal retries have been"
+ " disabled. Call Connection#setRetryAbortsInternally(true) or execute `SET"
+ " RETRY_ABORTS_INTERNALLY=TRUE` to enable resuming execution after rolling back to a"
+ " savepoint.");
checkTimedOut();
if (transactionStarted == null) {
transactionStarted = Timestamp.now();
}
}
private boolean shouldPing() {
return isActive()
&& keepAliveLock != null
&& keepTransactionAlive
&& !timedOutOrCancelled
&& rolledBackToSavepointException == null;
}
private void maybeScheduleKeepAlivePing() {
if (shouldPing()) {
keepAliveLock.lock();
try {
if (keepAliveFuture == null || keepAliveFuture.isDone()) {
keepAliveFuture =
KEEP_ALIVE_SERVICE.schedule(
new KeepAliveRunnable(),
keepAliveIntervalMillis > 0
? keepAliveIntervalMillis
: DEFAULT_KEEP_ALIVE_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS);
}
} finally {
keepAliveLock.unlock();
}
}
}
private void cancelScheduledKeepAlivePing() {
if (keepAliveLock != null) {
keepAliveLock.lock();
try {
if (keepAliveFuture != null) {
keepAliveFuture.cancel(false);
}
} finally {
keepAliveLock.unlock();
}
}
}
private class KeepAliveRunnable implements Runnable {
@Override
public void run() {
if (shouldPing()) {
// Do a shoot-and-forget ping and schedule a new ping over 8 seconds after this ping has
// finished.
ApiFuture<ResultSet> future =
executeQueryAsync(
CallType.SYNC,
SELECT1_STATEMENT,
AnalyzeMode.NONE,
Options.tag(
System.getProperty(
"spanner.connection.keep_alive_query_tag",
"connection.transaction-keep-alive")));
future.addListener(
ReadWriteTransaction.this::maybeScheduleKeepAlivePing, MoreExecutors.directExecutor());
}
}
}
private void checkTimedOut() {
ConnectionPreconditions.checkState(
!timedOutOrCancelled,
"The last statement of this transaction timed out or was cancelled. "
+ "The transaction is no longer usable. "
+ "Rollback the transaction and start a new one.");
}
@Override
public boolean isActive() {
// Consider ABORTED an active state, as it is something that is automatically set if the
// transaction is aborted by the backend. That means that we should not automatically create a
// new transaction for the following statement after a transaction has aborted, and instead we
// should wait until the application has rolled back the current transaction.
//
// Otherwise the following list of statements could show unexpected behavior:
// connection.executeUpdateAsync("UPDATE FOO SET BAR=1 ...");
// connection.executeUpdateAsync("UPDATE BAR SET FOO=2 ...");
// connection.commitAsync();
//
// If the first update statement fails with an aborted exception, the second update statement
// should not be executed in a new transaction, but should also abort.
return getState().isActive() || state == UnitOfWorkState.ABORTED;
}
void checkAborted() {
if (this.state == UnitOfWorkState.ABORTED && this.abortedException != null) {
if (this.abortedException instanceof AbortedDueToConcurrentModificationException) {
throw SpannerExceptionFactory.newAbortedDueToConcurrentModificationException(
(AbortedDueToConcurrentModificationException) this.abortedException);
} else {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.ABORTED,
"This transaction has already been aborted. Rollback this transaction to start a new"
+ " one.",
this.abortedException);
}
}
}
void checkRolledBackToSavepoint() {
if (this.rolledBackToSavepointException != null) {
if (savepointSupport == SavepointSupport.FAIL_AFTER_ROLLBACK
&& !((RollbackToSavepointException) this.rolledBackToSavepointException.getCause())
.getSavepoint()
.isAutoSavepoint()) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION,
"Using a read/write transaction after rolling back to a savepoint is not supported "
+ "with SavepointSupport="
+ savepointSupport);
} else {
AbortedException exception = this.rolledBackToSavepointException;
this.rolledBackToSavepointException = null;
throw exception;
}
}
}
@Override
ReadContext getReadContext() {
if (txContextFuture == null && canUseSingleUseRead) {
return dbClient.singleUse();
}
ConnectionPreconditions.checkState(txContextFuture != null, "Missing transaction context");
return get(txContextFuture);
}
TransactionContext getTransactionContext() {
ConnectionPreconditions.checkState(txContextFuture != null, "Missing transaction context");
return (TransactionContext) getReadContext();
}
@Override
public Timestamp getReadTimestamp() {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION,
"There is no read timestamp available for read/write transactions.");
}
@Override
public Timestamp getReadTimestampOrNull() {
return null;
}
private boolean hasCommitResponse() {
return commitResponseFuture != null;
}
@Override
public Timestamp getCommitTimestamp() {
ConnectionPreconditions.checkState(
hasCommitResponse(), "This transaction has not been committed.");
return get(commitResponseFuture).getCommitTimestamp();
}
@Override
public Timestamp getCommitTimestampOrNull() {
return hasCommitResponse() ? get(commitResponseFuture).getCommitTimestamp() : null;
}
@Override
public CommitResponse getCommitResponse() {
ConnectionPreconditions.checkState(
hasCommitResponse(), "This transaction has not been committed.");
return get(commitResponseFuture);
}
@Override
public CommitResponse getCommitResponseOrNull() {
return hasCommitResponse() ? get(commitResponseFuture) : null;
}
@Override
public ApiFuture<Void> executeDdlAsync(CallType callType, ParsedStatement ddl) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION,
"DDL-statements are not allowed inside a read/write transaction.");
}
private void handlePossibleInvalidatingException(SpannerException e) {
if (e.getErrorCode() == ErrorCode.DEADLINE_EXCEEDED
|| e.getErrorCode() == ErrorCode.CANCELLED) {
this.timedOutOrCancelled = true;
}
}
@Override
public ApiFuture<ResultSet> executeQueryAsync(
final CallType callType,
final ParsedStatement statement,
final AnalyzeMode analyzeMode,
final QueryOption... options) {
Preconditions.checkArgument(
(statement.getType() == StatementType.QUERY)
|| (statement.getType() == StatementType.UPDATE && statement.hasReturningClause()),
"Statement must be a query or DML with returning clause");
try (Scope ignore = span.makeCurrent()) {
checkOrCreateValidTransaction(statement, callType);
ApiFuture<ResultSet> res;
if (retryAbortsInternally && txContextFuture != null) {
res =
executeStatementAsync(
callType,
statement,
() -> {
checkTimedOut();
return runWithRetry(
() -> {
try {
getStatementExecutor()
.invokeInterceptors(
statement,
StatementExecutionStep.EXECUTE_STATEMENT,
ReadWriteTransaction.this);
DirectExecuteResultSet delegate =
DirectExecuteResultSet.ofResultSet(
internalExecuteQuery(statement, analyzeMode, options));
return createAndAddRetryResultSet(
delegate, statement, analyzeMode, options);
} catch (AbortedException e) {
throw e;
} catch (SpannerException e) {
createAndAddFailedQuery(e, statement, analyzeMode, options);
throw e;
}
});
},
// ignore interceptors here as they are invoked in the Callable.
InterceptorsUsage.IGNORE_INTERCEPTORS,
ImmutableList.of(SpannerGrpc.getExecuteStreamingSqlMethod()));
} else {
res = super.executeQueryAsync(callType, statement, analyzeMode, options);
}
ApiFutures.addCallback(res, new StatementResultCallback<>(), MoreExecutors.directExecutor());
return res;
}
}
@Override
public ApiFuture<ResultSet> analyzeUpdateAsync(
CallType callType, ParsedStatement update, AnalyzeMode analyzeMode, UpdateOption... options) {
try (Scope ignore = span.makeCurrent()) {
return ApiFutures.transform(
internalExecuteUpdateAsync(callType, update, analyzeMode, options),
Tuple::y,
MoreExecutors.directExecutor());
}
}
@Override
public ApiFuture<Long> executeUpdateAsync(
CallType callType, final ParsedStatement update, final UpdateOption... options) {
try (Scope ignore = span.makeCurrent()) {
return ApiFutures.transform(
internalExecuteUpdateAsync(callType, update, AnalyzeMode.NONE, options),
Tuple::x,
MoreExecutors.directExecutor());
}
}
/**
* Executes the given update statement using the specified query planning mode and with the given
* options and returns the result as a {@link Tuple}. The tuple contains either a {@link
* ResultSet} with the query plan and execution statistics, or a {@link Long} that contains the
* update count that was returned for the update statement. Only one of the elements in the tuple
* will be set, and the reason that we are using a {@link Tuple} here is because Java does not
* have a standard implementation for an 'Either' class (i.e. a Tuple where only one element is
* set). An alternative would be to always return a {@link ResultSet} with the update count
* encoded in the execution stats of the result set, but this would mean that we would create
* additional {@link ResultSet} instances every time an update statement is executed in normal
* mode.
*/
private ApiFuture<Tuple<Long, ResultSet>> internalExecuteUpdateAsync(
CallType callType, ParsedStatement update, AnalyzeMode analyzeMode, UpdateOption... options) {
Preconditions.checkNotNull(update);
Preconditions.checkArgument(update.isUpdate(), "The statement is not an update statement");
checkOrCreateValidTransaction(update, callType);
ApiFuture<Tuple<Long, ResultSet>> res;
if (retryAbortsInternally && txContextFuture != null) {
res =
executeStatementAsync(
callType,
update,
() -> {
checkTimedOut();
return runWithRetry(
() -> {
try {
getStatementExecutor()
.invokeInterceptors(
update,
StatementExecutionStep.EXECUTE_STATEMENT,
ReadWriteTransaction.this);
Tuple<Long, ResultSet> result;
long updateCount;
if (analyzeMode == AnalyzeMode.NONE) {
updateCount =
get(txContextFuture).executeUpdate(update.getStatement(), options);
result = Tuple.of(updateCount, null);
} else {
ResultSet resultSet =
get(txContextFuture)
.analyzeUpdateStatement(
update.getStatement(),
analyzeMode.getQueryAnalyzeMode(),
options);
updateCount =
Objects.requireNonNull(resultSet.getStats()).getRowCountExact();
result = Tuple.of(null, resultSet);
}
createAndAddRetriableUpdate(update, analyzeMode, updateCount, options);
return result;
} catch (AbortedException e) {
throw e;
} catch (SpannerException e) {
createAndAddFailedUpdate(e, update);
throw e;
}
});
},
// ignore interceptors here as they are invoked in the Callable.
InterceptorsUsage.IGNORE_INTERCEPTORS,
ImmutableList.of(SpannerGrpc.getExecuteSqlMethod()));
} else {
res =
executeStatementAsync(
callType,
update,
() -> {
checkTimedOut();
checkAborted();
if (analyzeMode == AnalyzeMode.NONE) {
return Tuple.of(
get(txContextFuture).executeUpdate(update.getStatement(), options), null);
}
ResultSet resultSet =
get(txContextFuture)
.analyzeUpdateStatement(
update.getStatement(), analyzeMode.getQueryAnalyzeMode(), options);
return Tuple.of(null, resultSet);
},
SpannerGrpc.getExecuteSqlMethod());
}
ApiFutures.addCallback(res, new StatementResultCallback<>(), MoreExecutors.directExecutor());
return res;
}
@Override
public ApiFuture<long[]> executeBatchUpdateAsync(
CallType callType, Iterable<ParsedStatement> updates, final UpdateOption... options) {
Preconditions.checkNotNull(updates);
try (Scope ignore = span.makeCurrent()) {
final List<Statement> updateStatements = new LinkedList<>();
for (ParsedStatement update : updates) {
Preconditions.checkArgument(
update.isUpdate(), "Statement is not an update statement: " + update.getSql());
updateStatements.add(update.getStatement());
}
checkOrCreateValidTransaction(Iterables.getFirst(updates, null), callType);
ApiFuture<long[]> res;
if (retryAbortsInternally) {
res =
executeStatementAsync(
callType,
RUN_BATCH_STATEMENT,
() -> {
checkTimedOut();
return runWithRetry(
() -> {
try {
getStatementExecutor()
.invokeInterceptors(
RUN_BATCH_STATEMENT,
StatementExecutionStep.EXECUTE_STATEMENT,
ReadWriteTransaction.this);
long[] updateCounts =
get(txContextFuture).batchUpdate(updateStatements, options);
createAndAddRetriableBatchUpdate(updateStatements, updateCounts, options);
return updateCounts;
} catch (AbortedException e) {
throw e;
} catch (SpannerException e) {
createAndAddFailedBatchUpdate(e, updateStatements);
throw e;
}
});
},
// ignore interceptors here as they are invoked in the Callable.
InterceptorsUsage.IGNORE_INTERCEPTORS,
ImmutableList.of(SpannerGrpc.getExecuteBatchDmlMethod()));
} else {
res =
executeStatementAsync(
callType,
RUN_BATCH_STATEMENT,
() -> {
checkTimedOut();
checkAborted();
return get(txContextFuture).batchUpdate(updateStatements);
},
SpannerGrpc.getExecuteBatchDmlMethod());
}
ApiFutures.addCallback(res, new StatementResultCallback<>(), MoreExecutors.directExecutor());
return res;
}
}
@Override
public ApiFuture<Void> writeAsync(CallType callType, Iterable<Mutation> mutations) {
try (Scope ignore = span.makeCurrent()) {
Preconditions.checkNotNull(mutations);
// We actually don't need an underlying transaction yet, as mutations are buffered until
// commit.
// But we do need to verify that this transaction is valid, and to mark the start of the
// transaction.
checkValidStateAndMarkStarted();
for (Mutation mutation : mutations) {
this.mutations.add(checkNotNull(mutation));
}
return ApiFutures.immediateFuture(null);
}
}
private final Callable<Void> commitCallable =
new Callable<Void>() {
@Override
public Void call() {
checkAborted();
get(txContextFuture).buffer(mutations);
txManager.commit();
commitResponseFuture.set(txManager.getCommitResponse());
state = UnitOfWorkState.COMMITTED;
return null;
}
};
@Override
public ApiFuture<Void> commitAsync(
@Nonnull CallType callType, @Nonnull EndTransactionCallback callback) {
try (Scope ignore = span.makeCurrent()) {
checkOrCreateValidTransaction(COMMIT_STATEMENT, callType);
cancelScheduledKeepAlivePing();
state = UnitOfWorkState.COMMITTING;
commitResponseFuture = SettableApiFuture.create();
ApiFuture<Void> res;
// Check if this transaction actually needs to commit anything.
if (txContextFuture == null) {
// No actual transaction was started by this read/write transaction, which also means that
// we don't have to commit anything.
commitResponseFuture.set(
new CommitResponse(
Timestamp.fromProto(com.google.protobuf.Timestamp.getDefaultInstance())));
callback.onSuccess();
state = UnitOfWorkState.COMMITTED;
res = SettableApiFuture.create();
((SettableApiFuture<Void>) res).set(null);
} else if (retryAbortsInternally) {
res =
executeStatementAsync(
callType,
COMMIT_STATEMENT,
() -> {
checkTimedOut();
try {
Void result =
runWithRetry(
() -> {
getStatementExecutor()
.invokeInterceptors(
COMMIT_STATEMENT,
StatementExecutionStep.EXECUTE_STATEMENT,
ReadWriteTransaction.this);
return commitCallable.call();
});
callback.onSuccess();
return result;
} catch (Throwable t) {
commitResponseFuture.setException(t);
callback.onFailure();
state = UnitOfWorkState.COMMIT_FAILED;
try {
txManager.close();
} catch (Throwable t2) {
// Ignore.
}
throw t;
}
},
InterceptorsUsage.IGNORE_INTERCEPTORS,
ImmutableList.of(SpannerGrpc.getCommitMethod()));
} else {
res =
executeStatementAsync(
callType,
COMMIT_STATEMENT,
() -> {
checkTimedOut();
try {
Void result = commitCallable.call();
callback.onSuccess();
return result;
} catch (Throwable t) {
commitResponseFuture.setException(t);
callback.onFailure();
state = UnitOfWorkState.COMMIT_FAILED;
try {
txManager.close();
} catch (Throwable t2) {
// Ignore.
}
throw t;
}
},
SpannerGrpc.getCommitMethod());
}
asyncEndUnitOfWorkSpan();
return res;
}
}
/**
* Executes a database call that could throw an {@link AbortedException}. If an {@link
* AbortedException} is thrown, the transaction will automatically be retried and the checksums of
* all {@link ResultSet}s and update counts of DML statements will be checked against the original
* values of the original transaction. If the checksums and/or update counts do not match, the
* method will throw an {@link AbortedException} that cannot be retried, as the underlying data
* have actually changed.
*
* <p>If {@link ReadWriteTransaction#retryAbortsInternally} has been set to <code>false</code>,
* this method will throw an exception instead of retrying the transaction if the transaction was
* aborted.
*
* @param callable The actual database calls.
* @return the results of the database calls.
* @throws SpannerException if the database calls threw an exception, an {@link
* AbortedDueToConcurrentModificationException} if a retry of the transaction yielded
* different results than the original transaction, or an {@link AbortedException} if the
* maximum number of retries has been exceeded.