S8WatchRuleService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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.Service.S8.Rules;
  5. namespace Admin.NET.Plugin.AiDOP.Service.S8;
  6. public class S8WatchRuleService : ITransient
  7. {
  8. private readonly SqlSugarRepository<AdoS8WatchRule> _rep;
  9. private readonly SqlSugarRepository<AdoS8DataSource> _dataSourceRep;
  10. private readonly SqlSugarRepository<AdoS8SceneConfig> _sceneRep;
  11. public S8WatchRuleService(
  12. SqlSugarRepository<AdoS8WatchRule> rep,
  13. SqlSugarRepository<AdoS8DataSource> dataSourceRep,
  14. SqlSugarRepository<AdoS8SceneConfig> sceneRep)
  15. {
  16. _rep = rep;
  17. _dataSourceRep = dataSourceRep;
  18. _sceneRep = sceneRep;
  19. }
  20. public async Task<List<AdoS8WatchRule>> ListAsync(long tenantId, long factoryId) =>
  21. await _rep.AsQueryable()
  22. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId)
  23. .ToListAsync();
  24. // S8-TENANT-FACTORY-P0-CLOSURE-1:归属一律由服务端可信作用域盖章,忽略 body.TenantId / body.FactoryId。
  25. public async Task<AdoS8WatchRule> CreateAsync(AdoS8WatchRule body, S8TrustedScope scope)
  26. {
  27. body.TenantId = scope.TenantId;
  28. body.FactoryId = scope.FactoryId;
  29. await ValidateAsync(body, scope);
  30. body.Id = 0;
  31. body.CreatedAt = DateTime.Now;
  32. await _rep.InsertAsync(body);
  33. return body;
  34. }
  35. // S8-TENANT-FACTORY-P0-CLOSURE-1:按 Id + 可信作用域绑行;越权 Id 视为不存在,归属不可被 body 改写。
  36. public async Task<AdoS8WatchRule> UpdateAsync(long id, AdoS8WatchRule body, S8TrustedScope scope)
  37. {
  38. var e = await LoadScopedAsync(id, scope);
  39. body.TenantId = e.TenantId;
  40. body.FactoryId = e.FactoryId;
  41. await ValidateAsync(body, scope, id);
  42. body.Id = id;
  43. body.CreatedAt = e.CreatedAt;
  44. body.UpdatedAt = DateTime.Now;
  45. await _rep.UpdateAsync(body);
  46. return body;
  47. }
  48. // S8-TENANT-FACTORY-P0-CLOSURE-1:删除必须先按可信作用域绑行,禁止裸 DeleteByIdAsync(id)。
  49. public async Task DeleteAsync(long id, S8TrustedScope scope)
  50. {
  51. var e = await LoadScopedAsync(id, scope);
  52. await _rep.DeleteByIdAsync(e.Id);
  53. }
  54. /// <summary>按 Id + 可信作用域取行;不在作用域内一律按「不存在」处理,不泄露他租户资源是否存在。</summary>
  55. private async Task<AdoS8WatchRule> LoadScopedAsync(long id, S8TrustedScope scope) =>
  56. await _rep.AsQueryable()
  57. .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
  58. .FirstAsync() ?? throw new S8NotFoundException();
  59. /// <summary>
  60. /// R4 安全更新:只更新 params_json 与 enabled。expression / rule_code / data_source_id /
  61. /// scene_code / watch_object_type / rule_type / source_object_type 一律不通过此路径修改。
  62. /// 当 RuleType 非空时,按对应 evaluator 的 Params.Parse 进行 schema 校验,解析失败抛 S8BizException。
  63. /// </summary>
  64. public async Task<AdoS8WatchRule> UpdateParamsAsync(long id, S8WatchRuleParamsPayload payload, S8TrustedScope scope)
  65. {
  66. var entity = await LoadScopedAsync(id, scope);
  67. var paramsJson = payload.ParamsJson?.Trim();
  68. if (!string.IsNullOrEmpty(paramsJson))
  69. {
  70. ValidateParamsJsonByRuleType(entity.RuleType, paramsJson);
  71. }
  72. entity.ParamsJson = string.IsNullOrEmpty(paramsJson) ? null : paramsJson;
  73. entity.Enabled = payload.Enabled;
  74. // TASK-002-RESET-DIMENSION-MODEL-DEV-2B:维度归属 + 报警机制按 payload 原样落库(含 null 清空)。
  75. entity.StageCode = NormalizeOrNull(payload.StageCode);
  76. entity.OrderFlowCode = NormalizeOrNull(payload.OrderFlowCode);
  77. entity.RuleMechanism = NormalizeOrNull(payload.RuleMechanism);
  78. entity.UpdatedAt = DateTime.Now;
  79. await _rep.UpdateAsync(entity);
  80. return entity;
  81. }
  82. private static string? NormalizeOrNull(string? value)
  83. {
  84. if (string.IsNullOrWhiteSpace(value)) return null;
  85. var trimmed = value.Trim();
  86. return trimmed.Length == 0 ? null : trimmed;
  87. }
  88. private static void ValidateParamsJsonByRuleType(string? ruleType, string paramsJson)
  89. {
  90. try
  91. {
  92. switch (ruleType)
  93. {
  94. case S8TimeoutRuleEvaluator.RuleTypeCode:
  95. {
  96. var p = S8TimeoutParams.Parse(paramsJson);
  97. if (string.IsNullOrWhiteSpace(p.DueAtField)
  98. || string.IsNullOrWhiteSpace(p.StatusField)
  99. || string.IsNullOrWhiteSpace(p.ExceptionTypeCode))
  100. throw new S8BizException("TIMEOUT params 缺少必填字段:dueAtField / statusField / exceptionTypeCode");
  101. break;
  102. }
  103. case S8ShortageRuleEvaluator.RuleTypeCode:
  104. {
  105. var p = S8ShortageParams.Parse(paramsJson);
  106. if (string.IsNullOrWhiteSpace(p.TargetQtyField)
  107. || string.IsNullOrWhiteSpace(p.ActualQtyField)
  108. || string.IsNullOrWhiteSpace(p.ExceptionTypeCode))
  109. throw new S8BizException("SHORTAGE params 缺少必填字段:targetQtyField / actualQtyField / exceptionTypeCode");
  110. break;
  111. }
  112. case S8OutOfRangeRuleEvaluator.RuleTypeCode:
  113. {
  114. var p = S8OutOfRangeParams.Parse(paramsJson);
  115. if (string.IsNullOrWhiteSpace(p.MeasuredValueField))
  116. throw new S8BizException("OUT_OF_RANGE params 缺少必填字段:measuredValueField");
  117. if (p.LowerBound == null && p.UpperBound == null
  118. && string.IsNullOrWhiteSpace(p.LowerBoundField)
  119. && string.IsNullOrWhiteSpace(p.UpperBoundField))
  120. throw new S8BizException("OUT_OF_RANGE params 必须提供 upperBound / lowerBound 或对应行内字段之一");
  121. break;
  122. }
  123. default:
  124. // RuleType 为空或非三类已知值:仅做 JSON 合法性校验,避免阻塞历史数据。
  125. using (JsonDocument.Parse(paramsJson)) { }
  126. break;
  127. }
  128. }
  129. catch (JsonException ex)
  130. {
  131. throw new S8BizException($"params_json 不是合法 JSON:{ex.Message}");
  132. }
  133. }
  134. public async Task<object> TestAsync(long id, S8TrustedScope scope)
  135. {
  136. var entity = await LoadScopedAsync(id, scope);
  137. await ValidateAsync(entity, scope, id);
  138. return new { id, success = true, message = "规则基础校验通过", pollIntervalSeconds = entity.PollIntervalSeconds };
  139. }
  140. // S8-SCHED-FRONTEND-1:远未来手工暂停哨兵值(与 SqlSugar DateTime 兼容;前端按 paused_until > now 判定)。
  141. private static readonly DateTime ManualPausedSentinel = new(9999, 12, 31, 23, 59, 59);
  142. /// <summary>
  143. /// S8-SCHED-FRONTEND-1:调度参数安全更新。仅修改 poll_interval_seconds / trigger_count_required /
  144. /// recover_count_required;不动 params_json / expression / rule_type / scene_code / data_source_id。
  145. /// </summary>
  146. public async Task<AdoS8WatchRule> UpdateScheduleAsync(long id, S8WatchRuleSchedulePayload payload, S8TrustedScope scope)
  147. {
  148. var entity = await LoadScopedAsync(id, scope);
  149. if (payload.PollIntervalSeconds < 60 || payload.PollIntervalSeconds > 86400)
  150. throw new S8BizException("poll_interval_seconds 必须在 60–86400 之间");
  151. if (payload.TriggerCountRequired < 1 || payload.TriggerCountRequired > 10)
  152. throw new S8BizException("trigger_count_required 必须在 1–10 之间");
  153. if (payload.RecoverCountRequired < 1 || payload.RecoverCountRequired > 10)
  154. throw new S8BizException("recover_count_required 必须在 1–10 之间");
  155. await _rep.Context.Updateable<AdoS8WatchRule>()
  156. .SetColumns(x => new AdoS8WatchRule
  157. {
  158. PollIntervalSeconds = payload.PollIntervalSeconds,
  159. TriggerCountRequired = payload.TriggerCountRequired,
  160. RecoverCountRequired = payload.RecoverCountRequired,
  161. UpdatedAt = DateTime.Now
  162. })
  163. .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
  164. .ExecuteCommandAsync();
  165. return await LoadScopedAsync(id, scope);
  166. }
  167. /// <summary>
  168. /// S8-SCHED-FRONTEND-1:立即执行一次。把 next_run_at 置为 NOW,让下个 tick 拾取。
  169. /// 不直接同步执行 evaluator;不阻塞请求;返回 200 + 提示。
  170. /// </summary>
  171. public async Task<object> RunNowAsync(long id, S8TrustedScope scope)
  172. {
  173. var entity = await LoadScopedAsync(id, scope);
  174. if (!entity.Enabled)
  175. throw new S8BizException("规则未启用,不能立即执行");
  176. var now = DateTime.Now;
  177. if (entity.PausedUntil.HasValue && entity.PausedUntil.Value > now)
  178. throw new S8BizException("规则已暂停,请先恢复");
  179. if (entity.LockUntil.HasValue && entity.LockUntil.Value > now)
  180. throw new S8BizException("规则正在执行中,请稍后再试");
  181. await _rep.Context.Updateable<AdoS8WatchRule>()
  182. .SetColumns(x => new AdoS8WatchRule
  183. {
  184. NextRunAt = now,
  185. UpdatedAt = now
  186. })
  187. .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
  188. .ExecuteCommandAsync();
  189. return new { id, queued = true, message = "已排队,最长 1 分钟内执行" };
  190. }
  191. /// <summary>
  192. /// S8-SCHED-FRONTEND-1:手工暂停。paused_until = 9999-12-31 哨兵 + pause_reason=MANUAL_PAUSED。
  193. /// 不强杀正在执行的 lease;当前运行完成后下一轮自然不被拾取。
  194. /// 不清 last_status / last_error。
  195. /// </summary>
  196. public async Task<object> PauseAsync(long id, S8TrustedScope scope)
  197. {
  198. var entity = await LoadScopedAsync(id, scope);
  199. await _rep.Context.Updateable<AdoS8WatchRule>()
  200. .SetColumns(x => new AdoS8WatchRule
  201. {
  202. PausedUntil = ManualPausedSentinel,
  203. PauseReason = "MANUAL_PAUSED",
  204. UpdatedAt = DateTime.Now
  205. })
  206. .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
  207. .ExecuteCommandAsync();
  208. return new { id, paused = true, message = "已暂停" };
  209. }
  210. /// <summary>
  211. /// S8-SCHED-FRONTEND-1:恢复。清 paused_until / pause_reason / last_error;归零 consecutive_failure_count;
  212. /// next_run_at = NOW 让下个 tick 立即拾取。不改 enabled / params_json / rule_type。
  213. /// </summary>
  214. public async Task<object> ResumeAsync(long id, S8TrustedScope scope)
  215. {
  216. var entity = await LoadScopedAsync(id, scope);
  217. var now = DateTime.Now;
  218. await _rep.Context.Updateable<AdoS8WatchRule>()
  219. .SetColumns(x => new AdoS8WatchRule
  220. {
  221. PausedUntil = null,
  222. PauseReason = null,
  223. ConsecutiveFailureCount = 0,
  224. LastError = null,
  225. NextRunAt = now,
  226. UpdatedAt = now
  227. })
  228. .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
  229. .ExecuteCommandAsync();
  230. return new { id, resumed = true, message = "已恢复,并将在下一轮调度中执行" };
  231. }
  232. private async Task ValidateAsync(AdoS8WatchRule body, S8TrustedScope scope, long? id = null)
  233. {
  234. if (string.IsNullOrWhiteSpace(body.RuleCode) || string.IsNullOrWhiteSpace(body.SceneCode))
  235. throw new S8BizException("规则编码和场景编码必填");
  236. var exists = await _rep.AsQueryable()
  237. .AnyAsync(x => x.Id != (id ?? 0) && x.TenantId == body.TenantId && x.FactoryId == body.FactoryId && x.RuleCode == body.RuleCode);
  238. if (exists) throw new S8BizException("监视规则编码已存在");
  239. // S8-TENANT-FACTORY-P0-CLOSURE-1:关联数据源必须同属可信作用域,禁止引用他租户数据源。
  240. var dataSource = await _dataSourceRep.GetFirstAsync(
  241. x => x.Id == body.DataSourceId && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
  242. ?? throw new S8BizException("关联数据源不存在");
  243. if (!dataSource.Enabled) throw new S8BizException("关联数据源未启用");
  244. var scene = await _sceneRep.GetFirstAsync(x => x.TenantId == body.TenantId && x.FactoryId == body.FactoryId && x.SceneCode == body.SceneCode)
  245. ?? throw new S8BizException("关联场景不存在");
  246. if (!scene.Enabled) throw new S8BizException("关联场景未启用");
  247. if (body.PollIntervalSeconds <= 0) throw new S8BizException("轮询间隔必须大于 0");
  248. }
  249. }