Jetty 12 recycle servlet channel (#8909)

Recycle ServletChannel 
Cleanup caching comments and impl
Don't recycle after completion notification
Delay setting callback until ServletHandler.handle called
Check that the retrieved ServletChannel is for the same context.
This commit is contained in:
Greg Wilkins 2022-11-24 13:56:43 +11:00 committed by GitHub
parent 842956aca7
commit 2460b86d41
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 285 additions and 221 deletions

View File

@ -13,15 +13,13 @@
package org.eclipse.jetty.server;
import java.util.Map;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.thread.Scheduler;
import org.eclipse.jetty.util.thread.ThreadPool;
/**
* Components made available via a {@link Request}
* TODO flesh out this idea... maybe better name?
* Common components made available via a {@link Request}
*/
public interface Components
{
@ -36,12 +34,13 @@ public interface Components
* The cache will have a life cycle limited by the connection, i.e. no cache map will live
* longer that the connection associated with it. However, a cache may have a shorter life
* than a connection (e.g. it may be discarded for implementation reasons). A cache map is
* guaranteed to be give to only a single request concurrently, so objects saved there do not
* guaranteed to be given to only a single request concurrently (scoped by
* {@link org.eclipse.jetty.server.internal.HttpChannelState}), so objects saved there do not
* need to be made safe from access by simultaneous request.
* If the connection is known to be none-persistent then the cache may be a noop cache and discard
* all items set on it.
* If the connection is known to be none-persistent then the cache may be a noop
* cache and discard all items set on it.
*
* @return A Map, which may be an empty map that discards all items.
* TODO This should be Attributes like everything else.
*/
Map<String, Object> getCache();
Attributes getCache();
}

View File

@ -117,6 +117,8 @@ import org.eclipse.jetty.util.thread.Invocable;
public interface Request extends Attributes, Content.Source
{
List<Locale> __defaultLocale = Collections.singletonList(Locale.getDefault());
String CACHE_ATTRIBUTE = Request.class.getCanonicalName() + ".CookieCache";
String COOKIE_ATTRIBUTE = Request.class.getCanonicalName() + ".Cookies";
/**
* an ID unique within the lifetime scope of the {@link ConnectionMetaData#getId()}).
@ -388,21 +390,21 @@ public interface Request extends Attributes, Content.Source
static List<HttpCookie> getCookies(Request request)
{
// TODO modify Request and HttpChannel to be optimised for the known attributes
List<HttpCookie> cookies = (List<HttpCookie>)request.getAttribute(Request.class.getCanonicalName() + ".Cookies");
List<HttpCookie> cookies = (List<HttpCookie>)request.getAttribute(COOKIE_ATTRIBUTE);
if (cookies != null)
return cookies;
// TODO: review whether to store the cookie cache at the connection level, or whether to cache them at all.
CookieCache cookieCache = (CookieCache)request.getComponents().getCache().get(Request.class.getCanonicalName() + ".CookieCache");
CookieCache cookieCache = (CookieCache)request.getComponents().getCache().getAttribute(CACHE_ATTRIBUTE);
if (cookieCache == null)
{
// TODO compliance listeners?
cookieCache = new CookieCache(request.getConnectionMetaData().getHttpConfiguration().getRequestCookieCompliance(), null);
request.getComponents().getCache().put(Request.class.getCanonicalName() + ".CookieCache", cookieCache);
request.getComponents().getCache().setAttribute(CACHE_ATTRIBUTE, cookieCache);
}
cookies = cookieCache.getCookies(request.getHeaders());
request.setAttribute(Request.class.getCanonicalName() + ".Cookies", cookies);
request.setAttribute(COOKIE_ATTRIBUTE, cookies);
return cookies;
}

View File

@ -169,7 +169,7 @@ public class HttpChannelState implements HttpChannel, Components
private Callback _writeCallback;
private Content.Chunk.Error _error;
private Predicate<Throwable> _onError;
private Map<String, Object> _cache;
private Attributes _cache;
public HttpChannelState(ConnectionMetaData connectionMetaData)
{
@ -321,14 +321,14 @@ public class HttpChannelState implements HttpChannel, Components
}
@Override
public Map<String, Object> getCache()
public Attributes getCache()
{
if (_cache == null)
{
if (getConnectionMetaData().isPersistent())
_cache = new HashMap<>();
_cache = new Attributes.Mapped(new HashMap<>());
else
_cache = NULL_CACHE;
_cache = Attributes.NULL;
}
return _cache;
}

View File

@ -125,7 +125,6 @@ public interface Attributes
};
}
/**
* Clear all attribute names
*/
@ -225,6 +224,7 @@ public interface Attributes
{
return getWrapped().equals(obj);
}
}
/**
@ -232,15 +232,23 @@ public interface Attributes
*/
class Mapped implements Attributes
{
private final java.util.concurrent.ConcurrentMap<String, Object> _map = new ConcurrentHashMap<>();
private final Set<String> _names = Collections.unmodifiableSet(_map.keySet());
private final Map<String, Object> _map;
private final Set<String> _names;
public Mapped()
{
this(new ConcurrentHashMap<>());
}
public Mapped(Map<String, Object> map)
{
_map = Objects.requireNonNull(map);
_names = Collections.unmodifiableSet(_map.keySet());
}
public Mapped(Mapped attributes)
{
this();
_map.putAll(attributes._map);
}
@ -567,4 +575,42 @@ public interface Attributes
return false;
}
}
Attributes NULL = new Attributes()
{
@Override
public Object removeAttribute(String name)
{
return null;
}
@Override
public Object setAttribute(String name, Object attribute)
{
return null;
}
@Override
public Object getAttribute(String name)
{
return null;
}
@Override
public Set<String> getAttributeNameSet()
{
return Collections.emptySet();
}
@Override
public void clearAttributes()
{
}
@Override
public Map<String, Object> asAttributeMap()
{
return Collections.emptyMap();
}
};
}

View File

