khora_telemetry/service.rs
1// Copyright 2025 eraflo
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Service for managing telemetry data and resource monitoring.
16
17use crate::metrics::registry::MetricsRegistry;
18use crate::monitoring::registry::MonitorRegistry;
19use std::time::{Duration, Instant};
20
21/// Service for managing telemetry data and resource monitoring.
22#[derive(Debug)]
23pub struct TelemetryService {
24 metrics: MetricsRegistry,
25 monitors: MonitorRegistry,
26 last_update: Instant,
27 update_interval: Duration,
28}
29
30impl TelemetryService {
31 /// Creates a new telemetry service with the given update interval.
32 pub fn new(update_interval: Duration) -> Self {
33 Self {
34 metrics: MetricsRegistry::new(),
35 monitors: MonitorRegistry::new(),
36 last_update: Instant::now(),
37 update_interval,
38 }
39 }
40
41 /// Should be called periodically (e.g., once per frame).
42 /// Updates all registered resource monitors if the interval has passed.
43 pub fn tick(&mut self) -> bool {
44 if self.last_update.elapsed() >= self.update_interval {
45 log::trace!("Updating all resource monitors...");
46 self.monitors.update_all();
47 self.last_update = Instant::now();
48 true
49 } else {
50 false
51 }
52 }
53
54 /// Returns a reference to the metrics registry.
55 pub fn metrics_registry(&self) -> &MetricsRegistry {
56 &self.metrics
57 }
58
59 /// Returns a reference to the monitor registry.
60 pub fn monitor_registry(&self) -> &MonitorRegistry {
61 &self.monitors
62 }
63}
64
65impl Default for TelemetryService {
66 fn default() -> Self {
67 Self::new(Duration::from_secs(1))
68 }
69}