-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathReactorNettyClient.java
1007 lines (782 loc) · 35.4 KB
/
ReactorNettyClient.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 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.r2dbc.postgresql.client;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoop;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import io.r2dbc.postgresql.api.ErrorDetails;
import io.r2dbc.postgresql.api.PostgresqlException;
import io.r2dbc.postgresql.message.backend.BackendKeyData;
import io.r2dbc.postgresql.message.backend.BackendMessage;
import io.r2dbc.postgresql.message.backend.BackendMessageDecoder;
import io.r2dbc.postgresql.message.backend.ErrorResponse;
import io.r2dbc.postgresql.message.backend.Field;
import io.r2dbc.postgresql.message.backend.NoticeResponse;
import io.r2dbc.postgresql.message.backend.NotificationResponse;
import io.r2dbc.postgresql.message.backend.ParameterStatus;
import io.r2dbc.postgresql.message.backend.ReadyForQuery;
import io.r2dbc.postgresql.message.frontend.FrontendMessage;
import io.r2dbc.postgresql.message.frontend.Terminate;
import io.r2dbc.postgresql.util.Assert;
import io.r2dbc.spi.R2dbcNonTransientResourceException;
import io.r2dbc.spi.R2dbcTransientResourceException;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Operators;
import reactor.core.publisher.Sinks;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.netty.Connection;
import reactor.netty.channel.AbortedException;
import reactor.netty.tcp.TcpClient;
import reactor.util.Logger;
import reactor.util.Loggers;
import reactor.util.annotation.Nullable;
import reactor.util.concurrent.Queues;
import reactor.util.context.Context;
import javax.net.ssl.SSLException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.StringJoiner;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static io.r2dbc.postgresql.client.TransactionStatus.IDLE;
/**
* An implementation of client based on the Reactor Netty project.
*
* @see TcpClient
*/
public final class ReactorNettyClient implements Client {
static final String CONNECTION_FAILURE = "08006";
private static final Logger logger = Loggers.getLogger(ReactorNettyClient.class);
private static final boolean DEBUG_ENABLED = logger.isDebugEnabled();
private static final Supplier<PostgresConnectionClosedException> UNEXPECTED = () -> new PostgresConnectionClosedException("Connection unexpectedly closed");
private static final Supplier<PostgresConnectionClosedException> EXPECTED = () -> new PostgresConnectionClosedException("Connection closed");
private final ByteBufAllocator byteBufAllocator;
private final ConnectionSettings settings;
private final Connection connection;
private final Scheduler scheduler;
private ConnectionContext context;
private final Sinks.Many<Publisher<FrontendMessage>> requestSink = Sinks.many().unicast().onBackpressureBuffer();
private final Sinks.Many<NotificationResponse> notificationProcessor = Sinks.many().multicast().directBestEffort();
private final AtomicBoolean isClosed = new AtomicBoolean(false);
private final BackendMessageSubscriber messageSubscriber = new BackendMessageSubscriber();
private volatile Integer processId;
private volatile Integer secretKey;
private volatile TimeZone timeZone;
private volatile TransactionStatus transactionStatus = IDLE;
private volatile Version version = new Version("", 0);
static {
// eagerly initialize the scheduler to avoid blocking calls due to TimeZoneDB retrieval
Schedulers.boundedElastic();
}
/**
* Create a new frame processor connected to a given TCP connection.
*
* @param connection the TCP connection
* @param settings the connection settings
* @throws IllegalArgumentException if {@code connection} is {@code null}
*/
private ReactorNettyClient(Connection connection, ConnectionSettings settings) {
Assert.requireNonNull(connection, "Connection must not be null");
this.settings = Assert.requireNonNull(settings, "ConnectionSettings must not be null");
connection.addHandlerLast(new EnsureSubscribersCompleteChannelHandler(this.requestSink));
connection.addHandlerLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE - 5, 1, 4, -4, 0));
this.connection = connection;
this.byteBufAllocator = connection.outbound().alloc();
ConnectionContext connectionContext = new ConnectionContext().withChannelId(connection.channel().toString());
SslHandler sslHandler = this.connection.channel().pipeline().get(SslHandler.class);
if (sslHandler == null) {
SSLSessionHandlerAdapter handlerAdapter = this.connection.channel().pipeline().get(SSLSessionHandlerAdapter.class);
if (handlerAdapter != null) {
sslHandler = handlerAdapter.getSslHandler();
}
}
if (sslHandler != null) {
SslHandler toUse = sslHandler;
connectionContext = connectionContext.withSslSession(() -> toUse.engine().getSession());
}
this.context = connectionContext;
EventLoop eventLoop = connection.channel().eventLoop();
this.scheduler = Schedulers.fromExecutorService(eventLoop, eventLoop.toString());
AtomicReference<Throwable> receiveError = new AtomicReference<>();
connection.inbound().receive()
.map(BackendMessageDecoder::decode)
.doOnError(receiveError::set)
.<BackendMessage>handle((backendMessage, sink) -> {
if (consumeMessage(backendMessage)) {
return;
}
sink.next(backendMessage);
})
.subscribe(this.messageSubscriber);
Mono<Void> request = this.requestSink.asFlux()
.concatMap(Function.identity())
.flatMap(message -> {
if (DEBUG_ENABLED) {
logger.debug(this.context.getMessage(String.format("Request: %s", message)));
}
return connection.outbound().send(message.encode(this.byteBufAllocator));
}, 1)
.then();
request
.onErrorResume(this::resumeError)
.doAfterTerminate(this::handleClose)
.subscribe();
}
@Override
public Mono<Void> close() {
return Mono.defer(() -> {
this.notificationProcessor.tryEmitComplete();
drainError(EXPECTED);
boolean connected = isConnected();
if (this.isClosed.compareAndSet(false, true)) {
if (!connected || this.processId == null) {
return closeConnection();
}
return Flux.just(Terminate.INSTANCE)
.doOnNext(message -> logger.debug(this.context.getMessage(String.format("Request: %s", message))))
.concatMap(message -> this.connection.outbound().send(message.encode(this.connection.outbound().alloc())))
.then()
.doOnSuccess(v -> this.connection.dispose())
.then(this.connection.onDispose());
}
return Mono.empty();
});
}
private Mono<? extends Void> closeConnection() {
this.connection.dispose();
return this.connection.onDispose();
}
@Override
public Flux<BackendMessage> exchange(Predicate<BackendMessage> takeUntil, Publisher<FrontendMessage> requests) {
Assert.requireNonNull(takeUntil, "takeUntil must not be null");
Assert.requireNonNull(requests, "requests must not be null");
if (!isConnected()) {
return Flux.error(this.messageSubscriber.createClientClosedException());
}
return this.messageSubscriber.addConversation(takeUntil, requests, this::doSendRequest, this::isConnected);
}
@Override
public void send(FrontendMessage message) {
Assert.requireNonNull(message, "requests must not be null");
doSendRequest(Mono.just(message));
}
private void doSendRequest(Publisher<FrontendMessage> it) {
this.requestSink.emitNext(it, Sinks.EmitFailureHandler.FAIL_FAST);
}
private Mono<Void> resumeError(Throwable throwable) {
handleConnectionError(throwable);
this.requestSink.emitComplete(Sinks.EmitFailureHandler.FAIL_FAST);
if (isSslException(throwable)) {
logger.debug(this.context.getMessage("Connection Error"), throwable);
} else {
logger.warn(this.context.getMessage("Connection Error"), throwable);
}
return close();
}
private static boolean isSslException(Throwable throwable) {
return throwable instanceof SSLException || throwable.getCause() instanceof SSLException;
}
/**
* Consume a {@link BackendMessage}. This method can either fully consume the message or it can signal by returning {@code false} that the method wasn't able to fully consume the message and
* that the message needs to be passed to an active {@link Conversation}.
*
* @param message the {@link BackendMessage} to handle
* @return {@code false} if the message could not be fully consumed and should be propagated to the active {@link Conversation}
*/
private boolean consumeMessage(BackendMessage message) {
if (DEBUG_ENABLED) {
logger.debug(this.context.getMessage(String.format("Response: %s", message)));
}
if (message.getClass() == NoticeResponse.class) {
this.settings.getNoticeLogLevel().log(logger, () -> this.context.getMessage(String.format("Notice: %s", toString(((NoticeResponse) message).getFields()))));
}
if (message.getClass() == BackendKeyData.class) {
BackendKeyData backendKeyData = (BackendKeyData) message;
this.processId = backendKeyData.getProcessId();
this.context = this.context.withProcessId(this.processId);
this.secretKey = backendKeyData.getSecretKey();
return true;
}
if (message.getClass() == ErrorResponse.class) {
this.settings.getErrorResponseLogLevel().log(logger, () -> String.format("Error: %s", toString(((ErrorResponse) message).getFields())));
}
if (message.getClass() == ParameterStatus.class) {
handleParameterStatus((ParameterStatus) message);
}
if (message.getClass() == ReadyForQuery.class) {
this.transactionStatus = TransactionStatus.valueOf(((ReadyForQuery) message).getTransactionStatus());
}
if (message.getClass() == NotificationResponse.class) {
this.notificationProcessor.tryEmitNext((NotificationResponse) message);
return true;
}
return false;
}
private void handleParameterStatus(ParameterStatus message) {
String name = message.getName();
if (name.equals("server_version_num") || name.equals("server_version")) {
Version existingVersion = this.version;
String versionString = existingVersion.getVersion();
int versionNum = existingVersion.getVersionNumber();
if (name.equals("server_version_num")) {
versionNum = Integer.parseInt(message.getValue());
}
if (name.equals("server_version")) {
versionString = message.getValue();
if (versionNum == 0) {
versionNum = Version.parseServerVersionStr(versionString);
}
}
this.version = new Version(versionString, versionNum);
}
if (name.equals("TimeZone")) {
this.timeZone = TimeZoneUtils.parseBackendTimeZone(message.getValue());
}
}
/**
* Create a new frame processor connected to a given host.
*
* @param host the host to connect to
* @param port the port to connect to
* @throws IllegalArgumentException if {@code host} is {@code null}
*/
public static Mono<ReactorNettyClient> connect(String host, int port) {
Assert.requireNonNull(host, "host must not be null");
return connect(host, port, null, new SSLConfig(SSLMode.DISABLE, null, null));
}
/**
* Create a new frame processor connected to a given host.
*
* @param host the host to connect to
* @param port the port to connect to
* @param connectTimeout connect timeout
* @param sslConfig SSL configuration
* @throws IllegalArgumentException if {@code host} is {@code null}
* @throws IllegalArgumentException if {@code sslConfig} is {@code null}
*/
public static Mono<ReactorNettyClient> connect(String host, int port, @Nullable Duration connectTimeout, SSLConfig sslConfig) {
Assert.requireNonNull(host, "host must not be null");
Assert.requireNonNull(sslConfig, "sslConfig must not be null");
ConnectionSettings.Builder builder = ConnectionSettings.builder().connectTimeout(connectTimeout).sslConfig(sslConfig);
return connect(InetSocketAddress.createUnresolved(host, port), builder.build());
}
/**
* Create a new frame processor connected to a given {@link SocketAddress}.
*
* @param socketAddress the socketAddress to connect to
* @param settings the connection settings
* @throws IllegalArgumentException if {@code socketAddress} or {@code settings} is {@code null}
*/
public static Mono<ReactorNettyClient> connect(SocketAddress socketAddress, ConnectionSettings settings) {
Assert.requireNonNull(socketAddress, "socketAddress must not be null");
Assert.requireNonNull(settings, "settings must not be null");
TcpClient tcpClient = TcpClient.create(settings.getConnectionProvider()).remoteAddress(() -> socketAddress);
if (settings.hasLoopResources()) {
tcpClient = tcpClient.runOn(settings.getRequiredLoopResources());
}
if (socketAddress instanceof InetSocketAddress) {
tcpClient = tcpClient.resolver(BalancedResolverGroup.INSTANCE);
tcpClient = tcpClient.option(ChannelOption.SO_KEEPALIVE, settings.isTcpKeepAlive());
tcpClient = tcpClient.option(ChannelOption.TCP_NODELAY, settings.isTcpNoDelay());
}
if (settings.hasConnectionTimeout()) {
tcpClient = tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, settings.getConnectTimeoutMs());
}
return tcpClient.doOnChannelInit((observer, channel, remoteAddress) -> {
ChannelPipeline pipeline = channel.pipeline();
InternalLogger logger = InternalLoggerFactory.getInstance(ReactorNettyClient.class);
if (logger.isTraceEnabled()) {
pipeline.addFirst(LoggingHandler.class.getSimpleName(),
new LoggingHandler(ReactorNettyClient.class, LogLevel.TRACE));
}
registerSslHandler(socketAddress, settings.getSslConfig(), channel);
}).connect().flatMap(it ->
getSslHandshake(it.channel()).thenReturn(new ReactorNettyClient(it, settings))
);
}
private static void registerSslHandler(SocketAddress socketAddress, SSLConfig sslConfig, Channel channel) {
try {
if (sslConfig.getSslMode().startSsl()) {
AbstractPostgresSSLHandlerAdapter sslAdapter;
if (sslConfig.getSslMode() == SSLMode.TUNNEL) {
sslAdapter = new SSLTunnelHandlerAdapter(channel.alloc(), socketAddress, sslConfig);
} else {
sslAdapter = new SSLSessionHandlerAdapter(channel.alloc(), socketAddress, sslConfig);
}
channel.pipeline().addFirst(sslAdapter);
}
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
private static Mono<Void> getSslHandshake(Channel channel) {
AbstractPostgresSSLHandlerAdapter sslAdapter = channel.pipeline().get(AbstractPostgresSSLHandlerAdapter.class);
return (sslAdapter != null) ? sslAdapter.getHandshake() : Mono.empty();
}
@Override
public Disposable addNotificationListener(Consumer<NotificationResponse> consumer) {
return this.notificationProcessor.asFlux().subscribe(consumer);
}
@Override
public void addNotificationListener(Subscriber<NotificationResponse> consumer) {
this.notificationProcessor.asFlux().subscribe(consumer);
}
@Override
public ByteBufAllocator getByteBufAllocator() {
return this.byteBufAllocator;
}
@Override
public ConnectionContext getContext() {
return this.context;
}
@Override
public Optional<Integer> getProcessId() {
return Optional.ofNullable(this.processId);
}
@Override
public Scheduler getScheduler() {
return this.scheduler;
}
@Override
public Optional<Integer> getSecretKey() {
return Optional.ofNullable(this.secretKey);
}
@Override
public Optional<TimeZone> getTimeZone() {
return Optional.ofNullable(this.timeZone);
}
@Override
public TransactionStatus getTransactionStatus() {
return this.transactionStatus;
}
@Override
public Version getVersion() {
return this.version;
}
@Override
public boolean isConnected() {
if (this.isClosed.get()) {
return false;
}
Channel channel = this.connection.channel();
return channel.isOpen();
}
@Override
public Mono<Void> cancelRequest() {
return Mono.defer(() -> {
int processId = this.getProcessId().orElseThrow(() -> new IllegalStateException("Connection does not yet have a processId"));
int secretKey = this.getSecretKey().orElseThrow(() -> new IllegalStateException("Connection does not yet have a secretKey"));
return ReactorNettyClient.connect(this.connection.channel().remoteAddress(), this.settings)
.flatMap(client -> CancelRequestMessageFlow.exchange(client, processId, secretKey).then(Mono.defer(client::closeConnection))
.onErrorResume(PostgresConnectionClosedException.class::isInstance, e -> Mono.empty()));
});
}
private static String toString(List<Field> fields) {
StringJoiner joiner = new StringJoiner(", ");
for (Field field : fields) {
joiner.add(field.getType().name() + "=" + field.getValue());
}
return joiner.toString();
}
private void handleClose() {
if (this.isClosed.compareAndSet(false, true)) {
drainError(UNEXPECTED);
} else {
drainError(EXPECTED);
}
}
private void handleConnectionError(Throwable error) {
if (AbortedException.isConnectionReset(error) && !isConnected()) {
drainError(() -> this.messageSubscriber.createClientClosedException(error));
}
drainError(() -> new PostgresConnectionException(error));
}
private void drainError(Supplier<? extends Throwable> supplier) {
this.messageSubscriber.close(supplier);
this.notificationProcessor.tryEmitError(supplier.get());
}
private final class EnsureSubscribersCompleteChannelHandler extends ChannelDuplexHandler {
private final Sinks.Many<?> requestSink;
private EnsureSubscribersCompleteChannelHandler(Sinks.Many<?> requestSink) {
this.requestSink = requestSink;
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
super.channelUnregistered(ctx);
this.requestSink.emitComplete(Sinks.EmitFailureHandler.FAIL_FAST);
handleClose();
}
}
static class PostgresConnectionClosedException extends R2dbcNonTransientResourceException implements PostgresqlException {
private final ErrorDetails errorDetails;
public PostgresConnectionClosedException(String reason) {
super(reason, CONNECTION_FAILURE, 0, (String) null);
this.errorDetails = ErrorDetails.fromCodeAndMessage(CONNECTION_FAILURE, reason);
}
public PostgresConnectionClosedException(String reason, @Nullable Throwable cause) {
super(reason, CONNECTION_FAILURE, 0, null, cause);
this.errorDetails = ErrorDetails.fromCodeAndMessage(CONNECTION_FAILURE, reason);
}
@Override
public ErrorDetails getErrorDetails() {
return this.errorDetails;
}
}
static class PostgresConnectionException extends R2dbcNonTransientResourceException implements PostgresqlException {
private final static ErrorDetails ERROR_DETAILS = ErrorDetails.fromCodeAndMessage(CONNECTION_FAILURE, "An I/O error occurred while sending to the backend or receiving from the backend");
public PostgresConnectionException(Throwable cause) {
super(ERROR_DETAILS.getMessage(), ERROR_DETAILS.getCode(), 0, null, cause);
}
@Override
public ErrorDetails getErrorDetails() {
return ERROR_DETAILS;
}
}
static class RequestQueueException extends R2dbcTransientResourceException implements PostgresqlException {
private final ErrorDetails errorDetails;
public RequestQueueException(String message) {
super(message, CONNECTION_FAILURE, 0, (String) null);
this.errorDetails = ErrorDetails.fromCodeAndMessage(CONNECTION_FAILURE, message);
}
@Override
public ErrorDetails getErrorDetails() {
return this.errorDetails;
}
}
static class ResponseQueueException extends R2dbcNonTransientResourceException implements PostgresqlException {
private final ErrorDetails errorDetails;
public ResponseQueueException(String message) {
super(message, CONNECTION_FAILURE, 0, (String) null);
this.errorDetails = ErrorDetails.fromCodeAndMessage(CONNECTION_FAILURE, message);
}
@Override
public ErrorDetails getErrorDetails() {
return this.errorDetails;
}
}
/**
* Value object representing a single conversation. The driver permits a single conversation at a time to ensure that request messages get routed to the proper response receiver and do not leak
* into other conversations. A conversation must be finished in the sense that the {@link Publisher} of {@link FrontendMessage} has completed before the next conversation is started.
* <p>
* A single conversation can make use of pipelining.
*/
private static class Conversation {
private static final AtomicLongFieldUpdater<Conversation> DEMAND_UPDATER = AtomicLongFieldUpdater.newUpdater(Conversation.class, "demand");
private final Predicate<BackendMessage> takeUntil;
private final FluxSink<BackendMessage> sink;
// access via DEMAND_UPDATER
private volatile long demand;
private Conversation(Predicate<BackendMessage> takeUntil, FluxSink<BackendMessage> sink) {
this.sink = sink;
this.takeUntil = takeUntil;
}
private void decrementDemand() {
Operators.addCap(DEMAND_UPDATER, this, -1);
}
/**
* Check whether the {@link BackendMessage} can complete the conversation.
*
* @param item the message to test whether it can complete the current conversation
* @return whether the {@link BackendMessage} can complete the current conversation
*/
public boolean canComplete(BackendMessage item) {
return this.takeUntil.test(item);
}
/**
* Complete the conversation.
*
* @param item the message completing the conversation
*/
public void complete(BackendMessage item) {
ReferenceCountUtil.release(item);
if (!this.sink.isCancelled()) {
this.sink.complete();
}
}
/**
* Emit a {@link BackendMessage}.
*
* @param item the item to emit
*/
public void emit(BackendMessage item) {
if (this.sink.isCancelled()) {
ReferenceCountUtil.release(item);
}
decrementDemand();
this.sink.next(item);
}
/**
* Notify the conversation about an error. Drops errors silently if the conversation is finished.
*
* @param throwable the error signal
*/
public void onError(Throwable throwable) {
if (!this.sink.isCancelled()) {
this.sink.error(throwable);
}
}
public boolean hasDemand() {
return DEMAND_UPDATER.get(this) > 0;
}
public boolean isCancelled() {
return this.sink.isCancelled();
}
public void incrementDemand(long n) {
Operators.addCap(DEMAND_UPDATER, this, n);
}
}
/**
* Subscriber that handles {@link Conversation}s and keeps track of the current demand. It also routes {@link BackendMessage}s to the currently active {@link Conversation}.
*/
private class BackendMessageSubscriber implements CoreSubscriber<BackendMessage> {
private static final int DEMAND = 256;
private final Queue<Conversation> conversations = Queues.<Conversation>small().get();
private final Queue<BackendMessage> buffer = Queues.<BackendMessage>get(DEMAND).get();
private final AtomicLong demand = new AtomicLong(0);
private final AtomicBoolean drain = new AtomicBoolean();
private volatile boolean terminated;
private Subscription upstream;
public Flux<BackendMessage> addConversation(Predicate<BackendMessage> takeUntil, Publisher<FrontendMessage> requests, Consumer<Publisher<FrontendMessage>> sender,
Supplier<Boolean> isConnected) {
return Flux.create(sink -> {
Conversation conversation = new Conversation(takeUntil, sink);
// ensure ordering in which conversations are added to both queues.
synchronized (this.conversations) {
if (this.conversations.offer(conversation)) {
sink.onRequest(value -> onRequest(conversation, value));
if (!isConnected.get()) {
sink.error(createClientClosedException());
return;
}
sender.accept(requests);
} else {
sink.error(new RequestQueueException("Cannot exchange messages because the request queue limit is exceeded"));
}
}
});
}
PostgresConnectionClosedException createClientClosedException() {
return createClientClosedException(null);
}
PostgresConnectionClosedException createClientClosedException(@Nullable Throwable cause) {
return new PostgresConnectionClosedException("Cannot exchange messages because the connection is closed", cause);
}
/**
* {@link Subscription#request(long)} callback. Request more for a {@link Conversation}. Potentially, demands also more upstream elements.
*
* @param conversation the conversation subject
* @param n number of requested elements
*/
public void onRequest(Conversation conversation, long n) {
conversation.incrementDemand(n);
demandMore();
tryDrainLoop();
}
/**
* {@link Subscriber#onSubscribe(Subscription)} callback. Registers the {@link Subscription} and potentially requests more upstream elements.
*
* @param s the subscription
*/
@Override
public void onSubscribe(Subscription s) {
this.upstream = s;
demandMore();
}
/**
* {@link Subscriber#onNext(Object)} callback. Decrements upstream demand and attempts to emit {@link BackendMessage} to an active {@link Conversation}. If a conversation has no demand, it
* will be buffered.
*
* @param message the message to emit
*/
@Override
public void onNext(BackendMessage message) {
if (this.terminated) {
ReferenceCountUtil.release(message);
Operators.onNextDropped(message, currentContext());
return;
}
this.demand.decrementAndGet();
// fast-path
if (this.buffer.isEmpty()) {
Conversation conversation = this.conversations.peek();
if (conversation != null && conversation.hasDemand()) {
emit(conversation, message);
potentiallyDemandMore(conversation);
return;
}
}
// slow-path
if (!this.buffer.offer(message)) {
ReferenceCountUtil.release(message);
Operators.onNextDropped(message, currentContext());
onError(new ResponseQueueException("Response queue is full"));
return;
}
tryDrainLoop();
}
/**
* {@link Subscriber#onError(Throwable)} callback.
*
* @param throwable the error to emit
*/
@Override
public void onError(Throwable throwable) {
if (this.terminated) {
Operators.onErrorDropped(throwable, currentContext());
return;
}
handleConnectionError(throwable);
ReactorNettyClient.this.requestSink.emitComplete(Sinks.EmitFailureHandler.FAIL_FAST);
this.terminated = true;
if (isSslException(throwable)) {
logger.debug(ReactorNettyClient.this.context.getMessage("Connection Error"), throwable);
} else {
logger.error(ReactorNettyClient.this.context.getMessage("Connection Error"), throwable);
}
ReactorNettyClient.this.close().subscribe();
}
/**
* {@link Subscriber#onComplete()} callback.
*/
@Override
public void onComplete() {
this.terminated = true;
ReactorNettyClient.this.handleClose();
}
/**
* Context propagation from an active {@link Conversation}.
*/
@Override
public Context currentContext() {
Conversation receiver = this.conversations.peek();
return receiver != null ? Context.of(receiver.sink.contextView()) : Context.empty();
}
private void tryDrainLoop() {
while (hasBufferedItems() && hasDownstreamDemand()) {
if (!drainLoop()) {
return;
}
}
}
/**
* Drains the buffer. Guarded for single-thread access.
*
* @return {@code true} if the drain loop was entered successfully. {@code false} otherwise (i.e. a different thread already works on the drain loop).
*/
private boolean drainLoop() {
if (!this.drain.compareAndSet(false, true)) {
return false;
}
Conversation lastConversation = null;
try {
while (hasBufferedItems()) {
Conversation conversation = this.conversations.peek();
lastConversation = conversation;
if (conversation == null) {
break;
}
if (conversation.hasDemand()) {
BackendMessage item = this.buffer.poll();
if (item == null) {
break;
}
emit(conversation, item);
} else {
break;
}
}
} finally {
this.drain.compareAndSet(true, false);
}
potentiallyDemandMore(lastConversation);
return true;
}
private void potentiallyDemandMore(@Nullable Conversation lastConversation) {
if (lastConversation == null || lastConversation.hasDemand() || lastConversation.isCancelled()) {
demandMore();
}
}
private void emit(Conversation conversation, BackendMessage item) {
if (conversation.canComplete(item)) {
this.conversations.poll();
conversation.complete(item);
} else {
conversation.emit(item);
}
}
private void demandMore() {
if (!hasBufferedItems() && this.demand.compareAndSet(0, DEMAND)) {
this.upstream.request(DEMAND);
}
}
private boolean hasDownstreamDemand() {
Conversation conversation = this.conversations.peek();
return conversation != null && conversation.hasDemand();
}
private boolean hasBufferedItems() {
return !this.buffer.isEmpty();
}
/**
* Cleanup the subscriber by terminating all {@link Conversation}s and purging the data buffer. All conversations are completed with an error signal provided by {@code supplier}.
*
* @param supplier the error supplier
*/
public void close(Supplier<? extends Throwable> supplier) {
this.terminated = true;
Conversation receiver;
while ((receiver = this.conversations.poll()) != null) {
receiver.onError(supplier.get());
}
while (!this.buffer.isEmpty()) {