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
- Variables
- func AddKey(ctx context.Context, ownerURL string, owner Binding, digest string) error
- func Address(url string) string
- func Bind(ctx context.Context, ownerURL string, tenant TenantID, bindings []Binding) error
- func BindingKey(host, id string) string
- func KeyDigest(key string) string
- func LoginKey(host, owner string) string
- func Migrate(ctx context.Context, ownerURL string) error
- func MigrateFrom(ctx context.Context, ownerURL string, files fs.FS) error
- func NewKey() (string, error)
- func NotAnswering(err error) bool
- func Provision(ctx context.Context, ownerURL string, tenant Tenant) error
- func RevokeKey(ctx context.Context, ownerURL, digest string) error
- type Admission
- type AttestedSpend
- type Batch
- type Binding
- type Deliveries
- type DemotionRecord
- type FailingVerdict
- type Installation
- type Line
- type LoginBinding
- type LoginHeldError
- type MintedCredential
- type OverrideCount
- type OverrideQuery
- type OverrideRecord
- func (r OverrideRecord) AddApproval(ctx context.Context, tenant TenantID, approval PullRequestApproval) error
- func (r OverrideRecord) AddFailure(ctx context.Context, tenant TenantID, verdict FailingVerdict) error
- func (r OverrideRecord) Overrides(ctx context.Context, tenant TenantID, query OverrideQuery) (OverrideCount, error)
- type Owner
- type Pin
- type PullRequestApproval
- type PullRequests
- type Receipt
- type Record
- type Repository
- type RuleDemotion
- type Store
- func (s *Store) AddEgress(ctx context.Context, counts []egress.Count) error
- func (s *Store) AddRepositories(ctx context.Context, installation int64, account string, ...) error
- func (s *Store) Attest(ctx context.Context, tenant TenantID, minted MintedCredential) error
- func (s *Store) AttestSpend(ctx context.Context, tenant TenantID, attested AttestedSpend) error
- func (s *Store) Close()
- func (s *Store) DeleteInstallation(ctx context.Context, installation int64) error
- func (s *Store) Deliveries(retention time.Duration) Deliveries
- func (s *Store) DemotionRecord() DemotionRecord
- func (s *Store) Egress(ctx context.Context) ([]egress.Count, error)
- func (s *Store) GatewaySpend(ctx context.Context, tenant TenantID, repo, pr string) (rows int64, usd decimal.Decimal, err error)
- func (s *Store) Ingest(ctx context.Context, tenant TenantID, batch Batch) (Receipt, error)
- func (s *Store) Installation(ctx context.Context, installation int64) (Installation, error)
- func (s *Store) LoginBindings(ctx context.Context, tenant TenantID) ([]LoginBinding, error)
- func (s *Store) MintedCredentials(ctx context.Context, tenant TenantID, keys []string) (map[string]MintedCredential, error)
- func (s *Store) OverrideRecord() OverrideRecord
- func (s *Store) PullRequest(ctx context.Context, tenant TenantID, repo, pr string) ([]Line, error)
- func (s *Store) RemoveRepositories(ctx context.Context, installation int64, repositories []int64) error
- func (s *Store) SuspendInstallation(ctx context.Context, installation int64, account string, suspended bool) error
- func (s *Store) TenantForKey(ctx context.Context, keySHA256 string) (TenantID, error)
- func (s *Store) TenantForLogin(ctx context.Context, host, owner string) (TenantID, error)
- func (s *Store) TenantForOwnerID(ctx context.Context, owner Owner) (Admission, error)
- type Tenant
- type TenantID
Constants ¶
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.
const ( HeadFromToken = "token" HeadStated = "stated" )
Values of HeadBasis.
const ( CredentialMinted = "minted" CredentialStated = "stated" )
Values of CredentialBasis.
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.
const KeyPrefix = "costroid_ik_"
KeyPrefix starts every ingest key. A bearer without it is a CI token.
Variables ¶
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 and attempt already // attested another key, or the same key otherwise. ErrAttestingRunUsed = errors.New("store: the attesting run has attested already") )
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") )
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.
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.
var ErrMigrationEdited = errors.New("store: an applied migration was edited")
ErrMigrationEdited means a migration already applied has changed on disk.
var ErrNotFound = errors.New("store: not found")
ErrNotFound means a lookup named nothing.
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 ¶
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 ¶
Address names the role, the host and the database a connection string connects to, and never its password.
func Bind ¶
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 ¶
BindingKey is the key a binding of an owner's id is stored under: the host, '#' and the id.
func MigrateFrom ¶
MigrateFrom applies the migrations in files, each in its own transaction.
func NewKey ¶
NewKey mints an ingest key. Only its digest is ever stored, so a key that is lost is revoked and replaced.
func NotAnswering ¶
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.
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 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 ¶
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.
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, branch, rule string) (RuleDemotion, bool, error)
Demotion reads where a rule's demotion stands at a base branch, 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
// 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.
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 ¶
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
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.
func (MintedCredential) SameRun ¶
func (m MintedCredential) SameRun(other MintedCredential) bool
SameRun reports whether two attestations name one run.
type OverrideCount ¶
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 string
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.
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
}
Owner is the owner of a verified CI token's repository, as the token states it.
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 ¶
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
}
Record is one row and the facts about its run that have no FOCUS column.
type Repository ¶
Repository is one repository an installation reaches.
type RuleDemotion ¶
type RuleDemotion struct {
Repository 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.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the application role's handle on the ledger.
func Open ¶
Open connects as the application role and refuses a role that could read past row level security.
func (*Store) AddEgress ¶
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 ¶
Attest stores an attestation, and the pull requests it names with it in the same transaction. The same attestation again, every field and the same pull requests, changes nothing. Any other from the same attesting run and attempt answers ErrAttestingRunUsed, 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 each rule, so two attestations that race end the same way.
func (*Store) AttestSpend ¶
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) DeleteInstallation ¶
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) GatewaySpend ¶
func (s *Store) GatewaySpend(ctx context.Context, tenant TenantID, 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.
func (*Store) Ingest ¶
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 ¶
Installation reads one installation and its repositories, ordered by id. An installation the table does not hold is ErrNotFound.
func (*Store) LoginBindings ¶
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 ¶
PullRequest derives one pull request's lines from the rows.
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 ¶
TenantForKey resolves the SHA-256 of an ingest key to its tenant.
func (*Store) TenantForLogin ¶
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 ¶
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.
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 ParseTenantID ¶
ParseTenantID accepts the canonical lower-case UUID form only.