Skip to content

Commit 4a485d7

Browse files
committed
WIP: Add full example in the config module.
1 parent d3aaa01 commit 4a485d7

File tree

1 file changed

+64
-1
lines changed

1 file changed

+64
-1
lines changed

src/frequenz/sdk/config/__init__.py

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,70 @@
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+
super().__init__()
31+
32+
async def _run(self) -> None:
33+
receiver = ...
34+
config_receiver = await config_manager().new_receiver(schema=ActorConfig)
35+
36+
async for selected in select(receiver, config_receiver):
37+
if selected_from(selected, receiver):
38+
...
39+
elif selected_from(selected, config_receiver):
40+
self._config = selected.message
41+
# Restart whatever is needed after a config update
42+
43+
44+
@dataclasses.dataclass
45+
class AppConfig:
46+
positive_int: int = dataclasses.field(
47+
default=42,
48+
metadata={"validate": marshmallow.validate.Range(min=0)},
49+
)
50+
my_actor: ActorConfig | None = None
51+
logging: LoggingConfig = LoggingConfig()
52+
53+
async def main() -> None:
54+
config_manager = initialize_config_manager(["config.toml"])
55+
try:
56+
# Receive the first configuration
57+
initial_config = await config_manager.new_receiver(schema=AppConfig,
58+
wait_for_first=True)
59+
except asyncio.TimeoutError:
60+
print("No configuration received in time")
61+
sys.exit(1)
62+
63+
actor = MyActor(ActorConfig(name=initial_config.my_actor))
64+
actor.start()
65+
await actor
66+
```
67+
"""
568

669
from ._global import (
770
get_config_manager,

0 commit comments

Comments
 (0)