| | | 1 | | using Serilog.Events; |
| | | 2 | | |
| | | 3 | | namespace Kestrun.Health; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Simple <see cref="IProbe"/> implementation that delegates execution to a user-supplied asynchronous function. |
| | | 7 | | /// </summary> |
| | 0 | 8 | | internal sealed class DelegateProbe(string name, IEnumerable<string>? tags, Func<CancellationToken, Task<ProbeResult>> c |
| | | 9 | | { |
| | 0 | 10 | | private readonly Func<CancellationToken, Task<ProbeResult>> _callback = callback ?? throw new ArgumentNullException( |
| | | 11 | | |
| | | 12 | | /// <inheritdoc /> |
| | 0 | 13 | | public string Name { get; } = string.IsNullOrWhiteSpace(name) |
| | 0 | 14 | | ? throw new ArgumentException("Probe name cannot be null or empty.", nameof(name)) |
| | 0 | 15 | | : name; |
| | | 16 | | |
| | | 17 | | /// <inheritdoc /> |
| | 0 | 18 | | public string[] Tags { get; } = tags?.Where(static t => !string.IsNullOrWhiteSpace(t)) |
| | 0 | 19 | | .Select(static t => t.Trim()) |
| | 0 | 20 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 0 | 21 | | .ToArray() ?? []; |
| | | 22 | | |
| | | 23 | | /// <inheritdoc /> |
| | 0 | 24 | | public Serilog.ILogger Logger { get; init; } = logger ?? Serilog.Log.ForContext("Probe", name); |
| | | 25 | | |
| | | 26 | | /// <inheritdoc /> |
| | | 27 | | public async Task<ProbeResult> CheckAsync(CancellationToken ct = default) |
| | | 28 | | { |
| | | 29 | | try |
| | | 30 | | { |
| | 0 | 31 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 32 | | { |
| | 0 | 33 | | Logger.Debug("DelegateProbe {Probe} starting", Name); |
| | | 34 | | } |
| | 0 | 35 | | var result = await _callback(ct).ConfigureAwait(false); |
| | 0 | 36 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 37 | | { |
| | 0 | 38 | | Logger.Debug("DelegateProbe {Probe} completed status={Status}", Name, result.Status); |
| | | 39 | | } |
| | 0 | 40 | | return result; |
| | | 41 | | } |
| | 0 | 42 | | catch (OperationCanceledException) when (ct.IsCancellationRequested) |
| | | 43 | | { |
| | 0 | 44 | | return new ProbeResult(ProbeStatus.Degraded, "Canceled"); |
| | | 45 | | } |
| | 0 | 46 | | catch (Exception ex) |
| | | 47 | | { |
| | 0 | 48 | | Logger.Error(ex, "DelegateProbe {Probe} failed", Name); |
| | 0 | 49 | | return new ProbeResult(ProbeStatus.Unhealthy, $"Exception: {ex.Message}"); |
| | | 50 | | } |
| | 0 | 51 | | } |
| | | 52 | | } |