Repository navigation
Expand file tree
/
Copy pathCache.cs
More file actions
374 lines (334 loc) · 13.6 KB
/
Copy pathCache.cs
File metadata and controls
374 lines (334 loc) · 13.6 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/* Cache */
//#define CACHE_LOG
using System;
using System.Linq;
using System.Text.Json;
using System.Collections.Generic;
using PayrollEngine.Client.Scripting.Function;
namespace PayrollEngine.Client.Scripting;
/// <summary>Result cache cycle</summary>
public enum ResultCacheCycle
{
/// <summary>Cache previous cycle results too</summary>
PreviousCycle,
/// <summary>Cache current cycle results only</summary>
CurrentCycle
}
/// <summary>Cache for collector results</summary>
public abstract class ConsolidatedResultCacheBase
{
/// <summary>The caching start date</summary>
private DateTime CycleStartDate { get; }
/// <summary>The result cache cycle</summary>
private ResultCacheCycle CacheCycle { get; }
/// <summary>The payrun job status</summary>
protected PayrunJobStatus? JobStatus { get; }
/// <summary>Cache constructor</summary>
/// <param name="cycleStartDate">The cycle start date</param>
/// <param name="jobStatus">The payrun job status</param>
/// <param name="cacheCycle">The result cache cycle</param>
protected ConsolidatedResultCacheBase(DateTime cycleStartDate,
PayrunJobStatus? jobStatus = null,
ResultCacheCycle cacheCycle = ResultCacheCycle.PreviousCycle)
{
CycleStartDate = cycleStartDate;
JobStatus = jobStatus;
CacheCycle = cacheCycle;
}
/// <summary>Get start date of previous cycle</summary>
/// <param name="function">The payrun function</param>
protected DateTime GetCacheStartDate(PayrunFunction function) =>
CacheCycle switch
{
ResultCacheCycle.PreviousCycle => function.GetCycle(CycleStartDate, -1).Start,
ResultCacheCycle.CurrentCycle => CycleStartDate,
_ => throw new ArgumentOutOfRangeException()
};
/// <summary>Check for matching result period</summary>
/// <param name="periodStarts">The period starts</param>
/// <param name="resultStart">The result start date</param>
/// <returns>True on matching period</returns>
protected static bool IsMatchingPeriodStarts(IList<DateTime> periodStarts, DateTime resultStart)
=> periodStarts.Any(x => x.Date == resultStart.Date);
/// <summary>Get consolidated period starts from the query moment until the current period</summary>
/// <param name="function">The payrun function</param>
/// <param name="query">The consolidated result query</param>
/// <returns>The period start dates</returns>
protected List<DateTime> GetConsolidatedPeriodStarts(PayrunFunction function, ConsolidatedResultQuery query)
{
// test for valid cycle setup
if (function.CycleStart != CycleStartDate)
{
throw new ScriptException($"Mismatching cache cycle dates: {function.CycleStart} vs {CycleStartDate}.");
}
// forecast
if (!string.IsNullOrWhiteSpace(query.Forecast))
{
// forecast queries not supported for cached consolidated results
return null;
}
// noRetro queries bypass the cache (cache contains retro entries)
if (query.NoRetro)
{
return null;
}
// mismatching job status
if (query.JobStatus != JobStatus)
{
function.LogWarning($"Mismatching cache query job status: {query.JobStatus} vs {JobStatus}");
return null;
}
// the cache covers the periods from the cache start date
var cacheStartDate = GetCacheStartDate(function);
if (query.PeriodMoment < cacheStartDate)
{
return null;
}
var periodStarts = function.GetConsolidatedPeriodStarts(query.PeriodMoment);
// order periods from newest to oldest
return [.. periodStarts.OrderByDescending(x => x)];
}
// Duplicated in backend payroll repository command
/// <summary>Check for matching result tags</summary>
/// <param name="queryTags">The query tags</param>
/// <param name="resultTags">The result tags</param>
/// <returns>True on matching tags</returns>
protected static bool IsMatchingTags(IList<string> queryTags, IList<string> resultTags)
{
// build query tag list
if (queryTags == null || !queryTags.Any())
{
return true;
}
var tagList = new List<string>(queryTags.Where(x => !string.IsNullOrWhiteSpace(x)).Distinct());
if (!tagList.Any())
{
return true;
}
// missing result tags
if (resultTags == null || !resultTags.Any())
{
return false;
}
// first tag used to enable the logical OR mode
var anyTag = "*".Equals(tagList.First().Trim(), StringComparison.InvariantCultureIgnoreCase);
if (anyTag)
{
tagList.RemoveAt(0);
// any query only with multiple tags
anyTag = tagList.Count > 1;
}
if (!tagList.Any())
{
return false;
}
// test tags filter
return anyTag ?
// check if any tag is present
tagList.Any(resultTags.Contains) :
// check if all tags are present
tagList.All(resultTags.Contains);
}
}
/// <summary>Cache for consolidated collector results</summary>
public class CollectorConsolidatedResultCache : ConsolidatedResultCacheBase
{
/// <summary>The consolidated results cache</summary>
private IList<CollectorResult> ConsolidatedResults { get; set; }
/// <summary>Cache constructor</summary>
/// <param name="cycleStartDate">The cycle start date</param>
/// <param name="jobStatus">The payrun job status</param>
/// <param name="cacheCycle">The result cache cycle</param>
public CollectorConsolidatedResultCache(DateTime cycleStartDate,
PayrunJobStatus? jobStatus = null,
ResultCacheCycle cacheCycle = ResultCacheCycle.PreviousCycle) :
base(cycleStartDate, jobStatus, cacheCycle)
{
}
/// <summary>Get the collector results</summary>
public IList<CollectorResult> GetConsolidatedResults(PayrunFunction function,
CollectorConsolidatedResultQuery query, string runtimeKey = null)
{
IList<CollectorResult> result;
var periodStarts = GetConsolidatedPeriodStarts(function, query);
if (periodStarts != null && PrepareResultCache(function, runtimeKey))
{
// use cache
result = ConsolidatedResults.Where(x =>
IsMatchingCollectorName(query.Collectors, x.CollectorName) &&
IsMatchingPeriodStarts(periodStarts, x.Start) &&
IsMatchingTags(query.Tags, x.Tags))
.ToList();
#if CACHE_LOG
function.LogWarning($"CollectorResultCache: reusing cache ({result.Count})");
#endif
}
else
{
// fallback to slow backend request
result = function.GetConsolidatedCollectorResults(query);
#if CACHE_LOG
function.LogWarning($"CollectorResultCache: fallback to database query ({result.Count})");
#endif
}
return result;
}
private static bool IsMatchingCollectorName(IList<string> queryCollectors, string collectorName) =>
!queryCollectors.Any() || queryCollectors.Contains(collectorName);
/// <summary>Get the result cache from the employee runtime</summary>
/// <param name="function"></param>
/// <param name="runtimeKey">The employee runtime key, default is <see cref="CollectorConsolidatedResultCache"/></param>
/// <returns>The collector result cache</returns>
private bool PrepareResultCache(PayrunFunction function, string runtimeKey = null)
{
if (function == null)
{
throw new ArgumentNullException(nameof(function));
}
if (string.IsNullOrWhiteSpace(runtimeKey))
{
runtimeKey = nameof(CollectorConsolidatedResultCache);
}
// reuse cached results
if (ConsolidatedResults != null)
{
return true;
}
try
{
// cached values from employee runtime
var results = function.GetEmployeeRuntimeValue<List<CollectorResult>>(runtimeKey);
if (results == null || !results.Any())
{
var cacheStartDate = GetCacheStartDate(function);
// initialize cache
var query = new CollectorConsolidatedResultQuery(new List<string>(), cacheStartDate, JobStatus);
ConsolidatedResults = function.GetConsolidatedCollectorResults(query);
#if CACHE_LOG
function.LogWarning($"CollectorResultCache:: setup cache: start={cacheStartDate}, period={function.Period}, {ConsolidatedResults?.Count}");
#endif
// update employee runtime
if (ConsolidatedResults != null && ConsolidatedResults.Any())
{
function.SetEmployeeRuntimeValue(runtimeKey,
JsonSerializer.Serialize(ConsolidatedResults));
}
}
else
{
// reused from employee runtime
ConsolidatedResults = results;
#if CACHE_LOG
function.LogWarning($"CollectorResultCache: consolidated collector cache success: {ConsolidatedResults?.Count}");
#endif
}
}
catch (Exception exception)
{
function.LogError(exception);
return false;
}
return true;
}
}
/// <summary>Cache for consolidated wage type results</summary>
public class WageTypeConsolidatedResultCache : ConsolidatedResultCacheBase
{
/// <summary>The consolidated results cache</summary>
private IList<WageTypeResult> ConsolidatedResults { get; set; }
/// <summary>Cache constructor</summary>
/// <param name="cycleStartDate">The cycle start date</param>
/// <param name="jobStatus">The payrun job status</param>
/// <param name="cacheCycle">The result cache cycle</param>
public WageTypeConsolidatedResultCache(DateTime cycleStartDate,
PayrunJobStatus? jobStatus = null,
ResultCacheCycle cacheCycle = ResultCacheCycle.PreviousCycle) :
base(cycleStartDate, jobStatus, cacheCycle)
{
}
/// <summary>Get the collector results</summary>
public IList<WageTypeResult> GetConsolidatedResults(PayrunFunction function,
WageTypeConsolidatedResultQuery query, string runtimeKey = null)
{
IList<WageTypeResult> result;
var periodStarts = GetConsolidatedPeriodStarts(function, query);
// use cache
if (periodStarts != null && PrepareResultCache(function, runtimeKey))
{
result = ConsolidatedResults.Where(x =>
IsMatchingWageTypeNumber(query.WageTypes, x.WageTypeNumber) &&
IsMatchingPeriodStarts(periodStarts, x.Start) &&
IsMatchingTags(query.Tags, x.Tags))
.ToList();
#if CACHE_LOG
function.LogWarning($"WageTypeResultCache: reusing cache ({result.Count})");
#endif
}
else
{
// fallback to slow backend request
result = function.GetConsolidatedWageTypeResults(query);
#if CACHE_LOG
function.LogWarning($"WageTypeResultCache: fallback to database query ({result.Count})");
#endif
}
return result;
}
private static bool IsMatchingWageTypeNumber(IList<decimal> queryNumbers, decimal wageTypeNumber) =>
!queryNumbers.Any() || queryNumbers.Any(x => x == wageTypeNumber);
/// <summary>Get the result cache from the employee runtime</summary>
/// <param name="function"></param>
/// <param name="runtimeKey">The employee runtime key, default is <see cref="WageTypeConsolidatedResultCache"/></param>
/// <returns>The collector result cache</returns>
private bool PrepareResultCache(PayrunFunction function, string runtimeKey = null)
{
if (function == null)
{
throw new ArgumentNullException(nameof(function));
}
if (string.IsNullOrWhiteSpace(runtimeKey))
{
runtimeKey = nameof(WageTypeConsolidatedResultCache);
}
// reuse cached results
if (ConsolidatedResults != null)
{
return true;
}
try
{
// cached values from employee runtime
var results = function.GetEmployeeRuntimeValue<List<WageTypeResult>>(runtimeKey);
if (results == null || !results.Any())
{
var cacheStartDate = GetCacheStartDate(function);
// initialize cache
var query = new WageTypeConsolidatedResultQuery(new List<decimal>(),
cacheStartDate, JobStatus);
ConsolidatedResults = function.GetConsolidatedWageTypeResults(query);
#if CACHE_LOG
function.LogWarning($"WageTypeResultCache:: setup cache: start={cacheStartDate}, period={function.Period}, {ConsolidatedResults?.Count}");
#endif
// update employee runtime
if (ConsolidatedResults != null && ConsolidatedResults.Any())
{
function.SetEmployeeRuntimeValue(runtimeKey,
JsonSerializer.Serialize(ConsolidatedResults));
}
}
else
{
ConsolidatedResults = results;
#if CACHE_LOG
function.LogWarning($"WageTypeResultCache:: consolidated wage type cache success: {ConsolidatedResults?.Count}");
#endif
}
}
catch (Exception exception)
{
function.LogError(exception);
return false;
}
return true;
}
}