MdpDatasetReleaseController.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. using Admin.NET.Core.Service;
  2. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  3. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  4. using Admin.NET.Plugin.ApprovalFlow;
  5. using Admin.NET.Plugin.ApprovalFlow.Service;
  6. using Microsoft.Extensions.Configuration;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using Microsoft.Extensions.Hosting;
  9. using System.Text.Json;
  10. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  11. public sealed record MdpCandidateInput(long SourceId, string Version, string MappingJson, int Revision);
  12. public sealed record MdpLifecycleInput(int Revision, string Reason);
  13. public sealed partial class MdpIngestDatasetController
  14. {
  15. private const string FlowType = "MDP_DATASET_RELEASE";
  16. private const string TrialPermission = "mdpRelease:trial";
  17. private const string PublishPermission = "mdpRelease:publish";
  18. private IConfiguration Settings => HttpContext.RequestServices.GetRequiredService<IConfiguration>();
  19. private string TargetEnvironment => Settings["MDP_RELEASE_ENVIRONMENT"] ?? HttpContext.RequestServices.GetRequiredService<IHostEnvironment>().EnvironmentName;
  20. private async Task<bool> Can(string permission) =>
  21. (await HttpContext.RequestServices.GetRequiredService<SysMenuService>().GetOwnBtnPermList()).Contains(permission);
  22. private sealed class Release
  23. {
  24. public long Id { get; set; }
  25. public long SourceId { get; set; }
  26. public string SourceCode { get; set; } = "";
  27. public string Version { get; set; } = "";
  28. public string MappingJson { get; set; } = "";
  29. public string State { get; set; } = "";
  30. public string EnvironmentKey { get; set; } = "";
  31. public int BaseRevision { get; set; }
  32. public string? TrialJson { get; set; }
  33. public long? FlowId { get; set; }
  34. }
  35. private sealed class ReleaseEvent
  36. {
  37. public string Action { get; set; } = "";
  38. public string Detail { get; set; } = "";
  39. public string Actor { get; set; } = "";
  40. public DateTime CreatedAt { get; set; }
  41. public string? ReleaseId { get; set; }
  42. }
  43. private const string ReleaseSelect = """
  44. SELECT id,source_id AS SourceId,source_code AS SourceCode,schema_version AS Version,mapping_json AS MappingJson,state,
  45. environment_key AS EnvironmentKey,base_revision AS BaseRevision,trial_json AS TrialJson,flow_id AS FlowId
  46. FROM mdp_ingest_release WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@id
  47. """;
  48. private sealed class HandoffEvidence
  49. {
  50. public long ReleaseId { get; set; }
  51. public string BatchId { get; set; } = "";
  52. public string FactoryId { get; set; } = "";
  53. public int Accepted { get; set; }
  54. public int Isolated { get; set; }
  55. public DateTime AcknowledgedAt { get; set; }
  56. }
  57. private async Task<Dictionary<long, HandoffEvidence>> HandoffEvidenceByRelease(long datasetId, long tenant)
  58. {
  59. var allowed = await AuthorizedFactories(tenant);
  60. var rows = await db.Ado.SqlQueryAsync<HandoffEvidence>("""
  61. SELECT ReleaseId,BatchId,FactoryId,Accepted,Isolated,AcknowledgedAt FROM (
  62. SELECT e.release_id AS ReleaseId,e.batch_id AS BatchId,CAST(e.factory_id AS CHAR) AS FactoryId,
  63. e.accepted_count AS Accepted,e.isolated_count AS Isolated,e.acknowledged_at AS AcknowledgedAt,
  64. ROW_NUMBER() OVER (PARTITION BY e.release_id ORDER BY (e.accepted_count>0) DESC,
  65. e.acknowledged_at,e.batch_id) AS receipt_rank
  66. FROM mdp_ingest_release_batch e
  67. JOIN JSON_TABLE(@visible,'$[*]' COLUMNS (factory BIGINT PATH '$')) f ON f.factory=e.factory_id
  68. WHERE e.tenant_id=@tenant AND e.dataset_id=@datasetId AND e.acknowledged_at IS NOT NULL
  69. ) evidence WHERE receipt_rank=1
  70. """, new { tenant, datasetId, visible = JsonSerializer.Serialize(allowed.Select(f => f.Id)) });
  71. return rows.ToDictionary(row => row.ReleaseId);
  72. }
  73. private Task<string> Lifecycle(long id) => db.Ado.SqlQuerySingleAsync<string>(
  74. "SELECT state FROM mdp_ingest_lifecycle WHERE dataset_id=@id", new { id });
  75. private Task Log(long id, long? release, string action, string detail) =>
  76. db.Ado.ExecuteCommandAsync("""
  77. INSERT INTO mdp_ingest_release_log(dataset_id,release_id,action,actor,detail,created_at)
  78. VALUES (@id,@release,@action,@actor,@detail,UTC_TIMESTAMP(6))
  79. """, new { id, release, action, actor = user.UserId, detail });
  80. [HttpGet("{id:long}/releases")]
  81. public Task<IActionResult> Releases(long id, [FromQuery] long? factoryId) => WithScope(factoryId, async scope =>
  82. {
  83. var dataset = await Datasets(scope).FirstAsync(x => x.Id == id);
  84. if (dataset is null) return NotFound();
  85. var releases = await db.Ado.SqlQueryAsync<Release>(ReleaseSelect + " ORDER BY id DESC",
  86. new { tenant = scope.TenantId, factory = scope.FactoryId, id });
  87. var lifecycle = await Lifecycle(id);
  88. var current = (await db.Ado.SqlQueryAsync<long>("""
  89. SELECT p.release_id FROM mdp_ingest_published_source p JOIN mdp_ingest_dataset d
  90. ON d.id=p.dataset_id AND d.tenant_id=p.tenant_id AND d.factory_id=p.factory_id
  91. LEFT JOIN mdp_ingest_source_package s ON s.dataset_id=p.dataset_id AND s.tenant_id=p.tenant_id
  92. AND s.factory_id=p.factory_id AND s.source_id=p.source_id
  93. WHERE d.id=@id AND d.tenant_id=@tenant AND d.factory_id=@factory
  94. AND p.schema_version=COALESCE(s.schema_version,d.active_schema_version)
  95. """, new { id, tenant=scope.TenantId, factory=scope.FactoryId })).ToHashSet();
  96. var evidence = await HandoffEvidenceByRelease(id, scope.TenantId);
  97. var history = new List<object>();
  98. foreach (var item in releases)
  99. {
  100. var approval = item.FlowId.HasValue ? await Approval(item) : null;
  101. var handoff = evidence.GetValueOrDefault(item.Id);
  102. var migrationRequired = item.State != "PUBLISHED" && await RequiresSchemaMigration(dataset, item);
  103. history.Add(new
  104. {
  105. id = item.Id.ToString(),
  106. sourceId = item.SourceId.ToString(),
  107. item.Version,
  108. item.MappingJson,
  109. item.State,
  110. isCurrent = current.Contains(item.Id),
  111. projectState = item.State switch
  112. {
  113. "PUBLISHED" when current.Contains(item.Id) && lifecycle is "PAUSED" or "RETIRED" => lifecycle,
  114. "PUBLISHED" => handoff?.Accepted > 0 ? "HANDED_OVER" : "AWAITING_HANDOFF",
  115. _ => item.State
  116. },
  117. handoff = handoff == null ? null : new { handoff.BatchId, handoff.FactoryId,
  118. handoff.Accepted, handoff.Isolated, handoff.AcknowledgedAt },
  119. item.EnvironmentKey,
  120. item.BaseRevision,
  121. item.TrialJson,
  122. schemaMigrationRequired = migrationRequired,
  123. schemaMigrationReady = migrationRequired && lifecycle == "PAUSED" && item.BaseRevision == dataset.Revision
  124. && await HasMigrationConfirmation(dataset, item),
  125. approval = approval?.Status.ToString(),
  126. flowId = item.FlowId?.ToString()
  127. });
  128. }
  129. var timeline = await db.Ado.SqlQueryAsync<ReleaseEvent>("""
  130. SELECT action,detail,CAST(actor AS CHAR) AS Actor,created_at AS CreatedAt,CAST(release_id AS CHAR) AS ReleaseId
  131. FROM mdp_ingest_release_log WHERE dataset_id=@id ORDER BY id DESC
  132. """, new { id });
  133. return Ok(new
  134. {
  135. history,
  136. timeline,
  137. environment = TargetEnvironment,
  138. lifecycle,
  139. canTrial = await Can(TrialPermission),
  140. canPublish = await Can(PublishPermission)
  141. });
  142. });
  143. private Task<ApprovalFlowInstance> Approval(Release row) =>
  144. db.Queryable<ApprovalFlowInstance>().ClearFilter().FirstAsync(f =>
  145. f.Id == row.FlowId && f.BizType == FlowType && f.BizId == row.Id);
  146. [HttpPost("{id:long}/releases")]
  147. public Task<IActionResult> Draft(long id, [FromQuery] long? factoryId, MdpCandidateInput input) =>
  148. Locked(id, factoryId, (dataset, scope) => SaveReleaseDraft(dataset, scope, input, "DRAFT", null));
  149. private async Task<IActionResult> SaveReleaseDraft(MdpIngestDataset dataset, DatasetScope scope,
  150. MdpCandidateInput input, string action, string? provenance)
  151. {
  152. var id = dataset.Id;
  153. Require(dataset.Revision == input.Revision, "配置已更新,请刷新");
  154. Require(await Lifecycle(id) != "RETIRED", "数据集已退役");
  155. var source = await BoundSource(dataset, input.SourceId);
  156. Require(source != null, "所选来源未授权或已停用");
  157. var config = new PurchaseVersionConfiguration(dataset.DatasetKey, input.Version, input.MappingJson);
  158. if (action == "DRAFT" && config.Package != null && !await Can(TrialPermission)) return Forbid();
  159. await ValidatePurchaseMasters(dataset, config);
  160. await CheckArchived(dataset, input.Version, config.MappingJson);
  161. if (action is "IMPORT" or "ROLLBACK")
  162. {
  163. var existing = await db.Ado.SqlQuerySingleAsync<long?>("""
  164. SELECT id FROM mdp_ingest_release WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@id
  165. AND source_id=@source AND schema_version=@version AND environment_key=@env AND base_revision=@revision
  166. AND state IN ('DRAFT','PREFLIGHT','RECONCILING','REVIEW') AND BINARY mapping_json=BINARY @json
  167. ORDER BY id DESC LIMIT 1
  168. """, new { tenant = scope.TenantId, factory = scope.FactoryId, id, source = input.SourceId,
  169. version = input.Version, env = TargetEnvironment, revision = input.Revision, json = config.MappingJson });
  170. if (existing.HasValue) return Ok(new { id = existing.Value.ToString() });
  171. }
  172. await db.Ado.ExecuteCommandAsync("""
  173. INSERT INTO mdp_ingest_release(tenant_id,factory_id,dataset_id,source_id,source_code,schema_version,environment_key,
  174. mapping_json,base_revision,state,created_by,created_at)
  175. VALUES (@tenant,@factory,@id,@source,@code,@version,@env,@json,@revision,'DRAFT',@actor,UTC_TIMESTAMP(6))
  176. """, new
  177. {
  178. tenant = scope.TenantId, factory = scope.FactoryId, id, source = input.SourceId, code = source!.SourceCode,
  179. version = input.Version, env = TargetEnvironment, json = config.MappingJson, revision = dataset.Revision, actor = user.UserId
  180. });
  181. var created = await db.Ado.GetLongAsync("SELECT LAST_INSERT_ID()");
  182. var stamp = config.Package is { } package ? $" {package.Digest}" : "";
  183. await Log(id, created, action, $"{input.Version}{stamp} {provenance}".TrimEnd());
  184. return Ok(new { id = created.ToString() });
  185. }
  186. [HttpPost("{id:long}/releases/{release:long}/{actionName}")]
  187. public Task<IActionResult> Transition(long id, long release, string actionName, [FromQuery] long? factoryId,
  188. [FromBody] MdpTrialInput? trial) => Locked(id, factoryId, async (dataset, scope) =>
  189. {
  190. Require(await Lifecycle(id) != "RETIRED", "数据集已退役");
  191. var row = await db.Ado.SqlQuerySingleAsync<Release>(ReleaseSelect + " AND id=@release FOR UPDATE",
  192. new { tenant = scope.TenantId, factory = scope.FactoryId, id, release });
  193. Require(row != null && row.EnvironmentKey == TargetEnvironment, "候选版本不属于当前环境");
  194. if (actionName == "publish" && row!.State == "PUBLISHED")
  195. return await Can(PublishPermission) ? NoContent() : Forbid();
  196. Require(row!.BaseRevision == dataset.Revision, "配置或绑定已变更,请基于当前修订创建新候选");
  197. var source = await BoundSource(dataset, row.SourceId);
  198. Require(source != null && source.SourceCode == row.SourceCode, "候选来源已停用、解绑或更名,请核对后重新创建候选");
  199. var config = new PurchaseVersionConfiguration(dataset.DatasetKey, row.Version, row.MappingJson);
  200. await CheckArchived(dataset, row.Version, config.MappingJson);
  201. string next;
  202. switch (actionName)
  203. {
  204. case "precheck":
  205. Require(row.State == "DRAFT", "只有草稿可以预检");
  206. await ValidatePurchaseMasters(dataset, config);
  207. await CheckConfiguredSourcePreflight(dataset, source!, row, HttpContext.RequestAborted);
  208. await CheckReceiver(dataset, source!, row);
  209. next = "PREFLIGHT";
  210. break;
  211. case "trial":
  212. if (!await Can(TrialPermission)) return Forbid();
  213. Require(row.State is "PREFLIGHT" or "RECONCILING" && trial != null, "请先预检并提供试跑样本");
  214. var result = await MdpDatasetSandbox.Run(Settings, new(scope.TenantId, scope.FactoryId, row.SourceId, id,
  215. source!.SourceCode, dataset.DatasetKey), row.Version, config, trial!, HttpContext.RequestAborted);
  216. var proofEvidence = result.Evidence with { ConfigDigest = config.Package?.Digest };
  217. var json = JsonSerializer.Serialize(proofEvidence, JsonSerializerOptions.Web);
  218. await db.Ado.ExecuteCommandAsync("""
  219. INSERT INTO mdp_ingest_release_trial(batch_id,release_id,payload,evidence_json,manifest_json,actor,created_at)
  220. VALUES (@batch,@release,@payload,@json,@manifest,@actor,UTC_TIMESTAMP(6))
  221. """, new
  222. {
  223. batch = result.Evidence.BatchId.ToString("D"),
  224. release,
  225. payload = result.Prepared.Batch.Payload.ToArray(),
  226. json,
  227. manifest = JsonSerializer.Serialize(new
  228. {
  229. result.Prepared.Batch.Versions,
  230. result.Prepared.Events,
  231. trial!.ExpectedValid,
  232. trial.ExpectedIsolated,
  233. trial.ExpectedQuantity
  234. }, JsonSerializerOptions.Web),
  235. actor = user.UserId
  236. });
  237. await db.Ado.ExecuteCommandAsync("UPDATE mdp_ingest_release SET trial_json=@evidence WHERE id=@release",
  238. new { evidence = json, release });
  239. next = "RECONCILING";
  240. break;
  241. case "submit":
  242. if (!await Can(TrialPermission)) return Forbid();
  243. Require(row.State == "RECONCILING" && row.TrialJson != null, "请先试跑对账");
  244. var proof = JsonSerializer.Deserialize<MdpTrialEvidence>(row.TrialJson!, JsonSerializerOptions.Web);
  245. Require(proof?.Matched == true && (config.Package == null || proof.ConfigDigest == config.Package.Digest),
  246. "试跑差额尚未核对通过或配置包摘要已经变化");
  247. var defined = await db.Queryable<Admin.NET.Plugin.ApprovalFlow.ApprovalFlow>().ClearFilter()
  248. .AnyAsync(f => f.BizType == FlowType && f.IsPublished && !f.IsDelete &&
  249. (f.TenantId == scope.TenantId || f.TenantId == null));
  250. Require(defined, "请先在审批流程设计器中发布“接收数据集版本发布”的人工审批流程");
  251. var flow = HttpContext.RequestServices.GetRequiredService<FlowEngineService>();
  252. var flowId = await flow.StartFlow(new StartFlowInput
  253. {
  254. BizType = FlowType,
  255. BizId = row.Id,
  256. BizNo = $"MDP-{row.Id}/{row.Version}",
  257. Title = $"{scope.FactoryName} · {dataset.Name} · {row.Version}",
  258. Comment = $"{TargetEnvironment},批次 {proof!.BatchId},有效 {proof.Valid},隔离 {proof.Isolated},数量 {proof.StandardQuantity}。来源 {source!.SourceCode},配置修订 {row.BaseRevision},映射版本 {config.Find(dataset.DatasetKey, row.Version)!.MappingVersion}"
  259. }, scope.TenantId);
  260. await db.Ado.ExecuteCommandAsync("UPDATE mdp_ingest_release SET flow_id=@flowId WHERE id=@release", new { flowId, release });
  261. next = "REVIEW";
  262. break;
  263. case "publish":
  264. if (!await Can(PublishPermission)) return Forbid();
  265. Require(row.State == "REVIEW" && row.FlowId.HasValue, "请先提交审批");
  266. if (config.Package is { } candidatePackage)
  267. Require(row.TrialJson != null && JsonSerializer.Deserialize<MdpTrialEvidence>(row.TrialJson, JsonSerializerOptions.Web)
  268. is { Matched: true } proofForPublish && proofForPublish.ConfigDigest == candidatePackage.Digest,
  269. "已审批试跑记录与候选配置包不一致");
  270. var approved = await Approval(row);
  271. Require(approved?.Status == FlowInstanceStatusEnum.Approved &&
  272. await HasFactoryApproval(approved.Id, scope), "尚未取得人工审批通过记录");
  273. await ValidatePurchaseMasters(dataset, config);
  274. await CheckConfiguredSourcePreflight(dataset, source!, row, HttpContext.RequestAborted);
  275. await CheckReceiver(dataset, source!, row);
  276. await EnsureSchemaMigrationReady(dataset, row);
  277. var rollback = await db.Ado.GetIntAsync("""
  278. SELECT COUNT(*) FROM mdp_ingest_release_log WHERE dataset_id=@id AND release_id=@release AND action='ROLLBACK'
  279. """, new { id, release }) > 0;
  280. await Publish(dataset, row, config.Package != null || rollback);
  281. next = "PUBLISHED";
  282. break;
  283. default: return BadRequest(new { message = "未知版本操作" });
  284. }
  285. await db.Ado.ExecuteCommandAsync("UPDATE mdp_ingest_release SET state=@next WHERE id=@release", new { next, release });
  286. await Log(id, release, actionName, config.Package is { } package ? $"{row.Version} {package.Digest}" : row.Version);
  287. return NoContent();
  288. });
  289. private async Task CheckReceiver(MdpIngestDataset dataset, MdpSource source, Release candidate)
  290. {
  291. // Read through the receiver's own connection so a stale deployment, wrong database or missing view grant blocks publication.
  292. var receiverConnection = Settings["MDP_PURCHASE_RECEIVER_MYSQL"];
  293. Require(!string.IsNullOrWhiteSpace(receiverConnection), "请先配置采购接收库连接");
  294. using var receiver = new SqlSugarClient(new ConnectionConfig
  295. {
  296. DbType = SqlSugar.DbType.MySql,
  297. ConnectionString = receiverConnection,
  298. IsAutoCloseConnection = true
  299. });
  300. try
  301. {
  302. var visible = await receiver.Ado.GetIntAsync("""
  303. SELECT COUNT(*) FROM mdp_purchase_release_probe p LEFT JOIN mdp_purchase_contract_version a
  304. ON a.dataset_id=p.dataset_id AND a.tenant_id=p.tenant_id AND a.factory_id=p.factory_id AND a.schema_version=p.schema_version
  305. WHERE p.id=@Id AND p.tenant_id=@TenantId AND p.factory_id=@FactoryId AND p.dataset_id=@datasetId
  306. AND p.source_id=@SourceId AND p.environment_key=@EnvironmentKey AND p.schema_version=@Version
  307. AND p.mapping_hash=SHA2(@MappingJson,256) AND (a.dataset_id IS NULL OR SHA2(a.mapping_json,256)=p.mapping_hash)
  308. """, new
  309. {
  310. candidate.Id,
  311. dataset.TenantId,
  312. dataset.FactoryId,
  313. datasetId = dataset.Id,
  314. candidate.SourceId,
  315. candidate.EnvironmentKey,
  316. candidate.Version,
  317. candidate.MappingJson
  318. });
  319. Require(visible == 1, "采购接收库尚未识别此环境的候选配置");
  320. }
  321. catch (Exception e) when (e is System.Data.Common.DbException or SqlSugarException)
  322. {
  323. throw new DatasetChangeException("采购接收库无法读取版本视图,请核对连接、迁移和读取权限");
  324. }
  325. var migration = await MdpPurchaseMigrationStore.LockNewAsync(db, dataset.TenantId, dataset.FactoryId, dataset.Id, source.Id);
  326. if (migration != null)
  327. {
  328. Require(!migration.Frozen && migration.PrimaryWriter == MdpPurchaseMigrationStore.Unified &&
  329. migration.NewSourceCode == source.SourceCode, "采购迁移范围尚未授权统一入口写入");
  330. return;
  331. }
  332. var authorized = await new MdpTenantStdSourceResolver(db).GetSourceForShareAsync(dataset.TenantId, "PURCHASE");
  333. Require(string.Equals(authorized?.SourceSystem, source.SourceCode, StringComparison.OrdinalIgnoreCase), "此来源尚未取得采购标准层写入权");
  334. }
  335. private async Task<bool> HasFactoryApproval(long flowId, DatasetScope scope)
  336. {
  337. var decision = await db.Queryable<ApprovalFlowLog>().ClearFilter()
  338. .Where(x => x.InstanceId == flowId && x.Action == FlowLogActionEnum.Approve && x.OperatorId > 0)
  339. .OrderByDescending(x => x.Id).FirstAsync();
  340. if (decision == null || await db.Queryable<ApprovalFlowLog>().ClearFilter()
  341. .AnyAsync(x => x.InstanceId == flowId && x.Action == FlowLogActionEnum.AutoTimeout)) return false;
  342. var approver = await db.Queryable<SysUser>().ClearFilter().Where(x =>
  343. x.Id == decision.OperatorId && x.TenantId == scope.TenantId && x.Status == StatusEnum.Enable)
  344. .Select(x => new { x.Id, x.OrgId }).FirstAsync();
  345. return approver != null && (await organizations.GetUserOrgIdList(approver.Id, approver.OrgId)).Contains(scope.FactoryId);
  346. }
  347. private async Task Publish(MdpIngestDataset dataset, Release row, bool governed)
  348. {
  349. var id = dataset.Id;
  350. var args = new
  351. {
  352. tenant = dataset.TenantId,
  353. factory = dataset.FactoryId,
  354. id,
  355. version = row.Version,
  356. json = row.MappingJson,
  357. source = row.SourceId,
  358. release = row.Id,
  359. actor = user.UserId, governed
  360. };
  361. await db.Ado.ExecuteCommandAsync("""
  362. INSERT INTO mdp_ingest_contract_archive(tenant_id,factory_id,dataset_id,schema_version,mapping_json,release_id)
  363. VALUES (@tenant,@factory,@id,@version,@json,@release) ON DUPLICATE KEY UPDATE release_id=release_id
  364. """, args);
  365. await db.Ado.ExecuteCommandAsync("""
  366. INSERT INTO mdp_ingest_published_source(tenant_id,factory_id,dataset_id,schema_version,source_id,release_id)
  367. VALUES (@tenant,@factory,@id,@version,@source,@release) ON DUPLICATE KEY UPDATE release_id=VALUES(release_id)
  368. """, args);
  369. await db.Ado.ExecuteCommandAsync("""
  370. INSERT INTO mdp_ingest_dataset_version(tenant_id,factory_id,dataset_id,schema_version,registered_by,registered_at)
  371. VALUES (@tenant,@factory,@id,@version,@actor,UTC_TIMESTAMP(6)) ON DUPLICATE KEY UPDATE id=id
  372. """, args);
  373. if (governed)
  374. await db.Ado.ExecuteCommandAsync("""
  375. INSERT INTO mdp_ingest_source_package(tenant_id,factory_id,dataset_id,source_id,schema_version)
  376. VALUES (@tenant,@factory,@id,@source,@version) ON DUPLICATE KEY UPDATE schema_version=VALUES(schema_version)
  377. """, args);
  378. else
  379. {
  380. await EnsureLegacySwitchPreservesSources(dataset, row);
  381. await db.Ado.ExecuteCommandAsync("""
  382. DELETE FROM mdp_ingest_source_package WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@id AND source_id=@source
  383. """, args);
  384. }
  385. await db.Ado.ExecuteCommandAsync("""
  386. UPDATE mdp_ingest_dataset SET enabled=1,
  387. active_schema_version=IF(@governed=1,COALESCE(active_schema_version,@version),@version),revision=revision+1,
  388. updated_by=@actor,updated_at=UTC_TIMESTAMP(6) WHERE id=@id
  389. """, args);
  390. await db.Ado.ExecuteCommandAsync("UPDATE mdp_ingest_release SET published_by=@actor,published_at=UTC_TIMESTAMP(6) WHERE id=@release", args);
  391. await SetLifecycle(id, "ACTIVE", "批准版本 " + row.Version, dataset.Revision + 1);
  392. }
  393. private async Task CheckArchived(MdpIngestDataset dataset, string version, string mapping)
  394. {
  395. var archived = await db.Ado.SqlQuerySingleAsync<string>("""
  396. SELECT mapping_json FROM mdp_ingest_contract_archive WHERE tenant_id=@TenantId AND factory_id=@FactoryId
  397. AND dataset_id=@Id AND schema_version=@version
  398. """, new { dataset.TenantId, dataset.FactoryId, dataset.Id, version });
  399. Require(archived == null || archived == mapping, "版本号已归档,请使用新版本号");
  400. }
  401. private Task<MdpSource> BoundSource(MdpIngestDataset ds, long source) =>
  402. db.Queryable<MdpSource>().Where(s => s.Id == source && s.TenantId == ds.TenantId && s.Status == 1 &&
  403. SqlFunc.Subqueryable<MdpIngestDatasetSource>().Where(b => b.SourceId == s.Id && b.DatasetId == ds.Id &&
  404. b.FactoryId == ds.FactoryId && b.TenantId == ds.TenantId && b.Enabled).Any()).FirstAsync();
  405. private Task SetLifecycle(long id, string state, string reason, int revision) => db.Ado.ExecuteCommandAsync("""
  406. INSERT INTO mdp_ingest_lifecycle(dataset_id,state,reason,revision,updated_by,updated_at) VALUES (@id,@state,@reason,@revision,@actor,UTC_TIMESTAMP(6))
  407. ON DUPLICATE KEY UPDATE state=VALUES(state),reason=VALUES(reason),revision=VALUES(revision),updated_by=VALUES(updated_by),updated_at=VALUES(updated_at)
  408. """, new { id, state, reason, revision, actor = user.UserId });
  409. [HttpPost("{id:long}/lifecycle/{operation}")]
  410. public Task<IActionResult> LifecycleAction(long id, string operation, [FromQuery] long? factoryId, MdpLifecycleInput input) =>
  411. Locked(id, factoryId, async (dataset, _) =>
  412. {
  413. if (!await Can(PublishPermission)) return Forbid();
  414. Require(input.Revision == dataset.Revision && !string.IsNullOrWhiteSpace(input.Reason) && input.Reason.Length <= 500,
  415. "请刷新修订号并填写操作原因");
  416. var state = await Lifecycle(id);
  417. Require(state != "RETIRED", "数据集已退役");
  418. if (operation == "retire")
  419. {
  420. Require(state == "PAUSED", "须先暂停接收");
  421. var outstanding = await db.Ado.SqlQuerySingleAsync<long>("""
  422. SELECT COUNT(*) FROM mdp_ingest_receive_task WHERE dataset_id=@id
  423. AND status NOT IN ('SUCCEEDED','PARTIAL','QUARANTINED')
  424. """, new { id });
  425. Require(outstanding == 0, "存在在途或待处置批次");
  426. }
  427. else if (operation == "resume")
  428. {
  429. Require(state == "PAUSED" && dataset.ActiveSchemaVersion != null, "只有已暂停的数据集可以恢复");
  430. var pausedAt = await db.Ado.GetIntAsync("SELECT revision FROM mdp_ingest_lifecycle WHERE dataset_id=@id", new { id });
  431. Require(pausedAt == dataset.Revision, "暂停后配置已修改,请重新走候选版本审批");
  432. }
  433. else Require(operation == "pause" && state != "PAUSED" && dataset.Enabled, "只有已启用的数据集可以暂停");
  434. await SetLifecycle(id, operation switch { "pause" => "PAUSED", "resume" => "ACTIVE", _ => "RETIRED" }, input.Reason, dataset.Revision + 1);
  435. await db.Ado.ExecuteCommandAsync("""
  436. UPDATE mdp_ingest_dataset SET enabled=@processing,revision=revision+1,updated_by=@actor,updated_at=UTC_TIMESTAMP(6) WHERE id=@id
  437. """, new { id, processing = operation == "retire" ? 0 : 1, actor = user.UserId });
  438. await Log(id, null, operation, input.Reason);
  439. return NoContent();
  440. });
  441. private Task<IActionResult> Locked(long id, long? factoryId, Func<MdpIngestDataset, DatasetScope, Task<IActionResult>> work) =>
  442. WithScope(factoryId, async scope =>
  443. {
  444. var tx = await db.Ado.UseTranAsync(async () =>
  445. {
  446. var locked = await db.Ado.SqlQuerySingleAsync<long?>("""
  447. SELECT id FROM mdp_ingest_dataset WHERE id=@id AND tenant_id=@tenant AND factory_id=@factory FOR UPDATE
  448. """, new { id, tenant = scope.TenantId, factory = scope.FactoryId });
  449. if (locked == null) return (IActionResult)NotFound();
  450. return await work(await Datasets(scope).FirstAsync(x => x.Id == id), scope);
  451. });
  452. if (tx.IsSuccess) return tx.Data;
  453. return tx.ErrorException switch
  454. {
  455. DatasetChangeException e => Conflict(new { message = e.Message }),
  456. ArgumentException e => BadRequest(new { message = e.Message }),
  457. JsonException => BadRequest(new { message = "请输入有效 JSON" }),
  458. IngestContractException e => BadRequest(new { message = e.Code.ToString() }),
  459. _ => throw tx.ErrorException ?? new InvalidOperationException("版本操作失败")
  460. };
  461. });
  462. private static void Require(bool condition, string message)
  463. {
  464. if (!condition) throw new DatasetChangeException(message);
  465. }
  466. }