// ----------------------------------------------------------------------------- // CacheWarmupHostedService.cs // Sprint: SPRINT_8200_0013_0001_GW_valkey_advisory_cache // Task: VCACHE-8200-024 // Description: Background service for cache warmup on startup // ----------------------------------------------------------------------------- using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace StellaOps.Concelier.Cache.Valkey; /// /// Background hosted service that warms the advisory cache on application startup. /// public sealed class CacheWarmupHostedService : BackgroundService { private readonly IAdvisoryCacheService _cacheService; private readonly ConcelierCacheOptions _options; private readonly ILogger? _logger; /// /// Initializes a new instance of . /// public CacheWarmupHostedService( IAdvisoryCacheService cacheService, IOptions options, ILogger? logger = null) { _cacheService = cacheService; _options = options.Value; _logger = logger; } /// protected override async Task ExecuteAsync(CancellationToken stoppingToken) { if (!_options.Enabled || !_options.EnableWarmup) { _logger?.LogInformation("Cache warmup is disabled"); return; } // Wait a short time for the application to fully start await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken).ConfigureAwait(false); _logger?.LogInformation("Starting cache warmup with limit {Limit}", _options.WarmupLimit); try { await _cacheService.WarmupAsync(_options.WarmupLimit, stoppingToken).ConfigureAwait(false); _logger?.LogInformation("Cache warmup completed successfully"); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { _logger?.LogInformation("Cache warmup cancelled"); } catch (Exception ex) { _logger?.LogError(ex, "Cache warmup failed"); } } }