crates-docs 0.9.0

High-performance Rust crate documentation query MCP server, supports Stdio/HTTP/SSE transport and OAuth authentication
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
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
//! Document cache module
//!
//! Provides document-specific cache service with support for independent TTL configuration
//! for crate docs, search results, and item docs.
//!
//! # Cache key format
//!
//! - Crate documentation: `crate:{name}` or `crate:{name}:{version}`
//! - Search results: `search:{query}:{limit}`
//! - Item documentation: `item:{crate}:{path}` or `item:{crate}:{version}:{path}`
//!
//! # Examples
//!
//! ```rust,no_run
//! use std::sync::Arc;
//! use crates_docs::tools::docs::cache::{DocCache, DocCacheTtl};
//! use crates_docs::cache::memory::MemoryCache;
//!
//! let cache = Arc::new(MemoryCache::new(1000));
//! let doc_cache = DocCache::new(cache);
//! ```

mod key;
mod stats;
mod ttl;

use crate::cache::Cache;
use std::sync::Arc;

// Re-export public types
pub use key::CacheKeyGenerator;
pub use stats::CacheStats;
pub use ttl::DocCacheTtl;

/// Document cache service
///
/// Provides document-specific cache operations, supports crate docs, search results, and item docs.
///
/// # Fields
///
/// - `cache`: Underlying cache instance
/// - `ttl`: TTL configuration
/// - `stats`: Cache statistics
#[derive(Clone)]
pub struct DocCache {
    cache: Arc<dyn Cache>,
    ttl: DocCacheTtl,
    stats: CacheStats,
}

impl DocCache {
    /// Create new document cache (with default TTL)
    ///
    /// # Arguments
    ///
    /// * `cache` - cache instance
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use std::sync::Arc;
    /// use crates_docs::tools::docs::cache::DocCache;
    /// use crates_docs::cache::memory::MemoryCache;
    ///
    /// let cache = Arc::new(MemoryCache::new(1000));
    /// let doc_cache = DocCache::new(cache);
    /// ```
    pub fn new(cache: Arc<dyn Cache>) -> Self {
        Self {
            cache,
            ttl: DocCacheTtl::default(),
            stats: CacheStats::new(),
        }
    }

    /// Create new document cache (with custom TTL)
    ///
    /// # Arguments
    ///
    /// * `cache` - cache instance
    /// * `ttl` - TTL configuration
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use std::sync::Arc;
    /// use crates_docs::tools::docs::cache::{DocCache, DocCacheTtl};
    /// use crates_docs::cache::memory::MemoryCache;
    ///
    /// let cache = Arc::new(MemoryCache::new(1000));
    /// let ttl = DocCacheTtl::with_jitter(
    ///     7200,  // crate_docs_secs
    ///     600,   // search_results_secs
    ///     3600,  // item_docs_secs
    ///     0.1,   // jitter_ratio
    /// );
    /// let doc_cache = DocCache::with_ttl(cache, ttl);
    /// ```
    pub fn with_ttl(cache: Arc<dyn Cache>, ttl: DocCacheTtl) -> Self {
        Self {
            cache,
            ttl,
            stats: CacheStats::new(),
        }
    }

    /// Get cached crate documentation
    ///
    /// # Arguments
    ///
    /// * `crate_name` - crate name
    /// * `version` - Optional version
    ///
    /// # Returns
    ///
    /// Returns document content if cache hit; otherwise returns `None`
    #[tracing::instrument(skip(self), fields(crate = crate_name, version = version), level = "trace")]
    pub async fn get_crate_docs(
        &self,
        crate_name: &str,
        version: Option<&str>,
    ) -> Option<Arc<str>> {
        let key = CacheKeyGenerator::crate_cache_key(crate_name, version);
        let result = self.cache.get(&key).await;
        let is_hit = result.is_some();
        if is_hit {
            self.stats.record_hit();
            tracing::span!(
                tracing::Level::TRACE,
                "cache",
                op = "get",
                hit = true,
                crate = crate_name
            )
            .in_scope(|| {
                tracing::trace!("Cache hit for crate docs");
            });
        } else {
            self.stats.record_miss();
            tracing::span!(
                tracing::Level::TRACE,
                "cache",
                op = "get",
                hit = false,
                crate = crate_name
            )
            .in_scope(|| {
                tracing::trace!("Cache miss for crate docs");
            });
        }
        result
    }

