Skip to content

Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy

Rust

fix attached monitor lifecycle and timing

Raine Virtaaa9b096a37bc
diff --git a/src/main.rs b/src/main.rs
index 958267d..d752e59 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -172,6 +172,7 @@ fn main() -> Result<()> {
.enable_all()
.build()?;
let client = reqwest::Client::builder()
+ .no_proxy()
.redirect(reqwest::redirect::Policy::none())
.timeout(std::time::Duration::from_secs(2))
.build()?;
@@ -203,7 +204,13 @@ async fn run_service(config: ServerConfig) -> Result<()> {
signal = service_shutdown_signal() => {
signal?;
let _ = shutdown.send(());
- server.await
+ tokio::select! {
+ result = &mut server => result,
+ signal = service_shutdown_signal() => {
+ signal?;
+ Ok(())
+ }
+ }
}
}
}
diff --git a/src/monitor.rs b/src/monitor.rs
index d6b07d1..811c8b7 100644
--- a/src/monitor.rs
+++ b/src/monitor.rs
@@ -240,6 +240,7 @@ impl Throughput {
#[derive(Debug, Clone)]
pub struct MonitorState {
pub started_at: SystemTime,
+ pub uptime: Duration,
pub sessions: Vec<SessionSummary>,
pub active: Vec<ActiveRequest>,
pub recent: Vec<CompletedRequest>,
@@ -284,6 +285,7 @@ impl SessionSummary {
#[derive(Debug)]
struct MonitorStore {
started_at: SystemTime,
+ started_instant: Instant,
active: HashMap<String, ActiveRequest>,
recent: VecDeque<CompletedRequest>,
session_usage: HashMap<Option<String>, SessionUsage>,
@@ -313,6 +315,7 @@ impl MonitorHandle {
Self {
store: Arc::new(Mutex::new(MonitorStore {
started_at: SystemTime::now(),
+ started_instant: Instant::now(),
active: HashMap::new(),
recent: VecDeque::new(),
session_usage: HashMap::new(),
@@ -333,6 +336,7 @@ impl MonitorHandle {
Ok(store) => store.snapshot(),
Err(_) => MonitorState {
started_at: SystemTime::now(),
+ uptime: Duration::ZERO,
sessions: Vec::new(),
active: Vec::new(),
recent: Vec::new(),
@@ -874,6 +878,7 @@ impl MonitorStore {
);
MonitorState {
started_at: self.started_at,
+ uptime: self.started_instant.elapsed(),
sessions,
active,
recent: self.recent.iter().cloned().collect(),
@@ -1095,6 +1100,22 @@ mod tests {
assert_eq!(state.active[0].session_seq, Some(3));
}
+ #[test]
+ fn uptime_uses_the_service_monotonic_clock() {
+ let monitor = MonitorHandle::new(10);
+ {
+ let mut store = monitor.store.lock().unwrap();
+ store.started_at = SystemTime::now() + Duration::from_secs(3_600);
+ store.started_instant = Instant::now() - Duration::from_secs(42);
+ }
+
+ let state = monitor.snapshot();
+
+ assert!(state.started_at > SystemTime::now());
+ assert!(state.uptime >= Duration::from_secs(42));
+ assert!(state.uptime < Duration::from_secs(43));
+ }
+
#[test]
fn resolved_model_appends_to_incoming_alias() {
let monitor = MonitorHandle::new(10);
diff --git a/src/monitor/mock.rs b/src/monitor/mock.rs
index 4237b7f..48846d1 100644
--- a/src/monitor/mock.rs
+++ b/src/monitor/mock.rs
@@ -371,6 +371,7 @@ fn mock_state_for_tick(
let sessions = session_summaries(&active, &recent, &session_usage, output_buckets);
MonitorState {
started_at,
+ uptime: now.duration_since(started_at).unwrap_or_default(),
sessions,
active,
recent: recent.into_iter().collect(),
diff --git a/src/monitor/snapshot.rs b/src/monitor/snapshot.rs
index 1a55ddc..2130069 100644
--- a/src/monitor/snapshot.rs
+++ b/src/monitor/snapshot.rs
@@ -66,6 +66,7 @@ impl SnapshotUpdate {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MonitorSnapshot {
pub started_at: SystemTime,
+ pub uptime: Duration,
pub sessions: Vec<SessionSnapshot>,
pub active: Vec<ActiveSnapshot>,
pub recent: Vec<CompletedSnapshot>,
@@ -75,6 +76,7 @@ impl From<MonitorState> for MonitorSnapshot {
fn from(state: MonitorState) -> Self {
Self {
started_at: state.started_at,
+ uptime: state.uptime,
sessions: state.sessions.into_iter().map(Into::into).collect(),
active: state.active.into_iter().map(Into::into).collect(),
recent: state.recent.into_iter().map(Into::into).collect(),
@@ -292,6 +294,7 @@ mod tests {
assert!(!encoded.contains("instant"));
let decoded: MonitorSnapshot = serde_json::from_str(&encoded).unwrap();
assert_eq!(decoded, snapshot);
+ assert_eq!(decoded.uptime, snapshot.uptime);
assert_eq!(decoded.active[0].elapsed(), snapshot.active[0].elapsed());
assert_eq!(decoded.active[0].rate(), snapshot.active[0].rate());
assert_eq!(decoded.sessions[0].rate(), snapshot.sessions[0].rate());
diff --git a/src/tui.rs b/src/tui.rs
index ce5d048..a078798 100644
--- a/src/tui.rs
+++ b/src/tui.rs
@@ -488,10 +488,6 @@ fn render_header(
app: &MonitorApp,
state: &MonitorSnapshot,
) {
- let uptime = state
- .started_at
- .elapsed()
- .unwrap_or_else(|_| Duration::from_secs(0));
let text = Line::from(vec![
Span::styled(
" claude-code-proxy",
@@ -504,7 +500,7 @@ fn render_header(
Span::styled(&app.listen_url, Style::default().fg(BG).bg(TEAL)),
Span::styled(" uptime ", Style::default().fg(BG).bg(TEAL)),
Span::styled(
- format_duration(uptime),
+ format_duration(state.uptime),
Style::default()
.fg(BG)
.bg(TEAL)
diff --git a/tests/cli.rs b/tests/cli.rs
index 8cc555d..5f5ed4c 100644
--- a/tests/cli.rs
+++ b/tests/cli.rs
@@ -1,6 +1,14 @@
use assert_cmd::Command;
use predicates::str::contains;
use std::env;
+#[cfg(unix)]
+use std::{
+ io::{Read, Write},
+ net::{TcpListener, TcpStream},
+ process::{Child, Stdio},
+ thread,
+ time::{Duration, Instant},
+};
use tempfile::TempDir;
#[test]
@@ -102,6 +110,87 @@ fn models_output_is_stable_order() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
+#[cfg(unix)]
+struct ChildGuard(Child);
+
+#[cfg(unix)]
+impl Drop for ChildGuard {
+ fn drop(&mut self) {
+ let _ = self.0.kill();
+ let _ = self.0.wait();
+ }
+}
+
+#[cfg(unix)]
+fn plain_service_exits_on_second_signal(signal: &str) -> Result<(), Box<dyn std::error::Error>> {
+ let port = TcpListener::bind("127.0.0.1:0")?.local_addr()?.port();
+ let child = std::process::Command::new(env!("CARGO_BIN_EXE_claude-code-proxy"))
+ .args(["serve", "--no-monitor", "--port", &port.to_string()])
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped())
+ .spawn()?;
+ let mut child = ChildGuard(child);
+ let deadline = Instant::now() + Duration::from_secs(15);
+ let mut held_connection = loop {
+ match TcpStream::connect(("127.0.0.1", port)) {
+ Ok(stream) => break stream,
+ Err(error) if Instant::now() < deadline => {
+ if let Some(status) = child.0.try_wait()? {
+ let mut stderr = String::new();
+ if let Some(mut pipe) = child.0.stderr.take() {
+ pipe.read_to_string(&mut stderr)?;
+ }
+ return Err(format!("service exited with {status}: {stderr}").into());
+ }
+ let _ = error;
+ thread::sleep(Duration::from_millis(20));
+ }
+ Err(error) => return Err(error.into()),
+ }
+ };
+ held_connection.write_all(b"GET /healthz HTTP/1.1\r\nHost: localhost\r\n")?;
+ thread::sleep(Duration::from_millis(100));
+
+ assert!(
+ std::process::Command::new("kill")
+ .args([signal, &child.0.id().to_string()])
+ .status()?
+ .success()
+ );
+ thread::sleep(Duration::from_millis(200));
+ assert!(child.0.try_wait()?.is_none());
+
+ assert!(
+ std::process::Command::new("kill")
+ .args([signal, &child.0.id().to_string()])
+ .status()?
+ .success()
+ );
+ let deadline = Instant::now() + Duration::from_secs(4);
+ loop {
+ if child.0.try_wait()?.is_some() {
+ return Ok(());
+ }
+ if Instant::now() >= deadline {
+ return Err("plain service did not exit after the second signal".into());
+ }
+ thread::sleep(Duration::from_millis(20));
+ }
+}
+
+#[cfg(unix)]
+#[test]
+fn plain_service_exits_on_second_ctrl_c() -> Result<(), Box<dyn std::error::Error>> {
+ plain_service_exits_on_second_signal("-INT")
+}
+
+#[cfg(unix)]
+#[test]
+fn plain_service_exits_on_second_sigterm() -> Result<(), Box<dyn std::error::Error>> {
+ plain_service_exits_on_second_signal("-TERM")
+}
+
#[test]
fn kimi_auth_status_reads_stored_auth() -> Result<(), Box<dyn std::error::Error>> {
let temp = TempDir::new()?;
diff --git a/tests/remote_monitor.rs b/tests/remote_monitor.rs
index e3e5a46..57aeef1 100644
--- a/tests/remote_monitor.rs
+++ b/tests/remote_monitor.rs
@@ -1,5 +1,6 @@
use std::{
net::SocketAddr,
+ process::{Command, Stdio},
sync::{
Arc,
atomic::{AtomicBool, AtomicUsize, Ordering},
@@ -231,6 +232,45 @@ async fn polling_keeps_last_snapshot_on_failure_and_recovers() {
assert_eq!(requests.load(Ordering::SeqCst), after_drop);
}
+#[tokio::test]
+async fn production_monitor_client_bypasses_outbound_proxy_environment() {
+ fn snapshot_app(requests: Arc<AtomicUsize>) -> Router {
+ Router::new().route(
+ "/monitor",
+ get(move || {
+ requests.fetch_add(1, Ordering::SeqCst);
+ let response = MonitorResponse::from(MonitorHandle::default().snapshot());
+ async move { Json(response) }
+ }),
+ )
+ }
+
+ let target_requests = Arc::new(AtomicUsize::new(0));
+ let target = serve(snapshot_app(target_requests.clone())).await;
+ let proxy_requests = Arc::new(AtomicUsize::new(0));
+ let proxy = serve(snapshot_app(proxy_requests.clone())).await;
+ let mut child = Command::new(env!("CARGO_BIN_EXE_claude-code-proxy"))
+ .args(["monitor", "--url", target.url.as_str()])
+ .env("HTTP_PROXY", proxy.url.as_str())
+ .env("http_proxy", proxy.url.as_str())
+ .env("ALL_PROXY", proxy.url.as_str())
+ .env("all_proxy", proxy.url.as_str())
+ .env_remove("NO_PROXY")
+ .env_remove("no_proxy")
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .unwrap();
+
+ wait_until(|| target_requests.load(Ordering::SeqCst) > 0).await;
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ let _ = child.kill();
+ let _ = child.wait();
+
+ assert_eq!(proxy_requests.load(Ordering::SeqCst), 0);
+}
+
#[tokio::test]
async fn incompatible_protocol_and_disabled_collection_report_attach_errors() {
let incompatible = serve(Router::new().route(