store

package
v1.0.0-alpha.41 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 29 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 store is the ledger: FOCUS rows in Postgres, one tenant at a time.

Every query runs inside a transaction that names its tenant with SET LOCAL, and row level security does the filtering. No statement here carries a tenant predicate of its own.

Index

Constants

View Source
const (
	OverrideWindowPullRequests = 20
	OverrideWindowDays         = 90
)

The window a rule's override rate is read over: the latest pull requests on which the rule failed, no older than a span of days.

View Source
const (
	HeadFromToken = "token"
	HeadStated    = "stated"
)

Values of HeadBasis.

View Source
const (
	CredentialMinted = "minted"
	CredentialStated = "stated"
)

Values of CredentialBasis.

View Source
const (
	TagRepo          = focus.TagRepo
	TagPR            = focus.TagPR
	TagCommitSHA     = focus.TagCommitSHA
	TagWorkflowRunID = focus.TagWorkflowRunID
)

Tag keys of the convention that the focus package leaves to the join.

View Source
const KeyPrefix = "costroid_ik_"

KeyPrefix starts every ingest key. A bearer without it is a CI token.

Variables

View Source
var (
	// ErrAttestedElsewhere means a key is already attested, for another run or
	// by another attesting run. The first attestation stands.
	ErrAttestedElsewhere = errors.New("store: the key is attested already")
	// ErrAttestingRunUsed means the attesting run, in this attempt or another,
	// already attested another key, or the same key otherwise.
	ErrAttestingRunUsed = errors.New("store: the attesting run has attested already")
)
View Source
var (
	// ErrNotMinted means a spend names a key no attestation holds for the run
	// it names.
	ErrNotMinted = errors.New("store: the key is not attested as minted for the run")
	// ErrSpendHeld means the key holds another figure than the one sent.
	ErrSpendHeld = errors.New("store: the key holds a spend already")
)
View Source
var ErrDatabaseAhead = errors.New("store: database is ahead of this binary")

ErrDatabaseAhead means the database holds a version this binary does not know. Migrations run forward only, so the binary is what has to change.

View Source
var ErrLoginNotStated = errors.New("store: the ledger holds a binding of the login, and the command line does not state it")

ErrLoginNotStated refuses a token whose id no binding holds, under a login the ledger holds a binding of that the command line does not state. Such a binding is carried over only while it is stated.

View Source
var ErrMigrationEdited = errors.New("store: an applied migration was edited")

ErrMigrationEdited means a migration already applied has changed on disk.

View Source
var ErrNotFound = errors.New("store: not found")

ErrNotFound means a lookup named nothing.

View Source
var ErrUnsafeRole = errors.New("store: unsafe application role")

ErrUnsafeRole means the service was given a role that could read past row level security.

Functions

func AddKey

func AddKey(ctx context.Context, ownerURL string, owner Binding, digest string) error

AddKey stores a key's digest for the tenant holding an SCM owner, through the owner role's connection: an owner's id, or a login a ledger that bound owners by login holds. An owner no tenant holds answers ErrNotFound.

func Address

func Address(url string) string

Address names the role, the host and the database a connection string connects to, and never its password.

func Bind

func Bind(ctx context.Context, ownerURL string, tenant TenantID, bindings []Binding) error

Bind gives owners to a tenant that exists, through the owner role's connection. Each binding names an owner's id, and an id another binding holds fails it.

func BindingKey

func BindingKey(host, id string) string

BindingKey is the key a binding of an owner's id is stored under: the host, '#' and the id.

func KeyDigest

func KeyDigest(key string) string

KeyDigest is the SHA-256 of a key, which is also its public id.

func LoginKey

func LoginKey(host, owner string) string

LoginKey is the key a binding by login is stored under, host:login in lower case.

func Migrate

func Migrate(ctx context.Context, ownerURL string) error

Migrate applies the embedded migrations through the owner's connection.

func MigrateFrom

func MigrateFrom(ctx context.Context, ownerURL string, files fs.FS) error

MigrateFrom applies the migrations in files, each in its own transaction.

func NewKey

