store

package
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package store owns Postgres connectivity and schema migration.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ChecksEntityKey

func ChecksEntityKey(
	installationID int64,
	repositoryGitHubID int64,
	sha string,
) string

ChecksEntityKey returns the normative lock and change-stream key for a head SHA's check runs.

func Connect

func Connect(
	ctx context.Context,
	databaseURL string,
	options ...ConnectOption,
) (*pgxpool.Pool, error)

Connect opens and verifies a Postgres pool with the cache durability invariants enabled.

func Migrate

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

Migrate applies River's migrations followed by our own plain-SQL files, in lexical order, tracked in schema_migrations. Each of our migrations runs in its own transaction and is applied at most once.

func PullRequestEntityKey

func PullRequestEntityKey(
	installationID int64,
	repositoryGitHubID int64,
	number int,
) string

PullRequestEntityKey returns the normative lock, scope, and change-stream key for a pull request.

func RepoRulesEntityKey

func RepoRulesEntityKey(
	installationID int64,
	repositoryGitHubID int64,
) string

RepoRulesEntityKey returns the normative lock and change-stream key for repository rules.

func RepositoryDiscoveryKey

func RepositoryDiscoveryKey(installationID int64, fullName string) string

RepositoryDiscoveryKey returns the normative lock key for repository discovery by full name.

func RepositoryEntityKey

func RepositoryEntityKey(installationID, repositoryGitHubID int64) string

RepositoryEntityKey returns the normative lock and change-stream key for a repository.

func StackEntityKey

func StackEntityKey(
	installationID int64,
	repositoryGitHubID int64,
	number int,
) string

StackEntityKey returns the normative lock, scope, and change-stream key for a stack.

Types

type ApplyPullRequestResult

type ApplyPullRequestResult struct {
	Applied               bool
	DomainChanged         bool
	ReviewRequestsChanged bool
	ReviewsChanged        bool
	CommentsChanged       bool
	ChangeInputsChanged   bool
	StackStateChanged     bool
	OldStackNumber        *int
	NewStackNumber        *int
	OldHeadSHA            string
	NewHeadSHA            string
}

ApplyPullRequestResult describes the accepted pull-request transition.

type ApplyStackResult

type ApplyStackResult struct {
	Applied        bool
	JoinedPRs      []int
	LeftPRs        []int
	MovedPRs       []int
	PriorStackByPR map[int]int
}

ApplyStackResult describes stack membership changes caused by a write.

type CacheObserver

type CacheObserver interface {
	CacheWrite(context.Context, string, bool, bool)
}

CacheObserver is M6's C-C2 compare-and-swap accounting seam.

type ChangedFileRecord added in v0.3.0

type ChangedFileRecord struct {
	Path         string
	PreviousPath string
	ChangeType   string
}

ChangedFileRecord is one member of the bounded current PR diff snapshot.

type CheckRunRecord

type CheckRunRecord struct {
	GitHubID        int64           `json:"gh_id"`
	NodeID          string          `json:"node_id"`
	Name            string          `json:"name"`
	Status          string          `json:"status"`
	Conclusion      string          `json:"conclusion"`
	DetailsURL      string          `json:"details_url"`
	AppSlug         string          `json:"app_slug"`
	StartedAt       *time.Time      `json:"started_at"`
	CompletedAt     *time.Time      `json:"completed_at"`
	GitHubUpdatedAt *time.Time      `json:"gh_updated_at"`
	SemanticVersion string          `json:"semantic_version"`
	Observed        json.RawMessage `json:"observed"`
}

CheckRunRecord is one check run in an authoritative head-SHA snapshot.

type ChecksRecord

type ChecksRecord struct {
	Repository RepositoryRecord
	HeadSHA    string
	Runs       []CheckRunRecord
	ETag       string
	SyncedAt   time.Time
	Source     SyncSource
}

ChecksRecord is the authoritative check-run set for one repository head SHA.

type ConnectOption

type ConnectOption func(*connectOptions)

ConnectOption customizes Postgres connectivity.

func WithRDSIAMAuthentication added in v0.2.0

func WithRDSIAMAuthentication() ConnectOption

WithRDSIAMAuthentication generates a fresh Amazon RDS IAM authentication token for every new physical pool connection. DATABASE_URL must not contain a password when this option is used.

func WithTracerProvider

func WithTracerProvider(provider trace.TracerProvider) ConnectOption

WithTracerProvider instruments pgx operations with the supplied provider.

type EntityWriter

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

