json-eval-rs 0.0.30

High-performance JSON Logic evaluator with schema validation and dependency tracking. Built on blazing-fast Rust engine.
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
# ParsedSchemaCache Documentation

## Overview

The `ParsedSchemaCache` is a built-in, thread-safe cache for storing and reusing `Arc<ParsedSchema>` instances. This enables high-performance scenarios where schemas are parsed once and reused across multiple evaluations.

## Features

- **Thread-safe**: Uses `Arc<RwLock<>>` for concurrent access
-**Caller-controlled**: You decide when to parse, cache, clear, and release memory
-**Flexible keys**: Use any string identifier for your cached schemas
-**Arc-based**: Cheap cloning via `Arc` reference counting
-**Global or local**: Use the built-in global cache or create your own instances
-**Zero-copy**: Cached schemas share memory across evaluations

## Use Cases

### 1. **Web Servers**
Parse schemas once at startup, cache them, and reuse for every request.

### 2. **Batch Processing**
Parse schema once, evaluate against thousands of data files.

### 3. **Multi-tenant Applications**
Cache schemas per tenant, reload when tenant schema changes.

### 4. **Schema Versioning**
Cache multiple versions of a schema simultaneously.

## API Reference

### Creating a Cache

```rust
use json_eval_rs::ParsedSchemaCache;

// Create a local cache instance
let cache = ParsedSchemaCache::new();

// Or use the global cache
use json_eval_rs::PARSED_SCHEMA_CACHE;
```

### Basic Operations

#### Insert
```rust
use json_eval_rs::{ParsedSchema, ParsedSchemaCache};
use std::sync::Arc;

let cache = ParsedSchemaCache::new();
let parsed = ParsedSchema::parse(schema_json)?;
cache.insert("my-schema".to_string(), Arc::new(parsed));
```

#### Get
```rust
if let Some(cached) = cache.get("my-schema") {
    // Use cached schema
    let mut eval = JSONEval::with_parsed_schema(cached, Some(context), None)?;
}
```

#### Remove
```rust
// Remove and return the schema
if let Some(removed) = cache.remove("my-schema") {
    println!("Removed schema");
}
```

#### Clear
```rust
// Remove all cached schemas
cache.clear();
```

### Advanced Operations

#### Check Existence
```rust
if cache.contains_key("my-schema") {
    println!("Schema exists in cache");
}
```

#### Get Cache Size
```rust
println!("Cache has {} entries", cache.len());
println!("Cache is empty: {}", cache.is_empty());
```

#### List All Keys
```rust
let keys = cache.keys();
for key in keys {
    println!("Cached schema: {}", key);
}
```

#### Get Statistics
```rust
let stats = cache.stats();
println!("{}", stats); // "ParsedSchemaCache: 3 entries (keys: schema1, schema2, schema3)"
```

#### Lazy Insertion
```rust
// Parse only if not already cached
let schema = cache.get_or_insert_with("my-schema", || {
    Arc::new(ParsedSchema::parse(schema_json).unwrap())
});
```

#### Batch Operations
```rust
// Insert multiple schemas at once
cache.insert_batch(vec![
    ("schema1".to_string(), Arc::new(parsed1)),
    ("schema2".to_string(), Arc::new(parsed2)),
]);

// Remove multiple schemas at once
let removed = cache.remove_batch(&["schema1".to_string(), "schema2".to_string()]);
```

## Usage Patterns

### Pattern 1: Application-Level Cache

```rust
use json_eval_rs::ParsedSchemaCache;
use std::sync::Arc;

struct MyApp {
    schema_cache: ParsedSchemaCache,
}

impl MyApp {
    fn new() -> Self {
        Self {
            schema_cache: ParsedSchemaCache::new(),
        }
    }
    
    fn load_schema(&self, key: &str, json: &str) -> Result<(), String> {
        let parsed = ParsedSchema::parse(json)?;
        self.schema_cache.insert(key.to_string(), Arc::new(parsed));
        Ok(())
    }
    
    fn evaluate(&self, schema_key: &str, data: &str) -> Result<String, String> {
        let cached = self.schema_cache.get(schema_key)
            .ok_or("Schema not found in cache")?;
        
        let mut eval = JSONEval::with_parsed_schema(cached, None, None)?;
        eval.evaluate(data, None)?;
        
        Ok(serde_json::to_string(&eval.get_evaluated_schema(false)).unwrap())
    }
}
```

### Pattern 2: Global Cache for Simple Applications

