Traffic accounting and reporting
Source files: 34 · checked against Etemenanki 46c12e4 · katana v6.1.0
Etemenanki/supervisor/src/entity/usage.rsEtemenanki/supervisor/src/entity/session.rsEtemenanki/supervisor/src/supervisor.rsEtemenanki/supervisor/src/serve.rsEtemenanki/supervisor/src/system/handoff.rsEtemenanki/supervisor/src/connector.rsEtemenanki/supervisor/src/policy.rsEtemenanki/supervisor/src/track/mod.rsEtemenanki/supervisor/src/track/metered.rsEtemenanki/supervisor/src/track/pace.rsEtemenanki/supervisor/src/track/sampler.rsEtemenanki/concepts/src/runtime.rsEtemenanki/protocols/src/core/mod.rsEtemenanki/protocols/src/hysteria/server/inbound.rsEtemenanki/protocols/src/hysteria/obfs.rsEtemenanki/protocols/src/vless/protocol.rsEtemenanki/supervisor/tests/unit/usage.rsEtemenanki/supervisor/tests/tracking.rsEtemenanki/supervisor/tests/hot_swap.rskatana/src/manager/node.rskatana/src/manager/mod.rskatana/src/runtime.rskatana/src/lower/mod.rskatana/src/api/mod.rskatana/src/api/newv2board.rskatana/src/api/helium.rskatana/src/config.rskatana/tests/unit/e2e.rskatana/tests/unit/lower/spec.rskatana/tests/unit/api/newv2board.rskatana/tests/unit/api/helium.rskatana/tests/integration/xray_interop.rskatana/tests/integration/hysteria_interop.rskatana/tests/support/mod.rs
katana 4 does not meter traffic itself. Each node runs its own etemenanki_supervisor::Supervisor<Uid>, and the supervisor (the actor that owns the node’s listeners, sessions and routes) counts, for every panel user, the bytes their client’s connections carry on the server’s wire. Once per poll cycle, katana takes those counts from the supervisor as one delta per user, sums them by panel uid and sends one report to the panel. Speed limits work the same way: katana lowers each user’s rate into the spec, and the supervisor paces the user’s flows.
This page is for contributors who change NodeManager::report, take_traffic or run in src/manager/node.rs, the panel clients’ report, or anything that decides what a user is billed. It covers what the bytes are, the report cycle, the request each panel type receives, the final report at shutdown, how speed limits reach the supervisor, and what replaced katana 3’s src/meter.rs and src/traffic.rs. The ledger behind take_usage is described in depth on Per-user usage accounting, and the pacer on Tracking. The operator’s view is on Traffic reporting.
Responsibilities
Section titled “Responsibilities”The supervisor of each node:
- gives every session a
Wirethat counts the wire bytes of the client’s side of the connection; - binds the session to its user when its first flow is admitted (
Session::admit), and keeps one account per user in itsLedger; - moves each live session’s new bytes into its user’s pending total once per sampler tick (every second in katana), and a closing session’s remainder when it closes;
- hands out pending totals through
Supervisor::take_usage, at most oneUsageDelta<Uid>per user and never the same byte twice; - paces every flow of a limited user against that user’s
Pacer.
katana, in src/manager/node.rs:
- calls
take_usageonce per poll cycle, fromNodeManager::take_traffic, and once more after the node’s supervisor has shut down; - sums the deltas by uid into a
NodeReportwith a new id and sends every uid with bytes in onePanelClient::reportrequest, and logs a warning when that request returns an error; - sends no traffic while
[node.controller].disable_upload_trafficis set; - lowers each user’s speed limit into
UserSpec::speed_limit(see Lowering a node into a spec).
Each [[node]] has its own NodeManager and its own supervisor, and so its own ledger. A node’s reports carry only what that node’s sessions counted.
katana does not:
- count or meter anything itself. The katana 3 modules that did (
src/meter.rs,src/traffic.rs) are gone; see What changed from katana 3. - install a
UsageSink, or change any other builder default. It starts every supervisor withSupervisor::start(spec), which isSupervisor::builder().start(spec): defaultApplyOptionsfor the first apply, the default sampler tick (DEFAULT_SAMPLE_INTERVAL, 1 s), no usage sink and the defaultSocketOptions. - call
Supervisor::usage_snapshot, which returns oneUsageTotalper user (everything since the supervisor started, reported or not) without taking anything. - read the sampler’s payload statistics (
StatsSnapshot). The only thing katana reads from the supervisor’s tracker is its flow events, for the client addresses a helium node reports (see Node manager). - persist anything. The ledger lives in memory.
- report online users or device counts. The client addresses users connected from go to helium only, and only under
enable_device_limit; they travel in the same report and are described on Node manager.
Key types
Section titled “Key types”/// A panel user, as the supervisor keys them: their panel id.#[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()) }}Uid is the U of every katana supervisor, so usage comes back keyed by the panel’s own user id: delta.user.0 is the id the panel listed the user under, with no lookup on katana’s side. katana’s inbound admits the node’s one user set (USER_SET, tag "users"), whose keys are Uids. How users become that UserSet is on Lowering a node into a spec.
The supervisor maps its internal UserKey back to the Uid it was handed out for (UsageBook in supervisor/src/supervisor.rs). Actor::commit_keys publishes the id of every new key before any session can bind it, so a take always finds a Uid for each delta. A key without one would be a bug rather than a delta to drop, because taken bytes cannot be put back: UsageBook::name panics with {key:?} was bound before it was published. The final delta of a user removed mid-interval comes back under their uid with the next take.
name() is the uid in decimal. It is the label every flow of the user carries, which is how a client address read off a flow finds its way back to a uid.
UsageDelta and take_usage
Section titled “UsageDelta and take_usage”/// Traffic one user moved since the last report.////// Directions are the user's: `up` is what their client sent toward/// destinations, `down` is what came back to it./// Serializable whenever the key is, so a report reaches a panel as it is.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct UsageDelta<U: UserId> { pub user: U, /// Bytes from the user's client, toward destinations. pub up: u64, /// Bytes back to the user's client. pub down: u64,}impl<U: UserId> Supervisor<U> { /// Every user's wire bytes counted since the previous take, at most one /// delta per user and none for a user who moved nothing. pub fn take_usage(&self) -> Vec<UsageDelta<U>>;}UsageDelta is Serialize whenever its key is, but its shape (user, up, down) matches no panel’s body, so katana builds its own rows (UserTraffic).
take_usageis a plain synchronous method on the handle. It reads the usage book directly and never goes through the supervisor’s command channel, so it answers while an apply is running and aftershutdownhas returned. katana relies on the second: its final take runs after the shutdown.- It drains what it returns: the bytes move from the account’s pending total into its reported total, and no later take returns them.
- A live session’s bytes reach a take once the sampler has reconciled them, about one sampler tick after they moved. When a session has ended, its remainder is in the next take.
- The order of the deltas is unspecified.
The node’s reporting state
Section titled “The node’s reporting state”pub struct NodeManager { /// The panel client. It keeps its own copy of what it was built from, so a /// config edit to any of that swaps in a new one. api: Mutex<Arc<PanelClient>>, /// Static config, updated by file-driven [`StaticUpdate::Config`]. cfg: Mutex<NodeConfig>, /// Set once the node first comes up. supervisor: OnceLock<Supervisor<Uid>>, // The other fields are described on the node manager page.}| Field | Type | Role in reporting |
|---|---|---|
supervisor |
OnceLock<Supervisor<Uid>> |
Set by the first successful bootstrap attempt. report returns at once while it is empty, so a node that never came up takes and sends nothing. |
cfg |
parking_lot::Mutex<NodeConfig> |
Read at every report for controller.disable_upload_traffic, and by poll_period for controller.update_periodic. |
api |
parking_lot::Mutex<Arc<PanelClient>> |
api() clones the Arc under the lock and releases it, so each report goes through whichever client is current when it runs. |
The poll loop, the config edits and every report run on the node’s own task (NodeManager::run), one at a time, so no two reports ever overlap. None of these locks is held across an .await: report clones the client Arc, and take_traffic reads the flag, in statements whose guards end with them. The full field list is on Node manager.
UserTraffic, NodeReport and PanelClient::report
Section titled “UserTraffic, NodeReport and PanelClient::report”pub struct UserTraffic { pub uid: i64, pub upload: i64, pub download: i64,}
pub struct NodeReport { pub id: uuid::Uuid, pub traffic: Vec<UserTraffic>, pub ips: Vec<(i64, Vec<IpAddr>)>,}
impl PanelClient { pub async fn report(&self, report: &NodeReport) -> Result<()>;}PanelClient is an enum over the newV2board and helium clients, and report dispatches to the client the node’s panel_type built. newV2board takes the traffic only and sends no request when there is none; helium takes the whole report, as the helium-node-api crate’s report::Report. Result is anyhow::Result. What each client sends is under The report request.
Configuration
Section titled “Configuration”| Key | Type | Default | Read by |
|---|---|---|---|
[node.controller].update_periodic |
u64 seconds |
60 (default_update_periodic) |
NodeManager::poll_period, which raises a value below 1 to 1 second |
[node.controller].disable_upload_traffic |
bool |
false |
take_traffic, at every call |
[node.api].timeout |
u64 seconds |
0, read as 5 (ApiConfig::timeout_secs) |
api::build_http_client: the request timeout of the panel client, which sends the traffic report |
[node.api].speed_limit |
f64 Mbps |
0.0 |
The panel clients, where a value above zero replaces every user’s limit from the panel (see Speed limits) |
Both [node.controller] keys reach a running node as a StaticUpdate::Config that only stores them. disable_upload_traffic applies from the next report; a changed update_periodic restarts the timer (see When a report runs). An edit to any [node.api] key, to enable_mtls or to [node.hysteria] builds a new panel client. The field tables are on the katana configuration reference.
What is billed
Section titled “What is billed”A report carries wire bytes per session, as supervisor/src/entity/usage.rs defines them: what the server’s bandwidth carries for the user’s client, the protocol’s own overhead included. Each connection a client opens is one session, except on gRPC, where each HTTP/2 stream is one. The supervisor feeds a session’s Wire in one of two ways, depending on the node type.
| Node | One session per | Fed by | What the count covers |
|---|---|---|---|
| VMess or VLESS over plain TCP | TCP connection | supervisor/src/serve.rs → drive: every Traffic step the connection’s runtime yields adds transport_rx as up and transport_tx as down (Traffic is in concepts/src/runtime.rs) |
The protocol stream as it crosses the socket: request and response headers, the protocol’s framing, encryption overhead and padding, and the payload |
| VMess, VLESS, Trojan, Shadowsocks, AnyTLS, SOCKS or HTTP over TLS (a Trojan or AnyTLS node always uses TLS, and a SOCKS or HTTP node always has TLS in its transport) | TLS connection | drive, on the stream the TLS transport yields |
The protocol stream inside TLS: for AnyTLS its frames and padding and every stream of its session. The TLS handshake and TLS record overhead are not counted |
| The same over WebSocket, with or without TLS | WebSocket connection | drive, on the stream the WebSocket transport yields |
The protocol stream inside the WebSocket frames. The HTTP upgrade, the frame headers and any TLS below them are not counted |
| The same over gRPC, with or without TLS | HTTP/2 stream: each stream on a gRPC connection is a session of its own | drive, per stream |
The protocol stream inside the gRPC framing. The carrier’s own framing counts toward nobody |
| Shadowsocks (legacy or 2022) over plain TCP | TCP connection | drive |
The encrypted stream as it crosses the socket, salt and authentication tags included |
| VLESS over REALITY, with or without Vision | TCP connection | drive, on the stream REALITY yields, wrapped in the Vision adapter on a Vision node |
The VLESS stream inside REALITY’s TLS, as the protocol core reads and writes it. The REALITY handshake and record overhead are not counted, and a connection REALITY relays to its cover site opens no flow and counts toward nobody |
| sss, over any of these transports | as for its transport | drive, on the decoded side of the transform chains |
The sss stream after the chains are undone, as the sss whitepaper asks: what the transforms add or save on the wire is not the user’s. See sss |
| Hysteria 2 | QUIC connection | Wire::quic(ConnectionBytes): quinn’s udp_rx.bytes as up and udp_tx.bytes as down. ConnectionBytes holds the quinn::Connection, so it counts until it is dropped with the connection’s other handles |
The UDP payload of every datagram the connection receives or sends: the QUIC handshake, QUIC framing, TLS, the HTTP/3 authentication request, every proxy stream and every UDP datagram. IP and UDP headers are not counted, and neither is the salt Salamander obfuscation adds to each datagram below quinn (obfs::SALT_LEN = 8 bytes) |
up is what the user’s client sent, down is what came back to it. katana reports them as upload and download.
Some consequences follow from counting the session rather than the flow:
- UDP relayed over a stream protocol is billed as part of that stream. VLESS and VMess UDP, and mux.cool with XUDP, travel inside the TCP connection, so their datagrams and framing are in the connection’s count.
- A mux connection is one session. Every sub-flow, and the mux frame headers, count toward the user who opened the connection. See mux.cool and XUDP for the framing.
- The handshake is billed. A session is bound to its user when its first flow is admitted, and the binding starts the account’s watermark for the session at
(0, 0), so everything the wire counted before it, the protocol’s own handshake included, is reported under that user. - Blocked and audited flows are billed at the wire.
AppConnector::connect(supervisor/src/connector.rs) admits a flow, and so binds its session, before it routes the flow, so the wire bytes of a session whose flows ablockrule or an audit rule sends to a blackhole still count toward the user. - A handed-over connection is billed like an accepted one. A TCP connection that a relay on the same host hands over on a node’s handoff socket is one session, counted as the table above says for its transport, from the moment the supervisor takes the socket. The control connection that carried it counts toward nobody.
- A connection that never opens a flow counts toward nobody. Only the first admitted flow binds a session (
Session::admit, guarded by itsboundflag). A stream handshake that fails, a wrong credential, or a handshake that does not reach an established core withinHANDSHAKE_TIMEOUT(10 s, frometemenanki_protocols::core;driveends the connection withinbound handshake timed out after 10s) opens no flow. Neither does a Hysteria 2 client that never authenticates, or never opens a stream or datagram flow. A session whose first flow is refused at admission, withthe session was closedorthe user was removed before the session opened a flow, is never bound either.
The details, including where each Wire is fed and who holds it, are on Per-user usage accounting.
An example
Section titled “An example”A VLESS client that sends no add-ons opens one TCP connection to a plain TCP node, sends 1,000,000 bytes to an IPv4 destination over it and reads them back. The node reports 1,000,026 bytes up and 1,000,002 bytes down for that user:
| Direction | Payload | Overhead | Billed |
|---|---|---|---|
| up | 1,000,000 | The request header: version 1 byte, UUID 16, add-ons length 1, command 1, port 2, address type 1, IPv4 address 4 | 1,000,026 |
| down | 1,000,000 | The response header RESPONSE_HEADER (protocols/src/vless/protocol.rs): version 1 byte, add-ons length 1 |
1,000,002 |
katana 3 reported 1,000,000 bytes each way for the same transfer, because it counted payload on the outbound side.
Billing and pacing measure different things
Section titled “Billing and pacing measure different things”A user is billed for wire bytes per session and paced on payload per flow. The pacer is charged by each flow’s Metered or MeteredDatagram wrapper with what the flow moved to and from its outbound, in both directions; protocol overhead and the Hysteria 2 QUIC overhead never reach it. The two figures therefore differ for the same user, and neither can be derived from the other.
The one path where a flow’s payload also counts toward its session’s wire is a SOCKS UDP association (AppConnector::charging_datagrams, which sets the flow’s charge). katana’s SOCKS nodes relay no UDP (udp: false), so it never takes that path. See Tracking.
Data flow
Section titled “Data flow”From the wire to the panel
Section titled “From the wire to the panel”flowchart LR ST["stream session: drive adds transport_rx / tx"] --> W["Wire of the session"] Q["Hysteria 2 session: quinn udp_rx / udp_tx"] --> W W -->|"first flow binds it"| A["Ledger account of the Uid"] A -->|"sampler tick or session close"| PD["pending total"] PD -->|take_usage| D["UsageDelta per Uid"] D --> M["take_traffic sums by uid"] M --> R["NodeReport, PanelClient::report: one request"]
Everything left of take_usage runs inside the supervisor. The data plane adds to the wires. The sampler task runs each tick on the blocking pool (spawn_blocking): it reconciles the ledger first, then scans the live flows and drains the closed ones for its payload statistics. Everything right of take_usage runs on the node’s task.
The poll cycle
Section titled “The poll cycle”NodeManager::poll_cycle(rebuild) is the only place a regular report runs. The report runs after the reconcile, so a take includes the remainders of sessions the apply closed that have already ended; the rest appear in a later take.
sequenceDiagram participant N as Node task participant P as PanelClient participant S as Supervisor N->>P: node_info and user_list N->>P: node_rule, unless disable_get_rule N->>S: apply_with, when something changed N->>S: take_usage() S-->>N: one UsageDelta per Uid with bytes N->>N: sum by uid, drop zero rows N->>P: report(new NodeReport), when not empty
The node-info and user-list half of the cycle, and when an apply runs, are on Node manager. After the reads, report is all the cycle sends to the panel: katana 6 sends no illegal-access report.
report and take_traffic
Section titled “report and take_traffic”let mut totals: HashMap<i64, (u64, u64)> = HashMap::new();for delta in usage { let total = totals.entry(delta.user.0).or_insert((0, 0)); total.0 = total.0.saturating_add(delta.up); total.1 = total.1.saturating_add(delta.down);}totals .into_iter() .filter(|(_, (up, down))| *up != 0 || *down != 0) .map(|(uid, (up, down))| UserTraffic { uid, upload: i64::try_from(up).unwrap_or(i64::MAX), download: i64::try_from(down).unwrap_or(i64::MAX), }) .collect()Step by step:
- No supervisor, no report.
let Some(supervisor) = self.supervisor.get() else { return; }: a node whose bootstrap has not succeeded has no supervisor and nothing to take. - Take.
take_trafficcallssupervisor.take_usage()before it reads the flag, so the ledger is drained on every cycle, whether or not anything is sent. - Reporting disabled. With
disable_upload_trafficset,take_trafficreturns no rows. The deltas just taken are dropped. - Sum. Each delta is added to its uid’s entry in a
HashMap<i64, (u64, u64)>withsaturating_add, so there is one entry per uid. - Drop zero rows. Every uid whose totals are
(0, 0)is left out, so no zero row is ever sent. - Build rows. Each total becomes a
UserTraffic, eachu64converted toi64withi64::try_from, saturating ati64::MAX. The rows follow theHashMap’s iteration order, which is unspecified. - The report. The rows, and the client addresses from
take_client_ips, become aNodeReportwith a new randomid(uuid::Uuid::new_v4). - Nothing to send, no request. A report with no rows and no client addresses is not sent, so an idle node makes no request at all.
- One request.
self.api().report(&report)sends it, through the client that is current at this moment. - On
Err. The node logs a warning (see A report that returns an error).
When a report runs
Section titled “When a report runs”| Trigger | What runs | Where |
|---|---|---|
The poll timer. The period is update_periodic seconds, minimum 1. The first tick of tokio::time::interval fires at once and serve consumes it before its loop, so the first timer report comes one full period after serve starts. |
poll_cycle(false) |
NodeManager::serve |
A config edit, once the node is up, that swaps in a new PanelClient or changes a setting the listener or its routes are built from |
poll_cycle(rebuild) at once, report included. It does not move the timer |
NodeManager::apply_static |
A changed update_periodic |
Nothing by itself. Once the edit is applied, serve replaces the interval and consumes its first tick, so the next timer report comes one full new period later |
NodeManager::serve |
| The node’s token is cancelled: katana shuts down, or a reload removes the node | One final report, after the supervisor has shut down |
NodeManager::run |
A StaticUpdate::Globals (an [[outbound]] or [dns] edit) reconciles the node without polling, so it sends no report. Neither does a bootstrap attempt: the node’s first report is the first timer tick or the first edit that polls. Which config edits swap the client or force a rebuild is on Node manager.
The final report
Section titled “The final report”sequenceDiagram participant RT as Runtime participant N as Node task participant S as Supervisor participant P as PanelClient RT->>N: cancel the node token N->>N: finish the running cycle, leave serve N->>N: await the client-address task N->>S: shutdown(Duration::ZERO) Note over S: listeners stop, every session closes and folds in its remaining count, the sampler ticks once more N->>S: take_usage() inside take_traffic N->>P: report(final NodeReport) RT->>RT: await the node task
if self.bootstrap(&shutdown, &mut static_rx).await { let watch = self.clone().spawn_client_ips(shutdown.clone()); self.serve(&shutdown, &mut static_rx).await; let _ = watch.await;}
// Every session has ended once the supervisor is down, and an ended// session's usage is counted in full, so this report is final. Flush// it instead of discarding up to one poll of traffic.if let Some(supervisor) = self.supervisor.get() { supervisor.shutdown(Duration::ZERO).await;}self.report().await;- The running cycle finishes first.
serverunspoll_cycleinside atokio::select!handler, andselect!does not poll the shutdown branch while a handler runs, so a cancellation that arrives during a report waits for that cycle to end. - Zero grace.
shutdown(Duration::ZERO)sendsCommand::Shutdownto the actor, andActor::shutdownstops the listeners, cancels the balancer probes, closes the connection task tracker, cancels the root token without waiting (zero grace), which closes every session, and waits until every connection task has ended. Each ending session folds its remaining count into its user’s account as its last handle drops (impl Drop for Session→Account::close). Only then does the actor stop its sampler, which ticks once more, and await it. Whenshutdownreturns, every session has folded its remaining count into the ledger. The comment inrungives the reason for the order: once the supervisor is down every session has ended, so the take after the shutdown is the node’s last, rather than leaving up to one poll period of traffic untaken. - The take after the shutdown.
take_usagestill works on a supervisor that has shut down, soreporttakes and sends the node’s last bytes as in any cycle. - A node that never came up has no supervisor: the shutdown step is skipped and
reportreturns at once. - The runtime waits.
src/runtime.rsawaits a node’s task after cancelling it. On process shutdown it cancels the root token, whose children are every node’s token, and awaits each node’s task in turn. When a reload removes a node, it cancels that node’s token and awaits its task. The process exits, or the reload continues, only after the node’s shutdown and final report have finished. Which reload edits remove a node is on Process runtime and reload.
The report request
Section titled “The report request”Each client sends one POST with a JSON body built from every row (Content-Type: application/json), on the client’s own reqwest::Client, which api::build_http_client builds with the [node.api].timeout request timeout. The URL is [node.api].host with any trailing / removed, followed by the path. newV2board carries the panel key in the query string, helium in an Authorization: Bearer header. Connection and response handling are the panel clients’ and are described on Panel clients.
newv2board::Client::report_user_traffic builds a HashMap<String, [i64; 2]> (HashMap::with_capacity(t.len())) from each row’s uid.to_string() to [upload, download] and posts it to PUSH_PATH = "/api/v1/server/UniProxy/push", with the same three query parameters as every UniProxy request (Client::query): node_id, node_type (the node type the panel finds this node by, node_type_param) and token ([node.api].key).
POST https://panel.example.com/api/v1/server/UniProxy/push?node_id=1&node_type=vless&token=replace-with-the-panel-key{"1001":[1000026,1000002]}The body is a JSON object keyed by uid; take_traffic builds at most one row per uid.
helium::Client::report posts the whole report to {host}/api/node/v2/{node_id}/report, with the key as Authorization: Bearer. The body is the helium-node-api crate’s report::Report, the type Helium reads it with, built from the NodeReport by report_body in src/api/helium.rs; agent_version is katana’s own version (CARGO_PKG_VERSION):
POST https://panel.example.com/api/node/v2/1/report{"report_id":"6f1c0f0e-2a4b-4c7d-9e3f-1a2b3c4d5e6f","agent_version":"6.0.0","traffic":[{"id":1001,"up":1000026,"down":1000002}],"ips":[]}helium answers with the crate’s report::ReportAnswer: {"duplicate": false}, or true for a report_id it has already recorded. ips is empty unless enable_device_limit is on.
Helium’s customer IDs are i32 and its counts u64, while a NodeReport holds i64s. report_body leaves out a traffic row whose uid does not fit i32 or whose upload or download is negative, and an ips entry whose uid does not fit, rather than wrap either into another number. Each one left out logs a WARN that names its uid and nothing else of the entry:
traffic left out of the report: the uid or a byte count is out of rangeclient addresses left out of the report: the uid is out of rangeA helium node’s own users never trip either filter: their uids are the panel’s i32 IDs widened to i64, and take_traffic never builds a negative count.
| newV2board | helium | |
|---|---|---|
| Path | /api/v1/server/UniProxy/push |
/api/node/v2/{node_id}/report |
| Key | token in the query, with node_id and node_type |
Authorization: Bearer |
| Body | {"<uid>": [upload, download], …} |
report::Report: {"report_id", "agent_version", "traffic": [{"id", "up", "down"}], "ips": [{"id", "ips"}]} |
| Rows | Every uid with bytes, in one request | Every uid with bytes that report_body can carry, in one request |
| Built by | newv2board::Client::report_user_traffic |
helium::Client::report → report_body |
Speed limits
Section titled “Speed limits”katana decides each user’s rate; the supervisor enforces it.
- The panel’s numbers. The newV2board client converts Mbps to bytes per second with
mbps_to_bps(src/api/mod.rs,MBPS_TO_BPS = 1_000_000.0 / 8.0, decimal megabits,0for any value at or below zero); helium’s users answer says onelimits.speed_limitfor all its users, in bytes per second already. A positive[node.api].speed_limitreplaces the panel’s figures. The per-panel mapping is on Panel clients. - One rate per user.
lower_users(src/lower/mod.rs) setsUserSpec::speed_limit = NonZeroU64::new(u.speed_limit): the user’s own limit, already the local override where one is set, andNone, unlimited, when it is zero. A node has no limit of its own; katana 6.1.0 removed the node-level limit anddetermine_rate, which only repeated the users’ limits. See Lowering a node into a spec. - Published at commit. When an apply commits, the supervisor’s
Actor::publish_limitshands the limits that changed toTracker::change_speed_limits, which sets the rate of each of those users’Pacer; the other users’ pacers are not touched. - Enforced per user. One
Pacerper user, a token bucket in bytes per second, is shared by every flow of the user in both directions. It charges each transfer after it moves, and the user’s next transfer waits out any debt. The bucket, its debt andset_rateare on Tracking.
The users are not part of the node reconcile compares (disruptive_part in src/manager/node.rs), so a speed-limit change does not drop the node’s connections. Live flows feel a changed rate on their next poll, and a flow already sleeping off debt looks again within MAX_WAIT (1 s, supervisor/src/track/pace.rs). The user’s sessions stay open (a_speed_limit_change_keeps_the_users_sessions in supervisor/tests/hot_swap.rs). The operator’s view is on Speed limits.
What changed from katana 3
Section titled “What changed from katana 3”katana 3.x metered each flow’s payload itself. src/meter.rs wrapped every stream outbound a connection opened in Metered (UDP went through a fan-out link holding the same kind of Gate), and the Gate billed what crossed it to the user’s UserCounter and held the flow back while the user’s TokenBucket was in debt. src/traffic.rs kept those counters per credential in a NodeTraffic registry, which each report read (NodeTraffic::snapshot, commit_reported). Both files are gone in katana 4, together with src/serve.rs, src/connector.rs, src/router.rs, src/inbound.rs, src/outbound/ and src/manager/{proxy,transport}.rs.
| katana 3.x | katana 4 | Described on |
|---|---|---|
Payload counted on the outbound side of each flow (Gate::sent, Gate::received) |
Wire bytes counted per session on the client side (Wire, fed by drive or by quinn) |
Per-user usage accounting |
UserCounter: two AtomicU64 totals per credential |
One Ledger account per user with a watermark per live session, in the node’s supervisor |
Per-user usage accounting |
NodeTraffic::snapshot, commit_reported, residuals and draining counters |
Supervisor::take_usage, which drains what it returns |
This page |
TokenBucket in each UserCounter |
Pacer per user in the supervisor’s tracker (track/pace.rs) |
Tracking |
Gate and Metered (src/meter.rs) |
Metered and MeteredDatagram (track/metered.rs) |
Tracking |
determine_rate in src/traffic.rs |
The user’s own limit into UserSpec::speed_limit (determine_rate moved to src/lower/mod.rs in katana 4 and was removed in 6.1.0) |
Lowering a node into a spec |
AuthKey, UserTag, UserEntry, NodeTraffic::prepare and commit |
Uid keys in one UserSet; the supervisor’s UserKey and apply |
Lowering a node into a spec, Users, principals and sessions |
Admission and its leases (src/connector.rs) |
Sessions and principals in the supervisor | Users, principals and sessions |
What that changes in the numbers a panel sees:
| katana 3.x | katana 4 | |
|---|---|---|
| Protocol overhead (headers, framing, encryption, padding) | Not billed | Billed |
| Mux | Each sub-flow’s payload | The whole connection, mux frames included, to the user who opened it |
| Hysteria 2 | Each proxy stream’s and datagram’s payload | The QUIC connection’s UDP bytes |
A flow sent to block or to an audit blackhole |
Nothing crossed an outbound, so nothing was billed | The session’s wire bytes are billed |
| A rate change | Only new flows used the new rate; open ones kept the old bucket until they closed | Live flows feel the new rate on their next poll, and a flow already waiting out debt within MAX_WAIT (1 s) |
A report under katana 4 is therefore larger than one under katana 3 for the same transfer. The operator-facing notes on the upgrade are in Upgrading to katana 4.
Invariants
Section titled “Invariants”| Invariant | Mechanism | Pinned by |
|---|---|---|
Every byte a bound session counted by its close reaches exactly one take_usage result, under its user |
The ledger’s watermarks and pending totals under each account’s lock | every_byte_is_taken_exactly_once (a property test) and takes_racing_live_sessions_report_every_byte_once (supervisor/tests/unit/usage.rs) |
| A take reports a live session’s bytes once they are reconciled, and a closed session’s remainder | Sampler-tick reconcile; Account::close on the session’s drop |
a_take_reports_live_bytes_once_they_are_reconciled (supervisor/tests/unit/usage.rs) |
A stream session counts the transport_rx and transport_tx of every Traffic step drive sees: the protocol stream after its transport, mux headers included |
drive feeds the session’s Wire |
mux_sub_flows_and_their_session_count_exactly_what_moved (supervisor/tests/tracking.rs): a mux connection’s session, and the user’s delta, equal the bytes the client sent and received, sub-flow frames included |
| A Hysteria 2 session bills its QUIC connection’s UDP bytes | Wire::quic |
a_hysteria2_session_bills_its_quic_connections_bytes (supervisor/tests/tracking.rs) |
| Reports carry a user’s relayed bytes under their uid | take_usage, take_traffic, the UniProxy push |
vmess_traffic_is_metered_and_reported, and through an upstream proxy outbound proxy_outbound_relays_and_meters (tests/unit/e2e.rs) |
| A Hysteria 2 user’s QUIC bytes are reported under their uid | The same, from Wire::quic |
a_hysteria_node_relays_and_meters (tests/unit/e2e.rs) |
| A removed user’s remaining bytes are reported under their uid | The removed user’s closing sessions fold their remainder into the user’s account, which the next take drains under the same uid (usage.rs: a user removed mid-interval keeps their account) |
Not pinned by a dedicated test. unchanged_user_survives_user_refresh (tests/unit/e2e.rs) removes user 1001 in its third phase, but its assertion holds whether or not the removal path contributes any bytes |
| Traffic over TLS, WebSocket, gRPC and mux is reported under the user | As above, for every transport | The xray_interop matrix (tests/integration/xray_interop.rs) |
| One report carries at most one row per uid | One delta per user per take; totals is keyed by uid |
Not pinned by a katana test |
| No zero row is sent, and an idle node sends no request | The zero-row filter in take_traffic and NodeReport::is_empty |
Not pinned by a test |
| The final take comes after every session has ended and folded in its remaining count | shutdown(Duration::ZERO) returns only after every connection task has ended |
Not pinned by a dedicated test; the e2e tests make their final assertion after the node’s task has ended |
With disable_upload_traffic, no traffic is sent, and the ledger is still drained |
The take runs before the flag is read; take_traffic returns no rows |
Not pinned by a test |
| A user’s rate is their own limit, and zero is unlimited | NonZeroU64::new(u.speed_limit) in lower_users |
a_user_is_held_to_their_speed_limit (tests/unit/lower/spec.rs) |
| A user’s speed limit paces their traffic | The supervisor’s Pacer |
a_users_speed_limit_paces_their_traffic (tests/unit/e2e.rs) |
| A speed-limit change keeps the user’s sessions | Pacer rates change in place | a_speed_limit_change_keeps_the_users_sessions (supervisor/tests/hot_swap.rs) |
Failure paths and cancellation
Section titled “Failure paths and cancellation”A report that returns an error
Section titled “A report that returns an error”When PanelClient::report returns Err(e), report logs at WARN (target katana::manager::node):
node <node_id>: report <report id>: <error><error> is the anyhow error’s Display, which prints its outermost context only: the request that failed, such as POST UniProxy push or POST report. How the clients build their errors is on Panel clients.
Reporting disabled
Section titled “Reporting disabled”With disable_upload_traffic set, every cycle still takes the node’s usage and sends no traffic; a helium node collecting client addresses still sends them. What those takes drain is never sent, even if the flag is cleared later.
A node that is not up
Section titled “A node that is not up”Until the node’s first bootstrap attempt succeeds, supervisor is empty and report returns before it takes anything. There is nothing to take: no listener has accepted a connection. Config edits received meanwhile are stored and run no poll cycle or report; a config edit makes the next bootstrap attempt start at once (see Node manager).
Cancellation
Section titled “Cancellation”- The node’s
CancellationTokenendsserveafter the running handler, whether a timer cycle or a config edit, has finished, so a report is never cut off between its take and its request. runshuts the supervisor down with zero grace before the final take, so connections get no time to finish. Every session has ended and folded in its remaining count before the take.- The runtime waits for the node’s shutdown and its final report before the process exits or the reload continues. The report’s request runs under the panel client’s request timeout (
[node.api].timeout).
Sessions that are still closing
Section titled “Sessions that are still closing”Sessions that an apply closes, such as a removed user’s under the default UserRemovalPolicy::Close (katana leaves the policy’s user_removal at its default and sets no per-inbound one), and sessions that reconcile closes with Supervisor::close(Selector::All) after an apply that drops every connection, are cancelled. A closed session’s remainder reaches the ledger when its last handle drops; what a take does not yet find there is in a later take.
No persistence
Section titled “No persistence”The ledger lives in the node’s supervisor, in memory, and is not written to disk. A crash or a SIGKILL ends the process without the final report.
Limits
Section titled “Limits”| What | Value | Where |
|---|---|---|
| Poll period | update_periodic seconds, default 60, minimum 1 |
default_update_periodic, NodeManager::poll_period |
| First timer report | One full poll period after serve starts |
NodeManager::serve |
| Usage lag behind live sessions | About one sampler tick: DEFAULT_SAMPLE_INTERVAL = 1 s, since katana starts with Supervisor::start. A tick delayed by a busy runtime is not made up in a burst (MissedTickBehavior::Delay); the next reconcile covers the longer interval |
supervisor/src/track/sampler.rs |
| Requests per report | One, carrying every uid with bytes | report |
| Rows per report | At most one per uid | take_traffic (HashMap<i64, (u64, u64)>) |
| Report request timeout | [node.api].timeout seconds; 0 means 5 |
ApiConfig::timeout_secs, api::build_http_client |
| Counter width | u64 per direction, summed with saturating_add, sent as i64, saturating at i64::MAX |
take_traffic, UserTraffic |
| Shutdown grace before the final take | Duration::ZERO |
NodeManager::run |
| Stream handshake timeout | HANDSHAKE_TIMEOUT = 10 s; a session that has not reached an established core by then opens no flow and is never bound |
protocols/src/core/mod.rs, supervisor/src/serve.rs → drive |
| Speed-limit unit | Bytes per second; 1 Mbps = 125,000 B/s | MBPS_TO_BPS in src/api/mod.rs |
| Persistence | None | NodeManager::new, Supervisor::start |
End-to-end tests in tests/unit/e2e.rs are compiled into the katana binary as its e2e test module (#[path] in src/main.rs). Each spawns a real NodeManager with spawn_node, whose static-update channel stays open and idle, against a fake panel on 127.0.0.1. test_node_cfg sets update_periodic = 1 and [node.api].timeout = 5. The fake newV2board panel (fake_panel_quirky, with default Quirks in these tests) records every /UniProxy/push body, and reported_totals sums [upload, download] for one uid over every recorded body. Each metering test polls reported_totals up to 150 times, 100 ms apart (15 s), then cancels the node, awaits its task and makes its final assertion.
| Test | Setup | What it pins |
|---|---|---|
vmess_traffic_is_metered_and_reported |
A VMess client echoes 50,000 bytes through the node | The panel receives at least 50,000 bytes each way for uid 1001 |
unchanged_user_survives_user_refresh |
User 1001 echoes 40,000 bytes, user 2002 is added, 1001 echoes another 40,000 bytes on the same connection, then 1001 is removed; 3 s pass after each user-list change | 1001’s connection survives the addition and drops after the removal; the panel receives at least 80,000 bytes each way for 1001 |
proxy_outbound_relays_and_meters |
The node’s default route goes through an upstream VLESS proxy; 50,000 bytes echoed | Traffic is still attributed to uid 1001 behind a proxy outbound |
a_hysteria_node_relays_and_meters |
A Hysteria 2 node described by [node.hysteria].port (hysteria_node_cfg: local node info, users from the panel); a Hysteria 2 client authenticated with its panel UUID echoes 50,000 bytes over a proxy stream |
The panel receives at least 50,000 bytes each way for uid 1001 |
a_users_speed_limit_paces_their_traffic |
The user’s speed_limit is 8 Mbps, 1,000,000 B/s; 1,500,000 bytes echoed each way |
The 3,000,000 bytes, against a 1,000,000-byte burst, take at least 1.5 s |
a_helium_node_without_enable_device_limit_reports_no_addresses |
A plain-TCP VMess node of a fake helium node API v2 (helium_node, fake_helium), without enable_device_limit; a client relayed for 203.0.113.8 echoes through it |
Traffic is reported, with every ips list empty |
All metering assertions are lower bounds on payload, because wire bytes exceed payload. They show that bytes are reported under the right uid; they do not check exact byte counts.
Unit tests:
| File | Test | What it pins |
|---|---|---|
tests/unit/lower/spec.rs |
a_user_is_held_to_their_speed_limit |
UserSpec::speed_limit in the lowered spec: None for a user’s limit of zero, otherwise the user’s limit |
tests/unit/api/newv2board.rs |
user_response_speed_limit_and_email |
mbps_to_bps(10.0) == 1_250_000 |
tests/unit/api/newv2board.rs |
push_body_shape |
A HashMap<String, [i64; 2]> serializes to {"<uid>": [upload, download]}. It builds the map itself and does not call report_user_traffic |
tests/unit/api/helium.rs |
the_report_body_is_the_crates_wire_form |
report_body writes the crate’s Report wire form, report_id, agent_version (katana’s version), traffic and ips, and the text reads back as the same Report |
tests/unit/api/helium.rs |
an_out_of_range_uid_or_a_negative_count_is_left_out |
Rows with a uid outside i32 or a negative count, and an ips entry with a uid outside i32, are left out; the warnings name those uids and none of their counts or addresses |
tests/unit/api/helium.rs |
users_are_held_to_the_answers_limits |
The answer’s limits reach every user, the speed limit in bytes per second and the device limit as sent; 0 stays no limit |
tests/unit/api/helium.rs |
the_local_speed_override_wins |
An 8 Mbps speed_limit makes every user’s limit 1,000,000 B/s; the device limit stays the panel’s |
Integration tests in tests/integration/xray_interop.rs run the real katana binary against a real Xray client, across VMess over TCP, WebSocket and gRPC, VMess over TCP with TLS, VLESS over WebSocket and gRPC with TLS, Trojan over TCP with TLS, and three mux.cool variants. Each checks that the echoed bytes match and that the panel’s totals for the user, polled by FakePanel::wait_for_traffic (tests/support/mod.rs) for up to 15 seconds, are above zero both ways. They skip themselves when the Xray-core source or go is missing, or when Xray does not build. tests/integration/hysteria_interop.rs relays through katana with the upstream Hysteria client and makes no traffic assertion.
Not covered by any katana test: disable_upload_traffic, the final report’s contents, and the per-uid sum in take_traffic on its own. A change to report or take_traffic should come with a test against a fake panel. The supervisor’s own tests of the ledger, the pacer and the usage sink are listed on Per-user usage accounting and Tracking. See Testing for how to run the suites.