cache

package
v0.18.1 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: GPL-3.0 Imports: 15 Imported by: 0

Documentation

Overview

Package cache provides an in-memory caching layer for oCMS.

Package cache provides caching infrastructure for oCMS.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RoleFromUser added in v0.3.0

func RoleFromUser(user *store.User) string

RoleFromUser extracts the role from a store.User. Returns "anonymous" if user is nil.

func SanitizeRedisURL added in v0.9.0

func SanitizeRedisURL(rawURL string) string

SanitizeRedisURL masks the password in a Redis URL for safe logging.

Types

type BackendType

type BackendType string

BackendType identifies the type of cache backend.

const (
	BackendMemory BackendType = "memory"
	BackendRedis  BackendType = "redis"
)

type Cache

type Cache interface {
	// Get retrieves a value from the cache.
	// Returns the value and nil error if found.
	// Returns nil and ErrCacheMiss if not found or expired.
	Get(ctx context.Context, key string) ([]byte, error)

	// Set stores a value in the cache with the specified TTL.
	// If TTL is 0, uses the default TTL.
	Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

	// Delete removes a key from the cache.
	Delete(ctx context.Context, key string) error

	// Clear removes all entries from the cache.
	Clear(ctx context.Context) error

	// Has checks if a key exists in the cache (and is not expired).
	Has(ctx context.Context, key string) (bool, error)

	// Close releases any resources held by the cache.
	Close() error
}

Cache defines the interface for cache implementations. All implementations must be thread-safe. This interface uses []byte for values to support both in-memory and Redis caches.

type Config

type Config struct {
	// Type is the cache backend type: "memory" or "redis"
	Type string

	// RedisURL is the Redis connection URL (only for redis type)
	// Example: redis://localhost:6379/0
	RedisURL string

	// Prefix is the key prefix for Redis (only for redis type)
	Prefix string

	// DefaultTTL is the default TTL for cache entries
	DefaultTTL time.Duration

	// MaxSize is the maximum number of entries for memory cache (0 = unlimited)
	MaxSize int

	// CleanupInterval is the interval for expired entry cleanup
	CleanupInterval time.Duration

	// FallbackToMemory enables automatic fallback to memory cache if Redis is unavailable
	FallbackToMemory bool
}

Config holds configuration for cache creation.

type ConfigCache

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

ConfigCache provides cached access to site configuration. It loads all config values once and serves them from memory, with automatic invalidation on updates.

func NewConfigCache

func NewConfigCache(queries *store.Queries) *ConfigCache

NewConfigCache creates a new config cache. TTL is set to 1 hour but cache is invalidated on any config change.

func (*ConfigCache) All

func (c *ConfigCache) All(ctx context.Context) (map[string]string, error)

All returns all config values.

func (*ConfigCache) Get

func (c *ConfigCache) Get(ctx context.Context, key string) (string, error)

Get retrieves a config value by key. Returns empty string if not found.

func (*ConfigCache) GetConfig

func (c *ConfigCache) GetConfig(ctx context.Context, key string) (store.Config, bool, error)

GetConfig retrieves a full config entry by key.

func (*ConfigCache) GetMultiple

func (c *ConfigCache) GetMultiple(ctx context.Context, keys ...string) (map[string]string, error)

GetMultiple retrieves multiple config values by keys.

func (*ConfigCache) Invalidate

func (c *ConfigCache) Invalidate()

Invalidate clears the cache and resets statistics, forcing a reload on next access.

func (*ConfigCache) InvalidateKey

func (c *ConfigCache) InvalidateKey(_ string)

InvalidateKey marks a specific key as needing reload. For simplicity, this invalidates the entire cache.

func (*ConfigCache) Preload

func (c *ConfigCache) Preload(ctx context.Context) error

Preload loads all config into cache. Useful for warming up the cache on startup.

func (*ConfigCache) ResetStats

func (c *ConfigCache) ResetStats()

ResetStats resets the cache statistics.

func (*ConfigCache) Stats

func (c *ConfigCache) Stats() Stats

Stats returns cache statistics.

