Search in sources :

Example 16 with HTTP2Stream

use of org.eclipse.jetty.http2.HTTP2Stream in project vert.x by eclipse.

the class Http2ServerConnection method createRequest.

private Http2ServerRequest createRequest(int streamId, Http2Headers headers, boolean streamEnded) {
    Http2Stream stream = handler.connection().stream(streamId);
    String contentEncoding = options.isCompressionSupported() ? HttpUtils.determineContentEncoding(headers) : null;
    Http2ServerRequest request = new Http2ServerRequest(this, options.getTracingPolicy(), streamContextSupplier.get(), serverOrigin, headers, contentEncoding, streamEnded);
    request.isConnect = request.method() == HttpMethod.CONNECT;
    request.init(stream);
    return request;
}
Also used : Http2Stream(io.netty.handler.codec.http2.Http2Stream)

Example 17 with HTTP2Stream

use of org.eclipse.jetty.http2.HTTP2Stream in project vert.x by eclipse.

the class Http2ServerTest method testStreamPauseResume.

private void testStreamPauseResume(Function<HttpServerRequest, Future<ReadStream<Buffer>>> streamProvider) throws Exception {
    Buffer expected = Buffer.buffer();
    String chunk = TestUtils.randomAlphaString(1000);
    AtomicBoolean done = new AtomicBoolean();
    AtomicBoolean paused = new AtomicBoolean();
    Buffer received = Buffer.buffer();
    server.requestHandler(req -> {
        Future<ReadStream<Buffer>> fut = streamProvider.apply(req);
        fut.onComplete(onSuccess(stream -> {
            vertx.setPeriodic(1, timerID -> {
                if (paused.get()) {
                    vertx.cancelTimer(timerID);
                    done.set(true);
                    // Let some time to accumulate some more buffers
                    vertx.setTimer(100, id -> {
                        stream.resume();
                    });
                }
            });
            stream.handler(received::appendBuffer);
            stream.endHandler(v -> {
                assertEquals(expected, received);
                testComplete();
            });
            stream.pause();
        }));
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        request.encoder.writeHeaders(request.context, id, POST("/form").set("content-type", "text/plain"), 0, false, request.context.newPromise());
        request.context.flush();
        Http2Stream stream = request.connection.stream(id);
        class Anonymous {

            void send() {
                boolean writable = request.encoder.flowController().isWritable(stream);
                if (writable) {
                    Buffer buf = Buffer.buffer(chunk);
                    expected.appendBuffer(buf);
                    request.encoder.writeData(request.context, id, buf.getByteBuf(), 0, false, request.context.newPromise());
                    request.context.flush();
                    request.context.executor().execute(this::send);
                } else {
                    request.encoder.writeData(request.context, id, Unpooled.EMPTY_BUFFER, 0, true, request.context.newPromise());
                    request.context.flush();
                    paused.set(true);
                }
            }
        }
        new Anonymous().send();
    });
    fut.sync();
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) MultiMap(io.vertx.core.MultiMap) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http1xOrH2CHandler(io.vertx.core.http.impl.Http1xOrH2CHandler) Context(io.vertx.core.Context) Utils(io.vertx.core.impl.Utils) Unpooled(io.netty.buffer.Unpooled) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) ByteArrayInputStream(java.io.ByteArrayInputStream) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ReadStream(io.vertx.core.streams.ReadStream) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) Http2Flags(io.netty.handler.codec.http2.Http2Flags) Trust(io.vertx.test.tls.Trust) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) StandardCharsets(java.nio.charset.StandardCharsets) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) Http2Error(io.netty.handler.codec.http2.Http2Error) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream) BiConsumer(java.util.function.BiConsumer) Assume(org.junit.Assume) AsyncResult(io.vertx.core.AsyncResult) DetectFileDescriptorLeaks(io.vertx.test.core.DetectFileDescriptorLeaks) VertxInternal(io.vertx.core.impl.VertxInternal) ClosedChannelException(java.nio.channels.ClosedChannelException) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) IOException(java.io.IOException) SSLHelper(io.vertx.core.net.impl.SSLHelper) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Bootstrap(io.netty.bootstrap.Bootstrap) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2Connection(io.netty.handler.codec.http2.Http2Connection) HttpUtils(io.vertx.core.http.impl.HttpUtils) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) ChannelFuture(io.netty.channel.ChannelFuture) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ReadStream(io.vertx.core.streams.ReadStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream)

Example 18 with HTTP2Stream

use of org.eclipse.jetty.http2.HTTP2Stream in project rest.li by linkedin.

the class Http2PipelinePropertyUtil method doAction.

private static <T> T doAction(ChannelHandlerContext ctx, Http2Connection http2Connection, int streamId, AttributeKey<Http2Connection.PropertyKey> key, BiFunction<Http2Stream, Http2Connection.PropertyKey, T> function) {
    ArgumentUtil.notNull(http2Connection, "http2Connection");
    final Http2Stream stream = http2Connection.stream(streamId);
    if (stream == null) {
        LOG.debug("Stream {} no longer exists", streamId);
        return null;
    }
    final Http2Connection.PropertyKey propertyKey = getKey(ctx, key);
    if (propertyKey == null) {
        LOG.debug("Property key {} is not valid", key);
        return null;
    }
    return function.apply(stream, propertyKey);
}
Also used : Http2Connection(io.netty.handler.codec.http2.Http2Connection) Http2Stream(io.netty.handler.codec.http2.Http2Stream)

Example 19 with HTTP2Stream

use of org.eclipse.jetty.http2.HTTP2Stream in project jetty.project by eclipse.

the class StreamCloseTest method testRequestDataClosedResponseDataClosedClosesStream.

@Test
public void testRequestDataClosedResponseDataClosedClosesStream() throws Exception {
    final CountDownLatch serverDataLatch = new CountDownLatch(1);
    start(new ServerSessionListener.Adapter() {

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
            MetaData.Response metaData = new MetaData.Response(HttpVersion.HTTP_2, 200, new HttpFields());
            HeadersFrame response = new HeadersFrame(stream.getId(), metaData, null, false);
            Callback.Completable completable = new Callback.Completable();
            stream.headers(response, completable);
            return new Stream.Listener.Adapter() {

                @Override
                public void onData(final Stream stream, DataFrame frame, final Callback callback) {
                    Assert.assertTrue(((HTTP2Stream) stream).isRemotelyClosed());
                    // We must copy the data that we send asynchronously.
                    ByteBuffer data = frame.getData();
                    ByteBuffer copy = ByteBuffer.allocate(data.remaining());
                    copy.put(data).flip();
                    completable.thenRun(() -> stream.data(new DataFrame(stream.getId(), copy, frame.isEndStream()), new Callback() {

                        @Override
                        public void succeeded() {
                            Assert.assertTrue(stream.isClosed());
                            Assert.assertEquals(0, stream.getSession().getStreams().size());
                            callback.succeeded();
                            serverDataLatch.countDown();
                        }
                    }));
                }
            };
        }
    });
    final CountDownLatch completeLatch = new CountDownLatch(1);
    Session session = newClient(new Session.Listener.Adapter());
    HeadersFrame frame = new HeadersFrame(newRequest("GET", new HttpFields()), null, false);
    FuturePromise<Stream> promise = new FuturePromise<>();
    session.newStream(frame, promise, new Stream.Listener.Adapter() {

        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback) {
            // The sent data callback may not be notified yet here.
            callback.succeeded();
            completeLatch.countDown();
        }
    });
    final Stream stream = promise.get(5, TimeUnit.SECONDS);
    Assert.assertFalse(stream.isClosed());
    Assert.assertFalse(((HTTP2Stream) stream).isLocallyClosed());
    final CountDownLatch clientDataLatch = new CountDownLatch(1);
    stream.data(new DataFrame(stream.getId(), ByteBuffer.wrap(new byte[512]), true), new Callback() {

        @Override
        public void succeeded() {
            // Here the stream may be just locally closed or fully closed.
            clientDataLatch.countDown();
        }
    });
    Assert.assertTrue(clientDataLatch.await(5, TimeUnit.SECONDS));
    Assert.assertTrue(serverDataLatch.await(5, TimeUnit.SECONDS));
    Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
    Assert.assertTrue(stream.isClosed());
    Assert.assertEquals(0, stream.getSession().getStreams().size());
}
Also used : ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HTTP2Stream(org.eclipse.jetty.http2.HTTP2Stream) FuturePromise(org.eclipse.jetty.util.FuturePromise) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) ByteBuffer(java.nio.ByteBuffer) Callback(org.eclipse.jetty.util.Callback) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) HTTP2Stream(org.eclipse.jetty.http2.HTTP2Stream) Stream(org.eclipse.jetty.http2.api.Stream) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 20 with HTTP2Stream

