This is an automated email from the ASF dual-hosted git repository.

markt-asf pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tomcat.git


The following commit(s) were added to refs/heads/main by this push:
     new 6fb36ad28f Remove HTTP/2 streams that are reset from the queue of 
streams waiting to be processed
6fb36ad28f is described below

commit 6fb36ad28fd266a551c0c4c761b388c73da5d513
Author: Mark Thomas <[email protected]>
AuthorDate: Fri Nov 27 12:13:39 2026 +0000

    Remove HTTP/2 streams that are reset from the queue of streams waiting to 
be processed
    
    Streams waiting for an execution slot are discarded when they are reset or
    closed. Reset streams that still have queued work continue to count towards
    the limit on concurrent streams until that work has been processed.
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 .../apache/coyote/http2/Http2UpgradeHandler.java   | 125 +++++-
 java/org/apache/coyote/http2/Stream.java           |   2 +
 java/org/apache/coyote/http2/StreamProcessor.java  |   5 +
 java/org/apache/coyote/http2/StreamRunnable.java   |  15 +-
 .../coyote/http2/TestHttp2QueuedStreams.java       | 491 +++++++++++++++++++++
 webapps/docs/changelog.xml                         |   7 +
 6 files changed, 640 insertions(+), 5 deletions(-)

diff --git a/java/org/apache/coyote/http2/Http2UpgradeHandler.java 
b/java/org/apache/coyote/http2/Http2UpgradeHandler.java
index 0c044c4baf..e03c87b9bb 100644
--- a/java/org/apache/coyote/http2/Http2UpgradeHandler.java
+++ b/java/org/apache/coyote/http2/Http2UpgradeHandler.java
@@ -20,12 +20,16 @@ import java.io.EOFException;
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
 import java.util.Base64;
 import java.util.Comparator;
 import java.util.HashSet;
 import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
 import java.util.Queue;
 import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentLinkedQueue;
 import java.util.concurrent.ConcurrentNavigableMap;
 import java.util.concurrent.ConcurrentSkipListMap;
@@ -189,6 +193,19 @@ class Http2UpgradeHandler extends AbstractStream 
implements InternalHttpUpgradeH
     // Stream concurrency control
     private AtomicInteger streamConcurrency = null;
     private Queue<StreamRunnable> queuedRunnable = null;
+    /*
+     * The runnables in queuedRunnable indexed by stream ID. The lists are 
only ever modified inside the atomic compute
+     * methods of the map so no further synchronization is required. This 
allows the runnables for a stream to be found
+     * without scanning the queue.
+     */
+    private Map<Integer,List<StreamRunnable>> queuedRunnableByStream = null;
+    /*
+     * Streams that are no longer active (so no longer count towards the limit 
on the number of active streams) but
+     * still have at least one runnable waiting in queuedRunnable. Modified 
only inside the atomic compute methods of
+     * queuedRunnableByStream. These streams still consume resources so they 
are included when enforcing the limit on
+     * the number of concurrent streams.
+     */
+    private final Set<Integer> retainedQueuedStreams = 
ConcurrentHashMap.newKeySet();
 
     // Track 'overhead' frames vs 'request/response' frames
     private final AtomicLong overheadCount;
@@ -270,6 +287,7 @@ class Http2UpgradeHandler extends AbstractStream implements 
InternalHttpUpgradeH
         if (protocol.getMaxConcurrentStreamExecution() < 
localSettings.getMaxConcurrentStreams()) {
             streamConcurrency = new AtomicInteger(0);
             queuedRunnable = new ConcurrentLinkedQueue<>();
+            queuedRunnableByStream = new ConcurrentHashMap<>();
         }
 
         parser = getParser(connectionId);
