Interface RequestContext
- All Known Subinterfaces:
ClientRequestContext
,ServiceRequestContext
- All Known Implementing Classes:
ClientRequestContextWrapper
,DefaultClientRequestContext
,DefaultServiceRequestContext
,NonWrappingRequestContext
,RequestContextWrapper
,ServiceRequestContextWrapper
public interface RequestContext
Request
, its Response
and related utilities.
A server-side Request
has a ServiceRequestContext
and
a client-side Request
has a ClientRequestContext
.-
Method Summary
Modifier and Type Method Description default ByteBufAllocator
alloc()
Returns theByteBufAllocator
for thisRequestContext
.<V> V
attr(AttributeKey<V> key)
Returns the value mapped to the givenAttributeKey
ornull
if there's no value set bysetAttr(AttributeKey, Object)
,setAttrIfAbsent(AttributeKey, Object)
orcomputeAttrIfAbsent(AttributeKey, Function)
.Iterator<Map.Entry<AttributeKey<?>,Object>>
attrs()
<V> V
computeAttrIfAbsent(AttributeKey<V> key, Function<? super AttributeKey<V>,? extends V> mappingFunction)
If the specifiedAttributeKey
is not already associated with a value (or is mapped tonull
), attempts to compute its value using the given mapping function and stores it into this context.default EventLoop
contextAwareEventLoop()
Returns anEventLoop
that will make sure thisRequestContext
is set as the current context before executing any callback.default Executor
contextAwareExecutor()
Returns anExecutor
that will make sure thisRequestContext
is set as the current context before executing any callback.static <T extends RequestContext>
Tcurrent()
Returns the context of theRequest
that is being handled in the current thread.static <T extends RequestContext>
TcurrentOrNull()
Returns the context of theRequest
that is being handled in the current thread.String
decodedPath()
Returns the absolute path part of the currentRequest
URI, excluding the query part, decoded in UTF-8.EventLoop
eventLoop()
default Executor
executor()
RequestId
id()
boolean
isTimedOut()
Returns whether thisRequestContext
has been timed-out (e.g., when the corresponding request passes a deadline).<A extends SocketAddress>
AlocalAddress()
Returns the local address of this request, ornull
if the connection is not established yet.RequestLogAccess
log()
Returns theRequestLogAccess
that provides the access to theRequestLog
, which contains the information collected while processing the currentRequest
.RequestLogBuilder
logBuilder()
Returns theRequestLogBuilder
that collects the information about the currentRequest
.default Runnable
makeContextAware(Runnable runnable)
Returns aRunnable
that makes sure the currentRequestContext
is set and then invokes the inputrunnable
.default <T> Callable<T>
makeContextAware(Callable<T> callable)
Returns aCallable
that makes sure the currentRequestContext
is set and then invokes the inputcallable
.default <T> CompletableFuture<T>
makeContextAware(CompletableFuture<T> future)
Returns aCompletableFuture
that makes sure the currentRequestContext
is set and then invokes the inputfuture
.default <T> CompletionStage<T>
makeContextAware(CompletionStage<T> stage)
Returns aCompletionStage
that makes sure the currentRequestContext
is set and then invokes the inputstage
.default Executor
makeContextAware(Executor executor)
Returns anExecutor
that will execute callbacks in the givenexecutor
, making sure to propagate the currentRequestContext
into the callback execution.default ExecutorService
makeContextAware(ExecutorService executor)
Returns anExecutorService
that will execute callbacks in the givenexecutor
, making sure to propagate the currentRequestContext
into the callback execution.default ScheduledExecutorService
makeContextAware(ScheduledExecutorService executor)
Returns aScheduledExecutorService
that will execute callbacks in the givenexecutor
, making sure to propagate the currentRequestContext
into the callback execution.default <T, U> BiConsumer<T,U>
makeContextAware(BiConsumer<T,U> action)
Returns aBiConsumer
that makes sure the currentRequestContext
is set and then invokes the inputaction
.default <T, U, V> BiFunction<T,U,V>
makeContextAware(BiFunction<T,U,V> function)
Returns aBiFunction
that makes sure the currentRequestContext
is set and then invokes the inputfunction
.default <T> Consumer<T>
makeContextAware(Consumer<T> action)
Returns aConsumer
that makes sure the currentRequestContext
is set and then invokes the inputaction
.default <T, R> Function<T,R>
makeContextAware(Function<T,R> function)
Returns aFunction
that makes sure the currentRequestContext
is set and then invokes the inputfunction
.default Logger
makeContextAware(Logger logger)
Returns aLogger
which prepends thisRequestContext
to the log message.static <T> T
mapCurrent(Function<? super RequestContext,T> mapper, Supplier<T> defaultValueSupplier)
Maps the context of theRequest
that is being handled in the current thread.MeterRegistry
meterRegistry()
Returns theMeterRegistry
that collects various stats.HttpMethod
method()
Returns the HTTP method of the currentRequest
.RequestContext
newDerivedContext(RequestId id, HttpRequest req, RpcRequest rpcReq)
Deprecated.This method will be removed without a replacement.<V> V
ownAttr(AttributeKey<V> key)
Returns the value mapped to the givenAttributeKey
ornull
if there's no value set bysetAttr(AttributeKey, Object)
,setAttrIfAbsent(AttributeKey, Object)
orcomputeAttrIfAbsent(AttributeKey, Function)
.Iterator<Map.Entry<AttributeKey<?>,Object>>
ownAttrs()
String
path()
SafeCloseable
push()
Pushes the specified context to the thread-local stack.String
query()
<A extends SocketAddress>
AremoteAddress()
Returns the remote address of this request, ornull
if the connection is not established yet.default SafeCloseable
replace()
Replaces the currentRequestContext
in the thread-local with this context without any validation.HttpRequest
request()
Returns theHttpRequest
associated with this context, ornull
if there's noHttpRequest
associated with this context yet.ServiceRequestContext
root()
Returns the rootServiceRequestContext
of this context.RpcRequest
rpcRequest()
Returns theRpcRequest
associated with this context, ornull
if there's noRpcRequest
associated with this context.SessionProtocol
sessionProtocol()
Returns theSessionProtocol
of the currentRequest
.<V> void
setAttr(AttributeKey<V> key, V value)
Associates the specified value with the givenAttributeKey
in this context.<V> V
setAttrIfAbsent(AttributeKey<V> key, V value)
Associates the specified value with the givenAttributeKey
in this context only if this context does not contain a mapping for theAttributeKey
.SSLSession
sslSession()
TheSSLSession
for this request if the connection is made over TLS, ornull
if the connection is not established yet or the connection is not a TLS connection.void
timeoutNow()
Triggers the current timeout immediately if a timeout was scheduled before.void
updateRequest(HttpRequest req)
Replaces theHttpRequest
associated with this context with the specified one.void
updateRpcRequest(RpcRequest rpcReq)
Replaces theRpcRequest
associated with this context with the specified one.
-
Method Details
-
current
Returns the context of theRequest
that is being handled in the current thread.- Throws:
IllegalStateException
- if the context is unavailable in the current thread
-
currentOrNull
Returns the context of theRequest
that is being handled in the current thread.- Returns:
- the
RequestContext
available in the current thread, ornull
if unavailable.
-
mapCurrent
@Nullable static <T> T mapCurrent(Function<? super RequestContext,T> mapper, @Nullable Supplier<T> defaultValueSupplier)Maps the context of theRequest
that is being handled in the current thread.- Parameters:
mapper
- theFunction
that maps theRequestContext
defaultValueSupplier
- theSupplier
that provides the value when the context is unavailable in the current thread. Ifnull
, thenull
will be returned when the context is unavailable in the current thread.
-
root
Returns the rootServiceRequestContext
of this context.- Returns:
- the root
ServiceRequestContext
, ornull
if this context was not created in the context of a server request.
-
attr
Returns the value mapped to the givenAttributeKey
ornull
if there's no value set bysetAttr(AttributeKey, Object)
,setAttrIfAbsent(AttributeKey, Object)
orcomputeAttrIfAbsent(AttributeKey, Function)
.Searching for attributes in a root context
Note: This section applies only to a
ClientRequestContext
. AServiceRequestContext
always has itself as aroot()
.If the value does not exist in this context but only in
root()
, this method will return the value from theroot()
.
If the value exists both in this context andClientRequestContext ctx = ...; assert ctx.root().attr(KEY).equals("root"); assert ctx.attr(KEY).equals("root"); assert ctx.ownAttr(KEY) == null;
root()
, this method will return the value from this context.ClientRequestContext ctx = ...; assert ctx.root().attr(KEY).equals("root"); assert ctx.ownAttr(KEY).equals("child"); assert ctx.attr(KEY).equals("child");
- See Also:
ownAttr(AttributeKey)
-
ownAttr
Returns the value mapped to the givenAttributeKey
ornull
if there's no value set bysetAttr(AttributeKey, Object)
,setAttrIfAbsent(AttributeKey, Object)
orcomputeAttrIfAbsent(AttributeKey, Function)
.Unlike
attr(AttributeKey)
, this does not search inroot()
.- See Also:
attr(AttributeKey)
-
attrs
Iterator<Map.Entry<AttributeKey<?>,Object>> attrs()Returns theIterator
of allMap.Entry
s this context contains.Searching for attributes in a root context
Note: This section applies only to a
ClientRequestContext
. AServiceRequestContext
always has itself as aroot()
.The
Iterator
returned by this method will also yield theMap.Entry
s from theroot()
except those whoseAttributeKey
exist already in this context, e.g.
Please note that any changes made to theClientRequestContext ctx = ...; assert ctx.ownAttr(KEY_A).equals("child_a"); assert ctx.root().attr(KEY_A).equals("root_a"); assert ctx.root().attr(KEY_B).equals("root_b"); Iterator<Entry<AttributeKey<?>, Object>> attrs = ctx.attrs(); assert attrs.next().getValue().equals("child_a"); // KEY_A // Skip KEY_A in the root. assert attrs.next().getValue().equals("root_b"); // KEY_B assert attrs.hasNext() == false;
Map.Entry
returned byIterator.next()
never affects theMap.Entry
owned byroot()
. For example:
If you want to change the value from the root while iterating, please callClientRequestContext ctx = ...; assert ctx.root().attr(KEY).equals("root"); assert ctx.ownAttr(KEY) == null; Iterator<Entry<AttributeKey<?>, Object>> attrs = ctx.attrs(); Entry<AttributeKey<?>, Object> next = attrs.next(); assert next.getKey() == KEY; // Overriding the root entry creates the client context's own entry. next.setValue("child"); assert ctx.attr(KEY).equals("child"); assert ctx.ownAttr(KEY).equals("child"); // root attribute remains unaffected. assert ctx.root().attr(KEY).equals("root");
attrs()
fromroot()
.ClientRequestContext ctx = ...; assert ctx.root().attr(KEY).equals("root"); assert ctx.ownAttr(KEY) == null; // Call attrs() from the root to set a value directly while iterating. Iterator<Entry<AttributeKey<?>, Object>> attrs = ctx.root().attrs(); Entry<AttributeKey<?>, Object> next = attrs.next(); assert next.getKey() == KEY; next.setValue("another_root"); // The ctx does not have its own attribute. assert ctx.ownAttr(KEY) == null; assert ctx.attr(KEY).equals("another_root");
- See Also:
ownAttrs()
-
ownAttrs
Iterator<Map.Entry<AttributeKey<?>,Object>> ownAttrs()- See Also:
attrs()
-
setAttr
Associates the specified value with the givenAttributeKey
in this context. If this context previously contained a mapping for theAttributeKey
, the old value is replaced by the specified value. Setnull
not to iterate the mapping fromattrs()
. -
setAttrIfAbsent
Associates the specified value with the givenAttributeKey
in this context only if this context does not contain a mapping for theAttributeKey
.- Returns:
null
if there was no mapping for theAttributeKey
or the old value if there's a mapping for theAttributeKey
.
-
computeAttrIfAbsent
@Nullable <V> V computeAttrIfAbsent(AttributeKey<V> key, Function<? super AttributeKey<V>,? extends V> mappingFunction)If the specifiedAttributeKey
is not already associated with a value (or is mapped tonull
), attempts to compute its value using the given mapping function and stores it into this context.If the mapping function returns
null
, no mapping is recorded.- Returns:
- the current (existing or computed) value associated with
the specified
AttributeKey
, ornull
if the computed value isnull
-
request
Returns theHttpRequest
associated with this context, ornull
if there's noHttpRequest
associated with this context yet. -
rpcRequest
Returns theRpcRequest
associated with this context, ornull
if there's noRpcRequest
associated with this context. -
updateRequest
Replaces theHttpRequest
associated with this context with the specified one. This method is useful to a decorator that manipulates HTTP request headers.Note that it is a bad idea to change the values of the pseudo headers (
":method"
,":path"
,":scheme"
and":authority"
) when replacing anHttpRequest
, because the properties of this context, such aspath()
, are unaffected by such an attempt. -
updateRpcRequest
Replaces theRpcRequest
associated with this context with the specified one. This method is useful to a decorator that manipulates an RPC call. -
sessionProtocol
SessionProtocol sessionProtocol()Returns theSessionProtocol
of the currentRequest
. -
remoteAddress
Returns the remote address of this request, ornull
if the connection is not established yet. -
localAddress
Returns the local address of this request, ornull
if the connection is not established yet. -
sslSession
TheSSLSession
for this request if the connection is made over TLS, ornull
if the connection is not established yet or the connection is not a TLS connection. -
id
RequestId id() -
method
HttpMethod method()Returns the HTTP method of the currentRequest
. -
path
String path() -
decodedPath
String decodedPath()Returns the absolute path part of the currentRequest
URI, excluding the query part, decoded in UTF-8. -
query
-
log
RequestLogAccess log()Returns theRequestLogAccess
that provides the access to theRequestLog
, which contains the information collected while processing the currentRequest
. -
logBuilder
RequestLogBuilder logBuilder()Returns theRequestLogBuilder
that collects the information about the currentRequest
. -
meterRegistry
MeterRegistry meterRegistry()Returns theMeterRegistry
that collects various stats. -
timeoutNow
void timeoutNow()Triggers the current timeout immediately if a timeout was scheduled before. Otherwise, the currentRequest
will be timed-out immediately after a timeout scheduler is initialized. -
isTimedOut
boolean isTimedOut()Returns whether thisRequestContext
has been timed-out (e.g., when the corresponding request passes a deadline). -
executor
-
eventLoop
EventLoop eventLoop() -
alloc
Returns theByteBufAllocator
for thisRequestContext
. Any buffers created by thisByteBufAllocator
must be reference-counted. If you don't know what this means, you should probably usebyte[]
orByteBuffer
directly instead of calling this method. -
contextAwareExecutor
Returns anExecutor
that will make sure thisRequestContext
is set as the current context before executing any callback. This should almost always be used for executing asynchronous callbacks in service code to make sure features that require theRequestContext
work properly. Most asynchronous libraries likeCompletableFuture
provide methods that accept anExecutor
to run callbacks on. -
contextAwareEventLoop
Returns anEventLoop
that will make sure thisRequestContext
is set as the current context before executing any callback. -
push
SafeCloseable push()Pushes the specified context to the thread-local stack. To pop the context from the stack, callSafeCloseable.close()
, which can be done using atry-with-resources
block:try (SafeCloseable ignored = ctx.push()) { ... }
This method may throw an
IllegalStateException
according to the status of the current thread-local. Please seeServiceRequestContext.push()
andClientRequestContext.push()
to find out the satisfying conditions. -
replace
Replaces the currentRequestContext
in the thread-local with this context without any validation. This method also does not run any callbacks.Note: Do not use this if you don't know what you are doing. This method does not prevent the situation where a wrong
RequestContext
is pushed into the thread-local. Usepush()
instead. -
makeContextAware
Returns anExecutor
that will execute callbacks in the givenexecutor
, making sure to propagate the currentRequestContext
into the callback execution. It is generally preferred to usecontextAwareEventLoop()
to ensure the callback stays on the same thread as well. -
makeContextAware
Returns anExecutorService
that will execute callbacks in the givenexecutor
, making sure to propagate the currentRequestContext
into the callback execution. -
makeContextAware
Returns aScheduledExecutorService
that will execute callbacks in the givenexecutor
, making sure to propagate the currentRequestContext
into the callback execution. -
makeContextAware
Returns aCallable
that makes sure the currentRequestContext
is set and then invokes the inputcallable
. -
makeContextAware
Returns aRunnable
that makes sure the currentRequestContext
is set and then invokes the inputrunnable
. -
makeContextAware
Returns aFunction
that makes sure the currentRequestContext
is set and then invokes the inputfunction
. -
makeContextAware
Returns aBiFunction
that makes sure the currentRequestContext
is set and then invokes the inputfunction
. -
makeContextAware
Returns aConsumer
that makes sure the currentRequestContext
is set and then invokes the inputaction
. -
makeContextAware
Returns aBiConsumer
that makes sure the currentRequestContext
is set and then invokes the inputaction
. -
makeContextAware
Returns aCompletionStage
that makes sure the currentRequestContext
is set and then invokes the inputstage
. -
makeContextAware
Returns aCompletableFuture
that makes sure the currentRequestContext
is set and then invokes the inputfuture
. -
makeContextAware
Returns aLogger
which prepends thisRequestContext
to the log message.- Parameters:
logger
- theLogger
to decorate.
-
newDerivedContext
@Deprecated RequestContext newDerivedContext(RequestId id, @Nullable HttpRequest req, @Nullable RpcRequest rpcReq)Deprecated.This method will be removed without a replacement.Creates a newRequestContext
whose properties andattrs()
are copied from thisRequestContext
, except having a different pair ofHttpRequest
andRpcRequest
and its ownRequestLog
.
-