Documentation
¶
Overview ¶
Package store provides the underlying persistence and locking mechanisms for the http-keystone middleware suite.
Index ¶
- Variables
- type Counter
- type Entry
- type Lease
- 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) (*Lease, error)
- func (m *MemoryStore) Refresh(_ context.Context, lease *Lease, ttl time.Duration) 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, lease *Lease) 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) (*Lease, error)
- func (r *RedisStore) Ping(ctx context.Context) error
- func (r *RedisStore) Refresh(ctx context.Context, lease *Lease, ttl time.Duration) error
- func (r *RedisStore) Save(ctx context.Context, key string, entry *Entry, ttl time.Duration) error
- func (r *RedisStore) Unlock(ctx context.Context, lease *Lease) 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 lock cannot be acquired because another // owner currently holds it. Callers should treat it as "someone else is // already doing this work" (for example, wait for the result or fail open). ErrLockFailed = errors.New("store: could not acquire lock") // ErrLockNotHeld is returned when a lease is refreshed or operated on but // is no longer the owner: it expired and may have been re-acquired by a // different caller. Unlock treats this as a no-op, but Refresh reports it // so a holder can react (stop work, retry) instead of assuming it still // owns the lock. ErrLockNotHeld = errors.New("store: lock is not held") )
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 Lease ¶ added in v0.2.1
type Lease struct {
// Key is the logical key the lock was acquired for.
Key string
// Token identifies the owner of the lock.
Token string
}
Lease is an owned lock handed back by Store.Lock. The Token is an unguessable identifier for the owner; Unlock and Refresh compare it so a caller can never release or extend a lock that now belongs to someone else after its TTL expired and it was re-acquired.
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 an owned, non-blocking lock for a given key. It returns a Lease identifying the owner, or ErrLockFailed if another caller holds a live lock. An expired lock may be taken over atomically: the check and the overwrite happen under one mutex, so two goroutines can never both observe the same expired lock and both succeed.
func (*MemoryStore) Refresh ¶ added in v0.2.1
Refresh extends the TTL of the lock identified by lease. It returns ErrLockNotHeld when the lease is no longer the owner.
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.
func (*MemoryStore) Unlock ¶
func (m *MemoryStore) Unlock(_ context.Context, lease *Lease) error
Unlock releases the lock identified by lease. It only deletes the entry when the stored token matches the lease, so a caller whose lock already expired and was re-acquired cannot release the new owner's lock.
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 an owned lock for key using SET NX with a unique token, so the lock is atomic and carries its owner. It returns ErrLockFailed when another owner holds a live lock.
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.
func (*RedisStore) Refresh ¶ added in v0.2.1
Refresh extends the TTL of the lock identified by lease. It returns ErrLockNotHeld when the lease is no longer the owner.
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 an owned lock for key that expires after ttl.
// On success it returns a Lease identifying the owner. It returns
// ErrLockFailed when another owner holds a live lock for the key. A
// non-positive ttl creates a lock that does not expire on its own.
Lock(ctx context.Context, key string, ttl time.Duration) (*Lease, error)
// Unlock releases the lock identified by lease. Unlocking with a lease
// that is no longer the owner (it expired and was re-acquired) is a no-op
// and never releases the current owner's lock.
Unlock(ctx context.Context, lease *Lease) error
// Refresh extends the TTL of the lock identified by lease. It returns
// ErrLockNotHeld when the lease is no longer the owner. A non-positive ttl
// makes the lock stop expiring on its own.
Refresh(ctx context.Context, lease *Lease, ttl time.Duration) error
}
Store defines the contract for any backend (Memory, Redis, etc.)