use std::{future::Future, net::SocketAddr, pin::Pin};
use crate::core::{CoreResult, ShutdownToken};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServiceInfo {
pub name: String,
pub addr: SocketAddr,
}
impl ServiceInfo {
pub fn new(name: impl Into<String>, addr: SocketAddr) -> Self {
Self {
name: name.into(),
addr,
}
}
}
pub type ServiceFuture<'a> = Pin<Box<dyn Future<Output = CoreResult<()>> + Send + 'a>>;
pub trait Service: Send + Sync + 'static {
fn name(&self) -> &str;
fn start(&self, shutdown: ShutdownToken) -> ServiceFuture<'_>;
fn stop(&self) -> ServiceFuture<'_> {
Box::pin(async { Ok(()) })
}
}
pub struct FnService<F> {
name: String,
start: F,
}
impl<F> FnService<F> {
pub fn new(name: impl Into<String>, start: F) -> Self {
Self {
name: name.into(),
start,
}
}
}
impl<F, Fut> Service for FnService<F>
where
F: Fn(ShutdownToken) -> Fut + Send + Sync + 'static,
Fut: Future<Output = CoreResult<()>> + Send + 'static,
{
fn name(&self) -> &str {
&self.name
}
fn start(&self, shutdown: ShutdownToken) -> ServiceFuture<'_> {
Box::pin((self.start)(shutdown))
}
}