Repository navigation
Expand file tree
/
Copy pathExecUtils.cs
More file actions
336 lines (297 loc) · 11.2 KB
/
Copy pathExecUtils.cs
File metadata and controls
336 lines (297 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ServiceStack.Logging;
using ServiceStack.Script;
using ServiceStack.Text;
namespace ServiceStack
{
public static class ExecUtils
{
public static void LogError(Type declaringType, string clientMethodName, Exception ex)
{
var log = LogManager.GetLogger(declaringType);
log.Error($"'{declaringType.FullName}' threw an error on {clientMethodName}: {ex.Message}", ex);
}
public static void ExecAll<T>(this IEnumerable<T> instances, Action<T> action)
{
foreach (var instance in instances)
{
try
{
action(instance);
}
catch (Exception ex)
{
LogError(instance.GetType(), action.GetType().Name, ex);
}
}
}
public static async Task ExecAllAsync<T>(this IEnumerable<T> instances, Func<T,Task> action)
{
foreach (var instance in instances)
{
try
{
await action(instance).ConfigAwait();
}
catch (Exception ex)
{
LogError(instance.GetType(), action.GetType().Name, ex);
}
}
}
public static async Task<TReturn> ExecAllReturnFirstAsync<T,TReturn>(this IEnumerable<T> instances, Func<T,Task<TReturn>> action)
{
TReturn firstResult = default;
var i = 0;
foreach (var instance in instances)
{
try
{
var ret = await action(instance).ConfigAwait();
if (i++ == 0)
firstResult = ret;
}
catch (Exception ex)
{
LogError(instance.GetType(), action.GetType().Name, ex);
}
}
return firstResult;
}
public static void ExecAllWithFirstOut<T, TReturn>(this IEnumerable<T> instances, Func<T, TReturn> action, ref TReturn firstResult)
{
foreach (var instance in instances)
{
try
{
var result = action(instance);
if (!Equals(firstResult, default(TReturn)))
{
firstResult = result;
}
}
catch (Exception ex)
{
LogError(instance.GetType(), action.GetType().Name, ex);
}
}
}
public static TReturn ExecReturnFirstWithResult<T, TReturn>(this IEnumerable<T> instances, Func<T, TReturn> action)
{
foreach (var instance in instances)
{
try
{
var result = action(instance);
if (!Equals(result, default(TReturn)))
{
return result;
}
}
catch (Exception ex)
{
LogError(instance.GetType(), action.GetType().Name, ex);
}
}
return default;
}
public static async Task<TReturn> ExecReturnFirstWithResultAsync<T, TReturn>(this IEnumerable<T> instances, Func<T, Task<TReturn>> action)
{
foreach (var instance in instances)
{
try
{
var result = await action(instance).ConfigAwait();
if (!Equals(result, default(TReturn)))
{
return result;
}
}
catch (Exception ex)
{
LogError(instance.GetType(), action.GetType().Name, ex);
}
}
return default;
}
public static void RetryUntilTrue(Func<bool> action, TimeSpan? timeOut=null)
{
var i = 0;
var firstAttempt = DateTime.UtcNow;
while (timeOut == null || DateTime.UtcNow - firstAttempt < timeOut.Value)
{
i++;
if (action())
{
return;
}
SleepBackOffMultiplier(i);
}
throw new TimeoutException($"Exceeded timeout of {timeOut.Value}");
}
public static async Task RetryUntilTrueAsync(Func<Task<bool>> action, TimeSpan? timeOut=null)
{
var i = 0;
var firstAttempt = DateTime.UtcNow;
while (timeOut == null || DateTime.UtcNow - firstAttempt < timeOut.Value)
{
i++;
if (await action().ConfigAwait())
{
return;
}
await DelayBackOffMultiplierAsync(i).ConfigAwait();
}
throw new TimeoutException($"Exceeded timeout of {timeOut.Value}");
}
public static void RetryOnException(Action action, TimeSpan? timeOut)
{
var i = 0;
Exception lastEx = null;
var firstAttempt = DateTime.UtcNow;
while (timeOut == null || DateTime.UtcNow - firstAttempt < timeOut.Value)
{
i++;
try
{
action();
return;
}
catch (Exception ex)
{
lastEx = ex;
SleepBackOffMultiplier(i);
}
}
throw new TimeoutException($"Exceeded timeout of {timeOut.Value}", lastEx);
}
public static async Task RetryOnExceptionAsync(Func<Task> action, TimeSpan? timeOut)
{
var i = 0;
Exception lastEx = null;
var firstAttempt = DateTime.UtcNow;
while (timeOut == null || DateTime.UtcNow - firstAttempt < timeOut.Value)
{
i++;
try
{
await action().ConfigAwait();
return;
}
catch (Exception ex)
{
lastEx = ex;
await DelayBackOffMultiplierAsync(i).ConfigAwait();
}
}
throw new TimeoutException($"Exceeded timeout of {timeOut.Value}", lastEx);
}
public static void RetryOnException(Action action, int maxRetries)
{
for (var i = 0; i < maxRetries; i++)
{
try
{
action();
break;
}
catch
{
if (i == maxRetries - 1) throw;
SleepBackOffMultiplier(i);
}
}
}
public static async Task RetryOnExceptionAsync(Func<Task> action, int maxRetries)
{
for (var i = 0; i < maxRetries; i++)
{
try
{
await action().ConfigAwait();
break;
}
catch
{
if (i == maxRetries - 1) throw;
await DelayBackOffMultiplierAsync(i).ConfigAwait();
}
}
}
/// <summary>
/// Default base sleep time (milliseconds).
/// </summary>
public static int BaseDelayMs { get; set; } = 100;
/// <summary>
/// Default maximum back-off time before retrying a request
/// </summary>
public static int MaxBackOffMs { get; set; } = 1000 * 20;
/// <summary>
/// Maximum retry limit. Avoids integer overflow issues.
/// </summary>
public static int MaxRetries { get; set; } = 30;
/// <summary>
/// How long to sleep before next retry using Exponential BackOff delay with Full Jitter.
/// </summary>
/// <param name="retriesAttempted"></param>
public static void SleepBackOffMultiplier(int retriesAttempted) => TaskUtils.Sleep(CalculateFullJitterBackOffDelay(retriesAttempted));
/// <summary>
/// How long to wait before next retry using Exponential BackOff delay with Full Jitter.
/// </summary>
/// <param name="retriesAttempted"></param>
public static Task DelayBackOffMultiplierAsync(int retriesAttempted) => Task.Delay(CalculateFullJitterBackOffDelay(retriesAttempted));
/// <summary>
/// Exponential BackOff Delay with Full Jitter
/// </summary>
/// <param name="retriesAttempted"></param>
/// <returns></returns>
public static int CalculateFullJitterBackOffDelay(int retriesAttempted) => CalculateFullJitterBackOffDelay(retriesAttempted, BaseDelayMs, MaxBackOffMs);
/// <summary>
/// Exponential BackOff Delay with Full Jitter from:
/// https://github.com/aws/aws-sdk-java/blob/master/aws-java-sdk-core/src/main/java/com/amazonaws/retry/PredefinedBackoffStrategies.java
/// </summary>
/// <param name="retriesAttempted"></param>
/// <param name="baseDelay"></param>
/// <param name="maxBackOffMs"></param>
/// <returns></returns>
public static int CalculateFullJitterBackOffDelay(int retriesAttempted, int baseDelay, int maxBackOffMs)
{
var random = new Random(Guid.NewGuid().GetHashCode());
var ceil = CalculateExponentialDelay(retriesAttempted, baseDelay, maxBackOffMs);
return random.Next(ceil);
}
/// <summary>
/// Calculate exponential retry back-off.
/// </summary>
/// <param name="retriesAttempted"></param>
/// <returns></returns>
public static int CalculateExponentialDelay(int retriesAttempted) => CalculateExponentialDelay(retriesAttempted, BaseDelayMs, MaxBackOffMs);
/// <summary>
/// Calculate exponential retry back-off.
/// </summary>
/// <param name="retriesAttempted"></param>
/// <param name="baseDelay"></param>
/// <param name="maxBackOffMs"></param>
/// <returns></returns>
public static int CalculateExponentialDelay(int retriesAttempted, int baseDelay, int maxBackOffMs)
{
if (retriesAttempted <= 0)
return baseDelay;
var retries = Math.Min(retriesAttempted, MaxRetries);
return (int)Math.Min((1L << retries) * baseDelay, maxBackOffMs);
}
/// <summary>
/// Calculate back-off logic for obtaining an in memory lock
/// </summary>
/// <param name="retries"></param>
/// <returns></returns>
public static int CalculateMemoryLockDelay(int retries) => retries < 10
? CalculateExponentialDelay(retries, baseDelay:5, maxBackOffMs:1000)
: CalculateFullJitterBackOffDelay(retries, baseDelay:10, maxBackOffMs:10000);
public static string ShellExec(string command, Dictionary<string, object> args=null) =>
new ProtectedScripts().sh(default, command, args);
}
}