68 lines
1.6 KiB
Rust
68 lines
1.6 KiB
Rust
use once_cell::sync::Lazy;
|
|
use std::{collections::HashMap, sync::Mutex};
|
|
|
|
use crate::{HarmonyProfile, HarmonyTarget};
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub enum HarmonyComposerEvent {
|
|
ProjectInitializationStarted,
|
|
ProjectInitialized,
|
|
ProjectCompilationStarted {
|
|
details: String,
|
|
},
|
|
ProjectCompiled,
|
|
ProjectCompilationFailed {
|
|
details: String,
|
|
},
|
|
DeploymentStarted {
|
|
target: HarmonyTarget,
|
|
profile: HarmonyProfile,
|
|
},
|
|
DeploymentCompleted,
|
|
DeploymentFailed {
|
|
details: String,
|
|
},
|
|
Shutdown,
|
|
}
|
|
|
|
type Subscriber = Box<dyn Fn(&HarmonyComposerEvent) + Send + Sync>;
|
|
|
|
static SUBSCRIBERS: Lazy<Mutex<HashMap<String, Subscriber>>> =
|
|
Lazy::new(|| Mutex::new(HashMap::new()));
|
|
|
|
/// Subscribes a listener to all instrumentation events.
|
|
///
|
|
/// Simply provide a unique name and a closure to run when an event happens.
|
|
///
|
|
/// # Example
|
|
/// ```
|
|
/// instrumentation::subscribe("my_logger", |event| {
|
|
/// println!("Event occurred: {:?}", event);
|
|
/// });
|
|
/// ```
|
|
pub fn subscribe<F>(name: &str, callback: F)
|
|
where
|
|
F: Fn(&HarmonyComposerEvent) + Send + Sync + 'static,
|
|
{
|
|
let mut subs = SUBSCRIBERS.lock().unwrap();
|
|
subs.insert(name.to_string(), Box::new(callback));
|
|
}
|
|
|
|
/// Instruments an event, notifying all subscribers.
|
|
///
|
|
/// This will call every closure that was registered with `subscribe`.
|
|
///
|
|
/// # Example
|
|
/// ```
|
|
/// instrumentation::instrument(HarmonyEvent::HarmonyStarted);
|
|
/// ```
|
|
pub fn instrument(event: HarmonyComposerEvent) -> Result<(), &'static str> {
|
|
let subs = SUBSCRIBERS.lock().unwrap();
|
|
|
|
for callback in subs.values() {
|
|
callback(&event);
|
|
}
|
|
|
|
Ok(())
|
|
}
|