MdpConfiguredDbSyncJob.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. using System.Text.Json;
  2. using Admin.NET.Plugin.AiDOP.DataPlatform;
  3. using Admin.NET.Plugin.AiDOP.DataPlatform.MdpRebuild;
  4. using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  5. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
  6. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  7. using Furion.Schedule;
  8. using Microsoft.Extensions.DependencyInjection;
  9. using Microsoft.Extensions.Logging;
  10. namespace Admin.NET.Plugin.AiDOP.Job;
  11. /// <summary>
  12. /// 方式甲动态调度。不标注 JobDetail,避免被内置扫描当成固定作业删掉。
  13. /// </summary>
  14. public sealed class MdpConfiguredDbSyncJob : IJob
  15. {
  16. private static readonly JsonSerializerOptions ScheduleJson = new(JsonSerializerDefaults.Web);
  17. private readonly IServiceScopeFactory _scopeFactory;
  18. private readonly ILogger _logger;
  19. public MdpConfiguredDbSyncJob(IServiceScopeFactory scopeFactory, ILoggerFactory loggerFactory)
  20. {
  21. _scopeFactory = scopeFactory;
  22. _logger = loggerFactory.CreateLogger(nameof(MdpConfiguredDbSyncJob));
  23. }
  24. public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
  25. {
  26. var properties = context.JobDetail.Properties ?? "{}";
  27. var payload = JsonSerializer.Deserialize<Payload>(properties);
  28. var legacyProperties = payload?.TenantId > 0 && !string.IsNullOrWhiteSpace(payload.TaskCode);
  29. if (!legacyProperties)
  30. payload = JsonSerializer.Deserialize<Payload>(properties, ScheduleJson);
  31. if (payload == null || payload.TenantId <= 0 || string.IsNullOrWhiteSpace(payload.TaskCode))
  32. {
  33. _logger.LogWarning("方式甲调度缺少 tenantId 或 taskCode");
  34. return;
  35. }
  36. using var scope = _scopeFactory.CreateScope();
  37. var db = scope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
  38. var ops = scope.ServiceProvider.GetRequiredService<MdpDbEntityOperationService>();
  39. var neutralProjection = scope.ServiceProvider.GetRequiredService<MdpDbSyncNeutralProjection>();
  40. var rebuild = scope.ServiceProvider.GetRequiredService<MdpDbSyncRebuildTrigger>();
  41. var task = await db.Queryable<MdpSyncTask>()
  42. .Where(x => x.TaskCode == payload.TaskCode && x.TenantId == payload.TenantId && x.Status == 1)
  43. .FirstAsync(stoppingToken);
  44. if (task == null || !string.Equals(task.TaskType, "DB_SYNC", StringComparison.OrdinalIgnoreCase))
  45. return;
  46. var schedule = await db.Queryable<MdpSyncTaskSchedule>()
  47. .Where(x => x.TaskCode == task.TaskCode && x.TenantId == task.TenantId)
  48. .FirstAsync(stoppingToken);
  49. if (schedule == null || schedule.AutoEnabled != 1)
  50. return;
  51. var relational = scope.ServiceProvider.GetRequiredService<MdpRelationalSyncService>();
  52. try
  53. {
  54. if (await relational.RunScheduledAsync(payload.TenantId, payload.TaskCode, stoppingToken))
  55. return;
  56. }
  57. catch (Exception error) when (!stoppingToken.IsCancellationRequested)
  58. {
  59. var code = error switch
  60. {
  61. MdpIngestHttpException ingest => ingest.Code,
  62. ConnectorContractException connector => connector.Code.ToString(),
  63. _ => error.GetType().Name,
  64. };
  65. // Provider or configuration exceptions can contain source secrets.
  66. _logger.LogWarning("数据库关系同步任务 {TaskCode} 未推进,原因 {Code}", task.TaskCode, code);
  67. throw new InvalidOperationException("Relational synchronization did not advance: " + code);
  68. }
  69. if (!legacyProperties)
  70. {
  71. _logger.LogWarning("方式甲调度缺少 tenantId 或 taskCode");
  72. return;
  73. }
  74. var entities = await db.Queryable<MdpEntity>()
  75. .Where(x => x.Status == 1 && (x.TenantId == payload.TenantId || x.TenantId == 0))
  76. .Where(x => x.JobId == task.TaskCode || x.JobId == task.JobCode)
  77. .ToListAsync(stoppingToken);
  78. var failed = 0;
  79. foreach (var entity in entities)
  80. {
  81. stoppingToken.ThrowIfCancellationRequested();
  82. var issues = MdpDbSyncRules.ValidateDbEntity(entity, "DB");
  83. if (issues.Count > 0)
  84. {
  85. failed++;
  86. continue;
  87. }
  88. try
  89. {
  90. var mode = string.IsNullOrWhiteSpace(schedule.SyncWindowType) ? entity.SyncMode : schedule.SyncWindowType;
  91. await ops.RunEntityAsync(entity.Id, mode, "调度自动执行", "AUTO", stoppingToken, payload.TenantId);
  92. }
  93. catch (Exception ex)
  94. {
  95. failed++;
  96. _logger.LogError(ex, "方式甲实体 {EntityCode} 调度失败", entity.EntityCode);
  97. }
  98. }
  99. if (failed > 0)
  100. {
  101. _logger.LogWarning("方式甲任务 {TaskCode} 有 {Failed} 个实体未成功", task.TaskCode, failed);
  102. throw new InvalidOperationException(
  103. $"方式甲任务 {task.TaskCode} 有 {failed} 个实体未成功,本轮不触发模块重算");
  104. }
  105. else if (entities.Count > 0)
  106. {
  107. await neutralProjection.ProjectAsync(entities, payload.TenantId, stoppingToken);
  108. var modules = await rebuild.EnqueueForTaskAsync(
  109. task, payload.TenantId, factoryId: 1, triggerType: ModuleRebuildTriggerType.DbSync, stoppingToken);
  110. _logger.LogInformation(
  111. "方式甲任务 {TaskCode} 抽取完成,已触发模块重算:{Modules}",
  112. task.TaskCode,
  113. modules.Count == 0 ? "无" : string.Join(",", modules));
  114. }
  115. }
  116. private sealed class Payload
  117. {
  118. public long TenantId { get; set; }
  119. public string? TaskCode { get; set; }
  120. }
  121. }