Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -863,4 +863,6 @@ FodyWeavers.xsd
### VisualStudio Patch ###
# Additional files built by Visual Studio

# End of https://www.toptal.com/developers/gitignore/api/windows,linux,macos,visualstudio,visualstudiocode,intellij,intellij+all,rider,angular,dotnetcore,aspnetcore,xamarinstudio
*.trx

# End of https://www.toptal.com/developers/gitignore/api/windows,linux,macos,visualstudio,visualstudiocode,intellij,intellij+all,rider,angular,dotnetcore,aspnetcore,xamarinstudio
34 changes: 34 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Conversations
any resulting updates to agents.md should go under the section "## Rules to follow"
When you see a convincing argument from me on how to solve or do something. add a summary for this in agents.md. so you learn what I want over time.
If I say any of the following point, you do this: add the context to agents.md, and associate this with a specific type of task.
if I say "never do x" in some way.
if I say "always do x" in some way.
if I say "the process is x" in some way.
If I tell you to remember something, you do the same, update


## Rules to follow
always check all test are passed.
- Prefer static interface members for result/command factories to centralize shared overloads and avoid duplication across result-like types.

# Repository Guidelines

## Project Structure & Module Organization
The solution `ManagedCode.Communication.slnx` ties together the core library (`ManagedCode.Communication`), ASP.NET Core adapters, Orleans integrations, performance benchmarks, and the consolidated test suite (`ManagedCode.Communication.Tests`). Tests mirror the runtime namespaces—look for feature-specific folders such as `Results`, `Commands`, and `AspNetCore`—so keep new specs alongside the code they exercise. Shared assets live at the repository root (`README.md`, `logo.png`) and are packaged automatically through `Directory.Build.props`.

## Build, Test, and Development Commands
- `dotnet restore ManagedCode.Communication.slnx` – restore all project dependencies.
- `dotnet build -c Release ManagedCode.Communication.slnx` – compile every project with warnings treated as errors.
- `dotnet test ManagedCode.Communication.Tests/ManagedCode.Communication.Tests.csproj` – run the xUnit suite; produces `*.trx` logs under `ManagedCode.Communication.Tests`.
- `dotnet test ManagedCode.Communication.Tests/ManagedCode.Communication.Tests.csproj /p:CollectCoverage=true /p:CoverletOutputFormat=lcov` – refresh `coverage.info` via coverlet.
- `dotnet run -c Release --project ManagedCode.Communication.Benchmark` – execute benchmark scenarios before performance-sensitive changes.

## Coding Style & Naming Conventions
Formatting is driven by the root `.editorconfig`: spaces only, 4-space indent for C#, CRLF endings for code, braces on new lines, and explicit types except when the type is obvious. The repo builds with C# 13, nullable reference types enabled, and analyzers elevated to errors—leave no compiler warnings behind. Stick to domain-centric names (e.g., `ResultExtensionsTests`) and prefer PascalCase for members and const fields per the configured naming rules.

## Testing Guidelines
All automated tests use xUnit with Shouldly and Microsoft test hosts; follow the existing spec style (`MethodUnderTest_WithScenario_ShouldOutcome`). New fixtures belong in the matching feature folder and should assert both success and failure branches for Result types. Maintain the default coverage settings supplied by `coverlet.collector`; update snapshots or helper helpers under `TestHelpers` (including shared Shouldly extensions) when shared setup changes.

## Commit & Pull Request Guidelines
Commits in this repository stay short, imperative, and often reference the related issue or PR number (e.g., `Add FailBadRequest methods (#30)`). Mirror that tone, limit each commit to a coherent change, and include updates to docs or benchmarks when behavior shifts. Pull requests should summarize intent, list breaking changes, attach relevant `dotnet test` outputs or coverage deltas, and link tracked issues. Screenshots or sample payloads are welcome for HTTP-facing work.
5 changes: 3 additions & 2 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<EnablePreviewFeatures>true</EnablePreviewFeatures>
</PropertyGroup>

<!--NuGet-->
Expand All @@ -26,8 +27,8 @@
<RepositoryUrl>https://github.com/managedcode/Communication</RepositoryUrl>
<PackageProjectUrl>https://github.com/managedcode/Communication</PackageProjectUrl>
<Product>Managed Code - Communication</Product>
<Version>9.6.2</Version>
<PackageVersion>9.6.2</PackageVersion>
<Version>9.6.3</Version>
<PackageVersion>9.6.3</PackageVersion>

</PropertyGroup>
<PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ManagedCode.Communication.Commands;
using ManagedCode.Communication.Logging;

namespace ManagedCode.Communication.AspNetCore.Extensions;

