Free, open-source Windows optimization tool for performance, privacy, and simplicity.
C# csharpdebloatdotnetgamingopen-sourceoptimizationoptimizeroptimizerduckperformanceprivacytweakertweakswindowswinui
refactor(revert): use explicit step indexes in revert data and persistence
fatDuck3cff0937738f
diff --git a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs b/optimizerDuck.Test/Services/Managers/RevertManagerTests.csindex b89bc1f..7cffad4 100644--- a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs+++ b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs@@ -38,7 +38,7 @@ public class RevertManagerTestsOptimizationId = id,OptimizationName = "TestOptimization",AppliedAt = DateTime.UtcNow,- Steps = new List<RevertStepData>(),+ Steps = Array.Empty<RevertStepData?>()};try@@ -99,10 +99,11 @@ public class RevertManagerTestsOptimizationId = id,OptimizationName = "TestOptimization",AppliedAt = DateTime.UtcNow,- Steps = new List<RevertStepData>+ Steps = new RevertStepData?[]{new(){+ Index = 1,Type = "Shell",Data = new ShellRevertStep{@@ -112,6 +113,7 @@ public class RevertManagerTests},new(){+ Index = 2,Type = "Shell",Data = new ShellRevertStep{@@ -158,10 +160,11 @@ public class RevertManagerTestsOptimizationId = id,OptimizationName = "TestOptimization",AppliedAt = DateTime.UtcNow,- Steps = new List<RevertStepData>+ Steps = new RevertStepData?[]{new(){+ Index = 1,Type = "Shell",Data = new ShellRevertStep{@@ -209,10 +212,11 @@ public class RevertManagerTestsOptimizationId = id,OptimizationName = "TestOptimization",AppliedAt = DateTime.UtcNow,- Steps = new List<RevertStepData>+ Steps = new RevertStepData?[]{new(){+ Index = 1,Type = "Shell",Data = new ShellRevertStep{@@ -222,6 +226,7 @@ public class RevertManagerTests},new(){+ Index = 2,Type = RetryableTestRevertStep.StepType,Data = new RetryableTestRevertStep{diff --git a/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs b/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.csindex db3c4f2..8a2ea2e 100644--- a/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs+++ b/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs@@ -106,40 +106,26 @@ public class OptimizationServiceIntegrationTests : IDisposable}}+ private readonly List<Guid> _testOptimizationIds = new();+public OptimizationServiceIntegrationTests(){- // Ensure clean revert directory- if (Directory.Exists(Shared.RevertDirectory))- {- foreach (var file in Directory.GetFiles(Shared.RevertDirectory))- {- try- {- File.Delete(file);- }- catch- {- // Ignore- }- }- }}public void Dispose(){- // Clean up test files- if (Directory.Exists(Shared.RevertDirectory))+ // Clean up only test files created by this class+ foreach (var id in _testOptimizationIds){- foreach (var file in Directory.GetFiles(Shared.RevertDirectory))+ var path = Path.Combine(Shared.RevertDirectory, id + ".json");+ try+ {+ if (File.Exists(path))+ File.Delete(path);+ }+ catch{- try- {- File.Delete(file);- }- catch- {- // Ignore- }+ // Ignore}}}@@ -162,6 +148,7 @@ public class OptimizationServiceIntegrationTests : IDisposable);var optimization = new PartialFailureOptimization(shouldFail: false);+ _testOptimizationIds.Add(optimization.Id);var progress = new Progress<ProcessingProgress>();var result = await optimizationService.ApplyAsync(optimization, progress);@@ -171,7 +158,7 @@ public class OptimizationServiceIntegrationTests : IDisposable// Verify revert data was savedvar revertData = await RevertManager.GetRevertDataAsync(optimization.Id);Assert.NotNull(revertData);- Assert.Equal(2, revertData.Steps.Count); // 2 successful steps+ Assert.Equal(2, revertData.Steps.Count(s => s != null)); // 2 successful steps}[Fact]diff --git a/optimizerDuck.Test/Services/OptimizationServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServiceTests.csindex 5d26e36..cb7486b 100644--- a/optimizerDuck.Test/Services/OptimizationServiceTests.cs+++ b/optimizerDuck.Test/Services/OptimizationServiceTests.cs@@ -126,10 +126,11 @@ public class OptimizationServiceTestsOptimizationId = optimization.Id,OptimizationName = optimization.OptimizationKey,AppliedAt = DateTime.UtcNow,- Steps = new List<RevertStepData>+ Steps = new RevertStepData?[]{new(){+ Index = 1,Type = "Shell",Data = new ShellRevertStep{@@ -257,17 +258,17 @@ public class OptimizationServiceTestsAssert.Equal(OptimizationSuccessResult.PartialSuccess, result.Status);Assert.NotNull(data);- Assert.Equal(3, data!.Steps.Count);- Assert.Equal("Shell", data.Steps[0].Type);- Assert.Equal("Unknown", data.Steps[1].Type);- Assert.Equal("Shell", data.Steps[2].Type);+ Assert.Equal(3, data!.Steps.Length);+ Assert.Equal("Shell", data.Steps[0]!.Type);+ Assert.Null(data.Steps[1]); // Gap - step 2 failed+ Assert.Equal("Shell", data.Steps[2]!.Type);Assert.Equal("exit 11",- data.Steps[0].Data[nameof(ShellRevertStep.Command)]?.ToString()+ data.Steps[0]!.Data[nameof(ShellRevertStep.Command)]?.ToString());Assert.Equal("exit 33",- data.Steps[2].Data[nameof(ShellRevertStep.Command)]?.ToString()+ data.Steps[2]!.Data[nameof(ShellRevertStep.Command)]?.ToString());}finally@@ -361,18 +362,18 @@ public class OptimizationServiceTestsvar data = await RevertManager.GetRevertDataAsync(optimization.Id);Assert.NotNull(data);- Assert.Equal(3, data!.Steps.Count);+ Assert.Equal(3, data!.Steps.Length);Assert.Equal("exit 11",- data.Steps[0].Data[nameof(ShellRevertStep.Command)]?.ToString()+ data.Steps[0]!.Data[nameof(ShellRevertStep.Command)]?.ToString());Assert.Equal("exit 0",- data.Steps[1].Data[nameof(ShellRevertStep.Command)]?.ToString()+ data.Steps[1]!.Data[nameof(ShellRevertStep.Command)]?.ToString());Assert.Equal("exit 33",- data.Steps[2].Data[nameof(ShellRevertStep.Command)]?.ToString()+ data.Steps[2]!.Data[nameof(ShellRevertStep.Command)]?.ToString());}finally@@ -491,9 +492,10 @@ public class OptimizationServiceTestsvar data = await RevertManager.GetRevertDataAsync(optimization.Id);Assert.NotNull(data);- Assert.Equal(4, data!.Steps.Count);+ Assert.Equal(4, data!.Steps.Length);var commands = data- .Steps.Select(step => step.Data[nameof(ShellRevertStep.Command)]!.ToString())+ .Steps.Where(step => step != null)+ .Select(step => step!.Data[nameof(ShellRevertStep.Command)]!.ToString()).ToArray();Assert.Equal(["exit 11", "exit 22", "exit 33", "exit 44"], commands);}diff --git a/optimizerDuck/Domain/Execution/ExecutionScope.cs b/optimizerDuck/Domain/Execution/ExecutionScope.csindex 6f02c15..556c4fa 100644--- a/optimizerDuck/Domain/Execution/ExecutionScope.cs+++ b/optimizerDuck/Domain/Execution/ExecutionScope.cs@@ -187,6 +187,29 @@ public sealed class ExecutionScope : IDisposable);}+ public static ExecutedStep? RecordStepAtIndex(+ int index,+ string name,+ string description,+ bool success,+ IRevertStep? revertStep = null,+ string? error = null,+ Func<Task<bool>>? retryAction = null+ )+ {+ var scope = Current;++ return scope?.RecordStepInternal(+ name,+ description,+ success,+ revertStep,+ error,+ retryAction,+ explicitIndex: index+ );+ }+public static void Track(string serviceName, bool success){var scope = Current;@@ -248,14 +271,17 @@ public sealed class ExecutionScope : IDisposablebool success,IRevertStep? revertStep,string? error,- Func<Task<bool>>? retryAction = null+ Func<Task<bool>>? retryAction = null,+ int? explicitIndex = null){if (LoggingOnly)return null;+ var stepIndex = explicitIndex ?? ++_stepIndex;+var step = new ExecutedStep(- ++_stepIndex,+ stepIndex,name,description,success,diff --git a/optimizerDuck/Domain/Revert/RevertData.cs b/optimizerDuck/Domain/Revert/RevertData.csindex 0b0624e..a092481 100644--- a/optimizerDuck/Domain/Revert/RevertData.cs+++ b/optimizerDuck/Domain/Revert/RevertData.cs@@ -7,6 +7,11 @@ namespace optimizerDuck.Domain.Revert;/// </summary>public class RevertStepData{+ /// <summary>+ /// The explicit index of this step in the execution sequence.+ /// </summary>+ public int Index { get; set; }+/// <summary>/// The type of the revert step (e.g., "Registry", "Service", "Shell")./// </summary>@@ -39,7 +44,8 @@ public class RevertDatapublic DateTime AppliedAt { get; set; }/// <summary>- /// The list of revert steps.+ /// The array of revert steps. Gaps are represented as null entries.+ /// Example: [step1, null, null, step4] for steps at indexes 1 and 4./// </summary>- public List<RevertStepData> Steps { get; set; } = new();+ public RevertStepData?[] Steps { get; set; } = Array.Empty<RevertStepData?>();}diff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.csindex 8d846b9..44ce312 100644--- a/optimizerDuck/Services/Optimization/OptimizationService.cs+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs@@ -280,11 +280,22 @@ public class OptimizationService(IReadOnlyList<OperationStepResult> failedSteps,bool reverseOrder,ILogger logger,+ RevertManager? revertManager = null,+ Guid? optimizationId = null,+ string? optimizationKey = null,IProgress<ProcessingProgress>? progress = null){return (- await RetryFailedStepsWithResultsAsync(failedSteps, reverseOrder, logger, progress)+ await RetryFailedStepsWithResultsAsync(+ failedSteps,+ reverseOrder,+ logger,+ revertManager,+ optimizationId,+ optimizationKey,+ progress+ )).FailedSteps;}@@ -292,6 +303,9 @@ public class OptimizationService(IReadOnlyList<OperationStepResult> failedSteps,bool reverseOrder,ILogger logger,+ RevertManager? revertManager = null,+ Guid? optimizationId = null,+ string? optimizationKey = null,IProgress<ProcessingProgress>? progress = null){@@ -348,23 +362,38 @@ public class OptimizationService(if (success){var retriedStep = retryScope.SuccessfulSteps.LastOrDefault();- recoveredSteps.Add(- retriedStep == null- ? step with- {- Error = null,- }- : new OperationStepResult- {- Index = step.Index,- Name = retriedStep.Name,- Description = retriedStep.Description,- Success = true,- Error = null,- RetryAction = null,- RevertStep = retriedStep.RevertStep,- }- );+ var recoveredStep = retriedStep == null+ ? step with { Error = null }+ : new OperationStepResult+ {+ Index = step.Index,+ Name = retriedStep.Name,+ Description = retriedStep.Description,+ Success = true,+ Error = null,+ RetryAction = null,+ RevertStep = retriedStep.RevertStep,+ };++ // Auto-persist recovered revert step if revertManager is available+ if (retriedStep?.RevertStep != null && revertManager != null && optimizationId.HasValue)+ {+ try+ {+ await revertManager.UpsertRevertStepAtIndexAsync(+ optimizationId.Value,+ optimizationKey ?? string.Empty,+ step.Index, // Use original failed step's index+ retriedStep.RevertStep+ );+ }+ catch (Exception ex)+ {+ logger.LogError(ex, "Failed to auto-persist revert step at index {Index}", step.Index);+ }+ }++ recoveredSteps.Add(recoveredStep);}}catch (Exception ex)diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.csindex 8630681..0745dbf 100644--- a/optimizerDuck/Services/Revert/RevertManager.cs+++ b/optimizerDuck/Services/Revert/RevertManager.cs@@ -23,27 +23,33 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFpublic async Task SaveRevertDataAsync(ExecutionScope scope){- if (!scope.HasSuccessfulSteps)- return;-- var steps = scope.ExecutedSteps- .Where(s => s.RevertStep != null)- .Select(s => new RevertStepData- {- Type = s.RevertStep!.Type,- Data = s.RevertStep.ToData(),- })+ var successfulSteps = scope.ExecutedSteps+ .Where(s => s.Success && s.RevertStep != null).ToList();- if (steps.Count == 0)+ if (successfulSteps.Count == 0)return;+ var maxIndex = successfulSteps.Max(s => s.Index);+ var steps = new RevertStepData?[maxIndex];++ foreach (var executedStep in successfulSteps)+ {+ var arrayIndex = executedStep.Index - 1;+ steps[arrayIndex] = new RevertStepData+ {+ Index = executedStep.Index,+ Type = executedStep.RevertStep.Type,+ Data = executedStep.RevertStep.ToData(),+ };+ }+await WriteJsonAsync(GetFilePath(scope.OptimizationId!.Value),new RevertData{OptimizationId = scope.OptimizationId!.Value,- OptimizationName = scope.OptimizationKey!,+ OptimizationName = scope.OptimizationName ?? scope.OptimizationKey!,AppliedAt = DateTime.Now,Steps = steps,}@@ -71,11 +77,14 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF};var failedSteps = new List<OperationStepResult>();- var total = steps.Count;+ var sortedSteps = steps.OrderByDescending(s => s.Index).ToList();+ var total = sortedSteps.Count;++ operationLogger.LogDebug("Reverting steps in reverse order (total: {Total})", total);- for (var i = total - 1; i >= 0; i--)+ for (var i = 0; i < total; i++){- var (idx, step) = steps[i];+ var (idx, step) = sortedSteps[i];progress?.Report(new ProcessingProgress{@@ -85,7 +94,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFtotal,step.Type),- Value = idx,+ Value = i + 1,Total = total,});@@ -142,10 +151,13 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFIRevertStep step){+ if (stepIndex <= 0)+ throw new ArgumentException("Step index must be greater than 0", nameof(stepIndex));+var filePath = GetFilePath(id);var lockObj = _fileLocks.GetOrAdd(id, _ => new SemaphoreSlim(1, 1));- await lockObj.WaitAsync();+ await lockObj.WaitAsync(TimeSpan.FromSeconds(30));try{var data =@@ -154,17 +166,25 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF{OptimizationId = id,OptimizationName = name,- Steps = [],+ Steps = Array.Empty<RevertStepData?>(),};- while (data.Steps.Count < stepIndex)- data.Steps.Add(new RevertStepData { Type = "Unknown", Data = new JObject() });+ // Expand array if needed+ if (data.Steps.Length < stepIndex)+ {+ var newSteps = new RevertStepData?[stepIndex];+ Array.Copy(data.Steps, newSteps, data.Steps.Length);+ data.Steps = newSteps;+ }+ // Place step at correct position (0-based index)data.Steps[stepIndex - 1] = new RevertStepData{+ Index = stepIndex,Type = step.Type,Data = step.ToData(),};+await WriteJsonAsync(filePath, data);}finally@@ -229,24 +249,44 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFprivate static async Task WriteJsonAsync(string path, RevertData data){Directory.CreateDirectory(Path.GetDirectoryName(path)!);- await File.WriteAllTextAsync(path, JsonConvert.SerializeObject(data, Formatting.Indented));++ var json = JsonConvert.SerializeObject(data, Formatting.Indented);+ await using var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true);+ await using var writer = new StreamWriter(fileStream);+ await writer.WriteAsync(json);}private async Task<List<(int Index, IRevertStep Step)>> LoadStepsAsync(Guid id){var data = await LoadAsync(GetFilePath(id));- if (data == null || data.Steps.Count == 0)+ if (data == null || data.Steps.Length == 0)return [];+ // Validate indexes: must be > 0, no duplicates+ var seenIndexes = new HashSet<int>();+ foreach (var step in data.Steps.Where(s => s != null))+ {+ if (step.Index <= 0)+ {+ logger.LogWarning("Invalid index {Index} in revert data for {Id}", step.Index, id);+ return [];+ }+ if (!seenIndexes.Add(step.Index))+ {+ logger.LogWarning("Duplicate index {Index} in revert data for {Id}", step.Index, id);+ return [];+ }+ }+var result = new List<(int, IRevertStep)>();- for (var i = 0; i < data.Steps.Count; i++)+ foreach (var stepData in data.Steps.Where(s => s != null)){- var step = DeserializeStep(data.Steps[i].Type, data.Steps[i].Data);+ var step = DeserializeStep(stepData.Type, stepData.Data);if (step != null)- result.Add((i + 1, step));+ result.Add((stepData.Index, step)); // Use explicit Index}- return result;+ return result.OrderBy(x => x.Item1).ToList();}private void Remove(Guid id, string? name = null)diff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.csindex 66b24d9..28fe6ec 100644--- a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs@@ -567,7 +567,10 @@ public partial class OptimizationCategoryViewModel : ViewModelremainingFailedSteps,true,_logger,- progress+ revertManager: null,+ optimizationId: null,+ optimizationKey: null,+ progress: progress)))@@ -590,20 +593,15 @@ public partial class OptimizationCategoryViewModel : ViewModelremainingFailedSteps,false,_logger,+ _revertManager,+ optimization.Id,+ optimization.OptimizationKey,progress));var newFailed = retryResult.FailedSteps.OrderBy(s => s.Index).ToList();- foreach (var s in retryResult.RecoveredSteps.Where(s => s.RevertStep != null))- await _revertManager.UpsertRevertStepAtIndexAsync(- optimization.Id,- optimization.OptimizationKey,- s.Index,- s.RevertStep!- );-remainingFailedSteps = newFailed;if (remainingFailedSteps.Count == 0)return FailureResolutionOutcome.Recovered;