|
| 1 | +/// Single HTTP request execution logic |
| 2 | +/// |
| 3 | +/// This module handles the low-level details of executing a single HTTP request: |
| 4 | +/// - Socket management (pooling/creation) |
| 5 | +/// - Connection establishment |
| 6 | +/// - Request serialization |
| 7 | +/// - Response reading |
| 8 | +/// - Connection reuse logic |
| 9 | +use crate::config::Config; |
| 10 | +use crate::dns::DnsResolver; |
| 11 | +use crate::error::Error; |
| 12 | +use crate::headers::Headers; |
| 13 | +use crate::method::Method; |
| 14 | +use crate::parser::RequestBuilder as ParserRequestBuilder; |
| 15 | +use crate::parser::uri::Uri; |
| 16 | +use crate::socket::BlockingSocket; |
| 17 | +use crate::transport::{ |
| 18 | + ConnectionPool, Connector, PoolKey, RawResponse, ResponseBodyExpectation, |
| 19 | +}; |
| 20 | +use alloc::string::String; |
| 21 | +use alloc::vec::Vec; |
| 22 | + |
| 23 | +/// Executes a single HTTP request without redirect handling |
| 24 | +pub struct RequestExecutor<'a, S, D> { |
| 25 | + pool: &'a mut ConnectionPool<S>, |
| 26 | + dns: &'a D, |
| 27 | + config: &'a Config, |
| 28 | +} |
| 29 | + |
| 30 | +impl<'a, S, D> RequestExecutor<'a, S, D> |
| 31 | +where |
| 32 | + S: BlockingSocket, |
| 33 | + D: DnsResolver, |
| 34 | +{ |
| 35 | + pub const fn new( |
| 36 | + pool: &'a mut ConnectionPool<S>, |
| 37 | + dns: &'a D, |
| 38 | + config: &'a Config, |
| 39 | + ) -> Self { |
| 40 | + Self { pool, dns, config } |
| 41 | + } |
| 42 | + |
| 43 | + /// Execute a single HTTP request and return raw response |
| 44 | + pub fn execute( |
| 45 | + &mut self, |
| 46 | + uri: &Uri, |
| 47 | + method: Method, |
| 48 | + custom_headers: &Headers, |
| 49 | + body: Option<&[u8]>, |
| 50 | + ) -> Result<RawResponse, Error> { |
| 51 | + // Extract host information from URI (copy to avoid lifetime issues) |
| 52 | + let host_str = Self::extract_host_from_uri(uri)?; |
| 53 | + let port = Self::extract_port_from_uri(uri); |
| 54 | + let pool_key = PoolKey::new(host_str.clone(), port); |
| 55 | + |
| 56 | + // Get or create socket |
| 57 | + let mut socket = self.get_or_create_socket(&pool_key)?; |
| 58 | + |
| 59 | + // Establish connection |
| 60 | + let connector = Connector::new(&mut socket, self.dns); |
| 61 | + let mut conn = connector.connect(uri, self.config)?; |
| 62 | + |
| 63 | + // Build and send request |
| 64 | + let request_bytes = |
| 65 | + self.build_request(uri, method, &host_str, custom_headers, body)?; |
| 66 | + conn.send_request(&request_bytes)?; |
| 67 | + |
| 68 | + // Read response |
| 69 | + let expectation = if method == Method::Head { |
| 70 | + ResponseBodyExpectation::NoBody |
| 71 | + } else { |
| 72 | + ResponseBodyExpectation::Normal |
| 73 | + }; |
| 74 | + let raw = conn.read_raw_response(expectation)?; |
| 75 | + |
| 76 | + // Handle connection pooling |
| 77 | + self.handle_connection_reuse(conn.is_reusable(), pool_key, socket); |
| 78 | + |
| 79 | + Ok(raw) |
| 80 | + } |
| 81 | + |
| 82 | + /// Extract hostname from URI |
| 83 | + fn extract_host_from_uri(uri: &Uri) -> Result<String, Error> { |
| 84 | + let authority = uri.authority(); |
| 85 | + authority.map_or_else( |
| 86 | + || Ok(String::new()), |
| 87 | + |auth| match auth.host() { |
| 88 | + crate::parser::uri::Host::RegName(name) => Ok(String::from(*name)), |
| 89 | + crate::parser::uri::Host::IpAddr(_) => Err(Error::IpAddressNotSupported), |
| 90 | + }, |
| 91 | + ) |
| 92 | + } |
| 93 | + |
| 94 | + /// Extract port from URI with defaults |
| 95 | + fn extract_port_from_uri(uri: &Uri) -> u16 { |
| 96 | + uri |
| 97 | + .authority() |
| 98 | + .and_then(super::super::parser::uri::Authority::port) |
| 99 | + .unwrap_or_else(|| if uri.scheme() == "https" { 443 } else { 80 }) |
| 100 | + } |
| 101 | + |
| 102 | + /// Get socket from pool or create new one |
| 103 | + fn get_or_create_socket(&mut self, pool_key: &PoolKey) -> Result<S, Error> { |
| 104 | + if self.config.connection_pooling { |
| 105 | + self |
| 106 | + .pool |
| 107 | + .get(pool_key) |
| 108 | + .map_or_else(|| S::new().map_err(Error::Socket), |s| Ok(s)) |
| 109 | + } else { |
| 110 | + S::new().map_err(Error::Socket) |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + /// Build HTTP request bytes |
| 115 | + fn build_request( |
| 116 | + &self, |
| 117 | + uri: &Uri, |
| 118 | + method: Method, |
| 119 | + host_str: &str, |
| 120 | + custom_headers: &Headers, |
| 121 | + body: Option<&[u8]>, |
| 122 | + ) -> Result<Vec<u8>, Error> { |
| 123 | + let mut builder = ParserRequestBuilder::new(method.as_str(), &uri.path_and_query()) |
| 124 | + .header("Host", host_str); |
| 125 | + |
| 126 | + // RFC 9112 Section 9.3: Send Connection: close if pooling is disabled |
| 127 | + if !self.config.connection_pooling { |
| 128 | + builder = builder.header("Connection", "close"); |
| 129 | + } |
| 130 | + |
| 131 | + // Add default headers from config |
| 132 | + if let Some(ref user_agent) = self.config.user_agent { |
| 133 | + builder = builder.header("User-Agent", user_agent.as_str()); |
| 134 | + } |
| 135 | + |
| 136 | + if let Some(ref accept) = self.config.accept { |
| 137 | + builder = builder.header("Accept", accept.as_str()); |
| 138 | + } |
| 139 | + |
| 140 | + // Add custom headers |
| 141 | + for (name, value) in custom_headers { |
| 142 | + builder = builder.header(name.as_str(), value.as_str()); |
| 143 | + } |
| 144 | + |
| 145 | + // Add body if present |
| 146 | + if let Some(body_data) = body { |
| 147 | + builder = builder.body(body_data.to_vec()); |
| 148 | + } |
| 149 | + |
| 150 | + builder.build().map_err(Error::Parse) |
| 151 | + } |
| 152 | + |
| 153 | + /// Handle connection reuse based on pooling config |
| 154 | + fn handle_connection_reuse(&mut self, is_reusable: bool, pool_key: PoolKey, socket: S) { |
| 155 | + if self.config.connection_pooling && is_reusable { |
| 156 | + self.pool.return_connection(pool_key, socket); |
| 157 | + } |
| 158 | + } |
| 159 | +} |
0 commit comments