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
- Variables
- func AcceptableCount(users []define.AllowListUser) int
- func HashUserList(users []define.AllowListUser) string
- func SnapshotFailureReason(err error) string
- func ValidateSnapshotNamespace(namespace string) bool
- type LocalLocker
- type Locker
- type PreparedRules
- type ReadView
- func (v *ReadView) Get() []define.AllowListUser
- func (v *ReadView) GetByMail(mail string) (define.AllowListUser, bool)
- func (v *ReadView) GetByPhone(phone string) (define.AllowListUser, bool)
- func (v *ReadView) GetByUserID(userID string) (define.AllowListUser, bool)
- func (v *ReadView) GetHash() string
- func (v *ReadView) Iterate(fn func(define.AllowListUser) bool)
- func (v *ReadView) Len() int
- func (v *ReadView) Page(page, pageSize int) (rows []define.AllowListUser, total, totalPages int)
- type RedisSnapshotStore
- type RedisUserCache
- type SafeUserCache
- func (c *SafeUserCache) ApplyPrepared(p *PreparedRules)
- func (c *SafeUserCache) Get() []define.AllowListUser
- func (c *SafeUserCache) GetByMail(mail string) (define.AllowListUser, bool)
- func (c *SafeUserCache) GetByPhone(phone string) (define.AllowListUser, bool)
- func (c *SafeUserCache) GetByUserID(userID string) (define.AllowListUser, bool)
- func (c *SafeUserCache) GetHash() string
- func (c *SafeUserCache) GetReadOnly() []define.AllowListUser
- func (c *SafeUserCache) Iterate(fn func(user define.AllowListUser) bool)
- func (c *SafeUserCache) Len() int
- func (c *SafeUserCache) ReadView() *ReadView
- func (c *SafeUserCache) Set(users []define.AllowListUser)
- func (c *SafeUserCache) SetValidated(users []define.AllowListUser, opts identity.Options) error
- type SnapshotEnvelope
- type SnapshotLease
- type ViewSource
Constants ¶
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 )
const ( IndexPhone = "phone" IndexMail = "mail" IndexUserID = "user_id" )
Index names for multi-index cache
const SNAPSHOT_SCHEMA_V2 = 2
Snapshot protocol constants follow the project's constant naming convention.
Variables ¶
var ( ErrSnapshotSchema = fmt.Errorf("%w: unsupported schema", ErrSnapshotContract) ErrSnapshotDataset = fmt.Errorf("%w: dataset mismatch", ErrSnapshotContract) ErrSnapshotPolicy = fmt.Errorf("%w: policy mismatch", ErrSnapshotContract) ErrSnapshotTimestamp = fmt.Errorf("%w: timestamp invalid", ErrSnapshotInvalid) ErrSnapshotTooLarge = fmt.Errorf("%w: size limit", ErrSnapshotInvalid) ErrSnapshotMissing = fmt.Errorf("%w: snapshot missing", ErrSnapshotConflict) )
Detailed snapshot failures retain the existing broad errors for errors.Is.
var ( ErrSnapshotInvalid = errors.New("invalid versioned snapshot") ErrSnapshotContract = errors.New("snapshot contract mismatch") ErrSnapshotLeaseLost = errors.New("snapshot writer lease lost") ErrSnapshotConflict = errors.New("snapshot revision changed") )
Versioned snapshot errors never include users, keys or raw payloads.
Functions ¶
func AcceptableCount ¶ added in v1.3.0
func AcceptableCount(users []define.AllowListUser) int
AcceptableCount reports how many records of users would survive a Set: how large the effective rule set becomes once empty-identifier records are dropped, per-record format validation has run, and duplicates sharing a primary key have collapsed.
It exists so a caller can learn "this load would leave the cache empty" BEFORE mutating the cache. Set is the single atomic swap point, so probing by writing and inspecting the result would expose an empty rule set to concurrent readers for as long as the caller takes to undo it. AcceptableCount answers the same question with no window at all.
It deliberately stays silent: the records it inspects are validated again for real by Set, which logs every rejection. Counting here must not duplicate those warnings.
The steps mirror SafeUserCache.Set and the cache-kit Set it delegates to, in the same order (normalize, validate, primary key, dedup); acceptable_count_test.go pins the two against each other so they cannot drift apart.
func HashUserList ¶ added in v0.9.0
func HashUserList(users []define.AllowListUser) string
HashUserList computes SHA256 hash of user list for change detection. Sorts by primary key (phone or mail), normalizes each user, then hashes. Used by SafeUserCache internally and by main for backgroundTask comparison.
func SnapshotFailureReason ¶ added in v1.5.0
SnapshotFailureReason is a bounded diagnostic code, never an error message.
func ValidateSnapshotNamespace ¶ added in v1.5.0
ValidateSnapshotNamespace checks an operator-selected dataset without exposing it.
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 ¶
Lock acquires distributed lock, compatible with gocron.Locker interface
This function uses redis-kit's HybridLocker which automatically falls back to local lock if Redis is unavailable. Lock default expiration time is DefaultLockTime seconds.
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)
Notes:
- Lock has automatic expiration time, even if process crashes won't cause permanent deadlock (Redis mode)
- Local lock only suitable for single-machine deployment, cannot prevent duplicate execution in multi-instance scenarios
func (*Locker) Unlock ¶
Unlock releases distributed lock
This function uses redis-kit's HybridLocker which automatically falls back to local lock if Redis is unavailable.
Parameters:
- key: lock key name, must match the key name used in Lock
Returns:
- error: error occurred when releasing lock
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 PreparedRules ¶ added in v1.5.0
type PreparedRules struct {
// contains filtered or unexported fields
}
PreparedRules owns a validated candidate that has not been published yet. Identity errors reject the whole input before per-record filtering is applied.
func PrepareRules ¶ added in v1.5.0
func PrepareRules(users []define.AllowListUser, opts identity.Options) (*PreparedRules, error)
PrepareRules constructs the effective indexes without changing any live cache or logging per-record rejections. Empty-ruleset policy can inspect the candidate before deciding whether to publish it.
func (*PreparedRules) InputCount ¶ added in v1.5.0
func (p *PreparedRules) InputCount() int
InputCount is the count before per-record format validation.
func (*PreparedRules) InputVersion ¶ added in v1.5.0
func (p *PreparedRules) InputVersion() string
InputVersion describes the loaded input, independently of the effective set.
func (*PreparedRules) ReadView ¶ added in v1.5.0
func (p *PreparedRules) ReadView() *ReadView
ReadView returns the immutable effective candidate.
type ReadView ¶ added in v1.5.0
type ReadView struct {
// contains filtered or unexported fields
}
ReadView is one immutable generation of effective users and their indexes. Values returned to callers own their Scope slices; none can mutate this view.
func (*ReadView) Get ¶ added in v1.5.0
func (v *ReadView) Get() []define.AllowListUser
Get returns a detached copy in the existing insertion order.
func (*ReadView) GetByMail ¶ added in v1.5.0
func (v *ReadView) GetByMail(mail string) (define.AllowListUser, bool)
GetByMail looks up a normalized email index.
func (*ReadView) GetByPhone ¶ added in v1.5.0
func (v *ReadView) GetByPhone(phone string) (define.AllowListUser, bool)
GetByPhone looks up a trimmed primary key.
func (*ReadView) GetByUserID ¶ added in v1.5.0
func (v *ReadView) GetByUserID(userID string) (define.AllowListUser, bool)
GetByUserID looks up the existing user ID index without changing its semantics.
func (*ReadView) GetHash ¶ added in v1.5.0
GetHash returns the version of the effective, normalized user set.
func (*ReadView) Iterate ¶ added in v1.5.0
func (v *ReadView) Iterate(fn func(define.AllowListUser) bool)
Iterate visits detached records in the existing insertion order.
func (*ReadView) Page ¶ added in v1.5.0
func (v *ReadView) Page(page, pageSize int) (rows []define.AllowListUser, total, totalPages int)
Page returns detached rows from this generation, together with its totals. It copies only the requested page, including Scope, without scanning other rows. Invalid page sizes return an empty page and zero total pages.
type RedisSnapshotStore ¶ added in v1.5.0
type RedisSnapshotStore struct {
// contains filtered or unexported fields
}
RedisSnapshotStore uses isolated, co-located Redis Cluster keys for schema v2.
func NewRedisSnapshotStore ¶ added in v1.5.0
func NewRedisSnapshotStore(client *redis.Client, namespace, policy string) (*RedisSnapshotStore, error)
NewRedisSnapshotStore rejects implicit datasets and invalid policy fingerprints.
func (*RedisSnapshotStore) Acquire ¶ added in v1.5.0
func (s *RedisSnapshotStore) Acquire(ctx context.Context, ttl time.Duration) (*SnapshotLease, error)
Acquire returns nil when another replica holds the bounded writer lease. It never falls back to a process-local lock.
func (*RedisSnapshotStore) Read ¶ added in v1.5.0
func (s *RedisSnapshotStore) Read(ctx context.Context) (*SnapshotEnvelope, error)
Read atomically distinguishes a missing key from a stored, valid empty set. Oversized values are rejected in Redis before being transferred to the client.
type RedisUserCache ¶
type RedisUserCache struct {
// contains filtered or unexported fields
}
RedisUserCache provides Redis-based user cache using cache-kit
func NewRedisUserCache ¶
func NewRedisUserCache(client *redis.Client) *RedisUserCache
NewRedisUserCache creates a new Redis user 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 using cache-kit MultiIndexCache 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) ApplyPrepared ¶ added in v1.5.0
func (c *SafeUserCache) ApplyPrepared(p *PreparedRules)
ApplyPrepared publishes an already prepared generation in one pointer swap. The candidate remains immutable and can be reused without revalidating users.
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
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) ReadView ¶ added in v1.5.0
func (c *SafeUserCache) ReadView() *ReadView
ReadView pins the current immutable generation for a multi-step read.
func (*SafeUserCache) Set ¶
func (c *SafeUserCache) Set(users []define.AllowListUser)
Set preserves the existing unvalidated-set API and insertion order. A new generation is built privately, then published atomically.
func (*SafeUserCache) SetValidated ¶ added in v0.14.0
func (c *SafeUserCache) SetValidated(users []define.AllowListUser, opts identity.Options) error
SetValidated runs centralized identity validation (identifier uniqueness, optional explicit user_id requirement) BEFORE swapping the data into the shared cache. On a uniqueness/missing-id conflict it returns a typed error and leaves the existing cache contents untouched, so a bad remote/local rule set can never overwrite good data with a partially-deduped ("last-write-wins") set. On success the cache is replaced with the deterministically-ordered validated set.
type SnapshotEnvelope ¶ added in v1.5.0
type SnapshotEnvelope struct {
SchemaVersion int `json:"schema_version"`
Dataset string `json:"dataset"`
Policy string `json:"policy"`
Revision string `json:"revision"`
Users []define.AllowListUser `json:"users"`
EffectiveVersion string `json:"effective_version"`
InputVersion string `json:"input_version"`
InputCount int `json:"input_count"`
Origin string `json:"origin"`
SourceSucceededAt time.Time `json:"source_succeeded_at"`
PublishedAt time.Time `json:"published_at"`
}
SnapshotEnvelope stores effective data and its original validation evidence. RestoredAt is intentionally absent: recovery is a process-local event.
type SnapshotLease ¶ added in v1.5.0
type SnapshotLease struct {
// contains filtered or unexported fields
}
SnapshotLease authorizes writes only while its Redis owner token still matches.
func (*SnapshotLease) Publish ¶ added in v1.5.0
func (l *SnapshotLease) Publish(ctx context.Context, input *SnapshotEnvelope) (*SnapshotEnvelope, error)
Publish writes one complete envelope, assigning publication time and revision. A slow writer whose lease expired cannot overwrite the next owner's result.
type ViewSource ¶ added in v1.5.0
type ViewSource interface {
ReadView() *ReadView
}
ViewSource supplies a generation that a consumer can retain for an entire read.