From d3fd092c2b1fe9f1a1eebe7123ec0b4b56c4f622 Mon Sep 17 00:00:00 2001 From: Nera contributors Date: Tue, 24 Nov 2026 15:08:35 +0000 Subject: [PATCH] fix(tcp): honor passive receive timeouts Programs receive a timeout result when their requested wait expires. A zero wait checks for data without pausing. Bytes already received remain available after a timeout, including when delivery switches modes. --- CHANGELOG.md | 9 ++ FEATURES.md | 2 +- crates/nera-runtime/src/ffi/gen_tcp.rs | 119 +++++++++------------ crates/nera-runtime/src/io_pool.rs | 5 + crates/nera-runtime/src/process.rs | 28 ++--- crates/nera-runtime/src/reactor.rs | 140 +++++++++++++++++++----- crates/nera-runtime/src/socket.rs | 142 +++++++++++++++++++++---- tests/README.md | 16 +++ tests/tcp_recv_timeout.erl | 70 ++++++++++++ tests/tcp_recv_timeout_active.erl | 84 +++++++++++++++ 10 files changed, 483 insertions(+), 132 deletions(-) create mode 100644 tests/tcp_recv_timeout.erl create mode 100644 tests/tcp_recv_timeout_active.erl diff --git a/CHANGELOG.md b/CHANGELOG.md index c0a444b..766145a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ All notable milestones for the nera project are documented in this file. +## TCP receive deadlines + +- `gen_tcp:recv/3` now returns `{error, timeout}` when its finite timeout + expires, for both available-data and exact-length reads. Previously an idle + connection could wait forever. A timeout leaves the connection open and + preserves bytes already read for the next receive. +- A zero timeout polls without waiting; `infinity` and `gen_tcp:recv/2` still + wait without a deadline. + ## Formatter keeps named fun names unquoted - `nera fmt` now prints a named fun's variable name as written, so diff --git a/FEATURES.md b/FEATURES.md index a985fc4..731f3ca 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -380,7 +380,7 @@ functions as compiled Erlang in `erlang/stdlib/maps.erl`. |-----------------------|--------|----------------------------------------------| | listen/2 | ✅ | Supports `{packet, line}`, `binary` options | | accept/1 | ✅ | Inherits listener socket options | -| recv/2,3 | ✅ | Blocking recv with optional timeout | +| recv/2,3 | ✅ | Receive with finite millisecond timeout, zero polling, or infinity | | send/2 | ✅ | Binary, iolist (nested lists/binaries) | | close/1 | ✅ | | | connect/3 | ✅ | | diff --git a/crates/nera-runtime/src/ffi/gen_tcp.rs b/crates/nera-runtime/src/ffi/gen_tcp.rs index 2011086..49efc4e 100644 --- a/crates/nera-runtime/src/ffi/gen_tcp.rs +++ b/crates/nera-runtime/src/ffi/gen_tcp.rs @@ -281,7 +281,7 @@ pub unsafe extern "C" fn nera_rt_gen_tcp_recv( sock_term: u64, length_term: u64, ) -> u64 { - nera_rt_gen_tcp_recv_3(ctx, sock_term, length_term, ErlTerm::nil().0) + nera_rt_gen_tcp_recv_3(ctx, sock_term, length_term, ErlTerm::atom(global_atom_table().intern("infinity")).0) } /// gen_tcp:send(Sock, Data) -> ok | {error, Reason} @@ -585,7 +585,7 @@ pub unsafe extern "C" fn nera_rt_gen_tcp_close( } /// gen_tcp:recv/3 — receive data from a socket with timeout (ms). -/// Timeout is currently ignored (acts like infinity). +/// Finite timeouts use a monotonic deadline shared by all partial reads. /// If length > 0, reads exactly that many bytes. If length == 0, reads /// any available data (same as recv/2). #[no_mangle] @@ -593,7 +593,7 @@ pub unsafe extern "C" fn nera_rt_gen_tcp_recv_3( ctx: *mut ProcessContext, sock_term: u64, length_term: u64, - _timeout_term: u64, + timeout_term: u64, ) -> u64 { let Some(handle) = crate::socket::SocketHandle::from_term(ErlTerm(sock_term)) else { return socket_error(ctx, crate::atom_table::ATOM_ENOENT); @@ -601,6 +601,22 @@ pub unsafe extern "C" fn nera_rt_gen_tcp_recv_3( let Some(length) = recv_length(ErlTerm(length_term)) else { return raise_badarg(ctx); }; + let timeout = ErlTerm(timeout_term); + let deadline = if timeout == ErlTerm::atom(global_atom_table().intern("infinity")) { + None + } else { + let Some(ms) = timeout.as_small_int().and_then(|ms| u32::try_from(ms).ok()) else { + return raise_badarg(ctx); + }; + Some(std::time::Instant::now() + std::time::Duration::from_millis(u64::from(ms))) + }; + #[cfg(not(mio_supported))] + if let Some(deadline) = deadline { + let poll_only = timeout.as_small_int() == Some(0); + return submit_io_and_wait(ctx, Box::new(move || { + crate::socket::recv_with_deadline(handle, length, deadline, poll_only) + })); + } let self_pid = if !ctx.is_null() { unsafe { (*ctx).pid } } else { crate::process::ProcessId::new(0) }; if length > 0 { @@ -608,72 +624,33 @@ pub unsafe extern "C" fn nera_rt_gen_tcp_recv_3( #[cfg(mio_supported)] { - // Try reading the exact amount non-blocking first. - use std::io::Read; - match crate::socket::get_stream(handle) { - Ok(stream) => { - let mut buf = Vec::with_capacity(len.min(4096)); - let mut tmp = [0u8; 4096]; - let read_len = len.min(tmp.len()); - match (&*stream).read(&mut tmp[..read_len]) { - Ok(0) => { - with_ctx_heap(ctx, |heap| { - let error_atom = ErlTerm::atom(ATOM_ERROR); - let closed_atom = ErlTerm::atom( - global_atom_table().intern("closed"), - ); - heap.alloc_tuple(&[error_atom, closed_atom]).0 - }) - } - Ok(n) => { - buf.extend_from_slice(&tmp[..n]); - if buf.len() >= len { - buf.truncate(len); - return with_ctx_heap(ctx, |heap| { - let ok_atom = ErlTerm::atom(ATOM_OK); - let binary = heap.alloc_binary_auto(&buf); - heap.alloc_tuple(&[ok_atom, binary]).0 - }); - } - // Got some bytes but not enough — reactor - // will accumulate the rest. - submit_to_reactor_and_wait( - ctx, - crate::reactor::PendingOp::RecvExact { - pid: self_pid, - stream_handle: handle, - target_len: len, - buf, - }, - ) - } - Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => { - submit_to_reactor_and_wait( - ctx, - crate::reactor::PendingOp::RecvExact { - pid: self_pid, - stream_handle: handle, - target_len: len, - buf: Vec::new(), - }, - ) - } - Err(e) => { - with_ctx_heap(ctx, |heap| { - let error_atom = ErlTerm::atom(ATOM_ERROR); - let reason_atom = ErlTerm::atom(io_error_to_atom_id(&e)); - heap.alloc_tuple(&[error_atom, reason_atom]).0 - }) + let mut buf = Vec::with_capacity(len.min(4096)); + let mut tmp = [0u8; 4096]; + loop { + let read_len = (len - buf.len()).min(tmp.len()); + match crate::socket::recv_into(handle, &mut tmp[..read_len]) { + Ok(0) => return socket_error(ctx, global_atom_table().intern("closed")), + Ok(n) => { + buf.extend_from_slice(&tmp[..n]); + if buf.len() == len { + return with_ctx_heap(ctx, |heap| { + let binary = heap.alloc_binary_auto(&buf); + heap.alloc_tuple(&[ErlTerm::atom(ATOM_OK), binary]).0 + }); } + // A zero-timeout poll drains all currently available chunks, not just 4096 bytes. + if timeout.as_small_int() == Some(0) { continue; } } + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {} + Err(e) => return socket_error(ctx, io_error_to_atom_id(&e)), } - Err(e) => { - with_ctx_heap(ctx, |heap| { - let error_atom = ErlTerm::atom(ATOM_ERROR); - let reason_atom = ErlTerm::atom(io_error_to_atom_id(&e)); - heap.alloc_tuple(&[error_atom, reason_atom]).0 - }) + if deadline.is_some_and(|deadline| std::time::Instant::now() >= deadline) { + crate::socket::restore_recv_buffer(handle, buf); + return socket_error(ctx, global_atom_table().intern("timeout")); } + return submit_to_reactor_and_wait(ctx, crate::reactor::PendingOp::RecvExact { + pid: self_pid, stream_handle: handle, target_len: len, buf, deadline, + }); } } @@ -700,11 +677,15 @@ pub unsafe extern "C" fn nera_rt_gen_tcp_recv_3( }) } Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => { + if deadline.is_some_and(|deadline| std::time::Instant::now() >= deadline) { + return socket_error(ctx, global_atom_table().intern("timeout")); + } submit_to_reactor_and_wait( ctx, crate::reactor::PendingOp::Recv { pid: self_pid, stream_handle: handle, + deadline, }, ) } @@ -982,7 +963,7 @@ pub unsafe extern "C" fn nera_rt_inet_setopts( // (preventing edge-triggered kqueue spin when the // reactor registers the fd). let mut peek_buf = [0u8; 4096]; - match crate::socket::peek_recv_fd(fd, &mut peek_buf) { + match crate::socket::peek_recv_fd(handle, fd, &mut peek_buf) { Ok(0) => { // Connection closed — fast path, no reactor involved deliver_tcp_closed_to_self(ctx, handle); @@ -994,7 +975,7 @@ pub unsafe extern "C" fn nera_rt_inet_setopts( // Complete line available — consume and deliver it // with its "\n" or "\r\n" terminator, as BEAM does. let line_len = pos + 1; - if crate::socket::consume_exact_fd(fd, &mut peek_buf[..line_len]).is_ok() { + if crate::socket::consume_exact_fd(handle, fd, &mut peek_buf[..line_len]).is_ok() { crate::reactor::COUNTER_SETOPTS_FASTPATH.fetch_add( 1, std::sync::atomic::Ordering::Relaxed, ); @@ -1021,7 +1002,7 @@ pub unsafe extern "C" fn nera_rt_inet_setopts( // into the line buffer so the kernel buffer // drains (avoids kqueue spin on re-register). let mut consume_buf = vec![0u8; n]; - let _ = crate::socket::consume_exact_fd(fd, &mut consume_buf); + let _ = crate::socket::consume_exact_fd(handle, fd, &mut consume_buf); crate::socket::set_line_buffer(handle, peek_buf[..n].to_vec()); // Register with reactor for more data. crate::socket::set_active_local(handle, active); @@ -1048,7 +1029,7 @@ pub unsafe extern "C" fn nera_rt_inet_setopts( } else { // Raw mode: try single read let mut read_buf = [0u8; 4096]; - match crate::socket::consume_fd(fd, &mut read_buf) { + match crate::socket::recv_into(handle, &mut read_buf) { Ok(0) => { // Connection closed — fast path, no reactor involved deliver_tcp_closed_to_self(ctx, handle); diff --git a/crates/nera-runtime/src/io_pool.rs b/crates/nera-runtime/src/io_pool.rs index 1c64c13..562aae5 100644 --- a/crates/nera-runtime/src/io_pool.rs +++ b/crates/nera-runtime/src/io_pool.rs @@ -261,6 +261,7 @@ pub(crate) fn wake_process_with_result(pid: ProcessId, result: IoResult) { /// - `OkBytes(b)` → `{ok, <>}` /// - `OkHandle(h)` → `{ok, H}` (small int) /// - `Closed` → `{error, closed}` +/// - `Timeout` → `{error, timeout}` /// - `Err(e)` → `{error, Reason}` where Reason is a POSIX atom pub(crate) fn io_result_to_term(heap: &mut crate::heap::ProcessHeap, result: IoResult) -> ErlTerm { match result { @@ -279,6 +280,10 @@ pub(crate) fn io_result_to_term(heap: &mut crate::heap::ProcessHeap, result: IoR ErlTerm::atom(ATOM_ERROR), ErlTerm::atom(crate::atom_table::ATOM_CLOSED), ]), + IoResult::Timeout => heap.alloc_tuple(&[ + ErlTerm::atom(ATOM_ERROR), + ErlTerm::atom(crate::atom_table::global_atom_table().intern("timeout")), + ]), IoResult::Err(e) => { let error_atom = ErlTerm::atom(ATOM_ERROR); let reason_atom = ErlTerm::atom(io_error_to_atom(e)); diff --git a/crates/nera-runtime/src/process.rs b/crates/nera-runtime/src/process.rs index bafd934..c2a55c4 100644 --- a/crates/nera-runtime/src/process.rs +++ b/crates/nera-runtime/src/process.rs @@ -680,30 +680,28 @@ fn handle_active_read_on_worker( // ── Line mode: peek + consume_exact with per-socket line buffer ── // // Uses peek to find newlines, then consume_exact to remove only - // the delivered line from the kernel buffer. Excess data (e.g. a - // data block after the command line) stays in the kernel for - // subsequent gen_tcp:recv calls in raw mode. + // the delivered line from retained or kernel bytes. Excess data (e.g. a + // data block after the command line) stays in the retained queue or + // kernel for subsequent gen_tcp:recv calls in raw mode. // - // When a partial line has no newline, the partial data is consumed - // from the kernel into a per-socket line buffer so the fd is no - // longer readable — preventing edge-triggered kqueue spin. The - // line buffer is prepended on the next readability event. + // Accumulating a partial line also drains kernel readiness, preventing + // edge-triggered kqueue spin. The partial prefix must precede bytes + // from the next notification, whether retained or newly received. let mut line_buf = crate::socket::take_line_buffer(stream_handle); let mut peek_buf = [0u8; 8192]; let mut got_eof = false; loop { - match crate::socket::peek_recv_fd(fd, &mut peek_buf) { + match crate::socket::peek_recv_fd(stream_handle, fd, &mut peek_buf) { Ok(0) => { got_eof = true; break; } Ok(n) => { if let Some(ppos) = peek_buf[..n].iter().position(|&b| b == b'\n') { - // Newline found in peeked data — consume up to and - // including the newline, leaving excess in kernel. + // Leave bytes after this newline available for the next receive. let line_len = ppos + 1; let mut tmp = vec![0u8; line_len]; - let _ = crate::socket::consume_exact_fd(fd, &mut tmp); + let _ = crate::socket::consume_exact_fd(stream_handle, fd, &mut tmp); // Build the line: line_buf (partial) + peek_buf[..=ppos]. // It keeps its "\n" or "\r\n" terminator, as BEAM @@ -718,7 +716,7 @@ fn handle_active_read_on_worker( if active_mode == ActiveMode::Once { crate::socket::set_active_local(stream_handle, ActiveMode::Passive); - // line_buf is empty; remaining data in kernel. + // Leave later bytes buffered for the next active-once arm. break; } // active == true: continue loop for more lines @@ -726,7 +724,7 @@ fn handle_active_read_on_worker( // No newline — consume all peeked data into line_buf // so the kernel buffer drains (prevents kqueue spin). let mut tmp = vec![0u8; n]; - let _ = crate::socket::consume_exact_fd(fd, &mut tmp); + let _ = crate::socket::consume_exact_fd(stream_handle, fd, &mut tmp); line_buf.extend_from_slice(&peek_buf[..n]); break; // wait for next readability event } @@ -769,7 +767,7 @@ fn handle_active_read_on_worker( // ── Raw mode: consume whatever is available ── let mut buf = [0u8; 4096]; loop { - match crate::socket::consume_fd(fd, &mut buf) { + match crate::socket::recv_into(stream_handle, &mut buf) { Ok(0) => { build_tcp_closed(proc, stream_handle); crate::socket::set_active_local(stream_handle, ActiveMode::Passive); @@ -921,6 +919,8 @@ pub enum IoResult { Ok, /// A socket was closed while its operation was pending. Closed, + /// A TCP receive deadline elapsed without completing the read. + Timeout, /// I/O error. Err(std::io::Error), } diff --git a/crates/nera-runtime/src/reactor.rs b/crates/nera-runtime/src/reactor.rs index 431de5c..aefb5c3 100644 --- a/crates/nera-runtime/src/reactor.rs +++ b/crates/nera-runtime/src/reactor.rs @@ -22,6 +22,7 @@ use std::io; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; use crossbeam_channel::{Receiver, Sender}; use mio::unix::SourceFd; @@ -92,6 +93,7 @@ pub enum PendingOp { Recv { pid: ProcessId, stream_handle: crate::socket::SocketHandle, + deadline: Option, }, /// Waiting to read exactly `target_len` bytes. RecvExact { @@ -99,6 +101,7 @@ pub enum PendingOp { stream_handle: crate::socket::SocketHandle, target_len: usize, buf: Vec, + deadline: Option, }, /// Waiting to read until a newline character. RecvLine { @@ -116,6 +119,13 @@ pub enum PendingOp { } impl PendingOp { + fn deadline(&self) -> Option { + match self { + Self::Recv { deadline, .. } | Self::RecvExact { deadline, .. } => *deadline, + _ => None, + } + } + /// The process ID that owns this pending operation. fn pid(&self) -> ProcessId { match self { @@ -344,13 +354,13 @@ impl IoReactor { /// catches workers that raced in between our last `try_recv` and the /// clear (saw `true`, skipped their wake, left the cmd in the channel). fn run(&mut self) { - self.run_with_poll(|poll, events| { - poll.poll(events, Some(std::time::Duration::from_millis(100))) + self.run_with_poll(|poll, events, timeout| { + poll.poll(events, Some(timeout)) }); } // Keep the real command loop observable without a wall-clock assertion. - fn run_with_poll(&mut self, mut poll: impl FnMut(&mut Poll, &mut Events) -> std::io::Result<()>) { + fn run_with_poll(&mut self, mut poll: impl FnMut(&mut Poll, &mut Events, Duration) -> std::io::Result<()>) { let mut events = Events::with_capacity(256); loop { if self.shutdown.load(Ordering::SeqCst) { @@ -377,6 +387,11 @@ impl IoReactor { return; } + self.expire_receives(); + let timeout = self.pending.values().filter_map(PendingOp::deadline) + .map(|deadline| deadline.saturating_duration_since(Instant::now())) + .fold(Duration::from_millis(100), Duration::min); + // About to block: publish wake_pending=false so the next worker // push triggers a fresh wake. Re-check the channel for racers // that pushed between our try_recv and the store. @@ -390,7 +405,7 @@ impl IoReactor { } // Poll for I/O events. - match poll(&mut self.poll, &mut events) { + match poll(&mut self.poll, &mut events, timeout) { Ok(_) => {} Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, Err(e) => { @@ -406,6 +421,25 @@ impl IoReactor { } } + fn expire_receives(&mut self) { + let now = Instant::now(); + let expired: Vec = self.pending.iter() + .filter(|(_, op)| op.deadline().is_some_and(|deadline| deadline <= now)) + .map(|(token, _)| *token).collect(); + for token in expired { + let op = self.pending.remove(&token).expect("expired receive"); + PENDING_COUNT.fetch_sub(1, Ordering::Relaxed); + let pid = op.pid(); + let handle = op.socket_handle(); + if let PendingOp::RecvExact { buf, .. } = op { + // A timed-out exact read must leave its consumed prefix for the next receive. + crate::socket::restore_recv_buffer(handle, buf); + } + self.deregister_fd(handle); + wake_process_with_result(pid, IoResult::Timeout); + } + } + /// Drain all queued commands. Does NOT touch `wake_pending` — the main /// `run` loop owns that flag, holding it `true` for the entire active /// phase of each iteration and only clearing it right before @@ -445,6 +479,9 @@ impl IoReactor { &mut SourceFd(&fd), token, Interest::READABLE, ); } + if crate::socket::has_recv_buffer(stream_handle) { + self.handle_event(token); + } } } ReactorCommand::Shutdown => { @@ -801,14 +838,14 @@ impl IoReactor { }; PENDING_COUNT.fetch_sub(1, Ordering::Relaxed); - if let PendingOp::Recv { pid, stream_handle } = op { + if let PendingOp::Recv { pid, stream_handle, deadline } = op { match crate::socket::try_recv(stream_handle) { Ok(bytes) => { self.deregister_fd(stream_handle); wake_process_with_result(pid, IoResult::OkBytes(bytes)); } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { - self.pending.insert(token, PendingOp::Recv { pid, stream_handle }); + self.pending.insert(token, PendingOp::Recv { pid, stream_handle, deadline }); PENDING_COUNT.fetch_add(1, Ordering::Relaxed); } Err(e) => { @@ -826,22 +863,12 @@ impl IoReactor { }; PENDING_COUNT.fetch_sub(1, Ordering::Relaxed); - if let PendingOp::RecvExact { pid, stream_handle, target_len, mut buf } = op { - let stream = match crate::socket::get_stream(stream_handle) { - Ok(s) => s, - Err(e) => { - self.deregister_fd(stream_handle); - wake_process_with_result(pid, IoResult::Err(e)); - return; - } - }; - - use std::io::Read; + if let PendingOp::RecvExact { pid, stream_handle, target_len, mut buf, deadline } = op { let mut tmp = [0u8; 4096]; loop { let remaining = target_len - buf.len(); let read_len = remaining.min(tmp.len()); - match (&*stream).read(&mut tmp[..read_len]) { + match crate::socket::recv_into(stream_handle, &mut tmp[..read_len]) { Ok(0) => { self.deregister_fd(stream_handle); let e = io::Error::new(io::ErrorKind::UnexpectedEof, "connection closed"); @@ -856,12 +883,17 @@ impl IoReactor { wake_process_with_result(pid, IoResult::OkBytes(buf)); return; } - // Continue draining until WouldBlock or enough data. + if deadline.is_some_and(|deadline| Instant::now() >= deadline) { + crate::socket::restore_recv_buffer(stream_handle, buf); + self.deregister_fd(stream_handle); + wake_process_with_result(pid, IoResult::Timeout); + return; + } } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { // Partial accumulation — re-insert and wait for more. self.pending.insert(token, PendingOp::RecvExact { - pid, stream_handle, target_len, buf, + pid, stream_handle, target_len, buf, deadline, }); PENDING_COUNT.fetch_add(1, Ordering::Relaxed); return; @@ -904,7 +936,7 @@ impl IoReactor { const MAX_LINE: usize = 300_000; let mut peek_buf = [0u8; 4096]; loop { - match crate::socket::peek_recv_fd(fd, &mut peek_buf) { + match crate::socket::peek_recv_fd(stream_handle, fd, &mut peek_buf) { Ok(0) => { self.deregister_fd(stream_handle); if buf.is_empty() { @@ -917,8 +949,8 @@ impl IoReactor { } Ok(n) => { if let Some(pos) = peek_buf[..n].iter().position(|&b| b == b'\n') { - // Found newline — consume_exact pos+1 bytes from kernel. - match crate::socket::consume_exact_fd(fd, &mut peek_buf[..pos + 1]) { + // Leave bytes after this newline available for the next receive. + match crate::socket::consume_exact_fd(stream_handle, fd, &mut peek_buf[..pos + 1]) { Ok(()) => { buf.extend_from_slice(&peek_buf[..pos]); if buf.last() == Some(&b'\r') { @@ -935,7 +967,7 @@ impl IoReactor { return; } // No newline — consume_exact all peeked bytes, append to buf. - match crate::socket::consume_exact_fd(fd, &mut peek_buf[..n]) { + match crate::socket::consume_exact_fd(stream_handle, fd, &mut peek_buf[..n]) { Ok(()) => { buf.extend_from_slice(&peek_buf[..n]); } @@ -1069,6 +1101,12 @@ impl IoReactor { self.active_handle_to_token.insert(stream_handle, token); PENDING_COUNT.fetch_add(1, Ordering::Relaxed); } + // epoll/kqueue cannot signal bytes retained outside the kernel receive buffer. + if crate::socket::has_recv_buffer(stream_handle) { + if let Some(&token) = self.active_handle_to_token.get(&stream_handle) { + self.handle_event(token); + } + } } fn handle_deregister_active(&mut self, handle: crate::socket::SocketHandle) { @@ -1230,6 +1268,56 @@ mod tests { }); } + #[test] + fn expired_receive_releases_registration_and_preserves_prefix() { + if isolate_active_registration("expired_receive_releases_registration_and_preserves_prefix") { return; } + let (_handle, mut reactor) = active_registration_fixture(); + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let socket = crate::socket::connect("127.0.0.1", listener.local_addr().unwrap().port()).unwrap(); + let (mut peer, _) = listener.accept().unwrap(); + use std::io::Write; + let token = Token(NEXT_TOKEN.fetch_add(1, Ordering::Relaxed)); + reactor.register_pending(token, PendingOp::Recv { + pid: ProcessId::new(1), stream_handle: socket, deadline: Some(Instant::now()), + }); + assert!(reactor.pending.contains_key(&token)); + reactor.expire_receives(); + assert!(reactor.pending.is_empty()); + assert!(!reactor.handle_to_token.contains_key(&socket)); + reactor.register_pending(token, PendingOp::RecvExact { + pid: ProcessId::new(1), stream_handle: socket, target_len: 4, + buf: Vec::new(), deadline: None, + }); + peer.write_all(b"ab").unwrap(); + let mut events = Events::with_capacity(8); + reactor.poll.poll(&mut events, Some(Duration::from_secs(3))).unwrap(); + assert!(events.iter().any(|event| event.token() == token)); + reactor.handle_event(token); + let Some(PendingOp::RecvExact { buf, deadline, .. }) = reactor.pending.get_mut(&token) else { + panic!("incomplete read must remain pending"); + }; + assert_eq!(buf, b"ab"); + *deadline = Some(Instant::now()); + reactor.expire_receives(); + assert!(reactor.pending.is_empty()); + assert!(!reactor.handle_to_token.contains_key(&socket)); + assert_eq!(PENDING_COUNT.load(Ordering::Relaxed), 0); + let mut bytes = [0; 2]; + assert_eq!(crate::socket::recv_into(socket, &mut bytes).unwrap(), 2); + assert_eq!(&bytes, b"ab"); + reactor.register_pending(token, PendingOp::Recv { + pid: ProcessId::new(1), stream_handle: socket, deadline: None, + }); + assert!(reactor.pending.contains_key(&token)); + peer.write_all(b"cd").unwrap(); + reactor.poll.poll(&mut events, Some(Duration::from_secs(3))).unwrap(); + assert!(events.iter().any(|event| event.token() == token)); + reactor.handle_event(token); + assert!(reactor.pending.is_empty()); + assert_eq!(PENDING_COUNT.load(Ordering::Relaxed), 0); + crate::socket::remove(socket); + } + #[test] fn active_registration_is_pending_until_published() { if isolate_active_registration("active_registration_is_pending_until_published") { return; } @@ -1269,7 +1357,7 @@ mod tests { reactor.drain_commands(); assert!(reactor.active_regs.is_empty()); assert!(!handle.has_pending(), "missing socket must not retain pending work"); - handle.register_op(PendingOp::Recv { pid: ProcessId::new(1), stream_handle: gone }); + handle.register_op(PendingOp::Recv { pid: ProcessId::new(1), stream_handle: gone, deadline: None }); assert!(handle.has_pending(), "ordinary registrations share the same queue handoff"); drop(reactor.cmd_rx.try_recv().unwrap()); assert!(!handle.has_pending()); @@ -1318,7 +1406,7 @@ mod tests { let (handle, mut reactor) = active_registration_fixture(); if queued { handle.shutdown(); } let mut polls = 0; - reactor.run_with_poll(|_, _| { + reactor.run_with_poll(|_, _, _| { polls += 1; assert!(!queued && polls == 1, "poll after Shutdown"); handle.shutdown(); diff --git a/crates/nera-runtime/src/socket.rs b/crates/nera-runtime/src/socket.rs index e905df4..0032e40 100644 --- a/crates/nera-runtime/src/socket.rs +++ b/crates/nera-runtime/src/socket.rs @@ -28,6 +28,7 @@ //! blocking I/O thread pool. use std::io; +use std::collections::VecDeque; use std::sync::Arc; use parking_lot::{Mutex, RwLock}; @@ -96,6 +97,8 @@ pub struct SocketOpts { /// edge-triggered kqueue spin). On the next readability event, this /// buffer is prepended to newly read data before scanning for newline. pub line_buffer: Vec, + /// Retained read prefixes are shared across option snapshots, not copied with them. + pub recv_buffer: Arc>>, } @@ -529,14 +532,54 @@ pub fn try_accept(listener_handle: SocketHandle) -> io::Result { Ok(stream_handle) } +pub(crate) fn restore_recv_buffer(handle: SocketHandle, bytes: Vec) { + with_entry_opts(handle, |opts| { + let mut buffer = opts.recv_buffer.lock(); + for byte in bytes.into_iter().rev() { + buffer.push_front(byte); + } + }); +} + +#[cfg(mio_supported)] +pub(crate) fn has_recv_buffer(handle: SocketHandle) -> bool { + with_entry_opts(handle, |opts| !opts.recv_buffer.lock().is_empty()).unwrap_or(false) +} + +fn consume_recv_buffer(handle: SocketHandle, dest: &mut [u8]) -> usize { + with_entry_opts(handle, |opts| { + let mut buffer = opts.recv_buffer.lock(); + let n = dest.len().min(buffer.len()); + for (dest, byte) in dest.iter_mut().zip(buffer.drain(..n)) { + *dest = byte; + } + n + }).unwrap_or(0) +} + +pub(crate) fn recv_into(handle: SocketHandle, dest: &mut [u8]) -> io::Result { + let stream = get_stream(handle)?; + let buffered = consume_recv_buffer(handle, dest); + if buffered > 0 { + return Ok(buffered); + } + #[cfg(mio_supported)] + { + use std::os::unix::io::AsRawFd; + consume_fd(stream.as_raw_fd(), dest) + } + #[cfg(not(mio_supported))] + { + use std::io::Read; + (&*stream).read(dest) + } +} + /// Try a non-blocking read from a stream. Returns data or WouldBlock. #[cfg(mio_supported)] pub fn try_recv(stream_handle: SocketHandle) -> io::Result> { - use std::io::Read; - - let stream = get_stream(stream_handle)?; let mut buf = vec![0u8; 4096]; - match (&*stream).read(&mut buf) { + match recv_into(stream_handle, &mut buf) { Ok(0) => Err(io::Error::new(io::ErrorKind::ConnectionAborted, "closed")), Ok(n) => { buf.truncate(n); @@ -615,9 +658,18 @@ pub(crate) fn get_raw_fd(handle: SocketHandle) -> Option io::Result { +pub(crate) fn peek_recv_fd(handle: SocketHandle, fd: std::os::unix::io::RawFd, buf: &mut [u8]) -> io::Result { + let buffered = with_entry_opts(handle, |opts| { + let buffer = opts.recv_buffer.lock(); + let n = buffer.len().min(buf.len()); + for (dest, byte) in buf.iter_mut().zip(buffer.iter()).take(n) { + *dest = *byte; + } + n + }).unwrap_or(0); + if buffered > 0 { return Ok(buffered); } let n = unsafe { libc::recv( fd, @@ -656,15 +708,15 @@ pub(crate) fn consume_fd( } } -/// Consume exactly `dest.len()` bytes from a raw fd, looping on short reads. -/// The caller should have peeked first to confirm the data is available. -/// Use for line-mode reads where partial consume would desync buffers. +/// The caller must peek through `peek_recv_fd` first: both operations consume +/// the retained prefix before kernel bytes, keeping line boundaries aligned. #[cfg(mio_supported)] pub(crate) fn consume_exact_fd( + handle: SocketHandle, fd: std::os::unix::io::RawFd, dest: &mut [u8], ) -> io::Result<()> { - let mut offset = 0; + let mut offset = consume_recv_buffer(handle, dest); while offset < dest.len() { let n = unsafe { libc::recv( @@ -690,12 +742,8 @@ pub(crate) fn consume_exact_fd( /// Read from a stream socket. Returns the bytes read, or an IO error. pub fn recv(stream_handle: SocketHandle) -> io::Result> { - use std::io::Read; - - let stream = get_stream(stream_handle)?; - let mut buf = vec![0u8; 4096]; - let n = (&*stream).read(&mut buf)?; + let n = recv_into(stream_handle, &mut buf)?; if n == 0 { return Err(io::Error::new( io::ErrorKind::ConnectionAborted, @@ -719,16 +767,12 @@ pub fn send(stream_handle: SocketHandle, data: &[u8]) -> io::Result<()> { /// `{packet, line}` line. Safety limit: stops after 300,000 bytes to /// prevent unbounded reads. pub fn recv_line(stream_handle: SocketHandle) -> io::Result> { - use std::io::Read; - - let stream = get_stream(stream_handle)?; - let mut line = Vec::new(); let mut byte = [0u8; 1]; const MAX_LINE: usize = 300_000; loop { - let n = (&*stream).read(&mut byte)?; + let n = recv_into(stream_handle, &mut byte)?; if n == 0 { if line.is_empty() { return Err(io::Error::new( @@ -747,9 +791,63 @@ pub fn recv_line(stream_handle: SocketHandle) -> io::Result> { /// Read exactly `length` bytes from a stream socket. pub fn recv_exact(stream_handle: SocketHandle, length: usize) -> io::Result> { - let stream = get_stream(stream_handle)?; + struct SocketReader(SocketHandle); + impl std::io::Read for SocketReader { + fn read(&mut self, dest: &mut [u8]) -> io::Result { + recv_into(self.0, dest) + } + } + read_exact_bytes(&mut SocketReader(stream_handle), length) +} - read_exact_bytes(&mut &*stream, length) +#[cfg(not(mio_supported))] +pub(crate) fn recv_with_deadline( + handle: SocketHandle, + length: usize, + deadline: std::time::Instant, + poll_only: bool, +) -> crate::process::IoResult { + use crate::process::IoResult; + let stream = match get_stream(handle) { + Ok(stream) => stream, + Err(e) => return IoResult::Err(e), + }; + let mut buf = Vec::new(); + let result = loop { + let remaining = deadline.saturating_duration_since(std::time::Instant::now()); + // std rejects a zero SO_RCVTIMEO; nonblocking mode implements the poll instead. + let setup = if remaining.is_zero() { + stream.set_nonblocking(true) + } else { + stream.set_read_timeout(Some(remaining)) + }; + if let Err(e) = setup { break IoResult::Err(e); } + let mut tmp = [0u8; 4096]; + let amount = if length == 0 { tmp.len() } else { (length - buf.len()).min(tmp.len()) }; + match recv_into(handle, &mut tmp[..amount]) { + Ok(0) => break IoResult::Closed, + Ok(n) => { + buf.extend_from_slice(&tmp[..n]); + if length == 0 || buf.len() == length { + break IoResult::OkBytes(std::mem::take(&mut buf)); + } + if !poll_only && std::time::Instant::now() >= deadline { + restore_recv_buffer(handle, std::mem::take(&mut buf)); + break IoResult::Timeout; + } + } + Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => { + restore_recv_buffer(handle, std::mem::take(&mut buf)); + break IoResult::Timeout; + } + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(e) => break IoResult::Err(e), + } + }; + if let Err(e) = stream.set_nonblocking(false).and_then(|_| stream.set_read_timeout(None)) { + return IoResult::Err(e); + } + result } // Accumulate only bytes actually received. In particular, a peer that closes diff --git a/tests/README.md b/tests/README.md index df99a3e..94f810d 100644 --- a/tests/README.md +++ b/tests/README.md @@ -47,6 +47,22 @@ the project working directory so relative fixtures continue to work. Run `python3 scripts/test-test-storage.py` after rebuilding to check this contract at the real native linker boundary on Unix. +## TCP receive timeout regression + +`nera test tcp_recv_timeout` exercises the `gen_tcp:recv/3` deadline contract +on real loopback sockets: idle reads with zero and positive lengths, zero +polling, retained partial exact reads, data arriving before the deadline, and +socket reuse with `infinity` and `recv/2`. It checks elapsed monotonic time and +requires the `recv_timeout_ok` completion marker. The delayed sends deliberately +cross a completed receive's deadline to detect a stale timeout waking a later +receive. The same fixture runs on BEAM with `erlc` and `tcp_recv_timeout:test/0`. + +`tcp_recv_timeout_active` checks recovery through raw `{active, true}` and +`{active, once}`, retained lines longer than a read chunk, and byte order when a +retained line prefix is followed by new socket data. It requires +`recv_timeout_active_ok` and also runs unchanged on BEAM. These assertions prevent kernel-only readiness or +line scanning from stranding retained bytes or delivering later bytes first. + ## Focused runtime contracts The [runtime contract index](../docs/RUNTIME_CONTRACTS.md) names the semantic diff --git a/tests/tcp_recv_timeout.erl b/tests/tcp_recv_timeout.erl new file mode 100644 index 0000000..4e7f7c4 --- /dev/null +++ b/tests/tcp_recv_timeout.erl @@ -0,0 +1,70 @@ +-module(tcp_recv_timeout). +-export([test/0]). +%% EXPECT: recv_timeout_ok + +%% Regression for recv/3 ignoring its finite timeout on an idle connection. +test() -> + {ok, L} = gen_tcp:listen(0, [binary, {active, false}]), + {ok, Port} = inet:port(L), + {ok, C} = gen_tcp:connect("127.0.0.1", Port, [binary, {active, false}]), + {ok, S} = gen_tcp:accept(L), + timeout_recv(S, 0, 60), + timeout_recv(S, 4, 60), + timeout_recv(S, 0, 0), + timeout_recv(S, 4, 0), + ok = gen_tcp:send(C, <<"poll">>), + timeout_recv(S, 5, 60), + {ok, <<"poll">>} = gen_tcp:recv(S, 4, 0), + Payload = binary:copy(<<7>>, 8192), + ok = gen_tcp:send(C, Payload), + timeout_recv(S, 8193, 60), + {ok, Payload} = gen_tcp:recv(S, 8192, 0), + ok = gen_tcp:send(C, <<"ab">>), + timeout_recv(S, 4, 60), + ok = gen_tcp:send(C, <<"cd">>), + {ok, <<"abcd">>} = gen_tcp:recv(S, 4, 1000), + ok = gen_tcp:send(C, <<"xy">>), + timeout_recv(S, 4, 60), + {ok, <<"xy">>} = gen_tcp:recv(S, 0, 0), + %% The total deadline must not restart when another fragment arrives. + spawn_link(fun() -> + receive after 100 -> ok end, + ok = gen_tcp:send(C, <<1>>), + receive after 150 -> ok end, + ok = gen_tcp:send(C, <<2, 3, 4>>) + end), + timeout_recv(S, 4, 200), + {ok, <<1, 2, 3, 4>>} = gen_tcp:recv(S, 4, infinity), + Parent = self(), + spawn_link(fun() -> + receive after 20 -> ok end, + ok = gen_tcp:send(C, <<"ready">>), + Parent ! sent + end), + {ok, <<"ready">>} = gen_tcp:recv(S, 5, 1000), + receive sent -> ok after 2000 -> fail(sender) end, + %% A completed receive's deadline must not wake the next receive. + spawn_link(fun() -> + receive after 1100 -> ok end, + ok = gen_tcp:send(C, <<"later">>) + end), + {ok, <<"later">>} = gen_tcp:recv(S, 5, infinity), + ok = gen_tcp:send(C, <<"two">>), + {ok, <<"two">>} = gen_tcp:recv(S, 3), + ok = gen_tcp:close(C), + ok = gen_tcp:close(S), + ok = gen_tcp:close(L), + io:format("recv_timeout_ok~n"), + ok. + +timeout_recv(S, Length, Timeout) -> + Start = erlang:monotonic_time(millisecond), + Result = gen_tcp:recv(S, Length, Timeout), + Elapsed = erlang:monotonic_time(millisecond) - Start, + {error, timeout} = Result, + case Elapsed >= Timeout andalso Elapsed < Timeout + 2000 of + true -> io:format("recv length=~p timeout=~p result=~p elapsed=~p~n", [Length, Timeout, Result, Elapsed]); + false -> fail({elapsed, Length, Timeout, Elapsed}) + end. + +fail(Reason) -> erlang:error({recv_timeout_failed, Reason}). diff --git a/tests/tcp_recv_timeout_active.erl b/tests/tcp_recv_timeout_active.erl new file mode 100644 index 0000000..5e327ba --- /dev/null +++ b/tests/tcp_recv_timeout_active.erl @@ -0,0 +1,84 @@ +-module(tcp_recv_timeout_active). +-export([test/0]). +%% EXPECT: recv_timeout_active_ok + +%% Retained bytes must remain readable when timeout recovery switches to active mode. +test() -> + raw(true), + raw(once), + lines(), + split_line(), + io:format("recv_timeout_active_ok~n"), + ok. + +raw(Mode) -> + {L, C, S} = pair(), + Payload = binary:copy(<<"0123456789abcdef">>, 1024), + retain(C, S, Payload), + ok = inet:setopts(S, [{active, Mode}]), + Recovered = chunks(S, Mode, byte_size(Payload), <<>>), + Payload = Recovered, + io:format("raw active=~p recovered=~p bytes~n", [Mode, byte_size(Recovered)]), + close(L, C, S). + +chunks(_S, _Mode, 0, Acc) -> Acc; +chunks(S, Mode, Remaining, Acc) -> + receive + {tcp, S, Data} when byte_size(Data) =< Remaining -> + Left = Remaining - byte_size(Data), + case Mode =:= once andalso Left > 0 of + true -> ok = inet:setopts(S, [{active, once}]); + false -> ok + end, + chunks(S, Mode, Left, <>) + after 2000 -> erlang:error({retained_bytes_stalled, Mode, Remaining}) + end. + +lines() -> + {L, C, S} = pair(), + First = <<(binary:copy(<<"x">>, 20000))/binary, "\r\n">>, + retain(C, S, <>), + ok = inet:setopts(S, [{packet, line}, {active, once}]), + FirstRead = line(S), + First = FirstRead, + ok = inet:setopts(S, [{active, true}]), + SecondRead = line(S), + <<"second\n">> = SecondRead, + ThirdRead = line(S), + <<"third\r\n">> = ThirdRead, + io:format("line recovered=~p bytes then ~p and ~p~n", [byte_size(FirstRead), SecondRead, ThirdRead]), + close(L, C, S). + +split_line() -> + {L, C, S} = pair(), + retain(C, S, <<"kept">>), + ok = inet:setopts(S, [{packet, line}, {active, once}]), + ok = gen_tcp:send(C, <<"tail\n">>), + %% BEAM backends differ on boundaries after a timed-out exact read; + %% this recovery assertion owns byte ordering, not that boundary choice. + Expected = <<"kepttail\n">>, + Recovered = chunks(S, once, byte_size(Expected), <<>>), + Expected = Recovered, + io:format("split line recovered=~p~n", [Recovered]), + close(L, C, S). + +line(S) -> + receive {tcp, S, Data} -> Data + after 2000 -> erlang:error(retained_line_stalled) + end. + +retain(C, S, Payload) -> + ok = gen_tcp:send(C, Payload), + {error, timeout} = gen_tcp:recv(S, byte_size(Payload) + 1, 60). + +pair() -> + {ok, L} = gen_tcp:listen(0, [binary, {active, false}]), + {ok, Port} = inet:port(L), + {ok, C} = gen_tcp:connect("127.0.0.1", Port, [binary, {active, false}]), + {ok, S} = gen_tcp:accept(L), + {L, C, S}. + +close(L, C, S) -> + ok = gen_tcp:close(C), + ok = gen_tcp:close(S), + ok = gen_tcp:close(L).