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
+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,