part of '../action.dart'; class _DelayTestTarget { const _DelayTestTarget({ required this.proxyName, required this.testUrl, required this.key, }); final String proxyName; final String testUrl; final String key; } typedef _DelayTestBatch = ({List proxies, String? testUrl}); class _DelayTestJob { _DelayTestJob(Iterable keys, this.timeout) : held = keys.toSet(); final Set held; final Duration timeout; final Set startedOnDispatch = {}; bool cancelled = false; } @Riverpod(keepAlive: true) class ProxiesAction extends _$ProxiesAction { CoreController get _core => ref.read(coreHandlerProvider); final TaskPool _delayTestPool = TaskPool(maxConcurrentDelayTests); final List<_DelayTestJob> _delayTestJobs = []; final List _bufferedDelays = []; final List _bufferedStarts = []; final List _bufferedFinishes = []; Timer? _delayFlushTimer; final Map _pendingSelectedRollback = {}; @override void build() { ref.onDispose(() => _delayFlushTimer?.cancel()); ref.listen(coreStatusProvider, (_, next) { if (next != CoreStatus.connected) { cancelDelayTests(); } }); } void cancelDelayTests() { for (final job in _delayTestJobs) { job.cancelled = true; job.held.clear(); } _delayFlushTimer?.cancel(); _delayFlushTimer = null; _bufferedDelays.clear(); _bufferedStarts.clear(); _bufferedFinishes.clear(); ref.read(pendingDelayTestsProvider.notifier).clear(); } void _scheduleDelayFlush() { _delayFlushTimer ??= Timer(renderThrottleDuration, _flushDelayResults); } void _flushDelayResults() { _delayFlushTimer?.cancel(); _delayFlushTimer = null; if (_bufferedDelays.isNotEmpty) { final delays = List.of(_bufferedDelays); _bufferedDelays.clear(); ref.read(delayDataSourceProvider.notifier).setDelays(delays); } if (_bufferedStarts.isNotEmpty || _bufferedFinishes.isNotEmpty) { final started = List.of(_bufferedStarts); final finished = List.of(_bufferedFinishes); _bufferedStarts.clear(); _bufferedFinishes.clear(); ref .read(pendingDelayTestsProvider.notifier) .apply(started: started, finished: finished); } } void updateGroupsDebounce([Duration? duration]) { debouncer.call(FunctionTag.updateGroups, updateGroups, duration: duration); } void changeProxyDebounce(String groupName, String proxyName) { _pendingSelectedRollback.putIfAbsent( groupName, () => _currentSelectedName(groupName), ); ref .read(profilesActionProvider.notifier) .updateCurrentSelectedMap(groupName, proxyName); debouncer.call((FunctionTag.changeProxy, groupName), ( String groupName, String proxyName, ) async { await changeProxy(groupName: groupName, proxyName: proxyName); updateGroupsDebounce(); }, args: [groupName, proxyName]); } String _currentSelectedName(String groupName) { return ref.read(currentProfileProvider)?.selectedMap[groupName] ?? ''; } Future updateGroups() async { try { ref.read(groupsProvider.notifier).value = await retry( task: () async { final sortType = ref.read( proxiesStyleSettingProvider.select((state) => state.sortType), ); final delayMap = ref.read(delayDataSourceProvider); final testUrl = ref.read( patchClashConfigProvider.select((state) => state.testUrl), ); final selectedMap = ref.read( currentProfileProvider.select((state) => state?.selectedMap ?? {}), ); try { return await _core.getProxiesGroups( selectedMap: selectedMap, sortType: sortType, delayMap: delayMap, defaultTestUrl: testUrl, ); } catch (e) { commonPrint.log( 'updateGroups error: $e', logLevel: coreFailureLogLevel(e), ); return []; } }, retryIf: (res) => res.isEmpty, ); } catch (e) { // The Core failure path already runs inside the retry task above; a // throw here only means ref.read hit a disposed container or the // groupsProvider write itself failed. commonPrint.log( 'updateGroups failed: $e', logLevel: coreFailureLogLevel(e), ); } } void updateCurrentGroupName(String groupName) { final profile = ref.read(currentProfileProvider); if (profile == null || profile.currentGroupName == groupName) return; ref .read(profilesProvider.notifier) .put(profile.copyWith(currentGroupName: groupName)); } void updateCurrentUnfoldSet(Set value) { final currentProfile = ref.read(currentProfileProvider); if (currentProfile == null) return; ref .read(profilesProvider.notifier) .put(currentProfile.copyWith(unfoldSet: value)); } void setDelay(Delay delay) { _bufferedDelays.add(delay); _scheduleDelayFlush(); } Future changeProxy({ required String groupName, required String proxyName, }) async { final profilesAction = ref.read(profilesActionProvider.notifier); final rollbackName = _pendingSelectedRollback.remove(groupName) ?? _currentSelectedName(groupName); profilesAction.updateCurrentSelectedMap(groupName, proxyName); final ChangeProxyResult result; try { result = await _core.changeProxy( ChangeProxyParams(groupName: groupName, proxyName: proxyName), ); if (result.message.isNotEmpty) { throw MessageException(result.message); } } catch (error) { commonPrint.log( 'changeProxy($groupName -> $proxyName) failed: $error', logLevel: coreFailureLogLevel(error), ); profilesAction.updateCurrentSelectedMap(groupName, rollbackName); dialogs.showBanner( currentAppLocalizations.changeProxyFailedTip, level: BannerLevel.error, ); return; } if (!result.changed) { return; } try { if (ref.read(appSettingProvider).closeConnections) { await _core.closeConnections(); } else { await _core.resetConnections(); } } catch (error) { commonPrint.log( 'changeProxy($groupName -> $proxyName) connection reset failed: $error', logLevel: coreFailureLogLevel(error), ); } } Future updateProvider( ExternalProvider provider, { bool showLoading = false, }) async { final operation = showLoading ? ref .read(updatingKeysProvider.notifier) .start(provider.updatingKey, scope: UpdatingScope.core) : null; try { final clashProvidersAction = ref.read( clashProvidersActionProvider.notifier, ); final ruleSet = await clashProvidersAction.remoteProviderOf(provider); if (ruleSet != null && !await clashProvidersAction.syncRemote(ruleSet)) { return; } await _core.updateExternalProvider(provider.name); ref .read(providersProvider.notifier) .setProvider(await _core.getExternalProvider(provider.name)); } finally { if (operation != null) { ref .read(updatingKeysProvider.notifier) .stop(provider.updatingKey, operation); } } } Future sideLoadExternalProvider( ExternalProvider provider, String data, { bool showLoading = false, }) async { final operation = showLoading ? ref .read(updatingKeysProvider.notifier) .start(provider.updatingKey, scope: UpdatingScope.core) : null; try { await _core.sideLoadExternalProvider( providerName: provider.name, data: data, ); ref .read(providersProvider.notifier) .setProvider(await _core.getExternalProvider(provider.name)); } finally { if (operation != null) { ref .read(updatingKeysProvider.notifier) .stop(provider.updatingKey, operation); } } } Future addToLocalProxies(String proxyName) async { final appLocalizations = currentAppLocalizations; final definition = await _core.getProxyDefinition(proxyName); if (definition == null) { throw MessageException( appLocalizations.customIssueMissingProxies(proxyName), ); } final (proxies, groupNames) = await ( database.customProxiesDao.query().get(), database.proxyGroupsDao.names().get(), ).wait; final (:name, :added) = importProxy( definition, existing: [for (final proxy in proxies) proxy.definition], groupNames: groupNames.toSet(), ); if (added == null) { dialogs.showBanner(appLocalizations.alreadyInLocalProxies(name)); return; } final order = indexing.generateKeyBetween( proxies.map((proxy) => proxy.order).nonNulls.lastOrNull, null, ); await database.customProxies.put( CustomProxy.fromDefinition(added).copyWith(order: order).toCompanion(), ); dialogs.showBanner(appLocalizations.addedToLocalProxies(name)); } Future proxyDelayTest(Proxy proxy, [String? testUrl]) { return _runDelayTests([ (proxies: [proxy], testUrl: testUrl), ]); } Future delayTest(List proxies, [String? testUrl]) async { await _runDelayTests([(proxies: proxies, testUrl: testUrl)]); ref.read(sortNumProvider.notifier).add(); } Future delayTestGroups(List groups) async { await _runDelayTests([ for (final group in groups) (proxies: group.all, testUrl: group.testUrl), ]); ref.read(sortNumProvider.notifier).add(); } Future delayTestPageGroup( String groupName, { bool matchSearch = true, }) async { final group = ref.read(groupsProvider).getGroup(groupName); if (group == null) { return; } final testing = ref.read(delayTestingGroupsProvider.notifier); if (!testing.start(groupName)) { return; } try { final query = SearchQuery( matchSearch ? ref.read(queryProvider(QueryTag.proxies)) : '', ); await delayTest( group.all.whereMatches(query, (proxy) => proxy.searchFields).toList(), group.testUrl, ); } finally { testing.stop(groupName); } } List<_DelayTestTarget> _resolveDelayTestTargets( List<_DelayTestBatch> batches, ) { final groups = ref.read(groupsProvider); final selectedMap = ref.read( currentProfileProvider.select((state) => state?.selectedMap ?? {}), ); final seen = {}; final targets = <_DelayTestTarget>[]; for (final batch in batches) { final fallbackTestUrl = ref.read(realTestUrlProvider(batch.testUrl)); for (final proxy in batch.proxies) { final state = computeRealSelectedProxyState( proxy.name, groups: groups, selectedMap: selectedMap, ); if (state.proxyName.isEmpty) { continue; } final currentTestUrl = state.testUrl.takeFirstValid([fallbackTestUrl]); final key = delayTestKey(currentTestUrl, state.proxyName); if (!seen.add(key)) { continue; } targets.add( _DelayTestTarget( proxyName: state.proxyName, testUrl: currentTestUrl, key: key, ), ); } } return targets; } Future _runDelayTests(List<_DelayTestBatch> batches) async { final targets = _resolveDelayTestTargets(batches); if (targets.isEmpty) { return; } final pending = ref.read(pendingDelayTestsProvider.notifier); final job = _DelayTestJob( targets.map((target) => target.key), Duration(milliseconds: ref.read(appSettingProvider).delayTestTimeout), ); _delayTestJobs.add(job); // TaskPool.run starts a task synchronously while it has an idle slot. job.startedOnDispatch.addAll( targets.take(_delayTestPool.idleSlots).map((target) => target.key), ); pending.apply(acquired: job.held, started: job.startedOnDispatch); try { await Future.wait( targets.map( (target) => _delayTestPool.run(() => _runDelayTest(job, target)), ), ); } finally { _delayTestJobs.remove(job); _flushDelayResults(); final abandoned = job.held.toList(); job.held.clear(); pending.apply( finished: abandoned.where(job.startedOnDispatch.contains), released: abandoned.where( (key) => !job.startedOnDispatch.contains(key), ), ); } } Future _runDelayTest(_DelayTestJob job, _DelayTestTarget target) async { if (job.cancelled) { return; } if (!job.startedOnDispatch.contains(target.key)) { _bufferedStarts.add(target.key); _scheduleDelayFlush(); } try { final delay = await _core.testDelay( TestDelayParams( proxyName: target.proxyName, testUrl: target.testUrl, timeout: job.timeout.inMilliseconds, ), ); if (!job.cancelled) { setDelay(delay); } } catch (error) { if (error is CoreMethodException && error.isCoreUnavailable) { job.cancelled = true; } commonPrint.log( 'Delay test failed for ${target.proxyName}: $error', logLevel: coreFailureLogLevel(error), ); } finally { if (job.held.remove(target.key)) { _bufferedFinishes.add(target.key); _scheduleDelayFlush(); } } } }