mirror of
https://github.com/zhom/donutbrowser.git
synced 2026-07-18 02:17:23 +02:00
refactor: cleanup bandwidth tracking functionality
This commit is contained in:
@@ -1064,6 +1064,19 @@ impl BrowserRunner {
|
||||
profile.id
|
||||
);
|
||||
|
||||
// Stop the proxy associated with this profile first
|
||||
let profile_id_str = profile.id.to_string();
|
||||
if let Err(e) = PROXY_MANAGER
|
||||
.stop_proxy_by_profile_id(app_handle.clone(), &profile_id_str)
|
||||
.await
|
||||
{
|
||||
log::warn!(
|
||||
"Warning: Failed to stop proxy for profile {}: {e}",
|
||||
profile_id_str
|
||||
);
|
||||
}
|
||||
|
||||
let mut process_actually_stopped = false;
|
||||
match self
|
||||
.camoufox_manager
|
||||
.find_camoufox_by_profile(&profile_path_str)
|
||||
@@ -1083,13 +1096,69 @@ impl BrowserRunner {
|
||||
{
|
||||
Ok(stopped) => {
|
||||
if stopped {
|
||||
log::info!(
|
||||
"Successfully stopped Camoufox process: {} (PID: {:?})",
|
||||
camoufox_process.id,
|
||||
camoufox_process.processId
|
||||
);
|
||||
// Verify the process actually died by checking after a short delay
|
||||
if let Some(pid) = camoufox_process.processId {
|
||||
use tokio::time::{sleep, Duration};
|
||||
sleep(Duration::from_millis(500)).await;
|
||||
|
||||
use sysinfo::{Pid, System};
|
||||
let system = System::new_all();
|
||||
process_actually_stopped = system.process(Pid::from(pid as usize)).is_none();
|
||||
|
||||
if process_actually_stopped {
|
||||
log::info!(
|
||||
"Successfully stopped Camoufox process: {} (PID: {:?}) - verified process is dead",
|
||||
camoufox_process.id,
|
||||
pid
|
||||
);
|
||||
} else {
|
||||
log::warn!(
|
||||
"Camoufox stop command returned success but process {} (PID: {:?}) is still running - forcing kill",
|
||||
camoufox_process.id,
|
||||
pid
|
||||
);
|
||||
// Force kill the process
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
use crate::platform_browser;
|
||||
if let Err(e) = platform_browser::macos::kill_browser_process_impl(
|
||||
pid,
|
||||
Some(&profile_path_str),
|
||||
)
|
||||
.await
|
||||
{
|
||||
log::error!("Failed to force kill Camoufox process {}: {}", pid, e);
|
||||
} else {
|
||||
process_actually_stopped = true;
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
use crate::platform_browser;
|
||||
if let Err(e) = platform_browser::linux::kill_browser_process_impl(pid).await
|
||||
{
|
||||
log::error!("Failed to force kill Camoufox process {}: {}", pid, e);
|
||||
} else {
|
||||
process_actually_stopped = true;
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use crate::platform_browser;
|
||||
if let Err(e) =
|
||||
platform_browser::windows::kill_browser_process_impl(pid).await
|
||||
{
|
||||
log::error!("Failed to force kill Camoufox process {}: {}", pid, e);
|
||||
} else {
|
||||
process_actually_stopped = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
process_actually_stopped = true; // No PID to verify, assume stopped
|
||||
}
|
||||
} else {
|
||||
log::info!(
|
||||
log::warn!(
|
||||
"Failed to stop Camoufox process: {} (PID: {:?})",
|
||||
camoufox_process.id,
|
||||
camoufox_process.processId
|
||||
@@ -1097,7 +1166,7 @@ impl BrowserRunner {
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::info!(
|
||||
log::error!(
|
||||
"Error stopping Camoufox process {}: {}",
|
||||
camoufox_process.id,
|
||||
e
|
||||
@@ -1111,9 +1180,10 @@ impl BrowserRunner {
|
||||
profile.name,
|
||||
profile.id
|
||||
);
|
||||
process_actually_stopped = true; // No process found, consider it stopped
|
||||
}
|
||||
Err(e) => {
|
||||
log::info!(
|
||||
log::error!(
|
||||
"Error finding Camoufox process for profile {}: {}",
|
||||
profile.name,
|
||||
e
|
||||
@@ -1121,6 +1191,11 @@ impl BrowserRunner {
|
||||
}
|
||||
}
|
||||
|
||||
// Log warning if process wasn't confirmed stopped, but continue with cleanup
|
||||
if !process_actually_stopped {
|
||||
log::warn!("Camoufox process may still be running, but proceeding with cleanup");
|
||||
}
|
||||
|
||||
// Clear the process ID from the profile
|
||||
let mut updated_profile = profile.clone();
|
||||
updated_profile.process_id = None;
|
||||
|
||||
@@ -664,14 +664,32 @@ impl ProxyManager {
|
||||
&& existing.upstream_port == desired_port;
|
||||
|
||||
if is_same_upstream {
|
||||
// Reuse existing local proxy
|
||||
return Ok(ProxySettings {
|
||||
proxy_type: "http".to_string(),
|
||||
host: "127.0.0.1".to_string(),
|
||||
port: existing.local_port,
|
||||
username: None,
|
||||
password: None,
|
||||
});
|
||||
// Check if profile_id matches - if not, we need to restart to update tracking
|
||||
let profile_id_matches = match (profile_id, &existing.profile_id) {
|
||||
(Some(ref new_id), Some(ref old_id)) => new_id == old_id,
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
if profile_id_matches {
|
||||
// Reuse existing local proxy (profile_id matches)
|
||||
return Ok(ProxySettings {
|
||||
proxy_type: "http".to_string(),
|
||||
host: "127.0.0.1".to_string(),
|
||||
port: existing.local_port,
|
||||
username: None,
|
||||
password: None,
|
||||
});
|
||||
} else {
|
||||
// Profile ID changed - need to restart proxy to update tracking
|
||||
log::info!(
|
||||
"Profile ID changed for proxy {}: {:?} -> {:?}, restarting proxy",
|
||||
existing.id,
|
||||
existing.profile_id,
|
||||
profile_id
|
||||
);
|
||||
needs_restart = true;
|
||||
}
|
||||
} else {
|
||||
// Upstream changed; we must restart the local proxy so that traffic is routed correctly
|
||||
needs_restart = true;
|
||||
@@ -864,6 +882,69 @@ impl ProxyManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Stop the proxy associated with a profile ID
|
||||
pub async fn stop_proxy_by_profile_id(
|
||||
&self,
|
||||
app_handle: tauri::AppHandle,
|
||||
profile_id: &str,
|
||||
) -> Result<(), String> {
|
||||
// Find the proxy ID for this profile
|
||||
let proxy_id = {
|
||||
let map = self.profile_active_proxy_ids.lock().unwrap();
|
||||
map.get(profile_id).cloned()
|
||||
};
|
||||
|
||||
if let Some(proxy_id) = proxy_id {
|
||||
// Find the PID for this proxy
|
||||
let pid = {
|
||||
let proxies = self.active_proxies.lock().unwrap();
|
||||
proxies.iter().find_map(|(pid, proxy)| {
|
||||
if proxy.id == proxy_id {
|
||||
Some(*pid)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
if let Some(pid) = pid {
|
||||
// Use the existing stop_proxy method
|
||||
self.stop_proxy(app_handle, pid).await
|
||||
} else {
|
||||
// Proxy not found in active_proxies, try to stop it directly by ID
|
||||
let proxy_cmd = app_handle
|
||||
.shell()
|
||||
.sidecar("donut-proxy")
|
||||
.map_err(|e| format!("Failed to create sidecar: {e}"))?
|
||||
.arg("proxy")
|
||||
.arg("stop")
|
||||
.arg("--id")
|
||||
.arg(&proxy_id);
|
||||
|
||||
let output = proxy_cmd.output().await.unwrap();
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
log::warn!("Proxy stop error: {stderr}");
|
||||
}
|
||||
|
||||
// Clear profile-to-proxy mapping
|
||||
let mut map = self.profile_active_proxy_ids.lock().unwrap();
|
||||
map.remove(profile_id);
|
||||
|
||||
// Emit event for reactive UI updates
|
||||
if let Err(e) = app_handle.emit("proxies-changed", ()) {
|
||||
log::error!("Failed to emit proxies-changed event: {e}");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
} else {
|
||||
// No proxy found for this profile
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// Update the PID mapping for an existing proxy
|
||||
pub fn update_proxy_pid(&self, old_pid: u32, new_pid: u32) -> Result<(), String> {
|
||||
let mut proxies = self.active_proxies.lock().unwrap();
|
||||
|
||||
@@ -30,9 +30,17 @@ pub async fn start_proxy_process_with_profile(
|
||||
listener.local_addr().unwrap().port()
|
||||
});
|
||||
|
||||
let config = ProxyConfig::new(id.clone(), upstream, Some(local_port)).with_profile_id(profile_id);
|
||||
let config =
|
||||
ProxyConfig::new(id.clone(), upstream, Some(local_port)).with_profile_id(profile_id.clone());
|
||||
save_proxy_config(&config)?;
|
||||
|
||||
// Log profile_id for debugging
|
||||
if let Some(ref pid) = profile_id {
|
||||
log::info!("Saved proxy config {} with profile_id: {}", id, pid);
|
||||
} else {
|
||||
log::info!("Saved proxy config {} without profile_id", id);
|
||||
}
|
||||
|
||||
// Spawn proxy worker process in the background using std::process::Command
|
||||
// This ensures proper process detachment on Unix systems
|
||||
let exe = std::env::current_exe()?;
|
||||
|
||||
@@ -45,12 +45,14 @@ impl<S: AsyncRead + Unpin> AsyncRead for CountingStream<S> {
|
||||
let result = Pin::new(&mut self.inner).poll_read(cx, buf);
|
||||
if let Poll::Ready(Ok(())) = &result {
|
||||
let bytes_read = buf.filled().len() - filled_before;
|
||||
self
|
||||
.bytes_read
|
||||
.fetch_add(bytes_read as u64, Ordering::Relaxed);
|
||||
// Update global tracker
|
||||
if let Some(tracker) = get_traffic_tracker() {
|
||||
tracker.add_bytes_received(bytes_read as u64);
|
||||
if bytes_read > 0 {
|
||||
self
|
||||
.bytes_read
|
||||
.fetch_add(bytes_read as u64, Ordering::Relaxed);
|
||||
// Update global tracker - count as received (data coming into proxy)
|
||||
if let Some(tracker) = get_traffic_tracker() {
|
||||
tracker.add_bytes_received(bytes_read as u64);
|
||||
}
|
||||
}
|
||||
}
|
||||
result
|
||||
@@ -66,7 +68,7 @@ impl<S: AsyncWrite + Unpin> AsyncWrite for CountingStream<S> {
|
||||
let result = Pin::new(&mut self.inner).poll_write(cx, buf);
|
||||
if let Poll::Ready(Ok(n)) = &result {
|
||||
self.bytes_written.fetch_add(*n as u64, Ordering::Relaxed);
|
||||
// Update global tracker
|
||||
// Update global tracker - count as sent (data going out of proxy)
|
||||
if let Some(tracker) = get_traffic_tracker() {
|
||||
tracker.add_bytes_sent(*n as u64);
|
||||
}
|
||||
@@ -522,15 +524,17 @@ pub async fn run_proxy_server(config: ProxyConfig) -> Result<(), Box<dyn std::er
|
||||
};
|
||||
|
||||
log::error!(
|
||||
"Found config: id={}, port={:?}, upstream={}",
|
||||
"Found config: id={}, port={:?}, upstream={}, profile_id={:?}",
|
||||
config.id,
|
||||
config.local_port,
|
||||
config.upstream_url
|
||||
config.upstream_url,
|
||||
config.profile_id
|
||||
);
|
||||
|
||||
log::error!("Starting proxy server for config id: {}", config.id);
|
||||
|
||||
// Initialize traffic tracker with profile ID if available
|
||||
// This can now be called multiple times to update the tracker
|
||||
init_traffic_tracker(config.id.clone(), config.profile_id.clone());
|
||||
log::error!(
|
||||
"Traffic tracker initialized for proxy: {} (profile_id: {:?})",
|
||||
@@ -538,6 +542,17 @@ pub async fn run_proxy_server(config: ProxyConfig) -> Result<(), Box<dyn std::er
|
||||
config.profile_id
|
||||
);
|
||||
|
||||
// Verify tracker was initialized correctly
|
||||
if let Some(tracker) = crate::traffic_stats::get_traffic_tracker() {
|
||||
log::error!(
|
||||
"Tracker verified: proxy_id={}, profile_id={:?}",
|
||||
tracker.proxy_id,
|
||||
tracker.profile_id
|
||||
);
|
||||
} else {
|
||||
log::error!("WARNING: Tracker was not initialized!");
|
||||
}
|
||||
|
||||
// Determine the bind address
|
||||
let bind_addr = SocketAddr::from(([127, 0, 0, 1], config.local_port.unwrap_or(0)));
|
||||
|
||||
|
||||
@@ -150,7 +150,7 @@ impl TrafficStats {
|
||||
}
|
||||
}
|
||||
|
||||
// Add new data point
|
||||
// Add new data point (even if bytes are zero, to ensure chart has continuous data)
|
||||
self.bandwidth_history.push(BandwidthDataPoint {
|
||||
timestamp: now,
|
||||
bytes_sent,
|
||||
@@ -392,6 +392,11 @@ impl LiveTrafficTracker {
|
||||
let mut stats = load_traffic_stats(&self.proxy_id)
|
||||
.unwrap_or_else(|| TrafficStats::new(self.proxy_id.clone(), self.profile_id.clone()));
|
||||
|
||||
// Ensure profile_id is set (in case stats were loaded from disk without it)
|
||||
if stats.profile_id.is_none() && self.profile_id.is_some() {
|
||||
stats.profile_id = self.profile_id.clone();
|
||||
}
|
||||
|
||||
// Update bandwidth history
|
||||
stats.record_bandwidth(bytes_sent, bytes_received);
|
||||
|
||||
@@ -419,17 +424,22 @@ impl LiveTrafficTracker {
|
||||
}
|
||||
|
||||
/// Global traffic tracker that can be accessed from connection handlers
|
||||
pub static TRAFFIC_TRACKER: std::sync::OnceLock<Arc<LiveTrafficTracker>> =
|
||||
std::sync::OnceLock::new();
|
||||
/// Using RwLock to allow reinitialization when proxy config changes
|
||||
static TRAFFIC_TRACKER: std::sync::RwLock<Option<Arc<LiveTrafficTracker>>> =
|
||||
std::sync::RwLock::new(None);
|
||||
|
||||
/// Initialize the global traffic tracker
|
||||
/// This can be called multiple times to update the tracker when proxy config changes
|
||||
pub fn init_traffic_tracker(proxy_id: String, profile_id: Option<String>) {
|
||||
let _ = TRAFFIC_TRACKER.set(Arc::new(LiveTrafficTracker::new(proxy_id, profile_id)));
|
||||
let tracker = Arc::new(LiveTrafficTracker::new(proxy_id, profile_id));
|
||||
if let Ok(mut guard) = TRAFFIC_TRACKER.write() {
|
||||
*guard = Some(tracker);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the global traffic tracker
|
||||
pub fn get_traffic_tracker() -> Option<Arc<LiveTrafficTracker>> {
|
||||
TRAFFIC_TRACKER.get().cloned()
|
||||
TRAFFIC_TRACKER.read().ok().and_then(|guard| guard.clone())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
Reference in New Issue
Block a user