what-core 1.7.0

Core framework for What - an HTML-first web framework powered by Rust
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
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
//! Caching system for What framework
//!
//! Provides multi-level caching with support for:
//! - Per-page caching
//! - Per-user caching
//! - Per-content caching
//! - External API response caching

use moka::future::Cache;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;

/// Cache key types for different caching strategies
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CacheKey {
    /// Cache by page path only (global cache)
    Page(String),
    /// Cache by page + user ID
    UserPage { path: String, user_id: String },
    /// Cache by content ID (e.g., post ID)
    Content { content_type: String, id: String },
    /// Cache by user + content
    UserContent {
        user_id: String,
        content_type: String,
        id: String,
    },
    /// Cache for external API responses
    External { url: String },
    /// Custom cache key
    Custom(String),
}

impl CacheKey {
    /// Create a page cache key
    pub fn page(path: impl Into<String>) -> Self {
        Self::Page(path.into())
    }

    /// Create a user-specific page cache key
    pub fn user_page(path: impl Into<String>, user_id: impl Into<String>) -> Self {
        Self::UserPage {
            path: path.into(),
            user_id: user_id.into(),
        }
    }

    /// Create a content cache key
    pub fn content(content_type: impl Into<String>, id: impl Into<String>) -> Self {
        Self::Content {
            content_type: content_type.into(),
            id: id.into(),
        }
    }

    /// Create a user-specific content cache key
    pub fn user_content(
        user_id: impl Into<String>,
        content_type: impl Into<String>,
        id: impl Into<String>,
    ) -> Self {
        Self::UserContent {
            user_id: user_id.into(),
            content_type: content_type.into(),
            id: id.into(),
        }
    }

    /// Create an external API cache key
    pub fn external(url: impl Into<String>) -> Self {
        Self::External { url: url.into() }
    }

    /// Create a custom cache key
    pub fn custom(key: impl Into<String>) -> Self {
        Self::Custom(key.into())
    }

    /// Convert to string representation for the cache
    fn to_cache_key(&self) -> String {
        match self {
            Self::Page(path) => format!("page:{}", path),
            Self::UserPage { path, user_id } => format!("user:{}:page:{}", user_id, path),
            Self::Content { content_type, id } => format!("content:{}:{}", content_type, id),
            Self::UserContent {
                user_id,
                content_type,
                id,
            } => format!("user:{}:content:{}:{}", user_id, content_type, id),
            Self::External { url } => format!("external:{}", url),
            Self::Custom(key) => format!("custom:{}", key),
        }
    }
}

/// Cached value with metadata
#[derive(Debug, Clone)]
pub struct CachedValue {
    /// The cached content
    pub content: String,
    /// ETag for conditional requests
    pub etag: Option<String>,
    /// Content type
    pub content_type: String,
}

impl CachedValue {
    pub fn html(content: String) -> Self {
        Self {
            content,
            etag: None,
            content_type: "text/html".to_string(),
        }
    }

    pub fn json(content: String) -> Self {
        Self {
            content,
            etag: None,
            content_type: "application/json".to_string(),
        }
    }

    pub fn with_etag(mut self, etag: impl Into<String>) -> Self {
        self.etag = Some(etag.into());
        self
    }
}

/// Multi-level cache for the What framework
#[derive(Clone)]
pub struct WhatCache {
    /// Main content cache
    content_cache: Cache<String, CachedValue>,
    /// External API response cache
    api_cache: Cache<String, String>,
    /// Default TTL for content
    #[allow(dead_code)]
    default_ttl: Duration,
    /// Default TTL for API responses
    #[allow(dead_code)]
    api_ttl: Duration,
    /// Tag index: maps tag (e.g., collection name) → set of cache keys
    /// Used for targeted invalidation instead of clearing the entire cache.
    tag_index: Arc<RwLock<HashMap<String, HashSet<String>>>>,
}

impl WhatCache {
    /// Create a new cache with default settings
    pub fn new() -> Self {
        Self::with_config(CacheConfig::default())
    }

