Search in sources :

Example 1 with ISession

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

the class FlowControlStrategyTest method testClientExceedingStreamWindow.

@Test
public void testClientExceedingStreamWindow() throws Exception {
    // On server, we don't consume the data.
    start(new ServerSessionListener.Adapter() {

        @Override
        public Map<Integer, Integer> onPreface(Session session) {
            // Enlarge the session window.
            ((ISession) session).updateRecvWindow(FlowControlStrategy.DEFAULT_WINDOW_SIZE);
            return super.onPreface(session);
        }
    });
    final CountDownLatch closeLatch = new CountDownLatch(1);
    Session session = newClient(new Session.Listener.Adapter() {

        @Override
        public void onClose(Session session, GoAwayFrame frame) {
            if (frame.getError() == ErrorCode.FLOW_CONTROL_ERROR.code)
                closeLatch.countDown();
        }
    });
    // Consume the whole stream window.
    MetaData.Request metaData = newRequest("POST", new HttpFields());
    HeadersFrame requestFrame = new HeadersFrame(metaData, null, false);
    FuturePromise<Stream> streamPromise = new FuturePromise<>();
    session.newStream(requestFrame, streamPromise, new Stream.Listener.Adapter());
    Stream stream = streamPromise.get(5, TimeUnit.SECONDS);
    ByteBuffer data = ByteBuffer.allocate(FlowControlStrategy.DEFAULT_WINDOW_SIZE);
    final CountDownLatch dataLatch = new CountDownLatch(1);
    stream.data(new DataFrame(stream.getId(), data, false), new Callback() {

        @Override
        public InvocationType getInvocationType() {
            return InvocationType.NON_BLOCKING;
        }

        @Override
        public void succeeded() {
            dataLatch.countDown();
        }
    });
    Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS));
    // Wait for a while before doing the "sneaky" write
    // below, see comments in the previous test case.
    Thread.sleep(1000);
    // Now the client is supposed to not send more frames.
    // If it does, the connection must be closed.
    HTTP2Session http2Session = (HTTP2Session) session;
    ByteBufferPool.Lease lease = new ByteBufferPool.Lease(connector.getByteBufferPool());
    ByteBuffer extraData = ByteBuffer.allocate(1024);
    http2Session.getGenerator().data(lease, new DataFrame(stream.getId(), extraData, true), extraData.remaining());
    List<ByteBuffer> buffers = lease.getByteBuffers();
    http2Session.getEndPoint().write(Callback.NOOP, buffers.toArray(new ByteBuffer[buffers.size()]));
    // Expect the connection to be closed.
    Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS));
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) InvocationType(org.eclipse.jetty.util.thread.Invocable.InvocationType) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) 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) FuturePromise(org.eclipse.jetty.util.FuturePromise) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) GoAwayFrame(org.eclipse.jetty.http2.frames.GoAwayFrame) Callback(org.eclipse.jetty.util.Callback) FutureCallback(org.eclipse.jetty.util.FutureCallback) Map(java.util.Map) HashMap(java.util.HashMap) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) ISession(org.eclipse.jetty.http2.ISession) Test(org.junit.Test)

Example 2 with ISession

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

the class InterleavingTest method testInterleaving.

