reinhardt-utils 0.1.0-rc.22

Utility functions aggregator for Reinhardt
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
//! Cache control middleware
//!
//! Provides Cache-Control header management for static files with
//! configurable policies based on file types and patterns.

use async_trait::async_trait;
use hyper::header::HeaderName;
use reinhardt_core::exception::Result;
use reinhardt_http::{Handler, Middleware};
use reinhardt_http::{Request, Response};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

/// Cache control directive
#[derive(Debug, Clone, PartialEq)]
pub enum CacheDirective {
	/// public - Response may be cached by any cache
	Public,
	/// private - Response is for single user and should not be cached by shared caches
	Private,
	/// no-cache - Must revalidate with origin server before using cached copy
	NoCache,
	/// no-store - Response must not be cached anywhere
	NoStore,
	/// must-revalidate - Must revalidate stale resources
	MustRevalidate,
	/// proxy-revalidate - Like must-revalidate but only for shared caches
	ProxyRevalidate,
	/// immutable - Response will not change and can be cached permanently
	Immutable,
}

impl CacheDirective {
	fn as_str(&self) -> &str {
		match self {
			CacheDirective::Public => "public",
			CacheDirective::Private => "private",
			CacheDirective::NoCache => "no-cache",
			CacheDirective::NoStore => "no-store",
			CacheDirective::MustRevalidate => "must-revalidate",
			CacheDirective::ProxyRevalidate => "proxy-revalidate",
			CacheDirective::Immutable => "immutable",
		}
	}
}

/// Cache control policy for specific file types or patterns
#[derive(Debug, Clone)]
pub struct CachePolicy {
	/// Cache directives
	pub directives: Vec<CacheDirective>,
	/// Maximum age in seconds
	pub max_age: Option<Duration>,
	/// S-maxage (for shared caches) in seconds
	pub s_maxage: Option<Duration>,
	/// Vary header value
	pub vary: Option<String>,
}

impl CachePolicy {
	/// Create a new cache policy
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_utils::staticfiles::caching::{CachePolicy, CacheDirective};
	/// use std::time::Duration;
	///
	/// let policy = CachePolicy::new()
	///     .with_directive(CacheDirective::Public)
	///     .with_max_age(Duration::from_secs(31536000));
	/// ```
	pub fn new() -> Self {
		Self {
			directives: Vec::new(),
			max_age: None,
			s_maxage: None,
			vary: None,
		}
	}

	/// Add a cache directive
	pub fn with_directive(mut self, directive: CacheDirective) -> Self {
		self.directives.push(directive);
		self
	}

	/// Set max-age
	pub fn with_max_age(mut self, max_age: Duration) -> Self {
		self.max_age = Some(max_age);
		self
	}

	/// Set s-maxage
	pub fn with_s_maxage(mut self, s_maxage: Duration) -> Self {
		self.s_maxage = Some(s_maxage);
		self
	}

	/// Set Vary header
	pub fn with_vary(mut self, vary: String) -> Self {
		self.vary = Some(vary);
		self
	}

	/// Create a policy for long-term caching (1 year)
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_utils::staticfiles::caching::CachePolicy;
	///
	/// let policy = CachePolicy::long_term();
	/// ```
	pub fn long_term() -> Self {
		Self::new()
			.with_directive(CacheDirective::Public)
			.with_directive(CacheDirective::Immutable)
			.with_max_age(Duration::from_secs(31536000)) // 1 year
	}

	/// Create a policy for short-term caching (5 minutes)
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_utils::staticfiles::caching::CachePolicy;
	///
	/// let policy = CachePolicy::short_term();
	/// ```
	pub fn short_term() -> Self {
		Self::new()
			.with_directive(CacheDirective::Public)
			.with_directive(CacheDirective::MustRevalidate)
			.with_max_age(Duration::from_secs(300)) // 5 minutes
	}

