fix(profile): identify subscriptions that need recovery

This commit is contained in:
Tunglies
2026-12-04 07:37:51 +08:00
parent 235a0507f0
commit 70d6917104
25 changed files with 236 additions and 52 deletions
+1
View File
@@ -28,6 +28,7 @@
<details>
<summary><strong> 🐞 修复问题 </strong></summary>
- 优化订阅恢复失败提示,显示受影响的订阅名称
- 修复「外部控制器」复制成功的提示一闪而过
- 修复订阅的规则、代理组、节点编辑器快速连续操作时条目可能重复或错位
- 修复检测更新后又发布新版时,应用内更新失败
+3
View File
@@ -0,0 +1,3 @@
fn main() {
println!("cargo::rerun-if-changed=locales");
}
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: وكيل النظام
tun: TUN
profile: ملف تعريفي
profileRecovery:
named: يجب استعادة الاشتراك «{name}». راجع سجل التطبيق للاطلاع على التفاصيل.
unknown: يجب استعادة أحد الاشتراكات، لكن تعذّر تحديده. راجع سجل التطبيق للاطلاع على التفاصيل.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: Systemproxy
tun: TUN
profile: Profil
profileRecovery:
named: Das Abonnement „{name}“ muss wiederhergestellt werden. Details stehen im Anwendungsprotokoll.
unknown: Ein Abonnement muss wiederhergestellt werden, konnte aber nicht identifiziert werden. Details stehen im Anwendungsprotokoll.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: System Proxy
tun: TUN
profile: Profile
profileRecovery:
named: Subscription “{name}” needs recovery. See the application log for details.
unknown: Subscription recovery is required. The affected subscription could not be identified. See the application log for details.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: Proxy del sistema
tun: TUN
profile: Perfil
profileRecovery:
named: Hay que recuperar la suscripción «{name}». Consulta el registro de la aplicación para más detalles.
unknown: Hay que recuperar una suscripción, pero no se pudo identificar cuál. Consulta el registro de la aplicación para más detalles.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: پروکسی سیستم
tun: TUN
profile: پروفایل
profileRecovery:
named: اشتراک «{name}» باید بازیابی شود. برای جزئیات، گزارش برنامه را ببینید.
unknown: بازیابی اشتراک لازم است، اما اشتراک موردنظر شناسایی نشد. برای جزئیات، گزارش برنامه را ببینید.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: Proksi Sistem
tun: TUN
profile: Profil
profileRecovery:
named: Langganan “{name}” perlu dipulihkan. Lihat log aplikasi untuk detailnya.
unknown: Langganan perlu dipulihkan, tetapi langganan yang terdampak tidak dapat diidentifikasi. Lihat log aplikasi untuk detailnya.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: システムプロキシ
tun: TUN
profile: プロファイル
profileRecovery:
named: サブスクリプション「{name}」の復旧が必要です。詳細はアプリのログを確認してください。
unknown: サブスクリプションの復旧が必要ですが、対象を特定できません。詳細はアプリのログを確認してください。
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: 시스템 프록시
tun: TUN
profile: 프로필
profileRecovery:
named: “{name}” 구독을 복구해야 합니다. 자세한 내용은 앱 로그를 확인하세요.
unknown: 구독을 복구해야 하지만 해당 구독을 식별할 수 없습니다. 자세한 내용은 앱 로그를 확인하세요.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: Proxy do sistema
tun: TUN
profile: Perfil
profileRecovery:
named: É necessário recuperar a assinatura “{name}”. Consulte o registro do aplicativo para mais detalhes.
unknown: É necessário recuperar uma assinatura, mas não foi possível identificá-la. Consulte o registro do aplicativo para mais detalhes.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: Системный прокси
tun: TUN
profile: Профиль
profileRecovery:
named: Подписку «{name}» нужно восстановить. Подробности в журнале приложения.
unknown: Не удалось определить, какую подписку необходимо восстановить. Подробности в журнале приложения.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: Sistem Vekil'i
tun: TUN
profile: Profil
profileRecovery:
named: “{name}” aboneliğinin kurtarılması gerekiyor. Ayrıntılar için uygulama günlüğüne bakın.
unknown: Kurtarılması gereken abonelik belirlenemedi. Ayrıntılar için uygulama günlüğüne bakın.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: Системалы прокси
tun: TUN
profile: Профиль
profileRecovery:
named: «{name}» язылуын торгызырга кирәк. Тулырак мәгълүмат кушымта журналында.
unknown: Кайсы язылуны торгызырга кирәклеген билгеләп булмады. Тулырак мәгълүмат кушымта журналында.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: 系统代理
tun: TUN
profile: 订阅
profileRecovery:
named: 订阅「{name}」需要恢复,详情请查看应用日志。
unknown: 订阅需要恢复,但无法识别受影响的订阅。详情请查看应用日志。
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: 系統代理
tun: 虛擬網路介面卡
profile: 訂閱
profileRecovery:
named: 訂閱「{name}」需要復原,詳情請查看應用程式記錄。
unknown: 訂閱需要復原,但無法識別受影響的訂閱。詳情請查看應用程式記錄。
@@ -2,6 +2,8 @@ use std::{io, path::PathBuf};
#[derive(Debug, thiserror::Error)]
pub enum StoreError {
#[error("could not recover subscription “{name}”: {source}")]
NamedRecovery { name: String, source: Box<Self> },
#[error(transparent)]
Io(#[from] io::Error),
#[error("{operation} {}", path.display())]
+45 -2
View File
@@ -85,12 +85,27 @@ impl Session {
}
#[cfg(windows)]
if !platform::supports_redo(&root)? {
return Err(StoreError::UnsupportedVolume);
let source = StoreError::UnsupportedVolume;
return Err(match pending_refresh_name(&root) {
Some(name) => StoreError::NamedRecovery {
name,
source: Box::new(source),
},
None => source,
});
}
let lock = platform::open_lock(&root.join(RECOVERY_LOCK_NAME))?;
lock.lock()?;
let session = Self { root, _lock: lock };
session.recover(checkpoint)?;
session
.recover(checkpoint)
.map_err(|error| match refresh_name(&session.root) {
Some(name) => StoreError::NamedRecovery {
name,
source: Box::new(error),
},
None => error,
})?;
Ok(session)
}
@@ -637,6 +652,34 @@ fn remove_file_if_exists(path: &Path) -> Result<()> {
}
}
fn refresh_name(root: &Path) -> Option<String> {
let journal = root.join(RECOVERY_JOURNAL_NAME);
directory(&journal).ok()?;
let marker = match optional_regular(&journal.join(DECISION)).ok()? {
Some(_) => DECISION,
None => DECISION_NEXT,
};
let decision = read_decision(&journal.join(marker)).ok()?;
let (index, _) = verified(&journal.join(INDEX_NEXT), decision.index_digest).ok()?;
let profiles: IProfiles = serde_yaml_ng::from_slice(&index).ok()?;
if body_filename(&profiles, &decision.uid).ok()? != decision.file {
return None;
}
let item = profiles.get_item(&decision.uid).ok()?;
item.name
.as_deref()
.filter(|name| !name.trim().is_empty())
.map(str::to_owned)
}
/// Identifies a pending transaction when this build or volume cannot replay it.
#[cfg(windows)]
pub fn pending_refresh_name(root: &Path) -> Option<String> {
let lock = File::open(root.join(RECOVERY_LOCK_NAME)).ok()?;
lock.try_lock_shared().ok()?;
refresh_name(root)
}
/// Replays a saved decision before the application creates or loads its index.
pub fn recover_pending(root: &Path) -> Result<()> {
match fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)) {
@@ -96,3 +96,33 @@ fn interrupted_creation_reverts_an_aliased_body() -> Result<(), clash_verge_prof
));
Ok(())
}
#[cfg(feature = "test-support")]
#[test]
fn recovery_identifies_the_interrupted_subscription_from_its_verified_index()
-> Result<(), clash_verge_profile_store::StoreError> {
use clash_verge_profile_store::{StoreError, recover_pending};
let home = tempfile::tempdir()?;
let root = home.path();
fs::create_dir(root.join("profiles"))?;
let index = "current: other\nitems:\n- {uid: other, name: Home, type: remote, file: other.yaml}\n- {uid: opaque, name: 工作线路, type: remote, file: target.yaml}\n";
fs::write(root.join("profiles.yaml"), index)?;
let candidate = serde_yaml_ng::from_str(index)?;
let outcome = Session::open(root)?.commit_observed("opaque", &candidate, b"new", &mut |phase| {
if phase == "decision-created" {
return Err(std::io::Error::other("interrupted").into());
}
Ok(())
});
assert!(matches!(outcome, CommitOutcome::NeedsRecovery(_)));
fs::write(root.join("profiles/target.yaml"), b"changed outside the refresh")?;
let error = recover_pending(root).unwrap_err();
assert!(
matches!(error, StoreError::NamedRecovery { name, source } if name == "工作线路" && matches!(*source, StoreError::LiveContentChanged(_)))
);
let journal = root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME);
fs::write(journal.join("index.next"), index.replace("工作线路", "Wrong"))?;
assert!(matches!(recover_pending(root), Err(StoreError::StagedChecksumMismatch)));
Ok(())
}
+14 -2
View File
@@ -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]
+70 -37
View File
@@ -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()?;
+6 -5
View File
@@ -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?;
+5 -2
View File
@@ -41,7 +41,7 @@ import {
viewProfile,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { failureCode, showNotice } from '@/services/notice-service'
import {
useProfileLoadingCache,
useSetProfileLoading,
@@ -431,7 +431,10 @@ const ProfileItemBase = (props: ProfileItemProps) => {
})
void mutateProfiles()
} catch {
} catch (err) {
if (failureCode(err) === 'PROFILE_RECOVERY_REQUIRED') {
showNotice.error(err)
}
} finally {
setLoading(false)
}
+17 -3
View File
@@ -16,7 +16,15 @@ import {
RefreshRounded,
TextSnippetOutlined,
} from '@mui/icons-material'
import { Box, Button, Divider, Grid, IconButton, Stack } from '@mui/material'
import {
Alert,
Box,
Button,
Divider,
Grid,
IconButton,
Stack,
} from '@mui/material'
import { getCurrentWindow } from '@tauri-apps/api/window'
import { readText } from '@tauri-apps/plugin-clipboard-manager'
import { readTextFile } from '@tauri-apps/plugin-fs'
@@ -50,7 +58,7 @@ import {
updateProfile,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { errorDetail, showNotice } from '@/services/notice-service'
import { errorDetail, failureCode, showNotice } from '@/services/notice-service'
import { revalidateQuery, useQuery } from '@/services/query-client'
import { useThemeMode } from '@/services/states'
import {
@@ -553,7 +561,10 @@ const ProfilePage = () => {
errorNotice: false,
})
throttleMutate()
} catch (err: any) {
} catch (err) {
if (failureCode(err) === 'PROFILE_RECOVERY_REQUIRED') {
showNotice.error(err)
}
console.error(`更新订阅 ${uid} 失败:`, err)
}
}
@@ -831,6 +842,9 @@ const ProfilePage = () => {
</Box>
}
>
{failureCode(error) === 'PROFILE_RECOVERY_REQUIRED' && (
<Alert severity="error">{errorDetail(error)}</Alert>
)}
<Stack
direction="row"
spacing={1}
+1 -1
View File
@@ -481,7 +481,7 @@ const baseShowNotice = (
return id
}
function failureCode(input: unknown): string | undefined {
export function failureCode(input: unknown): string | undefined {
return isCommandFailure(input) ? input.code! : undefined
}