mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-01 02:20:07 +08:00
refactor(task): move retry primitives into the task crate
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
//! Single-owner task drivers with caller-managed runtime and cancellation.
|
||||
//! Task drivers and retry primitives with caller-managed runtime and cancellation.
|
||||
|
||||
pub mod countdown;
|
||||
pub mod retry;
|
||||
pub mod scheduled_task;
|
||||
pub mod watch_task;
|
||||
|
||||
@@ -21,25 +21,29 @@ pub enum RetryError<E> {
|
||||
Stop(E),
|
||||
}
|
||||
|
||||
impl<E> RetryError<E> {
|
||||
fn into_inner(self) -> E {
|
||||
match self {
|
||||
Self::Retry(error) | Self::Stop(error) => error,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn retry<T: Send, E: Send, Fut: Future<Output = Result<T, RetryError<E>>> + Send>(
|
||||
policy: RetryPolicy,
|
||||
mut operation: impl FnMut(usize) -> Fut + Send,
|
||||
) -> Result<T, E> {
|
||||
let mut result = operation(0).await;
|
||||
for (index, delay) in policy.delays().enumerate() {
|
||||
match result {
|
||||
Ok(_) | Err(RetryError::Stop(_)) => break,
|
||||
Err(RetryError::Retry(_)) => {
|
||||
if !delay.is_zero() {
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
}
|
||||
if !matches!(result, Err(RetryError::Retry(_))) {
|
||||
break;
|
||||
}
|
||||
if !delay.is_zero() {
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
result = operation(index + 1).await;
|
||||
}
|
||||
result.map_err(|error| match error {
|
||||
RetryError::Retry(error) | RetryError::Stop(error) => error,
|
||||
})
|
||||
result.map_err(RetryError::into_inner)
|
||||
}
|
||||
|
||||
pub async fn try_strategies<
|
||||
@@ -53,15 +57,14 @@ pub async fn try_strategies<
|
||||
rest: [S; N],
|
||||
mut operation: impl FnMut(S) -> Fut + Send,
|
||||
) -> Result<(S, T), E> {
|
||||
retry(
|
||||
RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(N), Duration::ZERO),
|
||||
move |attempt| {
|
||||
let strategy = if attempt == 0 { first } else { rest[attempt - 1] };
|
||||
let future = operation(strategy);
|
||||
async move { future.await.map(|value| (strategy, value)).map_err(RetryError::Retry) }
|
||||
},
|
||||
)
|
||||
.await
|
||||
let mut result = operation(first).await.map(|value| (first, value));
|
||||
for strategy in rest {
|
||||
if result.is_ok() {
|
||||
break;
|
||||
}
|
||||
result = operation(strategy).await.map(|value| (strategy, value));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn retry_with_state<S: Send, T: Send, E: Send>(
|
||||
@@ -71,19 +74,15 @@ pub async fn retry_with_state<S: Send, T: Send, E: Send>(
|
||||
) -> Result<T, E> {
|
||||
let mut result = operation(&mut state, 0).await;
|
||||
for (index, delay) in policy.delays().enumerate() {
|
||||
match result {
|
||||
Ok(_) | Err(RetryError::Stop(_)) => break,
|
||||
Err(RetryError::Retry(_)) => {
|
||||
if !delay.is_zero() {
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
}
|
||||
if !matches!(result, Err(RetryError::Retry(_))) {
|
||||
break;
|
||||
}
|
||||
if !delay.is_zero() {
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
result = operation(&mut state, index + 1).await;
|
||||
}
|
||||
result.map_err(|error| match error {
|
||||
RetryError::Retry(error) | RetryError::Stop(error) => error,
|
||||
})
|
||||
result.map_err(RetryError::into_inner)
|
||||
}
|
||||
|
||||
pub fn retry_sync<T, E>(
|
||||
@@ -92,41 +91,39 @@ pub fn retry_sync<T, E>(
|
||||
) -> Result<T, E> {
|
||||
let mut result = operation(0);
|
||||
for (index, delay) in policy.delays().enumerate() {
|
||||
match result {
|
||||
Ok(_) | Err(RetryError::Stop(_)) => break,
|
||||
Err(RetryError::Retry(_)) => {
|
||||
if !delay.is_zero() {
|
||||
std::thread::sleep(delay);
|
||||
}
|
||||
}
|
||||
if !matches!(result, Err(RetryError::Retry(_))) {
|
||||
break;
|
||||
}
|
||||
if !delay.is_zero() {
|
||||
std::thread::sleep(delay);
|
||||
}
|
||||
result = operation(index + 1);
|
||||
}
|
||||
result.map_err(|error| match error {
|
||||
RetryError::Retry(error) | RetryError::Stop(error) => error,
|
||||
})
|
||||
result.map_err(RetryError::into_inner)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::future::ready;
|
||||
|
||||
#[tokio::test]
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn retries_stop_at_success_terminal_error_or_attempt_limit() {
|
||||
let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), Duration::ZERO);
|
||||
let delay = Duration::from_millis(50);
|
||||
let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), delay);
|
||||
let started = tokio::time::Instant::now();
|
||||
let mut calls = 0;
|
||||
let success = retry(policy, |attempt| {
|
||||
calls += 1;
|
||||
async move {
|
||||
if attempt == 1 {
|
||||
Ok(7)
|
||||
} else {
|
||||
Err(RetryError::Retry(attempt))
|
||||
}
|
||||
}
|
||||
ready(if attempt == 1 {
|
||||
Ok(7)
|
||||
} else {
|
||||
Err(RetryError::Retry(attempt))
|
||||
})
|
||||
})
|
||||
.await;
|
||||
assert_eq!((success, calls), (Ok(7), 2));
|
||||
assert_eq!(started.elapsed(), delay);
|
||||
calls = 0;
|
||||
let stopped = retry(policy, |_| {
|
||||
calls += 1;
|
||||
@@ -134,6 +131,7 @@ mod tests {
|
||||
})
|
||||
.await;
|
||||
assert_eq!((stopped, calls), (Err("terminal"), 1));
|
||||
assert_eq!(started.elapsed(), delay);
|
||||
calls = 0;
|
||||
let exhausted = retry(policy, |attempt| {
|
||||
calls += 1;
|
||||
@@ -141,6 +139,7 @@ mod tests {
|
||||
})
|
||||
.await;
|
||||
assert_eq!((exhausted, calls), (Err(2), 3));
|
||||
assert_eq!(started.elapsed(), delay * 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -161,11 +160,9 @@ mod tests {
|
||||
let result = retry_with_state(policy, Vec::new(), |visited, attempt| {
|
||||
Box::pin(async move {
|
||||
visited.push(attempt);
|
||||
if visited.len() == 3 {
|
||||
Ok(visited.clone())
|
||||
} else {
|
||||
Err(RetryError::Retry(()))
|
||||
}
|
||||
(visited.len() == 3)
|
||||
.then(|| visited.clone())
|
||||
.ok_or(RetryError::Retry(()))
|
||||
})
|
||||
})
|
||||
.await;
|
||||
@@ -4,7 +4,6 @@ use super::{
|
||||
profile_storage,
|
||||
};
|
||||
use crate::core::notify::{Refresh, announce};
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state};
|
||||
use crate::{
|
||||
core::{handle, tray::Tray},
|
||||
process::AsyncHandler,
|
||||
@@ -18,6 +17,7 @@ use clash_verge_draft::Draft;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
pub use clash_verge_profile::{IProfilePreview, IProfiles};
|
||||
use clash_verge_subscription::normalize_profile_home_url;
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry, retry_with_state};
|
||||
use futures::FutureExt as _;
|
||||
use serde_yaml_ng::Mapping;
|
||||
use std::num::NonZeroUsize;
|
||||
|
||||
@@ -237,7 +237,7 @@ impl CoreManager {
|
||||
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
|
||||
}
|
||||
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||
retry(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add(MAX_PORT_FALLBACK_RETRIES),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
#[cfg(test)]
|
||||
use super::claim_core_readiness_generation;
|
||||
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
use crate::{
|
||||
AsyncHandler,
|
||||
config::Config,
|
||||
@@ -11,6 +10,7 @@ use crate::{
|
||||
};
|
||||
use anyhow::{Context as _, Result};
|
||||
use clash_verge_logging::Type;
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||
use futures::{
|
||||
FutureExt as _,
|
||||
future::{Map, Shared},
|
||||
|
||||
@@ -555,7 +555,7 @@ pub async fn clear() -> Result<()> {
|
||||
|
||||
/// A failed system call is usually a transient RPC hiccup, so give it a few tries.
|
||||
async fn clear_with_retry() -> Result<()> {
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||
retry(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add((CLEAR_ATTEMPTS - 1) as usize),
|
||||
|
||||
@@ -135,7 +135,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
|
||||
/// Retries transport failures but stops at the first readable reply, including a rejection.
|
||||
pub async fn await_ready(&self, attempts: usize, interval: Duration) -> Result<RunState, ReadyWaitError> {
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||
let attempts = std::num::NonZeroUsize::new(attempts).ok_or_else(|| {
|
||||
ReadyWaitError::Unreachable(anyhow::anyhow!(
|
||||
"service readiness wait was configured with no attempts"
|
||||
|
||||
@@ -1302,7 +1302,7 @@ async fn create_sync_temp(target: &Path) -> Result<(PathBuf, tokio::fs::File)> {
|
||||
.with_context(|| format!("failed to create provider cache directory {}", parent.display()))?;
|
||||
}
|
||||
let name = target.file_name().map_or_default(|name| name.to_string_lossy());
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||
retry(
|
||||
RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(7), std::time::Duration::ZERO),
|
||||
|_| async {
|
||||
@@ -1719,7 +1719,7 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
|
||||
}
|
||||
|
||||
async fn clear_proxy_after_owner_loss() {
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||
let result = retry(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add(2),
|
||||
|
||||
@@ -349,7 +349,7 @@ fn stage_core(target: &Path, package: &[u8], version: &str) -> Result<StagedCore
|
||||
}
|
||||
|
||||
fn create_staging_file(directory: &Path, core_name: &OsStr) -> Result<(PathBuf, File)> {
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry_sync};
|
||||
retry_sync(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add(31),
|
||||
|
||||
@@ -76,8 +76,10 @@ async fn perform_profile_update(
|
||||
System,
|
||||
}
|
||||
|
||||
let result =
|
||||
crate::utils::retry::try_strategies(Strategy::Configured, [Strategy::Clash, Strategy::System], |strategy| {
|
||||
let result = clash_verge_task::retry::try_strategies(
|
||||
Strategy::Configured,
|
||||
[Strategy::Clash, Strategy::System],
|
||||
|strategy| {
|
||||
let mut options = merged_opt.clone();
|
||||
async move {
|
||||
let (name, success, failure) = match strategy {
|
||||
@@ -125,8 +127,9 @@ async fn perform_profile_update(
|
||||
}
|
||||
result
|
||||
}
|
||||
})
|
||||
.await;
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let last_err = match result {
|
||||
Ok((strategy, refresh)) => {
|
||||
// A persistence error must not replay a successful download with another transport.
|
||||
|
||||
@@ -109,7 +109,7 @@ fn current_user_home() -> anyhow::Result<PathBuf> {
|
||||
}
|
||||
.max(1024);
|
||||
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry_sync};
|
||||
retry_sync(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add(11),
|
||||
|
||||
@@ -11,7 +11,6 @@ pub(crate) mod network;
|
||||
pub use crate::core::notify::desktop as notification;
|
||||
pub mod port;
|
||||
pub mod resolve;
|
||||
pub mod retry;
|
||||
#[cfg(target_os = "windows")]
|
||||
pub mod schtasks;
|
||||
pub mod server;
|
||||
|
||||
@@ -52,7 +52,7 @@ pub async fn check_singleton() -> Result<SingletonDisposition> {
|
||||
.context("failed to initialize singleton lock")?;
|
||||
if !try_lock_instance(&lock).context("failed to acquire singleton lock")? {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(20);
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||
let secondary = retry(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add(400),
|
||||
|
||||
Reference in New Issue
Block a user