refresh on network connection changes

This commit is contained in:
ranfdev
2024-11-21 12:52:06 +01:00
parent 5002772c65
commit e60b61a623
2 changed files with 92 additions and 75 deletions

View File

@ -1,13 +1,13 @@
macro_rules! send_command { macro_rules! send_command {
($self:expr, $command:expr) => {{ ($self:expr, $command:expr) => {{
let (resp_tx, rx) = oneshot::channel(); let (resp_tx, rx) = oneshot::channel();
use anyhow::Context;
$self $self
.command_tx .command_tx
.send($command(resp_tx)) .send($command(resp_tx))
.await .await
.map_err(|_| anyhow::anyhow!("Actor mailbox error"))?; .context("Actor mailbox error")?;
rx.await rx.await.context("Actor response error")?
.map_err(|_| anyhow::anyhow!("Actor response error"))?
}}; }};
} }

View File

@ -3,7 +3,9 @@ use crate::models::NullNetworkMonitor;
use crate::models::NullNotifier; use crate::models::NullNotifier;
use anyhow::{anyhow, Context}; use anyhow::{anyhow, Context};
use futures::future::join_all; use futures::future::join_all;
use futures::StreamExt;
use std::{collections::HashMap, future::Future, sync::Arc}; use std::{collections::HashMap, future::Future, sync::Arc};
use tokio::select;
use tokio::{ use tokio::{
sync::{broadcast, mpsc, oneshot, RwLock}, sync::{broadcast, mpsc, oneshot, RwLock},
task::{spawn_local, LocalSet}, task::{spawn_local, LocalSet},
@ -135,8 +137,19 @@ impl NtfyActor {
} }
pub async fn run(&mut self) { pub async fn run(&mut self) {
while let Some(msg) = self.command_rx.recv().await { let mut network_change_stream = self.env.network_monitor.listen();
match msg { loop {
select! {
Some(_) = network_change_stream.next() => {
let _ = self.refresh_all().await;
},
Some(command) = self.command_rx.recv() => self.handle_command(command).await,
};
}
}
async fn handle_command(&mut self, command: NtfyCommand) {
match command {
NtfyCommand::Subscribe { NtfyCommand::Subscribe {
server, server,
topic, topic,
@ -156,13 +169,7 @@ impl NtfyActor {
} }
NtfyCommand::RefreshAll { resp_tx } => { NtfyCommand::RefreshAll { resp_tx } => {
let mut res = Ok(()); let res = self.refresh_all().await;
for sub in self.listener_handles.read().await.values() {
res = sub.restart().await;
if res.is_err() {
break;
}
}
let _ = resp_tx.send(res); let _ = resp_tx.send(res);
} }
@ -216,7 +223,6 @@ impl NtfyActor {
} }
} }
} }
}
async fn handle_watch_subscribed(&mut self) -> anyhow::Result<()> { async fn handle_watch_subscribed(&mut self) -> anyhow::Result<()> {
let f: Vec<_> = self let f: Vec<_> = self
@ -261,6 +267,17 @@ impl NtfyActor {
Ok(sub) Ok(sub)
} }
} }
async fn refresh_all(&self) -> anyhow::Result<()> {
let mut res = Ok(());
for sub in self.listener_handles.read().await.values() {
res = sub.restart().await;
if res.is_err() {
break;
}
}
res
}
} }
impl NtfyHandle { impl NtfyHandle {