type Context added in v0.4.0

type Context struct {
	LanguageCode string // "en", "ru", etc.
	Role         string // anonymous, public, editor, admin
}

Context holds context information for cache key generation. It captures language and role to create context-aware cache keys.

func DefaultContext added in v0.3.0

func DefaultContext() Context

DefaultContext returns a default cache context for anonymous English users.

func NewContext added in v0.4.0

func NewContext(langCode string, role string) Context

NewContext creates a new Context with the given language and role. If role is empty, defaults to "anonymous".

func (Context) PageIDKey added in v0.4.0

func (c Context) PageIDKey(id int64) string

PageIDKey generates a cache key for a page by ID. Format: {lang}:{role}:{id}

func (Context) PageKey added in v0.4.0

func (c Context) PageKey(slug string) string

PageKey generates a cache key for a page by slug. Format: {lang}:{role}:{slug}

type Error

type Error string

Error represents an error type for cache operations.

const (
	// ErrCacheMiss indicates the key was not found in cache or has expired.
	ErrCacheMiss Error = "cache miss"

	// ErrCacheClosed indicates the cache has been closed.
	ErrCacheClosed Error = "cache closed"
)

func (Error) Error

func (e Error) Error() string

type Kind

type Kind string

Kind identifies a specific cache.

const (
	KindConfig      Kind = "config"
	KindSitemap     Kind = "sitemap"
	KindMenu        Kind = "menu"
	KindLanguage    Kind = "language"
	KindTranslation Kind = "translation"
	KindPage        Kind = "page"
)

Kind constants for different cache types.

type LanguageCache

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

LanguageCache provides cached access to languages. Languages are cached for efficient lookups during request processing.

func NewLanguageCache

func NewLanguageCache(queries *store.Queries) *LanguageCache

NewLanguageCache creates a new language cache. TTL defaults to 1 hour but cache is invalidated on any language change.

func (*LanguageCache) GetActive

func (c *LanguageCache) GetActive(ctx context.Context) ([]store.Language, error)

GetActive retrieves only active languages.

func (*LanguageCache) GetAll

func (c *LanguageCache) GetAll(ctx context.Context) ([]store.Language, error)

GetAll retrieves all languages.

func (*LanguageCache) GetByCode

func (c *LanguageCache) GetByCode(ctx context.Context, code string) (*store.Language, error)

GetByCode retrieves a language by its code.

func (*LanguageCache) GetDefault

func (c *LanguageCache) GetDefault(ctx context.Context) (*store.Language, error)

GetDefault retrieves the default language.

func (*LanguageCache) Invalidate

func (c *LanguageCache) Invalidate()

Invalidate clears the cache and resets statistics, forcing a reload on next access.

func (*LanguageCache) IsActiveCode

func (c *LanguageCache) IsActiveCode(ctx context.Context, code string) (bool, error)

IsActiveCode checks if a language code is active.

func (*LanguageCache) Preload

func (c *LanguageCache) Preload(ctx context.Context) error

Preload loads all languages into cache. Useful for warming up the cache on startup.

func (*LanguageCache) ResetStats

func (c *LanguageCache) ResetStats()

ResetStats resets the cache statistics.

func (*LanguageCache) Stats

func (c *LanguageCache) Stats() Stats

Stats returns cache statistics.

type Manager

type Manager struct {
	Config      *ConfigCache
	Sitemap     *SitemapCache
	Menus       *MenuCache
	Language    *LanguageCache
	Translation *TranslationCache
	Page        *PageCache
	General     *SimpleCache // for misc cached data

	// Distributed cache (optional, nil if only using memory cache)
	Distributed Cache

	// Theme settings cache key prefix
	ThemeSettingsPrefix string
	// contains filtered or unexported fields
}

Manager manages all cache instances and provides a unified interface.

func NewManager

func NewManager(queries *store.Queries) *Manager

NewManager creates a new cache manager with default memory cache.

func NewManagerWithConfig

func NewManagerWithConfig(queries *store.Queries, cfg Config) *Manager

NewManagerWithConfig creates a new cache manager with optional distributed cache.

