AdoS8ConfigWatchRulesController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. using Admin.NET.Plugin.AiDOP.Infrastructure.S8;
  2. using Admin.NET.Plugin.AiDOP.Const.S8;
  3. using System.Security.Claims;
  4. using Admin.NET.Plugin.AiDOP.Entity.S8;
  5. using Admin.NET.Plugin.AiDOP.Infrastructure;
  6. using Admin.NET.Plugin.AiDOP.Service.S8;
  7. using Admin.NET.Plugin.AiDOP.Service.S8.Rules;
  8. using Microsoft.Extensions.Logging;
  9. namespace Admin.NET.Plugin.AiDOP.Controllers.S8;
  10. [ApiController]
  11. [Route("api/aidop/s8/config/watch-rules")]
  12. [NonUnify]
  13. public class AdoS8ConfigWatchRulesController : ControllerBase
  14. {
  15. private const string LegacyHeaderUseInstead = "PUT /api/aidop/s8/config/watch-rules/{id}/params";
  16. private readonly S8WatchRuleService _svc;
  17. private readonly ILogger<AdoS8ConfigWatchRulesController> _logger;
  18. private readonly S8TrustedScopeResolver _scope;
  19. public AdoS8ConfigWatchRulesController(
  20. S8WatchRuleService svc,
  21. ILogger<AdoS8ConfigWatchRulesController> logger,
  22. S8TrustedScopeResolver scope)
  23. {
  24. _svc = svc;
  25. _logger = logger;
  26. _scope = scope;
  27. }
  28. [HttpGet]
  29. [S8Permission(S8PermissionCatalog.ConfigRead)]
  30. public async Task<IActionResult> ListAsync([FromQuery] long tenantId = 1, [FromQuery] long factoryId = 1)
  31. {
  32. // Compatibility-only. Security scope is resolved server-side.
  33. _ = tenantId; _ = factoryId;
  34. var scope = await _scope.ResolveAsync();
  35. return Ok(await _svc.ListAsync(scope.TenantId, scope.FactoryId));
  36. }
  37. /// <summary>
  38. /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params.
  39. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。
  40. /// </summary>
  41. [Obsolete("Legacy full-create endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params for safe params editing.")]
  42. [HttpPost]
  43. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  44. public async Task<IActionResult> CreateAsync([FromBody] AdoS8WatchRule body)
  45. {
  46. MarkLegacyDeprecated("POST /api/aidop/s8/config/watch-rules");
  47. try { return Ok(await _svc.CreateAsync(body, await _scope.ResolveAsync())); }
  48. catch (S8NotFoundException) { return NotFound(); }
  49. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  50. }
  51. /// <summary>
  52. /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params.
  53. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。
  54. /// </summary>
  55. // ================================================================================
  56. // S8-STEP6E-CFG-WATCH-FIX-AND-SAFE-CERT-1:本入口已退役 → 410 Gone。
  57. //
  58. // 它是整实体更新,会连带把 13 个 scheduler-owned 运行时列暴露给客户端
  59. //(lock_token / lock_until / paused_until / next_run_at / last_* / consecutive_failure_count),
  60. // 足以窃取租约、制造重复执行、静默停掉监控、伪造调度审计。详见 S8WatchRuleService.UpdateAsync 注释。
  61. //
  62. // 选 410 而非 400/404:语义是「该能力曾经存在、现已永久退役」。
  63. // 400 会暗示「改对入参还能存」,404 会暗示「换个 Id 还能存」,都与事实不符。
  64. //
  65. // ⚠️ 不再调用 _scope.ResolveAsync():写能力已退役,不该为构造一个用不到的 scope 去读组织库;
  66. // 这同时保证 DB access = 0,并让工厂组织 0 个/多个的租户也稳定得到 410 而非作用域错误。
  67. // ⚠️ catch 顺序:S8WriteRetiredException 必须排在 S8NotFoundException / S8BizException 之前。
  68. // GET 与 /params /schedule /run-now /pause /resume 全部不受影响。
  69. // ================================================================================
  70. [Obsolete("Retired full-update endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params or /schedule.")]
  71. [HttpPut("{id:long}")]
  72. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  73. public async Task<IActionResult> UpdateAsync(long id, [FromBody] AdoS8WatchRule body)
  74. {
  75. MarkLegacyDeprecated($"PUT /api/aidop/s8/config/watch-rules/{id}", id);
  76. try { return Ok(await _svc.UpdateAsync(id, body, RetiredWriteScope)); }
  77. catch (S8WriteRetiredException ex)
  78. {
  79. return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status410Gone, new { message = ex.Message });
  80. }
  81. catch (S8NotFoundException) { return NotFound(); }
  82. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  83. }
  84. /// <summary>
  85. /// 写能力已永久退役:不得为了构造一个不会被使用的 scope 而读取组织库。
  86. /// Service 写方法必须在读取该占位值或访问任何仓储前抛 S8WriteRetiredException。
  87. /// (与 CFG_ALERT 的 RetiredWriteScope 同一模式。)
  88. /// </summary>
  89. private static readonly S8TrustedScope RetiredWriteScope = new(0, 0);
  90. /// <summary>
  91. /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params.
  92. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。
  93. /// </summary>
  94. [Obsolete("Legacy delete endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params for safe params editing.")]
  95. [HttpDelete("{id:long}")]
  96. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  97. public async Task<IActionResult> DeleteAsync(long id)
  98. {
  99. MarkLegacyDeprecated($"DELETE /api/aidop/s8/config/watch-rules/{id}", id);
  100. try { await _svc.DeleteAsync(id, await _scope.ResolveAsync()); }
  101. catch (S8NotFoundException) { return NotFound(); }
  102. return Ok();
  103. }
  104. /// <summary>
  105. /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params.
  106. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。
  107. /// </summary>
  108. [Obsolete("Legacy test endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params for safe params editing.")]
  109. [HttpPost("{id:long}/test")]
  110. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  111. public async Task<IActionResult> TestAsync(long id)
  112. {
  113. MarkLegacyDeprecated($"POST /api/aidop/s8/config/watch-rules/{id}/test", id);
  114. try { return Ok(await _svc.TestAsync(id, await _scope.ResolveAsync())); }
  115. catch (S8NotFoundException) { return NotFound(); }
  116. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  117. }
  118. /// <summary>
  119. /// S8-RULE01-INTEGRATION-PREVIEW-1:只读预演 —— 「这条规则现在启用会命中什么」。
  120. ///
  121. /// 在此之前想回答这个问题只能真把规则 enabled=true 然后等调度器跑,
  122. /// 对 Rule 01 而言那意味着一次性生成 28 条真实异常单,而验证只需要 1 条。
  123. /// 本端点补上这个中间档位:走**与生产完全相同**的 Gateway → Provider → Evaluator 链,
  124. /// 但不写 detection_log / exception / rule_detection_state,不改规则任何列,不发通知。
  125. ///
  126. /// 用 GET 而非 POST 是刻意的:它是一次查询,没有副作用,
  127. /// 用 POST 会让调用方以为「点了就会发生什么」。
  128. ///
  129. /// 权限沿用 ConfigWatchRule(能配规则的人才能预演),作用域由服务端盖章。
  130. /// </summary>
  131. [HttpGet("{id:long}/preview")]
  132. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  133. public async Task<IActionResult> PreviewAsync(long id, [FromServices] S8WatchRulePreviewService preview)
  134. {
  135. try { return Ok(await preview.PreviewAsync(id, await _scope.ResolveAsync())); }
  136. catch (S8NotFoundException) { return NotFound(); }
  137. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  138. catch (S8RuleEvaluatorException ex) { return BadRequest(new { reason = ex.Reason, message = ex.Message }); }
  139. }
  140. /// <summary>
  141. /// S8-RULE-GOVERNANCE-BATCH1:运行参数的**部分更新**。
  142. ///
  143. /// <para>只接受该规则的代码定义所声明的运行参数白名单
  144. /// (轮询间隔 / 抗抖次数 / 宽限分钟 / 严重度 / 部门兜底),未提供的字段保持原值。</para>
  145. ///
  146. /// <para><b>不再接受</b> params_json 原文与任何判定语义字段 —— 那些由代码定义,
  147. /// 出现在载荷里会得到 400 而不是被静默忽略。<b>也不再接受 enabled</b>,
  148. /// 启停请用 <c>/enable</c> 与 <c>/disable</c>。</para>
  149. ///
  150. /// <para>路由暂时保留 <c>/params</c> 以免与前端一次性大改耦合;
  151. /// 前端适配排在 Batch 4。</para>
  152. /// </summary>
  153. [HttpPut("{id:long}/params")]
  154. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  155. public async Task<IActionResult> UpdateParamsAsync(long id, [FromBody] S8RuleParametersPayload body)
  156. {
  157. try { return Ok(await _svc.UpdateParametersAsync(id, body, await _scope.ResolveAsync())); }
  158. catch (S8NotFoundException) { return NotFound(); }
  159. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  160. }
  161. /// <summary>
  162. /// 启用规则。<b>与参数写入完全分离</b>:本端点只写 enabled 与下次执行时间,
  163. /// 不触碰 params_json、不触碰任何参数列、不触碰定义投影列。
  164. ///
  165. /// <para>这条分离是 G1 的结构性修复:此前启停与 params_json 共用一个写入口,
  166. /// 一次「只想关个开关」的调用就会把规则的全部业务配置抹成 NULL。</para>
  167. ///
  168. /// <para>幂等:重复启用不产生写入。</para>
  169. /// </summary>
  170. [HttpPost("{id:long}/enable")]
  171. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  172. public async Task<IActionResult> EnableAsync(long id)
  173. {
  174. try { return Ok(await _svc.EnableAsync(id, await _scope.ResolveAsync())); }
  175. catch (S8NotFoundException) { return NotFound(); }
  176. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  177. }
  178. /// <summary>
  179. /// 停用规则。只写 enabled;幂等。
  180. /// <b>刻意不过 Enable Gate</b>:数据集出问题之后仍然必须能把规则关掉。
  181. /// </summary>
  182. [HttpPost("{id:long}/disable")]
  183. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  184. public async Task<IActionResult> DisableAsync(long id)
  185. {
  186. try { return Ok(await _svc.DisableAsync(id, await _scope.ResolveAsync())); }
  187. catch (S8NotFoundException) { return NotFound(); }
  188. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  189. }
  190. /// <summary>
  191. /// S8-SCHED-FRONTEND-1:调度参数安全更新(仅 poll_interval_seconds / trigger_count_required / recover_count_required)。
  192. /// S8-RULE-GOVERNANCE-BATCH1:已委托到统一的参数写入路径,语义与 <c>/params</c> 一致。
  193. /// </summary>
  194. [HttpPut("{id:long}/schedule")]
  195. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  196. public async Task<IActionResult> UpdateScheduleAsync(long id, [FromBody] S8WatchRuleSchedulePayload body)
  197. {
  198. try { return Ok(await _svc.UpdateScheduleAsync(id, body, await _scope.ResolveAsync())); }
  199. catch (S8NotFoundException) { return NotFound(); }
  200. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  201. }
  202. /// <summary>S8-SCHED-FRONTEND-1:立即执行一次,next_run_at 置为 NOW,由下一 tick 拾取。</summary>
  203. [HttpPost("{id:long}/run-now")]
  204. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  205. public async Task<IActionResult> RunNowAsync(long id)
  206. {
  207. try { return Ok(await _svc.RunNowAsync(id, await _scope.ResolveAsync())); }
  208. catch (S8NotFoundException) { return NotFound(); }
  209. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  210. }
  211. /// <summary>S8-SCHED-FRONTEND-1:手工暂停,paused_until 置为远未来哨兵 + pause_reason=MANUAL_PAUSED。</summary>
  212. [HttpPost("{id:long}/pause")]
  213. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  214. public async Task<IActionResult> PauseAsync(long id)
  215. {
  216. try { return Ok(await _svc.PauseAsync(id, await _scope.ResolveAsync())); }
  217. catch (S8NotFoundException) { return NotFound(); }
  218. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  219. }
  220. /// <summary>S8-SCHED-FRONTEND-1:恢复,清 paused_until / pause_reason / last_error / consecutive_failure_count,next_run_at = NOW。</summary>
  221. [HttpPost("{id:long}/resume")]
  222. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  223. public async Task<IActionResult> ResumeAsync(long id)
  224. {
  225. try { return Ok(await _svc.ResumeAsync(id, await _scope.ResolveAsync())); }
  226. catch (S8NotFoundException) { return NotFound(); }
  227. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  228. }
  229. /// <summary>
  230. /// 旧端点 deprecated 收口:写入响应 header 标记 + 结构化 warning 日志,便于运行期识别 legacy 调用。
  231. /// 不阻断调用,不改返回结构。
  232. /// </summary>
  233. private void MarkLegacyDeprecated(string endpoint, long? ruleId = null)
  234. {
  235. // 响应 header — Headers 在响应已开始发送后会抛 InvalidOperationException,此处守卫一下避免污染主调用。
  236. var headers = Response.Headers;
  237. if (!headers.ContainsKey("X-AiDOP-Deprecated"))
  238. headers["X-AiDOP-Deprecated"] = "true";
  239. if (!headers.ContainsKey("X-AiDOP-Use-Instead"))
  240. headers["X-AiDOP-Use-Instead"] = LegacyHeaderUseInstead;
  241. var userId = User?.FindFirst("UserId")?.Value
  242. ?? User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
  243. var tenantId = HttpContext?.Request?.Query["tenantId"].ToString();
  244. var factoryId = HttpContext?.Request?.Query["factoryId"].ToString();
  245. _logger.LogWarning(
  246. "legacy_watch_rule_endpoint endpoint={Endpoint} ruleId={RuleId} userId={UserId} tenantId={TenantId} factoryId={FactoryId} useInstead={UseInstead}",
  247. endpoint, ruleId, userId, tenantId, factoryId, LegacyHeaderUseInstead);
  248. }
  249. }