-
Notifications
You must be signed in to change notification settings - Fork 123
/
SpannerOptions.java
1421 lines (1279 loc) · 56.2 KB
/
SpannerOptions.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 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;
import com.google.api.core.ApiFunction;
import com.google.api.gax.core.ExecutorProvider;
import com.google.api.gax.grpc.GrpcCallContext;
import com.google.api.gax.grpc.GrpcInterceptorProvider;
import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.ApiCallContext;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.cloud.NoCredentials;
import com.google.cloud.ServiceDefaults;
import com.google.cloud.ServiceOptions;
import com.google.cloud.ServiceRpc;
import com.google.cloud.TransportOptions;
import com.google.cloud.grpc.GcpManagedChannelOptions;
import com.google.cloud.grpc.GrpcTransportOptions;
import com.google.cloud.spanner.Options.QueryOption;
import com.google.cloud.spanner.Options.UpdateOption;
import com.google.cloud.spanner.admin.database.v1.DatabaseAdminSettings;
import com.google.cloud.spanner.admin.database.v1.stub.DatabaseAdminStubSettings;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminSettings;
import com.google.cloud.spanner.admin.instance.v1.stub.InstanceAdminStubSettings;
import com.google.cloud.spanner.spi.SpannerRpcFactory;
import com.google.cloud.spanner.spi.v1.GapicSpannerRpc;
import com.google.cloud.spanner.spi.v1.SpannerRpc;
import com.google.cloud.spanner.v1.SpannerSettings;
import com.google.cloud.spanner.v1.stub.SpannerStubSettings;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.spanner.v1.ExecuteSqlRequest;
import com.google.spanner.v1.ExecuteSqlRequest.QueryOptions;
import com.google.spanner.v1.SpannerGrpc;
import io.grpc.CallCredentials;
import io.grpc.CompressorRegistry;
import io.grpc.Context;
import io.grpc.ExperimentalApi;
import io.grpc.ManagedChannelBuilder;
import io.grpc.MethodDescriptor;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.threeten.bp.Duration;
/** Options for the Cloud Spanner service. */
public class SpannerOptions extends ServiceOptions<Spanner, SpannerOptions> {
private static final long serialVersionUID = 2789571558532701170L;
private static SpannerEnvironment environment = SpannerEnvironmentImpl.INSTANCE;
private static final String JDBC_API_CLIENT_LIB_TOKEN = "sp-jdbc";
private static final String HIBERNATE_API_CLIENT_LIB_TOKEN = "sp-hib";
private static final String LIQUIBASE_API_CLIENT_LIB_TOKEN = "sp-liq";
private static final String PG_ADAPTER_CLIENT_LIB_TOKEN = "pg-adapter";
private static final String API_SHORT_NAME = "Spanner";
private static final String DEFAULT_HOST = "https://spanner.googleapis.com";
private static final ImmutableSet<String> SCOPES =
ImmutableSet.of(
"https://www.googleapis.com/auth/spanner.admin",
"https://www.googleapis.com/auth/spanner.data");
private static final int MAX_CHANNELS = 256;
@VisibleForTesting static final int DEFAULT_CHANNELS = 4;
// Set the default number of channels to GRPC_GCP_ENABLED_DEFAULT_CHANNELS when gRPC-GCP extension
// is enabled, to make sure there are sufficient channels available to move the sessions to a
// different channel if a network connection in a particular channel fails.
@VisibleForTesting static final int GRPC_GCP_ENABLED_DEFAULT_CHANNELS = 8;
private final TransportChannelProvider channelProvider;
@SuppressWarnings("rawtypes")
private final ApiFunction<ManagedChannelBuilder, ManagedChannelBuilder> channelConfigurator;
private final GrpcInterceptorProvider interceptorProvider;
private final SessionPoolOptions sessionPoolOptions;
private final int prefetchChunks;
private final int numChannels;
private final String transportChannelExecutorThreadNameFormat;
private final String databaseRole;
private final ImmutableMap<String, String> sessionLabels;
private final SpannerStubSettings spannerStubSettings;
private final InstanceAdminStubSettings instanceAdminStubSettings;
private final DatabaseAdminStubSettings databaseAdminStubSettings;
private final Duration partitionedDmlTimeout;
private final boolean grpcGcpExtensionEnabled;
private final GcpManagedChannelOptions grpcGcpOptions;
private final boolean autoThrottleAdministrativeRequests;
private final RetrySettings retryAdministrativeRequestsSettings;
private final boolean trackTransactionStarter;
/**
* These are the default {@link QueryOptions} defined by the user on this {@link SpannerOptions}.
*/
private final Map<DatabaseId, QueryOptions> defaultQueryOptions;
/** These are the default {@link QueryOptions} defined in environment variables on this system. */
private final QueryOptions envQueryOptions;
/**
* These are the merged query options of the {@link QueryOptions} set on this {@link
* SpannerOptions} and the {@link QueryOptions} in the environment variables. Options specified in
* environment variables take precedence above options specified in the {@link SpannerOptions}
* instance.
*/
private final Map<DatabaseId, QueryOptions> mergedQueryOptions;
private final CallCredentialsProvider callCredentialsProvider;
private final CloseableExecutorProvider asyncExecutorProvider;
private final String compressorName;
private final boolean leaderAwareRoutingEnabled;
/** Interface that can be used to provide {@link CallCredentials} to {@link SpannerOptions}. */
public interface CallCredentialsProvider {
/** Return the {@link CallCredentials} to use for a gRPC call. */
CallCredentials getCallCredentials();
}
/** Context key for the {@link CallContextConfigurator} to use. */
public static final Context.Key<CallContextConfigurator> CALL_CONTEXT_CONFIGURATOR_KEY =
Context.key("call-context-configurator");
/**
* {@link CallContextConfigurator} can be used to modify the {@link ApiCallContext} for one or
* more specific RPCs. This can be used to set specific timeout value for RPCs or use specific
* {@link CallCredentials} for an RPC. The {@link CallContextConfigurator} must be set as a value
* on the {@link Context} using the {@link SpannerOptions#CALL_CONTEXT_CONFIGURATOR_KEY} key.
*
* <p>This API is meant for advanced users. Most users should instead use the {@link
* SpannerCallContextTimeoutConfigurator} for setting timeouts per RPC.
*
* <p>Example usage:
*
* <pre>{@code
* CallContextConfigurator configurator =
* new CallContextConfigurator() {
* public <ReqT, RespT> ApiCallContext configure(
* ApiCallContext context, ReqT request, MethodDescriptor<ReqT, RespT> method) {
* if (method == SpannerGrpc.getExecuteBatchDmlMethod()) {
* return GrpcCallContext.createDefault()
* .withCallOptions(CallOptions.DEFAULT.withDeadlineAfter(60L, TimeUnit.SECONDS));
* }
* return null;
* }
* };
* Context context =
* Context.current().withValue(SpannerOptions.CALL_CONTEXT_CONFIGURATOR_KEY, configurator);
* context.run(
* () -> {
* try {
* client
* .readWriteTransaction()
* .run(
* new TransactionCallable<long[]>() {
* public long[] run(TransactionContext transaction) throws Exception {
* return transaction.batchUpdate(
* ImmutableList.of(statement1, statement2));
* }
* });
* } catch (SpannerException e) {
* if (e.getErrorCode() == ErrorCode.DEADLINE_EXCEEDED) {
* // handle timeout exception.
* }
* }
* }
* }</pre>
*/
public interface CallContextConfigurator {
/**
* Configure a {@link ApiCallContext} for a specific RPC call.
*
* @param context The default context. This can be used to inspect the current values.
* @param request The request that will be sent.
* @param method The method that is being called.
* @return An {@link ApiCallContext} that will be merged with the default {@link
* ApiCallContext}. If <code>null</code> is returned, no changes to the default {@link
* ApiCallContext} will be made.
*/
@Nullable
<ReqT, RespT> ApiCallContext configure(
ApiCallContext context, ReqT request, MethodDescriptor<ReqT, RespT> method);
}
private enum SpannerMethod {
COMMIT {
@Override
<ReqT, RespT> boolean isMethod(ReqT request, MethodDescriptor<ReqT, RespT> method) {
return method == SpannerGrpc.getCommitMethod();
}
},
ROLLBACK {
@Override
<ReqT, RespT> boolean isMethod(ReqT request, MethodDescriptor<ReqT, RespT> method) {
return method == SpannerGrpc.getRollbackMethod();
}
},
EXECUTE_QUERY {
@Override
<ReqT, RespT> boolean isMethod(ReqT request, MethodDescriptor<ReqT, RespT> method) {
// This also matches with Partitioned DML calls, but that call will override any timeout
// settings anyway.
return method == SpannerGrpc.getExecuteStreamingSqlMethod();
}
},
READ {
@Override
<ReqT, RespT> boolean isMethod(ReqT request, MethodDescriptor<ReqT, RespT> method) {
return method == SpannerGrpc.getStreamingReadMethod();
}
},
EXECUTE_UPDATE {
@Override
<ReqT, RespT> boolean isMethod(ReqT request, MethodDescriptor<ReqT, RespT> method) {
if (method == SpannerGrpc.getExecuteSqlMethod()) {
ExecuteSqlRequest sqlRequest = (ExecuteSqlRequest) request;
return sqlRequest.getSeqno() != 0L;
}
return false;
}
},
BATCH_UPDATE {
@Override
<ReqT, RespT> boolean isMethod(ReqT request, MethodDescriptor<ReqT, RespT> method) {
return method == SpannerGrpc.getExecuteBatchDmlMethod();
}
},
PARTITION_QUERY {
@Override
<ReqT, RespT> boolean isMethod(ReqT request, MethodDescriptor<ReqT, RespT> method) {
return method == SpannerGrpc.getPartitionQueryMethod();
}
},
PARTITION_READ {
@Override
<ReqT, RespT> boolean isMethod(ReqT request, MethodDescriptor<ReqT, RespT> method) {
return method == SpannerGrpc.getPartitionReadMethod();
}
};
abstract <ReqT, RespT> boolean isMethod(ReqT request, MethodDescriptor<ReqT, RespT> method);
static <ReqT, RespT> SpannerMethod valueOf(ReqT request, MethodDescriptor<ReqT, RespT> method) {
for (SpannerMethod m : SpannerMethod.values()) {
if (m.isMethod(request, method)) {
return m;
}
}
return null;
}
}
/**
* Helper class to configure timeouts for specific Spanner RPCs. The {@link
* SpannerCallContextTimeoutConfigurator} must be set as a value on the {@link Context} using the
* {@link SpannerOptions#CALL_CONTEXT_CONFIGURATOR_KEY} key.
*
* <p>Example usage:
*
* <pre>{@code
* // Create a context with a ExecuteQuery timeout of 10 seconds.
* Context context =
* Context.current()
* .withValue(
* SpannerOptions.CALL_CONTEXT_CONFIGURATOR_KEY,
* SpannerCallContextTimeoutConfigurator.create()
* .withExecuteQueryTimeout(Duration.ofSeconds(10L)));
* context.run(
* () -> {
* try (ResultSet rs =
* client
* .singleUse()
* .executeQuery(
* Statement.of(
* "SELECT SingerId, FirstName, LastName FROM Singers ORDER BY LastName"))) {
* while (rs.next()) {
* System.out.printf("%d %s %s%n", rs.getLong(0), rs.getString(1), rs.getString(2));
* }
* } catch (SpannerException e) {
* if (e.getErrorCode() == ErrorCode.DEADLINE_EXCEEDED) {
* // Handle timeout.
* }
* }
* }
* }</pre>
*/
public static class SpannerCallContextTimeoutConfigurator implements CallContextConfigurator {
private Duration commitTimeout;
private Duration rollbackTimeout;
private Duration executeQueryTimeout;
private Duration executeUpdateTimeout;
private Duration batchUpdateTimeout;
private Duration readTimeout;
private Duration partitionQueryTimeout;
private Duration partitionReadTimeout;
public static SpannerCallContextTimeoutConfigurator create() {
return new SpannerCallContextTimeoutConfigurator();
}
private SpannerCallContextTimeoutConfigurator() {}
@Override
public <ReqT, RespT> ApiCallContext configure(
ApiCallContext context, ReqT request, MethodDescriptor<ReqT, RespT> method) {
SpannerMethod spannerMethod = SpannerMethod.valueOf(request, method);
if (spannerMethod == null) {
return null;
}
switch (SpannerMethod.valueOf(request, method)) {
case BATCH_UPDATE:
return batchUpdateTimeout == null
? null
: GrpcCallContext.createDefault().withTimeout(batchUpdateTimeout);
case COMMIT:
return commitTimeout == null
? null
: GrpcCallContext.createDefault().withTimeout(commitTimeout);
case EXECUTE_QUERY:
return executeQueryTimeout == null
? null
: GrpcCallContext.createDefault()
.withTimeout(executeQueryTimeout)
.withStreamWaitTimeout(executeQueryTimeout);
case EXECUTE_UPDATE:
return executeUpdateTimeout == null
? null
: GrpcCallContext.createDefault().withTimeout(executeUpdateTimeout);
case PARTITION_QUERY:
return partitionQueryTimeout == null
? null
: GrpcCallContext.createDefault().withTimeout(partitionQueryTimeout);
case PARTITION_READ:
return partitionReadTimeout == null
? null
: GrpcCallContext.createDefault().withTimeout(partitionReadTimeout);
case READ:
return readTimeout == null
? null
: GrpcCallContext.createDefault()
.withTimeout(readTimeout)
.withStreamWaitTimeout(readTimeout);
case ROLLBACK:
return rollbackTimeout == null
? null
: GrpcCallContext.createDefault().withTimeout(rollbackTimeout);
default:
}
return null;
}
public Duration getCommitTimeout() {
return commitTimeout;
}
public SpannerCallContextTimeoutConfigurator withCommitTimeout(Duration commitTimeout) {
this.commitTimeout = commitTimeout;
return this;
}
public Duration getRollbackTimeout() {
return rollbackTimeout;
}
public SpannerCallContextTimeoutConfigurator withRollbackTimeout(Duration rollbackTimeout) {
this.rollbackTimeout = rollbackTimeout;
return this;
}
public Duration getExecuteQueryTimeout() {
return executeQueryTimeout;
}
public SpannerCallContextTimeoutConfigurator withExecuteQueryTimeout(
Duration executeQueryTimeout) {
this.executeQueryTimeout = executeQueryTimeout;
return this;
}
public Duration getExecuteUpdateTimeout() {
return executeUpdateTimeout;
}
public SpannerCallContextTimeoutConfigurator withExecuteUpdateTimeout(
Duration executeUpdateTimeout) {
this.executeUpdateTimeout = executeUpdateTimeout;
return this;
}
public Duration getBatchUpdateTimeout() {
return batchUpdateTimeout;
}
public SpannerCallContextTimeoutConfigurator withBatchUpdateTimeout(
Duration batchUpdateTimeout) {
this.batchUpdateTimeout = batchUpdateTimeout;
return this;
}
public Duration getReadTimeout() {
return readTimeout;
}
public SpannerCallContextTimeoutConfigurator withReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
return this;
}
public Duration getPartitionQueryTimeout() {
return partitionQueryTimeout;
}
public SpannerCallContextTimeoutConfigurator withPartitionQueryTimeout(
Duration partitionQueryTimeout) {
this.partitionQueryTimeout = partitionQueryTimeout;
return this;
}
public Duration getPartitionReadTimeout() {
return partitionReadTimeout;
}
public SpannerCallContextTimeoutConfigurator withPartitionReadTimeout(
Duration partitionReadTimeout) {
this.partitionReadTimeout = partitionReadTimeout;
return this;
}
}
/** Default implementation of {@code SpannerFactory}. */
private static class DefaultSpannerFactory implements SpannerFactory {
private static final DefaultSpannerFactory INSTANCE = new DefaultSpannerFactory();
@Override
public Spanner create(SpannerOptions serviceOptions) {
return new SpannerImpl(serviceOptions);
}
}
/** Default implementation of {@code SpannerRpcFactory}. */
private static class DefaultSpannerRpcFactory implements SpannerRpcFactory {
private static final DefaultSpannerRpcFactory INSTANCE = new DefaultSpannerRpcFactory();
@Override
public ServiceRpc create(SpannerOptions options) {
return new GapicSpannerRpc(options);
}
}
private static final AtomicInteger DEFAULT_POOL_COUNT = new AtomicInteger();
/** {@link ExecutorProvider} that is used for {@link AsyncResultSet}. */
public interface CloseableExecutorProvider extends ExecutorProvider, AutoCloseable {
/** Overridden to suppress the throws declaration of the super interface. */
@Override
void close();
}
/**
* Implementation of {@link CloseableExecutorProvider} that uses a fixed single {@link
* ScheduledExecutorService}.
*/
public static class FixedCloseableExecutorProvider implements CloseableExecutorProvider {
private final ScheduledExecutorService executor;
private FixedCloseableExecutorProvider(ScheduledExecutorService executor) {
this.executor = Preconditions.checkNotNull(executor);
}
@Override
public void close() {
executor.shutdown();
}
@Override
public ScheduledExecutorService getExecutor() {
return executor;
}
@Override
public boolean shouldAutoClose() {
return false;
}
/** Creates a FixedCloseableExecutorProvider. */
public static FixedCloseableExecutorProvider create(ScheduledExecutorService executor) {
return new FixedCloseableExecutorProvider(executor);
}
}
/**
* Default {@link ExecutorProvider} for high-level async calls that need an executor. The default
* uses a cached thread pool containing a max of 8 threads. The pool is lazily initialized and
* will not create any threads if the user application does not use any async methods. It will
* also scale down the thread usage if the async load allows for that.
*/
@VisibleForTesting
static CloseableExecutorProvider createDefaultAsyncExecutorProvider() {
return createAsyncExecutorProvider(8, 60L, TimeUnit.SECONDS);
}
/**
* Creates a {@link CloseableExecutorProvider} that can be used as an {@link ExecutorProvider} for
* the async API. The {@link ExecutorProvider} will lazily create up to poolSize threads. The
* backing threads will automatically be shutdown if they have not been used during the keep-alive
* time. The backing threads are created as daemon threads.
*
* @param poolSize the maximum number of threads to create in the pool
* @param keepAliveTime the time that an unused thread in the pool should be kept alive
* @param unit the time unit used for the keepAliveTime
* @return a {@link CloseableExecutorProvider} that can be used for {@link
* SpannerOptions.Builder#setAsyncExecutorProvider(CloseableExecutorProvider)}
*/
public static CloseableExecutorProvider createAsyncExecutorProvider(
int poolSize, long keepAliveTime, TimeUnit unit) {
String format =
String.format("spanner-async-pool-%d-thread-%%d", DEFAULT_POOL_COUNT.incrementAndGet());
ThreadFactory threadFactory =
new ThreadFactoryBuilder().setDaemon(true).setNameFormat(format).build();
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(poolSize, threadFactory);
executor.setKeepAliveTime(keepAliveTime, unit);
executor.allowCoreThreadTimeOut(true);
return FixedCloseableExecutorProvider.create(executor);
}
private SpannerOptions(Builder builder) {
super(SpannerFactory.class, SpannerRpcFactory.class, builder, new SpannerDefaults());
numChannels = builder.numChannels;
Preconditions.checkArgument(
numChannels >= 1 && numChannels <= MAX_CHANNELS,
"Number of channels must fall in the range [1, %s], found: %s",
MAX_CHANNELS,
numChannels);
transportChannelExecutorThreadNameFormat = builder.transportChannelExecutorThreadNameFormat;
channelProvider = builder.channelProvider;
channelConfigurator = builder.channelConfigurator;
interceptorProvider = builder.interceptorProvider;
sessionPoolOptions =
builder.sessionPoolOptions != null
? builder.sessionPoolOptions
: SessionPoolOptions.newBuilder().build();
prefetchChunks = builder.prefetchChunks;
databaseRole = builder.databaseRole;
sessionLabels = builder.sessionLabels;
try {
spannerStubSettings = builder.spannerStubSettingsBuilder.build();
instanceAdminStubSettings = builder.instanceAdminStubSettingsBuilder.build();
databaseAdminStubSettings = builder.databaseAdminStubSettingsBuilder.build();
} catch (IOException e) {
throw SpannerExceptionFactory.newSpannerException(e);
}
partitionedDmlTimeout = builder.partitionedDmlTimeout;
grpcGcpExtensionEnabled = builder.grpcGcpExtensionEnabled;
grpcGcpOptions = builder.grpcGcpOptions;
autoThrottleAdministrativeRequests = builder.autoThrottleAdministrativeRequests;
retryAdministrativeRequestsSettings = builder.retryAdministrativeRequestsSettings;
trackTransactionStarter = builder.trackTransactionStarter;
defaultQueryOptions = builder.defaultQueryOptions;
envQueryOptions = builder.getEnvironmentQueryOptions();
if (envQueryOptions.equals(QueryOptions.getDefaultInstance())) {
this.mergedQueryOptions = ImmutableMap.copyOf(builder.defaultQueryOptions);
} else {
// Merge all specific database options with the environment options.
Map<DatabaseId, QueryOptions> merged = new HashMap<>(builder.defaultQueryOptions);
for (Entry<DatabaseId, QueryOptions> entry : builder.defaultQueryOptions.entrySet()) {
merged.put(entry.getKey(), entry.getValue().toBuilder().mergeFrom(envQueryOptions).build());
}
this.mergedQueryOptions = ImmutableMap.copyOf(merged);
}
callCredentialsProvider = builder.callCredentialsProvider;
asyncExecutorProvider = builder.asyncExecutorProvider;
compressorName = builder.compressorName;
leaderAwareRoutingEnabled = builder.leaderAwareRoutingEnabled;
}
/**
* The environment to read configuration values from. The default implementation uses environment
* variables.
*/
public interface SpannerEnvironment {
/**
* The optimizer version to use. Must return an empty string to indicate that no value has been
* set.
*/
@Nonnull
String getOptimizerVersion();
/**
* The optimizer statistics package to use. Must return an empty string to indicate that no
* value has been set.
*/
@Nonnull
default String getOptimizerStatisticsPackage() {
throw new UnsupportedOperationException("Unimplemented");
}
}
/**
* Default implementation of {@link SpannerEnvironment}. Reads all configuration from environment
* variables.
*/
private static class SpannerEnvironmentImpl implements SpannerEnvironment {
private static final SpannerEnvironmentImpl INSTANCE = new SpannerEnvironmentImpl();
private static final String SPANNER_OPTIMIZER_VERSION_ENV_VAR = "SPANNER_OPTIMIZER_VERSION";
private static final String SPANNER_OPTIMIZER_STATISTICS_PACKAGE_ENV_VAR =
"SPANNER_OPTIMIZER_STATISTICS_PACKAGE";
private SpannerEnvironmentImpl() {}
@Override
public String getOptimizerVersion() {
return MoreObjects.firstNonNull(System.getenv(SPANNER_OPTIMIZER_VERSION_ENV_VAR), "");
}
@Override
public String getOptimizerStatisticsPackage() {
return MoreObjects.firstNonNull(
System.getenv(SPANNER_OPTIMIZER_STATISTICS_PACKAGE_ENV_VAR), "");
}
}
/** Builder for {@link SpannerOptions} instances. */
public static class Builder
extends ServiceOptions.Builder<Spanner, SpannerOptions, SpannerOptions.Builder> {
static final int DEFAULT_PREFETCH_CHUNKS = 4;
static final QueryOptions DEFAULT_QUERY_OPTIONS = QueryOptions.getDefaultInstance();
static final RetrySettings DEFAULT_ADMIN_REQUESTS_LIMIT_EXCEEDED_RETRY_SETTINGS =
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofSeconds(5L))
.setRetryDelayMultiplier(2.0)
.setMaxRetryDelay(Duration.ofSeconds(60L))
.setMaxAttempts(10)
.build();
private final ImmutableSet<String> allowedClientLibTokens =
ImmutableSet.of(
ServiceOptions.getGoogApiClientLibName(),
JDBC_API_CLIENT_LIB_TOKEN,
HIBERNATE_API_CLIENT_LIB_TOKEN,
LIQUIBASE_API_CLIENT_LIB_TOKEN,
PG_ADAPTER_CLIENT_LIB_TOKEN);
private TransportChannelProvider channelProvider;
@SuppressWarnings("rawtypes")
private ApiFunction<ManagedChannelBuilder, ManagedChannelBuilder> channelConfigurator;
private GrpcInterceptorProvider interceptorProvider;
private Integer numChannels;
private String transportChannelExecutorThreadNameFormat = "Cloud-Spanner-TransportChannel-%d";
private int prefetchChunks = DEFAULT_PREFETCH_CHUNKS;
private SessionPoolOptions sessionPoolOptions;
private String databaseRole;
private ImmutableMap<String, String> sessionLabels;
private SpannerStubSettings.Builder spannerStubSettingsBuilder =
SpannerStubSettings.newBuilder();
private InstanceAdminStubSettings.Builder instanceAdminStubSettingsBuilder =
InstanceAdminStubSettings.newBuilder();
private DatabaseAdminStubSettings.Builder databaseAdminStubSettingsBuilder =
DatabaseAdminStubSettings.newBuilder();
private Duration partitionedDmlTimeout = Duration.ofHours(2L);
private boolean grpcGcpExtensionEnabled = false;
private GcpManagedChannelOptions grpcGcpOptions;
private RetrySettings retryAdministrativeRequestsSettings =
DEFAULT_ADMIN_REQUESTS_LIMIT_EXCEEDED_RETRY_SETTINGS;
private boolean autoThrottleAdministrativeRequests = false;
private boolean trackTransactionStarter = false;
private Map<DatabaseId, QueryOptions> defaultQueryOptions = new HashMap<>();
private CallCredentialsProvider callCredentialsProvider;
private CloseableExecutorProvider asyncExecutorProvider;
private String compressorName;
private String emulatorHost = System.getenv("SPANNER_EMULATOR_HOST");
private boolean leaderAwareRoutingEnabled = true;
private Builder() {
// Manually set retry and polling settings that work.
OperationTimedPollAlgorithm longRunningPollingAlgorithm =
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRpcTimeout(Duration.ofSeconds(60L))
.setMaxRpcTimeout(Duration.ofSeconds(600L))
.setInitialRetryDelay(Duration.ofSeconds(20L))
.setMaxRetryDelay(Duration.ofSeconds(45L))
.setRetryDelayMultiplier(1.5)
.setRpcTimeoutMultiplier(1.5)
.setTotalTimeout(Duration.ofHours(48L))
.build());
databaseAdminStubSettingsBuilder
.createDatabaseOperationSettings()
.setPollingAlgorithm(longRunningPollingAlgorithm);
databaseAdminStubSettingsBuilder
.createBackupOperationSettings()
.setPollingAlgorithm(longRunningPollingAlgorithm);
databaseAdminStubSettingsBuilder
.restoreDatabaseOperationSettings()
.setPollingAlgorithm(longRunningPollingAlgorithm);
}
Builder(SpannerOptions options) {
super(options);
if (options.getHost() != null
&& this.emulatorHost != null
&& !options.getHost().equals(this.emulatorHost)) {
this.emulatorHost = null;
}
this.numChannels = options.numChannels;
this.transportChannelExecutorThreadNameFormat =
options.transportChannelExecutorThreadNameFormat;
this.sessionPoolOptions = options.sessionPoolOptions;
this.prefetchChunks = options.prefetchChunks;
this.databaseRole = options.databaseRole;
this.sessionLabels = options.sessionLabels;
this.spannerStubSettingsBuilder = options.spannerStubSettings.toBuilder();
this.instanceAdminStubSettingsBuilder = options.instanceAdminStubSettings.toBuilder();
this.databaseAdminStubSettingsBuilder = options.databaseAdminStubSettings.toBuilder();
this.partitionedDmlTimeout = options.partitionedDmlTimeout;
this.grpcGcpExtensionEnabled = options.grpcGcpExtensionEnabled;
this.grpcGcpOptions = options.grpcGcpOptions;
this.autoThrottleAdministrativeRequests = options.autoThrottleAdministrativeRequests;
this.retryAdministrativeRequestsSettings = options.retryAdministrativeRequestsSettings;
this.trackTransactionStarter = options.trackTransactionStarter;
this.defaultQueryOptions = options.defaultQueryOptions;
this.callCredentialsProvider = options.callCredentialsProvider;
this.asyncExecutorProvider = options.asyncExecutorProvider;
this.compressorName = options.compressorName;
this.channelProvider = options.channelProvider;
this.channelConfigurator = options.channelConfigurator;
this.interceptorProvider = options.interceptorProvider;
}
@Override
public Builder setTransportOptions(TransportOptions transportOptions) {
if (!(transportOptions instanceof GrpcTransportOptions)) {
throw new IllegalArgumentException(
"Only grpc transport is allowed for " + API_SHORT_NAME + ".");
}
return super.setTransportOptions(transportOptions);
}
@Override
protected Set<String> getAllowedClientLibTokens() {
return allowedClientLibTokens;
}
/**
* Sets the {@code ChannelProvider}. {@link GapicSpannerRpc} would create a default one if none
* is provided.
*
* <p>Setting a custom {@link TransportChannelProvider} also overrides any other settings that
* affect the default channel provider. These must be set manually on the custom {@link
* TransportChannelProvider} instead of on {@link SpannerOptions}. The settings of {@link
* SpannerOptions} that have no effect if you set a custom {@link TransportChannelProvider} are:
*
* <ol>
* <li>{@link #setChannelConfigurator(ApiFunction)}
* <li>{@link #setHost(String)}
* <li>{@link #setNumChannels(int)}
* <li>{@link #setInterceptorProvider(GrpcInterceptorProvider)}
* <li>{@link #setHeaderProvider(com.google.api.gax.rpc.HeaderProvider)}
* </ol>
*/
public Builder setChannelProvider(TransportChannelProvider channelProvider) {
this.channelProvider = channelProvider;
return this;
}
/**
* Sets an {@link ApiFunction} that will be used to configure the transport channel. This will
* only be used if no custom {@link TransportChannelProvider} has been set.
*/
public Builder setChannelConfigurator(
@SuppressWarnings("rawtypes")
ApiFunction<ManagedChannelBuilder, ManagedChannelBuilder> channelConfigurator) {
this.channelConfigurator = channelConfigurator;
return this;
}
/**
* Sets the {@code GrpcInterceptorProvider}. {@link GapicSpannerRpc} would create a default one
* if none is provided.
*/
public Builder setInterceptorProvider(GrpcInterceptorProvider interceptorProvider) {
this.interceptorProvider = interceptorProvider;
return this;
}
/**
* Sets the number of gRPC channels to use. By default 4 channels are created per {@link
* SpannerOptions}.
*/
public Builder setNumChannels(int numChannels) {
this.numChannels = numChannels;
return this;
}
/** Sets the name format for transport channel threads that should be used by this instance. */
Builder setTransportChannelExecutorThreadNameFormat(
String transportChannelExecutorThreadNameFormat) {
this.transportChannelExecutorThreadNameFormat = transportChannelExecutorThreadNameFormat;
return this;
}
/**
* Sets the options for managing the session pool. If not specified then the default {@code
* SessionPoolOptions} is used.
*/
public Builder setSessionPoolOption(SessionPoolOptions sessionPoolOptions) {
this.sessionPoolOptions = sessionPoolOptions;
return this;
}
/**
* Sets the database role that should be used for connections that are created by this instance.
* The database role that is used determines the access permissions that a connection has. This
* can for example be used to create connections that are only permitted to access certain
* tables.
*/
public Builder setDatabaseRole(String databaseRole) {
this.databaseRole = databaseRole;
return this;
}
/**
* Sets the labels to add to all Sessions created in this client.
*
* @param sessionLabels Map from label key to label value. Label key and value cannot be null.
* For more information on valid syntax see <a
* href="https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Session">
* api docs </a>.
*/
public Builder setSessionLabels(Map<String, String> sessionLabels) {
Preconditions.checkNotNull(sessionLabels, "Session labels map cannot be null");
for (String value : sessionLabels.values()) {
Preconditions.checkNotNull(value, "Null values are not allowed in the labels map.");
}
this.sessionLabels = ImmutableMap.copyOf(sessionLabels);
return this;
}
/**
* {@link SpannerOptions.Builder} does not support global retry settings, as it creates three
* different gRPC clients: {@link Spanner}, {@link DatabaseAdminClient} and {@link
* InstanceAdminClient}. Instead of calling this method, you should set specific {@link
* RetrySettings} for each of the underlying gRPC clients by calling respectively {@link
* #getSpannerStubSettingsBuilder()}, {@link #getDatabaseAdminStubSettingsBuilder()} or {@link
* #getInstanceAdminStubSettingsBuilder()}.
*/
@Override
public Builder setRetrySettings(RetrySettings retrySettings) {
throw new UnsupportedOperationException(
"SpannerOptions does not support setting global retry settings. "
+ "Call spannerStubSettingsBuilder().<method-name>Settings().setRetrySettings(RetrySettings) instead.");
}
/**
* Returns the {@link SpannerStubSettings.Builder} that will be used to build the {@link
* SpannerRpc}. Use this to set custom {@link RetrySettings} for individual gRPC methods.
*
* <p>The library will automatically use the defaults defined in {@link SpannerStubSettings} if
* no custom settings are set. The defaults are the same as the defaults that are used by {@link
* SpannerSettings}, and are generated from the file <a
* href="https://github.com/googleapis/googleapis/blob/master/google/spanner/v1/spanner_gapic.yaml">spanner_gapic.yaml</a>.
* Retries are configured for idempotent methods but not for non-idempotent methods.
*
* <p>You can set the same {@link RetrySettings} for all unary methods by calling this:
*
* <pre><code>
* builder
* .getSpannerStubSettingsBuilder()
* .applyToAllUnaryMethods(
* new ApiFunction<UnaryCallSettings.Builder<?, ?>, Void>() {
* public Void apply(Builder<?, ?> input) {
* input.setRetrySettings(retrySettings);
* return null;
* }
* });
* </code></pre>
*/
public SpannerStubSettings.Builder getSpannerStubSettingsBuilder() {
return spannerStubSettingsBuilder;
}
/**
* Returns the {@link InstanceAdminStubSettings.Builder} that will be used to build the {@link
* SpannerRpc}. Use this to set custom {@link RetrySettings} for individual gRPC methods.
*
* <p>The library will automatically use the defaults defined in {@link
* InstanceAdminStubSettings} if no custom settings are set. The defaults are the same as the
* defaults that are used by {@link InstanceAdminSettings}, and are generated from the file <a
* href="https://github.com/googleapis/googleapis/blob/master/google/spanner/admin/instance/v1/spanner_admin_instance_gapic.yaml">spanner_admin_instance_gapic.yaml</a>.
* Retries are configured for idempotent methods but not for non-idempotent methods.
*
* <p>You can set the same {@link RetrySettings} for all unary methods by calling this:
*
* <pre><code>
* builder
* .getInstanceAdminStubSettingsBuilder()
* .applyToAllUnaryMethods(
* new ApiFunction<UnaryCallSettings.Builder<?, ?>, Void>() {
* public Void apply(Builder<?, ?> input) {
* input.setRetrySettings(retrySettings);
* return null;
* }
* });
* </code></pre>
*/
public InstanceAdminStubSettings.Builder getInstanceAdminStubSettingsBuilder() {
return instanceAdminStubSettingsBuilder;
}
/**
* Returns the {@link DatabaseAdminStubSettings.Builder} that will be used to build the {@link
* SpannerRpc}. Use this to set custom {@link RetrySettings} for individual gRPC methods.
*
* <p>The library will automatically use the defaults defined in {@link
* DatabaseAdminStubSettings} if no custom settings are set. The defaults are the same as the
* defaults that are used by {@link DatabaseAdminSettings}, and are generated from the file <a
* href="https://github.com/googleapis/googleapis/blob/master/google/spanner/admin/database/v1/spanner_admin_database_gapic.yaml">spanner_admin_database_gapic.yaml</a>.
* Retries are configured for idempotent methods but not for non-idempotent methods.
*
* <p>You can set the same {@link RetrySettings} for all unary methods by calling this:
*
* <pre><code>
* builder
* .getDatabaseAdminStubSettingsBuilder()
* .applyToAllUnaryMethods(
* new ApiFunction<UnaryCallSettings.Builder<?, ?>, Void>() {
* public Void apply(Builder<?, ?> input) {
* input.setRetrySettings(retrySettings);
* return null;
* }
* });
* </code></pre>
*/
public DatabaseAdminStubSettings.Builder getDatabaseAdminStubSettingsBuilder() {
return databaseAdminStubSettingsBuilder;
}
/**
* Sets a timeout specifically for Partitioned DML statements executed through {@link
* DatabaseClient#executePartitionedUpdate(Statement, UpdateOption...)}. The default is 2 hours.
*/
public Builder setPartitionedDmlTimeout(Duration timeout) {
this.partitionedDmlTimeout = timeout;
return this;
}
/**
* Instructs the client library to automatically throttle the number of administrative requests
* if the rate of administrative requests generated by this {@link Spanner} instance will exceed
* the administrative limits Cloud Spanner. The default behavior is to not throttle any
* requests. If the limit is exceeded, Cloud Spanner will return a RESOURCE_EXHAUSTED error.
* More information on the administrative limits can be found here:
* https://cloud.google.com/spanner/quotas#administrative_limits. Setting this option is not a
* guarantee that the rate will never be exceeded, as this option will only throttle requests
* coming from this client. Additional requests from other clients could still cause the limit
* to be exceeded.
*/
public Builder setAutoThrottleAdministrativeRequests() {
this.autoThrottleAdministrativeRequests = true;
return this;
}
/**
* Disables automatic retries of administrative requests that fail if the <a
* href="https://cloud.google.com/spanner/quotas#administrative_limits">https://cloud.google.com/spanner/quotas#administrative_limits</a>
* have been exceeded. You should disable these retries if you intend to handle these errors in
* your application.
*/
public Builder disableAdministrativeRequestRetries() {