    /// Set crate document cache
    ///
    /// # Arguments
    ///
    /// * `crate_name` - crate name
    /// * `version` - Optional version
    /// * `content` - Document content
    ///
    /// # Errors
    ///
    /// Returns error if cache operation fails
    #[tracing::instrument(skip(self, content), fields(crate = crate_name, version = version), err, level = "trace")]
    pub async fn set_crate_docs(
        &self,
        crate_name: &str,
        version: Option<&str>,
        content: String,
    ) -> crate::error::Result<()> {
        let key = CacheKeyGenerator::crate_cache_key(crate_name, version);
        let ttl = self.ttl.crate_docs_duration();
        self.cache.set(key, content, Some(ttl)).await?;
        self.stats.record_set();
        tracing::trace!(ttl_secs = ttl.as_secs(), "Crate docs cached");
        Ok(())
    }

    /// Get cached crate HTML
    ///
    /// Returns `Arc<str>` to avoid unnecessary cloning on cache hits.
    /// The caller can clone if an owned String is needed.
    #[tracing::instrument(skip(self), fields(crate = crate_name, version = version), level = "trace")]
    pub async fn get_crate_html(
        &self,
        crate_name: &str,
        version: Option<&str>,
    ) -> Option<Arc<str>> {
        let key = CacheKeyGenerator::crate_html_cache_key(crate_name, version);
        let result = self.cache.get(&key).await;
        let is_hit = result.is_some();
        if is_hit {
            self.stats.record_hit();
            tracing::span!(
                tracing::Level::TRACE,
                "cache",
                op = "get_html",
                hit = true,
                crate = crate_name
            )
            .in_scope(|| {
                tracing::trace!("Cache hit for crate HTML");
            });
        } else {
            self.stats.record_miss();
            tracing::span!(
                tracing::Level::TRACE,
                "cache",
                op = "get_html",
                hit = false,
                crate = crate_name
            )
            .in_scope(|| {
                tracing::trace!("Cache miss for crate HTML");
            });
        }
        result
    }

    /// Set crate HTML cache
    ///
    /// # Errors
    ///
    /// Returns error if cache operation fails
    #[tracing::instrument(skip(self, content), fields(crate = crate_name, version = version), err, level = "trace")]
    pub async fn set_crate_html(
        &self,
        crate_name: &str,
        version: Option<&str>,
        content: String,
    ) -> crate::error::Result<()> {
        let key = CacheKeyGenerator::crate_html_cache_key(crate_name, version);
        let ttl = self.ttl.crate_docs_duration();
        self.cache.set(key, content, Some(ttl)).await?;
        self.stats.record_set();
        tracing::trace!(ttl_secs = ttl.as_secs(), "Crate HTML cached");
        Ok(())
    }

    /// Get cached search results
    ///
    /// # Arguments
    ///
    /// * `query` - Search query
    /// * `limit` - Result count limit
    /// * `sort` - Optional search sort order
    ///
    /// # Returns
    ///
    /// Returns search results if cache hit;otherwise returns `None`
    #[tracing::instrument(skip(self), fields(query, limit, sort), level = "trace")]
    pub async fn get_search_results(
        &self,
        query: &str,
        limit: u32,
        sort: Option<&str>,
    ) -> Option<Arc<str>> {
        let key = CacheKeyGenerator::search_cache_key(query, limit, sort);
        let result = self.cache.get(&key).await;
        let is_hit = result.is_some();
        if is_hit {
            self.stats.record_hit();
            tracing::span!(
                tracing::Level::TRACE,
                "cache",
                op = "get_search",
                hit = true
            )
            .in_scope(|| {
                tracing::trace!("Cache hit for search results");
            });
        } else {
            self.stats.record_miss();
            tracing::span!(
                tracing::Level::TRACE,
                "cache",
                op = "get_search",
                hit = false
            )
            .in_scope(|| {
                tracing::trace!("Cache miss for search results");
            });
        }
        result
    }

    /// Set search results cache
    ///
    /// # Arguments
    ///
    /// * `query` - Search query
    /// * `limit` - Result count limit
    /// * `sort` - Optional search sort order
    /// * `content` - search result content
    ///
    /// # Errors
    ///
    /// Returns error if cache operation fails
    #[tracing::instrument(skip(self, content), fields(query, limit, sort), err, level = "trace")]
    pub async fn set_search_results(
        &self,
        query: &str,
        limit: u32,
        sort: Option<&str>,
        content: String,
    ) -> crate::error::Result<()> {
        let key = CacheKeyGenerator::search_cache_key(query, limit, sort);
        let ttl = self.ttl.search_results_duration();
        self.cache.set(key, content, Some(ttl)).await?;
        self.stats.record_set();
        tracing::trace!(ttl_secs = ttl.as_secs(), "Search results cached");
        Ok(())
    }

