S8WatchSchedulerService.cs 67 KB

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