forked from frequenz-floss/frequenz-microgrid-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmicrogrid_client_actor.rs
More file actions
358 lines (334 loc) · 12.6 KB
/
microgrid_client_actor.rs
File metadata and controls
358 lines (334 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// License: MIT
// Copyright © 2025 Frequenz Energy-as-a-Service GmbH
//! The microgrid client actor that handles communication with the microgrid API.
use crate::{
client::{instruction::Instruction, retry_tracker::RetryTracker},
proto::microgrid::v1alpha18::{
ListElectricalComponentConnectionsRequest, ListElectricalComponentsRequest,
ReceiveElectricalComponentTelemetryStreamRequest,
ReceiveElectricalComponentTelemetryStreamResponse,
},
};
use std::collections::HashMap;
use tokio::{
select,
sync::{broadcast, mpsc},
};
use tonic::transport::Channel;
use tracing::Instrument as _;
use crate::{
Error,
proto::{
common::v1alpha8::microgrid::electrical_components::ElectricalComponentTelemetry,
microgrid::v1alpha18::microgrid_client::MicrogridClient,
},
};
enum StreamStatus {
Failed(u64),
Connected(u64),
Ended(u64),
}
/// This actor owns the connection to the microgrid API and processes instructions
/// received from any connected `MicrogridClientHandle` instance.
///
/// It allows there to be multiple `MicrogridClientHandle` instances, all
/// sharing the same connection to the microgrid API.
pub(super) struct MicrogridClientActor {
url: String,
instructions_rx: mpsc::Receiver<Instruction>,
}
impl MicrogridClientActor {
pub(super) fn new(url: String, instructions_rx: mpsc::Receiver<Instruction>) -> Self {
Self {
url,
instructions_rx,
}
}
pub(super) async fn run(mut self) {
let mut client = match MicrogridClient::<Channel>::connect(self.url).await {
Ok(t) => t,
Err(e) => {
tracing::error!("Could not connect to server: {e}");
return;
}
};
let mut component_streams: HashMap<u64, broadcast::Sender<ElectricalComponentTelemetry>> =
HashMap::new();
let (stream_status_tx, mut stream_status_rx) = mpsc::channel(50);
let mut retry_timer = tokio::time::interval(std::time::Duration::from_secs(1));
retry_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut components_to_retry = HashMap::new();
loop {
select! {
instruction = self.instructions_rx.recv() => {
if let Err(e) = handle_instruction(
&mut client,
&mut component_streams,
instruction,
stream_status_tx.clone(),
).await {
tracing::error!("MicrogridClientActor: Error handling instruction: {e}");
}
}
stream_status = stream_status_rx.recv() => {
match stream_status {
Some(StreamStatus::Failed(component_id)) => {
components_to_retry.entry(component_id).or_insert_with(
RetryTracker::new
).mark_new_failure();
}
Some(StreamStatus::Connected(component_id)) => {
components_to_retry.remove(&component_id);
}
Some(StreamStatus::Ended(component_id)) => {
components_to_retry.remove(&component_id);
}
None => {
tracing::error!("MicrogridClientActor: Stream status channel closed, exiting.");
return;
}
}
}
now = retry_timer.tick() => {
if let Err(e) = handle_retry_timer(
&mut client,
&mut component_streams,
&mut components_to_retry,
stream_status_tx.clone(),
now,
).await {
tracing::error!("MicrogridClientActor: Error handling retry timer: {e}");
}
}
}
}
}
}
/// Handles the instructions received from the `MicrogridClientHandle` instances.
async fn handle_instruction(
client: &mut MicrogridClient<Channel>,
component_streams: &mut HashMap<u64, broadcast::Sender<ElectricalComponentTelemetry>>,
instruction: Option<Instruction>,
stream_status_tx: mpsc::Sender<StreamStatus>,
) -> Result<(), Error> {
match instruction {
Some(Instruction::ReceiveElectricalComponentTelemetryStream {
electrical_component_id,
response_tx,
}) => {
// If a stream for the given component already exists, subscribe to
// it and return.
if let Some(stream) = component_streams.get(&electrical_component_id) {
response_tx
.send(stream.subscribe())
.map_err(|_| Error::internal("failed to send response"))?;
return Ok(());
}
// If a stream for the given electrical component does not exist,
// create a new channel and start a task for streaming telemetry
// from the API service into the channel.
let (tx, rx) = broadcast::channel::<ElectricalComponentTelemetry>(100);
component_streams.insert(electrical_component_id, tx.clone());
start_electrical_component_telemetry_stream(
client,
electrical_component_id,
tx,
stream_status_tx,
)
.await?;
response_tx.send(rx).map_err(|_| {
tracing::error!("failed to send response");
Error::internal("failed to send response")
})?;
}
Some(Instruction::ListElectricalComponents {
response_tx,
electrical_component_ids,
electrical_component_categories,
}) => {
let components = client
.list_electrical_components(ListElectricalComponentsRequest {
electrical_component_ids,
electrical_component_categories,
})
.await
.map_err(|e| Error::connection_failure(format!("list_components failed: {e}")))
.map(|r| r.into_inner().electrical_components);
response_tx
.send(components)
.map_err(|_| Error::internal("failed to send response"))?;
}
Some(Instruction::ListElectricalComponentConnections {
response_tx,
source_electrical_component_ids,
destination_electrical_component_ids,
}) => {
let connections = client
.list_electrical_component_connections(ListElectricalComponentConnectionsRequest {
source_electrical_component_ids,
destination_electrical_component_ids,
})
.await
.map_err(|e| Error::connection_failure(format!("list_connections failed: {e}")))
.map(|r| r.into_inner().electrical_component_connections);
response_tx
.send(connections)
.map_err(|_| Error::internal("failed to send response"))?;
}
None => {}
}
Ok(())
}
/// Handles the retry timer, checking if the data streams for any components
/// need to be retried and restarting their streaming tasks if necessary.
async fn handle_retry_timer(
client: &mut MicrogridClient<Channel>,
component_streams: &mut HashMap<u64, broadcast::Sender<ElectricalComponentTelemetry>>,
components_to_retry: &mut HashMap<u64, RetryTracker>,
stream_status_tx: mpsc::Sender<StreamStatus>,
now: tokio::time::Instant,
) -> Result<(), Error> {
for item in components_to_retry.iter_mut() {
if let Some(retry_time) = item.1.next_retry_time() {
if retry_time > now {
continue;
}
item.1.mark_new_retry();
let (component_id, _) = item;
if let Some(tx) = component_streams.get(component_id).cloned() {
start_electrical_component_telemetry_stream(
client,
*component_id,
tx,
stream_status_tx.clone(),
)
.await?;
} else {
tracing::error!("Component stream not found for retry: {component_id}");
return Err(Error::internal(format!(
"Component stream not found for retry: {component_id}"
)));
}
}
}
Ok(())
}
/// Creates a new data stream for the given component ID and starts a task to
/// fetch data from it in a loop.
async fn start_electrical_component_telemetry_stream(
client: &mut MicrogridClient<Channel>,
electrical_component_id: u64,
tx: broadcast::Sender<ElectricalComponentTelemetry>,
stream_status_tx: mpsc::Sender<StreamStatus>,
) -> Result<(), Error> {
let stream = match client
.receive_electrical_component_telemetry_stream(
ReceiveElectricalComponentTelemetryStreamRequest {
electrical_component_id,
filter: None,
},
)
.await
{
Ok(s) => s.into_inner(),
Err(e) => {
stream_status_tx
.send(StreamStatus::Failed(electrical_component_id))
.await
.map_err(|e| {
Error::connection_failure(format!(
"receive_component_data_stream failed for {electrical_component_id}: {e}",
))
})?;
return Err(Error::connection_failure(format!(
"receive_component_data_stream failed for {electrical_component_id}: {e}",
)));
}
};
stream_status_tx
.send(StreamStatus::Connected(electrical_component_id))
.await
.map_err(|e| {
Error::connection_failure(format!(
"Failed to send stream recovered message for {electrical_component_id}: {e}",
))
})?;
// create a task to fetch data from the stream in a loop and put into a channel.
tokio::spawn(
run_electrical_component_telemetry_stream(
stream,
electrical_component_id,
tx,
stream_status_tx,
)
.in_current_span(),
);
Ok(())
}
async fn run_electrical_component_telemetry_stream(
mut stream: tonic::Streaming<ReceiveElectricalComponentTelemetryStreamResponse>,
electrical_component_id: u64,
tx: broadcast::Sender<ElectricalComponentTelemetry>,
stream_status_tx: mpsc::Sender<StreamStatus>,
) {
loop {
if tx.receiver_count() == 0 {
tracing::debug!(
"Dropping ComponentData stream for component_id:{:?}",
electrical_component_id
);
stream_status_tx
.send(StreamStatus::Ended(electrical_component_id))
.await
.unwrap_or_else(|e| {
tracing::error!(
"Failed to send stream ended message for {:?}: {:?}",
electrical_component_id,
e
);
});
return;
}
let message = match stream.message().await {
Ok(m) => m,
Err(e) => {
tracing::error!(
"get_component_data stream failed for {:?}: {:?}",
electrical_component_id,
e
);
break;
}
};
let data = match message {
Some(ReceiveElectricalComponentTelemetryStreamResponse { telemetry: Some(d) }) => d,
Some(ReceiveElectricalComponentTelemetryStreamResponse { telemetry: None }) => {
tracing::warn!(
"get_component_data stream returned empty data for {}",
electrical_component_id
);
continue;
}
None => {
tracing::warn!(
"get_component_data stream ended for {:?}",
electrical_component_id
);
break;
}
};
if tx.send(data).is_err() {
continue;
};
}
if let Err(e) = stream_status_tx
.send(StreamStatus::Failed(electrical_component_id))
.await
{
tracing::error!(
"Failed to send stream stopped message for {:?}: {:?}",
electrical_component_id,
e
);
}
}