replication

package
v0.13.2 Latest Latest
Warning

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

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

Overview

Package replication copies every blob of the primary store to a secondary backend asynchronously, applies deletions to it, verifies that both sides agree and lets reads fall back to the replica (docs/operations/replication.md).

The pieces share one core: Store wraps the primary (tiered) store and queues work in the durable blob_replication table, Replicator works the queue off, Verifier walks both sides and repairs what is missing or damaged, and Service ties them together for the server.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMissingPrimary is the failure of a queued copy whose blob is not on
	// the primary store.
	ErrMissingPrimary = errors.New("blob is missing from the primary store")

	// ErrCorrupt is returned when no side holds bytes that hash to the blob id.
	ErrCorrupt = errors.New("no copy of the blob matches its sha256")
)

Functions

This section is empty.

Types

type Config

type Config struct {
	// Primary is the store clients read and write: the tiered store.
	Primary storage.BlobStore
	// Replica is the secondary backend.
	Replica storage.BlobStore
	// Queue is the durable queue and state (the PostgresDB).
	Queue database.BlobReplicationStore
	// SQLDB is the pool the verify lock's pinned connection comes from; nil
	// disables the lock (a single replica).
	SQLDB *sql.DB
	// Lock is the per-blob lock (storage.WithBlobLock); nil runs without one.
	Lock LockFunc
	// Info describes the replica for the status endpoint.
	Info ReplicaInfo
	// Options tune the workers.
	Options Options
	// Metrics may be nil.
	Metrics *metrics.ReplicationMetrics
	Log     *logger.Logger
}

Config is what New needs.

type Fallback

type Fallback string

Fallback is the read fallback mode (storage.ReadFallback*).

type LockFunc

type LockFunc func(ctx context.Context, sha string, fn func(ctx context.Context) error) error

LockFunc runs fn under the per-blob lock uploaders and deleters share (storage.WithBlobLock).

type Options

type Options struct {
	ReadFallback   Fallback
	Interval       time.Duration
	Batch          int
	Concurrency    int
	VerifyInterval time.Duration
	VerifyDeep     bool
	MaxBackoff     time.Duration
}

Options tunes replication. The zero value is not usable: take it from OptionsFromConfig.

func OptionsFromConfig

func OptionsFromConfig(c storage.ReplicaConfig) Options

OptionsFromConfig converts the storage.replica settings.

type ReplicaInfo

type ReplicaInfo struct {
	Type     string `json:"type"`
	Location string `json:"location"`
}

ReplicaInfo is the credential-free description of the replica.

type Replicator

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

Replicator works the replication queue off: it claims due operations, copies blobs to the replica and applies deletions to it, retrying failures with exponential backoff. Several replicas can run it: the queue hands every operation to one worker at a time.

func (*Replicator) RefreshStats

func (r *Replicator) RefreshStats(ctx context.Context)

RefreshStats updates the backlog gauges from the queue.

func (*Replicator) RunOnce

func (r *Replicator) RunOnce(ctx context.Context) (int, error)

RunOnce claims one batch of due operations and works them off with the configured concurrency. It returns how many it claimed.

func (*Replicator) Start

func (r *Replicator) Start()

Start begins working the queue. Only the first call counts.

func (*Replicator) Stop

func (r *Replicator) Stop()

Stop stops claiming, lets in-flight copies finish for a grace period, then cancels them (their operations stay queued and their claims expire) and waits for the loop to end. It is idempotent and safe without Start.

type Service

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

Service ties the replicating store, the queue worker, the verifier and the read repair together.

func New

func New(cfg Config) (*Service, error)

New assembles the replication service. Nothing runs until Start.

func (*Service) Replicator

func (s *Service) Replicator() *Replicator

Replicator returns the queue worker.

func (*Service) RequestVerify

func (s *Service) RequestVerify(ctx context.Context) (bool, error)

RequestVerify asks for a verify pass; false when one is already running or requested.

func (*Service) Start

func (s *Service) Start()

Start launches the queue worker, the verifier and the read repair.

func (*Service) Status

func (s *Service) Status(ctx context.Context) (Status, error)

Status reads the queue and the shared state.

func (*Service) Stop

func (s *Service) Stop()

Stop ends the loops: the queue worker finishes the copies in flight (up to a grace period) and leaves the rest queued. It is idempotent.

func (*Service) Store

func (s *Service) Store() *Store

Store returns the blob store to give the server: the primary store plus replication.

func (*Service) Verifier

func (s *Service) Verifier() *Verifier

Verifier returns the verifier.

type Status

type Status struct {
	Enabled      bool        `json:"enabled"`
	Replica      ReplicaInfo `json:"replica"`
	ReadFallback string      `json:"read_fallback"`

	BacklogCopy          int64   `json:"backlog_copy"`
	BacklogDelete        int64   `json:"backlog_delete"`
	OldestPendingSeconds float64 `json:"oldest_pending_age_seconds"`
	// Failing is the number of queued operations that failed repeatedly.
	Failing int64 `json:"failing"`

	ReplicatedTotal int64      `json:"replicated_total"`
	ReplicatedBytes int64      `json:"replicated_bytes_total"`
	LastError       string     `json:"last_error,omitempty"`
	LastErrorAt     *time.Time `json:"last_error_at,omitempty"`

	VerifyRequested bool          `json:"verify_requested"`
	VerifyRunning   *VerifyResult `json:"verify_running,omitempty"`
	LastVerify      *VerifyResult `json:"last_verify,omitempty"`
}

Status is the replication state the admin API reports.

type Store

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

Store is the blob store the server uses when a replica is configured. It wraps the primary (tiered) store: every blob written through it is queued for copying, every deletion for deletion on the replica, and reads the primary cannot answer are served from the replica (and repaired on the primary). Writing and deleting never wait for the replica.

