Files
ShadowsocksX-NG/ShadowsocksX-NG2/App/RulesWorkflow.swift
T
Qiu Yuzhou beaa92781a feat(rules): add independent offline address tests
Implement #77 using the complete saved versioned rule collection. Normalize domain, IP, and URL hosts; preserve three outcomes and all deciding identities, source memberships, and other target-specific matches without DNS or runtime dependencies.

Invalidate results when the target changes or refresh starts, and reject late asynchronous publication. Add the native address test panel and approved Chinese/English copy.

Validation: 760 hostless tests and 2 fixed-sslocal semantics smoke tests passed; ad-hoc Debug build passed. Changed-file format/lint clean; existing repository warnings remain. Standards and Spec reviews found no issues. Visual acceptance remains manual.
2026-10-02 20:59:26 +08:00

136 lines
4.7 KiB
Swift

import Combine
import Foundation
/// File reads and collection preparation run outside the UI actor; queries use
/// the prepared collection and do not rebuild semantic analysis on each keypress.
@MainActor
final class RulesWorkflow: ObservableObject {
@Published private(set) var snapshot = RulesPageSnapshot()
@Published private(set) var reportSource: RulesSourceSnapshot?
private let loadCustom: @Sendable () throws -> [CustomRule]
private let loadBuiltin: @Sendable (RulesSource) throws -> RuleSnapshot
private var collection: RulesCollection?
private var refreshGeneration = 0
private var testGeneration = 0
init(
loadCustom: @escaping @Sendable () throws -> [CustomRule] = { try CustomRuleStore().load() },
loadBuiltin: @escaping @Sendable (RulesSource) throws -> RuleSnapshot = { source in
switch source {
case .geolocationCN: try BuiltinRuleCatalog.loadGeolocationCN()
case .chinaIPv4: try BuiltinRuleCatalog.loadChinaIPv4()
case .gfwlist: try BuiltinRuleCatalog.loadGFWList()
case .custom, .fixed: throw RuleSnapshotError.missing
}
}
) {
self.loadCustom = loadCustom
self.loadBuiltin = loadBuiltin
}
func refresh() async {
refreshGeneration += 1
let generation = refreshGeneration
invalidateAddressTest()
snapshot.isLoading = true
let custom = loadCustom
let builtin = loadBuiltin
let result = await Task.detached(priority: .userInitiated) {
RulesCollection.load(custom: custom, builtin: builtin)
}.value
guard generation == refreshGeneration else { return }
collection = result
var next = snapshot
next.version = result.version
next.sources = result.sources
next.issues = result.issues
next.isLoading = false
snapshot = applyingQuery(to: next)
}
func setTestTarget(_ target: String) {
guard target != snapshot.addressTest.target else { return }
invalidateAddressTest()
snapshot.addressTest.target = target
}
func testAddress() async {
invalidateAddressTest()
guard snapshot.isComplete, let collection else {
snapshot.addressTest.failure = .incompleteCollection
return
}
let generation = testGeneration
let target = snapshot.addressTest.target
snapshot.addressTest.isTesting = true
let result = await Task.detached(priority: .userInitiated) {
do {
return Result<OfflineRuleMatcher.Result, OfflineRuleMatcher.Failure>.success(
try OfflineRuleMatcher.test(collection: collection, address: target))
} catch {
return .failure(error as? OfflineRuleMatcher.Failure ?? .invalidTarget)
}
}.value
guard generation == testGeneration, snapshot.isComplete,
snapshot.version == collection.version
else { return }
snapshot.addressTest.isTesting = false
switch result {
case .success(let result): snapshot.addressTest.result = result
case .failure(let failure): snapshot.addressTest.failure = failure
}
}
private func invalidateAddressTest() {
testGeneration += 1
snapshot.addressTest = RulesAddressTest(target: snapshot.addressTest.target)
}
func query(_ query: RulesQuery) {
guard query != snapshot.query else { return }
var next = snapshot
next.query = query
snapshot = applyingQuery(to: next)
}
func select(_ ids: Set<RulesRow.SelectionID>) {
let selection = ids.intersection(Set(snapshot.rows.map(\.id)))
guard selection != snapshot.selection else { return }
snapshot.selection = selection
}
/// Capture only on an explicit open request, independently of browsing and refresh.
@discardableResult
func openSourceReport(_ source: RulesSource) -> Bool {
guard let loaded = snapshot.sources.first(where: { $0.id == source }),
loaded.metadata != nil, loaded.conversionReport != nil
else { return false }
reportSource = loaded
return true
}
var selectedRelationshipRow: RulesRow? {
guard snapshot.selection.count == 1,
let row = snapshot.rows.first(where: { snapshot.selection.contains($0.id) }),
!row.relationships.isEmpty || row.fixedCoverage != nil
else { return nil }
return row
}
private func applyingQuery(to page: RulesPageSnapshot) -> RulesPageSnapshot {
guard let collection else { return page }
let query = page.query
let search = query.search.lowercased()
var rows = collection.rows.filter { row in
(query.action == nil || row.action == query.action)
&& (query.source.map { row.sources.contains($0) } ?? true)
&& (search.isEmpty || row.content.lowercased().contains(search))
}
if query.sort == .descending { rows.reverse() }
var next = page
next.rows = rows
next.selection.formIntersection(Set(rows.map(\.id)))
return next
}
}