mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-05 05:50:04 +08:00
fix(profile): identify subscriptions that need recovery
This commit is contained in:
@@ -34,11 +34,23 @@ fn profile_import_error(err: &anyhow::Error) -> std::string::String {
|
||||
format!("导入订阅失败: {err:#}")
|
||||
}
|
||||
|
||||
fn profile_command_error(error: anyhow::Error, fallback: Option<&str>) -> super::CommandFailure {
|
||||
if error.is::<crate::config::profile_storage::RecoveryRequired>() {
|
||||
coded_error("PROFILE_RECOVERY_REQUIRED", format_args!("{error:#}"))
|
||||
} else if let Some(code) = fallback {
|
||||
coded_error(code, format_args!("{error:#}"))
|
||||
} else {
|
||||
super::CommandFailure::plain(error)
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[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 _guard = crate::config::profile_storage::read()
|
||||
.await
|
||||
.map_err(|error| profile_command_error(error, None))?;
|
||||
let data = draft.data_arc();
|
||||
Ok(data)
|
||||
}
|
||||
@@ -146,7 +158,7 @@ pub async fn update_profile(index: std::string::String, option: Option<PrfOption
|
||||
feat::update_profile(&index, option.as_ref(), true)
|
||||
.await
|
||||
.inspect_err(|e| logging!(error, Type::Cmd, "update profile failed: {e:#}"))
|
||||
.with_error_code("PROFILE_UPDATE_FAILED")
|
||||
.map_err(|error| profile_command_error(error, Some("PROFILE_UPDATE_FAILED")))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use anyhow::{Result, anyhow};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_profile_store::RECOVERY_JOURNAL_NAME;
|
||||
use parking_lot::Mutex;
|
||||
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||
@@ -7,23 +8,51 @@ static PROFILE_IO: RwLock<()> = RwLock::const_new(());
|
||||
static BLOCKED: Mutex<Option<StorageBlock>> = Mutex::new(None);
|
||||
|
||||
enum StorageBlock {
|
||||
Transaction(String),
|
||||
Transaction(RecoveryRequired),
|
||||
Restore(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct RecoveryRequired(Option<String>);
|
||||
|
||||
impl std::fmt::Display for RecoveryRequired {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&match self.0.as_deref() {
|
||||
Some(name) => clash_verge_i18n::t!("profileRecovery.named", name = name),
|
||||
None => clash_verge_i18n::t!("profileRecovery.unknown"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RecoveryRequired {}
|
||||
|
||||
pub(crate) fn check() -> Result<()> {
|
||||
match BLOCKED.lock().as_ref() {
|
||||
Some(StorageBlock::Transaction(reason) | StorageBlock::Restore(reason)) => {
|
||||
Err(anyhow!("Profile storage requires recovery before use: {reason}"))
|
||||
}
|
||||
Some(StorageBlock::Transaction(recovery)) => Err(recovery.clone().into()),
|
||||
Some(StorageBlock::Restore(reason)) => Err(anyhow!("Profile storage requires recovery before use: {reason}")),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn block(error: &anyhow::Error) {
|
||||
pub(crate) fn block(name: Option<&str>, error: &anyhow::Error) -> anyhow::Error {
|
||||
logging!(error, Type::Config, "Profile recovery required: {error:#}");
|
||||
let mut blocked = BLOCKED.lock();
|
||||
if !matches!(*blocked, Some(StorageBlock::Transaction(_))) {
|
||||
*blocked = Some(StorageBlock::Transaction(format!("{error:#}")));
|
||||
if let Some(StorageBlock::Transaction(recovery)) = blocked.as_ref() {
|
||||
return recovery.clone().into();
|
||||
}
|
||||
let recovery = RecoveryRequired(name.filter(|name| !name.trim().is_empty()).map(str::to_owned));
|
||||
*blocked = Some(StorageBlock::Transaction(recovery.clone()));
|
||||
drop(blocked);
|
||||
recovery.into()
|
||||
}
|
||||
|
||||
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
|
||||
fn block_store(error: clash_verge_profile_store::StoreError) -> anyhow::Error {
|
||||
match error {
|
||||
clash_verge_profile_store::StoreError::NamedRecovery { name, source } => {
|
||||
block(Some(&name), &anyhow::Error::from(*source))
|
||||
}
|
||||
error => block(None, &error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +67,7 @@ pub(crate) async fn write_for_restore() -> Result<(RwLockWriteGuard<'static, ()>
|
||||
let guard = PROFILE_IO.write().await;
|
||||
let retry = match BLOCKED.lock().as_ref() {
|
||||
Some(StorageBlock::Transaction(reason)) => {
|
||||
return Err(anyhow!("Profile storage requires recovery before use: {reason}"));
|
||||
return Err(reason.clone().into());
|
||||
}
|
||||
Some(StorageBlock::Restore(_)) => true,
|
||||
None => false,
|
||||
@@ -67,25 +96,21 @@ pub(crate) async fn write() -> Result<RwLockWriteGuard<'static, ()>> {
|
||||
|
||||
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(());
|
||||
}
|
||||
let root = crate::utils::dirs::app_home_dir().map_err(|error| block(None, &error))?;
|
||||
if !journal_exists(&root).await.map_err(|error| block(None, &error))? {
|
||||
return Ok(());
|
||||
}
|
||||
tokio::task::spawn_blocking(move || {
|
||||
#[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"
|
||||
return clash_verge_profile_store::recover_pending(&root).map_err(block_store);
|
||||
#[cfg(all(windows, not(feature = "profile-store-windows")))]
|
||||
return Err(block(
|
||||
clash_verge_profile_store::pending_refresh_name(&root).as_deref(),
|
||||
&anyhow!("restore the pending profile transaction with redo support enabled"),
|
||||
));
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = &result {
|
||||
block(error);
|
||||
}
|
||||
result
|
||||
})
|
||||
.await
|
||||
.map_err(|error| block(None, &error.into()))?
|
||||
}
|
||||
|
||||
async fn journal_exists(root: &std::path::Path) -> Result<bool> {
|
||||
@@ -158,18 +183,20 @@ async fn commit_recoverable_refresh(
|
||||
if !supported {
|
||||
if journal_exists(&root).await? {
|
||||
let error = anyhow!("Profile refresh journal requires a supported NTFS volume");
|
||||
block(&error);
|
||||
return Err(error);
|
||||
return Err(block(
|
||||
clash_verge_profile_store::pending_refresh_name(&root).as_deref(),
|
||||
&error,
|
||||
));
|
||||
}
|
||||
write_legacy_refresh(&root, &uid, &candidate, body.as_bytes()).await?;
|
||||
return Ok(candidate);
|
||||
}
|
||||
}
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let session = Session::open(&root).map_err(anyhow::Error::from).inspect_err(|error| {
|
||||
let session = Session::open(&root).map_err(|error| {
|
||||
match std::fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)) {
|
||||
Err(status) if status.kind() == std::io::ErrorKind::NotFound => {}
|
||||
_ => block(error),
|
||||
Err(status) if status.kind() == std::io::ErrorKind::NotFound => error.into(),
|
||||
_ => block_store(error),
|
||||
}
|
||||
})?;
|
||||
let item = candidate.get_item(&uid)?;
|
||||
@@ -191,7 +218,7 @@ async fn commit_recoverable_refresh(
|
||||
match session.commit_refresh(&uid, &candidate, body.as_bytes()) {
|
||||
CommitOutcome::Committed => Ok(candidate),
|
||||
CommitOutcome::CommittedCleanupPending(error) => {
|
||||
block(&error.into());
|
||||
let _ = block(item.name.as_deref(), &error.into());
|
||||
Ok(candidate)
|
||||
}
|
||||
CommitOutcome::Retryable(error) => {
|
||||
@@ -199,13 +226,11 @@ async fn commit_recoverable_refresh(
|
||||
}
|
||||
CommitOutcome::RetryCleanupFailed(error) => {
|
||||
let error = anyhow::Error::from(error);
|
||||
block(&error);
|
||||
Err(error.context("failed to discard the incomplete profile refresh"))
|
||||
Err(block(item.name.as_deref(), &error).context("failed to discard the incomplete profile refresh"))
|
||||
}
|
||||
CommitOutcome::NeedsRecovery(error) => {
|
||||
let error = anyhow::Error::from(error);
|
||||
block(&error);
|
||||
Err(error.context("profile refresh requires recovery"))
|
||||
Err(block(item.name.as_deref(), &error))
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -214,8 +239,7 @@ async fn commit_recoverable_refresh(
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
let error = anyhow::Error::from(error).context("profile storage worker stopped unexpectedly");
|
||||
block(&error);
|
||||
Err(error)
|
||||
Err(block(None, &error))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -224,6 +248,15 @@ async fn commit_recoverable_refresh(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recovery_message_identifies_the_subscription_in_the_active_language() {
|
||||
let named = RecoveryRequired(Some("工作线路".into())).to_string();
|
||||
assert!(named.contains("工作线路"));
|
||||
let unknown = RecoveryRequired(None).to_string();
|
||||
assert!(!unknown.contains("工作线路"));
|
||||
assert_ne!(unknown, "profileRecovery.unknown");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_refresh_reports_a_written_body_when_index_replace_fails() -> Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
|
||||
@@ -318,7 +318,11 @@ pub(crate) async fn save_remote_refresh(
|
||||
let _profile_write = PROFILE_WRITE_LOCK.lock().await;
|
||||
anyhow::ensure!(!handle::Handle::global().is_exiting(), "application is exiting");
|
||||
let draft = Config::profiles().await;
|
||||
check_refresh_source(draft.data_arc().get_item(&uid)?, &url, file.as_ref())?;
|
||||
let snapshot = draft.data_arc();
|
||||
let source = snapshot.get_item(&uid)?;
|
||||
check_refresh_source(source, &url, file.as_ref())?;
|
||||
let name = source.name.clone();
|
||||
drop(snapshot);
|
||||
let refresh = prepare_remote_refresh(downloaded, options.as_ref()).await?;
|
||||
let mut storage_guard = None;
|
||||
let mut persisted = false;
|
||||
@@ -346,10 +350,7 @@ pub(crate) async fn save_remote_refresh(
|
||||
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:#}"
|
||||
));
|
||||
return Err(profile_storage::block(name.as_deref(), error).context("Profile refresh was saved"));
|
||||
}
|
||||
drop(storage_guard);
|
||||
result?;
|
||||
|
||||
Reference in New Issue
Block a user