| | | 1 | | using CounterpointCollective.Collections; |
| | | 2 | | using CounterpointCollective.Dataflow.Encapsulation; |
| | | 3 | | using CounterpointCollective.Dataflow.Fluent; |
| | | 4 | | using CounterpointCollective.Dataflow.Internal; |
| | | 5 | | using CounterpointCollective.Dataflow.Notifying; |
| | | 6 | | using CounterpointCollective.Threading; |
| | | 7 | | using System.Collections.Generic; |
| | | 8 | | using System.Threading; |
| | | 9 | | using System.Threading.Tasks; |
| | | 10 | | using System.Threading.Tasks.Dataflow; |
| | | 11 | | |
| | | 12 | | namespace CounterpointCollective.Dataflow |
| | | 13 | | { |
| | | 14 | | public class PriorityBufferBlock<T, TPriority> |
| | | 15 | | : AbstractEncapsulatedPropagatorBlock<(T Message, TPriority Priority), (T Message, TPriority Priority)> |
| | | 16 | | { |
| | | 17 | | private readonly BoundedPropagatorBlock<(T Message, TPriority Priority),(T Message, TPriority Priority)> _bounde |
| | 7 | 18 | | private readonly AsyncAutoResetEventSlim _holdElectionsSemaphore = new(false); |
| | 7 | 19 | | private readonly AsyncManualResetEventSlim _electionsHeld = new(); |
| | | 20 | | |
| | | 21 | | private TPriority worstPrioInElected = default!; |
| | 130 | 22 | | internal bool ElectionBufferContainsOutOfOrderItem { get; private set; } |
| | | 23 | | private int electedBufferCount; |
| | 0 | 24 | | internal int ElectedBufferCount => Volatile.Read(ref electedBufferCount); |
| | | 25 | | |
| | 27 | 26 | | protected override ITargetBlock<(T Message, TPriority Priority)> TargetSide => _boundedState; |
| | | 27 | | |
| | 64 | 28 | | protected override ISourceBlock<(T Message, TPriority Priority)> SourceSide => _boundedState; |
| | | 29 | | |
| | | 30 | | private readonly NotifyingSourceBlock<(T Message, TPriority Priority)> _outputBlock; |
| | | 31 | | |
| | | 32 | | public async Task AwaitElectionsHeldAsync() |
| | | 33 | | { |
| | 12 | 34 | | await _outputBlock.ProcessPendingEventsAsync(); |
| | 12 | 35 | | await _electionsHeld.WaitAsync(); |
| | 12 | 36 | | } |
| | | 37 | | |
| | 18 | 38 | | public int Count => _boundedState.Count; |
| | | 39 | | |
| | 4 | 40 | | public PriorityBufferBlock() : this(new()) |
| | 4 | 41 | | { } |
| | | 42 | | |
| | | 43 | | /// <param name="electedBufferSize"> |
| | | 44 | | /// The number of items to eagerly buffer for immediate consumption. |
| | | 45 | | /// |
| | | 46 | | /// A larger buffer can improve throughput when consuming messages, because more items are ready to be delivered |
| | | 47 | | /// However, a larger buffer also increases the likelihood of re-elections if new messages with higher priority |
| | | 48 | | /// Choose a value that balances consumption throughput against priority accuracy for your scenario. |
| | | 49 | | /// </param> |
| | | 50 | | public PriorityBufferBlock(DataflowBlockOptions options, int electedBufferSize = 1) |
| | 7 | 51 | | : this(Comparer<TPriority>.Default, options, electedBufferSize) |
| | 7 | 52 | | { } |
| | | 53 | | |
| | 7 | 54 | | public PriorityBufferBlock(IComparer<TPriority> comparer, DataflowBlockOptions options, int electedBufferSize = |
| | | 55 | | { |
| | | 56 | | void TriggerElection() |
| | | 57 | | { |
| | | 58 | | _electionsHeld.Reset(); |
| | | 59 | | _holdElectionsSemaphore.Set(); |
| | | 60 | | } |
| | | 61 | | |
| | 7 | 62 | | var inputQueue = new BufferBlock<(T Message, TPriority Priority)>(); |
| | | 63 | | |
| | 7 | 64 | | var queuedItems = new PriorityQueue<T, TPriority>(comparer); |
| | 7 | 65 | | var electionsCanTerminateGracefullyEvent = new AsyncManualResetEventSlim(); |
| | 7 | 66 | | electionsCanTerminateGracefullyEvent.Set(); |
| | | 67 | | |
| | 7 | 68 | | electedBufferCount = 0; |
| | 7 | 69 | | var electedBuffer = |
| | 7 | 70 | | new BufferBlock<(T Message, TPriority Priority)>( |
| | 7 | 71 | | new() |
| | 7 | 72 | | { |
| | 7 | 73 | | BoundedCapacity = electedBufferSize, |
| | 7 | 74 | | CancellationToken = options.CancellationToken |
| | 7 | 75 | | }); |
| | | 76 | | |
| | | 77 | | |
| | 7 | 78 | | var electionTask = |
| | 7 | 79 | | Task.Run(async () => |
| | 7 | 80 | | { |
| | 38 | 81 | | while (true) |
| | 7 | 82 | | { |
| | 45 | 83 | | var t = await Task.WhenAny(_holdElectionsSemaphore.WaitOneAsync()); |
| | 7 | 84 | | |
| | 40 | 85 | | if (!t.IsCompletedSuccessfully) |
| | 7 | 86 | | { |
| | 7 | 87 | | break; |
| | 7 | 88 | | } |
| | 7 | 89 | | |
| | 7 | 90 | | //Add new items to the queue |
| | 38 | 91 | | if (inputQueue.TryReceiveAll(out var ii)) |
| | 7 | 92 | | { |
| | 22 | 93 | | queuedItems.EnqueueRange(ii); |
| | 7 | 94 | | } |
| | 7 | 95 | | |
| | 7 | 96 | | //Check if the queue has an item that should go before the electedBuffer's last item. |
| | 38 | 97 | | ElectionBufferContainsOutOfOrderItem = electedBufferCount == 0 |
| | 38 | 98 | | ? false |
| | 38 | 99 | | : ElectionBufferContainsOutOfOrderItem || |
| | 38 | 100 | | ( |
| | 38 | 101 | | queuedItems.TryPeek(out var _, out var bestPriorityInQueue) |
| | 38 | 102 | | && comparer.Compare(bestPriorityInQueue, worstPrioInElected) < 0 |
| | 38 | 103 | | ); |
| | 7 | 104 | | |
| | 7 | 105 | | //If so, try to reclaim electedBuffer's items and add them to the queue too. |
| | 38 | 106 | | if (ElectionBufferContainsOutOfOrderItem && electedBuffer.TryReceiveAll(out var oldItems)) |
| | 7 | 107 | | { |
| | 4 | 108 | | ElectionBufferContainsOutOfOrderItem = false; |
| | 4 | 109 | | Interlocked.Add(ref electedBufferCount, -oldItems.Count); |
| | 4 | 110 | | queuedItems.EnqueueRange(oldItems); //O(m log(n+m)), m is expected to be small. |
| | 7 | 111 | | } |
| | 7 | 112 | | |
| | 38 | 113 | | if (queuedItems.Count == 0 && !ElectionBufferContainsOutOfOrderItem) |
| | 7 | 114 | | { |
| | 5 | 115 | | electionsCanTerminateGracefullyEvent.Set(); |
| | 7 | 116 | | } |
| | 7 | 117 | | else |
| | 7 | 118 | | { |
| | 33 | 119 | | electionsCanTerminateGracefullyEvent.Reset(); |
| | 33 | 120 | | if (!ElectionBufferContainsOutOfOrderItem) |
| | 7 | 121 | | { |
| | 59 | 122 | | while (electedBufferCount < electedBufferSize && queuedItems.TryDequeue(out var m, out v |
| | 7 | 123 | | { |
| | 29 | 124 | | worstPrioInElected = p; |
| | 29 | 125 | | await electedBuffer.SendAsync((m, p)); |
| | 29 | 126 | | Interlocked.Increment(ref electedBufferCount); |
| | 29 | 127 | | } |
| | 7 | 128 | | } |
| | 7 | 129 | | } |
| | 38 | 130 | | _electionsHeld.Set(); |
| | 7 | 131 | | } |
| | 9 | 132 | | }); |
| | | 133 | | |
| | 7 | 134 | | _outputBlock = electedBuffer.WithNotification(h => |
| | 7 | 135 | | { |
| | 7 | 136 | | h.OnDeliveringMessages = count => |
| | 7 | 137 | | { |
| | 20 | 138 | | Interlocked.Add(ref electedBufferCount, -count); |
| | 20 | 139 | | TriggerElection(); |
| | 27 | 140 | | }; |
| | 9 | 141 | | h.OnReservationReleased = () => TriggerElection(); |
| | 14 | 142 | | h.ConfigureDispatching = q => q.UseSynchronousDispatch(); |
| | 7 | 143 | | } |
| | 7 | 144 | | ); |
| | | 145 | | |
| | 7 | 146 | | inputQueue.Completion.ContinueWith(async t => |
| | 7 | 147 | | { |
| | 2 | 148 | | if (t.IsCompletedSuccessfully) |
| | 7 | 149 | | { |
| | 2 | 150 | | await electionsCanTerminateGracefullyEvent.WaitAsync(); |
| | 7 | 151 | | } |
| | 2 | 152 | | _holdElectionsSemaphore.Terminate(); |
| | 2 | 153 | | queuedItems.Clear(); |
| | 9 | 154 | | }); |
| | | 155 | | |
| | 7 | 156 | | electionTask.ContinueWith(_ => |
| | 7 | 157 | | { |
| | 2 | 158 | | _ = inputQueue.PropagateCompletion(electedBuffer); |
| | 9 | 159 | | }); |
| | | 160 | | |
| | 7 | 161 | | _boundedState = new BoundedPropagatorBlock< |
| | 7 | 162 | | (T Message, TPriority Priority), |
| | 7 | 163 | | (T Message, TPriority Priority)> |
| | 7 | 164 | | ( |
| | 7 | 165 | | inputQueue, |
| | 7 | 166 | | _outputBlock, |
| | 7 | 167 | | options.BoundedCapacity, |
| | 7 | 168 | | onEntered: TriggerElection |
| | 7 | 169 | | ); |
| | 7 | 170 | | } |
| | | 171 | | } |
| | | 172 | | } |