π Rust Microservice Macros
A procedural macro crate designed to power the
rust_microservice
ecosystem with compile-time server generation, automatic controller
discovery, OpenAPI integration, authentication enforcement, and
database injection.
This crate eliminates runtime registration patterns by generating deterministic, compile-time server bootstrap logic.
π― Design Goals
- β Zero runtime reflection
- β Compile-time controller discovery
- β Deterministic OpenAPI generation
- β Integrated JWT security middleware
- β Declarative database injection
- β Strict compile-time validation
All routing, OpenAPI metadata, middleware wrapping, and database bindings are generated at compile time using Rustβs procedural macro system.
ποΈ Architecture Overview
This crate is implemented using:
proc_macroproc_macro2syn(AST parsing)quote(token generation)walkdir(controller discovery)
Macro Expansion Pipeline
- Parse attribute arguments (
key = valuepairs) - Parse annotated Rust items (
ItemFn, modules, etc.) - Load and inspect controller files
- Extract Actix-Web handlers
- Generate:
- Server bootstrap
- Route registration
- Swagger/OpenAPI specification
- JWT middleware wrappers
- Database injection logic
No runtime route aggregation occurs β all handlers are resolved during compilation.
π§© Provided Macros
This crate exposes three primary procedural attribute macros:
#[api_server]#[secured]#[database]
π #[api_server]
Generates the full HTTP server bootstrap and controller registration
logic for an actix-web application.
Responsibilities
- Recursively scans controller directories
- Registers all HTTP handlers
- Generates Swagger UI configuration
- Generates OpenAPI documentation using
utoipa - Optionally initializes database connections
- Wraps the main function with
#[tokio::main] - Initializes and runs the global
Server
Supported Attributes
| Attribute | Type | Description |
|---|---|---|
controllers_path |
&str |
Comma-separated directories containing controllers |
openapi_title |
&str |
OpenAPI title |
openapi_api_name |
&str |
OpenAPI tag name |
openapi_api_description |
&str |
OpenAPI tag description |
openapi_auth_server |
&str |
OAuth2 token URL fallback |
database |
"true" / "false" |
Enables SeaORM database initialization |
banner |
&str |
Startup banner printed during server initialization |
Example
use ServerApi; // api_server was renamed to ServerApi for better ergonomics
async
β οΈ IMPORTANT: The server_api (ServerApi in rust_microservice), database and secured
macros has been renamed or re-exported to improve ergonomics in the rust_microservice crate.
This crate provides only the macro implementation. The public API is re-exported by the
rust_microservice crate. Therefore, when using the macro in your project, prefer ServerApi
instead of api_server.
Generated Behavior
- Wraps your function with
#[tokio::main] - Discovers all Actix-Web handlers
- Generates:
register_endpointsApiDoc(utoipa::OpenApi)- Swagger UI endpoint
/swagger-ui/*
π #[secured]
Protects an Actix-Web endpoint with JWT authentication and role-based authorization.
Internally generates:
- A middleware module
- A wrapper using
actix_web::middleware::from_fn - Automatic role validation via
Server::validate_jwt
Supported Attributes
| Attribute | Description |
|---|---|
method |
HTTP method (get, post, etc.) |
path |
Route path |
authorize |
Role expression |
Authorization Formats
Single Role
authorize = "ROLE_ADMIN"
Any Role
authorize = "hasAnyRole(ROLE_ADMIN, ROLE_USER)"
All Roles
authorize = "hasAllRoles(ROLE_ADMIN, ROLE_AUDITOR)"
Example
use secured;
use HttpResponse;
pub async
Security Validation
The middleware validates:
- JWT presence
- Signature
- Expiration (
exp) - Issuer (
iss) - Required roles
If validation fails β 401 Unauthorized.
π’οΈ #[database]
Injects a SeaORM DatabaseConnection into a repository function.
Required Attributes
| Attribute | Description |
|---|---|
name |
Database configuration name |
error |
Error variant returned if connection is unavailable |
The macro injects:
let db = global
.database_with_name?;
Example
use database;
pub async
π Controller Discovery
The api_server macro:
- Traverses
controllers_path - Parses each
.rsfile usingsyn - Extracts functions annotated with:
#[get]
#[post]
#[put]
#[delete]
#[patch]
#[head]
#[options]
#[trace]
#[connect]
#[secured]
These handlers are automatically registered into
actix_web::web::ServiceConfig.
π OpenAPI Generation
Uses utoipa to generate:
#[derive(OpenApi)]- Swagger UI configuration
- OAuth2 security scheme
- Global security requirements
The security scheme is dynamically configured from:
global?.settings.get_auth2_token_url
βοΈ Internal Utility Structures
KeyValue
Parses:
key = value
ArgList
Parses:
key1 = value1, key2 = value2
These power all attribute parsing in this crate.
π§ Compile-Time Guarantees
- Controllers must be valid Rust modules
- Handlers must use supported HTTP attributes
- Database names must exist at runtime
- Invalid macro parameters cause compile errors
π§ͺ Runtime Integration
Although this crate generates compile-time code, runtime behavior depends on:
actix-webtokioutoipasea-ormrust_microservice::Server
π Summary
This macro crate transforms a modular Rust project into a fully initialized HTTP API server with:
- Automatic route wiring
- JWT security enforcement
- OpenAPI documentation
- Swagger UI
- Database injection
All achieved with minimal boilerplate and strict compile-time guarantees.
π¦ Built for high-performance Rust microservices. Deterministic. Secure. Compile-time powered.