Skip to content

Commit 47ebc04

Browse files
committed
WIP: Add full example in the config module.
1 parent 44e52f7 commit 47ebc04

File tree

1 file changed

+63
-1
lines changed

1 file changed

+63
-1
lines changed

src/frequenz/sdk/config/__init__.py

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,69 @@
11
# License: MIT
22
# Copyright © 2024 Frequenz Energy-as-a-Service GmbH
33

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+
"""
567

668
from ._actor import ConfigManagingActor
769
from ._global import config_manager, initialize_config, shutdown_config_manager

0 commit comments

Comments
 (0)