Skip to content

Commit d50eeeb

Browse files
insideTheFluxclaude
authored andcommitted
Control port: bound the close drain in total; the reset test waits for the rejection
close_gracefully read with a 500 ms timeout per read but no overall limit, so a local client sending one byte every few hundred milliseconds kept the drain (and its connection slot) going until it had sent MAX_LINE. Each read now waits at most the time left of DRAIN_TIME (1 s). New test a_closing_connection_is_not_held_open_by_a_trickling_peer: without the limit it drains for 10 s. tcp_connection_is_closed_after_junk no longer sleeps before its second write: it reads the reply and the rejection first, so the server has rejected the junk before the next line is sent. It still pauses before the last read so that a reset can arrive. Without close_gracefully it fails with os error 10053 on Windows. From CodeRabbit's review of storytold#2723. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PtjHGt5gnCHXgLt4NbGorf
1 parent 869fe8a commit d50eeeb

1 file changed

Lines changed: 50 additions & 12 deletions

File tree

‎apps/lightcraft/src/control_server.rs‎

Lines changed: 50 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,9 @@ fn serve(stream: TcpStream, tx: &Sender<ControlRequest>, ctx: &egui::Context, id
9696
});
9797
}
9898

99+
/// The longest a closing connection is drained, however slowly its peer keeps sending.
100+
const DRAIN_TIME: Duration = Duration::from_secs(1);
101+
99102
/// [`serve_lines`] on a socket, then close it so the peer reads every reply.
100103
fn serve_stream(stream: TcpStream, handle: impl FnMut(String, Value) -> Option<Value>) {
101104
serve_lines(&stream, &stream, handle);
@@ -105,15 +108,21 @@ fn serve_stream(stream: TcpStream, handle: impl FnMut(String, Value) -> Option<V
105108
/// Close a connection the server is done with without destroying its last reply. A socket closed
106109
/// while the peer's later lines are unread, or arrive after it, answers them with a reset, and a
107110
/// reset can discard the replies the peer has not read yet (on Windows it does): the client sees
108-
/// "connection reset" instead of why. Send FIN, then read and drop what is left (bounded in bytes
109-
/// and time) before closing. From #1970 (LochLogic).
111+
/// "connection reset" instead of why. Send FIN, then read and drop what is left (at most
112+
/// [`MAX_LINE`] bytes, 500 ms per read and [`DRAIN_TIME`] in all) before closing. From #1970
113+
/// (LochLogic).
110114
fn close_gracefully(stream: &TcpStream) {
111115
let _ = stream.shutdown(std::net::Shutdown::Write);
112-
let _ = stream.set_read_timeout(Some(Duration::from_millis(500)));
116+
let start = std::time::Instant::now();
113117
let mut sink = [0u8; 8192];
114118
let mut left = MAX_LINE;
115119
let mut reader = stream;
116120
while left > 0 {
121+
// a peer that keeps trickling bytes must not hold the connection slot past DRAIN_TIME
122+
let wait = DRAIN_TIME.saturating_sub(start.elapsed()).min(Duration::from_millis(500));
123+
if wait.is_zero() || stream.set_read_timeout(Some(wait)).is_err() {
124+
break;
125+
}
117126
match reader.read(&mut sink) {
118127
Ok(0) | Err(_) => break,
119128
Ok(n) => left = left.saturating_sub(n),
@@ -532,18 +541,47 @@ mod tests {
532541
let mut c = TcpStream::connect(addr).unwrap();
533542
c.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
534543
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n").unwrap();
544+
let mut replies = BufReader::new(c.try_clone().unwrap());
545+
let (mut first, mut second) = (String::new(), String::new());
546+
replies.read_line(&mut first).unwrap();
547+
replies.read_line(&mut second).unwrap();
548+
assert!(first.contains("\"id\":7"), "{first}");
549+
assert!(second.contains("closing the connection"), "{second}");
535550
// A client that keeps sending after the junk: its next line reaches the server after the
536-
// rejection. A socket closed by then answers that line with a reset, and on Windows the reset
537-
// discarded the replies the client had not read yet (os error 10054).
538-
std::thread::sleep(Duration::from_millis(100));
551+
// rejection. A socket closed by then answers that line with a reset, which the client reads
552+
// as "connection reset" (os error 10053 / 10054 on Windows) instead of the end of the
553+
// replies. The pause lets a reset arrive before the read.
539554
c.write_all(b"{\"method\":\"y\"}\n").unwrap();
540555
std::thread::sleep(Duration::from_millis(100));
541-
let mut text = String::new();
542-
c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection
556+
let mut rest = String::new();
557+
let read = replies.read_to_string(&mut rest);
543558
server.join().unwrap();
544-
let lines: Vec<&str> = text.lines().collect();
545-
assert_eq!(lines.len(), 2, "{text}");
546-
assert!(lines[0].contains("\"id\":7"));
547-
assert!(lines[1].contains("closing the connection"));
559+
assert!(read.is_ok(), "the close must be clean, not a reset: {read:?}");
560+
assert_eq!(rest, "", "nothing follows the rejection");
561+
}
562+
563+
#[test]
564+
fn a_closing_connection_is_not_held_open_by_a_trickling_peer() {
565+
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
566+
let addr = listener.local_addr().unwrap();
567+
let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
568+
let server_done = Arc::clone(&done);
569+
let server = std::thread::spawn(move || {
570+
let (s, _) = listener.accept().unwrap();
571+
let t0 = std::time::Instant::now();
572+
close_gracefully(&s);
573+
server_done.store(true, Ordering::SeqCst);
574+
t0.elapsed()
575+
});
576+
let mut c = TcpStream::connect(addr).unwrap();
577+
// one byte every 100 ms: each read returns well within its 500 ms timeout
578+
for _ in 0..100 {
579+
if done.load(Ordering::SeqCst) || c.write_all(b"x").is_err() {
580+
break;
581+
}
582+
std::thread::sleep(Duration::from_millis(100));
583+
}
584+
let drained = server.join().unwrap();
585+
assert!(drained < DRAIN_TIME + Duration::from_secs(1), "drained for {drained:?}");
548586
}
549587
}

0 commit comments

Comments
 (0)