Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 43 additions & 14 deletions architecture/relay.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |

Expand Down Expand Up @@ -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 {
Expand All @@ -64,14 +69,22 @@ pub async fn relay_with_options<C, S>(client: C, server: S, options: RelayOption
-> Result<RelayReport, RelayFailure>
where C: AsyncRead + AsyncWrite + Unpin,
S: AsyncRead + AsyncWrite + Unpin;

pub async fn relay_with_idle_timeout<C, S>(
client: C, server: S, options: RelayOptions, idle_timeout: Option<Duration>
) -> Result<RelayIdleTimeoutOutcome, RelayFailure>
where C: AsyncRead + AsyncWrite + Unpin,
S: AsyncRead + AsyncWrite + Unpin;
```

Deliberately absent bounds: no `BoxStream`, no `Send`, no `'static`. The
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)

Expand All @@ -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
Expand All @@ -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.
Expand All @@ -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
Expand All @@ -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

Expand All @@ -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 |
Expand All @@ -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.
Expand Down
24 changes: 22 additions & 2 deletions crates/eggress-embed/tests/public_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<tokio::io::DuplexStream, tokio::io::DuplexStream>;
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::<tokio::io::DuplexStream, tokio::io::DuplexStream>;

Expand Down
3 changes: 3 additions & 0 deletions crates/eggress-relay/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,8 @@ readme = "README.md"
[dependencies]
tokio.workspace = true

[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }

[lints]
workspace = true
47 changes: 47 additions & 0 deletions crates/eggress-relay/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<C, S>(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
Expand Down
Loading
Loading