quota

package
v0.30.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LimitModeSoft = "soft"
	LimitModeHard = "hard"
)
View Source
const (
	CodeQuotaExhausted = "E_QUOTA_EXHAUSTED"

	CodeQuotaUnavailable = "E_QUOTA_UNAVAILABLE"
)
View Source
const (
	ReservationReserved = "reserved"
	ReservationSettled  = "settled"
	ReservationReleased = "released"
	ReservationExpired  = "expired"
)
View Source
const GrantCycleMonthly = "monthly"
View Source
const ReservationTTL = 24 * time.Hour

Variables

View Source
var ErrIdemReplay = errors.New("quota: idempotency key replayed")

ErrIdemReplay is returned by ConsumeWithTx when the caller's idempotency key was already recorded (a replayed submission): no charge was made and the caller should treat the operation as already-done.

Functions

func Period

func Period(now time.Time) string

Types

type ConsumeOpts

type ConsumeOpts struct {
	IdemKey string
}

type ConsumeResult

type ConsumeResult struct {
	Replay bool
}

type GrantIssued

type GrantIssued struct {
	WorkspaceID string
	Key         string
	Reason      string

	RefID  string
	Amount int
	Period string
}

type Limits

type Limits map[string]int64

type QuotaHooks

type QuotaHooks struct {
	OnNearLimit func(ctx context.Context, workspaceID, key string, used, limit int64) error

	OnExhausted func(ctx context.Context, workspaceID, key string) error

	OnGrant func(ctx context.Context, workspaceID, key, reason, refID string, amount int) error

	OnReservationExpired func(ctx context.Context, reservationID, workspaceID, quotaKey string, amount int64) error
}

type ReleaseResult

type ReleaseResult struct {
	Released int64

	Remaining int64

	Replay bool
}

type Reservation

type Reservation struct {
	ID             string     `json:"id"`
	WorkspaceID    string     `json:"workspace_id"`
	QuotaKey       string     `json:"quota_key"`
	PeriodKey      string     `json:"period_key"`
	Amount         int64      `json:"amount"`
	SettledAmount  int64      `json:"settled_amount"`
	ReleasedAmount int64      `json:"released_amount"`
	Status         string     `json:"status"`
	ExpiresAt      time.Time  `json:"expires_at"`
	CreatedAt      time.Time  `json:"created_at"`
	SettledAt      *time.Time `json:"settled_at,omitempty"`
	ReleasedAt     *time.Time `json:"released_at,omitempty"`
}

func (Reservation) Outstanding

func (r Reservation) Outstanding() int64

type ReservationBrief

type ReservationBrief struct {
	ID        string    `json:"id"`
	Amount    int64     `json:"amount"`
	Status    string    `json:"status"`
	ExpiresAt time.Time `json:"expires_at"`
}

type ReserveOpts

type ReserveOpts struct {
	FailOpen bool

	TTL time.Duration
}

type ReserveResult

type ReserveResult struct {
	ReservationID string

	Replay bool

	Degraded bool
}

type Service

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

func NewService

func NewService(pool *pgxpool.Pool) *Service

func (*Service) ActiveReservations

func (s *Service) ActiveReservations(ctx context.Context, workspaceID, period string) (map[string][]ReservationBrief, error)

func (*Service) Check

func (s *Service) Check(ctx context.Context, workspaceID, key string, now time.Time) (Status, error)

func (*Service) Consume

func (s *Service) Consume(ctx context.Context, workspaceID, key string, n int64, now time.Time) error

func (*Service) ConsumeWith

func (s *Service) ConsumeWith(ctx context.Context, workspaceID, key string, n int64, now time.Time, opts ConsumeOpts) (ConsumeResult, error)

func (*Service) ConsumeWithTx added in v0.30.0

func (s *Service) ConsumeWithTx(ctx context.Context, tx pgx.Tx, workspaceID, key string, n int64, now time.Time, opts ConsumeOpts) (ConsumeResult, error)

ConsumeWithTx charges n units of key inside the CALLER's transaction (callerCommit semantics, audit §4 P2): the charge becomes atomic with whatever business row the caller writes in the same tx — no crash window between "quota spent" and "row exists".

Contract:

  • tx must be a pgx.Tx (it satisfies execer); the caller owns Commit / Rollback. A charge that fails quota returns E_QUOTA_EXCEEDED and the caller rolls back — the idem insert (if any) rolls back with it, so a later retry with the same key is NOT treated as a replay.
  • With opts.IdemKey set, the key is recorded in quota_consume_idem in this same tx; replay detection (RowsAffected==0) returns ErrIdemReplay without touching the counter.
  • The near-limit hook is NOT fired here (it reads via the pool and would escape the tx); call (*Service).Consume after Commit if the product wants that signal — the video domain does not.

