reactor.netty.ConnectionObserver Java Examples

The following examples show how to use reactor.netty.ConnectionObserver. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpClientConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(Channel ch) {
	ConnectionObserver obs = this.observer;
	if (obs == null) {
		ConnectionObserver owner = ch.parent().attr(OWNER).get();
		if (owner instanceof Http2ConnectionProvider.DisposableAcquire) {
			obs = ((Http2ConnectionProvider.DisposableAcquire) owner).obs;
		}
	}
	if (obs != null && opsFactory != null) {
		addStreamHandlers(ch, obs, opsFactory);
	}
	else {
		// TODO handle server pushes
	}
}
 
Example #2
Source File: HttpServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
HttpServerOperations(Connection c,
		ConnectionObserver listener,
		@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressionPredicate,
		HttpRequest nettyRequest,
		@Nullable ConnectionInfo connectionInfo,
		ServerCookieEncoder encoder,
		ServerCookieDecoder decoder) {
	super(c, listener);
	this.nettyRequest = nettyRequest;
	this.path = resolvePath(nettyRequest.uri());
	this.nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
	this.responseHeaders = nettyResponse.headers();
	this.responseHeaders.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
	this.compressionPredicate = compressionPredicate;
	this.cookieHolder = Cookies.newServerRequestHolder(requestHeaders(), decoder);
	this.connectionInfo = connectionInfo;
	this.cookieEncoder = encoder;
	this.cookieDecoder = decoder;
}
 
Example #3
Source File: HttpClientOperationsTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addDecoderReplaysLastHttp() {
	ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8);
	EmbeddedChannel channel = new EmbeddedChannel();
	new HttpClientOperations(() -> channel, ConnectionObserver.emptyListener(),
			ClientCookieEncoder.STRICT, ClientCookieDecoder.STRICT)
			.addHandler(new JsonObjectDecoder());
	channel.writeInbound(new DefaultLastHttpContent(buf));

	MatcherAssert.assertThat(channel.pipeline().names().iterator().next(), is("JsonObjectDecoder$extractor"));

	Object content = channel.readInbound();
	MatcherAssert.assertThat(content, instanceOf(ByteBuf.class));
	((ByteBuf) content).release();

	content = channel.readInbound();
	MatcherAssert.assertThat(content, instanceOf(LastHttpContent.class));
	((LastHttpContent) content).release();

	MatcherAssert.assertThat(channel.readInbound(), nullValue());
}
 
Example #4
Source File: ChannelOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
		onTerminate.onComplete();
		listener.onStateChange(this, ConnectionObserver.State.DISCONNECTING);
	}
}
 
Example #5
Source File: InstanceWebClient.java    From Moss with Apache License 2.0 6 votes vote down vote up
private static WebClient.Builder createDefaultWebClient(Duration connectTimeout, Duration readTimeout) {
    HttpClient httpClient = HttpClient.create()
                                      .compress(true)
                                      .tcpConfiguration(tcp -> tcp.bootstrap(bootstrap -> bootstrap.option(
                                          ChannelOption.CONNECT_TIMEOUT_MILLIS,
                                          (int) connectTimeout.toMillis()
                                      )).observe((connection, newState) -> {
                                          if (ConnectionObserver.State.CONNECTED.equals(newState)) {
                                              connection.addHandlerLast(new ReadTimeoutHandler(readTimeout.toMillis(),
                                                  TimeUnit.MILLISECONDS
                                              ));
                                          }
                                      }));
    ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
    return WebClient.builder().clientConnector(connector);
}
 
Example #6
Source File: ChannelOperationsHandler.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
final public void channelInactive(ChannelHandlerContext ctx) {
	try {
		Connection connection = Connection.from(ctx.channel());
		ChannelOperations<?, ?> ops = connection.as(ChannelOperations.class);
		if (ops != null) {
			ops.onInboundClose();
		}
		else {
			listener.onStateChange(connection, ConnectionObserver.State.DISCONNECTING);
		}
	}
	catch (Throwable err) {
		exceptionCaught(ctx, err);
	}
}
 
Example #7
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
H2OrHttp11Codec(
		@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate,
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		HttpRequestDecoderSpec decoder,
		boolean forwarded,
		Http2Settings http2Settings,
		ConnectionObserver listener,
		@Nullable Supplier<? extends ChannelMetricsRecorder> metricsRecorder,
		int minCompressionSize,
		ChannelOperations.OnSetup opsFactory,
		@Nullable Function<String, String> uriTagValue) {
	super(ApplicationProtocolNames.HTTP_1_1);
	this.compressPredicate = compressPredicate;
	this.cookieDecoder = cookieDecoder;
	this.cookieEncoder = cookieEncoder;
	this.decoder = decoder;
	this.forwarded = forwarded;
	this.http2Settings = http2Settings;
	this.listener = listener;
	this.metricsRecorder = metricsRecorder;
	this.minCompressionSize = minCompressionSize;
	this.opsFactory = opsFactory;
	this.uriTagValue = uriTagValue;
}
 
