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
//! Query result caching for FraiseQL v2.
//!
//! # Overview
//!
//! This module provides transparent W-TinyLFU query result caching with view-based
//! and entity-based invalidation. Cache entries are automatically invalidated when
//! mutations modify the underlying data.
//!
//! # Scope
//!
//! - **W-TinyLFU result caching** with per-entry TTL (via moka)
//! - **Lock-free reads** — cache hits do not acquire any shared lock
//! - **View-based invalidation** and **entity-based invalidation** via O(k) reverse indexes
//! - **Security-aware cache key generation** (prevents data leakage)
//! - **Integration with `DatabaseAdapter`** via wrapper
//!
//! # Architecture
//!
//! ```text
//! ┌─────────────────────┐
//! │ GraphQL Query │
//! │ + Variables │
//! │ + WHERE Clause │
//! └──────────┬──────────┘
//! │
//! ↓ generate_cache_key()
//! ┌─────────────────────┐
//! │ ahash Cache Key │ ← Includes variables for security
//! └──────────┬──────────┘
//! │
//! ↓ QueryResultCache::get()
//! ┌─────────────────────┐
//! │ Cache Hit? │
//! │ - Check TTL (moka) │
//! │ - W-TinyLFU policy │
//! └──────────┬──────────┘
//! │
//! ┌─────┴─────┐
//! │ │
//! HIT MISS
//! │ │
//! ↓ ↓ execute_query()
//! Return Database Query
//! Cached + Store Result
//! Result + Track Views
//!
//! Mutation:
//! ┌─────────────────────┐
//! │ Mutation executed │
//! │ "createUser" │
//! └──────────┬──────────┘
//! │
//! ↓ InvalidationContext::for_mutation()
//! ┌─────────────────────┐
//! │ Modified Views: │
//! │ - v_user │
//! └──────────┬──────────┘
//! │
//! ↓ cache.invalidate_views()
//! ┌─────────────────────┐
//! │ Remove all caches │
//! │ reading from v_user │
//! └─────────────────────┘
//! ```
//!
//! # Configuration
//!
//! ```rust
//! use fraiseql_core::cache::CacheConfig;
//!
//! // Production configuration
//! let config = CacheConfig {
//! enabled: true,
//! max_entries: 50_000,
//! ttl_seconds: 86_400, // 24 hours
//! cache_list_queries: true,
//! ..Default::default()
//! };
//!
//! // Development (disable for deterministic tests)
//! let config = CacheConfig::disabled();
//! ```
//!
//! # Usage Example
//!
//! ```no_run
//! use fraiseql_core::cache::{CachedDatabaseAdapter, QueryResultCache, CacheConfig, InvalidationContext};
//! use fraiseql_core::db::{postgres::PostgresAdapter, DatabaseAdapter};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create database adapter
//! let db_adapter = PostgresAdapter::new("postgresql://localhost/db").await?;
//!
//! // Wrap with caching
//! let cache = QueryResultCache::new(CacheConfig::default());
//! let adapter = CachedDatabaseAdapter::new(
//! db_adapter,
//! cache,
//! "1.0.0".to_string() // schema version
//! );
//!
//! // Use as normal DatabaseAdapter - caching is transparent
//! let users = adapter
//! .execute_where_query("v_user", None, Some(10), None, None)
//! .await?;
//!
//! println!("Found {} users", users.len());
//!
//! // After mutation, invalidate
//! let invalidation = InvalidationContext::for_mutation(
//! "createUser",
//! vec!["v_user".to_string()]
//! );
//! adapter.invalidate_views(&invalidation.modified_views)?;
//! # Ok(())
//! # }
//! ```
//!
//! # Performance
//!
//! - **Cache hit latency**: ~0.05ms (P99 < 0.5ms) — lock-free read path
//! - **Expected hit rate**: 60-80% for typical workloads (higher than LRU under skewed access)
//! - **Memory usage**: ~100 MB for default config (10,000 entries @ 10 KB avg)
//! - **Speedup**: 50-200x faster than database queries
//!
//! # Security
//!
//! Cache keys include variable values to prevent data leakage between users.
//! Different users with different query variables get different cache entries.
//!
//! **Example**:
//! ```text
//! User A: query { user(id: 1) } → Cache key: abc123...
//! User B: query { user(id: 2) } → Cache key: def456... (DIFFERENT)
//! ```
//!
//! This prevents User B from accidentally seeing User A's cached data.
//!
//! # View-Based Invalidation
//!
//! Invalidation operates at the **view/table level**:
//!
//! - **Mutation modifies `v_user`** → Invalidate ALL caches reading from `v_user`
//! - **Expected hit rate**: 60-70% (some over-invalidation)
//!
//! **Example**:
//! ```text
//! Cache Entry 1: query { user(id: 1) } → reads v_user
//! Cache Entry 2: query { user(id: 2) } → reads v_user
//! Cache Entry 3: query { post(id: 100) } → reads v_post
//!
//! Mutation: updateUser(id: 1)
//! → Invalidates Entry 1 AND Entry 2 (even though Entry 2 not affected)
//! → Entry 3 remains cached
//! ```
//!
//! # Cache Security Requirements
//!
//! The cache is safe in single-tenant deployments with no additional configuration.
//! In **multi-tenant deployments**, two requirements must be met to prevent data
//! leakage between tenants:
//!
//! 1. **Row-Level Security (RLS) must be active.** The cache key includes the per-request WHERE
//! clause injected by FraiseQL's RLS policy engine. Different users with different RLS
//! predicates receive different cache entries. If RLS is disabled or returns an empty clause,
//! all users share the same key for identical queries and variables — Tenant A's data appears in
//! Tenant B's responses.
//!
//! 2. **Schema content hash must be used as the schema version.** Use
//! `CompiledSchema::content_hash()` (not `env!("CARGO_PKG_VERSION")`) when constructing
//! `CachedDatabaseAdapter`. This ensures that any schema change automatically invalidates all
//! cached entries, preventing stale-schema hits after deployment.
//!
//! The server emits a startup `warn!` when caching is enabled but no RLS policies
//! are declared in the compiled schema. This warning is informational in
//! single-tenant deployments and a critical security indicator in multi-tenant ones.
//!
//! # Future Enhancements
//!
//! - **Entity-level tracking**: Track by `User:123`, not just `v_user`
//! - **Cascade integration**: Parse mutation metadata for precise invalidation
//! - **Selective invalidation**: Only invalidate affected entity IDs
//! - **Expected hit rate**: 90-95% with entity-level tracking
//!
//! # Module Organization
//!
//! - **`adapter`**: `CachedDatabaseAdapter` wrapper for transparent caching
//! - **`config`**: Cache configuration with memory-safe bounds
//! - **`key`**: Security-critical cache key generation (includes APQ integration)
//! - **`result`**: W-TinyLFU cache storage (moka) with per-entry TTL, reverse indexes, and metrics
//! - **`dependency_tracker`**: Bidirectional view↔cache mapping
//! - **`invalidation`**: Public invalidation API with structured contexts
// Cascading invalidation with transitive dependencies
// Entity-level caching modules
// Fact table aggregation caching
// Public exports
pub use ;
pub use ;
pub use CascadeMetadata;
pub use CascadeResponseParser;
pub use ;
// Export dependency tracker (used in doctests and advanced use cases)
pub use DependencyTracker;
pub use EntityKey;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use UUIDExtractor;