Interface Application
- All Superinterfaces:
AutoCloseable,RouteGroup
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 | Registration | Path routed, method not registered there | Path not routed |
|---|---|---|---|
| GET, POST, PUT, PATCH, DELETE | shortcut or route(java.lang.String, java.lang.String, com.jsgalactic.axiom.context.Handler, com.jsgalactic.axiom.context.Middleware...) | 405 with Allow | 404 |
| HEAD | RouteGroup.head(java.lang.String, com.jsgalactic.axiom.context.Handler, com.jsgalactic.axiom.context.Middleware...) or the GET route of the same template |
405 with Allow | 404 |
| OPTIONS | RouteGroup.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 | |
| TRACE | refused | 405 with Allow | 404 |
| CONNECT | refused | 501 | |
| extension token, e.g. PROPFIND or QUERY | route(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 |
X-HTTP-Method-Override are ignored.-
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic enumApplication lifecycle; a closed application cannot be restarted. -
Method Summary
Modifier and TypeMethodDescriptionReturns the aggregate policy of the application-wide execution budget.admissionPolicy(AdmissionPolicy policy) Sets the aggregate policy of the application-wide execution budget before startup.admissionPolicy(Route route) Returns a registered route's bound in the application-wide budget, or the aggregate policy.admissionPolicy(Route route, AdmissionPolicy policy) Sets the bound of one registered route in the application-wide budget before startup.voidclose()Permanently rejects new requests.Opts in to closing this application when the JVM begins to shut down, for example onSIGTERMfrom a container runtime orSIGINT, or when the last non-daemon thread ends orSystem.exitis called.closeOnJvmShutdown(Duration drainDelay) LikecloseOnJvmShutdown(), but the hook first runs the actions registered withonDrain(java.lang.Runnable), which tell the outside world that this instance is going away (aHealthreadiness probe turns DOWN), then waitsdrainDelayso that a load balancer can notice and stop sending traffic, and only then closes the application and its listeners as described above.Attaches documentation to a registered route before startup, replacing an earlier one.Turns on development errors, before startup.Returns the documentation attached to a route withdescribe(com.jsgalactic.axiom.routing.Route, com.jsgalactic.axiom.routing.RouteDoc).<E extends Exception>
Applicationerror(Class<E> type, ErrorHandler<? super E> handler) Maps exceptions of a class and its subclasses to responses before startup.Returns the application-wide execution budget, including its route overrides.executionBudget(ExecutionBudget budget) Installs the application-wide execution budget before startup.executionBudget(Route route) Returns a registered route's bound in the application-wide budget, or the aggregate policy.executionBudget(Route route, AdmissionPolicy policy) Sets the bound of one registered route in the application-wide budget before startup.failureLog(System.Logger logger, System.Logger.Level level) Chooses where and at which level the runtime logs failures it answered, before startup.group(String prefix, Consumer<RouteGroup> configure) Creates a top-level route group; seeRouteGroup.group(String, Consumer).Executes a request synchronously on the calling thread with a fresh context.handle(Request request, ExecutionContext execution) Executes on the calling thread with explicit request identity and deadline metadata.default Responsehandle(Request request, ExecutionContext execution, BodyReader reader) Executes with an incremental body reader supplied by the caller.default Serverlisten(int port) Starts this application and binds a loopback HTTP listener.default Serverlisten(InetSocketAddress address) Starts this application and binds an HTTP listener using the installed transport provider.listen(InetSocketAddress address, ListenerOptions options) Starts this application and binds an HTTP listener with explicit limits and timeouts, such as the shutdown grace period or the connection cap.management(ManagementOptions options) Opts in to a separate management listener, before startup.managementHealth(Health health) Framework hook used byHealthto make its probes available on the management listener.Returns the bound management listener, if one has started.intReturns the configured request body limit.maxRequestBody(int bytes) Sets the largest accepted request body before startup.methodNotAllowed(Handler handler) Customises the 405 answer for a path some template matches but none serves the method of, before startup.metrics()Returns the configured metrics.Sets where listeners and the test client record request, latency and admission metrics, before startup.Customises the 404 answer for a path no template matches (and a recognized method; seerecognizeMethods(java.lang.String...)) before startup, without middleware.notImplemented(Handler handler) Customises the 501 answer for an unrecognized method on a path no template matches, before startup.Registers an action that runs once whenclose()closes this application, after the dispatcher is retired and before owned listeners close.Registers an action that starts draining, such asHealth.beginDrain()(which aHealthregisters on its own).recognizeMethods(String... methods) Declares methods this application recognizes although no route has them, before startup.Returns the configured execution budget.requestTimeout(Duration timeout) Sets the request execution budget before startup.Resolves a route identity without executing user code.route(String method, String path, Handler handler, Middleware... middleware) Registers a method/path template with optional route-level middleware.routes()Returns an immutable snapshot in registration order.start()Compiles routes, freezes registration, and enables in-memory execution without a listener.state()Returns the current lifecycle state.Returns the aggregate stream bound.streamPolicy(StreamPolicy policy) Sets the aggregate bound on active streams for each listener before startup.streamPolicy(Route route) Returns a registered route's stream override, or the default policy.streamPolicy(Route route, StreamPolicy policy) Sets the bound on active streams for one registered route before startup.default booleanstreamsBody(Route route) Reports whether a route's handler was registered as aStreamingHandler, so that a transport can hand it body bytes as they arrive instead of buffering them first.use(Middleware middleware) Adds global middleware.webSocket(String path, WebSocketHandler handler) Registers a WebSocket route on an HTTP/1.1 listener, before startup.
-
Method Details
-
route
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 ofA-Z a-z 0-9and!#$%&'*+-.^_`|~);getandGETare different methods. Extension methods such asPROPFINDorQUERYare registered here; there is noqueryshortcut while that method is still a draft. Only the request line's method is matched; method-override headers such asX-HTTP-Method-Overrideare 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:
routein interfaceRouteGroup- Parameters:
method- case-sensitive HTTP method tokenpath- absolute path template without query or fragmenthandler- callback invoked for matching requestsmiddleware- route-level middleware, outermost first; seeRouteGroup- Returns:
- the registered route identity
- Throws:
IllegalArgumentException- for a method that is not a token, forTRACE(whose echo of the request would expose credentials; TRACE requests are answered 405 or 404), forCONNECT(tunnels are not supported; CONNECT requests are answered 501), for an invalid template, or for a duplicate or same-shape route for one methodIllegalStateException- if configuration has ended
-
webSocket
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 fragmenthandler- shared, thread-safe session callbacks- Returns:
- this application
- Throws:
IllegalArgumentException- for an invalid template or a duplicate path shapeIllegalStateException- after configuration has ended
-
notFound
Customises the 404 answer for a path no template matches (and a recognized method; seerecognizeMethods(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, soctx.json(body)andctx.text(text)answer 404 and a returnednullis a 404 without a body. It may return anyResponse, or throw: exceptions are mapped as for any handler, byerror(java.lang.Class<E>, com.jsgalactic.axiom.context.ErrorHandler<? super E>)handlers or into a problem response. No route matched:ctx.route()throws andctx.matchedRoute()is empty. Without a handler the answer is theapplication/problem+json404. A second call replaces the first.- Parameters:
handler- shared, thread-safe handler- Returns:
- this application
- Throws:
IllegalStateException- if configuration has ended
-
methodNotAllowed
Customises the 405 answer for a path some template matches but none serves the method of, before startup. It behaves asnotFound(com.jsgalactic.axiom.context.Handler)with the status preset to 405. TheAllowheader 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 (seeContext.automaticOptions()), so this handler never sees one.- Parameters:
handler- shared, thread-safe handler- Returns:
- this application
- Throws:
IllegalStateException- if configuration has ended
-
notImplemented
Customises the 501 answer for an unrecognized method on a path no template matches, before startup. It behaves asnotFound(com.jsgalactic.axiom.context.Handler)with the status preset to 501.CONNECTis 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
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 anyAllowheader, 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 forCONNECT, which is always answered 501IllegalStateException- if configuration has ended
-
use
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 andctx.route()throwsIllegalStateException. Requests rejected before routing (413, CONNECT, listener errors) do not run middleware.- Specified by:
usein interfaceRouteGroup- Parameters:
middleware- shared, thread-safe middleware- Returns:
- this application
- Throws:
IllegalStateException- if configuration has ended
-
group
Creates a top-level route group; seeRouteGroup.group(String, Consumer).- Specified by:
groupin interfaceRouteGroup- Parameters:
prefix- group path prefix, or empty for a group that only scopes middlewareconfigure- registers the group's routes, middleware and nested groups- Returns:
- this application
-
error
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 throughMiddleware.afterError(com.jsgalactic.axiom.context.Context, com.jsgalactic.axiom.http.Response).AxiomExceptionkeeps its built-in problem response unless a handler is registered forAxiomExceptionor one of its subclasses: the built-in mapping counts as registered forAxiomException, so a handler forExceptiondoes not replace it. Exceptions without a handler behave as described forhandle(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, andInterruptedExceptionandCancellationExceptionare never offered to them.- Specified by:
errorin interfaceRouteGroup- Type Parameters:
E- exception type- Parameters:
type- exception classhandler- shared, thread-safe mapping- Returns:
- this application
- Throws:
IllegalArgumentException- if a handler is already registered for the classIllegalStateException- if configuration has ended
-
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 withServiceLoader.- Returns:
- this application
- Throws:
IllegalArgumentException- if the route table cannot be compiledIllegalStateException- if closed, or if two installed codecs declare the same media type
-
requestTimeout
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
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 MiBIllegalStateException- after configuration has ended
-
maxRequestBody
int maxRequestBody()Returns the configured request body limit.- Returns:
- limit in bytes
-
admissionPolicy
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
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 identitypolicy- complete route policy- Returns:
- this application
- Throws:
IllegalArgumentException- if the route is not registeredIllegalStateException- after configuration has ended
-
admissionPolicy
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
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 registeredIllegalStateException- after configuration has ended
-
executionBudget
ExecutionBudget executionBudget()Returns the application-wide execution budget, including its route overrides.- Returns:
- configured budget
-
executionBudget
Sets the bound of one registered route in the application-wide budget before startup. The aggregate bound still applies.- Parameters:
route- registered route identitypolicy- complete route policy- Returns:
- this application
- Throws:
IllegalArgumentException- if the route is not registeredIllegalStateException- after configuration has ended
-
executionBudget
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
Sets the aggregate bound on active streams for each listener before startup. The default isStreamPolicy.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
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 identitypolicy- complete stream policy for the route- Returns:
- this application
- Throws:
IllegalArgumentException- if the route is not registeredIllegalStateException- after configuration has ended
-
streamPolicy
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
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 identitydoc- route description- Returns:
- this application
- Throws:
IllegalArgumentException- if the route is not registeredIllegalStateException- after configuration has ended
-
doc
Returns the documentation attached to a route withdescribe(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
Sets where listeners and the test client record request, latency and admission metrics, before startup. The default isMetrics.NOOP. Metrics cover requests that pass through admission; directhandle(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
Chooses where and at which level the runtime logs failures it answered, before startup. The default is the logger namedcom.jsgalactic.axiom.failuresatSystem.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
AxiomExceptionanswered by the built-in problem response, and an exception that anerror handlermapped (including one it translated into anAxiomException), unless it is anAxiomExceptionbelow 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 atSystem.Logger.Level.ERRORon the same logger. Failures the listener answers itself are logged by the transport.- Parameters:
logger- destination, for exampleSystem.getLogger("audit")level- level of the entries;System.Logger.Level.OFFsilences them- Returns:
- this application
- Throws:
IllegalArgumentException- iflevelisSystem.Logger.Level.ALLIllegalStateException- 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 fromhandle(Request)) then carry an extradebugmember 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
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
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
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 runningIllegalStateException- if closed or no unique transport provider is installed
-
listen
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 addressoptions- immutable listener options; seeListenerOptions.defaults()- Returns:
- application-owned listener
- Throws:
IOException- if binding fails; the application remains runningIllegalStateException- if closed or no unique transport provider is installed
-
management
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 firstlisten(int)call, not by this method.The management listener serves only the health probes of
Healthinstances built for this application and a Prometheus text scrape ofmetrics(). 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 needsManagementOptions.Builder.allowWildcardBind.- Parameters:
options- immutable management settings- Returns:
- this application
- Throws:
IllegalArgumentException- if the options are invalidIllegalStateException- if configuration has ended
-
management
Optional<ManagementOptions> management()- Returns:
- the configured management settings, or empty when the listener is off
-
managementServer
Returns the bound management listener, if one has started. Its address is useful whenManagementOptions.port()is zero.- Returns:
- the application-owned management listener, or empty
-
managementHealth
Framework hook used byHealthto make its probes available on the management listener. Applications do not call this; building aHealthfor this application registers it automatically. At mostManagementOptions.MAX_HEALTHinstances 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
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 carriesContent-Lengthset 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 withrecognizeMethods(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 overmaxRequestBody()receive 413. Unknown paths, method mismatches andAxiomExceptions thrown by handlers orContext.bodybecomeapplication/problem+jsonresponses 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 witherror(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, unlessdevelopmentErrors()is on; this method is not a network error boundary.- Parameters:
request- request to execute- Returns:
- mapped handler result
- Throws:
Exception- if the handler failsIllegalStateException- unless running
-
handle
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 executeexecution- 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 tohandle(Request, ExecutionContext).- Parameters:
request- request to executeexecution- execution metadata owned by the callerreader- 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
Reports whether a route's handler was registered as aStreamingHandler, 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
Application.State 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 onSIGTERMfrom a container runtime orSIGINT, or when the last non-daemon thread ends orSystem.exitis 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 byServer.close()completes within each listener's shutdown grace period (seeListenerOptions.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 longerApplication.State.RUNNINGfrom the moment it closes, aHealthreadiness probe reports DOWN; callHealth.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
LikecloseOnJvmShutdown(), but the hook first runs the actions registered withonDrain(java.lang.Runnable), which tell the outside world that this instance is going away (aHealthreadiness probe turns DOWN), then waitsdrainDelayso 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 hourIllegalStateException- if the application is closed or the JVM is already shutting down
-
onDrain
Registers an action that starts draining, such asHealth.beginDrain()(which aHealthregisters on its own). It runs once, on the shutdown hook thread, at the start of the JVM shutdown hook ofcloseOnJvmShutdown(Duration), before the drain delay and before the application closes, and never whencloseOnJvmShutdown()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
Registers an action that runs once whenclose()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 byServer.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:
closein interfaceAutoCloseable
-