EntityWriter owns C-C1..C-C6. Network fetches never enter this package.

func NewEntityWriter

func NewEntityWriter(
	pool *pgxpool.Pool,
	observers ...CacheObserver,
) *EntityWriter

NewEntityWriter constructs a cache writer backed by pool.

func (*EntityWriter) ApplyChecksObserved

func (w *EntityWriter) ApplyChecksObserved(
	ctx context.Context,
	observation *Observation,
	checks ChecksRecord,
) (bool, error)

ApplyChecksObserved conditionally replaces a head SHA's check runs while holding its observation lock.

func (*EntityWriter) ApplyPullRequest

func (w *EntityWriter) ApplyPullRequest(
	ctx context.Context,
	pull PullRequestRecord,
) (ApplyPullRequestResult, error)

ApplyPullRequest conditionally applies a direct pull-request observation.

func (*EntityWriter) ApplyPullRequestBatch

func (w *EntityWriter) ApplyPullRequestBatch(
	ctx context.Context,
	applies []PullRequestApply,
) map[string]PullRequestApplyOutcome

ApplyPullRequestBatch preserves independent outcomes. Transport errors are handled by the caller; one poisoned entity never discards healthy siblings.

func (*EntityWriter) ApplyPullRequestObserved

func (w *EntityWriter) ApplyPullRequestObserved(
	ctx context.Context,
	observation *Observation,
	pull PullRequestRecord,
	hook PullRequestHook,
) (ApplyPullRequestResult, error)

ApplyPullRequestObserved conditionally applies a pull request while holding its observation lock.

func (*EntityWriter) ApplyRepoRulesObserved

func (w *EntityWriter) ApplyRepoRulesObserved(
	ctx context.Context,
	observation *Observation,
	rules RepoRulesRecord,
) (bool, error)

ApplyRepoRulesObserved conditionally replaces repository rules while holding the repository-rules observation lock.

func (*EntityWriter) ApplyRepository

func (w *EntityWriter) ApplyRepository(
	ctx context.Context,
	repository RepositoryRecord,
	source SyncSource,
	etag string,
	observedAt time.Time,
) (bool, error)

ApplyRepository conditionally applies a direct repository observation.

func (*EntityWriter) ApplyRepositoryObserved

func (w *EntityWriter) ApplyRepositoryObserved(
	ctx context.Context,
	observation *Observation,
	repository RepositoryRecord,
	source SyncSource,
	etag string,
	observedAt time.Time,
) (bool, error)

ApplyRepositoryObserved conditionally applies a repository while holding its observation lock.

func (*EntityWriter) ApplyStack

func (w *EntityWriter) ApplyStack(
	ctx context.Context,
	stack StackRecord,
) (ApplyStackResult, error)

ApplyStack conditionally applies a direct stack observation.

func (*EntityWriter) ApplyStackObserved

func (w *EntityWriter) ApplyStackObserved(
	ctx context.Context,
	observation *Observation,
	stack StackRecord,
	hook StackHook,
) (ApplyStackResult, error)

ApplyStackObserved conditionally applies a stack while holding its observation lock.

func (*EntityWriter) BeginObservation

func (w *EntityWriter) BeginObservation(
	ctx context.Context,
	entityKey string,
) (*Observation, error)

BeginObservation acquires C-C1's dedicated session-level advisory lock for entityKey. See C-C6 before extending its lifetime or nesting observations.

func (*EntityWriter) BranchTargets

func (w *EntityWriter) BranchTargets(
	ctx context.Context,
	repoFullName string,
	branch string,
) ([]string, error)

BranchTargets returns the derivation scopes affected by a branch change.

func (*EntityWriter) ChecksMetadata

func (w *EntityWriter) ChecksMetadata(
	ctx context.Context,
	repo string,
	headSHA string,
) (FetchMetadata, error)

ChecksMetadata returns conditional-fetch metadata for one head SHA.

func (*EntityWriter) PullRequestMetadata

func (w *EntityWriter) PullRequestMetadata(
	ctx context.Context,
	repo string,
	number int,
) (FetchMetadata, error)

PullRequestMetadata returns conditional-fetch metadata for one pull request.

func (*EntityWriter) RepoRulesMetadata

func (w *EntityWriter) RepoRulesMetadata(
	ctx context.Context,
	repo string,
) (FetchMetadata, int64, error)

RepoRulesMetadata returns conditional-fetch metadata for repository rules.

func (*EntityWriter) Repository

func (w *EntityWriter) Repository(
	ctx context.Context,
	fullName string,
) (RepositoryRecord, error)

