Documentation
¶
Index ¶
- Constants
- Variables
- func CompressBrotli(data []byte) ([]byte, error)
- func CompressForClient(data []byte, encoding string) ([]byte, error)
- func CompressGzip(data []byte) ([]byte, error)
- func CompressZstd(data []byte) ([]byte, error)
- func DecompressBrotli(data []byte) ([]byte, error)
- func DecompressGzip(data []byte) ([]byte, error)
- type AdminMetrics
- type CacheStats
- type DiskCache
- func (dc *DiskCache) Delete(key string) error
- func (dc *DiskCache) Get(key string) (*DiskCacheItem, error)
- func (dc *DiskCache) List() []string
- func (dc *DiskCache) LoadIndex() error
- func (dc *DiskCache) Put(key string, item *DiskCacheItem) error
- func (dc *DiskCache) Stats() (itemCount int64, diskUsage int64)
- type DiskCacheItem
- type MemoryCache
- func (c *MemoryCache[K, V]) Cost() int
- func (c *MemoryCache[K, V]) Delete(key K)
- func (c *MemoryCache[K, V]) Get(key K) (*V, bool)
- func (c *MemoryCache[K, V]) GetLRUKeys(limit int) []K
- func (c *MemoryCache[K, V]) LoadOrCompute(key K, valueFn func() (V, int, bool)) (actual V, loaded bool)
- func (c *MemoryCache[K, V]) Peek(key K) (*V, bool)
- func (c *MemoryCache[K, V]) Put(key K, value V, cost int) bool
- func (c *MemoryCache[K, V]) Range(f func(key K, value V) bool)
- func (c *MemoryCache[K, V]) Size() int
- type MemoryCacheItem
- type Metadata
- type MetricsCollector
- func (m *MetricsCollector) Cleanup()
- func (m *MetricsCollector) GetRates() map[string]map[string]float64
- func (m *MetricsCollector) MetricsMiddleware(next func(w http.ResponseWriter, r *http.Request) error, serverName string) func(w http.ResponseWriter, r *http.Request) error
- func (m *MetricsCollector) RecordCacheOperation(operation, status, serverName string)
- func (m *MetricsCollector) RecordItemSize(itemType, serverName string, size int64)
- func (m *MetricsCollector) RecordResponseTime(cacheStatus, serverName string, duration time.Duration)
- func (m *MetricsCollector) Reset()
- func (m *MetricsCollector) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (m *MetricsCollector) StartMetricsUpdater(storage *Storage, serverName string)
- func (m *MetricsCollector) UpdateCacheStats(serverName string, memStats, diskStats *CacheStats)
- type NopResponseWriter
- type ResponseWriter
- func (r *ResponseWriter) Close() error
- func (r *ResponseWriter) Flush()
- func (r *ResponseWriter) Header() http.Header
- func (r *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (r *ResponseWriter) Push(target string, opts *http.PushOptions) error
- func (r *ResponseWriter) Unwrap() http.ResponseWriter
- func (r *ResponseWriter) Write(b []byte) (int, error)
- func (r *ResponseWriter) WriteHeader(status int)
- type Sidekick
- func (Sidekick) CaddyModule() caddy.ModuleInfo
- func (s *Sidekick) Cleanup() error
- func (s *Sidekick) Provision(ctx caddy.Context) error
- func (s *Sidekick) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error
- func (s *Sidekick) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
- type Storage
- func (s *Storage) Flush() error
- func (s *Storage) Get(key string) ([]byte, *Metadata, error)
- func (s *Storage) GetDiskCache() *DiskCache
- func (s *Storage) GetMemCache() *MemoryCache[string, *MemoryCacheItem]
- func (s *Storage) List() map[string][]string
- func (s *Storage) Purge(key string) error
- func (s *Storage) Set(url string, metadata *Metadata, data []byte) error
- func (s *Storage) SetWithKey(key string, metadata *Metadata, data []byte) error
- func (s *Storage) WaitForAsyncOps()
- type SyncHandler
Constants ¶
const ( DefaultCacheDir = "/var/www/html/wp-content/cache" DefaultMemoryItemMaxSize = 4 * 1024 * 1024 // 4MB DefaultMemoryCacheMaxSize = 128 * 1024 * 1024 // 128MB DefaultMemoryCacheMaxCount = 32 * 1024 // 32K items DefaultBypassDebugQuery = "sidekick-nocache" DefaultPurgePath = "/__sidekick/purge" DefaultPurgeHeader = "X-Sidekick-Purge" DefaultPurgeToken = "dead-beef" CacheHeaderName = "X-Sidekick-Cache" // Not configurable DefaultNoCacheRegex = `` /* 129-byte string literal not displayed */ DefaultTTL = 300 DefaultDiskItemMaxSize = 100 * 1024 * 1024 // 100MB DefaultDiskMaxSize = 10 * 1024 * 1024 * 1024 // 10GB DefaultDiskMaxCount = 100000 // 100K items on disk DefaultStreamToDiskSize = 10 * 1024 * 1024 // 10MB DefaultBufferSize = 32 * 1024 // 32KB buffer size DefaultWPMuPluginEnabled = true // Enable mu-plugin management by default DefaultWPMuPluginDir = "/var/www/html/wp-content/mu-plugins" // Default mu-plugins directory )
Constants for default values
Variables ¶
var ( ErrCacheExpired = errors.New("cache expired") ErrCacheNotFound = errors.New("cache not found") )
Package-level errors
var CachedContentEncoding = []string{
"none",
"gzip",
"br",
"zstd",
}
Functions ¶
func CompressBrotli ¶
CompressBrotli compresses data using brotli
func CompressForClient ¶ added in v0.0.3
CompressForClient compresses data based on the requested encoding
func CompressGzip ¶
CompressGzip compresses data using gzip
func CompressZstd ¶ added in v0.0.3
CompressZstd compresses data using zstd
func DecompressBrotli ¶
DecompressBrotli decompresses brotli data Used internally for disk storage decompression
func DecompressGzip ¶
DecompressGzip decompresses gzip data Used internally for disk storage decompression
Types ¶
type AdminMetrics ¶ added in v0.0.4
type AdminMetrics struct {
// contains filtered or unexported fields
}
AdminMetrics is a Caddy admin module that exposes sidekick metrics
func (AdminMetrics) CaddyModule ¶ added in v0.0.4
func (AdminMetrics) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (*AdminMetrics) Cleanup ¶ added in v0.0.4
func (am *AdminMetrics) Cleanup() error
Cleanup cleans up the admin metrics handler
func (*AdminMetrics) Provision ¶ added in v0.0.4
func (am *AdminMetrics) Provision(ctx caddy.Context) error
Provision sets up the admin metrics handler.
func (*AdminMetrics) Routes ¶ added in v0.0.4
func (am *AdminMetrics) Routes() []caddy.AdminRoute
Routes returns the routes for the admin API.
type CacheStats ¶ added in v0.0.4
type CacheStats struct {
UsedBytes int64
LimitBytes int64 // -1 for unlimited, 0 for disabled
UsedCount int64
LimitCount int64 // -1 for unlimited, 0 for disabled
}
CacheStats holds cache statistics
type DiskCache ¶
type DiskCache struct {
// contains filtered or unexported fields
}
DiskCache wraps the generic LRU cache with disk-specific functionality
func NewDiskCache ¶
func NewDiskCache(basePath string, maxItemCount int, maxDiskSize int64, maxItemSize int64, logger *zap.Logger) *DiskCache
NewDiskCache creates a new disk cache instance
func (*DiskCache) Get ¶
func (dc *DiskCache) Get(key string) (*DiskCacheItem, error)
Get retrieves an item from disk cache
func (*DiskCache) LoadIndex ¶
LoadIndex loads the disk cache index from filesystem This is called on startup to rebuild the cache index
type DiskCacheItem ¶
type DiskCacheItem struct {
*Metadata
Path string // File path on disk
Size int64 // Size in bytes
AccessTime time.Time // Last access time
ModTime time.Time // Last modification time
}
DiskCacheItem represents an item stored in disk cache
type MemoryCache ¶
type MemoryCache[K comparable, V any] struct { // contains filtered or unexported fields }
func NewMemoryCache ¶
func NewMemoryCache[K comparable, V any](capacityCount int, capacityCost int) *MemoryCache[K, V]
func (*MemoryCache[K, V]) Cost ¶
func (c *MemoryCache[K, V]) Cost() int
func (*MemoryCache[K, V]) Delete ¶
func (c *MemoryCache[K, V]) Delete(key K)
func (*MemoryCache[K, V]) Get ¶
func (c *MemoryCache[K, V]) Get(key K) (*V, bool)
func (*MemoryCache[K, V]) GetLRUKeys ¶
func (c *MemoryCache[K, V]) GetLRUKeys(limit int) []K
GetLRUKeys returns a slice of keys in LRU order (oldest first) This is useful for eviction strategies
func (*MemoryCache[K, V]) LoadOrCompute ¶
func (c *MemoryCache[K, V]) LoadOrCompute(key K, valueFn func() (V, int, bool)) (actual V, loaded bool)
LoadOrCompute returns the existing value for the key if present. Otherwise, it computes the value using the provided function and returns the computed value. The loaded result is true if the value was loaded, false if stored.
func (*MemoryCache[K, V]) Peek ¶
func (c *MemoryCache[K, V]) Peek(key K) (*V, bool)
func (*MemoryCache[K, V]) Put ¶
func (c *MemoryCache[K, V]) Put(key K, value V, cost int) bool
func (*MemoryCache[K, V]) Range ¶
func (c *MemoryCache[K, V]) Range(f func(key K, value V) bool)
Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.
Range does not necessarily correspond to any consistent snapshot of the Map's contents: no key will be visited more than once, but if the value for any key is stored or deleted concurrently, Range may reflect any mapping for that key from any point during the Range call.
func (*MemoryCache[K, V]) Size ¶
func (c *MemoryCache[K, V]) Size() int
type MemoryCacheItem ¶
type MemoryCacheItem struct {
*Metadata
// contains filtered or unexported fields
}
type Metadata ¶
type Metadata struct {
StateCode int `json:"c,omitempty"`
Header [][]string `json:"h,omitempty"`
Timestamp int64 `json:"t,omitempty"`
Path string `json:"p,omitempty"` // Original request path
// contains filtered or unexported fields
}
func NewMetadataWithPath ¶
NewMetadataWithPath creates metadata with path information
func (*Metadata) LoadFromFile ¶
func (*Metadata) WriteToFile ¶
type MetricsCollector ¶ added in v0.0.4
type MetricsCollector struct {
// contains filtered or unexported fields
}
MetricsCollector handles all metrics collection for the sidekick plugin
func GetMetrics ¶ added in v0.0.4
func GetMetrics() *MetricsCollector
GetMetrics returns the global metrics instance if it exists
func GetOrCreateGlobalMetrics ¶ added in v0.0.4
func GetOrCreateGlobalMetrics(logger *zap.Logger) *MetricsCollector
GetOrCreateGlobalMetrics returns the global metrics instance, creating it if needed
func NewMetricsCollector ¶ added in v0.0.4
func NewMetricsCollector(logger *zap.Logger) *MetricsCollector
NewMetricsCollector creates a new metrics collector with its own registry
func (*MetricsCollector) Cleanup ¶ added in v0.0.4
func (m *MetricsCollector) Cleanup()
Cleanup stops the metrics collector and cleans up resources
func (*MetricsCollector) GetRates ¶ added in v0.0.4
func (m *MetricsCollector) GetRates() map[string]map[string]float64
GetRates returns the current hit, miss, and bypass rates for each cache type
func (*MetricsCollector) MetricsMiddleware ¶ added in v0.0.4
func (m *MetricsCollector) MetricsMiddleware(next func(w http.ResponseWriter, r *http.Request) error, serverName string) func(w http.ResponseWriter, r *http.Request) error
MetricsMiddleware wraps an HTTP handler to collect metrics
func (*MetricsCollector) RecordCacheOperation ¶ added in v0.0.4
func (m *MetricsCollector) RecordCacheOperation(operation, status, serverName string)
RecordCacheOperation records a cache operation with simplified metrics
func (*MetricsCollector) RecordItemSize ¶ added in v0.0.4
func (m *MetricsCollector) RecordItemSize(itemType, serverName string, size int64)
RecordItemSize records the size of a cached item for distribution analysis
func (*MetricsCollector) RecordResponseTime ¶ added in v0.0.4
func (m *MetricsCollector) RecordResponseTime(cacheStatus, serverName string, duration time.Duration)
RecordResponseTime records the response time for a request
func (*MetricsCollector) Reset ¶ added in v0.0.4
func (m *MetricsCollector) Reset()
Reset resets all metrics (useful for testing)
func (*MetricsCollector) ServeHTTP ¶ added in v0.0.4
func (m *MetricsCollector) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves the Prometheus metrics endpoint
func (*MetricsCollector) StartMetricsUpdater ¶ added in v0.0.4
func (m *MetricsCollector) StartMetricsUpdater(storage *Storage, serverName string)
StartMetricsUpdater starts a goroutine that periodically updates metrics
func (*MetricsCollector) UpdateCacheStats ¶ added in v0.0.4
func (m *MetricsCollector) UpdateCacheStats(serverName string, memStats, diskStats *CacheStats)
UpdateCacheStats updates cache statistics
type NopResponseWriter ¶
func (*NopResponseWriter) Header ¶
func (nop *NopResponseWriter) Header() http.Header
func (*NopResponseWriter) WriteHeader ¶
func (nop *NopResponseWriter) WriteHeader(statusCode int)
type ResponseWriter ¶
type ResponseWriter struct {
http.ResponseWriter
*http.Request
*Storage
*zap.Logger
// contains filtered or unexported fields
}
ResponseWriter handles the response and provide the way to cache the value
func NewResponseWriter ¶
func (*ResponseWriter) Close ¶
func (r *ResponseWriter) Close() error
Close sets cache on response end
func (*ResponseWriter) Flush ¶
func (r *ResponseWriter) Flush()
Implement http.Flusher interface if the underlying ResponseWriter supports it
func (*ResponseWriter) Header ¶
func (r *ResponseWriter) Header() http.Header
func (*ResponseWriter) Hijack ¶
func (r *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Implement http.Hijacker interface if the underlying ResponseWriter supports it
func (*ResponseWriter) Push ¶
func (r *ResponseWriter) Push(target string, opts *http.PushOptions) error
Implement http.Pusher interface if the underlying ResponseWriter supports it
func (*ResponseWriter) Unwrap ¶
func (r *ResponseWriter) Unwrap() http.ResponseWriter
func (*ResponseWriter) Write ¶
func (r *ResponseWriter) Write(b []byte) (int, error)
Write will write the response body
func (*ResponseWriter) WriteHeader ¶
func (r *ResponseWriter) WriteHeader(status int)
type Sidekick ¶
type Sidekick struct {
CacheDir string `json:"cache_dir,omitempty"`
PurgePath string `json:"purge_path,omitempty"`
PurgeURL string `json:"purge_url,omitempty"`
PurgeHeader string `json:"purge_header,omitempty"`
PurgeToken string `json:"purge_token,omitempty"`
Metrics string `json:"metrics,omitempty"` // Admin API path to expose metrics (e.g., "/metrics/sidekick")
NoCache []string `json:"nocache,omitempty"` // Path prefixes to bypass
NoCacheRegex string `json:"nocache_regex,omitempty"` // Regex pattern to bypass
NoCacheHome bool `json:"nocache_home,omitempty"` // Whether to skip caching home page
CacheResponseCodes []string `json:"cache_response_codes,omitempty"`
CacheTTL int `json:"cache_ttl,omitempty"` // TTL in seconds
Storage *Storage
// WordPress mu-plugin configuration
WPMuPluginEnabled bool `json:"wp_mu_plugin_enabled,omitempty"` // Whether to manage mu-plugins
WPMuPluginDir string `json:"wp_mu_plugin_dir,omitempty"` // Directory for mu-plugins
// Size configurations (stored as int64 for byte values)
CacheMemoryItemMaxSize int64 `json:"cache_memory_item_max_size,omitempty"` // Max size for single item in memory
CacheMemoryMaxSize int64 `json:"cache_memory_max_size,omitempty"` // Total memory cache size limit
CacheMemoryMaxPercent int `json:"cache_memory_max_percent,omitempty"` // Memory cache as percent of available RAM (1-100)
CacheMemoryMaxCount int `json:"cache_memory_max_count,omitempty"` // Max number of items in memory
CacheMemoryStreamToDiskSize int64 `json:"cache_memory_stream_to_disk_size,omitempty"` // Threshold to stream to disk
CacheDiskItemMaxSize int64 `json:"cache_disk_item_max_size,omitempty"` // Max size for any cached item on disk
CacheDiskMaxSize int64 `json:"cache_disk_max_size,omitempty"` // Total disk cache size limit
CacheDiskMaxPercent int `json:"cache_disk_max_percent,omitempty"` // Disk cache as percent of available space (1-100)
CacheDiskMaxCount int `json:"cache_disk_max_count,omitempty"` // Max number of items on disk
// Cache key configuration
CacheKeyHeaders []string `json:"cache_key_headers,omitempty"`
CacheKeyQueries []string `json:"cache_key_queries,omitempty"`
CacheKeyCookies []string `json:"cache_key_cookies,omitempty"`
// contains filtered or unexported fields
}
func (Sidekick) CaddyModule ¶
func (Sidekick) CaddyModule() caddy.ModuleInfo
type Storage ¶
type Storage struct {
// contains filtered or unexported fields
}
Storage manages both memory and disk cache storage
func NewStorage ¶
func NewStorage(loc string, ttl int, memItemMaxSize int, memMaxSize int, memMaxCount int, diskItemMaxSize int, diskMaxSize int, diskMaxCount int, logger *zap.Logger) *Storage
NewStorage creates a new Storage instance
func (*Storage) GetDiskCache ¶
func (*Storage) GetMemCache ¶
func (s *Storage) GetMemCache() *MemoryCache[string, *MemoryCacheItem]
func (*Storage) SetWithKey ¶
SetWithKey stores data with the provided key
func (*Storage) WaitForAsyncOps ¶
func (s *Storage) WaitForAsyncOps()
WaitForAsyncOps waits for all asynchronous operations to complete This is mainly useful for testing and graceful shutdown
type SyncHandler ¶
type SyncHandler struct {
// contains filtered or unexported fields
}
SyncHandler manages synchronization for cache operations