func (*Store) CompleteMultipart

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

CompleteMultipart implements storage.MultipartStagingStore. It only assembles the staging object; the blob (and its queued copy) comes with PromoteStaging.

func (*Store) Delete

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

Delete removes the blob from the primary store and queues the deletion of its replica copy. The replica copy outlives the primary one until the deletion is applied; the worker skips it when the blob is back or still referenced. A failure to queue is returned so the caller retries the delete.

func (*Store) DeleteCopy

func (s *Store) DeleteCopy(ctx context.Context, backendID, id string) error

DeleteCopy removes the copy of a blob one storage backend holds (a retired tier copy). The replica is not touched: the blob itself still exists.

func (*Store) DeleteStaging

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

DeleteStaging implements storage.StagingStore.

func (*Store) Exists

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

Exists reports whether the blob is on the primary store or, failing that, on the replica. A hit on the replica queues the primary's repair: callers skip their upload when the blob "exists", so a blob only the replica has would otherwise never be written back.

func (*Store) ExistsBySHA256

func (s *Store) ExistsBySHA256(ctx context.Context, sha string) (string, bool, error)

ExistsBySHA256 looks the blob up on the primary store, then on the replica.

func (*Store) Get

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

Get reads the blob from the primary store, from the replica when it is not there (see Options.ReadFallback).

func (*Store) GetFrom added in v0.11.0

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

GetFrom is Get from a byte offset (storage.RangeReader), with the same replica fallback.

func (*Store) GetMetadata

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

GetMetadata returns the blob's metadata from the primary store or the replica.

func (*Store) GetSize

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

GetSize returns the blob's size from the primary store or the replica.

func (*Store) HealthCheck added in v0.13.0

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

HealthCheck probes the primary side. The replica is not part of it: a down replica degrades redundancy, not serving, and its state is on the replication admin endpoints.

func (*Store) InitiateMultipart

func (s *Store) InitiateMultipart(ctx context.Context, id string, size, partSize int64) (string, error)

InitiateMultipart implements storage.MultipartStagingStore.

func (*Store) List

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

List lists the primary store; the replica is never consulted.

func (*Store) MultipartSupported

func (s *Store) MultipartSupported() bool

MultipartSupported implements storage.MultipartStagingStore.

func (*Store) OpenStaging

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

OpenStaging implements storage.StagingStore.

func (*Store) PresignGet

func (s *Store) PresignGet(ctx context.Context, sha string, ttl time.Duration, opts storage.PresignGetOptions) (string, error)

PresignGet implements storage.Presigner.

func (*Store) PresignStagingPart

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

PresignStagingPart implements storage.MultipartStagingStore.

func (*Store) PresignStagingPut

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

PresignStagingPut implements storage.StagingStore.

func (*Store) PresignURL

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

PresignURL implements storage.BlobStore.

func (*Store) PromoteStaging

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

PromoteStaging promotes the staged upload to its blob and queues the copy: this is where a client-direct upload becomes a blob.

func (*Store) Put

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

Put writes the blob to the primary store and queues its copy.

func (*Store) StagingSupported

func (s *Store) StagingSupported() bool

StagingSupported implements storage.StagingStore.

func (*Store) StatStaging

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

StatStaging implements storage.StagingStore.

func (*Store) WalkStaging

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

WalkStaging implements storage.StagingStore.

type Verifier

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

Verifier compares the primary store with the replica and repairs the differences: a blob missing from the replica is queued for copying, one missing from the primary (and still referenced) is restored from the replica, one with different bytes is rewritten from the side that hashes right. A pass walks both listings in id order and keeps its place in the database, so it survives restarts and runs on one replica at a time.

func (*Verifier) RequestRun

func (v *Verifier) RequestRun(ctx context.Context) (bool, error)

RequestRun asks for a verify pass; false when one is running or requested.

func (*Verifier) Tick

func (v *Verifier) Tick(ctx context.Context) error

Tick does one slice of verification work: it takes the cluster-wide lock, starts a pass when one was requested or is due, and works on the running one until it finishes or the time budget is spent. Without the lock (another replica is verifying) it does nothing.

type VerifyResult

type VerifyResult struct {
	StartedAt  time.Time  `json:"started_at"`
	FinishedAt *time.Time `json:"finished_at,omitempty"`
	// Deep is true when the bytes of both copies were hashed.
	Deep bool `json:"deep"`
	// Listing is "list" (the primary store was enumerated) or "database" (it
	// cannot list, so the blobs table was walked).
	Listing string `json:"listing,omitempty"`
	// ReplicaListed is false when the replica cannot enumerate its objects, so
	// blobs only it holds are not found.
	ReplicaListed bool `json:"replica_listed"`

	// Checked is the number of blobs examined.
	Checked int64 `json:"checked"`
	// MissingReplica blobs were not on the replica (a copy is queued).
	MissingReplica int64 `json:"missing_replica"`
	// MissingPrimary blobs were not on the primary store (restored from the replica).
	MissingPrimary int64 `json:"missing_primary"`
	// Mismatched blobs had different sizes (or, deep, contents) on the sides.
	Mismatched int64 `json:"mismatched"`
	// Repaired blobs were fixed or queued for copying.
	Repaired int64 `json:"repaired"`
	// Unreferenced blobs exist only on the replica and nothing needs them:
	// reported, never restored.
	Unreferenced int64 `json:"unreferenced"`
	// Lost blobs are referenced but exist on neither side.
	Lost int64 `json:"lost"`
	// Errors blobs could not be checked or repaired.
	Errors int64 `json:"errors"`
}

VerifyResult is the outcome (or, while running, the progress) of a verify pass. It is stored as JSON in blob_replication_state.

Jump to

Keyboard shortcuts

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