Repository resolves a current repository record by full name or alias.

func (*EntityWriter) ResolveFileOwnerIdentities added in v0.3.0

func (w *EntityWriter) ResolveFileOwnerIdentities(
	ctx context.Context,
	repoGitHubID int64,
	repositoryOwner string,
	owners []FileOwnerRecord,
) ([]FileOwnerRecord, error)

ResolveFileOwnerIdentities fills stable identities from facts already mirrored for this repository. It never performs a live GitHub lookup and leaves unknown users, teams, email owners, and malformed tokens explicit.

func (*EntityWriter) StackMetadata

func (w *EntityWriter) StackMetadata(
	ctx context.Context,
	repo string,
	number int,
) (FetchMetadata, error)

StackMetadata returns conditional-fetch metadata for one stack.

func (*EntityWriter) TombstonePullRequestObserved

func (w *EntityWriter) TombstonePullRequestObserved(
	ctx context.Context,
	observation *Observation,
	repository RepositoryRecord,
	number int,
	source SyncSource,
	at time.Time,
	hook PullRequestHook,
) (ApplyPullRequestResult, error)

TombstonePullRequestObserved conditionally tombstones a pull request while holding its observation lock.

func (*EntityWriter) TombstoneRepositoryObserved

func (w *EntityWriter) TombstoneRepositoryObserved(
	ctx context.Context,
	observation *Observation,
	repository RepositoryRecord,
	source SyncSource,
	at time.Time,
) (bool, error)

TombstoneRepositoryObserved applies C-R3's verified repository disappearance through the same lock/dirty/outbox transaction as every other authoritative cache mutation. Child mirrors remain retained history; live readers and future sweeps exclude them through the repository tombstone.

func (*EntityWriter) TombstoneStackObserved

func (w *EntityWriter) TombstoneStackObserved(
	ctx context.Context,
	observation *Observation,
	repository RepositoryRecord,
	number int,
	source SyncSource,
	at time.Time,
	hook StackHook,
) (ApplyStackResult, error)

TombstoneStackObserved conditionally tombstones a stack while holding its observation lock.

func (*EntityWriter) TouchChecks

func (w *EntityWriter) TouchChecks(
	ctx context.Context,
	observation *Observation,
	repository RepositoryRecord,
	headSHA string,
	checkedAt time.Time,
	etag string,
) error

TouchChecks records a successful unchanged check-runs observation.

func (*EntityWriter) TouchPullRequest

func (w *EntityWriter) TouchPullRequest(
	ctx context.Context,
	observation *Observation,
	repository RepositoryRecord,
	number int,
	checkedAt time.Time,
	etag string,
) error

TouchPullRequest records a successful unchanged pull-request observation.

func (*EntityWriter) TouchRepoRules

func (w *EntityWriter) TouchRepoRules(
	ctx context.Context,
	observation *Observation,
	repository RepositoryRecord,
	checkedAt time.Time,
	etag string,
) error

TouchRepoRules records a successful unchanged repository-rules observation.

func (*EntityWriter) TouchStack

func (w *EntityWriter) TouchStack(
	ctx context.Context,
	observation *Observation,
	repository RepositoryRecord,
	number int,
	checkedAt time.Time,
	etag string,
) error

TouchStack records a successful unchanged stack observation.

type FetchMetadata

type FetchMetadata struct {
	NodeID         string
	ETag           string
	StackNumber    *int
	StackPosition  *int
	HeadSHA        string
	RepoGitHubID   int64
	InstallationID int64
	RepoFullName   string
}

FetchMetadata is the cache metadata needed for a conditional GitHub fetch.

type FileOwnerRecord added in v0.3.0

type FileOwnerRecord struct {
	Path            string
	OwnerToken      string
	OwnerType       string
	OwnerName       string
	ResolutionState string
	OwnerGitHubID   int64
	OwnerNodeID     string
	OwnerLogin      string
	SourcePattern   string
	SourceLine      int
}

FileOwnerRecord is one CODEOWNERS token selected by the last matching rule for a changed path. OwnerType is syntactic; ResolutionState distinguishes a stable identity from an unresolved or explicitly deleted identity.

type Observation

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

Observation owns C-C1's narrowly allowed C-C6 exception: a session-level advisory lock on one dedicated connection, held across one entity's GitHub fetch and write. No transaction is open during the network call, and shared repository metadata locks must use a shorter post-fetch scope.

func (*Observation) Close

func (o *Observation) Close() error