@@ -392,7 +410,7 @@ class Http2UpgradeHandler extends AbstractStream implements 
InternalHttpUpgradeH
     protected void processStreamOnContainerThread(Stream stream) {
         StreamProcessor streamProcessor = new StreamProcessor(this, stream, 
adapter, socketWrapper);
         streamProcessor.setSslSupport(sslSupport);
-        processStreamOnContainerThread(streamProcessor, SocketEvent.OPEN_READ);
+        processStreamOnContainerThread(streamProcessor, SocketEvent.OPEN_READ, 
true);
     }
 
 
@@ -409,7 +427,12 @@ class Http2UpgradeHandler extends AbstractStream 
implements InternalHttpUpgradeH
 
 
     void processStreamOnContainerThread(StreamProcessor streamProcessor, 
SocketEvent event) {
-        StreamRunnable streamRunnable = new StreamRunnable(streamProcessor, 
event);
+        processStreamOnContainerThread(streamProcessor, event, false);
+    }
+
+
+    void processStreamOnContainerThread(StreamProcessor streamProcessor, 
SocketEvent event, boolean initial) {
+        StreamRunnable streamRunnable = new StreamRunnable(streamProcessor, 
event, initial);
         if (streamConcurrency == null) {
             socketWrapper.execute(streamRunnable);
         } else {
@@ -417,12 +440,90 @@ class Http2UpgradeHandler extends AbstractStream 
implements InternalHttpUpgradeH
                 increaseStreamConcurrency();
                 socketWrapper.execute(streamRunnable);
             } else {
-                queuedRunnable.offer(streamRunnable);
+                queueStreamRunnable(streamRunnable);
             }
         }
     }
 
 
+    private void queueStreamRunnable(StreamRunnable streamRunnable) {
+        Stream stream = streamRunnable.getProcessor().getStream();
+        queuedRunnableByStream.compute(Integer.valueOf(stream.getIdAsInt()), 
(id, runnables) -> {
+            if (runnables == null) {
+                runnables = new ArrayList<>(2);
+            }
+            runnables.add(streamRunnable);
+            if (!stream.isActive()) {
+                // Reset or closed before this runnable was queued
+                retainedQueuedStreams.add(id);
+            }
+            return runnables;
+        });
+        queuedRunnable.offer(streamRunnable);
+    }
+
+
+    /**
+     * Discards a stream that is waiting for an execution slot if that stream 
can no longer be processed because it has
+     * been reset or closed due to an error. A reset stream frees its slot in 
the limit on the number of active streams
+     * so, if the stream were left in the queue, the number of streams in the 
queue (and the memory they use) would not
+     * be limited. Streams that have started processing clean-up for 
themselves so are not affected but, if they still
+     * have work in the queue, they continue to count towards the limit on the 
number of concurrent streams until that
+     * work has been processed.
+     *
+     * @param stream the stream that has been reset or closed
+     */
+    void discardQueuedStream(Stream stream) {
+        if (queuedRunnableByStream == null) {
+            return;
+        }
+        StreamRunnable[] discarded = new StreamRunnable[1];
+        
queuedRunnableByStream.computeIfPresent(Integer.valueOf(stream.getIdAsInt()), 
(id, runnables) -> {
+            StreamRunnable initial = null;
+            for (StreamRunnable streamRunnable : runnables) {
+                if (streamRunnable.isInitial()) {
+                    initial = streamRunnable;
+                    break;
+                }
+            }
+            if (initial == null || !queuedRunnable.remove(initial)) {
+                // Processing has started (or is about to). The processor will 
perform the clean-up.
+                retainedQueuedStreams.add(id);
+                return runnables;
+            }
+            // Processing of this stream will never start so no event for it 
can be processed
+            for (StreamRunnable streamRunnable : runnables) {
+                queuedRunnable.remove(streamRunnable);
+            }
+            // Any event queued for this stream (e.g. by the reset) was only 
retained until it was processed
+            retainedQueuedStreams.remove(id);
+            discarded[0] = initial;
+            return null;
+        });
+
+        if (discarded[0] != null) {
+            // Perform the clean-up that would have been performed by the 
processor
+            StreamProcessor streamProcessor = discarded[0].getProcessor();
+            stream.close(null);
+            streamProcessor.recycle();
+            stream.recycle(false);
+        }
+    }
+
+
+    private void removeFromQueueIndex(StreamRunnable streamRunnable) {
+        
queuedRunnableByStream.computeIfPresent(Integer.valueOf(streamRunnable.getProcessor().getStream().getIdAsInt()),
+                (id, runnables) -> {
+                    runnables.remove(streamRunnable);
+                    if (runnables.isEmpty()) {
+                        retainedQueuedStreams.remove(id);
+                        return null;
+                    }
+                    return runnables;
+                });
+    }
+
+
     @Override
     public void setSocketWrapper(SocketWrapperBase<?> wrapper) {
         // NO-OP. It is passed via the constructor
@@ -695,6 +796,7 @@ class Http2UpgradeHandler extends AbstractStream implements 
InternalHttpUpgradeH
         if (getStreamConcurrency() < 
protocol.getMaxConcurrentStreamExecution()) {
             StreamRunnable streamRunnable = queuedRunnable.poll();
             if (streamRunnable != null) {
+                removeFromQueueIndex(streamRunnable);
                 increaseStreamConcurrency();
                 socketWrapper.execute(streamRunnable);
             }
@@ -1665,6 +1767,18 @@ class Http2UpgradeHandler extends AbstractStream 
implements InternalHttpUpgradeH
                 ((Stream) stream).receiveReset(Http2Error.CANCEL.getCode());
             }
         }
