diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 5ed9308bd..557b319e1 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -168,9 +168,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.20.3" +version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" [[package]] name = "byteorder" @@ -180,9 +180,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.12.1" +version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" [[package]] name = "bytesize" @@ -510,9 +510,9 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "filetime" -version = "0.2.29" +version = "0.2.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" dependencies = [ "cfg-if", "libc", @@ -1941,9 +1941,9 @@ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "jiff" -version = "0.2.43" +version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26699905cc795a23e3949585cc7ba3ee8ade090872a27e4316304a777297894a" +checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" dependencies = [ "jiff-core", "jiff-static", @@ -1957,18 +1957,18 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.5" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffe6854081f5ac0a3046a9b223729ccd7a20b1e0e8277e44dc0660eedf67dfe2" +checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" dependencies = [ "log", ] [[package]] name = "jiff-static" -version = "0.2.43" +version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b4ff49b2887190c760b86207b55cdcaabbdecaf7a0660d68aa2ed6f652abf0a" +checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" dependencies = [ "jiff-core", "proc-macro2", @@ -1978,9 +1978,9 @@ dependencies = [ [[package]] name = "jiff-tzdb" -version = "0.1.9" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" +checksum = "0980fca2cc272465bd60e82397607ba9f33add9e48defd77923301bbd03808f2" [[package]] name = "jiff-tzdb-platform" @@ -2153,9 +2153,9 @@ checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" [[package]] name = "mio" -version = "1.2.4" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi 0.11.1+wasi-snapshot-preview1", @@ -2376,7 +2376,7 @@ dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand 0.10.3", + "rand 0.10.4", "rand_pcg", "ring", "rustc-hash", @@ -2436,9 +2436,9 @@ dependencies = [ [[package]] name = "rand" -version = "0.10.3" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" dependencies = [ "chacha20", "getrandom 0.4.3", @@ -2500,9 +2500,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" dependencies = [ "aho-corasick", "memchr", @@ -2512,9 +2512,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.18" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" dependencies = [ "aho-corasick", "memchr", @@ -2523,9 +2523,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.11" +version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" [[package]] name = "reqwest" @@ -3809,9 +3809,9 @@ dependencies = [ [[package]] name = "zeroize" -version = "1.9.1" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" [[package]] name = "zerotrie" diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index ac855d65f..530a619e4 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -40,7 +40,14 @@ serde.workspace = true serde_json.workspace = true thiserror.workspace = true tracing.workspace = true -tokio = { workspace = true, optional = true, features = ["macros", "rt-multi-thread"] } +# `io-util` is what `net` needs on top of the workspace's own list +# (`net`, `sync`, `time`...): `AsyncReadExt`/`AsyncWriteExt`, i.e. reading +# a TCP stream into a buffer at all. +tokio = { workspace = true, optional = true, features = [ + "macros", + "rt-multi-thread", + "io-util", +] } tracing-subscriber = { workspace = true, optional = true , features = ["env-filter", "fmt"]} tracing-appender = { workspace = true, optional = true } gix = { version = "0.87.1", optional = true, features = ["blocking-http-transport-reqwest-rust-tls", "blocking-network-client", "worktree-mutation"] } @@ -62,6 +69,9 @@ rlimit = { version = "0.11.0", optional = true } [dev-dependencies] tempfile = "3.27" +# Virtual time makes the writer's per-frame deadlines deterministic in tests. +tokio = { workspace = true, features = ["test-util"] } + # `workspace = true` can't be combined with extra lints in the same table, # so the workspace list is repeated here with `missing_docs` added: this is # the crate meant to be reused by other projects, so its public API must be diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index d7d151506..87ea4265f 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -8,13 +8,12 @@ pub mod hello_world; #[cfg(feature = "git")] pub mod git; -/// NTP server -#[cfg(feature = "ntp")] -pub mod ntp; - /// Basic domain types: identifiers, values, measurements, protections, /// packets and boards. pub mod model; +/// NTP server +#[cfg(feature = "ntp")] +pub mod ntp; /// Parses an ADJ (Architecture Description JSON) directory into /// [`model::PodData`], plus backend-session metadata not modeled as @@ -26,13 +25,20 @@ pub mod adj; /// [`protocol::tcp`], [`protocol::udp`]. pub mod protocol; +/// Owns the real tokio sockets and reports what arrives on them, calling +/// into [`protocol`] to decode. See [`net::tcp`], [`net::udp`]. +#[cfg(feature = "net")] +pub mod net; + // Utils module pub(crate) mod utils; + /// Everything a recording needs on disk: writing CSV, text and JSON /// files without knowing what is in them ([`logger::CsvFile`]), moving /// those files around ([`logger::files`], feature `files`) and the /// snapshot of the machine that produced them ([`logger::host`], /// feature `host`). The policy — which files a recording has, what goes /// in each row — belongs to whoever calls this. + #[cfg(feature = "logger")] pub mod logger; diff --git a/backend/crates/core/src/net.rs b/backend/crates/core/src/net.rs new file mode 100644 index 000000000..d49fdd8d1 --- /dev/null +++ b/backend/crates/core/src/net.rs @@ -0,0 +1,46 @@ +//! Real sockets, on top of tokio (feature `net`). +//! +//! Two submodules do the actual I/O: [`crate::net::tcp`], a client that +//! keeps one task per board and recovers frames out of a byte stream, +//! and [`crate::net::udp`], a single shared receive-only socket. This module opens nothing. It defines only what +//! both of them need to agree on: [`crate::net::Event`] (what happened on +//! a link, carried by a [`crate::net::Notification`]) and +//! [`crate::net::Reporter`] (the two sinks they report through — one for +//! notifications, one for errors). +//! +//! Everything that reaches a [`crate::net::Reporter`] has already been +//! decoded by [`crate::protocol`], which this module layers on top of: +//! `protocol` turns bytes into packets and never touches a socket, `net` +//! owns the socket and calls into it. A sniffer or a simulator can use +//! `protocol` on its own, against a capture, without any of this. +//! +//! # Identity +//! +//! Everything that travels down the notification channel carries its +//! board: [`crate::net::Notification`] holds a +//! [`crate::model::BoardId`] next to the timestamp, whatever the event +//! is. No consumer ever has to go and look up whose packet it just got. +//! +//! It is never a second source of truth, though — it is resolved from +//! what the ADJ already says, once, here. A TCP task was spawned for one +//! board and knows it without asking; [`crate::net::udp`] resolves it +//! from the decoded packet's id through [`crate::protocol::Index`] (every +//! [`crate::model::PacketDef`] carries its `board`), which is one +//! `HashMap` lookup per datagram instead of one per consumer downstream. +//! +//! A board id is all the identity there is: one connection per board, and +//! one shared socket for UDP, so nothing needs telling apart beyond it. +//! +//! Addresses are for the operator, not for the domain types: they show +//! up interpolated in each submodule's error messages (`tcp::TcpError`, +//! `udp::Error`), which is where somebody actually reads them. + +mod error; +mod report; + +pub mod tcp; +pub mod udp; + +pub use error::Error; +use report::Closed; +pub use report::{ErrorReport, Event, Notification, Reporter, Sinks}; diff --git a/backend/crates/core/src/net/README.md b/backend/crates/core/src/net/README.md new file mode 100644 index 000000000..8d696f034 --- /dev/null +++ b/backend/crates/core/src/net/README.md @@ -0,0 +1,61 @@ +# `net` — socket transport (feature `net`) + +`net` owns Tokio sockets and uses the synchronous, socket-free `protocol` codecs. +The parent module opens no sockets itself: it exposes transports and defines +their shared reporting types and errors. + +Application policy, ADJ loading, logging to disk and frontend integration belong +outside this module. Transport errors and received protections never trigger a +fault automatically; the application decides how to respond. + +## Transports + +| Module | Status / purpose | +| --- | --- | +| [TCP](tcp/README.md) | A client with one independently reconnecting connection per configured board. Receives messages/protections and writes orders, keep-alive and faults. | +| UDP | Telemetry reception is **not implemented yet**; `udp::spawn` is a placeholder that panics. | + +TCP configuration, API usage, guarantees, limitations and manual probes are +documented in [tcp/README.md](tcp/README.md). + +## Shared API + +| Type / entry point | Purpose | +| --- | --- | +| `Reporter::channels(notifications, errors)` | Create bounded reporting channels and their receiving ends (`Sinks`). Both capacities must be nonzero. | +| `Reporter` | Cloneable reporting handle supplied to transports; publication methods are internal. | +| `Sinks` | Application-owned receivers for notifications and errors. | +| `Notification`, `Event` | Identify a board, timestamp and lifecycle event or decoded packet. | +| `ErrorReport`, `net::Error` | Timestamp transport failures and preserve their transport-specific identity. | + +## Reporting + +`Notification { board, at, event }` always carries the board's identity alongside +its timestamp. `Event` is `Connected`, `Disconnected` or `Received(Packet)`; +connection lifecycle events are TCP-only. `ErrorReport { at, error }` contains +the failure's own identity through the corresponding `net::Error` variant. +The transport's `Reporter` stamps events when publishing them. Validated TCP +order failures also arrive here as `net::Error::Tcp(tcp::TcpError::Send { board, order, source })`; +normal send success is returned to its caller after complete socket write. +Routing/encoding failures are returned only. See the TCP send contract for +writer waits, cancellation and reporting backpressure. + +Consume **both** channels concurrently with application operations. Both apply +backpressure rather than dropping on congestion, so leaving either consumer +idle can block publication. There is no ordering guarantee between the two +channels or across independent boards. Cancellation can discard a publication +waiting for capacity; already queued reports remain available to drain. + +Closing a consumer is also a transport cancellation signal. The exact shutdown +behavior is transport-specific; see [TCP cancellation](tcp/README.md#reporting-framing-and-cancellation). + +## Tests + +From `backend/`: + +```sh +cargo test -p software-core --features net +``` + +See [TCP tests and manual probes](tcp/README.md#tests) for hardware requirements, +simulator setup and safety warnings. diff --git a/backend/crates/core/src/net/error.rs b/backend/crates/core/src/net/error.rs new file mode 100644 index 000000000..49fdd25b9 --- /dev/null +++ b/backend/crates/core/src/net/error.rs @@ -0,0 +1,28 @@ +//! The one error type an [`super::ErrorReport`] can carry. + +use super::{tcp, udp}; + +/// Anything that went wrong in `net`. +/// +/// Aggregation only: this enum adds no identity and no message of its +/// own. Each submodule owns its own error type and puts the identity of +/// whatever failed — the board, or the peer address — +/// *inside* the variant, not just in its text, so that the identity +/// survives being sent down a channel. The Go backend lost it exactly +/// there: the log line before the send had the board, the error value +/// that travelled did not. +/// +/// Both variants are `#[error(transparent)]`, so `to_string()` on this +/// enum is the submodule's own message, identity interpolated and all — +/// which is what gets shown to the operator — and `source()` still walks +/// down to the original `io::Error` or +/// [`crate::protocol::DecodeError`]. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// On a board's TCP connection; wraps [`tcp::TcpError`]. + #[error(transparent)] + Tcp(#[from] tcp::TcpError), + /// On the shared UDP socket. + #[error(transparent)] + Udp(#[from] udp::Error), +} diff --git a/backend/crates/core/src/net/report.rs b/backend/crates/core/src/net/report.rs new file mode 100644 index 000000000..6a73cd126 --- /dev/null +++ b/backend/crates/core/src/net/report.rs @@ -0,0 +1,380 @@ +//! What [`super::tcp`]/[`super::udp`] report, and the sinks they report +//! through. +//! +//! Two separate channels, both bounded. Notifications +//! ([`Notification`]) carry everything that happened on a link, errors +//! ([`ErrorReport`]) everything that went wrong. They are separate +//! so an error does not have to wait behind a queue of received packets. +//! +//! Both channels apply backpressure rather than dropping on congestion. +//! Cancellation can still discard a publication waiting for capacity. + +use super::Error; +use crate::model::{BoardId, Packet}; +use std::time::SystemTime; +use tokio::sync::mpsc; + +/// Something that happened on a link: which board it concerns, when, +/// and what. +/// +/// Both `board` and `at` live in this envelope rather than inside the +/// variants of [`Event`], so that **everything** that travels down the +/// channel carries them — there is no event whose board the consumer has +/// to go and look up, and none that can be built without a timestamp. +/// The transport's reporter stamps `at` when publishing the event. +#[derive(Debug)] +pub struct Notification { + /// The board this concerns. + /// + /// Always known by the time anything is reported: a TCP task was + /// spawned for one board and knows it without asking, and [`super::udp`] + /// resolves it from the decoded packet's id through + /// [`crate::protocol::Index`] — `index.packet(id)` gives a + /// [`crate::model::PacketDef`], which carries its `board` — so that a + /// notification looks the same whichever transport brought it. + pub board: BoardId, + /// The instant the bytes came off the socket. + /// + /// Stamped when the event is reported, never by whoever writes it to + /// disk later: a queue adds delay under load, so a date taken at + /// write time would be wrong by exactly that delay, at exactly the + /// moment the data matters most. The frames that carry a board clock + /// of their own ([`crate::model::ShortTimestamp`], on protections and + /// messages) only carry a time of day, with no date, so this is also + /// the only full date a record can have. + pub at: SystemTime, + /// What happened. + pub event: Event, +} + +/// Something that went wrong, and when. +/// +/// Carries no identity of its own: whose failure it was travels inside +/// the [`Error`]'s own variant, which is the only place that always has +/// it. A datagram that fails to decode, for instance, resolves to no +/// board at all — its id is not in the ADJ, so there is no +/// [`crate::model::PacketDef`] to ask — and all that can be said about +/// it is the address it came from, which is exactly what +/// [`super::udp::Error::Decode`] holds. +#[derive(Debug)] +pub struct ErrorReport { + /// The instant the failure was reported, on the same clock as + /// [`Notification::at`]. + pub at: SystemTime, + /// What went wrong, identity included. + pub error: Error, +} + +/// What happened on a link. +#[derive(Debug)] +pub enum Event { + /// The board's connection came up, and it can now be talked to. + /// Which board is in the [`Notification`] around this, which is all + /// the identity there is: one connection per board. + /// + /// TCP only: there is nothing to connect in UDP, whose socket is + /// bound once and belongs to no single board. + Connected, + /// The board's connection went down, whatever the reason. If the + /// cause was worth reporting, it already went out as an + /// [`ErrorReport`] — but on the other channel, so nothing orders the + /// two against each other. + /// + /// TCP only, same as [`Event::Connected`]. + Disconnected, + /// A packet arrived and was decoded. Whose it is, is in the + /// [`Notification`] around it. + /// + /// [`Packet`] is the whole umbrella, so this one variant covers data, + /// protections and messages alike, with no second enum repeating that + /// split. Its [`Packet::Order`] variant is never produced while + /// receiving. Normal TCP send success is returned directly to its caller; + /// failed transport attempts use ErrorReport, not Received(Order). + Received(Packet), +} + +/// The receiving ends of a [`Reporter`]'s two channels, handed to the application. +#[derive(Debug)] +pub struct Sinks { + /// Notifications in publication order; concurrent boards may interleave. + pub notifications: mpsc::Receiver, + /// Everything that went wrong. + pub errors: mpsc::Receiver, +} + +/// The sinks [`super::tcp`] and [`super::udp`] report through. +/// +/// Cloneable, and meant to be cloned: every task gets its own copy — one +/// per TCP connection, one for the UDP loop — and they all feed the same +/// two channels. The application creates these channels through +/// [`Self::channels`] and passes the reporter to transports; only transports +/// can publish into them. +#[derive(Debug, Clone)] +pub struct Reporter { + notifications: mpsc::Sender, + errors: mpsc::Sender, +} + +/// The consumer is gone, so there is nobody left to report to. +/// +/// The only failure either sink has, and a signal to stop rather than +/// something to retry. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[error("the receiving end is gone")] +pub(super) struct Closed; + +impl Reporter { + /// Waits for either consumer to close, allowing a supervisor to stop even + /// while a connection is idle or waiting for its next retry. + pub(super) async fn closed(&self) { + tokio::select! { + () = self.notifications.closed() => {}, + () = self.errors.closed() => {}, + } + } + + /// Builds both channels with the given capacities, and returns the + /// sending half to hand to the submodules plus the receiving halves + /// to hand to the consumer. + /// + /// Both are bounded: publication waits for capacity, applying backpressure + /// to transports. Consume both channels concurrently. Closing either consumer + /// cancels TCP supervisors, including during idle connections or retries. + /// Cancellation can discard buffered input and unpublished events; already + /// queued notifications remain available to drain. + /// + /// # Panics + /// + /// Panics if either capacity is zero, as does [`mpsc::channel`]. + pub fn channels(notifications: usize, errors: usize) -> (Self, Sinks) { + let (notification_tx, notification_rx) = mpsc::channel(notifications); + let (error_tx, error_rx) = mpsc::channel(errors); + + ( + Self { + notifications: notification_tx, + errors: error_tx, + }, + Sinks { + notifications: notification_rx, + errors: error_rx, + }, + ) + } + + /// Stamps the instant and queues `event`. + /// + /// **Waits** if the channel is full, rather than dropping on congestion. + /// The backpressure reaches the read loop, which stops reading until + /// capacity is available. Success means queued, not yet consumed. + /// + /// Cancelling this future while it waits discards the not-yet-queued + /// notification. Immediate TCP session teardown can do this even for an + /// already decoded packet. Notifications already queued are unaffected + /// by cancelling the producer; consumer closure returns [`Closed`]. + /// + /// The instant is taken before the wait, not after, so a full queue + /// delays the notification without distorting its timestamp. + pub(super) async fn notify(&self, board: BoardId, event: Event) -> Result<(), Closed> { + let notification = Notification { + board, + at: SystemTime::now(), + event, + }; + + self.notifications + .send(notification) + .await + .map_err(|_| Closed) + } + + /// Stamps the instant and queues an error, on the error channel. + /// + /// Takes anything that converts into [`Error`], so a submodule + /// reports its own error type directly: + /// `reporter.report(tcp::TcpError::Connect { .. }).await`. + /// + /// Reporting does not decide application policy. The transport handles + /// socket teardown/reconnection independently; a rejected send may leave + /// its session usable. This channel informs the application, which can + /// expose failures to the operator through the frontend. + pub(super) async fn report(&self, error: impl Into) -> Result<(), Closed> { + let report = ErrorReport { + at: SystemTime::now(), + error: error.into(), + }; + + self.errors.send(report).await.map_err(|_| Closed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{AdjId, DataPacket}; + use crate::net::udp; + use std::net::{IpAddr, SocketAddr}; + use std::time::Duration; + + fn a_packet() -> Event { + Event::Received(Packet::Data(DataPacket::new(AdjId(1000), vec![]))) + } + + fn an_error() -> udp::Error { + udp::Error::Recv { + source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), + } + } + + #[tokio::test] + async fn a_notification_arrives_stamped() { + let (reporter, mut sinks) = Reporter::channels(4, 4); + + let before = SystemTime::now(); + let Ok(()) = reporter.notify(BoardId(3), a_packet()).await else { + unreachable!("the receiver is still alive"); + }; + let after = SystemTime::now(); + + let Some(notification) = sinks.notifications.recv().await else { + unreachable!("exactly one notification was sent"); + }; + assert!(notification.at >= before && notification.at <= after); + assert_eq!( + notification.board, + BoardId(3), + "the board travels with every notification, received packets included" + ); + } + + #[tokio::test] + async fn a_connection_event_names_its_board() { + let (reporter, mut sinks) = Reporter::channels(4, 4); + + // The one identity that cannot be derived from a packet: there is + // no packet here at all. + let Ok(()) = reporter.notify(BoardId(3), Event::Disconnected).await else { + unreachable!("the receiver is still alive"); + }; + + let Some(notification) = sinks.notifications.recv().await else { + unreachable!("exactly one notification was sent"); + }; + // The board is the whole identity: one connection per board. + assert_eq!(notification.board, BoardId(3)); + let Event::Disconnected = notification.event else { + unreachable!("a disconnection should arrive as Event::Disconnected"); + }; + } + + #[tokio::test] + async fn a_full_channel_makes_the_reporter_wait_instead_of_dropping() { + let (reporter, mut sinks) = Reporter::channels(1, 1); + + // Fill the single slot, then start a second report that cannot + // fit yet. + let Ok(()) = reporter.notify(BoardId(3), a_packet()).await else { + unreachable!("the first one fits"); + }; + let blocked = tokio::spawn({ + let reporter = reporter.clone(); + async move { reporter.notify(BoardId(3), a_packet()).await } + }); + + // It is still waiting: nothing was dropped, and nothing got + // through either. + tokio::time::sleep(Duration::from_millis(50)).await; + assert!( + !blocked.is_finished(), + "the second report should be waiting" + ); + + // Draining one slot lets it through, so both are delivered. + let Some(_first) = sinks.notifications.recv().await else { + unreachable!("the first notification was sent"); + }; + let Ok(Ok(())) = blocked.await else { + unreachable!("once a slot frees up, the second one goes through"); + }; + let Some(_second) = sinks.notifications.recv().await else { + unreachable!("the second notification went through"); + }; + } + + #[tokio::test] + async fn waiting_on_a_full_channel_does_not_delay_the_timestamp() { + let (reporter, mut sinks) = Reporter::channels(1, 1); + + let Ok(()) = reporter.notify(BoardId(3), a_packet()).await else { + unreachable!("the first one fits"); + }; + let blocked = tokio::spawn({ + let reporter = reporter.clone(); + async move { reporter.notify(BoardId(3), a_packet()).await } + }); + + // Let the second report sit in the queue for a while before + // anything drains it. + tokio::time::sleep(Duration::from_millis(50)).await; + let after_the_wait = SystemTime::now(); + + let Some(_first) = sinks.notifications.recv().await else { + unreachable!("the first notification was sent"); + }; + let Ok(Ok(())) = blocked.await else { + unreachable!("the second one goes through once there is room"); + }; + let Some(second) = sinks.notifications.recv().await else { + unreachable!("the second notification went through"); + }; + + // Stamped when it was reported, not when it finally fit. + assert!( + second.at <= after_the_wait, + "the timestamp should predate the end of the wait" + ); + } + + #[tokio::test] + async fn an_error_arrives_on_its_own_channel() { + let (reporter, mut sinks) = Reporter::channels(4, 4); + + let Ok(()) = reporter.report(an_error()).await else { + unreachable!("the receiver is still alive"); + }; + + let Some(report) = sinks.errors.recv().await else { + unreachable!("exactly one error was reported"); + }; + let Error::Udp(udp::Error::Recv { .. }) = report.error else { + unreachable!("a udp error should arrive as Error::Udp"); + }; + // Nothing reached the notification channel. + assert!(sinks.notifications.try_recv().is_err()); + } + + #[test] + fn a_udp_decode_error_keeps_the_address_it_cannot_resolve_to_a_board() { + let addr = SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400); + let error = udp::Error::Decode { + from: addr, + source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), + }; + + // The whole reason an error report carries no board: this one has + // an address, and no board to attribute it to. + let Error::Udp(udp::Error::Decode { from, .. }) = Error::from(error) else { + unreachable!("a decode error should convert into Error::Udp"); + }; + assert_eq!(from, addr); + } + + #[tokio::test] + async fn reporting_once_the_consumer_is_gone_says_so() { + let (reporter, sinks) = Reporter::channels(4, 4); + drop(sinks); + + assert_eq!(reporter.notify(BoardId(3), a_packet()).await, Err(Closed)); + assert_eq!(reporter.report(an_error()).await, Err(Closed)); + } +} diff --git a/backend/crates/core/src/net/tcp.rs b/backend/crates/core/src/net/tcp.rs new file mode 100644 index 000000000..d32aa255b --- /dev/null +++ b/backend/crates/core/src/net/tcp.rs @@ -0,0 +1,384 @@ +//! The TCP client: one connection per board, one task each. +//! +//! [`spawn`] starts one independent supervisor per board without a background order queue. +//! BoardClients route and encode orders, then write only to the current session. +//! Offline sends fail; connected callers wait for the writer within write_timeout. +//! Success confirms write_all, not firmware ACK. +//! Orders, heartbeats and faults share the same complete-frame writer. +//! Explicit task shutdown/joining remains pending. This module +//! exposes [`TcpError`], which [`super::Error::Tcp`] wraps, and defines the transport contract. +//! See [`super`] and `net/tcp/README.md`. +//! +//! # What this module is +//! +//! The backend is the **client**: it connects out to each board's +//! `TCP_SERVER` port, and never listens. One connection per board, each +//! one its own task with its own framing buffer and its own reconnection +//! state. That connection carries protections and messages inbound, and +//! orders and the keep-alive outbound. +//! +//! # Entry point +//! +//! [`spawn`], taking [`TcpConfig`], an `Arc` and a +//! [`super::Reporter`], and returning [`BoardClients`] — the API is written +//! out below, with its reasoning on the items themselves. One call opens +//! **every** configured connection: one task per distinct board ID, so the +//! per-board bookkeeping stays here. The application submits orders through +//! [`BoardClients::send`], which resolves their destination from the index. +//! +//! # Contract +//! +//! - **Framing is this module's job.** TCP is a byte stream: a frame can +//! arrive split across reads, and two frames can arrive glued together +//! in one read — both are normal, and the second is the common case. +//! So: accumulate into a per-connection buffer, run +//! [`crate::protocol::tcp::decode_next`] against a `&mut Cursor` over +//! it, and on success advance the buffer by `cursor.position()`. Never +//! consume from the buffer unless a frame parsed in full, or the stream +//! is permanently misaligned. All decode errors are deferred while at most +//! 374 bytes remain, including errors that do not mean incomplete input. +//! The largest supported inbound frame is 374 bytes (`2 + 4 + 48 + 320`), +//! so an undecodable suffix beyond that limit ends the session and triggers +//! reconnection. Complete frames are extracted before applying this limit. +//! - **One exclusive writer per connection.** Normal orders write in their +//! callers, waiting for the same mutex as heartbeats and faults. One deadline +//! covers waiting and writing. No frames interleave, and there are no per-kind +//! priorities. Cancelling before writing leaves the session usable; cancelling +//! an unfinished write closes it. +//! - **Be ready to be told to propagate the fault.** The application +//! decides when; this module is what can actually write, so it +//! exposes [`BoardClients::broadcast_fault`], which puts **the order with id +//! 0** — the fault, same as the Go backend's `SendFault` — into every +//! board's current writer concurrently, bounded by `write_timeout` for the +//! whole attempt. It reports which writes could not be confirmed instead of +//! collapsing them into one opaque error, since a fault that only +//! half-landed is exactly what the operator has to know. The same path +//! can be used by application policies for received protections or errors. +//! No automatic trigger or once-per-incident guard is implemented here. +//! - Reconnection with exponential backoff and unlimited retries, the +//! OS-level keep-alive disabled (there is an application-level one), +//! `linger = 0` for abortive close when a socket is dropped. This may discard +//! unsent bytes; socket write completion does not guarantee firmware receipt. +//! - Report through [`super::Reporter`] only: [`super::Event::Connected`] +//! and [`super::Event::Disconnected`] per connection, +//! [`super::Event::Received`] per frame, and [`TcpError`] on the error +//! channel. Never stamp a timestamp by hand — the reporter +//! does it. Never touch disk, WebSocket or aggregation. +//! - **A terminal decode failure is fatal**: see [`TcpError::is_fatal`]. An +//! unsuccessful attempt on at most 374 pending bytes is deferred; +//! the framing rule waits for more bytes without proving the suffix valid. Log a +//! terminal failure and report it on the error channel, which is all this +//! module does about it. Sending the pod to fault is not `net`'s call to make: +//! whoever consumes the error channel reads [`TcpError::is_fatal`] and +//! decides, which also keeps the "fault once" guard in one place +//! instead of one per transport. The stream cannot be resynchronised +//! mid-frame, though, so this module does close the connection and let +//! the reconnection loop reopen it — reconnecting will not fix a +//! mismatched ADJ, so expect the same frame to fail again. +//! - Everything else is decided here, locally: a failed connect or write +//! is what the backoff is for, and only the report goes up. + +use super::Reporter; +use crate::{ + model::{BoardId, Port}, + protocol::Index, +}; +use std::{collections::HashMap, net::SocketAddr, sync::Arc, time::Duration}; + +mod board_clients; +mod board_handle; +mod connection; +mod keep_alive; +mod endpoint; +mod error; +mod framing; +mod reader; +mod session; +mod supervisor; +mod writer; + +pub use board_clients::BoardClients; +pub use board_handle::BoardHandle; +pub use error::{SendError, TcpError, Unreachable}; + +/// One board to keep a connection to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BoardLink { + /// Whose connection this is. Every report about it names this board, + /// which is the whole identity of a link. + pub board: BoardId, + /// Where to connect: the board's `ip` + its `ports["TCP_SERVER"]`. + pub addr: SocketAddr, + /// The fixed local port to bind the client side to (`TCP_CLIENT + i` + /// in the Go backend). Socket setup uses abortive close (`linger = 0`) + /// when tearing down a connection; subsequent bind failures are reported + /// and retried through the normal connection path. + /// Zero requests an OS-assigned port, useful for isolated local tests. + pub local_port: Port, +} + +/// How long to wait between reconnection attempts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Backoff { + // The bounded initial interval restored after a successful connection. + initial: u64, + // The next wait in milliseconds, always bounded by max. + next: u64, + // The ceiling the doubling stops at. Retries are unlimited: a board + // that is not up yet is the normal state before a test, not an + // error to give up on. + max: u64, +} + +impl Backoff { + /// Creates an exponential backoff with millisecond intervals. + /// + /// The first interval is `initial.min(max)`. A zero initial interval or + /// maximum produces zero intervals throughout, with no deliberate retry delay. + pub fn new(initial: u64, max: u64) -> Self { + Self { + initial: initial.min(max), + next: initial.min(max), + max, + } + } + + /// Returns the next interval, doubling subsequent intervals up to the maximum. + /// + /// Saturating arithmetic allows unlimited attempts without overflow. Once + /// reached, the maximum is returned on every subsequent call until [`Self::reset`]. + fn get_interval(&mut self) -> Duration { + let interval = Duration::from_millis(self.next); + self.next = self.next.saturating_mul(2).min(self.max); + interval + } + + /// Restores the first interval without changing the configured maximum. + /// + /// Call after a successful connection so a later disconnection starts a new + /// retry sequence. Repeated resets are harmless and do not consume an interval. + fn reset(&mut self) { + self.next = self.initial; + } +} + +/// How to run the TCP client. +/// +/// Everything here is resolved by the application before `net` is reached: this +/// module reads no config file, and it does not read the ADJ to find its +/// peers either. That is also what lets a test point it at a fake peer. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TcpConfig { + /// One entry per board to connect to, already filtered by what the + /// config file lists: a board the ADJ declares but the config does + /// not name gets no client at all. + pub boards: Vec, + /// Bound on each connection attempt. + pub connect_timeout: Duration, + /// What to wait between attempts. + pub backoff: Backoff, + /// Period of the application-level keep-alive: an empty order with ID 1. + /// Zero disables it. The first send waits one period; subsequent periods + /// start when the previous keep-alive finishes. Ordinary orders do not reset + /// the timer, and overdue sends never accumulate into a catch-up burst. + /// Each spawned supervisor supplies this period to its session writer. + /// OS-level keep-alive remains disabled in favor of this application packet. + pub keep_alive: Duration, + /// Bound on waiting for the writer and writing a complete frame. + /// Also bounds each entire fault attempt, including its wait for the writer. + /// Expiry before writing leaves the session usable; expiry during writing closes it. + pub write_timeout: Duration, +} + +/// Opens a connection to every board in `config.boards`. +/// +/// One call, one task per board: the per-connection bookkeeping stays in +/// this module, and the application submits orders through the [`BoardClients`] +/// that come back, letting the index select their destination. +/// +/// `index` is the only part of the ADJ this module needs: it decodes +/// inbound frames and encodes outbound orders against it. The application owns +/// it and hands out clones; it is read-only here, and a reload of the ADJ +/// is a new [`Index`] with new tasks, never a mutation of this one. +/// +/// Connecting is *not* done before spawning, unlike [`super::udp`]: a +/// board that is not up yet is normal, so a failed attempt is a report +/// and a retry, never a startup failure. +/// +/// Each board gets an active-session endpoint and a supervisor with independent +/// backoff state, sharing the immutable index and Reporter channels. Repeated +/// board IDs keep their first link and log a warning; no duplicate task is started. +/// An empty board list returns empty handles without opening a connection. +/// +/// Tasks are detached for now: this API does not return join handles or implement +/// explicit shutdown. Closing either Reporter consumer stops the supervisors; +/// consume both channels concurrently while running. Dropping BoardClients alone +/// does not stop supervisors; close a Reporter consumer to cancel them. +/// No application handshake or hash exchange is performed. Fault broadcast is +/// explicit through [`BoardClients::broadcast_fault`], never triggered automatically. +/// +/// # Panics +/// +/// Starting a nonempty configuration outside a Tokio runtime panics, as does +/// [`tokio::spawn`]. +pub fn spawn(config: TcpConfig, index: Arc, reporter: Reporter) -> BoardClients { + tracing::debug!( + configured_boards = config.boards.len(), + connect_timeout = ?config.connect_timeout, + write_timeout = ?config.write_timeout, + keep_alive = ?config.keep_alive, + backoff = ?config.backoff, + "Starting TCP clients" + ); + let mut boards = HashMap::with_capacity(config.boards.len()); + let config = Arc::new(config); + for &link in &config.boards { + if boards.contains_key(&link.board) { + tracing::warn!(board = ?link.board, "ignoring duplicate TCP board link"); + continue; + } + let endpoint = endpoint::Endpoint::default(); + boards.insert( + link.board, + BoardHandle { + board: link.board, + index: Arc::clone(&index), + endpoint: endpoint.clone(), + write_timeout: config.write_timeout, + reporter: reporter.clone(), + }, + ); + + let index = Arc::clone(&index); + let config = Arc::clone(&config); + let reporter = reporter.clone(); + // Deliberately detached: explicit task ownership/joining is a later step. + let _task = tokio::spawn(async move { + let _ = supervisor::supervise(&link, &config, &index, &reporter, &endpoint).await; + }); + } + BoardClients::new(boards, index, config.write_timeout) +} + +#[cfg(test)] +mod manual_tests; + +#[cfg(test)] +mod test_support; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn backoff_doubles_in_milliseconds_and_stays_at_the_cap() { + // A non-power-of-two cap must be reached without rounding or wrapping. + let mut backoff = Backoff::new(100, 700); + for expected in [100, 200, 400, 700] { + assert_eq!(backoff.get_interval(), Duration::from_millis(expected)); + } + // Staying capped must not leave an ever-growing exponent or counter. + for _ in 0..10_000 { + assert_eq!(backoff.get_interval(), Duration::from_millis(700)); + } + } + + #[test] + fn backoff_bounds_the_first_interval() { + // Equal and excessive initial values both start at the configured cap. + for initial in [700, 701, u64::MAX] { + let mut backoff = Backoff::new(initial, 700); + for _ in 0..100 { + assert_eq!(backoff.get_interval(), Duration::from_millis(700)); + } + } + } + + #[test] + fn backoff_preserves_zero_intervals_without_overflow() { + // Preserve zero-valued configuration, including after the old exponent + // calculation would overflow even with an initial interval of zero. + for (initial, max) in [(0, 0), (0, 700), (0, u64::MAX), (100, 0)] { + let mut backoff = Backoff::new(initial, max); + for _ in 0..1_000 { + assert_eq!(backoff.get_interval(), Duration::ZERO); + } + } + } + + #[test] + fn backoff_saturates_before_applying_a_large_cap() { + // Doubling the initial interval exceeds u64::MAX, but a lower cap must + // still win over saturation. Also cover the largest representable cap. + let initial = u64::MAX / 2 + 1; + for max in [u64::MAX - 1, u64::MAX] { + let mut backoff = Backoff::new(initial, max); + assert_eq!(backoff.get_interval(), Duration::from_millis(initial)); + for _ in 0..100 { + assert_eq!(backoff.get_interval(), Duration::from_millis(max)); + } + } + } + + #[test] + fn backoff_reaches_the_largest_cap_from_one() { + // Exercise every representable power of two before saturation; merely + // capping the attempt counter would incorrectly stop at 2^63. + let mut backoff = Backoff::new(1, u64::MAX); + for exponent in 0..64 { + assert_eq!( + backoff.get_interval(), + Duration::from_millis(1u64 << exponent) + ); + } + for _ in 0..100 { + assert_eq!(backoff.get_interval(), Duration::from_millis(u64::MAX)); + } + } + + #[test] + fn backoff_reset_restarts_growth_even_after_reaching_the_cap() { + let mut backoff = Backoff::new(100, 700); + // Reset before the first wait, during growth and at the cap. None of + // these operations should consume the initial interval or change max. + for consumed in [0, 2, 20] { + backoff.reset(); + for _ in 0..consumed { + backoff.get_interval(); + } + backoff.reset(); + backoff.reset(); + for expected in [100, 200, 400, 700, 700] { + assert_eq!(backoff.get_interval(), Duration::from_millis(expected)); + } + } + } + + #[test] + fn backoff_reset_preserves_bounded_zero_and_extreme_initial_intervals() { + // Reset retains the constructor's clamping and zero semantics, without + // reintroducing overflow when an extreme sequence grows again. + for (initial, max) in [ + (0, 0), + (0, u64::MAX), + (100, 0), + (900, 700), + (u64::MAX / 2 + 1, u64::MAX), + (u64::MAX, u64::MAX), + ] { + let mut backoff = Backoff::new(initial, max); + for _ in 0..100 { + backoff.get_interval(); + } + backoff.reset(); + assert_eq!( + backoff.get_interval(), + Duration::from_millis(initial.min(max)) + ); + assert_eq!( + backoff.get_interval(), + Duration::from_millis(initial.min(max).saturating_mul(2).min(max)) + ); + } + } +} diff --git a/backend/crates/core/src/net/tcp/README.md b/backend/crates/core/src/net/tcp/README.md new file mode 100644 index 000000000..17dadb143 --- /dev/null +++ b/backend/crates/core/src/net/tcp/README.md @@ -0,0 +1,212 @@ +# `net::tcp` — reconnecting TCP clients (feature `net`) + +TCP is a client with one independently reconnecting connection per configured board. It receives messages/protections and writes orders, keep-alive and faults. +It connects to each board's `TCP_SERVER` port and never listens. + +Application policy, ADJ loading, logging to disk and frontend integration belong outside this module. Transport errors and received protections never trigger a fault automatically. See the [parent module](../README.md) for shared reporting types, channel semantics and the status of other transports. + +For a step-by-step explanation, open [trace.html](trace.html) directly in a browser. The standalone interactive walkthrough covers send/receive paths, byte layouts, reporting, partial frames, admission failures and cancellation. It uses illustrative data and no sockets or hardware. + +## Public API + +| Entry point / type | Purpose | +| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------ | +| `tcp::spawn(TcpConfig, Arc, Reporter) -> BoardClients` | Start configured clients without waiting for connections. Requires a Tokio runtime. | +| `tcp::TcpConfig`, `BoardLink`, `Backoff::new(initial_ms, max_ms)` | Supply board addresses, local ports, timeouts, retry intervals and heartbeat period. | +| `BoardClients::send(OrderPacket)` | Resolve the destination, validate, encode and write an order to its current session. | +| `BoardClients::broadcast_fault()` | Request a fault write on every currently active board session. | +| `BoardClients::board(BoardId)`, `BoardHandle::board()` | Read-only lookup of configured boards; presence does not mean connected. | +| `tcp::SendError`, `Unreachable`, `tcp::TcpError` | Inspect send, broadcast and TCP failures. | + +Connection/session helpers, writer coordination, direct board sends and reporter publication methods are internal. Applications send only through `BoardClients` so they cannot accidentally route an order to the wrong board. + +## Usage + +Load the matching ADJ outside `net`, build `Arc` from it, and resolve the desired boards into `TcpConfig::boards`. Each `BoardLink` supplies a board ID, remote IP/`TCP_SERVER` port and local port; local port zero lets the OS choose. For example, use `Backoff::new(500, 5000)`, a five-second `connect_timeout`, a two-second `write_timeout` and a one-second `keep_alive` period. + +`Reporter` is the cloneable handle TCP uses to publish notifications and transport errors; it does not write logs or decide how the application responds. `Reporter::channels(notifications, errors)` returns both the `Reporter` passed to `tcp::spawn` and a `Sinks` value kept by the application: + +- `sinks.notifications` receives board lifecycle events and decoded packets (`Notification`). +- `sinks.errors` receives transport failures (`ErrorReport`). TCP failures are wrapped as `net::Error::Tcp(tcp::TcpError::...)`; `SendError` remains the direct result of an order send. + +The two arguments set the bounded channel capacities. Consume **both** reporting channels concurrently with application operations so a full channel does not block transport reporting: + +```rust +use software_core::{ + net::{tcp, Reporter}, + protocol::Index, +}; +use std::sync::Arc; + +async fn run( + config: tcp::TcpConfig, + index: Arc, +) -> Result<(), Box> { + let (reporter, mut sinks) = Reporter::channels(256, 16); + let handles = tcp::spawn(config, index, reporter); + let application = async { + // For each fresh application command, call: + // handles.send(order).await?; // Complete socket write; no firmware ACK. + // Call handles.broadcast_fault().await only when application policy requires it. + tokio::signal::ctrl_c().await?; + Ok::<_, Box>(()) + }; + let reporting = async { + tokio::join!( + async { + while let Some(notification) = sinks.notifications.recv().await { + println!("{notification:?}"); + } + }, + async { + while let Some(report) = sinks.errors.recv().await { + eprintln!("{report:?}"); + } + }, + ); + }; + let result = tokio::select! { + result = application => result, + () = reporting => Err(std::io::Error::other("reporting stopped").into()), + }; + sinks.notifications.close(); + sinks.errors.close(); + drop(handles); + result +} +``` + +`spawn` returns before connecting. Wait for the destination's `Connected` event before attempting an order. The example keeps transport/reporting alive; invoke `handles.send(order).await` when the application receives a fresh command. An immediate call after `spawn` can return `SendError::Disconnected`. A `Connected` event is an observation, not a reservation: the connection can end before a subsequent send. Handle every send result. Do not automatically retry a hardware order after a write failure or timeout: firmware may already have received some or all of it. + +TCP publishes `Connected`, `Disconnected` and `Received(Packet)` through the [shared reporting channels](../README.md#reporting). Keep both consumers active to avoid blocking transport tasks on backpressure. + +## Guarantees + +### Connections and normal orders + +- `spawn` starts one supervisor per distinct board ID. Duplicate IDs keep the first link and warn; an empty config opens nothing. +- Startup and recovery use `connection::connect()`, which retries indefinitely with capped exponential backoff. Startup attempts immediately; after session loss the supervisor waits one interval. A successful connection resets the backoff. +- `send` accepts only declared order IDs and routes through the immutable index. Encoding validates wire representation, not application safety rules. +- After encoding, a send snapshots the current session. Offline boards fail with `Disconnected`; sends never wait for a connection or move to a newer session. +- Orders, heartbeats and faults all wait for one asynchronous socket mutex. There are no priority reservations, control channels or `Busy` rejections. Tokio's mutex serves lock waiters in the order they enter its queue; concurrent API invocations are not themselves an ordering guarantee. +- `write_timeout` covers both waiting for that mutex and the complete `write_all`. Encoding and error publication are outside this budget. A zero budget sends nothing. +- Expiry or cancellation before writing starts leaves the session and any active frame untouched. Once writing starts, an error, timeout or cancellation closes the session before another frame can write. Some or all bytes may already have reached firmware; the order is never replayed. +- Waiting orders remain in their callers' futures. There is no background order queue or detached task per send. Waiting does not retain an order across reconnection; retained references to the old writer become disconnected. +- **Success means `write_all` completed**, so the local socket accepted the frame. It does not confirm firmware receipt or execution. There is no order ACK or separate successful-send event. +- Heartbeat is reserved frame `01 00`. Zero `keep_alive` disables it. Otherwise the first write waits one period, and the next period starts after the preceding attempt ends; there are no catch-up bursts. A heartbeat whose writer wait expires is skipped. A heartbeat that fails after writing begins closes the session. There is no production read timeout. + +### Send results and error reporting + +| Result | Meaning | Reporting | +| --- | --- | --- | +| `Ok(())` | Complete local socket write; no firmware ACK. | No sent event. | +| `UnknownId(id)` | ID absent or declared as a different packet type. | Returned only. | +| `NoClient(board)` | Destination absent from the configured boards. | Returned only. | +| `Encode { board, source }` | Invalid parameters or unrepresentable value. | Returned only. | +| `Disconnected(board)` | No current session, or the captured session ended. | `TcpError::Send`, source kind `NotConnected`. | +| `Timeout(board)` | Writer wait or frame write exceeded the shared deadline. Only expiry during writing closes the session. | `TcpError::Send`, source kind `TimedOut`. | +| `Write { board, source }` | Socket write failure; session closed. | `TcpError::Send`, original shared I/O source. | + +Each transport failure is returned and published once as `TcpError::Send { board, order, source }`. The order ID is not a unique request ID. A failed normal write does not also produce a duplicate supervisor `TcpError::Write`. An unfinished write cancelled by its caller instead produces `TcpError::Write` with `Interrupted`, because there is no caller left to receive its result. Heartbeat/fault failures during writing are also reported by the supervisor. + +Consume both Reporter channels concurrently. Error publication can wait for capacity after the transport attempt ends, outside `write_timeout`. A full error channel cannot cause a failed order to be sent later. There is no cross-channel ordering guarantee between errors and lifecycle notifications. + +### Explicit fault broadcast + +`broadcast_fault()` writes reserved bytes `00 00`, independently of the ADJ. It snapshots the configured boards' current writers and polls all attempts concurrently under one absolute `write_timeout` deadline, including each wait for its mutex. Faults use the same write path as orders and heartbeats, without priority or a separate request queue. They never interrupt an existing frame. + +Disconnected boards fail immediately. Expired or cancelled waits send nothing and cannot reappear on a later session. Cancelling a fault that has started writing closes that session, just like cancelling an order. There is no detached fault write. + +`Unreachable(Vec)` identifies unconfirmed boards sorted by ID. A failure can still mean partial or complete delivery. An empty configuration succeeds. Fault does not install a persistent order lock; automatic triggers, a fault latch and recovery policy belong to the application. + +### Reporting, framing and cancellation + +TCP accumulates partial input and extracts complete ADJ-dependent frames. An undecodable suffix waits for more bytes until it exceeds the 374-byte framing limit; then `TcpError::Decode` is reported and the connection is reopened. EOF in a partial frame is `TcpError::Read`. Only decode failures are classified as fatal by `is_fatal()`; the application decides the response. + +Closing either Reporter consumer cancels supervisors even during idle I/O or offline retries. Dropping `BoardClients` alone does not stop them. Cancellation may omit a final `Disconnected` event and discard buffered input or an unpublished packet; queued notifications remain drainable. + +Sockets use zero linger (abortive close), not a lossless-delivery guarantee. Teardown signals the writer's closure so both active and waiting operations can stop. Idle sockets drop immediately; an active write drops its socket when polled or cancelled. No operation transfers to a new connection. + +### Implementation structure + +| File | Responsibility | +| --- | --- | +| `tcp.rs` | Configuration and one supervisor per board. | +| `board_clients.rs` | ADJ routing and concurrent explicit fault broadcasts. | +| `board_handle.rs` | Encode, snapshot a session, send and report transport errors. | +| `connection.rs`, `supervisor.rs` | Connection attempts, backoff, reconnects and lifecycle reports. | +| `session.rs` | Register a writer and drive reading/heartbeat until the session ends. | +| `endpoint.rs` | Publish the current writer and invalidate it when its registration is dropped. | +| `writer.rs` | Shared mutex, complete-frame writes, deadlines and cancellation safety. | +| `keep_alive.rs` | Periodic heartbeat using the writer's control method. | +| `reader.rs`, `framing.rs` | Incoming message/protection decoding and publication. | + +The send path is `encode → current_writer → write_order → result/report`. Each connection owns a fresh `Arc>`; `Endpoint` holds only the current writer. The registration guard closes and removes it on every session exit, including cancellation while publishing `Connected`. `Endpoint::request_fault` snapshots its writer before its returned future is polled, so delayed polling cannot retarget a reconnect. + +`write_order` and `write_control` share `write_frame`, which has three phases: `acquire_socket`, `FrameGuard::write_all` and `FrameGuard::finish`. Waiting owns no frame guard, so cancelling a waiter leaves the active write untouched. After acquisition, the guard closes an unfinished write before releasing the socket mutex. `finish` handles success or failure and disarms cancellation cleanup. One absolute deadline covers both waiting and writing. + +`FailureReporter` selects the reporting owner: orders report through their caller, while heartbeats and faults report through the session supervisor. The writer retains the first terminal `WriteFailure`; `take_unreported_failure` returns only a failure the supervisor still needs to publish. `keep_alive` uses writer methods to observe closure and send heartbeats; it does not access the socket directly. The writer's generic `W` defaults to the real TCP write half; tests substitute deterministic partial writers. + +## Tests + +From `backend/`: + +```sh +cargo test -p software-core --features net +``` + +Automated tests live in an inline `#[cfg(test)] mod tests` beside the implementation they exercise: + +| Owner | Test responsibility | +| --- | --- | +| `tcp.rs`, `error.rs` | Backoff arithmetic/reset and error classification/identity. | +| `connection.rs` | Socket options, connect failures, retry timing, cancellation and error-channel backpressure. | +| `framing.rs`, `reader.rs` | Partial/coalesced frames, variable field widths, framing limits, EOF/reset and notification backpressure. | +| `board_clients.rs` | ADJ routing/validation and multi-board explicit fault delivery. | +| `board_handle.rs` | Send-result reporting, concurrent sends/faults and failed-order reporting across reconnection. | +| `session.rs`, `supervisor.rs` | Registration cancellation, session invalidation, reconnect/no-replay and consumer shutdown. | +| `endpoint.rs` | Shared order/fault registration, captured sessions, teardown and no redirection across reconnects. | +| `writer.rs` | Serialized complete/partial writes, waiting deadlines, errors and cancellation. | +| `keep_alive.rs` | Heartbeat timing, serialized writes, skipped waits and failures. | + +Shared ADJ/socket/event fixtures and the controlled `AsyncWrite` fixture live in test-only [test_support.rs](test_support.rs). Scripted writer helpers are grouped in its inline `writes` module. All fixtures are compiled only for tests. The `send` and `broadcast_fault` entry points are unchanged; `SendError::Busy` has been removed because sends now wait for writer availability. Files are split at responsibility boundaries, with line count a review signal rather than a hard limit. Manual probes stay ignored in [manual_tests.rs](manual_tests.rs). + +Run a focused group with a Cargo name filter, for example: + +```sh +cargo test -p software-core --features net net::tcp::writer::tests +cargo test -p software-core --features net net::tcp::connection::tests +cargo test -p software-core --features net net::tcp::board_clients::tests +``` + +For these three, `ADJ_DIR` and `TCP_BOARD` are required; `TCP_LOCAL_PORT` defaults to 0 and `TCP_KEEP_ALIVE_MS` to 1000 (zero disables heartbeat). The board IP and `TCP_SERVER` port come from the ADJ. + +```sh +# Observe connections, messages and protections; no normal orders or faults. +ADJ_DIR=/path/to/adj TCP_BOARD=TEST \ +cargo test -p software-core --features net manual_tcp_spawn -- --ignored --nocapture + +# WARNING: sends a REAL fault once after the first Connected event. +ADJ_DIR=/path/to/adj TCP_BOARD=TEST \ +cargo test -p software-core --features net manual_tcp_fault -- --ignored --nocapture + +# WARNING: sends order 1001 once; inspect the test's parameter before using hardware. +ADJ_DIR=/path/to/adj TCP_BOARD=TEST \ +cargo test -p software-core --features net manual_tcp_supervisor -- --ignored --nocapture +``` + +Use a safe test setup. These probes print both channels until Ctrl+C. The fault probe fails on an unconfirmed write and never repeats its request on reconnect. Verify firmware's actual fault state separately. + +For a simulator, use a **private ADJ copy** with the selected board IP set to `127.0.0.1`. If `TCP_SERVER` is 50500, start this before the probe: + +```sh +nc -l 50500 | od -An -tx1 -v -w2 +``` + +The receive-only probe also uses connection retries and consumes both report channels; its 30-second overall deadline includes connection/backoff and reading. The fault probe produces `00 00` once, then heartbeats `01 00`. Restarting `nc` should reconnect without another fault. The separate `manual_tcp_receive` test uses the bundled fixture and loopback; its scripted peer command is in [manual_tests.rs](manual_tests.rs). + +## Limitations + +No hash exchange/handshake, explicit shutdown/join API, order ACKs or successful-order write notifications are implemented. The send result itself confirms the normal write. Physical-link loss is noticed only when TCP detects failure; heartbeat writes are not application-level ACKs. + +Implementation details and focused test contracts live in the corresponding Rust modules, rather than defining additional public entry points here. diff --git a/backend/crates/core/src/net/tcp/board_clients.rs b/backend/crates/core/src/net/tcp/board_clients.rs new file mode 100644 index 000000000..f4cb51cf5 --- /dev/null +++ b/backend/crates/core/src/net/tcp/board_clients.rs @@ -0,0 +1,363 @@ +use super::{BoardHandle, SendError, Unreachable}; +use crate::model::{BoardId, OrderPacket, PacketType}; +use crate::protocol::Index; +use std::{ + collections::HashMap, + future::{Future, poll_fn}, + sync::Arc, + task::Poll, + time::Duration, +}; +use tokio::time::Instant; + +/// Access to the configured boards' TCP clients. +/// +/// A board remains in this collection while disconnected. Connection state +/// belongs to its task, not to the presence of its handle in this map. +/// The shared, read-only index resolves order IDs to their destination boards. +#[derive(Debug)] +pub struct BoardClients { + // Configured boards by ID, including disconnected destinations. + boards: HashMap, + // Immutable ADJ packet definitions used to resolve order destinations. + index: Arc, + // Absolute budget for each fault attempt, including frame-boundary waits. + write_timeout: Duration, +} + +impl BoardClients { + /// Assembles the configured handles after their supervisor tasks are started. + pub(super) fn new( + boards: HashMap, + index: Arc, + write_timeout: Duration, + ) -> Self { + Self { + boards, + index, + write_timeout, + } + } + + /// Returns read-only access to a configured board, regardless of connection state. + /// Presence does not imply a live connection. Send orders through [`Self::send`] + /// rather than selecting a destination manually. + #[must_use] + pub fn board(&self, board: BoardId) -> Option<&BoardHandle> { + self.boards.get(&board) + } + + /// Resolves, validates and writes an order to the current destination session. + /// + /// Success confirms complete write_all acceptance, not firmware receipt or + /// execution. Offline sessions fail immediately. Connected callers wait for + /// the same mutex as heartbeats and faults; write_timeout bounds waiting and + /// writing together. No request survives reconnection and no background task + /// retains orders. Cancelling while waiting writes nothing; cancelling an + /// unfinished write closes that session. + /// + /// Routing/encoding failures are returned only. Transport failures also + /// publish [`super::TcpError::Send`]; consume both Reporter channels concurrently, + /// as reporting backpressure is outside write_timeout. + /// + /// # Errors + /// UnknownId, NoClient and Encode reject invalid input before writing. + /// Disconnected, Timeout and Write describe the transport attempt. + pub async fn send(&self, order: OrderPacket) -> Result<(), SendError> { + let definition = self + .index + .packet(order.id) + // Check if the packet is typed as order + .filter(|definition| matches!(&definition.packet_type, PacketType::Order(_))) + .ok_or(SendError::UnknownId(order.id))?; + let handle = self + .board(definition.board) + .ok_or(SendError::NoClient(definition.board))?; + + handle.send(order).await + } + + /// Writes the reserved fault frame (00 00) through every current board writer. + /// + /// Attempts run concurrently, each bounded by [`super::TcpConfig::write_timeout`] + /// from the start of this call, including waiting for the writer. Faults use + /// the same mutex as orders and heartbeats, without a priority reservation or + /// separate control queue. An in-progress frame is never interrupted by a fault. + /// + /// Disconnected boards fail immediately; no reconnection or automatic replay + /// is attempted. Each attempt snapshots its session. Cancelling before writing + /// sends nothing; cancelling an unfinished write closes that session. An empty + /// configuration succeeds. Success confirms write_all, not firmware execution. + /// A persistent fault latch and recovery policy belong to the application. + /// + /// # Errors + /// Returns the configured boards whose write completion was not confirmed + /// (offline, session ended, I/O failure, or deadline elapsed). A failed/partial + /// write is never retried and ends that session. Expiry while waiting leaves + /// it usable. Failure does not prove that no bytes were delivered. + pub async fn broadcast_fault(&self) -> Result<(), Unreachable> { + let started = Instant::now(); + let deadline = started + self.write_timeout; + tracing::info!(board_count = self.boards.len(), write_timeout = ?self.write_timeout, + "TCP fault broadcast requested"); + let mut pending: Vec<_> = self + .boards + .values() + .map(|handle| { + ( + handle.board, + Box::pin(handle.endpoint.request_fault(deadline)), + ) + }) + .collect(); + let mut failed = Vec::new(); + // Poll every board without spawning detached tasks or serialising waits. + // Dropping this future cancels every pending attempt in its captured session. + poll_fn(|cx| { + pending.retain_mut(|(board, request)| match request.as_mut().poll(cx) { + Poll::Ready(success) => { + if !success { + failed.push(*board); + } + false + } + Poll::Pending => true, + }); + if pending.is_empty() { + Poll::Ready(()) + } else { + Poll::Pending + } + }) + .await; + if failed.is_empty() { + tracing::info!( + board_count = self.boards.len(), + elapsed_ms = started.elapsed().as_millis(), + "TCP fault broadcast writes completed" + ); + Ok(()) + } else { + failed.sort_unstable_by_key(|board| board.0); + tracing::warn!(board_count = self.boards.len(), unconfirmed_boards = ?failed, + elapsed_ms = started.elapsed().as_millis(), + "TCP fault broadcast has unconfirmed writes"); + Err(Unreachable(failed)) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + model::{AdjId, OrderPacket, Port, Value}, + net::{ + Notification, Reporter, Sinks, + tcp::{Backoff, BoardLink, TcpConfig, spawn, test_support::*}, + }, + protocol::EncodeError, + }; + use std::net::{Ipv4Addr, SocketAddr}; + use tokio::{ + io::AsyncReadExt, + net::{TcpListener, TcpSocket, TcpStream}, + }; + + async fn next_notification( + sinks: &mut Sinks, + missing: &str, + ) -> Result> { + sinks + .notifications + .recv() + .await + .ok_or_else(|| missing.into()) + } + + async fn assert_fault_broadcast( + handles: &BoardClients, + first: &mut TcpStream, + second: &mut TcpStream, + ) -> Result<(), Box> { + let (mut a, mut b) = ([0xff; 2], [0xff; 2]); + let (broadcast, read_a, read_b) = tokio::join!( + handles.broadcast_fault(), + first.read_exact(&mut a), + second.read_exact(&mut b) + ); + assert_eq!(broadcast, Ok(())); + read_a?; + read_b?; + assert_eq!((a, b), ([0, 0], [0, 0])); + Ok(()) + } + + #[tokio::test] + async fn routes_and_encodes_each_order_only_to_its_destination() -> TestResult { + bounded(async { + let first = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?; + let second = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?; + let mut config = config(first.local_addr()?); + config.boards.push(BoardLink { + board: BoardId(9), + addr: second.local_addr()?, + local_port: Port(0), + }); + let (reporter, mut sinks) = Reporter::channels(16, 16); + let clients = spawn(config, index(), reporter); + let ((mut a, _), (mut b, _)) = tokio::try_join!(first.accept(), second.accept())?; + connected(&mut sinks).await?; + connected(&mut sinks).await?; + assert_eq!(clients.board(BOARD).map(BoardHandle::board), Some(BOARD)); + assert!(clients.board(BoardId(10)).is_none()); + clients.send(order(600, 42.0)).await?; + clients.send(order(601, 99.0)).await?; + let (mut aa, mut bb) = ([0; 3], [0; 3]); + a.read_exact(&mut aa).await?; + b.read_exact(&mut bb).await?; + assert_eq!(aa, [0x58, 2, 42]); + assert_eq!(bb, [0x59, 2, 99]); + assert!(sinks.errors.try_recv().is_err()); + sinks.notifications.close(); + peer_closed(&mut a).await?; + peer_closed(&mut b).await?; + Ok(()) + }) + .await + } + + #[tokio::test] + async fn validation_and_unconfigured_destination_fail_before_transport_admission() -> TestResult + { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let clients = spawn( + TcpConfig { + boards: vec![], + ..config(SocketAddr::from((Ipv4Addr::LOCALHOST, 1))) + }, + index(), + reporter, + ); + assert!(matches!( + clients.send(order(999, 1.0)).await, + Err(SendError::UnknownId(AdjId(999))) + )); + assert!(matches!( + clients.send(order(1600, 1.0)).await, + Err(SendError::UnknownId(AdjId(1600))) + )); + assert!(matches!( + clients.send(order(600, 1.0)).await, + Err(SendError::NoClient(BOARD)) + )); + assert!(clients.broadcast_fault().await.is_ok()); + assert!(sinks.errors.try_recv().is_err()); + let socket = TcpSocket::new_v4()?; + socket.bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))?; + let (reporter, mut sinks) = Reporter::channels(16, 16); + let clients = spawn(config(socket.local_addr()?), index(), reporter); + assert!(matches!( + clients + .send(OrderPacket::new(AdjId(600), vec![Value::Bool(true)])) + .await, + Err(SendError::Encode { + board: BOARD, + source: EncodeError::TypeMismatch + }) + )); + assert!(matches!( + clients.send(OrderPacket::new(AdjId(600), vec![])).await, + Err(SendError::Encode { + source: EncodeError::WrongFieldCount { + expected: 1, + got: 0 + }, + .. + }) + )); + assert!(matches!( + clients.send(order(600, 256.0)).await, + Err(SendError::Encode { + source: EncodeError::OutOfRange { .. }, + .. + }) + )); + assert!(sinks.errors.try_recv().is_err()); // Spawned task has not been polled. + sinks.notifications.close(); + Ok(()) + } + + #[tokio::test] + async fn broadcasts_faults_over_active_clients_without_replaying_after_reconnect() + -> Result<(), Box> { + use crate::net::Event; + use std::net::Ipv4Addr; + use tokio::{net::TcpListener, time::timeout}; + + timeout(Duration::from_secs(6), async { + let first_listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?; + let third_listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?; + let config = TcpConfig { + boards: vec![ + BoardLink { + board: BoardId(1), + addr: first_listener.local_addr()?, + local_port: Port(0), + }, + BoardLink { + board: BoardId(3), + addr: third_listener.local_addr()?, + local_port: Port(0), + }, + ], + connect_timeout: Duration::from_millis(100), + backoff: Backoff::new(1000, 1000), + write_timeout: Duration::from_millis(200), + keep_alive: Duration::ZERO, + }; + let (reporter, mut sinks) = Reporter::channels(32, 16); + // Reserved ID 0 must work with no ADJ orders declared at all. + let handles = spawn(config, Arc::new(Index::default()), reporter); + let (first, third) = + tokio::try_join!(first_listener.accept(), third_listener.accept())?; + let (mut first, mut third) = (first.0, third.0); + for _ in 0..2 { + let notification = next_notification(&mut sinks, "reporting stopped").await?; + assert!(matches!(notification.event, Event::Connected)); + } + + assert_fault_broadcast(&handles, &mut first, &mut third).await?; + + drop(first); + let notification = next_notification(&mut sinks, "missing disconnection").await?; + assert_eq!(notification.board, BoardId(1)); + assert!(matches!(notification.event, Event::Disconnected)); + // The offline board fails, without preventing the healthy board's write. + let mut b = [0xff; 2]; + let (broadcast, read_b) = + tokio::join!(handles.broadcast_fault(), third.read_exact(&mut b)); + assert_eq!(broadcast, Err(Unreachable(vec![BoardId(1)]))); + read_b?; + assert_eq!(b, [0, 0]); + + let (mut reconnected, _) = first_listener.accept().await?; + let notification = next_notification(&mut sinks, "missing reconnection").await?; + assert_eq!(notification.board, BoardId(1)); + assert!(matches!(notification.event, Event::Connected)); + // Neither the successful first fault nor the offline request is replayed. + let mut a = [0xff; 2]; + assert!( + timeout(Duration::from_millis(30), reconnected.read_exact(&mut a)) + .await + .is_err() + ); + assert_fault_broadcast(&handles, &mut reconnected, &mut third).await?; + sinks.notifications.close(); + sinks.errors.close(); + Ok::<_, Box>(()) + }) + .await??; + Ok(()) + } +} diff --git a/backend/crates/core/src/net/tcp/board_handle.rs b/backend/crates/core/src/net/tcp/board_handle.rs new file mode 100644 index 000000000..b2df3104f --- /dev/null +++ b/backend/crates/core/src/net/tcp/board_handle.rs @@ -0,0 +1,230 @@ +//! Read-only board identity and direct, session-bound normal order writes. +use super::{SendError, TcpError, endpoint}; +use crate::{ + model::{BoardId, OrderPacket}, + net::Reporter, + protocol::{Index, tcp}, +}; +use std::{io, sync::Arc, time::Duration}; +use tokio::time::Instant; + +/// A configured board, including while disconnected. Presence does not imply a +/// live socket. Submit orders through BoardClients so the index controls routing. +#[derive(Debug)] +pub struct BoardHandle { + pub(super) board: BoardId, + pub(super) index: Arc, + pub(super) endpoint: endpoint::Endpoint, + pub(super) write_timeout: Duration, + pub(super) reporter: Reporter, +} +impl BoardHandle { + /// The configured board's identity; independent of connection state. + #[must_use] + pub fn board(&self) -> BoardId { + self.board + } + + /// Encoding precedes writing. A send snapshots one session, waits for its + /// writer within write_timeout, and never waits for reconnection. Failed + /// transport attempts are reported once here; encoding failures are returned + /// only. Reporting backpressure is outside write_timeout. + pub(super) async fn send(&self, order: OrderPacket) -> Result<(), SendError> { + let started = Instant::now(); + tracing::debug!(board = ?self.board, order = ?order.id, "Attempting TCP order send"); + let bytes = tcp::encode_order(&order, &self.index).map_err(|source| { + tracing::debug!(board = ?self.board, order = ?order.id, error = ?source, + elapsed_ms = started.elapsed().as_millis(), "TCP order encoding failed"); + SendError::Encode { + board: self.board, + source, + } + })?; + let result = match self.endpoint.current_writer() { + Some(writer) => { + writer + .write_order(self.board, &bytes, self.write_timeout) + .await + } + None => Err(SendError::Disconnected(self.board)), + }; + if let Err(error) = &result { + let source = match error { + SendError::Disconnected(_) => Arc::new(io::Error::new( + io::ErrorKind::NotConnected, + "TCP session ended or has not connected", + )), + SendError::Timeout(_) => Arc::new(io::Error::new( + io::ErrorKind::TimedOut, + "TCP order write timed out", + )), + SendError::Write { source, .. } => Arc::clone(source), + _ => unreachable!("routing and encoding finish before writing"), + }; + tracing::warn!(board = ?self.board, order = ?order.id, error = ?error, + frame_len = bytes.len(), elapsed_ms = started.elapsed().as_millis(), + "TCP order send failed"); + let _ = self + .reporter + .report(TcpError::Send { + board: self.board, + order: order.id, + source, + }) + .await; + } else { + tracing::debug!(board = ?self.board, order = ?order.id, + frame_len = bytes.len(), elapsed_ms = started.elapsed().as_millis(), + "TCP order write completed"); + } + result + } +} + +#[cfg(test)] +mod tests { + use crate::{ + model::AdjId, + net::{ + Reporter, + tcp::{SendError, TcpError, spawn, test_support::*}, + }, + }; + use std::{ + future::Future, + net::{Ipv4Addr, SocketAddr}, + time::Duration, + }; + use tokio::{ + io::AsyncReadExt, + net::{TcpListener, TcpSocket}, + time::timeout, + }; + + #[tokio::test] + async fn zero_write_budget_reports_once_without_writing_or_reconnecting() -> TestResult { + bounded(async { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?; + let mut config = config(listener.local_addr()?); + config.write_timeout = Duration::ZERO; + let (reporter, mut sinks) = Reporter::channels(16, 16); + let clients = spawn(config, index(), reporter); + let (mut peer, _) = listener.accept().await?; + connected(&mut sinks).await?; + assert!(matches!( + clients.send(order(600, 22.0)).await, + Err(SendError::Timeout(BOARD)) + )); + let report = sinks.errors.recv().await.ok_or("missing send report")?; + assert!( + matches!(report.error, crate::net::Error::Tcp(TcpError::Send { + board: BOARD, order: AdjId(600), source + }) if source.kind() == std::io::ErrorKind::TimedOut) + ); + let mut bytes = [0; 3]; + assert!( + timeout(Duration::from_millis(20), peer.read(&mut bytes)) + .await + .is_err() + ); + assert!(sinks.notifications.try_recv().is_err()); + assert!(sinks.errors.try_recv().is_err()); + sinks.errors.close(); + peer_closed(&mut peer).await?; + Ok(()) + }) + .await + } + + #[tokio::test] + async fn concurrent_orders_and_fault_use_the_same_complete_frame_writer() -> TestResult { + bounded(async { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?; + let (reporter, mut sinks) = Reporter::channels(16, 16); + let clients = spawn(config(listener.local_addr()?), index(), reporter); + let (mut peer, _) = listener.accept().await?; + connected(&mut sinks).await?; + let (first, fault, second) = tokio::join!( + clients.send(order(600, 11.0)), + clients.broadcast_fault(), + clients.send(order(600, 22.0)), + ); + first?; + fault?; + second?; + let mut bytes = [0; 8]; + peer.read_exact(&mut bytes).await?; + // Concurrent calls have no promised invocation order. Every frame + // must still be intact, with each order and the fault appearing once. + let mut offset = 0; + let mut values = Vec::new(); + let mut faults = 0; + while offset < bytes.len() { + let id = u16::from_le_bytes([bytes[offset], bytes[offset + 1]]); + offset += 2; + match id { + 0 => faults += 1, + 600 => { + values.push(bytes[offset]); + offset += 1; + } + _ => return Err(format!("interleaved frame ID {id}").into()), + } + } + values.sort_unstable(); + assert_eq!(values, [11, 22]); + assert_eq!(faults, 1); + assert!(sinks.errors.try_recv().is_err()); + sinks.errors.close(); + peer_closed(&mut peer).await?; + Ok(()) + }) + .await + } + + #[tokio::test] + async fn reporting_backpressure_never_defers_a_rejected_order_into_a_new_connection() + -> TestResult { + bounded(async { + let socket = TcpSocket::new_v4()?; + socket.bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))?; + let (reporter, mut sinks) = Reporter::channels(16, 1); + let clients = spawn(config(socket.local_addr()?), index(), reporter); + assert!(matches!( + clients.send(order(600, 11.0)).await, + Err(SendError::Disconnected(BOARD)) + )); + let mut rejected = Box::pin(clients.send(order(600, 22.0))); + std::future::poll_fn(|cx| { + assert!(rejected.as_mut().poll(cx).is_pending()); + std::task::Poll::Ready(()) + }) + .await; // The second send waits only to publish its failure. + let listener = socket.listen(8)?; + let (mut peer, _) = listener.accept().await?; + connected(&mut sinks).await?; + sinks.errors.recv().await.ok_or("missing first rejection")?; + assert!(matches!( + rejected.await, + Err(SendError::Disconnected(BOARD)) + )); + sinks + .errors + .recv() + .await + .ok_or("missing second rejection")?; + clients.send(order(600, 33.0)).await?; + let mut bytes = [0; 3]; + peer.read_exact(&mut bytes).await?; + assert_eq!(bytes, [0x58, 2, 33]); + assert!( + timeout(Duration::from_millis(20), peer.read(&mut bytes)) + .await + .is_err() + ); + sinks.notifications.close(); + Ok(()) + }) + .await + } +} diff --git a/backend/crates/core/src/net/tcp/connection.rs b/backend/crates/core/src/net/tcp/connection.rs new file mode 100644 index 000000000..142a63feb --- /dev/null +++ b/backend/crates/core/src/net/tcp/connection.rs @@ -0,0 +1,483 @@ +//! Startup and recovery use one connection routine with capped exponential backoff. +//! +//! Socket setup and a single timed attempt are private details. All sibling +//! callers use connect(), which reports failures and retries until success or +//! reporting consumer loss. The supervisor owns the per-board backoff state and +//! the delay after an established session ends; this routine owns failure retries. + +use super::{Backoff, BoardLink, TcpError}; +use crate::net::{Closed, Reporter}; +use std::{ + io, + net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, + time::Duration, +}; +use tokio::{ + net::{TcpSocket, TcpStream}, + time::{sleep, timeout}, +}; + +/// Retries connection attempts until one succeeds or reporting detects consumer loss. +/// +/// This is the only connection entry point for startup, recovery and manual +/// probes. Every call retries failures with the supplied per-board backoff. +/// The first attempt in this routine is immediate. After a session ends, the +/// supervisor consumes one backoff interval before calling this same routine; +/// a successful preceding connection reset that interval to the initial value. +/// Each failure is logged and published through +/// [`Reporter::report`], then this helper waits for the next `backoff` interval. +/// Reporting applies backpressure: the interval starts after the error is queued, +/// not when the attempt fails. Consume the error channel concurrently to avoid +/// parking retries behind a full channel. Each attempt has its own +/// `connect_timeout`; reporting and backoff are outside that timeout. +/// +/// Failed attempts advance the caller's backoff state. A successful connection +/// resets it before returning the stream, so a later disconnection starts at the +/// initial interval. Keep that state across sessions instead of constructing a +/// fresh backoff for each failure. Retries have no limit. Zero intervals add no deliberate +/// retry delay and may generate errors rapidly. +/// +/// Success returns the connected stream immediately without emitting lifecycle +/// events, exchanging a hash, starting session I/O or reconnecting a later session. +/// No tasks are spawned. Dropping this future cancels the pending attempt, report +/// or wait; already queued errors remain available to the consumer. +/// +/// # Errors +/// +/// Returns [`Closed`] when publishing a failed attempt detects a closed error +/// consumer. Transport failures are reported, not returned. Consumer closure is +/// checked only when reporting, not proactively during a connection or wait. +pub(super) async fn connect( + link: &BoardLink, + connect_timeout: Duration, + backoff: &mut Backoff, + reporter: &Reporter, +) -> Result { + loop { + tracing::debug!(board = ?link.board, addr = %link.addr, "Attempting TCP connection"); + match connect_once(link, connect_timeout).await { + Ok(stream) => { + backoff.reset(); + tracing::debug!(board = ?link.board, addr = %link.addr, "TCP connection established"); + return Ok(stream); + } + Err(error) => { + tracing::debug!(board = ?link.board, addr = %link.addr, error = ?error, + "TCP connection attempt failed"); + reporter.report(error).await?; + let retry_delay = backoff.get_interval(); + tracing::debug!(board = ?link.board, addr = %link.addr, ?retry_delay, + "Waiting before TCP connection retry"); + sleep(retry_delay).await; + } + } + } +} + +/// One private socket attempt for the retry loop; sibling modules cannot bypass +/// the retry/reporting policy. Binds the local port before connecting. +/// +/// The remote address selects IPv4 or IPv6. The local address is unspecified +/// so routing selects the interface; local port zero requests an ephemeral port. +/// Kernel keep-alive is disabled: the application keep-alive is an empty order +/// with ID 1, sent later by the session's single writer. TCP_NODELAY is enabled. +/// Zero linger makes closing abortive and may discard unsent data. +/// +/// The timeout bounds the asynchronous connect, not the synchronous socket +/// setup. This function makes no retries, emits no events and performs no +/// application I/O or handshake. The caller owns the returned stream. +/// +/// # Errors +/// +/// Returns [`TcpError::Connect`] with the board ID and original I/O error if socket +/// creation, configuration, binding or connecting fails. An elapsed timeout is +/// represented by [`io::ErrorKind::TimedOut`]; its pending socket is dropped. +async fn connect_once(link: &BoardLink, connect_timeout: Duration) -> Result { + let result = async { + let (socket, local_ip) = match link.addr { + SocketAddr::V4(_) => (TcpSocket::new_v4()?, IpAddr::V4(Ipv4Addr::UNSPECIFIED)), + SocketAddr::V6(_) => (TcpSocket::new_v6()?, IpAddr::V6(Ipv6Addr::UNSPECIFIED)), + }; + socket.set_keepalive(false)?; + socket.set_zero_linger()?; + socket.set_nodelay(true)?; + socket.bind(SocketAddr::new(local_ip, link.local_port.0))?; + + timeout(connect_timeout, socket.connect(link.addr)) + .await + .map_err(io::Error::from)? + } + .await; + + result.map_err(|source| TcpError::Connect { + board: link.board, + source, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{BoardId, Port}; + use std::{ + future::{Future, poll_fn}, + pin::Pin, + task::Poll, + }; + use tokio::{ + net::TcpListener, + sync::mpsc::error::TryRecvError, + time::{Instant, advance}, + }; + const TEST_TIMEOUT: Duration = Duration::from_secs(2); + + async fn check_loopback_connection( + listener: TcpListener, + ) -> Result<(), Box> { + let link = BoardLink { + board: BoardId(3), + addr: listener.local_addr()?, + local_port: Port(0), + }; + + // Port zero lets parallel tests obtain distinct client ports from the OS. + let stream = connect_once(&link, TEST_TIMEOUT).await?; + let (_peer, source) = timeout(TEST_TIMEOUT, listener.accept()).await??; + assert_eq!(stream.peer_addr()?, link.addr); + assert_eq!(source, stream.local_addr()?); + assert_ne!(source.port(), 0); + + // Inspect the connected socket, not just the options requested during setup. + assert!(stream.nodelay()?); + assert_eq!(stream.linger()?, Some(Duration::ZERO)); + Ok(()) + } + + #[tokio::test] + async fn connects_to_an_ipv4_server_with_the_requested_options() + -> Result<(), Box> { + // A loopback listener acts as firmware without requiring a physical board. + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?; + check_loopback_connection(listener).await + } + + #[tokio::test] + async fn connects_to_an_ipv6_server_with_the_requested_options() + -> Result<(), Box> { + // Skip only when the host cannot provide IPv6 loopback; other failures matter. + // Linux EAFNOSUPPORT is not mapped to ErrorKind::Unsupported by std::io. + const LINUX_EAFNOSUPPORT: i32 = 97; + let listener = match TcpListener::bind((Ipv6Addr::LOCALHOST, 0)).await { + Ok(listener) => listener, + Err(error) + if matches!( + error.kind(), + io::ErrorKind::AddrNotAvailable | io::ErrorKind::Unsupported + ) || (cfg!(target_os = "linux") + && error.raw_os_error() == Some(LINUX_EAFNOSUPPORT)) => + { + eprintln!("IPv6 loopback is unavailable; skipping IPv6 connection test: {error}"); + return Ok(()); + } + Err(error) => return Err(error.into()), + }; + check_loopback_connection(listener).await + } + + #[tokio::test] + async fn an_occupied_local_port_reports_the_board_and_bind_error() + -> Result<(), Box> { + // Keep the port occupied throughout the attempt, avoiding a free-port race. + let occupied = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?; + let link = BoardLink { + board: BoardId(7), + addr: occupied.local_addr()?, + local_port: Port(occupied.local_addr()?.port()), + }; + let Err(error) = connect_once(&link, TEST_TIMEOUT).await else { + unreachable!("binding an occupied local port must fail"); + }; + + // Setup failures must retain both identity and cause, without faulting the pod. + assert!(!error.is_fatal()); + let TcpError::Connect { board, source } = error else { + unreachable!("a bind failure belongs to the connection attempt"); + }; + assert_eq!(board, BoardId(7)); + assert_eq!(source.kind(), io::ErrorKind::AddrInUse); + Ok(()) + } + + #[tokio::test] + async fn a_non_listening_peer_reports_the_board_and_connect_error() + -> Result<(), Box> { + // Reserve the remote port without listening, so no other test can claim it. + let unavailable = TcpSocket::new_v4()?; + unavailable.bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))?; + let link = BoardLink { + board: BoardId(9), + addr: unavailable.local_addr()?, + local_port: Port(0), + }; + let Err(error) = connect_once(&link, TEST_TIMEOUT).await else { + unreachable!("a bound but non-listening peer cannot accept the connection"); + }; + + // A refused connection is a retryable network failure, not a decode fault. + assert!(!error.is_fatal()); + let TcpError::Connect { board, source } = error else { + unreachable!("a refused connection must return TcpError::Connect"); + }; + assert_eq!(board, BoardId(9)); + assert_eq!(source.kind(), io::ErrorKind::ConnectionRefused); + Ok(()) + } + + /// Keeps the client bind port occupied so retry failures are synchronous and + /// deterministic, without depending on reactor readiness or remote routing. + async fn occupied_link() -> Result<(TcpListener, BoardLink), io::Error> { + let occupied = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?; + let link = BoardLink { + board: BoardId(7), + addr: occupied.local_addr()?, + local_port: Port(occupied.local_addr()?.port()), + }; + Ok((occupied, link)) + } + + /// Polls without letting Tokio automatically advance the paused clock. + async fn assert_pending_once(mut future: Pin<&mut F>) { + poll_fn(|cx| { + assert!(future.as_mut().poll(cx).is_pending()); + Poll::Ready(()) + }) + .await; + } + + #[tokio::test] + async fn retries_return_an_immediate_success_without_reporting_or_waiting() + -> Result<(), Box> { + // A minute-long backoff must not delay the first attempt. The returned + // stream retains connect's real socket configuration, with no I/O startup. + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?; + let link = BoardLink { + board: BoardId(3), + addr: listener.local_addr()?, + local_port: Port(0), + }; + let (reporter, mut sinks) = Reporter::channels(1, 1); + let mut backoff = Backoff::new(60_000, 240_000); + assert_eq!(backoff.get_interval(), Duration::from_secs(60)); + let stream = timeout( + TEST_TIMEOUT, + connect(&link, TEST_TIMEOUT, &mut backoff, &reporter), + ) + .await??; + assert_eq!(backoff.get_interval(), Duration::from_secs(60)); + let (_peer, source) = timeout(TEST_TIMEOUT, listener.accept()).await??; + assert_eq!(stream.peer_addr()?, link.addr); + assert_eq!(stream.local_addr()?, source); + assert!(stream.nodelay()?); + assert_eq!(stream.linger()?, Some(Duration::ZERO)); + assert!(matches!(sinks.errors.try_recv(), Err(TryRecvError::Empty))); + assert!(matches!( + sinks.notifications.try_recv(), + Err(TryRecvError::Empty) + )); + Ok(()) + } + + #[tokio::test] + async fn retries_connect_when_a_previously_unavailable_peer_starts_listening() + -> Result<(), Box> { + // Keep the remote port reserved without listening until the first refusal + // has been reported, then turn that same socket into the real server. + let unavailable = TcpSocket::new_v4()?; + unavailable.bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))?; + let link = BoardLink { + board: BoardId(9), + addr: unavailable.local_addr()?, + local_port: Port(0), + }; + let (reporter, mut sinks) = Reporter::channels(1, 16); + let mut backoff = Backoff::new(10, 40); + let connecting = async { connect(&link, TEST_TIMEOUT, &mut backoff, &reporter).await }; + let serving = async { + let Some(report) = sinks.errors.recv().await else { + unreachable!("the helper reports its initial connection failure"); + }; + assert!( + matches!(report.error, crate::net::Error::Tcp(TcpError::Connect { board, source }) + if board == link.board && source.kind() == io::ErrorKind::ConnectionRefused) + ); + let listener = unavailable.listen(1)?; + let (peer, _) = listener.accept().await?; + Ok::<_, io::Error>(peer) + }; + let (stream, peer) = + timeout(TEST_TIMEOUT, async { tokio::join!(connecting, serving) }).await?; + let stream = stream?; + let _peer = peer?; + // Even after one or more refused attempts, success restores the first wait. + assert_eq!(backoff.get_interval(), Duration::from_millis(10)); + assert_eq!(stream.peer_addr()?, link.addr); + assert!(matches!( + sinks.notifications.try_recv(), + Err(TryRecvError::Empty) + )); + Ok(()) + } + + #[tokio::test(start_paused = true)] + async fn retries_report_each_failure_and_wait_with_a_capped_backoff() + -> Result<(), Box> { + let (_occupied, link) = occupied_link().await?; + let (reporter, mut sinks) = Reporter::channels(1, 1); + let mut backoff = Backoff::new(100, 700); + let connecting = connect(&link, TEST_TIMEOUT, &mut backoff, &reporter); + tokio::pin!(connecting); + let started = Instant::now(); + assert_pending_once(connecting.as_mut()).await; + assert_eq!(started.elapsed(), Duration::ZERO); + let first = sinks.errors.try_recv()?; + assert!( + matches!(first.error, crate::net::Error::Tcp(TcpError::Connect { board, source }) + if board == link.board && source.kind() == io::ErrorKind::AddrInUse) + ); + + // Check both sides of every deadline, including repeated capped waits. + // There must be one report per attempt and no synthetic lifecycle events. + for interval in [100, 200, 400, 700, 700, 700] { + advance(Duration::from_millis(interval - 1)).await; + assert_pending_once(connecting.as_mut()).await; + assert!(matches!(sinks.errors.try_recv(), Err(TryRecvError::Empty))); + advance(Duration::from_millis(1)).await; + assert_pending_once(connecting.as_mut()).await; + let report = sinks.errors.try_recv()?; + assert!( + matches!(report.error, crate::net::Error::Tcp(TcpError::Connect { board, source }) + if board == link.board && source.kind() == io::ErrorKind::AddrInUse) + ); + assert!(matches!(sinks.errors.try_recv(), Err(TryRecvError::Empty))); + } + assert!(matches!( + sinks.notifications.try_recv(), + Err(TryRecvError::Empty) + )); + Ok(()) + } + + #[tokio::test(start_paused = true)] + async fn failed_retries_use_the_supplied_backoff_state_without_resetting_it() + -> Result<(), Box> { + // Passing an already advanced value must start its waits at 200 ms, + // rather than silently constructing a fresh sequence at 100 ms. + let (_occupied, link) = occupied_link().await?; + let (reporter, mut sinks) = Reporter::channels(1, 1); + let mut backoff = Backoff::new(100, 700); + assert_eq!(backoff.get_interval(), Duration::from_millis(100)); + { + let connecting = connect(&link, TEST_TIMEOUT, &mut backoff, &reporter); + tokio::pin!(connecting); + assert_pending_once(connecting.as_mut()).await; + sinks.errors.try_recv()?; + advance(Duration::from_millis(199)).await; + assert_pending_once(connecting.as_mut()).await; + assert!(matches!(sinks.errors.try_recv(), Err(TryRecvError::Empty))); + advance(Duration::from_millis(1)).await; + assert_pending_once(connecting.as_mut()).await; + sinks.errors.try_recv()?; + } + // Both scheduled waits advance the same caller-owned state, even when + // this helper is cancelled before completing its second wait. + assert_eq!(backoff.get_interval(), Duration::from_millis(700)); + Ok(()) + } + + #[tokio::test(start_paused = true)] + async fn retries_wait_for_error_capacity_before_starting_the_next_interval() + -> Result<(), Box> { + let (_occupied, link) = occupied_link().await?; + let (reporter, mut sinks) = Reporter::channels(1, 1); + let mut backoff = Backoff::new(100, 700); + let connecting = connect(&link, TEST_TIMEOUT, &mut backoff, &reporter); + tokio::pin!(connecting); + assert_pending_once(connecting.as_mut()).await; + // Leave the first report queued. The second failure cannot be published + // at 100 ms, and elapsed time must not consume its following 200 ms wait. + advance(Duration::from_millis(100)).await; + assert_pending_once(connecting.as_mut()).await; + advance(Duration::from_secs(1)).await; + assert_pending_once(connecting.as_mut()).await; + sinks.errors.try_recv()?; + assert_pending_once(connecting.as_mut()).await; + sinks.errors.try_recv()?; + assert!(matches!(sinks.errors.try_recv(), Err(TryRecvError::Empty))); + advance(Duration::from_millis(199)).await; + assert_pending_once(connecting.as_mut()).await; + assert!(matches!(sinks.errors.try_recv(), Err(TryRecvError::Empty))); + advance(Duration::from_millis(1)).await; + assert_pending_once(connecting.as_mut()).await; + sinks.errors.try_recv()?; + Ok(()) + } + + #[tokio::test] + async fn retries_stop_when_reporting_detects_a_closed_error_consumer() + -> Result<(), Box> { + // A failed report must return Closed, not enter the minute-long wait. + let (_occupied, link) = occupied_link().await?; + let (reporter, sinks) = Reporter::channels(1, 1); + drop(sinks.errors); + let mut backoff = Backoff::new(60_000, 60_000); + let result = timeout( + TEST_TIMEOUT, + connect(&link, TEST_TIMEOUT, &mut backoff, &reporter), + ) + .await?; + assert!(matches!(result, Err(Closed))); + Ok(()) + } + + #[tokio::test(start_paused = true)] + async fn retries_stop_if_the_consumer_closes_while_a_report_is_blocked() + -> Result<(), Box> { + let (_occupied, link) = occupied_link().await?; + let (reporter, sinks) = Reporter::channels(1, 1); + let mut backoff = Backoff::new(100, 700); + let connecting = connect(&link, TEST_TIMEOUT, &mut backoff, &reporter); + tokio::pin!(connecting); + assert_pending_once(connecting.as_mut()).await; + advance(Duration::from_millis(100)).await; + assert_pending_once(connecting.as_mut()).await; + // The second error is waiting for capacity behind the first one. + // Closing the receiver must release that wait and end the retry loop. + drop(sinks.errors); + assert!(matches!( + timeout(TEST_TIMEOUT, connecting).await?, + Err(Closed) + )); + Ok(()) + } + + #[tokio::test(start_paused = true)] + async fn cancelling_retries_during_backoff_preserves_reports_and_stops_attempts() + -> Result<(), Box> { + let (_occupied, link) = occupied_link().await?; + let (reporter, mut sinks) = Reporter::channels(1, 16); + let mut backoff = Backoff::new(100, 700); + let mut connecting = Box::pin(connect(&link, TEST_TIMEOUT, &mut backoff, &reporter)); + assert_pending_once(connecting.as_mut()).await; + drop(connecting); + // Cancellation owns no background task: advancing past many retries + // leaves exactly the one failure that had already been queued. + advance(Duration::from_secs(60)).await; + sinks.errors.try_recv()?; + assert!(matches!(sinks.errors.try_recv(), Err(TryRecvError::Empty))); + assert!(matches!( + sinks.notifications.try_recv(), + Err(TryRecvError::Empty) + )); + Ok(()) + } +} diff --git a/backend/crates/core/src/net/tcp/endpoint.rs b/backend/crates/core/src/net/tcp/endpoint.rs new file mode 100644 index 000000000..c04f4ba13 --- /dev/null +++ b/backend/crates/core/src/net/tcp/endpoint.rs @@ -0,0 +1,194 @@ +//! Shared access point to one board's current TCP session writer. +//! +//! An `Endpoint` is created once per configured board and shared between its +//! handle and connection supervisor. It holds an optional `Arc`: +//! `None` before a connection is registered or after its registration is removed, +//! and `Some(writer)` while that session is registered. Cloning the endpoint +//! shares this same slot, so every clone observes registration changes. +//! +//! Each new connection registers a fresh writer. `current_writer()` captures a +//! reference for an order; `request_fault()` captures one and sends the reserved +//! fault frame. The endpoint lock is released before any socket I/O. Connection +//! establishment and retries belong to the supervisor and connection module. +//! +//! The returned `Registration` guard ties the writer to the session's lifetime. +//! Dropping it closes the writer and clears the slot, invalidating references +//! retained by pending sends. The endpoint survives reconnections, but a captured +//! writer always belongs to its original session: pending writes never move to +//! the next connection. + +use super::writer::{SessionWriter, lock}; +use std::sync::{Arc, Mutex}; +use tokio::{io::AsyncWrite, net::tcp::OwnedWriteHalf, time::Instant}; + +#[derive(Debug)] +pub(super) struct Endpoint { + current: Arc>>>>, +} + +impl Default for Endpoint { + fn default() -> Self { + Self { + current: Arc::new(Mutex::new(None)), + } + } +} + +impl Clone for Endpoint { + fn clone(&self) -> Self { + Self { + current: Arc::clone(&self.current), + } + } +} + +impl Endpoint { + /// Capture the current writer without holding the endpoint lock during I/O. + pub(super) fn current_writer(&self) -> Option>> { + lock(&self.current).clone() + } + + /// The supervisor drops the previous registration before installing another. + pub(super) fn register(&self, writer: Arc>) -> Registration { + *lock(&self.current) = Some(Arc::clone(&writer)); + tracing::trace!(writer = ?Arc::as_ptr(&writer), "TCP session writer registered"); + Registration { + writer, + endpoint: self.clone(), + } + } +} + +impl Endpoint { + /// Request a fault on the session captured now; true confirms a complete local write. + /// Keep this capture outside the future so delayed polling cannot target a reconnect. + pub(super) fn request_fault( + &self, + deadline: Instant, + ) -> impl Future + Send + 'static { + let writer = self.current_writer(); + async move { + let Some(writer) = writer else { return false }; + writer.write_control(&[0, 0], deadline).await.is_ok() + } + } +} + +/// Removing a session also invalidates all references retained by pending callers. +#[derive(Debug)] +pub(super) struct Registration { + writer: Arc>, + endpoint: Endpoint, +} + +impl Drop for Registration { + fn drop(&mut self) { + self.writer.close(); + *lock(&self.endpoint.current) = None; + tracing::trace!(writer = ?Arc::as_ptr(&self.writer), "TCP session writer unregistered"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::net::tcp::{SendError, test_support::writes::*}; + + #[tokio::test] + async fn registration_invalidates_orders_and_faults_and_never_retargets_a_reconnect() { + let endpoint = Endpoint::default(); + let (writer, trace) = setup([]); + let writer = Arc::new(writer); + let active = endpoint.register(Arc::clone(&writer)); + assert!( + endpoint + .current_writer() + .is_some_and(|current| Arc::ptr_eq(&writer, ¤t)) + ); + let old_fault = endpoint.request_fault(Instant::now() + BUDGET); + drop(active); + assert!(endpoint.current_writer().is_none()); + let (next, next_trace) = setup([]); + let _next = endpoint.register(Arc::new(next)); + assert!(!old_fault.await); + assert!(matches!( + writer.write_order(BOARD, &[2, 3], BUDGET).await, + Err(SendError::Disconnected(BOARD)) + )); + assert!(lock(&trace).dropped); + assert!(lock(&next_trace).bytes.is_empty()); + assert!(endpoint.request_fault(Instant::now() + BUDGET).await); + assert_eq!(lock(&next_trace).bytes, [0, 0]); + } + + #[tokio::test(start_paused = true)] + async fn waiting_fault_expiry_or_cancellation_never_interrupts_an_order() { + let (writer, trace, endpoint, _active) = + setup_registered_writer([Step::Write(1), Step::Pending]); + let mut order = Box::pin(writer.write_order(BOARD, &[2, 3], BUDGET * 3)); + pending_once(order.as_mut()).await; + let mut cancelled = Box::pin(endpoint.request_fault(Instant::now() + BUDGET)); + pending_once(cancelled.as_mut()).await; + drop(cancelled); + assert!(!endpoint.request_fault(Instant::now() + BUDGET).await); + assert!(!lock(&trace).dropped); + lock(&trace).resume = true; + assert!(order.await.is_ok()); + assert_eq!(lock(&trace).bytes, [2, 3]); + assert!(endpoint.request_fault(Instant::now() + BUDGET).await); + assert_eq!(lock(&trace).bytes, [2, 3, 0, 0]); + } + + #[tokio::test] + async fn faults_wait_for_complete_orders_and_orders_wait_for_faults() { + let (writer, trace, endpoint, _active) = + setup_registered_writer([Step::Write(1), Step::Pending]); + let mut order = Box::pin(writer.write_order(BOARD, &[2, 3], BUDGET)); + pending_once(order.as_mut()).await; + let mut fault = Box::pin(endpoint.request_fault(Instant::now() + BUDGET)); + pending_once(fault.as_mut()).await; + lock(&trace).resume = true; + assert!(order.await.is_ok()); + assert!(fault.await); + assert_eq!(lock(&trace).bytes, [2, 3, 0, 0]); + + let (writer, trace, endpoint, _active) = + setup_registered_writer([Step::Write(1), Step::Pending]); + let mut fault = Box::pin(endpoint.request_fault(Instant::now() + BUDGET)); + pending_once(fault.as_mut()).await; + let mut order = Box::pin(writer.write_order(BOARD, &[2, 3], BUDGET)); + pending_once(order.as_mut()).await; + assert_eq!(lock(&trace).bytes, [0]); + lock(&trace).resume = true; + assert!(fault.await); + assert!(order.await.is_ok()); + assert_eq!(lock(&trace).bytes, [0, 0, 2, 3]); + } + + #[tokio::test] + async fn cancelling_a_partial_fault_closes_and_reports_the_session() { + let (writer, trace, endpoint, _active) = + setup_registered_writer([Step::Write(1), Step::Pending]); + let mut fault = Box::pin(endpoint.request_fault(Instant::now() + BUDGET)); + pending_once(fault.as_mut()).await; + drop(fault); + assert!(lock(&trace).dropped); + assert_eq!(lock(&trace).bytes, [0]); + assert_eq!( + writer.take_unreported_failure().map(|error| error.kind()), + Some(std::io::ErrorKind::Interrupted) + ); + assert!(!endpoint.request_fault(Instant::now() + BUDGET).await); + } + + #[tokio::test(start_paused = true)] + async fn offline_and_expired_faults_write_nothing() { + let endpoint = Endpoint::::default(); + assert!(!endpoint.request_fault(Instant::now() + BUDGET).await); + let (_writer, trace, endpoint, _active) = setup_registered_writer([]); + assert!(!endpoint.request_fault(Instant::now()).await); + assert_eq!(lock(&trace).calls, 0); + assert!(endpoint.request_fault(Instant::now() + BUDGET).await); + assert_eq!(lock(&trace).bytes, [0, 0]); + } +} diff --git a/backend/crates/core/src/net/tcp/error.rs b/backend/crates/core/src/net/tcp/error.rs new file mode 100644 index 000000000..74ec4537c --- /dev/null +++ b/backend/crates/core/src/net/tcp/error.rs @@ -0,0 +1,192 @@ +use crate::{ + model::{AdjId, BoardId}, + protocol::{DecodeError, EncodeError}, +}; + +/// Why an order could not be written. Failures before writing transmit no bytes; +/// write failures/timeouts may have transmitted a prefix or the entire frame. +/// Routing and encoding errors are returned only. Validated transport attempts +/// also produce [`TcpError::Send`] on the reporting channel. +#[derive(Debug, thiserror::Error)] +pub enum SendError { + /// The ID is absent from the index or is not an order. + #[error("no order is declared with id {0:?}")] + UnknownId(AdjId), + /// The destination has no configured TCP client. + #[error("board {0:?} has no configured TCP client")] + NoClient(BoardId), + /// The parameters cannot be represented by the protocol. No bytes were sent. + #[error("board {board:?}: could not encode order")] + Encode { + /// Destination board. + board: BoardId, + /// Original protocol error. + #[source] + source: EncodeError, + }, + /// No active session exists, or the selected session ended before completion. + #[error("board {0:?}: TCP session is disconnected")] + Disconnected(BoardId), + /// Waiting for the writer or writing exceeded write_timeout. + /// Expiry before writing leaves the session usable; expiry during writing closes it. + #[error("board {0:?}: TCP order write timed out")] + Timeout(BoardId), + /// Socket write failure. The session is closed and the order is never replayed. + #[error("board {board:?}: could not write order")] + Write { + /// Destination board. + board: BoardId, + /// Original I/O error, shared with the attempt's transport report. + #[source] + source: std::sync::Arc, + }, +} + +/// Boards whose fault-frame write completion could not be confirmed. +/// +/// Produced nonempty by a failed broadcast. Success confirms write_all, not +/// firmware execution; failure may still have transmitted some or all bytes. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("fault write completion was not confirmed for these boards: {0:?}")] +pub struct Unreachable(pub Vec); + +/// Something that went wrong on a board's TCP connection. +/// +/// Every variant names its board; send-attempt reports also identify the order. +/// One board has one active connection at a time. +/// [`crate::net::Error::Tcp`] wraps this type in a [`crate::net::ErrorReport`]. +#[derive(Debug, thiserror::Error)] +pub enum TcpError { + /// A validated order could not be sent. A timeout before writing does not + /// imply a disconnected session. + #[error("board {board:?}: order {order:?} could not be sent")] + Send { + /// Destination board resolved from the ADJ. + board: BoardId, + /// Order ID so the consumer can identify the rejected attempt. + order: AdjId, + /// NotConnected, TimedOut, or the underlying write failure. + #[source] + source: std::sync::Arc, + }, + /// The connection could not be opened. + #[error("board {board:?}: could not connect")] + Connect { + /// The board that was being connected to. + board: BoardId, + /// The underlying I/O failure. + #[source] + source: std::io::Error, + }, + + /// A socket read failed, or the peer closed in the middle of a frame. + #[error("board {board:?}: could not read")] + Read { + /// The board whose connection could not be read. + board: BoardId, + /// The underlying I/O failure, including an incomplete-frame EOF. + #[source] + source: std::io::Error, + }, + + /// The pending frame could not be decoded after exceeding the framing + /// limit. This can indicate an ADJ mismatch or malformed firmware output. + /// Classified as fatal for application policy: see [`TcpError::is_fatal`]. + #[error("board {board:?}: could not decode a frame")] + Decode { + /// The board whose frame failed. + board: BoardId, + /// What [`crate::protocol`] said about it. + #[source] + source: DecodeError, + }, + + /// An order, keep-alive or fault could not be written. + #[error("board {board:?}: could not write")] + Write { + /// The board that was being written to. + board: BoardId, + /// The underlying I/O failure, including `TimedOut` for an elapsed frame deadline. + #[source] + source: std::io::Error, + }, +} + +impl TcpError { + /// Whether this error is classified as fatal for the application's fault policy. + /// + /// Only [`TcpError::Decode`] qualifies. An undecodable suffix beyond the + /// framing limit can indicate an ADJ/firmware mismatch or malformed output; + /// the error alone does not establish its cause. The transport reports the + /// failure, closes the session and attempts to reconnect. Reconnecting alone + /// cannot repair an ADJ/firmware mismatch. + /// + /// This method only classifies the error: it neither broadcasts a fault nor + /// terminates the process. The application consumes the error report and + /// decides whether to call [`super::BoardClients::broadcast_fault`]. The Go + /// backend called `SendFault()` directly when `DecodeNext` returned an error, + /// including read failures; this module leaves that reaction to the caller. + /// + /// [`TcpError::Connect`], [`TcpError::Read`], [`TcpError::Write`] and + /// [`TcpError::Send`] return false. Connection and session failures use the + /// reconnection path; a send timeout while waiting for the writer can leave + /// the session usable. EOF within a partial frame is a read failure, not + /// proof of an ADJ mismatch. `Disconnected` reports a session ending, not a + /// determination that a board is permanently unavailable. + pub fn is_fatal(&self) -> bool { + match self { + TcpError::Decode { .. } => true, + TcpError::Connect { .. } + | TcpError::Read { .. } + | TcpError::Write { .. } + | TcpError::Send { .. } => false, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn io_error() -> std::io::Error { + std::io::Error::from(std::io::ErrorKind::ConnectionRefused) + } + + #[test] + fn a_frame_that_will_not_decode_faults_the_pod() { + let error = TcpError::Decode { + board: BoardId(3), + source: DecodeError::UnknownId(crate::model::AdjId(9999)), + }; + + // Classification is available to application policy without sending a fault. + assert!(error.is_fatal()); + } + + #[test] + fn a_board_that_is_not_up_yet_does_not_fault_the_pod() { + let connect = TcpError::Connect { + board: BoardId(3), + source: io_error(), + }; + let write = TcpError::Write { + board: BoardId(3), + source: io_error(), + }; + + // That is what the reconnection backoff is for. + assert!(!connect.is_fatal()); + assert!(!write.is_fatal()); + } + + #[test] + fn an_error_says_which_board_it_was() { + let error = TcpError::Write { + board: BoardId(3), + source: io_error(), + }; + + // The identity survives being formatted, which is what reaches + // the operator. + assert!(error.to_string().contains("BoardId(3)")); + } +} diff --git a/backend/crates/core/src/net/tcp/framing.rs b/backend/crates/core/src/net/tcp/framing.rs new file mode 100644 index 000000000..f16d9488e --- /dev/null +++ b/backend/crates/core/src/net/tcp/framing.rs @@ -0,0 +1,252 @@ +//! Transactional frame extraction from one TCP session's accumulated bytes. + +use crate::protocol::{ + DecodeError, Index, + tcp::{self, TcpFrame}, +}; +use bytes::{Buf, BytesMut}; +use std::io::Cursor; + +/// Extracts one complete frame, advancing `pending` only after a successful decode. +/// +/// Append incoming bytes with `BytesMut::extend_from_slice`, then call this +/// repeatedly until it returns `Ok(None)`. That result means the buffer is empty +/// or decoding has been deferred until more bytes arrive; it does not prove the +/// suffix is valid. Each connection session must own its own buffer; never carry +/// pending bytes into a reconnected session. +/// +/// All decode errors are deferred while the pending suffix is at most 374 bytes, +/// assuming well-formed firmware output. The limit is checked after decoding: +/// a larger buffer may contain many valid frames that must be extracted first. +/// +/// # Errors +/// +/// Returns the decoder's error if no frame can be extracted and more than 374 +/// bytes remain. The buffer stays unchanged; the socket owner must discard the +/// session and reconnect rather than try to resynchronise within the stream. +pub(super) fn next_frame( + pending: &mut BytesMut, + index: &Index, +) -> Result, DecodeError> { + // Largest supported inbound frame: message ID + timestamp + origin + text. + const MAX_FRAME_LEN: usize = 374; + + if pending.is_empty() { + return Ok(None); + } + + let mut cursor = Cursor::new(&pending[..]); + match tcp::decode_next(&mut cursor, index) { + Ok(frame) => { + let consumed = cursor.position() as usize; + pending.advance(consumed); + Ok(Some(frame)) + } + // Defer even definite decode errors until the undecodable suffix exceeds the limit. + Err(error) if pending.len() > MAX_FRAME_LEN => Err(error), + Err(_) => Ok(None), + } +} + +#[cfg(test)] +mod tests { + use super::super::test_support::inbound_frames as sample_frames; + use super::*; + use crate::{ + model::{AdjId, MessagePacket, ShortTimestamp}, + protocol::packet::message, + }; + + #[test] + fn an_empty_buffer_needs_more_bytes() { + let mut pending = BytesMut::new(); + assert_eq!(next_frame(&mut pending, &Index::default()), Ok(None)); + assert!(pending.is_empty()); + } + + #[test] + fn extracts_mixed_frames_with_adj_dependent_lengths() { + let (index, frames) = sample_frames(); + assert_eq!(frames[0].1.len(), 9); + assert_eq!(frames[2].1.len(), 16); + let mut pending = BytesMut::new(); + for (_, bytes) in &frames { + pending.extend_from_slice(bytes); + } + + for (frame, bytes) in &frames { + let before = pending.len(); + assert_eq!(next_frame(&mut pending, &index), Ok(Some(frame.clone()))); + assert_eq!(pending.len(), before - bytes.len()); + } + assert_eq!(next_frame(&mut pending, &index), Ok(None)); + assert!(pending.is_empty()); + } + + #[test] + fn preserves_every_partial_frame_until_its_remaining_bytes_arrive() { + let (index, frames) = sample_frames(); + for (frame, bytes) in &frames { + for split in 0..bytes.len() { + let mut pending = BytesMut::from(&bytes[..split]); + assert_eq!(next_frame(&mut pending, &index), Ok(None)); + assert_eq!(&pending[..], &bytes[..split]); + + pending.extend_from_slice(&bytes[split..]); + assert_eq!(next_frame(&mut pending, &index), Ok(Some(frame.clone()))); + assert!(pending.is_empty()); + } + } + } + + #[test] + fn extracts_a_mixed_stream_received_one_byte_at_a_time() -> Result<(), DecodeError> { + let (index, frames) = sample_frames(); + let mut pending = BytesMut::new(); + let mut received = Vec::new(); + for (_, bytes) in &frames { + for byte in bytes { + pending.extend_from_slice(&[*byte]); + while let Some(frame) = next_frame(&mut pending, &index)? { + received.push(frame); + } + } + } + + let expected: Vec<_> = frames.into_iter().map(|(frame, _)| frame).collect(); + assert_eq!(received, expected); + assert!(pending.is_empty()); + Ok(()) + } + + #[test] + fn extracts_a_complete_frame_and_keeps_the_next_partial_frame() { + let (index, frames) = sample_frames(); + let (first, first_bytes) = &frames[0]; + let (second, second_bytes) = &frames[1]; + let split = second_bytes.len() - 1; + let mut pending = BytesMut::from(&first_bytes[..]); + pending.extend_from_slice(&second_bytes[..split]); + + assert_eq!(next_frame(&mut pending, &index), Ok(Some(first.clone()))); + assert_eq!(next_frame(&mut pending, &index), Ok(None)); + assert_eq!(&pending[..], &second_bytes[..split]); + + pending.extend_from_slice(&second_bytes[split..]); + assert_eq!(next_frame(&mut pending, &index), Ok(Some(second.clone()))); + assert!(pending.is_empty()); + } + + #[test] + fn defers_non_eof_errors_until_the_pending_suffix_exceeds_the_limit() { + let (index, _) = sample_frames(); + let mut invalid_utf8 = AdjId(10).0.to_le_bytes().to_vec(); + invalid_utf8.extend([0, 0, 0, 0, 0xff, 0, 0]); + let mut unterminated = AdjId(10).0.to_le_bytes().to_vec(); + unterminated.extend([0; 4]); + unterminated.extend([b'x'; 48]); + + for (bytes, expected_error) in [ + (vec![0xff, 0xff], DecodeError::UnknownId(AdjId(u16::MAX))), + (invalid_utf8, DecodeError::InvalidUtf8(vec![0xff])), + (unterminated, DecodeError::UnterminatedString { max: 48 }), + ] { + let mut pending = BytesMut::from(&bytes[..]); + assert_eq!(next_frame(&mut pending, &index), Ok(None)); + assert_eq!(&pending[..], &bytes); + + pending.resize(374, 0); + let before = pending.clone(); + assert_eq!(next_frame(&mut pending, &index), Ok(None)); + assert_eq!(pending, before); + + pending.extend_from_slice(&[0]); + let before = pending.clone(); + assert_eq!(next_frame(&mut pending, &index), Err(expected_error)); + assert_eq!(pending, before); + } + } + + #[test] + fn accepts_a_maximum_length_message_once_its_last_byte_arrives() { + let (index, _) = sample_frames(); + let packet = MessagePacket { + id: AdjId(10), + timestamp: ShortTimestamp { + hour: 0, + minute: 0, + second: 0, + subsecond: 0, + }, + origin: "o".repeat(47), + message: "m".repeat(319), + }; + let Ok(bytes) = message::encode(&packet, &index) else { + unreachable!("both strings fit their wire limits including NUL"); + }; + assert_eq!(bytes.len(), 374); + let mut pending = BytesMut::from(&bytes[..373]); + assert_eq!(next_frame(&mut pending, &index), Ok(None)); + assert_eq!(&pending[..], &bytes[..373]); + + pending.extend_from_slice(&bytes[373..]); + assert_eq!( + next_frame(&mut pending, &index), + Ok(Some(TcpFrame::Message(packet))) + ); + assert!(pending.is_empty()); + } + + #[test] + fn drains_a_valid_burst_larger_than_the_frame_limit() { + let (index, frames) = sample_frames(); + let mut pending = BytesMut::new(); + for _ in 0..32 { + for (_, bytes) in &frames { + pending.extend_from_slice(bytes); + } + } + assert!(pending.len() > 374); + + for _ in 0..32 { + for (frame, _) in &frames { + assert_eq!(next_frame(&mut pending, &index), Ok(Some(frame.clone()))); + } + } + assert_eq!(next_frame(&mut pending, &index), Ok(None)); + assert!(pending.is_empty()); + } + + #[test] + fn delivers_valid_frames_before_rejecting_an_oversized_invalid_suffix() { + let (index, frames) = sample_frames(); + let (frame, bytes) = &frames[0]; + let mut pending = BytesMut::from(&bytes[..]); + let invalid = vec![0xff; 375]; + pending.extend_from_slice(&invalid); + + assert_eq!(next_frame(&mut pending, &index), Ok(Some(frame.clone()))); + assert_eq!( + next_frame(&mut pending, &index), + Err(DecodeError::UnknownId(AdjId(u16::MAX))) + ); + assert_eq!(&pending[..], &invalid); + } + + #[test] + fn independent_buffers_do_not_share_partial_frames() { + let (index, frames) = sample_frames(); + let (frame, bytes) = &frames[0]; + let mut first = BytesMut::from(&bytes[..3]); + let mut second = BytesMut::from(&bytes[..]); + + assert_eq!(next_frame(&mut first, &index), Ok(None)); + assert_eq!(next_frame(&mut second, &index), Ok(Some(frame.clone()))); + assert!(second.is_empty()); + assert_eq!(&first[..], &bytes[..3]); + + first.extend_from_slice(&bytes[3..]); + assert_eq!(next_frame(&mut first, &index), Ok(Some(frame.clone()))); + assert!(first.is_empty()); + } +} diff --git a/backend/crates/core/src/net/tcp/keep_alive.rs b/backend/crates/core/src/net/tcp/keep_alive.rs new file mode 100644 index 000000000..3e33745cc --- /dev/null +++ b/backend/crates/core/src/net/tcp/keep_alive.rs @@ -0,0 +1,136 @@ +//! Periodic keep-alive writes through the same writer as orders and faults. +use super::writer::SessionWriter; +use std::time::Duration; +use tokio::{ + io::AsyncWrite, + time::{Instant, sleep}, +}; + +#[derive(Debug, Clone, Copy)] +pub(super) struct Settings { + pub(super) write_timeout: Duration, + pub(super) keep_alive: Duration, +} + +const KEEP_ALIVE_FRAME: [u8; 2] = [1, 0]; + +/// Wait one period after each heartbeat; never accumulate overdue sends. +/// Faults are written directly through the session writer, without a control queue. +pub(super) async fn run_keep_alive( + writer: &SessionWriter, + settings: Settings, +) { + if settings.keep_alive.is_zero() { + writer.closed().await; + return; + } + loop { + tokio::select! { + biased; + () = writer.closed() => return, + () = sleep(settings.keep_alive) => {}, + } + let deadline = Instant::now() + settings.write_timeout; + tracing::trace!(writer = ?std::ptr::from_ref(writer), "Attempting TCP keep-alive write"); + let result = writer.write_control(&KEEP_ALIVE_FRAME, deadline).await; + tracing::trace!(writer = ?std::ptr::from_ref(writer), ?result, + "TCP keep-alive write attempt finished"); + // An expired mutex wait skips this heartbeat; an incomplete write closes the session. + if result.is_err() && writer.is_closed() { + return; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::net::tcp::{ + test_support::writes::*, + writer::{FrameError, lock}, + }; + use tokio::time::advance; + + #[tokio::test(start_paused = true)] + async fn heartbeat_waits_one_period_and_rearms_without_catchup() { + let (writer, trace) = setup([]); + let mut keep_alive = Box::pin(run_keep_alive(&writer, keep_alive_settings(BUDGET))); + pending_once(keep_alive.as_mut()).await; + assert!(lock(&trace).bytes.is_empty()); + assert!(writer.write_order(BOARD, &[2, 3], BUDGET).await.is_ok()); + advance(BUDGET * 3).await; + pending_once(keep_alive.as_mut()).await; + assert_eq!(lock(&trace).bytes, [2, 3, 1, 0]); + pending_once(keep_alive.as_mut()).await; + assert_eq!(lock(&trace).bytes, [2, 3, 1, 0]); + advance(BUDGET).await; + pending_once(keep_alive.as_mut()).await; + assert_eq!(lock(&trace).bytes, [2, 3, 1, 0, 1, 0]); + } + + #[tokio::test(start_paused = true)] + async fn orders_wait_for_a_partial_heartbeat_without_interleaving() { + let (writer, trace) = setup([Step::Write(1), Step::Pending]); + let mut keep_alive = Box::pin(run_keep_alive( + &writer, + Settings { + write_timeout: BUDGET * 3, + keep_alive: BUDGET, + }, + )); + pending_once(keep_alive.as_mut()).await; + advance(BUDGET).await; + pending_once(keep_alive.as_mut()).await; + assert_eq!(lock(&trace).bytes, [1]); + let mut order = Box::pin(writer.write_order(BOARD, &[2, 3], BUDGET * 3)); + pending_once(order.as_mut()).await; + lock(&trace).resume = true; + pending_once(keep_alive.as_mut()).await; + assert!(order.await.is_ok()); + assert_eq!(lock(&trace).bytes, [1, 0, 2, 3]); + advance(BUDGET).await; + pending_once(keep_alive.as_mut()).await; + assert_eq!(lock(&trace).bytes, [1, 0, 2, 3, 1, 0]); + } + + #[tokio::test(start_paused = true)] + async fn heartbeat_wait_timeout_leaves_the_active_order_untouched() { + let (writer, trace) = setup([Step::Write(1), Step::Pending]); + let mut order = Box::pin(writer.write_order(BOARD, &[2, 3], BUDGET * 4)); + pending_once(order.as_mut()).await; + let mut keep_alive = Box::pin(run_keep_alive(&writer, keep_alive_settings(BUDGET))); + pending_once(keep_alive.as_mut()).await; + advance(BUDGET).await; + pending_once(keep_alive.as_mut()).await; + advance(BUDGET).await; + pending_once(keep_alive.as_mut()).await; + assert!(!lock(&trace).dropped); + lock(&trace).resume = true; + assert!(order.await.is_ok()); + assert_eq!(lock(&trace).bytes, [2, 3]); + } + + #[tokio::test(start_paused = true)] + async fn partial_control_timeout_closes_and_reports_the_session() { + let (writer, trace) = setup([Step::Write(1), Step::Pending]); + assert!(matches!( + writer.write_control(&[1, 0], Instant::now() + BUDGET).await, + Err(FrameError::Timeout) + )); + assert!(writer.take_unreported_failure().is_some()); + assert!(lock(&trace).dropped); + assert_eq!(lock(&trace).bytes, [1]); + } + + #[tokio::test(start_paused = true)] + async fn disabled_heartbeat_writes_nothing_and_stops_on_session_close() { + let (writer, trace) = setup([]); + let mut keep_alive = Box::pin(run_keep_alive(&writer, keep_alive_settings(Duration::ZERO))); + pending_once(keep_alive.as_mut()).await; + advance(BUDGET * 10).await; + pending_once(keep_alive.as_mut()).await; + assert!(lock(&trace).bytes.is_empty()); + writer.close(); + keep_alive.await; + } +} diff --git a/backend/crates/core/src/net/tcp/manual_tests.rs b/backend/crates/core/src/net/tcp/manual_tests.rs new file mode 100644 index 000000000..3fd235c36 --- /dev/null +++ b/backend/crates/core/src/net/tcp/manual_tests.rs @@ -0,0 +1,361 @@ +use super::*; +use crate::model::{AdjId, OrderPacket, Value}; +use crate::net::{Notification, Sinks}; +use std::{io, path::Path}; + +struct ProbeConfig { + board_name: String, + link: BoardLink, + index: Arc, + config: TcpConfig, +} + +fn load_probe_config() -> Result> { + let adj_path = std::env::var_os("ADJ_DIR").ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + "set ADJ_DIR to the matching ADJ directory", + ) + })?; + let board_name = std::env::var("TCP_BOARD")?; + let local_port = Port(match std::env::var("TCP_LOCAL_PORT") { + Ok(value) => value.parse::()?, + Err(std::env::VarError::NotPresent) => 0, + Err(error) => return Err(error.into()), + }); + let keep_alive_ms = match std::env::var("TCP_KEEP_ALIVE_MS") { + Ok(value) => value.parse::()?, + Err(std::env::VarError::NotPresent) => 1000, + Err(error) => return Err(error.into()), + }; + let adj = crate::adj::load_from_dir(Path::new(&adj_path))?; + let board = adj + .pod_data + .boards + .values() + .find(|board| board.name == board_name) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("board {board_name:?} is not declared in the supplied ADJ"), + ) + })?; + let port = adj.info.ports.get("TCP_SERVER").ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + "the supplied ADJ has no TCP_SERVER port", + ) + })?; + let link = BoardLink { + board: board.id, + addr: SocketAddr::new(board.ip, port.0), + local_port, + }; + let index = Arc::new(Index::new(&adj.pod_data, Some(&adj.info.message_levels))); + let config = TcpConfig { + boards: vec![link], + connect_timeout: Duration::from_secs(5), + backoff: Backoff::new(500, 5000), + write_timeout: Duration::from_secs(2), + keep_alive: Duration::from_millis(keep_alive_ms), + }; + Ok(ProbeConfig { + board_name, + link, + index, + config, + }) +} + +fn start_probe(probe: ProbeConfig) -> (BoardClients, Sinks) { + let (reporter, sinks) = Reporter::channels(256, 16); + let handles = spawn(probe.config, probe.index, reporter); + (handles, sinks) +} + +/// Drains both channels concurrently; the hook must not block reporting. +async fn display_reports(sinks: &mut Sinks, mut on_notification: impl FnMut(&Notification)) { + tokio::join!( + async { + while let Some(notification) = sinks.notifications.recv().await { + println!("{notification:#?}"); + on_notification(¬ification); + } + }, + async { + while let Some(report) = sinks.errors.recv().await { + eprintln!("{report:#?}"); + } + }, + ); +} + +fn stop_probe(handles: BoardClients, sinks: &mut Sinks) { + // Consumer closure asks detached supervisors to stop, without joining them. + sinks.notifications.close(); + sinks.errors.close(); + drop(handles); +} + +#[tokio::test] +#[ignore = "manual test: start the documented nc listener on 127.0.0.1:50500 first"] +// THIS TEST IS SPECIAL: +// +// To try it, you need two terminals. Run these commands in this order, +// one in each terminal: +// 1. `{ +// printf '\x03\x00\x0c\x1e\x00\x00nc\x00One\x00' +// printf '\x03\x00\x0c\x1e\x00\x00nc\x00Two\x00' +// printf '\x03\x00\x0c\x1e\x00\x00n' +// sleep 3 +// printf 'c\x00Three\x00' +// } | nc -lN 127.0.0.1 50500` +// 2. `cargo test -p software-core -F net manual_tcp_receive -- --ignored --nocapture` +// +// The first two frames are sent whole. The third frame is split across two +// writes with a three-second delay. TCP may split or combine reads differently; +// the framing code must not depend on write/read boundaries matching. +// The test prints each complete frame, then finishes when nc closes the connection. +// +// This test checks connection, framing and reporting by displaying notifications. +// Initial connection failures use 500..5000 ms exponential backoff and are printed +// while retrying. The 30-second overall deadline covers connection and receiving. +async fn manual_tcp_receive() -> Result<(), Box> { + // Load the fixture ADJ so the real protocol decoder can resolve message ID 3. + let adj_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/adj/test/adj"); + let adj = crate::adj::load_from_dir(&adj_path)?; + let index = Arc::new(Index::new(&adj.pod_data, Some(&adj.info.message_levels))); + let addr = "127.0.0.1:50500".parse()?; + let link = BoardLink { + board: BoardId(1), + addr, + local_port: Port(0), + }; + + let (reporter, mut sinks) = Reporter::channels(1, 1); + let receiving = async { + let result = async { + // The probe uses the same retrying entry point as the supervisor. + // Its overall test deadline also covers connection attempts/backoff. + let mut backoff = Backoff::new(500, 5000); + let stream = + connection::connect(&link, Duration::from_secs(5), &mut backoff, &reporter).await?; + let (read_half, _write_half) = stream.into_split(); + Ok::<_, Box>( + reader::receive(read_half, link.board, &index, &reporter).await?, + ) + } + .await; + // Drop both report senders after connection/reading ends so consumers drain. + drop(reporter); + result + }; + let displaying = async { + let (frames, ()) = tokio::join!( + async { + let mut frames = 0; + while let Some(notification) = sinks.notifications.recv().await { + println!("Received notification: {notification:?}"); + frames += 1; + } + frames + }, + async { + // A one-slot error channel must not park connection retries. + while let Some(report) = sinks.errors.recv().await { + eprintln!("Connection error: {report:?}"); + } + }, + ); + frames + }; + + // Drain concurrently to respect backpressure; only the manual test has a deadline. + let (end, frames) = tokio::time::timeout(Duration::from_secs(30), async { + tokio::join!(receiving, displaying) + }) + .await?; + assert_eq!(end?, reader::ReceiveEnd::PeerClosed); + assert!( + frames > 0, + "the peer closed without sending a complete frame" + ); + Ok(()) +} + +/// Preserves station's original supervised probe, now driven through spawn/BoardClients. +/// +/// From backend/, with the ADJ matching the selected firmware: +/// ```text +/// ADJ_DIR=/path/to/adj TCP_BOARD=TEST \ +/// cargo test -p software-core --features net manual_tcp_supervisor -- --ignored --nocapture +/// ``` +/// Optional TCP_LOCAL_PORT defaults to 0; TCP_KEEP_ALIVE_MS defaults to 1000 +/// (zero disables keep-alive). The board IP and TCP_SERVER port come from ADJ. +/// For a local simulator, use a private ADJ copy with the board IP 127.0.0.1 +/// and start `nc -l 50500 | od -An -tx1 -v -w2` if TCP_SERVER is 50500. +/// +/// WARNING: this test sends order 1001 with numeric parameter -5.0 once. Use only +/// the intended TEST board/firmware or simulator, not an arbitrary real board. +/// For a float32 parameter, its bytes are e9 03 00 00 a0 c0; keep-alive is 01 00. +/// Closing and reopening the simulator should reconnect without repeating the +/// order. Backoff grows from 500 to 5000 ms on failures and resets on success. +/// +/// Prints both Reporter channels until Ctrl+C, without a test-only read timeout. +/// Ctrl+C closes the consumers; task joining and guaranteed final-event draining +/// are not implemented. The existing manual_tcp_receive test remains unchanged. +#[tokio::test] +#[ignore = "manual probe: requires ADJ_DIR, TCP_BOARD and a real board or simulator; sends order 1001"] +async fn manual_tcp_supervisor() -> Result<(), Box> { + let probe = load_probe_config()?; + println!( + "Manual TCP probe: {} at {}; order 1001(-5.0) once after Connected; press Ctrl+C to stop", + probe.board_name, probe.link.addr + ); + let (handles, mut sinks) = start_probe(probe); + let running = async { + let mut sent = false; + loop { + tokio::select! { + result = tokio::signal::ctrl_c() => { result?; return Ok::<_, Box>(()); } + notification = sinks.notifications.recv() => { + let notification = notification.ok_or("TCP notifications stopped")?; + println!("{notification:#?}"); + if !sent && matches!(notification.event, crate::net::Event::Connected) { + // Even this send can time out or return Disconnected if a + // heartbeat/fault/session teardown races the event. + // Never retry a hardware order automatically. + sent = true; + let sending = handles.send(OrderPacket::new(AdjId(1001), vec![Value::Number(-5.0)])); + tokio::pin!(sending); + loop { + tokio::select! { + result = &mut sending => { result?; break; } + report = sinks.errors.recv() => println!("{:#?}", report.ok_or("TCP errors stopped")?), + notification = sinks.notifications.recv() => println!("{:#?}", notification.ok_or("TCP notifications stopped")?), + result = tokio::signal::ctrl_c() => { result?; return Ok(()); } + } + } + } + } + report = sinks.errors.recv() => println!("{:#?}", report.ok_or("TCP errors stopped")?), + } + } + }; + let result = running.await; + stop_probe(handles, &mut sinks); + result +} + +/// Runs the current station main probe through the public multi-board `spawn` API. +/// +/// From backend/, with an ADJ matching the selected firmware: +/// ```text +/// ADJ_DIR=/path/to/adj TCP_BOARD=TEST \ +/// cargo test -p software-core --features net manual_tcp_spawn -- --ignored --nocapture +/// ``` +/// Optional TCP_LOCAL_PORT defaults to 0; TCP_KEEP_ALIVE_MS defaults to 1000 +/// (zero disables keep-alive). The selected board IP and TCP_SERVER port come +/// from the supplied ADJ. This probe sends no orders; it prints both Reporter +/// channels until Ctrl+C and exercises spawn, connect, receive and reconnect. +/// For a loopback simulator, use a private ADJ copy with the board IP set to +/// 127.0.0.1 and observe the configured port, e.g. `nc -l 50500`. +/// +/// Ctrl+C closes the reporting consumers and drops BoardClients. There is not yet an +/// explicit task join, so this is a manual probe rather than a shutdown test. +#[tokio::test] +#[ignore = "manual spawn probe: requires ADJ_DIR, TCP_BOARD and a real board or simulator"] +async fn manual_tcp_spawn() -> Result<(), Box> { + let probe = load_probe_config()?; + println!( + "Manual TCP spawn probe: {} at {}; no orders; press Ctrl+C to stop", + probe.board_name, probe.link.addr + ); + let (handles, mut sinks) = start_probe(probe); + let running = tokio::signal::ctrl_c(); + let result = tokio::select! { + stopped = running => stopped, + () = display_reports(&mut sinks, |_| {}) => Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "TCP reporting stopped before Ctrl+C", + )), + }; + stop_probe(handles, &mut sinks); + result?; + Ok(()) +} + +/// Sends one real fault through spawn/BoardClients after the first connection. +/// +/// WARNING: this actively requests a firmware fault. Use only a safe test +/// setup or simulator. From backend/: +/// ```text +/// ADJ_DIR=/path/to/adj TCP_BOARD=TEST \ +/// cargo test -p software-core --features net manual_tcp_fault -- --ignored --nocapture +/// ``` +/// TCP_LOCAL_PORT defaults to 0 and TCP_KEEP_ALIVE_MS to 1000; zero disables +/// keep-alive. The board IP and TCP_SERVER port come from the supplied ADJ. +/// With a private loopback ADJ and port 50500, observe the fault bytes `00 00` +/// using `nc -l 50500 | od -An -tx1 -v -w2`; keep-alive bytes are `01 00`. +/// +/// Both Reporter channels are consumed while waiting, writing and observing +/// firmware afterwards. Success only confirms write_all, not firmware receipt +/// or execution: verify the board's fault state separately. A failed broadcast +/// fails the test. No normal order, hash, automatic retry of the fault, or +/// second fault after reconnection is sent. Ctrl+C stops the probe even before +/// connection; closing consumers cancels supervisors without explicit joining. +#[tokio::test] +#[ignore = "manual fault probe: sends a REAL fault; requires ADJ_DIR, TCP_BOARD and a safe board or simulator"] +async fn manual_tcp_fault() -> Result<(), Box> { + use crate::net::Event; + use tokio::sync::oneshot; + + let probe = load_probe_config()?; + println!( + "WARNING: manual TCP fault probe: {} at {}; sends 00 00 once after connecting; press Ctrl+C to stop", + probe.board_name, probe.link.addr + ); + let board = probe.link.board; + let (handles, mut sinks) = start_probe(probe); + let (connected, first_connection) = oneshot::channel(); + let running = async { + // Wait outside the display loops so neither reporting channel is + // blocked while waiting for or writing the fault frame. + first_connection.await.map_err(|_| { + io::Error::new( + io::ErrorKind::BrokenPipe, + "reporting stopped before connection", + ) + })?; + println!("First connection established; requesting fault once"); + if let Err(error) = handles.broadcast_fault().await { + eprintln!("Fault write NOT confirmed: {error}"); + return Err(error.into()); + } + println!( + "Fault write confirmed; NOT a firmware ACK. Verify the board's fault state; press Ctrl+C to stop" + ); + // Keep the same handles and consumers alive for observation, without + // creating another fault request when the supervisor reconnects. + std::future::pending::>>().await + }; + let mut connected = Some(connected); + let on_notification = |notification: &Notification| { + let ready = notification.board == board && matches!(¬ification.event, Event::Connected); + // Taking the sender makes the trigger one-shot across all subsequent + // Connected events, including reconnections. + if ready && let Some(connected) = connected.take() { + let _ = connected.send(()); + } + }; + let result = tokio::select! { + result = running => result, + stopped = tokio::signal::ctrl_c() => stopped.map_err(Into::into), + () = display_reports(&mut sinks, on_notification) => Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "TCP reporting stopped before Ctrl+C", + ).into()), + }; + stop_probe(handles, &mut sinks); + result +} diff --git a/backend/crates/core/src/net/tcp/reader.rs b/backend/crates/core/src/net/tcp/reader.rs new file mode 100644 index 000000000..ad9aaa76c --- /dev/null +++ b/backend/crates/core/src/net/tcp/reader.rs @@ -0,0 +1,436 @@ +//! Reading and reporting ordinary frames from one established TCP session. + +use super::{TcpError, framing}; +use crate::{ + model::{BoardId, Packet}, + net::{Event, Reporter}, + protocol::{Index, tcp::TcpFrame}, +}; +use bytes::BytesMut; +use std::io; +use tokio::{io::AsyncReadExt, net::tcp::OwnedReadHalf}; + +/// Why a session reader stopped without a transport error. +#[derive(Debug, PartialEq, Eq)] +pub(super) enum ReceiveEnd { + /// The peer closed its write side at a frame boundary. + PeerClosed, + /// Publishing a frame failed because the notification consumer is gone. + /// The owner must stop rather than reconnect to an absent consumer. + ConsumerClosed, +} + +/// Reads ordinary frames and publishes each one through `reporter` in order. +/// +/// The read half must be ready for ordinary message/protection frames; this +/// reader performs no handshake. Its buffer is never reused across +/// sessions. The connection supplies board identity, including for global +/// message IDs whose index definitions do not belong to a real board. +/// +/// A full notification channel applies backpressure instead of dropping frames. +/// Consumer closure is detected when publishing, not while an idle socket read +/// is pending. There is no read timeout: silence is not a protocol violation. +/// Cancelling this future discards its buffered bytes and any packet still +/// waiting for notification capacity; already queued notifications are retained. +/// +/// Only `Received` notifications are emitted. The session owner handles logging, +/// error reporting, connection events and disposal of both socket halves. This +/// function does not reconnect, write orders or decide to fault the pod. +/// +/// # Errors +/// +/// Returns [`TcpError::Read`] for socket failures or EOF in a partial frame, and +/// [`TcpError::Decode`] for a terminal framing error. Completed preceding frames +/// have already been published. The read half is dropped when the function ends. +pub(super) async fn receive( + mut reader: OwnedReadHalf, + board: BoardId, + index: &Index, + reporter: &Reporter, +) -> Result { + // Retain incomplete frame bytes between socket reads. + let mut pending = BytesMut::new(); + // Per-read buffer size, independent of stream length and frame boundaries. + let mut chunk = [0; 1024]; + + loop { + let read = reader + .read(&mut chunk) + .await + .map_err(|source| TcpError::Read { board, source })?; + + if read == 0 { + return if pending.is_empty() { + Ok(ReceiveEnd::PeerClosed) + } else { + Err(TcpError::Read { + board, + source: io::Error::new( + io::ErrorKind::UnexpectedEof, + "peer closed with an incomplete TCP frame", + ), + }) + }; + } + + pending.extend_from_slice(&chunk[..read]); + tracing::trace!( + ?board, + bytes_read = read, + buffered_bytes = pending.len(), + "TCP socket read completed" + ); + while let Some(frame) = framing::next_frame(&mut pending, index) + .map_err(|source| TcpError::Decode { board, source })? + { + let (packet_id, packet) = match frame { + TcpFrame::Message(message) => (message.id, Packet::Message(message)), + TcpFrame::Protection(protection) => (protection.id, Packet::Protection(protection)), + }; + tracing::trace!( + ?board, + ?packet_id, + buffered_bytes = pending.len(), + "TCP frame decoded" + ); + + if reporter + .notify(board, Event::Received(packet)) + .await + .is_err() + { + return Ok(ReceiveEnd::ConsumerClosed); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::super::test_support::{TestResult, inbound_frames, socket_pair}; + use super::*; + use crate::{model::AdjId, protocol::DecodeError}; + use std::{ + future::{Future, poll_fn}, + task::Poll, + time::Duration, + }; + use tokio::{ + io::AsyncWriteExt, + net::{TcpStream, tcp::OwnedWriteHalf}, + time::timeout, + }; + + const TEST_TIMEOUT: Duration = Duration::from_secs(2); + + fn sample_frames() -> (Index, Vec<(Packet, Vec)>) { + let (index, frames) = inbound_frames(); + // Message first, then a boolean protection: preserve the reader tests' + // complete-prefix/partial-suffix setup while sharing the codec fixture. + let frames = frames + .into_iter() + .take(2) + .rev() + .map(|(frame, bytes)| { + let packet = match frame { + TcpFrame::Message(packet) => Packet::Message(packet), + TcpFrame::Protection(packet) => Packet::Protection(packet), + }; + (packet, bytes) + }) + .collect(); + (index, frames) + } + + async fn connected_pair() -> TestResult<(OwnedReadHalf, OwnedWriteHalf, TcpStream)> { + let (client, peer) = socket_pair(TEST_TIMEOUT).await?; + let (reader, writer) = client.into_split(); + Ok((reader, writer, peer)) + } + + #[tokio::test] + async fn reports_a_mixed_burst_in_order_with_the_connection_board() -> TestResult { + let (index, frames) = sample_frames(); + let (reader, _writer, mut peer) = connected_pair().await?; + let (reporter, mut sinks) = Reporter::channels(1, 1); + let mut bytes = Vec::new(); + for _ in 0..64 { + for (_, encoded) in &frames { + bytes.extend_from_slice(encoded); + } + } + assert!(bytes.len() > 1024); + + // Consume concurrently: a one-slot channel must not stall the whole test. + let (sent, received, ()) = timeout(TEST_TIMEOUT, async { + tokio::join!( + async { + peer.write_all(&bytes).await?; + peer.shutdown().await + }, + receive(reader, BoardId(42), &index, &reporter), + async { + for _ in 0..64 { + for (expected, _) in &frames { + let Some(notification) = sinks.notifications.recv().await else { + unreachable!("the reporter remains alive while receiving"); + }; + assert_eq!(notification.board, BoardId(42)); + let Event::Received(packet) = notification.event else { + unreachable!("the reader emits only Received notifications"); + }; + assert_eq!(&packet, expected); + } + } + } + ) + }) + .await?; + sent?; + assert_eq!(received?, ReceiveEnd::PeerClosed); + assert!(sinks.notifications.try_recv().is_err()); + assert!(sinks.errors.try_recv().is_err()); + Ok(()) + } + + #[tokio::test] + async fn waits_for_more_bytes_without_publishing_a_partial_frame() -> TestResult { + let (index, frames) = sample_frames(); + let (mut reader, _writer, mut peer) = connected_pair().await?; + let (reporter, mut sinks) = Reporter::channels(1, 1); + let (expected, bytes) = &frames[0]; + + // Make a prefix readable before polling the reader, then keep the peer open. + peer.write_all(&bytes[..7]).await?; + timeout(TEST_TIMEOUT, reader.peek(&mut [0; 1])).await??; + let reading = receive(reader, BoardId(42), &index, &reporter); + tokio::pin!(reading); + poll_fn(|cx| { + assert!(reading.as_mut().poll(cx).is_pending()); + Poll::Ready(()) + }) + .await; + assert!(sinks.notifications.try_recv().is_err()); + + // Completing the frame and closing the write side must produce exactly one packet. + peer.write_all(&bytes[7..]).await?; + peer.shutdown().await?; + assert_eq!( + timeout(TEST_TIMEOUT, reading).await??, + ReceiveEnd::PeerClosed + ); + let Ok(notification) = sinks.notifications.try_recv() else { + unreachable!("the completed frame was published"); + }; + let Event::Received(packet) = notification.event else { + unreachable!("the reader emits only Received notifications"); + }; + assert_eq!(&packet, expected); + assert!(sinks.notifications.try_recv().is_err()); + Ok(()) + } + + #[tokio::test] + async fn an_empty_peer_closure_is_normal_and_emits_no_events() -> TestResult { + let (reader, _writer, mut peer) = connected_pair().await?; + let (reporter, mut sinks) = Reporter::channels(1, 1); + + // Connection lifecycle notifications belong to the future supervisor, not this reader. + peer.shutdown().await?; + let end = timeout( + TEST_TIMEOUT, + receive(reader, BoardId(42), &Index::default(), &reporter), + ) + .await??; + assert_eq!(end, ReceiveEnd::PeerClosed); + assert!(sinks.notifications.try_recv().is_err()); + assert!(sinks.errors.try_recv().is_err()); + Ok(()) + } + + #[tokio::test] + async fn eof_in_a_partial_frame_is_a_nonfatal_read_error_after_the_valid_prefix() -> TestResult + { + let (index, frames) = sample_frames(); + let (reader, _writer, mut peer) = connected_pair().await?; + let (reporter, mut sinks) = Reporter::channels(1, 1); + + // A complete message must survive a following protection cut short by EOF. + peer.write_all(&frames[0].1).await?; + peer.write_all(&frames[1].1[..8]).await?; + peer.shutdown().await?; + let Err(error) = timeout( + TEST_TIMEOUT, + receive(reader, BoardId(42), &index, &reporter), + ) + .await? + else { + unreachable!("EOF cannot complete the pending protection value"); + }; + assert!(!error.is_fatal()); + let TcpError::Read { board, source } = error else { + unreachable!("a truncated connection is a read failure, not an ADJ mismatch"); + }; + assert_eq!(board, BoardId(42)); + assert_eq!(source.kind(), io::ErrorKind::UnexpectedEof); + let Ok(notification) = sinks.notifications.try_recv() else { + unreachable!("the complete message preceding EOF was published"); + }; + let Event::Received(packet) = notification.event else { + unreachable!("the reader emits only Received notifications"); + }; + assert_eq!(packet, frames[0].0); + assert!(sinks.errors.try_recv().is_err()); + Ok(()) + } + + #[tokio::test] + async fn an_oversized_invalid_suffix_is_fatal_after_publishing_the_valid_prefix() -> TestResult + { + let (index, frames) = sample_frames(); + let (reader, _writer, mut peer) = connected_pair().await?; + let (reporter, mut sinks) = Reporter::channels(1, 1); + + // A terminal suffix must not hide a valid message that arrived before it. + let mut bytes = frames[0].1.clone(); + bytes.extend([0xff; 375]); + peer.write_all(&bytes).await?; + let Err(error) = timeout( + TEST_TIMEOUT, + receive(reader, BoardId(42), &index, &reporter), + ) + .await? + else { + unreachable!("an undecodable suffix above 374 bytes must terminate the session"); + }; + assert!(error.is_fatal()); + let TcpError::Decode { board, source } = error else { + unreachable!("framing errors must retain the protocol decoder error"); + }; + assert_eq!(board, BoardId(42)); + assert_eq!(source, DecodeError::UnknownId(AdjId(u16::MAX))); + let Ok(notification) = sinks.notifications.try_recv() else { + unreachable!("the complete message preceding the invalid suffix was published"); + }; + let Event::Received(packet) = notification.event else { + unreachable!("the reader emits only Received notifications"); + }; + assert_eq!(packet, frames[0].0); + assert!(sinks.errors.try_recv().is_err()); + Ok(()) + } + + #[tokio::test] + async fn a_socket_reset_preserves_the_io_error_and_is_not_fatal() -> TestResult { + let (reader, _writer, peer) = connected_pair().await?; + let (reporter, _sinks) = Reporter::channels(1, 1); + + // Abort the peer rather than half-closing it, to exercise the actual read-error path. + peer.set_zero_linger()?; + drop(peer); + let Err(error) = timeout( + TEST_TIMEOUT, + receive(reader, BoardId(42), &Index::default(), &reporter), + ) + .await? + else { + unreachable!("an abortive peer close must fail the socket read"); + }; + assert!(!error.is_fatal()); + let TcpError::Read { board, source } = error else { + unreachable!("a connection reset is a read failure"); + }; + assert_eq!(board, BoardId(42)); + assert_eq!(source.kind(), io::ErrorKind::ConnectionReset); + Ok(()) + } + + #[tokio::test] + async fn a_closed_notification_consumer_stops_instead_of_requesting_reconnection() -> TestResult + { + let (index, frames) = sample_frames(); + let (reader, _writer, mut peer) = connected_pair().await?; + let (reporter, mut sinks) = Reporter::channels(1, 1); + + // Keep the peer connected: this outcome comes from notify, not from socket EOF. + sinks.notifications.close(); + peer.write_all(&frames[0].1).await?; + let end = timeout( + TEST_TIMEOUT, + receive(reader, BoardId(42), &index, &reporter), + ) + .await??; + assert_eq!(end, ReceiveEnd::ConsumerClosed); + assert!(sinks.errors.try_recv().is_err()); + Ok(()) + } + + #[tokio::test] + async fn backpressure_waits_for_capacity_or_consumer_closure() -> TestResult { + let (index, frames) = sample_frames(); + for close_consumer in [false, true] { + let (mut reader, _writer, mut peer) = connected_pair().await?; + let (reporter, mut sinks) = Reporter::channels(1, 1); + let bytes: Vec<_> = frames + .iter() + .flat_map(|(_, bytes)| bytes.iter().copied()) + .collect(); + peer.write_all(&bytes).await?; + peer.shutdown().await?; + + // Peek without consuming until this tiny burst is available. This makes + // one reader poll reach notify, without sleeps or assumptions about writes. + let mut preview = vec![0; bytes.len()]; + timeout(TEST_TIMEOUT, async { + while reader.peek(&mut preview).await? < bytes.len() { + tokio::task::yield_now().await; + } + Ok::<_, io::Error>(()) + }) + .await??; + + // Fill the only notification slot before the reader attempts to publish. + reporter.notify(BoardId(42), Event::Connected).await?; + let reading = receive(reader, BoardId(42), &index, &reporter); + tokio::pin!(reading); + poll_fn(|cx| { + assert!(reading.as_mut().poll(cx).is_pending()); + Poll::Ready(()) + }) + .await; + + if close_consumer { + // Closing a full channel must release the pending publication. + sinks.notifications.close(); + assert_eq!( + timeout(TEST_TIMEOUT, reading).await??, + ReceiveEnd::ConsumerClosed + ); + } else { + let Some(initial) = sinks.notifications.recv().await else { + unreachable!("the test prefilled the notification slot"); + }; + assert!(matches!(initial.event, Event::Connected)); + + // Drain while the reader advances, proving no decoded packet was dropped. + let (end, ()) = timeout(TEST_TIMEOUT, async { + tokio::join!(reading, async { + for (expected, _) in &frames { + let Some(notification) = sinks.notifications.recv().await else { + unreachable!("the reporter remains alive"); + }; + let Event::Received(packet) = notification.event else { + unreachable!("the prefilled lifecycle event was already drained"); + }; + assert_eq!(&packet, expected); + } + }) + }) + .await?; + assert_eq!(end?, ReceiveEnd::PeerClosed); + assert!(sinks.notifications.try_recv().is_err()); + } + } + Ok(()) + } +} diff --git a/backend/crates/core/src/net/tcp/session.rs b/backend/crates/core/src/net/tcp/session.rs new file mode 100644 index 000000000..2ec711088 --- /dev/null +++ b/backend/crates/core/src/net/tcp/session.rs @@ -0,0 +1,104 @@ +//! One connection's reader, keep-alive loop, and shared frame writer. +use super::{TcpError, endpoint, keep_alive, reader, writer::SessionWriter}; +use crate::{ + model::BoardId, + net::{Event, Reporter}, + protocol::Index, +}; +use std::sync::Arc; +use tokio::net::TcpStream; + +/// Session completion without a transport failure. +#[derive(Debug, PartialEq, Eq)] +pub(super) enum SessionEnd { + PeerClosed, + ConsumerClosed, +} + +/// Registers a fresh writer before Connected, then drives reads and control I/O. +/// Orders execute in their callers through that same exclusive writer. The registration +/// guard closes the writer on every exit, including cancellation while publishing +/// Connected. Old session references are invalidated and cannot target a reconnect. +/// A failed order reports [`TcpError::Send`] through its caller; cancelled writes and +/// control-write failures are reported as [`TcpError::Write`] by the supervisor. +pub(super) async fn run( + stream: TcpStream, + board: BoardId, + index: &Index, + reporter: &Reporter, + endpoint: &endpoint::Endpoint, + settings: keep_alive::Settings, +) -> Result { + let (read_half, write_half) = stream.into_split(); + let writer = Arc::new(SessionWriter::new(write_half)); + let registration = endpoint.register(Arc::clone(&writer)); + if reporter.notify(board, Event::Connected).await.is_err() { + return Ok(SessionEnd::ConsumerClosed); + } + let result = tokio::select! { + biased; + () = writer.closed() => Ok(SessionEnd::PeerClosed), + result = reader::receive(read_half, board, index, reporter) => result.map(|end| match end { + reader::ReceiveEnd::PeerClosed => SessionEnd::PeerClosed, + reader::ReceiveEnd::ConsumerClosed => SessionEnd::ConsumerClosed, + }), + () = keep_alive::run_keep_alive(&writer, settings) => Ok(SessionEnd::PeerClosed), + }; + // Close and unregister before collecting a terminal write failure. + drop(registration); + if let Some(source) = writer.take_unreported_failure() { + return Err(TcpError::Write { board, source }); + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::net::tcp::{SendError, test_support::*}; + use std::{future::Future, time::Duration}; + + #[tokio::test] + async fn cancellation_during_connected_publication_closes_and_unregisters_the_session() + -> TestResult { + bounded(async { + let (stream, mut peer) = socket_pair(LIMIT).await?; + let (reporter, mut sinks) = Reporter::channels(1, 16); + reporter.notify(BOARD, Event::Connected).await?; // Fill notification capacity. + let endpoint = endpoint::Endpoint::default(); + let index = index(); + let mut session = Box::pin(run( + stream, + BOARD, + &index, + &reporter, + &endpoint, + keep_alive::Settings { + write_timeout: LIMIT, + keep_alive: Duration::ZERO, + }, + )); + std::future::poll_fn(|cx| { + assert!(session.as_mut().poll(cx).is_pending()); + std::task::Poll::Ready(()) + }) + .await; + let old = endpoint.current_writer().ok_or("session not registered")?; + drop(session); + assert!(endpoint.current_writer().is_none()); + assert!( + !endpoint + .request_fault(tokio::time::Instant::now() + LIMIT) + .await + ); + assert!(matches!( + old.write_order(BOARD, &[2, 3], LIMIT).await, + Err(SendError::Disconnected(BOARD)) + )); + peer_closed(&mut peer).await?; + assert!(sinks.errors.try_recv().is_err()); + Ok(()) + }) + .await + } +} diff --git a/backend/crates/core/src/net/tcp/supervisor.rs b/backend/crates/core/src/net/tcp/supervisor.rs new file mode 100644 index 000000000..b46bf32ec --- /dev/null +++ b/backend/crates/core/src/net/tcp/supervisor.rs @@ -0,0 +1,217 @@ +//! Connection retries without retaining application orders between sessions. +use super::{ + BoardLink, TcpConfig, + connection::connect, + endpoint, keep_alive, + session::{self, SessionEnd}, +}; +use crate::{ + net::{Closed, Event, Reporter}, + protocol::Index, +}; +use tokio::time::sleep; + +/// Reconnects indefinitely with independent backoff. Each session installs a new +/// writer endpoint and clears it before Disconnected; neither orders nor fault +/// writes migrate between sessions. Closing either Reporter consumer cancels +/// all I/O, publication and retry waits. Tasks remain detached; dropping handles +/// alone does not stop supervision. No order channel determines task lifetime. +/// Startup and recovery both use connection::connect(), including its failure +/// retries. After a session ends, this supervisor waits one interval from the +/// same backoff state before connecting again; the last success reset that state. +pub(super) async fn supervise( + link: &BoardLink, + config: &TcpConfig, + index: &Index, + reporter: &Reporter, + endpoint: &endpoint::Endpoint, +) -> Result<(), Closed> { + let supervising = async { + let mut backoff = config.backoff; + loop { + let stream = connect(link, config.connect_timeout, &mut backoff, reporter).await?; + tracing::info!(board = ?link.board, addr = %link.addr, "TCP board connected"); + let end = session::run( + stream, + link.board, + index, + reporter, + endpoint, + keep_alive::Settings { + write_timeout: config.write_timeout, + keep_alive: config.keep_alive, + }, + ) + .await; + match end { + Ok(SessionEnd::ConsumerClosed) => return Err(Closed), + Ok(SessionEnd::PeerClosed) => (), + Err(error) => { + tracing::warn!(board = ?link.board, addr = %link.addr, error = ?error, + "TCP session failed"); + reporter.report(error).await?; + } + } + tracing::info!(board = ?link.board, addr = %link.addr, "TCP board disconnected"); + reporter.notify(link.board, Event::Disconnected).await?; + sleep(backoff.get_interval()).await; + } + }; + let result = + tokio::select! { result = supervising => result, () = reporter.closed() => Err(Closed) }; + tracing::debug!(board = ?link.board, addr = %link.addr, "TCP supervisor stopped"); + result +} + +#[cfg(test)] +mod tests { + use crate::{ + model::AdjId, + net::{ + Event, Reporter, + tcp::{SendError, TcpError, spawn, test_support::*}, + }, + }; + use std::{ + net::{Ipv4Addr, SocketAddr}, + time::Duration, + }; + use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpSocket}, + time::timeout, + }; + + #[tokio::test] + async fn offline_and_disconnected_orders_never_appear_after_connection_or_reconnection() + -> TestResult { + bounded(async { + let socket = TcpSocket::new_v4()?; + socket.bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))?; + let addr = socket.local_addr()?; // Bound but not listening: no port-reuse race. + let (reporter, mut sinks) = Reporter::channels(32, 64); + let clients = spawn(config(addr), index(), reporter); + assert!(matches!( + clients.send(order(600, 11.0)).await, + Err(SendError::Disconnected(BOARD)) + )); + let listener = socket.listen(8)?; + let (mut peer, _) = listener.accept().await?; + connected(&mut sinks).await?; + clients.send(order(600, 22.0)).await?; + let mut bytes = [0; 3]; + peer.read_exact(&mut bytes).await?; + assert_eq!(bytes, [0x58, 2, 22]); + let old_session = clients + .board(BOARD) + .ok_or("missing board")? + .endpoint + .current_writer() + .ok_or("missing session")?; + drop(peer); + assert!(matches!( + event(&mut sinks).await?.event, + Event::Disconnected + )); + assert!(matches!( + clients.send(order(600, 33.0)).await, + Err(SendError::Disconnected(BOARD)) + )); + let (mut peer, _) = listener.accept().await?; + connected(&mut sinks).await?; + assert!(matches!( + old_session.write_order(BOARD, &[0x58, 2, 44], LIMIT).await, + Err(SendError::Disconnected(BOARD)) + )); + clients.send(order(600, 55.0)).await?; + peer.read_exact(&mut bytes).await?; + assert_eq!(bytes, [0x58, 2, 55]); + assert!( + timeout(Duration::from_millis(20), peer.read(&mut bytes)) + .await + .is_err() + ); + let mut rejected = vec![]; + while let Ok(report) = sinks.errors.try_recv() { + if let crate::net::Error::Tcp(TcpError::Send { + board, + order, + source, + }) = report.error + { + assert_eq!(board, BOARD); + assert_eq!(order, AdjId(600)); + assert_eq!(source.kind(), std::io::ErrorKind::NotConnected); + rejected.push(order); + } + } + assert_eq!(rejected.len(), 2); + sinks.errors.close(); + peer_closed(&mut peer).await?; + Ok(()) + }) + .await + } + + #[tokio::test] + async fn closing_either_consumer_stops_an_idle_session_and_invalidates_its_writer() -> TestResult + { + bounded(async { + for errors in [false, true] { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?; + let (reporter, mut sinks) = Reporter::channels(16, 16); + let clients = spawn(config(listener.local_addr()?), index(), reporter); + let (mut peer, _) = listener.accept().await?; + connected(&mut sinks).await?; + let old = clients + .board(BOARD) + .ok_or("board missing")? + .endpoint + .current_writer() + .ok_or("session missing")?; + if errors { + sinks.errors.close(); + } else { + sinks.notifications.close(); + } + peer_closed(&mut peer).await?; + assert!(matches!( + old.write_order(BOARD, &[0x58, 2, 22], LIMIT).await, + Err(SendError::Disconnected(BOARD)) + )); + } + Ok(()) + }) + .await + } + + #[tokio::test] + async fn receive_decode_errors_are_reported_before_reopening_the_session() -> TestResult { + bounded(async { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?; + let (reporter, mut sinks) = Reporter::channels(16, 16); + let clients = spawn(config(listener.local_addr()?), index(), reporter); + let (mut peer, _) = listener.accept().await?; + connected(&mut sinks).await?; + peer.write_all(&[0xff; 375]).await?; + let report = sinks.errors.recv().await.ok_or("missing decode error")?; + assert!(matches!( + report.error, + crate::net::Error::Tcp(TcpError::Decode { board: BOARD, .. }) + )); + assert!(matches!( + event(&mut sinks).await?.event, + Event::Disconnected + )); + let (mut peer, _) = listener.accept().await?; + connected(&mut sinks).await?; + clients.send(order(600, 22.0)).await?; + let mut bytes = [0; 3]; + peer.read_exact(&mut bytes).await?; + assert_eq!(bytes, [0x58, 2, 22]); + sinks.notifications.close(); + Ok(()) + }) + .await + } +} diff --git a/backend/crates/core/src/net/tcp/test_support.rs b/backend/crates/core/src/net/tcp/test_support.rs new file mode 100644 index 000000000..11a140afe --- /dev/null +++ b/backend/crates/core/src/net/tcp/test_support.rs @@ -0,0 +1,331 @@ +//! Shared test-only ADJ, socket, event and scripted-write fixtures. +use super::*; +use crate::protocol::{ + packet::{message, protection}, + tcp::TcpFrame, +}; +use crate::{ + model::{ + AdjId, Board, MacAddress, Measurement, MeasurementKind, MessageLevel, MessagePacket, + NumericKind, OrderPacket, PacketDef, PacketType, PodData, ProtectionPacket, ShortTimestamp, + Value, + }, + net::{Event, Notification, Sinks}, +}; +use std::{ + future::Future, + net::{IpAddr, Ipv4Addr}, +}; +use tokio::{ + io::AsyncReadExt, + net::{TcpListener, TcpStream}, + time::timeout, +}; + +pub(super) type TestResult = Result>; +pub(super) const LIMIT: Duration = Duration::from_secs(4); +pub(super) const BOARD: BoardId = BoardId(7); + +pub(super) fn index() -> Arc { + let parameter = Measurement { + id: AdjId(100), + alias: "v".into(), + name: "Value".into(), + display_units: String::new(), + kind: MeasurementKind::Numeric { + wire_type: NumericKind::U8, + }, + protections: vec![], + }; + let boards = [(7, 600), (9, 601)] + .into_iter() + .map(|(board, id)| { + let id = AdjId(id); + let board = Board { + id: BoardId(board), + name: "TEST".into(), + ip: Ipv4Addr::LOCALHOST.into(), + mac: MacAddress([0; 6]), + packets: HashMap::from([ + ( + id, + PacketDef { + id, + board: BoardId(board), + name: "order".into(), + packet_type: PacketType::Order(vec![parameter.clone()]), + }, + ), + ( + AdjId(id.0 + 1000), + PacketDef { + id: AdjId(id.0 + 1000), + board: BoardId(board), + name: "data".into(), + packet_type: PacketType::Data(vec![]), + }, + ), + ]), + }; + (board.id, board) + }) + .collect(); + Arc::new(Index::new(&PodData { boards }, None)) +} +pub(super) fn order(id: u16, value: f64) -> OrderPacket { + OrderPacket::new(AdjId(id), vec![Value::Number(value)]) +} +pub(super) fn config(addr: SocketAddr) -> TcpConfig { + TcpConfig { + boards: vec![BoardLink { + board: BOARD, + addr, + local_port: Port(0), + }], + connect_timeout: Duration::from_millis(50), + backoff: Backoff::new(50, 100), + keep_alive: Duration::ZERO, + write_timeout: Duration::from_millis(100), + } +} +pub(super) async fn event(sinks: &mut Sinks) -> TestResult { + timeout(LIMIT, sinks.notifications.recv()) + .await? + .ok_or_else(|| "reporting stopped".into()) +} +pub(super) async fn connected(sinks: &mut Sinks) -> TestResult { + assert!(matches!(event(sinks).await?.event, Event::Connected)); + Ok(()) +} +pub(super) async fn peer_closed(peer: &mut TcpStream) -> TestResult { + let mut byte = [0]; + match timeout(LIMIT, peer.read(&mut byte)).await? { + Ok(0) => (), + Err(error) if error.kind() == std::io::ErrorKind::ConnectionReset => (), + other => return Err(format!("expected closed socket, got {other:?}").into()), + } + Ok(()) +} +pub(super) async fn bounded(test: impl Future) -> TestResult { + timeout(LIMIT, test).await? +} + +/// Client and mock peer, both bounded by the caller's existing test deadline. +pub(super) async fn socket_pair(budget: Duration) -> TestResult<(TcpStream, TcpStream)> { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?; + let client = timeout(budget, TcpStream::connect(listener.local_addr()?)).await??; + let (peer, _) = timeout(budget, listener.accept()).await??; + Ok((client, peer)) +} + +pub(super) fn inbound_frames() -> (Index, Vec<(TcpFrame, Vec)>) { + let packets = [ + (100, MeasurementKind::Boolean), + ( + 101, + MeasurementKind::Numeric { + wire_type: NumericKind::F64, + }, + ), + ] + .into_iter() + .map(|(id, kind)| { + let id = AdjId(id); + let definition = PacketDef { + id: AdjId((1 << 13) | id.0), + board: BoardId(1), + name: "protection".to_string(), + packet_type: PacketType::Protection(Measurement { + id, + alias: "watched".to_string(), + name: "Watched".to_string(), + display_units: String::new(), + kind, + protections: vec![], + }), + }; + (definition.id, definition) + }) + .collect(); + let board = Board { + id: BoardId(1), + name: "MOCK".to_string(), + ip: IpAddr::from([127, 0, 0, 1]), + mac: MacAddress([0; 6]), + packets, + }; + let pod = PodData { + boards: HashMap::from([(board.id, board)]), + }; + let levels = HashMap::from([(AdjId(10), MessageLevel::Fault)]); + let index = Index::new(&pod, Some(&levels)); + let timestamp = ShortTimestamp { + hour: 12, + minute: 30, + second: 0, + subsecond: 0, + }; + let frames = [ + TcpFrame::Protection(ProtectionPacket { + id: AdjId((1 << 13) | 100), + timestamp, + value: Value::Bool(true), + }), + TcpFrame::Message(MessagePacket { + id: AdjId(10), + timestamp, + origin: "LCU".to_string(), + message: "temperature \u{00b0}C".to_string(), + }), + TcpFrame::Protection(ProtectionPacket { + id: AdjId((1 << 13) | 101), + timestamp, + value: Value::Number(42.25), + }), + TcpFrame::Message(MessagePacket { + id: AdjId(10), + timestamp, + origin: String::new(), + message: String::new(), + }), + ] + .into_iter() + .map(|frame| { + let encoded = match &frame { + TcpFrame::Protection(packet) => protection::encode(packet, &index), + TcpFrame::Message(packet) => message::encode(packet, &index), + }; + let Ok(bytes) = encoded else { + unreachable!("the sample frames match their index definitions"); + }; + (frame, bytes) + }) + .collect(); + + (index, frames) +} + +/// Deterministic partial-write and control scheduling fixtures. +pub(super) mod writes { + //! Scripted writes exercise partial-frame failures without relying on OS buffers. + use crate::model::BoardId; + use crate::net::tcp::{ + endpoint::{Endpoint, Registration}, + keep_alive::Settings, + writer::{SessionWriter, lock}, + }; + use std::sync::Mutex as StdMutex; + use std::{ + collections::VecDeque, + future::{Future, poll_fn}, + pin::Pin, + task::{Context, Poll}, + }; + use std::{io, sync::Arc, time::Duration}; + use tokio::io::AsyncWrite; + + pub(in crate::net::tcp) const BOARD: BoardId = BoardId(7); + pub(in crate::net::tcp) const BUDGET: Duration = Duration::from_millis(20); + + #[derive(Debug)] + pub(in crate::net::tcp) enum Step { + Write(usize), + Fail(io::ErrorKind), + Pending, + Zero, + } + #[derive(Debug, Default)] + pub(in crate::net::tcp) struct Trace { + pub(in crate::net::tcp) bytes: Vec, + pub(in crate::net::tcp) calls: usize, + pub(in crate::net::tcp) dropped: bool, + pub(in crate::net::tcp) resume: bool, + } + #[derive(Debug)] + pub(in crate::net::tcp) struct Script { + steps: VecDeque, + trace: Arc>, + } + impl Drop for Script { + fn drop(&mut self) { + lock(&self.trace).dropped = true; + } + } + impl AsyncWrite for Script { + fn poll_write( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + lock(&self.trace).calls += 1; + match self.steps.pop_front() { + Some(Step::Pending) if !lock(&self.trace).resume => { + self.steps.push_front(Step::Pending); + Poll::Pending + } + Some(Step::Fail(kind)) => Poll::Ready(Err(io::Error::from(kind))), + Some(Step::Zero) => Poll::Ready(Ok(0)), + step => { + let n = match step { + Some(Step::Write(n)) => n.min(bytes.len()), + _ => bytes.len(), + }; + lock(&self.trace).bytes.extend_from_slice(&bytes[..n]); + Poll::Ready(Ok(n)) + } + } + } + fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + } + pub(in crate::net::tcp) fn setup( + steps: impl IntoIterator, + ) -> (SessionWriter