Example #8
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
Http11OrH2CleartextCodec(
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		boolean debug,
		boolean forwarded,
		Http2Settings http2Settings,
		ConnectionObserver listener,
		ChannelOperations.OnSetup opsFactory,
		boolean validate) {
	this.cookieDecoder = cookieDecoder;
	this.cookieEncoder = cookieEncoder;
	this.forwarded = forwarded;
	Http2FrameCodecBuilder http2FrameCodecBuilder =
			Http2FrameCodecBuilder.forServer()
			                      .validateHeaders(validate)
			                      .initialSettings(http2Settings);

	if (debug) {
		http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(
				LogLevel.DEBUG,
				"reactor.netty.http.server.h2"));
	}
	this.http2FrameCodec = http2FrameCodecBuilder.build();
	this.listener = listener;
	this.opsFactory = opsFactory;
}
 
Example #9
Source File: DefaultPooledConnectionProvider.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
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;
		}
	}
}
 
Example #10
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
static void addStreamHandlers(Channel ch, ChannelOperations.OnSetup opsFactory,
		ConnectionObserver listener, boolean readForwardHeaders,
		ServerCookieEncoder encoder, ServerCookieDecoder decoder) {
	if (ACCESS_LOG) {
		ch.pipeline()
		  .addLast(NettyPipeline.AccessLogHandler, new AccessLogHandlerH2());
	}
	ch.pipeline()
	  .addLast(NettyPipeline.H2ToHttp11Codec, new Http2StreamFrameToHttpObjectCodec(true))
	  .addLast(NettyPipeline.HttpTrafficHandler,
	           new Http2StreamBridgeServerHandler(listener, readForwardHeaders, encoder, decoder));

	ChannelOperations.addReactiveBridge(ch, opsFactory, listener);

	if (log.isDebugEnabled()) {
		log.debug(format(ch, "Initialized HTTP/2 stream pipeline {}"), ch.pipeline());
	}
}
 
Example #11
Source File: Http2ConnectionProvider.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
ConnectionObserver owner(Channel channel) {
	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;
		}
	}
}
 
Example #12
Source File: DefaultPooledConnectionProvider.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
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) owner).pooledRef
	                       .invalidate()
	                       .subscribe(null, null, () -> {
	                           if (log.isDebugEnabled()) {
	                               log.debug(format(channel, "Channel closed, now {} active connections and " +
	                                                                 "{} inactive connections"),
	                                       pool.metrics().acquiredSize(),
	                                       pool.metrics().idleSize());
	                           }
	                       });
	           }
	       });
}
 
Example #13
Source File: HttpClientOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
protected void onInboundClose() {
	if (isInboundCancelled() || isInboundDisposed()) {
		listener().onStateChange(this, ConnectionObserver.State.DISCONNECTING);
		return;
	}
	listener().onStateChange(this, HttpClientState.RESPONSE_INCOMPLETE);
	if (responseState == null) {
		if (markSentHeaderAndBody()) {
			listener().onUncaughtException(this, AbortedException.beforeSend());
		}
		else if (markSentBody()) {
			listener().onUncaughtException(this, new PrematureCloseException("Connection has been closed BEFORE response, while sending request body"));
		}
		else {
			listener().onUncaughtException(this, new PrematureCloseException("Connection prematurely closed BEFORE response"));
		}
		return;
	}
	super.onInboundError(new PrematureCloseException("Connection prematurely closed DURING response"));
}
 
Example #14
Source File: HttpClientConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
static void configureHttp2Pipeline(ChannelPipeline p, HttpResponseDecoderSpec decoder, Http2Settings http2Settings,
		ConnectionObserver observer) {
	Http2FrameCodecBuilder http2FrameCodecBuilder =
			Http2FrameCodecBuilder.forClient()
			                      .validateHeaders(decoder.validateHeaders())
			                      .initialSettings(http2Settings);

	if (p.get(NettyPipeline.LoggingHandler) != null) {
		http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(LogLevel.DEBUG,
				"reactor.netty.http.client.h2"));
	}

	p.addBefore(NettyPipeline.ReactiveBridge, NettyPipeline.HttpCodec, http2FrameCodecBuilder.build())
	 .addBefore(NettyPipeline.ReactiveBridge, NettyPipeline.H2MultiplexHandler, new Http2MultiplexHandler(new H2Codec()))
	 .addBefore(NettyPipeline.ReactiveBridge, NettyPipeline.HttpTrafficHandler, new HttpTrafficHandler(observer));
}
 