@Test
public void testInterleaving() throws Exception {
    CountDownLatch serverStreamsLatch = new CountDownLatch(2);
    List<Stream> serverStreams = new ArrayList<>();
    start(new ServerSessionListener.Adapter() {

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
            serverStreams.add(stream);
            serverStreamsLatch.countDown();
            return null;
        }
    });
    int maxFrameSize = Frame.DEFAULT_MAX_LENGTH + 1;
    Session session = newClient(new Session.Listener.Adapter() {

        @Override
        public Map<Integer, Integer> onPreface(Session session) {
            Map<Integer, Integer> settings = new HashMap<>();
            settings.put(SettingsFrame.MAX_FRAME_SIZE, maxFrameSize);
            return settings;
        }
    });
    BlockingQueue<FrameBytesCallback> dataFrames = new LinkedBlockingDeque<>();
    Stream.Listener streamListener = new Stream.Listener.Adapter() {

        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback) {
            ByteBuffer data = frame.getData();
            byte[] bytes = new byte[data.remaining()];
            data.get(bytes);
            dataFrames.offer(new FrameBytesCallback(frame, bytes, callback));
        }
    };
    HeadersFrame headersFrame1 = new HeadersFrame(newRequest("GET", new HttpFields()), null, true);
    FuturePromise<Stream> streamPromise1 = new FuturePromise<>();
    session.newStream(headersFrame1, streamPromise1, streamListener);
    streamPromise1.get(5, TimeUnit.SECONDS);
    HeadersFrame headersFrame2 = new HeadersFrame(newRequest("GET", new HttpFields()), null, true);
    FuturePromise<Stream> streamPromise2 = new FuturePromise<>();
    session.newStream(headersFrame2, streamPromise2, streamListener);
    streamPromise2.get(5, TimeUnit.SECONDS);
    Assert.assertTrue(serverStreamsLatch.await(5, TimeUnit.SECONDS));
    Thread.sleep(1000);
    Stream serverStream1 = serverStreams.get(0);
    Stream serverStream2 = serverStreams.get(1);
    MetaData.Response response1 = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, new HttpFields(), 0);
    serverStream1.headers(new HeadersFrame(serverStream1.getId(), response1, null, false), Callback.NOOP);
    Random random = new Random();
    byte[] content1 = new byte[2 * ((ISession) serverStream1.getSession()).updateSendWindow(0)];
    random.nextBytes(content1);
    byte[] content2 = new byte[2 * ((ISession) serverStream2.getSession()).updateSendWindow(0)];
    random.nextBytes(content2);
    MetaData.Response response2 = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, new HttpFields(), 0);
    serverStream2.headers(new HeadersFrame(serverStream2.getId(), response2, null, false), new Callback() {

        @Override
        public void succeeded() {
            // Write data for both streams from within the callback so that they get queued together.
            ByteBuffer buffer1 = ByteBuffer.wrap(content1);
            serverStream1.data(new DataFrame(serverStream1.getId(), buffer1, true), NOOP);
            ByteBuffer buffer2 = ByteBuffer.wrap(content2);
            serverStream2.data(new DataFrame(serverStream2.getId(), buffer2, true), NOOP);
        }
    });
    // The client reads with a buffer size that is different from the
    // frame size and synthesizes DATA frames, so expect N frames for
    // stream1 up to maxFrameSize of data, then M frames for stream2
    // up to maxFrameSize of data, and so forth, interleaved.
    Map<Integer, ByteArrayOutputStream> contents = new HashMap<>();
    contents.put(serverStream1.getId(), new ByteArrayOutputStream());
    contents.put(serverStream2.getId(), new ByteArrayOutputStream());
    List<StreamLength> streamLengths = new ArrayList<>();
    int finished = 0;
    while (finished < 2) {
        FrameBytesCallback frameBytesCallback = dataFrames.poll(5, TimeUnit.SECONDS);
        if (frameBytesCallback == null)
            Assert.fail();
        DataFrame dataFrame = frameBytesCallback.frame;
        int streamId = dataFrame.getStreamId();
        int length = dataFrame.remaining();
        streamLengths.add(new StreamLength(streamId, length));
        if (dataFrame.isEndStream())
            ++finished;
        contents.get(streamId).write(frameBytesCallback.bytes);
        frameBytesCallback.callback.succeeded();
    }
    // Verify that the content has been sent properly.
    Assert.assertArrayEquals(content1, contents.get(serverStream1.getId()).toByteArray());
    Assert.assertArrayEquals(content2, contents.get(serverStream2.getId()).toByteArray());
    // Verify that the interleaving is correct.
    Map<Integer, List<Integer>> groups = new HashMap<>();
    groups.put(serverStream1.getId(), new ArrayList<>());
    groups.put(serverStream2.getId(), new ArrayList<>());
    int currentStream = 0;
    int currentLength = 0;
    for (StreamLength streamLength : streamLengths) {
        if (currentStream == 0)
            currentStream = streamLength.stream;
        if (currentStream != streamLength.stream) {
            groups.get(currentStream).add(currentLength);
            currentStream = streamLength.stream;
            currentLength = 0;
        }
        currentLength += streamLength.length;
    }
    groups.get(currentStream).add(currentLength);
    Logger logger = Log.getLogger(getClass());
    logger.debug("frame lengths = {}", streamLengths);
    groups.forEach((stream, lengths) -> {
        logger.debug("stream {} interleaved lengths = {}", stream, lengths);
        for (Integer length : lengths) Assert.assertThat(length, Matchers.lessThanOrEqualTo(maxFrameSize));
    });
}
Also used : ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Logger(org.eclipse.jetty.util.log.Logger) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) Random(java.util.Random) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Stream(org.eclipse.jetty.http2.api.Stream) ArrayList(java.util.ArrayList) List(java.util.List) FuturePromise(org.eclipse.jetty.util.FuturePromise) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) Callback(org.eclipse.jetty.util.Callback) HashMap(java.util.HashMap) Map(java.util.Map) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Session(org.eclipse.jetty.http2.api.Session) ISession(org.eclipse.jetty.http2.ISession) Test(org.junit.Test)

