hyperlite 0.1.0

Lightweight HTTP framework built on hyper, tokio, and tower
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
# Hyperlite

[![CI](https://github.com/kriyaetive/hyperlite/workflows/CI/badge.svg)](https://github.com/kriyaetive/hyperlite/actions)
[![Crates.io](https://img.shields.io/crates/v/hyperlite.svg)](https://crates.io/crates/hyperlite)
[![Documentation](https://docs.rs/hyperlite/badge.svg)](https://docs.rs/hyperlite)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Status: Beta](https://img.shields.io/badge/status-beta-orange.svg)](#project-status)

A lightweight, fast HTTP framework built on hyper, tokio, and tower.

> **Beta notice:** Hyperlite is still undergoing hardening. Expect breaking surface changes and perform a full security review before shipping production traffic through it.

## Overview
Hyperlite keeps you close to the metal while smoothing over the rough edges of building HTTP services with `hyper`. It targets teams that need full control of the HTTP layer without vendor lock-in or the churn that comes with higher-level frameworks. Hyperlite composes cleanly with the Tower ecosystem, making it straightforward to layer in middleware such as tracing, CORS, authentication, and rate limiting. Bring your own data structures, serialization, and error handling—Hyperlite stays out of the way.

## Project Status
Hyperlite is currently in **beta**. The API may change without notice as we gather feedback from early adopters, and the framework has not been through comprehensive production security reviews. Deploy behind proven edge infrastructure (TLS termination, WAF, rate limiting) and add defense-in-depth middleware before relying on it for sensitive workloads.

## Features
- ✅ Fast path-based routing via `matchit`
- ✅ Tower `Service` trait integration throughout
- ✅ Response builders and JSON helpers
- ✅ Server utilities and graceful shutdown
- 🚧 Type-safe request and response helpers
- 🚧 JSON serialization utilities
- 🚧 Middleware composition with Tower layers
- ✅ Request extraction utilities
- ✅ Comprehensive examples and guides

## Installation

Add hyperlite to your `Cargo.toml`:

```toml
[dependencies]
hyperlite = "0.1"

```

Or use cargo add:

```bash
cargo add hyperlite
```
## Router API

## Router API

### Creating a Router

```rust
#[derive(Clone)]
struct MyState { /* ... */ }

let router = Router::new(MyState { /* ... */ });
```

### Adding Routes

```rust
let router = Router::new(state)
	.route("/users", Method::GET, Arc::new(list_users))
	.route("/users", Method::POST, Arc::new(create_user))
	.route("/users/{id}", Method::GET, Arc::new(get_user));
```

### Handler Signature

```rust
async fn handler(
	req: Request<BoxBody>,
	state: Arc<YourState>,
) -> Result<Response<Full<Bytes>>, BoxError> {
	// ...
}
```

### Multiple Methods Per Path

```rust
let router = router
	.route("/api/resource", Method::GET, Arc::new(get_handler))
	.route("/api/resource", Method::POST, Arc::new(post_handler))
	.route("/api/resource", Method::PUT, Arc::new(put_handler));
```

## Response Builders

Hyperlite provides consistent JSON response helpers following a standard envelope pattern.

### Success Responses

```rust
use hyperlite::{success, BoxError};
use hyper::{Response, StatusCode};
use http_body_util::Full;
use bytes::Bytes;
use serde::Serialize;

#[derive(Serialize)]
struct User {
		id: u64,
		name: String,
}

async fn get_user() -> Result<Response<Full<Bytes>>, BoxError> {
		let user = User { id: 1, name: "Alice".to_string() };
		Ok(success(StatusCode::OK, user))
}
```

Response format:

```json
{
	"success": true,
	"data": { "id": 1, "name": "Alice" },
	"meta": {
		"timestamp": "2024-01-15T10:30:00Z"
	}
}
```

### Error Responses

```rust
use hyperlite::{failure, ApiError, BoxError};
use hyper::{Response, StatusCode};
use http_body_util::Full;
use bytes::Bytes;

async fn validate_input() -> Result<Response<Full<Bytes>>, BoxError> {
		let errors = vec![
				ApiError::new("VALIDATION_ERROR", "Email is required"),
				ApiError::new("VALIDATION_ERROR", "Password too short"),
		];
		Ok(failure(StatusCode::BAD_REQUEST, errors))
}
```

Response format:

```json
{
	"success": false,
	"errors": [
		{ "code": "VALIDATION_ERROR", "message": "Email is required" },
		{ "code": "VALIDATION_ERROR", "message": "Password too short" }
	],
	"meta": {
		"timestamp": "2024-01-15T10:30:00Z"
	}
}
```

### Not Found Responses

```rust
use hyperlite::{not_found, BoxError};
use hyper::{Response, StatusCode};
use http_body_util::Full;
use bytes::Bytes;

async fn get_resource() -> Result<Response<Full<Bytes>>, BoxError> {
		Ok(not_found("/api/users/999".to_string()))
}
```

### Empty Responses

```rust
use hyperlite::{empty, BoxError};
use hyper::{Response, StatusCode};
use http_body_util::Full;
use bytes::Bytes;

async fn delete_resource() -> Result<Response<Full<Bytes>>, BoxError> {
		// delete logic here
		Ok(empty(StatusCode::NO_CONTENT))
}
```

### Response Envelope Structure

```text
{
	success: boolean,
	data?: T,
	message?: string,
	errors?: ApiError[],
	meta: {
		timestamp: string,
		correlationId?: string
	}
}
```

## Server Setup

Hyperlite ships with a `serve()` helper that boots an HTTP server and shuts it
down gracefully when the process receives Ctrl+C or SIGTERM.

### Basic Server

```rust
use hyperlite::{Router, serve};
use hyper::Method;
use std::net::SocketAddr;

#[tokio::main]
async fn main() -> Result<(), hyperlite::BoxError> {
	let router = Router::new(state)
		.route("/hello", Method::GET, hello_handler);

	let addr: SocketAddr = "127.0.0.1:3000".parse().expect("invalid address");
	serve(addr, router).await
}
```

### With Tower Middleware

```rust
use hyperlite::{Router, serve};
use tower::ServiceBuilder;
use tower_http::{
	cors::CorsLayer,
	trace::TraceLayer,
};
use std::net::SocketAddr;

#[tokio::main]
async fn main() -> Result<(), hyperlite::BoxError> {
	let service = ServiceBuilder::new()
		.layer(TraceLayer::new_for_http())
		.layer(CorsLayer::permissive())
		.service(
			Router::new(state)
				.route("/api/users", Method::GET, list_users)
		);

	let addr: SocketAddr = "0.0.0.0:8080".parse().expect("invalid address");
	serve(addr, service).await
}
```

### Graceful Shutdown

- **Ctrl+C**: Stops accepting new connections and waits for in-flight requests
- **SIGTERM (Unix)**: Same graceful shutdown path as Ctrl+C
- **In-flight requests**: Allowed to finish before the server exits

### Address Formats

`serve()` accepts any type convertible into `SocketAddr`. Parse string addresses before
starting the server:

```rust
use std::net::SocketAddr;

let addr: SocketAddr = "127.0.0.1:3000".parse()?;
serve(addr, router).await?;
```

### HTTP Protocol Support

- ✅ HTTP/1.1
- 🚧 HTTP/2 (planned for a future release)

The current implementation uses Hyper's HTTP/1 connection builder for maximum
compatibility.

## Request Extraction

Hyperlite provides type-safe extractors for parsing request data.

### JSON Body Parsing

Parse JSON request bodies with automatic validation:

```rust
use hyperlite::{parse_json_body, success};
use serde::Deserialize;

#[derive(Deserialize)]
struct CreateUser {
	email: String,
	username: String,
	password: String,
}

async fn register(
	req: Request<BoxBody>,
	state: Arc<AppState>,
) -> Result<Response<Full<Bytes>>, BoxError> {
	let payload = parse_json_body::<CreateUser>(req).await?;
    
	// Validate and create user
	// payload.email, payload.username, payload.password
    
	Ok(success(StatusCode::CREATED, user))
}
```

**Features:**
- ✅ Content-Type validation (must be `application/json`)
- ✅ 1MB size limit (prevents DoS attacks)
- ✅ Descriptive error messages for invalid JSON
- ✅ Works with any serde-deserializable type

### Query Parameters

Parse URL query strings into typed structs:

```rust
use hyperlite::{query_params, success};
use serde::Deserialize;

#[derive(Deserialize)]
struct SearchParams {
	q: String,
	#[serde(default)]
	limit: Option<i64>,
	#[serde(default)]
	offset: Option<i64>,
}

async fn search(
	req: Request<BoxBody>,
	state: Arc<AppState>,
) -> Result<Response<Full<Bytes>>, BoxError> {
	let params = query_params::<SearchParams>(&req)?;
    
	// Use params.q, params.limit, params.offset
	let results = search_database(&params.q, params.limit, params.offset).await?;
    
	Ok(success(StatusCode::OK, results))
}
```

**Example URLs:**
- `/search?q=recipe&limit=10`
- `/search?q=pasta&limit=20&offset=40`

### Path Parameters

Extract dynamic segments from URL paths:

```rust
use hyperlite::{path_param, success};
use uuid::Uuid;

// Route: /users/{id}/posts/{post_id}
async fn get_post(
	req: Request<BoxBody>,
	state: Arc<AppState>,
) -> Result<Response<Full<Bytes>>, BoxError> {
	// Extract and parse path parameters
	let user_id: Uuid = path_param(&req, "id")?;
	let post_id: Uuid = path_param(&req, "post_id")?;
    
	let post = fetch_post(user_id, post_id).await?;
	Ok(success(StatusCode::OK, post))
}

// Register route with path parameters
let router = Router::new(state)
	.route("/users/{id}/posts/{post_id}", Method::GET, Arc::new(|req, state| {
		Box::pin(get_post(req, state))
	}));
```

**Alternative: Get all params as HashMap:**

```rust
use hyperlite::path_params;
use std::collections::HashMap;

async fn handler(req: Request<BoxBody>) -> Result<Response<Full<Bytes>>, BoxError> {
	let params: HashMap<String, String> = path_params(&req)?;
	let id = params.get("id").ok_or("Missing id")?;
	Ok(success(StatusCode::OK, data))
}
```

### Request Extensions

Extract typed data stored in request extensions (e.g., by middleware):

```rust
use hyperlite::{get_extension, success};
use uuid::Uuid;

// Auth middleware inserts user_id into extensions
async fn protected_handler(
	req: Request<BoxBody>,
	state: Arc<AppState>,
) -> Result<Response<Full<Bytes>>, BoxError> {
	// Extract user ID inserted by auth middleware
	let user_id = get_extension::<Uuid>(&req)?;
    
	let user_data = fetch_user_data(user_id).await?;
	Ok(success(StatusCode::OK, user_data))
}
```

### Error Handling

All extractors return `Result<T, BoxError>` with descriptive error messages:

- **JSON parsing**: "Invalid JSON: expected value at line 1 column 5"
- **Query params**: "Invalid query parameters: missing field `q`"
- **Path params**: "Path parameter 'id' not found"
- **Extensions**: "Extension of type uuid::Uuid not found"

Convert errors to HTTP responses in your handlers:

```rust
async fn handler(req: Request<BoxBody>) -> Result<Response<Full<Bytes>>, BoxError> {
	let payload = parse_json_body::<CreateUser>(req).await
		.map_err(|err| {
			// Log error and return user-friendly message
			tracing::error!("JSON parse error: {}", err);
			BoxError::from("Invalid request body")
		})?;
    
	Ok(success(StatusCode::OK, payload))
}
```

## Examples

Hyperlite ships with three progressively richer examples. Build and run them
directly from the workspace root.

### Hello World

Minimal server with a single route and JSON response envelope:

```bash
cargo run --example hello_world
```

Demonstrates basic routing, handler signatures, response builders, and graceful
shutdown. Test with:

```bash
curl http://127.0.0.1:3000/hello
```

### With State

Stateful routing that exercises every request extractor and shared application
context:

```bash
cargo run --example with_state
```

Learn how to parse JSON bodies, query strings, and path parameters while
mutating shared state safely. Useful curl helpers:

```bash
# Get service stats
curl http://127.0.0.1:3000/stats

# Create a new user
curl -X POST http://127.0.0.1:3000/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice","email":"alice@example.com"}'

# List users with pagination
curl "http://127.0.0.1:3000/users?limit=10&offset=0"

# Fetch a specific user
curl http://127.0.0.1:3000/users/6f9619ff-8b86-d011-b42d-00cf4fc964ff
```

### With Middleware

Production-style stack layering request IDs, tracing, CORS, and custom
middleware:

```bash
RUST_LOG=info cargo run --example with_middleware
```

Highlights Tower's `ServiceBuilder`, middleware ordering, and request ID
propagation. Try the following:

```bash
# Health check with aggregated request stats
curl http://127.0.0.1:3000/health

# Observe propagated request IDs
curl -v http://127.0.0.1:3000/protected

# Echo JSON payloads (CORS-enabled)
curl -X POST http://127.0.0.1:3000/echo \
  -H "Content-Type: application/json" \
  -d '{"test":"data"}'

# Execute a CORS preflight request
curl -X OPTIONS http://127.0.0.1:3000/echo \
  -H "Origin: http://localhost:3001" \
  -H "Access-Control-Request-Method: POST"
```

All examples support Ctrl+C for graceful shutdown. Consult the source files in
`examples/` for extensive inline commentary.

## Testing

Hyperlite includes a comprehensive test suite covering all core modules.

### Running Tests

Run all tests:
```bash
cargo test
```

Run tests for a specific module:
```bash
cargo test router_tests
cargo test response_tests
cargo test extract_tests
cargo test middleware_tests
```

Run with output:
```bash
cargo test -- --nocapture
```

Run ignored tests (integration tests that bind to ports):
```bash
cargo test -- --ignored
```

### Test Coverage

The test suite covers:
- **Router**: Route registration, path matching, method filtering, 404/405 handling, path parameters
-**Response Builders**: Envelope structure, JSON serialization, correlation IDs, error responses
-**Extractors**: JSON body parsing, query parameters, path parameters, extensions
-**Server**: ConnectionHandler body conversion (limited serve() testing)
-**Middleware**: Tower layer composition, CORS, request-id, custom middleware

### Test Organization

Tests are organized in the `tests/` directory:
- `test_helpers.rs` - Shared test utilities and helper functions
- `router_tests.rs` - Router module tests
- `response_tests.rs` - Response builder tests
- `extract_tests.rs` - Request extractor tests
- `server_tests.rs` - Server module tests
- `middleware_tests.rs` - Middleware integration tests

### Writing Tests

When contributing tests:
1. Use the helper functions from `test_helpers.rs` for consistency
2. Follow the existing test patterns (see examples in each test file)
3. Use `#[tokio::test]` for async tests
4. Use descriptive test names that explain what is being tested
5. Add comments explaining complex test scenarios

### Coverage Goals

The test suite aims for 80%+ code coverage on core functionality:
- Router: 90%+ (critical path)
- Response builders: 85%+
- Extractors: 85%+
- Server: 60%+ (limited due to signal handling complexity)
- Overall: 80%+

## Architecture
- **Router**: Tower `Service` that matches paths and dispatches to async handlers.
- **Handlers**: Async functions returning `hyper::Response` types.
- **Middleware**: Standard Tower layers for cross-cutting concerns.
- **Server**: Hyper server with graceful shutdown hooks and connection limits.

## Comparison
- **vs Axum**: More control, no macros, fewer implicit behaviors—but less ergonomic extractors.
- **vs Actix-web**: Simpler Tower-based stack—trades away built-in actor features.
- **vs Warp**: More explicit and debuggable—at the expense of more boilerplate.
- **vs raw Hyper**: Adds routing and middleware composition while staying close to primitives.

## Development
- `cargo build` – Build the library
- `cargo test` – Run the test suite
- `cargo test -- --nocapture` – Run tests with output
- `cargo test <module>` – Run a specific test module (for example `router_tests`)
- `cargo doc --open` – Generate and view documentation
- `cargo clippy` – Lint the codebase
- `cargo fmt` – Format the code
- `cargo run --example <name>` – Run a specific example (`hello_world`, `with_state`, `with_middleware`)
- `cargo build --examples` – Build all example binaries

## Roadmap
- Phase 1: ✅ Project setup and dependency scaffolding
- Phase 2: ✅ Core router implementation
- Phase 3: ✅ Response builders
- Phase 4: ✅ Server utilities
- Phase 5: ✅ Request extractors
- Phase 6: ✅ Documentation and examples

## License
Hyperlite is licensed under the MIT License. See `LICENSE` for details.

## Contributing
Contributions are welcome! Please read our [Contributing Guidelines](CONTRIBUTING.md) before submitting a pull request.

By contributing, you agree to abide by our Code of Conduct (included in CONTRIBUTING.md).

## Links

- [Documentation]https://docs.rs/hyperlite
- [Crates.io]https://crates.io/crates/hyperlite
- [Repository]https://github.com/kriyaetive/hyperlite
- [Changelog]CHANGELOG.md
- [Contributing]CONTRIBUTING.md
- [License]LICENSE