-
Notifications
You must be signed in to change notification settings - Fork 630
/
ChannelOperations.java
631 lines (557 loc) · 17.3 KB
/
ChannelOperations.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
/*
* Copyright (c) 2011-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.channel;
import java.net.SocketAddress;
import java.nio.channels.ClosedChannelException;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Predicate;
import io.netty5.buffer.Buffer;
import io.netty5.buffer.BufferAllocator;
import io.netty5.util.Resource;
import io.netty5.channel.Channel;
import io.netty5.channel.ChannelHandler;
import io.netty5.channel.ChannelHandlerContext;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Operators;
import reactor.core.publisher.Sinks;
import reactor.netty5.BufferFlux;
import reactor.netty5.ChannelOperationsId;
import reactor.netty5.Connection;
import reactor.netty5.ConnectionObserver;
import reactor.netty5.NettyInbound;
import reactor.netty5.NettyOutbound;
import reactor.netty5.NettyPipeline;
import reactor.netty5.ReactorNetty;
import reactor.util.Logger;
import reactor.util.Loggers;
import reactor.util.annotation.Nullable;
import reactor.util.context.Context;
import static java.util.Objects.requireNonNull;
import static reactor.netty5.ReactorNetty.format;
/**
* {@link NettyInbound} and {@link NettyOutbound} that apply to a {@link Connection}
*
* @author Stephane Maldini
* @since 0.6
*/
public class ChannelOperations<INBOUND extends NettyInbound, OUTBOUND extends NettyOutbound>
implements NettyInbound, NettyOutbound, Connection, CoreSubscriber<Void>, ChannelOperationsId {
/**
* Add {@link NettyPipeline#ReactiveBridge} handler at the end of {@link Channel}
* pipeline. The bridge will buffer outgoing write and pass along incoming read to
* the current {@link ChannelOperations#get(Channel)}.
*
* @param ch the channel to bridge
* @param opsFactory the operations factory to invoke on channel active
* @param listener the listener to forward connection events to
*/
public static void addReactiveBridge(Channel ch, OnSetup opsFactory, ConnectionObserver listener) {
requireNonNull(ch, "channel");
requireNonNull(opsFactory, "opsFactory");
requireNonNull(listener, "listener");
ch.pipeline()
.addLast(NettyPipeline.ReactiveBridge, new ChannelOperationsHandler(opsFactory, listener));
}
/**
* Add {@link NettyPipeline#ChannelMetricsHandler} to the channel pipeline.
*
* @param ch the channel
* @param recorder the configured metrics recorder
* @param remoteAddress the remote address
* @param onServer true if {@link ChannelMetricsRecorder} is for the server, false if it is for the client
*/
public static void addMetricsHandler(Channel ch, ChannelMetricsRecorder recorder,
@Nullable SocketAddress remoteAddress, boolean onServer) {
requireNonNull(ch, "channel");
requireNonNull(recorder, "recorder");
SocketAddress remote = remoteAddress;
if (remote == null) {
remote = ch.remoteAddress();
}
ChannelHandler handler;
if (recorder instanceof MicrometerChannelMetricsRecorder micrometerChannelMetricsRecorder) {
handler = new MicrometerChannelMetricsHandler(micrometerChannelMetricsRecorder, remote, onServer);
}
else if (recorder instanceof ContextAwareChannelMetricsRecorder contextAwareChannelMetricsRecorder) {
handler = new ContextAwareChannelMetricsHandler(contextAwareChannelMetricsRecorder, remote, onServer);
}
else {
handler = new ChannelMetricsHandler(recorder, remote, onServer);
}
ch.pipeline()
.addFirst(NettyPipeline.ChannelMetricsHandler, handler);
}
/**
* Return the current {@link Channel} bound {@link ChannelOperations} or null if none
*
* @param ch the current {@link Channel}
*
* @return the current {@link Channel} bound {@link ChannelOperations} or null if none
*/
@Nullable
public static ChannelOperations<?, ?> get(Channel ch) {
return Connection.from(ch)
.as(ChannelOperations.class);
}
final Connection connection;
final FluxReceive inbound;
final ConnectionObserver listener;
final Sinks.Empty<Void> onTerminate;
final String shortId;
volatile Subscription outboundSubscription;
boolean localActive;
String longId;
protected ChannelOperations(ChannelOperations<INBOUND, OUTBOUND> replaced) {
this.connection = replaced.connection;
this.listener = replaced.listener;
this.onTerminate = replaced.onTerminate;
this.inbound = new FluxReceive(this);
this.shortId = replaced.shortId;
this.longId = replaced.longId;
this.localActive = replaced.localActive;
}
/**
* Create a new {@link ChannelOperations} attached to the {@link Channel}. Attach the {@link NettyPipeline#ReactiveBridge} handle.
*
* @param connection the new {@link Connection} connection
* @param listener the events callback
*/
public ChannelOperations(Connection connection, ConnectionObserver listener) {
this.connection = requireNonNull(connection, "connection");
this.listener = requireNonNull(listener, "listener");
this.onTerminate = Sinks.unsafe().empty();
this.inbound = new FluxReceive(this);
shortId = initShortId();
}
@Nullable
@Override
public <T extends Connection> T as(Class<T> clazz) {
if (clazz == ChannelOperations.class) {
@SuppressWarnings("unchecked")
T thiz = (T) this;
return thiz;
}
return Connection.super.as(clazz);
}
@Override
public BufferAllocator alloc() {
return connection.channel().bufferAllocator();
}
@Override
public NettyInbound inbound() {
return this;
}
@Override
public NettyOutbound outbound() {
return this;
}
@Override
public final Channel channel() {
return connection.channel();
}
@Override
public ChannelOperations<INBOUND, OUTBOUND> withConnection(Consumer<? super Connection> withConnection) {
requireNonNull(withConnection, "withConnection");
withConnection.accept(this);
return this;
}
@Override
public void dispose() {
if (log.isTraceEnabled()) {
log.trace(format(channel(), "Disposing ChannelOperation from a channel"),
new Exception("ChannelOperation dispose stack"));
}
OUTBOUND_CLOSE.set(this, Operators.cancelledSubscription());
if (!inbound.isDisposed()) {
discard();
}
connection.dispose();
}
@Override
public CoreSubscriber<Void> disposeSubscriber() {
return this;
}
@Override
public final boolean isDisposed() {
return !channel().isActive() || isSubscriptionDisposed();
}
/**
* Return true if dispose subscription has been terminated
*
* @return true if dispose subscription has been terminated
*/
public final boolean isSubscriptionDisposed() {
return OUTBOUND_CLOSE.get(this) == Operators.cancelledSubscription();
}
@Override
public final Mono<Void> onDispose() {
return connection.onDispose();
}
@Override
public Connection onDispose(final Disposable onDispose) {
connection.onDispose(onDispose);
return this;
}
@Override
public final void onComplete() {
if (isDisposed()) {
return;
}
OUTBOUND_CLOSE.set(this, Operators.cancelledSubscription());
onOutboundComplete();
}
@Override
public final void onError(Throwable t) {
if (isDisposed()) {
if (log.isDebugEnabled()) {
log.debug(format(channel(), "An outbound error could not be processed"), t);
}
return;
}
OUTBOUND_CLOSE.set(this, Operators.cancelledSubscription());
onOutboundError(t);
}
@Override
public final void onNext(Void aVoid) {
}
@Override
public final void onSubscribe(Subscription s) {
if (Operators.setOnce(OUTBOUND_CLOSE, this, s)) {
s.request(Long.MAX_VALUE);
}
}
@Override
public Flux<?> receiveObject() {
return inbound;
}
@Override
public BufferFlux receive() {
return BufferFlux.fromInbound(receiveObject(), alloc());
}
@Override
public NettyOutbound send(Publisher<? extends Buffer> dataStream, Predicate<Buffer> predicate) {
requireNonNull(predicate, "predicate");
if (!channel().isActive()) {
return then(Mono.error(AbortedException.beforeSend()));
}
if (dataStream instanceof Mono<?> mono) {
return then(mono.flatMap(m -> Mono.fromCompletionStage(channel().writeAndFlush(m).asStage()))
.doOnDiscard(Buffer.class, Buffer::close));
}
return then(MonoSendMany.bufferSource(dataStream, channel(), predicate));
}
@Override
public NettyOutbound sendObject(Publisher<?> dataStream, Predicate<Object> predicate) {
requireNonNull(predicate, "predicate");
if (!channel().isActive()) {
return then(Mono.error(AbortedException.beforeSend()));
}
if (dataStream instanceof Mono<?> mono) {
return then(mono.flatMap(m -> Mono.fromCompletionStage(channel().writeAndFlush(m).asStage()))
.doOnDiscard(Resource.class, Resource::dispose));
}
return then(MonoSendMany.objectSource(dataStream, channel(), predicate));
}
@Override
public NettyOutbound sendObject(Object message) {
if (!channel().isActive()) {
ReactorNetty.safeRelease(message);
return then(Mono.error(AbortedException.beforeSend()));
}
return then(Mono.fromCompletionStage(() -> connection.channel()
.writeAndFlush(message).asStage()),
() -> ReactorNetty.safeRelease(message));
}
@Override
public <S> NettyOutbound sendUsing(Callable<? extends S> sourceInput,
BiFunction<? super Connection, ? super S, ?> mappedInput,
Consumer<? super S> sourceCleanup) {
requireNonNull(sourceInput, "sourceInput");
requireNonNull(mappedInput, "mappedInput");
requireNonNull(sourceCleanup, "sourceCleanup");
return then(Mono.using(
sourceInput,
s -> Mono.fromCompletionStage(connection.channel()
.writeAndFlush(mappedInput.apply(this, s)).asStage()),
sourceCleanup)
);
}
/**
* Return a Mono succeeding when a {@link ChannelOperations} has been terminated
*
* @return a Mono succeeding when a {@link ChannelOperations} has been terminated
*/
@Override
public final Mono<Void> onTerminate() {
if (!isPersistent()) {
return connection.onDispose();
}
return onTerminate.asMono().or(connection.onDispose());
}
/**
* Return the available parent {@link ConnectionObserver} for user-facing lifecycle
* handling
*
* @return the available parent {@link ConnectionObserver}for user-facing lifecycle
* handling
*/
public final ConnectionObserver listener() {
return listener;
}
@Override
public String toString() {
return "ChannelOperations{" + connection.toString() + "}";
}
/**
* Drop pending content and complete inbound.
* Always discard content regardless whether there is a receiver.
*/
public final void discard() {
inbound.cancel();
}
/**
* Drop pending content and complete inbound.
* Discard content only in case there is no receiver.
*/
protected final void discardWhenNoReceiver() {
if (inbound.receiver == null) {
discard();
}
}
/**
* Return true if inbound traffic is not expected anymore
*
* @return true if inbound traffic is not expected anymore
*/
public final boolean isInboundCancelled() {
return inbound.isCancelled();
}
/**
* Return true if inbound traffic is not incoming or expected anymore
*
* @return true if inbound traffic is not incoming or expected anymore
*/
public final boolean isInboundDisposed() {
return inbound.isDisposed();
}
/**
* React on inbound {@link Channel#read}
*
* @param ctx the context
* @param msg the read payload
*/
protected void onInboundNext(ChannelHandlerContext ctx, Object msg) {
inbound.onInboundNext(msg);
}
/**
* React on inbound cancel (receive() subscriber cancelled)
*/
protected void onInboundCancel() {
}
/**
* React on inbound completion (last packet)
*/
protected void onInboundComplete() {
inbound.onInboundComplete();
}
/**
* React after inbound completion (last packet)
*/
protected void afterInboundComplete() {
// noop
}
/**
* React on inbound close (channel closed prematurely)
*/
protected void onInboundClose() {
discardWhenNoReceiver();
terminate();
}
/**
* React on inbound/outbound completion (last packet)
*/
protected void onOutboundComplete() {
if (log.isDebugEnabled()) {
log.debug(format(channel(), "[{}] User Handler requesting close connection"), formatName());
}
markPersistent(false);
terminate();
}
/**
* React on inbound/outbound error
*
* @param err the {@link Throwable} cause
*/
protected void onOutboundError(Throwable err) {
markPersistent(false);
terminate();
}
/**
* Final release/close (last packet)
*/
protected final void terminate() {
if (rebind(connection)) {
if (log.isTraceEnabled()) {
log.trace(format(channel(), "Disposing ChannelOperation from a channel"),
new Exception("ChannelOperation terminal stack"));
}
Operators.terminate(OUTBOUND_CLOSE, this);
// Do not call directly inbound.onInboundComplete()
// HttpClientOperations need to notify with error
// when there is no response state
onInboundComplete();
afterInboundComplete();
// EmitResult is ignored as it is guaranteed that this call happens in an event loop,
// and it is guarded by rebind(connection), so tryEmitEmpty() should happen just once
onTerminate.tryEmitEmpty();
listener.onStateChange(this, ConnectionObserver.State.DISCONNECTING);
}
}
/**
* React on inbound error
*
* @param err the {@link Throwable} cause
*/
protected final void onInboundError(Throwable err) {
inbound.onInboundError(err);
}
/**
* Return the delegate IO {@link Connection} for low-level IO access
*
* @return the delegate IO {@link Connection} for low-level IO access
*/
protected final Connection connection() {
return connection;
}
/**
* Return formatted name of this operation
*
* @return formatted name of this operation
*/
protected final String formatName() {
return getClass().getSimpleName()
.replace("Operations", "");
}
protected String initShortId() {
return channel().id().asShortText();
}
/**
* Wrap an inbound error
*
* @param err the {@link Throwable} cause
*/
protected Throwable wrapInboundError(Throwable err) {
if (err instanceof ClosedChannelException) {
return new AbortedException(err);
}
else if (err instanceof OutOfMemoryError) {
return ReactorNetty.wrapException(err);
}
else {
return err;
}
}
@Override
public boolean isPersistent() {
return connection.isPersistent();
}
@Override
public Context currentContext() {
return listener.currentContext();
}
@Override
public String asShortText() {
return shortId;
}
@Override
public String asLongText() {
boolean active = channel().isActive();
if (localActive == active && longId != null) {
return longId;
}
SocketAddress remoteAddress = channel().remoteAddress();
SocketAddress localAddress = channel().localAddress();
String shortText = asShortText();
if (remoteAddress != null) {
String localAddressStr = String.valueOf(localAddress);
String remoteAddressStr = String.valueOf(remoteAddress);
StringBuilder buf =
new StringBuilder(shortText.length() + 4 + localAddressStr.length() + 3 + 2 + remoteAddressStr.length())
.append(shortText)
.append(", L:")
.append(localAddressStr)
.append(active ? " - " : " ! ")
.append("R:")
.append(remoteAddressStr);
longId = buf.toString();
}
else if (localAddress != null) {
String localAddressStr = String.valueOf(localAddress);
StringBuilder buf = new StringBuilder(shortText.length() + 4 + localAddressStr.length())
.append(shortText)
.append(", L:")
.append(localAddressStr);
longId = buf.toString();
}
else {
longId = shortText;
}
localActive = active;
return longId;
}
/**
* A {@link ChannelOperations} factory
*/
@FunctionalInterface
public interface OnSetup {
/**
* Return an empty, no-op factory
*
* @return an empty, no-op factory
*/
static OnSetup empty() {
return EMPTY_SETUP;
}
/**
* Create a new {@link ChannelOperations} given a netty channel, a parent {@link
* ConnectionObserver} and an optional message (nullable).
*
* @param c a {@link Connection}
* @param listener a {@link ConnectionObserver}
* @param msg an optional message
*
* @return the new {@link ChannelOperations}
*/
@Nullable
ChannelOperations<?, ?> create(Connection c, ConnectionObserver listener, @Nullable Object msg);
}
static final Logger log = Loggers.getLogger(ChannelOperations.class);
static final Object TERMINATED_OPS = new Object();
static final OnSetup EMPTY_SETUP = (c, l, msg) -> null;
@SuppressWarnings("rawtypes")
static final AtomicReferenceFieldUpdater<ChannelOperations, Subscription>
OUTBOUND_CLOSE = AtomicReferenceFieldUpdater.newUpdater(ChannelOperations.class,
Subscription.class,
"outboundSubscription");
}