cache

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package cache provides user data caching functionality. Supports both in-memory cache and Redis cache implementations, as well as Redis-based distributed locks.

Package cache provides user data caching functionality. Supports both in-memory cache and Redis cache implementations, as well as Redis-based distributed locks.

Package cache provides user data caching functionality. Supports both in-memory cache and Redis cache implementations, as well as Redis-based distributed locks.

Package cache provides user data caching functionality. Supports both in-memory cache and Redis cache implementations, as well as Redis-based distributed locks.

Index

Constants

View Source
const (
	// REDIS_CACHE_KEY Redis key for storing user data
	REDIS_CACHE_KEY = "warden:users:cache"
	// REDIS_CACHE_VERSION_KEY Redis key for storing cache version
	REDIS_CACHE_VERSION_KEY = "warden:users:cache:version"
	// REDIS_CACHE_TTL Redis cache expiration time (1 hour)
	REDIS_CACHE_TTL = 1 * time.Hour
	// REDIS_OPERATION_TIMEOUT Redis operation timeout
	REDIS_OPERATION_TIMEOUT = 5 * time.Second
)
View Source
const (
	// LOCK_OPERATION_TIMEOUT lock operation timeout
	//nolint:revive // Constants use ALL_CAPS which conforms to project standards
	LOCK_OPERATION_TIMEOUT = 5 * time.Second
)

Variables

This section is empty.

Functions

This section is empty.

Types

type LocalLocker

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

LocalLocker provides local lock functionality, compatible with gocron.Locker interface Suitable for single-machine deployment scenarios, does not support distributed environments

func NewLocalLocker

func NewLocalLocker() *LocalLocker

NewLocalLocker creates a new local lock instance

func (*LocalLocker) Lock

func (l *LocalLocker) Lock(key string) (success bool, err error)

Lock acquires local lock, compatible with gocron.Locker interface

This function implements sync.Mutex-based local lock, suitable for single-machine deployment scenarios. In distributed environments, multiple instances cannot coordinate, may lead to duplicate execution.

Parameters:

  • key: lock key name, used to identify different locks

Returns:

  • success: true means successfully acquired lock, false means lock is already held
  • err: error occurred when acquiring lock (local lock will not return error)

Notes:

  • Local lock only suitable for single-machine deployment, cannot prevent duplicate execution in multi-instance scenarios
  • Lock will be automatically released when process exits

func (*LocalLocker) Unlock

func (l *LocalLocker) Unlock(key string) error

Unlock releases local lock, compatible with gocron.Locker interface

Parameters:

  • key: lock key name, must match the key name used in Lock

Returns:

  • error: error occurred when releasing lock (local lock will not return error)

type Locker

type Locker struct {
	Cache *redis.Client // Redis client, if nil then use local lock
	// contains filtered or unexported fields
}

Locker provides distributed lock functionality, compatible with gocron.Locker interface Supports both Redis distributed lock and local lock modes

func (*Locker) Lock

func (s *Locker) Lock(key string) (success bool, err error)

Lock acquires distributed lock, compatible with gocron.Locker interface

This function implements Redis-based distributed lock using SETNX command to ensure atomicity. If Redis is unavailable, automatically falls back to local lock. Lock default expiration time is DefaultLockTime seconds, preventing deadlocks.

Parameters:

  • key: lock key name, used to identify different locks

Returns:

  • success: true means successfully acquired lock, false means lock is held by another process
  • err: error occurred when acquiring lock (e.g., Redis connection error)

Side effects:

  • Sets lock key-value pair in Redis (Redis mode)
  • Stores lock value in local lockStore for subsequent unlock verification (Redis mode)
  • Uses randomly generated lock value to ensure only lock holder can release lock (Redis mode)

Notes:

  • Lock has automatic expiration time, even if process crashes won't cause permanent deadlock (Redis mode)
  • Lock value is stored in local memory, will be lost after process restart, but lock will be automatically released after expiration time (Redis mode)
  • Local lock only suitable for single-machine deployment, cannot prevent duplicate execution in multi-instance scenarios

func (*Locker) Unlock

func (s *Locker) Unlock(key string) error

Unlock releases distributed lock, verifies lock owner

