| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using System.Reflection; |
| | | 3 | | using Elsa.Common.Helpers; |
| | | 4 | | using Elsa.Common.RecurringTasks; |
| | | 5 | | using Microsoft.Extensions.DependencyInjection; |
| | | 6 | | using Microsoft.Extensions.Logging; |
| | | 7 | | |
| | | 8 | | namespace Elsa.Common.Multitenancy.EventHandlers; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Manages the lifecycle of startup, background, and recurring tasks for tenants. |
| | | 12 | | /// Executes tasks in the proper sequence: startup tasks first, then background tasks, then recurring tasks. |
| | | 13 | | /// </summary> |
| | 6 | 14 | | public class TenantTaskManager(RecurringTaskScheduleManager scheduleManager, ILogger<TenantTaskManager> logger) : ITenan |
| | | 15 | | { |
| | 6 | 16 | | private readonly ConcurrentDictionary<string, TenantRuntimeState> _tenantStates = new(); |
| | 6 | 17 | | private readonly CancellationTokenSource _shutdownCancellationTokenSource = new(); |
| | | 18 | | private int _disposeRequested; |
| | | 19 | | |
| | | 20 | | public async Task TenantActivatedAsync(TenantActivatedEventArgs args) |
| | | 21 | | { |
| | 15 | 22 | | if (Volatile.Read(ref _disposeRequested) == 1) |
| | 0 | 23 | | return; |
| | | 24 | | |
| | 15 | 25 | | using var activationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(args.CancellationToken, _shutd |
| | 15 | 26 | | var cancellationToken = activationTokenSource.Token; |
| | 15 | 27 | | var tenantScope = args.TenantScope; |
| | 15 | 28 | | var taskExecutor = tenantScope.ServiceProvider.GetRequiredService<ITaskExecutor>(); |
| | 15 | 29 | | var tenantId = GetTenantId(args.Tenant); |
| | 30 | 30 | | var state = _tenantStates.GetOrAdd(tenantId, static _ => new TenantRuntimeState()); |
| | | 31 | | |
| | 15 | 32 | | await state.Gate.WaitAsync(cancellationToken); |
| | | 33 | | |
| | | 34 | | try |
| | | 35 | | { |
| | 15 | 36 | | if (Volatile.Read(ref _disposeRequested) == 1) |
| | 0 | 37 | | return; |
| | | 38 | | |
| | 15 | 39 | | await StopTenantCoreAsync(state, cancellationToken); |
| | 15 | 40 | | state.CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| | | 41 | | |
| | | 42 | | // Step 1: Run startup tasks (with dependency ordering) |
| | 15 | 43 | | await RunStartupTasksAsync(tenantScope, taskExecutor, cancellationToken); |
| | | 44 | | |
| | | 45 | | // Step 2: Run background tasks |
| | 15 | 46 | | await RunBackgroundTasksAsync(tenantScope, taskExecutor, state, cancellationToken); |
| | | 47 | | |
| | | 48 | | // Step 3: Start recurring tasks |
| | 15 | 49 | | await StartRecurringTasksAsync(tenantScope, taskExecutor, state, cancellationToken); |
| | 15 | 50 | | } |
| | 0 | 51 | | catch |
| | | 52 | | { |
| | 0 | 53 | | await StopTenantCoreAsync(state, cancellationToken); |
| | 0 | 54 | | throw; |
| | | 55 | | } |
| | | 56 | | finally |
| | | 57 | | { |
| | 15 | 58 | | state.Gate.Release(); |
| | | 59 | | } |
| | 15 | 60 | | } |
| | | 61 | | |
| | | 62 | | public async Task TenantDeactivatedAsync(TenantDeactivatedEventArgs args) |
| | | 63 | | { |
| | 14 | 64 | | var tenantId = GetTenantId(args.Tenant); |
| | | 65 | | |
| | 14 | 66 | | if (!_tenantStates.TryGetValue(tenantId, out var state)) |
| | 0 | 67 | | return; |
| | | 68 | | |
| | 14 | 69 | | await state.Gate.WaitAsync(args.CancellationToken); |
| | | 70 | | |
| | | 71 | | try |
| | | 72 | | { |
| | 13 | 73 | | _tenantStates.TryRemove(tenantId, out _); |
| | 13 | 74 | | await StopTenantCoreAsync(state, args.CancellationToken); |
| | 13 | 75 | | } |
| | | 76 | | finally |
| | | 77 | | { |
| | 13 | 78 | | state.Gate.Release(); |
| | | 79 | | } |
| | 13 | 80 | | } |
| | | 81 | | |
| | | 82 | | private async Task RunStartupTasksAsync(ITenantScope tenantScope, ITaskExecutor taskExecutor, CancellationToken canc |
| | | 83 | | { |
| | 15 | 84 | | var startupTasks = tenantScope.ServiceProvider.GetServices<IStartupTask>() |
| | 108 | 85 | | .OrderBy(x => x.GetType().GetCustomAttribute<OrderAttribute>()?.Order ?? 0f) |
| | 15 | 86 | | .ToList(); |
| | | 87 | | |
| | | 88 | | // First apply OrderAttribute to determine a base order, then perform topological sorting. |
| | | 89 | | // The topological sort is the final ordering step to ensure dependency constraints are respected. |
| | 15 | 90 | | var sortedTasks = TopologicalTaskSorter.Sort(startupTasks).ToList(); |
| | 246 | 91 | | foreach (var task in sortedTasks) |
| | 108 | 92 | | await taskExecutor.ExecuteTaskAsync(task, cancellationToken); |
| | 15 | 93 | | } |
| | | 94 | | |
| | | 95 | | private Task RunBackgroundTasksAsync(ITenantScope tenantScope, ITaskExecutor taskExecutor, TenantRuntimeState state, |
| | | 96 | | { |
| | 15 | 97 | | var backgroundTasks = tenantScope.ServiceProvider.GetServices<IBackgroundTask>(); |
| | 15 | 98 | | var backgroundTaskStarter = tenantScope.ServiceProvider.GetRequiredService<IBackgroundTaskStarter>(); |
| | 15 | 99 | | var tenantCancellationToken = state.CancellationTokenSource?.Token ?? cancellationToken; |
| | | 100 | | |
| | 54 | 101 | | foreach (var backgroundTask in backgroundTasks) |
| | | 102 | | { |
| | 12 | 103 | | var task = backgroundTaskStarter |
| | 12 | 104 | | .StartAsync(backgroundTask, tenantCancellationToken) |
| | 12 | 105 | | .ContinueWith(_ => taskExecutor.ExecuteTaskAsync(backgroundTask, tenantCancellationToken), |
| | 12 | 106 | | cancellationToken, |
| | 12 | 107 | | TaskContinuationOptions.RunContinuationsAsynchronously, |
| | 12 | 108 | | TaskScheduler.Default) |
| | 12 | 109 | | .Unwrap(); |
| | | 110 | | |
| | 12 | 111 | | if (!task.IsCompleted) |
| | 12 | 112 | | state.RunningBackgroundTasks.Add(task); |
| | | 113 | | } |
| | | 114 | | |
| | 15 | 115 | | return Task.CompletedTask; |
| | | 116 | | } |
| | | 117 | | |
| | | 118 | | private async Task StartRecurringTasksAsync(ITenantScope tenantScope, ITaskExecutor taskExecutor, TenantRuntimeState |
| | | 119 | | { |
| | 15 | 120 | | var recurringTasks = tenantScope.ServiceProvider.GetServices<IRecurringTask>().ToList(); |
| | 15 | 121 | | var tenantCancellationToken = state.CancellationTokenSource?.Token ?? cancellationToken; |
| | | 122 | | |
| | 108 | 123 | | foreach (var task in recurringTasks) |
| | | 124 | | { |
| | 39 | 125 | | var schedule = scheduleManager.GetScheduleFor(task.GetType()); |
| | 39 | 126 | | var timer = schedule.CreateTimer(async () => |
| | 39 | 127 | | { |
| | 72 | 128 | | if (tenantCancellationToken.IsCancellationRequested) |
| | 0 | 129 | | return; |
| | 39 | 130 | | |
| | 39 | 131 | | try |
| | 39 | 132 | | { |
| | 72 | 133 | | await taskExecutor.ExecuteTaskAsync(task, tenantCancellationToken); |
| | 72 | 134 | | } |
| | 0 | 135 | | catch (OperationCanceledException e) |
| | 39 | 136 | | { |
| | 0 | 137 | | logger.LogInformation(e, "Recurring task {TaskType} was cancelled", task.GetType().Name); |
| | 0 | 138 | | } |
| | 0 | 139 | | catch (Exception e) when (!e.IsFatal()) |
| | 39 | 140 | | { |
| | 39 | 141 | | // Log but don't rethrow - recurring tasks should not crash the host |
| | 0 | 142 | | logger.LogError(e, "Recurring task {TaskType} failed with an error", task.GetType().Name); |
| | 0 | 143 | | } |
| | 111 | 144 | | }, logger); |
| | | 145 | | |
| | 39 | 146 | | state.ScheduledTimers.Add(timer); |
| | 39 | 147 | | state.RecurringTasks.Add(task); |
| | 39 | 148 | | await task.StartAsync(cancellationToken); |
| | | 149 | | } |
| | 15 | 150 | | } |
| | | 151 | | |
| | | 152 | | public async ValueTask DisposeAsync() |
| | | 153 | | { |
| | 11 | 154 | | if (Interlocked.Exchange(ref _disposeRequested, 1) == 1) |
| | 6 | 155 | | return; |
| | | 156 | | |
| | | 157 | | try |
| | | 158 | | { |
| | 5 | 159 | | await _shutdownCancellationTokenSource.CancelAsync(); |
| | 5 | 160 | | } |
| | 0 | 161 | | catch (ObjectDisposedException) |
| | | 162 | | { |
| | | 163 | | // Already disposed by a concurrent path. |
| | 0 | 164 | | } |
| | | 165 | | |
| | 14 | 166 | | foreach (var state in _tenantStates.Values) |
| | | 167 | | { |
| | 2 | 168 | | await state.Gate.WaitAsync(); |
| | | 169 | | |
| | | 170 | | try |
| | | 171 | | { |
| | 2 | 172 | | await StopTenantCoreAsync(state, CancellationToken.None); |
| | 2 | 173 | | } |
| | | 174 | | finally |
| | | 175 | | { |
| | 2 | 176 | | state.Gate.Release(); |
| | | 177 | | } |
| | 2 | 178 | | } |
| | | 179 | | |
| | | 180 | | try |
| | | 181 | | { |
| | 5 | 182 | | _shutdownCancellationTokenSource.Dispose(); |
| | 5 | 183 | | } |
| | 0 | 184 | | catch (ObjectDisposedException) |
| | | 185 | | { |
| | | 186 | | // Already disposed by a concurrent path. |
| | 0 | 187 | | } |
| | 11 | 188 | | } |
| | | 189 | | |
| | | 190 | | private async Task StopTenantCoreAsync(TenantRuntimeState state, CancellationToken cancellationToken) |
| | | 191 | | { |
| | 30 | 192 | | var cancellationTokenSource = state.CancellationTokenSource; |
| | | 193 | | |
| | | 194 | | // Cancel first so callbacks and long-running tasks can drain while resources are being disposed. |
| | 30 | 195 | | if (cancellationTokenSource != null) |
| | | 196 | | { |
| | | 197 | | try |
| | | 198 | | { |
| | 15 | 199 | | await cancellationTokenSource.CancelAsync(); |
| | 15 | 200 | | } |
| | 0 | 201 | | catch (ObjectDisposedException) |
| | | 202 | | { |
| | | 203 | | // Already disposed by a concurrent path. |
| | 0 | 204 | | } |
| | 0 | 205 | | catch (Exception e) when (!e.IsFatal()) |
| | | 206 | | { |
| | 0 | 207 | | logger.LogWarning(e, "Failed to cancel tenant task cancellation token source while stopping tenant tasks |
| | 0 | 208 | | } |
| | | 209 | | } |
| | | 210 | | |
| | 138 | 211 | | foreach (var timer in state.ScheduledTimers) |
| | | 212 | | { |
| | | 213 | | try |
| | | 214 | | { |
| | 39 | 215 | | await timer.DisposeAsync(); |
| | 39 | 216 | | } |
| | 0 | 217 | | catch (ObjectDisposedException) |
| | | 218 | | { |
| | | 219 | | // Timer is already disposed; this can happen during concurrent shutdown paths. |
| | 0 | 220 | | } |
| | 0 | 221 | | catch (Exception e) when (!e.IsFatal()) |
| | | 222 | | { |
| | 0 | 223 | | logger.LogWarning(e, "Failed to dispose a recurring timer while stopping tenant tasks"); |
| | 0 | 224 | | } |
| | | 225 | | } |
| | 30 | 226 | | state.ScheduledTimers.Clear(); |
| | | 227 | | |
| | 30 | 228 | | if (state.RunningBackgroundTasks.Count > 0) |
| | | 229 | | { |
| | | 230 | | try |
| | | 231 | | { |
| | 12 | 232 | | await Task.WhenAll(state.RunningBackgroundTasks); |
| | 12 | 233 | | } |
| | 0 | 234 | | catch (OperationCanceledException) |
| | | 235 | | { |
| | | 236 | | // Expected when cancellation is requested. |
| | 0 | 237 | | } |
| | 0 | 238 | | catch (AggregateException e) |
| | | 239 | | { |
| | 0 | 240 | | logger.LogError(e, "One or more background tasks failed while stopping tenant tasks"); |
| | 0 | 241 | | } |
| | 0 | 242 | | catch (InvalidOperationException e) |
| | | 243 | | { |
| | 0 | 244 | | logger.LogError(e, "Background task collection was in an invalid state while stopping tenant tasks"); |
| | 0 | 245 | | } |
| | 12 | 246 | | state.RunningBackgroundTasks.Clear(); |
| | | 247 | | } |
| | | 248 | | |
| | 138 | 249 | | foreach (var recurringTask in state.RecurringTasks) |
| | | 250 | | { |
| | | 251 | | try |
| | | 252 | | { |
| | 39 | 253 | | await recurringTask.StopAsync(cancellationToken); |
| | 39 | 254 | | } |
| | 0 | 255 | | catch (OperationCanceledException) |
| | | 256 | | { |
| | | 257 | | // Expected if caller requested cancellation during tenant deactivation. |
| | 0 | 258 | | } |
| | 0 | 259 | | catch (Exception e) when (!e.IsFatal()) |
| | | 260 | | { |
| | 0 | 261 | | logger.LogError(e, "Failed to stop recurring task {TaskType}", recurringTask.GetType().Name); |
| | 0 | 262 | | } |
| | 39 | 263 | | } |
| | 30 | 264 | | state.RecurringTasks.Clear(); |
| | | 265 | | |
| | 30 | 266 | | if (cancellationTokenSource == null) |
| | 15 | 267 | | return; |
| | | 268 | | |
| | | 269 | | try |
| | | 270 | | { |
| | 15 | 271 | | cancellationTokenSource.Dispose(); |
| | 15 | 272 | | } |
| | 0 | 273 | | catch (ObjectDisposedException) |
| | | 274 | | { |
| | | 275 | | // Already disposed by a concurrent path. |
| | 0 | 276 | | } |
| | 0 | 277 | | catch (Exception e) when (!e.IsFatal()) |
| | | 278 | | { |
| | 0 | 279 | | logger.LogWarning(e, "Failed to dispose tenant task cancellation token source"); |
| | 0 | 280 | | } |
| | | 281 | | |
| | 15 | 282 | | state.CancellationTokenSource = null; |
| | 30 | 283 | | } |
| | | 284 | | |
| | 29 | 285 | | private static string GetTenantId(Tenant tenant) => tenant.Id; |
| | | 286 | | |
| | | 287 | | private class TenantRuntimeState |
| | | 288 | | { |
| | | 289 | | // SemaphoreSlim only allocates a kernel handle when AvailableWaitHandle is accessed. |
| | | 290 | | // Since we exclusively use WaitAsync(), no kernel handle is ever created and disposal is a no-op. |
| | 76 | 291 | | public SemaphoreSlim Gate { get; } = new(1, 1); |
| | 81 | 292 | | public List<Task> RunningBackgroundTasks { get; } = []; |
| | 114 | 293 | | public List<ScheduledTimer> ScheduledTimers { get; } = []; |
| | 114 | 294 | | public List<IRecurringTask> RecurringTasks { get; } = []; |
| | 90 | 295 | | public CancellationTokenSource? CancellationTokenSource { get; set; } |
| | | 296 | | } |
| | | 297 | | } |