store

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 7 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package store provides the underlying persistence and locking mechanisms for the http-keystone middleware suite.

Index

Constants

This section is empty.

Variables

View Source
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")
)
View Source
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)

func NewMemoryCounter

func NewMemoryCounter() Counter

NewMemoryCounter returns a new thread-safe memory-based Counter.

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 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

func (m *MemoryStore) Get(_ context.Context, key string) (*Entry, error)

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

func (m *MemoryStore) Lock(_ context.Context, key string, ttl time.Duration) (bool, error)

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) Save

func (m *MemoryStore) Save(_ context.Context, key string, entry *Entry, ttl time.Duration) error

Save persists an Entry into memory with a specific time-to-live (TTL).

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, key string) error

Unlock releases the lock for the given key, allowing other processes to acquire it.

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

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

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.

func (*RedisCounter) Ping

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

Ping verifies that the Redis server is reachable.

func (*RedisCounter) Reset

func (c *RedisCounter) Reset(ctx context.Context, key string) error

Reset removes key immediately.

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

func (r *RedisStore) Get(ctx context.Context, key string) (*Entry, error)

Get retrieves a cached Entry by its key from Redis. Returns ErrNotFound if the key does not exist or has expired.

func (*RedisStore) Lock

func (r *RedisStore) Lock(ctx context.Context, key string, ttl time.Duration) (bool, error)

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.

func (*RedisStore) Save

func (r *RedisStore) Save(ctx context.Context, key string, entry *Entry, ttl time.Duration) error

Save persists an Entry into Redis with a specific time-to-live (TTL).

func (*RedisStore) Unlock

func (r *RedisStore) Unlock(ctx context.Context, key string) error

Unlock releases the lock for the given key.

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.)

Jump to

Keyboard shortcuts

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