Planning detailed Rust proxy implementation
The plan settles on using hyper's built-in connection pooling via its Client, a custom CircuitBreaker tracking per-second error/total counts in a sliding 60-second window, and a service that rejects requests with 503 if the circuit is open, forwarding otherwise. The approach includes parsing an upstream URL from env, adjusting request URIs, and maintaining concurrency safety via Arc<Mutex>. Next, I'll implement this full code in a single Rust main file.
use std::{
convert::Infallible,
net::SocketAddr,
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
use hyper::{
body::to_bytes,
client::HttpConnector,
header::HOST,
service::{make_service_fn, service_fn},
Body, Client, Method, Request, Response, Server, Uri,
};
use tokio::sync::Mutex;
/// Simple sliding-window circuit breaker with per-second buckets
struct CircuitBreaker {
buckets: Vec<Bucket>,
window_secs: u64,
threshold: f64,
}
#[derive(Clone, Copy, Debug)]
struct Bucket {
stamp: u64, // epoch second
total: u64,
errors: u64,
}
impl CircuitBreaker {
fn new(window_secs: u64, threshold: f64) -> Self {
let buckets = vec![
Bucket {
stamp: 0,
total: 0,
errors: 0
};
window_secs as usize
];
Self {
buckets,
window_secs,
threshold,
}
}
fn record(&mut self, now_sec: u64, is_error: bool) {
let idx = (now_sec % self.window_secs) as usize;
let bucket = &mut self.buckets[idx];
if bucket.stamp != now_sec {
// This bucket is stale, reset counts
bucket.stamp = now_sec;
bucket.total = 0;
bucket.errors = 0;
}
bucket.total += 1;
if is_error {
bucket.errors += 1;
}
}
fn is_open(&self, now_sec: u64) -> bool {
let cutoff = now_sec.saturating_sub(self.window_secs);
let mut total = 0u64;
let mut errors = 0u64;
for b in &self.buckets {
if b.stamp > cutoff {
total += b.total;
errors += b.errors;
}
}
if total == 0 {
return false;
}
(errors as f64 / total as f64) >= self.threshold
}
}
#[derive(Clone)]
struct Proxy {
upstream: Uri,
client: Client<HttpConnector, Body>,
breaker: Arc<Mutex<CircuitBreaker>>,
}
impl Proxy {
async fn handle(&self, mut req: Request<Body>) -> Result<Response<Body>, Infallible> {
let now_sec = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
// Check circuit breaker
{
let breaker = self.breaker.lock().await;
if breaker.is_open(now_sec) {
return Ok(Response::builder()
.status(503)
.body(Body::from("Upstream circuit open"))
.unwrap());
}
}
// Build new URI for upstream
let mut parts = req.uri().clone().into_parts();
// Keep path and query, replace scheme/authority
parts.scheme = self.upstream.scheme().cloned();
parts.authority = self.upstream.authority().cloned();
let new_uri = Uri::from_parts(parts).expect("failed to build upstream uri");
*req.uri_mut() = new_uri;
// Update Host header
if let Some(host) = self.upstream.host() {
let mut value = host.to_string();
if let Some(port) = self.upstream.port_u16() {
value.push(':');
value.push_str(&port.to_string());
}
req.headers_mut().insert(HOST, value.parse().unwrap());
}
// Proxy request to upstream
let resp_result = self.client.request(req).await;
let mut breaker = self.breaker.lock().await;
match resp_result {
Ok(resp) => {
// Record as error if 5xx
let is_error = resp.status().is_server_error();
breaker.record(now_sec, is_error);
Ok(resp)
}
Err(err) => {
breaker.record(now_sec, true);
eprintln!("Upstream error: {}", err);
Ok(Response::builder()
.status(502)
.body(Body::from("Bad Gateway"))
.unwrap())
}
}
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Configure upstream and listen address
let upstream = std::env::var("UPSTREAM")
.unwrap_or_else(|_| "http://127.0.0.1:9000".to_string())
.parse::<Uri>()?;
let addr: SocketAddr = "0.0.0.0:8080".parse()?;
// Hyper client with default connection pooling
let client = Client::builder()
.pool_max_idle_per_host(16)
.build::<_, Body>(HttpConnector::new());
let breaker = Arc::new(Mutex::new(CircuitBreaker::new(60, 0.10)));
let proxy = Proxy {
upstream,
client,
breaker,
};
let make_svc = make_service_fn(move |_| {
let proxy = proxy.clone();
async move {
Ok::<_, Infallible>(service_fn(move |req| {
let proxy = proxy.clone();
async move { proxy.handle(req).await }
}))
}
});
println!("Listening on http://{}", addr);
let server = Server::bind(&addr).serve(make_svc);
server.await?;
Ok(())
}
This program:
- Listens on
0.0.0.0:8080 and forwards requests to the UPSTREAM URL (set via environment variable, defaults to http://127.0.0.1:9000).
- Uses Hyper/Tokio for high-performance async I/O, with Hyper's built-in connection pooling configured via
pool_max_idle_per_host.
- Maintains a per-second sliding window of the last minute of upstream requests; if more than 10% of them result in upstream errors, the circuit breaker opens and new requests are answered with HTTP 503 until the error rate drops.