Path: redb-route/tests/redb.Route.Tests.Brokers/CrossBrokerBatchTests.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.Brokers/CrossBrokerBatchTests.cs ---- using System.Collections; using System.Text; using Confluent.Kafka; using Confluent.Kafka.Admin; using IBM.WMQ; using RabbitMQ.Client; using redb.Route.Core; using redb.Route.IbmMq; using redb.Route.Kafka; using redb.Route.RabbitMQ; using redb.Route.Tests.Kafka; namespace redb.Route.Tests.Brokers; /// /// A batch consumed from one broker and sent to another without a Split arrives as the same number of messages, each /// with its record's own body and headers, none of the batch exchange's: Kafka to RabbitMQ, RabbitMQ to IBM MQ, IBM MQ /// to Kafka. Needs the stand profiles kafka, rabbitmq and ibmmq. Waits are by condition, with a timeout. /// [Trait("Category", "Integration")] public sealed class CrossBrokerBatchTests : IAsyncLifetime { private const string KafkaServers = "localhost:29092,localhost:29094,localhost:29096"; private const string Rabbit = "host=localhost&port=5672&username=admin&password=admin"; private const string Mq = "host=localhost&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&user=app&password=admin"; private const string MqQueue = "DEV.QUEUE.LIST"; private const string MqBackoutQueue = "DEV.QUEUE.BATCH.BOQ"; public Task InitializeAsync() => KafkaReadiness.GroupCoordinatorAsync(); public Task DisposeAsync() => Task.CompletedTask; // ── Kafka ── /// A one-partition topic whose leader is known, so a verifying consumer can subscribe to it at once. private static Task KafkaTopic(string name) => KafkaReadiness.CreateSinglePartitionTopicAsync(name); private static async Task KafkaProduce(string topic, params string[] values) { using var producer = new ProducerBuilder(new ProducerConfig { BootstrapServers = KafkaServers }).Build(); foreach (var value in values) { var message = new Message { Key = "k-" + value, Value = value, Headers = new Confluent.Kafka.Headers() }; message.Headers.Add("XRecord", Encoding.UTF8.GetBytes("rec-" + value)); await producer.ProduceAsync(topic, message); } } private static List<(string Value, string? Record, string? Batch)> KafkaRead(string topic, int expected) { var config = new ConsumerConfig { BootstrapServers = KafkaServers, GroupId = $"verify-{Guid.NewGuid():N}", AutoOffsetReset = AutoOffsetReset.Earliest, }; using var consumer = new ConsumerBuilder(config).Build(); consumer.Subscribe(topic); var got = new List<(string, string?, string?)>(); var deadline = DateTime.UtcNow.AddSeconds(60); while (got.Count < expected && DateTime.UtcNow < deadline) { ConsumeResult? r; try { r = consumer.Consume(TimeSpan.FromMilliseconds(250)); } catch (ConsumeException ex) when (ex.Error.Code == ErrorCode.UnknownTopicOrPart) { // The consumer's metadata can lag behind a topic just created: it reports the topic until it knows it. continue; } if (r?.Message is null) continue; got.Add((Encoding.UTF8.GetString(r.Message.Value), Text(r.Message.Headers, "XRecord"), Text(r.Message.Headers, "XBatch"))); } consumer.Close(); return got; static string? Text(Confluent.Kafka.Headers headers, string name) => headers.TryGetLastBytes(name, out var bytes) ? Encoding.UTF8.GetString(bytes) : null; } // ── RabbitMQ ── private static async Task RabbitConnect() => await new ConnectionFactory { HostName = "localhost", Port = 5672, UserName = "admin", Password = "admin" }.CreateConnectionAsync(); private static string? RabbitHeader(IReadOnlyBasicProperties properties, string name) => properties.Headers is not null && properties.Headers.TryGetValue(name, out var value) ? value is byte[] bytes ? Encoding.UTF8.GetString(bytes) : value?.ToString() : null; // ── IBM MQ ── private static MQQueueManager MqConnect() => new("QM1", new Hashtable { [MQC.HOST_NAME_PROPERTY] = "localhost", [MQC.PORT_PROPERTY] = 1414, [MQC.CHANNEL_PROPERTY] = "DEV.APP.SVRCONN", [MQC.USER_ID_PROPERTY] = "app", [MQC.PASSWORD_PROPERTY] = "admin", [MQC.TRANSPORT_PROPERTY] = MQC.TRANSPORT_MQSERIES_MANAGED, }); private static List<(string Body, string? Catalogue)> MqTake(int expected, bool drainOnly = false) { var got = new List<(string, string?)>(); using var qm = MqConnect(); var q = qm.AccessQueue(MqQueue, MQC.MQOO_INPUT_SHARED | MQC.MQOO_FAIL_IF_QUIESCING); try { var deadline = DateTime.UtcNow.AddSeconds(drainOnly ? 0 : 60); var gmo = new MQGetMessageOptions { Options = MQC.MQGMO_WAIT | MQC.MQGMO_NO_SYNCPOINT, WaitInterval = 500 }; while (drainOnly || (got.Count < expected && DateTime.UtcNow < deadline)) { var message = new MQMessage(); try { q.Get(message, gmo); } catch (MQException ex) when (ex.ReasonCode == MQC.MQRC_NO_MSG_AVAILABLE) { if (drainOnly) break; continue; } string? catalogue = null; try { catalogue = message.GetStringProperty("redbIbmMqHeaders"); } catch (MQException) { /* no headers */ } got.Add((message.ReadString(message.MessageLength), catalogue)); } } finally { q.Close(); qm.Disconnect(); } return got; } private static void MqPut(params string[] bodies) { using var qm = MqConnect(); var q = qm.AccessQueue(MqQueue, MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING); foreach (var body in bodies) { var message = new MQMessage { Format = MQC.MQFMT_STRING }; // The connector carries a message's headers as one JSON property, as its own producer writes them. message.SetStringProperty("redbIbmMqHeaders", System.Text.Json.JsonSerializer.Serialize(new Dictionary { ["XRecord"] = "rec-" + body })); message.WriteString(body); q.Put(message); } q.Close(); qm.Disconnect(); } private static async Task Start(Action routes) { var context = new RouteContext(); context.AddComponent(new KafkaComponent()); context.AddComponent(new RabbitMQComponent()); context.AddComponent(new IbmMqComponent()); context.AddRoutes(routes); await context.Start(); return context; } [Fact] public async Task A_Kafka_batch_sent_to_RabbitMQ_arrives_as_one_message_per_record_with_its_own_headers() { var topic = await KafkaTopic("x-kafka"); await KafkaProduce(topic, "a", "b", "c"); var queue = $"x-rabbit-{Guid.NewGuid():N}"; await using var connection = await RabbitConnect(); await using var channel = await connection.CreateChannelAsync(); await channel.QueueDeclareAsync(queue, durable: true, exclusive: false, autoDelete: false); var got = new List<(string Body, string? Record, string? Batch)>(); try { await using (await Start(r => r .From($"kafka://{topic}?brokers={KafkaServers}&groupId=g-{Guid.NewGuid():N}&autoOffsetReset=earliest" + "&batching=true&maxBatchMessages=3&pollTimeoutMs=3000") .SetHeader("XBatch", "batch-level") .To($"rabbitmq://{queue}?{Rabbit}"))) { var deadline = DateTime.UtcNow.AddSeconds(60); while (got.Count < 3 && DateTime.UtcNow < deadline) { var item = await channel.BasicGetAsync(queue, autoAck: true); if (item is null) { await Task.Delay(200); continue; } got.Add((Encoding.UTF8.GetString(item.Body.Span), RabbitHeader(item.BasicProperties, "XRecord"), RabbitHeader(item.BasicProperties, "XBatch"))); } } } finally { await channel.QueueDeleteAsync(queue); } got.Select(g => g.Body).Should().Equal("a", "b", "c"); got.Select(g => g.Record).Should().Equal("rec-a", "rec-b", "rec-c"); got.Should().AllSatisfy(g => g.Batch.Should().BeNull("the batch exchange's headers are not the records'")); } [Fact] public async Task A_RabbitMQ_batch_sent_to_IBM_MQ_arrives_as_one_message_per_delivery_with_its_own_headers() { MqTake(0, drainOnly: true); var queue = $"x-rabbit-{Guid.NewGuid():N}"; await using var connection = await RabbitConnect(); await using var channel = await connection.CreateChannelAsync(); await channel.QueueDeclareAsync(queue, durable: true, exclusive: false, autoDelete: false); foreach (var body in new[] { "a", "b", "c" }) await channel.BasicPublishAsync(string.Empty, queue, mandatory: false, new BasicProperties { Headers = new Dictionary { ["XRecord"] = "rec-" + body } }, Encoding.UTF8.GetBytes(body)); List<(string Body, string? Catalogue)> got; try { await using (await Start(r => r .From($"rabbitmq://{queue}?{Rabbit}&batching=true&maxBatchMessages=3&pollTimeoutMs=3000") .SetHeader("XBatch", "batch-level") .To($"wmq:{MqQueue}?{Mq}"))) { got = MqTake(3); } } finally { await channel.QueueDeleteAsync(queue); } got.Select(g => g.Body).Should().Equal("a", "b", "c"); got.Should().AllSatisfy(g => g.Catalogue.Should().Contain("rec-").And.NotContain("batch-level")); } [Fact] public async Task An_IBM_MQ_batch_sent_to_Kafka_arrives_as_one_record_per_message_with_its_own_headers() { MqTake(0, drainOnly: true); MqPut("a", "b", "c"); var topic = await KafkaTopic("x-mq"); await using (await Start(r => r .From($"wmq:{MqQueue}?{Mq}&batching=true&maxBatchMessages=3&pollTimeoutMs=3000&backoutQueue={MqBackoutQueue}") .SetHeader("XBatch", "batch-level") .To($"kafka://{topic}?brokers={KafkaServers}"))) { var got = KafkaRead(topic, 3); got.Select(g => g.Value).Should().Equal("a", "b", "c"); got.Select(g => g.Record).Should().Equal("rec-a", "rec-b", "rec-c"); got.Should().AllSatisfy(g => g.Batch.Should().BeNull()); } } }