/// <summary>
/// Extension methods for command cleanup operations
/// </summary>
public static class CommandCleanupExtensions
{
/// <summary>
/// Perform automatic cleanup of expired commands
/// </summary>
public static async Task<int> AutoCleanupAsync(
this ICommandIdempotencyStore store,
TimeSpan? completedCommandMaxAge = null,
TimeSpan? failedCommandMaxAge = null,
TimeSpan? inProgressCommandMaxAge = null,
CancellationToken cancellationToken = default)
{
completedCommandMaxAge ??= TimeSpan.FromHours(24);
failedCommandMaxAge ??= TimeSpan.FromHours(1);
inProgressCommandMaxAge ??= TimeSpan.FromMinutes(30);

var totalCleaned = 0;

// Clean up completed commands (keep longer for caching)
totalCleaned += await store.CleanupCommandsByStatusAsync(
CommandExecutionStatus.Completed,
completedCommandMaxAge.Value,
cancellationToken);

// Clean up failed commands (clean faster to retry)
totalCleaned += await store.CleanupCommandsByStatusAsync(
CommandExecutionStatus.Failed,
failedCommandMaxAge.Value,
cancellationToken);

// Clean up stuck in-progress commands (potential zombies)
totalCleaned += await store.CleanupCommandsByStatusAsync(
CommandExecutionStatus.InProgress,
inProgressCommandMaxAge.Value,
cancellationToken);

return totalCleaned;
}

/// <summary>
/// Get health metrics for monitoring
/// </summary>
public static async Task<CommandStoreHealthMetrics> GetHealthMetricsAsync(
this ICommandIdempotencyStore store,
CancellationToken cancellationToken = default)
{
var counts = await store.GetCommandCountByStatusAsync(cancellationToken);

return new CommandStoreHealthMetrics
{
TotalCommands = counts.Values.Sum(),
CompletedCommands = counts.GetValueOrDefault(CommandExecutionStatus.Completed, 0),
InProgressCommands = counts.GetValueOrDefault(CommandExecutionStatus.InProgress, 0),
FailedCommands = counts.GetValueOrDefault(CommandExecutionStatus.Failed, 0),
ProcessingCommands = counts.GetValueOrDefault(CommandExecutionStatus.Processing, 0),
Timestamp = DateTimeOffset.UtcNow
};
}
}

/// <summary>
/// Health metrics for command store monitoring
/// </summary>
public record CommandStoreHealthMetrics
{
public int TotalCommands { get; init; }
public int CompletedCommands { get; init; }
public int InProgressCommands { get; init; }
public int FailedCommands { get; init; }
public int ProcessingCommands { get; init; }
public DateTimeOffset Timestamp { get; init; }

/// <summary>
/// Percentage of commands that are stuck in progress (potential issue)
/// </summary>
public double StuckCommandsPercentage =>
TotalCommands > 0 ? (double)InProgressCommands / TotalCommands * 100 : 0;

/// <summary>
/// Percentage of commands that failed (error rate)
/// </summary>
public double FailureRate =>
TotalCommands > 0 ? (double)FailedCommands / TotalCommands * 100 : 0;
}

/// <summary>
/// Background service for automatic command cleanup
/// </summary>
public class CommandCleanupBackgroundService : BackgroundService
{
private readonly ICommandIdempotencyStore _store;
private readonly ILogger<CommandCleanupBackgroundService> _logger;
private readonly TimeSpan _cleanupInterval;
private readonly CommandCleanupOptions _options;

public CommandCleanupBackgroundService(
ICommandIdempotencyStore store,
ILogger<CommandCleanupBackgroundService> logger,
CommandCleanupOptions? options = null)
{
_store = store;
_logger = logger;
_options = options ?? new CommandCleanupOptions();
_cleanupInterval = _options.CleanupInterval;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
LoggerCenter.LogCleanupServiceStarted(_logger, _cleanupInterval);

while (!stoppingToken.IsCancellationRequested)
{
try
{
var cleanedCount = await _store.AutoCleanupAsync(
_options.CompletedCommandMaxAge,
_options.FailedCommandMaxAge,
_options.InProgressCommandMaxAge,
stoppingToken);

if (cleanedCount > 0)
{
LoggerCenter.LogCleanupCompleted(_logger, cleanedCount);
}

// Log health metrics
if (_options.LogHealthMetrics)
{
var metrics = await _store.GetHealthMetricsAsync(stoppingToken);
LoggerCenter.LogHealthMetrics(_logger,
metrics.TotalCommands,
metrics.CompletedCommands,
metrics.FailedCommands,
metrics.InProgressCommands,
metrics.FailureRate / 100, // Convert to ratio for formatting
metrics.StuckCommandsPercentage / 100); // Convert to ratio for formatting
}
}
catch (Exception ex) when (!stoppingToken.IsCancellationRequested)
{
LoggerCenter.LogCleanupError(_logger, ex);
}

try
{
await Task.Delay(_cleanupInterval, stoppingToken);
}
catch (OperationCanceledException)
{
break;
}
}

LoggerCenter.LogCleanupServiceStopped(_logger);
}
}

/// <summary>
/// Configuration options for command cleanup
/// </summary>
public class CommandCleanupOptions
{
/// <summary>
/// How often to run cleanup
/// </summary>
public TimeSpan CleanupInterval { get; set; } = TimeSpan.FromMinutes(10);

/// <summary>
/// How long to keep completed commands (for caching)
/// </summary>
public TimeSpan CompletedCommandMaxAge { get; set; } = TimeSpan.FromHours(24);

/// <summary>
/// How long to keep failed commands before allowing cleanup
/// </summary>
public TimeSpan FailedCommandMaxAge { get; set; } = TimeSpan.FromHours(1);

/// <summary>
/// How long before in-progress commands are considered stuck
/// </summary>
public TimeSpan InProgressCommandMaxAge { get; set; } = TimeSpan.FromMinutes(30);

/// <summary>
/// Whether to log health metrics during cleanup
/// </summary>
public bool LogHealthMetrics { get; set; } = true;
}
Loading