using System.Security.Claims; using Admin.NET.Plugin.AiDOP.Entity.S8; using Admin.NET.Plugin.AiDOP.Infrastructure; using Admin.NET.Plugin.AiDOP.Service.S8; using Microsoft.Extensions.Logging; namespace Admin.NET.Plugin.AiDOP.Controllers.S8; [ApiController] [Route("api/aidop/s8/config/watch-rules")] [NonUnify] public class AdoS8ConfigWatchRulesController : ControllerBase { private const string LegacyHeaderUseInstead = "PUT /api/aidop/s8/config/watch-rules/{id}/params"; private readonly S8WatchRuleService _svc; private readonly ILogger _logger; private readonly S8TrustedScopeResolver _scope; public AdoS8ConfigWatchRulesController( S8WatchRuleService svc, ILogger logger, S8TrustedScopeResolver scope) { _svc = svc; _logger = logger; _scope = scope; } [HttpGet] public async Task ListAsync([FromQuery] long tenantId = 1, [FromQuery] long factoryId = 1) { // Compatibility-only. Security scope is resolved server-side. _ = tenantId; _ = factoryId; var scope = await _scope.ResolveAsync(); return Ok(await _svc.ListAsync(scope.TenantId, scope.FactoryId)); } /// /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。 /// [Obsolete("Legacy full-create endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params for safe params editing.")] [HttpPost] public async Task CreateAsync([FromBody] AdoS8WatchRule body) { MarkLegacyDeprecated("POST /api/aidop/s8/config/watch-rules"); try { return Ok(await _svc.CreateAsync(body, await _scope.ResolveAsync())); } catch (S8NotFoundException) { return NotFound(); } catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); } } /// /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。 /// // ================================================================================ // S8-STEP6E-CFG-WATCH-FIX-AND-SAFE-CERT-1:本入口已退役 → 410 Gone。 // // 它是整实体更新,会连带把 13 个 scheduler-owned 运行时列暴露给客户端 //(lock_token / lock_until / paused_until / next_run_at / last_* / consecutive_failure_count), // 足以窃取租约、制造重复执行、静默停掉监控、伪造调度审计。详见 S8WatchRuleService.UpdateAsync 注释。 // // 选 410 而非 400/404:语义是「该能力曾经存在、现已永久退役」。 // 400 会暗示「改对入参还能存」,404 会暗示「换个 Id 还能存」,都与事实不符。 // // ⚠️ 不再调用 _scope.ResolveAsync():写能力已退役,不该为构造一个用不到的 scope 去读组织库; // 这同时保证 DB access = 0,并让工厂组织 0 个/多个的租户也稳定得到 410 而非作用域错误。 // ⚠️ catch 顺序:S8WriteRetiredException 必须排在 S8NotFoundException / S8BizException 之前。 // GET 与 /params /schedule /run-now /pause /resume 全部不受影响。 // ================================================================================ [Obsolete("Retired full-update endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params or /schedule.")] [HttpPut("{id:long}")] public async Task UpdateAsync(long id, [FromBody] AdoS8WatchRule body) { MarkLegacyDeprecated($"PUT /api/aidop/s8/config/watch-rules/{id}", id); try { return Ok(await _svc.UpdateAsync(id, body, RetiredWriteScope)); } catch (S8WriteRetiredException ex) { return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status410Gone, new { message = ex.Message }); } catch (S8NotFoundException) { return NotFound(); } catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); } } /// /// 写能力已永久退役:不得为了构造一个不会被使用的 scope 而读取组织库。 /// Service 写方法必须在读取该占位值或访问任何仓储前抛 S8WriteRetiredException。 /// (与 CFG_ALERT 的 RetiredWriteScope 同一模式。) /// private static readonly S8TrustedScope RetiredWriteScope = new(0, 0); /// /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。 /// [Obsolete("Legacy delete endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params for safe params editing.")] [HttpDelete("{id:long}")] public async Task DeleteAsync(long id) { MarkLegacyDeprecated($"DELETE /api/aidop/s8/config/watch-rules/{id}", id); try { await _svc.DeleteAsync(id, await _scope.ResolveAsync()); } catch (S8NotFoundException) { return NotFound(); } return Ok(); } /// /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。 /// [Obsolete("Legacy test endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params for safe params editing.")] [HttpPost("{id:long}/test")] public async Task TestAsync(long id) { MarkLegacyDeprecated($"POST /api/aidop/s8/config/watch-rules/{id}/test", id); try { return Ok(await _svc.TestAsync(id, await _scope.ResolveAsync())); } catch (S8NotFoundException) { return NotFound(); } catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); } } /// /// R4 安全更新:仅修改 params_json 与 enabled,绝不接受 expression / rule_code / data_source_id / /// scene_code / watch_object_type / rule_type / source_object_type 等敏感字段。 /// 服务端按 rule_type 用对应 evaluator 的 Params.Parse 进行 schema 校验。 /// [HttpPut("{id:long}/params")] public async Task UpdateParamsAsync(long id, [FromBody] S8WatchRuleParamsPayload body) { try { return Ok(await _svc.UpdateParamsAsync(id, body, await _scope.ResolveAsync())); } catch (S8NotFoundException) { return NotFound(); } catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); } } /// /// S8-SCHED-FRONTEND-1:调度参数安全更新(仅 poll_interval_seconds / trigger_count_required / recover_count_required)。 /// 不动 params_json / rule_type / expression / data_source_id / scene_code。 /// [HttpPut("{id:long}/schedule")] public async Task UpdateScheduleAsync(long id, [FromBody] S8WatchRuleSchedulePayload body) { try { return Ok(await _svc.UpdateScheduleAsync(id, body, await _scope.ResolveAsync())); } catch (S8NotFoundException) { return NotFound(); } catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); } } /// S8-SCHED-FRONTEND-1:立即执行一次,next_run_at 置为 NOW,由下一 tick 拾取。 [HttpPost("{id:long}/run-now")] public async Task RunNowAsync(long id) { try { return Ok(await _svc.RunNowAsync(id, await _scope.ResolveAsync())); } catch (S8NotFoundException) { return NotFound(); } catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); } } /// S8-SCHED-FRONTEND-1:手工暂停,paused_until 置为远未来哨兵 + pause_reason=MANUAL_PAUSED。 [HttpPost("{id:long}/pause")] public async Task PauseAsync(long id) { try { return Ok(await _svc.PauseAsync(id, await _scope.ResolveAsync())); } catch (S8NotFoundException) { return NotFound(); } catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); } } /// S8-SCHED-FRONTEND-1:恢复,清 paused_until / pause_reason / last_error / consecutive_failure_count,next_run_at = NOW。 [HttpPost("{id:long}/resume")] public async Task ResumeAsync(long id) { try { return Ok(await _svc.ResumeAsync(id, await _scope.ResolveAsync())); } catch (S8NotFoundException) { return NotFound(); } catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); } } /// /// 旧端点 deprecated 收口:写入响应 header 标记 + 结构化 warning 日志,便于运行期识别 legacy 调用。 /// 不阻断调用,不改返回结构。 /// private void MarkLegacyDeprecated(string endpoint, long? ruleId = null) { // 响应 header — Headers 在响应已开始发送后会抛 InvalidOperationException,此处守卫一下避免污染主调用。 var headers = Response.Headers; if (!headers.ContainsKey("X-AiDOP-Deprecated")) headers["X-AiDOP-Deprecated"] = "true"; if (!headers.ContainsKey("X-AiDOP-Use-Instead")) headers["X-AiDOP-Use-Instead"] = LegacyHeaderUseInstead; var userId = User?.FindFirst("UserId")?.Value ?? User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; var tenantId = HttpContext?.Request?.Query["tenantId"].ToString(); var factoryId = HttpContext?.Request?.Query["factoryId"].ToString(); _logger.LogWarning( "legacy_watch_rule_endpoint endpoint={Endpoint} ruleId={RuleId} userId={UserId} tenantId={TenantId} factoryId={FactoryId} useInstead={UseInstead}", endpoint, ruleId, userId, tenantId, factoryId, LegacyHeaderUseInstead); } }