65 lines
2.2 KiB
C#
65 lines
2.2 KiB
C#
// -----------------------------------------------------------------------------
|
|
// 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;
|
|
|
|
/// <summary>
|
|
/// Background hosted service that warms the advisory cache on application startup.
|
|
/// </summary>
|
|
public sealed class CacheWarmupHostedService : BackgroundService
|
|
{
|
|
private readonly IAdvisoryCacheService _cacheService;
|
|
private readonly ConcelierCacheOptions _options;
|
|
private readonly ILogger<CacheWarmupHostedService>? _logger;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of <see cref="CacheWarmupHostedService"/>.
|
|
/// </summary>
|
|
public CacheWarmupHostedService(
|
|
IAdvisoryCacheService cacheService,
|
|
IOptions<ConcelierCacheOptions> options,
|
|
ILogger<CacheWarmupHostedService>? logger = null)
|
|
{
|
|
_cacheService = cacheService;
|
|
_options = options.Value;
|
|
_logger = logger;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
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");
|
|
}
|
|
}
|
|
}
|