-
Notifications
You must be signed in to change notification settings - Fork 358
/
FunctionExecutorExtensions.cs
78 lines (67 loc) · 2.99 KB
/
FunctionExecutorExtensions.cs
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host.Triggers;
using Microsoft.Azure.WebJobs.Logging;
namespace Microsoft.Azure.WebJobs.Host.Executors
{
/// <summary>
/// Provides extension methods for the <see cref="IFunctionExecutor"/> interface.
/// </summary>
internal static class FunctionExecutorExtensions
{
public static async Task<IDelayedException> TryExecuteAsync(this IFunctionExecutor executor, Func<IFunctionInstance> instanceFactory, ILoggerFactory loggerFactory, CancellationToken cancellationToken)
{
var attempt = 0;
IDelayedException functionResult = null;
ILogger logger = null;
RetryContext retryContext = null;
while (true)
{
IFunctionInstance functionInstance = instanceFactory.Invoke();
if (logger == null)
{
logger = loggerFactory.CreateLogger(LogCategories.CreateFunctionCategory(functionInstance.FunctionDescriptor.LogName));
}
if (retryContext == null && functionInstance.FunctionDescriptor.RetryStrategy != null)
{
retryContext = new RetryContext();
retryContext.MaxRetryCount = functionInstance.FunctionDescriptor.RetryStrategy.MaxRetryCount;
}
if (retryContext != null && functionInstance is FunctionInstance instance)
{
retryContext.Instance = instance;
instance.RetryContext = retryContext;
}
functionResult = await executor.TryExecuteAsync(functionInstance, cancellationToken);
if (functionResult == null)
{
// function invocation succeeded
break;
}
if (functionInstance.FunctionDescriptor.RetryStrategy == null)
{
// retry is not configured
break;
}
IRetryStrategy retryStrategy = functionInstance.FunctionDescriptor.RetryStrategy;
if (retryStrategy.MaxRetryCount != -1 && ++attempt > retryStrategy.MaxRetryCount)
{
// retry count exceeded
break;
}
retryContext.RetryCount = attempt;
retryContext.Exception = functionResult?.Exception;
TimeSpan nextDelay = retryStrategy.GetNextDelay(retryContext);
logger.LogFunctionRetryAttempt(nextDelay, attempt, retryStrategy.MaxRetryCount);
await Task.Delay(nextDelay);
}
return functionResult;
}
}
}