forked from temporalio/sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenvconfig.py
More file actions
413 lines (350 loc) · 14.7 KB
/
Copy pathenvconfig.py
File metadata and controls
413 lines (350 loc) · 14.7 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
"""Environment and file-based configuration for Temporal clients.
This module provides utilities to load Temporal client configuration from TOML files
and environment variables.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Literal, Mapping, Optional, Union, cast
from typing_extensions import TypeAlias, TypedDict
import temporalio.service
from temporalio.bridge.temporal_sdk_bridge import envconfig as _bridge_envconfig
DataSource: TypeAlias = Union[
Path, str, bytes
] # str represents a file contents, bytes represents raw data
# We define typed dictionaries for what these configs look like as TOML.
class ClientConfigTLSDict(TypedDict, total=False):
"""Dictionary representation of TLS config for TOML."""
disabled: bool
server_name: str
server_ca_cert: Mapping[str, str]
client_cert: Mapping[str, str]
client_key: Mapping[str, str]
class ClientConfigProfileDict(TypedDict, total=False):
"""Dictionary representation of a client config profile for TOML."""
address: str
namespace: str
api_key: str
tls: ClientConfigTLSDict
grpc_meta: Mapping[str, str]
def _from_dict_to_source(d: Optional[Mapping[str, Any]]) -> Optional[DataSource]:
if not d:
return None
if "data" in d:
return d["data"]
if "path" in d:
return Path(d["path"])
return None
def _source_to_dict(
source: Optional[DataSource],
) -> Optional[Mapping[str, str]]:
if isinstance(source, Path):
return {"path": str(source)}
if isinstance(source, str):
return {"data": source}
if isinstance(source, bytes):
return {"data": source.decode("utf-8")}
return None
def _source_to_path_and_data(
source: Optional[DataSource],
) -> tuple[Optional[str], Optional[bytes]]:
path: Optional[str] = None
data: Optional[bytes] = None
if isinstance(source, Path):
path = str(source)
elif isinstance(source, str):
data = source.encode("utf-8")
elif isinstance(source, bytes):
data = source
elif source is not None:
raise TypeError(
"config_source must be one of pathlib.Path, str, bytes, or None, "
f"but got {type(source).__name__}"
)
return path, data
def _read_source(source: Optional[DataSource]) -> Optional[bytes]:
if source is None:
return None
if isinstance(source, Path):
with open(source, "rb") as f:
return f.read()
if isinstance(source, str):
return source.encode("utf-8")
if isinstance(source, bytes):
return source
raise TypeError(
f"Source must be one of pathlib.Path, str, or bytes, but got {type(source).__name__}"
)
@dataclass(frozen=True)
class ClientConfigTLS:
"""TLS configuration as specified as part of client configuration
.. warning::
Experimental API.
"""
disabled: bool = False
"""If true, TLS is explicitly disabled."""
server_name: Optional[str] = None
"""SNI override."""
server_root_ca_cert: Optional[DataSource] = None
"""Server CA certificate source."""
client_cert: Optional[DataSource] = None
"""Client certificate source."""
client_private_key: Optional[DataSource] = None
"""Client key source."""
def to_dict(self) -> ClientConfigTLSDict:
"""Convert to a dictionary that can be used for TOML serialization."""
d: ClientConfigTLSDict = {}
if self.disabled:
d["disabled"] = self.disabled
if self.server_name is not None:
d["server_name"] = self.server_name
def set_source(
key: Literal["server_ca_cert", "client_cert", "client_key"],
source: Optional[DataSource],
):
if source is not None and (val := _source_to_dict(source)):
d[key] = val
set_source("server_ca_cert", self.server_root_ca_cert)
set_source("client_cert", self.client_cert)
set_source("client_key", self.client_private_key)
return d
def to_connect_tls_config(self) -> Union[bool, temporalio.service.TLSConfig]:
"""Create a `temporalio.service.TLSConfig` from this profile."""
if self.disabled:
return False
return temporalio.service.TLSConfig(
domain=self.server_name,
server_root_ca_cert=_read_source(self.server_root_ca_cert),
client_cert=_read_source(self.client_cert),
client_private_key=_read_source(self.client_private_key),
)
@staticmethod
def from_dict(d: Optional[ClientConfigTLSDict]) -> Optional[ClientConfigTLS]:
"""Create a ClientConfigTLS from a dictionary."""
if not d:
return None
return ClientConfigTLS(
disabled=d.get("disabled", False),
server_name=d.get("server_name"),
# Note: Bridge uses snake_case, but TOML uses kebab-case which is
# converted to snake_case. Core has server_ca_cert, client_key.
server_root_ca_cert=_from_dict_to_source(d.get("server_ca_cert")),
client_cert=_from_dict_to_source(d.get("client_cert")),
client_private_key=_from_dict_to_source(d.get("client_key")),
)
class ClientConnectConfig(TypedDict, total=False):
"""Arguments for `temporalio.client.Client.connect` that are configurable via
environment configuration.
.. warning::
Experimental API.
"""
target_host: Optional[str]
namespace: Optional[str]
api_key: Optional[str]
tls: Optional[Union[bool, temporalio.service.TLSConfig]]
rpc_metadata: Optional[Mapping[str, str]]
@dataclass(frozen=True)
class ClientConfigProfile:
"""Represents a client configuration profile.
This class holds the configuration as loaded from a file or environment.
See `to_connect_config` to transform the profile to `ClientConnectConfig`,
which can be used to create a client.
.. warning::
Experimental API.
"""
address: Optional[str] = None
"""Client address."""
namespace: Optional[str] = None
"""Client namespace."""
api_key: Optional[str] = None
"""Client API key."""
tls: Optional[ClientConfigTLS] = None
"""TLS configuration."""
grpc_meta: Mapping[str, str] = field(default_factory=dict)
"""gRPC metadata."""
@staticmethod
def from_dict(d: ClientConfigProfileDict) -> ClientConfigProfile:
"""Create a ClientConfigProfile from a dictionary."""
return ClientConfigProfile(
address=d.get("address"),
namespace=d.get("namespace"),
api_key=d.get("api_key"),
tls=ClientConfigTLS.from_dict(d.get("tls")),
grpc_meta=d.get("grpc_meta") or {},
)
def to_dict(self) -> ClientConfigProfileDict:
"""Convert to a dictionary that can be used for TOML serialization."""
d: ClientConfigProfileDict = {}
if self.address is not None:
d["address"] = self.address
if self.namespace is not None:
d["namespace"] = self.namespace
if self.api_key is not None:
d["api_key"] = self.api_key
if self.tls and (tls_dict := self.tls.to_dict()):
d["tls"] = tls_dict
if self.grpc_meta:
d["grpc_meta"] = self.grpc_meta
return d
def to_client_connect_config(self) -> ClientConnectConfig:
"""Create a `ClientConnectConfig` from this profile."""
config: ClientConnectConfig = {}
if self.address:
config["target_host"] = self.address
if self.namespace:
config["namespace"] = self.namespace
if self.api_key:
config["api_key"] = self.api_key
if self.tls:
config["tls"] = self.tls.to_connect_tls_config()
if self.grpc_meta:
config["rpc_metadata"] = self.grpc_meta
return config
@staticmethod
def load(
profile: str = "default",
*,
config_source: Optional[DataSource] = None,
disable_file: bool = False,
disable_env: bool = False,
config_file_strict: bool = False,
env_vars: Optional[Mapping[str, str]] = None,
) -> ClientConfigProfile:
"""Load a single client profile from given sources, applying env
overrides.
To get a :py:class:`ClientConnectConfig`, use the
:py:meth:`to_client_connect_config` method on the returned profile.
Args:
profile: Profile to load from the config.
config_source: If present, this is used as the configuration source
instead of default file locations. This can be a path to the file
or the string/byte contents of the file.
disable_file: If true, file loading is disabled. This is only used
when ``config_source`` is not present.
disable_env: If true, environment variable loading and overriding
is disabled. This takes precedence over the ``env_vars``
parameter.
config_file_strict: If true, will error on unrecognized keys.
env_vars: The environment to use for loading and overrides. If not
provided, environment variables are not used for overrides. To
use the current process's environment, :py:attr:`os.environ` can be
passed explicitly.
Returns:
The client configuration profile.
"""
path, data = _source_to_path_and_data(config_source)
raw_profile = _bridge_envconfig.load_client_connect_config(
profile=profile,
path=path,
data=data,
disable_file=disable_file,
disable_env=disable_env,
config_file_strict=config_file_strict,
env_vars=env_vars,
)
return ClientConfigProfile.from_dict(raw_profile)
@dataclass
class ClientConfig:
"""Client configuration loaded from TOML and environment variables.
This contains a mapping of profile names to client profiles. Use
`ClientConfigProfile.to_connect_config` to create a `ClientConnectConfig`
from a profile. See `load_profile` to load an individual profile.
.. warning::
Experimental API.
"""
profiles: Mapping[str, ClientConfigProfile]
"""Map of profile name to its corresponding ClientConfigProfile."""
def to_dict(self) -> Mapping[str, ClientConfigProfileDict]:
"""Convert to a dictionary that can be used for TOML serialization."""
return {k: v.to_dict() for k, v in self.profiles.items()}
@staticmethod
def from_dict(
d: Mapping[str, Mapping[str, Any]],
) -> ClientConfig:
"""Create a ClientConfig from a dictionary."""
# We must cast the inner dictionary because the source is often a plain
# Mapping[str, Any] from the bridge or other sources.
return ClientConfig(
profiles={
k: ClientConfigProfile.from_dict(cast(ClientConfigProfileDict, v))
for k, v in d.items()
}
)
@staticmethod
def load(
*,
config_source: Optional[DataSource] = None,
disable_file: bool = False,
config_file_strict: bool = False,
env_vars: Optional[Mapping[str, str]] = None,
) -> ClientConfig:
"""Load all client profiles from given sources.
This does not apply environment variable overrides to the profiles, it
only uses an environment variable to find the default config file path
(``TEMPORAL_CONFIG_FILE``). To get a single profile with environment variables
applied, use :py:meth:`ClientConfigProfile.load`.
Args:
config_source: If present, this is used as the configuration source
instead of default file locations. This can be a path to the file
or the string/byte contents of the file.
disable_file: If true, file loading is disabled. This is only used
when ``config_source`` is not present.
config_file_strict: If true, will TOML file parsing will error on
unrecognized keys.
env_vars: The environment variables to use for locating the default config
file. If not provided, ``TEMPORAL_CONFIG_FILE`` is not checked
and only the default path is used (e.g. ``~/.config/temporalio/temporal.toml``).
To use the current process's environment, :py:attr:`os.environ` can be passed
explicitly.
"""
path, data = _source_to_path_and_data(config_source)
loaded_profiles = _bridge_envconfig.load_client_config(
path=path,
data=data,
disable_file=disable_file,
config_file_strict=config_file_strict,
env_vars=env_vars,
)
return ClientConfig.from_dict(loaded_profiles)
@staticmethod
def load_client_connect_config(
profile: str = "default",
*,
config_file: Optional[str] = None,
disable_file: bool = False,
disable_env: bool = False,
config_file_strict: bool = False,
override_env_vars: Optional[Mapping[str, str]] = None,
) -> ClientConnectConfig:
"""Load a single client profile and convert to connect config.
This is a convenience function that combines loading a profile and
converting it to a connect config dictionary. This will use the current
process's environment for overrides unless disabled.
Args:
profile: The profile to load from the config. Defaults to "default".
config_file: Path to a specific TOML config file. If not provided,
default file locations are used. This is ignored if
``disable_file`` is true.
disable_file: If true, file loading is disabled.
disable_env: If true, environment variable loading and overriding
is disabled.
config_file_strict: If true, will error on unrecognized keys in the
TOML file.
override_env_vars: A dictionary of environment variables to use for
loading and overrides.
Returns:
TypedDict of keyword arguments for
:py:meth:`temporalio.client.Client.connect`.
"""
config_source: Optional[DataSource] = None
if config_file and not disable_file:
config_source = Path(config_file)
prof = ClientConfigProfile.load(
profile=profile,
config_source=config_source,
disable_file=disable_file,
disable_env=disable_env,
config_file_strict=config_file_strict,
env_vars=override_env_vars,
)
return prof.to_client_connect_config()