| | | 1 | | using Elsa.Workflows.Runtime.Requests; |
| | | 2 | | using Elsa.Workflows.Runtime.Responses; |
| | | 3 | | using JetBrains.Annotations; |
| | | 4 | | using Medallion.Threading; |
| | | 5 | | using Microsoft.Extensions.Logging; |
| | | 6 | | |
| | | 7 | | namespace Elsa.Workflows.Runtime.Distributed; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Decorator class that adds distributed locking to the Workflow Definitions Refresher. |
| | | 11 | | /// </summary> |
| | | 12 | | [UsedImplicitly] |
| | 7 | 13 | | public class DistributedWorkflowDefinitionsRefresher(IWorkflowDefinitionsRefresher inner, |
| | 7 | 14 | | IDistributedLockProvider distributedLockProvider, |
| | 7 | 15 | | ILogger<DistributedWorkflowDefinitionsRefresher> logger) : IWorkflowDefinitionsRefresher |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// This ensures that only one instance of the application can refresh a set of workflow definitions at a time, prev |
| | | 19 | | /// </summary> |
| | | 20 | | public async Task<RefreshWorkflowDefinitionsResponse> RefreshWorkflowDefinitionsAsync(RefreshWorkflowDefinitionsRequ |
| | | 21 | | { |
| | 4 | 22 | | var isRefreshingAll = request.DefinitionIds == null || request.DefinitionIds.Count == 0; |
| | 4 | 23 | | var lockKey = isRefreshingAll |
| | 4 | 24 | | ? "WorkflowDefinitionsRefresher:All" |
| | 8 | 25 | | : $"WorkflowDefinitionsRefresher:{string.Join(",", request.DefinitionIds!.OrderBy(x => x))}"; |
| | | 26 | | |
| | 4 | 27 | | await using var distributedLock = await distributedLockProvider.TryAcquireLockAsync( |
| | 4 | 28 | | lockKey, |
| | 4 | 29 | | TimeSpan.Zero, |
| | 4 | 30 | | cancellationToken); |
| | | 31 | | |
| | 4 | 32 | | if (distributedLock == null) |
| | | 33 | | { |
| | 2 | 34 | | var logMessage = isRefreshingAll |
| | 2 | 35 | | ? "Could not acquire lock for refreshing all workflow definitions. Another instance is already refreshin |
| | 2 | 36 | | : "Could not acquire lock for refreshing workflow definitions. Another instance is already refreshing th |
| | | 37 | | |
| | 2 | 38 | | logger.LogInformation(logMessage); |
| | | 39 | | |
| | 2 | 40 | | var failedDefinitionIds = isRefreshingAll ? Array.Empty<string>() : request.DefinitionIds!; |
| | 2 | 41 | | return new(Array.Empty<string>(), failedDefinitionIds, RefreshWorkflowDefinitionsStatus.AlreadyInProgress); |
| | | 42 | | } |
| | | 43 | | |
| | 2 | 44 | | return await inner.RefreshWorkflowDefinitionsAsync(request, cancellationToken); |
| | 4 | 45 | | } |
| | | 46 | | } |