func NewKey() (string, error)

NewKey mints an ingest key. Only its digest is ever stored, so a key that is lost is revoked and replaced.

func NotAnswering

func NotAnswering(err error) bool

NotAnswering reports whether err is only Postgres not answering yet: its name does not resolve, it refuses the connection, or it says it is starting. A server that answers anything else, a password or a role it refuses among them, is a fault that waiting does not heal, and so is an error that holds none of the three.

func Provision

func Provision(ctx context.Context, ownerURL string, tenant Tenant) error

Provision writes a tenant through the owner's connection, which the service holds only to migrate and to bind. A binding another binding holds fails it.

func RevokeKey

func RevokeKey(ctx context.Context, ownerURL, digest string) error

RevokeKey stops a key at the next request, through the owner role's connection. A key already revoked keeps its first stamp, and a digest no tenant holds answers ErrNotFound.

Types

type Admission

type Admission struct {
	Tenant TenantID
	// Pinned names the login binding, host:login, that this token carried
	// over to its owner's id. It is empty when the id was bound already.
	Pinned string
}

Admission is how a token's owner found its tenant.

type AttestedSpend

type AttestedSpend struct {
	Key   MintedCredential
	Spend string

	AttestingRunID      string
	AttestingRunAttempt string
}

AttestedSpend is what the gateway counted on a key, in USD, as the decimal string a run of a protected branch sent once the run the key was minted for had ended. Key names that run; the Attesting fields name the run whose token sent the figure.

type AttestingRunUsed

type AttestingRunUsed struct {
	Attempt string
}

AttestingRunUsed is ErrAttestingRunUsed with the attempt of the attesting run whose attestation stands.

func (AttestingRunUsed) Error

func (AttestingRunUsed) Error() string

func (AttestingRunUsed) Unwrap

func (AttestingRunUsed) Unwrap() error

type Batch

type Batch struct {
	Records []Record
	// Drops counts fields dropped at the edge, by field name.
	Drops map[string]int64
	Day   time.Time
}

Batch is one ingest request's writes.

type Binding

type Binding struct {
	Host  string
	Owner string
	ID    string
}

Binding names one SCM owner a tenant holds: by ID, the number its CI tokens state, or by Owner, a login, as a ledger that bound owners by login holds one.

type Deliveries

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

Deliveries keeps the webhook delivery ids the service has taken, so every instance refuses a replayed delivery, and a restart forgets none. The ids belong to the deployment, so no tenant is set.

func (Deliveries) Claim

func (d Deliveries) Claim(ctx context.Context, delivery string, now time.Time) (bool, error)

Claim reports true the first time an id is taken within the retention. It prunes the ids older than the retention first, in the same transaction.

func (Deliveries) Release

func (d Deliveries) Release(ctx context.Context, delivery string) error

Release forgets an id, so a redelivery of it is processed.

type DemotionRecord

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

DemotionRecord keeps where each rule's demotion stands in a repository, as serve's verdicts moved it. It only grows: a state is kept as a new row, and the application role holds no grant to change or remove one.

func (DemotionRecord) Demotion

func (r DemotionRecord) Demotion(ctx context.Context, tenant TenantID, repository Repo, branch, rule string) (RuleDemotion, bool, error)

Demotion reads where a rule's demotion stands at a base branch of the repository, as Repo says which, and false when no verdict has moved it.

func (DemotionRecord) Keep

func (r DemotionRecord) Keep(ctx context.Context, tenant TenantID, demotion RuleDemotion) (RuleDemotion, error)

Keep keeps a rule's demotion, and returns the one that stands after it: another verdict's when that one kept the same re-arm or term first.

type FailingVerdict

type FailingVerdict struct {
	Repository   string
	RepositoryID string
	// BaseBranch is the branch the pull request merges into, as the host
	// stated it. The record is of a rule at one base branch.
	BaseBranch  string
	PullRequest string
	HeadSHA     string
	Rule        string
	Limit       decimal.Decimal
	At          time.Time
}

