flyte 0.1.0__py3-none-any.whl → 0.2.0b0__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.

Potentially problematic release.


This version of flyte might be problematic. Click here for more details.

Files changed (205) hide show
  1. flyte/__init__.py +62 -2
  2. flyte/_api_commons.py +3 -0
  3. flyte/_bin/__init__.py +0 -0
  4. flyte/_bin/runtime.py +126 -0
  5. flyte/_build.py +25 -0
  6. flyte/_cache/__init__.py +12 -0
  7. flyte/_cache/cache.py +146 -0
  8. flyte/_cache/defaults.py +9 -0
  9. flyte/_cache/policy_function_body.py +42 -0
  10. flyte/_cli/__init__.py +0 -0
  11. flyte/_cli/_common.py +299 -0
  12. flyte/_cli/_create.py +42 -0
  13. flyte/_cli/_delete.py +23 -0
  14. flyte/_cli/_deploy.py +140 -0
  15. flyte/_cli/_get.py +235 -0
  16. flyte/_cli/_params.py +538 -0
  17. flyte/_cli/_run.py +174 -0
  18. flyte/_cli/main.py +98 -0
  19. flyte/_code_bundle/__init__.py +8 -0
  20. flyte/_code_bundle/_ignore.py +113 -0
  21. flyte/_code_bundle/_packaging.py +187 -0
  22. flyte/_code_bundle/_utils.py +339 -0
  23. flyte/_code_bundle/bundle.py +178 -0
  24. flyte/_context.py +146 -0
  25. flyte/_datastructures.py +342 -0
  26. flyte/_deploy.py +202 -0
  27. flyte/_doc.py +29 -0
  28. flyte/_docstring.py +32 -0
  29. flyte/_environment.py +43 -0
  30. flyte/_group.py +31 -0
  31. flyte/_hash.py +23 -0
  32. flyte/_image.py +757 -0
  33. flyte/_initialize.py +643 -0
  34. flyte/_interface.py +84 -0
  35. flyte/_internal/__init__.py +3 -0
  36. flyte/_internal/controllers/__init__.py +115 -0
  37. flyte/_internal/controllers/_local_controller.py +118 -0
  38. flyte/_internal/controllers/_trace.py +40 -0
  39. flyte/_internal/controllers/pbhash.py +39 -0
  40. flyte/_internal/controllers/remote/__init__.py +40 -0
  41. flyte/_internal/controllers/remote/_action.py +141 -0
  42. flyte/_internal/controllers/remote/_client.py +43 -0
  43. flyte/_internal/controllers/remote/_controller.py +361 -0
  44. flyte/_internal/controllers/remote/_core.py +402 -0
  45. flyte/_internal/controllers/remote/_informer.py +361 -0
  46. flyte/_internal/controllers/remote/_service_protocol.py +50 -0
  47. flyte/_internal/imagebuild/__init__.py +11 -0
  48. flyte/_internal/imagebuild/docker_builder.py +416 -0
  49. flyte/_internal/imagebuild/image_builder.py +241 -0
  50. flyte/_internal/imagebuild/remote_builder.py +0 -0
  51. flyte/_internal/resolvers/__init__.py +0 -0
  52. flyte/_internal/resolvers/_task_module.py +54 -0
  53. flyte/_internal/resolvers/common.py +31 -0
  54. flyte/_internal/resolvers/default.py +28 -0
  55. flyte/_internal/runtime/__init__.py +0 -0
  56. flyte/_internal/runtime/convert.py +205 -0
  57. flyte/_internal/runtime/entrypoints.py +135 -0
  58. flyte/_internal/runtime/io.py +136 -0
  59. flyte/_internal/runtime/resources_serde.py +138 -0
  60. flyte/_internal/runtime/task_serde.py +210 -0
  61. flyte/_internal/runtime/taskrunner.py +190 -0
  62. flyte/_internal/runtime/types_serde.py +54 -0
  63. flyte/_logging.py +124 -0
  64. flyte/_protos/__init__.py +0 -0
  65. flyte/_protos/common/authorization_pb2.py +66 -0
  66. flyte/_protos/common/authorization_pb2.pyi +108 -0
  67. flyte/_protos/common/authorization_pb2_grpc.py +4 -0
  68. flyte/_protos/common/identifier_pb2.py +71 -0
  69. flyte/_protos/common/identifier_pb2.pyi +82 -0
  70. flyte/_protos/common/identifier_pb2_grpc.py +4 -0
  71. flyte/_protos/common/identity_pb2.py +48 -0
  72. flyte/_protos/common/identity_pb2.pyi +72 -0
  73. flyte/_protos/common/identity_pb2_grpc.py +4 -0
  74. flyte/_protos/common/list_pb2.py +36 -0
  75. flyte/_protos/common/list_pb2.pyi +69 -0
  76. flyte/_protos/common/list_pb2_grpc.py +4 -0
  77. flyte/_protos/common/policy_pb2.py +37 -0
  78. flyte/_protos/common/policy_pb2.pyi +27 -0
  79. flyte/_protos/common/policy_pb2_grpc.py +4 -0
  80. flyte/_protos/common/role_pb2.py +37 -0
  81. flyte/_protos/common/role_pb2.pyi +53 -0
  82. flyte/_protos/common/role_pb2_grpc.py +4 -0
  83. flyte/_protos/common/runtime_version_pb2.py +28 -0
  84. flyte/_protos/common/runtime_version_pb2.pyi +24 -0
  85. flyte/_protos/common/runtime_version_pb2_grpc.py +4 -0
  86. flyte/_protos/logs/dataplane/payload_pb2.py +96 -0
  87. flyte/_protos/logs/dataplane/payload_pb2.pyi +168 -0
  88. flyte/_protos/logs/dataplane/payload_pb2_grpc.py +4 -0
  89. flyte/_protos/secret/definition_pb2.py +49 -0
  90. flyte/_protos/secret/definition_pb2.pyi +93 -0
  91. flyte/_protos/secret/definition_pb2_grpc.py +4 -0
  92. flyte/_protos/secret/payload_pb2.py +62 -0
  93. flyte/_protos/secret/payload_pb2.pyi +94 -0
  94. flyte/_protos/secret/payload_pb2_grpc.py +4 -0
  95. flyte/_protos/secret/secret_pb2.py +38 -0
  96. flyte/_protos/secret/secret_pb2.pyi +6 -0
  97. flyte/_protos/secret/secret_pb2_grpc.py +198 -0
  98. flyte/_protos/secret/secret_pb2_grpc_grpc.py +198 -0
  99. flyte/_protos/validate/validate/validate_pb2.py +76 -0
  100. flyte/_protos/workflow/node_execution_service_pb2.py +26 -0
  101. flyte/_protos/workflow/node_execution_service_pb2.pyi +4 -0
  102. flyte/_protos/workflow/node_execution_service_pb2_grpc.py +32 -0
  103. flyte/_protos/workflow/queue_service_pb2.py +106 -0
  104. flyte/_protos/workflow/queue_service_pb2.pyi +141 -0
  105. flyte/_protos/workflow/queue_service_pb2_grpc.py +172 -0
  106. flyte/_protos/workflow/run_definition_pb2.py +128 -0
  107. flyte/_protos/workflow/run_definition_pb2.pyi +310 -0
  108. flyte/_protos/workflow/run_definition_pb2_grpc.py +4 -0
  109. flyte/_protos/workflow/run_logs_service_pb2.py +41 -0
  110. flyte/_protos/workflow/run_logs_service_pb2.pyi +28 -0
  111. flyte/_protos/workflow/run_logs_service_pb2_grpc.py +69 -0
  112. flyte/_protos/workflow/run_service_pb2.py +133 -0
  113. flyte/_protos/workflow/run_service_pb2.pyi +175 -0
  114. flyte/_protos/workflow/run_service_pb2_grpc.py +412 -0
  115. flyte/_protos/workflow/state_service_pb2.py +58 -0
  116. flyte/_protos/workflow/state_service_pb2.pyi +71 -0
  117. flyte/_protos/workflow/state_service_pb2_grpc.py +138 -0
  118. flyte/_protos/workflow/task_definition_pb2.py +72 -0
  119. flyte/_protos/workflow/task_definition_pb2.pyi +65 -0
  120. flyte/_protos/workflow/task_definition_pb2_grpc.py +4 -0
  121. flyte/_protos/workflow/task_service_pb2.py +44 -0
  122. flyte/_protos/workflow/task_service_pb2.pyi +31 -0
  123. flyte/_protos/workflow/task_service_pb2_grpc.py +104 -0
  124. flyte/_resources.py +226 -0
  125. flyte/_retry.py +32 -0
  126. flyte/_reusable_environment.py +25 -0
  127. flyte/_run.py +410 -0
  128. flyte/_secret.py +61 -0
  129. flyte/_task.py +367 -0
  130. flyte/_task_environment.py +200 -0
  131. flyte/_timeout.py +47 -0
  132. flyte/_tools.py +27 -0
  133. flyte/_trace.py +128 -0
  134. flyte/_utils/__init__.py +20 -0
  135. flyte/_utils/asyn.py +119 -0
  136. flyte/_utils/coro_management.py +25 -0
  137. flyte/_utils/file_handling.py +72 -0
  138. flyte/_utils/helpers.py +108 -0
  139. flyte/_utils/lazy_module.py +54 -0
  140. flyte/_utils/uv_script_parser.py +49 -0
  141. flyte/_version.py +21 -0
  142. flyte/config/__init__.py +168 -0
  143. flyte/config/_config.py +196 -0
  144. flyte/config/_internal.py +64 -0
  145. flyte/connectors/__init__.py +0 -0
  146. flyte/errors.py +143 -0
  147. flyte/extras/__init__.py +5 -0
  148. flyte/extras/_container.py +273 -0
  149. flyte/io/__init__.py +11 -0
  150. flyte/io/_dataframe.py +0 -0
  151. flyte/io/_dir.py +448 -0
  152. flyte/io/_file.py +468 -0
  153. flyte/io/pickle/__init__.py +0 -0
  154. flyte/io/pickle/transformer.py +117 -0
  155. flyte/io/structured_dataset/__init__.py +129 -0
  156. flyte/io/structured_dataset/basic_dfs.py +219 -0
  157. flyte/io/structured_dataset/structured_dataset.py +1061 -0
  158. flyte/remote/__init__.py +25 -0
  159. flyte/remote/_client/__init__.py +0 -0
  160. flyte/remote/_client/_protocols.py +131 -0
  161. flyte/remote/_client/auth/__init__.py +12 -0
  162. flyte/remote/_client/auth/_authenticators/__init__.py +0 -0
  163. flyte/remote/_client/auth/_authenticators/base.py +397 -0
  164. flyte/remote/_client/auth/_authenticators/client_credentials.py +73 -0
  165. flyte/remote/_client/auth/_authenticators/device_code.py +118 -0
  166. flyte/remote/_client/auth/_authenticators/external_command.py +79 -0
  167. flyte/remote/_client/auth/_authenticators/factory.py +200 -0
  168. flyte/remote/_client/auth/_authenticators/pkce.py +516 -0
  169. flyte/remote/_client/auth/_channel.py +184 -0
  170. flyte/remote/_client/auth/_client_config.py +83 -0
  171. flyte/remote/_client/auth/_default_html.py +32 -0
  172. flyte/remote/_client/auth/_grpc_utils/__init__.py +0 -0
  173. flyte/remote/_client/auth/_grpc_utils/auth_interceptor.py +288 -0
  174. flyte/remote/_client/auth/_grpc_utils/default_metadata_interceptor.py +151 -0
  175. flyte/remote/_client/auth/_keyring.py +143 -0
  176. flyte/remote/_client/auth/_token_client.py +260 -0
  177. flyte/remote/_client/auth/errors.py +16 -0
  178. flyte/remote/_client/controlplane.py +95 -0
  179. flyte/remote/_console.py +18 -0
  180. flyte/remote/_data.py +155 -0
  181. flyte/remote/_logs.py +116 -0
  182. flyte/remote/_project.py +86 -0
  183. flyte/remote/_run.py +873 -0
  184. flyte/remote/_secret.py +132 -0
  185. flyte/remote/_task.py +227 -0
  186. flyte/report/__init__.py +3 -0
  187. flyte/report/_report.py +178 -0
  188. flyte/report/_template.html +124 -0
  189. flyte/storage/__init__.py +24 -0
  190. flyte/storage/_remote_fs.py +34 -0
  191. flyte/storage/_storage.py +251 -0
  192. flyte/storage/_utils.py +5 -0
  193. flyte/types/__init__.py +13 -0
  194. flyte/types/_interface.py +25 -0
  195. flyte/types/_renderer.py +162 -0
  196. flyte/types/_string_literals.py +120 -0
  197. flyte/types/_type_engine.py +2211 -0
  198. flyte/types/_utils.py +80 -0
  199. flyte-0.2.0b0.dist-info/METADATA +179 -0
  200. flyte-0.2.0b0.dist-info/RECORD +204 -0
  201. {flyte-0.1.0.dist-info → flyte-0.2.0b0.dist-info}/WHEEL +2 -1
  202. flyte-0.2.0b0.dist-info/entry_points.txt +3 -0
  203. flyte-0.2.0b0.dist-info/top_level.txt +1 -0
  204. flyte-0.1.0.dist-info/METADATA +0 -6
  205. flyte-0.1.0.dist-info/RECORD +0 -5