func (*Manager) AllStats

func (m *Manager) AllStats() []ManagerCacheStats

AllStats returns statistics for all caches.

func (*Manager) ClearAll

func (m *Manager) ClearAll()

ClearAll clears all caches and resets statistics.

func (*Manager) GetActiveLanguages

func (m *Manager) GetActiveLanguages(ctx context.Context) ([]store.Language, error)

GetActiveLanguages is a convenience method to get all active languages.

func (*Manager) GetConfig

func (m *Manager) GetConfig(ctx context.Context, key string) (string, error)

GetConfig is a convenience method to get a config value.

func (*Manager) GetDefaultLanguage

func (m *Manager) GetDefaultLanguage(ctx context.Context) (*store.Language, error)

GetDefaultLanguage is a convenience method to get the default language.

func (*Manager) GetLanguageByCode

func (m *Manager) GetLanguageByCode(ctx context.Context, code string) (*store.Language, error)

GetLanguageByCode is a convenience method to get a language by its code.

func (*Manager) GetMenu

func (m *Manager) GetMenu(ctx context.Context, slug string) (*MenuWithItems, error)

GetMenu is a convenience method to get a menu by slug.

func (*Manager) GetPublishedPageByID added in v0.3.0

func (m *Manager) GetPublishedPageByID(ctx context.Context, cacheCtx Context, id int64) (*store.Page, error)

GetPublishedPageByID is a convenience method to get a published page by ID. The cacheCtx provides language and role context for cache key generation.

func (*Manager) GetPublishedPageBySlug added in v0.3.0

func (m *Manager) GetPublishedPageBySlug(ctx context.Context, cacheCtx Context, slug string) (*store.Page, error)

GetPublishedPageBySlug is a convenience method to get a published page by slug. The cacheCtx provides language and role context for cache key generation.

func (*Manager) GetSitemap

func (m *Manager) GetSitemap(ctx context.Context, siteURL string) ([]byte, error)

GetSitemap is a convenience method to get the sitemap XML.

func (*Manager) GetTranslations

func (m *Manager) GetTranslations(ctx context.Context, entityType string, entityID int64) (TranslationMap, error)

GetTranslations is a convenience method to get translations for an entity.

func (*Manager) GetTranslationsBatch

func (m *Manager) GetTranslationsBatch(ctx context.Context, entityType string, entityIDs []int64) (map[int64]TranslationMap, error)

GetTranslationsBatch is a convenience method to get translations for multiple entities.

func (*Manager) HealthCheck

func (m *Manager) HealthCheck(ctx context.Context) error

HealthCheck performs a health check on the cache system. Returns nil if healthy, error otherwise.

func (*Manager) Info

func (m *Manager) Info() ManagerInfo

Info returns information about the cache manager configuration.

func (*Manager) InvalidateConfig

func (m *Manager) InvalidateConfig()

InvalidateConfig invalidates the config cache.

func (*Manager) InvalidateContent

func (m *Manager) InvalidateContent()

InvalidateContent invalidates content-related caches (sitemap, pages). Call this when pages, categories, or tags are created/updated/deleted.

func (*Manager) InvalidateLanguages

func (m *Manager) InvalidateLanguages()

InvalidateLanguages invalidates the language cache. Call this when languages are created/updated/deleted.

func (*Manager) InvalidateMenus

func (m *Manager) InvalidateMenus()

InvalidateMenus invalidates the menus cache. Call this when menus or menu items are created/updated/deleted.

func (*Manager) InvalidatePage added in v0.3.0

func (m *Manager) InvalidatePage(pageID int64)

InvalidatePage invalidates a specific page from the cache. Call this when a specific page is updated or deleted.

func (*Manager) InvalidatePages added in v0.3.0

func (m *Manager) InvalidatePages()

InvalidatePages invalidates the entire page cache. Call this after bulk operations on pages.

func (*Manager) InvalidateSitemap

func (m *Manager) InvalidateSitemap()

InvalidateSitemap invalidates the sitemap cache.

func (*Manager) InvalidateThemeSettings

