I have created multiple standards files that I can use to ensure my codebase remains consistent without feeding files and working examples into the chat.
I then created a rule that contains each standard file.
@ADVENTURE_STANDARDS.md
@API_STANDARDS.md
@SRC_STANDARDS.md
@MODEL_STANDARDS.md
@ADVENTURE_STANDARDS.md
@COMPONENT_STANDARDS.md
API Standards and Patterns
General Guidelines
Response Format
All API responses should follow the standard response structure defined in models/response.rs
:
pub struct ApiResponse<T> {
pub success: bool,
pub data: Option<T>,
pub error: Option<String>,
}
Error Handling
- Use the custom error types defined in
error.rs
- Always return appropriate HTTP status codes
- Include meaningful error messages
- Log errors with appropriate severity levels
CORS Configuration
- Use
tower-http
crate with CORS feature - Configure CORS at the application level using
CorsLayer
- Development settings:
let cors = CorsLayer::new() .allow_origin(Any) .allow_methods(Any) .allow_headers(Any);
- Production settings should be more restrictive:
let cors = CorsLayer::new() .allow_origin([ "https://your-domain.com".parse().unwrap(), "https://api.your-domain.com".parse().unwrap() ]) .allow_methods(["GET", "POST", "PUT", "DELETE"]) .allow_headers(["authorization", "content-type"]);
Code Execution Service
- Use sandboxed environment for code execution
- Configure Python virtual environment in
/sandbox/venv
- Set appropriate environment variables:
PYTHONPATH=/sandbox CODE_EXECUTION_TIMEOUT=5000
- Request format:
pub struct CodeExecutionRequest { code: String, input: Option<String>, }
- Response format:
pub struct CodeExecutionResponse { output: String, error: Option<String>, }
- Security considerations:
- Validate and sanitize input code
- Restrict allowed Python imports
- Set execution timeouts
- Limit memory usage
- Use isolated sandbox environment
Authentication
- All protected routes must use the
auth_required
middleware - JWT tokens must be included in the Authorization header
- Token expiration should be handled gracefully
Route Structure
Handler Functions
pub async fn handler_name(
State(state): State<AppState>,
auth: AuthUser, // If protected route
// Other parameters...
) -> Result<ApiResponse<T>, AppError> {
// Implementation
}
Route Registration
pub fn routes() -> Router {
Router::new()
.route("/path", get(handler_name))
.route("/path/:id", post(handler_name))
.with_state(state)
}
Query Parameters
Pagination
#[derive(Debug, Deserialize)]
pub struct PaginationParams {
pub page: Option<i64>,
pub limit: Option<i64>,
pub sort_by: Option<String>,
pub sort_order: Option<SortOrder>,
}
Filtering
#[derive(Debug, Deserialize)]
pub struct FilterParams {
pub search: Option<String>,
pub status: Option<String>,
pub date_from: Option<DateTime<Utc>>,
pub date_to: Option<DateTime<Utc>>,
}
Request Validation
Input Validation
- Use
serde
for request body validation - Implement custom validators when needed
- Return validation errors with specific messages
Example
#[derive(Debug, Deserialize, Validate)]
pub struct CreateChallengeRequest {
#[validate(length(min = 3, max = 100))]
pub title: String,
#[validate(length(min = 10))]
pub description: String,
#[validate(range(min = 1, max = 5))]
pub difficulty: i32,
}
Database Operations
Query Structure
// Use SQLx for database operations
let result = sqlx::query_as!(
Model,
r#"
SELECT * FROM table_name
WHERE condition = $1
ORDER BY created_at DESC
LIMIT $2 OFFSET $3
"#,
param1,
limit,
offset
)
.fetch_all(&state.db)
.await?;
Transaction Handling
let mut tx = state.db.begin().await?;
// Perform operations
tx.commit().await?;
Logging
Log Levels
- ERROR: For errors that need immediate attention
- WARN: For potential issues that don’t stop execution
- INFO: For normal operation events
- DEBUG: For detailed debugging information
Log Format
tracing::info!(
action = "operation_name",
user_id = %user.id,
"Operation completed successfully"
);
Testing
Unit Tests
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_handler() {
// Test implementation
}
}
Integration Tests
- Use test database
- Mock external services
- Clean up after tests
Performance Considerations
Caching
- Use Redis for caching when appropriate
- Cache frequently accessed data
- Implement cache invalidation strategies
Query Optimization
- Use appropriate indexes
- Limit result sets
- Use efficient query patterns
Security
Input Sanitization
- Validate all user input
- Escape SQL queries
- Sanitize HTML output
Rate Limiting
- Implement rate limiting middleware
- Use IP-based or user-based limits
- Return appropriate headers
Documentation
Code Comments
- Document complex logic
- Explain non-obvious decisions
- Keep comments up to date
API Documentation
- Use OpenAPI/Swagger for API documentation
- Include request/response examples
- Document error scenarios