mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-03 12:20:05 +08:00
fix(profile): recover interrupted subscription refreshes
Keep subscription body and index writes recoverable, and coordinate startup, readers, backup, and Draft publication around the transaction.
This commit is contained in:
@@ -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);
|
||||
|
||||
@@ -7,6 +7,7 @@ pub(crate) mod mihomo_yaml;
|
||||
mod mixed_port;
|
||||
mod port;
|
||||
mod prfitem;
|
||||
pub(crate) mod profile_storage;
|
||||
pub mod profiles;
|
||||
pub mod runtime;
|
||||
pub(crate) mod snapshot;
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
use anyhow::{Result, anyhow};
|
||||
use clash_verge_profile_store::RECOVERY_JOURNAL_NAME;
|
||||
use std::sync::OnceLock;
|
||||
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||
|
||||
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(RECOVERY_JOURNAL_NAME)).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(RECOVERY_JOURNAL_NAME)) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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::{
|
||||
@@ -70,52 +71,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,
|
||||
@@ -193,30 +195,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.
|
||||
@@ -287,6 +281,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, ()))
|
||||
})
|
||||
@@ -315,12 +310,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?
|
||||
}
|
||||
|
||||
fn selected_group<'a>(snapshot: &'a Proxies, name: &str) -> Option<SelectedGroup<'a>> {
|
||||
|
||||
Reference in New Issue
Block a user