MdpDatasetReleaseController.cs 26 KB

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