idempotency

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultUnresolvedTTL = 24 * time.Hour

DefaultUnresolvedTTL is how long a record stays in StateSending when no other value is configured.

Variables

View Source
var (
	// ErrInFlight indicates a concurrent request holds the pending slot.
	ErrInFlight = errors.New("idempotency: request in flight")
	// ErrDeliveryUnknown means delivery may have happened and cannot be retried safely.
	ErrDeliveryUnknown = errors.New("idempotency: delivery outcome unknown")
	// ErrNamespaceConflict indicates an unattributable legacy implicit-key record.
	ErrNamespaceConflict = errors.New("idempotency: legacy namespace conflict")

	// ErrConflict indicates the same key was used with a different request
	// fingerprint (different body). This maps to HTTP 409.
	ErrConflict = errors.New("idempotency: key reused with a different request")
	// ErrBackendUnavailable indicates the Redis backend failed; callers must
	// fail closed rather than proceeding without idempotency protection.
	ErrBackendUnavailable = errors.New("idempotency: backend unavailable")
	// ErrOwnershipLost indicates that a pending record expired or was replaced
	// before its original handler attempted to complete it.
	ErrOwnershipLost = errors.New("idempotency: pending ownership lost")
)

Errors returned by the store.

Functions

func Fingerprint

func Fingerprint(parts ...string) string

Fingerprint computes a stable fingerprint over the normalized request fields so the same key reused with a different body is detected as a conflict. Ordinary NUL-free requests retain their existing fingerprint for rolling upgrades. Embedded NULs require length framing: delimiters alone let bytes move between fields without changing the hash input. The v2 prefix keeps framed fingerprints disjoint from legacy hex digests.

Types

type Record

type Record struct {
	State       State           `json:"state"`
	Fingerprint string          `json:"fingerprint"`
	Owner       string          `json:"owner,omitempty"`
	ChallengeID string          `json:"challenge_id,omitempty"`
	Response    json.RawMessage `json:"response,omitempty"`
	CreatedAt   int64           `json:"created_at"`
}

Record is the persisted idempotency record. The Response is opaque JSON that the caller stores on success and replays on a duplicate.

type State

type State string

State is the lifecycle state of an idempotency record.

const (
	// StatePending is an expiring pre-send claim; a concurrent duplicate must
	// not proceed. MarkSending replaces its short TTL with the unresolved TTL
	// before delivery.
	StatePending State = "pending"
	// StateSending is persisted before delivery. A crash or an uncertain
	// provider result must never turn this key into a fresh send while the
	// record exists. It expires after the unresolved TTL so an interrupted
	// request does not leave a permanent key.
	StateSending State = "sending"
	// StateSucceeded means the original request completed and the stored
	// response should be replayed.
	StateSucceeded State = "succeeded"
	// StateFailed means the original request failed terminally; a retry with the
	// same key may proceed (the record is cleared on failure).
	StateFailed State = "failed"
)

type Store

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

Store implements an atomic, principal-namespaced idempotency store backed by Redis. Keys are HMAC(principal + client-key) so a raw client-supplied key is never used directly as a Redis key and one principal cannot probe or collide with another principal's keys.

func NewStore

func NewStore(client *redis.Client, prefix string, secret []byte, ttl time.Duration) *Store

NewStore creates a Store. secret must be non-empty (used to derive keys and prevent cross-principal collisions / key guessing).

func (*Store) Begin

func (s *Store) Begin(ctx context.Context, principal, clientKey, fingerprint string) (replay json.RawMessage, owner string, err error)

Begin attempts to claim the pending slot for (principal, clientKey, fingerprint). Outcomes:

  • nil, owner, nil -> caller owns the slot and must proceed, then call Succeed or Fail.
  • replayResp, "", nil -> a prior success exists; caller replays it (replayResp non-nil).
  • nil, "", ErrInFlight -> a concurrent request holds the slot.
  • nil, "", ErrDeliveryUnknown -> sending started; never resend automatically.
  • nil, "", ErrConflict -> key reused with a different fingerprint.
  • nil, "", ErrBackendUnavailable -> Redis failure; caller fails closed.

func (*Store) BeginWithLegacyGuard added in v1.3.13

func (s *Store) BeginWithLegacyGuard(ctx context.Context, principal, legacyPrincipal, clientKey, fingerprint string) (json.RawMessage, string, error)

BeginWithLegacyGuard keeps explicit-key record keys unchanged, unifies new implicit-key requests with them, and blocks ambiguous records from old code.

func (*Store) Fail

func (s *Store) Fail(ctx context.Context, principal, clientKey, fingerprint, owner string) error

Fail clears a pre-send pending slot so a retry can proceed. Once sending starts, even an error can mean delivery happened, so the record is retained.

func (*Store) MarkSending added in v1.3.3

func (s *Store) MarkSending(ctx context.Context, principal, clientKey, fingerprint, owner, challengeID string) error

MarkSending atomically replaces the pending lease before the external side effect. Only its owner can complete it; Fail cannot reopen it, and the key stays claimed until the unresolved TTL elapses. ChallengeID lets operators reconcile an interrupted send without storing codes.

func (*Store) Refresh added in v1.0.0

func (s *Store) Refresh(ctx context.Context, principal, clientKey, fingerprint, owner string) error

Refresh verifies that the caller still owns a pending record and renews its TTL before sending, or renews the unresolved TTL of a sending record. Handlers call this immediately before activation so an expired, stale request cannot mutate challenge state owned by a replacement request.

func (*Store) Succeed

func (s *Store) Succeed(ctx context.Context, principal, clientKey, fingerprint, owner string, response json.RawMessage) error

Succeed stores the terminal success response so future duplicates replay it.

func (*Store) WithUnresolvedTTL added in v1.7.0

func (s *Store) WithUnresolvedTTL(ttl time.Duration) *Store

WithUnresolvedTTL sets how long a record may stay in StateSending. It must exceed the pending TTL; non-positive values keep the current setting.

Jump to

Keyboard shortcuts

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