# Astrea Framework - AI Agent Instructions
> **Note to AI Agents/Coding Assistants:** When the user asks you to implement features, fix bugs, or write code for an `astrea` project, you **MUST** follow the guidelines and rules outlined in this document. Failure to do so will result in code that does not compile or diverges from the framework's intended architecture.
You are assisting the user with a Rust web application built using the `astrea` framework. `astrea` is a file-system based routing framework for `axum` (inspired by Next.js/Nitro/H3). You must adopt the following specific coding conventions and architectural patterns.
---
## Table of Contents
1. [Project Structure](#1-project-structure)
2. [File-System Based Routing](#2-file-system-based-routing)
3. [Application Initialization (main.rs)](#3-application-initialization-mainrs)
4. [Handler Signature](#4-handler-signature)
5. [Data Extraction](#5-data-extraction)
6. [Responses and Error Handling](#6-responses-and-error-handling)
7. [Application State Management](#7-application-state-management)
8. [Middleware](#8-middleware)
9. [WebSockets and Server-Sent Events](#9-websockets-and-server-sent-events)
10. [AI Agent Checklist](#10-ai-agent-checklist)
---
## 1. Project Structure
A properly structured Astrea project looks like this:
```
my-api/
├── Cargo.toml
├── src/
│ ├── main.rs # Application entry point (initialize server here)
│ ├── routes/ # All route handlers go here
│ │ ├── _middleware.rs # Global middleware (optional)
│ │ ├── index.get.rs # GET /
│ │ ├── health.get.rs # GET /health
│ │ └── api/
│ │ ├── _middleware.rs # Scoped API middleware (optional)
│ │ ├── users/
│ │ │ ├── index.get.rs # GET /api/users
│ │ │ ├── index.post.rs # POST /api/users
│ │ │ ├── [id].get.rs # GET /api/users/:id
│ │ │ ├── [id].put.rs # PUT /api/users/:id
│ │ │ └── [id].delete.rs # DELETE /api/users/:id
│ │ └── posts/
│ │ └── [...slug].get.rs # GET /api/posts/*slug (catch-all)
│ └── lib.rs # Optional: shared utilities and types
```
---
## 2. File-System Based Routing
You do **not** write `axum::Router` routes manually using `.route()` inside `main.rs`. Instead, you place `.rs` files directly into the `src/routes/` directory.
### Route Naming Convention
The file path translates directly to the HTTP path:
- `src/routes/index.get.rs` → `GET /`
- `src/routes/health.get.rs` → `GET /health`
- `src/routes/users/index.get.rs` → `GET /users`
- `src/routes/users/index.post.rs` → `POST /users`
- `src/routes/users/[id].get.rs` → `GET /users/:id` (dynamic parameter)
- `src/routes/users/[id].put.rs` → `PUT /users/:id`
- `src/routes/users/[id].delete.rs` → `DELETE /users/:id`
- `src/routes/posts/[...slug].get.rs` → `GET /posts/*slug` (catch-all route)
### HTTP Methods
Always include the HTTP method as the file extension:
- `.get.rs` → HTTP GET method
- `.post.rs` → HTTP POST method
- `.put.rs` → HTTP PUT method
- `.patch.rs` → HTTP PATCH method
- `.delete.rs` → HTTP DELETE method
- `.head.rs` → HTTP HEAD method
- `.options.rs` → HTTP OPTIONS method
### No Manual Registration
Do **NOT** edit `main.rs` to register routes. Routes are automatically generated by the `astrea::generate_routes!();` macro in the `mod routes` block. The framework scans the `src/routes/` directory at compile time and generates all routes automatically.
---
## 3. Application Initialization (main.rs)
This is how to properly set up an Astrea server:
### Basic Server Setup
```rust
// Define your application state (if needed)
#[derive(Clone)]
pub struct AppState {
pub app_name: String,
pub version: String,
// Add other state fields as needed
}
// Import the routes module
mod routes {
astrea::generate_routes!();
}
#[astrea::tokio::main]
async fn main() {
// 1. Initialize logging (optional but recommended)
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.init();
// 2. Create application state
let state = AppState {
app_name: "My API".to_string(),
version: "1.0.0".to_string(),
};
// 3. Create router and attach state
let app = routes::create_router()
.with_state(state);
// 4. Optional: Add OpenAPI/Swagger UI routes
let app = app.merge(
astrea::openapi::router("My API", "1.0.0")
);
// 5. Bind to address and start server
let listener = astrea::tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
// 6. Print helpful startup messages
println!("🚀 Server listening on http://0.0.0.0:3000");
println!("📚 Swagger UI: http://localhost:3000/swagger");
println!("📄 OpenAPI Spec: http://localhost:3000/openapi.json");
// 7. Start serving requests
astrea::axum::serve(listener, app).await.unwrap();
}
```
### Environment-Based Configuration
```rust
#[astrea::tokio::main]
async fn main() {
let host = std::env::var("HOST").unwrap_or("0.0.0.0".to_string());
let port = std::env::var("PORT").unwrap_or("3000".to_string());
let addr = format!("{}:{}", host, port);
let state = AppState {
app_name: std::env::var("APP_NAME").unwrap_or("My API".to_string()),
version: std::env::var("APP_VERSION").unwrap_or("1.0.0".to_string()),
};
let app = routes::create_router().with_state(state);
let listener = astrea::tokio::net::TcpListener::bind(&addr)
.await
.expect(&format!("Failed to bind to {}", addr));
println!("🚀 Server listening on http://{}", addr);
astrea::axum::serve(listener, app).await.unwrap();
}
```
---
## 4. Handler Signature
Astrea unifies all handler signatures. **Do NOT use standard `axum` extractors** (such as `Path<T>`, `Query<T>`, `State<T>`, or `Json<T>`) in the function signature.
### Basic Handler
All standard HTTP handlers **MUST** use this exact signature:
```rust
use astrea::prelude::*;
#[route]
pub async fn handler(event: Event) -> Result<Response> {
// Your logic here
json(json!({ "status": "ok" }))
}
```
### Handler with Request Body
When you need to read the raw request body (e.g., for JSON deserialization):
```rust
use astrea::prelude::*;
#[route]
pub async fn handler(event: Event) -> Result<Response> {
// The body is automatically extracted by Astrea
let body: MyRequest = get_body(&event)?;
json(json!({ "received": body }))
}
```
### Handler with Raw Bytes
For binary data or custom body parsing:
```rust
use astrea::prelude::*;
use bytes::Bytes;
#[route]
pub async fn handler(event: Event, bytes: Bytes) -> Result<Response> {
// Work with raw bytes
let data = String::from_utf8(bytes.to_vec())?;
text(data)
}
```
---
## 5. Data Extraction
Extract data synchronously inside the handler body using the provided helper functions. Extract everything from the `event` object:
### Path Parameters (URL Parameters)
```rust
// Required parameter - returns error if missing
let id = get_param_required(&event, "id")?;
// Optional parameter - returns Option
let page = get_param(&event, "page"); // Option<String>
```
### Query Parameters
```rust
// Get a single query parameter with fallback
let limit = get_query_param(&event, "limit").unwrap_or("10".to_string());
// Get all query parameters as a HashMap
let params = get_query(&event);
```
### Request Headers
```rust
// Get header value (case-insensitive)
let auth = get_header(&event, "Authorization");
// Required header
let auth = get_header(&event, "Authorization")
.ok_or_else(|| RouteError::unauthorized("Missing Authorization header"))?;
```
### Request Method and Path
```rust
let method = get_method(&event); // axum::http::Method
let path = get_path(&event); // String
```
### Request Body (JSON)
```rust
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUserRequest {
name: String,
email: String,
}
#[route]
pub async fn handler(event: Event) -> Result<Response> {
let body: CreateUserRequest = get_body(&event)?;
// Handle the body
json(json!({ "name": body.name }))
}
```
### Application State
```rust
#[route]
pub async fn handler(event: Event) -> Result<Response> {
// Extract application state (defined in main.rs)
let state = get_state::<AppState>(&event)?;
json(json!({
"app_name": state.app_name,
"version": state.version
}))
}
```
---
## 6. Responses and Error Handling
Always return `astrea::response::Result<Response>`. Use helpers from `astrea::prelude::*` to build responses.
### Response Builders
```rust
use astrea::prelude::*;
use axum::http::StatusCode;
// JSON response
json(json!({ "status": "ok" }))?
// Text response
text("Hello, World!")?
// Redirect response
redirect("/new-location")?
// Custom status code and headers
let response = json(data)?
.status(StatusCode::CREATED)
.header("X-Custom-Header", "value")
.header("Content-Type", "application/json");
```
### Error Handling
Use the `?` operator for ergonomic error handling. Any standard error implementing `Into<anyhow::Error>` is automatically converted to a 500 JSON response.
For explicit HTTP errors, return `astrea::response::RouteError`:
```rust
use astrea::response::RouteError;
// 400 Bad Request
return Err(RouteError::bad_request("Invalid input"));
// 404 Not Found
return Err(RouteError::not_found("User not found"));
// 401 Unauthorized
return Err(RouteError::unauthorized("Please provide valid credentials"));
// 403 Forbidden
return Err(RouteError::forbidden("You do not have permission"));
// Custom error with status code and message
return Err(RouteError::validation("Email format is invalid"));
```
### Complete Error Handling Example
```rust
#[derive(Deserialize)]
struct CreateUserRequest {
name: String,
email: String,
}
#[route]
pub async fn handler(event: Event) -> Result<Response> {
// Parse request body
let body: CreateUserRequest = get_body(&event)?;
// Validate input
if body.name.is_empty() {
return Err(RouteError::bad_request("Name is required"));
}
if !body.email.contains('@') {
return Err(RouteError::validation("Invalid email format"));
}
// Create user (may return error)
let user = create_user(&body).await?;
// Return success response
json(user)?.status(StatusCode::CREATED)
}
```
---
## 7. Application State Management
Application state allows you to share resources (databases, configuration, caches) across all route handlers.
### Defining State
In `main.rs`, define your state as a `Clone` struct:
```rust
#[derive(Clone)]
pub struct AppState {
pub db: Arc<DatabasePool>,
pub config: Config,
pub cache: Arc<Cache>,
}
```
### Initializing State
```rust
#[astrea::tokio::main]
async fn main() {
let db_pool = establish_connection().await?;
let state = AppState {
db: Arc::new(db_pool),
config: Config::from_env(),
cache: Arc::new(Cache::new()),
};
let app = routes::create_router().with_state(state);
// ...
}
```
### Using State in Handlers
```rust
#[route]
pub async fn handler(event: Event) -> Result<Response> {
let state = get_state::<AppState>(&event)?;
// Use the state
let users = state.db.fetch_users().await?;
let app_name = state.config.app_name.clone();
let cached_value = state.cache.get("key");
json(json!({ "users": users, "app": app_name }))
}
```
#### Best Practices
- **Use `Arc` for shared resources** - Wrap expensive-to-clone resources like database pools in `Arc<T>`
- **Derive `Clone`** - The state must implement `Clone` to be shared across handlers
- **Immutable state** - Keep state immutable; use `Arc<Mutex<T>>` or `Arc<RwLock<T>>` if you need interior mutability
- **Initialize in main** - Set up all state in `main.rs` before creating the router
---
## 8. Middleware
Middleware provides cross-cutting concerns like logging, authentication, CORS, compression, etc.
### Global Middleware
Create `src/routes/_middleware.rs` to apply middleware to all routes:
```rust
use astrea::middleware::*;
pub fn middleware<S: Clone + Send + Sync + 'static>() -> Middleware<S> {
Middleware::new().wrap(|router| {
router
// HTTP request tracing/logging
.layer(astrea::tower_http::trace::TraceLayer::new_for_http())
// CORS configuration
.layer(astrea::tower_http::cors::CorsLayer::permissive())
// Response compression
.layer(astrea::tower_http::compression::CompressionLayer::new())
})
}
```
### Scoped Middleware
Create `src/routes/api/_middleware.rs` to apply middleware only to `/api/*` routes:
```rust
use astrea::middleware::*;
pub fn middleware<S: Clone + Send + Sync + 'static>() -> Middleware<S> {
// Inherit parent middleware and add additional layers
Middleware::new().wrap(|router| {
router
.layer(astrea::tower_http::trace::TraceLayer::new_for_http())
})
}
```
### Middleware Modes
#### Extend Mode (Default)
```rust
Middleware::new() // Inherit all ancestor middleware layers
```
- Child routes **inherit** all parent middleware
- New middleware is **added on top** of ancestor layers
- Middleware chain: Ancestor A → Ancestor B → Parent C → Child D
- Use this for most cases to build up middleware protection
#### Override Mode
```rust
Middleware::override_parent() // Clear ALL ancestor middleware
```
- Child routes **discard** all ancestor middleware layers
- Only the override scope's own middleware applies
- **Important:** This clears all ancestor layers, not just the immediate parent
- Middleware chain: Child D only (Ancestor A, B, C are removed)
- Use this for public routes that shouldn't have auth/restrictions
### Understanding Middleware Inheritance Hierarchy
The key insight: **`override_parent()` clears the entire ancestor chain, not individual levels.**
**Example Project Structure:**
```
routes/
├── _middleware.rs # Middleware A: [CORS, Trace]
├── index.get.rs # Inherits: A only
├── api/
│ ├── _middleware.rs # Middleware B: [Auth, Token Check]
│ ├── users.get.rs # Inherits: A → B
│ ├── posts.get.rs # Inherits: A → B
│ └── public/
│ ├── _middleware.rs # Middleware C (Override mode): [Rate Limit]
│ ├── login.post.rs # Inherits: C only (A and B cleared!)
│ └── signup.post.rs # Inherits: C only (A and B cleared!)
```
**Middleware applied to each route:**
- `GET /` → Middleware A
- `GET /api/users` → Middleware A + Middleware B
- `GET /api/posts` → Middleware A + Middleware B
- `POST /api/public/login` → **Middleware C only** (Auth from B is removed!)
- `POST /api/public/signup` → **Middleware C only** (Auth from B is removed!)
### When to Use Each Mode
**Use `Middleware::new()` (Extend):**
- Building REST API with increasing security levels
- Adding request logging/tracing at each level
- Implementing role-based middleware that composes upward
**Use `Middleware::override_parent()` (Override):**
- Public authentication endpoints (login, signup, forgot-password)
- Health check endpoints that bypass all checks
- Public API documentation endpoints
- Webhook endpoints that use custom authentication
- Static file serving that shouldn't go through auth
### Common Middleware Patterns
**CORS Configuration:**
```rust
use astrea::tower_http::cors::{CorsLayer, AllowOrigin};
use axum::http::HeaderValue;
pub fn middleware<S: Clone + Send + Sync + 'static>() -> Middleware<S> {
Middleware::new().wrap(|router| {
let cors = CorsLayer::permissive(); // Allow all origins
router.layer(cors)
})
}
```
**Authentication Middleware (Custom):**
```rust
pub fn middleware<S: Clone + Send + Sync + 'static>() -> Middleware<S> {
// Note: Custom middleware logic should be in route handlers
// Use get_header(&event, "Authorization") to check auth
Middleware::new()
}
```
---
## 9. WebSockets and Server-Sent Events
Do not use axum's raw WebSocket or SSE extractors. Use Astrea's specialized route attributes.
### WebSocket Handler
```rust
use astrea::ws::{WebSocket, Message};
#[route(ws)]
pub async fn handler(event: Event, mut socket: WebSocket) {
while let Some(result) = socket.recv().await {
match result {
Ok(msg) => {
// Echo the message back
let _ = socket.send(msg).await;
}
Err(e) => {
eprintln!("WebSocket error: {}", e);
break;
}
}
}
}
```
**File:** `src/routes/ws/echo.ws.rs`
### Server-Sent Events Handler
```rust
use astrea::sse::{SseSender, SseEvent};
use std::time::Duration;
#[route(sse)]
pub async fn handler(event: Event, sender: SseSender) {
for i in 0..10 {
let event = SseEvent::new()
.event("message")
.data(format!("Message {}", i));
let _ = sender.send(event).await;
tokio::time::sleep(Duration::from_secs(1)).await;
}
}
```
**File:** `src/routes/stream/events.sse.rs`
---
## 10. AI Agent Checklist
Before outputting code to the user, verify ALL of these:
- [ ] **File Location** - Is the route handler in a dedicated `.rs` file inside `src/routes/`?
- [ ] **File Naming** - Does the filename follow the convention `<name>.<method>.rs`?
- [ ] **No Axum Extractors** - Are you avoiding `Path<T>`, `Query<T>`, `State<T>`, `Json<T>`, `Bytes` as function parameters?
- [ ] **Handler Signature** - Is the signature exactly `pub async fn handler(event: Event) -> Result<Response>`?
- [ ] **Data Extraction** - Are you using `get_param()`, `get_query_param()`, `get_body()`, `get_state()` functions?
- [ ] **Response Building** - Are you using `json()`, `text()`, `redirect()` helpers from `astrea::prelude::*`?
- [ ] **Error Handling** - Are you using `RouteError::*` for HTTP errors and the `?` operator for other errors?
- [ ] **State Management** - If using state, is it being passed via `get_state::<T>(&event)?`?
- [ ] **Middleware** - Is middleware defined in `_middleware.rs` files, not in `main.rs`?
- [ ] **No main.rs Route Registration** - Are you NOT manually calling `.route()` in `main.rs`?
- [ ] **main.rs Setup** - Does `main.rs` properly initialize state, create router via `routes::create_router()`, and bind to address?
### Example Code Structure to Verify
✅ **Good:**
```rust
// src/routes/api/users/[id].get.rs
use astrea::prelude::*;
#[route]
pub async fn handler(event: Event) -> Result<Response> {
let id = get_param_required(&event, "id")?;
let state = get_state::<AppState>(&event)?;
let user = state.db.get_user(&id).await?;
json(user)
}
```
❌ **Bad:**
```rust
// src/main.rs
use axum::{Path, extract::State};
#[axum::routes]
async fn get_user(Path(id): Path<String>, State(db): State<DatabasePool>) -> Json<User> {
// This violates Astrea conventions
}
```
By rigorously following these guidelines, you will synthesize highly idiomatic and working code for Astrea applications.