Skip to content

Free, open-source Windows optimization tool for performance, privacy, and simplicity.

Thêm test retry apply thất bại

fatDuck60010fdd69c8
diff --git a/.agents/skills/resx-translation/SKILL.md b/.agents/skills/resx-translation/SKILL.md
new file mode 100644
index 0000000..47cdeba
--- /dev/null
+++ b/.agents/skills/resx-translation/SKILL.md
@@ -0,0 +1,142 @@
+---
+name: resx-translation
+description: Translate, extend, and create `.resx` localization files for .NET apps with project-aware wording and minimal file churn. Use this skill whenever the user wants to localize or update `Translations.resx`, `*.resx`, WPF/WinForms/.NET resource files, add a new language like `vi`, `ja`, or `fr-FR`, fill missing translations, or improve an existing locale while preserving XML structure, placeholders, naming conventions, and current formatting. Trigger even when the user does not mention `.resx` explicitly but is clearly asking to localize app text, UI labels, menus, dialogs, settings, validation messages, or existing app translations. Also trigger for requests like "translate this resx", "add a new language", "fill missing strings", "localize my app", "translate resource files", or "complete the existing locale".
+---
+
+# Resx Translation
+
+The goal of this skill is to translate `.resx` files with product-aware context, preserve the resource structure, and change only what needs to be changed.
+
+## When to use it
+
+Use this skill when the user wants to:
+
+- Translate a `.resx` file into another language
+- Fill in missing strings in an existing localized file
+- Add a new resource file for a language code like `vi`, `ja`, or `fr-FR`
+- Update translations for a WPF, WinForms, .NET, or any app that uses `.resx`
+
+## Workflow
+
+### 1. Understand the project before translating
+
+Before editing any file, inspect the project to understand what kind of app it is, who it is for, and what domain it belongs to. Prefer reading files like `README`, project files, UI screens, settings, menus, view models, or any code that reveals domain context so the translation sounds natural.
+
+The point is to avoid overly literal translations when the domain needs more specialized language. For example:
+
+- music apps: keep terms like playlist, mix, mastering, or equalizer when appropriate
+- configuration/system apps: prefer concise, professional, technical wording
+- business apps: prefer clarity, stability, and consistent business terminology
+
+### 2. Identify the source resx file and its real format
+
+Check the default/source resx file first. Priority order:
+
+1. `Translations.resx` if it exists
+2. Any `*.resx` file that does not include a language code in the filename
+3. If the project uses English as a base language, also inspect `*.en.resx` if useful
+
+The goal is to understand:
+
+- the filename and naming convention
+- whether the project uses patterns like `Name.resx`, `Name.vi.resx`, `Name.ja.resx`, or something else
+- XML formatting, line breaks, node order, spacing, and any existing conventions
+- the file encoding and whether it uses BOM, UTF-8, UTF-16, or another existing pattern
+- which strings are actually user-facing text and which are metadata or technical values
+
+Follow the existing format. Do not regroup, reorder, reformat, add comments, or beautify the file unless the original file already does that.
+
+Preserve encoding carefully. When saving `.resx` files, avoid introducing encoding changes unless there is a clear reason. Match the existing file encoding whenever possible so the XML declaration, localized characters, and tooling behavior stay stable.
+
+### 3. Check whether language support also needs code or settings updates
+
+Do not stop at the `.resx` files. When the user asks to add a new language, also inspect the project for any language-selection or localization plumbing that must be updated so the new locale can actually appear and be used in the app.
+
+Look for related code such as:
+
+- settings pages or language dropdowns
+- supported language lists or culture registries
+- localization services, resource managers, or startup configuration
+- menu items, options screens, or app preferences tied to language selection
+
+If the project requires these updates, make them together with the new `.resx` file. If the project already discovers languages automatically, avoid unnecessary code changes.
+
+### 4. Determine the request type
+
+Clearly distinguish between these two cases:
+
+- **Extend/fill an existing language**: update the existing localized file and translate only what is needed
+- **Create a new language**: duplicate the source file into a new file with the requested language code, then translate each entry
+
+If the user's request is explicit, follow it. If the request is ambiguous but the files make the intent obvious, prefer the least disruptive path: extend an existing localized file if it already exists; otherwise create a new one when the requested language code does not exist.
+
+### 5. If the task is to extend an existing language
+
+Read the existing localized file together with the source file, then translate entries that are missing, still left in the source language, or clearly wrong for the project context.
+
+Prefer targeted edits. If the localized file already exists, update only missing, source-language, or clearly incorrect entries unless the user explicitly asks for a full translation pass or a rewrite of the whole locale.
+
+When extending translations:
+
+- keep the original meaning but prefer wording that fits the product context
+- do not translate word-for-word mechanically
+- respect the tone of the existing localized file if it is already good
+- keep terminology consistent within the file and across the project
+
+### 6. If the task is to create a new language
+
+Duplicate the source `.resx` file into a new file using the requested language code. Example: `Translations.resx` -> `Translations.vi.resx`.
+
+Then translate each translatable entry in the new file while preserving the XML structure and all attributes from the source.
+
+### 7. File update strategy
+
+Apply changes in the least disruptive way that still keeps the file correct.
+
+- For small files or narrowly scoped edits, direct rewrite is fine if you can preserve the exact structure and encoding.
+- For larger files, prefer targeted updates that touch only the specific entries that need translation instead of regenerating or rewriting the whole file.
+- Avoid full-file rewrites when the task is only to fill missing entries or correct a subset of strings.
+- Preserve ordering, indentation, XML declaration, and surrounding nodes so diffs stay small and reviewable.
+
+The goal is to keep the change set precise, safe, and easy for the user to review.
+
+### 8. Translation rules
+
+Translate only the user-facing text. Do not change keys, node names, attributes, or XML structure.
+
+Preserve exactly:
+
+- placeholders such as `{0}`, `{1}`, `%s`, `%d`
+- markup, HTML, XAML fragments, newline markers, and escaped characters
+- product names, feature names, shortcuts, error codes, commands, and any terminology that should remain unchanged in context
+- empty strings or technical strings that are not user-facing, unless the source file shows they are meant to be localized
+
+Be careful with short strings like `Open`, `Save`, `Apply`, `Reset`, `Close`, `Track`, `Mix`, `Profile`, `Library`, `Device`, and `Output`, because the right translation depends heavily on the screen and domain. If needed, inspect nearby code or UI context before deciding.
+
+Keep English terms unchanged when they function more like product language, technical labels, or domain-specific jargon than ordinary UI text. This often applies to terms such as `Playlist`, `Profile`, `Output`, `Driver`, `Theme`, and `Preset` when the surrounding product language, target audience, or existing translations suggest they should stay in English. Translate them only when the app clearly treats them as normal user-facing words in the target locale and the rest of the product uses localized equivalents consistently.
+
+### 9. File editing behavior
+
+Edit the target file directly. Do not add explanations into the file. Do not add comments. Do not create translation tables. Do not regroup entries. Do not change casing style, indentation, or layout unless the original file already follows a specific pattern.
+
+If you report back to the user, keep it brief and focus on:
+
+- which file was updated
+- which file was created, if any
+- which language was added or extended
+
+## Suggested execution order
+
+1. Understand the project and domain
+2. Find the source resx file and any related localized files
+3. Check whether language settings or localization code also need updates
+4. Determine whether this is an extension task or a new-language task
+5. Update or create the correct file using the project's naming convention
+6. Translate strings with domain-aware wording while preserving format and encoding
+7. Recheck placeholders, XML integrity, terminology consistency, and any required language-selection wiring before finishing
+
+## Expected output
+
+The main output is an updated `.resx` file that preserves the original format.
+
+If you respond in chat, keep the response short and focused on the file result.
diff --git a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
index 5d07170..669edf2 100644
--- a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
+++ b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
@@ -1,5 +1,6 @@
-using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Optimizations.Models;
@@ -128,6 +129,115 @@ public class RevertManagerTests
Assert.False(result.Success);
Assert.False(File.Exists(path));
+ var failedStep = Assert.Single(result.FailedSteps);
+ Assert.NotNull(failedStep.RetryAction);
+ }
+ finally
+ {
+ if (File.Exists(path))
+ File.Delete(path);
+ }
+ }
+
+ [Fact]
+ public async Task RevertAsync_WithAllStepFailures_LeavesFileForAnotherAttempt()
+ {
+ var id = Guid.NewGuid();
+ var path = Path.Combine(Shared.RevertDirectory, id + ".json");
+ var cancellationToken = TestContext.Current.CancellationToken;
+ Directory.CreateDirectory(Shared.RevertDirectory);
+
+ var payload = new RevertData
+ {
+ OptimizationId = id,
+ OptimizationName = "TestOptimization",
+ AppliedAt = DateTime.UtcNow,
+ Steps = new List<RevertStepData>
+ {
+ new()
+ {
+ Type = "Shell",
+ Data = new ShellRevertStep
+ {
+ ShellType = ShellType.CMD,
+ Command = "exit 1"
+ }.ToData()
+ }
+ }
+ };
+
+ try
+ {
+ var json = JsonConvert.SerializeObject(payload, Formatting.Indented);
+ await File.WriteAllTextAsync(path, json, cancellationToken);
+
+ var manager = new RevertManager(NullLogger<RevertManager>.Instance, NullLoggerFactory.Instance);
+ var result = await manager.RevertAsync(new MockOptimization(id));
+
+ Assert.False(result.Success);
+ Assert.True(result.AllStepsFailed);
+ Assert.True(File.Exists(path));
+ var failedStep = Assert.Single(result.FailedSteps);
+ Assert.NotNull(failedStep.RetryAction);
+ }
+ finally
+ {
+ if (File.Exists(path))
+ File.Delete(path);
+ }
+ }
+
+ [Fact]
+ public async Task RevertAsync_WithPartialFailures_RetryActionSucceedsAfterRevertDataIsDeleted()
+ {
+ var id = Guid.NewGuid();
+ var path = Path.Combine(Shared.RevertDirectory, id + ".json");
+ var cancellationToken = TestContext.Current.CancellationToken;
+ Directory.CreateDirectory(Shared.RevertDirectory);
+
+ var payload = new RevertData
+ {
+ OptimizationId = id,
+ OptimizationName = "TestOptimization",
+ AppliedAt = DateTime.UtcNow,
+ Steps = new List<RevertStepData>
+ {
+ new()
+ {
+ Type = "Shell",
+ Data = new ShellRevertStep
+ {
+ ShellType = ShellType.CMD,
+ Command = "exit 0"
+ }.ToData()
+ },
+ new()
+ {
+ Type = RetryableTestRevertStep.StepType,
+ Data = new RetryableTestRevertStep
+ {
+ StepId = Guid.NewGuid().ToString("N"),
+ RemainingFailures = 1
+ }.ToData()
+ }
+ }
+ };
+
+ try
+ {
+ var json = JsonConvert.SerializeObject(payload, Formatting.Indented);
+ await File.WriteAllTextAsync(path, json, cancellationToken);
+
+ var manager = new RevertManager(NullLogger<RevertManager>.Instance, NullLoggerFactory.Instance);
+ var result = await manager.RevertAsync(new MockOptimization(id));
+
+ Assert.False(result.Success);
+ Assert.False(File.Exists(path));
+
+ var failedStep = Assert.Single(result.FailedSteps);
+ Assert.NotNull(failedStep.RetryAction);
+ Assert.True(await failedStep.RetryAction!());
+ Assert.False(File.Exists(path));
}
finally
{
@@ -151,3 +261,45 @@ public class MockOptimization(Guid id) : IOptimization
return Task.FromResult(ApplyResult.True());
}
}
+
+public class RetryableTestRevertStep : IRevertStep
+{
+ public const string StepType = "RetryableTest";
+
+ public string StepId { get; set; } = Guid.NewGuid().ToString("N");
+
+ public int RemainingFailures { get; set; }
+
+ public string Type => StepType;
+
+ public string Description => $"Retryable test step {StepId}";
+
+ public Task<bool> ExecuteAsync()
+ {
+ if (RemainingFailures > 0)
+ {
+ RemainingFailures--;
+ throw new InvalidOperationException("planned test failure");
+ }
+
+ return Task.FromResult(true);
+ }
+
+ public JObject ToData()
+ {
+ return new JObject
+ {
+ [nameof(StepId)] = StepId,
+ [nameof(RemainingFailures)] = RemainingFailures
+ };
+ }
+
+ public static RetryableTestRevertStep FromData(JToken data)
+ {
+ return new RetryableTestRevertStep
+ {
+ StepId = data[nameof(StepId)]?.ToString() ?? Guid.NewGuid().ToString("N"),
+ RemainingFailures = data[nameof(RemainingFailures)]?.Value<int>() ?? 0
+ };
+ }
+}
diff --git a/optimizerDuck.Test/Services/OptimizationServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServiceTests.cs
index 85b744d..f20c4b1 100644
--- a/optimizerDuck.Test/Services/OptimizationServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServiceTests.cs
@@ -59,7 +59,7 @@ public class OptimizationServiceTests
}
[Fact]
- public async Task ApplyAsync_FailureMessage_TriggersAutoRevert_And_RemovesRevertDataFile()
+ public async Task ApplyAsync_FailureMessage_DoesNotPersistRevertDataFile()
{
await RunInStaThreadAsync(async () =>
{
@@ -151,6 +151,263 @@ public class OptimizationServiceTests
});
}
+ [Fact]
+ public async Task RetryFailedStepsWithResultsAsync_WhenRetrySucceeds_ReturnsRevertStepForOriginalIndex()
+ {
+ await RunInStaThreadAsync(async () =>
+ {
+ var failedStep = new OperationStepResult
+ {
+ Index = 3,
+ Name = "Shell",
+ Description = "failed step",
+ Success = false,
+ Error = "fail",
+ RetryAction = () =>
+ {
+ ExecutionScope.RecordStep("Shell", "retried step", true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" });
+ return Task.FromResult(true);
+ }
+ };
+
+ var result = await OptimizationService.RetryFailedStepsWithResultsAsync(
+ [failedStep],
+ false,
+ NullLogger.Instance);
+
+ Assert.Empty(result.FailedSteps);
+ Assert.Single(result.RecoveredSteps);
+ Assert.Equal(3, result.RecoveredSteps[0].Index);
+ Assert.NotNull(result.RecoveredSteps[0].RevertStep);
+ });
+ }
+
+ [Fact]
+ public async Task ApplyAsync_PartialSuccess_PersistsRevertStepsAtOriginalIndexes()
+ {
+ await RunInStaThreadAsync(async () =>
+ {
+ var optimization = new FakeOptimization
+ {
+ ApplyImpl = _ =>
+ {
+ ExecutionScope.RecordStep("Shell", "step 1", true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 11" });
+ ExecutionScope.RecordStep("Shell", "step 2", false, null, "fail", () =>
+ {
+ ExecutionScope.RecordStep("Shell", "step 2 retry", true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" });
+ return Task.FromResult(true);
+ });
+ ExecutionScope.RecordStep("Shell", "step 3", true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 33" });
+ return Task.FromResult(ApplyResult.True());
+ }
+ };
+
+ var revertPath = GetRevertFilePath(optimization.Id);
+
+ try
+ {
+ if (File.Exists(revertPath))
+ File.Delete(revertPath);
+
+ var service = CreateService();
+ var progress = new Progress<ProcessingProgress>(_ => { });
+
+ var result = await service.ApplyAsync(optimization, progress);
+ var data = await RevertManager.GetRevertDataAsync(optimization.Id);
+
+ Assert.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("exit 11", data.Steps[0].Data[nameof(ShellRevertStep.Command)]?.ToString());
+ Assert.Equal("exit 33", data.Steps[2].Data[nameof(ShellRevertStep.Command)]?.ToString());
+ }
+ finally
+ {
+ if (File.Exists(revertPath))
+ File.Delete(revertPath);
+ }
+ });
+ }
+
+ [Fact]
+ public async Task UpsertRevertStepAtIndexAsync_AfterRetrySuccess_InsertsStepAtFailedIndexWithoutShiftingLaterSteps()
+ {
+ await RunInStaThreadAsync(async () =>
+ {
+ var optimization = new FakeOptimization
+ {
+ ApplyImpl = _ =>
+ {
+ ExecutionScope.RecordStep("Shell", "step 1", true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 11" });
+ ExecutionScope.RecordStep("Shell", "step 2", false, null, "fail", () =>
+ {
+ ExecutionScope.RecordStep("Shell", "step 2 retry", true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" });
+ return Task.FromResult(true);
+ });
+ ExecutionScope.RecordStep("Shell", "step 3", true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 33" });
+ return Task.FromResult(ApplyResult.True());
+ }
+ };
+
+ var revertPath = GetRevertFilePath(optimization.Id);
+
+ try
+ {
+ if (File.Exists(revertPath))
+ File.Delete(revertPath);
+
+ var service = CreateService();
+ var progress = new Progress<ProcessingProgress>(_ => { });
+ var applyResult = await service.ApplyAsync(optimization, progress);
+
+ Assert.Equal(OptimizationSuccessResult.PartialSuccess, applyResult.Status);
+
+ var retryResult = await OptimizationService.RetryFailedStepsWithResultsAsync(
+ applyResult.FailedSteps,
+ false,
+ NullLogger.Instance);
+
+ var retriedStep = Assert.Single(retryResult.RecoveredSteps);
+ Assert.Equal(2, retriedStep.Index);
+ Assert.NotNull(retriedStep.RevertStep);
+
+ var revertManager = new RevertManager(NullLogger<RevertManager>.Instance, NullLoggerFactory.Instance);
+ await revertManager.UpsertRevertStepAtIndexAsync(
+ optimization.Id,
+ optimization.OptimizationKey,
+ retriedStep.Index,
+ retriedStep.RevertStep!);
+
+ var data = await RevertManager.GetRevertDataAsync(optimization.Id);
+
+ Assert.NotNull(data);
+ Assert.Equal(3, data!.Steps.Count);
+ Assert.Equal("exit 11", data.Steps[0].Data[nameof(ShellRevertStep.Command)]?.ToString());
+ Assert.Equal("exit 0", data.Steps[1].Data[nameof(ShellRevertStep.Command)]?.ToString());
+ Assert.Equal("exit 33", data.Steps[2].Data[nameof(ShellRevertStep.Command)]?.ToString());
+ }
+ finally
+ {
+ if (File.Exists(revertPath))
+ File.Delete(revertPath);
+ }
+ });
+ }
+
+ [Fact]
+ public async Task UpsertRevertStepAtIndexAsync_AfterMultipleRetrySuccesses_PreservesOriginalOrder()
+ {
+ await RunInStaThreadAsync(async () =>
+ {
+ var optimization = new FakeOptimization
+ {
+ ApplyImpl = _ =>
+ {
+ ExecutionScope.RecordStep("Shell", "step 1", true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 11" });
+ ExecutionScope.RecordStep("Shell", "step 2", false, null, "fail 2", () =>
+ {
+ ExecutionScope.RecordStep("Shell", "step 2 retry", true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 22" });
+ return Task.FromResult(true);
+ });
+ ExecutionScope.RecordStep("Shell", "step 3", true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 33" });
+ ExecutionScope.RecordStep("Shell", "step 4", false, null, "fail 4", () =>
+ {
+ ExecutionScope.RecordStep("Shell", "step 4 retry", true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 44" });
+ return Task.FromResult(true);
+ });
+ return Task.FromResult(ApplyResult.True());
+ }
+ };
+
+ var revertPath = GetRevertFilePath(optimization.Id);
+
+ try
+ {
+ if (File.Exists(revertPath))
+ File.Delete(revertPath);
+
+ var service = CreateService();
+ var progress = new Progress<ProcessingProgress>(_ => { });
+ var applyResult = await service.ApplyAsync(optimization, progress);
+
+ Assert.Equal(OptimizationSuccessResult.PartialSuccess, applyResult.Status);
+ Assert.Equal([2, 4], applyResult.FailedSteps.Select(step => step.Index).ToArray());
+
+ var retryResult = await OptimizationService.RetryFailedStepsWithResultsAsync(
+ applyResult.FailedSteps,
+ false,
+ NullLogger.Instance);
+
+ Assert.Empty(retryResult.FailedSteps);
+ Assert.Equal([2, 4], retryResult.RecoveredSteps.Select(step => step.Index).ToArray());
+
+ var revertManager = new RevertManager(NullLogger<RevertManager>.Instance, NullLoggerFactory.Instance);
+ foreach (var recoveredStep in retryResult.RecoveredSteps)
+ await revertManager.UpsertRevertStepAtIndexAsync(
+ optimization.Id,
+ optimization.OptimizationKey,
+ recoveredStep.Index,
+ recoveredStep.RevertStep!);
+
+ var data = await RevertManager.GetRevertDataAsync(optimization.Id);
+
+ Assert.NotNull(data);
+ Assert.Equal(4, data!.Steps.Count);
+ var commands = data.Steps
+ .Select(step => step.Data[nameof(ShellRevertStep.Command)]!.ToString())
+ .ToArray();
+ Assert.Equal(["exit 11", "exit 22", "exit 33", "exit 44"],
+ commands);
+ }
+ finally
+ {
+ if (File.Exists(revertPath))
+ File.Delete(revertPath);
+ }
+ });
+ }
+
+ [Fact]
+ public async Task RetryFailedStepsWithResultsAsync_WhenRetryStillFails_ReturnsUpdatedFailedStep()
+ {
+ await RunInStaThreadAsync(async () =>
+ {
+ var failedStep = new OperationStepResult
+ {
+ Index = 2,
+ Name = "Shell",
+ Description = "still failing step",
+ Success = false,
+ Error = "initial error",
+ RetryAction = () => throw new InvalidOperationException("retry exploded")
+ };
+
+ var result = await OptimizationService.RetryFailedStepsWithResultsAsync(
+ [failedStep],
+ false,
+ NullLogger.Instance);
+
+ var stillFailedStep = Assert.Single(result.FailedSteps);
+ Assert.Empty(result.RecoveredSteps);
+ Assert.Equal(2, stillFailedStep.Index);
+ Assert.Equal("retry exploded", stillFailedStep.Error);
+ });
+ }
+
private static OptimizationService CreateService()
{
var revertManager = new RevertManager(NullLogger<RevertManager>.Instance, NullLoggerFactory.Instance);
@@ -221,4 +478,4 @@ public class OptimizationServiceTests
return ApplyImpl((progress, context));
}
}
-}
\ No newline at end of file
+}
diff --git a/optimizerDuck/Domain/Execution/ExecutionScope.cs b/optimizerDuck/Domain/Execution/ExecutionScope.cs
index 16af572..6d330b9 100644
--- a/optimizerDuck/Domain/Execution/ExecutionScope.cs
+++ b/optimizerDuck/Domain/Execution/ExecutionScope.cs
@@ -122,6 +122,23 @@ public sealed class ExecutionScope : IDisposable
return scope;
}
+ public static ExecutionScope BeginForCapture(ILogger logger)
+ {
+ if (_current.Value != null)
+ throw new InvalidOperationException("An execution scope is already active in the current context.");
+
+ var scope = new ExecutionScope
+ {
+ OptimizationId = Guid.Empty,
+ OptimizationKey = string.Empty,
+ OptimizationName = string.Empty,
+ Logger = logger
+ };
+ _current.Value = scope;
+ logger.LogDebug("Execution scope started for retry capture");
+ return scope;
+ }
+
public static ExecutedStep? RecordStep(
string name,
string description,
@@ -154,31 +171,13 @@ public sealed class ExecutionScope : IDisposable
public List<OperationStepResult> GetStepResults()
{
- return _executedSteps.Select(s => new OperationStepResult
- {
- Index = s.Index,
- Name = s.Name,
- Description = s.Description,
- Success = s.Success,
- Error = s.Error,
- RetryAction = s.RetryAction,
- RevertStep = s.RevertStep
- }).ToList();
+ return _executedSteps.Select(ToOperationStepResult).ToList();
}
public OptimizationResult ToResult()
{
var status = ResolveStatus();
- var failedSteps = FailedSteps.Select(s => new OperationStepResult
- {
- Index = s.Index,
- Name = s.Name,
- Description = s.Description,
- Success = s.Success,
- Error = s.Error,
- RetryAction = s.RetryAction,
- RevertStep = s.RevertStep
- }).ToList();
+ var failedSteps = FailedSteps.Select(ToOperationStepResult).ToList();
var allFailed = failedSteps.Count == ExecutedSteps.Count;
@@ -244,6 +243,20 @@ public sealed class ExecutionScope : IDisposable
: OptimizationSuccessResult.Failed;
}
+ private static OperationStepResult ToOperationStepResult(ExecutedStep step)
+ {
+ return new OperationStepResult
+ {
+ Index = step.Index,
+ Name = step.Name,
+ Description = step.Description,
+ Success = step.Success,
+ Error = step.Error,
+ RetryAction = step.RetryAction,
+ RevertStep = step.RevertStep
+ };
+ }
+
private class Stats
{
public int Fail;
@@ -339,4 +352,4 @@ public sealed record ExecutedStep
/// An optional action to retry this step if it failed.
/// </summary>
public Func<Task<bool>>? RetryAction { get; init; }
-}
\ No newline at end of file
+}
diff --git a/optimizerDuck/Domain/Optimizations/Models/OperationStepResult.cs b/optimizerDuck/Domain/Optimizations/Models/OperationStepResult.cs
index 85479a9..a8e7b8d 100644
--- a/optimizerDuck/Domain/Optimizations/Models/OperationStepResult.cs
+++ b/optimizerDuck/Domain/Optimizations/Models/OperationStepResult.cs
@@ -8,7 +8,7 @@ namespace optimizerDuck.Domain.Optimizations.Models;
public record OperationStepResult
{
/// <summary>
- /// The zero-based index of this step in the execution order.
+ /// The one-based index of this step in the execution order.
/// </summary>
public int Index { get; init; }
@@ -41,4 +41,4 @@ public record OperationStepResult
/// The revert data generated when applying this step, used to support retry synchronization.
/// </summary>
public IRevertStep? RevertStep { get; init; }
-}
\ No newline at end of file
+}
diff --git a/optimizerDuck/Domain/Revert/RevertResult.cs b/optimizerDuck/Domain/Revert/RevertResult.cs
index 9d5f3f0..c873ae0 100644
--- a/optimizerDuck/Domain/Revert/RevertResult.cs
+++ b/optimizerDuck/Domain/Revert/RevertResult.cs
@@ -25,10 +25,10 @@ public class RevertResult
/// <summary>
/// Details of any steps that failed during revert.
/// </summary>
- public List<OperationStepResult> FailedStepDetails { get; set; } = [];
+ public List<OperationStepResult> FailedSteps { get; set; } = [];
/// <summary>
/// Indicates whether the revert failed completely (all steps failed).
/// </summary>
- public bool IsCompleteFailure { get; set; }
-}
\ No newline at end of file
+ public bool AllStepsFailed { get; set; }
+}
diff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.cs
index 1276e9b..f62a59b 100644
--- a/optimizerDuck/Services/Optimization/OptimizationService.cs
+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs
@@ -125,44 +125,20 @@ public class OptimizationService(
{
Status = OptimizationSuccessResult.Failed,
Message = applyResult.Message,
- FailedSteps = scope.FailedSteps.Select(s => new OperationStepResult
- {
- Index = s.Index,
- Name = s.Name,
- Description = s.Description,
- Success = s.Success,
- Error = s.Error,
- RetryAction = s.RetryAction
- }).ToList()
+ FailedSteps = scope.GetStepResults().Where(step => !step.Success).ToList()
};
progress.Report(new ProcessingProgress
{ Message = Translations.Optimization_Apply_Completed, IsIndeterminate = false, Value = 1, Total = 1 });
var result = scope.ToResult();
- if (scope.HasSuccessfulSteps)
- try
- {
- await revertManager.SaveRevertDataAsync(scope);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Failed to save revert data for {Name}", optimization.OptimizationKey);
- }
+ await TrySaveRevertDataAsync(scope, optimization);
return result;
}
catch (Exception ex)
{
- var failedSteps = scope.FailedSteps.Select(s => new OperationStepResult
- {
- Index = s.Index,
- Name = s.Name,
- Description = s.Description,
- Success = s.Success,
- Error = s.Error,
- RetryAction = s.RetryAction
- }).ToList();
+ var failedSteps = scope.GetStepResults().Where(step => !step.Success).ToList();
var status = scope.HasSuccessfulSteps
? OptimizationSuccessResult.PartialSuccess
@@ -175,15 +151,7 @@ public class OptimizationService(
FailedSteps = failedSteps
};
- if (scope.HasSuccessfulSteps)
- try
- {
- await revertManager.SaveRevertDataAsync(scope);
- }
- catch (Exception ex2)
- {
- _logger.LogError(ex2, "Failed to save revert data after exception");
- }
+ await TrySaveRevertDataAsync(scope, optimization);
return result;
}
@@ -224,29 +192,39 @@ public class OptimizationService(
IReadOnlyList<OperationStepResult> failedSteps, bool reverseOrder, ILogger logger,
IProgress<ProcessingProgress>? progress = null)
{
- if (failedSteps.Count == 0) return [];
+ return (await RetryFailedStepsWithResultsAsync(failedSteps, reverseOrder, logger, progress)).FailedSteps;
+ }
- var stillFailed = new List<OperationStepResult>();
+ public static async Task<RetryFailedStepsResult> RetryFailedStepsWithResultsAsync(
+ IReadOnlyList<OperationStepResult> failedSteps, bool reverseOrder, ILogger logger,
+ IProgress<ProcessingProgress>? progress = null)
+ {
+ if (failedSteps.Count == 0) return new RetryFailedStepsResult([], []);
+
+ var remainingFailedSteps = new List<OperationStepResult>();
+ var recoveredSteps = new List<OperationStepResult>();
var orderedSteps =
reverseOrder ? failedSteps.OrderByDescending(s => s.Index) : failedSteps.OrderBy(s => s.Index);
var total = failedSteps.Count;
+ var processedCount = 0;
progress?.Report(new ProcessingProgress
{ Message = Translations.Optimization_Retry_Processing, IsIndeterminate = true });
foreach (var step in orderedSteps)
{
+ processedCount++;
progress?.Report(new ProcessingProgress
{
- Message = string.Format(Translations.Optimization_RetryStep_Processing, step.Name, step.Index, total),
+ Message = string.Format(Translations.Optimization_RetryStep_Processing, step.Name, processedCount, total),
IsIndeterminate = false,
- Value = step.Index,
+ Value = processedCount,
Total = total
});
if (step.RetryAction == null)
{
- stillFailed.Add(step);
+ remainingFailedSteps.Add(step);
continue;
}
@@ -254,7 +232,25 @@ public class OptimizationService(
Exception? error = null;
try
{
+ using var retryScope = ExecutionScope.BeginForCapture(logger);
success = await step.RetryAction();
+
+ 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
+ });
+ }
}
catch (Exception ex)
{
@@ -262,10 +258,26 @@ public class OptimizationService(
logger.LogError(ex, "Retry step {Name} failed", step.Name);
}
- if (!success) stillFailed.Add(error != null ? step with { Error = error.Message } : step);
+ if (!success)
+ remainingFailedSteps.Add(error != null ? step with { Error = error.Message } : step);
}
- return stillFailed;
+ return new RetryFailedStepsResult(remainingFailedSteps, recoveredSteps);
+ }
+
+ private async Task TrySaveRevertDataAsync(ExecutionScope scope, IOptimization optimization)
+ {
+ if (!scope.HasSuccessfulSteps)
+ return;
+
+ try
+ {
+ await revertManager.SaveRevertDataAsync(scope);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Failed to save revert data for {Name}", optimization.OptimizationKey);
+ }
}
public static void ClearResources(ILogger logger)
@@ -288,4 +300,8 @@ public enum RestorePointResult
Success,
Failed,
FrequencyLimitReached
-}
\ No newline at end of file
+}
+
+public sealed record RetryFailedStepsResult(
+ List<OperationStepResult> FailedSteps,
+ List<OperationStepResult> RecoveredSteps);
diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.cs
index 313cac2..f1d067f 100644
--- a/optimizerDuck/Services/Revert/RevertManager.cs
+++ b/optimizerDuck/Services/Revert/RevertManager.cs
@@ -21,12 +21,24 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF
public async Task SaveRevertDataAsync(ExecutionScope scope)
{
- var steps = scope.SuccessfulSteps
- .Where(s => s.RevertStep != null)
- .Select(s => new RevertStepData { Type = s.RevertStep!.Type, Data = s.RevertStep.ToData() })
+ var maxIndex = scope.ExecutedSteps.Count == 0 ? 0 : scope.ExecutedSteps.Max(s => s.Index);
+ if (maxIndex == 0) return;
+
+ var steps = Enumerable.Range(0, maxIndex)
+ .Select(_ => new RevertStepData { Type = "Unknown", Data = new JObject() })
.ToList();
+ var hasRevertStep = false;
+
+ foreach (var step in scope.ExecutedSteps)
+ {
+ if (step.RevertStep == null)
+ continue;
+
+ steps[step.Index - 1] = new RevertStepData { Type = step.RevertStep.Type, Data = step.RevertStep.ToData() };
+ hasRevertStep = true;
+ }
- if (steps.Count == 0) return;
+ if (!hasRevertStep) return;
await WriteJsonAsync(GetFilePath(scope.OptimizationId!.Value), new RevertData
{
@@ -37,17 +49,18 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF
});
}
- public async Task<RevertResult> RevertAsync(IOptimization opt, IProgress<ProcessingProgress>? progress = null)
+ public async Task<RevertResult> RevertAsync(IOptimization optimization,
+ IProgress<ProcessingProgress>? progress = null)
{
- var l = loggerFactory.CreateLogger<RevertManager>();
- using var scope = ExecutionScope.BeginForLogging(opt.Id, opt.OptimizationKey, l);
+ var operationLogger = loggerFactory.CreateLogger<RevertManager>();
+ using var scope = ExecutionScope.BeginForLogging(optimization.Id, optimization.OptimizationKey, operationLogger);
- var steps = await LoadStepsAsync(opt.Id);
+ var steps = await LoadStepsAsync(optimization.Id);
if (steps.Count == 0)
return new RevertResult
- { Success = false, Message = string.Format(Translations.Revert_Error_NoDataFound, opt.Name) };
+ { Success = false, Message = string.Format(Translations.Revert_Error_NoDataFound, optimization.Name) };
- var failed = new List<OperationStepResult>();
+ var failedSteps = new List<OperationStepResult>();
var total = steps.Count;
for (var i = total - 1; i >= 0; i--)
@@ -65,7 +78,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF
}
catch (Exception ex)
{
- failed.Add(new OperationStepResult
+ failedSteps.Add(new OperationStepResult
{
Index = idx, Name = step.Type, Description = step.Description, Success = false, Error = ex.Message,
RetryAction = () => step.ExecuteAsync()
@@ -73,21 +86,24 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF
}
}
- if (failed.Count < total) Remove(opt.Id);
+ if (failedSteps.Count < total)
+ RemoveRevertData(optimization.Id, optimization.OptimizationKey);
return new RevertResult
{
- Success = failed.Count == 0,
- IsCompleteFailure = failed.Count == total,
- Message = failed.Count == total ? string.Format(Translations.Optimization_Revert_Error_Failed, opt.Name) :
- failed.Count > 0 ? string.Format(Translations.Optimization_Revert_Error_FailedWithSteps, opt.Name,
- failed.Count) :
- string.Format(Translations.Optimization_Revert_Success, opt.Name),
- FailedStepDetails = failed
+ Success = failedSteps.Count == 0,
+ AllStepsFailed = failedSteps.Count == total,
+ Message = failedSteps.Count == total
+ ? string.Format(Translations.Optimization_Revert_Error_Failed, optimization.Name)
+ : failedSteps.Count > 0
+ ? string.Format(Translations.Optimization_Revert_Error_FailedWithSteps, optimization.Name,
+ failedSteps.Count)
+ : string.Format(Translations.Optimization_Revert_Success, optimization.Name),
+ FailedSteps = failedSteps
};
}
- public async Task AppendOrUpdateRevertStepAsync(Guid id, string name, int idx, IRevertStep step)
+ public async Task UpsertRevertStepAtIndexAsync(Guid id, string name, int stepIndex, IRevertStep step)
{
var filePath = GetFilePath(id);
var lockObj = _fileLocks.GetOrAdd(id, _ => new SemaphoreSlim(1, 1));
@@ -98,10 +114,10 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF
var data = await LoadAsync(filePath) ?? new RevertData
{ OptimizationId = id, OptimizationName = name, Steps = [] };
- while (data.Steps.Count < idx)
+ while (data.Steps.Count < stepIndex)
data.Steps.Add(new RevertStepData { Type = "Unknown", Data = new JObject() });
- data.Steps[idx - 1] = new RevertStepData { Type = step.Type, Data = step.ToData() };
+ data.Steps[stepIndex - 1] = new RevertStepData { Type = step.Type, Data = step.ToData() };
await WriteJsonAsync(filePath, data);
}
finally
@@ -120,7 +136,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF
return await LoadAsync(GetFilePath(id));
}
- public static void ClearAllRevertData(ILogger l)
+ public static void ClearAllRevertData(ILogger logger)
{
if (!Directory.Exists(Shared.RevertDirectory)) return;
foreach (var f in Directory.GetFiles(Shared.RevertDirectory))
@@ -130,7 +146,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF
}
catch (Exception ex)
{
- l.LogError(ex, "Failed to delete {File}", f);
+ logger.LogError(ex, "Failed to delete {File}", f);
}
}
@@ -154,6 +170,11 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF
}
}
+ public void RemoveRevertData(Guid id, string? name = null)
+ {
+ Remove(id, name);
+ }
+
private static async Task WriteJsonAsync(string path, RevertData data)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
@@ -216,4 +237,4 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF
}
#endregion
-}
\ No newline at end of file
+}
diff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
index 1028a07..a28fd3d 100644
--- a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
@@ -11,6 +11,7 @@ using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Configuration;
using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.Revert;
using optimizerDuck.Domain.UI;
using optimizerDuck.Resources.Languages;
using optimizerDuck.Services;
@@ -150,7 +151,7 @@ public partial class OptimizationCategoryViewModel : ViewModel
// If result status is Failed, we can't retry it
if (applyResult.Status == OptimizationSuccessResult.Failed)
{
- ShowOutcomeSnackbar(false, false, true, "apply",
+ ShowOperationOutcomeSnackbar(OperationNotificationState.Failed, OptimizationOperation.Apply,
applyResult.Message, restorePointCreated);
_logger.LogWarning("Apply failed for {Name}: {Message}",
@@ -165,25 +166,21 @@ public partial class OptimizationCategoryViewModel : ViewModel
}
// Retry only if there are some successful steps and some failed steps
- var retryOutcome = await HandleFailedStepsAsync(
+ var retryOutcome = await HandleRetryableFailuresAsync(
optimization,
applyResult.FailedSteps,
- false);
+ OptimizationOperation.Apply);
await OptimizationService.UpdateOptimizationStateAsync(optimization);
- var succeeded = applyResult.Status == OptimizationSuccessResult.Success ||
- retryOutcome == RetryOutcome.Succeeded;
- var partial = retryOutcome == RetryOutcome.Skipped;
- var failed = retryOutcome == RetryOutcome.None &&
- applyResult.Status != OptimizationSuccessResult.Success;
+ var notificationState = ResolveApplyNotificationState(applyResult, retryOutcome);
- ShowOutcomeSnackbar(succeeded, partial, failed, "apply",
+ ShowOperationOutcomeSnackbar(notificationState, OptimizationOperation.Apply,
applyResult.Message, restorePointCreated);
- if (succeeded)
+ if (notificationState == OperationNotificationState.Success)
_logger.LogInformation("Successfully applied {Name}", optimization.OptimizationKey);
- else if (partial)
+ else if (notificationState == OperationNotificationState.Partial)
_logger.LogWarning("Partially applied {Name}", optimization.OptimizationKey);
else
_logger.LogWarning("Failed to apply {Name}", optimization.OptimizationKey);
@@ -203,24 +200,21 @@ public partial class OptimizationCategoryViewModel : ViewModel
optimization,
progress => _optimizationService.RevertAsync(optimization, progress));
- var retryOutcome = await HandleFailedStepsAsync(
+ var retryOutcome = await HandleRetryableFailuresAsync(
optimization,
- revertResult.FailedStepDetails,
- true);
+ revertResult.FailedSteps,
+ OptimizationOperation.Revert);
await OptimizationService.UpdateOptimizationStateAsync(optimization);
- var succeeded = revertResult.Success || retryOutcome == RetryOutcome.Succeeded;
- var partial = retryOutcome == RetryOutcome.Skipped && !revertResult.IsCompleteFailure;
- var failed = (retryOutcome == RetryOutcome.None && !revertResult.Success) ||
- (revertResult.IsCompleteFailure && retryOutcome == RetryOutcome.Skipped);
+ var notificationState = ResolveRevertNotificationState(revertResult, retryOutcome);
- ShowOutcomeSnackbar(succeeded, partial, failed, "revert",
+ ShowOperationOutcomeSnackbar(notificationState, OptimizationOperation.Revert,
revertResult.Message, restorePointCreated);
- if (succeeded)
+ if (notificationState == OperationNotificationState.Success)
_logger.LogInformation("Successfully reverted {Name}", optimization.OptimizationKey);
- else if (partial)
+ else if (notificationState == OperationNotificationState.Partial)
_logger.LogWarning("Partially reverted {Name}", optimization.OptimizationKey);
else
_logger.LogWarning("Failed to revert {Name}", optimization.OptimizationKey);
@@ -278,7 +272,7 @@ public partial class OptimizationCategoryViewModel : ViewModel
var fileName = baseOpt.OwnerType.Name;
var className = optimization.OptimizationKey;
- var relativePath = $"optimizerDuck/Core/Optimizers/{fileName}.cs";
+ var relativePath = $"optimizerDuck/Domain/Optimizations/Categories/{fileName}.cs";
var url = $"{Shared.GitHubRepoURL}/blob/master/{relativePath}";
// Fetch source from GitHub raw content to find the class line number
@@ -445,19 +439,19 @@ public partial class OptimizationCategoryViewModel : ViewModel
/// </summary>
/// <param name="optimization">The optimization that failed.</param>
/// <param name="failedSteps">The failed steps.</param>
- /// <param name="isRevert">Whether the optimization is being reverted.</param>
+ /// <param name="operation">The operation currently being processed.</param>
/// <returns>The retry outcome.</returns>
- private async Task<RetryOutcome> HandleFailedStepsAsync(IOptimization optimization,
- List<OperationStepResult> failedSteps, bool isRevert)
+ private async Task<FailureResolutionOutcome> HandleRetryableFailuresAsync(IOptimization optimization,
+ IReadOnlyList<OperationStepResult> failedSteps, OptimizationOperation operation)
{
if (failedSteps.Count == 0)
- return RetryOutcome.None;
+ return FailureResolutionOutcome.NoFailures;
// Always keep steps ordered by their original index for a stable UI.
- var currentFailed = failedSteps.OrderBy(s => s.Index).ToList();
- while (currentFailed.Count > 0)
+ var remainingFailedSteps = failedSteps.OrderBy(s => s.Index).ToList();
+ while (remainingFailedSteps.Count > 0)
{
- var dialogViewModel = new OptimizationResultDialogViewModel(currentFailed);
+ var dialogViewModel = new OptimizationResultDialogViewModel(remainingFailedSteps);
var dialogContent = new OptimizationResultDialog { DataContext = dialogViewModel };
var dialog = new ContentDialog
@@ -470,65 +464,85 @@ public partial class OptimizationCategoryViewModel : ViewModel
var result = await _contentDialogService.ShowAsync(dialog, CancellationToken.None);
if (result != ContentDialogResult.Primary)
- return RetryOutcome.Skipped;
+ return FailureResolutionOutcome.Deferred;
- // Retry only the remaining failed steps. For revert, keep reverse order.
- if (isRevert)
+ if (operation == OptimizationOperation.Revert)
{
- currentFailed = (await RunWithProcessingDialogAsync(
+ remainingFailedSteps = (await RunWithProcessingDialogAsync(
optimization,
progress => OptimizationService.RetryFailedStepsAsync(
- currentFailed,
+ remainingFailedSteps,
true,
_logger,
progress)))
- .OrderByDescending(s => s.Index)
+ .OrderBy(s => s.Index)
.ToList();
- if (currentFailed.Count == 0)
+ if (remainingFailedSteps.Count == 0)
{
+ _revertManager.RemoveRevertData(optimization.Id, optimization.OptimizationKey);
await OptimizationService.UpdateOptimizationStateAsync(optimization);
- return RetryOutcome.Succeeded;
+ return FailureResolutionOutcome.Recovered;
}
}
else
{
- var newFailed = (await RunWithProcessingDialogAsync(
+ var retryResult = await RunWithProcessingDialogAsync(
optimization,
- progress => OptimizationService.RetryFailedStepsAsync(
- currentFailed,
+ progress => OptimizationService.RetryFailedStepsWithResultsAsync(
+ remainingFailedSteps,
false,
_logger,
- progress)))
+ progress));
+
+ var newFailed = retryResult.FailedSteps
.OrderBy(s => s.Index)
.ToList();
- // If any apply step succeeded during this specific retry pass, update RevertManager
- var succeededThisAttempt =
- currentFailed.Where(old => newFailed.All(n => n.Index != old.Index)).ToList();
- foreach (var s in succeededThisAttempt)
- if (s.RevertStep != null)
- await _revertManager.AppendOrUpdateRevertStepAsync(optimization.Id,
- optimization.OptimizationKey, s.Index, s.RevertStep);
+ foreach (var s in retryResult.RecoveredSteps.Where(s => s.RevertStep != null))
+ await _revertManager.UpsertRevertStepAtIndexAsync(optimization.Id,
+ optimization.OptimizationKey, s.Index, s.RevertStep!);
- currentFailed = newFailed;
- if (currentFailed.Count == 0) return RetryOutcome.Succeeded;
+ remainingFailedSteps = newFailed;
+ if (remainingFailedSteps.Count == 0)
+ return FailureResolutionOutcome.Recovered;
}
}
- return RetryOutcome.Succeeded;
+ return FailureResolutionOutcome.Recovered;
+ }
+
+ private static OperationNotificationState ResolveApplyNotificationState(OptimizationResult applyResult,
+ FailureResolutionOutcome retryOutcome)
+ {
+ if (applyResult.Status == OptimizationSuccessResult.Success || retryOutcome == FailureResolutionOutcome.Recovered)
+ return OperationNotificationState.Success;
+
+ return retryOutcome == FailureResolutionOutcome.Deferred
+ ? OperationNotificationState.Partial
+ : OperationNotificationState.Failed;
+ }
+
+ private static OperationNotificationState ResolveRevertNotificationState(RevertResult revertResult,
+ FailureResolutionOutcome retryOutcome)
+ {
+ if (revertResult.Success || retryOutcome == FailureResolutionOutcome.Recovered)
+ return OperationNotificationState.Success;
+
+ return revertResult.AllStepsFailed
+ ? OperationNotificationState.Failed
+ : OperationNotificationState.Partial;
}
/// <summary>
/// Shows a snackbar notification based on the operation outcome.
/// </summary>
- /// <param name="succeeded">Whether the operation succeeded.</param>
- /// <param name="partial">Whether the operation was partially successful.</param>
- /// <param name="failed">Whether the operation failed.</param>
- /// <param name="operationType">The type of operation.</param>
+ /// <param name="notificationState">The notification state to show.</param>
+ /// <param name="operation">The type of operation.</param>
/// <param name="message">The message to show.</param>
/// <param name="restorePointCreated">Whether a restore point was created.</param>
- private void ShowOutcomeSnackbar(bool succeeded, bool partial, bool failed, string operationType,
+ private void ShowOperationOutcomeSnackbar(OperationNotificationState notificationState,
+ OptimizationOperation operation,
string message, bool restorePointCreated = false)
{
var showSuccess = _appOptionsMonitor.CurrentValue.Optimize.ShowCompletionNotification;
@@ -538,11 +552,11 @@ public partial class OptimizationCategoryViewModel : ViewModel
finalMessage += "\n" + string.Format(Translations.RestorePoint_Snackbar_Success_Message,
Shared.RestorePointName);
- if (succeeded)
+ if (notificationState == OperationNotificationState.Success)
{
if (showSuccess)
_snackbarService.Show(
- operationType == "apply"
+ operation == OptimizationOperation.Apply
? Translations.Optimization_Apply_Snackbar_Success_Title
: Translations.Optimization_Revert_Snackbar_Success_Title,
finalMessage,
@@ -550,10 +564,10 @@ public partial class OptimizationCategoryViewModel : ViewModel
new SymbolIcon { Symbol = SymbolRegular.CheckmarkCircle24, Filled = true },
TimeSpan.FromSeconds(5));
}
- else if (partial)
+ else if (notificationState == OperationNotificationState.Partial)
{
_snackbarService.Show(
- operationType == "apply"
+ operation == OptimizationOperation.Apply
? Translations.Optimization_Apply_Snackbar_Error_Title
: Translations.Optimization_Revert_Snackbar_Error_Title,
finalMessage,
@@ -561,10 +575,10 @@ public partial class OptimizationCategoryViewModel : ViewModel
new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },
TimeSpan.FromSeconds(5));
}
- else if (failed)
+ else if (notificationState == OperationNotificationState.Failed)
{
_snackbarService.Show(
- operationType == "apply"
+ operation == OptimizationOperation.Apply
? Translations.Optimization_Apply_Snackbar_Error_Title
: Translations.Optimization_Revert_Snackbar_Error_Title,
finalMessage,
@@ -670,12 +684,25 @@ public partial class OptimizationCategoryViewModel : ViewModel
};
}
- private enum RetryOutcome
+ private enum FailureResolutionOutcome
+ {
+ NoFailures,
+ Recovered,
+ Deferred
+ }
+
+ private enum OperationNotificationState
+ {
+ Success,
+ Partial,
+ Failed
+ }
+
+ private enum OptimizationOperation
{
- None,
- Succeeded,
- Skipped
+ Apply,
+ Revert
}
#endregion Helpers
-}
\ No newline at end of file
+}