Interface RequestContext
- All Known Subinterfaces:
ClientRequestContext
,ServiceRequestContext
- All Known Implementing Classes:
ClientRequestContextWrapper
,DefaultClientRequestContext
,DefaultServiceRequestContext
,NonWrappingRequestContext
,RequestContextWrapper
,ServiceRequestContextWrapper
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 TypeMethodDescriptiondefault ByteBufAllocator
alloc()
Returns theByteBufAllocator
for thisRequestContext
.<V> V
attr
(AttributeKey<V> key) Returns the value associated with the givenAttributeKey
ornull
if there's no value set bysetAttr(AttributeKey, Object)
.attrs()
void
cancel()
Cancels the currentRequest
.void
Returns the cause of cancellation,null
if the request has not been cancelled.static <T extends RequestContext>
Tcurrent()
Returns the context of theRequest
that is being handled in the current thread.static <T extends RequestContext>
TReturns the context of theRequest
that is being handled in the current thread.Returns the absolute path part of the currentRequest
URI, excluding the query part, decoded in UTF-8.Returns theContextAwareEventLoop
that is handling the currentRequest
.default boolean
hasAttr
(AttributeKey<?> key) default boolean
hasOwnAttr
(AttributeKey<?> key) id()
default boolean
Returns whether thisRequestContext
has been cancelled.default boolean
Returns whether thisRequestContext
has been timed-out, that is the cancellation cause is an instance ofTimeoutException
.<A extends SocketAddress>
AReturns the local address of this request, ornull
if the connection is not established yet.log()
Returns theRequestLogAccess
that provides the access to theRequestLog
, which contains the information collected while processing the currentRequest
.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 thisRequestContext
into the callback execution.default ScheduledExecutorService
makeContextAware
(ScheduledExecutorService executor) Returns aScheduledExecutorService
that will execute callbacks in the givenexecutor
, making sure to propagate thisRequestContext
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 ExecutorService
makeContextPropagating
(ExecutorService executor) Returns anExecutorService
that will execute callbacks in the givenexecutor
, propagating the caller'sRequestContext
(if any) into the callback execution.static ScheduledExecutorService
Returns aScheduledExecutorService
that will execute callbacks in the givenexecutor
, propagating the caller'sRequestContext
(if any) into the callback execution.static <T> T
mapCurrent
(Function<? super RequestContext, T> mapper, @Nullable Supplier<@Nullable T> defaultValueSupplier) Maps the context of theRequest
that is being handled in the current thread.Returns theMeterRegistry
that collects various stats.method()
Returns the HTTP method of the currentRequest
.<V> V
ownAttr
(AttributeKey<V> key) Returns the value associated with the givenAttributeKey
ornull
if there's no value set bysetAttr(AttributeKey, Object)
.ownAttrs()
path()
push()
Pushes the specified context to the thread-local stack.query()
<A extends SocketAddress>
AReturns 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.request()
Returns theHttpRequest
associated with this context, ornull
if there's noHttpRequest
associated with this context yet.root()
Returns the rootServiceRequestContext
of this context.Returns theRpcRequest
associated with this context, ornull
if there's noRpcRequest
associated with this context.default void
Immediately run a givenRunnable
with this context.default <T> T
Immediately call a givenCallable
with this context.Returns theSessionProtocol
of the currentRequest
.<V> V
setAttr
(AttributeKey<V> key, V value) Associates the specified value with the givenAttributeKey
in this context.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
Times out the currentRequest
.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.
-
makeContextPropagating
Returns anExecutorService
that will execute callbacks in the givenexecutor
, propagating the caller'sRequestContext
(if any) into the callback execution. If this executor service is only used from a single request then it's better to usemakeContextAware(ExecutorService)
-
makeContextPropagating
Returns aScheduledExecutorService
that will execute callbacks in the givenexecutor
, propagating the caller'sRequestContext
(if any) into the callback execution. If this executor service is only used from a single request then it's better to usemakeContextAware(ScheduledExecutorService)
-
mapCurrent
@Nullable static <T> T mapCurrent(Function<? super RequestContext, T> mapper, @Nullable @Nullable Supplier<@Nullable 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 associated with the givenAttributeKey
ornull
if there's no value set bysetAttr(AttributeKey, Object)
.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
Returns the value associated with the givenAttributeKey
ornull
if there's no value set bysetAttr(AttributeKey, Object)
.Unlike
attr(AttributeKey)
, this does not search inroot()
.- See Also:
-
hasAttr
- See Also:
-
hasOwnAttr
Returnstrue
if and only if the value associated with the specifiedAttributeKey
is notnull
.Unlike
hasAttr(AttributeKey)
, this does not search inroot()
.- See Also:
-
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
Iterator<Map.Entry<AttributeKey<?>,Object>> ownAttrs()- See Also:
-
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()
.- Returns:
- the old value that has been replaced if there's a mapping for the specified key in this context
or its
root()
, ornull
otherwise.
-
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. -
cancel
-
cancel
void cancel()Cancels the currentRequest
. -
timeoutNow
void timeoutNow()Times out the currentRequest
. -
cancellationCause
Returns the cause of cancellation,null
if the request has not been cancelled. -
isCancelled
default boolean isCancelled()Returns whether thisRequestContext
has been cancelled. -
isTimedOut
default boolean isTimedOut()Returns whether thisRequestContext
has been timed-out, that is the cancellation cause is an instance ofTimeoutException
. -
eventLoop
ContextAwareEventLoop eventLoop()Returns theContextAwareEventLoop
that is handling the currentRequest
. TheContextAwareEventLoop
sets thisRequestContext
as the current context before executing any submitted tasks. If you want to useEventLoop
without setting this context, callContextAwareEventLoop.withoutContext()
and use the returnedEventLoop
. -
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. -
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. -
run
Immediately run a givenRunnable
with this context. -
run
Immediately call a givenCallable
with this context.- Throws:
Exception
-
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 useeventLoop()
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 thisRequestContext
into the callback execution. If this executor service will be used for callbacks from several different requests, usemakeContextPropagating(ExecutorService)
instead. -
makeContextAware
Returns aScheduledExecutorService
that will execute callbacks in the givenexecutor
, making sure to propagate thisRequestContext
into the callback execution. If this executor service will be used for callbacks from several different requests, usemakeContextPropagating(ScheduledExecutorService)
instead. -
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.
-