docs(handler/tunnel): add architecture documentation and fix observeStats event loss

- Add package-level architecture doc in handler.go covering:
  - NAT traversal reverse proxy architecture
  - CmdBind/CmdConnect roles and data flow
  - Connector lifecycle and waitClose semantics
  - Entrypoint protocol dispatch (first-byte sniffing)
  - SD fallback behavior
- Add data-flow-oriented doc comments to all business files:
  - entrypoint.go: protocol dispatch, dial flow
  - connector.go: Connector/ConnectorPool semantics
  - dialer.go: two-phase dial strategy
  - tunnel.go: MaxWeight semantics, selection algorithm
  - bind.go: 6-step CmdBind flow
  - connect.go: CmdConnect flow with relay framing
  - ephttp.go, eptls.go, eprelay.go: per-protocol entrypoint flow
- Fix observeStats: after successful error retry, also flush new events
  instead of skipping the current tick (handler.go:261-271)
- Add test for observeStats retry-then-flush (handler_test.go)
This commit is contained in:
ginuerzh
2026-06-02 18:36:52 +08:00
parent e791ba47e2
commit 31878a72ec
12 changed files with 264 additions and 3 deletions
+26
View File
@@ -13,6 +13,32 @@ import (
xnet "github.com/go-gost/x/internal/net"
)
// handleConnect handles a CmdConnect request.
//
// This is the "pull" path: a public user's connection arrives via the tunnel
// handler's listener, and the handler creates a stream into the tunnel to
// reach the internal service.
//
// Flow:
// 1. Bypass check against dstAddr.
// 2. Ingress routing: if the tunnel is the public entryPointID, look up the
// destination host in the ingress table to find the target tunnel ID.
// For direct tunnels, the tunnelID from the request is used directly.
// 3. Dialer.Dial() → pool.Get() → GetConn() → mux.OpenStream()
// (or SD fallback if no local connector).
// 4. Relay protocol framing:
// a. Local node (node == h.id): write StatusOK response to the public
// connection, then write a StatusOK response with src/dst address
// features to the mux stream. The internal client uses these address
// features to know where to connect.
// b. Remote node (SD fallback): write the original relay request
// directly to the mux stream for the remote node to process.
// 5. Pipe(publicConn, muxStream) — bidirectional data relay until either
// side closes.
//
// The mux stream (cc) is closed via defer cc.Close() when this function
// returns. The public connection (conn) is closed by the caller's
// defer conn.Close() in Handle().
func (h *tunnelHandler) handleConnect(ctx context.Context, req *relay.Request, conn net.Conn, network, srcAddr string, dstAddr string, tunnelID relay.TunnelID, log logger.Logger) error {
log = log.WithFields(map[string]any{
"dst": fmt.Sprintf("%s/%s", dstAddr, network),