rapina 0.11.0

A fast, type-safe web framework for Rust inspired by FastAPI
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
//! Integration tests for middleware functionality.

use http::StatusCode;
use rapina::middleware::{
    BodyLimitMiddleware, CompressionConfig, CorsConfig, RateLimitConfig, RateLimitMiddleware,
    TRACE_ID_HEADER, TimeoutMiddleware, TraceIdMiddleware,
};
use rapina::prelude::*;
use rapina::testing::TestClient;
use std::time::Duration;

#[tokio::test]
async fn test_middleware_execution() {
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(TraceIdMiddleware::new())
        .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "Hello!" }));

    let client = TestClient::new(app).await;
    let response = client.get("/").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    // TraceIdMiddleware should add x-trace-id header
    assert!(response.headers().get(TRACE_ID_HEADER).is_some());
}

#[tokio::test]
async fn test_trace_id_middleware_adds_header() {
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(TraceIdMiddleware::new())
        .router(Router::new().route(http::Method::GET, "/health", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;
    let response = client.get("/health").send().await;

    assert_eq!(response.status(), StatusCode::OK);

    let trace_id = response.headers().get(TRACE_ID_HEADER);
    assert!(trace_id.is_some());

    // Trace ID should be a valid UUID (36 characters)
    let trace_id_str = trace_id.unwrap().to_str().unwrap();
    assert_eq!(trace_id_str.len(), 36);
}

#[tokio::test]
async fn test_trace_id_unique_per_request() {
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(TraceIdMiddleware::new())
        .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;

    let response1 = client.get("/").send().await;
    let response2 = client.get("/").send().await;

    let trace_id1 = response1
        .headers()
        .get(TRACE_ID_HEADER)
        .unwrap()
        .to_str()
        .unwrap();
    let trace_id2 = response2
        .headers()
        .get(TRACE_ID_HEADER)
        .unwrap()
        .to_str()
        .unwrap();

    // Each request should have a unique trace ID
    assert_ne!(trace_id1, trace_id2);
}

#[tokio::test]
async fn test_timeout_middleware_passes_fast_request() {
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(TimeoutMiddleware::new(Duration::from_secs(5)))
        .router(
            Router::new().route(http::Method::GET, "/fast", |_, _, _| async {
                "fast response"
            }),
        );

    let client = TestClient::new(app).await;
    let response = client.get("/fast").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.text(), "fast response");
}

#[tokio::test]
async fn test_body_limit_middleware_allows_small_body() {
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(BodyLimitMiddleware::new(1024 * 1024)) // 1MB limit
        .router(
            Router::new().route(http::Method::POST, "/upload", |req, _, _| async move {
                use http_body_util::BodyExt;
                let body = req.into_body().collect().await.unwrap().to_bytes();
                format!("Received {} bytes", body.len())
            }),
        );

    let client = TestClient::new(app).await;
    let response = client.post("/upload").body("small payload").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    assert!(response.text().contains("13 bytes")); // "small payload" is 13 bytes
}

#[tokio::test]
async fn test_multiple_middlewares() {
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(TraceIdMiddleware::new())
        .middleware(TimeoutMiddleware::new(Duration::from_secs(30)))
        .middleware(BodyLimitMiddleware::new(1024 * 1024))
        .router(Router::new().route(http::Method::GET, "/multi", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;
    let response = client.get("/multi").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.text(), "ok");
    // TraceIdMiddleware should still add the header
    assert!(response.headers().get(TRACE_ID_HEADER).is_some());
}

#[tokio::test]
async fn test_middleware_order_trace_id_first() {
    // When TraceIdMiddleware is first, it should wrap the entire request
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(TraceIdMiddleware::new())
        .middleware(TimeoutMiddleware::default())
        .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;
    let response = client.get("/").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    assert!(response.headers().get(TRACE_ID_HEADER).is_some());
}

#[tokio::test]
async fn test_middleware_with_post_request() {
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(TraceIdMiddleware::new())
        .router(
            Router::new().route(http::Method::POST, "/data", |req, _, _| async move {
                use http_body_util::BodyExt;
                let body = req.into_body().collect().await.unwrap().to_bytes();
                String::from_utf8_lossy(&body).to_string()
            }),
        );

    let client = TestClient::new(app).await;
    let response = client
        .post("/data")
        .json(&serde_json::json!({"key": "value"}))
        .send()
        .await;

    assert_eq!(response.status(), StatusCode::OK);
    assert!(response.headers().get(TRACE_ID_HEADER).is_some());
    assert!(response.text().contains("key"));
}

#[tokio::test]
async fn test_default_timeout_middleware() {
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(TimeoutMiddleware::default()) // 30 second default
        .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;
    let response = client.get("/").send().await;

    assert_eq!(response.status(), StatusCode::OK);
}

#[tokio::test]
async fn test_default_body_limit_middleware() {
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(BodyLimitMiddleware::default()) // 1MB default
        .router(Router::new().route(http::Method::POST, "/", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;
    let response = client.post("/").body("test").send().await;

    assert_eq!(response.status(), StatusCode::OK);
}

#[tokio::test]
async fn test_middleware_preserves_response_body() {
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(TraceIdMiddleware::new())
        .router(
            Router::new().route(http::Method::GET, "/json", |_, _, _| async {
                Json(serde_json::json!({
                    "status": "success",
                    "data": [1, 2, 3]
                }))
            }),
        );

    let client = TestClient::new(app).await;
    let response = client.get("/json").send().await;

    assert_eq!(response.status(), StatusCode::OK);

    let json: serde_json::Value = response.json();
    assert_eq!(json["status"], "success");
    assert_eq!(json["data"], serde_json::json!([1, 2, 3]));
}

#[tokio::test]
async fn test_middleware_with_error_response() {
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(TraceIdMiddleware::new())
        .router(
            Router::new().route(http::Method::GET, "/error", |_, _, _| async {
                Error::not_found("resource not found")
            }),
        );

    let client = TestClient::new(app).await;
    let response = client.get("/error").send().await;

    assert_eq!(response.status(), StatusCode::NOT_FOUND);
    // Middleware should still add trace ID even for errors
    assert!(response.headers().get(TRACE_ID_HEADER).is_some());
}

#[tokio::test]
async fn test_middleware_with_404() {
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(TraceIdMiddleware::new())
        .router(Router::new().route(http::Method::GET, "/exists", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;
    let response = client.get("/does-not-exist").send().await;

    assert_eq!(response.status(), StatusCode::NOT_FOUND);
    // Middleware runs even for non-existent routes
    assert!(response.headers().get(TRACE_ID_HEADER).is_some());
}

#[tokio::test]
async fn test_cors_preflight_returns_204() {
    let app = Rapina::new()
        .with_introspection(false)
        .with_cors(CorsConfig::permissive())
        .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;

    let response = client
        .request(http::Method::OPTIONS, "/")
        .header("Origin", "http://userapina.com")
        .send()
        .await;

    assert_eq!(response.status(), StatusCode::NO_CONTENT);
    assert!(
        response
            .headers()
            .get("access-control-allow-origin")
            .is_some()
    );
    assert!(
        response
            .headers()
            .get("access-control-allow-methods")
            .is_some()
    );
}

#[tokio::test]
async fn test_cors_rejects_disallowed_origin() {
    let app = Rapina::new()
        .with_introspection(false)
        .with_cors(CorsConfig::with_origins(vec![
            "http://userapina.com".to_string(),
        ]))
        .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;
    let response = client
        .request(http::Method::GET, "/")
        .header("Origin", "http://evil.com")
        .send()
        .await;

    // Request goes through but NO Access-Control-Allow-Origin header
    assert_eq!(response.status(), StatusCode::OK);
    assert!(
        response
            .headers()
            .get("access-control-allow-origin")
            .is_none()
    );
}

#[tokio::test]
async fn test_cors_allows_matching_origin() {
    let app = Rapina::new()
        .with_introspection(false)
        .with_cors(CorsConfig::with_origins(vec![
            "http://userapina.com".to_string(),
        ]))
        .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;
    let response = client
        .request(http::Method::GET, "/")
        .header("Origin", "http://userapina.com")
        .send()
        .await;

    assert_eq!(response.status(), StatusCode::OK);
    let origin_header = response.headers().get("access-control-allow-origin");
    assert!(origin_header.is_some());
    assert_eq!(
        origin_header.unwrap().to_str().unwrap(),
        "http://userapina.com"
    );
}

#[tokio::test]
async fn test_cors_permissive_returns_wildcard() {
    let app = Rapina::new()
        .with_introspection(false)
        .with_cors(CorsConfig::permissive())
        .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;

    let response = client
        .request(http::Method::OPTIONS, "/")
        .header("Origin", "http://any.com")
        .send()
        .await;

    let origin_header = response.headers().get("access-control-allow-origin");
    assert_eq!(origin_header.unwrap().to_str().unwrap(), "*");
}

#[tokio::test]
async fn test_rate_limit_allows_under_limit() {
    let app = Rapina::new()
        .with_introspection(false)
        .with_rate_limit(RateLimitConfig::new(100.0, 10)) // 10 burst
        .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;

    // Should allow requests under the burst limit
    for _ in 0..5 {
        let response = client.get("/").send().await;
        assert_eq!(response.status(), StatusCode::OK);
    }
}

#[tokio::test]
async fn test_rate_limit_returns_429_when_exceeded() {
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(RateLimitMiddleware::new(RateLimitConfig::new(1.0, 2))) // 2 burst
        .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;

    // First two requests allowed (burst)
    assert_eq!(client.get("/").send().await.status(), StatusCode::OK);
    assert_eq!(client.get("/").send().await.status(), StatusCode::OK);

    // Third request should be rate limited
    let response = client.get("/").send().await;
    assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
}

#[tokio::test]
async fn test_rate_limit_includes_retry_after_header() {
    let app = Rapina::new()
        .with_introspection(false)
        .with_rate_limit(RateLimitConfig::new(1.0, 1)) // 1 burst, 1 req/sec
        .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;

    // First request allowed
    assert_eq!(client.get("/").send().await.status(), StatusCode::OK);

    // Second request rate limited with Retry-After
    let response = client.get("/").send().await;
    assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);

    let retry_after = response.headers().get("retry-after");
    assert!(retry_after.is_some());

    let retry_secs: u64 = retry_after.unwrap().to_str().unwrap().parse().unwrap();
    assert!(retry_secs >= 1);
}

#[tokio::test]
async fn test_rate_limit_returns_json_error() {
    let app = Rapina::new()
        .with_introspection(false)
        .enable_rfc7807_errors()
        .rfc7807_base_uri("https://userapina.com/errors/")
        .with_rate_limit(RateLimitConfig::new(1.0, 1))
        .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;

    // Exhaust the limit
    client.get("/").send().await;

    // Check the error response body
    let response = client.get("/").send().await;
    assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);

    let json: serde_json::Value = response.json();
    assert_eq!(json["type"], "https://userapina.com/errors/rate-limited");
    assert_eq!(json["title"], "Rate Limited");
    assert_eq!(json["detail"], "too many requests");
    assert!(json["trace_id"].is_string());
}

#[tokio::test]
async fn test_rate_limit_per_minute_convenience() {
    // Test the per_minute convenience constructor
    let app = Rapina::new()
        .with_introspection(false)
        .with_rate_limit(RateLimitConfig::per_minute(60)) // 1 req/sec, 60 burst
        .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;

    // Should allow 60 rapid requests (burst capacity)
    for i in 0..60 {
        let response = client.get("/").send().await;
        assert_eq!(
            response.status(),
            StatusCode::OK,
            "Request {} should succeed",
            i + 1
        );
    }

    // 61st should be rate limited
    let response = client.get("/").send().await;
    assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
}

#[tokio::test]
async fn test_compression_gzip() {
    let large_body = "hello from rapina ".repeat(100);
    let body_clone = large_body.clone();

    let app = Rapina::new()
        .with_introspection(false)
        .with_compression(CompressionConfig::default())
        .router(Router::new().route(http::Method::GET, "/", move |_, _, _| {
            let body = body_clone.clone();
            async move { body }
        }));

    let client = TestClient::new(app).await;
    let response = client
        .get("/")
        .header("Accept-Encoding", "gzip")
        .send()
        .await;

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.headers().get("content-encoding").unwrap(), "gzip");
    assert_eq!(response.headers().get("vary").unwrap(), "Accept-Encoding");
}

#[tokio::test]
async fn test_compression_skips_small_response() {
    let app = Rapina::new()
        .with_introspection(false)
        .with_compression(CompressionConfig::default())
        .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "small" }));

    let client = TestClient::new(app).await;
    let response = client
        .get("/")
        .header("Accept-Encoding", "gzip")
        .send()
        .await;

    assert_eq!(response.status(), StatusCode::OK);
    assert!(response.headers().get("content-encoding").is_none());
}