	/// Create a policy that prevents caching
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_utils::staticfiles::caching::CachePolicy;
	///
	/// let policy = CachePolicy::no_cache();
	/// ```
	pub fn no_cache() -> Self {
		Self::new()
			.with_directive(CacheDirective::NoCache)
			.with_directive(CacheDirective::NoStore)
			.with_directive(CacheDirective::MustRevalidate)
	}

	/// Generate Cache-Control header value
	pub fn to_header_value(&self) -> String {
		let mut parts = Vec::new();

		// Add directives
		for directive in &self.directives {
			parts.push(directive.as_str().to_string());
		}

		// Add max-age
		if let Some(max_age) = self.max_age {
			parts.push(format!("max-age={}", max_age.as_secs()));
		}

		// Add s-maxage
		if let Some(s_maxage) = self.s_maxage {
			parts.push(format!("s-maxage={}", s_maxage.as_secs()));
		}

		parts.join(", ")
	}
}

impl Default for CachePolicy {
	fn default() -> Self {
		Self::new()
	}
}

/// Cache control middleware configuration
#[derive(Debug, Clone)]
pub struct CacheControlConfig {
	/// Whether the middleware is enabled
	pub enabled: bool,
	/// Default cache policy
	pub default_policy: CachePolicy,
	/// File type specific policies (extension -> policy)
	pub type_policies: HashMap<String, CachePolicy>,
	/// Pattern-based policies (regex pattern -> policy)
	pub pattern_policies: Vec<(String, CachePolicy)>,
}

impl CacheControlConfig {
	/// Create a new configuration with sensible defaults
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_utils::staticfiles::caching::CacheControlConfig;
	///
	/// let config = CacheControlConfig::new();
	/// ```
	pub fn new() -> Self {
		let mut config = Self {
			enabled: true,
			default_policy: CachePolicy::short_term(),
			type_policies: HashMap::new(),
			pattern_policies: Vec::new(),
		};

		// Set up common file type policies
		config
			.type_policies
			.insert("css".to_string(), CachePolicy::long_term());
		config
			.type_policies
			.insert("js".to_string(), CachePolicy::long_term());
		config
			.type_policies
			.insert("woff".to_string(), CachePolicy::long_term());
		config
			.type_policies
			.insert("woff2".to_string(), CachePolicy::long_term());
		config
			.type_policies
			.insert("ttf".to_string(), CachePolicy::long_term());
		config
			.type_policies
			.insert("eot".to_string(), CachePolicy::long_term());
		config
			.type_policies
			.insert("png".to_string(), CachePolicy::long_term());
		config
			.type_policies
			.insert("jpg".to_string(), CachePolicy::long_term());
		config
			.type_policies
			.insert("jpeg".to_string(), CachePolicy::long_term());
		config
			.type_policies
			.insert("gif".to_string(), CachePolicy::long_term());
		config
			.type_policies
			.insert("svg".to_string(), CachePolicy::long_term());
		config
			.type_policies
			.insert("webp".to_string(), CachePolicy::long_term());
		config
			.type_policies
			.insert("ico".to_string(), CachePolicy::long_term());
		config
			.type_policies
			.insert("wasm".to_string(), CachePolicy::long_term());

		// HTML files should revalidate more frequently
		config
			.type_policies
			.insert("html".to_string(), CachePolicy::short_term());

		config
	}

	/// Disable caching
	pub fn disabled() -> Self {
		Self {
			enabled: false,
			default_policy: CachePolicy::no_cache(),
			type_policies: HashMap::new(),
			pattern_policies: Vec::new(),
		}
	}

	/// Set policy for a file type
	pub fn with_type_policy(mut self, extension: String, policy: CachePolicy) -> Self {
		self.type_policies.insert(extension, policy);
		self
	}

	/// Set default policy
	pub fn with_default_policy(mut self, policy: CachePolicy) -> Self {
		self.default_policy = policy;
		self
	}

