katana overview
Source files: 63 · checked against katana v6.1.0 · Etemenanki 46c12e4
katana/Cargo.tomlkatana/Cargo.lockkatana/.gitmoduleskatana/src/main.rskatana/src/runtime.rskatana/src/config.rskatana/src/api/mod.rskatana/src/api/newv2board.rskatana/src/api/helium.rskatana/src/api/hysteria.rskatana/src/api/embedded_cert.rskatana/src/blocking.rskatana/src/manager/mod.rskatana/src/manager/node.rskatana/src/lower/mod.rskatana/src/lower/inbound.rskatana/src/lower/outbound.rskatana/src/lower/route.rskatana/src/rule.rskatana/tests/integration.rskatana/tests/integration/xray_interop.rskatana/tests/integration/sniff.rskatana/tests/integration/hysteria_interop.rskatana/tests/support/mod.rskatana/tests/unit/e2e.rskatana/tests/unit/runtime.rskatana/tests/unit/lower/spec.rskatana/tests/unit/lower/outbound.rskatana/tests/unit/rule.rskatana/tests/unit/manager/node.rskatana/tests/unit/api/helium.rskatana/tests/unit/api/newv2board.rskatana/tests/unit/api/http.rsEtemenanki/supervisor/Cargo.tomlEtemenanki/supervisor/src/lib.rsEtemenanki/supervisor/src/supervisor.rsEtemenanki/supervisor/src/policy.rsEtemenanki/supervisor/src/guard.rsEtemenanki/supervisor/src/connector.rsEtemenanki/supervisor/src/serve.rsEtemenanki/supervisor/src/system/listener.rsEtemenanki/supervisor/src/build/inbound.rsEtemenanki/supervisor/src/build/outbound.rsEtemenanki/supervisor/src/build/users.rsEtemenanki/supervisor/src/build/validate.rsEtemenanki/supervisor/src/entity/session.rsEtemenanki/supervisor/src/entity/usage.rsEtemenanki/supervisor/src/topology/flow.rsEtemenanki/supervisor/src/topology/plane.rsEtemenanki/supervisor/src/topology/router.rsEtemenanki/supervisor/src/topology/spec_plan/plan.rsEtemenanki/supervisor/src/topology/outbound/udp_fanout.rsEtemenanki/supervisor/src/track/mod.rsEtemenanki/supervisor/src/track/metered.rsEtemenanki/supervisor/src/track/pace.rsEtemenanki/supervisor/src/track/sampler.rsEtemenanki/protocols/Cargo.tomlEtemenanki/protocols/src/hysteria/server/config.rsEtemenanki/protocols/src/hysteria/server/inbound.rsEtemenanki/app/src/api.rsEtemenanki/app/src/instance.rsEtemenanki/app/src/lower.rsEtemenanki/app/src/main.rs
katana is a panel node agent. One process serves one or more panel nodes: it reads each node’s settings and user list from a panel (UniProxy, the node API of the V2board family, or Helium’s node API v2), keeps the node in step with them, and reports each user’s traffic back (and, to helium, the addresses users connected from). katana 6.0.0 removed the SSPanel (mod_mu) client, and with it the reports of audit hits that only SSPanel took; a node that still names SSPanel is refused (see Upgrading to katana 6). From 4.0 on, katana is a front end of etemenanki-supervisor: it lowers each node into a typed Spec, the desired state, and hands it to a Supervisor, which binds, serves, routes, admits, paces and counts. katana’s own code is the panel side, the lowering, and the loop that decides when to apply.
This page is the map for contributors. It says what katana owns and what it delegates, which crates it is built from, how the process is structured, what each module does, how a panel answer becomes a spec and a spec becomes a usage report, and where every 3.x module went. Each section links to the page that covers that part in detail.
Responsibilities
Section titled “Responsibilities”katana:
- parses its TOML config (
src/config.rs) and, with--test, checks each node before anything runs; - runs one
NodeManagerand oneSupervisor<Uid>per[[node]]table; - talks to the panel through
PanelClient: node settings, read into the contract’s node config (api::Node) with what katana cannot serve refused by name, users, audit rules and reports; - lowers the panel’s answer, the node’s config and the process-wide
[[outbound]]and[dns]into aSpec<Uid>(src/lower/), on the blocking pool; - applies each new spec with
Supervisor::apply_with, and closes every session of the node withclose(Selector::All)when a change needs it; - turns the panel’s audit rules into routes to blackhole outbounds (
src/rule.rs); - reads each user’s client addresses off the supervisor’s flow events, where it collects them (helium, under
enable_device_limit); - takes each user’s usage from the supervisor and reports it to the panel;
- applies edits of its config file to running nodes, and adds, removes or respawns nodes.
katana does not:
- parse, frame or authenticate any proxy protocol, terminate TLS, or relay a byte. The supervisor and the protocols crate do all of that.
- serve TUN inbounds, or a SOCKS or HTTP node in the clear. A panel node is VMess, VLESS (over REALITY, with or without Vision, among other transports), Trojan, Shadowsocks, Shadowsocks 2022, Hysteria 2, AnyTLS, SOCKS or HTTP over TLS, or sss. helium’s Shadowsocks is Shadowsocks 2022 or a legacy AEAD cipher, as UniProxy’s is, and sss comes through helium alone: the UniProxy client refuses an sss node with
newV2board: no UniProxy panel describes an sss node; sss is Helium's own protocol, served with panel_type = "Helium".src/lower/inbound.rs→credentialsanswers any other inbound withthe inbound admits no panel users. - reach a proxy upstream over TLS, WebSocket or gRPC. Every proxy outbound it lowers uses
StreamShape::Tcp; the module comment ofsrc/lower/outbound.rssays “TLS, WS and gRPC toward an upstream are out of scope”. - lower balancers, a split DNS setup, or removal and drain policies of its own. Every spec has
balancers: Vec::new()andDnsSpec::Single, withdrain: Noneon each outbound anduser_removal: Noneon the inbound. ItsPoliciesset only the IP ban and the gRPC carrier close, from[node.controller]. - report online users or node status to a panel. The panel clients have no such call; helium’s report carries client addresses, not an online count.
- use the values of
api.device_limitorcontroller.send_ip. Both are parsed, and both take part in the runtime’s comparison of[[node]]tables, so an edit to either reaches the node as aStaticUpdate::Config. An edit todevice_limitrebuilds the panel client like any other[node.api]field; an edit tosend_ipis only stored. - serve a REST API.
katana and the supervisor
Section titled “katana and the supervisor”| Concern | katana | etemenanki-supervisor |
Detail |
|---|---|---|---|
| Node settings | Fetches the node, api::Node (the contract’s NodeConfig), from the panel, converting a UniProxy answer into it, or builds it from [node.hysteria] |
None | Panel clients |
| The listener | Lowers one InboundSpec: bind host and port, a stream node’s handoff socket, transport shape, certificate bytes, sniffing, a WebSocket node’s real-IP header |
Binds it and any handoff socket, accepts, takes the TCP connections a relay on the same host hands over, and runs the TLS, WebSocket or gRPC handshake and the protocol core. Each connection is a session, and on a gRPC carrier each HTTP/2 stream is a session of its own | Serving |
| Users | Lowers the panel’s user list into one UserSet tagged users, each user’s credential derived from their UUID, with the panel’s device limit under enable_device_limit |
Builds the user tables, admits each flow’s principal on its session, and hands the sessions of a removed user, or of a user whose credential changed, to the removal policy | Users and sessions |
| Routing | Lowers [node.route], with the audit routes put first |
Compiles the route table into the plane and routes every flow and UDP packet | Routing plane |
| Outbounds and DNS | Lowers the built-in outbounds, every [[outbound]], one blackhole per audit rule id, and [dns] |
Builds, keeps and dials them | Outbounds, DNS |
| Speed limits | Passes on each user’s rate: the panel’s, or [node.api] speed_limit for every user when that is set |
Sets each user’s pacer rate when an apply commits, and paces their flows | Tracking |
| Device limits and bans | Lowers the panel’s device limits, the [node.controller] ban and carrier settings, and the proxies a WebSocket node trusts to name its clients |
Takes a WebSocket client’s address from a trusted proxy’s header, refuses a session from one address too many, bans an address that keeps failing to authenticate, closes a gRPC connection whose streams keep failing | Serving, Lowering a node into a spec |
| Usage | Takes usage on every poll and reports it | Counts wire bytes per session into a per-user ledger | Usage, Traffic accounting |
| Destination audit | Turns rules into audit#<id> routes to blackhole outbounds |
Routes each flow a rule matches to its blackhole | Destination audit |
| Changes | Decides when to apply, and when every session must be closed | Plans, prepares and commits each spec, keeping what did not change | Reconcile, Node manager |
| Validation | Refuses by name what a UniProxy answer asks for and the kernel cannot serve, as the answer is read; refuses this host’s settings the kernel cannot honour while lowering; repeats three Hysteria 2 checks | Owns every rule about what a spec means | Validation |
The module comment of supervisor/src/build/validate.rs states the split: validation there is “the one owner of every rule about what a spec means: which tags exist, which fields go together, which values are in range”, and “a front end owns only syntax (parsing its own format and reading files), so a rule is never checked on one side only”. katana refuses, by name, what it cannot serve before a spec exists, in two places. A panel’s answer becomes the contract’s node config (api::Node) as it is read: helium’s is one already, and a config that breaks the contract’s rules does not parse, while the UniProxy client (src/api/newv2board.rs → parse_node_config) refuses what a UniProxy answer asks for and katana cannot serve, then runs the contract’s validate(). The lowering then judges only what the TOML asks for; the module comment of src/lower/mod.rs says “The panel’s answer arrives as the contract’s node, which says nothing the kernel cannot serve; what the TOML asks for and the kernel cannot do is refused here, by name, before a spec exists”. Three checks the supervisor also makes are repeated in katana: the masquerade response (src/lower/inbound.rs → masquerade_spec, on every Hysteria 2 node), and, on a node [node.hysteria] describes or completes, the Salamander key length (at least 4 bytes) and the UDP idle timeout range (2 to 600 s), in src/api/hysteria.rs → obfs and udp; on a helium node the contract holds its answer to the same rules. The doc comment of masquerade_spec gives the reason for the first: the answer is “refused as the supervisor would refuse it: judged here too so the refusal reads as it always has.”
Dependencies
Section titled “Dependencies”The crate
Section titled “The crate”Cargo.toml declares the package katana, version 6.1.0, edition 2024. It has no library target. The package builds one binary from src/main.rs, whose clap doc comment is the --help headline, XrayR-compatible proxy node agent on the Etemenanki kernel, plus the integration-test target tests/integration.rs. No other crate depends on katana. The repository is separate from the Etemenanki workspace and consumes the kernel crates as published packages.
Kernel crates
Section titled “Kernel crates”All four come from a private Cargo registry, and so does etemenanki-reality (0.1.1 in the lockfile), which the protocols crate’s reality feature pulls in; katana names none of its items. katana does not depend on etemenanki-app. 4.9.0 moved katana onto protocols 6.0 and supervisor 0.12 with the reality feature on, 4.10.0 onto supervisor 1.0.0, protocols 6.1.0 and concepts 2.1.2, and 4.10.1 onto protocols 6.2.0 and supervisor 1.0.1. 5.0.0 moved no kernel crate; it added helium-node-api (below). 5.1.0 moved katana onto protocols 7.0.0 and supervisor 2.0.0, and 6.0.0 onto protocols 7.1.1 and supervisor 2.1.0. 6.1.0 changed no kernel crate’s requirement; its lockfile resolves concepts 2.2.0, environment 3.2.2, protocols 7.2.1 and reality 0.1.1.
| Crate | Cargo.toml |
Cargo.lock |
Features | What katana uses |
|---|---|---|---|---|
etemenanki-concepts |
2.1 |
2.2.0 | none | net::{Destination, DialNetwork, Remote} (src/lower/outbound.rs, and src/lower/inbound.rs for a REALITY node’s cover site); the tests also use its client and server runtimes |
etemenanki-environment |
3.0 |
3.2.2 | none | routing::{RouteMatch, parse_port_match} (src/lower/route.rs), routing::parse_domain_regexes (src/rule.rs) |
etemenanki-protocols |
7.1.1 |
7.2.1 | vendored-openssl, hysteria, reality |
transports::reality::{decode_private_key, decode_short_id}, vless::addons::XTLS_RPRX_VISION, hysteria::server::config::{DEFAULT_MAX_CONNECTIONS, DEFAULT_MAX_CIRCUITS}, hysteria::config::{Bandwidth, BandwidthConfig, Fallback, QuicOptions}, hysteria::server::masquerade::Masquerade, ss_2022::{Method, users::{decode_psk, normalise_psk}}, ss_legacy::Method, vmess::Security, wireguard::{DEFAULT_MTU, parse_key}, dns::{Backend, ResolverSpec}, helpers::address_family::AddressFamilyStrategy, transports::ws::endpoint::WsRoute (to judge a real_ip_header name) |
etemenanki-supervisor |
2.1 |
2.1.0 | none | Supervisor, ApplyOptions, Selector, check; the spec types in topology::spec_plan, RouteFile, RealIpSpec, RealityServerSpec, VlessFlow, SssChain, SssReject and SssServerSettings among them; topology::inbound::{BindSpec, HandoffSpec}; entity::user::{UserId, UserName, UserSet, UserSpec, Credentials, Account}; policy::{Policies, IpBanPolicy}; track::FlowEvent |
protocols/Cargo.toml defines no default features, so each feature below is in the build only because some crate asks for it:
Feature of etemenanki-protocols |
Asked for by | Pulls in | Why it is there |
|---|---|---|---|
vendored-openssl |
katana | openssl/vendored |
The OpenSSL behind the protocols crate’s TLS transports is built from source and linked in, instead of taken from the host |
hysteria |
katana, and etemenanki-supervisor |
quinn, h3, h3-quinn (the patched shinku-quinn and shinku-h3-quinn, see shinku-quic), shinku-quic, rustls, rustls-native-certs, rustls-pemfile, rustls-pki-types, blake2 |
katana serves Hysteria 2 nodes |
reality |
katana, and etemenanki-supervisor |
etemenanki-reality (REALITY’s own TLS 1.3 on OpenSSL, RustCrypto’s HKDF, HMAC and SHA-2, and ml-kem) |
katana serves VLESS nodes over REALITY |
tun |
etemenanki-supervisor only (features = ["hysteria", "tun", "reality"]) |
ipstack, tun-rs, rtnetlink, route_manager, etherparse |
Cargo unifies features within a build, so katana’s binary contains the TUN stack too. katana never lowers a TUN inbound |
The helium node API crate
Section titled “The helium node API crate”helium-node-api 0.2.0 (requirement 0.2.0, from the same private Cargo registry) is new in 5.0.0; 6.1.0 moved it from 0.1.0, whose Shadowsocks took the 2022 ciphers alone, to 0.2.0, whose SsCipher is Ss2022 { cipher, server_key } or Legacy(SsLegacyCipher). Its Cargo.toml comment calls it “the node API v2 contract with Helium: the config, users and report types both ends compile”. It holds the bodies of Helium’s node API v2 as types: helium_node_api::config::NodeConfig for GET config, users::Users for GET users, and report::Report and report::ReportAnswer for POST report. Helium serializes them from the same definitions. The node config is also katana’s own model of a node, whichever panel describes it: src/api/mod.rs → Node is a type alias of it, src/api/helium.rs hands a config answer on untouched, src/api/newv2board.rs converts a UniProxy answer into one, src/api/hysteria.rs builds one from [node.hysteria], and src/lower/inbound.rs lowers it. src/api/helium.rs maps the users answer and the report to and from katana’s models by type. In the tests, tests/unit/api/helium.rs and tests/unit/e2e.rs build users answers with it, and the UniProxy, lowering and node manager tests build node configs with it. It depends on base64, serde, serde_json and uuid, which katana’s lockfile already held, so adding it added no other package. Panel clients describes the bodies.
Other dependencies
Section titled “Other dependencies”| Crate | Requirement and features | Used in |
|---|---|---|
tokio |
1.53.1, full |
Everything async: #[tokio::main] in src/main.rs, signals, timers and channels in src/runtime.rs and src/manager/node.rs |
tokio-util |
0.7.19, codec, rt |
CancellationToken (src/runtime.rs, src/manager/node.rs) |
bytes |
1.12.1 |
The UniProxy and helium clients’ response bodies |
socket2 |
0.6.5 |
src/lower/inbound.rs → dual_stack, which asks an unbound IPv6 socket whether it takes IPv4 |
compact_str |
0.10, serde |
Tags and names in the config, the lowering and the audit |
parking_lot |
0.12 |
The Mutexes of NodeManager, RuleManager, EtagCache and the UniProxy client |
anyhow |
1.0 |
Panel client and runtime errors |
tracing, tracing-subscriber |
0.1; 0.3 with env-filter |
Logging; src/runtime.rs → init_tracing and its reloadable filter |
clap |
4.6, derive |
src/main.rs → Args |
cidr |
0.3 |
IpCidr: a rule’s cidr in src/lower/route.rs, and real_ip_from in src/lower/inbound.rs → real_ip |
regex |
1.13 |
Audit rules (DetectRule.pattern) |
serde, serde_json, toml |
1.0 with derive; 1.0; 1.1 |
The config schema and the panel responses |
uuid |
1.24, v4, serde |
User and outbound credentials, and each report’s random id |
reqwest |
0.13, no default features, gzip, json, native-tls-vendored, query |
The panel clients; gzip (since 6.0.1) has every request ask for a compressed answer and decompresses it, and native-tls-vendored builds their TLS on a vendored OpenSSL as well |
notify |
8 |
The config file watcher in src/runtime.rs |
mimalloc |
0.1, under [target.'cfg(target_env = "musl")'.dependencies] only |
src/main.rs → GLOBAL, the global allocator of a musl build |
Dev-dependencies: tokio again with test-util added (the comment: the relay idle deadline is minutes long, so it is only testable against a clock the test drives), and openssl 0.10.81 with vendored, which tests/support/mod.rs and tests/unit/e2e.rs use to make self-signed certificates. The comment on openssl explains the vendored choice: it matches the vendored-openssl feature, so both resolve to one OpenSSL build. The release profile sets lto = true and codegen-units = 4.
Changes since 3.x
Section titled “Changes since 3.x”| Change | Crates |
|---|---|
| Added | etemenanki-supervisor, socket2; mimalloc for musl builds; helium-node-api in 5.0.0 |
| Removed | tokio-stream, tower, futures, smallvec, arc-swap, moka, thiserror, rand |
| Raised | etemenanki-concepts 2.0.0 → 2.1, etemenanki-environment 2.0.0 → 3.0, etemenanki-protocols 2.0.0 → 7.1.1 |
Process structure
Section titled “Process structure”Entry point
Section titled “Entry point”src/main.rs declares the seven modules (api, blocking, config, lower, manager, rule, runtime) and, right after them and in test builds only, tests/unit/e2e.rs as mod e2e. A musl build also gets mimalloc as its global allocator; the glibc build keeps glibc’s. The comments on the static and on the Cargo.toml table give the reason: musl’s allocator takes one global lock for every malloc and free.
#[cfg(target_env = "musl")]#[global_allocator]static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
/// XrayR-compatible proxy node agent on the Etemenanki kernel.#[derive(Parser)]#[command(version, about)]struct Args { /// Path to the TOML configuration file. #[arg(short, long, default_value = "config.toml")] config: PathBuf, /// Validate the configuration and exit without binding any listener. #[arg(long)] test: bool,}
#[tokio::main]async fn main() -> ExitCodeThe pinned binary prints:
XrayR-compatible proxy node agent on the Etemenanki kernel
Usage: katana [OPTIONS]
Options: -c, --config <CONFIG> Path to the TOML configuration file [default: config.toml] --test Validate the configuration and exit without binding any listener -h, --help Print help -V, --version Print versionkatana --version prints katana 6.1.0. main runs on tokio’s multi-threaded runtime and does three things:
- It calls
runtime::init_tracing(&args.config), which installs the log subscriber with a reloadableEnvFilter. The initial filter isRUST_LOGwhen it parses; otherwise the config file’s[log].level, read withconfig::load; otherwiseinfo. The config’s level goes to the lenientEnvFilter::new, which skips a directive that does not parse with a line on standard error, for exampleignoring `bogus==`: error parsing level filter: expected one of "off", "error", "warn", "info", "debug", "trace", or a number 0-5; a filter left without any directive logs errors only.init_tracingreturns aLogReloadclosure that swaps the filter at run time throughEnvFilter::try_new, and that logsinvalid log level "<level>": <error>instead when the level it is given does not parse. Logs go to standard output in the defaulttracing_subscriberformat (time, level, target, message), for example2026-09-28T21:26:46.958170Z ERROR katana::runtime: config defines no [[node]] entries. - With
--test, it awaitsruntime::test_configand exits:Configuration OKon standard output and exit code 0, orconfiguration error: <error>on standard error and exit code 1. - Otherwise it returns what
runtime::run(args.config, reload)returns.
test_config loads the config, refuses one without nodes (config defines no [[node]] entries), logs the shared-WireGuard warning (see below), and then, for each node in order, builds its panel client with PanelClient::new and runs check_node. It stops at the first node that fails and prefixes its error with node <api.node_id>: . check_node is etemenanki_supervisor::check(&lower::test_spec(cfg, globals)?), a dry run that builds everything a start would build without binding. test_spec first refuses half a real_ip_header and real_ip_from setting, or a typo in one, a handoff_dir or handoff_group the relay could not use, and an unknown [node.hysteria] congestion, on every node. For most node types it holds only the outbounds, DNS and route table, because the inbound and its users come from the panel. A Hysteria 2 node’s own settings are local on newV2board, so test_spec lowers its inbound from the node api::hysteria::local builds from [node.hysteria], on port 1 when [node.hysteria].port is 0, with one placeholder user. A helium node names no node_type, so it is checked like every other non-Hysteria node; before that, building its panel client refuses any local key that would describe its protocol (see below). Validation describes check, and Process runtime and reload describes test_config.
The process root
Section titled “The process root”src/runtime.rs → run owns the loaded Config for the life of the process:
config::load. On error it logsfailed to load config: <error>and returns exit code 1.- A config with no
[[node]]logsconfig defines no [[node]] entriesand returns 1. warn_shared_wireguardlogs a warning for each WireGuard outbound that more than one node routes to.Arc::new(cfg.globals())is theGlobalsevery node lowers: the[[outbound]]entries and[dns].- A fresh root
CancellationToken, thenspawn_nodefor each node.spawn_nodecallsbuild_node(PanelClient::new, thencheck_node, thenNodeManager::new) andspawn_built. A node that does not build is logged asnode <api.node_id>: <error>and not spawned; the others start. - No node spawned:
no nodes could be started, exit code 1. - The config watcher. If it cannot be set up,
runlogsconfig watcher disabled (no live reload): <error>and serves on without reloads. - A signal task that waits for
SIGINTorSIGTERM(only Ctrl-C where theSIGTERMhandler cannot be installed, and on non-Unix targets) and cancels the root token. - The main loop selects on the root token and the watcher. When the config file is edited, it loads the file and calls
apply_reload; a file that does not load logsconfig reload failed, keeping current: <error>. - On cancellation it logs
shutting down, cancels the root token, awaits every node’sJoinHandle, and returns exit code 0.
apply_reload checks every node the new config adds or changes, and every node when [[outbound]] or [dns] changed, before it touches a running node; a kept node whose [[node]] table and the globals are both unchanged is not checked again. One failure refuses the whole reload, logged at ERROR as reload: node <display_id>: <error>; keeping current config. Otherwise it goes on in this order, logging each step at INFO:
| Step | Log line |
|---|---|
Set a changed log level through LogReload; a level removed from the file reloads as info |
reload: log level → <level> |
Send StaticUpdate::Globals to every node, when [[outbound]] or [dns] changed |
reload: outbound pool rebuilt |
| Remove each node whose identity is gone | reload: removing node <display_id> |
Send StaticUpdate::Config to each kept node whose [[node]] table changed |
reload: reconfigured node <display_id> |
| Spawn each added node | reload: added node <display_id> |
Process runtime and reload covers the schema, node identity and every reload branch.
One node manager and one supervisor per node
Section titled “One node manager and one supervisor per node”Each [[node]] gets its own NodeManager (src/manager/node.rs), spawned as one tokio task with a child of the root token. The first successful bootstrap lowers the spec on the blocking pool and starts the node’s own supervisor with Supervisor::start, which takes every builder default: a 1 s sampler tick (DEFAULT_SAMPLE_INTERVAL), no usage sink, the default socket options, and ApplyOptions::default() (allow_disruptive: false) for the first apply. start runs that first apply on the calling task, the node task, then spawns the sampler and the actor, and returns (Supervisor, ApplyReport); katana discards the report. The supervisor is stored once in NodeManager.supervisor, a OnceLock<Supervisor<Uid>>, and every later change goes through it.
One supervisor per node means that nodes share configuration values and no runtime state:
- each node builds its own outbounds from the same
Globals, so each has its own freedom sockets, proxy clients and WireGuard tunnel; - each node builds its own resolver from
[dns], with a cache of its own (the doc comment ofDnsConfig: “Each node keeps a cache of its own”); - each node has its own tracker, flow events and usage ledger, so a node’s report covers its own users only;
- a change to
[[outbound]]or[dns]reaches every node as its ownStaticUpdate::Globals, and each node applies it to its own supervisor.
The WireGuard case has a visible consequence: several nodes that route to one WireGuard outbound bring up several tunnels with the same key, and a WireGuard peer keeps one session per key. runtime::shared_wireguard looks for outbounds whose protocol is wireguard or wg and that more than one node names, by its route.default or by any of its rules; warn_shared_wireguard logs each one at startup, in --test and on each reload it accepts:
WARN katana::runtime: wireguard outbound wg-egress is routed to by 2 nodes (helium@https://panel.example.com#1, newv2board@https://panel.example.com#2/v2ray): each brings up its own tunnel with the same key, and the peer keeps only one of them at a timeNodes are named there by display_id, which never includes api.key.
Panel clients
Section titled “Panel clients”src/api/mod.rs → PanelClient is an enum over the two panel clients. PanelClient::new(cfg) picks one by panel_type, compared lower-cased: newv2board or v2board builds newv2board::Client, and helium builds helium::Client. sspanel fails by name, with the value as the file spells it, for example panel_type "SSpanel" is not supported: katana serves the NewV2board and Helium panels; the code’s comment gives the reason: a node that ran on SSPanel before has to be moved to another panel, not respelled. Anything else fails with unknown panel_type "<lower-cased value>". The UniProxy client refuses a node_type that NodeType::parse does not know with unknown node_type "<value as written>". On helium the panel alone describes the protocol, so helium::Client::new refuses a node whose config sets [node.api] node_type or enable_vless, or any [node.hysteria] key but congestion, naming the first one it finds:
[node.api] node_type is set, but a helium node's protocol is described by the panel; remove it (of [node.hysteria], only congestion is this host's to choose)pub enum PanelClient { NewV2board(newv2board::Client), Helium(helium::Client),}
impl PanelClient { pub fn new(cfg: &NodeConfig) -> Result<Self>; pub fn keeps_client_ips(&self) -> bool; pub async fn node_info(&self) -> Result<Option<Node>>; // None: 304 Not Modified pub async fn user_list(&self) -> Result<Option<Vec<UserInfo>>>; // None: 304 Not Modified pub async fn report(&self, report: &NodeReport) -> Result<()>; pub async fn node_rule(&self) -> Result<Option<Vec<DetectRule>>>; pub fn forget_etags(&self); pub fn inherit_routes(&self, old: &PanelClient);}| Call | UniProxy client | helium client |
|---|---|---|
node_info |
GET /api/v1/server/UniProxy/config |
GET /api/node/v2/<node_id>/config |
user_list |
GET /api/v1/server/UniProxy/user |
GET /api/node/v2/<node_id>/users |
report |
POST /api/v1/server/UniProxy/push, traffic only |
POST /api/node/v2/<node_id>/report, traffic and client addresses under a report id |
node_rule |
No request: the block routes of the last node config, plus the local rule file |
No request: the local rule file alone, as the node config carries no routes |
| Key | node_id, node_type and token in the query of every request |
Authorization: Bearer; the node id is in the path |
The UniProxy node_type parameter is newv2board::node_type_param: vless for a V2ray node with api.enable_vless, otherwise api.node_type lower-cased.
Each client holds its own reqwest::Client, built by build_http_client(timeout_secs, cfg.enable_mtls) with a timeout of api.timeout seconds (0 means 5 s, ApiConfig::timeout_secs). katana presents a client certificate when a panel asks for one, unless the node sets enable_mtls = false, and does not follow redirects. http_client_builder also turns on gzip(true), so every request says Accept-Encoding: gzip and a gzip-compressed answer is decompressed before it is read; a weak ETag (W/"…") is kept and sent back as it came. Each client also holds an EtagCache keyed by endpoint ("node" and "users") whose tags go out as If-None-Match; an empty tag is not stored. forget_etags clears the cache, and each bootstrap attempt calls it so that it reads everything in full. The UniProxy key travels in the query string, helium’s in a header. error_for_status strips the URL from reqwest’s status errors (without_url), every request error is wrapped in a context that names only the path or the endpoint, such as GET <path> or POST UniProxy push, and the node logs a panel error with {e}, which prints only that outermost context.
inherit_routes matters only between two UniProxy clients: a client built for a config edit takes the block routes the old client last read, so the audit rules derived from them hold until the new client reads the node config itself. helium sends no routes.
Only two modules outside src/api/ touch a client. src/runtime.rs builds clients (build_node, and the checks in apply_reload and test_config) but makes no request. src/manager/node.rs makes every request, and builds a replacement client when a config edit changes panel_type, [node.api], enable_mtls or [node.hysteria], which the UniProxy client keeps a copy of to complete a Hysteria 2 node. src/lower/ and src/rule.rs read the api models only (and test_spec calls api::hysteria::local), and nothing on the supervisor’s data path calls the panel. Panel clients describes every request and parser.
Task tree
Section titled “Task tree”flowchart TB main["runtime::run, the main task"] sig["signal task"] watch["config watcher"] node["NodeManager::run, one per node"] ips["client-address task, spawn_client_ips"] actor["supervisor actor"] sampler["supervisor sampler, every 1 s"] accept["accept loop, one per listener"] conn["one task per connection of a stream listener"] blocking["blocking pool: lowering, user-list parsing, drops"] sig -- "cancels root" --> main watch -- "config edited" --> main main -- "tokio::spawn with root.child_token()" --> node node -- "first apply, inside Supervisor::start" --> accept node -- "Supervisor::start spawns" --> sampler node -- "Supervisor::start spawns" --> actor actor -- "later applies" --> accept node -- "after bootstrap" --> ips accept -- "on the supervisor's TaskTracker" --> conn node -- "off_runtime" --> blocking
- The main task runs
runtime::runand owns the config and everyNodeHandle. - The signal task is spawned by
runand cancels the root token once. - The config watcher tells the main loop that the config file was edited. Process runtime and reload describes it.
NodeManager::runis one task per node. The bootstrap, the poll loop and the static updates all run on it, so a node never applies two changes at once.- The client-address task is spawned by
spawn_client_ipsonce the node is up. It reads the flow-event receiver it was handed until the node token fires or the channel closes, and keeps a user’s client address only where the node collects them. - The blocking pool. Work that grows with a node’s users runs there, through
src/blocking.rs→off_runtime: lowering a spec, parsing a user list, and dropping a replaced spec or user list (drop_off_runtime). The module comment gives the reason: a worker busy for long can leave the I/O driver unpolled, and every connection in the process waits, not just the node’s. - The supervisor’s tasks.
Listener::startspawns each listener’s accept loop on the supervisor’sTaskTracker: for the first spec from insideSupervisor::start, on the node task, and for later specs from the actor.Supervisor::startthen spawns the sampler, which ticks everyDEFAULT_SAMPLE_INTERVAL(1 s), the guard’s sweep, and the actor, which owns what runs. A stream accept loop (run_stream_inbound) spawns each connection on the same tracker, and one task (refresh_hot_tiers) that, once a second, refreshes the VMess validator’s hot tier when it is due (VMess: keys and authentication). A Hysteria 2 listener (run_hysteria_inbound) keeps its QUIC connections in aJoinSetthat its own task owns (Hy2Inbound::run). Sessions hang off the supervisor’s own root token, not off any katana token. The supervisor and Serving describe them.
Channels and tokens
Section titled “Channels and tokens”| Channel or token | Type | From → to | Purpose |
|---|---|---|---|
root |
CancellationToken |
signal task → main loop, and every node through its child | Process shutdown |
NodeHandle.shutdown |
root.child_token() |
apply_reload → one node |
Stops one node; fires with root too |
static_tx / static_rx |
mpsc::channel(16) of StaticUpdate |
apply_reload → one node |
A changed [[node]] table, or new globals |
| supervisor commands | mpsc::channel(16) inside Supervisor |
node task → supervisor actor | apply_with, close, shutdown |
| flow events | broadcast of EVENT_CAPACITY (1,024) |
supervisor tracker → client-address task | FlowEvent::Opened and FlowEvent::Closed |
| session tokens | One CancellationToken per session, a child of the supervisor’s root token |
close(Selector::All) cancels each session’s token; shutdown cancels the root |
Ends sessions; katana reaches them only through these two calls |
Shared state
Section titled “Shared state”| Item | Type | Written by | Read by |
|---|---|---|---|
NodeManager.api |
parking_lot::Mutex<Arc<PanelClient>> |
apply_static |
Every panel call, which clones the Arc out so no guard is held across a request |
NodeManager.cfg |
parking_lot::Mutex<NodeConfig> |
apply_static |
The node task and the client-address task |
NodeManager.globals |
parking_lot::Mutex<Arc<Globals>> |
apply_static |
lower_off_runtime |
NodeManager.rules |
RuleManager, holding the RuleManager lock below |
Built once in NodeManager::new |
The node task |
NodeManager.supervisor |
OnceLock<Supervisor<Uid>> |
try_bootstrap, once |
The node task, including spawn_client_ips, which subscribes to the flow events before it spawns the client-address task |
NodeManager.applied |
parking_lot::Mutex<Option<Applied>> |
try_bootstrap, reconcile |
lower_off_runtime, reconcile |
NodeManager.collect_ips |
AtomicBool, Relaxed |
new, apply_static |
The client-address task, take_client_ips |
NodeManager.client_ips |
parking_lot::Mutex<HashSet<(i64, IpAddr)>> |
The client-address task, take_client_ips, apply_static |
take_client_ips |
NodeManager.rebuild_pending |
AtomicBool, Relaxed |
poll_cycle(true), StaticUpdate::Globals, reconcile, try_bootstrap |
reconcile |
NodeManager.cur |
tokio::sync::Mutex<Cur> |
set_cur |
poll_cycle, StaticUpdate::Globals |
RuleManager.rules |
parking_lot::Mutex<Arc<[DetectRule]>> |
refresh_rules → update |
lower_off_runtime → rules() |
EtagCache.map |
parking_lot::Mutex<HashMap<&'static str, String>> |
Each panel GET |
Each panel GET; forget_etags clears it |
UniProxy Client.routes |
parking_lot::Mutex<Vec<RouteRule>> |
node_info, inherit_routes |
node_rule, and inherit_routes on the old client |
DUAL_STACK inside dual_stack |
function-local static OnceLock<bool> |
The first call, from the first bind_host of 0.0.0.0 |
Every later call |
Every NodeManager method runs on the node task, except the loop spawn_client_ips starts. That client-address task holds the flow-event receiver it was handed and an Arc of the manager, and, where collected, records each user’s client address into NodeManager.client_ips. A parking_lot guard is not Send (no crate in katana’s dependency graph enables parking_lot’s send_guard feature), and NodeManager::run goes to tokio::spawn, which needs a Send future, so holding a guard across an .await does not compile. The code keeps each guard inside one expression or a short block.
Module map
Section titled “Module map”Sizes are line counts at v6.1.0, comments included. The source files add up to 4,696 lines and the tests to 7,127.
| File | Lines | Responsibility |
|---|---|---|
src/main.rs |
55 | The musl build’s global allocator, Args and the #[tokio::main] main, which calls runtime::init_tracing, then takes the --test branch or runs runtime::run; compiles tests/unit/e2e.rs into test builds as mod e2e |
src/runtime.rs |
419 | The process root: run, NodeId, identity, display_id, shared_wireguard, warn_shared_wireguard, NodeHandle, spawn_node, build_node, check_node, spawn_built, apply_reload, setup_watcher, test_config, init_tracing and LogReload, wait_for_shutdown |
src/config.rs |
443 | The TOML schema, with deny_unknown_fields on every deserialized struct; Globals and Config::globals; ApiConfig::timeout_secs; load and parse_bytes |
src/blocking.rs |
29 | off_runtime and drop_off_runtime: work that grows with a node’s users, kept off the runtime’s workers |
src/api/mod.rs |
332 | Panel-neutral models (NodeType, RouteRule, Node, the type alias of the contract’s NodeConfig, UserInfo, UserTraffic, NodeReport, DetectRule), MBPS_TO_BPS and mbps_to_bps, traffic_email, EtagCache, error_for_status, build_http_client and http_client_builder, read_local_rules, panel_node_type, PanelClient |
src/api/newv2board.rs |
720 | The UniProxy client and its refusal of an sss node, node_type_param, the conversion of a config answer into the contract’s node (parse_node_config, json_error, check_protocol, v2ray, shadowsocks, proxy, tls, transport with Network and plain_tcp_header, reality), detect_rules, the lenient rate readers, the response structs |
src/api/helium.rs |
304 | The helium client of Helium’s node API v2: its endpoints, refuse_local_protocol, the config answer read as the contract’s node and handed on untouched, the users mapping (parse_users, user_infos), report_body, and parse |
src/api/hysteria.rs |
150 | A Hysteria 2 node in the contract’s terms where no panel describes it in full: local, the node [node.hysteria].port describes alone; uniproxy, a UniProxy node’s obfuscation and rates completed with [node.hysteria]’s UDP relay, masquerade and rate overrides; obfs, the Salamander rules both share; the contract’s validate() runs on the result |
src/api/embedded_cert.rs |
72 | node_client_identity, the panel clients’ client certificate |
src/manager/mod.rs |
23 | StaticUpdate; re-exports NodeManager |
src/manager/node.rs |
793 | NodeManager: bootstrap with backoff, the steady-state loop, poll_cycle, lower_off_runtime, reconcile with disruptive_part, apply_static, the client-address task (spawn_client_ips), refresh_rules, report with take_traffic and take_client_ips, log_listening, log_clock_check, log_guard |
src/lower/mod.rs |
221 | Uid, USER_SET, node_spec, shared_spec, policies, lower_users and its credential identity, test_spec |
src/lower/inbound.rs |
654 | lower_inbound, real_ip, websocket, handoff, handoff_file, group_id, find_gid, stream (with Under and read_cert_key), reality_spec, lower_stream_protocol, lower_sss, lower_shadowsocks, lower_hysteria with masquerade_spec and congestion, credentials, inbound_tag, bind_host, dual_stack |
src/lower/outbound.rs |
330 | lower_outbounds and lower_outbound per protocol, lower_wireguard, the address-family parsers, lower_dns |
src/lower/route.rs |
56 | lower_route: [node.route] into a RouteSpec, with each geo file stamped by RouteFile::stat |
src/rule.rs |
95 | AUDIT_TAG_PREFIX, audit_tag, audit_routes, and RuleManager, the node’s rule set |
The lowering is described on two pages: Lowering a node into a spec covers src/lower/mod.rs and src/lower/route.rs, and Inbounds and outbounds covers src/lower/inbound.rs and src/lower/outbound.rs. src/rule.rs is on Destination audit.
Key types
Section titled “Key types”StaticUpdate and Globals
Section titled “StaticUpdate and Globals”pub enum StaticUpdate { /// This node's static `[[node]]` config changed (same panel identity). Config(Box<NodeConfig>), /// The process-wide `[[outbound]]` entries or `[dns]` changed. Globals(Arc<Globals>),}#[derive(Clone, PartialEq, Default)]pub struct Globals { pub outbounds: Vec<OutboundConfig>, pub dns: DnsConfig,}
impl Config { pub fn globals(&self) -> Globals;}StaticUpdate is how an edit of the config file reaches a running node, as opposed to the panel poll. The runtime resolves identity changes itself by removing and adding the node, so a node never receives a Config with another panel identity. Globals is the part of the config that every node lowers into its own spec; there is no process-wide outbound pool.
The runtime’s handles
Section titled “The runtime’s handles”pub type LogReload = Box<dyn Fn(&str) + Send + Sync>;
/// A `[[node]]` identity for reload matching: the panel node an entry serves,/// `(panel_type, api.host, node_id, api.key, panel node type)`.type NodeId = (String, String, u32, String, String);
struct NodeHandle { id: NodeId, cfg: NodeConfig, task: JoinHandle<()>, static_tx: mpsc::Sender<StaticUpdate>, shutdown: CancellationToken,}
pub async fn run(config_path: PathBuf, reload: LogReload) -> ExitCode;pub async fn test_config(path: &Path) -> anyhow::Result<()>;pub fn init_tracing(config_path: &Path) -> LogReload;identity fills a NodeId with panel_type lower-cased, api.host, api.node_id, api.key and api::panel_node_type. That last field is the UniProxy node_type parameter (node_type_param, above), because UniProxy finds a node by its id and that type; it is empty on helium. A change to any field respawns the node. display_id renders the identity for logs as <panel>@<host>#<node_id>, followed by /<node_type> when that field is set, and never shows the key; for example newv2board@https://panel.example.com#3/v2ray.
NodeManager
Section titled “NodeManager”impl NodeManager { pub fn new(api: PanelClient, cfg: NodeConfig, globals: Arc<Globals>) -> Arc<Self>;
pub async fn run( self: Arc<Self>, shutdown: CancellationToken, mut static_rx: mpsc::Receiver<StaticUpdate>, );}
struct Cur { node: Option<Node>, users: Arc<[UserInfo]>,}
struct Applied { node: Node, spec: Arc<Spec<Uid>>,}new cannot fail: build_node has already built the client and checked the node, and nothing is bound until the bootstrap. run is the node’s whole life: bootstrap, then the client-address task and the steady-state loop, then shutdown and the final reports. The users and the spec are shared rather than copied, because a node can list tens of thousands of users. Cur is the panel’s last answer, which reconcile stores before it lowers. Applied is what the supervisor runs: the spec, and the node it was lowered from, whose disruptive part (disruptive_part) the next reconcile compares with the new node’s. Node manager lists every field and method.
Uid and the node’s spec
Section titled “Uid and the node’s spec”#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]pub struct Uid(pub i64);
impl UserId for Uid { fn name(&self) -> UserName { UserName::Username(self.0.to_string().into()) }}
pub const USER_SET: &str = "users";
pub fn node_spec( cfg: &NodeConfig, globals: &Globals, node: &Node, users: &[UserInfo], audit: &[DetectRule],) -> io::Result<Spec<Uid>>;
pub fn test_spec(cfg: &NodeConfig, globals: &Globals) -> io::Result<Spec<Uid>>;The supervisor keys katana’s users by the panel’s numeric user id, so each UsageDelta<Uid> names its uid directly and becomes a row of the report without a lookup. The name every flow of theirs carries is that id in decimal, which is how a client address read off a flow finds its way back to the user.
What node_spec puts into each field of the spec, in summary:
| Spec field | katana’s value |
|---|---|
inbounds |
The node’s inbound from lower_inbound, when at least one user is admitted: tag <Type>_<listen_ip>_<port>; BindSpec::Tcp, or BindSpec::Udp for Hysteria 2, on bind_host(listen_ip) and the node’s port; sniff = !disable_sniffing; users = Some("users"); user_removal = None; proxy_protocol on a TCP bind; handoff, <handoff_dir>/<port>.sock or, on one address, <handoff_dir>/<ip>-<port>.sock, on a TCP bind when handoff_dir is set; real_ip on a WebSocket node with real_ip_header set |
outbounds |
direct, block, freedom, blackhole, every [[outbound]], then one blackhole audit#<id> per audit rule id |
balancers |
Empty |
route |
The audit routes first, then the [node.route] rules; the default is direct unless route.default names another outbound; each geo file by its path as written, stamped with the file at that path when the route is lowered (RouteFile::stat) |
dns |
DnsSpec::Single of the backend [dns] describes |
user_sets |
One UserSet tagged users, keyed by Uid, each user’s speed_limit from their UserInfo and, under enable_device_limit, their device_limit |
policies |
ip_ban under enable_device_limit, and carrier_max_failures, from [node.controller]; the removal and drain defaults |
The listener is built from listen_ip: bind_host binds 0.0.0.0 as :: where the host’s IPv6 sockets also take IPv4, and any other address as written. dual_stack asks that of an unbound socket once per process; where IPv6 sockets take IPv6 alone it logs IPv6 sockets here take IPv6 alone (net.ipv6.bindv6only), so listen_ip 0.0.0.0 serves IPv4 only at WARN. Lowering a node into a spec has the field-by-field detail, users, credentials, the speed limit and the route; Inbounds and outbounds covers the listener and the outbounds.
Data flow
Section titled “Data flow”From a panel answer to a usage report
Section titled “From a panel answer to a usage report”flowchart LR panel["Panel"] client["PanelClient"] answer["the node, users, audit rules"] lower["lower::node_spec"] spec["Spec of Uid"] sup["the node's Supervisor"] ledger["usage ledger"] events["flow events"] ips["client-address task"] report["report: NodeReport"] panel -- "node_info, user_list, node_rule" --> client client --> answer answer --> lower lower --> spec spec -- "start, then apply_with" --> sup sup --> ledger sup --> events events -- "FlowEvent::Opened, where collected" --> ips ledger -- "take_usage" --> report ips -- "take_client_ips, helium" --> report report -- "PanelClient::report" --> panel
- Fetch.
node_infoasks the panel, except for a Hysteria 2 node with a non-zero[node.hysteria].port(never a helium node, whose client refuses that key):api::hysteria::localthen builds the node from the config and the panel is not asked. Either way the node arrives as the contract’sNodeConfig: helium’s answer as it is, a UniProxy answer converted by the UniProxy client, which refuses by name what katana cannot serve as it reads it.user_listfollows, thenrefresh_rulesunlesscontroller.disable_get_ruleis set;RuleManager::updatestores a new rule set only when the rule ids or patterns differ. The panel’s speed limits arrive inUserInfo.speed_limit, already in bytes per second: converted from Mbps (MBPS_TO_BPS= 125,000) for UniProxy, as sent for helium. A positiveapi.speed_limitoverrides the panel’s values inside the clients, so a user’s limit is the one in theirUserInfo; the node has no limit of its own. A user’s device limit arrives inUserInfo.device_limit; helium’s users answer states one speed limit and one device limit, and its client copies both onto everyUserInfo. A Hysteria 2 node’s rates, UDP relay and masquerade are fields of the node: from helium’s answer, or, on newV2board, the panel’s obfuscation and rates completed with[node.hysteria]’s UDP relay, masquerade and rate overrides. - Lower.
NodeManager::lower_off_runtimeclones the currentcfgandglobalsand callslower::node_specwith the rules in force, on the blocking pool. A setting of this host’s that the kernel cannot honour, such as an ACME cert mode orcert.reject_unknown_sni, is refused here by name, asnode requests kernel-unsupported feature: <feature>. A user whose credential cannot be lowered, a uid listed twice, and a user presenting an earlier user’s credential are skipped atWARNwithskipping user <uid>: <reason>,skipping user <uid>: listed twiceandskipping user <uid>: shares its credential with user <first uid>. Each names the uid, never the credential. - Apply. The bootstrap starts the supervisor with
Supervisor::startand logsnode <node_id>: listening on <address>, and how failed authentications are handled (log_guard). An IP host is printed as a socket address, so a0.0.0.0widened to::shows as[::]:<port>; any other host shows as<host>:<port>. Every later cycle runsreconcile, which skips the apply when the spec equals the applied one and no drop is due, and otherwise callsapply_with(spec, ApplyOptions { allow_disruptive: true }). When a drop is due (see below), it callsclose(Selector::All)after the apply commits. - Serve. The supervisor accepts, admits each flow’s principal on its session, routes the flow on the current plane, paces it by its user’s limit, and counts its session’s wire bytes into the user’s account.
- Audit and client addresses. A flow whose domain an audit rule matches is routed to that rule’s
audit#<id>blackhole. No panel is told about it: katana reports no audit hits. For every flow it opens, the tracker publishesFlowEvent::Opened; where the node collects client addresses, the client-address task keeps the flow’s source address under the uid parsed from the flow’s user label. - Report.
reportcallstake_traffic, which callsSupervisor::take_usage, which returns at most oneUsageDelta<Uid>per user who moved bytes, and turns each delta into aUserTraffic { uid, upload, download }row; for helium underenable_device_limit,take_client_ipsadds each user’s client addresses. The rows go out as oneNodeReportwith a new id throughPanelClient::report; a failed report is logged atWARNasnode <node_id>: report <report id>: <error>. Withcontroller.disable_upload_trafficset it takes the usage and sends no traffic. Traffic accounting covers the cycle, and Usage covers what is counted.
One poll cycle
Section titled “One poll cycle”serve drives the poll with a tokio::time::interval of update_periodic seconds (at least 1) and runs poll_cycle(false) on each tick. The interval’s first tick is consumed, so the first poll comes one full period after the bootstrap.
sequenceDiagram participant N as NodeManager participant P as PanelClient participant L as lower participant S as Supervisor N->>P: node_info, or the local Hysteria 2 node N->>P: user_list N->>P: node_rule, unless disable_get_rule N->>L: node_spec on the blocking pool, with cfg, globals, node, users, rules L-->>N: Spec of Uid, or Unchanged N->>S: apply_with, allow_disruptive N->>S: close(Selector::All), only when a drop is due N->>S: take_usage N->>P: report
A 304 from the panel means that the last answer, kept in cur, still holds. A failed request is logged at WARN as node <node_id>: node_info: <error> or node <node_id>: user_list: <error>, and a failed rule refresh as node <node_id>: node_rule: <error>. A UniProxy answer katana cannot serve is a failed node_info too, with the reason in the line, for example node 1: node_info: parse UniProxy config response: node requests kernel-unsupported feature: tcp header type "http"; the node keeps serving the node it has. Node manager covers every branch.
What closes every session on a node
Section titled “What closes every session on a node”reconcile decides whether a drop is due before it applies:
let drop_all = self.rebuild_pending.load(Ordering::Relaxed) || disruptive_part(&node) != disruptive_part(&applied.node);disruptive_part is the node with what the supervisor applies to new connections alone taken out: an AnyTLS node’s padding scheme, and a Hysteria 2 node’s up_mbps, down_mbps, ignore_client_bandwidth and UDP idle timeout. Everything else in the node is compared.
Three kinds of change make a drop due, and the node then calls close(Selector::All) once the apply commits:
- the panel changes any other part of the node: its protocol, port, transport, security, a REALITY key, shortId or cover site, a Shadowsocks cipher or key, the VLESS flow, sss’s chains or datagram limit, or a Hysteria 2 node’s obfuscation, masquerade or whether it relays UDP;
- a config edit to a local setting the listener or its routes are built from, such as
[node.route],[node.controller.cert],controller.disable_sniffingor[node.hysteria]:apply_staticrunspoll_cycle(true)at once, which setsrebuild_pending; - a change to
[[outbound]]or[dns]: every node receivesStaticUpdate::Globals, setsrebuild_pendingand reconciles its last answer at once, so every session on every node is closed.
Other changes are applied without that close:
- A user added, or a user’s speed limit or device limit changed: every session stays, and the supervisor sets the new limits when the apply commits. Users are not part of the node.
- A Hysteria 2 node’s rates or UDP idle timeout: the handler is swapped, and the connections that arrive afterwards get the new values.
- An AnyTLS node’s padding scheme: the handler is swapped, and the sessions that start afterwards get the new scheme.
disable_vmess_clock_checkor the ban and carrier settings: a poll at once, whose apply swaps the handler or the policies and keeps every session.real_ip_headerorreal_ip_from: a poll at once, whose apply swaps a WebSocket node’s handler and keeps every session.handoff_dirorhandoff_group: a poll at once, whose apply binds, moves or removes the node’s handoff socket and keeps every session, handed-over ones included.- A user removed, or a user’s credential changed: that user’s sessions go to the inbound’s removal policy, which katana leaves at the default,
Close. The other users keep theirs. - New audit rules: new audit routes and outbounds.
- New contents in the certificate or key file, which every lowering reads: the spec differs and is applied.
- A GeoIP or GeoSite file replaced at the same path: each lowering stamps the file it finds there, so the next poll’s spec differs and is applied.
- Any other
[node.api]field,enable_mtls, or the letter case ofpanel_type: a newPanelClientand an immediatepoll_cycle(false). A[node.hysteria]edit gets a newPanelClienttoo, and its poll drops every session, as above.
A Hysteria 2 obfuscation change is a Disrupt step in the supervisor’s plan; katana sets allow_disruptive, so the change is applied rather than refused. Node manager has the effect of each change, and Reconcile what an apply keeps.
Compared with etemenanki-app
Section titled “Compared with etemenanki-app”Both programs lower their input into a spec and run it on the supervisor. They differ in where the input comes from and how changes are applied.
| etemenanki-app | katana | |
|---|---|---|
| Input | The TOML file and the subscribe file it names | The panel’s node info, user list and audit rules, plus the [[node]], [[outbound]] and [dns] tables of the TOML file |
| Lowering | app/src/lower.rs, into Spec<UserName> |
src/lower/, into Spec<Uid> |
| Supervisors | One per process | One per [[node]] |
| Inbounds | Any number | One per node |
| Inbound protocols | SOCKS, HTTP, Trojan, AnyTLS, VLESS, VMess, sss, Shadowsocks, Shadowsocks 2022, Hysteria 2, TUN | VMess, VLESS, Trojan, Shadowsocks, Shadowsocks 2022, Hysteria 2, AnyTLS, SOCKS and HTTP over TLS, sss |
| Users | Written under each inbound, keyed by name | The panel’s list, keyed by uid, in one set tagged users |
| Speed and device limits | None: every user is lowered with speed_limit: None and device_limit: None |
Each user’s own speed limit (the panel’s, or [node.api] speed_limit), and the panel’s device limit under enable_device_limit |
| Applying a change | apply(spec) on each reload; a disruptive change is refused with a restart hint |
apply_with(spec, ApplyOptions { allow_disruptive: true }), then close(Selector::All) when a drop is due |
| What triggers a change | Its file watcher, and the REST API (route edits and reload) | The panel poll every update_periodic seconds, and edits of the config file |
| Usage | Not taken | take_usage on every poll, reported to the panel |
| Where lowering runs | On the calling task | On the blocking pool |
| The supervisor’s tracker | Read by the REST API | Its flow events read by the client-address task |
--test |
app/src/instance.rs → check |
runtime::test_config → check_node per node |
| Shutdown grace | 5 s (SHUTDOWN_GRACE) |
0 |
| REST API | [api] |
None |
The app’s side is on App configuration, App reload and REST API, and the path of one connection through the supervisor is on Connection lifecycle.
Where the 3.x modules went
Section titled “Where the 3.x modules went”katana 3.x ran its own serve loop, admission, router, metering and outbound pool on top of the kernel. 4.0 deleted them and moved onto the supervisor. The table names each deleted module, what it did, and where the concern lives at 6.1.0.
| 3.x module | What it did | Where it lives now | Detail |
|---|---|---|---|
src/serve.rs |
Scope, accept_loop, serve_socket, serve_stream, drive, run_hysteria: the accept loops and each connection’s runtime |
supervisor/src/serve.rs → run_stream_inbound, drive, run_hysteria_inbound, on the supervisor’s TaskTracker |
Serving |
src/manager/transport.rs |
TransportManager: one bound listener generation and its teardown |
supervisor/src/system/listener.rs: listeners keyed by BindSpec, kept across applies while the bind is unchanged. katana keeps one Supervisor per node in NodeManager.supervisor |
Serving, Reconcile |
src/manager/proxy.rs |
ProxyManager and Tables: swappable user tables and the pre-auth limit |
supervisor/src/build/inbound.rs → build_handler and UserTable; supervisor/src/system/listener.rs → prepare_swap, user_target, store_users; the per-inbound limits of the accept loop in supervisor/src/serve.rs |
Serving, Users and sessions |
src/connector.rs |
KatanaConnector, Admission, leases, Dispatcher, FanOut: admit, route, audit, dial and meter each flow |
supervisor/src/connector.rs → AppConnector (Session::admit, the current Plane, Tracker::meter_stream); supervisor/src/entity/session.rs → Sessions::revoke for removed users; supervisor/src/topology/flow.rs → Principal; supervisor/src/topology/outbound/udp_fanout.rs → FanOutLink for UDP. The audit is a route (katana src/rule.rs) |
Users and sessions, Routing plane, Destination audit |
src/router.rs |
route_target and build_router over the environment route model |
katana src/lower/route.rs → lower_route writes a RouteSpec; the supervisor compiles it (supervisor/src/topology/router.rs) into the plane (supervisor/src/topology/plane.rs) |
Lowering a node into a spec, Routing plane |
src/meter.rs |
Gate and Metered: per-flow counting and the speed-limit wait |
supervisor/src/track/metered.rs → Metered and supervisor/src/track/pace.rs → Pacer |
Tracking |
src/traffic.rs |
TokenBucket, UserCounter, NodeTraffic, AuthKey, UserTag, determine_rate |
determine_rate lived on in katana src/lower/mod.rs until 6.1.0 removed it with the node-level limit, so a user’s rate is their own; the token bucket as the supervisor’s Pacer; the counters as supervisor/src/entity/usage.rs → Wire and Ledger, read with Supervisor::take_usage; AuthKey and UserTag as katana’s Uid and the supervisor’s UserKey and Principal |
Usage, Tracking, Traffic accounting |
src/inbound.rs |
build_transport, build_protocol, the Hysteria 2 builders, validate_hysteria |
katana src/lower/inbound.rs → lower_inbound, lower_hysteria, credentials; the supervisor builds the handler from the spec. validate_hysteria became lower::test_spec, checked with etemenanki_supervisor::check |
Inbounds and outbounds, Validation |
src/outbound/mod.rs, freedom.rs, proxy.rs |
The outbound pool: direct TCP and UDP, proxy clients, WireGuard, the shared resolver | katana src/lower/outbound.rs → lower_outbounds, lower_dns; supervisor/src/build/outbound.rs and supervisor/src/topology/outbound/ |
Inbounds and outbounds, Outbounds, DNS |
src/manager/mod.rs helpers |
user_key, user_tag, node_tag, build_user_entries, user_set_differs |
lower::Uid, lower::inbound::credentials, lower::inbound::inbound_tag, lower::node_spec. Comparing the lowered spec with the applied one replaces user_set_differs |
Lowering a node into a spec, Node manager |
NodeType::keys_by_email in src/api/mod.rs |
Chose between UUID and name keys per protocol | Removed: every user is keyed by Uid |
Panel clients |
RuleManager::detect in src/rule.rs |
Checked each flow’s destination against the node’s rules | rule::audit_routes makes routes to one audit#<id> blackhole per rule id |
Destination audit |
The reconcile ladder in src/manager/node.rs (bring_up, tear_down, rebuild, rebuild_router, apply_route_change) |
Chose between a table swap and a listener rebuild | Supervisor::apply_with plans, prepares and commits each spec; katana adds close(Selector::All) when a drop is due |
Reconcile, Node manager |
Operators upgrading a deployment from 3.x will find the steps in Upgrading to katana 4.
Invariants
Section titled “Invariants”| Invariant | Mechanism | Pinned by |
|---|---|---|
| Every node runs its own supervisor; nodes share configuration values, not runtime state | NodeManager.supervisor; node_spec lowers the Globals into each node’s spec |
a_wireguard_outbound_several_nodes_route_to_is_reported (tests/unit/runtime.rs), for the consequence the runtime warns about |
| A spawned node’s bootstrap is retried with backoff until it succeeds, and the node still stops when cancelled | bootstrap backs off from 1 s to 60 s, capped by the poll period, and races every attempt and wait against the node token |
a_node_comes_up_once_the_panel_answers, a_node_whose_port_is_taken_comes_up_once_it_is_free, a_node_that_never_bootstraps_still_stops (tests/unit/e2e.rs) |
Under enable_device_limit, a user’s clients come from no more addresses than their device limit, and an address that keeps failing to authenticate is banned |
lower_users, lower::policies; the supervisor’s sessions and guard |
a_users_clients_come_from_no_more_ips_than_their_device_limit, an_ip_failing_to_authenticate_is_banned_and_others_are_served |
| Lowering never holds a runtime worker | lower_off_runtime |
lowering_leaves_the_runtime_worker_free (tests/unit/manager/node.rs) |
| A user-set change keeps the sessions of users who stay | The supervisor swaps the user table and keeps the sessions of users the new set still admits | unchanged_user_survives_user_refresh, repeated_user_refreshes_never_disturb_a_live_connection, a_retired_user_stops_while_the_rest_keep_their_connections |
| In the end-to-end tests, a user the panel removes can no longer relay over the connection they already had open, on a VMess node and on a Hysteria 2 node, while the users who stay keep theirs | The removal policy, Close by default |
Phase 3 of unchanged_user_survives_user_refresh; a_retired_user_stops_while_the_rest_keep_their_connections |
| A route edit closes every session on the node | apply_static runs poll_cycle(true); reconcile calls close(Selector::All) after the apply |
route_change_drops_connections |
| A protocol change closes the sessions of the old protocol | A panel answer that changes the protocol, or any other part of the node but what applies to new connections alone, changes disruptive_part; on newV2board an api.enable_vless edit on a V2ray node changes the node identity, so the node is respawned |
only_a_disruptive_change_drops_every_connection (tests/unit/manager/node.rs); a_newv2board_type_edit_respawns_the_node: the respawned node no longer serves VLESS (tests/unit/runtime.rs) |
| An edit that changes only the panel client keeps every session | apply_static swaps the client and runs poll_cycle(false) |
a_client_edit_takes_effect_without_dropping_connections |
An enable_mtls edit gives the node a new panel client, and an edit to nothing the client is built from keeps the old one |
apply_static compares panel_type, api, enable_mtls and hysteria |
a_reload_of_enable_mtls_alone_rebuilds_the_client (tests/unit/manager/node.rs) |
| A reload with a node that does not build changes nothing | apply_reload checks every added or changed node before it touches a running one |
a_reload_with_a_node_that_does_not_build_changes_nothing |
A helium node’s protocol comes from its panel alone: a local key that would describe it stops the build, --test and reload |
helium::Client::new → refuse_local_protocol, which every build, check and reload runs through PanelClient::new |
local_keys_the_panel_describes_are_refused (tests/unit/api/helium.rs) |
A node that names SSPanel is refused by name at start and by --test, and a reload that moves a running node to SSPanel changes nothing |
PanelClient::new, which build_node, test_config and the reload check all run |
an_sspanel_node_is_refused_at_test_and_at_start, a_reload_to_sspanel_changes_nothing (tests/unit/runtime.rs) |
A node is the panel node it serves; enable_mtls, on unless turned off, is not part of that |
NodeId; default_enable_mtls |
a_newv2board_node_is_also_the_type_it_asks_for, a_newv2board_type_edit_respawns_the_node, enable_mtls_is_on_unless_turned_off |
| A node’s name in a log never shows the panel key | display_id leaves out api.key |
a_node_is_logged_by_its_panel_node_not_its_key; a_wireguard_outbound_several_nodes_route_to_is_reported asserts that no node name contains the key |
| An outbound’s UUID is named, not echoed, in its error | require_uuid names the outbound only |
a_malformed_uuid_is_refused_without_echoing_it (tests/unit/lower/outbound.rs) |
| Traffic is reported under the authenticated panel user’s uid, through a proxy outbound and on Hysteria 2 too | Uid in the spec; take_usage per user |
vmess_traffic_is_metered_and_reported, proxy_outbound_relays_and_meters, a_hysteria_node_relays_and_meters; every cell of tests/integration/xray_interop.rs asserts a report for uid 1001 |
| A user’s speed limit paces their traffic | UserInfo.speed_limit into UserSpec.speed_limit |
a_users_speed_limit_paces_their_traffic; a_user_is_held_to_their_speed_limit (tests/unit/lower/spec.rs) |
| Audit rules route first, each rule id to its own blackhole | audit_routes spliced in at index 0 |
audit_rules_route_first_to_one_blackhole_per_rule_id, an_audit_tag_is_reserved (tests/unit/lower/spec.rs) |
| One bad user row does not refuse the node | lower_users skips and logs it |
users_without_a_usable_credential_are_skipped, a_shared_credential_admits_only_the_first_user |
listen_ip = "0.0.0.0" serves both address families where the host allows |
bind_host, dual_stack |
a_node_on_0_0_0_0_serves_ipv4_and_ipv6_clients, a_hysteria_node_on_0_0_0_0_serves_ipv4_and_ipv6_clients |
disable_sniffing controls sniffing |
sniff = !disable_sniffing |
a_sniffed_host_reaches_a_domain_rule, disable_sniffing_stops_the_domain_rule_matching (tests/integration/sniff.rs) |
No parking_lot guard of a node is held across an .await |
The guards are not Send, and the node future goes to tokio::spawn |
The compiler |
Failure paths and cancellation
Section titled “Failure paths and cancellation”Startup and --test
Section titled “Startup and --test”run logs under the target katana::runtime. The texts below were captured from the pinned binary with placeholder configs.
| Condition | run logs |
--test prints on standard error |
Exit code |
|---|---|---|---|
| The config file is missing | failed to load config: No such file or directory (os error 2) |
configuration error: No such file or directory (os error 2) |
1 |
No [[node]] |
config defines no [[node]] entries |
configuration error: config defines no [[node]] entries |
1 |
A node that does not build, for example with an unknown panel_type |
node 1: unknown panel_type "foo", then no nodes could be started when no other node starts |
configuration error: node 1: unknown panel_type "foo" |
1 |
A node with panel_type = "SSpanel" |
node 1: panel_type "SSpanel" is not supported: katana serves the NewV2board and Helium panels, then no nodes could be started when no other node starts |
configuration error: node 1: panel_type "SSpanel" is not supported: katana serves the NewV2board and Helium panels |
1 |
A [node.api] key katana 6 removed, vless_flow or disable_custom_config |
failed to load config: config parse error: TOML parse error at line <n>, column <m>, the first line of an unknown-key error |
configuration error: config parse error: TOML parse error at line <n>, column <m> |
1 |
A helium node that sets node_type |
node 1: [node.api] node_type is set, but a helium node's protocol is described by the panel; remove it (of [node.hysteria], only congestion is this host's to choose) |
The same text after configuration error: |
1 |
| Everything checks out | Nothing | Configuration OK, on standard output |
0 |
At startup a node that fails is skipped and the others start; the process exits only when none starts. --test stops at the first node that fails. Both prefix a node’s error with node <api.node_id>: . The watcher’s setup failure is not fatal: config watcher disabled (no live reload): <error>. Process runtime and reload lists more of these texts, and Error messages lists the texts the lowering and the supervisor produce.
Bootstrap
Section titled “Bootstrap”bootstrap runs one try_bootstrap per attempt. Each attempt first calls forget_etags, so it asks the panel afresh, then reads the node info and the user list, refreshes the rules unless disable_get_rule is set, lowers the spec on the blocking pool and calls Supervisor::start. A failed attempt is logged at ERROR as node <node_id>: <reason>; retrying in <n>s. The reason names the step that failed, for example node_info failed: <error>, user_list failed: <error>, or initial start failed: <error> when the spec did not lower or Supervisor::start refused it, for example because the port is still taken. A UniProxy answer katana cannot serve fails at the first step, with its reason: node 1: node_info failed: parse UniProxy config response: server_port 70000 is not a port (1 to 65535); retrying in 1s.
The wait is BOOTSTRAP_RETRY_MIN (1 s) after the first failure and doubles after each further one up to BOOTSTRAP_RETRY_MAX (60 s); each wait is capped at the poll period. Static updates are applied during the wait. Before the node is up they only store what they carry, and a StaticUpdate::Config ends the wait at once, because the edit may be the fix. One timer serves each wait, so updates arriving meanwhile cannot push the retry back. Node manager lists every bootstrap reason and the steady-state failures.
Shutdown
Section titled “Shutdown”sequenceDiagram participant R as runtime::run participant N as NodeManager::run participant A as client-address task participant S as Supervisor participant P as Panel R->>R: the signal cancels root, run logs shutting down R->>N: the node's child token fires N->>N: serve returns N->>A: awaits the client-address task, which ended on the same token N->>S: shutdown(Duration::ZERO) S-->>N: listeners stopped, every session closed and gone, last sample taken N->>S: take_usage N->>P: the final report, when there is something to report R->>N: awaits the JoinHandle
Supervisor::shutdown(Duration::ZERO) sends the actor a shutdown command. The actor stops every listener, cancels every balancer probe (katana lowers no balancers), closes its TaskTracker, gives the connections no grace, cancels the supervisor’s root token so that every session ends, waits until every task on the tracker is gone, and then stops the sampler, which publishes once more. The node’s comment gives the reason for this order: once the supervisor is down every session has ended, and an ended session’s usage is counted in full, so this report is the node’s final one, and it is sent rather than discarding up to one poll of traffic. A node cancelled before its bootstrap succeeded has no supervisor: it skips the shutdown, and report returns at once. When run has awaited every node task, it returns exit code 0.
Cancellation
Section titled “Cancellation”Cancellation travels downwards: the root token, then each node’s child token. The node task selects on its token in bootstrap (first, with biased), in the steady-state loop, and in the client-address task. Every connection belongs to the supervisor, whose sessions hang off the supervisor’s own root token; katana ends them only through close and shutdown. The supervisor describes what happens to a supervisor dropped without a shutdown.
Limits
Section titled “Limits”| Constant or setting | Value | Defined in | What it bounds |
|---|---|---|---|
BOOTSTRAP_RETRY_MIN |
1 s | src/manager/node.rs |
The wait after a first failed bootstrap attempt |
BOOTSTRAP_RETRY_MAX |
60 s | src/manager/node.rs |
The longest wait between attempts; a shorter poll period caps it |
| Poll period | update_periodic seconds, default 60, at least 1 |
src/config.rs, src/manager/node.rs → poll_period |
The period of the poll interval, and the cap on a bootstrap wait |
| Static update channel | 16 | src/runtime.rs → spawn_built |
StaticUpdates queued per node; apply_reload waits while one is full |
| Panel request timeout | api.timeout seconds, 5 when 0 |
src/config.rs → timeout_secs |
Every panel request |
MBPS_TO_BPS |
125,000 bytes/s per Mbps | src/api/mod.rs |
The speed-limit conversion |
Hysteria 2 max_connections |
DEFAULT_MAX_CONNECTIONS = 262,144 |
protocols/src/hysteria/server/config.rs |
QUIC connections per Hysteria 2 node; katana always lowers the default |
Hysteria 2 max_circuits |
DEFAULT_MAX_CIRCUITS = 4,194,304 |
protocols/src/hysteria/server/config.rs |
Live circuits per Hysteria 2 node; katana always lowers the default |
Hysteria 2 udp_idle_timeout |
60 s when UDP is on and it is unset; 2 to 600 s | src/api/hysteria.rs → udp for [node.hysteria] (helium’s node config has its own default, also 60 s, and the same range) |
An idle UDP association |
| Supervisor command channel | 16 | supervisor/src/supervisor.rs |
Commands queued for a node’s supervisor |
DEFAULT_SAMPLE_INTERVAL |
1 s | supervisor/src/track/sampler.rs |
The sampler tick, and so how far a live session’s bytes may lag behind take_usage |
| Shutdown grace | 0 | src/manager/node.rs → run |
Sessions get no time to finish when a node stops |
Each node’s spec has one inbound, so on a stream node the per-inbound limits of the supervisor’s accept loop, MAX_HANDSHAKES_PER_INBOUND and MAX_LIVE_CONNECTIONS_PER_INBOUND in supervisor/src/serve.rs, apply per node; a Hysteria 2 node is bounded by the two Hysteria 2 rows above. Serving gives their values, and Limits, timeouts and memory collects the limits of the whole stack.
Numbers are line counts.
Directorytests
- integration.rs the one integration test target (10)
Directoryintegration
- xray_interop.rs the real binary against Xray clients (276)
- sniff.rs disable_sniffing end to end (131)
- hysteria_interop.rs the real binary against the Hysteria client (114)
Directorysupport
- mod.rs FakePanel, echo server, certificates, reference client builds (554)
Directoryunit
- e2e.rs NodeManager against fake UniProxy and helium panels (2,091)
- runtime.rs node identity, the parse of the real-IP, handoff and enable_mtls keys, the SSPanel refusal, and apply_reload against running nodes (487)
- rule.rs (18)
Directorymanager
- node.rs lower_off_runtime, reloads of the real-IP, handoff and enable_mtls keys, and which node changes drop every connection (359)
Directorylower
- spec.rs node_spec, users, rates, device limits, policies, audit routes, the node check, the new node kinds, a Hysteria 2 node’s UDP relay and masquerade (454)
- inbound.rs (880)
- outbound.rs (256)
Directoryapi
- newv2board.rs a UniProxy answer read into the contract’s node, and what is refused as it is read (894)
- helium.rs the config answer as the contract’s node, users, report body and refused local keys (448)
- http.rs build_http_client with and without enable_mtls, and gzip-compressed answers (155)
Unit tests live under tests/unit/ and compile into the binary’s own test harness, so they reach private items. Each tested source file other than src/main.rs ends with #[cfg(test)], a #[path] attribute and mod tests;; src/main.rs declares its test module right after its module list, as mod e2e:
| Source file | Test file |
|---|---|
src/main.rs |
tests/unit/e2e.rs, as mod e2e |
src/runtime.rs |
tests/unit/runtime.rs |
src/manager/node.rs |
tests/unit/manager/node.rs |
src/rule.rs |
tests/unit/rule.rs |
src/lower/mod.rs |
tests/unit/lower/spec.rs |
src/lower/inbound.rs |
tests/unit/lower/inbound.rs |
src/lower/outbound.rs |
tests/unit/lower/outbound.rs |
src/api/mod.rs |
tests/unit/api/http.rs |
src/api/newv2board.rs |
tests/unit/api/newv2board.rs |
src/api/helium.rs |
tests/unit/api/helium.rs |
src/manager/mod.rs, src/config.rs, src/api/embedded_cert.rs, src/api/hysteria.rs, src/blocking.rs and src/lower/route.rs have no test module of their own. The end-to-end and runtime tests drive the node manager, the config and the panel models, tests/unit/lower/spec.rs reaches lower_route through node_spec, tests/unit/lower/inbound.rs and tests/unit/lower/spec.rs build Hysteria 2 nodes with api::hysteria directly, and tests/unit/api/newv2board.rs reaches it through parse_node_config.
tests/unit/e2e.rs runs a real NodeManager against hand-written panels and drives it with the kernel’s own VMess, Hysteria 2 and sss clients; the proxy-outbound test serves a VLESS upstream with the kernel’s VlessCore. Its 23 tests cover metering and reporting, user refresh, a proxy outbound, a route change, the speed limit, the bootstrap retries, the dual-stack bind, the Hysteria 2 node and its rates, the device limit and the IP ban, helium’s report, and an sss node with transform chains, served by the fake helium panel. Its fixtures:
test_node_cfgis a NewV2boardV2raynode withnode_id = 1,listen_ip = "127.0.0.1",update_periodic = 1and a 5 s timeout, so the node polls once a second.fake_panel_quirkyserves UniProxy withQuirks:config_failures, the number of node config requests answered with a 500 first, andetags, which tags every answer and answers a matchingIf-None-Matchwith304 Not Modified, as Xboard does. It records every traffic push.fake_heliumserves Helium’s node API v2 for node 1 (/api/node/v2/1/config,/usersand/report) from the config and users bodies it is given, with ETags, records every report, and refuses a request without the bearer token.helium_users_bodywrites a users answer with the crate’susers::Users, held to no limits;helium_node_cfgistest_node_cfgturned into a helium node with nonode_type;free_tcp_portpicks a loopback port for the node to bind.SPARE_LOOPBACK(127.0.0.2) holds the port ina_node_whose_port_is_taken_comes_up_once_it_is_free, so no other test can take it.- The two dual-stack tests skip with
skipped: this host's IPv6 sockets do not take IPv4wheredual_stack()is false.
The helpers tests/unit/runtime.rs needs are pub(crate): fake_panel, test_node_cfg, tcp_echo, wait_bound, wait_relays, the VMess and VLESS clients and the round-trip helpers. The rest, such as fake_panel_quirky, Quirks, fake_helium and the file’s own spawn_node, stay private. tests/unit/runtime.rs starts with checks that run no node: identity edits on newV2board, the log name without the key, and the parse of the real-IP, handoff and enable_mtls keys. an_sspanel_node_is_refused_at_test_and_at_start runs test_config, build_node and the runtime’s spawn_node on an SSPanel node. The file then wraps apply_reload in a small Runtime (config, root token, handles), which starts one node through the runtime’s spawn_node, and reloads it: a newV2board type edit that respawns the node, a reload refused because a node does not build, a reload refused because it moves the node to SSPanel, and a rule_list_path edit that keeps every connection. It also holds the shared-WireGuard test.
tests/integration.rs is the one integration target. It spawns the built katana binary (CARGO_BIN_EXE_katana) against FakePanel and connects with reference clients. xray_interop.rs runs 10 cells: VMess over TCP, WebSocket and gRPC without TLS, VMess over TCP with TLS, VLESS over WebSocket and gRPC with TLS, Trojan over TCP with TLS, and three mux cells; each asserts the echoed bytes and a traffic report for uid 1001. sniff.rs shows that a sniffed HTTP host reaches a domain rule and that disable_sniffing stops it. hysteria_interop.rs runs a Hysteria 2 node with a local [node.hysteria].port, connects the upstream Hysteria client with a bare UUID, and opens two streams on one QUIC connection.
tests/support/mod.rs holds the shared constants, among them NODE_ID (1), UID (1001), WS_PATH (/katanaws) and GRPC_SERVICE (GunService), and the panel bodies FakePanel serves. It builds the Xray and Hysteria clients with go build from the Xray-core and hysteria trees of the sibling Etemenanki checkout, into CARGO_TARGET_TMPDIR, once per test binary (XRAY_BIN, HYSTERIA_BIN). When a tree or go is missing, or a build fails, it prints a SKIP: line, such as SKIP: `go` not available; skipping xray interop test or SKIP: failed to build xray-core, and the tests that need the binary return without running; the Hysteria test says so again with SKIP: hysteria binary unavailable.
The end-to-end tests run on the real clock with a one-second poll period. See Testing for how to run the suites.
Reference trees
Section titled “Reference trees”The katana repository carries three git submodules that are not part of the crate: XrayR, V2bX and Xboard. They are the node agents and the panel that katana’s panel side is modelled on, and they serve only to explain panel compatibility. For example, the UniProxy client reads a Hysteria 2 node in the shape of V2bX’s Hysteria2Node, and its comments cite it. Nothing builds or tests against them. The integration tests use two other reference trees, Xray-core and hysteria, from the Etemenanki checkout next to katana, and only to build client binaries.