use tokio::sync::oneshot;
use tokio::sync::Mutex;
use crate::ha::ha_connection_state::HAConnectionState;
pub struct HAConnectionStateNotificationRequest {
notification_sender: Mutex<Option<oneshot::Sender<bool>>>,
expect_state: HAConnectionState,
remote_addr: String,
notify_when_shutdown: bool,
}
impl HAConnectionStateNotificationRequest {
pub fn new(
expect_state: HAConnectionState,
remote_addr: &str,
notify_when_shutdown: bool,
) -> (Self, oneshot::Receiver<bool>) {
let (sender, receiver) = oneshot::channel();
(
Self {
notification_sender: Mutex::new(Some(sender)),
expect_state,
remote_addr: remote_addr.to_string(),
notify_when_shutdown,
},
receiver,
)
}
pub fn expect_state(&self) -> HAConnectionState {
self.expect_state
}
pub fn remote_addr(&self) -> &str {
&self.remote_addr
}
pub fn notify_when_shutdown(&self) -> bool {
self.notify_when_shutdown
}
pub async fn complete(&self, result: bool) -> bool {
let mut sender_guard = self.notification_sender.lock().await;
if let Some(sender) = sender_guard.take() {
sender.send(result).is_ok()
} else {
false }
}
pub fn is_completed(&self) -> bool {
self.notification_sender.try_lock().is_ok_and(|guard| guard.is_none())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ha::ha_connection_state::HAConnectionState;
#[tokio::test]
async fn test_notification_request() {
let (request, receiver) =
HAConnectionStateNotificationRequest::new(HAConnectionState::Transfer, "127.0.0.1:9876", true);
assert_eq!(request.expect_state(), HAConnectionState::Transfer);
assert_eq!(request.remote_addr(), "127.0.0.1:9876");
assert!(request.notify_when_shutdown());
assert!(request.complete(true).await);
assert!(receiver.await.unwrap());
assert!(!request.complete(false).await);
}
}