+        /*
+         * Streams that are waiting to start processing never will so release 
them. Events queued for streams that have
+         * started processing (e.g. the error notification queued by the reset 
above) must still be processed as that is
+         * what cleans up the processor so those remain in the queue and are 
executed as slots become available.
+         */
+        if (queuedRunnable != null) {
+            for (StreamRunnable streamRunnable : queuedRunnable) {
+                if (streamRunnable.isInitial()) {
+                    
discardQueuedStream(streamRunnable.getProcessor().getStream());
+                }
+            }
+        }
         try {
             socketWrapper.close();
         } catch (Exception e) {
@@ -2009,7 +2123,8 @@ class Http2UpgradeHandler extends AbstractStream 
implements InternalHttpUpgradeH
             boolean processStream = false;
             if (stream.isActive()) {
                 if (stream.receivedEndOfHeaders()) {
-                    if (localSettings.getMaxConcurrentStreams() < 
activeRemoteStreamCount.get()) {
+                    if (localSettings.getMaxConcurrentStreams() < 
activeRemoteStreamCount.get() +
+                            retainedQueuedStreams.size()) {
                         decrementActiveRemoteStreamCount(stream);
                         // Ignoring maxConcurrentStreams increases the 
overhead count
                         increaseOverheadCount(FrameType.HEADERS);
@@ -2073,6 +2188,8 @@ class Http2UpgradeHandler extends AbstractStream 
implements InternalHttpUpgradeH
             if (active) {
                 decrementActiveRemoteStreamCount(stream);
             }
+            // If processing of this stream has not started, it never will
+            discardQueuedStream(stream);
         }
     }
 
diff --git a/java/org/apache/coyote/http2/Stream.java 
b/java/org/apache/coyote/http2/Stream.java
index 2c296bd119..f2bf048676 100644
--- a/java/org/apache/coyote/http2/Stream.java
+++ b/java/org/apache/coyote/http2/Stream.java
@@ -980,6 +980,8 @@ class Stream extends AbstractNonZeroStream implements 
HeaderEmitter {
             }
         }
         replace();
+        // If processing of this stream has not started, it never will
+        handler.discardQueuedStream(this);
     }
 
 
diff --git a/java/org/apache/coyote/http2/StreamProcessor.java 
b/java/org/apache/coyote/http2/StreamProcessor.java
index 3841e8cabf..ba894788fb 100644
--- a/java/org/apache/coyote/http2/StreamProcessor.java
+++ b/java/org/apache/coyote/http2/StreamProcessor.java
@@ -471,6 +471,11 @@ class StreamProcessor extends AbstractProcessor implements 
NonPipeliningProcesso
     }
 
 
