| | | 1 | | namespace ArturRios.Heimdall.WebApi.Monitoring; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Holds the readiness answer for <see cref="Window">a few seconds</see>, so the anonymous probe costs |
| | | 5 | | /// the database one read per window however often it is called (#215). |
| | | 6 | | /// </summary> |
| | | 7 | | /// <remarks> |
| | | 8 | | /// A singleton. Callers that arrive while a check is in flight, or within the window after it, share |
| | | 9 | | /// its result, so the window expiring does not release a herd of reads at once. The unhealthy answer is |
| | | 10 | | /// held too: while the database is down, a flood of probes writes no further read, stack trace or |
| | | 11 | | /// Warning until the window ends. Five seconds is shorter than the Compose probe's interval, so the |
| | | 12 | | /// probe still sees every change. |
| | | 13 | | /// </remarks> |
| | 15 | 14 | | public class ReadinessCache(TimeProvider clock) |
| | | 15 | | { |
| | | 16 | | /// <summary>How long an answer is reused.</summary> |
| | 1 | 17 | | public static readonly TimeSpan Window = TimeSpan.FromSeconds(5); |
| | | 18 | | |
| | 15 | 19 | | private readonly object _gate = new(); |
| | | 20 | | private Task<bool>? _current; |
| | | 21 | | private DateTimeOffset _startedAt; |
| | | 22 | | |
| | | 23 | | /// <summary>The cached answer, or the result of <paramref name="check" /> when there is none current.</summary> |
| | | 24 | | public Task<bool> IsReadyAsync(Func<Task<bool>> check) |
| | | 25 | | { |
| | 27 | 26 | | lock (_gate) |
| | | 27 | | { |
| | 27 | 28 | | var now = clock.GetUtcNow(); |
| | | 29 | | |
| | 27 | 30 | | if (_current is null || now - _startedAt >= Window) |
| | | 31 | | { |
| | 7 | 32 | | _current = check(); |
| | 7 | 33 | | _startedAt = now; |
| | | 34 | | } |
| | | 35 | | |
| | 27 | 36 | | return _current; |
| | | 37 | | } |
| | 27 | 38 | | } |
| | | 39 | | } |