Close releases the observation's advisory lock and dedicated connection.

func (*Observation) CloseContext

func (o *Observation) CloseContext(ctx context.Context) error

CloseContext releases the observation using a bounded cleanup context derived from ctx while remaining usable after caller cancellation.

func (*Observation) Key

func (o *Observation) Key() string

Key returns the entity key protected by the observation.

type PullRequestApply

type PullRequestApply struct {
	Context     context.Context //nolint:containedctx // each batched item retains its independent cancellation and values
	Record      PullRequestRecord
	Observation *Observation
	Hook        PullRequestHook
}

PullRequestApply describes one independently handled batch write.

type PullRequestApplyOutcome

type PullRequestApplyOutcome struct {
	Result ApplyPullRequestResult
	Err    error
}

PullRequestApplyOutcome captures one batch write's result and error.

type PullRequestChangeSnapshotRecord added in v0.3.0

type PullRequestChangeSnapshotRecord struct {
	BaseSHA          string
	HeadSHA          string
	FilesTotalCount  int
	FilesTruncated   bool
	CodeownersRef    string
	CodeownersSHA    string
	CodeownersPath   string
	CodeownersState  string
	CodeownersSource string
	CodeownersHash   string
	Files            []ChangedFileRecord
	Owners           []FileOwnerRecord
}

PullRequestChangeSnapshotRecord fences changed files and resolved ownership by the exact base/head pair returned in one PR observation.

type PullRequestCommentRecord added in v0.3.0

type PullRequestCommentRecord struct {
	GitHubID        int64
	NodeID          string
	AuthorKind      string
	AuthorNodeID    string
	AuthorLogin     string
	CreatedAt       time.Time
	GitHubUpdatedAt time.Time
}

PullRequestCommentRecord is one identity-keyed ordinary issue comment on a pull request. Bodies are deliberately absent from the public fact record.

type PullRequestHook

type PullRequestHook func(ApplyPullRequestResult) TransactionHook

PullRequestHook derives transaction work from a pull-request write result.

type PullRequestRecord

type PullRequestRecord struct {
	Repository          RepositoryRecord
	GitHubID            int64
	NodeID              string
	Number              int
	Title               string
	State               string
	Draft               bool
	AuthorLogin         string
	HeadRef             string
	HeadSHA             string
	BaseRef             string
	BaseSHA             string
	ReviewDecision      string
	MergeableState      string
	StackNumber         *int
	StackPosition       *int
	StackSummary        *StackSummaryRecord
	MembershipKnown     bool
	GitHubUpdatedAt     time.Time
	ReviewThreads       []ReviewThreadRecord
	ThreadsKnown        bool
	ReviewRequests      []ReviewRequestRecord
	ReviewRequestsKnown bool
	Reviews             []PullRequestReviewRecord
	ReviewsKnown        bool
	Comments            []PullRequestCommentRecord
	CommentsKnown       bool
	ChangeSnapshot      *PullRequestChangeSnapshotRecord
	ChangeInputsKnown   bool
	ETag                string
	SyncedAt            time.Time
	Source              SyncSource
}

PullRequestRecord is the authoritative pull-request state accepted by the cache.

type PullRequestReviewRecord added in v0.3.0

type PullRequestReviewRecord struct {
	GitHubID        int64
	NodeID          string
	AuthorKind      string
	AuthorNodeID    string
	AuthorLogin     string
	State           string
	SubmittedAt     *time.Time
	CommitOID       string
	GitHubUpdatedAt time.Time
}

PullRequestReviewRecord is one identity-keyed GitHub pull-request review. Lifecycle state plus SubmittedAt and GitHubUpdatedAt form the per-row monotonic basis; a dismissed review remains present with State set to "dismissed".

type RepoRuleRecord

type RepoRuleRecord struct {
	Key             string          `json:"rule_key"`
	Rule            json.RawMessage `json:"rule"`
	GitHubUpdatedAt *time.Time      `json:"gh_updated_at"`
	HeadSHA         string          `json:"head_sha"`
}

RepoRuleRecord is one normalized repository rule.

type RepoRulesRecord

type RepoRulesRecord struct {
	Repository RepositoryRecord
	Rules      []RepoRuleRecord
	ETag       string
	SyncedAt   time.Time
	Source     SyncSource
}

RepoRulesRecord is the authoritative repository-rules snapshot.

type RepositoryRecord

