refactor(profile): separate subscription refresh and scheduling policy

Separate download and scheduling policy from the subscription use case while retaining the existing write path.
This commit is contained in:
Tunglies
2026-11-30 18:44:12 +08:00
parent e31c01894a
commit 0415133c88
11 changed files with 407 additions and 306 deletions
+2 -2
View File
@@ -5,7 +5,7 @@ use crate::core::notify::NoticeStatus;
use crate::utils::window_manager::WindowManager;
use crate::{
config::{
Config, IProfiles, PrfItem, PrfOption, fetch_remote_profile,
Config, IProfiles, PrfItem, PrfOption, build_remote_profile,
profiles::{
PROFILE_WRITE_LOCK, cleanup_profile_files, profiles_append_item_safe,
profiles_append_item_with_filedata_safe, profiles_patch_item_safe, profiles_reorder_safe,
@@ -72,7 +72,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 fetch_remote_profile(&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:#}");
+1 -1
View File
@@ -12,7 +12,7 @@ pub(crate) mod snapshot;
mod verge;
pub(crate) use self::config::Config;
pub(crate) use self::prfitem::{fetch_remote_profile, read_profile_item_file};
pub(crate) use self::prfitem::{build_remote_profile, fetch_remote_refresh, read_profile_item_file};
pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*};
pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected};
+132 -52
View File
@@ -32,7 +32,7 @@ pub(super) async fn build_profile(item: &PrfItem, file_data: Option<String>) ->
let name = item.name.as_ref();
let desc = item.desc.as_ref();
let option = item.option.as_ref();
fetch_remote_profile(url, name, desc, option).await
build_remote_profile(url, name, desc, option).await
}
"local" => {
let name = item.name.clone().unwrap_or_else(|| "Local File".into());
@@ -117,24 +117,72 @@ async fn from_local(
})
}
pub(crate) async fn fetch_remote_profile(
struct DownloadedSubscription {
url: Url,
suggested_name: Option<std::string::String>,
extra: Option<PrfExtra>,
update_interval_minutes: Option<u64>,
home: Option<String>,
body: String,
}
pub(crate) struct RemoteProfileRefresh {
pub(super) extra: Option<PrfExtra>,
pub(super) home: Option<String>,
pub(super) updated: usize,
pub(super) option: PrfOption,
pub(super) body: String,
}
pub(crate) async fn build_remote_profile(
url: &str,
name: Option<&String>,
desc: Option<&String>,
option: Option<&PrfOption>,
) -> Result<PrfItem> {
let mut downloaded = download_subscription(url, option).await?;
let uid: String = help::get_uid("R").into();
let file = format!("{uid}.yaml").into();
let name = name
.cloned()
.or_else(|| downloaded.suggested_name.take().map(Into::into))
.unwrap_or_else(|| "Remote File".into());
let url = downloaded.url.as_str().into();
let RemoteProfileRefresh {
extra,
home,
updated,
option,
body,
} = prepare_remote_refresh(downloaded, option).await?;
Ok(PrfItem {
uid: Some(uid),
itype: Some("remote".into()),
name: Some(name),
desc: desc.cloned(),
file: Some(file),
url: Some(url),
selected: None,
extra,
option: Some(option),
home,
updated: Some(updated),
file_data: Some(body),
})
}
pub(crate) async fn fetch_remote_refresh(url: &str, option: Option<&PrfOption>) -> Result<RemoteProfileRefresh> {
let downloaded = download_subscription(url, option).await?;
prepare_remote_refresh(downloaded, option).await
}
async fn download_subscription(url: &str, option: Option<&PrfOption>) -> Result<DownloadedSubscription> {
let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false));
let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false));
let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false));
let allow_auto_update = Some(allow_auto_update_enabled(option));
let user_agent = option.and_then(|o| o.user_agent.clone());
let update_interval = option.and_then(|o| o.update_interval);
let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20);
let mut merge = option.and_then(|o| o.merge.clone());
let mut script = option.and_then(|o| o.script.clone());
let mut rules = option.and_then(|o| o.rules.clone());
let mut proxies = option.and_then(|o| o.proxies.clone());
let mut groups = option.and_then(|o| o.groups.clone());
let proxy_type = if self_proxy {
ProxyType::Localhost
@@ -151,7 +199,7 @@ pub(crate) async fn fetch_remote_profile(
url.as_str(),
proxy_type,
Some(timeout),
user_agent.clone(),
user_agent,
accept_invalid_certs,
)
.await
@@ -169,43 +217,52 @@ pub(crate) async fn fetch_remote_profile(
}
let document = decode_subscription(&url, resp.headers(), resp.text())?;
let update_interval = update_interval.or(document.update_interval_minutes);
let extra = document.usage.map(|usage| PrfExtra {
upload: usage.upload,
download: usage.download,
total: usage.total,
expire: usage.expire,
});
let uid = help::get_uid("R").into();
let file = format!("{uid}.yaml").into();
let name = name
.cloned()
.unwrap_or_else(|| document.filename.map_or_else(|| "Remote File".into(), Into::into));
ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?;
Ok(PrfItem {
uid: Some(uid),
itype: Some("remote".into()),
name: Some(name),
desc: desc.cloned(),
file: Some(file),
url: Some(url.as_str().into()),
selected: None,
extra,
option: Some(PrfOption {
update_interval,
merge,
script,
rules,
proxies,
groups,
allow_auto_update,
..PrfOption::default()
}),
Ok(DownloadedSubscription {
suggested_name: document.filename,
update_interval_minutes: document.update_interval_minutes,
home: document.home.map(Into::into),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(document.body.into()),
body: document.body.into(),
url,
extra,
})
}
async fn prepare_remote_refresh(
downloaded: DownloadedSubscription,
option: Option<&PrfOption>,
) -> Result<RemoteProfileRefresh> {
let mut resolved = PrfOption {
update_interval: option
.and_then(|o| o.update_interval)
.or(downloaded.update_interval_minutes),
merge: option.and_then(|o| o.merge.clone()),
script: option.and_then(|o| o.script.clone()),
rules: option.and_then(|o| o.rules.clone()),
proxies: option.and_then(|o| o.proxies.clone()),
groups: option.and_then(|o| o.groups.clone()),
allow_auto_update: Some(allow_auto_update_enabled(option)),
..PrfOption::default()
};
ensure_companion_items(
&mut resolved.merge,
&mut resolved.script,
&mut resolved.rules,
&mut resolved.proxies,
&mut resolved.groups,
)
.await?;
Ok(RemoteProfileRefresh {
extra: downloaded.extra,
home: downloaded.home,
updated: chrono::Local::now().timestamp() as usize,
option: resolved,
body: downloaded.body,
})
}
@@ -321,20 +378,11 @@ mod tests {
};
#[tokio::test]
async fn fetch_remote_profile_maps_response_to_profile_model() -> Result<()> {
async fn import_and_refresh_share_subscription_decoding() -> Result<()> {
const BODY: &str = "# keep this comment\nproxies: []\n";
let listener = TcpListener::bind("127.0.0.1:0").await?;
let url = format!("http://{}/subscription", listener.local_addr()?);
let server = tokio::spawn(async move {
let (socket, _) = listener.accept().await?;
let mut socket = BufReader::new(socket);
let mut line = std::string::String::new();
loop {
line.clear();
if socket.read_line(&mut line).await? == 0 || line == "\r\n" {
break;
}
}
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\
Content-Disposition: attachment; filename=remote.yaml\r\n\
@@ -343,7 +391,19 @@ mod tests {
Subscription-Userinfo: upload=1; download=2; total=3; expire=4\r\n\r\n{BODY}",
BODY.len()
);
socket.get_mut().write_all(response.as_bytes()).await
for _ in 0..2 {
let (socket, _) = listener.accept().await?;
let mut socket = BufReader::new(socket);
let mut line = std::string::String::new();
loop {
line.clear();
if socket.read_line(&mut line).await? == 0 || line == "\r\n" {
break;
}
}
socket.get_mut().write_all(response.as_bytes()).await?;
}
Ok::<_, std::io::Error>(())
});
let option = PrfOption {
update_interval: Some(0),
@@ -356,7 +416,15 @@ mod tests {
groups: Some("test-groups".into()),
..Default::default()
};
let item: clash_verge_profile::PrfItem = fetch_remote_profile(&url, None, None, Some(&option)).await?;
let item: clash_verge_profile::PrfItem = build_remote_profile(&url, None, None, Some(&option)).await?;
let refresh = fetch_remote_refresh(
&url,
Some(&PrfOption {
update_interval: None,
..option
}),
)
.await?;
server.await??;
assert_eq!(item.itype.as_deref(), Some("remote"));
assert_eq!(item.name.as_deref(), Some("remote.yaml"));
@@ -368,6 +436,18 @@ mod tests {
let fetched_option = item.option.context("expected profile options")?;
assert_eq!(fetched_option.update_interval, Some(0));
assert_eq!(fetched_option.allow_auto_update, Some(false));
assert_eq!(refresh.body.as_str(), BODY);
assert_eq!(refresh.home, item.home);
let usage = refresh.extra.context("expected refresh usage")?;
assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4));
assert_eq!(
refresh.option,
PrfOption {
update_interval: Some(120),
..fetched_option
}
);
Ok(())
}
}
+24 -32
View File
@@ -1,4 +1,7 @@
use super::{PrfItem, PrfOption, PrfSelected, patch_opt_field, prfitem::build_profile};
use super::{
PrfItem, PrfOption, PrfSelected, patch_opt_field,
prfitem::{RemoteProfileRefresh, build_profile},
};
use crate::core::notify::{Refresh, announce};
use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state};
use crate::{
@@ -188,37 +191,26 @@ fn validate_profile_file(file: &str) -> Result<()> {
}
/// Updates fields returned by a remote profile refresh.
async fn update_item(profiles: &mut IProfiles, uid: &str, item: &mut PrfItem) -> Result<()> {
if profiles.items.is_none() {
profiles.items = Some(vec![]);
}
async fn apply_remote_refresh(profiles: &mut IProfiles, uid: &str, refresh: RemoteProfileRefresh) -> Result<()> {
let _ = profiles.get_item(uid)?;
if let Some(items) = profiles.items.as_mut() {
for each in items.iter_mut() {
if each.uid.as_deref() == Some(uid) {
each.extra = item.extra;
each.updated = item.updated;
each.home = item.home.to_owned();
each.option = PrfOption::merge(each.option.as_ref(), item.option.as_ref());
if let Some(file_data) = item.file_data.take() {
let file = each.file.take();
let file =
file.unwrap_or_else(|| item.file.take().unwrap_or_else(|| format!("{}.yaml", uid).into()));
each.file = Some(file.clone());
let path = dirs::app_profiles_dir()?.join(file.as_str());
fs::write(&path, file_data.as_bytes())
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
}
break;
}
}
if let Some(each) = 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
.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
@@ -320,9 +312,9 @@ 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 profiles_update_item_safe(index: &str, item: &mut PrfItem) -> Result<()> {
pub(crate) async fn apply_remote_refresh_safe(index: &str, refresh: RemoteProfileRefresh) -> Result<()> {
with_profiles_edit(|mut profiles| async move {
update_item(&mut profiles, index, item).await?;
apply_remote_refresh(&mut profiles, index, refresh).await?;
Ok(profiles)
})
.await
+6 -40
View File
@@ -8,6 +8,7 @@ use crate::{
use anyhow::{Context as _, Result};
use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging, logging_error};
use clash_verge_profile::SubscriptionSchedule as TaskSchedule;
use futures::{FutureExt as _, StreamExt as _};
use std::{collections::HashMap, panic::AssertUnwindSafe, time::Duration};
use tokio::{
@@ -24,28 +25,6 @@ enum TimerCommand {
TaskFinished(String),
}
/// Next update is due at `updated + interval`, but the queue only takes a delay from now.
#[derive(Debug, PartialEq, Eq)]
struct TaskSchedule {
interval_minutes: u64,
first_delay: Duration,
}
impl TaskSchedule {
/// No recorded `updated` -> full interval. Deadline already past -> `ZERO`, fires at once.
fn new(interval_minutes: u64, updated: Option<usize>, now: i64) -> Self {
let full = Timer::interval_duration(interval_minutes);
let elapsed = updated
.filter(|updated| *updated > 0)
.map_or(0, |updated| now.saturating_sub(updated as i64).max(0) as u64);
Self {
interval_minutes,
first_delay: full.saturating_sub(Duration::from_secs(elapsed)),
}
}
}
struct TaskState {
key: Option<Key>,
interval_minutes: u64,
@@ -122,16 +101,9 @@ impl Timer {
let mut new_map = HashMap::new();
for item in items {
if let Some(option) = item.option.as_ref()
&& let (Some(interval), Some(uid)) = (option.update_interval, &item.uid)
&& option.allow_auto_update.unwrap_or(true)
&& interval > 0
if let Some(uid) = &item.uid
&& let Some(schedule) = TaskSchedule::for_profile(item, initializing, now)
{
let mut schedule = TaskSchedule::new(interval, item.updated, now);
// Startup historically treats an explicit zero timestamp as overdue.
if initializing && item.updated == Some(0) {
schedule.first_delay = Duration::ZERO;
}
new_map.insert(uid.clone(), schedule);
}
}
@@ -317,7 +289,7 @@ impl Timer {
// Full interval, not from `updated`: a failed run leaves `updated` in the past, so
// counting from it would retry at zero delay and spin.
let key = Self::schedule_task(queue, &uid, Self::interval_duration(state.interval_minutes));
let key = Self::schedule_task(queue, &uid, TaskSchedule::interval_duration(state.interval_minutes));
state.key = Some(key);
}
@@ -330,10 +302,6 @@ impl Timer {
});
}
const fn interval_duration(interval_minutes: u64) -> Duration {
Duration::from_secs(interval_minutes.saturating_mul(60))
}
fn schedule_task(queue: &mut DelayQueue<String>, uid: &str, delay: Duration) -> Key {
queue.insert(String::from(uid), delay)
}
@@ -348,10 +316,8 @@ impl Timer {
fn next_update_time(tasks: &HashMap<String, TaskState>, profiles: &IProfiles, uid: &str) -> Option<i64> {
let task = tasks.get(uid).filter(|task| !task.retired)?;
let updated = profiles.get_item(uid).ok()?.updated.filter(|updated| *updated > 0)?;
let updated = i64::try_from(updated).ok()?;
let interval = i64::try_from(task.interval_minutes).ok()?.checked_mul(60)?;
updated.checked_add(interval)
let updated = profiles.get_item(uid).ok()?.updated;
TaskSchedule::reported_deadline(task.interval_minutes, updated)
}
fn emit_update_event(uid: &str, is_start: bool) {
+2
View File
@@ -10,6 +10,7 @@ mod listener;
mod profile;
mod proxy;
pub(crate) mod proxy_view;
mod subscription;
mod tun;
mod window;
@@ -23,5 +24,6 @@ pub use icon::*;
pub use listener::*;
pub use profile::*;
pub use proxy::*;
pub use subscription::update_profile;
pub use tun::*;
pub use window::*;
+2 -177
View File
@@ -1,13 +1,11 @@
use crate::core::notify::NoticeStatus;
use crate::core::notify::{Refresh, announce};
use crate::{
cmd,
config::{Config, PrfOption, fetch_remote_profile, profiles::profiles_update_item_safe},
config::Config,
core::{CoreManager, handle, tray, validate::ValidationOutcome},
process::AsyncHandler,
utils::help::{mask_err, mask_url},
};
use anyhow::{Result, bail};
use anyhow::Result;
use clash_verge_logging::{Type, logging};
use std::collections::{HashMap, HashSet};
use tauri_plugin_mihomo::models::{Proxy, ProxyType, Rule};
@@ -201,179 +199,6 @@ async fn finish_proxy_switch(stale_proxies: Vec<std::string::String>) {
}
}
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
let profiles = Config::profiles().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");
if !is_remote {
logging!(info, Type::Config, "[订阅更新] 不是远程订阅,跳过更新");
Ok(None)
} else if item.url.is_none() {
logging!(warn, Type::Config, "[订阅更新] 缺少URL,无法更新");
bail!("failed to get the profile item url");
} else if !ignore_auto_update && !item.option.as_ref().and_then(|o| o.allow_auto_update).unwrap_or(true) {
logging!(info, Type::Config, "[订阅更新] 禁止自动更新,跳过更新");
Ok(None)
} else {
logging!(
info,
Type::Config,
"[订阅更新] 远程订阅,URL: {}",
mask_url(
item.url
.as_ref()
.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(),
)))
}
}
#[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>,
option: Option<&PrfOption>,
is_mannual_trigger: bool,
) -> Result<()> {
let merged_opt = PrfOption::merge(opt, option);
let profiles = Config::profiles().await;
let profiles_arc = profiles.latest_arc();
let profile_name = profiles_arc
.get_item(uid)
.ok()
.and_then(|item| item.name.clone())
.unwrap_or_else(|| String::from("UnKnown Profile"));
#[derive(Clone, Copy)]
enum Strategy {
Configured,
Clash,
System,
}
let result =
crate::utils::retry::try_strategies(Strategy::Configured, [Strategy::Clash, Strategy::System], |strategy| {
let mut options = merged_opt.clone();
async move {
let (name, success, failure) = match strategy {
Strategy::Configured => (
"configured",
"[订阅更新] 更新订阅配置成功",
"[订阅更新] 直接更新失败: {},尝试使用Clash代理更新",
),
Strategy::Clash => (
"clash",
"[订阅更新] 使用 Clash代理 更新订阅配置成功",
"[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新",
),
Strategy::System => (
"system",
"[订阅更新] 使用 系统代理 更新订阅配置成功",
"[订阅更新] 系统代理更新失败: {},所有重试均已失败",
),
};
match strategy {
Strategy::Configured => {}
Strategy::Clash | Strategy::System => {
let option = options.get_or_insert_with(PrfOption::default);
option.self_proxy = Some(matches!(strategy, Strategy::Clash));
option.with_proxy = Some(matches!(strategy, Strategy::System));
}
}
tracing::Span::current().record("strategy", name);
let started = std::time::Instant::now();
let result = fetch_remote_profile(url, None, None, options.as_ref()).await;
let elapsed_field = match strategy {
Strategy::Configured => "configured_elapsed",
Strategy::Clash => "clash_elapsed",
Strategy::System => "system_elapsed",
};
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
match &result {
Ok(_) => logging!(info, Type::Config, "{success}"),
Err(error) => logging!(
warn,
Type::Config,
"{}",
failure.replace("{}", &mask_err(&format!("{error:#}")))
),
}
result
}
})
.await;
let last_err = match result {
Ok((strategy, mut item)) => {
// A persistence error must not replay a successful download with another transport.
profiles_update_item_safe(uid, &mut item).await?;
if !matches!(strategy, Strategy::Configured) {
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
}
return Ok(());
}
Err(error) => error,
};
let last_err = mask_err(&last_err.to_string());
if is_mannual_trigger {
handle::Handle::notice(
NoticeStatus::UpdateFailedEvenWithClash,
format!("{profile_name} - {last_err}"),
);
}
bail!(last_err)
}
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_mannual_trigger))]
pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_mannual_trigger: bool) -> Result<()> {
let url_opt = should_update_profile(uid, is_mannual_trigger).await?;
let profile_persisted = match url_opt {
Some((url, opt)) => {
perform_profile_update(uid, &url, opt.as_ref(), option, is_mannual_trigger).await?;
true
}
None => false,
};
let profiles = Config::profiles().await;
let is_current = profiles.latest_arc().current.as_deref() == Some(uid);
let should_refresh = is_current || (!profile_persisted && is_mannual_trigger);
if should_refresh {
logging!(debug, Type::Config, "[订阅更新] 更新内核配置");
match CoreManager::global().update_config_with_force(is_mannual_trigger).await {
Ok(outcome) if outcome.is_valid() => announce(Refresh::Clash),
Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_mannual_trigger => {
logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome);
}
result => {
let message = match result {
Ok(outcome) => outcome.to_string(),
Err(err) => err.to_string(),
};
let message = mask_err(&message);
let message = if profile_persisted {
format!("订阅已保存,但未能确认已应用到内核: {message}")
} else {
message
};
logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message);
handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
bail!(message);
}
}
}
Ok(())
}
/// 增强配置
pub async fn enhance_profiles() -> Result<ValidationOutcome> {
CoreManager::global().update_config_forced().await
+185
View File
@@ -0,0 +1,185 @@
use crate::{
config::{Config, PrfOption, fetch_remote_refresh, profiles::apply_remote_refresh_safe},
core::{
CoreManager, handle,
notify::{NoticeStatus, Refresh, announce},
validate::ValidationOutcome,
},
utils::help::{mask_err, mask_url},
};
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>)>> {
let profiles = Config::profiles().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");
if !is_remote {
logging!(info, Type::Config, "[订阅更新] 不是远程订阅,跳过更新");
Ok(None)
} else if item.url.is_none() {
logging!(warn, Type::Config, "[订阅更新] 缺少URL,无法更新");
bail!("failed to get the profile item url");
} else if !ignore_auto_update && !item.option.as_ref().and_then(|o| o.allow_auto_update).unwrap_or(true) {
logging!(info, Type::Config, "[订阅更新] 禁止自动更新,跳过更新");
Ok(None)
} else {
logging!(
info,
Type::Config,
"[订阅更新] 远程订阅,URL: {}",
mask_url(
item.url
.as_ref()
.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(),
)))
}
}
#[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>,
option: Option<&PrfOption>,
is_manual_trigger: bool,
) -> Result<()> {
let merged_opt = PrfOption::merge(opt, option);
let profiles = Config::profiles().await;
let profiles_arc = profiles.latest_arc();
let profile_name = profiles_arc
.get_item(uid)
.ok()
.and_then(|item| item.name.clone())
.unwrap_or_else(|| String::from("UnKnown Profile"));
#[derive(Clone, Copy)]
enum Strategy {
Configured,
Clash,
System,
}
let result =
crate::utils::retry::try_strategies(Strategy::Configured, [Strategy::Clash, Strategy::System], |strategy| {
let mut options = merged_opt.clone();
async move {
let (name, success, failure) = match strategy {
Strategy::Configured => (
"configured",
"[订阅更新] 更新订阅配置成功",
"[订阅更新] 直接更新失败: {},尝试使用Clash代理更新",
),
Strategy::Clash => (
"clash",
"[订阅更新] 使用 Clash代理 更新订阅配置成功",
"[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新",
),
Strategy::System => (
"system",
"[订阅更新] 使用 系统代理 更新订阅配置成功",
"[订阅更新] 系统代理更新失败: {},所有重试均已失败",
),
};
match strategy {
Strategy::Configured => {}
Strategy::Clash | Strategy::System => {
let option = options.get_or_insert_with(PrfOption::default);
option.self_proxy = Some(matches!(strategy, Strategy::Clash));
option.with_proxy = Some(matches!(strategy, Strategy::System));
}
}
tracing::Span::current().record("strategy", name);
let started = std::time::Instant::now();
let result = fetch_remote_refresh(url, options.as_ref()).await;
let elapsed_field = match strategy {
Strategy::Configured => "configured_elapsed",
Strategy::Clash => "clash_elapsed",
Strategy::System => "system_elapsed",
};
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
match &result {
Ok(_) => logging!(info, Type::Config, "{success}"),
Err(error) => logging!(
warn,
Type::Config,
"{}",
failure.replace("{}", &mask_err(&format!("{error:#}")))
),
}
result
}
})
.await;
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?;
if !matches!(strategy, Strategy::Configured) {
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
}
return Ok(());
}
Err(error) => error,
};
let last_err = mask_err(&last_err.to_string());
if is_manual_trigger {
handle::Handle::notice(
NoticeStatus::UpdateFailedEvenWithClash,
format!("{profile_name} - {last_err}"),
);
}
bail!(last_err)
}
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_manual_trigger))]
pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_trigger: bool) -> Result<()> {
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?;
true
}
None => false,
};
let profiles = Config::profiles().await;
let is_current = profiles.latest_arc().current.as_deref() == Some(uid);
let should_refresh = is_current || (!profile_persisted && is_manual_trigger);
if should_refresh {
logging!(debug, Type::Config, "[订阅更新] 更新内核配置");
match CoreManager::global().update_config_with_force(is_manual_trigger).await {
Ok(outcome) if outcome.is_valid() => announce(Refresh::Clash),
Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_manual_trigger => {
logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome);
}
result => {
let message = match result {
Ok(outcome) => outcome.to_string(),
Err(err) => err.to_string(),
};
let message = mask_err(&message);
let message = if profile_persisted {
format!("订阅已保存,但未能确认已应用到内核: {message}")
} else {
message
};
logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message);
handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
bail!(message);
}
}
}
Ok(())
}
+2 -2
View File
@@ -5,7 +5,7 @@ use tauri::Url;
use tristr::alias::String;
use crate::{
config::{Config, PrfItem, fetch_remote_profile, profiles},
config::{Config, PrfItem, build_remote_profile, profiles},
core::{CoreManager, handle, timer::Timer},
utils::help,
};
@@ -113,7 +113,7 @@ async fn import_subscription(url: &str, name: Option<&String>) {
}
async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option<PrfItem> {
match fetch_remote_profile(url, name, None, None).await {
match build_remote_profile(url, name, None, None).await {
Ok(item) => Some(item),
Err(e) => {
logging!(error, Type::Config, "failed to parse profile from url: {:?}", e);