You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by zi...@apache.org on 2023/09/07 09:49:14 UTC

[pulsar-client-go] branch branch-0.11.0 updated (64c47537 -> 5c5af6ad)

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

zike pushed a change to branch branch-0.11.0
in repository https://gitbox.apache.org/repos/asf/pulsar-client-go.git


    from 64c47537 Release 0.11.0
     new e1154399 [Fix][Producer] check if message is nil (#1047)
     new e429eca5 [Fix][Producer] Stop block request even if Value and Payload are both set (#1052)
     new b17337b3 [Improve][Producer] simplify the flush logic (#1049)
     new e8a247ff [fix] [issue 1051]: Fix inaccurate producer mem limit in chunking and schema (#1055)
     new 5c5af6ad [fix] [issue 1057]:  Fix the producer flush opertion is not guarantee to flush all messages (#1058)

The 5 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 pulsar/producer_partition.go | 138 ++++++++++++++++++--------------
 pulsar/producer_test.go      | 185 +++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 262 insertions(+), 61 deletions(-)


[pulsar-client-go] 04/05: [fix] [issue 1051]: Fix inaccurate producer mem limit in chunking and schema (#1055)

Posted by zi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

zike pushed a commit to branch branch-0.11.0
in repository https://gitbox.apache.org/repos/asf/pulsar-client-go.git

commit e8a247ffc56c94fc5320e7f0fdc15f3b951d3e75
Author: Jiaqi Shen <18...@163.com>
AuthorDate: Thu Jul 20 15:51:41 2023 +0800

    [fix] [issue 1051]: Fix inaccurate producer mem limit in chunking and schema (#1055)
    
    ### Motivation
    
    The producer memory limit have some problem when `EnableChunking=true` or `Schema` is set.
    - When `Schema` is set, the actual message payload is `msg.Value`. The `len(msg.Payload)` may be 0 and memory can not be reserved acurate.
    https://github.com/apache/pulsar-client-go/blob/be3574019383ac0cdc65fec63e422fcfd6c82e4b/pulsar/producer_partition.go#L479-L494
    
    - In chunking, if producer meets the memory limit, it should release the memory for **chunks which has send out**. But the calculate for this release is not accurate, it should be `uncompressedPayloadSize - int64(lhs)` instead of `uncompressedPayloadSize - int64(rhs)`
    https://github.com/apache/pulsar-client-go/blob/be3574019383ac0cdc65fec63e422fcfd6c82e4b/pulsar/producer_partition.go#L662-L664
    
    - In chunking, if `internalSingleSend` is failed, it should release the memory for **single chunk**. But we release all the chunks memory repeatly now.
    https://github.com/apache/pulsar-client-go/blob/be3574019383ac0cdc65fec63e422fcfd6c82e4b/pulsar/producer_partition.go#L838-L843
    
    - When producer received the receipt from broker, it should release the memory **it reserved before sending**. But it releases wrong size in `chunking` and `schema`.
    https://github.com/apache/pulsar-client-go/blob/be3574019383ac0cdc65fec63e422fcfd6c82e4b/pulsar/producer_partition.go#L1221-L1230
    
    ### Modifications
    
    - Fix all the memory limit problems relative to `chunking` and `schema`
    - Add unit tests to cover these scenarios
    
    ---------
    
    Co-authored-by: shenjiaqi.2769 <sh...@bytedance.com>
    (cherry picked from commit 28f61d2f9e00279028e4c6e3558e5aa2665d25cd)
---
 pulsar/producer_partition.go |  55 +++++++++------
 pulsar/producer_test.go      | 159 +++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 192 insertions(+), 22 deletions(-)

diff --git a/pulsar/producer_partition.go b/pulsar/producer_partition.go
index 08f42f48..e8ad1953 100755
--- a/pulsar/producer_partition.go
+++ b/pulsar/producer_partition.go
@@ -482,21 +482,19 @@ func (p *partitionProducer) internalSend(request *sendRequest) {
 
 	// read payload from message
 	uncompressedPayload := msg.Payload
-	uncompressedPayloadSize := int64(len(uncompressedPayload))
 
 	var schemaPayload []byte
 	var err error
 
 	// The block chan must be closed when returned with exception
 	defer request.stopBlock()
-	if !p.canAddToQueue(request, uncompressedPayloadSize) {
+	if !p.canAddToQueue(request) {
 		return
 	}
 
 	if p.options.DisableMultiSchema {
 		if msg.Schema != nil && p.options.Schema != nil &&
 			msg.Schema.GetSchemaInfo().hash() != p.options.Schema.GetSchemaInfo().hash() {
-			p.releaseSemaphoreAndMem(uncompressedPayloadSize)
 			runCallback(request.callback, nil, request.msg, fmt.Errorf("msg schema can not match with producer schema"))
 			p.log.WithError(err).Errorf("The producer %s of the topic %s is disabled the `MultiSchema`", p.producerName, p.topic)
 			return
@@ -515,7 +513,6 @@ func (p *partitionProducer) internalSend(request *sendRequest) {
 		if uncompressedPayload == nil && schema != nil {
 			schemaPayload, err = schema.Encode(msg.Value)
 			if err != nil {
-				p.releaseSemaphoreAndMem(uncompressedPayloadSize)
 				runCallback(request.callback, nil, request.msg, newError(SchemaFailure, err.Error()))
 				p.log.WithError(err).Errorf("Schema encode message failed %s", msg.Value)
 				return
@@ -531,7 +528,6 @@ func (p *partitionProducer) internalSend(request *sendRequest) {
 		if schemaVersion == nil {
 			schemaVersion, err = p.getOrCreateSchema(schema.GetSchemaInfo())
 			if err != nil {
-				p.releaseSemaphoreAndMem(uncompressedPayloadSize)
 				p.log.WithError(err).Error("get schema version fail")
 				runCallback(request.callback, nil, request.msg, fmt.Errorf("get schema version fail, err: %w", err))
 				return
@@ -542,6 +538,11 @@ func (p *partitionProducer) internalSend(request *sendRequest) {
 
 	uncompressedSize := len(uncompressedPayload)
 
+	// try to reserve memory for uncompressedPayload
+	if !p.canReserveMem(request, int64(uncompressedSize)) {
+		return
+	}
+
 	deliverAt := msg.DeliverAt
 	if msg.DeliverAfter.Nanoseconds() > 0 {
 		deliverAt = time.Now().Add(msg.DeliverAfter)
@@ -591,7 +592,7 @@ func (p *partitionProducer) internalSend(request *sendRequest) {
 
 	// if msg is too large and chunking is disabled
 	if checkSize > maxMessageSize && !p.options.EnableChunking {
-		p.releaseSemaphoreAndMem(uncompressedPayloadSize)
+		p.releaseSemaphoreAndMem(int64(uncompressedSize))
 		runCallback(request.callback, nil, request.msg, errMessageTooLarge)
 		p.log.WithError(errMessageTooLarge).
 			WithField("size", checkSize).
@@ -610,7 +611,7 @@ func (p *partitionProducer) internalSend(request *sendRequest) {
 	} else {
 		payloadChunkSize = int(p._getConn().GetMaxMessageSize()) - proto.Size(mm)
 		if payloadChunkSize <= 0 {
-			p.releaseSemaphoreAndMem(uncompressedPayloadSize)
+			p.releaseSemaphoreAndMem(int64(uncompressedSize))
 			runCallback(request.callback, nil, msg, errMetaTooLarge)
 			p.log.WithError(errMetaTooLarge).
 				WithField("metadata size", proto.Size(mm)).
@@ -657,10 +658,11 @@ func (p *partitionProducer) internalSend(request *sendRequest) {
 					uuid:             uuid,
 					chunkRecorder:    cr,
 					transaction:      request.transaction,
+					reservedMem:      int64(rhs - lhs),
 				}
 				// the permit of first chunk has acquired
-				if chunkID != 0 && !p.canAddToQueue(nsr, 0) {
-					p.releaseSemaphoreAndMem(uncompressedPayloadSize - int64(rhs))
+				if chunkID != 0 && !p.canAddToQueue(nsr) {
+					p.releaseSemaphoreAndMem(int64(uncompressedSize - lhs))
 					return
 				}
 				p.internalSingleSend(mm, compressedPayload[lhs:rhs], nsr, uint32(maxMessageSize))
@@ -685,7 +687,7 @@ func (p *partitionProducer) internalSend(request *sendRequest) {
 			// after flushing try again to add the current payload
 			if ok := addRequestToBatch(smm, p, uncompressedPayload, request, msg, deliverAt, schemaVersion,
 				multiSchemaEnabled); !ok {
-				p.releaseSemaphoreAndMem(uncompressedPayloadSize)
+				p.releaseSemaphoreAndMem(int64(uncompressedSize))
 				runCallback(request.callback, nil, request.msg, errFailAddToBatch)
 				p.log.WithField("size", uncompressedSize).
 					WithField("properties", msg.Properties).
@@ -837,7 +839,7 @@ func (p *partitionProducer) internalSingleSend(mm *pb.MessageMetadata,
 
 	if err != nil {
 		runCallback(request.callback, nil, request.msg, err)
-		p.releaseSemaphoreAndMem(int64(len(msg.Payload)))
+		p.releaseSemaphoreAndMem(request.reservedMem)
 		p.log.WithError(err).Errorf("Single message serialize failed %s", msg.Value)
 		return
 	}
@@ -976,7 +978,7 @@ func (p *partitionProducer) failTimeoutMessages() {
 				sr := i.(*sendRequest)
 				if sr.msg != nil {
 					size := len(sr.msg.Payload)
-					p.releaseSemaphoreAndMem(int64(size))
+					p.releaseSemaphoreAndMem(sr.reservedMem)
 					p.metrics.MessagesPending.Dec()
 					p.metrics.BytesPending.Sub(float64(size))
 					p.metrics.PublishErrorsTimeout.Inc()
@@ -1208,7 +1210,7 @@ func (p *partitionProducer) ReceivedSendReceipt(response *pb.CommandSendReceipt)
 		for idx, i := range pi.sendRequests {
 			sr := i.(*sendRequest)
 			atomic.StoreInt64(&p.lastSequenceID, int64(pi.sequenceID))
-			p.releaseSemaphoreAndMem(int64(len(sr.msg.Payload)))
+			p.releaseSemaphoreAndMem(sr.reservedMem)
 			p.metrics.PublishLatency.Observe(float64(now-sr.publishTime.UnixNano()) / 1.0e9)
 			p.metrics.MessagesPublished.Inc()
 			p.metrics.MessagesPending.Dec()
@@ -1352,6 +1354,7 @@ type sendRequest struct {
 	uuid             string
 	chunkRecorder    *chunkRecorder
 	transaction      *transaction
+	reservedMem      int64
 }
 
 // stopBlock can be invoked multiple times safety
@@ -1401,31 +1404,39 @@ func (p *partitionProducer) releaseSemaphoreAndMem(size int64) {
 	p.client.memLimit.ReleaseMemory(size)
 }
 
-func (p *partitionProducer) canAddToQueue(sr *sendRequest, uncompressedPayloadSize int64) bool {
+func (p *partitionProducer) canAddToQueue(sr *sendRequest) bool {
 	if p.options.DisableBlockIfQueueFull {
 		if !p.publishSemaphore.TryAcquire() {
 			runCallback(sr.callback, nil, sr.msg, errSendQueueIsFull)
 			return false
 		}
-		if !p.client.memLimit.TryReserveMemory(uncompressedPayloadSize) {
+	} else {
+		if !p.publishSemaphore.Acquire(sr.ctx) {
+			runCallback(sr.callback, nil, sr.msg, errContextExpired)
+			return false
+		}
+	}
+	p.metrics.MessagesPending.Inc()
+	return true
+}
+
+func (p *partitionProducer) canReserveMem(sr *sendRequest, size int64) bool {
+	if p.options.DisableBlockIfQueueFull {
+		if !p.client.memLimit.TryReserveMemory(size) {
 			p.publishSemaphore.Release()
 			runCallback(sr.callback, nil, sr.msg, errMemoryBufferIsFull)
 			return false
 		}
 
 	} else {
-		if !p.publishSemaphore.Acquire(sr.ctx) {
-			runCallback(sr.callback, nil, sr.msg, errContextExpired)
-			return false
-		}
-		if !p.client.memLimit.ReserveMemory(sr.ctx, uncompressedPayloadSize) {
+		if !p.client.memLimit.ReserveMemory(sr.ctx, size) {
 			p.publishSemaphore.Release()
 			runCallback(sr.callback, nil, sr.msg, errContextExpired)
 			return false
 		}
 	}
-	p.metrics.MessagesPending.Inc()
-	p.metrics.BytesPending.Add(float64(len(sr.msg.Payload)))
+	sr.reservedMem += size
+	p.metrics.BytesPending.Add(float64(size))
 	return true
 }
 
diff --git a/pulsar/producer_test.go b/pulsar/producer_test.go
index b197278a..a042e0d7 100644
--- a/pulsar/producer_test.go
+++ b/pulsar/producer_test.go
@@ -1939,6 +1939,165 @@ func TestMemLimitRejectProducerMessages(t *testing.T) {
 	assert.NoError(t, err)
 }
 
+func TestMemLimitRejectProducerMessagesWithSchema(t *testing.T) {
+
+	c, err := NewClient(ClientOptions{
+		URL:              serviceURL,
+		MemoryLimitBytes: 100 * 6,
+	})
+	assert.NoError(t, err)
+	defer c.Close()
+
+	schema := NewAvroSchema(`{"fields":
+	[
+		{"name":"id","type":"int"},{"default":null,"name":"name","type":["null","string"]}
+	],
+	"name":"MyAvro","namespace":"schemaNotFoundTestCase","type":"record"}`, nil)
+
+	topicName := newTopicName()
+	producer1, _ := c.CreateProducer(ProducerOptions{
+		Topic:                   topicName,
+		DisableBlockIfQueueFull: true,
+		DisableBatching:         false,
+		BatchingMaxPublishDelay: 100 * time.Second,
+		SendTimeout:             2 * time.Second,
+	})
+
+	producer2, _ := c.CreateProducer(ProducerOptions{
+		Topic:                   topicName,
+		DisableBlockIfQueueFull: true,
+		DisableBatching:         false,
+		BatchingMaxPublishDelay: 100 * time.Second,
+		SendTimeout:             2 * time.Second,
+	})
+
+	// the size of encoded value is 6 bytes
+	value := map[string]interface{}{
+		"id": 0,
+		"name": map[string]interface{}{
+			"string": "abc",
+		},
+	}
+
+	n := 101
+	for i := 0; i < n/2; i++ {
+		producer1.SendAsync(context.Background(), &ProducerMessage{
+			Value:  value,
+			Schema: schema,
+		}, func(id MessageID, message *ProducerMessage, e error) {})
+
+		producer2.SendAsync(context.Background(), &ProducerMessage{
+			Value:  value,
+			Schema: schema,
+		}, func(id MessageID, message *ProducerMessage, e error) {})
+	}
+	// Last message in order to reach the limit
+	producer1.SendAsync(context.Background(), &ProducerMessage{
+		Value:  value,
+		Schema: schema,
+	}, func(id MessageID, message *ProducerMessage, e error) {})
+	time.Sleep(100 * time.Millisecond)
+	assert.Equal(t, int64(n*6), c.(*client).memLimit.CurrentUsage())
+
+	_, err = producer1.Send(context.Background(), &ProducerMessage{
+		Value:  value,
+		Schema: schema,
+	})
+	assert.Error(t, err)
+	assert.ErrorContains(t, err, getResultStr(ClientMemoryBufferIsFull))
+
+	_, err = producer2.Send(context.Background(), &ProducerMessage{
+		Value:  value,
+		Schema: schema,
+	})
+	assert.Error(t, err)
+	assert.ErrorContains(t, err, getResultStr(ClientMemoryBufferIsFull))
+
+	// flush pending msg
+	err = producer1.Flush()
+	assert.NoError(t, err)
+	err = producer2.Flush()
+	assert.NoError(t, err)
+	assert.Equal(t, int64(0), c.(*client).memLimit.CurrentUsage())
+
+	_, err = producer1.Send(context.Background(), &ProducerMessage{
+		Value:  value,
+		Schema: schema,
+	})
+	assert.NoError(t, err)
+	_, err = producer2.Send(context.Background(), &ProducerMessage{
+		Value:  value,
+		Schema: schema,
+	})
+	assert.NoError(t, err)
+}
+
+func TestMemLimitRejectProducerMessagesWithChunking(t *testing.T) {
+
+	c, err := NewClient(ClientOptions{
+		URL:              serviceURL,
+		MemoryLimitBytes: 5 * 1024,
+	})
+	assert.NoError(t, err)
+	defer c.Close()
+
+	topicName := newTopicName()
+	producer1, _ := c.CreateProducer(ProducerOptions{
+		Topic:                   topicName,
+		DisableBlockIfQueueFull: true,
+		DisableBatching:         true,
+		EnableChunking:          true,
+		SendTimeout:             2 * time.Second,
+	})
+
+	producer2, _ := c.CreateProducer(ProducerOptions{
+		Topic:                   topicName,
+		DisableBlockIfQueueFull: true,
+		DisableBatching:         false,
+		BatchingMaxPublishDelay: 100 * time.Millisecond,
+		SendTimeout:             2 * time.Second,
+	})
+
+	producer2.SendAsync(context.Background(), &ProducerMessage{
+		Payload: make([]byte, 5*1024+1),
+	}, func(id MessageID, message *ProducerMessage, e error) {
+		if e != nil {
+			t.Fatal(e)
+		}
+	})
+
+	time.Sleep(50 * time.Millisecond)
+	assert.Equal(t, int64(5*1024+1), c.(*client).memLimit.CurrentUsage())
+
+	_, err = producer1.Send(context.Background(), &ProducerMessage{
+		Payload: make([]byte, 1),
+	})
+	assert.Error(t, err)
+	assert.ErrorContains(t, err, getResultStr(ClientMemoryBufferIsFull))
+
+	// wait all the mem have been released
+	retryAssert(t, 10, 200, func() {}, func(t assert.TestingT) bool {
+		return assert.Equal(t, 0, int(c.(*client).memLimit.CurrentUsage()))
+	})
+
+	producer3, _ := c.CreateProducer(ProducerOptions{
+		Topic:                   topicName,
+		DisableBlockIfQueueFull: true,
+		DisableBatching:         true,
+		EnableChunking:          true,
+		MaxPendingMessages:      1,
+		ChunkMaxMessageSize:     1024,
+		SendTimeout:             2 * time.Second,
+	})
+
+	// producer2 will reserve 2*1024 bytes and then release 1024 byte (release the second chunk)
+	// because it reaches MaxPendingMessages in chunking
+	_, _ = producer3.Send(context.Background(), &ProducerMessage{
+		Payload: make([]byte, 2*1024),
+	})
+	assert.Equal(t, int64(1024), c.(*client).memLimit.CurrentUsage())
+}
+
 func TestMemLimitContextCancel(t *testing.T) {
 
 	c, err := NewClient(ClientOptions{


[pulsar-client-go] 05/05: [fix] [issue 1057]: Fix the producer flush opertion is not guarantee to flush all messages (#1058)

Posted by zi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

zike pushed a commit to branch branch-0.11.0
in repository https://gitbox.apache.org/repos/asf/pulsar-client-go.git

commit 5c5af6ada9e7352cb6fd5bef09cc23d8d880cf39
Author: Jiaqi Shen <18...@163.com>
AuthorDate: Thu Jul 20 19:35:05 2023 +0800

    [fix] [issue 1057]:  Fix the producer flush opertion is not guarantee to flush all messages (#1058)
    
    Fixes #1057
    
    ### Motivation
    
    `dataChan` is introduced by #1029  to fix the problem of reconnectToBroker. But it missed that if a flush operation excuted, there may still be some messages in `dataChan`. And these messages can't be flushed.
    
    ### Modifications
    
    - Fix the producer flush opertion is not guarantee to flush all messages
    
    (cherry picked from commit 9867c29ca329302e97ddd9c6a99f66853c7f447f)
---
 pulsar/producer_partition.go | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/pulsar/producer_partition.go b/pulsar/producer_partition.go
index e8ad1953..00d4e6f0 100755
--- a/pulsar/producer_partition.go
+++ b/pulsar/producer_partition.go
@@ -1048,6 +1048,15 @@ func (p *partitionProducer) internalFlushCurrentBatches() {
 }
 
 func (p *partitionProducer) internalFlush(fr *flushRequest) {
+	// clear all the messages which have sent to dataChan before flush
+	if len(p.dataChan) != 0 {
+		oldDataChan := p.dataChan
+		p.dataChan = make(chan *sendRequest, p.options.MaxPendingMessages)
+		for len(oldDataChan) != 0 {
+			pendingData := <-oldDataChan
+			p.internalSend(pendingData)
+		}
+	}
 
 	p.internalFlushCurrentBatch()
 


[pulsar-client-go] 02/05: [Fix][Producer] Stop block request even if Value and Payload are both set (#1052)

Posted by zi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

zike pushed a commit to branch branch-0.11.0
in repository https://gitbox.apache.org/repos/asf/pulsar-client-go.git

commit e429eca53562e02def06820afd56ab7b2efb4b85
Author: gunli <24...@qq.com>
AuthorDate: Thu Jul 13 17:15:37 2023 +0800

    [Fix][Producer] Stop block request even if Value and Payload are both set (#1052)
    
    ### Motivation
    Currently, if `!p.options.DisableBlockIfQueueFull` and `msg.Value != nil && msg.Payload != nil`, request will be blocked forever 'cause `defer request.stopBlock()` is set up after the verify logic.
    ```go
    if msg.Value != nil && msg.Payload != nil {
            p.log.Error("Can not set Value and Payload both")
            runCallback(request.callback, nil, request.msg, errors.New("can not set Value and Payload both"))
            return
    }
    
    // The block chan must be closed when returned with exception
    defer request.stopBlock()
    ```
    Here is the PR to stop block request even if Value and Payload are both set
    
    ### Modifications
    
    - pulsar/producer_partition.go
    
    ---------
    
    Co-authored-by: gunli <gu...@tencent.com>
    (cherry picked from commit e45122c2defc5efd4efc493d0acef278a7ccfc01)
---
 pulsar/producer_partition.go | 11 ++++++-----
 pulsar/producer_test.go      | 15 +++++++++++++++
 2 files changed, 21 insertions(+), 5 deletions(-)

diff --git a/pulsar/producer_partition.go b/pulsar/producer_partition.go
index 2f771fde..341ccf5d 100755
--- a/pulsar/producer_partition.go
+++ b/pulsar/producer_partition.go
@@ -486,11 +486,6 @@ func (p *partitionProducer) internalSend(request *sendRequest) {
 
 	var schemaPayload []byte
 	var err error
-	if msg.Value != nil && msg.Payload != nil {
-		p.log.Error("Can not set Value and Payload both")
-		runCallback(request.callback, nil, request.msg, errors.New("can not set Value and Payload both"))
-		return
-	}
 
 	// The block chan must be closed when returned with exception
 	defer request.stopBlock()
@@ -1118,6 +1113,12 @@ func (p *partitionProducer) internalSendAsync(ctx context.Context, msg *Producer
 		return
 	}
 
+	if msg.Value != nil && msg.Payload != nil {
+		p.log.Error("Can not set Value and Payload both")
+		runCallback(callback, nil, msg, newError(InvalidMessage, "Can not set Value and Payload both"))
+		return
+	}
+
 	// Register transaction operation to transaction and the transaction coordinator.
 	var newCallback func(MessageID, *ProducerMessage, error)
 	var txn *transaction
diff --git a/pulsar/producer_test.go b/pulsar/producer_test.go
index fecae8ef..b197278a 100644
--- a/pulsar/producer_test.go
+++ b/pulsar/producer_test.go
@@ -111,6 +111,12 @@ func TestSimpleProducer(t *testing.T) {
 
 	_, err = producer.Send(context.Background(), nil)
 	assert.NotNil(t, err)
+
+	_, err = producer.Send(context.Background(), &ProducerMessage{
+		Payload: []byte("hello"),
+		Value:   []byte("hello"),
+	})
+	assert.NotNil(t, err)
 }
 
 func TestProducerAsyncSend(t *testing.T) {
@@ -163,6 +169,15 @@ func TestProducerAsyncSend(t *testing.T) {
 		wg.Done()
 	})
 	wg.Wait()
+
+	wg.Add(1)
+	producer.SendAsync(context.Background(), &ProducerMessage{Payload: []byte("hello"), Value: []byte("hello")},
+		func(id MessageID, m *ProducerMessage, e error) {
+			assert.NotNil(t, e)
+			assert.Nil(t, id)
+			wg.Done()
+		})
+	wg.Wait()
 }
 
 func TestProducerCompression(t *testing.T) {


[pulsar-client-go] 01/05: [Fix][Producer] check if message is nil (#1047)

Posted by zi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

zike pushed a commit to branch branch-0.11.0
in repository https://gitbox.apache.org/repos/asf/pulsar-client-go.git

commit e1154399a9f6eed218f13814b5172278199c9436
Author: gunli <24...@qq.com>
AuthorDate: Thu Jul 6 16:29:15 2023 +0800

    [Fix][Producer] check if message is nil (#1047)
    
    * [Fix][Producer] check if message is nil
    
    * add a debug log
    
    ---------
    
    Co-authored-by: gunli <gu...@tencent.com>
    (cherry picked from commit 8d4513787a25423c988708dff985e9c994545df5)
---
 pulsar/producer_partition.go |  6 ++++++
 pulsar/producer_test.go      | 11 +++++++++++
 2 files changed, 17 insertions(+)

diff --git a/pulsar/producer_partition.go b/pulsar/producer_partition.go
index 9d04427a..2f771fde 100755
--- a/pulsar/producer_partition.go
+++ b/pulsar/producer_partition.go
@@ -1112,6 +1112,12 @@ func (p *partitionProducer) SendAsync(ctx context.Context, msg *ProducerMessage,
 
 func (p *partitionProducer) internalSendAsync(ctx context.Context, msg *ProducerMessage,
 	callback func(MessageID, *ProducerMessage, error), flushImmediately bool) {
+	if msg == nil {
+		p.log.Error("Message is nil")
+		runCallback(callback, nil, msg, newError(InvalidMessage, "Message is nil"))
+		return
+	}
+
 	// Register transaction operation to transaction and the transaction coordinator.
 	var newCallback func(MessageID, *ProducerMessage, error)
 	var txn *transaction
diff --git a/pulsar/producer_test.go b/pulsar/producer_test.go
index 7c3abdc7..fecae8ef 100644
--- a/pulsar/producer_test.go
+++ b/pulsar/producer_test.go
@@ -108,6 +108,9 @@ func TestSimpleProducer(t *testing.T) {
 		assert.NoError(t, err)
 		assert.NotNil(t, ID)
 	}
+
+	_, err = producer.Send(context.Background(), nil)
+	assert.NotNil(t, err)
 }
 
 func TestProducerAsyncSend(t *testing.T) {
@@ -152,6 +155,14 @@ func TestProducerAsyncSend(t *testing.T) {
 	wg.Wait()
 
 	assert.Equal(t, 0, errors.Size())
+
+	wg.Add(1)
+	producer.SendAsync(context.Background(), nil, func(id MessageID, m *ProducerMessage, e error) {
+		assert.NotNil(t, e)
+		assert.Nil(t, id)
+		wg.Done()
+	})
+	wg.Wait()
 }
 
 func TestProducerCompression(t *testing.T) {


[pulsar-client-go] 03/05: [Improve][Producer] simplify the flush logic (#1049)

Posted by zi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

zike pushed a commit to branch branch-0.11.0
in repository https://gitbox.apache.org/repos/asf/pulsar-client-go.git

commit b17337b3dfddbf8288ef6529b3812019cce6c30e
Author: gunli <24...@qq.com>
AuthorDate: Tue Jul 18 18:57:47 2023 +0800

    [Improve][Producer] simplify the flush logic (#1049)
    
    ### Motivation
    
    Simplify the producer flush logic
    
    ### Modifications
    1. add a callback field to the pendingItem, default is nil;
    2. in partitionProducer.internalFlush() get the last pendingItem from pendingQueue;
    3. update the last pendingItem by setup a new callback;
    4. in partitionProducer.ReceivedSendReceipt, no need to identify the sendRequest by checking if the msg is nil;
    5. in pendingItem.Complete(), invoke its callback to notify the flush is done.
    
    ---------
    
    Co-authored-by: gunli <gu...@tencent.com>
    (cherry picked from commit 3812c07a0b8f6c37a2803cd740f4bf917160fd22)
---
 pulsar/producer_partition.go | 59 ++++++++++++++++++--------------------------
 1 file changed, 24 insertions(+), 35 deletions(-)

diff --git a/pulsar/producer_partition.go b/pulsar/producer_partition.go
index 341ccf5d..08f42f48 100755
--- a/pulsar/producer_partition.go
+++ b/pulsar/producer_partition.go
@@ -853,11 +853,12 @@ func (p *partitionProducer) internalSingleSend(mm *pb.MessageMetadata,
 
 type pendingItem struct {
 	sync.Mutex
-	buffer       internal.Buffer
-	sequenceID   uint64
-	sentAt       time.Time
-	sendRequests []interface{}
-	completed    bool
+	buffer        internal.Buffer
+	sequenceID    uint64
+	sentAt        time.Time
+	sendRequests  []interface{}
+	completed     bool
+	flushCallback func(err error)
 }
 
 func (p *partitionProducer) internalFlushCurrentBatch() {
@@ -995,7 +996,7 @@ func (p *partitionProducer) failTimeoutMessages() {
 			}
 
 			// flag the sending has completed with error, flush make no effect
-			pi.Complete()
+			pi.Complete(errSendTimeout)
 			pi.Unlock()
 
 			// finally reached the last view item, current iteration ends
@@ -1067,15 +1068,10 @@ func (p *partitionProducer) internalFlush(fr *flushRequest) {
 		return
 	}
 
-	sendReq := &sendRequest{
-		msg: nil,
-		callback: func(id MessageID, message *ProducerMessage, e error) {
-			fr.err = e
-			close(fr.doneCh)
-		},
+	pi.flushCallback = func(err error) {
+		fr.err = err
+		close(fr.doneCh)
 	}
-
-	pi.sendRequests = append(pi.sendRequests, sendReq)
 }
 
 func (p *partitionProducer) Send(ctx context.Context, msg *ProducerMessage) (MessageID, error) {
@@ -1208,27 +1204,17 @@ func (p *partitionProducer) ReceivedSendReceipt(response *pb.CommandSendReceipt)
 		pi.Lock()
 		defer pi.Unlock()
 		p.metrics.PublishRPCLatency.Observe(float64(now-pi.sentAt.UnixNano()) / 1.0e9)
-		batchSize := int32(0)
-		for _, i := range pi.sendRequests {
-			sr := i.(*sendRequest)
-			if sr.msg != nil {
-				batchSize = batchSize + 1
-			} else { // Flush request
-				break
-			}
-		}
+		batchSize := int32(len(pi.sendRequests))
 		for idx, i := range pi.sendRequests {
 			sr := i.(*sendRequest)
-			if sr.msg != nil {
-				atomic.StoreInt64(&p.lastSequenceID, int64(pi.sequenceID))
-				p.releaseSemaphoreAndMem(int64(len(sr.msg.Payload)))
-				p.metrics.PublishLatency.Observe(float64(now-sr.publishTime.UnixNano()) / 1.0e9)
-				p.metrics.MessagesPublished.Inc()
-				p.metrics.MessagesPending.Dec()
-				payloadSize := float64(len(sr.msg.Payload))
-				p.metrics.BytesPublished.Add(payloadSize)
-				p.metrics.BytesPending.Sub(payloadSize)
-			}
+			atomic.StoreInt64(&p.lastSequenceID, int64(pi.sequenceID))
+			p.releaseSemaphoreAndMem(int64(len(sr.msg.Payload)))
+			p.metrics.PublishLatency.Observe(float64(now-sr.publishTime.UnixNano()) / 1.0e9)
+			p.metrics.MessagesPublished.Inc()
+			p.metrics.MessagesPending.Dec()
+			payloadSize := float64(len(sr.msg.Payload))
+			p.metrics.BytesPublished.Add(payloadSize)
+			p.metrics.BytesPending.Sub(payloadSize)
 
 			if sr.callback != nil || len(p.options.Interceptors) > 0 {
 				msgID := newMessageID(
@@ -1274,7 +1260,7 @@ func (p *partitionProducer) ReceivedSendReceipt(response *pb.CommandSendReceipt)
 		}
 
 		// Mark this pending item as done
-		pi.Complete()
+		pi.Complete(nil)
 	}
 }
 
@@ -1384,12 +1370,15 @@ type flushRequest struct {
 	err    error
 }
 
-func (i *pendingItem) Complete() {
+func (i *pendingItem) Complete(err error) {
 	if i.completed {
 		return
 	}
 	i.completed = true
 	buffersPool.Put(i.buffer)
+	if i.flushCallback != nil {
+		i.flushCallback(err)
+	}
 }
 
 // _setConn sets the internal connection field of this partition producer atomically.