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