This is an automated email from the ASF dual-hosted git repository.

ShannonDing pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/rocketmq-ai.git


The following commit(s) were added to refs/heads/main by this push:
     new 40f3b07  fix(transport): register streaming listener before request 
send
40f3b07 is described below

commit 40f3b079a324c047e5d52b0c81841cafa5f4f92e
Author: qingli9374 <[email protected]>
AuthorDate: Mon Nov 23 22:51:29 2026 +0800

    fix(transport): register streaming listener before request send
    
    fix(transport): register streaming listener before request send
---
 rocketmq-a2a/pom.xml                               |   6 ++
 .../rocketmq/a2a/common/util/RocketMQUtil.java     |  22 ++++
 .../a2a/transport/impl/RocketMQTransport.java      |  18 +++-
 .../util/RocketMQUtilStreamRegistrationTest.java   | 113 +++++++++++++++++++++
 4 files changed, 157 insertions(+), 2 deletions(-)

diff --git a/rocketmq-a2a/pom.xml b/rocketmq-a2a/pom.xml
index f50c360..c49c777 100644
--- a/rocketmq-a2a/pom.xml
+++ b/rocketmq-a2a/pom.xml
@@ -148,6 +148,12 @@
             <version>${jakarta.ws.rs-api.version}</version>
             <scope>provided</scope>
         </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <version>4.13.2</version>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
 
     <build>
diff --git 
a/rocketmq-a2a/src/main/java/org/apache/rocketmq/a2a/common/util/RocketMQUtil.java
 