func (m *Manager) InvalidateThemeSettings()

InvalidateThemeSettings invalidates theme settings in the config cache. Since theme settings are stored as config, we invalidate the entire config cache.

func (*Manager) InvalidateTranslation

func (m *Manager) InvalidateTranslation(entityType string, entityID int64)

InvalidateTranslation invalidates translation cache for a specific entity.

func (*Manager) InvalidateTranslations

func (m *Manager) InvalidateTranslations()

InvalidateTranslations invalidates the entire translation cache. Call this when translations are created/updated/deleted.

func (*Manager) IsRedis

func (m *Manager) IsRedis() bool

IsRedis returns true if using Redis as the distributed cache backend.

func (*Manager) Preload

func (m *Manager) Preload(ctx context.Context, siteURL string) error

Preload preloads caches with data.

func (*Manager) Start

func (m *Manager) Start()

Start starts background cleanup tasks.

func (*Manager) Stop

func (m *Manager) Stop()

Stop stops all background tasks and closes distributed cache.

func (*Manager) TotalStats

func (m *Manager) TotalStats() Stats

TotalStats returns aggregated statistics across all caches.

type ManagerCacheStats

type ManagerCacheStats struct {
	Name     string
	Kind     Kind
	Stats    Stats
	CachedAt *time.Time // when the cache was last populated (for sitemap)
	Size     int        // size in bytes (for sitemap)
}

ManagerCacheStats holds statistics for a specific cache in the manager.

type ManagerInfo

type ManagerInfo struct {
	BackendType BackendType // The distributed cache backend type
	IsFallback  bool        // True if fell back to memory due to Redis failure
	RedisURL    string      // Redis URL if using Redis (masked for security)
}

ManagerInfo holds information about the cache manager configuration.

type MemoryCache

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

MemoryCache is a thread-safe in-memory cache implementation. It implements the Cache interface using []byte values.

func NewMemoryCache

func NewMemoryCache(opts MemoryCacheOptions) *MemoryCache

NewMemoryCache creates a new memory cache with the given options.

func NewSimpleMemoryCache

func NewSimpleMemoryCache(ttl time.Duration) *MemoryCache

NewSimpleMemoryCache creates a memory cache with just a TTL (for backwards compatibility).

func (*MemoryCache) Clear

func (c *MemoryCache) Clear(_ context.Context) error

Clear removes all entries from the cache.

func (*MemoryCache) Close

func (c *MemoryCache) Close() error

Close stops the cleanup goroutine and releases resources.

func (*MemoryCache) Delete

func (c *MemoryCache) Delete(_ context.Context, key string) error

Delete removes a key from the cache.

func (*MemoryCache) DeleteByPrefix

func (c *MemoryCache) DeleteByPrefix(_ context.Context, prefix string) error

DeleteByPrefix removes all keys starting with the given prefix.

func (*MemoryCache) Get

func (c *MemoryCache) Get(_ context.Context, key string) ([]byte, error)

Get retrieves a value from the cache.

func (*MemoryCache) Has

func (c *MemoryCache) Has(_ context.Context, key string) (bool, error)

Has checks if a key exists in the cache (and is not expired).

func (*MemoryCache) Keys

func (c *MemoryCache) Keys() []string

Keys returns all keys in the cache (including expired ones).

func (*MemoryCache) ResetStats

func (c *MemoryCache) ResetStats()

ResetStats resets the cache statistics.

func (*MemoryCache) Set

func (c *MemoryCache) Set(_ context.Context, key string, value []byte, ttl time.Duration) error

Set stores a value in the cache with the specified TTL.

func (*MemoryCache) Stats

func (c *MemoryCache) Stats() Stats

Stats returns current cache statistics.

type MemoryCacheOptions

type MemoryCacheOptions struct {
	DefaultTTL      time.Duration
	MaxSize         int           // Maximum number of entries (0 = unlimited)
	CleanupInterval time.Duration // Interval for expired entry cleanup (0 = no cleanup)
}

MemoryCacheOptions configures the memory cache.

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