Example #15
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
static void configureH2Pipeline(ChannelPipeline p,
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		boolean forwarded,
		Http2Settings http2Settings,
		ConnectionObserver listener,
		ChannelOperations.OnSetup opsFactory,
		boolean validate) {
	p.remove(NettyPipeline.ReactiveBridge);

	Http2FrameCodecBuilder http2FrameCodecBuilder =
			Http2FrameCodecBuilder.forServer()
			                      .validateHeaders(validate)
			                      .initialSettings(http2Settings);

	if (p.get(NettyPipeline.LoggingHandler) != null) {
		http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(LogLevel.DEBUG,
				"reactor.netty.http.server.h2"));
	}

	p.addLast(NettyPipeline.HttpCodec, http2FrameCodecBuilder.build())
	 .addLast(NettyPipeline.H2MultiplexHandler,
	          new Http2MultiplexHandler(new H2Codec(opsFactory, listener, forwarded, cookieEncoder, cookieDecoder)));
}
 
Example #16
Source File: HttpTrafficHandler.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) {
	Channel channel = ctx.channel();
	if (channel.isActive()) {
		if (ctx.pipeline().get(NettyPipeline.H2MultiplexHandler) == null) {
			// Proceed with HTTP/1.x as per configuration
			ctx.fireChannelActive();
		}
		else if (ctx.pipeline().get(NettyPipeline.SslHandler) == null) {
			// Proceed with H2C as per configuration
			sendNewState(Connection.from(channel), ConnectionObserver.State.CONNECTED);
			ctx.flush();
			ctx.read();
		}
		else {
			// Proceed with H2 as per configuration
			sendNewState(Connection.from(channel), ConnectionObserver.State.CONNECTED);
		}
	}
}
 
Example #17
Source File: UdpServerConfig.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected ConnectionObserver defaultConnectionObserver() {
	if (channelGroup() == null && doOnBound() == null && doOnUnbound() == null) {
		return ConnectionObserver.emptyListener();
	}
	return new UdpServerDoOn(channelGroup(), doOnBound(), doOnUnbound());
}
 
Example #18
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
H2Codec(ChannelOperations.OnSetup opsFactory, ConnectionObserver listener, boolean forwarded,
		ServerCookieEncoder encoder, ServerCookieDecoder decoder) {
	this.forwarded = forwarded;
	this.listener = listener;
	this.cookieEncoder = encoder;
	this.cookieDecoder = decoder;
	this.opsFactory = opsFactory;
}
 
Example #19
Source File: HttpServerHandleHttpServerStateInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
public boolean isDisconnecting(Object[] args) {
    if (!validate(args)) {
        return false;
    }
    ConnectionObserver.State state = (ConnectionObserver.State) args[1];
    if (state != HttpServerState.DISCONNECTING) {
        return false;
    }
    return true;
}
 
Example #20
Source File: ClientTransportConfig.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected ConnectionObserver defaultConnectionObserver() {
	if (channelGroup() == null && doOnConnected() == null && doOnDisconnected() == null) {
		return ConnectionObserver.emptyListener();
	}
	return new ClientTransportDoOn(channelGroup(), doOnConnected(), doOnDisconnected());
}
 
Example #21
Source File: Http2ConnectionProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
static void invalidate(@Nullable ConnectionObserver owner, Channel channel) {
	if (owner instanceof DisposableAcquire) {
		DisposableAcquire da = ((DisposableAcquire) owner);
		da.pooledRef
		  .invalidate()
		  .subscribe(null, null, () -> {
		      if (log.isDebugEnabled()) {
		          log.debug(format(channel, "Channel removed from the pool, now {} active connections and {} inactive connections"),
		              da.pool.metrics().acquiredSize(),
		              da.pool.metrics().idleSize());
		      }
		  });
	}
}
 
Example #22
Source File: ServerTransportConfig.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected ConnectionObserver defaultConnectionObserver() {
	if (doOnBound() == null && doOnUnbound() == null) {
		return ConnectionObserver.emptyListener();
	}
	return new ServerTransportDoOn(doOnBound(), doOnUnbound());
}
 
Example #23
Source File: HttpClientOperations.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
HttpClientOperations(Connection c, ConnectionObserver listener, ClientCookieEncoder encoder, ClientCookieDecoder decoder) {
	super(c, listener);
	this.isSecure = c.channel()
	                 .pipeline()
	                 .get(NettyPipeline.SslHandler) != null;
	this.nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
	this.requestHeaders = nettyRequest.headers();
	this.cookieDecoder = decoder;
	this.cookieEncoder = encoder;
}
 
