554708a092
修复:数据面挂了客户端无感。原看门狗探 generate_204,会被分流判 direct 走本地 出网假阳性,永不触发。改为三路融合判活,针对「实际所连节点」(_connectedNode, 非会随 ping 漂移的 effectiveNode): ① 客户端→数据口 TCP 握手(节点 host:443,TUN 内必 direct→直奔真实节点,不被分流糊弄); ② 延迟同源:①的 RTT 回填连接页延迟(ConnectionState.livePingMs),挂了掉成 —; ③ 服务端权威:刷 /v1/nodes,所连节点被判 down(dp_healthy=0/agent掉线/运维下线)即处理。 看门狗即时首测 + 周期 15s;连续 3 次握不上 / 服务端 down → 智能切节点 / 手动告警断开。 连接页延迟改读 livePingMs(删除内核 urltest 取数)。补信号③测试。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
363 lines
15 KiB
Dart
363 lines
15 KiB
Dart
// connection_provider.dart — 连接状态机(严格三态,状态由内核事件驱动)
|
|
//
|
|
// 设计约定:
|
|
// - UI 调用 toggle(),控制器内部读取有效节点 + 认证令牌,调用 ConnectApi
|
|
// 并启动 VpnBridge 子进程。
|
|
// - 严禁乐观翻转:VpnPhase.on 必须由 bridge.statusStream 确认后才置。
|
|
// - 状态来源:bridge.statusStream(来自内核回调),非 Timer 模拟。
|
|
import 'dart:async';
|
|
|
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
|
|
import '../bridge/log.dart';
|
|
import '../bridge/vpn_bridge.dart';
|
|
import '../bridge/vpn_bridge_provider.dart';
|
|
import '../l10n/app_text.dart';
|
|
import '../models/node.dart';
|
|
import '../services/api_config.dart';
|
|
import '../services/connect_api.dart';
|
|
import '../services/device_identity.dart';
|
|
import '../services/latency_probe.dart';
|
|
import 'app_providers.dart';
|
|
import 'auth_provider.dart';
|
|
import 'nodes_provider.dart';
|
|
import 'settings_provider.dart';
|
|
|
|
// 设备 ID 由 deviceIdentityProvider 提供(secure storage 持久化的稳定 UUID)。
|
|
// API base URL 统一用 api_config.dart 的 kApiBaseUrl(单一来源,勿再重复声明)。
|
|
|
|
// ── 连接阶段枚举 ──────────────────────────────────────────────────
|
|
|
|
/// 连接阶段。严格三态,与设计稿一致。
|
|
enum VpnPhase { off, connecting, on }
|
|
|
|
// ── 连接状态快照 ──────────────────────────────────────────────────
|
|
|
|
class ConnectionState {
|
|
const ConnectionState(
|
|
{required this.phase, this.elapsed = Duration.zero, this.error, this.livePingMs});
|
|
|
|
final VpnPhase phase;
|
|
final Duration elapsed;
|
|
|
|
/// 连接失败原因(已本地化);null = 无错误。供 UI 提示,不再静默吞掉。
|
|
final String? error;
|
|
|
|
/// 连接期实测延迟(ms):看门狗周期性对数据面 IP(节点 host:443)做 TCP 握手得到。
|
|
/// >0 = 可达 RTT;0 = 数据口不可达(UI 显示 —);null = 尚未测。与看门狗同源(见下)。
|
|
final int? livePingMs;
|
|
|
|
/// 注意:error 不随 copyWith 传递(瞬时提示用毕即弃);livePingMs 默认沿用(计时器
|
|
/// 每秒 copyWith(elapsed:) 不应清掉延迟)。要改延迟显式传 livePingMs。
|
|
ConnectionState copyWith({VpnPhase? phase, Duration? elapsed, int? livePingMs}) =>
|
|
ConnectionState(
|
|
phase: phase ?? this.phase,
|
|
elapsed: elapsed ?? this.elapsed,
|
|
livePingMs: livePingMs ?? this.livePingMs,
|
|
);
|
|
|
|
@override
|
|
bool operator ==(Object other) =>
|
|
other is ConnectionState &&
|
|
other.phase == phase &&
|
|
other.elapsed == elapsed &&
|
|
other.error == error &&
|
|
other.livePingMs == livePingMs;
|
|
|
|
@override
|
|
int get hashCode => Object.hash(phase, elapsed, error, livePingMs);
|
|
}
|
|
|
|
// ── 连通看门狗 ─────────────────────────────────────────────────────
|
|
//
|
|
// 已连接(本地 TUN 已起)≠ 远端节点数据面可用。看门狗周期性融合三路信号判活,任一
|
|
// 命中即判当前所连节点不可用 → 智能选择自动切节点 / 手动选定的只断开提示:
|
|
// ① 客户端→数据口 TCP 可达性:直连节点 host:443(REALITY 数据口)做 TCP 握手。
|
|
// 节点 IP 在 TUN 内必判 direct(否则代理连自己死循环)→ 探测走物理网卡直奔真实
|
|
// 节点,不被分流糊弄。连续 N 次握不上 = 本客户端到数据口不通(覆盖 ISP/GFW 封端口/IP
|
|
// 等服务端看不到的 per-client 链路问题)。兼测延迟(②)。
|
|
// ② 延迟同源:①的握手 RTT 即连接页延迟,挂了掉成 — 本身就是可视信号。
|
|
// ③ 服务端权威健康:刷 /v1/nodes,所连节点被判 down(dp_healthy=0 / agent 掉线 /
|
|
// 运维下线)即处理。覆盖「443 还开着但节点失管/被下线/凭证推不下去」等 TCP 探不到的。
|
|
// 关键:探测/判活针对「实际所连节点」(_connectedNode),非 effectiveNode——智能模式下
|
|
// effectiveNode 会随 ping 变化自动飘到别的节点,会漏判当前节点已挂。
|
|
|
|
/// 数据面探测接缝:对节点数据口 (host, port=REALITY 443) 做 TCP 握手,返回 RTT(ms),
|
|
/// 0=不可达。默认走 latency_probe;测试可注入假实现。看门狗判活 + 连接页延迟两用,单一口径。
|
|
typedef DataPlaneProber = Future<int> Function(String host, int port);
|
|
|
|
const _kWatchdogInterval = Duration(seconds: 15);
|
|
const _kHealthFailLimit = 3; // 连续 N 次握不上(≈45s)才判定不可用,防抖
|
|
|
|
// ── 状态机 ───────────────────────────────────────────────────────
|
|
|
|
class ConnectionController extends StateNotifier<ConnectionState> {
|
|
ConnectionController(this._ref, this._bridge, {DataPlaneProber? prober})
|
|
: _prober = prober ?? probeLatency,
|
|
super(const ConnectionState(phase: VpnPhase.off)) {
|
|
// 订阅桥状态流:状态由内核事件驱动,严禁 UI 乐观翻转。
|
|
_statusSub = _bridge.statusStream.listen(_onKernelStatus);
|
|
}
|
|
|
|
final Ref _ref;
|
|
final VpnBridge _bridge;
|
|
final DataPlaneProber _prober;
|
|
StreamSubscription<VpnStatus>? _statusSub;
|
|
Timer? _elapsed;
|
|
Timer? _watchdog;
|
|
int _healthFails = 0;
|
|
bool _probing = false;
|
|
ConnectApi? _api;
|
|
// 实际所连节点(连接时锁定):看门狗探测/判活针对它,而非会随 ping 漂移的 effectiveNode。
|
|
Node? _connectedNode;
|
|
|
|
// ── 公有 API ───────────────────────────────────────────────────
|
|
|
|
/// 用户点击连接键:按当前状态决定动作,握手中忽略(禁乐观)。
|
|
void toggle() {
|
|
switch (state.phase) {
|
|
case VpnPhase.off:
|
|
_connect();
|
|
case VpnPhase.on:
|
|
_disconnect();
|
|
case VpnPhase.connecting:
|
|
break; // 握手进行中,不响应
|
|
}
|
|
}
|
|
|
|
/// 节点切换时触发:已连接则重连。
|
|
void onNodeChanged() {
|
|
if (state.phase == VpnPhase.on || state.phase == VpnPhase.connecting) {
|
|
_disconnect().then((_) => _connect());
|
|
}
|
|
}
|
|
|
|
// ── 内部 ─────────────────────────────────────────────────────
|
|
|
|
Future<void> _connect() async {
|
|
state = const ConnectionState(phase: VpnPhase.connecting);
|
|
|
|
final node = _ref.read(effectiveNodeProvider);
|
|
final zh = _ref.read(localeProvider) == AppLang.zh;
|
|
logLine('Connect', '_connect node=${node.code} uuid=${node.uuid.isEmpty ? "EMPTY" : "ok"} '
|
|
'selected=${_ref.read(selectedNodeCodeProvider)} nodes=${(_ref.read(nodesProvider).valueOrNull ?? const []).length}');
|
|
|
|
// 节点未就绪(列表加载中/为空):不连接,提示用户。
|
|
if (node.uuid.isEmpty) {
|
|
if (mounted) {
|
|
state = ConnectionState(
|
|
phase: VpnPhase.off,
|
|
error: zh ? '节点尚未就绪,请稍候重试' : 'Nodes not ready, please retry',
|
|
);
|
|
}
|
|
return;
|
|
}
|
|
|
|
_connectedNode = node; // 锁定本次实际所连节点,供看门狗探测/判活
|
|
try {
|
|
final configJson = await _fetchConfigWithRefresh(node.uuid);
|
|
// bridge.start() 不阻塞至连接建立;on 状态由 statusStream 回调驱动。
|
|
await _bridge.start(configJson);
|
|
} on ConnectApiException catch (e) {
|
|
// 把后端/网络错误冒泡到 UI(原静默回 off,用户不知所以)。
|
|
if (mounted) state = ConnectionState(phase: VpnPhase.off, error: zh ? e.messageZh : e.messageEn);
|
|
} catch (e) {
|
|
if (mounted) {
|
|
state = ConnectionState(
|
|
phase: VpnPhase.off,
|
|
error: zh ? '连接失败,请重试' : 'Connection failed, please retry',
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 取配置;access token 过期(401)时用 refresh token 续期后**重试一次**。
|
|
/// 续期失败(refresh 也过期 / 被拒)由 authProvider.refresh() 触发登出 → UI 回登录页。
|
|
Future<String> _fetchConfigWithRefresh(String nodeUuid) async {
|
|
final deviceId = await _ref.read(deviceIdentityProvider).deviceId();
|
|
Future<String> doFetch() {
|
|
final token = _ref.read(authProvider).accessToken ?? '';
|
|
_api?.dispose();
|
|
_api = _ref.read(connectApiFactoryProvider)(token);
|
|
return _api!.fetchConfig(
|
|
nodeId: nodeUuid,
|
|
deviceId: deviceId,
|
|
// smartRoute 偏好 → 国内分流(#5):国内 IP/域名直连,不走隧道。
|
|
splitCN: _ref.read(settingsProvider).smartRoute,
|
|
);
|
|
}
|
|
|
|
try {
|
|
return await doFetch();
|
|
} on ConnectApiException catch (e) {
|
|
if (e.statusCode == 401) {
|
|
// token 过期 → 续期后重试一次;续期成功则用新 token 再取。
|
|
final ok = await _ref.read(authProvider.notifier).refresh();
|
|
if (ok) return await doFetch();
|
|
}
|
|
rethrow;
|
|
}
|
|
}
|
|
|
|
Future<void> _disconnect() async {
|
|
_stopElapsed();
|
|
try {
|
|
await _bridge.stop();
|
|
} catch (_) {}
|
|
if (mounted) state = const ConnectionState(phase: VpnPhase.off);
|
|
}
|
|
|
|
void _onKernelStatus(VpnStatus s) {
|
|
if (!mounted) return;
|
|
switch (s) {
|
|
case VpnStatus.on:
|
|
state = state.copyWith(phase: VpnPhase.on);
|
|
_startElapsed();
|
|
_startWatchdog();
|
|
case VpnStatus.connecting:
|
|
state = state.copyWith(phase: VpnPhase.connecting);
|
|
_stopElapsed();
|
|
_stopWatchdog();
|
|
case VpnStatus.off:
|
|
case VpnStatus.error:
|
|
state = const ConnectionState(phase: VpnPhase.off);
|
|
_stopElapsed();
|
|
_stopWatchdog();
|
|
}
|
|
}
|
|
|
|
// ── 连通看门狗 ───────────────────────────────────────────────
|
|
void _startWatchdog() {
|
|
_watchdog?.cancel();
|
|
_healthFails = 0;
|
|
_watchdog = Timer.periodic(_kWatchdogInterval, (_) => _checkHealth());
|
|
unawaited(_checkHealth()); // 立即测一次:尽快回填延迟 + 早发现数据面异常
|
|
}
|
|
|
|
void _stopWatchdog() {
|
|
_watchdog?.cancel();
|
|
_watchdog = null;
|
|
_healthFails = 0;
|
|
_probing = false;
|
|
}
|
|
|
|
Future<void> _checkHealth() async {
|
|
if (_probing || !mounted || state.phase != VpnPhase.on) return;
|
|
// 实际所连节点(测试态直接 emit on 时未走 _connect → 回退 effectiveNode)。
|
|
final Node node = _connectedNode ?? _ref.read(effectiveNodeProvider);
|
|
if (node.uuid.isEmpty) return;
|
|
_probing = true;
|
|
// 信号③:服务端权威健康——刷 /v1/nodes,看所连节点是否被判 down。
|
|
var serverDown = false;
|
|
try {
|
|
await _ref.read(nodesProvider.notifier).refresh();
|
|
final cur = (_ref.read(nodesProvider).valueOrNull ?? const <Node>[])
|
|
.where((n) => n.uuid == node.uuid);
|
|
if (cur.isNotEmpty) serverDown = cur.first.isDown;
|
|
} catch (_) {
|
|
// 拉取失败不视为不健康(refresh 失败保留旧列表);本轮以 TCP 探测为准。
|
|
}
|
|
// 信号①②:对数据口 TCP 握手,得 RTT(0=不可达);RTT 同时回填连接页延迟。
|
|
final rtt = await _prober(node.host, node.port);
|
|
_probing = false;
|
|
if (!mounted || state.phase != VpnPhase.on) return;
|
|
final live = rtt > 0 ? rtt : 0;
|
|
if (state.livePingMs != live) state = state.copyWith(livePingMs: live);
|
|
// 服务端权威 down(已 2-strike 去抖)→ 立即处理,不再等客户端连续失败。
|
|
if (serverDown) {
|
|
logLine('Watchdog', 'server marked node ${node.code} down → unhealthy');
|
|
_stopWatchdog();
|
|
await _onNodeUnhealthy();
|
|
return;
|
|
}
|
|
if (rtt > 0) {
|
|
_healthFails = 0;
|
|
return;
|
|
}
|
|
_healthFails++;
|
|
logLine('Watchdog', 'data-plane probe ${node.code} ${node.host}:${node.port} failed ($_healthFails/$_kHealthFailLimit)');
|
|
if (_healthFails >= _kHealthFailLimit) {
|
|
_stopWatchdog();
|
|
await _onNodeUnhealthy();
|
|
}
|
|
}
|
|
|
|
/// 当前节点连续探测失败 / 被服务端判 down:智能 → 切到其他最优可用节点重连;手动 → 断开并提示。
|
|
Future<void> _onNodeUnhealthy() async {
|
|
final t = _ref.read(appTextProvider);
|
|
final Node node = _connectedNode ?? _ref.read(effectiveNodeProvider);
|
|
final smart = _ref.read(selectedNodeCodeProvider) == kSmartNodeCode;
|
|
final altCode = smart ? _pickAlternativeCode(node.code) : null;
|
|
if (smart && altCode != null) {
|
|
_ref.read(selectedNodeCodeProvider.notifier).select(altCode);
|
|
await _disconnect();
|
|
await _connect();
|
|
// 重连进行中给出「已自动切换」提示(connecting 态显示,连上后随 copyWith 清除)。
|
|
if (mounted && state.phase != VpnPhase.off) {
|
|
state = ConnectionState(phase: state.phase, error: t.nodeUnhealthySwitched);
|
|
}
|
|
return;
|
|
}
|
|
// 手动选定节点(或智能模式无其他可用节点):断开并提示,尊重用户选择、不自动换。
|
|
await _disconnect();
|
|
if (mounted) state = ConnectionState(phase: VpnPhase.off, error: t.nodeUnhealthyError);
|
|
}
|
|
|
|
/// 选延迟最优、可用(status up)、非当前节点的 code;无则 null。
|
|
String? _pickAlternativeCode(String excludeCode) {
|
|
final nodes = (_ref.read(nodesProvider).valueOrNull ?? const [])
|
|
.where((n) => !n.isDown && n.uuid.isNotEmpty && n.code != excludeCode)
|
|
.toList();
|
|
if (nodes.isEmpty) return null;
|
|
nodes.sort((a, b) {
|
|
final pa = a.ping > 0 ? a.ping : 1 << 30;
|
|
final pb = b.ping > 0 ? b.ping : 1 << 30;
|
|
return pa.compareTo(pb);
|
|
});
|
|
return nodes.first.code;
|
|
}
|
|
|
|
void _startElapsed() {
|
|
_elapsed?.cancel();
|
|
_elapsed = Timer.periodic(const Duration(seconds: 1), (_) {
|
|
if (mounted && state.phase == VpnPhase.on) {
|
|
state = state.copyWith(elapsed: state.elapsed + const Duration(seconds: 1));
|
|
}
|
|
});
|
|
}
|
|
|
|
void _stopElapsed() {
|
|
_elapsed?.cancel();
|
|
_elapsed = null;
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_statusSub?.cancel();
|
|
_stopElapsed();
|
|
_stopWatchdog();
|
|
_api?.dispose();
|
|
super.dispose();
|
|
}
|
|
}
|
|
|
|
// ── Provider ──────────────────────────────────────────────────────
|
|
|
|
final connectionProvider =
|
|
StateNotifierProvider<ConnectionController, ConnectionState>(
|
|
(ref) => ConnectionController(ref, ref.watch(vpnBridgeProvider)),
|
|
);
|
|
|
|
/// 内核实时统计流(上/下行瞬时速率、字节数)。连接页速度行的真实数据源。
|
|
final vpnStatsProvider = StreamProvider<VpnStatsEvent>(
|
|
(ref) => ref.watch(vpnBridgeProvider).statsStream,
|
|
);
|
|
|
|
/// 按 authToken 造 ConnectApi 的工厂(支柱 1:接缝即接口)。默认走真控制面;
|
|
/// 测试 override 注入 MockClient,即可驱动「连接成功」路径而不打真网络。
|
|
typedef ConnectApiFactory = ConnectApi Function(String authToken);
|
|
|
|
final connectApiFactoryProvider = Provider<ConnectApiFactory>(
|
|
(_) => (authToken) => ConnectApi(baseUrl: kApiBaseUrl, authToken: authToken),
|
|
);
|