kuflow-temporal-worker 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
README.md ADDED
@@ -0,0 +1,19 @@
1
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://github.com/kuflow/kuflow-sdk-python/blob/master/LICENSE)
2
+ [![Python](https://img.shields.io/pypi/pyversions/kuflow-temporal-worker.svg)](https://pypi.org/project/kuflow-temporal-worker)
3
+ [![PyPI](https://img.shields.io/pypi/v/kuflow-temporal-worker.svg)](https://pypi.org/project/kuflow-temporal-worker)
4
+
5
+ # KuFlow Temporal Common
6
+
7
+ TODO
8
+
9
+ ## Documentation
10
+
11
+ More detailed docs are available in the [documentation pages](https://docs.kuflow.com/developers/).
12
+
13
+ ## Contributing
14
+
15
+ We are happy to receive your help and comments, together we will dance a wonderful KuFlow. Please review our [contribution guide](CONTRIBUTING.md).
16
+
17
+ ## License
18
+
19
+ [MIT License](https://github.com/kuflow/kuflow-sdk-python/blob/master/LICENSE)
VERSION ADDED
@@ -0,0 +1 @@
1
+ 2.0.0
@@ -0,0 +1,45 @@
1
+ #
2
+ # MIT License
3
+ #
4
+ # Copyright (c) 2022 KuFlow
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in all
14
+ # copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ # SOFTWARE.
23
+ #
24
+
25
+ from kuflow_temporal_worker._connection import KuFlowTemporalConnection
26
+ from kuflow_temporal_worker._connection_config import (
27
+ KuFlowAuthorizationTokenProviderBackoff,
28
+ KuFlowConfig,
29
+ KuFlowWorkerInformationNotifierBackoff,
30
+ TemporalClientConfig,
31
+ TemporalConfig,
32
+ TemporalWorkerConfig,
33
+ )
34
+
35
+
36
+ __all__ = [
37
+ "KuFlowAuthorizationTokenProviderBackoff",
38
+ "KuFlowConfig",
39
+ "KuFlowTemporalConnection",
40
+ "KuFlowWorkerInformationNotifierBackoff",
41
+ "TemporalClientConfig",
42
+ "TemporalConfig",
43
+ "TemporalWorkerConfig",
44
+ ]
45
+ __version__ = "2.0.0.dev0"
@@ -0,0 +1,131 @@
1
+ #
2
+ # MIT License
3
+ #
4
+ # Copyright (c) 2022 KuFlow
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in all
14
+ # copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ # SOFTWARE.
23
+ #
24
+
25
+ import asyncio
26
+ import datetime
27
+ import logging
28
+ from typing import Mapping, Optional
29
+
30
+ from temporalio.client import Client
31
+
32
+ from kuflow_rest import models as models_rest
33
+
34
+ from ._connection_config import (
35
+ KuFlowAuthorizationTokenProviderBackoff,
36
+ KuFlowConfig,
37
+ TemporalConfig,
38
+ )
39
+
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+
44
+ class KuFlowAuthorizationTokenProvider:
45
+ def __init__(
46
+ self,
47
+ kuflow_config: KuFlowConfig,
48
+ temporal_config: TemporalConfig,
49
+ ):
50
+ self._temporal_client: Optional[Client] = None
51
+ self._temporal_config = temporal_config
52
+ self._kuflow_config = kuflow_config
53
+ self._consecutive_failures = 0
54
+ self._backoff = (
55
+ kuflow_config.authorization_token_provider_backoff
56
+ if kuflow_config.authorization_token_provider_backoff
57
+ else KuFlowAuthorizationTokenProviderBackoff()
58
+ )
59
+
60
+ def initialize_rpc_auth_metadata(self, init_metadata=None) -> Mapping[str, str]:
61
+ if init_metadata is None:
62
+ init_metadata = {}
63
+
64
+ authentication = self._create_authentication()
65
+ metadata = {}
66
+ if authentication.engine_token.token:
67
+ metadata = self._set_auth_rpc_metadata(token=authentication.engine_token.token, metadata=init_metadata)
68
+
69
+ return metadata
70
+
71
+ def start_auto_refresh(self, temporal_client: Client):
72
+ self._temporal_client = temporal_client
73
+ self.schedule_authorization_token_renovation()
74
+
75
+ def schedule_authorization_token_renovation(self) -> None:
76
+ refresh_in_seconds = 0
77
+ asyncio.create_task(self._delayed_schedule_authorization_token_renovation(refresh_in_seconds))
78
+
79
+ async def _delayed_schedule_authorization_token_renovation(self, refresh_in_seconds):
80
+ await asyncio.sleep(refresh_in_seconds)
81
+ await self._refresh_authorization_token_renovation()
82
+
83
+ async def _refresh_authorization_token_renovation(self):
84
+ try:
85
+ logger.debug("Token renewal begins...")
86
+ authentication = self._create_authentication()
87
+ self._consecutive_failures = 0
88
+
89
+ if authentication.engine_token.token:
90
+ new_metadata = self._set_auth_rpc_metadata(
91
+ token=authentication.engine_token.token, metadata=self._temporal_client.rpc_metadata
92
+ )
93
+ self._temporal_client.rpc_metadata = new_metadata
94
+
95
+ refresh_in_seconds = (
96
+ (
97
+ authentication.engine_token.expired_at
98
+ - datetime.datetime.now(authentication.engine_token.expired_at.tzinfo)
99
+ ).total_seconds()
100
+ if authentication.engine_token.expired_at
101
+ else 0
102
+ )
103
+
104
+ logger.info(f"Token renewed. Next refresh in {refresh_in_seconds} seconds")
105
+
106
+ asyncio.create_task(self._delayed_schedule_authorization_token_renovation(refresh_in_seconds))
107
+ except Exception as err:
108
+ self._consecutive_failures = self._consecutive_failures + 1
109
+
110
+ retry_duration_in_seconds = round(
111
+ self._backoff.sleep * self._backoff.exponential_rate**self._consecutive_failures
112
+ )
113
+ refresh_in_seconds = min(retry_duration_in_seconds, self._backoff.max_sleep)
114
+
115
+ logger.error(f"Token renewal failed. Nex retry in {refresh_in_seconds} seconds", err)
116
+
117
+ asyncio.create_task(self._delayed_schedule_authorization_token_renovation(refresh_in_seconds))
118
+
119
+ def _set_auth_rpc_metadata(self, token: str, metadata: Mapping[str, str]):
120
+ new_metadata = dict(metadata)
121
+ new_metadata["authorization"] = "Bearer " + token
122
+
123
+ return new_metadata
124
+
125
+ def _create_authentication(self) -> models_rest.Authentication:
126
+ authentication_create_params = models_rest.AuthenticationCreateParams(
127
+ type=models_rest.AuthenticationType.ENGINE_TOKEN,
128
+ tenant_id=self._kuflow_config.tenant_id,
129
+ )
130
+
131
+ return self._kuflow_config.rest_client.authentication.create_authentication(authentication_create_params)
@@ -0,0 +1,186 @@
1
+ #
2
+ # MIT License
3
+ #
4
+ # Copyright (c) 2022 KuFlow
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in all
14
+ # copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ # SOFTWARE.
23
+ #
24
+
25
+ import dataclasses
26
+ from typing import Dict, List, Optional, Set
27
+
28
+ import temporalio.activity
29
+ import temporalio.common
30
+ import temporalio.converter
31
+ import temporalio.runtime
32
+ import temporalio.workflow
33
+ from temporalio.client import Client, TLSConfig
34
+ from temporalio.worker import Worker
35
+
36
+ from kuflow_rest import models
37
+ from kuflow_temporal_common import CompositeEncodingPayloadConverter, KuFlowComposableEncodingPayloadConverter
38
+
39
+ from ._authentication import KuFlowAuthorizationTokenProvider
40
+ from ._connection_config import (
41
+ KuFlowConfig,
42
+ TemporalConfig,
43
+ )
44
+ from ._worker_information_notifier import KuFlowWorkerInformationNotifier
45
+
46
+
47
+ class KuFlowTemporalConnection:
48
+ """Configure a temporal client and worker with KuFlow requirements."""
49
+
50
+ def __init__(self, *, kuflow: KuFlowConfig, temporal: TemporalConfig):
51
+ """Create a KuFlowTemporalConnection."""
52
+
53
+ self._kuflow = kuflow
54
+ self._temporal = temporal
55
+ self._kuflow_authorization_token_provider: Optional[KuFlowAuthorizationTokenProvider] = None
56
+ self._kuFlow_worker_information_notifier: Optional[KuFlowWorkerInformationNotifier] = None
57
+ self._client: Optional[Client] = None
58
+ self._worker: Optional[Worker] = None
59
+ self._workflow_types: Set[str] = set()
60
+ self._activity_types: Set[str] = set()
61
+
62
+ async def connect(self) -> Client:
63
+ """Connect to a Temporal server"""
64
+
65
+ if self._client is not None:
66
+ return self._client
67
+
68
+ self._apply_default_configurations()
69
+
70
+ # Initializing an KuFlow token provider
71
+ self._kuflow_authorization_token_provider = KuFlowAuthorizationTokenProvider(
72
+ temporal_config=self._temporal,
73
+ kuflow_config=self._kuflow,
74
+ )
75
+
76
+ self._temporal.client.rpc_metadata = self._kuflow_authorization_token_provider.initialize_rpc_auth_metadata()
77
+
78
+ self._register_encoding_payload_converter()
79
+
80
+ client_config = self._temporal.client.__dict__.copy()
81
+ client_config.pop("target_host", None)
82
+
83
+ target_host = self._temporal.client.target_host or "engine.kuflow.com:443"
84
+
85
+ self._client = await Client.connect(target_host, **client_config)
86
+
87
+ self._kuflow_authorization_token_provider.start_auto_refresh(self._client)
88
+
89
+ return self._client
90
+
91
+ async def create_worker(self) -> Worker:
92
+ """Create a new Worker. This method initiates a connection to the server."""
93
+
94
+ if self._worker is not None:
95
+ return self._worker
96
+
97
+ if self._temporal.worker is None:
98
+ raise TypeError("Worker configurations are required")
99
+
100
+ client = await self.connect()
101
+
102
+ worker_config = self._temporal.worker.__dict__.copy()
103
+
104
+ self._worker = Worker(client, **worker_config)
105
+
106
+ return self._worker
107
+
108
+ async def run_worker(self):
109
+ """Start the temporal worker configured."""
110
+
111
+ worker = await self.create_worker()
112
+
113
+ self._workflow_types.clear()
114
+ self._activity_types.clear()
115
+
116
+ for workflow in self._temporal.worker.workflows:
117
+ defn = temporalio.workflow._Definition.must_from_class(workflow)
118
+ self._workflow_types.add(defn.name)
119
+
120
+ for activity in self._temporal.worker.activities:
121
+ if isinstance(activity, str):
122
+ self._activity_types.add(activity)
123
+ elif callable(activity):
124
+ defn = temporalio.activity._Definition.must_from_callable(activity)
125
+ self._activity_types.add(defn.name)
126
+
127
+ self._kuFlow_worker_information_notifier = KuFlowWorkerInformationNotifier(
128
+ kuflow_client=self._kuflow.rest_client,
129
+ kuflow_config=self._kuflow,
130
+ temporal_config=self._temporal,
131
+ temporal_worker=worker,
132
+ temporal_client=self._client,
133
+ temporal_workflow_types=self._workflow_types,
134
+ temporal_activity_types=self._activity_types,
135
+ backoff=self._kuflow.worker_information_notifier_backoff,
136
+ )
137
+ await self._kuFlow_worker_information_notifier.start()
138
+
139
+ await worker.run()
140
+
141
+ def _register_encoding_payload_converter(self):
142
+ additional_converter_classes = [KuFlowComposableEncodingPayloadConverter]
143
+
144
+ converters = list(temporalio.converter.DefaultPayloadConverter.default_encoding_payload_converters)
145
+
146
+ converters_by_encoding: Dict[str, List[temporalio.converter.EncodingPayloadConverter]] = {}
147
+
148
+ for converter_class in additional_converter_classes:
149
+ converter = converter_class()
150
+
151
+ converters_encoding = converters_by_encoding.get(converter.encoding, None)
152
+ if converters_encoding is None:
153
+ converters_encoding = [it for it in converters if it.encoding == converter.encoding]
154
+
155
+ converters_encoding.insert(0, converter)
156
+ converters_by_encoding[converter.encoding] = converters_encoding
157
+
158
+ for encoding in converters_by_encoding:
159
+ composite_converter = CompositeEncodingPayloadConverter(
160
+ encoding=encoding, converters=converters_by_encoding[encoding]
161
+ )
162
+
163
+ converters = [it if it.encoding != encoding else composite_converter for it in converters]
164
+
165
+ temporalio.converter.DefaultPayloadConverter.default_encoding_payload_converters = tuple(converters)
166
+
167
+ self._temporal.client.data_converter = dataclasses.replace(temporalio.converter.DataConverter.default)
168
+
169
+ def _apply_default_configurations(self):
170
+ authentication = models.Authentication(
171
+ type=models.AuthenticationType.ENGINE_CERTIFICATE,
172
+ tenant_id=self._kuflow.tenant_id,
173
+ )
174
+ authentication = self._kuflow.rest_client.authentication.create_authentication(authentication)
175
+
176
+ if self._temporal.client.tls is False:
177
+ self._temporal.client.tls = TLSConfig(
178
+ server_root_ca_cert=authentication.engine_certificate.tls.server_root_ca_certificate.encode("utf-8"),
179
+ client_cert=authentication.engine_certificate.tls.client_certificate.encode("utf-8"),
180
+ client_private_key=authentication.engine_certificate.tls.client_private_key.encode("utf-8"),
181
+ )
182
+
183
+ if self._temporal.client.namespace is None:
184
+ self._temporal.client.namespace = authentication.engine_certificate.namespace
185
+
186
+ self._temporal.client.namespace = self._temporal.client.namespace or "default"
@@ -0,0 +1,276 @@
1
+ #
2
+ # MIT License
3
+ #
4
+ # Copyright (c) 2022 KuFlow
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in all
14
+ # copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ # SOFTWARE.
23
+ #
24
+
25
+
26
+ import concurrent.futures
27
+ from dataclasses import dataclass, field
28
+ from datetime import timedelta
29
+ from typing import Awaitable, Callable, List, Mapping, Optional, Sequence, Type, Union
30
+
31
+ import temporalio.common
32
+ import temporalio.converter
33
+ import temporalio.runtime
34
+ import temporalio.workflow
35
+ from temporalio.client import HttpConnectProxyConfig, Interceptor, KeepAliveConfig, RetryConfig, TLSConfig
36
+ from temporalio.worker import SharedStateManager, UnsandboxedWorkflowRunner, WorkflowRunner
37
+ from temporalio.worker.workflow_sandbox import SandboxedWorkflowRunner
38
+
39
+ from kuflow_rest import KuFlowRestClient
40
+
41
+
42
+ class KuFlowAuthorizationTokenProviderBackoff:
43
+ """
44
+ :ivar sleep: Time in seconds to sleep
45
+ :type sleep: int
46
+ :ivar max_sleep: Maximum time in seconds reached in the backoff
47
+ :type max_sleep: int
48
+ :ivar exponential_rate: Increment rate factor
49
+ :type exponential_rate: int
50
+ """
51
+
52
+ def __init__(
53
+ self, sleep: Optional[int] = None, max_sleep: Optional[int] = None, exponential_rate: Optional[int] = None
54
+ ):
55
+ self.sleep = sleep if sleep else 1
56
+ self.max_sleep = max_sleep if max_sleep else 5 * 60
57
+ self.exponential_rate = exponential_rate if exponential_rate else 2.5
58
+
59
+
60
+ class KuFlowWorkerInformationNotifierBackoff:
61
+ """
62
+ :ivar sleep: Time in seconds to sleep
63
+ :type sleep: int
64
+ :ivar exponential_rate: Increment rate factor
65
+ :type exponential_rate: int
66
+ """
67
+
68
+ def __init__(self, sleep: Optional[int] = None, exponential_rate: Optional[int] = None):
69
+ self.sleep = sleep if sleep else 1
70
+ self.exponential_rate = exponential_rate if exponential_rate else 2.5
71
+
72
+
73
+ @dataclass
74
+ class KuFlowConfig:
75
+ """KuFlow configuration."""
76
+
77
+ rest_client: KuFlowRestClient
78
+ """Rest client used."""
79
+
80
+ authorization_token_provider_backoff: Optional[KuFlowAuthorizationTokenProviderBackoff] = None
81
+ """Authorization backoff configuration"""
82
+
83
+ worker_information_notifier_backoff: Optional[KuFlowWorkerInformationNotifierBackoff] = None
84
+ """Worker notifier backoff configuration"""
85
+
86
+ installation_id: Optional[str] = None
87
+ """Installation id"""
88
+
89
+ robot_ids: Optional[List[str]] = None
90
+ """Robot ids"""
91
+
92
+ tenant_id: Optional[List[str]] = None
93
+ """Tenant ids"""
94
+
95
+
96
+ @dataclass
97
+ class TemporalClientConfig:
98
+ """Temporal client configuration options."""
99
+
100
+ target_host: Optional[str] = None
101
+ """``host:port`` for the Temporal server. For local development, this is often "localhost:7233"."""
102
+
103
+ namespace: Optional[str] = None
104
+ """Namespace to use for client calls."""
105
+
106
+ data_converter: temporalio.converter.DataConverter = temporalio.converter.DataConverter.default
107
+ """Data converter to use for all data conversions to/from payloads."""
108
+
109
+ interceptors: Sequence[Interceptor] = field(default_factory=list)
110
+ """Set of interceptors that are chained together to allow intercepting of client calls. The earlier interceptors
111
+ wrap the later ones.
112
+
113
+ Any interceptors that also implement :py:class:`temporalio.worker.Interceptor` will be used as worker interceptors
114
+ too so they should not be given when creating a worker."""
115
+
116
+ default_workflow_query_reject_condition: Optional[temporalio.common.QueryRejectCondition] = None
117
+ """The default rejection condition for workflow queries if not set during query. See :py:meth:`WorkflowHandle.query`
118
+ for details on the rejection condition."""
119
+
120
+ tls: Union[bool, TLSConfig] = False
121
+ """If false, the default, do not use TLS. If true, use system default TLS configuration. If TLS configuration
122
+ present, that TLS configuration will be used."""
123
+
124
+ retry_config: Optional[RetryConfig] = None
125
+ """Retry configuration for direct service calls (when opted in) or all high-level calls made by this client (which
126
+ all opt-in to retries by default). If unset, a default retry configuration is used."""
127
+
128
+ keep_alive_config: Optional[KeepAliveConfig] = KeepAliveConfig.default
129
+ """Keep-alive configuration for the client connection. Default is to check every 30s and kill the connection if a
130
+ response doesn't come back in 15s. Can be set to ``None`` to disable."""
131
+
132
+ rpc_metadata: Mapping[str, str] = field(default_factory=object)
133
+ """Headers to use for all calls to the server. Keys here can be override by per-call RPC metadata keys."""
134
+
135
+ identity: Optional[str] = None
136
+ """Identity for this client. If unset, a default is created based on the version of the SDK."""
137
+
138
+ lazy: bool = False
139
+ """If true, the client will not connect until the first call is attempted or a worker is created with it. Lazy
140
+ clients cannot be used for workers."""
141
+
142
+ runtime: Optional[temporalio.runtime.Runtime] = None
143
+ """The runtime for this client, or the default if unset."""
144
+
145
+ http_connect_proxy_config: Optional[HttpConnectProxyConfig] = None
146
+ """Configuration for HTTP CONNECT proxy."""
147
+
148
+
149
+ @dataclass
150
+ class TemporalWorkerConfig:
151
+ """Temporal worker configuration options."""
152
+
153
+ task_queue: str
154
+ """Required task queue for this worker."""
155
+
156
+ activities: Sequence[Callable] = field(default_factory=list)
157
+ """Set of activity callables decorated with :py:func:`@activity.defn<temporalio.activity.defn>`. Activities may be
158
+ async functions or non-async functions. """
159
+
160
+ workflows: Sequence[Type] = field(default_factory=list)
161
+ """Set of workflow classes decorated with :py:func:`@workflow.defn<temporalio.workflow.defn>`."""
162
+
163
+ activity_executor: Optional[concurrent.futures.Executor] = None
164
+ """Concurrent executor to use for non-async activities. This is required if any activities are non-async. If this is
165
+ a :py:class:`concurrent.futures.ProcessPoolExecutor`, all non-async activities must be picklable. Note, a broken
166
+ executor failure from this executor will cause the worker to fail and shutdown."""
167
+
168
+ workflow_task_executor: Optional[concurrent.futures.ThreadPoolExecutor] = None
169
+ """Thread pool executor for workflow tasks. If this is not present, a new
170
+ :py:class:`concurrent.futures.ThreadPoolExecutor` will be created with ``max_workers`` set to
171
+ ``max(os.cpu_count(), 4)``. The default one will be properly shutdown, but if one is provided, the caller is
172
+ responsible for shutting it down after the worker is shut down."""
173
+
174
+ workflow_runner: WorkflowRunner = SandboxedWorkflowRunner()
175
+ """Runner for workflows."""
176
+
177
+ unsandboxed_workflow_runner: WorkflowRunner = UnsandboxedWorkflowRunner()
178
+ """Runner for workflows that opt-out of sandboxing."""
179
+
180
+ interceptors: Sequence[Interceptor] = field(default_factory=list)
181
+ """Collection of interceptors for this worker. Any interceptors already on the client that also implement
182
+ :py:class:`Interceptor` are prepended to this list and should not be explicitly given here."""
183
+
184
+ build_id: Optional[str] = None
185
+ """Unique identifier for the current runtime. This is best set as a hash of all code and should change only when
186
+ code does. If unset, a best-effort identifier is generated."""
187
+
188
+ identity: Optional[str] = None
189
+ """Identity for this worker client. If unset, the client identity is used."""
190
+
191
+ max_cached_workflows: int = 1000
192
+ """If nonzero, workflows will be cached and sticky task queues will be used."""
193
+
194
+ max_concurrent_workflow_tasks: int = 100
195
+ """Maximum allowed number of workflow tasks that will ever be given to this worker at one time."""
196
+
197
+ max_concurrent_activities: int = 100
198
+ """ Maximum number of activity tasks that will ever be given to this worker concurrently."""
199
+
200
+ max_concurrent_local_activities: int = 100
201
+ """Maximum number of local activity tasks that will ever be given to this worker concurrently."""
202
+
203
+ max_concurrent_workflow_task_polls: int = 5
204
+ """Maximum number of concurrent poll workflow task requests we will perform at a time on this worker's task
205
+ queue."""
206
+
207
+ nonsticky_to_sticky_poll_ratio: float = 0.2
208
+ """max_concurrent_workflow_task_polls * this number = the number of max pollers that will be allowed for the
209
+ nonsticky queue when sticky tasks are enabled. If both defaults are used, the sticky queue will allow 4 max pollers
210
+ while the nonsticky queue will allow one. The minimum for either poller is 1, so if
211
+ ``max_concurrent_workflow_task_polls`` is 1 and sticky queues are enabled, there will be 2 concurrent polls."""
212
+
213
+ max_concurrent_activity_task_polls: int = 5
214
+ """Maximum number of concurrent poll activity task requests we will perform at a time on this worker's task queue.
215
+ """
216
+
217
+ no_remote_activities: bool = False
218
+ """If true, this worker will only handle workflow tasks and local activities, it will not poll for activity tasks.
219
+ """
220
+
221
+ sticky_queue_schedule_to_start_timeout: timedelta = timedelta(seconds=10)
222
+ """How long a workflow task is allowed to sit on the sticky queue before it is timed out and moved to the non-sticky
223
+ queue where it may be picked up by any worker."""
224
+
225
+ max_heartbeat_throttle_interval: timedelta = timedelta(seconds=60)
226
+ """Longest interval for throttling activity heartbeats."""
227
+
228
+ default_heartbeat_throttle_interval: timedelta = timedelta(seconds=30)
229
+ """Default interval for throttling activity heartbeats in case per-activity heartbeat timeout is unset. Otherwise,
230
+ it's the per-activity heartbeat timeout * 0.8."""
231
+
232
+ max_activities_per_second: Optional[float] = None
233
+ """Limits the number of activities per second that this worker will process. The worker will not poll for new
234
+ activities if by doing so it might receive and execute an activity which would cause it to exceed this limit."""
235
+
236
+ max_task_queue_activities_per_second: Optional[float] = None
237
+ """Sets the maximum number of activities per second the task queue will dispatch, controlled server-side. Note that
238
+ this only takes effect upon an activity poll request. If multiple workers on the same queue have different values
239
+ set, they will thrash with the last poller winning."""
240
+
241
+ graceful_shutdown_timeout: timedelta = timedelta()
242
+ """Amount of time after shutdown is called that activities are given to complete before their tasks are cancelled.
243
+ """
244
+
245
+ shared_state_manager: Optional[SharedStateManager] = None
246
+ """Used for obtaining cross-process friendly synchronization primitives. This is required for non-async activities
247
+ where the activity_executor is not a :py:class:`concurrent.futures.ThreadPoolExecutor`. Reuse of these across
248
+ workers is encouraged."""
249
+
250
+ debug_mode: bool = False
251
+ """If true, will disable deadlock detection and may disable sandboxing in order to make using a debugger easier. If
252
+ false but the environment variable ``TEMPORAL_DEBUG`` is truthy, this will be set to true."""
253
+
254
+ disable_eager_activity_execution: bool = False
255
+ """If true, will disable eager activity execution. Eager activity execution is an optimization on some servers that
256
+ sends activities back to the same worker as the calling workflow if they can run there. This setting is experimental
257
+ and may be removed in a future release."""
258
+
259
+ on_fatal_error: Optional[Callable[[BaseException], Awaitable[None]]] = None
260
+ """An async function that can handle a failure before the worker shutdown commences. This cannot stop the shutdown
261
+ and any exception raised is logged and ignored."""
262
+
263
+ use_worker_versioning: bool = False
264
+ """If true, the `build_id` argument must be specified, and this worker opts into the worker versioning feature. This
265
+ ensures it only receives workflow tasks for workflows which it claims to be compatible with.
266
+
267
+ For more information, see https://docs.temporal.io/workers#worker-versioning"""
268
+
269
+
270
+ @dataclass
271
+ class TemporalConfig:
272
+ """Temporal configuration options."""
273
+
274
+ client: TemporalClientConfig
275
+
276
+ worker: Optional[TemporalWorkerConfig] = None
@@ -0,0 +1,168 @@
1
+ #
2
+ # MIT License
3
+ #
4
+ # Copyright (c) 2022 KuFlow
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in all
14
+ # copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ # SOFTWARE.
23
+ #
24
+
25
+ import asyncio
26
+ import logging
27
+ import socket
28
+ from typing import Any, Dict, Optional, Set
29
+
30
+ from azure.core.pipeline import PipelineResponse
31
+ from temporalio.client import Client
32
+ from temporalio.worker import Worker
33
+
34
+ from kuflow_rest import KuFlowRestClient, models
35
+
36
+ from ._connection_config import (
37
+ KuFlowConfig,
38
+ KuFlowWorkerInformationNotifierBackoff,
39
+ TemporalConfig,
40
+ )
41
+
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+
46
+ class KuFlowWorkerInformationNotifier:
47
+ def __init__(
48
+ self,
49
+ kuflow_client: KuFlowRestClient,
50
+ kuflow_config: KuFlowConfig,
51
+ temporal_config: TemporalConfig,
52
+ temporal_client: Client,
53
+ temporal_worker: Worker,
54
+ temporal_workflow_types: Optional[Set[str]] = None,
55
+ temporal_activity_types: Optional[Set[str]] = None,
56
+ backoff: Optional[KuFlowWorkerInformationNotifierBackoff] = None,
57
+ ):
58
+ if temporal_workflow_types is None:
59
+ temporal_workflow_types = set()
60
+ if temporal_activity_types is None:
61
+ temporal_activity_types = set()
62
+ if backoff is None:
63
+ backoff = KuFlowWorkerInformationNotifierBackoff()
64
+
65
+ self._kuflow_client = kuflow_client
66
+ self._kuflow_config = kuflow_config
67
+ self._temporal_config = temporal_config
68
+ self._temporal_client = temporal_client
69
+ self._temporal_worker = temporal_worker
70
+ self._temporal_workflow_types: Set[str] = temporal_workflow_types
71
+ self._temporal_activity_types: Set[str] = temporal_activity_types
72
+ self._backoff = backoff
73
+
74
+ self._delay_window_in_seconds = 5 * 60 # 5 min
75
+ self._consecutive_failures = 0
76
+ self._schedule_create_or_update_worker_delay_task: Optional[asyncio.Task] = None
77
+ self._started = False
78
+
79
+ async def start(self) -> None:
80
+ if self._started:
81
+ return
82
+
83
+ self._started = True
84
+ await self._create_or_update_worker()
85
+ self._schedule_create_or_update_worker()
86
+
87
+ async def _create_or_update_worker(self):
88
+ worker_create_params = models.WorkerCreateParams(
89
+ identity=self._get_worker_identity(),
90
+ hostname=socket.gethostname(),
91
+ ip=self._get_local_ip(),
92
+ task_queue=self._temporal_worker.task_queue,
93
+ workflow_types=list(self._temporal_workflow_types),
94
+ activity_types=list(self._temporal_activity_types),
95
+ installation_id=self._kuflow_config.installation_id,
96
+ robot_ids=self._kuflow_config.robot_ids,
97
+ tenant_id=self._kuflow_config.tenant_id,
98
+ )
99
+
100
+ try:
101
+ http_response: Any = {}
102
+
103
+ def cls(pipeline_response: PipelineResponse, worker: models.Worker, ignored: Dict[str, Any]):
104
+ nonlocal http_response
105
+
106
+ http_response = pipeline_response.http_response
107
+
108
+ return worker
109
+
110
+ worker_response = self._kuflow_client.worker.create_worker(worker_create_params, cls=cls)
111
+ logger.info(
112
+ f"""
113
+ Registered worker {worker_response.task_queue}/{worker_response.identity} with id {worker_response.id}
114
+ """.strip()
115
+ )
116
+
117
+ self._consecutive_failures = 0
118
+
119
+ delay_window_header: Optional[str] = http_response.headers["x-kf-delay-window"]
120
+ if delay_window_header is not None:
121
+ self._delay_window_in_seconds = int(delay_window_header)
122
+ except Exception as err:
123
+ self._consecutive_failures = self._consecutive_failures + 1
124
+
125
+ logger.error(
126
+ f"""
127
+ There are problems registering worker {worker_create_params.task_queue}/{worker_create_params.identity}"
128
+ """.strip(),
129
+ err,
130
+ )
131
+
132
+ def _schedule_create_or_update_worker(self) -> None:
133
+ delay_window_in_seconds = self._delay_window_in_seconds
134
+ if self._consecutive_failures > 0:
135
+ delay_window_in_seconds = min(
136
+ delay_window_in_seconds,
137
+ round(self._backoff.sleep * self._backoff.exponential_rate**self._consecutive_failures),
138
+ )
139
+
140
+ if self._schedule_create_or_update_worker_delay_task:
141
+ self._schedule_create_or_update_worker_delay_task.cancel()
142
+ self._schedule_create_or_update_worker_delay_task = asyncio.create_task(
143
+ self._execute_task__create_or_update_worker(delay_window_in_seconds)
144
+ )
145
+
146
+ async def _execute_task__create_or_update_worker(self, delay_in_seconds: float):
147
+ await asyncio.sleep(delay_in_seconds)
148
+ await self._create_or_update_worker()
149
+ self._schedule_create_or_update_worker()
150
+
151
+ def _get_worker_identity(self) -> str:
152
+ worker_config = self._temporal_worker.config()
153
+ if worker_config["identity"] is not None:
154
+ return worker_config["identity"]
155
+
156
+ return self._temporal_client.identity
157
+
158
+ def _get_local_ip(self) -> str:
159
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
160
+ try:
161
+ # doesn't even have to be reachable
162
+ s.connect(("192.255.255.255", 1))
163
+ ip = s.getsockname()[0]
164
+ except Exception:
165
+ ip = "127.0.0.1"
166
+ finally:
167
+ s.close()
168
+ return ip
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.1
2
+ Name: kuflow-temporal-worker
3
+ Version: 2.0.0
4
+ Summary: KuFlow utilities to use Temporal.io
5
+ Home-page: https://kuflow.com/
6
+ License: MIT
7
+ Author: KuFlow S.L.
8
+ Author-email: kuflow@kuflow.com
9
+ Requires-Python: >=3.8,<4.0
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Requires-Dist: kuflow-temporal-common (>=2.0.0,<3.0.0)
17
+ Requires-Dist: temporalio (>=1.6.0,<1.7.0)
18
+ Project-URL: Documentation, https://docs.kuflow.com/
19
+ Project-URL: Repository, https://github.com/kuflow/kuflow-sdk-python
20
+ Description-Content-Type: text/markdown
21
+
22
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://github.com/kuflow/kuflow-sdk-python/blob/master/LICENSE)
23
+ [![Python](https://img.shields.io/pypi/pyversions/kuflow-temporal-worker.svg)](https://pypi.org/project/kuflow-temporal-worker)
24
+ [![PyPI](https://img.shields.io/pypi/v/kuflow-temporal-worker.svg)](https://pypi.org/project/kuflow-temporal-worker)
25
+
26
+ # KuFlow Temporal Common
27
+
28
+ TODO
29
+
30
+ ## Documentation
31
+
32
+ More detailed docs are available in the [documentation pages](https://docs.kuflow.com/developers/).
33
+
34
+ ## Contributing
35
+
36
+ We are happy to receive your help and comments, together we will dance a wonderful KuFlow. Please review our [contribution guide](CONTRIBUTING.md).
37
+
38
+ ## License
39
+
40
+ [MIT License](https://github.com/kuflow/kuflow-sdk-python/blob/master/LICENSE)
41
+
@@ -0,0 +1,10 @@
1
+ README.md,sha256=t_sdsyMMelO41xWxgdNiR0bRonWsIxRpV9EoPbGuVWY,789
2
+ VERSION,sha256=wo_MpTY3vIjhJK8XJd8Ty5jGne3v1i-zzb4c22t2BiQ,6
3
+ kuflow_temporal_worker/__init__.py,sha256=CcbkJIB-seqBiSzmnXEKUJPIGU8AdNXsvMAAlYVRQsY,1681
4
+ kuflow_temporal_worker/_authentication.py,sha256=e9PaLDkBfrTJIGX12QM0prGlgo0UdFeKUF_GwypZ1G0,5191
5
+ kuflow_temporal_worker/_connection.py,sha256=zeQLl2hVH7q8FnrgZe9VJxrOF1Xie_zCBXHo8m6joEY,7545
6
+ kuflow_temporal_worker/_connection_config.py,sha256=pBGPIhk6CTn4FLwJNQLgOYQ3ROz0HgHEiRKnL-k3CB4,12966
7
+ kuflow_temporal_worker/_worker_information_notifier.py,sha256=Z5agLC4A9BfFpr2B3yI5ymwoG2QfeaGidjXcSeooV-E,6380
8
+ kuflow_temporal_worker-2.0.0.dist-info/WHEEL,sha256=vVCvjcmxuUltf8cYhJ0sJMRDLr1XsPuxEId8YDzbyCY,88
9
+ kuflow_temporal_worker-2.0.0.dist-info/METADATA,sha256=_7NDa0qq2A9jymbiaH9I4wV6FYX2RTQ6gviqoSofSjo,1587
10
+ kuflow_temporal_worker-2.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 1.4.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any