FailingVerdict is one rule failing on one head commit of a pull request, under the limit the verdict read. RepositoryID is the id the verdict's CI token states for the repository, empty under an ingest key.

type Installation

type Installation struct {
	ID        int64
	Account   string
	Suspended bool
	// Repositories are the repositories the installation reaches, by id.
	Repositories []Repository
}

Installation is one installation of the GitHub App as the deployment keeps it: ids and names, never a token.

type Line

type Line struct {
	Currency string
	// BillingAccountID is a sender's statement, so a line never adds across it.
	BillingAccountID string
	ServiceCategory  string
	Agent            string
	Model            string
	SkuMeter         string
	ConsumedUnit     string
	CostBasis        string
	CostSource       string
	AttributionGrade string
	RunIdentity      string
	BudgetEligible   bool
	Rows             int64
	// Contested counts the line's rows whose id another run also stated, the
	// ledger verifying both. Each counts here all the same.
	Contested int64
	// Outranked counts the line's rows whose charge a statement the ledger did
	// not verify also held, which gave way to the row and counts nowhere.
	Outranked        int64
	ConsumedQuantity decimal.Decimal
	ListCost         decimal.Decimal
	EffectiveCost    decimal.Decimal
	FirstCharge      time.Time
	LastCharge       time.Time
}

Line is one group of a pull request's rows. Lines never add across currencies or across units.

type LoginBinding

type LoginBinding struct {
	// Key is host:login.
	Key  string
	Pins []Pin
}

LoginBinding is a binding of an owner's login, which a ledger that bound owners by login holds, with each name its tokens pinned to an id.

type LoginHeldError

type LoginHeldError struct {
	// Binding is the login binding, host:login.
	Binding string
	// HeldID is the id the binding holds for the token's name. It is empty
	// when the token's own id is bound to another tenant.
	HeldID string
}

LoginHeldError refuses a token whose login a binding has carried over to another owner's id. Either the login has changed hands, or another owner's token pinned it first.

func (*LoginHeldError) Error

func (e *LoginHeldError) Error() string

type MintedCredential

type MintedCredential struct {
	KeySHA256    string
	Repository   string
	RepositoryID string
	RunID        string
	RunAttempt   string
	HeadSHA      string
	PullRequests PullRequests

	AttestingRunID      string
	AttestingRunAttempt string
	AttestingRef        string
}

MintedCredential is a gateway key that a run of a protected branch attested as minted for another run: the run its rows come from. HeadSHA is the head commit GitHub's event named for that run, and PullRequests the pull requests the event lists for it. The Attesting fields name the run whose token sent the attestation. RepositoryID is the id that token states for the repository, empty on an attestation kept before ids were.

func (MintedCredential) SameRun

func (m MintedCredential) SameRun(other MintedCredential) bool

SameRun reports whether two attestations name one run. The repository is one by its id when both name one, so a run attested before a rename is the same run after it, and by its name otherwise.

type OverrideCount

type OverrideCount struct {
	Failing   int
	Approved  int
	Approvers int
}

OverrideCount is a rule's record over its window. Failing counts the pull requests on which the rule failed, Approved those of them with an approval of a head commit on which it failed, and Approvers the accounts that gave those approvals.

type OverrideQuery

type OverrideQuery struct {
	Repository  Repo
	BaseBranch  string
	PullRequest string
	Rule        string
	Limit       decimal.Decimal
	Rearmed     time.Time
	At          time.Time
}

OverrideQuery names a rule's window: the repository and base branch, the rule and its present limit, the pull request being judged, the time of the verdict, and when the rule was last re-armed. The record is read of the repository as Repo says which.

type OverrideRecord

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

OverrideRecord is the ledger's record of the failing verdicts serve answered and the approvals serve verified. It only grows: it has no method to change or remove a row, and the application role holds no grant to.

func (OverrideRecord) AddApproval

func (r OverrideRecord) AddApproval(ctx context.Context, tenant TenantID, approval PullRequestApproval) error

AddApproval records an approval.

func (OverrideRecord) AddFailure

func (r OverrideRecord) AddFailure(ctx context.Context, tenant TenantID, verdict FailingVerdict) error