MenuCache provides cached access to menus. Menus are cached by slug for efficient frontend lookups.

func NewMenuCache

func NewMenuCache(queries *store.Queries) *MenuCache

NewMenuCache creates a new menu cache. TTL defaults to 1 hour but cache is invalidated on any menu change.

func (c *MenuCache) All(ctx context.Context) ([]*MenuWithItems, error)

All returns all cached menus, sorted by slug.

func (c *MenuCache) Get(ctx context.Context, slug string) (*MenuWithItems, error)

Get retrieves a menu by slug. Returns the menu with its items if found.

func (c *MenuCache) GetByID(ctx context.Context, id int64) (*MenuWithItems, error)

GetByID retrieves a menu by ID.

func (c *MenuCache) Invalidate()

Invalidate clears the cache and resets statistics, forcing a reload on next access.

func (c *MenuCache) InvalidateBySlug(_ string)

InvalidateBySlug invalidates a specific menu by slug. For simplicity, this invalidates the entire cache.

func (c *MenuCache) Preload(ctx context.Context) error

Preload loads all menus into cache. Useful for warming up the cache on startup.

func (c *MenuCache) ResetStats()

ResetStats resets the cache statistics.

func (c *MenuCache) Stats() Stats

Stats returns cache statistics.

type MenuWithItems struct {
	Menu  store.Menu
	Items []store.ListMenuItemsWithPageRow
}

MenuWithItems represents a menu with its items for caching. Items includes page data (title, slug) from JOIN for URL building.

type MultiTypedCache

type MultiTypedCache[T any] struct {
	*TypedCache[T]
}

MultiTypedCache provides multi-key operations for typed caches.

func NewMultiTypedCache

func NewMultiTypedCache[T any](cache Cache, defaultTTL time.Duration) *MultiTypedCache[T]

NewMultiTypedCache creates a new MultiTypedCache.

func (*MultiTypedCache[T]) DeleteMultiple

func (c *MultiTypedCache[T]) DeleteMultiple(ctx context.Context, keys []string) error

DeleteMultiple removes multiple keys from the cache.

func (*MultiTypedCache[T]) GetMultiple

func (c *MultiTypedCache[T]) GetMultiple(ctx context.Context, keys []string) map[string]*T

GetMultiple retrieves multiple values from the cache. Returns a map of found keys to their values.

func (*MultiTypedCache[T]) SetMultiple

func (c *MultiTypedCache[T]) SetMultiple(ctx context.Context, items map[string]*T) error

SetMultiple stores multiple values in the cache.

type PageCache added in v0.3.0

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

PageCache provides cached access to published pages. Pages are cached by context-aware keys: {lang}:{role}:{slug} or {lang}:{role}:{id}

func NewPageCache added in v0.3.0

func NewPageCache(queries *store.Queries) *PageCache

NewPageCache creates a new page cache. TTL defaults to 1 hour but cache is invalidated on any page change.

func (*PageCache) CacheEntryCount added in v0.3.0

func (c *PageCache) CacheEntryCount() int

CacheEntryCount returns the total number of cache entries (all context variants).

func (*PageCache) Count added in v0.3.0

func (c *PageCache) Count() int

Count returns the number of unique cached pages (not cache entries).

func (*PageCache) GetByID added in v0.3.0

func (c *PageCache) GetByID(ctx context.Context, cacheCtx Context, id int64) (*store.Page, error)

GetByID retrieves a published page by ID with context awareness. Returns the page if found in cache or database, nil if not found.

func (*PageCache) GetBySlug added in v0.3.0

func (c *PageCache) GetBySlug(ctx context.Context, cacheCtx Context, slug string) (*store.Page, error)

GetBySlug retrieves a published page by slug with context awareness. Returns the page if found in cache or database, nil if not found.

func (*PageCache) Invalidate added in v0.3.0

func (c *PageCache) Invalidate()

Invalidate clears the entire page cache and resets statistics.

func (*PageCache) InvalidateBySlug added in v0.3.0

func (c *PageCache) InvalidateBySlug(slug string)

