Interface ServiceRequestContext

All Superinterfaces:
RequestContext, Unwrappable
All Known Implementing Classes:
ServiceRequestContextWrapper

public interface ServiceRequestContext extends RequestContext
Provides information about an invocation and related utilities. Every request being handled has its own ServiceRequestContext instance.
  • Method Details

    • current

      static ServiceRequestContext current()
      Returns the server-side context of the Request that is being handled in the current thread. If the context is a ClientRequestContext, RequestContext.root() is returned.
      Throws:
      IllegalStateException - if the context is unavailable in the current thread or the current context is a ClientRequestContext and RequestContext.root() is null
    • currentOrNull

      @Nullable static @Nullable ServiceRequestContext currentOrNull()
      Returns the server-side context of the Request that is being handled in the current thread. If the context is a ClientRequestContext, RequestContext.root() is returned.
      Returns:
      the ServiceRequestContext available in the current thread, or null 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 the Request that is being handled in the current thread.
      Parameters:
      mapper - the Function that maps the ServiceRequestContext
      defaultValueSupplier - the Supplier that provides the value when the context is unavailable in the current thread. If null, the null will be returned when the context is unavailable in the current thread.
      Throws:
      IllegalStateException - if the current context is not a ServiceRequestContext.
    • of

      static ServiceRequestContext of(HttpRequest request)
      Returns a new ServiceRequestContext created from the specified HttpRequest. 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

      static ServiceRequestContextBuilder builder(HttpRequest request)
      Returns a new ServiceRequestContextBuilder created from the specified HttpRequest.
    • root

      @Nonnull default ServiceRequestContext root()
      Returns the root ServiceRequestContext of this context. This method always returns this.
      Specified by:
      root in interface RequestContext
      Returns:
      this
    • request

      @Nonnull HttpRequest request()
      Returns the HttpRequest associated with this context.
      Specified by:
      request in interface RequestContext
    • rpcRequest

      Returns the RpcRequest associated with this context, or null if there's no RpcRequest associated with this context. For example, this method will return null when the request being handled is 1) not an RPC request or 2) not decoded into an RPC request yet.
      Specified by:
      rpcRequest in interface RequestContext
    • remoteAddress

      @Nonnull <A extends SocketAddress> A remoteAddress()
      Returns the remote address of this request.
      Specified by:
      remoteAddress in interface RequestContext
    • localAddress

      @Nonnull <A extends SocketAddress> A localAddress()
      Returns the local address of this request.
      Specified by:
      localAddress in interface RequestContext
    • clientAddress

      InetAddress clientAddress()
      Returns the address of the client who initiated this request.
    • push

      @MustBeClosed default SafeCloseable push()
      Pushes this context to the thread-local stack. To pop the context from the stack, call SafeCloseable.close(), which can be done using a try-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:

      Otherwise, this method will throw an IllegalStateException.
      Specified by:
      push in interface RequestContext
    • config

      ServiceConfig config()
      Returns the ServiceConfig of the Service that is handling the current Request.
    • routingContext

      RoutingContext routingContext()
      Returns the RoutingContext used to find the Service.
    • pathParams

      Map<String,String> pathParams()
      Returns the path parameters mapped by the Route associated with the Service that is handling the current Request.
    • pathParam

      @Nullable default @Nullable String pathParam(String name)
      Returns the value of the specified path parameter.
    • queryParams

      QueryParams queryParams()
      Returns the decoded query part of the current Request URI, as defined in RFC3986.
    • queryParams

      default List<String> queryParams(String name)
      Returns all values for the parameter with the specified name. The returned List can't be modified.
      Parameters:
      name - the parameter name
      Returns:
      a List of parameter values or an empty List if there is no such parameter.
    • queryParam

      @Nullable default @Nullable String queryParam(String name)
      Returns the value of a parameter with the specified name. If there are more than one value for the specified name, 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 the ContextAwareBlockingTaskExecutor that could be used for executing a potentially long-running task. The ContextAwareBlockingTaskExecutor sets this ServiceRequestContext as the current context before executing any submitted tasks. If you want to use BlockingTaskExecutor without setting this context, call ContextAwareBlockingTaskExecutor.withoutContext() and use the returned BlockingTaskExecutor.
    • mappedPath

      String mappedPath()
      Returns the RequestContext.path() with its context path removed. This method can be useful for a reusable service bound at various path prefixes.
    • decodedMappedPath

      String decodedMappedPath()
      Returns the RequestContext.decodedPath() with its context path removed. This method can be useful for a reusable service bound at various path prefixes.
    • uri

      Returns the URI associated with the current Request. Note that this method is a shortcut of calling HttpRequest.uri() on request().
      Specified by:
      uri in interface RequestContext
      See Also:
    • negotiatedResponseMediaType

      @Nullable @Nullable MediaType negotiatedResponseMediaType()
      Returns the negotiated producible media type. If the media type negotiation is not used for the Service, null would be returned.
    • requestTimeoutMillis

      long requestTimeoutMillis()
      Returns the amount of time allowed from the start time of the Request until receiving the current Request and sending the corresponding Response completely. This value is initially set from ServiceConfig.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 the Request is not fully received or the corresponding Response is not sent completely within the specified amount time from now. Note that the specified requestTimeout must be positive. This value is initially set from ServiceConfig.requestTimeoutMillis(). This method is a shortcut for setRequestTimeoutMillis(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

      void setRequestTimeoutMillis(TimeoutMode mode, long requestTimeoutMillis)
      Schedules the request timeout that is triggered when the Request is not fully received or the corresponding Response is not sent completely within the specified TimeoutMode and the specified requestTimeoutMillis.
      timeout mode description
      Timeout modedescription
      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

      default void setRequestTimeout(Duration requestTimeout)
      Schedules the request timeout that is triggered when the Request is not fully received or the corresponding Response is not sent completely within the specified amount time from now. Note that the specified requestTimeout must be positive. This value is initially set from ServiceConfig.requestTimeoutMillis(). This method is a shortcut for setRequestTimeout(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

      void setRequestTimeout(TimeoutMode mode, Duration requestTimeout)
      Schedules the request timeout that is triggered when the Request is not fully received or the corresponding Response is not sent completely within the specified TimeoutMode and the specified requestTimeout.
      timeout mode description
      Timeout modedescription
      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 a CompletableFuture which is completed with a Throwable cancellation cause when the ServiceRequestContext is about to get cancelled. If the request is handled successfully without cancellation, the CompletableFuture won't complete.
    • whenRequestCancelled

      CompletableFuture<Throwable> whenRequestCancelled()
      Returns a CompletableFuture which is completed with a Throwable cancellation cause after the ServiceRequestContext has been cancelled. RequestContext.isCancelled() will always return true when the returned CompletableFuture is completed. If the request is handled successfully without cancellation, the CompletableFuture won't complete.
    • whenRequestTimingOut

      @Deprecated CompletableFuture<Void> whenRequestTimingOut()
      Deprecated.
      Returns a CompletableFuture which is completed when the ServiceRequestContext is about to get timed out. If the request is handled successfully or not cancelled by timeout, the CompletableFuture won't complete.
    • whenRequestTimedOut

      @Deprecated CompletableFuture<Void> whenRequestTimedOut()
      Deprecated.
      Returns a CompletableFuture which is completed after the ServiceRequestContext has been timed out. RequestContext.isTimedOut() will always return true when the returned CompletableFuture is completed. If the request is handled successfully or not cancelled by timeout, the CompletableFuture won't complete.
    • cancel

      default void cancel()
      Cancels the request. Shortcut for cancel(RequestCancellationException.get()).
      Specified by:
      cancel in interface RequestContext
    • timeoutNow

      default void timeoutNow()
      Times out the request. Shortcut for cancel(RequestTimeoutException.get()).
      Specified by:
      timeoutNow in interface RequestContext
    • maxRequestLength

      long maxRequestLength()
      Returns the maximum length of the current Request. This value is initially set from ServiceConfig.maxRequestLength(). If 0, there is no limit on the request size.
      See Also:
    • setMaxRequestLength

      void setMaxRequestLength(long maxRequestLength)
      Sets the maximum length of the current Request. This value is initially set from ServiceConfig.maxRequestLength(). If 0, there is no limit on the request size.
      See Also:
    • additionalResponseHeaders

      HttpHeaders additionalResponseHeaders()
      Returns the HttpHeaders which will be included when a Service sends an HttpResponse.
    • setAdditionalResponseHeader

      void setAdditionalResponseHeader(CharSequence name, Object value)
      Sets a header with the specified name and value. This will remove all previous values associated with the specified name. The header will be included when a Service sends an HttpResponse.
    • addAdditionalResponseHeader

      void addAdditionalResponseHeader(CharSequence name, Object value)
      Adds a header with the specified name and value. The header will be included when a Service sends an HttpResponse.
    • mutateAdditionalResponseHeaders

      void mutateAdditionalResponseHeaders(Consumer<HttpHeadersBuilder> mutator)
      Mutates the HttpHeaders which will be included when a Service sends an HttpResponse.
      Parameters:
      mutator - the Consumer that mutates the additional response headers
    • additionalResponseTrailers

      HttpHeaders additionalResponseTrailers()
      Returns the HttpHeaders which is included along with any other trailers when a Service completes an HttpResponse.
    • setAdditionalResponseTrailer

      void setAdditionalResponseTrailer(CharSequence name, Object value)
      Sets a trailer with the specified name and value. This will remove all previous values associated with the specified name. The trailer will be included when a Service completes an HttpResponse.
    • addAdditionalResponseTrailer

      void addAdditionalResponseTrailer(CharSequence name, Object value)
      Adds a trailer with the specified name and value. The trailer will be included when a Service completes an HttpResponse.
    • mutateAdditionalResponseTrailers

      void mutateAdditionalResponseTrailers(Consumer<HttpHeadersBuilder> mutator)
      Mutates the HttpHeaders which is included along with any other trailers when a Service completes an HttpResponse.
      Parameters:
      mutator - the Consumer that mutates the additional trailers
    • proxiedAddresses

      ProxiedAddresses proxiedAddresses()
      Returns the proxied addresses of the current Request.
    • shouldReportUnhandledExceptions

      boolean shouldReportUnhandledExceptions()
      Returns whether exceptions should be reported. When LoggingService 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

      @UnstableApi CompletableFuture<Void> initiateConnectionShutdown(long drainDurationMicros)
      Initiates graceful connection shutdown with a given drain duration in microseconds and returns CompletableFuture 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.

      See Also:
    • initiateConnectionShutdown

      @UnstableApi default CompletableFuture<Void> initiateConnectionShutdown(Duration drainDuration)
      Initiates graceful connection shutdown with a given drain duration and returns CompletableFuture that completes when the connection associated with this context is closed.
      See Also:
    • initiateConnectionShutdown

      @UnstableApi CompletableFuture<Void> initiateConnectionShutdown()
      Initiates connection shutdown without overriding current configuration of the drain duration and returns CompletableFuture that completes when the connection associated with this context is closed.
      Specified by:
      initiateConnectionShutdown in interface RequestContext
      See Also:
    • exchangeType

      ExchangeType exchangeType()
      Returns the ExchangeType that determines whether to stream an HttpRequest or HttpResponse.

      Note that an HttpRequest will be aggregated before serving the HttpService if ExchangeType.UNARY or ExchangeType.RESPONSE_STREAMING is set.

      Specified by:
      exchangeType in interface RequestContext
    • unwrap

      default ServiceRequestContext unwrap()
      Description copied from interface: Unwrappable
      Unwraps this object and returns the object being decorated. If this Unwrappable 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 interface RequestContext
      Specified by:
      unwrap in interface Unwrappable
    • unwrapAll

      default ServiceRequestContext unwrapAll()
      Description copied from interface: Unwrappable
      Unwraps this object and returns the innermost object being decorated. If this Unwrappable 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 interface RequestContext
      Specified by:
      unwrapAll in interface Unwrappable