Interface Application

All Superinterfaces:
AutoCloseable, RouteGroup

public interface Application extends RouteGroup, AutoCloseable
Registers routes before startup and owns their execution lifecycle. Registration, startup, and shutdown are thread-safe. Handlers may execute concurrently and are responsible for synchronizing shared application state.

Methods are case-sensitive RFC 9110 tokens and are handled as follows. "Allow" is the union of the methods registered on every template matching the path, plus HEAD wherever GET is. The same answers come from handle(Request), the test client and HTTP listeners.

Method handling
MethodRegistrationPath routed, method not registered there Path not routed
GET, POST, PUT, PATCH, DELETEshortcut or route(java.lang.String, java.lang.String, com.jsgalactic.axiom.context.Handler, com.jsgalactic.axiom.context.Middleware...)405 with Allow 404
HEADRouteGroup.head(java.lang.String, com.jsgalactic.axiom.context.Handler, com.jsgalactic.axiom.context.Middleware...) or the GET route of the same template 405 with Allow404
OPTIONSRouteGroup.options(java.lang.String, com.jsgalactic.axiom.context.Handler, com.jsgalactic.axiom.context.Middleware...)204 with Allow plus OPTIONS, no handler 404
OPTIONS *not possible 204 with every registered method (HEAD if GET is registered) plus OPTIONS
TRACErefused405 with Allow404
CONNECTrefused501
extension token, e.g. PROPFIND or QUERYroute(java.lang.String, java.lang.String, com.jsgalactic.axiom.context.Handler, com.jsgalactic.axiom.context.Middleware...)405 with Allow 404 if registered on any route or declared with recognizeMethods(java.lang.String...), otherwise 501
Request bodies are accepted and limited alike for every method, HEAD responses never carry a body, and method-override headers such as X-HTTP-Method-Override are ignored.
  • Method Details

    • route

      Route route(String method, String path, Handler handler, Middleware... middleware)
      Registers a method/path template with optional route-level middleware. Methods and static segments are case-sensitive. The method must be an RFC 9110 token (one or more of A-Z a-z 0-9 and !#$%&'*+-.^_`|~); get and GET are different methods. Extension methods such as PROPFIND or QUERY are registered here; there is no query shortcut while that method is still a draft. Only the request line's method is matched; method-override headers such as X-HTTP-Method-Override are ignored. Named parameters match one non-empty segment; named terminal wildcards match the remainder. Templates that differ only in capture names have the same shape and match the same paths; registering a second one for the same method fails here.
      Specified by:
      route in interface RouteGroup
      Parameters:
      method - case-sensitive HTTP method token
      path - absolute path template without query or fragment
      handler - callback invoked for matching requests
      middleware - route-level middleware, outermost first; see RouteGroup
      Returns:
      the registered route identity
      Throws:
      IllegalArgumentException - for a method that is not a token, for TRACE (whose echo of the request would expose credentials; TRACE requests are answered 405 or 404), for CONNECT (tunnels are not supported; CONNECT requests are answered 501), for an invalid template, or for a duplicate or same-shape route for one method
      IllegalStateException - if configuration has ended
    • webSocket

      Application webSocket(String path, WebSocketHandler handler)
      Registers a WebSocket route on an HTTP/1.1 listener, before startup. Only a GET upgrade carrying a valid WebSocket handshake on this path becomes a session; ordinary requests to the path keep their normal routes, and an upgrade on any other path is still answered 501. The template follows the same syntax as a route path and may carry named parameters, which are matched but not exposed to the handler. A second registration for the same path shape is rejected.

      Registration is frozen by start() like route registration. A handler is shared by all sessions on the path and must be thread-safe; the transport owns each session and ends every one of them within the listener's shutdown grace period. The JDK-only API carries no Netty types.

      Parameters:
      path - absolute path template without query or fragment
      handler - shared, thread-safe session callbacks
      Returns:
      this application
      Throws:
      IllegalArgumentException - for an invalid template or a duplicate path shape
      IllegalStateException - after configuration has ended
    • notFound

      Application notFound(Handler handler)
      Customises the 404 answer for a path no template matches (and a recognized method; see recognizeMethods(java.lang.String...)) before startup, without middleware. The handler runs as the innermost step of the global middleware chain, with the status already set to 404, so ctx.json(body) and ctx.text(text) answer 404 and a returned null is a 404 without a body. It may return any Response, or throw: exceptions are mapped as for any handler, by error(java.lang.Class<E>, com.jsgalactic.axiom.context.ErrorHandler<? super E>) handlers or into a problem response. No route matched: ctx.route() throws and ctx.matchedRoute() is empty. Without a handler the answer is the application/problem+json 404. A second call replaces the first.
      Parameters:
      handler - shared, thread-safe handler
      Returns:
      this application
      Throws:
      IllegalStateException - if configuration has ended
    • methodNotAllowed

      Application methodNotAllowed(Handler handler)
      Customises the 405 answer for a path some template matches but none serves the method of, before startup. It behaves as notFound(com.jsgalactic.axiom.context.Handler) with the status preset to 405. The Allow header is always the router's list (see the method table above): it is set on the handler's response whatever the handler sets, so a custom answer cannot omit or contradict it. OPTIONS requests are never 405: they are answered automatically (see Context.automaticOptions()), so this handler never sees one.
      Parameters:
      handler - shared, thread-safe handler
      Returns:
      this application
      Throws:
      IllegalStateException - if configuration has ended
    • notImplemented

      Application notImplemented(Handler handler)
      Customises the 501 answer for an unrecognized method on a path no template matches, before startup. It behaves as notFound(com.jsgalactic.axiom.context.Handler) with the status preset to 501. CONNECT is answered 501 before routing and middleware and is not customised.
      Parameters:
      handler - shared, thread-safe handler
      Returns:
      this application
      Throws:
      IllegalStateException - if configuration has ended
    • recognizeMethods

      Application recognizeMethods(String... methods)
      Declares methods this application recognizes although no route has them, before startup. A request whose path matches no template is answered 404 for a recognized method and 501 for any other (RFC 9110 section 15.6.2). Recognized are the RFC 9110 methods, PATCH, every method registered on a route and the methods declared here, for example an extension a gateway or global middleware answers itself. Declaring a method changes nothing else: it is not added to any Allow header, and a request for it whose path matches a template is still 405. Repeated calls add to the set; a method already recognized is accepted.
      Parameters:
      methods - case-sensitive RFC 9110 method tokens
      Returns:
      this application
      Throws:
      IllegalArgumentException - for a method that is not a token or for CONNECT, which is always answered 501
      IllegalStateException - if configuration has ended
    • use

      Application use(Middleware middleware)
      Adds global middleware. It runs first for every route, and also wraps the answers the router produces itself (404, 405, automatic OPTIONS, 501 for an unrecognized method); for those, ctx.matchedRoute() is empty and ctx.route() throws IllegalStateException. Requests rejected before routing (413, CONNECT, listener errors) do not run middleware.
      Specified by:
      use in interface RouteGroup
      Parameters:
      middleware - shared, thread-safe middleware
      Returns:
      this application
      Throws:
      IllegalStateException - if configuration has ended
    • group

      Application group(String prefix, Consumer<RouteGroup> configure)
      Creates a top-level route group; see RouteGroup.group(String, Consumer).
      Specified by:
      group in interface RouteGroup
      Parameters:
      prefix - group path prefix, or empty for a group that only scopes middleware
      configure - registers the group's routes, middleware and nested groups
      Returns:
      this application
    • error

      <E extends Exception> Application error(Class<E> type, ErrorHandler<? super E> handler)
      Maps exceptions of a class and its subclasses to responses before startup. When a handler or middleware throws, the registered class nearest to the exception's class in its superclass chain wins, after every middleware has unwound; the response is then decorated by the middleware through Middleware.afterError(com.jsgalactic.axiom.context.Context, com.jsgalactic.axiom.http.Response). AxiomException keeps its built-in problem response unless a handler is registered for AxiomException or one of its subclasses: the built-in mapping counts as registered for AxiomException, so a handler for Exception does not replace it. Exceptions without a handler behave as described for handle(Request). Requests rejected before routing (413, CONNECT) and listener errors are not offered to handlers. Only exceptions can be mapped; Errors are never handled. Handlers do not run for a request that was cancelled (its thread interrupted) or whose deadline expired, and InterruptedException and CancellationException are never offered to them.
      Specified by:
      error in interface RouteGroup
      Type Parameters:
      E - exception type
      Parameters:
      type - exception class
      handler - shared, thread-safe mapping
      Returns:
      this application
      Throws:
      IllegalArgumentException - if a handler is already registered for the class
      IllegalStateException - if configuration has ended
    • routes

      List<Route> routes()
      Returns an immutable snapshot in registration order.
      Returns:
      an immutable snapshot in registration order
    • start

      Application start()
      Compiles routes, freezes registration, and enables in-memory execution without a listener. Repeated calls while running are harmless. A compilation failure leaves registration intact and the application in the configuring state. Startup also discovers body codecs once with ServiceLoader.
      Returns:
      this application
      Throws:
      IllegalArgumentException - if the route table cannot be compiled
      IllegalStateException - if closed, or if two installed codecs declare the same media type
    • requestTimeout

      Application requestTimeout(Duration timeout)
      Sets the request execution budget before startup. The default is ten seconds.
      Parameters:
      timeout - positive duration, at most one day
      Returns:
      this application
      Throws:
      IllegalStateException - after configuration has ended
    • requestTimeout

      Duration requestTimeout()
      Returns the configured execution budget.
      Returns:
      request timeout
    • maxRequestBody

      Application maxRequestBody(int bytes)
      Sets the largest accepted request body before startup. The default is 1 MiB (1,048,576 bytes). Bodies are buffered in memory before the handler runs. Larger requests receive 413 without invoking a handler: HTTP listeners reject a declared Content-Length before reading the body and stop reading a chunked body as soon as it exceeds the limit; in-memory calls and the test client check the body length. Zero rejects every non-empty body. The ceiling is deliberate: bodies are held in memory, and 64 MiB equals the default listener budget for request bodies in flight, so any permitted body fits it (see the body guide).
      Parameters:
      bytes - limit from zero to 64 MiB
      Returns:
      this application
      Throws:
      IllegalArgumentException - for a negative limit or one above 64 MiB
      IllegalStateException - after configuration has ended
    • maxRequestBody

      int maxRequestBody()
      Returns the configured request body limit.
      Returns:
      limit in bytes
    • admissionPolicy

      Application admissionPolicy(AdmissionPolicy policy)
      Sets the aggregate policy of the application-wide execution budget before startup. Every listener and test client of this application draws from the same counters, so this is the only aggregate admission bound. Defaults to reject(36). The aggregate also supplies the policy of routes without an override; this method leaves those overrides unchanged.
      Parameters:
      policy - immutable aggregate limits, also the default for routes without an override
      Returns:
      this application
      Throws:
      IllegalStateException - after configuration has ended
    • admissionPolicy

      AdmissionPolicy admissionPolicy()
      Returns the aggregate policy of the application-wide execution budget.
      Returns:
      configured aggregate policy
    • admissionPolicy

      Application admissionPolicy(Route route, AdmissionPolicy policy)
      Sets the bound of one registered route in the application-wide budget before startup. The aggregate bound still applies, and the route's override is shared by every listener and test client of this application.
      Parameters:
      route - registered route identity
      policy - complete route policy
      Returns:
      this application
      Throws:
      IllegalArgumentException - if the route is not registered
      IllegalStateException - after configuration has ended
    • admissionPolicy

      AdmissionPolicy admissionPolicy(Route route)
      Returns a registered route's bound in the application-wide budget, or the aggregate policy.
      Parameters:
      route - registered route identity
      Returns:
      effective route policy
      Throws:
      IllegalArgumentException - if the route is not registered
    • executionBudget

      Application executionBudget(ExecutionBudget budget)
      Installs the application-wide execution budget before startup. Every listener and test client of this application draws from one set of aggregate and route counters; the budget replaces both the aggregate policy and all route overrides.
      Parameters:
      budget - immutable aggregate limits and per-route overrides
      Returns:
      this application
      Throws:
      IllegalArgumentException - if an overridden route is not registered
      IllegalStateException - after configuration has ended
    • executionBudget

      ExecutionBudget executionBudget()
      Returns the application-wide execution budget, including its route overrides.
      Returns:
      configured budget
    • executionBudget

      Application executionBudget(Route route, AdmissionPolicy policy)
      Sets the bound of one registered route in the application-wide budget before startup. The aggregate bound still applies.
      Parameters:
      route - registered route identity
      policy - complete route policy
      Returns:
      this application
      Throws:
      IllegalArgumentException - if the route is not registered
      IllegalStateException - after configuration has ended
    • executionBudget

      AdmissionPolicy executionBudget(Route route)
      Returns a registered route's bound in the application-wide budget, or the aggregate policy.
      Parameters:
      route - registered route identity
      Returns:
      effective route policy
      Throws:
      IllegalArgumentException - if the route is not registered
    • streamPolicy

      Application streamPolicy(StreamPolicy policy)
      Sets the aggregate bound on active streams for each listener before startup. The default is StreamPolicy.reject(36). The bound also serves as the default for each route and is independent of request admission: a stream transfers its request slot into a stream slot, leaving request capacity for ordinary requests.
      Parameters:
      policy - immutable stream bound; also the default bound for each route
      Returns:
      this application
      Throws:
      IllegalStateException - after configuration has ended
    • streamPolicy

      StreamPolicy streamPolicy()
      Returns the aggregate stream bound.
      Returns:
      configured default stream policy
    • streamPolicy

      Application streamPolicy(Route route, StreamPolicy policy)
      Sets the bound on active streams for one registered route before startup. The aggregate bound still applies, so a stream is admitted only when both bounds have room.
      Parameters:
      route - registered route identity
      policy - complete stream policy for the route
      Returns:
      this application
      Throws:
      IllegalArgumentException - if the route is not registered
      IllegalStateException - after configuration has ended
    • streamPolicy

      StreamPolicy streamPolicy(Route route)
      Returns a registered route's stream override, or the default policy.
      Parameters:
      route - registered route identity
      Returns:
      effective stream policy
      Throws:
      IllegalArgumentException - if the route is not registered
    • describe

      Application describe(Route route, RouteDoc doc)
      Attaches documentation to a registered route before startup, replacing an earlier one. The description is plain data for tools such as an OpenAPI generator; it never affects routing or request handling. Routes without one are documented by method and path only.
      Parameters:
      route - registered route identity
      doc - route description
      Returns:
      this application
      Throws:
      IllegalArgumentException - if the route is not registered
      IllegalStateException - after configuration has ended
    • doc

      Optional<RouteDoc> doc(Route route)
      Returns the documentation attached to a route with describe(com.jsgalactic.axiom.routing.Route, com.jsgalactic.axiom.routing.RouteDoc). Readable at any time, also after startup and close.
      Parameters:
      route - registered route identity
      Returns:
      the description, empty if none was attached
      Throws:
      IllegalArgumentException - if the route is not registered
    • metrics

      Application metrics(Metrics metrics)
      Sets where listeners and the test client record request, latency and admission metrics, before startup. The default is Metrics.NOOP. Metrics cover requests that pass through admission; direct handle(Request) calls bypass admission and are not recorded.
      Parameters:
      metrics - thread-safe metrics implementation
      Returns:
      this application
      Throws:
      IllegalStateException - after configuration has ended
    • metrics

      Metrics metrics()
      Returns the configured metrics.
      Returns:
      metrics receiving the runtime's measurements
    • failureLog

      Application failureLog(System.Logger logger, System.Logger.Level level)
      Chooses where and at which level the runtime logs failures it answered, before startup. The default is the logger named com.jsgalactic.axiom.failures at System.Logger.Level.WARNING.

      Each request failure is logged at most once, with the request ID and the exception, and never reaches a response: a 5xx AxiomException answered by the built-in problem response, and an exception that an error handler mapped (including one it translated into an AxiomException), unless it is an AxiomException below 500 answered below 500, which is an expected client error and is not logged. A failing error handler is a defect of the application and is always logged at System.Logger.Level.ERROR on the same logger. Failures the listener answers itself are logged by the transport.

      Parameters:
      logger - destination, for example System.getLogger("audit")
      level - level of the entries; System.Logger.Level.OFF silences them
      Returns:
      this application
      Throws:
      IllegalArgumentException - if level is System.Logger.Level.ALL
      IllegalStateException - if configuration has ended
    • developmentErrors

      Application developmentErrors()
      Turns on development errors, before startup. Off by default, and there is no way to turn it on by configuration value: the application must call this method.

      Responses the runtime builds for failures (an AxiomException's problem response, the generic 500 of a failing error handler, and the 500 for an exception that nothing maps, which is otherwise thrown from handle(Request)) then carry an extra debug member in the problem document with the exception's class name, message, up to 64 stack frames and up to 8 causes. These can contain internal details and request content, which production responses never do. Responses built by error handlers are unchanged, and failures the listener answers itself have no exception to show.

      To make it impossible to expose this by accident, listen(int) refuses to bind an address that is not a loopback address while it is on, and a warning is logged when the application starts. A reverse proxy or tunnel in front of a loopback listener would still forward the details: do not use it there.

      Returns:
      this application
      Throws:
      IllegalStateException - if configuration has ended
    • resolve

      Optional<Route> resolve(Request request)
      Resolves a route identity without executing user code. Requires a running application.
      Parameters:
      request - request to match using the same precedence as handle
      Returns:
      matching method/template, or empty for 404/405
    • listen

      default Server listen(int port) throws IOException
      Starts this application and binds a loopback HTTP listener.
      Parameters:
      port - port, or zero to allocate an available port
      Returns:
      application-owned listener
      Throws:
      IOException - if binding fails; the application remains running
    • listen

      default Server listen(InetSocketAddress address) throws IOException
      Starts this application and binds an HTTP listener using the installed transport provider. Multiple listeners may share an application. Closing the application closes all listeners.
      Parameters:
      address - bind address
      Returns:
      application-owned listener
      Throws:
      IOException - if binding fails; the application remains running
      IllegalStateException - if closed or no unique transport provider is installed
    • listen

      Server listen(InetSocketAddress address, ListenerOptions options) throws IOException
      Starts this application and binds an HTTP listener with explicit limits and timeouts, such as the shutdown grace period or the connection cap. The options apply to this listener only.
      Parameters:
      address - bind address
      options - immutable listener options; see ListenerOptions.defaults()
      Returns:
      application-owned listener
      Throws:
      IOException - if binding fails; the application remains running
      IllegalStateException - if closed or no unique transport provider is installed
    • management

      Application management(ManagementOptions options)
      Opts in to a separate management listener, before startup. Off by default: an application that never calls this keeps a single listener and no diagnostics port. The listener is bound lazily with the first listen(int) call, not by this method.

      The management listener serves only the health probes of Health instances built for this application and a Prometheus text scrape of metrics(). It runs no application routes, middleware or user handlers. It is owned by this application: closing one application listener leaves it running, while closing the application closes it too. Use a loopback or private address; a wildcard bind needs ManagementOptions.Builder.allowWildcardBind.

      Parameters:
      options - immutable management settings
      Returns:
      this application
      Throws:
      IllegalArgumentException - if the options are invalid
      IllegalStateException - if configuration has ended
    • management

      Returns:
      the configured management settings, or empty when the listener is off
    • managementServer

      Optional<Server> managementServer()
      Returns the bound management listener, if one has started. Its address is useful when ManagementOptions.port() is zero.
      Returns:
      the application-owned management listener, or empty
    • managementHealth

      Application managementHealth(Health health)
      Framework hook used by Health to make its probes available on the management listener. Applications do not call this; building a Health for this application registers it automatically. At most ManagementOptions.MAX_HEALTH instances are kept, so diagnostics cannot grow without bound.
      Parameters:
      health - a health service built for this application
      Returns:
      this application
      Throws:
      IllegalStateException - if the application is closed or too many are registered
    • handle

      Response handle(Request request) throws Exception
      Executes a request synchronously on the calling thread with a fresh context. Selects the most specific complete path match (static, parameter, wildcard at the first differing segment) that is registered for the request method; a more specific template without that method does not hide a less specific one with it. HEAD uses an explicit HEAD route, or else the GET route of the same template, and suppresses response bodies; a successful HEAD response (2xx other than 204 and 205) instead carries Content-Length set to the encoded length of the body it would have had, and keeps a body the HTTP transport could not send, so that HEAD fails where GET would. Returns 404 for an unknown path (501 when the method is neither an RFC 9110 method, PATCH, nor registered on any route or declared with recognizeMethods(java.lang.String...)), and 405 when no matching template has the method, with an Allow header listing the methods of all matching templates (HEAD wherever GET is, and OPTIONS). An OPTIONS request that no matching template registered is answered 204 without invoking a handler, with that Allow list plus OPTIONS. OPTIONS * is answered 204 without route lookup, with an Allow list of every registered method (HEAD if GET is registered) plus OPTIONS. CONNECT is answered 501 without routing. Bodies over maxRequestBody() receive 413. Unknown paths, method mismatches and AxiomExceptions thrown by handlers or Context.body become application/problem+json responses with only status, code, request ID and violations. Responses of safe-method requests (GET, HEAD, OPTIONS, TRACE) whose Content-Type has an installed codec are checked against the request's Accept header (406 when nothing matches; other methods ignore Accept, so a 406 cannot follow a side effect) and non-String, non-byte[] bodies are encoded by that codec. Exceptions from handlers and middleware are first offered to the handlers registered with error(java.lang.Class<E>, com.jsgalactic.axiom.context.ErrorHandler<? super E>); a failing error handler produces the generic 500 problem response. Other handler exceptions propagate unchanged, unless developmentErrors() is on; this method is not a network error boundary.
      Parameters:
      request - request to execute
      Returns:
      mapped handler result
      Throws:
      Exception - if the handler fails
      IllegalStateException - unless running
    • handle

      Response handle(Request request, ExecutionContext execution) throws Exception
      Executes on the calling thread with explicit request identity and deadline metadata. Adapters own scheduling and cancellation. An expired context fails before invocation; synchronous calls do not interrupt the caller or enforce a timeout after invocation.
      Parameters:
      request - request to execute
      execution - execution metadata owned by the caller
      Returns:
      mapped response
      Throws:
      Exception - if the handler fails or the context is already expired
    • handle

      default Response handle(Request request, ExecutionContext execution, BodyReader reader) throws Exception
      Executes with an incremental body reader supplied by the caller. Adapters that receive a request body while the handler runs pass a reader here; Context.bodyReader() then returns it. A reader is valid until the handler returns and is closed by the caller when the exchange ends. Implementations that do not stream bodies delegate to handle(Request, ExecutionContext).
      Parameters:
      request - request to execute
      execution - execution metadata owned by the caller
      reader - incremental body reader, or null for the buffered path
      Returns:
      mapped response
      Throws:
      Exception - if the handler fails or the context is already expired
    • streamsBody

      default boolean streamsBody(Route route)
      Reports whether a route's handler was registered as a StreamingHandler, so that a transport can hand it body bytes as they arrive instead of buffering them first. Safe to call before and after startup; an unknown or unmatched route returns false.
      Parameters:
      route - registered route identity
      Returns:
      true when the route reads its body incrementally
    • state

      Returns the current lifecycle state.
      Returns:
      the current lifecycle state
    • closeOnJvmShutdown

      Application closeOnJvmShutdown()
      Opts in to closing this application when the JVM begins to shut down, for example on SIGTERM from a container runtime or SIGINT, or when the last non-daemon thread ends or System.exit is called. Without this call nothing closes the application on its own; Axiom never registers a hook unless asked.

      The hook calls close() and then waits for every listener to terminate, so the graceful drain described by Server.close() completes within each listener's shutdown grace period (see ListenerOptions.shutdownGrace()): queued requests are answered 503, running handlers finish, and the remaining ones are interrupted afterwards. The wait is bounded by the longest grace period of any listener plus five seconds, so a handler that ignores interruption cannot keep the JVM from exiting. Because the application is no longer Application.State.RUNNING from the moment it closes, a Health readiness probe reports DOWN; call Health.beginDrain() from your own hook earlier if load balancers need time to notice; closeOnJvmShutdown(Duration) does that wait for you.

      Idempotent: the hook is registered once. An explicit close() unregisters it. The hook runs alongside other shutdown hooks, in no defined order, and the JVM's logging may already be winding down.

      Returns:
      this application
      Throws:
      IllegalStateException - if the application is closed or the JVM is already shutting down
    • closeOnJvmShutdown

      Application closeOnJvmShutdown(Duration drainDelay)
      Like closeOnJvmShutdown(), but the hook first runs the actions registered with onDrain(java.lang.Runnable), which tell the outside world that this instance is going away (a Health readiness probe turns DOWN), then waits drainDelay so that a load balancer can notice and stop sending traffic, and only then closes the application and its listeners as described above. The wait is spent in the hook thread, so choose a delay well under the container's termination grace period, which also has to cover the listeners' own shutdown grace. If this method is called twice, the first call's delay is kept.
      Parameters:
      drainDelay - time between the drain actions and the close; zero for none, at most one hour
      Returns:
      this application
      Throws:
      IllegalArgumentException - if the delay is negative or longer than one hour
      IllegalStateException - if the application is closed or the JVM is already shutting down
    • onDrain

      Application onDrain(Runnable action)
      Registers an action that starts draining, such as Health.beginDrain() (which a Health registers on its own). It runs once, on the shutdown hook thread, at the start of the JVM shutdown hook of closeOnJvmShutdown(Duration), before the drain delay and before the application closes, and never when closeOnJvmShutdown() was not used. It must be quick and must not block; an exception it throws is logged and does not stop the other actions or the shutdown. Actions run in registration order.
      Parameters:
      action - what to run
      Returns:
      this application
      Throws:
      IllegalStateException - if the application is closed
    • onClose

      Application onClose(Runnable action)
      Registers an action that runs once when close() closes this application, after the dispatcher is retired and before owned listeners close. It is meant for resources the application owns, such as a gRPC server, that must stop with it. Actions run in registration order on the thread calling close; an exception is logged and does not stop the other actions.
      Parameters:
      action - what to run
      Returns:
      this application
      Throws:
      IllegalStateException - if the application is closed
    • close

      void close()
      Permanently rejects new requests. Already accepted requests may finish. Idempotent and nonblocking. Each owned listener starts the graceful drain described by Server.close(): queued requests are answered 503, running network handlers get a grace period before they are interrupted. In-memory handlers are not interrupted. Await each listener's termination to join shutdown.
      Specified by:
      close in interface AutoCloseable