AdoS8ConfigWatchRulesController.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. using System.Security.Claims;
  2. using Admin.NET.Plugin.AiDOP.Entity.S8;
  3. using Admin.NET.Plugin.AiDOP.Infrastructure;
  4. using Admin.NET.Plugin.AiDOP.Service.S8;
  5. using Microsoft.Extensions.Logging;
  6. namespace Admin.NET.Plugin.AiDOP.Controllers.S8;
  7. [ApiController]
  8. [Route("api/aidop/s8/config/watch-rules")]
  9. [NonUnify]
  10. public class AdoS8ConfigWatchRulesController : ControllerBase
  11. {
  12. private const string LegacyHeaderUseInstead = "PUT /api/aidop/s8/config/watch-rules/{id}/params";
  13. private readonly S8WatchRuleService _svc;
  14. private readonly ILogger<AdoS8ConfigWatchRulesController> _logger;
  15. private readonly S8TrustedScopeResolver _scope;
  16. public AdoS8ConfigWatchRulesController(
  17. S8WatchRuleService svc,
  18. ILogger<AdoS8ConfigWatchRulesController> logger,
  19. S8TrustedScopeResolver scope)
  20. {
  21. _svc = svc;
  22. _logger = logger;
  23. _scope = scope;
  24. }
  25. [HttpGet]
  26. public async Task<IActionResult> ListAsync([FromQuery] long tenantId = 1, [FromQuery] long factoryId = 1)
  27. {
  28. // Compatibility-only. Security scope is resolved server-side.
  29. _ = tenantId; _ = factoryId;
  30. var scope = await _scope.ResolveAsync();
  31. return Ok(await _svc.ListAsync(scope.TenantId, scope.FactoryId));
  32. }
  33. /// <summary>
  34. /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params.
  35. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。
  36. /// </summary>
  37. [Obsolete("Legacy full-create endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params for safe params editing.")]
  38. [HttpPost]
  39. public async Task<IActionResult> CreateAsync([FromBody] AdoS8WatchRule body)
  40. {
  41. MarkLegacyDeprecated("POST /api/aidop/s8/config/watch-rules");
  42. try { return Ok(await _svc.CreateAsync(body, await _scope.ResolveAsync())); }
  43. catch (S8NotFoundException) { return NotFound(); }
  44. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  45. }
  46. /// <summary>
  47. /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params.
  48. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。
  49. /// </summary>
  50. // ================================================================================
  51. // S8-STEP6E-CFG-WATCH-FIX-AND-SAFE-CERT-1:本入口已退役 → 410 Gone。
  52. //
  53. // 它是整实体更新,会连带把 13 个 scheduler-owned 运行时列暴露给客户端
  54. //(lock_token / lock_until / paused_until / next_run_at / last_* / consecutive_failure_count),
  55. // 足以窃取租约、制造重复执行、静默停掉监控、伪造调度审计。详见 S8WatchRuleService.UpdateAsync 注释。
  56. //
  57. // 选 410 而非 400/404:语义是「该能力曾经存在、现已永久退役」。
  58. // 400 会暗示「改对入参还能存」,404 会暗示「换个 Id 还能存」,都与事实不符。
  59. //
  60. // ⚠️ 不再调用 _scope.ResolveAsync():写能力已退役,不该为构造一个用不到的 scope 去读组织库;
  61. // 这同时保证 DB access = 0,并让工厂组织 0 个/多个的租户也稳定得到 410 而非作用域错误。
  62. // ⚠️ catch 顺序:S8WriteRetiredException 必须排在 S8NotFoundException / S8BizException 之前。
  63. // GET 与 /params /schedule /run-now /pause /resume 全部不受影响。
  64. // ================================================================================
  65. [Obsolete("Retired full-update endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params or /schedule.")]
  66. [HttpPut("{id:long}")]
  67. public async Task<IActionResult> UpdateAsync(long id, [FromBody] AdoS8WatchRule body)
  68. {
  69. MarkLegacyDeprecated($"PUT /api/aidop/s8/config/watch-rules/{id}", id);
  70. try { return Ok(await _svc.UpdateAsync(id, body, RetiredWriteScope)); }
  71. catch (S8WriteRetiredException ex)
  72. {
  73. return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status410Gone, new { message = ex.Message });
  74. }
  75. catch (S8NotFoundException) { return NotFound(); }
  76. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  77. }
  78. /// <summary>
  79. /// 写能力已永久退役:不得为了构造一个不会被使用的 scope 而读取组织库。
  80. /// Service 写方法必须在读取该占位值或访问任何仓储前抛 S8WriteRetiredException。
  81. /// (与 CFG_ALERT 的 RetiredWriteScope 同一模式。)
  82. /// </summary>
  83. private static readonly S8TrustedScope RetiredWriteScope = new(0, 0);
  84. /// <summary>
  85. /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params.
  86. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。
  87. /// </summary>
  88. [Obsolete("Legacy delete endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params for safe params editing.")]
  89. [HttpDelete("{id:long}")]
  90. public async Task<IActionResult> DeleteAsync(long id)
  91. {
  92. MarkLegacyDeprecated($"DELETE /api/aidop/s8/config/watch-rules/{id}", id);
  93. try { await _svc.DeleteAsync(id, await _scope.ResolveAsync()); }
  94. catch (S8NotFoundException) { return NotFound(); }
  95. return Ok();
  96. }
  97. /// <summary>
  98. /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params.
  99. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。
  100. /// </summary>
  101. [Obsolete("Legacy test endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params for safe params editing.")]
  102. [HttpPost("{id:long}/test")]
  103. public async Task<IActionResult> TestAsync(long id)
  104. {
  105. MarkLegacyDeprecated($"POST /api/aidop/s8/config/watch-rules/{id}/test", id);
  106. try { return Ok(await _svc.TestAsync(id, await _scope.ResolveAsync())); }
  107. catch (S8NotFoundException) { return NotFound(); }
  108. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  109. }
  110. /// <summary>
  111. /// R4 安全更新:仅修改 params_json 与 enabled,绝不接受 expression / rule_code / data_source_id /
  112. /// scene_code / watch_object_type / rule_type / source_object_type 等敏感字段。
  113. /// 服务端按 rule_type 用对应 evaluator 的 Params.Parse 进行 schema 校验。
  114. /// </summary>
  115. [HttpPut("{id:long}/params")]
  116. public async Task<IActionResult> UpdateParamsAsync(long id, [FromBody] S8WatchRuleParamsPayload body)
  117. {
  118. try { return Ok(await _svc.UpdateParamsAsync(id, body, await _scope.ResolveAsync())); }
  119. catch (S8NotFoundException) { return NotFound(); }
  120. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  121. }
  122. /// <summary>
  123. /// S8-SCHED-FRONTEND-1:调度参数安全更新(仅 poll_interval_seconds / trigger_count_required / recover_count_required)。
  124. /// 不动 params_json / rule_type / expression / data_source_id / scene_code。
  125. /// </summary>
  126. [HttpPut("{id:long}/schedule")]
  127. public async Task<IActionResult> UpdateScheduleAsync(long id, [FromBody] S8WatchRuleSchedulePayload body)
  128. {
  129. try { return Ok(await _svc.UpdateScheduleAsync(id, body, await _scope.ResolveAsync())); }
  130. catch (S8NotFoundException) { return NotFound(); }
  131. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  132. }
  133. /// <summary>S8-SCHED-FRONTEND-1:立即执行一次,next_run_at 置为 NOW,由下一 tick 拾取。</summary>
  134. [HttpPost("{id:long}/run-now")]
  135. public async Task<IActionResult> RunNowAsync(long id)
  136. {
  137. try { return Ok(await _svc.RunNowAsync(id, await _scope.ResolveAsync())); }
  138. catch (S8NotFoundException) { return NotFound(); }
  139. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  140. }
  141. /// <summary>S8-SCHED-FRONTEND-1:手工暂停,paused_until 置为远未来哨兵 + pause_reason=MANUAL_PAUSED。</summary>
  142. [HttpPost("{id:long}/pause")]
  143. public async Task<IActionResult> PauseAsync(long id)
  144. {
  145. try { return Ok(await _svc.PauseAsync(id, await _scope.ResolveAsync())); }
  146. catch (S8NotFoundException) { return NotFound(); }
  147. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  148. }
  149. /// <summary>S8-SCHED-FRONTEND-1:恢复,清 paused_until / pause_reason / last_error / consecutive_failure_count,next_run_at = NOW。</summary>
  150. [HttpPost("{id:long}/resume")]
  151. public async Task<IActionResult> ResumeAsync(long id)
  152. {
  153. try { return Ok(await _svc.ResumeAsync(id, await _scope.ResolveAsync())); }
  154. catch (S8NotFoundException) { return NotFound(); }
  155. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  156. }
  157. /// <summary>
  158. /// 旧端点 deprecated 收口:写入响应 header 标记 + 结构化 warning 日志,便于运行期识别 legacy 调用。
  159. /// 不阻断调用,不改返回结构。
  160. /// </summary>
  161. private void MarkLegacyDeprecated(string endpoint, long? ruleId = null)
  162. {
  163. // 响应 header — Headers 在响应已开始发送后会抛 InvalidOperationException,此处守卫一下避免污染主调用。
  164. var headers = Response.Headers;
  165. if (!headers.ContainsKey("X-AiDOP-Deprecated"))
  166. headers["X-AiDOP-Deprecated"] = "true";
  167. if (!headers.ContainsKey("X-AiDOP-Use-Instead"))
  168. headers["X-AiDOP-Use-Instead"] = LegacyHeaderUseInstead;
  169. var userId = User?.FindFirst("UserId")?.Value
  170. ?? User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
  171. var tenantId = HttpContext?.Request?.Query["tenantId"].ToString();
  172. var factoryId = HttpContext?.Request?.Query["factoryId"].ToString();
  173. _logger.LogWarning(
  174. "legacy_watch_rule_endpoint endpoint={Endpoint} ruleId={RuleId} userId={UserId} tenantId={TenantId} factoryId={FactoryId} useInstead={UseInstead}",
  175. endpoint, ruleId, userId, tenantId, factoryId, LegacyHeaderUseInstead);
  176. }
  177. }