InvalidateBySlug removes all cached variants of a page by slug pattern. This clears all language/role variants for pages with matching slugs.

func (*PageCache) InvalidatePage added in v0.3.0

func (c *PageCache) InvalidatePage(pageID int64)

InvalidatePage removes ALL cached variants of a page by ID. This clears all language/role variants at once.

func (*PageCache) Preload added in v0.3.0

func (c *PageCache) Preload(ctx context.Context, cacheCtx Context, limit int) error

Preload loads popular pages into cache for a specific context. This can be called on startup to warm the cache with frequently accessed pages.

func (*PageCache) ResetStats added in v0.3.0

func (c *PageCache) ResetStats()

ResetStats resets the cache statistics.

func (*PageCache) Stats added in v0.3.0

func (c *PageCache) Stats() Stats

Stats returns cache statistics.

type RedisCache

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

RedisCache is a Redis-based cache implementation. It implements the Cache interface for distributed caching.

func NewRedisCache

func NewRedisCache(opts RedisCacheOptions) (*RedisCache, error)

NewRedisCache creates a new Redis cache with the given options.

func NewRedisCacheFromURL

func NewRedisCacheFromURL(url string, prefix string, defaultTTL time.Duration) (*RedisCache, error)

NewRedisCacheFromURL creates a Redis cache from just a URL with default options.

func (*RedisCache) Clear

func (c *RedisCache) Clear(ctx context.Context) error

Clear removes all entries with the cache prefix. Note: This uses SCAN + DEL which is safer than KEYS for production use.

func (*RedisCache) Client

func (c *RedisCache) Client() *redis.Client

Client returns the underlying Redis client for advanced operations. Use with caution.

func (*RedisCache) Close

func (c *RedisCache) Close() error

Close closes the Redis connection.

func (*RedisCache) Delete

func (c *RedisCache) Delete(ctx context.Context, key string) error

Delete removes a key from the cache.

func (*RedisCache) DeleteByPrefix

func (c *RedisCache) DeleteByPrefix(ctx context.Context, prefix string) error

DeleteByPrefix removes all keys starting with the given prefix. The prefix is added to the cache's base prefix.

func (*RedisCache) Get

func (c *RedisCache) Get(ctx context.Context, key string) ([]byte, error)

Get retrieves a value from the cache.

func (*RedisCache) Has

func (c *RedisCache) Has(ctx context.Context, key string) (bool, error)

Has checks if a key exists in the cache.

func (*RedisCache) Info

func (c *RedisCache) Info(ctx context.Context) (string, error)

Info returns Redis server info.

func (*RedisCache) Ping

func (c *RedisCache) Ping(ctx context.Context) error

Ping checks if the Redis connection is healthy.

func (*RedisCache) ResetStats

func (c *RedisCache) ResetStats()

ResetStats resets the cache statistics.

func (*RedisCache) Set

