mirror of
https://github.com/shadowsocks/ShadowsocksX-NG.git
synced 2026-11-16 03:14:41 +00:00
ADR-0022 的观察/修复/挂起策略此前溶解在控制器 15 个可变字段里、由 Gate/Inspection/Commands/Health/Mode 五个文件交叉读写。现在策略机独立为 SystemProxyObserver:意图开关、出口可用性、期望配置与健康循环调度以 @MainActor 闭包注入,模块不反向依赖控制器;底层继续只依赖 SystemProxyControlling / helper 注册缝 / 网络变化监视三条既有缝。 - 3 个 @Published 呈现事实随迁,控制器留同名只读门面(测试与诊断面零改动); adapter 再发布链 merge 观察机 objectWillChange,主队列 hop 语义不变 - 健康循环留在控制器(循环体含运行时健康呈现),任务柄归观察机; cleanup-until-quiet、网络变化 inspection 调度与操作互斥全部内聚 - 方法体逐字搬运(settings.systemProxyEnabled→isIntentEnabled() 等机械替换), 语义零改动;既有 777 测试全绿
180 lines
9.3 KiB
Swift
180 lines
9.3 KiB
Swift
import Foundation
|
||
|
||
/// GUI-owned runtime and system-proxy manager. Agent and system-proxy switches
|
||
/// persist independent intentions. System proxy writes use the privileged helper;
|
||
/// current configuration is observed read-only and differs from write outcomes.
|
||
/// Health/exit loss suspends system proxy settings, real recovery reapplies, and
|
||
/// passive network events only inspect (ADR-0022 / issue #73)——该观察/修复策略机
|
||
/// 独立在 `SystemProxyObserver`:控制器注入意图/出口/期望配置三个事实闭包并
|
||
/// 转发命令,健康循环保留在本体(循环体含运行时健康呈现)。GUI exit ends these
|
||
/// observations without stopping the LaunchAgent or adding helper responsibilities.
|
||
@MainActor
|
||
final class ProxyRuntimeController: ObservableObject {
|
||
/// Agent(后台代理运行时)运行状态。系统代理结果不在此面呈现——它有
|
||
/// 独立的 `SystemProxyControlState`。
|
||
enum AgentRunState: Equatable {
|
||
case off
|
||
case starting
|
||
case running
|
||
/// 代理在本机运行,但主机地址态的入站被 macOS 防火墙拒绝。
|
||
case firewallBlocked(FirewallBlockedFacts)
|
||
/// 启动失败:携带点名端点与端口的事实(D8;端口语义细节 #30 接线)。
|
||
case launchFailed(LaunchFailureFacts)
|
||
/// 需要用户在系统设置-登录项中允许后台项。
|
||
case requiresApproval
|
||
/// 服务管理或运行时文件本身失败。
|
||
case serviceFailed(ServiceFailureFacts)
|
||
}
|
||
|
||
/// Current configuration or operation result, independent of persisted intent.
|
||
typealias SystemProxyControlState = SystemProxyApplicationFacts
|
||
|
||
@Published var state: AgentRunState = .off
|
||
@Published var settings: ProxySettings
|
||
/// 当前活动目标(菜单栏状态摘要与级联只读呈现用,issue #31)。machine 是
|
||
/// 非发布值的普通结构体,代理关闭路径的激活动作不会触碰 state,菜单的
|
||
/// 「目标」行依赖这里的独立发布保持实时。
|
||
@Published var activeTargetID: NodeID?
|
||
/// 最近一次激活预检在分组中跳过的服务器;仅记录 app 已知的本地阻塞原因。
|
||
@Published var skippedServers: [SkippedServer] = []
|
||
/// 最近一次激活拒绝或目标清除的点名原因。独立于运行状态呈现:agent 可
|
||
/// 能仍在监听,激活失败不代表运行时停止(issue #60)。
|
||
@Published var lastActivationFailure: ActivationFailure?
|
||
var machine: ActivationStateMachine
|
||
|
||
let catalogSnapshotReader: RuntimeCatalogSnapshotReading
|
||
let activationFileStore: ActivationStateFileStore
|
||
let runtimeFileStore: RuntimeFileStore
|
||
let credentials: CredentialStoring
|
||
let plugins: ManagedPluginProviding
|
||
let settingsStore: ProxySettingsStoring
|
||
/// 自定义规则持久化(issue #66):规则模式 ACL 合并的用户入口。
|
||
var isUpdatingRules = false
|
||
let customRuleStore: CustomRuleStore
|
||
let ruleDocuments: RuleDocumentSession
|
||
let ruleSnapshots: BuiltinRuleSnapshots
|
||
var runtimePreparationGeneration = 0
|
||
/// 监听设置不可读时的点名原因(D8「任何路径不静默改端口」);非 nil 时
|
||
/// 设置只是占位出厂默认,禁止部署(见 `deploy`)。
|
||
var listenSettingsUnreadable: Bool
|
||
/// 新版偏好不可读时同样禁止部署,不以出厂端口静默替代用户配置。
|
||
var settingsUnreadable: Bool
|
||
let agent: LaunchAgentControlling
|
||
let probe: EndpointProbing
|
||
let systemProxy: SystemProxyControlling
|
||
let systemProxyHelper: SystemProxyHelperServicing
|
||
let systemProxyNetworkChangeMonitor: SystemProxyNetworkChangeMonitoring
|
||
/// 系统代理观察/修复策略机(ADR-0022):呈现事实的存储与发布点,详情见
|
||
/// 模块文档。惰性构造:事实闭包需捕获控制器,而闭包成形必须晚于自身
|
||
/// 全部存储属性的初始化(首次访问发生在 init 之后)。
|
||
lazy var systemProxyObserver: SystemProxyObserver = SystemProxyObserver(
|
||
systemProxy: systemProxy,
|
||
systemProxyHelper: systemProxyHelper,
|
||
systemProxyNetworkChangeMonitor: systemProxyNetworkChangeMonitor,
|
||
appBundle: appBundle,
|
||
helperRefreshDelayNanoseconds: helperRefreshDelayNanoseconds,
|
||
isIntentEnabled: { [weak self] in self?.settings.systemProxyEnabled ?? false },
|
||
isExitAvailable: { [weak self] in self?.systemProxyExitAvailable ?? false },
|
||
desiredConfiguration: { [weak self] in
|
||
guard let self else { return nil }
|
||
return self.desiredSystemProxyConfiguration
|
||
},
|
||
startSystemProxyHealthObservation: { [weak self] in
|
||
guard let self else { return }
|
||
self.startSystemProxyHealthObservation()
|
||
})
|
||
let firewallChecker: FirewallStatusChecking
|
||
let firewallExecutableURLs: [URL]
|
||
/// 宿主 app bundle 缝(生产为 Bundle.main):内置规则快照与 LaunchDaemon
|
||
/// 清单等打包资源的定位基准。去宿主化(ADR 0021)后单测运行于 xctest
|
||
/// runner,`Bundle.main` 不再是 app,经此缝注入构建产物 bundle。
|
||
let appBundle: Bundle
|
||
let firewallPollIntervalNanoseconds: UInt64
|
||
let launchHealthTimeoutSeconds: TimeInterval
|
||
/// 注册清单漂移重注时,注销与重注的间隔(launchd 对节流中 job 的移除异步)。
|
||
let systemProxyHealthPollIntervalNanoseconds: UInt64
|
||
let helperRefreshDelayNanoseconds: UInt64
|
||
/// 信号发送缝(默认 kill),单测观测 SIGUSR1 投递。
|
||
let sendSignal: @Sendable (Int32, Int32) -> Int32
|
||
let processIsAlive: @Sendable (Int32) -> Bool
|
||
/// 并发流代际:停止请求可使进行中的启动探测立即失效。
|
||
var flowGeneration = 0
|
||
var modeChangeGeneration = 0
|
||
var lastDocument: SslocalRuntimeDocument?
|
||
var firewallObservationTask: Task<Void, Never>?
|
||
|
||
@Published var proxyMode: ProxyMode
|
||
|
||
/// 规则模式子选项(issue #63):从设置快照投影。
|
||
var ruleDefaultAction: RuleDefaultAction { settings.ruleDefaultAction }
|
||
|
||
init(
|
||
catalogSnapshotReader: RuntimeCatalogSnapshotReading,
|
||
activationFileStore: ActivationStateFileStore = ActivationStateFileStore(
|
||
fileURL: ActivationStateFileStore.defaultFileURL()),
|
||
runtimeFileStore: RuntimeFileStore = RuntimeFileStore(),
|
||
credentials: CredentialStoring = KeychainCredentialStore(),
|
||
plugins: ManagedPluginProviding = BundleManagedPluginProvider(),
|
||
listenRestore: RestoredListenSettings = ListenSettingsFileStore.restored(),
|
||
settingsStore: ProxySettingsStoring = ProxySettingsFileStore(),
|
||
customRuleStore: CustomRuleStore = CustomRuleStore(),
|
||
appBundle: Bundle = .main,
|
||
ruleSnapshots: BuiltinRuleSnapshots? = nil,
|
||
settingsRestore: RestoredProxySettings? = nil,
|
||
agent: LaunchAgentControlling = SMAppLaunchAgentService(),
|
||
probe: EndpointProbing = SystemEndpointProbe(),
|
||
systemProxy: SystemProxyControlling = XPCSystemProxyController(),
|
||
systemProxyHelper: SystemProxyHelperServicing = SMAppServiceSystemProxyHelper(),
|
||
systemProxyNetworkChangeMonitor: SystemProxyNetworkChangeMonitoring =
|
||
NoopSystemProxyNetworkChangeMonitor(),
|
||
proxyMode: ProxyMode? = nil,
|
||
firewallChecker: FirewallStatusChecking = SocketFilterFirewallChecker(),
|
||
firewallExecutableURLs: [URL]? = nil,
|
||
firewallPollIntervalNanoseconds: UInt64 = 2_000_000_000,
|
||
launchHealthTimeoutSeconds: TimeInterval = 15,
|
||
systemProxyHealthPollIntervalNanoseconds: UInt64 = 2_000_000_000,
|
||
helperRefreshDelayNanoseconds: UInt64 = 15_000_000_000,
|
||
sendSignal: @escaping @Sendable (Int32, Int32) -> Int32 = { kill($0, $1) },
|
||
processIsAlive: @escaping @Sendable (Int32) -> Bool = { $0 > 0 && kill($0, 0) == 0 }
|
||
) {
|
||
self.catalogSnapshotReader = catalogSnapshotReader
|
||
self.activationFileStore = activationFileStore
|
||
self.runtimeFileStore = runtimeFileStore
|
||
self.credentials = credentials
|
||
self.plugins = plugins
|
||
self.settingsStore = settingsStore
|
||
self.customRuleStore = customRuleStore
|
||
self.ruleDocuments = RuleDocumentSession(store: customRuleStore)
|
||
self.ruleSnapshots = ruleSnapshots ?? BuiltinRuleSnapshots(bundle: appBundle)
|
||
self.appBundle = appBundle
|
||
let restoredSettings =
|
||
settingsRestore
|
||
?? RestoredProxySettings(
|
||
settings: ProxySettings(listen: listenRestore.settings),
|
||
unreadableError: listenRestore.unreadableError.map {
|
||
.legacyListenSettings($0)
|
||
})
|
||
settings = restoredSettings.settings
|
||
listenSettingsUnreadable =
|
||
settingsRestore == nil && listenRestore.unreadableError != nil
|
||
settingsUnreadable = restoredSettings.unreadableError != nil
|
||
self.agent = agent
|
||
self.probe = probe
|
||
self.systemProxy = systemProxy
|
||
self.systemProxyHelper = systemProxyHelper
|
||
self.systemProxyNetworkChangeMonitor = systemProxyNetworkChangeMonitor
|
||
self.firewallChecker = firewallChecker
|
||
self.firewallExecutableURLs = firewallExecutableURLs ?? Self.defaultFirewallExecutableURLs
|
||
self.firewallPollIntervalNanoseconds = firewallPollIntervalNanoseconds
|
||
self.launchHealthTimeoutSeconds = launchHealthTimeoutSeconds
|
||
self.systemProxyHealthPollIntervalNanoseconds = systemProxyHealthPollIntervalNanoseconds
|
||
self.helperRefreshDelayNanoseconds = helperRefreshDelayNanoseconds
|
||
self.sendSignal = sendSignal
|
||
self.processIsAlive = processIsAlive
|
||
let persistedTarget = try? activationFileStore.loadActiveTargetID()
|
||
machine = ActivationStateMachine(activeTargetID: persistedTarget)
|
||
activeTargetID = machine.activeTargetID
|
||
self.proxyMode = proxyMode ?? Self.makeProxyMode(from: restoredSettings.settings)
|
||
}
|
||
}
|