-
Couldn't load subscription status.
- Fork 13
Introduce GrpcStreamBroadcaster to enable keep_alive options #154
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
flora-hofmann-frequenz
merged 1 commit into
frequenz-floss:v0.x.x
from
flora-hofmann-frequenz:incorporate_grpcbroadcaster
Mar 28, 2025
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,9 +7,7 @@ | |
| from collections.abc import AsyncIterator, Iterable, Iterator | ||
| from dataclasses import dataclass | ||
| from datetime import datetime, timedelta, timezone | ||
| from typing import cast | ||
|
|
||
| import grpc.aio as grpcaio | ||
| from typing import Any, AsyncIterable, cast | ||
|
|
||
| # pylint: disable=no-name-in-module | ||
| from frequenz.api.common.v1.microgrid.microgrid_pb2 import ( | ||
|
|
@@ -39,8 +37,10 @@ | |
| ) | ||
| from frequenz.api.reporting.v1.reporting_pb2 import TimeFilter as PBTimeFilter | ||
| from frequenz.api.reporting.v1.reporting_pb2_grpc import ReportingStub | ||
| from frequenz.client.base.channel import ChannelOptions | ||
| from frequenz.client.base.client import BaseApiClient | ||
| from frequenz.client.base.exception import ClientNotConnected | ||
| from frequenz.client.base.streaming import GrpcStreamBroadcaster | ||
| from frequenz.client.common.metric import Metric | ||
| from google.protobuf.timestamp_pb2 import Timestamp as PBTimestamp | ||
|
|
||
|
|
@@ -177,14 +177,29 @@ def sample(self) -> MetricSample: | |
| class ReportingApiClient(BaseApiClient[ReportingStub]): | ||
| """A client for the Reporting service.""" | ||
|
|
||
| def __init__(self, server_url: str, key: str | None = None) -> None: | ||
| def __init__( | ||
| self, | ||
| server_url: str, | ||
| key: str | None = None, | ||
| connect: bool = True, | ||
| channel_defaults: ChannelOptions = ChannelOptions(), # default options | ||
| ) -> None: | ||
| """Create a new Reporting client. | ||
|
|
||
| Args: | ||
| server_url: The URL of the Reporting service. | ||
| key: The API key for the authorization. | ||
| connect: Whether to connect to the server immediately. | ||
| channel_defaults: The default channel options. | ||
| """ | ||
| super().__init__(server_url, ReportingStub) | ||
| super().__init__( | ||
| server_url, | ||
| ReportingStub, | ||
| connect=connect, | ||
| channel_defaults=channel_defaults, | ||
| ) | ||
|
|
||
| self._broadcasters: dict[int, GrpcStreamBroadcaster[Any, Any]] = {} | ||
|
|
||
| self._metadata = (("key", key),) if key else () | ||
|
|
||
|
|
@@ -294,10 +309,7 @@ async def _list_microgrid_components_data_batch( | |
| include_states: bool = False, | ||
| include_bounds: bool = False, | ||
| ) -> AsyncIterator[ComponentsDataBatch]: | ||
| """Iterate over the component data batches in the stream. | ||
|
|
||
| Note: This does not yet support aggregating the data. It | ||
| also does not yet support fetching bound and state data. | ||
| """Iterate over the component data batches in the stream using GrpcStreamBroadcaster. | ||
|
|
||
| Args: | ||
| microgrid_components: A list of tuples of microgrid IDs and component IDs. | ||
|
|
@@ -367,21 +379,33 @@ def dt2ts(dt: datetime) -> PBTimestamp: | |
| filter=stream_filter, | ||
| ) | ||
|
|
||
| try: | ||
| stream = cast( | ||
| AsyncIterator[PBReceiveMicrogridComponentsDataStreamResponse], | ||
| self.stub.ReceiveMicrogridComponentsDataStream( | ||
| request, metadata=self._metadata | ||
| ), | ||
| def transform_response( | ||
| response: PBReceiveMicrogridComponentsDataStreamResponse, | ||
| ) -> ComponentsDataBatch: | ||
| return ComponentsDataBatch(response) | ||
|
|
||
| async def stream_method() -> ( | ||
| AsyncIterable[PBReceiveMicrogridComponentsDataStreamResponse] | ||
| ): | ||
| call_iterator = self.stub.ReceiveMicrogridComponentsDataStream( | ||
| request, metadata=self._metadata | ||
| ) | ||
| async for response in stream: | ||
| if not response: | ||
| break | ||
| yield ComponentsDataBatch(response) | ||
| async for response in cast( | ||
| AsyncIterable[PBReceiveMicrogridComponentsDataStreamResponse], | ||
| call_iterator, | ||
| ): | ||
| yield response | ||
|
|
||
| broadcaster = GrpcStreamBroadcaster( | ||
| stream_name="microgrid-components-data-stream", | ||
| stream_method=stream_method, | ||
| transform=transform_response, | ||
| retry_strategy=None, | ||
| ) | ||
|
|
||
| except grpcaio.AioRpcError as e: | ||
| print(f"RPC failed: {e}") | ||
| return | ||
| receiver = broadcaster.new_receiver() | ||
| async for data in receiver: | ||
| yield data | ||
|
|
||
| async def receive_aggregated_data( | ||
| self, | ||
|
|
@@ -393,10 +417,9 @@ async def receive_aggregated_data( | |
| end: datetime | None, | ||
| resampling_period: timedelta, | ||
| ) -> AsyncIterator[MetricSample]: | ||
| """Iterate over aggregated data for a single metric. | ||
| """Iterate over aggregated data for a single metric using GrpcStreamBroadcaster. | ||
|
|
||
| For now this only supports a single metric and aggregation formula. | ||
|
|
||
| Args: | ||
| microgrid_id: The microgrid ID. | ||
| metric: The metric name. | ||
|
|
@@ -442,18 +465,26 @@ def dt2ts(dt: datetime) -> PBTimestamp: | |
| filter=stream_filter, | ||
| ) | ||
|
|
||
| try: | ||
| stream = cast( | ||
| AsyncIterator[PBAggregatedStreamResponse], | ||
| self.stub.ReceiveAggregatedMicrogridComponentsDataStream( | ||
| request, metadata=self._metadata | ||
| ), | ||
| def transform_response(response: PBAggregatedStreamResponse) -> MetricSample: | ||
| return AggregatedMetric(response).sample() | ||
|
|
||
| async def stream_method() -> AsyncIterable[PBAggregatedStreamResponse]: | ||
| call_iterator = self.stub.ReceiveAggregatedMicrogridComponentsDataStream( | ||
| request, metadata=self._metadata | ||
| ) | ||
| async for response in stream: | ||
| if not response: | ||
| break | ||
| yield AggregatedMetric(response).sample() | ||
|
|
||
| except grpcaio.AioRpcError as e: | ||
| print(f"RPC failed: {e}") | ||
| return | ||
|
|
||
| async for response in cast( | ||
| AsyncIterable[PBAggregatedStreamResponse], call_iterator | ||
| ): | ||
| yield response | ||
|
|
||
| broadcaster = GrpcStreamBroadcaster( | ||
| stream_name="aggregated-microgrid-data-stream", | ||
| stream_method=stream_method, | ||
| transform=transform_response, | ||
| retry_strategy=None, | ||
| ) | ||
|
|
||
| receiver = broadcaster.new_receiver() | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same comment about the receiver method as above. |
||
| async for data in receiver: | ||
| yield data | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh, we get a receiver here. We can have two methods, one returning an iterator as we have now, another returning a receiver. That would be useful for you, correct @phillip-wenig-frequenz ?
Can be a subsequent PR though.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Will add it in a follow up PR! (Issue #155)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually you just need a function that returns a receiver, because the receiver is already an iterator.