#[tokio::test]
async fn test_compression_skips_without_accept_encoding() {
    let large_body = "hello from rapina ".repeat(100);
    let body_clone = large_body.clone();

    let app = Rapina::new()
        .with_introspection(false)
        .with_compression(CompressionConfig::default())
        .router(Router::new().route(http::Method::GET, "/", move |_, _, _| {
            let body = body_clone.clone();
            async move { body }
        }));

    let client = TestClient::new(app).await;
    let response = client.get("/").send().await;

    assert_eq!(response.status(), StatusCode::OK);
    assert!(response.headers().get("content-encoding").is_none());
}

#[tokio::test]
async fn test_trace_id_middleware_preserves_incoming_trace_id() {
    let app = Rapina::new()
        .with_introspection(false)
        .middleware(TraceIdMiddleware::new())
        .router(Router::new().route(http::Method::GET, "/health", |_, _, _| async { "ok" }));

    let client = TestClient::new(app).await;
    let custom_trace_id = "my-custom-trace-id-123";

    let response = client
        .get("/health")
        .header("x-trace-id", custom_trace_id)
        .send()
        .await;

    assert_eq!(response.status(), StatusCode::OK);

    let header_value = response.headers().get(TRACE_ID_HEADER).unwrap();
    assert_eq!(header_value.to_str().unwrap(), custom_trace_id);
}