1use std::collections::HashMap;
29use std::hash::{DefaultHasher, Hash, Hasher};
30use std::sync::{Arc, Mutex};
31
32use serde_json::Value;
33
34use crate::{GenericSchemaAdapter, SchemaAdapter};
35
36#[derive(Debug)]
54pub struct SchemaCache {
55 adapter: Arc<dyn SchemaAdapter>,
56 entries: Mutex<HashMap<CacheKey, Value>>,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60enum CacheKey {
61 Bound(u64),
62 Legacy { schema: u64, normalized: u64 },
63}
64
65fn hash_canonical(value: &Value, hasher: &mut DefaultHasher) {
74 match value {
75 Value::Null => 0u8.hash(hasher),
76 Value::Bool(flag) => {
77 1u8.hash(hasher);
78 flag.hash(hasher);
79 }
80 Value::Number(number) => {
81 2u8.hash(hasher);
82 number.to_string().hash(hasher);
88 }
89 Value::String(text) => {
90 3u8.hash(hasher);
91 text.hash(hasher);
92 }
93 Value::Array(items) => {
94 4u8.hash(hasher);
95 items.len().hash(hasher);
96 for item in items {
97 hash_canonical(item, hasher);
98 }
99 }
100 Value::Object(members) => {
101 5u8.hash(hasher);
102 members.len().hash(hasher);
103 let mut entries: Vec<(&String, &Value)> = members.iter().collect();
104 entries.sort_unstable_by_key(|(key, _)| *key);
105 for (key, member) in entries {
106 key.hash(hasher);
107 hash_canonical(member, hasher);
108 }
109 }
110 }
111}
112
113impl SchemaCache {
114 pub fn new() -> Self {
129 Self::for_adapter(Arc::new(GenericSchemaAdapter))
130 }
131
132 pub fn for_adapter(adapter: Arc<dyn SchemaAdapter>) -> Self {
147 Self { adapter, entries: Mutex::new(HashMap::new()) }
148 }
149
150 pub fn normalize(&self, schema: &Value) -> Value {
170 let key = CacheKey::Bound(Self::hash_schema(schema));
171 if let Some(cached) = self.lock_entries().get(&key) {
172 return cached.clone();
173 }
174 let normalized = self.adapter.normalize_schema(schema.clone());
177 self.lock_entries().entry(key).or_insert(normalized).clone()
178 }
179
180 fn lock_entries(&self) -> std::sync::MutexGuard<'_, HashMap<CacheKey, Value>> {
181 self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
182 }
183
184 #[deprecated(
191 note = "bind the adapter with SchemaCache::for_adapter and call SchemaCache::normalize"
192 )]
193 pub fn get_or_normalize(&self, schema: &Value, adapter: &dyn SchemaAdapter) -> Value {
194 let schema_hash = Self::hash_schema(schema);
195 let normalized = adapter.normalize_schema(schema.clone());
196 let key =
197 CacheKey::Legacy { schema: schema_hash, normalized: Self::hash_schema(&normalized) };
198 self.lock_entries().entry(key).or_insert(normalized).clone()
199 }
200
201 pub fn clear(&self) {
223 self.lock_entries().clear();
224 }
225
226 pub fn len(&self) -> usize {
228 self.lock_entries().len()
229 }
230
231 pub fn is_empty(&self) -> bool {
233 self.len() == 0
234 }
235
236 fn hash_schema(schema: &Value) -> u64 {
246 let mut hasher = DefaultHasher::new();
247 hash_canonical(schema, &mut hasher);
248 hasher.finish()
249 }
250}
251
252impl Default for SchemaCache {
253 fn default() -> Self {
254 Self::new()
255 }
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261 use serde_json::json;
262 use std::sync::atomic::{AtomicUsize, Ordering};
263
264 use crate::GenericSchemaAdapter;
265
266 fn generic_cache() -> SchemaCache {
267 SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter))
268 }
269
270 #[derive(Debug)]
271 struct TaggedAdapter(&'static str);
272
273 impl SchemaAdapter for TaggedAdapter {
274 fn normalize_schema(&self, mut schema: Value) -> Value {
275 schema
276 .as_object_mut()
277 .expect("test schema should be an object")
278 .insert("normalized_by".to_string(), Value::String(self.0.to_string()));
279 schema
280 }
281 }
282
283 #[derive(Debug)]
284 struct CountingAdapter(Arc<AtomicUsize>);
285
286 impl SchemaAdapter for CountingAdapter {
287 fn normalize_schema(&self, schema: Value) -> Value {
288 self.0.fetch_add(1, Ordering::Relaxed);
289 schema
290 }
291 }
292
293 #[test]
294 fn test_cache_returns_normalized_schema() {
295 let cache = generic_cache();
296 let schema = json!({
297 "$schema": "http://json-schema.org/draft-07/schema#",
298 "type": "object",
299 "properties": { "name": { "type": "string" } }
300 });
301
302 let result = cache.normalize(&schema);
303 assert!(result.get("$schema").is_none());
304 assert_eq!(result["type"], "object");
305 }
306
307 #[test]
308 fn test_cache_returns_same_result_on_repeated_calls() {
309 let cache = generic_cache();
310 let schema = json!({
311 "type": "object",
312 "properties": { "x": { "type": "integer", "const": 42 } }
313 });
314
315 let first = cache.normalize(&schema);
316 let second = cache.normalize(&schema);
317 assert_eq!(first, second);
318 }
319
320 #[test]
321 fn repeated_calls_only_invoke_the_bound_adapter_once() {
322 let calls = Arc::new(AtomicUsize::new(0));
323 let cache = SchemaCache::for_adapter(Arc::new(CountingAdapter(Arc::clone(&calls))));
324 let schema = json!({"type": "string"});
325
326 cache.normalize(&schema);
327 cache.normalize(&schema);
328
329 assert_eq!(calls.load(Ordering::Relaxed), 1);
330 }
331
332 #[test]
333 fn adapter_instances_cannot_share_entries() {
334 let schema = json!({"type": "object"});
335 let alpha = SchemaCache::for_adapter(Arc::new(TaggedAdapter("alpha")));
336 let beta = SchemaCache::for_adapter(Arc::new(TaggedAdapter("beta")));
337
338 assert_eq!(alpha.normalize(&schema)["normalized_by"], "alpha");
339 assert_eq!(beta.normalize(&schema)["normalized_by"], "beta");
340 assert_eq!(alpha.len(), 1);
341 assert_eq!(beta.len(), 1);
342 }
343
344 #[test]
345 #[allow(deprecated)]
346 fn deprecated_api_keeps_adapter_results_separate() {
347 let cache = SchemaCache::new();
348 let schema = json!({"type": "object"});
349
350 let alpha = cache.get_or_normalize(&schema, &TaggedAdapter("alpha"));
351 let beta = cache.get_or_normalize(&schema, &TaggedAdapter("beta"));
352
353 assert_eq!(alpha["normalized_by"], "alpha");
354 assert_eq!(beta["normalized_by"], "beta");
355 assert_eq!(cache.len(), 2);
356 }
357
358 #[test]
359 fn test_cache_stores_entries() {
360 let cache = generic_cache();
361
362 assert!(cache.is_empty());
363 assert_eq!(cache.len(), 0);
364
365 let schema1 = json!({"type": "string"});
366 let schema2 = json!({"type": "number"});
367
368 cache.normalize(&schema1);
369 assert_eq!(cache.len(), 1);
370
371 cache.normalize(&schema2);
372 assert_eq!(cache.len(), 2);
373
374 cache.normalize(&schema1);
376 assert_eq!(cache.len(), 2);
377 }
378
379 #[test]
380 fn test_cache_clear_removes_all_entries() {
381 let cache = generic_cache();
382
383 cache.normalize(&json!({"type": "string"}));
384 cache.normalize(&json!({"type": "number"}));
385 assert_eq!(cache.len(), 2);
386
387 cache.clear();
388 assert!(cache.is_empty());
389 }
390
391 #[test]
392 fn test_cache_different_schemas_produce_different_entries() {
393 let cache = generic_cache();
394
395 let schema_a = json!({"type": "string", "format": "hostname"});
396 let schema_b = json!({"type": "string", "format": "email"});
397
398 let result_a = cache.normalize(&schema_a);
399 let result_b = cache.normalize(&schema_b);
400
401 assert!(result_a.get("format").is_none());
403 assert_eq!(result_b["format"], "email");
404 assert_eq!(cache.len(), 2);
405 }
406
407 #[test]
408 fn test_cache_new_is_empty() {
409 let cache = SchemaCache::new();
410 assert!(cache.is_empty());
411 assert_eq!(cache.len(), 0);
412 }
413
414 #[test]
415 fn test_cache_default_is_empty() {
416 let cache = SchemaCache::default();
417 assert!(cache.is_empty());
418 }
419
420 #[test]
421 fn test_cache_handles_empty_schema() {
422 let cache = generic_cache();
423 let schema = json!({});
424
425 let result = cache.normalize(&schema);
426 assert_eq!(result, json!({}));
427 assert_eq!(cache.len(), 1);
428 }
429
430 #[test]
431 fn test_cache_handles_null_schema() {
432 let cache = generic_cache();
433 let schema = Value::Null;
434
435 let result = cache.normalize(&schema);
436 assert_eq!(result, Value::Null);
438 assert_eq!(cache.len(), 1);
439 }
440
441 #[test]
444 fn key_order_does_not_create_a_second_entry() {
445 let cache = generic_cache();
446
447 cache.normalize(&json!({ "type": "object", "properties": { "a": {}, "b": {} } }));
448 cache.normalize(&json!({ "properties": { "b": {}, "a": {} }, "type": "object" }));
449
450 assert_eq!(cache.len(), 1, "key order must not change a schema's identity");
451 }
452
453 #[test]
454 fn genuinely_different_schemas_keep_separate_entries() {
455 let cache = generic_cache();
456
457 cache.normalize(&json!({ "type": "string" }));
458 cache.normalize(&json!({ "type": "integer" }));
459
460 assert_eq!(cache.len(), 2);
461 }
462
463 #[test]
466 fn unusual_property_names_stay_distinct() {
467 let cache = generic_cache();
468
469 cache.normalize(&json!({ "properties": { "a/b": {} } }));
470 cache.normalize(&json!({ "properties": { "a~b": {} } }));
471
472 assert_eq!(cache.len(), 2);
473 }
474
475 #[test]
477 fn a_string_and_a_number_hash_differently() {
478 let cache = generic_cache();
479
480 cache.normalize(&json!({ "const": "1" }));
481 cache.normalize(&json!({ "const": 1 }));
482
483 assert_eq!(cache.len(), 2);
484 }
485
486 #[test]
496 fn numbers_are_identified_by_their_written_form() {
497 let cache = generic_cache();
498
499 cache.normalize(&json!({ "const": 5 }));
500 cache.normalize(&json!({ "const": 5.0 }));
501
502 assert_eq!(cache.len(), 2);
503 }
504
505 #[derive(Debug)]
507 struct GatedAdapter(std::sync::Mutex<std::sync::mpsc::Receiver<()>>);
508
509 impl SchemaAdapter for GatedAdapter {
510 fn normalize_schema(&self, schema: Value) -> Value {
511 if schema.get("slow").is_some() {
512 let _ = self.0.lock().map(|release| release.recv());
513 }
514 schema
515 }
516 }
517
518 #[test]
519 fn a_slow_normalization_does_not_block_other_schemas() {
520 let (release, gate) = std::sync::mpsc::channel();
521 let cache =
522 Arc::new(SchemaCache::for_adapter(Arc::new(GatedAdapter(std::sync::Mutex::new(gate)))));
523 let slow = {
524 let cache = cache.clone();
525 std::thread::spawn(move || cache.normalize(&json!({"slow": true})))
526 };
527 std::thread::sleep(std::time::Duration::from_millis(50));
528
529 let (done, finished) = std::sync::mpsc::channel();
530 let fast = {
531 let cache = cache.clone();
532 std::thread::spawn(move || {
533 let _ = done.send(cache.normalize(&json!({"type": "string"})));
534 })
535 };
536 let result = finished.recv_timeout(std::time::Duration::from_secs(5));
537 release.send(()).expect("release the slow normalization");
538 slow.join().expect("slow normalization thread");
539 fast.join().expect("fast normalization thread");
540
541 assert_eq!(result, Ok(json!({"type": "string"})));
542 assert_eq!(cache.len(), 2);
543 }
544}