Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 | ✅ | |
Expand Down
119 changes: 50 additions & 69 deletions crates/nera-runtime/src/ffi/gen_tcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -585,95 +585,72 @@ 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]
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);
};
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 {
let len = length;

#[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,
});
}
}

Expand All @@ -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,
},
)
}
Expand Down Expand Up @@ -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);
Expand All @@ -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,
);
Expand All @@ -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);
Expand All @@ -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);
Expand Down
5 changes: 5 additions & 0 deletions crates/nera-runtime/src/io_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,7 @@ pub(crate) fn wake_process_with_result(pid: ProcessId, result: IoResult) {
/// - `OkBytes(b)` → `{ok, <<binary>>}`
/// - `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 {
Expand All @@ -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));
Expand Down
28 changes: 14 additions & 14 deletions crates/nera-runtime/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -718,15 +716,15 @@ 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
} else {
// 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
}
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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),
}
Expand Down
Loading
Loading