Skip to content

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

feat: imrpove codes

fatDuck70513f3efe1b
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
new file mode 100644
index 0000000..304f41e
--- /dev/null
+++ b/.claude/settings.local.json
@@ -0,0 +1,8 @@
+{
+ "permissions": {
+ "allow": [
+ "Bash(test:*)",
+ "Bash(dotnet build:*)"
+ ]
+ }
+}
diff --git a/.gitattributes b/.gitattributes
index 176a458..94f480d 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1 +1 @@
-* text=auto
+* text=auto eol=lf
\ No newline at end of file
diff --git a/AGENTS.md b/AGENTS.md
index e78cf51..6d3ca2d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -2,49 +2,283 @@
Welcome to the `optimizerDuck` repository! This document provides guidelines for contributing to the project, ensuring consistency and maintainability across the codebase.
-## Project Structure & Module Organization
+## Project Overview
+
+optimizerDuck is a free, open-source Windows optimization tool built with WPF and .NET 10. It provides system performance optimizations, privacy enhancements, disk cleanup, bloatware removal, and startup management features.
+
+## Build, Test & Lint Commands
+
+### Building
+```bash
+# Build the entire solution
+dotnet build optimizerDuck.slnx
+
+# Or use the build script
+./build.bat
+```
+
+### Testing
+```bash
+# Run all tests
+dotnet test optimizerDuck.Test/optimizerDuck.Test.csproj
+
+# Run a single test class
+dotnet test optimizerDuck.Test/optimizerDuck.Test.csproj --filter "FullyQualifiedName~OptimizationServiceTests"
-The repository is organized into two primary projects:
+# Run a single test method
+dotnet test optimizerDuck.Test/optimizerDuck.Test.csproj --filter "FullyQualifiedName~OptimizationServiceTests.ApplyAsync_Success_PersistsRevertDataFile"
-- **`optimizerDuck/`**: The core C# Windows application source.
- - `UI/`: Contains XAML views, pages, and components.
- - `Services/`: Houses business logic and system operations (e.g., `DiskCleanupService.cs`, `OptimizationService.cs`).
- - `Common/`: Shared utilities, helpers, and data converters.
- - `Resources/`: Application assets and multi-language `.resx` translation files.
-- **`optimizerDuck.Test/`**: The xUnit test suite for validating application logic.
+# Run tests with coverage
+dotnet test optimizerDuck.Test/optimizerDuck.Test.csproj --collect:"XPlat Code Coverage"
+```
-*To build the application, execute the `build.bat` script in the root directory or run `dotnet build optimizerDuck.slnx`.*
+### Linting
+No explicit lint command is configured. The project uses standard C# conventions enforced by the compiler and IDE. The `.editorconfig` suppresses `CA1416` (Platform compatibility) warnings.
+
+## Project Structure & Module Organization
+
+```
+optimizerDuck/
+├── optimizerDuck/ # Main application
+│ ├── UI/ # XAML views and view models
+│ │ ├── Views/
+│ │ │ ├── Pages/ # Page views (Dashboard, Settings, etc.)
+│ │ │ ├── Windows/ # Window views (MainWindow)
+│ │ │ └── Dialogs/ # Dialog views
+│ │ └── ViewModels/ # MVVM view models
+│ ├── Services/ # Business logic and system operations
+│ │ ├── OptimizationServices/ # Registry, Shell, Service, ScheduledTask
+│ │ └── Managers/ # RevertManager, ConfigManager, LanguageManager
+│ ├── Core/
+│ │ ├── Optimizers/ # Optimization category implementations
+│ │ ├── Models/ # Data models and interfaces
+│ │ └── Interfaces/ # IOptimization, IOptimizationCategory
+│ ├── Common/
+│ │ ├── Converters/ # XAML value converters
+│ │ ├── Helpers/ # Utility classes (Shared, ThemeResource)
+│ │ └── Extensions/ # Extension methods
+│ └── Resources/
+│ ├── Languages/ # Localization .resx files
+│ └── Images/ # Application assets
+│
+└── optimizerDuck.Test/ # Test suite
+ └── Services/ # Tests mirror main project structure
+```
## Coding Style & Naming Conventions
-This project targets modern .NET (C#) and uses XAML for the frontend presentation.
+### C# Conventions
+
+- **Classes, Methods, Properties, Enums**: Use `PascalCase`
+ ```csharp
+ public class OptimizationService { }
+ public void ApplyAsync() { }
+ public string OptimizationKey { get; }
+ public enum OptimizationRisk { Safe, Moderate, Risky }
+ ```
+
+- **Private Fields**: Use `_` prefix with `camelCase`
+ ```csharp
+ private readonly ILogger _logger;
+ private static readonly Dictionary<Guid, bool> _stateCache = new();
+ ```
+
+- **Local Variables & Parameters**: Use `camelCase`
+ ```csharp
+ var optimizationId = optimization.Id;
+ public Task<ApplyResult> ApplyAsync(IProgress<ProcessingProgress> progress)
+ ```
+
+- **Constants**: Use `PascalCase` for public, `_PascalCase` for private
+ ```csharp
+ public const int MaxRetries = 3;
+ private const int Win32Priority = 38;
+ ```
+
+### Import Organization
+
+Imports are ordered alphabetically. `System.*` imports come first, followed by third-party libraries, then project namespaces:
+
+```csharp
+using System.IO;
+using System.Text.RegularExpressions;
+using Microsoft.Extensions.Logging;
+using CommunityToolkit.Mvvm.ComponentModel;
+using optimizerDuck.Core.Interfaces;
+using optimizerDuck.Services.Managers;
+```
+
+### Primary Constructors (C# 12+)
+
+The project uses primary constructors for dependency injection. Inject dependencies in the class declaration:
+
+```csharp
+public class OptimizationService(
+ RevertManager revertManager,
+ ILoggerFactory loggerFactory,
+ IContentDialogService contentDialogService,
+ ILogger<OptimizationService> logger)
+{
+ private readonly ILogger _logger = logger;
+ // ...
+}
+```
+
+### MVVM Pattern with CommunityToolkit.Mvvm
-- **Classes & Methods**: Use `PascalCase` (e.g., `OptimizationService`, `GetSettings()`).
-- **Variables & Parameters**: Use `camelCase` (e.g., `availableSpace`, `configData`).
-- **Localization**: Avoid hardcoding UI text. Update the `.resx` files located in the `optimizerDuck/Resources/` directory for any new user-facing strings.
-- **Linting & Formatting**: Follow standard C# conventions. The project's `.editorconfig` silently suppresses `CA1416` (Platform compatibility) warnings.
+Use `[ObservableProperty]` for bindable properties and `[RelayCommand]` for commands:
+
+```csharp
+public partial class SettingsViewModel : ViewModel
+{
+ [ObservableProperty]
+ private ApplicationTheme _currentApplicationTheme;
+
+ [RelayCommand]
+ private void OpenRootDir()
+ {
+ // ...
+ }
+}
+```
+
+### Nullable Reference Types
+
+Nullable reference types are enabled. Use `?` for nullable types and null checks:
+
+```csharp
+public Type? OwnerType { get; set; }
+private IHost? _host;
+
+if (result != null)
+ return result;
+```
+
+## Localization
+
+All user-facing text must be localized using the `.resx` files in `optimizerDuck/Resources/Languages/`:
+
+- `Translations.resx` - Default (English)
+- Access via `Translations.ResourceName` or `Loc.Instance["Key"]`
+
+Never hardcode UI strings in code. Add new strings to the `.resx` file first.
+
+## Optimization Implementation Pattern
+
+Optimizations follow a specific pattern using attributes and base classes:
+
+```csharp
+[OptimizationCategory(typeof(OptimizationPage))]
+public class Performance : IOptimizationCategory
+{
+ public string Name { get; init; } = Loc.Instance[$"Optimizer.{nameof(Performance)}"];
+ public OptimizationCategoryOrder Order { get; init; } = OptimizationCategoryOrder.Performance;
+ public ObservableCollection<IOptimization> Optimizations { get; init; } = [];
+
+ [Optimization(
+ Id = "GUID-HERE",
+ Risk = OptimizationRisk.Safe,
+ Tags = OptimizationTags.System | OptimizationTags.Performance)]
+ public class DisableBackgroundApps : BaseOptimization
+ {
+ public override Task<ApplyResult> ApplyAsync(
+ IProgress<ProcessingProgress> progress,
+ OptimizationContext context)
+ {
+ // Use RegistryService, ShellService, etc.
+ RegistryService.Write(
+ new RegistryItem(@"HKCU\Software\Path", "ValueName", 1)
+ );
+ context.Logger.LogInformation("Applied optimization");
+ return Task.FromResult(ApplyResult.True());
+ }
+ }
+}
+```
+
+Use `RevertManager.Record()` to enable reverting:
+
+```csharp
+RevertManager.Record(new ShellRevertStep
+{
+ ShellType = ShellType.PowerShell,
+ Command = "revert command"
+});
+```
+
+## Error Handling
+
+- Use `ILogger` for logging errors, warnings, and information
+- Use try-catch for operations that may fail (file I/O, shell commands)
+- Return meaningful result objects instead of throwing exceptions for expected failures
+
+```csharp
+try
+{
+ // Operation
+}
+catch (Exception ex)
+{
+ logger.LogError(ex, "Failed to perform operation: {Details}", details);
+ return ApplyResult.False("Operation failed");
+}
+```
## Testing Guidelines
-We utilize **xUnit** as our testing framework and `coverlet` for test coverage.
+- **Framework**: xUnit with coverlet for coverage
+- **Test Class Naming**: Suffix with `Tests` (e.g., `OptimizationServiceTests`)
+- **Test Method Naming**: Describe behavior being tested
+ ```csharp
+ [Fact]
+ public async Task ApplyAsync_Success_PersistsRevertDataFile() { }
-- **Test Placement**: Align test project paths with the main project layout (e.g., tests for `Services/` go into `optimizerDuck.Test/Services/`).
-- **Naming Convention**: Suffix your test classes with `Tests` (e.g., `DiskCleanupServiceTests.cs`). Describe the behavior being tested clearly formatted in your test method names.
-- **Running Tests**: You can execute the test suite via the .NET CLI:
- ```bash
- dotnet test optimizerDuck.Test/optimizerDuck.Test.csproj
+ [Fact]
+ public async Task RevertAsync_WithValidData_RemovesFile() { }
```
+- **Test Placement**: Mirror the main project structure
+ - Tests for `Services/OptimizationService.cs` → `optimizerDuck.Test/Services/OptimizationServiceTests.cs`
+
+- **WPF/STA Tests**: Use the `RunInStaThreadAsync` helper for tests requiring STA thread:
+ ```csharp
+ private static Task RunInStaThreadAsync(Func<Task> action)
+ {
+ var tcs = new TaskCompletionSource();
+ var thread = new Thread(() =>
+ {
+ try { action().GetAwaiter().GetResult(); tcs.SetResult(); }
+ catch (Exception ex) { tcs.SetException(ex); }
+ });
+ thread.SetApartmentState(ApartmentState.STA);
+ thread.Start();
+ return tcs.Task;
+ }
+ ```
+
+## Key Dependencies
+
+- **WPF-UI** (4.2.0): Modern WPF controls and theming
+- **CommunityToolkit.Mvvm** (8.4.0): MVVM helpers
+- **Microsoft.Extensions.Hosting**: Dependency injection and configuration
+- **Serilog**: Structured logging
+- **Newtonsoft.Json**: JSON serialization
+- **TaskScheduler**: Windows scheduled task management
+
## Commit & Pull Request Guidelines
-We follow the **Conventional Commits** format for our Git workflow. Structure your commit messages using the following prefixes:
+Follow **Conventional Commits** format:
+
+- `feat:` - New features (e.g., `feat: add disk cleanup page`)
+- `fix:` - Bug fixes (e.g., `fix: correct registry path`)
+- `refactor:` - Code restructuring without behavior changes
+- `docs:` - Documentation updates
+- `test:` - Adding or modifying tests
-- `feat:` for new capabilities (e.g., `feat: add disk cleanup page and its features`).
-- `fix:` for bug resolutions (e.g., `fix: use proper color`).
-- `refactor:` for restructurings or enhancements (e.g., `refactor: move converters to common`).
+### Pull Request Checklist
-**When submitting a Pull Request:**
-- Prepend the PR title with the appropriate conventional commit type.
-- Ensure all recent changes compile successfully and all tests pass.
-- Provide a brief description of the applied modifications. Link any relevant GitHub issues.
-- Include a visual screenshot or GIF if your pull request modifies or creates UI elements.
+1. Prepend PR title with conventional commit type
+2. Ensure build succeeds: `dotnet build optimizerDuck.slnx`
+3. Ensure tests pass: `dotnet test optimizerDuck.Test/optimizerDuck.Test.csproj`
+4. Provide description of modifications and link relevant issues
+5. Include screenshots/GIF for UI changes
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..f6d0531
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,164 @@
+# CLAUDE.md
+
+This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
+
+## Build and Development Commands
+
+### Building the Application
+This is a .NET 10.0 WPF application with two publish profiles:
+
+```bash
+# Portable build (multiple files, smaller executable)
+dotnet publish optimizerDuck/optimizerDuck.csproj /p:PublishProfile=Portable
+
+# Single-file build (single large executable)
+dotnet publish optimizerDuck/optimizerDuck.csproj /p:PublishProfile=Single
+```
+
+Reference: `build.bat` for the interactive build script.
+
+### Testing
+```bash
+# Run all tests
+dotnet test
+
+# Run tests with specific filter
+dotnet test --filter "FullyQualifiedName~OptimizerName"
+
+# Run specific test project
+dotnet test optimizerDuck.Test/optimizerDuck.Test.csproj
+```
+
+### General Development
+```bash
+# Restore dependencies
+dotnet restore
+
+# Build solution
+dotnet build
+
+# Clean solution
+dotnet clean
+```
+
+## High-Level Architecture
+
+optimizerDuck is a Windows optimization tool built with WPF, following MVVM pattern and modern .NET practices. Understanding the architecture requires knowledge across multiple layers:
+
+### 1. Discovery and Registration System
+
+**Attribute-Based Optimization Discovery**: Optimizations are discovered at startup via reflection using `[Optimization]` attributes. The `OptimizationRegistry` in `Services/OptimizationRegistry.cs` handles this by scanning assemblies for types implementing `IOptimization`.
+
+Key files:
+- `OptimizerDuck.Core.Optimizers.BaseOptimization` - Abstract base for all optimizations
+- `OptimizerDuck.Services.OptimizationRegistry` - Discovers and registers optimizations
+- `OptimizerDuck.Core.Models.Attributes.OptimizationAttribute` - Defines optimization metadata
+- `OptimizerDuck.Services.OptimizationPageRegistryExtensions` - DI registration helper
+
+**Category Organization**: Optimizations are grouped by categories (e.g., Performance, Security). Categories use `[OptimizationCategory]` attributes and are ordered via `OptimizationCategoryOrder`.
+
+### 2. Execution and Revert System
+
+**Two-Phase Execution with Revert Support**: Each optimization can modify system state and record a revert plan. This is handled by the `OptimizationService` and `RevertManager`:
+
+- **Apply Phase**: Optimizations execute modifications and capture revert data
+- **Revert Data**: Stored as JSON in `%appdata%\optimizerDuck\Revert\{guid}.json`
+- **Revert Steps**: Support registry, services, scheduled tasks, and shell command reversions
+
+Key files:
+- `OptimizerDuck.Services.OptimizationService` - Coordinates optimization execution
+- `OptimizerDuck.Services.Managers.RevertManager` - Manages revert data persistence
+- `OptimizerDuck.Core.Models.Execution.OptimizationExecutionContext` - Tracks execution state
+- `OptimizerDuck.Core.Models.Revert.*` - Revert data models and step definitions
+
+### 3. Low-Level System Operations
+
+**Service Layer**: System modifications are abstracted through service classes in `Services/OptimizationServices/`:
+
+- `RegistryService` - Windows registry modifications
+- `ServiceProcessService` - Windows service control
+- `ScheduledTaskService` - Task scheduler operations
+- `ShellService` - PowerShell command execution
+
+**Critical Pattern**: These services accept a `password` parameter for privilege elevation. Never hardcode passwords - always accept them as method parameters. The `ShellService.Init()` method configures the elevation approach based on app settings.
+
+### 4. State Management and Tracking
+
+**State Persistence**: Current optimization states are cached in-memory and serialized to disk. The system tracks whether each optimization is applied and when.
+
+- `OptimizationService._stateCache` - In-memory state tracking
+- State files stored in `%appdata%\optimizerDuck\`
+- State must survive application restarts
+
+### 5. Dependency Injection and App Lifecycle
+
+**DI Container Setup**: The application uses `Microsoft.Extensions.Hosting` and services are registered in `App.xaml.cs`. Key points:
+
+- All major services are registered as singletons
+- Optimization pages are registered via `AddAllOptimizationPages()` extension method
+- WPF UI services (navigation, dialogs) use WPF-UI framework integration
+- Serilog is used for structured logging with a custom `ScopeBlockTextFormatter`
+
+**App Flow**:
+1. `App.OnStartup()` builds DI container, validates configuration
+2. `OptimizationRegistry.PreloadOptimizations()` discovers optimizations
+3. MainWindow shown via navigation service
+4. User interactions trigger `OptimizationService.ApplyOptimizationAsync()` or `RevertOptimizationAsync()`
+5. `App.OnExit()` flushes logs
+
+### 6. Multi-Language Support
+
+**Resource-Based Localization**: Uses .resx files in `Resources/Languages/`. The `LanguageManager` handles culture switching. Always use resource keys from `Translations.resx` for user-visible strings.
+
+## Important Patterns and Constraints
+
+### Optimization Implementation Pattern
+
+Every optimization must:
+1. Inherit from `BaseOptimization`
+2. Have `[Optimization]` attribute with unique ID and metadata
+3. Implement `IsOptimized()` to check current state
+4. Implement `Revert()` to revert changes
+5. Record revert steps via `executionContext.RecordRevertStep()`
+6. Use async/await for all async operations
+
+### Error Handling and Logging
+
+- Always use `ILogger<T>` for logging (injected via DI)
+- Use Serilog's structured logging: `logger.LogInformation("Applied {Count} changes", count)`
+- Catch exceptions at optimization boundaries - individual optimization failures shouldn't crash the app
+- User-facing errors should use the WPF-UI dialog service
+
+### File System Locations
+
+The app uses these directories (see `Common.Helpers.Shared`):
+- `%appdata%\optimizerDuck\` - Root directory for app data
+- `%appdata%\optimizerDuck\Revert\` - Revert data storage
+- `%appdata%\optimizerDuck\appsettings.json` - Configuration file
+- `%appdata%\optimizerDuck\optimizerDuck.log` - Log file
+
+## Testing Approach
+
+The project uses xUnit. When adding new optimizations:
+1. Add unit tests for the optimization logic
+2. Test revert functionality thoroughly
+3. Mock system services using test fakes
+4. Integration tests should use a test-friendly DI setup
+
+Reference: `optimizerDuck.Test/Services/Managers/RevertManagerTests.cs` for testing patterns.
+
+## Key Dependencies
+
+- **WPF-UI (4.2.0)**: UI framework, must follow their patterns for controls and dialogs
+- **CommunityToolkit.Mvvm (8.4.0)**: MVVM infrastructure, use `[ObservableProperty]` and automatic command generation
+- **Serilog (4.3.1)**: Logging framework with structured logging support
+- **Microsoft.Extensions.Hosting (10.0.3)**: DI and app lifecycle management
+
+## Important Files
+
+- `optimizerDuck/appsettings.json` (user config, created at runtime) - App configuration including theme, language, elevation password
+- `*.pubxml` files - Publish configurations
+- `OptimizationService.cs` - Core optimization execution logic
+- `BaseOptimization.cs` - Base class for all optimizations
+- `RevertManager.cs` - Revert system coordinator
+- `app.manifest` - Windows UAC manifest for privilege elevation
diff --git a/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs b/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
new file mode 100644
index 0000000..96005b5
--- /dev/null
+++ b/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
@@ -0,0 +1,192 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Core.Interfaces;
+using optimizerDuck.Core.Models.Execution;
+using optimizerDuck.Core.Models.Optimization;
+using optimizerDuck.Core.Models.UI;
+using OptimizationState = optimizerDuck.Core.Models.UI.OptimizationState;
+
+namespace optimizerDuck.Test.Services;
+
+public class ExecutionScopeTests
+{
+ [Fact]
+ public void RecordStep_WithSuccessfulStep_RecordsStep()
+ {
+ var logger = NullLogger.Instance;
+
+ using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+
+ ExecutionScope.RecordStep("TestStep", "Test description", true);
+
+ Assert.Single(scope.ExecutedSteps);
+ Assert.True(scope.HasSuccessfulSteps);
+ Assert.Equal("TestStep", scope.ExecutedSteps[0].Name);
+ }
+
+ [Fact]
+ public void RecordStep_WithFailedStep_RecordsFailedStep()
+ {
+ var logger = NullLogger.Instance;
+
+ using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+
+ ExecutionScope.RecordStep("TestStep", "Test description", false, error: "Test error");
+
+ Assert.Single(scope.ExecutedSteps);
+ Assert.False(scope.ExecutedSteps[0].Success);
+ Assert.False(scope.HasSuccessfulSteps);
+ Assert.Equal("Test error", scope.ExecutedSteps[0].Error);
+ }
+
+ [Fact]
+ public void RecordStep_WithRevertStep_RecordsRevertData()
+ {
+ var logger = NullLogger.Instance;
+ var revertStep = new MockRevertStep();
+
+ using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+
+ ExecutionScope.RecordStep("TestStep", "Test description", true, revertStep);
+
+ Assert.Single(scope.SuccessfulSteps);
+ Assert.NotNull(scope.SuccessfulSteps[0].RevertStep);
+ }
+
+ [Fact]
+ public void FailedSteps_ReturnsOnlyFailedSteps()
+ {
+ var logger = NullLogger.Instance;
+
+ using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+
+ ExecutionScope.RecordStep("SuccessStep1", "Description", true);
+ ExecutionScope.RecordStep("FailedStep", "Description", false, error: "Error");
+ ExecutionScope.RecordStep("SuccessStep2", "Description", true);
+
+ var failedSteps = scope.FailedSteps;
+
+ Assert.Single(failedSteps);
+ Assert.Equal("FailedStep", failedSteps[0].Name);
+ }
+
+ [Fact]
+ public void StepIndex_IncrementsSequentially()
+ {
+ var logger = NullLogger.Instance;
+
+ using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+
+ ExecutionScope.RecordStep("Step1", "Description", true);
+ ExecutionScope.RecordStep("Step2", "Description", true);
+ ExecutionScope.RecordStep("Step3", "Description", true);
+
+ Assert.Equal(1, scope.ExecutedSteps[0].Index);
+ Assert.Equal(2, scope.ExecutedSteps[1].Index);
+ Assert.Equal(3, scope.ExecutedSteps[2].Index);
+ }
+
+ [Fact]
+ public void Dispose_ClearsCurrentScope()
+ {
+ var logger = NullLogger.Instance;
+
+ var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+
+ ExecutionScope.RecordStep("Success", "Description", true);
+ ExecutionScope.RecordStep("Fail", "Description", false);
+
+ Assert.NotNull(ExecutionScope.Current);
+
+ scope.Dispose();
+
+ Assert.Null(ExecutionScope.Current);
+ }
+
+ [Fact]
+ public void Begin_WithLogger_CreatesLightweightScope()
+ {
+ var logger = NullLogger.Instance;
+
+ using var scope = ExecutionScope.Begin(logger);
+
+ ExecutionScope.RecordStep("TestStep", "Description", true);
+
+ Assert.NotNull(ExecutionScope.Current);
+ Assert.Single(scope.ExecutedSteps);
+ Assert.Equal(Guid.Empty, scope.OptimizationId);
+ }
+
+ [Fact]
+ public void Begin_ThrowsIfAlreadyActive()
+ {
+ var logger = NullLogger.Instance;
+
+ using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+
+ Assert.Throws<InvalidOperationException>(() =>
+ ExecutionScope.Begin(Guid.NewGuid(), "Another", logger));
+ }
+
+ [Fact]
+ public void RecordStep_WithoutActiveScope_ReturnsNull()
+ {
+ var result = ExecutionScope.RecordStep("TestStep", "Description", true);
+
+ Assert.Null(result);
+ }
+
+ [Fact]
+ public void Track_UpdatesStats()
+ {
+ var logger = NullLogger.Instance;
+
+ using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+
+ ExecutionScope.Track("Registry", true);
+ ExecutionScope.Track("Registry", true);
+ ExecutionScope.Track("Registry", false);
+
+ var steps = scope.GetStepResults();
+ Assert.Empty(steps);
+ }
+
+ [Fact]
+ public void GetStepResults_ReturnsOperationStepResults()
+ {
+ var logger = NullLogger.Instance;
+
+ using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+
+ ExecutionScope.RecordStep("Step1", "Desc1", true);
+ ExecutionScope.RecordStep("Step2", "Desc2", false, error: "err");
+
+ var results = scope.GetStepResults();
+
+ Assert.Equal(2, results.Count);
+ Assert.True(results[0].Success);
+ Assert.False(results[1].Success);
+ Assert.Equal("err", results[1].Error);
+ }
+}
+
+public class MockOptimization : IOptimization
+{
+ public Guid Id { get; } = Guid.NewGuid();
+ public OptimizationRisk Risk => OptimizationRisk.Safe;
+ public string OptimizationKey => "MockOptimization";
+ public string Name => "Mock Optimization";
+ public string ShortDescription => "Mock description";
+ public OptimizationState State { get; set; } = new();
+
+ public Task<ApplyResult> ApplyAsync(IProgress<ProcessingProgress> progress, OptimizationContext context)
+ {
+ return Task.FromResult(ApplyResult.True());
+ }
+}
+
+public class MockRevertStep : IRevertStep
+{
+ public string Type => "Mock";
+ public Task<bool> ExecuteAsync() => Task.FromResult(true);
+ public Newtonsoft.Json.Linq.JObject ToData() => new();
+}
diff --git a/optimizerDuck.Test/Services/OptimizationServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServiceTests.cs
index 619dace..9363f57 100644
--- a/optimizerDuck.Test/Services/OptimizationServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServiceTests.cs
@@ -2,6 +2,7 @@ using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Core.Interfaces;
+using optimizerDuck.Core.Models.Execution;
using optimizerDuck.Core.Models.Optimization;
using optimizerDuck.Core.Models.Revert;
using optimizerDuck.Core.Models.Revert.Steps;
@@ -23,8 +24,8 @@ public class OptimizationServiceTests
{
ApplyImpl = _ =>
{
- RevertManager.Record(new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" });
- ServiceTracker.TrackStep("Test", "Test step", true);
+ ExecutionScope.RecordStep("Test", "Test step", true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" });
return Task.FromResult(ApplyResult.True());
}
};
@@ -66,8 +67,9 @@ public class OptimizationServiceTests
{
ApplyImpl = _ =>
{
- RevertManager.Record(new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" });
- ServiceTracker.TrackStep("Test", "Failed step", false, "fail", () => Task.FromResult(false));
+ ExecutionScope.RecordStep("Test", "Test step", true,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" });
+ ExecutionScope.RecordStep("Test", "Failed step", false, error: "fail");
return Task.FromResult(ApplyResult.False("apply failed"));
}
};
@@ -212,7 +214,7 @@ public class OptimizationServiceTests
public string Name { get; } = "Test";
public string ShortDescription { get; } = "Test";
- public OptimizationState State { get; set; } = null!;
+ public OptimizationState State { get; set; } = new();
public Task<ApplyResult> ApplyAsync(IProgress<ProcessingProgress> progress, OptimizationContext context)
{
diff --git a/optimizerDuck/Core/Models/Execution/ExecutionScope.cs b/optimizerDuck/Core/Models/Execution/ExecutionScope.cs
new file mode 100644
index 0000000..7d85c48
--- /dev/null
+++ b/optimizerDuck/Core/Models/Execution/ExecutionScope.cs
@@ -0,0 +1,329 @@
+using System.Collections.Concurrent;
+using System.Diagnostics;
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Core.Interfaces;
+using optimizerDuck.Core.Models.Optimization;
+using optimizerDuck.Core.Models.UI;
+
+namespace optimizerDuck.Core.Models.Execution;
+
+public sealed class ExecutionScope : IDisposable
+{
+ private static readonly AsyncLocal<ExecutionScope?> _current = new();
+
+ private readonly Guid _optimizationId;
+ private readonly string _optimizationKey;
+ private readonly ILogger _logger;
+ private readonly Stopwatch _stopwatch;
+ private readonly List<ExecutedStep> _executedSteps = [];
+ private readonly ConcurrentDictionary<string, Stats> _stats = new();
+ private int _stepIndex;
+ private bool _disposed;
+
+ private ExecutionScope(Guid optimizationId, string optimizationKey, ILogger logger)
+ {
+ _optimizationId = optimizationId;
+ _optimizationKey = optimizationKey;
+ _logger = logger;
+ _stopwatch = Stopwatch.StartNew();
+ }
+
+ public static ExecutionScope? Current => _current.Value;
+
+ public Guid OptimizationId => _optimizationId;
+
+ public string OptimizationKey => _optimizationKey;
+
+ public ILogger Logger => _logger;
+
+ public IReadOnlyList<ExecutedStep> ExecutedSteps => _executedSteps.AsReadOnly();
+
+ public IReadOnlyList<ExecutedStep> SuccessfulSteps =>
+ _executedSteps.Where(s => s.Success).ToArray();
+
+ public IReadOnlyList<ExecutedStep> FailedSteps =>
+ _executedSteps.Where(s => !s.Success).ToArray();
+
+ public bool HasSuccessfulSteps => _executedSteps.Any(s => s.Success);
+
+ public static ExecutionScope Begin(Guid optimizationId, string optimizationKey, ILogger logger)
+ {
+ if (_current.Value != null)
+ throw new InvalidOperationException("An execution scope is already active in the current context.");
+
+ var scope = new ExecutionScope(optimizationId, optimizationKey, logger);
+ _current.Value = scope;
+ logger.LogDebug("Execution scope started for {Key} (ID: {Id})", optimizationKey, optimizationId);
+ return scope;
+ }
+
+ public static ExecutionScope Begin(ILogger logger)
+ {
+ if (_current.Value != null)
+ throw new InvalidOperationException("An execution scope is already active in the current context.");
+
+ var scope = new ExecutionScope(Guid.Empty, string.Empty, logger);
+ _current.Value = scope;
+ logger.LogDebug("Execution scope started");
+ return scope;
+ }
+
+ public static ExecutedStep? RecordStep(
+ string name,
+ string description,
+ bool success,
+ IRevertStep? revertStep = null,
+ string? error = null,
+ Func<Task<bool>>? retryAction = null)
+ {
+ var scope = Current;
+ if (scope == null)
+ return null;
+
+ return scope.RecordStepInternal(name, description, success, revertStep, error, retryAction);
+ }
+
+ public static void Track(string serviceName, bool success)
+ {
+ var scope = Current;
+ if (scope == null)
+ return;
+
+ scope._stats.AddOrUpdate(
+ serviceName,
+ _ => success
+ ? new Stats { Success = 1 }
+ : new Stats { Fail = 1 },
+ (_, stats) =>
+ {
+ if (success) stats.Success++;
+ else stats.Fail++;
+ return stats;
+ });
+ }
+
+ 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
+ }).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
+ }).ToList();
+
+ var allFailed = failedSteps.Count == ExecutedSteps.Count;
+ var hasFailures = failedSteps.Count > 0;
+
+ return new OptimizationResult
+ {
+ Status = status,
+ Message = status switch
+ {
+ OptimizationSuccessResult.Success =>
+ string.Format(optimizerDuck.Resources.Languages.Translations.Optimization_Apply_Success,
+ _optimizationKey),
+ OptimizationSuccessResult.Failed when allFailed =>
+ string.Format(optimizerDuck.Resources.Languages.Translations.Optimization_Apply_Error_Failed,
+ _optimizationKey),
+ OptimizationSuccessResult.PartialSuccess or OptimizationSuccessResult.Failed =>
+ string.Format(
+ optimizerDuck.Resources.Languages.Translations.Optimization_Apply_Error_FailedWithSteps,
+ _optimizationKey,
+ failedSteps.Count),
+ _ => $"Unknown result for {_optimizationKey}"
+ },
+ FailedSteps = failedSteps
+ };
+ }
+
+ private ExecutedStep RecordStepInternal(
+ string name,
+ string description,
+ bool success,
+ IRevertStep? revertStep,
+ string? error,
+ Func<Task<bool>>? retryAction = null)
+ {
+ var step = new ExecutedStep(
+ ++_stepIndex,
+ name,
+ description,
+ success,
+ revertStep,
+ error,
+ retryAction);
+
+ _executedSteps.Add(step);
+
+ _logger.LogDebug("Step {Index} ({Name}): {Result}",
+ step.Index, name, success ? "SUCCESS" : "FAILED");
+
+ return step;
+ }
+
+ #region Logging
+
+ public static void Log(LogLevel level, string message, params object[] args)
+ {
+ Current?._logger.Log(level, message, args);
+ }
+
+ public static void LogDebug(string message, params object[] args)
+ {
+ Log(LogLevel.Debug, message, args);
+ }
+
+ public static void LogTrace(string message, params object[] args)
+ {
+ Log(LogLevel.Trace, message, args);
+ }
+
+ public static void LogInfo(string message, params object[] args)
+ {
+ Log(LogLevel.Information, message, args);
+ }
+
+ public static void LogWarning(string message, params object[] args)
+ {
+ Log(LogLevel.Warning, message, args);
+ }
+
+ public static void LogError(Exception? ex, string message, params object[] args)
+ {
+ Current?._logger.LogError(ex, message, args);
+ }
+
+ #endregion Logging
+
+ private OptimizationSuccessResult ResolveStatus()
+ {
+ if (_executedSteps.Count == 0)
+ return OptimizationSuccessResult.Failed;
+
+ var failed = FailedSteps.Count;
+ var total = ExecutedSteps.Count;
+
+ return failed == 0
+ ? OptimizationSuccessResult.Success
+ : failed < total
+ ? OptimizationSuccessResult.PartialSuccess
+ : OptimizationSuccessResult.Failed;
+ }
+
+ public void Dispose()
+ {
+ if (_disposed)
+ return;
+ _disposed = true;
+
+ _stopwatch.Stop();
+
+ if (_stats.IsEmpty)
+ {
+ _logger.LogInformation(
+ "[{Key}] Completed in {Time} (no operations tracked)",
+ _optimizationKey,
+ _stopwatch.Elapsed.ToString(@"mm\:ss\.fff"));
+ }
+ else
+ {
+ var summary = string.Join(", ", _stats.Select(kv =>
+ $"{kv.Key}: +({kv.Value.Success}) -({kv.Value.Fail})"));
+
+ _logger.LogInformation(
+ "[{Key}] Completed in {Time} | {Summary}",
+ _optimizationKey,
+ _stopwatch.Elapsed.ToString(@"mm\:ss\.fff"),
+ summary);
+ }
+
+ _logger.LogInformation(
+ "[{Key}] Steps: {Total} ({Success} success, {Failed} failed)",
+ _optimizationKey,
+ _executedSteps.Count,
+ _executedSteps.Count(s => s.Success),
+ _executedSteps.Count(s => !s.Success)
+ );
+
+ _current.Value = null;
+ }
+
+ private class Stats
+ {
+ public int Success;
+ public int Fail;
+ }
+}
+
+/// <summary>
+/// Represents a step that was executed during an optimization.
+/// </summary>
+public sealed record ExecutedStep
+{
+ /// <summary>
+ /// The index of the step in the execution sequence.
+ /// </summary>
+ public int Index { get; init; }
+
+ /// <summary>
+ /// The category/name of the step (e.g., "Registry", "Shell").
+ /// </summary>
+ public string Name { get; init; }
+
+ /// <summary>
+ /// A description of what the step did.
+ /// </summary>
+ public string Description { get; init; }
+
+ /// <summary>
+ /// Whether the step succeeded.
+ /// </summary>
+ public bool Success { get; init; }
+
+ /// <summary>
+ /// The revert step that can undo this operation, if applicable.
+ /// </summary>
+ public IRevertStep? RevertStep { get; init; }
+
+ /// <summary>
+ /// The error message if the step failed, or null if it succeeded.
+ /// </summary>
+ public string? Error { get; init; }
+
+ /// <summary>
+ /// An optional action to retry this step if it failed.
+ /// </summary>
+ public Func<Task<bool>>? RetryAction { get; init; }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExecutedStep" /> class.
+ /// </summary>
+ public ExecutedStep(int index, string name, string description, bool success,
+ IRevertStep? revertStep, string? error, Func<Task<bool>>? retryAction = null)
+ {
+ Index = index;
+ Name = name;
+ Description = description;
+ Success = success;
+ RevertStep = revertStep;
+ Error = error;
+ RetryAction = retryAction;
+ }
+}
diff --git a/optimizerDuck/Core/Models/Revert/RevertContext.cs b/optimizerDuck/Core/Models/Revert/RevertContext.cs
deleted file mode 100644
index bbfcfa2..0000000
--- a/optimizerDuck/Core/Models/Revert/RevertContext.cs
+++ /dev/null
@@ -1,60 +0,0 @@
-using Microsoft.Extensions.Logging;
-using optimizerDuck.Core.Interfaces;
-using optimizerDuck.Services.Managers;
-
-namespace optimizerDuck.Core.Models.Revert;
-
-/// <summary>
-/// Manages the recording of revert steps during an optimization apply operation.
-/// Implements <see cref="IAsyncDisposable" /> to automatically persist recorded steps on disposal.
-/// </summary>
-public sealed class RevertContext : IAsyncDisposable
-{
- private readonly ILogger _logger;
- private readonly RevertManager _manager;
- private readonly IOptimization _optimization;
- private readonly Stack<IRevertStep> _steps = new();
-
- /// <summary>
- /// Initializes a new <see cref="RevertContext" /> for the given optimization.
- /// </summary>
- /// <param name="optimization">The optimization being performed.</param>
- /// <param name="logger">The logger for diagnostic messages.</param>
- /// <param name="manager">The revert manager responsible for persistence.</param>
- internal RevertContext(IOptimization optimization, ILogger logger, RevertManager manager)
- {
- _optimization = optimization;
- _logger = logger;
- _manager = manager;
- }
-
- /// <summary>
- /// Persists recorded revert steps and clears the current context.
- /// </summary>
- public async ValueTask DisposeAsync()
- {
- try
- {
- if (_steps.Count > 0)
- await _manager.SaveAsync(
- _optimization.Id,
- _optimization.OptimizationKey,
- _steps);
- else
- _logger.LogWarning("No revert steps recorded for {Name}", _optimization.OptimizationKey);
- }
- finally
- {
- if (RevertManager.Current == this) RevertManager.ClearCurrent();
- }
- }
-
- /// <summary>
- /// Adds a revert step to the recording stack.
- /// </summary>
- /// <param name="step">The revert step to record.</param>
- internal void AddStep(IRevertStep step)
- {
- _steps.Push(step);
- }
-}
\ No newline at end of file
diff --git a/optimizerDuck/Core/Models/Revert/RevertValidationResult.cs b/optimizerDuck/Core/Models/Revert/RevertValidationResult.cs
index ff79150..5fd1beb 100644
--- a/optimizerDuck/Core/Models/Revert/RevertValidationResult.cs
+++ b/optimizerDuck/Core/Models/Revert/RevertValidationResult.cs
@@ -1,5 +1,3 @@
-using optimizerDuck.Resources.Languages;
-
namespace optimizerDuck.Core.Models.Revert;
/// <summary>
@@ -35,7 +33,7 @@ public class RevertValidationResult
/// <returns>A valid <see cref="RevertValidationResult" />.</returns>
public static RevertValidationResult Success()
{
- return new RevertValidationResult(true, "Revert data is valid.", Translations.Revert_Error_InvalidData);
+ return new RevertValidationResult(true, "Revert data is valid.", string.Empty);
}
/// <summary>
diff --git a/optimizerDuck/Core/Models/Revert/Steps/RegistryRevertStep.cs b/optimizerDuck/Core/Models/Revert/Steps/RegistryRevertStep.cs
index 41d0b5b..35941c6 100644
--- a/optimizerDuck/Core/Models/Revert/Steps/RegistryRevertStep.cs
+++ b/optimizerDuck/Core/Models/Revert/Steps/RegistryRevertStep.cs
@@ -152,7 +152,7 @@ public class RegistryRevertStep : IRevertStep
value = token.ToObject<string>();
break;
case RegistryValueKind.MultiString:
- value = token.Type == JTokenType.Array ? token.ToObject<string[]>() : token.ToObject<string[]>();
+ value = token.ToObject<string[]>();
break;
case RegistryValueKind.Binary:
// stored as base64 string
diff --git a/optimizerDuck/Services/BloatwareService.cs b/optimizerDuck/Services/BloatwareService.cs
index 36ca84c..8de1681 100644
--- a/optimizerDuck/Services/BloatwareService.cs
+++ b/optimizerDuck/Services/BloatwareService.cs
@@ -8,6 +8,7 @@ using Microsoft.Extensions.Options;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Core.Models.Bloatware;
using optimizerDuck.Core.Models.Config;
+using optimizerDuck.Core.Models.Execution;
using optimizerDuck.Services.OptimizationServices;
using JsonSerializer = System.Text.Json.JsonSerializer;
@@ -97,7 +98,7 @@ public class BloatwareService(ILogger<BloatwareService> logger, IOptionsMonitor<
/// <param name="appXPackage">The package to remove.</param>
public async Task RemoveAppXPackage(AppXPackage appXPackage)
{
- using var tracker = ServiceTracker.Begin(logger);
+ using var scope = ExecutionScope.Begin(logger);
try
{
if (string.IsNullOrWhiteSpace(appXPackage.PackageFullName))
diff --git a/optimizerDuck/Services/Managers/RevertManager.cs b/optimizerDuck/Services/Managers/RevertManager.cs
index 8191eb8..1fb9c05 100644
--- a/optimizerDuck/Services/Managers/RevertManager.cs
+++ b/optimizerDuck/Services/Managers/RevertManager.cs
@@ -7,84 +7,56 @@ using optimizerDuck.Common.Helpers;
using optimizerDuck.Core.Interfaces;
using optimizerDuck.Core.Models.Optimization;
using optimizerDuck.Core.Models.Revert;
-using optimizerDuck.Core.Models.Revert.Steps;
using optimizerDuck.Core.Models.UI;
using optimizerDuck.Resources.Languages;
namespace optimizerDuck.Services.Managers;
-/// <summary>
-/// Manages revert functionality for optimizations, allowing users to undo changes.
-/// </summary>
public class RevertManager(ILogger<RevertManager> logger)
{
- /// <summary>
- /// Async local storage for the current revert context.
- /// </summary>
- private static readonly AsyncLocal<RevertContext?> _current = new();
-
- /// <summary>
- /// Auto-discovered registry mapping step type strings to their FromData factory methods.
- /// Built once at startup via reflection.
- /// </summary>
private static readonly Dictionary<string, Func<JObject, IRevertStep>> _stepRegistry = BuildStepRegistry();
- /// <summary>
- /// Gets the current revert context for the active async operation.
- /// </summary>
- public static RevertContext? Current => _current.Value;
-
- /// <summary>
- /// Begins recording revert steps for the specified optimization.
- /// </summary>
- /// <param name="optimization">The optimization being performed.</param>
- /// <returns>The created revert context.</returns>
- public RevertContext BeginRecording(IOptimization optimization)
- {
- var context = new RevertContext(optimization, logger, this);
- _current.Value = context;
- return context;
- }
+ public static IReadOnlyCollection<string> RegisteredStepTypes => _stepRegistry.Keys.ToList().AsReadOnly();
- /// <summary>
- /// Records a revert step to the current context.
- /// </summary>
- /// <param name="step">The revert step to record.</param>
- public static void Record(IRevertStep step)
+ public async Task SaveRevertDataAsync(Core.Models.Execution.ExecutionScope executionScope)
{
- Current?.AddStep(step);
- }
+ var successfulSteps = executionScope.SuccessfulSteps
+ .Where(s => s.RevertStep != null)
+ .ToList();
- internal async Task SaveAsync(Guid optimizationId, string optimizationName, Stack<IRevertStep> steps)
- {
- var filePath = Path.Combine(Shared.RevertDirectory, optimizationId + ".json");
+ if (successfulSteps.Count == 0)
+ {
+ logger.LogWarning("No revert steps to save for {Key}", executionScope.OptimizationKey);
+ return;
+ }
+
+ var steps = successfulSteps
+ .Select(s => new RevertStepData
+ {
+ Type = s.RevertStep!.Type,
+ Data = s.RevertStep.ToData()
+ })
+ .ToList();
+
+ var filePath = Path.Combine(Shared.RevertDirectory, executionScope.OptimizationId + ".json");
var tempPath = filePath + ".tmp";
try
{
- // Persist revert steps atomically to avoid partial writes.
- var stepData = steps.Reverse()
- .Select(s => new RevertStepData
- {
- Type = s.Type,
- Data = s.ToData()
- })
- .ToList();
-
var payload = new RevertData
{
- OptimizationId = optimizationId,
- OptimizationName = optimizationName,
+ OptimizationId = executionScope.OptimizationId,
+ OptimizationName = executionScope.OptimizationKey,
AppliedAt = DateTime.Now,
- Steps = stepData
+ Steps = steps
};
Directory.CreateDirectory(Shared.RevertDirectory);
var json = JsonConvert.SerializeObject(payload, Formatting.Indented);
await File.WriteAllTextAsync(tempPath, json);
File.Move(tempPath, filePath, true);
- logger.LogInformation("Saved {Count} revert steps for {Name} to {File}", steps.Count, optimizationName,
- filePath);
+ logger.LogInformation("Saved {Count} revert steps for {Name} to {File}",
+ steps.Count, executionScope.OptimizationKey, filePath);
}
catch (Exception ex)
{
@@ -95,10 +67,9 @@ public class RevertManager(ILogger<RevertManager> logger)
}
catch
{
- // Best-effort cleanup only.
}
- logger.LogError(ex, "Failed to save revert data for {Name}", optimizationName);
+ logger.LogError(ex, "Failed to save revert data for {Name}", executionScope.OptimizationKey);
throw;
}
}
@@ -136,11 +107,11 @@ public class RevertManager(ILogger<RevertManager> logger)
var failedStepDetails = new List<OperationStepResult>();
var totalSteps = steps.Count;
- var stack = new Stack<RevertStepEntry>(steps);
- while (stack.Count > 0)
+ // Revert steps in reverse order (LIFO) for correct undo semantics
+ for (var i = steps.Count - 1; i >= 0; i--)
{
- var (currentIndex, step) = stack.Pop();
+ var (currentIndex, step) = steps[i];
progress?.Report(new ProcessingProgress
{
@@ -154,7 +125,6 @@ public class RevertManager(ILogger<RevertManager> logger)
var success = false;
Exception? lastError = null;
- // Retry loop: attempt up to maxRetries + 1 times total
for (var attempt = 0; attempt <= maxRetries; attempt++)
{
try
@@ -171,7 +141,7 @@ public class RevertManager(ILogger<RevertManager> logger)
{
logger.LogWarning("Revert step {Index} ({Type}) failed on attempt {Attempt}, retrying...",
currentIndex, step.Type, attempt + 1);
- await Task.Delay(200 * (attempt + 1)); // progressive delay
+ await Task.Delay(200 * (attempt + 1));
}
}
@@ -196,7 +166,6 @@ public class RevertManager(ILogger<RevertManager> logger)
var allFailed = failedCount == totalSteps;
var hasFailures = failedCount > 0;
- // Partial revert: save remaining failed steps back to file for later retry
if (hasFailures && !allFailed)
{
await SaveFailedStepsAsync(optimizationId, optimizationKey, steps, failedStepDetails);
@@ -205,7 +174,7 @@ public class RevertManager(ILogger<RevertManager> logger)
}
else if (!hasFailures)
{
- await RemoveAsync(optimizationId, optimizationKey);
+ Remove(optimizationId, optimizationKey);
}
return new RevertResult
@@ -232,9 +201,6 @@ public class RevertManager(ILogger<RevertManager> logger)
}
}
- /// <summary>
- /// Saves only the failed steps back to the revert file so a subsequent revert can retry them.
- /// </summary>
private async Task SaveFailedStepsAsync(Guid optimizationId, string optimizationName,
List<RevertStepEntry> allSteps, List<OperationStepResult> failedDetails)
{
@@ -277,7 +243,6 @@ public class RevertManager(ILogger<RevertManager> logger)
}
catch
{
- // Best-effort cleanup only.
}
logger.LogError(ex, "Failed to save remaining failed steps for {Name}", optimizationName);
@@ -327,7 +292,6 @@ public class RevertManager(ILogger<RevertManager> logger)
public static Task<bool> IsAppliedAsync(Guid optimizationId)
{
- // Revert data file existence is the source of truth.
var filePath = Path.Combine(Shared.RevertDirectory, optimizationId + ".json");
return Task.FromResult(File.Exists(filePath));
}
@@ -352,7 +316,7 @@ public class RevertManager(ILogger<RevertManager> logger)
}
}
- private Task RemoveAsync(Guid optimizationId, string optimizationName)
+ private void Remove(Guid optimizationId, string optimizationName)
{
try
{
@@ -367,16 +331,8 @@ public class RevertManager(ILogger<RevertManager> logger)
{
logger.LogError(ex, "Failed to remove revert data for {Id}", optimizationId);
}
-
- return Task.CompletedTask;
}
- #region Auto-Discovery
-
- /// <summary>
- /// Builds the step registry by scanning all IRevertStep implementations via reflection.
- /// Each step type must have a static FromData(JObject) method.
- /// </summary>
private static Dictionary<string, Func<JObject, IRevertStep>> BuildStepRegistry()
{
var registry = new Dictionary<string, Func<JObject, IRevertStep>>(StringComparer.OrdinalIgnoreCase);
@@ -392,18 +348,15 @@ public class RevertManager(ILogger<RevertManager> logger)
{
try
{
- // Create a temporary instance to get the Type property value
var instance = (IRevertStep)Activator.CreateInstance(type)!;
var typeKey = instance.Type;
- // Find the static FromData method (accepts JObject or JToken)
var fromDataMethod = type.GetMethod("FromData",
BindingFlags.Static | BindingFlags.Public,
null,
[typeof(JObject)],
null);
- // Fallback: try JToken parameter
fromDataMethod ??= type.GetMethod("FromData",
BindingFlags.Static | BindingFlags.Public,
null,
@@ -416,24 +369,16 @@ public class RevertManager(ILogger<RevertManager> logger)
}
catch
{
- // Skip types that can't be instantiated or lack FromData
}
}
}
catch
{
- // Fallback: if reflection fails entirely, the registry remains empty
- // and DeserializeStep will return null for all types.
}
return registry;
}
- /// <summary>
- /// Returns the list of registered revert step type names.
- /// </summary>
- public static IReadOnlyCollection<string> RegisteredStepTypes => _stepRegistry.Keys.ToList().AsReadOnly();
-
private IRevertStep? DeserializeStep(string serviceType, JToken data)
{
try
@@ -462,10 +407,6 @@ public class RevertManager(ILogger<RevertManager> logger)
}
}
- #endregion Auto-Discovery
-
- #region Validation
-
private async Task<RevertValidationResult> ValidateAsync(Guid optimizationId)
{
var filePath = Path.Combine(Shared.RevertDirectory, optimizationId + ".json");
@@ -534,14 +475,7 @@ public class RevertManager(ILogger<RevertManager> logger)
return RevertValidationResult.Success();
}
- #endregion Validation
-
- internal static void ClearCurrent()
- {
- _current.Value = null;
- }
-
- public static void ClearAllRevertDataAsync()
+ public static void ClearAllRevertData()
{
if (!Directory.Exists(Shared.RevertDirectory))
return;
@@ -553,9 +487,8 @@ public class RevertManager(ILogger<RevertManager> logger)
}
catch
{
- // Best-effort cleanup only.
}
}
private sealed record RevertStepEntry(int Index, IRevertStep Step);
-}
\ No newline at end of file
+}
diff --git a/optimizerDuck/Services/OptimizationService.cs b/optimizerDuck/Services/OptimizationService.cs
index e27e8e3..4d618ba 100644
--- a/optimizerDuck/Services/OptimizationService.cs
+++ b/optimizerDuck/Services/OptimizationService.cs
@@ -3,6 +3,7 @@ using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Core.Interfaces;
+using optimizerDuck.Core.Models.Execution;
using optimizerDuck.Core.Models.Optimization;
using optimizerDuck.Core.Models.Optimization.Services;
using optimizerDuck.Core.Models.Revert;
@@ -17,9 +18,6 @@ using Wpf.Ui.Controls;
namespace optimizerDuck.Services;
-/// <summary>
-/// Provides services for applying and reverting optimizations.
-/// </summary>
public class OptimizationService(
RevertManager revertManager,
ILoggerFactory loggerFactory,
@@ -32,18 +30,8 @@ public class OptimizationService(
private static readonly object _cacheLock = new();
private readonly ILogger _logger = logger;
- /// <summary>
- /// Indicates whether a system restore point was requested before applying optimizations.
- /// </summary>
public bool WasRequestedRestorePoint { get; set; } = false;
- /// <summary>
- /// Creates a Windows system restore point.
- /// </summary>
- /// <returns>
- /// A task that completes with a <see cref="RestorePointResult" /> indicating success,
- /// failure, or if the frequency limit was reached.
- /// </returns>
public async Task<RestorePointResult> CreateRestorePointAsync()
{
var dialogViewModel = new ProcessingViewModel();
@@ -71,12 +59,11 @@ public class OptimizationService(
IsIndeterminate = true
});
- using var tracker = ServiceTracker.Begin(_logger);
+ using var scope = ExecutionScope.Begin(_logger);
var result = await RunPowerShellAsync(
$"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS");
- // it gives stderr but exitcode is 0
if (result.Stderr.Contains("already been created within the past 1440 minutes",
StringComparison.OrdinalIgnoreCase))
{
@@ -103,7 +90,6 @@ public class OptimizationService(
IsIndeterminate = true
});
- // try to enable it
_logger.LogInformation("Enabling System Protection on system drive...");
var enableResult = await RunPowerShellAsync("Enable-ComputerRestore -Drive \"$env:SystemDrive\"");
if (enableResult.ExitCode != 0)
@@ -118,7 +104,6 @@ public class OptimizationService(
IsIndeterminate = true
});
- // retry creating restore point
_logger.LogInformation("Retrying to create restore point...");
result = await RunPowerShellAsync(
$"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS");
@@ -150,28 +135,18 @@ public class OptimizationService(
#region Main Methods
- /// <summary>
- /// Applies an optimization to the system.
- /// </summary>
- /// <param name="optimization">The optimization to apply.</param>
- /// <param name="progress">A progress reporter for UI updates.</param>
- /// <returns>A task that completes with the optimization result.</returns>
public async Task<OptimizationResult> ApplyAsync(IOptimization optimization,
IProgress<ProcessingProgress> progress)
{
var optimizationLogger = loggerFactory.CreateLogger(optimization.GetType());
- OptimizationResult result;
- List<OperationStepResult> stepResults = [];
- var tracker = ServiceTracker.Begin(optimizationLogger);
+ using var executionScope = ExecutionScope.Begin(optimization.Id, optimization.OptimizationKey,
+ optimizationLogger);
- RevertContext? revertContext = null;
- var revertContextDisposed = false;
+ OptimizationResult result;
try
{
- revertContext = revertManager.BeginRecording(optimization);
-
progress.Report(new ProcessingProgress
{
Message = Translations.Optimization_Apply_Processing,
@@ -187,33 +162,23 @@ public class OptimizationService(
StreamService = streamService
}));
- if (!string.IsNullOrWhiteSpace(applyResult.Message)) // Optimization failed
+ if (!string.IsNullOrWhiteSpace(applyResult.Message))
{
- // Retry to recover from failed steps
- stepResults = tracker.GetSteps().ToList();
- var failedApplySteps = stepResults.Where(s => !s.Success).ToList();
-
- // Persist revert steps first, then attempt an immediate revert.
- await revertContext.DisposeAsync();
- revertContextDisposed = true;
-
- var revertResult = await revertManager.RevertAsync(
- optimization.Id,
- optimization.OptimizationKey,
- progress);
-
- // If revert succeeds, remove any cached applied state.
- if (revertResult.Success)
- lock (_cacheLock)
- {
- _stateCache.Remove(optimization.Id);
- }
+ var failedSteps = executionScope.FailedSteps;
return new OptimizationResult
{
Status = OptimizationSuccessResult.Failed,
Message = applyResult.Message,
- FailedSteps = failedApplySteps
+ FailedSteps = failedSteps.Select(step => new OperationStepResult
+ {
+ Index = step.Index,
+ Name = step.Name,
+ Description = step.Description,
+ Success = step.Success,
+ Error = step.Error,
+ RetryAction = step.RetryAction
+ }).ToList()
};
}
@@ -225,96 +190,88 @@ public class OptimizationService(
Total = 1
});
- // Collect steps after apply completes.
- stepResults = tracker.GetSteps().ToList();
- var failedSteps = stepResults.Where(s => !s.Success).ToList();
-
- var status = ResolveStatus(stepResults, failedSteps);
- result = new OptimizationResult
- {
- Status = status,
- Message = status == OptimizationSuccessResult.Success
- ? string.Format(Translations.Optimization_Apply_Success, optimization.OptimizationKey)
- : stepResults.Count == failedSteps.Count // if all steps failed
- ? string.Format(Translations.Optimization_Apply_Error_Failed, optimization.OptimizationKey)
- : string.Format(Translations.Optimization_Apply_Error_FailedWithSteps,
- optimization.OptimizationKey,
- failedSteps.Count),
- FailedSteps = failedSteps
- };
+ result = executionScope.ToResult();
- // Update cache after successful apply
- if (status == OptimizationSuccessResult.Success)
+ if (result.Status == OptimizationSuccessResult.Success)
lock (_cacheLock)
{
_stateCache[optimization.Id] = (true, DateTime.Now);
}
- if (!revertContextDisposed)
- await revertContext.DisposeAsync();
+ if (executionScope.HasSuccessfulSteps)
+ {
+ try
+ {
+ await revertManager.SaveRevertDataAsync(executionScope);
+ }
+ catch (Exception saveEx)
+ {
+ _logger.LogError(saveEx, "Failed to save revert data for {Name}, but optimization was applied",
+ optimization.OptimizationKey);
+ }
+ }
}
catch (Exception ex)
{
- stepResults = tracker?.GetSteps().ToList() ?? [];
- var failedSteps = stepResults.Where(s => !s.Success).ToList();
-
- var status = ResolveStatus(stepResults, failedSteps);
+ var failedStepResults = executionScope.FailedSteps.Select(step => new OperationStepResult
+ {
+ Index = step.Index,
+ Name = step.Name,
+ Description = step.Description,
+ Success = step.Success,
+ Error = step.Error,
+ RetryAction = step.RetryAction
+ }).ToList();
+
+ var status = GetStatus(executionScope);
result = new OptimizationResult
{
Status = status,
Message = string.Format(Translations.Optimization_Apply_Error_Failed,
optimization.OptimizationKey),
Exception = ex,
- FailedSteps = failedSteps
+ FailedSteps = failedStepResults
};
- // Best-effort: persist any revert steps that were recorded before the exception.
- if (revertContext is not null && !revertContextDisposed)
+ if (executionScope.HasSuccessfulSteps)
+ {
try
{
- await revertContext.DisposeAsync();
- revertContextDisposed = true;
+ await revertManager.SaveRevertDataAsync(executionScope);
+ _logger.LogWarning("Saved revert data for {Name} despite exception", optimization.OptimizationKey);
}
catch (Exception saveEx)
{
- _logger.LogError(saveEx, "Failed to save revert data after exception for {Name}",
+ _logger.LogError(saveEx, "Critical: Failed to save revert data after exception for {Name}",
optimization.OptimizationKey);
}
- }
- finally
- {
- tracker?.Dispose();
+ }
}
return result;
- OptimizationSuccessResult ResolveStatus(
- IReadOnlyCollection<OperationStepResult> steps,
- IReadOnlyCollection<OperationStepResult> failedSteps)
+ OptimizationSuccessResult GetStatus(Core.Models.Execution.ExecutionScope scope)
{
- if (steps.Count == 0)
+ if (scope.ExecutedSteps.Count == 0)
return OptimizationSuccessResult.Failed;
- if (failedSteps.Count == 0)
- return OptimizationSuccessResult.Success;
+ var failed = scope.FailedSteps.Count;
+ var total = scope.ExecutedSteps.Count;
- return failedSteps.Count < steps.Count
- ? OptimizationSuccessResult.PartialSuccess
- : OptimizationSuccessResult.Failed;
+ return failed switch
+ {
+ 0 => OptimizationSuccessResult.Success,
+ _ when failed < total => OptimizationSuccessResult.PartialSuccess,
+ _ => OptimizationSuccessResult.Failed
+ };
}
}
- /// <summary>
- /// Reverts a previously applied optimization.
- /// </summary>
- /// <param name="optimization">The optimization to revert.</param>
- /// <param name="progress">A progress reporter for UI updates (optional).</param>
- /// <returns>A task that completes with the revert result.</returns>
public async Task<RevertResult> RevertAsync(IOptimization optimization,
IProgress<ProcessingProgress>? progress = null)
{
var optimizationLogger = loggerFactory.CreateLogger(optimization.GetType());
- using var tracker = ServiceTracker.Begin(optimizationLogger);
+ using var scope = ExecutionScope.Begin(optimizationLogger);
progress?.Report(new ProcessingProgress
{
@@ -327,10 +284,9 @@ public class OptimizationService(
optimization.OptimizationKey,
progress);
- // Merge tracker steps with revert result details
- var trackerSteps = tracker.GetSteps().ToList();
- if (result.FailedStepDetails.Count == 0 && trackerSteps.Any(s => !s.Success))
- result.FailedStepDetails = trackerSteps.Where(s => !s.Success).ToList();
+ var scopeSteps = scope.GetStepResults();
+ if (result.FailedStepDetails.Count == 0 && scopeSteps.Any(s => !s.Success))
+ result.FailedStepDetails = scopeSteps.Where(s => !s.Success).ToList();
progress?.Report(new ProcessingProgress
{
@@ -340,7 +296,6 @@ public class OptimizationService(
Total = 1
});
- // Update cache after revert
if (result.Success)
lock (_cacheLock)
{
@@ -354,20 +309,11 @@ public class OptimizationService(
#region Helpers
- /// <summary>
- /// Checks whether an optimization has been applied.
- /// </summary>
- /// <param name="optimizationId">The unique identifier of the optimization.</param>
- /// <returns>True if the optimization was applied; otherwise, false.</returns>
public static Task<bool> IsAppliedAsync(Guid optimizationId)
{
return RevertManager.IsAppliedAsync(optimizationId);
}
- /// <summary>
- /// Updates the applied state for a collection of optimizations.
- /// </summary>
- /// <param name="optimizations">The optimizations to update.</param>
public static async Task UpdateOptimizationStateAsync(params IOptimization[] optimizations)
{
var optimizationIds = optimizations.Select(o => o.Id).ToArray();
@@ -378,7 +324,6 @@ public class OptimizationService(
foreach (var optimization in optimizations)
if (_stateCache.TryGetValue(optimization.Id, out var cachedState))
{
- // Use cached state
optimization.State.IsApplied = cachedState.IsApplied;
optimization.State.AppliedAt = cachedState.AppliedAt;
}
@@ -388,7 +333,6 @@ public class OptimizationService(
}
}
- // Only fetch from disk for uncached optimizations
if (uncachedIds.Count > 0)
{
var tasks = uncachedIds.Select(async id =>
@@ -406,7 +350,6 @@ public class OptimizationService(
var results = await Task.WhenAll(tasks);
- // Update optimizations with fetched data
foreach (var optimization in optimizations)
{
var result = results.FirstOrDefault(r => r.Id == optimization.Id);
@@ -419,23 +362,11 @@ public class OptimizationService(
}
}
- /// <summary>
- /// Updates the applied state for a collection of optimizations.
- /// </summary>
- /// <param name="optimizations">The optimizations to update.</param>
public static async Task UpdateOptimizationStateAsync(IEnumerable<IOptimization> optimizations)
{
await UpdateOptimizationStateAsync(optimizations.ToArray());
}
- /// <summary>
- /// Retries failed optimization steps with configurable max retry attempts.
- /// </summary>
- /// <param name="failedSteps">The steps that previously failed.</param>
- /// <param name="reverseOrder">Whether to execute steps in reverse order.</param>
- /// <param name="progress">A progress reporter for UI updates (optional).</param>
- /// <param name="maxRetries">Maximum number of retry attempts per step (default 3).</param>
- /// <returns>A list of steps that still failed after retry.</returns>
public static async Task<List<OperationStepResult>> RetryFailedStepsAsync(
IReadOnlyList<OperationStepResult> failedSteps,
bool reverseOrder,
@@ -490,11 +421,10 @@ public class OptimizationService(
}
catch
{
- // Retry on next attempt
}
if (attempt < maxRetries - 1)
- await Task.Delay(200 * (attempt + 1)); // progressive delay
+ await Task.Delay(200 * (attempt + 1));
}
if (!success)
@@ -504,7 +434,7 @@ public class OptimizationService(
return stillFailed;
}
- public static void ClearResourcesAsync()
+ public static void ClearResources()
{
lock (_cacheLock)
{
@@ -521,7 +451,6 @@ public class OptimizationService(
}
catch
{
- // Best-effort cleanup only.
}
}
diff --git a/optimizerDuck/Services/OptimizationServices/RegistryService.cs b/optimizerDuck/Services/OptimizationServices/RegistryService.cs
index 0190ee8..b09f433 100644
--- a/optimizerDuck/Services/OptimizationServices/RegistryService.cs
+++ b/optimizerDuck/Services/OptimizationServices/RegistryService.cs
@@ -3,10 +3,10 @@ using System.Globalization;
using System.IO;
using System.Security;
using Microsoft.Win32;
+using optimizerDuck.Core.Models.Execution;
using optimizerDuck.Core.Models.Optimization.Services;
using optimizerDuck.Core.Models.Revert.Steps;
using optimizerDuck.Resources.Languages;
-using optimizerDuck.Services.Managers;
namespace optimizerDuck.Services.OptimizationServices;
@@ -42,8 +42,8 @@ public static class RegistryService
if (string.IsNullOrWhiteSpace(fullPath))
{
- ServiceTracker.LogError(null, "Registry path is null or empty");
- ServiceTracker.Track(nameof(RegistryService), false);
+ ExecutionScope.LogError(null, "Registry path is null or empty");
+ ExecutionScope.Track(nameof(RegistryService), false);
return false;
}
@@ -53,8 +53,8 @@ public static class RegistryService
if (!RootKeysMap.TryGetValue(rootToken, out rootKey))
{
- ServiceTracker.LogError(null, "Unknown root key: {RootToken}", rootToken);
- ServiceTracker.Track(nameof(RegistryService), false);
+ ExecutionScope.LogError(null, "Unknown root key: {RootToken}", rootToken);
+ ExecutionScope.Track(nameof(RegistryService), false);
return false;
}
@@ -168,17 +168,17 @@ public static class RegistryService
var result = ConvertRegistryValue<T>(value);
- ServiceTracker.LogInfo("Read registry {Path}:{Name} = {Value}",
+ ExecutionScope.LogInfo("Read registry {Path}:{Name} = {Value}",
item.Path, item.Name!, result?.ToString() ?? "<null>");
return result;
}
catch (Exception ex)
{
- ServiceTracker.LogError(ex, "Failed to read registry {Path}:{Name}",
+ ExecutionScope.LogError(ex, "Failed to read registry {Path}:{Name}",
item.Path, item.Name!);
- ServiceTracker.LogInfo("Read registry {Path}:{Name} = <default> (raw={RawType})",
+ ExecutionScope.LogInfo("Read registry {Path}:{Name} = <default> (raw={RawType})",
item.Path, item.Name!, value?.GetType().FullName ?? "<null>");
return default;
@@ -190,9 +190,9 @@ public static class RegistryService
{
if (item.Value == null)
{
- ServiceTracker.LogError(null, "Value can't be null when writing {Path}:{Name}",
+ ExecutionScope.LogError(null, "Value can't be null when writing {Path}:{Name}",
item.Path, item.Name!);
- ServiceTracker.Track(nameof(Write), false);
+ ExecutionScope.Track(nameof(Write), false);
return false;
}
@@ -237,8 +237,8 @@ public static class RegistryService
key.SetValue(item.Name, item.Value, item.Kind);
- if (valueExists)
- RevertManager.Record(new RegistryRevertStep
+ var revertStep = valueExists
+ ? new RegistryRevertStep
{
Action = RevertAction.RestorePrevious,
Path = item.Path,
@@ -246,51 +246,38 @@ public static class RegistryService
Value = backupValue,
Kind = backupKind ?? RegistryValueKind.Unknown,
CreatedSubKeys = createdSubKeys
- });
- else
- RevertManager.Record(new RegistryRevertStep
+ }
+ : new RegistryRevertStep
{
Action = RevertAction.NoPreviousValue,
Path = item.Path,
Name = item.Name,
CreatedSubKeys = createdSubKeys
- });
+ };
- ServiceTracker.LogInfo("Wrote {Path}:{Name}[{Kind}] = {Value}",
+ ExecutionScope.LogInfo("Wrote {Path}:{Name}[{Kind}] = {Value}",
item.Path, item.Name!, item.Kind, item.Value);
- ServiceTracker.Track(nameof(Write), true);
- ServiceTracker.TrackStep(
- "Registry",
- description,
- true,
- null,
- () => Task.Run(() => Write(item)));
+ ExecutionScope.Track(nameof(Write), true);
+ ExecutionScope.RecordStep("Registry", description, true, revertStep, null);
return true;
}
catch (UnauthorizedAccessException)
{
- ServiceTracker.LogError(null, "Access denied writing {Path}:{Name}",
+ ExecutionScope.LogError(null, "Access denied writing {Path}:{Name}",
item.Path, item.Name!);
- ServiceTracker.Track(nameof(Write), false);
- ServiceTracker.TrackStep(
- "Registry",
- description,
- false,
+ ExecutionScope.Track(nameof(Write), false);
+ ExecutionScope.RecordStep("Registry", description, false, null,
Translations.Service_Common_Error_AccessDenied,
- () => Task.Run(() => Write(item)));
+ retryAction: () => Task.FromResult(Write(item)));
return false;
}
catch (Exception ex)
{
- ServiceTracker.LogError(ex, "Failed to write registry {Path}:{Name}",
+ ExecutionScope.LogError(ex, "Failed to write registry {Path}:{Name}",
item.Path, item.Name!);
- ServiceTracker.Track(nameof(Write), false);
- ServiceTracker.TrackStep(
- "Registry",
- description,
- false,
- ex.Message,
- () => Task.Run(() => Write(item)));
+ ExecutionScope.Track(nameof(Write), false);
+ ExecutionScope.RecordStep("Registry", description, false, null, ex.Message,
+ retryAction: () => Task.FromResult(Write(item)));
return false;
}
}, true, true, createdSubKeys);
@@ -317,15 +304,10 @@ public static class RegistryService
if (key == null)
{
// Missing subkey means there's nothing to delete; treat as success for revert.
- ServiceTracker.LogInfo("Skip delete registry {Path}:{Name} (subkey missing)",
+ ExecutionScope.LogInfo("Skip delete registry {Path}:{Name} (subkey missing)",
item.Path, item.Name!);
- ServiceTracker.Track(nameof(DeleteValue), true);
- ServiceTracker.TrackStep(
- "Registry",
- description,
- true,
- null,
- () => Task.Run(() => DeleteValue(item)));
+ ExecutionScope.Track(nameof(DeleteValue), true);
+ ExecutionScope.RecordStep("Registry", description, true, null, null);
return true;
}
@@ -335,13 +317,8 @@ public static class RegistryService
// Key does not exist, treat as success for revert
if (key.GetValue(item.Name) == null)
{
- ServiceTracker.Track(nameof(DeleteValue), true);
- ServiceTracker.TrackStep(
- "Registry",
- description,
- true,
- null,
- () => Task.Run(() => DeleteValue(item)));
+ ExecutionScope.Track(nameof(DeleteValue), true);
+ ExecutionScope.RecordStep("Registry", description, true, null, null);
return true;
}
@@ -351,49 +328,37 @@ public static class RegistryService
key.DeleteValue(item.Name!, false);
// Record revert: key existed before deletion
- RevertManager.Record(new RegistryRevertStep
+ var revertStep = new RegistryRevertStep
{
Action = RevertAction.RestorePrevious,
Path = item.Path,
Name = item.Name,
Value = backupValue,
Kind = backupKind
- });
-
- ServiceTracker.LogInfo("Deleted registry {Path}:{Name}", item.Path, item.Name!);
- ServiceTracker.Track(nameof(DeleteValue), true);
- ServiceTracker.TrackStep(
- "Registry",
- description,
- true,
- null,
- () => Task.Run(() => DeleteValue(item)));
+ };
+
+ ExecutionScope.LogInfo("Deleted registry {Path}:{Name}", item.Path, item.Name!);
+ ExecutionScope.Track(nameof(DeleteValue), true);
+ ExecutionScope.RecordStep("Registry", description, true, revertStep, null);
return true;
}
catch (UnauthorizedAccessException)
{
- ServiceTracker.LogError(null, "Access denied deleting {Path}:{Name}",
+ ExecutionScope.LogError(null, "Access denied deleting {Path}:{Name}",
item.Path, item.Name!);
- ServiceTracker.Track(nameof(DeleteValue), false);
- ServiceTracker.TrackStep(
- "Registry",
- $"{item.Path}:{item.Name}",
- false,
+ ExecutionScope.Track(nameof(DeleteValue), false);
+ ExecutionScope.RecordStep("Registry", $"{item.Path}:{item.Name}", false, null,
Translations.Service_Common_Error_AccessDenied,
- () => Task.Run(() => DeleteValue(item)));
+ retryAction: () => Task.FromResult(DeleteValue(item)));
return false;
}
catch (Exception ex)
{
- ServiceTracker.LogError(ex, "Failed to delete registry {Path}:{Name}",
+ ExecutionScope.LogError(ex, "Failed to delete registry {Path}:{Name}",
item.Path, item.Name!);
- ServiceTracker.Track(nameof(DeleteValue), false);
- ServiceTracker.TrackStep(
- "Registry",
- $"{item.Path}:{item.Name}",
- false,
- ex.Message,
- () => Task.Run(() => DeleteValue(item)));
+ ExecutionScope.Track(nameof(DeleteValue), false);
+ ExecutionScope.RecordStep("Registry", $"{item.Path}:{item.Name}", false, null, ex.Message,
+ retryAction: () => Task.FromResult(DeleteValue(item)));
return false;
}
finally
@@ -467,20 +432,15 @@ public static class RegistryService
? root.Name
: $"{root.Name}\\{subPath}";
- ServiceTracker.LogError(
+ ExecutionScope.LogError(
ex,
"{Reason}: {Path}",
logReason,
path);
- ServiceTracker.Track(nameof(RegistryService), false);
+ ExecutionScope.Track(nameof(RegistryService), false);
- ServiceTracker.TrackStep(
- "Registry",
- path,
- false,
- uiReason,
- () => Task.FromResult(false));
+ ExecutionScope.RecordStep("Registry", path, false, null, uiReason);
}
/// <summary>
@@ -513,7 +473,7 @@ public static class RegistryService
$"Failed to create registry key: {root.Name}\\{currentPath}");
createdSubKeys.Add($"{root.Name}\\{currentPath}");
- ServiceTracker.LogDebug(
+ ExecutionScope.LogDebug(
"Created registry subkey: {Path}",
$"{root.Name}\\{currentPath}");
}
@@ -584,27 +544,27 @@ public static class RegistryService
parent?.DeleteSubKey(keyName, false);
}
- ServiceTracker.LogInfo("Cleaned up empty registry key {Path}", fullPath);
+ ExecutionScope.LogInfo("Cleaned up empty registry key {Path}", fullPath);
}
else
{
// Key is not empty, don't delete it
- ServiceTracker.LogDebug(
+ ExecutionScope.LogDebug(
"Skipped cleanup of registry key {Path} (has {SubKeyCount} subkeys and {ValueCount} values)",
fullPath, key.SubKeyCount, key.ValueCount);
}
}
catch (UnauthorizedAccessException)
{
- ServiceTracker.LogWarning("Access denied cleaning up registry key: {Path}", fullPath);
+ ExecutionScope.LogWarning("Access denied cleaning up registry key: {Path}", fullPath);
}
catch (IOException ex)
{
- ServiceTracker.LogError(ex, "I/O error cleaning up registry key: {Path}", fullPath);
+ ExecutionScope.LogError(ex, "I/O error cleaning up registry key: {Path}", fullPath);
}
catch (Exception ex)
{
- ServiceTracker.LogError(ex, "Failed to cleanup registry key: {Path}", fullPath);
+ ExecutionScope.LogError(ex, "Failed to cleanup registry key: {Path}", fullPath);
}
}
diff --git a/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs b/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs
index e6b5c89..1535f16 100644
--- a/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs
+++ b/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs
@@ -1,9 +1,9 @@
using System.Collections.ObjectModel;
using Microsoft.Win32.TaskScheduler;
+using optimizerDuck.Core.Models.Execution;
using optimizerDuck.Core.Models.Revert.Steps;
using optimizerDuck.Core.Models.ScheduledTask;
using optimizerDuck.Resources.Languages;
-using optimizerDuck.Services.Managers;
using Task = Microsoft.Win32.TaskScheduler.Task;
namespace optimizerDuck.Services.OptimizationServices;
@@ -23,7 +23,7 @@ public static class ScheduledTaskService
}
catch (Exception ex)
{
- ServiceTracker.LogDebug("Failed to check task enabled state {Path}: {Error}", fullPath, ex.Message);
+ ExecutionScope.LogDebug("Failed to check task enabled state {Path}: {Error}", fullPath, ex.Message);
return false;
}
}
@@ -45,45 +45,48 @@ public static class ScheduledTaskService
task.Enabled = false;
// Record revert step: restore to previous enabled state
+ ScheduledTaskRevertStep? revertStep = null;
if (wasEnabled)
- RevertManager.Record(new ScheduledTaskRevertStep
+ revertStep = new ScheduledTaskRevertStep
{
FullPath = fullPath,
OriginalEnabled = true
- });
+ };
- ServiceTracker.LogInfo("Disabled task {Path}", fullPath);
- ServiceTracker.Track(nameof(DisableTask), true);
- ServiceTracker.TrackStep(
+ ExecutionScope.LogInfo("Disabled task {Path}", fullPath);
+ ExecutionScope.Track(nameof(DisableTask), true);
+ ExecutionScope.RecordStep(
"ScheduledTask",
description,
true,
- null,
- () => System.Threading.Tasks.Task.Run(() => DisableTask(fullPath)));
+ revertStep,
+ null);
return true;
}
catch (UnauthorizedAccessException)
{
- ServiceTracker.LogError(null, "Access denied disabling task {Path}", fullPath);
- ServiceTracker.Track(nameof(DisableTask), false);
- ServiceTracker.TrackStep(
+ ExecutionScope.LogError(null, "Access denied disabling task {Path}", fullPath);
+ ExecutionScope.Track(nameof(DisableTask), false);
+ ExecutionScope.RecordStep(
"ScheduledTask",
description,
false,
+ null,
Translations.Service_Common_Error_AccessDenied,
- () => System.Threading.Tasks.Task.Run(() => DisableTask(fullPath)));
+ retryAction: () => System.Threading.Tasks.Task.FromResult(DisableTask(fullPath)));
return false;
}
catch (Exception ex)
{
- ServiceTracker.LogError(ex, "Failed to disable task {Path}", fullPath);
- ServiceTracker.Track(nameof(DisableTask), false);
- ServiceTracker.TrackStep(
+ ExecutionScope.LogError(ex, "Failed to disable task {Path}", fullPath);
+ ExecutionScope.Track(nameof(DisableTask), false);
+ ExecutionScope.RecordStep(
"ScheduledTask",
description,
false,
+ null,
ex.Message,
- () => System.Threading.Tasks.Task.Run(() => DisableTask(fullPath)));
+ retryAction: () => System.Threading.Tasks.Task.FromResult(DisableTask(fullPath)));
return false;
}
}
@@ -105,45 +108,48 @@ public static class ScheduledTaskService
task.Enabled = true;
// Record revert step: restore to previous enabled state
+ ScheduledTaskRevertStep? revertStep = null;
if (!wasEnabled)
- RevertManager.Record(new ScheduledTaskRevertStep
+ revertStep = new ScheduledTaskRevertStep
{
FullPath = fullPath,
OriginalEnabled = false
- });
+ };
- ServiceTracker.LogInfo("Enabled task {Path}", fullPath);
- ServiceTracker.Track(nameof(EnableTask), true);
- ServiceTracker.TrackStep(
+ ExecutionScope.LogInfo("Enabled task {Path}", fullPath);
+ ExecutionScope.Track(nameof(EnableTask), true);
+ ExecutionScope.RecordStep(
"ScheduledTask",
description,
true,
- null,
- () => System.Threading.Tasks.Task.Run(() => EnableTask(fullPath)));
+ revertStep,
+ null);
return true;
}
catch (UnauthorizedAccessException)
{
- ServiceTracker.LogError(null, "Access denied enabling task {Path}", fullPath);
- ServiceTracker.Track(nameof(EnableTask), false);
- ServiceTracker.TrackStep(
+ ExecutionScope.LogError(null, "Access denied enabling task {Path}", fullPath);
+ ExecutionScope.Track(nameof(EnableTask), false);
+ ExecutionScope.RecordStep(
"ScheduledTask",
description,
false,
+ null,
Translations.Service_Common_Error_AccessDenied,
- () => System.Threading.Tasks.Task.Run(() => EnableTask(fullPath)));
+ retryAction: () => System.Threading.Tasks.Task.FromResult(EnableTask(fullPath)));
return false;
}
catch (Exception ex)
{
- ServiceTracker.LogError(ex, "Failed to enable task {Path}", fullPath);
- ServiceTracker.Track(nameof(EnableTask), false);
- ServiceTracker.TrackStep(
+ ExecutionScope.LogError(ex, "Failed to enable task {Path}", fullPath);
+ ExecutionScope.Track(nameof(EnableTask), false);
+ ExecutionScope.RecordStep(
"ScheduledTask",
description,
false,
+ null,
ex.Message,
- () => System.Threading.Tasks.Task.Run(() => EnableTask(fullPath)));
+ retryAction: () => System.Threading.Tasks.Task.FromResult(EnableTask(fullPath)));
return false;
}
}
@@ -169,7 +175,7 @@ public static class ScheduledTaskService
}
catch (Exception ex)
{
- ServiceTracker.LogError(ex, "Failed to enumerate scheduled tasks");
+ ExecutionScope.LogError(ex, "Failed to enumerate scheduled tasks");
}
return results;
@@ -194,11 +200,11 @@ public static class ScheduledTaskService
var task = ts.GetTask(fullPath) ?? throw new InvalidOperationException(
string.Format(Translations.ScheduledTasks_Error_TaskNotFound, fullPath));
task.Run();
- ServiceTracker.LogInfo("Started task {Path}", fullPath);
+ ExecutionScope.LogInfo("Started task {Path}", fullPath);
}
catch (Exception ex)
{
- ServiceTracker.LogError(ex, "Failed to run task {Path}", fullPath);
+ ExecutionScope.LogError(ex, "Failed to run task {Path}", fullPath);
throw;
}
}
@@ -211,11 +217,11 @@ public static class ScheduledTaskService
var task = ts.GetTask(fullPath) ?? throw new InvalidOperationException(
string.Format(Translations.ScheduledTasks_Error_TaskNotFound, fullPath));
task.Stop();
- ServiceTracker.LogInfo("Stopped task {Path}", fullPath);
+ ExecutionScope.LogInfo("Stopped task {Path}", fullPath);
}
catch (Exception ex)
{
- ServiceTracker.LogError(ex, "Failed to stop task {Path}", fullPath);
+ ExecutionScope.LogError(ex, "Failed to stop task {Path}", fullPath);
throw;
}
}
@@ -233,7 +239,7 @@ public static class ScheduledTaskService
}
catch (Exception ex)
{
- ServiceTracker.LogDebug("Failed to get state for task {Path}: {Error}", fullPath, ex.Message);
+ ExecutionScope.LogDebug("Failed to get state for task {Path}: {Error}", fullPath, ex.Message);
return null;
}
}
@@ -247,11 +253,11 @@ public static class ScheduledTaskService
string.Format(Translations.ScheduledTasks_Error_TaskNotFound, fullPath));
var folderPath = task.Folder.Path;
ts.GetFolder(folderPath).DeleteTask(task.Name);
- ServiceTracker.LogInfo("Deleted task {Path}", fullPath);
+ ExecutionScope.LogInfo("Deleted task {Path}", fullPath);
}
catch (Exception ex)
{
- ServiceTracker.LogError(ex, "Failed to delete task {Path}", fullPath);
+ ExecutionScope.LogError(ex, "Failed to delete task {Path}", fullPath);
throw;
}
}
@@ -316,11 +322,11 @@ public static class ScheduledTaskService
}
folder.RegisterTaskDefinition(model.Name, td);
- ServiceTracker.LogInfo("Registered task {Name} in folder {Folder}", model.Name, folderPath);
+ ExecutionScope.LogInfo("Registered task {Name} in folder {Folder}", model.Name, folderPath);
}
catch (Exception ex)
{
- ServiceTracker.LogError(ex, "Failed to register task {Name} in {Folder}", model.Name, folderPath);
+ ExecutionScope.LogError(ex, "Failed to register task {Name} in {Folder}", model.Name, folderPath);
throw;
}
}
@@ -338,7 +344,7 @@ public static class ScheduledTaskService
}
catch (Exception ex)
{
- ServiceTracker.LogDebug("Failed to map task {Name}: {Error}", task.Name, ex.Message);
+ ExecutionScope.LogDebug("Failed to map task {Name}: {Error}", task.Name, ex.Message);
}
foreach (var subFolder in folder.SubFolders)
@@ -346,7 +352,7 @@ public static class ScheduledTaskService
}
catch (Exception ex)
{
- ServiceTracker.LogDebug("Failed to enumerate folder {Path}: {Error}", folder.Path, ex.Message);
+ ExecutionScope.LogDebug("Failed to enumerate folder {Path}: {Error}", folder.Path, ex.Message);
}
}
diff --git a/optimizerDuck/Services/OptimizationServices/ServiceProcessService.cs b/optimizerDuck/Services/OptimizationServices/ServiceProcessService.cs
index ef68848..3cbe2d9 100644
--- a/optimizerDuck/Services/OptimizationServices/ServiceProcessService.cs
+++ b/optimizerDuck/Services/OptimizationServices/ServiceProcessService.cs
@@ -1,10 +1,10 @@
using System.Diagnostics;
using System.Management;
using optimizerDuck.Common.Extensions;
+using optimizerDuck.Core.Models.Execution;
using optimizerDuck.Core.Models.Optimization.Services;
using optimizerDuck.Core.Models.Revert.Steps;
using optimizerDuck.Resources.Languages;
-using optimizerDuck.Services.Managers;
namespace optimizerDuck.Services.OptimizationServices;
@@ -39,7 +39,7 @@ public static class ServiceProcessService
}
catch (Exception ex)
{
- ServiceTracker.LogError(ex, "Failed to get startup type for {ServiceName}", serviceName);
+ ExecutionScope.LogError(ex, "Failed to get startup type for {ServiceName}", serviceName);
return null;
}
}
@@ -60,18 +60,19 @@ public static class ServiceProcessService
if (service == null)
{
- ServiceTracker.LogInfo(
+ ExecutionScope.LogInfo(
"[SERVICE][{Name}][FAIL][NOT_FOUND][D=0ms] startup -> {StartupType}",
item.Name,
item.StartupType
);
- ServiceTracker.Track(nameof(ChangeServiceStartupType), false);
- ServiceTracker.TrackStep(
+ ExecutionScope.Track(nameof(ChangeServiceStartupType), false);
+ ExecutionScope.RecordStep(
"Service",
description,
false,
+ null,
Translations.Service_Service_Error_NotFound,
- () => Task.Run(() => ChangeServiceStartupType(item)));
+ retryAction: () => Task.FromResult(ChangeServiceStartupType(item)));
return false;
}
@@ -94,12 +95,13 @@ public static class ServiceProcessService
if (resultCode == 0)
{
+ ServiceRevertStep? revertStep = null;
if (originalStartupType.HasValue && originalStartupType.Value != item.StartupType)
- RevertManager.Record(new ServiceRevertStep
+ revertStep = new ServiceRevertStep
{
ServiceName = item.Name,
OriginalStartupType = originalStartupType.Value
- });
+ };
// Handle delayed auto start registry key
var registrySuccess = item.StartupType == ServiceStartupType.AutomaticDelayedStart
@@ -113,24 +115,25 @@ public static class ServiceProcessService
sw.Stop();
- ServiceTracker.LogInfo(
+ ExecutionScope.LogInfo(
"[SERVICE][{Name}][OK][CODE=0][D={Duration}] startup -> {StartupType}",
item.Name,
sw.Elapsed.FormatTime(),
item.StartupType
);
- ServiceTracker.Track(nameof(ChangeServiceStartupType), registrySuccess);
- ServiceTracker.TrackStep(
+ ExecutionScope.Track(nameof(ChangeServiceStartupType), registrySuccess);
+ ExecutionScope.RecordStep(
"Service",
description,
registrySuccess,
+ registrySuccess ? revertStep : null,
registrySuccess ? null : Translations.Service_Service_Error_UpdateRegistryForStartupTypeFailed,
- () => Task.Run(() => ChangeServiceStartupType(item)));
+ retryAction: registrySuccess ? null : () => Task.FromResult(ChangeServiceStartupType(item)));
return registrySuccess;
}
- ServiceTracker.LogInfo(
+ ExecutionScope.LogInfo(
"[SERVICE][{Name}][FAIL][CODE={Code}][D={Duration}] startup -> {StartupType}",
item.Name,
resultCode,
@@ -138,30 +141,32 @@ public static class ServiceProcessService
item.StartupType
);
- ServiceTracker.Track(nameof(ChangeServiceStartupType), false);
- ServiceTracker.TrackStep(
+ ExecutionScope.Track(nameof(ChangeServiceStartupType), false);
+ ExecutionScope.RecordStep(
"Service",
description,
false,
+ null,
string.Format(Translations.Service_Service_Error_ChangeStartModeFailedWithCode, resultCode),
- () => Task.Run(() => ChangeServiceStartupType(item)));
+ retryAction: () => Task.FromResult(ChangeServiceStartupType(item)));
return false;
}
catch (Exception ex)
{
- ServiceTracker.LogError(
+ ExecutionScope.LogError(
ex,
"[SERVICE][{Name}][FAIL][EXCEPTION] startup -> {StartupType}",
item.Name,
item.StartupType
);
- ServiceTracker.Track(nameof(ChangeServiceStartupType), false);
- ServiceTracker.TrackStep(
+ ExecutionScope.Track(nameof(ChangeServiceStartupType), false);
+ ExecutionScope.RecordStep(
"Service",
description,
false,
+ null,
ex.Message,
- () => Task.Run(() => ChangeServiceStartupType(item)));
+ retryAction: () => Task.FromResult(ChangeServiceStartupType(item)));
return false;
}
}
diff --git a/optimizerDuck/Services/OptimizationServices/ShellService.cs b/optimizerDuck/Services/OptimizationServices/ShellService.cs
index 7b56cd8..7151e48 100644
--- a/optimizerDuck/Services/OptimizationServices/ShellService.cs
+++ b/optimizerDuck/Services/OptimizationServices/ShellService.cs
@@ -3,10 +3,10 @@ using System.Text;
using Microsoft.Extensions.Options;
using optimizerDuck.Common.Extensions;
using optimizerDuck.Core.Models.Config;
+using optimizerDuck.Core.Models.Execution;
using optimizerDuck.Core.Models.Optimization.Services;
using optimizerDuck.Core.Models.Revert.Steps;
using optimizerDuck.Resources.Languages;
-using optimizerDuck.Services.Managers;
namespace optimizerDuck.Services.OptimizationServices;
@@ -52,16 +52,9 @@ public static class ShellService
_options = options;
}
- private static ShellResult Run(
- string fileName,
- string arguments,
- string command,
- string serviceName,
- ShellRevertStep? revertStep,
- ShellPolicy? policy = null)
+ private static (string commandForUser, string fullCommandForUser) SanitizeCommandForUser(
+ string fileName, string arguments, string command)
{
- policy ??= ShellPolicy.Default;
-
var commandForUser = (arguments.Contains("-EncodedCommand", StringComparison.OrdinalIgnoreCase)
? command.DecodeBase64()
: command)
@@ -75,6 +68,21 @@ public static class ShellService
var fullCommandForUser =
$"{fileName} {arguments.Replace("-EncodedCommand", "-Command", StringComparison.OrdinalIgnoreCase)} {commandForUser}";
+ return (commandForUser, fullCommandForUser);
+ }
+
+ private static ShellResult Run(
+ string fileName,
+ string arguments,
+ string command,
+ string serviceName,
+ ShellRevertStep? revertStep,
+ ShellPolicy? policy = null)
+ {
+ policy ??= ShellPolicy.Default;
+
+ var (_, fullCommandForUser) = SanitizeCommandForUser(fileName, arguments, command);
+
var processArgs =
fileName.Equals("cmd.exe", StringComparison.OrdinalIgnoreCase) &&
!arguments.Contains(
@@ -131,7 +139,7 @@ public static class ShellService
}
catch
{
- ServiceTracker.LogError(null, "Failed to kill process for timeout");
+ ExecutionScope.LogError(null, "Failed to kill process for timeout");
}
process.WaitForExit(2000); // grace drain
@@ -153,38 +161,33 @@ public static class ShellService
var success = policy.IsSuccess(result);
- ServiceTracker.Track(serviceName, success);
+ ExecutionScope.Track(serviceName, success);
- ServiceTracker.LogInfo("[{Service}][{Status}][EC={ExitCode}][D={Duration}] {Command}",
+ ExecutionScope.LogInfo("[{Service}][{Status}][EC={ExitCode}][D={Duration}] {Command}",
serviceName,
timedOut ? "TIMEOUT" : success ? "OK" : "FAIL",
result.ExitCode,
duration.FormatTime(),
fullCommandForUser);
- ServiceTracker.LogTrace("[{Service}][STDOUT] {Stdout}",
+ ExecutionScope.LogTrace("[{Service}][STDOUT] {Stdout}",
serviceName,
string.IsNullOrWhiteSpace(stdout) ? "N/A" : stdout
);
- ServiceTracker.LogTrace("[{Service}][STDERR] {Stderr}",
+ ExecutionScope.LogTrace("[{Service}][STDERR] {Stderr}",
serviceName,
string.IsNullOrWhiteSpace(stderr) ? "N/A" : stderr
);
var error = success ? null : policy.ErrorFactory(result);
- ServiceTracker.TrackStep(
+ ExecutionScope.RecordStep(
"Shell",
fullCommandForUser,
success,
+ revertStep,
error,
- () => Task.Run(() =>
- policy.IsSuccess(Run(fileName, arguments, command, serviceName, revertStep, policy))
- )
- );
-
- if (success && revertStep is not null)
- RevertManager.Record(revertStep);
+ retryAction: success ? null : () => Task.FromResult(Run(fileName, arguments, command, serviceName, revertStep, policy).ExitCode == 0));
return result;
}
@@ -199,14 +202,13 @@ public static class ShellService
Duration = TimeSpan.Zero
};
- ServiceTracker.Track(serviceName, false);
- ServiceTracker.LogError(ex, "[{Service}][FAIL][EXCEPTION] {Command}", serviceName, fullCommandForUser);
- ServiceTracker.TrackStep(
+ ExecutionScope.RecordStep(
"Shell",
fullCommandForUser,
false,
+ revertStep,
ex.Message,
- () => Task.FromResult(false));
+ retryAction: () => Task.FromResult(Run(fileName, arguments, command, serviceName, revertStep, policy).ExitCode == 0));
return result;
}
@@ -223,18 +225,7 @@ public static class ShellService
{
policy ??= ShellPolicy.Default;
- var commandForUser = (arguments.Contains("-EncodedCommand", StringComparison.OrdinalIgnoreCase)
- ? command.DecodeBase64()
- : command)
- .Replace("$ProgressPreference='SilentlyContinue'; ", "")
- .Replace("[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ", "")
- .Replace(
- "$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8; ",
- "")
- .Replace("chcp 65001 > nul & ", "");
-
- var fullCommandForUser =
- $"{fileName} {arguments.Replace("-EncodedCommand", "-Command", StringComparison.OrdinalIgnoreCase)} {commandForUser}";
+ var (_, fullCommandForUser) = SanitizeCommandForUser(fileName, arguments, command);
var psi = new ProcessStartInfo
{
@@ -312,36 +303,32 @@ public static class ShellService
var success = policy.IsSuccess(result);
- ServiceTracker.Track(serviceName, success);
+ ExecutionScope.Track(serviceName, success);
- ServiceTracker.LogInfo("[{Service}][{Status}][EC={ExitCode}][D={Duration}] {Command}",
+ ExecutionScope.LogInfo("[{Service}][{Status}][EC={ExitCode}][D={Duration}] {Command}",
serviceName,
timedOut ? "TIMEOUT" : success ? "OK" : "FAIL",
result.ExitCode,
sw.Elapsed.FormatTime(),
fullCommandForUser);
- ServiceTracker.LogTrace("[{Service}][STDOUT] {Stdout}",
+ ExecutionScope.LogTrace("[{Service}][STDOUT] {Stdout}",
serviceName,
string.IsNullOrWhiteSpace(stdout) ? "N/A" : stdout);
- ServiceTracker.LogTrace("[{Service}][STDERR] {Stderr}",
+ ExecutionScope.LogTrace("[{Service}][STDERR] {Stderr}",
serviceName,
string.IsNullOrWhiteSpace(stderr) ? "N/A" : stderr);
var error = success ? null : policy.ErrorFactory(result);
- ServiceTracker.TrackStep(
+ ExecutionScope.RecordStep(
"Shell",
fullCommandForUser,
success,
+ revertStep,
error,
- async () =>
- policy.IsSuccess(await RunAsync(fileName, arguments, command, serviceName, revertStep, policy, ct))
- );
-
- if (success && revertStep is not null)
- RevertManager.Record(revertStep);
+ retryAction: success ? null : async () => (await RunAsync(fileName, arguments, command, serviceName, revertStep, policy, ct)).ExitCode == 0);
return result;
}
@@ -356,15 +343,13 @@ public static class ShellService
Duration = TimeSpan.Zero
};
- ServiceTracker.Track(serviceName, false);
- ServiceTracker.LogError(ex, "[{Service}][FAIL][EXCEPTION] {Command}", serviceName, fullCommandForUser);
-
- ServiceTracker.TrackStep(
+ ExecutionScope.RecordStep(
"Shell",
fullCommandForUser,
false,
+ revertStep,
ex.Message,
- () => Task.FromResult(false));
+ retryAction: async () => (await RunAsync(fileName, arguments, command, serviceName, revertStep, policy, ct)).ExitCode == 0);
return result;
}
@@ -490,7 +475,8 @@ public static class ShellService
command.EncodeBase64(),
nameof(PowerShell),
revertStep,
- policy, ct);
+ policy,
+ ct);
}
/// <summary>
diff --git a/optimizerDuck/Services/ServiceTracker.cs b/optimizerDuck/Services/ServiceTracker.cs
deleted file mode 100644
index 0d899d3..0000000
--- a/optimizerDuck/Services/ServiceTracker.cs
+++ /dev/null
@@ -1,141 +0,0 @@
-using System.Collections.Concurrent;
-using System.Diagnostics;
-using Microsoft.Extensions.Logging;
-using optimizerDuck.Common.Extensions;
-using optimizerDuck.Core.Models.Optimization;
-
-namespace optimizerDuck.Services;
-
-public sealed class ServiceTracker : IDisposable
-{
- private static readonly AsyncLocal<ServiceTracker?> _current = new();
-
- private readonly ILogger _logger;
- private readonly ConcurrentDictionary<string, Stats> _stats = new();
- private readonly List<OperationStepResult> _steps = new();
- private readonly Stopwatch _stopwatch;
- private int _stepIndex;
-
- private ServiceTracker(ILogger logger)
- {
- _logger = logger;
- _stopwatch = Stopwatch.StartNew();
- }
-
- /// <summary>Current active tracker (null if none)</summary>
- public static ServiceTracker? Current => _current.Value;
-
- public void Dispose()
- {
- _stopwatch.Stop();
-
- if (_stats.IsEmpty)
- {
- _logger.LogInformation("Completed in {Time} (no operations tracked)",
- _stopwatch.Elapsed.FormatTime());
- }
- else
- {
- var summary = string.Join(", ", _stats.Select(kv =>
- $"{kv.Key}: +({kv.Value.Success}) -({kv.Value.Fail})"));
-
- _logger.LogInformation("Completed in {Time} | {Summary}",
- _stopwatch.Elapsed.FormatTime(), summary);
- }
-
- _current.Value = null;
- }
-
- /// <summary>Begin tracking with a logger</summary>
- public static ServiceTracker Begin(ILogger logger)
- {
- var tracker = new ServiceTracker(logger);
- _current.Value = tracker;
- return tracker;
- }
-
- /// <summary>Track a service operation result</summary>
- public static void Track(string serviceName, bool success)
- {
- var tracker = Current;
-
- tracker?._stats.AddOrUpdate(
- serviceName,
- _ => success
- ? new Stats { Success = 1 }
- : new Stats { Fail = 1 },
- (_, stats) =>
- {
- if (success) stats.Success++;
- else stats.Fail++;
- return stats;
- });
- }
-
-
- public static void TrackStep(string name, string description, bool success, string? error = null,
- Func<Task<bool>>? retryAction = null)
- {
- var tracker = Current;
- if (tracker == null)
- return;
-
- var index = ++tracker._stepIndex;
- tracker._steps.Add(new OperationStepResult
- {
- Index = index,
- Name = name,
- Description = description,
- Success = success,
- Error = error,
- RetryAction = retryAction
- });
- }
-
- public IReadOnlyList<OperationStepResult> GetSteps()
- {
- return _steps.ToList();
- }
-
- /// <summary>Log a message using the current tracker's logger</summary>
- public static void Log(LogLevel level, string message, params object[] args)
- {
- Current?._logger.Log(level, message, args);
- }
-
- /// <summary>Log debug message</summary>
- public static void LogDebug(string message, params object[] args)
- {
- Log(LogLevel.Debug, message, args);
- }
-
- /// <summary>Log trace message</summary>
- public static void LogTrace(string message, params object[] args)
- {
- Log(LogLevel.Trace, message, args);
- }
-
- /// <summary>Log info message</summary>
- public static void LogInfo(string message, params object[] args)
- {
- Log(LogLevel.Information, message, args);
- }
-
- /// <summary>Log warning message</summary>
- public static void LogWarning(string message, params object[] args)
- {
- Log(LogLevel.Warning, message, args);
- }
-
- /// <summary>Log error message</summary>
- public static void LogError(Exception? ex, string message, params object[] args)
- {
- Current?._logger.LogError(ex, message, args);
- }
-
- private class Stats
- {
- public int Fail;
- public int Success;
- }
-}
\ No newline at end of file
diff --git a/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs
index cafe6a0..3d5ab35 100644
--- a/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs
@@ -126,7 +126,7 @@ public partial class SettingsViewModel(
{
var result = await ConfirmationDialogAsync(Translations.Settings_ClearResources_Description);
if (result == ContentDialogResult.Primary)
- OptimizationService.ClearResourcesAsync();
+ OptimizationService.ClearResources();
}
[RelayCommand]
@@ -135,7 +135,7 @@ public partial class SettingsViewModel(
var result = await ConfirmationDialogAsync(Translations.Settings_ClearRevertData_Description);
if (result == ContentDialogResult.Primary)
{
- RevertManager.ClearAllRevertDataAsync();
+ RevertManager.ClearAllRevertData();
// Refresh optimizations
await OptimizationService.UpdateOptimizationStateAsync(
optimizationRegistry.OptimizationCategories.SelectMany(c => c.Optimizations));