| | | 1 | | using Anichron.Core.Data.Repository; |
| | | 2 | | using Anichron.Worker.Settings; |
| | | 3 | | using Microsoft.Extensions.Options; |
| | | 4 | | using NodaTime; |
| | | 5 | | |
| | | 6 | | namespace Anichron.Worker.Maintenance; |
| | | 7 | | |
| | 4 | 8 | | public sealed partial class TokenCleanupService( |
| | 4 | 9 | | IServiceScopeFactory scopeFactory, |
| | 4 | 10 | | IClock clock, |
| | 4 | 11 | | IOptions<WorkerSettings> options, |
| | 4 | 12 | | ILogger<TokenCleanupService> logger) : BackgroundService |
| | | 13 | | { |
| | 4 | 14 | | private readonly WorkerSettings settings = options.Value; |
| | | 15 | | |
| | | 16 | | protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| | 0 | 17 | | { |
| | 0 | 18 | | using var timer = new PeriodicTimer(TimeSpan.FromHours(settings.TokenCleanupIntervalHours)); |
| | | 19 | | do |
| | 0 | 20 | | { |
| | | 21 | | try |
| | 0 | 22 | | { |
| | 0 | 23 | | await RunCleanupAsync(stoppingToken); |
| | 0 | 24 | | } |
| | 0 | 25 | | catch (Exception ex) when (ex is not OperationCanceledException) |
| | 0 | 26 | | { |
| | 0 | 27 | | Log.CleanupFailed(logger, ex); |
| | 0 | 28 | | } |
| | 0 | 29 | | } |
| | 0 | 30 | | while (await timer.WaitForNextTickAsync(stoppingToken)); |
| | 0 | 31 | | } |
| | | 32 | | |
| | | 33 | | internal async Task RunCleanupAsync(CancellationToken ct) |
| | 4 | 34 | | { |
| | 4 | 35 | | using var scope = scopeFactory.CreateScope(); |
| | 4 | 36 | | var repository = scope.ServiceProvider.GetRequiredService<IRefreshTokenRepository>(); |
| | 4 | 37 | | var now = clock.GetCurrentInstant(); |
| | 4 | 38 | | var deleted = await repository.DeleteExpiredAsync(now, ct); |
| | 3 | 39 | | Log.TokensDeleted(logger, deleted); |
| | 3 | 40 | | } |
| | | 41 | | |
| | | 42 | | private static partial class Log |
| | | 43 | | { |
| | | 44 | | [LoggerMessage(Level = LogLevel.Information, Message = "Deleted {Count} expired refresh token(s).")] |
| | | 45 | | public static partial void TokensDeleted(ILogger logger, int count); |
| | | 46 | | |
| | | 47 | | [LoggerMessage(Level = LogLevel.Error, Message = "Token cleanup failed; will retry on next tick.")] |
| | | 48 | | public static partial void CleanupFailed(ILogger logger, Exception ex); |
| | | 49 | | } |
| | | 50 | | } |