AdoS8ConfigWatchRulesController.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. // ================================================================================
  38. // S8-RULE-GOVERNANCE-BATCH3:业务侧建规则入口已退役 → 410 Gone。
  39. //
  40. // 选 410 墓碑而非直接删掉 route:直接删会让遗留调用方拿到 405(该路径上还有 GET),
  41. // 而 405 说的是"方法不对",会让人以为换个动词就能建。410 才准确表达
  42. // 「这个能力曾经存在、现已永久退役」,并能把替代路径写进文案。
  43. //
  44. // ⚠️ 不再调用 _scope.ResolveAsync():能力已退役,不该为构造一个用不到的 scope 去读组织库。
  45. // 这保证 DB access = 0,并让工厂组织 0 个/多个的租户也稳定得到 410 而非作用域错误。
  46. // ⚠️ catch 顺序:S8WriteRetiredException 必须排在 S8BizException 之前,否则被基类吞成 400。
  47. // ================================================================================
  48. [Obsolete("Retired. Rules are defined in code (S8RuleCatalog) and provisioned per tenant.")]
  49. [HttpPost]
  50. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  51. public IActionResult CreateAsync([FromBody] AdoS8WatchRule body)
  52. {
  53. MarkLegacyDeprecated("POST /api/aidop/s8/config/watch-rules");
  54. _ = body;
  55. try { _ = _svc.CreateAsync(body, RetiredWriteScope); return Ok(); }
  56. catch (S8WriteRetiredException ex)
  57. {
  58. return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status410Gone, new { message = ex.Message });
  59. }
  60. }
  61. /// <summary>
  62. /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params.
  63. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。
  64. /// </summary>
  65. // ================================================================================
  66. // S8-STEP6E-CFG-WATCH-FIX-AND-SAFE-CERT-1:本入口已退役 → 410 Gone。
  67. //
  68. // 它是整实体更新,会连带把 13 个 scheduler-owned 运行时列暴露给客户端
  69. //(lock_token / lock_until / paused_until / next_run_at / last_* / consecutive_failure_count),
  70. // 足以窃取租约、制造重复执行、静默停掉监控、伪造调度审计。详见 S8WatchRuleService.UpdateAsync 注释。
  71. //
  72. // 选 410 而非 400/404:语义是「该能力曾经存在、现已永久退役」。
  73. // 400 会暗示「改对入参还能存」,404 会暗示「换个 Id 还能存」,都与事实不符。
  74. //
  75. // ⚠️ 不再调用 _scope.ResolveAsync():写能力已退役,不该为构造一个用不到的 scope 去读组织库;
  76. // 这同时保证 DB access = 0,并让工厂组织 0 个/多个的租户也稳定得到 410 而非作用域错误。
  77. // ⚠️ catch 顺序:S8WriteRetiredException 必须排在 S8NotFoundException / S8BizException 之前。
  78. // GET 与 /params /schedule /run-now /pause /resume 全部不受影响。
  79. // ================================================================================
  80. [Obsolete("Retired full-update endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params or /schedule.")]
  81. [HttpPut("{id:long}")]
  82. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  83. public async Task<IActionResult> UpdateAsync(long id, [FromBody] AdoS8WatchRule body)
  84. {
  85. MarkLegacyDeprecated($"PUT /api/aidop/s8/config/watch-rules/{id}", id);
  86. try { return Ok(await _svc.UpdateAsync(id, body, RetiredWriteScope)); }
  87. catch (S8WriteRetiredException ex)
  88. {
  89. return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status410Gone, new { message = ex.Message });
  90. }
  91. catch (S8NotFoundException) { return NotFound(); }
  92. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  93. }
  94. /// <summary>
  95. /// 写能力已永久退役:不得为了构造一个不会被使用的 scope 而读取组织库。
  96. /// Service 写方法必须在读取该占位值或访问任何仓储前抛 S8WriteRetiredException。
  97. /// (与 CFG_ALERT 的 RetiredWriteScope 同一模式。)
  98. /// </summary>
  99. private static readonly S8TrustedScope RetiredWriteScope = new(0, 0);
  100. /// <summary>
  101. /// S8-RULE-GOVERNANCE-BATCH3:业务侧删规则入口已退役 → 410 Gone。
  102. /// 规则由系统版本定义;"不想让它跑"的正确表达是 <c>/disable</c>,不是删除。
  103. /// 与 <see cref="UpdateAsync"/> / <see cref="CreateAsync"/> 同一墓碑形态。
  104. /// </summary>
  105. [Obsolete("Retired. Disable the rule instead; rule lifecycle belongs to the code release.")]
  106. [HttpDelete("{id:long}")]
  107. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  108. public IActionResult DeleteAsync(long id)
  109. {
  110. MarkLegacyDeprecated($"DELETE /api/aidop/s8/config/watch-rules/{id}", id);
  111. try { _ = _svc.DeleteAsync(id, RetiredWriteScope); return Ok(); }
  112. catch (S8WriteRetiredException ex)
  113. {
  114. return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status410Gone, new { message = ex.Message });
  115. }
  116. }
  117. // S8-RULE-GOVERNANCE-BATCH3:POST /{id}/test 已物理移除。
  118. // 它做的只是 LoadScoped + 配置字段校验(rule_code/scene 非空、编码唯一、dataset 在目录内、
  119. // 关联场景存在且启用、poll>0),**不取数、不判定**,返回一句"规则基础校验通过"。
  120. // 这些前提现在要么由代码定义保证、要么已不适用(场景行对代码定义的规则是无关约束)。
  121. // 「这条规则启用后会命中什么」由 GET /{id}/preview 真实回答,能力完全覆盖且更强。
  122. // 仓内无任何调用方:前端 s8ConfigApi.watchRules 无 test,通用 CRUD 页的 test 只用于
  123. // 场景/大屏卡片/角色三个 endpoint,不指向 watch-rules。
  124. /// <summary>
  125. /// S8-RULE01-INTEGRATION-PREVIEW-1:只读预演 —— 「这条规则现在启用会命中什么」。
  126. ///
  127. /// 在此之前想回答这个问题只能真把规则 enabled=true 然后等调度器跑,
  128. /// 对 Rule 01 而言那意味着一次性生成 28 条真实异常单,而验证只需要 1 条。
  129. /// 本端点补上这个中间档位:走**与生产完全相同**的 Gateway → Provider → Evaluator 链,
  130. /// 但不写 detection_log / exception / rule_detection_state,不改规则任何列,不发通知。
  131. ///
  132. /// 用 GET 而非 POST 是刻意的:它是一次查询,没有副作用,
  133. /// 用 POST 会让调用方以为「点了就会发生什么」。
  134. ///
  135. /// 权限沿用 ConfigWatchRule(能配规则的人才能预演),作用域由服务端盖章。
  136. /// </summary>
  137. [HttpGet("{id:long}/preview")]
  138. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  139. public async Task<IActionResult> PreviewAsync(long id, [FromServices] S8WatchRulePreviewService preview)
  140. {
  141. try { return Ok(await preview.PreviewAsync(id, await _scope.ResolveAsync())); }
  142. catch (S8NotFoundException) { return NotFound(); }
  143. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  144. catch (S8RuleEvaluatorException ex) { return BadRequest(new { reason = ex.Reason, message = ex.Message }); }
  145. }
  146. /// <summary>
  147. /// S8-RULE-GOVERNANCE-BATCH1:运行参数的**部分更新**。
  148. ///
  149. /// <para>只接受该规则的代码定义所声明的运行参数白名单
  150. /// (轮询间隔 / 抗抖次数 / 宽限分钟 / 严重度 / 部门兜底),未提供的字段保持原值。</para>
  151. ///
  152. /// <para><b>不再接受</b> params_json 原文与任何判定语义字段 —— 那些由代码定义,
  153. /// 出现在载荷里会得到 400 而不是被静默忽略。<b>也不再接受 enabled</b>,
  154. /// 启停请用 <c>/enable</c> 与 <c>/disable</c>。</para>
  155. ///
  156. /// <para>路由暂时保留 <c>/params</c> 以免与前端一次性大改耦合;
  157. /// 前端适配排在 Batch 4。</para>
  158. /// </summary>
  159. [HttpPut("{id:long}/params")]
  160. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  161. public async Task<IActionResult> UpdateParamsAsync(long id, [FromBody] S8RuleParametersPayload body)
  162. {
  163. try { return Ok(await _svc.UpdateParametersAsync(id, body, await _scope.ResolveAsync())); }
  164. catch (S8NotFoundException) { return NotFound(); }
  165. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  166. }
  167. /// <summary>
  168. /// 启用规则。<b>与参数写入完全分离</b>:本端点只写 enabled 与下次执行时间,
  169. /// 不触碰 params_json、不触碰任何参数列、不触碰定义投影列。
  170. ///
  171. /// <para>这条分离是 G1 的结构性修复:此前启停与 params_json 共用一个写入口,
  172. /// 一次「只想关个开关」的调用就会把规则的全部业务配置抹成 NULL。</para>
  173. ///
  174. /// <para>幂等:重复启用不产生写入。</para>
  175. /// </summary>
  176. [HttpPost("{id:long}/enable")]
  177. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  178. public async Task<IActionResult> EnableAsync(long id)
  179. {
  180. try { return Ok(await _svc.EnableAsync(id, await _scope.ResolveAsync())); }
  181. catch (S8NotFoundException) { return NotFound(); }
  182. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  183. }
  184. /// <summary>
  185. /// S8-RULE-GOVERNANCE-BATCH2:为**当前租户**补齐代码定义规则的运行策略行。
  186. ///
  187. /// <para>用途:研发发布了一条新规则之后,管理员无需重启即可让本租户立刻拿到对应的运行策略
  188. /// (默认停用)。幂等 —— 重复调用不会重复建行。</para>
  189. ///
  190. /// <para><b>只处理调用方自己的租户</b>:全租户对账是启动期的系统级动作。
  191. /// 若在这里放开全量,一个租户管理员就能对全平台其他租户写入运行策略行 ——
  192. /// 那与 S8 其余接口"作用域由服务端从登录身份盖章"的口径直接矛盾。</para>
  193. /// </summary>
  194. [HttpPost("provision")]
  195. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  196. public async Task<IActionResult> ProvisionAsync([FromServices] S8RuleProvisioningService provisioning)
  197. {
  198. try
  199. {
  200. var scope = await _scope.ResolveAsync();
  201. return Ok(await provisioning.SyncTenantAsync(scope.TenantId));
  202. }
  203. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  204. }
  205. /// <summary>
  206. /// 停用规则。只写 enabled;幂等。
  207. /// <b>刻意不过 Enable Gate</b>:数据集出问题之后仍然必须能把规则关掉。
  208. /// </summary>
  209. [HttpPost("{id:long}/disable")]
  210. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  211. public async Task<IActionResult> DisableAsync(long id)
  212. {
  213. try { return Ok(await _svc.DisableAsync(id, await _scope.ResolveAsync())); }
  214. catch (S8NotFoundException) { return NotFound(); }
  215. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  216. }
  217. /// <summary>
  218. /// S8-SCHED-FRONTEND-1:调度参数安全更新(仅 poll_interval_seconds / trigger_count_required / recover_count_required)。
  219. /// S8-RULE-GOVERNANCE-BATCH1:已委托到统一的参数写入路径,语义与 <c>/params</c> 一致。
  220. /// </summary>
  221. [HttpPut("{id:long}/schedule")]
  222. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  223. public async Task<IActionResult> UpdateScheduleAsync(long id, [FromBody] S8WatchRuleSchedulePayload body)
  224. {
  225. try { return Ok(await _svc.UpdateScheduleAsync(id, body, await _scope.ResolveAsync())); }
  226. catch (S8NotFoundException) { return NotFound(); }
  227. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  228. }
  229. /// <summary>S8-SCHED-FRONTEND-1:立即执行一次,next_run_at 置为 NOW,由下一 tick 拾取。</summary>
  230. [HttpPost("{id:long}/run-now")]
  231. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  232. public async Task<IActionResult> RunNowAsync(long id)
  233. {
  234. try { return Ok(await _svc.RunNowAsync(id, await _scope.ResolveAsync())); }
  235. catch (S8NotFoundException) { return NotFound(); }
  236. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  237. }
  238. /// <summary>S8-SCHED-FRONTEND-1:手工暂停,paused_until 置为远未来哨兵 + pause_reason=MANUAL_PAUSED。</summary>
  239. [HttpPost("{id:long}/pause")]
  240. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  241. public async Task<IActionResult> PauseAsync(long id)
  242. {
  243. try { return Ok(await _svc.PauseAsync(id, await _scope.ResolveAsync())); }
  244. catch (S8NotFoundException) { return NotFound(); }
  245. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  246. }
  247. /// <summary>S8-SCHED-FRONTEND-1:恢复,清 paused_until / pause_reason / last_error / consecutive_failure_count,next_run_at = NOW。</summary>
  248. [HttpPost("{id:long}/resume")]
  249. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  250. public async Task<IActionResult> ResumeAsync(long id)
  251. {
  252. try { return Ok(await _svc.ResumeAsync(id, await _scope.ResolveAsync())); }
  253. catch (S8NotFoundException) { return NotFound(); }
  254. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  255. }
  256. /// <summary>
  257. /// 旧端点 deprecated 收口:写入响应 header 标记 + 结构化 warning 日志,便于运行期识别 legacy 调用。
  258. /// 不阻断调用,不改返回结构。
  259. /// </summary>
  260. private void MarkLegacyDeprecated(string endpoint, long? ruleId = null)
  261. {
  262. // 响应 header — Headers 在响应已开始发送后会抛 InvalidOperationException,此处守卫一下避免污染主调用。
  263. var headers = Response.Headers;
  264. if (!headers.ContainsKey("X-AiDOP-Deprecated"))
  265. headers["X-AiDOP-Deprecated"] = "true";
  266. if (!headers.ContainsKey("X-AiDOP-Use-Instead"))
  267. headers["X-AiDOP-Use-Instead"] = LegacyHeaderUseInstead;
  268. var userId = User?.FindFirst("UserId")?.Value
  269. ?? User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
  270. var tenantId = HttpContext?.Request?.Query["tenantId"].ToString();
  271. var factoryId = HttpContext?.Request?.Query["factoryId"].ToString();
  272. _logger.LogWarning(
  273. "legacy_watch_rule_endpoint endpoint={Endpoint} ruleId={RuleId} userId={UserId} tenantId={TenantId} factoryId={FactoryId} useInstead={UseInstead}",
  274. endpoint, ruleId, userId, tenantId, factoryId, LegacyHeaderUseInstead);
  275. }
  276. }