Example 3 with ISession

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

the class StreamResetTest method testClientResetConsumesQueuedData.

@Test
public void testClientResetConsumesQueuedData() throws Exception {
    start(new EmptyHttpServlet());
    Session client = newClient(new Session.Listener.Adapter());
    MetaData.Request request = newRequest("GET", new HttpFields());
    HeadersFrame frame = new HeadersFrame(request, null, false);
    FuturePromise<Stream> promise = new FuturePromise<>();
    client.newStream(frame, promise, new Stream.Listener.Adapter());
    Stream stream = promise.get(5, TimeUnit.SECONDS);
    ByteBuffer data = ByteBuffer.allocate(FlowControlStrategy.DEFAULT_WINDOW_SIZE);
    CountDownLatch dataLatch = new CountDownLatch(1);
    stream.data(new DataFrame(stream.getId(), data, false), new Callback() {

        @Override
        public void succeeded() {
            dataLatch.countDown();
        }
    });
    // The server does not read the data, so the flow control window should be zero.
    Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS));
    Assert.assertEquals(0, ((ISession) client).updateSendWindow(0));
    // Now reset the stream.
    stream.reset(new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP);
    // Wait for the server to receive the reset and process
    // it, and for the client to process the window updates.
    Thread.sleep(1000);
    Assert.assertThat(((ISession) client).updateSendWindow(0), Matchers.greaterThan(0));
}
Also used : ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) WriteListener(javax.servlet.WriteListener) 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) FutureCallback(org.eclipse.jetty.util.FutureCallback) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) ServletOutputStream(javax.servlet.ServletOutputStream) IStream(org.eclipse.jetty.http2.IStream) ResetFrame(org.eclipse.jetty.http2.frames.ResetFrame) Session(org.eclipse.jetty.http2.api.Session) ISession(org.eclipse.jetty.http2.ISession) Test(org.junit.Test)

Example 4 with ISession

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

the class StreamResetTest method testServerExceptionConsumesQueuedData.