    /// Get cached item docs
    ///
    /// # Arguments
    ///
    /// * `crate_name` - crate name
    /// * `item_path` - Item path
    /// * `version` - Optional version
    ///
    /// # Returns
    ///
    /// Returns item docs if cache hit;otherwise returns `None`
    #[tracing::instrument(skip(self), fields(crate = crate_name, item = item_path, version), level = "trace")]
    pub async fn get_item_docs(
        &self,
        crate_name: &str,
        item_path: &str,
        version: Option<&str>,
    ) -> Option<Arc<str>> {
        let key = CacheKeyGenerator::item_cache_key(crate_name, item_path, version);
        let result = self.cache.get(&key).await;
        let is_hit = result.is_some();
        if is_hit {
            self.stats.record_hit();
            tracing::span!(tracing::Level::TRACE, "cache", op = "get_item", hit = true).in_scope(
                || {
                    tracing::trace!("Cache hit for item docs");
                },
            );
        } else {
            self.stats.record_miss();
            tracing::span!(tracing::Level::TRACE, "cache", op = "get_item", hit = false).in_scope(
                || {
                    tracing::trace!("Cache miss for item docs");
                },
            );
        }
        result
    }

    /// Set item docs cache
    ///
    /// # Arguments
    ///
    /// * `crate_name` - crate name
    /// * `item_path` - Item path
    /// * `version` - Optional version
    /// * `content` - Document content
    ///
    /// # Errors
    ///
    /// Returns error if cache operation fails
    #[tracing::instrument(skip(self, content), fields(crate = crate_name, item = item_path, version), err, level = "trace")]
    pub async fn set_item_docs(
        &self,
        crate_name: &str,
        item_path: &str,
        version: Option<&str>,
        content: String,
    ) -> crate::error::Result<()> {
        let key = CacheKeyGenerator::item_cache_key(crate_name, item_path, version);
        let ttl = self.ttl.item_docs_duration();
        self.cache.set(key, content, Some(ttl)).await?;
        self.stats.record_set();
        tracing::trace!(ttl_secs = ttl.as_secs(), "Item docs cached");
        Ok(())
    }

    /// Get cached item HTML
    ///
    /// Returns `Arc<str>` to avoid unnecessary cloning on cache hits.
    /// The caller can clone if an owned String is needed.
    #[tracing::instrument(skip(self), fields(crate = crate_name, item = item_path, version), level = "trace")]
    pub async fn get_item_html(
        &self,
        crate_name: &str,
        item_path: &str,
        version: Option<&str>,
    ) -> Option<Arc<str>> {
        let key = CacheKeyGenerator::item_html_cache_key(crate_name, item_path, version);
        let result = self.cache.get(&key).await;
        let is_hit = result.is_some();
        if is_hit {
            self.stats.record_hit();
            tracing::span!(
                tracing::Level::TRACE,
                "cache",
                op = "get_item_html",
                hit = true
            )
            .in_scope(|| {
                tracing::trace!("Cache hit for item HTML");
            });
        } else {
            self.stats.record_miss();
            tracing::span!(
                tracing::Level::TRACE,
                "cache",
                op = "get_item_html",
                hit = false
            )
            .in_scope(|| {
                tracing::trace!("Cache miss for item HTML");
            });
        }
        result
    }

    /// Set item HTML cache
    ///
    /// # Errors
    ///
    /// Returns error if cache operation fails
    #[tracing::instrument(skip(self, content), fields(crate = crate_name, item = item_path, version), err, level = "trace")]
    pub async fn set_item_html(
        &self,
        crate_name: &str,
        item_path: &str,
        version: Option<&str>,
        content: String,
    ) -> crate::error::Result<()> {
        let key = CacheKeyGenerator::item_html_cache_key(crate_name, item_path, version);
        let ttl = self.ttl.item_docs_duration();
        self.cache.set(key, content, Some(ttl)).await?;
        self.stats.record_set();
        tracing::trace!(ttl_secs = ttl.as_secs(), "Item HTML cached");
        Ok(())
    }

    /// Clear cache
    ///
    /// # Errors
    ///
    /// Returns error if cache operation fails
    #[tracing::instrument(skip(self), err, level = "trace")]
    pub async fn clear(&self) -> crate::error::Result<()> {
        tracing::trace!("Clearing all doc cache entries");
        self.cache.clear().await
    }

    /// Get cache statistics
    #[must_use]
    pub fn stats(&self) -> &CacheStats {
        &self.stats
    }

