forked from rabbitmq/rabbitmq-stream-java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStreamProducer.java
666 lines (618 loc) · 23.1 KB
/
StreamProducer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
// Copyright (c) 2020-2023 Broadcom. All Rights Reserved.
// The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
//
// This software, the RabbitMQ Stream Java client library, is dual-licensed under the
// Mozilla Public License 2.0 ("MPL"), and the Apache License version 2 ("ASL").
// For the MPL, please see LICENSE-MPL-RabbitMQ. For the ASL,
// please see LICENSE-APACHE2.
//
// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
// either express or implied. See the LICENSE file for specific language governing
// rights and limitations of this software.
//
// If you have any questions regarding licensing, please contact us at
package com.rabbitmq.stream.impl;
import static com.rabbitmq.stream.Constants.*;
import static com.rabbitmq.stream.impl.Utils.formatConstant;
import static com.rabbitmq.stream.impl.Utils.namedRunnable;
import com.rabbitmq.stream.Codec;
import com.rabbitmq.stream.ConfirmationHandler;
import com.rabbitmq.stream.ConfirmationStatus;
import com.rabbitmq.stream.Constants;
import com.rabbitmq.stream.Message;
import com.rabbitmq.stream.MessageBuilder;
import com.rabbitmq.stream.Producer;
import com.rabbitmq.stream.StreamException;
import com.rabbitmq.stream.compression.Compression;
import com.rabbitmq.stream.impl.Client.Response;
import com.rabbitmq.stream.impl.MessageAccumulator.AccumulatedEntity;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.buffer.ByteBuf;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.ToLongFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class StreamProducer implements Producer {
private static final AtomicLong ID_SEQUENCE = new AtomicLong(0);
private static final Logger LOGGER = LoggerFactory.getLogger(StreamProducer.class);
private static final ConfirmationHandler NO_OP_CONFIRMATION_HANDLER = confirmationStatus -> {};
private final long id;
private final MessageAccumulator accumulator;
// FIXME investigate a more optimized data structure to handle pending messages
private final ConcurrentMap<Long, AccumulatedEntity> unconfirmedMessages;
private final int batchSize;
private final String name;
private final String stream;
private final Client.OutboundEntityWriteCallback writeCallback;
private final Semaphore unconfirmedMessagesSemaphore;
private final Runnable closingCallback;
private final StreamEnvironment environment;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final int maxUnconfirmedMessages;
private final Codec codec;
private final ToLongFunction<Object> publishSequenceFunction =
entity -> ((AccumulatedEntity) entity).publishingId();
private final long enqueueTimeoutMs;
private final boolean blockOnMaxUnconfirmed;
private final boolean retryOnRecovery;
private volatile Client client;
private volatile byte publisherId;
private volatile Status status;
private volatile ScheduledFuture<?> confirmTimeoutFuture;
private final short publishVersion;
@SuppressFBWarnings("CT_CONSTRUCTOR_THROW")
StreamProducer(
String name,
String stream,
int subEntrySize,
int batchSize,
Compression compression,
Duration batchPublishingDelay,
int maxUnconfirmedMessages,
Duration confirmTimeout,
Duration enqueueTimeout,
boolean retryOnRecovery,
Function<Message, String> filterValueExtractor,
StreamEnvironment environment) {
if (filterValueExtractor != null && !environment.filteringSupported()) {
throw new IllegalArgumentException(
"Filtering is not supported by the broker "
+ "(requires RabbitMQ 3.13+ and stream_filtering feature flag activated");
}
this.id = ID_SEQUENCE.getAndIncrement();
this.environment = environment;
this.name = name;
this.stream = stream;
this.enqueueTimeoutMs = enqueueTimeout.toMillis();
this.retryOnRecovery = retryOnRecovery;
this.blockOnMaxUnconfirmed = enqueueTimeout.isZero();
this.closingCallback = environment.registerProducer(this, name, this.stream);
final Client.OutboundEntityWriteCallback delegateWriteCallback;
AtomicLong publishingSequence = new AtomicLong(computeFirstValueOfPublishingSequence());
ToLongFunction<Message> accumulatorPublishSequenceFunction =
msg -> {
if (msg.hasPublishingId()) {
return msg.getPublishingId();
} else {
return publishingSequence.getAndIncrement();
}
};
if (subEntrySize <= 1) {
this.accumulator =
new SimpleMessageAccumulator(
batchSize,
environment.codec(),
client.maxFrameSize(),
accumulatorPublishSequenceFunction,
filterValueExtractor,
this.environment.clock(),
stream,
this.environment.observationCollector());
if (filterValueExtractor == null) {
delegateWriteCallback = Client.OUTBOUND_MESSAGE_WRITE_CALLBACK;
} else {
delegateWriteCallback = OUTBOUND_MSG_FILTER_VALUE_WRITE_CALLBACK;
}
} else {
this.accumulator =
new SubEntryMessageAccumulator(
subEntrySize,
batchSize,
compression == Compression.NONE
? null
: environment.compressionCodecFactory().get(compression),
environment.codec(),
this.environment.byteBufAllocator(),
client.maxFrameSize(),
accumulatorPublishSequenceFunction,
this.environment.clock(),
stream,
environment.observationCollector());
delegateWriteCallback = Client.OUTBOUND_MESSAGE_BATCH_WRITE_CALLBACK;
}
this.maxUnconfirmedMessages = maxUnconfirmedMessages;
this.unconfirmedMessagesSemaphore = new Semaphore(maxUnconfirmedMessages, true);
this.unconfirmedMessages = new ConcurrentHashMap<>(this.maxUnconfirmedMessages, 0.75f, 2);
if (filterValueExtractor == null) {
this.publishVersion = VERSION_1;
this.writeCallback =
new Client.OutboundEntityWriteCallback() {
@Override
public int write(ByteBuf bb, Object entity, long publishingId) {
MessageAccumulator.AccumulatedEntity accumulatedEntity =
(MessageAccumulator.AccumulatedEntity) entity;
unconfirmedMessages.put(publishingId, accumulatedEntity);
return delegateWriteCallback.write(
bb, accumulatedEntity.encodedEntity(), publishingId);
}
@Override
public int fragmentLength(Object entity) {
return delegateWriteCallback.fragmentLength(
((MessageAccumulator.AccumulatedEntity) entity).encodedEntity());
}
};
} else {
this.publishVersion = VERSION_2;
this.writeCallback =
new Client.OutboundEntityWriteCallback() {
@Override
public int write(ByteBuf bb, Object entity, long publishingId) {
MessageAccumulator.AccumulatedEntity accumulatedEntity =
(MessageAccumulator.AccumulatedEntity) entity;
unconfirmedMessages.put(publishingId, accumulatedEntity);
return delegateWriteCallback.write(bb, accumulatedEntity, publishingId);
}
@Override
public int fragmentLength(Object entity) {
return delegateWriteCallback.fragmentLength(entity);
}
};
}
if (!batchPublishingDelay.isNegative() && !batchPublishingDelay.isZero()) {
AtomicReference<Runnable> taskReference = new AtomicReference<>();
Runnable task =
() -> {
if (canSend()) {
synchronized (StreamProducer.this) {
publishBatch(true);
}
}
if (status != Status.CLOSED) {
environment
.scheduledExecutorService()
.schedule(
namedRunnable(
taskReference.get(),
"Background batch publishing task for publisher %d on stream '%s'",
this.id,
this.stream),
batchPublishingDelay.toMillis(),
TimeUnit.MILLISECONDS);
}
};
taskReference.set(task);
environment
.scheduledExecutorService()
.schedule(
namedRunnable(
task,
"Background batch publishing task for publisher %d on stream '%s'",
this.id,
this.stream),
batchPublishingDelay.toMillis(),
TimeUnit.MILLISECONDS);
}
this.batchSize = batchSize;
this.codec = environment.codec();
if (!confirmTimeout.isZero()) {
AtomicReference<Runnable> taskReference = new AtomicReference<>();
Runnable confirmTimeoutTask = confirmTimeoutTask(confirmTimeout);
Runnable wrapperTask =
() -> {
try {
confirmTimeoutTask.run();
} catch (Exception e) {
LOGGER.info("Error while executing confirm timeout check task: {}", e.getCause());
}
if (this.status != Status.CLOSED) {
this.confirmTimeoutFuture =
this.environment
.scheduledExecutorService()
.schedule(
namedRunnable(
taskReference.get(),
"Background confirm timeout task for producer %d on stream %s",
this.id,
this.stream),
confirmTimeout.toMillis(),
TimeUnit.MILLISECONDS);
}
};
taskReference.set(wrapperTask);
this.confirmTimeoutFuture =
this.environment
.scheduledExecutorService()
.schedule(
namedRunnable(
taskReference.get(),
"Background confirm timeout task for producer %d on stream %s",
this.id,
this.stream),
confirmTimeout.toMillis(),
TimeUnit.MILLISECONDS);
}
this.status = Status.RUNNING;
}
private Runnable confirmTimeoutTask(Duration confirmTimeout) {
return () -> {
long limit = this.environment.clock().time() - confirmTimeout.toNanos();
SortedMap<Long, AccumulatedEntity> unconfirmedSnapshot =
new TreeMap<>(this.unconfirmedMessages);
int count = 0;
for (Entry<Long, AccumulatedEntity> unconfirmedEntry : unconfirmedSnapshot.entrySet()) {
if (unconfirmedEntry.getValue().time() < limit) {
if (Thread.currentThread().isInterrupted()) {
return;
}
error(unconfirmedEntry.getKey(), Constants.CODE_PUBLISH_CONFIRM_TIMEOUT);
count++;
} else {
// everything else is after, so we can stop
break;
}
}
if (count > 0) {
LOGGER.debug(
"{} outbound message(s) had reached the confirm timeout (limit {}) "
+ "for producer {} on stream '{}', application notified with callback",
count,
limit,
this.id,
this.stream);
}
};
}
private long computeFirstValueOfPublishingSequence() {
if (name == null || name.isEmpty()) {
return 0;
} else {
long lastPublishingId = this.client.queryPublisherSequence(this.name, this.stream);
if (lastPublishingId == 0) {
return 0;
} else {
return lastPublishingId + 1;
}
}
}
void confirm(long publishingId) {
AccumulatedEntity accumulatedEntity = this.unconfirmedMessages.remove(publishingId);
if (accumulatedEntity != null) {
int confirmedCount =
accumulatedEntity.confirmationCallback().handle(true, Constants.RESPONSE_CODE_OK);
this.unconfirmedMessagesSemaphore.release(confirmedCount);
} else {
this.unconfirmedMessagesSemaphore.release();
}
}
void error(long publishingId, short errorCode) {
AccumulatedEntity accumulatedEntity = unconfirmedMessages.remove(publishingId);
if (accumulatedEntity != null) {
int nackedCount = accumulatedEntity.confirmationCallback().handle(false, errorCode);
this.unconfirmedMessagesSemaphore.release(nackedCount);
} else {
unconfirmedMessagesSemaphore.release();
}
}
@Override
public MessageBuilder messageBuilder() {
return codec.messageBuilder();
}
@Override
public long getLastPublishingId() {
checkNotClosed();
if (this.name != null && !this.name.isEmpty()) {
if (canSend()) {
try {
return this.client.queryPublisherSequence(this.name, this.stream);
} catch (Exception e) {
throw new IllegalStateException(
"Error while trying to query last publishing ID for "
+ "producer "
+ this.name
+ " on stream "
+ stream);
}
} else {
throw new IllegalStateException("The producer has no connection");
}
} else {
throw new IllegalStateException("The producer has no name");
}
}
@Override
public void send(Message message, ConfirmationHandler confirmationHandler) {
if (confirmationHandler == null) {
confirmationHandler = NO_OP_CONFIRMATION_HANDLER;
}
try {
if (canSend()) {
if (this.blockOnMaxUnconfirmed) {
unconfirmedMessagesSemaphore.acquire();
doSend(message, confirmationHandler);
} else {
if (unconfirmedMessagesSemaphore.tryAcquire(
this.enqueueTimeoutMs, TimeUnit.MILLISECONDS)) {
doSend(message, confirmationHandler);
} else {
confirmationHandler.handle(
new ConfirmationStatus(message, false, CODE_MESSAGE_ENQUEUEING_FAILED));
}
}
} else {
failPublishing(message, confirmationHandler);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new StreamException("Interrupted while waiting to accumulate outbound message", e);
}
}
private void doSend(Message message, ConfirmationHandler confirmationHandler) {
if (canSend()) {
if (accumulator.add(message, confirmationHandler)) {
synchronized (this) {
publishBatch(true);
}
}
} else {
failPublishing(message, confirmationHandler);
}
}
private void failPublishing(Message message, ConfirmationHandler confirmationHandler) {
if (this.status == Status.NOT_AVAILABLE) {
confirmationHandler.handle(
new ConfirmationStatus(message, false, CODE_PRODUCER_NOT_AVAILABLE));
} else if (this.status == Status.CLOSED) {
confirmationHandler.handle(new ConfirmationStatus(message, false, CODE_PRODUCER_CLOSED));
} else {
confirmationHandler.handle(
new ConfirmationStatus(message, false, CODE_PRODUCER_NOT_AVAILABLE));
}
}
private boolean canSend() {
return this.status == Status.RUNNING;
}
@Override
public void close() {
if (this.closed.compareAndSet(false, true)) {
if (this.status == Status.RUNNING && this.client != null) {
LOGGER.debug("Deleting producer {}", this.publisherId);
Response response = this.client.deletePublisher(this.publisherId);
if (!response.isOk()) {
LOGGER.info(
"Could not delete publisher {} on producer closing: {}",
this.publisherId,
formatConstant(response.getResponseCode()));
}
} else {
LOGGER.debug(
"No need to delete producer {}, it is currently unavailable", this.publisherId);
}
this.environment.removeProducer(this);
closeFromEnvironment();
}
}
void closeFromEnvironment() {
this.closingCallback.run();
cancelConfirmTimeoutTask();
this.closed.set(true);
this.status = Status.CLOSED;
LOGGER.debug("Closed publisher {} successfully", this.publisherId);
}
void closeAfterStreamDeletion(short code) {
if (closed.compareAndSet(false, true)) {
if (!this.unconfirmedMessages.isEmpty()) {
Iterator<Entry<Long, AccumulatedEntity>> iterator =
unconfirmedMessages.entrySet().iterator();
while (iterator.hasNext()) {
AccumulatedEntity entry = iterator.next().getValue();
int confirmedCount = entry.confirmationCallback().handle(false, code);
this.unconfirmedMessagesSemaphore.release(confirmedCount);
iterator.remove();
}
}
cancelConfirmTimeoutTask();
this.environment.removeProducer(this);
this.status = Status.CLOSED;
}
}
private void cancelConfirmTimeoutTask() {
if (this.confirmTimeoutFuture != null) {
this.confirmTimeoutFuture.cancel(true);
}
}
private void publishBatch(boolean stateCheck) {
if ((!stateCheck || canSend()) && !accumulator.isEmpty()) {
List<Object> messages = new ArrayList<>(this.batchSize);
int batchCount = 0;
while (batchCount != this.batchSize) {
Object accMessage = accumulator.get();
if (accMessage == null) {
break;
}
messages.add(accMessage);
batchCount++;
}
client.publishInternal(
this.publishVersion,
this.publisherId,
messages,
this.writeCallback,
this.publishSequenceFunction);
}
}
boolean isOpen() {
return !this.closed.get();
}
void unavailable() {
this.status = Status.NOT_AVAILABLE;
}
void running() {
synchronized (this) {
if (!this.retryOnRecovery) {
LOGGER.debug(
"Skip to republish {} unconfirmed message(s) and re-publishing {} accumulated message(s)",
this.unconfirmedMessages.size(),
this.accumulator.size());
this.unconfirmedMessages.clear();
int toRelease = maxUnconfirmedMessages - unconfirmedMessagesSemaphore.availablePermits();
if (toRelease > 0) {
unconfirmedMessagesSemaphore.release(toRelease);
}
publishBatch(false);
} else {
LOGGER.debug(
"Re-publishing {} unconfirmed message(s) and {} accumulated message(s)",
this.unconfirmedMessages.size(),
this.accumulator.size());
if (!this.unconfirmedMessages.isEmpty()) {
Map<Long, AccumulatedEntity> messagesToResend = new TreeMap<>(this.unconfirmedMessages);
this.unconfirmedMessages.clear();
Iterator<Entry<Long, AccumulatedEntity>> resendIterator =
messagesToResend.entrySet().iterator();
while (resendIterator.hasNext()) {
List<Object> messages = new ArrayList<>(this.batchSize);
int batchCount = 0;
while (batchCount != this.batchSize) {
Object accMessage = resendIterator.hasNext() ? resendIterator.next().getValue() : null;
if (accMessage == null) {
break;
}
messages.add(accMessage);
batchCount++;
}
client.publishInternal(
this.publishVersion,
this.publisherId,
messages,
this.writeCallback,
this.publishSequenceFunction);
}
}
publishBatch(false);
int toRelease = maxUnconfirmedMessages - unconfirmedMessagesSemaphore.availablePermits();
if (toRelease > 0) {
unconfirmedMessagesSemaphore.release(toRelease);
if (!unconfirmedMessagesSemaphore.tryAcquire(this.unconfirmedMessages.size())) {
LOGGER.debug(
"Could not acquire {} permit(s) for message republishing",
this.unconfirmedMessages.size());
}
}
}
}
this.status = Status.RUNNING;
}
synchronized void setClient(Client client) {
this.client = client;
}
synchronized void setPublisherId(byte publisherId) {
this.publisherId = publisherId;
}
Status status() {
return this.status;
}
enum Status {
RUNNING,
NOT_AVAILABLE,
CLOSED
}
interface ConfirmationCallback {
int handle(boolean confirmed, short code);
Message message();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StreamProducer that = (StreamProducer) o;
return id == that.id && stream.equals(that.stream);
}
@Override
public int hashCode() {
return Objects.hash(id, stream);
}
@Override
public String toString() {
Client client = this.client;
return "{ "
+ "\"id\" : "
+ id
+ ","
+ "\"stream\" : \""
+ stream
+ "\","
+ "\"publishing_client\" : "
+ (client == null ? "null" : ("\"" + client.connectionName() + "\""))
+ "}";
}
private void checkNotClosed() {
if (this.closed.get()) {
throw new IllegalStateException("This producer instance has been closed");
}
}
private static final Client.OutboundEntityWriteCallback OUTBOUND_MSG_FILTER_VALUE_WRITE_CALLBACK =
new OutboundMessageFilterValueWriterCallback();
private static final class OutboundMessageFilterValueWriterCallback
implements Client.OutboundEntityWriteCallback {
@Override
public int write(ByteBuf bb, Object entity, long publishingId) {
AccumulatedEntity accumulatedEntity = (AccumulatedEntity) entity;
String filterValue = accumulatedEntity.filterValue();
if (filterValue == null) {
bb.writeShort(-1);
} else {
bb.writeShort(filterValue.length());
bb.writeBytes(filterValue.getBytes(StandardCharsets.UTF_8));
}
Codec.EncodedMessage messageToPublish =
(Codec.EncodedMessage) accumulatedEntity.encodedEntity();
bb.writeInt(messageToPublish.getSize());
bb.writeBytes(messageToPublish.getData(), 0, messageToPublish.getSize());
return 1;
}
@Override
public int fragmentLength(Object entity) {
AccumulatedEntity accumulatedEntity = (AccumulatedEntity) entity;
Codec.EncodedMessage message = (Codec.EncodedMessage) accumulatedEntity.encodedEntity();
String filterValue = accumulatedEntity.filterValue();
if (filterValue == null) {
return 8 + 2 + 4 + message.getSize();
} else {
return 8 + 2 + accumulatedEntity.filterValue().length() + 4 + message.getSize();
}
}
}
}