proxydb

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package proxydb is the pgx data layer: api keys, the model registry, routing rules, encrypted vendor keys, and the config version counter.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound      = errors.New("proxydb: not found")
	ErrAlreadyExists = errors.New("proxydb: already exists")
	ErrTenantInUse   = errors.New("proxydb: tenant still has active api keys")
)
View Source
var ErrBatchAlreadyExists = errors.New("proxydb: batch already exists")

ErrBatchAlreadyExists is returned on idempotency conflict if client resubmitted.

Functions

func CreateTeamTx added in v0.14.0

func CreateTeamTx(ctx context.Context, tx pgx.Tx, team *Team) error

func DeleteModel

func DeleteModel(ctx context.Context, tx pgx.Tx, id string) error

func DeleteOrganizationTx added in v0.14.0

func DeleteOrganizationTx(ctx context.Context, tx pgx.Tx, id string) error

DeleteOrganizationTx removes an organization, its teams (cascade) and their spend limits, detaching disabled keys like DeleteTeamTx; active keys refuse it.

func DeleteSpendLimit

func DeleteSpendLimit(ctx context.Context, tx pgx.Tx, subjectType, subjectID, period string) error

func DeleteTeamTx added in v0.14.0

func DeleteTeamTx(ctx context.Context, tx pgx.Tx, id string) error

DeleteTeamTx removes a team and its spend limits. Disabled keys are detached (keys are never deleted, so they would pin the team forever); active keys make it ErrTenantInUse: revoke or move them first.

func DeleteUserRateLimit

func DeleteUserRateLimit(ctx context.Context, tx pgx.Tx, userID, modelID string) error

func DeleteVendorKey

func DeleteVendorKey(ctx context.Context, tx pgx.Tx, apiKeyID, vendor string) error

func Migrate

func Migrate(ctx context.Context, pool *pgxpool.Pool, src fs.FS) error

Migrate applies every embedded file that the ledger has not recorded yet.

Each file runs in its own transaction, so a failure leaves the earlier ones applied and the rest pending. A failure is the caller's cue to refuse to serve: half-migrated is a state the code was not written for.

func ReplaceRules

func ReplaceRules(ctx context.Context, tx pgx.Tx, rules []*Rule) error

ReplaceRules swaps the whole rule set; position encodes chain order.

func SetTeamBudgetTx added in v0.14.0

func SetTeamBudgetTx(ctx context.Context, tx pgx.Tx, teamID string, limitNanoUSD int64) error

SetTeamBudgetTx makes the team's monthly spend limit match its budget: the team row and spend_limit change together, so they cannot drift apart.

func SetVendorKey

func SetVendorKey(ctx context.Context, tx pgx.Tx, v *VendorKey) error

func UpdateTeamTx added in v0.14.0

func UpdateTeamTx(ctx context.Context, tx pgx.Tx, team *Team) error

func UpdateVendorKeyCiphertext

func UpdateVendorKeyCiphertext(ctx context.Context, tx pgx.Tx, id string, ciphertext []byte, version int32) error

UpdateVendorKeyCiphertext is the rotation path: same secret, newer keyring version.

func UpsertModel

func UpsertModel(ctx context.Context, tx pgx.Tx, m *Model) error

func UpsertSpendLimit

func UpsertSpendLimit(ctx context.Context, tx pgx.Tx, l *SpendLimit) error

func UpsertUserRateLimit

func UpsertUserRateLimit(ctx context.Context, tx pgx.Tx, u *UserRateLimit) error

Types

type APIKey

type APIKey struct {
	ID                string
	Name              string
	KeyLookup         string
	KeyHash           string
	Scopes            []string
	DisabledAt        *time.Time
	CreatedAt         time.Time
	OrgID             *string
	TeamID            *string
	TeamAllowedModels []string
	// Policy of the key itself; empty and 0 mean no limit.
	AllowedModels []string
	RPMLimit      int32
	TPMLimit      int64
}

func (*APIKey) Active

func (k *APIKey) Active() bool

type Batch

type Batch struct {
	ID            string
	ClientBatchID string
	APIKeyID      string
	KeyName       string
	Model         string
	VendorJobName string
	State         string // PENDING, RUNNING, SUCCEEDED, FAILED, CANCELLED, EXPIRED
	TotalCount    int32
	DoneCount     int32
	FailedCount   int32
	Attributes    map[string]string
	ActionID      string
	CreatedAt     time.Time
	CompletedAt   *time.Time
	LeasedUntil   *time.Time
	// The submitting key's tenant, read on lease: stored attributes predate
	// the reserved team keys and may carry a caller's own team_id.
	OrgID  string
	TeamID string
}

type BatchItem

