storage

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: 50 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 (
	// MinPartSize is the smallest part of a multipart upload (the S3 minimum;
	// the last part may be smaller).
	MinPartSize int64 = 5 << 20

	// MaxPartSize is the largest part of a multipart upload (the Azure block
	// limit; S3 allows 5 GiB).
	MaxPartSize int64 = 4000 << 20

	// DefaultPartSize is the part size used when the client does not ask for one.
	DefaultPartSize int64 = 64 << 20

	// MaxParts is the largest number of parts of one upload (the S3 limit).
	MaxParts = 10000

	// MaxMultipartObjectBytes is the largest object a multipart upload can
	// assemble (the S3 object limit).
	MaxMultipartObjectBytes int64 = 5 << 40
)
View Source
const (
	// ReadFallbackNotFound serves a read from the replica only when the primary
	// answers that the blob does not exist (the default).
	ReadFallbackNotFound = "notfound"
	// ReadFallbackError also falls back on any other primary error (outage).
	ReadFallbackError = "error"
	// ReadFallbackOff never reads from the replica: it only protects against
	// loss, serving from it needs a manual cutover.
	ReadFallbackOff = "off"
)

Read fallback modes of a replica (ReplicaConfig.ReadFallback).

View Source
const FilesystemSpoolDir = "spool"

FilesystemSpoolDir is the directory under the blob root where the upload spools live (see SpoolDirFor). It is on the blob filesystem so that storing a spooled upload is a hard link, not a second write.

View Source
const OrphanBatch = 500

OrphanBatch bounds how many orphan blobs one CollectOrphanBlobs call removes.

View Source
const OrphanMinAge = time.Hour

OrphanMinAge is how old an unreferenced blobs row must be before it is collected, so an in-flight upload (which creates the blobs row before the row that references it) is never mistaken for garbage.

View Source
const OrphanScanWindow = 20000

OrphanScanWindow bounds how many blobs rows one CollectOrphanBlobs call examines, so the cost of a pass does not grow with the table.

View Source
const RelayRoute = "/upload-relay/{id}/{part}"

RelayRoute is the chi route pattern of the server-relayed upload endpoint. Backends without native presigned URLs (filesystem, OCI registry) hand out <PublicURL>/upload-relay/<id>/<part>?exp=<unix>&sig=<hex>; a single PUT is part 1 of 1. The route is mounted outside authentication: the HMAC signature in the query is the only credential.

Variables

View Source
var (
	ErrAzureAccountNameRequired        = errors.New("azure: AzureAccountName is required")
	ErrAzureAccountNameInvalid         = errors.New("azure: AzureAccountName must be 3-24 lowercase letters and digits")
	ErrAzureAccountKeyRequired         = errors.New("azure: AzureAccountKey is required")
	ErrAzureAccountKeyInvalid          = errors.New("azure: AzureAccountKey is not valid base64")
	ErrAzureContainerNameRequired      = errors.New("azure: AzureContainerName is required")
	ErrAzureEndpointInvalid            = errors.New("azure: AzureEndpoint must be an http(s) URL without query")
	ErrAzureMSDateHeaderRequired       = errors.New("azure: x-ms-date header is required")
	ErrAzurePutMetadataSHA256Required  = errors.New("AzureBlobStore.Put requires \"sha256\" in metadata")
	ErrAzureMissingContentLengthHeader = errors.New("azure: missing Content-Length header")
	ErrAzureUnexpectedStatus           = errors.New("azure: unexpected response")
)

Sentinel errors for Azure Blob Store.

View Source
var (
	ErrGCSBucketRequired     = errors.New("gcs: GCSBucket is required")
	ErrGCSHMACKeyRequired    = errors.New("gcs: GCSHMACKey is required")
	ErrGCSHMACSecretRequired = errors.New("gcs: GCSHMACSecret is required")
)

Sentinel errors for GCS Blob Store.

View Source
var (
	// ErrInvalidPartPlan is returned by PlanParts for a size or part size
	// outside the limits above.
	ErrInvalidPartPlan = errors.New("invalid multipart plan")

	// ErrMultipartIncomplete is returned by CompleteMultipart when a part is
	// missing or has the wrong size. The upload stays open: the client uploads
	// the missing parts and completes again.
	ErrMultipartIncomplete = errors.New("multipart upload is incomplete")
)

Sentinel errors of multipart uploads.

View Source
var (
	ErrOCIEndpointRequired = errors.New("oci: Endpoint (registry URL) is required")
	ErrOCIInsecureEndpoint = errors.New(
		"oci: Endpoint is plain http://; set ociInsecure (STORAGE_OCI_INSECURE) to allow it",
	)
	ErrOCIStagingPathRequired = errors.New(
		"oci: storage.stagingPath (STORAGE_STAGING_PATH) must be set to a persistent directory when uploads are relayed through the server",
	)
	ErrOCIBucketRequired        = errors.New("oci: Bucket (repository name) is required")
	ErrOCIPutRequiresSHA256     = errors.New("oci: Put requires \"sha256\" in metadata")
	ErrOCIMissingLocationHeader = errors.New("oci: initiate upload: missing Location header")
)

Sentinel errors for OCI Blob Store.

View Source
var ErrAzureCopyFailed = errors.New("azure: server-side copy failed")

ErrAzureCopyFailed is returned when Azure reports a server-side copy as failed or aborted.

View Source
var ErrBlobGone = errors.New("blob missing from the store")

ErrBlobGone is returned by CommitBlobs when a blob that has no source to re-store it from (Blob.Open == nil) is missing from the store at commit time: a concurrent delete removed it after the caller last saw it. The operation is safe to retry from the start.

View Source
var ErrBlobNotFound = errors.New("blob not found")

ErrBlobNotFound is wrapped by every backend when a blob does not exist.

View Source
var ErrDigestMismatch = errors.New("blob digest mismatch")

ErrDigestMismatch is returned by BlobStore.Put when the streamed bytes do not hash to the sha256 the caller claimed in the metadata. Nothing is stored when it is returned.

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

ErrInvalidBlobID is returned when a blob identifier is not a lowercase 64-character hex SHA-256 digest.

View Source
var ErrListNotSupported = errors.New("blob listing is not supported by this storage backend")

ErrListNotSupported is returned by List on backends that cannot enumerate their blobs (OCI registries expose no flat blob listing).

View Source
var ErrOffsetOutOfRange = errors.New("blob offset out of range")

ErrOffsetOutOfRange is returned by a ranged read whose offset is negative or lies beyond the end of the blob.

View Source
var ErrPresignNotSupported = errors.New("presign URL not supported by this storage backend")

ErrPresignNotSupported is returned by storage backends that do not support presigned URLs.

View Source
var ErrPromoteNotSupported = errors.New("the upload cannot be promoted in place")

ErrPromoteNotSupported is returned by UploadStore.PromoteUpload when the uploaded object cannot become a blob without passing through the server (the upload store is a host directory next to a blob store of another kind). The caller streams OpenUpload into BlobStore.Put instead.

View Source
var (
	ErrS3PutRequiresSHA256 = errors.New("S3BlobStore.Put requires \"sha256\" in metadata")
)

Sentinel errors for S3 Blob Store.

View Source
var ErrSingleUploadTooLarge = errors.New("object is too large for a single-request upload")