+    Stream getStream() {
+        return stream;
+    }
+
+
     @Override
     public final void recycle() {
         // StreamProcessor instances are not re-used.
diff --git a/java/org/apache/coyote/http2/StreamRunnable.java 
b/java/org/apache/coyote/http2/StreamRunnable.java
index 51967d18d5..b4bda2e9cc 100644
--- a/java/org/apache/coyote/http2/StreamRunnable.java
+++ b/java/org/apache/coyote/http2/StreamRunnable.java
@@ -22,11 +22,24 @@ class StreamRunnable implements Runnable {
 
     private final StreamProcessor processor;
     private final SocketEvent event;
+    // Is this the runnable that starts processing of the stream?
+    private final boolean initial;
 
 
-    StreamRunnable(StreamProcessor processor, SocketEvent event) {
+    StreamRunnable(StreamProcessor processor, SocketEvent event, boolean 
initial) {
         this.processor = processor;
         this.event = event;
+        this.initial = initial;
+    }
+
+
+    StreamProcessor getProcessor() {
+        return processor;
+    }
+
+
+    boolean isInitial() {
+        return initial;
     }
 
 
diff --git a/test/org/apache/coyote/http2/TestHttp2QueuedStreams.java 
b/test/org/apache/coyote/http2/TestHttp2QueuedStreams.java
new file mode 100644
index 0000000000..793f01dd1d
--- /dev/null
+++ b/test/org/apache/coyote/http2/TestHttp2QueuedStreams.java
@@ -0,0 +1,491 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.coyote.http2;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.nio.ByteBuffer;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import jakarta.servlet.AsyncContext;
+import jakarta.servlet.AsyncEvent;
+import jakarta.servlet.AsyncListener;
+import jakarta.servlet.http.HttpServlet;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.catalina.Context;
+import org.apache.catalina.connector.Connector;
+import org.apache.catalina.startup.Tomcat;
+import org.apache.coyote.Adapter;
+import org.apache.coyote.Request;
+import org.apache.coyote.http11.AbstractHttp11Protocol;
+import org.apache.coyote.http11.upgrade.InternalHttpUpgradeHandler;
+import org.apache.tomcat.util.net.SocketWrapperBase;
+
+/*
+ * The number of streams that can be executing at the same time is limited for 
each connection. If a stream has to wait
+ * for an execution slot and the client then resets it, the reset must not 
leave the stream (and the memory it uses)
+ * waiting in the queue.
+ */
+public class TestHttp2QueuedStreams extends Http2TestBase {
+
+    private static final int EXECUTION_LIMIT = 20;
+
+    private static final AtomicInteger blocked = new AtomicInteger();
+    private static final AtomicInteger counted = new AtomicInteger();
+    private static final AtomicInteger asyncStarted = new AtomicInteger();
+    private static final AtomicInteger asyncErrors = new AtomicInteger();
+
+    private volatile Http2UpgradeHandler handler;
+
+
+    @Test
+    public void testResetStreamsAreRemovedFromQueue() throws Exception {
+        connectAndFillExecutionSlots();
+
+        int streamId = 3 + 2 * EXECUTION_LIMIT;
+        int streams = 50;
+        for (int i = 0; i < streams; i++) {
+            sendPostRequestWithBody(streamId);
+            sendRst(streamId, Http2Error.CANCEL.getCode());
+            streamId += 2;
+        }
+
+        // The slots are still blocked so these streams could not have been 
processed
+        waitForQueuedStreams(0);
+        // Discarded streams must not continue to count towards the limit on 
concurrent streams
+        waitForRetainedStreams(0);
+
+        // Let the blocked requests complete
+        sendSettings(0, false, new SettingValue(4, 65535));
+        long end = System.nanoTime() + 10_000_000_000L;
+        while (blocked.get() > 0 && System.nanoTime() < end) {
+            Thread.sleep(50);
+        }
+        Assert.assertEquals(0, blocked.get());
+        // The streams were reset before processing started so the application 
should not have been called
+        Thread.sleep(500);
+        Assert.assertEquals(0, counted.get());
+    }
+
+
+    /*
+     * Streams that are waiting for an execution slot and that are not reset 
must still be processed once a slot is
+     * available.
+     */
+    @Test
+    public void testQueuedStreamsAreProcessed() throws Exception {
+        connectAndFillExecutionSlots();
+
+        int streamId = 3 + 2 * EXECUTION_LIMIT;
+        int streams = 10;
+        for (int i = 0; i < streams; i++) {
+            sendPostRequestWithBody(streamId);
+            streamId += 2;
+        }
+        waitForQueuedStreams(streams);
+
+        sendSettings(0, false, new SettingValue(4, 65535));
+        long end = System.nanoTime() + 10_000_000_000L;
+        while (counted.get() < streams && System.nanoTime() < end) {
+            Thread.sleep(50);
+        }
+        Assert.assertEquals(streams, counted.get());
+        waitForQueuedStreams(0);
+    }
+
+
+    /*
+     * A stream that has started processing and is then reset may have work 
(the error notification) waiting in the
+     * queue. The reset frees the stream's slot in the limit on the number of 
active streams but the stream must still
+     * count towards the limit on concurrent streams until that work has been 
processed.
+     */
+    @Test
+    public void testResetStreamWithQueuedErrorIsRetained() throws Exception {
+        connect();
+
+        // Start an asynchronous request. Processing of the stream starts but 
the request does not complete.
+        sendGetRequest(3, "/async");
+        long end = System.nanoTime() + 10_000_000_000L;
+        while (asyncStarted.get() < 1 && System.nanoTime() < end) {
+            Thread.sleep(50);
+        }
+        Assert.assertEquals(1, asyncStarted.get());
+
+        fillExecutionSlots(5);
+
+        // Reset the asynchronous stream. The error notification has to wait 
for an execution slot.
+        sendRst(3, Http2Error.CANCEL.getCode());
+        waitForQueuedStreams(1);
+        waitForRetainedStreams(1);
+
+        // Once the slots are available the notification is processed and the 
stream is no longer retained
+        sendSettings(0, false, new SettingValue(4, 65535));
+        end = System.nanoTime() + 10_000_000_000L;
+        while (blocked.get() > 0 && System.nanoTime() < end) {
+            Thread.sleep(50);
+        }
+        Assert.assertEquals(0, blocked.get());
+        waitForQueuedStreams(0);
+        waitForRetainedStreams(0);
+    }
+
+
+    /*
+     * Any close of a stream that is waiting for an execution slot must remove 
it from the queue, not just the paths
+     * that are currently used for resets and stream errors.
+     */
+    @Test
+    public void testCloseRemovesQueuedStream() throws Exception {
+        connectAndFillExecutionSlots();
+
+        int firstStreamId = 3 + 2 * EXECUTION_LIMIT;
+        int streams = 5;
+        for (int i = 0; i < streams; i++) {
+            sendPostRequestWithBody(firstStreamId + 2 * i);
+        }
+        waitForQueuedStreams(streams);
+
+        int streamId = firstStreamId + 2;
+        handler.getStream(streamId).close(new StreamException("Test", 
Http2Error.CANCEL, streamId));
+
+        waitForQueuedStreams(streams - 1);
+        waitForRetainedStreams(0);
+
+        // The remaining streams are still processed once slots are available
+        sendSettings(0, false, new SettingValue(4, 65535));
+        long end = System.nanoTime() + 10_000_000_000L;
+        while (counted.get() < streams - 1 && System.nanoTime() < end) {
+            Thread.sleep(50);
+        }
+        Assert.assertEquals(streams - 1, counted.get());
+        waitForQueuedStreams(0);
+    }
+
+
+    /*
+     * Closing a stream that has started processing must not discard the work 
it still has queued. That work is what
+     * cleans up the processor.
+     */
+    @Test
+    public void testCloseKeepsQueuedWorkOfStartedStream() throws Exception {
+        connect();
+
+        sendGetRequest(3, "/async");
+        long end = System.nanoTime() + 10_000_000_000L;
+        while (asyncStarted.get() < 1 && System.nanoTime() < end) {
+            Thread.sleep(50);
+        }
+        Assert.assertEquals(1, asyncStarted.get());
+
+        fillExecutionSlots(5);
+
+        sendRst(3, Http2Error.CANCEL.getCode());
+        waitForQueuedStreams(1);
+        waitForRetainedStreams(1);
+
+        handler.getStream(3).close(null);
+
+        // Nothing is discarded
+        waitForQueuedStreams(1);
+        waitForRetainedStreams(1);
+
+        sendSettings(0, false, new SettingValue(4, 65535));
+        end = System.nanoTime() + 10_000_000_000L;
+        while ((blocked.get() > 0 || asyncErrors.get() < 1) && 
System.nanoTime() < end) {
+            Thread.sleep(50);
+        }
+        Assert.assertEquals("onError() calls", 1, asyncErrors.get());
+        waitForQueuedStreams(0);
+        waitForRetainedStreams(0);
+    }
+
+
+    /*
+     * Closing the connection must not discard the error notifications that 
started asynchronous requests are waiting
+     * for since processing them is what cleans up the processor.
+     */
+    @Test
+    public void testCloseProcessesQueuedErrorNotifications() throws Exception {
+        connect();
+
+        sendGetRequest(3, "/async");
+        long end = System.nanoTime() + 10_000_000_000L;
+        while (asyncStarted.get() < 1 && System.nanoTime() < end) {
+            Thread.sleep(50);
+        }
+        Assert.assertEquals(1, asyncStarted.get());
+
+        fillExecutionSlots(5);
+
+        // The close resets every stream which queues the error notification 
for the asynchronous request
+        handler.close();
+
+        // Closing releases the blocked requests which frees the execution 
slots
+        end = System.nanoTime() + 10_000_000_000L;
+        while ((blocked.get() > 0 || asyncErrors.get() < 1) && 
System.nanoTime() < end) {
+            Thread.sleep(50);
+        }
+        Assert.assertEquals(0, blocked.get());
+        Assert.assertEquals("onError() calls", 1, asyncErrors.get());
+        waitForQueuedStreams(0);
+        waitForRetainedStreams(0);
+    }
+
+
+    /*
+     * Nothing in the queue will be processed once the connection has closed 
so it must be released.
+     */
+    @Test
+    public void testQueueIsClearedOnClose() throws Exception {
+        connectAndFillExecutionSlots();
+
+        int streamId = 3 + 2 * EXECUTION_LIMIT;
+        int streams = 10;
+        for (int i = 0; i < streams; i++) {
+            sendPostRequestWithBody(streamId);
+            streamId += 2;
+        }
+        waitForQueuedStreams(streams);
+
+        handler.close();
+
+        waitForQueuedStreams(0);
+    }
+
+
+    private void connectAndFillExecutionSlots() throws Exception {
+        connect();
+        fillExecutionSlots(3);
+    }
+
+
+    private void connect() throws Exception {
+        blocked.set(0);
+        counted.set(0);
+        asyncStarted.set(0);
+        asyncErrors.set(0);
+
+        enableHttp2WithHandlerCapture();
+        configureAndStartWebApplication();
+        openClientConnection(false);
+        doHttpUpgrade();
+        sendClientPreface();
+        validateHttp2InitialResponse(200);
+    }
+
+
+    private void fillExecutionSlots(int firstStreamId) throws Exception {
+        // A client window size of zero blocks the responses
+        sendSettings(0, false, new SettingValue(4, 0));
+        int streamId = firstStreamId;
+        for (int i = 0; i < EXECUTION_LIMIT; i++) {
+            sendGetRequest(streamId, "/block");
+            streamId += 2;
+        }
+        long end = System.nanoTime() + 10_000_000_000L;
+        while (blocked.get() < EXECUTION_LIMIT && System.nanoTime() < end) {
+            Thread.sleep(50);
+        }
+        Assert.assertEquals(EXECUTION_LIMIT, blocked.get());
+    }
+
+
+    private void sendGetRequest(int streamId, String path) throws IOException {
+        byte[] frameHeader = new byte[9];
+        ByteBuffer headersPayload = ByteBuffer.allocate(128);
+        buildGetRequest(frameHeader, headersPayload, null, streamId, path);
+        writeFrame(frameHeader, headersPayload);
+    }
+
+
+    /*
+     * Send the headers and body (as two DATA frames that are each large 
enough not to be treated as overhead) of a
+     * request to a servlet that counts the number of requests it processes.
+     */
+    private void sendPostRequestWithBody(int streamId) throws IOException {
+        byte[] headersFrameHeader = new byte[9];
+        ByteBuffer headersPayload = ByteBuffer.allocate(128);
+        byte[] dataFrameHeader = new byte[9];
+        ByteBuffer dataPayload = ByteBuffer.allocate(128);
+        buildPostRequest(headersFrameHeader, headersPayload, false, null, -1, 
"/count", dataFrameHeader, dataPayload,
+                null, false, streamId);
+        writeFrame(headersFrameHeader, headersPayload);
+        sendData(streamId, new byte[1024]);
+        sendData(streamId, new byte[1024]);
+    }
+
+
+    private void waitForRetainedStreams(int expected) throws Exception {
+        Field retainedField = 
Http2UpgradeHandler.class.getDeclaredField("retainedQueuedStreams");
+        retainedField.setAccessible(true);
+
+        int retained = -1;
+        long end = System.nanoTime() + 5_000_000_000L;
+        while (System.nanoTime() < end) {
+            retained = ((Set<?>) retainedField.get(handler)).size();
+            if (retained == expected) {
+                return;
+            }
+            Thread.sleep(50);
+        }
+        Assert.assertEquals("retained streams", expected, retained);
+    }
+
+
+    private void waitForQueuedStreams(int expected) throws Exception {
+        Field queueField = 
Http2UpgradeHandler.class.getDeclaredField("queuedRunnable");
+        queueField.setAccessible(true);
+        Field indexField = 
Http2UpgradeHandler.class.getDeclaredField("queuedRunnableByStream");
+        indexField.setAccessible(true);
+
+        int queued = -1;
+        int count = -1;
+        long end = System.nanoTime() + 5_000_000_000L;
+        while (System.nanoTime() < end) {
+            queued = ((Queue<?>) queueField.get(handler)).size();
+            count = ((Map<?,?>) indexField.get(handler)).size();
+            if (queued == expected && count == expected) {
+                return;
+            }
+            Thread.sleep(50);
+        }
+        Assert.assertEquals("queued runnables", expected, queued);
+        Assert.assertEquals("queued streams", expected, count);
+    }
+
+
+    private void enableHttp2WithHandlerCapture() {
+        Tomcat tomcat = getTomcatInstance();
+        Connector connector = tomcat.getConnector();
+        Assert.assertTrue(connector.setProperty("useAsyncIO", 
Boolean.toString(useAsyncIO)));
+        http2Protocol = new Http2Protocol() {
+            @Override
+            public String getHttpUpgradeName(boolean isSSLEnabled) {
+                return "h2c";
+            }
+
+            @Override
+            public InternalHttpUpgradeHandler 
getInternalUpgradeHandler(SocketWrapperBase<?> socketWrapper,
+                    Adapter adapter, Request coyoteRequest) {
+                InternalHttpUpgradeHandler result =
+                        super.getInternalUpgradeHandler(socketWrapper, 
adapter, coyoteRequest);
+                handler = (Http2UpgradeHandler) result;
+                return result;
+            }
+        };
+        // Long timeouts so the blocked streams are not timed out
+        http2Protocol.setReadTimeout(120000);
+        http2Protocol.setWriteTimeout(120000);
+        http2Protocol.setKeepAliveTimeout(300000);
+        http2Protocol.setStreamReadTimeout(120000);
+        http2Protocol.setStreamWriteTimeout(120000);
+        http2Protocol.setMaxConcurrentStreams(200);
+        http2Protocol.setMaxConcurrentStreamExecution(EXECUTION_LIMIT);
+        http2Protocol.setHttp11Protocol((AbstractHttp11Protocol<?>) 
connector.getProtocolHandler());
+        connector.addUpgradeProtocol(http2Protocol);
+    }
+
+
+    @Override
+    protected void configureAndStartWebApplication() throws 
org.apache.catalina.LifecycleException {
+        Tomcat tomcat = getTomcatInstance();
+
+        Context ctxt = getProgrammaticRootContext();
+        Tomcat.addServlet(ctxt, "simple", new SimpleServlet());
+        ctxt.addServletMapping("/simple", "simple");
+        Tomcat.addServlet(ctxt, "block", new BlockServlet());
+        ctxt.addServletMapping("/block", "block");
+        Tomcat.addServlet(ctxt, "async", new 
AsyncServlet()).setAsyncSupported(true);
+        ctxt.addServletMapping("/async", "async");
+        Tomcat.addServlet(ctxt, "count", new CountServlet());
+        ctxt.addServletMapping("/count", "count");
+
+        tomcat.start();
+    }
+
+
+    private static class BlockServlet extends HttpServlet {
+
+        private static final long serialVersionUID = 1L;
+
+        @Override
+        protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws IOException {
+            blocked.incrementAndGet();
+            try {
+                resp.setContentType("application/octet-stream");
+                resp.getOutputStream().write(new byte[100]);
+                // Blocks until the client provides a flow control window
+                resp.flushBuffer();
+            } finally {
+                blocked.decrementAndGet();
+            }
+        }
+    }
+
+
+    private static class AsyncServlet extends HttpServlet {
+
+        private static final long serialVersionUID = 1L;
+
+        @Override
+        protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
{
+            // Never completed by the application. Only the container (after 
the client reset) ends it.
+            AsyncContext asyncContext = req.startAsync();
+            asyncContext.setTimeout(120000);
+            asyncContext.addListener(new AsyncListener() {
+                @Override
+                public void onComplete(AsyncEvent event) {
+                }
+
+                @Override
+                public void onTimeout(AsyncEvent event) {
+                }
+
+                @Override
+                public void onError(AsyncEvent event) {
+                    asyncErrors.incrementAndGet();
+                }
+
+                @Override
+                public void onStartAsync(AsyncEvent event) {
+                }
+            });
+            asyncStarted.incrementAndGet();
+        }
+    }
+
+
+    private static class CountServlet extends HttpServlet {
+
+        private static final long serialVersionUID = 1L;
+
+        @Override
+        protected void doPost(HttpServletRequest req, HttpServletResponse 
resp) throws IOException {
+            counted.incrementAndGet();
+            resp.setContentType("text/plain");
+            resp.getWriter().print("OK");
+        }
+    }
+}
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index 372ecab8ab..0908deb69d 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -508,6 +508,13 @@
         notification for the request is only dispatched once, even if the reset
         is processed more than once. (markt)
       </fix>
+      <fix>
+        Remove an HTTP/2 stream that is waiting for an execution slot from the
+        queue of streams waiting to be processed when the stream is reset or
+        closed due to an error. A stream that has been reset but still has work
+        waiting to be processed continues to count towards the limit on the
+        number of concurrent streams until that work has been processed. 
(markt)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="Jasper">


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to