surrealdb_core/sys/
mod.rs1use futures::lock::Mutex;
2use std::sync::LazyLock;
3use sysinfo::Pid;
4use sysinfo::System;
5
6pub static ENVIRONMENT: LazyLock<Mutex<Environment>> =
9 LazyLock::new(|| Mutex::new(Environment::default()));
10
11pub static INFORMATION: LazyLock<Mutex<Information>> =
14 LazyLock::new(|| Mutex::new(Information::default()));
15
16pub async fn refresh() {
17 let mut environment = ENVIRONMENT.lock().await;
19 environment.refresh();
20 let mut information = INFORMATION.lock().await;
22 information.cpu_usage = environment.cpu_usage();
24 (information.memory_allocated, information.threads) = crate::mem::ALLOC.current_usage();
25 information.memory_usage = environment.memory_usage();
26 information.load_average = environment.load_average();
27 information.physical_cores = environment.physical_cores();
28 information.available_parallelism = environment.available_parallelism();
29}
30
31#[derive(Default)]
33pub struct Information {
34 pub available_parallelism: usize,
35 pub cpu_usage: f32,
36 pub load_average: [f64; 3],
37 pub memory_allocated: usize,
38 pub threads: usize,
39 pub memory_usage: u64,
40 pub physical_cores: usize,
41}
42
43pub struct Environment {
45 sys: System,
46 pid: Pid,
47}
48
49impl Default for Environment {
50 fn default() -> Self {
51 Self {
52 sys: System::new_all(),
53 #[cfg(target_family = "wasm")]
54 pid: 0.into(),
55 #[cfg(not(target_family = "wasm"))]
56 pid: Pid::from(std::process::id() as usize),
57 }
58 }
59}
60
61impl Environment {
62 pub fn load_average(&self) -> [f64; 3] {
67 let load = System::load_average();
68 [load.one, load.five, load.fifteen]
69 }
70
71 pub fn physical_cores(&self) -> usize {
77 self.sys.physical_core_count().unwrap_or_default()
78 }
79
80 pub fn available_parallelism(&self) -> usize {
86 std::thread::available_parallelism().map_or_else(|_| num_cpus::get(), |m| m.get())
87 }
88
89 pub fn cpu_usage(&self) -> f32 {
93 if let Some(process) = self.sys.process(self.pid) {
94 process.cpu_usage()
95 } else {
96 0.0
97 }
98 }
99
100 pub fn memory_usage(&self) -> u64 {
104 if let Some(process) = self.sys.process(self.pid) {
105 process.memory()
106 } else {
107 0
108 }
109 }
110
111 pub fn refresh(&mut self) {
115 self.sys.refresh_processes_specifics(
116 sysinfo::ProcessesToUpdate::Some(&[self.pid]),
117 true,
118 sysinfo::ProcessRefreshKind::nothing().with_memory().with_cpu(),
119 );
120 }
121}