Skip to content

Commit aacf920

Browse files
committed
Merge branch 'main' of https://github.com/Tuntii/RustAPI
2 parents d82d815 + 59c1b9a commit aacf920

File tree

6 files changed

+146
-23
lines changed

6 files changed

+146
-23
lines changed

crates/rustapi-extras/src/oauth2/tokens.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,7 @@ mod property_tests {
362362
// Remaining time should be close to expires_in (within a few seconds)
363363
let remaining_secs = remaining.unwrap().as_secs();
364364
prop_assert!(remaining_secs <= expires_in_secs);
365-
prop_assert!(remaining_secs >= expires_in_secs - 2); // Allow 2 sec tolerance
365+
prop_assert!(remaining_secs >= expires_in_secs.saturating_sub(2)); // Allow 2 sec tolerance
366366
}
367367

368368
/// Property 16: Token response builder pattern works correctly

docs/GETTING_STARTED.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,14 @@ Add RustAPI to your `Cargo.toml`:
2222

2323
```toml
2424
[dependencies]
25-
rustapi-rs = "0.1.9"
25+
rustapi-rs = "0.1.233"
2626
```
2727

2828
Or with specific features:
2929

3030
```toml
3131
[dependencies]
32-
rustapi-rs = { version = "0.1.9", features = ["jwt", "cors", "toon", "ws", "view"] }
32+
rustapi-rs = { version = "0.1.233", features = ["jwt", "cors", "toon", "ws", "view"] }
3333
```
3434

3535
### Available Features
@@ -358,7 +358,7 @@ ApiError::internal("message") // 500
358358
### CORS
359359

360360
```toml
361-
rustapi-rs = { version = "0.1.4", features = ["cors"] }
361+
rustapi-rs = { version = "0.1.233", features = ["cors"] }
362362
```
363363

