|
| 1 | +# License: All rights reserved |
| 2 | +# Copyright © 2024 Frequenz Energy-as-a-Service GmbH |
| 3 | + |
| 4 | +"""Helper class to manage actors based on dispatches.""" |
| 5 | + |
| 6 | +import logging |
| 7 | +from dataclasses import dataclass |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +from frequenz.channels import Receiver, Sender |
| 11 | +from frequenz.client.dispatch.types import ComponentSelector |
| 12 | +from frequenz.sdk.actor import Actor |
| 13 | + |
| 14 | +from ._dispatch import Dispatch, RunningState |
| 15 | + |
| 16 | +_logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +@dataclass(frozen=True, kw_only=True) |
| 20 | +class DispatchConfigurationEvent: |
| 21 | + """Event emitted when the dispatch configuration changes.""" |
| 22 | + |
| 23 | + components: ComponentSelector |
| 24 | + """Components to be used.""" |
| 25 | + |
| 26 | + dry_run: bool |
| 27 | + """Whether this is a dry run.""" |
| 28 | + |
| 29 | + payload: dict[str, Any] |
| 30 | + """Additional payload.""" |
| 31 | + |
| 32 | + |
| 33 | +class DispatchRunnerActor(Actor): |
| 34 | + """Helper class to manage actors based on dispatches. |
| 35 | +
|
| 36 | + Example usage: |
| 37 | +
|
| 38 | + ```python |
| 39 | + import os |
| 40 | + import asyncio |
| 41 | + from frequenz.dispatch import Dispatcher, DispatchRunnerActor, DispatchConfigurationEvent |
| 42 | + from frequenz.client.dispatch.types import ComponentSelector |
| 43 | + from frequenz.client.common.microgrid.components import ComponentCategory |
| 44 | +
|
| 45 | + from frequenz.channels import Receiver, Broadcast |
| 46 | + from unittest.mock import MagicMock |
| 47 | +
|
| 48 | + class MyActor(Actor): |
| 49 | + def __init__(self, config_channel: Receiver[DispatchConfigurationEvent]): |
| 50 | + super().__init__() |
| 51 | + self._config_channel = config_channel |
| 52 | + self._dry_run: bool |
| 53 | + self._payload: dict[str, Any] |
| 54 | +
|
| 55 | + async def _run(self) -> None: |
| 56 | + while True: |
| 57 | + config = await self._config_channel.receive() |
| 58 | + print("Received config:", config) |
| 59 | +
|
| 60 | + self.set_components(config.components) |
| 61 | + self._dry_run = config.dry_run |
| 62 | + self._payload = config.payload |
| 63 | +
|
| 64 | + def set_components(self, components: ComponentSelector) -> None: |
| 65 | + match components: |
| 66 | + case [int(), *_] as component_ids: |
| 67 | + print("Dispatch: Setting components to %s", components) |
| 68 | + case [ComponentCategory.BATTERY, *_]: |
| 69 | + print("Dispatch: Using all battery components") |
| 70 | + case _ as unsupported: |
| 71 | + print( |
| 72 | + "Dispatch: Requested an unsupported selector %r, " |
| 73 | + "but only component IDs or category BATTERY are supported.", |
| 74 | + unsupported, |
| 75 | + ) |
| 76 | +
|
| 77 | + async def run(): |
| 78 | + url = os.getenv("DISPATCH_API_URL", "grpc://fz-0004.frequenz.io:50051") |
| 79 | + key = os.getenv("DISPATCH_API_KEY", "some-key") |
| 80 | +
|
| 81 | + microgrid_id = 1 |
| 82 | +
|
| 83 | + dispatcher = Dispatcher( |
| 84 | + microgrid_id=microgrid_id, |
| 85 | + server_url=url, |
| 86 | + key=key |
| 87 | + ) |
| 88 | +
|
| 89 | + # Create config channel to receive (re-)configuration events pre-start and mid-run |
| 90 | + config_channel = Broadcast[DispatchConfigurationEvent](name="config_channel") |
| 91 | +
|
| 92 | + # Start actor and supporting actor, give each a config channel receiver |
| 93 | + my_actor = MyActor(config_channel.new_receiver()) |
| 94 | + supporting_actor = MagicMock(config_channel.new_receiver()) |
| 95 | +
|
| 96 | + status_receiver = dispatcher.running_status_change.new_receiver() |
| 97 | +
|
| 98 | + dispatch_handler = DispatchRunnerActor( |
| 99 | + actors=frozenset([my_actor, supporting_actor]), |
| 100 | + dispatch_type="EXAMPLE", |
| 101 | + running_status_receiver=status_receiver, |
| 102 | + configuration_sender=config_channel.new_sender(), |
| 103 | + ) |
| 104 | +
|
| 105 | + await asyncio.gather(dispatcher.start(), dispatch_handler.start()) |
| 106 | + ``` |
| 107 | + """ |
| 108 | + |
| 109 | + def __init__( |
| 110 | + self, |
| 111 | + actors: frozenset[Actor], |
| 112 | + dispatch_type: str, |
| 113 | + running_status_receiver: Receiver[Dispatch], |
| 114 | + configuration_sender: Sender[DispatchConfigurationEvent] | None = None, |
| 115 | + ) -> None: |
| 116 | + """Initialize the dispatch handler. |
| 117 | +
|
| 118 | + Args: |
| 119 | + actors: The actors to handle. |
| 120 | + dispatch_type: The type of dispatches to handle. |
| 121 | + running_status_receiver: The receiver for dispatch running status changes. |
| 122 | + configuration_sender: The sender for dispatch configuration events |
| 123 | + """ |
| 124 | + super().__init__() |
| 125 | + self._dispatch_rx = running_status_receiver |
| 126 | + self._actors = actors |
| 127 | + self._dispatch_type = dispatch_type |
| 128 | + self._configuration_sender = configuration_sender |
| 129 | + |
| 130 | + def _start_actors(self) -> None: |
| 131 | + """Start all actors.""" |
| 132 | + for actor in self._actors: |
| 133 | + if actor.is_running: |
| 134 | + _logger.warning("Actor %s is already running", actor.name) |
| 135 | + else: |
| 136 | + actor.start() |
| 137 | + |
| 138 | + async def _stop_actors(self, msg: str) -> None: |
| 139 | + """Stop all actors. |
| 140 | +
|
| 141 | + Args: |
| 142 | + msg: The message to be passed to the actors being stopped. |
| 143 | + """ |
| 144 | + for actor in self._actors: |
| 145 | + if actor.is_running: |
| 146 | + await actor.stop(msg) |
| 147 | + else: |
| 148 | + _logger.warning("Actor %s is not running", actor.name) |
| 149 | + |
| 150 | + async def _run(self) -> None: |
| 151 | + """Wait for dispatches and handle them.""" |
| 152 | + while True: |
| 153 | + _logger.info("Waiting for dispatch...") |
| 154 | + dispatch = await self._dispatch_rx.receive() |
| 155 | + await self._handle_dispatch(dispatch=dispatch) |
| 156 | + |
| 157 | + async def _handle_dispatch(self, dispatch: Dispatch) -> None: |
| 158 | + """Handle a dispatch. |
| 159 | +
|
| 160 | + Args: |
| 161 | + dispatch: The dispatch to handle. |
| 162 | +
|
| 163 | + Returns: |
| 164 | + The running state. |
| 165 | + """ |
| 166 | + running = dispatch.running(self._dispatch_type) |
| 167 | + match running: |
| 168 | + case RunningState.STOPPED: |
| 169 | + _logger.info("Stopping dispatch...") |
| 170 | + await self._stop_actors("Dispatch stopped") |
| 171 | + case RunningState.RUNNING: |
| 172 | + if self._configuration_sender is not None: |
| 173 | + _logger.info("Updating configuration...") |
| 174 | + await self._configuration_sender.send( |
| 175 | + DispatchConfigurationEvent( |
| 176 | + components=dispatch.selector, |
| 177 | + dry_run=dispatch.dry_run, |
| 178 | + payload=dispatch.payload, |
| 179 | + ) |
| 180 | + ) |
| 181 | + |
| 182 | + _logger.info("Running dispatch...") |
| 183 | + self._start_actors() |
| 184 | + case RunningState.DIFFERENT_TYPE: |
| 185 | + _logger.debug( |
| 186 | + "Unknown dispatch! Ignoring dispatch of type %s", dispatch.type |
| 187 | + ) |
0 commit comments