Search in sources :

Example 1 with HTTP2Session

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

the class FlowControlStrategyTest method testWindowSizeUpdates.

@Test
public void testWindowSizeUpdates() throws Exception {
    final CountDownLatch prefaceLatch = new CountDownLatch(1);
    final CountDownLatch stream1Latch = new CountDownLatch(1);
    final CountDownLatch stream2Latch = new CountDownLatch(1);
    final CountDownLatch settingsLatch = new CountDownLatch(1);
    start(new ServerSessionListener.Adapter() {

        @Override
        public Map<Integer, Integer> onPreface(Session session) {
            HTTP2Session serverSession = (HTTP2Session) session;
            Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverSession.getSendWindow());
            Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverSession.getRecvWindow());
            prefaceLatch.countDown();
            return null;
        }

        @Override
        public void onSettings(Session session, SettingsFrame frame) {
            for (Stream stream : session.getStreams()) {
                HTTP2Stream serverStream = (HTTP2Stream) stream;
                Assert.assertEquals(0, serverStream.getSendWindow());
                Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverStream.getRecvWindow());
            }
            settingsLatch.countDown();
        }

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
            HTTP2Stream serverStream = (HTTP2Stream) stream;
            MetaData.Request request = (MetaData.Request) frame.getMetaData();
            if ("GET".equalsIgnoreCase(request.getMethod())) {
                Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverStream.getSendWindow());
                Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverStream.getRecvWindow());
                stream1Latch.countDown();
            } else {
                Assert.assertEquals(0, serverStream.getSendWindow());
                Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverStream.getRecvWindow());
                stream2Latch.countDown();
            }
            return null;
        }
    });
    HTTP2Session clientSession = (HTTP2Session) newClient(new Session.Listener.Adapter());
    Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientSession.getSendWindow());
    Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientSession.getRecvWindow());
    Assert.assertTrue(prefaceLatch.await(5, TimeUnit.SECONDS));
    MetaData.Request request1 = newRequest("GET", new HttpFields());
    FuturePromise<Stream> promise1 = new FuturePromise<>();
    clientSession.newStream(new HeadersFrame(request1, null, true), promise1, new Stream.Listener.Adapter());
    HTTP2Stream clientStream1 = (HTTP2Stream) promise1.get(5, TimeUnit.SECONDS);
    Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientStream1.getSendWindow());
    Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientStream1.getRecvWindow());
    Assert.assertTrue(stream1Latch.await(5, TimeUnit.SECONDS));
    // Send a SETTINGS frame that changes the window size.
    // This tells the server that its stream send window must be updated,
    // so on the client it's the receive window that must be updated.
    Map<Integer, Integer> settings = new HashMap<>();
    settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, 0);
    SettingsFrame frame = new SettingsFrame(settings, false);
    FutureCallback callback = new FutureCallback();
    clientSession.settings(frame, callback);
    callback.get(5, TimeUnit.SECONDS);
    Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientStream1.getSendWindow());
    Assert.assertEquals(0, clientStream1.getRecvWindow());
    settingsLatch.await(5, TimeUnit.SECONDS);
    // Now create a new stream, it must pick up the new value.
    MetaData.Request request2 = newRequest("POST", new HttpFields());
    FuturePromise<Stream> promise2 = new FuturePromise<>();
    clientSession.newStream(new HeadersFrame(request2, null, true), promise2, new Stream.Listener.Adapter());
    HTTP2Stream clientStream2 = (HTTP2Stream) promise2.get(5, TimeUnit.SECONDS);
    Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientStream2.getSendWindow());
    Assert.assertEquals(0, clientStream2.getRecvWindow());
    Assert.assertTrue(stream2Latch.await(5, TimeUnit.SECONDS));
}
Also used : ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HTTP2Stream(org.eclipse.jetty.http2.HTTP2Stream) HashMap(java.util.HashMap) FuturePromise(org.eclipse.jetty.util.FuturePromise) CountDownLatch(java.util.concurrent.CountDownLatch) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) 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) Map(java.util.Map) HashMap(java.util.HashMap) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) FutureCallback(org.eclipse.jetty.util.FutureCallback) 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 HTTP2Session

use of org.eclipse.jetty.http2.HTTP2Session 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 3 with HTTP2Session

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

the class IdleTimeoutTest method testClientEnforcingStreamIdleTimeout.