    /// Get TTL configuration
    #[must_use]
    pub fn ttl(&self) -> &DocCacheTtl {
        &self.ttl
    }
}

impl Default for DocCache {
    fn default() -> Self {
        let cache = Arc::new(crate::cache::memory::MemoryCache::new(1000));
        Self::new(cache)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cache::memory::MemoryCache;

    #[tokio::test]
    async fn test_doc_cache() {
        let memory_cache = MemoryCache::new(100);
        let cache = Arc::new(memory_cache);
        let doc_cache = DocCache::new(cache);

        // Test crate document cache
        doc_cache
            .set_crate_docs("serde", Some("1.0"), "Test docs".to_string())
            .await
            .expect("set_crate_docs should succeed");
        let cached = doc_cache.get_crate_docs("serde", Some("1.0")).await;
        assert_eq!(
            cached.as_ref().map(std::convert::AsRef::as_ref),
            Some("Test docs")
        );

        // Test search results cache
        doc_cache
            .set_search_results(
                "web framework",
                10,
                Some("relevance"),
                "Search results".to_string(),
            )
            .await
            .expect("set_search_results should succeed");
        let search_cached = doc_cache
            .get_search_results("web framework", 10, Some("relevance"))
            .await;
        assert_eq!(
            search_cached.as_ref().map(std::convert::AsRef::as_ref),
            Some("Search results")
        );

        // Test item docs cache
        doc_cache
            .set_item_docs(
                "serde",
                "serde::Serialize",
                Some("1.0"),
                "Item docs".to_string(),
            )
            .await
            .expect("set_item_docs should succeed");
        let item_cached = doc_cache
            .get_item_docs("serde", "serde::Serialize", Some("1.0"))
            .await;
        assert_eq!(
            item_cached.as_ref().map(std::convert::AsRef::as_ref),
            Some("Item docs")
        );

        // Test clear
        doc_cache.clear().await.expect("clear should succeed");
        let cleared = doc_cache.get_crate_docs("serde", Some("1.0")).await;
        assert_eq!(cleared, None);
    }

    #[tokio::test]
    async fn test_doc_cache_getters_preserve_shared_ownership() {
        let memory_cache = Arc::new(MemoryCache::new(100));
        let doc_cache = DocCache::new(memory_cache.clone());

        doc_cache
            .set_crate_docs("serde", Some("1.0"), "Test docs".to_string())
            .await
            .expect("set_crate_docs should succeed");

        let key = CacheKeyGenerator::crate_cache_key("serde", Some("1.0"));
        let cached_from_doc_cache = doc_cache
            .get_crate_docs("serde", Some("1.0"))
            .await
            .expect("doc cache should return cached docs");
        let cached_from_backend = memory_cache
            .get(&key)
            .await
            .expect("backend cache should return cached docs");

        assert!(Arc::ptr_eq(&cached_from_doc_cache, &cached_from_backend));
    }

    #[tokio::test]
    async fn test_doc_cache_with_ttl() {
        let memory_cache = MemoryCache::new(100);
        let cache = Arc::new(memory_cache);

        let mut ttl = DocCacheTtl::default();
        ttl.crate_docs_secs = 7200;
        ttl.search_results_secs = 600;
        ttl.item_docs_secs = 3600;
        ttl.set_jitter_ratio(0.0); // Disable jitter for predictable tests

        let doc_cache = DocCache::with_ttl(cache, ttl);

        assert_eq!(doc_cache.ttl().crate_docs_secs, 7200);
        assert_eq!(doc_cache.ttl().search_results_secs, 600);
        assert_eq!(doc_cache.ttl().item_docs_secs, 3600);
    }

    #[tokio::test]
    async fn test_doc_cache_stats() {
        let memory_cache = MemoryCache::new(100);
        let cache = Arc::new(memory_cache);
        let doc_cache = DocCache::new(cache);

        // Record a hit
        doc_cache
            .set_crate_docs("serde", None, "docs".to_string())
            .await
            .ok();
        doc_cache.get_crate_docs("serde", None).await;

        // Record a miss
        doc_cache.get_crate_docs("nonexistent", None).await;

        assert_eq!(doc_cache.stats().hits(), 1);
        assert_eq!(doc_cache.stats().misses(), 1);
        assert_eq!(doc_cache.stats().sets(), 1);
    }

    #[test]
    fn test_doc_cache_default() {
        let doc_cache = DocCache::default();
        assert_eq!(doc_cache.ttl().crate_docs_secs, 3600);
        assert_eq!(doc_cache.ttl().search_results_secs, 300);
        assert_eq!(doc_cache.ttl().item_docs_secs, 1800);
    }
}