Aspect-RS: Aspect-Oriented Programming for Rust
📍 Private Development Repository
This is the private development repository for aspect-rs. The public repository is at:
- GitHub: https://github.com/yijunyu/aspect-rs
- Documentation: https://yijunyu.github.io/aspect-rs/
- Deployment: See DEPLOYMENT.md for deploying to public repo
A comprehensive Aspect-Oriented Programming (AOP) framework for Rust, bringing the power of cross-cutting concerns modularization to the Rust ecosystem.
📖 Read the Book - Comprehensive guide with 11 chapters covering motivation, usage, architecture, and advanced topics.
What is AOP?
Aspect-Oriented Programming helps you modularize cross-cutting concerns - functionality that cuts across multiple parts of your application:
- Logging: Track function entry/exit across your codebase
- Performance Monitoring: Measure execution time automatically
- Caching: Add memoization without cluttering business logic
- Security: Enforce authorization declaratively
- Transactions: Manage database transactions transparently
- Retry Logic: Add resilience patterns without boilerplate
- Validation: Enforce constraints before function execution
Installation
Add to your Cargo.toml:
[]
= "0.1"
= "0.1"
= "0.1" # Optional: production-ready aspects
Minimum Supported Rust Version (MSRV): 1.70+
Production-Ready Aspects (aspect-std)
The aspect-std crate provides 8 battle-tested aspects ready for production use:
| Aspect | Purpose | Example Use Case |
|---|---|---|
| LoggingAspect | Entry/exit logging | Trace function calls with timestamps |
| TimingAspect | Performance monitoring | Measure execution time, warn on slow functions |
| CachingAspect | Memoization | Cache expensive computations |
| MetricsAspect | Metrics collection | Track call counts, latency distributions |
| RateLimitAspect | Rate limiting | Prevent API abuse with token bucket |
| CircuitBreakerAspect | Fault tolerance | Handle service failures gracefully |
| AuthorizationAspect | Access control | Enforce role-based permissions (RBAC) |
| ValidationAspect | Input validation | Validate function arguments with custom rules |
Quick Examples
use *;
// Logging with timestamps
// Rate limiting (100 calls per minute)
// Authorization with role-based access control
// Circuit breaker (opens after 5 failures, retries after 30s)
Quick Start
Define an aspect and apply it to your functions:
use *;
use aspect;
// Define an aspect
;
// Apply it to your functions
Features
- ✅ Procedural Macros: Works with stable Rust, no custom toolchain needed
- ✅ Multiple Advice Types:
before,after,after_error,around - ✅ Aspect Composition: Stack multiple aspects on a single function
- ✅ Async Support: Full support for async functions
- ✅ Generic Functions: Preserves generics and lifetimes
- ✅ Zero Cost Abstractions: <10ns overhead for simple aspects
- ✅ Production-Ready Aspects: 8 battle-tested aspects in
aspect-std - ✅ Well-Tested: 108+ tests across all crates
- ✅ Comprehensive Benchmarks: Performance validated with criterion
Core Concepts
Aspects
An aspect is a module that encapsulates a cross-cutting concern. Implement the Aspect trait to define your aspect's behavior:
JoinPoints
A joinpoint represents a point in your program's execution where an aspect can be applied (e.g., function call). The JoinPoint struct provides context:
Advice
Advice is the action taken by an aspect at a joinpoint:
before: Runs before the function executesafter: Runs after successful executionafter_error: Runs if the function returns an erroraround: Wraps the entire function execution
Examples
Logging
;
Performance Monitoring
;
Multiple Aspects
Stack aspects to compose behavior:
Aspects execute in order: Cache → Timer → Logger → function → Logger → Timer → Cache
Comprehensive Examples
See the aspect-examples/ directory for complete working examples:
Basic Examples
- logging.rs: Entry/exit logging with timestamps
- timing.rs: Performance measurement and slow function warnings
- caching.rs: Memoization and cache monitoring
Advanced Examples
- advanced_aspects.rs: Rate limiting, circuit breakers, authorization, validation
- api_server.rs: Complete REST API with CRUD operations
- More patterns coming soon: Distributed tracing, async aspects, custom pointcuts
Run Examples
# Run the API server example
# Run advanced aspects demo
# Run all examples
Architecture
aspect-rs/
├── aspect-core/ # Core traits and types (Aspect, JoinPoint, etc.)
├── aspect-macros/ # Procedural macros (#[aspect] attribute)
├── aspect-std/ # Production-ready aspects library (8 aspects)
├── aspect-runtime/ # Runtime utilities and registry
├── aspect-examples/ # Comprehensive examples and patterns
├── aspect-driver/ # Phase 3: rustc-driver integration (design complete)
└── cargo-aspect/ # Phase 3: Cargo plugin for automatic weaving
How It Works
The #[aspect] macro transforms your function at compile time:
// You write:
// Macro expands to:
This approach provides:
- Zero runtime overhead when aspects are no-ops
- Compile-time safety - all aspect code is type-checked
- Clean generated code - easy to debug with
cargo expand
Roadmap
✅ Phase 1-2: Production Ready (v0.1.0 - Current)
- Core AOP infrastructure with
Aspecttrait #[aspect]procedural macro for function weaving- 8 production-ready aspects in
aspect-std - 108+ tests, comprehensive benchmarks
- Full documentation and examples
- Status: Stable, ready for production use
📋 Phase 3: Advanced Features (Design Complete)
- Automatic aspect weaving (no per-function annotations)
- Advanced pointcuts:
execution(),within(),call(),field_access() - rustc-driver integration for whole-program analysis
- Field access interception
- Call-site matching
- Status: Fully designed and documented, ready for implementation
See PHASE3_COMPLETE.md for complete Phase 3 documentation.
Performance
Benchmarked on AMD Ryzen 9 5950X (see BENCHMARKS.md):
| Scenario | Overhead | Target |
|---|---|---|
| No-op aspect | ~2ns | <10ns ✅ |
| Simple logging | ~8ns | <10ns ✅ |
| Multiple aspects | ~15ns | <20ns ✅ |
| Complex caching | Variable | Depends on cache hit rate |
All performance targets met!
📚 Documentation
Getting Started
- Quick Start Guide - Get up and running in 5 minutes
- API Documentation - Complete API reference
- Examples - 10 real-world code examples
Migration & Comparison
- Migration Guide - Migrate from manual code, decorators, middleware, or other AOP frameworks
- Comparison Guide - Compare aspect-rs with AspectJ, PostSharp, and alternative approaches
Advanced Topics
- Benchmarks Guide - Performance analysis and optimization techniques
- Optimization Guide - Strategies for achieving <5% overhead
- Phase 3 Design - Future automatic weaving and advanced features
Project Information
- Changelog - Complete version history
- Contributing - Contribution guidelines
- Release Checklist - Publication and release process
- Project Status - Current development status
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT license (LICENSE-MIT)
at your option.
Inspiration
Inspired by AspectJ (Java), Spring AOP, and the Rust community's desire for clean, modular code.