	/// Get policy for a given path
	pub(crate) fn get_policy(&self, path: &str) -> &CachePolicy {
		// Try extension-based matching first
		if let Some(extension) = path.rsplit('.').next()
			&& let Some(policy) = self.type_policies.get(extension)
		{
			return policy;
		}

		// Try pattern-based matching
		for (pattern, policy) in &self.pattern_policies {
			if let Ok(regex) = regex::Regex::new(pattern)
				&& regex.is_match(path)
			{
				return policy;
			}
		}

		// Return default policy
		&self.default_policy
	}
}

impl Default for CacheControlConfig {
	fn default() -> Self {
		Self::new()
	}
}

/// Cache control middleware
///
/// # Examples
///
/// ```
/// use reinhardt_utils::staticfiles::caching::{CacheControlMiddleware, CacheControlConfig};
/// use std::sync::Arc;
///
/// let config = CacheControlConfig::new();
/// let middleware = Arc::new(CacheControlMiddleware::new(config));
/// ```
pub struct CacheControlMiddleware {
	config: CacheControlConfig,
}

impl CacheControlMiddleware {
	/// Create a new cache control middleware
	pub fn new(config: CacheControlConfig) -> Self {
		Self { config }
	}

	/// Create with default configuration
	pub fn default_config() -> Self {
		Self::new(CacheControlConfig::new())
	}
}

