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
13 changes: 13 additions & 0 deletions docs/docs/content/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,19 @@
All notable changes to `rayforce` are documented here. This project adheres to
[Semantic Versioning](https://semver.org).

## Unreleased

### Added

- **`QConnection::connect_opts` chooses the keepalive.** It takes
`ConnectOpts`: credentials, a timeout and a `Keepalive`, which is `Auto` (the
core's 60 s default), `Off`, or `Budget(Duration)`, roughly when a silent peer
counts as dead. `connect` and `connect_with` keep their signatures and get
`Auto`. A zero timeout or budget is refused rather than passed on, because the
C side reads 0 as no timeout or as the default keepalive, and so is either
past `i32::MAX` milliseconds. `rayforce-sys` binds `q_connect_opts` and the
`Q_KEEPALIVE_*` constants.

## 1.4.0

### Changed
Expand Down
23 changes: 23 additions & 0 deletions docs/docs/content/documentation/ipc.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,29 @@ fn main() -> rayforce::Result<()> {
}
```

!!! note "A peer that goes silent"

`is_alive()` turns false when the peer closes. A peer that vanishes without
closing, such as a VPN tunnel reaped with no FIN, sends nothing to notice,
so the kernel's keepalive probes it instead. `connect` arms it at the
core's 60 s default. To notice sooner, connect with a budget:

```rust,no_run
# use std::time::Duration;
# use rayforce::{q::{ConnectOpts, Keepalive, QConnection}, Runtime};
# Runtime::scope(|_rt| {
let opts = ConnectOpts {
keepalive: Keepalive::Budget(Duration::from_secs(25)),
..ConnectOpts::default()
};
let conn = QConnection::connect_opts("127.0.0.1", 5010, &opts)?;
# Ok(())
# }).unwrap();
```

The budget is roughly when a silent peer counts as dead. On Linux it can be
up to one probe interval late, because the kernel acts on a probe tick.

!!! note "A handler is a type, not a closure"

The core takes a bare C function pointer with no user-data argument, so
Expand Down
21 changes: 21 additions & 0 deletions rayforce-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@ extern "C" {
password: *const ::std::os::raw::c_char,
timeout_ms: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
/// `q_connect` with the keepalive chosen: [`Q_KEEPALIVE_AUTO`],
/// [`Q_KEEPALIVE_OFF`], or a budget in ms. Armed once the handshake has
/// succeeded, best-effort as in the core: if `SO_KEEPALIVE` fails, the
/// connection is returned without keepalive. `q_connect` is this with AUTO.
pub fn q_connect_opts(
host: *const ::std::os::raw::c_char,
port: ::std::os::raw::c_int,
user: *const ::std::os::raw::c_char,
password: *const ::std::os::raw::c_char,
timeout_ms: ::std::os::raw::c_int,
keepalive_ms: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
/// Close a connection fd. Returns 0 on success, -1 on an invalid fd.
pub fn q_close(fd: ::std::os::raw::c_int) -> ::std::os::raw::c_int;
/// Encode + exchange + decode: send `msg` and return the decoded response
Expand Down Expand Up @@ -131,6 +143,15 @@ pub const Q_ERR_SOCKET: ::std::os::raw::c_int = -1;
pub const Q_ERR_HANDSHAKE: ::std::os::raw::c_int = -2;
pub const Q_ERR_TIMEOUT: ::std::os::raw::c_int = -3;

/// `q_connect_opts` keepalive choices (mirrors `q.h`, which holds them equal to
/// the core's `RAY_IPC_KEEPALIVE_*`). A positive value is a budget in ms.
///
/// AUTO is keepalive at the core's 60 s default, with no bound on
/// unacknowledged data.
pub const Q_KEEPALIVE_AUTO: ::std::os::raw::c_int = 0;
/// No keepalive.
pub const Q_KEEPALIVE_OFF: ::std::os::raw::c_int = -1;

/// `ray_ipc_connect` failure codes.
///
/// The public header declares the function with no contract at all
Expand Down
2 changes: 1 addition & 1 deletion rayforce/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ pub use ipc::TcpClient;
pub use lambda::Fn;
pub use ops::Operation;
pub use poll::Poll;
pub use q::{QConnection, QListener, Subscription};
pub use q::{ConnectOpts, Keepalive, QConnection, QListener, Subscription};
pub use query::{Select, Update};
pub use runtime::{eval, eval_value, get_global, on_runtime_thread, set_global, Runtime};
pub use serve::{By, Clock, Ended, IpcServer, Monotonic, RequestEnd, ServeIpc};
Expand Down
123 changes: 118 additions & 5 deletions rayforce/src/q.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use std::collections::HashMap;
use std::ffi::{c_void, CString};
use std::marker::PhantomData;
use std::os::raw::{c_char, c_int};
use std::time::Duration;

use rayforce_sys as sys;

Expand All @@ -34,6 +35,88 @@ use crate::poll::Poll;
use crate::runtime::assert_on_runtime_thread;
use crate::value::Value;

/// How a [`QConnection`] notices a peer that vanished without closing, such as
/// a suspended host or a VPN tunnel reaped with no FIN. Without keepalive
/// nothing arrives and nothing fails, and a [`Subscription`] that only receives
/// stays alive forever.
///
/// The same three choices as the core's own client (`ray_ipc_connect_opts`).
/// The kernel does the probing, so a peer that is alive but slow to push is
/// never affected: probes only go out while nothing is in flight.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Keepalive {
/// The core's default: a silent peer is dead after about 60 s, with no
/// bound on how long sent data may stay unacknowledged.
#[default]
Auto,
/// No keepalive. A silent peer is waited on forever.
Off,
/// A silent peer is dead about this long after the last thing it sent. The
/// first probe goes out after half the budget idle, then three more a sixth
/// apart, each in whole seconds and at least 1. Sent data that stays
/// unacknowledged this long also fails the connection (`TCP_USER_TIMEOUT`
/// on Linux), which a live peer that stops reading would trip too.
///
/// On Linux the kernel acts on a probe tick, so the connection can fail up
/// to one interval late: rayforce-q measured a 25 s budget failing at
/// 28.3 s with the peer's packets dropped.
Budget(Duration),
}

/// What [`QConnection::connect_opts`] takes beyond the address. The default is
/// no credentials, no timeout and [`Keepalive::Auto`]:
///
/// ```no_run
/// use std::time::Duration;
/// use rayforce::{q::{ConnectOpts, Keepalive, QConnection}, Runtime};
/// Runtime::scope(|_rt| {
/// let opts = ConnectOpts {
/// keepalive: Keepalive::Budget(Duration::from_secs(25)),
/// ..ConnectOpts::default()
/// };
/// let conn = QConnection::connect_opts("localhost", 5010, &opts)?;
/// Ok(())
/// })
/// # .unwrap();
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ConnectOpts<'a> {
/// Empty `user` and `password` degrade to the no-auth handshake.
pub user: &'a str,
pub password: &'a str,
/// Bounds the connect and each request on the plain client. `None` blocks.
pub timeout: Option<Duration>,
pub keepalive: Keepalive,
}

/// `keepalive` as the `keepalive_ms` `q_connect_opts` takes.
fn keepalive_ms(keepalive: Keepalive) -> Result<c_int> {
match keepalive {
Keepalive::Auto => Ok(sys::Q_KEEPALIVE_AUTO),
Keepalive::Off => Ok(sys::Q_KEEPALIVE_OFF),
Keepalive::Budget(budget) => positive_ms("keepalive budget", budget),
}
}

/// `duration` in the whole milliseconds the C side takes, rounded up. Zero is
/// refused, because the C side reads 0 as something else: no timeout at all, or
/// the default keepalive. Truncated, a sub-millisecond value would become that
/// 0, hence the rounding.
fn positive_ms(what: &str, duration: Duration) -> Result<c_int> {
if duration.is_zero() {
return Err(RayError::binding(format!(
"Q: a {what} must be greater than zero"
)));
}
let ms = duration.as_nanos().div_ceil(1_000_000);
c_int::try_from(ms).map_err(|_| {
RayError::binding(format!(
"Q: a {what} of {duration:?} is past the {} ms the C side takes",
c_int::MAX
))
})
}

/// An open connection to a Q server. Closed on drop.
///
/// Confined to its [`crate::Runtime::scope`], like a [`Value`]: `q_close` runs
Expand Down Expand Up @@ -73,26 +156,56 @@ impl QConnection {

/// Open a TCP connection with optional credentials and a connect/op timeout
/// (`timeout_ms <= 0` blocks). Empty `user`/`password` degrade to the
/// no-auth handshake.
/// no-auth handshake. Keepalive is [`Keepalive::Auto`]; see
/// [`QConnection::connect_opts`] to choose it.
pub fn connect_with(
host: &str,
port: u16,
user: &str,
password: &str,
timeout_ms: i32,
) -> Result<Self> {
let timeout = u64::try_from(timeout_ms)
.ok()
.filter(|&ms| ms > 0)
.map(Duration::from_millis);
Self::connect_opts(
host,
port,
&ConnectOpts {
user,
password,
timeout,
keepalive: Keepalive::Auto,
},
)
}

/// Open a TCP connection with everything [`ConnectOpts`] holds: credentials,
/// a connect/op timeout and the [`Keepalive`].
///
/// A zero `timeout` or keepalive budget is refused, and so is either past
/// `i32::MAX` milliseconds, the most the C side takes. Both are checked
/// before anything connects.
pub fn connect_opts(host: &str, port: u16, opts: &ConnectOpts<'_>) -> Result<Self> {
assert_on_runtime_thread("QConnection::connect");
let timeout_ms = opts
.timeout
.map_or(Ok(0), |timeout| positive_ms("timeout", timeout))?;
let keepalive_ms = keepalive_ms(opts.keepalive)?;
let host_c = CString::new(host).map_err(|_| RayError::binding("Q host contains NUL"))?;
let user_c = CString::new(user).map_err(|_| RayError::binding("Q user contains NUL"))?;
let pass_c =
CString::new(password).map_err(|_| RayError::binding("Q password contains NUL"))?;
let user_c =
CString::new(opts.user).map_err(|_| RayError::binding("Q user contains NUL"))?;
let pass_c = CString::new(opts.password)
.map_err(|_| RayError::binding("Q password contains NUL"))?;
let fd = unsafe {
sys::q_connect(
sys::q_connect_opts(
host_c.as_ptr(),
i32::from(port),
user_c.as_ptr(),
pass_c.as_ptr(),
timeout_ms,
keepalive_ms,
)
};
if fd < 0 {
Expand Down
129 changes: 129 additions & 0 deletions rayforce/tests/q.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
use std::io::{Read, Write};
use std::net::TcpListener;
use std::thread;
use std::time::{Duration, Instant};

use rayforce::q::{ConnectOpts, Keepalive};
use rayforce::{q, q::QConnection, Runtime, Table, Value};

// --- Q wire-format builders (server side) ---------------------------------
Expand Down Expand Up @@ -409,3 +411,130 @@ fn decode_response_cols_checks_the_wire_header() {
})
.unwrap();
}

/// Bind a mock that accepts one connection and never answers, not even the
/// handshake; returns the port. The socket stays open until the test ends.
fn spawn_silent() -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
thread::spawn(move || {
if let Ok((sock, _)) = listener.accept() {
thread::sleep(Duration::from_secs(60));
drop(sock);
}
});
port
}

#[test]
fn connect_opts_connects_with_every_keepalive() {
Runtime::scope(|_rt| {
// A sub-millisecond budget is valid: it rounds up, as a timeout does.
for keepalive in [
Keepalive::Auto,
Keepalive::Off,
Keepalive::Budget(Duration::from_secs(25)),
Keepalive::Budget(Duration::from_micros(1)),
] {
let port = spawn_mock(msg(&long_vec(&[7])));
let opts = ConnectOpts {
keepalive,
..ConnectOpts::default()
};
let conn = QConnection::connect_opts("127.0.0.1", port, &opts)
.unwrap_or_else(|e| panic!("{keepalive:?}: {e}"));
let v = conn.execute("7").unwrap();
assert_eq!(v.as_slice::<i64>().unwrap(), &[7], "{keepalive:?}");
}
Ok(())
})
.unwrap();
}

/// The timeout and the keepalive are both `int` milliseconds at the C call, so
/// swapped they would still compile. Swapped, this connect would wait out the
/// 30 s budget as its timeout instead of failing at 200 ms.
#[test]
fn connect_opts_times_out_on_the_timeout_not_the_keepalive() {
Runtime::scope(|_rt| {
let port = spawn_silent();
let opts = ConnectOpts {
timeout: Some(Duration::from_millis(200)),
keepalive: Keepalive::Budget(Duration::from_secs(30)),
..ConnectOpts::default()
};
let started = Instant::now();
let err = QConnection::connect_opts("127.0.0.1", port, &opts)
.err()
.expect("a silent peer cannot complete the handshake");
assert!(
started.elapsed() < Duration::from_secs(10),
"took {:?}: {err}",
started.elapsed()
);
Ok(())
})
.unwrap();
}

#[test]
fn connect_opts_refuses_a_zero_keepalive_budget() {
Runtime::scope(|_rt| {
// `Off` already says off; a zero budget that meant it too would turn
// keepalive off without anyone asking for that.
let opts = ConnectOpts {
keepalive: Keepalive::Budget(Duration::ZERO),
..ConnectOpts::default()
};
let err = QConnection::connect_opts("127.0.0.1", 1, &opts)
.err()
.expect("a zero budget is refused before connecting");
assert!(
err.to_string().contains("keepalive"),
"unexpected error: {err}"
);
Ok(())
})
.unwrap();
}

#[test]
fn connect_opts_refuses_a_keepalive_budget_past_the_c_int() {
Runtime::scope(|_rt| {
let ms = u64::try_from(i32::MAX).unwrap() + 1;
let opts = ConnectOpts {
keepalive: Keepalive::Budget(Duration::from_millis(ms)),
..ConnectOpts::default()
};
let err = QConnection::connect_opts("127.0.0.1", 1, &opts)
.err()
.expect("a budget past i32::MAX ms is refused before connecting");
assert!(
err.to_string().contains("keepalive"),
"unexpected error: {err}"
);
Ok(())
})
.unwrap();
}

#[test]
fn connect_opts_refuses_a_zero_timeout() {
Runtime::scope(|_rt| {
// The C side reads 0 as "block forever", the opposite of what a zero
// timeout asks for. `None` is how to say no timeout.
let opts = ConnectOpts {
timeout: Some(Duration::ZERO),
..ConnectOpts::default()
};
let err = QConnection::connect_opts("127.0.0.1", 1, &opts)
.err()
.expect("a zero timeout is refused before connecting");
assert!(
err.to_string().contains("timeout"),
"unexpected error: {err}"
);
Ok(())
})
.unwrap();
}
Loading