| | | 1 | | using System.Runtime.CompilerServices; |
| | | 2 | | using System.Threading.Channels; |
| | | 3 | | |
| | | 4 | | namespace Intentum.Core.Streaming; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// In-memory behavior stream consumer with bounded capacity for backpressure. |
| | | 8 | | /// When the channel is full, <see cref="PostAsync"/> waits until space is available (backpressure). |
| | | 9 | | /// </summary> |
| | | 10 | | public sealed class BoundedMemoryBehaviorStreamConsumer : IBehaviorStreamConsumer |
| | | 11 | | { |
| | | 12 | | private readonly Channel<BehaviorEventBatch> _channel; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Creates a bounded consumer. When capacity is reached, PostAsync will wait (backpressure). |
| | | 16 | | /// </summary> |
| | | 17 | | /// <param name="capacity">Maximum number of batches to buffer; must be positive.</param> |
| | 0 | 18 | | public BoundedMemoryBehaviorStreamConsumer(int capacity) |
| | 0 | 19 | | { |
| | 0 | 20 | | if (capacity <= 0) |
| | 0 | 21 | | throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "Capacity must be positive."); |
| | 0 | 22 | | _channel = Channel.CreateBounded<BehaviorEventBatch>(new BoundedChannelOptions(capacity) |
| | 0 | 23 | | { |
| | 0 | 24 | | FullMode = BoundedChannelFullMode.Wait |
| | 0 | 25 | | }); |
| | 0 | 26 | | } |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Posts a batch to the stream. If the channel is full, waits until space is available (backpressure). |
| | | 30 | | /// </summary> |
| | | 31 | | public ValueTask PostAsync(BehaviorEventBatch batch, CancellationToken cancellationToken = default) |
| | 0 | 32 | | { |
| | 0 | 33 | | return _channel.Writer.WriteAsync(batch, cancellationToken); |
| | 0 | 34 | | } |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// Completes the writer so ReadAllAsync will finish after all posted batches are read. |
| | | 38 | | /// </summary> |
| | | 39 | | public void Complete() |
| | 0 | 40 | | { |
| | 0 | 41 | | _channel.Writer.Complete(); |
| | 0 | 42 | | } |
| | | 43 | | |
| | | 44 | | /// <inheritdoc /> |
| | | 45 | | public async IAsyncEnumerable<BehaviorEventBatch> ReadAllAsync([EnumeratorCancellation] CancellationToken cancellati |
| | 0 | 46 | | { |
| | 0 | 47 | | await foreach (var batch in _channel.Reader.ReadAllAsync(cancellationToken)) |
| | 0 | 48 | | yield return batch; |
| | 0 | 49 | | } |
| | | 50 | | } |