    /// Create a cache with custom configuration
    pub fn with_config(config: CacheConfig) -> Self {
        let content_cache = Cache::builder()
            .max_capacity(config.max_content_entries)
            .time_to_live(Duration::from_secs(config.content_ttl_secs))
            .build();

        let api_cache = Cache::builder()
            .max_capacity(config.max_api_entries)
            .time_to_live(Duration::from_secs(config.api_ttl_secs))
            .build();

        Self {
            content_cache,
            api_cache,
            default_ttl: Duration::from_secs(config.content_ttl_secs),
            api_ttl: Duration::from_secs(config.api_ttl_secs),
            tag_index: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Get a cached page/content
    pub async fn get(&self, key: &CacheKey) -> Option<CachedValue> {
        self.content_cache.get(&key.to_cache_key()).await
    }

    /// Cache a page/content
    pub async fn set(&self, key: &CacheKey, value: CachedValue) {
        self.content_cache.insert(key.to_cache_key(), value).await;
    }

    /// Cache a page/content and associate it with tags for targeted invalidation.
    /// Tags are typically collection names (e.g., "posts", "users").
    pub async fn set_with_tags(&self, key: &CacheKey, value: CachedValue, tags: &[&str]) {
        let cache_key = key.to_cache_key();
        self.content_cache.insert(cache_key.clone(), value).await;

        if !tags.is_empty() {
            let mut index = self.tag_index.write().await;
            for tag in tags {
                index
                    .entry(tag.to_string())
                    .or_default()
                    .insert(cache_key.clone());
            }
        }
    }

    /// Cache a page/content with custom TTL
    pub async fn set_with_ttl(&self, key: &CacheKey, value: CachedValue, _ttl: Duration) {
        // Note: moka doesn't support per-entry TTL easily,
        // so we use the default TTL. For production, consider
        // using a different cache backend or custom expiry logic.
        self.content_cache.insert(key.to_cache_key(), value).await;
    }

    /// Get cached API response
    pub async fn get_api(&self, url: &str) -> Option<String> {
        self.api_cache.get(&format!("api:{}", url)).await
    }

    /// Cache API response
    pub async fn set_api(&self, url: &str, response: String) {
        self.api_cache
            .insert(format!("api:{}", url), response)
            .await;
    }

    /// Invalidate a specific cache entry
    pub async fn invalidate(&self, key: &CacheKey) {
        self.content_cache.invalidate(&key.to_cache_key()).await;
    }

    /// Invalidate all entries matching a tag.
    /// If no entries are tagged, falls back to full cache clear.
    pub async fn invalidate_by_tag(&self, tag: &str) {
        let mut index = self.tag_index.write().await;
        if let Some(keys) = index.remove(tag) {
            for key in &keys {
                self.content_cache.invalidate(key).await;
            }
            self.content_cache.run_pending_tasks().await;
            tracing::debug!(
                "Cache: invalidated {} entries for tag '{}'",
                keys.len(),
                tag
            );
        }
        // Also clean up any references to this tag's keys from other tags
        // (a key can have multiple tags)
    }

    /// Invalidate all content cache entries for a specific content type / collection.
    /// Uses the tag index for targeted invalidation. If no entries are tagged,
    /// falls back to full cache clear for safety.
    pub async fn invalidate_content_type(&self, content_type: &str) {
        let index = self.tag_index.read().await;
        if index.contains_key(content_type) {
            drop(index); // Release read lock before taking write lock
            self.invalidate_by_tag(content_type).await;
        } else {
            drop(index);
            // Fallback: no tagged entries, clear all content cache
            self.content_cache.invalidate_all();
            self.content_cache.run_pending_tasks().await;
        }
    }

    /// Invalidate all cache entries for a specific user.
    /// Uses prefix matching on cache keys.
    pub async fn invalidate_user(&self, user_id: &str) {
        let prefix = format!("user:{}:", user_id);
        let index = self.tag_index.read().await;
        if let Some(keys) = index.get(user_id) {
            let keys_to_remove: Vec<String> = keys.iter().cloned().collect();
            drop(index);
            for key in &keys_to_remove {
                self.content_cache.invalidate(key).await;
            }
        } else {
            drop(index);
            // Fallback: scan for keys with user prefix (best effort)
            // Moka doesn't support prefix scanning, so we clear all
            let _ = prefix; // Used for documentation, not runtime
            self.content_cache.invalidate_all();
        }
        self.content_cache.run_pending_tasks().await;
    }

    /// Clear all caches
    pub async fn clear_all(&self) {
        self.content_cache.invalidate_all();
        self.api_cache.invalidate_all();
        self.content_cache.run_pending_tasks().await;
        self.api_cache.run_pending_tasks().await;
        self.tag_index.write().await.clear();
    }

    /// Get cache statistics
    pub fn stats(&self) -> CacheStats {
        CacheStats {
            content_entries: self.content_cache.entry_count(),
            api_entries: self.api_cache.entry_count(),
        }
    }
}

impl Default for WhatCache {
    fn default() -> Self {
        Self::new()
    }
}

/// Cache configuration
#[derive(Debug, Clone)]
pub struct CacheConfig {
    /// Max entries in content cache
    pub max_content_entries: u64,
    /// Max entries in API cache
    pub max_api_entries: u64,
    /// TTL for content in seconds
    pub content_ttl_secs: u64,
    /// TTL for API responses in seconds
    pub api_ttl_secs: u64,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            max_content_entries: 10_000,
            max_api_entries: 1_000,
            content_ttl_secs: 300, // 5 minutes
            api_ttl_secs: 60,      // 1 minute
        }
    }
}

