mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-06 14:40:08 +08:00
refactor(backend): extract profile and subscription capabilities (#8800)
* chore(clippy): scope crate lint policy Keep panic-on-error lints at application target roots and scope signal dependencies to Linux. * docs(agents): define Rust backend architecture boundaries Document which layer owns Rust capabilities, fallible inputs, background work, and crate validation. * refactor(draft): type async publication conflicts Return typed conflicts for async Draft edits. Release the lock and edit permit before converting the error, and exercise overlapping updates. * refactor(logging): use typed logger errors Expose crate-owned logger errors and preserve the underlying error sources. * refactor(subscription): extract response decoding Keep HTTP and persistence in the app. Decode response metadata and framing in the crate, and fall back when the server filename is invalid. * refactor(profile): extract profile models and index rules Move profile models and index rules into the crate, preserving serialization and returning a typed missing-profile error. * refactor(profile): separate subscription refresh and scheduling policy Separate download and scheduling policy from the subscription use case while retaining the existing write path. * refactor(subscription): decode deep links in the subscription crate * refactor(profile): extract selected node recovery rules * docs(agents): define dependencies between capability crates * refactor(task): move retry primitives into the task crate * refactor(backup): extract backup ZIP writing * refactor(subscription): keep profile writes outside proxy fallback * fix(profile): preserve delays for future update timestamps * fix(subscription): preserve filenames from response headers and URL paths * fix(subscription): separate deep link parameters from nested URLs * refactor(profile): look up the refresh target once * refactor(subscription): pass the proxy directly to each download * refactor(profile): build companion options in one place * refactor(profile): remove companions from the deleted profile * style(profile): keep profile fields together * refactor(profile): name index operations after what they change * refactor(profile): call the core reload directly * refactor(backup): move archive validation to the restore change
This commit is contained in:
@@ -4,7 +4,7 @@ use crate::feat;
|
||||
use crate::utils::{dirs, yaml_emitter};
|
||||
use crate::{
|
||||
cmd::StringifyErr as _,
|
||||
config::{ClashInfo, Config, profiles::profiles_save_file_safe},
|
||||
config::{ClashInfo, Config, profiles::save_committed_profiles},
|
||||
constants,
|
||||
core::{
|
||||
CoreManager, handle,
|
||||
@@ -59,7 +59,7 @@ pub async fn change_clash_core(clash_core: std::string::String) -> CmdResult<Opt
|
||||
|
||||
match CoreManager::global().change_core(&clash_core).await {
|
||||
Ok(_) => {
|
||||
logging_error!(Type::Core, profiles_save_file_safe().await);
|
||||
logging_error!(Type::Core, save_committed_profiles().await);
|
||||
|
||||
match CoreManager::global().restart_core().await {
|
||||
Ok(_) => {
|
||||
@@ -88,7 +88,7 @@ pub async fn change_clash_core(clash_core: std::string::String) -> CmdResult<Opt
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn restart_core() -> CmdResult {
|
||||
logging_error!(Type::Core, profiles_save_file_safe().await);
|
||||
logging_error!(Type::Core, save_committed_profiles().await);
|
||||
let result = CoreManager::global()
|
||||
.restart_core()
|
||||
.await
|
||||
|
||||
@@ -5,12 +5,12 @@ use crate::core::notify::NoticeStatus;
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
use crate::{
|
||||
config::{
|
||||
Config, IProfiles, PrfItem, PrfOption,
|
||||
Config, IProfiles, PrfItem, PrfOption, build_remote_profile,
|
||||
profiles::{
|
||||
PROFILE_WRITE_LOCK, profiles_append_item_with_filedata_safe, profiles_patch_item_safe,
|
||||
profiles_reorder_safe, profiles_save_file_safe,
|
||||
PROFILE_WRITE_LOCK, append_profile, cleanup_profile_files, patch_profile_item, reorder_profiles,
|
||||
save_committed_profiles, save_profiles,
|
||||
},
|
||||
profiles_append_item_safe,
|
||||
read_profile_item_file,
|
||||
},
|
||||
core::{CoreManager, handle, timer::Timer, tray::Tray, validate::ValidationOutcome},
|
||||
feat,
|
||||
@@ -45,7 +45,7 @@ pub async fn get_profiles() -> CmdResult<SharedDraft<IProfiles>> {
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn enhance_profiles() -> CmdResult<ValidationOutcome> {
|
||||
match feat::enhance_profiles().await {
|
||||
match CoreManager::global().update_config_forced().await {
|
||||
Ok(outcome) if outcome.is_valid() => {
|
||||
handle::Handle::refresh_clash();
|
||||
Ok(outcome)
|
||||
@@ -71,7 +71,7 @@ pub async fn enhance_profiles() -> CmdResult<ValidationOutcome> {
|
||||
#[tracing::instrument(skip_all, level = "info", fields(url = %help::mask_url(&url), uid = tracing::field::Empty))]
|
||||
#[specta::specta]
|
||||
pub async fn import_profile(url: std::string::String, option: Option<PrfOption>) -> CmdResult {
|
||||
let item = &mut match PrfItem::from_url(&url, None, None, option.as_ref()).await {
|
||||
let item = &mut match build_remote_profile(&url, None, None, option.as_ref()).await {
|
||||
Ok(it) => it,
|
||||
Err(e) => {
|
||||
logging!(error, Type::Cmd, "[导入订阅] 下载失败: {e:#}");
|
||||
@@ -79,12 +79,12 @@ pub async fn import_profile(url: std::string::String, option: Option<PrfOption>)
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = profiles_append_item_safe(item).await {
|
||||
if let Err(e) = append_profile(item).await {
|
||||
logging!(error, Type::Cmd, "[导入订阅] 保存配置失败: {e:#}");
|
||||
return Err(coded_error("PROFILE_IMPORT_FAILED", e));
|
||||
}
|
||||
|
||||
if let Err(e) = profiles_save_file_safe().await {
|
||||
if let Err(e) = save_committed_profiles().await {
|
||||
logging!(error, Type::Cmd, "[导入订阅] 保存配置文件失败: {e:#}");
|
||||
return Err(coded_error("PROFILE_IMPORT_FAILED", e));
|
||||
}
|
||||
@@ -103,7 +103,7 @@ pub async fn import_profile(url: std::string::String, option: Option<PrfOption>)
|
||||
pub async fn reorder_profile(active_id: std::string::String, over_id: std::string::String) -> CmdResult {
|
||||
let active_id: String = active_id.into();
|
||||
let over_id: String = over_id.into();
|
||||
match profiles_reorder_safe(&active_id, &over_id).await {
|
||||
match reorder_profiles(&active_id, &over_id).await {
|
||||
Ok(_) => {
|
||||
logging!(info, Type::Cmd, "重新排序配置文件: {} -> {}", active_id, over_id);
|
||||
Ok(())
|
||||
@@ -126,9 +126,9 @@ pub async fn reorder_profile(active_id: std::string::String, over_id: std::strin
|
||||
pub async fn create_profile(item: ProfileCreate, file_data: Option<std::string::String>) -> CmdResult {
|
||||
let item: PrfItem = item.into();
|
||||
let file_data = file_data.map(String::from);
|
||||
match profiles_append_item_with_filedata_safe(&item, file_data).await {
|
||||
match profiles::create_profile(&item, file_data).await {
|
||||
Ok(_) => {
|
||||
profiles_save_file_safe()
|
||||
save_committed_profiles()
|
||||
.await
|
||||
.with_error_code("PROFILE_CREATE_FAILED")?;
|
||||
logging_error!(Type::Timer, Timer::global().refresh().await);
|
||||
@@ -159,9 +159,10 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
||||
|
||||
let profiles = Config::profiles().await;
|
||||
let result = profiles
|
||||
.with_data_modify(|mut candidate| async move {
|
||||
.with_data_modify::<_, _, _, anyhow::Error>(|mut candidate| async move {
|
||||
let original = candidate.clone();
|
||||
let (should_update, plan) = candidate.plan_delete_item(&index)?;
|
||||
let plan = candidate.plan_delete_item(&index)?;
|
||||
let should_update = plan.deleting_current;
|
||||
let guard = if should_update {
|
||||
match CoreManager::global()
|
||||
.update_config_forced_with_profiles(&candidate, &original)
|
||||
@@ -171,11 +172,11 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
||||
Err(outcome) => return Ok((original, Err(outcome))),
|
||||
}
|
||||
} else {
|
||||
candidate.save_file().await?;
|
||||
save_profiles(&candidate).await?;
|
||||
None
|
||||
};
|
||||
let current = candidate.current.clone();
|
||||
plan.cleanup().await;
|
||||
cleanup_profile_files(plan.files).await;
|
||||
Ok((candidate, Ok((should_update, current, guard))))
|
||||
})
|
||||
.await
|
||||
@@ -210,18 +211,14 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn restore_previous_profile(prev_profile: &str) -> CmdResult<()> {
|
||||
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
|
||||
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
|
||||
let restore_profiles = IProfiles {
|
||||
current: Some(prev_profile.into()),
|
||||
items: None,
|
||||
};
|
||||
Config::profiles()
|
||||
.await
|
||||
.edit_draft(|d| d.patch_config(&restore_profiles));
|
||||
.edit_draft(|d| d.patch_current(Some(prev_profile)));
|
||||
Config::profiles().await.apply();
|
||||
crate::process::AsyncHandler::spawn(|| async move {
|
||||
if let Err(e) = profiles_save_file_safe().await {
|
||||
if let Err(e) = save_committed_profiles().await {
|
||||
logging!(warn, Type::Cmd, "异步保存恢复配置文件失败: {e:#}");
|
||||
}
|
||||
});
|
||||
@@ -236,10 +233,7 @@ async fn commit_current_profile(profiles: &Draft<IProfiles>, current: Option<Str
|
||||
|
||||
profiles
|
||||
.with_data_modify(|mut committed| async move {
|
||||
committed.patch_config(&IProfiles {
|
||||
current: Some(current),
|
||||
items: None,
|
||||
});
|
||||
committed.patch_current(Some(¤t));
|
||||
Ok((committed, ()))
|
||||
})
|
||||
.await
|
||||
@@ -252,7 +246,7 @@ async fn handle_success(current_value: Option<&String>) -> CmdResult<ValidationO
|
||||
// Runtime refresh and tray rebuilding happen after saved node selections are restored.
|
||||
profiles::activate_selected_nodes();
|
||||
|
||||
if let Err(e) = profiles_save_file_safe().await {
|
||||
if let Err(e) = save_committed_profiles().await {
|
||||
logging!(warn, Type::Cmd, "异步保存配置文件失败: {e:#}");
|
||||
}
|
||||
|
||||
@@ -397,16 +391,12 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
|
||||
});
|
||||
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
|
||||
|
||||
let profiles = IProfiles {
|
||||
current: profiles.current,
|
||||
items: None,
|
||||
};
|
||||
let target_profile = profiles.current.as_ref();
|
||||
|
||||
let previous_profile = Config::profiles().await.data_arc().current.clone();
|
||||
|
||||
Config::profiles().await.edit_draft(|d| {
|
||||
d.patch_config(&profiles);
|
||||
d.patch_current(target_profile);
|
||||
});
|
||||
|
||||
perform_config_update(target_profile, previous_profile.as_ref())
|
||||
@@ -442,7 +432,7 @@ pub async fn patch_profile(index: std::string::String, profile: ProfilePatch) ->
|
||||
// Prevent an in-flight restore from overwriting a newer UI or chain selection.
|
||||
let records_a_selection = profile.selected.is_some();
|
||||
|
||||
profiles_patch_item_safe(&index, &profile)
|
||||
patch_profile_item(&index, &profile)
|
||||
.await
|
||||
.with_error_code("PROFILE_UPDATE_FAILED")?;
|
||||
|
||||
@@ -492,20 +482,17 @@ 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 item = {
|
||||
let file = {
|
||||
let profiles = Config::profiles().await;
|
||||
let profiles_ref = profiles.latest_arc();
|
||||
PrfItem {
|
||||
file: profiles_ref
|
||||
.get_item(&index)
|
||||
.with_error_code("PROFILE_READ_FAILED")?
|
||||
.file
|
||||
.to_owned(),
|
||||
..Default::default()
|
||||
}
|
||||
profiles_ref
|
||||
.get_item(&index)
|
||||
.with_error_code("PROFILE_READ_FAILED")?
|
||||
.file
|
||||
.clone()
|
||||
};
|
||||
|
||||
if let Some(file) = item.file.as_ref() {
|
||||
if let Some(file) = file.as_ref() {
|
||||
let path = dirs::app_profiles_dir()
|
||||
.with_error_code("PROFILE_READ_FAILED")?
|
||||
.join(file.as_str());
|
||||
@@ -521,7 +508,9 @@ pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::str
|
||||
}
|
||||
}
|
||||
|
||||
let data = item.read_file().await.with_error_code("PROFILE_READ_FAILED")?;
|
||||
let data = read_profile_item_file(file.as_deref())
|
||||
.await
|
||||
.with_error_code("PROFILE_READ_FAILED")?;
|
||||
Ok(data.into())
|
||||
}
|
||||
|
||||
@@ -575,16 +564,11 @@ mod tests {
|
||||
current: Some("a".into()),
|
||||
items: Some(vec![profile("a"), profile("b")]),
|
||||
});
|
||||
profiles.edit_draft(|draft| {
|
||||
draft.patch_config(&IProfiles {
|
||||
current: Some("b".into()),
|
||||
items: None,
|
||||
});
|
||||
});
|
||||
profiles.edit_draft(|draft| draft.patch_current(Some(&"b".into())));
|
||||
profiles
|
||||
.with_data_modify(|mut committed| async move {
|
||||
committed.items.get_or_insert_with(Vec::new).push(profile("new"));
|
||||
Ok((committed, ()))
|
||||
Ok::<_, clash_verge_draft::DraftConflict>((committed, ()))
|
||||
})
|
||||
.await?;
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::CmdResult;
|
||||
use crate::{
|
||||
cmd::StringifyErr as _,
|
||||
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
|
||||
config::{Config, IProfiles, PrfItem},
|
||||
config::{Config, IProfiles, read_profile_item_file},
|
||||
core::auto_backup::{self, AutoBackupTrigger},
|
||||
core::{
|
||||
CoreManager, handle,
|
||||
@@ -58,13 +58,7 @@ pub async fn save_profile_file(
|
||||
))
|
||||
})?;
|
||||
let original_content = if original_existed {
|
||||
PrfItem {
|
||||
file: Some(rel_path.clone()),
|
||||
..Default::default()
|
||||
}
|
||||
.read_file()
|
||||
.await
|
||||
.stringify_err()?
|
||||
read_profile_item_file(Some(rel_path.as_str())).await.stringify_err()?
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user