torrust_tracker/servers/
registar.rs1use std::collections::HashMap;
4use std::net::SocketAddr;
5use std::sync::Arc;
6
7use derive_more::Constructor;
8use tokio::sync::Mutex;
9use tokio::task::JoinHandle;
10
11pub type ServiceHeathCheckResult = Result<String, String>;
13
14#[derive(Debug, Constructor)]
18pub struct ServiceHealthCheckJob {
19 pub binding: SocketAddr,
20 pub info: String,
21 pub job: JoinHandle<ServiceHeathCheckResult>,
22}
23
24pub type FnSpawnServiceHeathCheck = fn(&SocketAddr) -> ServiceHealthCheckJob;
28
29#[derive(Clone, Debug, Constructor)]
33pub struct ServiceRegistration {
34 binding: SocketAddr,
35 check_fn: FnSpawnServiceHeathCheck,
36}
37
38impl ServiceRegistration {
39 #[must_use]
40 pub fn spawn_check(&self) -> ServiceHealthCheckJob {
41 (self.check_fn)(&self.binding)
42 }
43}
44
45pub type ServiceRegistrationForm = tokio::sync::oneshot::Sender<ServiceRegistration>;
47
48pub type ServiceRegistry = Arc<Mutex<HashMap<SocketAddr, ServiceRegistration>>>;
50
51#[derive(Clone, Debug)]
53pub struct Registar {
54 registry: ServiceRegistry,
55}
56
57#[allow(clippy::derivable_impls)]
58impl Default for Registar {
59 fn default() -> Self {
60 Self {
61 registry: ServiceRegistry::default(),
62 }
63 }
64}
65
66impl Registar {
67 pub fn new(register: ServiceRegistry) -> Self {
68 Self { registry: register }
69 }
70
71 #[must_use]
73 pub fn give_form(&self) -> ServiceRegistrationForm {
74 let (tx, rx) = tokio::sync::oneshot::channel::<ServiceRegistration>();
75 let register = self.clone();
76 tokio::spawn(async move {
77 register.insert(rx).await;
78 });
79 tx
80 }
81
82 async fn insert(&self, rx: tokio::sync::oneshot::Receiver<ServiceRegistration>) {
84 tracing::debug!("Waiting for the started service to send registration data ...");
85
86 let service_registration = rx
87 .await
88 .expect("it should receive the service registration from the started service");
89
90 let mut mutex = self.registry.lock().await;
91
92 mutex.insert(service_registration.binding, service_registration);
93 }
94
95 #[must_use]
97 pub fn entries(&self) -> ServiceRegistry {
98 self.registry.clone()
99 }
100}