Path: redb-route/tests/redb.Route.Tests.Redis/RedisStreamBatchTests.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/tests/redb.Route.Tests.Redis/RedisStreamBatchTests.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Redis; using StackExchange.Redis; namespace redb.Route.Tests.Redis; /// The stream batch options on the core contract and every start refusal of batch mode. public sealed class RedisStreamBatchOptionsTests { private static RedisEndpoint Endpoint(string path, string query) => (RedisEndpoint)new RedisComponent().CreateEndpoint( EndpointUriParser.Parse($"redis:{path}?connectionString=localhost:6379&{query}")); [Fact] public void Batch_mode_is_off_by_default_and_on_with_batching() { Endpoint("XGROUP:s", "consumerGroup=g").EndpointOptions.Batch.Should().BeNull(); var batch = Endpoint("XGROUP:s", "consumerGroup=g&batching=true&streamReadCount=25").EndpointOptions.Batch!; batch.MaxMessages.Should().Be(25, "the default batch is streamReadCount"); batch.PollTimeout.Should().Be(TimeSpan.FromSeconds(1)); var tuned = Endpoint("XREAD:s", "batching=true&maxBatchMessages=50&pollTimeoutMs=200&batchingIntervalMs=3000") .EndpointOptions.Batch!; tuned.MaxMessages.Should().Be(50); tuned.Interval.Should().Be(TimeSpan.FromSeconds(3)); } [Theory] [InlineData("SUBSCRIBE:c", "batching=true", "*batching=true needs a stream consumer (XREAD or XGROUP); SUBSCRIBE*")] [InlineData("BLPOP:q", "batching=true", "*batching=true needs a stream consumer (XREAD or XGROUP); BLPOP*")] [InlineData("XGROUP:s", "consumerGroup=g&maxBatchMessages=5", "*sets maxBatchMessages without batching=true*")] [InlineData("XGROUP:s", "consumerGroup=g&batching=true&pollTimeoutMs=0", "*pollTimeoutMs must be positive*")] public void Batch_mode_that_cannot_work_fails_at_endpoint_creation(string path, string query, string message) { var act = () => Endpoint(path, query); act.Should().Throw().WithMessage(message); } [Fact] public void The_builder_writes_the_batch_options() { var uri = redb.Route.Redis.Redis.XGroup("s").ConsumerGroup("g").Batching().MaxBatchMessages(20).PollTimeoutMs(250) .BatchingIntervalMs(4000).Build(); uri.Should().Contain("batching=true").And.Contain("maxBatchMessages=20").And.Contain("pollTimeoutMs=250") .And.Contain("batchingIntervalMs=4000"); } } /// /// Stream batch mode against Redis (localhost:6379): a batch closes by size or by the idle timeout, its body is a list /// of one message per entry, and with a group it is acknowledged once after the route; a failed batch stays pending and /// is claimed again; without a group the position moves on. /// [Trait("Category", "Integration")] public sealed class RedisStreamBatchIntegrationTests { private static RedisEndpoint Endpoint(string path, string query) => (RedisEndpoint)new RedisComponent().CreateEndpoint( EndpointUriParser.Parse($"redis:{path}?connectionString=localhost:6379&{query}")); private sealed class Route(Func? fail = null) : IProcessor { public readonly ConcurrentQueue> Batches = new(); private int _calls; public Task Process(IExchange exchange, CancellationToken ct = default) { Batches.Enqueue(((List)exchange.In.Body!).ToList()); return fail?.Invoke(Interlocked.Increment(ref _calls)) == true ? throw new InvalidOperationException("batch fails") : Task.CompletedTask; } public static string Field(IMessage m) => (string)((IDictionary)m.Body!)["n"]!; public int Delivered => Batches.Sum(b => b.Count); } private static async Task ConsumeAsync(string path, string query, Route route, Func until, int settleMs = 800) { var endpoint = Endpoint(path, query); var consumer = endpoint.CreateConsumer(route); await consumer.Start(); try { var deadline = DateTime.UtcNow.AddSeconds(15); while (!until(route) && DateTime.UtcNow < deadline) await Task.Delay(50); await Task.Delay(settleMs); } finally { await consumer.Stop(); await endpoint.Stop(); } return route; } private static async Task<(IDatabase Db, string Stream, string Group)> SeedAsync(int count) { var db = await TestRedis.Database(); var stream = $"batch-{Guid.NewGuid():N}"; for (var i = 0; i < count; i++) await db.StreamAddAsync(stream, "n", $"e{i}"); return (db, stream, $"g-{Guid.NewGuid():N}"); } [Fact] public async Task A_group_batch_is_one_exchange_per_batch_and_acknowledged_once() { var (db, stream, group) = await SeedAsync(6); var route = await ConsumeAsync($"XGROUP:{stream}", $"consumerGroup={group}&streamStartPosition=0&streamBlockTimeMs=50&batching=true&maxBatchMessages=3&pollTimeoutMs=2000", new Route(), r => r.Delivered >= 6); route.Batches.Select(b => b.Count).Should().Equal(3, 3); route.Batches.SelectMany(b => b).Select(Route.Field).Should().Equal("e0", "e1", "e2", "e3", "e4", "e5"); route.Batches.SelectMany(b => b).Should().OnlyContain(m => (string)m.Headers[RedisHeaders.Stream]! == stream && (string)m.Headers[$"{RedisHeaders.StreamFieldPrefix}n"]! == Route.Field(m)); (await db.StreamPendingAsync(stream, group)).PendingMessageCount.Should().Be(0, "both batches were acknowledged"); } [Fact] public async Task A_batch_closes_by_the_idle_timeout_and_one_entry_is_a_list_too() { var (_, stream, group) = await SeedAsync(1); var route = await ConsumeAsync($"XGROUP:{stream}", $"consumerGroup={group}&streamStartPosition=0&streamBlockTimeMs=50&batching=true&maxBatchMessages=10&pollTimeoutMs=300", new Route(), r => r.Delivered >= 1); route.Batches.Should().ContainSingle().Which.Select(Route.Field).Should().Equal("e0"); } [Fact] public async Task A_failed_group_batch_stays_pending_and_is_claimed_again() { var (db, stream, group) = await SeedAsync(2); var route = await ConsumeAsync($"XGROUP:{stream}", $"consumerGroup={group}&streamStartPosition=0&streamBlockTimeMs=50&batching=true&maxBatchMessages=2" + "&pollTimeoutMs=500&streamClaimMinIdleMs=1000", new Route(fail: call => call == 1), r => r.Batches.Count >= 2); var batches = route.Batches.ToList(); batches.Should().HaveCount(2, "the pending entries are claimed after streamClaimMinIdleMs and acknowledged"); batches[1].Select(Route.Field).Should().BeEquivalentTo("e0", "e1"); (await db.StreamPendingAsync(stream, group)).PendingMessageCount.Should().Be(0); } [Fact] public async Task Without_claiming_a_failed_batch_stays_pending() { var (db, stream, group) = await SeedAsync(2); await ConsumeAsync($"XGROUP:{stream}", $"consumerGroup={group}&streamStartPosition=0&streamBlockTimeMs=50&batching=true&maxBatchMessages=2&pollTimeoutMs=500", new Route(fail: _ => true), r => r.Batches.Count >= 1); (await db.StreamPendingAsync(stream, group)).PendingMessageCount.Should().Be(2, "a failed entry is not acknowledged, as in single mode"); } [Fact] public async Task A_stop_leaves_the_unfinished_batch_pending() { var (db, stream, group) = await SeedAsync(2); var route = new Route(); var endpoint = Endpoint($"XGROUP:{stream}", $"consumerGroup={group}&streamStartPosition=0&streamBlockTimeMs=50&batching=true&maxBatchMessages=10&pollTimeoutMs=8000"); var consumer = endpoint.CreateConsumer(route); await consumer.Start(); await Task.Delay(1500); // both entries are in the collector; the idle timeout is far away await consumer.Stop(); await endpoint.Stop(); route.Batches.Should().BeEmpty("an interrupted batch is not run"); (await db.StreamPendingAsync(stream, group)).PendingMessageCount.Should().Be(2); } [Fact] public async Task Without_a_group_the_position_moves_past_a_failed_batch() { var (db, stream, _) = await SeedAsync(2); var route = new Route(fail: call => call == 1); var endpoint = Endpoint($"XREAD:{stream}", "streamStartPosition=0&streamBlockTimeMs=50&batching=true&maxBatchMessages=2&pollTimeoutMs=300"); var consumer = endpoint.CreateConsumer(route); await consumer.Start(); try { var deadline = DateTime.UtcNow.AddSeconds(10); while (route.Batches.IsEmpty && DateTime.UtcNow < deadline) await Task.Delay(50); await db.StreamAddAsync(stream, "n", "e2"); deadline = DateTime.UtcNow.AddSeconds(10); while (route.Batches.Count < 2 && DateTime.UtcNow < deadline) await Task.Delay(50); await Task.Delay(800); } finally { await consumer.Stop(); await endpoint.Stop(); } route.Batches.Select(b => b.Select(Route.Field).ToArray()).Should().BeEquivalentTo( [new[] { "e0", "e1" }, new[] { "e2" }], o => o.WithStrictOrdering()); } }