Example #24
Source File: HttpTrafficHandler.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
void sendNewState(Connection connection, ConnectionObserver.State state) {
	ChannelOperations<?, ?> ops = connection.as(ChannelOperations.class);
	if (ops != null) {
		listener.onStateChange(ops, state);
	}
	else {
		listener.onStateChange(connection, state);
	}
}
 
Example #25
Source File: HttpTrafficHandler.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
	if (msg instanceof Http2SettingsFrame) {
		sendNewState(Connection.from(ctx.channel()), ConnectionObserver.State.CONFIGURED);
		ctx.pipeline().remove(NettyPipeline.ReactiveBridge);
		ctx.pipeline().remove(this);
		return;
	}

	ctx.fireChannelRead(msg);
}
 
Example #26
Source File: ServerTransport.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
/**
 * Binds the {@link ServerTransport} and returns a {@link Mono} of {@link DisposableServer}. If
 * {@link Mono} is cancelled, the underlying binding will be aborted. Once the {@link
 * DisposableServer} has been emitted and is not necessary anymore, disposing the main server
 * loop must be done by the user via {@link DisposableServer#dispose()}.
 *
 * @return a {@link Mono} of {@link DisposableServer}
 */
public Mono<? extends DisposableServer> bind() {
	CONF config = configuration();
	Objects.requireNonNull(config.bindAddress(), "bindAddress");

	Mono<? extends DisposableServer> mono =  Mono.create(sink -> {
		SocketAddress local = Objects.requireNonNull(config.bindAddress().get(), "Bind Address supplier returned null");
		if (local instanceof InetSocketAddress) {
			InetSocketAddress localInet = (InetSocketAddress) local;

			if (localInet.isUnresolved()) {
				local = AddressUtils.createResolved(localInet.getHostName(), localInet.getPort());
			}
		}

		boolean isDomainSocket = false;
		DisposableBind disposableServer;
		if (local instanceof DomainSocketAddress) {
			isDomainSocket = true;
			disposableServer = new UdsDisposableBind(sink, config, local);
		}
		else {
			disposableServer = new InetDisposableBind(sink, config, local);
		}

		ConnectionObserver childObs =
				new ChildObserver(config.defaultChildObserver().then(config.childObserver()));
		Acceptor acceptor = new Acceptor(config.childEventLoopGroup(), config.channelInitializer(childObs, null, true),
				config.childOptions, config.childAttrs, isDomainSocket);
		TransportConnector.bind(config, new AcceptorInitializer(acceptor), local, isDomainSocket)
		                  .subscribe(disposableServer);
	});

	if (config.doOnBind() != null) {
		mono = mono.doOnSubscribe(s -> config.doOnBind().accept(config));
	}
	return mono;
}
 
Example #27
Source File: ServerTransport.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
/**
 * Set or add the given {@link ConnectionObserver} for each remote connection
 *
 * @param observer the {@link ConnectionObserver} addition
 * @return a new {@link ServerTransport} reference
 */
public T childObserve(ConnectionObserver observer) {
	Objects.requireNonNull(observer, "observer");
	T dup = duplicate();
	ConnectionObserver current = configuration().childObserver;
	dup.configuration().childObserver = current == null ? observer : current.then(observer);
	return dup;
}
 
Example #28
Source File: HttpConnectionProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<? extends Connection> acquire(
		TransportConfig config,
		ConnectionObserver connectionObserver,
		@Nullable Supplier<? extends SocketAddress> remoteAddress,
		@Nullable AddressResolverGroup<?> resolverGroup) {
	if (((HttpClientConfig) config)._protocols == HttpClientConfig.h11) {
		return http1ConnectionProvider.acquire(config, connectionObserver, remoteAddress, resolverGroup);
	}
	else {
		return h2ConnectionProviderSupplier.get().acquire(config, connectionObserver, remoteAddress, resolverGroup);
	}
}
 
Example #29
Source File: HttpClientConfig.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
H2OrHttp11Codec(
		boolean acceptGzip,
		HttpResponseDecoderSpec decoder,
		Http2Settings http2Settings,
		@Nullable Supplier<? extends ChannelMetricsRecorder> metricsRecorder,
		ConnectionObserver observer,
		@Nullable Function<String, String> uriTagValue) {
	this.acceptGzip = acceptGzip;
	this.decoder = decoder;
	this.http2Settings = http2Settings;
	this.metricsRecorder = metricsRecorder;
	this.observer = observer;
	this.uriTagValue = uriTagValue;
}
 
Example #30
Source File: HttpServerHandleStateInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
public boolean isDisconnecting(Object[] args) {
    if (!validate(args)) {
        return false;
    }

    ConnectionObserver.State state = (ConnectionObserver.State) args[1];
    if (state != ConnectionObserver.State.DISCONNECTING) {
        return false;
    }

    return true;
}