using EntitlementBLL.Interfaces; using EntitlementDAL.Interfaces; using GB5Shared.Telemetry; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Quartz; namespace EntitlementBLL.Handlers; // Daily 02:00: re-issues signed bundles expiring within 7 days so clients never observe a lapsed // bundle from routine cache/CDN staleness alone. [DisallowConcurrentExecution] public class EntitlementBundleRefreshJob : IJob { private readonly IServiceScopeFactory _ScopeFactory; private readonly ILogger _Logger; public EntitlementBundleRefreshJob(IServiceScopeFactory scopeFactory, ILogger logger) { _ScopeFactory = scopeFactory; _Logger = logger; } public async Task Execute(IJobExecutionContext context) { using var activity = GB5Trace.BeginSection("entitlement-bundle-refresh-job"); var ct = context.CancellationToken; using var scope = _ScopeFactory.CreateScope(); var bundleDal = scope.ServiceProvider.GetRequiredService(); var bundleService = scope.ServiceProvider.GetRequiredService(); var loginFactory = scope.ServiceProvider.GetRequiredService(); var login = loginFactory.Create(-1); var cutoff = DateTime.UtcNow.AddDays(7); var expiring = await bundleDal.GetExpiringSoonAsync(cutoff, login, ct).ConfigureAwait(false); foreach (var bundle in expiring) { try { GB5Trace.Step("refresh-bundle", new { bundle.ClientId }); await bundleService.IssueSignedBundleAsync(bundle.ClientId, ct).ConfigureAwait(false); } catch (Exception ex) { GB5Trace.MarkFailed("entitlement-bundle-refresh-failed", ex); _Logger.LogError(ex, "EntitlementBundleRefreshJob failed for ClientId {ClientId}", bundle.ClientId); } } } }