b/rocketmq-a2a/src/main/java/org/apache/rocketmq/a2a/common/util/RocketMQUtil.java
index 065ef9d..34854d3 100644
--- 
a/rocketmq-a2a/src/main/java/org/apache/rocketmq/a2a/common/util/RocketMQUtil.java
+++ 
b/rocketmq-a2a/src/main/java/org/apache/rocketmq/a2a/common/util/RocketMQUtil.java
@@ -30,6 +30,7 @@ import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
+import java.util.function.Consumer;
 import com.alibaba.fastjson.JSON;
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.core.type.TypeReference;
@@ -391,11 +392,31 @@ public class RocketMQUtil {
      * @throws ClientException if client send message fails.
      */
     public static String sendRocketMQRequest(PayloadAndHeaders 
payloadAndHeaders, String agentTopic, String liteTopic, String 
workAgentResponseTopic, Producer producer, String taskId)
+        throws JsonProcessingException, ClientException {
+        return sendRocketMQRequest(payloadAndHeaders, agentTopic, liteTopic, 
workAgentResponseTopic, producer, taskId,
+            requestId -> {
+            });
+    }
+
+    /**
+     * Sends a request and exposes its generated request ID before the message 
is submitted.
+     *
+     * <p>Streaming responses can arrive immediately after the producer 
returns. Registering the
+     * response listener from this callback closes the race between sending 
the request and adding
+     * the listener to {@link #MESSAGE_STREAM_RESPONSE_MAP}.</p>
+     *
+     * @param requestIdConsumer callback invoked with the request ID before 
the producer sends.
+     */
+    public static String sendRocketMQRequest(PayloadAndHeaders 
payloadAndHeaders, String agentTopic, String liteTopic,
+        String workAgentResponseTopic, Producer producer, String taskId, 
Consumer<String> requestIdConsumer)
         throws JsonProcessingException, ClientException {
         if (null == payloadAndHeaders || StringUtils.isEmpty(agentTopic) || 
StringUtils.isEmpty(liteTopic) || StringUtils.isEmpty(workAgentResponseTopic) 
|| null == producer) {
             log.warn("RocketMQUtil sendRocketMQRequest param is invalid, 
payloadAndHeaders: [{}], agentTopic: [{}], workAgentResponseTopic: [{}], 
liteTopic: [{}], producer: [{}]", payloadAndHeaders, agentTopic, 
workAgentResponseTopic, liteTopic, producer);
             throw new IllegalArgumentException("sendRocketMQRequest param is 
invalid");
         }
+        if (requestIdConsumer == null) {
+            throw new IllegalArgumentException("requestIdConsumer must not be 
null");
+        }
         //build RocketMQRequest
         String requestId = RequestIdGenerator.nextId();
         RocketMQRequest request = RocketMQRequest.builder()
@@ -426,6 +447,7 @@ public class RocketMQUtil {
             log.debug("RocketMQUtil sendRocketMQRequest send message to 
serverNormalTopic agentTopic: [{}]", agentTopic);
         }
         try {
+            requestIdConsumer.accept(requestId);
             SendReceipt sendReceipt = producer.send(message);
             log.debug("RocketMQUtil sendRocketMQRequest agentTopic: [{}], 
msgId: [{}], requestId: [{}]", agentTopic, sendReceipt.getMessageId(), 
requestId);
             return requestId;
diff --git 
a/rocketmq-a2a/src/main/java/org/apache/rocketmq/a2a/transport/impl/RocketMQTransport.java
 
b/rocketmq-a2a/src/main/java/org/apache/rocketmq/a2a/transport/impl/RocketMQTransport.java
index 87ccba6..f47e032 100644
--- 
a/rocketmq-a2a/src/main/java/org/apache/rocketmq/a2a/transport/impl/RocketMQTransport.java
+++ 
b/rocketmq-a2a/src/main/java/org/apache/rocketmq/a2a/transport/impl/RocketMQTransport.java
@@ -21,6 +21,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.UUID;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.function.Consumer;
 import javax.annotation.Nullable;
 import io.a2a.client.transport.spi.ClientTransport;
@@ -230,17 +231,30 @@ public class RocketMQTransport implements ClientTransport 
{
         checkNotNullParam("request", request);
         checkNotNullParam("request.message", request.message());
         checkNotNullParam("eventConsumer", eventConsumer);
+        AtomicReference<String> registeredRequestId = new AtomicReference<>();
         try {
             SendStreamingMessageRequest sendStreamingMessageRequest = new 
SendStreamingMessageRequest.Builder().jsonrpc(JSONRPCMessage.JSONRPC_VERSION).method(SendStreamingMessageRequest.METHOD).params(request).build();
             PayloadAndHeaders payloadAndHeaders = 
applyInterceptors(SendStreamingMessageRequest.METHOD, 
sendStreamingMessageRequest, this.agentCard, context);
-            String requestId = sendRocketMQRequest(payloadAndHeaders, 
this.agentTopic, 
resolveAndSubscribeLiteTopic(request.message().getContextId()), 
this.workAgentResponseTopic, this.producer, null);
+            String requestId = sendRocketMQRequest(payloadAndHeaders, 
this.agentTopic,
+                
resolveAndSubscribeLiteTopic(request.message().getContextId()), 
this.workAgentResponseTopic,
+                this.producer, null, id -> {
+                    
MESSAGE_STREAM_RESPONSE_MAP.computeIfAbsent(this.namespace, k -> new 
ConcurrentHashMap<>())
+                        .put(id, new SSEEventListener(eventConsumer, 
errorConsumer));
+                    registeredRequestId.set(id);
+                });
             if (StringUtils.isEmpty(requestId)) {
                 log.error("RocketMQTransport sendMessageStreaming error, 
requestId is empty");
                 return;
             }
-            MESSAGE_STREAM_RESPONSE_MAP.computeIfAbsent(this.namespace, k -> 
new ConcurrentHashMap<>()).put(requestId, new SSEEventListener(eventConsumer, 
errorConsumer));
             log.debug("RocketMQTransport sendMessageStreaming successfully, 
requestId: [{}]", requestId);
         } catch (Exception e) {
+            String requestId = registeredRequestId.get();
+            if (StringUtils.isNotEmpty(requestId)) {
+                Map<String, SSEEventListener> listeners = 
MESSAGE_STREAM_RESPONSE_MAP.get(this.namespace);
+                if (listeners != null) {
+                    listeners.remove(requestId);
+                }
+            }
             log.error("RocketMQTransport sendMessageStreaming error", e);
             throw new A2AClientException("RocketMQTransport 
sendMessageStreaming error", e);
         }
diff --git 
a/rocketmq-a2a/src/test/java/org/apache/rocketmq/a2a/common/util/RocketMQUtilStreamRegistrationTest.java
 
b/rocketmq-a2a/src/test/java/org/apache/rocketmq/a2a/common/util/RocketMQUtilStreamRegistrationTest.java
new file mode 100644
index 0000000..cb96b97
--- /dev/null
+++ 
b/rocketmq-a2a/src/test/java/org/apache/rocketmq/a2a/common/util/RocketMQUtilStreamRegistrationTest.java
@@ -0,0 +1,113 @@
+/*
+ * 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.a2a.common.util;
+
+import io.a2a.client.transport.spi.interceptors.PayloadAndHeaders;
+import java.io.IOException;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.rocketmq.client.apis.ClientException;
+import org.apache.rocketmq.client.apis.message.Message;
+import org.apache.rocketmq.client.apis.message.MessageId;
+import org.apache.rocketmq.client.apis.producer.Producer;
+import org.apache.rocketmq.client.apis.producer.RecallReceipt;
+import org.apache.rocketmq.client.apis.producer.SendReceipt;
+import org.apache.rocketmq.client.apis.producer.Transaction;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class RocketMQUtilStreamRegistrationTest {
+
+    @Test
+    public void testRequestIdIsExposedBeforeSend() throws Exception {
+        AtomicBoolean callbackInvoked = new AtomicBoolean(false);
+        Producer producer = new Producer() {
+            @Override
+            public SendReceipt send(Message message) {
+                Assert.assertTrue("stream listener must be registered before 
send", callbackInvoked.get());
+                return receipt();
+            }
+
+            @Override
+            public SendReceipt send(Message message, Transaction transaction) {
+                throw new UnsupportedOperationException();
+            }
+
+            @Override
+            public CompletableFuture<SendReceipt> sendAsync(Message message) {
+                throw new UnsupportedOperationException();
+            }
+
+            @Override
+            public Transaction beginTransaction() {
+                throw new UnsupportedOperationException();
+            }
+
+            @Override
+            public RecallReceipt recallMessage(String messageId, String 
recallHandle) {
+                throw new UnsupportedOperationException();
+            }
+
+            @Override
+            public CompletableFuture<RecallReceipt> recallMessageAsync(String 
messageId, String recallHandle) {
+                throw new UnsupportedOperationException();
+            }
+
+            @Override
+            public void close() throws IOException {
+            }
+        };
+
+        String requestId = RocketMQUtil.sendRocketMQRequest(
+            new PayloadAndHeaders(Map.of(), Map.of()),
+            "agent-topic",
+            "lite-topic",
+            "response-topic",
+            producer,
+            null,
+            id -> callbackInvoked.set(true)
+        );
+
+        Assert.assertTrue(callbackInvoked.get());
+        Assert.assertNotNull(requestId);
+    }
+
+    private static SendReceipt receipt() {
+        return new SendReceipt() {
+            @Override
+            public MessageId getMessageId() {
+                return new MessageId() {
+                    @Override
+                    public String getVersion() {
+                        return "1";
+                    }
+
+                    @Override
+                    public String toString() {
+                        return "test-message-id";
+                    }
+                };
+            }
+
+            @Override
+            public String getRecallHandle() {
+                return null;
+            }
+        };
+    }
+}

Reply via email to