@ -38,7 +38,7 @@ class AsyncContentProducer implements ContentProducer
private static final Logger LOG = LoggerFactory.getLogger(AsyncContentProducer.class);
private static final Content.Chunk.Error RECYCLED_ERROR_CHUNK = Content.Chunk.from(new StaticException("ContentProducer has been recycled"));
private final AutoLock _lock = new AutoLock();
final AutoLock _lock;
private final ServletChannel _servletChannel;
private HttpInput.Interceptor _interceptor;
private Content.Chunk _rawChunk;
@ -47,15 +47,14 @@ class AsyncContentProducer implements ContentProducer
private long _firstByteNanoTime = Long.MIN_VALUE;
private long _rawBytesArrived;
AsyncContentProducer(ServletChannel servletChannel)
/**
* @param servletChannel The ServletChannel to produce input from.
* @param lock The lock of the HttpInput, shared with this instance
*/
AsyncContentProducer(ServletChannel servletChannel, AutoLock lock)
{
_servletChannel = servletChannel;
}
@Override
public AutoLock lock()
{
return _lock.lock();
_lock = lock;
}
@Override
@ -225,7 +224,7 @@ class AsyncContentProducer implements ContentProducer
private boolean consumeAvailableChunks()
{
ServletContextRequest request = _servletChannel.getRequest();
ServletContextRequest request = _servletChannel.getServletContextRequest();
while (true)
{
Content.Chunk chunk = request.read();
@ -288,7 +287,7 @@ class AsyncContentProducer implements ContentProducer
}
_servletChannel.getState().onReadUnready();
_servletChannel.getRequest().demand(() ->
_servletChannel.getServletContextRequest().demand(() ->
{
if (_servletChannel.getHttpInput().onContentProducible())
_servletChannel.handle();
@ -481,7 +480,7 @@ class AsyncContentProducer implements ContentProducer
private Content.Chunk produceRawChunk()
{
Content.Chunk chunk = _servletChannel.getRequest().read();
Content.Chunk chunk = _servletChannel.getServletContextRequest().read();
if (chunk != null)
{
_rawBytesArrived += chunk.remaining();
@ -523,7 +522,7 @@ class AsyncContentProducer implements ContentProducer
}
/**
* A semaphore that assumes working under {@link AsyncContentProducer#lock()} scope.
* A semaphore that assumes working under the same locked scope.
*/
class LockedSemaphore
{

View File

@ -116,7 +116,7 @@ public class AsyncContextState implements AsyncContext
ServletRequest servletRequest = getRequest();
ServletResponse servletResponse = getResponse();
ServletChannel servletChannel = _state.getServletChannel();
HttpServletRequest originalHttpServletRequest = servletChannel.getRequest().getHttpServletRequest();
HttpServletRequest originalHttpServletRequest = servletChannel.getServletContextRequest().getHttpServletRequest();
HttpServletResponse originalHttpServletResponse = servletChannel.getResponse().getHttpServletResponse();
return (servletRequest == originalHttpServletRequest && servletResponse == originalHttpServletResponse);
}

View File

@ -14,7 +14,6 @@
package org.eclipse.jetty.ee10.servlet;
import org.eclipse.jetty.io.Content;
import org.eclipse.jetty.util.thread.AutoLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -29,18 +28,15 @@ class BlockingContentProducer implements ContentProducer
private final AsyncContentProducer _asyncContentProducer;
private final AsyncContentProducer.LockedSemaphore _semaphore;
BlockingContentProducer(AsyncContentProducer delegate)
/**
* @param asyncContentProducer The {@link AsyncContentProducer} to block against.
*/
BlockingContentProducer(AsyncContentProducer asyncContentProducer)
{
_asyncContentProducer = delegate;
_asyncContentProducer = asyncContentProducer;
_semaphore = _asyncContentProducer.newLockedSemaphore();
}
@Override
public AutoLock lock()
{
return _asyncContentProducer.lock();
}
@Override
public void recycle()
{

View File

@ -15,20 +15,12 @@ package org.eclipse.jetty.ee10.servlet;
import org.eclipse.jetty.io.Content;
import org.eclipse.jetty.util.component.Destroyable;
import org.eclipse.jetty.util.thread.AutoLock;
/**
* ContentProducer is the bridge between {@link HttpInput} and {@link Content.Source}.
*/
public interface ContentProducer
{
/**
* Lock this instance. The lock must be held before any of this instance's
* method can be called, and must be released afterward.
* @return the lock that is guarding this instance.
*/
AutoLock lock();
/**
* Clear the interceptor and call {@link Destroyable#destroy()} on it if it implements {@link Destroyable}.
* A recycled {@link ContentProducer} will only produce special content with a non-null error until

View File

@ -37,11 +37,15 @@ public class HttpInput extends ServletInputStream implements Runnable
{
private static final Logger LOG = LoggerFactory.getLogger(HttpInput.class);
/**
* The lock shared with {@link AsyncContentProducer} and this class.
*/
final AutoLock _lock = new AutoLock();
private final ServletChannel _servletChannel;
private final ServletRequestState _channelState;
private final byte[] _oneByteBuffer = new byte[1];
private BlockingContentProducer _blockingContentProducer;
private AsyncContentProducer _asyncContentProducer;
private ServletRequestState _channelState;
private final BlockingContentProducer _blockingContentProducer;
private final AsyncContentProducer _asyncContentProducer;
private final LongAdder _contentConsumed = new LongAdder();
private volatile ContentProducer _contentProducer;
private volatile boolean _consumedEof;
@ -50,22 +54,26 @@ public class HttpInput extends ServletInputStream implements Runnable
public HttpInput(ServletChannel channel)
{
_servletChannel = channel;
_channelState = _servletChannel.getState();
_asyncContentProducer = new AsyncContentProducer(_servletChannel, _lock);
_blockingContentProducer = new BlockingContentProducer(_asyncContentProducer);
_contentProducer = _blockingContentProducer;
}
// TODO avoid this init()
public void recycle()
{
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
if (LOG.isDebugEnabled())
LOG.debug("recycle {}", this);
_blockingContentProducer.recycle();
_contentProducer = _blockingContentProducer;
}
}
public void reopen()
{
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
if (LOG.isDebugEnabled())
LOG.debug("reopen {}", this);
@ -77,20 +85,12 @@ public class HttpInput extends ServletInputStream implements Runnable
}
}
public void init()
{
_channelState = _servletChannel.getState(); // TODO can we change lifecycle so this is known in constructor and can be final
_asyncContentProducer = new AsyncContentProducer(_servletChannel); // TODO avoid object creation or recycle
_blockingContentProducer = new BlockingContentProducer(_asyncContentProducer); // TODO avoid object creation or recycle
_contentProducer = _blockingContentProducer;
}
/**
* @return The current Interceptor, or null if none set
*/
public Interceptor getInterceptor()
{
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
return _contentProducer.getInterceptor();
}
@ -103,7 +103,7 @@ public class HttpInput extends ServletInputStream implements Runnable
*/
public void setInterceptor(Interceptor interceptor)
{
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
if (LOG.isDebugEnabled())
LOG.debug("setting interceptor to {} on {}", interceptor, this);
@ -119,7 +119,7 @@ public class HttpInput extends ServletInputStream implements Runnable
*/
public void addInterceptor(Interceptor interceptor)
{
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
Interceptor currentInterceptor = _contentProducer.getInterceptor();
if (currentInterceptor == null)
@ -173,7 +173,7 @@ public class HttpInput extends ServletInputStream implements Runnable
public long getContentReceived()
{
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
return _contentProducer.getRawBytesArrived();
}
@ -181,7 +181,7 @@ public class HttpInput extends ServletInputStream implements Runnable
public boolean consumeAvailable()
{
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
if (LOG.isDebugEnabled())
LOG.debug("consumeAll {}", this);
@ -198,7 +198,7 @@ public class HttpInput extends ServletInputStream implements Runnable
public boolean isError()
{
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
boolean error = _contentProducer.isError();
if (LOG.isDebugEnabled())
@ -228,7 +228,7 @@ public class HttpInput extends ServletInputStream implements Runnable
@Override
public boolean isReady()
{
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
boolean ready = _contentProducer.isReady();
if (LOG.isDebugEnabled())
@ -257,7 +257,7 @@ public class HttpInput extends ServletInputStream implements Runnable
public boolean onContentProducible()
{
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
return _contentProducer.onContentProducible();
}
@ -266,7 +266,7 @@ public class HttpInput extends ServletInputStream implements Runnable
@Override
public int read() throws IOException
{
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
int read = read(_oneByteBuffer, 0, 1);
if (read == 0)
@ -288,7 +288,7 @@ public class HttpInput extends ServletInputStream implements Runnable
private int read(ByteBuffer buffer, byte[] b, int off, int len) throws IOException
{
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
// Don't try to get content if no bytes were requested to be read.
if (len == 0)
@ -332,7 +332,7 @@ public class HttpInput extends ServletInputStream implements Runnable
private void scheduleReadListenerNotification()
{
_servletChannel.execute(_servletChannel);
_servletChannel.execute(_servletChannel::handle);
}
/**
@ -342,7 +342,7 @@ public class HttpInput extends ServletInputStream implements Runnable
*/
public boolean hasContent()
{
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
// Do not call _contentProducer.available() as it calls HttpChannel.produceContent()
// which is forbidden by this method's contract.
@ -356,7 +356,7 @@ public class HttpInput extends ServletInputStream implements Runnable
@Override
public int available()
{
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
int available = _contentProducer.available();
if (LOG.isDebugEnabled())
@ -375,7 +375,7 @@ public class HttpInput extends ServletInputStream implements Runnable
public void run()
{
Content.Chunk chunk;
try (AutoLock lock = _contentProducer.lock())
try (AutoLock lock = _lock.lock())
{
// Call isReady() to make sure that if not ready we register for fill interest.
if (!_contentProducer.isReady())

View File

@ -354,7 +354,7 @@ public class HttpOutput extends ServletOutputStream implements Runnable
finally
{
if (wake)
_servletChannel.execute(_servletChannel); // TODO review in jetty-10 if execute is needed
_servletChannel.execute(_servletChannel::handle);
}
}
@ -1390,7 +1390,7 @@ public class HttpOutput extends ServletOutputStream implements Runnable
wake = _servletChannel.getState().onWritePossible();
}
if (wake)
_servletChannel.execute(_servletChannel);
_servletChannel.execute(_servletChannel::handle);
}
@Override

View File

@ -58,26 +58,49 @@ import org.slf4j.LoggerFactory;
import static org.eclipse.jetty.util.thread.Invocable.InvocationType.NON_BLOCKING;
/**
* TODO describe what this class does
* The ServletChannel contains the state and behaviors associated with the Servlet API
* lifecycle for a single request/response cycle. Specifically it uses
* {@link ServletRequestState} to coordinate the states of dispatch state, input and
* output according to the servlet specification. The combined state so obtained
* is reflected in the behaviour of the contained {@link HttpInput} implementation of
* {@link jakarta.servlet.ServletInputStream}.
*
* @see ServletRequestState
* @see HttpInput
*/
public class ServletChannel implements Runnable
public class ServletChannel
{
private static final Logger LOG = LoggerFactory.getLogger(ServletChannel.class);
private final ServletRequestState _state;
private final ServletContextHandler.Context _context;
private final ServletContextHandler.ServletContextApi _servletContextApi;
private final AtomicLong _requests = new AtomicLong();
private Connector _connector;
private Executor _executor;
private HttpConfiguration _configuration;
private EndPoint _endPoint;
private ServletRequestState _state;
private ServletContextHandler.ServletContextApi _servletContextApi;
private ServletContextRequest _request;
private boolean _expects100Continue;
private Listener _combinedListener;
private long _oldIdleTimeout;
private Callback _callback;
private final Connector _connector;
private final Executor _executor;
private final HttpConfiguration _configuration;
private final EndPoint _endPoint;
private final HttpInput _httpInput;
private final Listener _combinedListener;
private volatile ServletContextRequest _servletContextRequest;
private volatile boolean _expects100Continue;
private volatile long _oldIdleTimeout;
private volatile Callback _callback;
// Bytes written after interception (e.g. after compression).
private long _written;
private volatile long _written;
public ServletChannel(ServletContextHandler servletContextHandler, Request request)
{
_state = new ServletRequestState(this);
_context = servletContextHandler.getContext();
_servletContextApi = _context.getServletContext();
_connector = request.getConnectionMetaData().getConnector();
_executor = request.getContext();
_configuration = request.getConnectionMetaData().getHttpConfiguration();
_endPoint = request.getConnectionMetaData().getConnection().getEndPoint();
_httpInput = new HttpInput(this);
_combinedListener = new Listeners(_connector, servletContextHandler);
}
public void setCallback(Callback callback)
{
@ -86,35 +109,33 @@ public class ServletChannel implements Runnable
_callback = callback;
}
public void init(ServletContextRequest request)
/**
* Associate this channel with a specific request.
* @param servletContextRequest The request to associate
* @see #recycle()
*/
public void associate(ServletContextRequest servletContextRequest)
{
_connector = request.getConnectionMetaData().getConnector();
_executor = request.getContext();
_configuration = request.getConnectionMetaData().getHttpConfiguration();
_endPoint = request.getConnectionMetaData().getConnection().getEndPoint();
_state = new ServletRequestState(this); // TODO can this be recycled?
_servletContextApi = request.getContext().getServletContext();
_request = request;
_expects100Continue = request.getHeaders().contains(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString());
_combinedListener = new Listeners(request);
request.getHttpInput().init();
_state.recycle();
_httpInput.reopen();
_servletContextRequest = servletContextRequest;
_expects100Continue = servletContextRequest.getHeaders().contains(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString());
if (LOG.isDebugEnabled())
LOG.debug("new {} -> {},{}",
this,
_request,
_servletContextRequest,
_state);
}
public ServletContextHandler.Context getContext()
{
return _request.getContext();
return _context;
}
public ServletContextHandler getContextHandler()
{
return getContext().getContextHandler();
return _context.getContextHandler();
}
public ServletContextHandler.ServletContextApi getServletContext()
@ -124,12 +145,12 @@ public class ServletChannel implements Runnable
public HttpOutput getHttpOutput()
{
return _request.getHttpOutput();
return _servletContextRequest.getHttpOutput();
}
public HttpInput getHttpInput()
{
return _request.getHttpInput();
return _httpInput;
}
public ServletContextHandler.ServletContextApi getServletContextContext()
@ -195,14 +216,15 @@ public class ServletChannel implements Runnable
return _connector.getServer();
}
public ServletContextRequest getRequest()
public ServletContextRequest getServletContextRequest()
{
return _request;
return _servletContextRequest;
}
public ServletContextResponse getResponse()
{
return _request.getResponse();
ServletContextRequest request = _servletContextRequest;
return request == null ? null : request.getResponse();
}
public Connection getConnection()
@ -345,25 +367,25 @@ public class ServletChannel implements Runnable
}
}
public void recycle()
/**
* @see #associate(ServletContextRequest)
*/
private void recycle()
{
_httpInput.recycle();
_servletContextRequest = null;
_callback = null;
_written = 0;
_oldIdleTimeout = 0;
}
@Override
public void run()
{
handle();
}
/**
* @return True if the channel is ready to continue handling (ie it is not suspended)
*/
public boolean handle()
{
if (LOG.isDebugEnabled())
LOG.debug("handle {} {} ", _request.getHttpURI(), this);
LOG.debug("handle {} {} ", _servletContextRequest.getHttpURI(), this);
Action action = _state.handling();
@ -394,10 +416,10 @@ public class ServletChannel implements Runnable
dispatch(DispatcherType.REQUEST, () ->
{
ServletContextHandler.ServletContextApi servletContextApi = getServletContextContext();
ServletHandler servletHandler = servletContextApi.getContext().getServletContextHandler().getServletHandler();
ServletHandler.MappedServlet mappedServlet = _request._mappedServlet;
ServletHandler servletHandler = _context.getServletContextHandler().getServletHandler();
ServletHandler.MappedServlet mappedServlet = _servletContextRequest._mappedServlet;
mappedServlet.handle(servletHandler, Request.getPathInContext(_request), _request.getHttpServletRequest(), _request.getHttpServletResponse());
mappedServlet.handle(servletHandler, Request.getPathInContext(_servletContextRequest), _servletContextRequest.getHttpServletRequest(), _servletContextRequest.getHttpServletResponse());
});
break;
@ -408,15 +430,15 @@ public class ServletChannel implements Runnable
dispatch(DispatcherType.ASYNC, () ->
{
HttpURI uri;
String pathInContext = Request.getPathInContext(_request);
String pathInContext = Request.getPathInContext(_servletContextRequest);
AsyncContextEvent asyncContextEvent = _state.getAsyncContextEvent();
String dispatchString = asyncContextEvent.getDispatchPath();
if (dispatchString != null)
{
String contextPath = _request.getContext().getContextPath();
String contextPath = _context.getContextPath();
HttpURI.Immutable dispatchUri = HttpURI.from(dispatchString);
pathInContext = URIUtil.canonicalPath(dispatchUri.getPath());
uri = HttpURI.build(_request.getHttpURI())
uri = HttpURI.build(_servletContextRequest.getHttpURI())
.path(URIUtil.addPaths(contextPath, pathInContext))
.query(dispatchUri.getQuery());
}
@ -425,13 +447,13 @@ public class ServletChannel implements Runnable
uri = asyncContextEvent.getBaseURI();
if (uri == null)
{
uri = _request.getHttpURI();
uri = _servletContextRequest.getHttpURI();
}
else
{
pathInContext = uri.getCanonicalPath();
if (_request.getContext().getContextPath().length() > 1)
pathInContext = pathInContext.substring(_request.getContext().getContextPath().length());
if (_context.getContextPath().length() > 1)
pathInContext = pathInContext.substring(_context.getContextPath().length());
}
}
@ -454,7 +476,7 @@ public class ServletChannel implements Runnable
// the following is needed as you cannot trust the response code and reason
// as those could have been modified after calling sendError
Integer code = (Integer)_request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
Integer code = (Integer)_servletContextRequest.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (code == null)
code = HttpStatus.INTERNAL_SERVER_ERROR_500;
getResponse().setStatus(code);
@ -464,9 +486,9 @@ public class ServletChannel implements Runnable
// from the failed dispatch, then we try to consume it here and if we fail we add a
// Connection:close. This can't be deferred to COMPLETE as the response will be committed
// by then.
Response.ensureConsumeAvailableOrNotPersistent(_request, _request.getResponse());
Response.ensureConsumeAvailableOrNotPersistent(_servletContextRequest, _servletContextRequest.getResponse());
ContextHandler.Context context = (ContextHandler.Context)_request.getAttribute(ErrorHandler.ERROR_CONTEXT);
ContextHandler.Context context = (ContextHandler.Context)_servletContextRequest.getAttribute(ErrorHandler.ERROR_CONTEXT);
Request.Processor errorProcessor = ErrorHandler.getErrorProcessor(getServer(), context == null ? null : context.getContextHandler());
// If we can't have a body or have no processor, then create a minimal error response.
@ -481,7 +503,7 @@ public class ServletChannel implements Runnable
// _state.completing();
try (Blocker.Callback blocker = Blocker.callback())
{
dispatch(DispatcherType.ERROR, () -> errorProcessor.process(_request, getResponse(), blocker));
dispatch(DispatcherType.ERROR, () -> errorProcessor.process(_servletContextRequest, getResponse(), blocker));
blocker.block();
}
}
@ -510,7 +532,7 @@ public class ServletChannel implements Runnable
finally
{
// clean up the context that was set in Response.sendError
_request.removeAttribute(ErrorHandler.ERROR_CONTEXT);
_servletContextRequest.removeAttribute(ErrorHandler.ERROR_CONTEXT);
}
break;
}
@ -522,15 +544,13 @@ public class ServletChannel implements Runnable
case READ_CALLBACK:
{
ServletContextHandler handler = _state.getContextHandler();
handler.getContext().run(() -> _request.getHttpInput().run());
_context.run(() -> _servletContextRequest.getHttpInput().run());
break;
}
case WRITE_CALLBACK:
{
ServletContextHandler handler = _state.getContextHandler();
handler.getContext().run(() -> _request.getHttpOutput().run());
_context.run(() -> _servletContextRequest.getHttpOutput().run());
break;
}
@ -550,14 +570,14 @@ public class ServletChannel implements Runnable
// Indicate Connection:close if we can't consume all.
if (getResponse().getStatus() >= 200)
Response.ensureConsumeAvailableOrNotPersistent(_request, _request.getResponse());
Response.ensureConsumeAvailableOrNotPersistent(_servletContextRequest, _servletContextRequest.getResponse());
}
// RFC 7230, section 3.3.
if (!_request.isHead() &&
if (!_servletContextRequest.isHead() &&
getResponse().getStatus() != HttpStatus.NOT_MODIFIED_304 &&
!getResponse().isContentComplete(_request.getHttpOutput().getWritten()))
!getResponse().isContentComplete(_servletContextRequest.getHttpOutput().getWritten()))
{
if (sendErrorOrAbort("Insufficient content written"))
break;
@ -625,21 +645,21 @@ public class ServletChannel implements Runnable
{
try
{
_request.getResponse().getHttpOutput().reopen();
_servletContextApi.getContext().getServletContextHandler().requestInitialized(_request, _request.getHttpServletRequest());
_servletContextRequest.getResponse().getHttpOutput().reopen();
_context.getServletContextHandler().requestInitialized(_servletContextRequest, _servletContextRequest.getHttpServletRequest());
getHttpOutput().reopen();
_combinedListener.onBeforeDispatch(_request);
_combinedListener.onBeforeDispatch(_servletContextRequest);
dispatchable.dispatch();
}
catch (Throwable x)
{
_combinedListener.onDispatchFailure(_request, x);
_combinedListener.onDispatchFailure(_servletContextRequest, x);
throw x;
}
finally
{
_combinedListener.onAfterDispatch(_request);
_servletContextApi.getContext().getServletContextHandler().requestDestroyed(_request, _request.getHttpServletRequest());
_combinedListener.onAfterDispatch(_servletContextRequest);
_context.getServletContextHandler().requestDestroyed(_servletContextRequest, _servletContextRequest.getHttpServletRequest());
}
}
@ -661,19 +681,20 @@ public class ServletChannel implements Runnable
if (quiet != null || !getServer().isRunning())
{
if (LOG.isDebugEnabled())
LOG.debug(_request.getHttpServletRequest().getRequestURI(), failure);
LOG.debug(_servletContextRequest.getHttpServletRequest().getRequestURI(), failure);
}
else if (noStack != null)
{
// No stack trace unless there is debug turned on
if (LOG.isDebugEnabled())
LOG.warn("handleException {}", _request.getHttpServletRequest().getRequestURI(), failure);
LOG.warn("handleException {}", _servletContextRequest.getHttpServletRequest().getRequestURI(), failure);
else
LOG.warn("handleException {} {}", _request.getHttpServletRequest().getRequestURI(), noStack.toString());
LOG.warn("handleException {} {}", _servletContextRequest.getHttpServletRequest().getRequestURI(), noStack.toString());
}
else
{
LOG.warn(_request.getHttpServletRequest().getRequestURI(), failure);
ServletContextRequest request = _servletContextRequest;
LOG.warn(request == null ? "unknown request" : request.getHttpServletRequest().getRequestURI(), failure);
}
if (isCommitted())
@ -740,14 +761,14 @@ public class ServletChannel implements Runnable
@Override
public String toString()
{
if (_request == null)
if (_servletContextRequest == null)
{
return String.format("%s@%x{null}",
getClass().getSimpleName(),
hashCode());
}
long timeStamp = _request.getTimeStamp();
long timeStamp = _servletContextRequest.getTimeStamp();
return String.format("%s@%x{s=%s,r=%s,c=%b/%b,a=%s,uri=%s,age=%d}",
getClass().getSimpleName(),
hashCode(),
@ -756,7 +777,7 @@ public class ServletChannel implements Runnable
isRequestCompleted(),
isResponseCompleted(),
_state.getState(),
_request.getHttpURI(),
_servletContextRequest.getHttpURI(),
timeStamp == 0 ? 0 : System.currentTimeMillis() - timeStamp);
}
@ -776,13 +797,16 @@ public class ServletChannel implements Runnable
void onTrailers(HttpFields trailers)
{
_request.setTrailers(trailers);
_combinedListener.onRequestTrailers(_request);
_servletContextRequest.setTrailers(trailers);
_combinedListener.onRequestTrailers(_servletContextRequest);
}
/**
* @see #abort(Throwable)
*/
public void onCompleted()
{
ServletContextRequest.ServletApiRequest apiRequest = _request.getServletApiRequest();
ServletContextRequest.ServletApiRequest apiRequest = _servletContextRequest.getServletApiRequest();
if (LOG.isDebugEnabled())
LOG.debug("onCompleted for {} written={}", apiRequest.getRequestURI(), getBytesWritten());
@ -794,19 +818,26 @@ public class ServletChannel implements Runnable
{
Authentication authentication = apiRequest.getAuthentication();
if (authentication instanceof Authentication.User userAuthentication)
_request.setAttribute(CustomRequestLog.USER_NAME, userAuthentication.getUserIdentity().getUserPrincipal().getName());
_servletContextRequest.setAttribute(CustomRequestLog.USER_NAME, userAuthentication.getUserIdentity().getUserPrincipal().getName());
String realPath = apiRequest.getServletContext().getRealPath(Request.getPathInContext(_request));
_request.setAttribute(CustomRequestLog.REAL_PATH, realPath);
String realPath = apiRequest.getServletContext().getRealPath(Request.getPathInContext(_servletContextRequest));
_servletContextRequest.setAttribute(CustomRequestLog.REAL_PATH, realPath);
String servletName = _request.getServletName();
_request.setAttribute(CustomRequestLog.HANDLER_NAME, servletName);
String servletName = _servletContextRequest.getServletName();
_servletContextRequest.setAttribute(CustomRequestLog.HANDLER_NAME, servletName);
}
// Callback will either be succeeded here or failed in abort().
Callback callback = _callback;
ServletContextRequest servletContextRequest = _servletContextRequest;
// Must recycle before notification to allow for reuse.
// Recycle always done here even if an abort is called.
recycle();
if (_state.completeResponse())
_callback.succeeded();
_combinedListener.onComplete(_request);
{
_combinedListener.onComplete(servletContextRequest);
callback.succeeded();
}
}
public boolean isCommitted()
@ -840,6 +871,7 @@ public class ServletChannel implements Runnable
* then this method should be called.
*
* @param failure the failure that caused the abort.
* @see #onCompleted()
*/
public void abort(Throwable failure)
{
@ -848,8 +880,9 @@ public class ServletChannel implements Runnable
{
if (LOG.isDebugEnabled())
LOG.debug("abort {}", this, failure);
_combinedListener.onResponseFailure(_request, failure);
_callback.failed(failure);
Callback callback = _callback;
_combinedListener.onResponseFailure(_servletContextRequest, failure);
callback.failed(failure);
}
}
@ -1032,10 +1065,10 @@ public class ServletChannel implements Runnable
{
private final List<Listener> _listeners;
private Listeners(ServletContextRequest request)
private Listeners(Connector connector, ServletContextHandler servletContextHandler)
{
Collection<Listener> connectorListeners = request.getConnectionMetaData().getConnector().getBeans(Listener.class);
List<Listener> handlerListeners = request.getContext().getServletContextHandler().getEventListeners().stream()
Collection<Listener> connectorListeners = connector.getBeans(Listener.class);
List<Listener> handlerListeners = servletContextHandler.getEventListeners().stream()
.filter(l -> l instanceof Listener)
.map(Listener.class::cast)
.toList();

View File

@ -80,6 +80,7 @@ import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.ContextRequest;
import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.DecoratedObjectFactory;
import org.eclipse.jetty.util.DeprecationWarning;
import org.eclipse.jetty.util.ExceptionUtil;
@ -1157,19 +1158,17 @@ public class ServletContextHandler extends ContextHandler implements Graceful
return null;
// Get a servlet request, possibly from a cached version in the channel attributes.
// TODO We should cache this heavy weight object! Something like:
// TODO: ServletChannel is not properly cleared out so I have disabled the caching of this for now.
ServletChannel servletChannel = null; // (ServletChannel)request.getComponents().getCache().get("blah.blah.ServletChannel");
if (servletChannel == null)
Attributes cache = request.getComponents().getCache();
ServletChannel servletChannel = (ServletChannel)cache.getAttribute(ServletChannel.class.getName());
if (servletChannel == null || servletChannel.getContext() != getContext())
{
// TODO this may not be the right object to recycle, but ultimately we want to reuse: HttpInput, HttpOutput, ServletChannelState etc. etc.
servletChannel = new ServletChannel();
// request.getComponents().getCache().put("blah.blah.ServletChannel", servletChannel); TODO: Re-enable.
servletChannel = new ServletChannel(this, request);
cache.setAttribute(ServletChannel.class.getName(), servletChannel);
}
ServletContextRequest servletContextRequest = new ServletContextRequest(_servletContext, servletChannel, request, pathInContext,
matchedResource.getResource(), matchedResource.getPathSpec(), matchedResource.getMatchedPath());
servletChannel.init(servletContextRequest);
servletChannel.associate(servletContextRequest);
return servletContextRequest;
}

View File

@ -79,7 +79,6 @@ import org.eclipse.jetty.server.handler.ContextRequest;
import org.eclipse.jetty.server.handler.ContextResponse;
import org.eclipse.jetty.session.Session;
import org.eclipse.jetty.session.SessionManager;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.Fields;
import org.eclipse.jetty.util.HostPort;
import org.eclipse.jetty.util.StringUtil;
@ -105,7 +104,7 @@ public class ServletContextRequest extends ContextRequest implements Runnable
Object channel = request.getAttribute(ServletChannel.class.getName());
if (channel instanceof ServletChannel)
return ((ServletChannel)channel).getRequest();
return ((ServletChannel)channel).getServletContextRequest();
while (request instanceof ServletRequestWrapper)
{
@ -143,7 +142,7 @@ public class ServletContextRequest extends ContextRequest implements Runnable
_servletChannel = servletChannel;
_httpServletRequest = new ServletApiRequest();
_mappedServlet = mappedServlet;
_httpInput = new HttpInput(_servletChannel); // TODO recycle
_httpInput = _servletChannel.getHttpInput();
_pathInContext = pathInContext;
_pathSpec = pathSpec;
_matchedPath = matchedPath;
@ -154,13 +153,6 @@ public class ServletContextRequest extends ContextRequest implements Runnable
return _pathInContext;
}
@Override
public void process(Request request, Response response, Callback callback) throws Exception
{
_servletChannel.setCallback(callback);
super.process(request, response, callback);
}
@Override
public HttpFields getTrailers()
{

View File

@ -366,7 +366,7 @@ public class ServletContextResponse extends ContextResponse
}
// Try any default char encoding for the context.
ServletContext context = _servletChannel.getRequest().getContext().getServletContext();
ServletContext context = _servletChannel.getServletContextRequest().getContext().getServletContext();
if (context != null)
{
encoding = context.getResponseCharacterEncoding();

View File

@ -438,6 +438,7 @@ public class ServletHandler extends Handler.Wrapper
{
// We will always have a ServletScopedRequest and MappedServlet otherwise we will not reach ServletHandler.
ServletContextRequest servletRequest = Request.as(request, ServletContextRequest.class);
servletRequest.getServletChannel().setCallback(cb);
servletRequest.getServletChannel().handle();
};
}

View File

@ -480,7 +480,7 @@ public class ServletRequestState
return Action.WRITE_CALLBACK;
}
Scheduler scheduler = _servletChannel.getRequest()
Scheduler scheduler = _servletChannel.getServletContextRequest()
.getConnectionMetaData().getConnector().getScheduler();
if (scheduler != null && _timeoutMs > 0 && !_event.hasTimeoutTask())
_event.setTimeoutTask(scheduler.schedule(_event, _timeoutMs, TimeUnit.MILLISECONDS));
@ -733,7 +733,7 @@ public class ServletRequestState
cancelTimeout(event);
if (handle)
runInContext(event, _servletChannel);
runInContext(event, _servletChannel::handle);
}
public void asyncError(Throwable failure)
@ -767,7 +767,7 @@ public class ServletRequestState
if (event != null)
{
cancelTimeout(event);
runInContext(event, _servletChannel);
runInContext(event, _servletChannel::handle);
}
}
@ -859,7 +859,7 @@ public class ServletRequestState
// No sync as this is always called with lock held
// Determine the actual details of the exception
final Request request = _servletChannel.getRequest();
final Request request = _servletChannel.getServletContextRequest();
final int code;
final String message;
Throwable cause = _servletChannel.unwrap(th, BadMessageException.class, UnavailableException.class);
@ -910,10 +910,10 @@ public class ServletRequestState
// - after unhandle for sync
// - after both unhandle and complete for async
ServletContextRequest servletContextRequest = _servletChannel.getRequest();
ServletContextRequest servletContextRequest = _servletChannel.getServletContextRequest();
HttpServletRequest httpServletRequest = servletContextRequest.getHttpServletRequest();
final Request request = _servletChannel.getRequest();
final Request request = _servletChannel.getServletContextRequest();
final Response response = _servletChannel.getResponse();
if (message == null)
message = HttpStatus.getMessage(code);
@ -1110,7 +1110,7 @@ public class ServletRequestState
protected void scheduleDispatch()
{
// TODO long winded!!!
_servletChannel.getRequest().getConnectionMetaData().getConnector().getExecutor().execute(_servletChannel);
_servletChannel.getServletContextRequest().getConnectionMetaData().getConnector().getExecutor().execute(_servletChannel::handle);
}
protected void cancelTimeout()
@ -1198,7 +1198,7 @@ public class ServletRequestState
if (event != null && event.getSuppliedResponse() != null)
return event.getSuppliedResponse();
ServletContextRequest servletContextRequest = _servletChannel.getRequest();
ServletContextRequest servletContextRequest = _servletChannel.getServletContextRequest();
if (servletContextRequest != null)
return servletContextRequest.getHttpServletResponse();
return null;
@ -1211,17 +1211,17 @@ public class ServletRequestState
public Object getAttribute(String name)
{
return _servletChannel.getRequest().getAttribute(name);
return _servletChannel.getServletContextRequest().getAttribute(name);
}
public void removeAttribute(String name)
{
_servletChannel.getRequest().removeAttribute(name);
_servletChannel.getServletContextRequest().removeAttribute(name);
}
public void setAttribute(String name, Object attribute)
{
_servletChannel.getRequest().setAttribute(name, attribute);
_servletChannel.getServletContextRequest().setAttribute(name, attribute);
}
/**

View File

@ -42,7 +42,6 @@ import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.logging.StacklessLogging;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpChannel;
import org.eclipse.jetty.server.LocalConnector;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
@ -151,7 +150,6 @@ public class ErrorPageTest
rawRequest.append("\r\n");
String rawResponse = _connector.getResponse(rawRequest.toString());
System.out.println(rawResponse);
HttpTester.Response response = HttpTester.parseResponse(rawResponse);
assertThat(response.getStatus(), is(595));
@ -311,7 +309,7 @@ public class ErrorPageTest
public void testErrorException() throws Exception
{
_errorPageErrorHandler.setUnwrapServletException(false);
try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class))
try (StacklessLogging stackless = new StacklessLogging(ServletChannel.class))
{
String response = _connector.getResponse("GET /fail/exception HTTP/1.0\r\n\r\n");
assertThat(response, Matchers.containsString("HTTP/1.1 500 Server Error"));
@ -332,7 +330,7 @@ public class ErrorPageTest
}
_errorPageErrorHandler.setUnwrapServletException(true);
try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class))
try (StacklessLogging stackless = new StacklessLogging(ServletChannel.class))
{
String response = _connector.getResponse("GET /fail/exception HTTP/1.0\r\n\r\n");
assertThat(response, Matchers.containsString("HTTP/1.1 500 Server Error"));
@ -369,7 +367,7 @@ public class ErrorPageTest
@Test
public void testGlobalErrorException() throws Exception
{
try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class))
try (StacklessLogging stackless = new StacklessLogging(ServletChannel.class))
{
String response = _connector.getResponse("GET /fail/global?code=NAN HTTP/1.0\r\n\r\n");
assertThat(response, Matchers.containsString("HTTP/1.1 500 Server Error"));
@ -494,7 +492,7 @@ public class ErrorPageTest
{
try (StacklessLogging ignore = new StacklessLogging(_context.getLogger()))
{
try (StacklessLogging ignore2 = new StacklessLogging(HttpChannel.class))
try (StacklessLogging ignore2 = new StacklessLogging(ServletChannel.class))
{
__destroyed = new AtomicBoolean(false);
String response = _connector.getResponse("GET /unavailable/info HTTP/1.0\r\n\r\n");
@ -510,7 +508,7 @@ public class ErrorPageTest
{
try (StacklessLogging ignore = new StacklessLogging(_context.getLogger()))
{
try (StacklessLogging ignore2 = new StacklessLogging(HttpChannel.class))
try (StacklessLogging ignore2 = new StacklessLogging(ServletChannel.class))
{
__destroyed = new AtomicBoolean(false);
String response = _connector.getResponse("GET /unavailable/info?for=1 HTTP/1.0\r\n\r\n");

View File

@ -201,9 +201,16 @@ public abstract class EventSourceServlet extends HttpServlet
}
catch (IOException x)
{
// The other peer closed the connection
close();
eventSource.onClose();
try
{
// The other peer closed the connection
close();
eventSource.onClose();
}
catch (Throwable t)
{
t.printStackTrace();
}
}
}

View File

@ -51,7 +51,7 @@ public class ClientCrossContextSessionTest
{
String contextA = "/contextA";
String contextB = "/contextB";
String servletMapping = "/server";
String servletPath = "/server";
DefaultSessionCacheFactory cacheFactory = new DefaultSessionCacheFactory();
cacheFactory.setEvictionPolicy(SessionCache.NEVER_EVICT);
@ -62,11 +62,11 @@ public class ClientCrossContextSessionTest
TestServletA servletA = new TestServletA();
ServletHolder holderA = new ServletHolder(servletA);
ServletContextHandler ctxA = server.addContext(contextA);
ctxA.addServlet(holderA, servletMapping);
ctxA.addServlet(holderA, servletPath);
ServletContextHandler ctxB = server.addContext(contextB);
TestServletB servletB = new TestServletB();
ServletHolder holderB = new ServletHolder(servletB);
ctxB.addServlet(holderB, servletMapping);
ctxB.addServlet(holderB, servletPath);
try
{
@ -78,15 +78,15 @@ public class ClientCrossContextSessionTest
try
{
// Perform a request to contextA
ContentResponse response = client.GET("http://localhost:" + port + contextA + servletMapping);
ContentResponse responseA = client.GET("http://localhost:" + port + contextA + servletPath);
assertEquals(HttpServletResponse.SC_OK, response.getStatus());
String sessionCookie = response.getHeaders().get("Set-Cookie");
assertEquals(HttpServletResponse.SC_OK, responseA.getStatus());
String sessionCookie = responseA.getHeaders().get("Set-Cookie");
assertNotNull(sessionCookie);
String sessionId = SessionTestSupport.extractSessionId(sessionCookie);
// Perform a request to contextB with the same session cookie
Request request = client.newRequest("http://localhost:" + port + contextB + servletMapping);
Request request = client.newRequest("http://localhost:" + port + contextB + servletPath);
HttpField cookie = new HttpField("Cookie", "JSESSIONID=" + sessionId);
request.headers(headers -> headers.put(cookie));
ContentResponse responseB = request.send();
@ -131,7 +131,7 @@ public class ClientCrossContextSessionTest
public static class TestServletB extends HttpServlet
{
private static final long serialVersionUID = 1L;
public String sessionId;
public volatile String sessionId;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException

View File

@ -2434,11 +2434,11 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
@Override
protected ContextRequest wrap(org.eclipse.jetty.server.Request request)
{
HttpChannel httpChannel = (HttpChannel)request.getComponents().getCache().get(HttpChannel.class.getName());
HttpChannel httpChannel = (HttpChannel)request.getComponents().getCache().getAttribute(HttpChannel.class.getName());
if (httpChannel == null)
{
httpChannel = new HttpChannel(ContextHandler.this, request.getConnectionMetaData());
request.getComponents().getCache().put(HttpChannel.class.getName(), httpChannel);
request.getComponents().getCache().setAttribute(HttpChannel.class.getName(), httpChannel);
}
else if (httpChannel.getContextHandler() == ContextHandler.this)
{