AddFailure records a failing verdict.

func (OverrideRecord) Overrides

func (r OverrideRecord) Overrides(ctx context.Context, tenant TenantID, query OverrideQuery) (OverrideCount, error)

Overrides reads a rule's record over its window.

type Owner

type Owner struct {
	// Host is the SCM host.
	Host string
	// ID is the number the token gives the owner, and Name the path it
	// numbers: the login on GitHub, the project's namespace on GitLab.
	ID, Name string
	// Login is the first segment of the repository's path, which a ledger
	// that bound owners by login holds. Empty, the owner is found by its id
	// alone.
	Login string
	// Carry says the command line states the binding of Login, so a token of
	// it may carry that binding over to its id. Without it a binding of the
	// login is never pinned, and its token answers ErrLoginNotStated.
	Carry bool
	// Repository is the token's repository, by its name and its id. A token
	// that finds its tenant keeps that the id carries the name there, so the
	// repository's reads follow its renames. An owner that anything but a
	// verified CI token states, such as a webhook's delivery, names none.
	Repository Repo
}

Owner is the owner of a verified CI token's repository, as the token states it.

type Pin

type Pin struct {
	Name, ID string
	At       time.Time
}

Pin is a name a login binding carried over to the id of its first token.

type PullRequestApproval

type PullRequestApproval struct {
	Repository  string
	PullRequest string
	HeadSHA     string
	Approver    string
	At          time.Time
}

PullRequestApproval is one approval of one head commit of a pull request.

type PullRequests

type PullRequests string

PullRequests is a set of pull request numbers in one form, so that two statements of the same set compare equal: ascending, each once, separated by a space. Empty names none.

func PullRequestsOf

func PullRequestsOf(numbers []string) PullRequests

PullRequestsOf is the set of the numbers given, in any order.

func (PullRequests) Numbers

func (p PullRequests) Numbers() []string

Numbers lists the set, none when it is empty.

type Receipt

type Receipt struct {
	Inserted   int
	Duplicates int
	Contested  int
	Outranked  int
}

Receipt says what a batch changed. Contested counts the verified records whose row id another run's verified statement also holds. Outranked counts the records whose charge, by the row id or by another lifetime of a request's cache writes, a statement of the other rank also holds: the verified one outranks the other. Each counts a record whether it was kept or not.

type Record

type Record struct {
	Row        focus.Row
	RunAttempt string
	// Actor is an SCM login or a per-tenant pseudonym, never an address.
	Actor string
	Event string
	// TokenCommitSHA is the commit the CI token verifies, empty without one.
	TokenCommitSHA string
	// HeadBasis says where costroid/commit_sha came from, empty when the row
	// has none.
	HeadBasis string
	// CredentialBasis says whether SubAccountId is a key attested as minted
	// for the row's run or only stated, empty when the row names no credential.
	CredentialBasis string
	// RequestID is the provider's id for the request the row counts, empty
	// when the sender stated none. It is not stored: it lets a cache write
	// row be matched with the request's write rows of other lifetimes.
	RequestID string
	// RepositoryID is the id the CI token states for the row's repository,
	// empty on a row the ledger did not verify.
	RepositoryID string
}

Record is one row and the facts about its run that have no FOCUS column.

type Repo

type Repo struct {
	Name string
	ID   string
}

Repo is the repository a read is of: Name, its host and path, and ID, the number its host gives it, which a verified CI token states. The id stays with the repository through a rename of it or of its owner, and the name does not.

A read of a Repo with an ID takes every name the id has carried in the tenant, and of what those names hold, every statement that keeps this id or keeps none. A statement that keeps another id is another repository's, one that took a name this repository gave up or gave up a name it took. A Repo without an ID, as an ingest key names one, reads its name alone, whatever ids its statements keep.

type Repository

type Repository struct {
	ID       int64
	FullName string
}

Repository is one repository an installation reaches.

type RuleDemotion

type RuleDemotion struct {
	Repository   string
	RepositoryID string
	BaseBranch   string
	Rule         string
	Limit        decimal.Decimal
	Rearmed      time.Time
	Off          bool
	From         time.Time
	Failing      int
	Approved     int
	Approvers    int
}

