Documentation
¶
Overview ¶
Package store provides the underlying persistence and locking mechanisms for the http-keystone middleware suite.
Index ¶
- Variables
- type Counter
- type Entry
- type MemoryCounter
- func (m *MemoryCounter) Close() error
- func (m *MemoryCounter) Get(_ context.Context, key string) (int, error)
- func (m *MemoryCounter) Increment(ctx context.Context, key string, n int, ttl time.Duration) (int, error)
- func (m *MemoryCounter) Len() int
- func (m *MemoryCounter) Reset(_ context.Context, key string) error
- func (m *MemoryCounter) StartEvictor(ctx context.Context, interval time.Duration)
- type MemoryStore
- func (m *MemoryStore) Delete(_ context.Context, key string) error
- func (m *MemoryStore) Get(_ context.Context, key string) (*Entry, error)
- func (m *MemoryStore) Lock(_ context.Context, key string, ttl time.Duration) (bool, error)
- func (m *MemoryStore) Save(_ context.Context, key string, entry *Entry, ttl time.Duration) error
- func (m *MemoryStore) StartEvictor(interval time.Duration, stop <-chan struct{})
- func (m *MemoryStore) Unlock(_ context.Context, key string) error
- type RedisCounter
- func (c *RedisCounter) Close() error
- func (c *RedisCounter) Get(ctx context.Context, key string) (int, error)
- func (c *RedisCounter) Increment(ctx context.Context, key string, n int, ttl time.Duration) (int, error)
- func (c *RedisCounter) Ping(ctx context.Context) error
- func (c *RedisCounter) Reset(ctx context.Context, key string) error
- type RedisStore
- func (r *RedisStore) Close() error
- func (r *RedisStore) Delete(ctx context.Context, key string) error
- func (r *RedisStore) Get(ctx context.Context, key string) (*Entry, error)
- func (r *RedisStore) Lock(ctx context.Context, key string, ttl time.Duration) (bool, error)
- func (r *RedisStore) Ping(ctx context.Context) error
- func (r *RedisStore) Save(ctx context.Context, key string, entry *Entry, ttl time.Duration) error
- func (r *RedisStore) Unlock(ctx context.Context, key string) error
- type RedisStoreOptions
- type Store
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotFound is returned when a requested key does not exist in the store // or has already expired. Middleware should typically handle this by // proceeding to the next handler to fetch fresh data. ErrNotFound = errors.New("store: item not found") // ErrLockFailed is returned when a distributed lock cannot be acquired // within the allowed timeframe or because it is already held by another // process. This is primarily used by the idempotency middleware. ErrLockFailed = errors.New("store: could not acquire lock") )
var ErrCounterOverflow = errors.New("store: counter value overflows int")
ErrCounterOverflow is returned when a counter value cannot be represented as an int on the current platform.
Functions ¶
This section is empty.
Types ¶
type Counter ¶
type Counter interface {
// Get returns the current count for a key
Get(ctx context.Context, key string) (int, error)
// Increment adds n to the key and returns the new total.
// if the key doesn't exist, it's created with value 'n' and the given TTL.
Increment(ctx context.Context, key string, n int, ttl time.Duration) (int, error)
// Reset clears the counter
Reset(ctx context.Context, key string) error
}
Counter defines a simpler interface for numeric tracking (Abuse, Rate Limiting)
type Entry ¶
type Entry struct {
Status int `json:"status"`
Header map[string][]string `json:"header"`
Body []byte `json:"body"`
}
Entry represents the data that actually persists
type MemoryCounter ¶ added in v0.2.0
type MemoryCounter struct {
// contains filtered or unexported fields
}
MemoryCounter is a thread-safe in-memory Counter. Entries are stored with an expiry and are removed lazily on access, by an optional background evictor (see StartEvictor), or when MaxEntries is exceeded.
func NewMemoryCounter ¶
func NewMemoryCounter() *MemoryCounter
NewMemoryCounter returns a new thread-safe memory-based Counter.
func NewMemoryCounterWithLimit ¶ added in v0.2.0
func NewMemoryCounterWithLimit(maxEntries int) *MemoryCounter
NewMemoryCounterWithLimit returns a MemoryCounter that keeps at most maxEntries keys. When the limit is reached, the key that expires first is evicted to make room for the new one. A maxEntries value <= 0 means unlimited.
func (*MemoryCounter) Close ¶ added in v0.2.0
func (m *MemoryCounter) Close() error
Close stops a background evictor started by StartEvictor. It is safe to call multiple times and does not invalidate the counter.
func (*MemoryCounter) Get ¶ added in v0.2.0
Get returns the current count for key. An expired key is deleted and 0 is returned.
func (*MemoryCounter) Len ¶ added in v0.2.0
func (m *MemoryCounter) Len() int
Len returns the number of tracked keys, excluding expired ones.
func (*MemoryCounter) Reset ¶ added in v0.2.0
func (m *MemoryCounter) Reset(_ context.Context, key string) error
func (*MemoryCounter) StartEvictor ¶ added in v0.2.0
func (m *MemoryCounter) StartEvictor(ctx context.Context, interval time.Duration)
StartEvictor launches a background goroutine that removes expired keys every interval, stopping when ctx is done or Close is called. It is safe to call more than once; later calls replace the previous evictor.
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore is an in-memory implementation of the Store interface. It utilizes sync.Map for thread-safe data operations and distributed-style locking simulations, making it ideal for single-instance applications.
func NewMemoryStore ¶
func NewMemoryStore() *MemoryStore
NewMemoryStore initializes and returns a new pointer to a MemoryStore.
func (*MemoryStore) Delete ¶
func (m *MemoryStore) Delete(_ context.Context, key string) error
Delete removes a specific entry from the memory store immediately.
func (*MemoryStore) Get ¶
Get retrieves a cached Entry by its key. If the entry exists but has expired, it is deleted and ErrNotFound is returned.
func (*MemoryStore) Lock ¶
Lock attempts to acquire a non-blocking lock for a given key. It returns true if the lock was successfully acquired or if a previous lock has already expired. This is essential for preventing "thundering herd" issues in idempotency middleware.
func (*MemoryStore) StartEvictor ¶
func (m *MemoryStore) StartEvictor(interval time.Duration, stop <-chan struct{})
StartEvictor launches a background goroutine that periodically scans the store and removes expired entries. The goroutine stops when the provided stop channel is closed.
type RedisCounter ¶
type RedisCounter struct {
// contains filtered or unexported fields
}
RedisCounter implements Counter using Redis. It is suitable for distributed deployments where multiple application instances must share abuse scores, rate limits, or any other numeric counter.
Increment is atomic: the INCRBY and the optional expiry update run in a single Lua script, so concurrent increments cannot lose updates or leave a key without its TTL.
func NewRedisCounter ¶
func NewRedisCounter(addr string) *RedisCounter
NewRedisCounter creates a Redis-backed Counter using addr (for example "localhost:6379"). This is the convenience constructor for simple setups.
func NewRedisCounterWithClient ¶
func NewRedisCounterWithClient(client *redis.Client) *RedisCounter
NewRedisCounterWithClient creates a RedisCounter that reuses an existing go-redis client. The caller retains ownership of the client: Close is a no-op for counters created this way, and the caller must close the client when the application shuts down.
func NewRedisCounterWithOptions ¶
func NewRedisCounterWithOptions(opts RedisStoreOptions) *RedisCounter
NewRedisCounterWithOptions creates a RedisCounter with custom connection settings. It accepts the same options type as RedisStore so cache and abuse tracking can be pointed at the same Redis instance.
func (*RedisCounter) Close ¶
func (c *RedisCounter) Close() error
Close closes the underlying client when the counter owns it. It is a no-op for counters created with NewRedisCounterWithClient.
func (*RedisCounter) Get ¶
Get returns the current value for key. A missing or expired key returns 0 with a nil error, matching the in-memory Counter implementation.
func (*RedisCounter) Increment ¶
func (c *RedisCounter) Increment(ctx context.Context, key string, n int, ttl time.Duration) (int, error)
Increment atomically adds n to key and returns the new total. When ttl is positive, it becomes the key's expiry; every increment refreshes it, which gives abuse tracking a sliding cooldown window.
type RedisStore ¶
type RedisStore struct {
// contains filtered or unexported fields
}
RedisStore implements the Store interface using Redis as the backend. It is suitable for distributed production environments where multiple application instances need to share a consistent cache.
func NewRedisStore ¶
func NewRedisStore(addr string) *RedisStore
NewRedisStore creates a new RedisStore with the provided address. This is a convenience constructor for simple setups.
func NewRedisStoreWithOptions ¶
func NewRedisStoreWithOptions(opts RedisStoreOptions) *RedisStore
NewRedisStoreWithOptions creates a new RedisStore with custom configuration.
func (*RedisStore) Close ¶
func (r *RedisStore) Close() error
Close closes the Redis connection pool. It is important to call this when shutting down the application.
func (*RedisStore) Delete ¶
func (r *RedisStore) Delete(ctx context.Context, key string) error
Delete removes a specific entry from Redis immediately.
func (*RedisStore) Get ¶
Get retrieves a cached Entry by its key from Redis. Returns ErrNotFound if the key does not exist or has expired.
func (*RedisStore) Lock ¶
Lock attempts to acquire a distributed lock for a given key using SET NX. This is atomic and prevents race conditions in distributed environments. Returns true if the lock was successfully acquired.
func (*RedisStore) Ping ¶
func (r *RedisStore) Ping(ctx context.Context) error
Ping verifies that the Redis server is reachable. It is useful for readiness checks and for failing fast when the configured address is wrong.
type RedisStoreOptions ¶
type RedisStoreOptions struct {
// Addr is the Redis server address (e.g., "localhost:6379")
Addr string
// PoolSize is the maximum number of socket connections.
// Default is 10 connections per CPU.
PoolSize int
// MinIdleConns is the minimum number of idle connections.
// Default is 0.
MinIdleConns int
// Password for authentication. Empty string means no password.
Password string
// DB is the Redis database to use. Default is 0.
DB int
}
RedisStoreOptions provides configuration options for RedisStore.
type Store ¶
type Store interface {
// Get retrieves an entry by key
Get(ctx context.Context, key string) (*Entry, error)
// Save stores an entry with a specific TTL
Save(ctx context.Context, key string, entry *Entry, ttl time.Duration) error
// Delete removes an entry
Delete(ctx context.Context, key string) error
// Lock attempts to acquire a distributed lock for a key (crucial for Idempotency)
Lock(ctx context.Context, key string, ttl time.Duration) (bool, error)
// Unlock releases the lock
Unlock(ctx context.Context, key string) error
}
Store defines the contract for any backend (Memory, Redis, etc.)