A3S Boot
Overview
A3S Boot is a progressive Rust web framework crate for building modular A3S services. It takes the architectural ideas that make Nest.js useful for growing services and expresses them in explicit, idiomatic Rust:
- explicit application modules
- importable feature modules
- typed providers resolved through
ModuleRef - controller route groups
- framework-neutral route definitions and requests
- global, controller-level, and route-level pipes, guards, interceptors, and exception filters
- typed JSON DTO helpers for controller inputs and responses
- replaceable HTTP adapters
- a single application builder
- startup and shutdown module lifecycle hooks
Rust does not have TypeScript's runtime decorator metadata model. A3S Boot
supports Nest-style Rust attribute macros through a3s-boot-macros, and those
macros expand at compile time into the same explicit module, provider, and
controller definitions used by the core API. Axum is the default adapter, not
the framework kernel. If you are coming from Nest.js, see
Nest-Style Attribute Macros for the
@Injectable and @Controller style. See ROADMAP.md for the
Nest parity development plan.
Status
This repository contains the first framework slice:
Modulefor declaring imports, providers, controllers, direct routes, and lifecycle hooksModuleReffor typed provider lookup, optional lookup, presence checks, and token listingProviderDefinitionfor singleton, factory, and sharedArcfactory providersControllerDefinitionfor prefix-based route groupsa3s-boot-macroswith#[injectable],#[controller], and route attributes such as#[get("/{id}")],#[post("/", status = 201)], and#[sse("/events")]Pipe,Guard,Interceptor, andExceptionFilterpipeline traits- application-level
use_global_pipe,use_global_guard,use_global_interceptor, anduse_global_filter - exception filters that can recover errors from pipes, guards, handlers, and interceptors and decline to the next filter
BootRequest::text,json,with_text,with_json,BootResponse::json, and controller*_json/*_json_with_statusroute helpersBootResponse::text_with_status(...),json_with_status(...),sse(...),body_text(...),body_json(...),from_error(...),empty(...), andno_content()response helpers, redirect helpers, response body helpers, response status predicates, and response validationSseEventand streamingtext/event-streamroute helpers for Nest-style SSE- JSON request content-type and response accept helpers with HTTP 415/406 mapping
- request authorization/cookie helpers, HTTP 401 unauthorized mapping, and
opt-in
WWW-Authenticateresponse challenges - route helpers for GET/POST/PUT/PATCH/DELETE/OPTIONS/HEAD and JSON responses
HttpMethodcanonical display names and strict parsing for supported methods- percent-decoded path params through
{id}route segments, including typed path and query DTOs - case-insensitive request and response header lookup, plus content-type and strict content-length helpers
- application-level
global_prefix(...)route prefixing BootErrorHTTP status and response-message helpers for custom adaptersHttpAdapterfor plugging in different HTTP backends without coupling core to AxumAxumAdapterbehind the defaultaxumfeatureBootApplicationBuilderfor resolving module imports, providers, controllers, and routesBootApplication::call(...)andhandle(...)for framework-neutral in-process request dispatch,route_for(...)androute_match(...)for route lookup, andallowed_methods(...)/allowed_methods_header(...)for adapter method introspection- duplicate module deduplication by module name
- duplicate route rejection by HTTP method and path shape
- framework-neutral route registration
- route calls validate HTTP method and path pattern before executing handlers
- route matching preserves exact path segment shape, including trailing slashes, and prefers more specific static routes over parameter routes
- Axum requests preserve the real client HTTP method before route execution
- Axum routes register exact methods, so GET does not implicitly expose HEAD
- Axum HEAD responses preserve status and headers while sending an empty body
- Axum route registration normalizes parameter names so different methods can share the same dynamic path shape
- Axum unmatched paths map to Boot-style HTTP 404 responses
- Axum method-not-allowed paths map to Boot-style HTTP 405 responses while
preserving exact Boot
Allowvalues and route filters - Axum body limit failures, including oversized
Content-Lengthdeclarations, map to HTTP 413 Payload Too Large BootApplication::bootstrap,shutdown, andserve_with(...)lifecycle entrypointsserve_with(...)runs bootstrap before the adapter and shutdown after the adapter returns, including bootstrap and adapter errors
Quick Start
[]
= "0.1"
= { = "1", = ["macros", "rt-multi-thread"] }
use ;
;
;
async
Run the example:
Nest-Style Attribute Macros
The default a3s-boot features include a3s-boot-macros, so applications can
write Rust attributes that feel close to Nest.js decorators:
| Nest.js decorator | A3S Boot attribute macro |
|---|---|
@Injectable() |
#[injectable] on a service struct |
@Controller("cats") |
#[controller("/cats")] on an inherent impl block |
@Get(":id") |
#[get("/{id}")] on an async method |
@Post() |
#[post("/", status = 201)] on an async method |
@Sse("events") |
#[sse("/events")] on an async method returning an SSE event stream |
| Constructor injection | Resolve dependencies from ModuleRef, store them in the controller, then call Arc<Self>.controller()? |
@Module({ providers, controllers, imports }) |
impl Module with providers(), controllers(), and imports() |
These are Rust procedural macros, not TypeScript runtime decorators. They
generate ordinary ProviderDefinition and ControllerDefinition values at
compile time. The explicit API remains available and is what the macros expand
into:
use Arc;
use ;
use ;
;
;
async
#[injectable] adds provider helper methods such as into_provider() and
from_arc_provider(...). #[controller("/cats")] adds a
controller(self: Arc<Self>) method that collects route attributes from the
impl block. GET, POST, PUT, PATCH, and DELETE route attributes default to JSON:
#[get] and #[delete] can accept BootRequest and return serializable DTOs,
while #[post], #[put], and #[patch] accept one JSON DTO argument and
return a serializable DTO. Add raw only when the method should return
Result<BootResponse> directly, for example #[get("/health", raw)]. The
explicit *_json route attributes remain available as compatibility aliases,
but typical code should use #[get] and #[post] directly.
#[sse("/events")] registers a GET endpoint that returns a
text/event-stream response and accepts any stream whose items are
Result<SseEvent>.
Server-Sent Events
SSE routes mirror Nest.js @Sse() endpoints: handlers return a stream of
SseEvent values, and Boot sends them as text/event-stream chunks through the
selected adapter. SseEvent::stream(...) is a small helper for finite streams;
long-running handlers can return any Stream<Item = Result<SseEvent>>.
use ;
SSE routes require clients to accept text/event-stream; missing Accept,
*/*, text/*, and text/event-stream are accepted, while requests that only
accept unrelated media types return BootError::NotAcceptable.
Providers
Providers can be registered as owned singletons, factories, shared Arc<T>
values, or factories that return Arc<T>. Provider tokens are unique across the
resolved module graph:
use Arc;
use ;
;
let providers = vec!;
JSON DTOs
Controllers can accept typed request DTOs and return serializable response DTOs without manually parsing request bytes:
use ;
use ;
JSON body route helpers require a JSON-compatible request content type such as
application/json or application/*+json; missing or non-JSON content types map
to BootError::UnsupportedMediaType and HTTP 415. JSON response route helpers
honor Accept: requests with no Accept header, application/json,
concrete application/*+json types such as application/problem+json,
application/*, application/*+json, or */* can receive JSON; requests that
explicitly exclude JSON map to BootError::NotAcceptable and HTTP 406. Invalid
JSON and invalid UTF-8 text bodies map to BootError::BadRequest; adapters can
turn those into HTTP 400 while exception filters can override the response
shape. Manual handlers can use request.json() when they only want to parse
bytes, request.json_with_content_type() when they want the same content-type
check, and request.require_accepts_json() before returning JSON from custom
handlers. Use *_json_with_status(path, status, handler) on
ControllerDefinition or RouteDefinition when the helper should still parse
and serialize DTOs but return a non-200 status such as 201 or 202.
Empty status responses can use a dedicated helper instead of constructing an
empty byte vector, and text or JSON responses can set a status code while
preserving the right content type. In-process callers can decode response bodies
with body_text() and body_json(), or check status classes with helpers like
is_success() and is_client_error(). They can also check has_body() and
allows_body() or call validate() before handing a response to an adapter.
validate() runs status-code, Content-Length, no-body status, and response
header name/value checks in adapter order; the individual validate_status(),
validate_content_length(), validate_body_allowed(), and validate_headers()
helpers remain available for focused checks. Error responses can reuse the framework's standard HTTP error
mapping:
use ;
GET and DELETE helpers can also serialize response DTOs while still exposing the request for params, query values, and headers:
use ;
use Serialize;
Params And Query
Boot keeps route params adapter-neutral. Use whole {name} segments in routes
and read decoded values from BootRequest one at a time or as a typed DTO;
query strings can be read as raw single values, repeated values, or decoded into
a typed DTO. Parameter names must be non-empty, well-formed, and unique after
controller and global prefixes are applied. Route definitions and prefixes are
path-only and reject query or fragment markers; read query values from the
request instead. Invalid percent encoding and invalid UTF-8 in decoded params or
query values map to BootError::BadRequest. Prefer query_value(...) and
query_values(...) when the handler should reject malformed query strings; use
query_pairs(...) when the handler or adapter needs every decoded query pair,
including repeated keys.
Route definitions can also be inspected without executing handlers via
matches_path(...), path_params(...), path_shape(...), and
path_param_names(...).
use ;
use Deserialize;
Global Prefix And Headers
Use an application prefix when an adapter should expose every route under a shared base path:
use ;
Header helpers normalize names for storage and lookup:
use ;
let request = new
.with_content_type
.with_body
.with_content_length
.with_header
.with_header
.append_header
.append_header;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
request.validate_headers.unwrap;
request.validate_content_length.unwrap;
request.validate_body_limit.unwrap;
request.validate.unwrap;
request.validate_with_body_limit.unwrap;
assert!;
assert!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert!;
let response = new
.with_content_type
.with_content_length
.with_location
.append_header
.append_header;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
response.validate_content_length.unwrap;
assert_eq!;
assert!;
let unauthorized = empty
.with_www_authenticate
.append_www_authenticate;
assert_eq!;
assert_eq!;
The Axum adapter rejects request header values that cannot be represented as
text and reports them as BootError::BadRequest; invalid Content-Length
headers are also rejected as bad requests, repeated Content-Length values
must agree, declared lengths must match the decoded body length, and values
above the configured body limit map to HTTP 413 before the body is read.
The same request header, strict repeated-header, and body-length checks are
available in core via BootRequest::validate_headers(),
BootRequest::strict_content_length(), BootRequest::validate_content_length(),
BootRequest::validate_body_limit(...), BootRequest::validate(), and
BootRequest::validate_with_body_limit(...). Use validate() for header and
Content-Length checks, or validate_with_body_limit(...) when an adapter also
needs body-limit enforcement after reading the body. Use header_entries() on
requests and responses when an adapter needs to forward every stored header
line, including appended repeated headers. Request and response accessors such
as method(), path(), status(), body(), and into_body() let adapters
read common fields without depending on struct fields directly. Response-side
checks are available through BootResponse::strict_content_length() and
BootResponse::validate_content_length().
Invalid response status codes or headers are reported as internal adapter
errors instead of being silently dropped; adapters can reuse
BootResponse::validate() for the same status-code, Content-Length, no-body
status, and response header checks. Response Content-Length values must also
be valid, consistent, and match the response body length, and statuses that
cannot carry a body reject non-empty response bodies. Unsupported HTTP
methods are rejected as method-not-allowed errors instead of being remapped to
GET.
Replace The HTTP Backend
The core crate depends on the HttpAdapter trait, not on Axum. Axum is the
first adapter because it is a strong default for async Rust services, but a
Boot application can be served by any backend that can translate Boot routes,
requests, and responses.
Disable the default adapter when you only want the framework-neutral core:
[]
= { = "0.1", = false }
Implement an adapter for another HTTP stack, test harness, in-process gateway,
or custom runtime. In-process callers can also dispatch through the resolved
route table with BootApplication::call(...) or handle(...), reusing route
matching, parameter decoding, pipeline hooks, and exception filters. call(...)
returns unhandled BootErrors while handle(...) converts them to
BootResponse::from_error(...). Individual route snapshots expose the same
call(...) and handle(...) split for direct dispatch after an adapter has
selected a route. Custom adapters can
also query BootApplication::route_for(...), route_match(...), and
BootApplication::allowed_methods(...) from the same most-specific path
matching rules. allowed_methods_header(...) returns the corresponding
comma-separated Allow header value when a path matches. Adapters can build
method-not-allowed responses and use
BootResponse::from_error(...) or BootError::http_status_code(...) plus
http_response_message(...) for consistent error responses. Route snapshots
also expose resolved path shape, path parameter names, module metadata, and
controller metadata for adapter registration, logging, and diagnostics. When an
adapter has an actual request path, route_match(...) returns the selected
route plus decoded path parameter values with the same bad-request semantics as
route execution:
use SocketAddr;
use ;
;
Design Direction
A3S Boot aims to provide a structured service framework for A3S components:
| Concept | Direction |
|---|---|
| Module | A named feature boundary with imports, providers, and routes |
| ModuleRef | Typed provider container used by controllers and hosts |
| HTTP adapter | Replaceable backend adapter; Axum is the first implementation |
| Controller | Typed request handlers grouped by route prefix |
| Provider | Injectable service or repository dependency |
| Guard | Request authorization and policy gate |
| Interceptor | Cross-cutting request/response behavior at global, controller, or route scope |
| Pipe | Request validation and transformation |
| Filter | Error mapping into HTTP responses |
| Lifecycle hook | Startup and shutdown behavior for modules and providers |
The design is intentionally progressive: a small service can start with direct routes, then move into modules, providers, controllers, and request pipelines as the codebase grows. The framework core remains independent from any specific HTTP backend so A3S Gateway, A3S Code services, and standalone control-plane APIs can choose their adapter.
Source Layout
The crate is split by framework concern:
src/
├── adapters/ # Optional backend adapters such as Axum
├── app/ # Application instance, builder, and module registration
├── http/ # Adapter-neutral request, response, methods, and query parsing
├── module/ # Module trait and lifecycle hooks
├── pipeline/ # Pipes, guards, interceptors, filters, and execution context
├── provider/ # Provider tokens, definitions, and ModuleRef container
├── routing/ # Route handlers, controllers, route execution, and path matching
├── error.rs
└── lib.rs
lib.rs only exports the public surface. Behavior tests live under tests/
and exercise the crate through public APIs.
Development
License
MIT