cache

package
v0.0.0-...-63ce55b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 25, 2026 License: MIT Imports: 10 Imported by: 0

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

View Source
const (
	PrefixSession    = "session"
	PrefixUser       = "user"
	PrefixTemplate   = "template"
	PrefixQuota      = "quota"
	PrefixConfig     = "config"
	PrefixRepository = "repository"
	PrefixShare      = "share"
	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 ConfigKey

func ConfigKey(key string) string

Configuration cache keys

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 RepositoryKey

func RepositoryKey(repoID string) string

Repository cache keys

func SessionCollaboratorsKey

func SessionCollaboratorsKey(sessionID string) string

func SessionKey

func SessionKey(sessionID string) string

Session cache keys

func SessionPattern

func SessionPattern() string

Cache invalidation patterns

func SessionSharesKey

func SessionSharesKey(sessionID string) string

Share cache keys

func SessionStatsKey

func SessionStatsKey(sessionID string) string

func ShareInvitationKey

func ShareInvitationKey(token string) string

func TemplateByCategoryKey

func TemplateByCategoryKey(category string) string

func TemplateKey

func TemplateKey(templateName string) string

Template cache keys

func TemplatePattern

func TemplatePattern() string

func TemplateStatsKey

func TemplateStatsKey(templateName string) string

func UserByEmailKey

func UserByEmailKey(email string) string

func UserByUsernameKey

func UserByUsernameKey(username string) string

func UserFavoritesKey

func UserFavoritesKey(userID string) string

User-specific favorites key

func UserFavoritesPattern

func UserFavoritesPattern() string

User favorites invalidation pattern (invalidates all user favorite caches)

func UserKey

func UserKey(userID string) string

User cache keys

func UserPattern

func UserPattern(userID string) string

func UserQuotaKey

func UserQuotaKey(userID string) string

Quota cache keys

func UserSessionsKey

func UserSessionsKey(userID string) string

func UserSharedSessionsKey

func UserSharedSessionsKey(userID string) string

func UserStatsKey

func UserStatsKey(userID string) string

Stats cache keys

Types

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache provides caching functionality using Redis

func NewCache

func NewCache(config Config) (*Cache, error)

NewCache creates a new Redis cache client

func (*Cache) Close

func (c *Cache) Close() error

Close closes the Redis connection

func (*Cache) Delete

func (c *Cache) Delete(ctx context.Context, keys ...string) error

Delete removes a key from cache

func (*Cache) DeletePattern

func (c *Cache) DeletePattern(ctx context.Context, pattern string) error

DeletePattern deletes all keys matching a pattern

func (*Cache) Exists

func (c *Cache) Exists(ctx context.Context, key string) (bool, error)

Exists checks if a key exists in cache

func (*Cache) Expire

func (c *Cache) Expire(ctx context.Context, key string, ttl time.Duration) error

Expire sets a TTL on an existing key

func (*Cache) FlushAll

func (c *Cache) FlushAll(ctx context.Context) error

FlushAll clears all keys from cache (use with caution!)

func (*Cache) Get

func (c *Cache) Get(ctx context.Context, key string, target interface{}) error

Get retrieves a value from cache and unmarshals it into target

func (*Cache) GetStats

func (c *Cache) GetStats(ctx context.Context) (map[string]string, error)

GetStats returns cache statistics

func (*Cache) Increment

func (c *Cache) Increment(ctx context.Context, key string) (int64, error)

Increment atomically increments a counter

func (*Cache) IncrementBy

func (c *Cache) IncrementBy(ctx context.Context, key string, amount int64) (int64, error)

IncrementBy atomically increments a counter by a specific amount

func (*Cache) IsEnabled

func (c *Cache) IsEnabled() bool

IsEnabled returns whether caching is enabled

func (*Cache) Set

func (c *Cache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set stores a value in cache with the given TTL

func (*Cache) SetNX

func (c *Cache) SetNX(ctx context.Context, key string, value interface{}, ttl time.Duration) (bool, error)

SetNX sets a key only if it doesn't exist (for distributed locks)

func (*Cache) TTL

func (c *Cache) TTL(ctx context.Context, key string) (time.Duration, error)

TTL returns the remaining TTL for a key

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 Config

type Config struct {
	Host     string
	Port     string
	Password string
	DB       int
	Enabled  bool
}

Config holds cache configuration

type ResponseWriter

type ResponseWriter struct {
	gin.ResponseWriter
	// contains filtered or unexported fields
}

ResponseWriter is a custom response writer that captures the response body

func (*ResponseWriter) Write

func (w *ResponseWriter) Write(b []byte) (int, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL