Skip to content

Commit 208c6cc

Browse files
committed
Update 0.3.0
1 parent 267fdf3 commit 208c6cc

File tree

16 files changed

+203
-34
lines changed

16 files changed

+203
-34
lines changed

.github/workflows/publish.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ jobs:
9595
9696
- name: Type check
9797
run: |
98-
mypy src --ignore-missing-imports
98+
mypy src --ignore-missing-imports --disable-error-code=unused-ignore
9999
100100
build-and-publish:
101101
name: Build and Publish to PyPI

.github/workflows/test.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ jobs:
4747
4848
- name: Type check with mypy
4949
run: |
50-
mypy src --ignore-missing-imports
50+
mypy src --ignore-missing-imports --disable-error-code=unused-ignore
5151
5252
- name: Test with pytest
5353
run: |

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ repos:
1717
rev: v1.10.0
1818
hooks:
1919
- id: mypy
20-
args: [--ignore-missing-imports, --no-strict-optional]
20+
args: [--ignore-missing-imports, --no-strict-optional, --disable-error-code=unused-ignore]
2121
exclude: ^(scripts/|examples/)
2222
additional_dependencies:
2323
- types-PyYAML

=1.15.0

Lines changed: 0 additions & 7 deletions
This file was deleted.

=5.0.0

Whitespace-only changes.

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -262,13 +262,13 @@ async def get_user(user_id: int, db=Depends(cached_get_db)):
262262

263263
```python
264264
from fastapi import FastAPI
265-
from yokedcache.middleware import CacheMiddleware
265+
from yokedcache.middleware import HTTPCacheMiddleware
266266

267267
app = FastAPI()
268268

269269
# Add HTTP caching middleware
270270
app.add_middleware(
271-
CacheMiddleware,
271+
HTTPCacheMiddleware,
272272
cache_ttl=300,
273273
cache_key_prefix="http",
274274
include_paths=["/api/*"],
@@ -585,4 +585,4 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
585585

586586
---
587587

588-
**Made with care by [Project Yoked LLC](https://github.com/sirstig)**
588+
**Made with care by [SirStig](https://github.com/sirstig)**

docs/index.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ YokedCache is a powerful, async-first Python caching library that brings enterpr
1919
- **🛡️ Production-Ready**: Health checks, error handling, and security features
2020
- **🔐 Resilient**: Circuit breaker, retry logic, and graceful fallbacks *(v0.2.1)*
2121
- **⚡ Enhanced**: Smart async/sync context handling and performance optimizations *(v0.2.1)*
22+
- **🌐 Advanced Patterns**: HTTP middleware, single-flight protection, stale-while-revalidate *(v0.3.0)*
23+
- **🔍 Observability**: OpenTelemetry tracing and per-prefix backend routing *(v0.3.0)*
2224

2325
## Quick Start - Python FastAPI Redis Caching
2426

@@ -65,6 +67,7 @@ Powerful capabilities for complex use cases:
6567
- **[Backends & Setup](backends.md)** - Memory, Redis, Memcached backends with setup guides
6668
- **[Vector Search](vector-search.md)** - Semantic similarity search capabilities
6769
- **[Monitoring & Health](monitoring.md)** - Comprehensive monitoring, health checks, and alerting *(v0.2.1)*
70+
- **[Advanced Caching Patterns](usage-patterns.md#advanced-caching-patterns-v030)** - HTTP middleware, SWR, single-flight protection *(v0.3.0)*
6871

6972
### 📖 **Reference**
7073
Detailed technical documentation:
@@ -115,8 +118,20 @@ pip install yokedcache[vector] # Vector search
115118
pip install yokedcache[monitoring] # Prometheus & StatsD
116119
pip install yokedcache[memcached] # Memcached backend
117120
pip install yokedcache[fuzzy] # Fuzzy search
121+
pip install yokedcache[disk] # DiskCache backend (v0.3.0)
122+
pip install yokedcache[tracing] # OpenTelemetry tracing (v0.3.0)
118123
```
119124

125+
## What's New in 0.3.0
126+
127+
- **🌐 HTTP Response Middleware**: ETag/Cache-Control headers with 304 Not Modified responses
128+
- **🛡️ Single-Flight Protection**: Prevents cache stampede with automatic deduplication
129+
- **🔄 Stale-While-Revalidate**: Serve stale data while refreshing in background
130+
- **💪 Stale-If-Error**: Fallback to cached data during service failures
131+
- **🔀 Per-Prefix Routing**: Shard cache keys across multiple backends by prefix
132+
- **📊 OpenTelemetry Integration**: Distributed tracing with spans and metrics
133+
- **💾 New Backends**: DiskCache and SQLite backends for persistent caching
134+
120135
## What's New in 0.2.0
121136

122137
- **🆕 Multi-Backend Support**: Memory, Redis, and Memcached backends

