-
Notifications
You must be signed in to change notification settings - Fork 202
Expand file tree
/
Copy pathcommon.py
More file actions
1467 lines (1174 loc) · 49.5 KB
/
Copy pathcommon.py
File metadata and controls
1467 lines (1174 loc) · 49.5 KB
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
"""Common code used in the Temporal SDK."""
from __future__ import annotations
import asyncio
import inspect
import threading
import types
import warnings
from abc import ABC, abstractmethod
from collections.abc import Callable, Collection, Iterator, Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import IntEnum
from typing import (
Any,
ClassVar,
Generic,
TypeAlias,
TypeVar,
get_origin,
get_type_hints,
overload,
)
import google.protobuf.internal.containers
from typing_extensions import NamedTuple, Self
import temporalio.api.common.v1
import temporalio.api.deployment.v1
import temporalio.api.enums.v1
import temporalio.api.workflow.v1
import temporalio.types
@dataclass
class RetryPolicy:
"""Options for retrying workflows and activities."""
initial_interval: timedelta = timedelta(seconds=1)
"""Backoff interval for the first retry. Default 1s."""
backoff_coefficient: float = 2.0
"""Coefficient to multiply previous backoff interval by to get new
interval. Default 2.0.
"""
maximum_interval: timedelta | None = None
"""Maximum backoff interval between retries. Default 100x
:py:attr:`initial_interval`.
"""
maximum_attempts: int = 0
"""Maximum number of attempts.
If 0, the default, there is no maximum.
"""
non_retryable_error_types: Sequence[str] | None = None
"""List of error types that are not retryable."""
@staticmethod
def from_proto(proto: temporalio.api.common.v1.RetryPolicy) -> RetryPolicy:
"""Create a retry policy from the proto object."""
return RetryPolicy(
initial_interval=proto.initial_interval.ToTimedelta(),
backoff_coefficient=proto.backoff_coefficient,
maximum_interval=proto.maximum_interval.ToTimedelta()
if proto.HasField("maximum_interval")
else None,
maximum_attempts=proto.maximum_attempts,
non_retryable_error_types=list(proto.non_retryable_error_types)
if proto.non_retryable_error_types
else None,
)
def apply_to_proto(self, proto: temporalio.api.common.v1.RetryPolicy) -> None:
"""Apply the fields in this policy to the given proto object."""
# Do validation before converting
self._validate()
# Convert
proto.initial_interval.FromTimedelta(self.initial_interval)
proto.backoff_coefficient = self.backoff_coefficient
proto.maximum_interval.FromTimedelta(
self.maximum_interval or self.initial_interval * 100
)
proto.maximum_attempts = self.maximum_attempts
if self.non_retryable_error_types:
proto.non_retryable_error_types.extend(self.non_retryable_error_types)
def _validate(self) -> None:
# Validation taken from Go SDK's test suite
if self.maximum_attempts == 1:
# Ignore other validation if disabling retries
return
if self.initial_interval.total_seconds() < 0:
raise ValueError("Initial interval cannot be negative")
if self.backoff_coefficient < 1:
raise ValueError("Backoff coefficient cannot be less than 1")
if self.maximum_interval:
if self.maximum_interval.total_seconds() < 0:
raise ValueError("Maximum interval cannot be negative")
if self.maximum_interval < self.initial_interval:
raise ValueError(
"Maximum interval cannot be less than initial interval"
)
if self.maximum_attempts < 0:
raise ValueError("Maximum attempts cannot be negative")
class WorkflowIDReusePolicy(IntEnum):
"""How already-in-use workflow IDs are handled on start.
See :py:class:`temporalio.api.enums.v1.WorkflowIdReusePolicy`.
"""
ALLOW_DUPLICATE = int(
temporalio.api.enums.v1.WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE
)
ALLOW_DUPLICATE_FAILED_ONLY = int(
temporalio.api.enums.v1.WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE_FAILED_ONLY
)
REJECT_DUPLICATE = int(
temporalio.api.enums.v1.WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_REJECT_DUPLICATE
)
TERMINATE_IF_RUNNING = int(
temporalio.api.enums.v1.WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_TERMINATE_IF_RUNNING
)
class WorkflowIDConflictPolicy(IntEnum):
"""How already-running workflows of the same ID are handled on start.
See :py:class:`temporalio.api.enums.v1.WorkflowIdConflictPolicy`.
"""
UNSPECIFIED = int(
temporalio.api.enums.v1.WorkflowIdConflictPolicy.WORKFLOW_ID_CONFLICT_POLICY_UNSPECIFIED
)
FAIL = int(
temporalio.api.enums.v1.WorkflowIdConflictPolicy.WORKFLOW_ID_CONFLICT_POLICY_FAIL
)
USE_EXISTING = int(
temporalio.api.enums.v1.WorkflowIdConflictPolicy.WORKFLOW_ID_CONFLICT_POLICY_USE_EXISTING
)
TERMINATE_EXISTING = int(
temporalio.api.enums.v1.WorkflowIdConflictPolicy.WORKFLOW_ID_CONFLICT_POLICY_TERMINATE_EXISTING
)
class ActivityIDReusePolicy(IntEnum):
"""How already-closed activity IDs are handled on start.
.. warning::
This API is experimental.
See :py:class:`temporalio.api.enums.v1.ActivityIdReusePolicy`.
"""
UNSPECIFIED = int(
temporalio.api.enums.v1.ActivityIdReusePolicy.ACTIVITY_ID_REUSE_POLICY_UNSPECIFIED
)
ALLOW_DUPLICATE = int(
temporalio.api.enums.v1.ActivityIdReusePolicy.ACTIVITY_ID_REUSE_POLICY_ALLOW_DUPLICATE
)
ALLOW_DUPLICATE_FAILED_ONLY = int(
temporalio.api.enums.v1.ActivityIdReusePolicy.ACTIVITY_ID_REUSE_POLICY_ALLOW_DUPLICATE_FAILED_ONLY
)
REJECT_DUPLICATE = int(
temporalio.api.enums.v1.ActivityIdReusePolicy.ACTIVITY_ID_REUSE_POLICY_REJECT_DUPLICATE
)
class ActivityIDConflictPolicy(IntEnum):
"""How already-running activity IDs are handled on start.
.. warning::
This API is experimental.
See :py:class:`temporalio.api.enums.v1.ActivityIdConflictPolicy`.
"""
UNSPECIFIED = int(
temporalio.api.enums.v1.ActivityIdConflictPolicy.ACTIVITY_ID_CONFLICT_POLICY_UNSPECIFIED
)
FAIL = int(
temporalio.api.enums.v1.ActivityIdConflictPolicy.ACTIVITY_ID_CONFLICT_POLICY_FAIL
)
USE_EXISTING = int(
temporalio.api.enums.v1.ActivityIdConflictPolicy.ACTIVITY_ID_CONFLICT_POLICY_USE_EXISTING
)
class NexusOperationIDReusePolicy(IntEnum):
"""How already-closed Nexus operation IDs are handled on start.
.. warning::
This API is experimental and unstable.
See :py:class:`temporalio.api.enums.v1.NexusOperationIdReusePolicy`.
"""
UNSPECIFIED = int(
temporalio.api.enums.v1.NexusOperationIdReusePolicy.NEXUS_OPERATION_ID_REUSE_POLICY_UNSPECIFIED
)
ALLOW_DUPLICATE = int(
temporalio.api.enums.v1.NexusOperationIdReusePolicy.NEXUS_OPERATION_ID_REUSE_POLICY_ALLOW_DUPLICATE
)
ALLOW_DUPLICATE_FAILED_ONLY = int(
temporalio.api.enums.v1.NexusOperationIdReusePolicy.NEXUS_OPERATION_ID_REUSE_POLICY_ALLOW_DUPLICATE_FAILED_ONLY
)
REJECT_DUPLICATE = int(
temporalio.api.enums.v1.NexusOperationIdReusePolicy.NEXUS_OPERATION_ID_REUSE_POLICY_REJECT_DUPLICATE
)
class NexusOperationIDConflictPolicy(IntEnum):
"""How already-running Nexus operation IDs are handled on start.
.. warning::
This API is experimental and unstable.
See :py:class:`temporalio.api.enums.v1.NexusOperationIdConflictPolicy`.
"""
UNSPECIFIED = int(
temporalio.api.enums.v1.NexusOperationIdConflictPolicy.NEXUS_OPERATION_ID_CONFLICT_POLICY_UNSPECIFIED
)
FAIL = int(
temporalio.api.enums.v1.NexusOperationIdConflictPolicy.NEXUS_OPERATION_ID_CONFLICT_POLICY_FAIL
)
USE_EXISTING = int(
temporalio.api.enums.v1.NexusOperationIdConflictPolicy.NEXUS_OPERATION_ID_CONFLICT_POLICY_USE_EXISTING
)
class NexusOperationExecutionStatus(IntEnum):
"""Status of a standalone Nexus operation execution.
.. warning::
This API is experimental and unstable.
See :py:class:`temporalio.api.enums.v1.NexusOperationExecutionStatus`.
"""
UNSPECIFIED = int(
temporalio.api.enums.v1.NexusOperationExecutionStatus.NEXUS_OPERATION_EXECUTION_STATUS_UNSPECIFIED
)
RUNNING = int(
temporalio.api.enums.v1.NexusOperationExecutionStatus.NEXUS_OPERATION_EXECUTION_STATUS_RUNNING
)
COMPLETED = int(
temporalio.api.enums.v1.NexusOperationExecutionStatus.NEXUS_OPERATION_EXECUTION_STATUS_COMPLETED
)
FAILED = int(
temporalio.api.enums.v1.NexusOperationExecutionStatus.NEXUS_OPERATION_EXECUTION_STATUS_FAILED
)
CANCELED = int(
temporalio.api.enums.v1.NexusOperationExecutionStatus.NEXUS_OPERATION_EXECUTION_STATUS_CANCELED
)
TERMINATED = int(
temporalio.api.enums.v1.NexusOperationExecutionStatus.NEXUS_OPERATION_EXECUTION_STATUS_TERMINATED
)
TIMED_OUT = int(
temporalio.api.enums.v1.NexusOperationExecutionStatus.NEXUS_OPERATION_EXECUTION_STATUS_TIMED_OUT
)
class PendingNexusOperationExecutionState(IntEnum):
"""More detailed breakdown of :py:attr:`NexusOperationExecutionStatus.RUNNING`.
.. warning::
This API is experimental and unstable.
See :py:class:`temporalio.api.enums.v1.PendingNexusOperationState`.
"""
UNSPECIFIED = int(
temporalio.api.enums.v1.PendingNexusOperationState.PENDING_NEXUS_OPERATION_STATE_UNSPECIFIED
)
SCHEDULED = int(
temporalio.api.enums.v1.PendingNexusOperationState.PENDING_NEXUS_OPERATION_STATE_SCHEDULED
)
BACKING_OFF = int(
temporalio.api.enums.v1.PendingNexusOperationState.PENDING_NEXUS_OPERATION_STATE_BACKING_OFF
)
STARTED = int(
temporalio.api.enums.v1.PendingNexusOperationState.PENDING_NEXUS_OPERATION_STATE_STARTED
)
BLOCKED = int(
temporalio.api.enums.v1.PendingNexusOperationState.PENDING_NEXUS_OPERATION_STATE_BLOCKED
)
class NexusOperationCancellationState(IntEnum):
"""State of a Nexus operation cancellation.
.. warning::
This API is experimental and unstable.
"""
UNSPECIFIED = int(
temporalio.api.enums.v1.NexusOperationCancellationState.NEXUS_OPERATION_CANCELLATION_STATE_UNSPECIFIED
)
"""Default value, unspecified state."""
SCHEDULED = int(
temporalio.api.enums.v1.NexusOperationCancellationState.NEXUS_OPERATION_CANCELLATION_STATE_SCHEDULED
)
"""Cancellation request is in the queue waiting to be executed or is currently executing."""
BACKING_OFF = int(
temporalio.api.enums.v1.NexusOperationCancellationState.NEXUS_OPERATION_CANCELLATION_STATE_BACKING_OFF
)
"""Cancellation request has failed with a retryable error and is backing off before the next attempt."""
SUCCEEDED = int(
temporalio.api.enums.v1.NexusOperationCancellationState.NEXUS_OPERATION_CANCELLATION_STATE_SUCCEEDED
)
"""Cancellation request succeeded."""
FAILED = int(
temporalio.api.enums.v1.NexusOperationCancellationState.NEXUS_OPERATION_CANCELLATION_STATE_FAILED
)
"""Cancellation request failed with a non-retryable error."""
TIMED_OUT = int(
temporalio.api.enums.v1.NexusOperationCancellationState.NEXUS_OPERATION_CANCELLATION_STATE_TIMED_OUT
)
"""The associated operation timed out - exceeded the user supplied schedule-to-close timeout."""
BLOCKED = int(
temporalio.api.enums.v1.NexusOperationCancellationState.NEXUS_OPERATION_CANCELLATION_STATE_BLOCKED
)
"""Cancellation request is blocked, eg: by circuit breaker."""
class QueryRejectCondition(IntEnum):
"""Whether a query should be rejected in certain conditions.
See :py:class:`temporalio.api.enums.v1.QueryRejectCondition`.
"""
NONE = int(temporalio.api.enums.v1.QueryRejectCondition.QUERY_REJECT_CONDITION_NONE)
NOT_OPEN = int(
temporalio.api.enums.v1.QueryRejectCondition.QUERY_REJECT_CONDITION_NOT_OPEN
)
NOT_COMPLETED_CLEANLY = int(
temporalio.api.enums.v1.QueryRejectCondition.QUERY_REJECT_CONDITION_NOT_COMPLETED_CLEANLY
)
@dataclass(frozen=True)
class RawValue:
"""Representation of an unconverted, raw payload.
This type can be used as a parameter or return type in workflows,
activities, signals, and queries to pass through a raw payload.
Encoding/decoding of the payload is still done by the system.
"""
payload: temporalio.api.common.v1.Payload
def __getstate__(self) -> object:
"""Pickle support."""
# We'll convert payload to bytes and prepend a version number just in
# case we want to extend in the future
return b"1" + self.payload.SerializeToString()
def __setstate__(self, state: object) -> None:
"""Pickle support."""
if not isinstance(state, bytes):
raise TypeError(f"Expected bytes state, got {type(state)}")
if not state[:1] == b"1":
raise ValueError("Bad version prefix")
object.__setattr__(
self, "payload", temporalio.api.common.v1.Payload.FromString(state[1:])
)
# We choose to make this a list instead of an sequence so we can catch if people
# are not sending lists each time but maybe accidentally sending a string (which
# is a sequence)
SearchAttributeValues: TypeAlias = (
list[str] | list[int] | list[float] | list[bool] | list[datetime]
)
SearchAttributes: TypeAlias = Mapping[str, SearchAttributeValues]
SearchAttributeValue: TypeAlias = str | int | float | bool | datetime | Sequence[str]
SearchAttributeValueType = TypeVar(
"SearchAttributeValueType", str, int, float, bool, datetime, Sequence[str]
)
class SearchAttributeIndexedValueType(IntEnum):
"""Server index type of a search attribute."""
TEXT = int(temporalio.api.enums.v1.IndexedValueType.INDEXED_VALUE_TYPE_TEXT)
KEYWORD = int(temporalio.api.enums.v1.IndexedValueType.INDEXED_VALUE_TYPE_KEYWORD)
INT = int(temporalio.api.enums.v1.IndexedValueType.INDEXED_VALUE_TYPE_INT)
DOUBLE = int(temporalio.api.enums.v1.IndexedValueType.INDEXED_VALUE_TYPE_DOUBLE)
BOOL = int(temporalio.api.enums.v1.IndexedValueType.INDEXED_VALUE_TYPE_BOOL)
DATETIME = int(temporalio.api.enums.v1.IndexedValueType.INDEXED_VALUE_TYPE_DATETIME)
KEYWORD_LIST = int(
temporalio.api.enums.v1.IndexedValueType.INDEXED_VALUE_TYPE_KEYWORD_LIST
)
class SearchAttributeKey(ABC, Generic[SearchAttributeValueType]):
"""Typed search attribute key representation.
Use one of the ``for`` static methods here to create a key.
"""
@property
@abstractmethod
def name(self) -> str:
"""Get the name of the key."""
...
@property
@abstractmethod
def indexed_value_type(self) -> SearchAttributeIndexedValueType:
"""Get the server index typed of the key"""
...
@property
@abstractmethod
def value_type(self) -> type[SearchAttributeValueType]:
"""Get the Python type of value for the key.
This may contain generics which cannot be used in ``isinstance``.
:py:attr:`origin_value_type` can be used instead.
"""
...
@property
def origin_value_type(self) -> type:
"""Get the Python type of value for the key without generics."""
return get_origin(self.value_type) or self.value_type
@property
def _metadata_type(self) -> str:
index_type = self.indexed_value_type
if index_type == SearchAttributeIndexedValueType.TEXT:
return "Text"
elif index_type == SearchAttributeIndexedValueType.KEYWORD:
return "Keyword"
elif index_type == SearchAttributeIndexedValueType.INT:
return "Int"
elif index_type == SearchAttributeIndexedValueType.DOUBLE:
return "Double"
elif index_type == SearchAttributeIndexedValueType.BOOL:
return "Bool"
elif index_type == SearchAttributeIndexedValueType.DATETIME:
return "Datetime"
elif index_type == SearchAttributeIndexedValueType.KEYWORD_LIST:
return "KeywordList"
raise ValueError(f"Unrecognized type: {self}")
def value_set(
self, value: SearchAttributeValueType
) -> SearchAttributeUpdate[SearchAttributeValueType]:
"""Create a search attribute update to set the given value on this
key.
"""
return _SearchAttributeUpdate[SearchAttributeValueType](self, value)
def value_unset(self) -> SearchAttributeUpdate[SearchAttributeValueType]:
"""Create a search attribute update to unset the value on this key."""
return _SearchAttributeUpdate[SearchAttributeValueType](self, None)
@staticmethod
def for_text(name: str) -> SearchAttributeKey[str]:
"""Create a 'Text' search attribute type."""
return _SearchAttributeKey[str](name, SearchAttributeIndexedValueType.TEXT, str)
@staticmethod
def for_keyword(name: str) -> SearchAttributeKey[str]:
"""Create a 'Keyword' search attribute type."""
return _SearchAttributeKey[str](
name, SearchAttributeIndexedValueType.KEYWORD, str
)
@staticmethod
def for_int(name: str) -> SearchAttributeKey[int]:
"""Create an 'Int' search attribute type."""
return _SearchAttributeKey[int](name, SearchAttributeIndexedValueType.INT, int)
@staticmethod
def for_float(name: str) -> SearchAttributeKey[float]:
"""Create a 'Double' search attribute type."""
return _SearchAttributeKey[float](
name, SearchAttributeIndexedValueType.DOUBLE, float
)
@staticmethod
def for_bool(name: str) -> SearchAttributeKey[bool]:
"""Create a 'Bool' search attribute type."""
return _SearchAttributeKey[bool](
name, SearchAttributeIndexedValueType.BOOL, bool
)
@staticmethod
def for_datetime(name: str) -> SearchAttributeKey[datetime]:
"""Create a 'Datetime' search attribute type."""
return _SearchAttributeKey[datetime](
name, SearchAttributeIndexedValueType.DATETIME, datetime
)
@staticmethod
def for_keyword_list(name: str) -> SearchAttributeKey[Sequence[str]]:
"""Create a 'KeywordList' search attribute type."""
return _SearchAttributeKey[Sequence[str]](
name,
SearchAttributeIndexedValueType.KEYWORD_LIST,
# Generic types not supported yet like this: https://github.com/python/mypy/issues/4717
Sequence[str], # type: ignore
)
@staticmethod
def _from_metadata_type(name: str, metadata_type: str) -> SearchAttributeKey | None:
# The type metadata is usually in PascalCase (e.g. "KeywordList")
# but in rare cases may be in SCREAMING_SNAKE_CASE (e.g.
# "INDEXED_VALUE_TYPE_KEYWORD_LIST").
if metadata_type in ("Text", "INDEXED_VALUE_TYPE_TEXT"):
return SearchAttributeKey.for_text(name)
elif metadata_type in ("Keyword", "INDEXED_VALUE_TYPE_KEYWORD"):
return SearchAttributeKey.for_keyword(name)
elif metadata_type in ("Int", "INDEXED_VALUE_TYPE_INT"):
return SearchAttributeKey.for_int(name)
elif metadata_type in ("Double", "INDEXED_VALUE_TYPE_DOUBLE"):
return SearchAttributeKey.for_float(name)
elif metadata_type in ("Bool", "INDEXED_VALUE_TYPE_BOOL"):
return SearchAttributeKey.for_bool(name)
elif metadata_type in ("Datetime", "INDEXED_VALUE_TYPE_DATETIME"):
return SearchAttributeKey.for_datetime(name)
elif metadata_type in ("KeywordList", "INDEXED_VALUE_TYPE_KEYWORD_LIST"):
return SearchAttributeKey.for_keyword_list(name)
return None
@staticmethod
def _guess_from_untyped_values(
name: str, vals: SearchAttributeValues
) -> SearchAttributeKey | None:
if not vals:
return None
elif len(vals) > 1:
if isinstance(vals[0], str):
return SearchAttributeKey.for_keyword_list(name)
elif isinstance(vals[0], str):
return SearchAttributeKey.for_keyword(name)
elif isinstance(vals[0], int):
return SearchAttributeKey.for_int(name)
elif isinstance(vals[0], float):
return SearchAttributeKey.for_float(name)
elif isinstance(vals[0], bool):
return SearchAttributeKey.for_bool(name)
elif isinstance(vals[0], datetime):
return SearchAttributeKey.for_datetime(name)
return None
@dataclass(frozen=True)
class _SearchAttributeKey(SearchAttributeKey[SearchAttributeValueType]):
_name: str
_indexed_value_type: SearchAttributeIndexedValueType
# No supported way in Python to derive this, so we're setting manually
_value_type: type[SearchAttributeValueType]
@property
def name(self) -> str:
return self._name
@property
def indexed_value_type(self) -> SearchAttributeIndexedValueType:
return self._indexed_value_type
@property
def value_type(self) -> type[SearchAttributeValueType]:
return self._value_type
class SearchAttributePair(NamedTuple, Generic[SearchAttributeValueType]):
"""A named tuple representing a key/value search attribute pair."""
key: SearchAttributeKey[SearchAttributeValueType]
value: SearchAttributeValueType
class SearchAttributeUpdate(ABC, Generic[SearchAttributeValueType]):
"""Representation of a search attribute update."""
@property
@abstractmethod
def key(self) -> SearchAttributeKey[SearchAttributeValueType]:
"""Key that is being set."""
...
@property
@abstractmethod
def value(self) -> SearchAttributeValueType | None:
"""Value that is being set or ``None`` if being unset."""
...
@dataclass(frozen=True)
class _SearchAttributeUpdate(SearchAttributeUpdate[SearchAttributeValueType]):
_key: SearchAttributeKey[SearchAttributeValueType]
_value: SearchAttributeValueType | None
@property
def key(self) -> SearchAttributeKey[SearchAttributeValueType]:
return self._key
@property
def value(self) -> SearchAttributeValueType | None:
return self._value
@dataclass(frozen=True)
class TypedSearchAttributes(Collection[SearchAttributePair]):
"""Collection of typed search attributes.
This is represented as an immutable collection of
:py:class:`SearchAttributePair`. This can be created passing a sequence of
pairs to the constructor.
"""
search_attributes: Sequence[SearchAttributePair]
"""Underlying sequence of search attribute pairs. Do not mutate this, only
create new ``TypedSearchAttribute`` instances.
These are sorted by key name during construction. Duplicates cannot exist.
"""
empty: ClassVar[TypedSearchAttributes]
"""Class variable representing an empty set of attributes."""
def __post_init__(self):
"""Post-init initialization."""
# Sort
object.__setattr__(
self,
"search_attributes",
sorted(self.search_attributes, key=lambda pair: pair.key.name),
)
# Ensure no duplicates
for i, pair in enumerate(self.search_attributes):
if i > 0 and self.search_attributes[i - 1].key.name == pair.key.name:
raise ValueError(
f"Duplicate search attribute entries found for key {pair.key.name}"
)
def __len__(self) -> int:
"""Get the number of search attributes."""
return len(self.search_attributes)
def __getitem__(
self, key: SearchAttributeKey[SearchAttributeValueType]
) -> SearchAttributeValueType:
"""Get a single search attribute value by key or fail with
``KeyError``.
"""
ret = next((v for k, v in self if k == key), None)
if ret is None:
raise KeyError()
return ret
def __iter__(self) -> Iterator[SearchAttributePair]:
"""Get an iterator over search attribute key/value pairs."""
return iter(self.search_attributes)
def __contains__(self, key: object) -> bool:
"""Check whether this search attribute contains the given key.
This uses key equality so the key must be the same name and type.
"""
return any(k == key for k, _v in self)
@overload
def get(
self, key: SearchAttributeKey[SearchAttributeValueType]
) -> SearchAttributeValueType | None: ...
@overload
def get(
self,
key: SearchAttributeKey[SearchAttributeValueType],
default: temporalio.types.AnyType,
) -> SearchAttributeValueType | temporalio.types.AnyType: ...
def get(
self,
key: SearchAttributeKey[SearchAttributeValueType],
default: Any | None = None,
) -> Any:
"""Get an attribute value for a key (or default). This is similar to
dict.get.
"""
try:
return self.__getitem__(key)
except KeyError:
return default
def updated(self, *search_attributes: SearchAttributePair) -> TypedSearchAttributes:
"""Copy this collection, replacing attributes with matching key names or
adding if key name not present.
"""
attrs = list(self.search_attributes)
# Go over each update, replacing matching keys by index or adding
for attr in search_attributes:
existing_index = next(
(
i
for i, index_attr in enumerate(attrs)
if attr.key.name == index_attr.key.name
),
None,
)
if existing_index is None:
attrs.append(attr)
else:
attrs[existing_index] = attr
return TypedSearchAttributes(attrs)
TypedSearchAttributes.empty = TypedSearchAttributes(search_attributes=[])
def _warn_on_deprecated_search_attributes( # type:ignore[reportUnusedFunction]
attributes: SearchAttributes | Any | None,
stack_level: int = 2,
) -> None:
if attributes and isinstance(attributes, Mapping):
warnings.warn(
"Dictionary-based search attributes are deprecated",
DeprecationWarning,
stacklevel=1 + stack_level,
)
MetricAttributes: TypeAlias = Mapping[str, str | int | float | bool]
class MetricMeter(ABC):
"""Metric meter for recording metrics."""
noop: ClassVar[MetricMeter]
"""Metric meter implementation that does nothing."""
@abstractmethod
def create_counter(
self, name: str, description: str | None = None, unit: str | None = None
) -> MetricCounter:
"""Create a counter metric for adding values.
Args:
name: Name for the metric.
description: Optional description for the metric.
unit: Optional unit for the metric.
Returns:
Counter metric.
"""
...
@abstractmethod
def create_histogram(
self, name: str, description: str | None = None, unit: str | None = None
) -> MetricHistogram:
"""Create a histogram metric for recording values.
Args:
name: Name for the metric.
description: Optional description for the metric.
unit: Optional unit for the metric.
Returns:
Histogram metric.
"""
...
@abstractmethod
def create_histogram_float(
self, name: str, description: str | None = None, unit: str | None = None
) -> MetricHistogramFloat:
"""Create a histogram metric for recording values.
Args:
name: Name for the metric.
description: Optional description for the metric.
unit: Optional unit for the metric.
Returns:
Histogram metric.
"""
...
@abstractmethod
def create_histogram_timedelta(
self, name: str, description: str | None = None, unit: str | None = None
) -> MetricHistogramTimedelta:
"""Create a histogram metric for recording values.
Note, duration precision is millisecond. Also note, if "unit" is set as
"duration", it will be converted to "ms" or "s" on the way out.
Args:
name: Name for the metric.
description: Optional description for the metric.
unit: Optional unit for the metric.
Returns:
Histogram metric.
"""
...
@abstractmethod
def create_gauge(
self, name: str, description: str | None = None, unit: str | None = None
) -> MetricGauge:
"""Create a gauge metric for setting values.
Args:
name: Name for the metric.
description: Optional description for the metric.
unit: Optional unit for the metric.
Returns:
Gauge metric.
"""
...
@abstractmethod
def create_gauge_float(
self, name: str, description: str | None = None, unit: str | None = None
) -> MetricGaugeFloat:
"""Create a gauge metric for setting values.
Args:
name: Name for the metric.
description: Optional description for the metric.
unit: Optional unit for the metric.
Returns:
Gauge metric.
"""
...
@abstractmethod
def with_additional_attributes(
self, additional_attributes: MetricAttributes
) -> MetricMeter:
"""Create a new metric meter with the given attributes appended to the
current set.
Args:
additional_attributes: Additional attributes to append to the
current set.
Returns:
New metric meter.
Raises:
TypeError: Attribute values are not the expected type.
"""
...
class MetricCommon(ABC):
"""Base for all metrics."""
@property
@abstractmethod
def name(self) -> str:
"""Name for the metric."""
...
@property
@abstractmethod
def description(self) -> str | None:
"""Description for the metric if any."""
...
@property
@abstractmethod
def unit(self) -> str | None:
"""Unit for the metric if any."""
...
@abstractmethod
def with_additional_attributes(
self, additional_attributes: MetricAttributes
) -> Self:
"""Create a new metric with the given attributes appended to the
current set.
Args:
additional_attributes: Additional attributes to append to the
current set.
Returns:
New metric.
Raises:
TypeError: Attribute values are not the expected type.
"""
...
class MetricCounter(MetricCommon):
"""Counter metric created by a metric meter."""
@abstractmethod
def add(
self, value: int, additional_attributes: MetricAttributes | None = None
) -> None:
"""Add a value to the counter.
Args:
value: A non-negative integer to add.
additional_attributes: Additional attributes to append to the
current set.
Raises:
ValueError: Value is negative.
TypeError: Attribute values are not the expected type.
"""
...
class MetricHistogram(MetricCommon):
"""Histogram metric created by a metric meter."""
@abstractmethod
def record(
self, value: int, additional_attributes: MetricAttributes | None = None
) -> None:
"""Record a value on the histogram.
Args:
value: A non-negative integer to record.
additional_attributes: Additional attributes to append to the
current set.
Raises:
ValueError: Value is negative.
TypeError: Attribute values are not the expected type.
"""
...
class MetricHistogramFloat(MetricCommon):
"""Histogram metric created by a metric meter."""
@abstractmethod
def record(
self, value: float, additional_attributes: MetricAttributes | None = None
) -> None:
"""Record a value on the histogram.
Args:
value: A non-negative float to record.
additional_attributes: Additional attributes to append to the
current set.
Raises:
ValueError: Value is negative.
TypeError: Attribute values are not the expected type.
"""
...
class MetricHistogramTimedelta(MetricCommon):
"""Histogram metric created by a metric meter."""
@abstractmethod
def record(
self, value: timedelta, additional_attributes: MetricAttributes | None = None
) -> None:
"""Record a value on the histogram.
Note, duration precision is millisecond.
Args:
value: A non-negative timedelta to record.
additional_attributes: Additional attributes to append to the
current set.
Raises:
ValueError: Value is negative.
TypeError: Attribute values are not the expected type.
"""
...
class MetricGauge(MetricCommon):