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
<p align="center">
  <h1 align="center">Astrea</h1>
  <p align="center">
    A file-system based routing framework for <a href="https://github.com/tokio-rs/axum">Axum</a>.
    <br />
    Inspired by <a href="https://nitro.unjs.io/">Nitro</a> and <a href="https://h3.unjs.io/">H3</a>.
  </p>
</p>

<p align="center">
  <a href="https://crates.io/crates/astrea"><img src="https://img.shields.io/crates/v/astrea.svg" alt="crates.io" /></a>
  <a href="https://docs.rs/astrea"><img src="https://docs.rs/astrea/badge.svg" alt="docs.rs" /></a>
  <a href="https://github.com/TNXG/astrea/blob/main/LICENSE"><img src="https://img.shields.io/crates/l/astrea.svg" alt="MIT License" /></a>
  <a href="https://deepwiki.com/TNXG/astrea"><img src="https://img.shields.io/badge/DeepWiki-Astrea-blue.svg" alt="DeepWiki" /></a>
</p>

<p align="center">
  <a href="README.zh-CN.md">简体中文</a>
</p>

---

## What Is Astrea?

Astrea turns your **file structure** into **API routes** — at compile time, with zero runtime cost. Drop a `.rs` file into the `src/routes/` folder, and it becomes an HTTP endpoint. No manual route registration, no `build.rs`, no boilerplate.

Every handler looks the same:

```rust
#[route]
async fn handler(event: Event) -> Result<Response> {
    // your logic here
}
```

That's it. No complex extractor signatures. No learning curve for each parameter type.

## Features

- 📁 **File-based routing** — file name = route path, generated at compile time
- 🎯 **Unified handler signature** — every handler is `async fn(Event) -> Result<Response>`
- 🔧 **Simple extractors**`get_param()`, `get_query_param()`, `get_body()` — just call a function
- 🧅 **Scoped middleware**`_middleware.rs` files with inherit (extend) or replace (override) modes
- 📝 **OpenAPI auto-gen** — optional Swagger UI + OpenAPI 3.0 spec from your code (feature flag `openapi`)
- 🔄 **Axum compatible** — works with all existing Axum middleware and the Tower ecosystem
- 📦 **Zero extra deps** — re-exports `axum`, `tokio`, `serde`, `tower`, etc. — just depend on `astrea`

## Quick Start

### 1. Create a new project

```bash
cargo new my-api
cd my-api
```

### 2. Add Astrea

```bash
cargo add astrea
```

Or in `Cargo.toml`:

```toml
[package]
name = "my-api"
edition = "2024"

[dependencies]
astrea = "0.0.1"
```

> **Note:** Astrea requires Rust edition 2024 (Rust ≥ 1.85).

### 3. Create your route files

```
my-api/
├── src/
│   ├── main.rs
│   └── routes/
│       ├── index.get.rs          # GET /
│       └── users/
│           ├── index.get.rs      # GET /users
│           ├── index.post.rs     # POST /users
│           └── [id].get.rs       # GET /users/:id
```

#### `src/routes/index.get.rs`

```rust
use astrea::prelude::*;

#[route]
pub async fn handler(event: Event) -> Result<Response> {
    json(json!({ "message": "Hello, World!" }))
}
```

#### `src/routes/users/[id].get.rs`

```rust
use astrea::prelude::*;

#[route]
pub async fn handler(event: Event) -> Result<Response> {
    let id = get_param_required(&event, "id")?;
    json(json!({ "user_id": id }))
}
```

### 4. Write `main.rs`

```rust
mod routes {
    astrea::generate_routes!();
}

#[tokio::main]
async fn main() {
    let app = routes::create_router();
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    println!("Listening on http://localhost:3000");
    astrea::serve(listener, app).await.unwrap();
}
```

### 5. Run

```bash
cargo run
```

Done. You will see a beautiful startup log:

```text
┌─────────────────────────────────────────────────────────────────────┐
│                        🚀 Astrea Router                            │
├────────┬──────────────────────────────┬─────────────────────────────┤
│ Method │ Path                         │ Middleware                  │
├────────┼──────────────────────────────┼─────────────────────────────┤
│ GET    │ /                            │ (none)                      │
│ GET    │ /users                       │ (none)                      │
│ POST   │ /users                       │ (none)                      │
│ GET    │ /users/:id                   │ (none)                      │
└────────┴──────────────────────────────┴─────────────────────────────┘
✅ 4 route(s), 0 middleware scope(s) loaded
```

