Skip to content

Commit

Permalink
cherry pick #16915 to branch 2.7 (#16957)
Browse files Browse the repository at this point in the history
Co-authored-by: nicklixinyang <nicklixinyang@didiglobal.com>
  • Loading branch information
Nicklee007 and nicklixinyang committed Aug 7, 2022
1 parent 97a91b4 commit 85b6b63
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
Expand Up @@ -18,6 +18,8 @@
*/
package org.apache.pulsar.client.impl;

import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import lombok.Cleanup;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.ProducerConsumerBase;
Expand All @@ -29,13 +31,11 @@
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -55,6 +55,39 @@ public void cleanup() throws Exception {
super.internalCleanup();
}

@Test(timeOut = 10_000)
public void testProducerSemaphoreInvalidMessage() throws Exception {
final int pendingQueueSize = 100;

@Cleanup
ProducerImpl<byte[]> producer = (ProducerImpl<byte[]>) pulsarClient.newProducer()
.topic("testProducerSemaphoreAcquire")
.maxPendingMessages(pendingQueueSize)
.enableBatching(true)
.create();

this.stopBroker();

Field maxMessageSizeFiled = ClientCnx.class.getDeclaredField("maxMessageSize");
maxMessageSizeFiled.setAccessible(true);
maxMessageSizeFiled.set(null, 2);

try {
producer.send("semaphore-test".getBytes(StandardCharsets.UTF_8));
Assert.fail("can not reach here");
} catch (PulsarClientException.InvalidMessageException ex) {
Assert.assertEquals(producer.getSemaphore().availablePermits(), pendingQueueSize);
}

producer.conf.setBatchingEnabled(false);
try {
producer.send("semaphore-test".getBytes(StandardCharsets.UTF_8));
Assert.fail("can not reach here");
} catch (PulsarClientException.InvalidMessageException ex) {
Assert.assertEquals(producer.getSemaphore().availablePermits(), pendingQueueSize);
}
}

@Test(timeOut = 30000)
public void testProducerSemaphoreAcquireAndRelease() throws PulsarClientException, ExecutionException, InterruptedException {

Expand Down
Expand Up @@ -182,6 +182,7 @@ public boolean isMultiBatches() {
public OpSendMsg createOpSendMsg() throws IOException {
ByteBuf encryptedPayload = producer.encryptMessage(messageMetadata, getCompressedBatchMetadataAndPayload());
if (encryptedPayload.readableBytes() > ClientCnx.getMaxMessageSize()) {
producer.getSemaphore().release(messages.size());
discard(new PulsarClientException.InvalidMessageException(
"Message size is bigger than " + ClientCnx.getMaxMessageSize() + " bytes"));
return null;
Expand Down

0 comments on commit 85b6b63

Please sign in to comment.