idempotent

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrorCacheEmpty = fmt.Errorf("cache empty")
)

Functions

func DoIdempotent

func DoIdempotent(ctx context.Context, store *redis.Redis, key string, v any, seconds, expired int, fn func(ctx context.Context, v any) error) (bool, error)

DoIdempotent ensures that for a given key the user function fn is executed at most once across distributed workers, and subsequent callers reuse the cached result.

  • First caller:
  • Tries cache; if miss, acquires a distributed lock, executes fn, stores the result in cache, and returns (false, nil).
  • Concurrent callers:
  • If cache already has the value, return (true, nil).
  • If the lock is held by another worker, they wait up to `seconds` by polling the cache:
  • If the value appears in cache during this window, return (true, nil).
  • If it never appears, return an error (for example ErrorCacheEmpty or underlying Redis error).

seconds is the lock TTL in seconds and should be greater than the worst-case execution time of fn. expired is the cache TTL in seconds.

Types

type Idempotent

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

func NewIdempotent

func NewIdempotent(store *redis.Redis, key string) *Idempotent

func (*Idempotent) Lock

func (i *Idempotent) Lock(ctx context.Context, seconds int) (bool, error)

Lock Lock

func (*Idempotent) SetCacheValue

func (i *Idempotent) SetCacheValue(ctx context.Context, v any, expired int) error

func (*Idempotent) TryGetCacheValue

func (i *Idempotent) TryGetCacheValue(ctx context.Context, v any) (cached bool, err error)

func (*Idempotent) Unlock

func (i *Idempotent) Unlock(ctx context.Context) error

Unlock Unlock

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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