And `GET http://localhost:3000/` returns `{"message":"Hello, World!"}`.

---

## Route File Naming Convention

| File name | Route |
|---|---|
| `src/routes/index.get.rs` | `GET /` |
| `src/routes/users.get.rs` | `GET /users` |
| `src/routes/users/index.post.rs` | `POST /users` |
| `src/routes/users/[id].get.rs` | `GET /users/:id` |
| `src/routes/users/[id].delete.rs` | `DELETE /users/:id` |
| `src/routes/posts/[...slug].get.rs` | `GET /posts/*slug` (catch-all) |

**Rules:**
- File name format: `<name>.<method>.rs`
- `index` is a special name — it maps to the directory itself (no extra path segment)
- `[param]` → dynamic path parameter
- `[...param]` → catch-all parameter (matches everything after)

---

## Extracting Request Data

Astrea replaces complex Axum extractor signatures with simple function calls:

```rust
#[route]
pub async fn handler(event: Event, bytes: Bytes) -> Result<Response> {
    // Path parameters: /users/:id
    let id = get_param(&event, "id");                   // Option<&str>
    let id = get_param_required(&event, "id")?;          // &str (or 400 error)

    // Query parameters: /search?q=rust&page=2
    let q = get_query_param(&event, "q");                // Option<String>
    let all_query = get_query(&event);                   // &HashMap<String, String>

    // Request body (JSON)
    let body: MyStruct = get_body(&event, &bytes)?;      // deserialized struct

    // Headers
    let auth = get_header(&event, "authorization");      // Option<String>

    // Metadata
    let method = get_method(&event);                     // &Method
    let path = get_path(&event);                         // &str

    // Application state
    let db = get_state::<DatabasePool>(&event)?;         // your custom state

    json(json!({ "ok": true }))
}
```

---

## Response Helpers

```rust
// JSON (application/json)
json(json!({ "key": "value" }))?

// Plain text (text/plain)
text("Hello!")

// HTML (text/html)
html("<h1>Hello</h1>")

// Redirect (302 Found)
redirect("/login")?

// No Content (204)
no_content()

// Raw bytes
bytes(vec![0x89, 0x50, 0x4E, 0x47]).content_type("image/png")

// Streaming
stream(Body::from_stream(my_stream))
```

All responses support chaining:

```rust
json(data)?
    .status(StatusCode::CREATED)
    .header("X-Request-Id", "abc123")
```

---

## WebSockets & Server-Sent Events (SSE)

Astrea supports WebSockets and SSE natively via route attributes. Simply use `#[route(ws)]` or `#[route(sse)]` instead of `#[route]`.

### WebSockets (`#[route(ws)]`)

```rust
use astrea::prelude::*;
use astrea::ws::{WebSocket, Message};

#[route(ws)]
pub async fn handler(event: Event, mut socket: WebSocket) {
    // Receive and echo messages
    while let Some(Ok(msg)) = socket.recv().await {
        if let Message::Text(text) = msg {
            let _ = socket.send(Message::from(format!("Echo: {}", text.as_str()))).await;
        }
    }
}
```

### Server-Sent Events (`#[route(sse)]`)

```rust
use astrea::prelude::*;
use astrea::sse::{SseSender, SseEvent};
use std::time::Duration;

#[route(sse)]
pub async fn handler(event: Event, sender: SseSender) {
    let _ = sender.send(
        SseEvent::new()
            .event("greeting")
            .data("Hello from SSE!")
            .retry(Duration::from_secs(5))
    ).await;
}
```

---

## Error Handling

Return errors naturally — they become proper HTTP responses automatically:

```rust
#[route]
pub async fn handler(event: Event) -> Result<Response> {
    let id = get_param_required(&event, "id")?;       // 400 if missing

    if id == "0" {
        return Err(RouteError::not_found("User not found"));  // 404
    }

    // Third-party errors auto-convert to 500 via anyhow
    let data = some_fallible_operation()?;

    json(data)
}
```

Built-in error variants:

