hitbox-http 0.2.1

Cacheable HTTP Request and Response
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
use bytes::Bytes;
use hitbox::CacheableResponse;
use hitbox_http::{BufferedBody, CacheableHttpResponse};
use http::{HeaderValue, Response, StatusCode};
use http_body_util::Full;

type TestBody = BufferedBody<Full<Bytes>>;

async fn body_to_string(body: TestBody) -> String {
    let bytes = body.collect().await.unwrap();
    String::from_utf8_lossy(&bytes).to_string()
}

fn compare_responses(original: &Response<TestBody>, restored: &Response<TestBody>) -> Vec<String> {
    let mut differences = Vec::new();

    if original.status() != restored.status() {
        differences.push(format!(
            "Status code mismatch: expected {}, got {}",
            original.status(),
            restored.status()
        ));
    }

    for (name, value) in original.headers() {
        let restored_values: Vec<_> = restored.headers().get_all(name).iter().collect();
        if !restored_values.contains(&value) {
            differences.push(format!(
                "Header '{}' value mismatch: original has '{}', but not found in restored response",
                name,
                value.to_str().unwrap_or("<binary>")
            ));
        }
    }

    for (name, value) in restored.headers() {
        let original_values: Vec<_> = original.headers().get_all(name).iter().collect();
        if !original_values.contains(&value) {
            differences.push(format!(
                "Extra header in restored response: '{}' = '{}'",
                name,
                value.to_str().unwrap_or("<binary>")
            ));
        }
    }

    for name in original.headers().keys() {
        let original_count = original.headers().get_all(name).iter().count();
        let restored_count = restored.headers().get_all(name).iter().count();
        if original_count != restored_count {
            differences.push(format!(
                "Header '{}' count mismatch: original has {} values, restored has {} values",
                name, original_count, restored_count
            ));
        }
    }

    differences
}

async fn assert_responses_equal(original: Response<TestBody>, restored: Response<TestBody>) {
    let (original_parts, original_body) = original.into_parts();
    let (restored_parts, restored_body) = restored.into_parts();

    let original_bytes = original_body.collect().await.unwrap();
    let restored_bytes = restored_body.collect().await.unwrap();

    if original_bytes != restored_bytes {
        panic!(
            "Response body mismatch:\nExpected: {:?}\nGot: {:?}",
            String::from_utf8_lossy(&original_bytes),
            String::from_utf8_lossy(&restored_bytes)
        );
    }

    let original = Response::from_parts(
        original_parts,
        BufferedBody::Complete(Some(original_bytes.clone())),
    );
    let restored =
        Response::from_parts(restored_parts, BufferedBody::Complete(Some(restored_bytes)));

    let differences = compare_responses(&original, &restored);

    if !differences.is_empty() {
        panic!(
            "Response comparison failed with {} differences:\n{}",
            differences.len(),
            differences.join("\n")
        );
    }
}

/// Full serialization roundtrip: Response -> Cacheable -> Serializable -> bytes -> Serializable -> Cacheable -> Response
async fn roundtrip_test(response: Response<TestBody>) -> Response<TestBody> {
    let cacheable = CacheableHttpResponse::from_response(response);

    let cache_policy = cacheable.into_cached().await;
    let serializable = match cache_policy {
        hitbox::CachePolicy::Cacheable(s) => s,
        hitbox::CachePolicy::NonCacheable(_) => panic!("Expected cacheable"),
    };

    let serialized = bincode::serde::encode_to_vec(&serializable, bincode::config::standard())
        .expect("Failed to serialize");

    let (deserialized, _len): (_, _) =
        bincode::serde::decode_from_slice(&serialized, bincode::config::standard())
            .expect("Failed to deserialize");

    let cacheable_restored = CacheableHttpResponse::<Full<Bytes>>::from_cached(deserialized).await;

    cacheable_restored.into_response()
}

