From 4dea970ef48c2a7bd395b94bc1da795cd2716e74 Mon Sep 17 00:00:00 2001 From: majialong Date: Fri, 17 Jul 2026 13:03:15 +0800 Subject: [PATCH 1/3] [ISSUE #10620] Fix NPE when recording RPC latency for local proxy requests --- .../service/message/LocalRemotingCommand.java | 2 + .../message/LocalRemotingCommandTest.java | 80 +++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 proxy/src/test/java/org/apache/rocketmq/proxy/service/message/LocalRemotingCommandTest.java diff --git a/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalRemotingCommand.java b/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalRemotingCommand.java index 25066ea5305..9000170f0fd 100644 --- a/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalRemotingCommand.java +++ b/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalRemotingCommand.java @@ -16,6 +16,7 @@ */ package org.apache.rocketmq.proxy.service.message; +import com.google.common.base.Stopwatch; import java.util.HashMap; import org.apache.rocketmq.remoting.CommandCustomHeader; import org.apache.rocketmq.remoting.protocol.LanguageCode; @@ -31,6 +32,7 @@ public static LocalRemotingCommand createRequestCommand(int code, CommandCustomH cmd.setExtFields(new HashMap<>()); setCmdVersion(cmd); cmd.makeCustomHeaderToNet(); + cmd.setProcessTimer(Stopwatch.createStarted()); return cmd; } } diff --git a/proxy/src/test/java/org/apache/rocketmq/proxy/service/message/LocalRemotingCommandTest.java b/proxy/src/test/java/org/apache/rocketmq/proxy/service/message/LocalRemotingCommandTest.java new file mode 100644 index 00000000000..121f8d5e44f --- /dev/null +++ b/proxy/src/test/java/org/apache/rocketmq/proxy/service/message/LocalRemotingCommandTest.java @@ -0,0 +1,80 @@ +/* + * 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.rocketmq.proxy.service.message; + +import io.netty.channel.ChannelFuture; +import io.netty.channel.DefaultChannelPromise; +import io.netty.util.concurrent.ImmediateEventExecutor; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongHistogram; +import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.rocketmq.common.metrics.NopLongHistogram; +import org.apache.rocketmq.proxy.service.channel.SimpleChannel; +import org.apache.rocketmq.remoting.metrics.RemotingMetricsManager; +import org.apache.rocketmq.remoting.netty.NettyRemotingAbstract; +import org.apache.rocketmq.remoting.protocol.RemotingCommand; +import org.apache.rocketmq.remoting.protocol.RequestCode; +import org.junit.Test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class LocalRemotingCommandTest { + + @Test + public void testCreateRequestCommandShouldStartProcessTimer() { + LocalRemotingCommand command = LocalRemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE, null, "JAVA"); + + assertNotNull(command.getProcessTimer()); + assertTrue(command.getProcessTimer().isRunning()); + } + + @Test + public void testWriteResponseShouldRecordLatencyForLocalRemotingCommand() { + LocalRemotingCommand command = LocalRemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE, null, "JAVA"); + RemotingCommand response = RemotingCommand.createResponseCommand(0, null); + AtomicBoolean latencyRecorded = new AtomicBoolean(false); + LongHistogram rpcLatency = new NopLongHistogram() { + @Override + public void record(long value, Attributes attributes) { + latencyRecorded.set(true); + } + }; + RemotingMetricsManager remotingMetricsManager = new RemotingMetricsManager() { + @Override + public LongHistogram getRpcLatency() { + return rpcLatency; + } + }; + SimpleChannel channel = new SimpleChannel("127.0.0.1:8080", "127.0.0.1:8081") { + @Override + public ChannelFuture writeAndFlush(Object msg) { + return new DefaultChannelPromise(this, ImmediateEventExecutor.INSTANCE).setSuccess(); + } + }; + + NettyRemotingAbstract.writeResponse( + channel, + command, + response, + null, + remotingMetricsManager + ); + + assertTrue(latencyRecorded.get()); + } +} From a6016f947c84f5adf08fe6ba42754949d95a3074 Mon Sep 17 00:00:00 2001 From: majialong Date: Fri, 17 Jul 2026 13:37:19 +0800 Subject: [PATCH 2/3] address AI comments --- .../rocketmq/proxy/service/message/LocalRemotingCommand.java | 1 + 1 file changed, 1 insertion(+) diff --git a/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalRemotingCommand.java b/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalRemotingCommand.java index 9000170f0fd..1d7b10e2cea 100644 --- a/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalRemotingCommand.java +++ b/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalRemotingCommand.java @@ -32,6 +32,7 @@ public static LocalRemotingCommand createRequestCommand(int code, CommandCustomH cmd.setExtFields(new HashMap<>()); setCmdVersion(cmd); cmd.makeCustomHeaderToNet(); + // Local requests bypass NettyDecoder, so initialize the processing timer explicitly. cmd.setProcessTimer(Stopwatch.createStarted()); return cmd; } From 044a934685662f8fd6b4fb1ebdbe7038df6763e7 Mon Sep 17 00:00:00 2001 From: majialong Date: Wed, 25 Nov 2026 14:12:19 +0800 Subject: [PATCH 3/3] [ISSUE #10620] Guard null processTimer in writeResponse and fix batchAckMessage command creation --- proxy/BUILD.bazel | 1 + .../service/message/LocalMessageService.java | 2 +- .../message/LocalMessageServiceTest.java | 23 +++++++++++++ .../remoting/netty/NettyRemotingAbstract.java | 14 ++++---- .../netty/NettyRemotingAbstractTest.java | 34 +++++++++++++++++++ 5 files changed, 67 insertions(+), 7 deletions(-) diff --git a/proxy/BUILD.bazel b/proxy/BUILD.bazel index f5883a2107c..9f5f4ebc40c 100644 --- a/proxy/BUILD.bazel +++ b/proxy/BUILD.bazel @@ -100,6 +100,7 @@ java_library( "@maven//:io_netty_netty_all", "@maven//:io_github_aliyunmq_rocketmq_grpc_netty_codec_haproxy", "@maven//:org_apache_commons_commons_lang3", + "@maven//:io_opentelemetry_opentelemetry_api", "@maven//:io_opentelemetry_opentelemetry_exporter_otlp", "@maven//:io_opentelemetry_opentelemetry_exporter_prometheus", "@maven//:io_opentelemetry_opentelemetry_sdk", diff --git a/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalMessageService.java b/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalMessageService.java index a14b09665eb..fa47744cc76 100644 --- a/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalMessageService.java +++ b/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalMessageService.java @@ -445,7 +445,7 @@ public CompletableFuture batchAckMessage(ProxyContext ctx, List batchAckMap = new HashMap<>(); for (ReceiptHandleMessage receiptHandleMessage : handleList) { diff --git a/proxy/src/test/java/org/apache/rocketmq/proxy/service/message/LocalMessageServiceTest.java b/proxy/src/test/java/org/apache/rocketmq/proxy/service/message/LocalMessageServiceTest.java index a0fe3b9c981..d24fe905d19 100644 --- a/proxy/src/test/java/org/apache/rocketmq/proxy/service/message/LocalMessageServiceTest.java +++ b/proxy/src/test/java/org/apache/rocketmq/proxy/service/message/LocalMessageServiceTest.java @@ -62,6 +62,7 @@ import org.apache.rocketmq.proxy.service.channel.SimpleChannelHandlerContext; import org.apache.rocketmq.proxy.service.route.AddressableMessageQueue; import org.apache.rocketmq.remoting.exception.RemotingCommandException; +import org.apache.rocketmq.remoting.protocol.LanguageCode; import org.apache.rocketmq.remoting.protocol.RemotingCommand; import org.apache.rocketmq.remoting.protocol.RequestCode; import org.apache.rocketmq.remoting.protocol.ResponseCode; @@ -604,6 +605,28 @@ public void testAckMessage() throws Exception { assertThat(ackResult.getStatus()).isEqualTo(AckStatus.OK); } + @Test + public void testBatchAckMessage() throws Exception { + String messageId = "messageId"; + long popTime = System.currentTimeMillis(); + long invisibleTime = 3000L; + int reviveQueueId = 1; + String extraInfo = ExtraInfoUtil.buildExtraInfo(0L, popTime, invisibleTime, reviveQueueId, + topic, brokerName, queueId, queueOffset); + ReceiptHandle handle = ReceiptHandle.decode(extraInfo); + proxyContext.withVal(ContextVariable.LANGUAGE, LanguageCode.GO.name()); + RemotingCommand remotingCommand = RemotingCommand.createResponseCommand(ResponseCode.SUCCESS, null); + Mockito.when(ackMessageProcessorMock.processRequest(Mockito.any(SimpleChannelHandlerContext.class), Mockito.argThat(argument -> + argument instanceof LocalRemotingCommand + && argument.getCode() == RequestCode.BATCH_ACK_MESSAGE + && argument.getLanguage() == LanguageCode.GO + && argument.getProcessTimer() != null))).thenReturn(remotingCommand); + CompletableFuture future = localMessageService.batchAckMessage(proxyContext, + Collections.singletonList(new ReceiptHandleMessage(handle, messageId)), "group", topic, 1000L); + AckResult ackResult = future.get(); + assertThat(ackResult.getStatus()).isEqualTo(AckStatus.OK); + } + @Test public void testRecallMessage_success() throws Exception { RecallMessageResponseHeader responseHeader = new RecallMessageResponseHeader(); diff --git a/remoting/src/main/java/org/apache/rocketmq/remoting/netty/NettyRemotingAbstract.java b/remoting/src/main/java/org/apache/rocketmq/remoting/netty/NettyRemotingAbstract.java index a40aab3ae59..190a64c1c73 100644 --- a/remoting/src/main/java/org/apache/rocketmq/remoting/netty/NettyRemotingAbstract.java +++ b/remoting/src/main/java/org/apache/rocketmq/remoting/netty/NettyRemotingAbstract.java @@ -16,6 +16,7 @@ */ package org.apache.rocketmq.remoting.netty; +import com.google.common.base.Stopwatch; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; @@ -235,8 +236,9 @@ public static void writeResponse(Channel channel, RemotingCommand request, @Null if (response == null) { return; } + final Stopwatch processTimer = request.getProcessTimer(); final AttributesBuilder attributesBuilder; - if (remotingMetricsManager != null) { + if (remotingMetricsManager != null && processTimer != null) { attributesBuilder = remotingMetricsManager.newAttributesBuilder(); attributesBuilder.put(LABEL_IS_LONG_POLLING, request.isSuspended()) .put(LABEL_REQUEST_CODE, RemotingHelper.getRequestCodeDesc(request.getCode())) @@ -247,7 +249,7 @@ public static void writeResponse(Channel channel, RemotingCommand request, @Null if (request.isOnewayRPC()) { if (attributesBuilder != null) { attributesBuilder.put(LABEL_RESULT, RESULT_ONEWAY); - remotingMetricsManager.getRpcLatency().record(request.getProcessTimer().elapsed(TimeUnit.MILLISECONDS), attributesBuilder.build()); + remotingMetricsManager.getRpcLatency().record(processTimer.elapsed(TimeUnit.MILLISECONDS), attributesBuilder.build()); } return; } @@ -262,9 +264,9 @@ public static void writeResponse(Channel channel, RemotingCommand request, @Null log.error("Failed to write response[request code: {}, response code: {}, opaque: {}] to channel{}", request.getCode(), response.getCode(), response.getOpaque(), channel, future.cause()); } - if (remotingMetricsManager != null) { + if (attributesBuilder != null) { attributesBuilder.put(LABEL_RESULT, remotingMetricsManager.getWriteAndFlushResult(future)); - remotingMetricsManager.getRpcLatency().record(request.getProcessTimer().elapsed(TimeUnit.MILLISECONDS), attributesBuilder.build()); + remotingMetricsManager.getRpcLatency().record(processTimer.elapsed(TimeUnit.MILLISECONDS), attributesBuilder.build()); } if (callback != null) { callback.accept(future); @@ -274,9 +276,9 @@ public static void writeResponse(Channel channel, RemotingCommand request, @Null log.error("process request over, but response failed", e); log.error(request.toString()); log.error(response.toString()); - if (remotingMetricsManager != null) { + if (attributesBuilder != null) { attributesBuilder.put(LABEL_RESULT, RESULT_WRITE_CHANNEL_FAILED); - remotingMetricsManager.getRpcLatency().record(request.getProcessTimer().elapsed(TimeUnit.MILLISECONDS), attributesBuilder.build()); + remotingMetricsManager.getRpcLatency().record(processTimer.elapsed(TimeUnit.MILLISECONDS), attributesBuilder.build()); } } diff --git a/remoting/src/test/java/org/apache/rocketmq/remoting/netty/NettyRemotingAbstractTest.java b/remoting/src/test/java/org/apache/rocketmq/remoting/netty/NettyRemotingAbstractTest.java index dbbea86ea2f..31e0725d67b 100644 --- a/remoting/src/test/java/org/apache/rocketmq/remoting/netty/NettyRemotingAbstractTest.java +++ b/remoting/src/test/java/org/apache/rocketmq/remoting/netty/NettyRemotingAbstractTest.java @@ -16,9 +16,14 @@ */ package org.apache.rocketmq.remoting.netty; +import io.netty.channel.Channel; +import io.netty.channel.DefaultChannelPromise; +import io.netty.util.concurrent.ImmediateEventExecutor; import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.rocketmq.remoting.InvokeCallback; import org.apache.rocketmq.remoting.common.SemaphoreReleaseOnlyOnce; +import org.apache.rocketmq.remoting.metrics.RemotingMetricsManager; import org.apache.rocketmq.remoting.protocol.RemotingCommand; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,6 +32,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @@ -168,4 +178,28 @@ public void operationFail(Throwable throwable) { semaphore.acquire(1); assertThat(semaphore.availablePermits()).isEqualTo(0); } + + @Test + public void testWriteResponseWithNullProcessTimer() { + RemotingMetricsManager remotingMetricsManager = spy(new RemotingMetricsManager()); + Channel channel = mock(Channel.class); + when(channel.writeAndFlush(any())).thenAnswer(invocation -> + new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE).setSuccess()); + + RemotingCommand request = RemotingCommand.createRequestCommand(1, null); + RemotingCommand response = RemotingCommand.createResponseCommand(0, null); + AtomicBoolean callbackInvoked = new AtomicBoolean(false); + NettyRemotingAbstract.writeResponse(channel, request, response, future -> callbackInvoked.set(true), remotingMetricsManager); + assertTrue(callbackInvoked.get()); + + RemotingCommand onewayRequest = RemotingCommand.createRequestCommand(1, null); + onewayRequest.markOnewayRPC(); + NettyRemotingAbstract.writeResponse(channel, onewayRequest, RemotingCommand.createResponseCommand(0, null), null, remotingMetricsManager); + + Channel failingChannel = mock(Channel.class); + when(failingChannel.writeAndFlush(any())).thenThrow(new RuntimeException("write failed")); + NettyRemotingAbstract.writeResponse(failingChannel, request, RemotingCommand.createResponseCommand(0, null), null, remotingMetricsManager); + + verifyNoInteractions(remotingMetricsManager); + } } \ No newline at end of file