```rust
use json_eval_rs::PARSED_SCHEMA_CACHE;
use std::sync::Arc;

// At application startup
fn init() {
    let schema1 = ParsedSchema::parse(schema_json1).unwrap();
    PARSED_SCHEMA_CACHE.insert("v1".to_string(), Arc::new(schema1));
    
    let schema2 = ParsedSchema::parse(schema_json2).unwrap();
    PARSED_SCHEMA_CACHE.insert("v2".to_string(), Arc::new(schema2));
}

// Anywhere in your application
fn process(version: &str, data: &str) -> Result<(), String> {
    let cached = PARSED_SCHEMA_CACHE.get(version)
        .ok_or("Schema version not found")?;
    
    let mut eval = JSONEval::with_parsed_schema(cached, None, None)?;
    eval.evaluate(data, None)?;
    
    Ok(())
}
```

### Pattern 3: Multi-Tenant Schema Management

```rust
use json_eval_rs::ParsedSchemaCache;

struct TenantSchemaManager {
    cache: ParsedSchemaCache,
}

impl TenantSchemaManager {
    fn new() -> Self {
        Self {
            cache: ParsedSchemaCache::new(),
        }
    }
    
    fn load_tenant_schema(&self, tenant_id: &str, schema_json: &str) -> Result<(), String> {
        let key = format!("tenant:{}", tenant_id);
        let parsed = ParsedSchema::parse(schema_json)?;
        self.cache.insert(key, Arc::new(parsed));
        Ok(())
    }
    
    fn reload_tenant_schema(&self, tenant_id: &str, schema_json: &str) -> Result<(), String> {
        let key = format!("tenant:{}", tenant_id);
        // Remove old schema
        self.cache.remove(&key);
        // Parse and cache new schema
        let parsed = ParsedSchema::parse(schema_json)?;
        self.cache.insert(key, Arc::new(parsed));
        Ok(())
    }
    
    fn process_tenant_data(&self, tenant_id: &str, data: &str) -> Result<String, String> {
        let key = format!("tenant:{}", tenant_id);
        let cached = self.cache.get(&key)
            .ok_or("Tenant schema not found")?;
        
        let mut eval = JSONEval::with_parsed_schema(cached, None, None)?;
        eval.evaluate(data, None)?;
        
        Ok(serde_json::to_string(&eval.get_evaluated_schema(false)).unwrap())
    }
    
    fn remove_tenant(&self, tenant_id: &str) {
        let key = format!("tenant:{}", tenant_id);
        self.cache.remove(&key);
    }
}
```

### Pattern 4: Schema Versioning

```rust
use json_eval_rs::ParsedSchemaCache;

struct VersionedSchemaCache {
    cache: ParsedSchemaCache,
}

impl VersionedSchemaCache {
    fn new() -> Self {
        Self {
            cache: ParsedSchemaCache::new(),
        }
    }
    
    fn load_version(&self, version: &str, schema_json: &str) -> Result<(), String> {
        let key = format!("v{}", version);
        let parsed = ParsedSchema::parse(schema_json)?;
        self.cache.insert(key, Arc::new(parsed));
        Ok(())
    }
    
    fn evaluate_with_version(&self, version: &str, data: &str) -> Result<String, String> {
        let key = format!("v{}", version);
        let cached = self.cache.get(&key)
            .ok_or(format!("Schema version {} not found", version))?;
        
        let mut eval = JSONEval::with_parsed_schema(cached, None, None)?;
        eval.evaluate(data, None)?;
        
        Ok(serde_json::to_string(&eval.get_evaluated_schema(false)).unwrap())
    }
    
    fn list_versions(&self) -> Vec<String> {
        self.cache.keys()
            .into_iter()
            .filter_map(|k| k.strip_prefix("v").map(String::from))
            .collect()
    }
}
```

## Performance Characteristics

### Memory
- **Cache overhead**: `O(n)` where n is the number of cached schemas
- **Per-schema**: Shared via `Arc`, minimal overhead per clone
- **Thread safety**: `RwLock` allows multiple concurrent readers

### Speed
- **Insert/Remove**: `O(1)` average case (HashMap under IndexMap)
- **Get**: `O(1)` average case, cheap Arc clone
- **Clear**: `O(n)` where n is the number of entries

### Benchmarks (from example)
Testing with 100 iterations:
- **Without cache**: ~118μs per iteration (parse + evaluate each time)
- **With cache**: ~54μs per iteration (parse once, evaluate many)
- **Speedup**: ~2.15x faster

