Skip to main content

tiny_proxy/api/
endpoints.rs

1//! API endpoints for proxy management
2
3use anyhow::Result;
4use bytes::Bytes;
5use http_body::Body;
6use http_body_util::{BodyExt, Full};
7use hyper::{Request, Response};
8use std::sync::Arc;
9use tracing::{error, info};
10
11use crate::config::Config;
12
13/// Handle GET /config
14pub async fn handle_get_config<B>(
15    _req: Request<B>,
16    config: Arc<tokio::sync::RwLock<Config>>,
17) -> Result<Response<Full<Bytes>>>
18where
19    B: Body,
20{
21    let config = config.read().await;
22
23    let json = serde_json::to_string_pretty(&*config)
24        .unwrap_or_else(|_| r#"{"error": "Failed to serialize config"}"#.to_string());
25
26    info!("GET /config - Returning configuration");
27
28    let response = Response::builder()
29        .status(200)
30        .header("Content-Type", "application/json")
31        .body(Full::new(Bytes::from(json)))
32        .unwrap();
33
34    Ok(response)
35}
36
37/// Handle POST /config
38///
39/// Accepts a JSON body representing the new configuration and atomically
40/// replaces the current configuration. The new config takes effect
41/// immediately for all new incoming proxy connections.
42///
43/// # Request Body
44///
45/// JSON representation of the full `Config` struct, e.g.:
46/// ```json
47/// {
48///   "sites": {
49///     "localhost:8080": {
50///       "address": "localhost:8080",
51///       "directives": [
52///         { "ReverseProxy": { "to": "localhost:9001" } }
53///       ]
54///     }
55///   }
56/// }
57/// ```
58pub async fn handle_post_config<B>(
59    req: Request<B>,
60    config: Arc<tokio::sync::RwLock<Config>>,
61) -> Result<Response<Full<Bytes>>>
62where
63    B: Body,
64    B::Error: std::fmt::Display,
65{
66    let body_bytes = match BodyExt::collect(req.into_body()).await {
67        Ok(collected) => collected.to_bytes(),
68        Err(e) => {
69            let error_json = serde_json::json!({
70                "status": "error",
71                "message": format!("Failed to read request body: {}", e)
72            });
73            let response = Response::builder()
74                .status(400)
75                .header("Content-Type", "application/json")
76                .body(Full::new(Bytes::from(
77                    serde_json::to_string(&error_json).unwrap(),
78                )))
79                .unwrap();
80            return Ok(response);
81        }
82    };
83
84    let body_str = match std::str::from_utf8(&body_bytes) {
85        Ok(s) => s,
86        Err(_) => {
87            let error_json = serde_json::json!({
88                "status": "error",
89                "message": "Invalid UTF-8 in request body"
90            });
91            let response = Response::builder()
92                .status(400)
93                .header("Content-Type", "application/json")
94                .body(Full::new(Bytes::from(
95                    serde_json::to_string(&error_json).unwrap(),
96                )))
97                .unwrap();
98            return Ok(response);
99        }
100    };
101
102    // Parse JSON body into Config
103    let new_config: Config = match serde_json::from_str(body_str) {
104        Ok(config) => config,
105        Err(e) => {
106            error!("Failed to parse config JSON: {}", e);
107            let error_json = serde_json::json!({
108                "status": "error",
109                "message": format!("Invalid configuration JSON: {}", e)
110            });
111            let response = Response::builder()
112                .status(400)
113                .header("Content-Type", "application/json")
114                .body(Full::new(Bytes::from(
115                    serde_json::to_string(&error_json).unwrap(),
116                )))
117                .unwrap();
118            return Ok(response);
119        }
120    };
121
122    // Atomically replace the configuration
123    {
124        let mut guard = config.write().await;
125        let sites_count = new_config.sites.len();
126        *guard = new_config;
127        info!(
128            "POST /config - Configuration updated successfully ({} sites)",
129            sites_count
130        );
131    }
132
133    let response = Response::builder()
134        .status(200)
135        .header("Content-Type", "application/json")
136        .body(Full::new(Bytes::from(
137            r#"{"status": "success", "message": "Configuration updated"}"#.to_string(),
138        )))
139        .unwrap();
140
141    Ok(response)
142}
143
144/// Handle GET /health
145pub async fn handle_health_check<B>(_req: Request<B>) -> Result<Response<Full<Bytes>>>
146where
147    B: Body,
148{
149    info!("GET /health - Health check");
150
151    let health = serde_json::json!({
152        "status": "healthy",
153        "service": "tiny-proxy",
154        "version": env!("CARGO_PKG_VERSION")
155    });
156
157    let response = Response::builder()
158        .status(200)
159        .header("Content-Type", "application/json")
160        .body(Full::new(Bytes::from(
161            serde_json::to_string(&health).unwrap(),
162        )))
163        .unwrap();
164
165    Ok(response)
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171    use http_body_util::Empty;
172    use std::collections::HashMap;
173    use std::sync::Arc;
174
175    #[tokio::test]
176    async fn test_handle_health_check() {
177        let req: Request<Empty<Bytes>> = Request::builder().body(Empty::new()).unwrap();
178
179        let response = handle_health_check(req).await.unwrap();
180        assert_eq!(response.status(), 200);
181    }
182
183    #[tokio::test]
184    async fn test_handle_get_config() {
185        let config = Arc::new(tokio::sync::RwLock::new(Config {
186            sites: HashMap::new(),
187        }));
188
189        let req: Request<Empty<Bytes>> = Request::builder().body(Empty::new()).unwrap();
190
191        let response = handle_get_config(req, config).await.unwrap();
192        assert_eq!(response.status(), 200);
193    }
194
195    #[tokio::test]
196    async fn test_handle_post_config_valid_json() {
197        let config = Arc::new(tokio::sync::RwLock::new(Config {
198            sites: HashMap::new(),
199        }));
200
201        let new_config_json = r#"{
202            "sites": {
203                "localhost:8080": {
204                    "address": "localhost:8080",
205                    "directives": [
206                        {"ReverseProxy": {"to": "localhost:9001"}}
207                    ]
208                }
209            }
210        }"#;
211
212        let req = Request::builder()
213            .method("POST")
214            .uri("/config")
215            .body(Full::new(Bytes::from(new_config_json.to_string())))
216            .unwrap();
217
218        let response = handle_post_config(req, config.clone()).await.unwrap();
219        assert_eq!(response.status(), 200);
220
221        // Verify config was actually updated
222        let guard = config.read().await;
223        assert_eq!(guard.sites.len(), 1);
224        assert!(guard.sites.contains_key("localhost:8080"));
225    }
226
227    #[tokio::test]
228    async fn test_handle_post_config_invalid_json() {
229        let config = Arc::new(tokio::sync::RwLock::new(Config {
230            sites: HashMap::new(),
231        }));
232
233        let req = Request::builder()
234            .method("POST")
235            .uri("/config")
236            .body(Full::new(Bytes::from("not valid json")))
237            .unwrap();
238
239        let response = handle_post_config(req, config.clone()).await.unwrap();
240        assert_eq!(response.status(), 400);
241
242        // Verify config was NOT updated
243        let guard = config.read().await;
244        assert_eq!(guard.sites.len(), 0);
245    }
246
247    #[tokio::test]
248    async fn test_handle_post_config_empty_body() {
249        let config = Arc::new(tokio::sync::RwLock::new(Config {
250            sites: HashMap::new(),
251        }));
252
253        let req: Request<Empty<Bytes>> = Request::builder()
254            .method("POST")
255            .uri("/config")
256            .body(Empty::new())
257            .unwrap();
258
259        let response = handle_post_config(req, config).await.unwrap();
260        assert_eq!(response.status(), 400);
261    }
262}