GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — sdk-python/temporalio/envconfig.py at main · temporalio/sdk-python Expand file tree/ Copy pathenvconfig.pyMore file actions 520 lines (443 loc) · 19.4 KB / Copy pathenvconfig.pyFile metadata and controls520 lines (443 loc) · 19.4 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 """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 import os from abc import ABC, abstractmethod from collections.abc import Mapping, Sequence from dataclasses import dataclass, field from pathlib import Path from typing import Any, Literal, TypeAlias, cast from typing_extensions import Self, TypedDict import temporalio.client import temporalio.service from temporalio.bridge.temporal_sdk_bridge import envconfig as _bridge_envconfig DataSource: TypeAlias = ( 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 | None 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] ext: Mapping[str, Mapping[str, Any]] def _from_dict_to_source(d: Mapping[str, Any] | None) -> DataSource | None: 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: DataSource | None, ) -> Mapping[str, str] | None: 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: DataSource | None, ) -> tuple[str | None, bytes | None]: path: str | None = None data: bytes | None = 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( # type: ignore[reportUnreachable] "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: DataSource | None) -> bytes | None: 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( # type: ignore[reportUnreachable] 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""" disabled: bool | None = None """If True, TLS is explicitly disabled. If False, TLS is explicitly enabled. If None, TLS behavior was not configured.""" server_name: str | None = None """SNI override.""" server_root_ca_cert: DataSource | None = None """Server CA certificate source.""" client_cert: DataSource | None = None """Client certificate source.""" client_private_key: DataSource | None = 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 is not None: 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: DataSource | None, ): 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) -> bool | temporalio.service.TLSConfig: """Create a `temporalio.service.TLSConfig` from this profile.""" if self.disabled is True: 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), ) @classmethod def from_dict(cls, d: ClientConfigTLSDict | None) -> Self | None: """Create a ClientConfigTLS from a dictionary. ``None`` means there is no TLS table. An empty dictionary is a TLS table with nothing set, so it gives a default ``ClientConfigTLS``. """ if d is None: return None return cls( disabled=d.get("disabled"), 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. """ target_host: str namespace: str api_key: str tls: bool | temporalio.service.TLSConfig rpc_metadata: Mapping[str, str] plugins: Sequence[temporalio.client.Plugin] @dataclass(frozen=True) class ClientConfigProfile: """Represents a client configuration profile. This class holds the configuration as loaded from a file or environment. See `to_client_connect_config` to transform the profile to `ClientConnectConfig`, which can be used to create a client. """ address: str | None = None """Client address.""" namespace: str | None = None """Client namespace.""" api_key: str | None = None """Client API key.""" tls: ClientConfigTLS | None = None """TLS configuration.""" grpc_meta: Mapping[str, str] = field(default_factory=dict) """gRPC metadata.""" ext: Mapping[str, Mapping[str, Any]] = field(default_factory=dict) """Raw extension config from ``profile.<profile>.ext``, keyed by extension name. Each extension decodes its own table, which should be treated as read-only. Values are converted as by :py:mod:`tomllib`, so TOML datetimes are :py:class:`datetime.datetime`, :py:class:`datetime.date`, or :py:class:`datetime.time` objects. Not modified by environment variables. .. warning:: This API is experimental and unstable. """ @classmethod def from_dict(cls, d: ClientConfigProfileDict) -> Self: """Create a ClientConfigProfile from a dictionary.""" return cls( 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 {}, ext=d.get("ext") 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 is not None: d["tls"] = self.tls.to_dict() if self.grpc_meta: d["grpc_meta"] = self.grpc_meta if self.ext: d["ext"] = self.ext return d def to_client_connect_config(self) -> ClientConnectConfig: """Create a `ClientConnectConfig` from this profile.""" # Only include non-None values config: dict[str, Any] = {} if self.address: config["target_host"] = self.address if self.namespace is not None: config["namespace"] = self.namespace if self.api_key is not None: config["api_key"] = self.api_key # Enable TLS with default TLS options config["tls"] = True if self.tls is not None: # Use specified TLS options config["tls"] = self.tls.to_connect_tls_config() if self.grpc_meta: config["rpc_metadata"] = self.grpc_meta # Cast to ClientConnectConfig - this is safe because we've only included non-None values return cast(ClientConnectConfig, config) # type: ignore[reportInvalidCast] @staticmethod def load( profile: str | None = None, *, config_source: DataSource | None = None, disable_file: bool = False, disable_env: bool = False, config_file_strict: bool = False, override_env_vars: Mapping[str, str] | None = 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 ``override_env_vars`` parameter. config_file_strict: If true, will error on unrecognized keys. override_env_vars: The environment to use for loading and overrides. If not provided, the current process's environment is used. To use a specific set of environment variables, provide them here. To disable environment variable loading, set ``disable_env`` to true. 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=override_env_vars, ) return ClientConfigProfile.from_dict(raw_profile) @dataclass(frozen=True) class ClientConfigExtensionRequest: """Input to :py:meth:`ClientConfigExtension.client_plugin`. .. warning:: This API is experimental and unstable. """ profile: ClientConfigProfile """The loaded profile, with environment variable overrides applied.""" env: Mapping[str, str] | None """Env to read extension env vars from, or None if env loading is disabled.""" class ClientConfigExtension(ABC): """Extension that adds config to client environment configuration. An extension owns the TOML table under ``profile.<profile>.ext.<name>``, where ``<name>`` is :py:meth:`name`, and turns its config into a client plugin. Extensions are recommended to use a ``TEMPORAL_EXT_<NAME>_`` prefix for any environment variables they read. Pass extensions to :py:meth:`ClientConfig.load_client_connect_config`. .. warning:: This API is experimental and unstable. """ @abstractmethod def name(self) -> str: """The extension's table key under ``profile.<profile>.ext``. Must be unique among loaded extensions. """ @abstractmethod def client_plugin( self, req: ClientConfigExtensionRequest ) -> temporalio.client.Plugin | None: """Read this extension's config from the profile and env, and return a plugin that applies it, or None if there's nothing to apply. """ def _validate_extensions(extensions: Sequence[ClientConfigExtension]) -> None: names: set[str] = set() for i, extension in enumerate(extensions): if extension is None: # type: ignore[reportUnnecessaryComparison] raise ValueError(f"client config extension at index {i} is None") name = extension.name() if not name: raise ValueError(f"client config extension at index {i} has empty name") if name in names: raise ValueError(f'duplicate client config extension name "{name}"') names.add(name) @dataclass class ClientConfig: """Client configuration loaded from TOML and environment variables. This contains a mapping of profile names to client profiles. Use `ClientConfigProfile.to_client_connect_config` to create a `ClientConnectConfig` from a profile. See `ClientConfigProfile.load` to load an individual profile. """ 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()} @classmethod def from_dict( cls, d: Mapping[str, Mapping[str, Any]], ) -> Self: """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 cls( profiles={ k: ClientConfigProfile.from_dict(cast(ClientConfigProfileDict, v)) for k, v in d.items() } ) @staticmethod def load( *, config_source: DataSource | None = None, config_file_strict: bool = False, override_env_vars: Mapping[str, str] | None = 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. config_file_strict: If true, will TOML file parsing will error on unrecognized keys. override_env_vars: The environment variables to use for locating the default config file. If not provided, the current process's environment is used to check for ``TEMPORAL_CONFIG_FILE``. To use a specific set of environment variables, provide them here. To disable environment variable loading, set ``disable_file`` to true or pass an empty dictionary for this parameter. """ path, data = _source_to_path_and_data(config_source) loaded_profiles = _bridge_envconfig.load_client_config( path=path, data=data, config_file_strict=config_file_strict, env_vars=override_env_vars, ) return ClientConfig.from_dict(loaded_profiles) @staticmethod def load_client_connect_config( profile: str | None = None, *, config_file: str | None = None, disable_file: bool = False, disable_env: bool = False, config_file_strict: bool = False, override_env_vars: Mapping[str, str] | None = None, extensions: Sequence[ClientConfigExtension] = [], ) -> 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, plus any extensions. 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. If not provided, the current process's environment is used. To use a specific set of environment variables, provide them here. To disable environment variable loading, set ``disable_env`` to true. extensions: Extensions to apply, in order. Each extension is given the loaded profile and env, and any plugin it returns is appended to the ``plugins`` of the returned config. Extension names must be unique. To also pass other plugins to :py:meth:`temporalio.client.Client.connect`, combine them with these rather than passing ``plugins`` separately. .. warning:: This parameter is experimental and unstable. Returns: TypedDict of keyword arguments for :py:meth:`temporalio.client.Client.connect`. """ _validate_extensions(extensions) config_source: DataSource | None = 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, override_env_vars=override_env_vars, ) config = prof.to_client_connect_config() if extensions: req = ClientConfigExtensionRequest( profile=prof, env=None if disable_env else (os.environ if override_env_vars is None else override_env_vars), ) plugins: list[temporalio.client.Plugin] = [] for extension in extensions: try: plugin = extension.client_plugin(req) except Exception as err: raise RuntimeError( f'client config extension "{extension.name()}": {err}' ) from err if plugin is not None: plugins.append(plugin) if plugins: config["plugins"] = plugins return config |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |