use std::sync::Arc;
use parking_lot::RwLock;
use crate::shutdown::{ShutdownReason, ShutdownToken};
use crate::tasks::TaskRegistry;
pub use crate::tasks::TaskSummary;
#[derive(Debug)]
pub(crate) struct HandleState {
pub(crate) name: &'static str,
}
impl HandleState {
pub(crate) fn new(name: &'static str) -> Self {
Self { name }
}
}
#[derive(Clone)]
pub struct ServiceHandle {
shutdown: ShutdownToken,
tasks: TaskRegistry,
state: Arc<RwLock<HandleState>>,
}
impl ServiceHandle {
pub(crate) fn new(
shutdown: ShutdownToken,
tasks: TaskRegistry,
state: Arc<RwLock<HandleState>>,
) -> Self {
Self {
shutdown,
tasks,
state,
}
}
pub fn name(&self) -> &'static str {
self.state.read().name
}
pub fn request_shutdown(&self, reason: ShutdownReason) {
self.shutdown.cancel(reason);
}
pub fn is_running(&self) -> bool {
!self.shutdown.is_cancelled()
}
pub fn shutdown_token(&self) -> &ShutdownToken {
&self.shutdown
}
pub fn tasks(&self) -> Vec<TaskSummary> {
self.tasks.snapshot()
}
}
impl std::fmt::Debug for ServiceHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ServiceHandle")
.field("name", &self.state.read().name)
.field("is_running", &self.is_running())
.field("tasks", &self.tasks.len())
.finish()
}
}