database

package
v0.25.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: AGPL-3.0 Imports: 44 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

Index

Constants

View Source
const (
	// BlobReplicationCopy makes the blob exist on the replica.
	BlobReplicationCopy = "copy"
	// BlobReplicationDelete makes the blob disappear from the replica.
	BlobReplicationDelete = "delete"
)

Operations of the blob replication queue (see BlobReplicationStore).

View Source
const (
	// BlobDeletionScopeAll deletes every copy of the blob, on every tier: the
	// blob itself was deleted.
	BlobDeletionScopeAll = "*"
	// BlobDeletionScopePrimary deletes the copy on the primary (default) store.
	BlobDeletionScopePrimary = ""
)

Scopes of a queued blob deletion (BlobDeletion.Scope). Any other value is the storage_backends id of the tier whose copy a placement flip retired.

View Source
const BlobBatchLockChunk = 100

BlobBatchLockChunk bounds how many blob advisory locks one batched delete holds in its transaction. A DeleteBlobsIfUnreferenced call of at most this many blobs is a single transaction, which commits or removes nothing.

View Source
const (
	// DefaultDownloadCountFlushInterval is how often batched download counts are
	// written when the configuration does not say.
	DefaultDownloadCountFlushInterval = 5 * time.Second
)
View Source
const (
	FileRolePrimary = "primary"
)

Roles of a package_files row. Only a primary file counts as an artifact for quota and listing statistics.

View Source
const PackageRestoreBatch = 500

PackageRestoreBatch is the most rows one RestorePackageRows call takes.

Variables

View Source
var (
	// ErrGPGKeyNotFound is returned when a GPG key does not exist.
	ErrGPGKeyNotFound = errors.New("GPG key not found")
	// ErrGPGKeyExists is returned when a key with the same name or fingerprint is already stored.
	ErrGPGKeyExists = errors.New("GPG key already exists")
)
View Source
var (
	ErrSBOMReportNotFound    = errors.New("SBOM report not found")
	ErrLicensePolicyNotFound = errors.New("license policy not found")
)
View Source
var (
	// ErrVulnScanNotFound is returned when a vuln scan result does not exist in the repository.
	ErrVulnScanNotFound = errors.New("vuln scan result not found")

	// ErrSecretScanNotFound is returned when a secret scan result does not exist in the repository.
	ErrSecretScanNotFound = errors.New("secret scan result not found")

	// ErrBundleNotDraft is returned when a bundle mutation requires the draft state.
	ErrBundleNotDraft = errors.New("release bundle is not in draft state")

	// ErrBundleNotFound is returned when a release bundle does not exist.
	ErrBundleNotFound = errors.New("release bundle not found")
)
View Source
var (
	// ErrProjectTokenLimit: the project already has the maximum of active tokens.
	ErrProjectTokenLimit = errors.New("project token limit reached")
	// ErrProjectTokenName: an active token of the project already has the name.
	ErrProjectTokenName = errors.New("project token name already in use")
)

Errors of project token creation.

View Source
var (
	// ErrProjectNotFound: the project does not exist (any more).
	ErrProjectNotFound = errors.New("project not found")
	// ErrProjectOwnerLocked: the project's recorded owner can be neither
	// demoted nor removed.
	ErrProjectOwnerLocked = errors.New("the project owner cannot be demoted or removed")
	// ErrLastProjectOwner: the change would leave the project without an owner.
	ErrLastProjectOwner = errors.New("cannot remove or demote the last owner")
)

Errors of the locked project member/group changes.

View Source
var (
	// ErrTrashNotFound means no trashed row matches the kind/id (it was never
	// deleted, was already restored, or was purged).
	ErrTrashNotFound = errors.New("trash item not found")
	// ErrAmbiguousPyPIFilename means several packages of one repository hold a
	// file with the same name.
	ErrAmbiguousPyPIFilename = errors.New("pypi filename is ambiguous")
	// ErrTrashConflict means a restore collided with a live row that took over
	// the item's unique key while it sat in the trash.
	ErrTrashConflict = errors.New("a live item with the same identity already exists")
	// ErrTrashRepoTrashed means the item's repository is itself in the trash.
	ErrTrashRepoTrashed = errors.New("the item's repository is in the trash")
	// ErrTrashManifestInTrash means a docker tag cannot be restored because the
	// manifest it points at is itself in the trash (restore the manifest, which
	// brings its tags back).
	ErrTrashManifestInTrash = errors.New("the tag's manifest is in the trash")
	// ErrTrashUnknownKind means the kind is not a registered trash kind.
	ErrTrashUnknownKind = errors.New("unknown trash kind")
)
View Source
var (
	// ErrVEXFeedNotFound is returned when a VEX feed does not exist.
	ErrVEXFeedNotFound = errors.New("VEX feed not found")
	// ErrVEXFeedConflict is returned when another VEX feed has the name.
	ErrVEXFeedConflict = errors.New("VEX feed name already exists")
)
View Source
var ErrBlobLockLost = errors.New("blob lock lost while its holder ran")

ErrBlobLockLost is returned by WithBlobLocks when fn returned nil but the lock transaction could not be committed: its session ended while fn ran (connection loss, a failover, pg_terminate_backend), which releases the advisory locks, so fn may have run without the exclusion it relied on.

View Source
var ErrChecksumDrift = errors.New("checksum drift")
View Source
var ErrCurationRuleLimit = errors.New("repository has the maximum number of curation rules")

ErrCurationRuleLimit is returned by CreateCurationRule when the repository already holds curation.MaxRules rules.

View Source
var ErrCurationRuleNotFound = errors.New("curation rule not found")

ErrCurationRuleNotFound is returned when a rule does not exist in the repository.

View Source
var ErrDockerBlobsMissing = errors.New("manifest references a blob that is not available to the image")

ErrDockerBlobsMissing is returned by CreateDockerManifest when a blob the manifest requires is not (or no longer) available to its image.

View Source
var ErrDockerRowNotFound = errors.New("docker row not found")

ErrDockerRowNotFound is returned by DeleteDockerBlobFromImage and DeleteDockerManifest when no row matched: a concurrent request removed it first. Callers release the row's storage quota only when the delete removed it.

View Source
var ErrDuplicate = errors.New("artifact already exists")

ErrDuplicate is returned by Create*Package when an insert hits the unique constraint (ON CONFLICT), so callers can distinguish an idempotent duplicate upload (map to HTTP 409) from a real failure. This closes the check-then-insert TOCTOU: concurrent identical uploads race the existence check, but exactly one INSERT wins and the losers observe ErrDuplicate.

View Source
var ErrInvalidAuditLimit = errors.New("audit page limit must be positive")

ErrInvalidAuditLimit is returned by ListAuditLogs for a page size below 1.

View Source
var ErrInvalidBlobSHA256 = errors.New("invalid blob sha256: must be 64 lowercase hex characters")

ErrInvalidBlobSHA256 is returned when a blob row would be keyed by anything other than a lowercase 64-character hex SHA-256. blobs.sha256 is UNIQUE and every upsert resolves conflicts on it, so a single malformed value (the empty string in particular) would make unrelated artifacts share one row and serve each other's bytes.

View Source
var ErrInvalidConnOption = errors.New("invalid database option key")

ErrInvalidConnOption is returned when a database option key is not a valid PostgreSQL runtime parameter name.

View Source
var ErrInvalidFindingFilter = errors.New("invalid security finding filter")

ErrInvalidFindingFilter is returned by ListSecurityFindings for a type, severity or status it does not know, and for a page size below 1.

View Source
var ErrInvalidVulnScanFilter = errors.New("invalid vulnerability scan filter")

ErrInvalidVulnScanFilter is returned by ListVulnScanOverview for a severity, status, scanner, sort or priority it does not know, and for a page size below 1.

View Source
var ErrLastAdmin = errors.New("cannot remove the last enabled admin")

ErrLastAdmin is returned when a change would leave no enabled admin: deleting or disabling the last admin user, or removing its admin-all assignment.

View Source
var ErrLegacySchema = errors.New("database predates the 0.15 schema baseline")

ErrLegacySchema reports a database created by a release before 0.15, which squashed its migrations into baselineVersion. Such a database is never migrated in place; its data moves with `oa import`.

View Source
var ErrLicenseScanNotFound = errors.New("license scan result not found")

ErrLicenseScanNotFound is returned when a license scan result does not exist in the repository.

View Source
var (
	// ErrPackageRowSet reports a row set that names no valid table.
	ErrPackageRowSet = errors.New("invalid package row set")
)
View Source
var ErrPresignedUploadCap = errors.New("too many pending presigned uploads")

ErrPresignedUploadCap is returned by CreatePresignedUploadCapped when the user already has the maximum number of outstanding uploads.

View Source
var ErrProjectQuotaExceeded = errors.New("project storage quota would be exceeded")

ErrProjectQuotaExceeded is returned when moving a repository would push the target project past its storage ceiling.

View Source
var ErrProjectRepoLimit = errors.New("project repository limit reached")

ErrProjectRepoLimit is returned when creating or moving a repository would exceed the project's max_repositories.

View Source
var ErrRawPathForeign = errors.New("raw path is held by a file of another format")

ErrRawPathForeign is returned by UpsertRawArtifact when the live file at the path belongs to a package of another format, which a raw write never rewrites.

View Source
var ErrRepositoryNotFound = errors.New("repository not found")

ErrRepositoryNotFound is returned when a repository to modify does not exist (or is trashed).

View Source
var ErrVEXStatementNotFound = errors.New("VEX statement not found")

ErrVEXStatementNotFound is returned when a VEX statement does not exist in the repository.

View Source
var ErrVEXSuggestionNotFound = errors.New("VEX suggestion not found")

ErrVEXSuggestionNotFound is returned when a VEX suggestion does not exist in the repository.

Functions

func FlaggedArtifactPredicate added in v0.11.0

func FlaggedArtifactPredicate(repoExpr, idExpr string) string

FlaggedArtifactPredicate is the SQL predicate "the package row idExpr of the repository repoExpr is flagged". Both are SQL expressions of the caller's query (idExpr is the row's uuid; artifact_refs.artifact_path holds it as text). It probes artifact_refs by its (repository_id, artifact_path) unique index once per row it is evaluated for, so apply it after the cheaper predicates.

func IsForeignKeyViolation added in v0.2.0

func IsForeignKeyViolation(err error) bool

IsForeignKeyViolation reports whether err is a PostgreSQL foreign_key_violation or restrict_violation: a referenced row cannot be removed or a referencing row points nowhere.

func IsUniqueViolation added in v0.2.0

func IsUniqueViolation(err error) bool

IsUniqueViolation reports whether err is a PostgreSQL unique_violation.

func IsValidBlobSHA256 added in v0.5.0

func IsValidBlobSHA256(s string) bool

IsValidBlobSHA256 reports whether s is a well-formed blobs.sha256 value. It mirrors storage.ValidateBlobID, which this package cannot import (storage depends on database).

func OSVResultKey added in v0.14.0

func OSVResultKey(repositoryID, artifactID string) string

OSVResultKey is the GetOSVScanResults key of a stored package.

func RestoredRowID added in v0.15.0

func RestoredRowID(repoID, oldID string) string

RestoredRowID is the id restore gives the archived row oldID of a repository restored as repoID: the Go twin of the SQL expression newID builds, for callers that must rewrite the ids a row embeds in other columns (the deb version key and partition carry companion ids).

func ScanStrings added in v0.15.0

func ScanStrings(rows *sql.Rows) ([]string, error)

ScanStrings drains a single-text-column result set into a slice and closes rows.

func TrashFilesInTx added in v0.15.0

func TrashFilesInTx(ctx context.Context, tx sqlTx, repoID string, fileIDs []string, actor string) error

TrashFilesInTx soft-deletes package files of repoID inside the caller's transaction, whatever the repository's retention: a purge removes them for good once the retention window has passed. A caller that replaces live content (a forced bundle promotion) uses it so the replaced files stay restorable. ids are listed package_files ids; the repository's format decides the scope and hooks. ErrTrashNotFound means none of the files is live in repoID.

func TrashRowsInTx added in v0.8.0

func TrashRowsInTx(ctx context.Context, tx interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}, repoID string, kind models.TrashKind, ids []string, deletedBy string,
) error

TrashRowsInTx soft-deletes docker rows (manifests or tags) of repoID inside the caller's transaction, whatever the repository's retention: a purge removes them for good once the retention window has passed. A caller that replaces live content (a forced bundle promotion) uses it so the replaced rows stay restorable. Package formats use TrashFilesInTx. ErrTrashNotFound means none of the rows is live in repoID; any other kind is ErrTrashUnknownKind.

func UniqueViolationConstraint added in v0.2.0

func UniqueViolationConstraint(err error) string

UniqueViolationConstraint returns the violated constraint/index name when err is a unique_violation, and "" otherwise.

Types

type AIAnalysisStore added in v0.15.0

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

AIAnalysisStore owns AI analysis results.

func (AIAnalysisStore) AuthCacheGeneration added in v0.15.0

func (p AIAnalysisStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (AIAnalysisStore) AuthCacheTTL added in v0.15.0

func (p AIAnalysisStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (AIAnalysisStore) BeginTx added in v0.15.0

func (p AIAnalysisStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (AIAnalysisStore) Close added in v0.15.0

func (p AIAnalysisStore) Close() error

Close writes the pending download counts and closes the database connection.

func (AIAnalysisStore) CountFileDownload added in v0.19.0

func (p AIAnalysisStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (AIAnalysisStore) FlushDownloadCounts added in v0.19.0

func (p AIAnalysisStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (*AIAnalysisStore) GetAIAnalysis added in v0.15.0

func (p *AIAnalysisStore) GetAIAnalysis(ctx context.Context, repoID, artifactID string) (*models.AIAnalysis, error)

GetAIAnalysis retrieves an AI analysis by repo and artifact ID.

func (AIAnalysisStore) GetDB added in v0.15.0

func (p AIAnalysisStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*AIAnalysisStore) ListAIAnalyses added in v0.15.0

func (p *AIAnalysisStore) ListAIAnalyses(
	ctx context.Context,
	repoID string,
	status string,
	licenseReviewOnly bool,
	limit, offset int,
) ([]*models.AIAnalysis, int, error)

ListAIAnalyses lists AI analyses for a repository with optional status and REVIEW_REQUIRED license filters.

func (AIAnalysisStore) Migrate added in v0.15.0

func (p AIAnalysisStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (AIAnalysisStore) Ping added in v0.15.0

func (p AIAnalysisStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (AIAnalysisStore) PoolStat added in v0.15.0

func (p AIAnalysisStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*AIAnalysisStore) UpsertAIAnalysis added in v0.15.0

func (p *AIAnalysisStore) UpsertAIAnalysis(ctx context.Context, analysis *models.AIAnalysis) error

UpsertAIAnalysis inserts or updates an AI analysis record.

AI analyses are stored across scan_jobs + artifact_refs + ai_results; ArtifactName/ArtifactVersion live on ai_results (artifact_refs only tracks repository_id/artifact_path/format). analysis.Status's "processing" value is mapped onto scan_jobs' CHECK-constrained "running" (see aiStatusToJob/FromJob).

Only a "completed" analysis overwrites the result columns (summary, tags, license, security notes, model, token counts). A "processing", "pending" or "failed" upsert keeps what the last completed run stored, so a re-trigger or a failed re-analysis never wipes a good result; the status and error live on scan_jobs and always follow the latest upsert.

type APKStore added in v0.15.0

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

APKStore owns the Alpine apk packages and the signing key.

An apk lives on the generic package tables (packages P, package_versions V, package_files F); there is no side table: the APKINDEX stanza fields are small, read only as a whole by the index generation and ride in V.metadata. Grain 1:1: one .apk of the mirror tree branch/repo/arch/name-version.apk is one P (shared by branch/repo/name), one V and one F. The mapping:

P  name, name_key = branch/repo/name; attrs = {branch, repo, name}
V  version        = version
   version_key    = version|arch (arch is the mirror directory, not pkg_arch)
   metadata       = {pkg_arch, checksum, data_sha256, description, url, license, origin,
                    maintainer, commit, depends[], provides[], install_if[],
                    provider_priority}; all keys written, the arrays keep their order
F  path           = branch/repo/arch/name-version.apk; filename = name-version.apk
   arch           = the mirror directory; blob_id = the .apk blob; size_bytes = NULL
   part           = ''; checksums = {}
   attrs          = {build_time, installed_size} (only when not zero)
   download_count = the download counter

func (APKStore) AuthCacheGeneration added in v0.15.0

func (p APKStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (APKStore) AuthCacheTTL added in v0.15.0

func (p APKStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (APKStore) BeginTx added in v0.15.0

func (p APKStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (APKStore) Close added in v0.15.0

func (p APKStore) Close() error

Close writes the pending download counts and closes the database connection.

func (APKStore) CountFileDownload added in v0.19.0

func (p APKStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*APKStore) CreateApkPackage added in v0.15.0

func (p *APKStore) CreateApkPackage(ctx context.Context, pkg *models.ApkPackage) error

CreateApkPackage stores one .apk. A live row with the same coordinates is ErrDuplicate.

func (*APKStore) CreateApkSigningKeyIfAbsent added in v0.15.0

func (p *APKStore) CreateApkSigningKeyIfAbsent(ctx context.Context, k *models.ApkSigningKey) (bool, error)

CreateApkSigningKeyIfAbsent stores the key unless the repository has one; created reports whether it did.

func (*APKStore) DeleteApkPackage added in v0.15.0

func (p *APKStore) DeleteApkPackage(ctx context.Context, id, repoID string) error

DeleteApkPackage removes one live package row (and its version and package when nothing else holds them).

func (APKStore) FlushDownloadCounts added in v0.19.0

func (p APKStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (*APKStore) GetApkPackageFile added in v0.15.0

func (p *APKStore) GetApkPackageFile(ctx context.Context, repoID, branch, repo, arch, name, version string) (*models.ApkPackage, error)

GetApkPackageFile returns the live .apk, or (nil, nil).

func (*APKStore) GetApkSigningKey added in v0.15.0

func (p *APKStore) GetApkSigningKey(ctx context.Context, repoID string) (*models.ApkSigningKey, error)

GetApkSigningKey returns the repository's signing key, or (nil, nil).

func (APKStore) GetDB added in v0.15.0

func (p APKStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*APKStore) ListApkPackages added in v0.15.0

func (p *APKStore) ListApkPackages(ctx context.Context, repoID string) ([]*models.ApkPackage, error)

ListApkPackages returns every live package of the repository ordered by branch, repo, arch, name and version.

func (APKStore) Migrate added in v0.15.0

func (p APKStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (APKStore) Ping added in v0.15.0

func (p APKStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (APKStore) PoolStat added in v0.15.0

func (p APKStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*APKStore) ReplaceApkSigningKey added in v0.15.0

func (p *APKStore) ReplaceApkSigningKey(ctx context.Context, k *models.ApkSigningKey) error

ReplaceApkSigningKey stores the key, replacing the repository's current one.

type AnsibleStore added in v0.15.0

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

AnsibleStore owns the Ansible collections.

Mapping of a collection version onto the generic package tables (one published tarball is one version and one file; the collection is the package):

packages          name = name_key = "namespace.name" (the FQCN; neither part
                  contains a dot), attrs {namespace, name}
package_versions  version = version_key = collection version; metadata
                  {dependencies: object, metadata: the galaxy.yml info,
                  requires_ansible: text, omitted when empty}
package_files     path namespace/name/version/filename, filename as given,
                  the tarball blob, role primary, no unit_key (ansible is
                  not federated)

The id a client sees (upload response, import task URL) is package_files.id. A duplicate publish is a live version with a live file (ErrDuplicate).

func (AnsibleStore) AuthCacheGeneration added in v0.15.0

func (p AnsibleStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (AnsibleStore) AuthCacheTTL added in v0.15.0

func (p AnsibleStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (AnsibleStore) BeginTx added in v0.15.0

func (p AnsibleStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (AnsibleStore) Close added in v0.15.0

func (p AnsibleStore) Close() error

Close writes the pending download counts and closes the database connection.

func (AnsibleStore) CountFileDownload added in v0.19.0

func (p AnsibleStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*AnsibleStore) CreateAnsibleCollection added in v0.15.0

func (p *AnsibleStore) CreateAnsibleCollection(ctx context.Context, c *models.AnsibleCollection) error

CreateAnsibleCollection stores one collection version. A live version with the same namespace, name and version is ErrDuplicate.

func (*AnsibleStore) DeleteAnsibleCollection added in v0.15.0

func (p *AnsibleStore) DeleteAnsibleCollection(ctx context.Context, repoID, id string) error

DeleteAnsibleCollection hard-deletes a live collection version file; the version and the collection go with their last file.

func (AnsibleStore) FlushDownloadCounts added in v0.19.0

func (p AnsibleStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (*AnsibleStore) GetAnsibleCollection added in v0.15.0

func (p *AnsibleStore) GetAnsibleCollection(
	ctx context.Context,
	repoID, namespace, name, version string,
) (*models.AnsibleCollection, error)

GetAnsibleCollection returns the live version of a collection, or (nil, nil).

func (*AnsibleStore) GetAnsibleCollectionByID added in v0.15.0

func (p *AnsibleStore) GetAnsibleCollectionByID(ctx context.Context, repoID, id string) (*models.AnsibleCollection, error)

GetAnsibleCollectionByID returns the live collection version of the repository with the ID, or (nil, nil).

func (AnsibleStore) GetDB added in v0.15.0

func (p AnsibleStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*AnsibleStore) ListAnsibleCollectionNames added in v0.15.0

func (p *AnsibleStore) ListAnsibleCollectionNames(
	ctx context.Context, repoID string, limit, offset int,
) ([]*models.AnsibleCollectionName, int, error)

ListAnsibleCollectionNames returns a page of the collections of the repository in name order, and how many collections it has.

func (*AnsibleStore) ListAnsibleCollectionVersions added in v0.15.0

func (p *AnsibleStore) ListAnsibleCollectionVersions(
	ctx context.Context,
	repoID, namespace, name string,
) ([]*models.AnsibleCollection, error)

ListAnsibleCollectionVersions returns every live version of one collection.

func (*AnsibleStore) ListAnsibleCollections added in v0.15.0

func (p *AnsibleStore) ListAnsibleCollections(ctx context.Context, repoID string) ([]*models.AnsibleCollection, error)

ListAnsibleCollections returns every live version of every collection of the repository.

func (AnsibleStore) Migrate added in v0.15.0

func (p AnsibleStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (AnsibleStore) Ping added in v0.15.0

func (p AnsibleStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (AnsibleStore) PoolStat added in v0.15.0

func (p AnsibleStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

type AttestationStore added in v0.21.0

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

AttestationStore owns the index of attestations attached to docker images (oci_attestations) and the per-repository trust configuration they are verified against.

func (AttestationStore) AuthCacheGeneration added in v0.21.0

func (p AttestationStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (AttestationStore) AuthCacheTTL added in v0.21.0

func (p AttestationStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (AttestationStore) BeginTx added in v0.21.0

func (p AttestationStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (AttestationStore) Close added in v0.21.0

func (p AttestationStore) Close() error

Close writes the pending download counts and closes the database connection.

func (AttestationStore) CountFileDownload added in v0.21.0

func (p AttestationStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (AttestationStore) FlushDownloadCounts added in v0.21.0

func (p AttestationStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (AttestationStore) GetDB added in v0.21.0

func (p AttestationStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*AttestationStore) GetOCIAttestationFirstSeen added in v0.21.0

func (p *AttestationStore) GetOCIAttestationFirstSeen(
	ctx context.Context, repoID, image, subject, attestationDigest string,
) (time.Time, bool, error)

GetOCIAttestationFirstSeen returns when the envelope was first indexed for the subject of the image; false when it never was.

func (*AttestationStore) GetRepositoryAttestationTrust added in v0.21.0

func (p *AttestationStore) GetRepositoryAttestationTrust(ctx context.Context, repoID string) (json.RawMessage, error)

GetRepositoryAttestationTrust returns the repository's trust configuration document, nil when none is set.

func (*AttestationStore) HasVerifiedOCIAttestation added in v0.21.0

func (p *AttestationStore) HasVerifiedOCIAttestation(ctx context.Context, repoID, subject string, predicateTypes []string) (bool, error)

HasVerifiedOCIAttestation reports whether a verified attestation of one of the predicate types is indexed for the manifest digest.

func (*AttestationStore) ListOCIAttestations added in v0.21.0

func (p *AttestationStore) ListOCIAttestations(ctx context.Context, repoID, subject, image string) ([]*models.OCIAttestation, error)

ListOCIAttestations lists the attachments of a subject digest carried by manifests that are not in the trash, of one image when image is not empty.

func (*AttestationStore) ListOCIAttestationsByDigest added in v0.21.0

func (p *AttestationStore) ListOCIAttestationsByDigest(
	ctx context.Context, repoID, attestationDigest string,
) ([]*models.OCIAttestation, error)

ListOCIAttestationsByDigest lists the rows of an envelope digest.

func (*AttestationStore) ListOCIAttestationsPage added in v0.21.0

func (p *AttestationStore) ListOCIAttestationsPage(
	ctx context.Context,
	repoID, afterID string,
	limit int,
) ([]*models.OCIAttestation, error)

ListOCIAttestationsPage lists up to limit attachments of the repository whose id is greater than afterID, in id order.

func (AttestationStore) Migrate added in v0.21.0

func (p AttestationStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (AttestationStore) Ping added in v0.21.0

func (p AttestationStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (AttestationStore) PoolStat added in v0.21.0

func (p AttestationStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*AttestationStore) SetRepositoryAttestationTrust added in v0.21.0

func (p *AttestationStore) SetRepositoryAttestationTrust(ctx context.Context, repoID string, config json.RawMessage) error

SetRepositoryAttestationTrust stores the repository's trust configuration document.

func (*AttestationStore) UpsertOCIAttestation added in v0.21.0

func (p *AttestationStore) UpsertOCIAttestation(ctx context.Context, a *models.OCIAttestation) error

UpsertOCIAttestation records the attachment, or refreshes the row of the same (repository, image, subject, envelope): its verification outcome and the manifest carrying it. An existing row keeps its created_at, the time the envelope was first seen; a zero a.CreatedAt means now. The stored id and created_at are filled back into a.

type AuditRetentionStore added in v0.10.0

type AuditRetentionStore interface {
	// PurgeAuditLogsBefore deletes up to limit audit entries created before
	// cutoff, oldest first, and returns how many it removed. A result below
	// limit means nothing older than cutoff is left.
	PurgeAuditLogsBefore(ctx context.Context, cutoff time.Time, limit int) (int64, error)
}

AuditRetentionStore deletes audit entries past their retention window. It is implemented by *PostgresDB and found by the retention worker with a type assertion on Database.

type AuditStore added in v0.15.0

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

AuditStore owns the audit log.

func (AuditStore) AuthCacheGeneration added in v0.15.0

func (p AuditStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (AuditStore) AuthCacheTTL added in v0.15.0

func (p AuditStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (AuditStore) BeginTx added in v0.15.0

func (p AuditStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (AuditStore) Close added in v0.15.0

func (p AuditStore) Close() error

Close writes the pending download counts and closes the database connection.

func (AuditStore) CountFileDownload added in v0.19.0

func (p AuditStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (AuditStore) FlushDownloadCounts added in v0.19.0

func (p AuditStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (AuditStore) GetDB added in v0.15.0

func (p AuditStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*AuditStore) InsertAuditLog added in v0.15.0

func (p *AuditStore) InsertAuditLog(ctx context.Context, event *models.AuditLog) error

func (*AuditStore) ListAuditLogs added in v0.15.0

func (p *AuditStore) ListAuditLogs(ctx context.Context, params models.AuditListParams) (*models.AuditPage, error)

ListAuditLogs returns one page of audit entries, newest first. It reads Limit+1 rows to learn whether more follow, so no COUNT(*) runs for keyset (After) paging, and offset paging only counts when the page itself cannot answer (see auditTotal).

func (AuditStore) Migrate added in v0.15.0

func (p AuditStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (AuditStore) Ping added in v0.15.0

func (p AuditStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (AuditStore) PoolStat added in v0.15.0

func (p AuditStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*AuditStore) PurgeAuditLogsBefore added in v0.15.0

func (p *AuditStore) PurgeAuditLogsBefore(ctx context.Context, cutoff time.Time, limit int) (int64, error)

PurgeAuditLogsBefore implements AuditRetentionStore.

func (*AuditStore) ResolveAuditNames added in v0.15.0

func (p *AuditStore) ResolveAuditNames(ctx context.Context, refs models.AuditNameRefs) (*models.AuditNames, error)

ResolveAuditNames looks up the display names of the entities one audit page refers to, one query for all kinds. Entities that no longer exist are absent from the result.

type BackupStore added in v0.15.0

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

BackupStore owns backup jobs and the consistent backup snapshot.

func (BackupStore) AuthCacheGeneration added in v0.15.0

func (p BackupStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (BackupStore) AuthCacheTTL added in v0.15.0

func (p BackupStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (*BackupStore) BeginBackupSnapshot added in v0.15.0

func (p *BackupStore) BeginBackupSnapshot(ctx context.Context, leaseTTL time.Duration) (SnapshotReader, error)

BeginBackupSnapshot registers a backup lease and freezes the database. See SnapshotReader. The lease is renewed in the background until Release; if the process dies, it simply expires after leaseTTL and deferred blob deletions resume. The caller's ctx must outlive the backup: its cancellation ends the snapshot.

func (BackupStore) BeginTx added in v0.15.0

func (p BackupStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (BackupStore) Close added in v0.15.0

func (p BackupStore) Close() error

Close writes the pending download counts and closes the database connection.

func (BackupStore) CountFileDownload added in v0.19.0

func (p BackupStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*BackupStore) CreateBackupJob added in v0.15.0

func (p *BackupStore) CreateBackupJob(ctx context.Context, job *models.BackupJob) error

CreateBackupJob creates a new backup job.

func (*BackupStore) ExportPackageRows added in v0.15.0

func (p *BackupStore) ExportPackageRows(ctx context.Context, set PackageRowSet, repoID string, fn func(row []byte) error) error

ExportPackageRows streams the rows of set that belong to repoID, as of the snapshot, to fn as JSON objects (one jsonb value per call; fn owns the bytes).

func (BackupStore) FlushDownloadCounts added in v0.19.0

func (p BackupStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (*BackupStore) GetBackupJob added in v0.15.0

func (p *BackupStore) GetBackupJob(ctx context.Context, id string) (*models.BackupJob, error)

GetBackupJob retrieves a backup job by ID.

func (BackupStore) GetDB added in v0.15.0

func (p BackupStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*BackupStore) ListBackupJobs added in v0.15.0

func (p *BackupStore) ListBackupJobs(ctx context.Context, limit int) ([]*models.BackupJob, error)

ListBackupJobs lists backup jobs with a limit.

func (BackupStore) Migrate added in v0.15.0

func (p BackupStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (BackupStore) Ping added in v0.15.0

func (p BackupStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (BackupStore) PoolStat added in v0.15.0

func (p BackupStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*BackupStore) PurgeExpiredBackupLeases added in v0.15.0

func (p *BackupStore) PurgeExpiredBackupLeases(ctx context.Context) (int64, error)

PurgeExpiredBackupLeases removes the leases of backups that stopped renewing them (crashed). An expired lease already blocks nothing; this only tidies up.

func (*BackupStore) RestorePackageRows added in v0.15.0

func (p *BackupStore) RestorePackageRows(ctx context.Context, set PackageRowSet, repoID string, rows []json.RawMessage) (int, error)

RestorePackageRows inserts up to PackageRestoreBatch archived rows of set into repoID, a repository the restore created, in one statement. If the batch fails it retries the rows one by one so one bad row costs one row, not the batch: it returns how many rows were not restored and the first error. Rows are autocommitted, like every other restore step.

func (*BackupStore) UpdateBackupJob added in v0.15.0

func (p *BackupStore) UpdateBackupJob(ctx context.Context, job *models.BackupJob) error

UpdateBackupJob updates an existing backup job.

type BlobDeletion added in v0.7.0

type BlobDeletion struct {
	SHA256    string
	Scope     string
	QueuedAt  time.Time
	NotBefore time.Time
	Attempts  int
}

BlobDeletion is a queued deletion of blob bytes (see EnqueueBlobDeletion).

type BlobDeletionStore added in v0.7.0

type BlobDeletionStore interface {
	// ClaimBlobDeletions hands out up to limit deletions that are due: past
	// their grace period and not needed by any running backup. A claimed row is
	// invisible to other callers for claimFor.
	ClaimBlobDeletions(ctx context.Context, limit int, claimFor time.Duration) ([]BlobDeletion, error)
	// BlobDeletionDue re-checks, under the per-blob lock, that the deletion is
	// still due.
	BlobDeletionDue(ctx context.Context, sha256, scope string) (bool, error)
	// DeleteBlobDeletion removes a queued deletion.
	DeleteBlobDeletion(ctx context.Context, sha256, scope string) error
	// CountBlobDeletions returns the queue length.
	CountBlobDeletions(ctx context.Context) (int64, error)
	// PurgeExpiredBackupLeases removes leases of backups that stopped renewing.
	PurgeExpiredBackupLeases(ctx context.Context) (int64, error)
}

BlobDeletionStore is the deferred-deletion queue the blob deletion sweeper works through; *PostgresDB implements it. See docs/operations/storage.md.

type BlobRefStore added in v0.15.0

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

BlobRefStore owns the blobs table: upsert, reference counting, blob locks and the deferred-deletion queue.

func (*BlobRefStore) ArtifactExists added in v0.15.0

func (p *BlobRefStore) ArtifactExists(ctx context.Context, sha256 string, repositoryID string) (bool, error)

func (BlobRefStore) AuthCacheGeneration added in v0.15.0

func (p BlobRefStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (BlobRefStore) AuthCacheTTL added in v0.15.0

func (p BlobRefStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (BlobRefStore) BeginTx added in v0.15.0

func (p BlobRefStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (*BlobRefStore) BlobDeletionDue added in v0.15.0

func (p *BlobRefStore) BlobDeletionDue(ctx context.Context, sha256, scope string) (bool, error)

BlobDeletionDue reports whether the queued deletion may run right now: it exists, its grace period has passed and no live backup lease still needs the bytes. The sweeper asks again after taking the per-blob lock, because the blob may have been deleted once more (a newer deletion a backup still sees) since it was claimed.

func (*BlobRefStore) BlobReferenceCount added in v0.15.0

func (p *BlobRefStore) BlobReferenceCount(ctx context.Context, sha256 string) (int, error)

BlobReferenceCount returns the number of rows, across package_files and the other tables that store a blob_id FK into the global blobs table, referencing the blob identified by sha256. A count of 0 means the blob is safe to delete from storage (see SafeDeleteBlob in internal/storage/refcount.go). A blob that does not exist in the blobs table is still checked against the tables that reference storage objects by sha256 alone (generated metadata, deltas, release bundles, proxy cache).

func (*BlobRefStore) ClaimBlobDeletions added in v0.15.0

func (p *BlobRefStore) ClaimBlobDeletions(ctx context.Context, limit int, claimFor time.Duration) ([]BlobDeletion, error)

ClaimBlobDeletions hands out up to limit deletions that are due. A claimed row is invisible to other callers for claimFor (so two sweepers never take the same one, and a crashed sweeper's rows come back).

func (BlobRefStore) Close added in v0.15.0

func (p BlobRefStore) Close() error

Close writes the pending download counts and closes the database connection.

func (*BlobRefStore) CountBlobDeletions added in v0.15.0

func (p *BlobRefStore) CountBlobDeletions(ctx context.Context) (int64, error)

CountBlobDeletions returns how many deletions are queued.

func (BlobRefStore) CountFileDownload added in v0.19.0

func (p BlobRefStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*BlobRefStore) DeleteBlobDeletion added in v0.15.0

func (p *BlobRefStore) DeleteBlobDeletion(ctx context.Context, sha256, scope string) error

DeleteBlobDeletion removes a queued deletion (its bytes are gone, or it no longer applies).

func (*BlobRefStore) DeleteBlobIfUnreferenced added in v0.15.0

func (p *BlobRefStore) DeleteBlobIfUnreferenced(ctx context.Context, sha256 string) (bool, error)

DeleteBlobIfUnreferenced atomically removes the blobs row for sha256 and queues its bytes for deletion (BlobDeletionScopeAll), but only when no package row still references it. The check, row delete and enqueue run in one transaction under the blob advisory lock; the bytes are removed later by the sweeper, once the grace period has passed and no running backup can still need them. Returns true when the blob was removed.

func (*BlobRefStore) DeleteBlobsIfUnreferenced added in v0.19.0

func (p *BlobRefStore) DeleteBlobsIfUnreferenced(ctx context.Context, shas []string) (int, error)

DeleteBlobsIfUnreferenced is DeleteBlobIfUnreferenced for many blobs: per chunk of BlobBatchLockChunk, ONE transaction takes the blobs' advisory locks (sorted, the order WithBlobLocks uses, so no deadlock with an uploader), then one statement re-checks the references, deletes the blobs rows still unreferenced and queues their bytes for deletion. The check runs after the locks, exactly as in the single-blob protocol, so a blob an uploader is about to reference is never removed. It returns how many blobs were removed. An error (a foreign key a table outside the reference list holds, for example) fails the chunk it happened in as a whole: the caller retries those blobs one by one to isolate the offender. The count returned with an error covers the chunks that committed before the failing one (none for a call of at most BlobBatchLockChunk blobs).

func (*BlobRefStore) EnqueueBlobDeletion added in v0.15.0

func (p *BlobRefStore) EnqueueBlobDeletion(ctx context.Context, sha256, scope string) error

EnqueueBlobDeletion queues the copies of sha256 named by scope for deletion (see BlobDeletionScope*). The caller has already removed what made the copies live (the blobs row, or the placement on that tier) and normally holds the per-blob lock; a caller that cannot (a write that raced a placement flip and queues its own stray copy) may enqueue without it, because the sweeper re-checks the placement under the lock before it deletes anything. The bytes stay until the grace period has passed and no live backup can still need them.

func (*BlobRefStore) EnsureBlob added in v0.15.0

func (p *BlobRefStore) EnsureBlob(ctx context.Context, sha256, mediaType string, size int64) (string, error)

EnsureBlob ensures the global blobs table has a row for sha256 (creating it if it does not exist yet) and returns its blobs.id. Manifests are stored directly in the blob store without a per-repo registry row (unlike docker_blobs), so this is the manifest handlers' entry point into upsertBlobWithMediaType.

func (BlobRefStore) FlushDownloadCounts added in v0.19.0

func (p BlobRefStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (BlobRefStore) GetDB added in v0.15.0

func (p BlobRefStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*BlobRefStore) ListUnreferencedBlobs added in v0.15.0

func (p *BlobRefStore) ListUnreferencedBlobs(
	ctx context.Context,
	minAge time.Duration,
	after string,
	scan, limit int,
) ([]string, string, error)

ListUnreferencedBlobs scans one window of at most scan blobs rows whose sha256 sorts after the cursor and returns up to limit of them that no package row references and that are older than minAge (so in-flight uploads, which create the blobs row before their referencing row, are never picked). next is the cursor for the following call and is "" once the end of the table was reached, i.e. the scan wraps around.

Bounding the window (instead of evaluating the reference check for every old blob on every call) keeps the cost of a pass independent of table size, and advancing by sha256 means orphans that cannot be removed never block the ones behind them. Used to reclaim storage after repository deletion cascades its package rows.

func (BlobRefStore) Migrate added in v0.15.0

func (p BlobRefStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (BlobRefStore) Ping added in v0.15.0

func (p BlobRefStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (BlobRefStore) PoolStat added in v0.15.0

func (p BlobRefStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*BlobRefStore) SetBlobDeletionGrace added in v0.15.0

func (p *BlobRefStore) SetBlobDeletionGrace(d time.Duration)

SetBlobDeletionGrace sets how long the bytes of a deleted blob (or of a tier copy a placement flip retired) are kept before the sweeper may remove them. Zero means as soon as no running backup can still need them.

func (*BlobRefStore) UpsertBlob added in v0.15.0

func (p *BlobRefStore) UpsertBlob(ctx context.Context, sha256, blobKey string, sizeBytes int64) (string, error)

UpsertBlob inserts a blob row keyed by sha256 and returns its id, using ON CONFLICT to handle concurrent uploads safely.

func (*BlobRefStore) WithBlobLock added in v0.15.0

func (p *BlobRefStore) WithBlobLock(ctx context.Context, sha256 string, fn func(ctx context.Context) error) error

WithBlobLock runs fn inside a transaction holding a transaction-scoped advisory lock keyed on the blob sha256. Uploaders that create a reference to a blob and the garbage collector (DeleteBlobIfUnreferenced) serialize on the same lock, so a blob cannot be deleted between "ref count == 0" and the uploader's insert.

func (*BlobRefStore) WithBlobLocks added in v0.15.0

func (p *BlobRefStore) WithBlobLocks(ctx context.Context, shas []string, fn func(ctx context.Context) error) error

WithBlobLocks is WithBlobLock for several blobs at once: all locks are taken on ONE transaction connection, in sorted order (so two callers locking overlapping sets cannot deadlock each other), and held until fn returns. Taking them through nested WithBlobLock calls instead would pin one pooled connection per lock and let concurrent callers exhaust the pool.

fn does its database work on other pooled connections (the lock transaction itself stays idle), so it MUST NOT take another blob lock or delete a blob (WithBlobLock(s), SafeDeleteBlob, DeleteBlobIfUnreferenced, FlipBlobPlacement): every one of those holds one of the bounded lock slots (see core.lockSlots) and a nested acquisition inside a holder can deadlock once the concurrent holders fill the slots, each waiting for a slot of its own.

The lock transaction never writes. When fn returned nil but the transaction cannot be committed, the lock was lost during fn: ErrBlobLockLost is returned, wrapping the commit error. fn's own work is already committed by then and is not undone, so a caller must treat that as a failed operation and clean up the way it does for any other failure (SafeDeleteBlob keeps a blob a committed row references), never as proof that nothing was written.

type BlobReplication added in v0.9.0

type BlobReplication struct {
	SHA256 string
	// Op is BlobReplicationCopy or BlobReplicationDelete.
	Op string
	// Version changes whenever Op changes; CompleteBlobReplication and
	// FailBlobReplication act only on the version that was claimed.
	Version    int64
	Attempts   int
	EnqueuedAt time.Time
	// NextAttemptAt, LastError are set by GetBlobReplication only.
	NextAttemptAt time.Time
	LastError     string
}

BlobReplication is a queued replication operation.

type BlobReplicationBacklog added in v0.9.0

type BlobReplicationBacklog struct {
	Copy   int64
	Delete int64
	// Failing is the number of operations with at least the attempts asked for.
	Failing int64
	// OldestAgeSeconds is the age of the oldest queued operation (0 when empty).
	OldestAgeSeconds float64
}

BlobReplicationBacklog summarizes the queue.

type BlobReplicationState added in v0.9.0

type BlobReplicationState struct {
	ReplicatedTotal int64
	ReplicatedBytes int64
	LastError       string
	LastErrorAt     *time.Time
	// VerifyRequested is set by an admin asking for a verify pass; the next
	// worker tick starts it.
	VerifyRequested bool
	// VerifyCursor is the last blob id the running verify pass finished.
	VerifyCursor string
	// VerifyRun is the JSON counters of the running pass (nil = none runs);
	// LastVerify those of the last finished one.
	VerifyRun  json.RawMessage
	LastVerify json.RawMessage
}

BlobReplicationState is the shared singleton state of the replication subsystem: totals, the last error and the verify job's progress.

type BlobReplicationStore added in v0.9.0

type BlobReplicationStore interface {
	// EnqueueBlobReplication queues op ("copy" or "delete") for the blob. The
	// latest operation wins: a different op replaces the queued one (new
	// version, due at once), the same op again is a no-op.
	EnqueueBlobReplication(ctx context.Context, sha256, op string) error
	// ClaimBlobReplications hands out up to limit operations due at asOf. A
	// claimed row is invisible to other callers until asOf+claimFor.
	ClaimBlobReplications(ctx context.Context, asOf time.Time, limit int, claimFor time.Duration) ([]BlobReplication, error)
	// CompleteBlobReplication removes the claimed operation; false when it was
	// superseded meanwhile (a newer version stays queued).
	CompleteBlobReplication(ctx context.Context, sha256 string, version int64) (bool, error)
	// FailBlobReplication records a failed attempt: attempts+1, the error and
	// the next attempt time; false when the operation was superseded.
	FailBlobReplication(ctx context.Context, sha256 string, version int64, lastError string, nextAttempt time.Time) (bool, error)
	// ReleaseBlobReplication gives a claimed operation back unprocessed.
	ReleaseBlobReplication(ctx context.Context, sha256 string, version int64) error
	// GetBlobReplication returns the queued operation of the blob, nil when none.
	GetBlobReplication(ctx context.Context, sha256 string) (*BlobReplication, error)
	// BlobReplicationBacklog counts the queue; failingAttempts is the attempt
	// count from which an operation counts as failing.
	BlobReplicationBacklog(ctx context.Context, failingAttempts int) (BlobReplicationBacklog, error)
	// ListBlobSHAs returns up to limit blobs-table ids greater than after, ascending.
	ListBlobSHAs(ctx context.Context, after string, limit int) ([]string, error)
	// BlobReplicationReferenced reports whether the database still needs the
	// blob: a blobs row, generated repository metadata or a package row.
	BlobReplicationReferenced(ctx context.Context, sha256 string) (bool, error)

	// GetBlobReplicationState reads the singleton state.
	GetBlobReplicationState(ctx context.Context) (BlobReplicationState, error)
	// AddBlobReplicationProgress adds finished copies and their bytes.
	AddBlobReplicationProgress(ctx context.Context, copies, bytes int64) error
	// SetBlobReplicationLastError records the most recent failure.
	SetBlobReplicationLastError(ctx context.Context, message string) error
	// RequestReplicationVerify asks for a verify pass; false when one is
	// running or already requested.
	RequestReplicationVerify(ctx context.Context) (bool, error)
	// StartReplicationVerify begins a pass with the initial counters; false
	// when another replica already runs one.
	StartReplicationVerify(ctx context.Context, run json.RawMessage) (bool, error)
	// SaveReplicationVerifyProgress stores the cursor and counters of the
	// running pass; false when no pass runs.
	SaveReplicationVerifyProgress(ctx context.Context, cursor string, run json.RawMessage) (bool, error)
	// FinishReplicationVerify stores the result of the pass and ends it.
	FinishReplicationVerify(ctx context.Context, result json.RawMessage) error
}

BlobReplicationStore is the durable queue and state behind async blob replication (docs/operations/replication.md); *PostgresDB implements it.

type BlobRow added in v0.7.0

type BlobRow struct {
	SHA256    string
	SizeBytes int64
}

BlobRow is one blobs row as a backup reads it.

type BlobWrite added in v0.15.0

type BlobWrite struct {
	SHA256, Key, MediaType string
	Size                   int64
}

BlobWrite names the content of a file: its sha256 digest, storage key, media type and size. A zero BlobWrite (no digest) means a file without a blob.

type BootstrapAdmin added in v0.11.0

type BootstrapAdmin struct {
	Username     string
	PasswordHash string
	// MustChangePassword forces a password change at first login.
	MustChangePassword bool
	// PasswordExpiresAt, when set, is the instant after which the password is
	// rejected at login.
	PasswordExpiresAt *time.Time
	// TokenHash is the lookup digest of an access token to create for the
	// admin; empty creates none.
	TokenHash      string
	TokenName      string
	TokenExpiresAt *time.Time
}

BootstrapAdmin describes the first admin account created on an empty instance.

type BundleStore added in v0.15.0

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

BundleStore owns promotion pipelines and release bundles.

func (*BundleStore) AddBundleItem added in v0.15.0

func (p *BundleStore) AddBundleItem(ctx context.Context, item *models.ReleaseBundleItem) error

AddBundleItem inserts a bundle item. release_bundle_items has no component_id column, so item.ComponentID never round-trips through storage. The adder is stored as an adder_id UUID FK resolved from AddedBy (username) via a scalar subquery.

func (*BundleStore) AddBundleItems added in v0.15.0

func (p *BundleStore) AddBundleItems(ctx context.Context, bundleID string, items []*models.ReleaseBundleItem) error

AddBundleItems inserts all items atomically. The bundle row is locked and must be in draft state; otherwise ErrBundleNotDraft / ErrBundleNotFound is returned and nothing is inserted. Items whose (bundle_id, sha256) already exists are skipped. Each item's ID is filled in.

func (*BundleStore) ArchiveReleaseBundle added in v0.20.0

func (p *BundleStore) ArchiveReleaseBundle(
	ctx context.Context,
	bundleID, archivedBy string,
	archivedAt time.Time,
) (bool, error)

ArchiveReleaseBundle moves a sealed bundle to archived with a conditional UPDATE of the archive columns only, so a concurrent promotion's progress is kept. It reports false when the bundle is not sealed (any more).

func (BundleStore) AuthCacheGeneration added in v0.15.0

func (p BundleStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (BundleStore) AuthCacheTTL added in v0.15.0

func (p BundleStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (BundleStore) BeginTx added in v0.15.0

func (p BundleStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (*BundleStore) BundleItemStored added in v0.15.0

func (p *BundleStore) BundleItemStored(ctx context.Context, repoID, repoName, format, sha256, path string) (bool, error)

BundleItemStored reports whether repository repoID holds a live artifact of the given format whose content digest is sha256 and which path names. The path is read by itempath, the same reading the promotion engine resolves the item by. A bundle item that fails it would sign a claim about the repository that the repository does not back.

func (BundleStore) Close added in v0.15.0

func (p BundleStore) Close() error

Close writes the pending download counts and closes the database connection.

func (BundleStore) CountFileDownload added in v0.19.0

func (p BundleStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*BundleStore) CreateBundlePromotion added in v0.15.0

func (p *BundleStore) CreateBundlePromotion(ctx context.Context, pr *models.BundlePromotion) error

func (*BundleStore) CreatePromotionPipeline added in v0.15.0

func (p *BundleStore) CreatePromotionPipeline(ctx context.Context, pp *models.PromotionPipeline) error

func (*BundleStore) CreateReleaseBundle added in v0.15.0

func (p *BundleStore) CreateReleaseBundle(ctx context.Context, b *models.ReleaseBundle) error

func (*BundleStore) DeletePromotionPipeline added in v0.15.0

func (p *BundleStore) DeletePromotionPipeline(ctx context.Context, id string) error

func (*BundleStore) DeleteReleaseBundle added in v0.15.0

func (p *BundleStore) DeleteReleaseBundle(ctx context.Context, id string) error

func (BundleStore) FlushDownloadCounts added in v0.19.0

func (p BundleStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (*BundleStore) GetBundleItem added in v0.15.0

func (p *BundleStore) GetBundleItem(ctx context.Context, bundleID, sha256 string) (*models.ReleaseBundleItem, error)

func (BundleStore) GetDB added in v0.15.0

func (p BundleStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*BundleStore) GetPromotionPipelineByID added in v0.15.0

func (p *BundleStore) GetPromotionPipelineByID(ctx context.Context, id string) (*models.PromotionPipeline, error)

func (*BundleStore) GetPromotionPipelineByName added in v0.15.0

func (p *BundleStore) GetPromotionPipelineByName(ctx context.Context, name string) (*models.PromotionPipeline, error)

func (*BundleStore) GetReleaseBundle added in v0.15.0

func (p *BundleStore) GetReleaseBundle(ctx context.Context, name, version string) (*models.ReleaseBundle, error)

func (*BundleStore) GetReleaseBundleByID added in v0.15.0

func (p *BundleStore) GetReleaseBundleByID(ctx context.Context, id string) (*models.ReleaseBundle, error)

func (*BundleStore) ListBundleChecks added in v0.21.0

func (p *BundleStore) ListBundleChecks(ctx context.Context, bundleID string) ([]*models.BundleCheck, error)

ListBundleChecks returns the latest result of every check reported against the bundle, by name.

func (*BundleStore) ListBundleItems added in v0.15.0

func (p *BundleStore) ListBundleItems(ctx context.Context, bundleID string) ([]*models.ReleaseBundleItem, error)

func (*BundleStore) ListBundlePromotions added in v0.15.0

func (p *BundleStore) ListBundlePromotions(ctx context.Context, bundleID string) ([]*models.BundlePromotion, error)

func (*BundleStore) ListPromotionPipelines added in v0.15.0

func (p *BundleStore) ListPromotionPipelines(ctx context.Context) ([]*models.PromotionPipeline, error)

func (*BundleStore) ListReleaseBundles added in v0.15.0

func (p *BundleStore) ListReleaseBundles(
	ctx context.Context,
	nameFilter, stateFilter string,
	page, limit int,
) ([]*models.ReleaseBundle, int, error)

func (BundleStore) Migrate added in v0.15.0

func (p BundleStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (*BundleStore) PatchPromotionPipeline added in v0.20.0

func (p *BundleStore) PatchPromotionPipeline(ctx context.Context, id string, patch PipelinePatch) (*models.PromotionPipeline, error)

PatchPromotionPipeline writes only the columns in patch, so a concurrent edit of the other column is not reverted by a stale snapshot. It returns the updated pipeline, or nil when it does not exist.

func (BundleStore) Ping added in v0.15.0

func (p BundleStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (BundleStore) PoolStat added in v0.15.0

func (p BundleStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*BundleStore) RemoveBundleItem added in v0.15.0

func (p *BundleStore) RemoveBundleItem(ctx context.Context, bundleID, sha256 string) error

RemoveBundleItem deletes an item only while the bundle is still a draft. The draft check and the delete are one statement that row-locks the bundle, so a concurrent seal cannot slip between them; a non-draft bundle yields ErrBundleNotDraft. Removing an item that is already gone is a no-op.

func (*BundleStore) SealReleaseBundle added in v0.15.0

func (p *BundleStore) SealReleaseBundle(
	ctx context.Context,
	bundleID, sealedBy string,
	sealedAt time.Time,
	sig *models.BundleSignature,
) (bool, error)

SealReleaseBundle moves a draft bundle to sealed with a conditional UPDATE (WHERE state = 'draft'), so concurrent item adds/seals cannot interleave. It reports whether the bundle was sealed; false means it was no longer a draft (or does not exist), or, when sig is given, that its items changed since the manifest was signed. A bundle with no items is never sealed.

func (*BundleStore) UpsertBundleCheck added in v0.21.0

func (p *BundleStore) UpsertBundleCheck(ctx context.Context, c *models.BundleCheck) error

UpsertBundleCheck stores a check result: one row per (bundle, name), a new report replacing the previous one. c.ID, CreatedAt and UpdatedAt are filled from the stored row.

type CargoStore added in v0.15.0

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

CargoStore owns the Cargo crates.

Crates live in the generic package tables (repository format "cargo"; the mapping is the maintainers' reference, derived from migrations/001_baseline.sql):

packages          one per crate: name = the spelling of the first publish,
                  name_key = lower(name) (crate names are case-insensitive), attrs {}
package_versions  one per crate version: version = version_key = version;
                  metadata {"name": <name as published with this version>,
                  "description", "homepage", "documentation", "repository",
                  "license", "readme": text, "keywords", "categories", "authors":
                  arrays of text, "metadata_json": the publish metadata the sparse
                  index is built from, "yanked": boolean (always written: the
                  sparse-index stamp hashes the file id and the yanked flag)}.
                  Empty values are omitted; a missing key reads as ""/empty.
package_files     one primary listed file per version: path
                  "<name>/<version>/<name>-<version>.crate", filename
                  "<name>-<version>.crate", download_count, unit_key
                  "<name>@<version>" (the federation unit, name as published). The
                  blob's sha256 is the crate checksum of the sparse index.

A second publish of an equal version in any spelling of the name is ErrDuplicate (the live version key of the package).

func (CargoStore) AuthCacheGeneration added in v0.15.0

func (p CargoStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (CargoStore) AuthCacheTTL added in v0.15.0

func (p CargoStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (CargoStore) BeginTx added in v0.15.0

func (p CargoStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (*CargoStore) CargoIndexStamp added in v0.15.0

func (p *CargoStore) CargoIndexStamp(ctx context.Context, repoID, name string) (string, error)

CargoIndexStamp is a cheap validator of one crate's sparse index entry: it changes when a live version is added, removed or (un)yanked.

func (CargoStore) Close added in v0.15.0

func (p CargoStore) Close() error

Close writes the pending download counts and closes the database connection.

func (CargoStore) CountFileDownload added in v0.19.0

func (p CargoStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*CargoStore) CreateCargoCrate added in v0.15.0

func (p *CargoStore) CreateCargoCrate(ctx context.Context, crate *models.CargoCrate) error

CreateCargoCrate creates a new Cargo crate version. The crate blob row takes its size from crate.SizeBytes; a live version of the same crate (any spelling of the name) is ErrDuplicate.

func (CargoStore) FlushDownloadCounts added in v0.19.0

func (p CargoStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (*CargoStore) GetCargoCrate added in v0.15.0

func (p *CargoStore) GetCargoCrate(ctx context.Context, repoID, name, version string) (*models.CargoCrate, error)

func (CargoStore) GetDB added in v0.15.0

func (p CargoStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*CargoStore) ListCargoCrateVersions added in v0.15.0

func (p *CargoStore) ListCargoCrateVersions(ctx context.Context, repoID, name string) ([]*models.CargoCrate, error)

func (*CargoStore) ListCargoIndexVersions added in v0.15.0

func (p *CargoStore) ListCargoIndexVersions(ctx context.Context, repoID, name string) ([]*models.CargoCrate, error)

ListCargoIndexVersions returns the live versions of a crate with only the columns the sparse index needs (Name, Version, MetadataJSON, Checksum, Yanked), oldest first.

func (CargoStore) Migrate added in v0.15.0

func (p CargoStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (CargoStore) Ping added in v0.15.0

func (p CargoStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (CargoStore) PoolStat added in v0.15.0

func (p CargoStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*CargoStore) SearchCargoCrateSummaries added in v0.15.0

func (p *CargoStore) SearchCargoCrateSummaries(
	ctx context.Context,
	repoID, query string,
	limit int,
) ([]*models.CargoCrateSummary, int, error)

SearchCargoCrateSummaries matches crates by name or description and returns one summary per crate (at most limit, by name) together with the total number of matching crates.

func (*CargoStore) YankCargoCrate added in v0.15.0

func (p *CargoStore) YankCargoCrate(ctx context.Context, repoID, name, version string, yanked bool) error

type CatalogStore added in v0.15.0

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

CatalogStore is the format-independent package listing: the generic package tables (plus the docker tags and the proxy cache, see ListRepoComponents), repository size/security aggregates and the package rollups. A new format needs no branch: it lists once it writes package_files rows.

func (*CatalogStore) ArtifactSecurity added in v0.15.0

func (p *CatalogStore) ArtifactSecurity(
	ctx context.Context,
	repoID string,
	artifactIDs []string,
) (map[string]models.ArtifactSecurity, error)

ArtifactSecurity returns the scan state of the packages of repoID with the given listing row ids. A package that was never scanned has no entry.

func (CatalogStore) AuthCacheGeneration added in v0.15.0

func (p CatalogStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (CatalogStore) AuthCacheTTL added in v0.15.0

func (p CatalogStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (CatalogStore) BeginTx added in v0.15.0

func (p CatalogStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (CatalogStore) Close added in v0.15.0

func (p CatalogStore) Close() error

Close writes the pending download counts and closes the database connection.

func (CatalogStore) CountFileDownload added in v0.19.0

func (p CatalogStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (CatalogStore) FlushDownloadCounts added in v0.19.0

func (p CatalogStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (CatalogStore) GetDB added in v0.15.0

func (p CatalogStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*CatalogStore) GetRepoComponentBlob added in v0.15.0

func (p *CatalogStore) GetRepoComponentBlob(ctx context.Context, repoID, id string) (*models.ComponentBlob, error)

GetRepoComponentBlob resolves a row id of the package listing (ListComponentsByRepo) to its blob, scoped to repoID. It returns nil, nil when no row of any format has that id in the repository, or when id is not a UUID.

func (*CatalogStore) GetRepoComponentDetail added in v0.15.0

func (p *CatalogStore) GetRepoComponentDetail(ctx context.Context, repoID, id string) (*models.ComponentDetail, error)

GetRepoComponentDetail resolves a row id of the package listing (a package_files id of any format) to the artifact with the metadata its format shows, scoped to repoID. The query loads the file with its version, package and side-table JSON; the format's storage.Detail descriptor says which fields of that document are the summary, license, info entries and dependencies, so no format is named here. It returns nil, nil when the id is not in that repository or is not a UUID.

func (*CatalogStore) ListComponentsByRepo added in v0.15.0

func (p *CatalogStore) ListComponentsByRepo(
	ctx context.Context,
	repoID, formatFilter string,
	page, limit int,
) ([]*models.Component, int, error)

ListComponentsByRepo lists the packages of one repository across every format (see ListRepoComponents in queries/components.sql for the mapping). formatFilter, when non-empty, restricts the result to one format.

func (*CatalogStore) ListRecentPackages added in v0.15.0

func (p *CatalogStore) ListRecentPackages(ctx context.Context, repoIDs []string, limit int) ([]models.RecentPackage, error)

ListRecentPackages returns the newest package versions across the repositories in repoIDs, newest first, at most limit of them. Multi-file versions appear once.

func (*CatalogStore) ListRepoPackageRollup added in v0.15.0

func (p *CatalogStore) ListRepoPackageRollup(ctx context.Context, opts models.PackageRollupOptions) ([]models.PackageRollup, int, error)

ListRepoPackageRollup lists the packages (format, name) of a repository, one row each: the latest version, the version count and the latest version's size. It returns the requested page and the total number of matching packages.

The first stage groups the live versions (docker tags and proxy cache rows for those branches), the second reads the sizes of the page's packages only (see rollupQuery).

func (CatalogStore) Migrate added in v0.15.0

func (p CatalogStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (CatalogStore) Ping added in v0.15.0

func (p CatalogStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (CatalogStore) PoolStat added in v0.15.0

func (p CatalogStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*CatalogStore) ReconcileRepoStats added in v0.19.0

func (p *CatalogStore) ReconcileRepoStats(ctx context.Context, batch int, maxAge time.Duration) (int, error)

ReconcileRepoStats recomputes the repo_stats rows of up to batch repositories and returns how many it recomputed; a result below batch means nothing more is waiting. The repositories are the ones a write marked in repo_stats_dirty (the longest waiting first), then, with room left, the ones whose row is missing or was last computed more than maxAge ago, which repairs drift no mark announced. A repository deleted since is skipped.

The marks are claimed in the transaction that stores the figures, so a failed pass leaves them for the next one, and the figures are read after the claim: a write that commits later leaves a new mark that the next pass takes. Callers must not run it concurrently for the same database (the worker holds a cluster lock); two passes would only recompute the same rows.

func (*CatalogStore) RepoCatalogStats added in v0.15.0

func (p *CatalogStore) RepoCatalogStats(ctx context.Context, repoIDs []string) (map[string]models.RepoStats, error)

RepoCatalogStats returns the catalog figures of the repositories in repoIDs (a repository without any is present with zero values): package count, newest publication and security counts as the repo stats worker last stored them (see ReconcileRepoStats, docs/getting-started/upgrading.md), and the stored size and quota, which are live counters. It runs one indexed query for the whole set whatever the number of packages or scans.

func (*CatalogStore) SearchComponents added in v0.15.0

func (p *CatalogStore) SearchComponents(ctx context.Context, repoID string, opts ComponentListOptions) ([]*models.Component, int, error)

SearchComponents is ListComponentsByRepo with the extra filters and the ordering of ComponentListOptions.

type CleanupStore added in v0.15.0

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

CleanupStore owns cleanup policies.

func (CleanupStore) AuthCacheGeneration added in v0.15.0

func (p CleanupStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (CleanupStore) AuthCacheTTL added in v0.15.0

func (p CleanupStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (CleanupStore) BeginTx added in v0.15.0

func (p CleanupStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (CleanupStore) Close added in v0.15.0

func (p CleanupStore) Close() error

Close writes the pending download counts and closes the database connection.

func (CleanupStore) CountFileDownload added in v0.19.0

func (p CleanupStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*CleanupStore) CreateCleanupPolicy added in v0.15.0

func (p *CleanupStore) CreateCleanupPolicy(ctx context.Context, policy *models.CleanupPolicy) error

CreateCleanupPolicy creates a new cleanup policy.

func (*CleanupStore) DeleteCleanupPolicy added in v0.15.0

func (p *CleanupStore) DeleteCleanupPolicy(ctx context.Context, id string) error

DeleteCleanupPolicy deletes a cleanup policy.

func (CleanupStore) FlushDownloadCounts added in v0.19.0

func (p CleanupStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (*CleanupStore) GetCleanupPolicy added in v0.15.0

func (p *CleanupStore) GetCleanupPolicy(ctx context.Context, id string) (*models.CleanupPolicy, error)

GetCleanupPolicy retrieves a cleanup policy by ID.

func (CleanupStore) GetDB added in v0.15.0

func (p CleanupStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*CleanupStore) ListCleanupPolicies added in v0.15.0

func (p *CleanupStore) ListCleanupPolicies(ctx context.Context, repoID string) ([]*models.CleanupPolicy, error)

ListCleanupPolicies lists all cleanup policies for a repository.

func (*CleanupStore) ListEnabledCleanupPolicies added in v0.15.0

func (p *CleanupStore) ListEnabledCleanupPolicies(ctx context.Context) ([]*models.CleanupPolicy, error)

ListEnabledCleanupPolicies lists all enabled cleanup policies.

func (*CleanupStore) ListProjectCleanupPolicies added in v0.15.0

func (p *CleanupStore) ListProjectCleanupPolicies(ctx context.Context, projectID string) ([]*models.CleanupPolicy, error)

ListProjectCleanupPolicies lists the default cleanup policies of a project.

func (*CleanupStore) ListProjectCleanupRepositories added in v0.15.0

func (p *CleanupStore) ListProjectCleanupRepositories(ctx context.Context, projectID string) ([]string, error)

ListProjectCleanupRepositories returns the IDs of the live hosted repositories a project default policy applies to: those without an enabled repository-level policy.

func (CleanupStore) Migrate added in v0.15.0

func (p CleanupStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (CleanupStore) Ping added in v0.15.0

func (p CleanupStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (CleanupStore) PoolStat added in v0.15.0

func (p CleanupStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*CleanupStore) UpdateCleanupPolicy added in v0.15.0

func (p *CleanupStore) UpdateCleanupPolicy(ctx context.Context, policy *models.CleanupPolicy) error

UpdateCleanupPolicy updates an existing cleanup policy.

func (*CleanupStore) UpdateCleanupPolicyRunResult added in v0.15.0

func (p *CleanupStore) UpdateCleanupPolicyRunResult(ctx context.Context, id string, deletedCount int, runErr error) error

UpdateCleanupPolicyRunResult updates the run result of a cleanup policy.

type ComponentCursor added in v0.15.0

type ComponentCursor struct {
	CreatedAt time.Time
	ID        string
}

ComponentCursor is a position in the newest-first package listing, the (created_at, id) of a row: the listing order is created_at DESC, id ASC.

type ComponentListOptions added in v0.6.0

type ComponentListOptions struct {
	// Format restricts the listing to one package format ("" = all).
	Format string
	// Name restricts it to rows whose listed name equals Name exactly.
	Name string
	// Query keeps rows whose listed name or version contains Query, ignoring case.
	Query string
	// SortByName orders by (name, version) instead of newest first.
	SortByName bool
	// After, when set, continues the newest-first listing strictly after that row
	// (keyset paging): Page is then ignored. It cannot be combined with SortByName.
	After *ComponentCursor
	// NoTotal skips counting the matching rows; the returned total is then 0.
	NoTotal bool
	// TotalCap, when above zero, bounds the counting of the matching rows: the
	// total is exact up to CountCeiling and the lower bound CountCeiling+1
	// beyond it (see TotalExact). Zero counts every row.
	TotalCap int
	Page     int
	Limit    int
}

ComponentListOptions selects and orders a repository's package listing.

func (ComponentListOptions) CountCeiling added in v0.19.0

func (o ComponentListOptions) CountCeiling() int

CountCeiling is the number of rows the total counts exactly: TotalCap, but never less than the rows up to the end of the requested page, so that a deep page still knows whether the listing goes on. Zero means no ceiling.

func (ComponentListOptions) TotalExact added in v0.19.0

func (o ComponentListOptions) TotalExact(total int) bool

TotalExact reports whether a total returned for these options is the exact number of matching rows rather than the lower bound CountCeiling+1.

type ComponentSearcher added in v0.6.0

type ComponentSearcher interface {
	SearchComponents(ctx context.Context, repoID string, opts ComponentListOptions) ([]*models.Component, int, error)
}

ComponentSearcher is implemented by stores that can filter and order a repository's package listing (GET /api/v1/repositories/{name}/packages with package_name, q or sort). Kept separate from the main interface so only the real store has to provide it. It returns the requested page and the total number of matching rows.

type ComponentStore added in v0.15.0

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

ComponentStore reads and deletes the deb and rpm package rows as models.Component. Both formats live on the generic tables; the component is assembled from the file (package_files), its version (package_versions: the descriptive metadata) and its package (packages: the name), exactly as the rpm and deb specs map them:

Name                      = packages.name
Version                   = package_versions.version
Summary, Description,
License, URL, Vendor,
Group, Packager,
SourceRPM, BuildHost      = package_versions.metadata keys summary, description,
                            license, url, vendor, group_name, packager,
                            source_rpm, build_host (absent = '')
Release, Epoch,
BuildTime, ArchiveSize,
InstalledSize             = package_files.attrs keys of that name (absent = ''/0)
Arch, Filename            = package_files.arch, filename
PackageSize               = COALESCE(package_files.size_bytes, blob size, 0)

The header range and the parsed extras (rpm_files) are bulk data the readers of a component never use, so they are not loaded here.

func (ComponentStore) AuthCacheGeneration added in v0.15.0

func (p ComponentStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (ComponentStore) AuthCacheTTL added in v0.15.0

func (p ComponentStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (ComponentStore) BeginTx added in v0.15.0

func (p ComponentStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (ComponentStore) Close added in v0.15.0

func (p ComponentStore) Close() error

Close writes the pending download counts and closes the database connection.

func (ComponentStore) CountFileDownload added in v0.19.0

func (p ComponentStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*ComponentStore) DeleteComponent added in v0.15.0

func (p *ComponentStore) DeleteComponent(ctx context.Context, componentID string) error

DeleteComponent hard-deletes one live deb or rpm file (its side row goes with it) and the version and package it leaves empty. A missing id is not an error.

func (ComponentStore) FlushDownloadCounts added in v0.19.0

func (p ComponentStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (*ComponentStore) GetComponentByFilename added in v0.15.0

func (p *ComponentStore) GetComponentByFilename(ctx context.Context, repoID string, filename string) (*models.Component, error)

GetComponentByFilename looks up a live package of a repository by its file name.

func (*ComponentStore) GetComponentByID added in v0.15.0

func (p *ComponentStore) GetComponentByID(ctx context.Context, id string) (*models.Component, error)

GetComponentByID looks up a deb or rpm package by its file id.

func (*ComponentStore) GetComponentBySHA256 added in v0.15.0

func (p *ComponentStore) GetComponentBySHA256(ctx context.Context, repoID, sha256 string) (*models.Component, error)

GetComponentBySHA256 finds a live deb or rpm package in a repository by the sha256 of its blob.

func (*ComponentStore) GetComponentsByRepo added in v0.15.0

func (p *ComponentStore) GetComponentsByRepo(ctx context.Context, repoID string) ([]models.Component, error)

GetComponentsByRepo lists the RPM packages of a repository.

func (ComponentStore) GetDB added in v0.15.0

func (p ComponentStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (ComponentStore) Migrate added in v0.15.0

func (p ComponentStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (ComponentStore) Ping added in v0.15.0

func (p ComponentStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (ComponentStore) PoolStat added in v0.15.0

func (p ComponentStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

type ComposerStore added in v0.15.0

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

ComposerStore owns the Composer packages.

Packages live in the generic package tables (repository format "composer"; the mapping is the maintainers' reference, derived from migrations/001_baseline.sql):

packages          one per vendor/package: name = name_key = name as published, attrs {}
package_versions  one per published version: version = the display version
                  ("v1.2.3", "dev-main"), version_key = Composer's normalised
                  version (the live key and the cleanup tie-break text),
                  metadata {"composer_json": <the manifest as uploaded>}
package_files     one primary listed file per version: path
                  "<name>/<version_normalized>/<filename>", filename
                  "<vendor>-<package>-<version>.zip" (the listing expression),
                  attrs {"sha1": <40 hex>} (omitted when empty; sha1 is
                  not in checksums, the checksum search never looked at it)

Composer is not federated: the file carries no unit_key.

func (ComposerStore) AuthCacheGeneration added in v0.15.0

func (p ComposerStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (ComposerStore) AuthCacheTTL added in v0.15.0

func (p ComposerStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (ComposerStore) BeginTx added in v0.15.0

func (p ComposerStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (ComposerStore) Close added in v0.15.0

func (p ComposerStore) Close() error

Close writes the pending download counts and closes the database connection.

func (ComposerStore) CountFileDownload added in v0.19.0

func (p ComposerStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*ComposerStore) CreateComposerPackage added in v0.15.0

func (p *ComposerStore) CreateComposerPackage(ctx context.Context, c *models.ComposerPackage) error

CreateComposerPackage stores one package version. A live version with the same name and normalised version is ErrDuplicate.

func (*ComposerStore) DeleteComposerPackage added in v0.15.0

func (p *ComposerStore) DeleteComposerPackage(ctx context.Context, repoID, id string) error

DeleteComposerPackage removes a package version file; the version and the package go with it when it was their last file.

func (ComposerStore) FlushDownloadCounts added in v0.19.0

func (p ComposerStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (*ComposerStore) GetComposerPackage added in v0.15.0

func (p *ComposerStore) GetComposerPackage(ctx context.Context, repoID, name, versionNormalized string) (*models.ComposerPackage, error)

GetComposerPackage returns the live version of a package, or (nil, nil).

func (*ComposerStore) GetComposerPackageByID added in v0.15.0

func (p *ComposerStore) GetComposerPackageByID(ctx context.Context, repoID, id string) (*models.ComposerPackage, error)

GetComposerPackageByID returns the live package version of the repository with the ID, or (nil, nil).

func (ComposerStore) GetDB added in v0.15.0

func (p ComposerStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*ComposerStore) ListComposerPackageNames added in v0.15.0

func (p *ComposerStore) ListComposerPackageNames(ctx context.Context, repoID string) ([]*models.ComposerPackageName, error)

ListComposerPackageNames returns every package of the repository in name order with the description of its newest live version.

func (*ComposerStore) ListComposerPackageVersions added in v0.15.0

func (p *ComposerStore) ListComposerPackageVersions(ctx context.Context, repoID, name string) ([]*models.ComposerPackage, error)

ListComposerPackageVersions returns every live version of one package, oldest upload first.

func (ComposerStore) Migrate added in v0.15.0

func (p ComposerStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (ComposerStore) Ping added in v0.15.0

func (p ComposerStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (ComposerStore) PoolStat added in v0.15.0

func (p ComposerStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

type ConanStore added in v0.15.0

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

ConanStore owns the Conan recipes and packages.

Conan on the generic package tables (spec: /tmp/oa-plug/schema/104_conan.sql). The grain is one stored FILE of a recipe revision (empty package_id) or of a package (binary) revision of it; all the files of one recipe revision, binary packages included, share one package_versions row.

packages          name = name_key = name
package_versions  version     = version
                  version_key = version@user_channel#recipe_revision (one V per recipe
                                revision; the cleanup worker ranks by
                                split_part(version_key, '#', 1) = version@user_channel)
                  metadata    = {"user_channel": .., "recipe_revision": ..}
package_files     path = name/version@user_channel#rrev/[package_id#package_revision/]filename
                         (encodes the 8 columns of the legacy live-unique key, so
                         uq_package_files_path is that key; a file stored before 0.5.0
                         has filename "" and the path ends in "/")
                  filename  = the full reference name/version@user_channel#rrev for a LISTED
                              row, the file name otherwise (the real file name is always
                              attrs.filename)
                  blob_id   = the file blob, NULL for a row restored without content
                  size_bytes = NULL (the listing size is the blob's)
                  role = primary, for every row
                  listed = package_id = '' AND filename IN ('', 'conanmanifest.txt')
                  attrs = {"release": recipe_revision (omitted when ''), "filename": ..}
                  checksums = {"md5": .., "sha1": ..}, each only when known
conan_files       id -> package_files.id, package_id, package_revision

func (ConanStore) AuthCacheGeneration added in v0.15.0

func (p ConanStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (ConanStore) AuthCacheTTL added in v0.15.0

func (p ConanStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (ConanStore) BeginTx added in v0.15.0

func (p ConanStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (ConanStore) Close added in v0.15.0

func (p ConanStore) Close() error

Close writes the pending download counts and closes the database connection.

func (ConanStore) CountFileDownload added in v0.19.0

func (p ConanStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*ConanStore) CreateConanPackage added in v0.15.0

func (p *ConanStore) CreateConanPackage(ctx context.Context, pkg *models.ConanPackage) error

CreateConanPackage stores one Conan file, replacing the blob and digests of the live row with the same (recipe revision, package id, package revision, filename).

package_files.blob_id is nullable; rows restored from a backup that predates the sha256 field carry only the blob key, which then stands in for the digest.

func (*ConanStore) DeleteConanPackage added in v0.15.0

func (p *ConanStore) DeleteConanPackage(ctx context.Context, id string) error

DeleteConanPackage hard-deletes one live file together with the recipe revision (version) and package it leaves empty.

func (*ConanStore) FindConanPackageBySHA1 added in v0.15.0

func (p *ConanStore) FindConanPackageBySHA1(ctx context.Context, repoID, sha1 string) (*models.ConanPackage, error)

FindConanPackageBySHA1 returns a live file of the repository whose content has the given SHA-1, or (nil, nil).

func (ConanStore) FlushDownloadCounts added in v0.19.0

func (p ConanStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (*ConanStore) GetConanPackage added in v0.15.0

func (p *ConanStore) GetConanPackage(ctx context.Context, repoID string, key models.ConanFileKey) (*models.ConanPackage, error)

GetConanPackage returns the live file stored under key, or (nil, nil).

func (ConanStore) GetDB added in v0.15.0

func (p ConanStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*ConanStore) ListConanRecipeFiles added in v0.15.0

func (p *ConanStore) ListConanRecipeFiles(ctx context.Context, repoID, name, version, userChannel string) ([]*models.ConanPackage, error)

ListConanRecipeFiles returns every live file of one recipe (all its recipe and package revisions), oldest first.

func (*ConanStore) ListConanRecipes added in v0.15.0

func (p *ConanStore) ListConanRecipes(ctx context.Context, repoID string) ([]models.ConanRecipe, error)

ListConanRecipes returns the distinct recipes that have at least one file.

func (ConanStore) Migrate added in v0.15.0

func (p ConanStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (ConanStore) Ping added in v0.15.0

func (p ConanStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (ConanStore) PoolStat added in v0.15.0

func (p ConanStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*ConanStore) SetConanPackageDigests added in v0.15.0

func (p *ConanStore) SetConanPackageDigests(ctx context.Context, id, md5, sha1 string) error

SetConanPackageDigests records the MD5 and SHA-1 of a file stored without them.

type CondaStore added in v0.15.0

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

CondaStore owns the Conda packages.

Mapping onto the generic package tables:

packages          one per package name; name = name_key (case-sensitive)
package_versions  one per BUILD: version = version,
                  version_key = version-build_string|platform,
                  metadata = {build_string, platform}. The .tar.bz2 and the
                  .conda file of a build are two files of one version, so
                  retention ranks a build once.
package_files     one per file: path = platform/filename (live-unique),
                  filename = name-version-build_string<ext>, arch = platform,
                  attrs = {release (build string, omitted when empty),
                  extension, build_number, timestamp_ms, depends (order
                  kept), index_extra}, checksums = {md5} (omitted when
                  empty), role primary, no unit_key (conda is not
                  federated)

Cleanup note: partition (package, arch = platform, part ”), as the former (name, platform) partition with the build as the ranked unit.

func (CondaStore) AuthCacheGeneration added in v0.15.0

func (p CondaStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (CondaStore) AuthCacheTTL added in v0.15.0

func (p CondaStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (CondaStore) BeginTx added in v0.15.0

func (p CondaStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (CondaStore) Close added in v0.15.0

func (p CondaStore) Close() error

Close writes the pending download counts and closes the database connection.

func (*CondaStore) CondaRepodataStamp added in v0.15.0

func (p *CondaStore) CondaRepodataStamp(ctx context.Context, repoID, platform string) (string, error)

CondaRepodataStamp is a cheap validator of one platform's repodata.json: it changes exactly when a live package is added or removed.

func (CondaStore) CountFileDownload added in v0.19.0

func (p CondaStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*CondaStore) CreateCondaPackage added in v0.15.0

func (p *CondaStore) CreateCondaPackage(ctx context.Context, pkg *models.CondaPackage) error

CreateCondaPackage creates a new Conda package file. An empty pkg.Extension is stored as ".tar.bz2" and an empty pkg.Extra as "{}". A live file at the same platform/filename yields ErrDuplicate and is left untouched.

func (*CondaStore) DeleteCondaPackage added in v0.15.0

func (p *CondaStore) DeleteCondaPackage(ctx context.Context, id string) error

DeleteCondaPackage hard-deletes one package file and, when it was the last file of its build, the build and the package.

func (CondaStore) FlushDownloadCounts added in v0.19.0

func (p CondaStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (*CondaStore) GetCondaPackageFile added in v0.15.0

func (p *CondaStore) GetCondaPackageFile(
	ctx context.Context,
	repoID, name, version, buildString, platform, extension string,
) (*models.CondaPackage, error)

GetCondaPackageFile returns the live package file with this exact name, version, build, platform and extension, or nil.

func (CondaStore) GetDB added in v0.15.0

func (p CondaStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*CondaStore) HasCondaPackageName added in v0.15.0

func (p *CondaStore) HasCondaPackageName(ctx context.Context, repoID, name string) (bool, error)

HasCondaPackageName reports whether a live conda package of this name exists in the repository, in any platform.

func (*CondaStore) ListCondaPackageNames added in v0.15.0

func (p *CondaStore) ListCondaPackageNames(ctx context.Context, repoID string) ([]string, error)

ListCondaPackageNames returns the distinct lowercase live package names of a conda repository in every platform.

func (*CondaStore) ListCondaPackages added in v0.15.0

func (p *CondaStore) ListCondaPackages(ctx context.Context, repoID, platform string) ([]*models.CondaPackage, error)

ListCondaPackages lists the live package files of one platform (subdir).

func (CondaStore) Migrate added in v0.15.0

func (p CondaStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (CondaStore) Ping added in v0.15.0

func (p CondaStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (CondaStore) PoolStat added in v0.15.0

func (p CondaStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

type CurationStore added in v0.16.0

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

CurationStore owns the curation rules of proxy repositories.

Rules are read on the request path of every proxy repository that has curation on, so ListCurationRules (the enforcement path; the management API reads ListCurationRulesUncached) goes through the auth cache: a write made through this PostgresDB invalidates it (never stale for a request that starts after the write on this instance); a write by another replica is seen after at most the cache TTL (DB_AUTH_CACHE_TTL_MS, default 2s).

func (CurationStore) AuthCacheGeneration added in v0.16.0

func (p CurationStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (CurationStore) AuthCacheTTL added in v0.16.0

func (p CurationStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (CurationStore) BeginTx added in v0.16.0

func (p CurationStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (CurationStore) Close added in v0.16.0

func (p CurationStore) Close() error

Close writes the pending download counts and closes the database connection.

func (CurationStore) CountFileDownload added in v0.19.0

func (p CurationStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*CurationStore) CreateCurationRule added in v0.16.0

func (p *CurationStore) CreateCurationRule(ctx context.Context, rule *curation.Rule) (*curation.Rule, error)

CreateCurationRule stores rule (Action, Package, Version, Reason, CreatedBy; the repository is rule.RepositoryID) and returns it with its id and time. It fails with ErrCurationRuleLimit past curation.MaxRules rules.

func (*CurationStore) DeleteCurationRule added in v0.16.0

func (p *CurationStore) DeleteCurationRule(ctx context.Context, repoID, id string) error

DeleteCurationRule removes a rule; ErrCurationRuleNotFound when it does not exist in the repository.

func (CurationStore) FlushDownloadCounts added in v0.19.0

func (p CurationStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (*CurationStore) GetCurationRule added in v0.16.0

func (p *CurationStore) GetCurationRule(ctx context.Context, repoID, id string) (*curation.Rule, error)

GetCurationRule returns one rule of a repository, ErrCurationRuleNotFound when the repository has no such rule.

func (CurationStore) GetDB added in v0.16.0

func (p CurationStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*CurationStore) ListCurationRules added in v0.16.0

func (p *CurationStore) ListCurationRules(ctx context.Context, repoID string) ([]curation.Rule, error)

ListCurationRules returns the rules of a repository in creation order, for the enforcement path (see CurationStore). The returned slice is the caller's.

func (*CurationStore) ListCurationRulesUncached added in v0.17.0

func (p *CurationStore) ListCurationRulesUncached(ctx context.Context, repoID string) ([]curation.Rule, error)

ListCurationRulesUncached reads the rules of a repository from the database in creation order, bypassing the auth cache. The management API uses it: a list read after a write must show the write whichever replica served either.

func (CurationStore) Migrate added in v0.16.0

func (p CurationStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (CurationStore) Ping added in v0.16.0

func (p CurationStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (CurationStore) PoolStat added in v0.16.0

func (p CurationStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*CurationStore) UpdateCurationRule added in v0.16.0

func (p *CurationStore) UpdateCurationRule(ctx context.Context, rule *curation.Rule) (*curation.Rule, error)

UpdateCurationRule replaces the action, patterns and reason of the rule rule.ID of rule.RepositoryID; ErrCurationRuleNotFound when it does not exist.

type DatabaseConfig

type DatabaseConfig struct {
	// Driver names the database driver. It must be non-empty; PostgreSQL is
	// the only supported database and the server always connects to it.
	Driver string `yaml:"driver"`
	// Host is the database host.
	Host string `yaml:"host"`
	// Port is the database port.
	Port int `yaml:"port"`
	// User is the database user.
	User string `yaml:"user"`
	// Password is the database password. The CHANGE_ME placeholder of the
	// example files is rejected at startup.
	Password string `yaml:"password"`
	// Database is the database name.
	Database string `yaml:"database"`
	// SSLMode is the PostgreSQL sslmode; disable only for local development
	// without TLS.
	SSLMode string `yaml:"sslMode"`
	// Options are extra libpq connection parameters. The environment form is
	// comma-separated key=value pairs, merged over the YAML keys.
	Options map[string]string `yaml:"options"`
	// MaxOpenConns is the size limit of each of the two connection pools (pgx
	// and database/sql), so one replica can hold up to twice this many
	// PostgreSQL connections: size max_connections for
	// replicas x 2 x maxOpenConns. 0 means the driver default; otherwise at
	// least 2 (a blob-lock transaction pins one connection and its callback
	// needs another), and at least 4 while tiering.enabled is true.
	MaxOpenConns int `yaml:"maxOpenConns"`
	// MaxIdleConns is how many idle connections the pool keeps warm.
	MaxIdleConns int `yaml:"maxIdleConns"`
	// ConnMaxLifetimeMinutes is the maximum lifetime of a connection, in minutes.
	ConnMaxLifetimeMinutes int `yaml:"connMaxLifetimeMinutes"`
	// AuthCacheTTLMillis is how long, in milliseconds, per-request
	// authentication lookups (token, user, groups, permission targets,
	// repository by name) are served from memory. Writes through this process
	// invalidate immediately; other replicas observe a change after at most
	// this long. 0 disables the cache.
	AuthCacheTTLMillis int `yaml:"authCacheTtlMs"`
	// DownloadCountFlushInterval is how often the batched package download
	// counters (cargo, nuget, apk, nix, terraform) are written to the database.
	// A download shows in the counter within this long; 0 means 5s.
	DownloadCountFlushInterval time.Duration `yaml:"downloadCountFlushInterval"`
	// ConnectTimeout is how long startup keeps retrying the initial database
	// connection (capped exponential backoff) before giving up. 0 fails at the
	// first error.
	ConnectTimeout time.Duration `yaml:"connectTimeout"`
}

DatabaseConfig contains database connection configuration.

type DebStore added in v0.15.0

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

DebStore owns the Debian format tables: distributions, components, architectures and package control data.

A deb package lives on the generic package tables (packages P, package_versions V, package_files F) plus the side table deb_files. Grain 1:1: one .deb (name, version, arch, component) is one P (shared by name), one V and one F. The mapping, field by field:

P  name, name_key = Package (not normalised); attrs = {}
V  version        = Version as published (may carry an epoch)
   version_key    = version|arch|component_id (every coordinate of the legacy live key
                    that is not the package identity)
   metadata       = {summary, description, license, maintainer, homepage} (empty = absent)
F  path           = pool/<component>/<prefix>/<name>/<file>, file = filename or
                    name_version_arch.deb when the filename is empty (pkgdeb.PoolPath);
                    live paths are unique, and every writer refuses a second live row with
                    the same filename, so a violation is a conflict (ErrDuplicate)
   filename, arch = Filename, Architecture; blob_id = the .deb blob; size_bytes = NULL
   part           = distribution_id (the cleanup partition is name, arch, distribution)
   attrs          = {installed_size} (only when not zero); checksums = {}
deb_files (id = F.id): distribution_id, component_id, control_fields (the Packages stanza
   map, written in the transaction of the row by CreateDebPackage, read whole by Packages
   generation)

The distribution graph (debian_distributions/components/architectures) is untouched.

func (DebStore) AuthCacheGeneration added in v0.15.0

func (p DebStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (DebStore) AuthCacheTTL added in v0.15.0

func (p DebStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (DebStore) BeginTx added in v0.15.0

func (p DebStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (DebStore) Close added in v0.15.0

func (p DebStore) Close() error

Close writes the pending download counts and closes the database connection.

func (DebStore) CountFileDownload added in v0.19.0

func (p DebStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*DebStore) CreateDebPackage added in v0.15.0

func (p *DebStore) CreateDebPackage(ctx context.Context, pkg *models.Component, distID, compID string, ctl models.DebControl) error

CreateDebPackage inserts a DEB package with distribution and component references and its control data. The row, the control stanza and the maintainer/homepage commit together: a metadata regeneration that runs while an upload is in flight sees the package complete or not at all. A live package with the same name, version, architecture and component, or the same pool path, is ErrDuplicate.

func (*DebStore) CreateDebianArchitecture added in v0.15.0

func (p *DebStore) CreateDebianArchitecture(ctx context.Context, arch *models.DebianArchitecture) error

func (*DebStore) CreateDebianComponent added in v0.15.0

func (p *DebStore) CreateDebianComponent(ctx context.Context, comp *models.DebianComponent) error

func (*DebStore) CreateDebianDistribution added in v0.15.0

func (p *DebStore) CreateDebianDistribution(ctx context.Context, dist *models.DebianDistribution) error

func (DebStore) FlushDownloadCounts added in v0.19.0

func (p DebStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (DebStore) GetDB added in v0.15.0

func (p DebStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*DebStore) GetDebBlobInfo added in v0.15.0

func (p *DebStore) GetDebBlobInfo(ctx context.Context, blobID string) (string, int64, error)

GetDebBlobInfo resolves a blobs.id UUID to its content sha256 and size ("" / 0 if unknown).

func (*DebStore) GetDebPackageByID added in v0.15.0

func (p *DebStore) GetDebPackageByID(ctx context.Context, id string) (*models.DebPackage, error)

GetDebPackageByID fetches a live DEB package by its primary key, or (nil, nil).

func (*DebStore) GetDebianArchitecturesByDist added in v0.15.0

func (p *DebStore) GetDebianArchitecturesByDist(ctx context.Context, distID string) ([]models.DebianArchitecture, error)

func (*DebStore) GetDebianComponentsByDist added in v0.15.0

func (p *DebStore) GetDebianComponentsByDist(ctx context.Context, distID string) ([]models.DebianComponent, error)

func (*DebStore) GetDebianDistributionsByRepo added in v0.15.0

func (p *DebStore) GetDebianDistributionsByRepo(ctx context.Context, repoID string) ([]models.DebianDistribution, error)

func (*DebStore) GetDebianPackageByFilename added in v0.15.0

func (p *DebStore) GetDebianPackageByFilename(ctx context.Context, repoID string, filename string) (*models.Component, error)

func (*DebStore) GetDebianPackagesByDistComp added in v0.15.0

func (p *DebStore) GetDebianPackagesByDistComp(
	ctx context.Context,
	repoID string,
	dist string,
	comp string,
	arch string,
) ([]models.Component, error)

func (*DebStore) GetOrCreateDebianArchitecture added in v0.15.0

func (p *DebStore) GetOrCreateDebianArchitecture(ctx context.Context, distID, name string) (*models.DebianArchitecture, error)

GetOrCreateDebianArchitecture returns the architecture, creating it atomically if missing.

func (*DebStore) GetOrCreateDebianComponent added in v0.15.0

func (p *DebStore) GetOrCreateDebianComponent(ctx context.Context, distID, name string) (*models.DebianComponent, error)

GetOrCreateDebianComponent returns the component, creating it atomically if missing.

func (*DebStore) GetOrCreateDebianDistribution added in v0.15.0

func (p *DebStore) GetOrCreateDebianDistribution(ctx context.Context, repoID, name string) (*models.DebianDistribution, error)

GetOrCreateDebianDistribution returns the distribution, creating it atomically if missing.

func (*DebStore) ListDebPackageEntries added in v0.15.0

func (p *DebStore) ListDebPackageEntries(ctx context.Context, repoID, dist, comp, arch string) ([]models.DebPackageEntry, error)

ListDebPackageEntries returns package entries for a repository in a single query. Empty dist/comp/arch act as wildcards.

func (*DebStore) ListDebPackageStamps added in v0.19.0

func (p *DebStore) ListDebPackageStamps(ctx context.Context, repoID string) ([]models.DebPackageStamp, error)

ListDebPackageStamps returns the live package files of a hosted deb repository without their control fields, in the order of ListDebPackageEntries (distribution, component, architecture, name, version). A deb group keeps the stanza it rendered for a file under its stamp and reads the controls of the files it has no stanza for with ListDebPackagesWithControls.

func (*DebStore) ListDebPackagesByRepo added in v0.15.0

func (p *DebStore) ListDebPackagesByRepo(ctx context.Context, repoID string) ([]*models.DebPackage, error)

ListDebPackagesByRepo lists all DEB packages in a repository.

func (*DebStore) ListDebPackagesWithControls added in v0.19.0

func (p *DebStore) ListDebPackagesWithControls(ctx context.Context, repoID string, ids []string) ([]models.DebPackageStamp, error)

ListDebPackagesWithControls returns the live package files of the repository among ids with their control fields, in no particular order. A file that was deleted since the caller listed it is absent.

func (DebStore) Migrate added in v0.15.0

func (p DebStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (DebStore) Ping added in v0.15.0

func (p DebStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (DebStore) PoolStat added in v0.15.0

func (p DebStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

type DeclarativeStore added in v0.15.0

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

DeclarativeStore owns the objects managed by declarative configuration.

func (DeclarativeStore) AuthCacheGeneration added in v0.15.0

func (p DeclarativeStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (DeclarativeStore) AuthCacheTTL added in v0.15.0

func (p DeclarativeStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (DeclarativeStore) BeginTx added in v0.15.0

func (p DeclarativeStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (DeclarativeStore) Close added in v0.15.0

func (p DeclarativeStore) Close() error

Close writes the pending download counts and closes the database connection.

func (DeclarativeStore) CountFileDownload added in v0.19.0

func (p DeclarativeStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*DeclarativeStore) DeleteDeclarativeObject added in v0.15.0

func (p *DeclarativeStore) DeleteDeclarativeObject(ctx context.Context, kind, name string) (bool, error)

DeleteDeclarativeObject removes one marker and reports whether it existed.

func (DeclarativeStore) FlushDownloadCounts added in v0.19.0

func (p DeclarativeStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (DeclarativeStore) GetDB added in v0.15.0

func (p DeclarativeStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*DeclarativeStore) ListDeclarativeObjects added in v0.15.0

func (p *DeclarativeStore) ListDeclarativeObjects(ctx context.Context) ([]models.DeclarativeObject, error)

ListDeclarativeObjects returns every ownership marker, ordered by kind and name.

func (DeclarativeStore) Migrate added in v0.15.0

func (p DeclarativeStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (DeclarativeStore) Ping added in v0.15.0

func (p DeclarativeStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (DeclarativeStore) PoolStat added in v0.15.0

func (p DeclarativeStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*DeclarativeStore) UpsertDeclarativeObjects added in v0.15.0

func (p *DeclarativeStore) UpsertDeclarativeObjects(
	ctx context.Context,
	items []models.DeclarativeObject,
) ([]models.DeclarativeObject, error)

UpsertDeclarativeObjects stores the markers by (kind, name) in one transaction and returns them as stored.

type DeltaStore added in v0.15.0

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

DeltaStore owns package deltas.

func (DeltaStore) AuthCacheGeneration added in v0.15.0

func (p DeltaStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (DeltaStore) AuthCacheTTL added in v0.15.0

func (p DeltaStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (DeltaStore) BeginTx added in v0.15.0

func (p DeltaStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (DeltaStore) Close added in v0.15.0

func (p DeltaStore) Close() error

Close writes the pending download counts and closes the database connection.

func (DeltaStore) CountFileDownload added in v0.19.0

func (p DeltaStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*DeltaStore) CreatePackageDelta added in v0.15.0

func (p *DeltaStore) CreatePackageDelta(ctx context.Context, d *models.PackageDelta) error

func (DeltaStore) FlushDownloadCounts added in v0.19.0

func (p DeltaStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (DeltaStore) GetDB added in v0.15.0

func (p DeltaStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*DeltaStore) GetPackageDelta added in v0.15.0

func (p *DeltaStore) GetPackageDelta(ctx context.Context, repoID, fromSHA256, toSHA256 string) (*models.PackageDelta, error)

func (*DeltaStore) ListPackageDeltas added in v0.15.0

func (p *DeltaStore) ListPackageDeltas(ctx context.Context, repoID, toSHA256 string) ([]*models.PackageDelta, error)

ListPackageDeltas returns the deltas that target toSHA256. A delta whose source package is in the trash is hidden (it would reveal the trashed file's sha256 and name) and reappears when the source is restored; a source that still has a live row (same blob in another row) keeps its deltas visible.

func (DeltaStore) Migrate added in v0.15.0

func (p DeltaStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (DeltaStore) Ping added in v0.15.0

func (p DeltaStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (DeltaStore) PoolStat added in v0.15.0

func (p DeltaStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*DeltaStore) PruneRepoDeltas added in v0.15.0

func (p *DeltaStore) PruneRepoDeltas(ctx context.Context, repoID string, maxCount int, maxBytes int64) ([]string, error)

PruneRepoDeltas deletes the oldest package_deltas rows of a repository until at most maxCount rows totalling at most maxBytes remain, and returns the delta blob sha256s of the deleted rows (callers release them through storage.SafeDeleteBlob once the rows are gone).

type DependencyTrackStore added in v0.15.0

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

DependencyTrackStore owns the per-repository Dependency-Track settings and push records.

func (DependencyTrackStore) AuthCacheGeneration added in v0.15.0

func (p DependencyTrackStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (DependencyTrackStore) AuthCacheTTL added in v0.15.0

func (p DependencyTrackStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (DependencyTrackStore) BeginTx added in v0.15.0

func (p DependencyTrackStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (DependencyTrackStore) Close added in v0.15.0

func (p DependencyTrackStore) Close() error

Close writes the pending download counts and closes the database connection.

func (DependencyTrackStore) CountFileDownload added in v0.19.0

func (p DependencyTrackStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*DependencyTrackStore) DeleteRepositoryDependencyTrack added in v0.15.0

func (p *DependencyTrackStore) DeleteRepositoryDependencyTrack(ctx context.Context, repoID string) (bool, error)

DeleteRepositoryDependencyTrack removes the override; it reports whether one existed.

func (DependencyTrackStore) FlushDownloadCounts added in v0.19.0

func (p DependencyTrackStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (DependencyTrackStore) GetDB added in v0.15.0

func (p DependencyTrackStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*DependencyTrackStore) GetDependencyTrackPush added in v0.15.0

func (p *DependencyTrackStore) GetDependencyTrackPush(ctx context.Context, repoID, artifactID string) (*models.DependencyTrackPush, error)

GetDependencyTrackPush returns the push state of an artifact, nil when it was never pushed.

func (*DependencyTrackStore) GetRepositoryDependencyTrack added in v0.15.0

func (p *DependencyTrackStore) GetRepositoryDependencyTrack(ctx context.Context, repoID string) (*models.RepositoryDependencyTrack, error)

GetRepositoryDependencyTrack returns the repository's override, nil when none is set.

func (*DependencyTrackStore) LatestFinishedDependencyTrackPush added in v0.15.0

func (p *DependencyTrackStore) LatestFinishedDependencyTrackPush(ctx context.Context) (*models.DependencyTrackLastPush, error)

LatestFinishedDependencyTrackPush returns the outcome of the most recent finished push of any artifact, nil when none finished yet.

func (*DependencyTrackStore) ListDependencyTrackPushes added in v0.15.0

func (p *DependencyTrackStore) ListDependencyTrackPushes(
	ctx context.Context,
	repoID string,
	limit int,
) ([]*models.DependencyTrackPush, error)

ListDependencyTrackPushes lists the pushes of a repository, most recently updated first.

func (DependencyTrackStore) Migrate added in v0.15.0

func (p DependencyTrackStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (DependencyTrackStore) Ping added in v0.15.0

func (p DependencyTrackStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (DependencyTrackStore) PoolStat added in v0.15.0

func (p DependencyTrackStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*DependencyTrackStore) UpsertDependencyTrackPush added in v0.15.0

func (p *DependencyTrackStore) UpsertDependencyTrackPush(ctx context.Context, s *models.DependencyTrackPush) error

UpsertDependencyTrackPush records the state of an artifact's push and fills the stored row back into s.

func (*DependencyTrackStore) UpsertRepositoryDependencyTrack added in v0.15.0

func (p *DependencyTrackStore) UpsertRepositoryDependencyTrack(ctx context.Context, c *models.RepositoryDependencyTrack) error

UpsertRepositoryDependencyTrack stores the override and fills the stored row back into c.

type DockerBlobDeletion added in v0.20.0

type DockerBlobDeletion int

DockerBlobDeletion is what DeleteDockerBlobFromImage did.

const (
	// DockerBlobUnlinked: the image no longer reaches the blob, but other
	// images or manifests still hold the repository's record of it.
	DockerBlobUnlinked DockerBlobDeletion = iota + 1
	// DockerBlobRemoved: nothing held the blob, so the repository's record is
	// gone. The caller releases its storage quota and bytes.
	DockerBlobRemoved
	// DockerBlobInUse: a live manifest of the image references the blob (or the
	// blob has no image link and another image's manifest does); nothing was
	// changed.
	DockerBlobInUse
)

type DockerBlobImages added in v0.5.0

type DockerBlobImages interface {
	// DockerBlobVisible reports whether the image may serve and reference the
	// blob: it is linked to the image, or it predates image links and has none.
	DockerBlobVisible(ctx context.Context, repoID, image, digest string) (bool, error)
	// LinkDockerBlob links a blob the repository holds to the image.
	LinkDockerBlob(ctx context.Context, repoID, image, digest string) error
}

DockerBlobImages is implemented by databases that track which images of a repository a blob belongs to, so RBAC path_pattern scoped to one image also scopes the blob digests it can read and reference.

type DockerBlobToucher added in v0.4.0

type DockerBlobToucher interface {
	// TouchDockerBlob records a use of the blob and reports false when the
	// repository no longer has it.
	TouchDockerBlob(ctx context.Context, repoID, digest string) (bool, error)
}

DockerBlobToucher is implemented by databases that track when a registry blob was last used, so registry GC keeps recently used blobs.

type DockerBlobTrash added in v0.8.0

type DockerBlobTrash interface {
	// DockerBlobInTrash reports whether manifests of the repository reference
	// the blob and every one of them is in the trash.
	DockerBlobInTrash(ctx context.Context, repoID, digest string) (bool, error)
}

DockerBlobTrash is implemented by databases that can tell whether a blob is held only by trashed manifests.

type DockerCatalog added in v0.8.0

type DockerCatalog interface {
	// ListDockerCatalog returns up to limit catalog names after the given one
	// ("" starts at the beginning), ordered bytewise by distribution name.
	ListDockerCatalog(ctx context.Context, after string, limit int) ([]*models.DockerCatalogEntry, error)
}

DockerCatalog is implemented by databases that can list the images of every docker repository for the registry's /v2/_catalog.

type DockerGCStore added in v0.4.0

type DockerGCStore interface {
	// ListUnindexedDockerManifests returns up to limit manifests of the
	// repository whose references have not been recorded yet, leaving out the
	// manifests in skipIDs (ones the caller could not index this run).
	ListUnindexedDockerManifests(ctx context.Context, repoID string, skipIDs []string, limit int) ([]*models.DockerGCManifest, error)

	// SetDockerManifestRefs records the references of a manifest body and marks
	// the manifest indexed. A manifest deleted meanwhile is skipped silently.
	SetDockerManifestRefs(ctx context.Context, repoID string, m *models.DockerGCManifest, refs models.DockerManifestRefs) error

	// ListDockerGCManifests returns every live manifest of the repository with its
	// tagged/young flags (young: pushed within grace), index children and, for a
	// manifest held by dependent tags (cosign .sig/.att/.sbom/.src, referrers tag
	// schema), the subject digests of those tags.
	ListDockerGCManifests(ctx context.Context, repoID string, grace time.Duration) ([]*models.DockerGCManifest, error)

	// DeleteDockerManifestsForGC deletes the given manifests (by row id) that
	// are still older than grace, untagged (a dependent tag whose subject is
	// absent or among ids does not count) and not adjacent to a manifest outside
	// ids, together with their dependent tags, and returns the ones actually deleted.
	DeleteDockerManifestsForGC(ctx context.Context, repoID string, ids []string, grace time.Duration) ([]*models.DockerGCManifest, error)

	// ExpireDockerManifests deletes the live manifests whose quay.expires-after
	// deadline has passed, with every tag that points at them, their referrers,
	// the manifests held only by their cosign/referrers dependent tags and the
	// children of a deleted index nothing else lists, bypassing the grace period.
	// A manifest a release bundle pins, and a child of a live index that stays, are
	// left. With dryRun it only reports what it would delete.
	ExpireDockerManifests(ctx context.Context, repoID string, dryRun bool) ([]*models.DockerGCManifest, error)

	// ListDockerGCBlobs returns up to limit blob records of the repository that
	// no manifest other than excludeManifestIDs references and that have not
	// been used within grace.
	ListDockerGCBlobs(
		ctx context.Context,
		repoID string,
		grace time.Duration,
		excludeManifestIDs []string,
		limit int,
	) ([]*models.DockerGCBlob, error)

	// DeleteDockerBlobsForGC deletes the given blob records (by digest) that are
	// still unreferenced and unused within grace, and returns the ones actually
	// deleted. The caller removes the underlying blobs with storage.SafeDeleteBlob.
	DeleteDockerBlobsForGC(ctx context.Context, repoID string, digests []string, grace time.Duration) ([]*models.DockerGCBlob, error)

	// BlobRowExists reports whether the global blobs table still has sha256.
	BlobRowExists(ctx context.Context, sha256 string) (bool, error)
}

DockerGCStore is the storage side of Docker registry garbage collection (internal/worker.DockerGCWorker). PostgresDB implements it; the worker reports GC as unsupported for databases that do not.

Soft-deleted (trashed) manifests are not GC candidates (purge removes them), but their recorded references keep counting: layers and child manifests that a trashed manifest references are never collected, and a live manifest that a trashed tag points at stays "tagged" until that tag is purged, so restoring from the trash never yields a dangling reference.

Mutations take the repository's exclusive docker lock for the length of one transaction. CreateDockerManifest takes the same lock shared, so a push either completes before a GC transaction starts (and its references are then visible to it) or starts after it ends.

type DockerStore added in v0.15.0

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

DockerStore owns the OCI/Docker tables: blobs, uploads, manifests, tags, the catalog and garbage collection.

func (*DockerStore) AcquireDockerUploadLease added in v0.19.0

func (p *DockerStore) AcquireDockerUploadLease(
	ctx context.Context,
	repositoryID, image, uploadUUID, token string,
	ttl time.Duration,
) (*models.DockerUpload, error)

AcquireDockerUploadLease takes the session's lease for token (a UUID) for ttl and returns the session as it stands, so the caller starts from the committed position. It returns nil when the session does not exist for image or another live lease holds it.

func (*DockerStore) AdvanceDockerUpload added in v0.19.0

func (p *DockerStore) AdvanceDockerUpload(
	ctx context.Context,
	repositoryID, uploadUUID, token string,
	oldOffset, newOffset int64,
	hashState []byte,
	stageState string,
	ttl time.Duration,
	keepLease bool,
) (bool, error)

AdvanceDockerUpload moves the session from oldOffset to newOffset and records hashState and stageState with it, in one compare-and-set statement. keepLease extends the lease held by token to ttl; otherwise the lease is released with the move. It reports whether the session moved: false means the lease was lost, the offset is not oldOffset, or the session is gone, and nothing changed.

func (DockerStore) AuthCacheGeneration added in v0.15.0

func (p DockerStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (DockerStore) AuthCacheTTL added in v0.15.0

func (p DockerStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (DockerStore) BeginTx added in v0.15.0

func (p DockerStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (*DockerStore) BlobRowExists added in v0.15.0

func (p *DockerStore) BlobRowExists(ctx context.Context, sha256 string) (bool, error)

func (DockerStore) Close added in v0.15.0

func (p DockerStore) Close() error

Close writes the pending download counts and closes the database connection.

func (DockerStore) CountFileDownload added in v0.19.0

func (p DockerStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*DockerStore) CreateDockerBlob added in v0.15.0

func (p *DockerStore) CreateDockerBlob(ctx context.Context, blob *models.DockerBlob) error

CreateDockerBlob upserts the blob's content into the global blobs table (docker_blobs.blob_id FKs into blobs, which holds the media type, size and sha256) and inserts the per-repo docker_blobs registry row referencing it. blob.Inserted reports whether the repository's row is new (false: it already held the blob).

func (*DockerStore) CreateDockerManifest added in v0.15.0

func (p *DockerStore) CreateDockerManifest(ctx context.Context, m *models.DockerManifest) error

CreateDockerManifest upserts the manifest row. When m.Refs is set, the references of the manifest body are recorded in the same transaction, under the shared per-repository docker lock that registry GC takes exclusively before it deletes anything: GC then sees either none of this push or all of it, never a manifest whose references it cannot see yet. m.Inserted reports whether the live row is new (false: a re-push refreshed the existing one).

func (*DockerStore) CreateDockerUpload added in v0.15.0

func (p *DockerStore) CreateDockerUpload(ctx context.Context, upload *models.DockerUpload) error

func (*DockerStore) DeleteDockerBlobFromImage added in v0.20.0

func (p *DockerStore) DeleteDockerBlobFromImage(ctx context.Context, repoID, image, digest string) (DockerBlobDeletion, error)

DeleteDockerBlobFromImage deletes the blob for one image: it drops the image's link, and the repository's record of the blob only when no other image link and no manifest holds it. A blob a live manifest of the image references is refused with DockerBlobInUse. It returns ErrDockerRowNotFound when the record vanished meanwhile. It runs under the repository's exclusive docker lock, so a concurrent manifest push cannot reference the blob between the checks and the delete.

func (*DockerStore) DeleteDockerBlobsForGC added in v0.15.0

func (p *DockerStore) DeleteDockerBlobsForGC(
	ctx context.Context,
	repoID string,
	digests []string,
	grace time.Duration,
) ([]*models.DockerGCBlob, error)

func (*DockerStore) DeleteDockerManifest added in v0.15.0

func (p *DockerStore) DeleteDockerManifest(ctx context.Context, repoID, image, digest string) error

DeleteDockerManifest permanently removes the live manifest row and returns ErrDockerRowNotFound when there was none.

func (*DockerStore) DeleteDockerManifestsForGC added in v0.15.0

func (p *DockerStore) DeleteDockerManifestsForGC(
	ctx context.Context,
	repoID string,
	ids []string,
	grace time.Duration,
) ([]*models.DockerGCManifest, error)

func (*DockerStore) DeleteDockerTag added in v0.15.0

func (p *DockerStore) DeleteDockerTag(ctx context.Context, repoID, image, name string) error

func (*DockerStore) DeleteDockerTagsByDigest added in v0.15.0

func (p *DockerStore) DeleteDockerTagsByDigest(ctx context.Context, repoID, image, digest string) error

DeleteDockerTagsByDigest removes every tag of the image that points at digest.

func (*DockerStore) DeleteDockerUpload added in v0.15.0

func (p *DockerStore) DeleteDockerUpload(ctx context.Context, repositoryID, uploadUUID string) error

func (*DockerStore) DeleteStaleDockerUploads added in v0.15.0

func (p *DockerStore) DeleteStaleDockerUploads(ctx context.Context, cutoff time.Time) ([]string, error)

DeleteStaleDockerUploads deletes the upload sessions idle since before the cutoff and returns their UUIDs.

func (*DockerStore) DockerBlobInTrash added in v0.15.0

func (p *DockerStore) DockerBlobInTrash(ctx context.Context, repoID, digest string) (bool, error)

func (*DockerStore) DockerBlobQuarantined added in v0.15.0

func (p *DockerStore) DockerBlobQuarantined(ctx context.Context, repoID, digest string) (bool, error)

DockerBlobQuarantined reports whether a live manifest of the repository that references the blob is quarantined (see the query for the keys).

func (*DockerStore) DockerBlobVisible added in v0.15.0

func (p *DockerStore) DockerBlobVisible(ctx context.Context, repoID, image, digest string) (bool, error)

func (*DockerStore) DockerImageExists added in v0.15.0

func (p *DockerStore) DockerImageExists(ctx context.Context, repoID, image string) (bool, error)

DockerImageExists reports whether the image holds a live manifest.

func (*DockerStore) ExistingDockerUploadIDs added in v0.19.0

func (p *DockerStore) ExistingDockerUploadIDs(ctx context.Context, ids []string) ([]string, error)

ExistingDockerUploadIDs returns the ids among ids that are the upload UUID of a live session.

func (*DockerStore) ExpireDockerManifests added in v0.21.0

func (p *DockerStore) ExpireDockerManifests(ctx context.Context, repoID string, dryRun bool) ([]*models.DockerGCManifest, error)

func (DockerStore) FlushDownloadCounts added in v0.19.0

func (p DockerStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (DockerStore) GetDB added in v0.15.0

func (p DockerStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*DockerStore) GetDockerBlob added in v0.15.0

func (p *DockerStore) GetDockerBlob(ctx context.Context, repoID, digest string) (*models.DockerBlob, error)

func (*DockerStore) GetDockerManifest added in v0.15.0

func (p *DockerStore) GetDockerManifest(ctx context.Context, repoID, image, digest string) (*models.DockerManifest, error)

func (*DockerStore) GetDockerTag added in v0.15.0

func (p *DockerStore) GetDockerTag(ctx context.Context, repoID, image, name string) (*models.DockerTag, error)

func (*DockerStore) GetDockerUpload added in v0.15.0

func (p *DockerStore) GetDockerUpload(ctx context.Context, repositoryID, image, uploadUUID string) (*models.DockerUpload, error)

GetDockerUpload returns the session started for image in the repository, nil when there is none: a session asked through another image, or one that predates the image column, does not exist for the caller.

func (*DockerStore) LinkDockerBlob added in v0.15.0

func (p *DockerStore) LinkDockerBlob(ctx context.Context, repoID, image, digest string) error

func (*DockerStore) ListDockerBlobs added in v0.15.0

func (p *DockerStore) ListDockerBlobs(ctx context.Context, repoID string) ([]*models.DockerBlob, error)

func (*DockerStore) ListDockerCatalog added in v0.15.0

func (p *DockerStore) ListDockerCatalog(ctx context.Context, after string, limit int) ([]*models.DockerCatalogEntry, error)

func (*DockerStore) ListDockerGCBlobs added in v0.15.0

func (p *DockerStore) ListDockerGCBlobs(
	ctx context.Context,
	repoID string,
	grace time.Duration,
	excludeManifestIDs []string,
	limit int,
) ([]*models.DockerGCBlob, error)

func (*DockerStore) ListDockerGCManifests added in v0.15.0

func (p *DockerStore) ListDockerGCManifests(ctx context.Context, repoID string, grace time.Duration) ([]*models.DockerGCManifest, error)

func (*DockerStore) ListDockerManifestsByRepo added in v0.15.0

func (p *DockerStore) ListDockerManifestsByRepo(ctx context.Context, repoID string) ([]*models.DockerManifest, error)

ListDockerManifestsByRepo lists every manifest for a repository, with its blob's sha256 resolved via a JOIN (unlike BlobID above, which is the raw, restore-incompatible blobs.id UUID). Used only by backup export.

func (*DockerStore) ListDockerManifestsBySubject added in v0.15.0

func (p *DockerStore) ListDockerManifestsBySubject(
	ctx context.Context,
	repoID, image, subjectDigest string,
) ([]*models.DockerManifest, error)

ListDockerManifestsBySubject returns manifests in repoID whose OCI `subject` field points at subjectDigest, for the Referrers API (GET /v2/<name>/referrers/<digest>). No sqlc query exists for this lookup, so it runs directly against p.db.

func (*DockerStore) ListDockerTagIDsByDigest added in v0.15.0

func (p *DockerStore) ListDockerTagIDsByDigest(ctx context.Context, repoID, image, digest string) ([]string, error)

ListDockerTagIDsByDigest returns the ids of the live tags of the image that point at digest: the identifiers a scan of the image is recorded under.

func (*DockerStore) ListDockerTags added in v0.15.0

func (p *DockerStore) ListDockerTags(ctx context.Context, repoID, image, last string, n int) ([]*models.DockerTag, error)

func (*DockerStore) ListDockerTagsByRepo added in v0.15.0

func (p *DockerStore) ListDockerTagsByRepo(ctx context.Context, repoID string, limit int) ([]*models.DockerTag, error)

ListDockerTagsByRepo lists tags across every image of a repository, for backup export.

func (*DockerStore) ListUnindexedDockerManifests added in v0.15.0

func (p *DockerStore) ListUnindexedDockerManifests(
	ctx context.Context,
	repoID string,
	skipIDs []string,
	limit int,
) ([]*models.DockerGCManifest, error)

func (DockerStore) Migrate added in v0.15.0

func (p DockerStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (DockerStore) Ping added in v0.15.0

func (p DockerStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (DockerStore) PoolStat added in v0.15.0

func (p DockerStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*DockerStore) ReleaseDockerUploadLease added in v0.19.0

func (p *DockerStore) ReleaseDockerUploadLease(ctx context.Context, repositoryID, uploadUUID, token string) error

ReleaseDockerUploadLease clears the lease if token still holds it; it is not an error when it does not.

func (*DockerStore) RenewDockerUploadLease added in v0.19.0

func (p *DockerStore) RenewDockerUploadLease(
	ctx context.Context,
	repositoryID, uploadUUID, token string,
	ttl time.Duration,
) (bool, error)

RenewDockerUploadLease extends the lease held by token to ttl from now. It reports false when the lease is no longer held (expired and taken over, or the session is gone).

func (*DockerStore) SetDockerManifestRefs added in v0.15.0

func (p *DockerStore) SetDockerManifestRefs(
	ctx context.Context,
	repoID string,
	m *models.DockerGCManifest,
	refs models.DockerManifestRefs,
) error

func (*DockerStore) TouchDockerBlob added in v0.15.0

func (p *DockerStore) TouchDockerBlob(ctx context.Context, repoID, digest string) (bool, error)

TouchDockerBlob records that a client has just relied on the blob (HEAD probe, re-push, mount), so registry GC keeps it for its grace period. It reports false when the repository no longer has the blob.

func (*DockerStore) UpsertDockerTag added in v0.15.0

func (p *DockerStore) UpsertDockerTag(ctx context.Context, tag *models.DockerTag) error

type DockerUploadSweepStore added in v0.5.0

type DockerUploadSweepStore interface {
	DeleteStaleDockerUploads(ctx context.Context, cutoff time.Time) ([]string, error)
	ExistingDockerUploadIDs(ctx context.Context, ids []string) ([]string, error)
}

DockerUploadSweepStore is implemented by PostgresDB; the upload sweeper reports itself unsupported for databases that do not.

type ExploitCatalog added in v0.15.0

type ExploitCatalog interface {
	// ExploitSignals returns the KEV entry and EPSS score of each of the given
	// upper-case CVE ids that a feed lists; the others are absent from the map.
	ExploitSignals(ctx context.Context, cves []string) (map[string]models.ExploitSignal, error)
	// ExploitFeedStates returns the state of the feeds by name; a feed that was
	// never checked is absent.
	ExploitFeedStates(ctx context.Context) (map[string]models.ExploitFeedState, error)
	// ReplaceKEV makes entries the whole catalog, and records state (name, source,
	// version, publication date, validators) with the import time, in one transaction.
	ReplaceKEV(ctx context.Context, entries []models.KEVEntry, state models.ExploitFeedState) error
	// ReplaceEPSS makes the scores next yields until io.EOF the whole EPSS table
	// (updating the rows that exist, deleting the ones absent), and records state,
	// in one transaction. It returns the number of scores. A failure of next
	// leaves the table unchanged.
	ReplaceEPSS(ctx context.Context, state models.ExploitFeedState, next func() (models.EPSSScore, error)) (int, error)
	// RecordExploitFeedCheck stamps a check of a feed that did not replace its data:
	// the source answered "not modified" (errMsg empty) or the check failed.
	RecordExploitFeedCheck(ctx context.Context, name, sourceURL, errMsg string, checkedAt time.Time) error
	// ListVulnExploitCandidates returns up to limit stored vulnerability results with
	// findings, in id order, after the result with id afterID ("" starts at the beginning).
	ListVulnExploitCandidates(ctx context.Context, afterID string, limit int) ([]models.VulnExploitCandidate, error)
	// UpdateVulnExploitAggregates stores recomputed aggregates; results whose values
	// did not change are not written. It returns the number of rows changed.
	UpdateVulnExploitAggregates(ctx context.Context, aggs []models.VulnExploitAggregate) (int, error)
}

ExploitCatalog keeps the CISA KEV catalog and the FIRST EPSS scores and the per-result aggregates derived from them. It is implemented by *PostgresDB and found by the feed worker and the API with a type assertion on Database.

type ExploitStore added in v0.14.0

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

ExploitStore owns the exploit feed state (CISA KEV, EPSS) and the exploit aggregates of scan results.

func (ExploitStore) AuthCacheGeneration added in v0.15.0

func (p ExploitStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (ExploitStore) AuthCacheTTL added in v0.15.0

func (p ExploitStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (ExploitStore) BeginTx added in v0.15.0

func (p ExploitStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (ExploitStore) Close added in v0.15.0

func (p ExploitStore) Close() error

Close writes the pending download counts and closes the database connection.

func (ExploitStore) CountFileDownload added in v0.19.0

func (p ExploitStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*ExploitStore) ExploitFeedStates added in v0.14.0

func (p *ExploitStore) ExploitFeedStates(ctx context.Context) (map[string]models.ExploitFeedState, error)

ExploitFeedStates implements ExploitCatalog.

func (*ExploitStore) ExploitSignals added in v0.14.0

func (p *ExploitStore) ExploitSignals(ctx context.Context, cves []string) (map[string]models.ExploitSignal, error)

ExploitSignals implements ExploitCatalog.

func (ExploitStore) FlushDownloadCounts added in v0.19.0

func (p ExploitStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (ExploitStore) GetDB added in v0.15.0

func (p ExploitStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*ExploitStore) ListVulnExploitCandidates added in v0.14.0

func (p *ExploitStore) ListVulnExploitCandidates(ctx context.Context, afterID string, limit int) ([]models.VulnExploitCandidate, error)

ListVulnExploitCandidates implements ExploitCatalog.

func (ExploitStore) Migrate added in v0.15.0

func (p ExploitStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (ExploitStore) Ping added in v0.15.0

func (p ExploitStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (ExploitStore) PoolStat added in v0.15.0

func (p ExploitStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*ExploitStore) RecordExploitFeedCheck added in v0.14.0

func (p *ExploitStore) RecordExploitFeedCheck(ctx context.Context, name, sourceURL, errMsg string, checkedAt time.Time) error

RecordExploitFeedCheck implements ExploitCatalog.

func (*ExploitStore) ReplaceEPSS added in v0.14.0

func (p *ExploitStore) ReplaceEPSS(ctx context.Context, state models.ExploitFeedState, next func() (models.EPSSScore, error)) (int, error)

ReplaceEPSS implements ExploitCatalog.

func (*ExploitStore) ReplaceKEV added in v0.14.0

func (p *ExploitStore) ReplaceKEV(ctx context.Context, entries []models.KEVEntry, state models.ExploitFeedState) error

ReplaceKEV implements ExploitCatalog.

func (*ExploitStore) UpdateVulnExploitAggregates added in v0.14.0

func (p *ExploitStore) UpdateVulnExploitAggregates(ctx context.Context, aggs []models.VulnExploitAggregate) (int, error)

UpdateVulnExploitAggregates implements ExploitCatalog.

type FileWrite added in v0.15.0

type FileWrite struct {
	Path, Filename string
	// Blob is stored (or found) by its digest before the transaction starts.
	Blob BlobWrite
	// SizeBytes is the declared size that wins over the blob's; nil when the
	// blob's is the size.
	SizeBytes *int64
	// Role defaults to FileRolePrimary.
	Role string
	// Unlisted keeps the file out of the repository listing (go mod and info).
	Unlisted bool
	Arch     string
	Part     string
	Attrs    any
	// Checksums are the non-sha256 digests the checksum search matches
	// ("sha1", "md5", "sha512", "shasum", "integrity").
	Checksums     map[string]string
	UnitKey       string
	DownloadCount int64
}

FileWrite is one package_files row of a PackageWrite.

type FileWritten added in v0.15.0

type FileWritten struct {
	ID        string
	CreatedAt time.Time
	UpdatedAt time.Time
	// Replaced is the content the write took the path over from (nil when the
	// path was free); only the overwriting writers fill it.
	Replaced *models.ReplacedBlob
}

FileWritten is the generated part of one written file.

type GPGKeyStore added in v0.15.0

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

GPGKeyStore owns GPG signing keys and their assignment to repositories.

func (GPGKeyStore) AuthCacheGeneration added in v0.15.0

func (p GPGKeyStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (GPGKeyStore) AuthCacheTTL added in v0.15.0

func (p GPGKeyStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (GPGKeyStore) BeginTx added in v0.15.0

func (p GPGKeyStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (*GPGKeyStore) ClearGlobalGPGKey added in v0.15.0

func (p *GPGKeyStore) ClearGlobalGPGKey(ctx context.Context) error

ClearGlobalGPGKey leaves no key globally active.

func (*GPGKeyStore) ClearRepositoryGPGKey added in v0.15.0

func (p *GPGKeyStore) ClearRepositoryGPGKey(ctx context.Context, repoID string) (bool, error)

ClearRepositoryGPGKey removes a repository's own key (it then follows the global one) and reports whether there was one.

func (GPGKeyStore) Close added in v0.15.0

func (p GPGKeyStore) Close() error

Close writes the pending download counts and closes the database connection.

func (GPGKeyStore) CountFileDownload added in v0.19.0

func (p GPGKeyStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*GPGKeyStore) CreateGPGKey added in v0.15.0

func (p *GPGKeyStore) CreateGPGKey(ctx context.Context, k *models.GPGKey) error

CreateGPGKey stores k (inactive) and fills ID and CreatedAt back. ErrGPGKeyExists when the name or fingerprint is taken.

func (*GPGKeyStore) CreateGPGKeyIfNone added in v0.15.0

func (p *GPGKeyStore) CreateGPGKeyIfNone(ctx context.Context, k *models.GPGKey) (bool, error)

CreateGPGKeyIfNone stores k as the global active key only when no key exists yet, under a cluster-wide advisory lock so replicas starting together create exactly one. It reports whether k was stored.

func (*GPGKeyStore) DeleteGPGKey added in v0.15.0

func (p *GPGKeyStore) DeleteGPGKey(ctx context.Context, id string) error

DeleteGPGKey removes a key and its repository assignments; ErrGPGKeyNotFound when absent.

func (GPGKeyStore) FlushDownloadCounts added in v0.19.0

func (p GPGKeyStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (GPGKeyStore) GetDB added in v0.15.0

func (p GPGKeyStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*GPGKeyStore) GetGPGKey added in v0.15.0

func (p *GPGKeyStore) GetGPGKey(ctx context.Context, id string) (*models.GPGKey, error)

GetGPGKey loads one key including its sealed private part; ErrGPGKeyNotFound when absent.

func (*GPGKeyStore) GetGPGKeyByFingerprint added in v0.15.0

func (p *GPGKeyStore) GetGPGKeyByFingerprint(ctx context.Context, fingerprint string) (*models.GPGKey, error)

GetGPGKeyByFingerprint loads a key by its (upper-case hex) fingerprint; ErrGPGKeyNotFound when absent.

func (*GPGKeyStore) ListGPGKeyAssignments added in v0.15.0

func (p *GPGKeyStore) ListGPGKeyAssignments(ctx context.Context) ([]models.GPGKeyAssignment, error)

ListGPGKeyAssignments lists every repository-to-key binding.

func (*GPGKeyStore) ListGPGKeys added in v0.15.0

func (p *GPGKeyStore) ListGPGKeys(ctx context.Context) ([]*models.GPGKey, error)

ListGPGKeys lists every key without its private part.

func (*GPGKeyStore) ListRepositoriesForGPGKey added in v0.15.0

func (p *GPGKeyStore) ListRepositoriesForGPGKey(ctx context.Context, keyID string) ([]models.GPGSigningRepo, error)

ListRepositoriesForGPGKey returns the repositories bound to keyID.

func (*GPGKeyStore) ListSigningRepositoriesWithoutKey added in v0.15.0

func (p *GPGKeyStore) ListSigningRepositoriesWithoutKey(ctx context.Context) ([]models.GPGSigningRepo, error)

ListSigningRepositoriesWithoutKey returns the hosted deb, pacman and rpm repositories that have no key of their own, i.e. follow the global key.

func (GPGKeyStore) Migrate added in v0.15.0

func (p GPGKeyStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (GPGKeyStore) Ping added in v0.15.0

func (p GPGKeyStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (GPGKeyStore) PoolStat added in v0.15.0

func (p GPGKeyStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*GPGKeyStore) ResolveGPGKeyForRepository added in v0.15.0

func (p *GPGKeyStore) ResolveGPGKeyForRepository(ctx context.Context, repoID string) (*models.GPGKey, error)

ResolveGPGKeyForRepository returns the key that signs a repository's metadata (its own, else the global active one) with its sealed private part, or nil when nothing signs it.

func (*GPGKeyStore) SetGlobalGPGKey added in v0.15.0

func (p *GPGKeyStore) SetGlobalGPGKey(ctx context.Context, id string) error

SetGlobalGPGKey makes id the one globally active key; ErrGPGKeyNotFound when absent.

func (*GPGKeyStore) SetRepositoryGPGKey added in v0.15.0

func (p *GPGKeyStore) SetRepositoryGPGKey(ctx context.Context, repoID, keyID, assignedBy string) error

SetRepositoryGPGKey makes keyID the signing key of one repository.

type GoModStore added in v0.15.0

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

GoModStore owns the Go modules and the repair queries of the gomod repair task.

Go modules live in the generic package tables (repository format "go"; the mapping is the maintainers' reference, derived from migrations/001_baseline.sql):

packages          one per module path: name = name_key = module path (case-encoded
                  as the handler stores it), attrs {}
package_versions  one per module version incarnation: version = version_key =
                  "v1.2.3" (pseudo-versions included), metadata {}; created_at is
                  what .info reports as Time
package_files     two per version, trashed as a unit (the trash engine works on
                  the version scope, so trashing the listed zip id stamps the mod file too):
                    zip  path "<module>/@v/<version>.zip", filename "<version>.zip",
                         role primary, listed, unit_key "<module>@<version>" (the
                         federation unit is the version, content ref = the zip blob)
                    mod  path "<module>/@v/<version>.mod", filename "<version>.mod",
                         role mod, unlisted, attrs {"go_mod_content": "<go.mod text>"}:
                         .mod is served from this attribute, never from the blob

The ID of a GoModule is the zip file id (the listing, scan and blob-component id). Quota: the baseline trigger counts one artifact per primary file and the bytes of every blob, so an upload reserves the zip as (size, 1) and the go.mod as (size, 0); a hard delete releases both. There is no .info file: it is synthesised from the version and created_at.

func (GoModStore) AuthCacheGeneration added in v0.15.0

func (p GoModStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (GoModStore) AuthCacheTTL added in v0.15.0

func (p GoModStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (GoModStore) BeginTx added in v0.15.0

func (p GoModStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (GoModStore) Close added in v0.15.0

func (p GoModStore) Close() error

Close writes the pending download counts and closes the database connection.

func (GoModStore) CountFileDownload added in v0.19.0

func (p GoModStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*GoModStore) CreateGoModule added in v0.15.0

func (p *GoModStore) CreateGoModule(ctx context.Context, mod *models.GoModule) error

CreateGoModule creates a new Go module version: the package, the version and its zip and go.mod files in one transaction. The zip blob row is keyed by ZipHash; the mod blob has no digest field on models.GoModule, so its own blob key serves as the blobs.sha256 value (self-referential, mirrors the docker blob pattern; it never collides since blob keys are unique per upload). A module whose go.mod blob key is empty gets a go.mod file without a blob: the go.mod text lives in the file's attrs. A live version of the same module is ErrDuplicate.

func (*GoModStore) DeleteUnreferencedInvalidBlobRow added in v0.15.0

func (p *GoModStore) DeleteUnreferencedInvalidBlobRow(ctx context.Context, id string) (bool, error)

DeleteUnreferencedInvalidBlobRow deletes the blobs row id (a row with an invalid sha256) from the database only, when nothing references it any more. It never touches the storage object: for the shared "" row that object is a real module's zip, now relinked under its true digest. Returns true when the row was deleted.

func (*GoModStore) EmptySHA256BlobID added in v0.15.0

func (p *GoModStore) EmptySHA256BlobID(ctx context.Context) (string, error)

EmptySHA256BlobID returns the id of the shared blobs row with an empty sha256 left behind by OpenArtifact <= 0.4.1, or "" when it does not exist (blobs.sha256 is unique and indexed, so this is a point lookup).

func (GoModStore) FlushDownloadCounts added in v0.19.0

func (p GoModStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (GoModStore) GetDB added in v0.15.0

func (p GoModStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*GoModStore) GetGoModule added in v0.15.0

func (p *GoModStore) GetGoModule(ctx context.Context, repoID, modulePath, version string) (*models.GoModule, error)

GetGoModule retrieves a Go module by repo, path, and version. A version without a live zip file is not found.

func (*GoModStore) ListGoModuleVersions added in v0.15.0

func (p *GoModStore) ListGoModuleVersions(ctx context.Context, repoID, modulePath string) ([]*models.GoModule, error)

ListGoModuleVersions lists all versions of a module, oldest first.

func (*GoModStore) ListGomodAffectedRows added in v0.15.0

func (p *GoModStore) ListGomodAffectedRows(ctx context.Context) ([]GomodAffectedRow, error)

ListGomodAffectedRows returns every Go module version whose zip blob row has a sha256 that is not 64 lowercase hex characters.

func (*GoModStore) ListGomodSiblingZipKeys added in v0.15.0

func (p *GoModStore) ListGomodSiblingZipKeys(ctx context.Context) ([]string, error)

ListGomodSiblingZipKeys returns the digests of valid zip blobs of other Go module versions that share module path and version with an affected row (the same release published in another repository after the upgrade).

func (GoModStore) Migrate added in v0.15.0

func (p GoModStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (GoModStore) Ping added in v0.15.0

func (p GoModStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (GoModStore) PoolStat added in v0.15.0

func (p GoModStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*GoModStore) RelinkGomodZips added in v0.15.0

func (p *GoModStore) RelinkGomodZips(ctx context.Context, sha256 string, size int64, rowIDs []string) (int64, error)

RelinkGomodZips upserts the blobs row for the zip with digest sha256 and points the given zip files at it, but only rows that still reference badBlobID (so a concurrent change is never overwritten). It runs under the same per-blob advisory lock as uploads and SafeDeleteBlob and returns how many rows were relinked.

func (*GoModStore) TryGomodRepairLock added in v0.15.0

func (p *GoModStore) TryGomodRepairLock(ctx context.Context) (func(), bool, error)

TryGomodRepairLock takes the repair's session advisory lock on a pinned connection. ok is false when another replica holds it. release must be called when ok is true; it unlocks and returns the connection to the pool.

func (*GoModStore) UnreferencedBlobKeys added in v0.15.0

func (p *GoModStore) UnreferencedBlobKeys(ctx context.Context, ids []string) ([]string, error)

UnreferencedBlobKeys returns the subset of ids (blob store keys) that no blobs row carries as its sha256.

type GomodAffectedRow added in v0.5.0

type GomodAffectedRow struct {
	ID           string
	RepositoryID string
	RepoName     string
	ModulePath   string
	Version      string
	GoModContent string
	Trashed      bool
	// BadBlobID and BadBlobKey identify the invalid blobs row the zip points at.
	BadBlobID  string
	BadBlobKey string
}

GomodAffectedRow is a Go module version (trashed ones included) whose zip blob row has an invalid sha256. ID is the id of the zip file.

type GroupPatch added in v0.20.0

type GroupPatch struct {
	Name        *string
	Description *string
}

GroupPatch names the columns an admin edit writes; nil fields leave the stored value alone.

type HelmStore added in v0.15.0

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

HelmStore owns the Helm charts.

Mapping of a chart onto the generic package tables (one chart version, one .tgz, is one version and one file; the chart name is the package):

packages          name = name_key = chart name, attrs {}
package_versions  version = version_key = chart version; metadata
                  {app_version, description, home, icon, keywords, sources,
                  maintainers, api_version, type}: empty values are omitted,
                  a missing api_version reads "v2" and a missing type
                  "application"
package_files     path name/version/name-version.tgz, filename
                  name-version.tgz, the chart blob (its sha256 is the chart
                  digest), role primary, unit_key name@version (federation)

The id of a chart (the chart-list JSON) is package_files.id. A duplicate publish is a live version with a live file (ErrDuplicate).

func (HelmStore) AuthCacheGeneration added in v0.15.0

func (p HelmStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (HelmStore) AuthCacheTTL added in v0.15.0

func (p HelmStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (HelmStore) BeginTx added in v0.15.0

func (p HelmStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (HelmStore) Close added in v0.15.0

func (p HelmStore) Close() error

Close writes the pending download counts and closes the database connection.

func (HelmStore) CountFileDownload added in v0.19.0

func (p HelmStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*HelmStore) CreateHelmChart added in v0.15.0

func (p *HelmStore) CreateHelmChart(ctx context.Context, chart *models.HelmChart) error

CreateHelmChart creates a new Helm chart.

func (*HelmStore) DeleteHelmChart added in v0.15.0

func (p *HelmStore) DeleteHelmChart(ctx context.Context, repoID, name, version string) error

DeleteHelmChart hard-deletes the live file of a chart version; the version and the package go with their last file.

func (HelmStore) FlushDownloadCounts added in v0.19.0

func (p HelmStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (HelmStore) GetDB added in v0.15.0

func (p HelmStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*HelmStore) GetHelmChart added in v0.15.0

func (p *HelmStore) GetHelmChart(ctx context.Context, repoID, name, version string) (*models.HelmChart, error)

func (*HelmStore) HelmIndexStamp added in v0.15.0

func (p *HelmStore) HelmIndexStamp(ctx context.Context, repoID string) (string, error)

HelmIndexStamp is a cheap validator of a repository's index.yaml: it changes exactly when a live chart is added or removed.

func (*HelmStore) ListHelmCharts added in v0.15.0

func (p *HelmStore) ListHelmCharts(ctx context.Context, repoID string) ([]*models.HelmChart, error)

func (HelmStore) Migrate added in v0.15.0

func (p HelmStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (HelmStore) Ping added in v0.15.0

func (p HelmStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (HelmStore) PoolStat added in v0.15.0

func (p HelmStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

type IvyStore added in v0.15.0

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

IvyStore owns the Ivy artifacts.

Ivy on the generic package tables (mapping spec /tmp/oa-plug/schema/109_ivy.sql, restated as the maintainers' reference). No side table.

P  packages         name = name_key = organisation ':' module
                    attrs = {"organisation", "module"}
V  package_versions version = version_key = revision; metadata {}
F  package_files    filename = the artifact name, with '.' extension appended
                    only when the name does not end with it already (the handler
                    stores the whole file name, possibly with a sub-directory);
                    path = organisation '/' module '/' revision '/' filename
                    (repository-wide live-unique: the lookup key);
                    arch '', part '', role primary, listed, unit_key NULL,
                    attrs = {"artifact_name", "artifact_type", "artifact_ext"}

An upload to an existing path repoints the file at the new blob (ivy publishes with overwrite).

func (IvyStore) AuthCacheGeneration added in v0.15.0

func (p IvyStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (IvyStore) AuthCacheTTL added in v0.15.0

func (p IvyStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (IvyStore) BeginTx added in v0.15.0

func (p IvyStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (IvyStore) Close added in v0.15.0

func (p IvyStore) Close() error

Close writes the pending download counts and closes the database connection.

func (IvyStore) CountFileDownload added in v0.19.0

func (p IvyStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*IvyStore) CreateIvyArtifact added in v0.15.0

func (p *IvyStore) CreateIvyArtifact(ctx context.Context, artifact *models.IvyArtifact) error

CreateIvyArtifact stores an Ivy artifact; a live artifact with the same coordinates is repointed at the new blob.

func (*IvyStore) DeleteIvyArtifact added in v0.15.0

func (p *IvyStore) DeleteIvyArtifact(ctx context.Context, id string) error

func (IvyStore) FlushDownloadCounts added in v0.19.0

func (p IvyStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (IvyStore) GetDB added in v0.15.0

func (p IvyStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*IvyStore) GetIvyArtifact added in v0.15.0

func (p *IvyStore) GetIvyArtifact(
	ctx context.Context,
	repoID, organisation, module, revision, artifactName, artifactExt string,
) (*models.IvyArtifact, error)

func (*IvyStore) IvyModuleExists added in v0.15.0

func (p *IvyStore) IvyModuleExists(ctx context.Context, repoID, organisation, module string) (bool, error)

IvyModuleExists reports whether the repository holds a live version of the module.

func (IvyStore) Migrate added in v0.15.0

func (p IvyStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (IvyStore) Ping added in v0.15.0

func (p IvyStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (IvyStore) PoolStat added in v0.15.0

func (p IvyStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

type LicenseStore added in v0.15.0

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

LicenseStore owns license scan results and license policies.

func (LicenseStore) AuthCacheGeneration added in v0.15.0

func (p LicenseStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (LicenseStore) AuthCacheTTL added in v0.15.0

func (p LicenseStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (LicenseStore) BeginTx added in v0.15.0

func (p LicenseStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (LicenseStore) Close added in v0.15.0

func (p LicenseStore) Close() error

Close writes the pending download counts and closes the database connection.

func (LicenseStore) CountFileDownload added in v0.19.0

func (p LicenseStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*LicenseStore) CreateLicensePolicy added in v0.15.0

func (p *LicenseStore) CreateLicensePolicy(ctx context.Context, policy *models.LicensePolicy) error

CreateLicensePolicy creates a new license policy.

func (*LicenseStore) CreateLicenseScanResult added in v0.15.0

func (p *LicenseStore) CreateLicenseScanResult(ctx context.Context, result *models.LicenseScanResult) error

CreateLicenseScanResult creates a new license scan result (UPSERT).

func (*LicenseStore) DeleteLicensePolicy added in v0.15.0

func (p *LicenseStore) DeleteLicensePolicy(ctx context.Context, id string) error

DeleteLicensePolicy deletes a license policy by ID.

func (LicenseStore) FlushDownloadCounts added in v0.19.0

func (p LicenseStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (LicenseStore) GetDB added in v0.15.0

func (p LicenseStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*LicenseStore) GetLicensePolicy added in v0.15.0

func (p *LicenseStore) GetLicensePolicy(ctx context.Context, id string) (*models.LicensePolicy, error)

GetLicensePolicy gets a license policy by ID.

func (*LicenseStore) GetLicenseScanResult added in v0.15.0

func (p *LicenseStore) GetLicenseScanResult(ctx context.Context, repoID, artifactID string) (*models.LicenseScanResult, error)

GetLicenseScanResult gets a license scan result by repo and artifact ID.

func (*LicenseStore) GetLicenseScanResultByID added in v0.15.0

func (p *LicenseStore) GetLicenseScanResultByID(ctx context.Context, repoID, id string) (*models.LicenseScanResult, error)

GetLicenseScanResultByID returns the license scan result with the given ID scoped to repoID, or nil.

func (*LicenseStore) ListGlobalLicensePolicies added in v0.15.0

func (p *LicenseStore) ListGlobalLicensePolicies(ctx context.Context) ([]*models.LicensePolicy, error)

ListGlobalLicensePolicies lists only the global (repository_id IS NULL) license policies.

func (*LicenseStore) ListLicensePolicies added in v0.15.0

func (p *LicenseStore) ListLicensePolicies(ctx context.Context, repoID string) ([]*models.LicensePolicy, error)

ListLicensePolicies lists all license policies for a repository (including global policies).

func (*LicenseStore) ListLicenseScanResults added in v0.15.0

func (p *LicenseStore) ListLicenseScanResults(ctx context.Context, repoID string) ([]*models.LicenseScanResult, error)

ListLicenseScanResults lists all license scan results for a repository.

func (*LicenseStore) ListLicenseScanResultsPage added in v0.22.0

func (p *LicenseStore) ListLicenseScanResultsPage(
	ctx context.Context, repoID string, limit, offset int,
) ([]*models.LicenseScanResult, int, error)

ListLicenseScanResultsPage lists one page of a repository's license scan results, newest first, with the total number of results.

func (*LicenseStore) ListUnresolvedLicenseScanResults added in v0.22.0

func (p *LicenseStore) ListUnresolvedLicenseScanResults(
	ctx context.Context, repoID string, limit int,
) ([]*models.LicenseScanResult, error)

ListUnresolvedLicenseScanResults lists up to limit completed license scan results of a repository that found no license, newest first.

func (LicenseStore) Migrate added in v0.15.0

func (p LicenseStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (LicenseStore) Ping added in v0.15.0

func (p LicenseStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (LicenseStore) PoolStat added in v0.15.0

func (p LicenseStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*LicenseStore) SetLicenseScanQuarantine added in v0.15.0

func (p *LicenseStore) SetLicenseScanQuarantine(ctx context.Context, repoID, id string, quarantined bool) error

SetLicenseScanQuarantine quarantines (true) or approves (false) the artifact of exactly one license scan result (by ID, scoped to repoID). Approving records the decision for the licenses currently stored, so a later scan that finds the same licenses does not quarantine the artifact again; quarantining clears it. Returns ErrLicenseScanNotFound when nothing matched.

func (*LicenseStore) UpdateLicensePolicy added in v0.15.0

func (p *LicenseStore) UpdateLicensePolicy(ctx context.Context, policy *models.LicensePolicy) error

UpdateLicensePolicy updates a license policy.

type MavenStore added in v0.15.0

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

MavenStore owns the Maven artifacts and the generated Maven metadata pruning.

Maven on the generic package tables (the mapping spec is /tmp/oa-plug/schema/110_maven.sql, restated here as the maintainers' reference). One stored file (pom, jar, -sources.jar, one snapshot build's files, ...) is one package_files row; checksum sidecars and maven-metadata.xml are never stored.

P  packages         name = name_key = group_id ':' artifact_id
                    attrs = {"group_id", "artifact_id"}
V  package_versions version = version
                    version_key = version, plus '#' timestamp '-' build for a
                    timestamped snapshot build (every build is a version of
                    its own; all files of a build share it): the text the
                    cleanup worker ranks by
                    metadata = {"is_snapshot", "snapshot_timestamp" (absent
                    when none), "snapshot_build_number"}
F  package_files    path = repo_path (repository-wide live-unique), filename = repo_path,
                    role primary, listed, arch = classifier,
                    part = 'true:' version for a snapshot, else 'false',
                    checksums = {"md5", "sha1", "sha512"} (non-empty ones),
                    unit_key = repo_path (federation unit = the file)
side maven_files    classifier, extension, snapshot_timestamp, snapshot_build_number,
                    is_snapshot, md5, sha1, sha512 (the sidecar GETs read these;
                    written together with F.checksums in the upload transaction)

The cleanup partitions maven on (P, F.part), not on F.arch: -sources and -javadoc files rank together with the main jar of their version.

func (MavenStore) AuthCacheGeneration added in v0.15.0

func (p MavenStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (MavenStore) AuthCacheTTL added in v0.15.0

func (p MavenStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (MavenStore) BeginTx added in v0.15.0

func (p MavenStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (MavenStore) Close added in v0.15.0

func (p MavenStore) Close() error

Close writes the pending download counts and closes the database connection.

func (MavenStore) CountFileDownload added in v0.19.0

func (p MavenStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*MavenStore) CreateMavenArtifact added in v0.15.0

func (p *MavenStore) CreateMavenArtifact(ctx context.Context, a *models.MavenArtifact) error

CreateMavenArtifact stores a file of an artifact (a.BlobID is a blobs id). A live file at the same repo path is repointed at the new blob and its digests are replaced (the snapshot overwrite); the digests go to maven_files and package_files.checksums in the same transaction.

func (*MavenStore) DeleteMavenArtifact added in v0.15.0

func (p *MavenStore) DeleteMavenArtifact(ctx context.Context, id string) error

func (MavenStore) FlushDownloadCounts added in v0.19.0

func (p MavenStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (MavenStore) GetDB added in v0.15.0

func (p MavenStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*MavenStore) GetLatestSnapshot added in v0.15.0

func (p *MavenStore) GetLatestSnapshot(ctx context.Context, repoID, groupID, artifactID, version string) (*models.MavenArtifact, error)

func (*MavenStore) GetLatestSnapshotFile added in v0.15.0

func (p *MavenStore) GetLatestSnapshotFile(
	ctx context.Context,
	repoID, groupID, artifactID, version, classifier, extension string,
) (*models.MavenArtifact, error)

GetLatestSnapshotFile returns the newest snapshot build of the file with the given classifier and extension.

func (*MavenStore) GetMavenArtifactByPath added in v0.15.0

func (p *MavenStore) GetMavenArtifactByPath(ctx context.Context, repoID, path string) (*models.MavenArtifact, error)

func (*MavenStore) GetMavenArtifactsByGAV added in v0.15.0

func (p *MavenStore) GetMavenArtifactsByGAV(
	ctx context.Context,
	repoID, groupID, artifactID, version string,
) ([]*models.MavenArtifact, error)

func (*MavenStore) ListMavenArtifactsByRepo added in v0.15.0

func (p *MavenStore) ListMavenArtifactsByRepo(ctx context.Context, repoID string) ([]*models.MavenArtifact, error)

ListMavenArtifactsByRepo lists every live maven artifact of a repository. BlobSHA256/BlobSizeBytes carry the blob's digest and size (the restore handle: BlobID is a live blobs.id that does not survive a restore into a fresh DB).

func (*MavenStore) ListMavenGARefs added in v0.15.0

func (p *MavenStore) ListMavenGARefs(ctx context.Context, repoID, groupID, artifactID string) (*models.MavenGARefs, error)

ListMavenGARefs loads the versions and snapshot files of one group:artifact in a single narrow query (no artifact ids, paths or checksum join).

func (MavenStore) Migrate added in v0.15.0

func (p MavenStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (MavenStore) Ping added in v0.15.0

func (p MavenStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (MavenStore) PoolStat added in v0.15.0

func (p MavenStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*MavenStore) PruneMavenMetadata added in v0.15.0

func (p *MavenStore) PruneMavenMetadata(ctx context.Context, repositoryID, dir string, keep []string) ([]string, error)

PruneMavenMetadata deletes the generated maven-metadata.xml rows below the directory dir (e.g. "com/example/app/"): the artifact's own maven-metadata.xml and the one of each snapshot version directory, except the paths in keep. The regeneration calls it with the paths it just wrote, so metadata of an artifact (or snapshot version) that has no live file left disappears instead of advertising versions that were deleted or trashed. The blob shas of the deleted rows are returned so the caller can reclaim the objects.

type Migrator

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

Migrator applies embedded SQL migrations to a PostgreSQL database.

func NewMigrator

func NewMigrator(db *sql.DB) *Migrator

NewMigrator returns a Migrator backed by the embedded migrations FS.

func (*Migrator) Apply

func (m *Migrator) Apply(ctx context.Context) error

Apply runs all pending migrations in lexicographic order. It is idempotent: already-applied migrations are skipped. Returns an error if any migration fails or checksum drift is detected.

type NPMStore added in v0.15.0

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

NPMStore owns the npm packages, versions and dist-tags.

func (NPMStore) AuthCacheGeneration added in v0.15.0

func (p NPMStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (NPMStore) AuthCacheTTL added in v0.15.0

func (p NPMStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (NPMStore) BeginTx added in v0.15.0

func (p NPMStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (NPMStore) Close added in v0.15.0

func (p NPMStore) Close() error

Close writes the pending download counts and closes the database connection.

func (NPMStore) CountFileDownload added in v0.19.0

func (p NPMStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*NPMStore) CreateNPMPackage added in v0.15.0

func (p *NPMStore) CreateNPMPackage(ctx context.Context, pkg *models.NPMPackage) (*models.NPMPackage, error)

func (*NPMStore) CreateNPMVersion added in v0.15.0

func (p *NPMStore) CreateNPMVersion(ctx context.Context, v *models.NPMVersion) (*models.NPMVersion, error)

CreateNPMVersion writes the version and its tarball file in one transaction. v.BlobID is an existing blobs.id. A live version of the same number, or a live tarball with the same path, fails with ErrDuplicate. On success v.ID is the id of the tarball file.

func (*NPMStore) DeleteNPMDistTag added in v0.15.0

func (p *NPMStore) DeleteNPMDistTag(ctx context.Context, packageID, tag string) error

func (*NPMStore) DeleteNPMPackage added in v0.15.0

func (p *NPMStore) DeleteNPMPackage(ctx context.Context, packageID string) error

func (*NPMStore) DeleteNPMVersions added in v0.20.0

func (p *NPMStore) DeleteNPMVersions(ctx context.Context, packageID string, versions []string) error

DeleteNPMVersions hard-deletes the live versions among the given version keys with their tarball rows and the dist-tags that named them (unless a trashed incarnation of the same version remains), and bumps the packument ETag, in one transaction. The package row stays: DeleteNPMPackage removes it once no version row is left.

func (NPMStore) FlushDownloadCounts added in v0.19.0

func (p NPMStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (NPMStore) GetDB added in v0.15.0

func (p NPMStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*NPMStore) GetNPMDistTags added in v0.15.0

func (p *NPMStore) GetNPMDistTags(ctx context.Context, packageID string) (map[string]string, error)

func (*NPMStore) GetNPMPackageByName added in v0.15.0

func (p *NPMStore) GetNPMPackageByName(ctx context.Context, repoID, fullName string) (*models.NPMPackage, error)

func (*NPMStore) GetNPMVersion added in v0.15.0

func (p *NPMStore) GetNPMVersion(ctx context.Context, packageID, version string) (*models.NPMVersion, error)

func (*NPMStore) GetNPMVersionStates added in v0.15.0

func (p *NPMStore) GetNPMVersionStates(ctx context.Context, packageID string) ([]models.NPMVersionState, error)

GetNPMVersionStates returns number and deprecation of every live version of the package, without the manifests.

func (*NPMStore) GetNPMVersionsByPackage added in v0.15.0

func (p *NPMStore) GetNPMVersionsByPackage(ctx context.Context, packageID string) ([]*models.NPMVersion, error)

func (*NPMStore) ListNPMVersionsByNames added in v0.20.0

func (p *NPMStore) ListNPMVersionsByNames(ctx context.Context, packageID string, versions []string) (map[string]*models.NPMVersion, error)

ListNPMVersionsByNames returns the live versions of a package among the given version keys, keyed by version key; absent versions are not in the map.

func (*NPMStore) MarkPackumentStale added in v0.15.0

func (p *NPMStore) MarkPackumentStale(ctx context.Context, packageID string) error

func (NPMStore) Migrate added in v0.15.0

func (p NPMStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (NPMStore) Ping added in v0.15.0

func (p NPMStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (NPMStore) PoolStat added in v0.15.0

func (p NPMStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*NPMStore) UpdateNPMPackageLatestVersion added in v0.15.0

func (p *NPMStore) UpdateNPMPackageLatestVersion(ctx context.Context, packageID, latestVersion string) error

func (*NPMStore) UpdateNPMVersionManifest added in v0.15.0

func (p *NPMStore) UpdateNPMVersionManifest(ctx context.Context, packageID, version string, manifest []byte) error

UpdateNPMVersionManifest replaces the stored manifest of a live version (used for `npm deprecate`).

func (*NPMStore) UpsertNPMDistTag added in v0.15.0

func (p *NPMStore) UpsertNPMDistTag(ctx context.Context, t *models.NPMDistTag) (*models.NPMDistTag, error)

type NixStore added in v0.15.0

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

NixStore owns the Nix store paths, pending NARs and signing key.

Mapping of a store path onto the generic package tables (one narinfo plus the NAR it points at is one version and one file; the store path name is the package, the store hash the version):

packages          name = name_key = store path name (e.g. "hello-2.12.1")
package_versions  version = version_key = store hash; metadata
                  {nar_hash, nar_size, nar_file, compression, refs,
                  deriver, ca, signatures}: every key is always written
                  (refs and signatures as [] when empty, deriver and ca
                  as ""); nar_file is the URL path of the NAR and is what
                  GetNixPathByNarFile looks up
package_files     path = filename = "<store hash>.narinfo", the NAR blob
                  (several paths may share one NAR blob), role primary,
                  download_count (the NAR's counter), no unit_key (nix is
                  not federated)

The store hash is unique across names in a repository because the narinfo path is: a duplicate is a unique violation on the live path (ErrDuplicate). nix_pending_nars (staging) and nix_signing_keys keep their own tables.

func (NixStore) AuthCacheGeneration added in v0.15.0

func (p NixStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (NixStore) AuthCacheTTL added in v0.15.0

func (p NixStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (NixStore) BeginTx added in v0.15.0

func (p NixStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (NixStore) Close added in v0.15.0

func (p NixStore) Close() error

Close writes the pending download counts and closes the database connection.

func (NixStore) CountFileDownload added in v0.19.0

func (p NixStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*NixStore) CreateNixPath added in v0.15.0

func (p *NixStore) CreateNixPath(ctx context.Context, np *models.NixPath) error

CreateNixPath stores the path and drops the staging row of its NAR file in one transaction. A live path with the same store hash is ErrDuplicate.

func (*NixStore) CreateNixSigningKeyIfAbsent added in v0.15.0

func (p *NixStore) CreateNixSigningKeyIfAbsent(ctx context.Context, k *models.NixSigningKey) (bool, error)

CreateNixSigningKeyIfAbsent stores the key unless the repository has one; created reports whether it did.

func (*NixStore) DeleteNixPath added in v0.15.0

func (p *NixStore) DeleteNixPath(ctx context.Context, repoID, id string) error

DeleteNixPath hard-deletes one live path (its narinfo file); the version and the package go with it.

func (*NixStore) DeleteStaleNixPendingNars added in v0.15.0

func (p *NixStore) DeleteStaleNixPendingNars(ctx context.Context, before time.Time, limit int) ([]models.NixPendingNar, error)

DeleteStaleNixPendingNars deletes up to limit staging rows older than before and returns their repository, sha256 and reserved bytes, so the caller can delete the blobs and hand the reservations back.

func (NixStore) FlushDownloadCounts added in v0.19.0

func (p NixStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (NixStore) GetDB added in v0.15.0

func (p NixStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*NixStore) GetNixPathByHash added in v0.15.0

func (p *NixStore) GetNixPathByHash(ctx context.Context, repoID, storeHash string) (*models.NixPath, error)

GetNixPathByHash returns the live path of the store hash, or (nil, nil).

func (*NixStore) GetNixPathByNarFile added in v0.15.0

func (p *NixStore) GetNixPathByNarFile(ctx context.Context, repoID, narFile string) (*models.NixPath, error)

GetNixPathByNarFile returns a live path whose NAR file is narFile, or (nil, nil).

func (*NixStore) GetNixPendingNar added in v0.15.0

func (p *NixStore) GetNixPendingNar(ctx context.Context, repoID, sha256 string) (*models.NixPendingNar, error)

GetNixPendingNar returns the staged NAR file, or (nil, nil).

func (*NixStore) GetNixSigningKey added in v0.15.0

func (p *NixStore) GetNixSigningKey(ctx context.Context, repoID string) (*models.NixSigningKey, error)

GetNixSigningKey returns the repository's signing key, or (nil, nil).

func (*NixStore) ListNixPaths added in v0.15.0

func (p *NixStore) ListNixPaths(ctx context.Context, repoID string) ([]*models.NixPath, error)

ListNixPaths returns every live path of the repository ordered by store hash.

func (NixStore) Migrate added in v0.15.0

func (p NixStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (NixStore) Ping added in v0.15.0

func (p NixStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (NixStore) PoolStat added in v0.15.0

func (p NixStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*NixStore) PutNixPendingNar added in v0.15.0

func (p *NixStore) PutNixPendingNar(ctx context.Context, n *models.NixPendingNar) (bool, error)

PutNixPendingNar stores a NAR file that awaits its narinfo. It is idempotent per (repository, sha256): the result is false when the file was already staged, and the row (with its reservation) is left as it was.

func (*NixStore) ReplaceNixSigningKey added in v0.15.0

func (p *NixStore) ReplaceNixSigningKey(ctx context.Context, k *models.NixSigningKey) error

ReplaceNixSigningKey stores the key, replacing the repository's current one.

type NuGetStore added in v0.15.0

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

NuGetStore owns the NuGet packages.

Mapping of a package version onto the generic package tables (one .nupkg is one version and one file; the package id is the package):

packages          name = package id as stored (the handler lower-cases it),
                  name_key = lower(package id): every lookup is by name_key
package_versions  version = version_key = the normalised version; metadata
                  {title, description, summary, authors, owners, tags,
                  project_url, license_url, icon_url, min_client_version
                  (empty values omitted), require_license_acceptance,
                  is_prerelease (always written), dependency_groups
                  (omitted until derived; written, also as [], once
                  derived)}
package_files     path <id>/<version>/<id>.<version>.nupkg (the flat
                  container path), filename <id>.<version>.nupkg, the nupkg
                  blob, role primary, download_count (the package's
                  counter), unit_key <id>@<version> (federation)

The id of a package version is package_files.id. A duplicate publish is a live version with a live file: ErrDuplicate, the stored content stays.

func (NuGetStore) AuthCacheGeneration added in v0.15.0

func (p NuGetStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (NuGetStore) AuthCacheTTL added in v0.15.0

func (p NuGetStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (NuGetStore) BeginTx added in v0.15.0

func (p NuGetStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (NuGetStore) Close added in v0.15.0

func (p NuGetStore) Close() error

Close writes the pending download counts and closes the database connection.

func (NuGetStore) CountFileDownload added in v0.19.0

func (p NuGetStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*NuGetStore) CreateNuGetPackage added in v0.15.0

func (p *NuGetStore) CreateNuGetPackage(ctx context.Context, pkg *models.NuGetPackage) error

func (*NuGetStore) DeleteNuGetPackage added in v0.15.0

func (p *NuGetStore) DeleteNuGetPackage(ctx context.Context, repoID, packageID, version string) error

DeleteNuGetPackage hard-deletes the live file of a package version; the version and the package go with their last file.

func (NuGetStore) FlushDownloadCounts added in v0.19.0

func (p NuGetStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (NuGetStore) GetDB added in v0.15.0

func (p NuGetStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*NuGetStore) GetNuGetPackage added in v0.15.0

func (p *NuGetStore) GetNuGetPackage(ctx context.Context, repoID, packageID, version string) (*models.NuGetPackage, error)

func (*NuGetStore) ListNuGetPackageVersions added in v0.15.0

func (p *NuGetStore) ListNuGetPackageVersions(ctx context.Context, repoID, packageID string) ([]*models.NuGetPackage, error)

func (*NuGetStore) ListNuGetPackages added in v0.15.0

func (p *NuGetStore) ListNuGetPackages(ctx context.Context, repoID string) ([]*models.NuGetPackage, error)

func (NuGetStore) Migrate added in v0.15.0

func (p NuGetStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (*NuGetStore) NuGetVersionsStamp added in v0.19.0

func (p *NuGetStore) NuGetVersionsStamp(ctx context.Context, repoID, packageID string) (string, error)

NuGetVersionsStamp is a cheap validator of the version list and registration index of one package: it changes exactly when a live version is added or removed.

func (NuGetStore) Ping added in v0.15.0

func (p NuGetStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (NuGetStore) PoolStat added in v0.15.0

func (p NuGetStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*NuGetStore) SearchNuGetPackages added in v0.15.0

func (p *NuGetStore) SearchNuGetPackages(ctx context.Context, repoID, query string, skip, take int) ([]*models.NuGetPackage, int, error)

SearchNuGetPackages pages over matching packages: skip/take count packages, the total is the number of matching packages, and every live version of each package on the page is returned (grouped by package id, oldest first).

func (*NuGetStore) SetNuGetDependencyGroups added in v0.15.0

func (p *NuGetStore) SetNuGetDependencyGroups(ctx context.Context, repoID, packageID, version string, groups []byte) error

SetNuGetDependencyGroups records the dependency groups of a package that has none stored yet. A stored value is never overwritten and the file's updated_at is not touched.

type OIDCPolicyStore added in v0.16.0

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

OIDCPolicyStore owns the CI OIDC trust policies: the rules that exchange an ID token of an external issuer for a token of a service account.

Policies are read uncached: a policy an administrator disables or deletes must stop matching at once, and the exchange is nowhere near a hot path.

func (OIDCPolicyStore) AuthCacheGeneration added in v0.16.0

func (p OIDCPolicyStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (OIDCPolicyStore) AuthCacheTTL added in v0.16.0

func (p OIDCPolicyStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (OIDCPolicyStore) BeginTx added in v0.16.0

func (p OIDCPolicyStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (OIDCPolicyStore) Close added in v0.16.0

func (p OIDCPolicyStore) Close() error

Close writes the pending download counts and closes the database connection.

func (OIDCPolicyStore) CountFileDownload added in v0.19.0

func (p OIDCPolicyStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*OIDCPolicyStore) CreateOIDCPolicy added in v0.16.0

func (p *OIDCPolicyStore) CreateOIDCPolicy(ctx context.Context, pol *models.OIDCTrustPolicy) (*models.OIDCTrustPolicy, error)

CreateOIDCPolicy stores a policy and returns it with its id and times. A name that is taken is IsUniqueViolation; a service account that does not exist is IsForeignKeyViolation.

func (*OIDCPolicyStore) DeleteOIDCPolicy added in v0.16.0

func (p *OIDCPolicyStore) DeleteOIDCPolicy(ctx context.Context, id string) (bool, error)

DeleteOIDCPolicy deletes a policy and reports whether it existed.

func (OIDCPolicyStore) FlushDownloadCounts added in v0.19.0

func (p OIDCPolicyStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (OIDCPolicyStore) GetDB added in v0.16.0

func (p OIDCPolicyStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*OIDCPolicyStore) GetOIDCPolicy added in v0.16.0

func (p *OIDCPolicyStore) GetOIDCPolicy(ctx context.Context, id string) (*models.OIDCTrustPolicy, error)

GetOIDCPolicy returns the policy with the id, nil when there is none.

func (*OIDCPolicyStore) ListEnabledOIDCPoliciesByIssuer added in v0.16.0

func (p *OIDCPolicyStore) ListEnabledOIDCPoliciesByIssuer(ctx context.Context, issuer string) ([]*models.OIDCTrustPolicy, error)

ListEnabledOIDCPoliciesByIssuer returns the enabled policies of an issuer, oldest first, so the first match of an exchange is stable.

func (*OIDCPolicyStore) ListOIDCPolicies added in v0.16.0

func (p *OIDCPolicyStore) ListOIDCPolicies(ctx context.Context) ([]*models.OIDCTrustPolicy, error)

ListOIDCPolicies returns every policy by name.

func (OIDCPolicyStore) Migrate added in v0.16.0

func (p OIDCPolicyStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (OIDCPolicyStore) Ping added in v0.16.0

func (p OIDCPolicyStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (OIDCPolicyStore) PoolStat added in v0.16.0

func (p OIDCPolicyStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*OIDCPolicyStore) UpdateOIDCPolicy added in v0.16.0

func (p *OIDCPolicyStore) UpdateOIDCPolicy(ctx context.Context, pol *models.OIDCTrustPolicy) (*models.OIDCTrustPolicy, error)

UpdateOIDCPolicy replaces every editable field of the policy (name, issuer, audience, conditions, service account, ttl, enabled, discovery) and returns it, nil when there is no such policy.

type OSVMirror added in v0.15.0

type OSVMirror interface {
	// ApplyOSVAdvisories stores the advisories that are new or modified later
	// than the stored copy (the others are skipped) and returns the packages
	// whose advisories changed: the old and the new affected packages of every
	// changed record. It flags the ecosystems of those packages as having a
	// re-match pending, in the same transaction.
	ApplyOSVAdvisories(ctx context.Context, advisories []models.OSVAdvisory) ([]models.OSVPackageKey, error)

	// ListOSVAdvisoryIDs returns the ids of the advisories that have an
	// affected package in the ecosystem (withdrawn ones included).
	ListOSVAdvisoryIDs(ctx context.Context, ecosystem string) ([]string, error)

	// RemoveOSVAdvisories drops the affected packages of the ecosystem from
	// the given advisories, which its export no longer lists, and deletes the
	// advisories (and their aliases) left without any affected package. It
	// returns the packages that lost an advisory and flags the ecosystem as
	// having a re-match pending, in the same transaction.
	RemoveOSVAdvisories(ctx context.Context, ecosystem string, ids []string) ([]models.OSVPackageKey, error)

	// GetOSVMirrorState returns the import state of an ecosystem, nil when it
	// has none.
	GetOSVMirrorState(ctx context.Context, ecosystem string) (*models.OSVMirrorState, error)

	// ListOSVMirrorStates returns the import state of every ecosystem, by name.
	ListOSVMirrorStates(ctx context.Context) ([]models.OSVMirrorState, error)

	// SaveOSVMirrorState upserts the import state of an ecosystem. It never
	// touches RematchPending, which ApplyOSVAdvisories and
	// FinishOSVRematch own.
	SaveOSVMirrorState(ctx context.Context, st *models.OSVMirrorState) error

	// FinishOSVRematch clears the pending flag of an ecosystem and records when
	// its re-match started and how long it took.
	FinishOSVRematch(ctx context.Context, ecosystem string, started time.Time, took time.Duration) error

	// CountOSVAdvisories counts the live (not withdrawn) advisories affecting
	// an ecosystem.
	CountOSVAdvisories(ctx context.Context, ecosystem string) (int, error)

	// ListOSVAdvisoriesForPackages returns the live advisories that name each
	// of the normalized package names, keyed by that name.
	ListOSVAdvisoriesForPackages(ctx context.Context, ecosystem string, namesNorm []string) (map[string][]models.OSVAdvisoryMatch, error)

	// OSVCVEAliases returns, for each of the given advisory ids (or aliases)
	// the mirror holds, the CVE ids among the aliases of its record; ids the
	// mirror does not hold are absent, so an empty mirror yields an empty map.
	OSVCVEAliases(ctx context.Context, ids []string) (map[string][]string, error)

	// ListStoredPackages pages the package versions hosted repositories hold
	// for a format (one row per repository, name and version), in (repository,
	// name, version) order after the given position (nil: from the start).
	ListStoredPackages(ctx context.Context, format string, after *models.StoredPackage, limit int) ([]models.StoredPackage, error)

	// ListProxyCacheKeys pages the cached files of the proxy repositories of a
	// format, in id order after afterID ("": from the start).
	ListProxyCacheKeys(ctx context.Context, format, afterID string, limit int) ([]models.ProxyCacheKey, error)

	// GetOSVScanResults returns the results of the osv scanner for the given
	// package versions, keyed by OSVResultKey.
	GetOSVScanResults(ctx context.Context, pkgs []models.StoredPackage) (map[string]*models.VulnScanResult, error)

	// SaveOSVScanResult stores a result of the osv scanner for its artifact:
	// it creates the result or replaces the findings of the existing one and
	// leaves its quarantine flag alone (policies own it).
	SaveOSVScanResult(ctx context.Context, result *models.VulnScanResult) error
}

OSVMirror is the local mirror of the OSV database and the lookups its re-match needs. It is implemented by *PostgresDB and found with a type assertion on Database (like AuditRetentionStore).

type OSVStore added in v0.14.0

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

OSVStore owns the mirrored OSV advisories and per-package OSV scan results.

func (*OSVStore) ApplyOSVAdvisories added in v0.14.0

func (p *OSVStore) ApplyOSVAdvisories(ctx context.Context, advisories []models.OSVAdvisory) ([]models.OSVPackageKey, error)

ApplyOSVAdvisories implements OSVMirror.

func (OSVStore) AuthCacheGeneration added in v0.15.0

func (p OSVStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (OSVStore) AuthCacheTTL added in v0.15.0

func (p OSVStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (OSVStore) BeginTx added in v0.15.0

func (p OSVStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (OSVStore) Close added in v0.15.0

func (p OSVStore) Close() error

Close writes the pending download counts and closes the database connection.

func (OSVStore) CountFileDownload added in v0.19.0

func (p OSVStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*OSVStore) CountOSVAdvisories added in v0.14.0

func (p *OSVStore) CountOSVAdvisories(ctx context.Context, ecosystem string) (int, error)

CountOSVAdvisories implements OSVMirror.

func (*OSVStore) FinishOSVRematch added in v0.14.0

func (p *OSVStore) FinishOSVRematch(ctx context.Context, ecosystem string, started time.Time, took time.Duration) error

FinishOSVRematch implements OSVMirror.

func (OSVStore) FlushDownloadCounts added in v0.19.0

func (p OSVStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (OSVStore) GetDB added in v0.15.0

func (p OSVStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*OSVStore) GetOSVMirrorState added in v0.14.0

func (p *OSVStore) GetOSVMirrorState(ctx context.Context, ecosystem string) (*models.OSVMirrorState, error)

GetOSVMirrorState implements OSVMirror.

func (*OSVStore) GetOSVScanResults added in v0.14.0

func (p *OSVStore) GetOSVScanResults(ctx context.Context, pkgs []models.StoredPackage) (map[string]*models.VulnScanResult, error)

GetOSVScanResults implements OSVMirror.

func (*OSVStore) ListOSVAdvisoriesForPackages added in v0.14.0

func (p *OSVStore) ListOSVAdvisoriesForPackages(
	ctx context.Context, ecosystem string, namesNorm []string,
) (map[string][]models.OSVAdvisoryMatch, error)

ListOSVAdvisoriesForPackages implements OSVMirror.

func (*OSVStore) ListOSVAdvisoryIDs added in v0.15.0

func (p *OSVStore) ListOSVAdvisoryIDs(ctx context.Context, ecosystem string) ([]string, error)

ListOSVAdvisoryIDs implements OSVMirror.

func (*OSVStore) ListOSVMirrorStates added in v0.14.0

func (p *OSVStore) ListOSVMirrorStates(ctx context.Context) ([]models.OSVMirrorState, error)

ListOSVMirrorStates implements OSVMirror.

func (*OSVStore) ListStoredPackages added in v0.14.0

func (p *OSVStore) ListStoredPackages(
	ctx context.Context, format string, after *models.StoredPackage, limit int,
) ([]models.StoredPackage, error)

ListStoredPackages implements OSVMirror.

func (OSVStore) Migrate added in v0.15.0

func (p OSVStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (*OSVStore) OSVCVEAliases added in v0.14.0

func (p *OSVStore) OSVCVEAliases(ctx context.Context, ids []string) (map[string][]string, error)

OSVCVEAliases implements OSVMirror.

func (OSVStore) Ping added in v0.15.0

func (p OSVStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (OSVStore) PoolStat added in v0.15.0

func (p OSVStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*OSVStore) RemoveOSVAdvisories added in v0.15.0

func (p *OSVStore) RemoveOSVAdvisories(ctx context.Context, ecosystem string, ids []string) ([]models.OSVPackageKey, error)

RemoveOSVAdvisories implements OSVMirror.

func (*OSVStore) SaveOSVMirrorState added in v0.14.0

func (p *OSVStore) SaveOSVMirrorState(ctx context.Context, st *models.OSVMirrorState) error

SaveOSVMirrorState implements OSVMirror.

func (*OSVStore) SaveOSVScanResult added in v0.14.0

func (p *OSVStore) SaveOSVScanResult(ctx context.Context, result *models.VulnScanResult) error

SaveOSVScanResult implements OSVMirror.

type PackageRowKind added in v0.15.0

type PackageRowKind string

PackageRowKind selects which table of the package model a PackageRowSet is.

const (
	// PackageRowsCompanion is a repository-scoped table side rows reference.
	PackageRowsCompanion PackageRowKind = "companion"
	// PackageRowsPackages is the packages table.
	PackageRowsPackages PackageRowKind = "packages"
	// PackageRowsVersions is the package_versions table.
	PackageRowsVersions PackageRowKind = "package_versions"
	// PackageRowsFiles is the package_files table.
	PackageRowsFiles PackageRowKind = "package_files"
	// PackageRowsSide is a side table of package_files.
	PackageRowsSide PackageRowKind = "side"
	// PackageRowsTags is the package_tags table.
	PackageRowsTags PackageRowKind = "package_tags"
)

The kinds of row sets of a repository's package data, in restore order (parents first).

type PackageRowSet added in v0.15.0

type PackageRowSet struct {
	Kind PackageRowKind
	// Table is the table of a PackageRowsSide or PackageRowsCompanion set (a
	// plain identifier from a storage descriptor).
	Table string
	// Scope is the SQL condition over the alias t selecting a companion's rows of
	// repository $1 (export only).
	Scope string
	// RepoColumn is the companion column set to the new repository on restore.
	RepoColumn string
	// Refs are the uuid columns that reference companion ids (restore only).
	Refs []string
}

PackageRowSet names one table of a repository's package data to export or restore.

func (PackageRowSet) Name added in v0.15.0

func (s PackageRowSet) Name() string

Name is the table the set reads and writes.

type PackageWrite added in v0.15.0

type PackageWrite struct {
	RepoID string
	// Format is the repository format; it is stored on the package.
	Format string
	// Name is the display (listing) name, NameKey the identity inside the
	// repository (the normalised name; equal to Name when the format does not
	// normalise).
	Name, NameKey string
	// PkgAttrs is merged into packages.attrs.
	PkgAttrs map[string]any
	// Version is the display version, VersionKey its identity inside the
	// package (the version plus the coordinates the format keys on).
	Version, VersionKey string
	// VersionMeta is stored as package_versions.metadata of a new version; for
	// an existing live version it replaces the stored value only when
	// ReplaceVersionMeta is set.
	VersionMeta        any
	ReplaceVersionMeta bool
	// Exclusive makes the write fail with ErrDuplicate when the live version
	// already has a live file (a format whose upload is one file per version).
	Exclusive bool
	// CreatedAt overrides the creation time of the rows (restores and imports).
	CreatedAt time.Time
	Files     []FileWrite
}

PackageWrite is one upload: a package, one version of it and the files of that version, written together.

type PackageWritten added in v0.15.0

type PackageWritten struct {
	PackageID      string
	VersionID      string
	VersionCreated bool
	Files          []FileWritten
}

PackageWritten is the result of writePackage: the ids of the rows written, in the order of PackageWrite.Files for the files.

type PacmanStore added in v0.15.0

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

PacmanStore owns the Arch Linux pacman packages.

A pacman package lives on the generic package tables (packages P, package_versions V, package_files F) plus the side table pacman_files. Grain 1:1: one package file of (name, version, arch) is one P (shared by name), one V and one F. The mapping:

P  name, name_key = pkgname; attrs = {}
V  version        = [epoch:]pkgver-pkgrel as stored
   version_key    = version|arch (the legacy live key is name, version, arch; repo_arch
                    is not part of it)
   metadata       = {base, repo_arch, description, url, packager, licenses[],
                    package_groups[], replaces[], conflicts[], provides[], depends[],
                    optdepends[], makedepends[], checkdepends[]}; all keys written,
                    the arrays keep their order (the index emits them in that order)
F  path, filename = the published file name (it renders name-version-arch)
   arch           = the package's own arch ('any' or a CPU), not repo_arch
   blob_id        = the package blob; size_bytes = NULL; part = ''; checksums = {}
   attrs          = {build_time, installed_size, md5}: build_time (the legacy
                    build_date) and installed_size only when not zero, md5 always. md5
                    is not in checksums: checksum search never matched pacman
pacman_files (id = F.id): file_list (NULL = not read from the package yet: it stays NULL
   and SetPacmanFileList only writes where it is NULL), signature (base64, '' unsigned),
   signature_source ('' | 'uploader' | 'server'), signature_key (fingerprint, '')

func (PacmanStore) AuthCacheGeneration added in v0.15.0

func (p PacmanStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (PacmanStore) AuthCacheTTL added in v0.15.0

func (p PacmanStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (PacmanStore) BeginTx added in v0.15.0

func (p PacmanStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (PacmanStore) Close added in v0.15.0

func (p PacmanStore) Close() error

Close writes the pending download counts and closes the database connection.

func (PacmanStore) CountFileDownload added in v0.19.0

func (p PacmanStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*PacmanStore) CreatePacmanPackage added in v0.15.0

func (p *PacmanStore) CreatePacmanPackage(ctx context.Context, pkg *models.PacmanPackage) error

CreatePacmanPackage stores one package file. A live row with the same file name, or the same name, version and architecture, is ErrDuplicate.

func (*PacmanStore) DeletePacmanPackage added in v0.15.0

func (p *PacmanStore) DeletePacmanPackage(ctx context.Context, repoID, id string) error

DeletePacmanPackage removes a live package row (and its version and package when nothing else holds them).

func (PacmanStore) FlushDownloadCounts added in v0.19.0

func (p PacmanStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (PacmanStore) GetDB added in v0.15.0

func (p PacmanStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*PacmanStore) GetPacmanPackageByFilename added in v0.15.0

func (p *PacmanStore) GetPacmanPackageByFilename(ctx context.Context, repoID, filename string) (*models.PacmanPackage, error)

GetPacmanPackageByFilename returns the live package published under the file name, or (nil, nil).

func (*PacmanStore) ListPacmanFileLists added in v0.15.0

func (p *PacmanStore) ListPacmanFileLists(ctx context.Context, repoID string) (map[string]string, error)

ListPacmanFileLists returns the file lists of the live packages that have one.

func (*PacmanStore) ListPacmanPackages added in v0.15.0

func (p *PacmanStore) ListPacmanPackages(ctx context.Context, repoID string) ([]*models.PacmanPackage, error)

ListPacmanPackages returns every live package of the repository, without file lists.

func (*PacmanStore) ListPacmanPackagesWithoutFileList added in v0.15.0

func (p *PacmanStore) ListPacmanPackagesWithoutFileList(ctx context.Context, repoID string) ([]*models.PacmanPackage, error)

ListPacmanPackagesWithoutFileList returns the live packages that still need their file list read from the blob.

func (PacmanStore) Migrate added in v0.15.0

func (p PacmanStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (PacmanStore) Ping added in v0.15.0

func (p PacmanStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (PacmanStore) PoolStat added in v0.15.0

func (p PacmanStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*PacmanStore) SetPacmanFileList added in v0.15.0

func (p *PacmanStore) SetPacmanFileList(ctx context.Context, repoID, id, fileList string) error

SetPacmanFileList records the file list of a package that has none.

func (*PacmanStore) SetPacmanSignature added in v0.15.0

func (p *PacmanStore) SetPacmanSignature(ctx context.Context, repoID, id, signature, source, key string) error

SetPacmanSignature records the signature of a package file.

type PermissionStore added in v0.15.0

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

PermissionStore owns permission targets and their user/group assignments.

func (PermissionStore) AuthCacheGeneration added in v0.15.0

func (p PermissionStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (PermissionStore) AuthCacheTTL added in v0.15.0

func (p PermissionStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (PermissionStore) BeginTx added in v0.15.0

func (p PermissionStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (PermissionStore) Close added in v0.15.0

func (p PermissionStore) Close() error

Close writes the pending download counts and closes the database connection.

func (PermissionStore) CountFileDownload added in v0.19.0

func (p PermissionStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*PermissionStore) CreatePermissionAssignment added in v0.15.0

func (p *PermissionStore) CreatePermissionAssignment(ctx context.Context, assignment *models.PermissionAssignment) error

func (*PermissionStore) CreatePermissionTarget added in v0.15.0

func (p *PermissionStore) CreatePermissionTarget(ctx context.Context, target *models.PermissionTarget) (*models.PermissionTarget, error)

func (*PermissionStore) DeletePermissionAssignment added in v0.15.0

func (p *PermissionStore) DeletePermissionAssignment(ctx context.Context, targetID, principalType, principalID string) error

DeletePermissionAssignment removes one assignment. Removing the admin-all grant of the last enabled admin returns ErrLastAdmin.

func (*PermissionStore) DeletePermissionTarget added in v0.15.0

func (p *PermissionStore) DeletePermissionTarget(ctx context.Context, id string) error

func (PermissionStore) FlushDownloadCounts added in v0.19.0

func (p PermissionStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (PermissionStore) GetDB added in v0.15.0

func (p PermissionStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*PermissionStore) GetOrCreatePermissionAssignment added in v0.15.0

func (p *PermissionStore) GetOrCreatePermissionAssignment(ctx context.Context, targetID, principalType, principalID string) error

func (*PermissionStore) GetPermissionTargetByID added in v0.15.0

func (p *PermissionStore) GetPermissionTargetByID(ctx context.Context, id string) (*models.PermissionTarget, error)

func (*PermissionStore) GetPermissionTargetByName added in v0.15.0

func (p *PermissionStore) GetPermissionTargetByName(ctx context.Context, name string) (*models.PermissionTarget, error)

func (*PermissionStore) GetPermissionTargetsForPrincipal added in v0.15.0

func (p *PermissionStore) GetPermissionTargetsForPrincipal(
	ctx context.Context,
	userID string,
	groupIDs []string,
) ([]*models.PermissionTarget, error)

GetPermissionTargetsForPrincipal returns the permission targets held by a user and its groups, from the auth cache when fresh.

func (*PermissionStore) GetPermissionTargetsForPrincipalUncached added in v0.15.0

func (p *PermissionStore) GetPermissionTargetsForPrincipalUncached(
	ctx context.Context,
	userID string,
	groupIDs []string,
) ([]*models.PermissionTarget, error)

func (*PermissionStore) ListPermissionAssignments added in v0.15.0

func (p *PermissionStore) ListPermissionAssignments(ctx context.Context) ([]*models.PermissionAssignment, error)

ListPermissionAssignments returns every permission assignment (user and group principals alike).

func (*PermissionStore) ListPermissionAssignmentsForTarget added in v0.15.0

func (p *PermissionStore) ListPermissionAssignmentsForTarget(
	ctx context.Context,
	targetID string,
) ([]models.PermissionAssignmentView, error)

ListPermissionAssignmentsForTarget returns the assignments of one permission target with principal names, ordered by type then name.

func (*PermissionStore) ListPermissionTargets added in v0.15.0

func (p *PermissionStore) ListPermissionTargets(ctx context.Context) ([]*models.PermissionTarget, error)

func (PermissionStore) Migrate added in v0.15.0

func (p PermissionStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (*PermissionStore) PatchPermissionTarget added in v0.20.0

func (p *PermissionStore) PatchPermissionTarget(
	ctx context.Context, id string, patch PermissionTargetPatch,
) (*models.PermissionTarget, error)

PatchPermissionTarget writes only the columns in patch, so a concurrent edit of other columns is not reverted by a stale snapshot. It returns the updated row, or nil when the target does not exist.

func (PermissionStore) Ping added in v0.15.0

func (p PermissionStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (PermissionStore) PoolStat added in v0.15.0

func (p PermissionStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

type PermissionTargetPatch added in v0.20.0

type PermissionTargetPatch struct {
	Name             *string
	RepositoryFilter *string
	PathPattern      *string
	Actions          []string
}

PermissionTargetPatch names the columns an edit writes; nil fields leave the stored value alone.

type PipelinePatch added in v0.20.0

type PipelinePatch struct {
	Description *string
	Stages      *[]models.PipelineStage
}

PipelinePatch names the columns an edit writes; nil fields leave the stored value alone.

type PostgresDB

PostgresDB is the PostgreSQL database: the composition root that embeds one store per domain. Every store is a struct around the shared *core (pool, sqlc queries, caches) and lives in its own file(s); the method sets are promoted, so *PostgresDB satisfies whatever narrow interface a consumer declares. Consumers never depend on this type but on the small interfaces they declare themselves.

Package storage is split per format: each pkg_<format>.go is the typed store of one format over the generic tables packages, package_versions, package_files and package_tags (plus the side tables conan_files, deb_files, maven_files, pacman_files and rpm_files), written through writePackage/deleteFiles in pkg_generic.go. Docker is the one format with dedicated tables (docker_*, docker.go). Everything that spans formats reads the generic tables once and never switches on the format: CatalogStore (listing, catalog_branches.go), the blobRefSpecs in blob_refs.go (package_files.blob_id plus the docker and side tables that own a blob column), TrashStore, tiering and quota usage. The per-format differences are data: the storage.Storage descriptor each format registers (internal/format/storage). A new format adds a pkg_<format>.go and its queries, and no branch to any cross-format query.

func NewPostgresDB

func NewPostgresDB(cfg DatabaseConfig, log *logger.Logger) (*PostgresDB, error)

func (PostgresDB) AuthCacheGeneration added in v0.7.0

func (p PostgresDB) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (PostgresDB) AuthCacheTTL added in v0.7.0

func (p PostgresDB) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (PostgresDB) BeginTx

func (p PostgresDB) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (PostgresDB) Close

func (p PostgresDB) Close() error

Close writes the pending download counts and closes the database connection.

func (PostgresDB) CountFileDownload added in v0.19.0

func (p PostgresDB) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (PostgresDB) FlushDownloadCounts added in v0.19.0

func (p PostgresDB) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (PostgresDB) GetDB

func (p PostgresDB) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (PostgresDB) Migrate

func (p PostgresDB) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (PostgresDB) Ping

func (p PostgresDB) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (PostgresDB) PoolStat added in v0.9.0

func (p PostgresDB) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

type PostgresTx

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

PostgresTx implements the Transaction interface for PostgreSQL.

func (*PostgresTx) Commit

func (t *PostgresTx) Commit() error

Commit commits the transaction.

func (*PostgresTx) ExecContext

func (t *PostgresTx) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

ExecContext executes a query without returning rows.

func (*PostgresTx) QueryContext

func (t *PostgresTx) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

QueryContext executes a query that returns rows.

func (*PostgresTx) QueryRowContext

func (t *PostgresTx) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row

QueryRowContext executes a query that returns a single row.

func (*PostgresTx) Rollback

func (t *PostgresTx) Rollback() error

Rollback rolls back the transaction.

type PresignedUploadStore added in v0.15.0

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

PresignedUploadStore owns presigned upload sessions.

func (PresignedUploadStore) AuthCacheGeneration added in v0.15.0

func (p PresignedUploadStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (PresignedUploadStore) AuthCacheTTL added in v0.15.0

func (p PresignedUploadStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (PresignedUploadStore) BeginTx added in v0.15.0

func (p PresignedUploadStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (*PresignedUploadStore) ClaimPresignedUpload added in v0.15.0

func (p *PresignedUploadStore) ClaimPresignedUpload(ctx context.Context, repoID, id string, lease time.Duration) (bool, error)

ClaimPresignedUpload takes the complete lease of an upload for up to lease. It reports false when the upload is already completed, does not exist, or another complete holds an unexpired lease.

func (PresignedUploadStore) Close added in v0.15.0

func (p PresignedUploadStore) Close() error

Close writes the pending download counts and closes the database connection.

func (PresignedUploadStore) CountFileDownload added in v0.19.0

func (p PresignedUploadStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*PresignedUploadStore) CreatePresignedUpload added in v0.15.0

func (p *PresignedUploadStore) CreatePresignedUpload(ctx context.Context, u *models.PresignedUpload) error

CreatePresignedUpload records a presigned upload and fills u.ID and u.CreatedAt.

func (*PresignedUploadStore) CreatePresignedUploadCapped added in v0.15.0

func (p *PresignedUploadStore) CreatePresignedUploadCapped(ctx context.Context, u *models.PresignedUpload, maxPending int) error

CreatePresignedUploadCapped counts the user's outstanding uploads and inserts the new one in one transaction holding a per-user advisory lock, so parallel creates cannot all pass the check before any of them inserts.

func (*PresignedUploadStore) DeletePresignedUpload added in v0.15.0

func (p *PresignedUploadStore) DeletePresignedUpload(ctx context.Context, id string) error

DeletePresignedUpload removes a presigned upload row.

func (*PresignedUploadStore) ExistingPresignedUploadIDs added in v0.15.0

func (p *PresignedUploadStore) ExistingPresignedUploadIDs(ctx context.Context, ids []string) ([]string, error)

ExistingPresignedUploadIDs returns the subset of ids that have a row. Ids that are not UUIDs cannot have one and are dropped.

func (*PresignedUploadStore) ExtendPresignedUploadExpiry added in v0.15.0

func (p *PresignedUploadStore) ExtendPresignedUploadExpiry(ctx context.Context, id string, expiresAt time.Time) error

ExtendPresignedUploadExpiry moves the complete deadline of a pending upload forward to expiresAt; it never shortens it.

func (PresignedUploadStore) FlushDownloadCounts added in v0.19.0

func (p PresignedUploadStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (PresignedUploadStore) GetDB added in v0.15.0

func (p PresignedUploadStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*PresignedUploadStore) GetPresignedUpload added in v0.15.0

func (p *PresignedUploadStore) GetPresignedUpload(ctx context.Context, repoID, id string) (*models.PresignedUpload, error)

GetPresignedUpload returns the presigned upload id of repository repoID, or nil, nil when there is none.

func (*PresignedUploadStore) ListExpiredPresignedUploads added in v0.15.0

func (p *PresignedUploadStore) ListExpiredPresignedUploads(ctx context.Context, limit int) ([]string, error)

ListExpiredPresignedUploads returns up to limit ids of presigned uploads past their complete deadline.

func (*PresignedUploadStore) MarkPresignedUploadCompleted added in v0.15.0

func (p *PresignedUploadStore) MarkPresignedUploadCompleted(ctx context.Context, id, artifactID string) error

MarkPresignedUploadCompleted records that the upload produced artifactID.

func (PresignedUploadStore) Migrate added in v0.15.0

func (p PresignedUploadStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (PresignedUploadStore) Ping added in v0.15.0

func (p PresignedUploadStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (PresignedUploadStore) PoolStat added in v0.15.0

func (p PresignedUploadStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*PresignedUploadStore) ReleasePresignedUpload added in v0.15.0

func (p *PresignedUploadStore) ReleasePresignedUpload(ctx context.Context, id string) error

ReleasePresignedUpload gives up the lease of an upload that was not completed.

func (*PresignedUploadStore) SetPresignedUploadMultipartID added in v0.15.0

func (p *PresignedUploadStore) SetPresignedUploadMultipartID(ctx context.Context, id, multipartID string) error

SetPresignedUploadMultipartID records the backend handle of the upload's open multipart upload.

type ProjectPatch added in v0.20.0

type ProjectPatch struct {
	DisplayName      *string
	Description      *string
	AllowedFormats   *[]string
	AllowedRepoTypes []string
	RepoNamePrefix   *string
	AllowPublicRepos *bool
	MaxRepositories  *int
	TokenMaxTTLDays  *int
}

ProjectPatch names the columns an edit writes; nil fields leave the stored value alone. A non-nil AllowedFormats replaces the list, an empty one meaning every format (NULL).

type ProjectRoleGuard added in v0.6.0

type ProjectRoleGuard func(current string) error

ProjectRoleGuard decides a member or group change while the project row is locked. current is the target's role before the change ("" when the target has none); a non-nil error vetoes the change and is returned unchanged.

type ProjectStore added in v0.15.0

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

ProjectStore owns projects, their members, groups and tokens.

func (*ProjectStore) AddProjectMember added in v0.15.0

func (p *ProjectStore) AddProjectMember(ctx context.Context, projectID, userID, role string) error

func (ProjectStore) AuthCacheGeneration added in v0.15.0

func (p ProjectStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (ProjectStore) AuthCacheTTL added in v0.15.0

func (p ProjectStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (ProjectStore) BeginTx added in v0.15.0

func (p ProjectStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (*ProjectStore) ChangeProjectGroup added in v0.15.0

func (p *ProjectStore) ChangeProjectGroup(
	ctx context.Context,
	projectID, groupID, newRole string,
	createdBy *string,
	guard ProjectRoleGuard,
) error

ChangeProjectGroup attaches a group with newRole, changes its role, or detaches it (newRole == ""), in one transaction that holds the project row lock; the guard sees the group's current role ("" when not attached).

func (*ProjectStore) ChangeProjectMember added in v0.15.0

func (p *ProjectStore) ChangeProjectMember(ctx context.Context, projectID, userID, newRole string, guard ProjectRoleGuard) error

ChangeProjectMember sets, adds or removes (newRole == "") a user's project role in one transaction that holds the project row lock, so the guard, the recorded-owner and last-owner checks and the write see one consistent state and concurrent changes serialize. The guard runs first; then the invariants ErrProjectOwnerLocked and ErrLastProjectOwner apply.

func (ProjectStore) Close added in v0.15.0

func (p ProjectStore) Close() error

Close writes the pending download counts and closes the database connection.

func (ProjectStore) CountFileDownload added in v0.19.0

func (p ProjectStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*ProjectStore) CountRepositoriesByProject added in v0.15.0

func (p *ProjectStore) CountRepositoriesByProject(ctx context.Context, projectIDs []string) (map[string]int, error)

CountRepositoriesByProject returns the number of live repositories per project for the given project IDs (projects without any are absent).

func (*ProjectStore) CreateProject added in v0.15.0

func (p *ProjectStore) CreateProject(ctx context.Context, project *models.Project) error

func (*ProjectStore) CreateProjectToken added in v0.15.0

func (p *ProjectStore) CreateProjectToken(ctx context.Context, spec ProjectTokenSpec) (*models.Token, error)

CreateProjectToken creates, in one transaction that holds the project row lock, the service user, its membership with the token's role and the deploy token. It returns ErrProjectNotFound, ErrProjectTokenLimit or ErrProjectTokenName when the token cannot be minted.

func (*ProjectStore) DeleteProject added in v0.15.0

func (p *ProjectStore) DeleteProject(ctx context.Context, id string) error

func (ProjectStore) FlushDownloadCounts added in v0.19.0

func (p ProjectStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (ProjectStore) GetDB added in v0.15.0

func (p ProjectStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*ProjectStore) GetProject added in v0.15.0

func (p *ProjectStore) GetProject(ctx context.Context, id string) (*models.Project, error)

func (*ProjectStore) GetProjectByName added in v0.15.0

func (p *ProjectStore) GetProjectByName(ctx context.Context, name string) (*models.Project, error)

func (*ProjectStore) GetProjectGroup added in v0.15.0

func (p *ProjectStore) GetProjectGroup(ctx context.Context, projectID, groupID string) (*models.ProjectGroup, error)

func (*ProjectStore) GetProjectMember added in v0.15.0

func (p *ProjectStore) GetProjectMember(ctx context.Context, projectID, userID string) (*models.ProjectMember, error)

func (*ProjectStore) ListAllProjects added in v0.15.0

func (p *ProjectStore) ListAllProjects(ctx context.Context) ([]*models.Project, error)

func (*ProjectStore) ListProjectGrantsByUser added in v0.15.0

func (p *ProjectStore) ListProjectGrantsByUser(ctx context.Context, userID string) ([]*models.ProjectGrant, error)

ListProjectGrantsByUser returns the project grants of a user (see models.ProjectGrant), from the auth cache when fresh.

func (*ProjectStore) ListProjectGroups added in v0.15.0

func (p *ProjectStore) ListProjectGroups(ctx context.Context, projectID string) ([]*models.ProjectGroup, error)

func (*ProjectStore) ListProjectMembers added in v0.15.0

func (p *ProjectStore) ListProjectMembers(ctx context.Context, projectID string) ([]*models.ProjectMember, error)

func (*ProjectStore) ListProjectRepositories added in v0.15.0

func (p *ProjectStore) ListProjectRepositories(ctx context.Context, projectID string, page, limit int) ([]*models.Repository, int, error)

ListProjectRepositories returns one page of the project's live repositories, newest first, and their total number.

func (*ProjectStore) ListProjectStats added in v0.15.0

func (p *ProjectStore) ListProjectStats(ctx context.Context, projectIDs []string) (map[string]*models.ProjectStats, error)

ListProjectStats returns the member count, live usage and size ceiling of each given project in one query (projects that do not exist are absent).

func (*ProjectStore) ListProjectTokens added in v0.15.0

func (p *ProjectStore) ListProjectTokens(ctx context.Context, projectID string, createdBy *string) ([]*models.Token, error)

ListProjectTokens returns the project's tokens that are not revoked, newest first. createdBy limits them to the tokens minted by that user.

func (*ProjectStore) ListProjects added in v0.15.0

func (p *ProjectStore) ListProjects(ctx context.Context, userID string) ([]*models.Project, error)

ListProjects returns the projects the user belongs to (recorded owner, member, or through a group).

func (ProjectStore) Migrate added in v0.15.0

func (p ProjectStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (*ProjectStore) PatchProject added in v0.20.0

func (p *ProjectStore) PatchProject(ctx context.Context, id string, patch ProjectPatch) (*models.Project, error)

PatchProject writes only the columns in patch, so a concurrent edit of other columns is not reverted by a stale snapshot. It returns the updated row, or nil when the project does not exist.

func (ProjectStore) Ping added in v0.15.0

func (p ProjectStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (ProjectStore) PoolStat added in v0.15.0

func (p ProjectStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*ProjectStore) RevokeProjectToken added in v0.15.0

func (p *ProjectStore) RevokeProjectToken(ctx context.Context, projectID, tokenID string) (bool, error)

RevokeProjectToken revokes a token of the project and disables its service user in one transaction; the auth cache is dropped so the token stops working at once. It reports false when the project has no such active token.

func (*ProjectStore) SetProjectGroup added in v0.15.0

func (p *ProjectStore) SetProjectGroup(ctx context.Context, projectID, groupID, role string, createdBy *string) error

SetProjectGroup attaches the group to the project with role, or changes the role of an existing attachment.

type ProjectTokenSpec added in v0.6.0

type ProjectTokenSpec struct {
	ProjectID string
	// ProjectSlug seeds the service user's name.
	ProjectSlug string
	Name        string
	// Role is the token's project role (viewer or developer).
	Role      string
	CreatedBy string
	TokenHash string
	ExpiresAt *time.Time
	// MaxActive caps the active (not revoked) tokens of the project.
	MaxActive int
}

ProjectTokenSpec describes a project token to mint.

type PropertyStore added in v0.15.0

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

PropertyStore owns artifact properties.

func (PropertyStore) AuthCacheGeneration added in v0.15.0

func (p PropertyStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (PropertyStore) AuthCacheTTL added in v0.15.0

func (p PropertyStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (PropertyStore) BeginTx added in v0.15.0

func (p PropertyStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (PropertyStore) Close added in v0.15.0

func (p PropertyStore) Close() error

Close writes the pending download counts and closes the database connection.

func (PropertyStore) CountFileDownload added in v0.19.0

func (p PropertyStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*PropertyStore) DeleteArtifactProperty added in v0.15.0

func (p *PropertyStore) DeleteArtifactProperty(ctx context.Context, repoID, artifactID, key string) error

DeleteArtifactProperty deletes an artifact property.

func (PropertyStore) FlushDownloadCounts added in v0.19.0

func (p PropertyStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (PropertyStore) GetDB added in v0.15.0

func (p PropertyStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*PropertyStore) ListArtifactProperties added in v0.15.0

func (p *PropertyStore) ListArtifactProperties(ctx context.Context, repoID, artifactID string) (map[string]string, error)

ListArtifactProperties lists all properties for an artifact.

func (PropertyStore) Migrate added in v0.15.0

func (p PropertyStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (PropertyStore) Ping added in v0.15.0

func (p PropertyStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (PropertyStore) PoolStat added in v0.15.0

func (p PropertyStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*PropertyStore) SearchByProperty added in v0.15.0

func (p *PropertyStore) SearchByProperty(ctx context.Context, repoID, key, value string) ([]models.PropertyMatch, error)

SearchByProperty returns the artifacts of a repository whose property key equals value, sorted by id, each resolved to the stored file or docker tag it names when there is one (see models.PropertyMatch).

func (*PropertyStore) SetArtifactProperties added in v0.15.0

func (p *PropertyStore) SetArtifactProperties(ctx context.Context, repoID, artifactID string, props map[string]string, replace bool) error

SetArtifactProperties upserts all props for an artifact in a single transaction. When replace is true the artifact's existing properties are deleted first, in the same transaction.

type ProxyCacheStore added in v0.15.0

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

ProxyCacheStore owns the proxy cache entries.

func (ProxyCacheStore) AuthCacheGeneration added in v0.15.0

func (p ProxyCacheStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (ProxyCacheStore) AuthCacheTTL added in v0.15.0

func (p ProxyCacheStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (ProxyCacheStore) BeginTx added in v0.15.0

func (p ProxyCacheStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (ProxyCacheStore) Close added in v0.15.0

func (p ProxyCacheStore) Close() error

Close writes the pending download counts and closes the database connection.

func (ProxyCacheStore) CountFileDownload added in v0.19.0

func (p ProxyCacheStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*ProxyCacheStore) DeleteExpiredProxyCacheEntries added in v0.15.0

func (p *ProxyCacheStore) DeleteExpiredProxyCacheEntries(ctx context.Context) (int64, error)

func (*ProxyCacheStore) DeleteProxyCacheEntry added in v0.15.0

func (p *ProxyCacheStore) DeleteProxyCacheEntry(ctx context.Context, repoID, cacheKey string) error

func (ProxyCacheStore) FlushDownloadCounts added in v0.19.0

func (p ProxyCacheStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (ProxyCacheStore) GetDB added in v0.15.0

func (p ProxyCacheStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*ProxyCacheStore) GetProxyCacheEntry added in v0.15.0

func (p *ProxyCacheStore) GetProxyCacheEntry(ctx context.Context, repoID, cacheKey string) (*models.ProxyCacheEntry, error)

func (*ProxyCacheStore) ListCachedProxyKeys added in v0.16.1

func (p *ProxyCacheStore) ListCachedProxyKeys(ctx context.Context, repoID, prefix string, limit int) ([]string, error)

ListCachedProxyKeys lists the cache keys of the cached files of a repository that start with prefix, at most limit of them.

func (*ProxyCacheStore) ListProxyCacheKeys added in v0.15.0

func (p *ProxyCacheStore) ListProxyCacheKeys(ctx context.Context, format, afterID string, limit int) ([]models.ProxyCacheKey, error)

ListProxyCacheKeys implements OSVMirror.

func (ProxyCacheStore) Migrate added in v0.15.0

func (p ProxyCacheStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (ProxyCacheStore) Ping added in v0.15.0

func (p ProxyCacheStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (ProxyCacheStore) PoolStat added in v0.15.0

func (p ProxyCacheStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*ProxyCacheStore) UpsertProxyCacheEntry added in v0.15.0

func (p *ProxyCacheStore) UpsertProxyCacheEntry(ctx context.Context, entry *models.ProxyCacheEntry) error

type PyPIStore added in v0.15.0

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

PyPIStore owns the PyPI distributions.

Mapping onto the generic package tables (reference: one distribution file is one package_files row):

packages          one per PEP 503 normalised project name; name = name_key
                  = the name the handler stores, attrs = {}
package_versions  one per release: version = version_key = version;
                  metadata = {summary, author, author_email, license,
                  keywords, classifiers} of the release (last upload wins;
                  a further file of a release rewrites the same keys)
package_files     one per distribution file: path = name/version/filename
                  (live-unique, so a duplicate upload is ErrDuplicate),
                  filename = filename, arch = python tag ('' when none),
                  unit_key = path (the federation unit is the file),
                  attrs = {package_type, python_version, requires_python},
                  checksums = {} (only the blob's sha256 is recorded)

Cleanup note: the former retention partition was the package name only; the generic partition (package, arch, part) splits the files of a release by python tag, so pypi needs the "package only" partition from the cleanup engine.

func (PyPIStore) AuthCacheGeneration added in v0.15.0

func (p PyPIStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (PyPIStore) AuthCacheTTL added in v0.15.0

func (p PyPIStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (PyPIStore) BeginTx added in v0.15.0

func (p PyPIStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (PyPIStore) Close added in v0.15.0

func (p PyPIStore) Close() error

Close writes the pending download counts and closes the database connection.

func (PyPIStore) CountFileDownload added in v0.19.0

func (p PyPIStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*PyPIStore) CreatePyPIPackage added in v0.15.0

func (p *PyPIStore) CreatePyPIPackage(ctx context.Context, pkg *models.PyPIPackage) error

CreatePyPIPackage records one distribution file and its release. A live file of the same name, version and filename yields ErrDuplicate and nothing is written. pkg.MD5Digest does not round-trip: only the blob's sha256 is kept.

func (*PyPIStore) DeletePyPIPackage added in v0.15.0

func (p *PyPIStore) DeletePyPIPackage(ctx context.Context, repoID, name, version, filename string) error

DeletePyPIPackage hard-deletes one distribution file and, when it was the last one, its release and project.

func (PyPIStore) FlushDownloadCounts added in v0.19.0

func (p PyPIStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (PyPIStore) GetDB added in v0.15.0

func (p PyPIStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*PyPIStore) GetPyPIPackageByFilename added in v0.15.0

func (p *PyPIStore) GetPyPIPackageByFilename(ctx context.Context, repoID, filename string) (*models.PyPIPackage, error)

GetPyPIPackageByFilename returns the live file with this filename, nil when there is none and ErrAmbiguousPyPIFilename when several packages of the repository hold a file of that name.

func (*PyPIStore) ListPyPIPackageNames added in v0.15.0

func (p *PyPIStore) ListPyPIPackageNames(ctx context.Context, repoID string) ([]string, error)

ListPyPIPackageNames returns the stored project names of a repository that have a live release, sorted, without loading any file row.

func (*PyPIStore) ListPyPIPackageVersions added in v0.15.0

func (p *PyPIStore) ListPyPIPackageVersions(ctx context.Context, repoID, name string) ([]*models.PyPIPackage, error)

ListPyPIPackageVersions returns the live files of one project by its normalised name, newest version first.

func (PyPIStore) Migrate added in v0.15.0

func (p PyPIStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (PyPIStore) Ping added in v0.15.0

func (p PyPIStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (PyPIStore) PoolStat added in v0.15.0

func (p PyPIStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*PyPIStore) PyPIIndexStamp added in v0.19.0

func (p *PyPIStore) PyPIIndexStamp(ctx context.Context, repoID string) (string, error)

PyPIIndexStamp is a cheap validator of a repository's /simple/ root: it changes exactly when a project gains its first or loses its last live release.

func (*PyPIStore) PyPIProjectStamp added in v0.19.0

func (p *PyPIStore) PyPIProjectStamp(ctx context.Context, repoID, name string) (string, int64, error)

PyPIProjectStamp is a cheap validator of what one project's pages show (the simple page and the legacy JSON document): it returns the number of live files, 0 when the project does not exist, and a stamp that changes whenever a file is published, deleted, trashed or restored or a release's metadata is rewritten. name is the normalised project name.

type QuarantineStore added in v0.15.0

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

QuarantineStore owns the quarantine flag of secret-scanned artifacts.

func (*QuarantineStore) ArtifactHoldReason added in v0.21.0

func (p *QuarantineStore) ArtifactHoldReason(ctx context.Context, repoID string, keys []string) (quarantine.Reason, error)

ArtifactHoldReason says why the quarantined artifact identified by keys is held: quarantine.ReasonLicense when a license result flags it and no vulnerability or secret result does, quarantine.ReasonScan otherwise.

func (QuarantineStore) AuthCacheGeneration added in v0.15.0

func (p QuarantineStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (QuarantineStore) AuthCacheTTL added in v0.15.0

func (p QuarantineStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (QuarantineStore) BeginTx added in v0.15.0

func (p QuarantineStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (QuarantineStore) Close added in v0.15.0

func (p QuarantineStore) Close() error

Close writes the pending download counts and closes the database connection.

func (QuarantineStore) CountFileDownload added in v0.19.0

func (p QuarantineStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (QuarantineStore) FlushDownloadCounts added in v0.19.0

func (p QuarantineStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (QuarantineStore) GetDB added in v0.15.0

func (p QuarantineStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*QuarantineStore) HostedNamesHeld added in v0.24.0

func (p *QuarantineStore) HostedNamesHeld(ctx context.Context, repoIDs, names []string) ([]models.HeldName, error)

HostedNamesHeld returns, for the names of a batch lookup, which of the hosted repositories repoIDs hold a stored version of the package: the "hosted wins" ownership of a group. Index is the position in names. One query for every repository and name.

This must agree with serving, which decides ownership differently: a hosted member holds a name when it answers the format's package document with 200 (internal/group/hostedwins.go, PkgRef). A member with a live version that has a live file answers that document, and one without does not, so the two match today. A change to either side (what a hosted handler serves for a package with no live file, or this predicate) must keep them equal, or the batch availability answer stops following the group.

func (*QuarantineStore) HostedVersionsStored added in v0.24.0

func (p *QuarantineStore) HostedVersionsStored(
	ctx context.Context, repoIDs []string, versions []models.NameVersion,
) ([]models.StoredVersion, error)

HostedVersionsStored returns the stored versions among the package versions of a batch lookup in the hosted repositories repoIDs, each with the quarantine and license-policy holds PackageVersionHolds reports for it. Index is the position in versions. One query for every repository and version.

func (*QuarantineStore) IsArtifactQuarantined added in v0.15.0

func (p *QuarantineStore) IsArtifactQuarantined(ctx context.Context, repoID string, keys []string) (bool, error)

IsArtifactQuarantined reports whether any of keys (artifact_refs.artifact_path values) identifies an artifact of the repository whose vulnerability, secret or license scan result is flagged quarantined.

func (QuarantineStore) Migrate added in v0.15.0

func (p QuarantineStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (*QuarantineStore) PackageVersionHolds added in v0.16.0

func (p *QuarantineStore) PackageVersionHolds(ctx context.Context, repoID, pkg, version string) (models.VersionHolds, error)

PackageVersionHolds reports the scan holds of the live files of one version of a package of a repository whose format uses the generic package tables. Scan results hang on artifact_refs, keyed by the path a file is fetched from or its id, so a version is matched through its files' id, path and filename. pkg matches the package's display name or its identity key, version the version or its version key. A version without files, or a repository of a format outside the generic tables (docker), has no holds here.

func (QuarantineStore) Ping added in v0.15.0

func (p QuarantineStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (QuarantineStore) PoolStat added in v0.15.0

func (p QuarantineStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*QuarantineStore) QuarantineArtifact added in v0.15.0

func (p *QuarantineStore) QuarantineArtifact(ctx context.Context, repoID, artifactID string, quarantined bool) error

QuarantineArtifact updates the quarantine status of an artifact.

func (*QuarantineStore) QuarantinedKeys added in v0.19.0

func (p *QuarantineStore) QuarantinedKeys(ctx context.Context, repoID string, keys []string) ([]string, error)

QuarantinedKeys is IsArtifactQuarantined for many artifacts at once: it returns the subset of keys that identify a quarantined artifact of the repository, in one query (a listing checks every version it advertises).

type QuayRepositorySpec added in v0.21.0

type QuayRepositorySpec struct {
	ID           string
	RepositoryID string
	Name         string
	Description  string
	ReadTarget   models.PermissionTarget
	WriteTarget  models.PermissionTarget
}

QuayRepositorySpec describes a Quay repository to create: the row and the two permission targets that scope a principal to its image.

type QuayRobotSpec added in v0.21.0

type QuayRobotSpec struct {
	ID           string
	RepositoryID string
	Name         string
	Description  string
	Username     string
	TokenKind    string
	TokenName    string
	TokenHash    string
	TokenEnc     string
}

QuayRobotSpec describes a Quay robot account to create: the service account (its username), the deploy token minted for it and the sealed token the Quay API hands out again.

type QuayStore added in v0.21.0

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

QuayStore owns the state of the Quay-compatible API (internal/quayapi): the image paths, robot accounts, teams and notifications a Quay client created inside a hosted docker repository.

func (QuayStore) AuthCacheGeneration added in v0.21.0

func (p QuayStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (QuayStore) AuthCacheTTL added in v0.21.0

func (p QuayStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (QuayStore) BeginTx added in v0.21.0

func (p QuayStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (QuayStore) Close added in v0.21.0

func (p QuayStore) Close() error

Close writes the pending download counts and closes the database connection.

func (QuayStore) CountFileDownload added in v0.21.0

func (p QuayStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*QuayStore) CreateQuayNotification added in v0.21.0

func (p *QuayStore) CreateQuayNotification(ctx context.Context, n *models.QuayNotification) (*models.QuayNotification, error)

CreateQuayNotification stores a notification for a Quay repository.

func (*QuayStore) CreateQuayRepository added in v0.21.0

func (p *QuayStore) CreateQuayRepository(ctx context.Context, spec QuayRepositorySpec) (*models.QuayRepository, error)

CreateQuayRepository stores a Quay repository with its permission targets in one transaction. A clash with an existing image path is IsUniqueViolation.

func (*QuayStore) CreateQuayRobot added in v0.21.0

func (p *QuayStore) CreateQuayRobot(ctx context.Context, spec QuayRobotSpec) (*models.QuayRobot, error)

CreateQuayRobot creates the service account, its token and the robot row in one transaction. A clash with an existing robot name is IsUniqueViolation.

func (*QuayStore) CreateQuayTeam added in v0.21.0

func (p *QuayStore) CreateQuayTeam(ctx context.Context, repositoryID, name, groupName string) (*models.QuayTeam, error)

CreateQuayTeam creates a team and the group behind it (named groupName) in one transaction. A clash with an existing team is IsUniqueViolation.

func (*QuayStore) DeleteQuayNotification added in v0.21.0

func (p *QuayStore) DeleteQuayNotification(ctx context.Context, quayRepoID, id string) (bool, error)

DeleteQuayNotification deletes a notification and reports whether it existed.

func (*QuayStore) DeleteQuayRepository added in v0.21.0

func (p *QuayStore) DeleteQuayRepository(ctx context.Context, q *models.QuayRepository) error

DeleteQuayRepository removes a Quay repository: its tags (the manifests become untagged and the docker GC reclaims them), its permission targets with their assignments, and its notifications.

func (*QuayStore) DeleteQuayRobot added in v0.21.0

func (p *QuayStore) DeleteQuayRobot(ctx context.Context, b *models.QuayRobot) error

DeleteQuayRobot deletes a robot with its service account (and so its tokens and permission assignments).

func (QuayStore) FlushDownloadCounts added in v0.21.0

func (p QuayStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (QuayStore) GetDB added in v0.21.0

func (p QuayStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*QuayStore) GetQuayNotification added in v0.21.0

func (p *QuayStore) GetQuayNotification(ctx context.Context, quayRepoID, id string) (*models.QuayNotification, error)

GetQuayNotification returns one notification of a Quay repository, nil when there is none (or the id is not a UUID).

func (*QuayStore) GetQuayRepository added in v0.21.0

func (p *QuayStore) GetQuayRepository(ctx context.Context, repositoryID, name string) (*models.QuayRepository, error)

GetQuayRepository returns the Quay repository of an organization, nil when there is none.

func (*QuayStore) GetQuayRobot added in v0.21.0

func (p *QuayStore) GetQuayRobot(ctx context.Context, repositoryID, name string) (*models.QuayRobot, error)

GetQuayRobot returns the robot of an organization, nil when there is none.

func (*QuayStore) GetQuayTeam added in v0.21.0

func (p *QuayStore) GetQuayTeam(ctx context.Context, repositoryID, name string) (*models.QuayTeam, error)

GetQuayTeam returns the team of an organization, nil when there is none.

func (*QuayStore) ListQuayNotifications added in v0.21.0

func (p *QuayStore) ListQuayNotifications(ctx context.Context, quayRepoID string) ([]*models.QuayNotification, error)

ListQuayNotifications returns the notifications of a Quay repository, oldest first.

func (*QuayStore) ListQuayRepositories added in v0.21.0

func (p *QuayStore) ListQuayRepositories(ctx context.Context, repositoryID string) ([]*models.QuayRepository, error)

ListQuayRepositories returns the Quay repositories of an organization by name.

func (*QuayStore) ListQuayRobots added in v0.21.0

func (p *QuayStore) ListQuayRobots(ctx context.Context, repositoryID string) ([]*models.QuayRobot, error)

ListQuayRobots returns the robots of an organization by name.

func (*QuayStore) ListQuayTags added in v0.21.0

func (p *QuayStore) ListQuayTags(ctx context.Context, repositoryID, image string, page, limit int) ([]*models.QuayTag, bool, error)

ListQuayTags returns one page of the live tags of a Quay repository by name (page counts from 1) and whether more follow.

func (*QuayStore) ListQuayTeamPermissions added in v0.21.0

func (p *QuayStore) ListQuayTeamPermissions(ctx context.Context, groupID string) ([]*models.QuayTeamPermission, error)

ListQuayTeamPermissions returns the Quay repositories a team's group has access to, by name.

func (*QuayStore) ListQuayUserPermissions added in v0.21.0

func (p *QuayStore) ListQuayUserPermissions(ctx context.Context, q *models.QuayRepository) ([]*models.QuayUserPermission, error)

ListQuayUserPermissions returns the users and robots with access to a Quay repository by name.

func (QuayStore) Migrate added in v0.21.0

func (p QuayStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (QuayStore) Ping added in v0.21.0

func (p QuayStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (QuayStore) PoolStat added in v0.21.0

func (p QuayStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*QuayStore) RemoveQuayPermission added in v0.21.0

func (p *QuayStore) RemoveQuayPermission(ctx context.Context, q *models.QuayRepository, principalType, principalID string) (bool, error)

RemoveQuayPermission withdraws a principal's access to a Quay repository and reports whether it had any.

func (*QuayStore) RotateQuayRobotToken added in v0.21.0

func (p *QuayStore) RotateQuayRobotToken(
	ctx context.Context,
	b *models.QuayRobot,
	kind, name, hash, tokenEnc string,
) (*models.QuayRobot, error)

RotateQuayRobotToken revokes a robot's current token and stores a new one.

func (*QuayStore) SetQuayPermission added in v0.21.0

func (p *QuayStore) SetQuayPermission(ctx context.Context, q *models.QuayRepository, principalType, principalID string, write bool) error

SetQuayPermission gives a principal ("user" or "group") read or read+write access to a Quay repository, replacing any earlier role.

func (*QuayStore) UpdateQuayNotification added in v0.21.0

func (p *QuayStore) UpdateQuayNotification(ctx context.Context, n *models.QuayNotification) (*models.QuayNotification, error)

UpdateQuayNotification replaces a notification's content, nil when there is no such notification.

type QuotaStore added in v0.15.0

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

QuotaStore owns storage quotas and usage accounting, per repository and per project.

func (QuotaStore) AuthCacheGeneration added in v0.15.0

func (p QuotaStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (QuotaStore) AuthCacheTTL added in v0.15.0

func (p QuotaStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (QuotaStore) BeginTx added in v0.15.0

func (p QuotaStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (*QuotaStore) ChargeStorageUsage added in v0.15.0

func (p *QuotaStore) ChargeStorageUsage(ctx context.Context, repoID string, sizeBytes int64, artifactCount int) error

ChargeStorageUsage adds usage whose package row already exists (a row that was created without a reservation), past any limit: the artifact is stored, so refusing it would only desynchronise the counters. Nothing is left pending.

func (QuotaStore) Close added in v0.15.0

func (p QuotaStore) Close() error

Close writes the pending download counts and closes the database connection.

func (*QuotaStore) ConsumePendingUsage added in v0.22.0

func (p *QuotaStore) ConsumePendingUsage(ctx context.Context, repoID string, sizeBytes int64, artifactCount int) error

ConsumePendingUsage drops the pending ledger entry of a reservation whose rows were committed without consuming it (the exact-size entry first, then the oldest that fit). The counters are left untouched.

func (QuotaStore) CountFileDownload added in v0.19.0

func (p QuotaStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*QuotaStore) DecrementStorageUsage added in v0.15.0

func (p *QuotaStore) DecrementStorageUsage(ctx context.Context, repoID string, sizeBytes int64, artifactCount int) error

DecrementStorageUsage gives a reservation back (or accounts for a delete), on the repository and on its project's ceiling when that has one. A repository without a quota row has nothing to decrement.

func (QuotaStore) FlushDownloadCounts added in v0.19.0

func (p QuotaStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (QuotaStore) GetDB added in v0.15.0

func (p QuotaStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*QuotaStore) GetOrCreateStorageQuota added in v0.15.0

func (p *QuotaStore) GetOrCreateStorageQuota(ctx context.Context, repoID string) (*models.StorageQuota, error)

GetOrCreateStorageQuota gets or creates a storage quota for a repository.

func (*QuotaStore) GetProjectQuota added in v0.15.0

func (p *QuotaStore) GetProjectQuota(ctx context.Context, projectID string) (*models.ProjectQuota, error)

GetProjectQuota returns the project's storage ceiling; a project that never had one reads as unlimited (zero limits).

func (*QuotaStore) GetProjectUsage added in v0.15.0

func (p *QuotaStore) GetProjectUsage(ctx context.Context, projectID string) (*models.ProjectUsage, error)

GetProjectUsage reports a project's usage: the sum of its repositories' counters (always available, whether or not a ceiling is set), the ceiling, and one line per live repository, largest first.

func (*QuotaStore) GetRepositoryUsage added in v0.15.0

func (p *QuotaStore) GetRepositoryUsage(ctx context.Context, repoID string) (*models.RepositoryUsage, error)

GetRepositoryUsage counts the packages and versions a repository holds and when the newest version was created. It scans the repository's package rows: call it for one repository on demand.

func (*QuotaStore) ListQuotaOverview added in v0.15.0

func (p *QuotaStore) ListQuotaOverview(ctx context.Context, params models.QuotaListParams) ([]*models.QuotaOverview, int, error)

ListQuotaOverview returns one page of the instance-wide quota overview, largest usage first, and the number of matching lines.

func (*QuotaStore) ListStorageQuotas added in v0.15.0

func (p *QuotaStore) ListStorageQuotas(ctx context.Context) ([]*models.StorageQuota, error)

ListStorageQuotas returns every repository's quota row.

func (QuotaStore) Migrate added in v0.15.0

func (p QuotaStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (QuotaStore) Ping added in v0.15.0

func (p QuotaStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (QuotaStore) PoolStat added in v0.15.0

func (p QuotaStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*QuotaStore) ReconcileAllStorageUsage added in v0.15.0

func (p *QuotaStore) ReconcileAllStorageUsage(ctx context.Context) (int64, error)

ReconcileAllStorageUsage reconciles every repository (see ReconcileStorageUsage) and returns how many counters were corrected. Only one run is active at a time across replicas: when another holds the lock this returns 0, nil immediately.

func (*QuotaStore) ReconcileStorageUsage added in v0.15.0

func (p *QuotaStore) ReconcileStorageUsage(ctx context.Context, repoID string) (*models.StorageQuota, error)

ReconcileStorageUsage recomputes the usage counters of one repository from its package rows and returns the corrected quota (creating the quota row, unlimited, if it did not exist). The counters are maintained incrementally with asynchronous commits, so a crash can leave them off; this is the repair.

The recount is one statement over a single snapshot. An upload that has reserved but not yet inserted its row, or a delete that removed the row but not yet released it, is accounted for by its quota_pending entry, and the fix adds only the difference to the counter's current value, so the result is exact at every instant (entries older than quotaPendingReserveTTL and quotaPendingReleaseTTL are abandoned operations and do not count).

func (*QuotaStore) ReserveStorageUsage added in v0.15.0

func (p *QuotaStore) ReserveStorageUsage(ctx context.Context, repoID string, sizeBytes int64, artifactCount int) (bool, error)

ReserveStorageUsage atomically adds sizeBytes/artifactCount to the repository quota counters if doing so would not exceed the configured limits (a limit of 0 means unlimited), and, when the repository's project has a ceiling, to the project's counters too: the upload must fit both levels, otherwise nothing is reserved. It returns false, nil when a quota would be exceeded.

func (*QuotaStore) SetProjectQuota added in v0.15.0

func (p *QuotaStore) SetProjectQuota(
	ctx context.Context,
	projectID string,
	maxSizeBytes, maxArtifactCount int64,
	warnThresholdPercent int,
) (*models.ProjectQuota, error)

SetProjectQuota stores the project's storage ceiling (0 = unlimited) and returns it. Enabling a limit initialises the project counters from the repository counters in the same transaction; disabling it zeroes them (they are only maintained while a limit is set).

func (*QuotaStore) UpdateStorageQuota added in v0.15.0

func (p *QuotaStore) UpdateStorageQuota(ctx context.Context, quota *models.StorageQuota) error

UpdateStorageQuota updates a storage quota.

type RPMStore added in v0.15.0

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

RPMStore owns the RPM format tables.

An rpm package lives on the generic package tables (packages P, package_versions V, package_files F) plus the side table rpm_files. Grain 1:1: one .rpm (name, version, release, epoch, arch) is one P (shared by name), one V and one F. The mapping:

P  name, name_key = Name; attrs = {}
V  version        = Version (no release, no epoch)
   version_key    = version-release:epoch|arch (the part before '|' is the cleanup
                    ordering text; with the arch it is the whole legacy live key)
   metadata       = {summary, description, license, url, vendor, group_name, packager,
                    source_rpm, build_host} (empty = absent)
F  path           = filename, prefixed with '<epoch>:' when epoch is not 0; filename is
                    the canonical name-version-release.arch.rpm, rendered from the
                    columns when empty
   filename, arch = Filename, Arch; blob_id = the .rpm blob
   size_bytes     = package_size (wins over the blob size in listings; NULL = 0)
   part           = ''
   attrs          = {release, epoch, build_time, archive_size, installed_size}, a key only
                    when it is not ''/0; build_time is whole unix seconds
   checksums      = {}
rpm_files (id = F.id): header_start, header_end, rpm_extra (the parsed header extras,
   stored exactly as parsed and copied as-is; never reset or re-parse it)

func (RPMStore) AuthCacheGeneration added in v0.15.0

func (p RPMStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (RPMStore) AuthCacheTTL added in v0.15.0

func (p RPMStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (RPMStore) BeginTx added in v0.15.0

func (p RPMStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (RPMStore) Close added in v0.15.0

func (p RPMStore) Close() error

Close writes the pending download counts and closes the database connection.

func (RPMStore) CountFileDownload added in v0.19.0

func (p RPMStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*RPMStore) CreateRPMRepo added in v0.15.0

func (p *RPMStore) CreateRPMRepo(ctx context.Context, repo *models.RPMRepo) error

func (*RPMStore) CreateRpmPackage added in v0.15.0

func (p *RPMStore) CreateRpmPackage(ctx context.Context, pkg *models.Component) error

CreateRpmPackage inserts an RPM package. A live package with the same NEVRA.arch or the same path is ErrDuplicate.

func (RPMStore) FlushDownloadCounts added in v0.19.0

func (p RPMStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (RPMStore) GetDB added in v0.15.0

func (p RPMStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*RPMStore) GetRPMRepo added in v0.15.0

func (p *RPMStore) GetRPMRepo(ctx context.Context, repositoryID string) (*models.RPMRepo, error)

func (*RPMStore) GetRpmPackageByID added in v0.15.0

func (p *RPMStore) GetRpmPackageByID(ctx context.Context, id string) (*models.RpmPackage, error)

GetRpmPackageByID fetches a live RPM package by its primary key, or (nil, nil).

func (*RPMStore) ListRpmPackagesForMetadata added in v0.15.0

func (p *RPMStore) ListRpmPackagesForMetadata(ctx context.Context, repoID string) ([]rpmextra.Stored, error)

ListRpmPackagesForMetadata loads every rpm package of a repo with dependency, file and changelog data plus the header range, for metadata generation.

func (*RPMStore) MarkRepoStale added in v0.15.0

func (p *RPMStore) MarkRepoStale(ctx context.Context, repositoryID string) error

MarkRepoStale marks repository metadata as stale for regeneration. NOTE: Currently only tracks staleness for RPM repos via rpm_repos table. DEB staleness tracking needs a separate mechanism (e.g., a stale flag on repositories table).

func (RPMStore) Migrate added in v0.15.0

func (p RPMStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (RPMStore) Ping added in v0.15.0

func (p RPMStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (RPMStore) PoolStat added in v0.15.0

func (p RPMStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*RPMStore) RpmPackageExists added in v0.15.0

func (p *RPMStore) RpmPackageExists(ctx context.Context, repoID, name, version, release string, epoch int, arch string) (bool, error)

RpmPackageExists reports whether the repository already has a live package with the NEVRA.arch.

func (*RPMStore) UpdateRpmPackageExtra added in v0.15.0

func (p *RPMStore) UpdateRpmPackageExtra(ctx context.Context, repoID, sha256 string, extra []byte) error

UpdateRpmPackageExtra replaces rpm_extra for the packages of a repo backed by the blob with the given sha256. When the extra data carries sizes (sizes_parsed, see rpmextra.Marshal) the installed_size and archive_size attrs are corrected from it too: rows stored before the header size tags were read properly hold 0.

type RawStore added in v0.15.0

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

RawStore owns the raw (generic file) artifacts.

Mapping onto the generic package tables: one package, one version and one file per path.

packages          name = name_key = the path (case-sensitive), attrs = {}
package_versions  version = version_key = '' (every raw file is a release
                  with version ''), metadata = {}
package_files     path = filename = the raw path (live-unique), unit_key =
                  path, blob_id = the blob, role primary, listed, arch '',
                  part '', attrs = {content_type, metadata}, checksums = {}

Overwriting a path updates the file in place (id and created_at are kept); a path that was trashed and is written again gets a new version under the same package. Directory listings scan uq_package_files_path (repository_id, path text_pattern_ops) by prefix.

Cleanup note: the former retention partition was the DIRECTORY of the path (regexp_replace(path, '[^/]*$', ”)), ranked newest first; with one package per path the generic partition holds a single file each, so the cleanup engine needs a partition over the directory of package_files.path.

func (RawStore) AuthCacheGeneration added in v0.15.0

func (p RawStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (RawStore) AuthCacheTTL added in v0.15.0

func (p RawStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (RawStore) BeginTx added in v0.15.0

func (p RawStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (RawStore) Close added in v0.15.0

func (p RawStore) Close() error

Close writes the pending download counts and closes the database connection.

func (RawStore) CountFileDownload added in v0.19.0

func (p RawStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*RawStore) DeleteRawArtifact added in v0.15.0

func (p *RawStore) DeleteRawArtifact(ctx context.Context, repoID, path string) error

DeleteRawArtifact hard-deletes a raw artifact by repo ID and path, with the version and package it leaves empty.

func (RawStore) FlushDownloadCounts added in v0.19.0

func (p RawStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (RawStore) GetDB added in v0.15.0

func (p RawStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*RawStore) GetRawArtifact added in v0.15.0

func (p *RawStore) GetRawArtifact(ctx context.Context, repoID, path string) (*models.RawArtifact, error)

GetRawArtifact retrieves a raw artifact by repo ID and path.

func (*RawStore) InsertRawArtifactIfAbsent added in v0.15.0

func (p *RawStore) InsertRawArtifactIfAbsent(ctx context.Context, artifact *models.RawArtifact) (bool, error)

InsertRawArtifactIfAbsent inserts a raw artifact only when no live row exists at its path, in one atomic statement. It reports whether the row was inserted; false means the path is taken and nothing was changed.

func (*RawStore) ListRawArtifacts added in v0.15.0

func (p *RawStore) ListRawArtifacts(ctx context.Context, repoID, prefix string) ([]*models.RawArtifact, error)

ListRawArtifacts lists raw artifacts in a repository, optionally filtered by prefix.

func (RawStore) Migrate added in v0.15.0

func (p RawStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (RawStore) Ping added in v0.15.0

func (p RawStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (RawStore) PoolStat added in v0.15.0

func (p RawStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*RawStore) UpsertRawArtifact added in v0.15.0

func (p *RawStore) UpsertRawArtifact(ctx context.Context, artifact *models.RawArtifact) error

UpsertRawArtifact inserts or updates a raw artifact.

func (*RawStore) UpsertRawArtifactReplacing added in v0.20.0

func (p *RawStore) UpsertRawArtifactReplacing(ctx context.Context, artifact *models.RawArtifact) (*models.ReplacedBlob, error)

UpsertRawArtifactReplacing is UpsertRawArtifact that also returns the content the write replaced (nil when the path was free). Writers of one path are serialized, so the answer is the row this very write took over and the caller can give exactly its usage back.

type ReplicationStore added in v0.15.0

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

ReplicationStore owns the blob replication queue and verify state.

func (*ReplicationStore) AddBlobReplicationProgress added in v0.15.0

func (p *ReplicationStore) AddBlobReplicationProgress(ctx context.Context, copies, bytes int64) error

AddBlobReplicationProgress adds finished copies and their bytes.

func (ReplicationStore) AuthCacheGeneration added in v0.15.0

func (p ReplicationStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (ReplicationStore) AuthCacheTTL added in v0.15.0

func (p ReplicationStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (ReplicationStore) BeginTx added in v0.15.0

func (p ReplicationStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (*ReplicationStore) BlobReplicationBacklog added in v0.15.0

func (p *ReplicationStore) BlobReplicationBacklog(ctx context.Context, failingAttempts int) (BlobReplicationBacklog, error)

BlobReplicationBacklog counts the queue.

func (*ReplicationStore) BlobReplicationReferenced added in v0.15.0

func (p *ReplicationStore) BlobReplicationReferenced(ctx context.Context, sha256 string) (bool, error)

BlobReplicationReferenced reports whether the database still needs the blob.

func (*ReplicationStore) ClaimBlobReplications added in v0.15.0

func (p *ReplicationStore) ClaimBlobReplications(
	ctx context.Context,
	asOf time.Time,
	limit int,
	claimFor time.Duration,
) ([]BlobReplication, error)

ClaimBlobReplications hands out up to limit operations due at asOf.

func (ReplicationStore) Close added in v0.15.0

func (p ReplicationStore) Close() error

Close writes the pending download counts and closes the database connection.

func (*ReplicationStore) CompleteBlobReplication added in v0.15.0

func (p *ReplicationStore) CompleteBlobReplication(ctx context.Context, sha256 string, version int64) (bool, error)

CompleteBlobReplication removes the claimed operation.

func (ReplicationStore) CountFileDownload added in v0.19.0

func (p ReplicationStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*ReplicationStore) EnqueueBlobReplication added in v0.15.0

func (p *ReplicationStore) EnqueueBlobReplication(ctx context.Context, sha256, op string) error

EnqueueBlobReplication queues op for the blob (see BlobReplicationStore).

func (*ReplicationStore) FailBlobReplication added in v0.15.0

func (p *ReplicationStore) FailBlobReplication(
	ctx context.Context,
	sha256 string,
	version int64,
	lastError string,
	nextAttempt time.Time,
) (bool, error)

FailBlobReplication records a failed attempt.

func (*ReplicationStore) FinishReplicationVerify added in v0.15.0

func (p *ReplicationStore) FinishReplicationVerify(ctx context.Context, result json.RawMessage) error

FinishReplicationVerify stores the result of the pass and ends it.

func (ReplicationStore) FlushDownloadCounts added in v0.19.0

func (p ReplicationStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (*ReplicationStore) GetBlobReplication added in v0.15.0

func (p *ReplicationStore) GetBlobReplication(ctx context.Context, sha256 string) (*BlobReplication, error)

GetBlobReplication returns the queued operation of the blob, nil when none.

func (*ReplicationStore) GetBlobReplicationState added in v0.15.0

func (p *ReplicationStore) GetBlobReplicationState(ctx context.Context) (BlobReplicationState, error)

GetBlobReplicationState reads the singleton state.

func (ReplicationStore) GetDB added in v0.15.0

func (p ReplicationStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*ReplicationStore) ListBlobSHAs added in v0.15.0

func (p *ReplicationStore) ListBlobSHAs(ctx context.Context, after string, limit int) ([]string, error)

ListBlobSHAs returns one keyset page of the blobs table.

func (ReplicationStore) Migrate added in v0.15.0

func (p ReplicationStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (ReplicationStore) Ping added in v0.15.0

func (p ReplicationStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (ReplicationStore) PoolStat added in v0.15.0

func (p ReplicationStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*ReplicationStore) ReleaseBlobReplication added in v0.15.0

func (p *ReplicationStore) ReleaseBlobReplication(ctx context.Context, sha256 string, version int64) error

ReleaseBlobReplication gives a claimed operation back unprocessed.

func (*ReplicationStore) RequestReplicationVerify added in v0.15.0

func (p *ReplicationStore) RequestReplicationVerify(ctx context.Context) (bool, error)

RequestReplicationVerify asks for a verify pass.

func (*ReplicationStore) SaveReplicationVerifyProgress added in v0.15.0

func (p *ReplicationStore) SaveReplicationVerifyProgress(ctx context.Context, cursor string, run json.RawMessage) (bool, error)

SaveReplicationVerifyProgress stores the cursor and counters of the running pass.

func (*ReplicationStore) SetBlobReplicationLastError added in v0.15.0

func (p *ReplicationStore) SetBlobReplicationLastError(ctx context.Context, message string) error

SetBlobReplicationLastError records the most recent failure.

func (*ReplicationStore) StartReplicationVerify added in v0.15.0

func (p *ReplicationStore) StartReplicationVerify(ctx context.Context, run json.RawMessage) (bool, error)

StartReplicationVerify begins a pass.

type RepoGroupStore added in v0.15.0

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

RepoGroupStore owns group repository membership and the stale/owner state of generated group metadata.

func (*RepoGroupStore) AddGroupMember added in v0.15.0

func (p *RepoGroupStore) AddGroupMember(ctx context.Context, groupRepoID, memberRepoID string, priority int) error

func (RepoGroupStore) AuthCacheGeneration added in v0.15.0

func (p RepoGroupStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (RepoGroupStore) AuthCacheTTL added in v0.15.0

func (p RepoGroupStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (RepoGroupStore) BeginTx added in v0.15.0

func (p RepoGroupStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (RepoGroupStore) Close added in v0.15.0

func (p RepoGroupStore) Close() error

Close writes the pending download counts and closes the database connection.

func (RepoGroupStore) CountFileDownload added in v0.19.0

func (p RepoGroupStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (RepoGroupStore) FlushDownloadCounts added in v0.19.0

func (p RepoGroupStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (RepoGroupStore) GetDB added in v0.15.0

func (p RepoGroupStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*RepoGroupStore) GetGroupMetadataState added in v0.15.0

func (p *RepoGroupStore) GetGroupMetadataState(ctx context.Context, groupID string) (*models.GroupMetadataState, error)

GetGroupMetadataState returns the state row of a group, nil when it has none.

func (*RepoGroupStore) GetGroupPackageOwner added in v0.15.0

func (p *RepoGroupStore) GetGroupPackageOwner(ctx context.Context, groupID, path string) (string, bool, error)

GetGroupPackageOwner returns the member repository that owns path (a Debian pool path or an RPM location) in the merged index of the group, ok=false when the index lists no such file.

func (*RepoGroupStore) ListGroupMemberRepositories added in v0.15.0

func (p *RepoGroupStore) ListGroupMemberRepositories(ctx context.Context, groupRepoID string) ([]*models.Repository, error)

ListGroupMemberRepositories returns the live member repositories of a group in priority order (the order of ListGroupMembers) in one query.

func (*RepoGroupStore) ListGroupMembers added in v0.15.0

func (p *RepoGroupStore) ListGroupMembers(ctx context.Context, groupRepoID string) ([]*models.RepositoryGroupMember, error)

func (*RepoGroupStore) ListGroupsOfMember added in v0.15.0

func (p *RepoGroupStore) ListGroupsOfMember(ctx context.Context, memberRepoID string) ([]*models.Repository, error)

ListGroupsOfMember returns the live group repositories the repository is a member of, oldest link first.

func (*RepoGroupStore) ListMetadataGroupsOfMember added in v0.15.0

func (p *RepoGroupStore) ListMetadataGroupsOfMember(ctx context.Context, memberRepoID string) ([]string, error)

ListMetadataGroupsOfMember returns the ids of the group repositories of the formats with generated group metadata (repotype.GeneratedGroupMetadata) that list memberRepoID as a member.

func (*RepoGroupStore) ListStaleMetadataGroups added in v0.15.0

func (p *RepoGroupStore) ListStaleMetadataGroups(ctx context.Context) ([]string, error)

ListStaleMetadataGroups returns the group repositories of the formats with generated group metadata whose merged metadata is stale or was never generated.

func (*RepoGroupStore) MarkGroupMetadataStale added in v0.15.0

func (p *RepoGroupStore) MarkGroupMetadataStale(ctx context.Context, groupID string) error

MarkGroupMetadataStale records that the merged metadata of an apk, deb, pacman or rpm group must be regenerated, creating its state row on first use.

func (RepoGroupStore) Migrate added in v0.15.0

func (p RepoGroupStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (RepoGroupStore) Ping added in v0.15.0

func (p RepoGroupStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (RepoGroupStore) PoolStat added in v0.15.0

func (p RepoGroupStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*RepoGroupStore) ReplaceGroupMembers added in v0.15.0

func (p *RepoGroupStore) ReplaceGroupMembers(ctx context.Context, groupRepoID string, memberIDs []string) error

ReplaceGroupMembers atomically replaces the member list of a group repository. An empty memberIDs slice clears the group.

type RepoMetadataStore added in v0.15.0

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

RepoMetadataStore owns repository_metadata, the generated per-repository metadata files (Packages, repomd.xml, maven-metadata.xml, ...).

func (RepoMetadataStore) AuthCacheGeneration added in v0.15.0

func (p RepoMetadataStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (RepoMetadataStore) AuthCacheTTL added in v0.15.0

func (p RepoMetadataStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (RepoMetadataStore) BeginTx added in v0.15.0

func (p RepoMetadataStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (RepoMetadataStore) Close added in v0.15.0

func (p RepoMetadataStore) Close() error

Close writes the pending download counts and closes the database connection.

func (RepoMetadataStore) CountFileDownload added in v0.19.0

func (p RepoMetadataStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (RepoMetadataStore) FlushDownloadCounts added in v0.19.0

func (p RepoMetadataStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (RepoMetadataStore) GetDB added in v0.15.0

func (p RepoMetadataStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*RepoMetadataStore) GetRepoMetadataByPath added in v0.15.0

func (p *RepoMetadataStore) GetRepoMetadataByPath(ctx context.Context, repositoryID string, path string) (*models.RepoMetadata, error)

func (*RepoMetadataStore) GetRepoMetadataByRepo added in v0.15.0

func (p *RepoMetadataStore) GetRepoMetadataByRepo(ctx context.Context, repositoryID string) ([]models.RepoMetadata, error)

func (RepoMetadataStore) Migrate added in v0.15.0

func (p RepoMetadataStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (RepoMetadataStore) Ping added in v0.15.0

func (p RepoMetadataStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (RepoMetadataStore) PoolStat added in v0.15.0

func (p RepoMetadataStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*RepoMetadataStore) UpsertRepoMetadata added in v0.15.0

func (p *RepoMetadataStore) UpsertRepoMetadata(ctx context.Context, meta *models.RepoMetadata) error

type RepoStatsReconciler added in v0.19.0

type RepoStatsReconciler interface {
	// ReconcileRepoStats recomputes the figures of up to batch repositories
	// (marked ones first, then the ones whose figures are missing or older than
	// maxAge) and returns how many; a result below batch means nothing more is
	// waiting.
	ReconcileRepoStats(ctx context.Context, batch int, maxAge time.Duration) (int, error)
}

RepoStatsReconciler recomputes the stored per-repository figures of the repository list. It is implemented by *PostgresDB and found by the repo stats worker with a type assertion on Database.

type RepositorySettingsChange added in v0.20.0

type RepositorySettingsChange struct {
	// ReplaceMembers replaces the group's members with MemberIDs (which may be
	// empty, clearing the group).
	ReplaceMembers bool
	MemberIDs      []string
	// MoveToProjectID, when set, moves the repository (and its usage) to that
	// project in the same transaction.
	MoveToProjectID string
}

RepositorySettingsChange is what UpdateRepositorySettings changes besides the repository row's settings.

type RepositoryStore added in v0.15.0

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

RepositoryStore owns the repositories table: lookup, create/update/delete, the repository flags and the project move.

func (RepositoryStore) AuthCacheGeneration added in v0.15.0

func (p RepositoryStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (RepositoryStore) AuthCacheTTL added in v0.15.0

func (p RepositoryStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (RepositoryStore) BeginTx added in v0.15.0

func (p RepositoryStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (RepositoryStore) Close added in v0.15.0

func (p RepositoryStore) Close() error

Close writes the pending download counts and closes the database connection.

func (RepositoryStore) CountFileDownload added in v0.19.0

func (p RepositoryStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*RepositoryStore) CountRepositories added in v0.15.0

func (p *RepositoryStore) CountRepositories(ctx context.Context, formatFilter string) (int, error)

func (*RepositoryStore) CreateProjectRepository added in v0.15.0

func (p *RepositoryStore) CreateProjectRepository(
	ctx context.Context,
	repo *models.Repository,
	memberIDs []string,
	maxRepositories int,
) error

CreateProjectRepository is CreateRepositoryWithMembers under the project's repository cap: with the project row locked it refuses (ErrProjectRepoLimit) when the project already holds maxRepositories live repositories, so concurrent creations cannot overshoot the cap.

func (*RepositoryStore) CreateRepository added in v0.15.0

func (p *RepositoryStore) CreateRepository(ctx context.Context, repo *models.Repository) error

func (*RepositoryStore) CreateRepositoryWithMembers added in v0.15.0

func (p *RepositoryStore) CreateRepositoryWithMembers(ctx context.Context, repo *models.Repository, memberIDs []string) error

CreateRepositoryWithMembers inserts a repository and (for group repos) its ordered member list in a single transaction, so a failing member insert cannot leave a half-created group behind.

func (*RepositoryStore) DeleteRepository added in v0.15.0

func (p *RepositoryStore) DeleteRepository(ctx context.Context, id string) error

func (RepositoryStore) FlushDownloadCounts added in v0.19.0

func (p RepositoryStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (RepositoryStore) GetDB added in v0.15.0

func (p RepositoryStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*RepositoryStore) GetRepositoriesByIDs added in v0.20.0

func (p *RepositoryStore) GetRepositoriesByIDs(ctx context.Context, ids []string) (map[string]*models.Repository, error)

GetRepositoriesByIDs returns the live repositories among ids, keyed by id; ids that do not exist (or are in the trash) are absent from the map.

func (*RepositoryStore) GetRepositoryAttestationAttach added in v0.15.0

func (p *RepositoryStore) GetRepositoryAttestationAttach(ctx context.Context, repoID string) (bool, error)

GetRepositoryAttestationAttach reports whether the repository attaches signed attestations to its docker images as OCI referrers; false when never set.

func (*RepositoryStore) GetRepositoryByID added in v0.15.0

func (p *RepositoryStore) GetRepositoryByID(ctx context.Context, id string) (*models.Repository, error)

GetRepositoryByID retrieves a repository by its primary key.

func (*RepositoryStore) GetRepositoryByName added in v0.15.0

func (p *RepositoryStore) GetRepositoryByName(ctx context.Context, name string) (*models.Repository, error)

GetRepositoryByName returns the repository with the given name, from the auth cache when fresh.

func (*RepositoryStore) GetRepositoryByNameUncached added in v0.15.0

func (p *RepositoryStore) GetRepositoryByNameUncached(ctx context.Context, name string) (*models.Repository, error)

func (*RepositoryStore) ListPublicRepositoryNames added in v0.15.0

func (p *RepositoryStore) ListPublicRepositoryNames(ctx context.Context) ([]string, error)

ListPublicRepositoryNames returns the names of all repositories flagged public.

func (*RepositoryStore) ListRepositories added in v0.15.0

func (p *RepositoryStore) ListRepositories(ctx context.Context, page, limit int, formatFilter string) ([]*models.Repository, error)

func (RepositoryStore) Migrate added in v0.15.0

func (p RepositoryStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (*RepositoryStore) MoveRepositoryToProject added in v0.15.0

func (p *RepositoryStore) MoveRepositoryToProject(ctx context.Context, repoID, toProjectID string, maxRepositories int) error

MoveRepositoryToProject reassigns a repository to another project, under the target's repository cap when maxRepositories > 0 (ErrProjectRepoLimit). The repository's storage usage moves between the projects' ceilings in the same transaction and must fit the target's (ErrProjectQuotaExceeded).

func (RepositoryStore) Ping added in v0.15.0

func (p RepositoryStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (RepositoryStore) PoolStat added in v0.15.0

func (p RepositoryStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*RepositoryStore) SetRepositoryAttestationAttach added in v0.15.0

func (p *RepositoryStore) SetRepositoryAttestationAttach(ctx context.Context, repoID string, enabled bool) error

SetRepositoryAttestationAttach stores the repository's attach switch.

func (*RepositoryStore) UpdateRepository added in v0.15.0

func (p *RepositoryStore) UpdateRepository(ctx context.Context, repo *models.Repository) error

func (*RepositoryStore) UpdateRepositorySettings added in v0.20.0

func (p *RepositoryStore) UpdateRepositorySettings(ctx context.Context, repo *models.Repository, change RepositorySettingsChange) error

UpdateRepositorySettings writes the settings of repo, optionally moves it to another project and replaces its group members, all in one transaction: a failure leaves the repository untouched. The row's project_id is never taken from repo (a stale snapshot must not revert a concurrent transfer); only change.MoveToProjectID changes it. The project move fails with ErrProjectQuotaExceeded or ErrRepositoryNotFound.

type RubyGemsStore added in v0.15.0

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

RubyGemsStore owns the RubyGems gems.

Gems live in the generic package tables (repository format "rubygems"; the mapping is the maintainers' reference, derived from migrations/001_baseline.sql):

packages          one per gem name: name = name_key = name, attrs {}
package_versions  one per (version, platform): version = version, version_key =
                  version for the pure-Ruby platform and "version|platform"
                  otherwise ('|' cannot occur in either, so the key is injective;
                  the text before '|' is what the cleanup rank sorts on);
                  metadata {"description", "summary", "homepage": text,
                  "authors", "licenses": arrays of text, "dependencies": array,
                  "metadata_json": object, "yanked": boolean (always written)}.
                  Empty text values are omitted; a missing key reads as "".
package_files    one primary listed file per version: path
                  "<name>/<version>/<filename>", filename "<name>-<version>[-<platform>].gem",
                  arch = the platform (the listing and cleanup partition),
                  size_bytes = the gem size (wins over the blob size, NULL
                  when 0), download_count

Rubygems is not federated: the file carries no unit_key. Yanks apply per version (and so per platform build) as before.

func (RubyGemsStore) AuthCacheGeneration added in v0.15.0

func (p RubyGemsStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (RubyGemsStore) AuthCacheTTL added in v0.15.0

func (p RubyGemsStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (RubyGemsStore) BeginTx added in v0.15.0

func (p RubyGemsStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (RubyGemsStore) Close added in v0.15.0

func (p RubyGemsStore) Close() error

Close writes the pending download counts and closes the database connection.

func (RubyGemsStore) CountFileDownload added in v0.19.0

func (p RubyGemsStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*RubyGemsStore) CreateRubyGem added in v0.15.0

func (p *RubyGemsStore) CreateRubyGem(ctx context.Context, gem *models.RubyGem) error

CreateRubyGem creates a new RubyGem build. A live build with the same name, version and platform is ErrDuplicate.

gem.Size is persisted on the file (it wins over the blob size, for quota release and the listing) and recorded as the blob's size_bytes.

func (RubyGemsStore) FlushDownloadCounts added in v0.19.0

func (p RubyGemsStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (RubyGemsStore) GetDB added in v0.15.0

func (p RubyGemsStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*RubyGemsStore) GetRubyGem added in v0.15.0

func (p *RubyGemsStore) GetRubyGem(ctx context.Context, repoID, name, version, platform string) (*models.RubyGem, error)

func (*RubyGemsStore) ListRubyGemSpecs added in v0.15.0

func (p *RubyGemsStore) ListRubyGemSpecs(ctx context.Context, repoID string) ([]*models.RubyGem, error)

ListRubyGemSpecs returns the listed (not yanked) gems with only Name, Version and Platform set, by name then version descending.

func (*RubyGemsStore) ListRubyGemVersions added in v0.15.0

func (p *RubyGemsStore) ListRubyGemVersions(ctx context.Context, repoID, name string) ([]*models.RubyGem, error)

func (*RubyGemsStore) ListRubyGems added in v0.15.0

func (p *RubyGemsStore) ListRubyGems(ctx context.Context, repoID string) ([]*models.RubyGem, error)

func (RubyGemsStore) Migrate added in v0.15.0

func (p RubyGemsStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (RubyGemsStore) Ping added in v0.15.0

func (p RubyGemsStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (RubyGemsStore) PoolStat added in v0.15.0

func (p RubyGemsStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*RubyGemsStore) RubyGemsSpecsStamp added in v0.15.0

func (p *RubyGemsStore) RubyGemsSpecsStamp(ctx context.Context, repoID string) (string, error)

RubyGemsSpecsStamp is a cheap validator of every specs index of a repository: it changes when a listed gem is added, removed or yanked.

func (*RubyGemsStore) SearchRubyGems added in v0.15.0

func (p *RubyGemsStore) SearchRubyGems(ctx context.Context, repoID, query string) ([]*models.RubyGem, error)

func (*RubyGemsStore) YankRubyGem added in v0.15.0

func (p *RubyGemsStore) YankRubyGem(ctx context.Context, repoID, name, version, platform string, yanked bool) error

type SBOMStore added in v0.15.0

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

SBOMStore owns generated SBOM reports.

func (SBOMStore) AuthCacheGeneration added in v0.15.0

func (p SBOMStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (SBOMStore) AuthCacheTTL added in v0.15.0

func (p SBOMStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (SBOMStore) BeginTx added in v0.15.0

func (p SBOMStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (SBOMStore) Close added in v0.15.0

func (p SBOMStore) Close() error

Close writes the pending download counts and closes the database connection.

func (SBOMStore) CountFileDownload added in v0.19.0

func (p SBOMStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*SBOMStore) CreateSBOMReport added in v0.15.0

func (p *SBOMStore) CreateSBOMReport(ctx context.Context, report *models.SBOMReport) error

CreateSBOMReport creates or updates an SBOM report (upsert). The caller (internal/api/sbom.go) is expected to have already written the SBOM bytes into the blob store and set report.BlobSHA256/BlobSizeBytes; this upserts the corresponding blobs row and stores the resulting blob_id alongside the report metadata. A zero-value BlobSHA256 stores a NULL blob_id.

func (*SBOMStore) DeleteSBOMReportInRepo added in v0.15.0

func (p *SBOMStore) DeleteSBOMReportInRepo(ctx context.Context, repoID, id string) (string, error)

DeleteSBOMReportInRepo deletes the SBOM report with the given ID scoped to repoID and returns the sha256 of the blob it referenced ("" when it had none). Callers should afterwards remove the blob from storage if it is unreferenced (storage.SafeDeleteBlob). Returns ErrSBOMReportNotFound when nothing matched.

func (SBOMStore) FlushDownloadCounts added in v0.19.0

func (p SBOMStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (SBOMStore) GetDB added in v0.15.0

func (p SBOMStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*SBOMStore) GetSBOMReportByID added in v0.15.0

func (p *SBOMStore) GetSBOMReportByID(ctx context.Context, repoID, id string) (*models.SBOMReport, error)

GetSBOMReportByID returns the SBOM report with the given ID scoped to repoID, or nil.

func (*SBOMStore) GetSBOMReportsByArtifact added in v0.21.0

func (p *SBOMStore) GetSBOMReportsByArtifact(ctx context.Context, repoID, artifactID string) ([]*models.SBOMReport, error)

GetSBOMReportsByArtifact lists the SBOM reports stored for one artifact of a repository (one per SBOM format and spec version), newest first.

func (*SBOMStore) ListSBOMReports added in v0.15.0

func (p *SBOMStore) ListSBOMReports(ctx context.Context, repoID string) ([]*models.SBOMReport, error)

ListSBOMReports lists all SBOM reports for a repository.

func (SBOMStore) Migrate added in v0.15.0

func (p SBOMStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (SBOMStore) Ping added in v0.15.0

func (p SBOMStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (SBOMStore) PoolStat added in v0.15.0

func (p SBOMStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

type SBTStore added in v0.15.0

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

SBTStore owns the sbt artifacts.

sbt on the generic package tables (mapping spec /tmp/oa-plug/schema/119_sbt.sql, restated as the maintainers' reference). No side table.

P  packages         name = name_key = group_id ':' artifact_id
                    attrs = {"group_id", "artifact_id"}
V  package_versions version = version_key = version; metadata {}
F  package_files    filename = the file name; arch = the scala version ('' unless recorded);
                    path = group_id '/' artifact_id '/' version '/' filename
                    (repository-wide live-unique: the lookup key);
                    part '', role primary, listed, unit_key NULL, attrs {}

An upload to an existing path repoints the file at the new blob.

func (SBTStore) AuthCacheGeneration added in v0.15.0

func (p SBTStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (SBTStore) AuthCacheTTL added in v0.15.0

func (p SBTStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (SBTStore) BeginTx added in v0.15.0

func (p SBTStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (SBTStore) Close added in v0.15.0

func (p SBTStore) Close() error

Close writes the pending download counts and closes the database connection.

func (SBTStore) CountFileDownload added in v0.19.0

func (p SBTStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*SBTStore) CreateSBTArtifact added in v0.15.0

func (p *SBTStore) CreateSBTArtifact(ctx context.Context, artifact *models.SBTArtifact) error

CreateSBTArtifact stores an SBT artifact; a live artifact with the same coordinates is repointed at the new blob.

func (*SBTStore) DeleteSBTArtifact added in v0.15.0

func (p *SBTStore) DeleteSBTArtifact(ctx context.Context, id string) error

func (SBTStore) FlushDownloadCounts added in v0.19.0

func (p SBTStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (SBTStore) GetDB added in v0.15.0

func (p SBTStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*SBTStore) GetSBTArtifact added in v0.15.0

func (p *SBTStore) GetSBTArtifact(
	ctx context.Context,
	repoID, groupID, artifactID, version, filename string,
) (*models.SBTArtifact, error)

func (SBTStore) Migrate added in v0.15.0

func (p SBTStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (SBTStore) Ping added in v0.15.0

func (p SBTStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (SBTStore) PoolStat added in v0.15.0

func (p SBTStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*SBTStore) SBTModuleExists added in v0.15.0

func (p *SBTStore) SBTModuleExists(ctx context.Context, repoID, groupID, artifactID string) (bool, error)

SBTModuleExists reports whether the repository holds a live version of the artifact.

type SSOProviderPatch added in v0.20.0

type SSOProviderPatch struct {
	DisplayName        *string
	Icon               *string
	Enabled            *bool
	AutoProvisionUsers *bool
	LinkByEmail        *bool
	OIDCConfig         json.RawMessage
	SAMLConfig         json.RawMessage
	ClaimMapping       json.RawMessage
	GroupMapping       *map[string]string
	PermissionMapping  *map[string]string
}

SSOProviderPatch names the columns an admin edit writes; nil fields leave the stored value alone. A nil mapping pointer is unchanged, a pointer to a nil map writes JSON null.

type SSOStore added in v0.15.0

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

SSOStore owns the configured SSO providers (OIDC and SAML).

func (SSOStore) AuthCacheGeneration added in v0.15.0

func (p SSOStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (SSOStore) AuthCacheTTL added in v0.15.0

func (p SSOStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (SSOStore) BeginTx added in v0.15.0

func (p SSOStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (SSOStore) Close added in v0.15.0

func (p SSOStore) Close() error

Close writes the pending download counts and closes the database connection.

func (SSOStore) CountFileDownload added in v0.19.0

func (p SSOStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*SSOStore) CreateSSOProvider added in v0.15.0

func (p *SSOStore) CreateSSOProvider(ctx context.Context, provider *models.SSOProvider) error

func (*SSOStore) DeleteSSOProvider added in v0.15.0

func (p *SSOStore) DeleteSSOProvider(ctx context.Context, id string) error

func (SSOStore) FlushDownloadCounts added in v0.19.0

func (p SSOStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (SSOStore) GetDB added in v0.15.0

func (p SSOStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*SSOStore) GetSSOProviderBySlug added in v0.15.0

func (p *SSOStore) GetSSOProviderBySlug(ctx context.Context, slug string) (*models.SSOProvider, error)

func (*SSOStore) ListAllSSOProviders added in v0.15.0

func (p *SSOStore) ListAllSSOProviders(ctx context.Context) ([]*models.SSOProvider, error)

func (*SSOStore) ListEnabledSSOProviders added in v0.15.0

func (p *SSOStore) ListEnabledSSOProviders(ctx context.Context) ([]*models.SSOProvider, error)

func (SSOStore) Migrate added in v0.15.0

func (p SSOStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (*SSOStore) PatchSSOProvider added in v0.20.0

func (p *SSOStore) PatchSSOProvider(ctx context.Context, id string, patch SSOProviderPatch) (*models.SSOProvider, error)

PatchSSOProvider writes only the columns in patch, so a concurrent edit of other columns is not reverted by a stale snapshot. It returns the updated row, or nil when the provider does not exist.

func (SSOStore) Ping added in v0.15.0

func (p SSOStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (SSOStore) PoolStat added in v0.15.0

func (p SSOStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

type SecretScanStore added in v0.15.0

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

SecretScanStore owns secret scan results.

func (SecretScanStore) AuthCacheGeneration added in v0.15.0

func (p SecretScanStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (SecretScanStore) AuthCacheTTL added in v0.15.0

func (p SecretScanStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (SecretScanStore) BeginTx added in v0.15.0

func (p SecretScanStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (SecretScanStore) Close added in v0.15.0

func (p SecretScanStore) Close() error

Close writes the pending download counts and closes the database connection.

func (SecretScanStore) CountFileDownload added in v0.19.0

func (p SecretScanStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*SecretScanStore) CreateSecretScanResult added in v0.15.0

func (p *SecretScanStore) CreateSecretScanResult(ctx context.Context, result *models.SecretScanResult) error

CreateSecretScanResult creates a new secret scan result (UPSERT).

func (*SecretScanStore) DeleteSecretScanResult added in v0.15.0

func (p *SecretScanStore) DeleteSecretScanResult(ctx context.Context, repoID, id string) error

DeleteSecretScanResult deletes a secret scan result (and its owning scan job) by ID, scoped to repoID. Returns ErrSecretScanNotFound when nothing matched.

func (SecretScanStore) FlushDownloadCounts added in v0.19.0

func (p SecretScanStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (SecretScanStore) GetDB added in v0.15.0

func (p SecretScanStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*SecretScanStore) GetSecretScanResult added in v0.15.0

func (p *SecretScanStore) GetSecretScanResult(ctx context.Context, repoID, artifactID string) (*models.SecretScanResult, error)

GetSecretScanResult gets a secret scan result by repo and artifact ID.

func (*SecretScanStore) ListSecretScanResults added in v0.15.0

func (p *SecretScanStore) ListSecretScanResults(ctx context.Context, repoID string, flaggedOnly bool) ([]*models.SecretScanResult, error)

ListSecretScanResults lists all secret scan results for a repository.

func (SecretScanStore) Migrate added in v0.15.0

func (p SecretScanStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (SecretScanStore) Ping added in v0.15.0

func (p SecretScanStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (SecretScanStore) PoolStat added in v0.15.0

func (p SecretScanStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

type ServiceAccountStore added in v0.16.0

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

ServiceAccountStore owns the administrator-managed service accounts: auth_users rows of kind service_account. They share the users table (so tokens, permission assignments, group memberships and project roles work unchanged) but are never listed with the users and never log in.

func (ServiceAccountStore) AuthCacheGeneration added in v0.16.0

func (p ServiceAccountStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (ServiceAccountStore) AuthCacheTTL added in v0.16.0

func (p ServiceAccountStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (ServiceAccountStore) BeginTx added in v0.16.0

func (p ServiceAccountStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (ServiceAccountStore) Close added in v0.16.0

func (p ServiceAccountStore) Close() error

Close writes the pending download counts and closes the database connection.

func (ServiceAccountStore) CountFileDownload added in v0.19.0

func (p ServiceAccountStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*ServiceAccountStore) CreateServiceAccount added in v0.16.0

func (p *ServiceAccountStore) CreateServiceAccount(
	ctx context.Context,
	name string,
	description *string,
	disabled bool,
) (*models.User, error)

CreateServiceAccount creates a service account. The name is its username, unique among all accounts (a clash is IsUniqueViolation).

func (*ServiceAccountStore) DeleteServiceAccount added in v0.16.0

func (p *ServiceAccountStore) DeleteServiceAccount(ctx context.Context, id string) (bool, error)

DeleteServiceAccount deletes a service account with everything that belongs to it: tokens, group memberships, project roles and trust policies go by their foreign keys, the direct permission assignments (which have none) are removed explicitly. It reports whether the account existed.

func (ServiceAccountStore) FlushDownloadCounts added in v0.19.0

func (p ServiceAccountStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (ServiceAccountStore) GetDB added in v0.16.0

func (p ServiceAccountStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*ServiceAccountStore) GetServiceAccount added in v0.16.0

func (p *ServiceAccountStore) GetServiceAccount(ctx context.Context, id string) (*models.User, error)

GetServiceAccount returns the service account with the id, nil when there is none (a user of another kind is not one).

func (*ServiceAccountStore) ListServiceAccounts added in v0.16.0

func (p *ServiceAccountStore) ListServiceAccounts(ctx context.Context, page, perPage int) ([]*models.User, int, error)

ListServiceAccounts returns one page of service accounts by name and the total.

func (ServiceAccountStore) Migrate added in v0.16.0

func (p ServiceAccountStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (ServiceAccountStore) Ping added in v0.16.0

func (p ServiceAccountStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (ServiceAccountStore) PoolStat added in v0.16.0

func (p ServiceAccountStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*ServiceAccountStore) UpdateServiceAccount added in v0.16.0

func (p *ServiceAccountStore) UpdateServiceAccount(
	ctx context.Context, id string, description *string, disabled *bool,
) (*models.User, error)

UpdateServiceAccount sets the description (when non-nil) and the disabled flag (when non-nil) and returns the account, nil when there is no such account. Disabling takes effect for its tokens at once: a token of a disabled account authenticates nothing.

type SessionStore added in v0.15.0

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

SessionStore owns login sessions and consumed SAML assertions.

func (SessionStore) AuthCacheGeneration added in v0.15.0

func (p SessionStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (SessionStore) AuthCacheTTL added in v0.15.0

func (p SessionStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (SessionStore) BeginTx added in v0.15.0

func (p SessionStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (SessionStore) Close added in v0.15.0

func (p SessionStore) Close() error

Close writes the pending download counts and closes the database connection.

func (*SessionStore) ConsumeSAMLAssertion added in v0.15.0

func (p *SessionStore) ConsumeSAMLAssertion(ctx context.Context, providerSlug, assertionID string, expiresAt time.Time) (bool, error)

ConsumeSAMLAssertion records a SAML assertion ID as used and reports whether this call was the first to consume it. A false result means the assertion was already accepted before (replay). Expired records are purged opportunistically.

func (SessionStore) CountFileDownload added in v0.19.0

func (p SessionStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*SessionStore) CreateSession added in v0.15.0

func (p *SessionStore) CreateSession(ctx context.Context, session *models.Session) (*models.Session, error)

func (*SessionStore) DeleteOtherSessionsByUser added in v0.15.0

func (p *SessionStore) DeleteOtherSessionsByUser(ctx context.Context, userID, keepTokenHash string) error

DeleteOtherSessionsByUser revokes every session of a user except the one identified by keepTokenHash.

func (*SessionStore) DeleteSession added in v0.15.0

func (p *SessionStore) DeleteSession(ctx context.Context, tokenHash string) error

func (*SessionStore) DeleteSessionsByUser added in v0.15.0

func (p *SessionStore) DeleteSessionsByUser(ctx context.Context, userID string) error

DeleteSessionsByUser revokes every session of a user.

func (SessionStore) FlushDownloadCounts added in v0.19.0

func (p SessionStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (SessionStore) GetDB added in v0.15.0

func (p SessionStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*SessionStore) GetSessionByTokenHash added in v0.15.0

func (p *SessionStore) GetSessionByTokenHash(ctx context.Context, hash string) (*models.Session, error)

func (*SessionStore) GetSessionSSO added in v0.15.0

func (p *SessionStore) GetSessionSSO(ctx context.Context, tokenHash string) (*models.SessionSSO, error)

GetSessionSSO returns the SSO record of the session with tokenHash, or nil when the session was not created by SSO (or does not exist).

func (SessionStore) Migrate added in v0.15.0

func (p SessionStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (SessionStore) Ping added in v0.15.0

func (p SessionStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (SessionStore) PoolStat added in v0.15.0

func (p SessionStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*SessionStore) SetSessionSSO added in v0.15.0

func (p *SessionStore) SetSessionSSO(ctx context.Context, sessionID, providerSlug, encryptedIDToken string) error

SetSessionSSO records the SSO provider (and its encrypted ID token) a session was created by, for RP-initiated logout.

func (*SessionStore) UpdateSessionLastSeen added in v0.15.0

func (p *SessionStore) UpdateSessionLastSeen(ctx context.Context, sessionID string, expiresAt time.Time) error

type SettingsStore added in v0.15.0

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

SettingsStore owns system settings.

func (SettingsStore) AuthCacheGeneration added in v0.15.0

func (p SettingsStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (SettingsStore) AuthCacheTTL added in v0.15.0

func (p SettingsStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (SettingsStore) BeginTx added in v0.15.0

func (p SettingsStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (SettingsStore) Close added in v0.15.0

func (p SettingsStore) Close() error

Close writes the pending download counts and closes the database connection.

func (SettingsStore) CountFileDownload added in v0.19.0

func (p SettingsStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*SettingsStore) CreateSystemSettingIfAbsent added in v0.15.0

func (p *SettingsStore) CreateSystemSettingIfAbsent(ctx context.Context, key, value string) (bool, error)

CreateSystemSettingIfAbsent stores value under key unless the key exists; it reports whether it was stored. Concurrent callers (several replicas) agree on one winner.

func (SettingsStore) FlushDownloadCounts added in v0.19.0

func (p SettingsStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (SettingsStore) GetDB added in v0.15.0

func (p SettingsStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*SettingsStore) GetSystemSetting added in v0.15.0

func (p *SettingsStore) GetSystemSetting(ctx context.Context, key string) (string, error)

GetSystemSetting retrieves a system setting by key.

func (SettingsStore) Migrate added in v0.15.0

func (p SettingsStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (SettingsStore) Ping added in v0.15.0

func (p SettingsStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (SettingsStore) PoolStat added in v0.15.0

func (p SettingsStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*SettingsStore) SetSystemSetting added in v0.15.0

func (p *SettingsStore) SetSystemSetting(ctx context.Context, key, value string) error

SetSystemSetting sets or updates a system setting.

type SnapshotReader added in v0.7.0

type SnapshotReader interface {
	SnapshotReads

	// ListBlobsAfter returns up to limit stored objects with sha256 > after, in
	// sha256 order: blobs rows plus the generated metadata and deltas that
	// have no blobs row.
	ListBlobsAfter(ctx context.Context, after string, limit int) ([]BlobRow, error)
	// CountBlobs returns the number of objects ListBlobsAfter pages through.
	CountBlobs(ctx context.Context) (int64, error)

	// Release ends the snapshot and removes its lease. It is idempotent.
	Release()
}

SnapshotReader reads the database as of one instant: every call sees the same committed state, however long the backup takes and whatever is written meanwhile. It is read-only by construction (only read methods are listed, and the underlying transactions are READ ONLY).

A snapshot also holds a lease: while it is open, the sweeper deletes no blob bytes the snapshot can still see (a blob deleted, or a tier copy retired, after the snapshot was taken stays readable). Release ends both; a crashed holder's lease expires on its own.

type SnapshotReads added in v0.15.0

type SnapshotReads interface {
	// ExportPackageRows streams a repository's rows of one generic package table
	// (see PackageRowSet), as JSON objects.
	ExportPackageRows(ctx context.Context, set PackageRowSet, repoID string, fn func(row []byte) error) error
	GetProjectQuota(ctx context.Context, projectID string) (*models.ProjectQuota, error)
	ListAIAnalyses(
		ctx context.Context,
		repoID string,
		status string,
		licenseReviewOnly bool,
		limit, offset int,
	) ([]*models.AIAnalysis, int, error)
	ListAllProjects(ctx context.Context) ([]*models.Project, error)
	ListAllSSOProviders(ctx context.Context) ([]*models.SSOProvider, error)
	ListAllTokens(ctx context.Context, page, perPage int) ([]*models.Token, int, error)
	ListBundleItems(ctx context.Context, bundleID string) ([]*models.ReleaseBundleItem, error)
	ListBundlePromotions(ctx context.Context, bundleID string) ([]*models.BundlePromotion, error)
	ListCleanupPolicies(ctx context.Context, repoID string) ([]*models.CleanupPolicy, error)
	ListDockerBlobs(ctx context.Context, repoID string) ([]*models.DockerBlob, error)
	ListDockerManifestsByRepo(ctx context.Context, repoID string) ([]*models.DockerManifest, error)
	ListDockerTagsByRepo(ctx context.Context, repoID string, limit int) ([]*models.DockerTag, error)
	ListGroupMembers(ctx context.Context, groupRepoID string) ([]*models.RepositoryGroupMember, error)
	ListGroups(ctx context.Context) ([]*models.Group, error)
	ListLicenseScanResults(ctx context.Context, repoID string) ([]*models.LicenseScanResult, error)
	ListPermissionAssignments(ctx context.Context) ([]*models.PermissionAssignment, error)
	ListPermissionTargets(ctx context.Context) ([]*models.PermissionTarget, error)
	ListProjectCleanupPolicies(ctx context.Context, projectID string) ([]*models.CleanupPolicy, error)
	ListProjectGroups(ctx context.Context, projectID string) ([]*models.ProjectGroup, error)
	ListProjectMembers(ctx context.Context, projectID string) ([]*models.ProjectMember, error)
	ListPromotionPipelines(ctx context.Context) ([]*models.PromotionPipeline, error)
	ListReleaseBundles(ctx context.Context, nameFilter, stateFilter string, page, limit int) ([]*models.ReleaseBundle, int, error)
	ListRepositories(ctx context.Context, page, limit int, formatFilter string) ([]*models.Repository, error)
	ListSBOMReports(ctx context.Context, repoID string) ([]*models.SBOMReport, error)
	ListVEXStatements(ctx context.Context, repoID, artifactID string) ([]*models.VEXStatement, error)
	ListSecretScanResults(ctx context.Context, repoID string, flaggedOnly bool) ([]*models.SecretScanResult, error)
	ListStorageBackends(ctx context.Context) ([]*models.StorageBackend, error)
	ListStorageQuotas(ctx context.Context) ([]*models.StorageQuota, error)
	ListUserGroupMemberships(ctx context.Context) ([]*models.UserGroup, error)
	ListUsers(ctx context.Context, page, perPage int) ([]*models.User, int, error)
	ListVulnScanResults(ctx context.Context, repoID string, vulnerableOnly bool) ([]*models.VulnScanResult, error)
	ListWebhooks(ctx context.Context, repoID string) ([]*models.Webhook, error) // repoID="" = global
}

SnapshotReads are the table reads of a SnapshotReader. A test double of a snapshot over an in-memory fake implements these through the fake and the blob listing and lease itself.

type StorageBackendStore added in v0.15.0

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

StorageBackendStore owns the configured storage backends.

func (StorageBackendStore) AuthCacheGeneration added in v0.15.0

func (p StorageBackendStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (StorageBackendStore) AuthCacheTTL added in v0.15.0

func (p StorageBackendStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (StorageBackendStore) BeginTx added in v0.15.0

func (p StorageBackendStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (StorageBackendStore) Close added in v0.15.0

func (p StorageBackendStore) Close() error

Close writes the pending download counts and closes the database connection.

func (StorageBackendStore) CountFileDownload added in v0.19.0

func (p StorageBackendStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*StorageBackendStore) CreateStorageBackend added in v0.15.0

func (p *StorageBackendStore) CreateStorageBackend(ctx context.Context, backend *models.StorageBackend) error

CreateStorageBackend creates a new storage backend configuration.

func (*StorageBackendStore) DeleteStorageBackend added in v0.15.0

func (p *StorageBackendStore) DeleteStorageBackend(ctx context.Context, id string) error

DeleteStorageBackend deletes a storage backend.

func (StorageBackendStore) FlushDownloadCounts added in v0.19.0

func (p StorageBackendStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (StorageBackendStore) GetDB added in v0.15.0

func (p StorageBackendStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*StorageBackendStore) GetStorageBackend added in v0.15.0

func (p *StorageBackendStore) GetStorageBackend(ctx context.Context, name string) (*models.StorageBackend, error)

GetStorageBackend gets a storage backend by name.

func (*StorageBackendStore) ListStorageBackends added in v0.15.0

func (p *StorageBackendStore) ListStorageBackends(ctx context.Context) ([]*models.StorageBackend, error)

ListStorageBackends lists all storage backends.

func (StorageBackendStore) Migrate added in v0.15.0

func (p StorageBackendStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (StorageBackendStore) Ping added in v0.15.0

func (p StorageBackendStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (StorageBackendStore) PoolStat added in v0.15.0

func (p StorageBackendStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*StorageBackendStore) StorageBackendBusyReason added in v0.15.0

func (p *StorageBackendStore) StorageBackendBusyReason(ctx context.Context, backendID string) (string, error)

StorageBackendBusyReason reports why a backend's kind or config must not change (or the backend not be deleted): it holds blobs, is served by a tier or is named by a move journal row. "" means it is idle.

func (*StorageBackendStore) UpdateStorageBackendIfIdle added in v0.20.0

func (p *StorageBackendStore) UpdateStorageBackendIfIdle(
	ctx context.Context,
	backend *models.StorageBackend,
	requireIdle bool,
) (string, error)

UpdateStorageBackendIfIdle updates a storage backend's name, kind and config. When requireIdle is set (the kind or location changes), the backend row is locked FOR UPDATE and the busy check runs in the same transaction, so a concurrent tier move or blob write (which takes a key-share lock on the row) either commits first and is seen, or waits until the update is done. It returns "" when the backend was updated and the busy reason otherwise.

func (*StorageBackendStore) UpdateStorageBackendStatus added in v0.15.0

func (p *StorageBackendStore) UpdateStorageBackendStatus(ctx context.Context, id, status string, message *string) error

UpdateStorageBackendStatus updates the status of a storage backend.

type TerraformStore added in v0.15.0

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

TerraformStore owns Terraform/OpenTofu modules and providers.

Mapping onto the generic package tables. Modules and providers of one repository share the tables and are told apart by the package name prefix ("modules/", "providers/"), which is also what the listing shows.

Module (one archive is one version and one file; (name, system) is the package):

packages          name = name_key = "modules/<name>/<system>",
                  attrs {kind: "module", name, system}
package_versions  version = version_key = version, metadata {}
package_files     path modules/<name>/<system>/<version>/<filename>,
                  filename <name>-<system>-<version>.<ext>,
                  attrs {archive_ext}, the archive blob, role primary,
                  download_count (the module's counter), no unit_key
                  (terraform is not federated)

Provider (one version per provider version, one file per platform zip):

packages          name = name_key = "providers/<type>",
                  attrs {kind: "provider", type}
package_versions  version = version_key = version,
                  metadata {protocols: [..]} (version level: the first
                  platform of a version sets it)
package_files     path providers/<type>/<version>/<os>/<arch>/
                  terraform-provider-<type>_<version>_<os>_<arch>.zip,
                  filename the last segment, arch "<os>_<arch>" (the listing
                  and retention partition column), attrs {os, arch},
                  the zip blob, role primary, download_count

The id a client sees is package_files.id. A version is live while one of its platforms is live. A duplicate publish is a unique violation on the live version (modules) or on the live path (a platform): ErrDuplicate.

func (TerraformStore) AuthCacheGeneration added in v0.15.0

func (p TerraformStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (TerraformStore) AuthCacheTTL added in v0.15.0

func (p TerraformStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (TerraformStore) BeginTx added in v0.15.0

func (p TerraformStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (TerraformStore) Close added in v0.15.0

func (p TerraformStore) Close() error

Close writes the pending download counts and closes the database connection.

func (TerraformStore) CountFileDownload added in v0.19.0

func (p TerraformStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*TerraformStore) CreateTerraformModule added in v0.15.0

func (p *TerraformStore) CreateTerraformModule(ctx context.Context, mod *models.TerraformModule) error

CreateTerraformModule stores one module version. A live version with the same coordinates is ErrDuplicate (versions are immutable).

func (*TerraformStore) CreateTerraformProvider added in v0.15.0

func (p *TerraformStore) CreateTerraformProvider(ctx context.Context, prov *models.TerraformProvider) error

CreateTerraformProvider stores one provider platform zip. A live platform with the same coordinates is ErrDuplicate. The first platform of a version sets the version's protocols; the publish handler enforces that the later platforms declare the same.

func (*TerraformStore) DeleteTerraformModule added in v0.15.0

func (p *TerraformStore) DeleteTerraformModule(ctx context.Context, repoID, id string) error

DeleteTerraformModule hard-deletes one live module version file.

func (*TerraformStore) DeleteTerraformProvider added in v0.15.0

func (p *TerraformStore) DeleteTerraformProvider(ctx context.Context, repoID, id string) error

DeleteTerraformProvider hard-deletes one live provider platform file; the version goes with its last platform.

func (TerraformStore) FlushDownloadCounts added in v0.19.0

func (p TerraformStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (TerraformStore) GetDB added in v0.15.0

func (p TerraformStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*TerraformStore) GetTerraformModule added in v0.15.0

func (p *TerraformStore) GetTerraformModule(ctx context.Context, repoID, name, system, version string) (*models.TerraformModule, error)

GetTerraformModule returns the live module version, or (nil, nil).

func (*TerraformStore) GetTerraformProvider added in v0.15.0

func (p *TerraformStore) GetTerraformProvider(
	ctx context.Context,
	repoID, typ, version, osName, arch string,
) (*models.TerraformProvider, error)

GetTerraformProvider returns the live platform zip, or (nil, nil).

func (*TerraformStore) ListTerraformModuleVersions added in v0.15.0

func (p *TerraformStore) ListTerraformModuleVersions(ctx context.Context, repoID, name, system string) ([]*models.TerraformModule, error)

ListTerraformModuleVersions returns the live versions of one module, oldest first.

func (*TerraformStore) ListTerraformModules added in v0.15.0

func (p *TerraformStore) ListTerraformModules(ctx context.Context, repoID string) ([]*models.TerraformModule, error)

ListTerraformModules returns every live module version of the repository.

func (*TerraformStore) ListTerraformProviderPlatforms added in v0.15.0

func (p *TerraformStore) ListTerraformProviderPlatforms(ctx context.Context, repoID, typ string) ([]*models.TerraformProvider, error)

ListTerraformProviderPlatforms returns every live platform zip of one provider type, ordered by version, os and arch.

func (*TerraformStore) ListTerraformProviderVersionPlatforms added in v0.15.0

func (p *TerraformStore) ListTerraformProviderVersionPlatforms(
	ctx context.Context,
	repoID, typ, version string,
) ([]*models.TerraformProvider, error)

ListTerraformProviderVersionPlatforms returns every live platform zip of one provider version, ordered by os and arch.

func (*TerraformStore) ListTerraformProviders added in v0.15.0

func (p *TerraformStore) ListTerraformProviders(ctx context.Context, repoID string) ([]*models.TerraformProvider, error)

ListTerraformProviders returns every live provider platform zip of the repository.

func (TerraformStore) Migrate added in v0.15.0

func (p TerraformStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (TerraformStore) Ping added in v0.15.0

func (p TerraformStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (TerraformStore) PoolStat added in v0.15.0

func (p TerraformStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*TerraformStore) TerraformModuleStamp added in v0.15.0

func (p *TerraformStore) TerraformModuleStamp(ctx context.Context, repoID, name, system string) (string, error)

TerraformModuleStamp fingerprints the live versions of one module.

func (*TerraformStore) TerraformProviderStamp added in v0.15.0

func (p *TerraformStore) TerraformProviderStamp(ctx context.Context, repoID, typ string) (string, error)

TerraformProviderStamp fingerprints the live platforms of one provider type.

type TieringStore added in v0.15.0

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

TieringStore owns storage tiers, tiering policies, blob placement and the tier-move journal.

func (TieringStore) AuthCacheGeneration added in v0.15.0

func (p TieringStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (TieringStore) AuthCacheTTL added in v0.15.0

func (p TieringStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (*TieringStore) BeginStorageTierMove added in v0.15.0

func (p *TieringStore) BeginStorageTierMove(ctx context.Context, m *models.StorageTierMove) (*models.StorageTierMove, bool, error)

BeginStorageTierMove journals the start of a move. It returns the journal row that is now authoritative for the blob and whether this call created it; an existing row (a move in flight or one awaiting cleanup) is returned as is.

func (TieringStore) BeginTx added in v0.15.0

func (p TieringStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (TieringStore) Close added in v0.15.0

func (p TieringStore) Close() error

Close writes the pending download counts and closes the database connection.

func (TieringStore) CountFileDownload added in v0.19.0

func (p TieringStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*TieringStore) CountStorageTierMoves added in v0.15.0

func (p *TieringStore) CountStorageTierMoves(ctx context.Context) (int64, error)

CountStorageTierMoves counts the journal rows (moves in flight or awaiting cleanup).

func (*TieringStore) CreateStoragePolicy added in v0.15.0

func (p *TieringStore) CreateStoragePolicy(ctx context.Context, pol *models.StoragePolicy) error

CreateStoragePolicy inserts a policy (pol.ID must be set).

func (*TieringStore) CreateStorageTier added in v0.15.0

func (p *TieringStore) CreateStorageTier(ctx context.Context, t *models.StorageTier) error

CreateStorageTier inserts a tier (t.ID must be set).

func (*TieringStore) DeleteStoragePolicy added in v0.15.0

func (p *TieringStore) DeleteStoragePolicy(ctx context.Context, id string) (bool, error)

DeleteStoragePolicy deletes a policy; it reports whether a row was removed.

func (*TieringStore) DeleteStorageTierIfUnused added in v0.15.0

func (p *TieringStore) DeleteStorageTierIfUnused(ctx context.Context, tierID string) (string, error)

DeleteStorageTierIfUnused deletes a non-primary tier unless something still depends on it, atomically: the tier and its backend row are locked FOR UPDATE for the whole check-and-delete, so a concurrent move (whose journal and blobs.storage_backend_id writes take a key-share lock on the backend row) either commits before the check and is seen, or waits until the delete is done. It returns "" when the tier was deleted (or was already gone) and the human-readable reason otherwise.

func (*TieringStore) FailStorageTierMove added in v0.15.0

func (p *TieringStore) FailStorageTierMove(ctx context.Context, sha256, message string) error

FailStorageTierMove records a failed attempt on the journal row.

func (*TieringStore) FinishStorageTierMove added in v0.15.0

func (p *TieringStore) FinishStorageTierMove(ctx context.Context, sha256 string) error

FinishStorageTierMove removes the journal row once the move is complete.

func (*TieringStore) FlipBlobPlacement added in v0.15.0

func (p *TieringStore) FlipBlobPlacement(
	ctx context.Context,
	sha256, from, to string,
	verify func(ctx context.Context) error,
) (models.FlipOutcome, error)

FlipBlobPlacement atomically repoints blobs.storage_backend_id from `from` to `to` and marks the journal row flipped, in ONE transaction under the per-blob advisory lock that SafeDeleteBlob and uploaders take (WithBlobLock). It is the only place a placement changes: either the whole flip commits or nothing did, so a crash leaves exactly one authoritative placement.

verify runs once the blob lock is held and before the placement changes; a non-nil error aborts the flip. The mover uses it to prove the target copy still exists: every path that removes a copy (uploaders settling a race, SafeDeleteBlob) does so under the same lock, so a copy confirmed here cannot vanish before the flip commits. verify runs while the flip holds a blob-lock slot (see core.lockSlots), so like a WithBlobLocks callback it MUST NOT take another blob lock or delete a blob: a nested acquisition can deadlock once the concurrent holders fill the slots.

func (TieringStore) FlushDownloadCounts added in v0.19.0

func (p TieringStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (*TieringStore) GetBlobPlacement added in v0.15.0

func (p *TieringStore) GetBlobPlacement(ctx context.Context, sha256 string) (string, int64, bool, error)

GetBlobPlacement returns where the blob lives ("" = primary store) and its size. found is false when there is no blobs row.

func (TieringStore) GetDB added in v0.15.0

func (p TieringStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*TieringStore) GetStoragePolicy added in v0.15.0

func (p *TieringStore) GetStoragePolicy(ctx context.Context, id string) (*models.StoragePolicy, error)

GetStoragePolicy returns a policy by id, or nil when there is none.

func (*TieringStore) GetStorageTierByName added in v0.15.0

func (p *TieringStore) GetStorageTierByName(ctx context.Context, name string) (*models.StorageTier, error)

GetStorageTierByName returns the named tier, or nil when there is none.

func (*TieringStore) ListBlobRefs added in v0.15.0

func (p *TieringStore) ListBlobRefs(ctx context.Context, shas []string) (map[string][]models.BlobRef, error)

ListBlobRefs returns, per blob, the repository entries referencing it (repository name, format and artifact path).

func (*TieringStore) ListPromotionCandidates added in v0.15.0

func (p *TieringStore) ListPromotionCandidates(
	ctx context.Context,
	backendIDs []string,
	after string,
	limit int,
) ([]models.BlobFacts, error)

ListPromotionCandidates returns blobs placed on one of backendIDs that were read after they arrived there (last_accessed_at > tier_changed_at), ordered by sha256 after the cursor, skipping blobs with a move in flight.

func (*TieringStore) ListRecoverableStorageTierMoves added in v0.15.0

func (p *TieringStore) ListRecoverableStorageTierMoves(
	ctx context.Context,
	maxAttempts int,
	retryAfter time.Duration,
	limit int,
) ([]*models.StorageTierMove, error)

ListRecoverableStorageTierMoves returns journal rows that still have attempts left, or that last failed more than retryAfter ago.

func (*TieringStore) ListStoragePolicies added in v0.15.0

func (p *TieringStore) ListStoragePolicies(ctx context.Context) ([]*models.StoragePolicy, error)

ListStoragePolicies lists every policy in evaluation order.

func (*TieringStore) ListStorageTierMoves added in v0.15.0

func (p *TieringStore) ListStorageTierMoves(ctx context.Context, limit int) ([]*models.StorageTierMove, error)

ListStorageTierMoves returns the most recently touched journal rows.

func (*TieringStore) ListStorageTiers added in v0.15.0

func (p *TieringStore) ListStorageTiers(ctx context.Context) ([]*models.StorageTier, error)

ListStorageTiers lists every tier, hottest rank first.

func (TieringStore) Migrate added in v0.15.0

func (p TieringStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (TieringStore) Ping added in v0.15.0

func (p TieringStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (TieringStore) PoolStat added in v0.15.0

func (p TieringStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*TieringStore) ScanTierCandidates added in v0.15.0

func (p *TieringStore) ScanTierCandidates(
	ctx context.Context,
	after string,
	window int,
	clauses []models.TierScanClause,
) ([]models.BlobFacts, string, int, error)

ScanTierCandidates examines one window of at most `window` blobs rows after the cursor and returns those matching any clause (and not already being moved). next is the cursor for the following call, "" once the end of the table was reached; scanned is how many rows the window covered.

func (*TieringStore) StorageTierUsage added in v0.15.0

func (p *TieringStore) StorageTierUsage(ctx context.Context) ([]models.TierUsage, error)

StorageTierUsage returns blob counts and bytes per placement ("" = primary store).

func (*TieringStore) TouchBlobAccess added in v0.15.0

func (p *TieringStore) TouchBlobAccess(ctx context.Context, accessed map[string]time.Time, resolution time.Duration) (int64, error)

TouchBlobAccess raises blobs.last_accessed_at for the given blobs in one statement. A blob whose recorded access is already within resolution of the new time is left alone, so repeated downloads of a hot blob cost no write. The exception is a blob whose recorded access is not newer than its last tier change: its first read on the new tier is always written, or promote-on-read would miss it for up to resolution after a demotion.

Rows are locked in sha256 order (FOR UPDATE under ORDER BY) so two replicas flushing overlapping sets cannot deadlock each other. Every write here is a non-HOT update (last_accessed_at is in the promotion index predicate), which the access resolution bounds to one per blob per resolution window.

func (*TieringStore) UpdateStoragePolicy added in v0.15.0

func (p *TieringStore) UpdateStoragePolicy(ctx context.Context, pol *models.StoragePolicy) error

UpdateStoragePolicy overwrites every field of the policy.

func (*TieringStore) UpdateStorageTier added in v0.15.0

func (p *TieringStore) UpdateStorageTier(ctx context.Context, t *models.StorageTier) error

UpdateStorageTier updates a tier's name, rank and promote-on-read flag.

type TokenStore added in v0.15.0

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

TokenStore owns API tokens.

func (TokenStore) AuthCacheGeneration added in v0.15.0

func (p TokenStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (TokenStore) AuthCacheTTL added in v0.15.0

func (p TokenStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (TokenStore) BeginTx added in v0.15.0

func (p TokenStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (TokenStore) Close added in v0.15.0

func (p TokenStore) Close() error

Close writes the pending download counts and closes the database connection.

func (TokenStore) CountFileDownload added in v0.19.0

func (p TokenStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*TokenStore) CreateToken added in v0.15.0

func (p *TokenStore) CreateToken(ctx context.Context, token *models.Token) (*models.Token, error)

func (TokenStore) FlushDownloadCounts added in v0.19.0

func (p TokenStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (TokenStore) GetDB added in v0.15.0

func (p TokenStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*TokenStore) GetTokenByHash added in v0.15.0

func (p *TokenStore) GetTokenByHash(ctx context.Context, hash string) (*models.Token, error)

GetTokenByHash returns the token with the given hash, from the auth cache when fresh.

func (*TokenStore) GetTokenByHashUncached added in v0.15.0

func (p *TokenStore) GetTokenByHashUncached(ctx context.Context, hash string) (*models.Token, error)

func (*TokenStore) GetTokenByID added in v0.15.0

func (p *TokenStore) GetTokenByID(ctx context.Context, tokenID string) (*models.Token, error)

func (*TokenStore) ListAllTokens added in v0.15.0

func (p *TokenStore) ListAllTokens(ctx context.Context, page, perPage int) ([]*models.Token, int, error)

func (*TokenStore) ListTokensByUser added in v0.15.0

func (p *TokenStore) ListTokensByUser(ctx context.Context, userID string) ([]*models.Token, error)

func (*TokenStore) ListUnifiedTokens added in v0.15.0

func (p *TokenStore) ListUnifiedTokens(ctx context.Context, params models.TokenListParams) ([]*models.TokenListItem, int, error)

ListUnifiedTokens returns one page of the unified token list (personal, project and federation tokens), newest first, and the number of tokens the caller may see that match the filters.

func (TokenStore) Migrate added in v0.15.0

func (p TokenStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (TokenStore) Ping added in v0.15.0

func (p TokenStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (TokenStore) PoolStat added in v0.15.0

func (p TokenStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*TokenStore) RevokeToken added in v0.15.0

func (p *TokenStore) RevokeToken(ctx context.Context, tokenID string) error

func (*TokenStore) UpdateTokenLastUsed added in v0.15.0

func (p *TokenStore) UpdateTokenLastUsed(ctx context.Context, tokenID string) error

type Transaction

type Transaction interface {
	// Commit commits the transaction
	Commit() error

	// Rollback rolls back the transaction
	Rollback() error

	// Exec executes a query without returning rows
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

	// Query executes a query that returns rows
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

	// QueryRow executes a query that returns a single row
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

Transaction defines the interface for database transactions.

type TrashOps added in v0.15.0

type TrashOps interface {
	// TrashRows soft-deletes the given rows of repoID (stamps deleted_at and
	// deleted_by) and returns true. For a package format the ids are listed
	// package_files ids and kind only has to be a package kind (the repository's
	// format decides what is stamped); docker kinds address docker rows. It
	// returns false without touching anything when the repository's retention is
	// 0: the caller then hard-deletes as before. ErrTrashNotFound means none of
	// the rows is live in repoID.
	TrashRows(ctx context.Context, repoID string, kind models.TrashKind, ids []string, deletedBy string) (bool, error)

	// TrashRepository soft-deletes a repository (contents stay in place, hidden
	// with it). It returns false without touching anything when retention is 0.
	TrashRepository(ctx context.Context, id, deletedBy string) (bool, error)

	// ListTrash lists trashed items (newest first) and the total count.
	ListTrash(ctx context.Context, f models.TrashFilter) ([]*models.TrashItem, int, error)

	// GetTrashItem returns one trashed item, ErrTrashNotFound when absent.
	GetTrashItem(ctx context.Context, kind models.TrashKind, id string) (*models.TrashItem, error)

	// RestoreTrash brings an item (or a repository) back. ErrTrashNotFound,
	// ErrTrashConflict (unique key taken meanwhile) and ErrTrashRepoTrashed
	// are the expected failures.
	RestoreTrash(ctx context.Context, kind models.TrashKind, id string) (*models.TrashItem, error)

	// PurgeTrash permanently removes a trashed item (or repository, cascading
	// its contents) and reports what the caller must clean up: blobs to free via
	// storage.SafeDeleteBlob and quota to release. A repository's blobs are not
	// listed (they can be numerous); the caller collects orphans afterwards.
	// A foreign-key violation (IsForeignKeyViolation) means the repository is
	// still referenced, e.g. by a release bundle.
	PurgeTrash(ctx context.Context, kind models.TrashKind, id string) (*models.TrashPurgeResult, error)

	// PurgeExpiredTrash is PurgeTrash for the retention worker: it removes the
	// item only if its retention window has passed at the time of the purge,
	// judged inside the purge's own lock/statement. ErrTrashNotFound also
	// covers an item that was restored, re-trashed (fresh deleted_at) or whose
	// repository's retention was raised since ListExpiredTrash listed it.
	PurgeExpiredTrash(ctx context.Context, kind models.TrashKind, id string) (*models.TrashPurgeResult, error)

	// RegenKeys returns what the metadata workers key a refresh by for an item,
	// as the format's storage.Trash.RegenKeys fragment reads it: (group_id,
	// artifact_id) for a Maven artifact, (package id, "") for an npm version and
	// ("", "") for every other kind (deb/rpm refresh per repository).
	RegenKeys(ctx context.Context, kind models.TrashKind, id string) (string, string, error)

	// ListExpiredTrash returns up to limit items whose retention window has
	// passed (items of repositories that are themselves in the trash are
	// left to the repository's own purge).
	ListExpiredTrash(ctx context.Context, limit int) ([]models.TrashRef, error)
}

TrashOps is the storage side of soft delete (internal/trash, the trash API and the purge worker). PostgresDB implements it; handlers treat a database that does not (test fakes) as "soft delete unavailable" and hard-delete.

Retention is resolved per repository: repositories.trash_retention_days, or the server default (SetTrashRetentionDays) when NULL. 0 means no trash.

The reference id of a package item is package_files.id of its listed file; a docker item is a manifest or tag id and a repository item is the repository id.

type TrashStore added in v0.5.0

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

TrashStore owns the trash (soft-deleted repositories and packages), its retention and purge.

Every package format except docker keeps its files in package_files, so one generic engine (trash_files.go) trashes, restores and purges them; what a format does differently is data in its storage.Trash descriptor. Docker keeps dedicated tables and is the one explicit special case (trash_docker.go).

func (TrashStore) AuthCacheGeneration added in v0.15.0

func (p TrashStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (TrashStore) AuthCacheTTL added in v0.15.0

func (p TrashStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (TrashStore) BeginTx added in v0.15.0

func (p TrashStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (TrashStore) Close added in v0.15.0

func (p TrashStore) Close() error

Close writes the pending download counts and closes the database connection.

func (TrashStore) CountFileDownload added in v0.19.0

func (p TrashStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (TrashStore) FlushDownloadCounts added in v0.19.0

func (p TrashStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (TrashStore) GetDB added in v0.15.0

func (p TrashStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*TrashStore) GetTrashItem added in v0.5.0

func (p *TrashStore) GetTrashItem(ctx context.Context, kind models.TrashKind, id string) (*models.TrashItem, error)

GetTrashItem implements TrashOps.

func (*TrashStore) HardDeleteFiles added in v0.15.0

func (p *TrashStore) HardDeleteFiles(ctx context.Context, repoID string, ids []string) ([]models.FileDeletion, error)

HardDeleteFiles deletes the live units of the given listed files of repoID for good, in one transaction, bypassing the trash (the retention worker's hard-delete path, and the delete of a repository that keeps no trash). The hooks of the format's OnPurge run for each unit, then the files go and the versions and packages they leave empty are pruned. The result has one entry per id that was live; the caller frees the blobs and gives the quota back.

func (*TrashStore) ListExpiredTrash added in v0.5.0

func (p *TrashStore) ListExpiredTrash(ctx context.Context, limit int) ([]models.TrashRef, error)

ListExpiredTrash implements TrashOps.

func (*TrashStore) ListTrash added in v0.5.0

func (p *TrashStore) ListTrash(ctx context.Context, f models.TrashFilter) ([]*models.TrashItem, int, error)

ListTrash implements TrashOps.

func (TrashStore) Migrate added in v0.15.0

func (p TrashStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (TrashStore) Ping added in v0.15.0

func (p TrashStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (TrashStore) PoolStat added in v0.15.0

func (p TrashStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*TrashStore) PurgeExpiredTrash added in v0.19.1

func (p *TrashStore) PurgeExpiredTrash(ctx context.Context, kind models.TrashKind, id string) (*models.TrashPurgeResult, error)

PurgeExpiredTrash implements TrashOps.

func (*TrashStore) PurgeTrash added in v0.5.0

func (p *TrashStore) PurgeTrash(ctx context.Context, kind models.TrashKind, id string) (*models.TrashPurgeResult, error)

PurgeTrash implements TrashOps.

func (*TrashStore) RegenKeys added in v0.5.0

func (p *TrashStore) RegenKeys(ctx context.Context, kind models.TrashKind, id string) (string, string, error)

RegenKeys implements TrashOps.

func (*TrashStore) RestoreTrash added in v0.5.0

func (p *TrashStore) RestoreTrash(ctx context.Context, kind models.TrashKind, id string) (*models.TrashItem, error)

RestoreTrash implements TrashOps.

func (*TrashStore) SetTrashRetentionDays added in v0.15.0

func (p *TrashStore) SetTrashRetentionDays(days int)

SetTrashRetentionDays sets the server-wide default retention, in days, for repositories whose trash_retention_days is NULL.

func (*TrashStore) TrashRepository added in v0.5.0

func (p *TrashStore) TrashRepository(ctx context.Context, id, deletedBy string) (bool, error)

TrashRepository implements TrashOps.

func (*TrashStore) TrashRows added in v0.5.0

func (p *TrashStore) TrashRows(ctx context.Context, repoID string, kind models.TrashKind, ids []string, deletedBy string) (bool, error)

TrashRows implements TrashOps.

func (*TrashStore) TrashedRepositoryByName added in v0.15.0

func (p *TrashStore) TrashedRepositoryByName(ctx context.Context, name string) (*models.TrashItem, error)

TrashedRepositoryByName returns the repository in the trash that holds name (its name stays reserved until it is purged or restored), ErrTrashNotFound when no trashed repository has it. It is not part of TrashOps: only the repository-create conflict message needs it.

type UserGroupStore added in v0.15.0

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

UserGroupStore owns user groups and their memberships.

func (*UserGroupStore) AddUserToGroup added in v0.15.0

func (p *UserGroupStore) AddUserToGroup(ctx context.Context, userID, groupID string) error

func (UserGroupStore) AuthCacheGeneration added in v0.15.0

func (p UserGroupStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (UserGroupStore) AuthCacheTTL added in v0.15.0

func (p UserGroupStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (UserGroupStore) BeginTx added in v0.15.0

func (p UserGroupStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (UserGroupStore) Close added in v0.15.0

func (p UserGroupStore) Close() error

Close writes the pending download counts and closes the database connection.

func (UserGroupStore) CountFileDownload added in v0.19.0

func (p UserGroupStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*UserGroupStore) CreateGroup added in v0.15.0

func (p *UserGroupStore) CreateGroup(ctx context.Context, group *models.Group) (*models.Group, error)

func (*UserGroupStore) DeleteGroup added in v0.15.0

func (p *UserGroupStore) DeleteGroup(ctx context.Context, id string) error

func (UserGroupStore) FlushDownloadCounts added in v0.19.0

func (p UserGroupStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (UserGroupStore) GetDB added in v0.15.0

func (p UserGroupStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*UserGroupStore) GetGroupByID added in v0.15.0

func (p *UserGroupStore) GetGroupByID(ctx context.Context, id string) (*models.Group, error)

func (*UserGroupStore) GetGroupByName added in v0.15.0

func (p *UserGroupStore) GetGroupByName(ctx context.Context, name string) (*models.Group, error)

func (*UserGroupStore) GetOrCreateGroup added in v0.15.0

func (p *UserGroupStore) GetOrCreateGroup(ctx context.Context, name string) (*models.Group, error)

func (*UserGroupStore) ListGroups added in v0.15.0

func (p *UserGroupStore) ListGroups(ctx context.Context) ([]*models.Group, error)

func (*UserGroupStore) ListGroupsByUser added in v0.15.0

func (p *UserGroupStore) ListGroupsByUser(ctx context.Context, userID string) ([]*models.Group, error)

ListGroupsByUser returns the groups of a user, from the auth cache when fresh.

func (*UserGroupStore) ListGroupsByUserUncached added in v0.15.0

func (p *UserGroupStore) ListGroupsByUserUncached(ctx context.Context, userID string) ([]*models.Group, error)

func (*UserGroupStore) ListUserGroupMemberships added in v0.15.0

func (p *UserGroupStore) ListUserGroupMemberships(ctx context.Context) ([]*models.UserGroup, error)

ListUserGroupMemberships returns every user-to-group membership, including the ones an SSO login manages.

func (*UserGroupStore) ListUsersByGroup added in v0.15.0

func (p *UserGroupStore) ListUsersByGroup(ctx context.Context, groupID string) ([]*models.User, error)

func (UserGroupStore) Migrate added in v0.15.0

func (p UserGroupStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (*UserGroupStore) PatchGroup added in v0.20.0

func (p *UserGroupStore) PatchGroup(ctx context.Context, id string, patch GroupPatch) (*models.Group, error)

PatchGroup writes only the columns in patch, so a concurrent edit of the other column is not reverted by a stale snapshot. It returns the updated row, or nil when the group does not exist.

func (UserGroupStore) Ping added in v0.15.0

func (p UserGroupStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (UserGroupStore) PoolStat added in v0.15.0

func (p UserGroupStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*UserGroupStore) RemoveUserFromGroup added in v0.15.0

func (p *UserGroupStore) RemoveUserFromGroup(ctx context.Context, userID, groupID string) error

func (*UserGroupStore) SetGroupMembers added in v0.15.0

func (p *UserGroupStore) SetGroupMembers(ctx context.Context, groupID string, userIDs []string) error

SetGroupMembers replaces the members of a group with userIDs in one transaction: a user id that does not exist fails the insert with a foreign key violation (database.IsForeignKeyViolation) and nothing changes.

func (*UserGroupStore) SyncSSOGroups added in v0.15.0

func (p *UserGroupStore) SyncSSOGroups(ctx context.Context, userID string, groupIDs []string) error

type UserPatch added in v0.20.0

type UserPatch struct {
	SetEmail           bool // Email is written, nil clearing it to NULL
	Email              *string
	FullName           *string
	Disabled           *bool
	MustChangePassword *bool
	PasswordHash       *string
}

UserPatch names the columns an admin edit writes; nil fields (and SetEmail=false) leave the stored value alone.

type UserStore added in v0.15.0

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

UserStore owns user accounts, passwords and the bootstrap admin.

func (UserStore) AuthCacheGeneration added in v0.15.0

func (p UserStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (UserStore) AuthCacheTTL added in v0.15.0

func (p UserStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (UserStore) BeginTx added in v0.15.0

func (p UserStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (UserStore) Close added in v0.15.0

func (p UserStore) Close() error

Close writes the pending download counts and closes the database connection.

func (UserStore) CountFileDownload added in v0.19.0

func (p UserStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*UserStore) CountUsers added in v0.15.0

func (p *UserStore) CountUsers(ctx context.Context) (int, error)

func (*UserStore) CreateBootstrapAdmin added in v0.15.0

func (p *UserStore) CreateBootstrapAdmin(ctx context.Context, spec BootstrapAdmin) (bool, error)

CreateBootstrapAdmin creates the first admin user, binds it to the admin-all permission target and creates its optional access token in one transaction guarded by an advisory lock. It returns false (and creates nothing) when a user already exists, which is what a replica that lost the first-boot race observes.

func (*UserStore) CreateUser added in v0.15.0

func (p *UserStore) CreateUser(ctx context.Context, user *models.User) (*models.User, error)

func (*UserStore) DeleteUser added in v0.15.0

func (p *UserStore) DeleteUser(ctx context.Context, id string) (bool, error)

DeleteUser hard-deletes a human user. Sessions, tokens, project memberships, group links and the SSO link (external_id/provider_slug live on the row) go with it; creator/owner references are set to NULL by their foreign keys. The direct permission assignments carry no foreign key and are removed explicitly. It returns false when the user does not exist and ErrLastAdmin when the user is the last enabled admin.

func (UserStore) FlushDownloadCounts added in v0.19.0

func (p UserStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (UserStore) GetDB added in v0.15.0

func (p UserStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*UserStore) GetPasswordExpiry added in v0.15.0

func (p *UserStore) GetPasswordExpiry(ctx context.Context, userID string) (*time.Time, error)

GetPasswordExpiry returns the password expiry of a user that must still change its password; nil when there is none.

func (*UserStore) GetUserByEmail added in v0.15.0

func (p *UserStore) GetUserByEmail(ctx context.Context, email string) (*models.User, error)

func (*UserStore) GetUserByExternalID added in v0.15.0

func (p *UserStore) GetUserByExternalID(ctx context.Context, externalID, providerSlug string) (*models.User, error)

func (*UserStore) GetUserByID added in v0.15.0

func (p *UserStore) GetUserByID(ctx context.Context, id string) (*models.User, error)

GetUserByID returns the user with the given ID, from the auth cache when fresh.

func (*UserStore) GetUserByIDUncached added in v0.15.0

func (p *UserStore) GetUserByIDUncached(ctx context.Context, id string) (*models.User, error)

func (*UserStore) GetUserByUsername added in v0.15.0

func (p *UserStore) GetUserByUsername(ctx context.Context, username string) (*models.User, error)

func (*UserStore) ListUsers added in v0.15.0

func (p *UserStore) ListUsers(ctx context.Context, page, perPage int) ([]*models.User, int, error)

func (UserStore) Migrate added in v0.15.0

func (p UserStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (*UserStore) PatchUser added in v0.20.0

func (p *UserStore) PatchUser(ctx context.Context, id string, patch UserPatch) (*models.User, error)

PatchUser writes only the columns in patch, so a concurrent disable or password change on other columns is not reverted by a stale snapshot. It returns the updated row, or nil when the user does not exist. A user that is disabled after the write loses the project tokens it minted, in the same transaction.

func (UserStore) Ping added in v0.15.0

func (p UserStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (UserStore) PoolStat added in v0.15.0

func (p UserStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*UserStore) RepairBootstrapAdmin added in v0.15.0

func (p *UserStore) RepairBootstrapAdmin(ctx context.Context, username string) (bool, error)

RepairBootstrapAdmin re-binds the named local admin user to admin-all when no principal at all holds that target, which is the state an interrupted bootstrap leaves behind. It never touches an instance where some principal already holds admin-all.

func (*UserStore) UpdateUserLastLogin added in v0.15.0

func (p *UserStore) UpdateUserLastLogin(ctx context.Context, id string, at time.Time) error

UpdateUserLastLogin sets only last_login_at, so a login finishing from a stale snapshot cannot undo a concurrent disable or password reset.

func (*UserStore) UpdateUserPassword added in v0.15.0

func (p *UserStore) UpdateUserPassword(ctx context.Context, id, passwordHash string, mustChange bool) error

UpdateUserPassword sets only password_hash and must_change_password.

func (*UserStore) UpdateUserSSO added in v0.15.0

func (p *UserStore) UpdateUserSSO(ctx context.Context, userID string, externalID, providerSlug string) error

func (*UserStore) UpdateUserSSOProfile added in v0.15.0

func (p *UserStore) UpdateUserSSOProfile(ctx context.Context, id string, email, fullName *string, lastLogin time.Time) error

UpdateUserSSOProfile sets only email (when non-nil), full_name (when non-nil) and last_login_at, so an SSO login finishing from a stale snapshot cannot undo a concurrent disable or password reset.

type VEXFeedStore added in v0.22.0

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

VEXFeedStore owns the vendor CSAF VEX feeds and the statements imported from their documents (vex_feed_statements). Materializing those statements into vex_statements is VEXStore.ReplaceFeedVEXStatements.

func (VEXFeedStore) AuthCacheGeneration added in v0.22.0

func (p VEXFeedStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (VEXFeedStore) AuthCacheTTL added in v0.22.0

func (p VEXFeedStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (VEXFeedStore) BeginTx added in v0.22.0

func (p VEXFeedStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (VEXFeedStore) Close added in v0.22.0

func (p VEXFeedStore) Close() error

Close writes the pending download counts and closes the database connection.

func (VEXFeedStore) CountFileDownload added in v0.22.0

func (p VEXFeedStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*VEXFeedStore) CreateVEXFeed added in v0.22.0

func (p *VEXFeedStore) CreateVEXFeed(ctx context.Context, f *models.VEXFeed) error

CreateVEXFeed stores a feed and fills f with the stored row (ID, defaults, timestamps); ErrVEXFeedConflict when the name is taken.

func (*VEXFeedStore) DeleteVEXFeed added in v0.22.0

func (p *VEXFeedStore) DeleteVEXFeed(ctx context.Context, id string) error

DeleteVEXFeed deletes a feed with its imported and materialized statements; ErrVEXFeedNotFound when absent.

func (VEXFeedStore) FlushDownloadCounts added in v0.22.0

func (p VEXFeedStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (VEXFeedStore) GetDB added in v0.22.0

func (p VEXFeedStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*VEXFeedStore) GetVEXFeed added in v0.22.0

func (p *VEXFeedStore) GetVEXFeed(ctx context.Context, id string) (*models.VEXFeed, error)

GetVEXFeed reads one feed; ErrVEXFeedNotFound when absent.

func (*VEXFeedStore) ListVEXFeedStatements added in v0.22.0

func (p *VEXFeedStore) ListVEXFeedStatements(ctx context.Context, feedID string) ([]models.VEXFeedStatement, error)

ListVEXFeedStatements lists the imported statements of a feed in import order.

func (*VEXFeedStore) ListVEXFeeds added in v0.22.0

func (p *VEXFeedStore) ListVEXFeeds(ctx context.Context) ([]*models.VEXFeed, error)

ListVEXFeeds lists the feeds by name, with their statement counts.

func (VEXFeedStore) Migrate added in v0.22.0

func (p VEXFeedStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (VEXFeedStore) Ping added in v0.22.0

func (p VEXFeedStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (VEXFeedStore) PoolStat added in v0.22.0

func (p VEXFeedStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*VEXFeedStore) RecordVEXFeedSync added in v0.22.0

func (p *VEXFeedStore) RecordVEXFeedSync(ctx context.Context, feedID string, res models.VEXFeedSyncResult) error

RecordVEXFeedSync records the outcome of a sync: the attempt time and error always; on success also the success time, the new cursor (res.CursorAt nil keeps the current one) and the document counts. ErrVEXFeedNotFound when the feed is gone.

func (*VEXFeedStore) ReplaceVEXFeedDocument added in v0.22.0

func (p *VEXFeedStore) ReplaceVEXFeedDocument(ctx context.Context, feedID, documentURL string, stmts []models.VEXFeedStatement) error

ReplaceVEXFeedDocument replaces the stored statements of one document of a feed with stmts in one transaction (no stmts removes the document).

func (*VEXFeedStore) UpdateVEXFeed added in v0.22.0

func (p *VEXFeedStore) UpdateVEXFeed(ctx context.Context, f *models.VEXFeed) error

UpdateVEXFeed replaces the editable fields of feed f.ID (name, url, enabled, require_signature, pgp_keys, interval_hours) and fills f with the stored row; a new URL, pgp_keys or require_signature resets the cursor. ErrVEXFeedNotFound when absent, ErrVEXFeedConflict when another feed has the name.

type VEXStore added in v0.15.0

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

VEXStore owns VEX statements and the VEX suggestions of federated peers.

vex_statements holds one decision per (repository, artifact, vulnerability) whatever its source: an operator decision (local) replaces anything, a vendor feed (csaf) or an automatically applied peer decision (peer) never replaces a statement of another source.

func (*VEXStore) AcceptVEXSuggestion added in v0.22.0

func (p *VEXStore) AcceptVEXSuggestion(ctx context.Context, repoID, id, decidedBy string) (*models.VEXStatement, error)

AcceptVEXSuggestion records a suggestion of a repository as the target's statement (source peer, created by decidedBy), replacing whatever statement was there, and marks the suggestion accepted, in one transaction. It returns the stored statement; ErrVEXSuggestionNotFound when the suggestion is absent.

func (*VEXStore) ApplyPeerVEXStatement added in v0.22.0

func (p *VEXStore) ApplyPeerVEXStatement(ctx context.Context, s *models.VEXStatement) (bool, error)

ApplyPeerVEXStatement stores the decision of the federated peer s.PeerID as a peer statement: inserted, or updated when the target's statement is already that peer's. It reports whether it wrote; a statement of any other source is left alone.

func (VEXStore) AuthCacheGeneration added in v0.15.0

func (p VEXStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (VEXStore) AuthCacheTTL added in v0.15.0

func (p VEXStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (VEXStore) BeginTx added in v0.15.0

func (p VEXStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (VEXStore) Close added in v0.15.0

func (p VEXStore) Close() error

Close writes the pending download counts and closes the database connection.

func (VEXStore) CountFileDownload added in v0.19.0

func (p VEXStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*VEXStore) DeleteVEXStatement added in v0.15.0

func (p *VEXStore) DeleteVEXStatement(ctx context.Context, repoID, id string) error

DeleteVEXStatement deletes a decision scoped to repoID; ErrVEXStatementNotFound when absent.

func (*VEXStore) DeleteVEXSuggestionsOfPeer added in v0.22.0

func (p *VEXStore) DeleteVEXSuggestionsOfPeer(ctx context.Context, peerID string) (int64, error)

DeleteVEXSuggestionsOfPeer deletes every suggestion of a peer.

func (VEXStore) FlushDownloadCounts added in v0.19.0

func (p VEXStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (VEXStore) GetDB added in v0.15.0

func (p VEXStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*VEXStore) GetVEXSuggestion added in v0.22.0

func (p *VEXStore) GetVEXSuggestion(ctx context.Context, repoID, id string) (*models.VEXSuggestion, error)

GetVEXSuggestion reads one suggestion of a repository; ErrVEXSuggestionNotFound when absent.

func (*VEXStore) ListVEXStatements added in v0.15.0

func (p *VEXStore) ListVEXStatements(ctx context.Context, repoID, artifactID string) ([]*models.VEXStatement, error)

ListVEXStatements lists the decisions of a repository, optionally only those of one artifact (artifactID != "").

func (*VEXStore) ListVEXSuggestions added in v0.22.0

func (p *VEXStore) ListVEXSuggestions(ctx context.Context, repoID, state string) ([]*models.VEXSuggestion, error)

ListVEXSuggestions lists the suggestions of a repository in one state ("" = all), with the peer and the statement the target has now.

func (*VEXStore) ListVEXTargets added in v0.22.0

func (p *VEXStore) ListVEXTargets(ctx context.Context, repoID string) ([]models.VEXTarget, error)

ListVEXTargets returns the latest completed or partial vulnerability scan with findings of every artifact of repoID ("" = every repository), with the repository format.

func (VEXStore) Migrate added in v0.15.0

func (p VEXStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (VEXStore) Ping added in v0.15.0

func (p VEXStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (VEXStore) PoolStat added in v0.15.0

func (p VEXStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*VEXStore) PruneVEXSuggestions added in v0.22.0

func (p *VEXStore) PruneVEXSuggestions(ctx context.Context, peerID string, keepIDs []string) (int64, error)

PruneVEXSuggestions deletes the suggestions of a peer but keepIDs and returns how many it deleted.

func (*VEXStore) ReplaceFeedVEXStatements added in v0.22.0

func (p *VEXStore) ReplaceFeedVEXStatements(ctx context.Context, feedID string, stmts []*models.VEXStatement) (int, error)

ReplaceFeedVEXStatements replaces the statements materialized from a feed with stmts (stored as csaf statements of feedID) in one transaction. A target that has a statement of another source keeps it. It returns how many were inserted.

func (*VEXStore) SetVEXSuggestionState added in v0.22.0

func (p *VEXStore) SetVEXSuggestionState(ctx context.Context, repoID, id, state, decidedBy string) error

SetVEXSuggestionState moves a suggestion of a repository to state, decided by decidedBy now (pending clears the decision); ErrVEXSuggestionNotFound when absent.

func (*VEXStore) UpsertVEXStatement added in v0.15.0

func (p *VEXStore) UpsertVEXStatement(ctx context.Context, s *models.VEXStatement) error

UpsertVEXStatement records (or replaces, whatever its source) the decision for (RepositoryID, ArtifactID, VulnID) with the source of s (an empty SourceKind is local) and fills the stored row back into s.

func (*VEXStore) UpsertVEXSuggestion added in v0.22.0

func (p *VEXStore) UpsertVEXSuggestion(ctx context.Context, s *models.VEXSuggestion) (bool, error)

UpsertVEXSuggestion stores a peer's decision, keyed by (PeerID, ArtifactID, VulnID), and fills s.ID and s.State. It reports changed when the suggestion is new or its content (status, justification, statements) changed; a changed suggestion goes back to pending and loses its decision.

type VulnStore added in v0.15.0

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

VulnStore owns vulnerability scan results, the vulnerability overview and the security findings views.

func (VulnStore) AuthCacheGeneration added in v0.15.0

func (p VulnStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (VulnStore) AuthCacheTTL added in v0.15.0

func (p VulnStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (VulnStore) BeginTx added in v0.15.0

func (p VulnStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (VulnStore) Close added in v0.15.0

func (p VulnStore) Close() error

Close writes the pending download counts and closes the database connection.

func (VulnStore) CountFileDownload added in v0.19.0

func (p VulnStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*VulnStore) CreateVulnScanResult added in v0.15.0

func (p *VulnStore) CreateVulnScanResult(ctx context.Context, result *models.VulnScanResult) error

CreateVulnScanResult creates or updates a vulnerability scan result.

func (*VulnStore) DeleteVulnScanResult added in v0.15.0

func (p *VulnStore) DeleteVulnScanResult(ctx context.Context, repoID, id string) error

DeleteVulnScanResult deletes a vuln scan result (and its owning scan job) by ID, scoped to repoID. Returns ErrVulnScanNotFound when nothing matched.

func (VulnStore) FlushDownloadCounts added in v0.19.0

func (p VulnStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (VulnStore) GetDB added in v0.15.0

func (p VulnStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*VulnStore) GetVulnScanResult added in v0.15.0

func (p *VulnStore) GetVulnScanResult(ctx context.Context, repoID, artifactID string) (*models.VulnScanResult, error)

GetVulnScanResult gets a vulnerability scan result by repo and artifact ID. scan_jobs' UNIQUE(artifact_ref_id, scan_type, scanner) allows more than one scanner (osv/trivy/grype/...) to have scanned the same artifact, so this orders by most-recently-created and takes the first row instead of letting QueryRowContext pick an arbitrary one nondeterministically.

func (*VulnStore) GetVulnScanResultByID added in v0.15.0

func (p *VulnStore) GetVulnScanResultByID(ctx context.Context, repoID, id string) (*models.VulnScanResult, error)

GetVulnScanResultByID returns the vuln scan result with the given ID scoped to repoID, or nil.

func (*VulnStore) ListSecurityFindings added in v0.15.0

func (p *VulnStore) ListSecurityFindings(ctx context.Context, params models.FindingListParams) (*models.FindingPage, error)

ListSecurityFindings returns one keyset page of the findings of every requested type, worst first (by severity, or by exploit priority with Sort priority), then newest scan, then id.

func (*VulnStore) ListVulnScanOverview added in v0.15.0

func (p *VulnStore) ListVulnScanOverview(ctx context.Context, params models.VulnScanListParams) (*models.VulnScanOverviewPage, error)

ListVulnScanOverview returns one page of vulnerability scans across all repositories, worst first. See vulnOverviewQuery.

func (*VulnStore) ListVulnScanResults added in v0.15.0

func (p *VulnStore) ListVulnScanResults(ctx context.Context, repoID string, vulnerableOnly bool) ([]*models.VulnScanResult, error)

ListVulnScanResults lists all vulnerability scan results for a repository.

func (VulnStore) Migrate added in v0.15.0

func (p VulnStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (VulnStore) Ping added in v0.15.0

func (p VulnStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (VulnStore) PoolStat added in v0.15.0

func (p VulnStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*VulnStore) QuarantineVulnArtifact added in v0.15.0

func (p *VulnStore) QuarantineVulnArtifact(ctx context.Context, repoID, artifactID string, quarantined bool) error

QuarantineVulnArtifact updates the quarantine status of a vulnerable artifact.

func (*VulnStore) RepoSecuritySummary added in v0.15.0

func (p *VulnStore) RepoSecuritySummary(ctx context.Context, repoID, packageName, version string) (*models.RepoSecuritySummary, error)

RepoSecuritySummary returns the counts-only security state of a repository, narrowed to a package (and version) when given.

func (*VulnStore) SecurityFindingsSummary added in v0.15.0

func (p *VulnStore) SecurityFindingsSummary(ctx context.Context, f models.FindingFilter) (*models.FindingsSummary, error)

SecurityFindingsSummary counts the findings of the filter's scope per type and how many of its repositories were scanned.

func (*VulnStore) SecurityHealthStats added in v0.15.0

func (p *VulnStore) SecurityHealthStats(ctx context.Context) (*models.SecurityHealthStats, error)

SecurityHealthStats returns the instance-wide scan queue and coverage numbers.

func (*VulnStore) SetVulnScanQuarantine added in v0.15.0

func (p *VulnStore) SetVulnScanQuarantine(ctx context.Context, repoID, id string, quarantined bool) error

SetVulnScanQuarantine sets the quarantined flag of exactly one vuln scan result (by ID, scoped to repoID). Returns ErrVulnScanNotFound when nothing matched.

func (*VulnStore) UpdateVulnScanResult added in v0.15.0

func (p *VulnStore) UpdateVulnScanResult(ctx context.Context, result *models.VulnScanResult) error

UpdateVulnScanResult updates a vulnerability scan result.

func (*VulnStore) VulnScanOverviewSummary added in v0.15.0

func (p *VulnStore) VulnScanOverviewSummary(ctx context.Context, repoName string) (*models.VulnScanSummary, error)

VulnScanOverviewSummary counts the overview's scans in one pass, all of them or those of one repository.

type WebhookPatch added in v0.20.0

type WebhookPatch struct {
	Name           *string
	URL            *string
	SetSecret      bool
	SecretEnc      string
	Enabled        *bool
	Events         []string
	ContentType    *string
	PayloadFormat  *string
	SSLVerify      *bool
	MaxRetries     *int
	TimeoutSeconds *int
}

WebhookPatch names the columns an edit writes; nil fields leave the stored value alone. SecretEnc is only written when SetSecret is true, an empty value clearing the signing secret.

type WebhookStore added in v0.15.0

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

WebhookStore owns webhooks and their deliveries.

func (WebhookStore) AuthCacheGeneration added in v0.15.0

func (p WebhookStore) AuthCacheGeneration() uint64

AuthCacheGeneration changes whenever a write made through this PostgresDB invalidated the auth cache. A value derived from permission data is current only while the generation read before deriving it is unchanged. It never changes while the cache is disabled (TTL 0).

func (WebhookStore) AuthCacheTTL added in v0.15.0

func (p WebhookStore) AuthCacheTTL() time.Duration

AuthCacheTTL is the configured lifetime of auth-derived cache entries (0: caching disabled). Other caches that derive from the same permission data, such as the search handler's readable-repository sets, follow it.

func (WebhookStore) BeginTx added in v0.15.0

func (p WebhookStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (*WebhookStore) ClaimPendingWebhookDeliveries added in v0.15.0

func (p *WebhookStore) ClaimPendingWebhookDeliveries(
	ctx context.Context,
	limit int,
	lease time.Duration,
) ([]*models.WebhookDelivery, error)

ClaimPendingWebhookDeliveries atomically claims up to limit due deliveries (pending, next_retry_at unset or elapsed) for lease: it pushes their next_retry_at to the end of the lease under FOR UPDATE SKIP LOCKED, so concurrent pollers on any number of server instances never receive the same row. A claimed delivery that is never completed becomes claimable again once the lease expires.

func (WebhookStore) Close added in v0.15.0

func (p WebhookStore) Close() error

Close writes the pending download counts and closes the database connection.

func (WebhookStore) CountFileDownload added in v0.19.0

func (p WebhookStore) CountFileDownload(fileID string)

CountFileDownload records one download of a package file. It never blocks on the database: the count is written by the next flush (see FlushDownloadCounts).

func (*WebhookStore) CreateWebhook added in v0.15.0

func (p *WebhookStore) CreateWebhook(ctx context.Context, wh *models.Webhook) error

CreateWebhook creates a new webhook.

func (*WebhookStore) CreateWebhookDelivery added in v0.15.0

func (p *WebhookStore) CreateWebhookDelivery(ctx context.Context, delivery *models.WebhookDelivery) error

CreateWebhookDelivery creates a new webhook delivery record.

func (*WebhookStore) DeleteWebhook added in v0.15.0

func (p *WebhookStore) DeleteWebhook(ctx context.Context, id string) error

DeleteWebhook deletes a webhook.

func (WebhookStore) FlushDownloadCounts added in v0.19.0

func (p WebhookStore) FlushDownloadCounts(ctx context.Context) error

FlushDownloadCounts writes the pending download counts, adding them to package_files.download_count. On failure the unwritten counts stay pending (merged with any recorded meanwhile) for the next flush.

func (WebhookStore) GetDB added in v0.15.0

func (p WebhookStore) GetDB() *sql.DB

GetDB returns the underlying sql.DB connection.

func (*WebhookStore) GetWebhook added in v0.15.0

func (p *WebhookStore) GetWebhook(ctx context.Context, id string) (*models.Webhook, error)

func (*WebhookStore) ListWebhookDeliveries added in v0.15.0

func (p *WebhookStore) ListWebhookDeliveries(ctx context.Context, webhookID string, limit int) ([]*models.WebhookDelivery, error)

ListWebhookDeliveries lists deliveries for a webhook.

func (*WebhookStore) ListWebhooks added in v0.15.0

func (p *WebhookStore) ListWebhooks(ctx context.Context, repoID string) ([]*models.Webhook, error)

ListWebhooks lists all webhooks for a repository (or global if repoID is empty).

func (*WebhookStore) ListWebhooksForEvent added in v0.15.0

func (p *WebhookStore) ListWebhooksForEvent(ctx context.Context, repoID, eventType string) ([]*models.Webhook, error)

ListWebhooksForEvent lists all enabled webhooks that are subscribed to an event.

func (WebhookStore) Migrate added in v0.15.0

func (p WebhookStore) Migrate(ctx context.Context) error

Migrate runs database migrations.

func (*WebhookStore) PatchWebhook added in v0.20.0

func (p *WebhookStore) PatchWebhook(ctx context.Context, id string, patch WebhookPatch) (*models.Webhook, error)

PatchWebhook writes only the columns in patch, so a concurrent edit of other columns is not reverted by a stale snapshot. It returns the updated row, or nil when the webhook does not exist.

func (WebhookStore) Ping added in v0.15.0

func (p WebhookStore) Ping(ctx context.Context) error

Ping checks if the database is accessible.

func (WebhookStore) PoolStat added in v0.15.0

func (p WebhookStore) PoolStat() *pgxpool.Stat

PoolStat reads the statistics of the shared pgx pool (for the openartifact_db_pool_* metrics). It must not be called on a backup snapshot view, which has no pool of its own.

func (*WebhookStore) UpdateWebhookDelivery added in v0.15.0

func (p *WebhookStore) UpdateWebhookDelivery(ctx context.Context, delivery *models.WebhookDelivery) error

UpdateWebhookDelivery updates a webhook delivery record.

Source Files

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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