Interface ServiceRequestContext
- All Superinterfaces:
RequestContext
- All Known Implementing Classes:
DefaultServiceRequestContext,ServiceRequestContextWrapper
ServiceRequestContext instance.-
Method Summary
Modifier and TypeMethodDescriptionvoidaddAdditionalResponseHeader(CharSequence name, Object value)Adds a header with the specifiednameandvalue.voidaddAdditionalResponseTrailer(CharSequence name, Object value)Adds a trailer with the specifiednameandvalue.Returns theHttpHeaderswhich is included along with any other trailers when aServicecompletes anHttpResponse.Returns theContextAwareScheduledExecutorServicethat could be used for executing a potentially long-running task.static ServiceRequestContextBuilderbuilder(HttpRequest request)Returns a newServiceRequestContextBuildercreated from the specifiedHttpRequest.default voidcancel()Cancels the request.voidClears the previously scheduled request timeout, if any.Returns the address of the client who initiated this request.config()static ServiceRequestContextcurrent()Returns the server-side context of theRequestthat is being handled in the current thread.static @Nullable ServiceRequestContextReturns the server-side context of theRequestthat 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 returnsCompletableFuturethat completes when the channel is closed.initiateConnectionShutdown(long drainDurationMicros)Initiates graceful connection shutdown with a given drain duration in microseconds and returnsCompletableFuturethat completes when the channel is closed..default CompletableFuture<Void>initiateConnectionShutdown(Duration drainDuration)Initiates graceful connection shutdown with a given drain duration and returnsCompletableFuturethat completes when the channel is closed.<A extends SocketAddress>
AReturns the local address of this request.static <T> TmapCurrent(Function<? super ServiceRequestContext,T> mapper, @Nullable Supplier<@Nullable T> defaultValueSupplier)Maps the server-side context of theRequestthat is being handled in the current thread.Returns theRequestContext.path()with its context path removed.longReturns the maximum length of the currentRequest.voidvoidMutates theHttpHeaderswhich is included along with any other trailers when aServicecompletes anHttpResponse.Returns the negotiated producible media type.static ServiceRequestContextof(HttpRequest request)Returns a newServiceRequestContextcreated from the specifiedHttpRequest.Returns the value of the specified path parameter.Returns the proxied addresses of the currentRequest.default SafeCloseablepush()Pushes this context to the thread-local stack.<A extends SocketAddress>
AReturns the remote address of this request.request()Returns theHttpRequestassociated with this context.longdefault ServiceRequestContextroot()Returns the rootServiceRequestContextof this context.Returns theRoutingContextused to find theService.Returns theRpcRequestassociated with this context, ornullif there's noRpcRequestassociated with this context.voidsetAdditionalResponseHeader(CharSequence name, Object value)Sets a header with the specifiednameandvalue.voidsetAdditionalResponseTrailer(CharSequence name, Object value)Sets a trailer with the specifiednameandvalue.voidsetMaxRequestLength(long maxRequestLength)Sets the maximum length of the currentRequest.voidsetRequestTimeout(TimeoutMode mode, Duration requestTimeout)Schedules the request timeout that is triggered when theRequestis not fully received or the correspondingResponseis not sent completely within the specifiedTimeoutModeand the specifiedrequestTimeout.default voidsetRequestTimeout(Duration requestTimeout)default voidsetRequestTimeoutMillis(long requestTimeoutMillis)voidsetRequestTimeoutMillis(TimeoutMode mode, long requestTimeoutMillis)Schedules the request timeout that is triggered when theRequestis not fully received or the correspondingResponseis not sent completely within the specifiedTimeoutModeand the specifiedrequestTimeoutMillis.default voidTimes out the request.Returns aCompletableFuturewhich is completed with aThrowablecancellation cause after theServiceRequestContexthas been cancelled.Returns aCompletableFuturewhich is completed with aThrowablecancellation cause when theServiceRequestContextis 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, meterRegistry, method, ownAttr, ownAttrs, path, query, replace, run, run, sessionProtocol, setAttr, sslSession, updateRequest, updateRpcRequest
-
Method Details
-
current
Returns the server-side context of theRequestthat 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 aClientRequestContextandRequestContext.root()isnull
-
currentOrNull
Returns the server-side context of theRequestthat is being handled in the current thread. If the context is aClientRequestContext,RequestContext.root()is returned.- Returns:
- the
ServiceRequestContextavailable in the current thread, ornullif unavailable.
-
mapCurrent
@Nullable static <T> T mapCurrent(Function<? super ServiceRequestContext,T> mapper, @Nullable @Nullable Supplier<@Nullable T> defaultValueSupplier)Maps the server-side context of theRequestthat is being handled in the current thread.- Parameters:
mapper- theFunctionthat maps theServiceRequestContextdefaultValueSupplier- 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.- Throws:
IllegalStateException- if the current context is not aServiceRequestContext.
-
of
Returns a newServiceRequestContextcreated 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:
ServiceRequestContextBuilder
-
builder
Returns a newServiceRequestContextBuildercreated from the specifiedHttpRequest. -
root
Returns the rootServiceRequestContextof this context. This method always returnsthis.- Specified by:
rootin interfaceRequestContext- Returns:
this
-
request
Returns theHttpRequestassociated with this context.- Specified by:
requestin interfaceRequestContext
-
rpcRequest
Returns theRpcRequestassociated with this context, ornullif there's noRpcRequestassociated with this context. For example, this method will returnnullwhen the request being handled is 1) not an RPC request or 2) not decoded into an RPC request yet.- Specified by:
rpcRequestin interfaceRequestContext
-
remoteAddress
Returns the remote address of this request.- Specified by:
remoteAddressin interfaceRequestContext
-
localAddress
Returns the local address of this request.- Specified by:
localAddressin 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-resourcesblock: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
RequestContextin it - the thread-local has the same
ServiceRequestContextas this - reentrance - the thread-local has the
ClientRequestContextwhoseRequestContext.root()is the sameServiceRequestContextas this
IllegalStateException.- Specified by:
pushin interfaceRequestContext
- the thread-local does not have any
-
config
ServiceConfig config() -
routingContext
RoutingContext routingContext()Returns theRoutingContextused to find theService. -
pathParams
-
pathParam
Returns the value of the specified path parameter. -
blockingTaskExecutor
ContextAwareScheduledExecutorService blockingTaskExecutor()Returns theContextAwareScheduledExecutorServicethat could be used for executing a potentially long-running task. TheContextAwareScheduledExecutorServicesets thisServiceRequestContextas the current context before executing any submitted tasks. If you want to useScheduledExecutorServicewithout setting this context, callContextAwareScheduledExecutorService.withoutContext()and use the returnedScheduledExecutorService. -
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. -
negotiatedResponseMediaType
Returns the negotiated producible media type. If the media type negotiation is not used for theService,nullwould be returned. -
requestTimeoutMillis
long requestTimeoutMillis()Returns the amount of time allowed from the start time of theRequestuntil receiving the currentRequestand sending the correspondingResponsecompletely. 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 theRequestis not fully received or the correspondingResponseis not sent completely within the specified amount time from now. Note that the specifiedrequestTimeoutmust 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 theRequestis not fully received or the correspondingResponseis not sent completely within the specifiedTimeoutModeand the specifiedrequestTimeoutMillis.timeout mode description Timeout mode description TimeoutMode.SET_FROM_NOWSets a given amount of timeout from the current time. TimeoutMode.SET_FROM_STARTSets a given amount of timeout since the current Requestbegan processing.TimeoutMode.EXTENDExtends 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 theRequestis not fully received or the correspondingResponseis not sent completely within the specified amount time from now. Note that the specifiedrequestTimeoutmust 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 theRequestis not fully received or the correspondingResponseis not sent completely within the specifiedTimeoutModeand the specifiedrequestTimeout.timeout mode description Timeout mode description TimeoutMode.SET_FROM_NOWSets a given amount of timeout from the current time. TimeoutMode.SET_FROM_STARTSets a given amount of timeout since the current Requestbegan processing.TimeoutMode.EXTENDExtends 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 aCompletableFuturewhich is completed with aThrowablecancellation cause when theServiceRequestContextis about to get cancelled. If the request is handled successfully without cancellation, theCompletableFuturewon't complete. -
whenRequestCancelled
CompletableFuture<Throwable> whenRequestCancelled()Returns aCompletableFuturewhich is completed with aThrowablecancellation cause after theServiceRequestContexthas been cancelled.RequestContext.isCancelled()will always returntruewhen the returnedCompletableFutureis completed. If the request is handled successfully without cancellation, theCompletableFuturewon't complete. -
whenRequestTimingOut
Deprecated.UsewhenRequestCancelling()instead.Returns aCompletableFuturewhich is completed when theServiceRequestContextis about to get timed out. If the request is handled successfully or not cancelled by timeout, theCompletableFuturewon't complete. -
whenRequestTimedOut
Deprecated.UsewhenRequestCancelled()instead.Returns aCompletableFuturewhich is completed after theServiceRequestContexthas been timed out.RequestContext.isTimedOut()will always returntruewhen the returnedCompletableFutureis completed. If the request is handled successfully or not cancelled by timeout, theCompletableFuturewon't complete. -
cancel
default void cancel()Cancels the request. Shortcut forcancel(RequestCancellationException.get()).- Specified by:
cancelin interfaceRequestContext
-
timeoutNow
default void timeoutNow()Times out the request. Shortcut forcancel(RequestTimeoutException.get()).- Specified by:
timeoutNowin 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:
ContentTooLargeException
-
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:
ContentTooLargeException
-
additionalResponseHeaders
HttpHeaders additionalResponseHeaders() -
setAdditionalResponseHeader
Sets a header with the specifiednameandvalue. This will remove all previous values associated with the specifiedname. The header will be included when aServicesends anHttpResponse. -
addAdditionalResponseHeader
Adds a header with the specifiednameandvalue. The header will be included when aServicesends anHttpResponse. -
mutateAdditionalResponseHeaders
- Parameters:
mutator- theConsumerthat mutates the additional response headers
-
additionalResponseTrailers
HttpHeaders additionalResponseTrailers()Returns theHttpHeaderswhich is included along with any other trailers when aServicecompletes anHttpResponse. -
setAdditionalResponseTrailer
Sets a trailer with the specifiednameandvalue. This will remove all previous values associated with the specifiedname. The trailer will be included when aServicecompletes anHttpResponse. -
addAdditionalResponseTrailer
Adds a trailer with the specifiednameandvalue. The trailer will be included when aServicecompletes anHttpResponse. -
mutateAdditionalResponseTrailers
Mutates theHttpHeaderswhich is included along with any other trailers when aServicecompletes anHttpResponse.- Parameters:
mutator- theConsumerthat mutates the additional trailers
-
proxiedAddresses
ProxiedAddresses proxiedAddresses()Returns the proxied addresses of the currentRequest. -
initiateConnectionShutdown
Initiates graceful connection shutdown with a given drain duration in microseconds and returnsCompletableFuturethat completes when the channel 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 returnsCompletableFuturethat completes when the channel is closed. -
initiateConnectionShutdown
Initiates connection shutdown without overriding current configuration of the drain duration and returnsCompletableFuturethat completes when the channel is closed.
-
whenRequestCancelled()instead.