Interface ClientRequestContext
- All Superinterfaces:
RequestContext,Unwrappable
- All Known Implementing Classes:
ClientRequestContextWrapper
Request, its Response and its related utilities.
Every client request has its own ClientRequestContext instance.-
Method Summary
Modifier and TypeMethodDescriptionvoidaddAdditionalRequestHeader(CharSequence name, Object value) Adds a header with the specifiednameandvalue.Returns the authority which will eventually be sent when aClientsends anHttpRequest.static ClientRequestContextBuilderbuilder(HttpRequest request) Returns a newClientRequestContextBuildercreated from the specifiedHttpRequest.static ClientRequestContextBuilderbuilder(RpcRequest request, String uri) static ClientRequestContextBuilderbuilder(RpcRequest request, URI uri) default voidcancel()Cancels the response.voidClears the previously scheduled response timeout, if any.static ClientRequestContextcurrent()Returns the client-side context of theRequestthat is being handled in the current thread.static @Nullable ClientRequestContextReturns the client-side context of theRequestthat is being handled in the current thread.endpoint()Returns theEndpointGroupused for the currentRequest.fragment()Returns the fragment part of the URI of the currentRequest, as defined in the section 3.5 of RFC3986.Initiates connection shutdown and returnsCompletableFuturethat completes when the connection associated with this context is closed.static <T> TmapCurrent(Function<? super ClientRequestContext, T> mapper, @Nullable Supplier<T> defaultValueSupplier) Maps the client-side context of theRequestthat is being handled in the current thread.longReturns the maximum length of the receivedResponse.voidnewDerivedContext(RequestId id, @Nullable HttpRequest req, @Nullable RpcRequest rpcReq, @Nullable Endpoint endpoint) Creates a newClientRequestContextwhose properties andAttributes are copied from thisClientRequestContext, except having differentRequest,Endpointand its ownRequestLog.static ClientRequestContextof(HttpRequest request) Returns a newClientRequestContextcreated from the specifiedHttpRequest.static ClientRequestContextof(RpcRequest request, String uri) Returns a newClientRequestContextcreated from the specifiedRpcRequestand URI.static ClientRequestContextof(RpcRequest request, URI uri) options()Returns theClientOptionsof the currentRequest.default SafeCloseablepush()Pushes this context to the thread-local stack.request()Returns theHttpRequestassociated with this context, ornullif there's noHttpRequestassociated with this context yet.longReturns theRpcRequestassociated with this context, ornullif there's noRpcRequestassociated with this context.voidsetAdditionalRequestHeader(CharSequence name, Object value) Sets a header with the specifiednameandvalue.voidsetMaxResponseLength(long maxResponseLength) Sets the maximum length of the receivedResponse.voidsetResponseTimeout(TimeoutMode mode, Duration responseTimeout) Schedules the response timeout that is triggered when theResponseis not fully received within the specifiedTimeoutModeand the specifiedresponseTimeoutMillissince theResponsestarted orRequestwas fully sent.default voidsetResponseTimeout(Duration responseTimeout) Schedules the response timeout that is triggered when theResponseis not fully received within the specified amount of time from now.default voidsetResponseTimeoutMillis(long responseTimeoutMillis) Schedules the response timeout that is triggered when theResponseis not fully received within the specified amount of time from now.voidsetResponseTimeoutMillis(TimeoutMode mode, long responseTimeoutMillis) Schedules the response timeout that is triggered when theResponseis not fully received within the specifiedTimeoutModeand the specifiedresponseTimeoutMillissince theResponsestarted orRequestwas fully sent.voidsetWriteTimeout(Duration writeTimeout) Sets the amount of time allowed until the initial write attempt of the currentRequestsucceeds.voidsetWriteTimeoutMillis(long writeTimeoutMillis) Sets the amount of time allowed until the initial write attempt of the currentRequestsucceeds.default voidTimes out the response.default ClientRequestContextunwrap()Unwraps this object and returns the object being decorated.default ClientRequestContextUnwraps this object and returns the innermost object being decorated.uri()Returns theURIconstructed based onRequestContext.sessionProtocol(),authority(),RequestContext.path()andRequestContext.query().Returns aCompletableFuturewhich is completed with aThrowablecancellation cause after theClientRequestContexthas been cancelled.Returns aCompletableFuturewhich is completed with aThrowablecancellation cause when theClientRequestContextis about to get cancelled.Deprecated.Deprecated.UsewhenResponseCancelling()instead.longReturns the amount of time allowed until the initial write attempt of the currentRequestsucceeds.Methods inherited from interface com.linecorp.armeria.common.RequestContext
alloc, attr, attrs, cancel, cancellationCause, decodedPath, eventLoop, hasAttr, hasOwnAttr, id, isCancelled, isTimedOut, localAddress, log, logBuilder, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, meterRegistry, method, ownAttr, ownAttrs, path, query, remoteAddress, replace, requestAutoAbortDelayMillis, root, run, run, sessionProtocol, setAttr, setRequestAutoAbortDelay, setRequestAutoAbortDelayMillis, sslSession, updateRequest, updateRpcRequestMethods inherited from interface com.linecorp.armeria.common.util.Unwrappable
as, equalsIgnoreWrapper
-
Method Details
-
current
Returns the client-side context of theRequestthat is being handled in the current thread.- Throws:
IllegalStateException- if the context is unavailable in the current thread or the current context is not aClientRequestContext.
-
currentOrNull
Returns the client-side context of theRequestthat is being handled in the current thread.- Returns:
- the
ClientRequestContextavailable in the current thread, ornullif unavailable.
-
mapCurrent
@Nullable static <T> T mapCurrent(Function<? super ClientRequestContext, T> mapper, @Nullable @Nullable Supplier<T> defaultValueSupplier) Maps the client-side context of theRequestthat is being handled in the current thread.- Parameters:
mapper- theFunctionthat maps theClientRequestContextdefaultValueSupplier- 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 aClientRequestContext.
-
of
Returns a newClientRequestContextcreated 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:
-
of
Returns a newClientRequestContextcreated from the specifiedRpcRequestand URI. 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:
-
of
Returns a newClientRequestContextcreated from the specifiedRpcRequestandURI. 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 newClientRequestContextBuildercreated from the specifiedHttpRequest. -
builder
-
builder
-
request
Returns theHttpRequestassociated with this context, ornullif there's noHttpRequestassociated with this context yet. For example, when you send an RPC request, this method will returnnulluntil the RPC request is translated into an HTTP request.- Specified by:
requestin interfaceRequestContext
-
rpcRequest
Returns theRpcRequestassociated with this context, ornullif there's noRpcRequestassociated with this context. For example, this method will returnnullwhen you are not sending an RPC request but just a plain HTTP request.- Specified by:
rpcRequestin interfaceRequestContext
-
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
ClientRequestContextas this - reentrance - the thread-local has the
ServiceRequestContextwhich is the same asRequestContext.root() - the thread-local has the
ClientRequestContextwhoseRequestContext.root()is the sameRequestContext.root() - the thread-local has the
ClientRequestContextwhoseRequestContext.root()isnulland thisRequestContext.root()isnull
IllegalStateException.- Specified by:
pushin interfaceRequestContext
- the thread-local does not have any
-
newDerivedContext
ClientRequestContext newDerivedContext(RequestId id, @Nullable @Nullable HttpRequest req, @Nullable @Nullable RpcRequest rpcReq, @Nullable @Nullable Endpoint endpoint) Creates a newClientRequestContextwhose properties andAttributes are copied from thisClientRequestContext, except having differentRequest,Endpointand its ownRequestLog.Note that this method does not copy the
RequestLogproperties to the derived context. -
endpointGroup
Returns theEndpointGroupused for the currentRequest.- Returns:
- the
EndpointGroupif a user specified anEndpointGroupwhen initiating aRequest.nullif a user specified anEndpoint.
-
endpoint
-
options
ClientOptions options()Returns theClientOptionsof the currentRequest. -
fragment
Returns the fragment part of the URI of the currentRequest, as defined in the section 3.5 of RFC3986.- Returns:
- the fragment part of the request URI, or
nullif no fragment was specified
-
authority
Returns the authority which will eventually be sent when aClientsends anHttpRequest. This method checks the following locations and returns the first non-null value.- Either the
HttpHeaderNames.HOSTorHttpHeaderNames.AUTHORITYvalue fromadditionalRequestHeaders(). - The
HttpRequest.authority()fromrequest(). defaultRequestHeaders().Endpoint.authority().
- Either the
-
uri
Returns theURIconstructed based onRequestContext.sessionProtocol(),authority(),RequestContext.path()andRequestContext.query().- Specified by:
uriin interfaceRequestContext- Throws:
IllegalStateException- if the resulting URI is not valid.- See Also:
-
writeTimeoutMillis
long writeTimeoutMillis()Returns the amount of time allowed until the initial write attempt of the currentRequestsucceeds. This value is initially set fromClientOptions.WRITE_TIMEOUT_MILLIS. -
setWriteTimeoutMillis
void setWriteTimeoutMillis(long writeTimeoutMillis) Sets the amount of time allowed until the initial write attempt of the currentRequestsucceeds. This value is initially set fromClientOptions.WRITE_TIMEOUT_MILLIS. -
setWriteTimeout
Sets the amount of time allowed until the initial write attempt of the currentRequestsucceeds. This value is initially set fromClientOptions.WRITE_TIMEOUT_MILLIS. -
responseTimeoutMillis
long responseTimeoutMillis()Returns the amount of time allowed until receiving theResponsecompletely since the transfer of theResponsestarted or theRequestwas fully sent. This value is initially set fromClientOptions.RESPONSE_TIMEOUT_MILLIS. -
clearResponseTimeout
void clearResponseTimeout()Clears the previously scheduled response timeout, if any. Note that calling this will prevent the response from ever being timed out. -
setResponseTimeoutMillis
Schedules the response timeout that is triggered when theResponseis not fully received within the specifiedTimeoutModeand the specifiedresponseTimeoutMillissince theResponsestarted orRequestwas fully sent. This value is initially set fromClientOptions.RESPONSE_TIMEOUT_MILLIS.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 Responsebegan processing.TimeoutMode.EXTENDExtends the previously scheduled timeout by the given amount of timeout. For example:
ClientRequestContext ctx = ...; // Schedules a timeout from the start time of the response ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_START, 2000); assert ctx.responseTimeoutMillis() == 2000; ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_START, 1000); assert ctx.responseTimeoutMillis() == 1000; // Schedules timeout after 3 seconds from now. ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_NOW, 3000); // Extends the previously scheduled timeout. long oldResponseTimeoutMillis = ctx.responseTimeoutMillis(); ctx.setResponseTimeoutMillis(TimeoutMode.EXTEND, 1000); assert ctx.responseTimeoutMillis() == oldResponseTimeoutMillis + 1000; ctx.extendResponseTimeoutMillis(TimeoutMode.EXTEND, -500); assert ctx.responseTimeoutMillis() == oldResponseTimeoutMillis + 500; -
setResponseTimeoutMillis
default void setResponseTimeoutMillis(long responseTimeoutMillis) Schedules the response timeout that is triggered when theResponseis not fully received within the specified amount of time from now. Note that the specifiedresponseTimeoutMillismust be positive. This value is initially set fromClientOptions.RESPONSE_TIMEOUT_MILLIS. This method is a shortcut forsetResponseTimeoutMillis(TimeoutMode.SET_FROM_NOW, responseTimeoutMillis).For example:
ClientRequestContext ctx = ...; // Schedules timeout after 1 seconds from now. ctx.setResponseTimeoutMillis(1000);- Parameters:
responseTimeoutMillis- the amount of time allowed in milliseconds from now
-
setResponseTimeout
Schedules the response timeout that is triggered when theResponseis not fully received within the specifiedTimeoutModeand the specifiedresponseTimeoutMillissince theResponsestarted orRequestwas fully sent. This value is initially set fromClientOptions.RESPONSE_TIMEOUT_MILLIS.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 Responsebegan processing.TimeoutMode.EXTENDExtends the previously scheduled timeout by the given amount of timeout. For example:
ClientRequestContext ctx = ...; // Schedules a timeout from the start time of the response ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_START, Duration.ofSeconds(2)); assert ctx.responseTimeoutMillis() == 2000; ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_START, Duration.ofSeconds(1)); assert ctx.responseTimeoutMillis() == 1000; // Schedules timeout after 3 seconds from now. ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_NOW, Duration.ofSeconds(3)); // Extends the previously scheduled timeout. long oldResponseTimeoutMillis = ctx.responseTimeoutMillis(); ctx.setResponseTimeoutMillis(TimeoutMode.EXTEND, Duration.ofSeconds(1)); assert ctx.responseTimeoutMillis() == oldResponseTimeoutMillis + 1000; ctx.setResponseTimeoutMillis(TimeoutMode.EXTEND, Duration.ofMillis(-500)); assert ctx.responseTimeoutMillis() == oldResponseTimeoutMillis + 500; -
setResponseTimeout
Schedules the response timeout that is triggered when theResponseis not fully received within the specified amount of time from now. Note that the specifiedresponseTimeoutmust be positive. This value is initially set fromClientOptions.RESPONSE_TIMEOUT_MILLIS. This method is a shortcut forsetResponseTimeout(TimeoutMode.SET_FROM_NOW, responseTimeout).For example:
ClientRequestContext ctx = ...; // Schedules timeout after 1 seconds from now. ctx.setResponseTimeout(Duration.ofSeconds(1));- Parameters:
responseTimeout- the amount of time allowed from now
-
whenResponseCancelling
CompletableFuture<Throwable> whenResponseCancelling()Returns aCompletableFuturewhich is completed with aThrowablecancellation cause when theClientRequestContextis about to get cancelled. If the response is handled successfully without cancellation, theCompletableFuturewon't complete. -
whenResponseCancelled
CompletableFuture<Throwable> whenResponseCancelled()Returns aCompletableFuturewhich is completed with aThrowablecancellation cause after theClientRequestContexthas been cancelled.RequestContext.isCancelled()will always returntruewhen the returnedCompletableFutureis completed. If the response is handled successfully without cancellation, theCompletableFuturewon't complete. -
whenResponseTimingOut
Deprecated.UsewhenResponseCancelling()instead.Returns aCompletableFuturewhich is completed when theClientRequestContextis about to get timed out. If the response is handled successfully or not cancelled by timeout, theCompletableFuturewon't complete. -
whenResponseTimedOut
Deprecated.UsewhenResponseCancelled()instead.Returns aCompletableFuturewhich is completed after theClientRequestContexthas been timed out.RequestContext.isTimedOut()will always returntruewhen the returnedCompletableFutureis completed. If the response is handled successfully or not cancelled by timeout, theCompletableFuturewon't complete. -
cancel
default void cancel()Cancels the response. Shortcut forcancel(ResponseCancellationException.get()).- Specified by:
cancelin interfaceRequestContext
-
timeoutNow
default void timeoutNow()Times out the response. Shortcut forcancel(ResponseTimeoutException.get()).- Specified by:
timeoutNowin interfaceRequestContext
-
maxResponseLength
long maxResponseLength()Returns the maximum length of the receivedResponse. This value is initially set fromClientOptions.MAX_RESPONSE_LENGTH.- Returns:
- the maximum length of the response.
0if unlimited. - See Also:
-
setMaxResponseLength
void setMaxResponseLength(long maxResponseLength) Sets the maximum length of the receivedResponse. This value is initially set fromClientOptions.MAX_RESPONSE_LENGTH. Specify0to disable the limit of the length of a response.- See Also:
-
defaultRequestHeaders
Returns the defaultHttpHeaderswhich will be included when aClientsends anHttpRequest.Note that the values of the default
HttpHeaderscould be overridden if the sameHttpHeaderNamesare defined inHttpRequest.headers()oradditionalRequestHeaders(). -
additionalRequestHeaders
HttpHeaders additionalRequestHeaders() -
setAdditionalRequestHeader
Sets a header with the specifiednameandvalue. This will remove all previous values associated with the specifiedname. The header will be included when aClientsends anHttpRequest. -
addAdditionalRequestHeader
Adds a header with the specifiednameandvalue. The header will be included when aClientsends anHttpRequest. -
mutateAdditionalRequestHeaders
- Parameters:
mutator- theConsumerthat mutates the additional request headers
-
initiateConnectionShutdown
Initiates connection shutdown and returnsCompletableFuturethat completes when the connection associated with this context is closed.If not sent already,
"connection: close"header is sent with the request. If the underlying connection's protocol is HTTP/1.1, the connection will be closed as soon as all pending requests are processed. Otherwise, a GOAWAY frame will be sent to initiate graceful connection shutdown.- Specified by:
initiateConnectionShutdownin interfaceRequestContext- See Also:
-
exchangeType
Returns theExchangeTypethat determines whether to stream anHttpRequestorHttpResponse.Note that an
HttpRequestwill be aggregated before being written ifExchangeType.UNARYorExchangeType.RESPONSE_STREAMINGis set.- Specified by:
exchangeTypein interfaceRequestContext
-
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 interfaceRequestContext- 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 interfaceRequestContext- Specified by:
unwrapAllin interfaceUnwrappable
-
whenResponseCancelled()instead.