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 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 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 Supplier<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:
      ServiceRequestContextBuilder
    • 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

      @Nullable RpcRequest 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 String pathParam​(String name)
      Returns the value of the specified path parameter.
    • blockingTaskExecutor

      ContextAwareScheduledExecutorService blockingTaskExecutor()
      Returns the ContextAwareScheduledExecutorService that could be used for executing a potentially long-running task. The ContextAwareScheduledExecutorService sets this ServiceRequestContext as the current context before executing any submitted tasks. If you want to use ScheduledExecutorService without setting this context, call ContextAwareScheduledExecutorService.withoutContext() and use the returned ScheduledExecutorService.
    • 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.
    • negotiatedResponseMediaType

      @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:
      ContentTooLargeException
    • 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:
      ContentTooLargeException
    • 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.