astrea 0.3.1

A file-system based routing framework for Axum with automatic code generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
# 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.