cache

package
v0.0.0-20260608 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetOrLock

func GetOrLock(store Store, key string, ttl time.Duration, callback func() (any, error)) (any, error)

GetOrLock tries to get a cached value, or acquires a lock and executes the callback if the value doesn't exist. This prevents cache stampede.

func Many

func Many(store Store, keys []string) map[string]any

Many retrieves multiple cache values by their keys.

func PutMany

func PutMany(store Store, values map[string]any, ttl time.Duration) error

PutMany stores multiple key-value pairs in the cache with the same TTL.

func PutManyForever

func PutManyForever(store Store, values map[string]any) error

PutManyForever stores multiple key-value pairs permanently.

func Remember

func Remember(store Store, key string, ttl time.Duration, callback func() (any, error)) (any, error)

Remember retrieves an item from the cache and executes the closure if the key doesn't exist, storing the closure's result. This is Laravel's cache()->remember() pattern.

func RememberForever

func RememberForever(store Store, key string, callback func() (any, error)) (any, error)

RememberForever retrieves an item from the cache and executes the closure if the key doesn't exist, storing the result permanently.

Types

type AtomicCounter

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

AtomicCounter provides atomic increment/decrement operations.

func NewAtomicCounter

func NewAtomicCounter(store Store) *AtomicCounter

NewAtomicCounter creates a new atomic counter.

func (*AtomicCounter) Decrement

func (ac *AtomicCounter) Decrement(key string, amount int) (int, error)

Decrement atomically decrements a key by the given amount.

func (*AtomicCounter) Get

func (ac *AtomicCounter) Get(key string) (int, error)

Get returns the current value of the counter.

func (*AtomicCounter) Increment

func (ac *AtomicCounter) Increment(key string, amount int) (int, error)

Increment atomically increments a key by the given amount.

func (*AtomicCounter) Reset

func (ac *AtomicCounter) Reset(key string) error

Reset resets the counter to zero.

func (*AtomicCounter) Set

func (ac *AtomicCounter) Set(key string, value int) error

Set sets the counter to a specific value.

type CacheEvent

type CacheEvent struct {
	Type EventType
	Key  string
}

CacheEvent represents a cache event.

type CacheListener

type CacheListener func(CacheEvent)

CacheListener is a function that handles cache events.

type CacheStats

type CacheStats struct {
	Hits      int64
	Misses    int64
	Sets      int64
	Deletes   int64
	Flushes   int64
	Evictions int64
	// contains filtered or unexported fields
}

CacheStats provides statistics about cache usage.

func NewCacheStats

func NewCacheStats() *CacheStats

NewCacheStats creates a new CacheStats instance.

func (*CacheStats) HitRate

func (s *CacheStats) HitRate() float64

HitRate returns the cache hit rate as a percentage.

func (*CacheStats) RecordDelete

func (s *CacheStats) RecordDelete()

RecordDelete records a cache delete operation.

func (*CacheStats) RecordFlush

func (s *CacheStats) RecordFlush()

RecordFlush records a cache flush operation.

func (*CacheStats) RecordHit

func (s *CacheStats) RecordHit()

RecordHit records a cache hit.

func (*CacheStats) RecordMiss

func (s *CacheStats) RecordMiss()

RecordMiss records a cache miss.

func (*CacheStats) RecordSet

func (s *CacheStats) RecordSet()

RecordSet records a cache set operation.

func (*CacheStats) Reset

func (s *CacheStats) Reset()

Reset resets all statistics.

func (*CacheStats) Snapshot

func (s *CacheStats) Snapshot() CacheStats

Snapshot returns a copy of the current stats.

type DistributedLock

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

DistributedLock provides distributed locking using the cache store.

func NewDistributedLock

func NewDistributedLock(store Store, key string, ttl time.Duration) *DistributedLock

NewDistributedLock creates a new distributed lock.

func (*DistributedLock) Acquire

func (dl *DistributedLock) Acquire() bool

Acquire attempts to acquire the lock.

func (*DistributedLock) AcquireBlocking

