Search in sources :

Example 61 with Http2Stream

use of io.netty.handler.codec.http2.Http2Stream in project vert.x by eclipse-vertx.

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 62 with Http2Stream

use of io.netty.handler.codec.http2.Http2Stream in project esa-restclient by esastack.

the class Http2FrameHandler method onHeadersRead.

@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endOfStream) throws Http2Exception {
    final Http2Stream stream = connection.stream(streamId);
    headers.setInt(STREAM_ID.text(), streamId);
    headers.addLong(HttpHeadersUtils.TTFB, System.currentTimeMillis());
    onHeaders(streamId, stream, headers, stream.getProperty(messageKey) != null, endOfStream);
}
Also used : Http2Stream(io.netty.handler.codec.http2.Http2Stream)

Example 63 with Http2Stream

use of io.netty.handler.codec.http2.Http2Stream in project esa-restclient by esastack.

the class Http2FrameHandler method onDataRead.

@Override
public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) {
    final ResponseHandle handle = registry.get(streamId);
    if (handle == null) {
        // The request has ended before.
        return data.readableBytes() + padding;
    }
    final int readableBytes = data.readableBytes();
    if (readableBytes > 0) {
        ByteBuf retainedData;
        boolean exceeded = false;
        if (handle.remaining == -1L) {
            retainedData = data;
        } else {
            handle.remaining -= readableBytes;
            if (handle.remaining >= 0L) {
                retainedData = data;
            } else {
                handle.remaining += readableBytes;
                retainedData = data.slice(0, (int) handle.remaining);
                exceeded = true;
                handle.remaining = 0L;
            }
        }
        handle.onData(new BufferImpl(retainedData.duplicate()));
        if (exceeded) {
            String errMsg = String.format("Content length exceeded %d bytes", maxContentLength);
            onError(new ContentOverSizedException(errMsg), null, streamId, true);
            return readableBytes + padding;
        }
    }
    if (endOfStream) {
        handle.onEnd();
        final Http2Stream stream = connection.stream(streamId);
        if (stream != null) {
            stream.removeProperty(messageKey);
        }
        registry.remove(streamId);
    }
    // All bytes have been processed.
    return readableBytes + padding;
}
Also used : ContentOverSizedException(io.esastack.httpclient.core.exception.ContentOverSizedException) Http2Stream(io.netty.handler.codec.http2.Http2Stream) ByteBuf(io.netty.buffer.ByteBuf) BufferImpl(io.esastack.commons.net.netty.buffer.BufferImpl)

Example 64 with Http2Stream

use of io.netty.handler.codec.http2.Http2Stream in project esa-restclient by esastack.

the class Http2FrameHandler method onPushPromiseRead.

@Override
public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId, Http2Headers headers, int padding) throws Http2Exception {
    // A push promise should not be allowed to add headers to an existing stream
    Http2Stream promisedStream = connection.stream(promisedStreamId);
    if (promisedStream.getProperty(messageKey) != null) {
        throw connectionError(PROTOCOL_ERROR, "Push Promise Frame received for pre-existing stream id %d", promisedStreamId);
    }
    if (headers.status() == null) {
        headers.status(OK.codeAsText());
    }
    headers.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), Http2CodecUtil.DEFAULT_PRIORITY_WEIGHT);
    headers.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_PROMISE_ID.text(), streamId);
    onHeaders(promisedStreamId, promisedStream, headers, false, false);
}
Also used : Http2Stream(io.netty.handler.codec.http2.Http2Stream)

Example 65 with Http2Stream

use of io.netty.handler.codec.http2.Http2Stream in project esa-restclient by esastack.

the class Http2ConnectionHelper method setUp.