/// Cache statistics
#[derive(Debug, Clone)]
pub struct CacheStats {
    pub content_entries: u64,
    pub api_entries: u64,
}

/// Cache control directives for responses
#[derive(Debug, Clone, Default)]
pub struct CacheControl {
    /// Cache scope
    pub scope: CacheScope,
    /// Max age in seconds
    pub max_age: Option<u64>,
    /// Whether to revalidate
    pub must_revalidate: bool,
    /// Whether this is immutable
    pub immutable: bool,
}

#[derive(Debug, Clone, Default)]
pub enum CacheScope {
    /// Can be cached by any cache (CDN, browser, etc.)
    #[default]
    Public,
    /// Only cache in user's browser
    Private,
    /// Don't cache at all
    NoCache,
    /// Don't store at all
    NoStore,
}

impl CacheControl {
    pub fn public(max_age: u64) -> Self {
        Self {
            scope: CacheScope::Public,
            max_age: Some(max_age),
            must_revalidate: false,
            immutable: false,
        }
    }

    pub fn private(max_age: u64) -> Self {
        Self {
            scope: CacheScope::Private,
            max_age: Some(max_age),
            must_revalidate: false,
            immutable: false,
        }
    }

    pub fn no_cache() -> Self {
        Self {
            scope: CacheScope::NoCache,
            max_age: None,
            must_revalidate: true,
            immutable: false,
        }
    }

    pub fn immutable() -> Self {
        Self {
            scope: CacheScope::Public,
            max_age: Some(31536000), // 1 year
            must_revalidate: false,
            immutable: true,
        }
    }

