| | | 1 | | using System.Reflection; |
| | | 2 | | using Elsa.Common.DistributedHosting; |
| | | 3 | | using Elsa.Common.RecurringTasks; |
| | | 4 | | using Medallion.Threading; |
| | | 5 | | using Microsoft.Extensions.Options; |
| | | 6 | | |
| | | 7 | | namespace Elsa.Common.Multitenancy; |
| | | 8 | | |
| | 2 | 9 | | public class TaskExecutor(IDistributedLockProvider distributedLockProvider, IOptions<DistributedLockingOptions> options) |
| | | 10 | | { |
| | | 11 | | public async Task ExecuteTaskAsync(ITask task, CancellationToken cancellationToken) |
| | | 12 | | { |
| | 24 | 13 | | await ExecuteInternalAsync(task, () => task.ExecuteAsync(cancellationToken), cancellationToken); |
| | 12 | 14 | | } |
| | | 15 | | |
| | | 16 | | public async Task StartAsync(IBackgroundTask task, CancellationToken cancellationToken) |
| | | 17 | | { |
| | 2 | 18 | | await ExecuteInternalAsync(task, () => task.StartAsync(cancellationToken), cancellationToken); |
| | 1 | 19 | | } |
| | | 20 | | |
| | | 21 | | public async Task StopAsync(IBackgroundTask task, CancellationToken cancellationToken) |
| | | 22 | | { |
| | 0 | 23 | | await ExecuteInternalAsync(task, () => task.StopAsync(cancellationToken), cancellationToken); |
| | 0 | 24 | | } |
| | | 25 | | |
| | | 26 | | private async Task ExecuteInternalAsync(ITask task, Func<Task> action, CancellationToken cancellationToken) |
| | | 27 | | { |
| | 13 | 28 | | var taskType = task.GetType(); |
| | 13 | 29 | | var singleNodeTask = taskType.GetCustomAttribute<SingleNodeTaskAttribute>() != null; |
| | | 30 | | |
| | 13 | 31 | | if (singleNodeTask) |
| | | 32 | | { |
| | 9 | 33 | | var resourceName = taskType.AssemblyQualifiedName!; |
| | 9 | 34 | | await using (await distributedLockProvider.AcquireLockAsync(resourceName, options.Value.LockAcquisitionTimeo |
| | 9 | 35 | | await action(); |
| | | 36 | | } |
| | | 37 | | else |
| | | 38 | | { |
| | 4 | 39 | | await action(); |
| | | 40 | | } |
| | 13 | 41 | | } |
| | | 42 | | } |