-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathtable.py
2605 lines (2104 loc) · 80.7 KB
/
table.py
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
# -*- coding: utf-8 -*-
import abc
import ydb
from abc import abstractmethod
import logging
import time
import random
import enum
from . import (
issues,
convert,
settings as settings_impl,
scheme,
types,
_utilities,
_apis,
_sp_impl,
_session_impl,
_tx_ctx_impl,
tracing,
)
from ._errors import check_retriable_error
try:
from . import interceptor
except ImportError:
interceptor = None
_default_allow_split_transaction = False
logger = logging.getLogger(__name__)
##################################################################
# A deprecated aliases in case when direct import has been used #
##################################################################
SessionPoolEmpty = issues.SessionPoolEmpty
DataQuery = types.DataQuery
class DescribeTableSettings(settings_impl.BaseRequestSettings):
def __init__(self):
super(DescribeTableSettings, self).__init__()
self.include_shard_key_bounds = False
self.include_table_stats = False
def with_include_shard_key_bounds(self, value):
self.include_shard_key_bounds = value
return self
def with_include_table_stats(self, value):
self.include_table_stats = value
return self
class ExecDataQuerySettings(settings_impl.BaseRequestSettings):
def __init__(self):
super(ExecDataQuerySettings, self).__init__()
self.keep_in_cache = True
def with_keep_in_cache(self, value):
self.keep_in_cache = value
return self
class KeyBound(object):
__slots__ = ("_equal", "value", "type")
def __init__(self, key_value, key_type=None, inclusive=False):
"""
Represents key bound.
:param key_value: An iterable with key values
:param key_type: A type of key
:param inclusive: A flag that indicates bound includes key provided in the value.
"""
try:
iter(key_value)
except TypeError:
assert False, "value must be iterable!"
if isinstance(key_type, types.TupleType):
key_type = key_type.proto
self._equal = inclusive
self.value = key_value
self.type = key_type
def is_inclusive(self):
return self._equal
def is_exclusive(self):
return not self._equal
def __str__(self):
if self._equal:
return "InclusiveKeyBound(Tuple%s)" % str(self.value)
return "ExclusiveKeyBound(Tuple%s)" % str(self.value)
@classmethod
def inclusive(cls, key_value, key_type):
return cls(key_value, key_type, True)
@classmethod
def exclusive(cls, key_value, key_type):
return cls(key_value, key_type, False)
class KeyRange(object):
__slots__ = ("from_bound", "to_bound")
def __init__(self, from_bound, to_bound):
self.from_bound = from_bound
self.to_bound = to_bound
def __repr__(self):
return self.__str__()
def __str__(self):
return "KeyRange(%s, %s)" % (str(self.from_bound), str(self.to_bound))
class Column(object):
def __init__(self, name, type, family=None):
self._name = name
self._type = type
self.family = family
def __eq__(self, other):
return self.name == other.name and self._type.item == other.type.item
@property
def name(self):
return self._name
@property
def type(self):
return self._type
def with_family(self, family):
self.family = family
return self
@property
def type_pb(self):
try:
return self._type.proto
except Exception:
return self._type
@enum.unique
class FeatureFlag(enum.IntEnum):
UNSPECIFIED = 0
ENABLED = 1
DISABLED = 2
@enum.unique
class AutoPartitioningPolicy(enum.IntEnum):
AUTO_PARTITIONING_POLICY_UNSPECIFIED = 0
DISABLED = 1
AUTO_SPLIT = 2
AUTO_SPLIT_MERGE = 3
@enum.unique
class IndexStatus(enum.IntEnum):
INDEX_STATUS_UNSPECIFIED = 0
READY = 1
BUILDING = 2
class CachingPolicy(object):
def __init__(self):
self._pb = _apis.ydb_table.CachingPolicy()
self.preset_name = None
def with_preset_name(self, preset_name):
self._pb.preset_name = preset_name
self.preset_name = preset_name
return self
def to_pb(self):
return self._pb
class ExecutionPolicy(object):
def __init__(self):
self._pb = _apis.ydb_table.ExecutionPolicy()
self.preset_name = None
def with_preset_name(self, preset_name):
self._pb.preset_name = preset_name
self.preset_name = preset_name
return self
def to_pb(self):
return self._pb
class CompactionPolicy(object):
def __init__(self):
self._pb = _apis.ydb_table.CompactionPolicy()
self.preset_name = None
def with_preset_name(self, preset_name):
self._pb.preset_name = preset_name
self.preset_name = preset_name
return self
def to_pb(self):
return self._pb
class SplitPoint(object):
def __init__(self, *args):
self._value = tuple(args)
@property
def value(self):
return self._value
class ExplicitPartitions(object):
def __init__(self, split_points):
self.split_points = split_points
class PartitioningPolicy(object):
def __init__(self):
self._pb = _apis.ydb_table.PartitioningPolicy()
self.preset_name = None
self.uniform_partitions = None
self.auto_partitioning = None
self.explicit_partitions = None
def with_preset_name(self, preset_name):
self._pb.preset_name = preset_name
self.preset_name = preset_name
return self
def with_uniform_partitions(self, uniform_partitions):
self._pb.uniform_partitions = uniform_partitions
self.uniform_partitions = uniform_partitions
return self
def with_explicit_partitions(self, explicit_partitions):
self.explicit_partitions = explicit_partitions
return self
def with_auto_partitioning(self, auto_partitioning):
self._pb.auto_partitioning = auto_partitioning
self.auto_partitioning = auto_partitioning
return self
def to_pb(self, table_description):
if self.explicit_partitions is not None:
column_types = {}
pk = set(table_description.primary_key)
for column in table_description.columns:
if column.name in pk:
column_types[column.name] = column.type
for split_point in self.explicit_partitions.split_points:
typed_value = self._pb.explicit_partitions.split_points.add()
split_point_type = types.TupleType()
prefix_size = len(split_point.value)
for pl_el_id, pk_name in enumerate(table_description.primary_key):
if pl_el_id >= prefix_size:
break
split_point_type.add_element(column_types[pk_name])
typed_value.type.MergeFrom(split_point_type.proto)
typed_value.value.MergeFrom(convert.from_native_value(split_point_type.proto, split_point.value))
return self._pb
class TableIndex(object):
def __init__(self, name):
self._pb = _apis.ydb_table.TableIndex()
self._pb.name = name
self.name = name
self.index_columns = []
# output only.
self.status = None
self.type = None
def with_global_index(self):
self._pb.global_index.SetInParent()
return self
def with_index_columns(self, *columns):
for column in columns:
self._pb.index_columns.append(column)
self.index_columns.append(column)
return self
def to_pb(self):
return self._pb
@enum.unique
class IndexType(enum.IntEnum):
SYNCHRONOUS = 0
ASYNCHRONOUS = 1
class ReplicationPolicy(object):
def __init__(self):
self._pb = _apis.ydb_table.ReplicationPolicy()
self.preset_name = None
self.replicas_count = None
self.allow_promotion = None
self.create_per_availability_zone = None
def with_preset_name(self, preset_name):
self._pb.preset_name = preset_name
self.preset_name = preset_name
return self
def with_replicas_count(self, replicas_count):
self._pb.replicas_count = replicas_count
self.replicas_count = replicas_count
return self
def with_create_per_availability_zone(self, create_per_availability_zone):
self._pb.create_per_availability_zone = create_per_availability_zone
self.create_per_availability_zone = create_per_availability_zone
return self
def with_allow_promotion(self, allow_promotion):
self._pb.allow_promotion = allow_promotion
self.allow_promotion = allow_promotion
return self
def to_pb(self):
return self._pb
class StoragePool(object):
def __init__(self, media):
self.media = media
def to_pb(self):
return _apis.ydb_table.StoragePool(media=self.media)
class StoragePolicy(object):
def __init__(self):
self._pb = _apis.ydb_table.StoragePolicy()
self.preset_name = None
self.syslog = None
self.log = None
self.data = None
self.keep_in_memory = None
self.external = None
def with_preset_name(self, preset_name):
self._pb.preset_name = preset_name
self.preset_name = preset_name
return self
def with_syslog_storage_settings(self, syslog_settings):
self._pb.syslog.MergeFrom(syslog_settings.to_pb())
self.syslog = syslog_settings
return self
def with_log_storage_settings(self, log_settings):
self._pb.log.MergeFrom(log_settings.to_pb())
self.log = log_settings
return self
def with_data_storage_settings(self, data_settings):
self._pb.data.MergeFrom(data_settings.to_pb())
self.data = data_settings
return self
def with_external_storage_settings(self, external_settings):
self._pb.external.MergeFrom(external_settings.to_pb())
self.external = external_settings
return self
def with_keep_in_memory(self, keep_in_memory):
self._pb.keep_in_memory = keep_in_memory
self.keep_in_memory = keep_in_memory
return self
def to_pb(self):
return self._pb
class TableProfile(object):
def __init__(self):
self.preset_name = None
self.compaction_policy = None
self.partitioning_policy = None
self.storage_policy = None
self.execution_policy = None
self.replication_policy = None
self.caching_policy = None
def with_preset_name(self, preset_name):
self.preset_name = preset_name
return self
def with_compaction_policy(self, compaction_policy):
self.compaction_policy = compaction_policy
return self
def with_partitioning_policy(self, partitioning_policy):
self.partitioning_policy = partitioning_policy
return self
def with_execution_policy(self, execution_policy):
self.execution_policy = execution_policy
return self
def with_caching_policy(self, caching_policy):
self.caching_policy = caching_policy
return self
def with_storage_policy(self, storage_policy):
self.storage_policy = storage_policy
return self
def with_replication_policy(self, replication_policy):
self.replication_policy = replication_policy
return self
def to_pb(self, table_description):
pb = _apis.ydb_table.TableProfile()
if self.preset_name is not None:
pb.preset_name = self.preset_name
if self.execution_policy is not None:
pb.execution_policy.MergeFrom(self.execution_policy.to_pb())
if self.storage_policy is not None:
pb.storage_policy.MergeFrom(self.storage_policy.to_pb())
if self.replication_policy is not None:
pb.replication_policy.MergeFrom(self.replication_policy.to_pb())
if self.caching_policy is not None:
pb.caching_policy.MergeFrom(self.caching_policy.to_pb())
if self.compaction_policy is not None:
pb.compaction_policy.MergeFrom(self.compaction_policy.to_pb())
if self.partitioning_policy is not None:
pb.partitioning_policy.MergeFrom(self.partitioning_policy.to_pb(table_description))
return pb
class DateTypeColumnModeSettings(object):
def __init__(self, column_name, expire_after_seconds=0):
self.column_name = column_name
self.expire_after_seconds = expire_after_seconds
def to_pb(self):
pb = _apis.ydb_table.DateTypeColumnModeSettings()
pb.column_name = self.column_name
pb.expire_after_seconds = self.expire_after_seconds
return pb
@enum.unique
class ColumnUnit(enum.IntEnum):
UNIT_UNSPECIFIED = 0
UNIT_SECONDS = 1
UNIT_MILLISECONDS = 2
UNIT_MICROSECONDS = 3
UNIT_NANOSECONDS = 4
class ValueSinceUnixEpochModeSettings(object):
def __init__(self, column_name, column_unit, expire_after_seconds=0):
self.column_name = column_name
self.column_unit = column_unit
self.expire_after_seconds = expire_after_seconds
def to_pb(self):
pb = _apis.ydb_table.ValueSinceUnixEpochModeSettings()
pb.column_name = self.column_name
pb.column_unit = self.column_unit
pb.expire_after_seconds = self.expire_after_seconds
return pb
class TtlSettings(object):
def __init__(self):
self.date_type_column = None
self.value_since_unix_epoch = None
def with_date_type_column(self, column_name, expire_after_seconds=0):
self.date_type_column = DateTypeColumnModeSettings(column_name, expire_after_seconds)
return self
def with_value_since_unix_epoch(self, column_name, column_unit, expire_after_seconds=0):
self.value_since_unix_epoch = ValueSinceUnixEpochModeSettings(column_name, column_unit, expire_after_seconds)
return self
def to_pb(self):
pb = _apis.ydb_table.TtlSettings()
if self.date_type_column is not None:
pb.date_type_column.MergeFrom(self.date_type_column.to_pb())
elif self.value_since_unix_epoch is not None:
pb.value_since_unix_epoch.MergeFrom(self.value_since_unix_epoch.to_pb())
else:
raise RuntimeError("Unspecified ttl settings mode")
return pb
class TableStats(object):
def __init__(self):
self.partitions = None
self.store_size = 0
def with_store_size(self, store_size):
self.store_size = store_size
return self
def with_partitions(self, partitions):
self.partitions = partitions
return self
class ReadReplicasSettings(object):
def __init__(self):
self.per_az_read_replicas_count = 0
self.any_az_read_replicas_count = 0
def with_any_az_read_replicas_count(self, any_az_read_replicas_count):
self.any_az_read_replicas_count = any_az_read_replicas_count
return self
def with_per_az_read_replicas_count(self, per_az_read_replicas_count):
self.per_az_read_replicas_count = per_az_read_replicas_count
return self
def to_pb(self):
pb = _apis.ydb_table.ReadReplicasSettings()
if self.per_az_read_replicas_count > 0:
pb.per_az_read_replicas_count = self.per_az_read_replicas_count
elif self.any_az_read_replicas_count > 0:
pb.any_az_read_replicas_count = self.any_az_read_replicas_count
return pb
class PartitioningSettings(object):
def __init__(self):
self.partitioning_by_size = 0
self.partition_size_mb = 0
self.partitioning_by_load = 0
self.min_partitions_count = 0
self.max_partitions_count = 0
def with_max_partitions_count(self, max_partitions_count):
self.max_partitions_count = max_partitions_count
return self
def with_min_partitions_count(self, min_partitions_count):
self.min_partitions_count = min_partitions_count
return self
def with_partitioning_by_load(self, partitioning_by_load):
self.partitioning_by_load = partitioning_by_load
return self
def with_partition_size_mb(self, partition_size_mb):
self.partition_size_mb = partition_size_mb
return self
def with_partitioning_by_size(self, partitioning_by_size):
self.partitioning_by_size = partitioning_by_size
return self
def to_pb(self):
pb = _apis.ydb_table.PartitioningSettings()
pb.partitioning_by_size = self.partitioning_by_size
pb.partition_size_mb = self.partition_size_mb
pb.partitioning_by_load = self.partitioning_by_load
pb.min_partitions_count = self.min_partitions_count
pb.max_partitions_count = self.max_partitions_count
return pb
class StorageSettings(object):
def __init__(self):
self.tablet_commit_log0 = None
self.tablet_commit_log1 = None
self.external = None
self.store_external_blobs = 0
def with_store_external_blobs(self, store_external_blobs):
self.store_external_blobs = store_external_blobs
return self
def with_external(self, external):
self.external = external
return self
def with_tablet_commit_log1(self, tablet_commit_log1):
self.tablet_commit_log1 = tablet_commit_log1
return self
def with_tablet_commit_log0(self, tablet_commit_log0):
self.tablet_commit_log0 = tablet_commit_log0
return self
def to_pb(self):
st = _apis.ydb_table.StorageSettings()
st.store_external_blobs = self.store_external_blobs
if self.external:
st.external.MergeFrom(self.external.to_pb())
if self.tablet_commit_log0:
st.tablet_commit_log0.MergeFrom(self.tablet_commit_log0.to_pb())
if self.tablet_commit_log1:
st.tablet_commit_log1.MergeFrom(self.tablet_commit_log1.to_pb())
return st
@enum.unique
class Compression(enum.IntEnum):
UNSPECIFIED = 0
NONE = 1
LZ4 = 2
class ColumnFamily(object):
def __init__(self):
self.compression = 0
self.name = None
self.data = None
self.keep_in_memory = 0
def with_name(self, name):
self.name = name
return self
def with_compression(self, compression):
self.compression = compression
return self
def with_data(self, data):
self.data = data
return self
def with_keep_in_memory(self, keep_in_memory):
self.keep_in_memory = keep_in_memory
return self
def to_pb(self):
cm = _apis.ydb_table.ColumnFamily()
cm.keep_in_memory = self.keep_in_memory
cm.compression = self.compression
if self.name is not None:
cm.name = self.name
if self.data is not None:
cm.data.MergeFrom(self.data.to_pb())
return cm
class TableDescription(object):
def __init__(self):
self.columns = []
self.primary_key = []
self.profile = None
self.indexes = []
self.column_families = []
self.ttl_settings = None
self.attributes = {}
self.uniform_partitions = 0
self.partition_at_keys = None
self.compaction_policy = None
self.key_bloom_filter = 0
self.read_replicas_settings = None
self.partitioning_settings = None
self.storage_settings = None
def with_storage_settings(self, storage_settings):
self.storage_settings = storage_settings
return self
def with_column(self, column):
self.columns.append(column)
return self
def with_columns(self, *columns):
for column in columns:
self.with_column(column)
return self
def with_primary_key(self, key):
self.primary_key.append(key)
return self
def with_primary_keys(self, *keys):
for pk in keys:
self.with_primary_key(pk)
return self
def with_column_family(self, column_family):
self.column_families.append(column_family)
return self
def with_column_families(self, *column_families):
for column_family in column_families:
self.with_column_family(column_family)
return self
def with_indexes(self, *indexes):
for index in indexes:
self.with_index(index)
return self
def with_index(self, index):
self.indexes.append(index)
return self
def with_profile(self, profile):
self.profile = profile
return self
def with_ttl(self, ttl_settings):
self.ttl_settings = ttl_settings
return self
def with_attributes(self, attributes):
self.attributes = attributes
return self
def with_uniform_partitions(self, uniform_partitions):
self.uniform_partitions = uniform_partitions
return self
def with_partition_at_keys(self, partition_at_keys):
self.partition_at_keys = partition_at_keys
return self
def with_key_bloom_filter(self, key_bloom_filter):
self.key_bloom_filter = key_bloom_filter
return self
def with_partitioning_settings(self, partitioning_settings):
self.partitioning_settings = partitioning_settings
return self
def with_read_replicas_settings(self, read_replicas_settings):
self.read_replicas_settings = read_replicas_settings
return self
def with_compaction_policy(self, compaction_policy):
self.compaction_policy = compaction_policy
return self
class AbstractTransactionModeBuilder(abc.ABC):
@property
@abc.abstractmethod
def name(self):
pass
@property
@abc.abstractmethod
def settings(self):
pass
class SnapshotReadOnly(AbstractTransactionModeBuilder):
__slots__ = ("_pb", "_name")
def __init__(self):
self._pb = _apis.ydb_table.SnapshotModeSettings()
self._name = "snapshot_read_only"
@property
def settings(self):
return self._pb
@property
def name(self):
return self._name
class SerializableReadWrite(AbstractTransactionModeBuilder):
__slots__ = ("_pb", "_name")
def __init__(self):
self._name = "serializable_read_write"
self._pb = _apis.ydb_table.SerializableModeSettings()
@property
def settings(self):
return self._pb
@property
def name(self):
return self._name
class OnlineReadOnly(AbstractTransactionModeBuilder):
__slots__ = ("_pb", "_name")
def __init__(self):
self._pb = _apis.ydb_table.OnlineModeSettings()
self._pb.allow_inconsistent_reads = False
self._name = "online_read_only"
def with_allow_inconsistent_reads(self):
self._pb.allow_inconsistent_reads = True
return self
@property
def settings(self):
return self._pb
@property
def name(self):
return self._name
class StaleReadOnly(AbstractTransactionModeBuilder):
__slots__ = ("_pb", "_name")
def __init__(self):
self._pb = _apis.ydb_table.StaleModeSettings()
self._name = "stale_read_only"
@property
def settings(self):
return self._pb
@property
def name(self):
return self._name
class BackoffSettings(object):
def __init__(self, ceiling=6, slot_duration=0.001, uncertain_ratio=0.5):
self.ceiling = ceiling
self.slot_duration = slot_duration
self.uncertain_ratio = uncertain_ratio
def calc_timeout(self, retry_number):
slots_count = 1 << min(retry_number, self.ceiling)
max_duration_ms = slots_count * self.slot_duration * 1000.0
# duration_ms = random.random() * max_duration_ms * uncertain_ratio) + max_duration_ms * (1 - uncertain_ratio)
duration_ms = max_duration_ms * (random.random() * self.uncertain_ratio + 1.0 - self.uncertain_ratio)
return duration_ms / 1000.0
class RetrySettings(object):
def __init__(
self,
max_retries=10,
max_session_acquire_timeout=None,
on_ydb_error_callback=None,
backoff_ceiling=6,
backoff_slot_duration=1,
get_session_client_timeout=5,
fast_backoff_settings=None,
slow_backoff_settings=None,
idempotent=False,
):
self.max_retries = max_retries
self.max_session_acquire_timeout = max_session_acquire_timeout
self.on_ydb_error_callback = (lambda e: None) if on_ydb_error_callback is None else on_ydb_error_callback
self.fast_backoff = BackoffSettings(10, 0.005) if fast_backoff_settings is None else fast_backoff_settings
self.slow_backoff = (
BackoffSettings(backoff_ceiling, backoff_slot_duration)
if slow_backoff_settings is None
else slow_backoff_settings
)
self.retry_not_found = True
self.idempotent = idempotent
self.retry_internal_error = True
self.unknown_error_handler = lambda e: None
self.get_session_client_timeout = get_session_client_timeout
if max_session_acquire_timeout is not None:
self.get_session_client_timeout = min(self.max_session_acquire_timeout, self.get_session_client_timeout)
def with_fast_backoff(self, backoff_settings):
self.fast_backoff = backoff_settings
return self
def with_slow_backoff(self, backoff_settings):
self.slow_backoff = backoff_settings
return self
class YdbRetryOperationSleepOpt(object):
def __init__(self, timeout):
self.timeout = timeout
def __eq__(self, other):
return type(self) == type(other) and self.timeout == other.timeout
def __repr__(self):
return "YdbRetryOperationSleepOpt(%s)" % self.timeout
class YdbRetryOperationFinalResult(object):
def __init__(self, result):
self.result = result
self.exc = None
def __eq__(self, other):
return type(self) == type(other) and self.result == other.result and self.exc == other.exc
def __repr__(self):
return "YdbRetryOperationFinalResult(%s, exc=%s)" % (self.result, self.exc)
def set_exception(self, exc):
self.exc = exc
def retry_operation_impl(callee, retry_settings=None, *args, **kwargs):
retry_settings = RetrySettings() if retry_settings is None else retry_settings
status = None
for attempt in range(retry_settings.max_retries + 1):
try:
result = YdbRetryOperationFinalResult(callee(*args, **kwargs))
yield result
if result.exc is not None:
raise result.exc
except issues.Error as e:
status = e
retry_settings.on_ydb_error_callback(e)
retriable_info = check_retriable_error(e, retry_settings, attempt)
if not retriable_info.is_retriable:
raise
skip_yield_error_types = [
issues.Aborted,
issues.BadSession,
issues.NotFound,
issues.InternalError,
]
yield_sleep = True
for t in skip_yield_error_types:
if isinstance(e, t):
yield_sleep = False
if yield_sleep:
yield YdbRetryOperationSleepOpt(retriable_info.sleep_timeout_seconds)
except Exception as e:
# you should provide your own handler you want
retry_settings.unknown_error_handler(e)
raise
raise status
def retry_operation_sync(callee, retry_settings=None, *args, **kwargs):
opt_generator = retry_operation_impl(callee, retry_settings, *args, **kwargs)
for next_opt in opt_generator:
if isinstance(next_opt, YdbRetryOperationSleepOpt):
time.sleep(next_opt.timeout)
else:
return next_opt.result
class TableClientSettings(object):
def __init__(self):
self._client_query_cache_enabled = False
self._native_datetime_in_result_sets = False
self._native_date_in_result_sets = False
self._make_result_sets_lazy = False
self._native_json_in_result_sets = False
self._native_interval_in_result_sets = False
self._native_timestamp_in_result_sets = False
self._allow_truncated_result = convert._default_allow_truncated_result
def with_native_timestamp_in_result_sets(self, enabled):
# type:(bool) -> ydb.TableClientSettings
self._native_timestamp_in_result_sets = enabled
return self
def with_native_interval_in_result_sets(self, enabled):
# type:(bool) -> ydb.TableClientSettings
self._native_interval_in_result_sets = enabled
return self