Add ability to listen to node events from the frontend

This commit is contained in:
Sebastian Martinez
2024-09-18 12:25:28 +02:00
parent 797a64b8d7
commit ff6b7aa5dc
7 changed files with 95 additions and 1 deletions
+4
View File
@@ -73,6 +73,10 @@ pub enum Error {
hint: &'static str,
},
/// Tauri error.
#[error(transparent)]
Tauri(#[from] tauri::Error),
/// Storage error.
#[error(transparent)]
Storage(#[from] radicle::storage::Error),
+42
View File
@@ -0,0 +1,42 @@
use std::sync::{atomic::AtomicBool, Arc};
use radicle::{node::Handle, Node, Profile};
use tauri::{AppHandle, Emitter};
use crate::error::Error;
pub async fn subscribe_events(
handle: &AppHandle,
profile: Profile,
existing_events_thread: Arc<AtomicBool>,
) -> Result<(), Error> {
let event_handler = handle.clone();
let node = Node::new(profile.socket());
if !node.is_running() {
event_handler.emit("node_status", "stopped")?;
log::debug!("node: not subscribing to events due to stopped node.");
return Ok(());
};
event_handler.emit("node_status", "running")?;
if existing_events_thread.load(std::sync::atomic::Ordering::SeqCst) {
log::debug!("node: not subscribing to events due to a running subscription.");
return Ok(());
} else {
let join_handle = tauri::async_runtime::spawn(async move {
log::debug!("node: spawned node event subscription.");
while let Ok(events) = node.subscribe(std::time::Duration::MAX) {
existing_events_thread.store(true, std::sync::atomic::Ordering::SeqCst);
for event in events.into_iter().flatten() {
let _ = event_handler.emit("event", event);
}
}
existing_events_thread.store(false, std::sync::atomic::Ordering::SeqCst);
log::debug!("node: event subscription loop has exited.");
});
join_handle.await?;
}
Ok(())
}
+23 -1
View File
@@ -1,8 +1,13 @@
mod commands;
mod error;
mod events;
mod types;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use serde_json::json;
use tauri::Listener;
use tauri::Manager;
use radicle::identity::doc::PayloadId;
@@ -15,6 +20,7 @@ use radicle::storage::git::Repository;
use radicle::storage::{ReadRepository, ReadStorage};
use commands::{auth, cobs, profile, repos};
use events::subscribe_events;
use types::repo::SupportedPayloads;
struct AppState {
@@ -97,7 +103,23 @@ pub fn run() {
}),
}?;
app.manage(AppState { profile });
app.manage(AppState {
profile: profile.clone(),
});
let existing_events_thread: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
let events_handler = app.handle().clone();
app.listen("subscribe_events", move |_| {
let profile = profile.clone();
let existing_events_thread = existing_events_thread.clone();
let events_handler = events_handler.to_owned();
tauri::async_runtime::spawn(async move {
let _result =
subscribe_events(&events_handler, profile, existing_events_thread).await;
});
});
Ok(())
})