MdpRelationalSyncService.Schedule.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
  2. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  3. using static Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress.MdpRelationalSource;
  4. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  5. public sealed partial class MdpRelationalSyncService
  6. {
  7. private const string ProfileScope = """
  8. tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId AND profile_id=@Id
  9. """;
  10. internal async Task<object> ReadScheduleBindingAsync(RelationalTrialProfile profile, ConnectorBinding binding, CancellationToken token)
  11. {
  12. using var store = MdpIngestDatabase.Open(db);
  13. store.Ado.CancellationToken = token;
  14. var current = await BoundSchedule(store, profile);
  15. var tasks = await EligibleTasksAsync(store, profile, binding.Identity.SourceCode, token);
  16. return new
  17. {
  18. taskCode = current is null ? profile.ScheduleTaskCode : current.TaskCode,
  19. fromDeployment = current is null && profile.ScheduleTaskCode is not null,
  20. requiresRefresh = current?.TaskCode is not null && current.ScopeVersion != Signature(profile, binding),
  21. incremental = HasAppendLog(profile) || HasTimeSource(profile),
  22. tasks = tasks.Select(task => new { task.TaskCode, task.TaskName, task.AutoEnabled, task.CronExpr }),
  23. };
  24. }
  25. internal async Task SaveScheduleBindingAsync(RelationalTrialProfile profile, ConnectorBinding binding,
  26. string? taskCode, long actor, CancellationToken token)
  27. {
  28. using var store = MdpIngestDatabase.Open(db);
  29. store.Ado.CancellationToken = token;
  30. taskCode = string.IsNullOrWhiteSpace(taskCode) ? null : taskCode;
  31. var result = await store.Ado.UseTranAsync(async () =>
  32. {
  33. if (taskCode is not null)
  34. {
  35. var task = (await EligibleTasksAsync(store, profile, binding.Identity.SourceCode, token))
  36. .SingleOrDefault(t => string.Equals(t.TaskCode, taskCode, StringComparison.Ordinal));
  37. if (task is null)
  38. throw new MdpIngestHttpException(409, "RELATIONAL_TASK_INELIGIBLE");
  39. }
  40. var current = await BoundSchedule(store, profile, locked: true);
  41. var fields = new
  42. {
  43. profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId, profile.Id,
  44. taskCode, actor, scopeVersion = taskCode is null ? null : Signature(profile, binding),
  45. };
  46. if (current is null)
  47. await store.Ado.ExecuteCommandAsync("""
  48. INSERT INTO mdp_connector_relational_schedule
  49. (tenant_id,factory_id,dataset_id,source_id,profile_id,task_code,scope_version,updated_by,updated_at_utc)
  50. VALUES (@TenantId,@FactoryId,@DatasetId,@SourceId,@Id,@taskCode,@scopeVersion,@actor,UTC_TIMESTAMP(6))
  51. """, fields);
  52. else
  53. await store.Ado.ExecuteCommandAsync("""
  54. UPDATE mdp_connector_relational_schedule
  55. SET task_code=@taskCode,scope_version=@scopeVersion,updated_by=@actor,updated_at_utc=UTC_TIMESTAMP(6)
  56. WHERE
  57. """ + " " + ProfileScope, fields);
  58. });
  59. if (!result.IsSuccess) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(result.ErrorException!);
  60. }
  61. private static Task<RelationalScheduleBinding?> BoundSchedule(ISqlSugarClient store, RelationalTrialProfile profile,
  62. bool locked = false) => store.Ado.SqlQuerySingleAsync<RelationalScheduleBinding?>(
  63. """
  64. SELECT task_code AS TaskCode, scope_version AS ScopeVersion FROM mdp_connector_relational_schedule WHERE
  65. """ + " " + ProfileScope + (locked ? " FOR UPDATE" : ""), ProfileKeys(profile));
  66. private static object ProfileKeys(RelationalTrialProfile profile) =>
  67. new { profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId, profile.Id };
  68. private async Task<List<EligibleRelationalTask>> EligibleTasksAsync(ISqlSugarClient store, RelationalTrialProfile profile,
  69. string sourceCode, CancellationToken token)
  70. {
  71. var deploymentTasks = (await ReadProfiles(settings["MDP_RELATIONAL_TRIALS_FILE"], token))
  72. .Where(p => p.TenantId == profile.TenantId && p.SyncEnabled && p.Id != profile.Id && p.ScheduleTaskCode is not null)
  73. .Select(p => p.ScheduleTaskCode!).ToHashSet(StringComparer.OrdinalIgnoreCase);
  74. var tasks = await store.Ado.SqlQueryAsync<EligibleRelationalTask>("""
  75. SELECT t.task_code AS TaskCode,t.task_name AS TaskName,COALESCE(s.auto_enabled,0) AS AutoEnabled,s.cron_expr AS CronExpr
  76. FROM mdp_sync_task t
  77. LEFT JOIN mdp_sync_task_schedule s ON s.tenant_id=t.tenant_id AND s.task_code=t.task_code
  78. WHERE t.tenant_id=@TenantId AND t.status=1 AND t.task_type='DB_SYNC' AND t.source_system_code=@sourceCode
  79. AND NOT EXISTS (SELECT 1 FROM mdp_entity e WHERE e.status=1 AND e.tenant_id IN (0,t.tenant_id)
  80. AND (e.job_id=t.task_code OR e.job_id=t.job_code))
  81. AND NOT EXISTS (SELECT 1 FROM mdp_connector_relational_schedule r WHERE r.tenant_id=t.tenant_id
  82. AND r.task_code=t.task_code AND (r.factory_id<>@FactoryId OR r.dataset_id<>@DatasetId
  83. OR r.source_id<>@SourceId OR r.profile_id<>@Id))
  84. ORDER BY t.task_name,t.task_code
  85. """, new { profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId, profile.Id, sourceCode });
  86. return tasks.Where(task => !deploymentTasks.Contains(task.TaskCode)).ToList();
  87. }
  88. private sealed class RelationalScheduleBinding
  89. {
  90. public long FactoryId { get; set; }
  91. public long DatasetId { get; set; }
  92. public long SourceId { get; set; }
  93. public string ProfileId { get; set; } = "";
  94. public string? TaskCode { get; set; }
  95. public string? ScopeVersion { get; set; }
  96. }
  97. private sealed class EligibleRelationalTask
  98. {
  99. public string TaskCode { get; set; } = "";
  100. public string TaskName { get; set; } = "";
  101. public int AutoEnabled { get; set; }
  102. public string? CronExpr { get; set; }
  103. }
  104. }