Design principles
Source files: 109 · checked against Etemenanki 46c12e4 · katana v6.1.0
Etemenanki/concepts/src/lib.rsEtemenanki/concepts/src/core.rsEtemenanki/concepts/src/runtime.rsEtemenanki/concepts/src/buffer.rsEtemenanki/concepts/src/wake.rsEtemenanki/concepts/src/client.rsEtemenanki/concepts/tests/runtime.rsEtemenanki/concepts/tests/client.rsEtemenanki/environment/src/lib.rsEtemenanki/reality/Cargo.tomlEtemenanki/reality/src/lib.rsEtemenanki/reality/tests/unit/tls13/messages.rsEtemenanki/protocols/Cargo.tomlEtemenanki/protocols/src/lib.rsEtemenanki/protocols/src/error.rsEtemenanki/protocols/src/helpers/parse.rsEtemenanki/protocols/src/core/mod.rsEtemenanki/protocols/src/core/harness.rsEtemenanki/protocols/src/sniff/mod.rsEtemenanki/protocols/src/vmess/core.rsEtemenanki/protocols/src/vmess/accounts.rsEtemenanki/protocols/src/ss_2022/core.rsEtemenanki/protocols/src/ss_2022/crypto.rsEtemenanki/protocols/src/ss_legacy/core.rsEtemenanki/protocols/src/trojan/core.rsEtemenanki/protocols/src/vless/core.rsEtemenanki/protocols/src/http/core.rsEtemenanki/protocols/src/anytls/core.rsEtemenanki/protocols/src/anytls/client/mod.rsEtemenanki/protocols/src/sss/core.rsEtemenanki/protocols/src/transports/accept.rsEtemenanki/protocols/src/transports/connect.rsEtemenanki/protocols/src/transports/stream.rsEtemenanki/protocols/src/transports/camouflage.rsEtemenanki/protocols/src/transports/reality.rsEtemenanki/protocols/src/tun/udp.rsEtemenanki/protocols/src/tun/config.rsEtemenanki/protocols/src/tun/inbound.rsEtemenanki/protocols/src/mux/demux.rsEtemenanki/protocols/src/wireguard/device.rsEtemenanki/protocols/src/transports/grpc/stream.rsEtemenanki/protocols/src/hysteria/connection.rsEtemenanki/protocols/src/hysteria/server/config.rsEtemenanki/protocols/src/hysteria/server/inbound.rsEtemenanki/protocols/src/hysteria/server/datagrams.rsEtemenanki/protocols/tests/unit/core/mod.rsEtemenanki/protocols/tests/unit/trojan/core.rsEtemenanki/protocols/tests/unit/vmess/core.rsEtemenanki/protocols/tests/unit/vmess/protocol.rsEtemenanki/protocols/tests/unit/ss_2022/core.rsEtemenanki/protocols/tests/unit/mux/demux.rsEtemenanki/protocols/tests/unit/wireguard/device.rsEtemenanki/protocols/tests/pipeline/wireguard.rsEtemenanki/protocols/tests/unit/mux/frame.rsEtemenanki/protocols/tests/unit/hysteria/protocol.rsEtemenanki/protocols/tests/unit/hysteria/server/datagrams.rsEtemenanki/protocols/tests/unit/transports/grpc_liveness.rsEtemenanki/supervisor/Cargo.tomlEtemenanki/supervisor/src/supervisor.rsEtemenanki/supervisor/src/serve.rsEtemenanki/supervisor/src/system/blocking.rsEtemenanki/supervisor/src/policy.rsEtemenanki/supervisor/src/connector.rsEtemenanki/supervisor/src/topology/spec_plan/mod.rsEtemenanki/supervisor/src/topology/spec_plan/inbound.rsEtemenanki/supervisor/src/topology/spec_plan/outbound.rsEtemenanki/supervisor/src/topology/spec_plan/transport.rsEtemenanki/supervisor/src/topology/spec_plan/plan.rsEtemenanki/supervisor/src/topology/plane.rsEtemenanki/supervisor/src/topology/outbound/udp_fanout.rsEtemenanki/supervisor/src/build/validate.rsEtemenanki/supervisor/src/entity/session.rsEtemenanki/supervisor/src/entity/usage.rsEtemenanki/supervisor/src/track/mod.rsEtemenanki/supervisor/src/track/metered.rsEtemenanki/supervisor/src/track/pace.rsEtemenanki/supervisor/tests/hot_swap.rsEtemenanki/supervisor/tests/handoff.rsEtemenanki/supervisor/tests/tracking.rsEtemenanki/supervisor/tests/unit/plan.rsEtemenanki/supervisor/tests/unit/track.rsEtemenanki/supervisor/tests/unit/validate.rsEtemenanki/supervisor/tests/unit/session.rsEtemenanki/supervisor/tests/unit/plane.rsEtemenanki/supervisor/tests/unit/serve.rsEtemenanki/subscribe/src/proxy_servers.rsEtemenanki/app/src/config.rsEtemenanki/app/src/lower.rsEtemenanki/app/src/transport.rsEtemenanki/app/src/instance.rsEtemenanki/app/src/main.rsEtemenanki/app/tests/unit/config.rsEtemenanki/app/tests/unit/transport.rsEtemenanki/app/tests/unit/lower.rsEtemenanki/app/tests/integration/e2e_reload.rsEtemenanki/app/tests/integration/e2e_hysteria.rsEtemenanki/app/tests/integration/e2e_hysteria_inbound.rskatana/src/runtime.rskatana/src/manager/node.rskatana/src/blocking.rskatana/src/lower/mod.rskatana/src/lower/inbound.rskatana/src/config.rskatana/src/api/helium.rskatana/src/api/newv2board.rskatana/tests/unit/runtime.rskatana/tests/unit/e2e.rskatana/tests/unit/manager/node.rskatana/tests/unit/lower/spec.rs
This page collects the rules the code base is built on. Each rule comes with the reason for it, the type or check that enforces it, and the tests that pin it. The last section lists the review rules that maintainers apply to every change, stated as design rules.
Read it before changing a protocol core, the per-connection runtime, the supervisor’s apply path, a front end’s lowering, or metering and speed limits. Most of these rules are carried by the shape of the types rather than by convention. A change that seems to need a way around one of them usually belongs in a different layer.
At a glance
Section titled “At a glance”| Principle | Enforced by | Pinned by |
|---|---|---|
| Protocol cores are sans-I/O | ProxyCoreDecode::handle takes an Event and an Effects sink and nothing else; clocks are constructor arguments |
core_is_driven_without_any_io, codec_is_driven_without_any_io, every CoreHarness test |
| One task per connection | ProxyServerRuntime owns the transport, the core and every outbound; ProxyClientRuntime is an AsyncRead + AsyncWrite |
server_runtime_relays_through_a_client_runtime_in_one_task, stalled_outbound_holds_uplink_but_not_other_downlink |
| Capped buffers, explicit caps | three buffers per connection, capped at BUF_SIZE and grown only as bytes pass through them; semaphores and table-size checks with try_acquire |
frame_larger_than_the_buffer_is_an_error, staging_grows_to_n_and_no_further, unknown_or_excess_sessions_are_declined_with_end |
| Errors are events | RuntimeError has no outbound variant; outbound failures arrive as Event::ConnectFailed, OutboundError and SendFailed |
connect_failure_reaches_the_core_as_an_event, a_refused_datagram_send_keeps_the_key_alive |
| Desired state is typed and comparable | Spec holds typed values and key or PEM bytes and derives PartialEq; secrets are Secret<T> |
a_spec_never_prints_a_credential, the supervisor/tests/unit/plan.rs reuse tests |
| One owner per rule | a front end lowers its own format; supervisor/src/build/validate.rs owns every rule about what a spec means |
supervisor/tests/unit/validate.rs |
| Fail-closed configuration | #[serde(deny_unknown_fields)] on every config struct; behaviour-selecting strings matched against explicit lists; transport rules checked once for every protocol that takes a transport |
a_mistyped_key_is_rejected_rather_than_ignored, an_unknown_security_is_rejected_on_every_network, reality_is_vless_only |
| Prepare, then commit | Actor::apply: a pure plan, a fallible prepare with no visible effect, an infallible commit; check is prepare without binding |
a_refused_spec_changes_nothing, katana a_reload_with_a_node_that_does_not_build_changes_nothing |
| Live changes keep connections; policies decide what ends | sessions under the root token, listeners keyed by BindSpec, the plane behind ArcSwap, DrainPolicy and UserRemovalPolicy |
an_established_connection_survives_an_apply_that_keeps_its_inbound, a_changed_outbound_keeps_its_old_flows_unless_drained_with_close |
| Metering and speed limits inside the same task | Metered wraps each outbound; Pacer charges bytes after they move |
a_limited_users_flow_moves_at_its_limit, a_users_flows_share_one_limit |
| Observers never slow the data plane | per-flow atomic counters; a sampler off the data path; a bounded broadcast that lags; a usage sink on its own task | a_slow_usage_sink_does_not_stall_the_data_plane |
| Work that grows with the users runs off the runtime | off_runtime and drop_off_runtime on the blocking pool, in the supervisor and in katana |
changing_a_large_user_set_leaves_the_runtime_worker_free, katana lowering_leaves_the_runtime_worker_free |
| Deterministic time in tests | deadlines are events; the runtime and the pacer read the tokio clock | deadline_is_armed_against_the_tokio_clock, a_raised_or_removed_limit_is_felt_within_a_second |
| Panic-free parsing | crate-level #![deny(clippy::…)] in etemenanki-protocols, etemenanki-environment and etemenanki-reality; helpers::parse::{take, take_array, need_more} |
varint_above_62_bits_is_refused_not_panicked, udp_truncated_in_the_header_is_refused_and_never_panics, every_truncation_and_mutation_is_handled_without_panicking |
| Dependencies point down; public enums grow by addition | etemenanki-reality depends on no other etemenanki crate and reaches protocols only through the reality feature, behind wrapper types; the spec, transport and subscribe enums are #[non_exhaustive] |
no test: the compiler holds every downstream match to a wildcard arm |
Protocol cores are sans-I/O
Section titled “Protocol cores are sans-I/O”A protocol’s server side is a state machine from bytes and events to bytes and effects. It does not own a socket or a timer, and it never sees a task Context: handle is a plain function of the core’s state, one event and an effects sink.
Why. A proxy protocol is mostly parsing, cryptography and bookkeeping. With no I/O inside, a unit test calls the core with a hand-built byte slice and checks exactly what it asked for. The same core then runs unchanged over TCP, a Unix socket, a WebSocket, an HTTP/2 stream, a QUIC stream, a REALITY stream or the decoded side of sss’s transform chains. Every scheduling decision (what to read, when to stop reading, when to give up) lives in one place, the runtime, instead of being repeated in every protocol module.
The contract
Section titled “The contract”concepts/src/core.rs → ProxyCoreDecode is the whole interface between a server protocol and the rest of the system:
pub trait ProxyCoreDecode { type Key: Copy + Ord + Send + Sync + 'static; type Target; type Error; type TransportAddr: Clone + Send + Sync + 'static;
const STAGING_RESERVE: usize; const MAX_DATAGRAM: usize = 4096;
fn handle( &mut self, event: Event<'_, Self>, effects: &mut Effects<'_, Self>, ) -> Result<usize, Self::Error>;
fn held(&self) -> &[u8] { … }}A core receives one Event per call and returns how many leading bytes of it the core consumed. It answers by pushing Effects into the sink and by staging reply bytes toward the transport:
| Kind | Variants |
|---|---|
| Events from the transport | Transport, TransportDatagram, TransportSendFailed, TransportEof |
| Events from an outbound | Outbound, Datagram, SendFailed, OutboundEof, Connected, ConnectFailed, OutboundError |
| Events from the timer | Deadline |
| Effects that move bytes | Forward, SendTo (a range of the event’s slice); ForwardHeld, SendToHeld (a range of the core’s held buffer) |
| Effects on outbounds | Open, Shutdown, Close |
| Effects on the connection | ShutdownTransport, SetDeadline(Option<Duration>), Finish |
The client side (ProxyCoreEncodeHandshake, ProxyCoreEncode, ProxyCoreEncodeDatagram) follows the same rule: a codec seals plaintext into a Staging area and opens wire frames in place, with no I/O.
Hidden inputs are constructor arguments
Section titled “Hidden inputs are constructor arguments”The core module names the three inputs that would otherwise make a core non-deterministic: “Randomness, wall-clock time and shared account state are constructor arguments of the concrete core, never something the runtime injects”. The two cores that check timestamps take the clock as a plain function pointer:
impl<T> VMessCore<T> { pub fn new( validator: Arc<AccountValidator<T>>, now: fn() -> i64, sniff: bool, source: Option<IpAddr>, ) -> Self
pub fn with_hint(self, hint: Option<UserHint>) -> Self}impl<T> Ss2022Core<T> { pub fn new( config: Arc<Ss2022ServerConfig<T>>, validator: Option<Arc<Validator<T>>>, sniff: bool, source: Option<IpAddr>, now: fn() -> u64, ) -> Self
pub fn with_system_clock( config: Arc<Ss2022ServerConfig<T>>, validator: Option<Arc<Validator<T>>>, sniff: bool, source: Option<IpAddr>, ) -> Self}supervisor/src/serve.rs → serve_connection passes the real clock (vmess::aead::now_unix, or Ss2022Core::with_system_clock). A test passes a constant: eih_selects_the_user_and_a_stale_timestamp_is_refused in protocols/tests/unit/ss_2022/core.rs builds a core with the clock || 1_000 and checks that the request is refused as stale.
Shared account state arrives the same way, and it may keep time of its own. The VMess AccountValidator passed to VMessCore::new expires its replay window, and stamps the match times that order its hot tier, against std::time::Instant, so the injected now decides the timestamp check but not how long an auth ID counts as seen. A hint is an input of the same kind: VMessCore::with_hint names a user to try first, and the supervisor passes the user a gRPC connection’s last authenticated stream matched. It changes only which key the validator tries first, never whether an auth ID is admitted.
One deadline, armed by effect
Section titled “One deadline, armed by effect”Timeouts follow the same rule. A core does not measure its own timeouts: it arms the runtime’s single timer with Effect::SetDeadline and reacts to Event::Deadline. The contract in concepts/src/core.rs asks a protocol with several timeouts to keep its own ordered map of expiries, arm the earliest and re-arm on every Deadline, and to take the current time from “a clock passed to the constructor, never from Instant::now() inside handle, so tests can drive it”.
protocols/src/core/mod.rs → Timing is the shared helper for the common case. The connection’s Phase decides what the one deadline means:
stateDiagram-v2 [*] --> Handshake Handshake --> Sniff: request parsed, IP destination, sniffing on Handshake --> Relay: request parsed Sniff --> Relay: domain found, limit reached or deadline Relay --> Closing: one side closed Relay --> Closing: idle deadline, Finish pushed Closing --> [*]
| Phase | Deadline armed | Constant | Value |
|---|---|---|---|
Handshake |
once, on the first byte event (Timing::touch) |
HANDSHAKE_TIMEOUT |
10 s |
Sniff |
on entering the phase (Timing::enter) |
SNIFF_TIMEOUT (protocols/src/sniff/mod.rs) |
300 ms |
Relay, Closing |
again on every byte event, so it measures idleness, not lifetime | RELAY_IDLE_TIMEOUT |
300 s |
When the idle deadline passes, Timing::expired pushes Effect::Finish itself and returns Expired::Idle. For Handshake and Sniff it only reports which deadline passed, and the core decides.
Testing a core with CoreHarness
Section titled “Testing a core with CoreHarness”protocols/src/core/harness.rs → CoreHarness stands in for the runtime. It owns an EffectList and a WriteBuffer<HARNESS_STAGING> (HARNESS_STAGING = 64 KiB), and does no I/O:
pub struct CoreHarness<C: ProxyCoreDecode> { pub core: C, // effects, staging and the datagram packet list are private}
impl<C: ProxyCoreDecode> CoreHarness<C> { pub fn new(core: C) -> Self pub fn over_datagrams(core: C) -> Self pub fn event(&mut self, event: Event<'_, C>) -> Result<(usize, Vec<Effect<C>>), C::Error> pub fn transport(&mut self, data: &mut [u8]) -> Result<(usize, Vec<Effect<C>>), C::Error> pub fn feed(&mut self, data: &mut [u8]) -> Result<(usize, Vec<Effect<C>>), C::Error> pub fn outbound( &mut self, key: C::Key, data: &mut [u8], ) -> Result<(usize, Vec<Effect<C>>), C::Error> pub fn staged(&mut self) -> Vec<u8> pub fn staged_packets(&mut self) -> Vec<(Vec<u8>, C::TransportAddr)> pub fn held(&self, range: std::ops::Range<usize>) -> Vec<u8>}feed behaves like the runtime: it offers the unconsumed tail again while the core makes progress, and rebases Forward and SendTo ranges onto the caller’s slice. A timeout test needs no clock, because the deadline is only an event:
#[test]fn handshake_deadline_fails_the_connection() { let mut h = core(false); let mut partial = vec![0u8; 10]; h.transport(&mut partial).unwrap(); let err = h.event(Event::Deadline).unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::TimedOut); let _ = Duration::ZERO;}The sans-I/O shape also makes the subtle parts of the contract testable. The core documentation says “Never decrypt what you do not consume”: a core that decrypts a length header in place must remember that it did, because the same bytes come back on the next call. a_chunk_split_across_reads_decodes_its_header_once in protocols/tests/unit/vmess/core.rs cuts a VMess request ten bytes short, feeds the rest, and checks that the payload still comes out intact.
| Test | File | What it pins |
|---|---|---|
core_is_driven_without_any_io |
concepts/tests/runtime.rs |
A toy mux core is driven with a bare EffectList and WriteBuffer; a split frame stays unconsumed. |
codec_is_driven_without_any_io |
concepts/tests/client.rs |
The client codec contract works the same way. |
timing_arms_handshake_once_then_idle_per_byte_event |
protocols/tests/unit/core/mod.rs |
Timing arms the handshake deadline once, then the idle deadline on every byte event. |
a_chunk_split_across_reads_decodes_its_header_once |
protocols/tests/unit/vmess/core.rs |
The “never decrypt twice” rule. |
eih_selects_the_user_and_a_stale_timestamp_is_refused |
protocols/tests/unit/ss_2022/core.rs |
The injected clock decides the timestamp check. |
handshake_deadline_fails_the_connection |
protocols/tests/unit/trojan/core.rs |
A deadline delivered by hand fails a half-finished handshake with TimedOut. |
One task per connection
Section titled “One task per connection”One proxied connection is exactly one future: concepts/src/runtime.rs → ProxyServerRuntime. It owns the client’s transport, the core, the connector and every outbound the core opens, and it moves every byte itself. There is no task per direction and no channel between the halves.
pub struct ProxyServerRuntime<const BUF_SIZE: usize, Core, Trans, Conn, Mode = ProxyRunsQuiet>where Core: ProxyCoreDecode, Conn: Connector<Core::Target>,{ … }
impl<const BUF_SIZE: usize, Core, T, Conn> ProxyServerRuntime<BUF_SIZE, Core, StreamTransport<T>, Conn, ProxyRunsQuiet>where Core: ProxyCoreDecode, T: AsyncRead + AsyncWrite + Unpin, Conn: Connector<Core::Target>,{ pub fn new(transport: T, core: Core, connector: Conn) -> Self}With the default ProxyRunsQuiet marker the runtime is a Future whose output is Result<Traffic, RuntimeError<Core::Error>>. showing_progress() turns it into a Stream of Traffic deltas (the ProxyShowsProgress marker); the supervisor’s drive uses that mode to watch the handshake and to count each session’s wire bytes as they move. over_datagrams builds the same runtime over a DatagramLink transport instead of a byte stream.
An upstream proxy does not break the rule. concepts/src/client.rs → ProxyClientRuntime implements AsyncRead + AsyncWrite on its plaintext side and owns the wire side, so the server runtime polls it like any other outbound stream. Its module documentation: the server core “forwards plaintext into it with poll_write, reads plaintext back with poll_read, and nothing in between is a task or a channel”.
flowchart LR
client["client wire"]
subgraph task["one task: ProxyServerRuntime"]
up["up: ReadBuffer"]
core["ProxyCoreDecode"]
staging["staging: WriteBuffer"]
scratch["scratch buffer"]
out1["outbound stream"]
out2["ProxyClientRuntime"]
end
dest["destination"]
upstream["upstream proxy"]
client --> up --> core
core -- "Forward" --> out1 --> dest
core -- "Forward" --> out2 --> upstream
out1 -- "read" --> scratch --> core
core -- "stage" --> staging --> client
Why. With a task per direction and channels between them, each channel is a queue that someone has to bound, each task is a lifetime that someone has to end, and each error has to be carried across a channel to whoever decides what to do about it. With one task:
- Backpressure follows from the structure. The runtime reads from a side only when there is room for the result. When a destination stops accepting writes, the forward waits, and the transport is not read.
- Cancellation is by drop. Dropping the future drops the transport, every outbound and every buffer. Nothing is left running that would need to be found and stopped.
- Ordering is total. Effects apply in the order the core pushed them, so a core can reason about “open, then forward, then close” without races.
How backpressure works
Section titled “How backpressure works”The # Backpressure section of concepts/src/runtime.rs states the rules the scheduler follows:
- Effects apply strictly in order, and a forward that cannot complete holds everything behind it. While a forward of transport bytes waits, the transport is not read; downlink from other outbounds keeps flowing.
- A stream outbound is read only while staging has
STAGING_RESERVE + 1bytes free. A datagram outbound is read only while staging hasSTAGING_RESERVEplus the datagram limit free. A client that stops reading stops the downlink at the outbound sockets, and a packet is never read into less room than it may need. - A held-range effect (
ForwardHeld,SendToHeld) pins the core’s held buffer. No byte event is delivered until it has been applied.
Only outbounds whose waker fired are polled. concepts/src/wake.rs → ReadyQueue and KeyWaker record which key became ready, so a connection with many outbounds does not poll all of them on every wake-up. In the Future mode, poll performs at most WORK_BUDGET (64) units of work, then wakes itself and returns Pending, so a connection whose sockets are always ready cannot monopolise a worker thread.
Cancellation by drop
Section titled “Cancellation by drop”The supervisor ends connections by dropping their futures. supervisor/src/serve.rs → Shared::spawn_until runs every connection on the supervisor’s TaskTracker, ended by a token:
fn spawn_until<F>(&self, token: CancellationToken, fut: F)where F: Future<Output = ()> + Send + 'static;
fn until_cancelled<F>(token: CancellationToken, fut: F) -> impl Future<Output = Option<()>>where F: Future<Output = ()>;It spawns until_cancelled(token, fut), tokio-util’s with_cancellation_token_owned, which drops the future as soon as the token is cancelled. It is a combinator rather than an async block over a select!, which would keep two copies of the future and make the task twice its size. The token is the connection’s session token, a child of the supervisor’s root token rather than of the listener that accepted the connection. Cancelling it (a removal policy, Supervisor::close, the removal of the inbound, or shutdown) drops the connection future along with everything it owns, and stopping a listener cancels nothing it accepted. Supervisor::shutdown waits for the tracker, so it returns only after every task under it is gone.
Two client-side carriers have a driver task of their own. A gRPC client stream (protocols/src/transports/grpc/stream.rs → GrpcStream::connect) sits on an HTTP/2 connection whose connection future has to be polled apart from the stream. A Hysteria 2 client connection (protocols/src/hysteria/connection.rs) is shared by every circuit routed to it and runs its HTTP/3 driver, plus a datagram pump when the server said it relays UDP. The flows on top still run one task each. Both files hold these tasks in an AbortOnDropHandle, so dropping the owner also stops the driver. The AnyTLS client (protocols/src/anytls/client/mod.rs) has no driver: each pooled session carries one stream at a time, and that stream owns the session’s connection while it lives, so there is no shared writer and no per-stream queue. Its one task is a reaper that holds only a weak reference to the pool, so it ends with the connector.
| Test | File | What it pins |
|---|---|---|
stalled_outbound_holds_uplink_but_not_other_downlink |
concepts/tests/runtime.rs |
A stalled forward stops the uplink; another key’s downlink still reaches the client. |
datagram_outbound_is_never_truncated_by_staging_backpressure |
concepts/tests/runtime.rs |
A datagram is read only into enough room. |
server_runtime_relays_through_a_client_runtime_in_one_task |
concepts/tests/client.rs |
A server runtime relays through a client runtime without a second task. |
backpressure_from_the_wire_reaches_the_writer |
concepts/tests/client.rs |
A slow upstream makes the plaintext writer wait. |
a_stopped_listener_opens_no_session, cancelling_the_root_cancels_every_session |
supervisor/tests/unit/session.rs |
Session tokens are children of the root, and a stopped listener registers nothing. |
until_cancelled_ends_a_pending_future_and_drops_it, until_cancelled_never_starts_a_future_under_a_cancelled_token, a_spawned_connection_is_no_bigger_than_its_future |
supervisor/tests/unit/serve.rs |
A cancelled token drops the connection’s future, and the spawned task holds one copy of it. |
Metering and speed limits inside the same task
Section titled “Metering and speed limits inside the same task”The supervisor keeps the one-task model for accounting and speed limits. AppConnector::connect hands the runtime each stream outbound wrapped by supervisor/src/track/metered.rs → Metered (a UDP sub-link gets MeteredDatagram). Every read and write on the wrapper first checks the flow’s kill flag, then waits on the user’s pacer, then moves the bytes and adds them to the flow’s counters:
pub(crate) struct Pacer { … }
impl Pacer { pub(crate) fn set_rate(&self, rate: Option<NonZeroU64>); pub(crate) fn charge(&self, n: usize); pub(crate) fn poll_ready( &self, cx: &mut Context<'_>, pause: &mut Option<Pin<Box<Sleep>>>, ) -> Poll<()>;}A speed limit is therefore ordinary backpressure: poll_ready returns Pending until the user’s bucket is out of debt, the wrapper returns Pending, and the runtime stops reading the other side. There is no relay loop to count in and no extra task per user.
The rules are in the module documentation of pace.rs:
- One bucket per user, shared by every flow the user has open, in both directions. The rate is bytes per second with a one-second burst; an unlimited pacer costs one atomic load.
- Charged in full, after the move. “A transfer is charged in full after it moves, even when that is more than the bucket holds: the balance goes negative, and none of the user’s flows moves again until the refill has paid that debt back.” The limit is a property of bytes, not of how they were chunked.
- A bounded sleep. A paced flow sleeps until the debt is paid, clamped between
MIN_WAIT(1 ms), “so a sliver of debt does not spin the timer”, andMAX_WAIT(1 s), “so a raised or removed limit is felt within it”. - Published with the spec. At commit and at each user edit,
Actor::publish_limitspublishes the limitsuser_limitsworked out on the blocking pool during staging, taking the smallest limit when several user sets name the same user. It hands the tracker only the speed limits that changed (Tracker::change_speed_limits), and gives the session registry every user’s device limit (Sessions::set_device_limits).
A kill uses the same path: once a flow’s kill flag is set, the wrapper’s next poll fails with ConnectionAborted, and the runtime delivers Event::OutboundError for that key to the core.
| Test | File | What it pins |
|---|---|---|
a_limited_users_flow_moves_at_its_limit |
supervisor/tests/unit/track.rs |
On a paused clock, a limited flow moves at its rate. |
a_users_flows_share_one_limit |
supervisor/tests/unit/track.rs |
Two flows of one user share one bucket. |
a_raised_or_removed_limit_is_felt_within_a_second |
supervisor/tests/unit/track.rs |
MAX_WAIT bounds how long a flow sleeps on an old rate. |
killing_a_paced_flow_fails_its_pending_write |
supervisor/tests/unit/track.rs |
A flow parked on its user’s debt is woken by a kill. |
a_users_speed_limit_paces_their_traffic |
katana tests/unit/e2e.rs |
A panel user’s limit reaches the supervisor and paces the real node. |
Capped buffers and explicit caps
Section titled “Capped buffers and explicit caps”Every per-connection resource has a size or a count that is fixed in the code and visible in review.
Buffers grow to a cap and no further
Section titled “Buffers grow to a cap and no further”A ProxyServerRuntime has three buffers, each capped at BUF_SIZE bytes: up: ReadBuffer<BUF_SIZE> for transport reads, staging: WriteBuffer<BUF_SIZE> toward the transport, and scratch for outbound reads. concepts/src/buffer.rs states the rule: each buffer “is capped at N bytes, and backpressure comes from it being full at that size”. None is allocated at the cap up front:
upstarts at 2 KiB (INITIAL, orNif smaller). When reading has used up its free tail,make_roommoves the unparsed bytes to the front and doubles the storage, up toN;grow_tomakes room for a whole datagram before a datagram read.stagingholds nothing until the first stage;Staging::reservegrows it, never pastN, and its room is still counted againstN.scratchis anOption<Box<[u8; BUF_SIZE]>>, allocated whole at the first outbound read.
“So a peer pays for a buffer with its own bytes”: a client that sends a few bytes and stops, such as one that fails to authenticate, holds only the initial read buffer, and a connection moving data reaches the cap within its first few reads. The runtime’s documentation puts it as “a connection that never gets past its handshake holds only a small read buffer”. Beyond the buffers, the connection allocates one small Arc per outbound opened (the outbound’s waker).
The consequences are enforced:
- The runtime constructor asserts
BUF_SIZE > Core::STAGING_RESERVE(“BUF_SIZE must exceed the core’s STAGING_RESERVE or nothing is ever read”). - A frame larger than
BUF_SIZEis an error. Below the cap the read buffer grows; once the unparsed region fills allBUF_SIZEbytes (ReadBuffer::is_saturated) and the core still wants more, the runtime fails the connection withRuntimeError::FrameTooLarge. - Each core declares its cap as an associated
BUF_SIZE, and the supervisor instantiates the runtime with it, for exampledrive::<{ TrojanCore::<Principal>::BUF_SIZE }, _, _>.SssCoredeclares two,TCP_BUF_SIZEandUDP_BUF_SIZE, and the supervisor picks one by the command in the stream’s header.
| Core | BUF_SIZE |
Reason given in the source |
|---|---|---|
PassthroughCore |
8 KiB | Not stated in the source. The core relays verbatim; the TUN inbound uses it for TCP flows. |
TunUdpCore |
8 KiB | A datagram plus the runtime’s reserve. |
Hy2StreamCore |
8 KiB | A request with the longest address and padding. |
TrojanCore |
16 KiB | A UDP packet frame: the header plus at most 8 KiB. |
VlessCore |
16 KiB | A UDP frame of at most MAX_DATAGRAM bytes behind its length. |
Hy2UdpCore |
16 KiB | A reassembled packet plus its fragments’ headers. |
AnyTlsCore |
16 KiB | A Settings frame and a UDP packet frame fit with room to spare; every other frame is streamed. |
SssCore, TCP stream |
TCP_BUF_SIZE = 16 KiB |
sss streams carry no frames of their own. |
ShadowsocksCore |
20 KiB | One chunk of MAX_PAYLOAD plus its overhead, with room to spare. |
VMessCore |
32 KiB | Not stated in the source. |
Ss2022Core |
MAX_RECORD_LEN = 65,569 bytes |
The largest frame a client may send: a 65,535-byte payload plus a 2-byte length and two 16-byte tags. |
HttpCore |
MAX_HEAD = 64 KiB |
A whole HTTP request head. |
SssCore, UDP stream |
UDP_BUF_SIZE = 66 KiB |
A whole datagram record of U = 65,535 bytes. |
Counts are capped with permits
Section titled “Counts are capped with permits”A cap is a semaphore or a table-size check. Most are applied with try_acquire_owned or a length check: when the cap is reached, the new item is refused at once instead of waiting in a queue that would itself need a bound, and an accept loop that refuses at once keeps accepting instead of letting the kernel’s listen backlog absorb the overload.
| Cap | Where | Value | Over the cap |
|---|---|---|---|
MAX_LIVE_CONNECTIONS_PER_INBOUND |
supervisor/src/serve.rs |
4,194,304 per stream inbound, its TCP listener and handoff socket together, for every front end | The accepted socket is dropped. The owned permit travels with the socket into every stream it carries. |
MAX_SESSIONS |
protocols/src/mux/demux.rs |
256 per mux carrier | The new sub-flow is answered with End; the carrier survives. |
MAX_STREAMS |
protocols/src/anytls/core.rs |
256 per AnyTLS session | The SYN is answered with a FIN; the session survives. |
DEFAULT_MAX_CONNECTIONS |
protocols/src/hysteria/server/config.rs |
262,144 per listener (max_connections) |
The incoming QUIC connection is refused. |
DEFAULT_MAX_CIRCUITS |
protocols/src/hysteria/server/config.rs |
4,194,304 per listener (max_circuits) |
A new proxy stream is reset with H3_REQUEST_REJECTED; a new UDP association is dropped. |
MAX_SESSIONS |
protocols/src/hysteria/server/datagrams.rs |
256 per QUIC connection | A packet that would open another UDP association is dropped. |
MAX_UDP_SESSIONS |
protocols/src/hysteria/connection.rs |
256 per Hysteria 2 client connection | Opening another UDP session fails with WouldBlock. |
MAX_SUBS |
supervisor/src/topology/outbound/udp_fanout.rs |
64 sub-links (one per routed outbound version) per UDP association | The sub-link least recently sent to is closed first. |
DEFAULT_MAX_FLOWS |
protocols/src/tun/config.rs |
65,536 per device (max_flows) |
The new flow is dropped. |
The live-connection cap is a guardrail, not a quota. The comment on MAX_LIVE_CONNECTIONS_PER_INBOUND explains the sizing: a busy inbound legitimately carries hundreds of thousands of connections, many of them idle, so the cap “must sit far above normal traffic and still leave room under the process fd limit for the outbound socket each session may open”. The Hysteria 2 inbound’s two configurable caps must be at least 1: validation refuses max_connections = 0 and max_circuits = 0 with max_connections and max_circuits must be at least 1 (supervisor/src/build/validate.rs).
| Test | File | What it pins |
|---|---|---|
frame_larger_than_the_buffer_is_an_error |
concepts/tests/runtime.rs |
A 500-byte frame into a 128-byte runtime ends with FrameTooLarge. |
a_frame_past_the_first_read_buffer_is_relayed_whole_both_ways, a_frame_past_the_grown_buffer_is_still_an_error |
concepts/tests/runtime.rs |
A frame larger than the initial read buffer grows it; one larger than the cap still fails. |
read_buffer_starts_small_and_doubles_up_to_n, write_buffer_holds_nothing_until_a_stage, staging_grows_to_n_and_no_further |
concepts/src/buffer.rs |
The buffers start small or empty and never pass N. |
unknown_or_excess_sessions_are_declined_with_end |
protocols/tests/unit/mux/demux.rs |
The mux session cap declines, it does not tear down. |
the_circuit_limit_refuses_new_sessions |
protocols/tests/unit/hysteria/server/datagrams.rs |
A UDP association over the circuit limit is refused. |
stream_permits_are_released_when_a_circuit_ends |
app/tests/integration/e2e_hysteria.rs |
The Hysteria 2 client’s stream permits come back when a circuit ends, so 20 circuits in a row pass a limit of 4. Builds the upstream Hysteria server with go and returns early when it cannot. |
hysteria2_serves_at_least_one_connection_and_one_circuit |
supervisor/tests/unit/validate.rs |
max_connections and max_circuits must be at least 1. |
Errors are events
Section titled “Errors are events”A connection has one client and possibly many outbounds. If an outbound’s failure were a runtime error, one dead destination would end every sub-flow on a mux carrier, and the core could never answer the client with an HTTP 502 or a mux End. So the runtime reports outbound failures to the core as events, and the core decides.
concepts/src/runtime.rs → RuntimeError has no variant for an outbound. Its documentation: “Outbound failures are not here: they reach the core as events and it decides.”
pub enum RuntimeError<E> { Transport(io::Error), Core(E), UnknownKey, DuplicateKey, RangeOutOfBounds, BadConsume, FrameTooLarge, WrongLinkKind, StagedWithoutPeer,}Transport is the client’s side failing, Core is the protocol refusing the client, and FrameTooLarge is a frame that does not fit the read buffer. The other variants are a core breaking its contract, for example forwarding a range outside the event’s slice (RangeOutOfBounds) or staging bytes toward a datagram transport without a peer (StagedWithoutPeer).
| Failure | Arrives as | Key afterwards |
|---|---|---|
The dial for Effect::Open fails |
Event::ConnectFailed { key, error } |
Gone |
An outbound read or write fails, or its flow is killed (directly, or by a drain with Close of its outbound version) |
Event::OutboundError { key, error } |
Gone |
| A datagram outbound refuses one packet | Event::SendFailed { key, to, error } |
Still live |
| A datagram transport refuses one packet to a peer | Event::TransportSendFailed { to, error } |
Not applicable; the transport keeps serving other peers |
sequenceDiagram participant C as client participant R as ProxyServerRuntime participant K as HttpCore participant D as connector C->>R: CONNECT request R->>K: Event::Transport K->>R: Effect::Open R->>D: connect(target) D-->>R: io::Error R->>K: Event::ConnectFailed K->>R: stage RESP_502, ShutdownTransport, Finish R->>C: HTTP 502, then close
The client side makes this precise for upstream proxies. The connect future of ProxyClientConnector resolves only after the dial, the codec’s handshake and a flush of the handshake bytes (poll_connected). A server core’s Event::Connected therefore means the upstream flow is really open, and an upstream that refuses the handshake becomes ConnectFailed, not a relay that dies on its first byte.
Inside etemenanki-protocols, parsers classify failures as protocols/src/error.rs → ProtocolError and convert them to io::Error with a fixed kind:
ProtocolError variant |
io::ErrorKind |
|---|---|
Truncated |
UnexpectedEof |
Unauthenticated |
PermissionDenied |
Malformed, Overflow, Unsupported |
InvalidData |
Crypto, Other |
Other |
Io(e) |
the kind of e |
need_more relies on this mapping: it turns UnexpectedEof into Ok(None) (“wait for more bytes”) and keeps every other error.
| Test | File |
|---|---|
connect_failure_reaches_the_core_as_an_event |
concepts/tests/runtime.rs |
a_refused_datagram_send_keeps_the_key_alive |
concepts/tests/runtime.rs |
a_refused_transport_packet_is_reported_not_fatal |
concepts/tests/runtime.rs |
upstream_dial_failure_is_connect_failed_not_connected |
concepts/tests/client.rs |
refused_upstream_handshake_is_connect_failed_not_connected |
concepts/tests/client.rs |
Desired state is typed and comparable
Section titled “Desired state is typed and comparable”A front end does not configure the supervisor piece by piece. It hands over one value, a Spec (supervisor/src/topology/spec_plan/mod.rs), that describes everything that should run: listeners, upstreams, balancers, the route table, name resolution, the user sets, and the default policies. The module documentation states the rule: “Every field is typed: a spec holds a Destination, a Uuid, a method enum, decoded key bytes or PEM bytes, never the string they were parsed from.”
Why. Because every field is typed and Spec derives PartialEq, two specs compare with ==, “which is what lets a later plan(running, desired) tell a resource to keep from one to rebuild, without asking where either spec came from.” The same apply serves a TOML reload, a panel update and a mobile app’s reload, and an unchanged resource is kept whichever front end sent the spec.
- The front end reads the files. Nothing in a spec reads a file except the route spec’s geo data paths. The front end that lowers its own format reads certificates and keys and passes their bytes, so a spec is the whole input to an apply.
- Values are decoded once, by one set of rules. REALITY’s private key, shortIds and client versions arrive in Xray’s string formats. A front end decodes them into the bytes the spec holds with the decoders protocols wraps from etemenanki-reality (
transports::reality::decode_private_key,decode_public_key,decode_short_id,decode_client_version), so etemenanki-app and katana share one copy of the rules, and a bad value fails before a spec exists rather than at apply: when etemenanki-app lowers its config, and when katana’s newV2board client reads a UniProxy answer (src/api/newv2board.rs→reality). A helium answer carries the key and shortId in helium-node-api’s node config, whose own types check them as the answer is read, and katana’s lowering decodes the shortId withdecode_short_id. No error repeats a key or a shortId. - Secrets stay out of logs. A password, a pre-shared key or a private key is a
Secret<T>: it “compares and hashes as its contents, so a changed secret is a changed spec, butDebugprints neither it nor its length”.Secret::exposeis the one way to read it, for the code that has to put it on the wire. - Types cannot carry every rule. Which fields go together and which tags exist are checked when the spec is applied, and a spec that breaks a rule is refused whole.
| Test | File | What it pins |
|---|---|---|
a_spec_never_prints_a_credential |
app/tests/unit/lower.rs |
The Debug form of a lowered spec contains none of its credentials. |
a_route_change_alone_rebuilds_only_the_route_table |
supervisor/tests/unit/plan.rs |
An unchanged DNS setup and unchanged outbounds are reused. |
One owner per rule
Section titled “One owner per rule”Each rule about a configuration has exactly one place that enforces it.
- A front end refuses what its own format gets wrong, and lowers everything else faithfully: a TOML typo, an unknown protocol name, a stream block on a protocol that cannot carry one (etemenanki-app,
app/src/config.rsandapp/src/lower.rs); a panel answer that does not describe a node katana can serve (katana’s panel clients,src/api/newv2board.rsandsrc/api/helium.rs, which read every answer into helium-node-api’s node config); half of thereal_ip_headerandreal_ip_frompair, or ahandoff_dirtoo long for the node’s socket in it and ahandoff_groupthat is not in/etc/group(katana,src/lower/); a helium node config that sets a key its panel describes, such asnode_typeor a[node.hysteria]key other thancongestion(katana,src/api/helium.rs→refuse_local_protocol). supervisor/src/build/validate.rsowns every rule about what a spec means, for every front end: tags that must exist or be unique, a protocol served on the wrong kind of bind, a Hysteria 2 limit of 0, a TUN MTU below the IP stack’s floor, a real-IP header anywhere but on a WebSocket transport on a TCP listener, or with no trusted proxy, a handoff socket anywhere but beside a stream inbound’s TCP listener, or at a path a Unix socket cannot be bound at, REALITY under any protocol but VLESS, the Vision flow anywhere but over REALITY, AnyTLS over anything but TLS.plancallsvalidatefirst, so an apply, katana’s reload check and etemenanki-app’s--testall refuse the same specs with the sameApplyError.
The transport rules show the shape of this. InboundProtocolSpec::transport() (supervisor/src/topology/spec_plan/inbound.rs) is the one list of protocols that take a transport, and validation runs the transport rules once for every protocol it names: plain TCP on a Unix listener, TLS material exactly with a shape that layers TLS, REALITY settings exactly with the REALITY shape, and that shape under VLESS alone. A protocol added to the list meets every one of them, REALITY’s refusal included, without a line of its own; the real-IP rule and katana’s WebSocket check read the same list.
Why. A rule enforced twice drifts: one copy gets fixed and the other does not, and the two front ends start to disagree about what a valid configuration is. A rule enforced in the supervisor also holds for a front end that has not been written yet.
For example, a route to an outbound tag that does not exist is not something the TOML schema can see. The supervisor refuses it as ApplyError::UnknownReference, and etemenanki-app reports route references unknown outbound direkt.
Fail-closed configuration
Section titled “Fail-closed configuration”A configuration mistake stops the program with an error. It never falls back to a default that means something else. The comment on InboundConfig::listen in app/src/config.rs names the failure this prevents: a listen key that fails to deserialise “silently falling back to 0.0.0.0 and putting a proxy that was meant to be local on the network”.
Unknown keys are errors
Section titled “Unknown keys are errors”All 43 structs that app/src/config.rs deserialises carry #[serde(deny_unknown_fields)]: the top-level Config, every section, and every per-protocol settings struct, down to the Hysteria 2 bandwidth and quic blocks. (The file’s one other struct, Sources, holds the bytes a config was built from and is never deserialised.) Per-protocol settings stay an opaque toml::Value until the lowering knows the protocol; app/src/lower.rs then deserialises them into a struct that also denies unknown fields, and reports a mistake as inbound <tag>: invalid settings: …. The subscribe file’s structs and the REST API’s request bodies carry the same attribute, and so does every struct that katana’s src/config.rs deserialises.
A missing listen binds 127.0.0.1, not every interface (app/src/lower.rs → resolve_listen). The comment gives the reasoning: deny_unknown_fields catches the typo, “and the loopback default catches whatever it does not: a server that wants every interface says so.”
Unknown values are errors
Section titled “Unknown values are errors”Strings that select behaviour are matched against an explicit list, and anything else is an error. app/src/transport.rs shows the pattern:
pub fn tls_layer(network: &str, security: Option<&str>, ctx: &str) -> io::Result<bool>pub fn resolve_stream(stream: &StreamConfig, ctx: &str) -> io::Result<StreamShape>pub fn reject_stream_settings(stream: &StreamConfig, proto: &str, ctx: &str) -> io::Result<()>tls_layer validates security against the network instead of comparing it to "tls" with plaintext as the fallback. resolve_stream takes security = "reality" before tls_layer sees it, as a shape of its own that only network = "tcp" carries, so REALITY is never mistaken for an unknown value or for TLS. Its comment explains why this matters for a proxy in particular: when a plaintext transport is built by mistake, the only symptom is a failed handshake after the credential has already crossed the network in the clear. reject_stream_settings covers the related case of a [stream] block on a protocol that never reads it, which would otherwise be discarded without a word.
Each of these was checked with etemenanki-app --test:
| Mistake | Error |
|---|---|
lisen = "0.0.0.0" |
configuration invalid: TOML parse error at line 4, column 1, naming the unknown field |
protocol = "sock" |
inbound in: unknown protocol "sock" |
security = "tsl" |
inbound in: unknown stream security "tsl" (expected "tls" or "none") |
network = "tcp" with security = "tls" |
inbound in: security = "tls" is not valid with network = "tcp"; use network = "tls" for TLS over plain TCP (…) |
network = "ws" on a Hysteria 2 inbound |
inbound in: protocol hysteria2 does not support stream network "ws" |
network = "ws" on a SOCKS inbound that keeps udp on |
inbound in: socks serves udp associate over plain tcp only; turn udp off to wrap it in a transport |
security = "reality" on a Trojan inbound |
inbound in: reality is for vless only |
flow = "xtls-rprx-vision" on a VLESS inbound over network = "tls" |
inbound in: vless vision (xtls-rprx-vision) rides only over reality |
udpp = 1 in SOCKS settings |
inbound in: invalid settings: unknown field `udpp`, expected one of `auth`, `accounts`, `udp`, `udp_bind` |
network = "tpc" in a route rule |
invalid rule network "tpc" (expected "tcp" or "udp") |
domain_regex = ["("] |
invalid domain regex "(": regex parse error: … |
port = ["2000-1000"] |
invalid port spec: "2000-1000" has a lower bound above its upper bound |
cidr = ["10.0.0.0/33"] |
invalid cidr "10.0.0.0/33": … |
outbound = "direkt" in a route rule |
route references unknown outbound direkt |
--test runs app/src/instance.rs → check: it reads the config and subscribe files, lowers them into a spec exactly as a start does, and runs etemenanki_supervisor::check, which plans and prepares that spec on a fresh supervisor without binding anything. So it refuses exactly what a start would refuse.
| Test | File |
|---|---|
a_mistyped_key_is_rejected_rather_than_ignored |
app/tests/unit/config.rs |
an_unknown_security_is_rejected_on_every_network |
app/tests/unit/transport.rs |
tcp_with_tls_is_rejected_and_names_the_fix |
app/tests/unit/transport.rs |
a_transport_the_protocol_cannot_honour_is_rejected |
app/tests/unit/transport.rs |
reality_is_refused_on_any_network_but_tcp |
app/tests/unit/transport.rs |
every_protocol_meets_the_same_transport_rules, reality_is_vless_only, a_reality_outbound_is_vless_only, socks_relays_udp_over_plain_tcp_only |
supervisor/tests/unit/validate.rs |
Prepare, then commit
Section titled “Prepare, then commit”A new spec is validated, and everything it needs is fully constructed, before anything that serves traffic changes. The module documentation of supervisor/src/supervisor.rs states the split: “Prepare does everything that can fail — building outbounds, handlers and user tables, compiling routes, binding listeners — and has no visible effect: dropping what it built undoes it. Commit cannot fail.”
flowchart TB
spec["Spec from the front end"] --> plan["plan(running, desired): validate, then list steps"]
plan -- "refused" --> keep["ApplyError; nothing changed"]
plan --> disrupt{"a Disrupt step without allow_disruptive?"}
disrupt -- "yes" --> keep
disrupt -- "no" --> prepare["prepare: build, compile, bind, pair"]
prepare -- "error" --> drop["drop what was built"] --> keep
prepare --> commit["commit: publish the plane, start and swap listeners, store user tables, stop what is gone, hand old outbounds and removed users to their policies"]
Actor::apply runs the three stages in order:
plan(supervisor/src/topology/spec_plan/plan.rs) is pure: it validates the spec and compares it with the running state, and returns the steps (Bind,Build,Reuse,PublishPlane,SwapHandler,Disrupt,StopAccepting,CloseSessions,Drain). It opens no socket and starts no task.- The disruption gate. A
Disruptstep marks a change that ends live connections, such as a Hysteria 2 obfuscation change. WithoutApplyOptions::allow_disruptivethe spec is refused withApplyError::Disruptive. etemenanki-app refuses a TUN change, and a restart applies it. preparebuilds everything that can fail and binds every new listener beside the old ones.committhen publishes it.
Planning and staging the users run on the blocking pool rather than on the actor’s runtime worker (see Work that grows with the users runs off the runtime), so commit is left with pointer swaps.
The actor runs applies and user edits one at a time, so no lock is held across an .await. supervisor/src/supervisor.rs → check, which etemenanki-app’s --test and katana’s reload check call, is the same plan and prepare without binding.
Why. A reload that tears the running configuration down and only then finds that the new one cannot start leaves a proxy half up or down. With the split, a refused spec is a no-op, and a committed one can no longer fail half-way.
Each front end applies the rule to its own reload:
- etemenanki-app (
app/src/instance.rs→Core::reload_with) reads the config and subscribe files, lowers them, and callsSupervisor::apply. A spec that does not lower or is refused is logged asreload: <error>; keeping the running config; a disruptive change is refused withreload refused, keeping the running config: inbound <tag>: <reason>, which would end its live connections; restart to apply it. Either way the running spec stays as it was. - katana (
src/runtime.rs→apply_reload) checks every node the reload adds or changes against what it would run, withlower::test_specandetemenanki_supervisor::check, before it touches any running node. If one fails, it logsreload: node <id>: <error>; keeping current configand applies nothing. Each node’s panel sync applies throughNodeManager::reconcilewithallow_disruptive: true, and a refused apply changes nothing on that node.
| Test | File | What it pins |
|---|---|---|
a_refused_spec_changes_nothing |
supervisor/tests/hot_swap.rs |
A bind failure on one new inbound releases another bound in the same prepare; the plane, users and listeners are as before. |
a_hysteria2_obfuscation_change_needs_allow_disruptive |
supervisor/tests/hot_swap.rs |
A disruptive change is refused by default. |
a_refused_apply_keeps_a_running_handoff_socket_at_its_path |
supervisor/tests/handoff.rs |
A refused apply that would have bound a handoff socket afresh at its path leaves the running socket there: a Unix or handoff socket is bound under a staging name and moved over its path only at commit. |
a_reload_keeps_the_inbound_serving_on_its_udp_port |
app/tests/integration/e2e_hysteria_inbound.rs |
A reload that changes a Hysteria 2 inbound’s settings leaves it serving on the same port. |
a_reload_with_a_node_that_does_not_build_changes_nothing |
katana tests/unit/runtime.rs |
A reload with one node that does not build applies none of its edits. |
Live changes keep connections; policies decide what ends
Section titled “Live changes keep connections; policies decide what ends”An apply that changes one thing touches only what depends on it, and what happens to a live connection is decided by a named policy, not by the mechanics of the swap.
- Sessions outlive listeners. A connection runs under its session’s token, a child of the root token. Stopping or moving a listener stops accepting and ends nothing it accepted.
- Listeners are keyed by
BindSpec, one per bind. An inbound’s handoff socket is a bind of its own beside its TCP listener, and both serve the inbound’s one handler. Both count against the inbound’s one set of admission caps. A bind unchanged across an apply keeps its socket, whichever inbound holds it; a protocol or settings change swaps the handler that new connections are served with, and adding, moving or removing a handoff socket leaves the TCP listener and every connection be. - The plane is read-copy-update. Routes and outbounds are published together as one
Planebehind anArcSwap. A connector loads it once per connection, per mux sub-flow and per UDP packet, so a route change reaches the next of each and never moves an open stream. An apply does not close such a stream either; a client that switched a node callsSupervisor::close_reroutedafterwards, which closes the live flows the new routing sends to another outbound and leaves the rest (see Closing what a route change moved). - Outbounds are versioned. An unchanged outbound is reused by
Arc. A changed one is built as a newOutboundIdversion, and the old version is handed to itsDrainPolicy:Keepby default, because “a TCP flow cannot migrate to the successor mid-stream, so closing it would only turn a config change into dropped connections” (supervisor/src/policy.rs). A WireGuard outbound is the exception: its flows are always closed, whatever the policy, because they run on the old version’s device, which they do not keep alive and which could not run beside a successor on the same key and peer. A drain that closes flows kills them through the tracker, and a flow still dialing when the drain comes is killed when it lands. - Removed users are revoked. A user removed from a set, or whose credentials changed, is handed to the inbound’s
UserRemovalPolicy:Closeby default, because “revoking access is meant to take effect”.
| Test | File | What it pins |
|---|---|---|
an_established_connection_survives_an_apply_that_keeps_its_inbound |
supervisor/tests/hot_swap.rs |
An apply that adds an outbound and a rule leaves a live relay running. |
a_protocol_change_on_the_same_port_keeps_the_socket_and_old_connections |
supervisor/tests/hot_swap.rs |
SOCKS to HTTP on one port keeps the socket and the old relay. |
adding_or_removing_a_handoff_socket_keeps_the_tcp_listener, a_handoff_socket_passed_to_another_inbound_is_kept |
supervisor/tests/unit/plan.rs |
Each bind is planned on its own: a handoff socket is bound or stopped alone, and a listener belongs to its bind, not its inbound. |
a_reload_adds_moves_and_removes_a_handoff_socket_and_keeps_the_tcp_listener |
supervisor/tests/handoff.rs |
The same end to end: every connection, the handed-over ones included, lives through each change. |
a_route_change_reaches_the_next_udp_packet_but_not_an_established_tcp_flow |
supervisor/tests/hot_swap.rs |
The plane’s read-copy-update. |
close_rerouted_closes_only_the_flows_a_route_change_moves |
supervisor/tests/hot_swap.rs |
An apply alone closes nothing; close_rerouted then closes the flow the new default route moved and leaves the one whose rule still names its outbound. |
a_changed_outbound_keeps_its_old_flows_unless_drained_with_close |
supervisor/tests/hot_swap.rs |
DrainPolicy::Keep by default, Close on request. |
a_changed_outbound_drained_with_close_after_closes_its_flows_after_the_grace, a_drain_with_close_ends_a_udp_sub_link_but_not_its_association |
supervisor/tests/hot_swap.rs |
CloseAfter waits out its grace; a drain ends a UDP sub-link and leaves its association. |
a_flow_dialing_through_a_drain_is_closed_when_it_lands, closing_a_targets_flows_leaves_other_versions_running |
supervisor/tests/unit/plane.rs |
A drain reaches a flow that was still dialing, and only the drained version’s flows. |
removing_a_user_closes_only_their_sessions_and_refuses_them_after |
supervisor/tests/hot_swap.rs |
UserRemovalPolicy::Close by default. |
revoking_under_close_after_ends_the_session_once_the_grace_passes |
supervisor/tests/unit/session.rs |
CloseAfter on a paused clock. |
an_open_connection_keeps_transferring_across_a_reload |
app/tests/integration/e2e_reload.rs |
The same, end to end through etemenanki-app. |
Observers never slow the data plane
Section titled “Observers never slow the data plane”Tracking, statistics, usage accounting and flow events are read by front ends, REST clients and panels, and none of them may hold a relaying connection back.
- Counters are written by the relaying task alone. Each flow’s counters are atomics in its
FlowEntry, updated by theMeteredwrapper in the connection’s own task. Each session’s wire bytes are updated bydrivethe same way. - Aggregation happens elsewhere. The sampler (
supervisor/src/track/sampler.rs) reads the counters once per tick (DEFAULT_SAMPLE_INTERVAL, 1 s) and computes rates and totals off the data path; the usage ledger is reconciled in the background. - Events lag rather than block. Flow lifecycle events go out on a
tokio::sync::broadcastchannel ofEVENT_CAPACITY(1,024). Sending never waits: a subscriber that falls behind getsRecvError::Lagged(n)and loses the oldest events, and the data plane goes on. - Usage is delivered on its own task. A
UsageSinkis called from a task of its own on its interval. The usage module’s rule: “The data plane only adds to its session’s own counters.”
| Test | File | What it pins |
|---|---|---|
a_slow_usage_sink_does_not_stall_the_data_plane |
supervisor/tests/tracking.rs |
A sink that blocks does not hold up relaying. |
mux_sub_flows_and_their_session_count_exactly_what_moved |
supervisor/tests/tracking.rs |
Flow counters and session wire bytes count exactly what moved. |
Work that grows with the users runs off the runtime
Section titled “Work that grows with the users runs off the runtime”A node’s user set can be large. Planning an apply, staging its user tables and handlers, working out the user limits, and freeing what an apply replaced all grow with them, and none of it runs on an async worker. supervisor/src/system/blocking.rs gives the reason: “A worker busy for long can leave the I/O driver unpolled: tokio does not hand the driver to a parked worker before running the task it woke, so every connection in the process waits, not just the caller.”
pub(crate) async fn off_runtime<T, F>(work: F) -> Twhere F: FnOnce() -> T + Send + 'static, T: Send + 'static;
pub(crate) fn drop_off_runtime<T: Send + 'static>(value: T);off_runtimerunsworkon the blocking pool and returns its result; a panic in it is resumed in the caller.drop_off_runtimefrees a value on the blocking pool: what an apply replaces can hold every user of a node.- The actor lends its state.
Actor::stagemoves the running state out (Lent) for the blocking work and takes it back afterwards. The actor runs one command at a time, so nothing else reads that state meanwhile, and commit is left with pointer swaps. The sampler’s tick runs throughoff_runtimetoo. - The VMess hot tier is rebuilt off the handshake path. Each stream listener’s
refresh_hot_tiers(supervisor/src/serve.rs) askshot_tier_due()once a second (HOT_TIER_POLL), runsprepare_hot_tierthroughoff_runtime, and installs the result with one compare-and-swap (install_hot_tier). A handshake never rebuilds or reorders the tier.
katana keeps the same rule for its own per-user work, with a copy of the two functions in src/blocking.rs: each panel poll lowers its users off the runtime (NodeManager::lower_off_runtime), and both panel clients parse their user lists there.
| Test | File | What it pins |
|---|---|---|
changing_a_large_user_set_leaves_the_runtime_worker_free |
supervisor/tests/hot_swap.rs |
An apply that changes a large user set leaves the runtime worker free to serve. |
a_due_hot_tier_is_refreshed_by_the_listener |
supervisor/tests/unit/serve.rs |
A due VMess hot tier is prepared and installed by the listener’s refresher, which stops with the listener. |
lowering_leaves_the_runtime_worker_free |
katana tests/unit/manager/node.rs |
A poll’s lowering does not occupy the runtime worker. |
lowering_a_large_list_is_not_quadratic |
katana tests/unit/lower/spec.rs |
The shared-credential check does not compare each user with every one before it. |
Deterministic time in tests
Section titled “Deterministic time in tests”Proxy timeouts are measured in seconds or minutes: a 10 s handshake limit, a 300 s idle limit, a one-second speed-limit burst, a grace period before a removed user’s session closes. A test that sleeps through them is slow and flaky. The code avoids real sleeps in three ways:
- Deadlines are events. A core test delivers
Event::Deadlineby hand, as inhandshake_deadline_fails_the_connectionabove. No clock is involved. - The runtime and the supervisor arm tokio timers.
ProxyServerRuntime::set_deadlinecomputestokio::time::Instant::now() + afterand usestokio::time::sleep_until, neverstd::time. Its comment gives the reason: “so a paused test clock (the only way to test a minutes-long idle timeout) is honoured”. The pacer readstokio::time::Instantand sleeps withtokio::time::sleep_until, and removal grace timers sleep withtokio::time::sleep. A test marked#[tokio::test(start_paused = true)]then advances time instantly and exactly. - Wall clocks are injected. Timestamp checks take
now: fn() -> …in the constructor, as shown above.
| Test | File | Clock |
|---|---|---|
deadline_is_armed_against_the_tokio_clock |
concepts/tests/runtime.rs |
Paused; advances an hour first, so a deadline armed against std::time would fire at the wrong moment |
deadline_event_lets_the_core_time_out |
concepts/tests/runtime.rs |
Paused |
liveness_restarts_the_idle_deadline_on_progress |
protocols/tests/unit/transports/grpc_liveness.rs |
Paused |
handshake_deadline_fails_the_connection |
protocols/tests/unit/trojan/core.rs |
None; the deadline is an event |
a_limited_users_flow_moves_at_its_limit, a_raised_or_removed_limit_is_felt_within_a_second |
supervisor/tests/unit/track.rs |
Paused |
revoking_under_close_after_ends_the_session_once_the_grace_passes |
supervisor/tests/unit/session.rs |
Paused |
Panic-free parsing
Section titled “Panic-free parsing”Every byte a protocol parser reads comes from a peer that is not trusted. A panic in a parser kills the connection’s task, and a slice index computed from an attacker-controlled length is exactly where panics come from. So the library crates that parse wire data forbid the panicking forms at compile time. protocols/src/lib.rs, environment/src/lib.rs and reality/src/lib.rs all carry, at the crate root:
#![deny( clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing, clippy::arithmetic_side_effects)]A #![cfg_attr(test, allow(…))] right after it lifts the rule for test code, which works on known-good inputs. etemenanki-subscribe carries a lighter deny of unwrap_used, expect_used and panic; etemenanki-concepts, the supervisor, the app, the webclient, the ffi and katana carry no crate-level deny. The validation gate maintainers run before a change lands is cargo clippy --workspace --all-targets --all-features -- -D warnings, so every other clippy warning fails the change as well.
protocols/src/helpers/parse.rs provides the replacements:
pub fn take<'a, I>(data: &'a [u8], index: I, what: &'static str) -> Result<&'a [u8], ProtocolError>where I: SliceIndex<[u8], Output = [u8]>,
pub fn take_array<const N: usize>(data: &[u8], at: usize) -> Result<[u8; N], ProtocolError>
pub fn need_more<T>(result: std::io::Result<T>) -> std::io::Result<Option<T>>takereturnsProtocolError::Truncated(what)instead of panicking on an out-of-range slice.take_arraychecks the offset addition (Overflow("field offset")) and the bounds, foru16::from_be_bytesand similar reads.need_moreseparates “the buffer is still short” from “the input is malformed”, so a parser that is handed a growing buffer can ask to be called again.
| Test | File |
|---|---|
varint_above_62_bits_is_refused_not_panicked |
protocols/tests/unit/hysteria/protocol.rs |
varint_truncated_at_every_boundary |
protocols/tests/unit/hysteria/protocol.rs |
tcp_response_truncated_at_every_boundary |
protocols/tests/unit/hysteria/protocol.rs |
udp_truncated_in_the_header_is_refused_and_never_panics |
protocols/tests/unit/hysteria/protocol.rs |
rejects_truncated_metadata |
protocols/tests/unit/mux/frame.rs |
every_truncation_and_mutation_is_handled_without_panicking, server_hello_mutations_never_panic |
reality/tests/unit/tls13/messages.rs |
Dependencies point down; public enums grow by addition
Section titled “Dependencies point down; public enums grow by addition”A crate’s public API is a promise to every crate built on it. Two rules keep the promise cheap to keep.
etemenanki-reality sits at the bottom of the graph. It depends on no other etemenanki crate: its manifest lists tokio, bytes, OpenSSL, RustCrypto’s hkdf, hmac and sha2, and ml-kem, and its crate documentation states the boundary: “The caller connects to dest and hands both sockets in, so there is no dialer, resolver or routing here”. etemenanki-protocols 6.2.1 reaches it only through its reality feature, off by default like hysteria and tun, and only behind wrapper types of its own: RealityServer, RealityStream, ClientConfig and the decoders, which return io::Error, in protocols/src/transports/reality.rs, and Camouflage in protocols/src/transports/camouflage.rs. No type of etemenanki-reality appears in protocols’ public API, so a release of etemenanki-reality reaches the crates above it through a lockfile update alone. Camouflage and Disposition exist with or without the feature, so the API reads the same either way. etemenanki-supervisor 1.1.0 turns the feature on beside hysteria and tun. See etemenanki-reality overview and Transports: REALITY.
Enums that grow are #[non_exhaustive]. A new protocol or transport adds a variant, and an exhaustive public enum would make every addition a breaking change for whoever matches on it. These are marked:
| Crate | Enums |
|---|---|
| etemenanki-supervisor | InboundProtocolSpec, OutboundProtocolSpec, StreamShape |
| etemenanki-protocols | InboundTransport, TransportKind, TransportStream, Disposition |
| etemenanki-subscribe | Protocol, Stream, VmessSecurity, ShadowsocksMethod, Hysteria2Obfs |
A match outside the crate keeps a wildcard arm, which the compiler enforces; etemenanki-app and the ffi have theirs. A later variant is then a minor release, not a breaking one. Inside the supervisor a new protocol variant also meets the existing checks: InboundProtocolSpec::transport() and the shared transport validation described under One owner per rule hold it to every transport rule without a check of its own. At the pinned release, etemenanki-supervisor is at 1.1.0, etemenanki-subscribe at 1.0.0 and etemenanki-webclient at 2.0.0, all three past 0.x; the supervisor requires etemenanki-concepts 2.1.2 and etemenanki-protocols 6.2.
Review rules
Section titled “Review rules”Maintainers check every change against the rules below. Each rule describes what the code must do; none of them is a statement about which parts of the current code already do it. A change that touches the area a rule covers should come with a test for the rule, including a negative test where the rule forbids something.
UDP associations accept only their own client
Section titled “UDP associations accept only their own client”A UDP association (a SOCKS UDP ASSOCIATE, or any relay that hands a client a UDP endpoint) accepts datagrams only from the client that set it up, and checks every packet against that client. On the client side, a link accepts replies only from the relay it talks to and never treats a datagram from another source as a relay reply. Otherwise any host that can reach the relay port can inject packets into someone else’s flow.
A change here needs a test in which a third-party address sends to the relay and the packet is dropped.
Per-connection queues are bounded, and pressure reaches the producer
Section titled “Per-connection queues are bounded, and pressure reaches the producer”Every queue that holds data for one connection has an explicit capacity. Moving items from a bounded channel into an unbounded queue does not count: it removes the bound the channel was there to provide. When a consumer stops, the pressure travels back to whoever produces the data, and memory does not grow. In the one-task runtime the capped buffers are meant to be that bound; any component that adds a queue of its own needs a bound of its own.
The WireGuard driver (protocols/src/wireguard/device.rs) is a worked example. One driver task serves every connection in the tunnel, and each connection hands it application bytes over a bounded channel of CHANNEL_CAP (256) items. The driver takes at most one item ahead of a connection’s smoltcp socket and reads that connection’s channel only while it holds none. When the remote or the tunnel stops draining one connection, its socket fills, then its channel, and then its writer waits; the driver queues nothing more, and the other connections keep moving. On the way down, the driver reads a socket only while the connection’s channel toward the application has room.
| Test | File | What it pins |
|---|---|---|
a_held_item_keeps_the_channel_unread |
protocols/tests/unit/wireguard/device.rs |
While the driver holds an item, the channel is not read, so it fills and the producer’s next send fails with Full. |
a_stalled_tcp_flow_blocks_its_writer |
protocols/tests/pipeline/wireguard.rs |
A flow whose remote reads nothing blocks its writer after at most 512 KiB, another flow through the same tunnel still moves, and the waiting write goes through once the remote reads again. |
An active-connection limit covers the whole relay
Section titled “An active-connection limit covers the whole relay”A semaphore or permit that is described as limiting active connections is held from admission until the relay ends. A permit that covers only the handshake, the decode step or the transport step limits that stage, not active connections. At every spawn boundary, the permit has to move into the task that runs the relay and must not be dropped before the relay starts. A test for such a limit checks both sides: that the permit bounds something while the relay runs, and that it is released when the relay ends.
UDP to a multi-address name picks a usable family
Section titled “UDP to a multi-address name picks a usable family”When DNS returns several addresses for a UDP destination, the code picks one whose family (IPv4 or IPv6) matches a socket that is actually available. Taking the first answer and dropping the packet because that family has no socket ignores addresses that would have worked.
Fixed protocol fields are validated strictly
Section titled “Fixed protocol fields are validated strictly”Version bytes, reserved bytes, lengths, commands and type codes are checked against the values the protocol defines, and anything else is an error. The peer is not assumed to be a correct implementation. A change to a parser comes with negative tests that feed each fixed field a value the protocol does not define.
Configuration typos fail closed
Section titled “Configuration typos fail closed”Stable configuration structures reject unknown fields. This matters most for listen, port, protocol, network, security, TLS settings, outbounds and routing. An unknown value for a setting that selects behaviour is an error: a security value that is not recognised never results in plaintext because it is “not tls”.
Validation has one owner
Section titled “Validation has one owner”A rule about what a spec means is added to supervisor/src/build/validate.rs, once, for every front end. A front end refuses only what its own format gets wrong. A change that adds the same check to a front end and to the supervisor, or to two front ends, is asked to move it.
Applies are transactional
Section titled “Applies are transactional”An apply does not tear down what runs and only then discover that the new spec cannot start. The intended order is:
- validate the new spec and plan it against what runs;
- build and bind everything the new spec needs, beside what runs;
- only then publish it and stop what is gone;
- on failure, drop what was built and leave what runs untouched.
A change that makes commit fallible, or moves fallible work out of prepare, breaks this rule. A failed apply also needs a way to be retried once an external dependency recovers.
Every byte reaches exactly one take
Section titled “Every byte reaches exactly one take”Per-user usage keeps these properties:
- a byte lands in exactly one
take_usageresult, whichever of polling and a sink took it; - bytes a user moved before being removed are still reported;
- bytes added while a report is in flight are not taken by that report.
A take drains pending totals rather than resetting live counters, so bytes moved during the take land in a later one.
Rate limits charge actual bytes as debt
Section titled “Rate limits charge actual bytes as debt”A token bucket charges the number of bytes actually moved. A chunk larger than the bucket’s capacity is charged in full and the bucket goes into debt; the chunk does not pass after a single refill period. The effective rate does not depend on the size of the relay’s reads and writes.
Logs never contain credentials
Section titled “Logs never contain credentials”Log lines do not contain passwords, UUIDs, tokens, keys, panel secrets, or full URLs whose query string carries a secret. When a credential is malformed, the log names a safe identifier and the kind of error, never the value itself. Changes to HTTP error handling keep URLs and tokens redacted.