type BatchItem struct {
	BatchID        string
	CustomID       string
	Position       int32
	Status         string // PENDING, SUCCEEDED, FAILED
	ResponseSchema []byte // optional JSON representation of ResponseSchema
	Result         []byte // raw JSON of GenerateTextResponse
	Error          []byte // raw JSON of BatchItemError
	InputTokens    int64
	OutputTokens   int64
}

type DB

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

func New

func New(pool *pgxpool.Pool) *DB

func (*DB) CompleteBatch

func (d *DB) CompleteBatch(ctx context.Context, id string, finalState string, doneCount, failedCount int32, completedAt time.Time, items []*BatchItem) error

func (*DB) ConfigVersion

func (d *DB) ConfigVersion(ctx context.Context) (int64, error)

func (*DB) CreateBatch

func (d *DB) CreateBatch(ctx context.Context, b *Batch, items []*BatchItem) (*Batch, error)

func (*DB) CreateOrganization added in v0.14.0

func (d *DB) CreateOrganization(ctx context.Context, org *Organization) error

func (*DB) DeleteBatchesOlderThan

func (d *DB) DeleteBatchesOlderThan(ctx context.Context, cutoff time.Time) (int64, error)

func (*DB) DisableAPIKey

func (d *DB) DisableAPIKey(ctx context.Context, name string) error

func (*DB) ExpireBatch

func (d *DB) ExpireBatch(ctx context.Context, id string, expiredAt time.Time) error

func (*DB) GetAPIKeyByLookup

func (d *DB) GetAPIKeyByLookup(ctx context.Context, lookup string) (*APIKey, error)

func (*DB) GetAPIKeyByName

func (d *DB) GetAPIKeyByName(ctx context.Context, name string) (*APIKey, error)

func (*DB) GetBatch

func (d *DB) GetBatch(ctx context.Context, id, apiKeyID string) (*Batch, error)

func (*DB) GetBatchByClientBatchID

func (d *DB) GetBatchByClientBatchID(ctx context.Context, apiKeyID, clientBatchID string) (*Batch, error)

func (*DB) GetBatchByID

func (d *DB) GetBatchByID(ctx context.Context, id string) (*Batch, error)

func (*DB) GetNodeKeyByLookup

func (d *DB) GetNodeKeyByLookup(ctx context.Context, lookup string) (*NodeKey, error)

func (*DB) GetOrganization added in v0.14.0

func (d *DB) GetOrganization(ctx context.Context, id string) (*Organization, error)

func (*DB) GetTeam added in v0.14.0

func (d *DB) GetTeam(ctx context.Context, id string) (*Team, error)

func (*DB) InsertAPIKey

func (d *DB) InsertAPIKey(ctx context.Context, k *APIKey) error

func (*DB) InsertNodeKey

func (d *DB) InsertNodeKey(ctx context.Context, k *NodeKey) error

func (*DB) LeaseUnfinishedBatches

func (d *DB) LeaseUnfinishedBatches(ctx context.Context, leaseDuration time.Duration, limit int) ([]*Batch, error)

func (*DB) ListAPIKeys

func (d *DB) ListAPIKeys(ctx context.Context) ([]*APIKey, error)

func (*DB) ListAllBatchItems

func (d *DB) ListAllBatchItems(ctx context.Context, batchID string) ([]*BatchItem, error)

func (*DB) ListBatchItems

func (d *DB) ListBatchItems(ctx context.Context, batchID string, limit, offset int) ([]*BatchItem, error)

func (*DB) ListNodeKeys

func (d *DB) ListNodeKeys(ctx context.Context) ([]*NodeKey, error)

func (*DB) ListOrganizations added in v0.14.0

func (d *DB) ListOrganizations(ctx context.Context) ([]*Organization, error)

func (*DB) ListTeams added in v0.14.0

func (d *DB) ListTeams(ctx context.Context, orgID string) ([]*Team, error)

func (*DB) LoadModels

func (d *DB) LoadModels(ctx context.Context) ([]*Model, error)

func (*DB) LoadRules

func (d *DB) LoadRules(ctx context.Context) ([]*Rule, error)

func (*DB) LoadSpendLimits

func (d *DB) LoadSpendLimits(ctx context.Context) ([]*SpendLimit, error)

func (*DB) LoadUserRateLimits

func (d *DB) LoadUserRateLimits(ctx context.Context) ([]*UserRateLimit, error)

func (*DB) LoadVendorKeys

func (d *DB) LoadVendorKeys(ctx context.Context) ([]*VendorKey, error)

func (*DB) Mutate

func (d *DB) Mutate(ctx context.Context, fn func(tx pgx.Tx) error,
	validate func(models []*Model, rules []*Rule) error) (int64, error)

Mutate runs fn inside a transaction, then revalidates the resulting config via validate and bumps the version counter. Any error rolls everything back.

func (*DB) RevokeNodeKey

func (d *DB) RevokeNodeKey(ctx context.Context, id int64) (string, error)

func (*DB) SetAPIKeyPolicy added in v1.0.0

