S8WatchRuleService.cs 11 KB

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