S8WatchSchedulerService.cs 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  1. using Admin.NET.Plugin.AiDOP.Entity.S8;
  2. using Admin.NET.Plugin.AiDOP.Infrastructure.S8;
  3. using Admin.NET.Plugin.AiDOP.Service.S8.Rules;
  4. using Admin.NET.Plugin.AiDOP.Service.S8.Rules.DataAccess;
  5. using Admin.NET.Plugin.AiDOP.Service.S8.Rules.Definitions;
  6. using Microsoft.Extensions.Logging;
  7. using SqlSugar;
  8. using System.Globalization;
  9. using System.Text.Json;
  10. namespace Admin.NET.Plugin.AiDOP.Service.S8;
  11. /// <summary>
  12. /// 监视规则轮询调度服务(首轮存根)。
  13. /// 后续接入 Admin.NET 定时任务机制后,由调度器周期调用 <see cref="RunOnceAsync"/>,
  14. /// 按各规则的 PollIntervalSeconds 逐条评估并生成异常记录。
  15. /// </summary>
  16. public class S8WatchSchedulerService : ITransient
  17. {
  18. private readonly SqlSugarRepository<AdoS8WatchRule> _ruleRep;
  19. private readonly SqlSugarRepository<AdoS8Exception> _exceptionRep;
  20. private readonly SqlSugarRepository<AdoS8ExceptionType> _exceptionTypeRep;
  21. private readonly S8NotificationService _notificationService;
  22. private readonly S8NotificationLayerResolver _notificationLayerResolver;
  23. private readonly S8ImpactMetricsService _impactMetricsService;
  24. private readonly S8ManualReportService _manualReportService;
  25. // S8-STEP6E:Watch 主链的业务建单边界(唯一最窄 seam)。仅 :1482 的自动建单走它;
  26. // legacy debug 主链的 CreateFromWatchAsync 保持直连 _manualReportService,行为不变。
  27. private readonly IS8ExceptionReportDispatcher _reportDispatcher;
  28. private readonly S8TimeoutRuleEvaluator _timeoutEvaluator;
  29. private readonly S8ShortageRuleEvaluator _shortageEvaluator;
  30. private readonly S8OutOfRangeRuleEvaluator _outOfRangeEvaluator;
  31. private readonly ILogger<S8WatchSchedulerService> _logger;
  32. private readonly SqlSugarRepository<AdoS8DetectionLog> _detectionLogRep;
  33. private readonly SqlSugarRepository<AdoS8RuleDetectionState> _detectionStateRep;
  34. private readonly IS8RuleCatalog _ruleCatalog;
  35. private const string DetectionTriggerSource = "WATCH_SCHEDULER";
  36. private const string DetectResultCreated = "CREATED";
  37. private const string DetectResultRefreshed = "REFRESHED";
  38. private const string DetectResultRecovered = "RECOVERED";
  39. private const string DetectResultNoHit = "NO_HIT";
  40. private const string DetectResultEvaluateFailed = "EVALUATE_FAILED";
  41. // S8-DETECTION-LOG-WRITE-REDUCE-P1-1:REFRESHED 明细写入限频窗口。
  42. // 同 (tenant, factory, rule_code, dedup_key) 在 10 分钟内最多写一条 REFRESHED detection_log;
  43. // 业务侧 RefreshDetectionAsync / BackfillLegacyExceptionAsync 不受限频影响。
  44. private const int RefreshedRateLimitMinutes = 10;
  45. private const string DefaultTriggerType = "VALUE_DEVIATION";
  46. private const string SqlDataSourceType = "SQL";
  47. // G01-05 未闭环状态集合:复用自 S8ExceptionService 当前 pendingStatuses 事实口径
  48. // (见 S8ExceptionService.GetPagedAsync 中 pendingStatuses 的定义,两处必须保持一致)。
  49. // 这不是“自定义未闭环集合”;若现有口径调整,两处需同步修改。
  50. private static readonly string[] UnclosedExceptionStatuses =
  51. { "NEW", "ASSIGNED", "IN_PROGRESS", "PENDING_VERIFICATION" };
  52. public S8WatchSchedulerService(
  53. SqlSugarRepository<AdoS8WatchRule> ruleRep,
  54. SqlSugarRepository<AdoS8Exception> exceptionRep,
  55. SqlSugarRepository<AdoS8ExceptionType> exceptionTypeRep,
  56. S8NotificationService notificationService,
  57. S8NotificationLayerResolver notificationLayerResolver,
  58. S8ImpactMetricsService impactMetricsService,
  59. S8ManualReportService manualReportService,
  60. IS8ExceptionReportDispatcher reportDispatcher,
  61. S8TimeoutRuleEvaluator timeoutEvaluator,
  62. S8ShortageRuleEvaluator shortageEvaluator,
  63. S8OutOfRangeRuleEvaluator outOfRangeEvaluator,
  64. ILogger<S8WatchSchedulerService> logger,
  65. SqlSugarRepository<AdoS8DetectionLog> detectionLogRep,
  66. SqlSugarRepository<AdoS8RuleDetectionState> detectionStateRep,
  67. IS8RuleCatalog ruleCatalog)
  68. {
  69. _ruleRep = ruleRep;
  70. _exceptionRep = exceptionRep;
  71. _exceptionTypeRep = exceptionTypeRep;
  72. _notificationService = notificationService;
  73. _notificationLayerResolver = notificationLayerResolver;
  74. _impactMetricsService = impactMetricsService;
  75. _manualReportService = manualReportService;
  76. _reportDispatcher = reportDispatcher;
  77. _timeoutEvaluator = timeoutEvaluator;
  78. _shortageEvaluator = shortageEvaluator;
  79. _outOfRangeEvaluator = outOfRangeEvaluator;
  80. _logger = logger;
  81. _detectionLogRep = detectionLogRep;
  82. _detectionStateRep = detectionStateRep;
  83. _ruleCatalog = ruleCatalog;
  84. }
  85. public async Task<List<S8TenantFactoryScope>> ListEnabledScopesAsync()
  86. {
  87. return await _ruleRep.Context.Ado.SqlQueryAsync<S8TenantFactoryScope>(
  88. """
  89. SELECT DISTINCT r.tenant_id AS TenantId, r.factory_id AS FactoryId
  90. FROM ado_s8_watch_rule r
  91. INNER JOIN SysTenant t ON t.Id = r.tenant_id AND t.Status = 1
  92. WHERE r.enabled = 1
  93. AND r.tenant_id > 0
  94. AND r.factory_id > 0
  95. ORDER BY r.tenant_id, r.factory_id
  96. """);
  97. }
  98. // 取任意一条匹配的未闭环异常 Id 作为“是否存在重复单”的拦截依据。
  99. // 首版只需要“存在性”,不关心“最早 / 最新”;不在 G01-05 处理排序语义。
  100. /// <summary>
  101. /// 自动建单入口(debug run-once 使用;生产调度走 <see cref="RunDispatchTickAsync"/>)。
  102. ///
  103. /// S8-LEGACY-SQL-RESIDUAL-CLEANUP-3:原先此处还有一段旧 AlertRule 兼容主链
  104. /// (EvaluateDedupAsync → EvaluateHitsAsync → QueryDeviceRowsAsync → 直连 SQL),
  105. /// 该链自行开 SqlSugarScope 执行 rule.expression,
  106. /// 且只装载 rule_type 为空的未分类历史规则 + 需同场景恰好一条可运行 AlertRule。
  107. /// 经证实其唯一入口是 404 门禁的 debug controller,且 LoadExecutionRulesAsync 的过滤条件
  108. /// 在当前数据下恒返回空,已整体删除。本方法现在只保留三类正式 evaluator 路径。
  109. /// </summary>
  110. public async Task<List<S8WatchCreationResult>> CreateExceptionsAsync(long tenantId, long factoryId)
  111. {
  112. var results = new List<S8WatchCreationResult>();
  113. // R6 RunId:本次 CreateExceptionsAsync 调用对应的统一关联 id,落入 detection_log。
  114. var runId = Guid.NewGuid().ToString("N").Substring(0, 16);
  115. results.AddRange(await ProcessRulesByTypeAsync(tenantId, factoryId, _timeoutEvaluator, S8TimeoutRuleEvaluator.RuleTypeCode, runId));
  116. results.AddRange(await ProcessRulesByTypeAsync(tenantId, factoryId, _shortageEvaluator, S8ShortageRuleEvaluator.RuleTypeCode, runId));
  117. results.AddRange(await ProcessRulesByTypeAsync(tenantId, factoryId, _outOfRangeEvaluator, S8OutOfRangeRuleEvaluator.RuleTypeCode, runId));
  118. return results;
  119. }
  120. /// <summary>
  121. /// R2 TIMEOUT 类规则主链:薄包装,复用 <see cref="ProcessRulesByTypeAsync"/>。RunId 由内部生成。
  122. /// </summary>
  123. public Task<List<S8WatchCreationResult>> ProcessTimeoutRulesAsync(long tenantId, long factoryId) =>
  124. ProcessRulesByTypeAsync(tenantId, factoryId, _timeoutEvaluator, S8TimeoutRuleEvaluator.RuleTypeCode, Guid.NewGuid().ToString("N").Substring(0, 16));
  125. /// <summary>
  126. /// R3 SHORTAGE 类规则主链:薄包装,复用 <see cref="ProcessRulesByTypeAsync"/>。RunId 由内部生成。
  127. /// </summary>
  128. public Task<List<S8WatchCreationResult>> ProcessShortageRulesAsync(long tenantId, long factoryId) =>
  129. ProcessRulesByTypeAsync(tenantId, factoryId, _shortageEvaluator, S8ShortageRuleEvaluator.RuleTypeCode, Guid.NewGuid().ToString("N").Substring(0, 16));
  130. /// <summary>
  131. /// R3-OUT_OF_RANGE-REWRITE-1:OUT_OF_RANGE 类规则主链。
  132. /// 复用 <see cref="ProcessRulesByTypeAsync"/>,并对历史 dedup_key=NULL 的旧记录做 compat fallback:
  133. /// (source_rule_id=rule.Id AND related_object_code=hit AND status!=CLOSED AND dedup_key IS NULL AND is_deleted=0)
  134. /// 命中则 backfill 6 列,避免重复建单。RunId 由内部生成。
  135. /// </summary>
  136. public Task<List<S8WatchCreationResult>> ProcessOutOfRangeRulesAsync(long tenantId, long factoryId) =>
  137. ProcessRulesByTypeAsync(tenantId, factoryId, _outOfRangeEvaluator, S8OutOfRangeRuleEvaluator.RuleTypeCode, Guid.NewGuid().ToString("N").Substring(0, 16));
  138. /// <summary>
  139. /// R2/R3 通用规则主链。S8-SCHED-CLEANUP-LEGACY-PATH-1:本方法已收敛为 thin wrapper,
  140. /// 单规则处理(evaluator → reconcile → hit 循环 → CREATED/REFRESHED/NO_HIT/EVALUATE_FAILED 日志)
  141. /// 全部下沉至 <see cref="ProcessSingleRuleAsync"/>,与 Job tick 路径
  142. /// (<see cref="RunDispatchTickAsync"/> → <see cref="RunSingleRuleAsync"/> → ProcessSingleRuleAsync)
  143. /// 共享同一份逻辑,避免双维护。
  144. ///
  145. /// 调用方仅有 <see cref="CreateExceptionsAsync"/>(debug run-once / Process*RulesAsync 公共薄包装)。
  146. /// debug run-once 不持 lease(保留"手动立即跑"语义),但本方法在每条规则结束时通过
  147. /// <see cref="ApplyRunOnceCompletionAsync"/> 同步更新 watch_rule.last_run_at / last_status /
  148. /// last_error / last_duration_ms / last_run_id / consecutive_failure_count,缩小 run-once 与
  149. /// Job tick 之间的 last_* 状态分裂;不动 lock_token / running_started_at / paused_until,避免
  150. /// 与正在持锁运行的 Job 撕扯。
  151. /// </summary>
  152. private async Task<List<S8WatchCreationResult>> ProcessRulesByTypeAsync(
  153. long tenantId, long factoryId, IS8RuleEvaluator evaluator, string ruleType, string runId)
  154. {
  155. var aggregate = new List<S8WatchCreationResult>();
  156. var rules = await _ruleRep.AsQueryable()
  157. .Where(x => x.TenantId == tenantId
  158. && x.FactoryId == factoryId
  159. && x.Enabled
  160. && x.RuleType == ruleType)
  161. .ToListAsync();
  162. if (rules.Count == 0) return aggregate;
  163. foreach (var rule in rules.OrderBy(x => x.Id))
  164. {
  165. // S8-RULE-GOVERNANCE-BATCH1:无代码定义的规则不进入执行链(与 Job tick 路径同一口径)。
  166. if (!_ruleCatalog.IsDefined(rule.RuleCode))
  167. {
  168. _logger.LogWarning(
  169. "run_once_skip_no_definition ruleId={RuleId} ruleCode={RuleCode}", rule.Id, rule.RuleCode);
  170. aggregate.Add(BuildSkipResult(rule, S8RuleCatalog.ReasonNotFound, null));
  171. continue;
  172. }
  173. // S8-RUN-ONCE-LEASE-AWARENESS-1:debug run-once 不持 lease,但若该 rule 已被 Scheduler Job
  174. // 通过 PickReadyRulesAsync 抢锁(lock_token 非空且 lock_until > now),run-once 跳过该 rule,
  175. // 不写 last_*、不写 detection_log、不动锁,以避免与 Job tick 并发评估同一 rule 而互相覆盖运行态。
  176. // 锁状态用 ToListAsync 的初始快照判定;run-once 与 Job 的微秒级竞速无法在不抢 lease 的前提下
  177. // 完全消除(已登记为 follow-up 风险)。
  178. if (!string.IsNullOrEmpty(rule.LockToken)
  179. && rule.LockUntil.HasValue
  180. && rule.LockUntil.Value > DateTime.Now)
  181. {
  182. _logger.LogInformation(
  183. "run_once_skip_locked ruleId={RuleId} ruleCode={RuleCode} ruleType={RuleType} lockToken={Token} lockedBy={By} lockUntil={Until}",
  184. rule.Id, rule.RuleCode, ruleType, rule.LockToken, rule.LockedBy, rule.LockUntil);
  185. aggregate.Add(BuildSkipResult(rule, "rule_locked_by_scheduler", null));
  186. continue;
  187. }
  188. var sw = System.Diagnostics.Stopwatch.StartNew();
  189. S8RuleRunResult completion;
  190. try
  191. {
  192. var ruleResults = await ProcessSingleRuleAsync(tenantId, factoryId, rule, ruleType, evaluator, runId);
  193. aggregate.AddRange(ruleResults);
  194. completion = new S8RuleRunResult
  195. {
  196. Success = true,
  197. Stats = new S8RuleRunStats
  198. {
  199. Hits = ruleResults.Count,
  200. Created = ruleResults.Count(r => r.Created),
  201. Refreshed = ruleResults.Count(r => r.Reason == "duplicate_pending"),
  202. Pending = ruleResults.Count(r => r.Reason == "antiflap_pending_hit"),
  203. Failed = ruleResults.Count(r => r.Reason == "create_failed" || r.Reason == "refresh_failed" || r.Reason == "antiflap_failed" || r.Reason == "evaluate_failed")
  204. }
  205. };
  206. }
  207. catch (Exception ex)
  208. {
  209. // ProcessSingleRuleAsync 在 evaluator 抛 S8RuleEvaluatorException 时已写 EVALUATE_FAILED
  210. // detection_log 后再 throw(供 RunSingleRuleAsync 标 Success=false)。本路径无 lease,
  211. // 吞异常以保留"逐规则失败不影响其他规则"的旧 ProcessRulesByTypeAsync 语义。
  212. _logger.LogWarning(ex, "process_rule_failed ruleCode={RuleCode} ruleType={RuleType}", rule.RuleCode, ruleType);
  213. aggregate.Add(BuildSkipResult(rule, "evaluate_failed", ex.Message));
  214. completion = new S8RuleRunResult { Success = false, ErrorMessage = ex.Message, Stats = new() };
  215. }
  216. sw.Stop();
  217. try
  218. {
  219. await ApplyRunOnceCompletionAsync(rule, completion, (int)sw.ElapsedMilliseconds, runId);
  220. }
  221. catch (Exception ex)
  222. {
  223. _logger.LogWarning(ex, "run_once_completion_write_failed ruleCode={RuleCode} ruleType={RuleType}", rule.RuleCode, ruleType);
  224. }
  225. }
  226. return aggregate;
  227. }
  228. /// <summary>
  229. /// S8-SCHED-CLEANUP-LEGACY-PATH-1:debug run-once 的 last_* 状态回写(无 lease 版)。
  230. /// 与 <see cref="OnRuleCompletedAsync"/> 的语义平行,差异在于:
  231. /// - 不要求 lock_token 匹配(run-once 不持 lease)
  232. /// - 不写 lock_token / locked_by / lock_until / running_started_at(不与 Job lease 撕扯)
  233. /// - 不做 consecutive_failure_count 阈值的 paused_until 自动暂停(debug 路径不应自动暂停 demo rule)
  234. /// 写入:last_run_at / next_run_at / last_status / last_error / last_duration_ms / last_run_id /
  235. /// consecutive_failure_count / updated_at。
  236. /// </summary>
  237. private async Task ApplyRunOnceCompletionAsync(AdoS8WatchRule rule, S8RuleRunResult result, int durationMs, string runId)
  238. {
  239. var now = DateTime.Now;
  240. var nextRunAt = now.AddSeconds(NormalizePollInterval(rule.PollIntervalSeconds));
  241. if (result.Success)
  242. {
  243. await _ruleRep.Context.Updateable<AdoS8WatchRule>()
  244. .SetColumns(x => new AdoS8WatchRule
  245. {
  246. LastRunAt = now,
  247. NextRunAt = nextRunAt,
  248. LastStatus = "SUCCESS",
  249. LastError = null,
  250. LastDurationMs = durationMs,
  251. LastRunId = runId,
  252. ConsecutiveFailureCount = 0,
  253. UpdatedAt = now
  254. })
  255. .Where(x => x.Id == rule.Id)
  256. .ExecuteCommandAsync();
  257. }
  258. else
  259. {
  260. var errorTrunc = Truncate(result.ErrorMessage, 500);
  261. await _ruleRep.Context.Updateable<AdoS8WatchRule>()
  262. .SetColumns(x => new AdoS8WatchRule
  263. {
  264. LastRunAt = now,
  265. NextRunAt = nextRunAt,
  266. LastStatus = "FAILED",
  267. LastError = errorTrunc,
  268. LastDurationMs = durationMs,
  269. LastRunId = runId,
  270. ConsecutiveFailureCount = x.ConsecutiveFailureCount + 1,
  271. UpdatedAt = now
  272. })
  273. .Where(x => x.Id == rule.Id)
  274. .ExecuteCommandAsync();
  275. }
  276. }
  277. // S8-SCHED-EXEC-1:trigger / recover 抗抖计数兜底,null / <1 / >10 一律按 1,避免非法配置导致永远不建单 / 永远不恢复。
  278. private static int NormalizeAntiflapCount(int raw)
  279. {
  280. if (raw < 1 || raw > 10) return 1;
  281. return raw;
  282. }
  283. /// <summary>
  284. /// 命中时累加 detection_state.consecutive_hit_count;未存在则插入 hitCount=1。
  285. /// 返回当前 state 行(含 Id)以及命中后的 hitCount。
  286. /// 注意:本函数不消费 trigger_count_required;上游决定是否进入 CreateFromHitAsync。
  287. /// </summary>
  288. private async Task<(AdoS8RuleDetectionState? state, int hitCount)> UpsertDetectionStateOnHitAsync(
  289. long tenantId, long factoryId, AdoS8WatchRule rule, S8RuleHit hit)
  290. {
  291. var now = DateTime.Now;
  292. var existing = await _detectionStateRep.AsQueryable()
  293. .Where(x => x.TenantId == tenantId
  294. && x.FactoryId == factoryId
  295. && x.RuleCode == rule.RuleCode
  296. && x.DedupKey == hit.DedupKey)
  297. .FirstAsync();
  298. if (existing == null)
  299. {
  300. var fresh = new AdoS8RuleDetectionState
  301. {
  302. TenantId = tenantId,
  303. FactoryId = factoryId,
  304. RuleCode = rule.RuleCode,
  305. DedupKey = hit.DedupKey,
  306. SourceObjectType = string.IsNullOrEmpty(hit.SourceObjectType) ? null : hit.SourceObjectType,
  307. SourceObjectId = string.IsNullOrEmpty(hit.SourceObjectId) ? null : hit.SourceObjectId,
  308. ConsecutiveHitCount = 1,
  309. ConsecutiveMissCount = 0,
  310. LastSeenAt = now,
  311. LastHitAt = now,
  312. CreatedAt = now,
  313. UpdatedAt = now
  314. };
  315. // BUG-S8-DETECTION-STATE-ACTIVE-EXC-ID-TRIGGER1-001:必须回填 fresh.Id,否则
  316. // trigger=1 首 tick 建单后 UPDATE state SET active_exception_id WHERE id=state.Id
  317. // 命中 0 行(state.Id 为默认 0)。沿用 S8ManualReportService 既定模式。
  318. fresh = await _detectionStateRep.AsInsertable(fresh).ExecuteReturnEntityAsync();
  319. return (fresh, 1);
  320. }
  321. var newHitCount = existing.ConsecutiveHitCount + 1;
  322. await _detectionStateRep.Context.Updateable<AdoS8RuleDetectionState>()
  323. .SetColumns(x => new AdoS8RuleDetectionState
  324. {
  325. ConsecutiveHitCount = x.ConsecutiveHitCount + 1,
  326. ConsecutiveMissCount = 0,
  327. LastSeenAt = now,
  328. LastHitAt = now,
  329. SourceObjectType = string.IsNullOrEmpty(hit.SourceObjectType) ? existing.SourceObjectType : hit.SourceObjectType,
  330. SourceObjectId = string.IsNullOrEmpty(hit.SourceObjectId) ? existing.SourceObjectId : hit.SourceObjectId,
  331. UpdatedAt = now
  332. })
  333. .Where(x => x.Id == existing.Id)
  334. .ExecuteCommandAsync();
  335. existing.ConsecutiveHitCount = newHitCount;
  336. return (existing, newHitCount);
  337. }
  338. private async Task<long> FindOpenExceptionByDedupKeyAsync(long tenantId, long factoryId, string dedupKey)
  339. {
  340. var ids = await _exceptionRep.AsQueryable()
  341. .Where(x => x.TenantId == tenantId
  342. && x.FactoryId == factoryId
  343. && !x.IsDeleted
  344. && x.Status != "CLOSED"
  345. && x.DedupKey == dedupKey)
  346. .Select(x => x.Id)
  347. .Take(1)
  348. .ToListAsync();
  349. return ids.Count > 0 ? ids[0] : 0L;
  350. }
  351. /// <summary>
  352. /// R3 OUT_OF_RANGE compat fallback 查找:用 (source_rule_id, related_object_code, status!=CLOSED,
  353. /// dedup_key IS NULL, is_deleted=0) 严格条件定位旧 AlertRule 主链留下的历史记录。
  354. /// </summary>
  355. private async Task<long> FindLegacyOutOfRangeExceptionAsync(long tenantId, long factoryId, long sourceRuleId, string relatedObjectCode)
  356. {
  357. if (string.IsNullOrWhiteSpace(relatedObjectCode)) return 0L;
  358. var ids = await _exceptionRep.AsQueryable()
  359. .Where(x => x.TenantId == tenantId
  360. && x.FactoryId == factoryId
  361. && !x.IsDeleted
  362. && x.Status != "CLOSED"
  363. && x.DedupKey == null
  364. && x.SourceRuleId == sourceRuleId
  365. && x.RelatedObjectCode == relatedObjectCode)
  366. .Select(x => x.Id)
  367. .Take(1)
  368. .ToListAsync();
  369. return ids.Count > 0 ? ids[0] : 0L;
  370. }
  371. /// <summary>
  372. /// R3 OUT_OF_RANGE compat fallback backfill:把历史记录的 R1 新 6 列(dedup_key/source_rule_code/
  373. /// source_object_type/source_object_id/source_payload/last_detected_at)写入,并刷新 updated_at。
  374. /// </summary>
  375. private async Task BackfillLegacyExceptionAsync(long exceptionId, S8RuleHit hit)
  376. {
  377. await _exceptionRep.Context.Updateable<AdoS8Exception>()
  378. .SetColumns(x => new AdoS8Exception
  379. {
  380. DedupKey = hit.DedupKey,
  381. SourceRuleCode = hit.SourceRuleCode,
  382. SourceObjectType = hit.SourceObjectType,
  383. SourceObjectId = hit.SourceObjectId,
  384. SourcePayload = hit.SourcePayload,
  385. LastDetectedAt = hit.DetectedAt,
  386. UpdatedAt = DateTime.Now
  387. })
  388. .Where(x => x.Id == exceptionId)
  389. .ExecuteCommandAsync();
  390. }
  391. /// <summary>
  392. /// R5 恢复时间最小闭环:对当前 rule 下未关闭、有 dedup_key、recovered_at 仍为 NULL 的异常,
  393. /// 凡不在本轮 hits.dedup_key 集合内的,写入 recovered_at = now、updated_at = now。
  394. /// 仅写这 2 列;不动 status / assignee / verifier / source_payload / last_detected_at;
  395. /// recovered_at 一旦写入,本轮不做复发清空。
  396. /// R6 返回 recoveredIds 供上游决定是否写 NO_HIT 日志,并对每个 recovered exception 写一条 RECOVERED 日志。
  397. /// </summary>
  398. private async Task<List<long>> ReconcileRecoveriesForRuleAsync(
  399. long tenantId, long factoryId, AdoS8WatchRule rule, string ruleType, List<S8RuleHit> hits, string runId)
  400. {
  401. var hitDedupKeys = hits
  402. .Where(h => !string.IsNullOrWhiteSpace(h.DedupKey))
  403. .Select(h => h.DedupKey)
  404. .ToHashSet(StringComparer.Ordinal);
  405. var candidates = await _exceptionRep.AsQueryable()
  406. .Where(x => x.TenantId == tenantId
  407. && x.FactoryId == factoryId
  408. && !x.IsDeleted
  409. && x.Status != "CLOSED"
  410. && x.SourceRuleCode == rule.RuleCode
  411. && x.DedupKey != null
  412. && x.RecoveredAt == null)
  413. .Select(x => new { x.Id, x.DedupKey, x.SourceObjectType, x.SourceObjectId, x.RelatedObjectCode, x.ConsecutiveMissCount })
  414. .ToListAsync();
  415. if (candidates.Count == 0) return new List<long>();
  416. var now = DateTime.Now;
  417. var recoverRequired = NormalizeAntiflapCount(rule.RecoverCountRequired);
  418. var recoveredIds = new List<long>();
  419. foreach (var c in candidates)
  420. {
  421. if (hitDedupKeys.Contains(c.DedupKey!)) continue;
  422. // S8-SCHED-EXEC-1:恢复抗抖累计。
  423. // 1) 每次未命中:异常 ConsecutiveMissCount += 1,ConsecutiveHitCount 清零;
  424. // 2) miss < recover_count_required:仅累计,不写 recovered_at、不写 RECOVERED;
  425. // 3) miss >= recover_count_required:写 recovered_at、写 RECOVERED 日志。
  426. var newMissCount = c.ConsecutiveMissCount + 1;
  427. await _exceptionRep.Context.Updateable<AdoS8Exception>()
  428. .SetColumns(x => new AdoS8Exception
  429. {
  430. ConsecutiveMissCount = x.ConsecutiveMissCount + 1,
  431. ConsecutiveHitCount = 0,
  432. UpdatedAt = now
  433. })
  434. .Where(x => x.Id == c.Id)
  435. .ExecuteCommandAsync();
  436. // detection_state 同步累计 miss(建单后 state.active_exception_id 仍指向 c.Id)。
  437. await _detectionStateRep.Context.Updateable<AdoS8RuleDetectionState>()
  438. .SetColumns(x => new AdoS8RuleDetectionState
  439. {
  440. ConsecutiveMissCount = x.ConsecutiveMissCount + 1,
  441. ConsecutiveHitCount = 0,
  442. LastSeenAt = now,
  443. LastMissAt = now,
  444. UpdatedAt = now
  445. })
  446. .Where(x => x.TenantId == tenantId
  447. && x.FactoryId == factoryId
  448. && x.RuleCode == rule.RuleCode
  449. && x.DedupKey == c.DedupKey)
  450. .ExecuteCommandAsync();
  451. if (newMissCount < recoverRequired)
  452. {
  453. _logger.LogInformation(
  454. "antiflap_pending_recovery ruleCode={RuleCode} dedupKey={DedupKey} missCount={Miss} recoverRequired={Required}",
  455. rule.RuleCode, c.DedupKey, newMissCount, recoverRequired);
  456. continue;
  457. }
  458. await _exceptionRep.Context.Updateable<AdoS8Exception>()
  459. .SetColumns(x => new AdoS8Exception
  460. {
  461. RecoveredAt = now,
  462. UpdatedAt = now
  463. })
  464. .Where(x => x.Id == c.Id)
  465. .ExecuteCommandAsync();
  466. recoveredIds.Add(c.Id);
  467. await WriteDetectionLogAsync(new AdoS8DetectionLog
  468. {
  469. TenantId = tenantId, FactoryId = factoryId,
  470. RuleId = rule.Id, RuleCode = rule.RuleCode, RuleType = ruleType, SceneCode = rule.SceneCode,
  471. SourceObjectType = c.SourceObjectType, SourceObjectId = c.SourceObjectId,
  472. RelatedObjectCode = c.RelatedObjectCode, DedupKey = c.DedupKey,
  473. DetectResult = DetectResultRecovered,
  474. ExceptionId = c.Id,
  475. DetectedAt = now,
  476. PayloadSnapshot = JsonSerializer.Serialize(new { ruleId = rule.Id, ruleCode = rule.RuleCode, reason = "no_longer_hit", missCount = newMissCount, recoverRequired }),
  477. RunId = runId, TriggerSource = DetectionTriggerSource,
  478. Remark = "Rule no longer hit; recovered_at marked"
  479. });
  480. // S8-NOTIFY-WIRE-RECOVERED-1:detection_log 已写入、recovered_at 已落库后挂入恢复通知。
  481. // 通知失败仅 LogWarning,绝不影响恢复状态/检测日志。
  482. await TryDispatchRecoveredLayerNotificationAsync(c.Id);
  483. }
  484. if (recoveredIds.Count > 0)
  485. {
  486. _logger.LogInformation(
  487. "rule_recovered ruleCode={RuleCode} ruleType={RuleType} recoveredCount={Count} recoveredIds={Ids}",
  488. rule.RuleCode, ruleType, recoveredIds.Count, string.Join(",", recoveredIds));
  489. }
  490. return recoveredIds;
  491. }
  492. /// <summary>R6 通用 hit 日志构造(CREATED / REFRESHED 共用)。</summary>
  493. private static AdoS8DetectionLog BuildHitLog(
  494. long tenantId, long factoryId, AdoS8WatchRule rule, string ruleType, S8RuleHit hit,
  495. string detectResult, long exceptionId, string runId) => new()
  496. {
  497. TenantId = tenantId, FactoryId = factoryId,
  498. RuleId = rule.Id, RuleCode = rule.RuleCode, RuleType = ruleType, SceneCode = rule.SceneCode,
  499. SourceObjectType = hit.SourceObjectType, SourceObjectId = hit.SourceObjectId,
  500. RelatedObjectCode = hit.RelatedObjectCode, DedupKey = hit.DedupKey,
  501. DetectResult = detectResult,
  502. ExceptionId = exceptionId,
  503. DetectedAt = hit.DetectedAt,
  504. PayloadSnapshot = hit.SourcePayload,
  505. RunId = runId,
  506. TriggerSource = DetectionTriggerSource
  507. };
  508. /// <summary>R6 日志写入:失败仅 LogWarning,不阻断主链;不抛异常。</summary>
  509. private async Task WriteDetectionLogAsync(AdoS8DetectionLog log)
  510. {
  511. try
  512. {
  513. await _detectionLogRep.InsertAsync(log);
  514. }
  515. catch (Exception ex)
  516. {
  517. _logger.LogWarning(ex,
  518. "detection_log_write_failed runId={RunId} detectResult={Result} ruleCode={RuleCode} exceptionId={ExceptionId}",
  519. log.RunId, log.DetectResult, log.RuleCode, log.ExceptionId);
  520. }
  521. }
  522. /// <summary>
  523. /// S8-DETECTION-LOG-WRITE-REDUCE-P1-1:REFRESHED 明细限频判定。
  524. /// 查询 cutoff = detectedAt - RefreshedRateLimitMinutes 之后,
  525. /// 是否已有同 (tenant_id, factory_id, rule_code, dedup_key, DetectResult=REFRESHED) 的 detection_log;
  526. /// 命中既有索引 idx_s8_detection_log_dedup_time。查询失败仅 LogWarning 后返回 false,
  527. /// 宁可多写一条 REFRESHED 明细,也不阻断调度主链路;ruleCode / dedupKey 空白时同样返回 false(保留写入)。
  528. /// 业务侧 RefreshDetectionAsync / BackfillLegacyExceptionAsync 不在限频范围。
  529. /// </summary>
  530. private async Task<bool> HasRecentRefreshedDetectionLogAsync(
  531. long tenantId, long factoryId, string ruleCode, string dedupKey, DateTime detectedAt)
  532. {
  533. if (string.IsNullOrWhiteSpace(ruleCode) || string.IsNullOrWhiteSpace(dedupKey))
  534. return false;
  535. var cutoff = detectedAt.AddMinutes(-RefreshedRateLimitMinutes);
  536. try
  537. {
  538. return await _detectionLogRep.AsQueryable()
  539. .Where(x => x.TenantId == tenantId
  540. && x.FactoryId == factoryId
  541. && x.DedupKey == dedupKey
  542. && x.RuleCode == ruleCode
  543. && x.DetectResult == DetectResultRefreshed
  544. && x.DetectedAt >= cutoff)
  545. .AnyAsync();
  546. }
  547. catch (Exception ex)
  548. {
  549. _logger.LogWarning(ex,
  550. "detection_log_refreshed_ratelimit_check_failed ruleCode={RuleCode} dedupKey={DedupKey}",
  551. ruleCode, dedupKey);
  552. return false;
  553. }
  554. }
  555. private static string Truncate(string? s, int max) =>
  556. string.IsNullOrEmpty(s) ? string.Empty : (s.Length <= max ? s : s.Substring(0, max));
  557. private async Task RefreshDetectionAsync(long exceptionId, S8RuleHit hit)
  558. {
  559. // S8-SCHED-EXEC-1:刷新阶段抗抖累计 + 复发清空 recovered_at。
  560. // ConsecutiveHitCount += 1(用 SetColumns 内表达式完成原子自增);ConsecutiveMissCount 归零。
  561. // RecoveredAt 不为 NULL 时(复发)一并清空,保持业务对"再次命中即视为活跃"的预期。
  562. await _exceptionRep.Context.Updateable<AdoS8Exception>()
  563. .SetColumns(x => new AdoS8Exception
  564. {
  565. LastDetectedAt = hit.DetectedAt,
  566. SourcePayload = hit.SourcePayload,
  567. ConsecutiveHitCount = x.ConsecutiveHitCount + 1,
  568. ConsecutiveMissCount = 0,
  569. RecoveredAt = null,
  570. UpdatedAt = DateTime.Now
  571. })
  572. .Where(x => x.Id == exceptionId)
  573. .ExecuteCommandAsync();
  574. }
  575. private static S8WatchCreationResult BuildCreatedResult(AdoS8WatchRule rule, S8RuleHit hit, long exceptionId) =>
  576. new()
  577. {
  578. DedupResult = new S8WatchDedupResult
  579. {
  580. Hit = ToWatchHit(rule, hit),
  581. CanCreate = true,
  582. MatchedExceptionId = null,
  583. Reason = "no_pending"
  584. },
  585. Created = true,
  586. Skipped = false,
  587. CreatedExceptionId = exceptionId,
  588. Reason = "auto_created",
  589. ErrorMessage = null
  590. };
  591. private static S8WatchCreationResult BuildSkippedDuplicate(AdoS8WatchRule rule, S8RuleHit hit, long matchedId) =>
  592. new()
  593. {
  594. DedupResult = new S8WatchDedupResult
  595. {
  596. Hit = ToWatchHit(rule, hit),
  597. CanCreate = false,
  598. MatchedExceptionId = matchedId,
  599. Reason = "duplicate_pending"
  600. },
  601. Created = false,
  602. Skipped = true,
  603. CreatedExceptionId = null,
  604. Reason = "duplicate_pending",
  605. ErrorMessage = null
  606. };
  607. private static S8WatchCreationResult BuildSkipResult(AdoS8WatchRule rule, string reason, string? error, S8RuleHit? hit = null) =>
  608. new()
  609. {
  610. DedupResult = new S8WatchDedupResult
  611. {
  612. Hit = hit != null ? ToWatchHit(rule, hit) : new S8WatchHitResult { SourceRuleId = rule.Id, SourceRuleCode = rule.RuleCode },
  613. CanCreate = false,
  614. MatchedExceptionId = null,
  615. Reason = reason
  616. },
  617. Created = false,
  618. Skipped = true,
  619. CreatedExceptionId = null,
  620. Reason = reason,
  621. ErrorMessage = error
  622. };
  623. private static S8WatchHitResult ToWatchHit(AdoS8WatchRule rule, S8RuleHit hit) => new()
  624. {
  625. SourceRuleId = hit.SourceRuleId == 0 ? rule.Id : hit.SourceRuleId,
  626. SourceRuleCode = string.IsNullOrEmpty(hit.SourceRuleCode) ? rule.RuleCode : hit.SourceRuleCode,
  627. RelatedObjectCode = hit.RelatedObjectCode,
  628. Severity = hit.Severity,
  629. OccurrenceDeptId = hit.OccurrenceDeptId,
  630. ResponsibleDeptId = hit.ResponsibleDeptId,
  631. SourcePayload = hit.SourcePayload
  632. };
  633. // G01-04 首版最小比较符集合:>, >=, <, <=。
  634. // 允许首尾空格;非此集合的一律视为“比较符非法”,由调用方跳过。
  635. private static string NormalizeColumnName(string columnName) =>
  636. columnName.Replace("_", string.Empty, StringComparison.Ordinal).Trim().ToUpperInvariant();
  637. // ============================================================
  638. // S8-SCHED-EXEC-1:DB 驱动调度执行层
  639. // ============================================================
  640. private const int LeaseDurationMinutes = 5;
  641. private const int AutoPauseFailureThreshold = 3;
  642. private const int AutoPauseDurationHours = 1;
  643. private const int DefaultPollIntervalSeconds = 300;
  644. private const int MinPollIntervalSeconds = 60;
  645. private const int MaxPollIntervalSeconds = 86400;
  646. /// <summary>
  647. /// S8-SCHED-EXEC-1:释放过期 lease(lock_until &lt; NOW),不修改 last_status / last_error,仅清空 lock 三件套 + running_started_at。
  648. /// 返回释放的行数。
  649. /// </summary>
  650. public async Task<int> ResetExpiredLeasesAsync(long tenantId, long factoryId)
  651. {
  652. var now = DateTime.Now;
  653. var affected = await _ruleRep.Context.Updateable<AdoS8WatchRule>()
  654. .SetColumns(x => new AdoS8WatchRule
  655. {
  656. LockToken = null,
  657. LockedBy = null,
  658. LockUntil = null,
  659. RunningStartedAt = null,
  660. UpdatedAt = now
  661. })
  662. .Where(x => x.TenantId == tenantId
  663. && x.FactoryId == factoryId
  664. && x.LockUntil != null
  665. && x.LockUntil < now)
  666. .ExecuteCommandAsync();
  667. if (affected > 0)
  668. {
  669. _logger.LogWarning(
  670. "lease_reset tenantId={Tenant} factoryId={Factory} releasedCount={Count}",
  671. tenantId, factoryId, affected);
  672. }
  673. return affected;
  674. }
  675. /// <summary>
  676. /// S8-SCHED-EXEC-1:到期规则候选 + 乐观 UPDATE 抢锁,返回成功抢到的 lease 列表。
  677. /// 抢锁条件:enabled=1 AND (paused_until IS NULL OR paused_until &lt;= NOW)
  678. /// AND (next_run_at IS NULL OR next_run_at &lt;= NOW)
  679. /// AND (lock_until IS NULL OR lock_until &lt;= NOW)。
  680. /// 抢锁回写:lock_token / locked_by / lock_until = NOW + 5min / running_started_at = NOW / last_run_id = runId。
  681. /// affectedRows == 1 才算抢到;后续 OnRuleCompletedAsync 必须按 lockToken 回写,避免旧进程覆盖新 lease。
  682. /// </summary>
  683. public async Task<List<S8RuleLease>> PickReadyRulesAsync(long tenantId, long factoryId, int batchSize, string lockedBy, string runId)
  684. {
  685. if (batchSize <= 0) batchSize = 16;
  686. var now = DateTime.Now;
  687. var candidates = await _ruleRep.AsQueryable()
  688. .Where(x => x.TenantId == tenantId
  689. && x.FactoryId == factoryId
  690. && x.Enabled
  691. // S8-STANDARD-DATASET-HARD-CUTOVER-1:取数唯一依赖 dataset_code。
  692. // 保留这条谓词而非依赖 Enable Gate:Gate 只在"切换启用"那一刻生效,
  693. // 而 dataset_code 可能在此之后被清空(历史遗留行、直连改库)。
  694. // 一条没有数据集的规则跑起来只会每 tick 抛一次 dataset_code_missing。
  695. //
  696. // 刻意做成 **SQL 谓词而非内存过滤**:Take(batchSize) 在过滤之前生效,
  697. // 内存过滤会让无效候选占满名额,导致同租户的有效规则被饿死。
  698. && x.DatasetCode != null && x.DatasetCode != ""
  699. && (x.PausedUntil == null || x.PausedUntil <= now)
  700. && (x.NextRunAt == null || x.NextRunAt <= now)
  701. && (x.LockUntil == null || x.LockUntil <= now))
  702. .OrderBy(x => x.NextRunAt, OrderByType.Asc)
  703. .OrderBy(x => x.Id, OrderByType.Asc)
  704. .Take(batchSize)
  705. .Select(x => new { x.Id, x.RuleCode, x.RuleType })
  706. .ToListAsync();
  707. if (candidates.Count == 0) return new();
  708. var leases = new List<S8RuleLease>();
  709. foreach (var c in candidates)
  710. {
  711. var token = Guid.NewGuid().ToString("N");
  712. var lockUntil = DateTime.Now.AddMinutes(LeaseDurationMinutes);
  713. var runningAt = DateTime.Now;
  714. // 乐观 UPDATE:再校验一次条件,affectedRows=1 才算抢到。
  715. var affected = await _ruleRep.Context.Updateable<AdoS8WatchRule>()
  716. .SetColumns(x => new AdoS8WatchRule
  717. {
  718. LockToken = token,
  719. LockedBy = lockedBy,
  720. LockUntil = lockUntil,
  721. RunningStartedAt = runningAt,
  722. LastRunId = runId,
  723. UpdatedAt = runningAt
  724. })
  725. .Where(x => x.Id == c.Id
  726. && x.Enabled
  727. // 抢锁的乐观 UPDATE 复查同一条件:候选查询与本次 UPDATE 之间存在时间窗,
  728. // 期间该行的 dataset_code 可能被清空。
  729. && x.DatasetCode != null && x.DatasetCode != ""
  730. && (x.PausedUntil == null || x.PausedUntil <= runningAt)
  731. && (x.NextRunAt == null || x.NextRunAt <= runningAt)
  732. && (x.LockUntil == null || x.LockUntil <= runningAt))
  733. .ExecuteCommandAsync();
  734. if (affected == 1)
  735. {
  736. leases.Add(new S8RuleLease
  737. {
  738. RuleId = c.Id,
  739. RuleCode = c.RuleCode,
  740. RuleType = c.RuleType,
  741. LockToken = token,
  742. LockedBy = lockedBy,
  743. LockUntil = lockUntil,
  744. RunId = runId,
  745. AcquiredAt = runningAt
  746. });
  747. }
  748. }
  749. return leases;
  750. }
  751. /// <summary>
  752. /// S8-SCHED-EXEC-1:执行单条已抢锁规则的 evaluator → 抗抖去重 → 建单/刷新 → 恢复 reconcile。
  753. /// 不释放 lease(OnRuleCompletedAsync 负责);evaluator 抛异常时 Result.Success=false 并保留 ErrorMessage。
  754. /// </summary>
  755. public async Task<S8RuleRunResult> RunSingleRuleAsync(long tenantId, long factoryId, S8RuleLease lease)
  756. {
  757. // S8-P0-1-SCHEDULER-TRUSTED-SCOPE-1:执行入口必须按本次 tick 的可信作用域绑行。
  758. // 原实现只按 lease.RuleId 装载,不校验 rule 归属;一旦 lease 来源被改写 / 未来新增调用方,
  759. // 就会在 A 租户的 scope 上下文里执行 B 租户的规则,而下游全部以传入的 tenantId/factoryId 落库。
  760. // 这里同时做「谓词绑行」与「归属复核」两层,任一不符即 fail-fast,绝不静默降级。
  761. var rule = await _ruleRep.AsQueryable()
  762. .Where(x => x.Id == lease.RuleId && x.TenantId == tenantId && x.FactoryId == factoryId)
  763. .FirstAsync();
  764. if (rule == null)
  765. {
  766. return new S8RuleRunResult { Success = false, ErrorMessage = "rule_not_found", Stats = new() };
  767. }
  768. if (rule.TenantId != tenantId || rule.FactoryId != factoryId)
  769. {
  770. _logger.LogError(
  771. "rule_scope_mismatch ruleId={RuleId} ruleTenant={RuleTenant} ruleFactory={RuleFactory} scopeTenant={ScopeTenant} scopeFactory={ScopeFactory}",
  772. rule.Id, rule.TenantId, rule.FactoryId, tenantId, factoryId);
  773. return new S8RuleRunResult { Success = false, ErrorMessage = "rule_scope_mismatch", Stats = new() };
  774. }
  775. // S8-RULE-GOVERNANCE-BATCH1:分派的真源是**代码定义**,不是 DB 上的 rule_type 列。
  776. // 那一列现在只是 provisioning 维护的投影;若有人手工改它,规则的执行方式不应随之改变。
  777. // 同时这里是「没有代码定义的规则不得进入执行链」的把关点 —— 在 Create API 仍存在的
  778. // 过渡期(Batch 3 才退役),它保证业务即使造出任意 rule_code 也调不动调度器。
  779. var definition = _ruleCatalog.TryGet(rule.RuleCode);
  780. if (definition == null)
  781. {
  782. _logger.LogWarning(
  783. "rule_definition_not_found ruleId={RuleId} ruleCode={RuleCode} tenant={Tenant}",
  784. rule.Id, rule.RuleCode, tenantId);
  785. return new S8RuleRunResult { Success = false, ErrorMessage = S8RuleCatalog.ReasonNotFound, Stats = new() };
  786. }
  787. var ruleType = definition.RuleType;
  788. IS8RuleEvaluator? evaluator = ruleType switch
  789. {
  790. S8TimeoutRuleEvaluator.RuleTypeCode => _timeoutEvaluator,
  791. S8ShortageRuleEvaluator.RuleTypeCode => _shortageEvaluator,
  792. S8OutOfRangeRuleEvaluator.RuleTypeCode => _outOfRangeEvaluator,
  793. _ => null
  794. };
  795. if (evaluator == null)
  796. {
  797. return new S8RuleRunResult { Success = false, ErrorMessage = $"unsupported_rule_type:{ruleType}", Stats = new() };
  798. }
  799. try
  800. {
  801. var results = await ProcessSingleRuleAsync(tenantId, factoryId, rule, ruleType, evaluator, lease.RunId);
  802. var stats = new S8RuleRunStats
  803. {
  804. Hits = results.Count,
  805. Created = results.Count(r => r.Created),
  806. Refreshed = results.Count(r => r.Reason == "duplicate_pending"),
  807. Pending = results.Count(r => r.Reason == "antiflap_pending_hit"),
  808. Failed = results.Count(r => r.Reason == "create_failed" || r.Reason == "refresh_failed" || r.Reason == "antiflap_failed" || r.Reason == "evaluate_failed")
  809. };
  810. return new S8RuleRunResult { Success = true, Stats = stats };
  811. }
  812. catch (Exception ex)
  813. {
  814. return new S8RuleRunResult
  815. {
  816. Success = false,
  817. ErrorMessage = ex.Message,
  818. Stats = new()
  819. };
  820. }
  821. }
  822. /// <summary>
  823. /// S8-SCHED-EXEC-1:单规则处理(evaluator → reconcile → hit 循环)。
  824. /// 与 ProcessRulesByTypeAsync 内单规则循环体语义一致;此处抽出便于新调度路径直接调用单条 rule。
  825. /// </summary>
  826. private async Task<List<S8WatchCreationResult>> ProcessSingleRuleAsync(
  827. long tenantId, long factoryId, AdoS8WatchRule rule, string ruleType,
  828. IS8RuleEvaluator evaluator, string runId)
  829. {
  830. var results = new List<S8WatchCreationResult>();
  831. List<S8RuleHit> hits;
  832. try
  833. {
  834. hits = await evaluator.EvaluateAsync(tenantId, factoryId, rule);
  835. }
  836. catch (Exception ex)
  837. {
  838. var failureReason = ex is S8RuleEvaluatorException sre ? sre.Reason : ex.GetType().Name;
  839. await WriteDetectionLogAsync(new AdoS8DetectionLog
  840. {
  841. TenantId = tenantId, FactoryId = factoryId,
  842. RuleId = rule.Id, RuleCode = rule.RuleCode, RuleType = ruleType, SceneCode = rule.SceneCode,
  843. SourceObjectType = rule.SourceObjectType,
  844. DetectResult = DetectResultEvaluateFailed,
  845. DetectedAt = DateTime.Now,
  846. FailureReason = failureReason,
  847. FailureMessage = Truncate(ex.Message, 1000),
  848. RunId = runId, TriggerSource = DetectionTriggerSource
  849. });
  850. results.Add(BuildSkipResult(rule, "evaluate_failed", ex.Message));
  851. throw;
  852. }
  853. List<long> recoveredIds;
  854. try
  855. {
  856. recoveredIds = await ReconcileRecoveriesForRuleAsync(tenantId, factoryId, rule, ruleType, hits, runId);
  857. }
  858. catch (Exception ex)
  859. {
  860. _logger.LogWarning(ex, "recovery_reconcile_failed ruleCode={RuleCode} ruleType={RuleType}", rule.RuleCode, ruleType);
  861. recoveredIds = new();
  862. }
  863. // S8-DETECTION-LOG-WRITE-REDUCE-P1-1:NO_HIT 不再写 detection_log 明细。
  864. // 规则级"被定期评估"信号由 ado_s8_watch_rule.LastRunAt / LastStatus / LastRunId / LastDurationMs
  865. // 在 OnRuleCompletedAsync / ApplyRunOnceCompletionAsync 中承接,无需 detection_log 冗余记录。
  866. // DetectResultNoHit 常量保留(历史数据反查 / 未来如需恢复明细写入)。
  867. foreach (var hit in hits)
  868. {
  869. if (string.IsNullOrWhiteSpace(hit.DedupKey))
  870. {
  871. results.Add(BuildSkipResult(rule, "missing_dedup_key", null, hit));
  872. continue;
  873. }
  874. long matchedId;
  875. try
  876. {
  877. matchedId = await FindOpenExceptionByDedupKeyAsync(tenantId, factoryId, hit.DedupKey);
  878. }
  879. catch (Exception ex)
  880. {
  881. results.Add(BuildSkipResult(rule, "query_failed", ex.Message, hit));
  882. continue;
  883. }
  884. if (matchedId > 0)
  885. {
  886. try
  887. {
  888. await RefreshDetectionAsync(matchedId, hit);
  889. if (!await HasRecentRefreshedDetectionLogAsync(tenantId, factoryId, rule.RuleCode, hit.DedupKey, hit.DetectedAt))
  890. {
  891. await WriteDetectionLogAsync(BuildHitLog(tenantId, factoryId, rule, ruleType, hit, DetectResultRefreshed, matchedId, runId));
  892. }
  893. results.Add(BuildSkippedDuplicate(rule, hit, matchedId));
  894. }
  895. catch (Exception ex)
  896. {
  897. results.Add(BuildSkipResult(rule, "refresh_failed", ex.Message, hit));
  898. }
  899. continue;
  900. }
  901. if (string.Equals(ruleType, S8OutOfRangeRuleEvaluator.RuleTypeCode, StringComparison.OrdinalIgnoreCase))
  902. {
  903. long compatId;
  904. try
  905. {
  906. compatId = await FindLegacyOutOfRangeExceptionAsync(tenantId, factoryId, rule.Id, hit.RelatedObjectCode);
  907. }
  908. catch (Exception ex)
  909. {
  910. results.Add(BuildSkipResult(rule, "query_failed", ex.Message, hit));
  911. continue;
  912. }
  913. if (compatId > 0)
  914. {
  915. try
  916. {
  917. await BackfillLegacyExceptionAsync(compatId, hit);
  918. if (!await HasRecentRefreshedDetectionLogAsync(tenantId, factoryId, rule.RuleCode, hit.DedupKey, hit.DetectedAt))
  919. {
  920. await WriteDetectionLogAsync(BuildHitLog(tenantId, factoryId, rule, ruleType, hit, DetectResultRefreshed, compatId, runId));
  921. }
  922. results.Add(BuildSkippedDuplicate(rule, hit, compatId));
  923. }
  924. catch (Exception ex)
  925. {
  926. results.Add(BuildSkipResult(rule, "refresh_failed", ex.Message, hit));
  927. }
  928. continue;
  929. }
  930. }
  931. bool typeExists;
  932. try
  933. {
  934. typeExists = await _exceptionTypeRep.AsQueryable()
  935. .Where(t => t.TypeCode == hit.ExceptionTypeCode
  936. && (t.TenantId == 0 || t.TenantId == tenantId)
  937. && (t.FactoryId == 0 || t.FactoryId == factoryId)
  938. && t.Enabled)
  939. .AnyAsync();
  940. }
  941. catch (Exception ex)
  942. {
  943. results.Add(BuildSkipResult(rule, "query_failed", ex.Message, hit));
  944. continue;
  945. }
  946. if (!typeExists)
  947. {
  948. results.Add(BuildSkipResult(rule, "exception_type_missing", null, hit));
  949. continue;
  950. }
  951. int hitCount;
  952. AdoS8RuleDetectionState? state;
  953. try
  954. {
  955. (state, hitCount) = await UpsertDetectionStateOnHitAsync(tenantId, factoryId, rule, hit);
  956. }
  957. catch (Exception ex)
  958. {
  959. results.Add(BuildSkipResult(rule, "antiflap_failed", ex.Message, hit));
  960. continue;
  961. }
  962. var triggerRequired = NormalizeAntiflapCount(rule.TriggerCountRequired);
  963. if (hitCount < triggerRequired)
  964. {
  965. _logger.LogInformation(
  966. "antiflap_pending_hit ruleCode={RuleCode} dedupKey={DedupKey} hitCount={HitCount} trigger={Trigger}",
  967. rule.RuleCode, hit.DedupKey, hitCount, triggerRequired);
  968. results.Add(BuildSkipResult(rule, "antiflap_pending_hit", null, hit));
  969. continue;
  970. }
  971. try
  972. {
  973. var entity = await _reportDispatcher.CreateFromHitAsync(tenantId, factoryId, hit);
  974. await _exceptionRep.Context.Updateable<AdoS8Exception>()
  975. .SetColumns(x => new AdoS8Exception
  976. {
  977. ConsecutiveHitCount = hitCount,
  978. ConsecutiveMissCount = 0,
  979. UpdatedAt = DateTime.Now
  980. })
  981. .Where(x => x.Id == entity.Id)
  982. .ExecuteCommandAsync();
  983. if (state != null)
  984. {
  985. await _detectionStateRep.Context.Updateable<AdoS8RuleDetectionState>()
  986. .SetColumns(x => new AdoS8RuleDetectionState
  987. {
  988. ActiveExceptionId = entity.Id,
  989. UpdatedAt = DateTime.Now
  990. })
  991. .Where(x => x.Id == state.Id)
  992. .ExecuteCommandAsync();
  993. }
  994. await WriteDetectionLogAsync(BuildHitLog(tenantId, factoryId, rule, ruleType, hit, DetectResultCreated, entity.Id, runId));
  995. await TryDispatchLayerNotificationAsync(entity);
  996. results.Add(BuildCreatedResult(rule, hit, entity.Id));
  997. }
  998. catch (Exception ex)
  999. {
  1000. results.Add(BuildSkipResult(rule, "create_failed", ex.Message, hit));
  1001. }
  1002. }
  1003. return results;
  1004. }
  1005. /// <summary>
  1006. /// S8-SCHED-EXEC-1:lease 执行完成回写。
  1007. /// 必须 WHERE id = lease.RuleId AND lock_token = lease.LockToken;affectedRows = 0 视为 lease 丢失,记录 Warning,不覆盖状态。
  1008. /// 失败 ≥ 阈值(默认 3)写 paused_until = NOW + 1h。
  1009. /// </summary>
  1010. public async Task OnRuleCompletedAsync(long tenantId, long factoryId, S8RuleLease lease, S8RuleRunResult result, int durationMs)
  1011. {
  1012. var rule = await _ruleRep.AsQueryable().Where(x => x.Id == lease.RuleId).FirstAsync();
  1013. if (rule == null)
  1014. {
  1015. _logger.LogWarning("lease_complete_rule_missing ruleId={RuleId}", lease.RuleId);
  1016. return;
  1017. }
  1018. var now = DateTime.Now;
  1019. var effectiveInterval = NormalizePollInterval(rule.PollIntervalSeconds);
  1020. var nextRunAt = now.AddSeconds(effectiveInterval);
  1021. int affected;
  1022. if (result.Success)
  1023. {
  1024. affected = await _ruleRep.Context.Updateable<AdoS8WatchRule>()
  1025. .SetColumns(x => new AdoS8WatchRule
  1026. {
  1027. LastRunAt = now,
  1028. NextRunAt = nextRunAt,
  1029. LastStatus = "SUCCESS",
  1030. LastError = null,
  1031. LastDurationMs = durationMs,
  1032. ConsecutiveFailureCount = 0,
  1033. LockToken = null,
  1034. LockedBy = null,
  1035. LockUntil = null,
  1036. RunningStartedAt = null,
  1037. UpdatedAt = now
  1038. })
  1039. .Where(x => x.Id == lease.RuleId && x.LockToken == lease.LockToken)
  1040. .ExecuteCommandAsync();
  1041. }
  1042. else
  1043. {
  1044. var errorTrunc = Truncate(result.ErrorMessage, 500);
  1045. var newFailures = rule.ConsecutiveFailureCount + 1;
  1046. DateTime? pausedUntil = rule.PausedUntil;
  1047. string? pauseReason = rule.PauseReason;
  1048. if (newFailures >= AutoPauseFailureThreshold)
  1049. {
  1050. pausedUntil = now.AddHours(AutoPauseDurationHours);
  1051. pauseReason = Truncate($"AUTO_PAUSED_AFTER_{AutoPauseFailureThreshold}_FAILURES: {errorTrunc}", 64);
  1052. }
  1053. affected = await _ruleRep.Context.Updateable<AdoS8WatchRule>()
  1054. .SetColumns(x => new AdoS8WatchRule
  1055. {
  1056. LastRunAt = now,
  1057. NextRunAt = nextRunAt,
  1058. LastStatus = "FAILED",
  1059. LastError = errorTrunc,
  1060. LastDurationMs = durationMs,
  1061. ConsecutiveFailureCount = x.ConsecutiveFailureCount + 1,
  1062. PausedUntil = pausedUntil,
  1063. PauseReason = pauseReason,
  1064. LockToken = null,
  1065. LockedBy = null,
  1066. LockUntil = null,
  1067. RunningStartedAt = null,
  1068. UpdatedAt = now
  1069. })
  1070. .Where(x => x.Id == lease.RuleId && x.LockToken == lease.LockToken)
  1071. .ExecuteCommandAsync();
  1072. }
  1073. if (affected == 0)
  1074. {
  1075. _logger.LogWarning(
  1076. "lease_lost_on_complete ruleId={RuleId} ruleCode={RuleCode} lockToken={LockToken}",
  1077. lease.RuleId, lease.RuleCode, lease.LockToken);
  1078. }
  1079. }
  1080. /// <summary>
  1081. /// S8-SCHED-EXEC-1:单 tick 完整流程。Job / debug 调度入口。
  1082. /// 1) ResetExpiredLeasesAsync
  1083. /// 2) PickReadyRulesAsync(batchSize)
  1084. /// 3) 每条 rule 独立 try/catch 调用 RunSingleRuleAsync + OnRuleCompletedAsync
  1085. /// 单条规则失败不影响其他规则;整 tick 不抛异常。
  1086. /// </summary>
  1087. public async Task<S8DispatchTickResult> RunDispatchTickAsync(long tenantId, long factoryId, int batchSize, string lockedBy)
  1088. {
  1089. var tickId = Guid.NewGuid().ToString("N").Substring(0, 8);
  1090. var runId = Guid.NewGuid().ToString("N").Substring(0, 16);
  1091. var summary = new S8DispatchTickResult { TickId = tickId, RunId = runId };
  1092. try
  1093. {
  1094. summary.LeaseReleased = await ResetExpiredLeasesAsync(tenantId, factoryId);
  1095. }
  1096. catch (Exception ex)
  1097. {
  1098. _logger.LogError(ex, "tick_reset_lease_failed tickId={TickId}", tickId);
  1099. }
  1100. List<S8RuleLease> leases;
  1101. try
  1102. {
  1103. leases = await PickReadyRulesAsync(tenantId, factoryId, batchSize, lockedBy, runId);
  1104. }
  1105. catch (Exception ex)
  1106. {
  1107. _logger.LogError(ex, "tick_pick_failed tickId={TickId}", tickId);
  1108. return summary;
  1109. }
  1110. summary.Picked = leases.Count;
  1111. foreach (var lease in leases)
  1112. {
  1113. var sw = System.Diagnostics.Stopwatch.StartNew();
  1114. S8RuleRunResult runResult;
  1115. try
  1116. {
  1117. runResult = await RunSingleRuleAsync(tenantId, factoryId, lease);
  1118. }
  1119. catch (Exception ex)
  1120. {
  1121. runResult = new S8RuleRunResult { Success = false, ErrorMessage = ex.Message, Stats = new() };
  1122. }
  1123. sw.Stop();
  1124. try
  1125. {
  1126. await OnRuleCompletedAsync(tenantId, factoryId, lease, runResult, (int)sw.ElapsedMilliseconds);
  1127. }
  1128. catch (Exception ex)
  1129. {
  1130. _logger.LogError(ex, "tick_complete_failed tickId={TickId} ruleId={RuleId} ruleCode={RuleCode}", tickId, lease.RuleId, lease.RuleCode);
  1131. }
  1132. _logger.LogInformation(
  1133. "tick_rule_done tickId={TickId} runId={RunId} ruleId={RuleId} ruleCode={RuleCode} status={Status} durationMs={Dur} hits={Hits} created={Created} refreshed={Refreshed} pending={Pending} failed={Failed} error={Error}",
  1134. tickId, runId, lease.RuleId, lease.RuleCode,
  1135. runResult.Success ? "SUCCESS" : "FAILED",
  1136. sw.ElapsedMilliseconds,
  1137. runResult.Stats.Hits, runResult.Stats.Created, runResult.Stats.Refreshed, runResult.Stats.Pending, runResult.Stats.Failed,
  1138. runResult.ErrorMessage);
  1139. if (runResult.Success)
  1140. {
  1141. summary.Success++;
  1142. summary.Created += runResult.Stats.Created;
  1143. summary.Refreshed += runResult.Stats.Refreshed;
  1144. summary.Pending += runResult.Stats.Pending;
  1145. summary.PerRuleFailed += runResult.Stats.Failed;
  1146. }
  1147. else
  1148. {
  1149. summary.Failed++;
  1150. }
  1151. }
  1152. return summary;
  1153. }
  1154. private static int NormalizePollInterval(int raw)
  1155. {
  1156. if (raw < MinPollIntervalSeconds || raw > MaxPollIntervalSeconds) return DefaultPollIntervalSeconds;
  1157. return raw;
  1158. }
  1159. /// <summary>
  1160. /// S8-NOTIFY-WIRE-WATCH-1:异常自动建单成功后,非破坏性挂入通知分层路由。
  1161. /// 全程异常隔离:任何异常仅 LogWarning,不抛回主流程,不影响 detection_log / 事务 /
  1162. /// 异常状态机;该方法独立于 CreateFromWatchAsync / CreateFromHitAsync 的事务边界
  1163. /// (两者已 commit 后才返回 entity,故在此调用安全)。
  1164. /// sceneCode:先从 entity.SceneCode;空则 fallback 到 "S8_DEMO_DEFAULT"(demo 路径)。
  1165. /// severity:直接取 entity.Severity(CreateFromWatchAsync/CreateFromHitAsync 已保证非空)。
  1166. /// </summary>
  1167. private async Task TryDispatchLayerNotificationAsync(AdoS8Exception entity)
  1168. {
  1169. if (entity == null || entity.Id <= 0) return;
  1170. try
  1171. {
  1172. var sceneCode = string.IsNullOrWhiteSpace(entity.SceneCode) ? "S8_DEMO_DEFAULT" : entity.SceneCode;
  1173. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:写入前 Normalize,落 FOLLOW/SERIOUS。
  1174. var severity = S8SeverityCode.Normalize(entity.Severity);
  1175. // S8-DEMO-IMPACT-SORT-NOTICE-1:附带 30 天影响统计(重复次数 / 累计损失 / 建议关注级别)。
  1176. // 计算失败不阻断通知主链路;snap==null 时 BuildNotification 仅写基础 Context。
  1177. ExceptionImpactSnapshot? snap = null;
  1178. try
  1179. {
  1180. snap = await _impactMetricsService.ComputeOneAsync(entity);
  1181. }
  1182. catch (Exception ex)
  1183. {
  1184. _logger.LogWarning(ex, "notify_impact_compute_throw exceptionId={ExceptionId}", entity.Id);
  1185. }
  1186. var baseContent =
  1187. $"异常 {entity.ExceptionCode}:{entity.Title}(场景 {sceneCode},严重度 {severity}" +
  1188. (string.IsNullOrWhiteSpace(entity.SourceRuleCode) ? "" : $",规则 {entity.SourceRuleCode}") + ")";
  1189. var content = snap == null
  1190. ? baseContent
  1191. : baseContent
  1192. + Environment.NewLine
  1193. + $"过去30天同类异常发生 {snap.RepeatCount30d} 次,已关闭累计损失 {snap.CumulativeLossHours30d.ToString("0.#")} 小时,建议关注级别:{snap.SuggestedAttentionLabel}";
  1194. await _notificationLayerResolver.DispatchByLayerAsync(new S8NotificationLayerResolver.DispatchByLayerInput
  1195. {
  1196. TenantId = entity.TenantId,
  1197. FactoryId = entity.FactoryId,
  1198. ExceptionId = entity.Id,
  1199. ExceptionNo = entity.ExceptionCode,
  1200. SceneCode = sceneCode,
  1201. Severity = severity,
  1202. Title = entity.Title ?? string.Empty,
  1203. Content = content,
  1204. Status = entity.Status,
  1205. SourceRuleCode = entity.SourceRuleCode,
  1206. JumpUrl = $"/aidop/s8/exceptions/{entity.Id}",
  1207. RepeatCount30d = snap?.RepeatCount30d,
  1208. CumulativeLossHours30d = snap?.CumulativeLossHours30d,
  1209. SuggestedAttentionLevel = snap?.SuggestedAttentionLevel,
  1210. SuggestedAttentionLabel = snap?.SuggestedAttentionLabel,
  1211. ImpactReason = snap?.ImpactReason,
  1212. });
  1213. }
  1214. catch (Exception ex)
  1215. {
  1216. _logger.LogWarning(ex, "notify_dispatch_throw exceptionId={ExceptionId}", entity.Id);
  1217. }
  1218. }
  1219. /// <summary>
  1220. /// S8-NOTIFY-WIRE-RECOVERED-1:异常恢复(recovered_at 已写入、RECOVERED detection_log 已落库)后,
  1221. /// 非破坏性挂入分层通知。全程异常隔离:任何异常仅 LogWarning,不抛回主流程,不影响 detection_log /
  1222. /// 状态机;call site 已在事务边界外(recovered 路径无事务)。
  1223. /// 重新读取 entity 拿场景/严重度/编号/状态/规则代码(恢复事件相对低频,1 次额外读可接受)。
  1224. /// S8-DEMO-IMPACT-SORT-NOTICE-1:恢复事件**不**追加影响统计字段,保持原有恢复语义不变。
  1225. /// </summary>
  1226. private async Task TryDispatchRecoveredLayerNotificationAsync(long exceptionId)
  1227. {
  1228. if (exceptionId <= 0) return;
  1229. try
  1230. {
  1231. var entity = await _exceptionRep.GetByIdAsync(exceptionId);
  1232. if (entity == null)
  1233. {
  1234. _logger.LogWarning("notify_recovered_dispatch_entity_missing exceptionId={ExceptionId}", exceptionId);
  1235. return;
  1236. }
  1237. var sceneCode = string.IsNullOrWhiteSpace(entity.SceneCode) ? "S8_DEMO_DEFAULT" : entity.SceneCode;
  1238. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:写入前 Normalize,落 FOLLOW/SERIOUS。
  1239. var severity = S8SeverityCode.Normalize(entity.Severity);
  1240. var title = $"【已恢复】{entity.ExceptionCode}";
  1241. var content =
  1242. $"异常 {entity.ExceptionCode} 已恢复,场景 {sceneCode},严重度 {severity}" +
  1243. (string.IsNullOrWhiteSpace(entity.SourceRuleCode) ? "" : $",规则 {entity.SourceRuleCode}");
  1244. await _notificationLayerResolver.DispatchByLayerAsync(new S8NotificationLayerResolver.DispatchByLayerInput
  1245. {
  1246. TenantId = entity.TenantId,
  1247. FactoryId = entity.FactoryId,
  1248. ExceptionId = entity.Id,
  1249. ExceptionNo = entity.ExceptionCode,
  1250. SceneCode = sceneCode,
  1251. Severity = severity,
  1252. Title = title,
  1253. Content = content,
  1254. Status = entity.Status,
  1255. SourceRuleCode = entity.SourceRuleCode,
  1256. JumpUrl = $"/aidop/s8/exceptions/{entity.Id}",
  1257. Recovered = true,
  1258. });
  1259. }
  1260. catch (Exception ex)
  1261. {
  1262. _logger.LogWarning(ex, "notify_recovered_dispatch_throw exceptionId={ExceptionId}", exceptionId);
  1263. }
  1264. }
  1265. }
  1266. /// <summary>
  1267. /// G01-05 去重结果对象。仅服务 G01-06 建单前拦截,由 CanCreate 单决策位决定是否建单。
  1268. /// 只服务首版唯一场景 S2(迁移后由 S2S6_PRODUCTION 切到单模块 S2)+ 唯一 trigger_type VALUE_DEVIATION + 设备对象。
  1269. /// 不预留多 trigger_type / 平台化去重扩展结构。
  1270. /// Reason 值域:no_pending / duplicate_pending / missing_dedup_key / query_failed。
  1271. /// </summary>
  1272. public sealed class S8WatchDedupResult
  1273. {
  1274. public S8WatchHitResult Hit { get; set; } = new();
  1275. public bool CanCreate { get; set; }
  1276. public long? MatchedExceptionId { get; set; }
  1277. public string Reason { get; set; } = string.Empty;
  1278. }
  1279. /// <summary>
  1280. /// G01-06 建单结果对象。仅服务 G-01 首版主线验收,由 Created / Skipped 两位决定结局。
  1281. /// 只服务首版唯一场景 S2(迁移后由 S2S6_PRODUCTION 切到单模块 S2)+ 唯一 trigger_type VALUE_DEVIATION + 设备对象。
  1282. /// 不预留多 trigger_type / 平台化工单扩展结构。
  1283. /// Reason 值域:auto_created / create_failed / 透传自 DedupResult.Reason。
  1284. /// </summary>
  1285. public sealed class S8WatchCreationResult
  1286. {
  1287. public S8WatchDedupResult DedupResult { get; set; } = new();
  1288. public bool Created { get; set; }
  1289. public bool Skipped { get; set; }
  1290. public long? CreatedExceptionId { get; set; }
  1291. public string Reason { get; set; } = string.Empty;
  1292. public string? ErrorMessage { get; set; }
  1293. }
  1294. /// <summary>
  1295. /// G01-04 命中结果对象。承载 G01-05 去重与 G01-06 建单所需最小追溯字段,
  1296. /// 仅服务首版唯一场景 S2(迁移后由 S2S6_PRODUCTION 切到单模块 S2)+ 唯一 trigger_type VALUE_DEVIATION + 设备对象。
  1297. /// 不预留多 trigger_type / 多场景 / 平台化扩展结构。
  1298. /// </summary>
  1299. public sealed class S8WatchHitResult
  1300. {
  1301. public long SourceRuleId { get; set; }
  1302. public string SourceRuleCode { get; set; } = string.Empty;
  1303. public string RelatedObjectCode { get; set; } = string.Empty;
  1304. public decimal CurrentValue { get; set; }
  1305. public decimal ThresholdValue { get; set; }
  1306. public string TriggerCondition { get; set; } = string.Empty;
  1307. public string Severity { get; set; } = string.Empty;
  1308. public long? OccurrenceDeptId { get; set; }
  1309. public long? ResponsibleDeptId { get; set; }
  1310. public string SourcePayload { get; set; } = string.Empty;
  1311. }
  1312. /// <summary>S8-SCHED-EXEC-1:lease 抢占成功后传递的最小标识对象。</summary>
  1313. public sealed class S8RuleLease
  1314. {
  1315. public long RuleId { get; set; }
  1316. public string RuleCode { get; set; } = string.Empty;
  1317. public string? RuleType { get; set; }
  1318. public string LockToken { get; set; } = string.Empty;
  1319. public string LockedBy { get; set; } = string.Empty;
  1320. public DateTime LockUntil { get; set; }
  1321. public string RunId { get; set; } = string.Empty;
  1322. public DateTime AcquiredAt { get; set; }
  1323. }
  1324. /// <summary>S8-SCHED-EXEC-1:单条规则执行结果,OnRuleCompletedAsync 据此更新状态。</summary>
  1325. public sealed class S8RuleRunResult
  1326. {
  1327. public bool Success { get; set; }
  1328. public string? ErrorMessage { get; set; }
  1329. public S8RuleRunStats Stats { get; set; } = new();
  1330. }
  1331. public sealed class S8RuleRunStats
  1332. {
  1333. public int Hits { get; set; }
  1334. public int Created { get; set; }
  1335. public int Refreshed { get; set; }
  1336. public int Pending { get; set; }
  1337. public int Failed { get; set; }
  1338. }
  1339. /// <summary>S8-SCHED-EXEC-1:单 tick 调度结果聚合。</summary>
  1340. public sealed class S8DispatchTickResult
  1341. {
  1342. public string TickId { get; set; } = string.Empty;
  1343. public string RunId { get; set; } = string.Empty;
  1344. public int LeaseReleased { get; set; }
  1345. public int Picked { get; set; }
  1346. public int Success { get; set; }
  1347. public int Failed { get; set; }
  1348. public int Created { get; set; }
  1349. public int Refreshed { get; set; }
  1350. public int Pending { get; set; }
  1351. public int PerRuleFailed { get; set; }
  1352. }