1 //! The accept loop stops when it is asked to, and the connections that are2 //! running are allowed to finish.3 4 use std::io::{Read, Write};5 use std::net::{TcpListener, TcpStream};6 use std::os::unix::net::{UnixListener, UnixStream};7 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};8 use std::sync::{Arc, mpsc};9 use std::thread;10 use std::time::Duration;11 12 use inf3r_server::{Body, Limits, Response, Status, Stop, serve_unix_until, serve_until};13 14 const LIMITS: Limits = Limits {15 max_head_bytes: 8 << 10,16 max_body_bytes: 1 << 20,17 max_upload_bytes: 4 << 20,18 read_timeout: Duration::from_secs(5),19 head_timeout: Duration::from_secs(5),20 write_timeout: Duration::from_secs(5),21 max_connections: 64,22 };23 24 fn listener() -> TcpListener {25 TcpListener::bind("127.0.0.1:0").expect("a port")26 }27 28 fn call(addr: std::net::SocketAddr) -> TcpStream {29 TcpStream::connect(addr).expect("connect")30 }31 32 #[test]33 fn a_stop_ends_the_loop_and_lets_the_running_connection_finish() {34 let listener = listener();35 let addr = listener.local_addr().expect("an address");36 let stop = Stop::new();37 let entered = Arc::new(AtomicUsize::new(0));38 let release = Arc::new(AtomicBool::new(false));39 let served = Arc::new(AtomicUsize::new(0));40 41 let handler = {42 let entered = Arc::clone(&entered);43 let release = Arc::clone(&release);44 let served = Arc::clone(&served);45 move |_request: inf3r_server::Request| {46 entered.fetch_add(1, Ordering::SeqCst);47 while !release.load(Ordering::SeqCst) {48 thread::sleep(Duration::from_millis(1));49 }50 served.fetch_add(1, Ordering::SeqCst);51 Response::text(Status::OK, "done\n")52 }53 };54 55 let serving = stop.clone();56 let thread = thread::spawn(move || serve_until(listener, LIMITS, &serving, handler));57 58 let mut client = call(addr);59 client60 .write_all(b"GET /healthz HTTP/1.1\r\nHost: x\r\n\r\n")61 .expect("write");62 while entered.load(Ordering::SeqCst) == 0 {63 thread::sleep(Duration::from_millis(1));64 }65 stop.request();66 // The drain waits for the handler, so the serve thread cannot have67 // returned yet.68 thread::sleep(Duration::from_millis(20));69 assert_eq!(served.load(Ordering::SeqCst), 0);70 71 release.store(true, Ordering::SeqCst);72 let mut reply = String::new();73 client.read_to_string(&mut reply).expect("read");74 assert!(reply.starts_with("HTTP/1.1 200"), "{reply}");75 thread.join().expect("the loop").expect("serve");76 assert_eq!(served.load(Ordering::SeqCst), 1);77 }78 79 #[test]80 fn a_stop_with_no_connection_returns_at_once() {81 let listener = listener();82 let stop = Stop::new();83 let serving = stop.clone();84 let thread = thread::spawn(move || {85 serve_until(listener, LIMITS, &serving, |_request| {86 Response::text(Status::OK, "ok\n")87 })88 });89 stop.request();90 thread.join().expect("the loop").expect("serve");91 }92 93 #[test]94 fn the_wait_reports_the_connections_that_outlive_the_budget() {95 let stop = Stop::new();96 let active = stop.enter();97 assert_eq!(stop.wait_for(Duration::from_millis(10)), 1);98 drop(active);99 assert_eq!(stop.wait_for(Duration::from_millis(10)), 0);100 }101 102 #[test]103 fn the_listener_is_closed_when_the_loop_returns() {104 let listener = listener();105 let addr = listener.local_addr().expect("an address");106 let stop = Stop::new();107 let serving = stop.clone();108 let thread = thread::spawn(move || {109 serve_until(listener, LIMITS, &serving, |_request| {110 Response::text(Status::OK, "ok\n")111 })112 });113 stop.request();114 thread.join().expect("the loop").expect("serve");115 assert!(TcpStream::connect(addr).is_err());116 }117 118 #[test]119 fn an_idle_connection_ends_at_the_read_timeout_so_the_drain_returns() {120 let listener = listener();121 let addr = listener.local_addr().expect("an address");122 let mut limits = LIMITS;123 limits.read_timeout = Duration::from_millis(100);124 limits.head_timeout = Duration::from_secs(1);125 let stop = Stop::new();126 let serving = stop.clone();127 let thread = thread::spawn(move || {128 serve_until(listener, limits, &serving, |_request| {129 Response::text(Status::OK, "ok\n")130 })131 });132 133 let mut client = call(addr);134 client135 .set_read_timeout(Some(Duration::from_secs(2)))136 .expect("client timeout");137 // A head with no blank line: the connection is accepted and the parser is138 // waiting for more when the stop arrives.139 client140 .write_all(b"GET / HTTP/1.1\r\n")141 .expect("partial head");142 thread::sleep(Duration::from_millis(50));143 stop.request();144 145 let mut reply = String::new();146 client147 .read_to_string(&mut reply)148 .expect("the timeout reply");149 assert!(150 reply.starts_with("HTTP/1.1 408 Request Timeout\r\n"),151 "{reply}"152 );153 154 let (tx, rx) = mpsc::channel();155 thread::spawn(move || {156 let _ = tx.send(thread.join());157 });158 let joined = rx159 .recv_timeout(Duration::from_secs(2))160 .expect("the drain waited for the idle connection");161 joined.expect("the serve thread").expect("serve");162 }163 164 #[test]165 fn a_wedged_writer_ends_at_the_write_timeout_so_the_drain_returns() {166 let listener = listener();167 let addr = listener.local_addr().expect("an address");168 let mut limits = LIMITS;169 limits.read_timeout = Duration::from_secs(2);170 limits.head_timeout = Duration::from_secs(2);171 limits.write_timeout = Duration::from_millis(50);172 let stop = Stop::new();173 let entered = Arc::new(AtomicBool::new(false));174 let seen = Arc::clone(&entered);175 let body = "x".repeat(32 << 20);176 let handler = move |_request: inf3r_server::Request| {177 seen.store(true, Ordering::SeqCst);178 Response {179 status: Status::OK,180 headers: Vec::new(),181 body: Body::Bytes(body.as_bytes().to_vec()),182 }183 };184 let serving = stop.clone();185 let thread = thread::spawn(move || serve_until(listener, limits, &serving, handler));186 187 let mut client = call(addr);188 client189 .write_all(b"GET / HTTP/1.1\r\n\r\n")190 .expect("the request");191 while !entered.load(Ordering::SeqCst) {192 thread::sleep(Duration::from_millis(1));193 }194 // Do not read. The send buffer fills, and the write blocks until its195 // timeout. The stop must not wait for the 30 s drain ceiling.196 thread::sleep(Duration::from_millis(100));197 stop.request();198 199 let (tx, rx) = mpsc::channel();200 thread::spawn(move || {201 let _ = tx.send(thread.join());202 });203 let joined = rx204 .recv_timeout(Duration::from_secs(2))205 .expect("the drain waited for the wedged writer");206 joined.expect("the serve thread").expect("serve");207 }208 209 #[test]210 fn the_connection_cap_is_shared_by_both_listeners() {211 let listener = listener();212 let addr = listener.local_addr().expect("an address");213 let socket = std::env::temp_dir().join(format!("inf3r-cap-{}.sock", std::process::id()));214 let _ = std::fs::remove_file(&socket);215 let unix = UnixListener::bind(&socket).expect("unix listener");216 let mut limits = LIMITS;217 limits.max_connections = 1;218 let stop = Stop::new();219 let entered = Arc::new(AtomicBool::new(false));220 let release = Arc::new(AtomicBool::new(false));221 222 let tcp_handler = {223 let entered = Arc::clone(&entered);224 let release = Arc::clone(&release);225 move |_request: inf3r_server::Request| {226 entered.store(true, Ordering::SeqCst);227 while !release.load(Ordering::SeqCst) {228 thread::sleep(Duration::from_millis(1));229 }230 Response::text(Status::OK, "slow\n")231 }232 };233 let unix_handler = {234 let entered = Arc::clone(&entered);235 let release = Arc::clone(&release);236 move |_request: inf3r_server::Request| {237 entered.store(true, Ordering::SeqCst);238 while !release.load(Ordering::SeqCst) {239 thread::sleep(Duration::from_millis(1));240 }241 Response::text(Status::OK, "slow\n")242 }243 };244 245 let tcp_stop = stop.clone();246 let tcp_thread = thread::spawn(move || serve_until(listener, limits, &tcp_stop, tcp_handler));247 let unix_stop = stop.clone();248 let unix_thread =249 thread::spawn(move || serve_unix_until(unix, limits, &unix_stop, unix_handler));250 251 let mut first = call(addr);252 first253 .write_all(b"GET / HTTP/1.1\r\n\r\n")254 .expect("first request");255 while !entered.load(Ordering::SeqCst) {256 thread::sleep(Duration::from_millis(1));257 }258 259 let mut second = UnixStream::connect(&socket).expect("unix connect");260 second261 .write_all(b"GET / HTTP/1.1\r\n\r\n")262 .expect("second request");263 let mut busy = String::new();264 second.read_to_string(&mut busy).expect("busy reply");265 release.store(true, Ordering::SeqCst);266 267 let mut served = String::new();268 first.read_to_string(&mut served).expect("first reply");269 assert!(served.starts_with("HTTP/1.1 200 OK\r\n"), "{served}");270 assert!(271 busy.starts_with("HTTP/1.1 503 Service Unavailable\r\n"),272 "{busy}"273 );274 stop.request();275 tcp_thread.join().expect("tcp loop").expect("serve");276 unix_thread.join().expect("unix loop").expect("serve");277 let _ = std::fs::remove_file(&socket);278 }