RuleDemotion is where one rule's demotion stands at one base branch of a repository: the limit its window counts failures under, when the window last started empty, whether policy.auto_demote was false, and, once a verdict's record crossed the threshold, when and on what counts. From is zero while the rule is armed. RepositoryID is the id the verdict's CI token states for the repository, empty under an ingest key.

type Store

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

Store is the application role's handle on the ledger.

func Open

func Open(ctx context.Context, url string) (*Store, error)

Open connects as the application role and refuses a role that could read past row level security.

func (*Store) AddEgress

func (s *Store) AddEgress(ctx context.Context, counts []egress.Count) error

AddEgress adds to the deployment's egress counters, which belong to no tenant, so no tenant is set.

func (*Store) AddRepositories

func (s *Store) AddRepositories(ctx context.Context, installation int64, account string, repositories []Repository) error

AddRepositories keeps an installation and the repositories it now reaches. An installation event states its account each time, so an installation the table does not hold yet is added, and a renamed account or repository takes its new name. It leaves the installation's suspension as it is. The App's installations belong to the deployment, so no tenant is set.

func (*Store) Attest

func (s *Store) Attest(ctx context.Context, tenant TenantID, minted MintedCredential) error

Attest stores an attestation, and the pull requests it names with it in the same transaction. An attesting run is its repository and run id, in any attempt, because GitHub runs a job again as a later attempt of its run. The same attestation again, every field and the same pull requests, from any attempt of the attesting run that sent it, changes nothing. Any other from that attesting run answers AttestingRunUsed, and any other for a stored key ErrAttestedElsewhere. Where both hold, the attesting run's comes first, because it is about who is speaking.

A unique index holds the key's rule. The attesting run's rule is held by a lock on the attesting run for the transaction, so two attestations that race end the same way. No index can hold it: releases before this one took one attestation from each attempt of an attesting run, so a ledger they wrote can hold two keys attested by two attempts of one run. Each of those is still the same attestation again from any attempt, and no third is taken.

func (*Store) AttestSpend

func (s *Store) AttestSpend(ctx context.Context, tenant TenantID, attested AttestedSpend) error

AttestSpend keeps what the gateway counted on a minted key. The key must be attested as minted for the run named, or the write answers ErrNotMinted. A key holds one figure: the same string again, whichever attesting run and attempt sends it, changes nothing, and any other string answers ErrSpendHeld. An attesting run and attempt writes one figure: its figure for another key that holds none answers ErrAttestingRunUsed. A figure is never replaced, so the larger of two is never kept.

func (*Store) Close

func (s *Store) Close()

Close releases the pool.

func (*Store) DeleteInstallation

func (s *Store) DeleteInstallation(ctx context.Context, installation int64) error

DeleteInstallation forgets an installation and its repositories.

func (*Store) Deliveries

func (s *Store) Deliveries(retention time.Duration) Deliveries

Deliveries returns the delivery ids held for retention after each is taken.

func (*Store) DemotionRecord

func (s *Store) DemotionRecord() DemotionRecord

DemotionRecord returns the ledger's record of where demotions stand.

func (*Store) Egress

func (s *Store) Egress(ctx context.Context) ([]egress.Count, error)

Egress reads the counters, newest day first.

func (*Store) GatewaySpend

func (s *Store) GatewaySpend(ctx context.Context, tenant TenantID, repo Repo, pr string) (rows int64, usd decimal.Decimal, err error)

GatewaySpend reads the pull request's measured spend. usd adds up the spend a protected run attested for every key the pull request's budget-eligible rows name, minted for the row's own run, with credential_basis minted, and for every key an attesting run named the pull request for, whether a row of it arrived or not: each key once. rows counts the eligible rows on the first kind of key, and is 0 while a key of the second kind holds no spend, so a figure that leaves out a run's count stands behind no row. It reads the rows and the attestations of the repository, as Repo says which.

func (*Store) Ingest