func (d *DB) SetAPIKeyPolicy(ctx context.Context, name string, allowedModels []string, rpm int32, tpm int64) error

SetAPIKeyPolicy replaces the policy of the key with this name.

func (*DB) UpdateBatchRunning

func (d *DB) UpdateBatchRunning(ctx context.Context, id string, total, done, failed int32) error

type Model

type Model struct {
	ID              string
	Vendor          string
	Endpoint        string
	Efforts         []string
	Capabilities    []string
	RPM             int32
	PriceInPerMtok  float64
	PriceOutPerMtok float64
	// Peak rates, 0 when the vendor bills one price around the clock. DeepSeek
	// V4 doubles for two windows a day, so one price understates its cost.
	PriceInPeakPerMtok  float64
	PriceOutPeakPerMtok float64
	// Batch rates, 0 means half the standard (off-peak) rate.
	PriceInBatchPerMtok  float64
	PriceOutBatchPerMtok float64
	// Prompt-cache rates at the standard rate, 0 = the vendor default.
	PriceCacheReadPerMtok  float64
	PriceCacheWritePerMtok float64
	DailyTokensPerKey      int64
	DailyTokensPerUser     int64
	Burst                  int32
	QueueTimeoutMs         int32
	BudgetGraceMargin      float64
	Enabled                bool
}

func (*Model) BatchPriceInPerMtok

func (m *Model) BatchPriceInPerMtok() float64

func (*Model) BatchPriceOutPerMtok

func (m *Model) BatchPriceOutPerMtok() float64

func (*Model) CacheReadPerMtok added in v1.0.0

func (m *Model) CacheReadPerMtok() float64

CacheReadPerMtok is the standard rate for input read from the prompt cache. Unset, a vendor ratio that never undercharges: Anthropic's 0.1x holds for every Claude model, Bedrock's 0.25x covers Claude (0.1x) and Nova (0.25x).

func (*Model) CacheWritePerMtok added in v1.0.0

func (m *Model) CacheWritePerMtok() float64

CacheWritePerMtok is the standard rate for input written to the prompt cache: Anthropic and Bedrock charge Claude 1.25x input for the default 5-minute cache.

func (*Model) EffectiveBurst

func (m *Model) EffectiveBurst() int32

type NodeKey

type NodeKey struct {
	ID             int64
	NodeID         string
	Name           string
	KeyLookup      string
	KeyHash        string
	AllowedCIDRs   []string
	AllowedModels  []string
	MaxBaseWeight  float64
	MaxConcurrency int32
	DisabledAt     *time.Time
	CreatedAt      time.Time
}

func (*NodeKey) Active

func (k *NodeKey) Active() bool

type Organization added in v0.14.0

type Organization struct {
	ID        string
	Name      string
	CreatedAt time.Time
}

type Rule

type Rule struct {
	ID               string
	Name             string
	Priority         int32
	Effort           string // "" = any
	Attributes       map[string]string
	Enabled          bool
	Use              []string // ordered model ids
	Weights          []int32  // optional traffic weights per model in Use
	ShadowModel      string   // optional shadow model for async traffic mirroring
	ShadowPercentage float64  // 0.0 to 100.0 percent of traffic mirrored to ShadowModel
	ShadowEval       bool     // optional automated quality evaluation using Judge
}

type SpendLimit

type SpendLimit struct {
	SubjectType  string // "key" | "user" | "team"
	SubjectID    string // key name / user id, or "*" for the subject type's default
	Period       string // "day" | "month"
	LimitNanoUSD int64
}

SpendLimit caps spend for one subject over one UTC calendar period.

type Team added in v0.14.0

type Team struct {
	ID               string
	OrgID            string
	Name             string
	MonthlyBudgetUSD float64
	AllowedModels    []string
	CreatedAt        time.Time
}

type UserRateLimit

type UserRateLimit struct {
	UserID         string
	ModelID        string
	RPM            int32
	Burst          int32
	QueueTimeoutMs int32
	DailyTokens    int64
}

func (*UserRateLimit) EffectiveBurst

func (u *UserRateLimit) EffectiveBurst() int32

type VendorKey

type VendorKey struct {
	ID            string
	APIKeyID      string
	APIKeyName    string // joined for admin listings
	Vendor        string
	KeyCiphertext []byte
	KeyVersion    int32
	CreatedAt     time.Time
}

func LockStaleVendorKeysTx added in v0.14.0

func LockStaleVendorKeysTx(ctx context.Context, tx pgx.Tx, version int32) ([]*VendorKey, error)

LockStaleVendorKeysTx reads the vendor keys not at version and locks them until the transaction ends, so a key set meanwhile cannot be overwritten by a stale re-encryption of the previous one. Keys already at version are left unlocked: a rotation never rewrites them.

Jump to

Keyboard shortcuts

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