agentmux_srv/server/
muxspect_instances.rs1use std::path::Path;
15use std::sync::OnceLock;
16use std::time::Duration;
17
18use axum::extract::Request;
19use axum::http::{header, HeaderValue, StatusCode};
20use axum::middleware::Next;
21use axum::response::{IntoResponse, Response};
22use axum::Json;
23use serde_json::json;
24
25use crate::backend::instance_registry::{self, InstanceRecord};
26
27const FORWARD_TIMEOUT: Duration = Duration::from_secs(5);
30const MAX_FORWARDED_BYTES: usize = 8 * 1024 * 1024;
32
33pub async fn handle_muxspect_instances() -> impl IntoResponse {
36 let Some(dir) = crate::registry::resolve_shared_instances_dir() else {
37 return Json(json!({ "instances": [], "error": "this instance has no shared folder to list instances in" }));
38 };
39 let records = tokio::task::spawn_blocking(move || instance_registry::live_instances(&dir))
40 .await
41 .unwrap_or_default();
42 Json(listing_body(&records, std::process::id(), agentmux_common::time::now_ms_u64()))
43}
44
45fn listing_body(records: &[InstanceRecord], own_pid: u32, now_ms: u64) -> serde_json::Value {
46 json!({
47 "own_channel": crate::backend::reactive::registry::local_channel_id(),
48 "instances": records.iter().map(|r| r.listing(own_pid, now_ms)).collect::<Vec<_>>(),
49 })
50}
51
52fn split_channel(query: Option<&str>) -> Option<(String, String)> {
55 let mut channel = None;
56 let mut rest = url::form_urlencoded::Serializer::new(String::new());
57 for (k, v) in url::form_urlencoded::parse(query?.as_bytes()) {
58 if k == "channel" {
59 channel = Some(v.into_owned()).filter(|c| !c.is_empty());
60 } else {
61 rest.append_pair(&k, &v);
62 }
63 }
64 channel.map(|c| (c, rest.finish()))
65}
66
67fn error_response(status: StatusCode, message: String, known: &[InstanceRecord]) -> Response {
68 let channels: Vec<&str> = known.iter().map(|r| r.channel.as_str()).collect();
69 (status, Json(json!({ "error": message, "live_channels": channels }))).into_response()
70}
71
72fn forward_timeout(path: &str, query: &str) -> Duration {
75 if path == super::muxspect_browsers::PATH {
76 super::muxspect_browsers::longest_answer(query).max(FORWARD_TIMEOUT)
77 } else {
78 FORWARD_TIMEOUT
79 }
80}
81
82fn forward_client() -> &'static reqwest::Client {
83 static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
84 CLIENT.get_or_init(|| {
86 crate::http_client::client_with(|b| b.no_proxy().timeout(FORWARD_TIMEOUT))
87 })
88}
89
90pub async fn forward_to_channel(req: Request, next: Next) -> Response {
93 let Some((channel, rest_query)) = split_channel(req.uri().query()) else {
94 return next.run(req).await;
95 };
96 if channel == crate::backend::reactive::registry::local_channel_id() {
97 return next.run(req).await;
98 }
99 let Some(dir) = crate::registry::resolve_shared_instances_dir() else {
100 return error_response(StatusCode::SERVICE_UNAVAILABLE, "this instance has no shared folder to find other instances in".into(), &[]);
101 };
102 let path = req.uri().path().to_string();
103 forward(&dir, &channel, &path, &rest_query, instance_registry::live_instances).await
104}
105
106async fn forward(
109 dir: &Path,
110 channel: &str,
111 path: &str,
112 query: &str,
113 live: impl FnOnce(&Path) -> Vec<InstanceRecord> + Send + 'static,
114) -> Response {
115 let owned_dir = dir.to_path_buf();
116 let records = tokio::task::spawn_blocking(move || live(&owned_dir)).await.unwrap_or_default();
117 let Some(target) = records.iter().find(|r| r.channel == channel) else {
118 return error_response(StatusCode::NOT_FOUND, format!("no live AgentMux instance on channel '{channel}'"), &records);
119 };
120 let url = if query.is_empty() { format!("{}{path}", target.local_url) } else { format!("{}{path}?{query}", target.local_url) };
121 let sent = forward_client().get(url).timeout(forward_timeout(path, query)).header(agentmux_common::AUTH_KEY_HEADER, &target.auth_key).send().await;
122 match sent {
123 Ok(resp) => relay(resp, channel).await,
124 Err(e) => error_response(
125 StatusCode::BAD_GATEWAY,
126 format!("instance '{channel}' is listed but did not answer ({})", if e.is_timeout() { "timed out" } else { "connection failed" }),
127 &records,
128 ),
129 }
130}
131
132async fn read_capped(mut resp: reqwest::Response, cap: usize) -> Result<Option<Vec<u8>>, reqwest::Error> {
135 if resp.content_length().is_some_and(|len| len > cap as u64) {
136 return Ok(None);
137 }
138 let mut body = Vec::new();
139 while let Some(chunk) = resp.chunk().await? {
140 if body.len() + chunk.len() > cap {
141 return Ok(None);
142 }
143 body.extend_from_slice(&chunk);
144 }
145 Ok(Some(body))
146}
147
148async fn relay(resp: reqwest::Response, channel: &str) -> Response {
150 let status = StatusCode::from_u16(resp.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
151 let content_type = resp.headers().get(header::CONTENT_TYPE).cloned();
152 let version = resp.headers().get("x-agentmux-srv-version").cloned();
153 let body = match read_capped(resp, MAX_FORWARDED_BYTES).await {
154 Ok(Some(body)) => body,
155 Ok(None) => {
156 return error_response(StatusCode::BAD_GATEWAY, format!("instance '{channel}' answered with more than {MAX_FORWARDED_BYTES} bytes"), &[]);
157 }
158 Err(_) => return error_response(StatusCode::BAD_GATEWAY, format!("instance '{channel}' stopped answering part way"), &[]),
159 };
160 let mut out = (status, body).into_response();
161 let headers = out.headers_mut();
162 if let Some(v) = content_type {
163 headers.insert(header::CONTENT_TYPE, v);
164 }
165 if let Some(v) = version {
168 headers.insert("x-agentmux-forwarded-srv-version", v);
169 }
170 if let Ok(v) = HeaderValue::from_str(channel) {
171 headers.insert("x-agentmux-forwarded-channel", v);
172 }
173 out
174}
175
176#[cfg(test)]
177#[path = "muxspect_instances_tests.rs"]
178mod tests;