364364
```rust
@@ -379,7 +379,7 @@ RustApi::new()
379379
### JWT Authentication
380380

381381
```toml
382-
rustapi-rs = { version = "0.1.4", features = ["jwt"] }
382+
rustapi-rs = { version = "0.1.233", features = ["jwt"] }
383383
```
384384

385385
```rust
@@ -409,7 +409,7 @@ async fn protected(user: AuthUser<Claims>) -> Json<Response> {
409409
### Rate Limiting
410410

411411
```toml
412-
rustapi-rs = { version = "0.1.4", features = ["rate-limit"] }
412+
rustapi-rs = { version = "0.1.233", features = ["rate-limit"] }
413413
```
414414

415415
```rust
@@ -427,7 +427,7 @@ RustApi::new()
427427
## TOON Format (LLM Optimization)
428428

429429
```toml
430-
rustapi-rs = { version = "0.1.4", features = ["toon"] }
430+
rustapi-rs = { version = "0.1.233", features = ["toon"] }
431431
```
432432

433433
```rust
@@ -458,7 +458,7 @@ Response includes token counting headers:
458458
Real-time bidirectional communication:
459459

460460
```toml
461-
rustapi-rs = { version = "0.1.4", features = ["ws"] }
461+
rustapi-rs = { version = "0.1.233", features = ["ws"] }
462462
```
463463

464464
```rust
@@ -495,7 +495,7 @@ websocat ws://localhost:8080/ws
495495
Server-side HTML rendering with Tera:
496496

497497
```toml
498-
rustapi-rs = { version = "0.1.4", features = ["view"] }
498+
rustapi-rs = { version = "0.1.233", features = ["view"] }
499499
```
500500

501501
Create a template file `templates/index.html`:
@@ -697,7 +697,7 @@ struct AnyBody { ... }
697697
Check that the `swagger-ui` feature is enabled (it's on by default):
698698

699699
```toml
700-
rustapi-rs = { version = "0.1.9", features = ["swagger-ui"] }
700+
rustapi-rs = { version = "0.1.233", features = ["swagger-ui"] }
701701
```
702702

703703
### CLI Commands Not Working

docs/cookbook/src/crates/rustapi_extras.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ This crate is a collection of production-ready middleware. Everything is behind
1313
| `cors` | `CorsLayer` |
1414
| `csrf` | `CsrfLayer`, `CsrfToken` extractor |
1515
| `audit` | `AuditStore`, `AuditLogger` |
16+
| `insight` | `InsightLayer`, `InsightStore` |
1617
| `rate-limit` | `RateLimitLayer` |
1718

1819
## Middleware Usage
@@ -82,3 +83,38 @@ async fn delete_user(
8283
}
8384
```
8485

86+
## Traffic Insight
87+
88+
The `insight` feature provides powerful real-time traffic analysis and debugging capabilities without external dependencies. It is designed to be low-overhead and privacy-conscious.
89+
90+
```toml
91+
[dependencies]
92+
rustapi-extras = { version = "0.1", features = ["insight"] }
93+
```
94+
95+
### Setup
96+
97+
```rust
98+
use rustapi_extras::insight::{InsightLayer, InMemoryInsightStore, InsightConfig};
99+
use std::sync::Arc;
100+
101+
let store = Arc::new(InMemoryInsightStore::new());
102+
let config = InsightConfig::default();
103+
104+
let app = RustApi::new()
105+
.layer(InsightLayer::new(config, store.clone()));
106+
```
107+
108+
### Accessing Data
109+
110+
You can inspect the collected data (e.g., via an admin dashboard):
111+
112+
```rust
113+
#[rustapi_rs::get("/admin/insights")]
114+
async fn get_insights(State(store): State<Arc<InMemoryInsightStore>>) -> Json<InsightStats> {
115+
// Returns aggregated stats like req/sec, error rates, p99 latency
116+
Json(store.get_stats().await)
117+
}
118+
```
119+
120+
The `InsightStore` trait allows you to implement custom backends (e.g., ClickHouse or Elasticsearch) if you need long-term retention.

docs/cookbook/src/crates/rustapi_jobs.md

Lines changed: 75 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,87 @@
55

66
## Background Processing
77

8-
Long-running tasks shouldn't block HTTP requests. `rustapi-jobs` provides a robust queue system.
8+
Long-running tasks shouldn't block HTTP requests. `rustapi-jobs` provides a robust queue system that can run in-memory or be backed by Redis/Postgres.
9+
10+
## Usage Example
11+
12+
Here is how to set up a simple background job queue using the in-memory backend.
13+
14+
### 1. Define the Job
15+
16+
Jobs are simple structs that implement `Serialize` and `Deserialize`.
17+
18+
```rust
19+
use serde::{Deserialize, Serialize};
20+
use rustapi_jobs::{Job, JobContext, Result};
21+
use std::sync::Arc;
22+
23+
#[derive(Serialize, Deserialize, Debug, Clone)]
24+
struct EmailJob {
25+
to: String,
26+
subject: String,
27+
body: String,
28+
}
29+
30+
// Implement the Job trait to define how to process it
31+
#[async_trait::async_trait]
32+
impl Job for EmailJob {
33+
const NAME: &'static str = "email_job";
34+
35+
async fn run(&self, _ctx: JobContext) -> Result<()> {
36+
println!("Sending email to {} with subject: {}", self.to, self.subject);
37+
// Simulate work
38+
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
39+
Ok(())
40+
}
41+
}
42+
```
43+
44+
### 2. Configure the Queue
45+
46+
In your `main` function, initialize the queue and start the worker.
947

1048
```rust
11-
// Define a job
12-
#[derive(Serialize, Deserialize)]
13-
struct EmailJob { to: String }
49+
use rustapi_jobs::{JobQueue, InMemoryBackend, EnqueueOptions};
50+
51+
#[tokio::main]
52+
async fn main() -> Result<(), Box<dyn std::error::Error>> {
53+
// 1. Create the backend
54+
let backend = InMemoryBackend::new();
55+
56+
// 2. Create the queue
57+
let queue = JobQueue::new(backend);
1458

15-
// Enqueue it
16-
queue.push(EmailJob { to: "alice@example.com" }).await;
59+
// 3. Register the job type
60+
queue.register_job::<EmailJob>();
61+
62+
// 4. Start the worker in the background
63+
let worker_queue = queue.clone();
64+
tokio::spawn(async move {
65+
worker_queue.start_workers().await;
66+
});
67+
68+
// 5. Enqueue a job
69+
queue.enqueue(EmailJob {
70+
to: "user@example.com".into(),
71+
subject: "Welcome!".into(),
72+
body: "Thanks for joining.".into(),
73+
}).await?;
74+
75+
Ok(())
76+
}
1777
```
1878

1979
## Backends
2080

21-
- **Memory**: Great for development and testing.
22-
- **Redis**: High throughput persistence.
23-
- **Postgres**: Transactional reliability (acid).
81+
- **Memory**: Great for development and testing. Zero infrastructure required.
82+
- **Redis**: High throughput persistence. Recommended for production.
83+
- **Postgres**: Transactional reliability (ACID). Best if you cannot lose jobs.
84+
85+
## Reliability Features
2486

25-
## Reliability
87+
The worker system includes built-in reliability features:
2688

27-
The worker system features:
28-
- **Exponential Backoff**: Automatic retries for failing jobs.
29-
- **Dead Letter Queue**: Poison jobs are isolated for manual inspection.
89+
- **Exponential Backoff**: Automatically retries failing jobs with increasing delays.
90+
- **Dead Letter Queue (DLQ)**: "Poison" jobs that fail repeatedly are isolated for manual inspection.
91+
- **Concurrency Control**: Limit the number of concurrent workers to prevent overloading your system.

docs/cookbook/src/getting_started/installation.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,21 @@ Verify your installation:
2525
cargo-rustapi --version
2626
```
2727

28+
## Adding to an Existing Project
29+
30+
If you prefer not to use the CLI, you can add RustAPI to your `Cargo.toml` manually:
31+
32+
```bash
33+
cargo add rustapi-rs@0.1.233
34+
```
35+
36+
Or add this to your `Cargo.toml`:
37+
38+
```toml
39+
[dependencies]
40+
rustapi-rs = "0.1.233"
41+
```
42+
2843
## Editor Setup
2944

3045
For the best experience, we recommend **VS Code** with the **rust-analyzer** extension. This provides:

docs/cookbook/src/learning/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,16 @@ We maintain a comprehensive examples repository with **18 real-world projects**
1010

1111
🔗 **[rustapi-rs-examples](https://github.com/Tuntii/rustapi-rs-examples)** - Complete examples from hello-world to production microservices
1212

13+
### Cookbook Internal Path
14+
15+
If you prefer reading through documentation first, follow this path through the cookbook:
16+
17+
1. **Foundations**: Start with [Handlers & Extractors](../concepts/handlers.md) and [System Overview](../architecture/system_overview.md).
18+
2. **Core Crates**: Read about [rustapi-core](../crates/rustapi_core.md) and [rustapi-macros](../crates/rustapi_macros.md).
19+
3. **Building Blocks**: Try the [Creating Resources](../recipes/crud_resource.md) recipe.
20+
4. **Security**: Implement [JWT Authentication](../recipes/jwt_auth.md) and [CSRF Protection](../recipes/csrf_protection.md).
21+
5. **Advanced**: Explore [Performance Tuning](../recipes/high_performance.md) and [HTTP/3](../recipes/http3_quic.md).
22+
1323
### Why Use the Examples Repository?
1424

1525
| Benefit | Description |

0 commit comments

Comments
 (0)