S8WatchRuleService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. using System.Text.Json;
  2. using Admin.NET.Plugin.AiDOP.Entity.S8;
  3. using Admin.NET.Plugin.AiDOP.Infrastructure;
  4. using Admin.NET.Plugin.AiDOP.Infrastructure.S8;
  5. using Admin.NET.Plugin.AiDOP.Service.S8.Rules;
  6. namespace Admin.NET.Plugin.AiDOP.Service.S8;
  7. public class S8WatchRuleService : ITransient
  8. {
  9. private readonly SqlSugarRepository<AdoS8WatchRule> _rep;
  10. private readonly SqlSugarRepository<AdoS8DataSource> _dataSourceRep;
  11. private readonly SqlSugarRepository<AdoS8SceneConfig> _sceneRep;
  12. public S8WatchRuleService(
  13. SqlSugarRepository<AdoS8WatchRule> rep,
  14. SqlSugarRepository<AdoS8DataSource> dataSourceRep,
  15. SqlSugarRepository<AdoS8SceneConfig> sceneRep)
  16. {
  17. _rep = rep;
  18. _dataSourceRep = dataSourceRep;
  19. _sceneRep = sceneRep;
  20. }
  21. public async Task<List<AdoS8WatchRule>> ListAsync(long tenantId, long factoryId) =>
  22. await _rep.AsQueryable()
  23. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId)
  24. .ToListAsync();
  25. // S8-TENANT-FACTORY-P0-CLOSURE-1:归属一律由服务端可信作用域盖章,忽略 body.TenantId / body.FactoryId。
  26. public async Task<AdoS8WatchRule> CreateAsync(AdoS8WatchRule body, S8TrustedScope scope)
  27. {
  28. body.TenantId = scope.TenantId;
  29. body.FactoryId = scope.FactoryId;
  30. await ValidateAsync(body, scope);
  31. // S8-STEP6E:新建一律走 canonical 词表 + params schema,杜绝「存得下但运行时永远不生效」。
  32. ValidateVocabularyForCreate(body);
  33. if (!string.IsNullOrWhiteSpace(body.ParamsJson))
  34. ValidateParamsJsonByRuleType(body.RuleType, body.ParamsJson!.Trim());
  35. body.Id = 0;
  36. body.CreatedAt = DateTime.Now;
  37. // S8-STEP6E(与 CFG_DATASRC D-3 / CFG_ROLES 同源缺陷):回填自增主键。
  38. // 原 InsertAsync 只返回 bool,body.Id 保持 0,调用方随后 GET/PUT/DELETE 一律 404。
  39. body.Id = await _rep.AsInsertable(body).ExecuteReturnBigIdentityAsync();
  40. return body;
  41. }
  42. // ================================================================================
  43. // S8-STEP6E-CFG-WATCH-FIX-AND-SAFE-CERT-1:通用整实体 PUT 已退役。
  44. //
  45. // 原实现 `_rep.UpdateAsync(body)` 是**整列更新**,而 body 直接由客户端 JSON 绑定
  46. // (本实体即 DTO),服务端只重新盖章 5 个字段(Tenant/Factory/Id/CreatedAt/UpdatedAt)。
  47. // 实体与仓储层均无 UpdateIgnoreColumns / IsOnlyIgnoreUpdate 保护,因此调用方可写入
  48. // 全部 13 个 scheduler-owned 运行时列:
  49. // lock_token / locked_by / lock_until / running_started_at /
  50. // next_run_at / last_run_at / last_status / last_error / last_duration_ms / last_run_id /
  51. // consecutive_failure_count / paused_until / pause_reason
  52. //
  53. // 后果(按 S8WatchSchedulerService 的租约语义):
  54. // · 写 lock_token/lock_until → 窃取或作废活跃租约,令运行中实例的回写静默失败
  55. // · 清 lock → 第二实例重复拾取同一规则 → 重复建单
  56. // · lock_until 设远未来 → 该规则永不再被 PickReadyRulesAsync 选中(静默 DoS)
  57. // · paused_until 设远未来 → UI 仍显示「启用」但监控实际已停
  58. // · 写 last_status/last_run_id/last_error → 伪造调度审计轨迹
  59. // 且**无需恶意**:部分字段的 PUT body 会让这 13 列静默变 NULL(HTTP 200、无报错)。
  60. //
  61. // 退役而非改白名单,是因为该入口没有正式消费方(已穷举:前端 s8ConfigApi.watchRules
  62. // 无 update;e2e 只用 GET/POST/DELETE;服务端唯一引用是本 controller),
  63. // 而正式配置修改已有 UpdateParamsAsync / UpdateScheduleAsync 等窄入口。
  64. //
  65. // ⚠️ 抛出发生在**任何 DB 访问之前**:不做 LoadScopedAsync、不做重复性查询。
  66. // 这既保证零 DB 触碰,也保证任意 id(含越权 id)一律 410 而非 404
  67. // ——「这个能力没了」优先于「这条记录不属于你」,避免越权探测反推他租户数据是否存在。
  68. //
  69. // 保留方法签名是硬约束:S8TenantIsolationContractTests 用反射断言带 S8TrustedScope
  70. // 的写入口存在、且无 scope 的旧重载不存在。
  71. // ================================================================================
  72. public Task<AdoS8WatchRule> UpdateAsync(long id, AdoS8WatchRule body, S8TrustedScope scope) =>
  73. throw new S8WriteRetiredException(S8WriteRetiredException.WatchRuleUpdateMessage);
  74. // S8-TENANT-FACTORY-P0-CLOSURE-1:删除必须先按可信作用域绑行,禁止裸 DeleteByIdAsync(id)。
  75. public async Task DeleteAsync(long id, S8TrustedScope scope)
  76. {
  77. var e = await LoadScopedAsync(id, scope);
  78. await _rep.DeleteByIdAsync(e.Id);
  79. }
  80. /// <summary>按 Id + 可信作用域取行;不在作用域内一律按「不存在」处理,不泄露他租户资源是否存在。</summary>
  81. private async Task<AdoS8WatchRule> LoadScopedAsync(long id, S8TrustedScope scope) =>
  82. await _rep.AsQueryable()
  83. .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
  84. .FirstAsync() ?? throw new S8NotFoundException();
  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. /// 当 RuleType 非空时,按对应 evaluator 的 Params.Parse 进行 schema 校验,解析失败抛 S8BizException。
  89. /// </summary>
  90. public async Task<AdoS8WatchRule> UpdateParamsAsync(long id, S8WatchRuleParamsPayload payload, S8TrustedScope scope)
  91. {
  92. var entity = await LoadScopedAsync(id, scope);
  93. var paramsJson = payload.ParamsJson?.Trim();
  94. if (!string.IsNullOrEmpty(paramsJson))
  95. {
  96. ValidateParamsJsonByRuleType(entity.RuleType, paramsJson);
  97. }
  98. entity.ParamsJson = string.IsNullOrEmpty(paramsJson) ? null : paramsJson;
  99. entity.Enabled = payload.Enabled;
  100. // TASK-002-RESET-DIMENSION-MODEL-DEV-2B:维度归属 + 报警机制按 payload 原样落库(含 null 清空)。
  101. entity.StageCode = NormalizeOrNull(payload.StageCode);
  102. entity.OrderFlowCode = NormalizeOrNull(payload.OrderFlowCode);
  103. entity.RuleMechanism = NormalizeOrNull(payload.RuleMechanism);
  104. entity.UpdatedAt = DateTime.Now;
  105. await _rep.UpdateAsync(entity);
  106. return entity;
  107. }
  108. private static string? NormalizeOrNull(string? value)
  109. {
  110. if (string.IsNullOrWhiteSpace(value)) return null;
  111. var trimmed = value.Trim();
  112. return trimmed.Length == 0 ? null : trimmed;
  113. }
  114. /// <summary>
  115. /// S8-STEP6E:WATCH 侧 canonical 词表,**严格取自真实 evaluator dispatch**
  116. /// (S8WatchSchedulerService.RunSingleRuleAsync 的 switch,ordinal 大小写敏感),
  117. /// 不是从 NOTIFY 词表套用过来的。
  118. /// 注意 rule_type 为空/空白是**合法的历史态**(调度器按 rule_type_empty_skipped 跳过、
  119. /// 不算失败),但**不允许新建**——新建一条永远不会被任何 evaluator 承载的规则没有产品意义。
  120. /// </summary>
  121. private static readonly string[] CanonicalRuleTypes =
  122. {
  123. S8TimeoutRuleEvaluator.RuleTypeCode,
  124. S8ShortageRuleEvaluator.RuleTypeCode,
  125. S8OutOfRangeRuleEvaluator.RuleTypeCode,
  126. };
  127. /// <summary>
  128. /// S8-STEP6E:新建时的 canonical 词表校验(rule_type / scene / severity)。
  129. ///
  130. /// 只作用于 Create:
  131. /// · UpdateParamsAsync / UpdateScheduleAsync / Pause / Resume 都不修改这三个字段,无需重复校验;
  132. /// · TestAsync 是对**既有行**的探针,若在此加严会让 legacy 无效行连自检都跑不了。
  133. /// 即「legacy 无效数据允许读取与停用,但禁止继续创建」。
  134. /// </summary>
  135. private static void ValidateVocabularyForCreate(AdoS8WatchRule body)
  136. {
  137. // rule_type:必须是真实存在 evaluator 的三类之一。
  138. if (string.IsNullOrWhiteSpace(body.RuleType)
  139. || Array.IndexOf(CanonicalRuleTypes, body.RuleType) < 0)
  140. throw new S8BizException(
  141. "不支持的规则类型:" + (string.IsNullOrWhiteSpace(body.RuleType) ? "(空)" : body.RuleType)
  142. + ";当前仅支持 " + string.Join(" / ", CanonicalRuleTypes));
  143. // scene:S8SceneCode 本身没有 IsValid,canonical 单模块场景判定复用 S8ModuleCode.IsValid
  144. //(仓内唯一「严格 S1–S7、拒 legacy 复合场景」的现成实现,不另造第二套)。
  145. if (!S8ModuleCode.IsValid(body.SceneCode))
  146. throw new S8BizException(
  147. "不支持的场景编码:" + body.SceneCode + ";当前仅支持 " + string.Join(" / ", S8ModuleCode.All));
  148. // severity:必须在 S8SeverityCode.Normalize **之前**校验。
  149. // Normalize 的兜底分支是 `_ => Follow`,放在之后会把 HIGH / 拼写错误静默降级成 FOLLOW,
  150. // 门禁永远命中不了——DB 中 severity='HIGH' 的那一行正是这样进来的。
  151. // 也刻意不复用 S8SeverityCode.IsValid:那是宽松六值版(含 LOW/MEDIUM/HIGH/CRITICAL),
  152. // 供 legacy 查询参数兼容用,拿来当写入门禁会直接放行 legacy 值。
  153. if (!string.Equals(body.Severity, S8SeverityCode.Follow, StringComparison.Ordinal)
  154. && !string.Equals(body.Severity, S8SeverityCode.Serious, StringComparison.Ordinal))
  155. throw new S8BizException(
  156. "不支持的严重度:" + body.Severity + ";当前仅支持 "
  157. + S8SeverityCode.Follow + " / " + S8SeverityCode.Serious);
  158. }
  159. private static void ValidateParamsJsonByRuleType(string? ruleType, string paramsJson)
  160. {
  161. try
  162. {
  163. switch (ruleType)
  164. {
  165. case S8TimeoutRuleEvaluator.RuleTypeCode:
  166. {
  167. var p = S8TimeoutParams.Parse(paramsJson);
  168. if (string.IsNullOrWhiteSpace(p.DueAtField)
  169. || string.IsNullOrWhiteSpace(p.StatusField)
  170. || string.IsNullOrWhiteSpace(p.ExceptionTypeCode))
  171. throw new S8BizException("TIMEOUT params 缺少必填字段:dueAtField / statusField / exceptionTypeCode");
  172. break;
  173. }
  174. case S8ShortageRuleEvaluator.RuleTypeCode:
  175. {
  176. var p = S8ShortageParams.Parse(paramsJson);
  177. if (string.IsNullOrWhiteSpace(p.TargetQtyField)
  178. || string.IsNullOrWhiteSpace(p.ActualQtyField)
  179. || string.IsNullOrWhiteSpace(p.ExceptionTypeCode))
  180. throw new S8BizException("SHORTAGE params 缺少必填字段:targetQtyField / actualQtyField / exceptionTypeCode");
  181. break;
  182. }
  183. case S8OutOfRangeRuleEvaluator.RuleTypeCode:
  184. {
  185. var p = S8OutOfRangeParams.Parse(paramsJson);
  186. if (string.IsNullOrWhiteSpace(p.MeasuredValueField))
  187. throw new S8BizException("OUT_OF_RANGE params 缺少必填字段:measuredValueField");
  188. if (p.LowerBound == null && p.UpperBound == null
  189. && string.IsNullOrWhiteSpace(p.LowerBoundField)
  190. && string.IsNullOrWhiteSpace(p.UpperBoundField))
  191. throw new S8BizException("OUT_OF_RANGE params 必须提供 upperBound / lowerBound 或对应行内字段之一");
  192. break;
  193. }
  194. default:
  195. // RuleType 为空或非三类已知值:仅做 JSON 合法性校验,避免阻塞历史数据。
  196. using (JsonDocument.Parse(paramsJson)) { }
  197. break;
  198. }
  199. }
  200. catch (JsonException ex)
  201. {
  202. throw new S8BizException($"params_json 不是合法 JSON:{ex.Message}");
  203. }
  204. }
  205. public async Task<object> TestAsync(long id, S8TrustedScope scope)
  206. {
  207. var entity = await LoadScopedAsync(id, scope);
  208. await ValidateAsync(entity, scope, id);
  209. return new { id, success = true, message = "规则基础校验通过", pollIntervalSeconds = entity.PollIntervalSeconds };
  210. }
  211. // S8-SCHED-FRONTEND-1:远未来手工暂停哨兵值(与 SqlSugar DateTime 兼容;前端按 paused_until > now 判定)。
  212. private static readonly DateTime ManualPausedSentinel = new(9999, 12, 31, 23, 59, 59);
  213. /// <summary>
  214. /// S8-SCHED-FRONTEND-1:调度参数安全更新。仅修改 poll_interval_seconds / trigger_count_required /
  215. /// recover_count_required;不动 params_json / expression / rule_type / scene_code / data_source_id。
  216. /// </summary>
  217. public async Task<AdoS8WatchRule> UpdateScheduleAsync(long id, S8WatchRuleSchedulePayload payload, S8TrustedScope scope)
  218. {
  219. var entity = await LoadScopedAsync(id, scope);
  220. if (payload.PollIntervalSeconds < 60 || payload.PollIntervalSeconds > 86400)
  221. throw new S8BizException("poll_interval_seconds 必须在 60–86400 之间");
  222. if (payload.TriggerCountRequired < 1 || payload.TriggerCountRequired > 10)
  223. throw new S8BizException("trigger_count_required 必须在 1–10 之间");
  224. if (payload.RecoverCountRequired < 1 || payload.RecoverCountRequired > 10)
  225. throw new S8BizException("recover_count_required 必须在 1–10 之间");
  226. await _rep.Context.Updateable<AdoS8WatchRule>()
  227. .SetColumns(x => new AdoS8WatchRule
  228. {
  229. PollIntervalSeconds = payload.PollIntervalSeconds,
  230. TriggerCountRequired = payload.TriggerCountRequired,
  231. RecoverCountRequired = payload.RecoverCountRequired,
  232. UpdatedAt = DateTime.Now
  233. })
  234. .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
  235. .ExecuteCommandAsync();
  236. return await LoadScopedAsync(id, scope);
  237. }
  238. /// <summary>
  239. /// S8-SCHED-FRONTEND-1:立即执行一次。把 next_run_at 置为 NOW,让下个 tick 拾取。
  240. /// 不直接同步执行 evaluator;不阻塞请求;返回 200 + 提示。
  241. /// </summary>
  242. public async Task<object> RunNowAsync(long id, S8TrustedScope scope)
  243. {
  244. var entity = await LoadScopedAsync(id, scope);
  245. if (!entity.Enabled)
  246. throw new S8BizException("规则未启用,不能立即执行");
  247. var now = DateTime.Now;
  248. if (entity.PausedUntil.HasValue && entity.PausedUntil.Value > now)
  249. throw new S8BizException("规则已暂停,请先恢复");
  250. if (entity.LockUntil.HasValue && entity.LockUntil.Value > now)
  251. throw new S8BizException("规则正在执行中,请稍后再试");
  252. await _rep.Context.Updateable<AdoS8WatchRule>()
  253. .SetColumns(x => new AdoS8WatchRule
  254. {
  255. NextRunAt = now,
  256. UpdatedAt = now
  257. })
  258. .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
  259. .ExecuteCommandAsync();
  260. return new { id, queued = true, message = "已排队,最长 1 分钟内执行" };
  261. }
  262. /// <summary>
  263. /// S8-SCHED-FRONTEND-1:手工暂停。paused_until = 9999-12-31 哨兵 + pause_reason=MANUAL_PAUSED。
  264. /// 不强杀正在执行的 lease;当前运行完成后下一轮自然不被拾取。
  265. /// 不清 last_status / last_error。
  266. /// </summary>
  267. public async Task<object> PauseAsync(long id, S8TrustedScope scope)
  268. {
  269. var entity = await LoadScopedAsync(id, scope);
  270. await _rep.Context.Updateable<AdoS8WatchRule>()
  271. .SetColumns(x => new AdoS8WatchRule
  272. {
  273. PausedUntil = ManualPausedSentinel,
  274. PauseReason = "MANUAL_PAUSED",
  275. UpdatedAt = DateTime.Now
  276. })
  277. .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
  278. .ExecuteCommandAsync();
  279. return new { id, paused = true, message = "已暂停" };
  280. }
  281. /// <summary>
  282. /// S8-SCHED-FRONTEND-1:恢复。清 paused_until / pause_reason / last_error;归零 consecutive_failure_count;
  283. /// next_run_at = NOW 让下个 tick 立即拾取。不改 enabled / params_json / rule_type。
  284. /// </summary>
  285. public async Task<object> ResumeAsync(long id, S8TrustedScope scope)
  286. {
  287. var entity = await LoadScopedAsync(id, scope);
  288. var now = DateTime.Now;
  289. await _rep.Context.Updateable<AdoS8WatchRule>()
  290. .SetColumns(x => new AdoS8WatchRule
  291. {
  292. PausedUntil = null,
  293. PauseReason = null,
  294. ConsecutiveFailureCount = 0,
  295. LastError = null,
  296. NextRunAt = now,
  297. UpdatedAt = now
  298. })
  299. .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
  300. .ExecuteCommandAsync();
  301. return new { id, resumed = true, message = "已恢复,并将在下一轮调度中执行" };
  302. }
  303. private async Task ValidateAsync(AdoS8WatchRule body, S8TrustedScope scope, long? id = null)
  304. {
  305. if (string.IsNullOrWhiteSpace(body.RuleCode) || string.IsNullOrWhiteSpace(body.SceneCode))
  306. throw new S8BizException("规则编码和场景编码必填");
  307. var exists = await _rep.AsQueryable()
  308. .AnyAsync(x => x.Id != (id ?? 0) && x.TenantId == body.TenantId && x.FactoryId == body.FactoryId && x.RuleCode == body.RuleCode);
  309. if (exists) throw new S8BizException("监视规则编码已存在");
  310. // S8-TENANT-FACTORY-P0-CLOSURE-1:关联数据源必须同属可信作用域,禁止引用他租户数据源。
  311. var dataSource = await _dataSourceRep.GetFirstAsync(
  312. x => x.Id == body.DataSourceId && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
  313. ?? throw new S8BizException("关联数据源不存在");
  314. if (!dataSource.Enabled) throw new S8BizException("关联数据源未启用");
  315. var scene = await _sceneRep.GetFirstAsync(x => x.TenantId == body.TenantId && x.FactoryId == body.FactoryId && x.SceneCode == body.SceneCode)
  316. ?? throw new S8BizException("关联场景不存在");
  317. if (!scene.Enabled) throw new S8BizException("关联场景未启用");
  318. if (body.PollIntervalSeconds <= 0) throw new S8BizException("轮询间隔必须大于 0");
  319. }
  320. }