flyte/_initialize.py ADDED
@@ -0,0 +1,643 @@
1
+ from __future__ import annotations
2
+
3
+ import datetime
4
+ import functools
5
+ import os
6
+ import threading
7
+ import typing
8
+ from dataclasses import dataclass, replace
9
+ from datetime import timedelta
10
+ from pathlib import Path
11
+ from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Literal, Optional, TypeVar
12
+
13
+ from flyte.errors import InitializationError
14
+
15
+ from ._api_commons import syncer
16
+ from ._logging import initialize_logger
17
+ from ._tools import ipython_check
18
+
19
+ if TYPE_CHECKING:
20
+ from flyte.config import Config
21
+ from flyte.remote._client.auth import AuthType, ClientConfig
22
+ from flyte.remote._client.controlplane import ClientSet
23
+
24
+ Mode = Literal["local", "remote"]
25
+
26
+
27
+ def set_if_exists(d: dict, k: str, val: typing.Any) -> dict:
28
+ """
29
+ Given a dict ``d`` sets the key ``k`` with value of config ``v``, if the config value ``v`` is set
30
+ and return the updated dictionary.
31
+ """
32
+ exists = isinstance(val, bool) or bool(val is not None and val)
33
+ if exists:
34
+ d[k] = val
35
+ return d
36
+
37
+
38
+ @dataclass(init=True, repr=True, eq=True, frozen=True)
39
+ class Storage(object):
40
+ """
41
+ Data storage configuration that applies across any provider.
42
+ """
43
+
44
+ retries: int = 3
45
+ backoff: datetime.timedelta = datetime.timedelta(seconds=5)
46
+ enable_debug: bool = False
47
+ attach_execution_metadata: bool = True
48
+
49
+ _KEY_ENV_VAR_MAPPING: ClassVar[typing.Dict[str, str]] = {
50
+ "enable_debug": "UNION_STORAGE_DEBUG",
51
+ "retries": "UNION_STORAGE_RETRIES",
52
+ "backoff": "UNION_STORAGE_BACKOFF_SECONDS",
53
+ }
54
+
55
+ def get_fsspec_kwargs(self, anonymous: bool = False, /, **kwargs) -> Dict[str, Any]:
56
+ """
57
+ Returns the configuration as kwargs for constructing an fsspec filesystem.
58
+ """
59
+ return {}
60
+
61
+ @classmethod
62
+ def _auto_as_kwargs(cls) -> Dict[str, Any]:
63
+ retries = os.getenv(cls._KEY_ENV_VAR_MAPPING["retries"])
64
+ backoff = os.getenv(cls._KEY_ENV_VAR_MAPPING["backoff"])
65
+ enable_debug = os.getenv(cls._KEY_ENV_VAR_MAPPING["enable_debug"])
66
+
67
+ kwargs: Dict[str, Any] = {}
68
+ kwargs = set_if_exists(kwargs, "enable_debug", enable_debug)
69
+ kwargs = set_if_exists(kwargs, "retries", retries)
70
+ kwargs = set_if_exists(kwargs, "backoff", backoff)
71
+ return kwargs
72
+
73
+ @classmethod
74
+ def auto(cls) -> Storage:
75
+ """
76
+ Construct the config object automatically from environment variables.
77
+ """
78
+ return cls(**cls._auto_as_kwargs())
79
+
80
+
81
+ @dataclass(init=True, repr=True, eq=True, frozen=True)
82
+ class S3(Storage):
83
+ """
84
+ S3 specific configuration
85
+ """
86
+
87
+ endpoint: typing.Optional[str] = None
88
+ access_key_id: typing.Optional[str] = None
89
+ secret_access_key: typing.Optional[str] = None
90
+
91
+ _KEY_ENV_VAR_MAPPING: ClassVar[typing.Dict[str, str]] = {
92
+ "endpoint": "FLYTE_AWS_ENDPOINT",
93
+ "access_key_id": "FLYTE_AWS_ACCESS_KEY_ID",
94
+ "secret_access_key": "FLYTE_AWS_SECRET_ACCESS_KEY",
95
+ } | Storage._KEY_ENV_VAR_MAPPING
96
+
97
+ # Refer to https://github.com/developmentseed/obstore/blob/33654fc37f19a657689eb93327b621e9f9e01494/obstore/python/obstore/store/_aws.pyi#L11
98
+ # for key and secret
99
+ _CONFIG_KEY_FSSPEC_S3_KEY_ID: ClassVar = "access_key_id"
100
+ _CONFIG_KEY_FSSPEC_S3_SECRET: ClassVar = "secret_access_key"
101
+ _CONFIG_KEY_ENDPOINT: ClassVar = "endpoint_url"
102
+ _KEY_SKIP_SIGNATURE: ClassVar = "skip_signature"
103
+
104
+ @classmethod
105
+ def auto(cls) -> S3:
106
+ """
107
+ :return: Config
108
+ """
109
+ endpoint = os.getenv(cls._KEY_ENV_VAR_MAPPING["endpoint"], None)
110
+ access_key_id = os.getenv(cls._KEY_ENV_VAR_MAPPING["access_key_id"], None)
111
+ secret_access_key = os.getenv(cls._KEY_ENV_VAR_MAPPING["secret_access_key"], None)
112
+
113
+ kwargs = super()._auto_as_kwargs()
114
+ kwargs = set_if_exists(kwargs, "endpoint", endpoint)
115
+ kwargs = set_if_exists(kwargs, "access_key_id", access_key_id)
116
+ kwargs = set_if_exists(kwargs, "secret_access_key", secret_access_key)
117
+
118
+ return S3(**kwargs)
119
+
120
+ @classmethod
121
+ def for_sandbox(cls) -> S3:
122
+ """
123
+ :return:
124
+ """
125
+ kwargs = super()._auto_as_kwargs()
126
+ final_kwargs = kwargs | {
127
+ "endpoint": "http://localhost:4566",
128
+ "access_key_id": "minio",
129
+ "secret_access_key": "miniostorage",
130
+ }
131
+ return S3(**final_kwargs)
132
+
133
+ def get_fsspec_kwargs(self, anonymous: bool = False, /, **kwargs) -> Dict[str, Any]:
134
+ # Construct the config object
135
+ config: Dict[str, Any] = {}
136
+ if self._CONFIG_KEY_FSSPEC_S3_KEY_ID in kwargs or self.access_key_id:
137
+ config[self._CONFIG_KEY_FSSPEC_S3_KEY_ID] = kwargs.pop(
138
+ self._CONFIG_KEY_FSSPEC_S3_KEY_ID, self.access_key_id
139
+ )
140
+ if self._CONFIG_KEY_FSSPEC_S3_SECRET in kwargs or self.secret_access_key:
141
+ config[self._CONFIG_KEY_FSSPEC_S3_SECRET] = kwargs.pop(
142
+ self._CONFIG_KEY_FSSPEC_S3_SECRET, self.secret_access_key
143
+ )
144
+ if self._CONFIG_KEY_ENDPOINT in kwargs or self.endpoint:
145
+ config["endpoint_url"] = kwargs.pop(self._CONFIG_KEY_ENDPOINT, self.endpoint)
146
+
147
+ retries = kwargs.pop("retries", self.retries)
148
+ backoff = kwargs.pop("backoff", self.backoff)
149
+
150
+ if anonymous:
151
+ config[self._KEY_SKIP_SIGNATURE] = True
152
+
153
+ retry_config = {
154
+ "max_retries": retries,
155
+ "backoff": {
156
+ "base": 2,
157
+ "init_backoff": backoff,
158
+ "max_backoff": timedelta(seconds=16),
159
+ },
160
+ "retry_timeout": timedelta(minutes=3),
161
+ }
162
+
163
+ client_options = {"timeout": "99999s", "allow_http": True}
164
+
165
+ if config:
166
+ kwargs["config"] = config
167
+ kwargs["client_options"] = client_options or None
168
+ kwargs["retry_config"] = retry_config or None
169
+
170
+ return kwargs
171
+
172
+
173
+ @dataclass(init=True, repr=True, eq=True, frozen=True)
174
+ class GCS(Storage):
175
+ """
176
+ Any GCS specific configuration.
177
+ """
178
+
179
+ gsutil_parallelism: bool = False
180
+
181
+ _KEY_ENV_VAR_MAPPING: ClassVar[dict[str, str]] = {
182
+ "gsutil_parallelism": "GCP_GSUTIL_PARALLELISM",
183
+ }
184
+
185
+ @classmethod
186
+ def auto(cls) -> GCS:
187
+ gsutil_parallelism = os.getenv(cls._KEY_ENV_VAR_MAPPING["gsutil_parallelism"], None)
188
+
189
+ kwargs: Dict[str, Any] = {}
190
+ kwargs = set_if_exists(kwargs, "gsutil_parallelism", gsutil_parallelism)
191
+ return GCS(**kwargs)
192
+
193
+ def get_fsspec_kwargs(self, anonymous: bool = False, /, **kwargs) -> Dict[str, Any]:
194
+ return kwargs
195
+
196
+
197
+ @dataclass(init=True, repr=True, eq=True, frozen=True)
198
+ class ABFS(Storage):
199
+ """
200
+ Any Azure Blob Storage specific configuration.
201
+ """
202
+
203
+ account_name: typing.Optional[str] = None
204
+ account_key: typing.Optional[str] = None
205
+ tenant_id: typing.Optional[str] = None
206
+ client_id: typing.Optional[str] = None
207
+ client_secret: typing.Optional[str] = None
208
+
209
+ _KEY_ENV_VAR_MAPPING: ClassVar[dict[str, str]] = {
210
+ "account_name": "AZURE_STORAGE_ACCOUNT_NAME",
211
+ "account_key": "AZURE_STORAGE_ACCOUNT_KEY",
212
+ "tenant_id": "AZURE_TENANT_ID",
213
+ "client_id": "AZURE_CLIENT_ID",
214
+ "client_secret": "AZURE_CLIENT_SECRET",
215
+ }
216
+ _KEY_SKIP_SIGNATURE: ClassVar = "skip_signature"
217
+
218
+ @classmethod
219
+ def auto(cls) -> ABFS:
220
+ account_name = os.getenv(cls._KEY_ENV_VAR_MAPPING["account_name"], None)
221
+ account_key = os.getenv(cls._KEY_ENV_VAR_MAPPING["account_key"], None)
222
+ tenant_id = os.getenv(cls._KEY_ENV_VAR_MAPPING["tenant_id"], None)
223
+ client_id = os.getenv(cls._KEY_ENV_VAR_MAPPING["client_id"], None)
224
+ client_secret = os.getenv(cls._KEY_ENV_VAR_MAPPING["client_secret"], None)
225
+
226
+ kwargs: Dict[str, Any] = {}
227
+ kwargs = set_if_exists(kwargs, "account_name", account_name)
228
+ kwargs = set_if_exists(kwargs, "account_key", account_key)
229
+ kwargs = set_if_exists(kwargs, "tenant_id", tenant_id)
230
+ kwargs = set_if_exists(kwargs, "client_id", client_id)
231
+ kwargs = set_if_exists(kwargs, "client_secret", client_secret)
232
+ return ABFS(**kwargs)
233
+
234
+ def get_fsspec_kwargs(self, anonymous: bool = False, /, **kwargs) -> Dict[str, Any]:
235
+ config: Dict[str, Any] = {}
236
+ if "account_name" in kwargs or self.account_name:
237
+ config["account_name"] = kwargs.get("account_name", self.account_name)
238
+ if "account_key" in kwargs or self.account_key:
239
+ config["account_key"] = kwargs.get("account_key", self.account_key)
240
+ if "client_id" in kwargs or self.client_id:
241
+ config["client_id"] = kwargs.get("client_id", self.client_id)
242
+ if "client_secret" in kwargs or self.client_secret:
243
+ config["client_secret"] = kwargs.get("client_secret", self.client_secret)
244
+ if "tenant_id" in kwargs or self.tenant_id:
245
+ config["tenant_id"] = kwargs.get("tenant_id", self.tenant_id)
246
+
247
+ if anonymous:
248
+ config[self._KEY_SKIP_SIGNATURE] = True
249
+
250
+ client_options = {"timeout": "99999s", "allow_http": "true"}
251
+
252
+ if config:
253
+ kwargs["config"] = config
254
+ kwargs["client_options"] = client_options
255
+
256
+ return kwargs
257
+
258
+
259
+ @dataclass(init=True, repr=True, eq=True, frozen=True, kw_only=True)
260
+ class CommonInit:
261
+ """
262
+ Common initialization configuration for Flyte.
263
+ """
264
+
265
+ root_dir: Path
266
+ org: str | None = None
267
+ project: str | None = None
268
+ domain: str | None = None
269
+
270
+
271
+ @dataclass(init=True, kw_only=True, repr=True, eq=True, frozen=True)
272
+ class _InitConfig(CommonInit):
273
+ client: Optional[ClientSet] = None
274
+ storage: Optional[Storage] = None
275
+
276
+ def replace(self, **kwargs) -> _InitConfig:
277
+ return replace(self, **kwargs)
278
+
279
+
280
+ # Global singleton to store initialization configuration
281
+ _init_config: _InitConfig | None = None
282
+ _init_lock = threading.RLock() # Reentrant lock for thread safety
283
+
284
+
285
+ async def _initialize_client(
286
+ api_key: str | None = None,
287
+ auth_type: AuthType = "Pkce",
288
+ endpoint: str | None = None,
289
+ client_config: ClientConfig | None = None,
290
+ headless: bool = False,
291
+ insecure: bool = False,
292
+ insecure_skip_verify: bool = False,
293
+ ca_cert_file_path: str | None = None,
294
+ command: List[str] | None = None,
295
+ proxy_command: List[str] | None = None,
296
+ client_id: str | None = None,
297
+ client_credentials_secret: str | None = None,
298
+ rpc_retries: int = 3,
299
+ http_proxy_url: str | None = None,
300
+ ) -> ClientSet:
301
+ """
302
+ Initialize the client based on the execution mode.
303
+ :return: The initialized client
304
+ """
305
+ from flyte.remote._client.controlplane import ClientSet
306
+
307
+ if endpoint is not None:
308
+ return await ClientSet.for_endpoint(
309
+ endpoint,
310
+ insecure=insecure,
311
+ api_key=api_key,
312
+ insecure_skip_verify=insecure_skip_verify,
313
+ auth_type=auth_type,
314
+ headless=headless,
315
+ ca_cert_file_path=ca_cert_file_path,
316
+ command=command,
317
+ proxy_command=proxy_command,
318
+ client_id=client_id,
319
+ client_credentials_secret=client_credentials_secret,
320
+ client_config=client_config,
321
+ rpc_retries=rpc_retries,
322
+ http_proxy_url=http_proxy_url,
323
+ )
324
+ raise NotImplementedError("Currently only endpoints are supported.")
325
+
326
+
327
+ @syncer.wrap
328
+ async def init(
329
+ org: str | None = None,
330
+ project: str | None = None,
331
+ domain: str | None = None,
332
+ root_dir: Path | None = None,
333
+ log_level: int | None = None,
334
+ endpoint: str | None = None,
335
+ headless: bool = False,
336
+ insecure: bool = False,
337
+ insecure_skip_verify: bool = False,
338
+ ca_cert_file_path: str | None = None,
339
+ auth_type: AuthType = "Pkce",
340
+ command: List[str] | None = None,
341
+ proxy_command: List[str] | None = None,
342
+ api_key: str | None = None,
343
+ client_id: str | None = None,
344
+ client_credentials_secret: str | None = None,
345
+ auth_client_config: ClientConfig | None = None,
346
+ rpc_retries: int = 3,
347
+ http_proxy_url: str | None = None,
348
+ storage: Storage | None = None,
349
+ config: Config | None = None,
350
+ ) -> None:
351
+ """
352
+ Initialize the Flyte system with the given configuration. This method should be called before any other Flyte
353
+ remote API methods are called. Thread-safe implementation.
354
+
355
+ :param project: Optional project name (not used in this implementation)
356
+ :param domain: Optional domain name (not used in this implementation)
357
+ :param root_dir: Optional root directory from which to determine how to load files, and find paths to files.
358
+ defaults to the editable install directory if the cwd is in a Python editable install, else just the cwd.
359
+ :param log_level: Optional logging level for the logger, default is set using the default initialization policies
360
+ :param api_key: Optional API key for authentication
361
+ :param endpoint: Optional API endpoint URL
362
+ :param headless: Optional Whether to run in headless mode
363
+ :param mode: Optional execution model (local, remote). Default is local. When local is used,
364
+ the execution will be done locally. When remote is used, the execution will be sent to a remote server,
365
+ In the remote case, the endpoint or api_key must be set.
366
+ :param insecure_skip_verify: Whether to skip SSL certificate verification
367
+ :param auth_client_config: Optional client configuration for authentication
368
+ :param auth_type: The authentication type to use (Pkce, ClientSecret, ExternalCommand, DeviceFlow)
369
+ :param command: This command is executed to return a token using an external process
370
+ :param proxy_command: This command is executed to return a token for proxy authorization using an external process
371
+ :param client_id: This is the public identifier for the app which handles authorization for a Flyte deployment.
372
+ More details here: https://www.oauth.com/oauth2-servers/client-registration/client-id-secret/.
373
+ :param client_credentials_secret: Used for service auth, which is automatically called during pyflyte. This will
374
+ allow the Flyte engine to read the password directly from the environment variable. Note that this is
375
+ less secure! Please only use this if mounting the secret as a file is impossible
376
+ :param ca_cert_file_path: [optional] str Root Cert to be loaded and used to verify admin
377
+ :param http_proxy_url: [optional] HTTP Proxy to be used for OAuth requests
378
+ :param rpc_retries: [optional] int Number of times to retry the platform calls
379
+ :param audience: oauth2 audience for the token request. This is used to validate the token
380
+ :param insecure: insecure flag for the client
381
+ :param storage: Optional blob store (S3, GCS, Azure) configuration if needed to access (i.e. using Minio)
382
+ :param org: Optional organization override for the client. Should be set by auth instead.
383
+ :param config: Optional config to override the init parameters
384
+
385
+ :return: None
386
+ """
387
+ from flyte._utils import get_cwd_editable_install
388
+
389
+ interactive_mode = ipython_check()
390
+
391
+ initialize_logger(enable_rich=interactive_mode)
392
+ if log_level:
393
+ initialize_logger(log_level=log_level, enable_rich=interactive_mode)
394
+
395
+ global _init_config # noqa: PLW0603
396
+
397
+ with _init_lock:
398
+ if config is None:
399
+ from flyte.config import Config
400
+
401
+ config = Config.auto()
402
+ platform_cfg = config.platform
403
+ task_cfg = config.task
404
+ client = None
405
+ if endpoint or platform_cfg.endpoint or api_key:
406
+ client = await _initialize_client(
407
+ api_key=api_key,
408
+ auth_type=auth_type or platform_cfg.auth_mode,
409
+ endpoint=endpoint or platform_cfg.endpoint,
410
+ headless=headless,
411
+ insecure=insecure or platform_cfg.insecure,
412
+ insecure_skip_verify=insecure_skip_verify or platform_cfg.insecure_skip_verify,
413
+ ca_cert_file_path=ca_cert_file_path or platform_cfg.ca_cert_file_path,
414
+ command=command or platform_cfg.command,
415
+ proxy_command=proxy_command or platform_cfg.proxy_command,
416
+ client_id=client_id or platform_cfg.client_id,
417
+ client_credentials_secret=client_credentials_secret or platform_cfg.client_credentials_secret,
418
+ client_config=auth_client_config,
419
+ rpc_retries=rpc_retries or platform_cfg.rpc_retries,
420
+ http_proxy_url=http_proxy_url or platform_cfg.http_proxy_url,
421
+ )
422
+
423
+ root_dir = root_dir or get_cwd_editable_install() or Path.cwd()
424
+ _init_config = _InitConfig(
425
+ root_dir=root_dir,
426
+ project=project or task_cfg.project,
427
+ domain=domain or task_cfg.domain,
428
+ client=client,
429
+ storage=storage,
430
+ org=org or task_cfg.org,
431
+ )
432
+
433
+
434
+ def _get_init_config() -> Optional[_InitConfig]:
435
+ """
436
+ Get the current initialization configuration. Thread-safe implementation.
437
+
438
+ :return: The current InitData if initialized, None otherwise
439
+ """
440
+ with _init_lock:
441
+ return _init_config
442
+
443
+
444
+ def get_common_config() -> CommonInit:
445
+ """
446
+ Get the current initialization configuration. Thread-safe implementation.
447
+
448
+ :return: The current InitData if initialized, None otherwise
449
+ """
450
+ cfg = _get_init_config()
451
+ if cfg is None:
452
+ raise InitializationError(
453
+ "StorageNotInitializedError",
454
+ "user",
455
+ "Configuration has not been initialized. Call flyte.init() with a valid endpoint or",
456
+ " api-key before using this function.",
457
+ )
458
+ return cfg
459
+
460
+
461
+ def get_storage() -> Storage:
462
+ """
463
+ Get the current storage configuration. Thread-safe implementation.
464
+
465
+ :return: The current storage configuration
466
+ """
467
+ cfg = _get_init_config()
468
+ if cfg is None:
469
+ raise InitializationError(
470
+ "StorageNotInitializedError",
471
+ "user",
472
+ "Configuration has not been initialized. Call flyte.init() with a valid endpoint or",
473
+ " api-key before using this function.",
474
+ )
475
+ if cfg.storage is None:
476
+ # return default local storage
477
+ return typing.cast(Storage, cfg.replace(storage=Storage()).storage)
478
+ return cfg.storage
479
+
480
+
481
+ def get_client() -> ClientSet:
482
+ """
483
+ Get the current client. Thread-safe implementation.
484
+
485
+ :return: The current client
486
+ """
487
+ cfg = _get_init_config()
488
+ if cfg is None or cfg.client is None:
489
+ raise InitializationError(
490
+ "ClientNotInitializedError",
491
+ "user",
492
+ "Client has not been initialized. Call flyte.init() with a valid endpoint or"
493
+ " api-key before using this function.",
494
+ )
495
+ return cfg.client
496
+
497
+
498
+ def is_initialized() -> bool:
499
+ """
500
+ Check if the system has been initialized.
501
+
502
+ :return: True if initialized, False otherwise
503
+ """
504
+ return _get_init_config() is not None
505
+
506
+
507
+ def initialize_in_cluster(storage: Storage | None = None) -> None:
508
+ """
509
+ Initialize the system for in-cluster execution. This is a placeholder function and does not perform any actions.
510
+
511
+ :return: None
512
+ """
513
+ init(storage=storage)
514
+
515
+
516
+ # Define a generic type variable for the decorated function
517
+ T = TypeVar("T", bound=Callable)
518
+
519
+
520
+ def requires_client(func: T) -> T:
521
+ """
522
+ Decorator that checks if the client has been initialized before executing the function.
523
+ Raises InitializationError if the client is not initialized.
524
+
525
+ :param func: Function to decorate
526
+ :return: Decorated function that checks for initialization
527
+ """
528
+
529
+ @functools.wraps(func)
530
+ def wrapper(*args, **kwargs) -> T:
531
+ init_config = _get_init_config()
532
+ if init_config is None or init_config.client is None:
533
+ raise InitializationError(
534
+ "ClientNotInitializedError",
535
+ "user",
536
+ f"Function '{func.__name__}' requires client to be initialized. "
537
+ f"Call flyte.init() with a valid endpoint or api-key before using this function.",
538
+ )
539
+ return func(*args, **kwargs)
540
+
541
+ return typing.cast(T, wrapper)
542
+
543
+
544
+ def requires_storage(func: T) -> T:
545
+ """
546
+ Decorator that checks if the storage has been initialized before executing the function.
547
+ Raises InitializationError if the storage is not initialized.
548
+
549
+ :param func: Function to decorate
550
+ :return: Decorated function that checks for initialization
551
+ """
552
+
553
+ @functools.wraps(func)
554
+ def wrapper(*args, **kwargs):
555
+ if _get_init_config() is None or _get_init_config().storage is None:
556
+ raise InitializationError(
557
+ "StorageNotInitializedError",
558
+ "user",
559
+ f"Function '{func.__name__}' requires storage to be initialized. "
560
+ f"Call flyte.init() with a valid storage configuration before using this function.",
561
+ )
562
+ return func(*args, **kwargs)
563
+
564
+ return typing.cast(T, wrapper)
565
+
566
+
567
+ def requires_upload_location(func: T) -> T:
568
+ """
569
+ Decorator that checks if the storage has been initialized before executing the function.
570
+ Raises InitializationError if the storage is not initialized.
571
+
572
+ :param func: Function to decorate
573
+ :return: Decorated function that checks for initialization
574
+ """
575
+
576
+ @functools.wraps(func)
577
+ def wrapper(*args, **kwargs) -> T:
578
+ from ._context import internal_ctx
579
+
580
+ ctx = internal_ctx()
581
+ if not ctx.raw_data:
582
+ raise InitializationError(
583
+ "No upload path configured",
584
+ "user",
585
+ f"Function '{func.__name__}' requires client to be initialized. "
586
+ f"Call flyte.init() with storage configuration before using this function.",
587
+ )
588
+ return func(*args, **kwargs)
589
+
590
+ return typing.cast(T, wrapper)
591
+
592
+
593
+ def requires_initialization(func: T) -> T:
594
+ """
595
+ Decorator that checks if the system has been initialized before executing the function.
596
+ Raises InitializationError if the system is not initialized.
597
+
598
+ :param func: Function to decorate
599
+ :return: Decorated function that checks for initialization
600
+ """
601
+
602
+ @functools.wraps(func)
603
+ def wrapper(*args, **kwargs) -> T:
604
+ if not is_initialized():
605
+ raise InitializationError(
606
+ "NotInitConfiguredError",
607
+ "user",
608
+ f"Function '{func.__name__}' requires initialization. Call flyte.init() before using this function.",
609
+ )
610
+ return func(*args, **kwargs)
611
+
612
+ return typing.cast(T, wrapper)
613
+
614
+
615
+ async def _init_for_testing(
616
+ project: str | None = None,
617
+ domain: str | None = None,
618
+ root_dir: Path | None = None,
619
+ log_level: int | None = None,
620
+ client: ClientSet | None = None,
621
+ ):
622
+ from flyte._utils.helpers import get_cwd_editable_install
623
+
624
+ global _init_config # noqa: PLW0603
625
+
626
+ if log_level:
627
+ initialize_logger(log_level=log_level)
628
+
629
+ with _init_lock:
630
+ root_dir = root_dir or get_cwd_editable_install() or Path.cwd()
631
+ _init_config = _InitConfig(
632
+ root_dir=root_dir,
633
+ project=project,
634
+ domain=domain,
635
+ client=client,
636
+ )
637
+
638
+
639
+ def replace_client(client):
640
+ global _init_config # noqa: PLW0603
641
+
642
+ with _init_lock:
643
+ _init_config = _init_config.replace(client=client)