jamesfredley commented on code in PR #16786:
URL: https://github.com/apache/grails-core/pull/16786#discussion_r4411573883


##########
grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/CompletedHttpServletRequest.groovy:
##########
@@ -0,0 +1,1119 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.grails.plugins.web.async
+
+import java.nio.charset.Charset
+import java.nio.charset.StandardCharsets
+import java.security.Principal
+import java.text.ParseException
+import java.text.SimpleDateFormat
+import java.util.concurrent.ConcurrentHashMap
+
+import groovy.transform.CompileStatic
+
+import jakarta.servlet.AsyncContext
+import jakarta.servlet.DispatcherType
+import jakarta.servlet.ReadListener
+import jakarta.servlet.RequestDispatcher
+import jakarta.servlet.ServletConnection
+import jakarta.servlet.ServletContext
+import jakarta.servlet.ServletInputStream
+import jakarta.servlet.ServletRequest
+import jakarta.servlet.ServletRequestWrapper
+import jakarta.servlet.ServletResponse
+import jakarta.servlet.http.Cookie
+import jakarta.servlet.http.HttpServletMapping
+import jakarta.servlet.http.HttpServletRequest
+import jakarta.servlet.http.HttpServletResponse
+import jakarta.servlet.http.HttpSession
+import jakarta.servlet.http.HttpUpgradeHandler
+import jakarta.servlet.http.MappingMatch
+import jakarta.servlet.http.Part
+
+import org.springframework.http.HttpHeaders
+import org.springframework.http.HttpMethod
+import org.springframework.util.LinkedCaseInsensitiveMap
+import org.springframework.util.LinkedMultiValueMap
+import org.springframework.util.MultiValueMap
+import org.springframework.web.context.request.RequestAttributes
+import org.springframework.web.multipart.MultipartFile
+import org.springframework.web.multipart.MultipartHttpServletRequest
+
+import org.grails.web.util.WebUtils
+
+/**
+ * A copy of a request, taken as the request completed, which a task that 
outlives the request reads in its place.
+ *
+ * <p>The container recycles a request once it completes, so a task that read 
the request itself from then on
+ * would fail. As the request completes, a copy is taken of each request its 
tasks were given, such as the request
+ * and the request of a forward, and each task reads the copy of its request 
through a {@link #newView view} of its
+ * own, so each has the part of the body nothing had read, served through one 
stream or reader whose position
+ * persists, as the live request serves it. A copy holds the attributes, 
parameters, headers, locales and cookies of
+ * its request, the session and what identifies the request. The request, its 
response and what holds either, such
+ * as the web request of the request thread, are not carried over, so the copy 
holds nothing the container recycles.
+ * What only the live request can do, such as dispatching, processing 
asynchronously, creating a session or checking
+ * a role, is not available.</p>
+ *
+ * <p>The copies share the attributes of the request the container created and 
the body, as the requests share
+ * them, so attributes a task sets stay with the copies, shared by every task. 
What a request keeps itself, such as
+ * the forward attributes of the request a forward dispatched, stays with its 
own copy, as do the attributes it
+ * hides, and setting or removing one of them changes that copy only, as on 
the request.</p>
+ *
+ * <p>The parameters are those of the request. A multipart body the container 
could not parse leaves the copy
+ * without parameters, as params has none, and any other failure to read them 
is thrown to a task that reads them,
+ * as the live request throws it.</p>
+ *
+ * <p>The uploads of a multipart request are deleted as the request ends, so 
the copy answers as a multipart
+ * request without uploads when the request was a multipart request, and a 
copy of a multipart request an attribute
+ * held, such as the one the dispatcher resolved, takes its place, with its 
parameters, such as the text fields only
+ * it has. Reading params then finds the parameters it found on the live 
request and no uploads.</p>
+ *
+ * <p>The body is kept up to {@value #BODY_LIMIT} bytes. Reading a longer one 
from the copy throws, so the copy is
+ * not what holds an upload that was never read in memory. The body of a 
multipart request is not kept: its uploads
+ * go with the request, and its text fields are in the parameters.</p>
+ *
+ * @since 8.0.1
+ */
+@CompileStatic
+class CompletedHttpServletRequest implements MultipartHttpServletRequest {
+
+    /**
+     * The longest body, in bytes, a copy keeps: what remains of a longer one 
is not read.
+     */
+    static final int BODY_LIMIT = 2 * 1024 * 1024
+
+    private static final byte[] NO_BODY = new byte[0]
+    private static final int READ_CHUNK = 8192
+    // An attribute the request of a copy hides, though the request the 
container created has it
+    private static final Object HIDDEN = new Object()
+    private static final List<String> DATE_HEADER_FORMS = List.of(
+            'EEE, dd MMM yyyy HH:mm:ss zzz',
+            'EEEE, dd-MMM-yy HH:mm:ss zzz',
+            'EEE MMM dd HH:mm:ss yyyy')
+
+    private final Map<String, Object> attributes
+    private final Map<String, Object> ownAttributes
+    // Null when the body was longer than the copy keeps
+    private final byte[] body
+    private final Map<String, String[]> parameters
+    private final RuntimeException parameterFailure
+    private final Map<String, List<String>> headers
+    private final List<Locale> locales
+    private final Cookie[] cookies
+    private final HttpSession session
+    private final ServletContext servletContext
+    private final Principal userPrincipal
+    private final DispatcherType dispatcherType
+    private final HttpServletMapping httpServletMapping
+    private final ServletConnection servletConnection
+    private final String authType
+    private final String contentType
+    private final long contentLength
+    private final String method
+    private final String requestURI
+    private final String requestURL
+    private final String queryString
+    private final String contextPath
+    private final String servletPath
+    private final String pathInfo
+    private final String pathTranslated
+    private final String protocol
+    private final String scheme
+    private final String serverName
+    private final int serverPort
+    private final boolean secure
+    private final String remoteAddr
+    private final String remoteHost
+    private final int remotePort
+    private final String localName
+    private final String localAddr
+    private final int localPort
+    private final String remoteUser
+    private final String requestedSessionId
+    private final boolean requestedSessionIdValid
+    private final boolean requestedSessionIdFromCookie
+    private final boolean requestedSessionIdFromURL
+    private final String requestId
+    private final String protocolRequestId
+    private volatile String characterEncoding
+    private ServletInputStream inputStream
+    private BufferedReader reader
+
+    private CompletedHttpServletRequest(HttpServletRequest request, 
Map<String, Object> attributes,
+            Map<String, Object> ownAttributes, CopiedParameters parameters, 
byte[] body) {
+        this.attributes = attributes
+        this.ownAttributes = ownAttributes
+        this.parameters = parameters.values
+        this.parameterFailure = parameters.failure
+        this.body = body
+        Map<String, List<String>> headers = new 
LinkedCaseInsensitiveMap<>(Locale.ENGLISH)
+        for (String name : Collections.list(request.headerNames)) {
+            headers.put(name, 
Collections.unmodifiableList(Collections.list(request.getHeaders(name))))
+        }
+        this.headers = Collections.unmodifiableMap(headers)
+        this.locales = 
Collections.unmodifiableList(Collections.list(request.locales))
+        this.cookies = copyCookies(request.cookies)
+        this.session = request.getSession(false)
+        this.servletContext = request.servletContext
+        this.userPrincipal = request.userPrincipal
+        this.dispatcherType = request.dispatcherType
+        // Values only: the container's own objects can reference the request 
it recycles
+        this.httpServletMapping = copyMapping(request.httpServletMapping)
+        this.servletConnection = copyConnection(request.servletConnection)
+        this.authType = request.authType
+        this.characterEncoding = request.characterEncoding
+        this.contentType = request.contentType
+        this.contentLength = request.contentLengthLong
+        this.method = request.method
+        this.requestURI = request.requestURI
+        this.requestURL = request.requestURL?.toString()
+        this.queryString = request.queryString
+        this.contextPath = request.contextPath
+        this.servletPath = request.servletPath
+        this.pathInfo = request.pathInfo
+        this.pathTranslated = request.pathTranslated
+        this.protocol = request.protocol
+        this.scheme = request.scheme
+        this.serverName = request.serverName
+        this.serverPort = request.serverPort
+        this.secure = request.secure
+        this.remoteAddr = request.remoteAddr
+        this.remoteHost = request.remoteHost
+        this.remotePort = request.remotePort
+        this.localName = request.localName
+        this.localAddr = request.localAddr
+        this.localPort = request.localPort
+        this.remoteUser = request.remoteUser
+        this.requestedSessionId = request.requestedSessionId
+        this.requestedSessionIdValid = request.requestedSessionIdValid
+        this.requestedSessionIdFromCookie = 
request.requestedSessionIdFromCookie
+        this.requestedSessionIdFromURL = request.requestedSessionIdFromURL
+        this.requestId = request.requestId
+        this.protocolRequestId = request.protocolRequestId
+    }
+
+    // Field by field: the getters serve tasks, so some, such as getSession 
and getLocales, do not return the field
+    private CompletedHttpServletRequest(CompletedHttpServletRequest copy) {
+        this.attributes = copy.@attributes
+        this.ownAttributes = copy.@ownAttributes
+        this.body = copy.@body
+        this.parameters = copy.@parameters
+        this.parameterFailure = copy.@parameterFailure
+        this.headers = copy.@headers
+        this.locales = copy.@locales
+        this.cookies = copy.@cookies
+        this.session = copy.@session
+        this.servletContext = copy.@servletContext
+        this.userPrincipal = copy.@userPrincipal
+        this.dispatcherType = copy.@dispatcherType
+        this.httpServletMapping = copy.@httpServletMapping
+        this.servletConnection = copy.@servletConnection
+        this.authType = copy.@authType
+        this.characterEncoding = copy.@characterEncoding
+        this.contentType = copy.@contentType
+        this.contentLength = copy.@contentLength
+        this.method = copy.@method
+        this.requestURI = copy.@requestURI
+        this.requestURL = copy.@requestURL
+        this.queryString = copy.@queryString
+        this.contextPath = copy.@contextPath
+        this.servletPath = copy.@servletPath
+        this.pathInfo = copy.@pathInfo
+        this.pathTranslated = copy.@pathTranslated
+        this.protocol = copy.@protocol
+        this.scheme = copy.@scheme
+        this.serverName = copy.@serverName
+        this.serverPort = copy.@serverPort
+        this.secure = copy.@secure
+        this.remoteAddr = copy.@remoteAddr
+        this.remoteHost = copy.@remoteHost
+        this.remotePort = copy.@remotePort
+        this.localName = copy.@localName
+        this.localAddr = copy.@localAddr
+        this.localPort = copy.@localPort
+        this.remoteUser = copy.@remoteUser
+        this.requestedSessionId = copy.@requestedSessionId
+        this.requestedSessionIdValid = copy.@requestedSessionIdValid
+        this.requestedSessionIdFromCookie = copy.@requestedSessionIdFromCookie
+        this.requestedSessionIdFromURL = copy.@requestedSessionIdFromURL
+        this.requestId = copy.@requestId
+        this.protocolRequestId = copy.@protocolRequestId
+    }
+
+    /**
+     * Copies the requests the tasks of a request that is completing were 
given: the request, and any other request
+     * a later task was given, such as the request of a forward. It has to be 
called before the container recycles
+     * the request. Each copy holds what its request shows, and the copies 
share the attributes of the request the
+     * container created and the body, as the requests share them.
+     *
+     * @param requests the requests, each the request the container created or 
a wrapper of it, the first being the
+     *        one whose body the copies share
+     * @return the copies, in the order of the requests, with {@code null} for 
a request after the first that could
+     *         not be copied
+     */
+    static List<CompletedHttpServletRequest> copyOf(List<HttpServletRequest> 
requests) {
+        Map<String, Object> underlying = 
attributesOf(TaskRequest.underlying(requests.get(0)))
+        // The requests to copy: those given, then each multipart request an 
attribute holds, such as the one the
+        // dispatcher resolved, which wraps the request, so its copy, which 
has no uploads either, takes its place
+        List<HttpServletRequest> copied = new ArrayList<>(requests)
+        Map<Object, Integer> multipartRequests = new IdentityHashMap<>()
+        for (int i = 0; i < requests.size(); i++) {
+            if (requests.get(i) instanceof MultipartHttpServletRequest) {
+                multipartRequests.putIfAbsent(requests.get(i), i)
+            }
+        }
+        addMultipartRequests(underlying, copied, multipartRequests)
+        List<Map<String, Object>> shownOtherwise = new ArrayList<>()
+        for (int i = 0; i < copied.size(); i++) {
+            Map<String, Object> shown = 
differences(attributesOf(copied.get(i)), underlying)

Review Comment:
   A request that is already wrapped, then forwarded from /outer to /inner, 
still loses the forwarded view after the forward returns. The copy keeps the 
outer wrapper, which no longer has the forward attributes, so the task sees 
/outer and a null forward URI. Expected: the task keeps /inner and the forward 
from /outer.



##########
grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/TaskRequest.groovy:
##########
@@ -0,0 +1,388 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.grails.plugins.web.async
+
+import java.lang.reflect.InvocationHandler
+import java.lang.reflect.InvocationTargetException
+import java.lang.reflect.Method
+import java.lang.reflect.Modifier
+import java.lang.reflect.Proxy
+
+import groovy.transform.CompileStatic
+import groovy.transform.PackageScope
+
+import jakarta.servlet.AsyncEvent
+import jakarta.servlet.AsyncListener
+import jakarta.servlet.ServletRequest
+import jakarta.servlet.ServletRequestWrapper
+import jakarta.servlet.http.HttpServletRequest
+
+import org.springframework.web.context.request.RequestAttributes
+
+import org.grails.web.servlet.mvc.GrailsWebRequest
+
+/**
+ * The request a task started during a web request sees.
+ *
+ * <p>Until the request completes, it is the request the task was given, with 
every public view that request and
+ * the requests it wraps offer, such as a multipart wrapper's, so a task the 
response waits for, such as one started
+ * with {@code WebPromises}, renders through it. Tasks of one request can be 
given different requests, such as the
+ * request and the request of a forward, and each task keeps its own. The 
container recycles the request once it
+ * completes, including any asynchronous processing, so from then on each task 
sees a
+ * {@link CompletedHttpServletRequest copy} of its request taken as the 
request completed, and the recycled request
+ * is released. The copies are taken once for the request, however many tasks 
it has, and each task reads its copy
+ * through a view of its own, so each has the body to read. A multipart 
request stays one, without the uploads,
+ * which go with the request.</p>
+ *
+ * <p>A request completes when the dispatch the container started for it ends, 
as {@link TaskRequestFilter} tells,
+ * after any forward or include within it, though each of those completes the 
web request it bound or reused as it
+ * returns. Without the filter, such as in a unit test, the request completes 
with the web request the first of its
+ * tasks was started during.</p>
+ *
+ * @since 8.0.1
+ */
+@CompileStatic
+class TaskRequest implements InvocationHandler {
+
+    private static final String STATE = TaskRequest.name + '.STATE'
+    private static final String PROCESSING = TaskRequest.name + '.PROCESSING'
+    private static final String COMPLETION_CALLBACK = TaskRequest.name + 
'.COMPLETION'
+
+    private final GivenRequest given
+    private CompletedHttpServletRequest view
+
+    private TaskRequest(GivenRequest given) {
+        this.given = given
+    }
+
+    /**
+     * The request a task started during a web request sees. It has to be 
called while the web request is the
+     * current one, when the task is submitted.
+     *
+     * @param webRequest the web request the task is started during
+     * @return the request for the task
+     */
+    static HttpServletRequest of(GrailsWebRequest webRequest) {
+        HttpServletRequest current = webRequest.currentRequest
+        if (Proxy.isProxyClass(current.getClass())) {
+            InvocationHandler handler = Proxy.getInvocationHandler(current)
+            if (handler instanceof TaskRequest) {
+                // A task started from a task reads the request that task was 
given through a view of its own
+                return (HttpServletRequest) 
Proxy.newProxyInstance(current.getClass().classLoader,
+                        current.getClass().interfaces, new 
TaskRequest(((TaskRequest) handler).given))
+            }
+        }
+        ClassLoader loader = current.getClass().classLoader ?: 
TaskRequest.classLoader
+        return (HttpServletRequest) Proxy.newProxyInstance(loader, 
interfacesOf(current, loader),
+                new TaskRequest(givenOf(webRequest, current)))
+    }
+
+    /**
+     * Marks the request while the dispatch the container started for it is 
processed, unless an enclosing dispatch
+     * already marked it.
+     *
+     * @param request the request of the dispatch
+     * @return whether the request was marked, so the dispatch has to call 
{@link #processed} as it ends
+     */
+    @PackageScope
+    static boolean processing(ServletRequest request) {
+        ServletRequest underlying = underlying(request)
+        if (underlying.getAttribute(PROCESSING) != null) {
+            return false
+        }
+        underlying.setAttribute(PROCESSING, Boolean.TRUE)
+        return true
+    }
+
+    /**
+     * Ends the processing {@link #processing} marked: the requests the tasks 
of the request were given are copied,
+     * or, while the request is processed asynchronously, as that processing 
completes.
+     *
+     * @param request the request of the dispatch
+     */
+    @PackageScope
+    static void processed(ServletRequest request) {
+        ServletRequest underlying = underlying(request)
+        underlying.removeAttribute(PROCESSING)
+        Object state = underlying.getAttribute(STATE)
+        if (state instanceof RequestState) {
+            ((RequestState) state).requestCompleted()
+        }
+    }
+
+    // One state for the request, however many tasks it has and whichever 
request each was given, so completing it
+    // copies every request its tasks were given at once
+    private static GivenRequest givenOf(GrailsWebRequest webRequest, 
HttpServletRequest current) {
+        // The state lives on the request the container created, which every 
wrapper of it, such as the request a
+        // forward dispatched, shows, so the tasks of the request find it, 
unless the request has completed
+        ServletRequest underlying = underlying(current)
+        GivenRequest given = boundTo(underlying)?.give(current)
+        if (given != null) {
+            return given
+        }
+        RequestState state = new RequestState()
+        given = state.give(current)
+        if (marked(underlying)) {
+            // Copied as the dispatch the container started ends, though a 
forward or an include within it binds a
+            // web request of its own, or reuses this one, and completes it as 
it returns
+            underlying.setAttribute(STATE, state)
+        }
+        else if (webRequest.isActive()) {
+            underlying.setAttribute(STATE, state)
+            webRequest.registerDestructionCallback(COMPLETION_CALLBACK, 
state::requestCompleted,
+                    RequestAttributes.SCOPE_REQUEST)
+        }
+        else {
+            state.requestCompleted()
+        }
+        return given
+    }
+
+    private static RequestState boundTo(ServletRequest underlying) {
+        try {
+            Object state = underlying.getAttribute(STATE)
+            return state instanceof RequestState ? (RequestState) state : null
+        }
+        catch (IllegalStateException ignored) {
+            // The container has already recycled the request
+            return null
+        }
+    }
+
+    private static boolean marked(ServletRequest underlying) {
+        try {
+            return underlying.getAttribute(PROCESSING) != null
+        }
+        catch (IllegalStateException ignored) {
+            return false
+        }
+    }
+
+    /**
+     * The request the container created, which the given request is or wraps.
+     *
+     * @param request a request
+     * @return the innermost request of its wrappers
+     */
+    @PackageScope
+    static ServletRequest underlying(ServletRequest request) {
+        ServletRequest underlying = request
+        for (ServletRequest wrapped = unwrap(request); wrapped != null; 
wrapped = unwrap(wrapped)) {
+            underlying = wrapped
+        }
+        return underlying
+    }
+
+    // Every public view of the request and of the requests it wraps, such as 
a multipart wrapper's, so the task
+    // finds what a filter resolved however the request is wrapped, as 
unwrapping the request finds it
+    private static Class<?>[] interfacesOf(HttpServletRequest request, 
ClassLoader loader) {
+        Set<Class<?>> interfaces = new LinkedHashSet<>()
+        interfaces.add(HttpServletRequest)
+        for (ServletRequest wrapped = request; wrapped != null; wrapped = 
unwrap(wrapped)) {
+            for (Class<?> type = wrapped.getClass(); type != null; type = 
type.superclass) {
+                addInterfaces(type.interfaces, loader, interfaces)
+            }
+        }
+        return interfaces.toArray(new Class<?>[0])
+    }
+
+    private static void addInterfaces(Class<?>[] candidates, ClassLoader 
loader, Set<Class<?>> interfaces) {
+        for (Class<?> candidate : candidates) {
+            // A proxy class can only implement interfaces it can access, 
through the class loader that defines it.
+            // Nor is it a Groovy object, so Groovy calls it through these 
interfaces, not through the meta class of
+            // the request's class, whose methods it does not have
+            if (Modifier.isPublic(candidate.modifiers) && 
!GroovyObject.isAssignableFrom(candidate) &&
+                    visibleFrom(loader, candidate) && 
interfaces.add(candidate)) {
+                addInterfaces(candidate.interfaces, loader, interfaces)
+            }
+        }
+    }
+
+    private static boolean visibleFrom(ClassLoader loader, Class<?> type) {
+        try {
+            return Class.forName(type.name, false, loader).is(type)
+        }
+        catch (ClassNotFoundException ignored) {
+            return false
+        }
+    }
+
+    // The request, or the first request it wraps that offers the method, such 
as a multipart request in a wrapper
+    private static ServletRequest offering(ServletRequest request, Class<?> 
type) {
+        for (ServletRequest candidate = request; candidate != null; candidate 
= unwrap(candidate)) {
+            if (type.isInstance(candidate)) {
+                return candidate
+            }
+        }
+        return null
+    }
+
+    private static ServletRequest unwrap(ServletRequest request) {
+        return request instanceof ServletRequestWrapper ? 
((ServletRequestWrapper) request).request : null
+    }
+
+    @Override
+    Object invoke(Object proxy, Method method, Object[] args) throws Throwable 
{
+        if (method.name == 'equals' && method.parameterCount == 1) {
+            return proxy.is(args[0])
+        }
+        if (method.name == 'hashCode' && method.parameterCount == 0) {
+            return System.identityHashCode(proxy)
+        }
+        HttpServletRequest current = given.live
+        if (current == null) {
+            current = view()
+        }
+        ServletRequest target = offering(current, method.declaringClass)
+        if (target == null) {
+            // Only the live request offers the views the copy does not keep, 
such as a custom wrapper's
+            throw new IllegalStateException('The request has completed, so a 
task that outlives it cannot call ' +
+                    "${method.declaringClass.simpleName}.${method.name}, which 
the copy of the request does not keep")
+        }
+        try {
+            return method.invoke(target, args)
+        }
+        catch (InvocationTargetException e) {
+            throw e.targetException
+        }
+    }
+
+    private synchronized HttpServletRequest view() {
+        if (view == null) {
+            view = given.copyView()
+        }
+        return view
+    }
+
+    // What the tasks of one request share: its completion, which copies every 
request they were given at once
+    private static final class RequestState implements AsyncListener {
+
+        private final List<GivenRequest> given = new ArrayList<>()
+        private boolean completed
+
+        // The request a task was given, shared by the tasks given the same 
request, or null once the request has
+        // completed
+        private synchronized GivenRequest give(HttpServletRequest request) {
+            if (completed) {
+                return null
+            }
+            for (GivenRequest existing : given) {
+                if (existing.live.is(request)) {
+                    return existing
+                }
+            }
+            GivenRequest added = new GivenRequest(request)
+            given.add(added)
+            return added
+        }
+
+        private synchronized HttpServletRequest first() {
+            return completed ? null : given.get(0).live
+        }
+
+        private void requestCompleted() {
+            HttpServletRequest current = first()
+            if (current == null) {
+                return
+            }
+            try {
+                if (current.isAsyncStarted()) {

Review Comment:
   An authenticated async request for alice is copied in onComplete, after the 
security filter has cleared the thread. userPrincipal and remoteUser are read 
from that thread, so the copy is anonymous. Restoring alice before the task 
runs does not repair the copy. Capture the principal while the authenticated 
context is still present.



##########
grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/CompletedHttpServletRequest.groovy:
##########
@@ -0,0 +1,1119 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.grails.plugins.web.async
+
+import java.nio.charset.Charset
+import java.nio.charset.StandardCharsets
+import java.security.Principal
+import java.text.ParseException
+import java.text.SimpleDateFormat
+import java.util.concurrent.ConcurrentHashMap
+
+import groovy.transform.CompileStatic
+
+import jakarta.servlet.AsyncContext
+import jakarta.servlet.DispatcherType
+import jakarta.servlet.ReadListener
+import jakarta.servlet.RequestDispatcher
+import jakarta.servlet.ServletConnection
+import jakarta.servlet.ServletContext
+import jakarta.servlet.ServletInputStream
+import jakarta.servlet.ServletRequest
+import jakarta.servlet.ServletRequestWrapper
+import jakarta.servlet.ServletResponse
+import jakarta.servlet.http.Cookie
+import jakarta.servlet.http.HttpServletMapping
+import jakarta.servlet.http.HttpServletRequest
+import jakarta.servlet.http.HttpServletResponse
+import jakarta.servlet.http.HttpSession
+import jakarta.servlet.http.HttpUpgradeHandler
+import jakarta.servlet.http.MappingMatch
+import jakarta.servlet.http.Part
+
+import org.springframework.http.HttpHeaders
+import org.springframework.http.HttpMethod
+import org.springframework.util.LinkedCaseInsensitiveMap
+import org.springframework.util.LinkedMultiValueMap
+import org.springframework.util.MultiValueMap
+import org.springframework.web.context.request.RequestAttributes
+import org.springframework.web.multipart.MultipartFile
+import org.springframework.web.multipart.MultipartHttpServletRequest
+
+import org.grails.web.util.WebUtils
+
+/**
+ * A copy of a request, taken as the request completed, which a task that 
outlives the request reads in its place.
+ *
+ * <p>The container recycles a request once it completes, so a task that read 
the request itself from then on
+ * would fail. As the request completes, a copy is taken of each request its 
tasks were given, such as the request
+ * and the request of a forward, and each task reads the copy of its request 
through a {@link #newView view} of its
+ * own, so each has the part of the body nothing had read, served through one 
stream or reader whose position
+ * persists, as the live request serves it. A copy holds the attributes, 
parameters, headers, locales and cookies of
+ * its request, the session and what identifies the request. The request, its 
response and what holds either, such
+ * as the web request of the request thread, are not carried over, so the copy 
holds nothing the container recycles.
+ * What only the live request can do, such as dispatching, processing 
asynchronously, creating a session or checking
+ * a role, is not available.</p>
+ *
+ * <p>The copies share the attributes of the request the container created and 
the body, as the requests share
+ * them, so attributes a task sets stay with the copies, shared by every task. 
What a request keeps itself, such as
+ * the forward attributes of the request a forward dispatched, stays with its 
own copy, as do the attributes it
+ * hides, and setting or removing one of them changes that copy only, as on 
the request.</p>
+ *
+ * <p>The parameters are those of the request. A multipart body the container 
could not parse leaves the copy
+ * without parameters, as params has none, and any other failure to read them 
is thrown to a task that reads them,
+ * as the live request throws it.</p>
+ *
+ * <p>The uploads of a multipart request are deleted as the request ends, so 
the copy answers as a multipart
+ * request without uploads when the request was a multipart request, and a 
copy of a multipart request an attribute
+ * held, such as the one the dispatcher resolved, takes its place, with its 
parameters, such as the text fields only
+ * it has. Reading params then finds the parameters it found on the live 
request and no uploads.</p>
+ *
+ * <p>The body is kept up to {@value #BODY_LIMIT} bytes. Reading a longer one 
from the copy throws, so the copy is
+ * not what holds an upload that was never read in memory. The body of a 
multipart request is not kept: its uploads
+ * go with the request, and its text fields are in the parameters.</p>
+ *
+ * @since 8.0.1
+ */
+@CompileStatic
+class CompletedHttpServletRequest implements MultipartHttpServletRequest {
+
+    /**
+     * The longest body, in bytes, a copy keeps: what remains of a longer one 
is not read.
+     */
+    static final int BODY_LIMIT = 2 * 1024 * 1024
+
+    private static final byte[] NO_BODY = new byte[0]
+    private static final int READ_CHUNK = 8192
+    // An attribute the request of a copy hides, though the request the 
container created has it
+    private static final Object HIDDEN = new Object()
+    private static final List<String> DATE_HEADER_FORMS = List.of(
+            'EEE, dd MMM yyyy HH:mm:ss zzz',
+            'EEEE, dd-MMM-yy HH:mm:ss zzz',
+            'EEE MMM dd HH:mm:ss yyyy')
+
+    private final Map<String, Object> attributes
+    private final Map<String, Object> ownAttributes
+    // Null when the body was longer than the copy keeps
+    private final byte[] body
+    private final Map<String, String[]> parameters
+    private final RuntimeException parameterFailure
+    private final Map<String, List<String>> headers
+    private final List<Locale> locales
+    private final Cookie[] cookies
+    private final HttpSession session
+    private final ServletContext servletContext
+    private final Principal userPrincipal
+    private final DispatcherType dispatcherType
+    private final HttpServletMapping httpServletMapping
+    private final ServletConnection servletConnection
+    private final String authType
+    private final String contentType
+    private final long contentLength
+    private final String method
+    private final String requestURI
+    private final String requestURL
+    private final String queryString
+    private final String contextPath
+    private final String servletPath
+    private final String pathInfo
+    private final String pathTranslated
+    private final String protocol
+    private final String scheme
+    private final String serverName
+    private final int serverPort
+    private final boolean secure
+    private final String remoteAddr
+    private final String remoteHost
+    private final int remotePort
+    private final String localName
+    private final String localAddr
+    private final int localPort
+    private final String remoteUser
+    private final String requestedSessionId
+    private final boolean requestedSessionIdValid
+    private final boolean requestedSessionIdFromCookie
+    private final boolean requestedSessionIdFromURL
+    private final String requestId
+    private final String protocolRequestId
+    private volatile String characterEncoding
+    private ServletInputStream inputStream
+    private BufferedReader reader
+
+    private CompletedHttpServletRequest(HttpServletRequest request, 
Map<String, Object> attributes,
+            Map<String, Object> ownAttributes, CopiedParameters parameters, 
byte[] body) {
+        this.attributes = attributes
+        this.ownAttributes = ownAttributes
+        this.parameters = parameters.values
+        this.parameterFailure = parameters.failure
+        this.body = body
+        Map<String, List<String>> headers = new 
LinkedCaseInsensitiveMap<>(Locale.ENGLISH)
+        for (String name : Collections.list(request.headerNames)) {
+            headers.put(name, 
Collections.unmodifiableList(Collections.list(request.getHeaders(name))))
+        }
+        this.headers = Collections.unmodifiableMap(headers)
+        this.locales = 
Collections.unmodifiableList(Collections.list(request.locales))
+        this.cookies = copyCookies(request.cookies)
+        this.session = request.getSession(false)
+        this.servletContext = request.servletContext
+        this.userPrincipal = request.userPrincipal
+        this.dispatcherType = request.dispatcherType
+        // Values only: the container's own objects can reference the request 
it recycles
+        this.httpServletMapping = copyMapping(request.httpServletMapping)
+        this.servletConnection = copyConnection(request.servletConnection)
+        this.authType = request.authType
+        this.characterEncoding = request.characterEncoding
+        this.contentType = request.contentType
+        this.contentLength = request.contentLengthLong
+        this.method = request.method
+        this.requestURI = request.requestURI
+        this.requestURL = request.requestURL?.toString()
+        this.queryString = request.queryString
+        this.contextPath = request.contextPath
+        this.servletPath = request.servletPath
+        this.pathInfo = request.pathInfo
+        this.pathTranslated = request.pathTranslated
+        this.protocol = request.protocol
+        this.scheme = request.scheme
+        this.serverName = request.serverName
+        this.serverPort = request.serverPort
+        this.secure = request.secure
+        this.remoteAddr = request.remoteAddr
+        this.remoteHost = request.remoteHost
+        this.remotePort = request.remotePort
+        this.localName = request.localName
+        this.localAddr = request.localAddr
+        this.localPort = request.localPort
+        this.remoteUser = request.remoteUser
+        this.requestedSessionId = request.requestedSessionId
+        this.requestedSessionIdValid = request.requestedSessionIdValid
+        this.requestedSessionIdFromCookie = 
request.requestedSessionIdFromCookie
+        this.requestedSessionIdFromURL = request.requestedSessionIdFromURL
+        this.requestId = request.requestId
+        this.protocolRequestId = request.protocolRequestId
+    }
+
+    // Field by field: the getters serve tasks, so some, such as getSession 
and getLocales, do not return the field
+    private CompletedHttpServletRequest(CompletedHttpServletRequest copy) {
+        this.attributes = copy.@attributes
+        this.ownAttributes = copy.@ownAttributes
+        this.body = copy.@body
+        this.parameters = copy.@parameters
+        this.parameterFailure = copy.@parameterFailure
+        this.headers = copy.@headers
+        this.locales = copy.@locales
+        this.cookies = copy.@cookies
+        this.session = copy.@session
+        this.servletContext = copy.@servletContext
+        this.userPrincipal = copy.@userPrincipal
+        this.dispatcherType = copy.@dispatcherType
+        this.httpServletMapping = copy.@httpServletMapping
+        this.servletConnection = copy.@servletConnection
+        this.authType = copy.@authType
+        this.characterEncoding = copy.@characterEncoding
+        this.contentType = copy.@contentType
+        this.contentLength = copy.@contentLength
+        this.method = copy.@method
+        this.requestURI = copy.@requestURI
+        this.requestURL = copy.@requestURL
+        this.queryString = copy.@queryString
+        this.contextPath = copy.@contextPath
+        this.servletPath = copy.@servletPath
+        this.pathInfo = copy.@pathInfo
+        this.pathTranslated = copy.@pathTranslated
+        this.protocol = copy.@protocol
+        this.scheme = copy.@scheme
+        this.serverName = copy.@serverName
+        this.serverPort = copy.@serverPort
+        this.secure = copy.@secure
+        this.remoteAddr = copy.@remoteAddr
+        this.remoteHost = copy.@remoteHost
+        this.remotePort = copy.@remotePort
+        this.localName = copy.@localName
+        this.localAddr = copy.@localAddr
+        this.localPort = copy.@localPort
+        this.remoteUser = copy.@remoteUser
+        this.requestedSessionId = copy.@requestedSessionId
+        this.requestedSessionIdValid = copy.@requestedSessionIdValid
+        this.requestedSessionIdFromCookie = copy.@requestedSessionIdFromCookie
+        this.requestedSessionIdFromURL = copy.@requestedSessionIdFromURL
+        this.requestId = copy.@requestId
+        this.protocolRequestId = copy.@protocolRequestId
+    }
+
+    /**
+     * Copies the requests the tasks of a request that is completing were 
given: the request, and any other request
+     * a later task was given, such as the request of a forward. It has to be 
called before the container recycles
+     * the request. Each copy holds what its request shows, and the copies 
share the attributes of the request the
+     * container created and the body, as the requests share them.
+     *
+     * @param requests the requests, each the request the container created or 
a wrapper of it, the first being the
+     *        one whose body the copies share
+     * @return the copies, in the order of the requests, with {@code null} for 
a request after the first that could
+     *         not be copied
+     */
+    static List<CompletedHttpServletRequest> copyOf(List<HttpServletRequest> 
requests) {
+        Map<String, Object> underlying = 
attributesOf(TaskRequest.underlying(requests.get(0)))
+        // The requests to copy: those given, then each multipart request an 
attribute holds, such as the one the
+        // dispatcher resolved, which wraps the request, so its copy, which 
has no uploads either, takes its place
+        List<HttpServletRequest> copied = new ArrayList<>(requests)
+        Map<Object, Integer> multipartRequests = new IdentityHashMap<>()
+        for (int i = 0; i < requests.size(); i++) {
+            if (requests.get(i) instanceof MultipartHttpServletRequest) {
+                multipartRequests.putIfAbsent(requests.get(i), i)
+            }
+        }
+        addMultipartRequests(underlying, copied, multipartRequests)
+        List<Map<String, Object>> shownOtherwise = new ArrayList<>()
+        for (int i = 0; i < copied.size(); i++) {
+            Map<String, Object> shown = 
differences(attributesOf(copied.get(i)), underlying)
+            shownOtherwise.add(shown)
+            addMultipartRequests(shown, copied, multipartRequests)
+        }
+        // Every parameter map before the body: parsing the parameters 
consumes a form body, on the live request too
+        List<CopiedParameters> parameters = new ArrayList<>()
+        for (HttpServletRequest request : copied) {
+            parameters.add(copyParameters(request))
+        }
+        byte[] body = copyBody(requests.get(0))
+        Map<String, Object> attributes = new ConcurrentHashMap<>()
+        List<Map<String, Object>> ownAttributes = new ArrayList<>()
+        List<CompletedHttpServletRequest> copies = new ArrayList<>()
+        for (int i = 0; i < copied.size(); i++) {
+            Map<String, Object> own = new ConcurrentHashMap<>()
+            ownAttributes.add(own)
+            copies.add(i == 0 ? new CompletedHttpServletRequest(copied.get(0), 
attributes, own, parameters.get(0), body) :
+                    copyAlongside(copied.get(i), attributes, own, 
parameters.get(i), body))
+        }
+        putAttributes(underlying, attributes, multipartRequests, copies, false)
+        for (int i = 0; i < copied.size(); i++) {
+            putAttributes(shownOtherwise.get(i), ownAttributes.get(i), 
multipartRequests, copies, true)
+        }
+        return new ArrayList<>(copies.subList(0, requests.size()))
+    }
+
+    // A request that can no longer be read leaves its own tasks without a 
copy, not the tasks of the other requests
+    private static CompletedHttpServletRequest 
copyAlongside(HttpServletRequest request, Map<String, Object> attributes,
+            Map<String, Object> ownAttributes, CopiedParameters parameters, 
byte[] body) {
+        try {
+            return new CompletedHttpServletRequest(request, attributes, 
ownAttributes, parameters, body)
+        }
+        catch (RuntimeException ignored) {
+            return null
+        }
+    }
+
+    private static Map<String, Object> attributesOf(ServletRequest request) {
+        Map<String, Object> attributes = new LinkedHashMap<>()
+        for (String name : Collections.list(request.attributeNames)) {
+            Object value = request.getAttribute(name)
+            if (value != null) {
+                attributes.put(name, value)
+            }
+        }
+        return attributes
+    }
+
+    // What a request shows otherwise than the request the container created, 
such as the forward attributes a
+    // forward's request keeps itself: its own values, and the names it hides
+    private static Map<String, Object> differences(Map<String, Object> shown, 
Map<String, Object> underlying) {
+        Map<String, Object> differences = new LinkedHashMap<>()
+        for (Map.Entry<String, Object> attribute : shown.entrySet()) {
+            if (!Objects.equals(attribute.value, 
underlying.get(attribute.key))) {
+                differences.put(attribute.key, attribute.value)
+            }
+        }
+        for (String name : underlying.keySet()) {
+            if (!shown.containsKey(name)) {
+                differences.put(name, HIDDEN)
+            }
+        }
+        return differences
+    }
+
+    private static void addMultipartRequests(Map<String, Object> attributes, 
List<HttpServletRequest> copied,
+            Map<Object, Integer> multipartRequests) {
+        for (Object value : attributes.values()) {
+            if (value instanceof MultipartHttpServletRequest && 
!multipartRequests.containsKey(value)) {
+                multipartRequests.put(value, copied.size())
+                copied.add((HttpServletRequest) value)
+            }
+        }
+    }
+
+    // The attributes as the copies keep them: a multipart request is replaced 
by its copy, and what is recycled with
+    // the request is left out, so a request that showed it itself hides it
+    private static void putAttributes(Map<String, Object> attributes, 
Map<String, Object> kept,
+            Map<Object, Integer> multipartRequests, 
List<CompletedHttpServletRequest> copies, boolean own) {
+        for (Map.Entry<String, Object> attribute : attributes.entrySet()) {
+            Object value = attribute.value
+            if (value instanceof MultipartHttpServletRequest) {
+                value = copies.get(multipartRequests.get(value))
+            }
+            else if (recycledWithRequest(value)) {
+                value = null
+            }
+            if (value != null) {
+                kept.put(attribute.key, value)
+            }
+            else if (own) {
+                kept.put(attribute.key, HIDDEN)
+            }
+        }
+    }
+
+    /**
+     * A view of the copy for one task. Every view shares the copied request, 
including the attributes, and reads
+     * the one copied body through a stream or reader of its own, so what one 
task reads is still there for the next.
+     *
+     * @return the view
+     */
+    CompletedHttpServletRequest newView() {
+        return new CompletedHttpServletRequest(this)
+    }
+
+    // The request, its response and what holds either, such as the web 
request, are recycled with the request
+    private static boolean recycledWithRequest(Object value) {
+        return value instanceof ServletRequest || value instanceof 
ServletResponse || value instanceof RequestAttributes
+    }
+
+    private static String[] copyValues(String[] values) {
+        return values == null ? null : Arrays.copyOf(values, values.length)
+    }
+
+    // The parameters of the request, as WebUtils.readParameterMap reads them: 
a multipart body the container cannot
+    // parse leaves the request without parameters, and any other failure 
reaches the task that reads them, as on
+    // the request
+    private static CopiedParameters copyParameters(HttpServletRequest request) 
{
+        try {
+            Map<String, String[]> parameters = new LinkedHashMap<>()
+            for (Map.Entry<String, String[]> parameter : 
ownParameters(request).entrySet()) {
+                parameters.put(parameter.key, copyValues(parameter.value))
+            }
+            return new 
CopiedParameters(Collections.unmodifiableMap(parameters), null)
+        }
+        catch (RuntimeException unreadable) {
+            return new CopiedParameters(Collections.<String, String[]> 
emptyMap(),
+                    WebUtils.isMultipartContentType(request) ? null : 
unreadable)
+        }
+    }
+
+    // The parameters of the request or, when a multipart wrapper resolving 
lazily can no longer parse the body for
+    // them as the request completes, of the request it wraps
+    private static Map<String, String[]> ownParameters(HttpServletRequest 
request) {
+        RuntimeException failure = null
+        for (ServletRequest source = request; source != null; source = 
wrapped(source)) {
+            try {
+                return source.parameterMap
+            }
+            catch (RuntimeException unreadable) {
+                failure = failure ?: unreadable
+            }
+        }
+        throw failure
+    }
+
+    private static ServletRequest wrapped(ServletRequest request) {
+        return request instanceof ServletRequestWrapper ? 
((ServletRequestWrapper) request).request : null
+    }
+
+    private static Cookie[] copyCookies(Cookie[] cookies) {
+        if (cookies == null) {
+            return null
+        }
+        Cookie[] copies = new Cookie[cookies.length]
+        for (int i = 0; i < cookies.length; i++) {
+            copies[i] = (Cookie) cookies[i].clone()
+        }
+        return copies
+    }
+
+    // What remains of the body, or null when it is longer than the copy keeps
+    private static byte[] copyBody(HttpServletRequest request) {
+        if (WebUtils.isMultipartContentType(request)) {
+            // Its uploads go with the request and its text fields are in the 
parameters, so a multipart body the
+            // request did not read, such as one rejected for its size, is 
left unread
+            return NO_BODY
+        }
+        try {
+            InputStream remaining = request.inputStream

Review Comment:
   A task that has already read a from inputStream abcdef, and is still running 
when the copy reads the same stream, then sees EOF instead of bcdef. Do not 
drain a stream a running task already holds.



##########
grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/CompletedHttpServletRequest.groovy:
##########
@@ -0,0 +1,1119 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.grails.plugins.web.async
+
+import java.nio.charset.Charset
+import java.nio.charset.StandardCharsets
+import java.security.Principal
+import java.text.ParseException
+import java.text.SimpleDateFormat
+import java.util.concurrent.ConcurrentHashMap
+
+import groovy.transform.CompileStatic
+
+import jakarta.servlet.AsyncContext
+import jakarta.servlet.DispatcherType
+import jakarta.servlet.ReadListener
+import jakarta.servlet.RequestDispatcher
+import jakarta.servlet.ServletConnection
+import jakarta.servlet.ServletContext
+import jakarta.servlet.ServletInputStream
+import jakarta.servlet.ServletRequest
+import jakarta.servlet.ServletRequestWrapper
+import jakarta.servlet.ServletResponse
+import jakarta.servlet.http.Cookie
+import jakarta.servlet.http.HttpServletMapping
+import jakarta.servlet.http.HttpServletRequest
+import jakarta.servlet.http.HttpServletResponse
+import jakarta.servlet.http.HttpSession
+import jakarta.servlet.http.HttpUpgradeHandler
+import jakarta.servlet.http.MappingMatch
+import jakarta.servlet.http.Part
+
+import org.springframework.http.HttpHeaders
+import org.springframework.http.HttpMethod
+import org.springframework.util.LinkedCaseInsensitiveMap
+import org.springframework.util.LinkedMultiValueMap
+import org.springframework.util.MultiValueMap
+import org.springframework.web.context.request.RequestAttributes
+import org.springframework.web.multipart.MultipartFile
+import org.springframework.web.multipart.MultipartHttpServletRequest
+
+import org.grails.web.util.WebUtils
+
+/**
+ * A copy of a request, taken as the request completed, which a task that 
outlives the request reads in its place.
+ *
+ * <p>The container recycles a request once it completes, so a task that read 
the request itself from then on
+ * would fail. As the request completes, a copy is taken of each request its 
tasks were given, such as the request
+ * and the request of a forward, and each task reads the copy of its request 
through a {@link #newView view} of its
+ * own, so each has the part of the body nothing had read, served through one 
stream or reader whose position
+ * persists, as the live request serves it. A copy holds the attributes, 
parameters, headers, locales and cookies of
+ * its request, the session and what identifies the request. The request, its 
response and what holds either, such
+ * as the web request of the request thread, are not carried over, so the copy 
holds nothing the container recycles.
+ * What only the live request can do, such as dispatching, processing 
asynchronously, creating a session or checking
+ * a role, is not available.</p>
+ *
+ * <p>The copies share the attributes of the request the container created and 
the body, as the requests share
+ * them, so attributes a task sets stay with the copies, shared by every task. 
What a request keeps itself, such as
+ * the forward attributes of the request a forward dispatched, stays with its 
own copy, as do the attributes it
+ * hides, and setting or removing one of them changes that copy only, as on 
the request.</p>
+ *
+ * <p>The parameters are those of the request. A multipart body the container 
could not parse leaves the copy
+ * without parameters, as params has none, and any other failure to read them 
is thrown to a task that reads them,
+ * as the live request throws it.</p>
+ *
+ * <p>The uploads of a multipart request are deleted as the request ends, so 
the copy answers as a multipart
+ * request without uploads when the request was a multipart request, and a 
copy of a multipart request an attribute
+ * held, such as the one the dispatcher resolved, takes its place, with its 
parameters, such as the text fields only
+ * it has. Reading params then finds the parameters it found on the live 
request and no uploads.</p>
+ *
+ * <p>The body is kept up to {@value #BODY_LIMIT} bytes. Reading a longer one 
from the copy throws, so the copy is
+ * not what holds an upload that was never read in memory. The body of a 
multipart request is not kept: its uploads
+ * go with the request, and its text fields are in the parameters.</p>
+ *
+ * @since 8.0.1
+ */
+@CompileStatic
+class CompletedHttpServletRequest implements MultipartHttpServletRequest {
+
+    /**
+     * The longest body, in bytes, a copy keeps: what remains of a longer one 
is not read.
+     */
+    static final int BODY_LIMIT = 2 * 1024 * 1024
+
+    private static final byte[] NO_BODY = new byte[0]
+    private static final int READ_CHUNK = 8192
+    // An attribute the request of a copy hides, though the request the 
container created has it
+    private static final Object HIDDEN = new Object()
+    private static final List<String> DATE_HEADER_FORMS = List.of(
+            'EEE, dd MMM yyyy HH:mm:ss zzz',
+            'EEEE, dd-MMM-yy HH:mm:ss zzz',
+            'EEE MMM dd HH:mm:ss yyyy')
+
+    private final Map<String, Object> attributes
+    private final Map<String, Object> ownAttributes
+    // Null when the body was longer than the copy keeps
+    private final byte[] body
+    private final Map<String, String[]> parameters
+    private final RuntimeException parameterFailure
+    private final Map<String, List<String>> headers
+    private final List<Locale> locales
+    private final Cookie[] cookies
+    private final HttpSession session
+    private final ServletContext servletContext
+    private final Principal userPrincipal
+    private final DispatcherType dispatcherType
+    private final HttpServletMapping httpServletMapping
+    private final ServletConnection servletConnection
+    private final String authType
+    private final String contentType
+    private final long contentLength
+    private final String method
+    private final String requestURI
+    private final String requestURL
+    private final String queryString
+    private final String contextPath
+    private final String servletPath
+    private final String pathInfo
+    private final String pathTranslated
+    private final String protocol
+    private final String scheme
+    private final String serverName
+    private final int serverPort
+    private final boolean secure
+    private final String remoteAddr
+    private final String remoteHost
+    private final int remotePort
+    private final String localName
+    private final String localAddr
+    private final int localPort
+    private final String remoteUser
+    private final String requestedSessionId
+    private final boolean requestedSessionIdValid
+    private final boolean requestedSessionIdFromCookie
+    private final boolean requestedSessionIdFromURL
+    private final String requestId
+    private final String protocolRequestId
+    private volatile String characterEncoding
+    private ServletInputStream inputStream
+    private BufferedReader reader
+
+    private CompletedHttpServletRequest(HttpServletRequest request, 
Map<String, Object> attributes,
+            Map<String, Object> ownAttributes, CopiedParameters parameters, 
byte[] body) {
+        this.attributes = attributes
+        this.ownAttributes = ownAttributes
+        this.parameters = parameters.values
+        this.parameterFailure = parameters.failure
+        this.body = body
+        Map<String, List<String>> headers = new 
LinkedCaseInsensitiveMap<>(Locale.ENGLISH)
+        for (String name : Collections.list(request.headerNames)) {
+            headers.put(name, 
Collections.unmodifiableList(Collections.list(request.getHeaders(name))))
+        }
+        this.headers = Collections.unmodifiableMap(headers)
+        this.locales = 
Collections.unmodifiableList(Collections.list(request.locales))
+        this.cookies = copyCookies(request.cookies)
+        this.session = request.getSession(false)
+        this.servletContext = request.servletContext
+        this.userPrincipal = request.userPrincipal
+        this.dispatcherType = request.dispatcherType
+        // Values only: the container's own objects can reference the request 
it recycles
+        this.httpServletMapping = copyMapping(request.httpServletMapping)
+        this.servletConnection = copyConnection(request.servletConnection)
+        this.authType = request.authType
+        this.characterEncoding = request.characterEncoding
+        this.contentType = request.contentType
+        this.contentLength = request.contentLengthLong
+        this.method = request.method
+        this.requestURI = request.requestURI
+        this.requestURL = request.requestURL?.toString()
+        this.queryString = request.queryString
+        this.contextPath = request.contextPath
+        this.servletPath = request.servletPath
+        this.pathInfo = request.pathInfo
+        this.pathTranslated = request.pathTranslated
+        this.protocol = request.protocol
+        this.scheme = request.scheme
+        this.serverName = request.serverName
+        this.serverPort = request.serverPort
+        this.secure = request.secure
+        this.remoteAddr = request.remoteAddr
+        this.remoteHost = request.remoteHost
+        this.remotePort = request.remotePort
+        this.localName = request.localName
+        this.localAddr = request.localAddr
+        this.localPort = request.localPort
+        this.remoteUser = request.remoteUser
+        this.requestedSessionId = request.requestedSessionId
+        this.requestedSessionIdValid = request.requestedSessionIdValid
+        this.requestedSessionIdFromCookie = 
request.requestedSessionIdFromCookie
+        this.requestedSessionIdFromURL = request.requestedSessionIdFromURL
+        this.requestId = request.requestId
+        this.protocolRequestId = request.protocolRequestId
+    }
+
+    // Field by field: the getters serve tasks, so some, such as getSession 
and getLocales, do not return the field
+    private CompletedHttpServletRequest(CompletedHttpServletRequest copy) {
+        this.attributes = copy.@attributes
+        this.ownAttributes = copy.@ownAttributes
+        this.body = copy.@body
+        this.parameters = copy.@parameters
+        this.parameterFailure = copy.@parameterFailure
+        this.headers = copy.@headers
+        this.locales = copy.@locales
+        this.cookies = copy.@cookies
+        this.session = copy.@session
+        this.servletContext = copy.@servletContext
+        this.userPrincipal = copy.@userPrincipal
+        this.dispatcherType = copy.@dispatcherType
+        this.httpServletMapping = copy.@httpServletMapping
+        this.servletConnection = copy.@servletConnection
+        this.authType = copy.@authType
+        this.characterEncoding = copy.@characterEncoding
+        this.contentType = copy.@contentType
+        this.contentLength = copy.@contentLength
+        this.method = copy.@method
+        this.requestURI = copy.@requestURI
+        this.requestURL = copy.@requestURL
+        this.queryString = copy.@queryString
+        this.contextPath = copy.@contextPath
+        this.servletPath = copy.@servletPath
+        this.pathInfo = copy.@pathInfo
+        this.pathTranslated = copy.@pathTranslated
+        this.protocol = copy.@protocol
+        this.scheme = copy.@scheme
+        this.serverName = copy.@serverName
+        this.serverPort = copy.@serverPort
+        this.secure = copy.@secure
+        this.remoteAddr = copy.@remoteAddr
+        this.remoteHost = copy.@remoteHost
+        this.remotePort = copy.@remotePort
+        this.localName = copy.@localName
+        this.localAddr = copy.@localAddr
+        this.localPort = copy.@localPort
+        this.remoteUser = copy.@remoteUser
+        this.requestedSessionId = copy.@requestedSessionId
+        this.requestedSessionIdValid = copy.@requestedSessionIdValid
+        this.requestedSessionIdFromCookie = copy.@requestedSessionIdFromCookie
+        this.requestedSessionIdFromURL = copy.@requestedSessionIdFromURL
+        this.requestId = copy.@requestId
+        this.protocolRequestId = copy.@protocolRequestId
+    }
+
+    /**
+     * Copies the requests the tasks of a request that is completing were 
given: the request, and any other request
+     * a later task was given, such as the request of a forward. It has to be 
called before the container recycles
+     * the request. Each copy holds what its request shows, and the copies 
share the attributes of the request the
+     * container created and the body, as the requests share them.
+     *
+     * @param requests the requests, each the request the container created or 
a wrapper of it, the first being the
+     *        one whose body the copies share
+     * @return the copies, in the order of the requests, with {@code null} for 
a request after the first that could
+     *         not be copied
+     */
+    static List<CompletedHttpServletRequest> copyOf(List<HttpServletRequest> 
requests) {
+        Map<String, Object> underlying = 
attributesOf(TaskRequest.underlying(requests.get(0)))
+        // The requests to copy: those given, then each multipart request an 
attribute holds, such as the one the
+        // dispatcher resolved, which wraps the request, so its copy, which 
has no uploads either, takes its place
+        List<HttpServletRequest> copied = new ArrayList<>(requests)
+        Map<Object, Integer> multipartRequests = new IdentityHashMap<>()
+        for (int i = 0; i < requests.size(); i++) {
+            if (requests.get(i) instanceof MultipartHttpServletRequest) {
+                multipartRequests.putIfAbsent(requests.get(i), i)
+            }
+        }
+        addMultipartRequests(underlying, copied, multipartRequests)
+        List<Map<String, Object>> shownOtherwise = new ArrayList<>()
+        for (int i = 0; i < copied.size(); i++) {
+            Map<String, Object> shown = 
differences(attributesOf(copied.get(i)), underlying)
+            shownOtherwise.add(shown)
+            addMultipartRequests(shown, copied, multipartRequests)
+        }
+        // Every parameter map before the body: parsing the parameters 
consumes a form body, on the live request too
+        List<CopiedParameters> parameters = new ArrayList<>()
+        for (HttpServletRequest request : copied) {
+            parameters.add(copyParameters(request))
+        }
+        byte[] body = copyBody(requests.get(0))
+        Map<String, Object> attributes = new ConcurrentHashMap<>()
+        List<Map<String, Object>> ownAttributes = new ArrayList<>()
+        List<CompletedHttpServletRequest> copies = new ArrayList<>()
+        for (int i = 0; i < copied.size(); i++) {
+            Map<String, Object> own = new ConcurrentHashMap<>()
+            ownAttributes.add(own)
+            copies.add(i == 0 ? new CompletedHttpServletRequest(copied.get(0), 
attributes, own, parameters.get(0), body) :
+                    copyAlongside(copied.get(i), attributes, own, 
parameters.get(i), body))
+        }
+        putAttributes(underlying, attributes, multipartRequests, copies, false)
+        for (int i = 0; i < copied.size(); i++) {
+            putAttributes(shownOtherwise.get(i), ownAttributes.get(i), 
multipartRequests, copies, true)
+        }
+        return new ArrayList<>(copies.subList(0, requests.size()))
+    }
+
+    // A request that can no longer be read leaves its own tasks without a 
copy, not the tasks of the other requests
+    private static CompletedHttpServletRequest 
copyAlongside(HttpServletRequest request, Map<String, Object> attributes,
+            Map<String, Object> ownAttributes, CopiedParameters parameters, 
byte[] body) {
+        try {
+            return new CompletedHttpServletRequest(request, attributes, 
ownAttributes, parameters, body)
+        }
+        catch (RuntimeException ignored) {
+            return null
+        }
+    }
+
+    private static Map<String, Object> attributesOf(ServletRequest request) {
+        Map<String, Object> attributes = new LinkedHashMap<>()
+        for (String name : Collections.list(request.attributeNames)) {
+            Object value = request.getAttribute(name)
+            if (value != null) {
+                attributes.put(name, value)
+            }
+        }
+        return attributes
+    }
+
+    // What a request shows otherwise than the request the container created, 
such as the forward attributes a
+    // forward's request keeps itself: its own values, and the names it hides
+    private static Map<String, Object> differences(Map<String, Object> shown, 
Map<String, Object> underlying) {
+        Map<String, Object> differences = new LinkedHashMap<>()
+        for (Map.Entry<String, Object> attribute : shown.entrySet()) {
+            if (!Objects.equals(attribute.value, 
underlying.get(attribute.key))) {
+                differences.put(attribute.key, attribute.value)
+            }
+        }
+        for (String name : underlying.keySet()) {
+            if (!shown.containsKey(name)) {
+                differences.put(name, HIDDEN)
+            }
+        }
+        return differences
+    }
+
+    private static void addMultipartRequests(Map<String, Object> attributes, 
List<HttpServletRequest> copied,
+            Map<Object, Integer> multipartRequests) {
+        for (Object value : attributes.values()) {
+            if (value instanceof MultipartHttpServletRequest && 
!multipartRequests.containsKey(value)) {
+                multipartRequests.put(value, copied.size())
+                copied.add((HttpServletRequest) value)
+            }
+        }
+    }
+
+    // The attributes as the copies keep them: a multipart request is replaced 
by its copy, and what is recycled with
+    // the request is left out, so a request that showed it itself hides it
+    private static void putAttributes(Map<String, Object> attributes, 
Map<String, Object> kept,
+            Map<Object, Integer> multipartRequests, 
List<CompletedHttpServletRequest> copies, boolean own) {
+        for (Map.Entry<String, Object> attribute : attributes.entrySet()) {
+            Object value = attribute.value
+            if (value instanceof MultipartHttpServletRequest) {
+                value = copies.get(multipartRequests.get(value))
+            }
+            else if (recycledWithRequest(value)) {
+                value = null
+            }
+            if (value != null) {
+                kept.put(attribute.key, value)
+            }
+            else if (own) {
+                kept.put(attribute.key, HIDDEN)
+            }
+        }
+    }
+
+    /**
+     * A view of the copy for one task. Every view shares the copied request, 
including the attributes, and reads
+     * the one copied body through a stream or reader of its own, so what one 
task reads is still there for the next.
+     *
+     * @return the view
+     */
+    CompletedHttpServletRequest newView() {
+        return new CompletedHttpServletRequest(this)
+    }
+
+    // The request, its response and what holds either, such as the web 
request, are recycled with the request
+    private static boolean recycledWithRequest(Object value) {
+        return value instanceof ServletRequest || value instanceof 
ServletResponse || value instanceof RequestAttributes
+    }
+
+    private static String[] copyValues(String[] values) {
+        return values == null ? null : Arrays.copyOf(values, values.length)
+    }
+
+    // The parameters of the request, as WebUtils.readParameterMap reads them: 
a multipart body the container cannot
+    // parse leaves the request without parameters, and any other failure 
reaches the task that reads them, as on
+    // the request
+    private static CopiedParameters copyParameters(HttpServletRequest request) 
{
+        try {
+            Map<String, String[]> parameters = new LinkedHashMap<>()
+            for (Map.Entry<String, String[]> parameter : 
ownParameters(request).entrySet()) {
+                parameters.put(parameter.key, copyValues(parameter.value))
+            }
+            return new 
CopiedParameters(Collections.unmodifiableMap(parameters), null)
+        }
+        catch (RuntimeException unreadable) {
+            return new CopiedParameters(Collections.<String, String[]> 
emptyMap(),
+                    WebUtils.isMultipartContentType(request) ? null : 
unreadable)
+        }
+    }
+
+    // The parameters of the request or, when a multipart wrapper resolving 
lazily can no longer parse the body for
+    // them as the request completes, of the request it wraps
+    private static Map<String, String[]> ownParameters(HttpServletRequest 
request) {
+        RuntimeException failure = null
+        for (ServletRequest source = request; source != null; source = 
wrapped(source)) {

Review Comment:
   A non-multipart wrapper that throws from getParameterMap is unwrapped, and 
the task receives the underlying parameters. The same read throws while the 
request is live. Keep that failure. Unwrap only the multipart case this 
fallback is for.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to