-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathSpannerOptions.java
2073 lines (1857 loc) · 82 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 static com.google.api.gax.util.TimeConversionUtils.toJavaTimeDuration;
import static com.google.api.gax.util.TimeConversionUtils.toThreetenDuration;
import com.google.api.core.ApiFunction;
import com.google.api.core.BetaApi;
import com.google.api.core.InternalApi;
import com.google.api.core.ObsoleteApi;
import com.google.api.gax.core.ExecutorProvider;
import com.google.api.gax.core.GaxProperties;
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.api.gax.tracing.ApiTracerFactory;
import com.google.api.gax.tracing.BaseApiTracerFactory;
import com.google.api.gax.tracing.MetricsTracerFactory;
import com.google.api.gax.tracing.OpenTelemetryMetricsRecorder;
import com.google.api.gax.tracing.OpencensusTracerFactory;
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.DirectedReadOption;
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.DirectedReadOptions;
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 io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.Attributes;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
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 javax.annotation.concurrent.GuardedBy;
/** 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 boolean enableOpenCensusMetrics = true;
private static boolean enableOpenTelemetryMetrics = false;
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");
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 DecodeMode decodeMode;
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;
private final BuiltInOpenTelemetryMetricsProvider builtInOpenTelemetryMetricsProvider =
BuiltInOpenTelemetryMetricsProvider.INSTANCE;
/**
* 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;
private final boolean attemptDirectPath;
private final DirectedReadOptions directedReadOptions;
private final boolean useVirtualThreads;
private final OpenTelemetry openTelemetry;
private final boolean enableApiTracing;
private final boolean enableBuiltInMetrics;
private final boolean enableExtendedTracing;
private final boolean enableEndToEndTracing;
private final String monitoringHost;
enum TracingFramework {
OPEN_CENSUS,
OPEN_TELEMETRY
}
private static final Object lock = new Object();
@GuardedBy("lock")
private static TracingFramework activeTracingFramework;
/** 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().withTimeoutDuration(batchUpdateTimeout);
case COMMIT:
return commitTimeout == null
? null
: GrpcCallContext.createDefault().withTimeoutDuration(commitTimeout);
case EXECUTE_QUERY:
return executeQueryTimeout == null
? null
: GrpcCallContext.createDefault()
.withTimeoutDuration(executeQueryTimeout)
.withStreamWaitTimeoutDuration(executeQueryTimeout);
case EXECUTE_UPDATE:
return executeUpdateTimeout == null
? null
: GrpcCallContext.createDefault().withTimeoutDuration(executeUpdateTimeout);
case PARTITION_QUERY:
return partitionQueryTimeout == null
? null
: GrpcCallContext.createDefault().withTimeoutDuration(partitionQueryTimeout);
case PARTITION_READ:
return partitionReadTimeout == null
? null
: GrpcCallContext.createDefault().withTimeoutDuration(partitionReadTimeout);
case READ:
return readTimeout == null
? null
: GrpcCallContext.createDefault()
.withTimeoutDuration(readTimeout)
.withStreamWaitTimeoutDuration(readTimeout);
case ROLLBACK:
return rollbackTimeout == null
? null
: GrpcCallContext.createDefault().withTimeoutDuration(rollbackTimeout);
default:
}
return null;
}
/** This method is obsolete. Use {@link #getCommitTimeoutDuration()} instead. */
@ObsoleteApi("Use getCommitTimeoutDuration() instead.")
public org.threeten.bp.Duration getCommitTimeout() {
return toThreetenDuration(getCommitTimeoutDuration());
}
public Duration getCommitTimeoutDuration() {
return commitTimeout;
}
/** This method is obsolete. Use {@link #withCommitTimeoutDuration(Duration)} instead. */
@ObsoleteApi("Use withCommitTimeoutDuration() instead.")
public SpannerCallContextTimeoutConfigurator withCommitTimeout(
org.threeten.bp.Duration commitTimeout) {
return withCommitTimeoutDuration(toJavaTimeDuration(commitTimeout));
}
public SpannerCallContextTimeoutConfigurator withCommitTimeoutDuration(Duration commitTimeout) {
this.commitTimeout = commitTimeout;
return this;
}
/** This method is obsolete. Use {@link #getRollbackTimeoutDuration()} instead. */
@ObsoleteApi("Use getRollbackTimeoutDuration() instead.")
public org.threeten.bp.Duration getRollbackTimeout() {
return toThreetenDuration(getRollbackTimeoutDuration());
}
public Duration getRollbackTimeoutDuration() {
return rollbackTimeout;
}
/** This method is obsolete. Use {@link #withRollbackTimeoutDuration(Duration)} instead. */
@ObsoleteApi("Use withRollbackTimeoutDuration() instead.")
public SpannerCallContextTimeoutConfigurator withRollbackTimeout(
org.threeten.bp.Duration rollbackTimeout) {
return withRollbackTimeoutDuration(toJavaTimeDuration(rollbackTimeout));
}
public SpannerCallContextTimeoutConfigurator withRollbackTimeoutDuration(
Duration rollbackTimeout) {
this.rollbackTimeout = rollbackTimeout;
return this;
}
/** This method is obsolete. Use {@link #getExecuteQueryTimeoutDuration()} instead. */
@ObsoleteApi("Use getExecuteQueryTimeoutDuration() instead.")
public org.threeten.bp.Duration getExecuteQueryTimeout() {
return toThreetenDuration(getExecuteQueryTimeoutDuration());
}
public Duration getExecuteQueryTimeoutDuration() {
return executeQueryTimeout;
}
/** This method is obsolete. Use {@link #withExecuteQueryTimeoutDuration(Duration)} instead. */
@ObsoleteApi("Use withExecuteQueryTimeoutDuration() instead")
public SpannerCallContextTimeoutConfigurator withExecuteQueryTimeout(
org.threeten.bp.Duration executeQueryTimeout) {
return withExecuteQueryTimeoutDuration(toJavaTimeDuration(executeQueryTimeout));
}
public SpannerCallContextTimeoutConfigurator withExecuteQueryTimeoutDuration(
Duration executeQueryTimeout) {
this.executeQueryTimeout = executeQueryTimeout;
return this;
}
/** This method is obsolete. Use {@link #getExecuteUpdateTimeoutDuration()} instead. */
@ObsoleteApi("Use getExecuteUpdateTimeoutDuration() instead")
public org.threeten.bp.Duration getExecuteUpdateTimeout() {
return toThreetenDuration(getExecuteUpdateTimeoutDuration());
}
public Duration getExecuteUpdateTimeoutDuration() {
return executeUpdateTimeout;
}
/** This method is obsolete. Use {@link #withExecuteUpdateTimeoutDuration(Duration)} instead. */
@ObsoleteApi("Use withExecuteUpdateTimeoutDuration() instead")
public SpannerCallContextTimeoutConfigurator withExecuteUpdateTimeout(
org.threeten.bp.Duration executeUpdateTimeout) {
return withExecuteUpdateTimeoutDuration(toJavaTimeDuration(executeUpdateTimeout));
}
public SpannerCallContextTimeoutConfigurator withExecuteUpdateTimeoutDuration(
Duration executeUpdateTimeout) {
this.executeUpdateTimeout = executeUpdateTimeout;
return this;
}
/** This method is obsolete. Use {@link #getBatchUpdateTimeoutDuration()} instead. */
@ObsoleteApi("Use getBatchUpdateTimeoutDuration() instead")
public org.threeten.bp.Duration getBatchUpdateTimeout() {
return toThreetenDuration(getBatchUpdateTimeoutDuration());
}
public Duration getBatchUpdateTimeoutDuration() {
return batchUpdateTimeout;
}
/** This method is obsolete. Use {@link #withBatchUpdateTimeoutDuration(Duration)} instead. */
@ObsoleteApi("Use withBatchUpdateTimeoutDuration() instead")
public SpannerCallContextTimeoutConfigurator withBatchUpdateTimeout(
org.threeten.bp.Duration batchUpdateTimeout) {
return withBatchUpdateTimeoutDuration(toJavaTimeDuration(batchUpdateTimeout));
}
public SpannerCallContextTimeoutConfigurator withBatchUpdateTimeoutDuration(
Duration batchUpdateTimeout) {
this.batchUpdateTimeout = batchUpdateTimeout;
return this;
}
/** This method is obsolete. Use {@link #getReadTimeoutDuration()} instead. */
@ObsoleteApi("Use getReadTimeoutDuration() instead")
public org.threeten.bp.Duration getReadTimeout() {
return toThreetenDuration(getReadTimeoutDuration());
}
public Duration getReadTimeoutDuration() {
return readTimeout;
}
/** This method is obsolete. Use {@link #withReadTimeoutDuration(Duration)} instead. */
@ObsoleteApi("Use withReadTimeoutDuration() instead")
public SpannerCallContextTimeoutConfigurator withReadTimeout(
org.threeten.bp.Duration readTimeout) {
return withReadTimeoutDuration(toJavaTimeDuration(readTimeout));
}
public SpannerCallContextTimeoutConfigurator withReadTimeoutDuration(Duration readTimeout) {
this.readTimeout = readTimeout;
return this;
}
/** This method is obsolete. Use {@link #getPartitionQueryTimeoutDuration()} instead. */
@ObsoleteApi("Use getPartitionQueryTimeoutDuration() instead")
public org.threeten.bp.Duration getPartitionQueryTimeout() {
return toThreetenDuration(getPartitionQueryTimeoutDuration());
}
public Duration getPartitionQueryTimeoutDuration() {
return partitionQueryTimeout;
}
/**
* This method is obsolete. Use {@link #withPartitionQueryTimeoutDuration(Duration)} instead.
*/
@ObsoleteApi("Use withPartitionQueryTimeoutDuration() instead")
public SpannerCallContextTimeoutConfigurator withPartitionQueryTimeout(
org.threeten.bp.Duration partitionQueryTimeout) {
return withPartitionQueryTimeoutDuration(toJavaTimeDuration(partitionQueryTimeout));
}
public SpannerCallContextTimeoutConfigurator withPartitionQueryTimeoutDuration(
Duration partitionQueryTimeout) {
this.partitionQueryTimeout = partitionQueryTimeout;
return this;
}
/** This method is obsolete. Use {@link #getPartitionReadTimeoutDuration()} instead. */
@ObsoleteApi("Use getPartitionReadTimeoutDuration() instead")
public org.threeten.bp.Duration getPartitionReadTimeout() {
return toThreetenDuration(getPartitionReadTimeoutDuration());
}
public Duration getPartitionReadTimeoutDuration() {
return partitionReadTimeout;
}
/** This method is obsolete. Use {@link #withPartitionReadTimeoutDuration(Duration)} instead. */
@ObsoleteApi("Use withPartitionReadTimeoutDuration() instead")
public SpannerCallContextTimeoutConfigurator withPartitionReadTimeout(
org.threeten.bp.Duration partitionReadTimeout) {
return withPartitionReadTimeoutDuration(toJavaTimeDuration(partitionReadTimeout));
}
public SpannerCallContextTimeoutConfigurator withPartitionReadTimeoutDuration(
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(
getDefaultAsyncExecutorProviderCoreThreadCount(), 60L, TimeUnit.SECONDS);
}
@VisibleForTesting
static int getDefaultAsyncExecutorProviderCoreThreadCount() {
String propertyName = "com.google.cloud.spanner.async_num_core_threads";
String propertyValue = System.getProperty(propertyName, "8");
try {
int corePoolSize = Integer.parseInt(propertyValue);
if (corePoolSize < 0) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT,
String.format(
"The value for %s must be >=0. Invalid value: %s", propertyName, propertyValue));
}
return corePoolSize;
} catch (NumberFormatException exception) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT,
String.format(
"The %s system property must be a valid integer. The value %s could not be parsed as an integer.",
propertyName, propertyValue));
}
}
/**
* 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);
}
protected SpannerOptions(Builder builder) {
super(SpannerFactory.class, SpannerRpcFactory.class, builder, new SpannerDefaults());
numChannels = builder.numChannels == null ? DEFAULT_CHANNELS : 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;
if (builder.mTLSContext != null) {
channelConfigurator =
channelBuilder -> {
if (builder.channelConfigurator != null) {
channelBuilder = builder.channelConfigurator.apply(channelBuilder);
}
if (channelBuilder instanceof NettyChannelBuilder) {
((NettyChannelBuilder) channelBuilder).sslContext(builder.mTLSContext);
}
return channelBuilder;
};
} else {
channelConfigurator = builder.channelConfigurator;
}
interceptorProvider = builder.interceptorProvider;
sessionPoolOptions =
builder.sessionPoolOptions != null
? builder.sessionPoolOptions
: SessionPoolOptions.newBuilder().build();
prefetchChunks = builder.prefetchChunks;
decodeMode = builder.decodeMode;
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;
attemptDirectPath = builder.attemptDirectPath;
directedReadOptions = builder.directedReadOptions;
useVirtualThreads = builder.useVirtualThreads;
openTelemetry = builder.openTelemetry;
enableApiTracing = builder.enableApiTracing;
enableExtendedTracing = builder.enableExtendedTracing;
enableBuiltInMetrics = builder.enableBuiltInMetrics;
enableEndToEndTracing = builder.enableEndToEndTracing;
monitoringHost = builder.monitoringHost;
}
/**
* 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
default String getOptimizerVersion() {
return "";
}
/**
* The optimizer statistics package to use. Must return an empty string to indicate that no
* value has been set.
*/
@Nonnull
default String getOptimizerStatisticsPackage() {
return "";
}
default boolean isEnableExtendedTracing() {
return false;
}
default boolean isEnableApiTracing() {
return false;
}
default boolean isEnableBuiltInMetrics() {
return true;
}
default boolean isEnableEndToEndTracing() {
return false;
}
default String getMonitoringHost() {
return null;
}
}
/**
* 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 static final String SPANNER_ENABLE_EXTENDED_TRACING = "SPANNER_ENABLE_EXTENDED_TRACING";
private static final String SPANNER_ENABLE_API_TRACING = "SPANNER_ENABLE_API_TRACING";
private static final String SPANNER_ENABLE_END_TO_END_TRACING =
"SPANNER_ENABLE_END_TO_END_TRACING";
private static final String SPANNER_DISABLE_BUILTIN_METRICS = "SPANNER_DISABLE_BUILTIN_METRICS";
private static final String SPANNER_MONITORING_HOST = "SPANNER_MONITORING_HOST";
private SpannerEnvironmentImpl() {}
@Nonnull
@Override
public String getOptimizerVersion() {
return MoreObjects.firstNonNull(System.getenv(SPANNER_OPTIMIZER_VERSION_ENV_VAR), "");
}
@Nonnull
@Override
public String getOptimizerStatisticsPackage() {
return MoreObjects.firstNonNull(
System.getenv(SPANNER_OPTIMIZER_STATISTICS_PACKAGE_ENV_VAR), "");
}
@Override
public boolean isEnableExtendedTracing() {
return Boolean.parseBoolean(System.getenv(SPANNER_ENABLE_EXTENDED_TRACING));
}
@Override
public boolean isEnableApiTracing() {
return Boolean.parseBoolean(System.getenv(SPANNER_ENABLE_API_TRACING));
}
@Override
public boolean isEnableBuiltInMetrics() {
return !Boolean.parseBoolean(System.getenv(SPANNER_DISABLE_BUILTIN_METRICS));
}
@Override
public boolean isEnableEndToEndTracing() {
return Boolean.parseBoolean(System.getenv(SPANNER_ENABLE_END_TO_END_TRACING));
}
@Override
public String getMonitoringHost() {
return System.getenv(SPANNER_MONITORING_HOST);
}
}
/** 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 DecodeMode DEFAULT_DECODE_MODE = DecodeMode.DIRECT;
static final RetrySettings DEFAULT_ADMIN_REQUESTS_LIMIT_EXCEEDED_RETRY_SETTINGS =
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofSeconds(5L))
.setRetryDelayMultiplier(2.0)
.setMaxRetryDelayDuration(Duration.ofSeconds(60L))
.setMaxAttempts(10)
.build();
private final ImmutableSet<String> allowedClientLibTokens =
ImmutableSet.of(
ServiceOptions.getGoogApiClientLibName(),
createCustomClientLibToken(JDBC_API_CLIENT_LIB_TOKEN),
createCustomClientLibToken(HIBERNATE_API_CLIENT_LIB_TOKEN),
createCustomClientLibToken(LIQUIBASE_API_CLIENT_LIB_TOKEN),
createCustomClientLibToken(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 DecodeMode decodeMode = DEFAULT_DECODE_MODE;
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 boolean attemptDirectPath = true;
private DirectedReadOptions directedReadOptions;
private boolean useVirtualThreads = false;
private OpenTelemetry openTelemetry;
private boolean enableApiTracing = SpannerOptions.environment.isEnableApiTracing();
private boolean enableExtendedTracing = SpannerOptions.environment.isEnableExtendedTracing();
private boolean enableEndToEndTracing = SpannerOptions.environment.isEnableEndToEndTracing();
private boolean enableBuiltInMetrics = SpannerOptions.environment.isEnableBuiltInMetrics();
private String monitoringHost = SpannerOptions.environment.getMonitoringHost();
private SslContext mTLSContext = null;
private static String createCustomClientLibToken(String token) {
return token + " " + ServiceOptions.getGoogApiClientLibName();
}
protected Builder() {
// Manually set retry and polling settings that work.
OperationTimedPollAlgorithm longRunningPollingAlgorithm =
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRpcTimeoutDuration(Duration.ofSeconds(60L))
.setMaxRpcTimeoutDuration(Duration.ofSeconds(600L))
.setInitialRetryDelayDuration(Duration.ofSeconds(20L))
.setMaxRetryDelayDuration(Duration.ofSeconds(45L))
.setRetryDelayMultiplier(1.5)
.setRpcTimeoutMultiplier(1.5)
.setTotalTimeoutDuration(Duration.ofHours(48L))
.build());
databaseAdminStubSettingsBuilder
.createDatabaseOperationSettings()
.setPollingAlgorithm(longRunningPollingAlgorithm);
databaseAdminStubSettingsBuilder
.createBackupOperationSettings()
.setPollingAlgorithm(longRunningPollingAlgorithm);
databaseAdminStubSettingsBuilder
.restoreDatabaseOperationSettings()
.setPollingAlgorithm(longRunningPollingAlgorithm);
}