func (s *Store) Ingest(ctx context.Context, tenant TenantID, batch Batch) (Receipt, error)

Ingest writes a batch whole or not at all. A record whose owner already stated its row id in this tenant is a duplicate and changes nothing, and so is an unverified record of an id any owner stated. A verified record is never kept out by another owner's statement: both are kept, and the receipt counts the record as contested when the other is a run's, and as outranked when the ledger did not verify the other.

func (*Store) Installation

func (s *Store) Installation(ctx context.Context, installation int64) (Installation, error)

Installation reads one installation and its repositories, ordered by id. An installation the table does not hold is ErrNotFound.

func (*Store) LoginBindings

func (s *Store) LoginBindings(ctx context.Context, tenant TenantID) ([]LoginBinding, error)

LoginBindings reads the tenant's login bindings and their pins, in order.

func (*Store) MintedCredentials

func (s *Store) MintedCredentials(ctx context.Context, tenant TenantID, keys []string) (map[string]MintedCredential, error)

MintedCredentials reads the attestations of the keys named, by key.

func (*Store) OverrideRecord

func (s *Store) OverrideRecord() OverrideRecord

OverrideRecord returns the ledger's override record.

func (*Store) PullRequest

func (s *Store) PullRequest(ctx context.Context, tenant TenantID, repo Repo, pr string) ([]Line, error)

PullRequest derives one pull request's lines from the rows of the repository, as Repo says which.

func (*Store) RemoveRepositories

func (s *Store) RemoveRepositories(ctx context.Context, installation int64, repositories []int64) error

RemoveRepositories forgets repositories an installation no longer reaches.

func (*Store) SuspendInstallation

func (s *Store) SuspendInstallation(ctx context.Context, installation int64, account string, suspended bool) error

SuspendInstallation keeps whether an installation is suspended, and keeps the installation when the table does not hold it yet.

func (*Store) TenantForKey

func (s *Store) TenantForKey(ctx context.Context, keySHA256 string) (TenantID, error)

TenantForKey resolves the SHA-256 of an ingest key to its tenant.

func (*Store) TenantForLogin

func (s *Store) TenantForLogin(ctx context.Context, host, owner string) (TenantID, error)

TenantForLogin resolves a binding of an owner's login, which a ledger that bound owners by login holds, to its tenant. It is read at start, never for a token.

func (*Store) TenantForOwnerID

func (s *Store) TenantForOwnerID(ctx context.Context, owner Owner) (Admission, error)

TenantForOwnerID resolves a token's owner to its tenant by the owner's id. When no binding holds the id and the owner names a login the command line states, a binding of that login, which a ledger that bound owners by login holds, admits the token once: the token pins the binding's name to its id, and from then on only that id matches. A login binding pinned to another id answers *LoginHeldError, one the command line does not state ErrLoginNotStated, and an owner no binding holds ErrNotFound. A token admitted keeps, in the same transaction, that its repository's id carries its repository's name in the tenant. A token refused keeps nothing.

type Tenant

type Tenant struct {
	ID   TenantID
	Name string
	// Bindings are the SCM owners whose CI tokens resolve to this tenant.
	Bindings []Binding
	// KeySHA256 lists the SHA-256 of each ingest key.
	KeySHA256 []string
}

Tenant is one provisioned tenant.

type TenantID

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

TenantID is a validated tenant identifier. It is safe to place in SET LOCAL, which takes no bind parameters.

func NewTenantID

func NewTenantID() (TenantID, error)

NewTenantID mints a random version 4 UUID.

func ParseTenantID

func ParseTenantID(text string) (TenantID, error)

ParseTenantID accepts the canonical lower-case UUID form only.

func Tenants

func Tenants(ctx context.Context, ownerURL string) ([]TenantID, error)

Tenants lists every tenant's id, through the owner role's connection, which alone may read them all.

func (TenantID) String

func (t TenantID) String() string

String returns the canonical form.

Directories

Path Synopsis
Package storetest runs Postgres in Docker for the packages that need it.
Package storetest runs Postgres in Docker for the packages that need it.

Jump to

Keyboard shortcuts

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