| Method | Status Code |
|---|---|
| `RouteError::bad_request(msg)` | 400 |
| `RouteError::unauthorized(msg)` | 401 |
| `RouteError::forbidden(msg)` | 403 |
| `RouteError::not_found(msg)` | 404 |
| `RouteError::conflict(msg)` | 409 |
| `RouteError::validation(msg)` | 422 |
| `RouteError::rate_limit(msg)` | 429 |
| `RouteError::custom(StatusCode, msg)` | any |
| `?` on any `anyhow`-compatible error | 500 |

All errors are returned as JSON: `{"error": "...", "status": 404}`.

---

## Middleware

Create `_middleware.rs` files anywhere in the `src/routes/` directory. They scope to the folder they live in + all subfolders.

```
src/routes/
├── _middleware.rs            # applies to ALL routes
├── api/
│   ├── _middleware.rs        # applies to /api/* (stacks on root)
│   ├── users.get.rs          # ← root + api middleware
│   └── public/
│       ├── _middleware.rs    # OVERRIDES parent middleware
│       └── health.get.rs    # ← public middleware only
```

### Extend mode (default) — stack on parent

```rust
// src/routes/_middleware.rs
use astrea::middleware::*;

pub fn middleware() -> Middleware {
    Middleware::new()
        .wrap(|router| {
            router
                .layer(tower_http::trace::TraceLayer::new_for_http())
                .layer(tower_http::cors::CorsLayer::permissive())
        })
}
```

### Override mode — replace parent middleware

```rust
// src/routes/api/public/_middleware.rs
use astrea::middleware::*;

pub fn middleware() -> Middleware {
    Middleware::override_parent()
        .wrap(|router| {
            router.layer(tower::limit::ConcurrencyLimitLayer::new(100))
        })
}
```

---

## OpenAPI (Optional)

Enable the `openapi` feature to get automatic API documentation:

```toml
[dependencies]
astrea = { version = "0.0.1", features = ["openapi"] }
```

Then merge the OpenAPI router:

```rust
let app = routes::create_router()
    .merge(astrea::openapi::router("My API", "1.0.0"));
```

This gives you:
- `GET /openapi.json` — the OpenAPI 3.0 spec
- `GET /swagger` — Swagger UI

---

## Application State

Share state across handlers (database pools, config, etc.):

```rust
#[derive(Clone)]
struct AppState {
    db: DatabasePool,
}

// In handler:
#[route]
pub async fn handler(event: Event) -> Result<Response> {
    let state = get_state::<AppState>(&event)?;
    // use state.db ...
}
```

---

## Full Example

```
my-api/
├── Cargo.toml
└── src/
    ├── main.rs
    └── routes/
        ├── _middleware.rs
        ├── index.get.rs
        └── api/
            ├── _middleware.rs
            ├── users.get.rs
            ├── users.post.rs
            └── users/
                ├── [id].get.rs
                ├── [id].put.rs
                └── [id].delete.rs
```

This generates:
- `GET /` — root page
- `GET /api/users` — list users
- `POST /api/users` — create user
- `GET /api/users/:id` — get user by ID
- `PUT /api/users/:id` — update user
- `DELETE /api/users/:id` — delete user

Root middleware → all routes. API middleware → `/api/*` routes.

---

## Why Astrea?

| | Astrea | Plain Axum |
|---|---|---|
| **Route definition** | Drop a file | Manual `.route()` calls |
| **Handler signature** | Always `(Event) -> Result<Response>` | Varies per extractor combo |
| **Parameter access** | `get_param(&event, "id")` | `Path(id): Path<String>` |
| **Error handling** | Built-in JSON errors | DIY |
| **Middleware** | File-based scoping | Manual nesting |
| **OpenAPI** | Auto-generated | Manual or third-party |

---

## AI Agent Support

Astrea provides a built-in guide for AI coding assistants. If you are using an AI agent (like Copilot, Cursor, or Claude) to help you build your application, point them to the [`agent.md`](./agent.md) file in the root of the repository. It contains framework-specific rules, architectural context, and coding conventions to ensure your AI assistant writes idiomatic Astrea code.

---

## Minimum Supported Rust Version

Rust **1.85** or later (edition 2024).

## License

MIT © [TNXG (Asahi Shiori)](https://github.com/TNXG)