From bd1526d2639e6234bfd4af2738e9436200cfe8c3 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 19 Nov 2026 23:59:21 -0800 Subject: [PATCH 1/3] Fix BZ 70362 - don't restart async error handling after a completed dispatch An asynchronous dispatch that called sendError() and returned normally had already notified the AsyncListeners of completion when the check added for BZ 66875 started async error handling, which notified them of an error with no throwable and then of completion a second time. https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 --- .../catalina/connector/CoyoteAdapter.java | 4 +- .../catalina/core/AsyncContextImpl.java | 15 +++++++ .../catalina/core/TestAsyncContextImpl.java | 44 +++++++++++++++++++ webapps/docs/changelog.xml | 8 ++++ 4 files changed, 70 insertions(+), 1 deletion(-) diff --git a/java/org/apache/catalina/connector/CoyoteAdapter.java b/java/org/apache/catalina/connector/CoyoteAdapter.java index 12d670afff10..e63baaa96c5f 100644 --- a/java/org/apache/catalina/connector/CoyoteAdapter.java +++ b/java/org/apache/catalina/connector/CoyoteAdapter.java @@ -239,7 +239,9 @@ public boolean asyncDispatch(org.apache.coyote.Request req, org.apache.coyote.Re if (request.isAsyncDispatching()) { connector.getService().getContainer().getPipeline().getFirst().invoke(request, response); - if (response.isError()) { + // A dispatch that completed the asynchronous processing has already notified the listeners of + // completion, so an error response it created must not start async error handling (BZ 70362) + if (response.isError() && !asyncConImpl.isCompletedByDispatch()) { Throwable t = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); asyncConImpl.setErrorState(t, true); } diff --git a/java/org/apache/catalina/core/AsyncContextImpl.java b/java/org/apache/catalina/core/AsyncContextImpl.java index 655215eed320..d973f4c5dca0 100644 --- a/java/org/apache/catalina/core/AsyncContextImpl.java +++ b/java/org/apache/catalina/core/AsyncContextImpl.java @@ -126,6 +126,7 @@ public class AsyncContextImpl implements AsyncContext, AsyncContextCallback { private volatile boolean hasOriginalRequestAndResponse = true; private final AtomicBoolean hasErrorProcessingStarted = new AtomicBoolean(false); private final AtomicBoolean hasOnErrorReturned = new AtomicBoolean(false); + private volatile boolean completedByDispatch = false; /* * ThreadLocal for passing over-ridden URL encoding state when dispatching. @@ -362,6 +363,7 @@ public void recycle() { timeout = -1; hasErrorProcessingStarted.set(false); hasOnErrorReturned.set(false); + completedByDispatch = false; } private void clearServletRequestResponse() { @@ -402,6 +404,7 @@ public void setStarted(Context context, ServletRequest request, ServletResponse this.servletResponse = response; this.hasOriginalRequestAndResponse = originalRequestResponse; this.event = new AsyncEvent(this, request, response); + this.completedByDispatch = false; List listenersCopy = new ArrayList<>(listeners); listeners.clear(); @@ -444,6 +447,7 @@ protected void doInternalDispatch() throws ServletException, IOException { dispatch = null; runnable.run(); if (!request.isAsync()) { + completedByDispatch = true; fireOnComplete(); } } catch (RuntimeException x) { @@ -469,6 +473,17 @@ protected void doInternalDispatch() throws ServletException, IOException { } + /** + * Has the most recent dispatch completed the asynchronous processing? If it has, the listeners have been notified + * that the processing is complete. + * + * @return {@code true} if the most recent dispatch completed the asynchronous processing, otherwise {@code false} + */ + public boolean isCompletedByDispatch() { + return completedByDispatch; + } + + @Override public long getTimeout() { check(); diff --git a/test/org/apache/catalina/core/TestAsyncContextImpl.java b/test/org/apache/catalina/core/TestAsyncContextImpl.java index fd1bb765dcfe..529423996524 100644 --- a/test/org/apache/catalina/core/TestAsyncContextImpl.java +++ b/test/org/apache/catalina/core/TestAsyncContextImpl.java @@ -2403,6 +2403,50 @@ public void testTimeoutDispatchCustomErrorPage() throws Exception { } + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + */ + @Test + public void testSendErrorOnAsyncDispatchCompletesOnce() throws Exception { + resetTracker(); + Tomcat tomcat = getTomcatInstance(); + Context context = getProgrammaticRootContext(); + Wrapper wrapper = Tomcat.addServlet(context, "bug70362", new Bug70362Servlet()); + wrapper.setAsyncSupported(true); + context.addServletMapping("/bug70362", "bug70362"); + tomcat.start(); + + int rc = getUrl("http://localhost:" + getPort() + "/bug70362", new ByteChunk(), null); + Assert.assertEquals(HttpServletResponse.SC_SERVICE_UNAVAILABLE, rc); + + int count = 0; + while (getTrack().isEmpty() && count < 100) { + Thread.sleep(50); + count++; + } + // Allow time for any further, unexpected, listener events + Thread.sleep(500); + Assert.assertEquals("onComplete-", getTrack()); + } + + + public static class Bug70362Servlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (req.getDispatcherType() == DispatcherType.ASYNC) { + resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); + } else { + AsyncContext asyncContext = req.startAsync(); + asyncContext.addListener(new TrackingListener(false, false, null)); + asyncContext.dispatch(); + } + } + } + + public static class Bug58751AsyncServlet extends HttpServlet { private static final long serialVersionUID = 1L; diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml index c396213f6572..c08f17b8ddb4 100644 --- a/webapps/docs/changelog.xml +++ b/webapps/docs/changelog.xml @@ -237,6 +237,14 @@ ClassValue to cache the result of calling Class.getMethods(). (markt) + + 70362: When an asynchronous dispatch completes the + asynchronous processing after calling sendError(), do not + start asynchronous error handling, which notified the + AsyncListeners of an error and of completion again after + they had been notified of completion. Regression in the fix for + 66875. Patch provided by Scott Murphy Heiberg. + From 54c7416063f20aa6e5feaa5bac6fc4f13933b705 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 21 Nov 2026 21:51:52 -0800 Subject: [PATCH 2/3] Test BZ 70362 for a dispatch from start() and for a throwing dispatch Cover the dispatch() made from a container-managed thread via start(), and check that an exception thrown by the async dispatch still reaches the listeners as onError before onComplete. --- .../catalina/core/TestAsyncContextImpl.java | 52 +++++++++++++++++-- 1 file changed, 47 insertions(+), 5 deletions(-) diff --git a/test/org/apache/catalina/core/TestAsyncContextImpl.java b/test/org/apache/catalina/core/TestAsyncContextImpl.java index 529423996524..b8a57dc93c9d 100644 --- a/test/org/apache/catalina/core/TestAsyncContextImpl.java +++ b/test/org/apache/catalina/core/TestAsyncContextImpl.java @@ -2408,25 +2408,52 @@ public void testTimeoutDispatchCustomErrorPage() throws Exception { */ @Test public void testSendErrorOnAsyncDispatchCompletesOnce() throws Exception { + doTestBug70362(false, false, HttpServletResponse.SC_SERVICE_UNAVAILABLE, "onComplete-"); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + */ + @Test + public void testSendErrorOnAsyncDispatchFromStartCompletesOnce() throws Exception { + doTestBug70362(true, false, HttpServletResponse.SC_SERVICE_UNAVAILABLE, "onComplete-"); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * An exception thrown by the dispatch must still start async error handling. + */ + @Test + public void testExceptionOnAsyncDispatchStartsErrorHandling() throws Exception { + doTestBug70362(false, true, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "onError-onComplete-"); + } + + + private void doTestBug70362(boolean dispatchFromStart, boolean throwOnDispatch, int expectedStatus, + String expectedTrack) throws Exception { resetTracker(); Tomcat tomcat = getTomcatInstance(); Context context = getProgrammaticRootContext(); - Wrapper wrapper = Tomcat.addServlet(context, "bug70362", new Bug70362Servlet()); + Wrapper wrapper = + Tomcat.addServlet(context, "bug70362", new Bug70362Servlet(dispatchFromStart, throwOnDispatch)); wrapper.setAsyncSupported(true); context.addServletMapping("/bug70362", "bug70362"); tomcat.start(); int rc = getUrl("http://localhost:" + getPort() + "/bug70362", new ByteChunk(), null); - Assert.assertEquals(HttpServletResponse.SC_SERVICE_UNAVAILABLE, rc); + Assert.assertEquals(expectedStatus, rc); int count = 0; - while (getTrack().isEmpty() && count < 100) { + while (!getTrack().endsWith("onComplete-") && count < 100) { Thread.sleep(50); count++; } // Allow time for any further, unexpected, listener events Thread.sleep(500); - Assert.assertEquals("onComplete-", getTrack()); + Assert.assertEquals(expectedTrack, getTrack()); } @@ -2434,14 +2461,29 @@ public static class Bug70362Servlet extends HttpServlet { private static final long serialVersionUID = 1L; + private final boolean dispatchFromStart; + private final boolean throwOnDispatch; + + public Bug70362Servlet(boolean dispatchFromStart, boolean throwOnDispatch) { + this.dispatchFromStart = dispatchFromStart; + this.throwOnDispatch = throwOnDispatch; + } + @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getDispatcherType() == DispatcherType.ASYNC) { + if (throwOnDispatch) { + throw new ServletException("Bug70362"); + } resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { AsyncContext asyncContext = req.startAsync(); asyncContext.addListener(new TrackingListener(false, false, null)); - asyncContext.dispatch(); + if (dispatchFromStart) { + asyncContext.start(asyncContext::dispatch); + } else { + asyncContext.dispatch(); + } } } } From f2da85a1e61ae6f817aa604daaca306b9d1651f3 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 21 Nov 2026 23:48:35 -0800 Subject: [PATCH 3/3] BZ 70362 - report dispatch failures before completion, not after An asynchronous dispatch that recorded a failure and returned, or threw after an I/O error, notified the listeners of completion before the error handling in CoyoteAdapter.asyncDispatch notified them of the failure and of completion again. The notification of completion is now deferred in those cases so the error handling reports the failure first and completes once, with CoyoteAdapter firing the deferred notification if the error handling does not start. An error response with no exception no longer starts async error handling when the dispatch started a new async cycle and ended it with complete() or dispatch(), which replaced that with onError(null). The tests now wait for the access log entry, made once processing of the request has ended, rather than a fixed delay; check the throwable the listeners receive; cover dispatch() from start() both before and after the request thread exits service(); and check the in-progress async count returns to zero. --- .../catalina/connector/CoyoteAdapter.java | 18 +- .../catalina/core/AsyncContextImpl.java | 51 +++- .../catalina/core/TestAsyncContextImpl.java | 285 ++++++++++++++++-- webapps/docs/changelog.xml | 14 +- 4 files changed, 326 insertions(+), 42 deletions(-) diff --git a/java/org/apache/catalina/connector/CoyoteAdapter.java b/java/org/apache/catalina/connector/CoyoteAdapter.java index e63baaa96c5f..3c3f1fddf314 100644 --- a/java/org/apache/catalina/connector/CoyoteAdapter.java +++ b/java/org/apache/catalina/connector/CoyoteAdapter.java @@ -238,12 +238,20 @@ public boolean asyncDispatch(org.apache.coyote.Request req, org.apache.coyote.Re } if (request.isAsyncDispatching()) { - connector.getService().getContainer().getPipeline().getFirst().invoke(request, response); - // A dispatch that completed the asynchronous processing has already notified the listeners of - // completion, so an error response it created must not start async error handling (BZ 70362) - if (response.isError() && !asyncConImpl.isCompletedByDispatch()) { + try { + connector.getService().getContainer().getPipeline().getFirst().invoke(request, response); Throwable t = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); - asyncConImpl.setErrorState(t, true); + /* + * An error response does not start async error handling if the listeners have already been + * notified that the dispatch completed the async processing, or if it has no exception and the + * dispatch started a new async cycle and ended it with complete() or dispatch() (BZ 70362). + */ + if (response.isError() && !asyncConImpl.isCompletedByDispatch() && + (t != null || !(request.isAsyncCompleting() || request.isAsyncDispatching()))) { + asyncConImpl.setErrorState(t, true); + } + } finally { + asyncConImpl.fireDeferredOnComplete(); } } diff --git a/java/org/apache/catalina/core/AsyncContextImpl.java b/java/org/apache/catalina/core/AsyncContextImpl.java index d973f4c5dca0..6ab795e4a0bb 100644 --- a/java/org/apache/catalina/core/AsyncContextImpl.java +++ b/java/org/apache/catalina/core/AsyncContextImpl.java @@ -127,6 +127,7 @@ public class AsyncContextImpl implements AsyncContext, AsyncContextCallback { private final AtomicBoolean hasErrorProcessingStarted = new AtomicBoolean(false); private final AtomicBoolean hasOnErrorReturned = new AtomicBoolean(false); private volatile boolean completedByDispatch = false; + private volatile boolean completionDeferred = false; /* * ThreadLocal for passing over-ridden URL encoding state when dispatching. @@ -364,6 +365,7 @@ public void recycle() { hasErrorProcessingStarted.set(false); hasOnErrorReturned.set(false); completedByDispatch = false; + completionDeferred = false; } private void clearServletRequestResponse() { @@ -405,6 +407,7 @@ public void setStarted(Context context, ServletRequest request, ServletResponse this.hasOriginalRequestAndResponse = originalRequestResponse; this.event = new AsyncEvent(this, request, response); this.completedByDispatch = false; + this.completionDeferred = false; List listenersCopy = new ArrayList<>(listeners); listeners.clear(); @@ -447,8 +450,16 @@ protected void doInternalDispatch() throws ServletException, IOException { dispatch = null; runnable.run(); if (!request.isAsync()) { - completedByDispatch = true; - fireOnComplete(); + if (isUnreportedFailure()) { + /* + * The dispatch recorded a failure and returned. CoyoteAdapter starts async error handling which + * notifies the listeners of the failure before it completes the async processing. + */ + completionDeferred = true; + } else { + completedByDispatch = true; + fireOnComplete(); + } } } catch (RuntimeException x) { AtomicBoolean result = new AtomicBoolean(); @@ -460,7 +471,16 @@ protected void doInternalDispatch() throws ServletException, IOException { * information required to determine that onComplete() needs to be called. */ if (!result.get()) { - fireOnComplete(); + if (hasErrorProcessingStarted.get()) { + completedByDispatch = true; + fireOnComplete(); + } else { + /* + * CoyoteAdapter starts async error handling for the exception, which notifies the listeners of it + * before it completes the async processing. If it does not, it calls fireDeferredOnComplete(). + */ + completionDeferred = true; + } } if (x.getCause() instanceof ServletException) { throw (ServletException) x.getCause(); @@ -473,6 +493,16 @@ protected void doInternalDispatch() throws ServletException, IOException { } + /* + * Has the dispatch recorded a failure (an error response with an exception) that will start async error handling + * once the dispatch returns? + */ + private boolean isUnreportedFailure() { + return !hasErrorProcessingStarted.get() && request.getResponse().isError() && + request.getAttribute(RequestDispatcher.ERROR_EXCEPTION) != null; + } + + /** * Has the most recent dispatch completed the asynchronous processing? If it has, the listeners have been notified * that the processing is complete. @@ -484,6 +514,19 @@ public boolean isCompletedByDispatch() { } + /** + * Notifies the listeners that the most recent dispatch completed the asynchronous processing if that notification + * was deferred for async error handling that has not started. Called once the dispatch has returned. + */ + public void fireDeferredOnComplete() { + if (completionDeferred) { + completionDeferred = false; + completedByDispatch = true; + fireOnComplete(); + } + } + + @Override public long getTimeout() { check(); @@ -524,6 +567,8 @@ public void setErrorState(Throwable t, boolean fireOnError) { // Skip duplicate error processing return; } + // The error processing completes the async processing + completionDeferred = false; if (t != null) { request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); } diff --git a/test/org/apache/catalina/core/TestAsyncContextImpl.java b/test/org/apache/catalina/core/TestAsyncContextImpl.java index b8a57dc93c9d..896839390cf5 100644 --- a/test/org/apache/catalina/core/TestAsyncContextImpl.java +++ b/test/org/apache/catalina/core/TestAsyncContextImpl.java @@ -18,7 +18,9 @@ import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.io.PrintWriter; +import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; @@ -2405,55 +2407,200 @@ public void testTimeoutDispatchCustomErrorPage() throws Exception { /* * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * dispatch() is called on the request thread. */ @Test public void testSendErrorOnAsyncDispatchCompletesOnce() throws Exception { - doTestBug70362(false, false, HttpServletResponse.SC_SERVICE_UNAVAILABLE, "onComplete-"); + doTestBug70362(Bug70362Mode.SEND_ERROR, HttpServletResponse.SC_SERVICE_UNAVAILABLE, "onComplete-", null); } /* * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * dispatch() is called from start() before the request thread exits service(). */ @Test - public void testSendErrorOnAsyncDispatchFromStartCompletesOnce() throws Exception { - doTestBug70362(true, false, HttpServletResponse.SC_SERVICE_UNAVAILABLE, "onComplete-"); + public void testSendErrorOnAsyncDispatchFromStartBeforeExitCompletesOnce() throws Exception { + doTestBug70362(Bug70362Mode.SEND_ERROR_START_BEFORE_EXIT, HttpServletResponse.SC_SERVICE_UNAVAILABLE, + "onComplete-", null); } /* * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 * - * An exception thrown by the dispatch must still start async error handling. + * dispatch() is called from start() after the request thread has exited service(). + */ + @Test + public void testSendErrorOnAsyncDispatchFromStartAfterExitCompletesOnce() throws Exception { + doTestBug70362(Bug70362Mode.SEND_ERROR_START_AFTER_EXIT, HttpServletResponse.SC_SERVICE_UNAVAILABLE, + "onComplete-", null); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * The dispatch calls sendError(), starts a new asynchronous cycle and completes it. + */ + @Test + public void testSendErrorThenCompleteOnAsyncDispatchCompletesOnce() throws Exception { + doTestBug70362(Bug70362Mode.SEND_ERROR_RESTART_COMPLETE, HttpServletResponse.SC_SERVICE_UNAVAILABLE, + "onComplete-", null); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * The dispatch calls sendError(), starts a new asynchronous cycle and dispatches it. + */ + @Test + public void testSendErrorThenDispatchOnAsyncDispatchCompletesOnce() throws Exception { + doTestBug70362(Bug70362Mode.SEND_ERROR_RESTART_DISPATCH, HttpServletResponse.SC_SERVICE_UNAVAILABLE, + "onComplete-", null); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * An exception thrown by the dispatch is reported to the listeners before completion. */ @Test public void testExceptionOnAsyncDispatchStartsErrorHandling() throws Exception { - doTestBug70362(false, true, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "onError-onComplete-"); + doTestBug70362(Bug70362Mode.THROW, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "onError-onComplete-", + ServletException.class); } - private void doTestBug70362(boolean dispatchFromStart, boolean throwOnDispatch, int expectedStatus, - String expectedTrack) throws Exception { + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * A failure recorded on the request by a dispatch that then returns normally (as InputBuffer does for a read + * failure the application swallows) is reported to the listeners before completion. + */ + @Test + public void testRecordedFailureOnAsyncDispatchStartsErrorHandling() throws Exception { + doTestBug70362(Bug70362Mode.RECORDED_FAILURE, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + "onError-onComplete-", IOException.class); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=66875 + * + * A failure the dispatch handled itself, writing the response, does not start async error handling. + */ + @Test + public void testHandledFailureOnAsyncDispatchCompletesOnce() throws Exception { + doTestBug70362(Bug70362Mode.HANDLED_FAILURE, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "onComplete-", + null); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * The client has gone when the dispatch writes the response and the dispatch throws the resulting IOException. + */ + @Test + public void testIoErrorOnAsyncDispatchStartsErrorHandling() throws Exception { + doTestBug70362(Bug70362Mode.IO_ERROR, -1, "onError-onComplete-", IOException.class); + } + + + private void doTestBug70362(Bug70362Mode mode, int expectedStatus, String expectedTrack, + Class expectedThrowable) throws Exception { resetTracker(); + bug70362Throwable = null; Tomcat tomcat = getTomcatInstance(); Context context = getProgrammaticRootContext(); - Wrapper wrapper = - Tomcat.addServlet(context, "bug70362", new Bug70362Servlet(dispatchFromStart, throwOnDispatch)); + Bug70362Servlet servlet = new Bug70362Servlet(mode); + Wrapper wrapper = Tomcat.addServlet(context, "bug70362", servlet); wrapper.setAsyncSupported(true); context.addServletMapping("/bug70362", "bug70362"); + TesterAccessLogValve alv = new TesterAccessLogValve(); + context.getPipeline().addValve(alv); tomcat.start(); - int rc = getUrl("http://localhost:" + getPort() + "/bug70362", new ByteChunk(), null); - Assert.assertEquals(expectedStatus, rc); + if (mode == Bug70362Mode.IO_ERROR) { + try (Socket socket = new Socket("localhost", getPort())) { + OutputStream os = socket.getOutputStream(); + os.write(("GET /bug70362 HTTP/1.1" + CRLF + "Host: localhost" + CRLF + CRLF) + .getBytes(StandardCharsets.ISO_8859_1)); + os.flush(); + Assert.assertTrue(servlet.asyncStartedLatch.await(10, TimeUnit.SECONDS)); + // Reset the connection on close so the writes of the dispatch fail + socket.setSoLinger(true, 0); + } + servlet.clientClosedLatch.countDown(); + } else { + int rc = getUrl("http://localhost:" + getPort() + "/bug70362", new ByteChunk(), null); + Assert.assertEquals(expectedStatus, rc); + } + // The access log entry is made once processing of the request has ended, after all listener events int count = 0; - while (!getTrack().endsWith("onComplete-") && count < 100) { + while (alv.getEntryCount() < 1 && count < 200) { Thread.sleep(50); count++; } - // Allow time for any further, unexpected, listener events - Thread.sleep(500); + Assert.assertEquals(1, alv.getEntryCount()); Assert.assertEquals(expectedTrack, getTrack()); + Assert.assertEquals(0, ((StandardContext) context).getInProgressAsyncCount()); + if (expectedThrowable == null) { + Assert.assertNull(bug70362Throwable); + } else { + Assert.assertNotNull(bug70362Throwable); + Assert.assertTrue(bug70362Throwable.toString(), expectedThrowable.isInstance(bug70362Throwable)); + if (mode != Bug70362Mode.IO_ERROR) { + Assert.assertEquals(Bug70362Servlet.MESSAGE, bug70362Throwable.getMessage()); + } + } + } + + + private enum Bug70362Mode { + SEND_ERROR, + SEND_ERROR_START_BEFORE_EXIT, + SEND_ERROR_START_AFTER_EXIT, + SEND_ERROR_RESTART_COMPLETE, + SEND_ERROR_RESTART_DISPATCH, + THROW, + RECORDED_FAILURE, + HANDLED_FAILURE, + IO_ERROR + } + + + private static volatile Throwable bug70362Throwable; + + + public static class Bug70362Listener implements AsyncListener { + + @Override + public void onComplete(AsyncEvent event) throws IOException { + track("onComplete-"); + } + + @Override + public void onTimeout(AsyncEvent event) throws IOException { + track("onTimeout-"); + } + + @Override + public void onError(AsyncEvent event) throws IOException { + track("onError-"); + bug70362Throwable = event.getThrowable(); + } + + @Override + public void onStartAsync(AsyncEvent event) throws IOException { + // NO-OP + } } @@ -2461,29 +2608,109 @@ public static class Bug70362Servlet extends HttpServlet { private static final long serialVersionUID = 1L; - private final boolean dispatchFromStart; - private final boolean throwOnDispatch; + static final String MESSAGE = "Bug70362"; + + private final Bug70362Mode mode; + final transient CountDownLatch asyncStartedLatch = new CountDownLatch(1); + final transient CountDownLatch clientClosedLatch = new CountDownLatch(1); - public Bug70362Servlet(boolean dispatchFromStart, boolean throwOnDispatch) { - this.dispatchFromStart = dispatchFromStart; - this.throwOnDispatch = throwOnDispatch; + Bug70362Servlet(Bug70362Mode mode) { + this.mode = mode; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getDispatcherType() == DispatcherType.ASYNC) { - if (throwOnDispatch) { - throw new ServletException("Bug70362"); + switch (mode) { + case THROW: + throw new ServletException(MESSAGE); + case RECORDED_FAILURE: + req.setAttribute(RequestDispatcher.ERROR_EXCEPTION, new IOException(MESSAGE)); + resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + break; + case HANDLED_FAILURE: + // The application handled the failure and wrote the response itself, as in BZ 66875 + req.setAttribute(RequestDispatcher.ERROR_EXCEPTION, new IOException(MESSAGE)); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().print(MESSAGE); + break; + case SEND_ERROR_RESTART_COMPLETE: { + resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); + AsyncContext asyncContext = req.startAsync(); + asyncContext.addListener(new Bug70362Listener()); + asyncContext.complete(); + break; + } + case SEND_ERROR_RESTART_DISPATCH: { + if (req.getAttribute(MESSAGE) == null) { + req.setAttribute(MESSAGE, Boolean.TRUE); + resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); + AsyncContext asyncContext = req.startAsync(); + asyncContext.addListener(new Bug70362Listener()); + asyncContext.dispatch(); + } + break; + } + case IO_ERROR: { + OutputStream os = resp.getOutputStream(); + byte[] data = TestCoyoteAdapter.TEXT_8K.getBytes(StandardCharsets.UTF_8); + for (int i = 0; i < 1024; i++) { + os.write(data); + os.flush(); + } + break; + } + default: + resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } - resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); - } else { - AsyncContext asyncContext = req.startAsync(); - asyncContext.addListener(new TrackingListener(false, false, null)); - if (dispatchFromStart) { - asyncContext.start(asyncContext::dispatch); - } else { - asyncContext.dispatch(); + return; + } + + AsyncContext asyncContext = req.startAsync(); + asyncContext.setTimeout(0); + asyncContext.addListener(new Bug70362Listener()); + switch (mode) { + case SEND_ERROR_START_BEFORE_EXIT: { + // dispatch() is called while the request is still in the STARTING state + CountDownLatch dispatchedLatch = new CountDownLatch(1); + asyncContext.start(() -> { + asyncContext.dispatch(); + dispatchedLatch.countDown(); + }); + try { + Assert.assertTrue(dispatchedLatch.await(10, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + throw new ServletException(e); + } + break; } + case SEND_ERROR_START_AFTER_EXIT: + asyncContext.start(() -> { + try { + /* + * There is no signal for the request moving from STARTING to STARTED after service() + * exits so wait, as TestAsyncContextStateChanges does. + */ + Thread.sleep(1000); + } catch (InterruptedException e) { + // Ignore + } + asyncContext.dispatch(); + }); + break; + case IO_ERROR: + asyncContext.start(() -> { + try { + clientClosedLatch.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + // Ignore + } + asyncContext.dispatch(); + }); + asyncStartedLatch.countDown(); + break; + default: + asyncContext.dispatch(); } } } diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml index 58fb0ff48826..773a8a8e4883 100644 --- a/webapps/docs/changelog.xml +++ b/webapps/docs/changelog.xml @@ -242,11 +242,15 @@ LockOutRealm. (markt) - 70362: When an asynchronous dispatch completes the - asynchronous processing after calling sendError(), do not - start asynchronous error handling, which notified the - AsyncListeners of an error and of completion again after - they had been notified of completion. Regression in the fix for + 70362: Do not notify AsyncListeners of an error + after they have been notified of completion by an asynchronous dispatch, + and do not start asynchronous error handling for an error response + without an exception (e.g. from sendError()) when the + dispatch completed the asynchronous processing or started a new + asynchronous cycle and ended it with complete() or + dispatch(). A failure that an asynchronous dispatch + records, or an exception it throws after an I/O error, is reported to + the listeners before completion. Regression in the fix for 66875. Patch provided by Scott Murphy Heiberg.