#[tokio::test]
async fn test_basic_response() {
    let original = Response::builder()
        .status(200)
        .header("content-type", "application/json")
        .body(BufferedBody::Passthrough(Full::new(Bytes::from("{}"))))
        .unwrap();

    let original_clone = Response::builder()
        .status(200)
        .header("content-type", "application/json")
        .body(BufferedBody::Passthrough(Full::new(Bytes::from("{}"))))
        .unwrap();

    let restored = roundtrip_test(original).await;

    assert_responses_equal(original_clone, restored).await;
}

#[tokio::test]
async fn test_multiple_header_values() {
    let mut original = Response::builder()
        .status(200)
        .header("content-type", "application/json")
        .body(BufferedBody::Passthrough(Full::new(Bytes::from(
            r#"{"status":"ok"}"#,
        ))))
        .unwrap();

    let headers = original.headers_mut();
    headers.append(
        "set-cookie",
        HeaderValue::from_static("session=abc123; Path=/"),
    );
    headers.append(
        "set-cookie",
        HeaderValue::from_static("token=xyz789; Secure"),
    );
    headers.append("set-cookie", HeaderValue::from_static("user_id=42"));

    let mut original_clone = Response::builder()
        .status(200)
        .header("content-type", "application/json")
        .body(BufferedBody::Passthrough(Full::new(Bytes::from(
            r#"{"status":"ok"}"#,
        ))))
        .unwrap();
    let headers_clone = original_clone.headers_mut();
    headers_clone.append(
        "set-cookie",
        HeaderValue::from_static("session=abc123; Path=/"),
    );
    headers_clone.append(
        "set-cookie",
        HeaderValue::from_static("token=xyz789; Secure"),
    );
    headers_clone.append("set-cookie", HeaderValue::from_static("user_id=42"));

    let restored = roundtrip_test(original).await;

    assert_responses_equal(original_clone, restored).await;
}

#[tokio::test]
async fn test_special_header_values() {
    let original = Response::builder()
        .status(200)
        .header("x-empty", "")
        .header("x-whitespace", "  value  ")
        .header("x-special", "value-with-dash_and_underscore")
        .body(BufferedBody::Passthrough(Full::new(Bytes::from("test"))))
        .unwrap();

    let restored = roundtrip_test(original).await;

    assert_eq!(restored.headers().get("x-empty").unwrap(), "");
    assert_eq!(restored.headers().get("x-whitespace").unwrap(), "  value  ");
    assert_eq!(
        restored.headers().get("x-special").unwrap(),
        "value-with-dash_and_underscore"
    );
}

#[tokio::test]
async fn test_different_status_codes() {
    let test_cases = vec![
        (200, "OK"),
        (201, "Created"),
        (204, "No Content"),
        (301, "Moved Permanently"),
        (302, "Found"),
        (304, "Not Modified"),
        (400, "Bad Request"),
        (404, "Not Found"),
        (500, "Internal Server Error"),
        (503, "Service Unavailable"),
    ];

    for (code, body) in test_cases {
        let original = Response::builder()
            .status(code)
            .header("content-type", "text/plain")
            .body(BufferedBody::Passthrough(Full::new(Bytes::from(body))))
            .unwrap();

        let restored = roundtrip_test(original).await;

        assert_eq!(
            restored.status().as_u16(),
            code,
            "Status code mismatch for {}",
            code
        );
        let restored_body = body_to_string(restored.into_body()).await;
        assert_eq!(restored_body, body, "Body mismatch for status {}", code);
    }
}

