Skip to content

Transports: WebSocket and gRPC

Source files: 55 · checked against Etemenanki 46c12e4 · katana v6.1.0
  • Etemenanki/protocols/src/transports/mod.rs
  • Etemenanki/protocols/src/transports/ws/mod.rs
  • Etemenanki/protocols/src/transports/ws/endpoint.rs
  • Etemenanki/protocols/src/transports/ws/stream.rs
  • Etemenanki/protocols/src/transports/grpc/mod.rs
  • Etemenanki/protocols/src/transports/grpc/framing.rs
  • Etemenanki/protocols/src/transports/grpc/liveness.rs
  • Etemenanki/protocols/src/transports/grpc/settings.rs
  • Etemenanki/protocols/src/transports/grpc/stream.rs
  • Etemenanki/protocols/src/transports/accept.rs
  • Etemenanki/protocols/src/transports/coalesce.rs
  • Etemenanki/protocols/src/transports/connect.rs
  • Etemenanki/protocols/src/transports/stream.rs
  • Etemenanki/protocols/src/transports/keepalive.rs
  • Etemenanki/protocols/src/transports/tls/stream.rs
  • Etemenanki/protocols/src/transports/tls/config.rs
  • Etemenanki/app/src/main.rs
  • Etemenanki/app/src/transport.rs
  • Etemenanki/app/src/lower.rs
  • Etemenanki/app/src/subscribe.rs
  • Etemenanki/supervisor/src/topology/spec_plan/transport.rs
  • Etemenanki/supervisor/src/topology/spec_plan/inbound.rs
  • Etemenanki/supervisor/src/topology/inbound/mod.rs
  • Etemenanki/supervisor/src/build/inbound.rs
  • Etemenanki/supervisor/src/build/outbound.rs
  • Etemenanki/supervisor/src/build/validate.rs
  • Etemenanki/supervisor/src/serve.rs
  • Etemenanki/supervisor/src/guard.rs
  • Etemenanki/supervisor/src/carrier.rs
  • Etemenanki/supervisor/src/policy.rs
  • Etemenanki/protocols/tests/unit/transports/ws_endpoint.rs
  • Etemenanki/protocols/tests/unit/transports/grpc_framing.rs
  • Etemenanki/protocols/tests/unit/transports/grpc_liveness.rs
  • Etemenanki/protocols/tests/unit/transports/accept.rs
  • Etemenanki/protocols/tests/unit/transports/coalesce.rs
  • Etemenanki/protocols/tests/unit/transports/grpc_stream.rs
  • Etemenanki/protocols/tests/unit/transports/support.rs
  • Etemenanki/protocols/tests/pipeline/transports.rs
  • Etemenanki/app/tests/unit/lower.rs
  • Etemenanki/app/tests/unit/transport.rs
  • Etemenanki/supervisor/tests/unit/validate.rs
  • Etemenanki/supervisor/tests/unit/serve.rs
  • Etemenanki/supervisor/tests/unit/guard.rs
  • Etemenanki/supervisor/tests/guard.rs
  • Etemenanki/app/tests/support/mod.rs
  • Etemenanki/app/tests/support/runs.rs
  • Etemenanki/app/tests/integration/e2e_xray.rs
  • Etemenanki/app/tests/integration/e2e_xray_vmess.rs
  • Etemenanki/app/tests/integration/e2e_xray_mux.rs
  • Etemenanki/app/tests/integration/e2e_xray_wrapped.rs
  • katana/src/lower/inbound.rs
  • katana/src/lower/mod.rs
  • katana/src/config.rs
  • katana/src/api/newv2board.rs
  • katana/tests/integration/xray_interop.rs

WebSocket and gRPC are the two carriers that make a proxy connection look like web traffic. Both live in etemenanki-protocols (6.2.1 at this revision) under protocols/src/transports/, and both end in the same place: a TransportStream variant that implements AsyncRead + AsyncWrite, so a protocol core never learns which carrier it runs over.

This page is for contributors who change the carriers or the code that builds them: the upgrade, early-data and client-address handling of WebSocket, the Hunk/MultiHunk framing of gRPC, the HTTP/2 connection that one served socket turns into and the write batching under it, the timers that reclaim dead peers, and the WebSocket and gRPC parts of the path from a [.stream] block or a panel node to a built transport. TCP, TLS, TransportStream, MaybeTlsStream, resolve_stream, the supervisor’s validation and build of every transport spec, and TCP keepalive are covered in Transports: TCP and TLS.

Piece File → symbol Does Leaves to others
WebSocket endpoint ws/endpoint.rs → WsRoute, WsTarget, WsCallback, RealIpHeader Path normalisation, ?ed= parsing, Host check, early-data encoding, reading a client-address header, tungstenite limits TLS (below it), the payload (above it), deciding whether the header is believed (the supervisor)
WebSocket stream ws/stream.rs → WsStream Binary messages as bytes, Ping/Pong, Close as EOF, keepalive Ping, idle teardown, deferred client upgrade Protocol framing inside the payload
gRPC framing grpc/framing.rs → encode_hunk, encode_multi_hunk, HunkDecoder gRPC length prefix and the protobuf data field, message size cap HTTP/2 framing (the h2 crate)
gRPC settings grpc/settings.rs → GrpcPaths, GrpcMode h2 builder settings, the /<service>/Tun and /<service>/TunMulti paths, request and response headers, stream close
gRPC stream grpc/stream.rs → GrpcStream, StreamCount One HTTP/2 stream as bytes, writes under flow control, window credit, the client connection driver, the live-stream count Connection-level supervision on the server
Write batching coalesce.rs → Coalesced Under every served and every dialed HTTP/2 connection: holds h2’s writes until h2 flushes, at most one TLS record’s plaintext, so a DATA frame goes out as one write Reads, which pass straight through
Liveness grpc/liveness.rs → Liveness, ReadClock, Heard For a served HTTP/2 connection: the idle deadline, answered with GOAWAY; a PING every minute, where any byte heard from the peer counts as an answer; and a bound on a PONG that stays overdue
Accepting accept.rs → InboundTransport::accept, serve_h2 The 10 s transport handshake bound, fanning an HTTP/2 connection out into streams, refusing and logging other paths Serving each stream, which the caller’s sink does
Dialing connect.rs → TransportKind, TransportConnector Resolve, connect, keepalive, then wrap in TLS, WebSocket or gRPC Choosing the upstream (the outbound)
Lowering app/src/lower.rs → inbound_transport, outbound_transport; katana src/lower/inbound.rs → stream, real_ip, and src/api/newv2board.rs → transport for a UniProxy node A config block or a panel node becomes an InboundTransportSpec or OutboundTransportSpec; katana’s real_ip_header and real_ip_from become a WebSocket node’s InboundSpec::real_ip Building the transport
Building supervisor/src/build/inbound.rs → build_transport; supervisor/src/build/outbound.rs → transport_connector A validated spec becomes an InboundTransport or a TransportConnector Validation (build/validate.rs)
Serving supervisor/src/serve.rs → Connection::serve_socket, Connection::serve_tcp Runs accept on each accepted or handed-over TCP socket and serves every yielded stream in a session; on WebSocket, takes the client from a trusted proxy’s header (real_ip_source); on gRPC, closes a connection whose streams keep failing to authenticate, and has the next VMess stream try the user the connection’s last authenticated stream matched (supervisor/src/carrier.rs → Carrier) The accept loop and the drivers (Listeners and the serve loop)

Outside etemenanki-protocols and its tests, only the supervisor builds these transports. etemenanki-app and katana describe a transport in their spec and never construct one; WsStream::accept, WsStream::connect and GrpcStream::connect are public, but only the enums and their helper constructors are used outside the crate.

protocols/src/transports/ws/mod.rs and grpc/mod.rs declare every submodule pub, so the carriers’ public types can be reached by path as well as through the re-exports:

Path Public items
transports (re-exports in transports/mod.rs) Accepted, InboundTransport, TransportConnector, TransportKind, TransportStream
transports::ws WsStream, re-exported from ws::stream, and RealIpHeader, re-exported from ws::endpoint
transports::ws::endpoint WsRoute (new, host, real_ip_header), WsTarget (new, early_data_limit), RealIpHeader and MAX_REAL_IP_ADDRESSES; every other item is pub(crate) or private
transports::ws::stream WsStream (from_upgraded, accept, connect, is_open, real_ip_header), WS_IDLE_TIMEOUT, WS_KEEPALIVE_INTERVAL
transports::grpc GrpcStream, re-exported from grpc::stream
transports::grpc::settings GrpcPaths (new, classify) and GrpcMode; the constants (H2_PONG_TIMEOUT among them), builders and header helpers are pub(crate) or private
transports::grpc::stream GrpcStream (connect); GrpcStream::served and StreamCount are pub(crate)
transports::grpc::framing, transports::grpc::liveness nothing public: every item is pub(crate) or private
transports::coalesce nothing public: the module itself is pub(crate)

Both carriers end in TransportStream, as Ws(Box<WsStream<MaybeTlsStream>>) and Grpc(Box<GrpcStream>). The enum, its forwarding AsyncRead and AsyncWrite impls and its real_ip_header accessor are described in TransportStream; MaybeTlsStream and the other tls/stream.rs helpers (tcp_from_std, accept_optional_tcp, wrap_optional_tcp) in MaybeTlsStream and the helpers.

protocols/src/transports/accept.rs
pub const TRANSPORT_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
pub type Accepted = TransportStream;
#[derive(Clone)]
#[non_exhaustive]
pub enum InboundTransport {
Tcp,
Tls(ServerConfig),
Ws {
route: WsRoute,
tls: Option<ServerConfig>,
},
Grpc {
paths: Arc<GrpcPaths>,
tls: Option<ServerConfig>,
},
#[cfg(feature = "reality")]
Reality(super::reality::RealityServer),
}
impl InboundTransport {
pub fn ws(path: impl AsRef<str>, host: Option<&str>, tls: Option<ServerConfig>) -> Self;
pub fn grpc(service: impl AsRef<str>, tls: Option<ServerConfig>) -> Self;
pub async fn accept<F>(&self, tcp: TcpStream, mut sink: F) -> io::Result<Disposition>
where
F: FnMut(Accepted);
}
fn timed_out(what: &str) -> io::Error;
async fn within<T>(what: &str, fut: impl Future<Output = io::Result<T>>) -> io::Result<T>;
async fn maybe_tls(tcp: TcpStream, tls: Option<&ServerConfig>) -> io::Result<MaybeTlsStream>;
fn h2_io<T>(io: T, heard: &ReadClock) -> Heard<Coalesced<T>>;
async fn serve_h2<T, F>(
conn: Connection<T, Bytes>,
heard: ReadClock,
paths: &GrpcPaths,
peer: Option<SocketAddr>,
sink: &mut F,
) -> io::Result<()>;
fn logged_path(path: &str) -> &str;

InboundTransport::ws builds a WsRoute from path and adds host with WsRoute::host when one is given; a route built this way reads no client-address header. Only the pipeline tests call it: the supervisor builds the Ws variant itself, so that it can name the header (see What the supervisor builds). InboundTransport::grpc wraps GrpcPaths::new(service) in an Arc, so every clone of the transport shares one pair of path strings. For both carriers accept returns Disposition::Done; only REALITY returns anything else (see InboundTransport).

accept calls set_keepalive(&tcp) first, then:

Variant Inside within(what, …) Then
Ws what = "websocket": maybe_tls (the TLS accept when tls is Some), then WsStream::accept(io, route) sink(TransportStream::Ws(Box::new(stream))), and accept returns Ok(())
Grpc what = "grpc": maybe_tls, wrapped by h2_io in Heard<Coalesced<_>>, then configured_server_builder().handshake(io), an h2 error mapped with io::Error::other serve_h2(conn, heard, paths, peer, &mut sink), which returns when the HTTP/2 connection ends

Before the gRPC handshake, accept takes peer = tcp.peer_addr().ok(), which only the log lines use, and heard = ReadClock::new(), the clock Heard stamps on every read that brings bytes (see Liveness). h2_io puts Coalesced next to the stream whose records it shapes and Heard on h2’s side of it, where it sees reads as h2 makes them (see Write batching under h2). The Tcp arm and the Tls arm (within("tls", …), tls handshake timed out) are described in InboundTransport.

within wraps the future in tokio::time::timeout(TRANSPORT_HANDSHAKE_TIMEOUT, …), and on expiry returns timed_out(what): io::ErrorKind::TimedOut with the text websocket handshake timed out or grpc handshake timed out. The bound covers only the transport’s own step (TLS, the upgrade, the h2 preface). The protocol handshake behind it has a bound of its own, described on Listeners and the serve loop.

accept returns as soon as the one stream is handed to sink for WebSocket. For gRPC it returns only when the HTTP/2 connection ends, because the future itself is the connection driver (see Serving an HTTP/2 connection). A sink that served a gRPC stream inline would stop that driver, so the sink hands each stream to another task.

