Files
lmvpn_client/internal/stats/stats.go
T
kevin 7b4289ae00 feat: 路由模式重构(full/proxy/bypass) + CIDR动态URL获取 + 命中统计 + 连接稳定性修复
路由模式与CIDR配置重构:
- 路由模式从 full/split/custom 改为 full/proxy/bypass,移除 split 和 custom
- CIDR 按 IPv4/IPv6 分开配置,支持静态 CIDR + URL 动态获取
- URL 支持"代理前获取"(直连)和"代理后获取"(走隧道)两种时机
- 数据库迁移 v5 自动转换旧数据(custom_cidrs 拆分为 cidr_v4/v6,custom->proxy,split->full)

CIDR命中统计:
- 状态栏显示当前路由模式及 IPv4/IPv6 CIDR 命中数
- 代理模式: 显示命中/总数; 绕过模式: 显示已配置数 + 未命中目的地址数
- cidrTracker 在 pumpPackets 中逐包检查出站目的IP

连接稳定性修复(多轮):
- transport.Connect 添加 ctx 监听 goroutine,取消时关闭WS中断阻塞的ReadMessage
- auth.Login 加 context.Context 参数,可被 cancel 中断
- Disconnect() 先删路由再关TUN,避免断网窗口
- startSession 在 Connect 前释放 d.mu,避免锁持有过久
- onConnect 移除 SendStop 消除竞态
- before-proxy CIDR 获取移到 run 循环前,并行获取+5s超时,重连复用
- cidrTracker 加 RWMutex 防数据竞争

UI修复:
- CIDR URL 输入框改为水平滚动+纵向布局,防止撑宽窗口
- 路由模式为full时隐藏CIDR配置区域
2026-07-09 08:21:47 +08:00

171 lines
4.8 KiB
Go

// Package stats provides atomic counters for VPN session statistics.
package stats
import (
"sync/atomic"
"time"
)
// State represents the current VPN session state.
type State string
const (
StateDisconnected State = "disconnected"
StateConnecting State = "connecting"
StateConnected State = "connected"
StateReconnecting State = "reconnecting"
StateError State = "error"
)
// Stats holds live session statistics. Counters are atomic for
// lock-free reads from the UI/IPC layer.
//
// Counters are split by IP address family (v4/v6) at the recording
// site via AddRx/AddTx, which inspect the IP version nibble. The
// combined RxBytes/TxBytes are derived as the sum of the per-family
// counters in Snapshot, so callers that only need the total still
// work.
type Stats struct {
RxBytesV4 atomic.Int64
RxBytesV6 atomic.Int64
TxBytesV4 atomic.Int64
TxBytesV6 atomic.Int64
ConnectedAt atomic.Int64 // unix timestamp, 0 = not connected
state atomic.Value // State
assignedIP atomic.Value // string (IPv4)
assignedIP6 atomic.Value // string (IPv6, may be empty)
}
// AddRx records a downloaded packet (WebSocket → TUN) of length n,
// routing the bytes to the v4 or v6 counter based on the IP version
// nibble of the packet. Packets too short to contain a version byte
// or with an unknown version are ignored.
func (s *Stats) AddRx(p []byte) {
if len(p) == 0 {
return
}
n := int64(len(p))
switch p[0] >> 4 {
case 4:
s.RxBytesV4.Add(n)
case 6:
s.RxBytesV6.Add(n)
}
}
// AddTx records an uploaded packet (TUN → WebSocket) of length n,
// routing the bytes to the v4 or v6 counter based on the IP version
// nibble of the packet. Packets too short to contain a version byte
// or with an unknown version are ignored.
func (s *Stats) AddTx(p []byte) {
if len(p) == 0 {
return
}
n := int64(len(p))
switch p[0] >> 4 {
case 4:
s.TxBytesV4.Add(n)
case 6:
s.TxBytesV6.Add(n)
}
}
// New creates a Stats instance initialised to the disconnected state.
func New() *Stats {
s := &Stats{}
s.state.Store(StateDisconnected)
s.assignedIP.Store("")
s.assignedIP6.Store("")
return s
}
// SetState updates the current state atomically.
func (s *Stats) SetState(st State) { s.state.Store(st) }
// State returns the current state.
func (s *Stats) State() State { return s.state.Load().(State) }
// SetConnected marks the session as connected, recording the time and
// assigned IP addresses. ip6 may be empty for an IPv4-only server.
func (s *Stats) SetConnected(ip, ip6 string) {
s.ConnectedAt.Store(time.Now().Unix())
s.assignedIP.Store(ip)
s.assignedIP6.Store(ip6)
s.state.Store(StateConnected)
}
// SetDisconnected clears the connection metadata.
func (s *Stats) SetDisconnected() {
s.ConnectedAt.Store(0)
s.assignedIP.Store("")
s.assignedIP6.Store("")
s.state.Store(StateDisconnected)
}
// AssignedIP returns the server-assigned tunnel IPv4.
func (s *Stats) AssignedIP() string { return s.assignedIP.Load().(string) }
// AssignedIP6 returns the server-assigned tunnel IPv6 (may be empty).
func (s *Stats) AssignedIP6() string { return s.assignedIP6.Load().(string) }
// Snapshot returns a point-in-time copy of all counters.
//
// Per-family byte counters are read directly. The combined RxBytes/
// TxBytes are derived as v4+v6. Speed fields (RxSpeedV4 etc.) are
// left zero here; the SessionManager fills them in by computing
// per-tick deltas with EWMA smoothing.
type Snapshot struct {
RxBytesV4 int64
RxBytesV6 int64
TxBytesV4 int64
TxBytesV6 int64
RxBytes int64 // combined (v4+v6)
TxBytes int64 // combined (v4+v6)
// Speeds in bytes/sec (EWMA-smoothed). The UI converts to bits/sec.
RxSpeedV4 int64
TxSpeedV4 int64
RxSpeedV6 int64
TxSpeedV6 int64
RxSpeed int64 // combined
TxSpeed int64 // combined
ConnectedAt time.Time
AssignedIP string
AssignedIP6 string
State State
Uptime time.Duration
// Routing info (filled by SessionManager.reportStats).
RoutingMode string `json:"routing_mode,omitempty"` // "full", "proxy", "bypass"
CIDRV4Total int `json:"cidr_v4_total,omitempty"`
CIDRV4Hits int `json:"cidr_v4_hits,omitempty"`
CIDRV6Total int `json:"cidr_v6_total,omitempty"`
CIDRV6Hits int `json:"cidr_v6_hits,omitempty"`
}
// Snapshot returns a point-in-time copy of the statistics.
func (s *Stats) Snapshot() Snapshot {
rxv4 := s.RxBytesV4.Load()
rxv6 := s.RxBytesV6.Load()
txv4 := s.TxBytesV4.Load()
txv6 := s.TxBytesV6.Load()
snap := Snapshot{
RxBytesV4: rxv4,
RxBytesV6: rxv6,
TxBytesV4: txv4,
TxBytesV6: txv6,
RxBytes: rxv4 + rxv6,
TxBytes: txv4 + txv6,
AssignedIP: s.AssignedIP(),
AssignedIP6: s.AssignedIP6(),
State: s.State(),
}
ts := s.ConnectedAt.Load()
if ts > 0 {
snap.ConnectedAt = time.Unix(ts, 0)
snap.Uptime = time.Since(snap.ConnectedAt)
}
return snap
}