Files
pangolin/client/macos/Runner/StatsClient.swift
T
wangjia 7add0259b4 chore(client/macos): 清理延迟排查的诊断打点 + debug 注入(最终干净版)
延迟显示已修通。移除排查期的临时诊断:扩展侧 Log 客户端/klog 捕获、log.level=debug 注入、
diag 字段/setDiag;主 app StatsClient 每5帧的 dl/ul/urltest 打印;Dart 侧 [Stats]/[Ping] 打点。
保留全部修复:clash_api 注入取 urltest、sendProviderMessage 统计通道、/proxies history+active
缓存、共享广播流、_onStats 回退 effectiveNode、连接态跳过直连实测。

CURRENT_PROJECT_VERSION 52→53。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 18:03:30 +08:00

74 lines
3.0 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// StatsClient.swift app macOS
//
// PacketTunnel System Extension root app App Group
// root /var/root/... vs /Users/<user>/... app
// libbox command.sock NetworkExtension
// app NETunnelProviderSession.sendProviderMessage("stats")
// handleAppMessage JSON StatsCollector
//
// root/ socket pangolin/vpn/stats
// lib/bridge/vpn_bridge.dart onStats VpnChannel Dart
import Foundation
import NetworkExtension
final class StatsClient: NSObject {
/// VpnChannel statsSink
var onStats: (([String: Any]) -> Void)?
private let queue = DispatchQueue(label: "pangolin.stats.client")
private weak var session: NETunnelProviderSession?
private var timer: DispatchSourceTimer?
//
/// connected
func start(session: NETunnelProviderSession) {
queue.async { [weak self] in
guard let self else { return }
self.session = session
self.timer?.cancel()
let t = DispatchSource.makeTimerSource(queue: self.queue)
t.schedule(deadline: .now() + 0.2, repeating: 1.0)
t.setEventHandler { [weak self] in self?.poll() }
t.resume()
self.timer = t
NSLog("[pangolin/stats] polling via sendProviderMessage started")
}
}
func stop() {
queue.async { [weak self] in
guard let self else { return }
self.timer?.cancel()
self.timer = nil
self.session = nil
self.emit([
"uploadBytes": 0, "downloadBytes": 0,
"uploadSpeed": 0.0, "downloadSpeed": 0.0,
"urltestResults": [[String: Any]](),
])
}
}
private func poll() {
guard let session else { return }
do {
try session.sendProviderMessage(Data("stats".utf8)) { [weak self] resp in
guard let self, let resp, !resp.isEmpty else { return }
guard let obj = (try? JSONSerialization.jsonObject(with: resp)) as? [String: Any] else {
return
}
self.emit(obj)
}
} catch {
NSLog("[pangolin/stats] sendProviderMessage failed: %@", error.localizedDescription)
}
}
private func emit(_ stats: [String: Any]) {
DispatchQueue.main.async { [weak self] in self?.onStats?(stats) }
}
}