using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors; using Admin.NET.Plugin.AiDOP.Entity.DataPlatform; using static Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress.MdpRelationalSource; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; public sealed partial class MdpRelationalSyncService { private const string ProfileScope = """ tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId AND profile_id=@Id """; internal async Task ReadScheduleBindingAsync(RelationalTrialProfile profile, ConnectorBinding binding, CancellationToken token) { using var store = MdpIngestDatabase.Open(db); store.Ado.CancellationToken = token; var current = await BoundSchedule(store, profile); var tasks = await EligibleTasksAsync(store, profile, binding.Identity.SourceCode, token); return new { taskCode = current is null ? profile.ScheduleTaskCode : current.TaskCode, fromDeployment = current is null && profile.ScheduleTaskCode is not null, requiresRefresh = current?.TaskCode is not null && current.ScopeVersion != Signature(profile, binding), incremental = HasAppendLog(profile) || HasTimeSource(profile), tasks = tasks.Select(task => new { task.TaskCode, task.TaskName, task.AutoEnabled, task.CronExpr }), }; } internal async Task SaveScheduleBindingAsync(RelationalTrialProfile profile, ConnectorBinding binding, string? taskCode, long actor, CancellationToken token) { using var store = MdpIngestDatabase.Open(db); store.Ado.CancellationToken = token; taskCode = string.IsNullOrWhiteSpace(taskCode) ? null : taskCode; var result = await store.Ado.UseTranAsync(async () => { if (taskCode is not null) { var task = (await EligibleTasksAsync(store, profile, binding.Identity.SourceCode, token)) .SingleOrDefault(t => string.Equals(t.TaskCode, taskCode, StringComparison.Ordinal)); if (task is null) throw new MdpIngestHttpException(409, "RELATIONAL_TASK_INELIGIBLE"); } var current = await BoundSchedule(store, profile, locked: true); var fields = new { profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId, profile.Id, taskCode, actor, scopeVersion = taskCode is null ? null : Signature(profile, binding), }; if (current is null) await store.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_connector_relational_schedule (tenant_id,factory_id,dataset_id,source_id,profile_id,task_code,scope_version,updated_by,updated_at_utc) VALUES (@TenantId,@FactoryId,@DatasetId,@SourceId,@Id,@taskCode,@scopeVersion,@actor,UTC_TIMESTAMP(6)) """, fields); else await store.Ado.ExecuteCommandAsync(""" UPDATE mdp_connector_relational_schedule SET task_code=@taskCode,scope_version=@scopeVersion,updated_by=@actor,updated_at_utc=UTC_TIMESTAMP(6) WHERE """ + " " + ProfileScope, fields); }); if (!result.IsSuccess) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(result.ErrorException!); } private static Task BoundSchedule(ISqlSugarClient store, RelationalTrialProfile profile, bool locked = false) => store.Ado.SqlQuerySingleAsync( """ SELECT task_code AS TaskCode, scope_version AS ScopeVersion FROM mdp_connector_relational_schedule WHERE """ + " " + ProfileScope + (locked ? " FOR UPDATE" : ""), ProfileKeys(profile)); private static object ProfileKeys(RelationalTrialProfile profile) => new { profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId, profile.Id }; private async Task> EligibleTasksAsync(ISqlSugarClient store, RelationalTrialProfile profile, string sourceCode, CancellationToken token) { var deploymentTasks = (await ReadProfiles(settings["MDP_RELATIONAL_TRIALS_FILE"], token)) .Where(p => p.TenantId == profile.TenantId && p.SyncEnabled && p.Id != profile.Id && p.ScheduleTaskCode is not null) .Select(p => p.ScheduleTaskCode!).ToHashSet(StringComparer.OrdinalIgnoreCase); var tasks = await store.Ado.SqlQueryAsync(""" SELECT t.task_code AS TaskCode,t.task_name AS TaskName,COALESCE(s.auto_enabled,0) AS AutoEnabled,s.cron_expr AS CronExpr FROM mdp_sync_task t LEFT JOIN mdp_sync_task_schedule s ON s.tenant_id=t.tenant_id AND s.task_code=t.task_code WHERE t.tenant_id=@TenantId AND t.status=1 AND t.task_type='DB_SYNC' AND t.source_system_code=@sourceCode AND NOT EXISTS (SELECT 1 FROM mdp_entity e WHERE e.status=1 AND e.tenant_id IN (0,t.tenant_id) AND (e.job_id=t.task_code OR e.job_id=t.job_code)) AND NOT EXISTS (SELECT 1 FROM mdp_connector_relational_schedule r WHERE r.tenant_id=t.tenant_id AND r.task_code=t.task_code AND (r.factory_id<>@FactoryId OR r.dataset_id<>@DatasetId OR r.source_id<>@SourceId OR r.profile_id<>@Id)) ORDER BY t.task_name,t.task_code """, new { profile.TenantId, profile.FactoryId, profile.DatasetId, profile.SourceId, profile.Id, sourceCode }); return tasks.Where(task => !deploymentTasks.Contains(task.TaskCode)).ToList(); } private sealed class RelationalScheduleBinding { public long FactoryId { get; set; } public long DatasetId { get; set; } public long SourceId { get; set; } public string ProfileId { get; set; } = ""; public string? TaskCode { get; set; } public string? ScopeVersion { get; set; } } private sealed class EligibleRelationalTask { public string TaskCode { get; set; } = ""; public string TaskName { get; set; } = ""; public int AutoEnabled { get; set; } public string? CronExpr { get; set; } } }