Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

83 lines
2.8KB

  1. using Microsoft.Extensions.Options;
  2. namespace Campaign_Tracker.Server.ExtensionData;
  3. public sealed class LegacyLinkIntegrityOptions
  4. {
  5. public bool Enabled { get; init; } = true;
  6. public TimeSpan RunTimeLocal { get; init; } = new(2, 0, 0);
  7. }
  8. public sealed class LegacyLinkIntegrityHostedService : BackgroundService
  9. {
  10. private readonly IServiceScopeFactory _scopeFactory;
  11. private readonly ILogger<LegacyLinkIntegrityHostedService> _logger;
  12. private readonly LegacyLinkIntegrityOptions _options;
  13. public LegacyLinkIntegrityHostedService(
  14. IServiceScopeFactory scopeFactory,
  15. ILogger<LegacyLinkIntegrityHostedService> logger,
  16. IOptions<LegacyLinkIntegrityOptions> options)
  17. {
  18. _scopeFactory = scopeFactory;
  19. _logger = logger;
  20. _options = options.Value;
  21. }
  22. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  23. {
  24. if (!_options.Enabled)
  25. {
  26. _logger.LogInformation("Legacy link nightly integrity check scheduler is disabled.");
  27. return;
  28. }
  29. while (!stoppingToken.IsCancellationRequested)
  30. {
  31. await Task.Delay(GetDelayUntilNextRun(DateTimeOffset.Now, _options.RunTimeLocal), stoppingToken);
  32. await RunOnceAsync(stoppingToken);
  33. }
  34. }
  35. private async Task RunOnceAsync(CancellationToken cancellationToken)
  36. {
  37. try
  38. {
  39. using var scope = _scopeFactory.CreateScope();
  40. var check = scope.ServiceProvider.GetRequiredService<ILegacyLinkIntegrityCheck>();
  41. var report = await check.CheckAsync(cancellationToken);
  42. if (report.IsConsistent)
  43. {
  44. _logger.LogInformation(
  45. "Legacy link nightly integrity check passed: {Consistent}/{Total} records ({Percentage:F2}%).",
  46. report.ConsistentRecords, report.TotalRecords, report.ConsistencyPercentage);
  47. }
  48. else
  49. {
  50. _logger.LogError(
  51. "Legacy link nightly integrity check failed: {Failures}/{Total} records failed ({Percentage:F2}%).",
  52. report.FailedRecords, report.TotalRecords, report.ConsistencyPercentage);
  53. }
  54. }
  55. catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
  56. {
  57. }
  58. catch (Exception ex)
  59. {
  60. _logger.LogError(ex, "Legacy link nightly integrity check could not complete.");
  61. }
  62. }
  63. private static TimeSpan GetDelayUntilNextRun(DateTimeOffset now, TimeSpan runTimeLocal)
  64. {
  65. var next = new DateTimeOffset(now.Date + runTimeLocal, now.Offset);
  66. if (next <= now)
  67. {
  68. next = next.AddDays(1);
  69. }
  70. return next - now;
  71. }
  72. }

Powered by TurnKey Linux.