protocols/src/transports/connect.rs
#[derive(Clone)]
pub enum TransportKind {
Tcp,
Tls(ClientConfig),
Ws {
target: WsTarget,
tls: Option<ClientConfig>,
},
Grpc {
authority: Arc<str>,
service: Arc<str>,
mode: GrpcMode,
user_agent: Option<Arc<str>>,
tls: Option<ClientConfig>,
},
}
impl TransportKind {
pub fn ws(host: impl AsRef<str>, path: impl AsRef<str>, tls: Option<ClientConfig>) -> Self;
pub fn grpc(
authority: impl AsRef<str>,
service: impl AsRef<str>,
tls: Option<ClientConfig>,
) -> Self;
#[must_use]
pub fn multi(mut self) -> Self;
#[must_use]
pub fn user_agent(mut self, agent: Option<&str>) -> Self;
async fn wrap(&self, tcp: TcpStream) -> io::Result<TransportStream>;
}
#[derive(Clone)]
pub struct TransportConnector {
kind: Arc<TransportKind>,
dialer: Dialer,
resolver: Resolver,
strategy: AddressFamilyStrategy,
}
impl TransportConnector {
pub fn new(
kind: TransportKind,
dialer: Dialer,
resolver: Resolver,
strategy: AddressFamilyStrategy,
) -> Self;
pub fn tcp() -> Self;
pub async fn dial(&self, dest: &Destination) -> io::Result<TransportStream>;
}
impl Connector<Destination> for TransportConnector {
type Stream = TransportStream;
type Datagram = NoDatagram;
/* … */
}
Method Effect on Ws or Grpc On other variants
TransportKind::ws(host, path, tls) Ws { target: WsTarget::new(host, path), tls }; a ?ed=N on path enables early data — (constructor)
TransportKind::grpc(authority, service, tls) Grpc with mode = GrpcMode::Gun and user_agent = Some(DEFAULT_USER_AGENT) — (constructor)
multi() Switches a Grpc value to GrpcMode::Multi (TunMulti, for an Xray peer with multiMode: true) Returns the value unchanged
user_agent(Some(agent)) Replaces the user-agent header of a Grpc value Returns the value unchanged
user_agent(None) Removes the header Returns the value unchanged

TransportConnector::dial refuses a DialNetwork::Udp destination with io::ErrorKind::Unsupported and the text a proxy transport carries no datagrams of its own, pinned by transport_connector_refuses_udp (protocols/tests/pipeline/transports.rs): a proxy’s UDP rides inside its stream. Otherwise it resolves the upstream, connects to the first address that answers, calls set_keepalive, and then wrap. For Ws, wrap runs the TLS client handshake when tls is Some and then WsStream::connect(io, target, tls.is_some()). For Grpc, it runs the same TLS step and then GrpcStream::connect(io, tls.is_some(), authority, service, mode, user_agent). The secure flag only selects the URI scheme: wss or ws for the upgrade request, https or http for the gRPC request.

The connector keeps its kind as Arc<TransportKind>, so its clones share one value. TransportConnector::tcp(), the Connector<Destination> impl (which yields Outbound::Stream and can never yield a datagram, since NoDatagram is uninhabited), and the resolve and connect steps of dial are described in TransportKind and TransportConnector and Dialing an upstream.

Every accepted or dialed socket gets TCP keepalive first, then optional TLS, then the carrier. Under HTTP/2, Coalesced sits between the TLS layer and h2:

flowchart LR
  tcp["TcpStream"] --> ka["set_keepalive"]
  ka --> tls["MaybeTlsStream"]
  tls --> ws["WsStream"]
  tls --> co["Coalesced"]
  co --> h2["h2 Connection"]
  h2 --> g1["GrpcStream"]
  h2 --> g2["GrpcStream"]
  ws --> ts["TransportStream"]
  g1 --> ts
  g2 --> ts
  ts --> core["protocol core"]

One accepted WebSocket socket yields exactly one stream. One accepted gRPC socket yields one stream per HTTP/2 stream the peer opens on the tunnel paths. MaybeTlsStream (protocols/src/transports/tls/stream.rs) is Plain(TcpStream) or Tls(Box<SslStream<TcpStream>>); both carriers run over it, so plaintext and TLS share one I/O path.

etemenanki-app and katana describe a WebSocket or gRPC transport as one of two variants of the supervisor’s StreamShape (supervisor/src/topology/spec_plan/transport.rs): Ws { path, host, tls } or Grpc { service, authority, tls }, where tls says whether TLS is layered underneath. The shape sits in an InboundTransportSpec beside an optional ServerTlsSpec, or in an OutboundTransportSpec beside an optional ClientTlsSpec. The type and app/src/transport.rs → resolve_stream, which derives the shape for app inbounds and outbounds alike, are described in resolve_stream and StreamShape; tls_layer, which validates security against network, in tls_layer. What each front end fills into the WebSocket and gRPC fields:

Field etemenanki-app inbound (inbound_transport) etemenanki-app outbound (outbound_transport) katana inbound (stream)
WebSocket path ws.path, default "/" ws.path, default "/" the node’s path, which helium-node-api holds to a leading / and no query but ?ed=N; a UniProxy node’s settings’ path, "/" if missing or empty
WebSocket Host ws.host, or None (any Host accepted) ws.host, then tls.server_name, then server the node’s host, None when absent, never with a port; a UniProxy node’s Host header, None if empty
gRPC service grpc.service_name, required grpc.service_name, required the node’s service_name, which must not be empty
gRPC authority grpc.authority, not used by a server grpc.authority, then tls.server_name, then server None
TLS under ws or grpc security = "tls" security = "tls" the node’s security; always on Trojan, SOCKS and HTTP nodes

The WebSocket Host and the gRPC authority never become the TLS server name: the SNI, which is also the name the certificate is checked against, comes from tls.server_name or server only. app/tests/unit/lower.rs → a_server_config_lowers_to_its_spec pins two outbound fallbacks. An outbound with server = "203.0.113.1", security = "tls", tls.server_name = "cdn.example" and no ws.host lowers to Ws { path: "/", host: Some("cdn.example"), tls: true }, so the Host falls back from ws.host to tls.server_name, and its SNI is cdn.example, from tls.server_name rather than server. The same test pins a WebSocket inbound (Ws { path: "/t", host: None, tls: true } with the PEM bytes read) and a gRPC inbound (Grpc { service: "svc", authority: None, tls: false }).

One more input concerns only WebSocket inbounds: InboundSpec::real_ip (supervisor/src/topology/spec_plan/inbound.rs), the header a reverse proxy in front names the client in and the networks of the proxies trusted to set it. etemenanki-app has no key for it and always lowers real_ip: None. katana fills it from [node.controller]’s real_ip_header and real_ip_from, on WebSocket nodes only (see Lowering inbounds and outbounds). A katana reload that changes only these two keys applies at once: new connections read the new setting, and open ones are kept. What the supervisor does with it is in The client a trusted proxy names.

The inbounds that take a transport are those InboundProtocolSpec::transport names: SOCKS, HTTP, Trojan, VLESS, VMess, Shadowsocks, Shadowsocks 2022, AnyTLS and sss. AnyTLS runs over TLS alone and so over neither carrier, and a SOCKS inbound over either carrier must turn udp off; Shadowsocks over either carrier relays TCP only. A Unix listener carries neither carrier. etemenanki-app refuses a [.stream] block on such a listener that names a network other than tcp or a security other than none (reject_stream_settings) and lowers StreamShape::Tcp with no TLS, pinned by a_unix_listen_lowers_to_a_plain_stream (app/tests/unit/lower.rs). The supervisor refuses any other shape on a Unix bind, pinned by a_unix_listener_carries_only_the_plain_tcp_shape (supervisor/tests/unit/validate.rs), which includes a Ws shape.

The outbounds that take a transport are the proxy clients: SOCKS, HTTP, Trojan, VLESS, VMess, Shadowsocks, Shadowsocks 2022 and sss over either carrier, and AnyTLS over TLS alone. Outbounds from a subscribe file are first translated into the same [outbound.stream] structure (app/src/subscribe.rs → stream_config), so the same fallbacks and errors apply; see Subscribe files. katana’s other transports and refusals are on Lowering inbounds and outbounds.

etemenanki-app refuses a config that leaves out a name one of the carriers needs. app/src/main.rs logs the lowering error behind configuration invalid: under --test, and behind failed to start: on a normal start. The WebSocket and gRPC texts, as --test prints them (timestamps removed):

ERROR etemenanki_app: configuration invalid: inbound vless-in: grpc stream needs grpc.service_name
ERROR etemenanki_app: configuration invalid: inbound vless-in: protocol vless over a unix socket does not support stream network "ws"
ERROR etemenanki_app: configuration invalid: outbound proxy: ws stream needs ws.host or server
ERROR etemenanki_app: configuration invalid: outbound proxy: grpc stream needs grpc.authority or server
ERROR etemenanki_app: configuration invalid: outbound proxy: ws+tls stream needs tls.server_name or server

The last one needs ws.host set and neither tls.server_name nor server; the gRPC form reads grpc+tls stream needs tls.server_name or server. The certificate, key and CA texts are described in etemenanki-app: from TOML to a spec. The user-facing keys are documented in Transports and TLS.

validate (supervisor/src/build/validate.rs) checks every transport spec before anything is built; the full rule table is in Validation in the supervisor. Five rules concern only these carriers:

Rule Applies to Reason text
Ws { host: None, .. } outbound ws transport needs a host
Grpc { authority: None, .. } outbound grpc transport needs an authority
real_ip on anything but an inbound whose transport (InboundProtocolSpec::transport) has a Ws shape, on a TCP bind inbound only a websocket transport on a tcp listener reads a real-ip header
real_ip with an empty trusted list inbound a real-ip header needs at least one trusted proxy
real_ip.header that WsRoute::real_ip_header refuses inbound the real-ip header "<header>" is not a header name

The front end fills the host and the authority; a gap that reaches the supervisor is refused rather than guessed at. An inbound needs neither, since a server has nothing to borrow them from. A real-IP setting with no trusted proxy would never count, which validate.rs → real_ip_header treats as a mistake to report rather than a setting to keep. On an outbound, validate.rs → outbound_transport checks the TLS mismatch first and the host or authority second. On an inbound, validate_inbound checks the three real-IP rules, in the order above, before the Unix rule and the TLS mismatch. How the refusals are reported is on Validation and apply errors.

build/inbound.rs → build_transport and build/outbound.rs → transport_connector then build the values (see Building the values). For these carriers:

  • On the inbound side, build_transport(spec, real_ip, socket) builds Ws { path, host, .. } as InboundTransport::Ws { route, tls: tls(Alpn::Http1)? }. The route is WsRoute::new(path), then .host(host) when host is Some, so the Host is checked only then, then .real_ip_header(&real_ip.header)? when the inbound’s real_ip is Some. build_handler passes spec.real_ip in and copies it into StreamInbound::real_ip (supervisor/src/topology/inbound/mod.rs) for the serve loop. On the outbound side Ws becomes TransportKind::ws(host, path, tls(Alpn::Http1)?).
  • Grpc { service, authority, .. } becomes InboundTransport::grpc(service, tls(Alpn::Http2)?). authority is ignored there, because a server does not check the authority a client sends. On the outbound side it becomes TransportKind::grpc(authority, service, tls(Alpn::Http2)?).
  • transport_connector always uses TransportKind::grpc, so every gRPC outbound opens Tun with GrpcMode::Gun and DEFAULT_USER_AGENT: the supervisor calls neither multi nor user_agent.
  • On the outbound side a None host or authority fails with missing ws host or missing grpc authority (io::ErrorKind::InvalidInput). Validation makes both unreachable.

On the inbound side tls(alpn) is TlsServerConfig::from_pem(&cert_pem, key_pem.expose(), alpn) when the spec carries a ServerTlsSpec; on the outbound side it is ClientConfig::with_verify_mode(&server_name, verify, alpn). Alpn::Http1 offers and selects http/1.1 (wire bytes \x08http/1.1) and Alpn::Http2 offers and selects h2 (\x02h2). When a client does not offer the server’s protocol, the server’s select callback returns AlpnError::NOACK and the handshake goes on without ALPN instead of failing (see ALPN). Every front end gets the same ALPN, because every inbound is built here: katana’s WebSocket nodes with TLS negotiate http/1.1 just as etemenanki-app’s do. The rest of the outbound build is on Outbounds, UDP fan-out and balancers.

Serving in the supervisor: one session per stream

Section titled “Serving in the supervisor: one session per stream”

supervisor/src/serve.rs → run_stream_inbound accepts each socket and spawns Connection::serve_socket for it; the accept loop and the drivers are on Listeners and the serve loop. For a Unix socket no transport runs: the stream is served inline, with no local IP. For a TCP socket, serve_socket settles the connection’s client: the socket’s peer, or the client a PROXY protocol v2 header names when the inbound reads one, or, for a socket a relay on the same host handed over, the client named beside it. Connection::serve_tcp then drops a source the guard has banned, reads the socket’s local IP (tcp.local_addr()), and runs the inbound’s InboundTransport::accept with a closure as the sink (all on Accepting a socket):