This function implements secure lock release mechanism using Lua script to ensure atomicity. If Redis is unavailable, automatically falls back to local lock. Only releases lock when lock value matches, preventing accidental release of other process's lock.

Parameters:

  • key: lock key name, must match the key name used in Lock

Returns:

  • error: error occurred when releasing lock, possible reasons include:
  • Lock value mismatch (lock is held by another process or has expired)
  • Redis operation failure
  • Lock value type error (internal error)

Side effects:

  • Deletes lock key from Redis (only when lock value matches, Redis mode)
  • Deletes lock value record from local lockStore (Redis mode)

Security mechanisms:

  • Uses Lua script to ensure atomicity of check and delete (Redis mode)
  • Verifies lock value to prevent accidental release of other process's lock (Redis mode)
  • If no lock value stored locally, will directly delete (backward compatible, but not secure)

Notes:

  • Must use the same key as in Lock
  • If lock has expired or is held by another process, will return error (Redis mode)

type RedisUserCache

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

RedisUserCache provides Redis-based user cache

func NewRedisUserCache

func NewRedisUserCache(client *redis.Client) *RedisUserCache

NewRedisUserCache creates a new Redis user cache

func (*RedisUserCache) Clear

func (c *RedisUserCache) Clear() error

Clear clears cache

func (*RedisUserCache) Exists

func (c *RedisUserCache) Exists() (bool, error)

Exists checks if cache exists

func (*RedisUserCache) Get

func (c *RedisUserCache) Get() ([]define.AllowListUser, error)

Get gets user list from Redis

func (*RedisUserCache) GetVersion

func (c *RedisUserCache) GetVersion() (int64, error)

GetVersion gets cache version number

func (*RedisUserCache) Set

func (c *RedisUserCache) Set(users []define.AllowListUser) error

Set stores user list to Redis and updates version number

type SafeUserCache

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

SafeUserCache provides thread-safe user cache Uses map structure to improve lookup efficiency while maintaining API compatibility Maintains order list to preserve insertion order Caches hash value to optimize data change detection Maintains multiple indexes to support fast queries by phone, mail, user_id

func NewSafeUserCache

func NewSafeUserCache() *SafeUserCache

NewSafeUserCache creates a new thread-safe user cache

func (*SafeUserCache) Get

func (c *SafeUserCache) Get() []define.AllowListUser

Get gets a copy of user list (thread-safe) Returns slice format to maintain API compatibility Return order matches the order when Set was called Uses sync.Pool to optimize memory allocation

func (*SafeUserCache) GetByMail

func (c *SafeUserCache) GetByMail(mail string) (define.AllowListUser, bool)

GetByMail gets user by email (thread-safe, O(1) lookup)

func (*SafeUserCache) GetByPhone

func (c *SafeUserCache) GetByPhone(phone string) (define.AllowListUser, bool)

GetByPhone gets user by phone number (thread-safe, O(1) lookup)

func (*SafeUserCache) GetByUserID

func (c *SafeUserCache) GetByUserID(userID string) (define.AllowListUser, bool)

GetByUserID gets user by user ID (thread-safe, O(1) lookup)

func (*SafeUserCache) GetHash

func (c *SafeUserCache) GetHash() string

GetHash gets cached hash value (thread-safe) If hash value is not calculated, returns empty string Using cached hash value can avoid redundant calculations and improve performance

func (*SafeUserCache) GetReadOnly

func (c *SafeUserCache) GetReadOnly() []define.AllowListUser

GetReadOnly gets read-only view (actually returns copy, but semantically represents read-only) For read-only scenarios, recommend using Iterate method to avoid copying

func (*SafeUserCache) Iterate

func (c *SafeUserCache) Iterate(fn func(user define.AllowListUser) bool)

Iterate iterates all users, avoiding copying entire slice (thread-safe) Callback function receives user data in insertion order If callback function returns false, iteration will stop

func (*SafeUserCache) Len

func (c *SafeUserCache) Len() int

Len gets user count (thread-safe)

func (*SafeUserCache) Set

func (c *SafeUserCache) Set(users []define.AllowListUser)

Set sets user list (thread-safe) Accepts slice format, internally converts to map for storage Preserves input order

Jump to

Keyboard shortcuts

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