/
EnhancedBigtableStubSettings.java
1040 lines (941 loc) · 45.5 KB
/
EnhancedBigtableStubSettings.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 2018 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.bigtable.data.v2.stub;
import com.google.api.core.InternalApi;
import com.google.api.gax.batching.BatchingCallSettings;
import com.google.api.gax.batching.BatchingSettings;
import com.google.api.gax.batching.FlowControlSettings;
import com.google.api.gax.batching.FlowController;
import com.google.api.gax.batching.FlowController.LimitExceededBehavior;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.grpc.ChannelPoolSettings;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.FixedHeaderProvider;
import com.google.api.gax.rpc.ServerStreamingCallSettings;
import com.google.api.gax.rpc.StatusCode.Code;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.auth.Credentials;
import com.google.bigtable.v2.FeatureFlags;
import com.google.bigtable.v2.PingAndWarmRequest;
import com.google.cloud.bigtable.Version;
import com.google.cloud.bigtable.data.v2.models.ChangeStreamRecord;
import com.google.cloud.bigtable.data.v2.models.ConditionalRowMutation;
import com.google.cloud.bigtable.data.v2.models.KeyOffset;
import com.google.cloud.bigtable.data.v2.models.Query;
import com.google.cloud.bigtable.data.v2.models.Range.ByteStringRange;
import com.google.cloud.bigtable.data.v2.models.ReadChangeStreamQuery;
import com.google.cloud.bigtable.data.v2.models.ReadModifyWriteRow;
import com.google.cloud.bigtable.data.v2.models.Row;
import com.google.cloud.bigtable.data.v2.models.RowMutation;
import com.google.cloud.bigtable.data.v2.stub.mutaterows.MutateRowsBatchingDescriptor;
import com.google.cloud.bigtable.data.v2.stub.readrows.ReadRowsBatchingDescriptor;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import org.threeten.bp.Duration;
/**
* Settings class to configure an instance of {@link EnhancedBigtableStub}.
*
* <p>Sane defaults are provided for most settings:
*
* <ul>
* <li>The default service address (bigtable.googleapis.com) and default port (443) are used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The only required setting is the instance name.
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <pre>{@code
* BigtableDataSettings.Builder settingsBuilder = BigtableDataSettings.newBuilder()
* .setProjectId("my-project-id")
* .setInstanceId("my-instance-id")
* .setAppProfileId("default");
*
* settingsBuilder.readRowsSettings()
* .setRetryableCodes(Code.DEADLINE_EXCEEDED, Code.UNAVAILABLE);
*
* BigtableDataSettings settings = builder.build();
* }</pre>
*/
public class EnhancedBigtableStubSettings extends StubSettings<EnhancedBigtableStubSettings> {
private static final Logger logger =
Logger.getLogger(EnhancedBigtableStubSettings.class.getName());
// The largest message that can be received is a 256 MB ReadRowsResponse.
private static final int MAX_MESSAGE_SIZE = 256 * 1024 * 1024;
private static final String SERVER_DEFAULT_APP_PROFILE_ID = "";
private static final Set<Code> IDEMPOTENT_RETRY_CODES =
ImmutableSet.of(Code.DEADLINE_EXCEEDED, Code.UNAVAILABLE);
// Copy of default retrying settings in the yaml
private static final RetrySettings IDEMPOTENT_RETRY_SETTINGS =
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(10))
.setRetryDelayMultiplier(2)
.setMaxRetryDelay(Duration.ofMinutes(1))
.setInitialRpcTimeout(Duration.ofSeconds(20))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ofSeconds(20))
.setTotalTimeout(Duration.ofMinutes(10))
.build();
// Allow retrying ABORTED statuses. These will be returned by the server when the client is
// too slow to read the rows. This makes sense for the java client because retries happen
// after the row merging logic. Which means that the retry will not be invoked until the
// current buffered chunks are consumed.
private static final Set<Code> READ_ROWS_RETRY_CODES =
ImmutableSet.<Code>builder().addAll(IDEMPOTENT_RETRY_CODES).add(Code.ABORTED).build();
// Priming request should have a shorter timeout
private static Duration PRIME_REQUEST_TIMEOUT = Duration.ofSeconds(30);
private static final RetrySettings READ_ROWS_RETRY_SETTINGS =
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(10))
.setRetryDelayMultiplier(2.0)
.setMaxRetryDelay(Duration.ofMinutes(1))
.setMaxAttempts(10)
.setJittered(true)
.setInitialRpcTimeout(Duration.ofMinutes(30))
.setRpcTimeoutMultiplier(2.0)
.setMaxRpcTimeout(Duration.ofMinutes(30))
.setTotalTimeout(Duration.ofHours(12))
.build();
private static final RetrySettings MUTATE_ROWS_RETRY_SETTINGS =
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(10))
.setRetryDelayMultiplier(2)
.setMaxRetryDelay(Duration.ofMinutes(1))
.setInitialRpcTimeout(Duration.ofMinutes(1))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ofMinutes(1))
.setTotalTimeout(Duration.ofMinutes(10))
.build();
private static final Set<Code> GENERATE_INITIAL_CHANGE_STREAM_PARTITIONS_RETRY_CODES =
ImmutableSet.<Code>builder().addAll(IDEMPOTENT_RETRY_CODES).add(Code.ABORTED).build();
private static final RetrySettings GENERATE_INITIAL_CHANGE_STREAM_PARTITIONS_RETRY_SETTINGS =
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(10))
.setRetryDelayMultiplier(2.0)
.setMaxRetryDelay(Duration.ofMinutes(1))
.setMaxAttempts(10)
.setJittered(true)
.setInitialRpcTimeout(Duration.ofMinutes(1))
.setRpcTimeoutMultiplier(2.0)
.setMaxRpcTimeout(Duration.ofMinutes(10))
.setTotalTimeout(Duration.ofMinutes(60))
.build();
// Allow retrying ABORTED statuses. These will be returned by the server when the client is
// too slow to read the change stream records. This makes sense for the java client because
// retries happen after the mutation merging logic. Which means that the retry will not be
// invoked until the current buffered change stream mutations are consumed.
private static final Set<Code> READ_CHANGE_STREAM_RETRY_CODES =
ImmutableSet.<Code>builder().addAll(IDEMPOTENT_RETRY_CODES).add(Code.ABORTED).build();
private static final RetrySettings READ_CHANGE_STREAM_RETRY_SETTINGS =
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(10))
.setRetryDelayMultiplier(2.0)
.setMaxRetryDelay(Duration.ofMinutes(1))
.setMaxAttempts(10)
.setJittered(true)
.setInitialRpcTimeout(Duration.ofMinutes(5))
.setRpcTimeoutMultiplier(2.0)
.setMaxRpcTimeout(Duration.ofMinutes(5))
.setTotalTimeout(Duration.ofHours(12))
.build();
/**
* Scopes that are equivalent to JWT's audience.
*
* <p>When the credentials provider contains any of these scopes (default behavior) and the
* application default credentials point to a service account, then OAuth2 tokens will be replaced
* with JWT tokens. This removes the need for access token refreshes.
*/
private static final ImmutableList<String> JWT_ENABLED_SCOPES =
ImmutableList.<String>builder()
.add("https://www.googleapis.com/auth/bigtable.data")
.add("https://www.googleapis.com/auth/cloud-bigtable.data")
.add("https://www.googleapis.com/auth/cloud-platform")
.build();
/**
* In most cases, jwt audience == service name. However in some cases, this is not the case. The
* following mapping is used to patch the audience in a JWT token.
*/
private static final Map<String, String> DEFAULT_JWT_AUDIENCE_MAPPING =
ImmutableMap.of("batch-bigtable.googleapis.com", "https://bigtable.googleapis.com/");
private final String projectId;
private final String instanceId;
private final String appProfileId;
private final boolean isRefreshingChannel;
private ImmutableList<String> primedTableIds;
private final Map<String, String> jwtAudienceMapping;
private final ServerStreamingCallSettings<Query, Row> readRowsSettings;
private final UnaryCallSettings<Query, Row> readRowSettings;
private final UnaryCallSettings<String, List<KeyOffset>> sampleRowKeysSettings;
private final UnaryCallSettings<RowMutation, Void> mutateRowSettings;
private final BigtableBatchingCallSettings bulkMutateRowsSettings;
private final BigtableBulkReadRowsCallSettings bulkReadRowsSettings;
private final UnaryCallSettings<ConditionalRowMutation, Boolean> checkAndMutateRowSettings;
private final UnaryCallSettings<ReadModifyWriteRow, Row> readModifyWriteRowSettings;
private final ServerStreamingCallSettings<String, ByteStringRange>
generateInitialChangeStreamPartitionsSettings;
private final ServerStreamingCallSettings<ReadChangeStreamQuery, ChangeStreamRecord>
readChangeStreamSettings;
private final UnaryCallSettings<PingAndWarmRequest, Void> pingAndWarmSettings;
private final FeatureFlags featureFlags;
private EnhancedBigtableStubSettings(Builder builder) {
super(builder);
// Since point reads, streaming reads, bulk reads share the same base callable that converts
// grpc errors into ApiExceptions, they must have the same retry codes.
Preconditions.checkState(
builder
.readRowSettings
.getRetryableCodes()
.equals(builder.readRowsSettings.getRetryableCodes()),
"Single ReadRow retry codes must match ReadRows retry codes");
Preconditions.checkState(
builder
.bulkReadRowsSettings
.getRetryableCodes()
.equals(builder.readRowsSettings.getRetryableCodes()),
"Bulk ReadRow retry codes must match ReadRows retry codes");
projectId = builder.projectId;
instanceId = builder.instanceId;
appProfileId = builder.appProfileId;
isRefreshingChannel = builder.isRefreshingChannel;
primedTableIds = builder.primedTableIds;
jwtAudienceMapping = builder.jwtAudienceMapping;
// Per method settings.
readRowsSettings = builder.readRowsSettings.build();
readRowSettings = builder.readRowSettings.build();
sampleRowKeysSettings = builder.sampleRowKeysSettings.build();
mutateRowSettings = builder.mutateRowSettings.build();
bulkMutateRowsSettings = builder.bulkMutateRowsSettings.build();
bulkReadRowsSettings = builder.bulkReadRowsSettings.build();
checkAndMutateRowSettings = builder.checkAndMutateRowSettings.build();
readModifyWriteRowSettings = builder.readModifyWriteRowSettings.build();
generateInitialChangeStreamPartitionsSettings =
builder.generateInitialChangeStreamPartitionsSettings.build();
readChangeStreamSettings = builder.readChangeStreamSettings.build();
pingAndWarmSettings = builder.pingAndWarmSettings.build();
featureFlags = builder.featureFlags.build();
}
/** Create a new builder. */
public static Builder newBuilder() {
return new Builder();
}
/** Returns the project id of the target instance. */
public String getProjectId() {
return projectId;
}
/** Returns the target instance id. */
public String getInstanceId() {
return instanceId;
}
/** Returns the configured AppProfile to use */
public String getAppProfileId() {
return appProfileId;
}
/**
* Returns if channels will gracefully refresh connections to Cloud Bigtable service
*
* @deprecated Channel refreshing is enabled by default and this method will be deprecated.
*/
@Deprecated
public boolean isRefreshingChannel() {
return isRefreshingChannel;
}
/**
* @deprecated This field is ignored. If {@link #isRefreshingChannel()} is enabled, warm up
* requests will be sent to all table ids of the instance.
*/
@Deprecated
public List<String> getPrimedTableIds() {
return primedTableIds;
}
@InternalApi("Used for internal testing")
public Map<String, String> getJwtAudienceMapping() {
return jwtAudienceMapping;
}
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return BigtableStubSettings.defaultGrpcTransportProviderBuilder()
.setChannelPoolSettings(
ChannelPoolSettings.builder()
.setInitialChannelCount(10)
.setMinRpcsPerChannel(1)
.setMaxRpcsPerChannel(50)
.setPreemptiveRefreshEnabled(true)
.build())
.setMaxInboundMessageSize(MAX_MESSAGE_SIZE)
.setKeepAliveTime(Duration.ofSeconds(30)) // sends ping in this interval
.setKeepAliveTimeout(
Duration.ofSeconds(10)) // wait this long before considering the connection dead
// Attempts direct access to CBT service over gRPC to improve throughput,
// whether the attempt is allowed is totally controlled by service owner.
.setAttemptDirectPath(true);
}
@SuppressWarnings("WeakerAccess")
public static TransportChannelProvider defaultTransportChannelProvider() {
return defaultGrpcTransportProviderBuilder().build();
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return BigtableStubSettings.defaultCredentialsProviderBuilder()
.setJwtEnabledScopes(JWT_ENABLED_SCOPES);
}
/**
* Returns the object with the settings used for calls to ReadRows.
*
* <p>This is idempotent and streaming operation.
*
* <p>Default retry and timeout settings:
*
* <ul>
* <li>{@link ServerStreamingCallSettings.Builder#setIdleTimeout Default idle timeout} is set to
* 5 mins. Idle timeout is how long to wait before considering the stream orphaned by the
* user and closing it.
* <li>{@link ServerStreamingCallSettings.Builder#setWaitTimeout Default wait timeout} is set to
* 5 mins. Wait timeout is the maximum amount of time to wait for the next message from the
* server.
* <li>Retry {@link ServerStreamingCallSettings.Builder#setRetryableCodes error codes} are:
* {@link Code#DEADLINE_EXCEEDED}, {@link Code#UNAVAILABLE} and {@link Code#ABORTED}.
* <li>RetryDelay between failed attempts {@link RetrySettings.Builder#setInitialRetryDelay
* starts} at 10ms and {@link RetrySettings.Builder#setRetryDelayMultiplier increases
* exponentially} by a factor of 2 until a {@link RetrySettings.Builder#setMaxRetryDelay
* maximum of} 1 minute.
* <li>The default read timeout for {@link RetrySettings.Builder#setMaxRpcTimeout each attempt}
* is 30 minutes with {@link RetrySettings.Builder#setMaxAttempts maximum attempt} count of
* 10 times and the timeout to read the {@link RetrySettings.Builder#setTotalTimeout entire
* stream} is 12 hours.
* </ul>
*/
public ServerStreamingCallSettings<Query, Row> readRowsSettings() {
return readRowsSettings;
}
/**
* Returns the object with the settings used for calls to SampleRowKeys.
*
* <p>This is idempotent and non-streaming operation.
*
* <p>Default retry and timeout settings:
*
* <ul>
* <li>Retry {@link UnaryCallSettings.Builder#setRetryableCodes error codes} are: {@link
* Code#DEADLINE_EXCEEDED} and {@link Code#UNAVAILABLE}.
* <li>RetryDelay between failed attempts {@link RetrySettings.Builder#setInitialRetryDelay
* starts} at 10ms and {@link RetrySettings.Builder#setRetryDelayMultiplier increases
* exponentially} by a factor of 2 until a {@link RetrySettings.Builder#setMaxRetryDelay
* maximum of} 1 minute.
* <li>The default timeout for {@link RetrySettings.Builder#setMaxRpcTimeout each attempt} is 5
* minutes and the timeout for the {@link RetrySettings.Builder#setTotalTimeout entire
* operation} across all of the attempts is 10 mins.
* </ul>
*/
public UnaryCallSettings<String, List<KeyOffset>> sampleRowKeysSettings() {
return sampleRowKeysSettings;
}
/**
* Returns the object with the settings used for point reads via ReadRows.
*
* <p>This is an idempotent and non-streaming operation.
*
* <p>Default retry and timeout settings:
*
* <ul>
* <li>Retry {@link UnaryCallSettings.Builder#setRetryableCodes error codes} are: {@link
* Code#DEADLINE_EXCEEDED}, {@link Code#UNAVAILABLE} and {@link Code#ABORTED}.
* <li>RetryDelay between failed attempts {@link RetrySettings.Builder#setInitialRetryDelay
* starts} at 10ms and {@link RetrySettings.Builder#setRetryDelayMultiplier increases
* exponentially} by a factor of 2 until a {@link RetrySettings.Builder#setMaxRetryDelay
* maximum of} 1 minute.
* <li>The default timeout for {@link RetrySettings.Builder#setMaxRpcTimeout each attempt} is 20
* seconds and the timeout for the {@link RetrySettings.Builder#setTotalTimeout entire
* operation} across all of the attempts is 10 mins.
* </ul>
*
* @see RetrySettings for more explanation.
*/
public UnaryCallSettings<Query, Row> readRowSettings() {
return readRowSettings;
}
/**
* Returns the object with the settings used for calls to MutateRow.
*
* <p>This is an idempotent and non-streaming operation.
*
* <p>Default retry and timeout settings:
*
* <ul>
* <li>Retry {@link UnaryCallSettings.Builder#setRetryableCodes error codes} are: {@link
* Code#DEADLINE_EXCEEDED} and {@link Code#UNAVAILABLE}.
* <li>RetryDelay between failed attempts {@link RetrySettings.Builder#setInitialRetryDelay
* starts} at 10ms and {@link RetrySettings.Builder#setRetryDelayMultiplier increases
* exponentially} by a factor of 2 until a {@link RetrySettings.Builder#setMaxRetryDelay
* maximum of} 60 seconds.
* <li>The default timeout for {@link RetrySettings.Builder#setMaxRpcTimeout each attempt} is 20
* seconds and the timeout for the {@link RetrySettings.Builder#setTotalTimeout entire
* operation} across all of the attempts is 10 mins.
* </ul>
*
* @see RetrySettings for more explanation.
*/
public UnaryCallSettings<RowMutation, Void> mutateRowSettings() {
return mutateRowSettings;
}
/**
* Returns the object with the settings used for calls to MutateRows.
*
* <p>Please note that these settings will affect both manually batched calls
* (bulkMutateRowsCallable) and automatic batched calls (bulkMutateRowsBatchingCallable). The
* {@link RowMutation} request signature is ignored for the manual batched calls.
*
* <p>Default retry and timeout settings:
*
* <ul>
* <li>Retry {@link BatchingCallSettings.Builder#setRetryableCodes error codes} are: {@link
* Code#DEADLINE_EXCEEDED} and {@link Code#UNAVAILABLE}.
* <li>RetryDelay between failed attempts {@link RetrySettings.Builder#setInitialRetryDelay
* starts} at 10ms and {@link RetrySettings.Builder#setRetryDelayMultiplier increases
* exponentially} by a factor of 2 until a {@link RetrySettings.Builder#setMaxRetryDelay
* maximum of} 1 minute.
* <li>The default timeout for {@link RetrySettings.Builder#setMaxRpcTimeout each attempt} is 1
* minute and the timeout for the {@link RetrySettings.Builder#setTotalTimeout entire
* operation} across all of the attempts is 10 mins.
* </ul>
*
* <p>On breach of certain triggers, the operation initiates processing of accumulated request for
* which the default settings are:
*
* <ul>
* <li>When the {@link BatchingSettings.Builder#setElementCountThreshold request count} reaches
* 100.
* <li>When accumulated {@link BatchingSettings.Builder#setRequestByteThreshold request size}
* reaches to 20MB.
* <li>When an {@link BatchingSettings.Builder#setDelayThreshold interval of} 1 second passes
* after batching initialization or last processed batch.
* </ul>
*
* <p>A {@link FlowController} will be set up with {@link BigtableBatchingCallSettings.Builder
* #getDynamicFlowControlSettings()} for throttling in-flight requests. When the pending request
* count or accumulated request size reaches {@link FlowController} thresholds, then this
* operation will be throttled until some of the pending batches are resolved.
*
* @see RetrySettings for more explanation.
* @see BatchingSettings for batch related configuration explanation.
* @see BigtableBatchingCallSettings.Builder#getDynamicFlowControlSettings() for flow control
* related configuration explanation.
*/
public BigtableBatchingCallSettings bulkMutateRowsSettings() {
return bulkMutateRowsSettings;
}
/**
* Returns the call settings used for bulk read rows.
*
* <p>Default retry and timeout settings:
*
* <ul>
* <li>Retry {@link BatchingCallSettings.Builder#setRetryableCodes error codes} are: {@link
* Code#DEADLINE_EXCEEDED}, {@link Code#UNAVAILABLE} and {@link Code#ABORTED}.
* <li>RetryDelay between failed attempts {@link RetrySettings.Builder#setInitialRetryDelay
* starts} at 10ms and {@link RetrySettings.Builder#setRetryDelayMultiplier increases
* exponentially} by a factor of 2 until a {@link RetrySettings.Builder#setMaxRetryDelay
* maximum of} 1 minute.
* <li>The default timeout for {@link RetrySettings.Builder#setMaxRpcTimeout each attempt} is 5
* minute and the timeout for the {@link RetrySettings.Builder#setTotalTimeout entire
* operation} across all of the attempts is 10 mins.
* </ul>
*
* <p>On breach of certain triggers, the operation initiates processing of accumulated request for
* which the default settings are:
*
* <ul>
* <li>When the {@link BatchingSettings.Builder#setElementCountThreshold request count} reaches
* 100.
* <li>When accumulated {@link BatchingSettings.Builder#setRequestByteThreshold request size}
* reaches to 400KB.
* <li>When an {@link BatchingSettings.Builder#setDelayThreshold interval of} 1 second passes
* after batching initialization or last processed batch.
* </ul>
*
* <p>When the pending {@link FlowControlSettings.Builder#setMaxOutstandingElementCount request
* count} reaches a default of 1000 outstanding row keys per channel then this operation will by
* default be {@link FlowControlSettings.Builder#setLimitExceededBehavior blocked} until some of
* the pending batch are resolved.
*
* @see RetrySettings for more explanation.
* @see BatchingSettings for batch related configuration explanation.
*/
public BigtableBulkReadRowsCallSettings bulkReadRowsSettings() {
return bulkReadRowsSettings;
}
/**
* Returns the object with the settings used for calls to CheckAndMutateRow.
*
* <p>This is a non-idempotent and non-streaming operation.
*
* <p>By default this operation does not reattempt in case of RPC failure. The default timeout for
* the {@link RetrySettings.Builder#setTotalTimeout entire operation} is 20 seconds.
*
* @see RetrySettings for more explanation.
*/
public UnaryCallSettings<ConditionalRowMutation, Boolean> checkAndMutateRowSettings() {
return checkAndMutateRowSettings;
}
/**
* Returns the object with the settings used for calls to ReadModifyWriteRow.
*
* <p>This is a non-idempotent and non-streaming operation.
*
* <p>By default this operation does not reattempt in case of RPC failure. The default timeout for
* the {@link RetrySettings.Builder#setTotalTimeout entire operation} is 20 seconds.
*
* @see RetrySettings for more explanation.
*/
public UnaryCallSettings<ReadModifyWriteRow, Row> readModifyWriteRowSettings() {
return readModifyWriteRowSettings;
}
public ServerStreamingCallSettings<String, ByteStringRange>
generateInitialChangeStreamPartitionsSettings() {
return generateInitialChangeStreamPartitionsSettings;
}
public ServerStreamingCallSettings<ReadChangeStreamQuery, ChangeStreamRecord>
readChangeStreamSettings() {
return readChangeStreamSettings;
}
/**
* Returns the object with the settings used for calls to PingAndWarm.
*
* <p>By default the retries are disabled for PingAndWarm and deadline is set to 30 seconds.
*/
UnaryCallSettings<PingAndWarmRequest, Void> pingAndWarmSettings() {
return pingAndWarmSettings;
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
/** Builder for BigtableDataSettings. */
public static class Builder extends StubSettings.Builder<EnhancedBigtableStubSettings, Builder> {
private String projectId;
private String instanceId;
private String appProfileId;
private boolean isRefreshingChannel;
private ImmutableList<String> primedTableIds;
private Map<String, String> jwtAudienceMapping;
private final ServerStreamingCallSettings.Builder<Query, Row> readRowsSettings;
private final UnaryCallSettings.Builder<Query, Row> readRowSettings;
private final UnaryCallSettings.Builder<String, List<KeyOffset>> sampleRowKeysSettings;
private final UnaryCallSettings.Builder<RowMutation, Void> mutateRowSettings;
private final BigtableBatchingCallSettings.Builder bulkMutateRowsSettings;
private final BigtableBulkReadRowsCallSettings.Builder bulkReadRowsSettings;
private final UnaryCallSettings.Builder<ConditionalRowMutation, Boolean>
checkAndMutateRowSettings;
private final UnaryCallSettings.Builder<ReadModifyWriteRow, Row> readModifyWriteRowSettings;
private final ServerStreamingCallSettings.Builder<String, ByteStringRange>
generateInitialChangeStreamPartitionsSettings;
private final ServerStreamingCallSettings.Builder<ReadChangeStreamQuery, ChangeStreamRecord>
readChangeStreamSettings;
private final UnaryCallSettings.Builder<PingAndWarmRequest, Void> pingAndWarmSettings;
private FeatureFlags.Builder featureFlags;
/**
* Initializes a new Builder with sane defaults for all settings.
*
* <p>Most defaults are extracted from BaseBigtableDataSettings, however some of the more
* complex defaults are configured explicitly here. Once the overlayed defaults are configured,
* the base settings are augmented to work with overlayed functionality (like disabling retries
* in the underlying GAPIC client for batching).
*/
private Builder() {
this.appProfileId = SERVER_DEFAULT_APP_PROFILE_ID;
this.isRefreshingChannel = true;
primedTableIds = ImmutableList.of();
jwtAudienceMapping = DEFAULT_JWT_AUDIENCE_MAPPING;
setCredentialsProvider(defaultCredentialsProviderBuilder().build());
// Defaults provider
BigtableStubSettings.Builder baseDefaults = BigtableStubSettings.newBuilder();
setEndpoint(baseDefaults.getEndpoint());
setTransportChannelProvider(defaultTransportChannelProvider());
setStreamWatchdogCheckInterval(baseDefaults.getStreamWatchdogCheckInterval());
setStreamWatchdogProvider(baseDefaults.getStreamWatchdogProvider());
// Per-method settings using baseSettings for defaults.
readRowsSettings = ServerStreamingCallSettings.newBuilder();
readRowsSettings
.setRetryableCodes(READ_ROWS_RETRY_CODES)
.setRetrySettings(READ_ROWS_RETRY_SETTINGS)
.setIdleTimeout(Duration.ofMinutes(5))
.setWaitTimeout(Duration.ofMinutes(5));
// Point reads should use same defaults as streaming reads, but with a shorter timeout
readRowSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
readRowSettings
.setRetryableCodes(readRowsSettings.getRetryableCodes())
.setRetrySettings(
readRowsSettings()
.getRetrySettings()
.toBuilder()
.setTotalTimeout(IDEMPOTENT_RETRY_SETTINGS.getTotalTimeout())
.build());
sampleRowKeysSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
sampleRowKeysSettings
.setRetryableCodes(IDEMPOTENT_RETRY_CODES)
.setRetrySettings(
IDEMPOTENT_RETRY_SETTINGS
.toBuilder()
.setInitialRpcTimeout(Duration.ofMinutes(5))
.setMaxRpcTimeout(Duration.ofMinutes(5))
.build());
mutateRowSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
copyRetrySettings(baseDefaults.mutateRowSettings(), mutateRowSettings);
long maxBulkMutateElementPerBatch = 100L;
long maxBulkMutateOutstandingElementCount = 20_000L;
bulkMutateRowsSettings =
BigtableBatchingCallSettings.newBuilder(new MutateRowsBatchingDescriptor())
.setRetryableCodes(IDEMPOTENT_RETRY_CODES)
.setRetrySettings(MUTATE_ROWS_RETRY_SETTINGS)
.setBatchingSettings(
BatchingSettings.newBuilder()
.setIsEnabled(true)
.setElementCountThreshold(maxBulkMutateElementPerBatch)
.setRequestByteThreshold(20L * 1024 * 1024)
.setDelayThreshold(Duration.ofSeconds(1))
.setFlowControlSettings(
FlowControlSettings.newBuilder()
.setLimitExceededBehavior(LimitExceededBehavior.Block)
.setMaxOutstandingRequestBytes(100L * 1024 * 1024)
.setMaxOutstandingElementCount(maxBulkMutateOutstandingElementCount)
.build())
.build());
long maxBulkReadElementPerBatch = 100L;
long maxBulkReadRequestSizePerBatch = 400L * 1024L;
long maxBulkReadOutstandingElementCount = 20_000L;
bulkReadRowsSettings =
BigtableBulkReadRowsCallSettings.newBuilder(new ReadRowsBatchingDescriptor())
.setRetryableCodes(readRowsSettings.getRetryableCodes())
.setRetrySettings(IDEMPOTENT_RETRY_SETTINGS)
.setBatchingSettings(
BatchingSettings.newBuilder()
.setElementCountThreshold(maxBulkReadElementPerBatch)
.setRequestByteThreshold(maxBulkReadRequestSizePerBatch)
.setDelayThreshold(Duration.ofSeconds(1))
.setFlowControlSettings(
FlowControlSettings.newBuilder()
.setLimitExceededBehavior(LimitExceededBehavior.Block)
.setMaxOutstandingElementCount(maxBulkReadOutstandingElementCount)
.build())
.build());
checkAndMutateRowSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
copyRetrySettings(baseDefaults.checkAndMutateRowSettings(), checkAndMutateRowSettings);
readModifyWriteRowSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
copyRetrySettings(baseDefaults.readModifyWriteRowSettings(), readModifyWriteRowSettings);
generateInitialChangeStreamPartitionsSettings = ServerStreamingCallSettings.newBuilder();
generateInitialChangeStreamPartitionsSettings
.setRetryableCodes(GENERATE_INITIAL_CHANGE_STREAM_PARTITIONS_RETRY_CODES)
.setRetrySettings(GENERATE_INITIAL_CHANGE_STREAM_PARTITIONS_RETRY_SETTINGS)
.setIdleTimeout(Duration.ofMinutes(5));
readChangeStreamSettings = ServerStreamingCallSettings.newBuilder();
readChangeStreamSettings
.setRetryableCodes(READ_CHANGE_STREAM_RETRY_CODES)
.setRetrySettings(READ_CHANGE_STREAM_RETRY_SETTINGS)
.setIdleTimeout(Duration.ofMinutes(5));
pingAndWarmSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
pingAndWarmSettings.setRetrySettings(
RetrySettings.newBuilder()
.setMaxAttempts(1)
.setInitialRpcTimeout(PRIME_REQUEST_TIMEOUT)
.setMaxRpcTimeout(PRIME_REQUEST_TIMEOUT)
.setTotalTimeout(PRIME_REQUEST_TIMEOUT)
.build());
featureFlags = FeatureFlags.newBuilder().setReverseScans(true);
}
private Builder(EnhancedBigtableStubSettings settings) {
super(settings);
projectId = settings.projectId;
instanceId = settings.instanceId;
appProfileId = settings.appProfileId;
isRefreshingChannel = settings.isRefreshingChannel;
primedTableIds = settings.primedTableIds;
jwtAudienceMapping = settings.jwtAudienceMapping;
// Per method settings.
readRowsSettings = settings.readRowsSettings.toBuilder();
readRowSettings = settings.readRowSettings.toBuilder();
sampleRowKeysSettings = settings.sampleRowKeysSettings.toBuilder();
mutateRowSettings = settings.mutateRowSettings.toBuilder();
bulkMutateRowsSettings = settings.bulkMutateRowsSettings.toBuilder();
bulkReadRowsSettings = settings.bulkReadRowsSettings.toBuilder();
checkAndMutateRowSettings = settings.checkAndMutateRowSettings.toBuilder();
readModifyWriteRowSettings = settings.readModifyWriteRowSettings.toBuilder();
generateInitialChangeStreamPartitionsSettings =
settings.generateInitialChangeStreamPartitionsSettings.toBuilder();
readChangeStreamSettings = settings.readChangeStreamSettings.toBuilder();
pingAndWarmSettings = settings.pingAndWarmSettings.toBuilder();
featureFlags = settings.featureFlags.toBuilder();
}
// <editor-fold desc="Private Helpers">
/**
* Copies settings from unary RPC to another. This is necessary when modifying request and
* response types while trying to retain retry settings.
*/
private static void copyRetrySettings(
UnaryCallSettings.Builder<?, ?> source, UnaryCallSettings.Builder<?, ?> dest) {
dest.setRetryableCodes(source.getRetryableCodes());
dest.setRetrySettings(source.getRetrySettings());
}
// </editor-fold>
// <editor-fold desc="Public API">
/**
* Sets the project id of that target instance. This setting is required. All RPCs will be made
* in the context of this setting.
*/
public Builder setProjectId(@Nonnull String projectId) {
Preconditions.checkNotNull(projectId);
this.projectId = projectId;
return this;
}
/** Gets the project id of the target instance that was previously set on this Builder. */
public String getProjectId() {
return projectId;
}
/**
* Sets the target instance id. This setting is required. All RPCs will be made in the context
* of this setting.
*/
public Builder setInstanceId(@Nonnull String instanceId) {
Preconditions.checkNotNull(instanceId);
this.instanceId = instanceId;
return this;
}
/** Gets the target instance id that was previously set on this Builder. */
public String getInstanceId() {
return instanceId;
}
/**
* Sets the AppProfile to use. An application profile (sometimes also shortened to "app
* profile") is a group of configuration parameters for an individual use case. A client will
* identify itself with an application profile ID at connection time, and the requests will be
* handled according to that application profile.
*/
public Builder setAppProfileId(@Nonnull String appProfileId) {
Preconditions.checkNotNull(appProfileId, "AppProfileId can't be null");
this.appProfileId = appProfileId;
return this;
}
/**
* Resets the AppProfile id to the default for the instance.
*
* <p>An application profile (sometimes also shortened to "app profile") is a group of
* configuration parameters for an individual use case. A client will identify itself with an
* application profile ID at connection time, and the requests will be handled according to that
* application profile.
*
* <p>Every Bigtable Instance has a default application profile associated with it, this method
* configures the client to use it.
*/
public Builder setDefaultAppProfileId() {
setAppProfileId(SERVER_DEFAULT_APP_PROFILE_ID);
return this;
}
/** Gets the app profile id that was previously set on this Builder. */
public String getAppProfileId() {
return appProfileId;
}
/**
* Sets if channels will gracefully refresh connections to Cloud Bigtable service.
*
* <p>When enabled, this will wait for the connection to complete the SSL handshake and warm up
* serverside caches for all the tables of the instance. This feature is enabled by default.
*
* @see com.google.cloud.bigtable.data.v2.BigtableDataSettings.Builder#setRefreshingChannel
* @deprecated Channel refreshing is enabled by default and this method will be deprecated.
*/
@Deprecated
public Builder setRefreshingChannel(boolean isRefreshingChannel) {
this.isRefreshingChannel = isRefreshingChannel;
return this;
}
/**
* @deprecated This field is ignored. If {@link #isRefreshingChannel()} is enabled, warm up
* requests will be sent to all table ids of the instance.
*/
@Deprecated
public Builder setPrimedTableIds(String... tableIds) {
this.primedTableIds = ImmutableList.copyOf(tableIds);
return this;
}
/**
* Gets if channels will gracefully refresh connections to Cloud Bigtable service.
*
* @deprecated Channel refreshing is enabled by default and this method will be deprecated.
*/
@Deprecated
public boolean isRefreshingChannel() {
return isRefreshingChannel;
}
/**
* @deprecated This field is ignored. If {@link #isRefreshingChannel()} is enabled, warm up
* requests will be sent to all table ids of the instance.
*/
@Deprecated
public List<String> getPrimedTableIds() {
return primedTableIds;
}
@InternalApi("Used for internal testing")
public Builder setJwtAudienceMapping(Map<String, String> jwtAudienceMapping) {
this.jwtAudienceMapping = Preconditions.checkNotNull(jwtAudienceMapping);
return this;
}
@InternalApi("Used for internal testing")
public Map<String, String> getJwtAudienceMapping() {
return jwtAudienceMapping;
}
/** Returns the builder for the settings used for calls to readRows. */
public ServerStreamingCallSettings.Builder<Query, Row> readRowsSettings() {
return readRowsSettings;
}
/** Returns the builder for the settings used for point reads using readRow. */
public UnaryCallSettings.Builder<Query, Row> readRowSettings() {
return readRowSettings;
}
/** Returns the builder for the settings used for calls to SampleRowKeysSettings. */
public UnaryCallSettings.Builder<String, List<KeyOffset>> sampleRowKeysSettings() {
return sampleRowKeysSettings;
}
/** Returns the builder for the settings used for calls to MutateRow. */
public UnaryCallSettings.Builder<RowMutation, Void> mutateRowSettings() {
return mutateRowSettings;
}
/** Returns the builder for the settings used for calls to MutateRows. */
public BigtableBatchingCallSettings.Builder bulkMutateRowsSettings() {
return bulkMutateRowsSettings;
}
/** Returns the builder for the settings used for calls to MutateRows. */
public BigtableBulkReadRowsCallSettings.Builder bulkReadRowsSettings() {
return bulkReadRowsSettings;
}
/** Returns the builder for the settings used for calls to CheckAndMutateRow. */
public UnaryCallSettings.Builder<ConditionalRowMutation, Boolean> checkAndMutateRowSettings() {
return checkAndMutateRowSettings;
}
/** Returns the builder with the settings used for calls to ReadModifyWriteRow. */
public UnaryCallSettings.Builder<ReadModifyWriteRow, Row> readModifyWriteRowSettings() {
return readModifyWriteRowSettings;
}
/** Returns the builder for the settings used for calls to ReadChangeStream. */
public ServerStreamingCallSettings.Builder<ReadChangeStreamQuery, ChangeStreamRecord>
readChangeStreamSettings() {
return readChangeStreamSettings;
}
/**
* Returns the builder for the settings used for calls to GenerateInitialChangeStreamPartitions.
*/
public ServerStreamingCallSettings.Builder<String, ByteStringRange>
generateInitialChangeStreamPartitionsSettings() {
return generateInitialChangeStreamPartitionsSettings;
}
/** Returns the builder with the settings used for calls to PingAndWarm. */
public UnaryCallSettings.Builder<PingAndWarmRequest, Void> pingAndWarmSettings() {
return pingAndWarmSettings;
}
@SuppressWarnings("unchecked")
public EnhancedBigtableStubSettings build() {
Preconditions.checkState(projectId != null, "Project id must be set");
Preconditions.checkState(instanceId != null, "Instance id must be set");
if (isRefreshingChannel) {
Preconditions.checkArgument(
getTransportChannelProvider() instanceof InstantiatingGrpcChannelProvider,
"refreshingChannel only works with InstantiatingGrpcChannelProviders");
InstantiatingGrpcChannelProvider.Builder channelProviderBuilder =
((InstantiatingGrpcChannelProvider) getTransportChannelProvider()).toBuilder();
Credentials credentials = null;
if (getCredentialsProvider() != null) {
try {
credentials = getCredentialsProvider().getCredentials();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// Use shared credentials
this.setCredentialsProvider(FixedCredentialsProvider.create(credentials));
channelProviderBuilder.setChannelPrimer(
BigtableChannelPrimer.create(credentials, projectId, instanceId, appProfileId));
this.setTransportChannelProvider(channelProviderBuilder.build());
}
if (this.bulkMutateRowsSettings().isServerInitiatedFlowControlEnabled()) {
// only set mutate rows feature flag when this feature is enabled
featureFlags.setMutateRowsRateLimit(true);
}
// Serialize the web64 encode the bigtable feature flags
ByteArrayOutputStream boas = new ByteArrayOutputStream();
try {
featureFlags.build().writeTo(boas);
} catch (IOException e) {
throw new IllegalStateException(
"Unexpected IOException while serializing feature flags", e);
}
byte[] serializedFlags = boas.toByteArray();
byte[] encodedFlags = Base64.getUrlEncoder().encode(serializedFlags);
// Inject the UserAgent in addition to api-client header
Map<String, String> headers =