| | | 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: producer posts batches via Post; consumer reads via ReadAllAsync. |
| | | 8 | | /// Useful for testing and single-node scenarios. |
| | | 9 | | /// </summary> |
| | | 10 | | public sealed class MemoryBehaviorStreamConsumer : IBehaviorStreamConsumer |
| | | 11 | | { |
| | 2 | 12 | | private readonly Channel<BehaviorEventBatch> _channel = Channel.CreateUnbounded<BehaviorEventBatch>( |
| | 2 | 13 | | new UnboundedChannelOptions { SingleReader = true, SingleWriter = false }); |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Posts a batch to the stream. Consumers will receive it from ReadAllAsync. |
| | | 17 | | /// </summary> |
| | | 18 | | public ValueTask PostAsync(BehaviorEventBatch batch, CancellationToken cancellationToken = default) |
| | 2 | 19 | | { |
| | 2 | 20 | | return _channel.Writer.WriteAsync(batch, cancellationToken); |
| | 2 | 21 | | } |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Completes the writer so ReadAllAsync will finish after all posted batches are read. |
| | | 25 | | /// </summary> |
| | | 26 | | public void Complete() |
| | 2 | 27 | | { |
| | 2 | 28 | | _channel.Writer.Complete(); |
| | 2 | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <inheritdoc /> |
| | | 32 | | public async IAsyncEnumerable<BehaviorEventBatch> ReadAllAsync([EnumeratorCancellation] CancellationToken cancellati |
| | 2 | 33 | | { |
| | 10 | 34 | | await foreach (var batch in _channel.Reader.ReadAllAsync(cancellationToken)) |
| | 2 | 35 | | yield return batch; |
| | 2 | 36 | | } |
| | | 37 | | } |