Apply persistent rules when processes start (#21)
Apply persistent rules when processes start Wire persistent process rules into runtime process discovery so existing enabled rules can apply automatically while ThreadPilot is running. - Add PersistentRuleAutoApplyService for runtime rule auto-apply - Hook auto-apply into ProcessMonitorManagerService snapshot and process-start paths - Add ApplyPersistentRulesOnProcessStart app setting enabled by default - Use existing PersistentRulesEngine for CpuSelection, legacy affinity, CPU priority and memory priority - Add per-process/rule cooldown to avoid repeated apply spam - Clear cooldown state when processes exit or disappear from snapshots - Preserve safe protected-process and access-denied behavior without bypass claims - Preserve cancellation semantics during shutdown/stop paths - Add tests for matching rules, disabled/no-match cases, cooldown, retry, PID reuse, failures, feature flag and monitor integration No Windows Service, registry/IFEO persistence, installer changes, rules editor, version bump or tag changes.
This commit is contained in:
@@ -164,6 +164,9 @@ namespace ThreadPilot.Models
|
||||
[ObservableProperty]
|
||||
private bool enableFallbackPolling = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool applyPersistentRulesOnProcessStart = true;
|
||||
|
||||
// Advanced Settings
|
||||
[ObservableProperty]
|
||||
private bool enableDebugLogging = false;
|
||||
@@ -249,6 +252,7 @@ namespace ThreadPilot.Models
|
||||
this.FallbackPollingIntervalMs = other.FallbackPollingIntervalMs;
|
||||
this.EnableWmiMonitoring = other.EnableWmiMonitoring;
|
||||
this.EnableFallbackPolling = other.EnableFallbackPolling;
|
||||
this.ApplyPersistentRulesOnProcessStart = other.ApplyPersistentRulesOnProcessStart;
|
||||
|
||||
// Advanced Settings
|
||||
this.EnableDebugLogging = other.EnableDebugLogging;
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
/*
|
||||
* ThreadPilot - persistent rule runtime auto-apply coordinator.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public interface IPersistentRuleAutoApplyService
|
||||
{
|
||||
Task<IReadOnlyList<PersistentRuleAutoApplyResult>> ApplyForDiscoveredProcessesAsync(
|
||||
IEnumerable<ProcessModel> processes,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task<IReadOnlyList<PersistentRuleAutoApplyResult>> ApplyForProcessStartAsync(
|
||||
ProcessModel process,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
void MarkProcessExited(int processId);
|
||||
}
|
||||
|
||||
public sealed record PersistentRuleAutoApplyResult
|
||||
{
|
||||
public bool Success { get; init; }
|
||||
|
||||
public string RuleId { get; init; } = string.Empty;
|
||||
|
||||
public int ProcessId { get; init; }
|
||||
|
||||
public string ProcessName { get; init; } = string.Empty;
|
||||
|
||||
public string? ErrorCode { get; init; }
|
||||
|
||||
public string UserMessage { get; init; } = string.Empty;
|
||||
|
||||
public string TechnicalMessage { get; init; } = string.Empty;
|
||||
|
||||
public bool IsAccessDenied { get; init; }
|
||||
|
||||
public bool IsAntiCheatLikely { get; init; }
|
||||
|
||||
public bool IsProcessExited { get; init; }
|
||||
|
||||
public static PersistentRuleAutoApplyResult FromApplyResult(PersistentRuleApplyResult result) =>
|
||||
new()
|
||||
{
|
||||
Success = result.Success,
|
||||
RuleId = result.RuleId,
|
||||
ProcessId = result.ProcessId,
|
||||
ProcessName = result.ProcessName,
|
||||
ErrorCode = result.ErrorCode,
|
||||
UserMessage = result.IsAntiCheatLikely
|
||||
? ProcessOperationUserMessages.PersistentRulesProtectedProcessWarning
|
||||
: result.UserMessage,
|
||||
TechnicalMessage = result.TechnicalMessage,
|
||||
IsAccessDenied = result.IsAccessDenied,
|
||||
IsAntiCheatLikely = result.IsAntiCheatLikely,
|
||||
IsProcessExited = result.IsProcessExited,
|
||||
};
|
||||
}
|
||||
|
||||
public sealed class PersistentRuleAutoApplyService : IPersistentRuleAutoApplyService
|
||||
{
|
||||
private static readonly TimeSpan DefaultCooldown = TimeSpan.FromSeconds(30);
|
||||
|
||||
private readonly IPersistentProcessRuleStore ruleStore;
|
||||
private readonly IPersistentProcessRuleMatcher matcher;
|
||||
private readonly IPersistentRulesEngine rulesEngine;
|
||||
private readonly IApplicationSettingsService settingsService;
|
||||
private readonly ILogger<PersistentRuleAutoApplyService> logger;
|
||||
private readonly Func<DateTimeOffset> nowProvider;
|
||||
private readonly TimeSpan cooldown;
|
||||
private readonly ConcurrentDictionary<RuleAttemptKey, DateTimeOffset> recentAttempts = new();
|
||||
|
||||
public PersistentRuleAutoApplyService(
|
||||
IPersistentProcessRuleStore ruleStore,
|
||||
IPersistentProcessRuleMatcher matcher,
|
||||
IPersistentRulesEngine rulesEngine,
|
||||
IApplicationSettingsService settingsService,
|
||||
ILogger<PersistentRuleAutoApplyService> logger)
|
||||
: this(ruleStore, matcher, rulesEngine, settingsService, logger, () => DateTimeOffset.UtcNow, DefaultCooldown)
|
||||
{
|
||||
}
|
||||
|
||||
public PersistentRuleAutoApplyService(
|
||||
IPersistentProcessRuleStore ruleStore,
|
||||
IPersistentProcessRuleMatcher matcher,
|
||||
IPersistentRulesEngine rulesEngine,
|
||||
IApplicationSettingsService settingsService,
|
||||
ILogger<PersistentRuleAutoApplyService> logger,
|
||||
Func<DateTimeOffset> nowProvider,
|
||||
TimeSpan cooldown)
|
||||
{
|
||||
this.ruleStore = ruleStore ?? throw new ArgumentNullException(nameof(ruleStore));
|
||||
this.matcher = matcher ?? throw new ArgumentNullException(nameof(matcher));
|
||||
this.rulesEngine = rulesEngine ?? throw new ArgumentNullException(nameof(rulesEngine));
|
||||
this.settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService));
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
this.nowProvider = nowProvider ?? throw new ArgumentNullException(nameof(nowProvider));
|
||||
this.cooldown = cooldown <= TimeSpan.Zero ? DefaultCooldown : cooldown;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<PersistentRuleAutoApplyResult>> ApplyForDiscoveredProcessesAsync(
|
||||
IEnumerable<ProcessModel> processes,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(processes);
|
||||
|
||||
var snapshot = processes
|
||||
.Where(IsProcessEligible)
|
||||
.GroupBy(process => process.ProcessId)
|
||||
.Select(group => group.First())
|
||||
.ToList();
|
||||
this.ClearAttemptsForMissingProcesses(snapshot.Select(process => process.ProcessId).ToHashSet());
|
||||
|
||||
if (!this.IsEnabled() || snapshot.Count == 0)
|
||||
{
|
||||
return Array.Empty<PersistentRuleAutoApplyResult>();
|
||||
}
|
||||
|
||||
var rules = await this.ruleStore.LoadAsync().ConfigureAwait(false);
|
||||
if (rules.Count == 0)
|
||||
{
|
||||
return Array.Empty<PersistentRuleAutoApplyResult>();
|
||||
}
|
||||
|
||||
var results = new List<PersistentRuleAutoApplyResult>();
|
||||
foreach (var process in snapshot)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
results.AddRange(await this.ApplyForProcessAsync(process, rules, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<PersistentRuleAutoApplyResult>> ApplyForProcessStartAsync(
|
||||
ProcessModel process,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(process);
|
||||
|
||||
if (!this.IsEnabled() || !IsProcessEligible(process))
|
||||
{
|
||||
return Array.Empty<PersistentRuleAutoApplyResult>();
|
||||
}
|
||||
|
||||
var rules = await this.ruleStore.LoadAsync().ConfigureAwait(false);
|
||||
return await this.ApplyForProcessAsync(process, rules, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public void MarkProcessExited(int processId)
|
||||
{
|
||||
foreach (var key in this.recentAttempts.Keys.Where(key => key.ProcessId == processId))
|
||||
{
|
||||
this.recentAttempts.TryRemove(key, out _);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<PersistentRuleAutoApplyResult>> ApplyForProcessAsync(
|
||||
ProcessModel process,
|
||||
IReadOnlyList<PersistentProcessRule> rules,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var now = this.nowProvider();
|
||||
var candidates = rules
|
||||
.Where(rule => rule.IsEnabled && this.matcher.IsMatch(rule, process))
|
||||
.ToList();
|
||||
|
||||
if (candidates.Count == 0)
|
||||
{
|
||||
return Array.Empty<PersistentRuleAutoApplyResult>();
|
||||
}
|
||||
|
||||
var selectedRules = candidates
|
||||
.Where(rule => this.TryRecordAttempt(process.ProcessId, rule, now))
|
||||
.ToList();
|
||||
|
||||
if (selectedRules.Count == 0)
|
||||
{
|
||||
this.logger.LogDebug(
|
||||
"Persistent rule auto-apply suppressed by cooldown for process {ProcessName} (PID: {ProcessId})",
|
||||
process.Name,
|
||||
process.ProcessId);
|
||||
return Array.Empty<PersistentRuleAutoApplyResult>();
|
||||
}
|
||||
|
||||
var selectedSignatures = selectedRules
|
||||
.Select(GetRuleSignature)
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
try
|
||||
{
|
||||
// Runtime auto-apply only runs while ThreadPilot is open; it does not use registry,
|
||||
// IFEO, services, or protected-process bypass techniques.
|
||||
var applyResults = await this.rulesEngine
|
||||
.ApplyMatchingRulesAsync(
|
||||
process,
|
||||
rule => selectedSignatures.Contains(GetRuleSignature(rule)),
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var results = applyResults.Select(PersistentRuleAutoApplyResult.FromApplyResult).ToList();
|
||||
foreach (var result in results)
|
||||
{
|
||||
this.LogResult(result);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
this.logger.LogWarning(
|
||||
ex,
|
||||
"Persistent rule auto-apply failed for process {ProcessName} (PID: {ProcessId})",
|
||||
process.Name,
|
||||
process.ProcessId);
|
||||
|
||||
return selectedRules
|
||||
.Select(rule => new PersistentRuleAutoApplyResult
|
||||
{
|
||||
Success = false,
|
||||
RuleId = rule.Id,
|
||||
ProcessId = process.ProcessId,
|
||||
ProcessName = process.Name,
|
||||
UserMessage = "ThreadPilot could not apply the saved rule.",
|
||||
TechnicalMessage = ex.Message,
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryRecordAttempt(int processId, PersistentProcessRule rule, DateTimeOffset now)
|
||||
{
|
||||
var key = new RuleAttemptKey(processId, GetRuleSignature(rule));
|
||||
if (this.recentAttempts.TryGetValue(key, out var lastAttempt) &&
|
||||
now - lastAttempt < this.cooldown)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
this.recentAttempts[key] = now;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ClearAttemptsForMissingProcesses(HashSet<int> currentProcessIds)
|
||||
{
|
||||
foreach (var key in this.recentAttempts.Keys.Where(key => !currentProcessIds.Contains(key.ProcessId)))
|
||||
{
|
||||
this.recentAttempts.TryRemove(key, out _);
|
||||
}
|
||||
}
|
||||
|
||||
private void LogResult(PersistentRuleAutoApplyResult result)
|
||||
{
|
||||
if (result.Success)
|
||||
{
|
||||
this.logger.LogInformation(
|
||||
"Applied saved persistent rule {RuleId} to process {ProcessName} (PID: {ProcessId})",
|
||||
result.RuleId,
|
||||
result.ProcessName,
|
||||
result.ProcessId);
|
||||
return;
|
||||
}
|
||||
|
||||
var logLevel = result.IsAccessDenied || result.IsAntiCheatLikely || result.IsProcessExited
|
||||
? LogLevel.Debug
|
||||
: LogLevel.Warning;
|
||||
this.logger.Log(
|
||||
logLevel,
|
||||
"Persistent rule {RuleId} was not applied to process {ProcessName} (PID: {ProcessId}): {Message}",
|
||||
result.RuleId,
|
||||
result.ProcessName,
|
||||
result.ProcessId,
|
||||
result.UserMessage);
|
||||
}
|
||||
|
||||
private bool IsEnabled() =>
|
||||
this.settingsService.Settings.ApplyPersistentRulesOnProcessStart;
|
||||
|
||||
private static bool IsProcessEligible(ProcessModel process) =>
|
||||
process.ProcessId > 0 && !string.IsNullOrWhiteSpace(process.Name);
|
||||
|
||||
private static string GetRuleSignature(PersistentProcessRule rule) =>
|
||||
string.Join(
|
||||
"|",
|
||||
string.IsNullOrWhiteSpace(rule.Id) ? rule.Name : rule.Id,
|
||||
rule.UpdatedAt.ToUniversalTime().Ticks);
|
||||
|
||||
private readonly record struct RuleAttemptKey(int ProcessId, string RuleSignature);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ namespace ThreadPilot.Services
|
||||
{
|
||||
Task<IReadOnlyList<PersistentRuleApplyResult>> ApplyMatchingRulesAsync(
|
||||
ProcessModel process,
|
||||
Predicate<PersistentProcessRule>? ruleFilter = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -49,6 +50,7 @@ namespace ThreadPilot.Services
|
||||
|
||||
public async Task<IReadOnlyList<PersistentRuleApplyResult>> ApplyMatchingRulesAsync(
|
||||
ProcessModel process,
|
||||
Predicate<PersistentProcessRule>? ruleFilter = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(process);
|
||||
@@ -56,7 +58,9 @@ namespace ThreadPilot.Services
|
||||
var rules = await this.ruleStore.LoadAsync().ConfigureAwait(false);
|
||||
var results = new List<PersistentRuleApplyResult>();
|
||||
|
||||
foreach (var rule in rules.Where(rule => this.matcher.IsMatch(rule, process)))
|
||||
foreach (var rule in rules.Where(rule =>
|
||||
(ruleFilter == null || ruleFilter(rule)) &&
|
||||
this.matcher.IsMatch(rule, process)))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
results.Add(await this.ApplyRuleAsync(rule, process, cancellationToken).ConfigureAwait(false));
|
||||
|
||||
@@ -39,6 +39,7 @@ namespace ThreadPilot.Services
|
||||
private readonly IProcessService processService;
|
||||
private readonly ICoreMaskService coreMaskService;
|
||||
private readonly IAffinityApplyService affinityApplyService;
|
||||
private readonly IPersistentRuleAutoApplyService persistentRuleAutoApplyService;
|
||||
private readonly PowerPlanTransitionGate powerPlanTransitionGate;
|
||||
private readonly ILogger<ProcessMonitorManagerService> logger;
|
||||
private readonly IEnhancedLoggingService enhancedLogger;
|
||||
@@ -74,6 +75,7 @@ namespace ThreadPilot.Services
|
||||
IProcessService processService,
|
||||
ICoreMaskService coreMaskService,
|
||||
IAffinityApplyService affinityApplyService,
|
||||
IPersistentRuleAutoApplyService persistentRuleAutoApplyService,
|
||||
PowerPlanTransitionGate powerPlanTransitionGate,
|
||||
ILogger<ProcessMonitorManagerService> logger,
|
||||
IEnhancedLoggingService enhancedLogger)
|
||||
@@ -86,6 +88,7 @@ namespace ThreadPilot.Services
|
||||
this.processService = processService ?? throw new ArgumentNullException(nameof(processService));
|
||||
this.coreMaskService = coreMaskService ?? throw new ArgumentNullException(nameof(coreMaskService));
|
||||
this.affinityApplyService = affinityApplyService ?? throw new ArgumentNullException(nameof(affinityApplyService));
|
||||
this.persistentRuleAutoApplyService = persistentRuleAutoApplyService ?? throw new ArgumentNullException(nameof(persistentRuleAutoApplyService));
|
||||
this.powerPlanTransitionGate = powerPlanTransitionGate ?? throw new ArgumentNullException(nameof(powerPlanTransitionGate));
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
this.enhancedLogger = enhancedLogger ?? throw new ArgumentNullException(nameof(enhancedLogger));
|
||||
@@ -193,6 +196,7 @@ namespace ThreadPilot.Services
|
||||
{
|
||||
this.coreMaskService.UnregisterMaskApplication(processId);
|
||||
this.processService.UntrackProcess(processId);
|
||||
this.persistentRuleAutoApplyService.MarkProcessExited(processId);
|
||||
}
|
||||
this.runningAssociatedProcesses.Clear();
|
||||
|
||||
@@ -224,7 +228,8 @@ namespace ThreadPilot.Services
|
||||
|
||||
try
|
||||
{
|
||||
var currentProcesses = await this.processMonitorService.GetRunningProcessesAsync();
|
||||
var currentProcesses = (await this.processMonitorService.GetRunningProcessesAsync()).ToList();
|
||||
await this.ApplyPersistentRulesForDiscoveredProcessesAsync(currentProcesses);
|
||||
var associatedProcesses = new List<ProcessModel>();
|
||||
var currentProcessIds = new HashSet<int>(currentProcesses.Select(p => p.ProcessId));
|
||||
|
||||
@@ -235,6 +240,7 @@ namespace ThreadPilot.Services
|
||||
{
|
||||
this.coreMaskService.UnregisterMaskApplication(trackedPid);
|
||||
this.processService.UntrackProcess(trackedPid);
|
||||
this.persistentRuleAutoApplyService.MarkProcessExited(trackedPid);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,6 +369,8 @@ namespace ThreadPilot.Services
|
||||
LogEventTypes.ProcessMonitoring.Started,
|
||||
e.Process.Name, e.Process.ProcessId, "Process started and detected by monitoring");
|
||||
|
||||
await this.ApplyPersistentRulesForProcessStartAsync(e.Process);
|
||||
|
||||
var association = this.configuration.FindMatchingAssociation(e.Process);
|
||||
if (association != null)
|
||||
{
|
||||
@@ -421,6 +429,8 @@ namespace ThreadPilot.Services
|
||||
|
||||
try
|
||||
{
|
||||
this.persistentRuleAutoApplyService.MarkProcessExited(e.Process.ProcessId);
|
||||
|
||||
if (this.runningAssociatedProcesses.TryRemove(e.Process.ProcessId, out _))
|
||||
{
|
||||
this.coreMaskService.UnregisterMaskApplication(e.Process.ProcessId);
|
||||
@@ -602,6 +612,66 @@ namespace ThreadPilot.Services
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ApplyPersistentRulesForDiscoveredProcessesAsync(IEnumerable<ProcessModel> processes)
|
||||
{
|
||||
try
|
||||
{
|
||||
var results = await this.persistentRuleAutoApplyService.ApplyForDiscoveredProcessesAsync(processes);
|
||||
await this.LogPersistentRuleResultsAsync(results);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogWarning(ex, "Persistent rule auto-apply failed during process snapshot refresh");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ApplyPersistentRulesForProcessStartAsync(ProcessModel process)
|
||||
{
|
||||
try
|
||||
{
|
||||
var results = await this.persistentRuleAutoApplyService.ApplyForProcessStartAsync(process);
|
||||
await this.LogPersistentRuleResultsAsync(results);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogWarning(
|
||||
ex,
|
||||
"Persistent rule auto-apply failed for process {ProcessName} (PID: {ProcessId})",
|
||||
process.Name,
|
||||
process.ProcessId);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LogPersistentRuleResultsAsync(IReadOnlyList<PersistentRuleAutoApplyResult> results)
|
||||
{
|
||||
foreach (var result in results)
|
||||
{
|
||||
if (result.Success)
|
||||
{
|
||||
await this.enhancedLogger.LogProcessMonitoringEventAsync(
|
||||
LogEventTypes.ProcessMonitoring.AssociationTriggered,
|
||||
result.ProcessName,
|
||||
result.ProcessId,
|
||||
$"Persistent rule '{result.RuleId}' applied automatically");
|
||||
}
|
||||
else
|
||||
{
|
||||
this.logger.LogDebug(
|
||||
"Persistent rule {RuleId} was not applied to process {ProcessName} (PID: {ProcessId}): {Message}",
|
||||
result.RuleId,
|
||||
result.ProcessName,
|
||||
result.ProcessId,
|
||||
result.UserMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdateSettings()
|
||||
{
|
||||
// Update the process monitor service with new settings
|
||||
@@ -834,4 +904,3 @@ namespace ThreadPilot.Services
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -112,6 +112,7 @@ namespace ThreadPilot.Services
|
||||
services.AddSingleton<IPersistentProcessRuleStore, PersistentProcessRuleJsonStore>();
|
||||
services.AddSingleton<IPersistentProcessRuleMatcher, PersistentProcessRuleMatcher>();
|
||||
services.AddSingleton<IPersistentRulesEngine, PersistentRulesEngine>();
|
||||
services.AddSingleton<IPersistentRuleAutoApplyService, PersistentRuleAutoApplyService>();
|
||||
services.AddSingleton<IProcessRuleCreationService, ProcessRuleCreationService>();
|
||||
services.AddSingleton<ProcessFilterService>();
|
||||
services.AddSingleton<IVirtualizedProcessService, VirtualizedProcessService>();
|
||||
|
||||
@@ -11,6 +11,7 @@ namespace ThreadPilot.Core.Tests
|
||||
|
||||
Assert.True(settings.AutostartWithWindows);
|
||||
Assert.False(settings.StartMinimized);
|
||||
Assert.True(settings.ApplyPersistentRulesOnProcessStart);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
/*
|
||||
* ThreadPilot - persistent rule auto-apply coordinator tests.
|
||||
*/
|
||||
namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using System.Diagnostics;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using ThreadPilot.Models;
|
||||
using ThreadPilot.Services;
|
||||
|
||||
public sealed class PersistentRuleAutoApplyServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task ApplyForProcessStartAsync_WhenMatchingEnabledRuleExists_CallsRulesEngine()
|
||||
{
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService([rule], engine.Object);
|
||||
|
||||
var results = await service.ApplyForProcessStartAsync(process);
|
||||
|
||||
Assert.Single(results);
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
process,
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForProcessStartAsync_WhenRuleIsDisabled_DoesNotCallRulesEngine()
|
||||
{
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule() with { IsEnabled = false };
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService([rule], engine.Object);
|
||||
|
||||
var results = await service.ApplyForProcessStartAsync(process);
|
||||
|
||||
Assert.Empty(results);
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
It.IsAny<ProcessModel>(),
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForProcessStartAsync_WhenNoRuleMatches_DoesNotCallRulesEngine()
|
||||
{
|
||||
var process = CreateProcess("editor.exe");
|
||||
var rule = CreateRule(processName: "game.exe");
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService([rule], engine.Object);
|
||||
|
||||
var results = await service.ApplyForProcessStartAsync(process);
|
||||
|
||||
Assert.Empty(results);
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
It.IsAny<ProcessModel>(),
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForProcessStartAsync_DoesNotReapplySameRuleDuringCooldown()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService([rule], engine.Object, nowProvider: () => now);
|
||||
|
||||
await service.ApplyForProcessStartAsync(process);
|
||||
await service.ApplyForProcessStartAsync(process);
|
||||
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
process,
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForProcessStartAsync_AfterCooldown_RetriesRule()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService([rule], engine.Object, nowProvider: () => now);
|
||||
|
||||
await service.ApplyForProcessStartAsync(process);
|
||||
now = now.AddSeconds(31);
|
||||
await service.ApplyForProcessStartAsync(process);
|
||||
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
process,
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForProcessStartAsync_AfterProcessExit_DoesNotSuppressReusedPid()
|
||||
{
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService([rule], engine.Object);
|
||||
|
||||
await service.ApplyForProcessStartAsync(process);
|
||||
service.MarkProcessExited(process.ProcessId);
|
||||
await service.ApplyForProcessStartAsync(process);
|
||||
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
process,
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForProcessStartAsync_WithAccessDeniedFailure_ReturnsFailureWithoutThrowing()
|
||||
{
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var failure = CreateFailure(rule, process, ProcessOperationUserMessages.AccessDenied, isAccessDenied: true);
|
||||
var engine = CreateEngine(rule, failure);
|
||||
var service = CreateService([rule], engine.Object);
|
||||
|
||||
var result = Assert.Single(await service.ApplyForProcessStartAsync(process));
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.True(result.IsAccessDenied);
|
||||
Assert.Equal(ProcessOperationUserMessages.AccessDenied, result.UserMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForProcessStartAsync_WithProcessExitedFailure_ReturnsFailureWithoutThrowing()
|
||||
{
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var failure = CreateFailure(rule, process, ProcessOperationUserMessages.ProcessExited, isProcessExited: true);
|
||||
var engine = CreateEngine(rule, failure);
|
||||
var service = CreateService([rule], engine.Object);
|
||||
|
||||
var result = Assert.Single(await service.ApplyForProcessStartAsync(process));
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.True(result.IsProcessExited);
|
||||
Assert.Equal(ProcessOperationUserMessages.ProcessExited, result.UserMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForProcessStartAsync_WithProtectedProcessFailure_ReturnsSafeFailureWithoutThrowing()
|
||||
{
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var failure = CreateFailure(
|
||||
rule,
|
||||
process,
|
||||
ProcessOperationUserMessages.AntiCheatProtectedLikely,
|
||||
isAccessDenied: true,
|
||||
isAntiCheatLikely: true);
|
||||
var engine = CreateEngine(rule, failure);
|
||||
var service = CreateService([rule], engine.Object);
|
||||
|
||||
var result = Assert.Single(await service.ApplyForProcessStartAsync(process));
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.True(result.IsAntiCheatLikely);
|
||||
Assert.DoesNotContain("bypass", result.UserMessage, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForProcessStartAsync_WhenRulesEngineCancels_PropagatesCancellation()
|
||||
{
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var engine = CreateEngineThatCancels();
|
||||
var service = CreateService([rule], engine.Object);
|
||||
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() =>
|
||||
service.ApplyForProcessStartAsync(process));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForDiscoveredProcessesAsync_FeatureFlagDisabled_DoesNotCallRulesEngine()
|
||||
{
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService(
|
||||
[rule],
|
||||
engine.Object,
|
||||
settings: new ApplicationSettingsModel { ApplyPersistentRulesOnProcessStart = false });
|
||||
|
||||
var results = await service.ApplyForDiscoveredProcessesAsync([process]);
|
||||
|
||||
Assert.Empty(results);
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
It.IsAny<ProcessModel>(),
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForDiscoveredProcessesAsync_ClearsCooldownForProcessesNoLongerPresent()
|
||||
{
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService([rule], engine.Object);
|
||||
|
||||
await service.ApplyForDiscoveredProcessesAsync([process]);
|
||||
await service.ApplyForDiscoveredProcessesAsync([]);
|
||||
await service.ApplyForDiscoveredProcessesAsync([process]);
|
||||
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
process,
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Exactly(2));
|
||||
}
|
||||
|
||||
private static PersistentRuleAutoApplyService CreateService(
|
||||
IReadOnlyList<PersistentProcessRule> rules,
|
||||
IPersistentRulesEngine engine,
|
||||
ApplicationSettingsModel? settings = null,
|
||||
Func<DateTimeOffset>? nowProvider = null) =>
|
||||
new(
|
||||
new FakePersistentProcessRuleStore(rules),
|
||||
new PersistentProcessRuleMatcher(),
|
||||
engine,
|
||||
CreateSettingsService(settings ?? new ApplicationSettingsModel()),
|
||||
NullLogger<PersistentRuleAutoApplyService>.Instance,
|
||||
nowProvider ?? (() => DateTimeOffset.UtcNow),
|
||||
TimeSpan.FromSeconds(30));
|
||||
|
||||
private static Mock<IPersistentRulesEngine> CreateEngine(
|
||||
PersistentProcessRule rule,
|
||||
PersistentRuleApplyResult result)
|
||||
{
|
||||
var engine = new Mock<IPersistentRulesEngine>(MockBehavior.Strict);
|
||||
engine
|
||||
.Setup(x => x.ApplyMatchingRulesAsync(
|
||||
It.IsAny<ProcessModel>(),
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync((ProcessModel _, Predicate<PersistentProcessRule>? predicate, CancellationToken _) =>
|
||||
predicate == null || predicate(rule)
|
||||
? new[] { result }
|
||||
: Array.Empty<PersistentRuleApplyResult>());
|
||||
return engine;
|
||||
}
|
||||
|
||||
private static Mock<IPersistentRulesEngine> CreateEngineThatCancels()
|
||||
{
|
||||
var engine = new Mock<IPersistentRulesEngine>(MockBehavior.Strict);
|
||||
engine
|
||||
.Setup(x => x.ApplyMatchingRulesAsync(
|
||||
It.IsAny<ProcessModel>(),
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new OperationCanceledException());
|
||||
return engine;
|
||||
}
|
||||
|
||||
private static IApplicationSettingsService CreateSettingsService(ApplicationSettingsModel settings)
|
||||
{
|
||||
var settingsService = new Mock<IApplicationSettingsService>(MockBehavior.Loose);
|
||||
settingsService.SetupGet(x => x.Settings).Returns(settings);
|
||||
return settingsService.Object;
|
||||
}
|
||||
|
||||
private static ProcessModel CreateProcess(string name = "game.exe") =>
|
||||
new()
|
||||
{
|
||||
ProcessId = 42,
|
||||
Name = name,
|
||||
ExecutablePath = @"C:\Games\Game.exe",
|
||||
Priority = ProcessPriorityClass.Normal,
|
||||
};
|
||||
|
||||
private static PersistentProcessRule CreateRule(string id = "rule", string processName = "game.exe") =>
|
||||
new()
|
||||
{
|
||||
Id = id,
|
||||
Name = id,
|
||||
IsEnabled = true,
|
||||
ProcessName = processName,
|
||||
LegacyAffinityMask = 3,
|
||||
ApplyAffinityOnStart = true,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
UpdatedAt = DateTime.UtcNow,
|
||||
};
|
||||
|
||||
private static PersistentRuleApplyResult CreateSuccess(PersistentProcessRule rule, ProcessModel process) =>
|
||||
new()
|
||||
{
|
||||
Success = true,
|
||||
RuleId = rule.Id,
|
||||
ProcessId = process.ProcessId,
|
||||
ProcessName = process.Name,
|
||||
AffinityApplied = true,
|
||||
UserMessage = "Persistent rule applied.",
|
||||
TechnicalMessage = "ok",
|
||||
};
|
||||
|
||||
private static PersistentRuleApplyResult CreateFailure(
|
||||
PersistentProcessRule rule,
|
||||
ProcessModel process,
|
||||
string userMessage,
|
||||
bool isAccessDenied = false,
|
||||
bool isAntiCheatLikely = false,
|
||||
bool isProcessExited = false) =>
|
||||
new()
|
||||
{
|
||||
Success = false,
|
||||
RuleId = rule.Id,
|
||||
ProcessId = process.ProcessId,
|
||||
ProcessName = process.Name,
|
||||
UserMessage = userMessage,
|
||||
TechnicalMessage = userMessage,
|
||||
IsAccessDenied = isAccessDenied,
|
||||
IsAntiCheatLikely = isAntiCheatLikely,
|
||||
IsProcessExited = isProcessExited,
|
||||
};
|
||||
|
||||
private sealed class FakePersistentProcessRuleStore(IReadOnlyList<PersistentProcessRule> rules)
|
||||
: IPersistentProcessRuleStore
|
||||
{
|
||||
public Task<IReadOnlyList<PersistentProcessRule>> LoadAsync() =>
|
||||
Task.FromResult(rules);
|
||||
|
||||
public Task SaveAsync(IReadOnlyList<PersistentProcessRule> rules) =>
|
||||
Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Threading;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using ThreadPilot.Models;
|
||||
@@ -314,6 +315,121 @@ namespace ThreadPilot.Core.Tests
|
||||
coreMaskService.Verify(x => x.RegisterMaskApplication(31, "mask-game"), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ProcessStarted_AppliesPersistentRulesThroughCoordinator()
|
||||
{
|
||||
var process = new ProcessModel { ProcessId = 41, Name = "game.exe" };
|
||||
var processMonitor = new FakeProcessMonitorService();
|
||||
var configuration = new ProcessMonitorConfiguration();
|
||||
var associationService = CreateAssociationService(configuration);
|
||||
var powerPlanService = CreatePowerPlanService();
|
||||
var notificationService = CreateNotificationService();
|
||||
var processService = CreateProcessService();
|
||||
var coreMaskService = CreateCoreMaskService();
|
||||
var affinityApplyService = CreateAffinityApplyService();
|
||||
var autoApplyService = CreateAutoApplyService();
|
||||
var manager = CreateService(
|
||||
processMonitor,
|
||||
associationService,
|
||||
powerPlanService,
|
||||
notificationService,
|
||||
processService,
|
||||
coreMaskService,
|
||||
affinityApplyService,
|
||||
autoApplyService);
|
||||
|
||||
await manager.StartAsync();
|
||||
processMonitor.RaiseProcessStarted(process);
|
||||
await Task.Delay(100);
|
||||
|
||||
autoApplyService.Verify(
|
||||
x => x.ApplyForDiscoveredProcessesAsync(
|
||||
It.IsAny<IEnumerable<ProcessModel>>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
autoApplyService.Verify(
|
||||
x => x.ApplyForProcessStartAsync(process, It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateCurrentProcessesAsync_WhenPersistentRuleSnapshotApplyCancels_DoesNotLogWarning()
|
||||
{
|
||||
var processMonitor = new FakeProcessMonitorService
|
||||
{
|
||||
RunningProcesses =
|
||||
{
|
||||
new ProcessModel { ProcessId = 42, Name = "game.exe" },
|
||||
},
|
||||
};
|
||||
var configuration = new ProcessMonitorConfiguration();
|
||||
var associationService = CreateAssociationService(configuration);
|
||||
var powerPlanService = CreatePowerPlanService();
|
||||
var notificationService = CreateNotificationService();
|
||||
var processService = CreateProcessService();
|
||||
var coreMaskService = CreateCoreMaskService();
|
||||
var affinityApplyService = CreateAffinityApplyService();
|
||||
var autoApplyService = CreateAutoApplyService();
|
||||
autoApplyService
|
||||
.Setup(x => x.ApplyForDiscoveredProcessesAsync(
|
||||
It.IsAny<IEnumerable<ProcessModel>>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new OperationCanceledException());
|
||||
var logger = new CapturingLogger<ProcessMonitorManagerService>();
|
||||
var manager = CreateService(
|
||||
processMonitor,
|
||||
associationService,
|
||||
powerPlanService,
|
||||
notificationService,
|
||||
processService,
|
||||
coreMaskService,
|
||||
affinityApplyService,
|
||||
autoApplyService,
|
||||
logger);
|
||||
|
||||
await manager.StartAsync();
|
||||
await manager.EvaluateCurrentProcessesAsync();
|
||||
|
||||
Assert.Empty(logger.WarningMessages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ProcessStarted_WhenPersistentRuleAutoApplyCancels_DoesNotLogWarning()
|
||||
{
|
||||
var process = new ProcessModel { ProcessId = 43, Name = "game.exe" };
|
||||
var processMonitor = new FakeProcessMonitorService();
|
||||
var configuration = new ProcessMonitorConfiguration();
|
||||
var associationService = CreateAssociationService(configuration);
|
||||
var powerPlanService = CreatePowerPlanService();
|
||||
var notificationService = CreateNotificationService();
|
||||
var processService = CreateProcessService();
|
||||
var coreMaskService = CreateCoreMaskService();
|
||||
var affinityApplyService = CreateAffinityApplyService();
|
||||
var autoApplyService = CreateAutoApplyService();
|
||||
autoApplyService
|
||||
.Setup(x => x.ApplyForProcessStartAsync(
|
||||
process,
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new OperationCanceledException());
|
||||
var logger = new CapturingLogger<ProcessMonitorManagerService>();
|
||||
var manager = CreateService(
|
||||
processMonitor,
|
||||
associationService,
|
||||
powerPlanService,
|
||||
notificationService,
|
||||
processService,
|
||||
coreMaskService,
|
||||
affinityApplyService,
|
||||
autoApplyService,
|
||||
logger);
|
||||
|
||||
await manager.StartAsync();
|
||||
processMonitor.RaiseProcessStarted(process);
|
||||
await Task.Delay(100);
|
||||
|
||||
Assert.Empty(logger.WarningMessages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Dispose_CompletesOnBlockingSynchronizationContext()
|
||||
{
|
||||
@@ -378,7 +494,9 @@ namespace ThreadPilot.Core.Tests
|
||||
Mock<INotificationService> notificationService,
|
||||
Mock<IProcessService> processService,
|
||||
Mock<ICoreMaskService> coreMaskService,
|
||||
Mock<IAffinityApplyService> affinityApplyService)
|
||||
Mock<IAffinityApplyService> affinityApplyService,
|
||||
Mock<IPersistentRuleAutoApplyService>? autoApplyService = null,
|
||||
ILogger<ProcessMonitorManagerService>? logger = null)
|
||||
{
|
||||
var enhancedLogger = new Mock<IEnhancedLoggingService>(MockBehavior.Loose);
|
||||
enhancedLogger
|
||||
@@ -403,8 +521,9 @@ namespace ThreadPilot.Core.Tests
|
||||
processService.Object,
|
||||
coreMaskService.Object,
|
||||
affinityApplyService.Object,
|
||||
(autoApplyService ?? CreateAutoApplyService()).Object,
|
||||
new PowerPlanTransitionGate(TimeSpan.FromSeconds(2), () => DateTimeOffset.UtcNow),
|
||||
NullLogger<ProcessMonitorManagerService>.Instance,
|
||||
logger ?? NullLogger<ProcessMonitorManagerService>.Instance,
|
||||
enhancedLogger.Object);
|
||||
}
|
||||
|
||||
@@ -464,6 +583,23 @@ namespace ThreadPilot.Core.Tests
|
||||
return affinityApplyService;
|
||||
}
|
||||
|
||||
private static Mock<IPersistentRuleAutoApplyService> CreateAutoApplyService()
|
||||
{
|
||||
var autoApplyService = new Mock<IPersistentRuleAutoApplyService>(MockBehavior.Strict);
|
||||
autoApplyService
|
||||
.Setup(x => x.ApplyForDiscoveredProcessesAsync(
|
||||
It.IsAny<IEnumerable<ProcessModel>>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(Array.Empty<PersistentRuleAutoApplyResult>());
|
||||
autoApplyService
|
||||
.Setup(x => x.ApplyForProcessStartAsync(
|
||||
It.IsAny<ProcessModel>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(Array.Empty<PersistentRuleAutoApplyResult>());
|
||||
autoApplyService.Setup(x => x.MarkProcessExited(It.IsAny<int>()));
|
||||
return autoApplyService;
|
||||
}
|
||||
|
||||
private sealed class FakeProcessMonitorService : IProcessMonitorService
|
||||
{
|
||||
public event EventHandler<ProcessEventArgs>? ProcessStarted;
|
||||
@@ -528,5 +664,38 @@ namespace ThreadPilot.Core.Tests
|
||||
// Intentionally do not pump posted work to emulate a blocked UI thread.
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class CapturingLogger<T> : ILogger<T>
|
||||
{
|
||||
public List<string> WarningMessages { get; } = new();
|
||||
|
||||
public IDisposable? BeginScope<TState>(TState state)
|
||||
where TState : notnull =>
|
||||
NullScope.Instance;
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
|
||||
public void Log<TState>(
|
||||
LogLevel logLevel,
|
||||
EventId eventId,
|
||||
TState state,
|
||||
Exception? exception,
|
||||
Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
if (logLevel == LogLevel.Warning)
|
||||
{
|
||||
this.WarningMessages.Add(formatter(state, exception));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class NullScope : IDisposable
|
||||
{
|
||||
public static readonly NullScope Instance = new();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user