plan limits are read through the same tx so hard/soft mode and limit see a consistent snapshot with the caller's writes.

func (*Service) ExpireDueReservations

func (s *Service) ExpireDueReservations(ctx context.Context, now time.Time, limit int) ([]Reservation, error)

func (*Service) Grant

func (s *Service) Grant(ctx context.Context, workspaceID, key, reason, refID string, amount int, now time.Time) (bool, error)

func (*Service) GrantPeriodic

func (s *Service) GrantPeriodic(ctx context.Context, workspaceID, key, reason, refID string, amount int, cycle string, now time.Time) (bool, error)

func (*Service) GrantTx added in v0.9.0

func (s *Service) GrantTx(ctx context.Context, tx pgx.Tx, workspaceID, key, reason, refID string, amount int, now time.Time) (bool, error)

GrantTx runs the same idempotent insert as Grant on the CALLER's transaction (ADR 0016: provisioning grants credits inside the same transaction that inserts the personal workspace). It deliberately does NOT fire the OnGrant hook — hook timing inside a foreign transaction is not definable: the caller may still roll the grant back, and a hook side-fired here would have observed a grant that never committed. Callers that need the hook side-effect must fire it themselves after their transaction commits.

Reserved key prefixes (2026-11-13 audit §3.6): the billing domain owns any key starting with "price_" or "metered_" (its plan-sync writes them; see isQuotaDimKey). Product-defined credit keys MUST NOT use these prefixes — a collision makes the billing plan sync overwrite the product's grants with plan-derived amounts. Same rule for Grant/GrantPeriodic/grantOnce.

func (*Service) LimitsFor

func (s *Service) LimitsFor(ctx context.Context, workspaceID string) (Limits, string, error)

func (*Service) RefreshPeriodicGrants

func (s *Service) RefreshPeriodicGrants(ctx context.Context, now time.Time) ([]GrantIssued, error)

func (*Service) Release

func (s *Service) Release(ctx context.Context, workspaceID, key string, n int64, now time.Time) error

func (*Service) ReleasePeriod added in v0.30.0

func (s *Service) ReleasePeriod(ctx context.Context, workspaceID, key string, n int64, period string) error

ReleasePeriod releases n units on the EXPLICIT period using the service pool (non-transactional). This is the period-fixed counterpart of Release: callers that cannot run inside the caller's tx (background compensation like the video render worker) must still target the consumption-time period — releasing "now" across a month boundary decrements the wrong counter or matches zero rows silently.

func (*Service) ReleaseReservation

func (s *Service) ReleaseReservation(ctx context.Context, reservationID string, amount int64, idemKey string) (ReleaseResult, error)

func (*Service) ReleaseTx added in v0.30.0

func (s *Service) ReleaseTx(ctx context.Context, tx pgx.Tx, workspaceID, key string, n int64, period string) error

ReleaseTx releases n units on the EXPLICIT period inside the caller's transaction (audit §4 P3): the release becomes atomic with the caller's terminal state write (e.g. video_render → failed), and the period is the one fixed at consumption time — releasing "now" at a month boundary would decrement the wrong counter or silently match zero rows.

func (*Service) Reserve

func (s *Service) Reserve(ctx context.Context, workspaceID, key string, amount int64, idemKey string, opts ReserveOpts) (ReserveResult, error)

func (*Service) Settle

func (s *Service) Settle(ctx context.Context, reservationID string, actual int64, idemKey string) (SettleResult, error)

func (*Service) Usage

func (s *Service) Usage(ctx context.Context, workspaceID, key, period string) (int64, int64, error)

func (*Service) WithHooks

func (s *Service) WithHooks(h QuotaHooks) *Service

type SettleResult

type SettleResult struct {
	Actual int64

	Replay bool
}

type Status

type Status struct {
	Key     string `json:"key"`
	Limit   int64  `json:"limit"`
	Used    int64  `json:"used"`
	Granted int64  `json:"granted"`

	Reserved int64 `json:"reserved"`

	Reservations []ReservationBrief `json:"reservations,omitempty"`
	Period       string             `json:"period"`
}

func (Status) Exceeded

func (st Status) Exceeded() bool

Directories

Path Synopsis
adapters

Jump to

Keyboard shortcuts

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