Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
RoboTech-RS
RoboTech-RS is a microservice framework written in Rust for backend service development. This project provides core components for RESTful API development, including controller layer, business logic layer, data access layer, and extensive infrastructure tools, significantly simplifying the complexity of developing Rust backend services.
Project Structure
src/
├── api_client/ # API Client (optional feature: api-client)
│ # HTTP client wrapper for microservice communication
├── app/ # Application configuration management (feature: app)
│ # Config file loading, application context
├── cfg/ # Configuration module (feature: app)
│ # Supports TOML/YAML/JSON config formats
├── cst/ # Constants definition
│ # Global constants and enums
├── dao/ # Data Access Object (feature: db)
│ ├── eo/ # Entity Object - Database entity mapping
│ # Based on SeaORM Entity encapsulation
│ ├── dao_error.rs # DAO error handling
│ └── dao_utils.rs # DAO utility functions
│ # Generic CRUD operation wrappers
├── db/ # Database connection and migration (feature: db)
│ # Connection pool management, migration execution
├── env/ # Environment variable management (feature: app)
│ # Environment variable reading and validation
├── log/ # Logging system (feature: app)
│ # Structured logging with file rotation
├── macros/ # Macro definitions (feature: macros)
│ # Development helper macros
├── ro/ # Response Object
│ # Unified API response format
├── signal/ # Signal handling (feature: app)
│ # SIGTERM/SIGKILL graceful shutdown support
├── svc/ # Business logic layer (feature: app)
│ # Base service logic templates
└── web/ # Web server (feature: web)
├── cors/ # CORS middleware
├── ctrl/ # Controller base class
│ # BaseController for generic HTTP handling
├── health_check/ # Health check endpoint
├── https/ # HTTPS/TLS support
├── middleware/ # Middleware collection
│ # Request logging, auth, rate limiting
└── server/ # Web server core
# Axum server wrapper, multi-port listening
Feature Flags Mechanism
This project organizes functional modules through Rust's feature flags mechanism for on-demand loading and dependency optimization:
app: Application configuration management, including logging, configuration, environment variables, signal handlingweb: Web server implementation based on Axum (depends onapp), supports HTTPS, CORS, middlewaredb: Database operations based on SeaORM (depends onapp), provides DAO pattern encapsulationmacros: Macro definitions for development simplificationapi-client: HTTP client wrapper for inter-service communication
Note: Both web and db depend on app feature, meaning enabling them automatically includes app functionality.
Tech Stack
Core Framework
- Rust 2024 Edition: Modern systems programming language ensuring memory safety and zero-cost abstractions
- Axum: Ergonomic web framework in Tokio ecosystem, high performance and ergonomic
- Tokio: Async runtime providing high-concurrency processing capabilities
- SeaORM: Async ORM framework with type safety and compile-time SQL verification
Configuration & Serialization
- Serde: Serialization/deserialization framework
- Config: Multi-layer configuration management (files, env vars, CLI args)
- Validator: Data validation framework
- Chrono: Date and time processing
- Derive Setters / Typed Builder: Builder pattern constructors
Logging & Monitoring
- Tracing Ecosystem: Structured logging with JSON output
tracing-subscriber: Log subscriber and filterstracing-appender: File output and log rotationtracing-log: Compatibility withlogcrate
- Notify: File system events for config hot-reload
API Documentation
- Utoipa: OpenAPI 3.0 documentation generation
- Utoipa-Swagger-UI: Interactive API documentation UI
Networking & Security
- Tower / Tower-HTTP: Middleware collection (CORS, tracing, static files)
- Tokio-Rustls + AWS-LC-RS: TLS encryption support
- IPNet: IP address and subnet handling
- Reqwest: HTTP client
Database
- SQLx: Compile-time SQL verification
- SeaORM: Async ORM supporting MySQL and PostgreSQL
- Regex: Regular expression matching
- Once Cell: Lazy initialization global state
Utilities
- Anyhow: Error handling framework
- Thiserror: Custom error types
- Linkme: In-memory allocator
- Nix: Unix API wrapper
- Socket2: Socket API wrapper
- IdWorker: Distributed unique ID generation
- Wheel-RS: Internal通用 utility library
Internal Dependencies
- robotech-macros: Internal macro library for development acceleration
Feature Flags
This project uses feature flags to control dependencies and functional modules for on-demand loading and reduced binary size:
Core Features
| Feature | Description | Dependencies | Default |
|---|---|---|---|
app |
App config, logging, env vars, signals | - | ❌ |
web |
Web server (includes app) |
app, axum, tower |
❌ |
db |
Database operations (includes app) |
app, sea-orm, sqlx |
❌ |
macros |
Macro definitions | - | ❌ |
api-client |
HTTP client | reqwest |
❌ |
Recommended Combinations
Minimal API Service (smallest combination):
[]
= "1.5.1"
= ["app"]
Full Web Service + Database:
[]
= "1.5.1"
= ["web", "db", "macros"]
Microservice Scenario (with client):
[]
= "1.5.1"
= ["web", "db", "macros", "api-client"]
Core Features
1. Unified API Response Format
All API responses follow a unified structure for easy frontend parsing:
Field Descriptions:
result: Response result code (Success=1, Fail=-1, etc.)msg: Response message prompttimestamp: Timestamp in millisecondsextra: Extended data fielddetail: Detailed information (lists, pagination, etc.)code: Business code (for internationalization)
Usage Example:
use ;
// Success response
ROsuccess.finish
// Response with details
ROsuccess.detail.finish
// Error response
ROillegal_argument.finish
2. BaseDAO Data Access Layer
Provides generic CRUD operations, drastically reducing repetitive code:
Core Functions:
create: Create recordupdate: Update recorddelete_by_id: Delete by IDget_by_id: Get by IDlist: List all recordspage_list: Paginated queryexists: Check if record exists
Usage Example:
use BaseDAO;
use EntityTrait;
;
// Auto-generate CRUD methods
impl_base_dao!;
// Usage
let entity = create.await?;
let list = list.await?;
let page = page_list.await?;
3. BaseController Controller Layer
Provides HTTP request handling base class for simplified routing control:
Core Functions:
- Unified exception handling and error conversion
- Automatic response wrapping in RO format
- Built-in middleware support
- Common middleware like CORS, auth, rate limiting out-of-the-box
Usage Example:
use BaseController;
;
4. Configuration Management System
Supports multi-layer configuration priority: CLI args > Environment variables > Config file > Defaults
Configuration Loading Flow:
- Load config file on startup (TOML/YAML/JSON)
- Override with environment variables
- CLI args have highest priority
- Auto hot-reload when config file changes
Usage Example:
use build_app_cfg;
// Load configuration
let config = ?;
// Watch for config changes
watch_cfg_file!;
5. Logging System
Structured logging based on Tracing framework, production-ready out-of-the-box:
Core Functions:
- Multiple output sources (console, file)
- Log rotation (by size, by time)
- JSON format output (for ELK/Loki collection)
- Dynamic log level adjustment
- Call chain tracing (span/span tree)
Usage Example:
use init_log;
// Initialize logging
init_log?;
// Basic logging
info!;
debug!;
warn!;
error!;
// Span tracing
instrument
async
6. Database Connection & Migration
Automatically manages database connection pool and executes migrations:
Core Functions:
- Connection pool management (max/min connections)
- Automatic migration execution (upgrade DB schema on startup)
- SQL query logging
- Transaction support
Usage Example:
use init_db_conn;
// Initialize database connection
init_db_conn.await?;
// Auto migration
db_migrate!;
// Query
let entities = find.all.await?;
7. Signal Handling & Graceful Shutdown
Supports Unix signals for graceful shutdown:
Supported Signals:
SIGTERM(15): Graceful shutdownSIGINT(2): InterruptSIGUSR1/USR2: Custom handling
Signal Commands:
start: Default, sends SIGCONT to check if already runningrestart: Sends SIGTERM to stop old process, then starts new onestop/s: Sends SIGTERM for graceful shutdownkill/k: Sends SIGKILL for forced termination
Usage Example:
use SignalManager;
let = new?;
let receiver = mgr.watch_signal?;
// Wait for signal and gracefully close
wait_app_exit.await?
8. Middleware System
Built-in common middleware:
| Middleware | Function | Description |
|---|---|---|
| CORS | Cross-origin resource sharing | Custom domains, methods, headers |
| Trace | Request tracing | Log request duration, status code |
| IpFilter | IP filtering | Whitelist/blacklist support |
| Health Check | Health monitoring | /health endpoint |
| Auth | Authentication | JWT/OAuth2 (customizable) |
Adding Middleware:
use ServiceBuilder;
use TraceLayer;
let app = new
.route
.layer
.layer;
Quick Start
Prerequisites
- Rust 1.75+ (2024 Edition)
- PostgreSQL 12+ or MySQL 8.0+ (if using database)
- Redis (optional, for caching)
Step 1: Create Project
Step 2: Add Dependencies
# Cargo.toml
[]
= { = "1.5.1", = ["web", "db", "macros"] }
= { = "1", = ["full"] }
Step 3: Write Code
// main.rs
use AppConfig;
use init_db_conn;
use start_web_server;
use ;
async
Step 4: Configure Database
Create database and user:
-- PostgreSQL
;
;
-- MySQL
@'%' IDENTIFIED BY 'mypassword';
;
ALL PRIVILEGES ON mydb.* TO 'myuser'@'%';
Step 5: Run Service
# Development mode
# Specify config file
# Release mode
Access Swagger UI: http://localhost:9840/swagger-ui/
Quick Start
Prerequisites
- Rust 1.70 or higher
- PostgreSQL database (if using SeaORM)
Build Project
# Build with default features (api_client)
# Build with web server features
# Build with all features
Run Service
# Run service (requires web feature)
# Run service with database support
Core Concepts
RO (Response Object) - Response Object
All API responses are wrapped through RO structure, ensuring consistent return format.
BaseDAO - Data Access Base Class
Generic encapsulation of common CRUD operations, enabling complete data access layer with just a few lines of code.
EO (Entity Object) - Entity Object
Database table mapping via SeaORM Entity, auto-generated by robotech-macros.
DTO/VO - Data Transfer/View Objects
- DTO (Data Transfer Object): Receive request parameters from frontend
- VO (View Object): Data structures returned to frontend
Service - Business Logic Layer
Inherit BaseSvc or implement custom business logic, call DAO to complete data operations.
Controller - Controller Layer
Handle HTTP requests, call Service layer, return RO response.
Macro System (robotech-macros)
The project provides numerous macros to simplify development:
Application Config Macros
build_app_cfg!- Build application configurationwatch_cfg_file!- Watch config file changes and hot-reload
Database Macros
db_migrate!- Execute database migrationdb_conn!- Get database connection
Logging Macros
log_call- Auto-record function call logslog_result- Record return values
Controller Macros
impl_controller- Auto-generate controller routes
Full documentation at: robotech-macros
Usage Examples
Complete Microservice Example
use *;
use ;
use EntityTrait;
// 1. Define configuration
// 2. Define entity
// 3. Implement DAO
impl_base_dao!;
// 4. Implement Service
;
// 5. Implement Controller
;
// 6. Start service
async
License
This project is licensed under the MIT License - see the LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit issues and Pull Requests.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
Contact
- Project Homepage: https://github.com/rusthing/robotech-rs
- Issue Tracker: https://github.com/rusthing/robotech-rs/issues
- Author: zbz