Skip to content

Commit bd13e30

Browse files
committed
Shutdown HttpServer explicitly to avoid panics
1 parent 52b8d96 commit bd13e30

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

lightning-block-sync/src/http_clients.rs

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -595,7 +595,8 @@ mod tests {
595595
/// Server for handling HTTP client requests with a stock response.
596596
struct HttpServer {
597597
address: std::net::SocketAddr,
598-
_handler: std::thread::JoinHandle<()>,
598+
handler: std::thread::JoinHandle<()>,
599+
shutdown: std::sync::Arc<std::sync::atomic::AtomicBool>,
599600
}
600601

601602
/// Body of HTTP response messages.
@@ -643,26 +644,34 @@ mod tests {
643644
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
644645
let address = listener.local_addr().unwrap();
645646

646-
let _handler = std::thread::spawn(move || {
647+
let shutdown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
648+
let shutdown_signaled = std::sync::Arc::clone(&shutdown);
649+
let handler = std::thread::spawn(move || {
647650
let (mut stream, _) = listener.accept().unwrap();
651+
stream.set_write_timeout(Some(Duration::from_secs(1))).unwrap();
652+
648653
let lines_read = std::io::BufReader::new(&stream)
649654
.lines()
650655
.take_while(|line| !line.as_ref().unwrap().is_empty())
651656
.count();
652657
if lines_read == 0 { return; }
653658

654659
for chunk in response.as_bytes().chunks(16) {
655-
match stream.take_error().unwrap() {
656-
None => {
657-
stream.write(chunk).unwrap();
658-
stream.flush().unwrap();
659-
},
660-
Some(_) => break,
660+
if shutdown_signaled.load(std::sync::atomic::Ordering::SeqCst) {
661+
break;
662+
} else {
663+
stream.write(chunk).unwrap();
664+
stream.flush().unwrap();
661665
}
662666
}
663667
});
664668

665-
Self { address, _handler }
669+
Self { address, handler, shutdown }
670+
}
671+
672+
fn shutdown(self) {
673+
self.shutdown.store(true, std::sync::atomic::Ordering::SeqCst);
674+
self.handler.join().unwrap();
666675
}
667676

668677
fn endpoint(&self) -> HttpEndpoint {
@@ -810,6 +819,7 @@ mod tests {
810819
},
811820
Ok(_) => panic!("Expected error"),
812821
}
822+
server.shutdown();
813823
}
814824

815825
#[tokio::test]

0 commit comments

Comments
 (0)