    /// Convert to HTTP Cache-Control header value
    pub fn to_header_value(&self) -> String {
        let mut parts = Vec::new();

        match self.scope {
            CacheScope::Public => parts.push("public".to_string()),
            CacheScope::Private => parts.push("private".to_string()),
            CacheScope::NoCache => parts.push("no-cache".to_string()),
            CacheScope::NoStore => parts.push("no-store".to_string()),
        }

        if let Some(max_age) = self.max_age {
            parts.push(format!("max-age={}", max_age));
        }

        if self.must_revalidate {
            parts.push("must-revalidate".to_string());
        }

        if self.immutable {
            parts.push("immutable".to_string());
        }

        parts.join(", ")
    }
}

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

    #[tokio::test]
    async fn test_cache_basic() {
        let cache = WhatCache::new();

        let key = CacheKey::page("/about");
        let value = CachedValue::html("<h1>About</h1>".to_string());

        cache.set(&key, value.clone()).await;

        let retrieved = cache.get(&key).await.unwrap();
        assert_eq!(retrieved.content, "<h1>About</h1>");
    }

    #[tokio::test]
    async fn test_user_page_cache() {
        let cache = WhatCache::new();

        let key1 = CacheKey::user_page("/dashboard", "user1");
        let key2 = CacheKey::user_page("/dashboard", "user2");

        cache
            .set(&key1, CachedValue::html("User 1 Dashboard".to_string()))
            .await;
        cache
            .set(&key2, CachedValue::html("User 2 Dashboard".to_string()))
            .await;

        assert_eq!(cache.get(&key1).await.unwrap().content, "User 1 Dashboard");
        assert_eq!(cache.get(&key2).await.unwrap().content, "User 2 Dashboard");
    }

    #[tokio::test]
    async fn test_set_with_tags_and_invalidate_by_tag() {
        let cache = WhatCache::new();

        let key1 = CacheKey::page("/blog");
        let key2 = CacheKey::page("/blog/post-1");
        let key3 = CacheKey::page("/about");

        // Cache pages with tags
        cache
            .set_with_tags(&key1, CachedValue::html("Blog list".into()), &["posts"])
            .await;
        cache
            .set_with_tags(&key2, CachedValue::html("Post 1".into()), &["posts"])
            .await;
        cache
            .set_with_tags(&key3, CachedValue::html("About page".into()), &["pages"])
            .await;

        // All should be cached
        assert!(cache.get(&key1).await.is_some());
        assert!(cache.get(&key2).await.is_some());
        assert!(cache.get(&key3).await.is_some());

        // Invalidate "posts" tag — should only remove blog pages
        cache.invalidate_by_tag("posts").await;

        assert!(cache.get(&key1).await.is_none());
        assert!(cache.get(&key2).await.is_none());
        assert!(cache.get(&key3).await.is_some()); // About page untouched
    }

    #[tokio::test]
    async fn test_invalidate_content_type_targeted() {
        let cache = WhatCache::new();

        let key1 = CacheKey::page("/products");
        let key2 = CacheKey::page("/cart");

        cache
            .set_with_tags(&key1, CachedValue::html("Products".into()), &["products"])
            .await;
        cache
            .set_with_tags(&key2, CachedValue::html("Cart".into()), &["cart"])
            .await;

        // Invalidate "products" via content_type
        cache.invalidate_content_type("products").await;

        assert!(cache.get(&key1).await.is_none());
        assert!(cache.get(&key2).await.is_some());
    }

    #[tokio::test]
    async fn test_invalidate_content_type_fallback() {
        let cache = WhatCache::new();

        let key = CacheKey::page("/test");
        // Set WITHOUT tags
        cache.set(&key, CachedValue::html("Test".into())).await;

        // Invalidate unknown content type — should fall back to clearing all
        cache.invalidate_content_type("unknown").await;

        assert!(cache.get(&key).await.is_none());
    }

    #[tokio::test]
    async fn test_clear_all_clears_tag_index() {
        let cache = WhatCache::new();

        let key = CacheKey::page("/blog");
        cache
            .set_with_tags(&key, CachedValue::html("Blog".into()), &["posts"])
            .await;

        cache.clear_all().await;

        assert!(cache.get(&key).await.is_none());
        // Tag index should be empty
        assert!(cache.tag_index.read().await.is_empty());
    }

    #[test]
    fn test_cache_control_header() {
        let cc = CacheControl::public(3600);
        assert_eq!(cc.to_header_value(), "public, max-age=3600");

        let cc = CacheControl::private(600);
        assert_eq!(cc.to_header_value(), "private, max-age=600");

        let cc = CacheControl::no_cache();
        assert_eq!(cc.to_header_value(), "no-cache, must-revalidate");

        let cc = CacheControl::immutable();
        assert_eq!(cc.to_header_value(), "public, max-age=31536000, immutable");
    }
}