Path: redb-route/redb.Route.Sql/ConsumerRowStream.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/ConsumerRowStream.cs
----
using System.Data.Common;
using System.Runtime.CompilerServices;
namespace redb.Route.Sql;
/// Creates the body of a streaming poll delivered as one list, for a row type known only at run time.
internal static class ConsumerRowStream
{
/// A stream of rows over a reader positioned on its first row.
internal static object Create(Type elementType, DbDataReader reader, Func map, int maxRows) =>
Activator.CreateInstance(typeof(ConsumerRowStream<>).MakeGenericType(elementType), reader, map, maxRows)!;
}
///
/// The body of a poll with outputType=StreamList and pollDelivery=List: the rows of the consumer's open reader,
/// which is positioned on the first row. The consumer owns the reader and closes it as soon as the route is done, so the rows
/// are read once, while the route runs; at most maxMessagesPerPoll of them.
///
internal sealed class ConsumerRowStream(DbDataReader reader, Func map, int maxRows) : IAsyncEnumerable
{
private int _enumerated;
///
/// The rows were already read, or the route has finished.
public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _enumerated, 1) != 0)
throw new InvalidOperationException(
"The rows of a streaming poll (outputType=StreamList, pollDelivery=List) can be read once: they come from one open reader.");
if (reader.IsClosed)
throw new InvalidOperationException(
"The rows of a streaming poll (outputType=StreamList, pollDelivery=List) are read while the route runs; the reader is closed.");
return ReadRows(cancellationToken).GetAsyncEnumerator(cancellationToken);
}
private async IAsyncEnumerable ReadRows([EnumeratorCancellation] CancellationToken ct)
{
var count = 0;
do
{
if (maxRows >= 0 && count >= maxRows)
yield break;
yield return (T)map(reader);
count++;
}
while (await reader.ReadAsync(ct).ConfigureAwait(false));
}
}