ErrSingleUploadTooLarge is returned by PresignStagingPut when the backend cannot take an object of that size in one request (Azure's single Put Blob limit is 5000 MiB); the client has to use a multipart upload.

View Source
var ErrStagingChanged = errors.New("staging object changed")

ErrStagingChanged is returned by OpenStaging and PromoteStaging when the staging object is no longer the version the caller verified: the client's presigned PUT URL is still valid, so it can overwrite the object at any time.

View Source
var ErrStagingNotFound = errors.New("staging object not found")

ErrStagingNotFound is returned by StagingStore operations for a staging object that does not exist (never uploaded, already promoted or expired).

View Source
var ErrUploadDataLost = errors.New("upload data is missing")

ErrUploadDataLost means what the store holds for an upload does not match the position the caller recorded (object or part missing, wrong size): the upload cannot be completed and the client has to start again.

View Source
var ErrUploadTooLarge = errors.New("upload exceeds the size the storage backend can stage")

ErrUploadTooLarge means the upload outgrew what the backend can stage (parts or blocks of one object).

View Source
var ErrUploadsNotSupported = errors.New("resumable uploads are not supported by this storage backend")

ErrUploadsNotSupported is returned by UploadStore methods on a backend that cannot hold resumable uploads.

Functions

func AccessTracked added in v0.7.0

func AccessTracked(ctx context.Context) bool

AccessTracked reports whether ctx was marked by WithAccessTracking.

func CheckHealth added in v0.13.0

func CheckHealth(ctx context.Context, s BlobStore) error

CheckHealth probes s. A store with nothing to probe is healthy.

func ClampStagingTTL added in v0.5.0

func ClampStagingTTL(ttl time.Duration) time.Duration

ClampStagingTTL clamps an upload URL TTL to [1 minute, 12 hours].

func CollectOrphanBlobs added in v0.2.0

func CollectOrphanBlobs(
	ctx context.Context,
	db CollectOrphanBlobsStore,
	blobStore BlobStore,
	cur *OrphanCursor,
	minAge time.Duration,
	batch int,
) (int, error)

CollectOrphanBlobs deletes blobs (storage object + blobs row) that no package row references any more — e.g. after a repository delete cascaded its package rows away. Only blobs older than minAge are considered. It returns the number of blobs it handed to deletion (one a row still references again by now is left alone and not counted); databases without ListUnreferencedBlobs support are a no-op. One call examines at most OrphanScanWindow blobs rows starting at cur and advances it (wrapping to the start at the end of the table), so a full sweep takes several calls.

A blob that cannot be removed (storage error, invalid id) does not stop the pass: the remaining blobs are still processed and every failure is returned joined, so one poisoned blob cannot starve the rest of the batch forever.

func CollectOrphanBlobsSweep added in v0.5.0

func CollectOrphanBlobsSweep(
	ctx context.Context,
	db CollectOrphanBlobsSweepStore,
	blobStore BlobStore,
	cur *OrphanCursor,
	minAge time.Duration,
	batch, maxWindows int,
) (int, error)

CollectOrphanBlobsSweep runs up to maxWindows consecutive CollectOrphanBlobs windows and stops early once cur wrapped past the end of the blobs table, i.e. every blob was examined once. The scheduled sweep uses it so that a large table is covered within one tick, in bounded steps.

func CommitBlob added in v0.10.0

func CommitBlob(
	ctx context.Context,
	db any,
	store BlobStore,
	blob Blob,
	commit func(ctx context.Context, key string) error,
) error

CommitBlob stores one blob and runs commit under its per-blob lock; see CommitBlobs. commit receives the blob's storage key.

func CommitBlobs added in v0.10.0

func CommitBlobs(
	ctx context.Context,
	db any,
	store BlobStore,
	blobs []Blob,
	commit func(ctx context.Context, keys []string) error,
) error

CommitBlobs makes sure every blob is in store and runs commit (the DB work: the blobs rows and the rows that reference them) under the blobs' per-blob locks, with the invariant that when commit runs, every blob's object exists in the store and no concurrent SafeDeleteBlob/sweeper can remove it before commit returns. It is the one way an uploader stores a blob.

The bytes are written BEFORE the lock is taken: the lock is a database transaction pinning a pooled connection (and one of the bounded lock slots), so holding it across an object-store PUT would cap concurrent uploads at the slot count and let one large upload stall other uploads and deletes of the same blob. This is safe because a blob is content-addressed by sha256 (a Put of the same bytes is idempotent) and the only remover is the deferred deletion sweeper, which takes the per-blob lock and keeps bytes a row references. The window between the Put and the lock is the only one in which the object may vanish (a delete queued it, and the sweeper ran in between), so under the lock every object is checked again and one that vanished is stored again from its source, now under the lock; that is rare and keeps the critical section otherwise free of blob store writes. commit then runs with the object guaranteed present: a committed row never lacks its object.

Blobs that already exist are not written again. Errors from looking up or storing a blob are returned as *StoreError, errors from commit unchanged. Nothing is cleaned up on failure: an object this call wrote and no row references is left for the caller's SafeDeleteBlob (or the orphan sweep), exactly as when the Put used to run under the lock.

commit MUST NOT write blobs itself: a Put inside it would pin the lock again. For the same reason commit MUST NOT take a blob lock of its own (WithBlobLock, CommitBlob, SafeDeleteBlob, ...): every lock holder pins a connection and one of the bounded lock slots (database lockSlots), so enough concurrent callers nesting a second lock would hold every slot while waiting for one. A caller that needs another lock for the duration of commit names it in CommitBlobsUnder, which takes all of them on one connection.

func CommitBlobsUnder added in v0.19.1

func CommitBlobsUnder(
	ctx context.Context,
	db any,
	store BlobStore,
	blobs []Blob,
	extraLocks []string,
	commit func(ctx context.Context, keys []string) error,
) error

CommitBlobsUnder is CommitBlobs that also holds the lock of every key in extraLocks while commit runs. The keys are not blobs: they name something else commit must serialize on (a per-slot lock between writers of one logical row) and live in the same lock space as blob sha256s, so a key is best a hash of a name no blob content has; a collision with a blob only adds contention. All locks (the blobs' and the extra ones) are taken together, in sorted order, on one connection, so a caller needing both a logical lock and a blob lock never nests one lock inside the other.

func DiscardUnreferencedBytes added in v0.7.0

func DiscardUnreferencedBytes(ctx context.Context, db any, blobStore BlobStore, sha string) error

DiscardUnreferencedBytes frees the bytes of a blob the caller has just found unreferenced under the blob's lock, without a blobs row of its own to delete (generated metadata). The bytes are queued like any other deleted blob, not removed at once: a running backup may still list a blobs row of the same content (an upload of byte-identical content that was deleted since) and must find its bytes. The sweeper re-checks references before it removes anything. Databases without the queue (test doubles) delete right away.

func OpenAt added in v0.11.0

func OpenAt(ctx context.Context, s BlobStore, id string, offset int64) (io.ReadCloser, error)

OpenAt opens a blob at a byte offset: through RangeReader when the store has it, otherwise by reading and discarding the first offset bytes.

func PartCount added in v0.8.0

func PartCount(size, partSize int64) int

PartCount is the number of parts of an object of size bytes split into partSize parts; an empty object still has one (empty) part.

func PartLength added in v0.8.0

func PartLength(size, partSize int64, number int) int64

PartLength is the exact size of part number (1-based) of an object of size bytes split into partSize parts. It is 0 for a number outside the plan.

func PlanParts added in v0.8.0

func PlanParts(size, requested int64) (int64, int, error)

PlanParts validates a multipart plan and returns the part size and part count for an object of size bytes. requested is the part size the client asked for; 0 picks DefaultPartSize, raised to the smallest MiB multiple that keeps the part count within MaxParts.

func ReclaimMetadataBlob added in v0.5.0

func ReclaimMetadataBlob(ctx context.Context, db ReclaimMetadataBlobStore, blobStore BlobStore, sha string) error

ReclaimMetadataBlob deletes a superseded generated-metadata blob (maven maven-metadata.xml, ...) when nothing references it any more. Such blobs have no blobs row, so neither SafeDeleteBlob's package-table count nor the orphan collector sees them: the repository_metadata rows (which identical content in another repository may share) and the package tables are checked here, under the per-blob lock a generator holds while it stores the blob and commits its row, so a concurrent regeneration of the same content is never undercut.

func SafeDeleteBlob

func SafeDeleteBlob(ctx context.Context, db SafeDeleteBlobStore, blobStore BlobStore, sha256 string) error

SafeDeleteBlob deletes the blob identified by sha256 only if no package-table row still references it (db.BlobReferenceCount == 0).

With the Postgres database "deletes" means: the blobs row is removed at once and the bytes are queued for physical deletion by the blob deletion sweeper, which removes them after the configured grace period and once no running backup can still read them. blobStore is used only by databases without that queue (test doubles), which delete the bytes immediately.

Callers MUST delete their own DB row referencing the blob BEFORE calling this function, otherwise BlobReferenceCount will still see that row and the blob will never be removed from storage.

SafeDeleteBlob takes one of the database's bounded blob-lock slots, so it MUST NOT be called from inside a WithBlobLock(s) callback or a FlipBlobPlacement verify (see database.WithBlobLocks); do it after the callback returns.

func SpoolDirFor added in v0.19.0

func SpoolDirFor(cfg StorageConfig) string

SpoolDirFor returns the directory upload spools should be created in for the configured storage, creating it and removing spools a crashed process left behind. On the filesystem backend it is a directory of the blob root, the only place where a spool can become the blob without being copied; the other backends use their configured spool path, or the OS temp dir when none is set.

func ValidAzureAccountName added in v0.15.0

func ValidAzureAccountName(name string) bool

ValidAzureAccountName reports whether name is a well-formed Azure storage account name (3-24 lowercase letters and digits).

func ValidateBlobID added in v0.2.0

func ValidateBlobID(id string) error

ValidateBlobID reports whether id is a well-formed content-addressed blob identifier (lowercase hex SHA-256). Every backend key helper calls it so untrusted identifiers can never influence a filesystem path or object key.

func WithAccessTracking added in v0.7.0

func WithAccessTracking(ctx context.Context) context.Context

WithAccessTracking marks ctx as serving a client download: a tiered blob store records reads made with it as the blob's last access (used by tier policies and promote-on-read). Background reads (metadata regeneration, scans, the tier mover itself) do not carry the mark and so never count as a download.

func WithBlobLock added in v0.2.0

func WithBlobLock(ctx context.Context, db any, sha256 string, fn func(ctx context.Context) error) error

WithBlobLock runs fn while holding the per-blob lock that SafeDeleteBlob takes, so an uploader can store a blob and insert its referencing row without a concurrent SafeDeleteBlob removing the blob in between. When the database does not support locking, fn runs unguarded.

fn MUST NOT take another blob lock or call SafeDeleteBlob: each holds one of the database's bounded lock slots, and a nested acquisition can deadlock once concurrent holders fill them (see database.WithBlobLocks). With the Postgres database an error wrapping database.ErrBlobLockLost means fn returned nil but its lock was lost while it ran; treat it as a failed operation.

func WithBlobLocks added in v0.2.0

func WithBlobLocks(ctx context.Context, db any, shas []string, fn func(ctx context.Context) error) error

WithBlobLocks is WithBlobLock for several blobs held at once (a row that references two blobs, e.g. a Go module's zip and mod). The locks are taken in a deterministic order on a single connection. Databases that only support single-blob locks get nested WithBlobLock calls in the same order; databases without locking support run fn unguarded.

Types

type AzureBlobStore

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

AzureBlobStore implements BlobStore for Azure Blob Storage using the REST API.

func NewAzureBlobStore

func NewAzureBlobStore(cfg StorageConfig) (*AzureBlobStore, error)

NewAzureBlobStore creates a new Azure Blob Storage backend. The blob service is cfg.AzureEndpoint, or https://<account>.blob.core.windows.net when empty.

func (*AzureBlobStore) AppendUpload added in v0.19.0

func (a *AzureBlobStore) AppendUpload(
	ctx context.Context,
	id string,
	at UploadPosition,
	r io.Reader,
	commit func(ctx context.Context, state string, n int64) error,
) error

AppendUpload stages the bytes of r as the blocks n+1, n+2, ... of the blob uploads/<id>, where n is the block count of at. Staged blocks are invisible until CompleteUpload commits them, and the position only references blocks 1..n, so a failed append (and the blocks it staged) is harmless: the retry stages the same ids again, which overwrites them, and blocks past the new end are ignored at completion. Nothing is dropped after commit, there is nothing superseded.

The block count is not checked against the service here (it would cost a request per call); CompleteUpload does.

func (*AzureBlobStore) CompleteMultipart added in v0.8.0

func (a *AzureBlobStore) CompleteMultipart(ctx context.Context, id, _ string, size, partSize int64) error

CompleteMultipart checks that every planned block was staged with its planned size and commits them as the staging blob (Put Block List). It is idempotent: a committed staging blob of the right size means a previous call did it.

func (*AzureBlobStore) CompleteUpload added in v0.19.0

func (a *AzureBlobStore) CompleteUpload(ctx context.Context, id string, at UploadPosition) (StagedObject, error)

CompleteUpload commits blocks 1..n as the blob uploads/<id> (Put Block List) after checking that each is staged and that together they hold exactly at.Offset bytes; blocks staged beyond n, left by failed appends, are dropped by the commit. The version is the ETag of the committed blob.

It is idempotent: once committed there are no uncommitted blocks left, and a blob of at.Offset bytes is the result of an earlier call.

func (*AzureBlobStore) Delete

func (a *AzureBlobStore) Delete(ctx context.Context, id string) error

Delete removes a blob by its SHA-256 identifier.

func (*AzureBlobStore) DeleteStaging added in v0.8.0

func (a *AzureBlobStore) DeleteStaging(ctx context.Context, id string) error

DeleteStaging removes a staging object; a missing object is not an error. A blob that only has uncommitted blocks (an unfinished multipart upload) does not exist for Delete Blob: Azure discards such blocks by itself after a week.

func (*AzureBlobStore) DeleteUpload added in v0.19.0

func (a *AzureBlobStore) DeleteUpload(ctx context.Context, id string) error

DeleteUpload removes the completed upload; a missing one is not an error. Blocks staged for an upload that was never completed do not exist for Delete Blob: Azure discards them by itself after a week.

func (*AzureBlobStore) Exists

func (a *AzureBlobStore) Exists(ctx context.Context, id string) (bool, error)

Exists checks whether a blob exists using HEAD.

func (*AzureBlobStore) ExistsBySHA256

func (a *AzureBlobStore) ExistsBySHA256(ctx context.Context, sha256 string) (string, bool, error)

ExistsBySHA256 checks if a blob with the given SHA-256 hash exists.

func (*AzureBlobStore) Get

func (a *AzureBlobStore) Get(ctx context.Context, id string) (io.ReadCloser, error)

Get retrieves a blob by its SHA-256 identifier.

func (*AzureBlobStore) GetFrom added in v0.11.0

func (a *AzureBlobStore) GetFrom(ctx context.Context, id string, offset int64) (io.ReadCloser, error)

GetFrom implements RangeReader with a ranged Get Blob (x-ms-range).

func (*AzureBlobStore) GetMetadata

func (a *AzureBlobStore) GetMetadata(ctx context.Context, id string) (map[string]string, error)

GetMetadata retrieves metadata for a blob using HEAD.

func (*AzureBlobStore) GetSize

func (a *AzureBlobStore) GetSize(ctx context.Context, id string) (int64, error)

GetSize returns the size of a blob in bytes using HEAD.

func (*AzureBlobStore) HealthCheck

func (a *AzureBlobStore) HealthCheck(ctx context.Context) error

HealthCheck verifies that the Azure container is accessible.

func (*AzureBlobStore) InitiateMultipart added in v0.8.0

func (a *AzureBlobStore) InitiateMultipart(_ context.Context, id string, _, _ int64) (string, error)

InitiateMultipart opens a multipart upload. Azure needs no server-side upload object: blocks are staged on the blob itself, so the handle is empty.

func (*AzureBlobStore) List

func (a *AzureBlobStore) List(ctx context.Context, token string, limit int) ([]string, string, error)

List returns one page of at most limit blob ids after token, an Azure NextMarker. Blobs are returned in name order, which for the ab/cd/<sha> layout is ascending sha order. Entries that are not blob ids are skipped.

func (*AzureBlobStore) MultipartSupported added in v0.8.0

func (a *AzureBlobStore) MultipartSupported() bool

MultipartSupported reports that the Azure backend stages multipart uploads as block blobs.

func (*AzureBlobStore) OpenStaging added in v0.8.0

func (a *AzureBlobStore) OpenStaging(ctx context.Context, id, version string) (io.ReadCloser, error)

OpenStaging reads a staging object, conditional on its ETag.

func (*AzureBlobStore) OpenUpload added in v0.19.0

func (a *AzureBlobStore) OpenUpload(ctx context.Context, id, version string) (io.ReadCloser, error)

OpenUpload reads the completed upload, conditional on its ETag.

func (*AzureBlobStore) PresignGet added in v0.8.0

func (a *AzureBlobStore) PresignGet(_ context.Context, sha256 string, ttl time.Duration, opts PresignGetOptions) (string, error)

PresignGet returns a read-only SAS URL for the blob with a clamped TTL (a TTL <= 0 selects the store's configured presign TTL). The response overrides in opts are part of the signature. Signing is local: no request is made.

func (*AzureBlobStore) PresignStagingPart added in v0.8.0

func (a *AzureBlobStore) PresignStagingPart(_ context.Context, id, _ string, number int, _ int64, ttl time.Duration) (PresignedPut, error)

PresignStagingPart returns a SAS URL (permission write) for Put Block of part number of the staging object id. A SAS cannot sign the block length, so CompleteMultipart checks the sizes.

func (*AzureBlobStore) PresignStagingPut added in v0.8.0

func (a *AzureBlobStore) PresignStagingPut(_ context.Context, id string, size int64, ttl time.Duration) (PresignedPut, error)

PresignStagingPut returns a SAS URL (permissions create + write) for a single Put Blob of the staging object id. A SAS cannot sign the body length, so the size is checked against the staging object by the caller (StatStaging). Objects above the Put Blob limit need a multipart upload.

func (*AzureBlobStore) PresignURL

func (a *AzureBlobStore) PresignURL(ctx context.Context, sha256 string, ttl time.Duration) (string, error)

PresignURL returns a SAS URL for direct blob download.

func (*AzureBlobStore) PromoteStaging added in v0.8.0

func (a *AzureBlobStore) PromoteStaging(ctx context.Context, id, sha256, version string, metadata map[string]string) error

PromoteStaging copies a staging object to the content-addressed blob with a server-side Copy Blob (the bytes never pass through OpenArtifact). The copy is conditional on the staging object still having the ETag that was verified (x-ms-source-if-match), so an overwrite through the still-valid SAS after verification cannot put unverified bytes under a content-addressed name.

An existing blob is left alone, unless it is the leftover of a failed copy (removed and copied again) or of a copy still pending (awaited). The copy inherits the staging blob's properties and, when no metadata is given, its metadata, both chosen by the uploader, so they are reset to what Put writes.

func (*AzureBlobStore) PromoteUpload added in v0.19.0

func (a *AzureBlobStore) PromoteUpload(ctx context.Context, id, sha256, version string, metadata map[string]string) error

PromoteUpload copies the completed upload to the content-addressed blob with a server-side Copy Blob, exactly as PromoteStaging does for a staging object.

func (*AzureBlobStore) Put

func (a *AzureBlobStore) Put(ctx context.Context, data io.Reader, metadata map[string]string) (string, error)

Put stores a blob. The metadata map must contain a "sha256" key.

func (*AzureBlobStore) StagingSupported added in v0.8.0

func (a *AzureBlobStore) StagingSupported() bool

StagingSupported reports that the Azure backend has a staging area: the blobs under staging/ in the same container.

func (*AzureBlobStore) StatStaging added in v0.8.0

func (a *AzureBlobStore) StatStaging(ctx context.Context, id string) (StagedObject, error)

StatStaging describes a staging object; its ETag is the version.

func (*AzureBlobStore) UploadsSupported added in v0.19.0

func (a *AzureBlobStore) UploadsSupported() bool

UploadsSupported reports that uploads are the blobs uploads/<id> of the container.

func (*AzureBlobStore) WalkStaging added in v0.8.0

func (a *AzureBlobStore) WalkStaging(ctx context.Context, olderThan time.Time, fn func(ids []string) error) error

WalkStaging lists staging objects last modified before olderThan. Blobs without a readable modification time are skipped.

func (*AzureBlobStore) WalkUploads added in v0.19.0

func (a *AzureBlobStore) WalkUploads(ctx context.Context, olderThan time.Time, fn func(ids []string) error) error

WalkUploads lists the completed uploads last modified before olderThan. An upload that was never completed has no blob to list. Blobs without a readable modification time or an upload id as name are skipped.

type Blob added in v0.10.0

type Blob struct {
	// SHA256 is the hex sha256 of the content; the blob's identity and the
	// key of its per-blob lock. Put always receives it as the "sha256"
	// metadata entry.
	SHA256 string
	// Metadata is the extra Put metadata ("sha256" is added).
	Metadata map[string]string
	// Open returns a reader over the whole content, positioned at its start.
	// It is called once per Put attempt (normally one; again only when a
	// concurrent delete removed the object before the row was committed). A nil
	// Open marks a blob that must already exist: it is checked under the lock
	// and a missing one fails with ErrBlobGone.
	Open func() (io.Reader, error)
	// Promote, when set, stores the blob without its bytes passing through the
	// server (a server-side copy or link of an object already verified in the
	// store) and is tried before Open. ErrPromoteNotSupported falls back to
	// Open; any other error fails the call. A Blob with only Promote set has
	// no content to fall back to.
	Promote func(ctx context.Context) error
}

Blob is one blob a CommitBlobs call makes sure is in the store.

func BytesBlob added in v0.10.0

func BytesBlob(sha string, data []byte, meta map[string]string) Blob

BytesBlob is a Blob whose content is held in memory.

func ReaderBlob added in v0.10.0

func ReaderBlob(sha string, meta map[string]string, open func() io.Reader) Blob

ReaderBlob is a Blob whose reader open returns a fresh reader over the whole content each time it is called (base.Spool.Reader).

func SeekerBlob added in v0.10.0

func SeekerBlob(sha string, src io.ReadSeeker, meta map[string]string) Blob

SeekerBlob is a Blob read from src, rewound to its start before every attempt (an *os.File spool, a *base.Spool section reader).

type BlobSeeker added in v0.19.0

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

BlobSeeker is an io.ReadSeekCloser over a stored blob of a known size. A Seek costs nothing; the next Read opens the blob at the new position through OpenAt, so a filesystem store seeks and an object store issues a ranged GET instead of reading the bytes before the position. It is what lets http.ServeContent serve Range requests from any BlobStore.

func NewBlobSeeker added in v0.19.0

func NewBlobSeeker(ctx context.Context, store BlobStore, id string, size int64) *BlobSeeker

NewBlobSeeker returns a seeker over blob id of the given size. It opens nothing until the first Read.

func (*BlobSeeker) Close added in v0.19.0

func (s *BlobSeeker) Close() error

Close releases the open reader, if any.

func (*BlobSeeker) Open added in v0.19.0

func (s *BlobSeeker) Open() error

Open opens the blob at the current position now, so a missing blob is reported before any response header is written. Reading from that position afterwards reuses the reader.

func (*BlobSeeker) Read added in v0.19.0

func (s *BlobSeeker) Read(p []byte) (int, error)

Read implements io.Reader.

func (*BlobSeeker) Seek added in v0.19.0

func (s *BlobSeeker) Seek(offset int64, whence int) (int64, error)

Seek implements io.Seeker.

type BlobStore

type BlobStore interface {
	// Put stores a blob and returns its identifier
	Put(ctx context.Context, data io.Reader, metadata map[string]string) (string, error)

	// Get retrieves a blob by its identifier
	Get(ctx context.Context, id string) (io.ReadCloser, error)

	// Delete removes a blob by its identifier
	Delete(ctx context.Context, id string) error

	// Exists checks if a blob exists
	Exists(ctx context.Context, id string) (bool, error)

	// GetMetadata retrieves metadata for a blob
	GetMetadata(ctx context.Context, id string) (map[string]string, error)

	// List returns up to limit blob identifiers (sha256 hex, ascending) that
	// follow the opaque continuation token. An empty token starts at the
	// beginning; the returned next token is empty once the listing is
	// exhausted. Cost per call is independent of how many blobs precede the
	// token. Backends that cannot enumerate return ErrListNotSupported.
	List(ctx context.Context, token string, limit int) (ids []string, next string, err error)

	// GetSize returns the size of a blob in bytes
	GetSize(ctx context.Context, id string) (int64, error)

	// ExistsBySHA256 checks if a blob with the given SHA-256 hash exists.
	// Returns the blobID and true if found, or ("", false, nil) if not found.
	ExistsBySHA256(ctx context.Context, sha256 string) (blobID string, exists bool, err error)

	// PresignURL returns a presigned URL for direct blob download.
	// Returns ErrPresignNotSupported if the backend does not support presigned URLs.
	PresignURL(ctx context.Context, sha256 string, ttl time.Duration) (string, error)
}

BlobStore defines the interface for blob storage operations.

func NewBlobStore

func NewBlobStore(cfg StorageConfig) (BlobStore, error)

NewBlobStore creates a BlobStore from the given config, selecting the backend by Type.

type CollectOrphanBlobsStore added in v0.15.0

type CollectOrphanBlobsStore interface {
	// contains filtered or unexported methods
}

CollectOrphanBlobsStore is the part of the database CollectOrphanBlobs needs.

type CollectOrphanBlobsSweepStore added in v0.15.0

type CollectOrphanBlobsSweepStore interface {
	// contains filtered or unexported methods
}

CollectOrphanBlobsSweepStore is the part of the database CollectOrphanBlobsSweep needs.

type FilesystemStore

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

FilesystemStore implements the BlobStore interface for filesystem storage.

func NewFilesystemBlobStore

func NewFilesystemBlobStore(cfg StorageConfig) (*FilesystemStore, error)

NewFilesystemBlobStore creates a FilesystemStore from the given config.

func NewFilesystemStore

func NewFilesystemStore(basePath string) (*FilesystemStore, error)

NewFilesystemStore creates a new filesystem blob store.

func (*FilesystemStore) AppendUpload added in v0.19.0

func (fs *FilesystemStore) AppendUpload(
	ctx context.Context,
	id string,
	at UploadPosition,
	r io.Reader,
	commit func(ctx context.Context, state string, n int64) error,
) error

AppendUpload implements UploadStore.

func (FilesystemStore) CompleteMultipart added in v0.8.0

func (r FilesystemStore) CompleteMultipart(ctx context.Context, id, _ string, size, partSize int64) error

CompleteMultipart implements MultipartStagingStore.

func (*FilesystemStore) CompleteUpload added in v0.19.0

func (fs *FilesystemStore) CompleteUpload(ctx context.Context, id string, at UploadPosition) (StagedObject, error)

CompleteUpload implements UploadStore.

func (*FilesystemStore) Delete

func (fs *FilesystemStore) Delete(ctx context.Context, id string) error

Delete removes a blob by its identifier.

func (FilesystemStore) DeleteStaging added in v0.8.0

func (r FilesystemStore) DeleteStaging(_ context.Context, id string) error

DeleteStaging implements StagingStore.

func (*FilesystemStore) DeleteUpload added in v0.19.0

func (fs *FilesystemStore) DeleteUpload(ctx context.Context, id string) error

DeleteUpload implements UploadStore.

func (*FilesystemStore) Exists

func (fs *FilesystemStore) Exists(ctx context.Context, id string) (bool, error)

Exists checks if a blob exists.

func (*FilesystemStore) ExistsBySHA256

func (fs *FilesystemStore) ExistsBySHA256(ctx context.Context, sha256hex string) (string, bool, error)

ExistsBySHA256 finds a blob by its SHA-256 hash. Fast path: content-addressed blobs use SHA-256 as the blob ID (O(1) check). Fallback: scans metadata files for blobs stored with a non-SHA256 ID. Returns the blobID and true if found, or ("", false, nil) if not found.

func (*FilesystemStore) Get

func (fs *FilesystemStore) Get(ctx context.Context, id string) (io.ReadCloser, error)

Get retrieves a blob by its identifier.

func (*FilesystemStore) GetFrom added in v0.11.0

func (fs *FilesystemStore) GetFrom(ctx context.Context, id string, offset int64) (io.ReadCloser, error)

GetFrom implements RangeReader: the file is opened and seeked to offset.

func (*FilesystemStore) GetMetadata

func (fs *FilesystemStore) GetMetadata(ctx context.Context, id string) (map[string]string, error)

GetMetadata retrieves metadata for a blob.

func (*FilesystemStore) GetSize

func (fs *FilesystemStore) GetSize(ctx context.Context, id string) (int64, error)

GetSize returns the size of a blob in bytes.

func (*FilesystemStore) HealthCheck added in v0.13.0

func (fs *FilesystemStore) HealthCheck(ctx context.Context) error

HealthCheck verifies that the blob root is an existing directory the server can write to, by creating and removing a temporary file in it.

func (FilesystemStore) InitiateMultipart added in v0.8.0

func (r FilesystemStore) InitiateMultipart(_ context.Context, id string, size, partSize int64) (string, error)

InitiateMultipart implements MultipartStagingStore. The handle is empty.

func (*FilesystemStore) List

func (fs *FilesystemStore) List(ctx context.Context, token string, limit int) ([]string, string, error)

List returns up to limit blob ids in ascending order that sort after token (the last id of the previous page). Directories that sort entirely before the token are skipped, so the cost of a page does not grow with the number of blobs already listed.

func (FilesystemStore) MultipartSupported added in v0.8.0

func (r FilesystemStore) MultipartSupported() bool

MultipartSupported implements MultipartStagingStore.

func (FilesystemStore) OpenStaging added in v0.8.0

func (r FilesystemStore) OpenStaging(_ context.Context, id, version string) (io.ReadCloser, error)

OpenStaging implements StagingStore.

func (*FilesystemStore) OpenUpload added in v0.19.0

func (fs *FilesystemStore) OpenUpload(ctx context.Context, id, version string) (io.ReadCloser, error)

OpenUpload implements UploadStore.

func (FilesystemStore) PresignStagingPart added in v0.8.0

func (r FilesystemStore) PresignStagingPart(ctx context.Context, id, _ string, number int, length int64, ttl time.Duration) (PresignedPut, error)

PresignStagingPart implements MultipartStagingStore.

func (FilesystemStore) PresignStagingPut added in v0.8.0

func (r FilesystemStore) PresignStagingPut(ctx context.Context, id string, size int64, ttl time.Duration) (PresignedPut, error)

PresignStagingPut implements StagingStore.

func (*FilesystemStore) PresignURL

func (fs *FilesystemStore) PresignURL(_ context.Context, _ string, _ time.Duration) (string, error)

PresignURL returns ErrPresignNotSupported; filesystem storage does not support presigned URLs.

func (*FilesystemStore) PromoteStaging added in v0.8.0

func (fs *FilesystemStore) PromoteStaging(ctx context.Context, id, sha256hex, version string, metadata map[string]string) error

PromoteStaging implements StagingStore. The staging area is on the blob filesystem, so the exact checked staging object is hard-linked into place (atomic, no copy) with the same ".meta" sidecar Put writes; a copy is the fallback when the filesystem cannot link. An existing blob is left untouched.

func (*FilesystemStore) PromoteUpload added in v0.19.0

func (fs *FilesystemStore) PromoteUpload(_ context.Context, id, sha256hex, version string, metadata map[string]string) error

PromoteUpload implements UploadStore: the upload file is on the blob filesystem, so the verified object is hard-linked into place (no copy) with the ".meta" sidecar Put writes.

func (*FilesystemStore) Put

func (fs *FilesystemStore) Put(ctx context.Context, data io.Reader, metadata map[string]string) (string, error)

Put stores a blob and returns its identifier. The blob ID is the computed SHA-256 of the content; if metadata contains a "sha256" key it must equal it, else ErrDigestMismatch is returned and nothing is stored. An already-present blob is left untouched.

func (FilesystemStore) RelayHandler added in v0.8.0

func (r FilesystemStore) RelayHandler() http.Handler

RelayHandler implements RelayServer.

func (FilesystemStore) StagingSupported added in v0.8.0

func (r FilesystemStore) StagingSupported() bool

StagingSupported implements StagingStore.

func (FilesystemStore) StatStaging added in v0.8.0

func (r FilesystemStore) StatStaging(_ context.Context, id string) (StagedObject, error)

StatStaging implements StagingStore.

func (*FilesystemStore) UploadsSupported added in v0.19.0

func (fs *FilesystemStore) UploadsSupported() bool

UploadsSupported implements UploadStore. The uploads live on the blob filesystem, which every replica sharing the blob root sees.

func (FilesystemStore) WalkStaging added in v0.8.0

func (r FilesystemStore) WalkStaging(ctx context.Context, olderThan time.Time, fn func(ids []string) error) error

WalkStaging implements StagingStore. An id is reported when every file of it (object, partial upload, part markers, plan) is older than olderThan.

func (*FilesystemStore) WalkUploads added in v0.19.0

func (fs *FilesystemStore) WalkUploads(ctx context.Context, olderThan time.Time, fn func(ids []string) error) error

WalkUploads implements UploadStore.

type HealthChecker added in v0.13.0

type HealthChecker interface {
	HealthCheck(ctx context.Context) error
}

HealthChecker is implemented by stores that can probe their backend. Every store that wraps another one (metrics, tiers, replication, presign) implements it by forwarding to the store it wraps, so the probe reaches the backend from whatever layer the caller holds.

type HealthProbe added in v0.13.0

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

HealthProbe is a time-limited, cached storage probe, so an unauthenticated endpoint cannot turn requests into backend round trips: the result of a probe is reused for ttl, and a probe is bounded by timeout whatever the caller's context does. Concurrent callers share one probe.

func NewHealthProbe added in v0.13.0

func NewHealthProbe(store BlobStore, ttl, timeout time.Duration) *HealthProbe

NewHealthProbe returns a probe of store.

func (*HealthProbe) Check added in v0.13.0

func (p *HealthProbe) Check(ctx context.Context) error

Check returns the outcome of the last probe while it is younger than the ttl, else probes again. A nil probe, or one over a store with nothing to probe, is healthy. The error is the backend's: callers log it and must not put it in a response.

type MetricsBlobStore

type MetricsBlobStore struct {
	StagingForwarder
	// contains filtered or unexported fields
}

MetricsBlobStore times and counts the calls of the store it wraps. Staging and multipart staging calls pass straight through (StagingForwarder); only the bytes read through OpenStaging are counted.

func NewMetricsBlobStore

func NewMetricsBlobStore(inner BlobStore, reg *metrics.Registry) *MetricsBlobStore

func (*MetricsBlobStore) Delete

func (m *MetricsBlobStore) Delete(ctx context.Context, id string) error

func (*MetricsBlobStore) Exists

func (m *MetricsBlobStore) Exists(ctx context.Context, id string) (bool, error)

func (*MetricsBlobStore) ExistsBySHA256

func (m *MetricsBlobStore) ExistsBySHA256(ctx context.Context, sha256 string) (string, bool, error)

func (*MetricsBlobStore) Get

func (*MetricsBlobStore) GetFrom added in v0.11.0

func (m *MetricsBlobStore) GetFrom(ctx context.Context, id string, offset int64) (io.ReadCloser, error)

GetFrom forwards a ranged read (see OpenAt), counted and timed like Get.

func (*MetricsBlobStore) GetMetadata

func (m *MetricsBlobStore) GetMetadata(ctx context.Context, id string) (map[string]string, error)

func (*MetricsBlobStore) GetSize

func (m *MetricsBlobStore) GetSize(ctx context.Context, id string) (int64, error)

func (*MetricsBlobStore) HealthCheck added in v0.13.0

func (m *MetricsBlobStore) HealthCheck(ctx context.Context) error

HealthCheck probes the store this one wraps.

func (*MetricsBlobStore) List

func (m *MetricsBlobStore) List(ctx context.Context, token string, limit int) ([]string, string, error)

func (*MetricsBlobStore) OpenStaging added in v0.5.0

func (m *MetricsBlobStore) OpenStaging(ctx context.Context, id, version string) (io.ReadCloser, error)

OpenStaging forwards to the wrapped store and counts the bytes read.

func (*MetricsBlobStore) PresignGet added in v0.5.0

func (m *MetricsBlobStore) PresignGet(ctx context.Context, sha256 string, ttl time.Duration, opts PresignGetOptions) (string, error)

PresignGet forwards to the wrapped store when it can sign download URLs.

func (*MetricsBlobStore) PresignURL

func (m *MetricsBlobStore) PresignURL(ctx context.Context, sha256 string, ttl time.Duration) (string, error)

func (*MetricsBlobStore) Put

func (m *MetricsBlobStore) Put(ctx context.Context, data io.Reader, metadata map[string]string) (string, error)

type MultipartStagingStore added in v0.8.0

type MultipartStagingStore interface {
	// MultipartSupported reports whether the backend can stage multipart
	// uploads. The other methods return ErrPresignNotSupported when it cannot.
	MultipartSupported() bool

	// InitiateMultipart opens a multipart upload into the staging object id
	// (a server generated UUID) for an object of size bytes split into
	// partSize parts. The returned handle (the S3 upload id; empty for
	// backends that need none) is stored by the caller and passed back to the
	// other methods.
	InitiateMultipart(ctx context.Context, id string, size, partSize int64) (handle string, err error)

	// PresignStagingPart returns a URL the client PUTs part number (1-based)
	// to; length is the exact part size from PartLength.
	PresignStagingPart(ctx context.Context, id, handle string, number int, length int64, ttl time.Duration) (PresignedPut, error)

	// CompleteMultipart checks that every part 1..PartCount is present with
	// its planned size and assembles the staging object. It returns
	// ErrMultipartIncomplete, wrapped with the detail, when a part is missing
	// or has another size, and leaves the upload open. It is idempotent: when
	// the staging object already exists (a previous call assembled it) it
	// returns nil. After success the parts can no longer change the object.
	CompleteMultipart(ctx context.Context, id, handle string, size, partSize int64) error
}

MultipartStagingStore is implemented by backends whose staging area accepts an upload in parts, so objects above the 5 GiB single-PUT limit can bypass the server. The staging object ends up exactly where StagingStore expects it (StatStaging, OpenStaging, PromoteStaging and DeleteStaging work on it as for a single PUT); CompleteMultipart is the step that creates it.

Part sizes are fixed by the plan (PartLength): the presigned URL of a part signs its exact length, so the object store itself rejects any other size.

type OCIBlobStore

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

OCIBlobStore stores blobs in an OCI-compliant registry.

func NewOCIBlobStore

func NewOCIBlobStore(cfg StorageConfig) (*OCIBlobStore, error)

NewOCIBlobStore creates a new OCIBlobStore from the provided StorageConfig. StorageConfig.Endpoint must be the registry base URL (e.g. "https://registry.example.com"). StorageConfig.Bucket is used as the OCI repository name.

func (OCIBlobStore) CompleteMultipart added in v0.8.0

func (r OCIBlobStore) CompleteMultipart(ctx context.Context, id, _ string, size, partSize int64) error

CompleteMultipart implements MultipartStagingStore.

func (*OCIBlobStore) Delete

func (o *OCIBlobStore) Delete(ctx context.Context, id string) error

Delete removes a blob by its SHA-256 identifier.

func (OCIBlobStore) DeleteStaging added in v0.8.0

func (r OCIBlobStore) DeleteStaging(_ context.Context, id string) error

DeleteStaging implements StagingStore.

func (*OCIBlobStore) Exists

func (o *OCIBlobStore) Exists(ctx context.Context, id string) (bool, error)

Exists checks whether a blob exists using HEAD.

func (*OCIBlobStore) ExistsBySHA256

func (o *OCIBlobStore) ExistsBySHA256(ctx context.Context, sha256hex string) (string, bool, error)

ExistsBySHA256 checks whether a blob with the given SHA-256 hash exists. In OCI, blobs are natively addressed by digest, so this is equivalent to Exists.

func (*OCIBlobStore) Get

func (o *OCIBlobStore) Get(ctx context.Context, id string) (io.ReadCloser, error)

Get retrieves a blob by its SHA-256 identifier.

func (*OCIBlobStore) GetFrom added in v0.11.0

func (o *OCIBlobStore) GetFrom(ctx context.Context, id string, offset int64) (io.ReadCloser, error)

GetFrom implements RangeReader with a Range request; a registry that ignores the header answers 200 and the prefix is skipped locally.

func (*OCIBlobStore) GetMetadata

func (o *OCIBlobStore) GetMetadata(ctx context.Context, id string) (map[string]string, error)

GetMetadata returns a minimal metadata map derived from the HEAD response.

func (*OCIBlobStore) GetSize

func (o *OCIBlobStore) GetSize(ctx context.Context, id string) (int64, error)

GetSize returns the size of a blob in bytes using HEAD.

func (*OCIBlobStore) HealthCheck

func (o *OCIBlobStore) HealthCheck(ctx context.Context) error

HealthCheck verifies registry connectivity by calling GET /v2/.

func (OCIBlobStore) InitiateMultipart added in v0.8.0

func (r OCIBlobStore) InitiateMultipart(_ context.Context, id string, size, partSize int64) (string, error)

InitiateMultipart implements MultipartStagingStore. The handle is empty.

func (*OCIBlobStore) List

func (o *OCIBlobStore) List(_ context.Context, _ string, _ int) ([]string, string, error)

List is not supported: OCI registries expose no flat blob listing.

func (OCIBlobStore) MultipartSupported added in v0.8.0

func (r OCIBlobStore) MultipartSupported() bool

MultipartSupported implements MultipartStagingStore.

func (OCIBlobStore) OpenStaging added in v0.8.0

func (r OCIBlobStore) OpenStaging(_ context.Context, id, version string) (io.ReadCloser, error)

OpenStaging implements StagingStore.

func (OCIBlobStore) PresignStagingPart added in v0.8.0

func (r OCIBlobStore) PresignStagingPart(ctx context.Context, id, _ string, number int, length int64, ttl time.Duration) (PresignedPut, error)

PresignStagingPart implements MultipartStagingStore.

func (OCIBlobStore) PresignStagingPut added in v0.8.0

func (r OCIBlobStore) PresignStagingPut(ctx context.Context, id string, size int64, ttl time.Duration) (PresignedPut, error)

PresignStagingPut implements StagingStore.

func (*OCIBlobStore) PresignURL

func (o *OCIBlobStore) PresignURL(_ context.Context, _ string, _ time.Duration) (string, error)

PresignURL returns ErrPresignNotSupported; OCI registries do not support presigned URLs.

func (*OCIBlobStore) PromoteStaging added in v0.8.0

func (o *OCIBlobStore) PromoteStaging(ctx context.Context, id, sha256hex, version string, metadata map[string]string) error

PromoteStaging implements StagingStore: the exact checked staging object is pushed to the registry through Put, which verifies its SHA-256. A blob the registry already has is left untouched.

func (*OCIBlobStore) Put

func (o *OCIBlobStore) Put(ctx context.Context, data io.Reader, metadata map[string]string) (string, error)

Put uploads a blob to the OCI registry using the monolithic upload flow. The metadata map must contain a "sha256" key with the hex-encoded SHA-256 digest.

func (OCIBlobStore) RelayHandler added in v0.8.0

func (r OCIBlobStore) RelayHandler() http.Handler

RelayHandler implements RelayServer.

func (OCIBlobStore) StagingSupported added in v0.8.0

func (r OCIBlobStore) StagingSupported() bool

StagingSupported implements StagingStore.

func (OCIBlobStore) StatStaging added in v0.8.0

func (r OCIBlobStore) StatStaging(_ context.Context, id string) (StagedObject, error)

StatStaging implements StagingStore.

func (OCIBlobStore) WalkStaging added in v0.8.0

func (r OCIBlobStore) WalkStaging(ctx context.Context, olderThan time.Time, fn func(ids []string) error) error

WalkStaging implements StagingStore. An id is reported when every file of it (object, partial upload, part markers, plan) is older than olderThan.

type OrphanCursor added in v0.19.1

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

OrphanCursor is one caller's position in its sweep of the blobs table: where its next CollectOrphanBlobs call resumes (the zero value starts at the beginning). Every caller that sweeps (the scheduled cleanup, the trash purge, a repository delete) owns its own, so one caller's passes neither move another's position nor leave it a stretch of the table behind: each cursor continues its sweep window by window, a blob that cannot be removed is scanned past, and a window a pass could not finish (shutdown) is redone, not skipped. A cursor is safe for concurrent use; passes sharing one run one at a time, the later one continuing where the earlier stopped.

type PresignGetOptions added in v0.5.0

type PresignGetOptions struct {
	// ContentDisposition is the response-content-disposition override.
	ContentDisposition string
	// ContentType is the response-content-type override.
	ContentType string
}

PresignGetOptions are the response overrides baked into a presigned GET URL, so the object store (not OpenArtifact) answers with the right file name and media type. Empty fields are not signed.

type PresignedPut added in v0.5.0

type PresignedPut struct {
	// URL accepts a single HTTP PUT with the object as the body.
	URL string
	// Headers must be sent with the PUT (signed headers other than Host).
	Headers map[string]string
	// Expires is when the URL stops working.
	Expires time.Time
}

PresignedPut is a presigned upload target.

type Presigner added in v0.5.0

type Presigner interface {
	// PresignGet returns a presigned GET URL for the blob. It returns
	// ErrPresignNotSupported when the backend cannot sign URLs.
	PresignGet(ctx context.Context, sha256 string, ttl time.Duration, opts PresignGetOptions) (string, error)
}

Presigner is implemented by backends that can sign direct-download URLs with response header overrides. BlobStore.PresignURL is the same operation without overrides.

type RangeReader added in v0.11.0

type RangeReader interface {
	// GetFrom returns a reader positioned at offset and running to the end of
	// the blob. An offset of 0 is a plain Get. Wraps ErrBlobNotFound for a
	// missing blob and ErrOffsetOutOfRange when offset is past the end (an
	// offset equal to the size may yield an empty reader or that error).
	GetFrom(ctx context.Context, id string, offset int64) (io.ReadCloser, error)
}

RangeReader is implemented by stores that can open a blob at a byte offset without reading the bytes before it (filesystem seek, S3/GCS/Azure/OCI range GET, and the wrappers around them). Use OpenAt rather than asserting it.

type ReclaimMetadataBlobStore added in v0.15.0

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

ReclaimMetadataBlobStore is the part of the database ReclaimMetadataBlob needs.

type RelayServer added in v0.8.0

type RelayServer interface {
	// RelayHandler serves RelayRoute PUT requests.
	RelayHandler() http.Handler
}

RelayServer is implemented by stores whose staging uploads are relayed through this server.

type ReplicaConfig added in v0.9.0

type ReplicaConfig struct {
	StorageConfig `yaml:",inline"`

	// ReadFallback is what a read does when the primary cannot answer:
	// notfound (the default: the primary says the blob does not exist), error
	// (also when the primary fails) or off (never read from the replica).
	ReadFallback string `yaml:"readFallback"`
	// Interval is the pause between replication passes (queued blobs are also
	// picked up as soon as they are enqueued).
	Interval time.Duration `yaml:"interval"`
	// Batch is how many queued operations one claim takes.
	Batch int `yaml:"batch"`
	// Concurrency is how many blobs are copied at once.
	Concurrency int `yaml:"concurrency"`
	// VerifyInterval is the pause between verify passes; 0 = only on demand
	// (POST /api/v1/admin/storage/replication/verify).
	VerifyInterval time.Duration `yaml:"verifyInterval"`
	// VerifyDeep also hashes the bytes of both copies during a verify pass,
	// instead of comparing existence and size only.
	VerifyDeep bool `yaml:"verifyDeep"`
	// MaxBackoff caps the retry delay of a failing operation.
	MaxBackoff time.Duration `yaml:"maxBackoff"`
}

ReplicaConfig configures asynchronous replication of every blob to a secondary backend (docs/operations/replication.md). The backend itself is described by the same keys as the primary one (storage.type, storage.path, storage.bucket, ...); the presign and upload-relay keys are ignored: a replica is never presigned or uploaded to by clients. Replication is active when type is not empty.

func DefaultReplicaConfig added in v0.9.0

func DefaultReplicaConfig() ReplicaConfig

DefaultReplicaConfig returns the replica settings used when none are given; the backend part is empty, i.e. replication is off.

func (ReplicaConfig) Enabled added in v0.9.0

func (c ReplicaConfig) Enabled() bool

Enabled reports whether a replica is configured.

func (ReplicaConfig) Summary added in v0.9.0

func (c ReplicaConfig) Summary() string

Summary describes where the replica keeps its blobs without any credential: the backend kind and its directory, bucket, container or endpoint host.

type S3BlobStore

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

S3BlobStore implements BlobStore backed by Amazon S3 or any S3-compatible service.

func NewGCSBlobStore

func NewGCSBlobStore(cfg StorageConfig) (*S3BlobStore, error)

NewGCSBlobStore creates a new GCS BlobStore using the S3-compatible XML API. GCS has an S3-compatible XML API that can be accessed via the standard S3 client.

func NewS3BlobStore

func NewS3BlobStore(cfg StorageConfig) (*S3BlobStore, error)

NewS3BlobStore creates a new S3BlobStore from the provided StorageConfig.

func (*S3BlobStore) AppendUpload added in v0.19.0

func (s *S3BlobStore) AppendUpload(
	ctx context.Context,
	id string,
	at UploadPosition,
	r io.Reader,
	commit func(ctx context.Context, state string, n int64) error,
) (err error)

AppendUpload implements UploadStore. The tail is read back first and goes in front of the body. What the body adds up to below minUploadPart (the usual 64 KiB OCI chunk) is stored as the new tail straight from a buffer that grew with it; beyond that the data is cut into parts of s3PartSize sent while it streams, and what is left under minUploadPart is stored as the new tail. Nothing of the old position is touched until commit returned.

func (*S3BlobStore) CompleteMultipart added in v0.8.0

func (s *S3BlobStore) CompleteMultipart(ctx context.Context, id, handle string, size, partSize int64) error

CompleteMultipart lists the uploaded parts, checks them against the plan and completes the S3 multipart upload, which creates the staging object.

func (*S3BlobStore) CompleteUpload added in v0.19.0

func (s *S3BlobStore) CompleteUpload(ctx context.Context, id string, at UploadPosition) (StagedObject, error)

CompleteUpload implements UploadStore. An upload that never reached a part is its tail, copied to the upload key; otherwise the tail becomes the last part and the multipart upload is completed, which is repeatable: once it is gone, the finished object answers.

func (*S3BlobStore) Delete

func (s *S3BlobStore) Delete(ctx context.Context, id string) error

Delete removes a blob by its SHA-256 identifier. NoSuchKey is treated as success.

func (*S3BlobStore) DeleteStaging added in v0.5.0

func (s *S3BlobStore) DeleteStaging(ctx context.Context, id string) error

DeleteStaging removes a staging object and aborts any unfinished multipart upload of it; a missing object is not an error.

func (*S3BlobStore) DeleteUpload added in v0.19.0

func (s *S3BlobStore) DeleteUpload(ctx context.Context, id string) (err error)

DeleteUpload implements UploadStore: the object, the tails and every unfinished multipart upload of the key.

func (*S3BlobStore) Exists

func (s *S3BlobStore) Exists(ctx context.Context, id string) (bool, error)

Exists checks whether a blob exists using HeadObject.

func (*S3BlobStore) ExistsBySHA256

func (s *S3BlobStore) ExistsBySHA256(ctx context.Context, sha256 string) (string, bool, error)

ExistsBySHA256 checks whether a blob with the given SHA-256 hash exists using HeadObject.

func (*S3BlobStore) Get

func (s *S3BlobStore) Get(ctx context.Context, id string) (io.ReadCloser, error)

Get retrieves a blob by its SHA-256 identifier.

func (*S3BlobStore) GetFrom added in v0.11.0

func (s *S3BlobStore) GetFrom(ctx context.Context, id string, offset int64) (io.ReadCloser, error)

GetFrom implements RangeReader with a ranged GetObject.

func (*S3BlobStore) GetMetadata

func (s *S3BlobStore) GetMetadata(ctx context.Context, id string) (map[string]string, error)

GetMetadata returns object metadata via HeadObject. Returns nil, nil if not found.

func (*S3BlobStore) GetSize

func (s *S3BlobStore) GetSize(ctx context.Context, id string) (int64, error)

GetSize returns the size of a blob in bytes using HeadObject.

func (*S3BlobStore) HealthCheck

func (s *S3BlobStore) HealthCheck(ctx context.Context) error

HealthCheck verifies S3 bucket accessibility via HeadBucket.

func (*S3BlobStore) InitiateMultipart added in v0.8.0

func (s *S3BlobStore) InitiateMultipart(ctx context.Context, id string, _, _ int64) (string, error)

InitiateMultipart opens an S3 multipart upload on the staging key and returns its upload id.

func (*S3BlobStore) List

func (s *S3BlobStore) List(ctx context.Context, token string, limit int) ([]string, string, error)

List returns one page of at most limit (capped at 1000) blob ids following token, the last key of the previous page (ListObjectsV2 StartAfter). Keys sort lexicographically, which for the ab/cd/<sha> layout is ascending sha order. Objects whose basename is not a blob id are skipped, so a page may hold fewer than limit ids; keep calling until next is empty.

func (*S3BlobStore) MultipartSupported added in v0.8.0

func (s *S3BlobStore) MultipartSupported() bool

MultipartSupported reports that the S3 backend can stage multipart uploads.

func (*S3BlobStore) OpenStaging added in v0.5.0

func (s *S3BlobStore) OpenStaging(ctx context.Context, id, version string) (io.ReadCloser, error)

OpenStaging reads a staging object, conditional on its ETag.

func (*S3BlobStore) OpenUpload added in v0.19.0

func (s *S3BlobStore) OpenUpload(ctx context.Context, id, version string) (io.ReadCloser, error)

OpenUpload implements UploadStore. The SDK checks the CRC32 of a download against the checksum header of the object, which S3-compatible stores (Garage) report for a multipart object as that of one part; the digest of the blob is verified by the caller anyway. The span covers the request that opens the object, not the reading of its body.

func (*S3BlobStore) PresignGet added in v0.5.0

func (s *S3BlobStore) PresignGet(ctx context.Context, sha256 string, ttl time.Duration, opts PresignGetOptions) (string, error)

PresignGet returns a presigned GetObject URL with a clamped TTL. A TTL <= 0 selects the store's configured presign TTL. The response overrides in opts are part of the signature.

func (*S3BlobStore) PresignStagingPart added in v0.8.0

func (s *S3BlobStore) PresignStagingPart(
	ctx context.Context,
	id, handle string,
	number int,
	length int64,
	ttl time.Duration,
) (PresignedPut, error)

PresignStagingPart returns a presigned UploadPart URL for one part. The part length is part of the signature.

func (*S3BlobStore) PresignStagingPut added in v0.5.0

func (s *S3BlobStore) PresignStagingPut(ctx context.Context, id string, size int64, ttl time.Duration) (PresignedPut, error)

PresignStagingPut returns a presigned PutObject URL for the staging object id. The content length is part of the signature, so the object store itself rejects an upload of a different size.

func (*S3BlobStore) PresignURL

func (s *S3BlobStore) PresignURL(ctx context.Context, sha256 string, ttl time.Duration) (string, error)

PresignURL returns a presigned GetObject URL with a clamped TTL.

func (*S3BlobStore) PromoteStaging added in v0.5.0

func (s *S3BlobStore) PromoteStaging(ctx context.Context, id, sha256, version string, metadata map[string]string) error

PromoteStaging copies a staging object to the content-addressed key with a server-side CopyObject (the bytes never pass through OpenArtifact). The copy is conditional on the staging object still having the ETag that was verified, so an overwrite through the still-valid upload URL after verification cannot put unverified bytes under a content-addressed key. When the blob already exists the copy is skipped: content-addressed objects with the same hash are identical.

func (*S3BlobStore) PromoteUpload added in v0.19.0

func (s *S3BlobStore) PromoteUpload(ctx context.Context, id, sha256, version string, metadata map[string]string) (err error)

PromoteUpload implements UploadStore.

func (*S3BlobStore) Put

func (s *S3BlobStore) Put(ctx context.Context, data io.Reader, metadata map[string]string) (string, error)

Put uploads data to S3. The metadata map must contain a "sha256" key.

func (*S3BlobStore) StagingSupported added in v0.5.0

func (s *S3BlobStore) StagingSupported() bool

StagingSupported reports that the S3 backend has a staging area.

func (*S3BlobStore) StatStaging added in v0.5.0

func (s *S3BlobStore) StatStaging(ctx context.Context, id string) (StagedObject, error)

StatStaging describes a staging object.

func (*S3BlobStore) UploadsSupported added in v0.19.0

func (s *S3BlobStore) UploadsSupported() bool

UploadsSupported implements UploadStore: uploads are objects of the bucket (also on GCS, Garage and SeaweedFS, which share this store).

func (*S3BlobStore) WalkStaging added in v0.5.0

func (s *S3BlobStore) WalkStaging(ctx context.Context, olderThan time.Time, fn func(ids []string) error) error

WalkStaging lists staging objects last modified before olderThan.

func (*S3BlobStore) WalkUploads added in v0.19.0

func (s *S3BlobStore) WalkUploads(ctx context.Context, olderThan time.Time, fn func(ids []string) error) error

WalkUploads implements UploadStore: the objects (the upload, its tails, a chunk of the previous layout) and the unfinished multipart uploads under the upload prefix.

type SafeDeleteBlobStore added in v0.15.0

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

SafeDeleteBlobStore is the part of the database SafeDeleteBlob needs.

type StagedObject added in v0.5.0

type StagedObject struct {
	// Size is the object size in bytes.
	Size int64
	// Version identifies the exact bytes (the object's ETag). It is passed back
	// to OpenStaging and PromoteStaging so that both fail with
	// ErrStagingChanged if the object was overwritten after it was inspected.
	Version string
}

StagedObject describes a staging object as StatStaging saw it.

type StagingForwarder added in v0.15.0

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

StagingForwarder is the staging, multipart staging and resumable upload capability of a store that fronts another one: every call goes to the store target returns. A target without the staging capability answers ErrPresignNotSupported; one without the upload capability reports UploadsSupported false and answers ErrUploadsNotSupported. Uploads are scratch data of in-flight pushes, so they bypass replication, tiering and metrics of the wrapper, except PromoteUpload, which a wrapper overrides to account for the new blob. A wrapper embeds it and overrides the calls it has to intercept.

func NewStagingForwarder added in v0.15.0

func NewStagingForwarder(target func() BlobStore) StagingForwarder

NewStagingForwarder returns a forwarder to the store target returns; target is called on every request, so the store it names may change.

func (StagingForwarder) AppendUpload added in v0.19.0

func (f StagingForwarder) AppendUpload(
	ctx context.Context,
	id string,
	at UploadPosition,
	r io.Reader,
	commit func(ctx context.Context, state string, n int64) error,
) error

AppendUpload implements UploadStore.

func (StagingForwarder) CompleteMultipart added in v0.15.0

func (f StagingForwarder) CompleteMultipart(ctx context.Context, id, handle string, size, partSize int64) error

CompleteMultipart implements MultipartStagingStore.

func (StagingForwarder) CompleteUpload added in v0.19.0

func (f StagingForwarder) CompleteUpload(ctx context.Context, id string, at UploadPosition) (StagedObject, error)

CompleteUpload implements UploadStore.

func (StagingForwarder) DeleteStaging added in v0.15.0

func (f StagingForwarder) DeleteStaging(ctx context.Context, id string) error

DeleteStaging implements StagingStore.

func (StagingForwarder) DeleteUpload added in v0.19.0

func (f StagingForwarder) DeleteUpload(ctx context.Context, id string) error

DeleteUpload implements UploadStore.

func (StagingForwarder) InitiateMultipart added in v0.15.0

func (f StagingForwarder) InitiateMultipart(ctx context.Context, id string, size, partSize int64) (string, error)

InitiateMultipart implements MultipartStagingStore.

func (StagingForwarder) MultipartSupported added in v0.15.0

func (f StagingForwarder) MultipartSupported() bool

MultipartSupported implements MultipartStagingStore.

func (StagingForwarder) OpenStaging added in v0.15.0

func (f StagingForwarder) OpenStaging(ctx context.Context, id, version string) (io.ReadCloser, error)

OpenStaging implements StagingStore.

func (StagingForwarder) OpenUpload added in v0.19.0

func (f StagingForwarder) OpenUpload(ctx context.Context, id, version string) (io.ReadCloser, error)

OpenUpload implements UploadStore.

func (StagingForwarder) PresignStagingPart added in v0.15.0

func (f StagingForwarder) PresignStagingPart(
	ctx context.Context,
	id, handle string,
	number int,
	length int64,
	ttl time.Duration,
) (PresignedPut, error)

PresignStagingPart implements MultipartStagingStore.

func (StagingForwarder) PresignStagingPut added in v0.15.0

func (f StagingForwarder) PresignStagingPut(ctx context.Context, id string, size int64, ttl time.Duration) (PresignedPut, error)

PresignStagingPut implements StagingStore.

func (StagingForwarder) PromoteStaging added in v0.15.0

func (f StagingForwarder) PromoteStaging(ctx context.Context, id, sha256, version string, metadata map[string]string) error

PromoteStaging implements StagingStore.

func (StagingForwarder) PromoteUpload added in v0.19.0

func (f StagingForwarder) PromoteUpload(ctx context.Context, id, sha256, version string, metadata map[string]string) error

PromoteUpload implements UploadStore.

func (StagingForwarder) StagingSupported added in v0.15.0

func (f StagingForwarder) StagingSupported() bool

StagingSupported implements StagingStore.

func (StagingForwarder) StatStaging added in v0.15.0

func (f StagingForwarder) StatStaging(ctx context.Context, id string) (StagedObject, error)

StatStaging implements StagingStore.

func (StagingForwarder) UploadsSupported added in v0.19.0

func (f StagingForwarder) UploadsSupported() bool

UploadsSupported implements UploadStore.

func (StagingForwarder) WalkStaging added in v0.15.0

func (f StagingForwarder) WalkStaging(ctx context.Context, olderThan time.Time, fn func(ids []string) error) error

WalkStaging implements StagingStore.

func (StagingForwarder) WalkUploads added in v0.19.0

func (f StagingForwarder) WalkUploads(ctx context.Context, olderThan time.Time, fn func(ids []string) error) error

WalkUploads implements UploadStore.

type StagingStore added in v0.5.0

type StagingStore interface {
	// StagingSupported reports whether the backend has a staging area. The
	// remaining methods return ErrPresignNotSupported when it does not.
	StagingSupported() bool

	// PresignStagingPut returns a URL the client PUTs exactly size bytes to.
	PresignStagingPut(ctx context.Context, id string, size int64, ttl time.Duration) (PresignedPut, error)

	// StatStaging describes the staging object, or returns ErrStagingNotFound.
	StatStaging(ctx context.Context, id string) (StagedObject, error)

	// OpenStaging reads the staging object. It returns ErrStagingNotFound when
	// there is none and ErrStagingChanged when it is no longer version.
	OpenStaging(ctx context.Context, id, version string) (io.ReadCloser, error)

	// PromoteStaging copies version of the staging object to the
	// content-addressed blob sha256 (a no-op when the blob already exists). It
	// returns ErrStagingChanged, copying nothing, when the staging object is no
	// longer version. The staging object is left in place; the caller deletes
	// it with DeleteStaging once the blob is referenced.
	PromoteStaging(ctx context.Context, id, sha256, version string, metadata map[string]string) error

	// DeleteStaging removes the staging object. A missing object is not an error.
	DeleteStaging(ctx context.Context, id string) error

	// WalkStaging calls fn with the ids of staging objects last modified before
	// olderThan, in batches, until fn returns an error or the objects run out.
	// Keys under the staging prefix that are not staging ids are skipped.
	WalkStaging(ctx context.Context, olderThan time.Time, fn func(ids []string) error) error
}

StagingStore is implemented by backends that accept client-direct uploads into a staging area and can promote a verified staging object to its content-addressed place. Staging ids are UUIDs generated by the server.

The client keeps a working PUT URL for the whole upload TTL, so a staging object is never trusted by id alone: verification reads exactly the version StatStaging returned, and promotion copies exactly that version.

type StorageConfig

type StorageConfig struct {
	// Type selects the storage backend: filesystem, s3, gcs, azure, garage,
	// seaweedfs or oci. garage and seaweedfs reuse the S3 client with
	// path-style addressing forced on.
	Type string `yaml:"type"`
	// Endpoint is the endpoint URL of an S3-compatible service (s3, garage,
	// seaweedfs) or the URL of the OCI registry.
	Endpoint string `yaml:"endpoint"`
	// Bucket is the bucket name (s3, garage, seaweedfs) or the OCI repository
	// prefix.
	Bucket string `yaml:"bucket"`
	// Region is the AWS region or equivalent.
	Region string `yaml:"region"`
	// AccessKey is the S3 access key. It is used only when both keys are set,
	// otherwise the AWS credential chain applies.
	AccessKey string `yaml:"accessKey"`
	// SecretKey is the S3 secret key.
	SecretKey string `yaml:"secretKey"`
	// Path is the directory of the filesystem backend.
	Path string `yaml:"path"`
	// Options are free-form backend options. The environment form is
	// comma-separated key=value pairs, merged over the YAML keys. None of the
	// built-in backends reads any key yet.
	Options map[string]string `yaml:"options"`
	// ForcePathStyle uses path-style S3 addressing (required for MinIO, Garage
	// and SeaweedFS).
	ForcePathStyle bool `yaml:"forcePathStyle"`
	// PresignTTL is the lifetime of presigned download URLs (s3, gcs), clamped
	// to 1m-1h. It only applies while presignDownloads is on.
	PresignTTL time.Duration `yaml:"presignTtl"`
	// PresignUploadTTL is the lifetime of presigned PUT upload URLs, clamped to
	// 1m-12h.
	PresignUploadTTL time.Duration `yaml:"presignUploadTtl"`
	// PresignMaxPendingUploads is how many outstanding (not completed, not
	// expired) presigned uploads one user may hold; 0 means unlimited. Beyond
	// it, creating an upload answers 429.
	PresignMaxPendingUploads int `yaml:"presignMaxPendingUploads"`
	// PresignDownloads answers blob downloads with a 307 redirect to a
	// presigned URL (s3 and gcs only) instead of streaming them. A repository
	// can override it with presign_downloads.
	PresignDownloads bool `yaml:"presignDownloads"`
	// PresignMinSize is the size in bytes below which blobs are always
	// streamed; 0 redirects everything and a negative value is rejected at
	// startup.
	PresignMinSize int64 `yaml:"presignMinSize"`
	// PresignEndpoint is the public base URL (absolute http(s), no query or
	// fragment) that presigned URLs are signed against (S3 family); empty uses
	// the endpoint. Set it when the endpoint is not reachable by clients.
	PresignEndpoint string `yaml:"presignEndpoint"`
	// GCSBucket is the GCS bucket (reached through the S3-compatible XML API).
	GCSBucket string `yaml:"gcsBucket"`
	// GCSHMACKey is the GCS HMAC access key (required for gcs).
	GCSHMACKey string `yaml:"gcsHmacKey"`
	// GCSHMACSecret is the GCS HMAC secret.
	GCSHMACSecret string `yaml:"gcsHmacSecret"`
	// AzureAccountName is the Azure storage account name.
	AzureAccountName string `yaml:"azureAccountName"`
	// AzureAccountKey is the Azure storage account key.
	AzureAccountKey string `yaml:"azureAccountKey"`
	// AzureContainerName is the Azure container name.
	AzureContainerName string `yaml:"azureContainerName"`
	// AzureEndpoint is the blob service URL, for Azurite or a sovereign cloud;
	// empty uses https://<account>.blob.core.windows.net.
	AzureEndpoint string `yaml:"azureEndpoint"`
	// StagingPath is the spool directory for server-relayed presigned uploads
	// on oci storage (filesystem uses <path>/staging). Required for oci when
	// uploads are relayed (it also holds the relay signing key); use a
	// persistent directory.
	StagingPath string `yaml:"stagingPath"`
	// SpoolPath is the directory where s3, azure and oci spool a blob to disk
	// while verifying it before the upload; leftovers of a crash are swept from
	// it at startup. Empty means the system temp dir (not swept).
	SpoolPath string `yaml:"spoolPath"`
	// PublicURL is the public base URL of this server (BASE_URL) when the
	// operator set one, filled in by the config loader; server-relayed upload
	// URLs point at it.
	PublicURL string `yaml:"-"`
	// PublicURLFromRequest, set by the config loader when no BASE_URL is
	// configured, lets server-relayed upload URLs point at the origin of the
	// request that asks for them (internal/publicurl) instead of PublicURL.
	PublicURLFromRequest bool `yaml:"-"`
	// SafeDial makes every outbound connection of the backend go through
	// netutil.GuardTransport: loopback, private, link-local and cloud-metadata
	// addresses are refused when the connection is made (so DNS rebinding
	// cannot beat the check at save time), the private ones unless
	// OPENARTIFACT_ALLOW_PRIVATE_UPSTREAMS=true. It is set for backends
	// defined through the admin API and the database; the storage section of
	// the operator's own config file is trusted and dials unrestricted.
	SafeDial bool `yaml:"-"`
	// OCIInsecure allows plain HTTP to the OCI registry (dev and testing only).
	OCIInsecure bool `yaml:"ociInsecure"`
	// OCIUsername is the OCI registry user.
	OCIUsername string `yaml:"ociUsername"`
	// OCIPassword is the OCI registry password.
	OCIPassword string `yaml:"ociPassword"`
}

StorageConfig contains configuration for blob storage.

type StoreError added in v0.10.0

type StoreError struct {
	SHA256 string
	// Op is "check" for a failed existence check and "store" for a failed Put.
	Op  string
	Err error
}

StoreError is the error CommitBlobs returns when it could not look up or store a blob (as opposed to an error returned by the caller's commit function, which is passed through unchanged).

func (*StoreError) Error added in v0.10.0

func (e *StoreError) Error() string

func (*StoreError) Unwrap added in v0.10.0

func (e *StoreError) Unwrap() error

type UploadPosition added in v0.19.0

type UploadPosition struct {
	State  string
	Offset int64
}

UploadPosition is where a resumable upload stands: Offset bytes are stored, and State is the opaque, backend-specific token AppendUpload last handed to its commit callback ("" for a new upload). The caller persists both together, atomically, and passes them back unchanged.

type UploadStore added in v0.19.0

type UploadStore interface {
	// UploadsSupported reports whether the backend can hold uploads; the other
	// methods return ErrUploadsNotSupported when it cannot.
	UploadsSupported() bool

	// AppendUpload appends the bytes of r to upload id, which stands at at.
	// Once r ended and it delivered n > 0 bytes, the store calls commit with
	// the new State and n; commit makes the new position durable (the caller
	// stores it) and returns nil on success. Only after commit returned nil does
	// the store drop what the new position supersedes, so a failure (of the
	// read, the write or commit itself) leaves the upload at the position the
	// caller still holds: the append is simply retried from there. Bytes the
	// store accepted of a failed append are overwritten by the retry. When r
	// delivers no bytes commit is not called. ErrUploadDataLost when the stored
	// data does not match at.
	AppendUpload(
		ctx context.Context,
		id string,
		at UploadPosition,
		r io.Reader,
		commit func(ctx context.Context, state string, n int64) error,
	) error

	// CompleteUpload makes the upload one object holding exactly at.Offset
	// bytes and returns its size and version (the value PromoteUpload and
	// OpenUpload check, so an object overwritten after the digest was verified
	// is refused). Calling it again for the same position is fine.
	// ErrUploadDataLost when the stored data does not match at.
	CompleteUpload(ctx context.Context, id string, at UploadPosition) (StagedObject, error)

	// PromoteUpload makes the completed upload (exactly version) the blob with
	// the given sha256, without the bytes passing through the server where the
	// backend can; an existing blob is left untouched. ErrStagingChanged when
	// the object is not version any more, ErrStagingNotFound when it is gone,
	// ErrPromoteNotSupported when the backend cannot promote in place.
	PromoteUpload(ctx context.Context, id, sha256, version string, metadata map[string]string) error

	// OpenUpload reads the completed upload, conditional on version
	// (ErrStagingChanged / ErrStagingNotFound like PromoteUpload).
	OpenUpload(ctx context.Context, id, version string) (io.ReadCloser, error)

	// DeleteUpload removes everything stored for the upload, completed or not,
	// including unfinished multipart uploads. Missing data is not an error.
	DeleteUpload(ctx context.Context, id string) error

	// WalkUploads calls fn with the ids of uploads that have stored data last
	// modified (or, for an unfinished multipart upload, started) before
	// olderThan, in batches, until fn returns an error or the uploads run out.
	// An id may be reported more than once. Entries that are not upload ids
	// are skipped.
	WalkUploads(ctx context.Context, olderThan time.Time, fn func(ids []string) error) error
}

UploadStore holds the data of resumable uploads (the chunked OCI blob upload): one growing object per upload, outside the content-addressed blob namespace (it is never listed as a blob, deduplicated or replicated), visible to every replica that shares the blob store.

The store is not told what the bytes are; the caller hashes them as they stream through and keeps the running digest next to the position. The caller guarantees that at most one request works on an upload at a time (a lease in the database), so the store needs no locking of its own.

Upload ids are UUIDs generated by the server.

func NewDirUploadStore added in v0.19.0

func NewDirUploadStore(dir string) UploadStore

NewDirUploadStore returns an upload store over the directory dir (created on first use). PromoteUpload is not supported: the upload is not on the blob store's filesystem, so the caller streams it into BlobStore.Put.

func UploadsFor added in v0.19.0

func UploadsFor(store BlobStore, fallbackDir string) UploadStore

UploadsFor returns the upload store of a blob store: the store itself when it can hold uploads (filesystem, S3 and its relatives, Azure; shared by every replica that shares the blob store), otherwise a directory on this host, fallbackDir, which only the replica that wrote to it can read back.

type VerifiedFile added in v0.19.0

type VerifiedFile interface {
	io.Reader
	VerifiedFile() (path, sha256 string, size int64, ok bool)
}

VerifiedFile is implemented by a Put reader that is the whole, unread content of a file whose SHA-256 was computed while the file was written (the upload spool). A backend that sees one skips the second spool-and-hash pass: the filesystem store links the file into place, the object stores upload it directly. VerifiedFile returns the file's path, its SHA-256 and size; ok is false when the reader is partly read or has no file behind it, and a store then reads it like any other reader. The file must stay unchanged for the duration of the Put.

Jump to

Keyboard shortcuts

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