|
1 | 1 | # License: MIT |
2 | 2 | # Copyright © 2024 Frequenz Energy-as-a-Service GmbH |
3 | 3 |
|
4 | | -"""Configuration management.""" |
| 4 | +"""Configuration management. |
| 5 | +
|
| 6 | +Example: App configuring the global config manager. |
| 7 | + ```python |
| 8 | + import asyncio |
| 9 | + import dataclasses |
| 10 | + import sys |
| 11 | +
|
| 12 | + import marshmallow |
| 13 | +
|
| 14 | + from frequenz.channels import select, selected_from |
| 15 | + from frequenz.sdk.actor import Actor |
| 16 | + from frequenz.sdk.config import ( |
| 17 | + initialize_config, |
| 18 | + config_manager, |
| 19 | + LoggingConfigUpdatingActor, |
| 20 | + ConfigManager, |
| 21 | + ) |
| 22 | +
|
| 23 | + @dataclasses.dataclass |
| 24 | + class ActorConfig: |
| 25 | + name: str |
| 26 | +
|
| 27 | + class MyActor(Actor): |
| 28 | + def __init__(self, config: ActorConfig) -> None: |
| 29 | + self._config = config |
| 30 | +
|
| 31 | + async def _run(self) -> None: |
| 32 | + receiver = ... |
| 33 | + config_receiver = await config_manager().new_receiver(schema=ActorConfig) |
| 34 | +
|
| 35 | + async for selected in select(receiver, config_receiver): |
| 36 | + if selected_from(selected, receiver): |
| 37 | + ... |
| 38 | + elif selected_from(selected, config_receiver): |
| 39 | + self._config = selected.message |
| 40 | + # Restart whatever is needed after a config update |
| 41 | +
|
| 42 | +
|
| 43 | + @dataclasses.dataclass |
| 44 | + class AppConfig: |
| 45 | + positive_int: int = dataclasses.field( |
| 46 | + default=42, |
| 47 | + metadata={"validate": marshmallow.validate.Range(min=0)}, |
| 48 | + ) |
| 49 | + my_actor: ActorConfig | None = None |
| 50 | + logging: LoggingConfig = LoggingConfig() |
| 51 | +
|
| 52 | + async def main() -> None: |
| 53 | + config_manager = initialize_config_manager(["config.toml"]) |
| 54 | + try: |
| 55 | + # Receive the first configuration |
| 56 | + initial_config = await config_manager.new_receiver(schema=AppConfig, |
| 57 | + wait_for_first=True) |
| 58 | + except asyncio.TimeoutError: |
| 59 | + print("No configuration received in time") |
| 60 | + sys.exit(1) |
| 61 | +
|
| 62 | + actor = MyActor(ActorConfig(name=initial_config.my_actor)) |
| 63 | + actor.start() |
| 64 | + await actor |
| 65 | + ``` |
| 66 | +""" |
5 | 67 |
|
6 | 68 | from ._actor import ConfigManagingActor |
7 | 69 | from ._global import config_manager, initialize_config, shutdown_config_manager |
|
0 commit comments