Skip to main content

agentmux_srv_core/backend/dev_proxy/
forward.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One request through the dev proxy to a connection already open to the dev server, WebSocket
5//! upgrades included (Vite's hot reload is one).
6
7use axum::body::Body;
8use axum::extract::Request;
9use axum::http::{header, HeaderMap, HeaderName, HeaderValue, StatusCode};
10use axum::response::Response;
11use hyper_util::rt::TokioIo;
12use tokio::io::{AsyncRead, AsyncWrite};
13
14/// Headers that describe one connection, not the message. A WebSocket handshake needs `Connection`
15/// and `Upgrade` kept, and only that.
16const HOP_BY_HOP: &[&str] = &["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade"];
17
18fn wants_upgrade(headers: &HeaderMap) -> bool {
19    let has = |name: HeaderName, token: &str| {
20        headers.get_all(name).iter().filter_map(|v| v.to_str().ok()).any(|v| v.split(',').any(|t| t.trim().eq_ignore_ascii_case(token)))
21    };
22    has(header::CONNECTION, "upgrade") && headers.contains_key(header::UPGRADE)
23}
24
25fn copy_headers(from: &HeaderMap, to: &mut HeaderMap, keep_upgrade: bool) {
26    for (name, value) in from {
27        if name == header::HOST || (HOP_BY_HOP.contains(&name.as_str()) && !(keep_upgrade && (name == header::CONNECTION || name == header::UPGRADE))) {
28            continue;
29        }
30        to.append(name.clone(), value.clone());
31    }
32}
33
34/// Send `req` over `backend` and give back the dev server's answer. `host` is what the dev server is
35/// told it is being asked for (the proxy's own `Host` names the proxy, not the dev server).
36pub(super) async fn forward<S>(mut req: Request, backend: S, host: &str) -> Result<Response, String>
37where
38    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
39{
40    let upgrade = wants_upgrade(req.headers());
41    let client_upgrade = upgrade.then(|| hyper::upgrade::on(&mut req));
42    let (parts, body) = req.into_parts();
43
44    let mut out = hyper::Request::builder()
45        .method(parts.method)
46        .uri(parts.uri.path_and_query().map(|pq| pq.as_str()).unwrap_or("/"))
47        .version(axum::http::Version::HTTP_11);
48    let headers = out.headers_mut().expect("builder");
49    copy_headers(&parts.headers, headers, upgrade);
50    headers.insert(header::HOST, HeaderValue::from_str(host).map_err(|e| e.to_string())?);
51    let out = out.body(body).map_err(|e| e.to_string())?;
52
53    let (mut sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(backend)).await.map_err(|e| e.to_string())?;
54    tokio::spawn(async move {
55        let _ = connection.with_upgrades().await;
56    });
57    let mut answer = sender.send_request(out).await.map_err(|e| e.to_string())?;
58
59    if upgrade && answer.status() == StatusCode::SWITCHING_PROTOCOLS {
60        let backend_upgrade = hyper::upgrade::on(&mut answer);
61        let mut response = Response::builder().status(StatusCode::SWITCHING_PROTOCOLS);
62        copy_headers(answer.headers(), response.headers_mut().expect("builder"), true);
63        if let Some(client_upgrade) = client_upgrade {
64            tokio::spawn(async move {
65                if let (Ok(client), Ok(backend)) = (client_upgrade.await, backend_upgrade.await) {
66                    let _ = tokio::io::copy_bidirectional(&mut TokioIo::new(client), &mut TokioIo::new(backend)).await;
67                }
68            });
69        }
70        return response.body(Body::empty()).map_err(|e| e.to_string());
71    }
72
73    let (answer_parts, answer_body) = answer.into_parts();
74    let mut response = Response::builder().status(answer_parts.status);
75    copy_headers(&answer_parts.headers, response.headers_mut().expect("builder"), false);
76    response.body(Body::new(answer_body)).map_err(|e| e.to_string())
77}