flowchart TB
  acc["run_stream_inbound: accepted or handed-over TCP socket"] --> ss["Connection::serve_socket"]
  ss --> pp["the client, then serve_tcp: ban check"]
  pp --> ta["InboundTransport::accept(tcp, sink)"]
  ta -->|"Tcp, Tls, Ws or REALITY: one stream"| one["sink: the socket's own session"]
  ta -->|"Grpc: one call per HTTP/2 stream"| own["sink: Shared::connector opens a new session"]
  one --> sc["Shared::spawn_until: serve_connection"]
  own --> sc
  ta -->|"Err"| log["debug: inbound transport failed"]
  • multiplexed is matches!(transport, InboundTransport::Grpc { .. }).
  • The closure first settles the stream’s client. When the inbound has real_ip and the stream’s TransportStream::real_ip_header is Some (a WebSocket upgrade whose route reads the header), real_ip_source picks it, as The client a trusted proxy names describes; otherwise the client stays the connection’s source. A named client other than that source is checked against the guard’s bans first: a banned one is dropped, and the closure returns without serving the stream. On a connection that is not multiplexed, Session::set_source then records it on the socket’s session, so the device limit counts the named client rather than the proxy. From there on it is the source the connector, the Report and the core see.
  • For every other transport the closure serves the one stream as the socket’s own session, with a connector from Shared::connector_for.
  • For gRPC the closure opens a new session through Shared::connector for every stream, with a Wire of its own: each HTTP/2 stream is a session of its own.
  • In both cases the closure spawns serve_connection for the stream, with the local IP and a Report (supervisor/src/guard.rs), on the supervisor’s TaskTracker under its session’s token, and returns. On these carriers every stream runs a protocol core, whose handshake ends in that Report: a refused credential (PermissionDenied before the core is established) counts as a failure, and an established core as a success.
  • For gRPC, serve_tcp makes one Carrier (supervisor/src/carrier.rs) per connection, holding the token of the socket’s own session, and every stream’s Report shares it. A carrier’s streams are almost always one client’s, as the module doc puts it, so they share two things. One is a count of the connection’s failed streams in a row (Carrier::failed); a success clears it (Carrier::succeeded). The other is the user the connection’s last authenticated stream matched: Report::succeeded(user) stores it when the core names one (only VMessCore does, through Established::user_hint) and keeps the old one when it does not, and the next VMess stream of the connection tries that user first (Report::carrier_hint, VMessCore::with_hint; see VMess: keys and authentication). A failure leaves the stored user alone. Once Policies::carrier_max_failures (supervisor/src/policy.rs) failures in a row have counted, Report::failed logs closing a gRPC connection from <source> after <n> failed streams in a row at debug and cancels that token (Carrier::close), which drops accept and with it the connection. The default None never closes a connection for that; etemenanki-app leaves it there, and katana sets it from [node.controller].carrier_max_failures, default 8, where 0 means None (src/config.rs, src/lower/mod.rs → policies).
  • When accept returns an error, serve_tcp logs inbound transport failed: <error> at debug (target etemenanki_supervisor::serve).

What a session’s wire bytes count on these carriers (the protocol stream after the WebSocket or gRPC transport; a gRPC carrier’s own framing counts toward nobody) is on Per-user usage accounting.

protocols/src/transports/ws/endpoint.rs
pub(crate) const MAX_EARLY_DATA: usize = 16 * 1024;
pub(crate) const MAX_WS_MESSAGE_LEN: usize = 1024 * 1024;
pub(crate) fn ws_config() -> tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
pub const MAX_REAL_IP_ADDRESSES: usize = 32;
#[derive(Default)]
pub(crate) struct Upgraded {
pub(crate) early_data: Option<Bytes>,
pub(crate) real_ip: Option<RealIpHeader>,
}
pub(crate) type UpgradeSlot = Arc<Mutex<Upgraded>>;
pub(crate) fn upgrade_slot() -> UpgradeSlot;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RealIpHeader {
Missing,
Malformed,
Addresses(Box<[IpAddr]>),
}
impl RealIpHeader {
fn read(headers: &HeaderMap, name: &HeaderName) -> Self;
}
pub(crate) fn normalize_path(path: &str) -> String;
pub(crate) fn parse_early_data_path(path: &str) -> (String, Option<usize>);
pub(crate) fn host_matches(request_host: &str, config: &str) -> bool;
pub(crate) fn decode_early_data_header(value: &str) -> Result<Option<Bytes>, ()>;
pub(crate) fn encode_early_data_header(bytes: &[u8]) -> String;
#[derive(Clone, Debug)]
pub struct WsRoute {
path: Arc<str>,
host: Option<Arc<str>>,
real_ip: Option<HeaderName>,
}
impl WsRoute {
pub fn new(path: impl AsRef<str>) -> Self;
#[must_use]
pub fn host(mut self, host: impl Into<Arc<str>>) -> Self;
pub fn real_ip_header(mut self, name: &str) -> io::Result<Self>;
pub(crate) fn callback(&self, upgraded: UpgradeSlot) -> WsCallback;
fn accepts(&self, path: &str, host: Option<&str>) -> bool;
}
pub(crate) struct WsCallback {
route: WsRoute,
upgraded: UpgradeSlot,
}
impl Callback for WsCallback {
fn on_request(self, req: &Request, resp: Response) -> Result<Response, ErrorResponse>;
}
#[derive(Clone, Debug)]
pub struct WsTarget {
host: Arc<str>,
path: Arc<str>,
early_data_limit: Option<usize>,
}
impl WsTarget {
pub fn new(host: impl AsRef<str>, path: impl AsRef<str>) -> Self;
pub fn early_data_limit(&self) -> Option<usize>;
pub(crate) fn client_request(
&self,
tls: bool,
early_data: Option<&Bytes>,
) -> std::io::Result<http::Request<()>>;
}
fn reject_404() -> ErrorResponse;
fn reject_413() -> ErrorResponse;

WsRoute is what an inbound accepts; WsTarget is what an outbound requests. WsCallback implements tungstenite’s Callback and runs inside the server handshake with a clone of the route and the shared UpgradeSlot, which carries what the upgrade request held besides the upgrade itself: its early data and, on a route that reads one, what its client-address header said. The parking-lot Mutex in the slot is locked at most three times per connection: by the callback when it stores the header’s reading and when it stores valid early data, and by WsStream::accept when it takes the whole Upgraded out with std::mem::take.

client_request formats ws://<host><path> or wss://<host><path>, parses it as an http::Uri and turns it into tungstenite’s client request with into_client_request. tungstenite 0.30 fills five headers: Host (the URI’s authority, which is the WsTarget host as written), Connection: Upgrade, Upgrade: websocket, Sec-WebSocket-Version: 13 and a generated Sec-WebSocket-Key. With early data, client_request inserts the encoded bytes as Sec-WebSocket-Protocol. No other header is added. Each step maps its error with io::Error::other, so a host that does not form a valid URI fails there.

