Interface ServiceRequestContext
- All Superinterfaces:
RequestContext
,Unwrappable
- All Known Implementing Classes:
ServiceRequestContextWrapper
ServiceRequestContext
instance.-
Method Summary
Modifier and TypeMethodDescriptionvoid
addAdditionalResponseHeader
(CharSequence name, Object value) Adds a header with the specifiedname
andvalue
.void
addAdditionalResponseTrailer
(CharSequence name, Object value) Adds a trailer with the specifiedname
andvalue
.Returns theHttpHeaders
which is included along with any other trailers when aService
completes anHttpResponse
.Returns theContextAwareBlockingTaskExecutor
that could be used for executing a potentially long-running task.static ServiceRequestContextBuilder
builder
(HttpRequest request) Returns a newServiceRequestContextBuilder
created from the specifiedHttpRequest
.default void
cancel()
Cancels the request.void
Clears the previously scheduled request timeout, if any.Returns the address of the client who initiated this request.config()
static ServiceRequestContext
current()
Returns the server-side context of theRequest
that is being handled in the current thread.static @Nullable ServiceRequestContext
Returns the server-side context of theRequest
that is being handled in the current thread.Returns theRequestContext.decodedPath()
with its context path removed.Initiates connection shutdown without overriding current configuration of the drain duration and returnsCompletableFuture
that completes when the connection associated with this context is closed.initiateConnectionShutdown
(long drainDurationMicros) Initiates graceful connection shutdown with a given drain duration in microseconds and returnsCompletableFuture
that completes when the connection associated with this context is closed.default CompletableFuture<Void>
initiateConnectionShutdown
(Duration drainDuration) Initiates graceful connection shutdown with a given drain duration and returnsCompletableFuture
that completes when the connection associated with this context is closed.<A extends SocketAddress>
AReturns the local address of this request.static <T> T
mapCurrent
(Function<? super ServiceRequestContext, T> mapper, @Nullable Supplier<@Nullable T> defaultValueSupplier) Maps the server-side context of theRequest
that is being handled in the current thread.Returns theRequestContext.path()
with its context path removed.long
Returns the maximum length of the currentRequest
.void
void
Mutates theHttpHeaders
which is included along with any other trailers when aService
completes anHttpResponse
.Returns the negotiated producible media type.static ServiceRequestContext
of
(HttpRequest request) Returns a newServiceRequestContext
created from the specifiedHttpRequest
.Returns the value of the specified path parameter.Returns the proxied addresses of the currentRequest
.default SafeCloseable
push()
Pushes this context to the thread-local stack.queryParam
(String name) Returns the value of a parameter with the specifiedname
.queryParams
(String name) Returns all values for the parameter with the specified name.<A extends SocketAddress>
AReturns the remote address of this request.request()
Returns theHttpRequest
associated with this context.long
default ServiceRequestContext
root()
Returns the rootServiceRequestContext
of this context.Returns theRoutingContext
used to find theService
.Returns theRpcRequest
associated with this context, ornull
if there's noRpcRequest
associated with this context.void
setAdditionalResponseHeader
(CharSequence name, Object value) Sets a header with the specifiedname
andvalue
.void
setAdditionalResponseTrailer
(CharSequence name, Object value) Sets a trailer with the specifiedname
andvalue
.void
setMaxRequestLength
(long maxRequestLength) Sets the maximum length of the currentRequest
.void
setRequestTimeout
(TimeoutMode mode, Duration requestTimeout) Schedules the request timeout that is triggered when theRequest
is not fully received or the correspondingResponse
is not sent completely within the specifiedTimeoutMode
and the specifiedrequestTimeout
.default void
setRequestTimeout
(Duration requestTimeout) default void
setRequestTimeoutMillis
(long requestTimeoutMillis) void
setRequestTimeoutMillis
(TimeoutMode mode, long requestTimeoutMillis) Schedules the request timeout that is triggered when theRequest
is not fully received or the correspondingResponse
is not sent completely within the specifiedTimeoutMode
and the specifiedrequestTimeoutMillis
.void
setShouldReportUnhandledExceptions
(boolean value) Sets whether to report exceptions.boolean
Returns whether exceptions should be reported.default void
Times out the request.default ServiceRequestContext
unwrap()
Unwraps this object and returns the object being decorated.default ServiceRequestContext
Unwraps this object and returns the innermost object being decorated.uri()
Returns aCompletableFuture
which is completed with aThrowable
cancellation cause after theServiceRequestContext
has been cancelled.Returns aCompletableFuture
which is completed with aThrowable
cancellation cause when theServiceRequestContext
is about to get cancelled.Deprecated.Deprecated.UsewhenRequestCancelling()
instead.Methods inherited from interface com.linecorp.armeria.common.RequestContext
alloc, attr, attrs, cancel, cancellationCause, decodedPath, eventLoop, hasAttr, hasOwnAttr, id, isCancelled, isTimedOut, log, logBuilder, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, meterRegistry, method, ownAttr, ownAttrs, path, query, replace, run, run, sessionProtocol, setAttr, sslSession, updateRequest, updateRpcRequest
Methods inherited from interface com.linecorp.armeria.common.util.Unwrappable
as, equalsIgnoreWrapper
-
Method Details
-
current
Returns the server-side context of theRequest
that is being handled in the current thread. If the context is aClientRequestContext
,RequestContext.root()
is returned.- Throws:
IllegalStateException
- if the context is unavailable in the current thread or the current context is aClientRequestContext
andRequestContext.root()
isnull
-
currentOrNull
Returns the server-side context of theRequest
that is being handled in the current thread. If the context is aClientRequestContext
,RequestContext.root()
is returned.- Returns:
- the
ServiceRequestContext
available in the current thread, ornull
if unavailable.
-
mapCurrent
@Nullable static <T> T mapCurrent(Function<? super ServiceRequestContext, T> mapper, @Nullable @Nullable Supplier<@Nullable T> defaultValueSupplier) Maps the server-side context of theRequest
that is being handled in the current thread.- Parameters:
mapper
- theFunction
that maps theServiceRequestContext
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.- Throws:
IllegalStateException
- if the current context is not aServiceRequestContext
.
-
of
Returns a newServiceRequestContext
created from the specifiedHttpRequest
. Note that it is not usually required to create a new context by yourself, because Armeria will always provide a context object for you. However, it may be useful in some cases such as unit testing.- See Also:
-
builder
Returns a newServiceRequestContextBuilder
created from the specifiedHttpRequest
. -
root
Returns the rootServiceRequestContext
of this context. This method always returnsthis
.- Specified by:
root
in interfaceRequestContext
- Returns:
this
-
request
Returns theHttpRequest
associated with this context.- Specified by:
request
in interfaceRequestContext
-
rpcRequest
Returns theRpcRequest
associated with this context, ornull
if there's noRpcRequest
associated with this context. For example, this method will returnnull
when the request being handled is 1) not an RPC request or 2) not decoded into an RPC request yet.- Specified by:
rpcRequest
in interfaceRequestContext
-
remoteAddress
Returns the remote address of this request.- Specified by:
remoteAddress
in interfaceRequestContext
-
localAddress
Returns the local address of this request.- Specified by:
localAddress
in interfaceRequestContext
-
clientAddress
InetAddress clientAddress()Returns the address of the client who initiated this request. -
push
Pushes this 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()) { ... }
In order to call this method, the current thread-local state must meet one of the following conditions:
- the thread-local does not have any
RequestContext
in it - the thread-local has the same
ServiceRequestContext
as this - reentrance - the thread-local has the
ClientRequestContext
whoseRequestContext.root()
is the sameServiceRequestContext
as this
IllegalStateException
.- Specified by:
push
in interfaceRequestContext
- the thread-local does not have any
-
config
ServiceConfig config() -
routingContext
RoutingContext routingContext()Returns theRoutingContext
used to find theService
. -
pathParams
-
pathParam
Returns the value of the specified path parameter. -
queryParams
QueryParams queryParams() -
queryParams
Returns all values for the parameter with the specified name. The returnedList
can't be modified. -
queryParam
Returns the value of a parameter with the specifiedname
. If there are more than one value for the specifiedname
, the first value in insertion order is returned.- Parameters:
name
- the parameter name- Returns:
- the first parameter value if found, or
null
if there is no such parameter
-
blockingTaskExecutor
ContextAwareBlockingTaskExecutor blockingTaskExecutor()Returns theContextAwareBlockingTaskExecutor
that could be used for executing a potentially long-running task. TheContextAwareBlockingTaskExecutor
sets thisServiceRequestContext
as the current context before executing any submitted tasks. If you want to useBlockingTaskExecutor
without setting this context, callContextAwareBlockingTaskExecutor.withoutContext()
and use the returnedBlockingTaskExecutor
. -
mappedPath
String mappedPath()Returns theRequestContext.path()
with its context path removed. This method can be useful for a reusable service bound at various path prefixes. -
decodedMappedPath
String decodedMappedPath()Returns theRequestContext.decodedPath()
with its context path removed. This method can be useful for a reusable service bound at various path prefixes. -
uri
Returns theURI
associated with the currentRequest
. Note that this method is a shortcut of callingHttpRequest.uri()
onrequest()
.- Specified by:
uri
in interfaceRequestContext
- See Also:
-
negotiatedResponseMediaType
Returns the negotiated producible media type. If the media type negotiation is not used for theService
,null
would be returned. -
requestTimeoutMillis
long requestTimeoutMillis()Returns the amount of time allowed from the start time of theRequest
until receiving the currentRequest
and sending the correspondingResponse
completely. This value is initially set fromServiceConfig.requestTimeoutMillis()
. -
clearRequestTimeout
void clearRequestTimeout()Clears the previously scheduled request timeout, if any. Note that calling this will prevent the request from ever being timed out. -
setRequestTimeoutMillis
default void setRequestTimeoutMillis(long requestTimeoutMillis) Schedules the request timeout that is triggered when theRequest
is not fully received or the correspondingResponse
is not sent completely within the specified amount time from now. Note that the specifiedrequestTimeout
must be positive. This value is initially set fromServiceConfig.requestTimeoutMillis()
. This method is a shortcut forsetRequestTimeoutMillis(TimeoutMode.SET_FROM_NOW, requestTimeoutMillis)
.For example:
ServiceRequestContext ctx = ...; // Schedules timeout after 1 seconds from now. ctx.setRequestTimeoutMillis(1000);
- Parameters:
requestTimeoutMillis
- the amount of time allowed in milliseconds from now
-
setRequestTimeoutMillis
Schedules the request timeout that is triggered when theRequest
is not fully received or the correspondingResponse
is not sent completely within the specifiedTimeoutMode
and the specifiedrequestTimeoutMillis
.timeout mode description Timeout mode description TimeoutMode.SET_FROM_NOW
Sets a given amount of timeout from the current time. TimeoutMode.SET_FROM_START
Sets a given amount of timeout since the current Request
began processing.TimeoutMode.EXTEND
Extends the previously scheduled timeout by the given amount of timeout. For example:
ServiceRequestContext ctx = ...; // Schedules a timeout from the start time of the request ctx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_START, 2000); assert ctx.requestTimeoutMillis() == 2000; ctx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_START, 1000); assert ctx.requestTimeoutMillis() == 1000; // Schedules timeout after 3 seconds from now. ctx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_NOW, 3000); // Extends the previously scheduled timeout. long oldRequestTimeoutMillis = ctx.requestTimeoutMillis(); ctx.setRequestTimeoutMillis(TimeoutMode.EXTEND, 1000); assert ctx.requestTimeoutMillis() == oldRequestTimeoutMillis + 1000; ctx.extendRequestTimeoutMillis(TimeoutMode.EXTEND, -500); assert ctx.requestTimeoutMillis() == oldRequestTimeoutMillis + 500;
-
setRequestTimeout
Schedules the request timeout that is triggered when theRequest
is not fully received or the correspondingResponse
is not sent completely within the specified amount time from now. Note that the specifiedrequestTimeout
must be positive. This value is initially set fromServiceConfig.requestTimeoutMillis()
. This method is a shortcut forsetRequestTimeout(TimeoutMode.SET_FROM_NOW, requestTimeout)
.For example:
ServiceRequestContext ctx = ...; // Schedules timeout after 1 seconds from now. ctx.setRequestTimeout(Duration.ofSeconds(1));
- Parameters:
requestTimeout
- the amount of time allowed from now
-
setRequestTimeout
Schedules the request timeout that is triggered when theRequest
is not fully received or the correspondingResponse
is not sent completely within the specifiedTimeoutMode
and the specifiedrequestTimeout
.timeout mode description Timeout mode description TimeoutMode.SET_FROM_NOW
Sets a given amount of timeout from the current time. TimeoutMode.SET_FROM_START
Sets a given amount of timeout since the current Request
began processing.TimeoutMode.EXTEND
Extends the previously scheduled timeout by the given amount of timeout. For example:
ServiceRequestContext ctx = ...; // Schedules a timeout from the start time of the request ctx.setRequestTimeout(TimeoutMode.SET_FROM_START, Duration.ofSeconds(2)); assert ctx.requestTimeoutMillis() == 2000; ctx.setRequestTimeout(TimeoutMode.SET_FROM_START, Duration.ofSeconds(1)); assert ctx.requestTimeoutMillis() == 1000; // Schedules timeout after 3 seconds from now. ctx.setRequestTimeout(TimeoutMode.SET_FROM_NOW, Duration.ofSeconds(3)); // Extends the previously scheduled timeout. long oldRequestTimeoutMillis = ctx.requestTimeoutMillis(); ctx.setRequestTimeout(TimeoutMode.EXTEND, Duration.ofSeconds(1)); assert ctx.requestTimeoutMillis() == oldRequestTimeoutMillis + 1000; ctx.setRequestTimeout(TimeoutMode.EXTEND, Duration.ofMillis(-500)); assert ctx.requestTimeoutMillis() == oldRequestTimeoutMillis + 500;
-
whenRequestCancelling
CompletableFuture<Throwable> whenRequestCancelling()Returns aCompletableFuture
which is completed with aThrowable
cancellation cause when theServiceRequestContext
is about to get cancelled. If the request is handled successfully without cancellation, theCompletableFuture
won't complete. -
whenRequestCancelled
CompletableFuture<Throwable> whenRequestCancelled()Returns aCompletableFuture
which is completed with aThrowable
cancellation cause after theServiceRequestContext
has been cancelled.RequestContext.isCancelled()
will always returntrue
when the returnedCompletableFuture
is completed. If the request is handled successfully without cancellation, theCompletableFuture
won't complete. -
whenRequestTimingOut
Deprecated.UsewhenRequestCancelling()
instead.Returns aCompletableFuture
which is completed when theServiceRequestContext
is about to get timed out. If the request is handled successfully or not cancelled by timeout, theCompletableFuture
won't complete. -
whenRequestTimedOut
Deprecated.UsewhenRequestCancelled()
instead.Returns aCompletableFuture
which is completed after theServiceRequestContext
has been timed out.RequestContext.isTimedOut()
will always returntrue
when the returnedCompletableFuture
is completed. If the request is handled successfully or not cancelled by timeout, theCompletableFuture
won't complete. -
cancel
default void cancel()Cancels the request. Shortcut forcancel(RequestCancellationException.get())
.- Specified by:
cancel
in interfaceRequestContext
-
timeoutNow
default void timeoutNow()Times out the request. Shortcut forcancel(RequestTimeoutException.get())
.- Specified by:
timeoutNow
in interfaceRequestContext
-
maxRequestLength
long maxRequestLength()Returns the maximum length of the currentRequest
. This value is initially set fromServiceConfig.maxRequestLength()
. If 0, there is no limit on the request size.- See Also:
-
setMaxRequestLength
void setMaxRequestLength(long maxRequestLength) Sets the maximum length of the currentRequest
. This value is initially set fromServiceConfig.maxRequestLength()
. If 0, there is no limit on the request size.- See Also:
-
additionalResponseHeaders
HttpHeaders additionalResponseHeaders() -
setAdditionalResponseHeader
Sets a header with the specifiedname
andvalue
. This will remove all previous values associated with the specifiedname
. The header will be included when aService
sends anHttpResponse
. -
addAdditionalResponseHeader
Adds a header with the specifiedname
andvalue
. The header will be included when aService
sends anHttpResponse
. -
mutateAdditionalResponseHeaders
- Parameters:
mutator
- theConsumer
that mutates the additional response headers
-
additionalResponseTrailers
HttpHeaders additionalResponseTrailers()Returns theHttpHeaders
which is included along with any other trailers when aService
completes anHttpResponse
. -
setAdditionalResponseTrailer
Sets a trailer with the specifiedname
andvalue
. This will remove all previous values associated with the specifiedname
. The trailer will be included when aService
completes anHttpResponse
. -
addAdditionalResponseTrailer
Adds a trailer with the specifiedname
andvalue
. The trailer will be included when aService
completes anHttpResponse
. -
mutateAdditionalResponseTrailers
Mutates theHttpHeaders
which is included along with any other trailers when aService
completes anHttpResponse
.- Parameters:
mutator
- theConsumer
that mutates the additional trailers
-
proxiedAddresses
ProxiedAddresses proxiedAddresses()Returns the proxied addresses of the currentRequest
. -
shouldReportUnhandledExceptions
boolean shouldReportUnhandledExceptions()Returns whether exceptions should be reported. WhenLoggingService
handles exceptions, this is set to false. -
setShouldReportUnhandledExceptions
void setShouldReportUnhandledExceptions(boolean value) Sets whether to report exceptions.- Parameters:
value
- whether to report unhandled exceptions
-
initiateConnectionShutdown
Initiates graceful connection shutdown with a given drain duration in microseconds and returnsCompletableFuture
that completes when the connection associated with this context is closed.At the connection drain server signals the clients that the connection shutdown is imminent but still accepts in flight requests. At the connection drain end server stops accepting new requests.
If graceful shutdown is already triggered and the given connection drain duration is smaller than the wait time before the connection drain end, it reschedules the drain end to happen faster. Otherwise, drain will end as it was previously scheduled.
Note that HTTP/1 doesn't support draining as described here, so for HTTP/1 drain duration is always
0
, which means the connection will be closed immediately at the end of the current response. -
initiateConnectionShutdown
Initiates graceful connection shutdown with a given drain duration and returnsCompletableFuture
that completes when the connection associated with this context is closed. -
initiateConnectionShutdown
Initiates connection shutdown without overriding current configuration of the drain duration and returnsCompletableFuture
that completes when the connection associated with this context is closed.- Specified by:
initiateConnectionShutdown
in interfaceRequestContext
- See Also:
-
exchangeType
ExchangeType exchangeType()Returns theExchangeType
that determines whether to stream anHttpRequest
orHttpResponse
.Note that an
HttpRequest
will be aggregated before serving theHttpService
ifExchangeType.UNARY
orExchangeType.RESPONSE_STREAMING
is set.- Specified by:
exchangeType
in interfaceRequestContext
-
unwrap
Description copied from interface:Unwrappable
Unwraps this object and returns the object being decorated. If thisUnwrappable
is 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:
unwrap
in interfaceRequestContext
- Specified by:
unwrap
in interfaceUnwrappable
-
unwrapAll
Description copied from interface:Unwrappable
Unwraps this object and returns the innermost object being decorated. If thisUnwrappable
is 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:
unwrapAll
in interfaceRequestContext
- Specified by:
unwrapAll
in interfaceUnwrappable
-
whenRequestCancelled()
instead.