-
Notifications
You must be signed in to change notification settings - Fork 629
/
DefaultPooledConnectionProvider.java
571 lines (493 loc) · 17.4 KB
/
DefaultPooledConnectionProvider.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
/*
* Copyright (c) 2020-2022 VMware, Inc. or its affiliates, All Rights Reserved.
*
* 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 reactor.netty5.resources;
import java.io.IOException;
import java.net.SocketAddress;
import java.time.Clock;
import java.time.Duration;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiPredicate;
import java.util.function.Function;
import io.netty5.channel.Channel;
import io.netty5.channel.ChannelInitializer;
import io.netty5.channel.EventLoop;
import io.netty5.resolver.AddressResolverGroup;
import io.netty5.util.AttributeKey;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.Disposable;
import reactor.core.Disposables;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoSink;
import reactor.core.publisher.Operators;
import reactor.core.publisher.Sinks;
import reactor.netty5.Connection;
import reactor.netty5.ConnectionObserver;
import reactor.netty5.NettyPipeline;
import reactor.netty5.channel.ChannelOperations;
import reactor.netty5.transport.TransportConfig;
import reactor.netty5.transport.TransportConnector;
import reactor.pool.InstrumentedPool;
import reactor.pool.PooledRef;
import reactor.pool.PooledRefMetadata;
import reactor.util.Logger;
import reactor.util.Loggers;
import reactor.util.annotation.Nullable;
import reactor.util.concurrent.Queues;
import reactor.util.context.Context;
import static reactor.netty5.ReactorNetty.format;
/**
* A default implementation for pooled {@link ConnectionProvider}.
*
* @author Stephane Maldini
* @author Violeta Georgieva
*/
final class DefaultPooledConnectionProvider extends PooledConnectionProvider<DefaultPooledConnectionProvider.PooledConnection> {
DefaultPooledConnectionProvider(Builder builder) {
this(builder, null);
}
// Used only for testing purposes
DefaultPooledConnectionProvider(Builder builder, @Nullable Clock clock) {
super(builder, clock);
}
@Override
protected CoreSubscriber<PooledRef<PooledConnection>> createDisposableAcquire(
TransportConfig config,
ConnectionObserver connectionObserver,
long pendingAcquireTimeout,
InstrumentedPool<PooledConnection> pool,
MonoSink<Connection> sink,
Context currentContext) {
return new DisposableAcquire(connectionObserver, config.channelOperationsProvider(),
pendingAcquireTimeout, pool, sink, currentContext);
}
@Override
protected InstrumentedPool<PooledConnection> createPool(
TransportConfig config,
PoolFactory<PooledConnection> poolFactory,
SocketAddress remoteAddress,
AddressResolverGroup<?> resolverGroup) {
return new PooledConnectionAllocator(config, poolFactory, remoteAddress, resolverGroup).pool;
}
static final Logger log = Loggers.getLogger(DefaultPooledConnectionProvider.class);
static final AttributeKey<ConnectionObserver> OWNER = AttributeKey.valueOf("connectionOwner");
static final class DisposableAcquire
implements ConnectionObserver, Runnable, CoreSubscriber<PooledRef<PooledConnection>>, Disposable {
final Disposable.Composite cancellations;
final Context currentContext;
final ConnectionObserver obs;
final ChannelOperations.OnSetup opsFactory;
final long pendingAcquireTimeout;
final InstrumentedPool<PooledConnection> pool;
final boolean retried;
final MonoSink<Connection> sink;
PooledRef<PooledConnection> pooledRef;
Subscription subscription;
DisposableAcquire(
ConnectionObserver obs,
ChannelOperations.OnSetup opsFactory,
long pendingAcquireTimeout,
InstrumentedPool<PooledConnection> pool,
MonoSink<Connection> sink,
Context currentContext) {
this.cancellations = Disposables.composite();
this.currentContext = currentContext;
this.obs = obs;
this.opsFactory = opsFactory;
this.pendingAcquireTimeout = pendingAcquireTimeout;
this.pool = pool;
this.retried = false;
this.sink = sink;
}
DisposableAcquire(DisposableAcquire parent) {
this.cancellations = parent.cancellations;
this.currentContext = parent.currentContext;
this.obs = parent.obs;
this.opsFactory = parent.opsFactory;
this.pendingAcquireTimeout = parent.pendingAcquireTimeout;
this.pool = parent.pool;
this.retried = true;
this.sink = parent.sink;
}
@Override
public Context currentContext() {
return currentContext;
}
@Override
public void dispose() {
subscription.cancel();
}
@Override
public void onComplete() {
// noop
}
@Override
public void onError(Throwable throwable) {
sink.error(throwable);
}
@Override
public void onNext(PooledRef<PooledConnection> value) {
pooledRef = value;
PooledConnection pooledConnection = value.poolable();
pooledConnection.pooledRef = pooledRef;
Channel c = pooledConnection.channel;
if (c.executor().inEventLoop()) {
run();
}
else {
c.executor().execute(this);
}
}
@Override
public void onStateChange(Connection connection, State newState) {
if (newState == State.CONFIGURED) {
// First send a notification that the connection is ready and then change the state
// In case a cancellation was received, ChannelOperations will be disposed
// and there will be no subscription to the I/O handler at all.
// https://github.com/reactor/reactor-netty/issues/1165
sink.success(connection);
}
obs.onStateChange(connection, newState);
}
@Override
public void onSubscribe(Subscription s) {
if (Operators.validate(subscription, s)) {
this.subscription = s;
cancellations.add(this);
if (!retried) {
sink.onCancel(cancellations);
}
s.request(Long.MAX_VALUE);
}
}
@Override
public void onUncaughtException(Connection connection, Throwable error) {
sink.error(error);
obs.onUncaughtException(connection, error);
}
@Override
public void run() {
PooledConnection pooledConnection = pooledRef.poolable();
Channel c = pooledConnection.channel;
// The connection might be closed after checking the eviction predicate
if (!c.isActive()) {
pooledRef.invalidate()
.subscribe(null, null, () -> {
if (log.isDebugEnabled()) {
logPoolState(c, pool, "Channel closed");
}
});
if (!retried) {
if (log.isDebugEnabled()) {
log.debug(format(c, "Immediately aborted pooled channel, re-acquiring new channel"));
}
pool.acquire(Duration.ofMillis(pendingAcquireTimeout))
.contextWrite(ctx -> ctx.put(CONTEXT_CALLER_EVENTLOOP, c.executor()))
.subscribe(new DisposableAcquire(this));
}
else {
sink.error(new IOException("Error while acquiring from " + pool));
}
return;
}
// Set the owner only if the channel is active
ConnectionObserver current = c.attr(OWNER)
.getAndSet(this);
if (current instanceof PendingConnectionObserver pending) {
PendingConnectionObserver.Pending p;
current = null;
registerClose(pooledRef, pool);
while ((p = pending.pendingQueue.poll()) != null) {
if (p.error != null) {
onUncaughtException(p.connection, p.error);
}
else if (p.state != null) {
onStateChange(p.connection, p.state);
}
}
}
else if (current == null) {
registerClose(pooledRef, pool);
}
if (current != null) {
if (log.isDebugEnabled()) {
logPoolState(c, pool, "Channel acquired");
}
obs.onStateChange(pooledConnection, State.ACQUIRED);
ChannelOperations<?, ?> ops = opsFactory.create(pooledConnection, pooledConnection, null);
if (ops != null) {
if (c.pipeline().get(NettyPipeline.H2MultiplexHandler) == null) {
ops.bind();
// First send a notification that the connection is ready and then change the state
// In case a cancellation was received, ChannelOperations will be disposed
// and there will be no subscription to the I/O handler at all.
// https://github.com/reactor/reactor-netty/issues/1165
sink.success(ops);
obs.onStateChange(ops, State.CONFIGURED);
}
else {
// First send a notification that the connection is ready and then change the state
// In case a cancellation was received, ChannelOperations will be disposed
// and there will be no subscription to the I/O handler at all.
// https://github.com/reactor/reactor-netty/issues/1165
sink.success(ops);
obs.onStateChange(pooledConnection, State.CONFIGURED);
}
}
else {
// Already configured, just forward the connection
sink.success(pooledConnection);
}
return;
}
// Connected, leave onStateChange forward the event if factory
if (log.isDebugEnabled()) {
logPoolState(c, pool, "Channel connected");
}
if (opsFactory == ChannelOperations.OnSetup.empty()) {
sink.success(Connection.from(c));
}
}
void registerClose(PooledRef<PooledConnection> pooledRef, InstrumentedPool<PooledConnection> pool) {
Channel channel = pooledRef.poolable().channel;
if (log.isDebugEnabled()) {
log.debug(format(channel, "Registering pool release on close event for channel"));
}
channel.closeFuture()
.addListener(ff -> {
// When the connection is released the owner is NOOP
ConnectionObserver owner = channel.attr(OWNER).get();
if (owner instanceof DisposableAcquire disposableAcquire) {
disposableAcquire.pooledRef
.invalidate()
.subscribe(null, null, () -> {
if (log.isDebugEnabled()) {
logPoolState(channel, pool, "Channel closed");
}
});
}
});
}
}
static final class PendingConnectionObserver implements ConnectionObserver {
final Queue<Pending> pendingQueue = Queues.<Pending>unbounded(4).get();
final Context context;
public PendingConnectionObserver() {
this(Context.empty());
}
public PendingConnectionObserver(final Context context) {
this.context = context;
}
@Override
public void onStateChange(Connection connection, State newState) {
pendingQueue.add(new Pending(connection, null, newState));
}
@Override
public void onUncaughtException(Connection connection, Throwable error) {
pendingQueue.add(new Pending(connection, error, null));
}
@Override
public Context currentContext() {
return this.context;
}
static class Pending {
final Connection connection;
final Throwable error;
final State state;
Pending(Connection connection, @Nullable Throwable error, @Nullable State state) {
this.connection = connection;
this.error = error;
this.state = state;
}
}
}
static final class PooledConnection extends AtomicLong implements Connection, ConnectionObserver {
final Channel channel;
final Sinks.Empty<Void> onTerminate;
final InstrumentedPool<PooledConnection> pool;
PooledRef<PooledConnection> pooledRef;
PooledConnection(Channel channel, InstrumentedPool<PooledConnection> pool) {
this.channel = channel;
this.onTerminate = Sinks.unsafe().empty();
this.pool = pool;
}
@Override
public Channel channel() {
return channel;
}
@Override
public Context currentContext() {
return owner().currentContext();
}
@Override
public void onStateChange(Connection connection, State newState) {
if (log.isDebugEnabled()) {
log.debug(format(connection.channel(), "onStateChange({}, {})"), connection, newState);
}
if (newState == State.DISCONNECTING) {
if (!isPersistent() && channel.isActive()) {
// Will be released by closeFuture
channel.close();
owner().onStateChange(connection, State.DISCONNECTING);
return;
}
if (!channel.isActive()) {
owner().onStateChange(connection, State.DISCONNECTING);
// Will be released by closeFuture
return;
}
if (log.isDebugEnabled()) {
log.debug(format(connection.channel(), "Releasing channel"));
}
ConnectionObserver obs = channel.attr(OWNER)
.getAndSet(ConnectionObserver.emptyListener());
if (pooledRef == null) {
return;
}
pooledRef.release()
.subscribe(
null,
t -> {
if (log.isDebugEnabled()) {
logPoolState(pooledRef.poolable().channel, pool,
"Failed cleaning the channel from pool", t);
}
// EmitResult is ignored as it is guaranteed that this call happens in an event loop,
// and it is guarded by release(), so tryEmitEmpty() should happen just once
onTerminate.tryEmitEmpty();
obs.onStateChange(connection, State.RELEASED);
},
() -> {
if (log.isDebugEnabled()) {
logPoolState(pooledRef.poolable().channel, pool, "Channel cleaned");
}
// EmitResult is ignored as it is guaranteed that this call happens in an event loop,
// and it is guarded by release(), so tryEmitEmpty() should happen just once
onTerminate.tryEmitEmpty();
obs.onStateChange(connection, State.RELEASED);
});
return;
}
owner().onStateChange(connection, newState);
}
@Override
public Mono<Void> onTerminate() {
return onTerminate.asMono().or(onDispose());
}
@Override
public void onUncaughtException(Connection connection, Throwable error) {
owner().onUncaughtException(connection, error);
}
@Override
public String toString() {
return "PooledConnection{" + "channel=" + channel + '}';
}
ConnectionObserver owner() {
ConnectionObserver obs;
for (;;) {
obs = channel.attr(OWNER)
.get();
if (obs == null) {
obs = new PendingConnectionObserver();
}
else {
return obs;
}
if (channel.attr(OWNER)
.compareAndSet(null, obs)) {
return obs;
}
}
}
}
static final class PooledConnectionAllocator {
final TransportConfig config;
final InstrumentedPool<PooledConnection> pool;
final SocketAddress remoteAddress;
final AddressResolverGroup<?> resolver;
PooledConnectionAllocator(
TransportConfig config,
PoolFactory<PooledConnection> provider,
SocketAddress remoteAddress,
AddressResolverGroup<?> resolver) {
this.config = config;
this.remoteAddress = remoteAddress;
this.resolver = resolver;
this.pool = provider.newPool(connectChannel(), null, DEFAULT_DESTROY_HANDLER, DEFAULT_EVICTION_PREDICATE);
}
Publisher<PooledConnection> connectChannel() {
return Mono.create(sink -> {
PooledConnectionInitializer initializer = new PooledConnectionInitializer(sink);
EventLoop callerEventLoop = sink.contextView().hasKey(CONTEXT_CALLER_EVENTLOOP) ?
sink.contextView().get(CONTEXT_CALLER_EVENTLOOP) : null;
if (callerEventLoop != null) {
TransportConnector.connect(config, remoteAddress, resolver, initializer, callerEventLoop, sink.contextView())
.subscribe(initializer);
}
else {
TransportConnector.connect(config, remoteAddress, resolver, initializer, sink.contextView()).subscribe(initializer);
}
});
}
final class PooledConnectionInitializer extends ChannelInitializer<Channel> implements CoreSubscriber<Channel> {
final MonoSink<PooledConnection> sink;
PooledConnection pooledConnection;
PooledConnectionInitializer(MonoSink<PooledConnection> sink) {
this.sink = sink;
}
@Override
protected void initChannel(Channel ch) {
if (log.isDebugEnabled()) {
logPoolState(ch, pool, "Created a new pooled channel");
}
PooledConnection pooledConnection = new PooledConnection(ch, pool);
this.pooledConnection = pooledConnection;
ch.attr(OWNER).compareAndSet(null, new PendingConnectionObserver(Context.of(sink.contextView())));
ch.pipeline().remove(this);
ch.pipeline()
.addFirst(config.channelInitializer(pooledConnection, remoteAddress, false));
pooledConnection.bind();
}
@Override
public void onComplete() {
// noop
}
@Override
public void onError(Throwable t) {
sink.error(t);
}
@Override
public void onNext(Channel channel) {
sink.success(pooledConnection);
}
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
}
}
static final BiPredicate<PooledConnection, PooledRefMetadata> DEFAULT_EVICTION_PREDICATE =
(pooledConnection, metadata) -> !pooledConnection.channel.isActive() || !pooledConnection.isPersistent();
static final Function<PooledConnection, Publisher<Void>> DEFAULT_DESTROY_HANDLER =
pooledConnection -> {
if (!pooledConnection.channel.isActive()) {
return Mono.empty();
}
return Mono.fromCompletionStage(pooledConnection.channel.close().asStage());
};
}
}