docs/javascripts/schema.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
"price": "0",
3535
"priceCurrency": "USD"
3636
},
37-
"softwareVersion": "0.2.1",
37+
"softwareVersion": "0.3.0",
3838
"requirements": "Python 3.9+",
3939
"featureList": [
4040
"Redis caching with auto-invalidation",

docs/usage-patterns.md

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -543,6 +543,162 @@ async def get_with_fallback(key):
543543
)
544544
```
545545

546+
## Advanced Caching Patterns *(v0.3.0)*
547+
548+
YokedCache 0.3.0 introduces powerful advanced caching patterns designed for high-performance, production-ready applications.
549+
550+
### HTTP Response Middleware
551+
552+
Add HTTP caching middleware to FastAPI applications for automatic ETag and Cache-Control header management:
553+
554+
```python
555+
from fastapi import FastAPI
556+
from yokedcache import YokedCache
557+
from yokedcache.middleware import HTTPCacheMiddleware
558+
559+
app = FastAPI()
560+
cache = YokedCache()
561+
562+
# Add HTTP caching middleware
563+
app.add_middleware(
564+
HTTPCacheMiddleware,
565+
cache=cache,
566+
default_ttl=300,
567+
include_query=False,
568+
cache_control="public, max-age=300"
569+
)
570+
571+
@app.get("/api/users/{user_id}")
572+
async def get_user(user_id: int):
573+
# Response automatically cached with ETag headers
574+
# Returns 304 Not Modified for unchanged data
575+
return {"id": user_id, "name": "John Doe"}
576+
```
577+
578+
### Single-Flight Protection
579+
580+
Prevent cache stampede by ensuring only one request computes a value while others wait:
581+
582+
```python
583+
from yokedcache import YokedCache, CacheConfig
584+
585+
config = CacheConfig(
586+
redis_url="redis://localhost:6379",
587+
enable_single_flight=True
588+
)
589+
cache = YokedCache(config)
590+
591+
async def expensive_computation():
592+
# This will only run once, even with concurrent requests
593+
await asyncio.sleep(5)
594+
return compute_expensive_data()
595+
596+
# Multiple concurrent requests - only one computation runs
597+
results = await asyncio.gather(
598+
cache.fetch_or_set("expensive_key", expensive_computation, ttl=300),
599+
cache.fetch_or_set("expensive_key", expensive_computation, ttl=300),
600+
cache.fetch_or_set("expensive_key", expensive_computation, ttl=300),
601+
)
602+
# All results are identical, but computation only ran once
603+
```
604+
605+
### Stale-While-Revalidate (SWR)
606+
607+
Serve stale cached data immediately while refreshing in the background:
608+
609+
```python
610+
from yokedcache import YokedCache, CacheConfig
611+
612+
config = CacheConfig(
613+
redis_url="redis://localhost:6379",
614+
enable_stale_while_revalidate=True
615+
)
616+
cache = YokedCache(config)
617+
618+
# Function that returns stale data immediately and refreshes in background
619+
async def get_user_data(user_id: int):
620+
return await cache.fetch_or_set(
621+
f"user:{user_id}",
622+
lambda: fetch_user_from_db(user_id),
623+
ttl=60
624+
)
625+
```
626+
627+
### Stale-If-Error
628+
629+
Fallback to cached data when the primary data source fails:
630+
631+
```python
632+
from yokedcache import YokedCache, CacheConfig
633+
634+
config = CacheConfig(
635+
redis_url="redis://localhost:6379",
636+
enable_stale_if_error=True,
637+
stale_if_error_ttl=120 # Serve stale for up to 2 minutes after TTL expires
638+
)
639+
cache = YokedCache(config)
640+
641+
async def get_data_with_fallback(key: str):
642+
try:
643+
return await fetch_fresh_data(key)
644+
except Exception:
645+
# Returns stale cached data if available
646+
return await cache.get(key, default=None)
647+
```
648+
649+
### Per-Prefix Backend Routing
650+
651+
Route different cache keys to different backends based on key prefixes:
652+
653+
```python
654+
from yokedcache import YokedCache
655+
from yokedcache.backends import DiskCacheBackend, RedisBackend
656+
657+
cache = YokedCache()
658+
659+
# Setup prefix-based routing
660+
cache.setup_prefix_routing()
661+
662+
# Route different data types to different backends
663+
cache.add_backend_route("user:", RedisBackend("redis://localhost:6379/0"))
664+
cache.add_backend_route("temp:", DiskCacheBackend("/tmp/cache"))
665+
cache.add_backend_route("session:", RedisBackend("redis://localhost:6379/1"))
666+
667+
# Data automatically routed based on key prefix
668+
await cache.set("user:123", user_data) # -> Redis DB 0
669+
await cache.set("temp:abc", temp_data) # -> Disk cache
670+
await cache.set("session:xyz", session) # -> Redis DB 1
671+
```
672+
673+
### OpenTelemetry Distributed Tracing
674+
675+
Enable distributed tracing for cache operations:
676+
677+
```python
678+
from yokedcache import YokedCache, CacheConfig
679+
from yokedcache.tracing import initialize_tracing
680+
681+
# Initialize global tracing
682+
initialize_tracing(
683+
service_name="my-api",
684+
enabled=True,
685+
sample_rate=1.0
686+
)
687+
688+
config = CacheConfig(
689+
redis_url="redis://localhost:6379",
690+
enable_tracing=True
691+
)
692+
cache = YokedCache(config)
693+
694+
# All cache operations automatically traced
695+
async with cache._tracer.trace_operation("get_user", "user:123"):
696+
user = await cache.get("user:123")
697+
# Span includes timing, hit/miss, backend info
698+
```
699+
700+
These advanced patterns enable sophisticated caching strategies for high-performance, production applications.
701+
546702
## Performance Optimization Patterns
547703

548704
### Connection Reuse

examples/advanced_features_demo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""
22
YokedCache Advanced Features Demo
33
4-
This example demonstrates the new advanced caching features introduced in v0.2.4:
4+
This example demonstrates the new advanced caching features introduced in v0.3.0:
55
- HTTP Response Middleware
66
- Single-Flight Protection
77
- Stale-While-Revalidate

0 commit comments

Comments
 (0)