use of org.eclipse.jetty.http2.HTTP2Stream in project vert.x by eclipse.

the class Http2ServerConnection method onHeadersRead.

@Override
public synchronized void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endOfStream) {
    VertxHttp2Stream stream = streams.get(streamId);
    if (stream == null) {
        if (isMalformedRequest(headers)) {
            handler.writeReset(streamId, Http2Error.PROTOCOL_ERROR.code());
            return;
        }
        String contentEncoding = options.isCompressionSupported() ? HttpUtils.determineContentEncoding(headers) : null;
        Http2Stream s = handler.connection().stream(streamId);
        boolean writable = handler.encoder().flowController().isWritable(s);
        Http2ServerRequestImpl req = new Http2ServerRequestImpl(this, s, metrics, serverOrigin, headers, contentEncoding, writable);
        stream = req;
        CharSequence value = headers.get(HttpHeaderNames.EXPECT);
        if (options.isHandle100ContinueAutomatically() && ((value != null && HttpHeaderValues.CONTINUE.equals(value)) || headers.contains(HttpHeaderNames.EXPECT, HttpHeaderValues.CONTINUE))) {
            req.response().writeContinue();
        }
        streams.put(streamId, req);
        context.executeFromIO(() -> {
            Http2ServerResponseImpl resp = req.response();
            resp.beginRequest();
            requestHandler.handle(req);
            boolean hasPush = resp.endRequest();
            if (hasPush) {
                ctx.flush();
            }
        });
    } else {
    // Http server request trailer - not implemented yet (in api)
    }
    if (endOfStream) {
        context.executeFromIO(stream::onEnd);
    }
}
Also used : Http2Stream(io.netty.handler.codec.http2.Http2Stream)

Aggregations

Http2Stream (io.netty.handler.codec.http2.Http2Stream)26 Http2Exception (io.netty.handler.codec.http2.Http2Exception)10 Test (org.junit.Test)9 Metadata (io.grpc.Metadata)6 Http2StreamVisitor (io.netty.handler.codec.http2.Http2StreamVisitor)6 Status (io.grpc.Status)5 Http2Connection (io.netty.handler.codec.http2.Http2Connection)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 HttpFields (org.eclipse.jetty.http.HttpFields)4 HTTP2Session (org.eclipse.jetty.http2.HTTP2Session)4 HTTP2Stream (org.eclipse.jetty.http2.HTTP2Stream)4 Session (org.eclipse.jetty.http2.api.Session)4 Stream (org.eclipse.jetty.http2.api.Stream)4 ServerSessionListener (org.eclipse.jetty.http2.api.server.ServerSessionListener)4 ChannelFuture (io.netty.channel.ChannelFuture)3 Http2LocalFlowController (io.netty.handler.codec.http2.Http2LocalFlowController)3 HeadersFrame (org.eclipse.jetty.http2.frames.HeadersFrame)3 FuturePromise (org.eclipse.jetty.util.FuturePromise)3 ByteBuf (io.netty.buffer.ByteBuf)2 DefaultHttp2Connection (io.netty.handler.codec.http2.DefaultHttp2Connection)2