This is an automated email from the ASF dual-hosted git repository.
RongtongJin pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-clients.git
The following commit(s) were added to refs/heads/master by this push:
new 40c1267d fix(go): reuse the receive attempt id until messages are
received (#1499)
40c1267d is described below
commit 40c1267d1e32f35ef1c6aabd28ff0a05485910ca
Author: Quan <[email protected]>
AuthorDate: Wed Nov 18 21:18:14 2026 +0800
fix(go): reuse the receive attempt id until messages are received (#1499)
- Carry the process queue's attempt id in the receive request instead of
always generating a new one
- Reuse the attempt id after any failed or empty reception, not only after
DeadlineExceeded
- Rotate the attempt id only after messages are received, aligned with the
Java client
---
golang/process_queue.go | 19 +++---
golang/process_queue_test.go | 135 +++++++++++++++++++++++++++++++++++++++++++
2 files changed, 145 insertions(+), 9 deletions(-)
diff --git a/golang/process_queue.go b/golang/process_queue.go
index 737b4402..107695f9 100644
--- a/golang/process_queue.go
+++ b/golang/process_queue.go
@@ -26,8 +26,6 @@ import (
v2 "github.com/apache/rocketmq-clients/golang/v5/protocol/v2"
"github.com/google/uuid"
"go.uber.org/atomic"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
)
type ProcessQueue interface {
@@ -453,6 +451,8 @@ func (dpq *defaultProcessQueue)
receiveMessageImmediatelyWithAttemptId(attemptId
batchSize := dpq.getReceptionBatchSize()
longPollingTimeout := dpq.consumer.pcSettings.longPollingTimeout
request :=
dpq.consumer.pushConsumerExtension.WrapReceiveMessageRequest(int(batchSize),
dpq.mq, dpq.filterExpression, longPollingTimeout)
+ // The process queue owns the attempt id, so a retry carries the same
id the server may already have served.
+ request.AttemptId = &attemptId
startTime := time.Now()
dpq.activityNanoTime.Store(startTime.UnixNano())
@@ -470,12 +470,11 @@ func (dpq *defaultProcessQueue)
receiveMessageImmediatelyWithAttemptId(attemptId
messageCommons = append(messageCommons,
mv.GetMessageCommon())
}
dpq.consumer.cli.doAfter(MessageHookPoints_RECEIVE,
messageCommons, duration, MessageHookPointsStatus_OK)
- dpq.onReceiveMessageResult(mvs)
+ dpq.onReceiveMessageResult(mvs, request.GetAttemptId())
} else {
- nextAttemptId := ""
- if status.Code(err) == codes.DeadlineExceeded {
- nextAttemptId = request.GetAttemptId()
- }
+ // Keep the attempt id until messages are received,
since the server may have
+ // served this attempt even though its response never
reached the client.
+ nextAttemptId := request.GetAttemptId()
rpcErr, isRpcErr := AsErrRpcStatus(err)
isNoNewMessage := isRpcErr && rpcErr.GetCode() ==
int32(v2.Code_MESSAGE_NOT_FOUND)
// An empty long polling result is still a completed
reception, so it has
@@ -530,15 +529,17 @@ func (dpq *defaultProcessQueue)
receiveMessageLater(duration time.Duration, atte
})
}
-func (dpq *defaultProcessQueue) onReceiveMessageResult(mvs []*MessageView) {
+func (dpq *defaultProcessQueue) onReceiveMessageResult(mvs []*MessageView,
attemptId string) {
mvslen := int64(len(mvs))
if mvslen != 0 {
dpq.cacheMessages(mvs)
dpq.receivedMessagesQuantity.Add(mvslen)
dpq.consumer.receivedMessagesQuantity.Add(mvslen)
dpq.consumer.consumerService.consume(dpq, mvs)
+ dpq.receiveMessage()
+ return
}
- dpq.receiveMessage()
+ dpq.receiveMessageWithAttemptId(attemptId)
}
func (dpq *defaultProcessQueue) cacheMessages(mvs []*MessageView) {
diff --git a/golang/process_queue_test.go b/golang/process_queue_test.go
index af8d68fd..4bd4c4f5 100644
--- a/golang/process_queue_test.go
+++ b/golang/process_queue_test.go
@@ -19,7 +19,9 @@ package golang
import (
"context"
+ "errors"
"io"
+ "sync"
"sync/atomic"
"testing"
"time"
@@ -125,6 +127,139 @@ func
TestProcessQueueEmptyLongPollingBalancesInflightReceiveCount(t *testing.T)
}
}
+// scriptedReceiveStream replays the canned responses of one reception, then
EOF.
+type scriptedReceiveStream struct {
+ grpc.ClientStream
+ responses []*v2.ReceiveMessageResponse
+}
+
+func (stream *scriptedReceiveStream) Recv() (*v2.ReceiveMessageResponse,
error) {
+ if len(stream.responses) == 0 {
+ return nil, io.EOF
+ }
+ resp := stream.responses[0]
+ stream.responses = stream.responses[1:]
+ return resp, nil
+}
+
+type discardConsumeService struct{}
+
+func (discardConsumeService) consume(ProcessQueue, []*MessageView) {}
+
+func (discardConsumeService) consumeWithDuration(*MessageView, time.Duration,
func(ConsumerResult, error)) {
+}
+
+func (discardConsumeService) Shutdown() error { return nil }
+
+func receiveStatusResponse(code v2.Code) *v2.ReceiveMessageResponse {
+ return &v2.ReceiveMessageResponse{
+ Content: &v2.ReceiveMessageResponse_Status{Status:
&v2.Status{Code: code, Message: code.String()}},
+ }
+}
+
+// A failed reception may have been served by the server with only the response
+// lost, so the queue keeps resending the same attempt id until messages
arrive,
+// and starts a new attempt only after that.
+func TestProcessQueueKeepsAttemptIdUntilMessagesAreReceived(t *testing.T) {
+ consumer, err := NewPushConsumer(&Config{
+ Endpoint: fakeAddress,
+ ConsumerGroup: MOCK_GROUP,
+ Credentials: &credentials.SessionCredentials{},
+ },
+
WithPushSubscriptionExpressions(map[string]*FilterExpression{MOCK_TOPIC:
SUB_ALL}),
+ WithPushMessageListener(&FuncMessageListener{
+ Consume: func(*MessageView) ConsumerResult { return
SUCCESS },
+ }),
+ )
+ if err != nil {
+ t.Fatal(err)
+ }
+ pc := consumer.(*defaultPushConsumer)
+ manager := NewMockClientManager(gomock.NewController(t))
+ pc.cli.clientManager = manager
+ pc.cli.log = zap.NewNop().Sugar()
+ pc.cli.inited.Store(true)
+ pc.consumerService = discardConsumeService{}
+
+ message := &v2.Message{
+ Topic: &v2.Resource{Name: MOCK_TOPIC},
+ SystemProperties: &v2.SystemProperties{
+ MessageId: "message-1",
+ BodyEncoding: v2.Encoding_IDENTITY,
+ },
+ Body: []byte("body"),
+ }
+ var mu sync.Mutex
+ var attemptIds []string
+ manager.EXPECT().ReceiveMessage(gomock.Any(), gomock.Any(),
gomock.Any()).
+ DoAndReturn(func(_ context.Context, _ *v2.Endpoints, request
*v2.ReceiveMessageRequest) (v2.MessagingService_ReceiveMessageClient, error) {
+ mu.Lock()
+ attemptIds = append(attemptIds, request.GetAttemptId())
+ reception := len(attemptIds)
+ mu.Unlock()
+ switch reception {
+ case 1:
+ return nil, errors.New("connection reset")
+ case 3:
+ return &scriptedReceiveStream{responses:
[]*v2.ReceiveMessageResponse{
+ {Content:
&v2.ReceiveMessageResponse_Message{Message: message}},
+ receiveStatusResponse(v2.Code_OK),
+ }}, nil
+ default:
+ return &scriptedReceiveStream{responses:
[]*v2.ReceiveMessageResponse{
+
receiveStatusResponse(v2.Code_MESSAGE_NOT_FOUND),
+ }}, nil
+ }
+ }).AnyTimes()
+
+ mq := &v2.MessageQueue{
+ Topic: &v2.Resource{Name: MOCK_TOPIC},
+ Id: 0,
+ Broker: &v2.Broker{Name: "broker", Endpoints:
fakeEndpoints()},
+ AcceptMessageTypes: []v2.MessageType{v2.MessageType_NORMAL},
+ }
+ dpq, ok := pc.createProcessQueue(utils.ParseMessageQueue2Str(mq), mq,
SUB_ALL).(*defaultProcessQueue)
+ if !ok {
+ t.Fatal("process queue was not created")
+ }
+ defer dpq.drop()
+
+ dpq.receiveMessageImmediately()
+
+ const wanted = 5
+ var ids []string
+ deadline := time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) {
+ mu.Lock()
+ ids = append([]string(nil), attemptIds...)
+ mu.Unlock()
+ if len(ids) >= wanted {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ dpq.drop()
+ if len(ids) < wanted {
+ t.Fatalf("expected at least %d receptions, got %d", wanted,
len(ids))
+ }
+
+ if ids[0] == "" {
+ t.Fatal("expected the reception to carry an attempt id")
+ }
+ if ids[1] != ids[0] {
+ t.Errorf("expected the retry after a failed reception to reuse
attempt id %s, got %s", ids[0], ids[1])
+ }
+ if ids[2] != ids[1] {
+ t.Errorf("expected the reception after an empty result to reuse
attempt id %s, got %s", ids[1], ids[2])
+ }
+ if ids[3] == ids[2] {
+ t.Errorf("expected a new attempt id after messages were
received, got %s again", ids[3])
+ }
+ if ids[4] != ids[3] {
+ t.Errorf("expected the reception after an empty result to reuse
attempt id %s, got %s", ids[3], ids[4])
+ }
+}
+
// newSettlementTestProcessQueue builds a push consumer whose RPCs are served
by
// a mock client manager, plus one process queue to drive the settlement chains
// (ack, change invisible duration, forward to DLQ) against it.