-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathClient.java
2912 lines (2579 loc) · 99.9 KB
/
Client.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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.DEFAULT_USERNAME;
import static com.rabbitmq.stream.impl.Utils.encodeRequestCode;
import static com.rabbitmq.stream.impl.Utils.encodeResponseCode;
import static com.rabbitmq.stream.impl.Utils.extractResponseCode;
import static com.rabbitmq.stream.impl.Utils.formatConstant;
import static com.rabbitmq.stream.impl.Utils.noOpConsumer;
import static java.lang.String.format;
import static java.lang.String.join;
import static java.util.Arrays.asList;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.stream.StreamSupport.stream;
import com.rabbitmq.stream.AuthenticationFailureException;
import com.rabbitmq.stream.ByteCapacity;
import com.rabbitmq.stream.ChunkChecksum;
import com.rabbitmq.stream.Codec;
import com.rabbitmq.stream.Codec.EncodedMessage;
import com.rabbitmq.stream.Constants;
import com.rabbitmq.stream.Environment;
import com.rabbitmq.stream.Message;
import com.rabbitmq.stream.MessageBuilder;
import com.rabbitmq.stream.OffsetSpecification;
import com.rabbitmq.stream.Producer;
import com.rabbitmq.stream.StreamCreator.LeaderLocator;
import com.rabbitmq.stream.StreamException;
import com.rabbitmq.stream.compression.Compression;
import com.rabbitmq.stream.compression.CompressionCodec;
import com.rabbitmq.stream.compression.CompressionCodecFactory;
import com.rabbitmq.stream.impl.Client.ShutdownContext.ShutdownReason;
import com.rabbitmq.stream.impl.ServerFrameHandler.FrameHandler;
import com.rabbitmq.stream.impl.ServerFrameHandler.FrameHandlerInfo;
import com.rabbitmq.stream.impl.Utils.NamedThreadFactory;
import com.rabbitmq.stream.metrics.MetricsCollector;
import com.rabbitmq.stream.metrics.NoOpMetricsCollector;
import com.rabbitmq.stream.sasl.CredentialsProvider;
import com.rabbitmq.stream.sasl.DefaultSaslConfiguration;
import com.rabbitmq.stream.sasl.DefaultUsernamePasswordCredentialsProvider;
import com.rabbitmq.stream.sasl.SaslConfiguration;
import com.rabbitmq.stream.sasl.SaslMechanism;
import com.rabbitmq.stream.sasl.UsernamePasswordCredentialsProvider;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.ConnectTimeoutException;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.flush.FlushConsolidationHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.ToLongFunction;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is low-level client API to communicate with the broker.
*
* <p><b>It is not meant for public usage and can change at any time.</b>
*
* <p>Users are encouraged to use the {@link Environment}, {@link Producer}, {@link
* com.rabbitmq.stream.Consumer} API, and their respective builders to interact with the broker.
*
* <p>People wanting very fine control over their interaction with the broker can use {@link Client}
* but at their own risk.
*/
public class Client implements AutoCloseable {
private static final Charset CHARSET = StandardCharsets.UTF_8;
public static final int DEFAULT_PORT = 5552;
public static final int DEFAULT_TLS_PORT = 5551;
static final int MAX_REFERENCE_SIZE = 256;
static final OutboundEntityWriteCallback OUTBOUND_MESSAGE_WRITE_CALLBACK =
new OutboundMessageWriteCallback();
static final OutboundEntityWriteCallback OUTBOUND_MESSAGE_BATCH_WRITE_CALLBACK =
new OutboundMessageBatchWriteCallback();
static final String NETTY_HANDLER_FRAME_DECODER =
LengthFieldBasedFrameDecoder.class.getSimpleName();
static final String NETTY_HANDLER_IDLE_STATE = IdleStateHandler.class.getSimpleName();
static final Duration DEFAULT_RPC_TIMEOUT = Duration.ofSeconds(10);
private static final PublishConfirmListener NO_OP_PUBLISH_CONFIRM_LISTENER =
(publisherId, publishingId) -> {};
private static final PublishErrorListener NO_OP_PUBLISH_ERROR_LISTENER =
(publisherId, publishingId, errorCode) -> {};
private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);
final PublishConfirmListener publishConfirmListener;
final PublishErrorListener publishErrorListener;
final ChunkListener chunkListener;
final MessageListener messageListener;
final MessageIgnoredListener messageIgnoredListener;
final CreditNotification creditNotification;
final ConsumerUpdateListener consumerUpdateListener;
final MetadataListener metadataListener;
final Codec codec;
final Channel channel;
final ConcurrentMap<Integer, OutstandingRequest<?>> outstandingRequests =
new ConcurrentHashMap<>();
final List<SubscriptionOffset> subscriptionOffsets = new CopyOnWriteArrayList<>();
final ExecutorService executorService;
final ExecutorService dispatchingExecutorService;
final TuneState tuneState;
final AtomicBoolean closing = new AtomicBoolean(false);
final AtomicBoolean shuttingDownDispatching = new AtomicBoolean(false);
final ChunkChecksum chunkChecksum;
final MetricsCollector metricsCollector;
final CompressionCodecFactory compressionCodecFactory;
private final Consumer<ShutdownContext.ShutdownReason> shutdownListenerCallback;
private final ToLongFunction<Object> publishSequenceFunction =
new ToLongFunction<Object>() {
private final AtomicLong publishSequence = new AtomicLong(0);
@Override
public long applyAsLong(Object value) {
return publishSequence.getAndIncrement();
}
};
private final AtomicInteger correlationSequence = new AtomicInteger(0);
private final Runnable executorServiceClosing;
private final SaslConfiguration saslConfiguration;
private final CredentialsProvider credentialsProvider;
private final Runnable nettyClosing;
private final int maxFrameSize;
private final boolean frameSizeCopped;
private final EventLoopGroup eventLoopGroup;
private final Map<String, String> clientProperties;
private final String NETTY_HANDLER_FLUSH_CONSOLIDATION =
FlushConsolidationHandler.class.getSimpleName();
private final String NETTY_HANDLER_STREAM = StreamHandler.class.getSimpleName();
private final String host;
private final String clientConnectionName;
private final int port;
private final Map<String, String> serverProperties;
private final Map<String, String> connectionProperties;
private final Duration rpcTimeout;
private final List<String> saslMechanisms;
private volatile ShutdownReason shutdownReason = null;
private final Runnable streamStatsCommandVersionsCheck;
private final boolean filteringSupported;
private final Runnable superStreamManagementCommandVersionsCheck;
@SuppressFBWarnings("CT_CONSTRUCTOR_THROW")
public Client() {
this(new ClientParameters());
}
@SuppressFBWarnings("CT_CONSTRUCTOR_THROW")
public Client(ClientParameters parameters) {
this.publishConfirmListener = parameters.publishConfirmListener;
this.publishErrorListener = parameters.publishErrorListener;
this.chunkListener = parameters.chunkListener;
this.messageListener = parameters.messageListener;
this.messageIgnoredListener = parameters.messageIgnoredListener;
this.creditNotification = parameters.creditNotification;
this.codec = parameters.codec == null ? Codecs.DEFAULT : parameters.codec;
this.saslConfiguration = parameters.saslConfiguration;
this.credentialsProvider = parameters.credentialsProvider;
this.chunkChecksum = parameters.chunkChecksum;
this.metricsCollector = parameters.metricsCollector;
this.metadataListener = parameters.metadataListener;
this.consumerUpdateListener = parameters.consumerUpdateListener;
this.compressionCodecFactory =
parameters.compressionCodecFactory == null
? compression -> null
: parameters.compressionCodecFactory;
this.rpcTimeout = parameters.rpcTimeout == null ? DEFAULT_RPC_TIMEOUT : parameters.rpcTimeout;
final ShutdownListener shutdownListener = parameters.shutdownListener;
final AtomicBoolean started = new AtomicBoolean(false);
this.shutdownListenerCallback =
Utils.makeIdempotent(
shutdownReason -> {
// the channel can become inactive even though the opening is not done yet,
// so we guard the shutdown listener invocation to avoid trying to reconnect
// even before having connected. The caller should be notified of the failure
// by an exception anyway.
if (started.get()) {
this.metricsCollector.closeConnection();
shutdownListener.handle(new ShutdownContext(shutdownReason));
}
});
Consumer<Bootstrap> bootstrapCustomizer =
parameters.bootstrapCustomizer == null ? noOpConsumer() : parameters.bootstrapCustomizer;
Bootstrap b = new Bootstrap();
bootstrapCustomizer.accept(b);
if (b.config().group() == null) {
EventLoopGroup eventLoopGroup;
if (parameters.eventLoopGroup == null) {
this.eventLoopGroup = new NioEventLoopGroup();
eventLoopGroup = this.eventLoopGroup;
} else {
this.eventLoopGroup = null;
eventLoopGroup = parameters.eventLoopGroup;
}
b.group(eventLoopGroup);
} else {
this.eventLoopGroup = null;
}
if (b.config().channelFactory() == null) {
b.channel(NioSocketChannel.class);
}
if (!b.config().options().containsKey(ChannelOption.SO_KEEPALIVE)) {
b.option(ChannelOption.SO_KEEPALIVE, true);
}
if (!b.config().options().containsKey(ChannelOption.ALLOCATOR)) {
b.option(
ChannelOption.ALLOCATOR,
parameters.byteBufAllocator == null
? ByteBufAllocator.DEFAULT
: parameters.byteBufAllocator);
}
Consumer<Channel> channelCustomizer =
parameters.channelCustomizer == null ? noOpConsumer() : parameters.channelCustomizer;
b.handler(
new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ch.pipeline()
.addFirst(
NETTY_HANDLER_FLUSH_CONSOLIDATION,
new FlushConsolidationHandler(
FlushConsolidationHandler.DEFAULT_EXPLICIT_FLUSH_AFTER_FLUSHES, true));
ch.pipeline()
.addLast(
NETTY_HANDLER_FRAME_DECODER,
new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
ch.pipeline().addLast(NETTY_HANDLER_STREAM, new StreamHandler());
ch.pipeline().addLast(new MetricsHandler(metricsCollector));
if (parameters.sslContext != null) {
SslHandler sslHandler =
parameters.sslContext.newHandler(ch.alloc(), parameters.host, parameters.port);
if (parameters.tlsHostnameVerification) {
SSLEngine sslEngine = sslHandler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParameters);
}
ch.pipeline().addFirst("ssl", sslHandler);
}
channelCustomizer.accept(ch);
}
});
ChannelFuture f;
String clientConnectionName = parameters.clientProperties.getOrDefault("connection_name", "");
try {
LOGGER.debug(
"Trying to create stream connection to {}:{}, with client connection name '{}'",
parameters.host,
parameters.port,
clientConnectionName);
f = b.connect(parameters.host, parameters.port).sync();
this.host = parameters.host;
this.port = parameters.port;
this.clientConnectionName = clientConnectionName;
} catch (Exception e) {
String message =
format(
"Error while creating stream connection to %s:%d", parameters.host, parameters.port);
if (e instanceof ConnectTimeoutException) {
throw new TimeoutStreamException(message, e);
} else if (e instanceof ConnectException) {
throw new ConnectionStreamException(message, e);
} else {
throw new StreamException(message, e);
}
}
this.channel = f.channel();
this.nettyClosing = Utils.makeIdempotent(this::closeNetty);
ExecutorServiceFactory executorServiceFactory = parameters.executorServiceFactory;
if (executorServiceFactory == null) {
this.executorService =
Executors.newSingleThreadExecutor(new NamedThreadFactory(clientConnectionName + "-"));
} else {
this.executorService = executorServiceFactory.get();
}
ExecutorServiceFactory dispatchingExecutorServiceFactory =
parameters.dispatchingExecutorServiceFactory;
if (dispatchingExecutorServiceFactory == null) {
this.dispatchingExecutorService =
Executors.newSingleThreadExecutor(
new NamedThreadFactory("dispatching-" + clientConnectionName + "-"));
} else {
this.dispatchingExecutorService = dispatchingExecutorServiceFactory.get();
}
this.executorServiceClosing =
Utils.makeIdempotent(
() -> {
if (dispatchingExecutorServiceFactory == null) {
List<Runnable> outstandingTasks = this.dispatchingExecutorService.shutdownNow();
this.shuttingDownDispatching.set(true);
for (Runnable outstandingTask : outstandingTasks) {
try {
outstandingTask.run();
} catch (Exception e) {
LOGGER.info(
"Error while releasing buffer in outstanding connection tasks: {}",
e.getMessage());
}
}
} else {
dispatchingExecutorServiceFactory.clientClosed(this.dispatchingExecutorService);
}
if (executorServiceFactory == null) {
this.executorService.shutdownNow();
} else {
executorServiceFactory.clientClosed(this.executorService);
}
});
try {
this.tuneState =
new TuneState(
parameters.requestedMaxFrameSize, (int) parameters.requestedHeartbeat.getSeconds());
this.clientProperties = clientProperties(parameters.clientProperties);
this.serverProperties = peerProperties();
this.saslMechanisms = getSaslMechanisms();
authenticate(this.credentialsProvider);
this.tuneState.await(Duration.ofSeconds(10));
this.maxFrameSize = this.tuneState.getMaxFrameSize();
this.frameSizeCopped = this.maxFrameSize() > 0;
LOGGER.debug(
"Connection tuned with max frame size {} and heartbeat {}",
this.maxFrameSize(),
tuneState.getHeartbeat());
this.connectionProperties = open(parameters.virtualHost);
Set<FrameHandlerInfo> supportedCommands = maybeExchangeCommandVersions();
AtomicBoolean streamStatsSupported = new AtomicBoolean(false);
AtomicBoolean filteringSupportedReference = new AtomicBoolean(false);
AtomicBoolean superStreamManagementSupported = new AtomicBoolean(false);
supportedCommands.forEach(
c -> {
if (c.getKey() == COMMAND_STREAM_STATS) {
streamStatsSupported.set(true);
}
if (c.getKey() == COMMAND_PUBLISH && c.getMaxVersion() >= VERSION_2) {
filteringSupportedReference.set(true);
}
if (c.getKey() == COMMAND_CREATE_SUPER_STREAM) {
superStreamManagementSupported.set(true);
}
});
this.streamStatsCommandVersionsCheck =
streamStatsSupported.get()
? () -> {}
: () -> {
throw new UnsupportedOperationException(
"QueryStreamInfo is available only on RabbitMQ 3.11 or more.");
};
this.filteringSupported = filteringSupportedReference.get();
this.superStreamManagementCommandVersionsCheck =
superStreamManagementSupported.get()
? () -> {}
: () -> {
throw new UnsupportedOperationException(
"Super stream management is available only on RabbitMQ 3.13 or more.");
};
started.set(true);
this.metricsCollector.openConnection();
} catch (RuntimeException e) {
this.closingSequence(null);
throw e;
}
}
private static class MetricsHandler extends ChannelOutboundHandlerAdapter {
private final MetricsCollector metricsCollector;
private MetricsHandler(MetricsCollector metricsCollector) {
this.metricsCollector = metricsCollector;
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
throws Exception {
metricsCollector.writtenBytes(((ByteBuf) msg).capacity());
super.write(ctx, msg, promise);
}
}
private static Map<String, String> clientProperties(Map<String, String> fromParameters) {
fromParameters = fromParameters == null ? Collections.emptyMap() : fromParameters;
Map<String, String> clientProperties = new HashMap<>(fromParameters);
clientProperties.putAll(ClientProperties.DEFAULT_CLIENT_PROPERTIES);
return Collections.unmodifiableMap(clientProperties);
}
static void checkMessageFitsInFrame(int maxFrameSize, Codec.EncodedMessage encodedMessage) {
int frameBeginning = 4 + 2 + 2 + 4 + 8 + 4 + encodedMessage.getSize();
if (frameBeginning > maxFrameSize) {
throw new IllegalArgumentException(
"Message too big to fit in one frame: " + encodedMessage.getSize());
}
}
Codec codec() {
return codec;
}
int maxFrameSize() {
return this.maxFrameSize;
}
private Map<String, String> peerProperties() {
int clientPropertiesSize = mapSize(this.clientProperties);
int length = 2 + 2 + 4 + clientPropertiesSize;
int correlationId = correlationSequence.incrementAndGet();
try {
ByteBuf bb = allocateNoCheck(length + 4);
bb.writeInt(length);
bb.writeShort(encodeRequestCode(COMMAND_PEER_PROPERTIES));
bb.writeShort(VERSION_1);
bb.writeInt(correlationId);
writeMap(bb, this.clientProperties);
OutstandingRequest<Map<String, String>> request = outstandingRequest();
outstandingRequests.put(correlationId, request);
channel.writeAndFlush(bb);
request.block();
if (request.error() == null) {
return request.response.get();
} else {
throw new StreamException("Error when establishing stream connection", request.error());
}
} catch (StreamException e) {
outstandingRequests.remove(correlationId);
throw e;
} catch (RuntimeException e) {
outstandingRequests.remove(correlationId);
throw new StreamException("Error while trying to exchange peer properties", e);
}
}
void authenticate(CredentialsProvider credentialsProvider) {
SaslMechanism saslMechanism = this.saslConfiguration.getSaslMechanism(this.saslMechanisms);
byte[] challenge = null;
boolean authDone = false;
while (!authDone) {
byte[] saslResponse = saslMechanism.handleChallenge(challenge, credentialsProvider);
SaslAuthenticateResponse saslAuthenticateResponse =
sendSaslAuthenticate(saslMechanism, saslResponse);
if (saslAuthenticateResponse.isOk()) {
authDone = true;
} else if (saslAuthenticateResponse.isChallenge()) {
challenge = saslAuthenticateResponse.challenge;
} else if (saslAuthenticateResponse.isAuthenticationFailure()) {
String message =
"Unexpected response code during authentication: "
+ formatConstant(saslAuthenticateResponse.getResponseCode());
if (saslAuthenticateResponse.getResponseCode()
== RESPONSE_CODE_AUTHENTICATION_FAILURE_LOOPBACK) {
message +=
". The user is not authorized to connect from a remote host. "
+ "If the broker is running locally, make sure the '"
+ this.host
+ "' hostname is resolved to "
+ "the loopback interface (localhost, 127.0.0.1, ::1). "
+ "See https://www.rabbitmq.com/access-control.html#loopback-users.";
}
throw new AuthenticationFailureException(
message, saslAuthenticateResponse.getResponseCode());
} else {
throw new StreamException(
"Unexpected response code during authentication: "
+ formatConstant(saslAuthenticateResponse.getResponseCode()));
}
}
}
private SaslAuthenticateResponse sendSaslAuthenticate(
SaslMechanism saslMechanism, byte[] challengeResponse) {
int length =
2
+ 2
+ 4
+ 2
+ saslMechanism.getName().length()
+ 4
+ (challengeResponse == null ? 0 : challengeResponse.length);
int correlationId = correlationSequence.incrementAndGet();
try {
ByteBuf bb = allocateNoCheck(length + 4);
bb.writeInt(length);
bb.writeShort(encodeRequestCode(COMMAND_SASL_AUTHENTICATE));
bb.writeShort(VERSION_1);
bb.writeInt(correlationId);
bb.writeShort(saslMechanism.getName().length());
bb.writeBytes(saslMechanism.getName().getBytes(CHARSET));
if (challengeResponse == null) {
bb.writeInt(-1);
} else {
bb.writeInt(challengeResponse.length).writeBytes(challengeResponse);
}
OutstandingRequest<SaslAuthenticateResponse> request = outstandingRequest();
outstandingRequests.put(correlationId, request);
channel.writeAndFlush(bb);
request.block();
return request.response.get();
} catch (StreamException e) {
outstandingRequests.remove(correlationId);
throw e;
} catch (RuntimeException e) {
outstandingRequests.remove(correlationId);
throw new StreamException("Error while trying to authenticate", e);
}
}
private Map<String, String> open(String virtualHost) {
int length = 2 + 2 + 4 + 2 + virtualHost.length();
int correlationId = correlationSequence.incrementAndGet();
try {
ByteBuf bb = allocate(length + 4);
bb.writeInt(length);
bb.writeShort(encodeRequestCode(COMMAND_OPEN));
bb.writeShort(VERSION_1);
bb.writeInt(correlationId);
bb.writeShort(virtualHost.length());
bb.writeBytes(virtualHost.getBytes(CHARSET));
OutstandingRequest<OpenResponse> request = outstandingRequest();
outstandingRequests.put(correlationId, request);
channel.writeAndFlush(bb);
request.block();
if (!request.response.get().isOk()) {
throw new StreamException(
"Unexpected response code when connecting to virtual host: "
+ formatConstant(request.response.get().getResponseCode()));
}
return request.response.get().connectionProperties;
} catch (StreamException e) {
outstandingRequests.remove(correlationId);
throw e;
} catch (RuntimeException e) {
outstandingRequests.remove(correlationId);
throw new StreamException("Error during open command", e);
}
}
// for testing
void send(byte[] content) {
ByteBuf bb = allocateNoCheck(content.length);
bb.writeBytes(content);
try {
channel.writeAndFlush(bb).sync();
} catch (InterruptedException e) {
throw new StreamException("Error while sending bytes", e);
}
}
private void sendClose(short code, String reason) {
int length = 2 + 2 + 4 + 2 + 2 + reason.length();
int correlationId = correlationSequence.incrementAndGet();
try {
ByteBuf bb = allocate(length + 4);
bb.writeInt(length);
bb.writeShort(encodeRequestCode(COMMAND_CLOSE));
bb.writeShort(VERSION_1);
bb.writeInt(correlationId);
bb.writeShort(code);
bb.writeShort(reason.length());
bb.writeBytes(reason.getBytes(CHARSET));
OutstandingRequest<Response> request = outstandingRequest();
outstandingRequests.put(correlationId, request);
channel.writeAndFlush(bb);
request.block();
if (!request.response.get().isOk()) {
LOGGER.warn(
"Unexpected response code when closing: {}",
formatConstant(request.response.get().getResponseCode()));
throw new StreamException(
"Unexpected response code when closing: "
+ formatConstant(request.response.get().getResponseCode()));
}
} catch (StreamException e) {
outstandingRequests.remove(correlationId);
throw e;
} catch (RuntimeException e) {
outstandingRequests.remove(correlationId);
throw new StreamException("Error while closing connection", e);
}
}
private List<String> getSaslMechanisms() {
int length = 2 + 2 + 4;
int correlationId = correlationSequence.incrementAndGet();
try {
ByteBuf bb = allocateNoCheck(length + 4);
bb.writeInt(length);
bb.writeShort(encodeRequestCode(COMMAND_SASL_HANDSHAKE));
bb.writeShort(VERSION_1);
bb.writeInt(correlationId);
OutstandingRequest<List<String>> request = outstandingRequest();
outstandingRequests.put(correlationId, request);
channel.writeAndFlush(bb);
request.block();
return request.response.get();
} catch (StreamException e) {
outstandingRequests.remove(correlationId);
throw e;
} catch (RuntimeException e) {
outstandingRequests.remove(correlationId);
throw new StreamException("Error while exchanging SASL mechanisms", e);
}
}
public Response create(String stream) {
return create(stream, Collections.emptyMap());
}
public Response create(String stream, Map<String, String> arguments) {
int length = 2 + 2 + 4 + 2 + stream.length() + mapSize(arguments);
int correlationId = correlationSequence.incrementAndGet();
try {
ByteBuf bb = allocate(length + 4);
bb.writeInt(length);
bb.writeShort(encodeRequestCode(COMMAND_CREATE_STREAM));
bb.writeShort(VERSION_1);
bb.writeInt(correlationId);
bb.writeShort(stream.length());
bb.writeBytes(stream.getBytes(CHARSET));
writeMap(bb, arguments);
OutstandingRequest<Response> request = outstandingRequest();
outstandingRequests.put(correlationId, request);
channel.writeAndFlush(bb);
request.block();
return request.response.get();
} catch (StreamException e) {
outstandingRequests.remove(correlationId);
throw e;
} catch (RuntimeException e) {
outstandingRequests.remove(correlationId);
throw new StreamException(format("Error while creating stream '%s'", stream), e);
}
}
Response createSuperStream(
String superStream,
List<String> partitions,
List<String> bindingKeys,
Map<String, String> arguments) {
this.superStreamManagementCommandVersionsCheck.run();
if (partitions.isEmpty() || bindingKeys.isEmpty()) {
throw new IllegalArgumentException(
"Partitions and routing keys of a super stream cannot be empty");
}
if (partitions.size() != bindingKeys.size()) {
throw new IllegalArgumentException(
"Partitions and routing keys of a super stream must have "
+ "the same number of elements");
}
arguments = arguments == null ? Collections.emptyMap() : arguments;
int length =
2
+ 2
+ 4
+ 2
+ superStream.length()
+ collectionSize(partitions)
+ collectionSize(bindingKeys)
+ mapSize(arguments);
int correlationId = correlationSequence.incrementAndGet();
try {
ByteBuf bb = allocate(length + 4);
bb.writeInt(length);
bb.writeShort(encodeRequestCode(COMMAND_CREATE_SUPER_STREAM));
bb.writeShort(VERSION_1);
bb.writeInt(correlationId);
bb.writeShort(superStream.length());
bb.writeBytes(superStream.getBytes(CHARSET));
writeCollection(bb, partitions);
writeCollection(bb, bindingKeys);
writeMap(bb, arguments);
OutstandingRequest<Response> request = outstandingRequest();
outstandingRequests.put(correlationId, request);
channel.writeAndFlush(bb);
request.block();
return request.response.get();
} catch (StreamException e) {
outstandingRequests.remove(correlationId);
throw e;
} catch (RuntimeException e) {
outstandingRequests.remove(correlationId);
throw new StreamException(format("Error while creating super stream '%s'", superStream), e);
}
}
Response deleteSuperStream(String superStream) {
this.superStreamManagementCommandVersionsCheck.run();
int length = 2 + 2 + 4 + 2 + superStream.length();
int correlationId = correlationSequence.incrementAndGet();
try {
ByteBuf bb = allocate(length + 4);
bb.writeInt(length);
bb.writeShort(encodeRequestCode(COMMAND_DELETE_SUPER_STREAM));
bb.writeShort(VERSION_1);
bb.writeInt(correlationId);
bb.writeShort(superStream.length());
bb.writeBytes(superStream.getBytes(CHARSET));
OutstandingRequest<Response> request = outstandingRequest();
outstandingRequests.put(correlationId, request);
channel.writeAndFlush(bb);
request.block();
return request.response.get();
} catch (StreamException e) {
outstandingRequests.remove(correlationId);
throw e;
} catch (RuntimeException e) {
outstandingRequests.remove(correlationId);
throw new StreamException(format("Error while deleting stream '%s'", superStream), e);
}
}
private static int collectionSize(Collection<String> elements) {
return 4 + elements.stream().mapToInt(v -> 2 + v.length()).sum();
}
private static int arraySize(String... elements) {
return collectionSize(asList(elements));
}
private static int mapSize(Map<String, String> elements) {
return 4
+ elements.entrySet().stream()
.mapToInt(e -> 2 + e.getKey().length() + 2 + e.getValue().length())
.sum();
}
private static ByteBuf writeCollection(ByteBuf bb, Collection<String> elements) {
bb.writeInt(elements.size());
elements.forEach(e -> bb.writeShort(e.length()).writeBytes(e.getBytes(CHARSET)));
return bb;
}
private static ByteBuf writeArray(ByteBuf bb, String... elements) {
return writeCollection(bb, asList(elements));
}
private static ByteBuf writeMap(ByteBuf bb, Map<String, String> elements) {
bb.writeInt(elements.size());
elements.forEach(
(key, value) ->
bb.writeShort(key.length())
.writeBytes(key.getBytes(CHARSET))
.writeShort(value.length())
.writeBytes(value.getBytes(CHARSET)));
return bb;
}
ByteBuf allocate(ByteBufAllocator allocator, int capacity) {
if (frameSizeCopped && capacity > this.maxFrameSize()) {
throw new IllegalArgumentException(
"Cannot allocate "
+ capacity
+ " bytes for outbound frame, limit is "
+ this.maxFrameSize());
}
return allocator.buffer(capacity);
}
private ByteBuf allocate(int capacity) {
return allocate(channel.alloc(), capacity);
}
ByteBuf allocateNoCheck(ByteBufAllocator allocator, int capacity) {
return allocator.buffer(capacity);
}
private ByteBuf allocateNoCheck(int capacity) {
return allocateNoCheck(channel.alloc(), capacity);
}
public Response delete(String stream) {
int length = 2 + 2 + 4 + 2 + stream.length();
int correlationId = correlationSequence.incrementAndGet();
try {
ByteBuf bb = allocate(length + 4);
bb.writeInt(length);
bb.writeShort(encodeRequestCode(COMMAND_DELETE_STREAM));
bb.writeShort(VERSION_1);
bb.writeInt(correlationId);
bb.writeShort(stream.length());
bb.writeBytes(stream.getBytes(CHARSET));
OutstandingRequest<Response> request = outstandingRequest();
outstandingRequests.put(correlationId, request);
channel.writeAndFlush(bb);
request.block();
return request.response.get();
} catch (StreamException e) {
outstandingRequests.remove(correlationId);
throw e;
} catch (RuntimeException e) {
outstandingRequests.remove(correlationId);
throw new StreamException(format("Error while deleting stream '%s'", stream), e);
}
}
Map<String, StreamMetadata> metadata(List<String> streams) {
return this.metadata(streams.toArray(new String[] {}));
}
public Map<String, StreamMetadata> metadata(String... streams) {
if (streams == null || streams.length == 0) {
throw new IllegalArgumentException("At least one stream must be specified");
}
int length = 2 + 2 + 4 + arraySize(streams); // API code, version, correlation ID, array size
int correlationId = correlationSequence.incrementAndGet();
try {
ByteBuf bb = allocate(length + 4);
bb.writeInt(length);
bb.writeShort(encodeRequestCode(COMMAND_METADATA));
bb.writeShort(VERSION_1);
bb.writeInt(correlationId);
writeArray(bb, streams);
OutstandingRequest<Map<String, StreamMetadata>> request = outstandingRequest();
outstandingRequests.put(correlationId, request);
channel.writeAndFlush(bb);
request.block();
return request.response.get();
} catch (StreamException e) {
outstandingRequests.remove(correlationId);
throw e;
} catch (RuntimeException e) {
outstandingRequests.remove(correlationId);
throw new StreamException(
format("Error while getting metadata for stream(s) '%s'", join(",", streams)), e);
}
}
public Response declarePublisher(byte publisherId, String publisherReference, String stream) {
int publisherReferenceSize =
(publisherReference == null || publisherReference.isEmpty()
? 0
: publisherReference.length());
if (publisherReferenceSize >= MAX_REFERENCE_SIZE) {
throw new IllegalArgumentException(
"If specified, publisher reference must less than 256 characters");
}
int length = 2 + 2 + 4 + 1 + 2 + publisherReferenceSize + 2 + stream.length();
int correlationId = correlationSequence.getAndIncrement();
try {
ByteBuf bb = allocate(length + 4);
bb.writeInt(length);
bb.writeShort(encodeRequestCode(COMMAND_DECLARE_PUBLISHER));
bb.writeShort(VERSION_1);
bb.writeInt(correlationId);
bb.writeByte(publisherId);
bb.writeShort(publisherReferenceSize);
if (publisherReferenceSize > 0) {
bb.writeBytes(publisherReference.getBytes(CHARSET));
}
bb.writeShort(stream.length());
bb.writeBytes(stream.getBytes(CHARSET));
OutstandingRequest<Response> request = outstandingRequest();
outstandingRequests.put(correlationId, request);
channel.writeAndFlush(bb);
request.block();
return request.response.get();
} catch (StreamException e) {
outstandingRequests.remove(correlationId);
throw e;
} catch (RuntimeException e) {
outstandingRequests.remove(correlationId);
throw new StreamException(
format("Error while declaring publisher for stream '%s'", stream), e);
}
}
public Response deletePublisher(byte publisherId) {
int length = 2 + 2 + 4 + 1;
int correlationId = correlationSequence.getAndIncrement();
try {
ByteBuf bb = allocate(length + 4);
bb.writeInt(length);
bb.writeShort(encodeRequestCode(COMMAND_DELETE_PUBLISHER));
bb.writeShort(VERSION_1);
bb.writeInt(correlationId);
bb.writeByte(publisherId);
OutstandingRequest<Response> request = outstandingRequest();
outstandingRequests.put(correlationId, request);
channel.writeAndFlush(bb);
request.block();
return request.response.get();
} catch (StreamException e) {
outstandingRequests.remove(correlationId);
throw e;
} catch (RuntimeException e) {
outstandingRequests.remove(correlationId);
throw new StreamException("Error while deleting publisher", e);
}
}
public List<Long> publish(byte publisherId, List<Message> messages) {
return this.publish(publisherId, messages, this.publishSequenceFunction);
}
public List<Long> publish(
byte publisherId, List<Message> messages, ToLongFunction<Object> publishSequenceFunction) {
List<Object> encodedMessages = new ArrayList<>(messages.size());
for (Message message : messages) {
Codec.EncodedMessage encodedMessage = codec.encode(message);
checkMessageFitsInFrame(encodedMessage);
encodedMessages.add(encodedMessage);
}
return publishInternal(
VERSION_1,
this.channel,
publisherId,
encodedMessages,
OUTBOUND_MESSAGE_WRITE_CALLBACK,
publishSequenceFunction);
}
public List<Long> publish(
byte publisherId, List<Message> messages, OutboundEntityMappingCallback mappingCallback) {
return this.publish(publisherId, messages, mappingCallback, this.publishSequenceFunction);
}
public List<Long> publish(
byte publisherId,
List<Message> messages,
OutboundEntityMappingCallback mappingCallback,
ToLongFunction<Object> publishSequenceFunction) {
List<Object> encodedMessages = new ArrayList<>(messages.size());
for (Message message : messages) {
Codec.EncodedMessage encodedMessage = codec.encode(message);
checkMessageFitsInFrame(encodedMessage);
OriginalAndEncodedOutboundEntity wrapper =
new OriginalAndEncodedOutboundEntity(message, encodedMessage);
encodedMessages.add(wrapper);
}
return publishInternal(
VERSION_1,
this.channel,
publisherId,
encodedMessages,
new OriginalEncodedEntityOutboundEntityWriteCallback(
mappingCallback, OUTBOUND_MESSAGE_WRITE_CALLBACK),
publishSequenceFunction);