Interface RequestContext
- All Superinterfaces:
Unwrappable
- All Known Subinterfaces:
ClientRequestContext,ServiceRequestContext
- All Known Implementing Classes:
ClientRequestContextWrapper,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 ByteBufAllocatoralloc()Returns theByteBufAllocatorfor thisRequestContext.<V> Vattr(AttributeKey<V> key) Returns the value associated with the givenAttributeKeyornullif there's no value set bysetAttr(AttributeKey, Object).attrs()voidcancel()Cancels the currentRequest.voidReturns the cause of cancellation,nullif the request has not been cancelled.static <T extends RequestContext>
Tcurrent()Returns the context of theRequestthat is being handled in the current thread.static <T extends RequestContext>
TReturns the context of theRequestthat is being handled in the current thread.Returns the absolute path part of the currentRequestURI, excluding the query part, decoded in UTF-8.Returns theContextAwareEventLoopthat is handling the currentRequest.default booleanhasAttr(AttributeKey<?> key) default booleanhasOwnAttr(AttributeKey<?> key) hook()Returns the hook which is invoked whenever thisRequestContextis pushed to theRequestContextStorage.voidhook(Supplier<? extends AutoCloseable> contextHook) Adds a hook which is invoked whenever thisRequestContextis pushed to theRequestContextStorage.id()Initiates connection shutdown and returnsCompletableFuturethat completes when the connection associated with this context is closed.default booleanReturns whether thisRequestContexthas been cancelled.default booleanReturns whether thisRequestContexthas been timed-out, that is the cancellation cause is an instance ofTimeoutException.Returns the local address of this request, ornullif the connection is not established yet.log()Returns theRequestLogAccessthat provides the access to theRequestLog, which contains the information collected while processing the currentRequest.Returns theRequestLogBuilderthat collects the information about the currentRequest.default ContextAwareBlockingTaskExecutormakeContextAware(BlockingTaskExecutor executor) Returns aContextAwareBlockingTaskExecutorthat will execute callbacks in the givenexecutor, making sure to propagate thisRequestContextinto the callback execution.default RunnablemakeContextAware(Runnable runnable) Returns aContextAwareRunnablethat makes sure the currentRequestContextis set and then invokes the inputrunnable.default <T> Callable<T>makeContextAware(Callable<T> callable) Returns aContextAwareCallablethat makes sure the currentRequestContextis set and then invokes the inputcallable.default <T> CompletableFuture<T>makeContextAware(CompletableFuture<T> future) Returns aCompletableFuturethat makes sure the currentRequestContextis set and then invokes the inputfuture.default <T> CompletionStage<T>makeContextAware(CompletionStage<T> stage) Returns aCompletionStagethat makes sure the currentRequestContextis set and then invokes the inputstage.default ContextAwareExecutormakeContextAware(Executor executor) Returns aContextAwareExecutorthat will execute callbacks in the givenexecutor, making sure to propagate the currentRequestContextinto the callback execution.default ContextAwareExecutorServicemakeContextAware(ExecutorService executor) Returns aContextAwareExecutorServicethat will execute callbacks in the givenexecutor, making sure to propagate thisRequestContextinto the callback execution.makeContextAware(ScheduledExecutorService executor) Returns aContextAwareScheduledExecutorServicethat will execute callbacks in the givenexecutor, making sure to propagate thisRequestContextinto the callback execution.default <T,U> BiConsumer<T, U> makeContextAware(BiConsumer<T, U> action) Returns aContextAwareBiConsumerthat makes sure the currentRequestContextis set and then invokes the inputaction.default <T,U, V> BiFunction<T, U, V> makeContextAware(BiFunction<T, U, V> function) Returns aContextAwareBiFunctionthat makes sure the currentRequestContextis set and then invokes the inputfunction.default <T> Consumer<T>makeContextAware(Consumer<T> action) Returns aContextAwareConsumerthat makes sure the currentRequestContextis set and then invokes the inputaction.default <T,R> Function<T, R> makeContextAware(Function<T, R> function) Returns aContextAwareFunctionthat makes sure the currentRequestContextis set and then invokes the inputfunction.default LoggermakeContextAware(Logger logger) Returns aLoggerwhich prepends thisRequestContextto the log message.static BlockingTaskExecutormakeContextPropagating(BlockingTaskExecutor executor) Returns aBlockingTaskExecutorthat will execute callbacks in the givenexecutor, propagating the caller'sRequestContext(if any) into the callback execution.static ExecutormakeContextPropagating(Executor executor) Returns anExecutorthat will execute callbacks in the givenexecutor, propagating the caller'sRequestContext(if any) into the callback execution.static ExecutorServicemakeContextPropagating(ExecutorService executor) Returns anExecutorServicethat will execute callbacks in the givenexecutor, propagating the caller'sRequestContext(if any) into the callback execution.static ScheduledExecutorServiceReturns aScheduledExecutorServicethat will execute callbacks in the givenexecutor, propagating the caller'sRequestContext(if any) into the callback execution.static <T> TmapCurrent(Function<? super RequestContext, T> mapper, @Nullable Supplier<@Nullable T> defaultValueSupplier) Maps the context of theRequestthat is being handled in the current thread.Returns theMeterRegistrythat collects various stats.method()Returns the HTTP method of the currentRequest.<V> VownAttr(AttributeKey<V> key) Returns the value associated with the givenAttributeKeyornullif there's no value set bysetAttr(AttributeKey, Object).ownAttrs()path()push()Pushes the specified context to the thread-local stack.query()Returns the remote address of this request, ornullif the connection is not established yet.default SafeCloseablereplace()Replaces the currentRequestContextin the thread-local with this context without any validation.request()Returns theHttpRequestassociated with this context, ornullif there's noHttpRequestassociated with this context yet.longReturns the amount of time to wait in millis before aborting anHttpRequestwhen its correspondingHttpResponseis complete.root()Returns the rootServiceRequestContextof this context.Returns theRpcRequestassociated with this context, ornullif there's noRpcRequestassociated with this context.default voidImmediately run a givenRunnablewith this context.default <T> TImmediately call a givenCallablewith this context.Returns theSessionProtocolof the currentRequest.<V> VsetAttr(AttributeKey<V> key, V value) Associates the specified value with the givenAttributeKeyin this context.default voidsetRequestAutoAbortDelay(Duration delay) Sets the amount of time to wait before aborting anHttpRequestwhen its correspondingHttpResponseis complete.voidsetRequestAutoAbortDelayMillis(long delayMillis) Sets the amount of time in millis to wait before aborting anHttpRequestwhen its correspondingHttpResponseis complete.TheSSLSessionfor this request if the connection is made over TLS, ornullif the connection is not established yet or the connection is not a TLS connection.voidTimes out the currentRequest.default RequestContextunwrap()Unwraps this object and returns the object being decorated.default RequestContextUnwraps this object and returns the innermost object being decorated.voidupdateRequest(HttpRequest req) Replaces theHttpRequestassociated with this context with the specified one.voidupdateRpcRequest(RpcRequest rpcReq) Replaces theRpcRequestassociated with this context with the specified one.uri()Methods inherited from interface com.linecorp.armeria.common.util.Unwrappable
as, equalsIgnoreWrapper
-
Method Details
-
current
Returns the context of theRequestthat is being handled in the current thread.- Throws:
IllegalStateException- if the context is unavailable in the current thread
-
currentOrNull
Returns the context of theRequestthat is being handled in the current thread.- Returns:
- the
RequestContextavailable in the current thread, ornullif unavailable.
-
makeContextPropagating
Returns anExecutorthat will execute callbacks in the givenexecutor, propagating the caller'sRequestContext(if any) into the callback execution. If this executor is only used from a single request then it's better to usemakeContextAware(Executor) -
makeContextPropagating
Returns anExecutorServicethat 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 aScheduledExecutorServicethat 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) -
makeContextPropagating
Returns aBlockingTaskExecutorthat 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(BlockingTaskExecutor) -
mapCurrent
@Nullable static <T> T mapCurrent(Function<? super RequestContext, T> mapper, @Nullable @Nullable Supplier<@Nullable T> defaultValueSupplier) Maps the context of theRequestthat is being handled in the current thread.- Parameters:
mapper- theFunctionthat maps theRequestContextdefaultValueSupplier- theSupplierthat provides the value when the context is unavailable in the current thread. Ifnull, thenullwill be returned when the context is unavailable in the current thread.
-
root
Returns the rootServiceRequestContextof this context.- Returns:
- the root
ServiceRequestContext, ornullif this context was not created in the context of a server request.
-
attr
Returns the value associated with the givenAttributeKeyornullif there's no value set bysetAttr(AttributeKey, Object).Searching for attributes in a root context
Note: This section applies only to a
ClientRequestContext. AServiceRequestContextalways 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 givenAttributeKeyornullif there's no value set bysetAttr(AttributeKey, Object).Unlike
attr(AttributeKey), this does not search inroot().- See Also:
-
hasAttr
- See Also:
-
hasOwnAttr
Returnstrueif and only if the value associated with the specifiedAttributeKeyis notnull.Unlike
hasAttr(AttributeKey), this does not search inroot().- See Also:
-
attrs
Iterator<Map.Entry<AttributeKey<?>,Object>> attrs()Returns theIteratorof allMap.Entrys this context contains.Searching for attributes in a root context
Note: This section applies only to a
ClientRequestContext. AServiceRequestContextalways has itself as aroot().The
Iteratorreturned by this method will also yield theMap.Entrys from theroot()except those whoseAttributeKeyexist 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.Entryreturned byIterator.next()never affects theMap.Entryowned 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 givenAttributeKeyin this context. If this context previously contained a mapping for theAttributeKey, the old value is replaced by the specified value. Setnullnot 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(), ornullotherwise.
-
request
Returns theHttpRequestassociated with this context, ornullif there's noHttpRequestassociated with this context yet. -
rpcRequest
Returns theRpcRequestassociated with this context, ornullif there's noRpcRequestassociated with this context. -
updateRequest
Replaces theHttpRequestassociated 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 theRpcRequestassociated with this context with the specified one. This method is useful to a decorator that manipulates an RPC call. -
sessionProtocol
SessionProtocol sessionProtocol()Returns theSessionProtocolof the currentRequest. -
remoteAddress
Returns the remote address of this request, ornullif the connection is not established yet.- Returns:
- an
InetSocketAddress, aDomainSocketAddressornull
-
localAddress
Returns the local address of this request, ornullif the connection is not established yet.- Returns:
- an
InetSocketAddress, aDomainSocketAddressornull
-
sslSession
TheSSLSessionfor this request if the connection is made over TLS, ornullif 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 currentRequestURI, excluding the query part, decoded in UTF-8. -
query
-
uri
-
log
RequestLogAccess log()Returns theRequestLogAccessthat provides the access to theRequestLog, which contains the information collected while processing the currentRequest. -
logBuilder
RequestLogBuilder logBuilder()Returns theRequestLogBuilderthat collects the information about the currentRequest. -
meterRegistry
MeterRegistry meterRegistry()Returns theMeterRegistrythat collects various stats. -
requestAutoAbortDelayMillis
Returns the amount of time to wait in millis before aborting anHttpRequestwhen its correspondingHttpResponseis complete. -
setRequestAutoAbortDelay
Sets the amount of time to wait before aborting anHttpRequestwhen its correspondingHttpResponseis complete. Note that this method must be called before theHttpResponseis completed to take effect. -
setRequestAutoAbortDelayMillis
Sets the amount of time in millis to wait before aborting anHttpRequestwhen its correspondingHttpResponseis complete. Note that this method must be called before theHttpResponseis completed to take effect. -
cancel
-
cancel
void cancel()Cancels the currentRequest. -
timeoutNow
void timeoutNow()Times out the currentRequest. -
cancellationCause
Returns the cause of cancellation,nullif the request has not been cancelled. -
isCancelled
default boolean isCancelled()Returns whether thisRequestContexthas been cancelled. -
isTimedOut
default boolean isTimedOut()Returns whether thisRequestContexthas been timed-out, that is the cancellation cause is an instance ofTimeoutException. -
eventLoop
ContextAwareEventLoop eventLoop()Returns theContextAwareEventLoopthat is handling the currentRequest. TheContextAwareEventLoopsets thisRequestContextas the current context before executing any submitted tasks. If you want to useEventLoopwithout setting this context, callContextAwareEventLoop.withoutContext()and use the returnedEventLoop. -
alloc
Returns theByteBufAllocatorfor thisRequestContext. Any buffers created by thisByteBufAllocatormust be reference-counted. If you don't know what this means, you should probably usebyte[]orByteBufferdirectly instead of calling this method. -
exchangeType
-
initiateConnectionShutdown
Initiates connection shutdown and returnsCompletableFuturethat completes when the connection associated with this context is closed. -
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-resourcesblock:try (SafeCloseable ignored = ctx.push()) { ... }This method may throw an
IllegalStateExceptionaccording to the status of the current thread-local. Please seeServiceRequestContext.push()andClientRequestContext.push()to find out the satisfying conditions. -
hook
Adds a hook which is invoked whenever thisRequestContextis pushed to theRequestContextStorage. TheAutoCloseablereturned bycontextHookwill be called whenever thisRequestContextis popped from theRequestContextStorage. This method is useful when you need to propagate a custom context in thisRequestContext's scope.Note:
- The
contextHookis not invoked when thishook(Supplier)method is called thus you need to call it yourself if you want to apply the hook in the current thread. - This operation is highly performance-sensitive operation, and thus it's not a good idea to run a time-consuming task.
- The
-
hook
Returns the hook which is invoked whenever thisRequestContextis pushed to theRequestContextStorage. TheSafeCloseablereturned by theSupplierwill be called whenever thisRequestContextis popped from theRequestContextStorage. -
unwrap
Description copied from interface:UnwrappableUnwraps this object and returns the object being decorated. If thisUnwrappableis the innermost object, this method returns itself. For example:class Foo implements Unwrappable {} class Bar<T extends Unwrappable> extends AbstractUnwrappable<T> { Bar(T delegate) { super(delegate); } } class Qux<T extends Unwrappable> extends AbstractUnwrappable<T> { Qux(T delegate) { super(delegate); } } Foo foo = new Foo(); assert foo.unwrap() == foo; Bar<Foo> bar = new Bar<>(foo); assert bar.unwrap() == foo; Qux<Bar<Foo>> qux = new Qux<>(bar); assert qux.unwrap() == bar; assert qux.unwrap().unwrap() == foo;- Specified by:
unwrapin interfaceUnwrappable
-
unwrapAll
Description copied from interface:UnwrappableUnwraps this object and returns the innermost object being decorated. If thisUnwrappableis the innermost object, this method returns itself. For example:class Foo implements Unwrappable {} class Bar<T extends Unwrappable> extends AbstractUnwrappable<T> { Bar(T delegate) { super(delegate); } } class Qux<T extends Unwrappable> extends AbstractUnwrappable<T> { Qux(T delegate) { super(delegate); } } Foo foo = new Foo(); assert foo.unwrapAll() == foo; Bar<Foo> bar = new Bar<>(foo); assert bar.unwrapAll() == foo; Qux<Bar<Foo>> qux = new Qux<>(bar); assert qux.unwrap() == bar; assert qux.unwrapAll() == foo;- Specified by:
unwrapAllin interfaceUnwrappable
-
run
Immediately run a givenRunnablewith this context. -
run
Immediately call a givenCallablewith this context.- Throws:
Exception
-
replace
Replaces the currentRequestContextin 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
RequestContextis pushed into the thread-local. Usepush()instead. -
makeContextAware
Returns aContextAwareExecutorthat will execute callbacks in the givenexecutor, making sure to propagate the currentRequestContextinto the callback execution. It is generally preferred to useeventLoop()to ensure the callback stays on the same thread as well. -
makeContextAware
Returns aContextAwareExecutorServicethat will execute callbacks in the givenexecutor, making sure to propagate thisRequestContextinto the callback execution. If this executor service will be used for callbacks from several requests, usemakeContextPropagating(ExecutorService)instead. -
makeContextAware
Returns aContextAwareScheduledExecutorServicethat will execute callbacks in the givenexecutor, making sure to propagate thisRequestContextinto the callback execution. If this executor service will be used for callbacks from several requests, usemakeContextPropagating(ScheduledExecutorService)instead. -
makeContextAware
Returns aContextAwareBlockingTaskExecutorthat will execute callbacks in the givenexecutor, making sure to propagate thisRequestContextinto the callback execution. If this executor service will be used for callbacks from several requests, usemakeContextPropagating(BlockingTaskExecutor)instead. -
makeContextAware
Returns aContextAwareCallablethat makes sure the currentRequestContextis set and then invokes the inputcallable. -
makeContextAware
Returns aContextAwareRunnablethat makes sure the currentRequestContextis set and then invokes the inputrunnable. -
makeContextAware
Returns aContextAwareFunctionthat makes sure the currentRequestContextis set and then invokes the inputfunction. -
makeContextAware
Returns aContextAwareBiFunctionthat makes sure the currentRequestContextis set and then invokes the inputfunction. -
makeContextAware
Returns aContextAwareConsumerthat makes sure the currentRequestContextis set and then invokes the inputaction. -
makeContextAware
Returns aContextAwareBiConsumerthat makes sure the currentRequestContextis set and then invokes the inputaction. -
makeContextAware
Returns aCompletionStagethat makes sure the currentRequestContextis set and then invokes the inputstage. -
makeContextAware
Returns aCompletableFuturethat makes sure the currentRequestContextis set and then invokes the inputfuture. -
makeContextAware
Returns aLoggerwhich prepends thisRequestContextto the log message.- Parameters:
logger- theLoggerto decorate.
-