func (dl *DistributedLock) AcquireBlocking(timeout time.Duration) bool

AcquireBlocking attempts to acquire the lock with retry.

func (*DistributedLock) ForceRelease

func (dl *DistributedLock) ForceRelease()

ForceRelease releases the lock regardless of ownership.

func (*DistributedLock) GetRemainingTTL

func (dl *DistributedLock) GetRemainingTTL() time.Duration

GetRemainingTTL returns the remaining TTL of the lock (approximate).

func (*DistributedLock) IsHeld

func (dl *DistributedLock) IsHeld() bool

IsHeld checks if the lock is currently held.

func (*DistributedLock) Release

func (dl *DistributedLock) Release() bool

Release releases the lock if owned by this instance.

type EventDispatcher

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

EventDispatcher dispatches cache events.

func NewEventDispatcher

func NewEventDispatcher() *EventDispatcher

NewEventDispatcher creates a new cache event dispatcher.

func (*EventDispatcher) Dispatch

func (d *EventDispatcher) Dispatch(event CacheEvent)

Dispatch sends a cache event to all listeners.

func (*EventDispatcher) Listen

func (d *EventDispatcher) Listen(listener CacheListener)

Listen registers a listener for cache events.

type EventType

type EventType string

EventType represents the type of cache event.

const (
	EventHit    EventType = "hit"
	EventMiss   EventType = "miss"
	EventWrite  EventType = "write"
	EventDelete EventType = "delete"
	EventFlush  EventType = "flush"
)

type FileDriver

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

FileDriver implements cache using the local filesystem.

func NewFileDriver

func NewFileDriver(directory string) *FileDriver

NewFileDriver creates a new file cache driver.

func (*FileDriver) Decrement

func (d *FileDriver) Decrement(key string, amount int) (int, error)

Decrement decrements an integer value in the cache.

func (*FileDriver) Flush

func (d *FileDriver) Flush() error

Flush removes all cache entries.

func (*FileDriver) Forever

func (d *FileDriver) Forever(key string, value any) error

Forever stores a value with no expiration.

func (*FileDriver) Forget

func (d *FileDriver) Forget(key string) error

Forget removes a cache entry.

func (*FileDriver) Get

func (d *FileDriver) Get(key string) (any, error)

Get retrieves a cache value by key.

func (*FileDriver) Has

func (d *FileDriver) Has(key string) bool

Has checks if a cache entry exists and is not expired.

func (*FileDriver) Increment

func (d *FileDriver) Increment(key string, amount int) (int, error)

Increment increments an integer value in the cache.

func (*FileDriver) Put

func (d *FileDriver) Put(key string, value any, ttl time.Duration) error

Put stores a value in the cache with an expiration duration.

type InMemoryTagStore

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

InMemoryTagStore is an in-memory implementation of TagStore.

func NewInMemoryTagStore

func NewInMemoryTagStore() *InMemoryTagStore

NewInMemoryTagStore creates a new in-memory tag store.

func (*InMemoryTagStore) AddKeyToTag

func (s *InMemoryTagStore) AddKeyToTag(tag, key string)

func (*InMemoryTagStore) FlushTag

func (s *InMemoryTagStore) FlushTag(tag string)

func (*InMemoryTagStore) GetKeysForTag

func (s *InMemoryTagStore) GetKeysForTag(tag string) []string

func (*InMemoryTagStore) GetTagsForKey

func (s *InMemoryTagStore) GetTagsForKey(key string) []string

func (*InMemoryTagStore) RemoveKeyFromTag

func (s *InMemoryTagStore) RemoveKeyFromTag(tag, key string)

func (*InMemoryTagStore) SetTagsForKey

func (s *InMemoryTagStore) SetTagsForKey(key string, tags []string)

type Lock

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

Lock represents a distributed lock backed by the cache.

func AcquireLock

func AcquireLock(store Store, name string, ttl time.Duration) *Lock

AcquireLock attempts to acquire a named lock with the given TTL. Returns the Lock object. Call lock.Get() to try acquiring, lock.Release() to free.

func NewLock

