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 TypeMethodDescriptionvoid
addAdditionalRequestHeader
(CharSequence name, Object value) Adds a header with the specifiedname
andvalue
.Returns the authority which will eventually be sent when aClient
sends anHttpRequest
.static ClientRequestContextBuilder
builder
(HttpRequest request) Returns a newClientRequestContextBuilder
created from the specifiedHttpRequest
.static ClientRequestContextBuilder
builder
(RpcRequest request, String uri) static ClientRequestContextBuilder
builder
(RpcRequest request, URI uri) default void
cancel()
Cancels the response.void
Clears the previously scheduled response timeout, if any.static ClientRequestContext
current()
Returns the client-side context of theRequest
that is being handled in the current thread.static @Nullable ClientRequestContext
Returns the client-side context of theRequest
that is being handled in the current thread.endpoint()
Returns theEndpointGroup
used for the currentRequest
.fragment()
Returns the fragment part of the URI of the currentRequest
, as defined in the section 3.5 of RFC3986.host()
Returns the host part ofauthority()
, without a port number.Initiates connection shutdown and returnsCompletableFuture
that completes when the connection associated with this context is closed.default boolean
Returns whether thisClientRequestContext
has been timed-out, that is the cancellation cause is an instance ofTimeoutException
orUnprocessedRequestException
and wrapped cause isTimeoutException
.static <T> T
mapCurrent
(Function<? super ClientRequestContext, T> mapper, @Nullable Supplier<T> defaultValueSupplier) Maps the client-side context of theRequest
that is being handled in the current thread.long
Returns the maximum length of the receivedResponse
.void
newDerivedContext
(RequestId id, @Nullable HttpRequest req, @Nullable RpcRequest rpcReq, @Nullable Endpoint endpoint) Creates a newClientRequestContext
whose properties andAttribute
s are copied from thisClientRequestContext
, except having differentRequest
,Endpoint
and its ownRequestLog
.static ClientRequestContext
of
(HttpRequest request) Returns a newClientRequestContext
created from the specifiedHttpRequest
.static ClientRequestContext
of
(RpcRequest request, String uri) Returns a newClientRequestContext
created from the specifiedRpcRequest
and URI.static ClientRequestContext
of
(RpcRequest request, URI uri) options()
Returns theClientOptions
of the currentRequest
.default SafeCloseable
push()
Pushes this context to the thread-local stack.request()
Returns theHttpRequest
associated with this context, ornull
if there's noHttpRequest
associated with this context yet.long
Returns theResponseTimeoutMode
which determines when aresponseTimeoutMillis()
will start to be scheduled.Returns theRpcRequest
associated with this context, ornull
if there's noRpcRequest
associated with this context.void
setAdditionalRequestHeader
(CharSequence name, Object value) Sets a header with the specifiedname
andvalue
.void
setMaxResponseLength
(long maxResponseLength) Sets the maximum length of the receivedResponse
.void
setResponseTimeout
(TimeoutMode mode, Duration responseTimeout) Schedules the response timeout that is triggered when theResponse
is not fully received within the specifiedTimeoutMode
and the specifiedresponseTimeoutMillis
since theResponse
started orRequest
was fully sent.default void
setResponseTimeout
(Duration responseTimeout) Schedules the response timeout that is triggered when theResponse
is not fully received within the specified amount of time from now.default void
setResponseTimeoutMillis
(long responseTimeoutMillis) Schedules the response timeout that is triggered when theResponse
is not fully received within the specified amount of time from now.void
setResponseTimeoutMillis
(TimeoutMode mode, long responseTimeoutMillis) Schedules the response timeout that is triggered when theResponse
is not fully received within the specifiedTimeoutMode
and the specifiedresponseTimeoutMillis
since theResponse
started orRequest
was fully sent.void
setWriteTimeout
(Duration writeTimeout) Sets the amount of time allowed until the initial write attempt of the currentRequest
succeeds.void
setWriteTimeoutMillis
(long writeTimeoutMillis) Sets the amount of time allowed until the initial write attempt of the currentRequest
succeeds.default void
Times out the response.default ClientRequestContext
unwrap()
Unwraps this object and returns the object being decorated.default ClientRequestContext
Unwraps this object and returns the innermost object being decorated.uri()
Returns theURI
constructed based onRequestContext.sessionProtocol()
,authority()
,RequestContext.path()
andRequestContext.query()
.Returns aCompletableFuture
which is completed with aThrowable
cancellation cause after theClientRequestContext
has been cancelled.Returns aCompletableFuture
which is completed with aThrowable
cancellation cause when theClientRequestContext
is about to get cancelled.Deprecated.Deprecated.UsewhenResponseCancelling()
instead.long
Returns the amount of time allowed until the initial write attempt of the currentRequest
succeeds.Methods inherited from interface com.linecorp.armeria.common.RequestContext
alloc, attr, attrs, cancel, cancellationCause, decodedPath, eventLoop, hasAttr, hasOwnAttr, hook, hook, id, isCancelled, 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, updateRpcRequest
Methods inherited from interface com.linecorp.armeria.common.util.Unwrappable
as, equalsIgnoreWrapper
-
Method Details
-
current
Returns the client-side context of theRequest
that 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 theRequest
that is being handled in the current thread.- Returns:
- the
ClientRequestContext
available in the current thread, ornull
if unavailable.
-
mapCurrent
@Nullable static <T> T mapCurrent(Function<? super ClientRequestContext, T> mapper, @Nullable @Nullable Supplier<T> defaultValueSupplier) Maps the client-side context of theRequest
that is being handled in the current thread.- Parameters:
mapper
- theFunction
that maps theClientRequestContext
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 aClientRequestContext
.
-
of
Returns a newClientRequestContext
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:
-
of
Returns a newClientRequestContext
created from the specifiedRpcRequest
and 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 newClientRequestContext
created from the specifiedRpcRequest
andURI
. 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 newClientRequestContextBuilder
created from the specifiedHttpRequest
. -
builder
-
builder
-
request
Returns theHttpRequest
associated with this context, ornull
if there's noHttpRequest
associated with this context yet. For example, when you send an RPC request, this method will returnnull
until the RPC request is translated into an HTTP request.- 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 you are not sending an RPC request but just a plain HTTP request.- Specified by:
rpcRequest
in 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-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
ClientRequestContext
as this - reentrance - the thread-local has the
ServiceRequestContext
which is the same asRequestContext.root()
- the thread-local has the
ClientRequestContext
whoseRequestContext.root()
is the sameRequestContext.root()
- the thread-local has the
ClientRequestContext
whoseRequestContext.root()
isnull
and thisRequestContext.root()
isnull
IllegalStateException
.- Specified by:
push
in 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 newClientRequestContext
whose properties andAttribute
s are copied from thisClientRequestContext
, except having differentRequest
,Endpoint
and its ownRequestLog
.Note that this method does not copy the
RequestLog
properties to the derived context. -
endpointGroup
Returns theEndpointGroup
used for the currentRequest
.- Returns:
- the
EndpointGroup
if a user specified anEndpointGroup
when initiating aRequest
.null
if a user specified anEndpoint
.
-
endpoint
-
options
ClientOptions options()Returns theClientOptions
of 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
null
if no fragment was specified
-
authority
Returns the authority which will eventually be sent when aClient
sends anHttpRequest
. This method checks the following locations and returns the first non-null value.- Either the
HttpHeaderNames.HOST
orHttpHeaderNames.AUTHORITY
value fromadditionalRequestHeaders()
. - The
HttpRequest.authority()
fromrequest()
. defaultRequestHeaders()
.Endpoint.authority()
.
- Either the
-
host
Returns the host part ofauthority()
, without a port number. -
uri
Returns theURI
constructed based onRequestContext.sessionProtocol()
,authority()
,RequestContext.path()
andRequestContext.query()
.- Specified by:
uri
in 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 currentRequest
succeeds. 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 currentRequest
succeeds. This value is initially set fromClientOptions.WRITE_TIMEOUT_MILLIS
. -
setWriteTimeout
Sets the amount of time allowed until the initial write attempt of the currentRequest
succeeds. This value is initially set fromClientOptions.WRITE_TIMEOUT_MILLIS
. -
responseTimeoutMillis
long responseTimeoutMillis()Returns the amount of time allowed until receiving theResponse
completely since the transfer of theResponse
started or theRequest
was 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 theResponse
is not fully received within the specifiedTimeoutMode
and the specifiedresponseTimeoutMillis
since theResponse
started orRequest
was fully sent. This value is initially set fromClientOptions.RESPONSE_TIMEOUT_MILLIS
.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 Response
began processing.TimeoutMode.EXTEND
Extends 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 theResponse
is not fully received within the specified amount of time from now. Note that the specifiedresponseTimeoutMillis
must 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 theResponse
is not fully received within the specifiedTimeoutMode
and the specifiedresponseTimeoutMillis
since theResponse
started orRequest
was fully sent. This value is initially set fromClientOptions.RESPONSE_TIMEOUT_MILLIS
.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 Response
began processing.TimeoutMode.EXTEND
Extends 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 theResponse
is not fully received within the specified amount of time from now. Note that the specifiedresponseTimeout
must 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 aCompletableFuture
which is completed with aThrowable
cancellation cause when theClientRequestContext
is about to get cancelled. If the response is handled successfully without cancellation, theCompletableFuture
won't complete. -
whenResponseCancelled
CompletableFuture<Throwable> whenResponseCancelled()Returns aCompletableFuture
which is completed with aThrowable
cancellation cause after theClientRequestContext
has been cancelled.RequestContext.isCancelled()
will always returntrue
when the returnedCompletableFuture
is completed. If the response is handled successfully without cancellation, theCompletableFuture
won't complete. -
whenResponseTimingOut
Deprecated.UsewhenResponseCancelling()
instead.Returns aCompletableFuture
which is completed when theClientRequestContext
is about to get timed out. If the response is handled successfully or not cancelled by timeout, theCompletableFuture
won't complete. -
whenResponseTimedOut
Deprecated.UsewhenResponseCancelled()
instead.Returns aCompletableFuture
which is completed after theClientRequestContext
has been timed out.isTimedOut()
will always returntrue
when the returnedCompletableFuture
is completed. If the response is handled successfully or not cancelled by timeout, theCompletableFuture
won't complete. -
cancel
default void cancel()Cancels the response. Shortcut forcancel(ResponseCancellationException.get())
.- Specified by:
cancel
in interfaceRequestContext
-
timeoutNow
default void timeoutNow()Times out the response. Shortcut forcancel(ResponseTimeoutException.get())
.- Specified by:
timeoutNow
in interfaceRequestContext
-
isTimedOut
default boolean isTimedOut()Returns whether thisClientRequestContext
has been timed-out, that is the cancellation cause is an instance ofTimeoutException
orUnprocessedRequestException
and wrapped cause isTimeoutException
.- Specified by:
isTimedOut
in 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.
0
if unlimited. - See Also:
-
setMaxResponseLength
void setMaxResponseLength(long maxResponseLength) Sets the maximum length of the receivedResponse
. This value is initially set fromClientOptions.MAX_RESPONSE_LENGTH
. Specify0
to disable the limit of the length of a response.- See Also:
-
defaultRequestHeaders
Returns the defaultHttpHeaders
which will be included when aClient
sends anHttpRequest
.Note that the values of the default
HttpHeaders
could be overridden if the sameHttpHeaderNames
are defined inHttpRequest.headers()
oradditionalRequestHeaders()
.- See Also:
-
additionalRequestHeaders
HttpHeaders additionalRequestHeaders() -
setAdditionalRequestHeader
Sets a header with the specifiedname
andvalue
. This will remove all previous values associated with the specifiedname
. The header will be included when aClient
sends anHttpRequest
. -
addAdditionalRequestHeader
Adds a header with the specifiedname
andvalue
. The header will be included when aClient
sends anHttpRequest
. -
mutateAdditionalRequestHeaders
- Parameters:
mutator
- theConsumer
that mutates the additional request headers
-
initiateConnectionShutdown
Initiates connection shutdown and returnsCompletableFuture
that 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:
initiateConnectionShutdown
in interfaceRequestContext
- See Also:
-
exchangeType
Returns theExchangeType
that determines whether to stream anHttpRequest
orHttpResponse
.Note that an
HttpRequest
will be aggregated before being written ifExchangeType.UNARY
orExchangeType.RESPONSE_STREAMING
is set.- Specified by:
exchangeType
in interfaceRequestContext
-
responseTimeoutMode
Returns theResponseTimeoutMode
which determines when aresponseTimeoutMillis()
will start to be scheduled.- See Also:
-
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
-
whenResponseCancelled()
instead.