Repository navigation
8.0 (fix): Complete asynchronous processing on Undertow once an error its request dispatch sent is answered - #17100
Conversation
…t dispatch sent is answered A request dispatch that started asynchronous processing and then sent an error, as Spring MVC does for a server error it resolves, left that processing open forever on Undertow when an error page answered the error. Undertow sends the error, through the error page that maps to it, once the dispatch has returned, and ends the exchange with it. The processing then never completed and never timed out, so its listeners were never told: the observation of the request never stopped, and a DeferredResult was never resolved. A handler now completes the processing once the exchange has ended, as Jetty does. Tomcat leaves such processing to its asynchronous timeout, and so does Undertow when no error page maps to the error.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## 8.0.x #17100 +/- ##
==================================================
+ Coverage 62.5742% 62.5842% +0.0100%
- Complexity 27543 27552 +9
==================================================
Files 2249 2250 +1
Lines 111725 111747 +22
Branches 20486 20490 +4
==================================================
+ Hits 69911 69936 +25
+ Misses 32455 32448 -7
- Partials 9359 9363 +4
🚀 New features to boost your workflow:
|
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. Completion runs before the error response is sent.
| } | ||
| this.next.handleRequest(exchange); | ||
| AsyncContextImpl asyncContext = context.getOriginalRequest().getAsyncContextInternal(); | ||
| if (context.getErrorCode() > 0 && asyncContext != null && !asyncContext.isCompletedBeforeInitialRequestDone()) { |
There was a problem hiding this comment.
A request starts asynchronous processing, sends an error, and then completes. Completion runs before the error response is sent, because this skips the listener once completion has already been asked for. Run completion after the error response.
There was a problem hiding this comment.
Fixed in 41589e7. The order came from Undertow, not from this check: ServletInitialHandler.handleFirstRequest tells the listeners as soon as the handler chain returns, and only then sends the error. Without the check, the listeners hear onComplete twice. When the dispatch has completed the processing itself, the handler now sends the error through doErrorDispatch before it returns, then clears the error code so Undertow doesn't send it again. onComplete now comes after the error page has answered and the response has ended. New test: asynchronousProcessingThatADispatchCompletesAfterSendingAnErrorCompletesOnceTheErrorPageHasAnsweredIt. It got ["onComplete", "errorPage"] before the fix.
matrei
left a comment
There was a problem hiding this comment.
Reviewed at 3c13e38 (base 8.0.x). It's on today's 8.0.x head (96a4ea4), so it merges cleanly.
AsyncErrorCompletionHandler is byte-identical to the copy #17088 put on 9.0.x, and so are the factory line and the three completion tests. The dispatcher-type test stays on 9.0.x with ForwardDispatcherTypeHandler, as it should.
The fix is right, and 8.0.x is the right branch. 7.0.x to 7.2.x have no grails-undertow: there, Undertow support comes from Spring Boot 3 itself, and Grails has no factory to register a handler in. The fix ends processing that otherwise never ends, so it needs no upgrade note on a patch branch.
What I ran:
-
Unit tests of
grails-undertow-spring-bootat the head: 74 tests, all pass. -
The three completion tests, 40 times each: 120 runs, all pass.
-
With the
!asyncContext.isCompletedBeforeInitialRequestDone()check (AsyncErrorCompletionHandler.java:52) removed, the third test fails with["onComplete", "onComplete"]. So it guards what the description says it does. -
The servlet from the description (start asynchronous processing, send a 503), with and without an error page, waiting 40 s, on:
- Undertow, with and without the handler
- Tomcat 11.0.27
- Jetty 12.1.15
See 1 and 2.
-
The merge-ups into 8.1.x and 9.0.x. See 3.
Before merge
1. Tomcat doesn't complete the processing either. Only Jetty does. The Javadoc (AsyncErrorCompletionHandler.java:29-33) says the handler completes it "as Tomcat and Jetty do". The description says a plain servlet hears onComplete on both. This is what the servlet from the description got:
| With an error page | Without one | |
|---|---|---|
| Jetty 12.1.15 | error page, onComplete, response |
onComplete, response |
| Tomcat 11.0.27 | error page, response, then onTimeout and onComplete 30 s later |
onTimeout, onComplete and the response, all 30 s later |
| Undertow, without the handler | error page, response, then nothing in 45 s | response, then onTimeout and onComplete 30 s later |
| Undertow, with the handler | error page, response, onComplete |
response, onComplete |
So Tomcat leaves the processing to its asynchronous timeout. Undertow does the same when no error page answers the error. Undertow never ends the processing only when an error page answers. Spring Boot registers an error page for a Spring MVC application, so the fix still covers the case that matters.
The functional specs pass on Tomcat for another reason. Grails leaves the failure on the request, and Tomcat reports it to the listeners and then completes the processing (CoyoteAdapter.java:366-372).
I'd have the Javadoc say what each container does:
* Completes the asynchronous processing a request dispatch started once the error that dispatch sent has been
* answered, as Jetty does. Undertow sends the error, through the error page that maps to it, once the dispatch has
* returned, and ends the exchange with it. The asynchronous processing is then never completed and never times out,
* so its listeners are never told it completed: {@code ServerHttpObservationFilter} never stops its observation of
* the request, and a {@code DeferredResult} is never resolved. Tomcat leaves such processing to time out, and so does
* Undertow when no error page maps to the error.
The description's servlet example needs the same correction. One more claim in the description doesn't hold: an async request timeout isn't such an error. Spring MVC answers a timeout from the asynchronous dispatch that follows it. WebAsyncManager sets an AsyncRequestTimeoutException as the result and dispatches (lines 332-338 in 7.0.9 and 7.1.0). The handler acts on the request dispatch only.
The 9.0.x copy has the same Javadoc. If #17101 makes the same edit, both branches add identical files, and the merge-up has nothing to resolve in the handler. Otherwise, take this side for the handler in the merge-up.
Notes
2. On James's point: the order is Undertow's own, and this handler can't change it. Take a dispatch that sends an error and then completes the processing itself. With an error page that records when it runs:
- Undertow:
onComplete, error page, response. That's with or without the handler. - Tomcat 11.0.27 and Jetty 12.1.15: error page,
onComplete, response.
Undertow completes that processing in ServletInitialHandler.handleFirstRequest, once the handler chain has returned. It calls handleCompletedBeforeInitialRequestDone() (:279-281), and only after that does it send the error (:284). The inner handler chain wrapper has returned by then. It can't move the completion behind the error page, short of doing Undertow's error dispatch itself.
The PR leaves this case as it was, and the third test pins that the processing still completes once. I'd keep the order out of this PR.
Both behaviours, this order and the processing that never completes, belong in an Undertow issue. A link from the Javadoc, like the #37731 notes in #17101, would tell whoever bumps Undertow when the handler can go. I found no existing issue for it.
3. Merge-up. It merges cleanly into 8.1.x. Into 9.0.x, git reports conflicts in two files:
- The factory.
UndertowServletWebServerFactoryTests: three hunks, the imports and the dispatcher-type test.
The description only names the factory line. In both files, taking the 9.0.x side gives exactly the 9.0.x files. The handler is an identical addition, unless 1 changes it on this branch only.
Verified as correct
git diffof the handler against 9.0.x is empty. The three tests match 9.0.x's, and the factory line sits where the 9.0.x one does.- Without the handler, a request whose error an error page answers never hears
onComplete, even after 45 s. With the handler, it hears it once the response is out. That case is the second test. - The handler acts on the request dispatch only. The error dispatch passes through it with its own dispatcher type. The trace shows
REQUESTfor/sendsError, thenERRORfor the error page. - On the request thread,
complete()only marks the processing as completed (AsyncContextImpl.java:264).handleCompletedBeforeInitialRequestDone()is what tells the listeners, so the listener calls both. - CI is green.
Only Jetty completes the asynchronous processing a request dispatch started once the error it sent has been answered. Tomcat leaves it to its asynchronous timeout, and so does Undertow when no error page maps to the error. Undertow never ends it only when an error page answers.
…has been answered on Undertow A request dispatch that started asynchronous processing, sent an error and then completed the processing itself had its listeners told before the error page ran. Undertow completes such processing once the dispatch has returned, and only then sends the error. When the dispatch has completed the processing, the handler now sends the error itself before it returns and clears it, so the listeners are told once the error has been answered, and Undertow does not send it again.
|
@matrei Thanks.
|
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. On a second dispatch, completion still runs before the error response.
|
|
||
| @Override | ||
| public void handleRequest(HttpServerExchange exchange) throws Exception { | ||
| ServletRequestContext context = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); |
There was a problem hiding this comment.
A servlet dispatches to /second. /second starts asynchronous processing again, sends an error, and completes. onComplete still runs before the error page, because this only handles the first dispatch. Run completion after the error response there too.
There was a problem hiding this comment.
Fixed in 0030da2. Undertow runs an asynchronous dispatch through the same ServletInitialHandler.handleFirstRequest as the request dispatch: it completes the processing once the dispatch returns, and only then sends the error. The handler now acts on asynchronous dispatches too, and only on processing the dispatch left started, so a dispatch that didn't start it again leaves the processing it was dispatched by alone. That also fixes processing an asynchronous dispatch started and left open after sending an error, which never completed, with or without an error page. Three new tests in UndertowServletWebServerFactoryTests cover /dispatches → /sendsError. All three failed before: ["onComplete", "errorPage"], ["errorPage"] and [].
…e its error is answered on Undertow Undertow handles an asynchronous dispatch as it does the request dispatch: it sends the error the dispatch sent once the dispatch has returned. An asynchronous dispatch that started asynchronous processing again and sent an error therefore left that processing open as well, and one that also completed it had its listeners told before the error page ran. The handler now acts on asynchronous dispatches too, and only on processing the dispatch left started, so an asynchronous dispatch that did not start it again leaves the processing it was dispatched by alone.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. Completion still runs before the error page when a later handler completes the processing.
| if (context.getErrorCode() <= 0 || asyncContext == null || !request.isAsyncStarted()) { | ||
| return; | ||
| } | ||
| if (asyncContext.isCompletedBeforeInitialRequestDone()) { |
There was a problem hiding this comment.
A first servlet dispatches to a second. The second starts asynchronous processing again and sends an error. A handler outside it then completes the processing. onComplete runs before the error page, because this checks completion before that later handler runs. Run completion after the error response.
There was a problem hiding this comment.
Fixed in 717f73c. It was worse than that: the handler then completed the processing a second time when the exchange ended, so the listeners heard ["onComplete", "errorPage", "onComplete"]. As soon as the servlet chain returns, the handler now sends the error through doErrorDispatch, clears it, and then completes the processing. Undertow tells the listeners once, after the error has been answered, and a later complete() from a handler outside is ignored. Undertow runs outer handler chain wrappers on a request dispatch only (DeploymentManagerImpl, PredicateHandler(DispatcherTypePredicate.REQUEST, outerHandlers, …)). On an asynchronous dispatch, the handler outside is an inner one that a deployment customizer adds after the factory's. Two new tests cover both and failed before: an outer handler that completes after a request dispatch, and a later inner one that completes after the asynchronous dispatch to /sendsError.
…es on Undertow The handler decided whether the processing was completed as soon as the servlet chain returned. A handler outside it, such as an outer handler on a request dispatch or an inner one added later by a deployment customizer, could still complete it before Undertow sent the error. Undertow then told the listeners before the error page ran, and the handler's own completion told them a second time once the exchange ended. The handler now sends the error, and clears it, as soon as the servlet chain has returned, and then completes the processing, so Undertow tells the listeners once, after the error has been answered, and a later completion is ignored.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. Completion still runs before the error page when a later handler forwards and then completes.
| HttpServletRequestImpl request = context.getOriginalRequest(); | ||
| AsyncContextImpl asyncContext = request.getAsyncContextInternal(); | ||
| // An asynchronous dispatch that did not start the processing again finds the processing it was dispatched by | ||
| if (context.getErrorCode() <= 0 || asyncContext == null || !request.isAsyncStarted()) { |
There was a problem hiding this comment.
A servlet starts asynchronous processing again and returns. A later handler forwards to a servlet that sends an error, then completes. onComplete runs before the error page, because this has already returned before that forward. Run completion after the error response.
There was a problem hiding this comment.
Fixed in c2262ef and 43263b7. Instead of chasing each handler that can sit outside this one, the handler is now added at the last point before Undertow builds its handler chains. The factory adds a servlet extension after its customizers. That extension adds a servlet container initializer, and the initializer adds a context listener that adds the handlers once every other listener has been told the context is initialized. So the handler wraps every handler that customizers, servlet extensions, servlet container initializers (Spring Boot's ServletContextInitializers among them) and context listeners add. On a request dispatch it's the outermost outer handler, and on an asynchronous one the outermost inner handler, since Undertow runs outer handlers on request dispatches only. Only Undertow's own handlers stay around it, and none of them sends an error, forwards or completes once the handlers it wraps have returned. New tests forward to a servlet that sends an error and then complete, from handlers each of those adds, after a request dispatch and after an asynchronous one. Each got ["onComplete", "errorPage"] before.
…s returned The handler acted once the servlet chain inside it returned, but any handler a deployment customizer or a servlet extension added sat outside it, and could still forward to a servlet that sends an error, or complete the processing, after it had returned. Undertow then told the listeners before the error page ran. The factory now adds the handler from a servlet extension it adds after its customizers, which runs after every other extension, so the handler wraps every handler they add: as the outermost outer handler on a request dispatch, since Undertow runs outer handlers on request dispatches only, and as the outermost inner handler on an asynchronous one. Only Undertow's own handlers remain around it, and none of those sends an error, forwards or completes the processing once the handlers it wraps have returned.
Undertow builds its handler chains only after the servlet container initializers, Spring Boot's among them, and the context listeners have run, and both can still add handlers then. A handler one of them added sat outside the async error handler, and a forward to an error and a completion from it again told the listeners before the error page ran. The servlet extension now adds a servlet container initializer, which runs after every other one, and that adds a listener, which is told the context was initialized after every other listener, and only that listener adds the handlers. A dispatch that dispatches the processing after sending its error now leaves the completion to the dispatch it asked for: without an error page, completing it told the listeners before that dispatch ran. The tests that forward to an error from handlers around the dispatch now run one request per server, for a request and for an asynchronous dispatch, so that a late callback of one request cannot be counted for the other or cleared away.
…ends An application on Undertow whose request starts asynchronous processing and then sends an error now hears onComplete once the error has been answered. Before, the processing stayed open when an error page answered the error, and otherwise timed out with onTimeout and then onComplete.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A handler added after this one still completes before the error page.
|
|
||
| @Override | ||
| public void contextInitialized(ServletContextEvent event) { | ||
| deployment.addOuterHandlerChainWrapper( |
There was a problem hiding this comment.
A servlet extension adds a handler outside this one. That handler forwards to a servlet that sends an error, then completes. onComplete runs before the error page, because this handler is registered before that later one. Wrap the handlers that are added after it too.
There was a problem hiding this comment.
This handler isn't registered by the servlet extension itself any more. Since 43263b7 the extension only adds a servlet container initializer, which adds a context listener, and the handlers are added in that listener's contextInitialized (line 86). Undertow runs every servlet extension (ServiceLoader, ServletExtensionHolder, then the deployment's own) in DeploymentManagerImpl.handleExtensions, before the servlet container initializers and well before contextInitialized. So whatever an extension adds is added before this handler and ends up inside it. processingCompletesOnceTheErrorPageHasAnsweredAnErrorAHandlerAServletExtensionAddedForwardedTo is your case: an extension adds handlers that forward to a servlet that sends an error and then complete, after a request dispatch and after an asynchronous one. It passes at 35c1a79. c78878b adds the two other ways an extension can add them: through ServletExtensionHolder, and from a context listener it adds, which is the latest an extension can add one. Both pass. The listener variant got ["onComplete", "errorPage"] with the handler of c2262ef, before 43263b7.
A servlet extension registered with Undertow's ServletExtensionHolder runs before the ones a deployment lists, and one can also add a context listener that adds its handlers once the context is initialized. Both now forward to an error and complete the processing in a test, after a request dispatch and after an asynchronous one. The listener's handlers sat outside the async error handler until it was added from a listener of its own.
…atch, and once only Three more ways an error left the asynchronous processing open, or told its listeners at the wrong time, on Undertow: - An error a request listener sent, after the dispatch or before the request reached the handlers, was sent by Undertow outside them and left the processing open. A thread setup action now completes such processing once the dispatch has returned. - An asynchronous dispatch that started the processing again and sent an error completed the processing before it too, before Undertow told that processing's listeners it had started again, so a listener that followed it there was told the old processing completed and missed the new one. Its error is now sent, and the processing completed, in a task Undertow runs once it has told them. - A dispatch that sent an error and then dispatched the processing had the error sent at once and cleared, so the dispatch it asked for failed when it sent an error again, which Undertow otherwise ignores once an error has been sent. Undertow now sends that error once the dispatch has returned, and a later dispatch only keeps it from being sent again, by setting it aside until that dispatch has returned. The error the handler sends itself is set aside the same way and restored once the dispatch has returned.
The upgrade note covers an error the dispatch that started the processing sends, or a later asynchronous dispatch that started it again. An error sent from work that runs once the dispatch has returned is unchanged: without an error page it still reaches onTimeout.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A handler added from a servlet extension still completes before the error page.
| return; | ||
| } | ||
| this.next.handleRequest(exchange); | ||
| int errorCode = context.getErrorCode(); |
There was a problem hiding this comment.
A servlet extension adds a handler outside this one. That handler forwards to a servlet that sends an error, then completes. onComplete runs before the error page, because this checks for the error before that forward. Wrap the handlers that are added after it too.
There was a problem hiding this comment.
Fixed in e33d33f and 57f5c89. Two ways were still open, both while Undertow builds the chains. An inner handler can add an outer handler as Undertow wraps it, and so can a security handler or the initial security handler: Undertow wraps the inner handlers (DeploymentManagerImpl, line 224), then the security handlers and the initial security handler (327 and 446), and only then the outer handlers (230). This handler's outer instance is now added at the last of those wraps. With security disabled, that's as Undertow wraps this handler's inner instance, the last inner handler. Otherwise it's in a security handler added after every other one, or, when an initial security handler is set, once that one has wrapped. Undertow iterates each list as it wraps it, so nothing can be added after that. New tests: processingCompletesOnceTheErrorPageHasAnsweredAnErrorAHandlerAddedWhileTheChainsAreBuiltForwardedTo (an inner handler adds it) and processingCompletesOnceTheErrorPageHasAnsweredAnErrorAHandlerASecurityHandlerAddedForwardedTo (a security handler, and the initial security handler, add it). Each got ["onComplete", "errorPage"] on the request dispatch before.
There was a problem hiding this comment.
Following matrei's second round, ec7b1c3 takes these cases back out of this PR. Both handlers are registered from the factory's servlet extension again, without the initializer, listener and security-wrapper chain from e33d33f and 57f5c89. So a handler that a servlet container initializer, a context listener, a security handler or an inner handler adds while Undertow builds the chains sits outside it again. Grails adds no such handler on 8.0.x. undertow-io/undertow#2018 fixes the case in Undertow itself: ServletInitialHandler.handleFirstRequest sends the error before it checks for a completion, so it no longer matters where the handler that forwards and completes sits.
…een wrapped A servlet extension, or any code holding the deployment, could still add an outer handler while Undertow built the handler chains: Undertow wraps the inner chain first, and an inner handler can add an outer one as it is wrapped. That outer handler sat outside the async error handler on a request dispatch, and its forward to an error and its completion again told the listeners before the error page ran. The outer handler is now added as Undertow wraps the async error handler's inner one, which is the last inner handler, so every outer handler an inner one adds comes before it. Undertow iterates each list as it wraps it, so nothing can be added to a list after that.
…ast late handler routes - The error of an asynchronous dispatch that started the processing again is sent within that dispatch again, as Undertow sends any other. Sending it from a task after the dispatch ran the error page after request listeners had been told the request ended, outside Undertow's exception handling, on an executor that could refuse it, and while the processing could time out. Only completing processing no error page completed waits for Undertow to tell the processing before it that it started again. - Undertow wraps the security handlers and the initial security handler after the inner handlers and before the outer ones, so either could still add an outer handler outside this one. The outer handler is now added as Undertow makes its last wrap before the outer handlers. - The processing left open once a dispatch has returned is completed only when Undertow sent an error recorded outside the handlers, not for any ended response with an error status, which an application can write itself and keep processing for. - An error Undertow sent outside the handlers is recorded, so that a later dispatch the request asked for does not send it again.
…once When an asynchronous dispatch starts the processing again, Undertow completes the earlier processing as soon as the new one is completed, so its listeners can hear onComplete before the error page, as they do without an error.
fe583dd to
e792e17
Compare
undertow-io/undertow#2018 proposes sending a dispatch's error before the listeners are told, which also completes the processing an error page answered. Once Grails uses an Undertow release with it, the handler is needed only for what that change leaves open.
|
@matrei The Undertow fix is undertow-io/undertow#2018: |
matrei
left a comment
There was a problem hiding this comment.
Second round, at 90ef701 (base 8.0.x). It merges cleanly with today's 8.0.x (5bdcbc2).
Round 1's point is done: the Javadoc and the description say what each container does, and the async request timeout example is gone. Thanks.
The handler now does a lot more than in round 1. It sends the error itself. It wraps handlers that servlet container initializers, context listeners and security handlers add. A thread setup action runs after every request and asynchronous dispatch. As far as I can tell from Undertow's sources it's correct, but one part changes behaviour, and most of the rest is more than a patch branch should carry. See 1 and 2.
What I ran:
- Unit tests of
grails-undertow-spring-bootat the head: 107 tests, all pass. UndertowServletWebServerFactoryTests10 times: 46 tests each, all pass every time.- The new tests against round 1's handler and factory (3c13e38): 32 of the 46 fail.
- The tests with parts of the handler taken out, one at a time and then all together. See 1 and 2.
- The merge-up into 8.1.x and from there into 9.0.x, resolved as the description says. Then the module's tests and
UndertowFailedActionObservationSpecon the result. See 3. - The handler checked against the sources of undertow-servlet 2.0.3.
Before merge
1. Completing processing that no error page answered is a behaviour change. In round 1 I wrote that the fix needs no upgrade note on a patch branch. That holds for processing an error page answered, which never ended. It doesn't hold for an error that no error page maps to: Undertow ended that processing at the asynchronous timeout, as Tomcat does. I missed that the handler changes it.
The upgrade note you added says so (upgrading80x.adoc:509, SKILL.md:170): an application that cleans up in onTimeout has to move that to onComplete. A patch release shouldn't ask that.
On 8.0.x I'd leave that processing to Undertow. Two completions do it:
AsyncErrorCompletionHandler.java:194-203, once the handler has sent the error.:248-250, for an error Undertow sent from outside the handlers.
With both taken out, four tests fail, all of them the case without an error page:
asynchronousProcessingCompletesOnceAnErrorItsRequestDispatchSentIsAnsweredasynchronousProcessingCompletesOnceAnErrorItsAsynchronousDispatchSentIsAnsweredasynchronousProcessingStartedAgainCompletesOnceThePreviousProcessingHeardItStartedwitherrorPage = falseasynchronousProcessingARequestListenerStartsCompletesOnceTheErrorItSentIsAnsweredwitherrorPage = false
Every other test passes. What remains fixes two things: processing that never ended, and listeners told it completed before the error page had run. Neither needs a note, so both doc lines can go. The Javadoc's first paragraph (:41-47) would then say that the handler, too, leaves such processing to time out.
On 9.0.x the change is fine with a note. #17088 already put it there for a request dispatch, without one. So the merge-up would keep those lines and their four tests on 9.0.x. The note would go in upgrading90x.adoc, next to #17088's Undertow bullet.
2. Most of the new code is for configurations that no Grails application has. Two parts:
- The registration chain (
:102-149). A servlet extension adds a servlet container initializer, which adds a context listener, which adds the inner handler. To add the outer one, the inner handler adds a security handler or replaces the initial security handler. DispatchBoundary, a thread setup action that runs after every request and asynchronous dispatch (:103,:211-253).
I took each out to see which tests need it:
- Both handlers registered from the servlet extension itself, with
addInnerHandlerChainWrapperandaddOuterHandlerinaddTo: 9 tests fail. In each, a handler that forwards to a servlet that sends an error, and then completes, is added by one of these:- a servlet container initializer
- a context listener, including one that a servlet extension adds
- a security handler or the initial security handler
- an inner handler, while Undertow builds the chains
- Without
DispatchBoundary: 5 tests fail. In each, a request listener sends the error or starts the processing. - Both changes, plus the one from 1: 29 of the 46 pass. The 17 that fail are exactly these groups and the four from 1.
Registered from the servlet extension, the handler still wraps every handler that customizers and servlet extensions add. On 8.0.x, Grails' factory adds no handler but this one. Spring Boot's ServletContextInitializers get the ServletContext, not the DeploymentInfo, so they can't add one. Grails registers no request listener either.
undertow-io/undertow#2018 fixes every one of these cases in handleFirstRequest, wherever the handler sits. For a patch branch, I'd keep only the two handlers, registered from the servlet extension. That means no initializer, no listener, no security wrappers and no DispatchBoundary. The remaining cases would wait for #2018. That also leaves less to remove once Grails uses an Undertow release with it. James's last point is one of those cases. I'd answer it with #2018 rather than with more code here.
Notes
3. Merge-up into 9.0.x. It merges cleanly into 8.1.x. From there into 9.0.x, the conflicts aren't the ones the description lists:
grails-upgrade/SKILL.mdconflicts. 9.0.x's skill starts from Grails 8, so take its side.- The factory merges without a conflict. It keeps 9.0.x's
addInnerHandlerChainWrapper(AsyncErrorCompletionHandler::new)(UndertowServletWebServerFactory.java:251on 9.0.x), which doesn't compile against this handler. It still has to go, but git won't stop on it. - The handler and the tests conflict as described.
I resolved it as the description says:
- the handler from this side
- both sides of the tests
- 9.0.x's skill
- the factory line removed
With that, the module's 108 tests pass on 9.0.x, and so do the 26 tests of UndertowFailedActionObservationSpec. With 1, the handler on 9.0.x also keeps the two completions, so the handler can no longer simply be taken from this side.
Verified as correct
- The order the handler relies on, in
DeploymentManagerImpl.deploy:- The servlet extensions run (
:157) before Undertow collects the thread setup actions (:159-163) and runs the servlet container initializers (:202). - The listeners hear
contextInitialized(:220) before the inner handlers are wrapped (:224). - The security wrappers are applied (
:327) before the initial security wrapper is read (:342). - The outer handlers are wrapped last (
:230). SendErrorPageHandler(:231) sends an error before its chain runs, not after it.
- The servlet extensions run (
DispatchBoundaryacts on request and asynchronous dispatches only. The only thread setup action whose context is aServletRequestContextisServletInitialHandler's first-request handler (ServletInitialHandler.java:128).- The handler's
doErrorDispatchruns inside the sametryofhandleFirstRequestas Undertow's own (:276-286). So an error page that throws is handled as before. - Each part of the handler has tests that fail without it. See 1 and 2.
- undertow-io/undertow#2018 moves the
doErrorDispatchinhandleFirstRequestahead of the completion check, which is what this handler's core does. It's open. - CI: 88 checks pass, 9 skipped.
Processing that no error page answered is left to Undertow again, which ends it at the asynchronous timeout, as Tomcat does: completing it changed when an application's listeners heard onTimeout, which a patch release should not ask applications to adapt to. The handler now sends a dispatch's error itself only when the processing ends then, because the dispatch completed it or an error page answers the error and its error dispatch completes it, and leaves anything else, error and processing both, to Undertow. The upgrade guide and the grails-upgrade skill no longer need a note for it. Both handlers are registered from the factory's servlet extension again, around the handlers its customizers and servlet extensions add, without the servlet container initializer, context listener, security wrappers and dispatch-boundary thread setup action that reached handlers and request listeners Grails does not add. undertow-io/undertow#2018 fixes those cases in Undertow, wherever the handler sits.
|
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. Completing a second cycle still tells the first cycle it is done before the error page runs.
| this.next.handleRequest(exchange); | ||
| return; | ||
| } | ||
| this.next.handleRequest(exchange); |
There was a problem hiding this comment.
A request starts asynchronous processing and dispatches. The next servlet starts it again, sends an error, and completes. The first cycle is told it is done before the error page runs, because this checks for the error only after that call returns. Run the error page first.
There was a problem hiding this comment.
This one comes from the servlet's own complete() call, not from where this handler checks for the error. AsyncContextImpl.complete() completes the processing it was started again over (lines 256-257), and that processing was dispatched, so it tells its listeners at once (lines 253-254). That happens inside the servlet's call, before the dispatch returns to any handler. Your case, measured: with the handler [first:onComplete, errorPage, onComplete, first:onStartAsync], with Undertow alone [first:onComplete, onComplete, errorPage, first:onStartAsync]. The handler moves the second cycle's onComplete after the error page, which processingAnAsynchronousDispatchCompletesAfterSendingAnErrorCompletesOnceTheErrorPageHasAnsweredIt covers. The first cycle is told when the application completes the processing, with or without an error, and undertow-io/undertow#2018 doesn't change that either. The description lists it under what stays as Undertow does it.
…-error-completion-8.0.x
The listener the Undertow factory tests record events with now says when Undertow tells it the processing completed before the response was sent. A dispatch that sends an error and completes the processing itself, with no error page, gave a 503 and one onComplete with or without the async error handler, so its test could not tell the handler had sent the error first. Without the handler it now records the completion as coming before the response. A sent error sets the response's status and marks it committed before the error is sent, so the listener reads whether the exchange has ended. With an error page and a dispatch the request asked for, Undertow's own error dispatch still completes the processing before the response, as the test of that case now records.
This comment has been minimized.
This comment has been minimized.
matrei
left a comment
There was a problem hiding this comment.
Third round, at a40203a (base 8.0.x). It's on today's 8.0.x head (60ab3df), so it merges cleanly. Against 8.0.x it still changes only the handler, the factory and the tests.
Round 2's three points are done:
- Processing whose error no error page maps to is left to the asynchronous timeout again. The tests check
onTimeoutand thenonComplete, the lines inupgrading80x.adocand the skill are gone, and the Javadoc says the handler leaves such processing too (AsyncErrorCompletionHandler.java:37-38). - Both handlers are added from the servlet extension (
:81-84). The initializer, listener and security-wrapper chain andDispatchBoundaryare gone, and the handler is down to 126 lines. - The description's merge-up section matches what git does. See 1 for keeping #17088's completion on 9.0.x.
a40203a also pins the one part of the handler no test needed at ec7b1c3: the isCompletedBeforeInitialRequestDone() half of :118, for a dispatch that completes the processing after sending an error no error page maps to. Thanks, and thanks for answering James's point with undertow-io/undertow#2018.
What I ran:
- At the head, with the build cache off: the 92 tests of
grails-undertow-spring-bootand the 29 integration tests of the Undertow test app, all pass. UndertowServletWebServerFactoryTests10 times: 33 tests each, all pass every time.- The factory without the handler: 17 of the 33 fail. That's one more than at ec7b1c3:
asynchronousProcessingThatADispatchCompletesAfterSendingAnErrorCompletesOncenow hearsonComplete before the response. - The handler with each of its parts taken out in turn:
- no outer handler: 9 fail
- no inner handler: 10 fail
- the error not cleared before the handler sends it (
:122): 15 fail, with every listener hearingonCompletetwice - no error-page check, so only processing the dispatch completed: 4 fail
- the marker for a dispatched error not set (
:112), or not read (:99-103): 2 fail each, the two tests that dispatch after sending an error :118reduced to!answeredByAnErrorPage: 1 fails, the test a40203a pins. At ec7b1c3 none did.
- James's case from his last review, with a temporary test, three times with the handler and three times without. See "Verified as correct".
- The merge-up into today's 8.1.x and from there into today's 9.0.x, resolved to keep #17088's completion there. Then the module's tests and
UndertowFailedActionObservationSpecon the result. See 1. - The handler checked against the sources of undertow-servlet 2.0.3 again, and against undertow-io/undertow#2018.
CI: 89 checks pass, 9 skipped.
Notes
1. Merge-up into 9.0.x. It goes as the description says:
- The merge into 8.1.x is clean.
- From 8.1.x into 9.0.x, only the handler and the tests conflict.
- The factory merges silently with 9.0.x's line 251, which has to go.
The test conflict shows the choice. 9.0.x's asynchronousProcessingCompletesOnceAnErrorItsRequestDispatchSentIsAnswered expects onComplete, where this side's ...NoErrorPageMapsIsLeftToTheAsynchronousTimeout expects onTimeout, onComplete.
To keep #17088's completion, I took the handler from this side and replaced :115-123 with:
String errorMessage = context.getErrorMessage();
context.setError(-1, null);
context.getOriginalResponse().doErrorDispatch(errorCode, errorMessage);
// The error dispatch completes the processing once an error page has run, and nothing completes it otherwise
asyncContext.complete();How that works:
complete()ignores processing that is already completed (AsyncContextImpl.java:242-245).- Inside the dispatch, it only marks the processing completed (
:263-264). - Undertow then tells the listeners once the dispatch has returned, after the error was written.
In the tests I kept:
- 9.0.x's imports and its dispatcher-type test
- the two no-error-page tests back at
onComplete, with 9.0.x's name for the request-dispatch one
The errorPage = false row of aListenerThatFollowsAsynchronousProcessingStartedAgainHearsItEndOnce then hears first:onComplete, onComplete, first:onStartAsync. That's the order of the error-page row, as the description says.
With that, the module's 93 tests pass on 9.0.x, and so do the 27 tests of UndertowFailedActionObservationSpec. a40203a applies to that resolution without a change. With its listener, the two no-error-page tests there now also check that the listeners hear onComplete after the error was written.
Completing asynchronous dispatches too goes beyond #17088, so the upgrading90x.adoc note the description mentions is still needed. The first paragraph of the Javadoc (:37-38) also has to say what 9.0.x does.
2. Optional: the asynchronous dispatch's twin of the test a40203a pins. The description lists, for a request dispatch and for an asynchronous dispatch that starts the processing again, that "a dispatch that completes the processing after sending the error has its listeners hear onComplete once, after the error has been sent, through the error page or without one". Without an error page, only the request dispatch has a test. A temporary test through dispatchesAsynchronously(), with sendsErrorAfterStartingAsync(events, true) and no error page, gets a 503 and onComplete with the handler, and onComplete before the response without it. A /dispatches variant of asynchronousProcessingThatADispatchCompletesAfterSendingAnErrorCompletesOnce would pin the inner handler for that case too.
3. Nit: a leftover test parameter. assertCompletesOnceTheErrorPageHasAnswered (UndertowServletWebServerFactoryTests.java:652-663) still takes ServletContextInitializer... initializers. Only the removed initializer and listener tests passed any. Without it, getWebServer can take the four registrations directly, and the java.util.ArrayList and java.util.Arrays imports go too.
Verified as correct
- James's point on
:94doesn't hold for this PR. The earlier processing hearsonCompletebefore the error page runs, but that's Undertow's own, and no handler around the dispatch can move it:- The servlet's
complete()on the new processing also completes the processing before it (AsyncContextImpl.java:256-257). - That processing was dispatched, so its listeners are told at once (
:253-254). That happens inside the servlet's call, before the dispatch returns to any handler. - His case is:
/firststarts the processing and dispatches, then/sendsErrorstarts it again, sends a503and completes it, with an error page. With the handler, the listeners hearfirst:onComplete before the response,errorPage,onComplete,first:onStartAsync. Without it, they hearfirst:onComplete before the response,onComplete before the response,errorPage,first:onStartAsync. All three runs each way gave the same. - So the handler moves the new processing's
onCompleteafter the error page, as you measured, and leaves the earlier processing as Undertow has it. - undertow-io/undertow#2018 only moves the error dispatch in
ServletInitialHandler.handleFirstRequest, so it leaves that order too. Running the error page first would mean sending the error from insidecomplete(). - The description lists this under what stays as Undertow does it (third bullet).
- The servlet's
- The listener's new check,
isResponseComplete(), matches what Undertow does. It tells the listeners of processing completed during the dispatch atServletInitialHandler.java:279-282, after the handler'sdoErrorDispatchhas ended the response (HttpServletResponseImpl.java:182). Only Undertow's own error dispatch completes dispatched processing before that: in itsfinally(RequestDispatcherImpl.java:422-426), which tells the listeners at once (AsyncContextImpl.java:253-254). That's theonComplete before the responsethatasynchronousProcessingADispatchDispatchesAfterSendingAnErrorAnErrorPageAnswersCompletesOncenow records. - What the handler relies on, in undertow-servlet 2.0.3:
handleFirstRequesttells the listeners of processing completed during the dispatch (ServletInitialHandler.java:279-282) before it sends the error (:284-286). The handler runs insidenext.handleRequest(:278), so an error it sends comes first.- The error dispatch completes the processing in its
finally(RequestDispatcherImpl.java:422-426). Inside the dispatch that only marks it completed, and Undertow tells the listeners at:279-282. That is the fix for processing an error page answered. - The error code stays set for the dispatch the processing was dispatched to. A second
sendErroris ignored once the response has started (HttpServletResponseImpl.java:135-137). So clearing the error code there (:99-103) is what keeps Undertow from sending the error again.
- The extension is added after the customizers (
UndertowServletWebServerFactory.java:256). Undertow runs a deployment's own extensions after theServiceLoaderandServletExtensionHolderones (DeploymentManagerImpl.java:281-304). So the handlers wrap what all of them add, and the tests cover a customizer, a deployment's extension and a held extension. - Sending the error from the handler also when nothing completes the processing fails no test. That's expected: without an error page, Undertow sends the same response, and the processing still times out. Leaving it to Undertow keeps the order as it was.
- Without the
isAsyncStarted()check (:107), an asynchronous dispatch that didn't start the processing again only gets the marker, which no later dispatch reads. So it changes nothing either, and the check makes the intent explicit.
…rror, with no error page The request dispatch had a test that the handler sends the error before Undertow tells the listeners of processing the dispatch completed; the asynchronous dispatch that starts the processing again now has one too. Without the handler, its listeners hear onComplete before the response. Also drop the initializers parameter of the error page assertion, which nothing passes since the initializer and listener tests went, and the imports only it used.
|
only requested nit/test changes after approval |
AbstractDetachedCriteria.clone() keeps 8.1.x's cloned variable and also copies the superseded join types that 8.0.x added. The Hibernate 5 sections of the upgrade skill's Grails 8.0.1 part go before its Grails 8.1.0 part, so the skill stays in release order. This merge moves org.json to 20260814, managed in grails-bom, as #17194 did on 7.x: 8.1.x resolved the same 20251224 through jedis 7.4.1 as 8.0.x. Merge-up advice followed: - #17100: the merge into 8.1.x is clean, as its description says. - #17203: the SBOMs of the root, grails-gradle and grails-forge builds were generated again with CycloneDX 3.6.1, and every license check passes. - #17095: the change of the asynchronous worker cleanup comes along as is.
The Hibernate 5 sort and join changes of 7.0.x meet #17074 here. AbstractHibernateQuery takes the 7.0.x code, where orders are applied when the query runs, with #17074's rejection of a sort by an alias the query does not define in applyOrder; GrailsHibernateUtil and GrailsHibernateQueryUtils merge with the rejection in place. UndefinedAliasSortSpec is 9.0.x's, with the entities the 7.0.x spec registers. SbomPlugin keeps 9.0.x's JLine 4 handling and takes #17203's license names; two 9.0.x SbomPluginSpec features read the license under the key license, as #17203's wrapper writes it. GrailsAsyncContext and its spec keep 9.0.x's code and take the comment and the feature #17095's review added on 7.0.x, since #17124 is still open. The upgrade skill keeps 9.0.x's side, as in #17156. This merge moves org.json to 20260814, managed in grails-bom, as #17194 did on 7.x; jedis 8.0.2 pulls 20260719 on 9.0.x, and the SBOM plugin maps 20260814 in place of 20260719, and its SbomPluginSpec feature for org.json names 20260814. Merge-up advice followed: - #17100: the factory no longer adds 9.0.x's inner AsyncErrorCompletionHandler that does not compile against the merged handler. The handler is 8.0.x's, completing the processing once it has sent the error, so 9.0.x keeps #17088's completion of processing no error page answers (matrei's resolution); its Javadoc says so. UndertowServletWebServerFactoryTests keeps 9.0.x's imports, its dispatcher-type test and its request-dispatch test, and adds 8.0.x's tests, with the no-error-page tests expecting onComplete. upgrading90x.adoc gets a note next to #17088's Undertow bullet. - #17100 (matrei's review): the upgrade skill takes 9.0.x's side. - #17074: the resolution is the 7.0.x code plus the rejection; the reference branch carries parts 10 to 13 as well, which 7.0.x does not have, so the rejection is applied to the code 7.0.x has. A sort by an invalid association property, such as club.unknown, keeps 9.0.x's Invalid sort property. - #17095: 9.0.x already has the change. - #17203: the SBOMs of the root, grails-gradle and grails-forge builds were generated again with CycloneDX 3.6.1.
On Undertow, a request or asynchronous dispatch that starts asynchronous processing and then sends an error, which an error page answers, leaves that processing open forever. Spring MVC sends such an error for a server error it resolves, for example a 503
ResponseStatusException, and Spring Boot registers an error page for a Spring MVC application.Undertow sends the error, through the error page that maps to it, after the dispatch has returned. Its error dispatch completes the processing, but too late for Undertow to tell the listeners, and the processing then never times out either. So its
AsyncListeners never hearonComplete:ServerHttpObservationFilternever stops its observation of the request, and the completion callbacks of aDeferredResultnever run. A plain servlet reproduces it:When the dispatch, or a handler around it, completes the processing after sending the error, Undertow tells the listeners once the dispatch has returned and only then sends the error. So they hear
onCompletebefore the error page runs.AsyncErrorCompletionHandlerfixes both. Once the handlers of aREQUESTorASYNCdispatch have returned, the processing the dispatch started may still be open with an error sent. If the dispatch completed the processing, or an error page maps the error, the handler sends the error itself throughdoErrorDispatchand sets it aside, so Undertow doesn't send it again. Undertow then tells the listeners once the dispatch has returned, after the error has been answered. Processing whose error no error page maps to is left to Undertow, which ends it at the asynchronous timeout, as Tomcat does, so the listeners hearonTimeoutas they did before.The factory adds the handler from a servlet extension it adds after its
UndertowDeploymentInfoCustomizers, so it wraps the handlers the customizers and servlet extensions add. Undertow runs outer handlers on request dispatches only, so a request dispatch is handled by an outer handler, and an asynchronous dispatch by an inner one.A dispatch that sends an error and then dispatches the processing leaves it to Undertow to send that error, once, and the completion to the dispatch it asked for. That dispatch only keeps the error from being sent a second time.
undertow-io/undertow#2018 fixes both in Undertow itself:
ServletInitialHandler.handleFirstRequestsends the error before it checks for a completion. Once Grails uses an Undertow release with it, the handler is needed only to keep a dispatched request's error from being sent twice.What stays as Undertow does it, with or without this handler:
onCompletebeforeonStartAsync, as it does without an error.onCompletebefore that dispatch runs.This doesn't depend on Spring Framework 7.1. On 9.0.x the request-dispatch completion shipped in #17088, and the review there asked for it on 8.0.x too (the
grails-undertowservlet package is identical on both branches). On 9.0.x the handler from #17088 also completes processing that no error page answered, which belongs there with a note inupgrading90x.adoc. The merge-up into 8.1.x is clean. From there into 9.0.x:addInnerHandlerChainWrapper(AsyncErrorCompletionHandler::new), which doesn't compile against this handler. Remove it.AsyncErrorCompletionHandler, which both branches add: take this side, and keep completing processing that no error page answered if 9.0.x is to keep it.UndertowServletWebServerFactoryTests: keep both sides, 9.0.x's imports and dispatcher-type test plus the tests here.Tests, in
UndertowServletWebServerFactoryTests, for a request dispatch and for an asynchronous dispatch that starts the processing again:onTimeoutand thenonComplete.onCompleteonce, after the error has been sent, through the error page or without one. The tests record a completion Undertow tells the listeners of before it has sent the response as such.ServletExtensionHolder.onCompletebefore the response, then the dispatch.