Skip to main content

DevelopmentNodeEnvironment_MicrosoftVSCodeDependency_22NodeVersion_Bundle_Clean_Debug_ElectronProfile_EsbuildCompiler_Mountain/IPC/Common/ServiceInfo/
ServiceRegistry.rs

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