|
| 1 | +//! HTTP request and response helpers for Sentinel proxy |
| 2 | +//! |
| 3 | +//! This module provides utilities for: |
| 4 | +//! - Extracting request information from Pingora sessions |
| 5 | +//! - Writing HTTP responses to Pingora sessions |
| 6 | +//! - Generating and managing correlation IDs |
| 7 | +//! |
| 8 | +//! These helpers reduce boilerplate in the main proxy logic and ensure |
| 9 | +//! consistent handling of HTTP operations. |
| 10 | +
|
| 11 | +use bytes::Bytes; |
| 12 | +use http::Response; |
| 13 | +use http_body_util::{BodyExt, Full}; |
| 14 | +use pingora::http::ResponseHeader; |
| 15 | +use pingora::prelude::*; |
| 16 | +use pingora::proxy::Session; |
| 17 | +use std::collections::HashMap; |
| 18 | + |
| 19 | +use crate::routing::RequestInfo; |
| 20 | + |
| 21 | +// ============================================================================ |
| 22 | +// Request Helpers |
| 23 | +// ============================================================================ |
| 24 | + |
| 25 | +/// Extract request info from a Pingora session |
| 26 | +/// |
| 27 | +/// Builds a `RequestInfo` struct from the session's request headers, |
| 28 | +/// suitable for route matching and processing. |
| 29 | +/// |
| 30 | +/// # Example |
| 31 | +/// |
| 32 | +/// ```ignore |
| 33 | +/// let request_info = extract_request_info(session); |
| 34 | +/// let route = router.match_request(&request_info); |
| 35 | +/// ``` |
| 36 | +pub fn extract_request_info(session: &Session) -> RequestInfo { |
| 37 | + let req_header = session.req_header(); |
| 38 | + |
| 39 | + let mut headers = HashMap::new(); |
| 40 | + for (name, value) in req_header.headers.iter() { |
| 41 | + if let Ok(value_str) = value.to_str() { |
| 42 | + headers.insert(name.as_str().to_lowercase(), value_str.to_string()); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + let host = headers.get("host").cloned().unwrap_or_default(); |
| 47 | + let path = req_header.uri.path().to_string(); |
| 48 | + |
| 49 | + RequestInfo { |
| 50 | + method: req_header.method.as_str().to_string(), |
| 51 | + path: path.clone(), |
| 52 | + host, |
| 53 | + headers, |
| 54 | + query_params: RequestInfo::parse_query_params(&path), |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +/// Extract or generate a correlation ID from request headers |
| 59 | +/// |
| 60 | +/// Looks for existing correlation ID headers in order of preference: |
| 61 | +/// 1. `x-correlation-id` |
| 62 | +/// 2. `x-request-id` |
| 63 | +/// 3. `x-trace-id` |
| 64 | +/// |
| 65 | +/// If none are found, generates a new UUID v4. |
| 66 | +/// |
| 67 | +/// # Example |
| 68 | +/// |
| 69 | +/// ```ignore |
| 70 | +/// let correlation_id = get_or_create_correlation_id(session); |
| 71 | +/// tracing::info!(correlation_id = %correlation_id, "Processing request"); |
| 72 | +/// ``` |
| 73 | +pub fn get_or_create_correlation_id(session: &Session) -> String { |
| 74 | + let req_header = session.req_header(); |
| 75 | + |
| 76 | + // Check for existing correlation ID headers (in order of preference) |
| 77 | + const CORRELATION_HEADERS: [&str; 3] = ["x-correlation-id", "x-request-id", "x-trace-id"]; |
| 78 | + |
| 79 | + for header_name in &CORRELATION_HEADERS { |
| 80 | + if let Some(value) = req_header.headers.get(*header_name) { |
| 81 | + if let Ok(id) = value.to_str() { |
| 82 | + return id.to_string(); |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + // Generate new correlation ID |
| 88 | + uuid::Uuid::new_v4().to_string() |
| 89 | +} |
| 90 | + |
| 91 | +// ============================================================================ |
| 92 | +// Response Helpers |
| 93 | +// ============================================================================ |
| 94 | + |
| 95 | +/// Write an HTTP response to a Pingora session |
| 96 | +/// |
| 97 | +/// Handles the conversion from `http::Response<Full<Bytes>>` to Pingora's |
| 98 | +/// format and writes it to the session. |
| 99 | +/// |
| 100 | +/// # Arguments |
| 101 | +/// |
| 102 | +/// * `session` - The Pingora session to write to |
| 103 | +/// * `response` - The HTTP response to write |
| 104 | +/// * `keepalive_secs` - Keepalive timeout in seconds (None = disable keepalive) |
| 105 | +/// |
| 106 | +/// # Returns |
| 107 | +/// |
| 108 | +/// Returns `Ok(())` on success or an error if writing fails. |
| 109 | +/// |
| 110 | +/// # Example |
| 111 | +/// |
| 112 | +/// ```ignore |
| 113 | +/// let response = Response::builder() |
| 114 | +/// .status(200) |
| 115 | +/// .body(Full::new(Bytes::from("OK")))?; |
| 116 | +/// write_response(session, response, Some(60)).await?; |
| 117 | +/// ``` |
| 118 | +pub async fn write_response( |
| 119 | + session: &mut Session, |
| 120 | + response: Response<Full<Bytes>>, |
| 121 | + keepalive_secs: Option<u64>, |
| 122 | +) -> Result<(), Box<Error>> { |
| 123 | + let status = response.status().as_u16(); |
| 124 | + |
| 125 | + // Collect headers to owned strings to avoid lifetime issues |
| 126 | + let headers_owned: Vec<(String, String)> = response |
| 127 | + .headers() |
| 128 | + .iter() |
| 129 | + .map(|(k, v)| { |
| 130 | + ( |
| 131 | + k.as_str().to_string(), |
| 132 | + v.to_str().unwrap_or("").to_string(), |
| 133 | + ) |
| 134 | + }) |
| 135 | + .collect(); |
| 136 | + |
| 137 | + // Extract body bytes |
| 138 | + let full_body = response.into_body(); |
| 139 | + let body_bytes: Bytes = BodyExt::collect(full_body) |
| 140 | + .await |
| 141 | + .map(|collected| collected.to_bytes()) |
| 142 | + .unwrap_or_default(); |
| 143 | + |
| 144 | + // Build Pingora response header |
| 145 | + let mut resp_header = ResponseHeader::build(status, None)?; |
| 146 | + for (key, value) in headers_owned { |
| 147 | + resp_header.insert_header(key, &value)?; |
| 148 | + } |
| 149 | + |
| 150 | + // Write response to session |
| 151 | + session.set_keepalive(keepalive_secs); |
| 152 | + session |
| 153 | + .write_response_header(Box::new(resp_header), false) |
| 154 | + .await?; |
| 155 | + session.write_response_body(Some(body_bytes), true).await?; |
| 156 | + |
| 157 | + Ok(()) |
| 158 | +} |
| 159 | + |
| 160 | +/// Write an error response to a Pingora session |
| 161 | +/// |
| 162 | +/// Convenience wrapper for error responses with status code, body, and content type. |
| 163 | +/// |
| 164 | +/// # Arguments |
| 165 | +/// |
| 166 | +/// * `session` - The Pingora session to write to |
| 167 | +/// * `status` - HTTP status code |
| 168 | +/// * `body` - Response body as string |
| 169 | +/// * `content_type` - Content-Type header value |
| 170 | +pub async fn write_error( |
| 171 | + session: &mut Session, |
| 172 | + status: u16, |
| 173 | + body: &str, |
| 174 | + content_type: &str, |
| 175 | +) -> Result<(), Box<Error>> { |
| 176 | + let mut resp_header = ResponseHeader::build(status, None)?; |
| 177 | + resp_header.insert_header("Content-Type", content_type)?; |
| 178 | + resp_header.insert_header("Content-Length", &body.len().to_string())?; |
| 179 | + |
| 180 | + session.set_keepalive(None); |
| 181 | + session |
| 182 | + .write_response_header(Box::new(resp_header), false) |
| 183 | + .await?; |
| 184 | + session |
| 185 | + .write_response_body(Some(Bytes::copy_from_slice(body.as_bytes())), true) |
| 186 | + .await?; |
| 187 | + |
| 188 | + Ok(()) |
| 189 | +} |
| 190 | + |
| 191 | +/// Write a plain text error response |
| 192 | +/// |
| 193 | +/// Shorthand for `write_error` with `text/plain; charset=utf-8` content type. |
| 194 | +pub async fn write_text_error( |
| 195 | + session: &mut Session, |
| 196 | + status: u16, |
| 197 | + message: &str, |
| 198 | +) -> Result<(), Box<Error>> { |
| 199 | + write_error(session, status, message, "text/plain; charset=utf-8").await |
| 200 | +} |
| 201 | + |
| 202 | +/// Write a JSON error response |
| 203 | +/// |
| 204 | +/// Creates a JSON object with `error` and optional `message` fields. |
| 205 | +/// |
| 206 | +/// # Example |
| 207 | +/// |
| 208 | +/// ```ignore |
| 209 | +/// // Produces: {"error":"not_found","message":"Resource does not exist"} |
| 210 | +/// write_json_error(session, 404, "not_found", Some("Resource does not exist")).await?; |
| 211 | +/// ``` |
| 212 | +pub async fn write_json_error( |
| 213 | + session: &mut Session, |
| 214 | + status: u16, |
| 215 | + error: &str, |
| 216 | + message: Option<&str>, |
| 217 | +) -> Result<(), Box<Error>> { |
| 218 | + let body = match message { |
| 219 | + Some(msg) => format!(r#"{{"error":"{}","message":"{}"}}"#, error, msg), |
| 220 | + None => format!(r#"{{"error":"{}"}}"#, error), |
| 221 | + }; |
| 222 | + write_error(session, status, &body, "application/json").await |
| 223 | +} |
| 224 | + |
| 225 | +// ============================================================================ |
| 226 | +// Tests |
| 227 | +// ============================================================================ |
| 228 | + |
| 229 | +#[cfg(test)] |
| 230 | +mod tests { |
| 231 | + // Integration tests require mocking Pingora session. |
| 232 | + // See crates/proxy/tests/ for integration test examples. |
| 233 | +} |
0 commit comments