Server runtime
Source files: 50 · checked against Etemenanki 46c12e4
Etemenanki/concepts/src/runtime.rsEtemenanki/concepts/src/buffer.rsEtemenanki/concepts/src/wake.rsEtemenanki/concepts/src/core.rsEtemenanki/concepts/src/link.rsEtemenanki/concepts/tests/runtime.rsEtemenanki/concepts/tests/client.rsEtemenanki/supervisor/src/serve.rsEtemenanki/supervisor/src/guard.rsEtemenanki/supervisor/src/connector.rsEtemenanki/supervisor/src/entity/usage.rsEtemenanki/supervisor/src/track/mod.rsEtemenanki/supervisor/src/track/metered.rsEtemenanki/supervisor/src/track/pace.rsEtemenanki/supervisor/src/topology/plane.rsEtemenanki/supervisor/src/topology/inbound/mod.rsEtemenanki/supervisor/tests/tracking.rsEtemenanki/supervisor/tests/unit/track.rsEtemenanki/supervisor/tests/unit/plane.rsEtemenanki/supervisor/tests/unit/serve.rsEtemenanki/protocols/src/core/mod.rsEtemenanki/protocols/src/http/core.rsEtemenanki/protocols/src/http/protocol.rsEtemenanki/protocols/src/trojan/core.rsEtemenanki/protocols/src/trojan/protocol.rsEtemenanki/protocols/src/vless/core.rsEtemenanki/protocols/src/vmess/core.rsEtemenanki/protocols/src/anytls/core.rsEtemenanki/protocols/src/anytls/frame.rsEtemenanki/protocols/src/anytls/padding.rsEtemenanki/protocols/src/sss/core.rsEtemenanki/protocols/src/sss/protocol.rsEtemenanki/protocols/src/sss/server.rsEtemenanki/protocols/src/transports/accept.rsEtemenanki/protocols/src/transports/stream.rsEtemenanki/protocols/src/mux/demux.rsEtemenanki/protocols/src/mux/frame.rsEtemenanki/protocols/src/helpers/address.rsEtemenanki/protocols/src/ss_aead.rsEtemenanki/protocols/src/ss_legacy/core.rsEtemenanki/protocols/src/ss_2022/core.rsEtemenanki/protocols/src/ss_2022/crypto.rsEtemenanki/protocols/src/hysteria/protocol.rsEtemenanki/protocols/src/hysteria/server/inbound.rsEtemenanki/protocols/src/hysteria/server/datagrams.rsEtemenanki/protocols/src/tun/inbound.rsEtemenanki/protocols/src/tun/udp.rsEtemenanki/protocols/tests/support/pipeline.rsEtemenanki/environment/src/dial/mod.rsEtemenanki/environment/tests/integration/udp.rs
ProxyServerRuntime drives one proxied connection. It is a single hand-written Future (or, on request, a Stream) that owns three things: the client-facing transport, every outbound the connection opens, and the sans-I/O protocol core. It moves bytes between them through three buffers, each capped at BUF_SIZE and grown on demand, polls only the outbounds that actually woke, and never spawns a task. Every server protocol except SOCKS runs its traffic inside these runtimes. For HTTP, Trojan, VLESS, VMess, Shadowsocks, Shadowsocks 2022, AnyTLS, sss, Hysteria 2 and TUN connections, the rules on this page therefore decide the largest protocol frame a connection accepts (BUF_SIZE), when the runtime stops reading a side (backpressure), which outbounds one wake-up polls, how outbound failures reach the protocol, and which bytes are counted.
This page is for contributors who change concepts/src/runtime.rs, concepts/src/buffer.rs or concepts/src/wake.rs, for protocol authors who need to know exactly when their core is called and with how much room, and for anyone reading the supervisor’s serve loop. The core’s side of the contract (ProxyCoreDecode, Event, Effect, the Effects sink) is on Server core. This page covers the driver that calls it, and the last part shows who drives the driver: supervisor/src/serve.rs → drive for every stream protocol, and the Hysteria 2 and TUN inbounds for theirs.
Responsibilities
Section titled “Responsibilities”The runtime:
- reads the transport into a read buffer that grows up to
BUF_SIZE, and hands the unparsed bytes to the core; - dials an outbound when the core asks (
Effect::Open), through theConnectorit was built with; - applies the core’s effects in the order they were pushed, writing forwarded ranges to outbounds without copying them;
- reads outbounds into a scratch buffer and hands each chunk or packet to the core;
- writes whatever the core staged back to the transport;
- runs one deadline timer on the core’s behalf;
- counts the bytes it moves (
Traffic); - decides when not to read. All of its backpressure comes from that decision.
The runtime does not:
- parse or produce protocol bytes. That is the core’s job.
- choose destinations, route or resolve names. That happens inside the
Connectorand the links it returns. - keep timers of its own. Its only timer is the one the core arms with
Effect::SetDeadline, and the core hears it fire as theDeadlineevent. Some cores take a clock in their constructor:VMessCore::newtakesnow: fn() -> i64, to which the supervisor passesprotocols/src/vmess/aead.rs→now_unix, andHy2UdpCorecounts its own one-second sweep ticks fromDeadlineevents. - log. It has no
tracingcalls. Outbound failures go to the core as events, and fatal errors go to the caller as aRuntimeError, which the caller logs. - spawn. Everything a connection owns lives inside the runtime value.
Where it runs
Section titled “Where it runs”| Caller | Core | Constructor | Mode | What the caller logs when the runtime fails |
|---|---|---|---|---|
supervisor/src/serve.rs → drive, called from serve_connection |
HttpCore, TrojanCore, VlessCore, VMessCore, ShadowsocksCore, Ss2022Core, AnyTlsCore, each over Principal |
new over the accepted byte stream, with an AppConnector |
showing_progress |
debug: {protocol} connection from {source:?} ended: {e} |
supervisor/src/serve.rs → drive, called from serve_sss once sss’s gate admitted the stream |
SssCore over Principal |
new over the side of the stream that sss’s transform chains decode, with an AppConnector |
showing_progress |
as the row above |
protocols/src/hysteria/server/inbound.rs → classifier, for a proxy-request stream once the QUIC connection has authenticated |
Hy2StreamCore, one runtime per proxy stream |
new over QuicIo |
quiet | debug: hysteria2: proxy stream failed: {e} |
protocols/src/hysteria/server/inbound.rs → serve_connection, after the credential is accepted, when ServerConfig::udp is set |
Hy2UdpCore, one runtime over the connection’s datagrams |
over_datagrams over QuicDatagrams |
quiet | debug: hysteria2: datagram runtime ended: {e} |
protocols/src/tun/inbound.rs → TunInbound::run → serve_stream |
PassthroughCore (or PassthroughCore::sniffing), one runtime per TCP stream |
new over TrackedTcp |
showing_progress |
debug: tun: tcp flow {src} -> {dst} ended: {e} |
protocols/src/tun/inbound.rs → TunInbound::run, per client source socket address (IP and port) |
TunUdpCore, one runtime over that source’s UDP flows |
over_datagrams over TunUdpLink |
quiet | trace: tun: udp association of {src} ended: {e} |
In the first two rows, {protocol} is StreamProtocol::name() and {source:?} is the connector’s Option<IpAddr>; the code writes them as positional {} and {:?}.
The Hysteria 2 and TUN rows run under the supervisor too: supervisor/src/serve.rs → run_hysteria_inbound drives Hy2Inbound::run, and run_tun_inbound drives TunInbound::run over a device that TunInbound::prepare readied. The SOCKS inbound has its own driver (protocols/src/socks/server.rs → SocksInbound::serve) and does not use this runtime.
Every front end reaches these runtimes the same way, by applying a spec to a supervisor: etemenanki-app, the FFI, and katana, which at 4.10.0 has no serving code of its own. See Listeners and the serve loop.
Admission a caller holds for a runtime’s life
Section titled “Admission a caller holds for a runtime’s life”The runtime itself enforces no connection or flow limit. The callers that have one take a permit before they build the runtime and keep it in the task that awaits it, so the permit is released when the runtime ends or is dropped:
| Caller | Permit | When none is left |
|---|---|---|
classifier (Hysteria 2 proxy stream) |
config.circuit_permits.clone().try_acquire_owned(), moved into the serving task as _permit |
The stream is reset with H3_REQUEST_REJECTED, and hysteria2: refusing a stream; the listener is at its circuit limit is logged at debug |
Hy2UdpCore (Hysteria 2 datagrams) |
One circuit permit per association, held in its Session entry; at most MAX_SESSIONS (256) associations per connection |
The packet is consumed and dropped, with hysteria2: refusing a session; the table is full or hysteria2: refusing an association; the listener is at its circuit limit at trace |
TunInbound::run (TCP stream or UDP association) |
permits.clone().try_acquire_owned() from a Semaphore of TunConfig::max_flows, moved into the flow task |
tun: dropping a flow; the flow limit is reached at debug |
A TUN UDP association takes its permit once, when its first flow arrives. Later flows from the same source socket address are handed to the running association through an mpsc channel of FLOW_QUEUE (16), and a flow that finds the channel full is dropped. The permits of a stream listener’s connections are on Listeners and the serve loop.
Key types
Section titled “Key types”ProxyServerRuntime
Section titled “ProxyServerRuntime”pub struct ProxyServerRuntime<const BUF_SIZE: usize, Core, Trans, Conn, Mode = ProxyRunsQuiet>where Core: ProxyCoreDecode, Conn: Connector<Core::Target>,{ /* private fields */ }
#[derive(Debug, Clone, Copy, Default)]pub struct ProxyRunsQuiet;#[derive(Debug, Clone, Copy, Default)]pub struct ProxyShowsProgress;| Parameter | Bound | Meaning |
|---|---|---|
BUF_SIZE |
const usize, must exceed Core::STAGING_RESERVE |
Cap of each of the three buffers (transport read, transport staging, outbound scratch); none is allocated at that size up front. It also caps the largest protocol frame the connection accepts. The values the callers use are in Buffer sizes per core. |
Core |
ProxyCoreDecode |
The protocol state machine. Its associated types fix the outbound key (Key), what gets dialed (Target), its error (Error) and the transport peer address (TransportAddr). |
Trans |
Transport<Addr = Core::TransportAddr> on the impls that drive it |
StreamTransport<T> (from new) or DatagramTransport<D> (from over_datagrams). Callers never name it. |
Conn |
Connector<Core::Target>, plus Conn::Datagram: DatagramLink<Addr = Destination> on the impls that drive it |
Dials a target into an Outbound::Stream or an Outbound::Datagram. |
Mode |
ProxyRunsQuiet (default) or ProxyShowsProgress |
Selects the Future impl, which resolves to the total Traffic, or the Stream impl, which yields one Traffic delta per unit of work. |
Constructors
Section titled “Constructors”impl<const BUF_SIZE: usize, Core, T, Conn> ProxyServerRuntime<BUF_SIZE, Core, StreamTransport<T>, Conn, ProxyRunsQuiet>where Core: ProxyCoreDecode, T: AsyncRead + AsyncWrite + Unpin, Conn: Connector<Core::Target>,{ pub fn new(transport: T, core: Core, connector: Conn) -> Self;}
impl<const BUF_SIZE: usize, Core, D, Conn> ProxyServerRuntime<BUF_SIZE, Core, DatagramTransport<D>, Conn, ProxyRunsQuiet>where Core: ProxyCoreDecode, D: DatagramLink<Addr = Core::TransportAddr>, Conn: Connector<Core::Target>,{ pub fn over_datagrams(link: D, core: Core, connector: Conn) -> Self;}
impl<const BUF_SIZE: usize, Core, Trans, Conn> ProxyServerRuntime<BUF_SIZE, Core, Trans, Conn, ProxyRunsQuiet>where Core: ProxyCoreDecode, Conn: Connector<Core::Target>,{ pub fn showing_progress( self, ) -> ProxyServerRuntime<BUF_SIZE, Core, Trans, Conn, ProxyShowsProgress>;}-
newwraps the stream inStreamTransport, andover_datagramswraps the link inDatagramTransport. Both then call a privatebuild, which allocates a read bufferupof 2 KiB (orBUF_SIZE, if smaller) and nothing forstagingorscratch, creates an emptyReadyQueue, sets every flag tofalseand setsprefer_transport = true, so the very first poll tries the transport before the outbounds. -
buildstarts with:assert!(BUF_SIZE > Core::STAGING_RESERVE,"BUF_SIZE must exceed the core's STAGING_RESERVE or nothing is ever read");This is a run-time
assert!, so a bad instantiation panics when the runtime is constructed, not when it is compiled. The reason: a stream outbound is read only withSTAGING_RESERVE + 1bytes of staging room, which a buffer no larger than the reserve never has, anddatagram_limitcomputesBUF_SIZE - Core::STAGING_RESERVE. -
showing_progressconsumes the quiet runtime and moves every field into theProxyShowsProgressform. It is only defined on the quiet type, so a runtime changes mode at most once. Every caller that uses it does so right after construction.
Every production caller instantiates BUF_SIZE with the core’s own associated constant, for example ProxyServerRuntime::<{ Hy2UdpCore::<()>::BUF_SIZE }, _, _, _>::over_datagrams(...), or drive::<{ TrojanCore::<Principal>::BUF_SIZE }, _, _>(...), where drive is generic over const BUF: usize, takes the core as a closure, and builds ProxyServerRuntime::<BUF, Core, _, _>::new(stream, make_core(), connector).
Accessors
Section titled “Accessors”impl<const BUF_SIZE: usize, Core, Trans, Conn, Mode> ProxyServerRuntime<BUF_SIZE, Core, Trans, Conn, Mode>where Core: ProxyCoreDecode, Conn: Connector<Core::Target>,{ pub fn core(&self) -> &Core; pub fn summary(&self) -> Traffic;}
// On the impl that drives the runtime// (Trans: Transport<Addr = Core::TransportAddr>, Conn::Datagram: DatagramLink<Addr = Destination>):pub const fn datagram_limit() -> usize;core()lets the caller inspect the core between steps.driveandserve_streamuse it to ask whether the handshake is over (is_established()).summary()returns the total of every delta reported so far.datagram_limit()is the largest packet delivered whole from a datagram outbound:Core::MAX_DATAGRAM, capped atBUF_SIZE - Core::STAGING_RESERVE. ForTunUdpCorethat ismin(4096, 8192 - 4096)= 4,096 bytes.- The type implements
UnpinwheneverTrans: Unpin, whatever the core and connector are. The transport isUnpin, and the connect futures and the timer are boxed, so nothing inside relies on being pinned.
Transports
Section titled “Transports”The client side is seen through one trait, so the runtime is written once for both kinds of transport. The trait is public, but a caller never needs to name it.
pub enum Received<A> { Bytes, Datagram(A), Eof,}
pub trait Transport: Unpin { const DATAGRAM: bool; type Addr;
fn poll_recv( &mut self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<Received<Self::Addr>>>;
fn poll_send( &mut self, cx: &mut Context<'_>, data: &[u8], to: Option<&Self::Addr>, ) -> Poll<io::Result<usize>>;
fn poll_flush(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;}
pub struct StreamTransport<T>(pub T);pub struct DatagramTransport<D>(pub D);StreamTransport<T> |
DatagramTransport<D> |
|
|---|---|---|
| Bound | T: AsyncRead + AsyncWrite + Unpin |
D: DatagramLink |
DATAGRAM |
false |
true |
Addr |
() |
D::Addr: a SocketAddr for a link whose packets name a peer (a UDP socket serving many peers, or TUN’s per-source TunUdpLink, addressed by the far end), () for a single-peer link such as a QUIC connection’s datagrams |
poll_recv |
A read that fills nothing is Received::Eof; otherwise Received::Bytes. The runtime never passes an empty buffer, so a zero-byte read can only mean end of stream. |
poll_recv_from, always Received::Datagram(from). There is no end of stream. |
poll_send |
poll_write; to is ignored |
poll_send_to(to). to = None is an InvalidInput error, “a datagram transport needs a peer per packet”; the runtime always passes a peer. |
poll_flush, poll_shutdown |
Forwarded to T |
No-ops that return Ready(Ok(())) |
The outbound side uses the traits in concepts/src/link.rs:
pub trait Connector<Target> { type Stream: AsyncRead + AsyncWrite + Unpin; type Datagram: DatagramLink; type Future: Future<Output = io::Result<Outbound<Self::Stream, Self::Datagram>>>;
fn connect(&mut self, target: Target) -> Self::Future;}
pub enum Outbound<S, D> { Stream(S), Datagram(D),}Outbound streams are stored by value in the runtime’s map, which moves them when it rebalances, hence Unpin. The dial future may be any future: the runtime boxes it, once per open. Any FnMut(Target) -> Fut whose future yields an Outbound is a Connector, which is how the tests pass closures. See Links, connectors and net types for DatagramLink, UdpOutbound and Destination.
The supervisor’s connector, as the runtime sees it
Section titled “The supervisor’s connector, as the runtime sees it”The supervisor passes an AppConnector (supervisor/src/connector.rs). Its Stream is Metered<OutboundStream>, its Datagram is a FanOutLink, and its Future is a boxed dyn Future + Send. What AppConnector::connect(flow) returns decides which event the core receives:
| Flow | The dial future resolves to | The core receives |
|---|---|---|
Refused by its session (session.admit(&flow.user.user_data) returns Err) |
That error, at once | ConnectFailed |
UDP (flow.destination.network == DialNetwork::Udp) |
Outbound::Datagram(FanOutLink), at once, with nothing dialed |
Connected; the link routes packet by packet |
| TCP | Routed inside connect on the plane loaded there once (plane.route(&flow, &ctx)); a balancer picks its member then (resolve(None)); Target::connect_stream opens it, Tracker::meter_stream wraps the result into Outbound::Stream(Metered<OutboundStream>), and Target::close_if_drained kills the new flow if a drain closed that version while it dialed |
Connected, or ConnectFailed with the open error |
How a flow is routed and filed is on The plane: routing each flow.
Private helpers
Section titled “Private helpers”The runtime’s private methods, with the two type aliases they share:
type SlotOf<Core, Conn> = Slot< <Core as ProxyCoreDecode>::Key, <Conn as Connector<<Core as ProxyCoreDecode>::Target>>::Future, <Conn as Connector<<Core as ProxyCoreDecode>::Target>>::Stream, <Conn as Connector<<Core as ProxyCoreDecode>::Target>>::Datagram,>;
/// Whether a step made progress.type Step<Core> = Result<bool, RuntimeError<<Core as ProxyCoreDecode>::Error>>;| Method | Returns | Role |
|---|---|---|
poll_once(&mut self, cx) |
Poll<Result<Option<Traffic>, RuntimeError<Core::Error>>> |
Registers the task’s waker with the ReadyQueue, runs step, and turns progress into a delta. Both the Future and the Stream impl are built on it. |
step(&mut self, cx) |
Result<Option<bool>, RuntimeError<Core::Error>> |
One unit of work: Some(true) progress, Some(false) nothing to do until woken, None the connection is over |
deliver(core, effects, staging, packets, event) |
Result<usize, RuntimeError<Core::Error>> |
Calls Core::handle and returns what it consumed. It is an associated function over split borrows, so the event can borrow up or scratch while the core, the sink and staging are borrowed alongside. Under a stream transport it builds the sink with Effects::new and skips the packet accounting entirely; under a datagram transport it builds it with Effects::with_packets and runs the StagedWithoutPeer check. |
enqueue(&mut self, source, base, limit) |
Result<(), …> |
Validates the sink’s effects and moves them onto queue |
handle_meta(&mut self, event) |
Result<(), …> |
Delivers an event without bytes (Connected, ConnectFailed, OutboundEof, TransportEof, TransportSendFailed, Deadline), then enqueue(Source::Scratch, 0, 0) and drive_effects |
feed_transport(&mut self) |
Result<(), …> |
Delivers Event::Transport in a loop; see Reading the transport |
after_scratch(&mut self, consumed, len) |
Result<(), …> |
Finishes an Outbound or Datagram event: BadConsume unless consumed == len, then enqueue(Source::Scratch, 0, len) and drive_effects |
drive_effects(&mut self) |
Step<Core> |
Applies the queue |
fail_outbound(&mut self, key, error), report_send_failure(&mut self, key, to, error) |
Result<(), …> |
Deliver OutboundError or SendFailed and enqueue(Source::Scratch, 0, 0) the answer, without applying it |
forget_key(&mut self, key), set_deadline(&mut self, after), reschedule_starved(&mut self) |
() |
Drop a key and its queued effects; arm or disarm the timer; reschedule starved keys |
pinned(&self, source), held_free(&self) |
bool |
The pin checks of Source pins |
poll_transport_write, poll_transport_send_packets, poll_transport_read, poll_transport_recv_packet, poll_outbounds, service_key, poll_deadline |
Step<Core> |
The polls step is made of |
Buffers
Section titled “Buffers”The runtime has three buffers, each capped at BUF_SIZE bytes, and allocates none of them at that size up front (concepts/src/buffer.rs). The read buffer up starts at INITIAL (2 KiB) or BUF_SIZE if smaller, and doubles each time reading uses up its free region; the staging buffer holds no storage until the first byte is staged, and then grows with what is staged; the scratch buffer is allocated whole at the first outbound read. A connection that never gets past its handshake therefore holds only the small read buffer, and one that moves data reaches BUF_SIZE within its first few reads. Every copy the runtime itself makes lands in one of these buffers, and backpressure comes from them being full at the cap.
flowchart LR client["client transport"] up["up: ReadBuffer"] core["Core::handle"] queue["effect queue"] out["outbound links"] scratch["scratch"] staging["staging: WriteBuffer"] client -->|"poll_recv"| up up -->|"Event::Transport"| core core -->|"Forward ranges"| queue queue -->|"poll_write, poll_send_to"| out out -->|"poll_read, poll_recv_from"| scratch scratch -->|"Event::Outbound, Event::Datagram"| core core -->|"stage, reserve, stage_to"| staging staging -->|"poll_send"| client
Uplink bytes are not copied by the runtime at all. The core decrypts them in place in the read buffer and forwards ranges of it, which the runtime writes to the outbound straight from up. Downlink bytes are read into scratch and copied once more, when the core seals them into staging.
The read buffer: ReadBuffer<BUF_SIZE>
Section titled “The read buffer: ReadBuffer<BUF_SIZE>”The transport is read into up, which is split into three regions:
0 ............... start ............... end ............ data.len()| parsed | unparsed | free || (a queued | (the tail of a | (the next read || forward may | split frame) | lands here) || still read it) | | || Method | Signature | Used for |
|---|---|---|
new, Default |
pub fn new() -> Self |
An empty buffer, start = end = 0, with min(INITIAL, N) bytes of storage |
start |
pub fn start(&self) -> usize |
The base that forward ranges from a transport event are made absolute against |
unparsed |
pub fn unparsed(&mut self) -> &mut [u8] |
The slice handed to the core as Event::Transport, mutable so the core can decrypt in place |
unparsed_len |
pub fn unparsed_len(&self) -> usize |
Whether there is anything left to feed |
slice |
pub fn slice(&self, range: Range<usize>) -> &[u8] |
Resolving a queued forward’s absolute range when it is applied |
free_len, free |
pub fn free_len(&self) -> usize, pub fn free(&mut self) -> &mut [u8] |
The tail the next read goes into |
advance_end |
pub fn advance_end(&mut self, n: usize) |
Accounting for a read of n bytes (debug_assert! that it fits) |
advance_start |
pub fn advance_start(&mut self, n: usize) |
Accounting for what the core consumed (debug_assert! that start stays at or below end) |
compact |
pub fn compact(&mut self) |
Moving the unparsed tail to offset 0 with copy_within (a reset to empty when nothing is unparsed). If the unparsed bytes still fill the storage, which is then below N, it doubles the storage, so compacting a buffer that is not saturated always frees room. |
make_room |
pub fn make_room(&mut self) |
Refilling the free region once reading has used it up: moves the unparsed tail to the front, as compact does, and doubles the storage while it is below N. The buffer must not be saturated (debug_assert!). |
grow_to |
pub fn grow_to(&mut self, len: usize) |
Growing the storage to at least len bytes, capped at N, keeping every offset; used before a datagram read, which needs room for a whole packet at once |
is_saturated |
pub fn is_saturated(&self) -> bool |
start == 0 && end == N: the unparsed region fills all N bytes |
Queued forwards hold absolute offsets into this buffer, so the parsed region cannot move while one of them is queued. Growing keeps every offset (the private grow helper extends the Vec in place), and moving is lazy and guarded:
- Stream transport.
poll_transport_readcallsmake_roomonly when the free tail is empty (free_len() == 0). If the buffer is saturated at that point, the core still wants more of a frame that cannot fit, and the connection fails withRuntimeError::FrameTooLarge. Otherwisestartis above 0 or the storage is belowBUF_SIZE, somake_roomfrees at least one byte. The read path returns early while a ranged effect into this buffer is queued, somake_roomnever moves bytes that an effect still references (see Source pins). - Datagram transport. A packet is consumed whole, so
poll_transport_recv_packetresets the buffer (compactwith nothing unparsed) before every read, after adebug_assert_eq!that nothing is unparsed (“a datagram never leaves a tail”), and then callsgrow_to(MAX_DATAGRAM.min(BUF_SIZE))so the whole packet fits.
The staging buffer: WriteBuffer<BUF_SIZE>
Section titled “The staging buffer: WriteBuffer<BUF_SIZE>”Bytes bound for the transport are staged in staging. The core appends at end through a Staging writer, and the runtime writes [start .. end) out and slides start forward.
0 ............. start ............. end ........... data.len()| written | pending | room |impl<const N: usize> Default for WriteBuffer<N>; // WriteBuffer::new()
impl<const N: usize> WriteBuffer<N> { pub fn new() -> Self; pub fn is_empty(&self) -> bool; pub fn pending(&self) -> &[u8]; pub fn advance_start(&mut self, n: usize); pub fn room(&mut self) -> usize; pub fn staging(&mut self) -> Staging<'_>;}
impl Staging<'_> { pub fn room(&self) -> usize; pub fn reserve(&mut self, len: usize) -> Option<&mut [u8]>; pub fn put(&mut self, bytes: &[u8]) -> Option<()>;}- The storage is an empty
Vecuntil the first stage.room()counts againstN, not against what is allocated, so an empty buffer offersNbytes of room without holding any. advance_startresets both offsets to 0 once everything pending has been written, so a drained buffer always offers room for allNbytes.room()slides the pending bytes to the front when that is what makes room, which is whenstart != 0and the tail has reachedN(end == N). This is the only copy the buffer makes on its own.room()takes&mut selffor that reason, andstaging()calls it first, so the core always gets the largest tail available.Stagingborrows the buffer’sVec, a reference toend, and the capNaslimit.Staging::reserveclaimslenbytes at the tail and returns them for the core to fill in place, or returnsNonewithout claiming anything. When the claim runs past the current storage,reservefirst grows theVecto the larger of the claim’s end, twice its current length and 2 KiB, never pastlimit. The claimed bytes count as staged at once.putisreserveplus a copy. A frame is sealed where it lies, with no intermediateVec.
The scratch buffer
Section titled “The scratch buffer”scratch: Option<Box<[u8; BUF_SIZE]>> receives outbound reads. It is None until the first outbound read, which creates it with get_or_insert_with(boxed_array); buffer::boxed_array (crate-private) builds the array from vec![0u8; N].into_boxed_slice(), so a large BUF_SIZE never passes through the stack. Before that, only empty ranges index scratch (the effects of events without bytes are enqueued against it with a limit of 0), and the private Self::scratch(&scratch, range) returns an empty slice for them. service_key reads at most:
(staging.room() - Core::STAGING_RESERVE).min(BUF_SIZE)bytes from a stream outbound;datagram_limit()bytes from a datagram outbound.
The first cap is what makes the event contract hold: an outbound chunk of n bytes is only ever delivered with at least STAGING_RESERVE + n bytes of staging free, so the core can seal all of it.
The rest of the state
Section titled “The rest of the state”| Field | Type | Purpose |
|---|---|---|
transport, core, connector |
Trans, Core, Conn |
Owned by value |
outbounds |
BTreeMap<Core::Key, SlotOf<Core, Conn>> |
One slot per live outbound key |
ready |
ReadyQueue<Core::Key> |
Keys whose outbound signalled readiness |
drained |
VecDeque<Core::Key> |
Keys popped from ready and not yet serviced, oldest first |
starved |
Vec<Core::Key> |
Keys that wanted servicing but were held back by staging room or a pinned buffer |
packets |
PacketList<Core::TransportAddr>, which is VecDeque<(usize, A)> |
Under a datagram transport, the packets in staging, front first: a length and a peer each |
effects |
EffectList<Core>, which is SmallVec<[Effect<C>; INLINE_EFFECTS]> |
The sink the core pushes into; empty between calls |
queue |
SmallVec<[Queued<Core>; INLINE_EFFECTS]> |
Effects not yet applied, front first |
deadline, deadline_armed |
Option<Pin<Box<Sleep>>>, bool |
The single timer |
delta, summary |
Traffic |
Bytes moved in the current unit of work, and in total |
The flags complete the state:
| Flag | Set when | Meaning |
|---|---|---|
up_needs_feed |
A pin stopped feed_transport with bytes unparsed |
Feed the leftover bytes before reading more |
transport_read_closed |
The stream transport returned end of stream | Never read the transport again |
transport_write_closed |
poll_shutdown completed, or a datagram transport drained its packets after ShutdownTransport |
Never write the transport again |
transport_needs_flush |
A stream write accepted bytes | Flush once staging is empty |
shutdown_transport |
Effect::ShutdownTransport was applied |
Half-close the transport once staging is empty |
finished |
Effect::Finish was applied |
Stop reading; complete once the writes are done |
failed |
The stream mode yielded an error | Return None from every later poll_next |
prefer_transport |
Flipped after each read that made progress | Which side step tries first |
Allocations
Section titled “Allocations”| When | What is allocated |
|---|---|
build |
The read buffer up, at 2 KiB (or BUF_SIZE if smaller), and the ReadyQueue’s shared Arc, which holds two parking_lot::Mutexes. staging holds no storage and scratch is None. The map, the deques, starved and the two SmallVecs start empty. |
Reading uses up up’s free region while it is below BUF_SIZE |
make_room doubles up, up to BUF_SIZE |
| A datagram transport read | grow_to grows up to MAX_DATAGRAM.min(BUF_SIZE), if it is not that large yet |
The first stage into staging, and any stage past its storage |
Staging::reserve grows it to the larger of the stage’s end, twice its length and 2 KiB, never past BUF_SIZE |
| The first outbound read | The boxed [u8; BUF_SIZE] scratch array |
An Effect::Open is applied |
One Arc<KeyWaker> (ReadyQueue::waker), the boxed dial future, and the map entry |
The first SetDeadline(Some(_)) is applied |
One boxed Sleep. Later arms reset it in place. |
More than INLINE_EFFECTS (4) effects in one call, or on the queue |
The SmallVec spills to the heap |
| As needed | drained, starved, packets and the ready list inside the ReadyQueue grow with the number of keys or packets |
The core’s own state, including whatever it keeps in held(), is the core’s to allocate and bound.
Outbound slots
Section titled “Outbound slots”Each live key owns a Slot in outbounds:
enum LinkState<F, S, D> { Connecting(Pin<Box<F>>), Stream(S), Datagram(D),}
struct Slot<K, F, S, D> { link: LinkState<F, S, D>, waker: Arc<KeyWaker<K>>, read_closed: bool, write_closed: bool, need_flush: bool,}need_flush is set when a forward was written but the link’s poll_flush returned Pending. service_key finishes that flush before it reads the key again.
stateDiagram-v2 [*] --> Connecting: Open effect is applied Connecting --> Stream: dial returns Outbound Stream Connecting --> Datagram: dial returns Outbound Datagram Connecting --> [*]: dial fails, ConnectFailed Connecting --> [*]: Close effect Stream --> [*]: Close effect Stream --> [*]: write, flush, shutdown or read error, OutboundError Stream --> [*]: shut down and read to EOF Datagram --> [*]: Close effect Datagram --> [*]: receive error, OutboundError
- Open.
Effect::Openfails the connection withDuplicateKeyif the key already has a slot, including one that is still connecting. Otherwise the runtime mints a waker withready.waker(key), callsconnector.connect(target), stores the future boxed asConnecting, and callsschedule()on the new waker so the dial is polled once. - Connect. When the dial resolves, the slot becomes
StreamorDatagram, the key is scheduled again, and the core receivesEvent::Connected { key }. A failed dial removes the key (see Losing a key) and deliversEvent::ConnectFailed { key, error }. - Half-close. A stream slot is removed when both halves are closed.
Effect::Shutdownsetswrite_closedoncepoll_shutdowncompletes; a zero-byte read setsread_closedand deliversEvent::OutboundEof. Whichever happens second removes the slot. - Datagram slots.
Effect::Shutdownon a datagram slot completes at once and only marks the write side;read_closedis never set on one. A datagram link has no end of stream, so the slot ends throughCloseor a receive error. - Close.
Effect::Closeremoves the slot at once, in any state, and drops the link or the in-flight dial future. It does not purge effects queued after it for the same key, so a later non-emptyForward, a laterSendToor a laterShutdownto that key fails withUnknownKeyunless anOpenfor the key comes first.
Per-key wake-ups
Section titled “Per-key wake-ups”One task polls many outbounds. Polling all of them on every wake-up would cost O(N) per wake-up, so each outbound is polled with its own waker that records which key became ready. It is the scheme FuturesUnordered uses, without its intrusive list.
struct Shared<K> { ready: Mutex<Vec<K>>, parent: Mutex<Option<Waker>>,}
pub struct ReadyQueue<K> { shared: Arc<Shared<K>>,}
impl<K> ReadyQueue<K> { pub fn new() -> Self; pub fn register(&self, waker: &Waker); pub fn waker(&self, key: K) -> Arc<KeyWaker<K>>; pub fn drain_into(&self, into: &mut VecDeque<K>); pub fn is_empty(&self) -> bool;}
pub struct KeyWaker<K> { key: K, queued: AtomicBool, shared: Arc<Shared<K>>,}
impl<K: Copy> KeyWaker<K> { pub fn key(&self) -> K; pub fn clear_queued(&self);}
impl<K: Copy + Send + Sync + 'static> KeyWaker<K> { pub fn waker(self: &Arc<Self>) -> Waker; pub fn schedule(self: &Arc<Self>);}
impl<K: Copy + Send + Sync + 'static> Wake for KeyWaker<K> { /* wake, wake_by_ref */ }Both mutexes are parking_lot::Mutex. Because KeyWaker implements std::task::Wake, KeyWaker::waker is Waker::from(self.clone()): a reference-count increment, not an allocation. The wake scheme’s one allocation is the Arc minted per open. ReadyQueue also implements Default; the runtime uses register, waker and drain_into, and the unit tests use is_empty.
sequenceDiagram participant IO as outbound I/O driver participant KW as KeyWaker of key participant RQ as ReadyQueue participant T as runtime task T->>RQ: register task waker, every poll_once IO->>KW: wake_by_ref KW->>KW: queued.swap(true) KW->>RQ: push key, only if it was not queued KW->>RQ: take the parent waker KW->>T: wake the parent T->>RQ: drain_into(drained), oldest first T->>KW: clear_queued T->>IO: poll the outbound with the key's own waker
| Rule | Mechanism |
|---|---|
| A key is queued at most once, however often it wakes | wake_by_ref pushes the key only if queued.swap(true, Ordering::AcqRel) returned false |
| A burst of wake-ups wakes the task once | wake_by_ref take()s the parent waker. poll_once calls register on every poll to put it back, and register skips the clone when the stored waker will_wake the new one. |
| A wake-up that lands during a poll is not lost | service_key calls clear_queued() (a Release store) before polling the outbound, so a wake-up during the poll queues the key again instead of being swallowed by the dedupe |
| A new key is polled once | waker(key) returns an unqueued waker, so the runtime calls schedule() after Open |
| A key that needs a poll without an I/O event gets one | schedule() is wake_by_ref(). The runtime calls it after Open, after a dial completes, after every outbound read that returned data or a packet (readiness wakers only fire after a Pending), and when a starved key is released. Because it also wakes the parent, a key scheduled during a poll is guaranteed another poll. |
poll_outbounds refills drained from ready only when drained is empty. It then services keys front to back and returns after the first one that made progress. A key whose read succeeded is rescheduled to the back of the ready queue, so busy outbounds take turns. A key that returns Pending is dropped from drained; its own waker queues it again when its I/O is ready. A key that no longer has a slot (a stale wake-up after Close) is skipped.
The effect queue
Section titled “The effect queue”The core pushes effects into the effects sink during handle. After every call the runtime validates them and moves them onto queue, tagging each with the buffer its range indexes:
#[derive(Clone, Copy, PartialEq, Eq)]enum Source { Transport, Scratch, Held,}
struct Queued<C: ProxyCoreDecode> { effect: Effect<C>, source: Source,}enqueue(source, base, limit) checks every range and makes it absolute:
ForwardandSendToranges must satisfystart <= end <= limit, wherelimitis the length of the event’s byte slice. They are then shifted bybase:up.start()for a transport event, 0 for an outbound event. Events that carry no bytes are enqueued withSource::Scratchandlimit = 0, so they can only forward empty ranges.ForwardHeldandSendToHeldranges must satisfystart <= end <= core.held().len(), measured once whenenqueuestarts. They are taggedSource::Held, stay relative, and are resolved againstheld()again when applied, so aVecthat reallocates between the two is fine.- Any violation fails the connection with
RangeOutOfBounds.
Every call that delivers an event is followed by enqueue, and the effects start applying at once:
| Event | Delivered by | Enqueued as | Applied by |
|---|---|---|---|
Transport |
feed_transport |
enqueue(Source::Transport, up.start(), len) |
drive_effects, right after |
TransportDatagram |
poll_transport_recv_packet |
enqueue(Source::Transport, up.start(), n) |
drive_effects, right after |
Outbound, Datagram |
service_key, then after_scratch |
enqueue(Source::Scratch, 0, len) |
drive_effects, right after |
Connected, ConnectFailed, OutboundEof, TransportEof, TransportSendFailed, Deadline |
handle_meta |
enqueue(Source::Scratch, 0, 0) |
drive_effects, right after |
OutboundError, SendFailed raised while effects are applied |
fail_outbound, report_send_failure |
enqueue(Source::Scratch, 0, 0) |
The drive_effects loop that is already running |
OutboundError from a read, receive or pending flush |
service_key → fail_outbound |
enqueue(Source::Scratch, 0, 0) |
drive_effects, called by service_key right after |
Source pins
Section titled “Source pins”A queued ranged effect pins the buffer it reads: nothing new is read into that buffer until the effect has been applied. Queued::pins(source) answers the question per effect, and pinned(source) asks it of the whole queue (self.queue.iter().any(|q| q.pins(source))); held_free() is !pinned(Source::Held).
fn pins(&self, source: Source) -> bool { match &self.effect { Effect::Forward { .. } | Effect::SendTo { .. } => self.source == source, Effect::ForwardHeld { .. } | Effect::SendToHeld { .. } => source == Source::Held, _ => false, }}| Pinned source | Tagged on | While it is pinned |
|---|---|---|
Source::Transport |
Ranges into the read buffer up, at absolute offsets |
The transport is not read, and the core is not fed more transport bytes (up_needs_feed is set instead) |
Source::Scratch |
Ranges into scratch, and every effect pushed during an event without bytes (whose ranges are empty) |
No connected outbound is serviced; keys that wake are parked in starved |
Source::Held |
Every ForwardHeld and SendToHeld |
The transport is not read or fed, and no connected outbound is serviced |
Open, Shutdown, Close, ShutdownTransport, SetDeadline and Finish pin nothing. The length of a range does not matter: an empty Forward or SendTo pins its source like any other until it is applied. At the front of the queue an empty Forward is dropped and an empty SendTo is sent.
The held pin is what lets a core rewrite its own held buffer safely. While any held effect is queued, the core receives no byte event: no Transport, TransportDatagram, Outbound, Datagram, OutboundEof or TransportEof. A slot that is still Connecting is exempt from the scratch and held pins, because polling a dial touches neither buffer, so Connected and ConnectFailed still arrive; so do Deadline, TransportSendFailed and the failure events raised while effects are applied.
The pin starts only when the core’s call returns and its effects are enqueued. Within one call, a held range pushed earlier still reads held() after the call, so the core must leave those bytes in place until its next byte event. protocols/src/mux/demux.rs → Demux::feed_chunks follows this rule: VMessCore passes it every chunk that one read opened in a single call, because “the held forwards it pushes all read the buffer after the event”, and the demux trims its held buffer only at the start of its next feed or feed_chunks call. The rules for core authors are on Server core.
Applying effects: drive_effects
Section titled “Applying effects: drive_effects”drive_effects applies the queue front to back, in the order the core pushed the effects, and returns whether it applied anything. Outbound writes are polled with the key’s own waker, not the task’s, so a blocked write wakes exactly its key. A forward’s bytes are written once its key’s dial has completed.
| Effect | Applied as | Errors and events |
|---|---|---|
Forward, ForwardHeld |
An empty range is dropped, before the key is looked up. Otherwise poll_write of the range on the stream, then poll_flush with the same waker. A partial write advances range.start, and the loop tries the rest at once. A flush that returns Pending sets need_flush; the bytes written still count. |
No slot: UnknownKey. Datagram slot: WrongLinkKind. Held range no longer inside held(): RangeOutOfBounds. A write of 0 bytes (WriteZero), a write error or a flush error: the effect is removed, the key is dropped and the core receives OutboundError. |
SendTo, SendToHeld |
One poll_send_to(data, &to) on the datagram link, even for an empty range. The length the link reports is counted. |
No slot: UnknownKey. Stream slot: WrongLinkKind. Held range no longer inside held(): RangeOutOfBounds. A refused send: the packet is dropped, the key stays live, and the core receives SendFailed. |
Open |
See Outbound slots | Live key: DuplicateKey |
Shutdown |
poll_shutdown on a stream; completes at once on a datagram slot. Completion sets write_closed, and removes the slot if read_closed is already set. |
No slot: UnknownKey. I/O error: the key is dropped and the core receives OutboundError. |
Close |
Removes the slot | None, even for an unknown key |
ShutdownTransport |
Sets shutdown_transport |
None |
SetDeadline(after) |
Some: resets the boxed Sleep to tokio::time::Instant::now() + after (creating it with sleep_until the first time) and arms it. None: disarms it. |
None |
Finish |
Sets finished |
None |
At the end of a pass that applied something, if keys are starved and neither the scratch nor the held buffer is pinned any more, the starved keys are rescheduled. The bytes written by forwards and sends in the pass are added to delta.outbound_tx.
Losing a key: forget_key
Section titled “Losing a key: forget_key”When a key is lost, forget_key removes the slot and every queued Forward, SendTo, ForwardHeld, SendToHeld, Shutdown and Close aimed at it. A forward waiting on a dial that has failed has nowhere to go, and the core learns of the loss through exactly one event (ConnectFailed or OutboundError). Whatever the core answers is enqueued at the back of the queue.
fail_outbound (forget the key, deliver OutboundError, enqueue the answer) and report_send_failure (deliver SendFailed, enqueue the answer, keep the key) run from inside drive_effects, so they only enqueue; the drive_effects loop that raised them keeps going and applies the answer when it reaches it. service_key also calls fail_outbound for a read, receive or flush error, and calls drive_effects itself right after. A failed dial goes through forget_key and handle_meta(Event::ConnectFailed { .. }).
Scheduling: one unit of work
Section titled “Scheduling: one unit of work”poll_once registers the task’s waker with the ReadyQueue and calls step, which performs at most one unit of work. step returns Some(true) for progress, Some(false) for nothing to do until woken, and None once the connection is over. On progress, poll_once moves delta into summary and returns the delta.
The diagram and the list below show one step before the core has pushed Finish. What changes once it has is in Finish and completion.
flowchart TB
poll["poll_once: ready.register(task waker)"]
dl{"armed deadline fired?"}
fx{"drive_effects applied an effect?"}
wr{"poll_transport_write made progress?"}
io["transport read and outbound service, preferred side first"]
moved{"one side made progress?"}
prog["progress: move delta into summary"]
pend["Pending"]
poll --> dl
dl -->|yes| prog
dl -->|no| fx
fx -->|yes| prog
fx -->|no| wr
wr -->|yes| prog
wr -->|no| io
io --> moved
moved -->|"yes, prefer the side that did not move"| prog
moved -->|no| pend
In order:
- Deadline.
poll_deadlinepolls the armedSleep. The timer goes first so that a connection whose I/O is always ready cannot starve its own handshake or idle deadline. When it fires, the timer is disarmed and the core receivesEvent::Deadlinethroughhandle_meta. - Effects.
drive_effectsretries whatever is still queued, typically a forward the outbound could not take yet. - Transport writes.
poll_transport_writewrites staged bytes: onepoll_sendper step over a stream, every sendable packet over a datagram transport. Once staging is empty it flushes, and then performs a requestedpoll_shutdown. A completed flush alone does not count as progress; a completed shutdown does. - Reads, alternating.
steptriespoll_transport_readandpoll_outboundsin the orderprefer_transportgives. A transport read that made progress setsprefer_transport = false; an outbound that made progress sets it back totrue. Neither side can starve the other. - Nothing to do. The step reports no progress and
poll_oncereturnsPending. Every source polled has registered a waker by then: the timer and the transport with the task’sContext, and each outbound with its key waker, which leads back to the task through theReadyQueue.
WORK_BUDGET
Section titled “WORK_BUDGET”pub const WORK_BUDGET: usize = 64;The quiet Future::poll loops over units of work up to WORK_BUDGET (64) times. If the budget runs out while every unit still makes progress, it calls cx.waker().wake_by_ref() and returns Pending. One busy quiet runtime whose transport or outbounds are always synchronously ready therefore cannot monopolize an executor worker. The stream mode performs one unit per poll_next and has no budget: drive and serve_stream await one step per runtime.next() and add no budget of their own.
Reading the transport
Section titled “Reading the transport”poll_transport_read over a stream transport:
- Returns without progress if the read side is closed,
Source::TransportorSource::Heldis pinned, orstaging.room() < Core::STAGING_RESERVE. Under a datagram transport it then hands over topoll_transport_recv_packet(see Datagram transports). - If
up_needs_feedis set, feeds the leftover unparsed bytes to the core first, and reports progress if that consumed anything or pinned the buffer again. - If the free tail is empty, fails with
FrameTooLargewhen the buffer is saturated, and callsmake_roomotherwise. - Reads into the free tail. End of stream sets
transport_read_closedand deliversEvent::TransportEof. Otherwise the bytes are counted intransport_rxand fed.
feed_transport clears up_needs_feed and delivers Event::Transport(up.unparsed()) in a loop. After each call it checks the consumed count (more than it was given is BadConsume), enqueues the effects with base = up.start(), advances start, and applies the effects. It stops when nothing is unparsed, when the core consumed nothing, or when a pin appears (setting up_needs_feed). So the core is called again as long as it consumes something, and the runtime reads more only once the core has consumed everything or has stopped consuming. Staging room is checked once, before the read, not before each call in this loop.
Servicing an outbound key
Section titled “Servicing an outbound key”service_key(key) polls one outbound once:
- Returns if the key has no slot. Otherwise calls
clear_queued()and builds aContextfrom the key’s waker. - If
need_flushis set, finishes the flush first.Pendingreturns without progress; an error fails the key and applies the core’s answer. - Computes the staging room this key needs:
STAGING_RESERVE + datagram_limit()for a datagram slot,STAGING_RESERVE + 1otherwise (including a slot that is still connecting). If the room is short, or the scratch or held buffer is pinned and the slot is notConnecting, pushes the key ontostarvedand returns. Connecting: polls the dial (see Outbound slots).Stream: unlessread_closed, reads intoscratch[..max], allocatingscratchfirst if this is the first outbound read. A zero-byte read is end of stream. Otherwise the key is rescheduled,outbound_rxis counted, and the core receivesEvent::Outbound { key, data }, which it must consume whole. A read error fails the key.Datagram: receives one packet intoscratch[..datagram_limit()]. The key is rescheduled,outbound_rxis counted, and the core receivesEvent::Datagram { key, from, data }, which it must consume whole. A receive error fails the key; it is the only way a datagram outbound is lost withoutClose.
Backpressure
Section titled “Backpressure”The buffers grow only up to BUF_SIZE, so every backpressure rule has the same shape: the runtime declines to read something until there is somewhere for the result to go. Bytes that are not read stay where the transport keeps them: in the kernel’s TCP receive buffer, whose window then closes toward the peer, or in the HTTP/2 or QUIC stream’s flow-control window when the transport is a stream of one of those.
When the transport is not read
Section titled “When the transport is not read”| Condition | Why |
|---|---|
transport_read_closed |
The transport already returned end of stream |
A ranged effect into the read buffer is queued (pinned(Source::Transport)) |
Its bytes are still in the read buffer at absolute offsets; reading and make_room could move them. A stalled outbound therefore stalls the uplink instead of buffering it. |
A held effect is queued (!held_free()) |
The core must not receive a byte event while its held buffer is pinned |
staging.room() < Core::STAGING_RESERVE |
The core must be able to stage its reply. A client that stops reading fills staging, and then its own uplink stops too. |
finished |
step no longer reads once the core has finished |
When the runtime stops feeding because of a pin, it sets up_needs_feed, and the next read attempt feeds the leftover unparsed bytes before reading anything new.
Reserve checks on the outbound side
Section titled “Reserve checks on the outbound side”| Outbound | Serviced only with this much staging room | Read size |
|---|---|---|
| Stream (or still connecting) | STAGING_RESERVE + 1 |
room - STAGING_RESERVE, capped at BUF_SIZE |
| Datagram | STAGING_RESERVE + datagram_limit() |
datagram_limit() |
A datagram outbound waits for room for a whole packet, never less. A client that stops reading therefore stalls the downlink at the outbound socket instead of receiving truncated packets.
Starved keys
Section titled “Starved keys”A key that wakes while the runtime cannot take its data (step 3 of Servicing an outbound key) is pushed onto starved and not polled. Its queued flag is already cleared, so its own waker can still queue it. reschedule_starved drains starved and calls schedule() on every key that still has a slot. It runs:
- after a stream transport write accepted at least one byte, which freed staging room;
- after a datagram transport send loop sent or dropped at least one packet;
- at the end of a
drive_effectspass that applied something, once neither the scratch nor the held buffer is pinned any more.
A rescheduled key that is still short of room is starved again.
Ordering and the uplink
Section titled “Ordering and the uplink”Effects apply in the order the core pushed them. A forward of transport bytes that the outbound cannot take yet stays queued and pins the read buffer, so the transport is not read until it has been written: the client’s further bytes stay on its side of the transport. Downlink does not go through the queue: an outbound read lands in scratch and is sealed into staging during the same event, subject only to staging room and the scratch and held pins.
stalled_outbound_holds_uplink_but_not_other_downlink in concepts/tests/runtime.rs pins this: a forward the outbound only partly accepts (8 of 100 bytes, over an 8-byte duplex) keeps the transport unread until the rest is written, while downlink from another outbound still reaches the client. The final outbound_tx is 100.
Backpressure from the supervisor’s wrappers
Section titled “Backpressure from the supervisor’s wrappers”The supervisor’s stream outbounds are Metered<OutboundStream>. For a user with a speed limit, Metered (supervisor/src/track/metered.rs) first waits out the user’s token-bucket debt before each read or write: Pacer::poll_ready (supervisor/src/track/pace.rs) returns Pending and parks the flow on its own Sleep, between MIN_WAIT (1 ms) and MAX_WAIT (1 s) per look. The runtime needs no special case for that. A pending write keeps the transport unread, as above, and a pending read leaves the key idle until the Sleep wakes its key waker. The speed limit reaches the client through the same backpressure as a slow destination.
Metered keeps a separate boxed Sleep per direction (read_pause for reads, write_pause for writes), so a paused read does not reset the write’s timer. poll_flush and poll_shutdown are guarded by the kill check but not paced. A poll that returns Pending, paced or not, registers the task’s waker in the flow entry’s read_waker or write_waker (futures::task::AtomicWaker), and FlowEntry::kill wakes both. MeteredDatagram, which wraps a UDP flow’s sub-links, paces and guards poll_send_to (write side) and poll_recv_from (read side) the same way. The bucket itself is on Tracking flows, stats and speed limits.
Event contract
Section titled “Event contract”The runtime checks staging room before it reads, so that the core can seal what it is handed:
| Poll that leads to the event | Room checked first |
|---|---|
Transport read: Transport, TransportDatagram, TransportEof |
STAGING_RESERVE |
Stream outbound service: Outbound, OutboundEof, OutboundError from a read, and Connected or ConnectFailed for a dial |
STAGING_RESERVE + 1. A chunk of n bytes is read only into room - STAGING_RESERVE, so STAGING_RESERVE + n is free when it arrives. |
Datagram outbound service: Datagram, OutboundError from a receive |
STAGING_RESERVE + datagram_limit() |
Deadline |
none |
Failures raised while effects are applied, packets are sent or a pending flush is finished: OutboundError from a write, flush or shutdown, SendFailed, TransportSendFailed |
none |
Deadline is delivered without a room check. The failure events in the last row are raised by whatever pass hit the failure, without a room check of their own. A core must tolerate stage or reserve returning None in those handlers. More generally, a core should turn None from the staging writer into an error it returns (the test cores write .ok_or("staging full")?, and PassthroughCore and most other protocol cores return staging_full() from protocols/src/core/mod.rs, “staging room below the core’s declared reserve”), never treat it as unreachable.
Transport bytes are expected to be forwarded, not staged. The reserve is checked once before the transport is read, and feed_transport may then call the core several times on the rest of that read, so only the first call is sure to find the reserve free. A core that echoes transport bytes back reads Staging::room and consumes fewer bytes when its answer does not fit.
The runtime checks the consumed count after every call:
| Event | The core must consume | Checked in |
|---|---|---|
Transport(data) |
At most data.len(). The rest stays in the read buffer and is offered again, followed by newly read bytes. |
feed_transport |
TransportDatagram |
Exactly data.len(). There is nowhere to keep a remainder. |
poll_transport_recv_packet |
Outbound, Datagram |
Exactly data.len() |
after_scratch |
| Events without bytes | Anything; the return value is ignored | handle_meta, fail_outbound, report_send_failure |
A violation fails the connection with BadConsume.
Datagram transports
Section titled “Datagram transports”over_datagrams builds a runtime over a DatagramLink: a link whose packets name a peer (TransportAddr = SocketAddr), such as one UDP socket serving many peers or TUN’s TunUdpLink, or the datagram side of a QUIC connection (TransportAddr = ()). The core usually acts as a demultiplexer. Hy2UdpCore keys its outbounds by the session id inside each packet, holds at most MAX_SESSIONS (256) associations per connection, each with one circuit permit, and closes idle ones from a sweep it re-arms every SWEEP_INTERVAL (1 s) with SetDeadline; idleness is counted in sweep ticks, idle_timeout.as_secs().max(1) of them. It logs a lost association at debug (hysteria2: association {key} ended: {error}) and a refused packet at trace (hysteria2: packet on {key} to {to:?} dropped: {error} for SendFailed, hysteria2: dropping a reply datagram: {error} for TransportSendFailed). The session table is described on Hysteria 2 server. TunUdpCore uses a single outbound key for the whole source, and stages each reply to the far-end address it came from, which TunUdpLink maps back to the client’s flow.
- Reads follow the kernel socket rule: one packet per read, into the empty read buffer, with room for at most
Core::MAX_DATAGRAM.min(BUF_SIZE)bytes. A longer packet is truncated by the link’s receive. The packet is counted intransport_rx, delivered asEvent::TransportDatagram { from, data }, and must be consumed whole. If the link ever returnsReceived::BytesorReceived::Eof, the connection fails withRuntimeError::Transport(InvalidData, “datagram transport delivered a stream read”). - Staging needs a peer for every byte.
deliverbuilds the sink withEffects::with_packets, and the core stages each packet withstage_toorput_to(see TheEffectssink), which reserves the bytes and pushes(len, to)ontopackets. After the core returns,delivercompares how much the staging buffer grew with the sum of the new packet lengths. A byte staged with plainstageorreservebreaks that equality, and the connection fails withStagedWithoutPeer. Under a stream transportdeliverbuilds the sink withEffects::newand does none of this accounting; therestage_toreturnsNoneandtransport_is_datagram()isfalse. - Sends go packet by packet in
poll_transport_send_packets:poll_send(&pending[..len], Some(&to))for the front packet, and once the link has taken or refused it, the packet is popped and staging advances bylen. Packets the link cannot take yet stay staged, front first. A packet the link refuses is dropped, is not counted intransport_tx, and is reported to the core asEvent::TransportSendFailed { to, error }. One peer’s unreachable address must not take the others down, so a refused send is never fatal; fatal link errors surface on the read side. - Shutdown. There is no write half to close. Once the packets have drained, a pending
ShutdownTransportonly marks the write side closed. - End. A datagram transport never delivers
TransportEof, so such a runtime ends only throughEffect::Finish, aRuntimeError(a fatal receive error from the link, for example), or being dropped.
The two datagram transports in the tree decide how their runtimes report and end:
| Link | Send | Receive |
|---|---|---|
QuicDatagrams (protocols/src/hysteria/server/datagrams.rs), Addr = () |
Synchronous: copies the packet into a Bytes and hands it to quinn::Connection::send_datagram. An error is mapped by hysteria::quic::datagram_error and reaches the core as TransportSendFailed. |
Reads one datagram through a boxed read_datagram future and copies what fits. A connection error becomes BrokenPipe, a fatal receive that ends the Hysteria 2 datagram runtime as RuntimeError::Transport. |
TunUdpLink (protocols/src/tun/udp.rs), Addr = SocketAddr of the far end |
A reply to a far end the client never addressed is dropped and reported as sent (tun: dropping a reply from {to}: the client never addressed it at debug). A write error retires that flow (tun: flow to {to} ended on write: {e} at trace) and is also reported as sent. |
Adopts the flows the accept loop queued, then reads the flows round-robin. A flow that ends (idle timeout or gone) is retired. Once no flow is left, it fails with NotConnected, tun: every flow of this association is gone, which ends the TUN UDP runtime. |
Finish and completion
Section titled “Finish and completion”Effect::Finish sets finished. Because effects apply in order, everything the core pushed before Finish (a Shutdown of an outbound, for example) has already completed, or been dropped with a lost key, when it takes effect.
From then on, step no longer reads the transport or any outbound, and it keeps writing staging to the transport. The runtime completes when staging is empty and, if ShutdownTransport was requested, the transport’s write side has been shut down. The quiet form resolves to Ok(summary), and the stream form ends with None. The transport and any outbounds still open close when the caller drops the completed runtime.
| Core pushes | Result |
|---|---|
ShutdownTransport, then Finish |
Staging drains, the transport is flushed and half-closed, and the runtime completes. The client reads end of stream. |
Finish alone |
Staging drains and the runtime completes. The runtime polls the transport’s flush in the step that completes but does not wait for it, and the transport closes when the runtime is dropped. Push ShutdownTransport too when the last bytes must be flushed. |
| Nothing, after every source has closed | The runtime does not complete on its own. A core must push Finish to end the connection, typically once the transport has reached end of stream and every outbound is gone. |
Traffic and the two modes
Section titled “Traffic and the two modes”#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pub struct Traffic { pub transport_rx: u64, pub transport_tx: u64, pub outbound_rx: u64, pub outbound_tx: u64,}
impl std::ops::AddAssign for Traffic { /* field-wise += */ }| Counter | Counted when |
|---|---|
transport_rx |
A stream read lands n bytes in the read buffer, or a transport packet of n bytes (after truncation) is received |
transport_tx |
A stream write accepts n bytes, or a transport packet of len staged bytes is sent. Refused packets are not counted. |
outbound_rx |
An outbound read or packet of n bytes lands in scratch |
outbound_tx |
A forward writes n bytes, or a datagram send reports n bytes |
impl<const BUF_SIZE: usize, Core, Trans, Conn> Future for ProxyServerRuntime<BUF_SIZE, Core, Trans, Conn, ProxyRunsQuiet>where Core: ProxyCoreDecode, Trans: Transport<Addr = Core::TransportAddr>, Conn: Connector<Core::Target>, Conn::Datagram: DatagramLink<Addr = Destination>,{ type Output = Result<Traffic, RuntimeError<Core::Error>>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;}The future resolves once, to the total traffic over the connection’s lifetime. Each poll runs up to WORK_BUDGET units of work. The Hysteria 2 stream and datagram runtimes and the TUN UDP runtime use this form, each awaited inside a task of a JoinSet the inbound owns. The tests spawn it directly, for example tokio::spawn(ProxyServerRuntime::<256, _, _, _>::new(transport, core, connector)), and the protocol tests’ serve_runtime and serve_runtime_over harnesses use it too.
impl<const BUF_SIZE: usize, Core, Trans, Conn> Stream for ProxyServerRuntime<BUF_SIZE, Core, Trans, Conn, ProxyShowsProgress>where Core: ProxyCoreDecode, Trans: Transport<Addr = Core::TransportAddr>, Conn: Connector<Core::Target>, Conn::Datagram: DatagramLink<Addr = Destination>,{ type Item = Result<Traffic, RuntimeError<Core::Error>>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>;}Each item is the Traffic delta of one unit of work. A delta with every counter zero is a non-payload step: a connect, a close, a deadline. The deltas add up to summary(). The stream must be polled for the connection to move.
The stream form exists so that a caller can act between steps. Two callers use it, the same way: supervisor/src/serve.rs → drive and protocols/src/tun/inbound.rs → serve_stream poll runtime.next() under tokio::time::timeout(HANDSHAKE_TIMEOUT, …) until runtime.core().is_established(), then keep polling without a timeout until the stream ends. serve_stream fails a timeout with TimedOut, tun: the client never spoke. drive also adds each delta’s transport bytes to the session’s Wire; serve_stream discards the deltas.
Who drives it: the supervisor’s drive
Section titled “Who drives it: the supervisor’s drive”supervisor/src/serve.rs → serve_connection serves one byte stream: an accepted Unix-socket stream, or a stream that the inbound’s transport yields over a TCP socket, one its TCP listener accepted or one a relay handed over on its handoff socket (see Listeners and the serve loop).
InboundTransport::accept (protocols/src/transports/accept.rs) hands each stream it yields to a sink, which spawns serve_connection for it, and then returns a Disposition, a #[non_exhaustive] enum:
Disposition::Done: every stream the socket yielded went to the sink. TCP, TLS, WebSocket and gRPC return nothing else.Disposition::Camouflage(relay): only REALITY returns it, for a socket that is not a client of the inbound. The sink never saw the socket, and no runtime is built for it:serve_tcpruns the relay itself. It drops the connection’s handshake permit, keeps the live permit until the relay ends, runs under the session’s cancellation like any connection, and reports nothing to the ban guard. See REALITY transport.
Before it spawns serve_connection, the sink of a VLESS inbound whose flow is XTLS Vision wraps the REALITY stream in the Vision adapter (TransportStream::into_vision_server, protocols/src/transports/stream.rs). If that fails, {tag}: vision setup failed: {e} is logged at debug and the stream is dropped. See XTLS Vision.
serve_connection matches the inbound’s StreamProtocol:
Socksgoes to the SOCKS driver over aWireCountedstream, not to a runtime.Sssgoes toserve_sss, boxed so that other protocols’ connection futures do not grow to its size.serve_sssreads the request header through sss’s gate (sss::acceptinprotocols/src/sss/server.rs) before any runtime exists. An admitted stream is driven bydriveover its decoded side, withSssCore::TCP_BUF_SIZEorSssCore::UDP_BUF_SIZEby the header’s command. A refused one is logged atdebugas{tag}: sss stream from {source:?} refused: {reason}and then drained, still holding its handshake permit, or handed to the fallback, which releases the permit. Neither is reported to the ban guard. See sss.- Every other protocol calls
drivewith a closure that builds its core from the inbound handler’s validator, config or user table, the inbound’ssniffflag and the connector’ssource().drivecalls the closure once, inside its own future: anasync fnkeeps its arguments in its future, and the runtime built from a core in hand would hold a second copy (a_connections_future_holds_one_runtime_and_little_besidesinsupervisor/tests/unit/serve.rspins that the connection’s future is at most 1 KiB larger than its runtime).
StreamProtocol |
Core built with |
|---|---|
Http |
|| HttpCore::new(config.load_full(), sniff, source) |
Trojan |
|| TrojanCore::new(validator.load_full(), sniff, source) |
Vless |
|| VlessCore::new(users.load_full(), sniff, source) (the variant is Vless { users, vision }; vision is read by the sink above) |
Vmess |
|| VMessCore::new(validator.clone(), now_unix, sniff, source).with_hint(hint) (hint is report.carrier_hint(): on a gRPC connection, the user the connection’s last authenticated stream matched) |
Shadowsocks |
|| ShadowsocksCore::new(resolved.load_full(), sniff, source) |
Ss2022 |
|| Ss2022Core::with_system_clock(users.config.clone(), users.validator.clone(), sniff, source) (users is loaded once, outside the closure) |
Anytls |
|| AnyTlsCore::new(users.load_full(), padding.clone(), sniff, source) |
Sss |
in serve_sss, after the gate: move || SssCore::new(users, max_datagram, sniff, source), with the user table loaded when the stream was accepted |
drive needs to know when a core has finished its handshake, and is_established is an inherent method on each core, which a generic function cannot call. serve.rs therefore declares a trait and implements it with the established! macro, which expands to one impl Established for $core<Principal> forwarding to the inherent method, for each of HttpCore, TrojanCore, VlessCore, ShadowsocksCore, Ss2022Core, AnyTlsCore and SssCore. VMessCore implements it by hand, because it also overrides user_hint, the user its auth id matched, which drive passes to report.succeeded so that a gRPC connection’s next VMess stream tries that user first:
pub trait Established { fn is_established(&self) -> bool; fn user_hint(&self) -> Option<UserHint> { None }}
macro_rules! established { ($($core:ident),*) => { $(impl Established for $core<Principal> { fn is_established(&self) -> bool { $core::is_established(self) } })* };}
// drive's bound on the core:// Core: ProxyCoreDecode<Target = Flow, Error = io::Error, TransportAddr = ()> + EstablishedThe loop, abridged:
let wire = connector.session().map(|s| s.wire().clone());let count = |traffic: &Traffic| { if let Some(wire) = &wire { wire.add(traffic.transport_rx, traffic.transport_tx); }};let mut runtime = ProxyServerRuntime::<BUF, Core, _, _>::new(stream, make_core(), connector).showing_progress();while !runtime.core().is_established() { match tokio::time::timeout(HANDSHAKE_TIMEOUT, runtime.next()).await { Err(_) => return Err(/* TimedOut, "inbound handshake timed out after 10s" */), Ok(Some(Ok(traffic))) => count(&traffic), Ok(Some(Err(e))) => { if matches!(&e, RuntimeError::Core(c) if c.kind() == io::ErrorKind::PermissionDenied) { report.failed(); } return Err(io::Error::other(e.to_string())); } Ok(None) => return Ok(()), }}report.succeeded(runtime.core().user_hint());while let Some(step) = runtime.next().await { count(&step.map_err(|e| io::Error::other(e.to_string()))?);}Ok(())flowchart TB
sc["serve_connection: pass a closure that builds the core"]
mk["ProxyServerRuntime::new(stream, make_core(), AppConnector), showing_progress"]
est{"core established?"}
hs["timeout(HANDSHAKE_TIMEOUT, runtime.next())"]
rl["runtime.next()"]
wire["Wire::add(transport_rx, transport_tx)"]
err["return Err, logged at debug"]
ok["return Ok"]
sc --> mk --> est
est -->|no| hs
est -->|yes| rl
hs -->|"a delta"| wire
rl -->|"a delta"| wire
wire --> est
hs -->|"timeout or RuntimeError"| err
rl -->|RuntimeError| err
hs -->|"stream ended"| ok
rl -->|"stream ended"| ok
| Outcome | What drive returns |
|---|---|
No runtime step within HANDSHAKE_TIMEOUT (10 s, protocols/src/core/mod.rs) before the core is established |
io::ErrorKind::TimedOut, inbound handshake timed out after 10s. The number is built from HANDSHAKE_TIMEOUT.as_secs(). |
The runtime yields a RuntimeError, in either phase |
io::Error::other(e.to_string()), so the text is the RuntimeError display: transport: …, proxy core: …, or one of the contract texts in the table below. Before the core is established, a RuntimeError::Core of kind PermissionDenied (a refused credential, by the contract in protocols/src/core/mod.rs) first calls report.failed() on the supervisor’s guard (supervisor/src/guard.rs). |
| The runtime ends before the core is established (the client closed, or the core refused and finished) | Ok(()) |
| The runtime ends after | Ok(()). Reaching an established core has already called report.succeeded(..) with the core’s user_hint(). |
serve_connection logs an Err from any driver, the SOCKS driver included, at debug as {protocol} connection from {source:?} ended: {e}. protocol is StreamProtocol::name() (socks, http, trojan, vless, vmess, shadowsocks, shadowsocks-2022, anytls, sss), and source is the connector’s Option<IpAddr>, printed with Debug, so a line reads, for example, trojan connection from Some(203.0.113.9) ended: inbound handshake timed out after 10s. A Unix-socket listener has no peer address, and prints None.
Wire bytes
Section titled “Wire bytes”count is where the per-user wire bytes of every stream inbound except SOCKS come from. count adds each delta’s transport_rx and transport_tx: bytes of the protocol stream after the listener’s transport, before the protocol’s own framing and encryption are undone. An sss runtime’s transport is the side its transform chains decode, so an sss session counts sss bytes after the transforms are undone, not what they send on the wire. The session’s Wire (supervisor/src/entity/usage.rs) holds them:
| Item | Behaviour |
|---|---|
Wire::counted() |
A stream session’s wire: two AtomicU64 counters, up and down, fed as bytes move |
Wire::quic(ConnectionBytes) |
A Hysteria 2 session’s wire: the same counters, plus the QUIC connection’s own byte counts |
Wire::add(up, down) |
fetch_add with Ordering::Relaxed on each counter, skipping a zero. drive passes up = transport_rx (from the client) and down = transport_tx (to the client). |
Wire::read() |
(up, down) so far. For a QUIC session it adds ConnectionBytes::bytes(), the connection’s udp_rx and udp_tx byte counts from quinn’s statistics, to the counted values. |
WireCounted (supervisor/src/serve.rs) |
The stream the SOCKS driver gets, since no runtime reports what it moved: a completed read adds its bytes to up, and a completed write adds its bytes to down |
How those counters become per-user usage is on Per-user usage accounting.
Each connection task runs under Shared::spawn_until(session.token(), …), which spawns until_cancelled(token, fut) on the supervisor’s TaskTracker. until_cancelled is tokio-util’s fut.with_cancellation_token_owned(token), a combinator rather than an async block over a select!, which would keep the future twice. When the token fires first, the future, and with it drive and the runtime, is dropped where it stands, and a future whose token is already cancelled never starts. The accept path, the transports and the sessions are on Listeners and the serve loop.
Invariants
Section titled “Invariants”| Invariant | Enforced by | Pinned by |
|---|---|---|
BUF_SIZE leaves room beyond the staging reserve |
assert! in build |
none |
| Bytes a queued ranged effect references are not moved or overwritten | Source pins: pinned(Source::Transport) blocks transport reads, make_room and feeding; scratch and held pins park outbound keys in starved; held_free() blocks byte events |
held_bytes_are_forwarded_after_the_dial_and_survive_later_rewrites, stalled_outbound_holds_uplink_but_not_other_downlink |
| Effects apply in the order pushed | drive_effects applies the queue front to back |
half_close_propagates_both_ways_and_finishes, stalled_outbound_holds_uplink_but_not_other_downlink |
| A forward is written only once its own key’s dial has completed | drive_effects writes a forward only to a Stream slot |
held_bytes_are_forwarded_after_the_dial_and_survive_later_rewrites, relays_two_keys_and_completes_on_fin |
| A protocol frame fits the read buffer, or the connection fails | is_saturated() check raises FrameTooLarge |
frame_larger_than_the_buffer_is_an_error, a_frame_past_the_grown_buffer_is_still_an_error |
A buffer grows to BUF_SIZE and no further |
make_room and grow_to cap at N; Staging::reserve grows only up to limit |
staging_grows_to_n_and_no_further, read_buffer_starts_small_and_doubles_up_to_n, a_frame_past_the_first_read_buffer_is_relayed_whole_both_ways |
| An outbound chunk can always be sealed toward the transport | Room check in service_key; stream reads capped at room - STAGING_RESERVE |
exercised by every relay test, for example relays_two_keys_and_completes_on_fin |
| A datagram outbound is never truncated by backpressure | Room check of STAGING_RESERVE + datagram_limit() |
datagram_outbound_is_never_truncated_by_staging_backpressure |
| Every byte staged toward a datagram transport has a peer | Staged-bytes versus framed-bytes check in deliver |
staging_without_a_peer_under_a_datagram_transport_is_an_error, stage_to_is_refused_under_a_stream_transport |
| One refused packet does not end the connection | poll_transport_send_packets drops and reports; drive_effects reports SendFailed and keeps the key |
a_refused_transport_packet_is_reported_not_fatal, a_refused_datagram_send_keeps_the_key_alive, single_peer_datagram_transport_demuxes_sessions_and_reports_refusals |
| An outbound failure is an event, not a runtime error | fail_outbound, and the ConnectFailed path in service_key |
connect_failure_reaches_the_core_as_an_event; through a client runtime, upstream_dial_failure_is_connect_failed_not_connected and refused_upstream_handshake_is_connect_failed_not_connected |
| A lost key is reported once and nothing more is sent to it | forget_key before the single event |
connect_failure_reaches_the_core_as_an_event covers the event; the purge of queued effects has no dedicated test |
| A wake-up during a poll is not lost | clear_queued() before polling; schedule() after every successful read |
clearing_queued_lets_the_key_be_queued_again in concepts/src/wake.rs |
| A burst of outbound wake-ups wakes the task once | Dedupe on queued; parent waker taken on wake |
wake_queues_key_once_and_wakes_parent in concepts/src/wake.rs |
| The deadline cannot be starved by ready I/O | Polled first in step |
none directly; deadline_event_lets_the_core_time_out covers firing |
| The deadline follows tokio’s clock | tokio::time::Instant::now() and sleep_until in set_deadline |
deadline_is_armed_against_the_tokio_clock |
| A busy quiet runtime cannot monopolize a worker | WORK_BUDGET loop and self-wake in Future::poll |
none |
| Deltas add up to the total | poll_once moves delta into summary on every progress step |
stream_mode_reports_each_unit_of_work |
| A stream inbound’s session wire is fed from the runtime’s transport counters | drive adds each delta’s transport_rx and transport_tx to the session’s Wire |
mux_sub_flows_and_their_session_count_exactly_what_moved in supervisor/tests/tracking.rs |
Failure paths and cancellation
Section titled “Failure paths and cancellation”RuntimeError
Section titled “RuntimeError”#[derive(Debug)]pub enum RuntimeError<E> { Transport(io::Error), Core(E), UnknownKey, DuplicateKey, RangeOutOfBounds, BadConsume, FrameTooLarge, WrongLinkKind, StagedWithoutPeer,}
impl<E: fmt::Display> fmt::Display for RuntimeError<E>;impl<E: fmt::Debug + fmt::Display> std::error::Error for RuntimeError<E>;impl<E> From<io::Error> for RuntimeError<E>;A RuntimeError ends the connection. Apart from Transport, Core and FrameTooLarge, every variant means the core broke the runtime’s contract, so it points to a bug in a protocol core rather than to a misbehaving peer. WrongLinkKind can also mean that the connector returned the other kind of link from the one the core expected. From<io::Error> maps to Transport.
| Variant | Display |
Raised when |
|---|---|---|
Transport(e) |
transport: {e} |
A transport read, write, flush or shutdown returns an error; a stream write accepts 0 bytes (WriteZero); a datagram transport returns a stream read. A refused datagram send is not an error. |
Core(e) |
proxy core: {e} |
Core::handle returns Err, for any event. A protocol core’s handshake deadline, for example, shows up as proxy core: client did not complete its request in time. |
UnknownKey |
effect targets an unknown outbound key |
A non-empty Forward or ForwardHeld, a SendTo or SendToHeld, or a Shutdown reaches the queue front for a key with no slot |
DuplicateKey |
open reuses a live outbound key |
Open reaches the queue front for a key that has a slot |
RangeOutOfBounds |
forward range outside the event slice or held buffer |
At enqueue, a range is reversed or ends past the event slice or held(); at apply, a held range no longer fits held() |
BadConsume |
core consumed an impossible byte count |
A Transport call reports more than it was given, or a TransportDatagram, Outbound or Datagram payload is not consumed whole |
FrameTooLarge |
protocol frame exceeds the read buffer |
The unparsed transport data fills BUF_SIZE and the core still wants more |
WrongLinkKind |
stream effect on a datagram outbound or vice versa |
Forward/ForwardHeld on a datagram slot, or SendTo/SendToHeld on a stream slot, found once the dial has completed |
StagedWithoutPeer |
bytes staged toward a datagram transport without a peer |
Under a datagram transport, the core staged bytes outside stage_to/put_to |
Outbound failures are events
Section titled “Outbound failures are events”Outbound failures never end the connection by themselves. They reach the core, and the core decides:
| Event | Raised when | Key afterwards |
|---|---|---|
ConnectFailed { key, error } |
The dial future resolves to Err |
Gone; queued effects for it dropped |
OutboundError { key, error } |
A write returns an error or 0 bytes, a flush or shutdown fails, a stream read fails, or a datagram receive fails | Gone; queued effects for it dropped |
SendFailed { key, to, error } |
A datagram outbound refuses one packet (for example UdpOutbound refusing a domain with Unsupported, “a plain UDP outbound cannot resolve a domain”) |
Live |
TransportSendFailed { to, error } |
A datagram transport refuses one packet | Not applicable; the runtime carries on |
The mux paths of TrojanCore, VlessCore and VMessCore turn a sub-flow’s outbound error into the end of that sub-flow and keep the connection, and AnyTlsCore ends that stream with a FIN and keeps the session; a single-flow core such as PassthroughCore finishes. That choice is the core’s, not the runtime’s.
Failures the supervisor’s wrappers raise
Section titled “Failures the supervisor’s wrappers raise”The supervisor’s outbound streams report its decision to close a flow through an ordinary I/O error, so the runtime needs nothing extra to honour it:
| Wrapper | Error | Raised on |
|---|---|---|
Metered (supervisor/src/track/metered.rs), when the flow was killed through the tracker: by Tracker::kill, or by Tracker::kill_where, which a drain uses through Target::close_flows (supervisor/src/topology/plane.rs) when the drain policy of the outbound version the flow was opened on closes its flows (DrainPolicy::Close at once, DrainPolicy::CloseAfter once its grace has passed), and which Supervisor::close_rerouted uses for the flows the current plane would send to another outbound |
ConnectionAborted, the flow was killed (from supervisor/src/track/mod.rs) |
The next read, write, flush or shutdown of that flow |
close_flows sets the version’s drained flag before it kills, and AppConnector::connect hands every flow it has just metered to Target::close_if_drained, so a flow that was still dialing during the drain is killed when it lands. For a stream outbound, the runtime turns the error into OutboundError for that key, drops the key’s queued effects, and the core decides what that means. killing_one_mux_sub_flow_leaves_its_siblings_and_the_carrier in supervisor/tests/tracking.rs shows the result through a VLESS mux connection: the killed sub-flow ends, its sibling keeps moving, and a new sub-flow still opens on the same carrier. UDP flows go through a FanOutLink instead, whose sub-links are wrapped the same way, in MeteredDatagram, and checked with close_if_drained when they land; see The plane: routing each flow. A flow through a balancer is filed under the member it was opened on, so the member’s drain closes it, not the balancer’s.
Stream mode after an error
Section titled “Stream mode after an error”poll_next yields the error once as Some(Err(e)), sets failed, and returns None on every later poll.
Cancellation by drop
Section titled “Cancellation by drop”Dropping the future or the stream cancels the connection. The runtime owns the transport, the core, every in-flight dial future and every outbound link, so all of them are dropped with it and their sockets close. Dropping does not flush: bytes still in staging are discarded and queued effects are never applied. There is no separate cancel method, and the runtime spawns nothing that could outlive it.
The callers rely on this:
| Caller | What drops the runtime |
|---|---|
drive |
Its own return on a handshake timeout; and Shared::spawn_until when the session’s token is cancelled. The supervisor cancels a session’s token when it closes that session (for example an explicit close, a user-removal policy that closes, or removing the inbound) and, through the root token, at shutdown; see Users, principals and sessions. |
serve_stream (TUN TCP) |
Its own return on a handshake timeout (tun: the client never spoke); and TunInbound::run, whose flows JoinSet owns every flow task, so dropping its future drops every runtime |
| The Hysteria 2 runtimes | Three nested JoinSets: Hy2Inbound::run owns one task per connection in connections; that task’s serve_connection owns the connection’s tasks, which hold the datagram runtime and the classifier; and the classifier owns the proxy-stream runtimes in serving. A connection that ends or is closed drops its tasks, and with them every runtime of the connection. |
In every case, dropping the runtime is the whole of the cleanup.
Limits
Section titled “Limits”| Constant | Value | Defined in | Meaning |
|---|---|---|---|
BUF_SIZE |
Per instantiation; see Buffer sizes per core | ProxyServerRuntime const generic |
Cap of each of the three buffers, and the largest protocol frame |
INITIAL |
2,048 | concepts/src/buffer.rs |
The size a read buffer starts at and the least a staging buffer first grows to, unless BUF_SIZE is smaller |
ProxyCoreDecode::STAGING_RESERVE |
Declared per core | concepts/src/core.rs |
Staging room guaranteed before the transport is read |
ProxyCoreDecode::MAX_DATAGRAM |
4,096 by default | concepts/src/core.rs |
Largest datagram delivered whole, on either side |
datagram_limit() |
min(MAX_DATAGRAM, BUF_SIZE - STAGING_RESERVE) |
concepts/src/runtime.rs |
Read size for a datagram outbound |
| Transport packet read size | MAX_DATAGRAM.min(BUF_SIZE) |
poll_transport_recv_packet |
Read size for a datagram transport |
WORK_BUDGET |
64 | concepts/src/runtime.rs |
Units of work per quiet Future::poll before a self-wake |
INLINE_EFFECTS |
4 | concepts/src/core.rs |
Effects held inline in EffectList and in the queue before spilling to the heap (a handshake typically pushes three: SetDeadline, Open and Forward) |
HANDSHAKE_TIMEOUT |
10 s | protocols/src/core/mod.rs |
The per-step timeout drive and serve_stream apply until the core is established. It is also the protocol cores’ own handshake deadline, armed through Timing (“how long a client has to complete its request once it has started it”); see Server core. |
RELAY_IDLE_TIMEOUT |
300 s | protocols/src/core/mod.rs |
The relay idle deadline a core arms through Timing, re-armed on every byte event; when it fires, Timing::expired pushes Effect::Finish |
MAX_SESSIONS |
256 | protocols/src/hysteria/server/datagrams.rs |
Associations one Hysteria 2 datagram runtime holds at once |
SWEEP_INTERVAL |
1 s | protocols/src/hysteria/server/datagrams.rs |
The deadline Hy2UdpCore re-arms to sweep idle associations |
FLOW_QUEUE |
16 | protocols/src/tun/udp.rs |
New flows queued toward one TUN UDP association before further ones are dropped |
MIN_WAIT, MAX_WAIT |
1 ms, 1 s | supervisor/src/track/pace.rs |
Shortest and longest sleep of a paced flow before it looks at its user’s bucket again |
Buffer sizes per core
Section titled “Buffer sizes per core”The values each caller instantiates BUF_SIZE with, and the core constants the runtime reads. Most of these constants carry a doc comment saying what they must hold; the glosses below quote them. VMessCore::BUF_SIZE (“The buffer size a runtime over this core needs.”) and PassthroughCore::BUF_SIZE (“Every buffer size this core needs.”) give no reason.
| Core | Key |
BUF_SIZE |
STAGING_RESERVE |
MAX_DATAGRAM |
datagram_limit() |
|---|---|---|---|---|---|
PassthroughCore (protocols/src/core/mod.rs) |
Single |
8 * 1024 = 8,192 |
0 |
default, 4,096 | 4,096 |
HttpCore |
Single |
MAX_HEAD = 64 * 1024 = 65,536: a whole request head |
256: a status line and its headers |
default, 4,096 | 4,096 |
TrojanCore |
FlowKey |
16 * 1024 = 16,384: a UDP packet frame is at most the header plus 8 KiB |
PACKET_HEADER_MAX.next_multiple_of(16) + downlink_overhead(BUF_SIZE) = 272 + 536 = 808: one UDP packet frame header, or the mux Keep headers one outbound read splits into, beyond the payload |
MAX_LENGTH = 8,192 |
8,192 |
VlessCore |
FlowKey |
16 * 1024 = 16,384: a UDP frame carries at most MAX_DATAGRAM bytes behind its length |
272 + downlink_overhead(BUF_SIZE) = 808: the response header, a UDP frame’s length prefix, or the mux Keep headers one outbound read splits into, beyond the payload |
8192 |
8,192 |
VMessCore |
FlowKey |
32 * 1024 = 32,768 |
4096: the response header plus the overhead of the chunks one outbound read of BUF_SIZE splits into |
8192 |
8,192 |
AnyTlsCore |
StreamKey (the stream’s wire id) |
16 * 1024 = 16,384: a Settings frame and a UDP packet frame fit with room to spare, and everything else is streamed |
2 * HEADER_LEN + MAX_SCHEME_LEN + SERVER_SETTINGS.len() = 14 + 2,048 + 3 = 2,065: the largest reply to one frame, the padding scheme and ServerSettings that answer the client’s Settings |
MAX_UDP_PAYLOAD = 8,192 |
8,192 |
SssCore, TCP stream |
FlowKey |
TCP_BUF_SIZE = 16 * 1024 = 16,384 |
PACKET_HEADER_MAX = 262: one datagram record’s header beyond its data |
MAX_DATAGRAM = 65,535 |
not used: a TCP stream opens no datagram outbound |
SssCore, UDP stream |
FlowKey |
UDP_BUF_SIZE = 66 * 1024 = 67,584: a whole record of U = 65535 bytes |
262, as above | 65,535 | 65,535 |
ShadowsocksCore |
Single |
20 * 1024 = 20,480: one chunk of MAX_PAYLOAD plus its overhead, with room to spare |
32 + 2 * RECORD_OVERHEAD + 28 = 128: the response salt plus the overhead of the chunks one outbound read (at most BUF_SIZE, so two chunks) splits into |
default, 4,096 | 4,096 |
Ss2022Core |
Single |
MAX_RECORD_LEN = MAX_PACKET_SIZE + RECORD_OVERHEAD = 65,535 + 34 = 65,569: the largest frame a client may send |
32 + 1 + 8 + 32 + 2 + 2 * TAG_LEN + RECORD_OVERHEAD + 115 = 256: the response header (salt, fixed chunk and two tags) or one record’s overhead beyond the payload |
default, 4,096 | 4,096 |
Hy2StreamCore |
Single |
8 * 1024 = 8,192: a request with the longest address and padding |
2048: a TCPResponse with the longest padding |
default, 4,096 | 4,096 |
Hy2UdpCore |
u32 (session id) |
16 * 1024 = 16,384: a reassembled packet plus its fragments’ headers |
4096: the fragment headers a reply of MAX_DATAGRAM splits into |
MAX_UDP_SIZE = 4,096 |
4,096 |
TunUdpCore |
Single |
8 * 1024 = 8,192: a datagram at most, plus what the runtime keeps in reserve |
4096: replies are staged whole, one packet each |
4096 |
4,096 |
The constants behind the computed values:
| Constant | Defined in | Value |
|---|---|---|
MAX_HEAD |
protocols/src/http/protocol.rs |
64 * 1024 = 65,536: the largest HTTP request or response head the core buffers |
MAX_LENGTH |
protocols/src/trojan/protocol.rs |
8,192: the largest single UDP packet payload the reader accepts (maxLength in Go) |
MAX_UDP_SIZE |
protocols/src/hysteria/protocol.rs |
4,096: the largest reassembled UDP payload accepted, upstream’s MaxUDPSize |
AddressCodec::MAX_LEN |
protocols/src/helpers/address.rs |
1 + 1 + 255 + 2 = 259 |
PACKET_HEADER_MAX |
protocols/src/trojan/protocol.rs |
AddressCodec::MAX_LEN + 2 + 2 = 263 (address, length, CRLF), rounded up to 272 by next_multiple_of(16) |
FRAME_OVERHEAD_MAX |
protocols/src/mux/frame.rs |
2 + MIN_META_LEN + 1 + AddressCodec::MAX_LEN + 2 = 2 + 4 + 1 + 259 + 2 = 268 |
MAX_DATA_LEN |
protocols/src/mux/frame.rs |
8 * 1024 = 8,192 |
downlink_overhead(read_size) |
protocols/src/mux/demux.rs |
read_size.div_ceil(MAX_DATA_LEN).saturating_mul(FRAME_OVERHEAD_MAX): one mux Keep header per 8 KiB piece of one outbound read. For 16,384 bytes: 2 × 268 = 536 |
TAG_LEN, RECORD_HEADER_LEN, RECORD_OVERHEAD |
protocols/src/ss_aead.rs |
16, 2 + TAG_LEN = 18, RECORD_HEADER_LEN + TAG_LEN = 34 |
MAX_PACKET_SIZE, MAX_RECORD_LEN |
protocols/src/ss_2022/crypto.rs |
0xFFFF = 65,535, 65,569 |
HEADER_LEN |
protocols/src/anytls/frame.rs |
7: an AnyTLS frame header (command, stream id, length) |
MAX_SCHEME_LEN |
protocols/src/anytls/padding.rs |
2,048: the longest padding scheme |
SERVER_SETTINGS, MAX_UDP_PAYLOAD |
protocols/src/anytls/core.rs |
b"v=2" (3 bytes); 8 * 1024 = 8,192, Trojan’s MAX_LENGTH |
PACKET_HEADER_MAX, MAX_DATAGRAM (sss) |
protocols/src/sss/protocol.rs |
262: the longest datagram record header, an address and a length; u16::MAX = 65,535 |
TrojanCore, VlessCore and VMessCore key their outbounds by FlowKey, because a connection may carry either its own flow (FlowKey::Direct) or mux.cool sub-flows (FlowKey::Sub); see mux.cool and XUDP. SssCore uses FlowKey too, but only FlowKey::Direct: an sss stream carries one request. AnyTlsCore keys each stream of its session by StreamKey, the id the client’s SYN gave it; see AnyTLS.
The integration tests live in concepts/tests/runtime.rs. They drive the runtime with toy sans-I/O cores over in-memory duplex streams, loopback UDP sockets and an mpsc-backed datagram link:
| Toy core | Transport | Key | STAGING_RESERVE |
Wire |
|---|---|---|---|---|
TinyMux |
Stream | u8 |
HDR + 64 = 68 |
[kind:u8][key:u8][len:u16][payload], payload XOR 0x55. Client kinds: 1 open, 2 data, 3 close, 4 fin. Replies: 2 data, 5 connected, 6 connect failed or outbound error (the error text, cut to 60 bytes), 7 EOF. An optional idle duration is re-armed with SetDeadline after every transport event that consumed bytes. |
TinyUdp |
Stream | Single |
4 | [len:u16][port:u16][payload]; len == 0 finishes; len == 0xFFFE sends an empty packet to an IPv6 loopback peer through an IPv4 socket, which the socket refuses; a SendFailed is answered with [0xFFFF][port] |
TinyHub |
Datagram, SocketAddr peers |
SocketAddr |
2 | [port:u16][payload], one UDP outbound per peer; port 0 finishes; port 0xFFFF puts a packet to an IPv6 peer through the IPv4 hub socket, and the core finishes on the TransportSendFailed; misbehave stages without a peer |
Sniffing |
Stream | Single |
0 | Holds the first 8 bytes as the target name and forwards them from held(); once open, clears the held buffer at the start of every transport event; overshoot pushes a held range one byte past the end |
TinySessions over TinyQuic |
Datagram, single peer (()) |
u32 |
6 | [session:u32][port:u16][payload]; session 0 finishes; the link refuses packets over 64 bytes (InvalidInput, “datagram too large”), and the core answers a refusal with the notice [0xFF, 0xFF, 0xFF, 0xFF, 0, 0] |
The TinyMux harness gives the client a 4,096-byte duplex and each outbound a duplex of a chosen capacity; its dialer refuses the target "fail" with ConnectionRefused, “refused by test”.
| Test | Behaviour it pins |
|---|---|
core_is_driven_without_any_io |
A core runs on hand-built events with no runtime: a split frame stays unconsumed, and payloads are decrypted in place |
relays_two_keys_and_completes_on_fin |
Two keys relay uplink and one relays downlink; Connected reaches the client for both; ShutdownTransport plus Finish completes; exact Traffic totals |
stalled_outbound_holds_uplink_but_not_other_downlink |
A forward the outbound only partly accepts keeps the transport unread until the rest is written, while another outbound’s downlink still reaches the client |
connect_failure_reaches_the_core_as_an_event |
A failed dial reaches the core as ConnectFailed, not as a runtime error |
half_close_propagates_both_ways_and_finishes |
Pending data reaches the outbound before its shutdown; outbound EOF reaches the core; the runtime finishes |
deadline_event_lets_the_core_time_out |
SetDeadline fires Deadline under a paused clock |
frame_larger_than_the_buffer_is_an_error |
FrameTooLarge with BUF_SIZE = 128 and a frame with a 500-byte payload (504 bytes with its 4-byte header) |
a_frame_past_the_first_read_buffer_is_relayed_whole_both_ways |
With BUF_SIZE = 16384, a 10,000-byte frame up and 12,000 bytes down pass whole although the buffers start at 2 KiB; outbound_tx is 10,000 and outbound_rx 12,000 |
a_frame_past_the_grown_buffer_is_still_an_error |
FrameTooLarge with BUF_SIZE = 8192 and a 9,000-byte payload, once the read buffer has grown to 8 KiB |
stream_mode_reports_each_unit_of_work |
showing_progress yields deltas that sum to the expected totals, one of them carrying the forward, and zero deltas for meta steps |
datagrams_round_trip_through_a_real_udp_socket |
SendTo and Event::Datagram through a real UDP outbound |
datagram_outbound_is_never_truncated_by_staging_backpressure |
With the client not reading, ten 1,000-byte replies wait at the socket instead of being truncated |
deadline_is_armed_against_the_tokio_clock |
The deadline uses tokio’s clock, not std’s: with the paused clock an hour ahead, a 5 s deadline does not fire within 4 s |
datagram_transport_demultiplexes_peers_and_frames_replies |
over_datagrams with many peers; each peer gets only its own replies; exact Traffic totals |
staging_without_a_peer_under_a_datagram_transport_is_an_error |
StagedWithoutPeer |
stage_to_is_refused_under_a_stream_transport |
stage_to returns None under a stream transport, while stage still works |
a_datagram_past_the_first_read_buffer_is_delivered_whole |
A 4,000-byte payload through a datagram transport and a UDP outbound with BUF_SIZE = 16384 arrives whole both ways: the transport read and the staged reply are both sized at their first use |
held_bytes_are_forwarded_after_the_dial_and_survive_later_rewrites |
The held name reaches the outbound once the gated dial completes, ahead of the bytes the client sent after it, although the core clears its held buffer at later transport events; outbound_tx is 21 |
a_held_range_past_the_buffer_is_rejected |
RangeOutOfBounds for a held range |
a_refused_datagram_send_keeps_the_key_alive |
SendFailed is reported and the same key keeps relaying |
a_refused_transport_packet_is_reported_not_fatal |
TransportSendFailed is reported, and the refused packet is not counted in transport_tx |
single_peer_datagram_transport_demuxes_sessions_and_reports_refusals |
A single-peer datagram link (TransportAddr = ()): an oversized reply is refused and other sessions carry on |
Unit tests next to the code:
| File | Test | Behaviour it pins |
|---|---|---|
concepts/src/buffer.rs |
read_buffer_compacts_unparsed_tail_to_front |
compact moves the unparsed tail to offset 0 |
concepts/src/buffer.rs |
read_buffer_saturation_means_frame_too_large |
is_saturated holds only when the unparsed region fills all N bytes |
concepts/src/buffer.rs |
write_buffer_slides_pending_when_full |
room() slides pending bytes when the tail is full; a full drain resets |
concepts/src/buffer.rs |
staging_refuses_over_reservation_without_partial_commit |
A refused reserve claims nothing |
concepts/src/buffer.rs |
read_buffer_starts_small_and_doubles_up_to_n |
A read buffer starts at 2 KiB, and make_room doubles it to 4 KiB and 8 KiB, keeping every byte |
concepts/src/buffer.rs |
make_room_moves_the_tail_and_grows_below_n |
make_room moves the tail and grows below N; at N it only moves |
concepts/src/buffer.rs |
compact_frees_room_in_any_buffer_short_of_saturated |
compact doubles when the move frees nothing |
concepts/src/buffer.rs |
a_small_n_is_allocated_whole |
A buffer whose N is below 2 KiB starts at N |
concepts/src/buffer.rs |
grow_to_makes_room_for_a_whole_datagram_up_to_n |
grow_to grows to the asked length, never shrinks, and stops at N |
concepts/src/buffer.rs |
write_buffer_holds_nothing_until_a_stage |
A write buffer allocates nothing until the first stage, and its room counts against N |
concepts/src/buffer.rs |
staging_grows_to_n_and_no_further |
A first stage past 2 KiB gets its length, doubling stops at N, and a reservation past N is refused |
concepts/src/wake.rs |
wake_queues_key_once_and_wakes_parent |
Dedupe, and one parent wake per registration |
concepts/src/wake.rs |
clearing_queued_lets_the_key_be_queued_again |
A key is queued again only after clear_queued |
Other tests that run a server runtime or pin the wrappers it relays through:
| File | Test or helper | What it shows |
|---|---|---|
concepts/tests/client.rs, module server_side |
server_runtime_relays_through_a_client_runtime_in_one_task |
A server runtime whose outbound is a client runtime in the same task; Connected reaches the core only once the upstream has received the header |
| same | upstream_dial_failure_is_connect_failed_not_connected, refused_upstream_handshake_is_connect_failed_not_connected |
A failed upstream dial or a refused upstream handshake reaches the server core as ConnectFailed |
environment/tests/integration/udp.rs |
dual_stack_link_serves_a_proxy_runtime |
A runtime whose connector is the environment crate’s Dialer, which implements Connector<DialTarget> and Connector<SocketTarget> (environment/src/dial/mod.rs). Its TinyUdp opens DialTarget::Udp(vec![AddressFamily::V4, AddressFamily::V6]), which UdpDialer::bind_dual turns into a DualStackUdp link; 4 bytes go each way. |
protocols/tests/support/pipeline.rs |
serve_runtime |
The harness the protocol tests use: one quiet runtime per accepted loopback connection, dialing through the harness’s own FreedomConnector (a TCP connect to an IP destination, or a UDP socket bound on 127.0.0.1; a domain is refused with Unsupported, “domain”), printing server runtime ended with {e} on an error. It is not the supervisor’s FreedomConnector. |
| same | serve_runtime_over |
As serve_runtime, but each accepted connection first goes through an InboundTransport (a TLS handshake, say) and the runtime runs over the stream it yields; the AnyTLS pipeline tests serve their core behind TLS with it |
supervisor/tests/tracking.rs |
mux_sub_flows_and_their_session_count_exactly_what_moved |
Through a VLESS inbound served by drive, the session’s up and down equal the bytes the client’s socket sent and received, and the user’s usage is the same |
| same | killing_one_mux_sub_flow_leaves_its_siblings_and_the_carrier |
A killed flow reaches the core as that key’s outbound error; the connection and the other keys carry on |
supervisor/tests/unit/track.rs |
killing_a_flow_fails_its_pending_read |
A Metered stream with a read pending fails it with ConnectionAborted once Tracker::kill kills its flow |
| same | killing_a_paced_flow_fails_its_pending_write |
A write parked on its user’s debt fails with ConnectionAborted on a kill, before its 1 s pacing sleep ends |
| same | a_limited_users_flow_moves_at_its_limit |
300,000 bytes at a limit of 100,000 B/s take between 2 s and 3 s: a one-second burst, then the debt |
| same | a_raised_or_removed_limit_is_felt_within_a_second |
A write parked on 10 s of debt resumes within MAX_WAIT of the limit being removed |
supervisor/tests/unit/plane.rs |
closing_a_targets_flows_aborts_its_open_streams |
A stream metered on a Tracker: close_flows(&tracker) returns 1, and the stream’s read, write and flush fail as aborted |
| same | closing_a_targets_flows_aborts_its_datagram_links_and_wakes_a_waiting_receive |
A metered datagram link’s pending receive fails as aborted when close_flows(&tracker) returns 1, and so does the next send |
| same | a_balanced_stream_is_closed_by_its_members_drain_not_the_balancers |
A stream opened through a balancer keeps working when the balancer’s close_flows returns 0, and fails when its member’s returns 1 |
| same | closing_a_targets_flows_leaves_other_versions_running |
A drain closes only its own version’s flows: not the next version of the same outbound, and not another outbound’s |
| same | a_flow_dialing_through_a_drain_is_closed_when_it_lands |
A flow still dialing during close_flows (which finds 0) is killed by close_if_drained once it is metered |
supervisor/tests/unit/serve.rs |
a_connections_future_holds_one_runtime_and_little_besides, a_spawned_connection_is_no_bigger_than_its_future |
A connection’s future holds one VMess runtime plus at most 1 KiB, and spawning it through until_cancelled adds at most 256 bytes |
| same | an_sss_connections_future_holds_one_runtime_and_little_besides |
serve_sss’s future is at most 1 KiB larger than the UDP-sized sss runtime: the gate, the TCP and UDP runtimes and a refusal’s drain are states of one future, not fields of it |
| same | a_camouflaged_connection_gives_its_handshake_permit_back |
Two REALITY sockets that are not clients are relayed to dest: their handshake permits are back while the relays run, their live permits are held, an IP-ban policy of one failure bans no one, and closing the sessions ends the relays and returns the live permits |
| same | until_cancelled_ends_a_pending_future_and_drops_it, until_cancelled_lets_a_finishing_future_finish, until_cancelled_never_starts_a_future_under_a_cancelled_token |
until_cancelled drops the future on cancellation, returns Some(()) when it finishes, and never starts it under a cancelled token |
The variants UnknownKey, DuplicateKey, WrongLinkKind and BadConsume, the WORK_BUDGET self-wake, and drive’s own handshake timeout have no dedicated test. Add one when you touch those paths. To test a core without the runtime, see Testing.