AdoS8ConfigWatchRulesController.cs 11 KB

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