#[tokio::test]
async fn test_different_body_types() {
    let original = Response::builder()
        .status(204)
        .body(BufferedBody::Passthrough(Full::new(Bytes::from(""))))
        .unwrap();
    let restored = roundtrip_test(original).await;
    assert_eq!(body_to_string(restored.into_body()).await, "");

    let original = Response::builder()
        .status(200)
        .body(BufferedBody::Passthrough(Full::new(Bytes::from("small"))))
        .unwrap();
    let restored = roundtrip_test(original).await;
    assert_eq!(body_to_string(restored.into_body()).await, "small");

    let large_body = "x".repeat(10000);
    let large_body_bytes = Bytes::from(large_body.clone());
    let original = Response::builder()
        .status(200)
        .body(BufferedBody::Passthrough(Full::new(large_body_bytes)))
        .unwrap();
    let restored = roundtrip_test(original).await;
    assert_eq!(body_to_string(restored.into_body()).await, large_body);
}

#[tokio::test]
async fn test_binary_data() {
    let binary_data = vec![0u8, 1, 2, 255, 254, 128, 127];
    let original = Response::builder()
        .status(200)
        .header("content-type", "application/octet-stream")
        .body(BufferedBody::Passthrough(Full::new(Bytes::from(
            binary_data,
        ))))
        .unwrap();

    let restored = roundtrip_test(original).await;

    assert_eq!(restored.status(), StatusCode::OK);
    assert_eq!(
        restored.headers().get("content-type").unwrap(),
        "application/octet-stream"
    );
}

#[tokio::test]
async fn test_no_extra_headers() {
    let original = Response::builder()
        .status(200)
        .body(BufferedBody::Passthrough(Full::new(Bytes::from("minimal"))))
        .unwrap();

    let restored = roundtrip_test(original).await;

    assert_eq!(restored.status(), StatusCode::OK);
    let body = body_to_string(restored.into_body()).await;
    assert_eq!(body, "minimal");
}

#[tokio::test]
async fn test_many_headers() {
    let mut builder = Response::builder().status(200);

    for i in 0..50 {
        builder = builder.header(format!("x-custom-{}", i), format!("value-{}", i));
    }

    let original = builder
        .body(BufferedBody::Passthrough(Full::new(Bytes::from(
            "many headers",
        ))))
        .unwrap();
    let original_header_count = original.headers().len();

    let restored = roundtrip_test(original).await;

    assert_eq!(restored.headers().len(), original_header_count);
    assert_eq!(restored.headers().get("x-custom-0").unwrap(), "value-0");
    assert_eq!(restored.headers().get("x-custom-25").unwrap(), "value-25");
    assert_eq!(restored.headers().get("x-custom-49").unwrap(), "value-49");

    let body = body_to_string(restored.into_body()).await;
    assert_eq!(body, "many headers");
}

#[tokio::test]
async fn test_long_header_values() {
    let long_value = "x".repeat(1000);

    let original = Response::builder()
        .status(200)
        .header("x-long-header", long_value.as_str())
        .body(BufferedBody::Passthrough(Full::new(Bytes::from("test"))))
        .unwrap();

    let restored = roundtrip_test(original).await;

    assert_eq!(
        restored.headers().get("x-long-header").unwrap(),
        long_value.as_str()
    );
}

