remove unused code, minor refactorings

This commit is contained in:
ranfdev
2024-11-21 10:53:22 +01:00
parent 76e3ad9ee1
commit a758ffcd6e
6 changed files with 61 additions and 61 deletions

View File

@ -34,6 +34,7 @@ impl RequestInfo {
#[async_trait] #[async_trait]
trait LightHttpClient: Send + Sync { trait LightHttpClient: Send + Sync {
fn get(&self, url: &str) -> RequestBuilder; fn get(&self, url: &str) -> RequestBuilder;
fn post(&self, url: &str) -> RequestBuilder;
async fn execute(&self, request: Request) -> Result<Response>; async fn execute(&self, request: Request) -> Result<Response>;
} }
@ -43,6 +44,10 @@ impl LightHttpClient for Client {
self.get(url) self.get(url)
} }
fn post(&self, url: &str) -> RequestBuilder {
self.post(url)
}
async fn execute(&self, request: Request) -> Result<Response> { async fn execute(&self, request: Request) -> Result<Response> {
Ok(self.execute(request).await?) Ok(self.execute(request).await?)
} }
@ -77,6 +82,10 @@ impl HttpClient {
self.client.get(url) self.client.get(url)
} }
pub fn post(&self, url: &str) -> RequestBuilder {
self.client.post(url)
}
pub async fn execute(&self, request: Request) -> Result<Response> { pub async fn execute(&self, request: Request) -> Result<Response> {
self.request_tracker self.request_tracker
.push(RequestInfo::from_request(&request)) .push(RequestInfo::from_request(&request))
@ -183,6 +192,10 @@ impl LightHttpClient for NullableClient {
Client::new().get(url) Client::new().get(url)
} }
fn post(&self, url: &str) -> RequestBuilder {
Client::new().post(url)
}
async fn execute(&self, request: Request) -> Result<Response> { async fn execute(&self, request: Request) -> Result<Response> {
time::sleep(Duration::from_millis(1)).await; time::sleep(Duration::from_millis(1)).await;
let url = request.url().to_string(); let url = request.url().to_string();

View File

@ -19,10 +19,9 @@ use http_client::HttpClient;
#[derive(Clone)] #[derive(Clone)]
pub struct SharedEnv { pub struct SharedEnv {
db: message_repo::Db, db: message_repo::Db,
proxy: Arc<dyn models::NotificationProxy>, notifier: Arc<dyn models::NotificationProxy>,
http: reqwest::Client, http_client: HttpClient,
nullable_http: HttpClient, network_monitor: Arc<dyn models::NetworkMonitorProxy>,
network: Arc<dyn models::NetworkMonitorProxy>,
credentials: credentials::Credentials, credentials: credentials::Credentials,
} }

View File

@ -114,35 +114,6 @@ pub struct ListenerActor {
} }
impl ListenerActor { impl ListenerActor {
pub fn new(config: ListenerConfig) -> ListenerHandle {
let (event_tx, event_rx) = async_channel::bounded(64);
let (commands_tx, commands_rx) = mpsc::channel(1);
let config_clone = config.clone();
// use a new local set to isolate panics
let local_set = LocalSet::new();
local_set.spawn_local(async move {
let this = Self {
event_tx,
commands_rx: Some(commands_rx),
config: config_clone,
state: ConnectionState::Unitialized,
};
this.run_loop().await;
});
spawn_local(local_set);
ListenerHandle {
events: event_rx,
config,
commands: commands_tx,
listener_actor: Arc::new(RwLock::new(None)),
join_handle: Arc::new(None),
}
}
pub async fn run_loop(mut self) { pub async fn run_loop(mut self) {
let mut commands_rx = self.commands_rx.take().unwrap(); let mut commands_rx = self.commands_rx.take().unwrap();
loop { loop {
@ -280,6 +251,35 @@ pub struct ListenerHandle {
} }
impl ListenerHandle { impl ListenerHandle {
pub fn new(config: ListenerConfig) -> ListenerHandle {
let (event_tx, event_rx) = async_channel::bounded(64);
let (commands_tx, commands_rx) = mpsc::channel(1);
let config_clone = config.clone();
// use a new local set to isolate panics
let local_set = LocalSet::new();
local_set.spawn_local(async move {
let this = ListenerActor {
event_tx,
commands_rx: Some(commands_rx),
config: config_clone,
state: ConnectionState::Unitialized,
};
this.run_loop().await;
});
spawn_local(local_set);
Self {
events: event_rx,
config,
commands: commands_tx,
listener_actor: Arc::new(RwLock::new(None)),
join_handle: Arc::new(None),
}
}
// the response will be sent as an event in self.events // the response will be sent as an event in self.events
pub async fn request_state(&self) -> ConnectionState { pub async fn request_state(&self) -> ConnectionState {
let (tx, rx) = oneshot::channel(); let (tx, rx) = oneshot::channel();
@ -337,7 +337,7 @@ mod tests {
since: 0, since: 0,
}; };
let mut listener = ListenerActor::new(config.clone()); let mut listener = ListenerHandle::new(config.clone());
let items: Vec<_> = listener.events.take(3).collect().await; let items: Vec<_> = listener.events.take(3).collect().await;
dbg!(&items); dbg!(&items);
@ -383,7 +383,7 @@ mod tests {
since: 0, since: 0,
}; };
let mut listener = ListenerActor::new(config.clone()); let mut listener = ListenerHandle::new(config.clone());
let items: Vec<_> = listener.events.take(3).collect().await; let items: Vec<_> = listener.events.take(3).collect().await;
dbg!(&items); dbg!(&items);
@ -414,7 +414,7 @@ mod tests {
since: 0, since: 0,
}; };
let mut listener = ListenerActor::new(config.clone()); let mut listener = ListenerHandle::new(config.clone());
// assert_event_matches!(listener, ListenerEvent::Connected { .. },); // assert_event_matches!(listener, ListenerEvent::Connected { .. },);
}); });

View File

@ -249,8 +249,8 @@ impl NtfyActor {
) -> impl Future<Output = anyhow::Result<SubscriptionHandle>> { ) -> impl Future<Output = anyhow::Result<SubscriptionHandle>> {
let server = sub.server.clone(); let server = sub.server.clone();
let topic = sub.topic.clone(); let topic = sub.topic.clone();
let listener = ListenerActor::new(ListenerConfig { let listener = ListenerHandle::new(ListenerConfig {
http_client: self.env.nullable_http.clone(), http_client: self.env.http_client.clone(),
credentials: self.env.credentials.clone(), credentials: self.env.credentials.clone(),
endpoint: server.clone(), endpoint: server.clone(),
topic: topic.clone(), topic: topic.clone(),
@ -378,7 +378,6 @@ impl NtfyHandle {
} }
pub fn start( pub fn start(
socket_path: std::path::PathBuf,
dbpath: &str, dbpath: &str,
notification_proxy: Arc<dyn models::NotificationProxy>, notification_proxy: Arc<dyn models::NotificationProxy>,
network_proxy: Arc<dyn models::NetworkMonitorProxy>, network_proxy: Arc<dyn models::NetworkMonitorProxy>,
@ -400,10 +399,9 @@ pub fn start(
let env = SharedEnv { let env = SharedEnv {
db: Db::connect(&dbpath).unwrap(), db: Db::connect(&dbpath).unwrap(),
proxy: notification_proxy, notifier: notification_proxy,
http: build_client().unwrap(), http_client: HttpClient::new(build_client().unwrap()),
nullable_http: HttpClient::new(build_client().unwrap()), network_monitor: network_proxy,
network: network_proxy,
credentials, credentials,
}; };
@ -452,9 +450,8 @@ mod tests {
let notification_proxy = Arc::new(NullNotifier::new()); let notification_proxy = Arc::new(NullNotifier::new());
let network_proxy = Arc::new(NullNetworkMonitor::new()); let network_proxy = Arc::new(NullNetworkMonitor::new());
let dbpath = ":memory:"; let dbpath = ":memory:";
let socket_path = std::path::PathBuf::from("/tmp/ntfy.sock");
let handle = start(socket_path, dbpath, notification_proxy, network_proxy).unwrap(); let handle = start(dbpath, notification_proxy, network_proxy).unwrap();
let rt = tokio::runtime::Builder::new_current_thread() let rt = tokio::runtime::Builder::new_current_thread()
.enable_all() .enable_all()

View File

@ -182,7 +182,7 @@ impl SubscriptionActor {
async fn publish(&self, msg: String) -> anyhow::Result<()> { async fn publish(&self, msg: String) -> anyhow::Result<()> {
let server = &self.model.server; let server = &self.model.server;
let creds = self.env.credentials.get(server); let creds = self.env.credentials.get(server);
let mut req = self.env.http.post(server); let mut req = self.env.http_client.post(server);
if let Some(creds) = creds { if let Some(creds) = creds {
req = req.basic_auth(creds.username, Some(creds.password)); req = req.basic_auth(creds.username, Some(creds.password));
} }
@ -212,7 +212,7 @@ impl SubscriptionActor {
if !already_stored { if !already_stored {
// Show notification. If this fails, panic // Show notification. If this fails, panic
if !{ self.model.muted } { if !{ self.model.muted } {
let notifier = self.env.proxy.clone(); let notifier = self.env.notifier.clone();
let title = { msg.notification_title(&self.model) }; let title = { msg.notification_title(&self.model) };

View File

@ -30,7 +30,6 @@ mod imp {
#[derive(Default)] #[derive(Default)]
pub struct NotifyApplication { pub struct NotifyApplication {
pub window: RefCell<WeakRef<NotifyWindow>>, pub window: RefCell<WeakRef<NotifyWindow>>,
pub socket_path: RefCell<PathBuf>,
pub hold_guard: OnceCell<gio::ApplicationHoldGuard>, pub hold_guard: OnceCell<gio::ApplicationHoldGuard>,
pub ntfy: OnceCell<NtfyHandle>, pub ntfy: OnceCell<NtfyHandle>,
} }
@ -59,8 +58,6 @@ mod imp {
// Set icons for shell // Set icons for shell
gtk::Window::set_default_icon_name(APP_ID); gtk::Window::set_default_icon_name(APP_ID);
let socket_path = glib::user_data_dir().join("com.ranfdev.Notify.socket");
self.socket_path.replace(socket_path);
app.setup_css(); app.setup_css();
app.setup_gactions(); app.setup_gactions();
app.setup_accels(); app.setup_accels();
@ -72,7 +69,7 @@ mod imp {
let app = self.obj(); let app = self.obj();
if self.hold_guard.get().is_none() { if self.hold_guard.get().is_none() {
app.ensure_rpc_running(&self.socket_path.borrow()); app.ensure_rpc_running();
} }
glib::MainContext::default().spawn_local(async move { glib::MainContext::default().spawn_local(async move {
@ -109,7 +106,7 @@ impl NotifyApplication {
return; return;
} }
} }
self.build_window(&self.imp().socket_path.borrow()); self.build_window();
self.main_window().present(); self.main_window().present();
} }
@ -254,7 +251,7 @@ impl NotifyApplication {
Ok(()) Ok(())
} }
fn ensure_rpc_running(&self, socket_path: &Path) { fn ensure_rpc_running(&self) {
let dbpath = glib::user_data_dir().join("com.ranfdev.Notify.sqlite"); let dbpath = glib::user_data_dir().join("com.ranfdev.Notify.sqlite");
info!(database_path = %dbpath.display()); info!(database_path = %dbpath.display());
@ -318,13 +315,7 @@ impl NotifyApplication {
} }
} }
let proxies = std::sync::Arc::new(Proxies { notification: s }); let proxies = std::sync::Arc::new(Proxies { notification: s });
let ntfy = ntfy_daemon::start( let ntfy = ntfy_daemon::start(dbpath.to_str().unwrap(), proxies.clone(), proxies).unwrap();
socket_path.to_owned(),
dbpath.to_str().unwrap(),
proxies.clone(),
proxies,
)
.unwrap();
self.imp() self.imp()
.ntfy .ntfy
.set(ntfy) .set(ntfy)
@ -333,7 +324,7 @@ impl NotifyApplication {
self.imp().hold_guard.set(self.hold()).unwrap(); self.imp().hold_guard.set(self.hold()).unwrap();
} }
fn build_window(&self, socket_path: &Path) { fn build_window(&self) {
let ntfy = self.imp().ntfy.get().unwrap(); let ntfy = self.imp().ntfy.get().unwrap();
let window = NotifyWindow::new(self, ntfy.clone()); let window = NotifyWindow::new(self, ntfy.clone());