-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmicrogrid_client_actor.rs
More file actions
417 lines (393 loc) · 15.5 KB
/
Copy pathmicrogrid_client_actor.rs
File metadata and controls
417 lines (393 loc) · 15.5 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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
// License: MIT
// Copyright © 2025 Frequenz Energy-as-a-Service GmbH
//! The microgrid client actor that handles communication with the microgrid API.
use crate::client::{
MicrogridApiClient,
instruction::Instruction,
proto::common::microgrid::electrical_components::ElectricalComponentTelemetry,
proto::microgrid::{
ListElectricalComponentConnectionsRequest, ListElectricalComponentsRequest,
ReceiveElectricalComponentTelemetryStreamRequest,
ReceiveElectricalComponentTelemetryStreamResponse,
},
retry_tracker::RetryTracker,
};
use chrono::DateTime;
use futures::{Stream, StreamExt};
use std::collections::HashMap;
use tokio::{
select,
sync::{broadcast, mpsc},
};
use tracing::Instrument as _;
use crate::Error;
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<T> {
client: T,
instructions_rx: mpsc::Receiver<Instruction>,
}
impl<T: MicrogridApiClient> MicrogridClientActor<T> {
pub(super) fn new_from_client(client: T, instructions_rx: mpsc::Receiver<Instruction>) -> Self {
Self {
client,
instructions_rx,
}
}
pub(super) async fn run(mut self) {
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 self.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);
match component_streams.get(&component_id) {
// A subscriber arrived between the stream
// task's no-receivers check and this message;
// the task is gone, so restart the stream for
// the new subscriber.
Some(tx) if tx.receiver_count() > 0 => {
let tx = tx.clone();
start_electrical_component_telemetry_stream(
&mut self.client,
component_id,
tx,
stream_status_tx.clone(),
)
.await;
}
// Drop the cached sender: nothing writes to it
// anymore, so handing out further subscriptions
// on it would never yield data. The next
// subscription starts a fresh stream instead.
_ => {
component_streams.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 self.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<T: MicrogridApiClient>(
client: &mut T,
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: electrical_component_categories
.into_iter()
.map(|c| c as i32)
.collect(),
})
.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"))?;
}
Some(Instruction::AugmentElectricalComponentBounds {
electrical_component_id,
target_metric,
bounds,
request_lifetime,
response_tx,
}) => {
let response = client
.augment_electrical_component_bounds(
crate::client::proto::microgrid::AugmentElectricalComponentBoundsRequest {
electrical_component_id,
target_metric: target_metric as i32,
bounds,
request_lifetime: request_lifetime.and_then(|d| {
let secs = d.num_seconds();
u64::try_from(secs).ok()
}),
},
)
.await
.map_err(|e| {
Error::api_server_error(format!(
"augment_electrical_component_bounds failed: {e}"
))
})
.map(|r| {
r.into_inner().valid_until_time.and_then(|t| {
match DateTime::from_timestamp(t.seconds, t.nanos as u32) {
dt @ Some(_) => dt,
None => {
tracing::error!(
concat!(
"Received invalid valid_until_time in ",
"AugmentElectricalComponentBoundsResponse: {:?}"
),
t
);
None
}
}
})
});
response_tx
.send(response)
.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<T: MicrogridApiClient>(
client: &mut T,
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<T: MicrogridApiClient>(
client: &mut T,
electrical_component_id: u64,
tx: broadcast::Sender<ElectricalComponentTelemetry>,
stream_status_tx: mpsc::Sender<StreamStatus>,
) {
let stream = match client
.receive_electrical_component_telemetry_stream(
ReceiveElectricalComponentTelemetryStreamRequest {
electrical_component_id,
filter: None,
},
)
.await
{
Ok(s) => s.into_inner(),
Err(e) => {
let _ = stream_status_tx
.send(StreamStatus::Failed(electrical_component_id))
.await;
tracing::debug!("Failed to start telemetry stream for {electrical_component_id}: {e}",);
return;
}
};
if let Err(e) = stream_status_tx
.send(StreamStatus::Connected(electrical_component_id))
.await
{
tracing::error!(
"Failed to send stream connected message for {electrical_component_id}: {e}",
);
return;
}
// 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(),
);
}
async fn run_electrical_component_telemetry_stream(
mut stream: impl Stream<
Item = Result<ReceiveElectricalComponentTelemetryStreamResponse, tonic::Status>,
> + Unpin,
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.next().await {
Some(m) => m,
None => {
tracing::error!(
"get_component_data stream failed for {}",
electrical_component_id,
);
break;
}
};
let data = match message {
Ok(ReceiveElectricalComponentTelemetryStreamResponse { telemetry: Some(d) }) => d,
Ok(ReceiveElectricalComponentTelemetryStreamResponse { telemetry: None }) => {
tracing::warn!(
"get_component_data stream returned empty data for {}",
electrical_component_id
);
continue;
}
Err(e) => {
tracing::warn!(
"get_component_data stream ended for {}: {:?}",
electrical_component_id,
e
);
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
);
}
}