#[async_trait]
impl Middleware for CacheControlMiddleware {
	async fn process(&self, request: Request, handler: Arc<dyn Handler>) -> Result<Response> {
		// Skip if disabled
		if !self.config.enabled {
			return handler.handle(request).await;
		}

		// Get path before moving request
		let path = request.uri.path().to_string();

		// Convert errors to responses so post-processing always runs,
		// even when invoked outside MiddlewareChain. (#3244)
		let mut response = match handler.handle(request).await {
			Ok(resp) => resp,
			Err(e) => Response::from(e),
		};

		// Only add Cache-Control for successful responses
		if !response.status.is_success() {
			return Ok(response);
		}

		// Get appropriate policy for this path
		let policy = self.config.get_policy(&path);

		// Add Cache-Control header
		// These header name/value parses use known-valid static strings, so expect() is appropriate
		let cache_control_header: HeaderName = "cache-control"
			.parse()
			.expect("valid header name: cache-control");
		response.headers.insert(
			cache_control_header,
			policy
				.to_header_value()
				.parse()
				.expect("valid header value for cache-control"),
		);

		// Add Vary header if specified
		if let Some(vary) = &policy.vary {
			let vary_header: HeaderName = "vary".parse().expect("valid header name: vary");
			if let Ok(vary_value) = vary.parse() {
				response.headers.insert(vary_header, vary_value);
			} else {
				tracing::warn!("Invalid Vary header value: {}", vary);
			}
		}

		Ok(response)
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use bytes::Bytes;
	use hyper::{HeaderMap, Method, StatusCode, Version};

	struct TestHandler {
		status: StatusCode,
	}

	impl TestHandler {
		fn ok() -> Self {
			Self {
				status: StatusCode::OK,
			}
		}

		fn not_found() -> Self {
			Self {
				status: StatusCode::NOT_FOUND,
			}
		}
	}

	#[async_trait]
	impl Handler for TestHandler {
		async fn handle(&self, _request: Request) -> Result<Response> {
			Ok(Response::new(self.status).with_body(Bytes::from("test")))
		}
	}

	#[tokio::test]
	async fn test_cache_policy_long_term() {
		let policy = CachePolicy::long_term();
		let header_value = policy.to_header_value();

		assert_eq!(header_value, "public, immutable, max-age=31536000");
	}

	#[tokio::test]
	async fn test_cache_policy_short_term() {
		let policy = CachePolicy::short_term();
		let header_value = policy.to_header_value();

		assert_eq!(header_value, "public, must-revalidate, max-age=300");
	}

	#[tokio::test]
	async fn test_cache_policy_no_cache() {
		let policy = CachePolicy::no_cache();
		let header_value = policy.to_header_value();

		assert_eq!(header_value, "no-cache, no-store, must-revalidate");
	}

	#[tokio::test]
	async fn test_css_file_gets_long_term_cache() {
		let config = CacheControlConfig::new();
		let middleware = Arc::new(CacheControlMiddleware::new(config));
		let handler = Arc::new(TestHandler::ok());

		let request = Request::builder()
			.method(Method::GET)
			.uri("/static/style.css")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = middleware.process(request, handler).await.unwrap();

		let cache_control = response
			.headers
			.get("cache-control")
			.unwrap()
			.to_str()
			.unwrap();
		assert_eq!(cache_control, "public, immutable, max-age=31536000");
	}

	#[tokio::test]
	async fn test_js_file_gets_long_term_cache() {
		let config = CacheControlConfig::new();
		let middleware = Arc::new(CacheControlMiddleware::new(config));
		let handler = Arc::new(TestHandler::ok());

		let request = Request::builder()
			.method(Method::GET)
			.uri("/static/app.js")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = middleware.process(request, handler).await.unwrap();

		let cache_control = response
			.headers
			.get("cache-control")
			.unwrap()
			.to_str()
			.unwrap();
		assert_eq!(cache_control, "public, immutable, max-age=31536000");
	}

	#[tokio::test]
	async fn test_html_file_gets_short_term_cache() {
		let config = CacheControlConfig::new();
		let middleware = Arc::new(CacheControlMiddleware::new(config));
		let handler = Arc::new(TestHandler::ok());

		let request = Request::builder()
			.method(Method::GET)
			.uri("/index.html")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = middleware.process(request, handler).await.unwrap();

		let cache_control = response
			.headers
			.get("cache-control")
			.unwrap()
			.to_str()
			.unwrap();
		assert_eq!(cache_control, "public, must-revalidate, max-age=300");
	}

	#[tokio::test]
	async fn test_image_files_get_long_term_cache() {
		let config = CacheControlConfig::new();
		let middleware = Arc::new(CacheControlMiddleware::new(config));
		let handler = Arc::new(TestHandler::ok());

		for ext in &["png", "jpg", "jpeg", "gif", "svg", "webp"] {
			let url = format!("/static/image.{}", ext);
			let request = Request::builder()
				.method(Method::GET)
				.uri(url.as_str())
				.version(Version::HTTP_11)
				.headers(HeaderMap::new())
				.body(Bytes::new())
				.build()
				.unwrap();

			let response = middleware.process(request, handler.clone()).await.unwrap();
			let cache_control = response
				.headers
				.get("cache-control")
				.unwrap()
				.to_str()
				.unwrap();
			assert_eq!(
				cache_control, "public, immutable, max-age=31536000",
				"Extension: {}",
				ext
			);
		}
	}

	#[tokio::test]
	async fn test_font_files_get_long_term_cache() {
		let config = CacheControlConfig::new();
		let middleware = Arc::new(CacheControlMiddleware::new(config));
		let handler = Arc::new(TestHandler::ok());

		for ext in &["woff", "woff2", "ttf", "eot"] {
			let url = format!("/static/font.{}", ext);
			let request = Request::builder()
				.method(Method::GET)
				.uri(url.as_str())
				.version(Version::HTTP_11)
				.headers(HeaderMap::new())
				.body(Bytes::new())
				.build()
				.unwrap();

			let response = middleware.process(request, handler.clone()).await.unwrap();
			let cache_control = response
				.headers
				.get("cache-control")
				.unwrap()
				.to_str()
				.unwrap();
			assert_eq!(
				cache_control, "public, immutable, max-age=31536000",
				"Extension: {}",
				ext
			);
		}
	}

	#[tokio::test]
	async fn test_unknown_extension_gets_default_policy() {
		let config = CacheControlConfig::new();
		let middleware = Arc::new(CacheControlMiddleware::new(config));
		let handler = Arc::new(TestHandler::ok());

		let request = Request::builder()
			.method(Method::GET)
			.uri("/static/file.unknown")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = middleware.process(request, handler).await.unwrap();

		let cache_control = response
			.headers
			.get("cache-control")
			.unwrap()
			.to_str()
			.unwrap();
		// Default policy is short_term
		assert_eq!(cache_control, "public, must-revalidate, max-age=300");
	}

	#[tokio::test]
	async fn test_custom_type_policy() {
		let config =
			CacheControlConfig::new().with_type_policy("txt".to_string(), CachePolicy::no_cache());
		let middleware = Arc::new(CacheControlMiddleware::new(config));
		let handler = Arc::new(TestHandler::ok());

		let request = Request::builder()
			.method(Method::GET)
			.uri("/static/file.txt")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = middleware.process(request, handler).await.unwrap();

		let cache_control = response
			.headers
			.get("cache-control")
			.unwrap()
			.to_str()
			.unwrap();
		assert_eq!(cache_control, "no-cache, no-store, must-revalidate");
	}

	#[tokio::test]
	async fn test_disabled_middleware() {
		let config = CacheControlConfig::disabled();
		let middleware = Arc::new(CacheControlMiddleware::new(config));
		let handler = Arc::new(TestHandler::ok());

		let request = Request::builder()
			.method(Method::GET)
			.uri("/static/style.css")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = middleware.process(request, handler).await.unwrap();

		// Should not have Cache-Control header
		assert!(!response.headers.contains_key("cache-control"));
	}

	#[tokio::test]
	async fn test_non_success_response_not_cached() {
		let config = CacheControlConfig::new();
		let middleware = Arc::new(CacheControlMiddleware::new(config));
		let handler = Arc::new(TestHandler::not_found());

		let request = Request::builder()
			.method(Method::GET)
			.uri("/static/nonexistent.css")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = middleware.process(request, handler).await.unwrap();

		// 404 responses should not get Cache-Control headers
		assert!(!response.headers.contains_key("cache-control"));
	}

	#[tokio::test]
	async fn test_vary_header() {
		let policy = CachePolicy::short_term().with_vary("Accept-Encoding".to_string());
		let config = CacheControlConfig::new().with_default_policy(policy);
		let middleware = Arc::new(CacheControlMiddleware::new(config));
		let handler = Arc::new(TestHandler::ok());

		let request = Request::builder()
			.method(Method::GET)
			.uri("/static/file.unknown")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = middleware.process(request, handler).await.unwrap();

		assert!(response.headers.contains_key("vary"));
		assert_eq!(
			response.headers.get("vary").unwrap().to_str().unwrap(),
			"Accept-Encoding"
		);
	}

	#[tokio::test]
	async fn test_s_maxage() {
		let policy = CachePolicy::new()
			.with_directive(CacheDirective::Public)
			.with_max_age(Duration::from_secs(300))
			.with_s_maxage(Duration::from_secs(3600));
		let header_value = policy.to_header_value();

		assert_eq!(header_value, "public, max-age=300, s-maxage=3600");
	}

	#[tokio::test]
	async fn test_wasm_file_gets_long_term_cache() {
		let config = CacheControlConfig::new();
		let middleware = Arc::new(CacheControlMiddleware::new(config));
		let handler = Arc::new(TestHandler::ok());

		let request = Request::builder()
			.method(Method::GET)
			.uri("/static/app.wasm")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = middleware.process(request, handler).await.unwrap();

		let cache_control = response
			.headers
			.get("cache-control")
			.unwrap()
			.to_str()
			.unwrap();
		assert_eq!(cache_control, "public, immutable, max-age=31536000");
	}

	#[tokio::test]
	async fn test_default_config_includes_wasm() {
		let config = CacheControlConfig::new();
		assert!(config.type_policies.contains_key("wasm"));
	}

	#[tokio::test]
	async fn test_multiple_directives() {
		let policy = CachePolicy::new()
			.with_directive(CacheDirective::Public)
			.with_directive(CacheDirective::MustRevalidate)
			.with_directive(CacheDirective::ProxyRevalidate)
			.with_max_age(Duration::from_secs(3600));
		let header_value = policy.to_header_value();

		assert_eq!(
			header_value,
			"public, must-revalidate, proxy-revalidate, max-age=3600"
		);
	}
}