func NewLock(store Store, name string, ttl time.Duration) *Lock

NewLock creates a new lock instance.

func (*Lock) Block

func (l *Lock) Block(timeout time.Duration) bool

Block is a convenience method that tries to acquire the lock, blocking until successful or timeout. Alias for GetBlocking.

func (*Lock) ForceGet

func (l *Lock) ForceGet() bool

ForceGet acquires the lock without checking existing locks (force).

func (*Lock) Get

func (l *Lock) Get() bool

Get attempts to acquire the lock. Returns true if successful.

func (*Lock) GetBlocking

func (l *Lock) GetBlocking(timeout time.Duration) bool

GetBlocking attempts to acquire the lock, retrying until timeout.

func (*Lock) GetRemaining

func (l *Lock) GetRemaining() time.Duration

GetRemaining returns the remaining time-to-live for the lock.

func (*Lock) IsHeld

func (l *Lock) IsHeld() bool

IsHeld checks if the lock is currently held.

func (*Lock) Release

func (l *Lock) Release() bool

Release releases the lock only if the current owner holds it.

type MemoryDriver

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

MemoryDriver implements the cache Store in memory.

func NewMemoryDriver

func NewMemoryDriver() *MemoryDriver

NewMemoryDriver creates a new in-memory cache driver.

func (*MemoryDriver) Decrement

func (d *MemoryDriver) Decrement(key string, value int) (int, error)

func (*MemoryDriver) Flush

func (d *MemoryDriver) Flush() error

func (*MemoryDriver) Forever

func (d *MemoryDriver) Forever(key string, value any) error

func (*MemoryDriver) Forget

func (d *MemoryDriver) Forget(key string) error

func (*MemoryDriver) Get

func (d *MemoryDriver) Get(key string) (any, error)

func (*MemoryDriver) Has

func (d *MemoryDriver) Has(key string) bool

func (*MemoryDriver) Increment

func (d *MemoryDriver) Increment(key string, value int) (int, error)

func (*MemoryDriver) Put

func (d *MemoryDriver) Put(key string, value any, ttl time.Duration) error

type RateLimiter

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

RateLimiter provides rate limiting functionality using the Cache Store.

func NewRateLimiter

func NewRateLimiter(cache Store) *RateLimiter

NewRateLimiter creates a new RateLimiter instance.

func (*RateLimiter) Attempts

func (rl *RateLimiter) Attempts(key string) (int, error)

Attempts gets the number of attempts for the given key.

func (*RateLimiter) Hit

func (rl *RateLimiter) Hit(key string, decaySeconds int) (int, error)

Hit increments the number of attempts for a given key.

func (*RateLimiter) Reset

func (rl *RateLimiter) Reset(key string) error

Reset resets the attempts for the given key.

func (*RateLimiter) TooManyAttempts

func (rl *RateLimiter) TooManyAttempts(key string, maxAttempts int) bool

TooManyAttempts determines if the given key has exceeded the max attempts.

type RedisStore

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

RedisStore is a cache driver backed by Redis.

func NewRedisStore

func NewRedisStore(client *redis.Client, prefix string) *RedisStore

NewRedisStore creates a new Redis-backed cache store.

func (*RedisStore) Decrement

func (s *RedisStore) Decrement(key string, value int) (int, error)

Decrement decrements an integer value in the cache.

func (*RedisStore) Flush

func (s *RedisStore) Flush() error

Flush clears the entire cache (current database).

func (*RedisStore) Forever

func (s *RedisStore) Forever(key string, value any) error

Forever stores a value by key indefinitely.

func (*RedisStore) Forget

func (s *RedisStore) Forget(key string) error

Forget removes a specific key from the cache.

func (*RedisStore) Get

func (s *RedisStore) Get(key string) (any, error)

Get retrieves a value by key.

func (*RedisStore) Has

func (s *RedisStore) Has(key string) bool

Has checks if a key exists in the cache.

func (*RedisStore) Increment

func (s *RedisStore) Increment(key string, value int) (int, error)

Increment increments an integer value in the cache.

