cache

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2025 License: ISC Imports: 10 Imported by: 4

README

Cache Library Documentation

GitHub Tag Go Reference License Go Report Card Contributors Issues

This library provides a flexible and extensible caching system with support for in-memory and Redis-based caching. It includes utilities for managing rate limiters, queues, and verification codes.

Cache

The Cache interface provides a unified API for caching operations:

  • Put(key string, value any, ttl *time.Duration) error: Store a value with an optional TTL.
  • Update(key string, value any) (bool, error): Update an existing key.
  • PutOrUpdate(key string, value any, ttl *time.Duration) error: Store or update a value.
  • Get(key string) (any, error): Retrieve a value.
  • Pull(key string) (any, error): Retrieve and remove a value.
  • Cast(key string) (cast.Caster, error): Retrieve and cast a value.
  • Exists(key string) (bool, error): Check if a key exists.
  • Forget(key string) error: Remove a key.
  • TTL(key string) (time.Duration, error): Get the TTL of a key.
  • Increment(key string, value int64) (bool, error): Increment a numeric value.
  • Decrement(key string, value int64) (bool, error): Decrement a numeric value.
  • IncrementFloat(key string, value float64) (bool, error): Increment a float value.
  • DecrementFloat(key string, value float64) (bool, error): Decrement a float value.

Memory Cache

The MemoryCache is an in-memory implementation of the Cache interface:

cache := cache.NewMemoryCache()
ttl := 5 * time.Second
err := cache.Put("key", "value", &ttl)
value, err := cache.Get("key")

Redis Cache

The RedisCache is a Redis-based implementation of the Cache interface:

redisClient := redis.NewClient(&redis.Options{})
cache := cache.NewRedisCache("prefix", redisClient)
ttl := 5 * time.Second
err := cache.Put("key", "value", &ttl)
value, err := cache.Get("key")

Queue

The Queue provides methods for managing a queue:

  • Push(value any) error: Add a value.
  • Pull() (any, error): Retrieve and remove the first item.
  • Pop() (any, error): Retrieve and remove the last item.
  • Cast() (cast.Caster, error): Retrieve and cast the first item.
  • Length() (int64, error): Get the number of items.
  • Clear() error: Remove all items.

Rate Limiter

The RateLimiter manages rate limits:

  • Hit() error: Decrement remaining attempts.
  • Lock() error: Lock the rate limiter.
  • Reset() error: Reset the rate limiter.
  • Clear() error: Remove the rate limiter.
  • MustLock() (bool, error): Check if locking is required.
  • TotalAttempts() (uint32, error): Get total attempts.
  • RetriesLeft() (uint32, error): Get remaining attempts.
  • AvailableIn() (time.Duration, error): Time until unlock.

Verification Code

The VerificationCode manages verification codes:

  • Set(code string) error: Store a code.
  • Generate(count uint) (string, error): Generate a random code.
  • Clear() error: Clear the code.
  • Get() (string, error): Retrieve the code.
  • Validate(code string) (bool, error): Validate a code.
  • Exists() (bool, error): Check if a code exists.
  • TTL() (time.Duration, error): Get the TTL of the code.

License

This project is licensed under the ISC License. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache interface {
	// Put stores a value in the cache with the specified key and optional TTL (time-to-live).
	// If ttl is nil, the value is stored indefinitely.
	// Returns an error if the operation fails.
	Put(key string, value any, ttl *time.Duration) error

	// Update updates the value of an existing key in the cache.
	// Returns true if the key exists, and an error if the operation fails.
	Update(key string, value any) (bool, error)

	// PutOrUpdate stores a value in the cache with the specified key and TTL.
	// If the key exists, the existing TTL is preserved.
	// If ttl is nil, the value is stored indefinitely.
	// Returns an error if the operation fails.
	PutOrUpdate(key string, value any, ttl *time.Duration) error

	// Get retrieves the value associated with the specified key from the cache.
	// Returns the value and an error if the operation fails.
	Get(key string) (any, error)

	// Pull retrieves the value associated with the specified key and removes it from the cache.
	// Returns the value and an error if the operation fails.
	Pull(key string) (any, error)

	// Cast retrieves the value associated with the specified key and casts it to a cast.Caster.
	// Returns the casted value and an error if the operation fails.
	Cast(key string) (cast.Caster, error)

	// Exists checks whether a key exists in the cache.
	// Returns true if the key exists, and an error if the operation fails.
	Exists(key string) (bool, error)

	// Forget removes the value associated with the specified key from the cache.
	// Returns an error if the operation fails.
	Forget(key string) error

	// TTL retrieves the time-to-live (TTL) of the value associated with the specified key.
	// Returns the TTL and an error if the operation fails.
	TTL(key string) (time.Duration, error)

	// Increment increases the integer value of the specified key by the given amount.
	// Returns true if the key exists, and an error if the operation fails.
	Increment(key string, value int64) (bool, error)

	// Decrement decreases the integer value of the specified key by the given amount.
	// Returns true if the key exists, and an error if the operation fails.
	Decrement(key string, value int64) (bool, error)

	// IncrementFloat increases the float value of the specified key by the given amount.
	// Returns true if the key exists, and an error if the operation fails.
	IncrementFloat(key string, value float64) (bool, error)

	// DecrementFloat decreases the float value of the specified key by the given amount.
	// Returns true if the key exists, and an error if the operation fails.
	DecrementFloat(key string, value float64) (bool, error)
}

