Documentation
¶
Overview ¶
Package cache provides Redis-based caching for StreamSpace API.
This file implements the core Redis cache client with connection pooling.
Purpose: - Provide high-performance caching for frequently accessed data - Reduce database load for read-heavy operations - Enable distributed caching across multiple API instances - Support atomic operations and distributed locks
Features: - Connection pooling (25 max connections, 5 min idle) - Automatic retry with exponential backoff - Graceful fallback when Redis is unavailable (cache disabled mode) - JSON serialization/deserialization - TTL-based expiration - Pattern-based invalidation - Atomic counters and distributed locks (SetNX) - Statistics and monitoring (pool stats, hit/miss tracking)
Cache Strategy:
- Get: Retrieve value, deserialize JSON
- Set: Serialize to JSON, store with TTL
- Delete: Remove single or multiple keys
- DeletePattern: Bulk invalidation via pattern matching
- SetNX: Distributed lock acquisition
Implementation Details: - Uses go-redis client with connection pooling - Auto-reconnection on connection failures - 3 retry attempts with 8-512ms exponential backoff - 5-second dial timeout, 3-second read/write timeouts - Values stored as JSON for flexibility
Thread Safety: - Redis client is thread-safe - Safe for concurrent access across goroutines
Dependencies: - github.com/redis/go-redis/v9 for Redis client
Example Usage:
// Initialize cache
cache, err := cache.NewCache(cache.Config{
Host: "localhost",
Port: "6379",
Password: "",
DB: 0,
Enabled: true,
})
if err != nil {
log.Fatal(err)
}
defer cache.Close()
// Store session in cache
err = cache.Set(ctx, cache.SessionKey("session-123"), session, 5*time.Minute)
// Retrieve from cache
var session Session
err = cache.Get(ctx, cache.SessionKey("session-123"), &session)
// Invalidate user's sessions
err = cache.DeletePattern(ctx, cache.UserPattern("user-123"))
Package cache provides Redis-based caching for StreamSpace API.
This file defines standardized cache key naming conventions and patterns.
Purpose: - Provide consistent cache key naming across all cache operations - Enable efficient cache invalidation via pattern matching - Organize cache keys by resource type - Support multi-level cache hierarchies
Features: - Resource-specific key prefixes (session, user, template, quota) - Hierarchical key structure (prefix:resource:identifier) - Pattern-based invalidation (session:*, user:123:*) - User-scoped keys for isolation - List and collection keys
Key Naming Convention:
- Format: {prefix}:{resource}:{identifier}
- Example: session:user1-firefox
- Example: user:username:alice
- Example: quota:user:user123
Key Patterns for Invalidation:
- session:* - All sessions
- *:user:123* - All user-specific caches
- template:category:browsers - Templates in category
Implementation Details: - Keys use colon (:) as separator for Redis best practices - Prefixes prevent key collisions across resource types - Patterns use wildcards (*) for bulk invalidation
Example Usage:
// Generate cache key for session
key := cache.SessionKey("user1-firefox")
// Result: "session:user1-firefox"
// Generate key for user by username
key := cache.UserByUsernameKey("alice")
// Result: "user:username:alice"
// Invalidate all user-related caches
pattern := cache.UserPattern("user123")
err := cache.DeletePattern(ctx, pattern)
// Deletes: user:user123, session:user:user123:list, quota:user:user123, etc.
Package cache provides Redis-based caching for StreamSpace API.
This file implements HTTP caching middleware for Gin framework.
Purpose: - Cache HTTP GET responses to reduce backend load - Automatically invalidate cache on mutations (POST, PUT, DELETE) - Add cache control headers for browser/CDN caching - Provide cache hit/miss transparency
Features: - Response caching for GET requests - Cache key generation from request URI (SHA-256 hash) - Automatic cache invalidation after mutations - X-Cache header (HIT/MISS) for debugging - Async cache operations (non-blocking) - Cache-Control headers for browser caching
Middleware Types:
- CacheMiddleware: Caches GET responses
- InvalidateCacheMiddleware: Clears cache after mutations
- CacheControl: Adds Cache-Control headers
Implementation Details: - Only caches successful responses (2xx status codes) - Response body captured via custom ResponseWriter - Cache operations run asynchronously to avoid blocking requests - Cache keys generated via SHA-256 hash of request URI - Gracefully handles cache unavailability (continues without caching)
Thread Safety: - Middleware is thread-safe (uses goroutines for async operations) - Safe for concurrent requests
Dependencies: - github.com/gin-gonic/gin for HTTP framework
Example Usage:
// Apply response caching middleware
router.Use(cache.CacheMiddleware(cacheClient, 5*time.Minute))
// Apply cache invalidation for mutations
router.POST("/sessions", cache.InvalidateCacheMiddleware(cacheClient, cache.SessionPattern()), handler)
// Add cache control headers
router.Use(cache.CacheControl(1*time.Hour))
// Result:
// - GET /sessions: Cached for 5 minutes, X-Cache: HIT/MISS header added
// - POST /sessions: Invalidates all session:* keys
// - Response includes: Cache-Control: public, max-age=3600
Index ¶
- Constants
- func AllConfigKey() string
- func AllQuotasKey() string
- func AllRepositoriesKey() string
- func AllSessionsKey() string
- func AllTemplatesKey() string
- func AllUsersKey() string
- func CacheControl(maxAge time.Duration) gin.HandlerFunc
- func CacheMiddleware(cache *Cache, ttl time.Duration) gin.HandlerFunc
- func ConfigKey(key string) string
- func FeaturedTemplatesKey() string
- func GlobalStatsKey() string
- func InvalidateCacheMiddleware(cache *Cache, pattern string) gin.HandlerFunc
- func QuotaPattern() string
- func RepositoryKey(repoID string) string
- func SessionCollaboratorsKey(sessionID string) string
- func SessionKey(sessionID string) string
- func SessionPattern() string
- func SessionSharesKey(sessionID string) string
- func SessionStatsKey(sessionID string) string
- func ShareInvitationKey(token string) string
- func TemplateByCategoryKey(category string) string
- func TemplateKey(templateName string) string
- func TemplatePattern() string
- func TemplateStatsKey(templateName string) string
- func UserByEmailKey(email string) string
- func UserByUsernameKey(username string) string
- func UserFavoritesKey(userID string) string
- func UserFavoritesPattern() string
- func UserKey(userID string) string
- func UserPattern(userID string) string
- func UserQuotaKey(userID string) string
- func UserSessionsKey(userID string) string
- func UserSharedSessionsKey(userID string) string
- func UserStatsKey(userID string) string
- type Cache
- func (c *Cache) Close() error
- func (c *Cache) Delete(ctx context.Context, keys ...string) error
- func (c *Cache) DeletePattern(ctx context.Context, pattern string) error
- func (c *Cache) Exists(ctx context.Context, key string) (bool, error)
- func (c *Cache) Expire(ctx context.Context, key string, ttl time.Duration) error
- func (c *Cache) FlushAll(ctx context.Context) error
- func (c *Cache) Get(ctx context.Context, key string, target interface{}) error
- func (c *Cache) GetStats(ctx context.Context) (map[string]string, error)
- func (c *Cache) Increment(ctx context.Context, key string) (int64, error)
- func (c *Cache) IncrementBy(ctx context.Context, key string, amount int64) (int64, error)
- func (c *Cache) IsEnabled() bool
- func (c *Cache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
- func (c *Cache) SetNX(ctx context.Context, key string, value interface{}, ttl time.Duration) (bool, error)
- func (c *Cache) TTL(ctx context.Context, key string) (time.Duration, error)
- type CachedResponse
- type Config
- type ResponseWriter
Constants ¶
const ( PrefixSession = "session" PrefixUser = "user" PrefixTemplate = "template" PrefixQuota = "quota" PrefixConfig = "config" PrefixRepository = "repository" PrefixStats = "stats" )
Key prefixes for different resource types
Variables ¶
This section is empty.
Functions ¶
func AllConfigKey ¶
func AllConfigKey() string
func AllQuotasKey ¶
func AllQuotasKey() string
func AllRepositoriesKey ¶
func AllRepositoriesKey() string
func AllSessionsKey ¶
func AllSessionsKey() string
func AllTemplatesKey ¶
func AllTemplatesKey() string
func AllUsersKey ¶
func AllUsersKey() string
func CacheControl ¶
func CacheControl(maxAge time.Duration) gin.HandlerFunc
CacheControl middleware adds cache control headers to responses
func CacheMiddleware ¶
func CacheMiddleware(cache *Cache, ttl time.Duration) gin.HandlerFunc
CacheMiddleware returns a Gin middleware for caching GET requests
func FeaturedTemplatesKey ¶
func FeaturedTemplatesKey() string
func GlobalStatsKey ¶
func GlobalStatsKey() string
func InvalidateCacheMiddleware ¶
func InvalidateCacheMiddleware(cache *Cache, pattern string) gin.HandlerFunc
InvalidateCacheMiddleware clears related cache entries after mutations
func QuotaPattern ¶
func QuotaPattern() string
func SessionCollaboratorsKey ¶
func SessionStatsKey ¶
func ShareInvitationKey ¶
func TemplateByCategoryKey ¶
func TemplatePattern ¶
func TemplatePattern() string
func TemplateStatsKey ¶
func UserByEmailKey ¶
func UserByUsernameKey ¶
func UserFavoritesPattern ¶
func UserFavoritesPattern() string
User favorites invalidation pattern (invalidates all user favorite caches)
func UserPattern ¶
func UserSessionsKey ¶
func UserSharedSessionsKey ¶
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache provides caching functionality using Redis
func (*Cache) DeletePattern ¶
DeletePattern deletes all keys matching a pattern
func (*Cache) IncrementBy ¶
IncrementBy atomically increments a counter by a specific amount
type CachedResponse ¶
type CachedResponse struct {
StatusCode int `json:"status_code"`
Headers map[string]string `json:"headers"`
Body string `json:"body"`
}
CachedResponse represents a cached HTTP response
type ResponseWriter ¶
type ResponseWriter struct {
gin.ResponseWriter
// contains filtered or unexported fields
}
ResponseWriter is a custom response writer that captures the response body