@Test
public void testClientEnforcingStreamIdleTimeout() throws Exception {
    final int idleTimeout = 1000;
    start(new HttpServlet() {

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            sleep(2 * idleTimeout);
        }
    });
    Session session = newClient(new Session.Listener.Adapter());
    final CountDownLatch dataLatch = new CountDownLatch(1);
    final CountDownLatch timeoutLatch = new CountDownLatch(1);
    MetaData.Request metaData = newRequest("GET", new HttpFields());
    HeadersFrame requestFrame = new HeadersFrame(metaData, null, true);
    session.newStream(requestFrame, new Promise.Adapter<Stream>() {

        @Override
        public void succeeded(Stream stream) {
            stream.setIdleTimeout(idleTimeout);
        }
    }, new Stream.Listener.Adapter() {

        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback) {
            callback.succeeded();
            dataLatch.countDown();
        }

        @Override
        public boolean onIdleTimeout(Stream stream, Throwable x) {
            Assert.assertThat(x, Matchers.instanceOf(TimeoutException.class));
            timeoutLatch.countDown();
            return true;
        }
    });
    Assert.assertTrue(timeoutLatch.await(5, TimeUnit.SECONDS));
    // We must not receive any DATA frame.
    Assert.assertFalse(dataLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));
    // Stream must be gone.
    Assert.assertTrue(session.getStreams().isEmpty());
    // Session must not be closed, nor disconnected.
    Assert.assertFalse(session.isClosed());
    Assert.assertFalse(((HTTP2Session) session).isDisconnected());
}
Also used : ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Promise(org.eclipse.jetty.util.Promise) FuturePromise(org.eclipse.jetty.util.FuturePromise) Callback(org.eclipse.jetty.util.Callback) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) ServletInputStream(javax.servlet.ServletInputStream) Stream(org.eclipse.jetty.http2.api.Stream) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 4 with HTTP2Session

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

the class StreamCountTest method testServerAllowsOneStreamEnforcedByServer.

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

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
            HTTP2Session session = (HTTP2Session) stream.getSession();
            session.setMaxRemoteStreams(1);
            return new Stream.Listener.Adapter() {

                @Override
                public void onData(Stream stream, DataFrame frame, Callback callback) {
                    if (frame.isEndStream()) {
                        HttpFields fields = new HttpFields();
                        MetaData.Response metaData = new MetaData.Response(HttpVersion.HTTP_2, 200, fields);
                        stream.headers(new HeadersFrame(stream.getId(), metaData, null, true), callback);
                    } else {
                        callback.succeeded();
                    }
                }
            };
        }
    });
    Session session = newClient(new Session.Listener.Adapter());
    HttpFields fields = new HttpFields();
    MetaData.Request metaData = newRequest("GET", fields);
    HeadersFrame frame1 = new HeadersFrame(metaData, null, false);
    FuturePromise<Stream> streamPromise1 = new FuturePromise<>();
    final CountDownLatch responseLatch = new CountDownLatch(1);
    session.newStream(frame1, streamPromise1, new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            if (frame.isEndStream())
                responseLatch.countDown();
        }
    });
    Stream stream1 = streamPromise1.get(5, TimeUnit.SECONDS);
    HeadersFrame frame2 = new HeadersFrame(metaData, null, false);
    FuturePromise<Stream> streamPromise2 = new FuturePromise<>();
    session.newStream(frame2, streamPromise2, new Stream.Listener.Adapter() {

        @Override
        public void onReset(Stream stream, ResetFrame frame) {
            resetLatch.countDown();
        }
    });
    streamPromise2.get(5, TimeUnit.SECONDS);
    Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS));
    stream1.data(new DataFrame(stream1.getId(), BufferUtil.EMPTY_BUFFER, true), Callback.NOOP);
    Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS));
}
Also used : ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) FuturePromise(org.eclipse.jetty.util.FuturePromise) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) Callback(org.eclipse.jetty.util.Callback) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) ResetFrame(org.eclipse.jetty.http2.frames.ResetFrame) 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 5 with HTTP2Session

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

the class AsyncIOServletTest method testAsyncReadEarlyEOF.

