Skip to content

astraly-labs/0d-master-api

Repository files navigation

πŸš€ 0D Master API

Pragma Template is a template for creating a new service using axum and diesel. It follows modern Rust practices, emphasizing reliability, safety, and maintainability.

✨ Features

  • Modern Architecture: Built with a modular crate-based design
  • High Performance: Leverages Rust's performance and safe concurrency
  • Database Integration: Uses PostgreSQL with Diesel ORM and connection pooling
  • API Documentation: Auto-generated OpenAPI documentation via Utoipa
  • Observability: Integrated with OpenTelemetry for tracing and monitoring
  • Rate Limiting: IP-based rate limiting with domain whitelist support
  • Request Timeout: Configurable timeout middleware to prevent resource exhaustion
  • Security: Built-in CORS configuration and middleware architecture
  • Containerization: Docker ready with multi-stage builds for minimal image size
  • Development Tools: Docker Compose for local development environment
  • CI/CD: GitHub Actions workflows for automated testing and deployments

πŸ“‚ Project Structure

The project is organized into a workspace with multiple crates:

0d-master-api/
β”œβ”€β”€ bin/                     # Binary crates
β”‚   └── 0d-bin/          # Main executable
β”œβ”€β”€ crates/                  # Library crates
β”‚   β”œβ”€β”€ 0d-api/          # API logic and routes
β”‚   └── 0d-db/           # Database models and interactions
|       └── migrations/      # Database migrations
└── src/                     # Workspace shared code

This structure allows for clear separation of concerns and easier maintenance.

🏁 Getting Started

Prerequisites

  • Rust 1.86.0 or newer
  • Docker and Docker Compose (for development environment)
  • PostgreSQL (for production or standalone use)

Environment Setup

  1. Clone the repository:

    git clone https://github.com/yourusername/0d-master-api.git
    cd 0d-master-api
  2. Copy the example environment file:

    cp .env.example .env
  3. Update .env with your configuration values

Development Environment

The project includes a Docker Compose file for setting up a local development environment:

# Start the development environment
docker-compose -f compose.dev.yaml up -d

# Check the services
docker-compose -f compose.dev.yaml ps

This will start:

  • PostgreSQL database
  • Grafana LGTM stack for observability (Loki, Grafana, Tempo, Mimir)

Building the Project

# Build the project
cargo build

# Run tests
cargo nextest run

# Run with cargo
cargo run --bin 0d-bin

Running in Docker

# Build the Docker image
docker build -t 0d-bin .

# Run the container
docker run -p 3000:3000 --env-file .env 0d-bin

βš™οΈ Configuration

The service is configured via environment variables:

Core Configuration

  • DATABASE_URL: PostgreSQL connection string
  • DATABASE_MAX_CONN: Maximum database connections in the pool
  • API_PORT: Port for the API server
  • CORS_ALLOWED_ORIGINS: Comma-separated list of allowed browser origins (http://localhost:3000,https://app.0d.finance is a safe starting point; unset to fall back to permissive mode)
  • OTEL_COLLECTOR_ENDPOINT: OpenTelemetry collector endpoint for tracing

Rate Limiting Configuration

  • RATE_LIMIT_ENABLED: Enable/disable rate limiting (default: true)
  • RATE_LIMIT_PER_SECOND: Number of requests allowed per second (default: 2)
  • RATE_LIMIT_BURST_SIZE: Burst capacity for rate limiting (default: 5)
  • RATE_LIMIT_CLEANUP_INTERVAL_SECS: Cleanup interval for rate limiter storage (default: 60)
  • RATE_LIMIT_WHITELIST_DOMAINS: Comma-separated list of domains to bypass rate limiting (e.g., trusted-domain.com,api.partner.com)

Request Timeout Configuration

  • REQUEST_TIMEOUT_SECS: Request timeout in seconds (default: 30)

πŸ›‘οΈ Middleware Architecture

The API implements a layered middleware architecture for security and performance:

Rate Limiting

  • IP-based rate limiting using tower_governor
  • Configurable requests per second and burst capacity
  • Domain whitelist support: Bypass rate limiting for trusted domains by checking Origin/Referer headers
  • Automatic cleanup of internal storage to prevent memory leaks

Request Timeout

  • Configurable timeout for all requests to prevent resource exhaustion
  • Returns 408 Request Timeout when exceeded

Middleware Order (innermost to outermost)

  1. OpenTelemetry tracing - Distributed tracing and observability
  2. Rate limiting - Request throttling with domain whitelist
  3. Timeout - Request timeout enforcement
  4. CORS - Cross-origin resource sharing

πŸ“š API Documentation

When the service is running, API documentation is available at:

http://localhost:{API_PORT}/v1/docs

The documentation is automatically generated from the API code using Utoipa.

πŸ”„ Database Migrations

Database migrations are managed with Diesel:

# Install Diesel CLI (if not already installed)
cargo install diesel_cli --no-default-features --features postgres

# Run migrations
diesel migration run

# Create a new migration
diesel migration generate name_of_migration

πŸ§ͺ Testing

# Run all tests
cargo test

# Run specific tests
cargo test -p 0d-api

# Format and lint code
make format

πŸ› οΈ Project Completion Guide

To complete this template you can:

  1. Models and Business Logic

    • Implement models in crates/0d-db/src/models/
    • Add business logic in crates/0d-api/src/handlers/
    • Create database migrations
  2. API Endpoints

    • Implement endpoints in crates/0d-api/src/handlers/
  3. Testing and Documentation

    • Write comprehensive tests for all endpoints
    • Complete API documentation
    • Add usage examples

πŸ’‘ Best Practices

  • Security: Always follow security best practices
  • Testing: Maintain high test coverage using codecov and nextes.st
  • Documentation: Keep API documentation up to date
  • Error Handling: Implement proper error handling and user feedback
  • Rate Limiting: Built-in rate limiting is enabled by default to prevent abuse. Configure via environment variables to adjust limits or whitelist trusted domains
  • Request Timeouts: Configure appropriate timeout values based on your use case to prevent long-running requests from blocking resources
  • Audit Logging: Add detailed audit logging for security events

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add some amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ‘ Acknowledgements

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 5