lean_ctx/proxy/
forward.rs1use axum::{
2 body::Body,
3 extract::State,
4 http::{request::Parts, Request, StatusCode},
5 response::Response,
6};
7
8use super::ProxyState;
9
10const MAX_BODY_BYTES: usize = 10 * 1024 * 1024;
11
12pub type CompressFn = fn(&[u8]) -> (Vec<u8>, usize, usize);
13
14pub async fn forward_request(
15 State(state): State<ProxyState>,
16 req: Request<Body>,
17 upstream_base: &str,
18 default_path: &str,
19 compress_body: CompressFn,
20 provider_label: &str,
21 extra_stream_types: &[&str],
22) -> Result<Response, StatusCode> {
23 let (parts, body) = req.into_parts();
24 let body_bytes = axum::body::to_bytes(body, MAX_BODY_BYTES)
25 .await
26 .map_err(|_| StatusCode::BAD_REQUEST)?;
27
28 state.stats.record_request();
29
30 let (compressed_body, original_size, compressed_size) = compress_body(&body_bytes);
31
32 if compressed_size < original_size {
33 state
34 .stats
35 .record_compression(original_size, compressed_size);
36 }
37
38 let upstream_url = build_upstream_url(&parts, upstream_base, default_path);
39 let response = send_upstream(
40 &state,
41 &parts,
42 &upstream_url,
43 compressed_body,
44 provider_label,
45 )
46 .await?;
47
48 build_response(response, extra_stream_types).await
49}
50
51fn build_upstream_url(parts: &Parts, base: &str, default_path: &str) -> String {
52 format!(
53 "{base}{}",
54 parts
55 .uri
56 .path_and_query()
57 .map_or(default_path, axum::http::uri::PathAndQuery::as_str)
58 )
59}
60
61async fn send_upstream(
62 state: &ProxyState,
63 parts: &Parts,
64 url: &str,
65 body: Vec<u8>,
66 provider_label: &str,
67) -> Result<reqwest::Response, StatusCode> {
68 let mut req = state.client.request(parts.method.clone(), url);
69
70 const ALLOWED_HEADERS: &[&str] = &[
71 "authorization",
72 "x-api-key",
73 "content-type",
74 "accept",
75 "user-agent",
76 "anthropic-version",
77 "anthropic-beta",
78 "anthropic-dangerous-direct-browser-access",
79 "openai-organization",
80 "openai-beta",
81 "x-goog-api-key",
82 "x-goog-api-client",
83 ];
84 for (key, value) in &parts.headers {
85 let k = key.as_str().to_lowercase();
86 if ALLOWED_HEADERS.contains(&k.as_str()) {
87 req = req.header(key.clone(), value.clone());
88 }
89 }
90
91 req.body(body).send().await.map_err(|e| {
92 tracing::error!("lean-ctx proxy: {provider_label} upstream error: {e}");
93 StatusCode::BAD_GATEWAY
94 })
95}
96
97async fn build_response(
98 response: reqwest::Response,
99 extra_stream_types: &[&str],
100) -> Result<Response, StatusCode> {
101 let status = StatusCode::from_u16(response.status().as_u16()).unwrap_or(StatusCode::OK);
102 let resp_headers = response.headers().clone();
103
104 let is_stream = resp_headers
105 .get("content-type")
106 .and_then(|v| v.to_str().ok())
107 .is_some_and(|ct| {
108 ct.contains("text/event-stream") || extra_stream_types.iter().any(|t| ct.contains(t))
109 });
110
111 if is_stream {
112 let stream = response.bytes_stream();
113 let body = Body::from_stream(stream);
114 let mut resp = Response::builder().status(status);
115 for (k, v) in &resp_headers {
116 resp = resp.header(k, v);
117 }
118 return resp
119 .body(body)
120 .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR);
121 }
122
123 let resp_bytes = response
124 .bytes()
125 .await
126 .map_err(|_| StatusCode::BAD_GATEWAY)?;
127
128 let mut resp = Response::builder().status(status);
129 for (k, v) in &resp_headers {
130 let ks = k.as_str().to_lowercase();
131 if ks == "transfer-encoding" || ks == "content-length" {
132 continue;
133 }
134 resp = resp.header(k, v);
135 }
136 resp.body(Body::from(resp_bytes))
137 .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
138}