S8SchedulerScopeGuardTests.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. using Admin.NET.Plugin.AiDOP.Service.S8;
  2. using System.Reflection;
  3. using Xunit;
  4. namespace Admin.NET.Plugin.AiDOP.Tests.S8;
  5. /// <summary>
  6. /// S8-P0-1-SCHEDULER-TRUSTED-SCOPE-1:Scheduler 多租户执行边界守卫。
  7. ///
  8. /// <para>背景(2026-09-02 实测事故):Watch Scheduler 是**平台后台任务**,
  9. /// <c>ListEnabledScopesAsync</c> 按设计遍历全部「有启用规则且 Status=1」的租户。
  10. /// 该遍历本身合法,但当时链路上有三个缺口,使得一次 tick 会跨租户串味:</para>
  11. /// <list type="number">
  12. /// <item>执行入口 <c>RunSingleRuleAsync</c> 只按 <c>lease.RuleId</c> 装载规则,不校验归属;</item>
  13. /// <item>自动建单算 SLA 的 <c>ResolveSlaDeadlineAsync</c> 用 <c>ClearFilter()</c> + 仅 TypeCode 等值
  14. /// + <c>ORDER BY FactoryId DESC</c>,在**全库**范围挑「factory_id 最大」的那行;</item>
  15. /// <item>跨租户扫描的超时升级 Job 按 TypeCode 建全局 map,会把 B 租户的
  16. /// <c>escalate_role_code</c> 用到 A 租户的异常上。</item>
  17. /// </list>
  18. ///
  19. /// <para>本测试锁住修复后的口径:**遍历可以跨租户,但每条规则的执行必须隔离在自己的
  20. /// trusted (TenantId, FactoryId) 里**,且下游按作用域取配置。断言走源码扫描,
  21. /// 因为这些约束落在方法体的查询谓词上,反射看不到。</para>
  22. /// </summary>
  23. public class S8SchedulerScopeGuardTests
  24. {
  25. private static readonly string PluginRoot =
  26. Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../Admin.NET.Plugin.AiDOP"));
  27. private const string SchedulerSrc = "Service/S8/S8WatchSchedulerService.cs";
  28. private const string ManualReportSrc = "Service/S8/S8ManualReportService.cs";
  29. private const string EscalationSrc = "Service/S8/S8TimeoutAutoEscalationService.cs";
  30. private static string ReadSource(string relativePath)
  31. {
  32. var full = Path.Combine(PluginRoot, relativePath);
  33. Assert.True(File.Exists(full), $"源码文件不存在,路径需同步更新:{full}");
  34. return File.ReadAllText(full);
  35. }
  36. /// <summary>只取可执行代码行:注释里为留档会复述旧写法,不应算违规。</summary>
  37. private static string CodeOnly(string relativePath) =>
  38. string.Join('\n', ReadSource(relativePath)
  39. .Split('\n')
  40. .Select(l => l.Trim())
  41. .Where(l => !l.StartsWith("///", StringComparison.Ordinal)
  42. && !l.StartsWith("//", StringComparison.Ordinal)));
  43. /// <summary>
  44. /// 缺口 1:执行入口必须按本次 tick 的 scope 绑行,并对归属不符 fail-fast。
  45. /// </summary>
  46. [Fact]
  47. public void RunSingleRule_BindsRuleToTickScope_AndFailsFastOnMismatch()
  48. {
  49. var code = CodeOnly(SchedulerSrc);
  50. // 装载规则时必须同时带 TenantId / FactoryId 谓词,禁止裸 Id 装载。
  51. Assert.Contains("x.Id == lease.RuleId && x.TenantId == tenantId && x.FactoryId == factoryId", code);
  52. // 归属复核 + 明确的失败原因码;不得静默继续执行。
  53. Assert.Contains("rule_scope_mismatch", code);
  54. Assert.Contains("rule.TenantId != tenantId || rule.FactoryId != factoryId", code);
  55. }
  56. /// <summary>
  57. /// 缺口 2:SLA 解析必须接收显式作用域,且查询带 (租户命中 OR 0) AND (工厂命中 OR 0)。
  58. /// 签名用反射钉住,避免有人新增无作用域重载。
  59. /// </summary>
  60. [Fact]
  61. public void ResolveSlaDeadline_RequiresExplicitTenantAndFactory()
  62. {
  63. var methods = typeof(S8ManualReportService)
  64. .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
  65. .Where(m => m.Name == "ResolveSlaDeadlineAsync")
  66. .ToList();
  67. Assert.NotEmpty(methods);
  68. Assert.All(methods, m =>
  69. {
  70. var p = m.GetParameters();
  71. Assert.True(p.Length >= 2, "ResolveSlaDeadlineAsync 必须显式接收 tenantId / factoryId");
  72. Assert.Equal(typeof(long), p[0].ParameterType);
  73. Assert.Equal(typeof(long), p[1].ParameterType);
  74. });
  75. }
  76. /// <summary>缺口 2:SLA 查询谓词本身必须带作用域,不能只靠调用方传参而查询里不用。</summary>
  77. [Fact]
  78. public void ResolveSlaDeadline_QueryCarriesScopePredicate()
  79. {
  80. var code = CodeOnly(ManualReportSrc);
  81. Assert.Contains("(t.TenantId == tenantId || t.TenantId == 0)", code);
  82. Assert.Contains("(t.FactoryId == factoryId || t.FactoryId == 0)", code);
  83. }
  84. /// <summary>
  85. /// 缺口 3:跨租户扫描的超时升级 Job,异常类型必须按**每条异常自身**的作用域解析,
  86. /// 不得再用「按 TypeCode 建全局 map + 取 factory_id 最大」的写法。
  87. /// </summary>
  88. [Fact]
  89. public void TimeoutAutoEscalation_ResolvesExceptionTypePerRowScope()
  90. {
  91. var code = CodeOnly(EscalationSrc);
  92. // 旧写法已移除:全局 typeMap 按 TypeCode 直接取用。
  93. Assert.DoesNotContain("typeMap.TryGetValue", code);
  94. // 新写法:逐异常按 (TenantId, FactoryId) 解析。
  95. Assert.Contains("ResolveTypeForScope", code);
  96. Assert.Contains("t.TenantId == tenantId || t.TenantId == 0", code);
  97. Assert.Contains("t.FactoryId == factoryId || t.FactoryId == 0", code);
  98. Assert.Contains("ResolveTypeForScope(e.ExceptionTypeCode!, e.TenantId, e.FactoryId)", code);
  99. }
  100. /// <summary>
  101. /// 遍历入口本身保持「平台后台任务」语义:按租户枚举 + 只取 Status=1 的租户,
  102. /// 但每个 scope 必须带 tenant_id / factory_id 两个维度(不能只按租户)。
  103. /// </summary>
  104. [Fact]
  105. public void EnabledScopeEnumeration_IsTenantAndFactoryPaired()
  106. {
  107. var code = CodeOnly(SchedulerSrc);
  108. Assert.Contains("SELECT DISTINCT r.tenant_id AS TenantId, r.factory_id AS FactoryId", code);
  109. Assert.Contains("INNER JOIN SysTenant t ON t.Id = r.tenant_id AND t.Status = 1", code);
  110. Assert.Contains("AND r.tenant_id > 0", code);
  111. Assert.Contains("AND r.factory_id > 0", code);
  112. }
  113. /// <summary>
  114. /// 下游写入口必须继续以显式 (tenantId, factoryId) 承接,不允许退回从 rule / 客户端推导。
  115. /// </summary>
  116. [Fact]
  117. public void DownstreamWriters_KeepExplicitScopeParameters()
  118. {
  119. var pick = typeof(S8WatchSchedulerService).GetMethod(
  120. nameof(S8WatchSchedulerService.PickReadyRulesAsync));
  121. Assert.NotNull(pick);
  122. Assert.Equal(typeof(long), pick!.GetParameters()[0].ParameterType);
  123. Assert.Equal(typeof(long), pick.GetParameters()[1].ParameterType);
  124. var run = typeof(S8WatchSchedulerService).GetMethod(
  125. nameof(S8WatchSchedulerService.RunSingleRuleAsync));
  126. Assert.NotNull(run);
  127. Assert.Equal(typeof(long), run!.GetParameters()[0].ParameterType);
  128. Assert.Equal(typeof(long), run.GetParameters()[1].ParameterType);
  129. }
  130. }