diff --git a/architecture/relay.md b/architecture/relay.md index a88c9770..8ededbec 100644 --- a/architecture/relay.md +++ b/architecture/relay.md @@ -11,7 +11,7 @@ facade, never this crate directly. | File | Role | |---|---| -| `crates/eggress-relay/src/lib.rs` | Entire crate: `RelayOptions` (`new`/`try_new`/`bounded`), `InvalidRelayOptions`, `HalfClosePolicy`, `RelayReport`/`RelayTermination`/`RelaySide`, `RelayFailure`/`RelayDirection`, `relay()`/`relay_with_options()`, inline unit tests | +| `crates/eggress-relay/src/lib.rs` | Entire crate: `RelayOptions` (`new`/`try_new`/`bounded`), `InvalidRelayOptions`, `HalfClosePolicy`, `RelayReport`/`RelayTermination`/`RelaySide`, `RelayIdleTimeoutOutcome`, `RelayFailure`/`RelayDirection`, `relay()`/`relay_with_options()`/`relay_with_idle_timeout()`, inline unit tests | | `crates/eggress-relay/README.md` | Direct-consumer usage and the `eggress-embed` distinction | | `crates/eggress-core/src/relay.rs` | Legacy facade: unchanged `RelayResult`/`TerminationReason`/`relay(BoxStream, BoxStream)`, explicit 64 KiB + one-second options, rich-to-legacy mapping (not part of this crate) | @@ -45,6 +45,11 @@ pub struct RelayReport { pub termination: RelayTermination, } +pub enum RelayIdleTimeoutOutcome { + Completed(RelayReport), + IdleTimedOut { bytes_upstream: u64, bytes_downstream: u64 }, +} + pub enum RelayDirection { Upstream, Downstream } pub struct RelayFailure { @@ -64,6 +69,12 @@ pub async fn relay_with_options(client: C, server: S, options: RelayOption -> Result where C: AsyncRead + AsyncWrite + Unpin, S: AsyncRead + AsyncWrite + Unpin; + +pub async fn relay_with_idle_timeout( + client: C, server: S, options: RelayOptions, idle_timeout: Option +) -> Result +where C: AsyncRead + AsyncWrite + Unpin, + S: AsyncRead + AsyncWrite + Unpin; ``` Deliberately absent bounds: no `BoxStream`, no `Send`, no `'static`. The @@ -71,7 +82,9 @@ engine runs inline in the caller's task (no `tokio::spawn`), so generic streams — `TcpStream`, `UnixStream`, TLS streams, joined halves, in-memory `duplex` streams, application wrappers — work without boxing. Inside Eggress, protocol/transport boundaries still use `BoxStream`; the core facade passes -its boxes straight into this generic surface. +its boxes straight into this generic surface. Existing APIs remain unchanged. +The opt-in API's `None` disables idle timing; its timeout outcome is separate +from `RelayTermination::DrainTimedOut` and carries both directional counters. ## How it works (control flow) @@ -96,7 +109,11 @@ its boxes straight into this generic surface. 6. A drain failure returns `RelayFailure` for the surviving direction; a drain expiry drops the survivor and returns `RelayTermination::DrainTimedOut { first_closed }` with current counts. -7. Dropping the outer future drops both directional states, both streams, and +7. When enabled, a connection-wide idle deadline resets only after a + successful non-empty write in either direction. It remains active during + post-half-close draining; idle expiry returns `IdleTimedOut` with current + counters, while `DrainFor` retains its distinct `DrainTimedOut` report. +8. Dropping the outer future drops both directional states, both streams, and all owned halves — no detached task can outlive the relay. ## Half-close semantics @@ -107,7 +124,8 @@ its boxes straight into this generic surface. response is still delivered completely. - `HalfClosePolicy::DrainFor(d)` bounds that wait for peers that never answer a FIN; expiry is reported as `DrainTimedOut`, never silently as an ordinary - close. + close. It is independent from the opt-in idle deadline, which remains active + both before and after half-close. - The Eggress facade explicitly requests `DrainFor(1s)` + 64 KiB, preserving the historical server cutoff. Changing Eggress product behavior is a separate decision, never bundled into this primitive. @@ -119,6 +137,8 @@ its boxes straight into this generic surface. a distinction it cannot define deterministically). - Bounded-drain expiry → `Ok(RelayReport)` with `DrainTimedOut` (visible, not collapsed). +- Opt-in idle expiry → `Ok(RelayIdleTimeoutOutcome::IdleTimedOut)` with both + transferred-byte counts; old entry points cannot produce this outcome. - Any directional I/O error → `Err(RelayFailure)` with direction, source `io::Error` (so `ErrorKind` survives), and transferred counts. - Legacy mapping (in `eggress-core`, not here): rich close reasons pass @@ -128,10 +148,12 @@ its boxes straight into this generic surface. ## Dependency boundary -Only `tokio` (workspace features). No `eggress-*` crate, no `thiserror` -(the failure type implements `Display`/`Error` directly), no metrics, no -buffer pool (application policy), no middleware/callback/inspection hooks — -consumers needing inspection wrap their streams above this layer. +Runtime dependencies remain only `tokio` (workspace features). Tokio's +`test-util` feature is dev-only for deterministic paused-time tests. No +`eggress-*` crate, no `thiserror` (the failure type implements +`Display`/`Error` directly), no metrics, no buffer pool (application policy), +no middleware/callback/inspection hooks — consumers needing inspection wrap +their streams above this layer. ## Test coverage map @@ -144,7 +166,12 @@ All inline in `src/lib.rs` (`cargo test -p eggress-relay`): | `unbounded_drain_delivers_slow_response_after_client_half_close` | 300 ms-delayed response succeeds under default `Drain` (the regression the one-second cutoff would break) | | `bounded_drain_contrast_times_out_on_slow_response` | Same 300 ms delay under `DrainFor(50ms)` → `DrainTimedOut{Client}` | | `bounded_drain_timeout_reports_first_closed_side_and_counts` | Silent peer → bounded drain expires with side + counts, never hangs | -| `upstream_failure_reports_direction_kind_and_counts` | Scripted upstream read error → direction, `ErrorKind`, pre-failure bytes | +| `idle_timeout_none_keeps_silent_relay_open` / `zero_idle_timeout_expires_before_polling_streams` / `idle_timeout_expires_quiet_relay_with_counts_and_releases_streams` | Disabled default, immediate expiry, counter preservation, and endpoint release | +| `upstream_forwarded_bytes_reset_the_shared_idle_deadline` / `downstream_forwarded_bytes_reset_the_shared_idle_deadline` | Either direction resets the shared deadline | +| `buffered_but_unwritten_input_does_not_reset_idle_deadline` | Only successful writes count as activity | +| `idle_timeout_remains_active_during_half_close_drain` / `response_within_idle_interval_completes_after_half_close` | Idle expiry and slow half-close response behavior | +| `idle_deadline_wins_over_progress_ready_at_exact_deadline` / `drain_deadline_wins_exact_tie_with_idle_deadline` | Deterministic same-deadline precedence | +| `upstream_failure_reports_direction_kind_and_counts` / `opted_in_relay_preserves_io_failure_and_byte_counts` | Scripted I/O errors preserve direction, `ErrorKind`, and pre-failure bytes | | `downstream_failure_reports_direction_kind` | Scripted downstream read error → direction, `ErrorKind`, counts | | `tiny_buffer_preserves_content_and_counts` | 7-byte buffer over 32 KiB payload: exact content + counts | | `dropping_relay_releases_both_streams` | Drop outer future while pending → both halves released, no spawned task retains them | @@ -157,14 +184,16 @@ behavior. ## Reviewer gotchas -- One `RelayFuture` owns both complete streams and their directional states; - there are no detached direction tasks or generic split locks. +- One `RelayFuture` owns both complete streams, directional states, and both + optional deadlines; there are no detached direction tasks/timers or generic + split locks. - The relay state machine uses a bounded per-poll step budget. This avoids split-lock contention while preventing an always-ready direction from starving its peer. -- The first clean close selects the draining side. An optional `Sleep` deadline - is stored on the relay future, and timeout returns the current directional - byte counters without spawning or detaching work. +- The first clean close selects the draining side. Independent idle and + `DrainFor` `Sleep` deadlines stay on the relay future. Drain expiry wins an + exact tie; idle expiry is otherwise a distinct outcome with current + directional byte counters, without spawning or detaching work. - `BrokenPipe`/`ConnectionReset` from post-EOF `shutdown()` are tolerated exactly like the historical implementation; any other shutdown error fails the direction. diff --git a/crates/eggress-embed/tests/public_api.rs b/crates/eggress-embed/tests/public_api.rs index 4cf5fe6a..b26f88eb 100644 --- a/crates/eggress-embed/tests/public_api.rs +++ b/crates/eggress-embed/tests/public_api.rs @@ -47,14 +47,34 @@ fn outbound_authority_and_compat_reexport_paths_compile() { #[test] fn relay_routing_core_representative_paths_compile() { // `eggress-relay::{relay, RelayOptions, RelayReport}` type paths. - let options = eggress_relay::RelayOptions::default(); - assert!(options.buffer_size.get() > 0); + let options = eggress_relay::RelayOptions { + buffer_size: std::num::NonZeroUsize::new(8192).unwrap(), + half_close: eggress_relay::HalfClosePolicy::Drain, + }; + assert_eq!(options.buffer_size.get(), 8192); let report = eggress_relay::RelayReport { bytes_upstream: 0, bytes_downstream: 0, termination: eggress_relay::RelayTermination::ClientClosed, }; assert_eq!(report.bytes_upstream, 0); + let _termination_shape = match report.termination { + eggress_relay::RelayTermination::ClientClosed => 0, + eggress_relay::RelayTermination::ServerClosed => 1, + eggress_relay::RelayTermination::DrainTimedOut { .. } => 2, + }; + + // The accepted idle-timeout seam is additive and its outcome is public. + let _idle_relay = + eggress_relay::relay_with_idle_timeout::; + let _idle_outcome = eggress_relay::RelayIdleTimeoutOutcome::IdleTimedOut { + bytes_upstream: 0, + bytes_downstream: 0, + }; + let (_relay_client, _relay_server) = tokio::io::duplex(1024); + let _idle_call = + eggress_relay::relay_with_idle_timeout(_relay_client, _relay_server, options, None); + // Proves the maintained async entry point resolves without executing I/O. let _relay = eggress_relay::relay::; diff --git a/crates/eggress-relay/Cargo.toml b/crates/eggress-relay/Cargo.toml index a76d0fb9..168b38aa 100644 --- a/crates/eggress-relay/Cargo.toml +++ b/crates/eggress-relay/Cargo.toml @@ -13,5 +13,8 @@ readme = "README.md" [dependencies] tokio.workspace = true +[dev-dependencies] +tokio = { workspace = true, features = ["test-util"] } + [lints] workspace = true diff --git a/crates/eggress-relay/README.md b/crates/eggress-relay/README.md index afa10adf..05707ed2 100644 --- a/crates/eggress-relay/README.md +++ b/crates/eggress-relay/README.md @@ -34,6 +34,53 @@ where } ``` +### Optional connection-wide idle timeout + +`relay_with_idle_timeout(client, server, options, Some(duration))` is an +additive opt-in for callers that need to close a connection with no forwarded +byte progress. A successful write in either direction resets the same deadline; +reads, buffered-but-unwritten data, EOF, and shutdown do not. The deadline stays +active after a half-close and is independent of `HalfClosePolicy::DrainFor`. + +```rust +use std::time::Duration; +use tokio::io::{AsyncRead, AsyncWrite}; +use eggress_relay::{relay_with_idle_timeout, RelayIdleTimeoutOutcome, RelayOptions}; + +async fn idle_bridge(client: C, server: S) +where + C: AsyncRead + AsyncWrite + Unpin, + S: AsyncRead + AsyncWrite + Unpin, +{ + let outcome = relay_with_idle_timeout( + client, + server, + RelayOptions::default(), + Some(Duration::from_secs(30)), + ) + .await; + match outcome { + Ok(RelayIdleTimeoutOutcome::Completed(report)) => { + // Handle the existing completion report. + let _ = report; + } + Ok(RelayIdleTimeoutOutcome::IdleTimedOut { bytes_upstream, bytes_downstream }) => { + // The relay stopped after no successful forwarded write for 30 seconds. + let _ = (bytes_upstream, bytes_downstream); + } + Err(failure) => { + // Directional I/O errors remain distinct and keep their byte counts. + let _ = failure; + } + } +} +``` + +Pass `None` to disable the new timer; `Some(Duration::ZERO)` expires on the +first poll before stream I/O. Existing `relay()` and `relay_with_options()` +remain disabled and retain their existing result types. A timeout may close a +legitimate quiet stream, so consumers own the setting and choose the duration. + The default policy (`HalfClosePolicy::Drain`) waits for the opposite direction without an extra deadline, so a slow response after a client half-close is delivered. Choose diff --git a/crates/eggress-relay/src/lib.rs b/crates/eggress-relay/src/lib.rs index 9e064f2f..f24aefad 100644 --- a/crates/eggress-relay/src/lib.rs +++ b/crates/eggress-relay/src/lib.rs @@ -182,6 +182,24 @@ pub struct RelayReport { pub termination: RelayTermination, } +/// Terminal outcome of [`relay_with_idle_timeout`]. +/// +/// Idle expiry is distinct from [`RelayTermination::DrainTimedOut`]: the +/// former means no bytes were forwarded in either direction for the configured +/// interval, while the latter bounds only post-half-close draining. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RelayIdleTimeoutOutcome { + /// The relay completed according to its half-close policy. + Completed(RelayReport), + /// The connection-wide interval elapsed without forwarded-byte progress. + IdleTimedOut { + /// Bytes copied client -> server before expiry. + bytes_upstream: u64, + /// Bytes copied server -> client before expiry. + bytes_downstream: u64, + }, +} + /// Which copy direction failed. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RelayDirection { @@ -253,6 +271,38 @@ enum DirectionPoll { Failed(std::io::Error), } +/// After a successful write, let due deadlines win before extending the idle +/// interval. Drain expiry is checked first when both deadlines are due. +fn reset_idle_deadline_after_write( + cx: &mut std::task::Context<'_>, + drain_deadline: &mut Option>>, + idle_deadline: &mut Option>>, + idle_timeout: Option, +) -> bool { + let Some(idle_timeout) = idle_timeout else { + return true; + }; + + if let Some(deadline) = drain_deadline.as_mut() { + if std::future::Future::poll(deadline.as_mut(), cx).is_ready() { + return false; + } + } + + let Some(deadline) = idle_deadline.as_mut() else { + debug_assert!(false, "idle timeout has no deadline"); + return true; + }; + if std::future::Future::poll(deadline.as_mut(), cx).is_ready() { + return false; + } + + deadline + .as_mut() + .reset(tokio::time::Instant::now() + idle_timeout); + true +} + /// Poll one direction while retaining both complete streams in the parent /// future. The bounded step budget prevents a stream that is always ready from /// monopolising a poll and starving the opposite direction. @@ -260,6 +310,9 @@ fn poll_direction( mut reader: std::pin::Pin<&mut R>, mut writer: std::pin::Pin<&mut W>, state: &mut DirectionState, + drain_deadline: &mut Option>>, + idle_deadline: &mut Option>>, + idle_timeout: Option, cx: &mut std::task::Context<'_>, ) -> std::task::Poll where @@ -284,6 +337,14 @@ where state.write_pos += written; state.bytes += written as u64; made_progress = true; + if !reset_idle_deadline_after_write( + cx, + drain_deadline, + idle_deadline, + idle_timeout, + ) { + return std::task::Poll::Ready(DirectionPoll::Progress); + } continue; } std::task::Poll::Ready(Err(error)) => { @@ -356,12 +417,15 @@ struct RelayFuture { downstream: DirectionState, half_close: HalfClosePolicy, first_closed: Option, + idle_timeout: Option, + idle_deadline: Option>>, drain_deadline: Option>>, } impl RelayFuture { - fn new(client: C, server: S, options: RelayOptions) -> Self { + fn new(client: C, server: S, options: RelayOptions, idle_timeout: Option) -> Self { let buffer_size = options.buffer_size.get(); + let idle_deadline = idle_timeout.map(|duration| Box::pin(tokio::time::sleep(duration))); Self { client, server, @@ -369,6 +433,8 @@ impl RelayFuture { downstream: DirectionState::new(buffer_size), half_close: options.half_close, first_closed: None, + idle_timeout, + idle_deadline, drain_deadline: None, } } @@ -379,6 +445,33 @@ impl RelayFuture { self.drain_deadline = Some(Box::pin(tokio::time::sleep(duration))); } } + + /// Poll drain before idle so an exact tie preserves the established + /// post-half-close termination classification. + fn poll_expired(&mut self, cx: &mut std::task::Context<'_>) -> Option { + if let Some(deadline) = self.drain_deadline.as_mut() { + if std::future::Future::poll(deadline.as_mut(), cx).is_ready() { + if let Some(first_closed) = self.first_closed { + return Some(RelayIdleTimeoutOutcome::Completed(RelayReport { + bytes_upstream: self.upstream.bytes, + bytes_downstream: self.downstream.bytes, + termination: RelayTermination::DrainTimedOut { first_closed }, + })); + } + debug_assert!(false, "drain deadline fired with no first close"); + } + } + + if let Some(deadline) = self.idle_deadline.as_mut() { + if std::future::Future::poll(deadline.as_mut(), cx).is_ready() { + return Some(RelayIdleTimeoutOutcome::IdleTimedOut { + bytes_upstream: self.upstream.bytes, + bytes_downstream: self.downstream.bytes, + }); + } + } + None + } } impl std::future::Future for RelayFuture @@ -386,21 +479,48 @@ where C: AsyncRead + AsyncWrite + Unpin, S: AsyncRead + AsyncWrite + Unpin, { - type Output = Result; + type Output = Result; fn poll( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll { let this = self.get_mut(); + let had_first_closed = this.first_closed.is_some(); + + if let Some(timeout) = this.idle_timeout { + if timeout.is_zero() { + return std::task::Poll::Ready(Ok(RelayIdleTimeoutOutcome::IdleTimedOut { + bytes_upstream: this.upstream.bytes, + bytes_downstream: this.downstream.bytes, + })); + } + } + + // Preserve the legacy entry points' established ordering: without an + // idle timer, poll the surviving direction before checking DrainFor. + if this.idle_timeout.is_some() { + if let Some(outcome) = this.poll_expired(cx) { + return std::task::Poll::Ready(Ok(outcome)); + } + } if this.first_closed.is_none() { - match poll_direction( + let upstream = poll_direction( std::pin::Pin::new(&mut this.client), std::pin::Pin::new(&mut this.server), &mut this.upstream, + &mut this.drain_deadline, + &mut this.idle_deadline, + this.idle_timeout, cx, - ) { + ); + if this.idle_timeout.is_some() { + if let Some(outcome) = this.poll_expired(cx) { + return std::task::Poll::Ready(Ok(outcome)); + } + } + match upstream { std::task::Poll::Ready(DirectionPoll::Complete) => { this.start_drain(RelaySide::Client); } @@ -416,12 +536,21 @@ where } if this.first_closed.is_none() { - match poll_direction( + let downstream = poll_direction( std::pin::Pin::new(&mut this.server), std::pin::Pin::new(&mut this.client), &mut this.downstream, + &mut this.drain_deadline, + &mut this.idle_deadline, + this.idle_timeout, cx, - ) { + ); + if this.idle_timeout.is_some() { + if let Some(outcome) = this.poll_expired(cx) { + return std::task::Poll::Ready(Ok(outcome)); + } + } + match downstream { std::task::Poll::Ready(DirectionPoll::Complete) => { this.start_drain(RelaySide::Server); } @@ -442,25 +571,12 @@ where } } - if let Some(deadline) = this.drain_deadline.as_mut() { - if std::future::Future::poll(deadline.as_mut(), cx).is_ready() { - let Some(first_closed) = this.first_closed else { - debug_assert!(false, "drain deadline fired with no first close"); - return std::task::Poll::Ready(Err(RelayFailure { - direction: RelayDirection::Upstream, - source: std::io::Error::new( - std::io::ErrorKind::BrokenPipe, - "relay drain without first close", - ), - bytes_upstream: this.upstream.bytes, - bytes_downstream: this.downstream.bytes, - })); - }; - return std::task::Poll::Ready(Ok(RelayReport { - bytes_upstream: this.upstream.bytes, - bytes_downstream: this.downstream.bytes, - termination: RelayTermination::DrainTimedOut { first_closed }, - })); + // In opted-in mode, a newly-started DrainFor timer can be zero duration. + // Poll it before the surviving direction; legacy entry points retain + // their established post-direction drain check. + if !had_first_closed && this.idle_timeout.is_some() { + if let Some(outcome) = this.poll_expired(cx) { + return std::task::Poll::Ready(Ok(outcome)); } } @@ -481,26 +597,37 @@ where std::pin::Pin::new(&mut this.server), std::pin::Pin::new(&mut this.client), &mut this.downstream, + &mut this.drain_deadline, + &mut this.idle_deadline, + this.idle_timeout, cx, ), RelaySide::Server => poll_direction( std::pin::Pin::new(&mut this.client), std::pin::Pin::new(&mut this.server), &mut this.upstream, + &mut this.drain_deadline, + &mut this.idle_deadline, + this.idle_timeout, cx, ), }; + // Catch deadlines that became due during this direction poll. This is + // also the legacy entry points' established DrainFor check ordering. + if let Some(outcome) = this.poll_expired(cx) { + return std::task::Poll::Ready(Ok(outcome)); + } match remaining { std::task::Poll::Ready(DirectionPoll::Complete) => { - std::task::Poll::Ready(Ok(RelayReport { + std::task::Poll::Ready(Ok(RelayIdleTimeoutOutcome::Completed(RelayReport { bytes_upstream: this.upstream.bytes, bytes_downstream: this.downstream.bytes, termination: match first_closed { RelaySide::Client => RelayTermination::ClientClosed, RelaySide::Server => RelayTermination::ServerClosed, }, - })) + }))) } std::task::Poll::Ready(DirectionPoll::Failed(source)) => { std::task::Poll::Ready(Err(RelayFailure { @@ -529,7 +656,7 @@ where relay_with_options(client, server, RelayOptions::default()).await } -/// Relay with explicit options. +/// Relay with explicit options and no idle timeout. /// /// A single [`RelayFuture`] owns both complete streams and their two /// directional copy states. It polls bounded work from each direction in the @@ -546,12 +673,73 @@ where C: AsyncRead + AsyncWrite + Unpin, S: AsyncRead + AsyncWrite + Unpin, { - RelayFuture::new(client, server, options).await + match RelayFuture::new(client, server, options, None).await? { + RelayIdleTimeoutOutcome::Completed(report) => Ok(report), + RelayIdleTimeoutOutcome::IdleTimedOut { .. } => { + unreachable!("idle timeout is disabled for relay_with_options") + } + } +} + +/// Relay with an optional connection-wide timeout for successfully forwarded +/// byte progress. +/// +/// The connection-wide idle timer starts on the future's first poll and stays +/// active through half-close draining. Only a successful non-empty write in +/// either direction resets it; reads, buffered input, EOF, and shutdown do not. +/// `None` disables the timer; `Some(Duration::ZERO)` expires before either +/// stream is polled. At an idle deadline, timeout takes precedence over I/O or +/// progress observed in that poll. If idle and `DrainFor` deadlines are both +/// due, `DrainTimedOut` takes precedence. +/// +/// A timeout is returned as [`RelayIdleTimeoutOutcome::IdleTimedOut`] with the +/// final directional byte counts. The same future owns both streams, so +/// timeout completion and cancellation both drop them without spawning a +/// detached task. +/// +/// ```no_run +/// use std::time::Duration; +/// use tokio::io::{AsyncRead, AsyncWrite}; +/// use eggress_relay::{relay_with_idle_timeout, RelayIdleTimeoutOutcome, RelayOptions}; +/// +/// async fn bridge(client: C, server: S) +/// where +/// C: AsyncRead + AsyncWrite + Unpin, +/// S: AsyncRead + AsyncWrite + Unpin, +/// { +/// let outcome = relay_with_idle_timeout( +/// client, +/// server, +/// RelayOptions::default(), +/// Some(Duration::from_secs(30)), +/// ) +/// .await; +/// match outcome { +/// Ok(RelayIdleTimeoutOutcome::Completed(report)) => { let _ = report; } +/// Ok(RelayIdleTimeoutOutcome::IdleTimedOut { bytes_upstream, bytes_downstream }) => { +/// let _ = (bytes_upstream, bytes_downstream); +/// } +/// Err(failure) => { let _ = failure; } +/// } +/// } +/// ``` +pub async fn relay_with_idle_timeout( + client: C, + server: S, + options: RelayOptions, + idle_timeout: Option, +) -> Result +where + C: AsyncRead + AsyncWrite + Unpin, + S: AsyncRead + AsyncWrite + Unpin, +{ + RelayFuture::new(client, server, options, idle_timeout).await } #[cfg(test)] mod tests { use super::*; + use std::future::Future; use std::pin::Pin; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; @@ -565,6 +753,10 @@ mod tests { } } + async fn poll_once(future: &mut Pin>) -> Poll { + std::future::poll_fn(|cx| Poll::Ready(future.as_mut().poll(cx))).await + } + async fn relay_pair( client_payload: &[u8], server_payload: &[u8], @@ -916,6 +1108,340 @@ mod tests { } } + #[tokio::test(start_paused = true)] + async fn idle_timeout_none_keeps_silent_relay_open() { + let (_client_peer, relay_client) = tokio::io::duplex(64); + let (relay_server, _server_peer) = tokio::io::duplex(64); + let mut relay = Box::pin(relay_with_idle_timeout( + relay_client, + relay_server, + test_options(HalfClosePolicy::Drain), + None, + )); + + assert!(poll_once(&mut relay).await.is_pending()); + tokio::time::advance(Duration::from_secs(60)).await; + assert!(poll_once(&mut relay).await.is_pending()); + } + + #[tokio::test(start_paused = true)] + async fn idle_deadline_starts_on_first_poll_not_future_construction() { + let (_client_peer, relay_client) = tokio::io::duplex(64); + let (relay_server, _server_peer) = tokio::io::duplex(64); + let mut relay = Box::pin(relay_with_idle_timeout( + relay_client, + relay_server, + test_options(HalfClosePolicy::Drain), + Some(Duration::from_secs(10)), + )); + + tokio::time::advance(Duration::from_secs(60)).await; + assert!(poll_once(&mut relay).await.is_pending()); + tokio::time::advance(Duration::from_secs(9)).await; + assert!(poll_once(&mut relay).await.is_pending()); + tokio::time::advance(Duration::from_secs(1)).await; + assert!(matches!( + poll_once(&mut relay).await, + Poll::Ready(Ok(RelayIdleTimeoutOutcome::IdleTimedOut { + bytes_upstream: 0, + bytes_downstream: 0, + })) + )); + } + + #[tokio::test] + async fn zero_idle_timeout_expires_before_polling_streams() { + let client = ScriptedStream::new(Vec::new(), Some(std::io::ErrorKind::ConnectionReset)); + let server = ScriptedStream::new(Vec::new(), Some(std::io::ErrorKind::ConnectionReset)); + + let outcome = relay_with_idle_timeout( + client, + server, + test_options(HalfClosePolicy::Drain), + Some(Duration::ZERO), + ) + .await + .unwrap(); + + assert_eq!( + outcome, + RelayIdleTimeoutOutcome::IdleTimedOut { + bytes_upstream: 0, + bytes_downstream: 0, + } + ); + } + + #[tokio::test(start_paused = true)] + async fn idle_timeout_expires_quiet_relay_with_counts_and_releases_streams() { + let drops = Arc::new(AtomicUsize::new(0)); + let (client_peer, relay_client) = tokio::io::duplex(64); + let (relay_server, server_peer) = tokio::io::duplex(64); + let client = DropCounted { + inner: relay_client, + drops: Arc::clone(&drops), + }; + let server = DropCounted { + inner: relay_server, + drops: Arc::clone(&drops), + }; + let mut relay = Box::pin(relay_with_idle_timeout( + client, + server, + test_options(HalfClosePolicy::Drain), + Some(Duration::from_secs(5)), + )); + + assert!(poll_once(&mut relay).await.is_pending()); + tokio::time::advance(Duration::from_secs(5)).await; + let outcome = poll_once(&mut relay).await; + assert!(matches!( + outcome, + Poll::Ready(Ok(RelayIdleTimeoutOutcome::IdleTimedOut { + bytes_upstream: 0, + bytes_downstream: 0, + })) + )); + drop(relay); + assert_eq!(drops.load(Ordering::SeqCst), 2); + drop((client_peer, server_peer)); + } + + #[tokio::test(start_paused = true)] + async fn idle_deadline_wins_over_progress_ready_at_exact_deadline() { + let (mut client_peer, relay_client) = tokio::io::duplex(64); + let (relay_server, _server_peer) = tokio::io::duplex(64); + let mut relay = Box::pin(relay_with_idle_timeout( + relay_client, + relay_server, + test_options(HalfClosePolicy::Drain), + Some(Duration::from_secs(5)), + )); + + assert!(poll_once(&mut relay).await.is_pending()); + tokio::time::advance(Duration::from_secs(5)).await; + client_peer.write_all(b"late").await.unwrap(); + + let outcome = poll_once(&mut relay).await; + assert!(matches!( + outcome, + Poll::Ready(Ok(RelayIdleTimeoutOutcome::IdleTimedOut { + bytes_upstream: 0, + bytes_downstream: 0, + })) + )); + } + + #[tokio::test(start_paused = true)] + async fn upstream_forwarded_bytes_reset_the_shared_idle_deadline() { + let (mut client_peer, relay_client) = tokio::io::duplex(64); + let (relay_server, mut server_peer) = tokio::io::duplex(64); + let mut relay = Box::pin(relay_with_idle_timeout( + relay_client, + relay_server, + test_options(HalfClosePolicy::Drain), + Some(Duration::from_secs(10)), + )); + + assert!(poll_once(&mut relay).await.is_pending()); + tokio::time::advance(Duration::from_secs(9)).await; + client_peer.write_all(b"u").await.unwrap(); + assert!(poll_once(&mut relay).await.is_pending()); + let mut forwarded = [0; 1]; + server_peer.read_exact(&mut forwarded).await.unwrap(); + assert_eq!(&forwarded, b"u"); + + tokio::time::advance(Duration::from_secs(9)).await; + assert!(poll_once(&mut relay).await.is_pending()); + tokio::time::advance(Duration::from_secs(2)).await; + let outcome = poll_once(&mut relay).await; + assert!(matches!( + outcome, + Poll::Ready(Ok(RelayIdleTimeoutOutcome::IdleTimedOut { + bytes_upstream: 1, + bytes_downstream: 0, + })) + )); + } + + #[tokio::test(start_paused = true)] + async fn downstream_forwarded_bytes_reset_the_shared_idle_deadline() { + let (mut client_peer, relay_client) = tokio::io::duplex(64); + let (relay_server, mut server_peer) = tokio::io::duplex(64); + let mut relay = Box::pin(relay_with_idle_timeout( + relay_client, + relay_server, + test_options(HalfClosePolicy::Drain), + Some(Duration::from_secs(10)), + )); + + assert!(poll_once(&mut relay).await.is_pending()); + tokio::time::advance(Duration::from_secs(9)).await; + server_peer.write_all(b"d").await.unwrap(); + assert!(poll_once(&mut relay).await.is_pending()); + let mut forwarded = [0; 1]; + client_peer.read_exact(&mut forwarded).await.unwrap(); + assert_eq!(&forwarded, b"d"); + + tokio::time::advance(Duration::from_secs(9)).await; + assert!(poll_once(&mut relay).await.is_pending()); + tokio::time::advance(Duration::from_secs(2)).await; + let outcome = poll_once(&mut relay).await; + assert!(matches!( + outcome, + Poll::Ready(Ok(RelayIdleTimeoutOutcome::IdleTimedOut { + bytes_upstream: 0, + bytes_downstream: 1, + })) + )); + } + + #[tokio::test(start_paused = true)] + async fn buffered_but_unwritten_input_does_not_reset_idle_deadline() { + let (mut client_peer, relay_client) = tokio::io::duplex(8); + // Keep the one-byte server-side buffer full so the second byte remains + // buffered in the relay without a successful destination write. + let (relay_server, _server_peer) = tokio::io::duplex(1); + let mut relay = Box::pin(relay_with_idle_timeout( + relay_client, + relay_server, + test_options(HalfClosePolicy::Drain), + Some(Duration::from_secs(10)), + )); + + assert!(poll_once(&mut relay).await.is_pending()); + client_peer.write_all(b"a").await.unwrap(); + assert!(poll_once(&mut relay).await.is_pending()); + tokio::time::advance(Duration::from_secs(9)).await; + + client_peer.write_all(b"b").await.unwrap(); + assert!(poll_once(&mut relay).await.is_pending()); + tokio::time::advance(Duration::from_secs(2)).await; + let outcome = poll_once(&mut relay).await; + assert!(matches!( + outcome, + Poll::Ready(Ok(RelayIdleTimeoutOutcome::IdleTimedOut { + bytes_upstream: 1, + bytes_downstream: 0, + })) + )); + } + + #[tokio::test(start_paused = true)] + async fn idle_timeout_remains_active_during_half_close_drain() { + let (mut client_peer, relay_client) = tokio::io::duplex(64); + let (relay_server, mut server_peer) = tokio::io::duplex(64); + let mut relay = Box::pin(relay_with_idle_timeout( + relay_client, + relay_server, + test_options(HalfClosePolicy::Drain), + Some(Duration::from_secs(10)), + )); + + client_peer.write_all(b"req").await.unwrap(); + client_peer.shutdown().await.unwrap(); + assert!(poll_once(&mut relay).await.is_pending()); + let mut request = [0; 3]; + server_peer.read_exact(&mut request).await.unwrap(); + assert_eq!(&request, b"req"); + + tokio::time::advance(Duration::from_secs(10)).await; + let outcome = poll_once(&mut relay).await; + assert!(matches!( + outcome, + Poll::Ready(Ok(RelayIdleTimeoutOutcome::IdleTimedOut { + bytes_upstream: 3, + bytes_downstream: 0, + })) + )); + } + + #[tokio::test(start_paused = true)] + async fn response_within_idle_interval_completes_after_half_close() { + let (mut client_peer, relay_client) = tokio::io::duplex(64); + let (relay_server, mut server_peer) = tokio::io::duplex(64); + let mut relay = Box::pin(relay_with_idle_timeout( + relay_client, + relay_server, + test_options(HalfClosePolicy::Drain), + Some(Duration::from_secs(10)), + )); + + client_peer.write_all(b"req").await.unwrap(); + client_peer.shutdown().await.unwrap(); + assert!(poll_once(&mut relay).await.is_pending()); + let mut request = [0; 3]; + server_peer.read_exact(&mut request).await.unwrap(); + assert_eq!(&request, b"req"); + + tokio::time::advance(Duration::from_secs(9)).await; + assert!(poll_once(&mut relay).await.is_pending()); + server_peer.write_all(b"ok").await.unwrap(); + server_peer.shutdown().await.unwrap(); + let outcome = poll_once(&mut relay).await; + let report = match outcome { + Poll::Ready(Ok(RelayIdleTimeoutOutcome::Completed(report))) => report, + other => panic!("expected successful half-close completion, got {other:?}"), + }; + let mut response = [0; 2]; + client_peer.read_exact(&mut response).await.unwrap(); + assert_eq!(&response, b"ok"); + assert_eq!(report.bytes_upstream, 3); + assert_eq!(report.bytes_downstream, 2); + assert_eq!(report.termination, RelayTermination::ClientClosed); + } + + #[tokio::test(start_paused = true)] + async fn drain_deadline_wins_exact_tie_with_idle_deadline() { + let (mut client_peer, relay_client) = tokio::io::duplex(64); + let (relay_server, _server_peer) = tokio::io::duplex(64); + let mut relay = Box::pin(relay_with_idle_timeout( + relay_client, + relay_server, + test_options(HalfClosePolicy::DrainFor(Duration::from_secs(5))), + Some(Duration::from_secs(5)), + )); + + client_peer.shutdown().await.unwrap(); + assert!(poll_once(&mut relay).await.is_pending()); + tokio::time::advance(Duration::from_secs(5)).await; + let outcome = poll_once(&mut relay).await; + let report = match outcome { + Poll::Ready(Ok(RelayIdleTimeoutOutcome::Completed(report))) => report, + other => panic!("expected drain timeout to win the tie, got {other:?}"), + }; + assert_eq!(report.bytes_upstream, 0); + assert_eq!(report.bytes_downstream, 0); + assert_eq!( + report.termination, + RelayTermination::DrainTimedOut { + first_closed: RelaySide::Client, + } + ); + } + + #[tokio::test] + async fn opted_in_relay_preserves_io_failure_and_byte_counts() { + let client = ScriptedStream::new( + b"partial".to_vec(), + Some(std::io::ErrorKind::ConnectionReset), + ); + let server = ScriptedStream::new(Vec::new(), None); + let failure = relay_with_idle_timeout( + client, + server, + test_options(HalfClosePolicy::Drain), + Some(Duration::from_secs(10)), + ) + .await + .expect_err("I/O failure remains distinct from idle expiry"); + + assert_eq!(failure.direction, RelayDirection::Upstream); + assert_eq!(failure.source.kind(), std::io::ErrorKind::ConnectionReset); + assert_eq!(failure.bytes_upstream, 7); + assert_eq!(failure.bytes_downstream, 0); + } + #[tokio::test] async fn dropping_relay_releases_both_streams() { let drops = Arc::new(AtomicUsize::new(0)); diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index a052d589..e1cf069c 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -160,6 +160,12 @@ maintainer-authorized Eggress release. Source implementation/closure does not itself authorize a version bump or tag. +### Conditionally closed maintenance — optional relay no-progress timeout + +[Issue #10](https://github.com/eggstack/eggress/issues/10) requests an opt-in no-progress timeout at the generic relay API. The source implementation is complete under accepted [ADR-0003](../plans/adrs/ADR-0003-relay-idle-timeout-semantics.md); see the [subsystem roadmap](../plans/subsystems/proxy-core-relay-roadmap.md), [implementation plan](../plans/implementation/proxy-core-relay/003-optional-relay-idle-timeout.md), and [closure record](../plans/closure/proxy-core-relay/003-status.md). + +The additive API is implemented and existing relay calls remain disabled and source-compatible. Closure remains conditional pending a separately authorized compatible release and the downstream adoption handoff; the workspace verification gate passes on the reconciled tree (2026-11-28). No release or downstream issue was created. After a compatible API release is separately authorized and published, the plan calls for linked Eggchaos config-adoption and Eggtunnel exact-pin/adoption issues (with its existing `relay_drain` kept separate). + ## Completed Milestones ### Phase 1: Core TCP proxy foundation diff --git a/docs/RUST_API.md b/docs/RUST_API.md index bb87642d..c7d86182 100644 --- a/docs/RUST_API.md +++ b/docs/RUST_API.md @@ -12,7 +12,7 @@ existing public items. | Full in-process service lifecycle | `eggress-embed::{EggressConfig, EggressService, EggressHandle}` | | Listener-free outbound chains | `eggress-outbound::OutboundConnector` | | Existing full-service imports | `eggress_embed::outbound::*` compatibility re-export | -| Generic relay between connected streams | `eggress-relay::{relay, RelayOptions, RelayReport}` | +| Generic relay between connected streams | `eggress-relay::{relay, relay_with_idle_timeout, RelayOptions, RelayReport, RelayIdleTimeoutOutcome}` | | CLI and installed binaries | `eggress-cli` (`eggress` and `pproxy` targets) | `eggress-config::RuntimeConfig` crossing `eggress-embed::EggressConfig` is an @@ -77,7 +77,9 @@ Representative (not exhaustive) downstream-shaped compile contracts: - `eggress-embed/tests/public_api.rs`: embed config handoff (`EggressConfig::from_toml_str`/`from_compiled`), outbound authority (`OutboundConnector::direct`/`from_chain`) plus `eggress_embed::outbound` - compatibility re-export, relay/routing/core paths, plus Phase 4 + compatibility re-export, relay/routing/core paths, including an old + `RelayOptions` struct literal, exhaustive `RelayTermination` match, and the + additive `relay_with_idle_timeout`/`RelayIdleTimeoutOutcome` paths; plus Phase 4 `supporting_config_runtime_paths_compile` (`eggress-config` TOML compile, `eggress-runtime` supervisor/state/classify signatures) and `protocol_representative_paths_compile` (HTTP/SOCKS via URI + `HttpDetector`/ @@ -116,5 +118,7 @@ Representative (not exhaustive) downstream-shaped compile contracts: Compatibility re-exports (`eggress_embed::outbound::*`, server re-exports) remain covered; private implementation movement (Phases 1–2) does not change -public paths. No public item or feature changes visibility, name, location, -default, or signature in this phase. +public paths. The relay timeout is an additive opt-in surface only: existing +`RelayOptions`, `RelayReport`, `RelayTermination`, and relay function +signatures/defaults remain unchanged, and existing entry points never enable +the timeout. diff --git a/eggpack-adoption-research.md b/eggpack-adoption-research.md new file mode 100644 index 00000000..dc4b6428 --- /dev/null +++ b/eggpack-adoption-research.md @@ -0,0 +1,62 @@ +# Eggpack producer-side adoption research + +**Scope:** assess whether Eggpack should replace or augment Eggress's prebuilt CLI release packaging. Research only; no release workflow or source changes are proposed or applied here. + +## Executive finding + +Eggpack's producer contract fits Eggress's four Unix .tar.gz artifacts, including the existing two-binary archive layout. It is **not a drop-in replacement for the five-target release today**: Eggress's Windows artifact is a .zip, while Eggpack's current finalizer accepts only tar+gzip archives. Changing Windows to tar.gz would alter an established installer and self-updater contract, so it should not be done implicitly. + +**Recommendation:** keep the current release workflow authoritative. If Eggpack adoption is worth pursuing, first run a pinned, non-publishing shadow pilot for the four Unix artifacts, compare its outputs and qualification against the current pipeline, and leave Windows and the public release uploader unchanged. Do not migrate production until Eggpack supports the current Windows ZIP contract or an explicit product decision approves a Windows format change. Keep producer tooling separate from Eggress's runtime Eggup dependencies. + +## Eggress's existing contract + +The release workflow builds the eggress and pproxy CLI binaries for five targets: Linux x86_64 and AArch64, macOS x86_64 and AArch64, and Windows x86_64 MSVC. Each archive contains the two sibling executables. Four assets are named eggress-.tar.gz; Windows is eggress-x86_64-pc-windows-msvc.zip. Each has an adjacent .sha256 sidecar. The tag supplies the version namespace, so the filenames intentionally do not embed the release version. These names and target mappings are also encoded in the updater (crates/eggress-cli/src/update/target.rs:8-15,63-77). + +The workflow is more than a pack command. It is tag-triggered (or manually dispatched for an existing tag), builds from that exact tag, verifies versions and CLI startup/help behavior, runs listener-bind smoke checks, verifies the complete five-archive/checksum set, stages both installer scripts, and then creates or updates the GitHub Release and uploads assets (.github/workflows/release-binaries.yml:7-16,45-89,115-153,371-440,443-526). The release preflight enforces the vX.Y.Z tag, workspace/Python/compat version lockstep, internal exact-version pins, tagged-commit identity, and a clean tree (scripts/release-preflight.sh:12-23,152-176). + +The Windows installer explicitly downloads the .zip (packaging/install.ps1:24-42). The updater consumes the same target-specific archive and checksum naming, verifies the archive before extraction, and updates eggress and pproxy together (crates/eggress-cli/src/update/eggup.rs:1-23; crates/eggress-cli/src/update/mod.rs:1-15). Its current trust path has no Eggpack manifest dependency. + +## Eggpack fit and limits + +Eggpack separates a schema-v1 distribution contract from producer execution. The contract can describe target triples/aliases, asset and checksum names, archive member paths, and installed names. Its asset forms include direct assets, bundles, and one archive containing multiple named members. The sample archive fixture demonstrates two executables as members of one .tar.gz plus a checksum sidecar; it is an illustrative fixture, not an Eggress qualification result. + +The producer core plans builds, binds logical outputs to Cargo packages/binaries, runs bounded builds and qualification, then finalizes candidate bytes under contract names and creates SHA-256 sidecars and a manifest. Its README describes candidate-format/architecture checks and identity-bound qualification evidence. The archive finalizer currently exposes only ArchiveEncoding::TarGzip, and requires the contract archive name to end in .tar.gz. It does not provide ZIP output. Thus, the contract can express Eggress's member layout, but the current producer cannot finalize the Windows archive without a format change or an out-of-band packaging path. + +Eggpack's local operator flow builds and finalizes files; local commands do not publish. Workflow generation/checking and GitHub staging are distinct CI capabilities, so adopting the producer need not grant it authority to publish a production release. Eggress would still need to retain or explicitly replace its own version preflight, exact tag/source checks, target matrix, compatibility-floor claims, runtime smoke checks, full-set/checksum gate, installer staging, and GitHub Release upload behavior. Eggpack qualification should not be treated as equivalent to those Eggress-specific release policies until tested. + +The project quickstart demonstrates installing the CLI from a Git checkout at a configured exact revision; its sample revision is explicitly a placeholder that must be replaced by an approved immutable commit. At research time, the crates.io API returned 404 for eggpack-cli and eggpack-contract, so producer-tool availability appears Git-pinned rather than registry-published. Recheck this before any implementation. Pinning a reviewed immutable revision and the workflow's third-party actions is a prerequisite, not an optional polish step. + +## Relationship to Eggup + +Eggress already uses eggup-core and eggup-archive for the updater's transactional install and safe archive extraction. eggup-eggpack is a separate, optional **consumer-side adapter**: it projects an Eggpack manifest into Eggup acquisition/deployment inputs. It is not the archive producer or a tool for creating Eggress release archives. Adding it to Eggress solely to adopt producer packaging would mix runtime and release-tooling concerns without solving the ZIP gap. A future decision to make the updater consume Eggpack manifests should be evaluated separately. + +## Low-risk adoption path + +1. Preserve the current release workflow as the production source of truth and keep all existing asset names, target mappings, installer inputs, updater behavior, and permissions unchanged. +2. If a pilot is approved, create a shadow contract and generated/checkable workflow pinned to a reviewed Eggpack commit. Give it no production release credentials or public-upload step. Start with the four Unix tarballs; keep the Windows ZIP on the existing path. +3. Compare the pilot to the current artifacts: exact filenames and sidecars, both binary members and their names, checksums, executable identity/version, listener-bind behavior, Linux glibc floor, and target/source identity. Keep Eggress's release preflight and qualification gates unless Eggpack proves equivalent coverage. +4. Require full matrix parity, including an Eggpack ZIP finalizer (or a separately approved Windows-format change), before considering production replacement. Then review workflow permissions, immutable pins, failure behavior, and manifest/consumer implications as a distinct change. + +## Decision + +**Do not replace the five-target production pipeline with Eggpack yet.** A shadow pilot is technically feasible for the four Unix tarballs and can establish value without changing the public contract. Full adoption is blocked by Windows ZIP support or an explicit, separately reviewed decision to change that contract. + +## Sources + +Local Eggress contracts: +- .github/workflows/release-binaries.yml:7-16,45-89,115-153,371-440,443-526 +- crates/eggress-cli/src/update/target.rs:8-15,63-77 +- crates/eggress-cli/src/update/eggup.rs:1-23 +- crates/eggress-cli/src/update/mod.rs:1-15 +- packaging/install.ps1:24-42 +- scripts/release-preflight.sh:12-23,152-176 + +Eggpack upstream material reviewed (accessed 2026-11-19): +- [Quickstart](https://github.com/eggstack/eggpack/blob/main/docs/quickstart.md) +- [Contract schema and conformance](https://github.com/eggstack/eggpack/blob/main/crates/eggpack-contract/README.md) +- [Producer core](https://github.com/eggstack/eggpack/blob/main/crates/eggpack-core/README.md) +- [Archive finalizer implementation](https://github.com/eggstack/eggpack/blob/main/crates/eggpack-core/src/finalization.rs) +- [CLI/workflow command reference](https://github.com/eggstack/eggpack/blob/main/crates/eggpack-cli/README.md) +- [Illustrative two-member archive fixture](https://github.com/eggstack/eggpack/blob/main/crates/eggpack-contract/tests/fixtures/egress-archive.toml) +- [eggpack-cli registry endpoint](https://crates.io/api/v1/crates/eggpack-cli) and [eggpack-contract registry endpoint](https://crates.io/api/v1/crates/eggpack-contract) (both returned 404 during this check) +- [Published eggup-eggpack 0.2.0 consumer adapter](https://crates.io/crates/eggup-eggpack/0.2.0) diff --git a/plans/adrs/ADR-0003-relay-idle-timeout-semantics.md b/plans/adrs/ADR-0003-relay-idle-timeout-semantics.md new file mode 100644 index 00000000..55bfac5a --- /dev/null +++ b/plans/adrs/ADR-0003-relay-idle-timeout-semantics.md @@ -0,0 +1,107 @@ +# ADR-0003: Optional no-progress timeout for the generic relay + +Status: accepted + +Date: 2026-11-18 + +Decision owners: project maintainers + +Related specification sections: + +- plans/000-long-term-specification.md §4.11 (published-surface stability) +- plans/001-terminology-and-domain-model.md §3 (Relay) + +Affected subsystem roadmaps: + +- plans/subsystems/proxy-core-relay-roadmap.md + +## Context + +Issue #10 requests an opt-in no-progress/idle timeout at the existing eggress-relay seam. It must be disabled when absent, preserve byte delivery, cancellation, and half-close behavior, and state whether activity is measured per direction or per connection. + +The current relay owns both streams in one future and tracks directional byte counts. RelayOptions is a public struct with public fields; RelayTermination is a public exhaustive enum. Extending either can break source compatibility for direct consumers. The crates.io reverse-dependency page currently lists eggress-core, eggress-embed, eggchaos-server, and eggtunnel. Eggchaos is the identified feature consumer; Eggtunnel exact-pins an older relay release. + +## Decision drivers + +- Keep the existing relay entry points and result contract source-compatible. +- Keep the new behavior explicitly opt-in and disabled on existing calls. +- Measure useful connection activity without restarting or duplicating the copy loop. +- Preserve exact directional byte counts and distinguish idle expiry from half-close drain expiry. +- Keep listener and product configuration policy outside the leaf relay crate. + +## Considered options + +### Option A — Add a field to RelayOptions and a variant to RelayTermination + +This is the smallest implementation diff and is easy to wire into known Eggstack consumers. However, adding a public struct field breaks downstream struct literals, and adding an enum variant breaks exhaustive matches. The published reverse-dependency list is evidence of current consumers, not proof that no other source consumers exist. + +### Option B — Add a separate opt-in API and outcome type (selected) + +Keep RelayOptions, RelayReport, RelayTermination, relay(), and relay_with_options() unchanged. Add an opt-in entry point that accepts the existing RelayOptions plus an optional idle duration, and return a new outcome type that distinguishes a normal RelayReport from IdleTimedOut with both byte counts. Share the same internal RelayFuture/state machine. + +This adds a small new public surface but avoids source-breaking existing contracts and lets old calls remain disabled without migration. + +### Option C — Wrap the existing relay future in a caller-side timeout + +This closes the streams when the wrapper is dropped, but discards the relay's final byte counts and does not provide a relay-specific terminal outcome. It also leaves each consumer to reimplement timeout/report handling. Reject. + +## Decision + +Accept Option B: add a separate, opt-in API and outcome type. Keep RelayOptions, RelayReport, RelayTermination, relay(), and relay_with_options() unchanged. The new API contract is: + +```rust +pub async fn relay_with_idle_timeout( + client: C, + server: S, + options: RelayOptions, + idle_timeout: Option, +) -> Result +``` + +RelayIdleTimeoutOutcome has Completed(RelayReport) and IdleTimedOut { bytes_upstream, bytes_downstream } cases. The exact public type definitions must follow the existing crate conventions while preserving this shape and behavior. + +The timeout is connection-wide: a successful write of one or more bytes in either direction resets the same idle deadline. Read readiness, buffered-but-unwritten input, EOF, shutdown, and timer wakeups do not count as forwarded-byte progress. The timer starts on the first poll of the opted-in relay future, not while an unpolled future is merely being constructed, and remains active after a half-close while the opposite direction drains. The existing DrainFor timer remains independent and continues to mean post-half-close drain grace. + +None disables the idle timer. Some(Duration::ZERO) expires immediately on the future's first poll, before either stream is polled and before any bytes are forwarded. For a positive duration, at any poll where the monotonic current time is at or beyond the idle deadline, IdleTimedOut takes precedence over stream I/O or progress observed on that poll; a write at or after the deadline cannot reset or rescue the expired timer. If the idle and DrainFor deadlines are both due on the same poll, the existing DrainTimedOut result takes precedence, preserving the established drain classification. If the opted-in API receives None, it completes with the existing RelayReport behavior. The normal relay APIs continue to use no idle timeout and preserve current behavior. + +Idle timeout is represented by the new API's outcome type rather than by adding a RelayTermination variant. I/O errors remain RelayFailure when observed before a deadline is due. The implementation owns both streams and returns from the same future; it must not spawn a detached timer task. + +## Consequences + +### Positive + +- Existing downstream calls, struct literals, and exhaustive matches remain source-compatible. +- Timeout outcome and transferred-byte totals remain observable. +- Eggchaos can opt in through the supported relay seam without duplicating the bidirectional copy loop. +- Eggtunnel and the Eggress compatibility facade need not change merely to remain compatible. + +### Negative + +- The new API and outcome type are slightly more surface than a field and enum variant. +- Consumers that want the feature still need a released Eggress version and their own configuration/adoption work. + +### Neutral or deferred + +- The Eggress server/core compatibility facade remains on its current behavior; no global runtime default changes. +- No pproxy compatibility claim changes. +- Downstream config and dependency changes are separate repo work tracked by follow-up issues after publication. + +## Compatibility and migration + +This is additive. Existing public types and functions remain unchanged. The new API is opt-in; no existing caller starts timing out. Eggchaos should expose its own optional runtime setting and choose the new API only when configured. Eggtunnel's existing relay_drain remains a half-close grace, not an idle timeout. Any later change to this accepted public contract requires a superseding ADR and renewed compatibility review. + +## Security and reliability implications + +An enabled idle deadline can close a legitimate but quiet application stream; callers choose the duration, and the default remains disabled. Reset only after successful writes so pending writes cannot keep a stalled relay alive. On expiry, preserve byte counters, drop both streams through normal future completion, and keep cancellation behavior equivalent to the current engine. Do not log payloads or secret-bearing metadata. + +## Verification + +- Deterministic relay tests prove disabled behavior, connection-wide reset by either direction, expiry with exact byte counts, expiry during post-half-close drain, and immediate zero-duration expiry before stream polling. +- Exact-deadline tests prove idle expiry wins over same-poll I/O progress at or after its deadline, while DrainTimedOut wins a tie when both idle and drain deadlines are due. +- Existing transfer, half-close, drain-timeout, I/O failure, and future-drop tests continue to pass unchanged. +- Compile coverage proves existing RelayOptions literals and exhaustive RelayTermination matching remain valid. +- Eggchaos downstream issue records config propagation and outcome handling; Eggtunnel downstream issue records exact-pin adoption and whether it opts in. + +## Supersession + +None. diff --git a/plans/adrs/README.md b/plans/adrs/README.md index b5ef571d..5298ab67 100644 --- a/plans/adrs/README.md +++ b/plans/adrs/README.md @@ -4,6 +4,11 @@ This directory contains durable decisions that affect Eggress architecture acros Pre-existing product/compat decision records live under `docs/adr/` (e.g. SSH upstream parity, QUIC/H3 parity, SSR compatibility) in their original `ADR_.md` convention and stay where they are. New cross-cutting process or architecture decisions that govern multiple subsystems or milestones go here under the `ADR-NNNN` convention below. +Current `plans/adrs/` records: + +- `ADR-0001-planning-conventions.md` (accepted) — codegg-style planning hierarchy. +- `ADR-0003-relay-idle-timeout-semantics.md` (accepted) — additive API and connection-wide no-progress semantics for eggress-relay. + Use an ADR when a question cannot be answered safely inside one implementation plan without establishing a reusable architectural contract. ## Naming diff --git a/plans/closure/proxy-core-relay/003-status.md b/plans/closure/proxy-core-relay/003-status.md new file mode 100644 index 00000000..fae2f558 --- /dev/null +++ b/plans/closure/proxy-core-relay/003-status.md @@ -0,0 +1,142 @@ +# Proxy Core and Relay Milestone 003 — Closure Status + +Status: conditionally closed + +Source implementation plan: + +- [`plans/implementation/proxy-core-relay/003-optional-relay-idle-timeout.md`](../../implementation/proxy-core-relay/003-optional-relay-idle-timeout.md) + +Source subsystem roadmap: + +- [`plans/subsystems/proxy-core-relay-roadmap.md`](../../subsystems/proxy-core-relay-roadmap.md) + +Repository baseline reviewed: `51b37a0933861796af262b533be230419edc0b31` (also current HEAD when reviewed) + +Reconciliation baseline: `730468c` (`origin/main`, 2026-11-28) + +Implementation commits or pull requests: + +- `cursor/security-hardening` relay M003 commit rebased onto `origin/main` `730468c`; no release was published. + +## 1. Executive finding + +The source-level M003 capability is implemented: the generic relay has an additive opt-in connection-wide idle timeout, distinct timeout reporting with directional byte totals, unchanged existing API types/signatures, and no changes to Eggress relay defaults. Focused relay, core, and public API checks pass. The milestone is conditionally closed because release/downstream handoff evidence is intentionally deferred until a separately authorized publication; the full workspace gate passes on the reconciled tree (section 13). + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Additive API and separate outcome; preserve published literals and exhaustive matches | `relay_with_idle_timeout`, `RelayIdleTimeoutOutcome`; `eggress-embed/tests/public_api.rs` | pass | Existing `RelayOptions` struct literal and `RelayTermination` exhaustive match compile. | +| Disabled behavior, first-poll start, and zero-duration expiry before stream polling | `idle_timeout_none_keeps_silent_relay_open`, `idle_deadline_starts_on_first_poll_not_future_construction`, `zero_idle_timeout_expires_before_polling_streams` | pass | Paused-time tests. | +| Connection-wide resets only after successful writes in either direction | Upstream/downstream reset tests; buffered-but-unwritten test | pass | Reads and buffered input do not reset the deadline. | +| Half-close drain, independent deadlines, exact tie, and exact byte counts | Half-close expiry/completion and deadline precedence tests | pass | Drain timeout remains distinct and wins its exact tie with idle expiry. | +| I/O errors and cancellation/resource release | Opted-in I/O error/count test; stream drop test | pass | Errors remain `RelayFailure`; both streams are released. | +| Workspace-wide verification | Workspace Clippy, format, and locked tests | pass (reconciled) | Reconciled tree: Clippy, formatting, and the full locked suite pass, including `direct_connect_falls_back_to_next_resolved_address`; original baseline limitations are retained in section 4. | +| Release and downstream adoption handoff | No release or downstream issues created | deferred | Follow the implementation plan after a separately authorized compatible release. | + +## 3. Production implementation evidence + +- Added `RelayIdleTimeoutOutcome::{Completed, IdleTimedOut}` and `relay_with_idle_timeout(client, server, options, idle_timeout)` in `crates/eggress-relay/src/lib.rs`. +- Integrated idle and drain deadlines in the existing shared relay future. Successful non-empty writes reset the connection-wide deadline; both streams remain owned by the caller's future. +- Retained the existing `relay()` and `relay_with_options()` signatures/results and preserved their legacy drain-check ordering. Existing Eggress/core defaults remain unchanged. +- Added Tokio `test-util` as a dev-only feature, deterministic timeout/half-close/error/drop tests, public API compatibility coverage, and crate/architecture/API documentation. +- No release version, protocol behavior, compatibility claim, downstream consumer source, or GitHub issue was changed. + +## 4. Verification executed + +### Commands run + +```bash +rustfmt --edition 2021 crates/eggress-relay/src/lib.rs crates/eggress-embed/tests/public_api.rs +cargo fmt --package eggress-relay --package eggress-embed -- --check +cargo test -p eggress-relay --locked +cargo test -p eggress-core --locked relay +cargo test -p eggress-embed --locked --test public_api +cargo clippy -p eggress-relay --all-targets --locked -- -D warnings +cargo test --workspace --locked +cargo test --workspace --locked -- --skip direct_connect_falls_back_to_next_resolved_address +cargo clippy --workspace --all-targets -- -D warnings +cargo fmt --all -- --check +git diff --check +``` + +### Results (baseline run; section 13 records the reconciled re-run) + +- Targeted formatting passed. +- `cargo test -p eggress-relay --locked`: 23 unit tests and 2 doctests passed. +- `cargo test -p eggress-core --locked relay`: 8 relay tests passed. +- `cargo test -p eggress-embed --locked --test public_api`: 5 tests passed. +- Relay-crate Clippy passed with `-D warnings`. +- `cargo clippy --workspace --all-targets -- -D warnings` failed on `unexpected cfg condition value: ssh` in `benches/tls_setup.rs:92,96`, promoted by `-D warnings`. +- `cargo fmt --all -- --check` reports a pre-existing formatting difference in the pre-existing working-tree edit `crates/eggress-cli/tests/pproxy_binary.rs`; that file was not modified for M003. +- `cargo test --workspace --locked` ran many suites but did not complete within 300 seconds; it was still running `eggress-core::connector::tests::direct_connect_falls_back_to_next_resolved_address`. The filtered command `cargo test --workspace --locked -- --skip direct_connect_falls_back_to_next_resolved_address` passed across the remaining workspace tests and doctests with that one test filtered out. The unfiltered workspace suite remained incomplete at that baseline (section 13 records the reconciled re-run). +- External interoperability suites were not run; no compatibility claim changed. No benchmark, audit, release, or downstream issue action was in scope. + +## 5. Invariant review + +- Existing public relay APIs, public struct literals, and exhaustive termination matches remain source-compatible: supported by the compile test. +- Existing calls and the core compatibility facade do not enable idle timing; quiet `None` behavior and core relay tests pass. +- `None` disables timing; zero expires before stream I/O; a positive timer begins on first poll. +- Successful writes in either direction reset the shared deadline; EOF, reads, buffered input, and shutdown do not. +- Idle timing remains active through half-close drain. `DrainFor` stays independent, with drain expiry retaining precedence on an exact tie. +- Directional byte accounting, I/O error direction/source, stream release, and cancellation ownership remain covered by focused tests. +- No detached task or timer service was introduced. + +## 6. Failure and recovery review + +The timeout is a normal terminal result and drops both streams through completion of the shared future. I/O failures remain errors with directional counts. Cancellation still drops the owning future and its streams. No persistent state, retries, or recovery protocol was added. The timeout remains opt-in because legitimate quiet streams may otherwise be closed. + +## 7. Migration and compatibility review + +This is an additive API. Existing callers require no migration; the relay core facade does not opt in. `DrainFor` retains its half-close meaning and is not reinterpreted. No compatibility manifest or pproxy claim changed. + +## 8. Security review + +No secrets, payload logging, authentication, or privilege behavior was added. The timeout outcome exposes only the existing directional byte totals. + +## 9. Documentation and operations + +Updated `crates/eggress-relay/README.md`, public rustdoc in `crates/eggress-relay/src/lib.rs`, `architecture/relay.md`, `docs/RUST_API.md`, the proxy-core subsystem roadmap, the implementation plan, `plans/registry.md`, and `docs/ROADMAP.md`. This closure record captures the test and operational boundaries. + +## 10. Unresolved findings + +Rows 1–3 are resolved on the reconciled tree (section 13); the baseline observations are retained for provenance. + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| Medium | Workspace Clippy is blocked by the `ssh` cfg warnings in the TLS benchmark. | The full lint gate is not qualified. | Resolve under an appropriately scoped maintenance change or verify after its fix. | +| Medium | Workspace formatting includes a pre-existing difference in `crates/eggress-cli/tests/pproxy_binary.rs`. | Full formatting gate is not clean; that unrelated edit was preserved. | Have its owner format/review it, then rerun the full formatting check. | +| Medium | Workspace tests exceeded the 300-second command limit in a connector test. | The full locked workspace test result is unknown. | Rerun in an environment where the connector test completes; record the complete result. | +| Low | No compatible release or downstream adoption issues exist yet. | Consumers cannot use the API from a published version, and adoption is untracked. | After separately authorized publication, open the two linked issues or record a no-action disposition per the implementation plan. | + +## 11. Roadmap disposition + +Milestone conditionally closed with post-publication operational evidence outstanding. Source implementation and the full workspace verification gate are complete; do not treat this as a published API or downstream adoption. Complete the post-publication handoff before claiming fully closed operational status. + +## 12. Registry updates + +- Mark Proxy core and relay M003 conditionally closed in `plans/registry.md` and `plans/subsystems/proxy-core-relay-roadmap.md`. +- Keep release publication and downstream issue creation as post-publication follow-ups; neither was performed. + +## 13. Reconciliation verification (2026-11-28) + +Relay M003 was rebased onto `origin/main` `730468c`. The branch's parallel +2026-11-17 security-program commits were dropped as superseded by main's +`a1e932a` and remain available at `origin/cursor/security-hardening` +(`e8fb268`). The unrelated `pproxy_binary.rs` timing edit and `eggup 0.2.0` +bump from that tip were not carried. + +Re-run on the reconciled tree: + +- `cargo fmt --all -- --check`: pass. +- `cargo clippy --workspace --all-targets -- -D warnings`: pass. +- `cargo test -p eggress-relay --locked`: 23 unit tests and 2 doctests pass. +- `cargo test -p eggress-core relay --locked`: 8 tests pass. +- `cargo test -p eggress-embed --test public_api --locked`: 5 tests pass. +- `cargo test --workspace --locked`: 3110 passed, 0 failed, including + `direct_connect_falls_back_to_next_resolved_address` (previously stalled). + +This resolves the workspace Clippy, formatting, and full-suite findings +recorded in section 10 for the reconciled tree. Status remains conditionally +closed because release publication and downstream issue handoff remain +deferred. diff --git a/plans/implementation/proxy-core-relay/003-optional-relay-idle-timeout.md b/plans/implementation/proxy-core-relay/003-optional-relay-idle-timeout.md new file mode 100644 index 00000000..d6c487f3 --- /dev/null +++ b/plans/implementation/proxy-core-relay/003-optional-relay-idle-timeout.md @@ -0,0 +1,229 @@ +# Proxy Core and Relay M003 — Optional Connection-Wide No-Progress Timeout + +Status: conditionally closed — source implementation complete; workspace verification passes (reconciled 2026-11-28); post-publication handoff remains open + +Planning baseline: branch cursor/security-hardening, commit 51b37a0933861796af262b533be230419edc0b31 + +Source roadmap: + +- plans/subsystems/proxy-core-relay-roadmap.md +- plans/000-long-term-specification.md §4.11 +- plans/001-terminology-and-domain-model.md §3 + +Applicable ADRs: + +- Accepted: plans/adrs/ADR-0003-relay-idle-timeout-semantics.md + +Primary class: capability, implemented through relay infrastructure + +Upstream request: https://github.com/eggstack/eggress/issues/10 + +## 1. Objective + +Add an additive, opt-in, connection-wide no-progress timeout to the generic eggress-relay API. It must close a stalled relay without moving the bidirectional copy loop into consumers, preserve directional byte accounting and half-close behavior, and remain disabled for all existing calls. + +ADR-0003 was accepted before implementation. The user explicitly authorized implementation in this conversation. Source work and focused validation are complete; release publication and downstream issue creation remain separate operational actions and were not performed. + +## 2. Why this milestone exists + +- Issue #10 identified a concrete consumer need and left the per-direction/per-connection semantic open; accepted ADR-0003 resolves it. +- The current relay owns both streams in one future and already tracks successful directional byte counts. +- The current DrainFor deadline begins only after EOF and is not an idle timer. +- The relay crate is a published primary Rust API; a source-compatible additive entry point is preferable to extending public struct fields or exhaustive enums. +- The repository's direct published dependency list and inspected consumer call sites are known. Downstream issue creation can be sequenced after a releasable API exists. + +### Readiness gates + +Historical implementation gates: + +1. **Complete:** ADR-0003 was accepted, including the additive API/result shape, zero-duration behavior, and exact-deadline precedence. +2. **Complete:** explicit implementation authorization was received from the user in this conversation. +3. **Complete:** the current source baseline was rechecked. The pre-existing modification in `crates/eggress-cli/tests/pproxy_binary.rs` was preserved and remains outside this change. + +## 3. Pre-implementation baseline evidence + +- RelayOptions contains public buffer_size and half_close fields: crates/eggress-relay/src/lib.rs:62-69. +- RelayFuture owns both streams, directional states, and the optional drain deadline: crates/eggress-relay/src/lib.rs:352-380. +- relay() and relay_with_options() are the public entry points: crates/eggress-relay/src/lib.rs:523-550. +- The relay engine records byte counts only after successful writes and returns them on normal completion, drain expiry, and I/O failure: architecture/relay.md, “How it works” and “Error & failure model.” +- The legacy core facade sets its own bounded drain and maps rich termination into its historical result: crates/eggress-core/src/relay.rs:44-60. +- The maintained embed public-API test exercises relay type paths: crates/eggress-embed/tests/public_api.rs:49-59. +- Registry evidence lists four direct published dependents: eggress-core and eggress-embed in this workspace, plus eggchaos-server and eggtunnel. Eggchaos has a direct RelayOptions literal and report handling; Eggtunnel has server and client relay calls and exact-pins eggress-relay 1.0.8. + +## 4. Invariants that must not regress + +- All data movement remains in the eggress-relay engine; no consumer duplicates the copy loop. +- Existing relay() and relay_with_options() retain current result types and no-timeout behavior. +- Absence of an idle timeout never closes a quiet connection. +- The timer is connection-wide and resets only after bytes are successfully forwarded in either direction. +- EOF and half-close are not idle activity. Idle timing remains active while the opposite direction drains. +- DrainFor continues to bound only post-half-close draining; it is not replaced, restarted, or reinterpreted as an idle timeout. +- Every terminal outcome preserves accurate bytes_upstream and bytes_downstream. +- Timeout completion drops both streams in the relay future; no detached timer/task survives cancellation. +- No Eggress server/core default, listener topology, protocol behavior, pproxy claim, or feature flag changes as part of this milestone. + +## 5. Scope + +### In scope + +- One additive opt-in API and a distinct result/outcome type, per accepted ADR-0003. +- One idle deadline integrated into RelayFuture and reset by forwarded bytes in either direction. +- Tests, crate README/rustdoc, architecture/relay.md, and docs/RUST_API.md updates. +- A release handoff note and linked downstream issue creation after the API is published. + +### Explicitly out of scope + +- Adding a public field to RelayOptions or a variant to RelayTermination without a separately accepted breaking-API decision. +- Enabling timeouts in relay(), relay_with_options(), eggress-core, eggress-server, or Eggress runtime defaults. +- Eggchaos or Eggtunnel source/config changes in this repository. +- Per-direction timeouts, TCP keepalive, protocol-specific heartbeat detection, a global timer service, detached tasks, metrics/logging policy, or a buffer/copy-loop rewrite. +- Version bump, tag, crate publication, or release authorization. + +## 6. Required production changes + +### Generic relay API and engine + +- Keep RelayOptions, RelayReport, RelayTermination, relay(), and relay_with_options() source-compatible. +- Add `relay_with_idle_timeout(client, server, options, idle_timeout: Option) -> Result` with the same stream bounds as `relay_with_options`. The outcome is `Completed(RelayReport)` or `IdleTimedOut { bytes_upstream: u64, bytes_downstream: u64 }`; preserve this API shape from accepted ADR-0003. +- Route old and new entry points through one internal relay future/state machine. Old entry points supply no idle deadline. +- Start the optional deadline on the first poll of the opted-in relay future, not when an unpolled future is merely constructed. Reset it only when a destination write successfully forwards one or more bytes; do not reset on read readiness, bytes merely buffered, EOF, shutdown, or timer wakeup. +- Keep the drain deadline and idle deadline independent. On any poll where the idle deadline is due, IdleTimedOut takes precedence over stream progress or I/O observed on that poll. If idle and DrainFor deadlines are both due on the same poll, preserve existing behavior by returning DrainTimedOut. Cover both rules with deterministic tests. +- Preserve the existing fair polling, write/shutdown handling, I/O failure source/direction, byte totals, and drop/cancellation behavior. +- `None` disables idle timing. `Some(Duration::ZERO)` expires on the future's first poll, before either stream is polled or any bytes are forwarded; document and test this behavior. + +### Compatibility facade and consumers + +- Do not enable the new timeout in eggress-core's legacy relay facade. Add only compatibility coverage if the new public API could affect its compilation or semantics. +- Do not add Eggress-side config: configuration belongs to the consumer that opts in. +- Add public-API compile coverage proving existing RelayOptions struct literals and existing RelayTermination matches remain valid. + +## 7. Ordered work packages + +### A — Accept and register the API decision (complete) + +Intent: close the public contract before implementation. + +Completed: ADR-0003 was accepted on 2026-11-18. It fixes the additive entry point and outcome shape, connection-wide reset semantics, zero-duration behavior, and idle/drain/progress deadline precedence. The ADR is linked from this plan and the subsystem roadmap. + +Acceptance evidence: `plans/adrs/ADR-0003-relay-idle-timeout-semantics.md` (accepted). No code work is authorized by completing this work package. + +### B — Implement the relay timer and result (complete) + +Intent: integrate the optional deadline without changing existing callers. + +Completed: added the API/outcome, shared the `RelayFuture`, reset on successful writes in either direction, preserved byte counts and half-close behavior, and retained legacy drain polling order. No detached tasks were introduced. + +Acceptance evidence: 23 relay unit tests and 2 relay doctests pass; targeted relay Clippy passes; focused core and embed API tests pass. + +### C — Document and qualify (conditionally complete) + +Intent: make the contract usable by direct consumers. + +Completed: updated crate rustdoc/README, `architecture/relay.md`, `docs/RUST_API.md`, and embed public-API compatibility coverage. + +Acceptance evidence: focused checks and the full workspace suite pass on the reconciled tree (2026-11-28), including `direct_connect_falls_back_to_next_resolved_address`; workspace Clippy and formatting are clean. The original baseline run's limitations are retained in the closure record (sections 4 and 13). + +### D — Downstream issue handoff after publication + +Intent: track consumer adoption without importing downstream code into this change. + +Required actions after a compatible Eggress release is published: + +1. Open a linked issue in eggstack/eggchaos for an optional runtime-config setting using the new relay API. Include absent/disabled default, validation, propagation through its runtime configuration/builder, both-byte-count outcome reporting, and deterministic tests. Eggchaos is the definite feature consumer identified by issue #10. +2. Open a linked issue in eggstack/eggtunnel to update its exact eggress-relay = 1.0.8 pin to the published version and decide whether to expose the new timeout in both its server and client relay paths. Preserve relay_drain as separate half-close behavior; do not silently enable the timeout. If maintainers decline the feature, record that no adoption is required and close the issue accordingly. +3. Put the resulting downstream issue URLs and the published version in the M003 closure record. Do not claim downstream adoption until those repositories complete their work. + +These issues were not created during this source implementation; they remain post-publication follow-ups. eggress-core and eggress-embed are in this workspace and do not need separate downstream repository issues. + +## 8. Failure, cancellation, and deadline semantics + +- A successful idle timeout is a normal terminal outcome for the new API, not an I/O RelayFailure. +- It returns the last committed directional byte counts and drops both streams. +- A directional read/write/shutdown error remains a RelayFailure with its existing source, direction, and byte counts. +- A half-close drain expiry remains DrainTimedOut in the existing RelayReport when it wins; the new idle outcome is distinct when the idle deadline wins. +- Dropping the caller's relay future must release both streams and the timer without spawning or detaching work. +- At or after a due idle deadline, IdleTimedOut wins over stream I/O/progress observed on that poll; a successful write at the deadline cannot rescue the relay. If idle and DrainFor are both due on the same poll, DrainTimedOut wins. Pin both rules with deterministic tests. + +## 9. Compatibility and migration + +The intended API change is additive. Existing callers do not need a source migration, and old entry points remain disabled by default. The existing Eggress compatibility facade keeps its 64 KiB buffer and one-second DrainFor setting. The API's release/version publication is separate from source closure and follows normal maintainer authorization. + +The downstream issue handoff must distinguish: + +- Eggchaos: optional feature adoption and config propagation; its ^1.0.12 requirement can resolve a compatible release, subject to its lockfile and API use. +- Eggtunnel: exact pin update is required only to compile/use the new API; the feature remains opt-in and its existing relay_drain remains unchanged. + +## 10. Required tests + +### Focused relay tests + +- New API with no idle duration remains disabled and completes a quiet/slow-response case. +- No forwarded bytes until the deadline produces IdleTimedOut with exact zero/current counters and releases both stream endpoints. `Some(Duration::ZERO)` expires before polling either stream and forwards zero bytes. +- Successful forwarded bytes in the client-to-server direction reset the shared deadline. +- Successful forwarded bytes in the server-to-client direction reset the same shared deadline. +- Buffered input without a successful write does not reset the deadline. +- The timer remains active after one side half-closes; a delayed response within the interval is delivered, while silence beyond it times out. +- DrainFor expiry and idle expiry remain distinguishable; idle expiry wins over same-poll progress at/after its deadline, while DrainTimedOut wins an exact tie between the two deadlines. +- Existing bidirectional transfer, slow half-close response, bounded drain, I/O failure, tiny buffer, and future-drop tests remain passing. + +Prefer deterministic Tokio-time tests. The current workspace Tokio feature list omits test-util; add it only as a test/dev feature if needed, not to the relay's runtime dependency surface. + +### API and integration coverage + +- Public-API compile test for old struct literals and old exhaustive enum matches. +- New API's result type is accessible through the intended published crate path. +- No Eggress server/default behavior or compatibility facade timeout changes. + +## 11. Required verification commands + +Narrow tests first: + +- cargo test -p eggress-relay +- cargo test -p eggress-core relay +- cargo test -p eggress-embed --test public_api + +Before merge: + +- cargo fmt --all -- --check +- cargo clippy --workspace --all-targets -- -D warnings +- cargo test --workspace --locked + +Do not run external pproxy/interoperability suites unless a compatibility claim changes; this plan explicitly forbids such a change. + +## 12. Documentation updates + +- crates/eggress-relay/README.md and public rustdoc examples +- architecture/relay.md +- docs/RUST_API.md +- plans/closure/proxy-core-relay/003-status.md after implementation/verification +- docs/ROADMAP.md and plans/registry.md only to reconcile actual status and release/issue handoff + +## 13. Acceptance criteria + +M003 may close only when: + +- An additive opt-in API exists and old APIs preserve disabled-by-default behavior. +- Connection-wide activity, reset conditions, first-poll timer start, half-close interaction, due-deadline precedence (including the DrainFor tie), zero-duration behavior, and outcome reporting are documented. +- Idle expiry is distinct from drain expiry and preserves byte counts. +- All focused tests and required Rust gates pass. +- Public API qualification and architecture docs are updated. +- After publication, the Eggchaos issue and Eggtunnel adoption issue (or documented no-action disposition) are linked in closure evidence. +- Release publication and downstream implementation status are stated separately from source-level completion. + +## 14. Stop conditions + +Stop and report for maintainer review if: + +- The selected design requires changing existing RelayOptions fields, RelayTermination variants, signatures, or Eggress defaults. +- The shared timer cannot preserve fair bidirectional polling, exact byte counts, or stream-drop/cancellation semantics. +- A consumer asks to reinterpret relay_drain as idle timeout or to enable the feature by default. +- Supporting the API requires listener, protocol, server-config, parity, or release scope beyond this milestone. +- An external consumer's actual source/manifest contradicts the recorded dependency evidence. + +## 15. Closure evidence required + +Record baseline/final commits; accepted ADR; before/after API contract; timeout/half-close/cancellation tests; exact focused and broad command outcomes; public API and documentation updates; any residual limitations; release status; and downstream issue URLs/dispositions. Do not state that downstream repos adopted the feature unless their changes are verified. + +## 16. Handoff notes + +Source implementation is complete and recorded in `plans/closure/proxy-core-relay/003-status.md`. Preserve the pre-existing modification in `crates/eggress-cli/tests/pproxy_binary.rs` from baseline `51b37a0`. No release was published and no downstream issues were created. After a compatible release is explicitly authorized and published, complete the Eggchaos/Eggtunnel handoff described in Work Package D; do not claim downstream adoption until verified. diff --git a/plans/registry.md b/plans/registry.md index 1964c166..61f2b71d 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -27,7 +27,7 @@ Complementary authority: `docs/ROADMAP.md` (canonical roadmap), `docs/parity/ppr | Subsystem | Status | Roadmap | Current milestone | Dependencies or blockers | |---|---|---|---|---| -| Proxy core and relay | closed | `plans/subsystems/proxy-core-relay-roadmap.md` | All milestones closed; 1.0.10 H2/pool correctives qualified | None. Historical evidence in `plans/archive/phase-records/`. | +| Proxy core and relay | conditionally closed | `plans/subsystems/proxy-core-relay-roadmap.md` | M001–M002 closed; M003 source implementation landed | Post-publication downstream handoff remains; workspace verification passes. See `plans/closure/proxy-core-relay/003-status.md`. | | Server, runtime lifecycle, and configuration | closed | `plans/subsystems/server-runtime-config-roadmap.md` | All milestones closed | None. | | Routing, health, metrics, and admin | closed | `plans/subsystems/routing-health-observability-roadmap.md` | All milestones closed; M003 CIDR/admin exposure qualified | None. | | Edge protocols | closed | `plans/subsystems/protocols-edge-roadmap.md` | All milestones closed; M003 SOCKS4/UDP/auth-transport qualified | None. | @@ -41,6 +41,7 @@ Complementary authority: `docs/ROADMAP.md` (canonical roadmap), `docs/parity/ppr | Subsystem | Milestone | Status | Implementation plan | Dependency / consumer | |---|---|---|---|---| +| Proxy core and relay | M003 optional connection-wide no-progress timeout | conditionally closed | `plans/implementation/proxy-core-relay/003-optional-relay-idle-timeout.md` | Closure: `plans/closure/proxy-core-relay/003-status.md`; post-publication issue handoff remains. | | Transports | M003 downstream-safe bounded WebSocket composition API | ready | `plans/implementation/transports/003-downstream-safe-bounded-websocket-composition-api.md` | Published v1.0.11 baseline; requested by Eggtunnel M019 to remove direct Tungstenite ownership. | | Transports | M004 TLS trust/default advisory remediation | closed | `plans/implementation/transports/004-tls-trust-and-dependency-advisory-remediation.md` | `plans/closure/transports/004-status.md` | | Transports | M005 `russh` 0.65 advisory migration | closed | `plans/implementation/transports/005-russh-065-advisory-migration.md` | `plans/closure/transports/005-status.md` | @@ -53,6 +54,10 @@ The six security-corrective plans above closed on 2026-11-16 after the coordinator broad gate. Delivery M003 landed and closed 2026-09-29 (`plans/closure/delivery/003-status.md`). +## Proposed work (not authorized for implementation) + +None at present. Proxy core and relay M003 source implementation is complete and conditionally closed pending the named verification and post-publication handoff in its closure record. + ## Current execution order and dependency gates **1.0.10 gate (closed — published 2026-09-24):** the 1.0.10 runtime/TLS implementation, package dry-run, and CI were qualified (physical H2 isolation proven by handshake counts with shared-registry control at `c5826b3`; Rust CI `36032622797` success). `v1.0.10` is tagged and published (PyPI, crates.io, GitHub Release with five CLI archives). Archive phase-records retain their original "prepared, unpublished" wording as provenance. @@ -65,6 +70,8 @@ coordinator broad gate. Delivery M003 landed and closed 2026-09-29 **Security corrective gate (closed 2026-11-16):** the 2026-11-16 audit corrective program at `plans/subsystems/security-hardening-roadmap.md` is implemented and verified. S1 removed the distrusted-root/webpki exposure and the default-graph TLS/QUIC/tokio advisories; S2 moved optional SSH to `russh 0.65.2`; S3 restored pproxy SOCKS4 full-credential semantics and enforced UDP private-egress policy after DNS; S4 canonicalized CIDR matching and added admin Host/Origin validation; S5 hardened the updater and added the advisory gate; S6 corrected the compatibility auth-reuse contract and redacted compat diagnostics. The remaining audit items are the seven `zip 6.0.0` advisories in the updater graph (owner: Delivery M004) and the unmaintained `chrono` transitive through `russh-util` on the optional `ssh` path (owner: Transports M005), both tracked as narrow, commented `deny.toml` exceptions with review by 2027-05-01. No tag or publication is authorized by these plans. +**Relay M003 gate:** ADR-0003 is accepted and source implementation is conditionally closed. Workspace-wide tests, Clippy, and formatting pass on the reconciled tree. After a compatible API release is authorized and published, open linked adoption issues for Eggchaos configuration and Eggtunnel exact-pin/adoption; do not create those issues before publication. + **Eggup updater-convergence gate (closed 2026-09-28; consumer landed 2026-09-29):** Delivery M003 is registered at `plans/implementation/delivery/003-eggup-archive-pair-self-update-adoption.md` and closed in `plans/closure/delivery/003-status.md`. Eggup Archive M001d is runtime-qualified (`eggstack/eggup@18d83de`, hosted run `36335233644`), and the required post-M001d APIs shipped as compatible registry packages: `eggup-core 0.1.2` + `eggup-archive 0.1.2` (Eggup M009 closure, `eggstack/eggup@v0.1.2`). The final Cargo dependency cutover landed against the registry versions with hosted Linux/macOS/Windows updater evidence. Eggress release/checksum/version/CLI policy remains local. ## Blocked work @@ -72,10 +79,13 @@ coordinator broad gate. Delivery M003 landed and closed 2026-09-29 - **`zip 6.0.0` / `eggup-archive` (tracked residual)** — RUSTSEC-2026-0429/-0367/-0368/-0369 and, published 2026-11-17, -0545/-0547/-0548 remain in the updater dependency graph. `eggup-archive 0.1.2` and `0.2.0` pin `zip = "6.0.0"`; an upstream Eggup release with `zip >= 9.0.0` is required. The vulnerable `extract`/`ZipStreamReader` APIs are not used by Eggup's bounded extractor and `aes-crypto` is disabled, so the advisory gate carries a narrow, commented exception with owner (Delivery M004) and review date (2027-05-01); delete it when the upstream dependency lands. - **`chrono` unmaintained / `russh-util` (tracked residual)** — RUSTSEC-2026-0543 is unmaintained (not a vulnerability) and is pulled unconditionally by `russh-util 0.52.0` through `russh 0.65.2`, the latest published and fixed SSH line. Reachable only through the optional `ssh` feature; no safe upgrade exists. Narrow, commented exception with owner (Transports M005) and review by 2027-05-01. `cargo deny --workspace check` passes on 2026-11-17 with exactly these exceptions. +No other implementation blocker. Relay M003 source work is conditionally closed pending post-publication issue handoff (see `plans/closure/proxy-core-relay/003-status.md`). + ## Closure work and current control points | Subsystem | Status | Controlling evidence | |---|---|---| +| Proxy core and relay M003 | conditionally closed | `plans/closure/proxy-core-relay/003-status.md`; post-publication downstream handoff remains | | 1.0.10 H2/pool/ALPN qualification | closed, published as `v1.0.10` (2026-09-24) | `plans/archive/phase-records/H2_PHYSICAL_SESSION_EVIDENCE_CORRECTIVE.md`, `ONE_ZERO_TEN_CLOSURE_EVIDENCE_PASS.md`, `H2_TLS_OVERRIDE_ALPN_PRESERVATION_AND_1_0_10_QUALIFICATION_CORRECTIVE.md`, `POOLED_TRANSPORT_POLICY_IDENTITY_AND_1_0_10_ROLLFORWARD.md`; implementation `c5826b3`; Rust CI `36032622797` | | Distribution/release maintenance | closed | `plans/archive/phase-records/DISTRIBUTION_AND_RELEASE_MAINTENANCE_ROADMAP.md`, `PYPI_WHEEL_MATRIX_EXPANSION.md`, `MANUAL_CRATES_IO_PUBLISHING_SIMPLIFICATION.md` | | Eggfetch 0.2 consolidation | closed | `plans/archive/phase-records/EGGFETCH_0_2_HTTP_CONNECT_CONSOLIDATION.md`, `EGGFETCH_0_2_CORRECTIVE_CLOSURE.md`, `EGGFETCH_0_2_EVIDENCE_DOCUMENTATION_CLEANUP.md` | diff --git a/plans/subsystems/proxy-core-relay-roadmap.md b/plans/subsystems/proxy-core-relay-roadmap.md index f7381efb..91deaf9e 100644 --- a/plans/subsystems/proxy-core-relay-roadmap.md +++ b/plans/subsystems/proxy-core-relay-roadmap.md @@ -1,6 +1,6 @@ # Proxy Core and Relay Roadmap -Status: closed +Status: conditionally closed — source implementation landed; workspace verification passes on the reconciled tree (2026-11-28); post-publication evidence remains Long-term references: @@ -11,6 +11,7 @@ Long-term references: Related ADRs: - `plans/adrs/ADR-0001-planning-conventions.md` (process only) +- Accepted: `plans/adrs/ADR-0003-relay-idle-timeout-semantics.md` ## 1. Purpose and ownership boundary @@ -28,10 +29,12 @@ Architecture: `architecture/relay.md`, `architecture/core.md`. ### Capabilities - Bidirectional TCP relay with byte counts feeding `SessionReport`/`SessionMetrics`. +- Optional, connection-wide no-progress timeout for direct generic-relay consumers; disabled for existing calls. ### Infrastructure - `ReplayStream`, `ProtocolDispatcher`, relay helpers, benches (`tcp_relay`). +- One optional idle deadline inside the existing relay future; no detached timer or second copy loop. ### Polish @@ -43,18 +46,21 @@ Architecture: `architecture/relay.md`, `architecture/core.md`. ## 4. Current state -Relay extraction and API stabilization complete (`REUSABLE_RELAY_EXTRACTION_AND_API_STABILIZATION.md` in archive). 1.0.10 line qualified; no active relay blocker. +Relay extraction and API stabilization are complete, and the 1.0.10 line is qualified. Issue #10 requested an optional no-progress timeout at the generic relay seam. M003 source implementation and focused qualification are complete under accepted ADR-0003; broader verification and post-publication operational handoff remain outstanding. ## 5. Target architecture -All data-plane byte movement flows through the boxed relay boundary with uniform accounting — attained. +All data-plane byte movement flows through the boxed relay boundary with uniform accounting — attained. The accepted opt-in idle deadline remains inside the leaf relay and preserves the existing relay APIs and defaults. ## 6. Dependency graph ```text -Stream/relay primitives (hard) - `--> Reusable relay extraction (hard) - `--> 1.0.10 qualification (operational) +Stream/relay primitives (hard; closed) + `--> Reusable relay extraction (hard; closed) + `--> 1.0.10 qualification (operational; closed) + `--> M003 optional idle-timeout API (conditionally closed; see closure record) + `--> published API (release not performed) + `--> Eggchaos / Eggtunnel adoption issues (post-publication) ``` ## 7. Milestones @@ -67,21 +73,37 @@ Class: infrastructure. Objective: stream/relay primitives + replay/dispatch. Exi Class: infrastructure. Objective: `eggress-relay` leaf engine with stable facade. Exit: extraction landed with benches green. Status: closed. Evidence: archive record + Git history. +### Milestone 3 — Optional connection-wide no-progress timeout + +Class: capability (relay infrastructure). + +Objective: offer an additive opt-in idle timeout at the generic relay seam without changing existing API behavior or Eggress defaults. + +Dependencies: ADR-0003 is accepted and implementation is complete. Workspace-wide verification passes on the reconciled tree (2026-11-28); publication and downstream adoption remain separate post-publication operational follow-ups. + +Deliverable boundary: one shared relay state machine, one additive opt-in API/outcome, focused tests and docs. No downstream source/config changes in this repository. + +User or operator value: direct consumers can terminate a truly stalled relay without reimplementing bidirectional copying. + +Exit conditions: timeout is connection-wide, starts on the first poll, resets only by successfully forwarded bytes in either direction, and remains distinct from DrainFor. Existing calls stay disabled. Some(Duration::ZERO) expires before stream polling; a due idle deadline beats same-poll progress, while DrainTimedOut wins if both deadlines are due together. Every outcome reports exact directional byte counts. + +Deferred work: Eggchaos configuration and Eggtunnel dependency/API adoption are tracked by linked downstream issues after publication. + ## 8. Cross-cutting requirements -Config/migration: none (no config surface). Protocol/compat: relay semantics are part of the behavior baseline; changes require differential evidence. Security: bounded buffers, no secret logging. Concurrency: half-close drain bounded. Observability: byte counts into session metrics. Performance: benches informational. Docs: `architecture/relay.md`, `architecture/core.md`. +Config/migration: the leaf relay owns no user config; consumers own optional timeout settings. Protocol/compat: no pproxy claim changes; existing relay behavior stays disabled by default. Security: bounded buffers, no secret logging. Concurrency: preserve fair polling, half-close, cancellation, and independent drain/idle deadlines. Observability: retain exact byte counts and a distinct idle outcome. Performance: avoid a second copy loop or detached timer; benches are informational. Docs: `architecture/relay.md`, `architecture/core.md`, `docs/RUST_API.md`. ## 9. Verification strategy -`cargo test -p eggress-relay`, `cargo bench --bench tcp_relay` (informational), workspace suite for broad changes. +`cargo test -p eggress-relay`, `cargo test -p eggress-core relay`, public API compile coverage, `cargo fmt --all -- --check`, workspace Clippy and locked tests for the substantial public-crate change. Add deterministic timeout/half-close/cancellation tests; benchmark only if evidence indicates material overhead. ## 10. Risks and decision points -None active. Buffer-size or pooling changes require measured evidence and an ADR-level decision, not a routine milestone. +Accepted decision: use a new entry point and outcome type rather than changing RelayOptions or RelayTermination, because those are published public contracts. ADR-0003 fixes zero-duration behavior as immediate expiry before stream polling; at/after a due idle deadline, timeout wins over same-poll progress, and DrainTimedOut wins a tie when both deadlines are due. Implementation is complete; no release or downstream issue was created. Workspace-wide tests, Clippy, and formatting pass on the reconciled tree (2026-11-28; closure record section 13). ## 11. Completion definition -Relay engine stable behind the boxed boundary with qualified 1.0.10 evidence — attained. +Relay engine stable behind the boxed boundary with qualified 1.0.10 evidence — attained. M003 source implementation is conditionally closed with a closure record; release publication and linked downstream issue handoff remain post-publication operations. ## 12. Milestone status @@ -89,3 +111,4 @@ Relay engine stable behind the boxed boundary with qualified 1.0.10 evidence — |---|---|---|---|---| | 1 | closed (historical) | archive phase records | archive phase records | — | | 2 | closed (historical) | archive `REUSABLE_RELAY_EXTRACTION_AND_API_STABILIZATION.md` | Git history + suite evidence | — | +| 3 | conditionally closed | `plans/implementation/proxy-core-relay/003-optional-relay-idle-timeout.md` | `plans/closure/proxy-core-relay/003-status.md` | Post-publication downstream issue handoff; workspace verification passes |