Runtime State Machines¶
This index covers the runtime state machines in the wind Cargo workspace and identifies which component owns each transition. On a single connection, sending, receiving, and authentication progress independently; to diagnose a stalled flow, identify which event the caller is waiting on and inspect the component responsible for producing it.
See Formal Verification for the properties formally proved about these transitions and their runtime assumptions.
Connections and Streams¶
| Owner | Source | Transitions and observable behavior |
|---|---|---|
Bidirectional TCP relay & per-direction Phase |
wind-core/src/io.rswind-core/src/io/direction.rs |
Each direction cycles independently through Reading → Writing → Reading; short writes preserve the offset for the next attempt. EOF moves a direction through ShuttingDown → Done. With a non-zero timeout, HalfCloseTimer moves from AwaitingEof to Armed on the first EOF, covering pending writes and shutdowns in both directions; zero selects Disabled; progress in either direction resets the deadline. |
Quiche handshake HandshakeState |
wind-quic/src/quiche/driver.rs |
Negotiating owns the connection handle and delivery oneshot. The handshake callback enforces ECH checks and records negotiated parameters before entering Established. On close, the driver saves final traffic counters before waking callers awaiting closed(). |
Quiche receive half ReceivePhase |
wind-quic/src/quiche/driver.rs |
Open transitions to FinPending or ResetPending(code). Readers receive all buffered bytes before observing either terminal event. Reset codes require a channel slot, so the driver retains them until space opens; dropping the sender exposes EOF. |
Quiche send half SendPhase |
wind-quic/src/quiche/driver.rs |
Streams without a local sender start in Absent. Graceful close follows Open → Draining → Finished, sending FIN once queued bytes drain. Explicit RESET jumps to Failed; write errors enter FailedPendingFin for cleanup and best-effort FIN. At the outbound queue cap, Backpressured parks the receiver until queue depth drops back to Open. |
| HTTP/3 adapter & prefix replay | wind-quic/src/h3_adapter.rswind-quic/src/prefixed.rs |
H3Send.pending holds partially written frames and flushes before accepting another frame or finishing the stream. Bi/uni openers keep independent OpenAttempt slots whose Opening state retains the same future across polls until returning to Idle. PrefixedRecv replays bytes consumed during protocol classification before reading the underlying stream. |
| Quinn shared UDP socket | wind-quic/src/quinn/udp.rs |
On transient peer network errors, retry holds a backoff timer and resumes receiving on expiry; local socket errors propagate immediately. |
TUIC server auth AuthState |
wind-tuic/src/server/mod.rswind-tuic/src/server/authentication.rs |
Admits up to 3 Authenticate commands within the original deadline. In Pending, commands are evaluated in admission order and excess commands are discarded; unknown users or bad tokens consume one attempt, allowing two retries before closing on the third failure. Success publishes Authenticated(user), wakes waiting streams, and discards queued attempts. Post-auth Authenticate, TLS errors, or hook vetoes close the connection; Closed retains published identity for on_disconnect and blocks late publications. |
| TUIC stream classification & HTTP/3 masquerade | wind-tuic/src/server/mod.rswind-tuic/src/server/masquerade.rs |
Leading bytes classify TUIC (0x05) vs. HTTP/3. Routing the first HTTP/3 stream flips shared H3Phase from Parked to Active, observed by both the HTTP/3 service and auth timeout check. Cancelling the connection stops its accept loops and child tasks. |
| TUIC client session & reconnect | wind-tuic/src/client/session.rswind-tuic/src/{quinn,quiche}/outbound.rs |
Session starts after dial and authentication. A successful heartbeat resets consecutive failures; the third consecutive failure or connection close yields Lost; Shutdown stops the supervisor. Both backends begin every reconnect episode in ReconnectPhase::DialImmediately, waiting initial_backoff after the first failure and doubling up to max_backoff. Shutdown cancels dialing or backoff; only a successful dial swaps the published connection. Quinn retains the last resolved peer; Quiche caches session tickets when early data is enabled. |
| HTTP & SOCKS inbound | wind-socks/src/inbound.rswind-socks/src/http.rs |
Fixed Http and Socks5 modes dispatch immediately; Socks and Mixed peek one byte to choose SessionProtocol. Only Socks5Admission::Admitted reaches command processing. HTTP validates auth on every request when required; valid CONNECT moves HttpPhase from Forwarding to UpgradePending awaiting Hyper's upgraded stream. Closing the TCP control connection ends its UDP association. |
| SOCKS5 inbound UDP peer pinning | wind-socks/src/udp.rs |
Client IP is preset or pinned on the first observed datagram. Valid, unfragmented, within-limit datagrams publish their source as the reply endpoint; source port 0 clears it (leaving replies without a destination); later valid datagrams from the same IP may update the port. |
SOCKS5 UDP outbound AssociationState |
wind-socks/src/udp_outbound.rs |
Initial negotiation errors return to the caller. Losing an established association terminates or enters Reconnecting per config; packets arriving during backoff or renegotiation are discarded; success returns to Relaying. Closing input stops retries; cancellation or dropped reply receiver ends the association. |
| Naive TCP & UoT v2 | wind-naive/src/lib.rs |
Subsequent connections reuse the first Cronet library dynamically loaded by the process. TCP half-closes independently per direction; UoT v2 waits for the first datagram before opening CONNECT, then writes the request header and relays frames. CancelOnDrop propagates cancellation to the native stream; JoinSession hands blocking threads to cleanup. |
Application, Routing, and Resources¶
| Owner | Source | Transitions and observable behavior |
|---|---|---|
| Config resolution & plugin assembly | wind/src/conf/resolved.rswind/src/plugin.rs |
Resolves persisted config into typed runtime form. Load-balance groups enter the build queue once all dependencies are ready; missing references or cycles fail startup; the first declared outbound is the default. |
| Application & inbound lifecycle | wind-core/src/app.rswind-core/src/inbound.rs |
After starting inbounds, waits for signal or cancellation, then cancels child tasks and drains up to the shutdown deadline. Every started listener is owned by RunningInbound, releasing early listeners automatically if startup is aborted. |
Traffic flush FlushOutcome |
wind-core/src/hooks/stats.rswind-core/src/app.rs |
Atomically claims counter drain rights: empty batches yield Idle, successful submissions yield Delivered, failures restore counters losslessly and yield Restored. Shutdown retries restored batches a bounded number of times. |
| Active connections | wind-core/src/active.rs |
Registration increments the user's count; kicking requests cancellation; deregistration decrements; reusing a conn_id transfers the count to the new registration. |
| UDP dispatch, tunnel & direct outbound | wind-core/src/dispatcher.rswind-base/src/tunnel.rswind-base/src/direct.rs |
Dispatcher waits for the first datagram, routes, replays it, and validates subsequent packets. Connected tunnels serve one peer; multi-peer UDP tunnels drop new sources at capacity, drop packets on full channels, prune closed entries, and GC idle entries. Direct UDP send/receive loops share a session lifetime so either exiting stops the other. |
| Lazy outbound & load balancing | wind-base/src/lazy.rswind-base/src/load_balance.rs |
LazyState holds the init future, ready outbound, or permanent failure; if the first caller cancels, the next caller resumes the same future. HealthChecks spawns one probe task on first start and cancels active probes on drop. All-unhealthy falls back to the full child set; sticky TCP entries live up to 10 minutes while the child remains healthy. |
| TUIC server UDP & reassembly | wind-tuic/src/server/mod.rswind-tuic/src/udp/runtime.rs |
Cache owns each association; dissociation, eviction, or shutdown cancels its tasks. FragmentGroup keys on (assoc_id, pkt_id); only unseen fragment IDs decrement the missing count while duplicates overwrite their slot; complete groups are removed under lock and assembled in ID order. Cleanup expires aged groups and evicts the least recently updated group at capacity; reusing a removed key starts empty. |
| TUIC client UDP association | wind-tuic/src/client/association.rswind-tuic/src/client/association/slots.rswind-tuic/src/proto/udp_stream.rs |
RegisteredAssociation atomically reserves an unused 16-bit ID and holds the connection it registered on. Channel close, send error, or cancellation stops forwarding; cleanup attempts to send Dissociate on the original connection (up to 5 seconds if the caller drops, cut short on global shutdown) before releasing the ID. Relay mode and peer capability determine DATAGRAM vs. uni-stream transport. |
| ACME resolver & file-backed HTTP-01 | wind-acme/src/resolver.rswind-acme/src/http01.rs |
Resolver tracks rustls-acme events. File-backed callers provision once (ensure_acme_cert) or subscribe (watch_acme_cert): valid caches inside the renewal window start in RenewalCheck::Due, switching to Daily on success or hourly Retry on failure while serving the existing pair. Installation stages both files, writes the key first, rolls back if cert install fails, and publishes only matched pairs. Dropping the last receiver stops the watcher and challenge server. |
| Quiche certificate rotation | wind-quic/src/quiche/tls.rs |
CertStore::update validates and parses the new cert/key pair before publishing atomically; parse failures keep serving the previous certificate. |
| ACL evaluation & rules | wind-acl/src/eval.rswind-rule/src/lib.rs |
Resolution distinguishes forward, reject, drop, chain return, and chain exhaustion; calling chains continue evaluation or emit the final route. |
| DNS & GeoData snapshots | wind-dns/src/resolver.rswind-geodata/src/lib.rs |
Hickory executes queries while Wind handles literal IPs and stack filtering. GeoData writes a separate temp file, atomically renames, mmaps, and validates offsets and ordering before serving queries. |
Tracing a Stalled Transition¶
| Symptom | What to inspect | Local regression test |
|---|---|---|
| A TCP relay stays open after one peer sends FIN | Check whether the reverse direction is still making progress; a non-zero half-close timer fires only after both directions stop progressing | cargo test -p wind-core --lib half_close |
| A SOCKS5 or HTTP client never reaches its target | Check the SOCKS5 admission reply, or the HTTP auth result and CONNECT upgrade handoff |
cargo test -p wind-socks --test socks_tcp |
| A TUIC peer disappears | First replacement dial should start immediately; subsequent retries follow exponential backoff | cargo test -p wind-tuic --lib redial |
| An HTTP/3 stream fails to open or a quiche writer stalls | A pending open must resume the same future; a backpressured writer waits for the driver queue to fall below its cap | cargo test -p wind-quic --features h3,quiche --lib |
| Certificate renewal fails | Watcher should keep serving the active pair and retry hourly; pending orders must register challenge responses before marking ready | cargo test -p wind-acme --features http01 --lib renewal |
Cross-crate data-plane tests live in crates/wind-test/. Per-transition regressions live alongside their implementations (such as wind-socks/tests/udp_source_check.rs and wind-socks/src/udp_outbound/tests.rs).