func (*RedisStore) Put

func (s *RedisStore) Put(key string, value any, ttl time.Duration) error

Put stores a value by key with an expiration time.

type SlidingWindowRateLimiter

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

SlidingWindowRateLimiter uses a sliding window algorithm for rate limiting.

func NewSlidingWindowRateLimiter

func NewSlidingWindowRateLimiter(store Store, window time.Duration, limit int) *SlidingWindowRateLimiter

NewSlidingWindowRateLimiter creates a new sliding window rate limiter.

func (*SlidingWindowRateLimiter) Allow

func (sw *SlidingWindowRateLimiter) Allow(key string) bool

Allow checks if a request is allowed under the rate limit.

func (*SlidingWindowRateLimiter) Remaining

func (sw *SlidingWindowRateLimiter) Remaining(key string) int

Remaining returns the number of remaining requests in the window.

func (*SlidingWindowRateLimiter) Reset

func (sw *SlidingWindowRateLimiter) Reset(key string)

Reset resets the rate limiter for a key.

type Store

type Store interface {
	Get(key string) (any, error)
	Put(key string, value any, ttl time.Duration) error
	Increment(key string, value int) (int, error)
	Decrement(key string, value int) (int, error)
	Forever(key string, value any) error
	Forget(key string) error
	Has(key string) bool
	Flush() error
}

Store is the interface for cache drivers.

type TagStore

type TagStore interface {
	GetTagsForKey(key string) []string
	SetTagsForKey(key string, tags []string)
	GetKeysForTag(tag string) []string
	AddKeyToTag(tag, key string)
	RemoveKeyFromTag(tag, key string)
	FlushTag(tag string)
}

TagStore extends TaggedCache with additional operations.

type TaggedCache

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

TaggedCache provides cache tag-based invalidation.

func Tag

func Tag(store Store, tags ...string) *TaggedCache

Tag creates a tagged cache instance.

func (*TaggedCache) Decrement

func (tc *TaggedCache) Decrement(key string, amount int) (int, error)

Decrement decrements a counter with tag prefix.

func (*TaggedCache) Flush

func (tc *TaggedCache) Flush() error

Flush removes all keys with any of the tags.

func (*TaggedCache) Forever

func (tc *TaggedCache) Forever(key string, value any) error

Forever stores a value permanently with tag prefix.

func (*TaggedCache) Forget

func (tc *TaggedCache) Forget(key string) error

Forget removes a specific key with tag prefix.

func (*TaggedCache) Get

func (tc *TaggedCache) Get(key string) (any, error)

Get retrieves a value by key with tag prefix.

func (*TaggedCache) Has

func (tc *TaggedCache) Has(key string) bool

Has checks if a key exists with tag prefix.

func (*TaggedCache) Increment

func (tc *TaggedCache) Increment(key string, amount int) (int, error)

Increment increments a counter with tag prefix.

func (*TaggedCache) Put

func (tc *TaggedCache) Put(key string, value any, duration time.Duration) error

Put stores a value with tag prefix.

type TokenBucketRateLimiter

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

TokenBucketRateLimiter uses a token bucket algorithm for rate limiting.

func NewTokenBucketRateLimiter

func NewTokenBucketRateLimiter(rate, capacity int) *TokenBucketRateLimiter

NewTokenBucketRateLimiter creates a new token bucket rate limiter.

func (*TokenBucketRateLimiter) Allow

func (tb *TokenBucketRateLimiter) Allow(key string) bool

Allow checks if a request is allowed.

func (*TokenBucketRateLimiter) Remaining

func (tb *TokenBucketRateLimiter) Remaining(key string) int

Remaining returns the number of remaining tokens.

func (*TokenBucketRateLimiter) Reset

func (tb *TokenBucketRateLimiter) Reset(key string)

Reset resets the token bucket for a key.

func (*TokenBucketRateLimiter) Wait

func (tb *TokenBucketRateLimiter) Wait(key string, timeout time.Duration) bool

Wait blocks until a token is available or timeout.

Jump to

Keyboard shortcuts

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