fix(profile): recover interrupted subscription refreshes

Recover pending redo at startup, coordinate profile readers and writers, and publish Draft state only after persistence. Keep the Windows legacy path by default.
This commit is contained in:
Tunglies
2026-11-30 18:44:12 +08:00
parent 0415133c88
commit 2c8b532f68
22 changed files with 1465 additions and 172 deletions
+5
View File
@@ -22,6 +22,7 @@ tokio-trace = ["clash-verge-logging/tokio-trace"]
chrome-trace = ["clash-verge-logging/chrome-trace"]
clippy = ["tauri/test"]
perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
profile-store-windows = []
[package.metadata.bundle]
identifier = "io.github.clash-verge-rev.clash-verge-rev"
@@ -30,6 +31,7 @@ identifier = "io.github.clash-verge-rev.clash-verge-rev"
tauri-build = { version = "2.7.6", features = [] }
[dependencies]
tempfile = { workspace = true }
clash-verge-draft = { workspace = true }
clash-verge-task = { workspace = true }
clash-verge-media-unlock = { workspace = true }
@@ -109,6 +111,9 @@ specta = { workspace = true, features = ["derive", "function", "serde_json"] }
tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] }
specta-typescript = "=0.0.13"
[target.'cfg(any(unix, windows))'.dependencies]
clash-verge-profile-store = { workspace = true }
[target.'cfg(unix)'.dependencies]
libc = "0.2.191"
+11 -3
View File
@@ -39,6 +39,7 @@ fn profile_import_error(err: &anyhow::Error) -> std::string::String {
#[specta::specta]
pub async fn get_profiles() -> CmdResult<SharedDraft<IProfiles>> {
let draft = Config::profiles().await;
let _guard = crate::config::profile_storage::read().await.stringify_err()?;
let data = draft.data_arc();
Ok(data)
}
@@ -157,8 +158,11 @@ pub async fn update_profile(index: std::string::String, option: Option<PrfOption
pub async fn delete_profile(index: std::string::String) -> CmdResult {
let index: String = index.into();
let profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
crate::config::profile_storage::check().stringify_err()?;
let profiles = Config::profiles().await;
let mut storage_guard = None;
let slot = &mut storage_guard;
let result = profiles
.with_data_modify::<_, _, _, anyhow::Error>(|mut candidate| async move {
let original = candidate.clone();
@@ -177,11 +181,13 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
None
};
let current = candidate.current.clone();
*slot = Some(crate::config::profile_storage::write().await?);
cleanup_profile_files(plan.files).await;
Ok((candidate, Ok((should_update, current, guard))))
})
.await
.with_error_code("PROFILE_DELETE_FAILED")?;
drop(storage_guard);
let (should_update, current, config_update_guard) = match result {
Ok(result) => result,
Err(outcome) => {
@@ -214,10 +220,9 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
Config::profiles()
commit_current_profile(&Config::profiles().await, Some(prev_profile.clone()))
.await
.edit_draft(|d| d.patch_current(Some(prev_profile)));
Config::profiles().await.apply();
.stringify_err()?;
crate::process::AsyncHandler::spawn(|| async move {
if let Err(e) = profiles_save_file_safe().await {
logging!(warn, Type::Cmd, "异步保存恢复配置文件失败: {e:#}");
@@ -391,6 +396,7 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
CURRENT_SWITCHING_PROFILE.store(false, Ordering::Release);
});
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
crate::config::profile_storage::check().stringify_err()?;
let target_profile = profiles.current.as_ref();
@@ -458,6 +464,7 @@ pub async fn patch_profile(index: std::string::String, profile: ProfilePatch) ->
#[tauri::command]
#[specta::specta]
pub async fn view_profile(index: std::string::String) -> CmdResult {
let _guard = crate::config::profile_storage::read().await.stringify_err()?;
let profiles = Config::profiles().await;
let profiles_ref = profiles.latest_arc();
let file = profiles_ref
@@ -483,6 +490,7 @@ pub async fn view_profile(index: std::string::String) -> CmdResult {
#[tauri::command]
#[specta::specta]
pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::string::String> {
let _guard = crate::config::profile_storage::read().await.stringify_err()?;
let file = {
let profiles = Config::profiles().await;
let profiles_ref = profiles.latest_arc();
+30 -16
View File
@@ -2,7 +2,7 @@ use super::CmdResult;
use crate::{
cmd::StringifyErr as _,
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
config::{Config, IProfiles, read_profile_item_file},
config::{Config, IProfiles, profile_storage, profiles::PROFILE_WRITE_LOCK, read_profile_item_file},
core::auto_backup::{self, AutoBackupTrigger},
core::{
CoreManager, handle,
@@ -34,6 +34,9 @@ pub async fn save_profile_file(
_ => None,
};
let _profile_write = PROFILE_WRITE_LOCK.lock().await;
let profile_guard = profile_storage::write().await.stringify_err()?;
// 在异步操作前获取必要元数据并释放锁
let (rel_path, is_merge_file, is_script_file, affects_runtime) = {
let profiles = Config::profiles().await;
@@ -65,12 +68,18 @@ pub async fn save_profile_file(
// 保存新的配置文件
fs::write(&file_path, &file_data).await.stringify_err()?;
drop(profile_guard);
let original = OriginalProfileFile {
content: &original_content,
existed: original_existed,
written: &file_data,
};
let changes_applied = handle_saved_profile_file(
&file_path_str,
&file_path,
&original_content,
original_existed,
&original,
is_merge_file,
is_script_file,
affects_runtime,
@@ -86,13 +95,19 @@ pub async fn save_profile_file(
Ok(changes_applied)
}
async fn restore_original(
file_path: &std::path::Path,
original_content: &str,
original_existed: bool,
) -> CmdResult<()> {
if original_existed {
fs::write(file_path, original_content).await.stringify_err()
struct OriginalProfileFile<'a> {
content: &'a str,
existed: bool,
written: &'a str,
}
async fn restore_original(file_path: &std::path::Path, original: &OriginalProfileFile<'_>) -> CmdResult<()> {
let _guard = profile_storage::write().await.stringify_err()?;
if fs::read(file_path).await.stringify_err()? != original.written.as_bytes() {
return Err("profile file changed during validation".into());
}
if original.existed {
fs::write(file_path, original.content).await.stringify_err()
} else {
fs::remove_file(file_path).await.stringify_err()
}
@@ -122,8 +137,7 @@ fn profile_affects_runtime(profiles: &IProfiles, index: &str) -> bool {
async fn handle_saved_profile_file(
file_path_str: &str,
file_path: &std::path::Path,
original_content: &str,
original_existed: bool,
original: &OriginalProfileFile<'_>,
is_merge_file: bool,
is_script_file: bool,
affects_runtime: bool,
@@ -140,13 +154,13 @@ async fn handle_saved_profile_file(
Ok(outcome) if outcome.is_valid() => {}
Ok(outcome) => {
logging!(warn, Type::Config, "[cmd配置save] 文件验证失败: {}", outcome);
restore_original(file_path, original_content, original_existed).await?;
restore_original(file_path, original).await?;
handle_validation_notice(&outcome, target, file_type);
return Ok(outcome);
}
Err(e) => {
logging!(error, Type::Config, "[cmd配置save] 验证过程发生错误: {e:#}");
restore_original(file_path, original_content, original_existed).await?;
restore_original(file_path, original).await?;
return Err(e.to_string().into());
}
}
@@ -167,13 +181,13 @@ async fn handle_saved_profile_file(
}
Ok(outcome) => {
logging!(warn, Type::Config, "[cmd配置save] 运行时配置应用失败: {}", outcome);
restore_original(file_path, original_content, original_existed).await?;
restore_original(file_path, original).await?;
handle_validation_notice(&outcome, ValidationNoticeTarget::Runtime, "运行时配置");
Ok(outcome)
}
Err(err) => {
logging!(error, Type::Config, "[cmd配置save] 运行时配置应用错误: {err:#}");
restore_original(file_path, original_content, original_existed).await?;
restore_original(file_path, original).await?;
Err(err.to_string().into())
}
}
+32 -6
View File
@@ -3,7 +3,8 @@ use crate::core::notify::NoticeStatus;
use crate::{
config::{
prfitem::{build_merge_profile, build_script_profile},
profiles::{load_profiles, profiles_append_item_to_safe, save_profiles},
profile_storage,
profiles::{load_profiles, profiles_append_item_to_safe, save_profiles_unlocked},
runtime::IRuntime,
},
constants::{files, timing},
@@ -84,6 +85,7 @@ impl Config {
}
pub async fn init_config_before_window() -> Result<()> {
profile_storage::check()?;
Self::ensure_default_profile_items().await?;
let verge = Self::verge().await.latest_arc();
@@ -245,12 +247,24 @@ impl Config {
}
pub async fn generate() -> Result<()> {
let profiles = Self::profiles().await.latest_arc();
Self::generate_with_profiles(&profiles).await
let profiles = Self::profiles().await;
let inputs = {
let _guard = profile_storage::read().await?;
enhance::collect_render_inputs(&profiles.latest_arc()).await?
};
Self::generate_from_inputs(inputs).await
}
pub(crate) async fn generate_with_profiles(profiles: &IProfiles) -> Result<()> {
let (mut config, exists_keys, logs, dns_override) = enhance::enhance(profiles).await?;
let inputs = {
let _guard = profile_storage::read().await?;
enhance::collect_render_inputs(profiles).await?
};
Self::generate_from_inputs(inputs).await
}
async fn generate_from_inputs(inputs: enhance::ProfileRenderInputs) -> Result<()> {
let (mut config, exists_keys, logs, dns_override) = enhance::enhance(inputs).await;
resolve_provider_path_conflicts(&mut config, &dirs::app_home_dir()?)?;
sanitize_tunnels_proxy(&mut config);
@@ -313,8 +327,20 @@ impl Config {
let save_profiles_task = AsyncHandler::spawn(|| async {
let _profile_write = super::profiles::PROFILE_WRITE_LOCK.lock().await;
let profiles = Self::profiles().await;
profiles.apply();
logging_error!(Type::Config, save_profiles(&profiles.data_arc()).await);
let mut storage_guard = None;
let slot = &mut storage_guard;
let draft = &profiles;
let result = profiles
.with_data_modify(|_| async move {
*slot = Some(profile_storage::write().await?);
let candidate = (**draft.latest_arc()).clone();
let saved = save_profiles_unlocked(&candidate).await;
draft.discard();
Ok((candidate, saved))
})
.await;
drop(storage_guard);
logging_error!(Type::Config, result.and_then(std::convert::identity));
});
let _ = tokio::join!(save_clash_task, save_verge_task, save_profiles_task);
+1
View File
@@ -6,6 +6,7 @@ mod encrypt;
mod mixed_port;
mod port;
mod prfitem;
pub(crate) mod profile_storage;
pub mod profiles;
pub mod runtime;
pub(crate) mod snapshot;
+152
View File
@@ -0,0 +1,152 @@
use anyhow::{Result, anyhow};
use std::sync::OnceLock;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
const PROFILE_JOURNAL: &str = ".profile-refresh";
static PROFILE_IO: RwLock<()> = RwLock::const_new(());
static BLOCKED: OnceLock<String> = OnceLock::new();
pub(crate) fn check() -> Result<()> {
match BLOCKED.get() {
Some(reason) => Err(anyhow!("Profile storage requires recovery before use: {reason}")),
None => Ok(()),
}
}
pub(crate) fn block(error: &anyhow::Error) {
let _ = BLOCKED.set(format!("{error:#}"));
}
pub(crate) async fn read() -> Result<RwLockReadGuard<'static, ()>> {
let guard = PROFILE_IO.read().await;
check()?;
Ok(guard)
}
pub(crate) async fn write() -> Result<RwLockWriteGuard<'static, ()>> {
let guard = PROFILE_IO.write().await;
check()?;
Ok(guard)
}
pub(crate) async fn recover_at_startup() -> Result<()> {
let _guard = write().await?;
let root = crate::utils::dirs::app_home_dir().inspect_err(block)?;
let result: Result<()> = async {
if !journal_exists(&root).await? {
return Ok(());
}
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
return tokio::task::spawn_blocking(move || clash_verge_profile_store::recover_pending(&root))
.await?
.map_err(Into::into);
#[cfg(not(any(unix, all(windows, feature = "profile-store-windows"))))]
return Err(anyhow!(
"restore the pending profile transaction with redo support enabled"
));
}
.await;
if let Err(error) = &result {
block(error);
}
result
}
async fn journal_exists(root: &std::path::Path) -> Result<bool> {
match tokio::fs::symlink_metadata(root.join(PROFILE_JOURNAL)).await {
Ok(_) => Ok(true),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error.into()),
}
}
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
pub(super) async fn commit_refresh(
uid: String,
candidate: super::IProfiles,
body: tristr::alias::String,
) -> Result<super::IProfiles> {
use clash_verge_profile_store::{CommitOutcome, Session, recover_pending};
let root = crate::utils::dirs::app_home_dir()?;
#[cfg(windows)]
{
use anyhow::Context as _;
let probe_root = root.clone();
let supported =
tokio::task::spawn_blocking(move || clash_verge_profile_store::supports_redo(&probe_root)).await??;
if !supported {
if journal_exists(&root).await? {
let error = anyhow!("Profile refresh journal requires a supported NTFS volume");
block(&error);
return Err(error);
}
let file = candidate
.get_item(&uid)?
.file
.as_deref()
.context("missing profile filename")?;
let path = crate::utils::dirs::app_profiles_dir()?.join(file);
tokio::fs::write(path, body.as_bytes())
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
super::profiles::save_profiles_unlocked(&candidate).await?;
return Ok(candidate);
}
}
let result = tokio::task::spawn_blocking(move || {
let session = Session::open(&root).map_err(anyhow::Error::from).inspect_err(|error| {
match std::fs::symlink_metadata(root.join(PROFILE_JOURNAL)) {
Err(status) if status.kind() == std::io::ErrorKind::NotFound => {}
_ => block(error),
}
})?;
let item = candidate.get_item(&uid)?;
if let Some(file) = item.file.as_deref()
&& !file.contains(['/', '\\', ':', '\0'])
&& !matches!(file, "" | "." | "..")
{
let path = root.join("profiles").join(file);
match std::fs::symlink_metadata(&path) {
Ok(metadata) if metadata.is_file() => {
std::fs::OpenOptions::new().write(true).open(&path)?;
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
}
match session.commit_refresh(&uid, &candidate, body.as_bytes()) {
CommitOutcome::Committed => Ok(candidate),
CommitOutcome::CommittedCleanupPending(error) => {
if recover_pending(&root).is_err() {
block(&error.into());
}
Ok(candidate)
}
CommitOutcome::Retryable(error) => {
if let Err(recovery) = recover_pending(&root).map_err(anyhow::Error::from) {
block(&recovery);
return Err(recovery.context("failed to discard the incomplete profile refresh"));
}
Err(anyhow::Error::from(error).context("profile refresh stopped before commit"))
}
CommitOutcome::NeedsRecovery(error) => {
let error = anyhow::Error::from(error);
block(&error);
Err(error.context("profile refresh requires recovery"))
}
}
})
.await;
match result {
Ok(result) => result,
Err(error) => {
let error = anyhow::Error::from(error).context("profile storage worker stopped unexpectedly");
block(&error);
Err(error)
}
}
}
+112 -61
View File
@@ -1,6 +1,7 @@
use super::{
PrfItem, PrfOption, PrfSelected, patch_opt_field,
prfitem::{RemoteProfileRefresh, build_profile},
profile_storage,
};
use crate::core::notify::{Refresh, announce};
use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state};
@@ -67,52 +68,53 @@ pub(crate) async fn cleanup_profile_files(files: Vec<String>) {
}
pub(crate) async fn load_profiles() -> IProfiles {
let path = match dirs::profiles_path() {
Ok(p) => p,
Err(err) => {
logging!(error, Type::Config, "failed to get profiles path: {err:#}");
return IProfiles::default();
}
};
match help::read_yaml::<IProfiles>(&path).await {
Ok(mut profiles) => {
let items = profiles.items.get_or_insert_with(Vec::new);
let mut home_changed = false;
for item in items.iter_mut() {
if item.uid.is_none() {
item.uid = Some(help::get_uid("d").into());
}
if item.itype.as_deref() == Some("remote") {
item.option
.get_or_insert_with(PrfOption::default)
.allow_auto_update
.get_or_insert(true);
}
if item
.home
.as_deref()
.is_some_and(|home| normalize_profile_home_url(home).is_none())
{
item.home = None;
home_changed = true;
}
}
if home_changed && let Err(err) = save_profiles(&profiles).await {
logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}");
}
profiles
}
Err(err) => {
logging!(error, Type::Config, "failed to read profiles.yaml: {err:#}");
match load_profiles_checked().await {
Ok(profiles) => profiles,
Err(error) => {
logging!(error, Type::Config, "failed to load profiles: {error:#}");
IProfiles::default()
}
}
}
pub(crate) async fn load_profiles_checked() -> Result<IProfiles> {
profile_storage::check()?;
let mut profiles: IProfiles = help::read_yaml(&dirs::profiles_path()?).await?;
let items = profiles.items.get_or_insert_with(Vec::new);
let mut home_changed = false;
for item in items.iter_mut() {
if item.uid.is_none() {
item.uid = Some(help::get_uid("d").into());
}
if item.itype.as_deref() == Some("remote") {
item.option
.get_or_insert_with(PrfOption::default)
.allow_auto_update
.get_or_insert(true);
}
if item
.home
.as_deref()
.is_some_and(|home| normalize_profile_home_url(home).is_none())
{
item.home = None;
home_changed = true;
}
}
if home_changed && let Err(err) = save_profiles_unlocked(&profiles).await {
logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}");
}
Ok(profiles)
}
pub(crate) async fn save_profiles(profiles: &IProfiles) -> Result<()> {
let _guard = profile_storage::write().await?;
save_profiles_unlocked(profiles).await
}
pub(crate) async fn save_profiles_unlocked(profiles: &IProfiles) -> Result<()> {
help::save_yaml(
&dirs::profiles_path()?,
profiles,
@@ -190,30 +192,22 @@ fn validate_profile_file(file: &str) -> Result<()> {
Ok(())
}
/// Updates fields returned by a remote profile refresh.
async fn apply_remote_refresh(profiles: &mut IProfiles, uid: &str, refresh: RemoteProfileRefresh) -> Result<()> {
fn stage_remote_refresh(profiles: &mut IProfiles, uid: &str, refresh: &RemoteProfileRefresh) -> Result<()> {
let _ = profiles.get_item(uid)?;
if let Some(each) = profiles
if let Some(item) = profiles
.items
.iter_mut()
.flatten()
.find(|item| item.uid.as_deref() == Some(uid))
{
each.extra = refresh.extra;
each.updated = Some(refresh.updated);
each.home = refresh.home;
each.option = PrfOption::merge(each.option.as_ref(), Some(&refresh.option));
let file = each
.file
item.extra = refresh.extra;
item.updated = Some(refresh.updated);
item.home = refresh.home.clone();
item.option = PrfOption::merge(item.option.as_ref(), Some(&refresh.option));
item.file
.get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into());
let path = dirs::app_profiles_dir()?.join(file.as_str());
fs::write(&path, refresh.body.as_bytes())
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
}
save_profiles(profiles).await
Ok(())
}
/// Raise intervals below `min_minutes`. `None`/`0` mean "never auto-update", left alone.
@@ -284,6 +278,7 @@ pub(crate) async fn profiles_append_item_safe(item: &mut PrfItem) -> Result<()>
pub(super) async fn profiles_append_item_to_safe(profiles: &Draft<IProfiles>, item: &mut PrfItem) -> Result<()> {
profiles
.with_data_modify(|mut profiles| async move {
let _guard = profile_storage::write().await?;
append_item(&mut profiles, item).await?;
Ok((profiles, ()))
})
@@ -312,12 +307,68 @@ pub(crate) async fn profiles_save_file_safe() -> Result<()> {
with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await
}
pub(crate) async fn apply_remote_refresh_safe(index: &str, refresh: RemoteProfileRefresh) -> Result<()> {
with_profiles_edit(|mut profiles| async move {
apply_remote_refresh(&mut profiles, index, refresh).await?;
Ok(profiles)
pub(crate) async fn apply_remote_refresh_safe(
uid: &str,
url: &str,
file: Option<String>,
refresh: RemoteProfileRefresh,
) -> Result<()> {
let uid = uid.to_owned();
let url = url.to_owned();
// Dropping the caller must not separate an issued disk write from its Draft publication.
tokio::spawn(async move {
let _profile_write = PROFILE_WRITE_LOCK.lock().await;
anyhow::ensure!(!handle::Handle::global().is_exiting(), "application is exiting");
let draft = Config::profiles().await;
let mut storage_guard = None;
let mut persisted = false;
let result = {
let storage_guard = &mut storage_guard;
let persisted = &mut persisted;
draft
.with_data_modify(|mut candidate| async move {
*storage_guard = Some(profile_storage::write().await?);
let current = candidate.get_item(&uid)?;
anyhow::ensure!(
current.itype.as_deref() == Some("remote")
&& current.url.as_deref() == Some(url.as_str())
&& current.file == file,
"profile source or filename changed during refresh"
);
stage_remote_refresh(&mut candidate, &uid, &refresh)?;
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
let candidate = profile_storage::commit_refresh(uid, candidate, refresh.body).await?;
#[cfg(not(any(unix, all(windows, feature = "profile-store-windows"))))]
{
let file = candidate
.get_item(&uid)?
.file
.as_deref()
.context("missing profile filename")?;
let path = dirs::app_profiles_dir()?.join(file);
fs::write(&path, refresh.body.as_bytes())
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
save_profiles_unlocked(&candidate).await?;
}
*persisted = true;
Ok((candidate, ()))
})
.await
};
if let Err(error) = &result
&& persisted
{
profile_storage::block(error);
return Err(anyhow::anyhow!(
"Profile refresh is saved, but its Draft could not be published: {error:#}"
));
}
drop(storage_guard);
result?;
profile_storage::check().context("Profile refresh was saved")
})
.await
.await?
}
#[derive(Debug, PartialEq, Eq)]
+17 -14
View File
@@ -279,21 +279,24 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
zip.add_directory("profiles/", SimpleFileOptions::default())?;
let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
if let Ok(mut entries) = fs::read_dir(dirs::app_profiles_dir()?).await {
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
if path.is_file() {
let file_name_os = entry.file_name();
let file_name = file_name_os
.to_str()
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
let backup_path = format!("profiles/{}", file_name);
zip.start_file(backup_path, options)?;
let file_content = fs::read(&path).await?;
zip.write_all(&file_content)?;
}
let profile_guard = crate::config::profile_storage::read().await?;
let mut entries = fs::read_dir(dirs::app_profiles_dir()?).await?;
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
if path.is_file() {
let file_name_os = entry.file_name();
let file_name = file_name_os
.to_str()
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
let backup_path = format!("profiles/{}", file_name);
zip.start_file(backup_path, options)?;
let file_content = fs::read(&path).await?;
zip.write_all(&file_content)?;
}
}
let profile_index = fs::read(dirs::profiles_path()?).await?;
drop(profile_guard);
zip.start_file(dirs::CLASH_CONFIG, options)?;
zip.write_all(fs::read(dirs::clash_path()?).await?.as_slice())?;
@@ -314,7 +317,7 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
}
zip.start_file(dirs::PROFILE_YAML, options)?;
zip.write_all(fs::read(dirs::profiles_path()?).await?.as_slice())?;
zip.write_all(&profile_index)?;
zip.finish()?;
Ok((zip_file_name, zip_path))
}
+2
View File
@@ -231,6 +231,8 @@ impl CoreManager {
pub async fn init(&self) -> Result<bool> {
const MAX_PORT_FALLBACK_RETRIES: usize = 3;
crate::config::profile_storage::check()?;
if let Some(reason) = crate::config::Config::startup_core_block_reason() {
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
}
+22 -7
View File
@@ -246,10 +246,14 @@ async fn read_dns_settings(enabled: bool) -> Option<Mapping> {
serde_yaml_ng::from_str(&yaml).ok()
}
/// Returns the enhanced profile, its original keys, script logs, and DNS override decision.
pub async fn enhance(
profiles: &IProfiles,
) -> Result<(Mapping, HashSet<String>, HashMap<String, ResultLog>, DnsOverrideState)> {
pub(crate) struct ProfileRenderInputs {
profile: RenderProfile,
settings: RenderSettings,
dns_config: Option<Mapping>,
dns_override: DnsOverrideState,
}
pub(crate) async fn collect_render_inputs(profiles: &IProfiles) -> Result<ProfileRenderInputs> {
let profile_uid = profiles.current.as_deref().unwrap_or_default();
let settings = get_config_values(profile_uid).await;
let profile = collect_profile_items(profiles).await?;
@@ -260,13 +264,24 @@ pub async fn enhance(
settings.dns_override_confirmation,
);
let dns_config = read_dns_settings(dns_override.enabled).await;
Ok(ProfileRenderInputs {
profile,
settings: settings.render,
dns_config,
dns_override,
})
}
/// Returns the enhanced profile, its original keys, script logs, and DNS override decision.
pub(crate) async fn enhance(
inputs: ProfileRenderInputs,
) -> (Mapping, HashSet<String>, HashMap<String, ResultLog>, DnsOverrideState) {
let RenderedConfig {
config,
exists_keys,
logs,
discarded_keys,
} = render(profile, settings.render, dns_config).await;
} = render(inputs.profile, inputs.settings, inputs.dns_config).await;
notify_discarded_keys(discarded_keys);
Ok((config, exists_keys, logs, dns_override))
(config, exists_keys, logs, inputs.dns_override)
}
+104 -47
View File
@@ -1,5 +1,5 @@
use crate::{
config::{Config, IClashTemp, IVerge, profiles::load_profiles},
config::{Config, IClashTemp, IVerge, profiles::load_profiles_checked},
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
process::AsyncHandler,
utils::{
@@ -12,9 +12,14 @@ use chrono::Utc;
use clash_verge_logging::{Type, logging};
use reqwest_dav::list_cmd::ListFile;
use serde::Serialize;
use std::path::PathBuf;
use std::{
fs::File,
io,
path::{Path, PathBuf},
};
use tokio::fs;
use tristr::alias::String;
use zip::ZipArchive;
#[derive(Debug, Serialize, specta::Type)]
pub struct LocalBackupFile {
@@ -29,16 +34,30 @@ async fn finalize_restored_verge_config(
webdav_url: Option<String>,
webdav_username: Option<String>,
webdav_password: Option<String>,
archive: ZipArchive<File>,
) -> Result<()> {
let config_write = Config::lock_config_write().await;
// A broken restored `verge.yaml` is a restore failure, not a reason to load defaults.
let mut restored = help::read_yaml::<IVerge>(&verge_path()?).await?;
restored.webdav_url = webdav_url;
restored.webdav_username = webdav_username;
restored.webdav_password = webdav_password;
restored.save_file().await?;
let profiles_draft = Config::profiles().await;
let mut profile_guard = None;
let restored = {
let guard = &mut profile_guard;
let draft = &profiles_draft;
profiles_draft
.with_data_modify(|_| async move {
*guard = Some(crate::config::profile_storage::write().await?);
let (profiles, mut restored) = restore_files(archive).await?;
restored.webdav_url = webdav_url;
restored.webdav_username = webdav_username;
restored.webdav_password = webdav_password;
if let Err(error) = restored.save_file().await {
crate::config::profile_storage::block(&error);
return Err(error);
}
draft.discard();
Ok((profiles, restored))
})
.await?
};
let restored_clash = IClashTemp::new().await;
let clash_draft = Config::clash().await;
clash_draft.edit_draft(|d| {
@@ -46,18 +65,12 @@ async fn finalize_restored_verge_config(
});
clash_draft.apply();
let restored_profiles = load_profiles().await;
let profiles_draft = Config::profiles().await;
profiles_draft.edit_draft(|d| {
*d = restored_profiles;
});
profiles_draft.apply();
let verge_draft = Config::verge().await;
verge_draft.edit_draft(|d| {
*d = restored.clone();
});
verge_draft.apply();
drop(profile_guard);
auto_backup::publish_settings(&verge_draft.data_arc());
// Turn it off here; a failing core side effect below would otherwise skip this step.
@@ -132,8 +145,58 @@ pub async fn delete_webdav_backup(filename: String) -> Result<()> {
})
}
fn prepare_restore_archive(path: &Path) -> Result<ZipArchive<File>> {
let mut archive = ZipArchive::new(File::open(path)?)?;
for i in 0..archive.len() {
let mut entry = archive.by_index(i)?;
anyhow::ensure!(!entry.is_symlink(), "backup contains a symbolic link");
let path = entry
.enclosed_name()
.ok_or_else(|| anyhow!("backup contains an invalid path"))?;
for component in path.components() {
if let std::path::Component::Normal(name) = component {
let name = name.to_string_lossy();
anyhow::ensure!(
!name.eq_ignore_ascii_case(".profile-refresh")
&& !name.eq_ignore_ascii_case(".profile-refresh.lock"),
"archive contains profile recovery data"
);
}
}
io::copy(&mut entry, &mut io::sink())?;
}
Ok(archive)
}
async fn restore_files(mut archive: ZipArchive<File>) -> Result<(crate::config::IProfiles, IVerge)> {
let home_dir = app_home_dir()?;
AsyncHandler::spawn_blocking(move || -> Result<()> {
let extracted = archive.extract(&home_dir).map_err(anyhow::Error::from);
if let Err(error) = &extracted {
crate::config::profile_storage::block(error);
}
extracted
})
.await
.map_err(|join| anyhow!("backup extraction task failed: {join}"))??;
let loaded = async {
let verge = help::read_yaml::<IVerge>(&verge_path()?).await?;
let profiles = load_profiles_checked().await?;
Ok((profiles, verge))
}
.await;
if let Err(error) = &loaded {
crate::config::profile_storage::block(error);
}
loaded
}
/// Backup creation strips the WebDAV credentials, so the live ones are kept.
async fn restore_backup_archive(path: PathBuf) -> Result<()> {
crate::config::profile_storage::check()?;
let archive = AsyncHandler::spawn_blocking(move || prepare_restore_archive(&path))
.await
.map_err(|join| anyhow!("backup preflight task failed: {join}"))??;
let (webdav_url, webdav_username, webdav_password) = {
let verge = Config::verge().await;
let verge = verge.latest_arc();
@@ -144,41 +207,35 @@ async fn restore_backup_archive(path: PathBuf) -> Result<()> {
)
};
let home_dir = app_home_dir()?;
AsyncHandler::spawn_blocking(move || -> Result<()> {
let file = std::fs::File::open(&path)?;
let mut zip = zip::ZipArchive::new(file)?;
zip.extract(&home_dir)?;
Ok(())
tokio::spawn(async move {
let _profile_write = crate::config::profiles::PROFILE_WRITE_LOCK.lock().await;
finalize_restored_verge_config(webdav_url, webdav_username, webdav_password, archive).await
})
.await
.map_err(|join| anyhow!("backup extraction task failed: {join}"))??;
let _profile_write = crate::config::profiles::PROFILE_WRITE_LOCK.lock().await;
finalize_restored_verge_config(webdav_url, webdav_username, webdav_password).await
.await?
}
#[tracing::instrument(skip_all, level = "info", fields(filename = %filename))]
pub async fn restore_webdav_backup(filename: String) -> Result<()> {
let backup_storage_path = app_home_dir()
.map_err(|e| anyhow::anyhow!("Failed to get app home dir: {e}"))?
.join(filename.as_str());
let name = filename.clone();
backup::WebDavClient::global()
.download(filename, backup_storage_path.clone())
.await
.map_err(|err| {
logging!(
error,
Type::Backup,
"Failed to download WebDAV backup file {name}: {err:#}"
);
err
})?;
let res = restore_backup_archive(backup_storage_path.clone()).await;
let _ = backup_storage_path.remove_if_exists().await;
res
tokio::spawn(async move {
let archive_dir = tempfile::tempdir()?;
let archive = archive_dir.path().join("backup.zip");
let name = filename.clone();
backup::WebDavClient::global()
.download(filename, archive.clone())
.await
.map_err(|err| {
logging!(
error,
Type::Backup,
"Failed to download WebDAV backup file {name}: {err:#}"
);
err
})?;
let result = restore_backup_archive(archive).await;
drop(archive_dir);
result
})
.await?
}
pub async fn create_local_backup() -> Result<()> {
+7 -4
View File
@@ -34,10 +34,13 @@ pub async fn set_dns_override(
profiles.current.as_ref() == Some(&profile_uid),
"The active profile changed; retry the DNS setting"
);
let source = dns_override_source(
profiles.current.as_deref().unwrap_or_default(),
&current_mapping(&profiles).await?,
)?;
let source = {
let _guard = crate::config::profile_storage::read().await?;
dns_override_source(
profiles.current.as_deref().unwrap_or_default(),
&current_mapping(&profiles).await?,
)?
};
if enabled && let Some(source) = source.as_ref().filter(|source| Some(*source) != confirmation.as_ref()) {
return Ok(DnsOverrideOutcome::ConfirmationRequired { source: source.clone() });
}
+20 -12
View File
@@ -1,5 +1,5 @@
use crate::{
config::{Config, PrfOption, fetch_remote_refresh, profiles::apply_remote_refresh_safe},
config::{Config, PrfOption, fetch_remote_refresh, profile_storage, profiles::apply_remote_refresh_safe},
core::{
CoreManager, handle,
notify::{NoticeStatus, Refresh, announce},
@@ -11,8 +11,15 @@ use anyhow::{Result, bail};
use clash_verge_logging::{Type, logging};
use tristr::alias::String;
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
struct RefreshSource {
url: String,
file: Option<String>,
option: Option<PrfOption>,
}
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<RefreshSource>> {
let profiles = Config::profiles().await;
let _guard = profile_storage::read().await?;
let profiles = profiles.latest_arc();
let item = profiles.get_item(uid)?;
let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote");
@@ -37,22 +44,23 @@ async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Op
.ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?
)
);
Ok(Some((
item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?,
item.option.clone(),
)))
Ok(Some(RefreshSource {
url: item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?,
file: item.file.clone(),
option: item.option.clone(),
}))
}
}
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
async fn perform_profile_update(
uid: &str,
url: &str,
opt: Option<&PrfOption>,
source: &RefreshSource,
option: Option<&PrfOption>,
is_manual_trigger: bool,
) -> Result<()> {
let merged_opt = PrfOption::merge(opt, option);
let url = source.url.as_str();
let merged_opt = PrfOption::merge(source.option.as_ref(), option);
let profiles = Config::profiles().await;
let profiles_arc = profiles.latest_arc();
let profile_name = profiles_arc
@@ -122,7 +130,7 @@ async fn perform_profile_update(
let last_err = match result {
Ok((strategy, refresh)) => {
// A persistence error must not replay a successful download with another transport.
apply_remote_refresh_safe(uid, refresh).await?;
apply_remote_refresh_safe(uid, url, source.file.clone(), refresh).await?;
if !matches!(strategy, Strategy::Configured) {
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
}
@@ -146,8 +154,8 @@ pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_tri
let url_opt = should_update_profile(uid, is_manual_trigger).await?;
let profile_persisted = match url_opt {
Some((url, opt)) => {
perform_profile_update(uid, &url, opt.as_ref(), option, is_manual_trigger).await?;
Some(source) => {
perform_profile_update(uid, &source, option, is_manual_trigger).await?;
true
}
None => false,
+6 -1
View File
@@ -470,7 +470,8 @@ async fn initialize_config_files() -> Result<()> {
logging!(info, Type::Setup, "Created verge config at {:?}", path);
}
if let Ok(path) = dirs::profiles_path()
if crate::config::profile_storage::check().is_ok()
&& let Ok(path) = dirs::profiles_path()
&& !path.exists()
{
let template = IProfiles::default();
@@ -489,6 +490,10 @@ async fn initialize_config_files() -> Result<()> {
/// Initializes configuration required before Tauri setup.
pub async fn init_config() -> Result<()> {
if let Err(error) = crate::config::profile_storage::recover_at_startup().await {
logging!(error, Type::Config, "Profile recovery failed: {error:#}");
}
#[cfg(target_os = "macos")]
migrate_legacy_macos_logs().await?;