Package com.linecorp.armeria.server
Interface ServiceRequestContext
- All Superinterfaces:
RequestContext
- All Known Implementing Classes:
DefaultServiceRequestContext
,ServiceRequestContextWrapper
public interface ServiceRequestContext extends RequestContext
Provides information about an invocation and related utilities. Every request being handled has its own
ServiceRequestContext
instance.-
Method Summary
Modifier and Type Method Description default AccessLogWriter
accessLogWriter()
Deprecated.Access viaconfig()
.void
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
.HttpHeaders
additionalResponseHeaders()
HttpHeaders
additionalResponseTrailers()
Returns theHttpHeaders
which is included along with any other trailers when aService
completes anHttpResponse
.ScheduledExecutorService
blockingTaskExecutor()
Returns theScheduledExecutorService
that could be used for executing a potentially long-running task.static ServiceRequestContextBuilder
builder(HttpRequest request)
Returns a newServiceRequestContextBuilder
created from the specifiedHttpRequest
.void
clearRequestTimeout()
Clears the previously scheduled request timeout, if any.default InetAddress
clientAddress()
Returns the address of the client who initiated this request.ServiceConfig
config()
static ServiceRequestContext
current()
Returns the server-side context of theRequest
that is being handled in the current thread.static ServiceRequestContext
currentOrNull()
Returns the server-side context of theRequest
that is being handled in the current thread.String
decodedMappedPath()
Returns theRequestContext.decodedPath()
with its context path removed.default void
extendRequestTimeout(Duration adjustment)
Deprecated.default void
extendRequestTimeoutMillis(long adjustmentMillis)
Deprecated.boolean
isTimedOut()
Returns whether thisServiceRequestContext
has been timed-out (e.g., when the corresponding request passes a deadline).<A extends SocketAddress>
AlocalAddress()
Returns the local address of this request.static <T> T
mapCurrent(Function<? super ServiceRequestContext,T> mapper, Supplier<T> defaultValueSupplier)
Maps the server-side context of theRequest
that is being handled in the current thread.String
mappedPath()
Returns theRequestContext.path()
with its context path removed.long
maxRequestLength()
Returns the maximum length of the currentRequest
.void
mutateAdditionalResponseHeaders(Consumer<HttpHeadersBuilder> mutator)
void
mutateAdditionalResponseTrailers(Consumer<HttpHeadersBuilder> mutator)
Mutates theHttpHeaders
which is included along with any other trailers when aService
completes anHttpResponse
.MediaType
negotiatedResponseMediaType()
Returns the negotiated producible media type.ServiceRequestContext
newDerivedContext(RequestId id, HttpRequest req, RpcRequest rpcReq)
Creates a newRequestContext
whose properties andRequestContext.attrs()
are copied from thisRequestContext
, except having a different pair ofHttpRequest
andRpcRequest
and its ownRequestLog
.static ServiceRequestContext
of(HttpRequest request)
Returns a newServiceRequestContext
created from the specifiedHttpRequest
.default String
pathParam(String name)
Returns the value of the specified path parameter.Map<String,String>
pathParams()
ProxiedAddresses
proxiedAddresses()
Returns the proxied addresses of the currentRequest
.default SafeCloseable
push()
Pushes this context to the thread-local stack.<A extends SocketAddress>
AremoteAddress()
Returns the remote address of this request.HttpRequest
request()
Returns theHttpRequest
associated with this context.Runnable
requestTimeoutHandler()
ReturnsRequest
timeout handler which is executed when receiving the currentRequest
and sending the correspondingResponse
is not completely received within the allowedrequestTimeoutMillis()
.long
requestTimeoutMillis()
default Route
route()
Deprecated.Access viaconfig()
.RoutingContext
routingContext()
Returns theRoutingContext
used to find theService
.RpcRequest
rpcRequest()
Returns theRpcRequest
associated with this context, ornull
if there's noRpcRequest
associated with this context.default Server
server()
Deprecated.Access viaconfig()
.default HttpService
service()
Deprecated.Access viaconfig()
.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
.default 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
setRequestTimeoutAfter(Duration requestTimeout)
Deprecated.default void
setRequestTimeoutAfterMillis(long requestTimeoutMillis)
Deprecated.default void
setRequestTimeoutAt(Instant requestTimeoutAt)
Deprecated.This method will be removed without a replacement.void
setRequestTimeoutAtMillis(long requestTimeoutAtMillis)
Deprecated.This method will be removed without a replacement.void
setRequestTimeoutHandler(Runnable requestTimeoutHandler)
Sets a handler to run when the request times out.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
.default boolean
verboseResponses()
Deprecated.Access viaconfig()
.default VirtualHost
virtualHost()
Deprecated.Access viaconfig()
.Methods inherited from interface com.linecorp.armeria.common.RequestContext
alloc, attr, attrs, computeAttrIfAbsent, contextAwareEventLoop, contextAwareExecutor, decodedPath, eventLoop, executor, id, log, logBuilder, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, makeContextAware, meterRegistry, method, path, query, replace, sessionProtocol, setAttr, setAttrIfAbsent, sslSession, updateRequest, updateRpcRequest
-
Method Details
-
current
Returns the server-side context of theRequest
that is being handled in the current thread. If the context is aClientRequestContext
,ClientRequestContext.root()
is returned.- Throws:
IllegalStateException
- if the context is unavailable in the current thread or the current context is aClientRequestContext
andClientRequestContext.root()
isnull
-
currentOrNull
Returns the server-side context of theRequest
that is being handled in the current thread. If the context is aClientRequestContext
,ClientRequestContext.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 Supplier<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:
ServiceRequestContextBuilder
-
builder
Returns a newServiceRequestContextBuilder
created from the specifiedHttpRequest
. -
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
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
whoseClientRequestContext.root()
is the sameServiceRequestContext
as this
IllegalStateException
.- Specified by:
push
in interfaceRequestContext
- the thread-local does not have any
-
newDerivedContext
ServiceRequestContext newDerivedContext(RequestId id, @Nullable HttpRequest req, @Nullable RpcRequest rpcReq)Description copied from interface:RequestContext
Creates a newRequestContext
whose properties andRequestContext.attrs()
are copied from thisRequestContext
, except having a different pair ofHttpRequest
andRpcRequest
and its ownRequestLog
.- Specified by:
newDerivedContext
in interfaceRequestContext
-
config
ServiceConfig config() -
server
Deprecated.Access viaconfig()
. -
virtualHost
Deprecated.Access viaconfig()
.Returns theVirtualHost
that is handling the currentRequest
. -
route
Deprecated.Access viaconfig()
. -
routingContext
RoutingContext routingContext()Returns theRoutingContext
used to find theService
. -
pathParams
-
pathParam
Returns the value of the specified path parameter. -
service
Deprecated.Access viaconfig()
.Returns theHttpService
that is handling the currentRequest
. -
blockingTaskExecutor
ScheduledExecutorService blockingTaskExecutor()Returns theScheduledExecutorService
that could be used for executing a potentially long-running task. TheScheduledExecutorService
will propagate theServiceRequestContext
automatically when running a task.Note that performing a long-running task in
Service.serve(ServiceRequestContext, Request)
may block theServer
's I/O event loop and thus should be executed in other threads. -
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
,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 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 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;
-
extendRequestTimeoutMillis
Deprecated.Extends the previously scheduled request timeout by the specified amount ofadjustmentMillis
. This method does nothing if no request timeout was scheduled previously. Note that a negativeadjustment
reduces the current timeout. The initial timeout is set fromServiceConfig.requestTimeoutMillis()
.For example:
ServiceRequestContext ctx = ...; long oldRequestTimeoutMillis = ctx.requestTimeoutMillis(); ctx.extendRequestTimeoutMillis(1000); assert ctx.requestTimeoutMillis() == oldRequestTimeoutMillis + 1000; ctx.extendRequestTimeoutMillis(-500); assert ctx.requestTimeoutMillis() == oldRequestTimeoutMillis + 500;
- Parameters:
adjustmentMillis
- the amount of time in milliseconds to extend the current timeout by
-
extendRequestTimeout
Deprecated.Extends the previously scheduled request timeout by the specified amount ofadjustment
. This method does nothing if no response timeout was scheduled previously. Note that a negativeadjustment
reduces the current timeout. The initial timeout is set fromServiceConfig.requestTimeoutMillis()
.For example:
ServiceRequestContext ctx = ...; long oldRequestTimeoutMillis = ctx.requestTimeoutMillis(); ctx.extendRequestTimeout(Duration.ofSeconds(1)); assert ctx.requestTimeoutMillis() == oldRequestTimeoutMillis + 1000; ctx.extendRequestTimeout(Duration.ofMillis(-500)); assert ctx.requestTimeoutMillis() == oldRequestTimeoutMillis + 500;
- Parameters:
adjustment
- the amount of time to extend the current timeout by
-
setRequestTimeoutAfterMillis
Deprecated.Schedules the request timeout that is triggered when theRequest
is not fully received or the correspondingResponse
is not sent completely within the specified amount of time from now. Note that the specifiedrequestTimeoutMillis
must be positive. The initial timeout is set fromServiceConfig.requestTimeoutMillis()
.For example:
ServiceRequestContext ctx = ...; // Schedules timeout after 1 seconds from now. ctx.setRequestTimeoutAfterMillis(1000);
- Parameters:
requestTimeoutMillis
- the amount of time allowed in milliseconds from now
-
setRequestTimeoutAfter
Deprecated.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. The initial timeout is set fromServiceConfig.requestTimeoutMillis()
.For example:
ServiceRequestContext ctx = ...; // Schedules timeout after 1 seconds from now. ctx.setRequestTimeoutAfter(Duration.ofSeconds(1));
- Parameters:
requestTimeout
- the amount of time allowed from now
-
setRequestTimeoutAtMillis
Deprecated.This method will be removed without a replacement. UsesetRequestTimeout(TimeoutMode, Duration)
orclearRequestTimeout()
.Schedules the request timeout that is triggered at the specified time represented as the number since the epoch (1970-01-01T00:00:00Z
). Note that the request will be timed out immediately if the specified time is before now. The initial timeout is set fromServiceConfig.requestTimeoutMillis()
.For example:
ServiceRequestContext ctx = ...; // Schedules timeout after 1 seconds from now. long responseTimeoutAt = Instant.now().plus(1, ChronoUnit.SECONDS).toEpochMilli(); ctx.setRequestTimeoutAtMillis(responseTimeoutAt);
- Parameters:
requestTimeoutAtMillis
- the request timeout represented as the number of milliseconds since the epoch (1970-01-01T00:00:00Z
)
-
setRequestTimeoutAt
Deprecated.This method will be removed without a replacement. UsesetRequestTimeout(TimeoutMode, Duration)
orclearRequestTimeout()
.Schedules the request timeout that is triggered at the specified time represented as the number since the epoch (1970-01-01T00:00:00Z
). Note that the request will be timed out immediately if the specified time is before now. The initial timeout is set fromServiceConfig.requestTimeoutMillis()
.For example:
ServiceRequestContext ctx = ...; // Schedules timeout after 1 seconds from now. ctx.setRequestTimeoutAt(Instant.now().plus(1, ChronoUnit.SECONDS));
- Parameters:
requestTimeoutAt
- the request timeout represented as the number of milliseconds since the epoch (1970-01-01T00:00:00Z
)
-
requestTimeoutHandler
ReturnsRequest
timeout handler which is executed when receiving the currentRequest
and sending the correspondingResponse
is not completely received within the allowedrequestTimeoutMillis()
. -
setRequestTimeoutHandler
Sets a handler to run when the request times out.requestTimeoutHandler
must close the response, e.g., by callingStreamWriter.close()
. If not set, the response will be closed withHttpStatus.SERVICE_UNAVAILABLE
.For example,
HttpResponseWriter res = HttpResponse.streaming(); ctx.setRequestTimeoutHandler(() -> { res.write(ResponseHeaders.of(HttpStatus.OK, HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8)); res.write(HttpData.ofUtf8("Request timed out.")); res.close(); }); ...
-
isTimedOut
boolean isTimedOut()Returns whether thisServiceRequestContext
has been timed-out (e.g., when the corresponding request passes a deadline). -
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
-
verboseResponses
Deprecated.Access viaconfig()
.Returns whether the verbose response mode is enabled. When enabled, the service responses will contain the exception type and its full stack trace, which may be useful for debugging while potentially insecure. When disabled, the service responses will not expose such server-side details to the client. -
accessLogWriter
Deprecated.Access viaconfig()
.Returns theAccessLogWriter
. -
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
.
-