9a4baba19a
* feat: back up persistent rules and resolve rule precedence deterministically
- Configuration export now includes persistent process rules (schema 3.0),
stays compatible with 2.0 bundles, validates before writing, previews
what an import replaces and rolls back on failure.
- Matching rules apply broad-to-specific (name, wildcard path, exact path,
then most recently edited), shared by the engine and the process summary,
which now lists the apply order and flags conflicting values.
- Localized the new strings in all seven languages.
* feat: clearer process and rule editors
- Process details: CPU, memory and I/O priority pickers with an explicit
Apply, undo of the last manual priority change (guarded against reused
PIDs), adaptive side/bottom details panel.
- Manual process control stays available while automation is paused, with
a persistent notice instead of an overlay.
- Saved-rule editor stages all edits (including the core mask) and saves
them together, showing pending changes.
- Localized the new strings in all seven languages.
* fix: one save path for a saved rule's cores
The rules editor's core mask went through a new update path that reported
success without saving when no affinity payload was built, and kept a
legacy mask next to a CPU selection. Merge it with the old single-purpose
method (now unused), keep its checks, and localize the undo message.
* feat: per-process efficiency mode (EcoQoS) for live processes and rules
Closes #66.
- Native: SetProcessInformation/GetProcessInformation with
ProcessPowerThrottling (EXECUTION_SPEED), three states: Windows decides,
On (EcoQoS), Off (never throttle / HighQoS).
- Process tab: context menu entries, a picker with Apply in the details
panel, current state in the summary, undo of the last change, included
when saving current settings as a rule (only if explicitly set).
- Rules: EfficiencyMode + ApplyEfficiencyModeOnStart, applied by the rules
engine, editable in the saved-rule editor, validated on import and part
of conflict detection.
- The summary flags when the global Power Throttling tweak voids it. CPU
priority is left alone, unlike Task Manager's efficiency mode.
- Localized in all seven languages.
* chore: keep CRLF line endings in SelectedProcessSummaryViewModel
* feat: clearer navigation, process page and rules editor
- Navigation pane open with short labels instead of seven bare icons.
- Processes: one toolbar row (search with placeholder, Filters and
Columns menus, sort, refresh); details split into Process, Priority,
CPU cores and Rule cards; pickers start from the process's current
values and stay empty when a value cannot be read; help paragraphs
moved into tooltips; core picker always visible.
- Rules: process rules first, clearer tab names, localized choices in the
saved-rule editor instead of internal enum names.
- Shorter page titles and subtitles in all seven languages; removed the
strings this made unused.
No data format changes.
* feat: settings and tweaks as Windows 11 rows, localized rule list
- Settings: one column of rows (what it is on the left, its switch on the
right), most used sections first, Save as the primary action.
- Tweaks: one tweak per row with its status dot and switch.
- Rule list: 'Applies' and 'Mode' columns use the same localized labels as
the editor and refresh on language change.
- Removed 76 strings no code referenced, from all seven languages.
* fix: issues found testing the beta in a clean Windows 11 VM
- Process counter could show more visible processes than the total
('157 / 151'): the batch total was a snapshot from the first load.
- Narrow windows (or 150% scaling): toolbar buttons move under the search
box instead of squeezing it to a few letters.
- Rules list keeps the 'Applies' column readable when narrow.
- Settings status message gets its own line instead of being cut.
Tested in a Hyper-V Windows 11 VM: clean install, upgrade, uninstall,
light and dark theme, 100% and 150% scaling.
* feat: remember layout choices; Windows 11 toggles in Tweaks
- The navigation pane, window size/position/maximized state, and the
process list filters, sort and columns now survive a restart. They live
in ui-state.json, apart from settings.json, so they never mark the
Settings page as unsaved or travel in exported configurations. A corrupt
file falls back to defaults; tests write to a temp file.
- Fixes the pane re-opening on every start (it was hard-coded open).
- Tweaks use a native-looking Windows 11 switch (40x20 track, sliding
thumb) with On/Off written beside it.
- New test: every on/off setting survives save and reload.
* docs: handoff for the 1.7.7 PR stack and beta test
* fix: P/E cores from the highest EfficiencyClass, AMD CCDs from real L3 groups
The legacy topology treated the lowest EfficiencyClass as the performance
core, swapping P- and E-cores on hybrid Intel CPUs. AMD CCDs were guessed
as 8 cores each, which split 6+6 parts (7900X3D, 9900X3D) into 8+4; they now
come from the L3 groups Windows reports, with the guess kept only as a
fallback. The topology snapshot also keeps each L3 group's size.
* feat: Game Boost, CPU Sets for the game and selected background apps
While a detected game runs, Game Boost sets process default CPU Sets from
the CPU topology: on AMD X3D with one larger L3 the game goes to the V-Cache
CCD, on Intel hybrid CPUs to the P-cores, and selected background apps
(browsers, sync clients, updaters, launchers) to the other cores. On dual-CCD
parts with equal L3 only the background moves, unless Isolation mode also
keeps the game on CCD0. Single-L3 and unreadable topologies are left to
Windows. Above Normal priority for the game is optional; never High.
Each change is written to a journal before it is made and undone when the
game exits, Game Boost is turned off or ThreadPilot closes, and on the next
start after a crash. Only values still exactly as Game Boost set them are
restored, never one a user rule or a manual change has taken over since.
Persistent rules and Game Boost share one apply gate, and a rule always
wins over Game Boost for the setting it covers.
The switch, mode and lists are on the Tweaks page, off by default, and take
effect without a restart.
* fix: Game Boost background entries with a full path never matched
The background list compared full-path entries against an empty path, so
only bare process names worked. Found by a new integration test that runs
the real services on two copies of PING.EXE: CPU Sets and priority are set
and read back through Windows, removed when Game Boost is turned off, and
undone from the journal after a simulated crash. The topology is simulated
from this machine's CPU Set IDs, so the test also runs on CPUs where Game
Boost would not act; it skips itself below 8 cores.
* feat: report Game Boost sessions and restore results in Activity
* test: diagnose EcoQoS read failures on Windows Server
* chore: prepare 1.7.7-beta.2 and keep prereleases out of stable channels
* test: use native full-query access mask in EcoQoS diagnostic
* docs: update beta handoff and prerelease publication policy
* ci: run native EcoQoS tests on a Windows 11-era kernel
Windows Server 2022 build 20348 rejects GetProcessInformation(ProcessPowerThrottling) with ERROR_INVALID_PARAMETER (87), with both limited and full query handles. Windows 11 local tests pass. Use Server 2025 for CI/release tests and smoke testing; keep the real round-trip assertions, remove temporary probes.
* test: lock beta publication and native runner contracts
* chore: separate stable 1.7.7 from experimental Game Boost
Stable retains the validated EcoQoS/rules/UI stack. Preserve the complete local Game Boost implementation at ef2ec24 for the separate 1.7.8-beta.1 prerelease; no experimental Game Boost/topology changes ship in stable. Keep channel-aware publication and Windows 11-era native CI tests.
734 lines
31 KiB
C#
734 lines
31 KiB
C#
/*
|
|
* ThreadPilot - persistent process rule creation from explicit Process tab actions.
|
|
*/
|
|
namespace ThreadPilot.Services
|
|
{
|
|
using System.Diagnostics;
|
|
using Microsoft.Extensions.Logging;
|
|
using ThreadPilot.Models;
|
|
|
|
public interface IProcessRuleCreationService
|
|
{
|
|
Task<ProcessRuleCreationResult> SaveRuleAsync(
|
|
ProcessModel process,
|
|
ProcessRuleCreationPayload payload,
|
|
CancellationToken cancellationToken = default);
|
|
|
|
Task<ProcessRuleCreationResult> SaveCurrentSettingsAsRuleAsync(
|
|
ProcessModel process,
|
|
IReadOnlyList<bool>? currentCoreSelection,
|
|
ProcessMemoryPriority? currentMemoryPriority,
|
|
CpuAssignmentMode cpuAssignmentMode = CpuAssignmentMode.Automatic,
|
|
ProcessIoPriority? currentIoPriority = null,
|
|
bool preventSystemSleepWhileRunning = false,
|
|
ProcessEfficiencyMode? currentEfficiencyMode = null,
|
|
CancellationToken cancellationToken = default);
|
|
|
|
Task<ProcessRuleCreationResult> DeleteRuleAsync(
|
|
ProcessModel process,
|
|
CancellationToken cancellationToken = default);
|
|
|
|
Task<ProcessRuleCreationResult> DeleteRuleByIdAsync(
|
|
string ruleId,
|
|
CancellationToken cancellationToken = default);
|
|
|
|
Task<ProcessRuleCreationResult> UpdateRuleAsync(
|
|
PersistentProcessRule rule,
|
|
CancellationToken cancellationToken = default);
|
|
|
|
Task<ProcessRuleCreationResult> UpdateRuleWithCoreSelectionAsync(
|
|
PersistentProcessRule rule,
|
|
IReadOnlyList<bool>? coreSelection,
|
|
CancellationToken cancellationToken = default);
|
|
|
|
Task<IReadOnlyList<string>> GetRulesNeedingTopologyReviewAsync(
|
|
CancellationToken cancellationToken = default);
|
|
}
|
|
|
|
public sealed record ProcessRuleCreationPayload
|
|
{
|
|
public CpuSelection? CpuSelection { get; init; }
|
|
|
|
public long? LegacyAffinityMask { get; init; }
|
|
|
|
public ProcessPriorityClass? Priority { get; init; }
|
|
|
|
public ProcessMemoryPriority? MemoryPriority { get; init; }
|
|
|
|
public ProcessIoPriority? IoPriority { get; init; }
|
|
|
|
public ProcessEfficiencyMode? EfficiencyMode { get; init; }
|
|
|
|
public bool PreventSystemSleepWhileRunning { get; init; }
|
|
|
|
public CpuAssignmentMode CpuAssignmentMode { get; init; } = CpuAssignmentMode.Automatic;
|
|
}
|
|
|
|
public sealed record ProcessRuleCreationResult
|
|
{
|
|
public bool Success { get; init; }
|
|
|
|
public bool Created { get; init; }
|
|
|
|
public bool Updated { get; init; }
|
|
|
|
public PersistentProcessRule? Rule { get; init; }
|
|
|
|
public string UserMessage { get; init; } = string.Empty;
|
|
|
|
public string ErrorCode { get; init; } = string.Empty;
|
|
|
|
public static ProcessRuleCreationResult Failed(string errorCode, string userMessage) =>
|
|
new()
|
|
{
|
|
Success = false,
|
|
ErrorCode = errorCode,
|
|
UserMessage = userMessage,
|
|
};
|
|
}
|
|
|
|
public sealed class ProcessRuleCreationService : IProcessRuleCreationService
|
|
{
|
|
public const string NoCurrentSettingsMessage =
|
|
"There are no current settings to save as a rule.";
|
|
|
|
public const string NoSavedRuleMessage =
|
|
"There is no saved rule for this process.";
|
|
|
|
public const string UnsafeAffinityMessage =
|
|
"The current affinity selection cannot be saved safely on this CPU topology.";
|
|
|
|
private const string RuleDescription = "Created from Process tab action.";
|
|
|
|
private readonly IPersistentProcessRuleStore ruleStore;
|
|
private readonly ICpuTopologyProvider? topologyProvider;
|
|
private readonly CpuSelectionMigrationService migrationService;
|
|
private readonly ILogger<ProcessRuleCreationService> logger;
|
|
|
|
public ProcessRuleCreationService(
|
|
IPersistentProcessRuleStore ruleStore,
|
|
ICpuTopologyProvider? topologyProvider,
|
|
CpuSelectionMigrationService migrationService,
|
|
ILogger<ProcessRuleCreationService> logger)
|
|
{
|
|
this.ruleStore = ruleStore ?? throw new ArgumentNullException(nameof(ruleStore));
|
|
this.topologyProvider = topologyProvider;
|
|
this.migrationService = migrationService ?? throw new ArgumentNullException(nameof(migrationService));
|
|
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
}
|
|
|
|
public async Task<ProcessRuleCreationResult> SaveCurrentSettingsAsRuleAsync(
|
|
ProcessModel process,
|
|
IReadOnlyList<bool>? currentCoreSelection,
|
|
ProcessMemoryPriority? currentMemoryPriority,
|
|
CpuAssignmentMode cpuAssignmentMode = CpuAssignmentMode.Automatic,
|
|
ProcessIoPriority? currentIoPriority = null,
|
|
bool preventSystemSleepWhileRunning = false,
|
|
ProcessEfficiencyMode? currentEfficiencyMode = null,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(process);
|
|
|
|
var payload = new ProcessRuleCreationPayload
|
|
{
|
|
Priority = ShouldCaptureCurrentCpuPriority(process.Priority)
|
|
? process.Priority
|
|
: null,
|
|
MemoryPriority = currentMemoryPriority,
|
|
IoPriority = currentIoPriority,
|
|
// Only an explicit choice is worth saving; "Windows decides" is the default anyway.
|
|
EfficiencyMode = currentEfficiencyMode is ProcessEfficiencyMode.SystemManaged ? null : currentEfficiencyMode,
|
|
PreventSystemSleepWhileRunning = preventSystemSleepWhileRunning,
|
|
CpuAssignmentMode = cpuAssignmentMode,
|
|
};
|
|
|
|
var affinityPayload = currentCoreSelection == null
|
|
? await this.BuildAffinityPayloadFromLegacyMaskAsync(
|
|
process.ProcessorAffinity,
|
|
"Saved current Process tab affinity",
|
|
cancellationToken).ConfigureAwait(false)
|
|
: await this.BuildAffinityPayloadFromCoreSelectionAsync(
|
|
currentCoreSelection,
|
|
"Saved current Process tab affinity",
|
|
cancellationToken).ConfigureAwait(false);
|
|
|
|
if (!affinityPayload.Success)
|
|
{
|
|
return affinityPayload;
|
|
}
|
|
|
|
if (affinityPayload.Payload != null)
|
|
{
|
|
payload = payload with
|
|
{
|
|
CpuSelection = affinityPayload.Payload.CpuSelection,
|
|
LegacyAffinityMask = affinityPayload.Payload.LegacyAffinityMask,
|
|
CpuAssignmentMode = cpuAssignmentMode,
|
|
};
|
|
}
|
|
|
|
return await this.SaveRuleAsync(process, payload, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
// Deliberately matched with the same FindExistingRuleIndex that saving uses: if delete and
|
|
// save disagreed on which rule belongs to a process, a rule could become impossible to
|
|
// remove from the UI that created it.
|
|
public async Task<ProcessRuleCreationResult> DeleteRuleAsync(
|
|
ProcessModel process,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(process);
|
|
|
|
var rules = (await this.ruleStore.LoadAsync().ConfigureAwait(false)).ToList();
|
|
var existingIndex = FindExistingRuleIndex(rules, process);
|
|
if (existingIndex < 0)
|
|
{
|
|
return ProcessRuleCreationResult.Failed("NoSavedRuleToDelete", NoSavedRuleMessage);
|
|
}
|
|
|
|
return await this.RemoveAtAsync(rules, existingIndex, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
// The saved-rules list in the Rules tab holds rules, not processes: it can address a rule
|
|
// whose process is not running, which is exactly when a stale rule needs removing.
|
|
public async Task<ProcessRuleCreationResult> DeleteRuleByIdAsync(
|
|
string ruleId,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(ruleId))
|
|
{
|
|
return ProcessRuleCreationResult.Failed("NoSavedRuleToDelete", NoSavedRuleMessage);
|
|
}
|
|
|
|
var rules = (await this.ruleStore.LoadAsync().ConfigureAwait(false)).ToList();
|
|
var existingIndex = rules.FindIndex(rule => string.Equals(rule.Id, ruleId, StringComparison.Ordinal));
|
|
if (existingIndex < 0)
|
|
{
|
|
return ProcessRuleCreationResult.Failed("NoSavedRuleToDelete", NoSavedRuleMessage);
|
|
}
|
|
|
|
return await this.RemoveAtAsync(rules, existingIndex, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
// Editing a rule in place, from the saved-rules list. The affinity payload is not editable
|
|
// there - that needs the core picker in the Process tab - so it is carried over untouched
|
|
// rather than rebuilt, and only the fields the editor owns are replaced.
|
|
public Task<ProcessRuleCreationResult> UpdateRuleAsync(
|
|
PersistentProcessRule rule,
|
|
CancellationToken cancellationToken = default) =>
|
|
this.UpdateRuleWithCoreSelectionAsync(rule, null, cancellationToken);
|
|
|
|
public async Task<ProcessRuleCreationResult> UpdateRuleWithCoreSelectionAsync(
|
|
PersistentProcessRule rule,
|
|
IReadOnlyList<bool>? coreSelection,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(rule);
|
|
|
|
if (rule.Priority.HasValue && ProcessPriorityGuardrails.IsBlocked(rule.Priority.Value))
|
|
{
|
|
return ProcessRuleCreationResult.Failed(
|
|
"RealtimePriorityBlocked",
|
|
ProcessOperationUserMessages.RealtimePriorityBlocked);
|
|
}
|
|
|
|
var rules = (await this.ruleStore.LoadAsync().ConfigureAwait(false)).ToList();
|
|
var existingIndex = rules.FindIndex(candidate => string.Equals(candidate.Id, rule.Id, StringComparison.Ordinal));
|
|
if (existingIndex < 0)
|
|
{
|
|
return ProcessRuleCreationResult.Failed("NoSavedRuleToUpdate", NoSavedRuleMessage);
|
|
}
|
|
|
|
var existing = rules[existingIndex];
|
|
var updated = existing with
|
|
{
|
|
IsEnabled = rule.IsEnabled,
|
|
Priority = rule.Priority,
|
|
MemoryPriority = rule.MemoryPriority,
|
|
IoPriority = rule.IoPriority,
|
|
EfficiencyMode = rule.EfficiencyMode,
|
|
CpuAssignmentMode = rule.CpuAssignmentMode,
|
|
PreventSystemSleepWhileRunning = rule.PreventSystemSleepWhileRunning,
|
|
ApplyPriorityOnStart = rule.Priority.HasValue,
|
|
ApplyMemoryPriorityOnStart = rule.MemoryPriority.HasValue,
|
|
ApplyIoPriorityOnStart = rule.IoPriority.HasValue,
|
|
ApplyEfficiencyModeOnStart = rule.EfficiencyMode.HasValue,
|
|
UpdatedAt = DateTime.UtcNow,
|
|
};
|
|
|
|
if (coreSelection != null)
|
|
{
|
|
var affinity = await this.BuildAffinityPayloadFromCoreSelectionAsync(coreSelection, "Saved rule editor", cancellationToken).ConfigureAwait(false);
|
|
if (!affinity.Success)
|
|
{
|
|
return affinity;
|
|
}
|
|
|
|
if (affinity.Payload == null)
|
|
{
|
|
return ProcessRuleCreationResult.Failed("NoActionableRulePayload", NoCurrentSettingsMessage);
|
|
}
|
|
|
|
updated = updated with
|
|
{
|
|
CpuSelection = affinity.Payload.CpuSelection,
|
|
LegacyAffinityMask = HasSelectionPayload(affinity.Payload.CpuSelection) ? null : affinity.Payload.LegacyAffinityMask,
|
|
ApplyAffinityOnStart = true,
|
|
};
|
|
}
|
|
|
|
rules[existingIndex] = updated;
|
|
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
await this.ruleStore.SaveAsync(rules).ConfigureAwait(false);
|
|
|
|
var processName = string.IsNullOrWhiteSpace(updated.ProcessName)
|
|
? "process"
|
|
: updated.ProcessName.Trim();
|
|
this.logger.LogInformation("Updated saved rule {RuleId} for process {ProcessName}", updated.Id, processName);
|
|
|
|
return new ProcessRuleCreationResult
|
|
{
|
|
Success = true,
|
|
Updated = true,
|
|
Rule = updated,
|
|
UserMessage = $"Updated saved rule for {processName}.",
|
|
};
|
|
}
|
|
|
|
// Nothing checked saved rules against the machine they are running on. A rule that pins
|
|
// cores which no longer exist does not announce itself: it fails at apply time, inside a
|
|
// path that reports it as the process having exited. Ask the question where the rules are
|
|
// listed instead, once, at load.
|
|
public async Task<IReadOnlyList<string>> GetRulesNeedingTopologyReviewAsync(
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
if (this.topologyProvider == null)
|
|
{
|
|
return [];
|
|
}
|
|
|
|
var rules = await this.ruleStore.LoadAsync().ConfigureAwait(false);
|
|
if (rules.Count == 0)
|
|
{
|
|
return [];
|
|
}
|
|
|
|
CpuTopologySnapshot topology;
|
|
try
|
|
{
|
|
topology = await this.topologyProvider.GetTopologySnapshotAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
// Without a trustworthy topology the honest answer is to say nothing rather than
|
|
// accuse every rule of being stale.
|
|
this.logger.LogDebug(ex, "Could not read the CPU topology to review saved rules");
|
|
return [];
|
|
}
|
|
|
|
return rules
|
|
.Where(rule => rule.ApplyAffinityOnStart
|
|
&& HasSelectionPayload(rule.CpuSelection)
|
|
&& this.migrationService.ShouldRequireReview(
|
|
rule.CpuSelection!,
|
|
rule.CpuSelection!.Metadata.TopologySignature,
|
|
topology))
|
|
.Select(rule => string.IsNullOrWhiteSpace(rule.ProcessName) ? "(unnamed)" : rule.ProcessName!)
|
|
.Distinct(StringComparer.OrdinalIgnoreCase)
|
|
.ToList();
|
|
}
|
|
|
|
private async Task<ProcessRuleCreationResult> RemoveAtAsync(
|
|
List<PersistentProcessRule> rules,
|
|
int index,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var removed = rules[index];
|
|
rules.RemoveAt(index);
|
|
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
await this.ruleStore.SaveAsync(rules).ConfigureAwait(false);
|
|
|
|
var processName = string.IsNullOrWhiteSpace(removed.ProcessName)
|
|
? "process"
|
|
: removed.ProcessName.Trim();
|
|
this.logger.LogInformation(
|
|
"Deleted saved rule {RuleId} for process {ProcessName}",
|
|
removed.Id,
|
|
processName);
|
|
|
|
return new ProcessRuleCreationResult
|
|
{
|
|
Success = true,
|
|
Rule = removed,
|
|
UserMessage = $"Deleted saved rule for {processName}.",
|
|
};
|
|
}
|
|
|
|
public async Task<ProcessRuleCreationResult> SaveRuleAsync(
|
|
ProcessModel process,
|
|
ProcessRuleCreationPayload payload,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(process);
|
|
ArgumentNullException.ThrowIfNull(payload);
|
|
|
|
var sanitizedPayload = SanitizePayload(payload);
|
|
if (!sanitizedPayload.Success)
|
|
{
|
|
return sanitizedPayload;
|
|
}
|
|
|
|
payload = sanitizedPayload.Payload!;
|
|
if (!HasActionablePayload(payload))
|
|
{
|
|
return ProcessRuleCreationResult.Failed("NoActionableRulePayload", NoCurrentSettingsMessage);
|
|
}
|
|
|
|
var rules = (await this.ruleStore.LoadAsync().ConfigureAwait(false)).ToList();
|
|
var existingIndex = FindExistingRuleIndex(rules, process);
|
|
var created = existingIndex < 0;
|
|
var now = DateTime.UtcNow;
|
|
var processName = string.IsNullOrWhiteSpace(process.Name)
|
|
? "process"
|
|
: process.Name.Trim();
|
|
var executablePath = string.IsNullOrWhiteSpace(process.ExecutablePath)
|
|
? null
|
|
: process.ExecutablePath.Trim();
|
|
var existing = created ? null : rules[existingIndex];
|
|
|
|
// Saving is a merge, not a replacement. A caller that does not carry a field - or a
|
|
// field that could not be read from the process this time - must not silently erase
|
|
// what the rule already had: that turned "Apply CPU assignment and save as rule" into
|
|
// a quiet way to lose the memory and I/O priority saved a moment earlier. Removing a
|
|
// field is done by deleting the rule, which is an explicit action.
|
|
var hasAffinityPayload = HasSelectionPayload(payload.CpuSelection) || payload.LegacyAffinityMask.HasValue;
|
|
var cpuSelection = hasAffinityPayload ? payload.CpuSelection : existing?.CpuSelection;
|
|
var legacyAffinityMask = hasAffinityPayload
|
|
? (HasSelectionPayload(payload.CpuSelection) ? null : payload.LegacyAffinityMask)
|
|
: existing?.LegacyAffinityMask;
|
|
var cpuAssignmentMode = hasAffinityPayload
|
|
? payload.CpuAssignmentMode
|
|
: existing?.CpuAssignmentMode ?? payload.CpuAssignmentMode;
|
|
var priority = payload.Priority ?? existing?.Priority;
|
|
var memoryPriority = payload.MemoryPriority ?? existing?.MemoryPriority;
|
|
var ioPriority = payload.IoPriority ?? existing?.IoPriority;
|
|
var efficiencyMode = payload.EfficiencyMode ?? existing?.EfficiencyMode;
|
|
|
|
var rule = new PersistentProcessRule
|
|
{
|
|
Id = existing?.Id ?? Guid.NewGuid().ToString("N"),
|
|
Name = $"{processName} rule",
|
|
IsEnabled = true,
|
|
ProcessName = processName,
|
|
ExecutablePath = executablePath,
|
|
CpuSelection = cpuSelection,
|
|
LegacyAffinityMask = HasSelectionPayload(cpuSelection) ? null : legacyAffinityMask,
|
|
CpuAssignmentMode = cpuAssignmentMode,
|
|
Priority = priority,
|
|
MemoryPriority = memoryPriority,
|
|
IoPriority = ioPriority,
|
|
EfficiencyMode = efficiencyMode,
|
|
ApplyAffinityOnStart = HasSelectionPayload(cpuSelection) || legacyAffinityMask.HasValue,
|
|
ApplyPriorityOnStart = priority.HasValue,
|
|
ApplyMemoryPriorityOnStart = memoryPriority.HasValue,
|
|
ApplyIoPriorityOnStart = ioPriority.HasValue,
|
|
ApplyEfficiencyModeOnStart = efficiencyMode.HasValue,
|
|
PreventSystemSleepWhileRunning = payload.PreventSystemSleepWhileRunning,
|
|
CreatedAt = existing?.CreatedAt ?? now,
|
|
UpdatedAt = now,
|
|
Description = RuleDescription,
|
|
};
|
|
|
|
if (created)
|
|
{
|
|
rules.Add(rule);
|
|
}
|
|
else
|
|
{
|
|
rules[existingIndex] = rule;
|
|
}
|
|
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
await this.ruleStore.SaveAsync(rules).ConfigureAwait(false);
|
|
|
|
return new ProcessRuleCreationResult
|
|
{
|
|
Success = true,
|
|
Created = created,
|
|
Updated = !created,
|
|
Rule = rule,
|
|
UserMessage = created
|
|
? $"Saved rule for {processName}."
|
|
: $"Updated saved rule for {processName}.",
|
|
};
|
|
}
|
|
|
|
private static PayloadBuildResult BuildLegacyAffinityPayload(IReadOnlyList<bool> currentCoreSelection)
|
|
{
|
|
if (currentCoreSelection.Count == 0 || !currentCoreSelection.Any(selected => selected))
|
|
{
|
|
return PayloadBuildResult.Empty();
|
|
}
|
|
|
|
if (currentCoreSelection.Count > 64)
|
|
{
|
|
return PayloadBuildResult.Failed("UnsafeLegacyAffinity", UnsafeAffinityMessage);
|
|
}
|
|
|
|
long legacyMask = 0;
|
|
for (var bit = 0; bit < currentCoreSelection.Count; bit++)
|
|
{
|
|
if (currentCoreSelection[bit])
|
|
{
|
|
legacyMask |= 1L << bit;
|
|
}
|
|
}
|
|
|
|
return legacyMask == 0
|
|
? PayloadBuildResult.Empty()
|
|
: PayloadBuildResult.Succeeded(new ProcessRuleCreationPayload { LegacyAffinityMask = legacyMask });
|
|
}
|
|
|
|
private static PayloadSanitizationResult SanitizePayload(ProcessRuleCreationPayload payload)
|
|
{
|
|
if (payload.Priority.HasValue && ProcessPriorityGuardrails.IsBlocked(payload.Priority.Value))
|
|
{
|
|
return PayloadSanitizationResult.Failed(
|
|
"RealtimePriorityBlocked",
|
|
ProcessOperationUserMessages.RealtimePriorityBlocked);
|
|
}
|
|
|
|
var hasCpuSelection = HasSelectionPayload(payload.CpuSelection);
|
|
var legacyMask = hasCpuSelection ? null : payload.LegacyAffinityMask;
|
|
if (legacyMask.HasValue && legacyMask.Value == 0)
|
|
{
|
|
legacyMask = null;
|
|
}
|
|
|
|
return PayloadSanitizationResult.Succeeded(payload with
|
|
{
|
|
CpuSelection = hasCpuSelection ? payload.CpuSelection : null,
|
|
LegacyAffinityMask = legacyMask,
|
|
CpuAssignmentMode = Enum.IsDefined(payload.CpuAssignmentMode)
|
|
? payload.CpuAssignmentMode
|
|
: CpuAssignmentMode.Automatic,
|
|
});
|
|
}
|
|
|
|
private static bool ShouldCaptureCurrentCpuPriority(ProcessPriorityClass priority) =>
|
|
priority is ProcessPriorityClass.Idle
|
|
or ProcessPriorityClass.BelowNormal
|
|
or ProcessPriorityClass.AboveNormal
|
|
or ProcessPriorityClass.High;
|
|
|
|
private static bool HasActionablePayload(ProcessRuleCreationPayload payload) =>
|
|
HasSelectionPayload(payload.CpuSelection) ||
|
|
payload.LegacyAffinityMask.HasValue ||
|
|
payload.Priority.HasValue ||
|
|
payload.MemoryPriority.HasValue ||
|
|
payload.IoPriority.HasValue ||
|
|
payload.EfficiencyMode.HasValue ||
|
|
payload.PreventSystemSleepWhileRunning;
|
|
|
|
private static bool HasSelectionPayload(CpuSelection? selection) =>
|
|
selection != null &&
|
|
(selection.CpuSetIds.Count > 0 || selection.LogicalProcessors.Count > 0);
|
|
|
|
private static int FindExistingRuleIndex(IReadOnlyList<PersistentProcessRule> rules, ProcessModel process)
|
|
{
|
|
var executablePath = string.IsNullOrWhiteSpace(process.ExecutablePath)
|
|
? null
|
|
: process.ExecutablePath.Trim();
|
|
if (!string.IsNullOrWhiteSpace(executablePath))
|
|
{
|
|
for (var index = 0; index < rules.Count; index++)
|
|
{
|
|
if (string.Equals(
|
|
rules[index].ExecutablePath,
|
|
executablePath,
|
|
StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return index;
|
|
}
|
|
}
|
|
|
|
var pathlessNameMatch = FindProcessNameMatchIndex(rules, process, requirePathUnavailable: true);
|
|
return pathlessNameMatch;
|
|
}
|
|
|
|
return FindProcessNameMatchIndex(rules, process, requirePathUnavailable: false);
|
|
}
|
|
|
|
private static int FindProcessNameMatchIndex(
|
|
IReadOnlyList<PersistentProcessRule> rules,
|
|
ProcessModel process,
|
|
bool requirePathUnavailable)
|
|
{
|
|
var processName = string.IsNullOrWhiteSpace(process.Name)
|
|
? null
|
|
: process.Name.Trim();
|
|
if (string.IsNullOrWhiteSpace(processName))
|
|
{
|
|
return -1;
|
|
}
|
|
|
|
for (var index = 0; index < rules.Count; index++)
|
|
{
|
|
if (requirePathUnavailable && !string.IsNullOrWhiteSpace(rules[index].ExecutablePath))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (string.Equals(rules[index].ProcessName, processName, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return index;
|
|
}
|
|
}
|
|
|
|
return -1;
|
|
}
|
|
|
|
private async Task<PayloadBuildResult> BuildAffinityPayloadFromCoreSelectionAsync(
|
|
IReadOnlyList<bool> currentCoreSelection,
|
|
string selectionReason,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
if (currentCoreSelection.Count == 0 || !currentCoreSelection.Any(selected => selected))
|
|
{
|
|
return PayloadBuildResult.Empty();
|
|
}
|
|
|
|
var selection = await this.TryMigrateCoreSelectionAsync(
|
|
currentCoreSelection,
|
|
selectionReason,
|
|
cancellationToken).ConfigureAwait(false);
|
|
if (selection != null)
|
|
{
|
|
return PayloadBuildResult.Succeeded(new ProcessRuleCreationPayload { CpuSelection = selection });
|
|
}
|
|
|
|
return BuildLegacyAffinityPayload(currentCoreSelection);
|
|
}
|
|
|
|
private async Task<PayloadBuildResult> BuildAffinityPayloadFromLegacyMaskAsync(
|
|
long legacyMask,
|
|
string selectionReason,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
if (legacyMask == 0)
|
|
{
|
|
return PayloadBuildResult.Empty();
|
|
}
|
|
|
|
var selection = await this.TryMigrateLegacyMaskAsync(
|
|
legacyMask,
|
|
selectionReason,
|
|
cancellationToken).ConfigureAwait(false);
|
|
if (selection != null)
|
|
{
|
|
return PayloadBuildResult.Succeeded(new ProcessRuleCreationPayload { CpuSelection = selection });
|
|
}
|
|
|
|
return PayloadBuildResult.Succeeded(new ProcessRuleCreationPayload { LegacyAffinityMask = legacyMask });
|
|
}
|
|
|
|
private async Task<CpuSelection?> TryMigrateCoreSelectionAsync(
|
|
IReadOnlyList<bool> currentCoreSelection,
|
|
string selectionReason,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
if (this.topologyProvider == null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
try
|
|
{
|
|
var topology = await this.topologyProvider.GetTopologySnapshotAsync(cancellationToken).ConfigureAwait(false);
|
|
var migrated = this.migrationService.MigrateFromLegacyCoreMask(currentCoreSelection, topology);
|
|
return WithSelectionReason(migrated.Selection, selectionReason);
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
this.logger.LogDebug(ex, "Could not migrate current core selection to CpuSelection for saved rule");
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private async Task<CpuSelection?> TryMigrateLegacyMaskAsync(
|
|
long legacyMask,
|
|
string selectionReason,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
if (this.topologyProvider == null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
try
|
|
{
|
|
var topology = await this.topologyProvider.GetTopologySnapshotAsync(cancellationToken).ConfigureAwait(false);
|
|
var migrated = this.migrationService.MigrateFromLegacyAffinityMask(legacyMask, topology);
|
|
return WithSelectionReason(migrated.Selection, selectionReason);
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
this.logger.LogDebug(ex, "Could not migrate current legacy affinity mask to CpuSelection for saved rule");
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private static CpuSelection? WithSelectionReason(CpuSelection? selection, string selectionReason)
|
|
{
|
|
if (!HasSelectionPayload(selection))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return selection! with
|
|
{
|
|
Metadata = selection.Metadata with
|
|
{
|
|
SelectionReason = selectionReason,
|
|
},
|
|
};
|
|
}
|
|
|
|
private sealed record PayloadBuildResult(
|
|
bool Success,
|
|
ProcessRuleCreationPayload? Payload,
|
|
string ErrorCode,
|
|
string UserMessage)
|
|
{
|
|
public static PayloadBuildResult Empty() => new(true, null, string.Empty, string.Empty);
|
|
|
|
public static PayloadBuildResult Succeeded(ProcessRuleCreationPayload payload) =>
|
|
new(true, payload, string.Empty, string.Empty);
|
|
|
|
public static PayloadBuildResult Failed(string errorCode, string userMessage) =>
|
|
new(false, null, errorCode, userMessage);
|
|
|
|
public static implicit operator ProcessRuleCreationResult(PayloadBuildResult result) =>
|
|
ProcessRuleCreationResult.Failed(result.ErrorCode, result.UserMessage);
|
|
}
|
|
|
|
private sealed record PayloadSanitizationResult(
|
|
bool Success,
|
|
ProcessRuleCreationPayload? Payload,
|
|
string ErrorCode,
|
|
string UserMessage)
|
|
{
|
|
public static PayloadSanitizationResult Succeeded(ProcessRuleCreationPayload payload) =>
|
|
new(true, payload, string.Empty, string.Empty);
|
|
|
|
public static PayloadSanitizationResult Failed(string errorCode, string userMessage) =>
|
|
new(false, null, errorCode, userMessage);
|
|
|
|
public static implicit operator ProcessRuleCreationResult(PayloadSanitizationResult result) =>
|
|
ProcessRuleCreationResult.Failed(result.ErrorCode, result.UserMessage);
|
|
}
|
|
}
|
|
}
|