-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCommandCleanupExtensions.cs
More file actions
202 lines (177 loc) · 6.94 KB
/
CommandCleanupExtensions.cs
File metadata and controls
202 lines (177 loc) · 6.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
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;
}