worker

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: AGPL-3.0 Imports: 67 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 CleanupPreviewLimit = 500

CleanupPreviewLimit bounds the rows a CleanupPreview lists.

View Source
const (

	// DockerGCReportLimit bounds the entries listed in a DockerGCReport.
	DockerGCReportLimit = 1000
)

Variables

View Source
var (
	ErrRepositoryNotFound = errors.New("repository not found")
	// ErrPolicyNotFound is returned by TriggerPolicy for an unknown policy ID.
	ErrPolicyNotFound = errors.New("cleanup policy not found")
	// ErrPolicyBusy is returned when the policy is already being executed.
	ErrPolicyBusy = errors.New("cleanup policy is already running")
	// ErrCleanupStopping is returned by TriggerPolicy once the worker is shutting down.
	ErrCleanupStopping = errors.New("cleanup worker is shutting down")
)

Sentinel errors for cleanup worker.

View Source
var (
	// ErrDockerGCBusy means another run is collecting the repository.
	ErrDockerGCBusy = errors.New("docker registry garbage collection is already running for this repository")
	// ErrNotDockerRepo means GC was requested for a repository that is not a docker registry.
	ErrNotDockerRepo = errors.New("repository is not a docker repository")
	// ErrInvalidDockerGCGrace means a negative grace period was requested.
	ErrInvalidDockerGCGrace = errors.New("grace period must not be negative")
)
View Source
var ErrPackageNotFound = errors.New("package not found")

ErrPackageNotFound means no live package row has the id in the repository.

Functions

func ApkPackageDirs added in v0.13.0

func ApkPackageDirs(rows []*models.ApkPackage) map[string][]apk.Package

ApkPackageDirs groups the live package rows by directory.

func ApkRowPackage added in v0.13.0

func ApkRowPackage(row *models.ApkPackage) apk.Package

