Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Architecture

rs-netty 的主路径可以按四层理解:transport、pipeline runtime、stage traits、channel/context。

Crate Layout

  • src/lib.rs:公开模块和常用类型 re-export。
  • src/traits.rsInboundBusinessHandlerDatagramHandlerOutboundFlow
  • src/pipeline/stream:TCP typed builder 和 runtime pipeline。
  • src/pipeline/datagram:UDP typed builder 和 runtime pipeline。
  • src/pipeline/core:共享的 IdentityThen、stage pipe traits 和 builder state marker。
  • src/codec:stream/datagram codec traits 和内置 codec。
  • src/context:stage context、handler context、stats 和 identity 信息。
  • src/channel:外部写入 handle,以及内部 command enum。
  • src/tls.rstls feature 下的 TLS context builder 和 server/client context。
  • src/transport/tcp:TCP server、client、connection runtime 和配置。
  • src/transport/udp:UDP server、client、socket runtime 和配置。
  • src/life.rs:lifecycle hook trait 和 close reason。
  • rs-netty-macros#[handler] attribute macro。

TCP Runtime Flow

TCP server 每个 accepted connection 都会调用 pipeline factory,创建独立 pipeline 实例。client 可以使用可复用 factory,也可以用 pipeline_instance 消耗一个单次 pipeline。

运行时大致流程:

TcpListener / TcpStream
  -> optional TLS accept/connect
  -> read_buf
  -> Decoder::decode
  -> InboundPipe
  -> BusinessPipe
  -> Handler::read(Context<W>, msg)
  -> Context outbox or Channel command queue
  -> OutboundPipe
  -> Encoder::encode
  -> write_buf
  -> flush/write_all

StreamConnectionRuntime 负责 select socket read、external channel command 和 shutdown signal。没有 idle timeout 时走 no-timeout loop;配置了 idle_timeout 时增加一个 read-idle timer。这个 timer 只由 socket read 重置,外部 outbound write 不重置。

UDP Runtime Flow

UDP server/client 都围绕一个 socket task 运行,pipeline 是 socket-level 的:

UdpSocket::recv_from
  -> DatagramDecoder::decode_datagram
  -> InboundPipe
  -> BusinessPipe
  -> DatagramHandler::read(DatagramContext<W>, msg)
  -> DatagramContext outbox or DatagramChannel command queue
  -> OutboundPipe
  -> DatagramEncoder::encode_datagram
  -> pending_datagrams
  -> flush/send_to

UDP server 目前不为每个 peer 创建 child pipeline。需要 per-peer state 时,handler 应自己维护 HashMap<SocketAddr, State> 之类的结构。

Static Stage Composition

builder 在类型层面把 stage 串成 Then<A, B>Identity 表示没有该方向的 stage。运行时的 InboundPipeBusinessPipeOutboundPipe 递归处理 Then

  • 前一个 stage 返回 Flow::Next(value) 时,继续传给后一个 stage。
  • 返回 Flow::Stop 时,当前消息方向停止,不视为错误。
  • 返回 Err 时,连接或 socket runtime 将错误映射为 decode/encode/handler/runtime 错误。

主路径不需要动态 Box<dyn Handler> pipeline 分发;pipeline 类型由泛型静态组合出来。

Channel And Context

Context<W>DatagramContext<W> 是 final handler 里的写入入口。它们持有 handler-local outbox,适合在同一次 read 内进行多次写入和控制 flush 边界。

Channel<W>DatagramChannel<W> 是 cloneable external handle。它们通过 bounded Tokio mpsc 把命令发送给 connection/socket task。TCP channel 暴露 stats()capacity()max_capacity()is_closed();UDP channel 暴露 socket id/local addr 和 queue 状态。