epics_libcom_rs/runtime/blocking_io.rs
1//! Blocking socket ⇄ `AsyncRead`/`AsyncWrite` adapters: the byte source for
2//! every reactor-free driver in the workspace.
3//!
4//! ```text
5//! socket --read--> reader pump thread --Vec<u8> chunks--> ChannelReader
6//! |
7//! whatever drives the protocol future
8//! |
9//! socket <--write-- writer pump thread <--framed bytes-- ChannelWriter
10//! ```
11//!
12//! # Why this lives in `epics-base-rs` and not in a protocol crate
13//!
14//! It was written once, inside `epics-pva-rs`'s blocking **server** driver, and
15//! the obvious next move was to promote it within that crate so the PVA client
16//! could reach it too. Measured, that destination is wrong:
17//! `epics-ca-rs` does not depend on `epics-pva-rs` and must not — the only
18//! crate that depends on both is `epics-bridge-rs`, which sits *above* them
19//! (`doc/calink-rtems-design.md` §3.3). A primitive promoted inside
20//! `epics-pva-rs` is one the CA client structurally cannot call, so the next CA
21//! increment writes a third copy — exactly the outcome "one seam, two callers"
22//! exists to prevent.
23//!
24//! So it lands here, beside the rest of its family: `runtime::task::spawn`,
25//! `block_on_sync`/`park_on`, `StackSizeClass`, `spawn_dedicated_thread`,
26//! `enter_ioc_thread`. Every protocol crate can reach it, and none of them owns
27//! it.
28//!
29//! # The seam is the byte source, not the frame pipeline
30//!
31//! Nothing here parses anything. Both pumps move `Vec<u8>` and neither knows
32//! whether the bytes are PVA frames, CA messages, or noise; the protocol future
33//! on the other side of the adapters is untouched and uncompiled-differently.
34//! That is what makes a driver built on this primitive arguable from the hosted
35//! driver's own tests: same parser, same `select!`, same handlers, different
36//! implementors of two `dyn` traits.
37//!
38//! # Two facts that must not be re-derived
39//!
40//! * **No fd dup.** The read and write roles come from **one** descriptor
41//! shared through an `Arc`, via `impl Read for &TcpStream` /
42//! `impl Write for &TcpStream` — never `try_clone`. `try_clone` is
43//! `fcntl(F_DUPFD_CLOEXEC)`, and on RTEMS 6 that cannot work for a socket:
44//! RTEMS's `fcntl` has no `F_DUPFD_CLOEXEC` case at all
45//! (`cpukit/libcsupport/src/fcntl.c:146-220` falls to
46//! `default: errno = EINVAL`), and even plain `F_DUPFD` fails because
47//! `duplicate_iop` calls the file's `open_h` while rtems-libbsd installs
48//! `rtems_bsd_sysgen_nodeops` on every socket. Measured on the target: `dup`,
49//! `F_DUPFD` and `F_DUPFD_CLOEXEC` all fail on a socket while `F_DUPFD` on
50//! `/dev/console` succeeds. A caller that reaches for `try_clone` compiles
51//! and fails at runtime on target only.
52//! * **A blocking write needs a deadline, not a per-syscall timeout.**
53//! `SO_SNDTIMEO` bounds each `write` syscall, so a peer that accepts one byte
54//! per tick never trips it and holds the pump thread indefinitely — and a
55//! target that does not implement the option at all (VxWorks 7) has no bound
56//! whatever. [`write_frame_deadline`] therefore waits for writability against
57//! its own deadline and sets no socket option.
58//!
59//! # Lifecycle: a pump you cannot spawn without holding the thing that ends it
60//!
61//! [`spawn_reader_pump`] and [`spawn_writer_pump`] each return an adapter *and*
62//! a guard, and there is no way to obtain the former without the latter. The
63//! guards' `Drop` is what retires the threads, which is what makes every exit
64//! path — clean return, `?`, and a panic unwinding through the caller — covered
65//! without any cleanup written on an error branch.
66//!
67//! The two guards end their threads differently because the threads park
68//! differently:
69//!
70//! | guard | how its thread is parked | how the guard returns it |
71//! |---|---|---|
72//! | [`ReaderPumpGuard`] | inside a blocking `read` behind an effectively-infinite `SO_RCVTIMEO` | `shutdown(Shutdown::Both)` on the shared socket, then `join` |
73//! | [`WriterPumpGuard`] | inside `recv()` on the frame channel | drop the only strong sender, then `join` |
74//!
75//! A caller that needs a specific teardown *order* — writer down first so
76//! frames emitted on the way out reach the wire, then reader — gets it by
77//! dropping the guards in that order, or by declaring them in the reverse of
78//! it.
79//!
80//! The reader guard's row is a POSIX contract: `shutdown` waking a thread
81//! parked in a blocking `read` is what unix (RTEMS included) provides and
82//! Windows does not (measured, PR #56 CI 2026-07-24 — the parked read
83//! outlived a 120 s bound). That is why `exec_backend`, the only
84//! configuration that runs these pumps in production, refuses Windows at
85//! compile time (`lib.rs`), and why the tests asserting this contract are
86//! `#[cfg(unix)]`.
87//!
88//! # Where the async goes
89//!
90//! [`block_on_sync`] is the single bridge, in both pumps. On a bare thread it
91//! parks; on a multi-thread runtime worker it hands the worker off first. It is
92//! **not** `blocking_send`, which panics inside a runtime context and would
93//! make this module unusable from a hosted worker.
94//!
95//! # Before the pumps: the dial
96//!
97//! A reactor-free driver cannot `await` a connect either, so the blocking
98//! `connect` needs a thread just as the two pumps do — and for the same reason,
99//! at the same band. [`DialPool`] owns those threads. It is here rather than in
100//! a protocol crate for the reason the pumps are: `epics-ca-rs` and
101//! `epics-pva-rs` both dial and neither may depend on the other.
102
103// RTEMS-EXEC-MODEL-ALLOW(1): `one_descriptor_serves_both_pumps` asserts both
104// pump directions concurrently from the async side, which needs the
105// multi-thread tokio flavor; it runs and passes in the feature-ON suite (the
106// pumps themselves are std threads, the tokio runtime only hosts the
107// assertions).
108
109use std::collections::VecDeque;
110use std::io::{self, Read, Write};
111use std::net::{Shutdown, SocketAddr, TcpStream};
112use std::pin::Pin;
113use std::sync::{Arc, Condvar, Mutex, MutexGuard};
114use std::task::{Context, Poll, Waker};
115use std::time::{Duration, Instant};
116
117use tokio::io::ReadBuf;
118use tokio::sync::{mpsc, oneshot};
119use tracing::{debug, warn};
120
121use crate::runtime::task::{StackSizeClass, ThreadPriority, block_on_sync, spawn_dedicated_thread};
122use crate::runtime::worker_pool::{Job, SetLease, Worker, WorkerPool, WorkerRole};
123
124/// One blocking read, sized to match the frame readers that consume it so the
125/// byte arrival pattern is the hosted one.
126pub const DEFAULT_READ_CHUNK: usize = 4096;
127
128/// The `FIONREAD` ioctl request — bytes pending in the socket receive queue.
129/// C `rsrv`'s batch-up gate: hold accumulated replies while this is `> 0`,
130/// flush at `0` (`camsgtask.c:55`, `cast_server.c:272`), and libca's flow
131/// control input on the client side (`tcpiiu.cpp:544`).
132///
133/// The `libc` crate exposes `FIONREAD` for hosted Unix but omits it for
134/// `armv7-rtems-eabihf`, so the RTEMS value is supplied here. RTEMS newlib
135/// defines it in `sys/rtems/include/sys/filio.h` as `_IOR('f', 127, int)`;
136/// `sys/ioccom.h` in the same tree encodes
137/// `_IOR(g,n,t) = IOC_OUT | (sizeof(t) << 16) | (g << 8) | n` with
138/// `IOC_OUT = 0x40000000`. For a 4-byte `int` that is
139/// `0x40000000 | (4 << 16) | ('f' << 8) | 127 = 0x4004_667F` — the same value
140/// the `libc` crate hardcodes for the whole BSD family (`unix/bsd/mod.rs`),
141/// which C `rsrv` runs on RTEMS in production. Pending on-target runtime
142/// verification at the QEMU/BSP phase; a wrong value only makes the `ioctl`
143/// error, and every caller then flushes (C's own `status < 0` branch),
144/// degrading to per-datagram / per-iteration flushing — never a hang or a
145/// crash. (Candidate for an upstream `libc` newlib/rtems binding so this
146/// local definition can later be dropped.)
147#[cfg(all(unix, not(target_os = "rtems")))]
148const FIONREAD_REQUEST: libc::c_ulong = libc::FIONREAD as libc::c_ulong;
149#[cfg(target_os = "rtems")]
150const FIONREAD_REQUEST: libc::c_ulong = 0x4004_667F;
151
152/// Bytes pending in the socket receive queue via `FIONREAD`.
153///
154/// **One owner for the whole workspace.** Two callers need this exact
155/// question answered and they are on opposite sides of the protocol: C
156/// `rsrv`'s batch-up gate holds accumulated replies while this is `> 0` and
157/// flushes at `0` (`camsgtask.c:52-67`, `cast_server.c:268-281`), and libca's
158/// `tcpiiu::bytesArePendingInOS()` is the sole input to client flow control
159/// (`tcpiiu.cpp:544-567`). They were two implementations — the server's here,
160/// the client's a bare `libc::FIONREAD` that does not exist on
161/// `armv7-rtems-eabihf` at all — which is one implementation too many for a
162/// constant whose RTEMS value had to be derived from newlib headers by hand.
163///
164/// On any `ioctl` error this returns `Err`, and every caller treats that as
165/// "flush now" / "nothing pending" — matching C's `status < 0` branch — so an
166/// absent or wrong FIONREAD never coalesces (byte-correct, just unbatched),
167/// never latches flow control on, and never hangs.
168#[cfg(unix)]
169pub fn pending_bytes<F: std::os::fd::AsRawFd>(sock: &F) -> io::Result<usize> {
170 let mut n: libc::c_int = 0;
171 // SAFETY: `as_raw_fd()` is a valid open socket fd; FIONREAD writes one
172 // `c_int` count through the out-pointer, whose type and size match.
173 let rc = unsafe {
174 libc::ioctl(
175 sock.as_raw_fd(),
176 FIONREAD_REQUEST as _,
177 &mut n as *mut libc::c_int,
178 )
179 };
180 if rc != 0 {
181 return Err(io::Error::last_os_error());
182 }
183 Ok(n.max(0) as usize)
184}
185
186#[cfg(not(unix))]
187pub fn pending_bytes<F>(_sock: &F) -> io::Result<usize> {
188 // No FIONREAD off Unix (RTEMS and the host CI are both Unix-family). Report
189 // "unavailable" so callers flush every iteration — never coalesce — which
190 // is byte-correct, just unbatched.
191 Err(io::Error::new(
192 io::ErrorKind::Unsupported,
193 "FIONREAD unavailable on this platform",
194 ))
195}
196
197/// A blocking socket op hit its `SO_RCVTIMEO`/`SO_SNDTIMEO`.
198///
199/// Unix reports the expiry as `WouldBlock`, some platforms as `TimedOut`.
200pub fn is_socket_timeout(kind: io::ErrorKind) -> bool {
201 matches!(kind, io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut)
202}
203
204/// Announce a pump thread that did not end normally.
205///
206/// The guards below make a loss *survivable* — the connection is torn down
207/// however a pump ends. They do not make it *visible*, and a process that has
208/// lost a thread but reads exactly like a healthy one is what closes here. The
209/// loss that reaches this function is a pump that panicked; a pooled worker is
210/// never *created* per connection, so the old "could not be created" loss is
211/// gone with the per-connection spawn.
212///
213/// Through `errlog` and not `tracing` alone: `errlog_sev_printf` reaches the
214/// console whatever the log configuration — including an RTEMS console whose
215/// subscriber is the in-tree one — and printing it is what a C IOC does.
216fn pump_thread_lost(role: &str, label: &str, what: &str) {
217 crate::runtime::log::errlog_sev_printf(
218 crate::runtime::log::ErrlogSevEnum::Major,
219 &format!(
220 "{label}: the {role} thread {what}; this connection is being torn \
221 down. Other connections are unaffected."
222 ),
223 );
224 warn!(label, role, what, "blocking socket pump: a thread was lost");
225}
226
227// ---------------------------------------------------------------------------
228// Dial side
229// ---------------------------------------------------------------------------
230
231/// How many dial threads one [`DialPool`] may ever create.
232///
233/// The bound is on *creations for the life of the process*, not on threads
234/// alive at an instant, because that is the resource that was being consumed:
235/// every `std::thread` leaks 128 B on RTEMS permanently (its TLS key is freed
236/// before the key's destructor runs), so a dial that spawns per attempt leaks
237/// per attempt. A pool whose workers never retire creates at most this many,
238/// ever — the leak becomes a one-off 4 × 128 B, whatever the redial cadence.
239///
240/// Four, not one: a worker is occupied for as long as its `connect` blocks, and
241/// a SYN-blackholed peer holds one for the whole OS connect ladder long after
242/// the awaiting side gave up at its own bound. The ladder that bounds a worker
243/// is the *target's*, not the host's: on `armv7-rtems-eabihf` libbsd ends an
244/// unanswered handshake at `TCPTV_KEEP_INIT` (`75 * hz`), measured at 75 s,
245/// while a Linux host runs `tcp_syn_retries` out to ~130 s. This pool exists
246/// for the RTEMS target, so 75 s is the figure its sizing is reasoned against.
247/// One worker would let a single unreachable peer head-of-line-block
248/// every other dial in the process; four keeps distinct in-flight dials
249/// independent in normal operation. The cost is four `Small` stacks
250/// (4 × 256 KiB on `armv7-rtems-eabihf`), and only if four dials were ever
251/// concurrently in flight — a client that only ever dials one server at a time
252/// creates exactly one worker and reuses it forever.
253///
254/// Past the bound, dials queue. That is not a failure mode that needs its own
255/// handling: a queued request is still under the caller's own timeout, so it
256/// fails at that deadline exactly as an in-flight one would, and a worker that
257/// later reaches a request whose caller has gone opens no socket at all.
258pub const MAX_DIAL_WORKERS: usize = 4;
259
260/// One dial handed to a worker: where to connect, and where the result goes.
261struct DialRequest {
262 target: SocketAddr,
263 reply: oneshot::Sender<io::Result<TcpStream>>,
264}
265
266/// Everything the pool mutates, under one lock.
267///
268/// The three counts answer one question — *is a worker owed?* — and are kept in
269/// the shape that makes the answer exact: `workers - busy` is available, and a
270/// request is covered iff the available ones outnumber the queue.
271struct DialQueue {
272 /// Requests no worker has taken yet.
273 pending: VecDeque<DialRequest>,
274 /// Workers holding a request. Counting the *busy* ones rather than the
275 /// parked ones is load-bearing: a worker between its `connect` and its park
276 /// is neither, and counting parked workers would make it read as
277 /// unavailable — so a caller woken by that very worker's reply would create
278 /// a second one it does not need. The busy count is released *before* the
279 /// reply is sent, so a woken caller always sees its worker as available.
280 busy: usize,
281 /// Workers created. Only ever decremented when a spawn *fails*: a worker
282 /// that exists never exits, which is the whole point.
283 workers: usize,
284}
285
286/// A bounded, permanent set of threads that own this role's blocking TCP
287/// dials.
288///
289/// # Why the dial needs a thread at all
290///
291/// The connect is a blocking syscall and every caller is a task. On the exec
292/// backend a task runs on a cooperative callback-band worker shared with every
293/// other future on its band, so connecting inline parks the band for the whole
294/// attempt — measured exactly there (gdb all-thread dump, host-linux
295/// `realtime-pva-ioc`): one unanswering name server starved every future on Medium
296/// for ~40 s per attempt. So the connect goes to a thread and the caller parks
297/// on a oneshot instead.
298///
299/// # Why the threads are permanent
300///
301/// The obvious shape — one transient thread per dial — is unbounded in thread
302/// *creations*, and creations are what cost on RTEMS (see [`MAX_DIAL_WORKERS`]).
303/// A search engine whose name server is down redials roughly every 10 s for as
304/// long as the IOC runs, so "transient, one per attempt" is a leak with no
305/// ceiling. Making the workers permanent and reusing them removes the family
306/// rather than capping it: after the first dial of each concurrency level there
307/// is nothing left to create.
308///
309/// # What a worker owes the socket it opens
310///
311/// A worker is the **single finalizer** for every socket it opens. If the
312/// caller gave up (timed out, or its future was dropped) the oneshot send fails
313/// and the returned `TcpStream` is dropped right there, closing the fresh
314/// socket. A worker that reaches a request whose caller is already gone skips
315/// the connect entirely, so a backlog built up behind a blackholed peer costs
316/// no sockets at all.
317///
318/// # Where the timeout is *not*
319///
320/// The worker issues a plain blocking [`TcpStream::connect`] — the CA client's
321/// proven on-target dial, C parity with `tcpiiu.cpp`'s blocking `::connect()`,
322/// and a thread that owns its blocking needs no poll machinery. The
323/// application-level bound belongs to the awaiting side, which holds the
324/// [`oneshot::Receiver`] this returns and is free to wrap it in
325/// `runtime::task::timeout`. Do not add a bound here: the two are deliberately
326/// split, and collapsing them puts the application deadline back inside a
327/// syscall that cannot honour it.
328pub struct DialPool {
329 /// OS thread-name stem; workers are `"{name_prefix} {index}"`. Keep it
330 /// short — RTEMS truncates thread names at 16 bytes.
331 name_prefix: &'static str,
332 /// The band every worker enters. Dials belong to the band of the pumps
333 /// they precede, so this is per-role and is why the pool is not global.
334 priority: ThreadPriority,
335 queue: Mutex<DialQueue>,
336 work: Condvar,
337}
338
339impl DialPool {
340 /// Declare a role's dial pool. `const` so it can be a `static`: a pool is
341 /// per-role and lives as long as the process, so a caller needs no `Arc`
342 /// and no lazy initialiser.
343 pub const fn new(name_prefix: &'static str, priority: ThreadPriority) -> Self {
344 Self {
345 name_prefix,
346 priority,
347 queue: Mutex::new(DialQueue {
348 pending: VecDeque::new(),
349 busy: 0,
350 workers: 0,
351 }),
352 work: Condvar::new(),
353 }
354 }
355
356 /// Threads this pool has created — never more than [`MAX_DIAL_WORKERS`].
357 ///
358 /// The bound made observable: this is the number the per-attempt shape grew
359 /// without limit.
360 pub fn worker_count(&self) -> usize {
361 self.lock().workers
362 }
363
364 /// Requests waiting for a worker, and workers currently inside a dial.
365 ///
366 /// The other half of the bound: `worker_count()` alone cannot distinguish
367 /// "four workers, nothing queued" from "four workers, every one pinned and
368 /// a fifth dial waiting" — which is the state
369 /// [`MAX_DIAL_WORKERS`] exists to produce and the
370 /// only state in which the queueing it documents is observable.
371 pub fn queue_depth(&self) -> (usize, usize) {
372 let q = self.lock();
373 (q.pending.len(), q.busy)
374 }
375
376 /// Submit a dial. The returned receiver resolves with whatever the worker's
377 /// `connect` returned.
378 ///
379 /// The error is a thread-creation failure, and only that: it is returned
380 /// *before* the request is queued, so a caller that sees it knows no dial is
381 /// pending on its behalf.
382 pub fn dial(
383 &'static self,
384 target: SocketAddr,
385 ) -> io::Result<oneshot::Receiver<io::Result<TcpStream>>> {
386 let (reply, rx) = oneshot::channel();
387 let req = DialRequest { target, reply };
388
389 let mut q = self.lock();
390 // Each queued request already claims one available worker, so this
391 // request is covered only if the available ones outnumber the queue.
392 if q.pending.len() + q.busy < q.workers || q.workers >= MAX_DIAL_WORKERS {
393 q.pending.push_back(req);
394 drop(q);
395 self.work.notify_one();
396 return Ok(rx);
397 }
398
399 // Create the worker *before* queueing, so a spawn failure leaves the
400 // pool exactly as it found it and the caller keeps its error.
401 let index = q.workers;
402 q.workers += 1;
403 drop(q);
404 if let Err(e) = spawn_dedicated_thread(
405 format!("{} {index}", self.name_prefix),
406 self.priority,
407 StackSizeClass::Small,
408 move || self.worker_loop(),
409 ) {
410 self.lock().workers -= 1;
411 return Err(e);
412 }
413 self.lock().pending.push_back(req);
414 self.work.notify_one();
415 Ok(rx)
416 }
417
418 /// A worker's whole life: take a request, connect, hand the socket back.
419 ///
420 /// Never returns. See the type docs for why that is the fix rather than an
421 /// oversight.
422 fn worker_loop(&self) -> ! {
423 loop {
424 let req = {
425 let mut q = self.lock();
426 loop {
427 if let Some(req) = q.pending.pop_front() {
428 q.busy += 1;
429 break req;
430 }
431 // No lost wakeup to worry about: every worker re-reads
432 // `pending` under this lock before parking, so a request
433 // queued while this one was still running is seen here.
434 q = self.work.wait(q).unwrap_or_else(|e| e.into_inner());
435 }
436 };
437 // The caller gave up while this request sat in the queue. Opening a
438 // socket nobody can receive would only make this worker its
439 // finalizer for no reason.
440 let dialed = (!req.reply.is_closed()).then(|| TcpStream::connect(req.target));
441 // Release the slot *before* replying: the caller this reply wakes
442 // may dial again immediately, and it must see this worker as
443 // available rather than create a second one.
444 self.lock().busy -= 1;
445 if let Some(dialed) = dialed {
446 // Single finalizer: a failed send drops the `TcpStream` here,
447 // which closes the socket this worker opened.
448 let _ = req.reply.send(dialed);
449 }
450 }
451 }
452
453 fn lock(&self) -> MutexGuard<'_, DialQueue> {
454 self.queue.lock().unwrap_or_else(|e| e.into_inner())
455 }
456}
457
458// ---------------------------------------------------------------------------
459// Reader side
460// ---------------------------------------------------------------------------
461
462/// `AsyncRead` over a channel of byte chunks — the blocking stand-in for a
463/// socket read half.
464///
465/// **Cancel-safety** is the whole point of the `cur`/`pos` pair and is why this
466/// type exists at all rather than a channel being read inline. A frame reader
467/// used directly as a `select!` arm survives losing that race because its
468/// accumulated bytes live *outside* it. This adapter has the same property: a
469/// chunk leaves the channel only when `poll_recv` returns `Ready`, and a
470/// partially-copied chunk stays in `cur`/`pos` across as many dropped
471/// `poll_read` futures as the caller likes. A lost race consumes nothing.
472pub struct ChannelReader {
473 rx: mpsc::Receiver<Vec<u8>>,
474 /// The chunk currently being handed out, and how much of it has gone.
475 cur: Vec<u8>,
476 pos: usize,
477}
478
479impl ChannelReader {
480 /// Build an adapter over an existing chunk channel.
481 ///
482 /// Public because a caller may want the adapter without a socket behind it
483 /// — a test double, or a byte source that is not a `TcpStream`. The paired
484 /// [`spawn_reader_pump`] is what a socket-backed caller wants.
485 pub fn new(rx: mpsc::Receiver<Vec<u8>>) -> Self {
486 Self {
487 rx,
488 cur: Vec::new(),
489 pos: 0,
490 }
491 }
492}
493
494impl tokio::io::AsyncRead for ChannelReader {
495 fn poll_read(
496 mut self: Pin<&mut Self>,
497 cx: &mut Context<'_>,
498 buf: &mut ReadBuf<'_>,
499 ) -> Poll<io::Result<()>> {
500 // No room offered: report "nothing filled" without taking anything out
501 // of the channel. Consuming here would be the one way this adapter
502 // could lose bytes.
503 if buf.remaining() == 0 {
504 return Poll::Ready(Ok(()));
505 }
506 let me = &mut *self;
507 loop {
508 if me.pos < me.cur.len() {
509 let n = (me.cur.len() - me.pos).min(buf.remaining());
510 buf.put_slice(&me.cur[me.pos..me.pos + n]);
511 me.pos += n;
512 if me.pos == me.cur.len() {
513 me.cur.clear();
514 me.pos = 0;
515 }
516 return Poll::Ready(Ok(()));
517 }
518 match me.rx.poll_recv(cx) {
519 Poll::Ready(Some(chunk)) => {
520 // An empty chunk is not an EOF marker; skip it rather than
521 // letting it read as one.
522 if chunk.is_empty() {
523 continue;
524 }
525 me.cur = chunk;
526 me.pos = 0;
527 }
528 // Every sender gone = the reader thread ended (EOF, read error,
529 // or RCVTIMEO). Zero bytes filled is what a frame reader turns
530 // into its own peer-closed error — the existing hosted EOF
531 // path, unchanged.
532 Poll::Ready(None) => return Poll::Ready(Ok(())),
533 Poll::Pending => return Poll::Pending,
534 }
535 }
536 }
537}
538
539/// Read loop. Ends on EOF, read error, or a read that outlives `read_timeout`;
540/// dropping `tx` on the way out is the EOF signal to the adapter.
541///
542/// The wait is [`wait_readable`], not the socket's own `SO_RCVTIMEO`, because
543/// the descriptor is non-blocking — see [`own_blocking_mode`] for why it has to
544/// be. `read_timeout` is the same value the option carried, applied per read
545/// exactly as the option applied it, so a connection ends on a silent peer at
546/// the same point it did before.
547fn reader_pump(
548 sock: Arc<TcpStream>,
549 tx: mpsc::Sender<Vec<u8>>,
550 chunk_size: usize,
551 label: String,
552 read_timeout: Option<Duration>,
553) {
554 // `impl Read for &TcpStream`: one shared descriptor, no `try_clone`.
555 let mut sock = &*sock;
556 let mut chunk = vec![0u8; chunk_size];
557 loop {
558 match wait_readable(sock, read_timeout.map(|t| Instant::now() + t)) {
559 Ok(true) => {}
560 Ok(false) => {
561 debug!(label, "blocking reader: receive timeout, ending connection");
562 break;
563 }
564 Err(e) => {
565 debug!(label, error = %e, "blocking reader: wait failed");
566 break;
567 }
568 }
569 let n = match sock.read(&mut chunk) {
570 Ok(0) => break,
571 Ok(n) => n,
572 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
573 // Readiness that yielded nothing: back to the wait, which re-arms
574 // the same bound, so this cannot spin.
575 Err(e) if e.kind() == io::ErrorKind::WouldBlock => continue,
576 Err(e) if is_socket_timeout(e.kind()) => {
577 debug!(label, "blocking reader: receive timeout, ending connection");
578 break;
579 }
580 Err(e) => {
581 debug!(label, error = %e, "blocking reader: read failed");
582 break;
583 }
584 };
585 // The house sync-over-async primitive: parks this thread (no runtime
586 // entered) or hands the worker off (hosted). NOT `blocking_send`.
587 if !matches!(block_on_sync(tx.send(chunk[..n].to_vec())), Ok(Ok(()))) {
588 break;
589 }
590 }
591}
592
593/// The spawned reader pump, woken and joined on **every** exit path.
594///
595/// # Invariant
596///
597/// MUST: once the reader pump has been spawned, it is woken and joined before
598/// its owner returns — clean return, `?`, or a panic unwinding out of the
599/// caller.
600///
601/// # The defect this closes
602///
603/// A writer-spawn failure used to `?` out with the reader already running,
604/// leaving it parked in `read` behind an `SO_RCVTIMEO` that a PVA `op_timeout`
605/// makes effectively infinite (~64,000 s by default), holding its socket and
606/// its descriptor for the life of the IOC. The connection slot was returned
607/// correctly, which is exactly what made the leak invisible: the connection
608/// count looked healthy while descriptors drained away.
609///
610/// Owning the handle in a guard, rather than calling cleanup on the error
611/// branch, is what makes the leak unexpressible: there is no way to have
612/// spawned the reader without also holding the value that joins it. The same
613/// applies to the panic path, which no error-branch cleanup could have covered.
614pub struct ReaderPumpGuard {
615 /// The same descriptor the pump reads from. Owning an `Arc` rather than
616 /// borrowing is load-bearing: waking a pump that has already ended must be
617 /// a no-op on a still-open fd, never a `shutdown` of an fd number the OS
618 /// has since handed to someone else.
619 sock: Arc<TcpStream>,
620 label: String,
621 /// The pooled job running `reader_pump`. Joining it returns the worker to
622 /// its pool; the worker itself is not retired, only the job.
623 job: Option<Job>,
624}
625
626impl Drop for ReaderPumpGuard {
627 fn drop(&mut self) {
628 if let Some(job) = self.job.take() {
629 // The pump's `read` is parked behind an effectively-infinite
630 // timeout, so the socket has to be shut to return it. `ENOTCONN`
631 // when the peer has already gone: there was nothing to wake, which
632 // is not a failure of anything.
633 let _ = self.sock.shutdown(Shutdown::Both);
634 // The join result is the only place a panicked pump is ever
635 // reported: `reader_pump` returns `()`, so an `Err` here means it
636 // unwound, and the connection's own error will be a bland
637 // channel-closed rather than the cause. Discarding it left the two
638 // unlinkable.
639 if job.join().is_err() {
640 pump_thread_lost("reader", &self.label, "panicked");
641 }
642 }
643 }
644}
645
646/// Drive `sock`'s read half on a pooled `worker`, yielding the `AsyncRead`
647/// half of the seam and the guard that retires the job.
648///
649/// Infallible: the thread already exists — it is the leased `worker` — so there
650/// is no creation to fail. Admission failure now lives in
651/// [`WorkerPool::acquire`], which is where it belongs.
652///
653/// `queue_depth` is the chunk channel's depth. **One** is the faithful choice
654/// for a demand-driven frame reader — one read per poll, each frame dispatched
655/// fully before the next read — because it reproduces that with at most one
656/// chunk of read-ahead, which the kernel receive buffer already provides. A
657/// larger depth lets a fast peer queue chunks while a slow consumer blocks: a
658/// behaviour change, not an optimisation.
659pub fn spawn_reader_pump(
660 worker: Worker,
661 sock: Arc<TcpStream>,
662 label: &str,
663 chunk_size: usize,
664 queue_depth: usize,
665) -> (ChannelReader, ReaderPumpGuard) {
666 // What the caller configured, read back rather than passed in, so this
667 // signature is unchanged: the socket already carries the read bound, and
668 // `SO_RCVTIMEO` stops being the mechanism that applies it without ceasing
669 // to be where the value lives. `None` — never set, or a target whose
670 // getter declines — polls with no deadline, which is what a socket with no
671 // `SO_RCVTIMEO` did before.
672 let read_timeout = sock_read_timeout(&sock);
673 spawn_reader_pump_with_timeout(worker, sock, label, chunk_size, queue_depth, read_timeout)
674}
675
676fn sock_read_timeout(sock: &TcpStream) -> Option<Duration> {
677 sock.read_timeout().ok().flatten()
678}
679
680fn spawn_reader_pump_with_timeout(
681 worker: Worker,
682 sock: Arc<TcpStream>,
683 label: &str,
684 chunk_size: usize,
685 queue_depth: usize,
686 read_timeout: Option<Duration>,
687) -> (ChannelReader, ReaderPumpGuard) {
688 let (tx, rx) = mpsc::channel::<Vec<u8>>(queue_depth);
689 let pump_sock = sock.clone();
690 let pump_label = label.to_string();
691 let job = worker.run(move || reader_pump(pump_sock, tx, chunk_size, pump_label, read_timeout));
692 (
693 ChannelReader::new(rx),
694 ReaderPumpGuard {
695 sock,
696 label: label.to_string(),
697 job: Some(job),
698 },
699 )
700}
701
702// ---------------------------------------------------------------------------
703// Writer side
704// ---------------------------------------------------------------------------
705
706/// Wake slot for a `poll_write` that found the frame channel full. The writer
707/// pump wakes it after each frame it takes, which is the moment room appears.
708#[derive(Default)]
709struct WriteRoom {
710 waker: Mutex<Option<Waker>>,
711}
712
713impl WriteRoom {
714 fn park(&self, cx: &Context<'_>) {
715 *self.waker.lock().expect("write-room waker poisoned") = Some(cx.waker().clone());
716 }
717
718 fn wake(&self) {
719 let waker = self.waker.lock().expect("write-room waker poisoned").take();
720 if let Some(w) = waker {
721 w.wake();
722 }
723 }
724}
725
726/// `AsyncWrite` over a channel of frames — the blocking stand-in for a socket
727/// write half.
728///
729/// Holds a [`mpsc::WeakSender`], never a strong one, and that is load-bearing
730/// rather than tidiness. This adapter is typically owned by a task that is
731/// *aborted*, not joined, when the connection ends, so the moment its last
732/// strong sender drops is not a moment the owner controls. With only a weak
733/// handle here, [`WriterPumpGuard`]'s sender is the sole thing keeping the
734/// channel open, and dropping it ends the pump deterministically instead of
735/// whenever the runtime gets round to reaping an aborted task.
736pub struct ChannelWriter {
737 tx: mpsc::WeakSender<Vec<u8>>,
738 room: Arc<WriteRoom>,
739}
740
741fn write_closed() -> io::Error {
742 io::Error::new(
743 io::ErrorKind::BrokenPipe,
744 "the writer pump thread has ended",
745 )
746}
747
748impl tokio::io::AsyncWrite for ChannelWriter {
749 fn poll_write(
750 self: Pin<&mut Self>,
751 cx: &mut Context<'_>,
752 buf: &[u8],
753 ) -> Poll<io::Result<usize>> {
754 if buf.is_empty() {
755 return Poll::Ready(Ok(0));
756 }
757 let Some(tx) = self.tx.upgrade() else {
758 return Poll::Ready(Err(write_closed()));
759 };
760 // Register interest BEFORE trying, so a take that happens between the
761 // try and the return cannot be missed: either `try_send` sees the room
762 // that take created, or the take's `wake()` finds this waker.
763 self.room.park(cx);
764 match tx.try_send(buf.to_vec()) {
765 Ok(()) => Poll::Ready(Ok(buf.len())),
766 Err(mpsc::error::TrySendError::Full(_)) => Poll::Pending,
767 Err(mpsc::error::TrySendError::Closed(_)) => Poll::Ready(Err(write_closed())),
768 }
769 // `tx` drops here. Nothing in this adapter holds a strong sender across
770 // a suspension, which is what makes the guard's drop decisive.
771 }
772
773 /// Frames are flushed by the writer pump as it takes them; there is no
774 /// buffer here to push.
775 fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
776 Poll::Ready(Ok(()))
777 }
778
779 fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
780 Poll::Ready(Ok(()))
781 }
782}
783
784/// `POLLOUT` and `MSG_DONTWAIT` for this target.
785///
786/// Deliberately not `libc::POLLOUT` / `libc::MSG_DONTWAIT` — but by choice,
787/// not because a bare name fails to resolve. It once did: `unix/newlib/arm`
788/// and `unix/newlib/rtems` defined 16 of these names with **different
789/// values** — `POLLOUT` `0x10` against `0x0004`, `MSG_DONTWAIT` `4` against
790/// `0x80` — and that glob-versus-glob collision made naming them through
791/// `libc` an ambiguity error on `armv7-rtems-eabihf`. The pinned `libc` fork
792/// (`Cargo.lock:2076-2078`) closed it in `6f64e70d`, "newlib: gate the arm
793/// prelude import on not(rtems)", so each name now has exactly one definition
794/// there and a bare `libc::POLLOUT` both compiles and carries the right
795/// value — `asyn-rs`'s serial driver names `libc::POLLIN`/`POLLOUT` directly
796/// and is inside the RTEMS gate's build. Nobody needs to re-derive that.
797///
798/// What survives is the half of the reason that never depended on the
799/// collision, and it is the better half: RTEMS's stack is libbsd, so the
800/// FreeBSD values are the true ones (`sys/poll.h`, `sys/socket.h`), and these
801/// constants are pinned to the target's own headers rather than inherited
802/// from whichever module the glob happened to win. [`FIONREAD_REQUEST`] above
803/// is stated for that same reason — except that one is still *required*,
804/// because `FIONREAD` is defined in neither newlib module.
805///
806/// Every other Unix — the hosted hosts and `*-wrs-vxworks*` — takes `libc`'s.
807#[cfg(target_os = "rtems")]
808const POLLOUT_EVENT: libc::c_short = 0x0004;
809#[cfg(target_os = "rtems")]
810const POLLIN_EVENT: libc::c_short = 0x0001;
811#[cfg(target_os = "rtems")]
812const SEND_DONTWAIT: libc::c_int = 0x0080;
813#[cfg(all(unix, not(target_os = "rtems")))]
814const POLLOUT_EVENT: libc::c_short = libc::POLLOUT;
815#[cfg(all(unix, not(target_os = "rtems")))]
816const POLLIN_EVENT: libc::c_short = libc::POLLIN;
817#[cfg(all(unix, not(target_os = "rtems")))]
818const SEND_DONTWAIT: libc::c_int = libc::MSG_DONTWAIT;
819
820/// Put `sock` in non-blocking mode, so that no syscall this module issues on it
821/// can park regardless of which flags and options the target honours.
822///
823/// This module owns the descriptor's blocking mode; that ownership is what the
824/// bound is made of. Both directions are gated by a `poll` against the caller's
825/// own deadline ([`wait_readable`], [`wait_writable`]), so the mode is not a
826/// performance choice but the thing that makes "the syscall returns" true by
827/// construction instead of true wherever `MSG_DONTWAIT` or `SO_SNDTIMEO`
828/// happens to be implemented.
829///
830/// C reaches the same place the same way: `setNonBlock(fd, 1)` at connect under
831/// `USE_POLL` (`drvAsynIPPort.c:511`), with a poll on reads as well as writes.
832/// Which is also the evidence that the call is available on the embedded
833/// targets — it is `ioctl(FIONBIO)`, the one socket control C already relies on
834/// there, not one of the options VxWorks answers `ENOPROTOOPT` to.
835///
836/// Windows keeps blocking sockets and its `SO_SNDTIMEO`/`SO_RCVTIMEO`, which it
837/// does implement; the `not(unix)` arms of both waits are built on them.
838#[cfg(unix)]
839fn own_blocking_mode(sock: &TcpStream) -> io::Result<()> {
840 sock.set_nonblocking(true)
841}
842
843#[cfg(not(unix))]
844fn own_blocking_mode(_sock: &TcpStream) -> io::Result<()> {
845 Ok(())
846}
847
848/// Wait until `sock` has a byte to read or has hit EOF, or `deadline` passes.
849/// `Ok(true)` = readable, `Ok(false)` = the deadline passed with it still empty.
850/// `None` waits with no deadline, which is what an unconfigured socket did
851/// before.
852///
853/// The read-side twin of [`wait_writable`], and it exists for the same reason:
854/// with the descriptor non-blocking, a `read` cannot park, so the bound has to
855/// come from here. It replaces `SO_RCVTIMEO` as the *mechanism* while keeping
856/// it as the *value* — callers still say how long a read may take, and
857/// [`drive_socket_blocking`] still sets the option for the `not(unix)` arm.
858///
859/// `POLLHUP` also returns `Ok(true)`: the read that follows returns 0 and the
860/// pump ends on its existing EOF path, which is how a `shutdown` still wakes a
861/// waiting reader now that no `read` is parked for it to interrupt.
862#[cfg(unix)]
863fn wait_readable(sock: &TcpStream, deadline: Option<Instant>) -> io::Result<bool> {
864 use std::os::fd::AsRawFd;
865
866 loop {
867 let ms = match deadline {
868 Some(d) => {
869 let remaining = d.saturating_duration_since(Instant::now());
870 if remaining.is_zero() {
871 return Ok(false);
872 }
873 remaining.as_millis().max(1).min(libc::c_int::MAX as u128) as libc::c_int
874 }
875 None => -1,
876 };
877 let mut fds = libc::pollfd {
878 fd: sock.as_raw_fd(),
879 events: POLLIN_EVENT,
880 revents: 0,
881 };
882 // SAFETY: one initialised `pollfd` whose `fd` is this borrowed socket's
883 // and stays open for the call; `poll` reads `fd`/`events` and writes
884 // only `revents`.
885 let rc = unsafe { libc::poll(&mut fds, 1, ms) };
886 if rc > 0 {
887 return Ok(true);
888 }
889 if rc == 0 {
890 return Ok(false);
891 }
892 let e = io::Error::last_os_error();
893 if e.kind() != io::ErrorKind::Interrupted {
894 return Err(e);
895 }
896 // `EINTR`: the remaining time is recomputed at the top, so a signal
897 // storm cannot extend the bound.
898 }
899}
900
901/// Non-Unix arm: Windows implements `SO_RCVTIMEO` and keeps a blocking socket,
902/// so the read that follows carries its own bound and this only arms it.
903#[cfg(not(unix))]
904fn wait_readable(sock: &TcpStream, deadline: Option<Instant>) -> io::Result<bool> {
905 let Some(d) = deadline else {
906 sock.set_read_timeout(None)?;
907 return Ok(true);
908 };
909 let remaining = d.saturating_duration_since(Instant::now());
910 if remaining.is_zero() {
911 return Ok(false);
912 }
913 sock.set_read_timeout(Some(remaining.max(Duration::from_millis(1))))?;
914 Ok(true)
915}
916
917/// Wait until `sock` will accept at least one byte, or `deadline` passes.
918/// `Ok(true)` = writable, `Ok(false)` = the deadline passed with it still full.
919///
920/// Half of what makes [`write_frame_deadline`]'s bound hold by construction:
921/// the wait belongs to this module, so no socket option is load-bearing and a
922/// target that implements none of them is bounded exactly as one that
923/// implements them all. `POLLERR`/`POLLHUP` also return `Ok(true)`, so the send
924/// that follows reports the real errno instead of this function inventing one.
925#[cfg(unix)]
926fn wait_writable(sock: &TcpStream, deadline: Instant) -> io::Result<bool> {
927 use std::os::fd::AsRawFd;
928
929 loop {
930 let remaining = deadline.saturating_duration_since(Instant::now());
931 if remaining.is_zero() {
932 return Ok(false);
933 }
934 // Rounded up to 1 ms so a sub-millisecond remainder waits instead of
935 // spinning, and clamped so a very long deadline still fits `poll`'s
936 // `c_int` milliseconds.
937 let ms = remaining.as_millis().max(1).min(libc::c_int::MAX as u128) as libc::c_int;
938 let mut fds = libc::pollfd {
939 fd: sock.as_raw_fd(),
940 events: POLLOUT_EVENT,
941 revents: 0,
942 };
943 // SAFETY: one initialised `pollfd` whose `fd` is this borrowed socket's
944 // and stays open for the call; `poll` reads `fd`/`events` and writes
945 // only `revents`.
946 let rc = unsafe { libc::poll(&mut fds, 1, ms) };
947 if rc > 0 {
948 return Ok(true);
949 }
950 if rc == 0 {
951 return Ok(false);
952 }
953 let e = io::Error::last_os_error();
954 if e.kind() != io::ErrorKind::Interrupted {
955 return Err(e);
956 }
957 // `EINTR`: the remaining time is recomputed at the top, so a signal
958 // storm cannot extend the bound.
959 }
960}
961
962/// Hand as much of `buf` to the socket as it will take **without parking**,
963/// however many bytes that is.
964///
965/// The other half of the bound, and the half that is easy to get wrong: a
966/// blocking `write` on a stream socket does not return a short count when the
967/// send buffer fills, it waits until the *whole* buffer is queued
968/// (`tcp_sendmsg` parks in `sk_stream_wait_memory`). So waiting for `POLLOUT`
969/// first is not enough on its own — the very next `write` re-enters the same
970/// unbounded wait one byte later. The socket is non-blocking for as long as it
971/// is live ([`own_blocking_mode`]), so the send takes what there is room for and
972/// returns; `MSG_DONTWAIT` rides on top as the per-call form of the same ask.
973///
974/// That mode is on the file description the reader pump shares (see the module
975/// docs on why it is shared and not `dup`ed), which is what [`wait_readable`]
976/// exists for: the reader polls before reading rather than parking in `read`,
977/// so sharing the description with a non-blocking writer costs it nothing.
978///
979/// A full buffer surfaces as `EAGAIN`/`WouldBlock`, which returns the caller to
980/// [`wait_writable`] and therefore to the deadline.
981///
982/// `SIGPIPE` needs no flag here: Rust's startup sets it to `SIG_IGN` on every
983/// Unix target, so a send to a closed peer returns `EPIPE`.
984///
985/// # The flag is the fast path, not the guarantee
986///
987/// It cannot be the guarantee, because a target may ignore it. XNU's `sosend`
988/// decides whether to sleep from `so_state & SS_NBIO` and its own internal
989/// `MSG_NBIO`, and `MSG_DONTWAIT` reaches it only as the sockbuf-lock wait
990/// hint, so on Darwin the send parked and the deadline was left riding on
991/// whatever `SO_SNDTIMEO` the caller had armed — measured, macOS CI
992/// 2026-07-27, `doc/darwin-send-dontwait-gap.md`. What makes the send return
993/// on every target is [`own_blocking_mode`]. The flag stays because where it
994/// *is* honoured it saves the loop a `poll` on the common path where the
995/// socket has room.
996#[cfg(unix)]
997fn write_some(sock: &TcpStream, buf: &[u8]) -> io::Result<usize> {
998 use std::os::fd::AsRawFd;
999
1000 // SAFETY: `buf` is a valid initialised slice borrowed for the call, and
1001 // `as_raw_fd()` is this borrowed socket's open descriptor. `send` reads
1002 // `buf.len()` bytes from the pointer and writes nothing through it.
1003 let n = unsafe {
1004 libc::send(
1005 sock.as_raw_fd(),
1006 buf.as_ptr().cast(),
1007 buf.len(),
1008 SEND_DONTWAIT,
1009 )
1010 };
1011 if n < 0 {
1012 return Err(io::Error::last_os_error());
1013 }
1014 Ok(n as usize)
1015}
1016
1017/// Non-Unix arm of the same two-part contract.
1018///
1019/// `poll` would mean `WSAPoll` and a Win32 dependency this crate does not
1020/// carry, and Windows *does* implement `SO_SNDTIMEO`. So arm it — from inside
1021/// this module, not from a caller — to the time the deadline has left: the send
1022/// that follows returns within `remaining`, and the loop ends the frame on the
1023/// next pass. The bound is still owned here, which is the property that
1024/// matters.
1025///
1026/// The blocking pumps are refused on Windows at compile time (`lib.rs`), so
1027/// this arm keeps the primitive's contract uniform where the module still
1028/// compiles rather than carrying production traffic.
1029#[cfg(not(unix))]
1030fn wait_writable(sock: &TcpStream, deadline: Instant) -> io::Result<bool> {
1031 let remaining = deadline.saturating_duration_since(Instant::now());
1032 if remaining.is_zero() {
1033 return Ok(false);
1034 }
1035 sock.set_write_timeout(Some(remaining.max(Duration::from_millis(1))))?;
1036 Ok(true)
1037}
1038
1039#[cfg(not(unix))]
1040fn write_some(sock: &TcpStream, buf: &[u8]) -> io::Result<usize> {
1041 let mut sock = sock;
1042 sock.write(buf)
1043}
1044
1045/// Write one whole frame under a **deadline**, not merely a per-syscall
1046/// timeout.
1047///
1048/// A hosted writer bounds `write_all(&frame)` as a unit. A per-syscall socket
1049/// timeout bounds each `write` instead, so a peer that accepts one byte per
1050/// tick never trips it and holds the pump thread indefinitely — the exact
1051/// stuck-peer hazard the hosted timeout exists to prevent, on a resource (an OS
1052/// thread) that is scarcer on RTEMS than a task is on the host.
1053///
1054/// # The deadline holds on every target, by construction
1055///
1056/// This function owns its bound end to end. It takes over the socket's blocking
1057/// mode (`own_blocking_mode`, crate-private) so that no syscall below it can
1058/// park; `wait_writable` does every wait, against `deadline`. Between them there
1059/// is no call in this loop that can outlast `send_timeout`, and nothing a caller
1060/// does or fails to do can disarm it.
1061///
1062/// Owning the mode is what makes that true rather than nearly true. `write_some`
1063/// passing `MSG_DONTWAIT` is not enough on its own: XNU consults `SS_NBIO` and
1064/// its internal `MSG_NBIO` and ignores the flag a caller sends, so on Darwin the
1065/// send parked and the deadline was carried by whatever `SO_SNDTIMEO` the caller
1066/// happened to have armed — measured, macOS CI 2026-07-27, where the case that
1067/// armed none outlived a 20 s wait while its armed sibling ended on time. The
1068/// flag stays, because where it is honoured it saves the loop a `poll`, but it
1069/// is no longer what the guarantee rests on.
1070///
1071/// It used to lean on the caller having set `SO_SNDTIMEO`, which was the only
1072/// thing that returned control to this loop. That made the bound conditional on
1073/// a socket option, and VxWorks 7 does not implement it — `setsockopt` returns
1074/// `ENOPROTOOPT`, so on that target the deadline was silently absent and a peer
1075/// that accepted the connection and then stopped reading parked the pump with
1076/// nothing entitled to reclaim it
1077/// (`doc/vxworks-circuit-wedge-on-target-measurement.md` §5). An invariant that
1078/// one target can switch off is not an invariant; the wait is the caller's own
1079/// now, and `SO_SNDTIMEO` is not set anywhere in this module.
1080///
1081/// A partial write on expiry needs no repair: the caller ends the pump and the
1082/// connection is torn down, so nothing is ever written to this socket again.
1083pub fn write_frame_deadline(
1084 sock: &TcpStream,
1085 frame: &[u8],
1086 send_timeout: Duration,
1087) -> io::Result<()> {
1088 // Here, not at the call sites, so that no caller can be the one that forgot
1089 // — including a caller that reached this socket without going through
1090 // `drive_socket_blocking`. Idempotent, so the writer pump paying for it once
1091 // per frame costs an `ioctl` next to the `poll` and `send` it already makes.
1092 own_blocking_mode(sock)?;
1093 // `impl Write for &TcpStream`: rebind so `write`/`flush` have a mutable
1094 // place to borrow, without needing `&mut TcpStream` from the caller.
1095 let mut sock = sock;
1096 let deadline = Instant::now() + send_timeout;
1097 let mut off = 0;
1098 while off < frame.len() {
1099 // The one gate, ahead of every syscall, so every way round the loop is
1100 // bounded — a stalled peer, a trickling one, and an `Interrupted`
1101 // storm alike.
1102 if !wait_writable(sock, deadline)? {
1103 return Err(io::Error::new(
1104 io::ErrorKind::TimedOut,
1105 "send deadline expired with the frame incomplete",
1106 ));
1107 }
1108 match write_some(sock, &frame[off..]) {
1109 Ok(0) => {
1110 return Err(io::Error::new(
1111 io::ErrorKind::WriteZero,
1112 "peer accepted no bytes",
1113 ));
1114 }
1115 Ok(n) => off += n,
1116 Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
1117 // `EAGAIN` from the non-blocking send, or the non-Unix arm's socket
1118 // timeout: no progress, back round to the gate above.
1119 Err(e) if is_socket_timeout(e.kind()) => {}
1120 Err(e) => return Err(e),
1121 }
1122 }
1123 sock.flush()
1124}
1125
1126/// Drain frames to the socket in order. Ends when the guard drops the last
1127/// strong sender, or on the first write error / send-deadline expiry.
1128///
1129/// Whichever of those ends it, it shuts the socket on the way out. A dead
1130/// writer means the connection is over, and the consumer must not wait up to a
1131/// heartbeat period to find that out — but the fix is the socket shutdown, not
1132/// an extra `select!` arm in the protocol loop: the reader pump's `read` then
1133/// returns 0 and the consumer unwinds down its existing EOF path, leaving the
1134/// protocol module and the hosted timing alone.
1135fn writer_pump(
1136 sock: Arc<TcpStream>,
1137 mut rx: mpsc::Receiver<Vec<u8>>,
1138 room: Arc<WriteRoom>,
1139 send_timeout: Duration,
1140 label: String,
1141) {
1142 // `Ok(None)` = the guard let go of its sender; `Err(_)` = this thread
1143 // cannot block here at all. Both end the pump.
1144 while let Ok(Some(frame)) = block_on_sync(rx.recv()) {
1145 // A slot just opened; let a parked `poll_write` retry.
1146 room.wake();
1147 if let Err(e) = write_frame_deadline(&sock, &frame, send_timeout) {
1148 debug!(label, error = %e, "blocking writer: send failed, ending connection");
1149 break;
1150 }
1151 }
1152 // Whatever parked the producer, it must not stay parked on a dead writer.
1153 room.wake();
1154 // Uniform, not special-cased on *why* the pump ended: the only thing that
1155 // ends it is the connection being over. On the error paths this is what
1156 // retires the connection at once; on the normal path the owner is already
1157 // tearing down and repeats the same shutdown a moment later, harmlessly —
1158 // every frame this thread was given has been written before it gets here.
1159 let _ = sock.shutdown(Shutdown::Both);
1160}
1161
1162/// The spawned writer pump and the only strong frame sender, retired together
1163/// on **every** exit path.
1164///
1165/// The sender lives here rather than beside the guard because the pump parks on
1166/// `rx.recv()` and leaves only when the last strong sender drops. A guard that
1167/// joined without dropping the sender would hang; keeping the two in one value
1168/// means the order cannot be got wrong, and does not depend on the declaration
1169/// order of two separate locals.
1170pub struct WriterPumpGuard {
1171 frames: Option<mpsc::Sender<Vec<u8>>>,
1172 label: String,
1173 /// The pooled job running `writer_pump`; joining it returns the worker.
1174 job: Option<Job>,
1175}
1176
1177impl Drop for WriterPumpGuard {
1178 fn drop(&mut self) {
1179 // Decisive because it is the only strong sender — [`ChannelWriter`]
1180 // holds a weak handle. The pump drains what is queued, sees `None`, and
1181 // exits; on its way out it shuts the socket.
1182 drop(self.frames.take());
1183 if let Some(job) = self.job.take() {
1184 // Same reading as [`ReaderPumpGuard`]'s: an `Err` is a panicked
1185 // pump, and a pump that unwound with frames still queued dropped
1186 // them.
1187 if job.join().is_err() {
1188 pump_thread_lost("writer", &self.label, "panicked");
1189 }
1190 }
1191 }
1192}
1193
1194/// Drive `sock`'s write half on a pooled `worker`, yielding the `AsyncWrite`
1195/// half of the seam and the guard that retires the job. Infallible for the same
1196/// reason as [`spawn_reader_pump`].
1197///
1198/// `queue_depth` follows the same reasoning as [`spawn_reader_pump`]'s: a
1199/// producer that emits one frame at a time and waits for it gets, at depth 1,
1200/// the same backpressure a blocking socket write would.
1201///
1202/// `send_timeout` bounds one whole frame and needs no cooperation from the
1203/// caller: [`write_frame_deadline`] owns the wait it is enforced by.
1204pub fn spawn_writer_pump(
1205 worker: Worker,
1206 sock: Arc<TcpStream>,
1207 label: &str,
1208 send_timeout: Duration,
1209 queue_depth: usize,
1210) -> (ChannelWriter, WriterPumpGuard) {
1211 let (tx, rx) = mpsc::channel::<Vec<u8>>(queue_depth);
1212 let room = Arc::new(WriteRoom::default());
1213 let adapter = ChannelWriter {
1214 tx: tx.downgrade(),
1215 room: room.clone(),
1216 };
1217 let pump_label = label.to_string();
1218 let job = worker.run(move || writer_pump(sock, rx, room, send_timeout, pump_label));
1219 (
1220 adapter,
1221 WriterPumpGuard {
1222 // The only strong sender moves into the guard, so it cannot be
1223 // dropped out of order with the join. `adapter` above already took
1224 // its weak handle.
1225 frames: Some(tx),
1226 label: label.to_string(),
1227 job: Some(job),
1228 },
1229 )
1230}
1231
1232// ---------------------------------------------------------------------------
1233// Owning adapters: the shape a caller with no teardown thread of its own wants
1234// ---------------------------------------------------------------------------
1235
1236/// A [`ChannelReader`] that owns its pump guard.
1237///
1238/// The server driver keeps its guards as locals because it *has* a thread that
1239/// outlives the protocol future and can drop them in a chosen order. A client
1240/// connection has no such thread: its reader and writer are tasks, and the
1241/// adapters are the only things the connection hands them. So for that shape
1242/// the guard rides *inside* the adapter, and the rule "you cannot hold the byte
1243/// source without holding the thing that retires its pump" holds there too.
1244pub struct GuardedReader {
1245 inner: ChannelReader,
1246 _guard: ReaderPumpGuard,
1247 /// The connection's worker-set lease, shared with [`GuardedWriter`]. The set
1248 /// returns to its pool only when both adapters — and both pump jobs they
1249 /// hold — are gone, which is exactly when the connection is over.
1250 _lease: Arc<SetLease>,
1251}
1252
1253impl tokio::io::AsyncRead for GuardedReader {
1254 fn poll_read(
1255 self: Pin<&mut Self>,
1256 cx: &mut Context<'_>,
1257 buf: &mut ReadBuf<'_>,
1258 ) -> Poll<io::Result<()>> {
1259 Pin::new(&mut self.get_mut().inner).poll_read(cx, buf)
1260 }
1261}
1262
1263/// A [`ChannelWriter`] that owns its pump guard. See [`GuardedReader`].
1264pub struct GuardedWriter {
1265 inner: ChannelWriter,
1266 _guard: WriterPumpGuard,
1267 /// The other strong reference to the connection's lease; see
1268 /// [`GuardedReader`].
1269 _lease: Arc<SetLease>,
1270}
1271
1272impl tokio::io::AsyncWrite for GuardedWriter {
1273 fn poll_write(
1274 self: Pin<&mut Self>,
1275 cx: &mut Context<'_>,
1276 buf: &[u8],
1277 ) -> Poll<io::Result<usize>> {
1278 Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
1279 }
1280
1281 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1282 Pin::new(&mut self.get_mut().inner).poll_flush(cx)
1283 }
1284
1285 fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1286 Pin::new(&mut self.get_mut().inner).poll_shutdown(cx)
1287 }
1288}
1289
1290/// Everything a caller needs to set up on a socket before its pumps start.
1291#[derive(Clone, Debug)]
1292pub struct PumpConfig {
1293 /// `SO_RCVTIMEO`. NOT a shutdown mechanism — a protocol's idle timeout is
1294 /// typically hours, so what ends a parked reader is the guard's `shutdown`.
1295 pub read_timeout: Duration,
1296 /// The bound on writing one whole frame; see [`write_frame_deadline`].
1297 pub send_timeout: Duration,
1298 /// Bytes per blocking read. [`DEFAULT_READ_CHUNK`] unless the consumer's
1299 /// hosted reader uses a different one.
1300 pub chunk_size: usize,
1301 /// Depth of both the chunk and the frame channel.
1302 pub queue_depth: usize,
1303}
1304
1305impl Default for PumpConfig {
1306 fn default() -> Self {
1307 Self {
1308 read_timeout: Duration::from_secs(64_000),
1309 send_timeout: Duration::from_secs(30),
1310 chunk_size: DEFAULT_READ_CHUNK,
1311 queue_depth: 1,
1312 }
1313 }
1314}
1315
1316/// Drive one already-connected socket with two blocking pumps, returning the
1317/// two owning adapters.
1318///
1319/// This is the whole seam for a caller that has no teardown thread: hand it a
1320/// connected `TcpStream`, receive an `AsyncRead` and an `AsyncWrite` that the
1321/// protocol code cannot tell from a split socket, with both pump threads owned
1322/// by the values returned.
1323///
1324/// The socket's blocking mode is taken over here (`own_blocking_mode`,
1325/// crate-private), and fatally: it is what makes both pumps' bounds hold by
1326/// construction rather than wherever a flag or option is honoured, so a target
1327/// that refused it would be a target this seam cannot bound, and that is worth
1328/// a failed dial rather than a silent park. `SO_RCVTIMEO` is still set, also
1329/// fatally, but as the *value* the reader's wait uses and as the mechanism on
1330/// the `not(unix)` arm; on unix the wait is a `POLLIN` poll. There is no
1331/// send-side counterpart: [`write_frame_deadline`] owns its own bound and needs
1332/// no socket option, so there is nothing here for a target that implements
1333/// fewer of them to switch off.
1334///
1335/// # The pool, and the two bands it carries
1336///
1337/// The two pumps come from one leased worker set of `pool`, taken atomically so
1338/// a circuit at capacity can never hold one pump and block for the other. Their
1339/// bands are the pool roster's, not this function's: at least one caller's
1340/// upstream C derives two — libca gives a circuit's receive thread
1341/// `highestPriorityLevelBelow(initializing thread)` and its send thread
1342/// `lowestPriorityLevelAbove(...)` (`tcpiiu.cpp:677-682`), so the sender sits
1343/// *above* the receiver and can always drain a queue the receiver's work is
1344/// filling — and a caller whose upstream uses one band for both (pvxs, one
1345/// reactor thread) declares the same band twice in its roster. The `Err` is now
1346/// admission's: [`io::ErrorKind::WouldBlock`] when the circuit pool is full,
1347/// otherwise a socket-option or thread-creation failure.
1348pub fn drive_socket_blocking(
1349 pool: &WorkerPool<2>,
1350 stream: TcpStream,
1351 label: &str,
1352 config: &PumpConfig,
1353) -> io::Result<(GuardedReader, GuardedWriter)> {
1354 let _ = stream.set_nodelay(true);
1355 // The mode both pumps' bounds are built on, fatal: see this function's docs.
1356 own_blocking_mode(&stream)?;
1357 // SO_RCVTIMEO, fatal: every target that runs this accepts it.
1358 stream.set_read_timeout(Some(config.read_timeout))?;
1359 // No SO_SNDTIMEO, on purpose. It was set here once, and it was the send
1360 // deadline's only way of regaining control — which made the deadline
1361 // conditional on an option VxWorks 7 does not implement (`ENOPROTOOPT`,
1362 // errno 42, measured on target). Setting it fatally aborted every CA client
1363 // circuit the instant its dial succeeded; setting it best-effort left the
1364 // writer pump able to park with nothing to reclaim it. Neither is a bound.
1365 // `write_frame_deadline` now waits for writability against its own
1366 // deadline, so the guarantee is the same on a target that implements every
1367 // socket option and on one that implements none.
1368
1369 // Borrow the circuit's two pump workers as one set, or refuse. Roster order
1370 // is [reader, writer], the order `acquire` returns them.
1371 let (lease, [reader_worker, writer_worker]) = pool.acquire()?;
1372 let lease = Arc::new(lease);
1373
1374 // One socket, two roles: the SAME descriptor shared through an `Arc`. See
1375 // the module docs for why this is not `try_clone`.
1376 let stream = Arc::new(stream);
1377
1378 // The configured value directly, not read back off the socket: this is the
1379 // path that knows it, and it should not depend on the target implementing
1380 // the `SO_RCVTIMEO` *getter* as well as the setter.
1381 let (reader, reader_guard) = spawn_reader_pump_with_timeout(
1382 reader_worker,
1383 stream.clone(),
1384 label,
1385 config.chunk_size,
1386 config.queue_depth,
1387 Some(config.read_timeout),
1388 );
1389 let (writer, writer_guard) = spawn_writer_pump(
1390 writer_worker,
1391 stream,
1392 label,
1393 config.send_timeout,
1394 config.queue_depth,
1395 );
1396
1397 Ok((
1398 GuardedReader {
1399 inner: reader,
1400 _guard: reader_guard,
1401 _lease: lease.clone(),
1402 },
1403 GuardedWriter {
1404 inner: writer,
1405 _guard: writer_guard,
1406 _lease: lease,
1407 },
1408 ))
1409}
1410
1411/// The role roster a circuit's [`drive_socket_blocking`] pool must be built
1412/// with: `[reader, writer]`, both on `Small` stacks. The two bands are the
1413/// caller's to choose (see [`drive_socket_blocking`]'s docs).
1414pub fn circuit_roster(
1415 reader_priority: ThreadPriority,
1416 writer_priority: ThreadPriority,
1417) -> [WorkerRole; 2] {
1418 [
1419 WorkerRole {
1420 suffix: "reader",
1421 stack: StackSizeClass::Small,
1422 priority: reader_priority,
1423 },
1424 WorkerRole {
1425 suffix: "writer",
1426 stack: StackSizeClass::Small,
1427 priority: writer_priority,
1428 },
1429 ]
1430}
1431
1432#[cfg(test)]
1433mod tests {
1434 use super::*;
1435 use std::net::{TcpListener, TcpStream as StdTcpStream};
1436 use std::thread;
1437 use tokio::io::{AsyncReadExt, AsyncWriteExt};
1438
1439 /// Production scope of this file: everything before the first column-0
1440 /// `#[cfg(test)]`.
1441 fn production_scope(src: &str) -> &str {
1442 match src.find("\n#[cfg(test)]") {
1443 Some(i) => &src[..i],
1444 None => src,
1445 }
1446 }
1447
1448 /// The production scope with every comment removed.
1449 ///
1450 /// Both guards below forbid *code* from naming something, and this module's
1451 /// docs name several of those things at length precisely because explaining
1452 /// why they are forbidden is the point. Matching raw source made the
1453 /// `try_clone` guard fail on its own rationale — five prose hits, zero code
1454 /// hits — which is a guard that punishes documentation. Stripping comments
1455 /// first is what makes the assertion mean what it says.
1456 fn code_only(src: &str) -> String {
1457 src.lines()
1458 .map(|line| match line.find("//") {
1459 Some(i) => &line[..i],
1460 None => line,
1461 })
1462 .collect::<Vec<_>>()
1463 .join("\n")
1464 }
1465
1466 /// The RTEMS constraint this module exists to satisfy: it must not reach
1467 /// for tokio's async net/timer/spawn machinery, none of which builds for
1468 /// `armv7-rtems-eabihf`, and it must not suspend a future directly — every
1469 /// await goes through `block_on_sync`. `tokio::sync` and `tokio::io`'s
1470 /// traits ARE allowed and are what the two adapters are built from.
1471 ///
1472 /// Same guard the two blocking drivers carry, moved here with the code it
1473 /// describes. Needles are `concat!`-split so this body does not match
1474 /// itself under `include_str!`.
1475 #[test]
1476 fn the_blocking_io_seam_has_no_async_runtime_symbols() {
1477 let prod = code_only(production_scope(include_str!("blocking_io.rs")));
1478 // Fail closed: if the seam is no longer in the slice, the slice is
1479 // wrong and every assertion below would pass vacuously.
1480 assert!(
1481 prod.contains("fn drive_socket_blocking"),
1482 "production slice no longer covers the seam"
1483 );
1484 let forbidden = [
1485 concat!("tokio", "::net"),
1486 concat!("tokio", "::time"),
1487 concat!("tokio", "::", "spawn"),
1488 concat!("block", "_in_place"),
1489 concat!(".", "await"),
1490 ];
1491 for token in forbidden {
1492 assert_eq!(
1493 prod.matches(token).count(),
1494 0,
1495 "the blocking I/O seam must not reference `{token}`: it has no async \
1496 net/timer/spawn on RTEMS, and every await goes through `block_on_sync`"
1497 );
1498 }
1499 }
1500
1501 /// The no-fd-dup rule, as a source-text guard rather than a comment.
1502 ///
1503 /// `try_clone` compiles everywhere and fails `ENXIO` on RTEMS only, so a
1504 /// reviewer who has not read the module docs has no local signal that it is
1505 /// wrong. This gives them one.
1506 #[test]
1507 fn the_seam_never_duplicates_a_descriptor() {
1508 let prod = code_only(production_scope(include_str!("blocking_io.rs")));
1509 assert!(
1510 prod.contains("fn drive_socket_blocking"),
1511 "production slice no longer covers the seam"
1512 );
1513 for token in [concat!("try", "_clone"), concat!("F_DUP", "FD")] {
1514 assert_eq!(
1515 prod.matches(token).count(),
1516 0,
1517 "`{token}` is back in the blocking I/O seam: on RTEMS 6 every fd \
1518 duplication of a socket fails ENXIO. The read and write roles come \
1519 from one descriptor shared through an `Arc`."
1520 );
1521 }
1522 }
1523
1524 // ── adapter: cancel-safety ──────────────────────────────────────────
1525
1526 /// Losing a `select!` race must consume nothing. A frame reader is used
1527 /// directly as a `select!` arm, so if this adapter dropped bytes on a lost
1528 /// race the failure would be silent and intermittent — a truncated frame
1529 /// long after the fact.
1530 ///
1531 /// Both boundaries of "what was in flight when the race was lost":
1532 ///
1533 /// * **mid-chunk** — part of a chunk has been handed out and the rest is
1534 /// parked in `cur`/`pos`;
1535 /// * **pending** — no chunk has arrived at all, so the poll registered a
1536 /// waker and returned `Pending`.
1537 #[epics_macros_rs::epics_test]
1538 async fn channel_reader_loses_no_bytes_when_a_select_race_is_lost() {
1539 let (tx, rx) = mpsc::channel::<Vec<u8>>(1);
1540 let mut reader = ChannelReader::new(rx);
1541
1542 // Boundary 1: a partially-consumed chunk survives.
1543 tx.send(b"ABCDEFGH".to_vec()).await.expect("chunk queued");
1544 let mut small = [0u8; 3];
1545 let n = reader.read(&mut small).await.expect("first read");
1546 assert_eq!(&small[..n], b"ABC");
1547 for _ in 0..4 {
1548 let mut buf = [0u8; 8];
1549 tokio::select! {
1550 biased;
1551 // This arm always wins, so the read future below is created and
1552 // dropped without ever completing.
1553 _ = std::future::ready(()) => {}
1554 _ = reader.read(&mut buf) => unreachable!("the ready arm wins under `biased`"),
1555 }
1556 }
1557 let mut rest = [0u8; 8];
1558 let n = reader.read(&mut rest).await.expect("read after lost races");
1559 assert_eq!(
1560 &rest[..n],
1561 b"DEFGH",
1562 "a lost race must not eat the parked tail of the chunk"
1563 );
1564
1565 // Boundary 2: a poll that returned Pending consumed nothing either.
1566 for _ in 0..4 {
1567 let mut buf = [0u8; 8];
1568 tokio::select! {
1569 biased;
1570 _ = std::future::ready(()) => {}
1571 _ = reader.read(&mut buf) => unreachable!("the ready arm wins under `biased`"),
1572 }
1573 }
1574 tx.send(b"IJKL".to_vec())
1575 .await
1576 .expect("second chunk queued");
1577 let mut after = [0u8; 8];
1578 let n = reader
1579 .read(&mut after)
1580 .await
1581 .expect("read after pending races");
1582 assert_eq!(
1583 &after[..n],
1584 b"IJKL",
1585 "a chunk must not be taken out of the channel by a poll that returned Pending"
1586 );
1587
1588 // And EOF still reads as EOF once every sender is gone.
1589 drop(tx);
1590 let mut eof = [0u8; 8];
1591 assert_eq!(
1592 reader.read(&mut eof).await.expect("eof read"),
1593 0,
1594 "all senders dropped must surface as a zero-length read"
1595 );
1596 }
1597
1598 /// A zero-length `poll_read` buffer must not eat a chunk.
1599 #[epics_macros_rs::epics_test]
1600 async fn a_zero_length_read_consumes_nothing() {
1601 let (tx, rx) = mpsc::channel::<Vec<u8>>(1);
1602 let mut reader = ChannelReader::new(rx);
1603 tx.send(b"XY".to_vec()).await.expect("chunk queued");
1604 let mut none = [0u8; 0];
1605 assert_eq!(reader.read(&mut none).await.expect("empty read"), 0);
1606 let mut buf = [0u8; 8];
1607 let n = reader.read(&mut buf).await.expect("real read");
1608 assert_eq!(&buf[..n], b"XY", "the chunk survived a zero-length read");
1609 }
1610
1611 // ── adapter: the weak sender ────────────────────────────────────────
1612
1613 /// The adapter must not be what keeps the frame channel open, or a pump
1614 /// would outlive the guard that is supposed to end it.
1615 #[epics_macros_rs::epics_test]
1616 async fn channel_writer_does_not_keep_the_frame_channel_open() {
1617 let (tx, mut rx) = mpsc::channel::<Vec<u8>>(1);
1618 let room = Arc::new(WriteRoom::default());
1619 let mut writer = ChannelWriter {
1620 tx: tx.downgrade(),
1621 room,
1622 };
1623 writer.write_all(b"frame").await.expect("queued");
1624 assert_eq!(rx.recv().await.as_deref(), Some(&b"frame"[..]));
1625
1626 // The guard's sender goes; the adapter is still alive and holding only
1627 // a weak handle.
1628 drop(tx);
1629 assert!(
1630 rx.recv().await.is_none(),
1631 "a live ChannelWriter must not keep the channel open once the only \
1632 strong sender is gone"
1633 );
1634 assert!(
1635 writer.write_all(b"after").await.is_err(),
1636 "writing to a closed channel must be an error, not a silent drop"
1637 );
1638 }
1639
1640 // ── the deadline loop ───────────────────────────────────────────────
1641
1642 fn socket_pair() -> (StdTcpStream, StdTcpStream) {
1643 let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind");
1644 let addr = listener.local_addr().expect("addr");
1645 let client = StdTcpStream::connect(addr).expect("connect");
1646 let (server, _) = listener.accept().expect("accept");
1647 (client, server)
1648 }
1649
1650 /// A peer that never reads must not hold the writer pump past the deadline.
1651 ///
1652 /// unix-only: this asserts the POSIX loopback send-backpressure contract —
1653 /// a bounded send buffer, so a never-reading peer parks the sender.
1654 /// Windows grows the loopback send backlog dynamically and accepted the
1655 /// whole 8 MiB frame in 12 ms (measured, PR #56 CI 2026-07-24), so there
1656 /// is no backpressure for the deadline to trip there. The drivers that
1657 /// need the deadline run on `exec_backend`, which refuses Windows at
1658 /// compile time (`lib.rs`).
1659 #[cfg(unix)]
1660 #[test]
1661 fn the_deadline_loop_ends_a_trickling_peer() {
1662 let (client, server) = socket_pair();
1663 let send_timeout = Duration::from_millis(200);
1664 client
1665 .set_write_timeout(Some(send_timeout / 4))
1666 .expect("sndtimeo");
1667 // Never read from `server`, so the socket buffers fill and stay full.
1668 let big = vec![0u8; 8 * 1024 * 1024];
1669 let started = Instant::now();
1670 let err = write_frame_deadline(&client, &big, send_timeout)
1671 .expect_err("a peer that never reads must trip the deadline");
1672 assert_eq!(err.kind(), io::ErrorKind::TimedOut);
1673 assert!(
1674 started.elapsed() < send_timeout * 20,
1675 "the deadline bounded the whole frame, not each syscall: {:?}",
1676 started.elapsed()
1677 );
1678 drop(server);
1679 }
1680
1681 /// The same bound, on a socket carrying **no `SO_SNDTIMEO` at all**.
1682 ///
1683 /// This is the VxWorks 7 boundary: `setsockopt(SO_SNDTIMEO)` is
1684 /// unimplemented there and returns `ENOPROTOOPT`, so no caller can arm the
1685 /// option however hard it tries
1686 /// (`doc/vxworks-circuit-wedge-on-target-measurement.md` §5). The two cases
1687 /// above cover "the option took"; this one covers "it did not", which is
1688 /// the only case where the deadline had nothing to regain control on.
1689 ///
1690 /// The write runs on its own thread and the assertion is on a bounded
1691 /// `recv`, because the failure being excluded is a park with no end: a
1692 /// direct call would hang the test rather than fail it.
1693 ///
1694 /// Runs on Darwin too, which is the point of it. `MSG_DONTWAIT` does not
1695 /// make an XNU send non-blocking, so while the flag was the only thing
1696 /// keeping the send out of a park this case was the one that failed there;
1697 /// it passes because [`own_blocking_mode`] no longer leaves the guarantee
1698 /// to the flag.
1699 #[cfg(unix)]
1700 #[test]
1701 fn the_deadline_holds_with_no_socket_send_timeout() {
1702 let (client, server) = socket_pair();
1703 // Deliberately no `set_write_timeout`. That is the whole boundary.
1704 let send_timeout = Duration::from_millis(200);
1705 // Never read from `server`, so the socket buffers fill and stay full.
1706 let big = vec![0u8; 8 * 1024 * 1024];
1707 let (tx, rx) = std::sync::mpsc::channel();
1708 let started = Instant::now();
1709 thread::spawn(move || {
1710 let outcome = write_frame_deadline(&client, &big, send_timeout).map_err(|e| e.kind());
1711 let _ = tx.send(outcome);
1712 });
1713 // Two orders of magnitude above the deadline, and still finite: what
1714 // this separates is "bounded" from "never".
1715 let outcome = rx
1716 .recv_timeout(send_timeout * 100)
1717 .expect("the frame's deadline must end the write without a socket timeout to lean on");
1718 assert_eq!(
1719 outcome.expect_err("a peer that never reads must trip the deadline"),
1720 io::ErrorKind::TimedOut
1721 );
1722 assert!(
1723 started.elapsed() < send_timeout * 20,
1724 "the deadline bounded the whole frame: {:?}",
1725 started.elapsed()
1726 );
1727 drop(server);
1728 }
1729
1730 /// And the ordinary case still delivers.
1731 #[test]
1732 fn the_deadline_loop_delivers_a_frame_to_a_reading_peer() {
1733 let (client, mut server) = socket_pair();
1734 let send_timeout = Duration::from_secs(5);
1735 client
1736 .set_write_timeout(Some(send_timeout / 4))
1737 .expect("sndtimeo");
1738 let reader = thread::spawn(move || {
1739 let mut got = vec![0u8; 5];
1740 server.read_exact(&mut got).expect("read");
1741 got
1742 });
1743 write_frame_deadline(&client, b"hello", send_timeout).expect("delivered");
1744 assert_eq!(reader.join().expect("reader"), b"hello");
1745 }
1746
1747 // ── guards ──────────────────────────────────────────────────────────
1748
1749 /// A process-lifetime circuit pool for the pump/guard tests, so a `#[test]`
1750 /// can borrow a worker exactly as a real circuit does. Ample capacity so no
1751 /// test refuses; the tests that care about refusal build their own pool.
1752 static TEST_POOL: std::sync::LazyLock<WorkerPool<2>> = std::sync::LazyLock::new(|| {
1753 WorkerPool::new(
1754 "test",
1755 circuit_roster(ThreadPriority::Low, ThreadPriority::Low),
1756 64,
1757 )
1758 });
1759
1760 /// Borrow one set: the lease and its reader/writer workers. The lease must
1761 /// be held until both pump jobs are joined, or the set would re-idle early.
1762 fn lease_pair() -> (SetLease, Worker, Worker) {
1763 let (lease, [reader, writer]) = TEST_POOL.acquire().expect("acquire a test set");
1764 (lease, reader, writer)
1765 }
1766
1767 /// The reader guard's whole purpose: a pump parked in `read` behind a
1768 /// timeout longer than the test could wait is returned by the guard's drop.
1769 ///
1770 /// unix-only: this asserts the POSIX teardown contract — a local
1771 /// `shutdown(Shutdown::Both)` returns a thread parked in a blocking
1772 /// `read`. Windows does not provide that wake (measured, PR #56 CI
1773 /// 2026-07-24: the parked read outlived the 120 s test bound on x86_64),
1774 /// which is why `exec_backend` refuses Windows at compile time
1775 /// (`lib.rs`) — nothing there can reach the pumps' teardown.
1776 #[cfg(unix)]
1777 #[test]
1778 fn the_reader_guard_returns_a_pump_parked_in_read() {
1779 let (client, server) = socket_pair();
1780 // An effectively-infinite receive timeout: only the shutdown can end
1781 // this pump.
1782 client
1783 .set_read_timeout(Some(Duration::from_secs(64_000)))
1784 .expect("rcvtimeo");
1785 let (lease, reader_worker, _writer_worker) = lease_pair();
1786 let (reader, guard) = spawn_reader_pump(reader_worker, Arc::new(client), "parked", 4096, 1);
1787 // The peer sends nothing, so the pump is parked in `read`.
1788 let started = Instant::now();
1789 drop(reader);
1790 drop(guard);
1791 assert!(
1792 started.elapsed() < Duration::from_secs(10),
1793 "the guard's shutdown must return a parked read, not wait out SO_RCVTIMEO"
1794 );
1795 drop(lease);
1796 drop(server);
1797 }
1798
1799 /// The writer guard must drop its sender *before* joining, or the join
1800 /// deadlocks against a pump parked on `recv()`.
1801 #[test]
1802 fn the_writer_guard_drops_its_sender_before_joining() {
1803 let (client, server) = socket_pair();
1804 let (lease, _reader_worker, writer_worker) = lease_pair();
1805 let (writer, guard) = spawn_writer_pump(
1806 writer_worker,
1807 Arc::new(client),
1808 "sender-order",
1809 Duration::from_secs(5),
1810 1,
1811 );
1812 let started = Instant::now();
1813 drop(writer);
1814 drop(guard);
1815 assert!(
1816 started.elapsed() < Duration::from_secs(10),
1817 "dropping the guard must end a pump parked on recv(), not hang"
1818 );
1819 drop(lease);
1820 drop(server);
1821 }
1822
1823 // ── loss announcements ──────────────────────────────────────────────
1824
1825 /// A subscriber that keeps what was emitted, so a test can assert an
1826 /// announcement actually happened.
1827 ///
1828 /// `errlog_sev_printf` routes through `tracing` on the
1829 /// `epics_base_rs::errlog` target *and* to the console fallback; the
1830 /// `tracing` half is the observable one from in-process, and installing
1831 /// this for the duration of a drop is how these tests read it.
1832 #[derive(Clone, Default)]
1833 struct CapturedLines(Arc<Mutex<Vec<String>>>);
1834
1835 impl tracing::Subscriber for CapturedLines {
1836 fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
1837 true
1838 }
1839 fn event(&self, event: &tracing::Event<'_>) {
1840 struct Fields<'a>(&'a mut String);
1841 impl tracing::field::Visit for Fields<'_> {
1842 fn record_debug(
1843 &mut self,
1844 field: &tracing::field::Field,
1845 value: &dyn std::fmt::Debug,
1846 ) {
1847 use std::fmt::Write;
1848 let _ = write!(self.0, " {}={value:?}", field.name());
1849 }
1850 }
1851 let mut line = event.metadata().target().to_string();
1852 event.record(&mut Fields(&mut line));
1853 self.0.lock().expect("captured lines").push(line);
1854 }
1855 fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
1856 tracing::span::Id::from_u64(1)
1857 }
1858 fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
1859 fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
1860 fn enter(&self, _: &tracing::span::Id) {}
1861 fn exit(&self, _: &tracing::span::Id) {}
1862 }
1863
1864 /// Everything emitted on the calling thread while `f` runs.
1865 fn lines_while(f: impl FnOnce()) -> Vec<String> {
1866 let captured = CapturedLines::default();
1867 tracing::subscriber::with_default(captured.clone(), f);
1868 let lines = captured.0.lock().expect("captured lines");
1869 lines.clone()
1870 }
1871
1872 /// The guards made a lost pump *survivable*; this is what makes it
1873 /// *visible*.
1874 ///
1875 /// `ReaderPumpGuard::drop` used to join and throw the result away, so a
1876 /// pump that unwound left nothing behind: the connection's own error is a
1877 /// bland channel-closed, and the two were unlinkable. Dropping must also not
1878 /// itself panic — a propagating drop would abort the process during another
1879 /// unwind.
1880 #[test]
1881 fn a_panicked_reader_pump_is_reported_and_not_discarded() {
1882 let (client, server) = socket_pair();
1883 let (lease, reader_worker, _writer_worker) = lease_pair();
1884 let lines = lines_while(|| {
1885 let _guard = ReaderPumpGuard {
1886 sock: Arc::new(client),
1887 label: "PVA connection 127.0.0.1:0".to_string(),
1888 job: Some(reader_worker.run(|| panic!("reader blew up"))),
1889 };
1890 });
1891 assert!(
1892 lines
1893 .iter()
1894 .any(|l| l.starts_with("epics_base_rs::errlog")
1895 && l.contains("reader thread panicked")),
1896 "a panicked reader must reach errlog, which prints whatever the log \
1897 configuration is — including an RTEMS console. Captured: {lines:?}"
1898 );
1899 drop(lease);
1900 drop(server);
1901 }
1902
1903 #[test]
1904 fn a_panicked_writer_pump_is_reported_and_not_discarded() {
1905 let (frames, _rx) = mpsc::channel::<Vec<u8>>(1);
1906 let (lease, _reader_worker, writer_worker) = lease_pair();
1907 let lines = lines_while(|| {
1908 let _guard = WriterPumpGuard {
1909 frames: Some(frames),
1910 label: "PVA connection 127.0.0.1:0".to_string(),
1911 job: Some(writer_worker.run(|| panic!("writer blew up"))),
1912 };
1913 });
1914 assert!(
1915 lines
1916 .iter()
1917 .any(|l| l.starts_with("epics_base_rs::errlog")
1918 && l.contains("writer thread panicked")),
1919 "a panicked writer dropped whatever frames were still queued; that \
1920 must not be silent. Captured: {lines:?}"
1921 );
1922 drop(lease);
1923 }
1924
1925 /// The other boundary: an ordinary teardown is not a loss. Every connection
1926 /// that ever closes runs these drops, so announcing there would bury the
1927 /// real losses on a serial console.
1928 #[test]
1929 fn a_pump_that_ends_cleanly_is_not_announced() {
1930 let (client, server) = socket_pair();
1931 let (lease, reader_worker, _writer_worker) = lease_pair();
1932 let lines = lines_while(|| {
1933 let _guard = ReaderPumpGuard {
1934 sock: Arc::new(client),
1935 label: "PVA connection 127.0.0.1:0".to_string(),
1936 job: Some(reader_worker.run(|| {})),
1937 };
1938 });
1939 assert!(
1940 !lines
1941 .iter()
1942 .any(|l| l.contains("was lost") || l.contains("panicked")),
1943 "an ordinary connection teardown must print nothing: {lines:?}"
1944 );
1945 drop(lease);
1946 drop(server);
1947 }
1948
1949 /// Structural closure as source: a pump lost to a panic must be announced.
1950 /// Both guards report through the one announcement function; the old
1951 /// creation-failure loss is gone with the per-connection spawn — a pooled
1952 /// worker is borrowed, never created per connection.
1953 #[test]
1954 fn every_pump_loss_goes_through_the_announcement() {
1955 let prod = production_scope(include_str!("blocking_io.rs"));
1956 assert_eq!(
1957 code_only(prod)
1958 .matches(concat!("let _ = jo", "b.join()"))
1959 .count(),
1960 0,
1961 "a discarded join result is a panicked pump nobody hears about"
1962 );
1963 for owner in [
1964 "impl Drop for ReaderPumpGuard",
1965 "impl Drop for WriterPumpGuard",
1966 ] {
1967 let at = prod
1968 .find(owner)
1969 .unwrap_or_else(|| panic!("`{owner}` is gone from this module"));
1970 let body = &prod[at..(at + 900).min(prod.len())];
1971 assert!(
1972 body.contains(concat!("pump_thread_", "lost(")),
1973 "`{owner}` can lose a pump thread without saying so"
1974 );
1975 }
1976 }
1977
1978 /// Both roles come from one descriptor, and both actually move bytes.
1979 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1980 async fn one_descriptor_serves_both_pumps() {
1981 let (client, mut server) = socket_pair();
1982 let (mut reader, mut writer) = drive_socket_blocking(
1983 &TEST_POOL,
1984 client,
1985 "127.0.0.1:0",
1986 &PumpConfig {
1987 read_timeout: Duration::from_secs(5),
1988 send_timeout: Duration::from_secs(5),
1989 ..PumpConfig::default()
1990 },
1991 )
1992 .expect("pumps started");
1993
1994 let peer = thread::spawn(move || {
1995 let mut got = vec![0u8; 4];
1996 server.read_exact(&mut got).expect("peer read");
1997 server.write_all(b"pong").expect("peer write");
1998 got
1999 });
2000
2001 writer.write_all(b"ping").await.expect("wrote");
2002 let mut got = [0u8; 4];
2003 reader.read_exact(&mut got).await.expect("read back");
2004 assert_eq!(&got, b"pong");
2005 assert_eq!(peer.join().expect("peer"), b"ping");
2006 }
2007
2008 /// The invariant [`DialPool`] exists for: a dial *borrows* a thread, it does
2009 /// not create one.
2010 ///
2011 /// Sequential dials — the shape a reconnect loop makes — must all be served
2012 /// by the same worker, so the count of threads created over the process's
2013 /// life is 1 rather than one per attempt. The per-attempt shape this
2014 /// replaced would report 8 here (and leak 8 × 128 B of RTEMS TLS key).
2015 ///
2016 /// The tight spot is the *first* dial after a reply: the caller is woken by
2017 /// the very worker that must serve it next, so a pool that counted parked
2018 /// workers would see none available and create a second. That is why the
2019 /// assertion is inside the loop and not only after it.
2020 #[epics_macros_rs::epics_test]
2021 async fn sequential_dials_reuse_one_worker() {
2022 static POOL: DialPool = DialPool::new("test-dial", ThreadPriority::Low);
2023 const DIALS: usize = 8;
2024
2025 let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
2026 let addr = listener.local_addr().expect("addr");
2027 // Hold every accepted side open: a peer that closed would let a dial
2028 // fail for a reason this test is not about.
2029 let acceptor = thread::spawn(move || {
2030 (0..DIALS)
2031 .map(|_| listener.accept().expect("accept").0)
2032 .collect::<Vec<_>>()
2033 });
2034
2035 for i in 0..DIALS {
2036 let dialed = POOL.dial(addr).expect("dial submitted");
2037 let stream = dialed
2038 .await
2039 .expect("the worker must reply")
2040 .expect("connect to a live listener");
2041 assert_eq!(
2042 POOL.worker_count(),
2043 1,
2044 "dial {i} created a new thread instead of reusing the idle \
2045 worker: sequential dials must borrow one thread, not one each"
2046 );
2047 drop(stream);
2048 }
2049
2050 assert_eq!(
2051 POOL.worker_count(),
2052 1,
2053 "{DIALS} sequential dials must have created exactly one thread"
2054 );
2055 drop(acceptor.join().expect("acceptor"));
2056 }
2057}