oxcache 0.2.0

A high-performance multi-level cache library for Rust with L1 (memory) and L2 (Redis) caching.
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
# API Reference

> **⚠️ API Version Notice**
>
> This document describes **Oxcache v0.2.0** APIs.

This document provides detailed API reference for the Oxcache library.

## Table of Contents

- [Feature Requirements]#feature-requirements
- [Cache Macro]#cache-macro
- [Cache Management]#cache-management
- [Cache Operations]#cache-operations
- [Configuration]#configuration
- [Synchronization]#synchronization
- [Recovery]#recovery
- [Security Features]#security-features
- [Observability]#observability

## Feature Requirements

Oxcache uses feature gates to control functionality. Here are the key features and their requirements:

### Core Features
- **`minimal`**: L1 cache only (Memory backends)
- **`core`**: L1 + L2 cache (Redis)
- **`full`**: All features enabled

### Component Features
- **`memory`**: L1 cache backends (Moka + DashMap)
- **`redis`**: L2 cache implementation (Redis)
- **`macros`**: Required for `#[cached]` attribute macro
- **`serialization`**: JSON serialization (serde + serde_json)
- **`metrics`**: OpenTelemetry metrics and observability
- **`tracing`**: Structured logging support

### Advanced Features
- **`compression`**: Data compression (flate2)
- **`batch-write`**: Optimized batch writing (tokio-util)
- **`lua-script`**: Lua script execution support
- **`cli`**: Command-line interface (clap)
- **`testing`**: Testing support utilities

### Example Configurations

```toml
# Full features (recommended)
oxcache = { version = "0.2.0", features = ["full"] }

# Core functionality only
oxcache = { version = "0.2.0", features = ["core"] }

# Minimal - L1 cache only
oxcache = { version = "0.2.0", features = ["minimal"] }

# Custom selection
oxcache = { version = "0.2.0", features = ["core", "macros", "metrics"] }
```

### Feature Dependencies

Some features require other features to be enabled:

| Feature | Required Features | Description |
|---------|-------------------|-------------|
| `lua-script` | `redis` | Lua script execution |
| `cli` | `metrics`, `dashmap`, `tracing` | Command-line interface |
| `core` | `minimal`, `redis`, `futures` | Core L1 + L2 cache |
| `full` | `core`, `macros`, `compression`, `batch-write`, `lua-script`, `cli`, `testing` | All features |

## Cache Macro

### `#[cached]` Attribute Macro

Zero-boilerplate caching decorator for async functions.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `service` | `&str` | Yes | - | Cache service name |
| `ttl` | `u64` | No | `None` | Time-to-live in seconds |
| `key` | `&str` | No | Auto-generated | Custom cache key format |
| `key_prefix` | `&str` | No | `""` | Prefix for cache key |
| `key_generator` | `&str` | No | `"default"` | Key generation strategy: `"default"`, `"simple"`, `"md5"`, `"murmur3"`, `"namespace"` |
| `cache_type` | `&str` | No | `"two-level"` | Cache type: `"two-level"`, `"l1-only"`, `"l2-only"` |

**Example:**

```rust
// Enable macros feature in Cargo.toml
oxcache = { version = "0.2.0", features = ["macros"] }

// In your code
use oxcache::cached;

#[cached(service = "default", ttl = 3600)]
async fn fetch_user(user_id: &str) -> Result<User> {
    // Function body
}
```

**Custom Key Format:**

```rust
#[cached(service = "default", ttl = 3600, key = "user:{user_id}")]
async fn fetch_user(user_id: &str) -> Result<User> {
    // Function body
}
```

## Cache Management

### Initialization

#### `init(config: OxcacheConfig) -> Result<()>`

Initialize cache system with given configuration.

```rust
use oxcache::{init, oxcache_config, ServiceConfig};

let config = oxcache_config()
    .with_service("default", ServiceConfig::two_level())
    .build();

init(config).await?;
```

### Client Management

For direct cache instance management, use the `Cache` and `CacheBuilder` types:

```rust
use oxcache::{Cache, CacheBuilder};

// Create cache directly using Cache::builder()
let cache: Cache<String, User> = Cache::builder()
    .redis("redis://localhost:6379")
    .build()
    .await?;

// Or create tiered cache (L1 + L2)
let cache: Cache<String, User> = Cache::builder()
    .tiered(10000, "redis://localhost:6379")
    .ttl(Duration::from_secs(3600))
    .build()
    .await?;

// Register for macro usage
cache.register_for_macro("my_service").await;
```

## Cache Operations

### Trait `CacheOps`

All cache clients implement this trait.

#### `get<T>(&self, key: &str) -> Result<Option<T>>`

Get a value from the cache.

**Type Parameters:**
- `T`: Value type, must implement `DeserializeOwned`

**Returns:**
- `Ok(Some(T))`: Value found
- `Ok(None)`: Value not found
- `Err(Error)`: Cache error