type RepositoryRecord struct {
	InstallationID  int64
	OrgID           int64
	GitHubID        int64
	NodeID          string
	Owner           string
	Name            string
	FullName        string
	DefaultBranch   string
	DefaultHeadSHA  string
	Archived        bool
	GitHubUpdatedAt time.Time
	ETag            string
	LastCheckedAt   time.Time
}

RepositoryRecord is the validated repository state accepted by the cache.

type ReviewCommentRecord

type ReviewCommentRecord struct {
	ID          string    `json:"id"`
	Body        string    `json:"body"`
	UpdatedAt   time.Time `json:"updated_at"`
	AuthorLogin string    `json:"author_login"`
}

ReviewCommentRecord is one review comment embedded in a review thread.

type ReviewRequestKind added in v0.3.0

type ReviewRequestKind string

ReviewRequestKind distinguishes GitHub user and team review requests.

const (
	ReviewRequestUser ReviewRequestKind = "user"
	ReviewRequestTeam ReviewRequestKind = "team"
)

type ReviewRequestRecord added in v0.3.0

type ReviewRequestRecord struct {
	Kind        ReviewRequestKind
	GitHubID    int64
	NodeID      string
	Login       string
	RequestedAt *time.Time
}

ReviewRequestRecord is one member of GitHub's authoritative current pull-request reviewRequests set. RequestedAt is nil when GitHub does not expose an authoritative request timestamp.

type ReviewThreadRecord

type ReviewThreadRecord struct {
	ID              string
	IsResolved      bool
	IsOutdated      bool
	Path            string
	Line            *int
	Comments        []ReviewCommentRecord
	GitHubUpdatedAt time.Time
}

ReviewThreadRecord is one authoritative pull-request review thread.

type StackEntry

type StackEntry struct {
	Number    int        `json:"number"`
	State     string     `json:"state"`
	Draft     bool       `json:"draft"`
	MergedAt  *time.Time `json:"merged_at,omitempty"`
	UpdatedAt time.Time  `json:"updated_at"`
	HeadRef   string     `json:"head_ref"`
	HeadSHA   string     `json:"head_sha"`
}

StackEntry is one ordered pull request in a stack snapshot.

type StackHook

type StackHook func(ApplyStackResult) TransactionHook

StackHook derives transaction work from a stack write result.

type StackRecord

type StackRecord struct {
	Repository      RepositoryRecord
	GitHubID        int64
	NodeID          string
	Number          int
	BaseRef         string
	BaseSHA         string
	Open            bool
	Entries         []StackEntry
	GitHubUpdatedAt time.Time
	ETag            string
	SyncedAt        time.Time
	Source          SyncSource
}

StackRecord is the authoritative stack state accepted by the cache. BaseSHA is empty when GitHub reports the base ref without a resolvable commit. This is authoritative upstream truth, including for open stacks.

type StackSummaryRecord

type StackSummaryRecord struct {
	GitHubID int64
	Number   int
	Size     int
	Position int
	BaseRef  string
	BaseSHA  string
}

StackSummaryRecord is the stack tuple embedded in an authoritative pull-request response. BaseSHA is empty when GitHub reports the stack base ref but can no longer resolve its commit, including historical stacks whose base branch was deleted.

type SyncSource

type SyncSource string

SyncSource identifies the workflow that supplied an authoritative cache observation.

const (
	// SyncSourceWebhook identifies observations triggered by GitHub webhooks.
	SyncSourceWebhook SyncSource = "webhook"
	// SyncSourceReconcile identifies observations from reconciliation work.
	SyncSourceReconcile SyncSource = "reconcile"
	// SyncSourceBackfill identifies observations from historical backfills.
	SyncSourceBackfill SyncSource = "backfill"
	// SyncSourceManual identifies operator-requested observations.
	SyncSourceManual SyncSource = "manual"
	// SyncSourceInteractive identifies user-blocking interactive refreshes.
	SyncSourceInteractive SyncSource = "interactive"
)

func (SyncSource) Valid

func (s SyncSource) Valid() bool

Valid reports whether s is a supported cache observation source.

type TransactionHook

type TransactionHook func(context.Context, pgx.Tx) error

TransactionHook runs after the accepted cache mutation, dirty marking, and event insert but before commit. Fetch workers use it for durable generation bumps and River follow-ups (C-C3). C-C6 forbids network I/O in this callback.

Directories

Path Synopsis
Package rdsiam generates short-lived Amazon RDS IAM database auth tokens.
Package rdsiam generates short-lived Amazon RDS IAM database auth tokens.

Jump to

Keyboard shortcuts

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