Skip to content

Commit 34517ce

Browse files
wbwb
authored andcommitted
fix(event): improve event delivery reliability
Apply the publisher queue limit before socket creation and retain realtime events under backpressure. Deliver block and transaction triggers synchronously so rollback flags are captured before cached capsules are reused. Always shut down the event loader executor after the final load attempt, and log failures with their stack traces.
1 parent 4a21592 commit 34517ce

6 files changed

Lines changed: 196 additions & 78 deletions

File tree

‎framework/src/main/java/org/tron/common/logsfilter/nativequeue/NativeMessageQueue.java‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,22 +27,21 @@ public static NativeMessageQueue getInstance() {
2727
}
2828

2929
public boolean start(int bindPort, int sendQueueLength) {
30-
context = new ZContext();
31-
publisher = context.createSocket(SocketType.PUB);
32-
33-
if (Objects.isNull(publisher)) {
34-
return false;
35-
}
36-
37-
if (bindPort == 0 || bindPort < 0) {
30+
if (bindPort <= 0) {
3831
bindPort = DEFAULT_BIND_PORT;
3932
}
4033

41-
if (sendQueueLength < 0) {
34+
if (sendQueueLength <= 0) {
4235
sendQueueLength = DEFAULT_QUEUE_LENGTH;
4336
}
4437

38+
context = new ZContext();
4539
context.setSndHWM(sendQueueLength);
40+
publisher = context.createSocket(SocketType.PUB);
41+
42+
if (Objects.isNull(publisher)) {
43+
return false;
44+
}
4645

4746
String bindAddress = String.format("tcp://*:%d", bindPort);
4847
return publisher.bind(bindAddress);

‎framework/src/main/java/org/tron/core/services/event/BlockEventLoad.java‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public class BlockEventLoad {
3737
public void init() {
3838
executor.scheduleWithFixedDelay(() -> {
3939
try {
40-
if (!instance.isBusy()) {
40+
if (!instance.isBusy() && !realtimeEventService.isBusy()) {
4141
load();
4242
}
4343
} catch (Exception e) {
@@ -51,10 +51,11 @@ public void init() {
5151
public void close() {
5252
try {
5353
load();
54+
} catch (Exception e) {
55+
logger.error("Failed to load remaining events during shutdown.", e);
56+
} finally {
5457
executor.shutdown();
5558
logger.info("Event load service close.");
56-
} catch (Exception e) {
57-
logger.warn("Stop event load service fail. {}", e.getMessage());
5859
}
5960
}
6061

‎framework/src/main/java/org/tron/core/services/event/RealtimeEventService.java‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ public class RealtimeEventService {
2929

3030
private static BlockingQueue<Event> queue = new LinkedBlockingQueue<>();
3131

32-
private int maxEventSize = 10000;
32+
private static final int BUSY_EVENT_SIZE = 500;
3333

3434
private final ScheduledExecutorService executor = ExecutorServiceManager
3535
.newSingleThreadScheduledExecutor("realtime-event");
@@ -56,13 +56,13 @@ public void close() {
5656
}
5757

5858
public void add(Event event) {
59-
if (queue.size() >= maxEventSize) {
60-
logger.warn("Add event failed, blockId {}.", event.getBlockEvent().getBlockId().getString());
61-
return;
62-
}
6359
queue.offer(event);
6460
}
6561

62+
public boolean isBusy() {
63+
return queue.size() >= BUSY_EVENT_SIZE;
64+
}
65+
6666
public synchronized void work() {
6767
while (queue.size() > 0) {
6868
Event event = queue.poll();
Lines changed: 61 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,87 +1,93 @@
11
package org.tron.common.logsfilter;
22

3-
import java.util.concurrent.ExecutorService;
3+
import static org.mockito.ArgumentMatchers.anyString;
4+
import static org.mockito.Mockito.inOrder;
5+
import static org.mockito.Mockito.mock;
6+
import static org.mockito.Mockito.mockConstruction;
7+
import static org.mockito.Mockito.when;
8+
49
import org.junit.After;
510
import org.junit.Assert;
11+
import org.junit.Before;
612
import org.junit.Test;
7-
import org.tron.common.es.ExecutorServiceManager;
13+
import org.mockito.InOrder;
14+
import org.mockito.MockedConstruction;
815
import org.tron.common.logsfilter.nativequeue.NativeMessageQueue;
916
import org.zeromq.SocketType;
1017
import org.zeromq.ZContext;
1118
import org.zeromq.ZMQ;
1219

1320
public class NativeMessageQueueTest {
1421

15-
public int bindPort = 5555;
16-
public String dataToSend = "################";
17-
public String topic = "testTopic";
18-
19-
private ExecutorService subscriberExecutor;
20-
private final String zmqSubscriber = "zmq-subscriber";
22+
private NativeMessageQueue queue;
23+
private ZMQ.Socket publisher;
24+
private MockedConstruction<ZContext> contexts;
25+
26+
@Before
27+
public void setUp() {
28+
publisher = mock(ZMQ.Socket.class);
29+
when(publisher.bind(anyString())).thenReturn(true);
30+
contexts = mockConstruction(ZContext.class, (context, construction) ->
31+
when(context.createSocket(SocketType.PUB)).thenReturn(publisher));
32+
queue = new NativeMessageQueue();
33+
}
2134

2235
@After
2336
public void tearDown() {
24-
ExecutorServiceManager.shutdownAndAwaitTermination(subscriberExecutor, zmqSubscriber);
25-
subscriberExecutor = null;
37+
try {
38+
if (queue != null) {
39+
queue.stop();
40+
}
41+
} finally {
42+
if (contexts != null) {
43+
contexts.close();
44+
}
45+
}
2646
}
2747

2848
@Test
29-
public void invalidBindPort() {
30-
boolean bRet = NativeMessageQueue.getInstance().start(-1111, 0);
31-
Assert.assertEquals(true, bRet);
32-
NativeMessageQueue.getInstance().stop();
49+
public void configuredSendQueueLengthIsAppliedBeforeSocketCreation() {
50+
assertStartup(6000, 2000, 6000, 2000);
3351
}
3452

3553
@Test
36-
public void invalidSendLength() {
37-
boolean bRet = NativeMessageQueue.getInstance().start(0, -2222);
38-
Assert.assertEquals(true, bRet);
39-
NativeMessageQueue.getInstance().stop();
54+
public void invalidBindPortUsesDefaultPort() {
55+
assertStartup(-1111, 1000, 5555, 1000);
4056
}
4157

4258
@Test
43-
public void publishTrigger() {
44-
45-
int sendLength = 0;
46-
boolean bRet = NativeMessageQueue.getInstance().start(bindPort, sendLength);
47-
Assert.assertEquals(true, bRet);
48-
49-
startSubscribeThread();
50-
51-
try {
52-
Thread.sleep(1000);
53-
} catch (InterruptedException e) {
54-
Thread.currentThread().interrupt();
55-
}
56-
57-
NativeMessageQueue.getInstance().publishTrigger(dataToSend, topic);
58-
59-
try {
60-
Thread.sleep(1000);
61-
} catch (InterruptedException e) {
62-
Thread.currentThread().interrupt();
63-
}
59+
public void negativeSendQueueLengthUsesDefaultSndHWM() {
60+
assertStartup(6000, -1, 6000, 1000);
61+
}
6462

65-
NativeMessageQueue.getInstance().stop();
63+
@Test
64+
public void zeroSendQueueLengthUsesDefaultSndHWM() {
65+
assertStartup(6000, 0, 6000, 1000);
6666
}
6767

68-
public void startSubscribeThread() {
69-
subscriberExecutor = ExecutorServiceManager.newSingleThreadExecutor(zmqSubscriber);
70-
subscriberExecutor.execute(() -> {
71-
try (ZContext context = new ZContext()) {
72-
ZMQ.Socket subscriber = context.createSocket(SocketType.SUB);
68+
@Test
69+
public void publishTriggerSendsTopicBeforePayload() {
70+
Assert.assertTrue(queue.start(6000, 1000));
7371

74-
Assert.assertTrue(subscriber.connect(String.format("tcp://localhost:%d", bindPort)));
75-
Assert.assertTrue(subscriber.subscribe(topic));
72+
queue.publishTrigger("payload", "topic");
7673

77-
while (!Thread.currentThread().isInterrupted()) {
78-
byte[] message = subscriber.recv();
79-
String triggerMsg = new String(message);
74+
InOrder delivery = inOrder(publisher);
75+
delivery.verify(publisher).bind("tcp://*:6000");
76+
delivery.verify(publisher).sendMore("topic");
77+
delivery.verify(publisher).send("payload");
78+
delivery.verifyNoMoreInteractions();
79+
}
8080

81-
Assert.assertTrue(triggerMsg.contains(dataToSend) || triggerMsg.contains(topic));
82-
}
83-
// ZMQ.Socket will be automatically closed when ZContext is closed
84-
}
85-
});
81+
private void assertStartup(int port, int queueLength, int expectedPort, int expectedQueueLength) {
82+
Assert.assertTrue(queue.start(port, queueLength));
83+
Assert.assertEquals(1, contexts.constructed().size());
84+
ZContext context = contexts.constructed().get(0);
85+
86+
// ZContext applies its defaults when creating the socket, so ordering matters.
87+
InOrder startup = inOrder(context, publisher);
88+
startup.verify(context).setSndHWM(expectedQueueLength);
89+
startup.verify(context).createSocket(SocketType.PUB);
90+
startup.verify(publisher).bind("tcp://*:" + expectedPort);
91+
startup.verifyNoMoreInteractions();
8692
}
8793
}

‎framework/src/test/java/org/tron/core/event/BlockEventLoadTest.java‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,14 @@
55
import java.lang.reflect.Field;
66
import java.lang.reflect.Method;
77
import java.util.concurrent.BlockingQueue;
8+
import java.util.concurrent.ScheduledExecutorService;
9+
import java.util.concurrent.TimeUnit;
10+
import org.junit.After;
811
import org.junit.Assert;
912
import org.junit.Test;
13+
import org.mockito.ArgumentCaptor;
1014
import org.mockito.Mockito;
15+
import org.tron.common.logsfilter.EventPluginLoader;
1116
import org.tron.common.utils.ReflectUtils;
1217
import org.tron.core.ChainBaseManager;
1318
import org.tron.core.capsule.BlockCapsule;
@@ -23,6 +28,69 @@
2328
public class BlockEventLoadTest {
2429
BlockEventLoad blockEventLoad = new BlockEventLoad();
2530

31+
@After
32+
public void tearDown() throws Exception {
33+
getExecutor().shutdownNow();
34+
}
35+
36+
@Test
37+
public void shouldNotLoadWhenRealtimeEventServiceIsBusy() throws Exception {
38+
verifyScheduledLoad(false, true, 0);
39+
}
40+
41+
@Test
42+
public void shouldNotLoadWhenPluginIsBusy() throws Exception {
43+
verifyScheduledLoad(true, false, 0);
44+
}
45+
46+
@Test
47+
public void shouldLoadWhenBothConsumersAreReady() throws Exception {
48+
verifyScheduledLoad(false, false, 1);
49+
}
50+
51+
@Test
52+
public void shouldShutDownExecutorWhenFinalLoadFails() throws Exception {
53+
blockEventLoad = Mockito.spy(blockEventLoad);
54+
Mockito.doThrow(new Exception("load failure")).when(blockEventLoad).load();
55+
ScheduledExecutorService executor = getExecutor();
56+
57+
blockEventLoad.close();
58+
59+
Mockito.verify(blockEventLoad).load();
60+
Assert.assertTrue(executor.isShutdown());
61+
}
62+
63+
private void verifyScheduledLoad(boolean pluginBusy, boolean realtimeBusy, int loadCalls)
64+
throws Exception {
65+
EventPluginLoader plugin = mock(EventPluginLoader.class);
66+
RealtimeEventService realtime = mock(RealtimeEventService.class);
67+
ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);
68+
// Replace only scheduling and loading; execute the real init() task synchronously.
69+
getExecutor().shutdownNow();
70+
ReflectUtils.setFieldValue(blockEventLoad, "executor", scheduler);
71+
ReflectUtils.setFieldValue(blockEventLoad, "instance", plugin);
72+
ReflectUtils.setFieldValue(blockEventLoad, "realtimeEventService", realtime);
73+
Mockito.when(plugin.isBusy()).thenReturn(pluginBusy);
74+
Mockito.when(realtime.isBusy()).thenReturn(realtimeBusy);
75+
blockEventLoad = Mockito.spy(blockEventLoad);
76+
Mockito.doNothing().when(blockEventLoad).load();
77+
78+
blockEventLoad.init();
79+
ArgumentCaptor<Runnable> task = ArgumentCaptor.forClass(Runnable.class);
80+
Mockito.verify(scheduler).scheduleWithFixedDelay(task.capture(), Mockito.anyLong(),
81+
Mockito.anyLong(), Mockito.eq(TimeUnit.MILLISECONDS));
82+
task.getValue().run();
83+
84+
Mockito.verify(blockEventLoad, Mockito.times(loadCalls)).load();
85+
Mockito.verify(blockEventLoad, Mockito.never()).close();
86+
}
87+
88+
private ScheduledExecutorService getExecutor() throws ReflectiveOperationException {
89+
Field field = BlockEventLoad.class.getDeclaredField("executor");
90+
field.setAccessible(true);
91+
return (ScheduledExecutorService) field.get(blockEventLoad);
92+
}
93+
2694
@Test
2795
public void test() throws Exception {
2896
Method method = blockEventLoad.getClass().getDeclaredMethod("load");

0 commit comments

Comments
 (0)