Cache provides a nil-safe interface for caching operations.

func NewMemoryCache

func NewMemoryCache() Cache

NewMemoryCache creates and returns a new in-memory cache instance.

func NewRedisCache

func NewRedisCache(prefix string, client *redis.Client) Cache

NewRedisCache creates a new Redis cache instance with a given prefix and Redis client.

type Queue

type Queue interface {
	// Push adds a value to the end of the queue.
	// Returns an error if the operation fails.
	Push(value any) error

	// Pull retrieves and removes the first item from the queue.
	// Returns the value and an error if the operation fails.
	Pull() (any, error)

	// Pop retrieves and removes the last item from the queue.
	// Returns the value and an error if the operation fails.
	Pop() (any, error)

	// Cast retrieves and removes the first item from the queue,
	// casting it to a `cast.Caster` type.
	// Returns the `Caster` instance and an error if the operation fails.
	Cast() (cast.Caster, error)

	// Length returns the current number of items in the queue.
	// Returns the queue length and an error if the operation fails.
	Length() (int64, error)

	// Clear removes all items from the queue.
	Clear() error
}

Queue represents a thread-safe, nil-safe queue interface. It provides methods to perform common queue operations.

func NewRedisQueue

func NewRedisQueue(name string, client *redis.Client) Queue

NewRedisQueue creates a new Redis queue instance.

type RateLimiter

type RateLimiter interface {
	// Hit decrements the user's remaining attempts.
	// Returns an error if the operation fails.
	Hit() error

	// Lock locks the rate limiter, preventing further attempts.
	// Returns an error if the operation fails.
	Lock() error

	// Reset resets the rate limiter to its initial state.
	// Returns an error if the operation fails.
	Reset() error

	// Clear removes the rate limiter from the cache.
	// Returns an error if the operation fails.
	Clear() error

	// MustLock checks if the rate limiter should be locked.
	// Returns a boolean indicating the lock state and an error if the operation fails.
	MustLock() (bool, error)

	// TotalAttempts returns the total number of attempts made by the user.
	// Returns the total attempts and an error if the operation fails.
	TotalAttempts() (uint32, error)

	// RetriesLeft returns the number of remaining attempts for the user.
	// Returns the remaining attempts and an error if the operation fails.
	RetriesLeft() (uint32, error)

	// AvailableIn returns the time duration until the rate limiter unlocks.
	// Returns the time until unlock and an error if the operation fails.
	AvailableIn() (time.Duration, error)
}

RateLimiter defines the interface for a rate limiter.

func NewRateLimiter

func NewRateLimiter(name string, maxAttempts uint32, ttl time.Duration, cache Cache) RateLimiter

NewRateLimiter creates and returns a new rate limiter instance.

type VerificationCode

type VerificationCode interface {
	// Set stores the verification code in the cache.
	Set(code string) error

	// Generate creates a random numeric code of the specified length and stores it in the cache.
	Generate(count uint) (string, error)

	// Clear removes the verification code from the cache.
	Clear() error

	// Get retrieves the verification code from the cache.
	Get() (string, error)

	// Validate checks if the provided code matches the stored verification code.
	Validate(code string) (bool, error)

	// Exists checks if the verification code exists in the cache.
	Exists() (bool, error)

	// TTL retrieves the time-to-live (TTL) of the verification code in the cache.
	TTL() (time.Duration, error)
}

VerificationCode defines the interface for managing verification codes in a cache.

func NewVerification

func NewVerification(name string, maxAttempts uint32, ttl time.Duration, cache Cache) VerificationCode

NewVerification creates a new instance of the verification code.

Jump to

Keyboard shortcuts

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