From 3ba46960934c758b4a5ee6ef4f2705a2c4d2ae0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 27 Nov 2026 22:09:19 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20builder=20sees=20live=20sta?= =?UTF-8?q?ts=20per=20user=20(follow=20=E2=86=92=20client=20pushes)=20and?= =?UTF-8?q?=20server=20stats=20on=20Overview;=20usage=20sampler=20is=20its?= =?UTF-8?q?=20own=20crate;=20Save/Confirm=20only=20when=20changed;=20clear?= =?UTF-8?q?er=20toggle;=20aligned=20builder=20actions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.toml | 2 +- crates/client/Cargo.toml | 5 +- crates/client/src/gui.rs | 2 + crates/client/src/gui/builder.rs | 8 +- crates/client/src/gui/builder/overview.rs | 53 +++++++- crates/client/src/gui/builder/server.rs | 2 +- crates/client/src/gui/builder/ui.rs | 1 + crates/client/src/gui/builder/users.rs | 120 +++++++++++++++--- crates/client/src/gui/chat.rs | 82 ++++++++---- crates/client/src/gui/dock.rs | 6 +- crates/client/src/gui/parts.rs | 9 +- crates/client/src/gui/stream_stats.rs | 3 +- crates/client/src/gui/voice_stats.rs | 46 ++++--- crates/client/src/lib.rs | 2 +- crates/client/src/media/decode.rs | 6 +- crates/client/src/share/session.rs | 31 +---- crates/client/src/voice/engine.rs | 9 +- crates/client/src/voice/mod.rs | 9 +- crates/common/src/call.rs | 17 +++ crates/common/src/event.rs | 6 + crates/common/src/lib.rs | 1 + crates/common/src/stats.rs | 112 ++++++++++++++++ crates/server/Cargo.toml | 1 + crates/server/src/call/mod.rs | 4 + crates/server/src/call/stats.rs | 49 +++++++ crates/server/src/hub.rs | 11 ++ crates/server/src/lib.rs | 1 + crates/server/src/network.rs | 27 ++++ crates/server/src/stats.rs | 109 ++++++++++++++++ crates/usage/Cargo.toml | 19 +++ crates/{client/src/usage => usage/src}/drm.rs | 2 +- .../src/usage/mod.rs => usage/src/lib.rs} | 44 +------ .../{client/src/usage => usage/src}/nvidia.rs | 6 +- .../src/usage => usage/src}/threads.rs | 0 .../src/usage => usage/src}/windows.rs | 0 35 files changed, 624 insertions(+), 181 deletions(-) create mode 100644 crates/common/src/stats.rs create mode 100644 crates/server/src/call/stats.rs create mode 100644 crates/server/src/stats.rs create mode 100644 crates/usage/Cargo.toml rename crates/{client/src/usage => usage/src}/drm.rs (99%) rename crates/{client/src/usage/mod.rs => usage/src/lib.rs} (84%) rename crates/{client/src/usage => usage/src}/nvidia.rs (96%) rename crates/{client/src/usage => usage/src}/threads.rs (100%) rename crates/{client/src/usage => usage/src}/windows.rs (100%) diff --git a/Cargo.toml b/Cargo.toml index 2e1bc79..d387b12 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["crates/client", "crates/common", "crates/pixel", "crates/spectrum", "crates/server"] +members = ["crates/client", "crates/common", "crates/pixel", "crates/spectrum", "crates/server", "crates/usage"] [profile.dev] debug = "line-tables-only" diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index 1754f89..527c51e 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -4,6 +4,7 @@ version = "0.1.0" edition = "2024" [dependencies] +usage = { path = "../usage" } common.workspace = true pixel.workspace = true spectrum.workspace = true @@ -37,7 +38,6 @@ sysinfo = { version = "0.40.4", default-features = false, features = ["system"] [target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies] nokhwa = { version = "0.10.11", default-features = false, features = ["input-native"] } -nvml-wrapper = "0.13.0" [target.'cfg(target_os = "linux")'.dependencies] pipewire = { version = "0.10.1", features = ["v0_3_49"] } @@ -47,9 +47,6 @@ ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "sc [target.'cfg(target_os = "windows")'.dependencies] wasapi = "0.27.0" windows-capture = "2.0.1" -wmi = "0.18.4" -winreg = "0.56.0" -serde = { version = "1.0.229", features = ["derive"] } [target.'cfg(target_os = "macos")'.dependencies] coreaudio-rs = "0.14.2" diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index 6725f58..78ee5c5 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -886,6 +886,8 @@ impl Yumush { Event::ShareStopped { user_id, kind, .. } if self.is_watching(*user_id, *kind) => { self.close_viewer(cx) } + Event::StatsWanted(true) => self.start_stats_push(cx), + Event::StatsWanted(false) => self.chat.stats_task = None, Event::Typing { .. } => { cx.spawn(async move |this, cx| { cx.background_executor().timer(chat::TYPING_TTL).await; diff --git a/crates/client/src/gui/builder.rs b/crates/client/src/gui/builder.rs index 575769f..244b0fe 100644 --- a/crates/client/src/gui/builder.rs +++ b/crates/client/src/gui/builder.rs @@ -117,7 +117,8 @@ impl Yumush { BuilderTab::Log => self.log_body(entity, palette), }; let mut sections = vec![ - page_heading(title, self.tab_actions(tab, entity, palette), palette).into_any_element(), + page_heading(title, self.tab_actions(tab, entity, palette, cx), palette) + .into_any_element(), ]; sections.extend(body); @@ -162,6 +163,7 @@ impl Yumush { tab: BuilderTab, entity: &Entity, palette: Palette, + cx: &App, ) -> Vec { match tab { BuilderTab::Voice => vec![ @@ -175,7 +177,7 @@ impl Yumush { ) .into_any_element(), ], - BuilderTab::Server => vec![ + BuilderTab::Server if self.server_form(cx) != self.server => vec![ accent_button( "save_server", "Save", @@ -281,7 +283,7 @@ impl Yumush { .is_some_and(|me| permission::is_builder(me.role)) } - pub(super) fn load_builder(&self, window: &mut Window, cx: &mut Context) { + pub(super) fn load_builder(&mut self, window: &mut Window, cx: &mut Context) { self.load_open_reports(window, cx); match self.chat.builder_tab { BuilderTab::Overview => self.load_overview(window, cx), diff --git a/crates/client/src/gui/builder/overview.rs b/crates/client/src/gui/builder/overview.rs index 9bb0e9e..b36dcf4 100644 --- a/crates/client/src/gui/builder/overview.rs +++ b/crates/client/src/gui/builder/overview.rs @@ -1,21 +1,26 @@ use crate::net::Fail; use common::{ - call::{GetDailyStats, GetOverview}, + call::{GetDailyStats, GetOverview, GetServerStats}, model::DayStat, time::DAY_MILLIS, }; use gpui_kit::{Context, Div, IntoElement, ParentElement, Styled, Window, div, px}; use jiff::Timestamp; +use std::time::Duration; use super::ui::{card, card_header, stat_tile}; use crate::gui::{ - DAY, Palette, Yumush, storage, + DAY, Palette, Yumush, + builder::BuilderTab, + chat::View, + storage, style::{radius, size, space, text}, - text, + text, voice_stats, }; const CHART_HEIGHT: f32 = 80.; const PANEL_HEIGHT: f32 = 140.; +const SERVER_STATS_TICK: Duration = Duration::from_secs(1); fn day_label(day: u64) -> String { Timestamp::from_millisecond((day * DAY_MILLIS) as i64) @@ -119,7 +124,36 @@ fn bar_chart( } impl Yumush { - pub(super) fn load_overview(&self, window: &mut Window, cx: &mut Context) { + fn watch_server_stats(&mut self, cx: &mut Context) { + if self.chat.server_stats_task.is_some() { + return; + } + let network = self.network.clone(); + self.chat.server_stats_task = Some(cx.spawn(async move |this, cx| { + loop { + let open = this + .update(cx, |yumush, _| { + yumush.chat.view == View::Builder + && yumush.chat.builder_tab == BuilderTab::Overview + }) + .unwrap_or(false); + if !open { + let _ = this.update(cx, |yumush, _| yumush.chat.server_stats_task = None); + break; + } + if let Ok(stats) = network.call(GetServerStats).await { + let _ = this.update(cx, |yumush, cx| { + yumush.chat.server_stats = Some(stats); + cx.notify(); + }); + } + cx.background_executor().timer(SERVER_STATS_TICK).await; + } + })); + } + + pub(super) fn load_overview(&mut self, window: &mut Window, cx: &mut Context) { + self.watch_server_stats(cx); self.fetch_builder( window, cx, @@ -177,6 +211,17 @@ impl Yumush { palette, )), ); + if let Some(stats) = &self.chat.server_stats { + rows.push( + card(palette) + .child(card_header("Server", Vec::new(), palette)) + .child(div().p(px(space::LG)).child(voice_stats::stats_panel( + stats, + &|id| self.chat.name_of(id), + palette, + ))), + ); + } rows } diff --git a/crates/client/src/gui/builder/server.rs b/crates/client/src/gui/builder/server.rs index 6a49478..88a08cb 100644 --- a/crates/client/src/gui/builder/server.rs +++ b/crates/client/src/gui/builder/server.rs @@ -100,7 +100,7 @@ impl Yumush { ); } - fn server_form(&self, cx: &App) -> Option { + pub(super) fn server_form(&self, cx: &App) -> Option { let chat = &self.chat; Some(ServerSettings { name: input_text(&chat.server_name, cx), diff --git a/crates/client/src/gui/builder/ui.rs b/crates/client/src/gui/builder/ui.rs index 6a0142d..2789a91 100644 --- a/crates/client/src/gui/builder/ui.rs +++ b/crates/client/src/gui/builder/ui.rs @@ -80,6 +80,7 @@ pub(super) fn action_button( clickable(id, palette, action) .tip(tip) .h(px(size::CONTROL_SM)) + .min_w(px(size::THUMB)) .px(px(space::MD)) .flex() .items_center() diff --git a/crates/client/src/gui/builder/users.rs b/crates/client/src/gui/builder/users.rs index 54abd48..0e6109e 100644 --- a/crates/client/src/gui/builder/users.rs +++ b/crates/client/src/gui/builder/users.rs @@ -3,11 +3,13 @@ use std::future::Future; use common::{ call::{ - BanUser, ClearProfile, CreateUser, DeleteUser, ListSessions, PurgeUser, RenameUser, - ResetPassword, RevokeSession, RevokeSessions, SetRole, SuspendUser, TimeoutUser, + BanUser, ClearProfile, CreateUser, DeleteUser, FollowStats, ListSessions, PurgeUser, + RenameUser, ResetPassword, RevokeSession, RevokeSessions, SetRole, SuspendUser, + TimeoutUser, }, model::{Account, BanScope, Role, SessionInfo, User}, permission, + stats::Stats, time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms}, }; use gpui_kit::{ @@ -193,6 +195,28 @@ impl Yumush { }); } + pub(super) fn toggle_builder_stats(&mut self, user_id: Id, cx: &mut Context) { + let target = match self.chat.followed { + Some((id, _)) if id == user_id => None, + _ => Some(user_id), + }; + self.chat.followed = target.map(|id| (id, Stats::default())); + let network = self.network.clone(); + cx.spawn(async move |this, cx| { + let latest = network.call(FollowStats { user_id: target }).await; + let _ = this.update(cx, |yumush, cx| { + if let (Ok(Some(stats)), Some(followed)) = (latest, yumush.chat.followed.as_mut()) + && Some(followed.0) == target + { + followed.1 = stats; + } + cx.notify(); + }); + }) + .detach(); + cx.notify(); + } + pub(super) fn toggle_builder_password(&mut self, user_id: Id, cx: &mut Context) { if self.chat.pending_builder_password == Some(user_id) { self.chat.pending_builder_password = None; @@ -238,6 +262,9 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { + if let Some((followed, _)) = self.chat.followed { + self.toggle_builder_stats(followed, cx); + } if self .chat .builder_sessions @@ -417,7 +444,7 @@ impl Yumush { .to_lowercase() .contains(query.as_str()) }) - .map(|account| self.builder_row(account, me, entity, palette)) + .map(|account| self.builder_row(account, me, entity, palette, cx)) .collect(), None => Vec::new(), }; @@ -608,7 +635,16 @@ impl Yumush { user_id: Id, entity: &Entity, palette: Palette, + cx: &App, ) -> Div { + let value = self.chat.builder_rename.read(cx).text().to_string(); + let current = self + .chat + .builder_users + .iter() + .find(|account| account.user.id == user_id) + .map_or("", |account| account.user.username.as_str()); + let ready = !value.is_empty() && value != current; div() .h(px(size::ROW)) .px(px(space::MD)) @@ -621,14 +657,16 @@ impl Yumush { .min_w_0() .child(field(palette, &self.chat.builder_rename)), ) - .child(plain_button( - format!("confirm_rename_{user_id}"), - "Confirm", - palette, - entity_action(entity, |yumush, window, cx| { - yumush.rename_builder_user(window, cx) - }), - )) + .when(ready, |row| { + row.child(plain_button( + format!("confirm_rename_{user_id}"), + "Confirm", + palette, + entity_action(entity, |yumush, window, cx| { + yumush.rename_builder_user(window, cx) + }), + )) + }) } pub(super) fn builder_password_row( @@ -636,7 +674,10 @@ impl Yumush { user_id: Id, entity: &Entity, palette: Palette, + cx: &App, ) -> Div { + let value = self.chat.builder_password.read(cx).text().to_string(); + let ready = !value.is_empty(); div() .h(px(size::ROW)) .px(px(space::MD)) @@ -649,14 +690,16 @@ impl Yumush { .min_w_0() .child(field(palette, &self.chat.builder_password)), ) - .child(plain_button( - format!("confirm_password_{user_id}"), - "Confirm", - palette, - entity_action(entity, |yumush, window, cx| { - yumush.reset_builder_password(window, cx) - }), - )) + .when(ready, |row| { + row.child(plain_button( + format!("confirm_password_{user_id}"), + "Confirm", + palette, + entity_action(entity, |yumush, window, cx| { + yumush.reset_builder_password(window, cx) + }), + )) + }) } pub(super) fn builder_row( @@ -665,6 +708,7 @@ impl Yumush { me: &User, entity: &Entity, palette: Palette, + cx: &App, ) -> Div { let user = &account.user; let is_self = user.id == me.id; @@ -754,6 +798,29 @@ impl Yumush { }), ); + let stats_id = user.id; + let stats_open = self + .chat + .followed + .as_ref() + .filter(|(id, _)| *id == user.id) + .map(|(_, stats)| stats); + let stats_button = action_button( + format!("stats_user_{}", user.id), + IconName::Activity, + "Stats", + "Live connection and machine stats", + if stats_open.is_some() { + palette.text + } else { + tone + }, + palette, + entity_action(entity, move |yumush, _, cx| { + yumush.toggle_builder_stats(stats_id, cx) + }), + ); + let password_button = action_button( format!("password_user_{}", user.id), IconName::KeyRound, @@ -933,6 +1000,7 @@ impl Yumush { manage.then(|| rename_button.into_any_element()), manage.then(|| password_button.into_any_element()), can_role.then(|| role_button.into_any_element()), + Some(stats_button.into_any_element()), ]; let moderation_actions = [ manage.then(|| timeout_button.into_any_element()), @@ -968,9 +1036,11 @@ impl Yumush { account_actions.into_iter().flatten().collect(), )) .children( - password_open.then(|| self.builder_password_row(user.id, entity, palette)), + password_open.then(|| self.builder_password_row(user.id, entity, palette, cx)), + ) + .children( + rename_open.then(|| self.builder_rename_row(user.id, entity, palette, cx)), ) - .children(rename_open.then(|| self.builder_rename_row(user.id, entity, palette))) .children(action_group( "Moderation", palette, @@ -984,6 +1054,14 @@ impl Yumush { danger_actions.into_iter().flatten().collect(), )) .children(action_group("Sessions", palette, sessions)) + .children(stats_open.map(|stats| { + super::super::voice_stats::stats_panel( + stats, + &|id| self.chat.name_of(id), + palette, + ) + .pt(px(space::MD)) + })) }); div().flex().flex_col().child(row).children(panel) diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index d5aeeb2..8fa65bc 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -32,12 +32,11 @@ use crate::gui::{ use crate::net::Levels; use crate::settings::VOLUME; use crate::share::session::ShareSample; -use crate::voice::VoiceSample; use common::{ call::{ CreateCommunity, DeclineCall, DeleteMessage, GetUser, LeaveCommunity, ListBans, ListCommunities, ListMembers, ListMessages, ListPins, ListUnreads, ListVoiceParticipants, - SearchCommunity, WatchCommunity, + PushStats, SearchCommunity, WatchCommunity, }, constant::MESSAGE_PAGE_LIMIT, event::Event, @@ -261,13 +260,14 @@ pub struct Chat { pub(super) server_muted: HashSet, pub(super) builder_voice_rooms: Vec, pub(super) voice_task: Option>, + pub(super) stats_task: Option>, + pub(super) server_stats: Option, + pub(super) server_stats_task: Option>, pub(super) user_volume: Option, - pub(super) voice_samples: VecDeque, - pub(super) traffic: VecDeque<(f32, f32)>, - pub(super) share_sample: ShareSample, + pub(super) stats: common::stats::Stats, + pub(super) followed: Option<(Id, common::stats::Stats)>, pub(super) share_loss: HashMap<(Id, Kind), VecDeque>, - pub(super) stats: Option, - pub(super) usage: Option, + pub(super) stats_at: Option, pub(super) usage_monitor: crate::usage::Monitor, pub(super) ringing: HashSet, pub(super) ring_task: Option>, @@ -508,12 +508,13 @@ impl Chat { server_muted: HashSet::new(), builder_voice_rooms: Vec::new(), voice_task: None, - voice_samples: VecDeque::new(), - traffic: VecDeque::new(), - share_sample: ShareSample::default(), + stats_task: None, + server_stats: None, + server_stats_task: None, + stats: common::stats::Stats::default(), + followed: None, share_loss: HashMap::new(), - stats: None, - usage: None, + stats_at: None, usage_monitor: crate::usage::Monitor::default(), ringing: HashSet::new(), ring_task: None, @@ -560,6 +561,11 @@ impl Chat { } } + pub fn name_of(&self, user_id: Id) -> String { + self.author(user_id) + .map_or_else(|| user_id.to_string(), |user| user.username.clone()) + } + pub fn slow_seconds(&self) -> Option { let remaining = self.slowed_until?.saturating_sub(common::time::now_ms()); (remaining > 0).then(|| remaining.div_ceil(1000)) @@ -706,6 +712,12 @@ impl Chat { shares.retain(|share| share.user_id != user_id || share.kind != kind); } } + Event::StatsWanted(_) => {} + Event::StatsOf { user_id, stats } => { + if let Some(followed) = self.followed.as_mut().filter(|(id, _)| *id == user_id) { + followed.1 = stats; + } + } Event::ReportCreated | Event::SettingsUpdated(_) => {} } } @@ -1185,9 +1197,9 @@ impl Chat { self.voice_state = VoiceState::Off; self.waves.clear(); self.voice_task = None; - self.voice_samples.clear(); - self.traffic.clear(); - self.share_sample = ShareSample::default(); + self.stats.voice.clear(); + self.stats.traffic.clear(); + self.stats.share = ShareSample::default(); self.share_loss.clear(); } @@ -1235,7 +1247,7 @@ impl Chat { history.pop_front(); } } - self.share_sample = sample; + self.stats.share = sample; } } @@ -1323,13 +1335,13 @@ impl RenderOnce for MembersTrigger { impl Yumush { pub(super) fn toggle_stats(&mut self, at: StatsAt) { - self.chat.stats = (self.chat.stats != Some(at)).then_some(at); + self.chat.stats_at = (self.chat.stats_at != Some(at)).then_some(at); self.refresh_usage(); } - fn refresh_usage(&mut self) { + pub(super) fn refresh_usage(&mut self) { if let Some(usage) = self.chat.usage_monitor.latest() { - self.chat.usage = Some(usage); + self.chat.stats.usage = Some(usage); } } @@ -1403,7 +1415,7 @@ impl Yumush { fn stats_sheet(&self, palette: Palette) -> Option { let at = self .chat - .stats + .stats_at .filter(|_| self.chat.voice_community().is_some())?; Some( div() @@ -1423,7 +1435,11 @@ impl Yumush { .border_color(palette.border) .bg(palette.tokens.raise()) .shadow_lg() - .child(voice_stats::stats_panel(&self.chat, palette)), + .child(voice_stats::stats_panel( + &self.chat.stats, + &|id| self.chat.name_of(id), + palette, + )), ) } @@ -2319,6 +2335,22 @@ impl Yumush { cx.notify(); } + pub(super) fn start_stats_push(&mut self, cx: &mut Context) { + let network = self.network.clone(); + self.chat.stats_task = Some(cx.spawn(async move |this, cx| { + loop { + let Ok(stats) = this.update(cx, |yumush, _| { + yumush.refresh_usage(); + yumush.chat.stats.clone() + }) else { + break; + }; + let _ = network.call(PushStats { stats }).await; + cx.background_executor().timer(VOICE_SAMPLE_INTERVAL).await; + } + })); + } + fn start_voice_poll(&mut self, cx: &mut Context) { let network = self.network.clone(); @@ -2350,14 +2382,14 @@ impl Yumush { .iter() .map(|(_, _, stats)| stats.kbps as f32) .sum::(); - let traffic = &mut yumush.chat.traffic; + let traffic = &mut yumush.chat.stats.traffic; traffic.push_back((up, down)); while traffic.len() > SAMPLE_HISTORY { traffic.pop_front(); } } if let Some(sample) = sample { - let samples = &mut yumush.chat.voice_samples; + let samples = &mut yumush.chat.stats.voice; tracing::debug!( target: "metrics", up = sample.traffic.up_kbps, @@ -2376,7 +2408,7 @@ impl Yumush { yumush.chat.record_share(share); cx.notify(); } - if due && yumush.chat.stats.is_some() { + if due && yumush.chat.stats_at.is_some() { yumush.refresh_usage(); } yumush.update_waves(levels, cx); @@ -2703,7 +2735,7 @@ impl Yumush { .child(stats_button( entity, palette, - self.chat.stats == Some(StatsAt::Header), + self.chat.stats_at == Some(StatsAt::Header), )) })), ) diff --git a/crates/client/src/gui/dock.rs b/crates/client/src/gui/dock.rs index cc15b07..5d78647 100644 --- a/crates/client/src/gui/dock.rs +++ b/crates/client/src/gui/dock.rs @@ -28,7 +28,7 @@ impl Yumush { let user = self.user.as_ref()?; let me = user.id; let t = Tokens::of(cx); - let frayed = voice_stats::quality(&self.chat.voice_samples) == Some(Quality::Poor); + let frayed = voice_stats::quality(&self.chat.stats.voice) == Some(Quality::Poor); let voice = if frayed { Voice::Frayed } else if !muted && self.chat.waves.speaking.contains(&me) { @@ -40,12 +40,12 @@ impl Yumush { name: user.username.clone().into(), bands: self.chat.waves.voice(me).cloned(), voice, - ping: self.chat.voice_samples.back().map(|sample| sample.ping_ms), + ping: self.chat.stats.voice.back().map(|sample| sample.ping_ms), muted, deafened, camera: self.network.share_source(Kind::Camera).is_some(), screen: self.network.share_source(Kind::Screen).is_some(), - stats: self.chat.stats == Some(super::chat::StatsAt::Dock), + stats: self.chat.stats_at == Some(super::chat::StatsAt::Dock), }; let go_id = community.id; let actions = CallActions { diff --git a/crates/client/src/gui/parts.rs b/crates/client/src/gui/parts.rs index 816eb7f..da0ea9b 100644 --- a/crates/client/src/gui/parts.rs +++ b/crates/client/src/gui/parts.rs @@ -147,10 +147,11 @@ pub fn toggle( t: Tokens, flip: impl Fn(&mut Window, &mut App) + 'static, ) -> Stateful
{ - let (bar, knob, left) = if on { - (t.hue(super::style::my_hue()), t.paper(), 20.) + let hue = t.hue(super::style::my_hue()); + let (bar, knob, ring, left) = if on { + (hue, hue, hue, 20.) } else { - (t.faint(), t.faint(), 0.) + (t.off(), t.ground(), t.faint(), 0.) }; div() .id(id) @@ -175,6 +176,8 @@ pub fn toggle( .left(px(left)) .size(px(10.)) .rounded_full() + .border(px(stroke::LINE)) + .border_color(ring) .bg(knob), ) } diff --git a/crates/client/src/gui/stream_stats.rs b/crates/client/src/gui/stream_stats.rs index 5e304be..eb58c95 100644 --- a/crates/client/src/gui/stream_stats.rs +++ b/crates/client/src/gui/stream_stats.rs @@ -12,7 +12,8 @@ use crate::share::session::WatchStats; pub(super) fn watch_stats(yumush: &Yumush, user_id: Id, kind: Kind) -> Option<&WatchStats> { yumush .chat - .share_sample + .stats + .share .watching .iter() .find(|(id, sent, _)| *id == user_id && *sent == kind) diff --git a/crates/client/src/gui/voice_stats.rs b/crates/client/src/gui/voice_stats.rs index 0c4e3a0..324a0d3 100644 --- a/crates/client/src/gui/voice_stats.rs +++ b/crates/client/src/gui/voice_stats.rs @@ -4,11 +4,13 @@ use common::{ model::Id, share::{Kind, Layer}, }; -use gpui_kit::{AnyElement, Div, FontWeight, Hsla, IntoElement, ParentElement, Styled, div, px}; +use gpui_kit::{ + AnyElement, Div, FontWeight, Hsla, IntoElement, ParentElement, Styled, div, + prelude::FluentBuilder as _, px, +}; use super::{ Palette, - chat::Chat, parts::{Fill, Ink, Text, band, grow, spark, stack, track, words}, style::{Tokens, size, space}, }; @@ -16,6 +18,7 @@ use crate::media::decode::Engine; use crate::share::session::{LayerStats, WatchStats}; use crate::usage::Usage; use crate::voice::VoiceSample; +use common::stats::Stats; pub const SAMPLE_HISTORY: usize = 60; const LABEL_W: f32 = size::ROW * 2.; @@ -68,24 +71,28 @@ pub fn quality(samples: &VecDeque) -> Option { samples.back().map(Quality::of) } -pub fn stats_panel(chat: &Chat, palette: Palette) -> Div { +pub fn stats_panel(stats: &Stats, name: &dyn Fn(Id) -> String, palette: Palette) -> Div { let t = palette.tokens; - let share = &chat.share_sample; + let share = &stats.share; band(space::XXL) .items_start() .flex_wrap() .child( stack(space::XL) .w(px(COLUMN_W)) - .child(connection(chat, t)) - .child(traffic(chat, t)) - .children(chat.usage.as_ref().map(|usage| machine(usage, t))), + .when(!stats.voice.is_empty(), |column| { + column.child(connection(stats, t)) + }) + .when(!stats.traffic.is_empty(), |column| { + column.child(traffic(stats, t)) + }) + .children(stats.usage.as_ref().map(|usage| machine(usage, t))), ) .child( stack(space::XL) .w(px(COLUMN_W)) .children(sending(&share.sending, t)) - .children(watching(&share.watching, chat, t)), + .children(watching(&share.watching, name, t)), ) } @@ -138,8 +145,8 @@ pub(super) fn number(value: String, name: &'static str, bad: bool, t: Tokens) -> .child(words(name, Text::Caption, Ink::Faint, t)) } -fn connection(chat: &Chat, t: Tokens) -> Div { - let latest = chat.voice_samples.back(); +fn connection(stats: &Stats, t: Tokens) -> Div { + let latest = stats.voice.back(); let quality = latest.map(Quality::of); let bad = quality == Some(Quality::Poor); let field = |value: Option| value.unwrap_or_else(|| "…".into()); @@ -185,7 +192,8 @@ fn connection(chat: &Chat, t: Tokens) -> Div { ) .child( div().h(px(size::CONTROL_SM)).child(spark( - chat.voice_samples + stats + .voice .iter() .map(|sample| (sample.ping_ms / PING_SCALE).clamp(0., 1.)) .collect(), @@ -195,9 +203,9 @@ fn connection(chat: &Chat, t: Tokens) -> Div { ) } -fn traffic(chat: &Chat, t: Tokens) -> Div { - let up: Vec = chat.traffic.iter().map(|(up, _)| *up).collect(); - let down: Vec = chat.traffic.iter().map(|(_, down)| *down).collect(); +fn traffic(stats: &Stats, t: Tokens) -> Div { + let up: Vec = stats.traffic.iter().map(|(up, _)| *up).collect(); + let down: Vec = stats.traffic.iter().map(|(_, down)| *down).collect(); let max = up.iter().chain(&down).copied().fold(1., f32::max); let line = |values: &[f32], ink: Hsla| { div() @@ -347,7 +355,11 @@ fn sending(sending: &[(Kind, LayerStats)], t: Tokens) -> Vec
{ .collect() } -fn watching(watching: &[(Id, Kind, WatchStats)], chat: &Chat, t: Tokens) -> Option
{ +fn watching( + watching: &[(Id, Kind, WatchStats)], + name: &dyn Fn(Id) -> String, + t: Tokens, +) -> Option
{ if watching.is_empty() { return None; } @@ -374,9 +386,7 @@ fn watching(watching: &[(Id, Kind, WatchStats)], chat: &Chat, t: Tokens) -> Opti t, )) .children(watching.iter().map(|(user_id, kind, stats)| { - let name = chat - .author(*user_id) - .map_or_else(|| user_id.to_string(), |user| user.username.clone()); + let name = name(*user_id); let detail = format!( "{} · {}", kind_word(*kind), diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index 76a0879..9a7de53 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -13,7 +13,7 @@ pub mod net; pub mod settings; pub mod share; pub mod tray; -pub mod usage; +pub use usage; pub mod voice; pub const NAME: &str = "Yumush"; diff --git a/crates/client/src/media/decode.rs b/crates/client/src/media/decode.rs index 200de08..584336b 100644 --- a/crates/client/src/media/decode.rs +++ b/crates/client/src/media/decode.rs @@ -178,11 +178,7 @@ impl Picture { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Engine { - Hardware, - Software, -} +pub use common::stats::Engine; pub enum VideoDecoder { H264(Box), diff --git a/crates/client/src/share/session.rs b/crates/client/src/share/session.rs index 09ce19b..b7003d8 100644 --- a/crates/client/src/share/session.rs +++ b/crates/client/src/share/session.rs @@ -95,36 +95,7 @@ pub enum Tick { Loss(u16), } -pub struct LayerStats { - pub layer: Layer, - pub engine: Engine, - pub kbps: u32, - pub fps: f32, - pub gap_ms: (i64, i64), -} - -#[derive(Default)] -pub struct WatchStats { - pub layer: Option, - pub engine: Option, - pub kbps: u32, - pub fps: f32, - pub loss: f32, - pub keyframes: u32, - pub buffer_ms: i64, - pub latency_ms: Option, - pub nacks: u32, - pub shown_fps: f32, - pub dropped: u32, - pub interval_ms: (i64, i64), - pub swing_ms: i64, -} - -#[derive(Default)] -pub struct ShareSample { - pub sending: Vec<(Kind, LayerStats)>, - pub watching: Vec<(Id, Kind, WatchStats)>, -} +pub use common::stats::{LayerStats, ShareSample, WatchStats}; struct Tally { engine: Engine, diff --git a/crates/client/src/voice/engine.rs b/crates/client/src/voice/engine.rs index 669e3ce..f6b290d 100644 --- a/crates/client/src/voice/engine.rs +++ b/crates/client/src/voice/engine.rs @@ -84,14 +84,7 @@ struct Speaker { spectrum: Spectrum, } -#[derive(Debug, Clone, Copy, Default)] -pub struct Traffic { - pub jitter_ms: f32, - pub buffer_ms: f32, - pub loss: f32, - pub up_kbps: f32, - pub down_kbps: f32, -} +pub use common::stats::Traffic; impl Speaker { fn new(sequence: u32, now: Instant) -> Self { diff --git a/crates/client/src/voice/mod.rs b/crates/client/src/voice/mod.rs index 78f9926..10c2a9e 100644 --- a/crates/client/src/voice/mod.rs +++ b/crates/client/src/voice/mod.rs @@ -20,7 +20,7 @@ pub mod engine; use crate::settings::VoiceSettings; use audio::{Audio, Choice, Worker}; -use engine::{Engine, SILENT_DB, Traffic}; +use engine::{Engine, SILENT_DB}; const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 2; const PLAYBACK_RING: usize = RING_SAMPLES * PLAYBACK_CHANNELS; @@ -34,12 +34,7 @@ pub const PLAYBACK_CHANNELS: usize = 2; pub type Capture = Arc>>; pub type Playback = Arc>>; -#[derive(Debug, Clone, Copy, Default)] -pub struct VoiceSample { - pub ping_ms: f32, - pub traffic: Traffic, - pub bitrate_kbps: u32, -} +pub use common::stats::VoiceSample; pub struct Voice { engine: Arc>, diff --git a/crates/common/src/call.rs b/crates/common/src/call.rs index 06f1bfa..baa3977 100644 --- a/crates/common/src/call.rs +++ b/crates/common/src/call.rs @@ -11,6 +11,7 @@ use crate::{ Role, ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, }, share::{Codec, Kind, Quality, Share, Source}, + stats::Stats, validate::{ validate_avatar_size, validate_community_name, validate_forward, validate_new_message, validate_password, validate_poll, validate_reaction, validate_reason, @@ -619,6 +620,19 @@ pub struct CreateBackup; #[derive(Debug, Clone, Encode, Decode)] pub struct ListBackups; +#[derive(Debug, Clone, Encode, Decode)] +pub struct FollowStats { + pub user_id: Option, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct GetServerStats; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct PushStats { + pub stats: Stats, +} + #[derive(Debug, Clone, Encode, Decode)] pub struct DeleteBackup { pub name: String, @@ -744,4 +758,7 @@ calls! { CreateBackup: Builder -> BackupInfo; ListBackups: Builder -> Vec; DeleteBackup: Builder -> (); + FollowStats: Builder -> Option; + PushStats: User -> (); + GetServerStats: Builder -> Stats; } diff --git a/crates/common/src/event.rs b/crates/common/src/event.rs index 0ec8cb0..18a4e67 100644 --- a/crates/common/src/event.rs +++ b/crates/common/src/event.rs @@ -5,6 +5,7 @@ use crate::model::{ User, }; use crate::share::{Kind, Layer, Share}; +use crate::stats::Stats; #[derive(Debug, Clone, Encode, Decode)] pub enum Event { @@ -80,6 +81,11 @@ pub enum Event { user_id: Id, kind: Kind, }, + StatsWanted(bool), + StatsOf { + user_id: Id, + stats: Stats, + }, } #[derive(Debug, Clone, Encode, Decode)] diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index b1eb1bd..9a81d2d 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -10,6 +10,7 @@ pub mod open; pub mod permission; pub mod session; pub mod share; +pub mod stats; pub mod time; pub mod transport; pub mod validate; diff --git a/crates/common/src/stats.rs b/crates/common/src/stats.rs new file mode 100644 index 0000000..bcd9681 --- /dev/null +++ b/crates/common/src/stats.rs @@ -0,0 +1,112 @@ +use std::collections::VecDeque; + +use bitcode::{Decode, Encode}; + +use crate::{ + model::Id, + share::{Kind, Layer}, +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] +pub enum Engine { + Hardware, + Software, +} + +#[derive(Debug, Clone, Copy, Default, Encode, Decode)] +pub struct Traffic { + pub jitter_ms: f32, + pub buffer_ms: f32, + pub loss: f32, + pub up_kbps: f32, + pub down_kbps: f32, +} + +#[derive(Debug, Clone, Copy, Default, Encode, Decode)] +pub struct VoiceSample { + pub ping_ms: f32, + pub traffic: Traffic, + pub bitrate_kbps: u32, +} + +#[derive(Debug, Clone, Default, Encode, Decode)] +pub struct Usage { + pub cpu_model: String, + pub machine: f32, + pub total: f32, + pub threads: Option, + pub memory: Memory, + pub gpu: Option, +} + +#[derive(Debug, Clone, Copy, Default, Encode, Decode)] +pub struct Threads { + pub gui: f32, + pub camera: f32, + pub encode: f32, + pub decode: f32, +} + +#[derive(Debug, Clone, Copy, Default, Encode, Decode)] +pub struct Memory { + pub own_mb: u32, + pub used_mb: u32, + pub total_mb: u32, +} + +#[derive(Debug, Clone, Default, Encode, Decode)] +pub struct Gpu { + pub model: String, + pub gfx: f32, + pub video: f32, + pub vram_mb: u32, + pub machine: GpuMachine, +} + +#[derive(Debug, Clone, Copy, Default, Encode, Decode)] +pub struct GpuMachine { + pub gfx: f32, + pub video: f32, + pub vram_used_mb: u32, + pub vram_total_mb: u32, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct LayerStats { + pub layer: Layer, + pub engine: Engine, + pub kbps: u32, + pub fps: f32, + pub gap_ms: (i64, i64), +} + +#[derive(Debug, Clone, Default, Encode, Decode)] +pub struct WatchStats { + pub layer: Option, + pub engine: Option, + pub kbps: u32, + pub fps: f32, + pub loss: f32, + pub keyframes: u32, + pub buffer_ms: i64, + pub latency_ms: Option, + pub nacks: u32, + pub shown_fps: f32, + pub dropped: u32, + pub interval_ms: (i64, i64), + pub swing_ms: i64, +} + +#[derive(Debug, Clone, Default, Encode, Decode)] +pub struct ShareSample { + pub sending: Vec<(Kind, LayerStats)>, + pub watching: Vec<(Id, Kind, WatchStats)>, +} + +#[derive(Debug, Clone, Default, Encode, Decode)] +pub struct Stats { + pub voice: VecDeque, + pub traffic: VecDeque<(f32, f32)>, + pub usage: Option, + pub share: ShareSample, +} diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index 9a1991f..c8c28e4 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -4,6 +4,7 @@ version = "0.1.0" edition = "2024" [dependencies] +usage = { path = "../usage" } common.workspace = true tokio.workspace = true quinn = { workspace = true, features = ["rustls-aws-lc-rs"] } diff --git a/crates/server/src/call/mod.rs b/crates/server/src/call/mod.rs index 286eb75..6408309 100644 --- a/crates/server/src/call/mod.rs +++ b/crates/server/src/call/mod.rs @@ -2,6 +2,7 @@ mod admin; mod community; mod message; mod social; +mod stats; mod user; mod voice; @@ -213,5 +214,8 @@ pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec { Request::CreateBackup(call) => serve(call, cx).await, Request::ListBackups(call) => serve(call, cx).await, Request::DeleteBackup(call) => serve(call, cx).await, + Request::FollowStats(call) => serve(call, cx).await, + Request::PushStats(call) => serve(call, cx).await, + Request::GetServerStats(call) => serve(call, cx).await, } } diff --git a/crates/server/src/call/stats.rs b/crates/server/src/call/stats.rs new file mode 100644 index 0000000..5ee0356 --- /dev/null +++ b/crates/server/src/call/stats.rs @@ -0,0 +1,49 @@ +use common::{ + call::{FollowStats, GetServerStats, PushStats}, + event::Event, + stats::Stats, +}; + +use crate::{ + call::{Cx, Handle, Me}, + error::ServerError, + publish::To, +}; + +impl Handle for FollowStats { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let change = cx.sh.services.stats.follow(cx.client.id, self.user_id); + if let Some(user_id) = change.stopped { + cx.emit(To::User(user_id), Event::StatsWanted(false)); + } + if let Some(user_id) = change.started { + cx.emit(To::User(user_id), Event::StatsWanted(true)); + } + + Ok(change.latest) + } +} + +impl Handle for PushStats { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let user_id = me.user()?.id; + for conn in cx.sh.services.stats.push(user_id, self.stats.clone()) { + cx.emit( + To::Conn(conn), + Event::StatsOf { + user_id, + stats: self.stats.clone(), + }, + ); + } + + Ok(()) + } +} + +impl Handle for GetServerStats { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { + let services = &cx.sh.services; + Ok(services.machine.sample(services.hub.bytes())) + } +} diff --git a/crates/server/src/hub.rs b/crates/server/src/hub.rs index 5ff67cc..4af1483 100644 --- a/crates/server/src/hub.rs +++ b/crates/server/src/hub.rs @@ -146,6 +146,17 @@ impl Hub { .collect() } + pub fn bytes(&self) -> (u64, u64) { + let clients = self.0.lock().unwrap(); + let mut total = (0, 0); + for conn in clients.values().filter_map(|client| client.conn.as_ref()) { + let stats = conn.stats(); + total.0 += stats.udp_tx.bytes; + total.1 += stats.udp_rx.bytes; + } + total + } + pub fn all(&self) -> Vec { self.0.lock().unwrap().keys().copied().collect() } diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index fc3780d..35a701f 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -13,6 +13,7 @@ pub mod rate_limit; pub mod request; pub mod retention; pub mod rooms; +pub mod stats; #[cfg(test)] mod test; diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index fad7844..808449b 100644 --- a/crates/server/src/network.rs +++ b/crates/server/src/network.rs @@ -1,3 +1,5 @@ +use crate::publish::{Broadcast, To}; +use common::event::Event; use std::{path::PathBuf, sync::Arc, sync::atomic::Ordering, time::Duration}; use bytes::Bytes; @@ -26,6 +28,7 @@ use crate::{ rate_limit::RateLimit, request, retention, rooms::Rooms, + stats::{Follows, Machine}, }; const HELLO_DEADLINE: Duration = Duration::from_secs(5); @@ -35,6 +38,8 @@ pub struct Services { pub rooms: Rooms, pub hub: Hub, pub rate_limit: RateLimit, + pub stats: Follows, + pub machine: Machine, } #[derive(Clone)] @@ -145,6 +150,19 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv }; tokio::spawn(write_events(events, send_stream)); publish_presence(&shared, presence).await; + if client + .user_id() + .is_some_and(|user_id| shared.services.stats.is_followed(user_id)) + { + let conn = client.id; + publish::job(&shared, async |_| { + Ok(vec![Broadcast::new( + To::Conn(conn), + Event::StatsWanted(true), + )]) + }) + .await?; + } tokio::spawn(datagram::relay_datagrams( connection.clone(), @@ -163,6 +181,15 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv client.closed.store(true, Ordering::Release); let presence = hub.remove(client.id); + if let Some(user_id) = shared.services.stats.leave(client.id) { + publish::job(&shared, async |_| { + Ok(vec![Broadcast::new( + To::User(user_id), + Event::StatsWanted(false), + )]) + }) + .await?; + } if let Some(me) = &client.me { publish::job(&shared, async |db| { diff --git a/crates/server/src/stats.rs b/crates/server/src/stats.rs new file mode 100644 index 0000000..9d60c16 --- /dev/null +++ b/crates/server/src/stats.rs @@ -0,0 +1,109 @@ +use std::{ + collections::{HashMap, VecDeque}, + sync::{Arc, Mutex}, + time::Instant, +}; + +use common::{model::Id, stats::Stats}; + +use usage::Monitor; + +use crate::hub::ConnId; + +#[derive(Default)] +struct Inner { + following: HashMap, + latest: HashMap, +} + +pub struct Change { + pub stopped: Option, + pub started: Option, + pub latest: Option, +} + +#[derive(Clone, Default)] +pub struct Follows(Arc>); + +impl Follows { + pub fn follow(&self, conn: ConnId, target: Option) -> Change { + let mut inner = self.0.lock().unwrap(); + let old = inner.following.remove(&conn); + if let Some(target) = target { + inner.following.insert(conn, target); + } + let followed = |user: Id| inner.following.values().any(|id| *id == user); + Change { + stopped: old.filter(|old| !followed(*old)), + started: target.filter(|target| { + old != Some(*target) + && inner.following.values().filter(|id| *id == target).count() == 1 + }), + latest: target.and_then(|target| inner.latest.get(&target).cloned()), + } + } + + pub fn leave(&self, conn: ConnId) -> Option { + self.follow(conn, None).stopped + } + + pub fn push(&self, user: Id, stats: Stats) -> Vec { + let mut inner = self.0.lock().unwrap(); + inner.latest.insert(user, stats); + inner + .following + .iter() + .filter(|(_, id)| **id == user) + .map(|(conn, _)| *conn) + .collect() + } + + pub fn is_followed(&self, user: Id) -> bool { + self.0 + .lock() + .unwrap() + .following + .values() + .any(|id| *id == user) + } +} + +const HISTORY: usize = 60; + +#[derive(Default)] +struct Rates { + last: Option<(Instant, u64, u64)>, + history: VecDeque<(f32, f32)>, +} + +#[derive(Clone, Default)] +pub struct Machine { + monitor: Arc, + rates: Arc>, +} + +impl Machine { + pub fn sample(&self, (sent, received): (u64, u64)) -> Stats { + let now = Instant::now(); + let mut rates = self.rates.lock().unwrap(); + if let Some((at, last_sent, last_received)) = rates.last { + let seconds = now.duration_since(at).as_secs_f32().max(f32::EPSILON); + let kbps = + |bytes: u64, last: u64| bytes.saturating_sub(last) as f32 * 8. / 1000. / seconds; + let rate = (kbps(sent, last_sent), kbps(received, last_received)); + rates.history.push_back(rate); + while rates.history.len() > HISTORY { + rates.history.pop_front(); + } + } + rates.last = Some((now, sent, received)); + Stats { + traffic: rates.history.clone(), + usage: self.monitor.latest().map(|usage| usage::Usage { + threads: None, + ..usage + }), + ..Stats::default() + } + } +} diff --git a/crates/usage/Cargo.toml b/crates/usage/Cargo.toml new file mode 100644 index 0000000..d83ff6f --- /dev/null +++ b/crates/usage/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "usage" +version = "0.1.0" +edition = "2024" + +[dependencies] +common.workspace = true +sysinfo = { version = "0.40.4", default-features = false, features = ["system"] } + +[target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies] +nvml-wrapper = "0.13.0" + +[target.'cfg(target_os = "windows")'.dependencies] +wmi = "0.18.4" +winreg = "0.56.0" +serde = { version = "1.0.229", features = ["derive"] } + +[lints] +workspace = true diff --git a/crates/client/src/usage/drm.rs b/crates/usage/src/drm.rs similarity index 99% rename from crates/client/src/usage/drm.rs rename to crates/usage/src/drm.rs index 75699f5..a3ce2f5 100644 --- a/crates/client/src/usage/drm.rs +++ b/crates/usage/src/drm.rs @@ -104,7 +104,7 @@ impl Sampler { }, ); Some(Gpu { - model, + model: model.to_string(), gfx: percent(current.own.gfx, previous.own.gfx, wall), video: percent(current.own.video, previous.own.video, wall), vram_mb: (current.own.vram_kib >> 10) as u32, diff --git a/crates/client/src/usage/mod.rs b/crates/usage/src/lib.rs similarity index 84% rename from crates/client/src/usage/mod.rs rename to crates/usage/src/lib.rs index e03d26a..5f34564 100644 --- a/crates/client/src/usage/mod.rs +++ b/crates/usage/src/lib.rs @@ -21,47 +21,7 @@ mod windows; const INTERVAL: Duration = Duration::from_secs(1); const IDLE_AFTER: Duration = Duration::from_secs(3); -#[derive(Clone, Default)] -pub struct Usage { - pub cpu_model: Arc, - pub machine: f32, - pub total: f32, - pub threads: Option, - pub memory: Memory, - pub gpu: Option, -} - -#[derive(Clone, Copy, Default)] -pub struct Threads { - pub gui: f32, - pub camera: f32, - pub encode: f32, - pub decode: f32, -} - -#[derive(Clone, Copy, Default)] -pub struct Memory { - pub own_mb: u32, - pub used_mb: u32, - pub total_mb: u32, -} - -#[derive(Clone, Default)] -pub struct Gpu { - pub model: Arc, - pub gfx: f32, - pub video: f32, - pub vram_mb: u32, - pub machine: GpuMachine, -} - -#[derive(Clone, Copy, Default)] -pub struct GpuMachine { - pub gfx: f32, - pub video: f32, - pub vram_used_mb: u32, - pub vram_total_mb: u32, -} +pub use common::stats::{Gpu, GpuMachine, Memory, Threads, Usage}; struct Shared { latest: Option, @@ -174,7 +134,7 @@ impl Sampler { #[cfg(not(target_os = "linux"))] let threads = None; Some(Usage { - cpu_model: self.cpu_model.clone(), + cpu_model: self.cpu_model.to_string(), machine: self.system.global_cpu_usage(), total: process.cpu_usage() / self.cores, threads, diff --git a/crates/client/src/usage/nvidia.rs b/crates/usage/src/nvidia.rs similarity index 96% rename from crates/client/src/usage/nvidia.rs rename to crates/usage/src/nvidia.rs index eea35cd..bfcade2 100644 --- a/crates/client/src/usage/nvidia.rs +++ b/crates/usage/src/nvidia.rs @@ -10,7 +10,7 @@ const MIB: u64 = 1024 * 1024; enum State { #[default] Unset, - Ready(Nvml), + Ready(Box), Failed, } @@ -25,7 +25,7 @@ impl Sampler { pub fn sample(&mut self) -> Option { if let State::Unset = self.state { self.state = match Nvml::init() { - Ok(nvml) => State::Ready(nvml), + Ok(nvml) => State::Ready(Box::new(nvml)), Err(_) => State::Failed, }; } @@ -91,7 +91,7 @@ impl Sampler { }) .clone(); return Some(Gpu { - model, + model: model.to_string(), gfx: gfx as f32, video: video as f32, vram_mb, diff --git a/crates/client/src/usage/threads.rs b/crates/usage/src/threads.rs similarity index 100% rename from crates/client/src/usage/threads.rs rename to crates/usage/src/threads.rs diff --git a/crates/client/src/usage/windows.rs b/crates/usage/src/windows.rs similarity index 100% rename from crates/client/src/usage/windows.rs rename to crates/usage/src/windows.rs