diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 51ba1dae3..ab999301b 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", @@ -1958,18 +1958,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", @@ -1979,9 +1979,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" @@ -2154,9 +2154,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", @@ -2377,7 +2377,7 @@ dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand 0.10.3", + "rand 0.10.4", "rand_pcg", "ring", "rustc-hash", @@ -2437,9 +2437,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", @@ -2501,9 +2501,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", @@ -2513,9 +2513,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", @@ -2524,9 +2524,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" @@ -3814,9 +3814,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 08324ed3f..68c5e0eed 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -70,6 +70,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 a0644a70c..85dd84d65 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 @@ -33,11 +32,13 @@ 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 index 3ba454472..4d93f0f16 100644 --- a/backend/crates/core/src/net.rs +++ b/backend/crates/core/src/net.rs @@ -32,7 +32,7 @@ //! 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::Error`, +//! up interpolated in each submodule's error messages (`tcp::TcpError`, //! `udp::UdpError`), which is where somebody actually reads them. mod error; diff --git a/backend/crates/core/src/net/README.md b/backend/crates/core/src/net/README.md index 50b0f78dd..c5bfb9aa9 100644 --- a/backend/crates/core/src/net/README.md +++ b/backend/crates/core/src/net/README.md @@ -7,13 +7,15 @@ touches a socket; `net` owns the socket and calls into `protocol`. Nothing above Two submodules do the I/O, and **this directory's shared part opens nothing**: ``` -net/ -├── net.rs # module root: docs and re-exports -├── report.rs # Event, Notification, ErrorReport, Reporter — what is reported -├── error.rs # Error — aggregates tcp::Error / udp::UdpError, nothing else -├── tcp.rs # the TCP client (not written yet: error type + contract) -├── udp.rs # the shared UDP socket -└── udp/ # its tests: tests.rs, test_support.rs, manual_tests.rs (load probe) +src/ +├── net.rs # module root and re-exports +└── net/ + ├── report.rs # Event, Notification, ErrorReport, Reporter, Sinks + ├── error.rs # Error wraps TcpError and UdpError + ├── tcp.rs # TCP clients and task ownership + ├── tcp/ # TCP implementation and tests + ├── udp.rs # shared UDP socket + └── udp/ # UDP tests and load probe ``` ## The shared part @@ -35,9 +37,8 @@ datagram instead of one per consumer downstream. And the board is all the identity there is: one connection per board, 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 `tcp::Error`/`udp::UdpError` messages, which is where somebody -actually reads them. +TCP error reports identify the board. UDP reports for individual datagrams +include their source address and any board resolved from that address. ### `Event` and `Notification` — what happened, and when @@ -49,39 +50,31 @@ enum Event { } ``` -`Event::Received` leans on the existing `model::Packet` umbrella -(`Data | Order | Protection | Message`) rather than repeating that split with one -variant per packet type. Its `Order` variant is never produced while receiving — -it is there for an eventual "the order really did go out on the wire" report, -which only `net` can make. +`Event::Received` carries a decoded data packet (UDP), protection or message +(TCP). The result of `BoardClients::send` confirms whether a normal order was +written to the local socket. There is no successful-send notification or firmware +acknowledgement. `board` and `at` sit in the envelope rather than inside the variants so that **everything** that travels down the channel carries them, and so a notification -**cannot be built without a timestamp**. `Reporter::notify` is the only thing that -stamps it. That -matters: a queue adds delay under load, so a date taken when the record is -*written* would be wrong by exactly that delay, precisely when the data matters -most. It is also the only full date a record can have — the board clock on -protections and messages (`ShortTimestamp`) is a time of day with no date. +**cannot be built without a timestamp**. `Reporter::notify` takes the timestamp +before waiting for queue capacity, so delays in the channel do not skew it. +The board clock on protections and messages (`ShortTimestamp`) contains only a +time of day. -### `Reporter` — the two sinks +### Reporting ```rust let (reporter, sinks) = Reporter::channels(notifications, errors); - -reporter.notify(board, event).await?; // notification channel -reporter.report(tcp_or_udp_error).await?; // error channel +// Pass reporter to the transport and read sinks.notifications and sinks.errors. ``` -Cloneable, and meant to be cloned: one copy per TCP connection task, one for the -UDP loop, all feeding the same two channels. - -Two channels, not one, because the rules differ. **A notification is never -dropped**: `notify` waits when the channel is full, so the backpressure reaches -the read loop and the kernel's receive buffer becomes the only place anything can -be lost — and whatever is lost there is lost *before* being decoded, so -"everything decoded gets through" stays literally true. An error is rare enough -that it can afford to queue behind telemetry. +Each transport uses a cloneable `Reporter`. Both channels are bounded and +publication waits when either destination queue is full. Consume notifications +and errors concurrently to prevent a stalled consumer from blocking transport +work. The channels have separate ordering, so an error may be consumed before a +related lifecycle notification. Cancelling I/O during shutdown may discard an +unpublished report. Reports already queued can still be drained. `ErrorReport` carries **no board**, unlike a notification: the identity of what failed lives inside the `Error` variant, which is the only place that always has @@ -92,71 +85,46 @@ address it came from and the board that address belongs to, if it belongs to one ### `Error` — aggregation only -`net::Error` adds no identity and no message of its own; both variants are -`#[error(transparent)]`, so `to_string()` is the submodule's own message with its -identity already interpolated, and `source()` still reaches the original -`io::Error` or `DecodeError`. Each submodule owns its error type and puts the -board or address **inside the variant** — the Go backend lost exactly -that when an error crossed its channel. `is_fatal()`, if needed, belongs to each -submodule's own error: nobody outside knows which of its variants are fatal. +`net::Error` wraps `TcpError` or `UdpError`. Messages and any underlying +`io::Error` or `DecodeError` come from the wrapped error. Each transport defines +its own `is_fatal()` helper. Application policy can match the variants directly. ## The contract for the two submodules | | `tcp` | `udp` | |---|---|---| -| Entry point | `spawn(Config, Arc, Reporter) -> Handles` | `spawn_udp(UdpConfig, Arc, Reporter) -> Result, UdpError>` (binds first) | -| Inputs | its `Config` (boards, timeouts, backoff, keep-alive) | its `UdpConfig` (bind address, `SO_RCVBUF`, IP → board) | +| Entry point | `spawn(...)` returns `BoardClients`. `spawn_managed(...)` returns `(BoardClients, TcpTasks)`. | `spawn_udp(...)` binds the socket and returns `Result, UdpError>`. | +| Configuration | `TcpConfig`: board links, timeouts, backoff and keep-alive | `UdpConfig`: bind address, `SO_RCVBUF` and IP → board map | | Role | client only; one connection per board, one task each | one shared socket, receive-only, one task | -| Framing | buffer + `&mut Cursor` + advance by `cursor.position()`; bail out past 374 bytes | none — `recv_from` delivers a whole datagram into a reused 64 KiB buffer | -| Writing | yes (orders, keep-alive); a single writer task per connection | no | -| On a decode error | report it; **fatal**, and close/reopen the connection (the stream cannot be resynchronised) | report it; **fatal**, and keep receiving | +| Framing | buffer per connection; report a terminal decode failure when the undecodable suffix exceeds 374 bytes | `recv_from` delivers whole datagrams into a reused 64 KiB buffer | +| Writing | orders, keep-alive and faults share one exclusive writer per session | none | +| On a decode error | report the terminal error, close the session and retry the connection | report the error and keep receiving | | `Connected`/`Disconnected` | per board | never | -| Fault | writes it: `Handles::propagate_fault()`, id 0 to every board | cannot write; a received id 0 is reported as `UdpError::Fault`, before decoding | - -Both take the same two things besides their own `Config`: an `Arc` — the -only part of the ADJ `net` needs, owned by `station` and read-only here — and a -`Reporter`. Neither reads a config file, and neither reads the ADJ itself: the -addresses `tcp` connects to are resolved by `station` and arrive in `Config`, -which is also what lets a test point it at a fake peer. - -`net` never decides to fault the pod, but `tcp` is what can write one: `station` -reads `is_fatal()` and calls `Handles::propagate_fault()`, which puts the order -with id 0 into every board's writer channel (the Go backend's `SendFault`). A -*received* packet with id 0 is the same action requested by a board, and -`station` answers it the same way. In `udp` it arrives on the error channel as -`UdpError::Fault { from, board }`: recognised by its id alone, before decoding, without -looking at the ADJ. - -Three rules both follow: - -1. The timestamp comes from `Reporter`, never by hand. -2. Decode and report, nothing else — no disk, no WebSocket, no aggregation. -3. What to do about an error is decided locally; only the report goes up. - -### What "fatal" means - -`tcp::Error::is_fatal`/`udp::UdpError::is_fatal` are about the **pod**: they say -the pod has to be sent to fault. They are a hint, not a decision — what happens -next (the fault, closing the connections, shutting the backend down safely) is -decided by whoever consumes the error channel (`station`). Nothing in `net` ever -calls `std::process::exit`. - -On either transport, a decode failure is fatal, and this is a deliberate -departure from Go. Nothing corrupts a frame or a datagram in flight (both -transports checksum, TCP retransmits, and the pod's network does not fragment), so -something that will not decode means the loaded ADJ does not describe what the -firmware is sending — which reconnecting cannot fix. A failed connect or write is -*not* fatal: that is what the backoff is for. - -Two more are fatal in `udp`: losing the socket (`UdpError::Recv`), which is every -board's telemetry gone at once, and a fault sent by a board (`UdpError::Fault`, -packet id 0), which is a board asking for exactly that. - -`net` never raises the fault itself — neither transport does. It logs, it reports, -and `is_fatal()` is the classification whoever consumes the error channel acts on. -That is deliberate: a mismatched ADJ fails on every frame that follows, thousands -a second, so the fault has to be broadcast **once**, and the guard for that lives -in one place instead of one per transport. +| Received fault | reserved `00 00` at a frame boundary produces `TcpError::Fault { board }` and the session stays open | id 0 produces `UdpError::Fault { from, board }` before decoding | +| Shutdown | closing either reporting receiver cancels supervisors; `TcpTasks::shutdown().await` cancels and joins managed tasks | abort and await the returned task to stop it, including while idle | + +Both transports take their configuration, a shared read-only `Arc` and +a `Reporter`. The caller loads the ADJ and resolves board addresses and ports. +See the [TCP API](tcp/README.md) for examples and the +[station startup settings](../../../station/src/event/README.md) for board +selection and local ADJ configuration. + +### Faults and fatal errors + +The application decides whether to call `BoardClients::broadcast_fault()`. +The call attempts to write the reserved frame through each configured board's +current session and reports any unconfirmed writes. + +`TcpError::is_fatal()` returns true for terminal decode failures only. +`UdpError::is_fatal()` also returns true for received fault datagrams. Station's +policy matches errors directly and treats board faults from either transport +as nonfatal to the backend. It shows the first fault per board across TCP and +UDP and requests propagation when enabled and the fault queue has room. + +Station treats terminal TCP decode errors and UDP decode or receive errors +as fatal. It gives the fault attempt a deadline while TCP is still available, +then shuts down. A UDP bind failure is returned to the caller during startup. +An ADJ mismatch is one possible cause of a decode failure. ## Why TCP needs a buffer and UDP does not @@ -165,8 +133,8 @@ half a frame or two frames glued together — both are normal, and the glued cas the frequent one. Our frames carry no length prefix: a protection's length is fixed but derivable only from the ADJ (`2 + 4 + 2 + the watched measurement's wire width`), and a message ends at the second NUL byte of its two variable-length -strings. So a frame's end is never known in advance, only deduced by parsing it — -which is why the loop tries, and retries with more bytes when it fails. +strings. The receive loop parses buffered bytes to find each frame boundary and +waits for more data when a frame is incomplete. A reserved fault frame is two bytes. The Go backend never faced this because it read straight off the connection, where a blocking read simply waits mid-frame. That state has to live somewhere: in Go it @@ -175,10 +143,3 @@ which is also what lets `protocol` stay synchronous and socket-free, reusable by sniffer against a capture. UDP has none of it: the kernel hands over a whole datagram or nothing. - -## Open questions - -- Who raises the fault on `is_fatal()`, and where its "only once" guard lives. - Not in `net`: both transports only report. -- Whether an order's write is reported back as - `Event::Received(Packet::Order(..))`, or `station` just assumes it went out. diff --git a/backend/crates/core/src/net/error.rs b/backend/crates/core/src/net/error.rs index 1588e2043..c93b2590a 100644 --- a/backend/crates/core/src/net/error.rs +++ b/backend/crates/core/src/net/error.rs @@ -19,9 +19,9 @@ use super::{tcp, udp}; /// [`crate::protocol::DecodeError`]. #[derive(Debug, thiserror::Error)] pub enum Error { - /// On a board's TCP connection. + /// On a board's TCP connection; wraps [`tcp::TcpError`]. #[error(transparent)] - Tcp(#[from] tcp::Error), + Tcp(#[from] tcp::TcpError), /// On the shared UDP socket. #[error(transparent)] Udp(#[from] udp::UdpError), diff --git a/backend/crates/core/src/net/report.rs b/backend/crates/core/src/net/report.rs index 4ad86342f..92da9eb7f 100644 --- a/backend/crates/core/src/net/report.rs +++ b/backend/crates/core/src/net/report.rs @@ -148,6 +148,17 @@ impl Reporter { ) } + /// Waits until either reporting consumer closes or drops its receiver. + /// + /// Transports use this to cancel idle I/O and retry waits when the + /// application can no longer consume all their reports. + pub(super) async fn closed(&self) { + tokio::select! { + () = self.notifications.closed() => {}, + () = self.errors.closed() => {}, + } + } + /// Stamps the instant and queues `event`. /// /// **Waits** if the channel is full, rather than dropping anything: @@ -178,14 +189,13 @@ impl Reporter { /// /// Takes anything that converts into [`Error`], so a submodule /// reports its own error type directly: - /// `reporter.report(tcp::Error::Connect { .. }).await`. + /// `reporter.report(tcp::TcpError::Connect { .. }).await`. /// - /// Reporting is not deciding: by the time an error gets here its - /// submodule has already done whatever it was going to do about it - /// (reconnect, carry on with the next datagram), and has already - /// logged it through `tracing`. This channel is only for telling the - /// operator, through the frontend. - pub async fn report(&self, error: impl Into) -> Result<(), Closed> { + /// 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(), diff --git a/backend/crates/core/src/net/tcp.rs b/backend/crates/core/src/net/tcp.rs index 297923dc1..96ea7bab5 100644 --- a/backend/crates/core/src/net/tcp.rs +++ b/backend/crates/core/src/net/tcp.rs @@ -1,26 +1,30 @@ //! The TCP client: one connection per board, one task each. //! -//! **Not written yet.** This file currently holds only the error type -//! [`super::Error`] aggregates, plus the contract below, so that the rest -//! of `net` compiles and whoever implements this module knows what the -//! shared part expects of it. See [`super`] and `net/README.md`. +//! [`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. +//! Use [`spawn_managed`] to wait for supervisor shutdown. 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. +//! state. That connection carries protections, messages and faults inbound, +//! and orders, the keep-alive and faults outbound. //! //! # Entry point //! -//! [`spawn`], taking [`Config`], an `Arc` and a -//! [`super::Reporter`], and returning [`Handles`] — the API is written +//! [`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** connection: one task per entry in [`Config::boards`], so the -//! per-board bookkeeping stays here and `station` only ever asks for -//! "write this to that board". +//! **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 //! @@ -31,42 +35,47 @@ //! [`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. A failed parse means "not enough bytes -//! yet"; the one safeguard is that no frame can exceed 374 bytes -//! (`2 + 4 + 48 + 320`), so a buffer that grows past that without -//! yielding a frame is out of step rather than waiting, and the -//! connection should be dropped and reopened. -//! - **One writer task per connection.** Orders, the keep-alive and the -//! fault all share the socket, so a single task must own the write -//! half, or two half-written frames can interleave on the wire. That -//! task is what [`super::Reporter`]-side callers reach through the -//! board's channel in `Handles`. -//! - **Be ready to be told to propagate the fault.** `station` is what -//! decides (it is the one consuming the error channel and reading -//! [`Error::is_fatal`]); this module is what can actually write, so it -//! exposes `Handles::propagate_fault`, which puts **the order with id +//! 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. +//! - **An inbound fault is a reserved frame.** At a frame boundary, `00 00` +//! consumes exactly two bytes before ADJ-dependent decoding. Split IDs wait +//! for both bytes. Each occurrence reports [`TcpError::Fault`] with the +//! connection's board, without closing the session or broadcasting a fault. +//! Ordinary frames following it are still decoded; the application decides +//! whether to propagate the board fault. +//! - **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 writer channel at once, bounded by `write_timeout` per -//! write. It reports back which boards it could not reach instead of +//! 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 -//! covers the other case the Go backend had under `propagate_fault`: a -//! *received* packet with id 0 is a board announcing a fault, and -//! `station` answers it by calling this, so that logic does not have to -//! exist twice. +//! 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` so a dropped connection frees its fixed local port -//! immediately instead of sitting in `TIME_WAIT`. +//! `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 [`Error`] on the error -//! channel. Never stamp a timestamp by hand — [`super::Reporter::notify`] +//! [`super::Event::Received`] per ordinary frame, and [`TcpError`] on the error +//! channel. Never stamp a timestamp by hand — the reporter //! does it. Never touch disk, WebSocket or aggregation. -//! - **A decode failure is fatal**: see [`Error::is_fatal`]. Log it and -//! report it on the error channel — and that 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 [`Error::is_fatal`] and +//! - **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 @@ -76,11 +85,28 @@ //! is what the backoff is for, and only the report goes up. use super::Reporter; -use crate::model::{AdjId, BoardId, OrderPacket}; -use crate::protocol::{DecodeError, Index}; -use std::net::SocketAddr; -use std::sync::Arc; -use std::time::Duration; +use crate::{ + model::{BoardId, Port}, + protocol::Index, +}; +use std::{collections::HashMap, net::SocketAddr, sync::Arc, time::Duration}; +use tokio::task::JoinSet; + +mod board_clients; +mod board_handle; +mod connection; +mod endpoint; +mod error; +mod framing; +mod keep_alive; +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)] @@ -91,29 +117,65 @@ pub struct BoardLink { /// 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). Being fixed is why `linger = 0` matters: a - /// dropped connection must not leave this port in `TIME_WAIT`. - pub local_port: u16, + /// 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 first wait after a connection fails or drops. - pub initial: Duration, - /// 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. - pub max: Duration, + // 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 `station` before `net` is reached: this +/// 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 Config { +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. @@ -122,254 +184,244 @@ pub struct Config { pub connect_timeout: Duration, /// What to wait between attempts. pub backoff: Backoff, - /// Period of the application-level keep-alive this module sends on - /// its own. The OS-level keep-alive is - /// disabled precisely because this one exists. + /// 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 each write, so that a peer that stops reading cannot park - /// a writer task for good (1 s in the Go backend). + /// 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 `station` only ever asks for "write this to that -/// board" through the [`Handles`] that come back. +/// this module, and the application submits orders through the [`BoardClients`] +/// that come back, letting the index select their destination. /// -/// `adj` is the only part of the ADJ this module needs: it decodes -/// inbound frames and encodes outbound orders against it. `station` owns +/// `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. -pub fn spawn(config: Config, adj: Arc, reporter: Reporter) -> Handles { - let _ = (config, adj, reporter); - todo!("the TCP client is not written yet: see this module's contract") +/// +/// 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. +/// +/// This API detaches the tasks. Use [`spawn_managed`] to retain their handles. +/// 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 { + let (clients, mut tasks) = spawn_managed(config, index, reporter); + tasks.0.detach_all(); + clients } -/// The writing side of every connection [`spawn`] opened. -/// -/// The representation is left to the implementation — a writer channel -/// per board and the task handles — so that this file states the API and -/// nothing else. +/// Owns the supervisors started by [`spawn_managed`]. Dropping it requests cancellation. #[derive(Debug)] -pub struct Handles {} - -impl Handles { - /// The handle for one board, or `None` if the config did not list it. - #[must_use] - pub fn board(&self, board: BoardId) -> Option<&BoardHandle> { - let _ = board; - todo!("the TCP client is not written yet: see this module's contract") - } +#[must_use] +pub struct TcpTasks(JoinSet<()>); - /// Hands an order to the board it belongs to, resolved by its id - /// through the [`Index`]. - /// - /// Returns once the order is queued on that board's writer, not once - /// it is on the wire — the write itself is bounded by - /// [`Config::write_timeout`] and reported through [`Error::Write`]. - /// - /// # Errors - /// - /// See [`SendError`]: an id no ADJ declares, a board with no client, - /// or a connection task that is gone. - pub async fn send(&self, order: OrderPacket) -> Result<(), SendError> { - let _ = order; - todo!("the TCP client is not written yet: see this module's contract") - } - - /// Sends the fault — the order with id 0 — to every board at once. - /// - /// This module does not decide to fault the pod; `station` does, by - /// reading [`Error::is_fatal`] off the error channel. This is only - /// the one place that can actually write it, so it is where the - /// fan-out lives. A *received* packet with id 0 is a board asking for - /// the same thing, and `station` answers it by calling this, so that - /// logic does not exist twice. - /// - /// # Errors - /// - /// [`Unreachable`], naming the boards the fault did not reach rather - /// than collapsing them into one opaque failure: a fault that only - /// half landed is exactly what the operator has to be told. - pub async fn propagate_fault(&self) -> Result<(), Unreachable> { - todo!("the TCP client is not written yet: see this module's contract") - } - - /// Closes every connection and waits for its task to finish. - pub async fn shutdown(self) { - todo!("the TCP client is not written yet: see this module's contract") +impl TcpTasks { + /// Cancels every supervisor and waits for its session cleanup to finish. + pub async fn shutdown(mut self) { + self.0.abort_all(); + while let Some(result) = self.0.join_next().await { + if let Err(error) = result + && !error.is_cancelled() + { + tracing::error!(%error, "TCP supervisor task failed"); + } + } } } -/// The writing side of one board's connection. +/// Starts the same clients as [`spawn`] and retains ownership of their tasks. /// -/// The representation is left to the implementation, same as -/// [`Handles`]. -#[derive(Debug)] -pub struct BoardHandle {} +/// # Panics +/// Starting a nonempty configuration outside a Tokio runtime panics. +pub fn spawn_managed( + config: TcpConfig, + index: Arc, + reporter: Reporter, +) -> (BoardClients, TcpTasks) { + 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 mut tasks = JoinSet::new(); + 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(), + }, + ); -impl BoardHandle { - /// Hands an order to this board's writer, without consulting the - /// order's id — [`Handles::send`] is what routes. - /// - /// # Errors - /// - /// [`SendError::Gone`] if this connection's task is no longer there. - pub async fn send(&self, order: OrderPacket) -> Result<(), SendError> { - let _ = order; - todo!("the TCP client is not written yet: see this module's contract") + let index = Arc::clone(&index); + let config = Arc::clone(&config); + let reporter = reporter.clone(); + tasks.spawn(async move { + let _ = supervisor::supervise(&link, &config, &index, &reporter, &endpoint).await; + }); } + ( + BoardClients::new(boards, index, config.write_timeout), + TcpTasks(tasks), + ) } -/// Why an order could not be handed to a writer. -/// -/// Returned to the caller, not reported through [`super::Reporter`]: it -/// says something about the order that was asked for, not about the state -/// of a connection. [`Error`] is the one that travels on the error -/// channel. -#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] -pub enum SendError { - /// No order with this id is declared in the loaded ADJ. - #[error("no order is declared with id {0:?}")] - UnknownId(AdjId), - /// The order resolves to a board the config did not list, so no - /// client was ever opened for it. - #[error("board {0:?} has no TCP client: the config does not list it")] - NoClient(BoardId), - /// The board's connection task is no longer running. - #[error("board {0:?}: its connection task is gone")] - Gone(BoardId), -} - -/// The boards a fault broadcast did not reach. -/// -/// Never empty: a broadcast that reached everybody returns `Ok`. -#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -#[error("the fault did not reach these boards: {0:?}")] -pub struct Unreachable(pub Vec); - -/// Something that went wrong on a board's TCP connection. -/// -/// Every variant names its board, which is the whole identity of a link: -/// one connection per board. -#[derive(Debug, thiserror::Error)] -pub enum Error { - /// 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 frame could not be decoded, which means the loaded ADJ does not - /// describe what the board is sending. Fatal: see - /// [`Error::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 or a keep-alive 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. - #[source] - source: std::io::Error, - }, -} +#[cfg(test)] +mod manual_tests; -impl Error { - /// Whether this error means the pod has to be sent to fault. - /// - /// "Fatal" is about the **pod**, not about this process: the backend - /// stays up — still reading its other connections, still serving the - /// frontend, still recording — so that whoever is operating the pod - /// can see what happened. Nothing here ever calls - /// `std::process::exit`. - /// - /// Only [`Error::Decode`] qualifies, and this is the one place where - /// the behaviour deliberately departs from the Go backend. Go treated - /// an undecodable frame as a connection that had fallen out of step, - /// and reconnecting was the remedy. But nothing corrupts a frame in - /// flight — TCP checksums and retransmits — so a frame that will not - /// decode means the loaded ADJ does not match what the firmware is - /// sending, and reopening the connection cannot fix that. The stream - /// still cannot be resynchronised mid-frame, so the connection is - /// closed and reopened anyway; what changes is that the pod is also - /// sent to fault instead of carrying on as if a retry would help. - /// - /// [`Error::Connect`] and [`Error::Write`] are not fatal: a board - /// that is not up yet, or a write that failed on a connection that - /// just dropped, is exactly what the reconnection loop with its - /// backoff is for. Losing a board for good is reported through - /// [`super::Event::Disconnected`], not through this. - pub fn is_fatal(&self) -> bool { - match self { - Error::Decode { .. } => true, - Error::Connect { .. } | Error::Write { .. } => false, - } - } -} +#[cfg(test)] +mod test_support; #[cfg(test)] mod tests { use super::*; - fn io_error() -> std::io::Error { - std::io::Error::from(std::io::ErrorKind::ConnectionRefused) + #[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 a_frame_that_will_not_decode_faults_the_pod() { - let error = Error::Decode { - board: BoardId(3), - source: DecodeError::UnknownId(crate::model::AdjId(9999)), - }; + 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)); + } + } + } - // Not a desynchronised stream to retry: the ADJ does not match - // the firmware, and reconnecting cannot fix that. - assert!(error.is_fatal()); + #[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 a_board_that_is_not_up_yet_does_not_fault_the_pod() { - let connect = Error::Connect { - board: BoardId(3), - source: io_error(), - }; - let write = Error::Write { - board: BoardId(3), - source: io_error(), - }; + 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)); + } + } + } - // That is what the reconnection backoff is for. - assert!(!connect.is_fatal()); - assert!(!write.is_fatal()); + #[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 an_error_says_which_board_it_was() { - let error = Error::Write { - board: BoardId(3), - source: io_error(), - }; + 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)); + } + } + } - // The identity survives being formatted, which is what reaches - // the operator. - assert!(error.to_string().contains("BoardId(3)")); + #[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..e2920eb77 --- /dev/null +++ b/backend/crates/core/src/net/tcp/README.md @@ -0,0 +1,225 @@ +# `net::tcp` — reconnecting TCP clients (feature `net`) + +TCP is a client with one independently reconnecting connection per configured board. It receives messages, protections and reserved fault frames, 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, received protections and received faults never trigger a broadcast automatically. See the [parent module](../README.md) for shared reporting types, channel semantics and the status of other transports. + +## Public API + +| Entry point / type | Purpose | +| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------ | +| `tcp::spawn(TcpConfig, Arc, Reporter) -> BoardClients` | Start configured clients without waiting for connections. Requires a Tokio runtime. | +| `tcp::spawn_managed(TcpConfig, Arc, Reporter) -> (BoardClients, TcpTasks)` | Start clients and retain ownership of their supervisors. | +| `TcpTasks::shutdown().await` | Cancel the supervisors and wait for cleanup. | +| `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()` | Attempt fault writes on all configured boards and report unconfirmed writes. | +| `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 TCP error publication are internal. Applications use `BoardClients` to route orders to their declared destinations. + +## 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. + +See [station's startup settings](../../../../station/src/event/README.md) for the actual board selection, local ports and timing defaults used by the binary. + +`Reporter::channels(notifications, errors)` returns the `Reporter` passed to `tcp::spawn` or `tcp::spawn_managed` and a `Sinks` value kept by the application: + +- `sinks.notifications` receives board lifecycle events and decoded packets (`Notification`). +- `sinks.errors` receives transport failures and board fault signals (`ErrorReport`), wrapped as `net::Error::Tcp(TcpError::...)`. The direct result of an order send uses `SendError`. + +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 (clients, tasks) = tcp::spawn_managed(config, index, reporter); + let application = async { + // For each fresh application command, call: + // clients.send(order).await? confirms a complete socket write. + // Call clients.broadcast_fault().await 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(); + tasks.shutdown().await; + drop(clients); + result +} +``` + +Both spawn functions return before connecting. Wait for the destination's `Connected` event before attempting an order. The connection may still end before the send, so handle every result. After a write failure or timeout, firmware may already have received some or all of the order. The application should avoid automatically retrying 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 + +At each frame boundary, TCP recognises reserved bytes `00 00` as a complete +fault before consulting the ADJ. A split ID waits for its second byte. Each fault +is published as `TcpError::Fault { board }` on the error channel, including +repeats; no `Received` notification is generated for it. Reporting waits for +error-channel capacity. The session remains open and continues parsing any +following frames, without automatically broadcasting a fault. `is_fatal()` is +false for this report: application policy decides whether to propagate the board +fault or show it to the operator. Zeros inside ordinary frames are payload, not +separate faults. + +For ordinary packets, 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. With `spawn_managed`, the owner can also call `TcpTasks::shutdown().await` to cancel any remaining supervisors and join them. Dropping `TcpTasks` requests cancellation without waiting. 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, reserved fault recognition 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, reserved faults and reporting 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 and event fixtures live in [test_support.rs](test_support.rs). Its `writes` module contains the controlled `AsyncWrite` fixture. Manual probes live in [manual_tests.rs](manual_tests.rs) and are ignored by default. + +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 +``` + +The three manual probes below require `ADJ_DIR` and `TCP_BOARD`. `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, 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..e12aea384 --- /dev/null +++ b/backend/crates/core/src/net/tcp/error.rs @@ -0,0 +1,201 @@ +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 { + /// The board sent the reserved fault frame (`00 00`). + /// Reported without ending the session or triggering an automatic broadcast. + #[error("board {board:?}: signalled a fault (packet id 0)")] + Fault { + /// The board identified by this TCP connection. + board: BoardId, + }, + /// 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. [`TcpError::Fault`] also returns false: + /// it reports a board fault without stopping transport. 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 { .. } + | TcpError::Fault { .. } => 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..3896c3c2a --- /dev/null +++ b/backend/crates/core/src/net/tcp/framing.rs @@ -0,0 +1,335 @@ +//! 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; + +/// A reserved fault or an ADJ-dependent message/protection frame. +#[derive(Debug, Clone, PartialEq)] +pub(super) enum Frame { + Fault, + Packet(TcpFrame), +} + +/// Extracts one complete frame, advancing `pending` only after recognition. +/// +/// Reserved bytes `00 00` form a complete fault frame at a frame boundary, +/// before consulting the ADJ. A single zero byte remains pending. +/// +/// 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); + } + + if pending.starts_with(&[0, 0]) { + pending.advance(2); + return Ok(Some(Frame::Fault)); + } + + 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::Packet(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 reserved_faults_need_two_bytes_but_no_adj_definition() { + let index = Index::default(); + let mut pending = BytesMut::from(&[0][..]); + assert_eq!(next_frame(&mut pending, &index), Ok(None)); + assert_eq!(&pending[..], &[0]); + + // A whole fault followed by the first byte of another fault. + pending.extend_from_slice(&[0, 0]); + assert_eq!(next_frame(&mut pending, &index), Ok(Some(Frame::Fault))); + assert_eq!(&pending[..], &[0]); + assert_eq!(next_frame(&mut pending, &index), Ok(None)); + pending.extend_from_slice(&[0]); + assert_eq!(next_frame(&mut pending, &index), Ok(Some(Frame::Fault))); + assert!(pending.is_empty()); + } + + #[test] + fn faults_can_surround_ordinary_frames_without_consuming_their_payloads() { + let (index, frames) = sample_frames(); + let mut pending = BytesMut::from(&[0, 0][..]); + for (_, bytes) in &frames { + pending.extend_from_slice(bytes); + pending.extend_from_slice(&[0, 0]); + } + assert_eq!(next_frame(&mut pending, &index), Ok(Some(Frame::Fault))); + for (frame, _) in frames { + assert_eq!( + next_frame(&mut pending, &index), + Ok(Some(Frame::Packet(frame))) + ); + assert_eq!(next_frame(&mut pending, &index), Ok(Some(Frame::Fault))); + } + assert!(pending.is_empty()); + + // Zeros inside an undecodable frame are not a resynchronisation point. + pending.extend_from_slice(&[0xff, 0xff, 0, 0]); + assert_eq!(next_frame(&mut pending, &index), Ok(None)); + assert_eq!(&pending[..], &[0xff, 0xff, 0, 0]); + } + + #[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::Packet(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::Packet(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)? { + let Frame::Packet(frame) = frame else { + unreachable!("ordinary fixture frames"); + }; + 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(Frame::Packet(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(Frame::Packet(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(Frame::Packet(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::Packet(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::Packet(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::Packet(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::Packet(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..36ac5237a --- /dev/null +++ b/backend/crates/core/src/net/tcp/reader.rs @@ -0,0 +1,538 @@ +//! Reading and reporting 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 packet or fault failed because its reporting consumer is gone. + /// The owner must stop rather than reconnect to an absent consumer. + ConsumerClosed, +} + +/// Reads 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. +/// +/// Full reporting channels apply 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. +/// +/// Ordinary packets emit `Received` notifications. Reserved fault frames (`00 00`) +/// publish [`TcpError::Fault`] on the error channel without ending the session. +/// The session owner handles transport failures, connection events and disposal +/// of both socket halves. This function does not reconnect, write orders or +/// decide to fault the pod. No ordering is promised across the two report queues. +/// +/// # 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 { + framing::Frame::Fault => { + tracing::debug!(?board, "TCP board signalled a fault"); + if reporter.report(TcpError::Fault { board }).await.is_err() { + return Ok(ReceiveEnd::ConsumerClosed); + } + continue; + } + framing::Frame::Packet(TcpFrame::Message(message)) => { + (message.id, Packet::Message(message)) + } + framing::Frame::Packet(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_faults_and_keeps_the_session_usable_for_later_packets() -> TestResult { + timeout(TEST_TIMEOUT, async { + let (index, frames) = sample_frames(); + let (reader, _writer, mut peer) = connected_pair().await?; + let (reporter, mut sinks) = Reporter::channels(4, 4); + let reading = tokio::spawn(async move { + receive(reader, BoardId(42), &index, &reporter).await + }); + + peer.write_all(&[0, 0]).await?; + let fault = sinks.errors.recv().await.ok_or("missing fault report")?; + let crate::net::Error::Tcp(error) = fault.error else { + unreachable!("TCP reports its own error type"); + }; + assert!(matches!(error, TcpError::Fault { board: BoardId(42) })); + assert!(!error.is_fatal()); + assert!(!reading.is_finished(), "a board fault does not end the session"); + let mut byte = [0]; + assert!(matches!(peer.try_read(&mut byte), Err(error) if error.kind() == io::ErrorKind::WouldBlock), + "the reader must not automatically echo or broadcast a fault"); + + let mut bytes = Vec::new(); + for (_, encoded) in &frames { + bytes.extend_from_slice(encoded); + } + bytes.extend_from_slice(&[0, 0]); + peer.write_all(&bytes).await?; + peer.shutdown().await?; + assert_eq!(reading.await??, ReceiveEnd::PeerClosed); + for (expected, _) in frames { + let notification = sinks.notifications.recv().await.ok_or("missing packet")?; + assert_eq!(notification.board, BoardId(42)); + assert!(matches!(notification.event, Event::Received(packet) if packet == expected)); + } + let fault = sinks.errors.recv().await.ok_or("missing repeated fault")?; + assert!(matches!(fault.error, crate::net::Error::Tcp(TcpError::Fault { board: BoardId(42) }))); + assert!(sinks.notifications.try_recv().is_err()); + assert!(sinks.errors.try_recv().is_err()); + Ok(()) + }).await? + } + + #[tokio::test] + async fn faults_wait_for_error_capacity_or_stop_when_the_consumer_closes() -> TestResult { + for close_consumer in [false, true] { + let (reader, _writer, mut peer) = connected_pair().await?; + let (reporter, mut sinks) = Reporter::channels(1, 1); + reporter + .report(TcpError::Fault { board: BoardId(9) }) + .await?; + peer.write_all(&[0, 0]).await?; + peer.shutdown().await?; + let index = Index::default(); + let reading = receive(reader, BoardId(42), &index, &reporter); + tokio::pin!(reading); + assert!( + timeout(Duration::from_millis(20), &mut reading) + .await + .is_err() + ); + + if close_consumer { + sinks.errors.close(); + assert_eq!( + timeout(TEST_TIMEOUT, reading).await??, + ReceiveEnd::ConsumerClosed + ); + } else { + sinks.errors.recv().await.ok_or("missing queued fault")?; + assert_eq!( + timeout(TEST_TIMEOUT, reading).await??, + ReceiveEnd::PeerClosed + ); + let fault = sinks + .errors + .recv() + .await + .ok_or("missing fault after backpressure")?; + assert!(matches!( + fault.error, + crate::net::Error::Tcp(TcpError::Fault { board: BoardId(42) }) + )); + } + assert!(sinks.notifications.try_recv().is_err()); + } + Ok(()) + } + + #[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..bffa6a813 --- /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. Dropping BoardClients 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