Skip to main content

Mountain/IPC/Common/ServiceInfo/
ServiceRegistry.rs

1#![allow(non_snake_case)]
2
3//! Map of registered services keyed by name + a configurable discovery
4//! cadence. `ShouldDiscover` returns true once the configured interval
5//! has elapsed since the last `MarkDiscovery` (or `Register` /
6//! `Unregister`, both of which stamp the timestamp implicitly).
7
8use std::{
9	collections::HashMap,
10	time::{Duration, Instant},
11};
12
13use crate::IPC::Common::ServiceInfo::ServiceInfo;
14
15#[derive(Debug, Clone)]
16pub struct Struct {
17	pub Services:HashMap<String, ServiceInfo::Struct>,
18
19	pub LastDiscovery:Instant,
20
21	pub DiscoveryInterval:Duration,
22}
23
24impl Struct {
25	pub fn new(DiscoveryInterval:Duration) -> Self {
26		Self { Services:HashMap::new(), LastDiscovery:Instant::now(), DiscoveryInterval }
27	}
28
29	pub fn Register(&mut self, Service:ServiceInfo::Struct) {
30		self.Services.insert(Service.Name.clone(), Service);
31
32		self.LastDiscovery = Instant::now();
33	}
34
35	pub fn Unregister(&mut self, Name:&str) -> Option<ServiceInfo::Struct> {
36		self.Services.remove(Name).map(|Service| {
37			self.LastDiscovery = Instant::now();
38			Service
39		})
40	}
41
42	pub fn Get(&self, Name:&str) -> Option<&ServiceInfo::Struct> { self.Services.get(Name) }
43
44	pub fn GetMut(&mut self, Name:&str) -> Option<&mut ServiceInfo::Struct> { self.Services.get_mut(Name) }
45
46	pub fn ShouldDiscover(&self) -> bool { self.LastDiscovery.elapsed() >= self.DiscoveryInterval }
47
48	pub fn HealthyServices(&self) -> Vec<&ServiceInfo::Struct> {
49		self.Services.values().filter(|S| S.IsHealthy()).collect()
50	}
51
52	pub fn UnhealthyServices(&self) -> Vec<&ServiceInfo::Struct> {
53		self.Services.values().filter(|S| !S.IsHealthy()).collect()
54	}
55
56	pub fn MarkDiscovery(&mut self) { self.LastDiscovery = Instant::now(); }
57}
58
59impl Default for Struct {
60	fn default() -> Self { Self::new(Duration::from_secs(60)) }
61}