AdoS8ConfigWatchRulesController.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. [Obsolete("Legacy full-update endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params for safe params editing.")]
  51. [HttpPut("{id:long}")]
  52. public async Task<IActionResult> UpdateAsync(long id, [FromBody] AdoS8WatchRule body)
  53. {
  54. MarkLegacyDeprecated($"PUT /api/aidop/s8/config/watch-rules/{id}", id);
  55. try { return Ok(await _svc.UpdateAsync(id, body, await _scope.ResolveAsync())); }
  56. catch (S8NotFoundException) { return NotFound(); }
  57. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  58. }
  59. /// <summary>
  60. /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params.
  61. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。
  62. /// </summary>
  63. [Obsolete("Legacy delete endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params for safe params editing.")]
  64. [HttpDelete("{id:long}")]
  65. public async Task<IActionResult> DeleteAsync(long id)
  66. {
  67. MarkLegacyDeprecated($"DELETE /api/aidop/s8/config/watch-rules/{id}", id);
  68. try { await _svc.DeleteAsync(id, await _scope.ResolveAsync()); }
  69. catch (S8NotFoundException) { return NotFound(); }
  70. return Ok();
  71. }
  72. /// <summary>
  73. /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params.
  74. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。
  75. /// </summary>
  76. [Obsolete("Legacy test endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params for safe params editing.")]
  77. [HttpPost("{id:long}/test")]
  78. public async Task<IActionResult> TestAsync(long id)
  79. {
  80. MarkLegacyDeprecated($"POST /api/aidop/s8/config/watch-rules/{id}/test", id);
  81. try { return Ok(await _svc.TestAsync(id, await _scope.ResolveAsync())); }
  82. catch (S8NotFoundException) { return NotFound(); }
  83. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  84. }
  85. /// <summary>
  86. /// R4 安全更新:仅修改 params_json 与 enabled,绝不接受 expression / rule_code / data_source_id /
  87. /// scene_code / watch_object_type / rule_type / source_object_type 等敏感字段。
  88. /// 服务端按 rule_type 用对应 evaluator 的 Params.Parse 进行 schema 校验。
  89. /// </summary>
  90. [HttpPut("{id:long}/params")]
  91. public async Task<IActionResult> UpdateParamsAsync(long id, [FromBody] S8WatchRuleParamsPayload body)
  92. {
  93. try { return Ok(await _svc.UpdateParamsAsync(id, body, await _scope.ResolveAsync())); }
  94. catch (S8NotFoundException) { return NotFound(); }
  95. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  96. }
  97. /// <summary>
  98. /// S8-SCHED-FRONTEND-1:调度参数安全更新(仅 poll_interval_seconds / trigger_count_required / recover_count_required)。
  99. /// 不动 params_json / rule_type / expression / data_source_id / scene_code。
  100. /// </summary>
  101. [HttpPut("{id:long}/schedule")]
  102. public async Task<IActionResult> UpdateScheduleAsync(long id, [FromBody] S8WatchRuleSchedulePayload body)
  103. {
  104. try { return Ok(await _svc.UpdateScheduleAsync(id, body, await _scope.ResolveAsync())); }
  105. catch (S8NotFoundException) { return NotFound(); }
  106. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  107. }
  108. /// <summary>S8-SCHED-FRONTEND-1:立即执行一次,next_run_at 置为 NOW,由下一 tick 拾取。</summary>
  109. [HttpPost("{id:long}/run-now")]
  110. public async Task<IActionResult> RunNowAsync(long id)
  111. {
  112. try { return Ok(await _svc.RunNowAsync(id, await _scope.ResolveAsync())); }
  113. catch (S8NotFoundException) { return NotFound(); }
  114. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  115. }
  116. /// <summary>S8-SCHED-FRONTEND-1:手工暂停,paused_until 置为远未来哨兵 + pause_reason=MANUAL_PAUSED。</summary>
  117. [HttpPost("{id:long}/pause")]
  118. public async Task<IActionResult> PauseAsync(long id)
  119. {
  120. try { return Ok(await _svc.PauseAsync(id, await _scope.ResolveAsync())); }
  121. catch (S8NotFoundException) { return NotFound(); }
  122. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  123. }
  124. /// <summary>S8-SCHED-FRONTEND-1:恢复,清 paused_until / pause_reason / last_error / consecutive_failure_count,next_run_at = NOW。</summary>
  125. [HttpPost("{id:long}/resume")]
  126. public async Task<IActionResult> ResumeAsync(long id)
  127. {
  128. try { return Ok(await _svc.ResumeAsync(id, await _scope.ResolveAsync())); }
  129. catch (S8NotFoundException) { return NotFound(); }
  130. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  131. }
  132. /// <summary>
  133. /// 旧端点 deprecated 收口:写入响应 header 标记 + 结构化 warning 日志,便于运行期识别 legacy 调用。
  134. /// 不阻断调用,不改返回结构。
  135. /// </summary>
  136. private void MarkLegacyDeprecated(string endpoint, long? ruleId = null)
  137. {
  138. // 响应 header — Headers 在响应已开始发送后会抛 InvalidOperationException,此处守卫一下避免污染主调用。
  139. var headers = Response.Headers;
  140. if (!headers.ContainsKey("X-AiDOP-Deprecated"))
  141. headers["X-AiDOP-Deprecated"] = "true";
  142. if (!headers.ContainsKey("X-AiDOP-Use-Instead"))
  143. headers["X-AiDOP-Use-Instead"] = LegacyHeaderUseInstead;
  144. var userId = User?.FindFirst("UserId")?.Value
  145. ?? User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
  146. var tenantId = HttpContext?.Request?.Query["tenantId"].ToString();
  147. var factoryId = HttpContext?.Request?.Query["factoryId"].ToString();
  148. _logger.LogWarning(
  149. "legacy_watch_rule_endpoint endpoint={Endpoint} ruleId={RuleId} userId={UserId} tenantId={TenantId} factoryId={FactoryId} useInstead={UseInstead}",
  150. endpoint, ruleId, userId, tenantId, factoryId, LegacyHeaderUseInstead);
  151. }
  152. }