MdpSourceIdentityBackfillWorker.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using Microsoft.Extensions.DependencyInjection;
  2. using Microsoft.Extensions.Hosting;
  3. using Microsoft.Extensions.Logging;
  4. namespace Admin.NET.Plugin.AiDOP.DataPlatform.Schema;
  5. /// <summary>
  6. /// HTTP 已开始监听后再执行历史来源身份回填,避免数据迁移阻塞宿主启动。
  7. /// </summary>
  8. public sealed class MdpSourceIdentityBackfillWorker : BackgroundService
  9. {
  10. private readonly IServiceScopeFactory _scopeFactory;
  11. private readonly IHostApplicationLifetime _lifetime;
  12. private readonly ILogger<MdpSourceIdentityBackfillWorker> _logger;
  13. public MdpSourceIdentityBackfillWorker(
  14. IServiceScopeFactory scopeFactory,
  15. IHostApplicationLifetime lifetime,
  16. ILogger<MdpSourceIdentityBackfillWorker> logger)
  17. {
  18. _scopeFactory = scopeFactory;
  19. _lifetime = lifetime;
  20. _logger = logger;
  21. }
  22. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  23. {
  24. var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
  25. using var registration = _lifetime.ApplicationStarted.Register(() => started.TrySetResult());
  26. try
  27. {
  28. await started.Task.WaitAsync(stoppingToken);
  29. }
  30. catch (OperationCanceledException)
  31. {
  32. return;
  33. }
  34. try
  35. {
  36. using var scope = _scopeFactory.CreateScope();
  37. var db = scope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
  38. await MdpSchemaAligner.BackfillProvenSourceAsync(db);
  39. }
  40. catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
  41. {
  42. }
  43. catch (Exception ex)
  44. {
  45. _logger.LogWarning(ex, "中台历史来源身份回填失败;不影响 HTTP 服务");
  46. }
  47. }
  48. }