void setUp(HandleRegistry registry) throws Http2Exception {
    MockitoAnnotations.initMocks(this);
    when(stream.open(anyBoolean())).thenReturn(stream);
    when(remote.flowController()).thenReturn(remoteFlowController);
    when(local.flowController()).thenReturn(localFlowController);
    when(connection.remote()).thenReturn(remote);
    when(connection.local()).thenReturn(local);
    when(connection.forEachActiveStream(any(Http2StreamVisitor.class))).thenAnswer((Answer<Http2Stream>) in -> {
        Http2StreamVisitor visitor = in.getArgument(0);
        if (!visitor.visit(stream)) {
            return stream;
        }
        return null;
    });
    when(connection.numActiveStreams()).thenReturn(1);
    when(connection.stream(STREAM_ID)).thenReturn(stream);
    when(connection.goAwaySent(anyInt(), anyLong(), any(ByteBuf.class))).thenReturn(true);
    when(encoder.connection()).thenReturn(connection);
    when(encoder.frameWriter()).thenReturn(frameWriter);
    when(encoder.flowController()).thenReturn(remoteFlow);
    when(encoder.writeSettings(any(ChannelHandlerContext.class), any(Http2Settings.class), any(ChannelPromise.class))).thenAnswer(invocation -> {
        ChannelPromise p = invocation.getArgument(2);
        return p.setSuccess();
    });
    when(encoder.writeGoAway(any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class), any(ChannelPromise.class))).thenAnswer(invocation -> {
        ChannelPromise p = invocation.getArgument(4);
        return p.setSuccess();
    });
    when(decoder.connection()).thenReturn(connection);
    when(decoder.flowController()).thenReturn(localFlow);
    when(frameWriter.writeGoAway(any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class), any(ChannelPromise.class))).thenAnswer((Answer<ChannelFuture>) invocation -> {
        ByteBuf buf = invocation.getArgument(3);
        buf.release();
        ChannelPromise p = invocation.getArgument(4);
        return p.setSuccess();
    });
    channel = new EmbeddedChannel(new Http2ConnectionHandler(decoder, encoder, Http2Settings.defaultSettings(), false, registry));
    Helper.mockHeaderAndDataFrameWrite(encoder);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) Mock(org.mockito.Mock) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Http2FrameWriter(io.netty.handler.codec.http2.Http2FrameWriter) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) Mockito.when(org.mockito.Mockito.when) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) ChannelFuture(io.netty.channel.ChannelFuture) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) Http2StreamVisitor(io.netty.handler.codec.http2.Http2StreamVisitor) Http2Settings(io.netty.handler.codec.http2.Http2Settings) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) MockitoAnnotations(org.mockito.MockitoAnnotations) Answer(org.mockito.stubbing.Answer) Http2Connection(io.netty.handler.codec.http2.Http2Connection) ByteBuf(io.netty.buffer.ByteBuf) ChannelPromise(io.netty.channel.ChannelPromise) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Http2Stream(io.netty.handler.codec.http2.Http2Stream) Http2LocalFlowController(io.netty.handler.codec.http2.Http2LocalFlowController) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) Http2RemoteFlowController(io.netty.handler.codec.http2.Http2RemoteFlowController) Mockito.mock(org.mockito.Mockito.mock) ChannelFuture(io.netty.channel.ChannelFuture) Http2StreamVisitor(io.netty.handler.codec.http2.Http2StreamVisitor) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) Http2Stream(io.netty.handler.codec.http2.Http2Stream) Http2Settings(io.netty.handler.codec.http2.Http2Settings) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

Http2Stream (io.netty.handler.codec.http2.Http2Stream)44 Http2Exception (io.netty.handler.codec.http2.Http2Exception)15 ByteBuf (io.netty.buffer.ByteBuf)12 Test (org.junit.Test)12 Test (org.junit.jupiter.api.Test)9 Http2Connection (io.netty.handler.codec.http2.Http2Connection)8 ChannelFuture (io.netty.channel.ChannelFuture)7 Http2StreamVisitor (io.netty.handler.codec.http2.Http2StreamVisitor)7 CountDownLatch (java.util.concurrent.CountDownLatch)7 Metadata (io.grpc.Metadata)6 Http2LocalFlowController (io.netty.handler.codec.http2.Http2LocalFlowController)6 Status (io.grpc.Status)5 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)5 StreamException (io.netty.handler.codec.http2.Http2Exception.StreamException)5 Channel (io.netty.channel.Channel)4 DefaultHttp2Headers (io.netty.handler.codec.http2.DefaultHttp2Headers)4 Http2Headers (io.netty.handler.codec.http2.Http2Headers)4 AsyncResult (io.vertx.core.AsyncResult)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 Bootstrap (io.netty.bootstrap.Bootstrap)3