reinhardt-core 0.1.0

Core components for Reinhardt framework
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
//! Caching for negotiation results

use std::collections::HashMap;
use std::time::{Duration, Instant};

/// Cache key based on Accept header
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CacheKey {
	accept_header: String,
}

impl CacheKey {
	/// Creates a new CacheKey from Accept header
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::negotiation::cache::CacheKey;
	///
	/// let key = CacheKey::new("application/json");
	/// ```
	pub fn new(accept_header: impl Into<String>) -> Self {
		Self {
			accept_header: accept_header.into(),
		}
	}

	/// Creates a CacheKey from multiple headers
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::negotiation::cache::CacheKey;
	///
	/// let key = CacheKey::from_headers(&[
	///     ("Accept", "application/json"),
	///     ("Accept-Language", "en-US"),
	/// ]);
	/// ```
	pub fn from_headers(headers: &[(&str, &str)]) -> Self {
		let combined = headers
			.iter()
			.map(|(k, v)| format!("{}:{}", k, v))
			.collect::<Vec<_>>()
			.join(";");

		Self {
			accept_header: combined,
		}
	}
}

/// Cached negotiation result
#[derive(Debug, Clone)]
pub struct CacheEntry<T> {
	value: T,
	expires_at: Instant,
}

impl<T> CacheEntry<T> {
	/// Creates a new cache entry with TTL
	fn new(value: T, ttl: Duration) -> Self {
		Self {
			value,
			expires_at: Instant::now() + ttl,
		}
	}

	/// Checks if the entry has expired
	fn is_expired(&self) -> bool {
		Instant::now() > self.expires_at
	}
}

/// Cache for negotiation results
#[derive(Debug)]
pub struct NegotiationCache<T>
where
	T: Clone,
{
	cache: HashMap<CacheKey, CacheEntry<T>>,
	ttl: Duration,
	max_entries: usize,
}

impl<T> NegotiationCache<T>
where
	T: Clone,
{
	/// Creates a new NegotiationCache with default settings
	///
	/// Default TTL: 5 minutes, Max entries: 1000
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::negotiation::cache::NegotiationCache;
	/// use reinhardt_core::negotiation::MediaType;
	///
	/// let cache: NegotiationCache<MediaType> = NegotiationCache::new();
	/// ```
	pub fn new() -> Self {
		Self {
			cache: HashMap::new(),
			ttl: Duration::from_secs(300), // 5 minutes
			max_entries: 1000,
		}
	}

	/// Creates a cache with custom TTL
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::negotiation::cache::NegotiationCache;
	/// use reinhardt_core::negotiation::MediaType;
	/// use std::time::Duration;
	///
	/// let cache: NegotiationCache<MediaType> = NegotiationCache::with_ttl(
	///     Duration::from_secs(600)
	/// );
	/// ```
	pub fn with_ttl(ttl: Duration) -> Self {
		Self {
			cache: HashMap::new(),
			ttl,
			max_entries: 1000,
		}
	}

	/// Creates a cache with custom TTL and max entries
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::negotiation::cache::NegotiationCache;
	/// use reinhardt_core::negotiation::MediaType;
	/// use std::time::Duration;
	///
	/// let cache: NegotiationCache<MediaType> = NegotiationCache::with_config(
	///     Duration::from_secs(600),
	///     500
	/// );
	/// ```
	pub fn with_config(ttl: Duration, max_entries: usize) -> Self {
		Self {
			cache: HashMap::new(),
			ttl,
			max_entries,
		}
	}

	/// Gets a cached value if it exists and hasn't expired
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::negotiation::cache::{NegotiationCache, CacheKey};
	/// use reinhardt_core::negotiation::MediaType;
	///
	/// let mut cache: NegotiationCache<MediaType> = NegotiationCache::new();
	/// let key = CacheKey::new("application/json");
	/// let media_type = MediaType::new("application", "json");
	///
	/// cache.set(key.clone(), media_type.clone());
	///
	/// let result = cache.get(&key);
	/// assert!(result.is_some());
	/// assert_eq!(result.unwrap().subtype, "json");
	/// ```
	pub fn get(&mut self, key: &CacheKey) -> Option<T> {
		if let Some(entry) = self.cache.get(key) {
			if entry.is_expired() {
				self.cache.remove(key);
				return None;
			}
			return Some(entry.value.clone());
		}
		None
	}

	/// Sets a cached value
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::negotiation::cache::{NegotiationCache, CacheKey};
	/// use reinhardt_core::negotiation::MediaType;
	///
	/// let mut cache: NegotiationCache<MediaType> = NegotiationCache::new();
	/// let key = CacheKey::new("application/json");
	/// let media_type = MediaType::new("application", "json");
	///
	/// cache.set(key, media_type);
	/// ```
	pub fn set(&mut self, key: CacheKey, value: T) {
		// Evict oldest entries if cache is full
		if self.cache.len() >= self.max_entries {
			self.evict_oldest();
		}

		let entry = CacheEntry::new(value, self.ttl);
		self.cache.insert(key, entry);
	}

	/// Gets or computes a cached value
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::negotiation::cache::{NegotiationCache, CacheKey};
	/// use reinhardt_core::negotiation::MediaType;
	///
	/// let mut cache: NegotiationCache<MediaType> = NegotiationCache::new();
	/// let key = CacheKey::new("application/json");
	///
	/// let result = cache.get_or_compute(&key, || {
	///     MediaType::new("application", "json")
	/// });
	///
	/// assert_eq!(result.subtype, "json");
	///
	/// // Second call returns cached value
	/// let result2 = cache.get_or_compute(&key, || {
	///     unreachable!("Should not be called")
	/// });
	/// assert_eq!(result2.subtype, "json");
	/// ```
	pub fn get_or_compute<F>(&mut self, key: &CacheKey, compute: F) -> T
	where
		F: FnOnce() -> T,
	{
		if let Some(cached) = self.get(key) {
			return cached;
		}

		let value = compute();
		self.set(key.clone(), value.clone());
		value
	}

	/// Clears all expired entries
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::negotiation::cache::NegotiationCache;
	/// use reinhardt_core::negotiation::MediaType;
	///
	/// let mut cache: NegotiationCache<MediaType> = NegotiationCache::new();
	/// cache.clear_expired();
	/// ```
	pub fn clear_expired(&mut self) {
		self.cache.retain(|_, entry| !entry.is_expired());
	}

	/// Clears all entries
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::negotiation::cache::NegotiationCache;
	/// use reinhardt_core::negotiation::MediaType;
	///
	/// let mut cache: NegotiationCache<MediaType> = NegotiationCache::new();
	/// cache.clear();
	/// assert_eq!(cache.len(), 0);
	/// ```
	pub fn clear(&mut self) {
		self.cache.clear();
	}

	/// Returns the number of cached entries
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::negotiation::cache::{NegotiationCache, CacheKey};
	/// use reinhardt_core::negotiation::MediaType;
	///
	/// let mut cache: NegotiationCache<MediaType> = NegotiationCache::new();
	/// assert_eq!(cache.len(), 0);
	///
	/// let key = CacheKey::new("application/json");
	/// cache.set(key, MediaType::new("application", "json"));
	/// assert_eq!(cache.len(), 1);
	/// ```
	pub fn len(&self) -> usize {
		self.cache.len()
	}

	/// Checks if the cache is empty
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::negotiation::cache::NegotiationCache;
	/// use reinhardt_core::negotiation::MediaType;
	///
	/// let cache: NegotiationCache<MediaType> = NegotiationCache::new();
	/// assert!(cache.is_empty());
	/// ```
	pub fn is_empty(&self) -> bool {
		self.cache.is_empty()
	}

	/// Evicts the oldest entry (simple FIFO strategy)
	fn evict_oldest(&mut self) {
		if let Some(key) = self.cache.keys().next().cloned() {
			self.cache.remove(&key);
		}
	}
}

