From 223f0a0f3eaf54b5926351dab5ba2a26a6b68e44 Mon Sep 17 00:00:00 2001 From: wy471x Date: Sun, 23 Aug 2026 18:53:15 +0800 Subject: [PATCH 1/2] fix: release inbound MqttPublishMessage payload ByteBuf and retain per subscriber write The inbound MqttPublishMessage payload ByteBuf was never released, leaking a native/pooled buffer on every PUBLISH. Fan-out to multiple subscriber channels also wrote the same ByteBuf without retaining it. Release the inbound message in channelRead, retain the payload across the asynchronous send, and use retainedDuplicate for each subscriber. Co-Authored-By: Claude --- .../protocol/mqtt/MqttTransportHandler.java | 15 ++-- .../apache/shenyu/protocol/mqtt/Publish.java | 18 +++-- .../mqtt/MqttTransportHandlerTest.java | 76 +++++++++++++++++++ .../shenyu/protocol/mqtt/PublishTest.java | 30 ++++++++ 4 files changed, 129 insertions(+), 10 deletions(-) create mode 100644 shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/MqttTransportHandlerTest.java diff --git a/shenyu-protocol/shenyu-protocol-mqtt/src/main/java/org/apache/shenyu/protocol/mqtt/MqttTransportHandler.java b/shenyu-protocol/shenyu-protocol-mqtt/src/main/java/org/apache/shenyu/protocol/mqtt/MqttTransportHandler.java index 49ddc8a058a3..b8d79f4c14bd 100644 --- a/shenyu-protocol/shenyu-protocol-mqtt/src/main/java/org/apache/shenyu/protocol/mqtt/MqttTransportHandler.java +++ b/shenyu-protocol/shenyu-protocol-mqtt/src/main/java/org/apache/shenyu/protocol/mqtt/MqttTransportHandler.java @@ -20,6 +20,7 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.mqtt.MqttMessage; +import io.netty.util.ReferenceCountUtil; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; @@ -30,11 +31,15 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement @Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { - if (msg instanceof MqttMessage) { - MqttFactory mqttFactory = new MqttFactory((MqttMessage) msg, ctx); - mqttFactory.connect(); - } else { - ctx.close(); + try { + if (msg instanceof MqttMessage) { + MqttFactory mqttFactory = new MqttFactory((MqttMessage) msg, ctx); + mqttFactory.connect(); + } else { + ctx.close(); + } + } finally { + ReferenceCountUtil.release(msg); } } diff --git a/shenyu-protocol/shenyu-protocol-mqtt/src/main/java/org/apache/shenyu/protocol/mqtt/Publish.java b/shenyu-protocol/shenyu-protocol-mqtt/src/main/java/org/apache/shenyu/protocol/mqtt/Publish.java index bd7f48ef9667..57adb9303055 100644 --- a/shenyu-protocol/shenyu-protocol-mqtt/src/main/java/org/apache/shenyu/protocol/mqtt/Publish.java +++ b/shenyu-protocol/shenyu-protocol-mqtt/src/main/java/org/apache/shenyu/protocol/mqtt/Publish.java @@ -18,7 +18,6 @@ package org.apache.shenyu.protocol.mqtt; import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.mqtt.MqttFixedHeader; @@ -28,6 +27,7 @@ import io.netty.handler.codec.mqtt.MqttPubAckMessage; import io.netty.handler.codec.mqtt.MqttMessageType; import io.netty.handler.codec.mqtt.MqttPublishVariableHeader; +import io.netty.util.ReferenceCountUtil; import org.apache.shenyu.common.utils.Singleton; import org.apache.shenyu.protocol.mqtt.repositories.SubscribeRepository; import org.apache.shenyu.protocol.mqtt.repositories.TopicRepository; @@ -50,8 +50,6 @@ public void publish(final ChannelHandlerContext ctx, final MqttPublishMessage ms String topic = msg.variableHeader().topicName(); ByteBuf payload = msg.payload(); String message = byteBufToString(payload); - //// todo qos - MqttQoS mqttQoS = msg.fixedHeader().qosLevel(); if (msg.fixedHeader().isRetain()) { if (payload.isReadable()) { Singleton.INST.get(TopicRepository.class).add(topic, message); @@ -60,8 +58,18 @@ public void publish(final ChannelHandlerContext ctx, final MqttPublishMessage ms } } int packetId = msg.variableHeader().packetId(); - CompletableFuture.runAsync(() -> send(topic, payload, packetId)); + // The inbound message is released by MqttTransportHandler once publish returns, retain the payload for the asynchronous send. + payload.retain(); + CompletableFuture.runAsync(() -> { + try { + send(topic, payload, packetId); + } finally { + ReferenceCountUtil.safeRelease(payload); + } + }); + //// todo qos + MqttQoS mqttQoS = msg.fixedHeader().qosLevel(); switch (mqttQoS.value()) { case 0: break; @@ -125,7 +133,7 @@ private void send(final String topic, final ByteBuf payload, final int packetId) if (channel.isActive()) { MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttPublishVariableHeader mqttPublishVariableHeader = new MqttPublishVariableHeader(topic, packetId); - MqttPublishMessage mqttPublishMessage = new MqttPublishMessage(mqttFixedHeader, mqttPublishVariableHeader, Unpooled.wrappedBuffer(payload)); + MqttPublishMessage mqttPublishMessage = new MqttPublishMessage(mqttFixedHeader, mqttPublishVariableHeader, payload.retainedDuplicate()); channel.writeAndFlush(mqttPublishMessage); } }); diff --git a/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/MqttTransportHandlerTest.java b/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/MqttTransportHandlerTest.java new file mode 100644 index 000000000000..d001ab2e4a59 --- /dev/null +++ b/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/MqttTransportHandlerTest.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.shenyu.protocol.mqtt; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.mqtt.MqttFixedHeader; +import io.netty.handler.codec.mqtt.MqttMessageType; +import io.netty.handler.codec.mqtt.MqttPublishMessage; +import io.netty.handler.codec.mqtt.MqttPublishVariableHeader; +import io.netty.handler.codec.mqtt.MqttQoS; +import io.netty.util.CharsetUtil; +import io.netty.util.IllegalReferenceCountException; +import org.apache.shenyu.common.utils.Singleton; +import org.apache.shenyu.protocol.mqtt.repositories.SubscribeRepository; +import org.apache.shenyu.protocol.mqtt.repositories.TopicRepository; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.time.Duration; + +import static org.awaitility.Awaitility.await; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +/** + * Test cases for {@link MqttTransportHandler}. + */ +public final class MqttTransportHandlerTest { + + @BeforeAll + static void setUp() { + Singleton.INST.single(TopicRepository.class, new TopicRepository()); + Singleton.INST.single(SubscribeRepository.class, new SubscribeRepository()); + } + + @Test + public void channelReadReleasesInboundMessage() throws Exception { + MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, MqttQoS.AT_MOST_ONCE, false, 0); + MqttPublishVariableHeader variableHeader = new MqttPublishVariableHeader("test/topic", 1); + MqttPublishMessage msg = new MqttPublishMessage(fixedHeader, variableHeader, Unpooled.copiedBuffer("hello", CharsetUtil.UTF_8)); + new MqttTransportHandler().channelRead(mock(ChannelHandlerContext.class), msg); + await().atMost(Duration.ofSeconds(5)) + .until(() -> { + try { + msg.payload().refCnt(); + return false; + } catch (IllegalReferenceCountException e) { + // refCnt() throws once the payload has been fully released. + return true; + } + }); + } + + @Test + public void channelReadClosesChannelForNonMqttMessage() throws Exception { + ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); + new MqttTransportHandler().channelRead(ctx, new Object()); + verify(ctx).close(); + } +} diff --git a/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/PublishTest.java b/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/PublishTest.java index 6d25ff035205..253f537008fd 100644 --- a/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/PublishTest.java +++ b/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/PublishTest.java @@ -18,6 +18,7 @@ package org.apache.shenyu.protocol.mqtt; import io.netty.buffer.Unpooled; +import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.mqtt.MqttFixedHeader; import io.netty.handler.codec.mqtt.MqttMessageType; @@ -25,17 +26,24 @@ import io.netty.handler.codec.mqtt.MqttPublishVariableHeader; import io.netty.handler.codec.mqtt.MqttQoS; import io.netty.util.CharsetUtil; +import io.netty.util.ReferenceCountUtil; import org.apache.shenyu.common.utils.Singleton; import org.apache.shenyu.protocol.mqtt.repositories.SubscribeRepository; import org.apache.shenyu.protocol.mqtt.repositories.TopicRepository; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * Test cases for {@link Publish}. @@ -80,6 +88,28 @@ public void zeroByteRetainedPublishClearsRetainedMessage() { assertNull(topicRepository.get(CLEARED_TOPIC)); } + @Test + public void publishDeliversPayloadToEachSubscriber() { + Channel channel1 = mock(Channel.class); + when(channel1.isActive()).thenReturn(true); + Channel channel2 = mock(Channel.class); + when(channel2.isActive()).thenReturn(true); + SubscribeRepository subscribeRepository = Singleton.INST.get(SubscribeRepository.class); + subscribeRepository.add(Collections.singletonList("test/fanout"), Arrays.asList(channel1, channel2)); + await().atMost(Duration.ofSeconds(5)) + .until(() -> subscribeRepository.get("test/fanout").contains(channel1) && subscribeRepository.get("test/fanout").contains(channel2)); + MqttPublishMessage msg = publishMessage("test/fanout", "hello", false); + new Publish().publish(mock(ChannelHandlerContext.class), msg); + // one reference held by the inbound message plus one per active subscriber after the send completes. + await().atMost(Duration.ofSeconds(5)) + .until(() -> msg.payload().refCnt() == 3); + ArgumentCaptor captor = ArgumentCaptor.forClass(MqttPublishMessage.class); + verify(channel1).writeAndFlush(captor.capture()); + verify(channel2).writeAndFlush(captor.capture()); + captor.getAllValues().forEach(message -> assertEquals("hello", message.payload().toString(CharsetUtil.UTF_8))); + captor.getAllValues().forEach(ReferenceCountUtil::safeRelease); + } + private MqttPublishMessage publishMessage(final String topic, final String payload, final boolean retain) { MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, MqttQoS.AT_MOST_ONCE, retain, 0); MqttPublishVariableHeader variableHeader = new MqttPublishVariableHeader(topic, 1); From 444548cb8adc05c82e4aeabc876add731702c6d0 Mon Sep 17 00:00:00 2001 From: wy471x Date: Thu, 1 Oct 2026 17:13:08 +0800 Subject: [PATCH 2/2] test(mqtt): tidy up leak-fix tests and unbreak checkstyle - drop redundant imports failing RedundantImport - use EmbeddedChannel instead of a mock context that NPEs - fix invalid SubscribeRepository/Map API usages in PublishTest - remove duplicated tests, dead code and racy packet-id/refCnt assertions --- .../mqtt/MqttTransportHandlerTest.java | 94 ++++++------------- .../shenyu/protocol/mqtt/PublishTest.java | 64 ++----------- 2 files changed, 39 insertions(+), 119 deletions(-) diff --git a/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/MqttTransportHandlerTest.java b/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/MqttTransportHandlerTest.java index 46882aa33fd6..58c24665797a 100644 --- a/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/MqttTransportHandlerTest.java +++ b/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/MqttTransportHandlerTest.java @@ -17,12 +17,12 @@ package org.apache.shenyu.protocol.mqtt; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.mqtt.MqttConnectMessage; import io.netty.handler.codec.mqtt.MqttConnectPayload; import io.netty.handler.codec.mqtt.MqttConnectVariableHeader; -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.mqtt.MqttFixedHeader; import io.netty.handler.codec.mqtt.MqttMessageType; import io.netty.handler.codec.mqtt.MqttPublishMessage; @@ -31,7 +31,6 @@ import io.netty.handler.codec.mqtt.MqttTopicSubscription; import io.netty.handler.codec.mqtt.MqttVersion; import io.netty.util.CharsetUtil; -import io.netty.util.IllegalReferenceCountException; import org.apache.shenyu.common.utils.Singleton; import org.apache.shenyu.protocol.mqtt.repositories.ChannelRepository; import org.apache.shenyu.protocol.mqtt.repositories.SubscribeRepository; @@ -39,10 +38,6 @@ import org.awaitility.core.ThrowingRunnable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.AfterAll; -import org.apache.shenyu.protocol.mqtt.repositories.SubscribeRepository; -import org.apache.shenyu.protocol.mqtt.repositories.TopicRepository; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; @@ -54,9 +49,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.awaitility.Awaitility.await; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; /** * Test cases for {@link MqttTransportHandler}. @@ -71,8 +63,6 @@ public final class MqttTransportHandlerTest { private static final String PASSWORD = "test-password"; - private static ChannelRepository channelRepository; - private static final Duration TIMEOUT = Duration.ofSeconds(5); private static final Duration POLL_INTERVAL = Duration.ofMillis(10); @@ -87,22 +77,6 @@ public final class MqttTransportHandlerTest { private EmbeddedChannel registeredChannel; - @BeforeAll - static void setUpAll() { - Singleton.INST.single(TopicRepository.class, new TopicRepository()); - Singleton.INST.single(SubscribeRepository.class, new SubscribeRepository()); - channelRepository = new ChannelRepository(); - Singleton.INST.single(ChannelRepository.class, channelRepository); - new MqttContext().setUserName(USER_NAME); - new MqttContext().setPassword(PASSWORD); - } - - @AfterAll - static void tearDownAll() { - new MqttContext().setUserName(null); - new MqttContext().setPassword(null); - } - @BeforeEach public void setUp() { Singleton.INST.single(ChannelRepository.class, CHANNEL_REPOSITORY); @@ -133,51 +107,48 @@ public void tearDown() { new MqttContext().setPassword(null); } + @Test + public void channelReadReleasesInboundPublishMessage() { + EmbeddedChannel channel = new EmbeddedChannel(new MqttTransportHandler()); + MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, MqttQoS.AT_MOST_ONCE, false, 0); + MqttPublishVariableHeader variableHeader = new MqttPublishVariableHeader(TOPIC, 1); + MqttPublishMessage message = new MqttPublishMessage(fixedHeader, variableHeader, + Unpooled.copiedBuffer("hello", CharsetUtil.UTF_8)); + ByteBuf payload = message.payload(); + + channel.writeInbound(message); + + assertEquals(0, payload.refCnt()); + channel.finishAndReleaseAll(); + } + @Test public void duplicateConnectCleansUpChannelRepository() { EmbeddedChannel channel = new EmbeddedChannel(new MqttTransportHandler()); channel.writeInbound(connectMessage()); - assertEquals(CLIENT_ID, channelRepository.get(channel)); + assertEquals(CLIENT_ID, CHANNEL_REPOSITORY.get(channel)); channel.writeInbound(connectMessage()); channel.runPendingTasks(); assertFalse(channel.isActive()); - assertNull(channelRepository.get(channel)); + assertNull(CHANNEL_REPOSITORY.get(channel)); channel.finishAndReleaseAll(); } - @Test - public void channelReadReleasesInboundMessage() throws Exception { - MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, MqttQoS.AT_MOST_ONCE, false, 0); - MqttPublishVariableHeader variableHeader = new MqttPublishVariableHeader("test/topic", 1); - MqttPublishMessage msg = new MqttPublishMessage(fixedHeader, variableHeader, Unpooled.copiedBuffer("hello", CharsetUtil.UTF_8)); - new MqttTransportHandler().channelRead(mock(ChannelHandlerContext.class), msg); - await().atMost(Duration.ofSeconds(5)) - .until(() -> { - try { - msg.payload().refCnt(); - return false; - } catch (IllegalReferenceCountException e) { - // refCnt() throws once the payload has been fully released. - return true; - } - }); - } - @Test public void abruptChannelCloseCleansUpChannelRepository() { EmbeddedChannel channel = new EmbeddedChannel(new MqttTransportHandler()); channel.writeInbound(connectMessage()); - assertEquals(CLIENT_ID, channelRepository.get(channel)); + assertEquals(CLIENT_ID, CHANNEL_REPOSITORY.get(channel)); channel.close(); channel.runPendingTasks(); assertFalse(channel.isActive()); - assertNull(channelRepository.get(channel)); + assertNull(CHANNEL_REPOSITORY.get(channel)); channel.finishAndReleaseAll(); } @@ -196,10 +167,14 @@ public void nonMqttMessageClosesConnectedChannel() { } @Test - public void channelReadClosesChannelForNonMqttMessage() throws Exception { - ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); - new MqttTransportHandler().channelRead(ctx, new Object()); - verify(ctx).close(); + public void testOperationCompleteCleansRepositoriesOnClose() throws Exception { + assertEquals(1, MqttPacketIdGenerator.next(registeredChannel)); + + new MqttTransportHandler().operationComplete(registeredChannel.closeFuture()); + + awaitAssert(() -> assertNull(CHANNEL_REPOSITORY.get(registeredChannel))); + awaitAssert(() -> assertFalse(SUBSCRIBE_REPOSITORY.get(TOPIC).containsKey(registeredChannel))); + assertEquals(1, MqttPacketIdGenerator.next(registeredChannel)); } private MqttConnectMessage connectMessage() { @@ -212,17 +187,6 @@ private MqttConnectMessage connectMessage() { return new MqttConnectMessage(fixedHeader, variableHeader, payload); } - @Test - public void testOperationCompleteCleansRepositoriesOnClose() throws Exception { - assertEquals(1, MqttPacketIdGenerator.next(registeredChannel)); - - new MqttTransportHandler().operationComplete(registeredChannel.closeFuture()); - - awaitAssert(() -> assertNull(CHANNEL_REPOSITORY.get(registeredChannel))); - awaitAssert(() -> assertFalse(SUBSCRIBE_REPOSITORY.get(TOPIC).containsKey(registeredChannel))); - assertEquals(1, MqttPacketIdGenerator.next(registeredChannel)); - } - /** * The repositories mutate their state asynchronously on the common pool, * so assertions are retried until the mutation becomes visible. diff --git a/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/PublishTest.java b/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/PublishTest.java index c317ed72c3dd..a840b5dc0f3d 100644 --- a/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/PublishTest.java +++ b/shenyu-protocol/shenyu-protocol-mqtt/src/test/java/org/apache/shenyu/protocol/mqtt/PublishTest.java @@ -44,8 +44,6 @@ import org.apache.shenyu.protocol.mqtt.repositories.TopicRepository; import org.apache.shenyu.protocol.mqtt.utils.MqttPacketIdGenerator; import org.awaitility.core.ThrowingRunnable; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -95,8 +93,6 @@ public final class PublishTest { private static final String PASSWORD = "test-password"; - private static TopicRepository topicRepository; - private static final String PAYLOAD = "hello"; private static final int PUBLISHER_PACKET_ID = 12345; @@ -121,22 +117,6 @@ public final class PublishTest { private EmbeddedChannel publisherChannel; - @BeforeAll - static void setUpAll() { - topicRepository = new TopicRepository(); - Singleton.INST.single(TopicRepository.class, topicRepository); - Singleton.INST.single(SubscribeRepository.class, new SubscribeRepository()); - Singleton.INST.single(ChannelRepository.class, new ChannelRepository()); - new MqttContext().setUserName(USER_NAME); - new MqttContext().setPassword(PASSWORD); - } - - @AfterAll - static void tearDownAll() { - new MqttContext().setUserName(null); - new MqttContext().setPassword(null); - } - @BeforeEach public void setUp() { Singleton.INST.single(SubscribeRepository.class, SUBSCRIBE_REPOSITORY); @@ -165,15 +145,14 @@ public void tearDown() { @Test public void retainedPublishStoresMessage() { - new Publish().publish(mock(ChannelHandlerContext.class), publishMessage(RETAINED_TOPIC, "hello", true)); - await().atMost(Duration.ofSeconds(5)) - .until(() -> "hello".equals(topicRepository.get(RETAINED_TOPIC))); + new Publish().publish(publisherContext(), publishMessage(RETAINED_TOPIC, PAYLOAD, true)); + awaitAssert(() -> assertEquals(PAYLOAD, TOPIC_REPOSITORY.get(RETAINED_TOPIC))); } @Test public void nonRetainedPublishDoesNotStoreMessage() { - new Publish().publish(mock(ChannelHandlerContext.class), publishMessage(NON_RETAINED_TOPIC, "hello", false)); - assertNull(topicRepository.get(NON_RETAINED_TOPIC)); + new Publish().publish(publisherContext(), publishMessage(NON_RETAINED_TOPIC, PAYLOAD, false)); + assertNull(TOPIC_REPOSITORY.get(NON_RETAINED_TOPIC)); } @Test @@ -226,28 +205,6 @@ public void zeroByteRetainedPublishClearsRetainedMessage() { assertNull(TOPIC_REPOSITORY.get(CLEARED_TOPIC)); } - @Test - public void publishDeliversPayloadToEachSubscriber() { - Channel channel1 = mock(Channel.class); - when(channel1.isActive()).thenReturn(true); - Channel channel2 = mock(Channel.class); - when(channel2.isActive()).thenReturn(true); - SubscribeRepository subscribeRepository = Singleton.INST.get(SubscribeRepository.class); - subscribeRepository.add(Collections.singletonList("test/fanout"), Arrays.asList(channel1, channel2)); - await().atMost(Duration.ofSeconds(5)) - .until(() -> subscribeRepository.get("test/fanout").contains(channel1) && subscribeRepository.get("test/fanout").contains(channel2)); - MqttPublishMessage msg = publishMessage("test/fanout", "hello", false); - new Publish().publish(mock(ChannelHandlerContext.class), msg); - // one reference held by the inbound message plus one per active subscriber after the send completes. - await().atMost(Duration.ofSeconds(5)) - .until(() -> msg.payload().refCnt() == 3); - ArgumentCaptor captor = ArgumentCaptor.forClass(MqttPublishMessage.class); - verify(channel1).writeAndFlush(captor.capture()); - verify(channel2).writeAndFlush(captor.capture()); - captor.getAllValues().forEach(message -> assertEquals("hello", message.payload().toString(CharsetUtil.UTF_8))); - captor.getAllValues().forEach(ReferenceCountUtil::safeRelease); - } - @Test public void testPublishDeliversAtGrantedQosWithOwnPacketId() { addSubscriber(subscriberChannel, MqttQoS.AT_LEAST_ONCE); @@ -297,7 +254,11 @@ public void testPublishAllocatesPacketIdFromSubscriberIdSpace() { addSubscriber(subscriberChannel, MqttQoS.EXACTLY_ONCE); addSubscriber(otherSubscriberChannel, MqttQoS.EXACTLY_ONCE); + // wait for the first delivery so that the second publish cannot interleave packet id allocation publishToSubscribers(MqttQoS.EXACTLY_ONCE); + captureMessages(subscriberChannel, 1); + captureMessages(otherSubscriberChannel, 1); + publishToSubscribers(MqttQoS.EXACTLY_ONCE); List messages = captureMessages(subscriberChannel, 2); @@ -316,10 +277,11 @@ public void testPublishFanOutRetainsPayloadPerSubscriber() { ByteBuf payload = Unpooled.copiedBuffer(PAYLOAD, CharsetUtil.UTF_8); try { publishToSubscribers(MqttQoS.AT_LEAST_ONCE, payload); - awaitAssert(() -> assertEquals(3, payload.refCnt())); MqttPublishMessage delivered = captureMessage(subscriberChannel); MqttPublishMessage otherDelivered = captureMessage(otherSubscriberChannel); + // one reference held by the inbound message plus one retained duplicate per active subscriber + awaitAssert(() -> assertEquals(3, payload.refCnt())); assertEquals(PAYLOAD, delivered.payload().toString(CharsetUtil.UTF_8)); assertEquals(PAYLOAD, otherDelivered.payload().toString(CharsetUtil.UTF_8)); @@ -407,12 +369,6 @@ private T awaitOutbound(final EmbeddedChannel channel) { return channel.readOutbound(); } - private ChannelHandlerContext connectedContext() { - EmbeddedChannel channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter()); - new MessageType().setConnected(channel, true); - return channel.pipeline().lastContext(); - } - private MqttConnectMessage connectMessage() { MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttConnectVariableHeader variableHeader = new MqttConnectVariableHeader(