@Test
public void testServerExceptionConsumesQueuedData() throws Exception {
    try (StacklessLogging suppressor = new StacklessLogging(HttpChannel.class)) {
        start(new HttpServlet() {

            @Override
            protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                try {
                    // Wait to let the data sent by the client to be queued.
                    Thread.sleep(1000);
                    throw new IllegalStateException("explictly_thrown_by_test");
                } catch (InterruptedException e) {
                    throw new InterruptedIOException();
                }
            }
        });
        Session client = newClient(new Session.Listener.Adapter());
        Log.getLogger(HttpChannel.class).info("Expecting java.lang.IllegalStateException: explictly_thrown_by_test");
        MetaData.Request request = newRequest("GET", new HttpFields());
        HeadersFrame frame = new HeadersFrame(request, null, false);
        FuturePromise<Stream> promise = new FuturePromise<>();
        client.newStream(frame, promise, new Stream.Listener.Adapter());
        Stream stream = promise.get(5, TimeUnit.SECONDS);
        ByteBuffer data = ByteBuffer.allocate(FlowControlStrategy.DEFAULT_WINDOW_SIZE);
        CountDownLatch dataLatch = new CountDownLatch(1);
        stream.data(new DataFrame(stream.getId(), data, false), new Callback() {

            @Override
            public void succeeded() {
                dataLatch.countDown();
            }
        });
        // The server does not read the data, so the flow control window should be zero.
        Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS));
        Assert.assertEquals(0, ((ISession) client).updateSendWindow(0));
        // Wait for the server process the exception, and
        // for the client to process the window updates.
        Thread.sleep(2000);
        Assert.assertThat(((ISession) client).updateSendWindow(0), Matchers.greaterThan(0));
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) WriteListener(javax.servlet.WriteListener) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) HttpChannel(org.eclipse.jetty.server.HttpChannel) Stream(org.eclipse.jetty.http2.api.Stream) ServletOutputStream(javax.servlet.ServletOutputStream) IStream(org.eclipse.jetty.http2.IStream) HttpServlet(javax.servlet.http.HttpServlet) FuturePromise(org.eclipse.jetty.util.FuturePromise) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) Callback(org.eclipse.jetty.util.Callback) FutureCallback(org.eclipse.jetty.util.FutureCallback) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) Session(org.eclipse.jetty.http2.api.Session) ISession(org.eclipse.jetty.http2.ISession) Test(org.junit.Test)

Example 5 with ISession

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

the class SimpleFlowControlStrategy method onDataConsumed.

@Override
public void onDataConsumed(ISession session, IStream stream, int length) {
    if (length <= 0)
        return;
    // This is the simple algorithm for flow control.
    // This method is called when a whole flow controlled frame has been consumed.
    // We send a WindowUpdate every time, even if the frame was very small.
    WindowUpdateFrame sessionFrame = new WindowUpdateFrame(0, length);
    session.updateRecvWindow(length);
    if (LOG.isDebugEnabled())
        LOG.debug("Data consumed, increased session recv window by {} for {}", length, session);
    Frame[] streamFrame = Frame.EMPTY_ARRAY;
    if (stream != null) {
        if (stream.isClosed()) {
            if (LOG.isDebugEnabled())
                LOG.debug("Data consumed, ignoring update stream recv window by {} for closed {}", length, stream);
        } else {
            streamFrame = new Frame[1];
            streamFrame[0] = new WindowUpdateFrame(stream.getId(), length);
            stream.updateRecvWindow(length);
            if (LOG.isDebugEnabled())
                LOG.debug("Data consumed, increased stream recv window by {} for {}", length, stream);
        }
    }
    session.frames(stream, Callback.NOOP, sessionFrame, streamFrame);
}
Also used : WindowUpdateFrame(org.eclipse.jetty.http2.frames.WindowUpdateFrame) WindowUpdateFrame(org.eclipse.jetty.http2.frames.WindowUpdateFrame) Frame(org.eclipse.jetty.http2.frames.Frame)

Aggregations

Stream (org.eclipse.jetty.http2.api.Stream)7 ISession (org.eclipse.jetty.http2.ISession)6 ByteBuffer (java.nio.ByteBuffer)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 HttpFields (org.eclipse.jetty.http.HttpFields)5 MetaData (org.eclipse.jetty.http.MetaData)5 Session (org.eclipse.jetty.http2.api.Session)5 ServerSessionListener (org.eclipse.jetty.http2.api.server.ServerSessionListener)5 DataFrame (org.eclipse.jetty.http2.frames.DataFrame)5 HeadersFrame (org.eclipse.jetty.http2.frames.HeadersFrame)5 Callback (org.eclipse.jetty.util.Callback)5 FuturePromise (org.eclipse.jetty.util.FuturePromise)5 Test (org.junit.Test)5 IStream (org.eclipse.jetty.http2.IStream)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 WindowUpdateFrame (org.eclipse.jetty.http2.frames.WindowUpdateFrame)3 FutureCallback (org.eclipse.jetty.util.FutureCallback)3 ServletOutputStream (javax.servlet.ServletOutputStream)2 WriteListener (javax.servlet.WriteListener)2