mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-17 09:12:10 +08:00
refactor(core): type notice statuses behind the frozen wire contract
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::{core::handle, utils::window_manager::WindowState};
|
||||
use clash_verge_i18n;
|
||||
use tauri_plugin_notification::NotificationExt as _;
|
||||
|
||||
pub enum NotificationEvent<'a> {
|
||||
DashboardToggled,
|
||||
ClashModeChanged {
|
||||
mode: &'a str,
|
||||
},
|
||||
SystemProxyToggled(bool),
|
||||
/// A proxy change failed while no window could report it.
|
||||
SystemProxyFailed,
|
||||
/// The system proxy guard stopped.
|
||||
SystemProxyGuardStopped,
|
||||
TunModeToggled(bool),
|
||||
LightweightModeEntered,
|
||||
ProfilesReactivated,
|
||||
AppQuit,
|
||||
}
|
||||
|
||||
/// Whether no app window can currently show the failure.
|
||||
pub const fn needs_system_notification(state: WindowState) -> bool {
|
||||
match state {
|
||||
WindowState::Hidden | WindowState::Minimized | WindowState::NotExist => true,
|
||||
WindowState::VisibleFocused | WindowState::VisibleUnfocused => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn notify(title: Cow<'_, str>, body: Cow<'_, str>) {
|
||||
let app_handle = handle::Handle::app_handle();
|
||||
app_handle.notification().builder().title(title).body(body).show().ok();
|
||||
}
|
||||
|
||||
pub async fn notify_event<'a>(event: NotificationEvent<'a>) {
|
||||
match event {
|
||||
NotificationEvent::DashboardToggled => {
|
||||
let title = clash_verge_i18n::t!("notifications.dashboardToggled.title");
|
||||
let body = clash_verge_i18n::t!("notifications.dashboardToggled.body");
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::ClashModeChanged { mode } => {
|
||||
let title = clash_verge_i18n::t!("notifications.clashModeChanged.title");
|
||||
let body = clash_verge_i18n::t!("notifications.clashModeChanged.body")
|
||||
.replace("{mode}", mode)
|
||||
.into();
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::SystemProxyToggled(enabled) => {
|
||||
let title = clash_verge_i18n::t!("notifications.systemProxyToggled.title");
|
||||
let key = if enabled {
|
||||
"notifications.systemProxyToggled.on"
|
||||
} else {
|
||||
"notifications.systemProxyToggled.off"
|
||||
};
|
||||
|
||||
let body = clash_verge_i18n::t!(key);
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::SystemProxyFailed => {
|
||||
let title = clash_verge_i18n::t!("notifications.systemProxyFailed.title");
|
||||
let body = clash_verge_i18n::t!("notifications.systemProxyFailed.body");
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::SystemProxyGuardStopped => {
|
||||
let title = clash_verge_i18n::t!("notifications.systemProxyGuardStopped.title");
|
||||
let body = clash_verge_i18n::t!("notifications.systemProxyGuardStopped.body");
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::TunModeToggled(enabled) => {
|
||||
let title = clash_verge_i18n::t!("notifications.tunModeToggled.title");
|
||||
let key = if enabled {
|
||||
"notifications.tunModeToggled.on"
|
||||
} else {
|
||||
"notifications.tunModeToggled.off"
|
||||
};
|
||||
let body = clash_verge_i18n::t!(key);
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::LightweightModeEntered => {
|
||||
let title = clash_verge_i18n::t!("notifications.lightweightModeEntered.title");
|
||||
let body = clash_verge_i18n::t!("notifications.lightweightModeEntered.body");
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::ProfilesReactivated => {
|
||||
let title = clash_verge_i18n::t!("notifications.profilesReactivated.title");
|
||||
let body = clash_verge_i18n::t!("notifications.profilesReactivated.body");
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::AppQuit => {
|
||||
let title = clash_verge_i18n::t!("notifications.appQuit.title");
|
||||
let body = clash_verge_i18n::t!("notifications.appQuit.body");
|
||||
notify(title, body);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
use super::NoticeStatus;
|
||||
use crate::{APP_HANDLE, singleton};
|
||||
use smartstring::alias::String;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
use tauri::AppHandle;
|
||||
use tauri_plugin_mihomo::{Mihomo, MihomoExt as _};
|
||||
|
||||
use super::notification::{FrontendEvent, NotificationSystem};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Handle {
|
||||
is_exiting: AtomicBool,
|
||||
}
|
||||
|
||||
impl Default for Handle {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
is_exiting: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
singleton!(Handle, HANDLE);
|
||||
|
||||
impl Handle {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn app_handle() -> &'static AppHandle {
|
||||
#[allow(clippy::expect_used)]
|
||||
APP_HANDLE.get().expect("App handle not initialized")
|
||||
}
|
||||
|
||||
pub fn mihomo() -> &'static Mihomo {
|
||||
Self::app_handle().mihomo()
|
||||
}
|
||||
|
||||
pub fn refresh_clash() {
|
||||
Self::send_event(FrontendEvent::RefreshClash);
|
||||
}
|
||||
|
||||
pub fn refresh_verge() {
|
||||
Self::send_event(FrontendEvent::RefreshVerge);
|
||||
}
|
||||
|
||||
pub fn refresh_profiles() {
|
||||
Self::send_event(FrontendEvent::RefreshProfiles);
|
||||
}
|
||||
|
||||
pub fn refresh_proxy_config() {
|
||||
Self::send_event(FrontendEvent::RefreshProxyConfig);
|
||||
}
|
||||
|
||||
/// Push a Run State snapshot to the frontend.
|
||||
///
|
||||
/// Sent on every transition, so the frontend does not have to poll to notice that the Core
|
||||
/// stopped or that the Service came back.
|
||||
pub fn notify_run_state(state: &crate::core::runstate::RunStateView) {
|
||||
let Ok(state) = serde_json::to_value(state) else {
|
||||
return;
|
||||
};
|
||||
Self::send_event(FrontendEvent::RunStateChanged { state });
|
||||
}
|
||||
|
||||
pub fn notify_profile_changed(profile_id: &String) {
|
||||
Self::send_event(FrontendEvent::ProfileChanged {
|
||||
current_profile_id: profile_id,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn notify_timer_updated(profile_index: &String) {
|
||||
Self::send_event(FrontendEvent::TimerUpdated { profile_index });
|
||||
}
|
||||
|
||||
pub fn notify_profile_update_started(uid: &String) {
|
||||
Self::send_event(FrontendEvent::ProfileUpdateStarted { uid });
|
||||
}
|
||||
|
||||
pub fn notify_profile_update_completed(uid: &String) {
|
||||
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
|
||||
}
|
||||
|
||||
pub fn notice(status: NoticeStatus, message: impl Into<Arc<str>>) {
|
||||
Self::send_event(FrontendEvent::NoticeMessage {
|
||||
status,
|
||||
message: message.into(),
|
||||
});
|
||||
}
|
||||
|
||||
pub fn set_is_exiting(&self) {
|
||||
self.is_exiting.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn clear_is_exiting(&self) {
|
||||
self.is_exiting.store(false, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn is_exiting(&self) -> bool {
|
||||
self.is_exiting.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
fn send_event(event: FrontendEvent) {
|
||||
let handle = Self::global();
|
||||
if handle.is_exiting() {
|
||||
return;
|
||||
}
|
||||
|
||||
NotificationSystem::send_event(Self::app_handle().clone(), event);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl Handle {
|
||||
pub fn set_activation_policy(&self, policy: tauri::ActivationPolicy) -> Result<(), String> {
|
||||
Self::app_handle()
|
||||
.set_activation_policy(policy)
|
||||
.map_err(|e| e.to_string().into())
|
||||
}
|
||||
|
||||
pub fn set_activation_policy_regular(&self) {
|
||||
let _ = self.set_activation_policy(tauri::ActivationPolicy::Regular);
|
||||
}
|
||||
|
||||
pub fn set_activation_policy_accessory(&self) {
|
||||
let _ = self.set_activation_policy(tauri::ActivationPolicy::Accessory);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
pub mod desktop;
|
||||
pub mod handle;
|
||||
pub mod notification;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
pub enum NoticeStatus {
|
||||
// dead send: no frontend handler
|
||||
#[serde(rename = "info")]
|
||||
Info,
|
||||
#[serde(rename = "import_sub_url::ok")]
|
||||
ImportSubUrlOk,
|
||||
#[serde(rename = "import_sub_url::error")]
|
||||
ImportSubUrlError,
|
||||
#[serde(rename = "set_config::error")]
|
||||
SetConfigError,
|
||||
#[serde(rename = "core_start::error")]
|
||||
CoreStartError,
|
||||
#[serde(rename = "service_core::repair_required")]
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
ServiceCoreRepairRequired,
|
||||
#[serde(rename = "service_core::app_data_not_owned")]
|
||||
ServiceCoreAppDataNotOwned,
|
||||
#[serde(rename = "service_core::sidecar_fallback")]
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
ServiceCoreSidecarFallback,
|
||||
#[serde(rename = "dns_override::auto_disabled")]
|
||||
DnsOverrideAutoDisabled,
|
||||
#[serde(rename = "enhance::discarded_keys")]
|
||||
EnhanceDiscardedKeys,
|
||||
#[serde(rename = "tun_mode::auto_disabled")]
|
||||
TunModeAutoDisabled,
|
||||
#[serde(rename = "tun_mode::auto_disable_failed")]
|
||||
TunModeAutoDisableFailed,
|
||||
#[serde(rename = "app_restart::core_stop_failed")]
|
||||
AppRestartCoreStopFailed,
|
||||
#[serde(rename = "app_quit::core_stop_failed")]
|
||||
AppQuitCoreStopFailed,
|
||||
#[serde(rename = "update_with_clash_proxy")]
|
||||
UpdateWithClashProxy,
|
||||
#[serde(rename = "update_failed_even_with_clash")]
|
||||
UpdateFailedEvenWithClash,
|
||||
#[serde(rename = "reactivate_profiles::error")]
|
||||
ReactivateProfilesError,
|
||||
#[serde(rename = "update_failed")]
|
||||
UpdateFailed,
|
||||
#[serde(rename = "config_validate::boot_error")]
|
||||
ConfigValidateBootError,
|
||||
#[serde(rename = "config_validate::error")]
|
||||
ConfigValidateError,
|
||||
#[serde(rename = "config_validate::process_terminated")]
|
||||
ConfigValidateProcessTerminated,
|
||||
#[serde(rename = "config_validate::script_error")]
|
||||
ConfigValidateScriptError,
|
||||
#[serde(rename = "config_validate::script_syntax_error")]
|
||||
ConfigValidateScriptSyntaxError,
|
||||
#[serde(rename = "config_validate::script_missing_main")]
|
||||
ConfigValidateScriptMissingMain,
|
||||
#[serde(rename = "config_validate::file_not_found")]
|
||||
ConfigValidateFileNotFound,
|
||||
#[serde(rename = "config_validate::yaml_syntax_error")]
|
||||
ConfigValidateYamlSyntaxError,
|
||||
#[serde(rename = "config_validate::yaml_read_error")]
|
||||
ConfigValidateYamlReadError,
|
||||
#[serde(rename = "config_validate::yaml_mapping_error")]
|
||||
ConfigValidateYamlMappingError,
|
||||
#[serde(rename = "config_validate::merge_syntax_error")]
|
||||
ConfigValidateMergeSyntaxError,
|
||||
#[serde(rename = "config_validate::merge_mapping_error")]
|
||||
ConfigValidateMergeMappingError,
|
||||
#[serde(rename = "config_core::change_success")]
|
||||
ConfigCoreChangeSuccess,
|
||||
#[serde(rename = "config_core::change_error")]
|
||||
ConfigCoreChangeError,
|
||||
#[serde(rename = "mixed_port::fallback")]
|
||||
MixedPortFallback,
|
||||
#[serde(rename = "mixed_port::fallback_error")]
|
||||
MixedPortFallbackError,
|
||||
// dead listener: frontend handler retained
|
||||
#[allow(dead_code)]
|
||||
#[serde(rename = "config_validate::core_change")]
|
||||
ConfigValidateCoreChange,
|
||||
// dead listener: frontend handler retained
|
||||
#[allow(dead_code)]
|
||||
#[serde(rename = "config_validate::stdout_error")]
|
||||
ConfigValidateStdoutError,
|
||||
// dead listener: frontend handler retained
|
||||
#[allow(dead_code)]
|
||||
#[serde(rename = "config_validate::yaml_key_error")]
|
||||
ConfigValidateYamlKeyError,
|
||||
// dead listener: frontend handler retained
|
||||
#[allow(dead_code)]
|
||||
#[serde(rename = "config_validate::yaml_error")]
|
||||
ConfigValidateYamlError,
|
||||
// dead listener: frontend handler retained
|
||||
#[allow(dead_code)]
|
||||
#[serde(rename = "config_validate::merge_key_error")]
|
||||
ConfigValidateMergeKeyError,
|
||||
// dead listener: frontend handler retained
|
||||
#[allow(dead_code)]
|
||||
#[serde(rename = "config_validate::merge_error")]
|
||||
ConfigValidateMergeError,
|
||||
// dead send: no frontend handler
|
||||
#[serde(rename = "set_config::ok")]
|
||||
SetConfigOk,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::NoticeStatus;
|
||||
|
||||
#[test]
|
||||
fn notice_status_wire_contract() {
|
||||
let statuses = [
|
||||
NoticeStatus::Info,
|
||||
NoticeStatus::ImportSubUrlOk,
|
||||
NoticeStatus::ImportSubUrlError,
|
||||
NoticeStatus::SetConfigError,
|
||||
NoticeStatus::CoreStartError,
|
||||
NoticeStatus::ServiceCoreRepairRequired,
|
||||
NoticeStatus::ServiceCoreAppDataNotOwned,
|
||||
NoticeStatus::ServiceCoreSidecarFallback,
|
||||
NoticeStatus::DnsOverrideAutoDisabled,
|
||||
NoticeStatus::EnhanceDiscardedKeys,
|
||||
NoticeStatus::TunModeAutoDisabled,
|
||||
NoticeStatus::TunModeAutoDisableFailed,
|
||||
NoticeStatus::AppRestartCoreStopFailed,
|
||||
NoticeStatus::AppQuitCoreStopFailed,
|
||||
NoticeStatus::UpdateWithClashProxy,
|
||||
NoticeStatus::UpdateFailedEvenWithClash,
|
||||
NoticeStatus::ReactivateProfilesError,
|
||||
NoticeStatus::UpdateFailed,
|
||||
NoticeStatus::ConfigValidateBootError,
|
||||
NoticeStatus::ConfigValidateError,
|
||||
NoticeStatus::ConfigValidateProcessTerminated,
|
||||
NoticeStatus::ConfigValidateScriptError,
|
||||
NoticeStatus::ConfigValidateScriptSyntaxError,
|
||||
NoticeStatus::ConfigValidateScriptMissingMain,
|
||||
NoticeStatus::ConfigValidateFileNotFound,
|
||||
NoticeStatus::ConfigValidateYamlSyntaxError,
|
||||
NoticeStatus::ConfigValidateYamlReadError,
|
||||
NoticeStatus::ConfigValidateYamlMappingError,
|
||||
NoticeStatus::ConfigValidateMergeSyntaxError,
|
||||
NoticeStatus::ConfigValidateMergeMappingError,
|
||||
NoticeStatus::ConfigCoreChangeSuccess,
|
||||
NoticeStatus::ConfigCoreChangeError,
|
||||
NoticeStatus::MixedPortFallback,
|
||||
NoticeStatus::MixedPortFallbackError,
|
||||
NoticeStatus::ConfigValidateCoreChange,
|
||||
NoticeStatus::ConfigValidateStdoutError,
|
||||
NoticeStatus::ConfigValidateYamlKeyError,
|
||||
NoticeStatus::ConfigValidateYamlError,
|
||||
NoticeStatus::ConfigValidateMergeKeyError,
|
||||
NoticeStatus::ConfigValidateMergeError,
|
||||
NoticeStatus::SetConfigOk,
|
||||
];
|
||||
let expected = [
|
||||
"info",
|
||||
"import_sub_url::ok",
|
||||
"import_sub_url::error",
|
||||
"set_config::error",
|
||||
"core_start::error",
|
||||
"service_core::repair_required",
|
||||
"service_core::app_data_not_owned",
|
||||
"service_core::sidecar_fallback",
|
||||
"dns_override::auto_disabled",
|
||||
"enhance::discarded_keys",
|
||||
"tun_mode::auto_disabled",
|
||||
"tun_mode::auto_disable_failed",
|
||||
"app_restart::core_stop_failed",
|
||||
"app_quit::core_stop_failed",
|
||||
"update_with_clash_proxy",
|
||||
"update_failed_even_with_clash",
|
||||
"reactivate_profiles::error",
|
||||
"update_failed",
|
||||
"config_validate::boot_error",
|
||||
"config_validate::error",
|
||||
"config_validate::process_terminated",
|
||||
"config_validate::script_error",
|
||||
"config_validate::script_syntax_error",
|
||||
"config_validate::script_missing_main",
|
||||
"config_validate::file_not_found",
|
||||
"config_validate::yaml_syntax_error",
|
||||
"config_validate::yaml_read_error",
|
||||
"config_validate::yaml_mapping_error",
|
||||
"config_validate::merge_syntax_error",
|
||||
"config_validate::merge_mapping_error",
|
||||
"config_core::change_success",
|
||||
"config_core::change_error",
|
||||
"mixed_port::fallback",
|
||||
"mixed_port::fallback_error",
|
||||
"config_validate::core_change",
|
||||
"config_validate::stdout_error",
|
||||
"config_validate::yaml_key_error",
|
||||
"config_validate::yaml_error",
|
||||
"config_validate::merge_key_error",
|
||||
"config_validate::merge_error",
|
||||
"set_config::ok",
|
||||
];
|
||||
let actual: Vec<_> = statuses
|
||||
.into_iter()
|
||||
.map(serde_json::to_value)
|
||||
.collect::<Result<_, _>>()
|
||||
.unwrap();
|
||||
assert_eq!(actual, expected.map(serde_json::Value::from));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
use super::NoticeStatus;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use once_cell::sync::Lazy;
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::json;
|
||||
use smartstring::alias::String;
|
||||
use std::sync::Arc;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
future::Future,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
use tauri::{AppHandle, Emitter as _, Manager as _, WebviewWindow};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum FrontendEvent<'a> {
|
||||
RefreshClash,
|
||||
RefreshVerge,
|
||||
RefreshProfiles,
|
||||
RefreshProxyConfig,
|
||||
NoticeMessage {
|
||||
status: NoticeStatus,
|
||||
message: Arc<str>,
|
||||
},
|
||||
ProfileChanged {
|
||||
current_profile_id: &'a String,
|
||||
},
|
||||
TimerUpdated {
|
||||
profile_index: &'a String,
|
||||
},
|
||||
ProfileUpdateStarted {
|
||||
uid: &'a String,
|
||||
},
|
||||
ProfileUpdateCompleted {
|
||||
uid: &'a String,
|
||||
},
|
||||
RunStateChanged {
|
||||
state: serde_json::Value,
|
||||
},
|
||||
PendingFailuresChanged,
|
||||
#[cfg(target_os = "linux")]
|
||||
ThemeChanged {
|
||||
theme: tauri::Theme,
|
||||
},
|
||||
}
|
||||
|
||||
/// Operation associated with a pending failure.
|
||||
#[allow(clippy::enum_variant_names)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum FailedOperation {
|
||||
SystemProxyEnable,
|
||||
SystemProxyDisable,
|
||||
SystemProxyRestore,
|
||||
SystemProxyGuard,
|
||||
}
|
||||
|
||||
impl FailedOperation {
|
||||
/// User requests outrank incidental restores under the same code.
|
||||
const fn outranks(self, other: Self) -> bool {
|
||||
matches!(self, Self::SystemProxyEnable | Self::SystemProxyDisable) && matches!(other, Self::SystemProxyRestore)
|
||||
}
|
||||
|
||||
/// Whether a successful apply of `asked` resolves this operation's failure.
|
||||
const fn retired_by_success_of(self, asked: Self) -> bool {
|
||||
match (self, asked) {
|
||||
// Only replacing or stopping the guard resolves its failure.
|
||||
(Self::SystemProxyGuard, _) | (_, Self::SystemProxyGuard) => false,
|
||||
// The user asked and got an answer, so nothing earlier is still owed to them.
|
||||
(_, Self::SystemProxyEnable | Self::SystemProxyDisable) => true,
|
||||
// An incidental restore says nothing about a request they may not have seen fail.
|
||||
(Self::SystemProxyRestore, Self::SystemProxyRestore) => true,
|
||||
(_, Self::SystemProxyRestore) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Latest unresolved failure for one stable code.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PendingFailure {
|
||||
/// Stable code used as the table key.
|
||||
pub code: String,
|
||||
/// Full diagnostic context chain.
|
||||
pub detail: String,
|
||||
pub operation: FailedOperation,
|
||||
/// Monotonic identity for repeated failures under the same code.
|
||||
pub sequence: u64,
|
||||
}
|
||||
|
||||
/// Non-destructive pending state, indexed by stable code.
|
||||
#[derive(Debug, Default)]
|
||||
struct FailureTable {
|
||||
entries: Mutex<HashMap<String, PendingFailure>>,
|
||||
sequence: AtomicU64,
|
||||
}
|
||||
|
||||
impl FailureTable {
|
||||
fn record(&self, operation: FailedOperation, code: &str, detail: String) {
|
||||
// Sequence assignment and replacement must share one ordering lock.
|
||||
let mut entries = self.entries.lock();
|
||||
// Preserve an unanswered request over a later restore.
|
||||
let operation = entries
|
||||
.get(code)
|
||||
.filter(|existing| existing.operation.outranks(operation))
|
||||
.map_or(operation, |existing| existing.operation);
|
||||
let failure = PendingFailure {
|
||||
code: code.into(),
|
||||
detail,
|
||||
operation,
|
||||
sequence: self.sequence.fetch_add(1, Ordering::AcqRel).wrapping_add(1),
|
||||
};
|
||||
entries.insert(code.into(), failure);
|
||||
}
|
||||
|
||||
fn snapshot(&self) -> Vec<PendingFailure> {
|
||||
let mut failures: Vec<PendingFailure> = self.entries.lock().values().cloned().collect();
|
||||
failures.sort_by_key(|failure| failure.sequence);
|
||||
failures
|
||||
}
|
||||
|
||||
/// Return whether a guard failure was retired.
|
||||
fn retire_guard(&self) -> bool {
|
||||
let mut entries = self.entries.lock();
|
||||
let before = entries.len();
|
||||
entries.retain(|_, failure| failure.operation != FailedOperation::SystemProxyGuard);
|
||||
before != entries.len()
|
||||
}
|
||||
|
||||
/// Return whether any proxy failure was retired.
|
||||
fn retire_system_proxy(&self, asked: FailedOperation) -> bool {
|
||||
let mut entries = self.entries.lock();
|
||||
let before = entries.len();
|
||||
entries.retain(|_, failure| !failure.operation.retired_by_success_of(asked));
|
||||
before != entries.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod failure_table_tests {
|
||||
use super::{FailedOperation, FailureTable};
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_declared_intent_reaches_the_place_the_write_fails() {
|
||||
let asked = super::asking_for(FailedOperation::SystemProxyEnable, async {
|
||||
tokio::task::yield_now().await;
|
||||
super::what_was_asked()
|
||||
})
|
||||
.await;
|
||||
|
||||
assert_eq!(asked, FailedOperation::SystemProxyEnable);
|
||||
assert_eq!(super::what_was_asked(), FailedOperation::SystemProxyRestore);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_incidental_failure_does_not_take_over_a_request_the_user_is_still_owed() {
|
||||
let table = FailureTable::default();
|
||||
table.record(
|
||||
FailedOperation::SystemProxyEnable,
|
||||
"SYSPROXY_PRIVILEGE_REQUIRED",
|
||||
"asked for it on".into(),
|
||||
);
|
||||
table.record(
|
||||
FailedOperation::SystemProxyRestore,
|
||||
"SYSPROXY_PRIVILEGE_REQUIRED",
|
||||
"and a restart hit it too".into(),
|
||||
);
|
||||
|
||||
let entries = table.snapshot();
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert_eq!(entries[0].operation, FailedOperation::SystemProxyEnable);
|
||||
assert_eq!(entries[0].detail, "and a restart hit it too");
|
||||
|
||||
assert!(!table.retire_system_proxy(FailedOperation::SystemProxyRestore));
|
||||
assert!(table.retire_system_proxy(FailedOperation::SystemProxyEnable));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_still_replaces_an_incidental_failure() {
|
||||
let table = FailureTable::default();
|
||||
table.record(
|
||||
FailedOperation::SystemProxyRestore,
|
||||
"SYSPROXY_PRIVILEGE_REQUIRED",
|
||||
"a".into(),
|
||||
);
|
||||
table.record(
|
||||
FailedOperation::SystemProxyDisable,
|
||||
"SYSPROXY_PRIVILEGE_REQUIRED",
|
||||
"b".into(),
|
||||
);
|
||||
|
||||
let entries = table.snapshot();
|
||||
assert_eq!(entries[0].operation, FailedOperation::SystemProxyDisable);
|
||||
assert!(table.retire_system_proxy(FailedOperation::SystemProxyDisable));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_incidental_failures_still_replace_each_other() {
|
||||
let table = FailureTable::default();
|
||||
table.record(
|
||||
FailedOperation::SystemProxyRestore,
|
||||
"SYSPROXY_PRIVILEGE_REQUIRED",
|
||||
"first".into(),
|
||||
);
|
||||
table.record(
|
||||
FailedOperation::SystemProxyRestore,
|
||||
"SYSPROXY_PRIVILEGE_REQUIRED",
|
||||
"second".into(),
|
||||
);
|
||||
|
||||
let entries = table.snapshot();
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert_eq!(entries[0].detail, "second");
|
||||
}
|
||||
}
|
||||
|
||||
tokio::task_local! {
|
||||
/// User-requested operation inherited by the current task.
|
||||
static ASKING_FOR: FailedOperation;
|
||||
}
|
||||
|
||||
/// Run `operation` with the user's intent attached to whatever failure it produces.
|
||||
pub async fn asking_for<T>(operation: FailedOperation, work: impl Future<Output = T>) -> T {
|
||||
ASKING_FOR.scope(operation, work).await
|
||||
}
|
||||
|
||||
/// What the caller asked for, or a restore when nobody asked.
|
||||
pub fn what_was_asked() -> FailedOperation {
|
||||
ASKING_FOR
|
||||
.try_with(|operation| *operation)
|
||||
.unwrap_or(FailedOperation::SystemProxyRestore)
|
||||
}
|
||||
|
||||
static PENDING_FAILURES: Lazy<FailureTable> = Lazy::new(FailureTable::default);
|
||||
|
||||
pub fn record_failure(operation: FailedOperation, code: &str, detail: impl Into<String>) {
|
||||
PENDING_FAILURES.record(operation, code, detail.into());
|
||||
notify_pending_failures_changed();
|
||||
}
|
||||
|
||||
pub fn has_pending_failure(code: &str) -> bool {
|
||||
PENDING_FAILURES.entries.lock().contains_key(code)
|
||||
}
|
||||
|
||||
/// Return unresolved failures oldest first without clearing them.
|
||||
pub fn pending_failures() -> Vec<PendingFailure> {
|
||||
PENDING_FAILURES.snapshot()
|
||||
}
|
||||
|
||||
/// Retire guard failures after replacement or shutdown.
|
||||
pub fn retire_guard_failures() {
|
||||
if PENDING_FAILURES.retire_guard() {
|
||||
notify_pending_failures_changed();
|
||||
}
|
||||
}
|
||||
|
||||
/// Retire failures resolved by a successful apply of what was asked.
|
||||
pub fn retire_system_proxy_failures(asked: FailedOperation) {
|
||||
if PENDING_FAILURES.retire_system_proxy(asked) {
|
||||
notify_pending_failures_changed();
|
||||
}
|
||||
}
|
||||
|
||||
/// Nudge the window to reread pending state; the event carries no payload.
|
||||
fn notify_pending_failures_changed() {
|
||||
let Some(app_handle) = crate::APP_HANDLE.get() else {
|
||||
return;
|
||||
};
|
||||
NotificationSystem::send_event(app_handle.clone(), FrontendEvent::PendingFailuresChanged);
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct NotificationSystem {}
|
||||
|
||||
impl NotificationSystem {
|
||||
fn emit_to_window(window: &WebviewWindow, event_name: &'static str, payload: serde_json::Value) {
|
||||
if let Err(e) = window.emit(event_name, payload) {
|
||||
logging!(warn, Type::Frontend, "Event emit failed: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_event(event: FrontendEvent) -> (&'static str, Result<serde_json::Value, serde_json::Error>) {
|
||||
match event {
|
||||
FrontendEvent::RefreshClash => ("verge://refresh-clash-config", Ok(json!("yes"))),
|
||||
FrontendEvent::RefreshVerge => ("verge://refresh-verge-config", Ok(json!("yes"))),
|
||||
FrontendEvent::RefreshProfiles => ("verge://refresh-profiles", Ok(json!("yes"))),
|
||||
FrontendEvent::RefreshProxyConfig => ("verge://refresh-proxy-config", Ok(serde_json::Value::Null)),
|
||||
FrontendEvent::NoticeMessage { status, message } => (
|
||||
"verge://notice-message",
|
||||
serde_json::to_value((status, message.as_ref())),
|
||||
),
|
||||
FrontendEvent::ProfileChanged { current_profile_id } => ("profile-changed", Ok(json!(current_profile_id))),
|
||||
FrontendEvent::TimerUpdated { profile_index } => ("verge://timer-updated", Ok(json!(profile_index))),
|
||||
FrontendEvent::ProfileUpdateStarted { uid } => ("profile-update-started", Ok(json!({ "uid": uid }))),
|
||||
FrontendEvent::ProfileUpdateCompleted { uid } => ("profile-update-completed", Ok(json!({ "uid": uid }))),
|
||||
FrontendEvent::RunStateChanged { state } => ("verge://run-state-changed", Ok(state)),
|
||||
FrontendEvent::PendingFailuresChanged => ("verge://pending-failures-changed", Ok(serde_json::Value::Null)),
|
||||
#[cfg(target_os = "linux")]
|
||||
FrontendEvent::ThemeChanged { theme } => ("tauri://theme-changed", serde_json::to_value(theme)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn send_event(app_handle: AppHandle, event: FrontendEvent) {
|
||||
let (event_name, Ok(payload)) = Self::serialize_event(event) else {
|
||||
return;
|
||||
};
|
||||
let dispatch_handle = app_handle.clone();
|
||||
// Emitting from a runtime worker can deadlock on macOS when WebKit's protocol handler
|
||||
// waits for Tauri's webview lock while emit waits synchronously for the main thread.
|
||||
if let Err(err) = app_handle.run_on_main_thread(move || {
|
||||
if let Some(window) = dispatch_handle.get_webview_window("main") {
|
||||
Self::emit_to_window(&window, event_name, payload);
|
||||
}
|
||||
}) {
|
||||
logging!(warn, Type::Frontend, "Failed to dispatch event on main thread: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod wire_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn frontend_event_wire_contract() {
|
||||
let uid = String::from("profile");
|
||||
let events = [
|
||||
(
|
||||
FrontendEvent::RefreshClash,
|
||||
"verge://refresh-clash-config",
|
||||
json!("yes"),
|
||||
),
|
||||
(
|
||||
FrontendEvent::RefreshVerge,
|
||||
"verge://refresh-verge-config",
|
||||
json!("yes"),
|
||||
),
|
||||
(FrontendEvent::RefreshProfiles, "verge://refresh-profiles", json!("yes")),
|
||||
(
|
||||
FrontendEvent::RefreshProxyConfig,
|
||||
"verge://refresh-proxy-config",
|
||||
json!(null),
|
||||
),
|
||||
(
|
||||
FrontendEvent::NoticeMessage {
|
||||
status: NoticeStatus::SetConfigOk,
|
||||
message: Arc::from("ok"),
|
||||
},
|
||||
"verge://notice-message",
|
||||
json!(["set_config::ok", "ok"]),
|
||||
),
|
||||
(
|
||||
FrontendEvent::TimerUpdated { profile_index: &uid },
|
||||
"verge://timer-updated",
|
||||
json!("profile"),
|
||||
),
|
||||
(
|
||||
FrontendEvent::RunStateChanged {
|
||||
state: json!({"running": true}),
|
||||
},
|
||||
"verge://run-state-changed",
|
||||
json!({"running": true}),
|
||||
),
|
||||
(
|
||||
FrontendEvent::PendingFailuresChanged,
|
||||
"verge://pending-failures-changed",
|
||||
json!(null),
|
||||
),
|
||||
(
|
||||
FrontendEvent::ProfileChanged {
|
||||
current_profile_id: &uid,
|
||||
},
|
||||
"profile-changed",
|
||||
json!("profile"),
|
||||
),
|
||||
(
|
||||
FrontendEvent::ProfileUpdateStarted { uid: &uid },
|
||||
"profile-update-started",
|
||||
json!({"uid": "profile"}),
|
||||
),
|
||||
(
|
||||
FrontendEvent::ProfileUpdateCompleted { uid: &uid },
|
||||
"profile-update-completed",
|
||||
json!({"uid": "profile"}),
|
||||
),
|
||||
];
|
||||
for (event, name, payload) in events {
|
||||
let (actual_name, actual_payload) = NotificationSystem::serialize_event(event);
|
||||
assert_eq!(actual_name, name);
|
||||
assert_eq!(actual_payload.unwrap(), payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user