/
PollingProcessor.cs
274 lines (240 loc) · 9.63 KB
/
PollingProcessor.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using io.harness.cfsdk.client.connector;
using io.harness.cfsdk.HarnessOpenAPIService;
using Microsoft.Extensions.Logging;
namespace io.harness.cfsdk.client.api
{
public enum RefreshOutcome
{
Success,
Error,
TooSoon,
}
internal interface IPollCallback
{
/// <summary>
/// After initial data poll
/// </summary>
void OnPollerReady();
void OnPollError(string message);
}
internal interface IPollingProcessor
{
/// <summary>
/// Stop pooling
/// </summary>
void Stop();
/// <summary>
/// Start periodic pooling
/// </summary>
void Start();
RefreshOutcome RefreshSegments(TimeSpan timeout);
RefreshOutcome RefreshFlags(TimeSpan timeout);
RefreshOutcome RefreshFlagsAndSegments(TimeSpan timeout);
}
/// <summary>
/// This class is responsible to periodically read from server and persist all flags and
/// segments.
/// PollingProcessor will be always started after library is initialized, and continue to
/// read periodically date in case if SSE is turned off, or unavailable.
/// </summary>
internal class PollingProcessor : IPollingProcessor
{
private readonly ILogger<PollingProcessor> logger;
private readonly IConnector connector;
private readonly IRepository repository;
private readonly IPollCallback callback;
private readonly Config config;
private Timer pollTimer;
private bool isInitialized = false;
private readonly object cacheRefreshLock = new object();
private DateTime lastFlagsRefreshTime = DateTime.MinValue;
private DateTime lastSegmentsRefreshTime = DateTime.MinValue;
private const int MaxCacheRefreshTime = 60;
private readonly TimeSpan refreshCooldown = TimeSpan.FromSeconds(MaxCacheRefreshTime);
public PollingProcessor(IConnector connector, IRepository repository, Config config, IPollCallback callback, ILoggerFactory loggerFactory)
{
this.callback = callback;
this.repository = repository;
this.connector = connector;
this.config = config;
this.logger = loggerFactory.CreateLogger<PollingProcessor>();
}
public void Start()
{
var intervalMs = config.PollIntervalInMiliSeconds;
if (intervalMs < 60000)
{
logger.LogWarning("Poll interval cannot be less than 60 seconds");
intervalMs = 60000;
}
logger.LogDebug("Populate cache for first time after authentication");
try
{
Task.WhenAll(new List<Task> { ProcessFlags(), ProcessSegments() }).Wait();
}
catch (Exception ex)
{
logger.LogWarning(ex, "First poll failed: {Reason}", ex.Message);
}
logger.LogDebug("SDKCODE(poll:4000): Polling started, intervalMs: {intervalMs}", intervalMs);
// start timer which will initiate periodic reading of flags and segments
pollTimer = new Timer(OnTimedEventAsync, null, intervalMs, intervalMs);
}
public void Stop()
{
logger.LogDebug("SDKCODE(poll:4001): Polling stopped");
// stop timer
if (pollTimer == null) return;
pollTimer.Dispose();
pollTimer = null;
}
private async Task ProcessFlags()
{
try
{
logger.LogDebug("Fetching flags started");
var flags = await this.connector.GetFlags();
logger.LogDebug("Fetching flags finished");
repository.SetFlags(flags);
logger.LogInformation("Flag cache loaded {GetFlagsCount} flags", repository.GetFlagsCount());
}
catch (Exception ex)
{
logger.LogError(ex,"Exception was raised when fetching flags data with the message: {reason}", ex.Message);
throw;
}
}
private async Task ProcessSegments()
{
try
{
logger.LogDebug("Fetching segments started");
IEnumerable<Segment> segments = await connector.GetSegments();
logger.LogInformation("Count of segments {}", segments.Count());
logger.LogDebug("Fetching segments finished");
repository.SetSegments(segments);
logger.LogInformation("Group cache loaded {SegmentRuleCount} groups", repository.GetSegmentsCount());
}
catch (Exception ex)
{
logger.LogError(ex, "Exception was raised when fetching segments data with the message: {reason}", ex.Message);
throw;
}
}
public RefreshOutcome RefreshFlagsAndSegments(TimeSpan timeout)
{
lock (cacheRefreshLock)
{
if (!CanRefreshCache(ref lastSegmentsRefreshTime))
{
logger.LogWarning("Attempt to refresh groups too soon after the last refresh");
return RefreshOutcome.TooSoon;
}
var processSegmentsTask = Task.Run(async () => await ProcessSegments());
var processFlagsTask = Task.Run(async () => await ProcessFlags());
try
{
// Await both tasks to complete within the timeout
var refreshSuccessful = Task.WaitAll(new[] { processSegmentsTask, processFlagsTask }, timeout);
if (refreshSuccessful)
{
UpdateLastRefreshTime(ref lastSegmentsRefreshTime);
return RefreshOutcome.Success;
}
logger.LogWarning("Refreshing flags and groups did not complete within the specified timeout");
return RefreshOutcome.Error;
}
catch (Exception ex)
{
logger.LogError(ex, "Exception occurred while refreshing flags and groups");
return RefreshOutcome.Error;
}
}
}
public RefreshOutcome RefreshSegments(TimeSpan timeout)
{
lock (cacheRefreshLock)
{
if (!CanRefreshCache(ref lastSegmentsRefreshTime))
{
logger.LogWarning("Attempt to refresh groups too soon after the last refresh");
return RefreshOutcome.TooSoon;
}
try
{
var task = Task.Run(async () => await ProcessSegments());
var refreshSuccessful = task.Wait(timeout);
if (refreshSuccessful)
{
UpdateLastRefreshTime(ref lastSegmentsRefreshTime);
return RefreshOutcome.Success;
}
logger.LogWarning("Refresh groups did not complete within the specified timeout");
return RefreshOutcome.Error;
}
catch (Exception ex)
{
logger.LogError(ex, "Exception occurred while trying to refresh groups");
return RefreshOutcome.Error;
}
}
}
public RefreshOutcome RefreshFlags(TimeSpan timeout)
{
lock (cacheRefreshLock)
{
if (!CanRefreshCache(ref lastFlagsRefreshTime))
{
logger.LogWarning("Attempt to refresh flags too soon after the last refresh");
return RefreshOutcome.TooSoon;
}
try
{
var task = Task.Run(async () => await ProcessFlags());
var refreshSuccessful = task.Wait(timeout);
if (refreshSuccessful)
{
UpdateLastRefreshTime(ref lastFlagsRefreshTime);
return RefreshOutcome.Success;
}
logger.LogWarning("RefreshFlags did not complete within the specified timeout");
return RefreshOutcome.Error;
}
catch (Exception ex)
{
logger.LogError(ex, "Exception occurred while trying to refresh flags");
return RefreshOutcome.Error;
}
}
}
private bool CanRefreshCache(ref DateTime lastRefreshTime)
{
return (DateTime.UtcNow - lastRefreshTime) >= refreshCooldown;
}
private void UpdateLastRefreshTime(ref DateTime lastRefreshTime)
{
lastRefreshTime = DateTime.UtcNow;
}
private async void OnTimedEventAsync(object source)
{
try
{
logger.LogDebug("Running polling iteration");
await Task.WhenAll(new List<Task> { ProcessFlags(), ProcessSegments() });
if (isInitialized) return;
isInitialized = true;
callback?.OnPollerReady();
}
catch(Exception ex)
{
logger.LogWarning(ex,"Polling failed with error: {reason}. Will retry in {pollIntervalInSeconds}", ex.Message, config.pollIntervalInSeconds);
callback?.OnPollError(ex.Message);
}
}
}
}