forked from Azure/durabletask
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDispatcherBase.cs
290 lines (250 loc) · 10.3 KB
/
DispatcherBase.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
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
// ----------------------------------------------------------------------------------
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace DurableTask
{
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Tracing;
public abstract class DispatcherBase<T>
{
const int DefaultMaxConcurrentWorkItems = 20;
const int BackoffIntervalOnInvalidOperationSecs = 10;
const int CountDownToZeroDelay = 5;
static TimeSpan DefaultReceiveTimeout = TimeSpan.FromSeconds(30);
static TimeSpan WaitIntervalOnMaxSessions = TimeSpan.FromSeconds(5);
readonly string id;
readonly string name;
readonly object thisLock = new object();
readonly WorkItemIdentifier workItemIdentifier;
volatile int concurrentWorkItemCount;
volatile int countDownToZeroDelay;
volatile int delayOverrideSecs;
volatile bool isFetching;
volatile int isStarted;
protected int maxConcurrentWorkItems;
protected DispatcherBase(string name, WorkItemIdentifier workItemIdentifier)
{
isStarted = 0;
isFetching = false;
this.name = name;
id = Guid.NewGuid().ToString("N");
maxConcurrentWorkItems = DefaultMaxConcurrentWorkItems;
this.workItemIdentifier = workItemIdentifier;
}
public void Start()
{
if (Interlocked.CompareExchange(ref isStarted, 1, 0) != 0)
{
throw TraceHelper.TraceException(TraceEventType.Error,
new InvalidOperationException("TaskOrchestrationDispatcher has already started"));
}
TraceHelper.Trace(TraceEventType.Information, "{0} starting. Id {1}.", name, id);
OnStart();
Task.Factory.StartNew(() => Dispatch());
}
public void Stop()
{
Stop(false);
}
public void Stop(bool forced)
{
if (Interlocked.CompareExchange(ref isStarted, 0, 1) != 1)
{
//idempotent
return;
}
TraceHelper.Trace(TraceEventType.Information, "{0} stopping. Id {1}.", name, id);
OnStopping(forced);
if (!forced)
{
int retryCount = 7;
while ((concurrentWorkItemCount > 0 || isFetching) && retryCount-- >= 0)
{
Thread.Sleep(4000);
}
}
OnStopped(forced);
TraceHelper.Trace(TraceEventType.Information, "{0} stopped. Id {1}.", name, id);
}
protected abstract void OnStart();
protected abstract void OnStopping(bool isForced);
protected abstract void OnStopped(bool isForced);
protected abstract Task<T> OnFetchWorkItem(TimeSpan receiveTimeout);
protected abstract Task OnProcessWorkItem(T workItem);
protected abstract Task SafeReleaseWorkItem(T workItem);
protected abstract Task AbortWorkItem(T workItem);
protected abstract int GetDelayInSecondsAfterOnFetchException(Exception exception);
protected abstract int GetDelayInSecondsAfterOnProcessException(Exception exception);
// TODO : dispatcher refactoring between worker, orchestrator, tacker & DLQ
public async Task Dispatch()
{
while (isStarted == 1)
{
if (concurrentWorkItemCount >= maxConcurrentWorkItems)
{
TraceHelper.Trace(TraceEventType.Information,
GetFormattedLog(
string.Format(
"Max concurrent operations are already in progress. Waiting for {0}s for next accept.",
WaitIntervalOnMaxSessions)));
await Task.Delay(WaitIntervalOnMaxSessions);
continue;
}
int delaySecs = 0;
T workItem = default(T);
try
{
isFetching = true;
TraceHelper.Trace(TraceEventType.Information,
GetFormattedLog(string.Format("Starting fetch with timeout of {0}", DefaultReceiveTimeout)));
workItem = await OnFetchWorkItem(DefaultReceiveTimeout);
}
catch (TimeoutException)
{
delaySecs = 0;
}
catch (Exception exception)
{
// TODO : dump full node context here
TraceHelper.TraceException(TraceEventType.Warning, exception,
GetFormattedLog("Exception while fetching workItem"));
delaySecs = GetDelayInSecondsAfterOnFetchException(exception);
}
finally
{
isFetching = false;
}
if (!(Equals(workItem, default(T))))
{
if (isStarted == 0)
{
await SafeReleaseWorkItem(workItem);
}
else
{
Interlocked.Increment(ref concurrentWorkItemCount);
Task.Factory.StartNew<Task>(ProcessWorkItem, workItem);
}
}
delaySecs = Math.Max(delayOverrideSecs, delaySecs);
if (delaySecs > 0)
{
await Task.Delay(TimeSpan.FromSeconds(delaySecs));
}
}
}
protected virtual async Task ProcessWorkItem(object workItemObj)
{
var workItem = (T) workItemObj;
bool abortWorkItem = true;
string workItemId = string.Empty;
try
{
workItemId = workItemIdentifier(workItem);
TraceHelper.Trace(TraceEventType.Information,
GetFormattedLog(string.Format("Starting to process workItem {0}", workItemId)));
await OnProcessWorkItem(workItem);
AdjustDelayModifierOnSuccess();
TraceHelper.Trace(TraceEventType.Information,
GetFormattedLog(string.Format("Finished processing workItem {0}", workItemId)));
abortWorkItem = false;
}
catch (TypeMissingException exception)
{
TraceHelper.TraceException(TraceEventType.Error, exception,
GetFormattedLog(string.Format("Exception while processing workItem {0}", workItemId)));
TraceHelper.Trace(TraceEventType.Error,
"Backing off after invalid operation by " + BackoffIntervalOnInvalidOperationSecs);
// every time we hit invalid operation exception we back off the dispatcher
AdjustDelayModifierOnFailure(BackoffIntervalOnInvalidOperationSecs);
}
catch (Exception exception)
{
if (Utils.IsFatal(exception))
{
throw;
}
TraceHelper.TraceException(TraceEventType.Error, exception,
GetFormattedLog(string.Format("Exception while processing workItem {0}", workItemId)));
int delayInSecs = GetDelayInSecondsAfterOnProcessException(exception);
if (delayInSecs > 0)
{
TraceHelper.Trace(TraceEventType.Error,
"Backing off after exception by at least " + delayInSecs + " until " + CountDownToZeroDelay +
" successful operations");
AdjustDelayModifierOnFailure(delayInSecs);
}
else
{
// if the derived dispatcher doesn't think this exception worthy of backoff then
// count it as a 'successful' operation
AdjustDelayModifierOnSuccess();
}
}
finally
{
Interlocked.Decrement(ref concurrentWorkItemCount);
}
if (abortWorkItem)
{
await ExceptionTraceWrapperAsync(() => AbortWorkItem(workItem));
}
await ExceptionTraceWrapperAsync(() => SafeReleaseWorkItem(workItem));
}
void AdjustDelayModifierOnSuccess()
{
lock (thisLock)
{
if (countDownToZeroDelay > 0)
{
countDownToZeroDelay--;
}
if (countDownToZeroDelay == 0)
{
delayOverrideSecs = 0;
}
}
}
void AdjustDelayModifierOnFailure(int delaySecs)
{
lock (thisLock)
{
delayOverrideSecs = Math.Max(delayOverrideSecs, delaySecs);
countDownToZeroDelay = CountDownToZeroDelay;
}
}
async Task ExceptionTraceWrapperAsync(Func<Task> asyncAction)
{
try
{
await asyncAction();
}
catch (Exception exception)
{
if (Utils.IsFatal(exception))
{
throw;
}
// eat and move on
TraceHelper.TraceException(TraceEventType.Error, exception);
}
}
protected string GetFormattedLog(string message)
{
return string.Format("{0}-{1}: {2}", name, id, message);
}
protected delegate string WorkItemIdentifier(T workItem);
}
}