**Example:**

```rust
let user: Option<User> = client.get("user:123").await?;
```

#### `set<T>(&self, key: &str, value: &T, ttl: Option<u64>) -> Result<()>`

Set a value in the cache.

**Parameters:**
- `key`: Cache key
- `value`: Value to cache, must implement `Serialize`
- `ttl`: Time-to-live in seconds (None = no expiration)

**Example:**

```rust
client.set("user:123", &user, Some(3600)).await?;
```

#### `delete(&self, key: &str) -> Result<()>`

Delete a value from the cache.

```rust
client.delete("user:123").await?;
```

#### `exists(&self, key: &str) -> Result<bool>`

Check if a key exists in the cache.

```rust
let exists = client.exists("user:123").await?;
```

#### `clear(&self) -> Result<()>`

Clear all entries in the cache.

```rust
client.clear().await?;
```

### Batch Operations

Note: Batch operations are currently handled internally by the OptimizedBatchWriter for performance optimization. Direct batch operation APIs are planned for future releases.

#### Optimized Batch Writer

For high-throughput scenarios, use the optimized batch writer:

```rust
use oxcache::sync::OptimizedBatchWriter;

let writer = OptimizedBatchWriter::new(
    client.clone(),
    "default".to_string(),
    100,  // batch_size
    50,   // max_flush_interval_ms
).await?;
```

## Configuration

### Builder Pattern

#### `oxcache_config() -> OxcacheConfigBuilder`

Create a new configuration builder.

```rust
let builder = oxcache_config();
```

#### `OxcacheConfigBuilder::with_service(name: &str, config: ServiceConfig) -> Self`

Add a service configuration.

```rust
let config = oxcache_config()
    .with_service("default", ServiceConfig::two_level())
    .build();
```

#### `OxcacheConfigBuilder::build(self) -> OxcacheConfig`

Build the final configuration.

```rust
let config = oxcache_config().build();
```

### Service Configuration

#### `ServiceConfig::two_level() -> Self`

Create a two-level cache configuration.

```rust
let config = ServiceConfig::two_level();
```

#### `ServiceConfig::l1_only() -> Self`

Create an L1-only cache configuration.

```rust
let config = ServiceConfig::l1_only();
```

#### `ServiceConfig::l2_only() -> Self`

Create an L2-only cache configuration.

```rust
let config = ServiceConfig::l2_only();
```

#### `ServiceConfig::with_ttl(self, ttl: u64) -> Self`

Set the default TTL for the service.

```rust
let config = ServiceConfig::two_level().with_ttl(3600);
```

### L1 Configuration

#### `L1Config::new() -> Self`

Create a new L1 configuration with defaults.

```rust
let l1 = L1Config::new();
```

#### `L1Config::with_max_capacity(self, capacity: u64) -> Self`

Set maximum cache capacity.

```rust
let l1 = L1Config::new().with_max_capacity(10000);
```

#### `L1Config::with_time_to_idle(self, ttl: u64) -> Self`

Set idle expiration time.

```rust
let l1 = L1Config::new().with_time_to_idle(600);
```

### L2 Configuration

#### `L2Config::new() -> Self`

Create a new L2 configuration.

```rust
let l2 = L2Config::new();
```

#### `L2Config::with_mode(self, mode: RedisMode) -> Self`

Set Redis connection mode.

```rust
let l2 = L2Config::new()
    .with_mode(RedisMode::Standalone)
    .with_connection_string("redis://localhost:6379");
```

#### `L2Config::with_connection_string(self, connection_string: &str) -> Self`

Set Redis connection string.

```rust
let l2 = L2Config::new()
    .with_connection_string("redis://localhost:6379");
```

#### `L2Config::with_enable_batch_write(self, enable: bool) -> Self`

Enable batch write optimization.

```rust
let l2 = L2Config::new().with_enable_batch_write(true);
```

## Synchronization

### Batch Writer

#### `OptimizedBatchWriter`

Optimized batch writer for high-throughput scenarios.

```rust
use oxcache::sync::OptimizedBatchWriter;

let writer = OptimizedBatchWriter::new(
    client.clone(),
    "default".to_string(),
    100,  // batch_size
    50,   // max_flush_interval_ms
).await?;
```

### Invalidation

Cache invalidation is handled internally by the `#[cached]` macro and the internal registry. For manual invalidation, use the cache operations:

```rust
// Invalidate a specific key
cache.delete("user:123").await?;

// Clear all entries
cache.clear().await?;
```

### Cache Promotion

Cache promotion is handled automatically by the tiered cache backend. Hot keys are automatically promoted from L2 to L1 based on access patterns.

To configure promotion behavior:

```rust
use oxcache::{Cache, CacheBuilder, BackendBuilder};

let cache: Cache<String, User> = CacheBuilder::new()
    .backend(
        BackendBuilder::tiered()
            .l1_capacity(10000)
            .l2_connection_string("redis://localhost:6379")
            .auto_promote(true)  // Enable automatic promotion
    )
    .build()
    .await?;
```

## Recovery

### Health Check

#### `HealthChecker`

Check cache health status.

```rust
use oxcache::recovery::HealthChecker;

let checker = HealthChecker::new(client.clone()).await?;
let health = checker.check().await?;

if health.is_healthy() {
    println!("Cache is healthy");
}
```

### Write-Ahead Log (WAL)

#### `WALManager`

Manage write-ahead log for durability.

```rust
use oxcache::recovery::WALManager;

let wal = WALManager::new("/path/to/wal").await?;

// Append entry
wal.append_entry("SET user:123 value 3600").await?;

// Replay entries
wal.replay().await?;
```

## Security Features

### Input Validation

Oxcache provides comprehensive input validation to protect against common attacks.

#### `validate_redis_key(key: &str) -> Result<()>`

Validate Redis key format and content.

```rust
use oxcache::security::validate_redis_key;

// Valid key
validate_redis_key("user:123").expect("Valid key");

// Invalid key (empty, too long, or contains dangerous characters)
// Returns Err(CacheError::InvalidInput)
```

**Validation Rules:**
- Key cannot be empty
- Key cannot exceed 512KB
- Key cannot contain dangerous characters (`\r`, `\n`, `\0`)
- Key is scanned for SQL injection and path traversal patterns

#### `validate_lua_script(script: &str, num_keys: usize) -> Result<()>`

Validate Lua script for security issues.

```rust
use oxcache::security::validate_lua_script;

// Valid script
validate_lua_script("return redis.call('GET', KEYS[1])", 1).expect("Valid script");
```

**Validation Rules:**
- Script length cannot exceed 10KB
- Number of keys cannot exceed 100
- Dangerous commands are blocked: `FLUSHALL`, `FLUSHDB`, `KEYS`, `SHUTDOWN`, `DEBUG`, `CONFIG`, `SAVE`, `BGSAVE`, `MONITOR`
- Comment preprocessing prevents bypass via comments

#### `validate_scan_pattern(pattern: &str) -> Result<()>`

Validate SCAN pattern to prevent ReDoS attacks.

```rust
use oxcache::security::validate_scan_pattern;

// Valid pattern
validate_scan_pattern("user:*").expect("Valid pattern");
```

**Validation Rules:**
- Pattern length cannot exceed 256 characters
- Maximum of 10 wildcard (`*`) characters
- Count parameter is clamped to safe range (1-1000)

### Rate Limiting

#### `GlobalRateLimiter`

Prevent DoS attacks.

```rust
use oxcache::{RateLimitConfig, GlobalRateLimiter};

let config = RateLimitConfig {
    max_requests_per_second: 1000,
    burst_capacity: 2000,
    block_duration_secs: 10,
};

let limiter = GlobalRateLimiter::new(Some(config));

if limiter.check("user:123").await? {
    // Process request
} else {
    return Err(Error::RateLimitExceeded);
}
```

## Observability

### Metrics

#### `MetricsCollector`

Collect cache metrics.

```rust
use oxcache::MetricsCollector;

let collector = MetricsCollector::new("default".to_string());
let metrics = collector.collect().await?;

println!("Hits: {}", metrics.hits);
println!("Misses: {}", metrics.misses);
println!("Hit Rate: {:.2}%", metrics.hit_rate());
```

### Telemetry

#### `init_tracing(service_name: &str, otlp_endpoint: Option<&str>)`

Initialize distributed tracing.

```rust
use oxcache::telemetry::init_tracing;

init_tracing("my_service", Some("http://localhost:4317"));
```

### Logging

Oxcache uses the `tracing` crate for structured logging.

```rust
use tracing::{info, error, warn};

info!("Cache initialized");
warn!("Redis connection lost, switching to L1-only mode");
error!("Failed to write to cache: {}", err);
```

## Error Handling

### Error Types

```rust
use oxcache::Error;

match result {
    Ok(data) => println!("{:?}", data),
    Err(Error::KeyNotFound) => println!("Key not found"),
    Err(Error::SerializationError(e)) => println!("Serialization error: {}", e),
    Err(Error::ConnectionError(e)) => println!("Connection error: {}", e),
    Err(e) => println!("Other error: {}", e),
}
```

## Type Aliases

```rust
pub type CacheResult<T> = Result<T, Error>;
pub type CacheClient = Arc<dyn CacheOps>;
```

## Examples

See the [examples/](../examples/) directory for more usage examples:

- [Basic Operations]../examples/src/01_basics/
- [Advanced Features]../examples/src/02_advanced/
- [Configuration]../examples/src/03_config/
- [Database Integration]../examples/src/05_database/
- [Feature Demos]../examples/src/06_features/