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