protocols/src/transports/ws/stream.rs
pub const WS_IDLE_TIMEOUT: Duration = Duration::from_secs(300);
pub const WS_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(60);
type Upgrade<S> = Pin<Box<dyn Future<Output = io::Result<WebSocketStream<S>>> + Send>>;
enum State<S> {
Deferred {
stream: Option<S>,
target: WsTarget,
secure: bool,
limit: usize,
},
Upgrading(Upgrade<S>),
Open(Box<WebSocketStream<S>>),
Failed(io::ErrorKind, String),
}
pub struct WsStream<S> {
state: State<S>,
pending_read: Bytes,
read_closed: bool,
close_sent: bool,
control: Option<Message>,
keepalive: Pin<Box<Sleep>>,
idle: Pin<Box<Sleep>>,
read_waker: Option<Waker>,
real_ip: Option<RealIpHeader>,
}
impl<S> WsStream<S>
where
S: AsyncRead + AsyncWrite + Unpin,
{
pub fn from_upgraded(ws: WebSocketStream<S>, initial: Option<Bytes>) -> Self;
pub fn real_ip_header(&self) -> Option<&RealIpHeader>;
pub async fn accept(stream: S, route: &WsRoute) -> io::Result<Self>;
pub async fn connect(stream: S, target: &WsTarget, secure: bool) -> io::Result<Self>
where
S: Send + 'static;
pub fn is_open(&self) -> bool;
fn with_state(state: State<S>, pending_read: Bytes) -> Self;
fn touch(&mut self);
fn start_upgrade(&mut self, first: &[u8]) -> io::Result<usize>
where
S: Send + 'static;
fn poll_open(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<&mut WebSocketStream<S>>>;
fn poll_control(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
fn take_pending(&mut self, buf: &mut ReadBuf<'_>);
}
impl<S> AsyncRead for WsStream<S> where S: AsyncRead + AsyncWrite + Unpin { /* … */ }
impl<S> AsyncWrite for WsStream<S> where S: AsyncRead + AsyncWrite + Unpin + Send + 'static { /* … */ }
fn ws_err(e: WsError) -> io::Error;
fn after(d: Duration) -> Instant;

In TransportStream the stream is always WsStream<MaybeTlsStream>, boxed. from_upgraded seeds pending_read with initial (or nothing), and with_state arms both timers from tokio::time::Instant::now() (after) and leaves real_ip at None. accept passes the slot’s early data to from_upgraded and then moves the header’s reading into real_ip, so real_ip_header is Some only on an accepted session whose route reads a header; from_upgraded and connect give None. is_open is true only in State::Open. start_upgrade returns Ok(0) when the state is not Deferred; its two callers, poll_write and poll_shutdown, only call it in Deferred.

WsRoute::new runs the configured path through normalize_path, which strips ?ed= with parse_early_data_path before it mirrors Xray’s GetNormalizedPath (empty becomes /, a missing leading / is added). WsTarget::new calls parse_early_data_path itself to keep the limit, then normalize_path. The same path string can therefore be written on both sides: the server strips ?ed=N just as the client does, and never sees it on the wire. The VMess early-data interop tests configure both ends with /vmess?ed=2048.

Configured path Upgrade path Early-data limit (WsTarget)
"" / none
echo /echo none
/x?ed=2048 /x Some(2048)
x?ed=2048 /x Some(2048)
/x?foo=1&ed=2048 /x?foo=1 Some(2048)
/x?foo=1 /x?foo=1 none

The rules in parse_early_data_path:

  • Only a query part named ed with a non-empty value is treated as early-data configuration. It is removed from the path whether or not its value parses.
  • The value is parsed as usize. A value that does not parse removes the parameter but leaves the limit at None.
  • With several ed parts, each one overwrites the limit, so the last decides; a later one that does not parse resets it to None.
  • When ed is present, empty query parts are dropped and the remaining ones are re-joined with &; with none left, the ? goes too. Without ed (an ed= with an empty value included), the path is returned untouched.
  • WsStream::connect only defers the upgrade when the limit is greater than zero, so ?ed=0 means no early data.

host_matches mirrors Xray’s internet.IsValidHTTPHost: both sides are lower-cased, the request value is cut at its last : to drop a port, and the host part must equal the configured value exactly.

Route Request Result
no host configured any Host, or none accepted
example.com Example.COM:443 accepted
example.com other.example:443 404
example.com:443 example.com:443 404: the port is stripped from the request value only, never from the configured one
example.com no Host header, or a value that is not visible ASCII 404
any a path other than the route’s, compared case-sensitively 404

The rejection is built by reject_404: an empty-body 404 Not Found returned from the callback, which makes tungstenite answer with it and fail the handshake with HTTP error: 404 Not Found.

Behind a reverse proxy every WebSocket client arrives from the proxy’s address, so a server cannot tell its clients apart. A proxy names the client in a header of the upgrade request instead: nginx’s realip module passes X-Real-IP, others append to X-Forwarded-For. WsRoute::real_ip_header(name) names the header a route reads, and WsStream::real_ip_header (and TransportStream::real_ip_header) reports what an accepted upgrade’s header said. A route that names no header reads nothing.

real_ip_header parses name with HeaderName::from_bytes, so the header is matched without regard to case. A name that is not a valid header name, such as X Real IP or an empty string, fails with io::ErrorKind::InvalidInput and not a header name: "<name>", the name in Debug quoting.

WsCallback::on_request reads the header right after the path and Host check, so an upgrade refused with 404 reads nothing. RealIpHeader::read takes every line of the header, in order, as one comma-separated list:

What the request carries RealIpHeader
no line of the header Missing
entries that each parse, once trimmed, as a bare IP address, at most MAX_REAL_IP_ADDRESSES (32) of them Addresses, in the order listed: the client first, then each proxy that appended the address it heard from; an IPv4-mapped IPv6 address is given as IPv4 (to_canonical)
a line that is not visible ASCII, an entry that is not a bare address (a port, brackets, unknown, an empty entry, two addresses separated by a space), or a 33rd entry Malformed

The tests in ws_endpoint.rs pin examples: two lines 203.0.113.9, 2001:db8::7 and ::ffff:127.0.0.1 read as [203.0.113.9, 2001:db8::7, 127.0.0.1]; "", unknown, 203.0.113.9:443, [2001:db8::7], 203.0.113.9,,198.51.100.1 and 203.0.113.9 198.51.100.1 are each Malformed; a list of exactly 32 addresses reads, and 33 do not. The cap’s doc comment gives its size: a real chain of proxies is a handful long.

Reading the header trusts nothing. Anyone can send it, and the protocols crate does not know who did; the doc comments on RealIpHeader and both accessors leave the decision to a caller that knows which peers are proxies it trusts.

In the supervisor that caller is the serve loop, on an inbound whose InboundSpec::real_ip is set:

supervisor/src/topology/spec_plan/inbound.rs
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RealIpSpec {
pub header: CompactString,
pub trusted: Vec<cidr::IpCidr>,
}
impl RealIpSpec {
pub fn trusts(&self, ip: IpAddr) -> bool;
}

trusts canonicalises ip, so an IPv4-mapped address counts as its IPv4 one, and asks whether any network in trusted holds it. supervisor/src/serve.rs → real_ip_source(real_ip, header, source) then names the client the way nginx’s realip module does. The header counts only on a connection from a proxy in the trusted networks:

Connection Header Client
from an address no trusted network holds, or with no known address any the connection’s own; the header is ignored, so a client cannot name itself someone else
from a proxy in the trusted networks Addresses the rightmost listed address no trusted network holds, or the leftmost when they hold every one
from a proxy in the trusted networks Missing the proxy, logged at debug as trusted proxy <ip> sent no <header> header; serving it as the client
from a proxy in the trusted networks Malformed the proxy, logged at debug as trusted proxy <ip> sent a <header> header that lists no addresses; serving it as the client

<header> is RealIpSpec::header as the spec spells it. What the serve loop does with the client it names (the bans, the session’s source, the device limit) is in Serving in the supervisor and on Listeners and the serve loop.

Xray-compatible early data carries the first client bytes inside the upgrade request, in the Sec-WebSocket-Protocol header, so a client-first protocol saves one round trip.

Step Side Mechanism
Encode client encode_early_data_header: base64 URL-safe alphabet, no padding (b"hello" → aGVsbG8, [0xfb, 0xff] → -_8)
Size client The first min(len, ed, MAX_EARLY_DATA) bytes of the first non-empty write, so never more than 16 KiB
Normalise server Trim whitespace, map + to - and / to _, drop =: standard and URL-safe, padded or not, all decode
Decode server URL_SAFE_NO_PAD. An empty value, a value that does not decode, or one that decodes to nothing is not early data
Cap server More than MAX_EARLY_DATA decoded bytes returns Err(()), and the callback answers 413 Payload Too Large (reject_413)
Echo server Valid early data is stored in the slot and the request’s Sec-WebSocket-Protocol value is echoed verbatim in the 101 response
Deliver server WsStream::accept takes the slot and seeds pending_read, so the early data is the first thing the core reads

WsCallback::on_request runs its checks in a fixed order:

  1. WsRoute::accepts with the request path and the Host value (None when the header is missing or not visible ASCII). A mismatch returns Err(reject_404()), whatever the request’s early data.
  2. On a route that reads a client-address header, RealIpHeader::read runs and its result goes into the slot’s real_ip (see The client a trusted proxy names). Whatever the header says, the checks go on.
  3. No Sec-WebSocket-Protocol header, or a value that is not visible ASCII (to_str fails): the response goes back unchanged and the slot holds no early data.
  4. decode_early_data_header: Err(()) becomes Err(reject_413()); Ok(None) returns the response unchanged.
  5. Ok(Some(bytes)): the bytes go into the slot’s early_data, and the header value is copied into the response.

In every case but the first and fourth the upgrade succeeds.

The echo is load-bearing. tungstenite’s client handshake treats a request that carried Sec-WebSocket-Protocol and a 101 without one as a subprotocol error and fails the upgrade, so a server that consumed the early data but did not echo it would break every Etemenanki client that uses ?ed=.

On the client, WsStream::connect with a positive limit does not upgrade at all. It parks the socket in State::Deferred with limit = min(ed, MAX_EARLY_DATA) and returns. The first non-empty poll_write calls start_upgrade, which takes up to limit bytes, builds the request with them, boxes the tungstenite handshake into State::Upgrading, wakes any reader parked in read_waker, and returns Ok(take). The boxed handshake does nothing until the stream is polled again: the rest of a write_all, a woken read, a flush or a shutdown drives it through poll_open. The caller’s write_all then writes the rest as ordinary messages once the upgrade completes.

sequenceDiagram
  participant CC as client core
  participant CW as WsStream client
  participant SW as WsStream::accept
  participant SC as server core
  CC->>CW: connect with path /ws?ed=2048
  Note over CW: State Deferred, no bytes sent
  CC->>CW: write_all 2100 bytes, first poll_write
  CW->>CW: start_upgrade takes 2048, state Upgrading
  CW-->>CC: Ok(2048)
  CC->>CW: second poll_write, 52 bytes
  Note over CW: poll_open drives the boxed handshake
  CW->>SW: GET /ws with Sec-WebSocket-Protocol base64url(2048 bytes)
  SW->>SW: WsRoute::accepts path and Host
  SW->>SW: decode_early_data_header into UpgradeSlot
  SW-->>CW: 101 with Sec-WebSocket-Protocol echoed
  Note over CW: Upgrading becomes Open
  SW->>SC: WsStream with pending_read = 2048 bytes
  CW->>SW: Binary message, 52 bytes
  SC->>SC: reads 2048 bytes, then 52

A read issued before the first write returns Pending from poll_open and stores its waker; start_upgrade wakes it. A poll_shutdown in Deferred calls start_upgrade(&[]). The early-data slice goes through .filter(|b| !b.is_empty()), so that request carries no Sec-WebSocket-Protocol header, and the close still reaches the peer as a WebSocket Close frame. poll_flush in Deferred returns Ok(()) without doing anything.

stateDiagram-v2
  [*] --> Open: accept, or connect without ed
  [*] --> Deferred: connect with ed greater than 0
  Deferred --> Upgrading: first non-empty poll_write, or poll_shutdown
  Upgrading --> Open: handshake done, timers reset
  Upgrading --> Failed: handshake error
  Failed --> Failed: every call returns the stored error
  Open --> [*]

State::Failed(io::ErrorKind, String) keeps the kind and text of the upgrade error, and poll_open rebuilds an equal io::Error on every later call. A write that started the upgrade has already returned Ok, so the failure surfaces on the next read, write, flush or shutdown. An upgrade started by poll_shutdown is different: the same call goes on into poll_open and drives it, so its failure surfaces from that shutdown. Dropping the stream in Upgrading drops the boxed handshake future and the socket with it.

start_upgrade takes the socket out of Deferred before it builds the request. If WsTarget::client_request fails there (a host that does not form a valid URI, for example), that first write returns the error, the state stays Deferred without a socket, and any later write or shutdown fails with websocket upgrade already started.

The mapping between WebSocket messages and bytes is fixed:

Direction Event WsStream action
read bytes left in pending_read Handed out first (take_pending), before the closed flag, the timers or the socket are looked at
read Binary(bytes) Stored in pending_read; handed out across as many poll_read calls as the buffer sizes need. An empty Binary message leaves pending_read empty and the loop reads on, so it never looks like EOF
read Ping(payload) control = Some(Pong(payload)), replacing any frame already waiting (a queued keepalive Ping or an unsent Pong); sent by the next poll_control
read Close(_) read_closed = true: EOF
read Text, Pong, raw Frame Ignored, but they still reset both timers
read stream end, ConnectionClosed, AlreadyClosed, ResetWithoutClosingHandshake EOF
read any other tungstenite error, including a size limit Err: the I/O error itself for WsError::Io, otherwise io::Error::other
write empty buffer Ok(0), no message
write non-empty buffer Exactly one Binary message with a copy of the buffer, then touch and Ok(buf.len())
flush Drives an upgrade in flight, runs poll_control, then flushes the sink
shutdown Starts a deferred upgrade and drives it; then one Close(None) (guarded by close_sent), then flush. ConnectionClosed or AlreadyClosed during that flush counts as success. It does not call poll_control, so a waiting control frame is not handed to the sink before the Close

ws_err maps tungstenite errors: WsError::Io(e) is returned as e; ConnectionClosed and AlreadyClosed become BrokenPipe with the text websocket closed; anything else becomes io::Error::other. A write therefore fails in one of two ways once the session is closing:

  • When tungstenite reports the connection closed (ConnectionClosed, or AlreadyClosed once it has terminated), the write fails with BrokenPipe, websocket closed.
  • After a Close has been sent (by poll_shutdown) or received, but before tungstenite has terminated the connection, tungstenite 0.30 refuses the message with ProtocolError::SendAfterClosing. The write fails with io::ErrorKind::Other and the text WebSocket protocol error: Sending after closing is not allowed.

control holds at most one control frame. poll_control is called from poll_read as well as from poll_write and poll_flush. When a frame is waiting, it hands the frame to the sink once poll_ready says the sink is ready, and returns Pending while it is not. Then, with or without a frame, it polls one flush of the sink and does not wait for it; only a flush error is returned. On the write path a waiting frame must reach the sink before the payload message is queued. On the read path a sink that is not ready does not block the read: the frame waits and the read proceeds. Because every poll_read on an open session gets this far, a pending read also pushes buffered outgoing messages toward the socket.

tungstenite 0.30 also queues a Pong of its own when it reads a Ping, and a Pong handed to its sink replaces a queued Pong that has not been flushed yet. The peer therefore sees one Pong per Ping, or two when tungstenite flushed its own before WsStream sent the second; both carry the Ping’s payload, and RFC 6455 allows unsolicited Pongs.

tungstenite sends no keepalive of its own, so WsStream owns two tokio::time::Sleep timers:

Timer Constant Fires Effect
keepalive WS_KEEPALIVE_INTERVAL = 60 s 60 s after the last activity Re-armed for another 60 s; queues Ping with an empty payload if no control frame is waiting
idle WS_IDLE_TIMEOUT = 300 s 300 s after the last activity read_closed = true: the read side reports EOF, as a peer that vanished without a FIN would

touch resets both. It runs when the upgrade completes, on every incoming frame of any kind (a Pong included, which is what turns the Ping into a liveness probe), and after every successful write. The timers belong to the read side, as the module doc puts it: only poll_read polls them, after poll_open has returned the open session and with idle checked before keepalive. They therefore fire while a reader is waiting on the stream; writes reset them through touch but never poll them. The keepalive matches the HTTP/2 transport’s H2_KEEPALIVE_INTERVAL. The idle timeout does not match H2_IDLE_TIMEOUT (30 s); it matches the cores’ RELAY_IDLE_TIMEOUT (300 s) instead. The doc comment on WS_IDLE_TIMEOUT gives the reason: a WebSocket session is one tunnelled connection, not a carrier of many, so HTTP/2’s shorter deadline for a connection with no streams has no counterpart here. The triggers differ too, since WebSocket counts frames while HTTP/2 counts open streams and bytes heard.

ws_config replaces tungstenite’s defaults (64 MiB per message, 16 MiB per frame) with MAX_WS_MESSAGE_LEN = 1 MiB for both max_message_size and max_frame_size. tungstenite reassembles a fragmented message into one buffer before yielding it; with this config it refuses any message or frame larger than 1 MiB instead. The code’s reasoning: tunnelled payloads are far smaller (a VMess chunk’s length is a u16), so 1 MiB leaves generous headroom, and it matches the gRPC carrier’s MAX_GRPC_MESSAGE_LEN. The same config is passed to accept_hdr_async_with_config and client_async_with_config, so it applies to inbound and dialed sessions alike.

Both tungstenite limits apply to received messages only, and both are > checks: a message or frame of exactly 1,048,576 bytes passes. The refusal reads Space limit exceeded: Message too long: <size> > 1048576. WsStream::poll_write never splits a buffer and tungstenite sends a message as one frame, so a single write of more than 1,048,576 bytes goes out as one message that an Etemenanki peer refuses. The pipeline tests’ 200 000-byte write_all goes out as one message below that limit.

The gRPC carrier is Xray’s “gun” transport: a bidirectional-streaming gRPC call whose messages are protobuf Hunk { bytes data = 1; } or, in multi mode, MultiHunk { repeated bytes data = 1; }. There is no generated protobuf code; the one field is written and parsed by hand.

protocols/src/transports/grpc/settings.rs
const H2_INITIAL_STREAM_WINDOW_SIZE: u32 = 4 * 1024 * 1024;
const H2_INITIAL_CONNECTION_WINDOW_SIZE: u32 = 16 * 1024 * 1024;
const H2_MAX_FRAME_SIZE: u32 = 256 * 1024;
pub(crate) const MAX_GRPC_MESSAGE_LEN: usize = 1024 * 1024;
pub(crate) const H2_IDLE_TIMEOUT: Duration = Duration::from_secs(30);
pub(crate) const H2_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(60);
pub(crate) const H2_KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(20);
pub(crate) const H2_PONG_TIMEOUT: Duration = Duration::from_secs(300);
pub(crate) const DEFAULT_USER_AGENT: &str = /* desktop Chrome, below */;
#[derive(Debug)]
pub struct GrpcPaths {
tun: Arc<str>,
multi: Arc<str>,
}
impl GrpcPaths {
pub fn new(service: impl AsRef<str>) -> Self;
pub fn classify(&self, path: &str) -> Option<GrpcMode>;
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GrpcMode {
Gun,
Multi,
}
pub(crate) fn configured_client_builder() -> h2::client::Builder;
pub(crate) fn configured_server_builder() -> h2::server::Builder;
pub(crate) fn grpc_response() -> http::Response<()>;
pub(crate) fn grpc_request(
secure: bool,
authority: &str,
service: &str,
mode: GrpcMode,
user_agent: Option<&str>,
) -> std::io::Result<http::Request<()>>;
pub(crate) fn finish_stream(send_stream: &mut SendStream<Bytes>, is_server: bool);
protocols/src/transports/grpc/framing.rs
const HUNK_DATA_TAG: u8 = 0x0A;
fn put_varint(buf: &mut BytesMut, value: u64);
fn read_varint(data: &[u8]) -> io::Result<(u64, usize)>;
fn varint_len(value: u64) -> usize;
fn hunk_field_len(payload_len: usize) -> io::Result<usize>;
pub(crate) fn encode_hunk(payload: &[u8]) -> io::Result<Bytes>;
pub(crate) fn encode_multi_hunk(payloads: &[Bytes]) -> io::Result<Bytes>;
pub(crate) struct HunkDecoder {
chunks: VecDeque<Bytes>,
len: usize,
}
impl HunkDecoder {
pub(crate) fn new() -> Self;
pub(crate) fn push(&mut self, chunk: Bytes);
pub(crate) fn buffered(&self) -> usize;
pub(crate) fn next(&mut self) -> io::Result<Option<Bytes>>;
pub(crate) fn next_multi(&mut self) -> io::Result<Option<Vec<Bytes>>>;
fn copy_prefix<const N: usize>(&self) -> Option<[u8; N]>;
fn consume(&mut self, n: usize);
fn take_bytes(&mut self, n: usize) -> Bytes;
fn take_frame(&mut self) -> io::Result<Option<Bytes>>;
}
protocols/src/transports/grpc/stream.rs
pub struct GrpcStream {
send: SendStream<Bytes>,
recv: Recv,
mode: GrpcMode,
is_server: bool,
decoder: HunkDecoder,
ready: VecDeque<Bytes>,
write_pending: Option<Bytes>,
finished: bool,
_driver: Option<AbortOnDropHandle<()>>,
_guard: Option<StreamGuard>,
}
enum Recv {
Awaiting(ResponseFuture),
Body(RecvStream),
Done,
}
impl GrpcStream {
pub(crate) fn served(
send: SendStream<Bytes>,
recv: RecvStream,
mode: GrpcMode,
count: &Arc<StreamCount>,
) -> Self;
pub async fn connect<T>(
io: T,
secure: bool,
authority: &str,
service: &str,
mode: GrpcMode,
user_agent: Option<&str>,
) -> io::Result<Self>
where
T: AsyncRead + AsyncWrite + Unpin + Send + 'static;
fn build(
send: SendStream<Bytes>,
recv: Recv,
mode: GrpcMode,
is_server: bool,
driver: Option<AbortOnDropHandle<()>>,
guard: Option<StreamGuard>,
) -> Self;
fn poll_drain(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
fn decode(&mut self) -> io::Result<bool>;
}
pub(crate) struct StreamCount {
live: AtomicUsize,
changed: Notify,
}
impl StreamCount {
pub(crate) fn new() -> Arc<Self>;
pub(crate) fn is_idle(&self) -> bool;
pub(crate) async fn changed(&self);
fn guard(self: &Arc<Self>) -> StreamGuard;
}
struct StreamGuard(Arc<StreamCount>);
fn h2_err(e: h2::Error) -> io::Error;

A served GrpcStream is built with is_server = true, Recv::Body, a StreamGuard and no driver; a dialed one with is_server = false, Recv::Awaiting, a driver and no guard. h2_err unwraps an h2 I/O error into the io::Error inside it (or h2 io error if there is none) and turns every other h2 error into io::Error::other.

StreamCount is an AtomicUsize of live served streams plus a tokio::sync::Notify. guard increments live with fetch_add (AcqRel) and returns a StreamGuard; the guard’s Drop decrements it with fetch_sub (AcqRel) and calls notify_waiters. is_idle loads live with Acquire and compares it with zero, and changed awaits Notify::notified.

GrpcPaths::new builds both paths from the service name, inserted verbatim with no normalisation or escaping (an empty name gives //Tun and //TunMulti). classify compares the request path exactly.

Path GrpcMode Message type
/<service>/Tun Gun one Hunk per gRPC message
/<service>/TunMulti Multi one MultiHunk per gRPC message
anything else none stream reset with REFUSED_STREAM, logged at debug
Message Headers
Client request (grpc_request) POST, URI https://<authority>/<service>/Tun (or http://, or /TunMulti), content-type: application/grpc, te: trailers, and user-agent when one is set
Server response (grpc_response) 200, content-type: application/grpc, sent as soon as the stream is accepted, with the stream left open
Server close (finish_stream) trailers grpc-status: 0
Client close (finish_stream) an empty DATA frame with END_STREAM

serve_h2 logs a refused stream as grpc: refusing a stream from <peer> for path "<path>". The path is the peer’s to choose, so the line shows at most its first LOGGED_PATH_CHARS (64) characters: logged_path cuts it on a character boundary, never inside a multi-byte character, and the cut path is printed with Debug quoting.

grpc_request fails with io::Error::other when the formatted URI does not parse or the request does not build; finish_stream ignores the result of sending the trailers or the final frame.

DEFAULT_USER_AGENT is a desktop Chrome string, Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.7977.42 Safari/537.36. TransportKind::grpc sets it; TransportKind::user_agent(None) removes the header.

Every gRPC message on the stream is a length-prefixed message:

Offset Size Field Meaning
0 1 compressed flag Written as 0x00: uncompressed. The decoder does not read this byte
1 4 message length u32, big-endian (put_u32): the length of the protobuf message that follows
5 message length message A protobuf Hunk or MultiHunk

A Hunk message is one length-delimited field:

Size Field Meaning
1 tag 0x0A (HUNK_DATA_TAG): field number 1, wire type 2
1 to 10 length Base-128 varint (put_varint): the length of data
length data The tunnelled bytes

A MultiHunk message is zero or more of the same 0x0A / varint / data triples back to back. encode_multi_hunk skips empty payloads and computes the message length over the non-empty ones only. Both encoders size their buffer up front with 5usize.saturating_add(msg_len) and write it once.

Two encodings from the tests, byte for byte:

Call Bytes
encode_hunk(b"ok") 00 00 00 00 04 0A 02 6F 6B
encode_multi_hunk(["a", "", "bc"]) 00 00 00 00 07 0A 01 61 0A 02 62 63

A 130-byte payload needs a two-byte varint (82 01), so its message length is 0x85 (133).

GrpcStream::poll_write encodes each non-empty write as one message: one Hunk in Gun mode, a MultiHunk with a single entry in Multi mode. Encoding fails with hunk message too large (InvalidData) only when the message length overflows usize or does not fit in a u32 (hunk_field_len and the u32 conversion). The encoder does not apply MAX_GRPC_MESSAGE_LEN. A single write of N bytes makes a message of N + 1 + varint_len(N) bytes, and for any N near 1 MiB the varint takes 3 bytes. The decoder refuses a message length above 1,048,576, so, as with WebSocket, a single write of more than 1,048,572 bytes produces a message that an Etemenanki peer refuses.

HTTP/2 DATA frames do not line up with gRPC messages, so HunkDecoder keeps the received chunks in a VecDeque<Bytes> with a running length (push ignores empty chunks) and never copies until it has a whole message:

  1. take_frame peeks the 5-byte header across chunk boundaries (copy_prefix::<5>). Fewer than 5 bytes: Ok(None).
  2. It reads the length from bytes 1 to 4 and rejects anything over MAX_GRPC_MESSAGE_LEN immediately, before the body has arrived, with grpc message length exceeds the accepted maximum.
  3. With fewer than 5 + length bytes buffered it returns Ok(None) and waits.
  4. Otherwise consume(5) drops the header and take_bytes splits off the body. When the body sits in one chunk this is a zero-copy split_to; otherwise the pieces are copied into one BytesMut. take_bytes(0) returns an empty Bytes.
  5. next (gun) requires the first byte to be 0x0A, reads the varint and splits off data. An empty message or empty data is skipped and the loop moves to the next message. Bytes after the declared data in the same message are discarded.
  6. next_multi walks every field of the message, requiring each to be 0x0A, and returns the non-empty entries. It can return an empty Vec.

read_varint reads at most ten bytes. In the tenth byte, shifted by 63, only the lowest bit lands in the u64; a tenth byte with its continuation bit set is refused.

Condition Error text (io::ErrorKind::InvalidData)
declared length over 1 MiB grpc message length exceeds the accepted maximum
field tag other than 0x0A unexpected protobuf field in Hunk / unexpected protobuf field in MultiHunk
varint runs off the end truncated varint
varint that continues past its tenth byte varint overflow
fewer bytes than the varint declares hunk data shorter than declared

Two more checks are defensive. grpc frame too large guards a checked_add(5) on a length already capped at 1 MiB, which cannot overflow. hunk data too large guards the u64 to usize conversion of the varint, which always succeeds on 64-bit targets.

Constant Value Used by
H2_INITIAL_STREAM_WINDOW_SIZE 4 MiB both builders: initial_window_size
H2_INITIAL_CONNECTION_WINDOW_SIZE 16 MiB both builders: initial_connection_window_size
H2_MAX_FRAME_SIZE 256 KiB both builders: max_frame_size
MAX_GRPC_MESSAGE_LEN 1 MiB HunkDecoder::take_frame, on served and dialed streams
H2_IDLE_TIMEOUT 30 s served connections (Liveness)
H2_KEEPALIVE_INTERVAL 60 s served connections (Liveness)
H2_KEEPALIVE_TIMEOUT 20 s served connections (Liveness)
H2_PONG_TIMEOUT 300 s served connections (Liveness)
DEFAULT_USER_AGENT Chrome string TransportKind::grpc

The code comment gives the windows’ purpose: high-RTT tunnel throughput. H2_IDLE_TIMEOUT is short because, as its doc comment says, a client that pools connections loses nothing but a dial by it: it has been told to go away, and opens a fresh connection for its next stream. H2_PONG_TIMEOUT is generous because a PONG waits for every byte queued ahead of its PING to drain down a slow link; it equals RELAY_IDLE_TIMEOUT.

sequenceDiagram
  participant CC as client core
  participant CG as GrpcStream client
  participant D as driver task
  participant S as serve_h2
  participant SG as GrpcStream served
  participant SC as server core
  CG->>D: handshake, then tokio::spawn(conn)
  CG->>S: HEADERS POST /svc/Tun
  S->>S: GrpcPaths::classify gives Gun
  S-->>CG: HEADERS 200 application/grpc
  S->>SG: GrpcStream::served, guard taken
  S->>SC: sink(TransportStream::Grpc)
  CC->>CG: poll_write payload
  CG->>SG: DATA encode_hunk(payload)
  SG->>SC: HunkDecoder::next, release_capacity
  SC->>SG: poll_write reply
  SG->>CG: DATA encode_hunk(reply)
  CG->>CC: Recv Awaiting then Body, decode
  CC->>CG: poll_shutdown
  CG->>SG: empty DATA with END_STREAM
  SC->>SG: poll_shutdown
  SG->>CG: trailers grpc-status 0

The client does not wait for the response headers in connect. Recv::Awaiting holds the ResponseFuture, and the first poll_read resolves it into Recv::Body, so a client-first protocol can write immediately after connect returns. A response that fails (a reset stream, for example) fails that read through h2_err.

InboundTransport::accept for Grpc does TLS (optional) and the h2 server handshake inside the 10 s within("grpc", …) bound, over I/O that h2_io wraps in Heard<Coalesced<_>>, then calls serve_h2:

protocols/src/transports/accept.rs
async fn serve_h2<T, F>(
mut conn: Connection<T, Bytes>,
heard: ReadClock,
paths: &GrpcPaths,
peer: Option<SocketAddr>,
sink: &mut F,
) -> io::Result<()>
where
T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
F: FnMut(Accepted),

serve_h2 creates one StreamCount, one Liveness::new(conn.ping_pong(), heard) and a going_away flag, false at first. h2::server::Connection::accept both yields new streams and drives the connection’s I/O. Served streams live in other tasks, but their bytes only move while serve_h2 keeps polling conn.accept(). The loop computes idle = count.is_idle() and then runs a tokio::select! over three arms:

flowchart TB
  top["loop: idle = count.is_idle()"] --> sel{"select!"}
  sel -->|"conn.accept() gives a stream"| cls{"classify path"}
  cls -->|"None"| rst["debug log, send_reset REFUSED_STREAM"]
  cls -->|"Gun or Multi"| resp["send_response 200"]
  resp --> prog1["liveness.note_progress()"]
  prog1 --> sink["sink(GrpcStream::served)"]
  sel -->|"count.changed(), only if not idle"| prog["liveness.note_progress()"]
  sel -->|"watch(idle) gives Dead"| stop["debug log, break: drop the connection"]
  sel -->|"watch(idle) gives Idle, first time"| ga["graceful_shutdown, going_away"]
  sel -->|"watch(idle) gives Idle again"| stop
  sel -->|"conn.accept() gives None"| stop
  rst --> top
  sink --> top
  prog --> top
  ga --> top
  • note_progress runs only once a stream is classified and its response sent, that is, once it is handed on. A refused request does not restart the idle deadline: the doc comment on H2_IDLE_TIMEOUT gives the reason, that a peer that knows no service name could otherwise keep the connection by asking for one now and then. An error from conn.accept() does not call it either.
  • A stream whose path classify rejects is logged at debug and reset with REFUSED_STREAM; the connection keeps serving the others.
  • If send_response fails, the stream is dropped and the loop continues.
  • An error from conn.accept() ends serve_h2 with that error (io::Error::other), except while going away: then an I/O error ends the loop quietly, since a peer with nothing open may hang up without hearing the rest of the goodbye.
  • StreamCount tracks live served streams. Each GrpcStream::served takes a StreamGuard; when the guard drops, notify_waiters wakes the count.changed() arm while that arm is waiting. The arm is enabled only while streams are open, so the end of the last stream restarts the idle deadline too.
  • watch returns a Verdict. Dead breaks the loop after logging grpc: dropping the connection from <peer>: nothing heard for <n>s, PING unanswered for <m>s at debug, where <n> is Liveness::silence and <m> is Liveness::unanswered (0 when no PING is outstanding), both in whole seconds.
  • The first Idle tells the peer to go away instead of hanging up: conn.graceful_shutdown() sends GOAWAY, going_away is set, and liveness.note_going_away() gives the connection H2_KEEPALIVE_TIMEOUT before it is judged idle again. A stream the peer opens before it hears the GOAWAY is still served, and h2 closes the connection once none is left. A second Idle breaks the loop.
  • A conn.accept() that yields None (the connection closed), a Dead verdict and a second Idle all break the loop, and serve_h2 returns Ok(()).

When serve_h2 returns, the Connection is dropped and every stream still open on it fails on its next read or write.

Liveness supervises a served connection against three hazards, each with its own deadline:

protocols/src/transports/grpc/liveness.rs
pub(crate) fn deadline(now: Instant, after: Duration) -> Instant;
#[derive(Clone, Debug)]
pub(crate) struct ReadClock {
base: Instant,
last_ms: Arc<AtomicU64>,
}
impl ReadClock {
pub(crate) fn new() -> Self;
pub(crate) fn stamp(&self);
pub(crate) fn last(&self) -> Instant;
}
pub(crate) struct Heard<T> {
io: T,
clock: ReadClock,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Verdict {
Alive,
Idle,
Dead,
}
pub(crate) struct Liveness {
ping_pong: Option<PingPong>,
heard: ReadClock,
next_ping: Instant,
ping_sent: Option<Instant>,
idle_due: Instant,
}
impl Liveness {
pub(crate) fn new(ping_pong: Option<PingPong>, heard: ReadClock) -> Self;
pub(crate) fn note_progress(&mut self);
pub(crate) fn note_going_away(&mut self);
pub(crate) fn silence(&self) -> Duration;
pub(crate) fn unanswered(&self) -> Option<Duration>;
pub(crate) async fn watch(&mut self, idle: bool) -> Verdict;
async fn tick(&mut self, idle: bool) -> Verdict;
fn dead_at(&self, sent: Instant) -> Instant;
fn next_wake(&self, idle: bool) -> Instant;
}
async fn poll_pong(ping_pong: Option<&mut PingPong>) -> Verdict;

ReadClock records when the peer was last heard from: a base Instant and the milliseconds after it of the latest read that brought bytes, in an AtomicU64 shared by its clones. new counts as hearing from the peer at once, since a connection is handed over right after a handshake the peer had to answer. stamp stores the elapsed milliseconds with a relaxed store and last turns them back into an Instant. Heard<T> wraps the connection’s I/O (a Coalesced stream, from h2_io) and calls stamp whenever a poll_read fills any bytes; its writes pass straight through, vectored writes and is_write_vectored included. The clock is shared rather than reported, as its doc comment says: the reads happen inside h2’s polling of the connection, which the watcher never sees, and a stamp is one store.

Hazard Verdict Deadline Applies when Reset by
A peer completes the handshake and opens no stream, which would park Connection::accept forever Idle idle_due, H2_IDLE_TIMEOUT = 30 s idle is true: StreamCount is zero note_progress: a stream handed on or a stream ended
A peer vanishes without a FIN while streams are open (a mobile NAT rebind is the common case), so the idle deadline never applies Dead H2_KEEPALIVE_TIMEOUT = 20 s with nothing heard, counted from the later of the PING and the last read a PING is outstanding any byte heard from the peer pushes it back; the PONG clears it
A peer keeps sending but never reads, so its PONG never comes and every frame queued for it stays in memory Dead H2_PONG_TIMEOUT = 300 s after the PING a PING is outstanding the PONG

Any byte from the peer counts as a sign of life, not only the PONG. The doc comment gives the reason: the PING queues behind every byte already on its way down, so on a slow or congested downlink its answer can take far longer than 20 s while the peer keeps acknowledging data, and judging by the PONG alone tore such a busy, healthy connection down with every stream on it. The PONG is still owed, which is what the third deadline bounds.

new sets next_ping to 60 s and idle_due to 30 s from the moment serve_h2 starts, with tokio::time::Instant. note_progress sets idle_due to a full 30 s from now. note_going_away sets it to H2_KEEPALIVE_TIMEOUT (20 s) from now: a connection told to go away gets as long as a PONG to finish closing, not another full idle period. Neither touches next_ping, so PINGs go out every H2_KEEPALIVE_INTERVAL independent of traffic. silence is the time since heard.last(), and unanswered the age of the outstanding PING, if one is.

dead_at(sent) is the earlier of two instants: H2_KEEPALIVE_TIMEOUT after the later of sent and heard.last(), and H2_PONG_TIMEOUT after sent. Reads do not wake the watcher, so a peer heard from in the meantime has only pushed this instant later, and the tick that finds it so sleeps again.

One tick:

  1. next_wake(idle) picks the earliest deadline that applies: next_ping, dead_at(sent) while a PING is outstanding, and idle_due only when idle.
  2. A tokio::select! races sleep_until that instant against poll_pong. If poll_pong wins, ping_sent is cleared and its verdict is returned: Alive for a PONG, Dead for an error (the connection closed).
  3. After the sleep: idle and past idle_due is Idle; past dead_at(sent) is Dead.
  4. Past next_ping: next_ping is re-armed 60 s from now. When no PING is outstanding and a PingPong exists, tick sends Ping::opaque() and sets ping_sent to now in the same step. A failed send_ping is Dead at once.
  5. Otherwise Alive.

serve_h2 passes conn.ping_pong(), which h2 hands out once. With None, poll_pong pends forever, no PING is sent, and only the idle deadline applies; the grpc_liveness.rs unit tests use this.

watch loops over tick until the verdict is not Alive, rather than resolving on every tick. In tokio::select!, an arm whose pattern does not match is disabled for the rest of that call, so an arm that resolved on every tick would stop re-arming its timers the first time it found the peer alive. The loop is cancel-safe, which it must be because every other arm of serve_h2’s select! drops it: its awaits are a timer and a poll, no state changes across an await, and ping_sent is set in the same synchronous step that sends the PING, so a cancelled watch never leaves a PING unwatched.

Neither verdict is an error: serve_h2 answers Idle with GOAWAY and Dead by dropping the connection, and returns Ok(()). The doc comment explains why this supervision sits at the HTTP/2 layer: nothing below it has a timeout, and the connection outlives the handshake bounds that cover everything before it.

GrpcStream::connect opens a fresh HTTP/2 connection for every dial and one stream on it (the module doc: one connection per dial):

  1. configured_client_builder().handshake(Coalesced::new(io)) returns (SendRequest, Connection), so h2’s writes on a dialed connection are batched as on a served one (see Write batching under h2); a handshake error is mapped with h2_err.
  2. The Connection future is spawned with tokio::spawn and wrapped in AbortOnDropHandle. When it ends with an error, the task logs grpc connection ended: <error> at debug (target etemenanki_protocols::transports::grpc::stream).
  3. grpc_request builds the request; send_req.ready() waits until the connection can open a stream, and send_request(request, false) opens it with the body still open. Errors from ready and send_request go through h2_err.
  4. The SendRequest handle is dropped when connect returns; the open stream keeps the connection alive.

The driver is spawned before step 3, so if building or sending the request fails, connect returns the error, the AbortOnDropHandle is dropped, and the driver task is aborted with it. After a successful connect the handle is stored in _driver: dropping the GrpcStream drops the handle, which aborts the driver task and with it the connection. A dialed connection is never shared between streams.

The first poll_read turns the response into its body with into_body, whatever its status and headers, and the stream reads DATA frames until the body ends; the response trailers are not read.

write_pending: Option<Bytes> holds at most one encoded message:

  1. poll_write first drains the previous message with poll_drain. It returns Pending until that is fully handed to h2, which is how HTTP/2 flow control pushes back on the writer. An empty write returns Ok(0) after this drain.
  2. It encodes the new buffer, stores it in write_pending and makes one best-effort poll_drain; only an error from that drain is returned.
  3. It returns Ok(buf.len()) even if part of the message is still pending. poll_flush and the next poll_write finish it.

poll_drain loops while a message is pending: it calls reserve_capacity(pending.len()), waits on poll_capacity, and sends as many bytes as the granted capacity allows with send_data(chunk, false). An error from poll_capacity or send_data goes through h2_err. A None from poll_capacity means the stream is closed: BrokenPipe, h2 send stream closed. The branch that returns Pending on a granted capacity of zero is defensive: h2 0.4.20’s poll_capacity never grants zero, and returns Pending itself instead. poll_flush is poll_drain. poll_shutdown drains, then calls finish_stream once (guarded by finished).

protocols/src/transports/coalesce.rs
pub(crate) const HELD_MAX: usize = 16 * 1024;
pub(crate) struct Coalesced<T> {
io: T,
held: Vec<u8>,
written: usize,
}
impl<T> Coalesced<T> {
pub(crate) fn new(io: T) -> Self;
}
impl<T: AsyncWrite + Unpin> Coalesced<T> {
fn poll_send(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
fn poll_send_all(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
}
impl<T: AsyncRead + Unpin> AsyncRead for Coalesced<T> { /* passes through */ }
impl<T: AsyncWrite + Unpin> AsyncWrite for Coalesced<T> { /* … */ }

h2 writes a DATA frame of 1 KiB or more as two writes: its own buffer, topped up to 1 KiB with the start of the payload, then the rest of the payload. Straight onto TLS, each write is a record and a sendto of its own, so such a frame costs two of each. Coalesced holds what h2 writes until h2 flushes, which it does after every such frame, and sends it then as one write, and so as one record. Both ends of the carrier run h2 over one: accept.rs → h2_io puts it under every connection an inbound serves, and GrpcStream::connect under every connection an outbound dials. It knows nothing of HTTP/2 or TLS; plaintext connections get the same batching.

Call What Coalesced does
poll_write, empty buffer Ok(0); nothing is allocated or sent
poll_write When held is full (HELD_MAX bytes), first sends all of it, and pends while the stream below pends. The first write after a flush allocates held for HELD_MAX bytes with reserve_exact. Then it copies as much of the buffer as fits and returns that count
poll_flush Sends everything held, frees the buffer (held = Vec::new()), then flushes the stream below
poll_shutdown Sends everything held, frees the buffer, then shuts the stream below down
poll_read Passes straight through
is_write_vectored false

poll_send writes held[written..] until nothing is left, advancing written by each partial write, and only then clears the buffer. A stream below that takes 0 bytes fails the send with io::ErrorKind::WriteZero rather than looping. One rule comes from OpenSSL: a write that pends is retried from the same byte with no fewer bytes, because OpenSSL refuses a retried SSL_write shorter than the one that pended. That is why writes only ever add to the buffer, why nothing is taken out of it before all of it is written, and why the buffer is never reallocated: the bytes of a write that pends stay where they are.

HELD_MAX is the most plaintext one TLS record carries (RFC 8446 §5.1), and it bounds the buffer both ways:

  • a connection holds at most 16 KiB of h2’s writes; a full buffer goes out, as one record, before it takes more, so a stalled stream underneath stalls h2 instead of growing the buffer;
  • a flush frees the buffer, so an idle connection holds none.

Coalesced stays a non-vectored writer on purpose, as its module doc explains. h2 copies a DATA frame shorter than its chain threshold into its own buffer, where frames from every stream share one write, and flushes after each longer one. A vectored writer lowers that threshold from 1 KiB to 256 bytes, which would give every frame of 256 to 1023 bytes a record of its own. Heard forwards is_write_vectored, so h2 sees false on served connections too.

poll_read works in a fixed order:

  1. Hand out bytes from the front of ready if there are any.
  2. Otherwise run decode, which asks the decoder for one message (or one MultiHunk batch) and appends its payloads to ready.
  3. Otherwise pull one DATA chunk from h2 (poll_data) into the decoder, or resolve Recv::Awaiting first. None from poll_data moves to Recv::Done, which is EOF.

The decoder is fed one DATA chunk at a time, and only when ready is empty and no complete message is buffered, so nothing is pulled from h2 until the reader asks for it.

When the body ends, decode still runs before the Recv match, so complete messages already buffered are delivered first. Bytes of a trailing partial message stay in the decoder and are dropped with the stream: the reader sees a clean EOF, not an error.

decode returns window credit with flow_control().release_capacity(consumed), where consumed is the drop in HunkDecoder::buffered() across the call; it does so only in Recv::Body and ignores the result. Credit is released only for bytes the decoder consumed, so bytes of an unfinished message keep holding their credit.

Invariant Enforced by Pinned by
One non-empty write is exactly one WebSocket Binary message WsStream::poll_write sends Message::Binary(Bytes::copy_from_slice(buf)) no dedicated test; the pipeline round trips only compare the echoed bytes
One non-empty write is exactly one gRPC message GrpcStream::poll_write → encode_hunk / encode_multi_hunk encode_hunk_writes_exact_small_frame, encode_multi_hunk_writes_exact_repeated_fields (protocols/tests/unit/transports/grpc_framing.rs) pin the encoding; one_grpc_connection_carries_many_streams (protocols/tests/pipeline/transports.rs) checks that a served stream echoes a 10-byte read as exactly one Hunk
The same path string works on both sides; ?ed= never reaches the wire parse_early_data_path + normalize_path in WsRoute::new and WsTarget::new normalizes_paths, parses_outbound_early_data_path (protocols/tests/unit/transports/ws_endpoint.rs)
At most min(ed, MAX_EARLY_DATA) bytes ride the upgrade, and they are the first bytes the server core reads start_upgrade returns take; from_upgraded seeds pending_read ws_early_data_is_the_first_bytes_the_server_reads (transports.rs)
Early data over 16 KiB is refused before the upgrade decode_early_data_header returns Err(()), the callback answers 413 rejects_oversized_early_data_header, callback_rejects_oversized_early_data (ws_endpoint.rs)
Valid early data is echoed; invalid early data is ignored, not echoed WsCallback::on_request callback_captures_and_echoes_valid_early_data, callback_ignores_invalid_early_data, decodes_xray_early_data_header, encodes_xray_early_data_header (ws_endpoint.rs)
A route reads only the client-address header it names, and only a route that names one reads any WsCallback::on_request reads route.real_ip, after the path and Host check a_route_reads_its_real_ip_header_and_only_that (ws_endpoint.rs)
The header’s addresses keep their order across lines, a mapped address is IPv4, and anything but at most 32 bare addresses is Malformed RealIpHeader::read a_forwarded_list_keeps_its_order_across_lines, anything_but_addresses_is_malformed (ws_endpoint.rs)
A header counts only on a connection from a proxy in the trusted networks; elsewhere the connection’s client stands real_ip_source (supervisor/src/serve.rs) a_trusted_proxys_header_names_the_client_and_no_one_elses_does (supervisor/tests/unit/serve.rs), a_trusted_proxys_forwarded_header_names_the_websocket_client, a_forwarded_header_from_anyone_untrusted_is_ignored (supervisor/tests/guard.rs)
A client a trusted proxy names is held to the bans and the device limit serve_tcp’s sink: Guard::is_banned, Session::set_source a_forwarded_client_failing_to_authenticate_is_banned_and_others_are_not, the_device_limit_counts_the_forwarded_client (supervisor/tests/guard.rs)
A real-IP setting reaches the build only on a WebSocket transport on a TCP bind, with a trusted proxy and a valid header name validate.rs → real_ip_header a_real_ip_header_needs_a_websocket_a_trusted_proxy_and_a_name, shadowsocks_and_socks_over_websocket_read_a_real_ip_header (supervisor/tests/unit/validate.rs), a_real_ip_header_must_be_a_header_name (ws_endpoint.rs)
A wrong path or Host never upgrades WsRoute::accepts → reject_404 route_accepts_only_matching_path_and_host, host_matching_ignores_case_and_port (ws_endpoint.rs), ws_rejects_a_wrong_path_at_the_upgrade (transports.rs)
No received WebSocket message or frame over 1 MiB is accepted, on inbound and dialed sessions alike ws_config passed to both tungstenite entry points the_configured_limits_replace_tungstenite_defaults (ws_endpoint.rs) checks the config values
A declared gRPC length over 1 MiB is refused before its body is buffered HunkDecoder::take_frame checks MAX_GRPC_MESSAGE_LEN on the header decoder_rejects_a_message_longer_than_the_maximum, decoder_rejects_an_oversized_length_before_buffering_the_body, decoder_accepts_a_message_at_the_maximum (grpc_framing.rs)
DATA frame boundaries do not matter HunkDecoder chunk queue and copy_prefix decoder_waits_for_split_frame, decoder_reads_multiple_frames_from_one_chunk, decoder_reads_multi_hunk_entries (grpc_framing.rs)
Malformed hunks fail with InvalidData tag and length checks in next / next_multi decoder_rejects_unexpected_field, decoder_rejects_short_declared_payload (grpc_framing.rs)
Only /<service>/Tun and /<service>/TunMulti are served GrpcPaths::classify, REFUSED_STREAM otherwise classify_path_matches_tun_modes (protocols/tests/unit/transports/grpc_liveness.rs) pins the classification; grpc_multi_mode_over_tls_round_trip (transports.rs) serves TunMulti; a_refused_stream_leaves_the_connection_serving (protocols/tests/unit/transports/accept.rs) drives the reset for four other paths and then serves /svc/Tun on the same connection
A refused stream does not restart the idle deadline note_progress runs only after send_response a_refused_stream_does_not_restart_the_idle_deadline (accept.rs)
A logged path is at most 64 characters and never cut inside a character logged_path with LOGGED_PATH_CHARS a_logged_path_is_cut_on_a_character_boundary (accept.rs)
One served connection carries many streams serve_h2 loop, sink per stream one_grpc_connection_carries_many_streams (transports.rs)
A served connection with no streams is told to go away after H2_IDLE_TIMEOUT (30 s), and dropped if still idle H2_KEEPALIVE_TIMEOUT (20 s) later Liveness::idle_due, note_going_away; serve_h2 sends GOAWAY on the first Idle liveness_gives_up_on_a_connection_with_no_streams, liveness_restarts_the_idle_deadline_on_progress, liveness_gives_a_departing_connection_a_pong_s_time (grpc_liveness.rs), a_connection_that_opens_no_stream_is_given_up_on, an_idle_connection_is_told_to_go_away (accept.rs)
A served connection with live streams is not dropped by the idle deadline idle_due is only consulted when idle is true liveness_keeps_a_connection_carrying_streams (grpc_liveness.rs)
A peer still sending is kept while its PONG queues behind a slow downlink Heard stamps ReadClock; dead_at counts from the last read a_peer_still_sending_is_kept_while_its_pong_waits_behind_a_slow_downlink (accept.rs)
A peer that goes silent is dropped once a PING goes unheard for H2_KEEPALIVE_TIMEOUT dead_at a_peer_that_goes_silent_is_dropped_once_a_ping_goes_unheard (accept.rs)
A peer that sends but never reads is dropped once its PONG is H2_PONG_TIMEOUT late dead_at a_peer_that_sends_but_never_reads_is_dropped_once_its_pong_is_overdue (accept.rs)
An h2 DATA frame of 1 KiB or more goes out in one write, on served and dialed connections alike Coalesced under h2: h2_io, GrpcStream::connect a_tunnel_message_goes_out_in_one_write (accept.rs), a_dialed_message_goes_out_in_one_write (protocols/tests/unit/transports/grpc_stream.rs), a_frame_written_in_two_goes_out_as_one_write (protocols/tests/unit/transports/coalesce.rs)
Frames under 1 KiB from h2’s own buffer share a write Coalesced::is_write_vectored is false, and Heard forwards it short_messages_share_a_write (accept.rs), short_dialed_messages_share_a_write (grpc_stream.rs), it_is_not_a_vectored_writer (coalesce.rs)
Coalesced never holds more than HELD_MAX; a stalled stream below stalls the writer poll_write sends a full buffer before it takes more a_full_buffer_goes_out_before_more_is_taken, a_stalled_stream_stalls_the_writer_instead_of_growing_the_buffer (coalesce.rs)
A write that pended is retried from the same byte with no fewer bytes poll_send only appends and clears once everything is written a_pended_write_is_retried_with_no_fewer_bytes, a_partly_taken_write_is_resumed (coalesce.rs)
An idle connection holds no write buffer poll_flush and poll_shutdown free held a_flush_frees_the_buffer, an_empty_write_is_a_no_op (coalesce.rs)
Window credit is returned only for consumed bytes GrpcStream::decode releases held - buffered() no dedicated test
A dialed connection dies with its stream AbortOnDropHandle in _driver no dedicated test
Liveness::watch is cancel-safe ping_sent set in the same step as send_ping no dedicated test
Every gRPC stream on an inbound is a session of its own Connection::serve_tcp (multiplexed) → Shared::connector per yielded stream no dedicated test
A gRPC connection keeps the last user its streams authenticated as; a failure or a core that names no user keeps the one it has Carrier::succeeded, Report::carrier_hint a_carrier_hands_its_last_user_to_the_next_stream (supervisor/tests/unit/guard.rs)
A transport spec carries TLS material exactly when its shape layers TLS validate_inbound and outbound_transport in supervisor/src/build/validate.rs an_inbound_carries_tls_material_exactly_when_its_shape_layers_tls, an_outbound_carries_tls_settings_exactly_when_its_shape_layers_tls (supervisor/tests/unit/validate.rs)
An outbound’s WebSocket Host and gRPC authority are always set; an inbound needs neither app outbound_transport fallbacks; outbound_transport in validate.rs a_server_config_lowers_to_its_spec (app/tests/unit/lower.rs), an_outbound_needs_a_ws_host_and_a_grpc_authority, an_inbound_needs_no_ws_host_or_grpc_authority (validate.rs)
A Unix listener carries neither WebSocket nor gRPC app inbound_transport’s Unix branch; validate_inbound’s Unix rule a_unix_listen_lowers_to_a_plain_stream (app/tests/unit/lower.rs), a_unix_listener_carries_only_the_plain_tcp_shape (validate.rs)
TLS is layered under ws and grpc only when security = "tls", and an unknown security is refused rather than read as plaintext app/src/transport.rs → tls_layer ws_and_grpc_layer_tls_only_when_asked, an_unknown_security_is_rejected_on_every_network (both over ws and grpc), security_is_trimmed_before_matching (over ws) in app/tests/unit/transport.rs
WebSocket over TLS negotiates http/1.1 and gRPC over TLS negotiates h2, whichever front end wrote the spec build_transport and transport_connector pass Alpn::Http1 and Alpn::Http2 no supervisor test; ws_over_tls_with_early_data_round_trip and grpc_multi_mode_over_tls_round_trip (transports.rs) build both ends with those values
Situation What happens
Inbound TLS plus WebSocket upgrade, or TLS plus h2 handshake, exceeds TRANSPORT_HANDSHAKE_TIMEOUT accept fails with TimedOut, websocket handshake timed out or grpc handshake timed out; the supervisor logs inbound transport failed: … and drops the socket
Upgrade refused (404, 413) The server’s accept fails with HTTP error: 404 Not Found or HTTP error: 413 Payload Too Large. A client dialed without ed fails in connect with the same kind of text; a deferred client stores it in State::Failed and reports it on its next call
Deferred upgrade fails State::Failed; the first write already returned Ok(take), every later call returns the stored error. An upgrade started by poll_shutdown reports its failure from that shutdown
Building the deferred request fails The first write returns the error; later writes and shutdowns fail with websocket upgrade already started
A route is given a client-address header name that is not one WsRoute::real_ip_header fails with InvalidInput, not a header name: "<name>"; in the supervisor validation refuses the spec first, with the real-ip header "<header>" is not a header name
A trusted proxy sends no client-address header, or one that is not a list of addresses The stream is served with the proxy as its client; the supervisor logs it at debug
A trusted proxy names a banned client The supervisor’s sink returns without serving that stream; the stream is dropped
WebSocket peer closes or disappears EOF on read (Close, stream end, reset without closing handshake)
WebSocket quiet for 300 s while being read EOF on read
Write after tungstenite reports the connection closed BrokenPipe, websocket closed
Write after a Close was sent or received, before the connection is terminated io::ErrorKind::Other, WebSocket protocol error: Sending after closing is not allowed
WebSocket message or frame over 1 MiB received Err from poll_read: Space limit exceeded: Message too long: <size> > 1048576
Unknown gRPC path That stream is reset with REFUSED_STREAM and logged at debug; the connection continues, and its idle deadline is not restarted
send_response fails That stream is dropped silently; the connection continues
conn.accept() errors serve_h2 returns the error, the supervisor logs inbound transport failed: …, and the connection is dropped
Liveness judges the peer dead serve_h2 logs grpc: dropping the connection from <peer>: … at debug and returns Ok(()); the connection is dropped, open streams fail
Liveness judges the connection idle GOAWAY with NO_ERROR; a stream the peer opens before it hears it is still served, and h2 closes the connection once none is left. Still idle H2_KEEPALIVE_TIMEOUT later, the connection is dropped; an I/O error from conn.accept() meanwhile ends it quietly
A gRPC connection’s streams keep failing to authenticate With carrier_max_failures set, the supervisor cancels the socket’s session after that many failures in a row, which drops the connection
Dialed gRPC handshake, ready or send_request fails connect returns the error through h2_err; a driver already spawned is aborted
Dialed gRPC request cannot be built grpc_request fails with io::Error::other; the driver is aborted
h2 stream or connection error on a GrpcStream h2_err: an I/O error is unwrapped, anything else becomes io::Error::other
Send side closed while draining BrokenPipe, h2 send stream closed
The stream under Coalesced takes 0 bytes of a write WriteZero from the flush or the next write, an I/O error to h2
Malformed gRPC message InvalidData from the decoder, surfaced from poll_read
gRPC body ends in the middle of a message Complete messages are delivered, then a clean EOF; the partial message is dropped
Dialed GrpcStream dropped The driver task is aborted and the HTTP/2 connection closes
Dialed WsStream dropped while upgrading The boxed handshake future and its socket are dropped
Front end leaves out a required name etemenanki-app refuses the config (texts above); the supervisor refuses a spec with a gap (ws transport needs a host, grpc transport needs an authority)
TCP keepalive options rejected by the platform set_keepalive logs could not enable TCP keepalive: <error> at debug and the connection carries on

The log lines these carriers produce:

Level Target Text When
debug etemenanki_supervisor::serve inbound transport failed: <error> InboundTransport::accept returned an error
debug etemenanki_supervisor::serve trusted proxy <ip> sent no <header> header; serving it as the client A WebSocket upgrade from a trusted proxy carried no client-address header
debug etemenanki_supervisor::serve trusted proxy <ip> sent a <header> header that lists no addresses; serving it as the client The header was Malformed
debug etemenanki_protocols::transports::accept grpc: refusing a stream from <peer> for path "<path>" A served stream asked for a path other than the tunnel paths; <path> is cut to 64 characters
debug etemenanki_protocols::transports::accept grpc: dropping the connection from <peer>: nothing heard for <n>s, PING unanswered for <m>s Liveness judged the peer dead
debug etemenanki_supervisor::guard closing a gRPC connection from <source> after <n> failed streams in a row carrier_max_failures failed streams in a row
debug etemenanki_protocols::transports::grpc::stream grpc connection ended: <error> A dialed HTTP/2 connection’s driver ended with an error
debug etemenanki_protocols::transports::keepalive could not enable TCP keepalive: <error> The keepalive socket options were refused

<peer> and <source> are printed as Option values, such as Some(198.51.100.9:40000) for a peer and Some(198.51.100.9) for a source.

Cancellation follows ownership. Dropping a WsStream drops its socket. A served GrpcStream holds the send and receive handles of one HTTP/2 stream: dropping it before that stream has ended makes h2 reset that one stream, and its StreamGuard decrements the StreamCount. Dropping the future that runs serve_h2 drops the Connection, and every stream still open on it fails on its next read or write. A dialed stream owns its connection through _driver.

Constant Value Where
TRANSPORT_HANDSHAKE_TIMEOUT 10 s accept.rs: TLS plus upgrade or h2 handshake on accept
MAX_EARLY_DATA 16 KiB ws/endpoint.rs: decoded early data, and the cap on a client’s ed
MAX_WS_MESSAGE_LEN 1 MiB ws/endpoint.rs: tungstenite max_message_size and max_frame_size
MAX_REAL_IP_ADDRESSES 32 ws/endpoint.rs: addresses a client-address header may list before it is Malformed
WS_KEEPALIVE_INTERVAL 60 s ws/stream.rs: quiet period before a Ping
WS_IDLE_TIMEOUT 300 s ws/stream.rs: quiet period before EOF
MAX_GRPC_MESSAGE_LEN 1 MiB grpc/settings.rs: largest declared gRPC message
H2_INITIAL_STREAM_WINDOW_SIZE 4 MiB grpc/settings.rs
H2_INITIAL_CONNECTION_WINDOW_SIZE 16 MiB grpc/settings.rs
H2_MAX_FRAME_SIZE 256 KiB grpc/settings.rs
H2_IDLE_TIMEOUT 30 s grpc/settings.rs: served connection with no streams, before GOAWAY
H2_KEEPALIVE_INTERVAL 60 s grpc/settings.rs: PING period on a served connection
H2_KEEPALIVE_TIMEOUT 20 s grpc/settings.rs: silence after a PING before the peer is dropped; also the grace after GOAWAY
H2_PONG_TIMEOUT 300 s grpc/settings.rs: the longest a PING may go unanswered while the peer is still heard from
LOGGED_PATH_CHARS 64 accept.rs: characters of a refused path shown in its log line
HELD_MAX 16 KiB coalesce.rs: h2’s writes held under one HTTP/2 connection, one TLS record’s plaintext

The largest single write an Etemenanki peer accepts follows from the two message caps: 1,048,576 bytes on WebSocket and 1,048,572 bytes on gRPC. TCP keepalive (TCP_KEEPALIVE_IDLE 120 s, TCP_KEEPALIVE_INTERVAL 30 s, TCP_KEEPALIVE_RETRIES 3, in protocols/src/transports/keepalive.rs) sits under both carriers; see Transports: TCP and TLS. The process-wide view is on Limits.

File Tests Covers
protocols/tests/unit/transports/ws_endpoint.rs normalizes_paths, parses_outbound_early_data_path, host_matching_ignores_case_and_port, route_accepts_only_matching_path_and_host, decodes_xray_early_data_header, encodes_xray_early_data_header, rejects_oversized_early_data_header, callback_captures_and_echoes_valid_early_data, callback_ignores_invalid_early_data, callback_rejects_oversized_early_data, the_configured_limits_replace_tungstenite_defaults, a_route_reads_its_real_ip_header_and_only_that, a_forwarded_list_keeps_its_order_across_lines, anything_but_addresses_is_malformed, a_real_ip_header_must_be_a_header_name Path and ?ed= handling, Host check, early-data codec and callback, size limits; the client-address header through the callback: only the named header is read, a route naming none reads nothing, lines keep their order, 32 addresses read and 33 do not, the malformed values listed above, and two invalid header names
protocols/tests/unit/transports/grpc_framing.rs encode_hunk_writes_exact_small_frame, encode_hunk_writes_multi_byte_varint_length, encode_multi_hunk_writes_exact_repeated_fields, decoder_waits_for_split_frame, decoder_reads_multiple_frames_from_one_chunk, decoder_reads_multi_hunk_entries, decoder_rejects_unexpected_field, decoder_rejects_short_declared_payload, decoder_rejects_a_message_longer_than_the_maximum, decoder_rejects_an_oversized_length_before_buffering_the_body, decoder_accepts_a_message_at_the_maximum Exact wire bytes, reassembly, malformed input, the 1 MiB cap
protocols/tests/unit/transports/grpc_liveness.rs classify_path_matches_tun_modes, liveness_gives_up_on_a_connection_with_no_streams, liveness_keeps_a_connection_carrying_streams, liveness_restarts_the_idle_deadline_on_progress, liveness_gives_a_departing_connection_a_pong_s_time Path classification; the idle deadline on a paused clock (start_paused), with Liveness::new(None, ReadClock::new()): an idle connection is judged Idle, not Dead, and one told to go away gets at least H2_KEEPALIVE_TIMEOUT and less than H2_IDLE_TIMEOUT
protocols/tests/unit/transports/accept.rs a_connection_that_opens_no_stream_is_given_up_on, a_refused_stream_does_not_restart_the_idle_deadline, a_refused_stream_leaves_the_connection_serving, an_idle_connection_is_told_to_go_away, a_logged_path_is_cut_on_a_character_boundary, a_peer_still_sending_is_kept_while_its_pong_waits_behind_a_slow_downlink, a_peer_that_goes_silent_is_dropped_once_a_ping_goes_unheard, a_peer_that_sends_but_never_reads_is_dropped_once_its_pong_is_overdue, a_tunnel_message_goes_out_in_one_write, short_messages_share_a_write serve_h2 and Liveness wired together, over h2_io as accept builds it, over tokio::io::duplex against an h2 client or a hand-written one, on a paused clock stepped by hand. An idle connection is given up on no earlier than H2_IDLE_TIMEOUT and returns Ok; probes on a wrong path every 10 s are refused with REFUSED_STREAM and do not hold it open; /wrong/Tun, /SVC/Tun, /svc/tun and /svc/Tun/ are refused while /svc/Tun is still served; an idle connection sends GOAWAY with NO_ERROR before it closes; logged_path keeps 64 characters of an ASCII and a CJK path. The last three wrap the client’s end of the pipe: a downlink limited to 1 KiB/s with the client sending every second is kept for four PING periods; a client that stops reading and writing is dropped between H2_KEEPALIVE_INTERVAL and H2_KEEPALIVE_INTERVAL plus twice H2_KEEPALIVE_TIMEOUT; a client that sends every second but stops reading is dropped no earlier than H2_PONG_TIMEOUT. The last two record every write the server makes under h2: one 8000-byte tunnel message goes out in one write and no write is h2’s 1 KiB head alone, and eight 600-byte messages share one write
protocols/tests/unit/transports/grpc_stream.rs a_dialed_message_goes_out_in_one_write, short_dialed_messages_share_a_write The same two checks on the dialing side: GrpcStream::connect over a recorded pipe end, against a bare h2 server
protocols/tests/unit/transports/coalesce.rs a_frame_written_in_two_goes_out_as_one_write, a_full_buffer_goes_out_before_more_is_taken, a_stalled_stream_stalls_the_writer_instead_of_growing_the_buffer, a_pended_write_is_retried_with_no_fewer_bytes, a_partly_taken_write_is_resumed, shutdown_sends_what_is_held_first, a_flush_frees_the_buffer, an_empty_write_is_a_no_op, a_stream_that_takes_nothing_is_an_error, it_is_not_a_vectored_writer, bytes_cross_a_pipe_both_ways Coalesced over a hand-written sink that records writes, flushes and shutdowns, and can stall, cap each write or take nothing: h2’s two writes for one frame reach it as one at the flush; HELD_MAX + 9 bytes go out as HELD_MAX and then 9; a stalled sink keeps the buffer at HELD_MAX without reallocating and wakes the writer; every retry of a pended write starts with the bytes that pended; a partly taken write is resumed; a shutdown sends what is held first; a flush frees the buffer; a sink that takes nothing gives WriteZero; and bytes cross a real tokio::io::duplex pipe both ways
protocols/tests/pipeline/transports.rs ws_round_trip, ws_over_tls_with_early_data_round_trip, ws_early_data_is_the_first_bytes_the_server_reads, ws_rejects_a_wrong_path_at_the_upgrade, grpc_round_trip, grpc_multi_mode_over_tls_round_trip, one_grpc_connection_carries_many_streams, transport_connector_refuses_udp The four WebSocket and gRPC _round_trip tests echo hello and 200 000 bytes through InboundTransport and TransportConnector, then expect a clean EOF. The early-data test writes 19 bytes with ?ed=16 and checks that the first write returns 16. The wrong-path test expects 404 in the dial error. The many-streams test opens three streams on one raw h2 client connection. The TCP and TLS tests in the same file are on the TCP and TLS page
app/tests/unit/lower.rs a_server_config_lowers_to_its_spec, a_unix_listen_lowers_to_a_plain_stream The WebSocket and gRPC inbound shapes, PEM bytes read into ServerTlsSpec, the outbound Host and SNI fallback to tls.server_name; a Unix listener’s plain Tcp shape with no TLS
app/tests/unit/transport.rs ws_and_grpc_layer_tls_only_when_asked, an_unknown_security_is_rejected_on_every_network, security_is_trimmed_before_matching security decides TLS under ws and grpc; unknown values are refused on both; a padded " tls " layers TLS under ws. The rest of the file is on the TCP and TLS page
supervisor/tests/unit/validate.rs an_inbound_carries_tls_material_exactly_when_its_shape_layers_tls, an_inbound_needs_no_ws_host_or_grpc_authority, an_outbound_carries_tls_settings_exactly_when_its_shape_layers_tls, an_outbound_needs_a_ws_host_and_a_grpc_authority, a_unix_listener_carries_only_the_plain_tcp_shape, a_real_ip_header_needs_a_websocket_a_trusted_proxy_and_a_name, shadowsocks_and_socks_over_websocket_read_a_real_ip_header, shadowsocks_runs_over_a_transport, socks_relays_udp_over_plain_tcp_only The spec rules for Ws and Grpc shapes, including a Ws shape refused on a Unix bind; a real-IP setting accepted on a Ws HTTP, Shadowsocks or SOCKS inbound and refused on Tcp and Grpc shapes, with no trusted network, and with the name X Real IP; Shadowsocks over the carriers; SOCKS over a carrier only with udp off
supervisor/tests/unit/serve.rs a_trusted_proxys_header_names_the_client_and_no_one_elses_does real_ip_source with 127.0.0.0/8 and 10.0.0.0/8 trusted: one listed address, the rightmost untrusted address of three, the leftmost when all are trusted, Missing and Malformed keeping the proxy, an IPv4-mapped proxy address trusted as IPv4, and a header from an untrusted source or from no source ignored
supervisor/tests/unit/guard.rs a_carrier_is_closed_after_failed_streams_in_a_row, a_carrier_hands_its_last_user_to_the_next_stream A carrier’s failure run, cleared by a success in between; its last user: none at first, set by a success that names one, kept by a failure and by a success that names none, replaced by a later one, and never set on a Report without a carrier
supervisor/tests/guard.rs a_grpc_connection_whose_streams_keep_failing_is_closed, a_trusted_proxys_forwarded_header_names_the_websocket_client, a_forwarded_header_from_anyone_untrusted_is_ignored, the_device_limit_counts_the_forwarded_client, a_forwarded_client_failing_to_authenticate_is_banned_and_others_are_not A VLESS-over-gRPC inbound with carrier_max_failures 3: three streams with an unknown UUID on one raw h2 connection, and the server closes the connection. A VLESS-over-WebSocket inbound reading X-Forwarded-For through a real upgrade: the sessions are tracked under the clients the header names, with the proxy itself for a missing or malformed header; a header from a connection outside the trusted networks is ignored; a device limit of 1 counts the forwarded addresses; and a forwarded address that fails three times is banned, while another forwarded address and the proxy itself are still served
app/tests/integration/e2e_xray.rs app_client_ws_xray_server_plain, app_server_ws_xray_client_plain, app_client_grpc_xray_server_plain, app_server_grpc_xray_client_plain, app_client_ws_xray_server_tls, app_client_grpc_xray_server_tls, app_server_ws_xray_client_tls, app_server_grpc_xray_client_tls VLESS over WebSocket (WS_PATH = /vlessws) and gRPC (GRPC_SERVICE = GunService) against a real Xray binary, both directions
app/tests/integration/e2e_xray_vmess.rs app_server_vmess_grpc_xray_client_tls, app_client_vmess_ws_xray_server_early_data_plain, app_server_vmess_ws_xray_client_early_data_plain gRPC with TLS and WebSocket early data (/vmess?ed=2048 on both ends) against Xray
app/tests/integration/e2e_xray_mux.rs vless_mux_over_ws_tls mux.cool composed over WebSocket with TLS, on MUX_WS_PATH = /muxws
app/tests/integration/e2e_xray_wrapped.rs app_server_shadowsocks_over_grpc, app_client_shadowsocks_over_grpc, app_server_shadowsocks_over_ws_tls, app_client_shadowsocks_over_ws_tls, app_server_shadowsocks_2022_over_grpc_tls, app_client_shadowsocks_2022_over_grpc_tls Shadowsocks and Shadowsocks 2022 inside gRPC and WebSocket, against the pinned Xray in both directions
katana tests/integration/xray_interop.rs vmess_ws_plain, vmess_grpc_plain, vless_ws_tls, vless_grpc_tls, vless_ws_tls_mux The real katana binary serving a node from a fake panel, with Xray as the client; each test checks the echoed bytes and that the panel received traffic for the user

protocols/tests/unit/transports/support.rs is mounted as transports::test_support in test builds; it provides Recorded, a pipe end that keeps every write it takes, and writes_carrying, which counts the writes that carry part of a message. app/tests/support/mod.rs provides the shared pieces of the app’s interop tests: the WS_PATH and GRPC_SERVICE constants, spawn_app (the real etemenanki-app binary), spawn_xray, and XRAY_BIN, which builds Xray once per test process, running go build -o <run directory>/xray ./main in the Xray-core checkout and then renaming the binary to $CARGO_TARGET_TMPDIR/xray, or keeping the run’s own copy when the rename fails. The run directory is the test process’s own, under $CARGO_TARGET_TMPDIR/runs/. When go is missing it prints SKIP: `go` not available; skipping xray interop test, and when the build fails SKIP: failed to build xray-core; the tests then return early. katana’s interop tests skip the same way, and also print SKIP: <path> not found; skipping xray interop test when the Xray-core checkout is missing.

No test drives WS_KEEPALIVE_INTERVAL or WS_IDLE_TIMEOUT. a_connection_that_opens_no_stream_is_given_up_on passes the real conn.ping_pong() and its client answers PINGs, so the answered-PING path of Liveness runs there, and its waited >= H2_IDLE_TIMEOUT assertion would catch a responsive peer judged dead early. A PONG that never arrives is covered by the silent-peer and never-reads tests above; no test covers a failed send_ping, and a change there needs a paused-clock test in the style of grpc_liveness.rs. See Testing for how the suites are run.