-
Notifications
You must be signed in to change notification settings - Fork 803
/
EntityActionScheduler.cs
254 lines (221 loc) · 7.61 KB
/
EntityActionScheduler.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Yarp.ReverseProxy.Utilities;
namespace Yarp.ReverseProxy.Health;
/// <summary>
/// Periodically invokes specified actions on registered entities.
/// </summary>
/// <remarks>
/// It creates a separate <see cref="Timer"/> for each registration which is considered
/// reasonably efficient because .NET already maintains a process-wide managed timer queue.
/// There are 2 scheduling modes supported: run once and infinite run. In "run once" mode,
/// an entity gets unscheduled after the respective timer fired for the first time whereas
/// in "infinite run" entities get repeatedly rescheduled until either they are explicitly removed
/// or the <see cref="EntityActionScheduler{T}"/> instance is disposed.
/// </remarks>
internal sealed class EntityActionScheduler<T> : IDisposable where T : notnull
{
private readonly ConcurrentDictionary<T, SchedulerEntry> _entries = new();
private readonly WeakReference<EntityActionScheduler<T>> _weakThisRef;
private readonly Func<T, Task> _action;
private readonly bool _runOnce;
private readonly TimeProvider _timeProvider;
private const int NotStarted = 0;
private const int Started = 1;
private const int Disposed = 2;
private int _status;
public EntityActionScheduler(Func<T, Task> action, bool autoStart, bool runOnce, TimeProvider timeProvider)
{
_action = action ?? throw new ArgumentNullException(nameof(action));
_runOnce = runOnce;
_timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
_status = autoStart ? Started : NotStarted;
_weakThisRef = new WeakReference<EntityActionScheduler<T>>(this);
}
public void Dispose()
{
Volatile.Write(ref _status, Disposed);
foreach (var entry in _entries.Values)
{
entry.Dispose();
}
}
public void Start()
{
if (Interlocked.CompareExchange(ref _status, Started, NotStarted) != NotStarted)
{
return;
}
foreach (var entry in _entries.Values)
{
entry.EnsureStarted();
}
}
public void ScheduleEntity(T entity, TimeSpan period)
{
// Ensure the Timer has a weak reference to this scheduler; otherwise,
// EntityActionScheduler can be rooted by the Timer implementation.
var entry = new SchedulerEntry(_weakThisRef, entity, period, _timeProvider);
if (_entries.TryAdd(entity, entry))
{
// Scheduler could have been started while we were adding the new entry.
// Start timer here to ensure it's not forgotten.
if (Volatile.Read(ref _status) == Started)
{
entry.EnsureStarted();
}
}
else
{
entry.Dispose();
}
}
public void ChangePeriod(T entity, TimeSpan newPeriod)
{
Debug.Assert(!_runOnce, "Calling ChangePeriod on a RunOnce scheduler may cause the callback to fire twice");
if (_entries.TryGetValue(entity, out var entry))
{
entry.ChangePeriod(newPeriod);
}
else
{
ScheduleEntity(entity, newPeriod);
}
}
public void UnscheduleEntity(T entity)
{
if (_entries.TryRemove(entity, out var entry))
{
entry.Dispose();
}
}
public bool IsScheduled(T entity)
{
return _entries.ContainsKey(entity);
}
private sealed class SchedulerEntry : IDisposable
{
private readonly WeakReference<EntityActionScheduler<T>> _scheduler;
private readonly T _entity;
private readonly ITimer _timer;
private TimeSpan _period;
private bool _timerStarted;
private bool _runningCallback;
public SchedulerEntry(WeakReference<EntityActionScheduler<T>> scheduler, T entity, TimeSpan period, TimeProvider timeProvider)
{
_scheduler = scheduler;
_entity = entity;
_period = period;
// Don't capture the current ExecutionContext and its AsyncLocals onto the timer causing them to live forever
var restoreFlow = false;
try
{
if (!ExecutionContext.IsFlowSuppressed())
{
ExecutionContext.SuppressFlow();
restoreFlow = true;
}
_timer = timeProvider.CreateTimer(static s => _ = TimerCallback(s), this, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
}
finally
{
if (restoreFlow)
{
ExecutionContext.RestoreFlow();
}
}
}
public void ChangePeriod(TimeSpan newPeriod)
{
lock (this)
{
_period = newPeriod;
if (_timerStarted && !_runningCallback)
{
SetTimer();
}
}
}
public void EnsureStarted()
{
lock (this)
{
if (!_timerStarted)
{
SetTimer();
}
}
}
private void SetTimer()
{
Debug.Assert(Monitor.IsEntered(this));
Debug.Assert(!_runningCallback);
_timerStarted = true;
try
{
_timer.Change(_period, Timeout.InfiniteTimeSpan);
}
catch (ObjectDisposedException)
{
// It can be thrown if the timer has been already disposed.
// Just suppress it.
}
}
public void Dispose()
{
_timer.Dispose();
}
// Timer.Change is racy as the callback could already be scheduled while we are starting the timer again.
// Avoid running the callback multiple times concurrently by using the _runningCallback flag.
private static async Task TimerCallback(object? state)
{
var entry = (SchedulerEntry)state!;
lock (entry)
{
if (entry._runningCallback)
{
return;
}
entry._runningCallback = true;
}
if (!entry._scheduler.TryGetTarget(out var scheduler))
{
return;
}
var pair = new KeyValuePair<T, SchedulerEntry>(entry._entity, entry);
if (scheduler._runOnce && scheduler._entries.TryRemove(pair))
{
entry.Dispose();
}
try
{
await scheduler._action(entry._entity);
if (!scheduler._runOnce && scheduler._entries.Contains(pair))
{
// This entry has not been unscheduled - set the timer again
lock (entry)
{
entry._runningCallback = false;
entry.SetTimer();
}
}
}
catch (Exception ex)
{
// We are running on the ThreadPool, don't propagate excetions
Debug.Fail(ex.ToString()); // TODO: Log
if (scheduler._entries.TryRemove(pair))
{
entry.Dispose();
}
return;
}
}
}
}