#[tokio::test]
async fn test_common_headers() {
    let original = Response::builder()
        .status(200)
        .header("content-type", "application/json; charset=utf-8")
        .header("cache-control", "max-age=3600, public")
        .header("etag", "\"686897696a7c876b7e\"")
        .header("last-modified", "Wed, 21 Oct 2015 07:28:00 GMT")
        .header("vary", "Accept-Encoding")
        .header("server", "hitbox/1.0")
        .body(BufferedBody::Passthrough(Full::new(Bytes::from(
            r#"{"data":"test"}"#,
        ))))
        .unwrap();

    let restored = roundtrip_test(original).await;

    assert_eq!(
        restored.headers().get("content-type").unwrap(),
        "application/json; charset=utf-8"
    );
    assert_eq!(
        restored.headers().get("cache-control").unwrap(),
        "max-age=3600, public"
    );
    assert_eq!(
        restored.headers().get("etag").unwrap(),
        "\"686897696a7c876b7e\""
    );
    assert_eq!(
        restored.headers().get("last-modified").unwrap(),
        "Wed, 21 Oct 2015 07:28:00 GMT"
    );
    assert_eq!(restored.headers().get("vary").unwrap(), "Accept-Encoding");
    assert_eq!(restored.headers().get("server").unwrap(), "hitbox/1.0");

    let body = body_to_string(restored.into_body()).await;
    assert_eq!(body, r#"{"data":"test"}"#);
}

#[tokio::test]
async fn test_redirect_response() {
    let original = Response::builder()
        .status(302)
        .header("location", "https://example.com/new-location")
        .header("cache-control", "no-cache")
        .body(BufferedBody::Passthrough(Full::new(Bytes::from(""))))
        .unwrap();

    let restored = roundtrip_test(original).await;

    assert_eq!(restored.status(), StatusCode::FOUND);
    assert_eq!(
        restored.headers().get("location").unwrap(),
        "https://example.com/new-location"
    );
    assert_eq!(restored.headers().get("cache-control").unwrap(), "no-cache");
}

#[tokio::test]
async fn test_json_response_with_unicode() {
    let json_body = r#"{"message":"Hello δΈ–η•Œ 🌍","emoji":"πŸš€"}"#;

    let original = Response::builder()
        .status(200)
        .header("content-type", "application/json; charset=utf-8")
        .body(BufferedBody::Passthrough(Full::new(Bytes::from(json_body))))
        .unwrap();

    let restored = roundtrip_test(original).await;

    assert_eq!(restored.status(), StatusCode::OK);
    let body = body_to_string(restored.into_body()).await;
    assert_eq!(body, json_body);
}

#[tokio::test]
#[should_panic(expected = "Response comparison failed with")]
async fn test_comparison_detects_status_mismatch() {
    let original = Response::builder()
        .status(200)
        .body(BufferedBody::Passthrough(Full::new(Bytes::from("test"))))
        .unwrap();

    let different = Response::builder()
        .status(404)
        .body(BufferedBody::Passthrough(Full::new(Bytes::from("test"))))
        .unwrap();

    assert_responses_equal(original, different).await;
}

#[tokio::test]
#[should_panic(expected = "Response body mismatch")]
async fn test_comparison_detects_body_mismatch() {
    let original = Response::builder()
        .status(200)
        .body(BufferedBody::Passthrough(Full::new(Bytes::from(
            "original body",
        ))))
        .unwrap();

    let different = Response::builder()
        .status(200)
        .body(BufferedBody::Passthrough(Full::new(Bytes::from(
            "different body",
        ))))
        .unwrap();

    assert_responses_equal(original, different).await;
}

#[tokio::test]
#[should_panic(expected = "Response comparison failed with")]
async fn test_comparison_detects_header_mismatch() {
    let original = Response::builder()
        .status(200)
        .header("x-custom", "value1")
        .body(BufferedBody::Passthrough(Full::new(Bytes::from("test"))))
        .unwrap();

    let different = Response::builder()
        .status(200)
        .header("x-custom", "value2")
        .body(BufferedBody::Passthrough(Full::new(Bytes::from("test"))))
        .unwrap();

    assert_responses_equal(original, different).await;
}

#[tokio::test]
#[should_panic(expected = "count mismatch")]
async fn test_comparison_detects_multivalue_count_mismatch() {
    let mut original = Response::builder()
        .status(200)
        .body(BufferedBody::Passthrough(Full::new(Bytes::from("test"))))
        .unwrap();
    original
        .headers_mut()
        .append("set-cookie", HeaderValue::from_static("a=1"));
    original
        .headers_mut()
        .append("set-cookie", HeaderValue::from_static("b=2"));

    let mut different = Response::builder()
        .status(200)
        .body(BufferedBody::Passthrough(Full::new(Bytes::from("test"))))
        .unwrap();
    different
        .headers_mut()
        .append("set-cookie", HeaderValue::from_static("a=1"));

    assert_responses_equal(original, different).await;
}