@Test
public void testAsyncReadEarlyEOF() throws Exception {
    // SSLEngine receives the close alert from the client, and when
    // the server passes the response to encrypt and write, SSLEngine
    // only generates the close alert back, without encrypting the
    // response, so we need to skip the transports over TLS.
    Assume.assumeThat(transport, Matchers.not(Matchers.isOneOf(Transport.HTTPS, Transport.H2)));
    String content = "jetty";
    int responseCode = HttpStatus.NO_CONTENT_204;
    CountDownLatch readLatch = new CountDownLatch(content.length());
    CountDownLatch errorLatch = new CountDownLatch(1);
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            AsyncContext asyncContext = request.startAsync();
            ServletInputStream input = request.getInputStream();
            input.setReadListener(new ReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    while (input.isReady() && !input.isFinished()) {
                        int read = input.read();
                        // System.err.printf("%x%n", read);
                        readLatch.countDown();
                    }
                }

                @Override
                public void onAllDataRead() throws IOException {
                }

                @Override
                public void onError(Throwable x) {
                    response.setStatus(responseCode);
                    asyncContext.complete();
                    errorLatch.countDown();
                }
            });
        }
    });
    CountDownLatch responseLatch = new CountDownLatch(1);
    DeferredContentProvider contentProvider = new DeferredContentProvider();
    contentProvider.offer(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)));
    org.eclipse.jetty.client.api.Request request = client.newRequest(newURI()).method(HttpMethod.POST).path(servletPath).content(contentProvider).onResponseSuccess(response -> responseLatch.countDown());
    Destination destination = client.getDestination(getScheme(), "localhost", connector.getLocalPort());
    FuturePromise<org.eclipse.jetty.client.api.Connection> promise = new FuturePromise<>();
    destination.newConnection(promise);
    org.eclipse.jetty.client.api.Connection connection = promise.get(5, TimeUnit.SECONDS);
    CountDownLatch clientLatch = new CountDownLatch(1);
    connection.send(request, result -> {
        assertThat(result.getResponse().getStatus(), Matchers.equalTo(responseCode));
        clientLatch.countDown();
    });
    assertTrue(readLatch.await(5, TimeUnit.SECONDS));
    switch(transport) {
        case HTTP:
        case HTTPS:
            ((HttpConnectionOverHTTP) connection).getEndPoint().shutdownOutput();
            break;
        case H2C:
        case H2:
            // In case of HTTP/2, we not only send the request, but also the preface and
            // SETTINGS frames. SETTINGS frame need to be replied, so we want to wait to
            // write the reply before shutting output down, so that the test does not fail.
            Thread.sleep(1000);
            Session session = ((HttpConnectionOverHTTP2) connection).getSession();
            ((HTTP2Session) session).getEndPoint().shutdownOutput();
            break;
        default:
            Assert.fail();
    }
    // Wait for the response to arrive before finishing the request.
    assertTrue(responseLatch.await(5, TimeUnit.SECONDS));
    contentProvider.close();
    assertTrue(errorLatch.await(5, TimeUnit.SECONDS));
    assertTrue(clientLatch.await(5, TimeUnit.SECONDS));
}
Also used : Destination(org.eclipse.jetty.client.api.Destination) AsyncContext(javax.servlet.AsyncContext) HttpConnectionOverHTTP2(org.eclipse.jetty.http2.client.http.HttpConnectionOverHTTP2) Matchers.containsString(org.hamcrest.Matchers.containsString) ReadListener(javax.servlet.ReadListener) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) HttpServlet(javax.servlet.http.HttpServlet) FuturePromise(org.eclipse.jetty.util.FuturePromise) Connection(org.eclipse.jetty.io.Connection) HttpServletResponse(javax.servlet.http.HttpServletResponse) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Aggregations

CountDownLatch (java.util.concurrent.CountDownLatch)13 HTTP2Session (org.eclipse.jetty.http2.HTTP2Session)13 Session (org.eclipse.jetty.http2.api.Session)13 Test (org.junit.Test)13 HttpFields (org.eclipse.jetty.http.HttpFields)12 ServerSessionListener (org.eclipse.jetty.http2.api.server.ServerSessionListener)12 HeadersFrame (org.eclipse.jetty.http2.frames.HeadersFrame)12 MetaData (org.eclipse.jetty.http.MetaData)11 Stream (org.eclipse.jetty.http2.api.Stream)11 FuturePromise (org.eclipse.jetty.util.FuturePromise)7 ByteBuffer (java.nio.ByteBuffer)6 ByteBufferPool (org.eclipse.jetty.io.ByteBufferPool)6 OutputStream (java.io.OutputStream)5 HashMap (java.util.HashMap)5 DataFrame (org.eclipse.jetty.http2.frames.DataFrame)5 SettingsFrame (org.eclipse.jetty.http2.frames.SettingsFrame)5 Callback (org.eclipse.jetty.util.Callback)5 Socket (java.net.Socket)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 HTTP2Stream (org.eclipse.jetty.http2.HTTP2Stream)4