From b92588f1f9f5678970fdc05460b70e31ad47cdb5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 28 Jun 2021 21:45:17 -0500 Subject: improve Retry --- src/slskd/Common/Retry.cs | 64 +++++++++++++++++++++++++++++------------------ 1 file changed, 39 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Retry.cs b/src/slskd/Common/Retry.cs index c0e1bd83..f18b7459 100644 --- a/src/slskd/Common/Retry.cs +++ b/src/slskd/Common/Retry.cs @@ -21,42 +21,51 @@ namespace slskd using System.Collections.Generic; using System.Threading.Tasks; - public class Retry + /// + /// Retry logic. + /// + public static class Retry { - public static async Task Do(Func task, TimeSpan retryInterval, int maxAttemptCount = 3) + /// + /// Executes logic with the specified retry parameters. + /// + /// The logic to execute. + /// A function returning a value indicating whether the last Exception is retryable. + /// The maximum number of retry attempts. + /// The maximum delay in milliseconds. + /// The execution context. + public static async Task Do(Func task, Func isRetryable = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) { - var exceptions = new List(); - for (int attempted = 0; attempted < maxAttemptCount; attempted++) + await Do(async () => { - try - { - if (attempted > 0) - { - await Task.Delay(retryInterval); - } - - await task(); - return; - } - catch (Exception ex) - { - exceptions.Add(ex); - } - } - - throw new AggregateException(exceptions); + await task(); + return Task.FromResult(null); + }, isRetryable, maxAttempts, maxDelayInMilliseconds); } - public static async Task Do(Func> task, TimeSpan retryInterval, int maxAttemptCount = 3) + /// + /// Executes logic with the specified retry parameters. + /// + /// The logic to execute. + /// A function returning a value indicating whether the last Exception is retryable. + /// The maximum number of retry attempts. + /// The maximum delay in miliseconds. + /// The Type of the logic return value. + /// The execution context. + public static async Task Do(Func> task, Func isRetryable = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) { + isRetryable ??= (_, _) => true; + var exceptions = new List(); - for (int attempted = 0; attempted < maxAttemptCount; attempted++) + + for (int attempts = 0; attempts < maxAttempts; attempts++) { try { - if (attempted > 0) + if (attempts > 0) { - await Task.Delay(retryInterval); + var (delay, jitter) = Compute.ExponentialBackoffDelay(attempts, maxDelayInMilliseconds); + await Task.Delay(delay + jitter); } return await task(); @@ -64,6 +73,11 @@ namespace slskd catch (Exception ex) { exceptions.Add(ex); + + if (!isRetryable(attempts + 1, ex)) + { + throw new AggregateException(exceptions); + } } } -- cgit v1.2.3