/
MockSpannerServiceImpl.java
1817 lines (1687 loc) · 69.4 KB
/
MockSpannerServiceImpl.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
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
*
* 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.spanner;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.cloud.ByteArray;
import com.google.cloud.Date;
import com.google.cloud.spanner.TransactionRunnerImpl.TransactionContextImpl;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import com.google.protobuf.Empty;
import com.google.protobuf.Timestamp;
import com.google.protobuf.Value.KindCase;
import com.google.rpc.Code;
import com.google.rpc.ResourceInfo;
import com.google.rpc.RetryInfo;
import com.google.spanner.v1.BatchCreateSessionsRequest;
import com.google.spanner.v1.BatchCreateSessionsResponse;
import com.google.spanner.v1.BeginTransactionRequest;
import com.google.spanner.v1.CommitRequest;
import com.google.spanner.v1.CommitResponse;
import com.google.spanner.v1.CreateSessionRequest;
import com.google.spanner.v1.DeleteSessionRequest;
import com.google.spanner.v1.ExecuteBatchDmlRequest;
import com.google.spanner.v1.ExecuteBatchDmlResponse;
import com.google.spanner.v1.ExecuteSqlRequest;
import com.google.spanner.v1.GetSessionRequest;
import com.google.spanner.v1.ListSessionsRequest;
import com.google.spanner.v1.ListSessionsResponse;
import com.google.spanner.v1.PartialResultSet;
import com.google.spanner.v1.Partition;
import com.google.spanner.v1.PartitionQueryRequest;
import com.google.spanner.v1.PartitionReadRequest;
import com.google.spanner.v1.PartitionResponse;
import com.google.spanner.v1.ReadRequest;
import com.google.spanner.v1.ResultSet;
import com.google.spanner.v1.ResultSetMetadata;
import com.google.spanner.v1.ResultSetStats;
import com.google.spanner.v1.RollbackRequest;
import com.google.spanner.v1.Session;
import com.google.spanner.v1.SpannerGrpc.SpannerImplBase;
import com.google.spanner.v1.StructType;
import com.google.spanner.v1.StructType.Field;
import com.google.spanner.v1.Transaction;
import com.google.spanner.v1.TransactionOptions;
import com.google.spanner.v1.TransactionOptions.ModeCase;
import com.google.spanner.v1.TransactionOptions.ReadWrite;
import com.google.spanner.v1.TransactionSelector;
import com.google.spanner.v1.Type;
import com.google.spanner.v1.TypeCode;
import io.grpc.Metadata;
import io.grpc.ServerServiceDefinition;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.protobuf.ProtoUtils;
import io.grpc.protobuf.lite.ProtoLiteUtils;
import io.grpc.stub.StreamObserver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.threeten.bp.Instant;
/**
* In-process mock implementation of a Cloud Spanner server. The user must specify the results the
* server should return for queries and updates by calling {@link
* MockSpannerServiceImpl#putStatementResult(StatementResult)}. Note that the SQL statements that
* are put as statement results are not parsed and are only used as a key know which result to
* return. This also means that small stylistic differences between two SQL statements will be
* regarded as two different SQL statements by the mock server.
*
* <p>Session and transaction creation is automatically managed and does not need to be mocked.
*
* <p>Usage:
*
* <pre>{@code
* Statement statementSelect1 = Statement.of("SELECT 1 AS COL1");
* com.google.spanner.v1.ResultSetMetadata select1Metadata =
* com.google.spanner.v1.ResultSetMetadata.newBuilder()
* .setRowType(
* StructType.newBuilder()
* .addFields(
* Field.newBuilder()
* .setName("COL1")
* .setType(
* com.google.spanner.v1.Type.newBuilder()
* .setCode(TypeCode.INT64)
* .build())
* .build())
* .build())
* .build();
* com.google.spanner.v1.ResultSet select1ResultSet =
* com.google.spanner.v1.ResultSet.newBuilder()
* .addRows(
* ListValue.newBuilder()
* .addValues(com.google.protobuf.Value.newBuilder().setStringValue("1").build())
* .build())
* .setMetadata(select1Metadata)
* .build();
* Statement updateStatement = Statement.of("UPDATE FOO SET BAR=1 WHERE BAZ=2");
* MockSpannerServiceImpl mockSpanner = new MockSpannerServiceImpl();
* mockSpanner.putStatementResult(StatementResult.of(statementSelect1, select1ResultSet));
* mockSpanner.putStatementResult(StatementResult.of(updateStatement, 1L));
* MockServiceHelper serviceHelper =
* new MockServiceHelper("in-process-1", Arrays.<MockGrpcService>asList(mockSpanner));
* serviceHelper.start();
*
* serviceHelper.reset();
* TransportChannelProvider channelProvider = serviceHelper.createChannelProvider();
* SpannerSettings settings =
* SpannerSettings.newBuilder()
* .setTransportChannelProvider(channelProvider)
* .setCredentialsProvider(NoCredentialsProvider.create())
* .build();
* SpannerClient spannerClient = SpannerClient.create(settings);
* Spanner spanner =
* SpannerOptions.newBuilder()
* .setChannelProvider(channelProvider)
* .setCredentials(NoCredentials.getInstance())
* .build()
* .getService();
* DatabaseClient dbClient =
* spanner.getDatabaseClient(DatabaseId.of("PROJECT_ID", "INSTANCE_ID", "DATABASE_ID"));
* try (ResultSet resultSet =
* dbClient.singleUse().executeQuery(Statement.of("SELECT 1 AS COL1"))) {
* while (resultSet.next()) {
* System.out.println("COL1: " + resultSet.getLong("COL1"));
* }
* }
* long updateCount =
* dbClient
* .readWriteTransaction()
* .run(
* new TransactionCallable<Long>() {
* @Override
* public Long run(TransactionContext transaction) throws Exception {
* return transaction.executeUpdate(
* Statement.of("UPDATE FOO SET BAR=1 WHERE BAZ=2"));
* }
* });
* System.out.println("Update count: " + updateCount);
* spannerClient.close();
* }</pre>
*/
public class MockSpannerServiceImpl extends SpannerImplBase implements MockGrpcService {
private static class PartialResultSetsIterator implements Iterator<PartialResultSet> {
private static final int MAX_ROWS_IN_CHUNK = 1;
private final ResultSet resultSet;
private boolean hasNext;
private boolean first = true;
private int currentRow = 0;
private PartialResultSetsIterator(ResultSet resultSet) {
this.resultSet = resultSet;
this.hasNext = true;
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public PartialResultSet next() {
PartialResultSet.Builder builder = PartialResultSet.newBuilder();
if (first) {
builder.setMetadata(resultSet.getMetadata());
first = false;
}
int recordCount = 0;
while (recordCount < MAX_ROWS_IN_CHUNK && currentRow < resultSet.getRowsCount()) {
builder.addAllValues(resultSet.getRows(currentRow).getValuesList());
recordCount++;
currentRow++;
}
hasNext = currentRow < resultSet.getRowsCount();
return builder.build();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
/** The result of a statement that is executed on a {@link MockSpannerServiceImpl}. */
public static class StatementResult {
private enum StatementResultType {
RESULT_SET,
UPDATE_COUNT,
EXCEPTION;
}
private final StatementResultType type;
private final Statement statement;
private final Long updateCount;
private final ResultSet resultSet;
private final StatusRuntimeException exception;
/** Creates a {@link StatementResult} for a query that returns a {@link ResultSet}. */
public static StatementResult query(Statement statement, ResultSet resultSet) {
return new StatementResult(statement, resultSet);
}
/** Creates a {@link StatementResult} for a read request. */
public static StatementResult read(
String table, KeySet keySet, Iterable<String> columns, ResultSet resultSet) {
return new StatementResult(table, keySet, columns, resultSet);
}
/** Creates a {@link StatementResult} for a DML statement that returns an update count. */
public static StatementResult update(Statement statement, long updateCount) {
return new StatementResult(statement, updateCount);
}
/** Creates a {@link StatementResult} for statement that should return an error. */
public static StatementResult exception(Statement statement, StatusRuntimeException exception) {
return new StatementResult(statement, exception);
}
/**
* Creates a {@link Statement} for a read statement. This {@link Statement} can be used to mock
* a result for a read request.
*/
public static Statement createReadStatement(
String table, KeySet keySet, Iterable<String> columns) {
Preconditions.checkNotNull(table);
Preconditions.checkNotNull(keySet);
Preconditions.checkNotNull(columns);
Preconditions.checkArgument(
isValidKeySet(keySet),
"Currently only KeySet.all() and KeySet.singleKey(Key.of()) are supported for read statements");
StringBuilder builder = new StringBuilder("SELECT ");
boolean first = true;
for (String col : columns) {
if (!first) {
builder.append(", ");
}
builder.append(col);
}
builder.append(" FROM ").append(table);
if (keySet.isAll()) {
builder.append(" WHERE 1=1");
} else {
builder.append(" WHERE ID=1");
}
return Statement.of(builder.toString());
}
private static boolean isValidKeySet(KeySet keySet) {
if (keySet.isAll()) {
return true;
}
int keys = 0;
for (Key key : keySet.getKeys()) {
keys++;
if (key.size() != 0) {
return false;
}
}
return keys == 1;
}
private StatementResult(Statement statement, Long updateCount) {
this.statement = Preconditions.checkNotNull(statement);
this.updateCount = Preconditions.checkNotNull(updateCount);
this.resultSet = null;
this.exception = null;
this.type = StatementResultType.UPDATE_COUNT;
}
private StatementResult(Statement statement, ResultSet resultSet) {
this.statement = Preconditions.checkNotNull(statement);
this.resultSet = Preconditions.checkNotNull(resultSet);
this.updateCount = null;
this.exception = null;
this.type = StatementResultType.RESULT_SET;
}
private StatementResult(
String table, KeySet keySet, Iterable<String> columns, ResultSet resultSet) {
this.statement = createReadStatement(table, keySet, columns);
this.resultSet = Preconditions.checkNotNull(resultSet);
this.updateCount = null;
this.exception = null;
this.type = StatementResultType.RESULT_SET;
}
private StatementResult(Statement statement, StatusRuntimeException exception) {
this.statement = Preconditions.checkNotNull(statement);
this.exception = Preconditions.checkNotNull(exception);
this.resultSet = null;
this.updateCount = null;
this.type = StatementResultType.EXCEPTION;
}
private StatementResultType getType() {
return type;
}
private ResultSet getResultSet() {
Preconditions.checkState(
type == StatementResultType.RESULT_SET,
"This statement result does not contain a result set");
return resultSet;
}
private Long getUpdateCount() {
Preconditions.checkState(
type == StatementResultType.UPDATE_COUNT,
"This statement result does not contain an update count");
return updateCount;
}
private StatusRuntimeException getException() {
Preconditions.checkState(
type == StatementResultType.EXCEPTION,
"This statement result does not contain an exception");
return exception;
}
}
/** Class for simulating execution time of server calls. */
public static class SimulatedExecutionTime {
private static final Random RANDOM = new Random();
private final int minimumExecutionTime;
private final int randomExecutionTime;
private final Queue<Exception> exceptions;
private final boolean stickyException;
/**
* Creates a simulated execution time that will always be somewhere between <code>
* minimumExecutionTime+randomExecutionTime</code> milliseconds long.
*
* @param minimumExecutionTime The minimum number of milliseconds the execution of the method
* should be.
* @param randomExecutionTime The maximum random number of milliseconds that should be added to
* the minimum execution time.
* @return a {@link SimulatedExecutionTime} that can be set as the execution time of a server
* call on a {@link MockSpannerServiceImpl}.
*/
public static SimulatedExecutionTime ofMinimumAndRandomTime(
int minimumExecutionTime, int randomExecutionTime) {
return new SimulatedExecutionTime(minimumExecutionTime, randomExecutionTime);
}
public static SimulatedExecutionTime none() {
return new SimulatedExecutionTime(0, 0);
}
public static SimulatedExecutionTime ofException(Exception exception) {
return new SimulatedExecutionTime(0, 0, Arrays.asList(exception), false);
}
public static SimulatedExecutionTime ofStickyException(Exception exception) {
return new SimulatedExecutionTime(0, 0, Arrays.asList(exception), true);
}
public static SimulatedExecutionTime ofExceptions(Collection<Exception> exceptions) {
return new SimulatedExecutionTime(0, 0, exceptions, false);
}
public static SimulatedExecutionTime ofMinimumAndRandomTimeAndExceptions(
int minimumExecutionTime, int randomExecutionTime, Collection<Exception> exceptions) {
return new SimulatedExecutionTime(
minimumExecutionTime, randomExecutionTime, exceptions, false);
}
private SimulatedExecutionTime(int minimum, int random) {
this(minimum, random, Collections.<Exception>emptyList(), false);
}
private SimulatedExecutionTime(
int minimum, int random, Collection<Exception> exceptions, boolean stickyException) {
Preconditions.checkArgument(minimum >= 0, "Minimum execution time must be >= 0");
Preconditions.checkArgument(random >= 0, "Random execution time must be >= 0");
this.minimumExecutionTime = minimum;
this.randomExecutionTime = random;
this.exceptions = new LinkedList<>(exceptions);
this.stickyException = stickyException;
}
private void simulateExecutionTime(
Queue<Exception> globalExceptions,
boolean stickyGlobalExceptions,
ReadWriteLock freezeLock) {
try {
freezeLock.readLock().lock();
checkException(globalExceptions, stickyGlobalExceptions);
checkException(this.exceptions, stickyException);
if (minimumExecutionTime > 0 || randomExecutionTime > 0) {
Uninterruptibles.sleepUninterruptibly(
(randomExecutionTime == 0 ? 0 : RANDOM.nextInt(randomExecutionTime))
+ minimumExecutionTime,
TimeUnit.MILLISECONDS);
}
} finally {
freezeLock.readLock().unlock();
}
}
private static void checkException(Queue<Exception> exceptions, boolean keepException) {
Exception e = keepException ? exceptions.peek() : exceptions.poll();
if (e != null) {
Throwables.throwIfUnchecked(e);
throw Status.INTERNAL.withDescription(e.getMessage()).withCause(e).asRuntimeException();
}
}
}
public static final SimulatedExecutionTime NO_EXECUTION_TIME = SimulatedExecutionTime.none();
private final Random random = new Random();
private double abortProbability = 0.0010D;
private final Queue<AbstractMessage> requests = new ConcurrentLinkedQueue<>();
private final ReadWriteLock freezeLock = new ReentrantReadWriteLock();
private final Queue<Exception> exceptions = new ConcurrentLinkedQueue<>();
private boolean stickyGlobalExceptions = false;
private final ConcurrentMap<Statement, StatementResult> statementResults =
new ConcurrentHashMap<>();
private final ConcurrentMap<String, Session> sessions = new ConcurrentHashMap<>();
private ConcurrentMap<String, Instant> sessionLastUsed = new ConcurrentHashMap<>();
private final ConcurrentMap<ByteString, Transaction> transactions = new ConcurrentHashMap<>();
private final ConcurrentMap<ByteString, Boolean> isPartitionedDmlTransaction =
new ConcurrentHashMap<>();
private final ConcurrentMap<ByteString, Boolean> abortedTransactions = new ConcurrentHashMap<>();
private final AtomicBoolean abortNextTransaction = new AtomicBoolean();
private final AtomicBoolean abortNextStatement = new AtomicBoolean();
private final ConcurrentMap<String, AtomicLong> transactionCounters = new ConcurrentHashMap<>();
private final ConcurrentMap<String, List<ByteString>> partitionTokens = new ConcurrentHashMap<>();
private ConcurrentMap<ByteString, Instant> transactionLastUsed = new ConcurrentHashMap<>();
private int maxNumSessionsInOneBatch = 100;
private int maxTotalSessions = Integer.MAX_VALUE;
private AtomicInteger numSessionsCreated = new AtomicInteger();
private SimulatedExecutionTime beginTransactionExecutionTime = NO_EXECUTION_TIME;
private SimulatedExecutionTime commitExecutionTime = NO_EXECUTION_TIME;
private SimulatedExecutionTime batchCreateSessionsExecutionTime = NO_EXECUTION_TIME;
private SimulatedExecutionTime createSessionExecutionTime = NO_EXECUTION_TIME;
private SimulatedExecutionTime deleteSessionExecutionTime = NO_EXECUTION_TIME;
private SimulatedExecutionTime executeBatchDmlExecutionTime = NO_EXECUTION_TIME;
private SimulatedExecutionTime executeSqlExecutionTime = NO_EXECUTION_TIME;
private SimulatedExecutionTime executeStreamingSqlExecutionTime = NO_EXECUTION_TIME;
private SimulatedExecutionTime getSessionExecutionTime = NO_EXECUTION_TIME;
private SimulatedExecutionTime listSessionsExecutionTime = NO_EXECUTION_TIME;
private SimulatedExecutionTime partitionQueryExecutionTime = NO_EXECUTION_TIME;
private SimulatedExecutionTime partitionReadExecutionTime = NO_EXECUTION_TIME;
private SimulatedExecutionTime readExecutionTime = NO_EXECUTION_TIME;
private SimulatedExecutionTime rollbackExecutionTime = NO_EXECUTION_TIME;
private SimulatedExecutionTime streamingReadExecutionTime = NO_EXECUTION_TIME;
private String generateSessionName(String database) {
return String.format("%s/sessions/%s", database, UUID.randomUUID().toString());
}
private ByteString generateTransactionName(String session) {
AtomicLong counter = transactionCounters.get(session);
if (counter == null) {
counter = new AtomicLong();
transactionCounters.put(session, counter);
}
return ByteString.copyFromUtf8(
String.format("%s/transactions/%d", session, counter.incrementAndGet()));
}
private ByteString generatePartitionToken(String session, ByteString transactionId) {
ByteString token = ByteString.copyFromUtf8(UUID.randomUUID().toString());
String key = partitionKey(session, transactionId);
List<ByteString> tokens = partitionTokens.get(key);
if (tokens == null) {
tokens = new ArrayList<>(5);
partitionTokens.put(key, tokens);
}
tokens.add(token);
return token;
}
private String partitionKey(String session, ByteString transactionId) {
return String.format("%s/transactions/%s", session, transactionId.toStringUtf8());
}
private Timestamp getCurrentGoogleTimestamp() {
long current = System.currentTimeMillis();
long seconds = TimeUnit.MILLISECONDS.toSeconds(current);
int nanos = (int) TimeUnit.MILLISECONDS.toNanos(current - TimeUnit.SECONDS.toMillis(seconds));
return Timestamp.newBuilder().setSeconds(seconds).setNanos(nanos).build();
}
/**
* Puts a result that will be returned by this service. {@link StatementResult#statement} will be
* used as a key for the result, and any existing {@link StatementResult} for the same {@link
* Statement} will be overwritten.
*/
public void putStatementResult(StatementResult result) {
Preconditions.checkNotNull(result);
statementResults.put(result.statement, result);
}
private StatementResult getResult(Statement statement) {
StatementResult res = statementResults.get(statement);
if (res == null) {
throw Status.INTERNAL
.withDescription(
String.format(
"There is no result registered for the statement: %s\n"
+ "Call TestSpannerImpl#addStatementResult(StatementResult) before executing the statement.",
statement.toString()))
.asRuntimeException();
}
return res;
}
/** Sets the probability that this mock server aborts a read/write transaction at random. */
public void setAbortProbability(double probability) {
Preconditions.checkArgument(
probability >= 0D && probability <= 1D, "Probability must be >= 0 and <= 1");
this.abortProbability = probability;
}
/**
* Instruct the mock server to abort the specified transaction. Use this method to test handling
* of {@link AbortedException} in your code.
*/
public void abortTransaction(TransactionContext transactionContext) {
Preconditions.checkNotNull(transactionContext);
if (transactionContext instanceof TransactionContextImpl) {
TransactionContextImpl impl = (TransactionContextImpl) transactionContext;
ByteString id =
impl.getTransactionSelector() == null ? null : impl.getTransactionSelector().getId();
if (id != null) {
markAbortedTransaction(id);
}
} else {
throw new IllegalArgumentException(
"Unsupported TransactionContext type: " + transactionContext.getClass().getName());
}
}
/** Instruct the mock server to abort the next transaction that is created. */
public void abortNextTransaction() {
abortNextTransaction.set(true);
}
/** Instructs the mock server to abort the transaction of the next statement that is executed. */
public void abortNextStatement() {
abortNextStatement.set(true);
}
/** Instruct the mock server to abort all transactions currently active on the server. */
public void abortAllTransactions() {
for (ByteString id : transactions.keySet()) {
markAbortedTransaction(id);
}
}
public void freeze() {
freezeLock.writeLock().lock();
}
public void unfreeze() {
freezeLock.writeLock().unlock();
}
public void setMaxSessionsInOneBatch(int max) {
this.maxNumSessionsInOneBatch = max;
}
public void setMaxTotalSessions(int max) {
this.maxTotalSessions = max;
}
@Override
public void batchCreateSessions(
BatchCreateSessionsRequest request,
StreamObserver<BatchCreateSessionsResponse> responseObserver) {
requests.add(request);
Preconditions.checkNotNull(request.getDatabase());
String name = null;
try {
if (request.getSessionCount() <= 0) {
throw Status.INVALID_ARGUMENT
.withDescription("Session count must be >= 0")
.asRuntimeException();
}
batchCreateSessionsExecutionTime.simulateExecutionTime(
exceptions, stickyGlobalExceptions, freezeLock);
if (sessions.size() >= maxTotalSessions) {
throw Status.RESOURCE_EXHAUSTED
.withDescription("Maximum number of sessions reached")
.asRuntimeException();
}
Timestamp now = getCurrentGoogleTimestamp();
BatchCreateSessionsResponse.Builder response = BatchCreateSessionsResponse.newBuilder();
int maxSessionsToCreate = Math.min(maxNumSessionsInOneBatch, request.getSessionCount());
for (int i = 0; i < Math.min(maxTotalSessions - sessions.size(), maxSessionsToCreate); i++) {
name = generateSessionName(request.getDatabase());
Session session =
Session.newBuilder()
.setCreateTime(now)
.setName(name)
.setApproximateLastUseTime(now)
.build();
Session prev = sessions.putIfAbsent(name, session);
if (prev == null) {
if (sessions.size() <= maxTotalSessions) {
sessionLastUsed.put(name, Instant.now());
response.addSession(session);
numSessionsCreated.incrementAndGet();
} else {
sessions.remove(name);
}
} else {
// Someone else tried to create a session with the same id. This should not be possible
throw Status.ALREADY_EXISTS.asRuntimeException();
}
}
responseObserver.onNext(response.build());
responseObserver.onCompleted();
} catch (StatusRuntimeException e) {
if (name != null) {
sessions.remove(name);
}
responseObserver.onError(e);
} catch (Throwable e) {
if (name != null) {
sessions.remove(name);
}
responseObserver.onError(
Status.INTERNAL
.withDescription("Batch create sessions failed: " + e.getMessage())
.asRuntimeException());
}
}
@Override
public void createSession(
CreateSessionRequest request, StreamObserver<Session> responseObserver) {
requests.add(request);
Preconditions.checkNotNull(request.getDatabase());
String name = generateSessionName(request.getDatabase());
try {
createSessionExecutionTime.simulateExecutionTime(
exceptions, stickyGlobalExceptions, freezeLock);
Timestamp now = getCurrentGoogleTimestamp();
Session session =
Session.newBuilder()
.setCreateTime(now)
.setName(name)
.setApproximateLastUseTime(now)
.build();
Session prev = sessions.putIfAbsent(name, session);
if (prev == null) {
sessionLastUsed.put(name, Instant.now());
numSessionsCreated.incrementAndGet();
responseObserver.onNext(session);
responseObserver.onCompleted();
} else {
// Someone else tried to create a session with the same id. This should not be possible
responseObserver.onError(Status.ALREADY_EXISTS.asRuntimeException());
}
} catch (StatusRuntimeException e) {
sessions.remove(name);
responseObserver.onError(e);
} catch (Throwable e) {
sessions.remove(name);
responseObserver.onError(
Status.INTERNAL
.withDescription("Create session failed: " + e.getMessage())
.asRuntimeException());
}
}
@Override
public void getSession(GetSessionRequest request, StreamObserver<Session> responseObserver) {
requests.add(request);
Preconditions.checkNotNull(request.getName());
try {
getSessionExecutionTime.simulateExecutionTime(exceptions, stickyGlobalExceptions, freezeLock);
Session session = sessions.get(request.getName());
if (session == null) {
setSessionNotFound(request.getName(), responseObserver);
} else {
session =
session.toBuilder().setApproximateLastUseTime(getCurrentGoogleTimestamp()).build();
responseObserver.onNext(session);
responseObserver.onCompleted();
}
} catch (StatusRuntimeException e) {
responseObserver.onError(e);
} catch (Throwable t) {
responseObserver.onError(Status.INTERNAL.asRuntimeException());
}
}
private <T> void setSessionNotFound(String name, StreamObserver<T> responseObserver) {
ResourceInfo resourceInfo =
ResourceInfo.newBuilder()
.setResourceType(SpannerExceptionFactory.SESSION_RESOURCE_TYPE)
.setResourceName(name)
.build();
Metadata.Key<ResourceInfo> key =
Metadata.Key.of(
resourceInfo.getDescriptorForType().getFullName() + Metadata.BINARY_HEADER_SUFFIX,
ProtoLiteUtils.metadataMarshaller(resourceInfo));
Metadata trailers = new Metadata();
trailers.put(key, resourceInfo);
responseObserver.onError(
Status.NOT_FOUND
.withDescription(String.format("Session not found: Session with id %s not found", name))
.asRuntimeException(trailers));
}
@Override
public void listSessions(
ListSessionsRequest request, StreamObserver<ListSessionsResponse> responseObserver) {
requests.add(request);
try {
listSessionsExecutionTime.simulateExecutionTime(
exceptions, stickyGlobalExceptions, freezeLock);
List<Session> res = new ArrayList<>();
for (Session session : sessions.values()) {
if (session.getName().startsWith(request.getDatabase())) {
res.add(
session.toBuilder().setApproximateLastUseTime(getCurrentGoogleTimestamp()).build());
}
}
Collections.sort(
res,
new Comparator<Session>() {
@Override
public int compare(Session o1, Session o2) {
return o1.getName().compareTo(o2.getName());
}
});
responseObserver.onNext(ListSessionsResponse.newBuilder().addAllSessions(res).build());
responseObserver.onCompleted();
} catch (StatusRuntimeException e) {
responseObserver.onError(e);
} catch (Throwable t) {
responseObserver.onError(Status.INTERNAL.asRuntimeException());
}
}
@Override
public void deleteSession(DeleteSessionRequest request, StreamObserver<Empty> responseObserver) {
requests.add(request);
Preconditions.checkNotNull(request.getName());
try {
deleteSessionExecutionTime.simulateExecutionTime(
exceptions, stickyGlobalExceptions, freezeLock);
Session session = sessions.get(request.getName());
if (session != null) {
try {
doDeleteSession(session);
} catch (Throwable e) {
responseObserver.onError(Status.INTERNAL.asRuntimeException());
return;
}
}
responseObserver.onNext(Empty.getDefaultInstance());
responseObserver.onCompleted();
} catch (StatusRuntimeException e) {
responseObserver.onError(e);
}
}
void doDeleteSession(Session session) {
sessions.remove(session.getName());
transactionCounters.remove(session.getName());
sessionLastUsed.remove(session.getName());
}
@Override
public void executeSql(ExecuteSqlRequest request, StreamObserver<ResultSet> responseObserver) {
requests.add(request);
Preconditions.checkNotNull(request.getSession());
Session session = sessions.get(request.getSession());
if (session == null) {
setSessionNotFound(request.getSession(), responseObserver);
return;
}
sessionLastUsed.put(session.getName(), Instant.now());
try {
executeSqlExecutionTime.simulateExecutionTime(exceptions, stickyGlobalExceptions, freezeLock);
ByteString transactionId = getTransactionId(session, request.getTransaction());
simulateAbort(session, transactionId);
Statement statement =
buildStatement(request.getSql(), request.getParamTypesMap(), request.getParams());
StatementResult result = getResult(statement);
switch (result.getType()) {
case EXCEPTION:
throw result.getException();
case RESULT_SET:
returnResultSet(
result.getResultSet(), transactionId, request.getTransaction(), responseObserver);
break;
case UPDATE_COUNT:
if (isPartitionedDmlTransaction(transactionId)) {
commitTransaction(transactionId);
responseObserver.onNext(
ResultSet.newBuilder()
.setStats(
ResultSetStats.newBuilder()
.setRowCountLowerBound(result.getUpdateCount())
.build())
.build());
} else {
responseObserver.onNext(
ResultSet.newBuilder()
.setStats(
ResultSetStats.newBuilder()
.setRowCountExact(result.getUpdateCount())
.build())
.setMetadata(
ResultSetMetadata.newBuilder()
.setTransaction(Transaction.newBuilder().setId(transactionId).build())
.build())
.build());
}
break;
default:
throw new IllegalStateException("Unknown result type: " + result.getType());
}
responseObserver.onCompleted();
} catch (StatusRuntimeException e) {
responseObserver.onError(e);
} catch (Throwable t) {
responseObserver.onError(Status.INTERNAL.asRuntimeException());
}
}
private ResultSetMetadata createTransactionMetadata(TransactionSelector transactionSelector) {
if (transactionSelector.hasBegin() || transactionSelector.hasSingleUse()) {
Transaction transaction = getTemporaryTransactionOrNull(transactionSelector);
return ResultSetMetadata.newBuilder().setTransaction(transaction).build();
}
return ResultSetMetadata.getDefaultInstance();
}
private void returnResultSet(
ResultSet resultSet,
ByteString transactionId,
TransactionSelector transactionSelector,
StreamObserver<ResultSet> responseObserver) {
ResultSetMetadata metadata = resultSet.getMetadata();
if (transactionId != null) {
metadata =
metadata
.toBuilder()
.setTransaction(Transaction.newBuilder().setId(transactionId).build())
.build();
} else if (transactionSelector.hasBegin() || transactionSelector.hasSingleUse()) {
Transaction transaction = getTemporaryTransactionOrNull(transactionSelector);
metadata = metadata.toBuilder().setTransaction(transaction).build();
}
resultSet = resultSet.toBuilder().setMetadata(metadata).build();
responseObserver.onNext(resultSet);
}
@Override
public void executeBatchDml(
ExecuteBatchDmlRequest request, StreamObserver<ExecuteBatchDmlResponse> responseObserver) {
requests.add(request);
Preconditions.checkNotNull(request.getSession());
Session session = sessions.get(request.getSession());
if (session == null) {
setSessionNotFound(request.getSession(), responseObserver);
return;
}
sessionLastUsed.put(session.getName(), Instant.now());
try {
executeBatchDmlExecutionTime.simulateExecutionTime(
exceptions, stickyGlobalExceptions, freezeLock);
// Get or start transaction
ByteString transactionId = getTransactionId(session, request.getTransaction());
if (isPartitionedDmlTransaction(transactionId)) {
throw Status.FAILED_PRECONDITION
.withDescription(
"This transaction is a partitioned DML transaction and cannot be used for batch DML updates.")
.asRuntimeException();
}
simulateAbort(session, transactionId);
List<StatementResult> results = new ArrayList<>();
com.google.rpc.Status status =
com.google.rpc.Status.newBuilder().setCode(Code.OK_VALUE).build();
resultLoop:
for (com.google.spanner.v1.ExecuteBatchDmlRequest.Statement statement :
request.getStatementsList()) {
try {
Statement spannerStatement =
buildStatement(
statement.getSql(), statement.getParamTypesMap(), statement.getParams());
StatementResult res = getResult(spannerStatement);
switch (res.getType()) {
case EXCEPTION:
status =
com.google.rpc.Status.newBuilder()
.setCode(res.getException().getStatus().getCode().value())
.build();
break resultLoop;
case RESULT_SET:
throw Status.INVALID_ARGUMENT
.withDescription("Not a DML statement: " + statement.getSql())
.asRuntimeException();
case UPDATE_COUNT:
results.add(res);
break;
default:
throw new IllegalStateException("Unknown result type: " + res.getType());
}
} catch (StatusRuntimeException e) {
status =
com.google.rpc.Status.newBuilder()
.setCode(e.getStatus().getCode().value())
.setMessage(e.getMessage())
.build();
break;
} catch (Exception e) {
status =
com.google.rpc.Status.newBuilder()
.setCode(Code.UNKNOWN_VALUE)
.setMessage(e.getMessage())
.build();
break;
}
}
ExecuteBatchDmlResponse.Builder builder = ExecuteBatchDmlResponse.newBuilder();
for (StatementResult res : results) {
builder.addResultSets(
ResultSet.newBuilder()
.setStats(
ResultSetStats.newBuilder().setRowCountExact(res.getUpdateCount()).build())
.setMetadata(createTransactionMetadata(request.getTransaction()))
.build());
}
builder.setStatus(status);
responseObserver.onNext(builder.build());
responseObserver.onCompleted();
} catch (StatusRuntimeException e) {
responseObserver.onError(e);
} catch (Throwable t) {
responseObserver.onError(Status.INTERNAL.asRuntimeException());
}
}
@Override
public void executeStreamingSql(
ExecuteSqlRequest request, StreamObserver<PartialResultSet> responseObserver) {
requests.add(request);
Preconditions.checkNotNull(request.getSession());
Session session = sessions.get(request.getSession());
if (session == null) {
setSessionNotFound(request.getSession(), responseObserver);
return;
}
sessionLastUsed.put(session.getName(), Instant.now());
try {
executeStreamingSqlExecutionTime.simulateExecutionTime(
exceptions, stickyGlobalExceptions, freezeLock);
// Get or start transaction
ByteString transactionId = getTransactionId(session, request.getTransaction());