| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using System.Threading.Channels; |
| | | 3 | | using Elsa.Common.Multitenancy; |
| | | 4 | | |
| | | 5 | | namespace Elsa.Workflows.Runtime; |
| | | 6 | | |
| | | 7 | | public class BookmarkQueueSignaler : IBookmarkQueueSignaler |
| | | 8 | | { |
| | 241 | 9 | | private readonly ConcurrentDictionary<string, Channel<object?>> _channels = new(); |
| | | 10 | | private readonly ITenantAccessor? _tenantAccessor; |
| | | 11 | | |
| | 1 | 12 | | public BookmarkQueueSignaler() |
| | | 13 | | { |
| | 1 | 14 | | } |
| | | 15 | | |
| | 240 | 16 | | public BookmarkQueueSignaler(ITenantAccessor tenantAccessor) |
| | | 17 | | { |
| | 240 | 18 | | _tenantAccessor = tenantAccessor; |
| | 240 | 19 | | } |
| | | 20 | | |
| | | 21 | | public Task AwaitAsync(CancellationToken cancellationToken = default) |
| | | 22 | | { |
| | 489 | 23 | | return GetChannel().Reader.ReadAsync(cancellationToken).AsTask(); |
| | | 24 | | } |
| | | 25 | | |
| | | 26 | | public Task TriggerAsync(CancellationToken cancellationToken = default) |
| | | 27 | | { |
| | 1329 | 28 | | return TriggerAsync(CurrentTenantId(), cancellationToken); |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | public Task TriggerAsync(string tenantId, CancellationToken cancellationToken = default) |
| | | 32 | | { |
| | 1330 | 33 | | GetChannel(tenantId).Writer.TryWrite(null); |
| | 1330 | 34 | | return Task.CompletedTask; |
| | | 35 | | } |
| | | 36 | | |
| | | 37 | | public void Release(string tenantId) |
| | | 38 | | { |
| | 31 | 39 | | _channels.TryRemove(tenantId.NormalizeTenantId(), out _); |
| | 31 | 40 | | } |
| | | 41 | | |
| | | 42 | | private Channel<object?> GetChannel(string? tenantId = null) |
| | | 43 | | { |
| | 2021 | 44 | | return _channels.GetOrAdd((tenantId ?? CurrentTenantId()).NormalizeTenantId(), static _ => CreateChannel()); |
| | | 45 | | } |
| | | 46 | | |
| | 1818 | 47 | | private string CurrentTenantId() => (_tenantAccessor?.TenantId).NormalizeTenantId(); |
| | | 48 | | |
| | | 49 | | private static Channel<object?> CreateChannel() |
| | | 50 | | { |
| | 202 | 51 | | var options = new BoundedChannelOptions(1) |
| | 202 | 52 | | { |
| | 202 | 53 | | SingleReader = true, |
| | 202 | 54 | | SingleWriter = false, |
| | 202 | 55 | | AllowSynchronousContinuations = false |
| | 202 | 56 | | }; |
| | 202 | 57 | | return Channel.CreateBounded<object?>(options); |
| | | 58 | | } |
| | | 59 | | } |