diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index af911a2e..7751f2ed 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -14,6 +14,7 @@ - A new module `frequenz.client.dispatch.test` has been added, providing a fake Service and Client as well as a `DispatchGenerator` to generate `Dispatch` instances filled with random data. - The `DispatchGenerator.generate_dispatch` method now accepts a `microgrid_id` parameter to generate `Dispatch` instances with a specific microgrid ID. +- The `Client.create()` method now returns the newly created `Dispatch` object. ## Bug Fixes diff --git a/src/frequenz/client/dispatch/_client.py b/src/frequenz/client/dispatch/_client.py index bd6a242d..5181264b 100644 --- a/src/frequenz/client/dispatch/_client.py +++ b/src/frequenz/client/dispatch/_client.py @@ -19,9 +19,10 @@ from frequenz.api.dispatch.v1.dispatch_pb2 import ( TimeIntervalFilter as PBTimeIntervalFilter, ) -from google.protobuf.timestamp_pb2 import Timestamp -from ._internal_types import DispatchCreateRequest +from frequenz.client.base.conversion import to_timestamp + +from ._internal_types import DispatchCreateRequest, rounded_start_time from .types import ( ComponentSelector, Dispatch, @@ -86,14 +87,6 @@ async def list( """ time_interval = None - def to_timestamp(dt: datetime | None) -> Timestamp | None: - if dt is None: - return None - - ts = Timestamp() - ts.FromDatetime(dt) - return ts - if start_from or start_to or end_from or end_to: time_interval = PBTimeIntervalFilter( start_from=to_timestamp(start_from), @@ -130,9 +123,12 @@ async def create( dry_run: bool = False, payload: dict[str, Any] | None = None, recurrence: RecurrenceRule | None = None, - ) -> None: + ) -> Dispatch: """Create a dispatch. + Will try to return the created dispatch, identifying it by + the same fields as the request. + Args: microgrid_id: The microgrid_id to create the dispatch for. _type: User defined string to identify the dispatch type. @@ -144,25 +140,38 @@ async def create( payload: The payload of the dispatch. recurrence: The recurrence rule of the dispatch. + Returns: + Dispatch: The created dispatch + Raises: ValueError: If start_time is in the past. + ValueError: If the created dispatch could not be found. """ - if start_time <= datetime.now().astimezone(start_time.tzinfo): + if start_time <= datetime.now(tz=start_time.tzinfo): raise ValueError("start_time must not be in the past") + # Raise if it's not UTC + if start_time.tzinfo is None or start_time.tzinfo.utcoffset(start_time) is None: + raise ValueError("start_time must be timezone aware") + request = DispatchCreateRequest( microgrid_id=microgrid_id, type=_type, start_time=start_time, duration=duration, selector=selector, - is_active=active, - is_dry_run=dry_run, + active=active, + dry_run=dry_run, payload=payload or {}, recurrence=recurrence or RecurrenceRule(), - ).to_protobuf() + ) + + await self._stub.CreateMicrogridDispatch(request.to_protobuf()) # type: ignore - await self._stub.CreateMicrogridDispatch(request) # type: ignore + if dispatch := await self._try_fetch_created_dispatch(request): + return dispatch + + raise ValueError("Could not find the created dispatch") async def update( self, @@ -195,7 +204,7 @@ async def update( case "type": raise ValueError("Updating type is not supported") case "start_time": - msg.update.start_time.FromDatetime(val) + msg.update.start_time.CopyFrom(to_timestamp(val)) case "duration": msg.update.duration = int(val.total_seconds()) case "selector": @@ -258,3 +267,31 @@ async def delete(self, dispatch_id: int) -> None: """ request = DispatchDeleteRequest(id=dispatch_id) await self._stub.DeleteMicrogridDispatch(request) # type: ignore + + async def _try_fetch_created_dispatch( + self, + request: DispatchCreateRequest, + ) -> Dispatch | None: + """Try to fetch the created dispatch. + + Will return the created dispatch if it was found, otherwise None. + + Args: + request: The dispatch create request. + + Returns: + Dispatch: The created dispatch, if it was found. + """ + async for dispatch in self.list(microgrid_id=request.microgrid_id): + found = True + for key, value in request.__dict__.items(): + if key == "start_time": + value = rounded_start_time(value) + + if not (found := getattr(dispatch, key) == value): + break + + if found: + return dispatch + + return None diff --git a/src/frequenz/client/dispatch/_internal_types.py b/src/frequenz/client/dispatch/_internal_types.py index 549311e3..c1dacfae 100644 --- a/src/frequenz/client/dispatch/_internal_types.py +++ b/src/frequenz/client/dispatch/_internal_types.py @@ -5,7 +5,7 @@ from dataclasses import dataclass -from datetime import datetime, timedelta, timezone +from datetime import datetime, timedelta from typing import Any # pylint: disable=no-name-in-module @@ -16,6 +16,8 @@ # pylint: enable=no-name-in-module from google.protobuf.json_format import MessageToDict +from frequenz.client.base.conversion import to_datetime, to_timestamp + from .types import ( ComponentSelector, RecurrenceRule, @@ -46,10 +48,10 @@ class DispatchCreateRequest: selector: ComponentSelector """The component selector specifying which components the dispatch targets.""" - is_active: bool + active: bool """Indicates whether the dispatch is active and eligible for processing.""" - is_dry_run: bool + dry_run: bool """Indicates if the dispatch is a dry run. Executed for logging and monitoring without affecting actual component states.""" @@ -79,11 +81,11 @@ def from_protobuf( return DispatchCreateRequest( microgrid_id=pb_object.microgrid_id, type=pb_object.type, - start_time=pb_object.start_time.ToDatetime().replace(tzinfo=timezone.utc), + start_time=rounded_start_time(to_datetime(pb_object.start_time)), duration=timedelta(seconds=pb_object.duration), selector=component_selector_from_protobuf(pb_object.selector), - is_active=pb_object.is_active, - is_dry_run=pb_object.is_dry_run, + active=pb_object.is_active, + dry_run=pb_object.is_dry_run, payload=MessageToDict(pb_object.payload), recurrence=RecurrenceRule.from_protobuf(pb_object.recurrence), ) @@ -98,12 +100,29 @@ def to_protobuf(self) -> PBDispatchCreateRequest: pb_request.microgrid_id = self.microgrid_id pb_request.type = self.type - pb_request.start_time.FromDatetime(self.start_time) + pb_request.start_time.CopyFrom(to_timestamp(self.start_time)) pb_request.duration = int(self.duration.total_seconds()) pb_request.selector.CopyFrom(component_selector_to_protobuf(self.selector)) - pb_request.is_active = self.is_active - pb_request.is_dry_run = self.is_dry_run + pb_request.is_active = self.active + pb_request.is_dry_run = self.dry_run pb_request.payload.update(self.payload) pb_request.recurrence.CopyFrom(self.recurrence.to_protobuf()) return pb_request + + +def rounded_start_time(start_time: datetime) -> datetime: + """Round the start time to the nearest second. + + Args: + start_time: The start time to round. + + Returns: + The rounded start time. + """ + # Round start_time seconds to have the same behavior as the gRPC server + # https://github.com/frequenz-io/frequenz-service-dispatch/issues/77 + new_seconds = start_time.second + start_time.microsecond / 1_000_000 + start_time = start_time.replace(microsecond=0, second=0) + start_time += timedelta(seconds=round(new_seconds)) + return start_time diff --git a/src/frequenz/client/dispatch/test/_service.py b/src/frequenz/client/dispatch/test/_service.py index cc364cba..98b236a9 100644 --- a/src/frequenz/client/dispatch/test/_service.py +++ b/src/frequenz/client/dispatch/test/_service.py @@ -8,6 +8,7 @@ import dataclasses from dataclasses import dataclass, replace from datetime import datetime, timezone +from random import shuffle import grpc import grpc.aio @@ -45,6 +46,9 @@ class FakeService: _last_id: int = 0 """Last used dispatch id.""" + _shuffle_after_create: bool = False + """Whether to shuffle the dispatches after creating them.""" + # pylint: disable=invalid-name async def ListMicrogridDispatches( self, request: PBDispatchListRequest @@ -116,6 +120,9 @@ async def CreateMicrogridDispatch( update_time=datetime.now(tz=timezone.utc), ) ) + if self._shuffle_after_create: + shuffle(self.dispatches) + return Empty() async def UpdateMicrogridDispatch( @@ -240,8 +247,6 @@ def _dispatch_from_request( The initialized dispatch. """ params = _request.__dict__ - params["active"] = params.pop("is_active") - params["dry_run"] = params.pop("is_dry_run") return Dispatch( id=_id, diff --git a/src/frequenz/client/dispatch/test/client.py b/src/frequenz/client/dispatch/test/client.py index bee234b3..2fbbeb95 100644 --- a/src/frequenz/client/dispatch/test/client.py +++ b/src/frequenz/client/dispatch/test/client.py @@ -17,10 +17,15 @@ class FakeClient(Client): This client uses a fake service to simulate the dispatch api. """ - def __init__(self) -> None: - """Initialize the mock client.""" + def __init__(self, shuffle_after_create: bool = False) -> None: + """Initialize the mock client. + + Args: + shuffle_after_create: Whether to shuffle the dispatches after creating them. + """ super().__init__(MagicMock(), "mock") self._stub = FakeService() # type: ignore + self._service._shuffle_after_create = shuffle_after_create @property def dispatches(self) -> list[Dispatch]: diff --git a/src/frequenz/client/dispatch/test/generator.py b/src/frequenz/client/dispatch/test/generator.py index 5f84b756..74e30967 100644 --- a/src/frequenz/client/dispatch/test/generator.py +++ b/src/frequenz/client/dispatch/test/generator.py @@ -8,6 +8,7 @@ from frequenz.client.common.microgrid.components import ComponentCategory +from .._internal_types import rounded_start_time from ..types import Dispatch, EndCriteria, Frequency, RecurrenceRule, Weekday @@ -84,8 +85,10 @@ def generate_dispatch(self, microgrid_id: int | None = None) -> Dispatch: update_time=create_time + timedelta(seconds=self._rng.randint(0, 1000000)), microgrid_id=microgrid_id or self._rng.randint(0, 100), type=str(self._rng.randint(0, 100_000)), - start_time=datetime.now().astimezone(timezone.utc) - + timedelta(seconds=self._rng.randint(0, 1000000)), + start_time=rounded_start_time( + datetime.now(tz=timezone.utc) + + timedelta(seconds=self._rng.randint(0, 1000000)) + ), duration=timedelta(seconds=self._rng.randint(0, 1000000)), selector=self._rng.choice( # type: ignore [ diff --git a/src/frequenz/client/dispatch/types.py b/src/frequenz/client/dispatch/types.py index f8b47307..2669c2f1 100644 --- a/src/frequenz/client/dispatch/types.py +++ b/src/frequenz/client/dispatch/types.py @@ -5,7 +5,7 @@ from dataclasses import dataclass, field -from datetime import datetime, timedelta, timezone +from datetime import datetime, timedelta from enum import IntEnum from typing import Any @@ -17,6 +17,8 @@ from frequenz.api.dispatch.v1.dispatch_pb2 import RecurrenceRule as PBRecurrenceRule from google.protobuf.json_format import MessageToDict +from frequenz.client.base.conversion import to_datetime, to_timestamp + # pylint: enable=no-name-in-module from frequenz.client.common.microgrid.components import ComponentCategory @@ -125,10 +127,7 @@ def from_protobuf(cls, pb_criteria: PBRecurrenceRule.EndCriteria) -> "EndCriteri case "count": instance.count = pb_criteria.count case "until": - instance.until = pb_criteria.until.ToDatetime().replace( - tzinfo=timezone.utc - ) - + instance.until = to_datetime(pb_criteria.until) return instance def to_protobuf(self) -> PBRecurrenceRule.EndCriteria: @@ -142,7 +141,7 @@ def to_protobuf(self) -> PBRecurrenceRule.EndCriteria: if self.count is not None: pb_criteria.count = self.count elif self.until is not None: - pb_criteria.until.FromDatetime(self.until) + pb_criteria.until.CopyFrom(to_timestamp(self.until)) return pb_criteria @@ -306,9 +305,9 @@ def from_protobuf(cls, pb_object: PBDispatch) -> "Dispatch": id=pb_object.id, microgrid_id=pb_object.microgrid_id, type=pb_object.type, - create_time=pb_object.create_time.ToDatetime().replace(tzinfo=timezone.utc), - update_time=pb_object.update_time.ToDatetime().replace(tzinfo=timezone.utc), - start_time=pb_object.start_time.ToDatetime().replace(tzinfo=timezone.utc), + create_time=to_datetime(pb_object.create_time), + update_time=to_datetime(pb_object.update_time), + start_time=to_datetime(pb_object.start_time), duration=timedelta(seconds=pb_object.duration), selector=component_selector_from_protobuf(pb_object.selector), active=pb_object.is_active, @@ -328,9 +327,9 @@ def to_protobuf(self) -> PBDispatch: pb_dispatch.id = self.id pb_dispatch.microgrid_id = self.microgrid_id pb_dispatch.type = self.type - pb_dispatch.create_time.FromDatetime(self.create_time) - pb_dispatch.update_time.FromDatetime(self.update_time) - pb_dispatch.start_time.FromDatetime(self.start_time) + pb_dispatch.create_time.CopyFrom(to_timestamp(self.create_time)) + pb_dispatch.update_time.CopyFrom(to_timestamp(self.update_time)) + pb_dispatch.start_time.CopyFrom(to_timestamp(self.start_time)) pb_dispatch.duration = int(self.duration.total_seconds()) pb_dispatch.selector.CopyFrom(component_selector_to_protobuf(self.selector)) pb_dispatch.is_active = self.active diff --git a/tests/test_dispatch_client.py b/tests/test_dispatch_client.py index b8706493..ad35c941 100644 --- a/tests/test_dispatch_client.py +++ b/tests/test_dispatch_client.py @@ -52,6 +52,24 @@ async def test_create_dispatch() -> None: assert stored_dispatches[0] == sample +async def test_create_return_dispatch() -> None: + """Test creating a dispatch and returning the created dispatch.""" + # Make sure we don't rely on the order of the dispatches + generator = DispatchGenerator() + client = FakeClient(shuffle_after_create=True) + + for _ in range(100): + sample = generator.generate_dispatch() + + dispatch = await client.create(**to_create_params(sample)) + + # Before we can compare, we need to set the create_time and update_time + # as they are generated by the (fake) remote point + sample = _update(sample, dispatch) + + assert dispatch == sample + + async def test_list_dispatches() -> None: """Test listing dispatches.""" sampler = DispatchGenerator()