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

commit e81820fb3a6a3e16a74f832e5810216c80cf5910
Author: Mark Thomas <[email protected]>
AuthorDate: Wed Nov 25 19:20:09 2026 +0000

    Complete the request if AsyncContext.dispatch() fails on a non-container 
thread
    
    The path used by AsyncContext.dispatch() is derived by the container so, if
    it can't be used, the application can't be expected to recover. If the 
caller
    is the container thread processing the request, the exception propagates and
    is handled in the usual way. If it is any other thread, nothing handled the
    failure and the request remained in the async state until the async timeout
    expired (which might be never).
    
    Dispatch to a container thread, as for a normal dispatch, but rather than
    dispatching the request, throw the exception on the container thread. The
    failure is then handled in the same way as any other failure of an
    asynchronous dispatch: the error page is generated, onError() is called and
    the request is completed.
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 .../org/apache/catalina/core/AsyncContextImpl.java |  44 +++-
 .../apache/catalina/core/TestAsyncContextImpl.java | 286 +++++++++++++++++++++
 webapps/docs/changelog.xml                         |   7 +
 3 files changed, 336 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/catalina/core/AsyncContextImpl.java 
b/java/org/apache/catalina/core/AsyncContextImpl.java
index c0b8a45b8d..b55d75d13d 100644
--- a/java/org/apache/catalina/core/AsyncContextImpl.java
+++ b/java/org/apache/catalina/core/AsyncContextImpl.java
@@ -223,7 +223,13 @@ public class AsyncContextImpl implements AsyncContext, 
AsyncContextCallback {
         // Calls check() so local copies are validated
         HttpServletRequest hsr = getRequest() instanceof HttpServletRequest h 
? h : request;
         String path = hsr.getRequestURI();
-        String cpath = 
RequestUtil.getContextPathEncoded(request.getConnector(), hsr);
+        String cpath;
+        try {
+            cpath = RequestUtil.getContextPathEncoded(request.getConnector(), 
hsr);
+        } catch (IllegalStateException ise) {
+            failDispatch(ise);
+            throw ise;
+        }
         if (cpath.length() > 1) {
             path = path.substring(cpath.length());
         }
@@ -235,11 +241,47 @@ public class AsyncContextImpl implements AsyncContext, 
AsyncContextCallback {
         try {
             uriEncoded.set(Boolean.TRUE);
             dispatch(path);
+        } catch (UnsupportedOperationException | IllegalArgumentException e) {
+            failDispatch(e);
+            throw e;
         } finally {
             uriEncoded.set(Boolean.FALSE);
         }
     }
 
+
+    /**
+     * Called when {@link #dispatch()} fails because the dispatch path, that 
was derived by the container, could not be
+     * used. The application can't be expected to recover from this.
+     * <p>
+     * If the caller is the container thread that is processing the request, 
the exception propagates out of the
+     * application and is handled by the container. In any other case nothing 
would handle the exception on behalf of
+     * the container and the request would remain in the asynchronous state 
until the asynchronous timeout expired
+     * (which might be never). Dispatch to a container thread, as for a normal 
dispatch, but rather than dispatching
+     * the request, throw the exception so that it is handled in the same way 
as any other failure of an asynchronous
+     * dispatch.
+     *
+     * @param t The reason the dispatch failed
+     */
+    private void failDispatch(RuntimeException t) {
+        if (request.getCoyoteRequest().isRequestThread()) {
+            return;
+        }
+        synchronized (asyncContextLock) {
+            if (dispatch != null) {
+                // A dispatch has already been requested
+                return;
+            }
+            // Runs on a container thread where the failure is handled like 
any other failure of an async dispatch
+            dispatch = () -> {
+                // As for a normal dispatch, the dispatch is now being 
processed
+                request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCHED, 
null);
+                throw t;
+            };
+            request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCH, null);
+        }
+    }
+
     @Override
     public void dispatch(String path) {
         dispatch(getRequest().getServletContext(), path);
diff --git a/test/org/apache/catalina/core/TestAsyncContextImpl.java 
b/test/org/apache/catalina/core/TestAsyncContextImpl.java
index 8c861bfa76..33573f7d59 100644
--- a/test/org/apache/catalina/core/TestAsyncContextImpl.java
+++ b/test/org/apache/catalina/core/TestAsyncContextImpl.java
@@ -19,6 +19,8 @@ package org.apache.catalina.core;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.PrintWriter;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Proxy;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.nio.charset.StandardCharsets;
@@ -29,6 +31,8 @@ import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
 import java.util.logging.Level;
 import java.util.logging.LogManager;
 
@@ -39,6 +43,7 @@ import jakarta.servlet.DispatcherType;
 import jakarta.servlet.GenericServlet;
 import jakarta.servlet.RequestDispatcher;
 import jakarta.servlet.Servlet;
+import jakarta.servlet.ServletContext;
 import jakarta.servlet.ServletException;
 import jakarta.servlet.ServletOutputStream;
 import jakarta.servlet.ServletRequest;
@@ -50,6 +55,7 @@ import jakarta.servlet.ServletResponseWrapper;
 import jakarta.servlet.WriteListener;
 import jakarta.servlet.http.HttpServlet;
 import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequestWrapper;
 import jakarta.servlet.http.HttpServletResponse;
 
 import org.junit.Assert;
@@ -2579,6 +2585,286 @@ public class TestAsyncContextImpl extends 
TomcatBaseTest {
     }
 
 
+    /*
+     * The path for the dispatch in AsyncContext.dispatch() is derived by the 
container so, if it can't be used, the
+     * application can't be expected to recover. If the caller is not the 
container thread that is processing the
+     * request there is nothing to handle the exception so the container must 
complete the request rather than leave
+     * it waiting for the async timeout (which could be infinite).
+     */
+    @Test
+    public void testAsyncDispatchNoArgFailureNonContainerThread() throws 
Exception {
+        AsyncDispatchNoArgFailureServlet servlet = new 
AsyncDispatchNoArgFailureServlet(false);
+        long elapsed = doTestAsyncDispatchNoArgFailure(servlet);
+
+        // The async timeout is 10s
+        Assert.assertTrue("Request waited for the async timeout: " + elapsed + 
"ms", elapsed < 5000);
+        Assert.assertTrue("The caller must be told about the failure", 
servlet.callerException.get() instanceof
+                UnsupportedOperationException);
+        // The failure is handled like any other failure of an async dispatch 
so may be wrapped
+        Throwable listenerThrowable = servlet.listenerThrowable.get();
+        while (listenerThrowable != null && !(listenerThrowable instanceof 
UnsupportedOperationException)) {
+            listenerThrowable = listenerThrowable.getCause();
+        }
+        Assert.assertNotNull("onError() must be called with the failure", 
listenerThrowable);
+        Assert.assertTrue("onComplete() must be called", 
servlet.completed.await(5, TimeUnit.SECONDS));
+    }
+
+
+    /*
+     * As above but the caller is the container thread that is processing the 
request so the exception propagates out
+     * of the application and is handled in the usual way.
+     */
+    @Test
+    public void testAsyncDispatchNoArgFailureContainerThread() throws 
Exception {
+        AsyncDispatchNoArgFailureServlet servlet = new 
AsyncDispatchNoArgFailureServlet(true);
+        long elapsed = doTestAsyncDispatchNoArgFailure(servlet);
+
+        Assert.assertTrue("Request waited for the async timeout: " + elapsed + 
"ms", elapsed < 5000);
+        Assert.assertTrue("onComplete() must be called", 
servlet.completed.await(5, TimeUnit.SECONDS));
+    }
+
+
+    /*
+     * The failure is handled in the same way as any other failure so a mapped 
error page for the exception must be
+     * used.
+     */
+    @Test
+    public void testAsyncDispatchNoArgFailureNonContainerThreadErrorPage() 
throws Exception {
+        AsyncDispatchNoArgFailureServlet servlet = new 
AsyncDispatchNoArgFailureServlet(false);
+        ByteChunk responseBody = new ByteChunk();
+        long elapsed = doTestAsyncDispatchNoArgFailure(servlet, context -> {
+            Tomcat.addServlet(context, "errorPage", new HttpServlet() {
+                private static final long serialVersionUID = 1L;
+
+                @Override
+                protected void doGet(HttpServletRequest req, 
HttpServletResponse resp) throws IOException {
+                    resp.setContentType("text/plain");
+                    resp.getWriter().print("ERROR-PAGE:" +
+                            ((Class<?>) 
req.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)).getName());
+                }
+            });
+            context.addServletMapping("/errorPage", "errorPage");
+            ErrorPage errorPage = new ErrorPage();
+            
errorPage.setExceptionType(UnsupportedOperationException.class.getName());
+            errorPage.setLocation("/errorPage");
+            context.addErrorPage(errorPage);
+        }, responseBody);
+
+        Assert.assertTrue("Request waited for the async timeout: " + elapsed + 
"ms", elapsed < 5000);
+        Assert.assertEquals("ERROR-PAGE:" + 
UnsupportedOperationException.class.getName(),
+                responseBody.toString());
+    }
+
+
+    /*
+     * Each listener must be able to use the AsyncContext to recover from the 
failure, not just the first.
+     */
+    @Test
+    public void 
testAsyncDispatchNoArgFailureNonContainerThreadSecondListenerCompletes() throws 
Exception {
+        AsyncDispatchNoArgFailureServlet servlet = new 
AsyncDispatchNoArgFailureServlet(false);
+        servlet.secondListenerCompletes = true;
+        ByteChunk responseBody = new ByteChunk();
+        long elapsed = doTestAsyncDispatchNoArgFailure(servlet, null, 
responseBody);
+
+        Assert.assertTrue("Request waited for the async timeout: " + elapsed + 
"ms", elapsed < 5000);
+        Assert.assertNull("The second listener must be able to use the 
AsyncContext",
+                servlet.secondListenerException.get());
+        Assert.assertTrue("onComplete() must be called", 
servlet.completed.await(5, TimeUnit.SECONDS));
+    }
+
+
+    /*
+     * The failure is handled like the failure of any other asynchronous 
dispatch so an error page must be able to start
+     * asynchronous processing.
+     */
+    @Test
+    public void 
testAsyncDispatchNoArgFailureNonContainerThreadErrorPageStartsAsync() throws 
Exception {
+        AsyncDispatchNoArgFailureServlet servlet = new 
AsyncDispatchNoArgFailureServlet(false);
+        AtomicReference<Throwable> errorPageException = new 
AtomicReference<>();
+        ByteChunk responseBody = new ByteChunk();
+        long elapsed = doTestAsyncDispatchNoArgFailure(servlet, context -> {
+            Wrapper w = Tomcat.addServlet(context, "errorPage", new 
HttpServlet() {
+                private static final long serialVersionUID = 1L;
+
+                @Override
+                protected void doGet(HttpServletRequest req, 
HttpServletResponse resp) throws IOException {
+                    try {
+                        AsyncContext ac = req.startAsync();
+                        resp.setContentType("text/plain");
+                        resp.getWriter().print("ERROR-PAGE-ASYNC");
+                        ac.complete();
+                    } catch (RuntimeException e) {
+                        errorPageException.set(e);
+                    }
+                }
+            });
+            w.setAsyncSupported(true);
+            context.addServletMapping("/errorPage", "errorPage");
+            ErrorPage errorPage = new ErrorPage();
+            
errorPage.setExceptionType(UnsupportedOperationException.class.getName());
+            errorPage.setLocation("/errorPage");
+            context.addErrorPage(errorPage);
+        }, responseBody, 500);
+
+        Assert.assertTrue("Request waited for the async timeout: " + elapsed + 
"ms", elapsed < 5000);
+        Assert.assertNull("The error page must be able to start async 
processing", errorPageException.get());
+        Assert.assertEquals("ERROR-PAGE-ASYNC", responseBody.toString());
+    }
+
+
+    private long 
doTestAsyncDispatchNoArgFailure(AsyncDispatchNoArgFailureServlet servlet) 
throws Exception {
+        return doTestAsyncDispatchNoArgFailure(servlet, null, new ByteChunk());
+    }
+
+
+    private long 
doTestAsyncDispatchNoArgFailure(AsyncDispatchNoArgFailureServlet servlet,
+            Consumer<Context> contextConfig, ByteChunk responseBody) throws 
Exception {
+        return doTestAsyncDispatchNoArgFailure(servlet, contextConfig, 
responseBody, 500);
+    }
+
+
+    private long 
doTestAsyncDispatchNoArgFailure(AsyncDispatchNoArgFailureServlet servlet,
+            Consumer<Context> contextConfig, ByteChunk responseBody, int 
expectedStatus) throws Exception {
+        Tomcat tomcat = getTomcatInstance();
+        Context context = tomcat.addContext("/test", null);
+        // Disable class path scanning - it slows the tests down by almost an 
order of magnitude
+        ((StandardJarScanner) context.getJarScanner()).setScanClassPath(false);
+
+        Wrapper w = Tomcat.addServlet(context, "failure", servlet);
+        w.setAsyncSupported(true);
+        context.addServletMapping("/failure", "failure");
+        if (contextConfig != null) {
+            contextConfig.accept(context);
+        }
+        tomcat.start();
+
+        long start = System.nanoTime();
+        int rc = getUrl("http://localhost:"; + getPort() + "/test/failure", 
responseBody, null);
+        long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - 
start);
+
+        Assert.assertEquals(responseBody.toString(), expectedStatus, rc);
+        return elapsed;
+    }
+
+
+    /*
+     * Starts async processing with a request that provides a ServletContext 
that can't provide a dispatcher that
+     * supports async dispatching. This simulates a failure in the container.
+     */
+    private static class AsyncDispatchNoArgFailureServlet extends HttpServlet {
+
+        private static final long serialVersionUID = 1L;
+
+        private final boolean containerThread;
+        private boolean secondListenerCompletes = false;
+        private final transient AtomicReference<Throwable> callerException = 
new AtomicReference<>();
+        private final transient AtomicReference<Throwable> listenerThrowable = 
new AtomicReference<>();
+        private final transient AtomicReference<Throwable> 
secondListenerException = new AtomicReference<>();
+        private final transient CountDownLatch completed = new 
CountDownLatch(1);
+
+        AsyncDispatchNoArgFailureServlet(boolean containerThread) {
+            this.containerThread = containerThread;
+        }
+
+        @Override
+        protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws IOException {
+            ServletContext realContext = req.getServletContext();
+            ServletContext brokenContext = (ServletContext) 
Proxy.newProxyInstance(
+                    getClass().getClassLoader(), new Class<?>[] { 
ServletContext.class }, (proxy, method, args) -> {
+                        if ("getRequestDispatcher".equals(method.getName())) {
+                            // Not an AsyncDispatcher
+                            return new RequestDispatcher() {
+                                @Override
+                                public void forward(ServletRequest request, 
ServletResponse response) {
+                                    // NO-OP
+                                }
+
+                                @Override
+                                public void include(ServletRequest request, 
ServletResponse response) {
+                                    // NO-OP
+                                }
+                            };
+                        }
+                        try {
+                            return method.invoke(realContext, args);
+                        } catch (InvocationTargetException e) {
+                            throw e.getCause();
+                        }
+                    });
+            HttpServletRequest brokenRequest = new 
HttpServletRequestWrapper(req) {
+                @Override
+                public ServletContext getServletContext() {
+                    return brokenContext;
+                }
+            };
+
+            AsyncContext ac = req.startAsync(brokenRequest, resp);
+            // Long enough that the test fails if the request is left to time 
out
+            ac.setTimeout(10000);
+            ac.addListener(new AsyncListener() {
+                @Override
+                public void onComplete(AsyncEvent event) {
+                    completed.countDown();
+                }
+
+                @Override
+                public void onTimeout(AsyncEvent event) {
+                    // NO-OP
+                }
+
+                @Override
+                public void onError(AsyncEvent event) {
+                    listenerThrowable.set(event.getThrowable());
+                }
+
+                @Override
+                public void onStartAsync(AsyncEvent event) {
+                    // NO-OP
+                }
+            });
+            if (secondListenerCompletes) {
+                ac.addListener(new AsyncListener() {
+                    @Override
+                    public void onComplete(AsyncEvent event) {
+                        // NO-OP
+                    }
+
+                    @Override
+                    public void onTimeout(AsyncEvent event) {
+                        // NO-OP
+                    }
+
+                    @Override
+                    public void onError(AsyncEvent event) {
+                        try {
+                            event.getAsyncContext().complete();
+                        } catch (RuntimeException e) {
+                            secondListenerException.set(e);
+                        }
+                    }
+
+                    @Override
+                    public void onStartAsync(AsyncEvent event) {
+                        // NO-OP
+                    }
+                });
+            }
+
+            if (containerThread) {
+                ac.dispatch();
+            } else {
+                new Thread(() -> {
+                    try {
+                        ac.dispatch();
+                    } catch (RuntimeException e) {
+                        callerException.set(e);
+                    }
+                }).start();
+            }
+        }
+    }
+
+
     /*
      * A failed dispatch must not change the state of the request. The 
application must be able to recover from the
      * failure. In particular, the async attributes that record the original 
request must not have been set by the
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index 633ae9ac2d..eb0f50e520 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -289,6 +289,13 @@
         per the context decoding settings. Also ensure that a failed
         asynchronous dispatch does not modify the request attributes. (markt)
       </fix>
+      <fix>
+        If <code>AsyncContext.dispatch()</code> is unable to dispatch the
+        request, for example because of a bug, and it is not called by the
+        container thread processing the request then treat the failure as an
+        error. Fire <code>AsyncListener.onError()</code>, generate the error
+        response and complete the request. (markt)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="Coyote">


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

Reply via email to