Files
rspade_system/docs/rsx-architecture.md
root f6fac6c4bc Fix bin/publish: copy docs.dist from project root
Fix bin/publish: use correct .env path for rspade_system
Fix bin/publish script: prevent grep exit code 1 from terminating script

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-21 02:08:33 +00:00

457 lines
12 KiB
Markdown
Executable File

# RSX Architecture Documentation
## Overview
RSX (RSpade eXtension) is a path-agnostic development framework built on top of Laravel that provides a modern, attribute-driven development experience. Developers can organize their code freely without worrying about file paths, imports, or directory structures.
## Core Philosophy
1. **Path Independence**: Files reference each other by class name, not file path
2. **Attribute-Driven**: PHP 8 attributes for routing, caching, middleware, and more
3. **Automatic Discovery**: All files are automatically indexed and made available
4. **Zero Configuration**: Works out of the box with sensible defaults
5. **Performance First**: Fast in development, optimized in production
6. **Opinionated Design**: Strong conventions for consistent development
## Three-Tier Architecture
RSX follows a clear three-tier directory structure philosophy:
### 1. Framework Layer: `/app/RSpade/`
This directory contains framework and library code that should NOT be modified by users.
**Purpose**: Core RSX functionality that powers the path-agnostic environment
**Key Components**:
#### Core System (`/app/RSpade/Core/`)
- **Manifest.php** - File indexing and discovery system
- Scans directories for PHP classes
- Builds comprehensive class map
- Handles file-based and memory caching
- Supports incremental rebuilds
- **Autoloader.php** - SPL autoloader for RSX classes
- Integrates with Manifest for class loading
- Supports path-agnostic class resolution
- Falls back to PSR-4 for non-RSX classes
#### Dispatch System (`/app/RSpade/Core/Dispatch/`)
- **Dispatcher.php** - Central request dispatcher
- Routes HTTP requests to appropriate handlers
- Processes attributes before and after execution
- Handles static assets, API requests, and controllers
- Integrates with Laravel's request/response cycle
- **RouteResolver.php** - URL pattern matching
- Converts route patterns to regex
- Extracts parameters from URLs
- Handles optional parameters and wildcards
- Sorts routes by specificity
- **AttributeProcessor.php** - Attribute handling
- Chain of Responsibility pattern
- Processes attributes before/after method execution
- Supports custom processors
- Handles caching, rate limiting, CORS, etc.
- **ApiHandler.php** - API request processing
- JSON-only responses (opinionated design)
- Internal API execution without HTTP overhead
- Session stack management for nested calls
- Pagination, filtering, and sorting support
- **AssetHandler.php** - Static file serving
- Serves files from `/rsx/*/public/` directories
- Proper MIME type detection
- Cache headers for performance
- Security checks for path traversal
#### Attributes (`/app/RSpade/Core/Attributes/`)
- **Route.php** - HTTP route definition
```php
#[Route('/api/users', methods: ['GET', 'POST'])]
```
- **Cache.php** - Response caching
```php
#[Cache(ttl: 3600, key: 'user-list', tags: ['users'])]
```
- **RateLimit.php** - Request throttling
```php
#[RateLimit(max_attempts: 60, decay_minutes: 1)]
```
- **Middleware.php** - Middleware application
```php
#[Middleware(['auth', 'verified'])]
```
- **Cors.php** - Cross-Origin Resource Sharing
```php
#[Cors(allowed_origins: ['https://app.example.com'])]
```
- **ApiVersion.php** - API versioning
```php
#[ApiVersion('v2', deprecated: false)]
```
#### Processors (`/app/RSpade/Core/Processors/`)
- **CacheProcessor.php** - Handles Cache attributes
- **RateLimitProcessor.php** - Handles RateLimit attributes
- **MiddlewareProcessor.php** - Handles Middleware attributes
- **CorsProcessor.php** - Handles CORS preflight and headers
#### Base Classes (`/app/RSpade/Core/Base/`)
- **Rsx_Controller** - Base controller with dispatch integration
- **Rsx_Model_Abstract** - Base model with manifest awareness
- **Rsx_Api** - Base API controller with JSON responses
- **Rsx_Service** - Base service class
- **Rsx_Component** - Base UI component class
### 2. Application Layer: `/app/*` (other directories)
Standard Laravel application directories that users can modify.
**Purpose**: Traditional Laravel application code
**Examples**:
- `/app/Http/Controllers/` - Laravel controllers
- `/app/Models/` - Eloquent models
- `/app/Console/Commands/` - Artisan commands
- `/app/Services/` - Business logic services
### 3. User Development Space: `/rsx/`
Path-agnostic RSX development directory.
**Purpose**: User-created RSX components that are automatically discovered
**Convention-based Structure** (optional):
```
/rsx/
├── controllers/ # HTTP controllers
├── api/ # API endpoints
├── models/ # Data models
├── services/ # Business logic
├── components/ # UI components
├── views/ # Blade templates
├── js/ # JavaScript modules
├── styles/ # SCSS/CSS files
└── */public/ # Public assets (served directly)
```
## Request Flow
### 1. HTTP Request Arrives
```
Browser/Client → Laravel → RSX Dispatcher
```
### 2. Dispatcher Processing
```
Dispatcher → AssetHandler (if static file)
→ RouteResolver → Find matching route
→ AttributeProcessor → Process before attributes
→ HandlerFactory → Create handler instance
→ Execute handler method
→ AttributeProcessor → Process after attributes
→ Response
```
### 3. Attribute Processing Pipeline
```
Request → RateLimitProcessor → MiddlewareProcessor → CacheProcessor → Handler
← CorsProcessor ← CacheProcessor ← Response
```
## Key Features
### 1. Attribute-Driven Development
```php
namespace Rsx\Api;
use App\RSpade\Core\Base\Rsx_Api;
use App\RSpade\Core\Attributes\{Route, Cache, RateLimit, Cors};
#[Cors(allowed_origins: ['https://app.example.com'])]
class UserApi extends Rsx_Api
{
#[Route('/api/users', methods: ['GET'])]
#[Cache(ttl: 300, tags: ['users'])]
#[RateLimit(max_attempts: 60)]
public static function list_users($params)
{
return ['users' => User::all()];
}
#[Route('/api/users/:id', methods: ['GET'])]
public static function get_user($params)
{
return User::find($params['id']);
}
}
```
### 2. Path-Agnostic Class Loading
```php
// No need for use statements or full paths
class OrderController extends Rsx_Controller
{
public function process_order($params)
{
// Classes are auto-discovered
$order = new OrderModel();
$payment = new PaymentService();
return $payment->process($order);
}
}
```
### 3. Internal API Execution (Future)
```php
// Call API endpoints internally without HTTP overhead
$result = API::execute('UserApi.get_profile', ['user_id' => 123]);
// Nested calls maintain separate session contexts
// UserApi → OrderApi → PaymentApi (each with own session)
```
### 4. Smart Asset Serving
Any file in `/rsx/*/public/` is automatically served:
- `/rsx/shop/public/logo.png` → `/rsx/shop/public/logo.png`
- Proper MIME types and cache headers
- No configuration needed
## Manifest System
The Manifest is the heart of RSX's path-agnostic architecture:
### Building
```bash
php artisan rsx:manifest:build # Full rebuild
php artisan rsx:manifest:rebuild # Force rebuild
php artisan rsx:manifest:clear # Clear cache
```
### Manifest Structure
```json
{
"classes": {
"UserController": {
"file": "/rsx/controllers/UserController.php",
"type": "controller",
"namespace": "Rsx\\Controllers"
}
},
"routes": {
"controllers": {
"/users": {
"GET": {
"class": "UserController",
"method": "index"
}
}
}
},
"metadata": {
"build_time": "2024-01-01 12:00:00",
"file_count": 150,
"route_count": 45
}
}
```
## Performance Optimizations
### 1. Two-Level Caching
- **Memory Cache**: In-process array cache for current request
- **File Cache**: Persistent cache across requests
- **Automatic invalidation**: Based on file modification times
### 2. Route Compilation
```bash
php artisan rsx:routes:cache # Compile routes for production
php artisan rsx:routes:clear # Clear route cache
```
### 3. Lazy Loading
- Classes are only loaded when actually used
- Manifest is loaded once per request
- Attributes are extracted on-demand
## Testing Framework
RSX includes comprehensive testing infrastructure:
### Test Organization
```
/tests/RsxFramework/
├── Unit/ # Isolated class tests
├── Integration/ # Component interaction tests
├── EndToEnd/ # Complete flow tests
└── Commands/ # Artisan command tests
```
### Running Tests
```bash
php artisan test # All tests (color-free output)
php artisan test tests/RsxFramework # Framework tests only
php artisan test --coverage # With coverage report
```
## Artisan Commands
### Manifest Management
```bash
php artisan rsx:manifest:build # Build manifest
php artisan rsx:manifest:show # Display manifest
php artisan rsx:manifest:stats # Show statistics
php artisan rsx:manifest:watch # Watch for changes
```
### Route Management
```bash
php artisan rsx:routes # List all routes
php artisan rsx:routes:list # Detailed route list
php artisan rsx:routes:cache # Cache routes
php artisan rsx:routes:clear # Clear route cache
```
### Development Tools
```bash
php artisan rsx:make:controller # Create RSX controller
php artisan rsx:make:api # Create API endpoint
php artisan rsx:make:model # Create RSX model
```
## Configuration
### Environment Variables
```env
RSX_CACHE_ENABLED=true # Enable manifest caching
RSX_CACHE_TTL=3600 # Cache TTL in seconds
RSX_AUTO_BUILD=true # Auto-build manifest if missing
RSX_WATCH_ENABLED=false # Enable file watching
```
### Configuration File
```php
// config/rsx.php
return [
'manifest' => [
'cache_enabled' => env('RSX_CACHE_ENABLED', true),
'cache_ttl' => env('RSX_CACHE_TTL', 3600),
],
'dispatch' => [
'api_json_only' => true, # APIs always return JSON
'asset_cache_ttl' => 86400,
],
];
```
## Best Practices
### 1. Use Attributes Wisely
- Apply at class level for all methods
- Apply at method level for specific routes
- Combine multiple attributes for complex behavior
### 2. Organize by Feature
```
/rsx/shop/
├── controllers/
├── models/
├── services/
└── public/
/rsx/blog/
├── controllers/
├── models/
└── public/
```
### 3. Keep Controllers Thin
- Business logic in services
- Data access in models
- Controllers for request/response only
### 4. Leverage Caching
- Use Cache attribute for expensive operations
- Set appropriate TTL values
- Use cache tags for invalidation
### 5. Rate Limiting
- Always add rate limiting to public APIs
- Use different limits for authenticated vs anonymous
- Consider using custom key resolvers
## Migration from Laravel
### Step 1: Move Controllers
```bash
# Move Laravel controller to RSX
mv app/Http/Controllers/UserController.php rsx/controllers/
```
### Step 2: Add Attributes
```php
// Before (Laravel)
Route::get('/users', [UserController::class, 'index']);
// After (RSX)
#[Route('/users', methods: ['GET'])]
public function index($params) { }
```
### Step 3: Update References
```php
// Before
use App\Http\Controllers\UserController;
// After - no import needed!
$controller = new UserController();
```
## Troubleshooting
### Manifest Not Building
```bash
php artisan rsx:manifest:rebuild --verbose
```
### Routes Not Found
```bash
php artisan rsx:routes:list | grep "your-route"
```
### Class Not Loading
```bash
php artisan rsx:manifest:show | grep "YourClass"
```
### Cache Issues
```bash
php artisan rsx:manifest:clear
php artisan rsx:routes:clear
php artisan cache:clear
```
## Future Roadmap
1. **GraphQL Support** - Automatic GraphQL schema from attributes
2. **WebSocket Integration** - Real-time features with attributes
3. **Module System** - Package RSX modules for reuse
4. **Hot Reload** - Automatic reload during development
5. **IDE Integration** - Full IntelliSense for RSX classes
6. **Distributed Caching** - Redis/Memcached for manifest
7. **API Documentation** - Auto-generate from attributes
8. **Database Migrations** - Attribute-based migrations