Real-world improvements can be much higher (10x-100x) for complex schemas.

## Thread Safety

The cache is fully thread-safe and can be used across multiple threads:

```rust
use json_eval_rs::ParsedSchemaCache;
use std::sync::Arc;
use std::thread;

let cache = Arc::new(ParsedSchemaCache::new());

// Thread 1: Insert
let cache1 = cache.clone();
thread::spawn(move || {
    let parsed = ParsedSchema::parse(schema).unwrap();
    cache1.insert("shared".to_string(), Arc::new(parsed));
});

// Thread 2: Read
let cache2 = cache.clone();
thread::spawn(move || {
    if let Some(cached) = cache2.get("shared") {
        // Use cached schema
    }
});
```

## Best Practices

### 1. **Choose the Right Cache**
- Use **global cache** (`PARSED_SCHEMA_CACHE`) for simple applications
- Use **local cache** for better control and testing

### 2. **Key Naming Conventions**
```rust
// Good: Descriptive, namespaced keys
cache.insert("tenant:123:v2".to_string(), schema);
cache.insert("calculation-engine:v1".to_string(), schema);

// Avoid: Generic keys that may conflict
cache.insert("schema".to_string(), schema);
cache.insert("1".to_string(), schema);
```

### 3. **Memory Management**
```rust
// Remove unused schemas to free memory
cache.remove("old-schema");

// Clear cache when doing bulk reloads
cache.clear();
for (key, schema) in new_schemas {
    cache.insert(key, schema);
}
```

### 4. **Error Handling**
```rust
// Always handle missing schemas gracefully
let schema = cache.get("my-schema")
    .ok_or("Schema not found. Please load it first.")?;
```

### 5. **Lazy Loading**
```rust
// Use get_or_insert_with to avoid redundant parsing
let schema = cache.get_or_insert_with("my-schema", || {
    // Only executes if not already cached
    Arc::new(ParsedSchema::parse(schema_json).unwrap())
});
```

## Examples

See `examples/cache_demo.rs` for a comprehensive demonstration of all cache features:

```bash
cargo run --example cache_demo
```

This example demonstrates:
1. Local cache instance usage
2. Global cache usage
3. Performance comparison (cached vs non-cached)
4. Lazy insertion pattern

## Integration with Existing Code

### Before (No Cache)
```rust
fn evaluate_data(schema_json: &str, data: &str) -> Result<String, String> {
    let mut eval = JSONEval::new(schema_json, None, Some(data))?;
    eval.evaluate(data, None)?;
    Ok(serde_json::to_string(&eval.get_evaluated_schema(false)).unwrap())
}
```

### After (With Cache)
```rust
fn evaluate_data(
    cache: &ParsedSchemaCache,
    schema_key: &str,
    data: &str
) -> Result<String, String> {
    let cached = cache.get(schema_key)
        .ok_or("Schema not found in cache")?;
    
    let mut eval = JSONEval::with_parsed_schema(cached, None, None)?;
    eval.evaluate(data, None)?;
    Ok(serde_json::to_string(&eval.get_evaluated_schema(false)).unwrap())
}

// One-time initialization
let cache = ParsedSchemaCache::new();
let parsed = ParsedSchema::parse(schema_json)?;
cache.insert("my-schema".to_string(), Arc::new(parsed));

// Many evaluations (reuses parsed schema)
for data_file in data_files {
    let result = evaluate_data(&cache, "my-schema", &data_file)?;
}
```

## Troubleshooting

### Q: Why is my cache growing indefinitely?
**A**: You're not removing old entries. Call `cache.remove()` or `cache.clear()` when schemas are no longer needed.

### Q: Can I share the cache between async tasks?
**A**: Yes! The cache is thread-safe. Wrap it in `Arc` if needed:
```rust
let cache = Arc::new(ParsedSchemaCache::new());
```

### Q: How do I know what's in the cache?
**A**: Use `cache.stats()` or `cache.keys()` to inspect cache contents.

### Q: Should I use the global cache or create my own?
**A**: 
- Global cache: Simple applications, prototypes, scripts
- Local cache: Libraries, applications with complex lifecycle management, testing

### Q: What happens if I insert with the same key twice?
**A**: The old value is replaced and returned from `insert()`.

## Changelog

### v0.0.11
- ✅ Initial release of `ParsedSchemaCache`
- ✅ Thread-safe Arc-based caching
- ✅ Global `PARSED_SCHEMA_CACHE` instance
- ✅ Comprehensive API with batch operations
- ✅ Full documentation and examples