impl<T> Default for NegotiationCache<T>
where
	T: Clone,
{
	fn default() -> Self {
		Self::new()
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::negotiation::MediaType;

	#[test]
	fn test_cache_key_new() {
		let key = CacheKey::new("application/json");
		assert_eq!(key.accept_header, "application/json");
	}

	#[test]
	fn test_cache_key_from_headers() {
		let key =
			CacheKey::from_headers(&[("Accept", "application/json"), ("Accept-Language", "en-US")]);
		assert!(key.accept_header.contains("Accept:application/json"));
		assert!(key.accept_header.contains("Accept-Language:en-US"));
	}

	#[test]
	fn test_cache_get_set() {
		let mut cache: NegotiationCache<MediaType> = NegotiationCache::new();
		let key = CacheKey::new("application/json");
		let media_type = MediaType::new("application", "json");

		cache.set(key.clone(), media_type);

		let result = cache.get(&key);
		assert!(result.is_some());
		assert_eq!(result.unwrap().subtype, "json");
	}

	#[test]
	fn test_cache_get_or_compute() {
		let mut cache: NegotiationCache<MediaType> = NegotiationCache::new();
		let key = CacheKey::new("application/json");

		let result = cache.get_or_compute(&key, || MediaType::new("application", "json"));
		assert_eq!(result.subtype, "json");

		// Second call should use cached value
		let mut called = false;
		let result2 = cache.get_or_compute(&key, || {
			called = true;
			MediaType::new("application", "xml")
		});
		assert!(!called);
		assert_eq!(result2.subtype, "json");
	}

	#[test]
	fn test_cache_expiration() {
		let mut cache: NegotiationCache<MediaType> =
			NegotiationCache::with_ttl(Duration::from_millis(10));
		let key = CacheKey::new("application/json");
		let media_type = MediaType::new("application", "json");

		cache.set(key.clone(), media_type);

		// Should exist immediately
		assert!(cache.get(&key).is_some());

		// Wait for expiration
		std::thread::sleep(Duration::from_millis(20));

		// Should be expired
		assert!(cache.get(&key).is_none());
	}

	#[test]
	fn test_cache_clear() {
		let mut cache: NegotiationCache<MediaType> = NegotiationCache::new();
		let key = CacheKey::new("application/json");
		cache.set(key, MediaType::new("application", "json"));

		assert_eq!(cache.len(), 1);
		cache.clear();
		assert_eq!(cache.len(), 0);
	}

	#[test]
	fn test_cache_max_entries() {
		let mut cache: NegotiationCache<MediaType> = NegotiationCache::with_config(
			Duration::from_secs(300),
			2, // Max 2 entries
		);

		cache.set(CacheKey::new("key1"), MediaType::new("application", "json"));
		cache.set(CacheKey::new("key2"), MediaType::new("text", "html"));

		assert_eq!(cache.len(), 2);

		// Adding third entry should evict oldest
		cache.set(CacheKey::new("key3"), MediaType::new("application", "xml"));

		assert_eq!(cache.len(), 2);
	}
}