ApkRowPackage is the index entry of a stored package. Its architecture is the one of the directory (what Alpine's `apk index --rewrite-arch` writes): a noarch package lives in each arch directory, and apk fetches a package from <repo>/<arch of its index entry>/, so an A:noarch entry would send apk to a noarch directory that does not exist. The package file itself stays noarch.

func CleanupFormatSupported added in v0.8.0

func CleanupFormatSupported(format string) bool

CleanupFormatSupported reports whether the cleanup worker can run policies for repositories of the given format; the API uses it to reject policies that could never run.

func ValidDistName added in v0.8.0

func ValidDistName(name string) bool

ValidDistName reports whether name is acceptable as a Debian distribution of a group.

Types

type AIAnalysisRequest

type AIAnalysisRequest struct {
	RepositoryID    string
	ArtifactID      string
	ArtifactFormat  string
	ArtifactName    string
	ArtifactVersion string
	// ManifestText is caller-supplied plain-text content (package.json,
	// pom.xml, ...). When empty the worker extracts the manifest from the
	// stored artifact itself.
	ManifestText string
}

AIAnalysisRequest carries the context needed to analyze one artifact.

type AIAnalysisStore added in v0.15.0

type AIAnalysisStore interface {
	GetConanPackage(ctx context.Context, repoID string, key models.ConanFileKey) (*models.ConanPackage, error)
	GetRepoComponentBlob(ctx context.Context, repoID string, id string) (*models.ComponentBlob, error)
	UpsertAIAnalysis(ctx context.Context, analysis *models.AIAnalysis) error
}

AIAnalysisStore is the part of the database AIAnalysisWorker needs.

type AIAnalysisWorker

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

AIAnalysisWorker processes artifact uploads asynchronously and enriches them with AI-generated metadata (tags, summary, license status, security notes).

func NewAIAnalysisWorker

func NewAIAnalysisWorker(db AIAnalysisStore, aiClient *ai.Client, log *logger.Logger) *AIAnalysisWorker

NewAIAnalysisWorker creates a new worker. Pass nil aiClient to disable AI calls (records will be created with status "pending" for later processing). The client and the auto-analysis switch can be replaced at runtime with Configure.

func (*AIAnalysisWorker) AutoAnalyze added in v0.6.0

func (w *AIAnalysisWorker) AutoAnalyze() bool

AutoAnalyze reports whether uploads are analysed without being asked to.

func (*AIAnalysisWorker) Configure added in v0.6.0

func (w *AIAnalysisWorker) Configure(s ai.Settings)

Configure atomically replaces the model client and the auto-analysis switch. Analyses already running finish on the client they started with; every analysis that starts afterwards uses the new one.

func (*AIAnalysisWorker) Enabled added in v0.6.0

func (w *AIAnalysisWorker) Enabled() bool

Enabled reports whether a model client is configured.

func (*AIAnalysisWorker) Notify

func (w *AIAnalysisWorker) Notify(req AIAnalysisRequest)

Notify schedules an AI analysis for the given artifact (debounced).

func (*AIAnalysisWorker) NotifyUpload added in v0.6.0

func (w *AIAnalysisWorker) NotifyUpload(ref UploadRef)

NotifyUpload queues a just-uploaded package for analysis when auto-analysis is on. It never blocks the upload: the lookup of the package's ID happens on the worker goroutine, and a full queue drops the notification.

func (*AIAnalysisWorker) Start

func (w *AIAnalysisWorker) Start()

Start launches the background processing goroutine.

func (*AIAnalysisWorker) Stop

func (w *AIAnalysisWorker) Stop()

Stop gracefully shuts down the worker.

func (*AIAnalysisWorker) SyncSettings added in v0.15.0

func (w *AIAnalysisWorker) SyncSettings(ctx context.Context, r ai.SettingReader, env ai.Settings, interval time.Duration)

SyncSettings keeps the worker on the AI settings stored in the database until ctx ends: every interval it reads the effective settings (the stored ones over env, see ai.LoadSettings) and calls Configure when they differ from the ones in use. An admin saves the settings through one process, which applies them to its own worker at once; this is how every other process (replicas of the API, the worker role) follows, so disabling AI, a model change or a key rotation does not wait for a restart.

A read that fails leaves the settings in use alone: the stored ones are not known. Two processes applying a change at the same moment can leave this one on the older settings until the next interval.

func (*AIAnalysisWorker) WithBlobStore added in v0.6.0

func (w *AIAnalysisWorker) WithBlobStore(bs storage.BlobStore) *AIAnalysisWorker

WithBlobStore gives the worker access to stored artifacts so it can extract manifests itself; without it only caller-supplied manifest text works.

func (*AIAnalysisWorker) WithDebounce

func (w *AIAnalysisWorker) WithDebounce(d time.Duration) *AIAnalysisWorker

WithDebounce sets the debounce duration (default 2s).

type AIAutoAnalyzePublisher added in v0.6.0

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

AIAutoAnalyzePublisher is a webhook.Publisher that forwards every event to the wrapped publisher and, for artifact uploads, also hands the package to the AI worker. It is the single place uploads of every format are observed.

func NewAIAutoAnalyzePublisher added in v0.6.0

func NewAIAutoAnalyzePublisher(next webhook.Publisher, w *AIAnalysisWorker) *AIAutoAnalyzePublisher

NewAIAutoAnalyzePublisher wraps next (which may be nil).

func (*AIAutoAnalyzePublisher) Dispatch added in v0.6.0

func (p *AIAutoAnalyzePublisher) Dispatch(ctx context.Context, repoID, eventType string, payload map[string]any)

Dispatch implements webhook.Publisher.

type ApkMetadataStore added in v0.15.0

type ApkMetadataStore interface {
	BeginTx(ctx context.Context) (database.Transaction, error)
	GetRepositoryByID(ctx context.Context, id string) (*models.Repository, error)
	ListApkPackages(ctx context.Context, repoID string) ([]*models.ApkPackage, error)
	// contains filtered or unexported methods
}

ApkMetadataStore is the part of the database ApkMetadataWorker needs.

type ApkMetadataWorker added in v0.13.0

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

ApkMetadataWorker regenerates the signed APKINDEX.tar.gz of every branch/repo/arch directory of hosted apk repositories, through the shared coalescing RegenQueue (one running and one pending regeneration per repository).

func NewApkMetadataWorker added in v0.13.0

func NewApkMetadataWorker(
	db ApkMetadataStore,
	blobStore storage.BlobStore,
	signers ApkSignerResolver,
	log *logger.Logger,
) *ApkMetadataWorker

NewApkMetadataWorker builds the worker. signers may be nil (unsigned indexes).

func (*ApkMetadataWorker) ForwardTo added in v0.15.0

func (w *ApkMetadataWorker) ForwardTo(s *workq.Store)

ForwardTo makes NotifyStale write a worker request to s instead of scheduling the regeneration here (server.role=web); see RegenRemote.

func (*ApkMetadataWorker) NotifyStale added in v0.13.0

func (w *ApkMetadataWorker) NotifyStale(repoID string)

NotifyStale schedules a coalesced regeneration of the repository's indexes.

func (*ApkMetadataWorker) ServeFrom added in v0.15.0

func (w *ApkMetadataWorker) ServeFrom(c *workq.Consumer)

ServeFrom makes the worker regenerate what the requests claimed by c ask for.

func (*ApkMetadataWorker) Stop added in v0.13.0

func (w *ApkMetadataWorker) Stop()

Stop drains pending regenerations and waits for running ones (bounded).

func (*ApkMetadataWorker) WithDebounce added in v0.13.0

func (w *ApkMetadataWorker) WithDebounce(d time.Duration) *ApkMetadataWorker

WithDebounce sets the quiet period a notification waits for.

func (*ApkMetadataWorker) WithDrainTimeout added in v0.13.0

func (w *ApkMetadataWorker) WithDrainTimeout(d time.Duration) *ApkMetadataWorker

WithDrainTimeout sets how long Stop waits for pending regenerations.

func (*ApkMetadataWorker) WithMetrics added in v0.13.0

func (w *ApkMetadataWorker) WithMetrics(reg *metrics.Registry) *ApkMetadataWorker

WithMetrics records regeneration counts and durations in reg.

func (*ApkMetadataWorker) WithRegenLimiter added in v0.13.0

func (w *ApkMetadataWorker) WithRegenLimiter(l *RegenLimiter) *ApkMetadataWorker

WithRegenLimiter shares a concurrency limiter with the other metadata workers.

func (*ApkMetadataWorker) WithStaleHook added in v0.13.0

func (w *ApkMetadataWorker) WithStaleHook(fn func(repoID string)) *ApkMetadataWorker

WithStaleHook calls fn with the repository id on every NotifyStale: the group repositories that list it as a member regenerate their merged index.

type ApkSignerResolver added in v0.13.0

type ApkSignerResolver interface {
	SignerForRepo(ctx context.Context, repo *models.Repository) (*apk.Signer, error)
}

ApkSignerResolver finds the signer of a repository's index. A nil signer with no error means the index is served unsigned.

type AuditRetentionStats added in v0.10.0

type AuditRetentionStats struct {
	// Deleted counts the audit entries removed.
	Deleted int64
	// Batches counts the delete statements that ran, the last (short or empty)
	// one included.
	Batches int
	// Busy is set when another replica holds the retention lock; nothing was
	// done.
	Busy bool
}

AuditRetentionStats is the outcome of one retention pass.

type AuditRetentionStore added in v0.15.0

type AuditRetentionStore interface {
	GetDB() *sql.DB
}

AuditRetentionStore is the part of the database AuditRetentionWorker needs.

type AuditRetentionWorker added in v0.10.0

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

AuditRetentionWorker deletes audit entries older than audit.retentionDays, oldest first in batches of a fixed size, paced by a ticker. Replicas are excluded from each other by a Postgres advisory lock held on a pinned connection for the whole pass, so the work is done once per cycle however many replicas run. Interrupted passes lose nothing: every batch commits on its own and the next pass continues with the oldest remaining rows.

Nothing is exported before the deletion; see docs/operations/audit-retention.md.

func NewAuditRetentionWorker added in v0.10.0

func NewAuditRetentionWorker(
	db AuditRetentionStore,
	log *logger.Logger,
	retentionDays int,
	interval time.Duration,
	batch int,
) *AuditRetentionWorker

NewAuditRetentionWorker creates the worker. retentionDays is the age past which entries are deleted (0 or less keeps everything: Start and RunOnce do nothing), interval the pause between scheduled passes and batch the entries one delete statement removes. Without a database that implements database.AuditRetentionStore the worker does nothing.

func (*AuditRetentionWorker) RunOnce added in v0.10.0

RunOnce runs one retention pass: it deletes, batch by batch, every audit entry created before now minus the retention until a batch comes back short or ctx ends. A pass that finds the lock held by another replica does nothing and reports Busy. The error is non-nil only when the pass could not run to the end (lock or delete failure, cancelled ctx); entries deleted before that stay deleted and are counted in the stats.

func (*AuditRetentionWorker) Start added in v0.10.0

func (w *AuditRetentionWorker) Start()

Start runs a first pass right away and then one per interval. It does nothing when retention is off, the interval is not positive or the database has no audit retention support. Only the first call counts.

func (AuditRetentionWorker) Stop added in v0.10.0

func (l AuditRetentionWorker) Stop()

Stop cancels an in-flight pass and waits for the schedule goroutine to exit. It is idempotent and safe without Start.

func (*AuditRetentionWorker) WithMetrics added in v0.10.0

WithMetrics counts the deleted entries and stamps the last finished pass.

type AuthPurgeStore added in v0.15.0

type AuthPurgeStore interface {
	GetDB() *sql.DB
}

AuthPurgeStore is the part of the database AuthPurgeWorker needs.

type AuthPurgeWorker added in v0.2.0

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

AuthPurgeWorker periodically deletes expired sessions, long-expired or revoked API tokens (and the service accounts of project tokens) and finished webhook deliveries so those tables do not grow without bound.

func NewAuthPurgeWorker added in v0.2.0

func NewAuthPurgeWorker(db AuthPurgeStore, log *logger.Logger) *AuthPurgeWorker

func (*AuthPurgeWorker) SetWebhookDeliveryRetention added in v0.5.0

func (w *AuthPurgeWorker) SetWebhookDeliveryRetention(days int)

SetWebhookDeliveryRetention sets how many days finished webhook deliveries are kept (0: forever). Call before Start.

func (*AuthPurgeWorker) Start added in v0.2.0

func (w *AuthPurgeWorker) Start()

func (*AuthPurgeWorker) Stop added in v0.2.0

func (w *AuthPurgeWorker) Stop()

type BlobByteStore added in v0.7.0

type BlobByteStore interface {
	// Delete removes every copy of the blob, on every tier.
	Delete(ctx context.Context, sha256 string) error
	// DeleteCopy removes the copy on one backend ("" = the primary store).
	DeleteCopy(ctx context.Context, backendID, sha256 string) error
}

BlobByteStore removes blob bytes. *tiering.Store implements it.

type BlobDeletionStats added in v0.7.0

type BlobDeletionStats struct {
	// Deleted counts queued deletions whose bytes were removed.
	Deleted int
	// Kept counts queued deletions dropped without touching the bytes because
	// the blob was re-uploaded, or the copy became authoritative again.
	Kept int
	// Held counts deletions a running backup (or a concurrent newer deletion)
	// still holds back; they stay queued.
	Held int
	// Failed counts deletions whose byte removal failed; they stay queued and
	// are retried after the claim period.
	Failed int
	// Pending is the queue length after the pass.
	Pending int64
}

BlobDeletionStats is the outcome of one sweep pass.

type BlobDeletionSweeper added in v0.7.0

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

BlobDeletionSweeper removes the bytes of deleted blobs and retired tier copies that SafeDeleteBlob and the tier mover queued (database.BlobDeletion).

A deletion is carried out only when its grace period has passed and no running backup can still read the bytes (the database checks the backups' snapshot leases). Right before deleting, the sweeper takes the per-blob lock that uploaders and deleters share and checks again that the deletion is still due and that the bytes are not needed after all: a blob that was re-uploaded during the grace period (a blobs row exists again), or a copy that became the blob's placement again, is kept and the entry dropped. A copy that is already gone counts as deleted.

There is no global lock: every replica may run a sweeper, rows are claimed with FOR UPDATE SKIP LOCKED and held for a claim period, and the per-blob lock serializes the actual deletion.

func NewBlobDeletionSweeper added in v0.7.0

func NewBlobDeletionSweeper(
	db BlobDeletionSweeperStore,
	store BlobByteStore,
	log *logger.Logger,
	interval time.Duration,
	batch int,
) *BlobDeletionSweeper

NewBlobDeletionSweeper creates the sweeper. interval is the pause between scheduled passes (a non-positive interval disables the schedule; RunOnce still works) and batch the number of deletions claimed at a time. Without a database that implements database.BlobDeletionStore the sweeper does nothing.

func (*BlobDeletionSweeper) RunOnce added in v0.7.0

RunOnce runs one pass: it claims due deletions batch by batch until none is left (or ctx ends) and processes each under its blob lock. A failing deletion is logged, counted in Failed and left queued; it never aborts the pass. The error is non-nil only when the queue could not be read or ctx ended.

func (*BlobDeletionSweeper) Start added in v0.7.0

func (w *BlobDeletionSweeper) Start()

Start begins the scheduled passes. It does nothing when the interval is not positive or the database has no deletion queue. Only the first call counts.

func (BlobDeletionSweeper) Stop added in v0.7.0

func (l BlobDeletionSweeper) Stop()

Stop cancels an in-flight pass and waits for the schedule goroutine to exit. It is idempotent and safe without Start.

func (*BlobDeletionSweeper) WithMetrics added in v0.7.0

WithMetrics publishes the queue length and the swept counts.

type BlobDeletionSweeperStore added in v0.15.0

type BlobDeletionSweeperStore interface {
	BlobReferenceCount(ctx context.Context, sha256 string) (int, error)
}

BlobDeletionSweeperStore is the part of the database BlobDeletionSweeper needs.

type CleanupPreview added in v0.8.0

type CleanupPreview struct {
	// Repository is the repository the policy applies to.
	Repository string
	// Format is the repository's format.
	Format string
	// Rows is the number of package rows the run would remove (or move to the
	// trash). A version made of several files (jar and pom, sdist and wheel)
	// counts one row per file.
	Rows int
	// Bytes is the size of the blobs the rows reference (a blob shared by two
	// rows counts twice; docker tags count 0, their images are shared layers).
	Bytes int64
	// Items lists the rows, at most CleanupPreviewLimit.
	Items []CleanupPreviewItem
	// Truncated reports that Items is shorter than Rows.
	Truncated bool
}

CleanupPreview is the outcome of a dry run: what a run of the policy would remove right now, without removing anything.

type CleanupPreviewItem added in v0.8.0

type CleanupPreviewItem struct {
	ID      string
	Name    string
	Version string
}

CleanupPreviewItem is one row a run of the policy would remove.

type CleanupStore added in v0.15.0

type CleanupStore interface {
	BlobReferenceCount(ctx context.Context, sha256 string) (int, error)
	DecrementStorageUsage(ctx context.Context, repoID string, sizeBytes int64, artifactCount int) error
	DeleteStaleNixPendingNars(ctx context.Context, before time.Time, limit int) ([]models.NixPendingNar, error)
	GetCleanupPolicy(ctx context.Context, id string) (*models.CleanupPolicy, error)
	GetDB() *sql.DB
	GetRepositoryByID(ctx context.Context, id string) (*models.Repository, error)
	HardDeleteFiles(ctx context.Context, repoID string, ids []string) ([]models.FileDeletion, error)
	ListEnabledCleanupPolicies(ctx context.Context) ([]*models.CleanupPolicy, error)
	ListProjectCleanupRepositories(ctx context.Context, projectID string) ([]string, error)
	MarkPackumentStale(ctx context.Context, packageID string) error
	MarkRepoStale(ctx context.Context, repositoryID string) error
	ReconcileAllStorageUsage(ctx context.Context) (int64, error)
	UpdateCleanupPolicyRunResult(ctx context.Context, id string, deletedCount int, runErr error) error
}

CleanupStore is the part of the database CleanupWorker needs.

type CleanupWorker

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

func NewCleanupWorker

func NewCleanupWorker(db CleanupStore, blobStore storage.BlobStore, log *logger.Logger) *CleanupWorker

func (*CleanupWorker) DeletePackage added in v0.8.0

func (w *CleanupWorker) DeletePackage(
	ctx context.Context,
	repo *models.Repository,
	id string,
	guard func(DeletedPackage) error,
	actor string,
) (*DeletedPackage, error)

DeletePackage deletes the package row with the given id (an id of the package listing, GET /repositories/{name}/packages) of a repository of any format the cleanup supports, the way a cleanup policy does: into the trash when the repository keeps one, else for good with its blobs and quota, and with the format's generated metadata refreshed afterwards. guard runs on the addressed row before anything changes (the immutable-release check, which needs the request); its error is returned as is. Unlike a policy run, it applies no release-bundle or quarantine protection: an administrator chose this row. actor is the username recorded as the trash entry's deleted_by (the requester, never the cleanup policy).

func (*CleanupWorker) PreviewDraftPolicy added in v0.16.0

func (w *CleanupWorker) PreviewDraftPolicy(ctx context.Context, policy *models.CleanupPolicy) (*CleanupPreview, error)

PreviewDraftPolicy is PreviewPolicy for a policy that is not stored (the one being edited): policy.RepositoryID names the repository and the policy is and the caller has validated it. It returns ErrRepositoryNotFound for an unknown repository.

func (*CleanupWorker) PreviewPolicy added in v0.8.0

func (w *CleanupWorker) PreviewPolicy(ctx context.Context, policyID string) (*CleanupPreview, error)

PreviewPolicy reports what a run of the repository policy would remove, applying every protection a run applies (immutable releases, release bundles, quarantine, dist-tagged and newest-snapshot rows), and removes nothing. It returns ErrPolicyNotFound for an unknown policy or a project default policy (see PreviewProjectPolicy).

func (*CleanupWorker) PreviewProjectDraftPolicy added in v0.16.1

func (w *CleanupWorker) PreviewProjectDraftPolicy(ctx context.Context, policy *models.CleanupPolicy) ([]*CleanupPreview, error)

PreviewProjectDraftPolicy is PreviewProjectPolicy for a policy that is not stored (the one being edited): policy.ProjectID names the project and the caller has validated the policy.

func (*CleanupWorker) PreviewProjectPolicy added in v0.8.0

func (w *CleanupWorker) PreviewProjectPolicy(ctx context.Context, policyID string) ([]*CleanupPreview, error)

PreviewProjectPolicy reports what a run of a project default policy would remove, per repository: the policy expands over the live hosted repositories of the project that have no enabled policy of their own, exactly as a run does. Repositories of an unsupported format are left out.

func (*CleanupWorker) SetLifecycleWorkers added in v0.15.0

func (w *CleanupWorker) SetLifecycleWorkers(ws *formatlifecycle.Workers)

SetLifecycleWorkers wires the metadata workers a cleanup run needs to leave the generated metadata (rpm, deb, pacman, apk indexes, maven-metadata.xml, the npm packument, the docker registry) consistent with the rows it removed. A format with no worker in ws gets no refresh; the stale sweep recovers the formats that mark their repository stale.

func (*CleanupWorker) Start

func (w *CleanupWorker) Start()

Start begins the schedule. Only the first call counts.

func (*CleanupWorker) Stop

func (w *CleanupWorker) Stop()

Stop is idempotent and safe without Start. It also waits for the manually triggered policy runs.

func (*CleanupWorker) TriggerPolicy added in v0.2.0

func (w *CleanupWorker) TriggerPolicy(ctx context.Context, policyID string) error

TriggerPolicy starts an immediate asynchronous run of the given policy (regardless of schedule or enabled flag). It returns ErrPolicyNotFound for an unknown policy and ErrPolicyBusy if the policy is already running; the outcome is recorded in the policy's last_run_* fields.

type DebMetadataStore added in v0.15.0

type DebMetadataStore interface {
	BeginTx(ctx context.Context) (database.Transaction, error)
	GetDebianArchitecturesByDist(ctx context.Context, distID string) ([]models.DebianArchitecture, error)
	GetDebianComponentsByDist(ctx context.Context, distID string) ([]models.DebianComponent, error)
	GetDebianDistributionsByRepo(ctx context.Context, repoID string) ([]models.DebianDistribution, error)
	ListDebPackageEntries(ctx context.Context, repoID string, dist string, comp string, arch string) ([]models.DebPackageEntry, error)
	// contains filtered or unexported methods
}

DebMetadataStore is the part of the database DebMetadataWorker needs.

type DebMetadataWorker

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

func NewDebMetadataWorker

func NewDebMetadataWorker(
	db DebMetadataStore,
	blobStore storage.BlobStore,
	signers gpgresolver.Resolver,
	log *logger.Logger,
) *DebMetadataWorker

func (*DebMetadataWorker) ForwardTo added in v0.15.0

func (w *DebMetadataWorker) ForwardTo(s *workq.Store)

ForwardTo makes NotifyStale write a worker request to s instead of scheduling the regeneration here (server.role=web); see RegenRemote.

func (*DebMetadataWorker) NotifyStale

func (w *DebMetadataWorker) NotifyStale(repoID string)

NotifyStale schedules a coalesced regeneration of the repository's dists/ metadata.

func (*DebMetadataWorker) ServeFrom added in v0.15.0

func (w *DebMetadataWorker) ServeFrom(c *workq.Consumer)

ServeFrom makes the worker regenerate what the requests claimed by c ask for.

func (*DebMetadataWorker) Stop

func (w *DebMetadataWorker) Stop()

Stop drains pending regenerations and waits for running ones (bounded).

func (*DebMetadataWorker) WithDebounce added in v0.4.0

func (w *DebMetadataWorker) WithDebounce(d time.Duration) *DebMetadataWorker

func (*DebMetadataWorker) WithDrainTimeout added in v0.9.0

func (w *DebMetadataWorker) WithDrainTimeout(d time.Duration) *DebMetadataWorker

WithDrainTimeout sets how long Stop waits for pending regenerations (default 10s); `openartifact rebuild` raises it to wait for a whole rebuilt catalogue.

func (*DebMetadataWorker) WithMetrics added in v0.4.0

func (w *DebMetadataWorker) WithMetrics(reg *metrics.Registry) *DebMetadataWorker

WithMetrics records regeneration counts and durations in reg.

func (*DebMetadataWorker) WithRegenLimiter added in v0.4.0

func (w *DebMetadataWorker) WithRegenLimiter(l *RegenLimiter) *DebMetadataWorker

WithRegenLimiter shares a concurrency limiter with the other metadata workers.

func (*DebMetadataWorker) WithStaleHook added in v0.8.0

func (w *DebMetadataWorker) WithStaleHook(fn func(repoID string)) *DebMetadataWorker

WithStaleHook calls fn with the repository id on every NotifyStale: the group repositories that list it as a member regenerate their merged metadata.

type DeletedPackage added in v0.8.0

type DeletedPackage struct {
	// ID is the id the delete addressed; Kind its trash kind.
	ID   string
	Kind models.TrashKind
	// Name and Version are those of the row the id addressed.
	Name    string
	Version string
	// Rows is the number of rows removed.
	Rows int
	// Trashed reports that the rows went to the trash and not away for good.
	Trashed bool
}

DeletedPackage describes what an explicit package delete removed.

type DockerGCBlob added in v0.4.0

type DockerGCBlob struct {
	Digest string
	Size   int64
}

DockerGCBlob is a blob record reported by a GC run.

type DockerGCDB added in v0.8.0

type DockerGCDB interface {
	GetDB() *sql.DB
	ListRepositories(ctx context.Context, page, limit int, formatFilter string) ([]*models.Repository, error)
	quota.ReleaseNStore
	storage.SafeDeleteBlobStore
	database.DockerGCStore
}

DockerGCDB is the database a DockerGCWorker needs: the repository listing, the advisory lock connection and the GC store. *database.PostgresDB implements it.

type DockerGCManifest added in v0.4.0

type DockerGCManifest struct {
	Image  string
	Digest string
	Size   int64
}

DockerGCManifest is a manifest reported by a GC run.

type DockerGCOptions added in v0.4.0

type DockerGCOptions struct {
	// DryRun reports what would be deleted without deleting anything.
	DryRun bool
	// Grace is the minimum age of what may be deleted. Zero means no grace.
	Grace time.Duration
}

DockerGCOptions selects how a registry GC run behaves.

type DockerGCReport added in v0.4.0

type DockerGCReport struct {
	Repository  string
	DryRun      bool
	GracePeriod time.Duration

	// ManifestsDeleted counts the manifests deleted (or, in a dry run, that
	// would be): the untagged ones and the expired ones.
	ManifestsDeleted int
	// ManifestsExpired counts, among ManifestsDeleted, the manifests removed
	// because their quay.expires-after deadline passed, with their referrers,
	// signatures and attestations.
	ManifestsExpired int
	// BlobRefsDeleted counts the blob records of the repository deleted because
	// no manifest references them any more.
	BlobRefsDeleted int
	// BlobsFreed counts the storage objects actually removed: the ones no other
	// repository, package or manifest still referenced. In a dry run it is the
	// number of storage objects the deleted records point at, an upper bound.
	BlobsFreed int
	// BytesFreed is the size of the BlobsFreed objects.
	BytesFreed int64
	// Failures counts storage deletions that failed and were logged. The rows
	// are already gone, so the orphan collector reclaims their blobs later.
	Failures int
	// ManifestsMissingBody counts manifests whose body is absent from storage.
	// Their references are unknown, so they stay unindexed and, while they
	// exist, no blob of the repository is swept.
	ManifestsMissingBody int

	// Manifests and Blobs list the deleted entries, capped at DockerGCReportLimit.
	Manifests []DockerGCManifest
	Blobs     []DockerGCBlob
	Truncated bool
}

DockerGCReport is the outcome of one registry GC run.

type DockerGCWorker added in v0.4.0

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

DockerGCWorker deletes untagged docker manifests older than a grace period and the blobs only they referenced.

A manifest is kept when a tag points at it, when it was pushed within the grace period, or when it is tied to a kept manifest: a child of a kept index, the subject of a kept referrer, or a referrer of a kept subject. After the manifests, the repository's blob records that no manifest references and that no client has used within the grace period are deleted, and their storage via storage.SafeDeleteBlob (reference counted across repositories).

Safety against concurrent pushes: a run holds a session advisory lock so runs do not overlap; every deletion re-checks the same conditions inside a transaction that holds the repository's exclusive docker lock, which manifest pushes take shared; and recently pushed or used content is never touched.

func NewDockerGCWorker added in v0.4.0

func NewDockerGCWorker(db DockerGCDB, blobStore storage.BlobStore, log *logger.Logger, interval, grace time.Duration) *DockerGCWorker

NewDockerGCWorker creates the worker. interval is the pause between scheduled passes over all docker repositories (0 disables the schedule; RunRepo still works for on-demand runs); grace is the default minimum age.

func (*DockerGCWorker) CollectRemoved added in v0.15.0

func (w *DockerGCWorker) CollectRemoved(ctx context.Context, repo *models.Repository) error

CollectRemoved runs the garbage collection of a repository after tags were deleted from it, with the worker's default grace period. A run that is already in progress covers the removal, so it is not an error.

func (*DockerGCWorker) DefaultGrace added in v0.4.0

func (w *DockerGCWorker) DefaultGrace() time.Duration

DefaultGrace is the configured grace period, used when a run does not specify one.

func (*DockerGCWorker) RunRepo added in v0.4.0

RunRepo runs registry GC on one docker repository. It stops early, leaving a consistent state, when ctx or the worker is cancelled, or after an hour.

func (*DockerGCWorker) Start added in v0.4.0

func (w *DockerGCWorker) Start()

Start begins the scheduled passes. With a non-positive interval nothing is scheduled.

func (DockerGCWorker) Stop added in v0.4.0

func (l DockerGCWorker) Stop()

Stop cancels an in-flight pass and waits for the schedule goroutine to exit. It is idempotent and safe without Start.

type DockerUploadSweeper added in v0.5.0

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

DockerUploadSweeper deletes abandoned docker blob upload sessions: rows idle longer than the TTL together with the data they hold (a multipart upload in progress is aborted, which is what frees its parts), and the upload data no session owns any more, whatever left it behind (a cancelled or crashed push, a repository deleted with uploads in flight, a failed delete). Every replica runs it: deleting a session is one atomic statement, deleting upload data is idempotent, and a replica that keeps uploads on its own disk (the oci backend) is the only one that can sweep them, so no lock elects a single sweeper.

func NewDockerUploadSweeper added in v0.5.0

func NewDockerUploadSweeper(db any, uploads storage.UploadStore, ttl time.Duration, log *logger.Logger) *DockerUploadSweeper

NewDockerUploadSweeper builds the sweeper over the upload store of the blob store (storage.UploadsFor). A non-positive ttl, a nil upload store or a database without DockerUploadSweepStore yields a sweeper that does nothing.

func (*DockerUploadSweeper) Start added in v0.5.0

func (s *DockerUploadSweeper) Start()

Start begins the periodic sweep.

func (*DockerUploadSweeper) Stop added in v0.5.0

func (s *DockerUploadSweeper) Stop()

Stop ends the sweep loop and waits for it to exit.

func (*DockerUploadSweeper) Sweep added in v0.5.0

func (s *DockerUploadSweeper) Sweep(ctx context.Context, now time.Time)

Sweep deletes upload sessions idle since before now-ttl with their data, and the upload data untouched since then that no session owns.

type ExploitFeedsWorker added in v0.14.0

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

ExploitFeedsWorker imports the CISA KEV catalog and the FIRST EPSS scores once per interval. One replica runs an import at a time (a Postgres advisory lock on a pinned connection), and a start finds the feeds already checked within the interval (by any replica) and waits out the rest of it, so restarts do not download again. A run in which a feed failed is retried after an hour at most.

func NewExploitFeedsWorker added in v0.14.0

func NewExploitFeedsWorker(importer *exploit.Importer, store exploit.Lookup, sqlDB *sql.DB, log *logger.Logger,
	interval time.Duration) *ExploitFeedsWorker

NewExploitFeedsWorker returns a worker running importer every interval (0 or less: the worker does nothing). sqlDB pins the advisory lock; nil (test fakes) means there are no other replicas.

func (*ExploitFeedsWorker) RunOnce added in v0.14.0

RunOnce runs one import. busy is set, and nothing done, when another replica holds the lock. The error is non-nil only when the lock could not be taken; a feed that failed is in the result.

func (*ExploitFeedsWorker) Start added in v0.14.0

func (w *ExploitFeedsWorker) Start()

Start begins the schedule. Only the first call counts.

func (ExploitFeedsWorker) Stop added in v0.14.0

func (l ExploitFeedsWorker) Stop()

Stop cancels an in-flight pass and waits for the schedule goroutine to exit. It is idempotent and safe without Start.

func (*ExploitFeedsWorker) WithMetrics added in v0.14.0

func (w *ExploitFeedsWorker) WithMetrics(reg *metrics.Registry) *ExploitFeedsWorker

WithMetrics counts imports and stamps the last success of each feed.

type GroupMetadataStore added in v0.15.0

type GroupMetadataStore interface {
	BeginTx(ctx context.Context) (database.Transaction, error)
	GetDebianArchitecturesByDist(ctx context.Context, distID string) ([]models.DebianArchitecture, error)
	GetDebianComponentsByDist(ctx context.Context, distID string) ([]models.DebianComponent, error)
	GetDebianDistributionsByRepo(ctx context.Context, repoID string) ([]models.DebianDistribution, error)
	GetGroupMetadataState(ctx context.Context, groupID string) (*models.GroupMetadataState, error)
	GetRepoMetadataByPath(ctx context.Context, repositoryID string, path string) (*models.RepoMetadata, error)
	GetRepositoryByID(ctx context.Context, id string) (*models.Repository, error)
	ListApkPackages(ctx context.Context, repoID string) ([]*models.ApkPackage, error)

	ListGroupMemberRepositories(ctx context.Context, groupRepoID string) ([]*models.Repository, error)
	ListMetadataGroupsOfMember(ctx context.Context, memberRepoID string) ([]string, error)
	ListPacmanFileLists(ctx context.Context, repoID string) (map[string]string, error)
	ListPacmanPackages(ctx context.Context, repoID string) ([]*models.PacmanPackage, error)
	ListStaleMetadataGroups(ctx context.Context) ([]string, error)
	MarkGroupMetadataStale(ctx context.Context, groupID string) error
	// contains filtered or unexported methods
}

GroupMetadataStore is the part of the database GroupMetadataWorker needs.

type GroupMetadataWorker added in v0.8.0

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

GroupMetadataWorker generates the metadata of apk, deb, pacman and rpm group repositories: the Release/Packages indexes, repodata, APKINDEX or databases a client needs, merged across the group's hosted and proxy members in member order, plus the table of which member owns which file so downloads are served from the member whose checksum the index lists.

The result is stored in the group's own repository_metadata rows. It is regenerated, through a coalescing queue, whenever a member (or the group) changes (NotifyStale, NotifyMemberChanged), and refreshed in the background once a proxy member's cached upstream metadata may have changed.

func NewGroupMetadataWorker added in v0.8.0

func NewGroupMetadataWorker(
	db GroupMetadataStore,
	blobStore storage.BlobStore,
	opener MemberOpener,
	rpm RPMPackageLoader,
	signers gpgresolver.Resolver,
	log *logger.Logger,
) *GroupMetadataWorker

NewGroupMetadataWorker creates the worker. signers resolves the key that signs each group's metadata (nil, or a nil result, for an unsigned group); it is asked per generation so a key change takes effect.

func (*GroupMetadataWorker) ForwardTo added in v0.15.0

func (w *GroupMetadataWorker) ForwardTo(s *workq.Store)

ForwardTo makes NotifyStale and Refresh write a worker request to s instead of scheduling the regeneration here (server.role=web); see RegenRemote.

func (*GroupMetadataWorker) Generate added in v0.8.0

func (w *GroupMetadataWorker) Generate(ctx context.Context, groupID, hint string, readable []string) error

Generate synchronously generates the metadata of the group, waiting for a generation another process runs. hint is what a client asked for that the group may not serve yet: a Debian distribution, or a pacman architecture. group.ErrDistNotFound is returned when no member has it.

readable are the IDs of the members the caller may read. The metadata a caller is served lists only those members' packages: when they are not all of the group's members, it is generated (and signed) as a variant of its own, stored under Scope(readable), and dropped whenever the group is regenerated.

func (*GroupMetadataWorker) NotifyMemberChanged added in v0.8.0

func (w *GroupMetadataWorker) NotifyMemberChanged(repoID string)

NotifyMemberChanged marks every deb, pacman or rpm group that lists repoID as a member stale. It is the hook of the hosted workers' NotifyStale: uploads, deletes, trash and restores of a member all end up there.

func (*GroupMetadataWorker) NotifyStale added in v0.8.0

func (w *GroupMetadataWorker) NotifyStale(groupID string)

NotifyStale records that the group's metadata is out of date and schedules a coalesced regeneration.

func (*GroupMetadataWorker) Refresh added in v0.8.0

func (w *GroupMetadataWorker) Refresh(groupID string)

Refresh schedules a regeneration unless one is already waiting or running.

func (*GroupMetadataWorker) RegenerateStale added in v0.8.0

func (w *GroupMetadataWorker) RegenerateStale(ctx context.Context)

RegenerateStale schedules every group whose metadata is stale or was never generated; it runs once at startup (a restored backup has no generated group metadata, a migration may invalidate it).

func (*GroupMetadataWorker) Scope added in v0.8.0

func (w *GroupMetadataWorker) Scope(ctx context.Context, groupID string, readable []string) (string, bool, error)

Scope returns the path prefix under which the metadata for a caller who can read the members with the given IDs is stored: empty when that is every member the group lists (the common case, one shared index), a per-subset prefix otherwise. ok is false when the caller can read none of them.

func (*GroupMetadataWorker) ServeFrom added in v0.15.0

func (w *GroupMetadataWorker) ServeFrom(c *workq.Consumer)

ServeFrom makes the worker regenerate what the requests claimed by c ask for.

func (*GroupMetadataWorker) Stop added in v0.8.0

func (w *GroupMetadataWorker) Stop()

Stop drains pending regenerations and waits for running ones (bounded).

func (*GroupMetadataWorker) WithApkSigners added in v0.13.0

func (w *GroupMetadataWorker) WithApkSigners(signers ApkSignerResolver) *GroupMetadataWorker

WithApkSigners enables apk groups' signed indexes: signers resolves the key of each group (an apk key, not a GPG one).

func (*GroupMetadataWorker) WithDebounce added in v0.8.0

WithDebounce sets the coalescing delay of NotifyStale.

func (*GroupMetadataWorker) WithMetrics added in v0.8.0

WithMetrics records regeneration counts and durations in reg.

func (*GroupMetadataWorker) WithRegenLimiter added in v0.8.0

func (w *GroupMetadataWorker) WithRegenLimiter(l *RegenLimiter) *GroupMetadataWorker

WithRegenLimiter shares a concurrency limiter with the other metadata workers.

type MavenMetadataStore added in v0.15.0

type MavenMetadataStore interface {
	BlobReferenceCount(ctx context.Context, sha256 string) (int, error)
	GetDB() *sql.DB
	GetRepoMetadataByPath(ctx context.Context, repositoryID string, path string) (*models.RepoMetadata, error)
	ListMavenGARefs(ctx context.Context, repoID string, groupID string, artifactID string) (*models.MavenGARefs, error)
	UpsertRepoMetadata(ctx context.Context, meta *models.RepoMetadata) error
}

MavenMetadataStore is the part of the database MavenMetadataWorker needs.

type MavenMetadataWorker

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

func NewMavenMetadataWorker

func NewMavenMetadataWorker(
	db MavenMetadataStore,
	blobStore storage.BlobStore,
	sqlDB *sql.DB,
	log *logger.Logger,
	reg *metrics.Registry,
) *MavenMetadataWorker

func (*MavenMetadataWorker) ForwardTo added in v0.15.0

func (w *MavenMetadataWorker) ForwardTo(s *workq.Store)

ForwardTo makes NotifyStale write a worker request to s instead of scheduling the regeneration here (server.role=web); see RegenRemote.

func (*MavenMetadataWorker) NotifyStale

func (w *MavenMetadataWorker) NotifyStale(repoID, groupID, artifactID string)

NotifyStale schedules a coalesced regeneration of the artifact's maven-metadata.xml.

func (*MavenMetadataWorker) ServeFrom added in v0.15.0

func (w *MavenMetadataWorker) ServeFrom(c *workq.Consumer)

ServeFrom makes the worker regenerate what the requests claimed by c ask for.

func (*MavenMetadataWorker) Stop

func (w *MavenMetadataWorker) Stop()

Stop drains pending regenerations and waits for running ones (bounded).

func (*MavenMetadataWorker) WithDebounce

func (*MavenMetadataWorker) WithDrainTimeout added in v0.9.0

func (w *MavenMetadataWorker) WithDrainTimeout(d time.Duration) *MavenMetadataWorker

WithDrainTimeout sets how long Stop waits for pending regenerations (default 10s); `openartifact rebuild` raises it to wait for a whole rebuilt catalogue.

func (*MavenMetadataWorker) WithRegenLimiter added in v0.4.0

func (w *MavenMetadataWorker) WithRegenLimiter(l *RegenLimiter) *MavenMetadataWorker

WithRegenLimiter shares a concurrency limiter with the other metadata workers.

type MemberOpener added in v0.8.0

type MemberOpener interface {
	Open(ctx context.Context, repo *models.Repository, relPath string) (io.ReadCloser, error)
}

MemberOpener reads files of a proxy member as the proxy serves them (proxy.Service).

type NPMMetadataStore added in v0.15.0

type NPMMetadataStore interface {
	GetNPMVersionStates(ctx context.Context, packageID string) ([]models.NPMVersionState, error)
	UpdateNPMPackageLatestVersion(ctx context.Context, packageID string, latestVersion string) error
}

NPMMetadataStore is the part of the database NPMMetadataWorker needs.

type NPMMetadataWorker

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

func NewNPMMetadataWorker

func NewNPMMetadataWorker(db NPMMetadataStore, log *logger.Logger, sqlDB *sql.DB, reg *metrics.Registry) *NPMMetadataWorker

func (*NPMMetadataWorker) ForwardTo added in v0.15.0

func (w *NPMMetadataWorker) ForwardTo(s *workq.Store)

ForwardTo makes NotifyStale write a worker request to s instead of scheduling the regeneration here (server.role=web); see RegenRemote.

func (*NPMMetadataWorker) NotifyStale

func (w *NPMMetadataWorker) NotifyStale(packageID string)

NotifyStale schedules a coalesced regeneration of the package's denormalized metadata.

func (*NPMMetadataWorker) ServeFrom added in v0.15.0

func (w *NPMMetadataWorker) ServeFrom(c *workq.Consumer)

ServeFrom makes the worker regenerate what the requests claimed by c ask for.

func (*NPMMetadataWorker) Stop

func (w *NPMMetadataWorker) Stop()

Stop drains pending regenerations and waits for running ones (bounded).

func (*NPMMetadataWorker) WithDebounce

func (w *NPMMetadataWorker) WithDebounce(d time.Duration) *NPMMetadataWorker

func (*NPMMetadataWorker) WithDrainTimeout added in v0.9.0

func (w *NPMMetadataWorker) WithDrainTimeout(d time.Duration) *NPMMetadataWorker

WithDrainTimeout sets how long Stop waits for pending regenerations (default 10s); `openartifact rebuild` raises it to wait for a whole rebuilt catalogue.

func (*NPMMetadataWorker) WithRegenLimiter added in v0.4.0

func (w *NPMMetadataWorker) WithRegenLimiter(l *RegenLimiter) *NPMMetadataWorker

WithRegenLimiter shares a concurrency limiter with the other metadata workers.

type OSVMirrorStats added in v0.14.0

type OSVMirrorStats struct {
	// Imported, Unchanged and Failed count the ecosystems by import outcome.
	Imported  int
	Unchanged int
	Failed    int
	// Rematch is the re-match outcome by OSV ecosystem.
	Rematch map[string]OSVRematchStats
	// Busy is set when another replica holds the lock; nothing was done.
	Busy bool
}

OSVMirrorStats is the outcome of one pass.

type OSVMirrorStore added in v0.15.0

type OSVMirrorStore interface {
	GetDB() *sql.DB
	GetRepositoryByID(ctx context.Context, id string) (*models.Repository, error)
}

OSVMirrorStore is the part of the database OSVMirrorWorker needs.

type OSVMirrorWorker added in v0.14.0

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

OSVMirrorWorker keeps the local OSV mirror current and matches the stored packages against it: once per interval it imports the export of every configured ecosystem (a conditional download, incremental by `modified`), then re-matches the package versions of hosted repositories and of the proxy cache against the advisories that changed. Findings are created, updated or closed (a withdrawn advisory); a new finding raises the vulnerability.new webhook and an audit entry. The findings are stored like those of a manual osv scan, so the security inbox, VEX, export and the policies read them unchanged; the worker never touches their quarantine flag.

Replicas are excluded from each other by a Postgres advisory lock held on a pinned connection for the whole pass. A pass is resumable: the high-water mark moves only after an import is applied, and a re-match a crash cut short is flagged in the database and redone in full by the next pass.

func NewOSVMirrorWorker added in v0.14.0

func NewOSVMirrorWorker(
	db OSVMirrorStore, importer *osv.Importer, ecosystems []string, log *logger.Logger, interval time.Duration,
) *OSVMirrorWorker

NewOSVMirrorWorker creates the worker for the given OSV ecosystems. A non-positive interval disables the schedule (RunOnce still works). Without a database that implements database.OSVMirror the worker does nothing.

func (*OSVMirrorWorker) RunOnce added in v0.14.0

func (w *OSVMirrorWorker) RunOnce(ctx context.Context) (OSVMirrorStats, error)

RunOnce runs one pass: it imports every configured ecosystem, then re-matches the stored packages against what changed. A failing ecosystem is recorded in its state and counted; the others still run. The error is non-nil only when the pass could not run to the end (lock failure, cancelled ctx, a re-match that failed).

func (*OSVMirrorWorker) SetPublisher added in v0.14.0

func (w *OSVMirrorWorker) SetPublisher(p webhook.Publisher)

SetPublisher wires the webhook publisher for vulnerability.new events. It must be called before Start.

func (*OSVMirrorWorker) Start added in v0.14.0

func (w *OSVMirrorWorker) Start()

Start begins the scheduled passes: the first right away, then one per interval. Only the first call counts.

func (OSVMirrorWorker) Stop added in v0.14.0

func (l OSVMirrorWorker) Stop()

Stop cancels an in-flight pass and waits for the schedule goroutine to exit. It is idempotent and safe without Start.

func (*OSVMirrorWorker) WithMetrics added in v0.14.0

func (w *OSVMirrorWorker) WithMetrics(reg *metrics.Registry) *OSVMirrorWorker

WithMetrics records the import and re-match metrics in reg.

type OSVRematchStats added in v0.14.0

type OSVRematchStats struct {
	// Evaluated is the number of package versions matched against the mirror.
	Evaluated int
	// Detected counts new advisory findings, Resolved findings that ended
	// (withdrawn or fixed in the data) and Updated findings whose data changed.
	Detected int
	Resolved int
	Updated  int
	// Silent is set for the first import of an ecosystem: it creates the
	// findings without raising events, so enabling the mirror on an instance
	// full of packages does not flood the webhooks.
	Silent bool
	// Started is when the re-match began and Took how long it ran.
	Started time.Time
	Took    time.Duration
}

OSVRematchStats counts what the re-match of one ecosystem did.

type PacmanMetadataStore added in v0.15.0

type PacmanMetadataStore interface {
	BeginTx(ctx context.Context) (database.Transaction, error)
	ListPacmanFileLists(ctx context.Context, repoID string) (map[string]string, error)
	ListPacmanPackages(ctx context.Context, repoID string) ([]*models.PacmanPackage, error)
	ListPacmanPackagesWithoutFileList(ctx context.Context, repoID string) ([]*models.PacmanPackage, error)
	SetPacmanFileList(ctx context.Context, repoID string, id string, fileList string) error
	SetPacmanSignature(ctx context.Context, repoID string, id string, signature string, source string, key string) error
	// contains filtered or unexported methods
}

PacmanMetadataStore is the part of the database PacmanMetadataWorker needs.

type PacmanMetadataWorker added in v0.13.0

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

PacmanMetadataWorker regenerates the pacman databases of hosted pacman repositories: for each architecture directory the "db" and "files" archives (repo-add layout), signed with the repository key, and the public key. It also signs, with the same key, the packages the uploader did not sign. Runs are coalesced by the regeneration queue.

func NewPacmanMetadataWorker added in v0.13.0

func NewPacmanMetadataWorker(
	db PacmanMetadataStore,
	blobStore storage.BlobStore,
	signers gpgresolver.Resolver,
	log *logger.Logger,
) *PacmanMetadataWorker

NewPacmanMetadataWorker creates the worker.

func (*PacmanMetadataWorker) ForwardTo added in v0.15.0

func (w *PacmanMetadataWorker) ForwardTo(s *workq.Store)

ForwardTo makes NotifyStale write a worker request to s instead of scheduling the regeneration here (server.role=web); see RegenRemote.

func (*PacmanMetadataWorker) NotifyStale added in v0.13.0

func (w *PacmanMetadataWorker) NotifyStale(repoID string)

NotifyStale schedules a coalesced regeneration of the repository's databases.

func (*PacmanMetadataWorker) ServeFrom added in v0.15.0

func (w *PacmanMetadataWorker) ServeFrom(c *workq.Consumer)

ServeFrom makes the worker regenerate what the requests claimed by c ask for.

func (*PacmanMetadataWorker) Stop added in v0.13.0

func (w *PacmanMetadataWorker) Stop()

Stop drains pending regenerations and waits for running ones (bounded).

func (*PacmanMetadataWorker) WithDebounce added in v0.13.0

WithDebounce sets how long a burst of uploads is coalesced.

func (*PacmanMetadataWorker) WithDrainTimeout added in v0.13.0

func (w *PacmanMetadataWorker) WithDrainTimeout(d time.Duration) *PacmanMetadataWorker

WithDrainTimeout sets how long Stop waits for pending regenerations.

func (*PacmanMetadataWorker) WithMetrics added in v0.13.0

WithMetrics records regeneration counts and durations in reg.

func (*PacmanMetadataWorker) WithRegenLimiter added in v0.13.0

func (w *PacmanMetadataWorker) WithRegenLimiter(l *RegenLimiter) *PacmanMetadataWorker

WithRegenLimiter shares a concurrency limiter with the other metadata workers.

func (*PacmanMetadataWorker) WithStaleHook added in v0.13.0

func (w *PacmanMetadataWorker) WithStaleHook(fn func(repoID string)) *PacmanMetadataWorker

WithStaleHook calls fn with the repository id on every NotifyStale: the group repositories that list it as a member regenerate their merged databases.

type PresignedUploadStore added in v0.15.0

type PresignedUploadStore interface {
	DeletePresignedUpload(ctx context.Context, id string) error
	ExistingPresignedUploadIDs(ctx context.Context, ids []string) ([]string, error)
	ListExpiredPresignedUploads(ctx context.Context, limit int) ([]string, error)
}

PresignedUploadStore is the part of the database PresignedUploadWorker needs.

type PresignedUploadWorker added in v0.5.0

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

PresignedUploadWorker expires presigned uploads that were never completed: it deletes their staging object and their database row once the complete deadline (URL expiry plus grace) has passed, so abandoned uploads do not accumulate in the bucket. It also sweeps the staging prefix for objects that have no row at all (a client re-PUT to a still-valid URL after its upload was cleaned up or rejected, a repository deleted with uploads in flight) once they are older than any URL could still be valid.

func NewPresignedUploadWorker added in v0.5.0

func NewPresignedUploadWorker(
	db PresignedUploadStore,
	blobStore storage.BlobStore,
	urlTTL time.Duration,
	log *logger.Logger,
) *PresignedUploadWorker

NewPresignedUploadWorker builds the worker. urlTTL is the upload URL lifetime the server signs with; staging objects without a row are only deleted once they are older than that plus the complete grace. A blobStore that cannot stage uploads yields a worker that only removes the rows.

func (*PresignedUploadWorker) Start added in v0.5.0

func (w *PresignedUploadWorker) Start()

Start launches the sweep loop.

func (*PresignedUploadWorker) Stop added in v0.5.0

func (w *PresignedUploadWorker) Stop()

Stop ends the loop and waits for the in-flight sweep.

func (*PresignedUploadWorker) Sweep added in v0.5.0

func (w *PresignedUploadWorker) Sweep(ctx context.Context) int

Sweep removes every expired upload (in batches) and every orphaned staging object, and returns how many it removed. A failure on one leaves it for the next sweep.

type ProxyCacheStore added in v0.15.0

type ProxyCacheStore interface {
	BlobReferenceCount(ctx context.Context, sha256 string) (int, error)
	DeleteExpiredProxyCacheEntries(ctx context.Context) (int64, error)
	GetDB() *sql.DB
}

ProxyCacheStore is the part of the database ProxyCacheWorker needs.

type ProxyCacheWorker

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

func NewProxyCacheWorker

func NewProxyCacheWorker(db ProxyCacheStore, blobStore storage.BlobStore, log *logger.Logger) *ProxyCacheWorker

NewProxyCacheWorker creates the eviction worker. blobStore may be nil, in which case only database rows are evicted.

func (*ProxyCacheWorker) Start

func (w *ProxyCacheWorker) Start()

func (*ProxyCacheWorker) Stop

func (w *ProxyCacheWorker) Stop()

type PurgeStats added in v0.5.0

type PurgeStats struct {
	// Purged counts the items (repositories included) removed from the database.
	Purged int
	// Repositories counts the repositories among Purged.
	Repositories int
	// Failed counts items whose purge failed (a repository still referenced by
	// a release bundle, a database error). They stay in the trash and are
	// retried by the next pass.
	Failed int
	// BlobErrors counts blobs of purged items that could not be freed. Their
	// rows are gone, so the orphan collector reclaims them later.
	BlobErrors int
	// OrphansRemoved counts the blobs removed by the orphan sweep that closes
	// a pass which purged something.
	OrphansRemoved int
	// Busy is set when another replica holds the purge lock; nothing was done.
	Busy bool
	// Capped is set when the pass stopped at the per-pass item cap; more
	// expired items may be waiting.
	Capped bool
}

PurgeStats is the outcome of one purge pass.

type RPMPackageLoader added in v0.8.0

type RPMPackageLoader interface {
	PackagesForMetadata(ctx context.Context, repoID string) ([]pkgrpm.Package, error)
}

RPMPackageLoader returns every package of a hosted rpm repository with the data its metadata needs (RPMetadataWorker.PackagesForMetadata).

type RPMetadataStore added in v0.15.0

type RPMetadataStore interface {
	BeginTx(ctx context.Context) (database.Transaction, error)
	GetRepoMetadataByPath(ctx context.Context, repositoryID string, path string) (*models.RepoMetadata, error)
	ListRpmPackagesForMetadata(ctx context.Context, repoID string) ([]rpmextra.Stored, error)
	UpdateRpmPackageExtra(ctx context.Context, repoID string, sha256 string, extra []byte) error
	// contains filtered or unexported methods
}

RPMetadataStore is the part of the database RPMetadataWorker needs.

type RPMetadataWorker

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

func NewRPMetadataWorker

func NewRPMetadataWorker(
	db RPMetadataStore,
	blobStore storage.BlobStore,
	signers gpgresolver.Resolver,
	log *logger.Logger,
	reg *metrics.Registry,
) *RPMetadataWorker

func (*RPMetadataWorker) ForwardTo added in v0.15.0

func (w *RPMetadataWorker) ForwardTo(s *workq.Store)

ForwardTo makes NotifyStale write a worker request to s instead of scheduling the regeneration here (server.role=web); see RegenRemote.

func (*RPMetadataWorker) NotifyStale

func (w *RPMetadataWorker) NotifyStale(repoID string)

NotifyStale schedules a coalesced regeneration of the repository's repodata.

func (*RPMetadataWorker) PackagesForMetadata added in v0.8.0

func (w *RPMetadataWorker) PackagesForMetadata(ctx context.Context, repoID string) ([]rpm.Package, error)

PackagesForMetadata returns every package of the repository with the data its metadata needs, completing rows stored by older versions from their blobs.

func (*RPMetadataWorker) Regenerate added in v0.2.0

func (w *RPMetadataWorker) Regenerate(ctx context.Context, repoID string) error

Regenerate synchronously rebuilds the repository's RPM metadata, including writing new metadata blobs and reclaiming superseded ones. NotifyStale is the debounced asynchronous entry point.

func (*RPMetadataWorker) RegenerateStale added in v0.4.0

func (w *RPMetadataWorker) RegenerateStale(ctx context.Context)

RegenerateStale regenerates every RPM repository flagged metadata_stale; it runs once at startup so migrations that invalidate metadata take effect without waiting for an upload.

func (*RPMetadataWorker) ServeFrom added in v0.15.0

func (w *RPMetadataWorker) ServeFrom(c *workq.Consumer)

ServeFrom makes the worker regenerate what the requests claimed by c ask for.

func (*RPMetadataWorker) Stop

func (w *RPMetadataWorker) Stop()

Stop drains pending regenerations and waits for running ones (bounded).

func (*RPMetadataWorker) WithDebounce added in v0.4.0

func (w *RPMetadataWorker) WithDebounce(d time.Duration) *RPMetadataWorker

func (*RPMetadataWorker) WithDrainTimeout added in v0.9.0

func (w *RPMetadataWorker) WithDrainTimeout(d time.Duration) *RPMetadataWorker

WithDrainTimeout sets how long Stop waits for pending regenerations (default 10s); `openartifact rebuild` raises it to wait for a whole rebuilt catalogue.

func (*RPMetadataWorker) WithRegenLimiter added in v0.4.0

func (w *RPMetadataWorker) WithRegenLimiter(l *RegenLimiter) *RPMetadataWorker

WithRegenLimiter shares a concurrency limiter with the other metadata workers.

func (*RPMetadataWorker) WithStaleHook added in v0.8.0

func (w *RPMetadataWorker) WithStaleHook(fn func(repoID string)) *RPMetadataWorker

WithStaleHook calls fn with the repository id on every NotifyStale: the group repositories that list it as a member regenerate their merged metadata.

type RegenLimiter added in v0.4.0

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

RegenLimiter caps how many regenerations run at once. Share one limiter between workers (WithRegenLimiter) so every format together respects a single cap; a worker without one gets a private limiter.

func NewRegenLimiter added in v0.4.0

func NewRegenLimiter(n int) *RegenLimiter

NewRegenLimiter returns a limiter allowing n concurrent regenerations; n < 1 selects the default (4).

type RegenRemote added in v0.15.0

type RegenRemote interface {
	ForwardTo(s *workq.Store)
	ServeFrom(c *workq.Consumer)
}

RegenRemote is a metadata worker that can hand its regenerations to a worker process (server.role): a web process calls ForwardTo, so NotifyStale writes a request to the database instead of scheduling the regeneration in memory, and a process that runs the workers calls ServeFrom, so the requests it claims are scheduled on this worker.

type RepoStatsPass added in v0.19.0

type RepoStatsPass struct {
	// Repositories counts the repositories whose figures were recomputed.
	Repositories int
	// Busy is set when another replica holds the lock; nothing was done.
	Busy bool
}

RepoStatsPass is the outcome of one pass of the repo stats worker.

type RepoStatsStore added in v0.19.0

type RepoStatsStore interface {
	GetDB() *sql.DB
}

RepoStatsStore is the part of the database RepoStatsWorker needs.

type RepoStatsWorker added in v0.19.0

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

RepoStatsWorker keeps repo_stats, the per-repository package count, newest publication and security counts of GET /api/v1/repositories, up to date: it recomputes the figures of the repositories a write marked in repo_stats_dirty, and of those whose figures are missing or older than an hour. The repository list reads the stored figures, so it lags the data by about the interval. Replicas are excluded from each other by a Postgres advisory lock held on a pinned connection for the pass; a pass interrupted at any point loses no mark (each batch claims its marks in the transaction that stores its figures).

func NewRepoStatsWorker added in v0.19.0

func NewRepoStatsWorker(db RepoStatsStore, log *logger.Logger, interval time.Duration) *RepoStatsWorker

NewRepoStatsWorker creates the worker, which runs a pass at Start and then one per interval. Without a database that implements database.RepoStatsReconciler, or with a non-positive interval, it does nothing.

func (*RepoStatsWorker) RunOnce added in v0.19.0

func (w *RepoStatsWorker) RunOnce(ctx context.Context) (RepoStatsPass, error)

RunOnce runs one pass: batch after batch, it recomputes the marked and drifted repositories until a batch comes back short or ctx ends. A pass that finds the lock held by another replica does nothing and reports Busy. The error is non-nil only when the pass could not run to the end; the batches that committed stay stored.

func (*RepoStatsWorker) Start added in v0.19.0

func (w *RepoStatsWorker) Start()

Start runs a first pass right away, so a freshly migrated database is filled in without waiting, and then one per interval.

func (RepoStatsWorker) Stop added in v0.19.0

func (l RepoStatsWorker) Stop()

Stop cancels an in-flight pass and waits for the schedule goroutine to exit. It is idempotent and safe without Start.

type TierMoverWorker added in v0.7.0

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

TierMoverWorker schedules tiering.Engine passes: every interval, and on demand through Trigger. A pass holds a Postgres advisory lock on a pinned connection, so with several replicas exactly one moves blobs at a time; the engine itself is crash-safe and resumable (see docs/operations/storage-tiering.md), so killing the process mid-pass loses nothing.

func NewTierMoverWorker added in v0.7.0

func NewTierMoverWorker(engine TierPassRunner, sqlDB *sql.DB, log *logger.Logger, interval time.Duration, enabled bool) *TierMoverWorker

NewTierMoverWorker creates the worker. sqlDB is the pool the pinned lock connection comes from (nil means no other replicas to exclude). When enabled is false the worker never moves anything and Trigger reports false.

func (*TierMoverWorker) RunOnce added in v0.7.0

RunOnce runs one pass under the cluster lock. busy is true when another replica holds the lock (nothing was done).

func (*TierMoverWorker) Start added in v0.7.0

func (w *TierMoverWorker) Start()

Start begins the schedule. Only the first call counts.

func (*TierMoverWorker) Status added in v0.7.0

func (w *TierMoverWorker) Status() tiering.RunnerStatus

Status reports the worker's state.

func (TierMoverWorker) Stop added in v0.7.0

func (l TierMoverWorker) Stop()

Stop cancels an in-flight pass and waits for the schedule goroutine to exit. It is idempotent and safe without Start.

func (*TierMoverWorker) Trigger added in v0.7.0

func (w *TierMoverWorker) Trigger() bool

Trigger queues an immediate pass. It reports false when the worker is disabled or a pass is already running with another one queued behind it.

type TierPassRunner added in v0.7.0

type TierPassRunner interface {
	RunPass(ctx context.Context) (tiering.PassStats, error)
}

TierPassRunner runs one mover pass; *tiering.Engine implements it.

type TrashPurgeStore added in v0.15.0

type TrashPurgeStore interface {
	BlobReferenceCount(ctx context.Context, sha256 string) (int, error)
	DecrementStorageUsage(ctx context.Context, repoID string, sizeBytes int64, artifactCount int) error
	GetDB() *sql.DB
}

TrashPurgeStore is the part of the database TrashPurgeWorker needs.

type TrashPurgeWorker added in v0.5.0

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

TrashPurgeWorker permanently removes soft-deleted items (and repositories) whose retention window has passed: it purges the rows, frees their blobs via storage.SafeDeleteBlob (which keeps blobs other rows or repositories still reference), releases quota, and records the audit event and webhook.

Every pass is resumable and idempotent. The database purge commits first; a crash before the blobs are freed leaves unreferenced blobs that the orphan collector (this worker's closing sweep, or the cleanup worker) reclaims, and quota counters a crash left off are corrected by the periodic reconcile. Replicas are excluded from each other by a Postgres advisory lock held on a pinned connection for the whole pass.

func NewTrashPurgeWorker added in v0.5.0

func NewTrashPurgeWorker(db TrashPurgeStore, blobStore storage.BlobStore, log *logger.Logger, interval time.Duration) *TrashPurgeWorker

NewTrashPurgeWorker creates the worker. interval is the pause between scheduled passes; a non-positive interval disables the schedule (RunOnce still works). Without a database that implements database.TrashOps the worker does nothing.

func (*TrashPurgeWorker) RunOnce added in v0.5.0

func (w *TrashPurgeWorker) RunOnce(ctx context.Context) (PurgeStats, error)

RunOnce runs one purge pass: it removes every item whose retention has passed (at most trashPurgeMaxItems) and, when it removed anything, sweeps orphaned blobs. A pass that finds the purge lock held by another replica does nothing and reports Busy. A failing item is logged, counted in Failed and skipped; it never aborts the pass. The error is non-nil only when the pass could not run to the end (lock or listing failure, cancelled ctx).

func (*TrashPurgeWorker) SetPublisher added in v0.5.0

func (w *TrashPurgeWorker) SetPublisher(p webhook.Publisher)

SetPublisher wires the webhook publisher for artifact.purged and repository.purged events. It must be called before Start.

A purged repository's own webhooks are removed with it, so only global webhooks (those not tied to a repository) receive repository.purged.

func (*TrashPurgeWorker) Start added in v0.5.0

func (w *TrashPurgeWorker) Start()

Start begins the scheduled passes. It does nothing when the interval is not positive or the database has no trash support. Only the first call counts.

func (TrashPurgeWorker) Stop added in v0.5.0

func (l TrashPurgeWorker) Stop()

Stop cancels an in-flight pass and waits for the schedule goroutine to exit. It is idempotent and safe without Start.

func (*TrashPurgeWorker) WithMetrics added in v0.5.0

func (w *TrashPurgeWorker) WithMetrics(reg *metrics.Registry) *TrashPurgeWorker

WithMetrics counts purged items in reg.TrashPurgedTotal.

type UploadRef added in v0.6.0

type UploadRef struct {
	RepositoryID string
	Format       string
	Name         string
	Version      string
	Path         string
	SHA256       string
}

UploadRef identifies a package an upload event announced; the worker finds the package's row IDs itself.

type VEXFeedLister added in v0.22.0

type VEXFeedLister interface {
	ListVEXFeeds(ctx context.Context) ([]*models.VEXFeed, error)
}

VEXFeedLister lists the configured vendor VEX feeds.

type VEXFeedSyncer added in v0.22.0

type VEXFeedSyncer interface {
	SyncFeed(ctx context.Context, feedID string) (models.VEXFeedSyncResult, error)
	ApplyFeeds(ctx context.Context) error
}

VEXFeedSyncer syncs and materializes the vendor VEX feeds (vexsync.Service).

type VEXFeedsWorker added in v0.22.0

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

VEXFeedsWorker syncs every enabled vendor VEX feed once per its interval and rematerializes the statements of every feed hourly. Each feed is synced under its own advisory lock (taken by the syncer), so replicas share the work and never sync one feed twice at once; the due times are read from the feeds, so a restart does not sync again.

func NewVEXFeedsWorker added in v0.22.0

func NewVEXFeedsWorker(syncer VEXFeedSyncer, feeds VEXFeedLister, log *logger.Logger) *VEXFeedsWorker

NewVEXFeedsWorker returns the worker.

func (*VEXFeedsWorker) RunOnce added in v0.22.0

func (w *VEXFeedsWorker) RunOnce(ctx context.Context) error

RunOnce syncs the feeds that are due, then rematerializes every feed when the last materialization is an hour old. A feed whose sync fails does not stop the others.

func (*VEXFeedsWorker) Start added in v0.22.0

func (w *VEXFeedsWorker) Start()

Start begins the schedule: a pass at once, then one every vexFeedsTick. Only the first call counts.

func (VEXFeedsWorker) Stop added in v0.22.0

func (l VEXFeedsWorker) Stop()

Stop cancels an in-flight pass and waits for the schedule goroutine to exit. It is idempotent and safe without Start.

Jump to

Keyboard shortcuts

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