func (c *RedisCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

Set stores a value in the cache with the specified TTL.

func (*RedisCache) Stats

func (c *RedisCache) Stats() Stats

Stats returns current cache statistics. Note: Redis doesn't track per-prefix stats, so we use local counters.

type RedisCacheOptions

type RedisCacheOptions struct {
	// URL is the Redis connection URL (e.g., redis://localhost:6379/0)
	URL string

	// Prefix is prepended to all keys (e.g., "ocms:")
	Prefix string

	// DefaultTTL is the default expiration time for cache entries
	DefaultTTL time.Duration

	// PoolSize is the maximum number of connections (0 = use default)
	PoolSize int

	// ConnectTimeout is the timeout for establishing a connection
	ConnectTimeout time.Duration

	// ReadTimeout is the timeout for read operations
	ReadTimeout time.Duration

	// WriteTimeout is the timeout for write operations
	WriteTimeout time.Duration
}

RedisCacheOptions configures the Redis cache.

func DefaultRedisCacheOptions

func DefaultRedisCacheOptions() RedisCacheOptions

DefaultRedisCacheOptions returns sensible defaults.

type Result

type Result struct {
	Cache       Cache
	BackendType BackendType
	IsFallback  bool // True if fell back to memory due to Redis failure
}

Result holds the created cache and metadata about it.

func NewCacheWithInfo

func NewCacheWithInfo(cfg Config) (*Result, error)

NewCacheWithInfo creates a cache and returns additional metadata about the cache type. If RedisURL is provided and type is "redis", attempts to create a Redis cache. Falls back to memory cache if Redis is unavailable and FallbackToMemory is true.

type SimpleCache

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

SimpleCache is a thread-safe in-memory cache with TTL support.

func New

func New(ttl time.Duration) *SimpleCache

New creates a new cache with the specified TTL.

func (*SimpleCache) Clear

func (c *SimpleCache) Clear()

Clear removes all entries from the cache.

func (*SimpleCache) Delete

func (c *SimpleCache) Delete(key string)

Delete removes a key from the cache.

func (*SimpleCache) DeleteByPrefix

func (c *SimpleCache) DeleteByPrefix(prefix string)

DeleteByPrefix removes all keys starting with the given prefix.

func (*SimpleCache) Get

func (c *SimpleCache) Get(key string) (any, bool)

Get retrieves a value from the cache. Returns the value and true if found and not expired, nil and false otherwise.

func (*SimpleCache) Keys

func (c *SimpleCache) Keys() []string

Keys returns all keys in the cache (including expired ones).

func (*SimpleCache) ResetStats

func (c *SimpleCache) ResetStats()

ResetStats resets the cache statistics.

func (*SimpleCache) Set

func (c *SimpleCache) Set(key string, value any)

Set stores a value in the cache with the default TTL.

func (*SimpleCache) SetWithTTL

func (c *SimpleCache) SetWithTTL(key string, value any, ttl time.Duration)

SetWithTTL stores a value in the cache with a custom TTL.

func (*SimpleCache) StartCleanup

func (c *SimpleCache) StartCleanup(interval time.Duration)

StartCleanup starts a background goroutine that periodically removes expired entries.

func (*SimpleCache) Stats

func (c *SimpleCache) Stats() Stats

Stats returns current cache statistics.

func (*SimpleCache) Stop

func (c *SimpleCache) Stop()

Stop stops the cleanup goroutine.

type SitemapCache

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

SitemapCache provides cached sitemap XML generation. The sitemap is regenerated when invalidated or when TTL expires.

func NewSitemapCache

func NewSitemapCache(queries *store.Queries, ttl time.Duration) *SitemapCache

NewSitemapCache creates a new sitemap cache. TTL defaults to 1 hour.

func (*SitemapCache) CachedAt

func (c *SitemapCache) CachedAt() time.Time

CachedAt returns when the sitemap was last cached.

func (*SitemapCache) Get

func (c *SitemapCache) Get(ctx context.Context, siteURL string) ([]byte, error)

Get returns the cached sitemap XML, generating it if needed.

func (*SitemapCache) Invalidate

func (c *SitemapCache) Invalidate()

Invalidate clears the cached sitemap and resets statistics, forcing regeneration on next request.

func (*SitemapCache) IsCached

func (c *SitemapCache) IsCached() bool

IsCached returns true if the sitemap is currently cached.

func (*SitemapCache) ResetStats

func (c *SitemapCache) ResetStats()

ResetStats resets the cache statistics.

func (*SitemapCache) Size

func (c *SitemapCache) Size() int

Size returns the size of the cached sitemap in bytes.

func (*SitemapCache) Stats

func (c *SitemapCache) Stats() Stats

Stats returns cache statistics.

type Stats

type Stats struct {
	Hits    int64      `json:"hits"`
	Misses  int64      `json:"misses"`
	Sets    int64      `json:"sets"`
	Items   int        `json:"items"`
	HitRate float64    `json:"hit_rate"`
	Size    int64      `json:"size_bytes,omitempty"` // Approximate size in bytes (used by distributed caches)
	ResetAt *time.Time `json:"reset_at,omitempty"`   // when stats were last reset (nil if never reset)
}

Stats holds cache statistics.

type StatsProvider

type StatsProvider interface {
	Stats() Stats
	ResetStats()
}

StatsProvider is an optional interface for caches that provide statistics.

type TranslationCache

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

TranslationCache provides cached access to translation mappings. Caches are organized by entity type for efficient bulk operations.

func NewTranslationCache

func NewTranslationCache(queries *store.Queries) *TranslationCache

NewTranslationCache creates a new translation cache.

func (*TranslationCache) Get

func (c *TranslationCache) Get(ctx context.Context, entityType string, entityID int64) (TranslationMap, error)

Get retrieves translation map for a specific entity. Returns a map of language code -> translated entity ID.

func (*TranslationCache) GetBatch

func (c *TranslationCache) GetBatch(ctx context.Context, entityType string, entityIDs []int64) (map[int64]TranslationMap, error)

GetBatch retrieves translations for multiple entities of the same type. This is more efficient than calling Get for each entity individually.

func (*TranslationCache) GetForLanguage

func (c *TranslationCache) GetForLanguage(ctx context.Context, entityType string, entityID int64, langCode string) (int64, bool, error)

GetForLanguage retrieves the translation ID for a specific entity and language.

func (*TranslationCache) Invalidate

func (c *TranslationCache) Invalidate()

Invalidate clears the entire translation cache.

func (*TranslationCache) InvalidateEntity

func (c *TranslationCache) InvalidateEntity(entityType string, entityID int64)

InvalidateEntity invalidates cache for a specific entity.

func (*TranslationCache) InvalidateType

func (c *TranslationCache) InvalidateType(entityType string)

InvalidateType invalidates all cache entries for an entity type.

func (*TranslationCache) ResetStats

func (c *TranslationCache) ResetStats()

ResetStats resets the cache statistics.

func (*TranslationCache) Stats

func (c *TranslationCache) Stats() Stats

Stats returns cache statistics.

type TranslationEntry

type TranslationEntry struct {
	EntityType    string
	EntityID      int64
	LanguageID    int64
	LanguageCode  string
	TranslationID int64
}

TranslationEntry represents a single translation link.

type TranslationMap

type TranslationMap map[string]int64

TranslationMap maps language code to translation ID for a single entity.

type TypedCache

type TypedCache[T any] struct {
	// contains filtered or unexported fields
}

TypedCache provides type-safe caching operations using generics. It wraps a Cache implementation and handles JSON serialization/deserialization.

func NewTypedCache

func NewTypedCache[T any](cache Cache, defaultTTL time.Duration) *TypedCache[T]

NewTypedCache creates a new TypedCache wrapping the given cache implementation.

func (*TypedCache[T]) Delete

func (c *TypedCache[T]) Delete(ctx context.Context, key string) error

Delete removes a key from the cache.

func (*TypedCache[T]) Get

func (c *TypedCache[T]) Get(ctx context.Context, key string) (*T, bool)

Get retrieves a value from the cache. Returns the value and true if found, zero value and false otherwise.

func (*TypedCache[T]) GetOrSet

func (c *TypedCache[T]) GetOrSet(ctx context.Context, key string, fn func() (*T, error)) (*T, error)

GetOrSet retrieves a value from cache, or calls the provided function to compute and store it if not found.

func (*TypedCache[T]) GetOrSetWithTTL

func (c *TypedCache[T]) GetOrSetWithTTL(ctx context.Context, key string, ttl time.Duration, fn func() (*T, error)) (*T, error)

GetOrSetWithTTL retrieves a value from cache, or calls the provided function to compute and store it if not found, using a custom TTL.

func (*TypedCache[T]) Has

func (c *TypedCache[T]) Has(ctx context.Context, key string) bool

Has checks if a key exists in the cache.

func (*TypedCache[T]) Set

func (c *TypedCache[T]) Set(ctx context.Context, key string, value *T) error

Set stores a value in the cache with the default TTL.

func (*TypedCache[T]) SetWithTTL

func (c *TypedCache[T]) SetWithTTL(ctx context.Context, key string, value *T, ttl time.Duration) error

SetWithTTL stores a value in the cache with a custom TTL.

Jump to

Keyboard shortcuts

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