Documentation
¶
Overview ¶
Package federation replicates the artifacts of a repository between OpenArtifact instances (docs/design/federation.md): every member keeps an event log of its changes, written transactionally with them, and pulls the logs of its peers.
Index ¶
- Constants
- Variables
- func Backoff(n int, poll, maxDelay time.Duration) time.Duration
- func Describe(err error) string
- func GenerateToken() (string, error)
- func HashToken(plain string) []byte
- func StoredReason(stored string) string
- func ValidVEXTrust(s string) bool
- func ValidatePeerTLS(caPEM, clientCert, clientKey string) error
- func ValidatePeerURL(ctx context.Context, raw string) error
- type ArtifactInfo
- type BlobRef
- type BlobStream
- type Change
- type Client
- func (c *Client) Blob(ctx context.Context, unitKey, sha256 string, from int64) (*BlobStream, error)
- func (c *Client) Info(ctx context.Context) (*InfoResponse, error)
- func (c *Client) Log(ctx context.Context, after int64, limit int) (*LogResponse, error)
- func (c *Client) Unit(ctx context.Context, key string) (*UnitResponse, error)
- func (c *Client) VEX(ctx context.Context) ([]byte, error)
- type Codec
- type Content
- type Deferred
- type Engine
- type Entry
- type HTTPError
- type InfoResponse
- type LogResponse
- type Metrics
- type NewPeer
- type Notifier
- type Options
- type OptionsStore
- type Peer
- type PeerMetric
- type PeerPatch
- type PeerSecrets
- type PeerState
- type Progress
- type Querier
- type Regen
- type RepoInfo
- type RepoState
- type Reservation
- type Server
- type Stamp
- type Store
- func (s *Store) AuthenticateToken(ctx context.Context, plain string) (string, error)
- func (s *Store) ClearDeferred(ctx context.Context, peerID, key string) error
- func (s *Store) Counts(ctx context.Context, repoID string) (int64, int64, error)
- func (s *Store) CreatePeer(ctx context.Context, n NewPeer) (*Peer, error)
- func (s *Store) CreateToken(ctx context.Context, repoID, name, createdBy string) (*Token, string, error)
- func (s *Store) Defer(ctx context.Context, peerID, key string, seq int64, reason string, cause error) error
- func (s *Store) DeletePeer(ctx context.Context, repoID, id string) error
- func (s *Store) Disable(ctx context.Context, repoID string) error
- func (s *Store) DuePeers(ctx context.Context, poll time.Duration) ([]*Peer, error)
- func (s *Store) Enable(ctx context.Context, repoID, format string) error
- func (s *Store) GetEntry(ctx context.Context, q Querier, repoID, key string) (*Entry, error)
- func (s *Store) GetPeer(ctx context.Context, repoID, id string) (*Peer, error)
- func (s *Store) InstanceID(ctx context.Context) (uuid.UUID, error)
- func (s *Store) ListDeferred(ctx context.Context, peerID string, dueOnly bool, limit int) ([]Deferred, error)
- func (s *Store) ListEntries(ctx context.Context, repoID string, after int64, limit int) ([]Entry, error)
- func (s *Store) ListPeers(ctx context.Context, repoID string) ([]*Peer, error)
- func (s *Store) ListTokens(ctx context.Context, repoID string) ([]*Token, error)
- func (s *Store) MarkAttempt(ctx context.Context, id string) error
- func (s *Store) MarkFailure(ctx context.Context, id string, cause error, retryIn time.Duration) error
- func (s *Store) MarkSuccess(ctx context.Context, id string) error
- func (s *Store) MarkVEXSync(ctx context.Context, peerID string, syncErr error) error
- func (s *Store) PeerMetrics(ctx context.Context) ([]PeerMetric, error)
- func (s *Store) PurgeTombstones(ctx context.Context, retention time.Duration) (int64, error)
- func (s *Store) RepoBlobSizes(ctx context.Context, repoID string, shas []string) (map[string]int64, error)
- func (s *Store) RepoByID(ctx context.Context, repoID string) (*RepoInfo, error)
- func (s *Store) RepoState(ctx context.Context, repoID string) (*RepoState, error)
- func (s *Store) RequestResync(ctx context.Context, repoID, id string) error
- func (s *Store) RevokeToken(ctx context.Context, repoID, id string) error
- func (s *Store) SaveProgress(ctx context.Context, id string, p Progress) error
- func (s *Store) SetVEXPublish(ctx context.Context, repoID string, on bool) error
- func (s *Store) TrashRetentionDays(ctx context.Context, q Querier, repoID string, def int) (int, error)
- func (s *Store) UpdatePeer(ctx context.Context, repoID, id string, patch PeerPatch) (*Peer, error)
- type Token
- type UnitResponse
- type VEXPublisher
- type VEXReceiver
- type Worker
Constants ¶
const ( ReasonUnreachable = "unreachable" ReasonTimeout = "timeout" ReasonTLS = "tls" ReasonNotFound = "not_found" ReasonRateLimited = "rate_limited" ReasonUpstreamError = "upstream_error" ReasonProtocolMismatch = "protocol_mismatch" ReasonBlockedAddress = "blocked_address" ReasonInvalidConfig = "invalid_config" ReasonInvalidResponse = "invalid_response" ReasonInvalidUnit = "invalid_unit" ReasonQuarantined = "quarantined" ReasonDependency = "dependency_unavailable" ReasonBlobRejected = "blob_rejected" ReasonBlobGone = "blob_gone" ReasonClockSkew = "clock_skew" ReasonQuotaExceeded = "quota_exceeded" ReasonCanceled = "canceled" ReasonInternal = "internal_error" )
The reasons stored in federation_peers.last_error and federation_deferred.last_error, and so returned by the API. The vocabulary is fixed: a failure is reduced to one of these (plus the HTTP status of the peer's answer when it gave one), never to text of the peer, the network stack or the database. The cause is logged instead.
const ( // DefaultMaxPartialBytes caps the partial downloads kept between pulls. DefaultMaxPartialBytes int64 = 10 << 30 // DefaultMaxPartialAge is how long an untouched partial download is kept. DefaultMaxPartialAge = 24 * time.Hour // DefaultSpoolDirName is the directory under the OS temp dir used when no // spool directory is configured. DefaultSpoolDirName = "openartifact-federation" )
const ( KindArtifact = "artifact" KindRef = "ref" )
Unit kinds. An artifact unit owns content; a ref unit points at another unit (a tag at a version or a manifest) and moves.
const ( EventArtifactAdded = "artifact_added" EventArtifactDeleted = "artifact_deleted" EventRefMoved = "ref_moved" EventMetadataChanged = "metadata_changed" )
Event names logged for a unit.
const ( // VEXTrustIgnore fetches nothing. VEXTrustIgnore = "ignore" // VEXTrustSuggest keeps the decisions as pending suggestions. VEXTrustSuggest = "suggest" // VEXTrustApply applies the decisions where no other statement exists. VEXTrustApply = "apply" )
VEX trust of a peer: what happens to the VEX decisions it publishes.
const ( // DefaultMaxClockSkew is how far ahead of the local clock the wall time of // a peer's stamp may be (federation.maxClockSkew). The clock of a // repository never goes back, so one stamp from the far future would make // every later local change of the repository carry it and win against the // changes of every other member. DefaultMaxClockSkew = 5 * time.Minute )
const ProtocolVersion = 2
ProtocolVersion is the version of the pull protocol this build speaks.
Version 2 replicates the rows of the generic package tables (packages, package_versions, package_files, package_tags and the format's side tables) with one codec for every format but docker; version 1 carried the per-format tables of releases before 0.15 and is not understood any more.
const TokenPrefix = "oafed_"
TokenPrefix starts every peer token, so a leaked one is recognisable and secret scanners can match it.
Variables ¶
var ( // ErrUnsupportedFormat means the repository format has no federation codec. ErrUnsupportedFormat = errors.New("federation does not support this repository format") // ErrNotFederated means the repository is not federated. ErrNotFederated = errors.New("repository is not federated") // ErrNotFound means a peer, token or unit does not exist. ErrNotFound = errors.New("not found") // ErrConflict means the request conflicts with existing state (duplicate peer name). ErrConflict = errors.New("conflict") // ErrStale means an incoming change lost against a newer local stamp; the // engine drops it. ErrStale = errors.New("stale unit") // ErrQuarantined means the origin refuses to serve the unit (HTTP 423). ErrQuarantined = errors.New("unit is quarantined at the origin") // ErrInvalid means a request failed validation (message is client-safe). ErrInvalid = errors.New("invalid") )
Functions ¶
func Backoff ¶
Backoff is the delay before retry n (0-based) of a failing peer: doubling from the base up to max, with +-20% jitter. A peer is never given up on.
func Describe ¶ added in v0.15.0
Describe classifies a failure for storage and display: a reason of the fixed vocabulary, followed by "(HTTP <status>)" when a peer answered with a status.
func GenerateToken ¶
GenerateToken returns a new random peer token.
func StoredReason ¶ added in v0.15.0
StoredReason makes a stored last_error safe to return: values written by Describe pass through, anything else (rows written before the vocabulary existed hold raw upstream text) becomes the generic upstream_error.
func ValidVEXTrust ¶ added in v0.22.0
ValidVEXTrust reports whether s is a VEX trust level.
func ValidatePeerTLS ¶
ValidatePeerTLS checks the optional TLS settings of a peer: a CA bundle, and a client certificate that must come with its key.
Types ¶
type ArtifactInfo ¶
ArtifactInfo describes a unit for webhooks and audit.
type BlobRef ¶
type BlobRef struct {
SHA256 string `json:"sha256"`
Size int64 `json:"size"`
MediaType string `json:"media_type,omitempty"`
}
BlobRef names a blob a unit references by content hash.
type BlobStream ¶ added in v0.11.0
type BlobStream struct {
// Body streams the blob from Offset to its end; the caller closes it.
Body io.ReadCloser
// Offset is the position in the blob of the first byte of Body: the
// offset that was asked for when the peer honoured the range, 0 when it
// answered with the whole blob.
Offset int64
}
BlobStream is an open blob response.
type Change ¶
type Change struct {
// Replaced is true when a live row of the unit existed and was updated in
// place; its previous usage is ReplacedSize/ReplacedCount.
Replaced bool
ReplacedSize int64
ReplacedCount int
// RemovedSize/RemovedCount is the usage of the row a Delete removed.
RemovedSize int64
RemovedCount int
// ReleasedBlobs lists sha256 digests that lost a reference (candidates for
// storage.SafeDeleteBlob once the transaction committed). A soft delete
// releases none: the trash keeps its blobs.
ReleasedBlobs []string
// Regen lists the metadata refreshes to queue.
Regen []Regen
// Artifact describes the unit; nil for a unit without a webhook event
// (a tag, a package-level reference).
Artifact *ArtifactInfo
// Missing is true when Delete found no live row (nothing to do).
Missing bool
}
Change reports what applying or deleting a unit did, for the engine's post-commit work (quota, blob cleanup, metadata regeneration, webhooks).
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client talks to the peer endpoints of one remote member.
func NewClient ¶
func NewClient(ctx context.Context, p *Peer, secrets PeerSecrets, timeout time.Duration) (*Client, error)
NewClient builds an SSRF-guarded client for a peer. The peer's CA (when set) replaces the system roots for this peer only, and its client certificate is presented for mutual TLS.
func (*Client) Blob ¶
Blob opens the content of a blob of a unit, from byte offset from on when the peer supports ranges (from <= 0 reads it whole). A peer that ignores the range answers with the full blob and Offset 0 tells the caller so.
func (*Client) Info ¶
func (c *Client) Info(ctx context.Context) (*InfoResponse, error)
Info fetches the peer's log identity and head.
type Codec ¶
type Codec interface {
// Export reads the live state of a unit. It returns (nil, nil) when the
// unit has no live row (never existed, or deleted).
Export(ctx context.Context, q Querier, repoID, key string) (*Content, error)
// Usage is the storage usage the unit adds to the repository's quota, as
// the reservations to make before applying it (see Reservation). Files the
// repository already holds with the same blob are not new usage.
Usage(ctx context.Context, q Querier, repoID, key string, c *Content) ([]Reservation, error)
// Import writes the unit as a live row, updating the live row of the same
// key in place when there is one. All blobs of c exist in the blob store
// and in the blobs table; blobIDs maps their sha256 to blobs.id. Rows are
// written inside tx, which the engine owns; Import must not commit.
Import(ctx context.Context, tx *sql.Tx, repoID, key string, c *Content, blobIDs map[string]string) (*Change, error)
// Delete removes the live row of the unit: it stamps deleted_at/deleted_by
// when soft is true (the trash keeps it), and removes it otherwise.
Delete(ctx context.Context, tx *sql.Tx, repoID, key string, soft bool, deletedBy string) (*Change, error)
// Backfill registers a unit in the change log for every live row of the
// repository (enabling federation on a repository that has content), by
// calling federation_record with each row's updated_at as its stamp.
Backfill(ctx context.Context, tx *sql.Tx, repoID string) error
// LockTables are the tables Enable locks against writers (SHARE mode) for
// the instant between registering a repository's log and backfilling it, so
// no concurrent change slips between the two.
LockTables() []string
}
Codec maps the units of one repository format to their rows. A codec holds no state; every method takes the repository it works on. Keys are the unit keys of docs/design/federation.md, built identically by the capture triggers (migration 071).
type Content ¶
type Content struct {
Kind string `json:"kind"`
Data json.RawMessage `json:"data"`
Blobs []BlobRef `json:"blobs,omitempty"`
Deps []string `json:"deps,omitempty"`
ContentRef string `json:"content_ref"`
}
Content is the replicated state of a live unit: everything a peer needs to recreate the rows (Data, format specific and opaque to the transport), the blobs to fetch first and the units that must exist before it (Deps).
type Deferred ¶
type Deferred struct {
UnitKey string
Seq int64
Attempts int
Reason string
LastError string
FirstSeenAt time.Time
NextAttemptAt time.Time
}
Deferred is a unit set aside after failing to apply.
type Engine ¶
type Engine struct {
Options
// contains filtered or unexported fields
}
Engine applies the changes pulled from peers and runs the pull workers.
func (*Engine) Kick ¶
func (e *Engine) Kick()
Kick asks the worker to look for due peers now (after a peer was added or a resync requested on this replica).
type Entry ¶
type Entry struct {
Seq int64 `json:"seq"`
UnitKey string `json:"unit_key"`
Kind string `json:"kind"`
Event string `json:"event"`
Tombstone bool `json:"tombstone"`
Stamp Stamp `json:"stamp"`
ContentRef string `json:"content_ref"`
ChangedAt time.Time `json:"changed_at"`
// Base is the stamp of the unit state this change replaced where it was
// made; nil when the unit had no previous state there or the serving member
// predates base stamps. It tells a sequential overwrite from a concurrent
// write.
Base *Stamp `json:"base,omitempty"`
}
Entry is one row of a repository's change log as served to peers: the latest event of a unit. Entries are listed in Seq order; a unit appears once, at the position of its last change.
type InfoResponse ¶
type InfoResponse struct {
Instance uuid.UUID `json:"instance_id"`
LogID uuid.UUID `json:"log_id"`
HeadSeq int64 `json:"head_seq"`
Repository string `json:"repository"`
Format string `json:"format"`
Version int `json:"protocol_version"`
}
InfoResponse is the body of GET /federation/v1/info.
type LogResponse ¶
type LogResponse struct {
LogID uuid.UUID `json:"log_id"`
HeadSeq int64 `json:"head_seq"`
Entries []Entry `json:"entries"`
// More is true when entries beyond the returned page exist.
More bool `json:"more"`
}
LogResponse is the body of GET /federation/v1/log.
type Metrics ¶
type Metrics struct {
Applied *prometheus.CounterVec
Conflicts *prometheus.CounterVec
PullErrors *prometheus.CounterVec
// Resumed counts blob transfers continued with a Range request from a
// partial download instead of restarted.
Resumed *prometheus.CounterVec
// contains filtered or unexported fields
}
Metrics are the Prometheus series of federation, all labelled repo and peer (both bounded by the operator's configuration, never by client input).
The counters are incremented by the pull workers; the gauges are computed at scrape time from the peers' stored state, so they are right on every replica and after a restart.
func NewMetrics ¶
func NewMetrics(reg prometheus.Registerer, store *Store) (*Metrics, error)
NewMetrics creates the federation metrics and registers them on reg. The gauges read through store.
type NewPeer ¶
type NewPeer struct {
RepoID string
Name string
BaseURL string
Token string
CAPEM string
ClientCert string
ClientKey string
// VEXTrust is the peer's VEX trust ("" means VEXTrustIgnore).
VEXTrust string
}
NewPeer is the input of CreatePeer. Secrets are given in clear and stored encrypted.
type Notifier ¶
type Notifier interface {
Notify(r Regen)
}
Notifier queues the metadata regeneration of replicated changes (the RegenQueue of the format's worker). It ignores the formats whose metadata is generated on read.
type Options ¶
type Options struct {
Store *Store
SQL *sql.DB
DB OptionsStore
Blobs storage.BlobStore
Log *logger.Logger
Webhooks webhook.Publisher
Notify Notifier
Metrics *Metrics
// VEX receives the VEX decisions of the peers that are trusted with them,
// fetched after a successful pull (nil: no VEX exchange).
VEX VEXReceiver
PollInterval time.Duration
BatchSize int
MaxBackoff time.Duration
RequestTimeout time.Duration
TombstoneRetention time.Duration
// TrashDefaultDays is the server-wide trash retention applied to
// repositories without their own (0: applied deletes are permanent).
TrashDefaultDays int
// SpoolDir is where blobs of peers are downloaded to, and where an
// interrupted download waits to be resumed by the next pull (empty: a
// directory under the OS temp dir). Give every instance its own.
SpoolDir string
// MaxPartialBytes caps the total size of the partial downloads kept in
// the spool (0: DefaultMaxPartialBytes); the least recently written go first.
MaxPartialBytes int64
// MaxPartialAge discards a partial download untouched for this long
// (0: DefaultMaxPartialAge).
MaxPartialAge time.Duration
// MaxClockSkew is how far ahead of the local clock the stamp of a peer's
// change may be; a change beyond it is set aside until the local clock
// catches up (0: DefaultMaxClockSkew).
MaxClockSkew time.Duration
// MaxBlobBytes refuses a blob of a peer larger than this (0: no limit
// beyond the declared size of each blob being verified).
MaxBlobBytes int64
}
Options configures an Engine.
type OptionsStore ¶ added in v0.15.0
type OptionsStore interface {
BlobReferenceCount(ctx context.Context, sha256 string) (int, error)
DecrementStorageUsage(ctx context.Context, repoID string, sizeBytes int64, artifactCount int) error
EnsureBlob(ctx context.Context, sha256 string, mediaType string, size int64) (string, error)
ReserveStorageUsage(ctx context.Context, repoID string, sizeBytes int64, artifactCount int) (bool, error)
}
OptionsStore is the part of the database Options needs.
type Peer ¶
type Peer struct {
ID string
RepoID string
Name string
BaseURL string
Enabled bool
TokenEnc string
CAPEM string
ClientCertEnc string
ClientKeyEnc string
CursorSeq int64
RemoteHeadSeq int64
RemoteLogID *uuid.UUID
LastAttemptAt *time.Time
LastSuccessAt *time.Time
LastError string
ErrorCount int
NextAttemptAt *time.Time
OldestPendingAt *time.Time
AppliedTotal int64
ConflictsTotal int64
ResyncRequested bool
CreatedAt time.Time
// VEXTrust is what happens to the peer's VEX decisions (VEXTrustIgnore,
// VEXTrustSuggest or VEXTrustApply); VEXSyncedAt and VEXError are the
// outcome of their last fetch.
VEXTrust string
VEXSyncedAt *time.Time
VEXError string
DeferredUnits int
}
Peer is a pull source of a federated repository with its replication state. The secret fields hold the stored (encrypted) values; use PeerSecrets to open them.
func (*Peer) Secrets ¶
func (p *Peer) Secrets() (PeerSecrets, error)
Secrets decrypts the peer's credentials.
type PeerMetric ¶
type PeerMetric struct {
Repo string
Peer string
Lag time.Duration
Backlog int64
LastSuccess *time.Time
}
PeerMetric is one peer's gauge values.
type PeerPatch ¶
type PeerPatch struct {
Name *string
BaseURL *string
Token *string
CAPEM *string
ClientCert *string
ClientKey *string
Enabled *bool
VEXTrust *string
}
PeerPatch is a partial update of a peer; nil fields are left alone.
type PeerSecrets ¶
PeerSecrets are a peer's credentials in clear.
type PeerState ¶
type PeerState string
PeerState summarises where a peer stands, for the API and the UI.
type Progress ¶
type Progress struct {
Cursor int64
RemoteHead int64
RemoteLogID uuid.UUID
OldestPending *time.Time
// Applied and Conflicts are added to the peer's totals.
Applied int64
Conflicts int64
// ClearResync drops the resync request, once the full pass completed.
ClearResync bool
}
Progress is what a pull persists about a peer.
type Querier ¶
type Querier interface {
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}
Querier is the part of *sql.DB, *sql.Tx and *sql.Conn the codecs read with.
type Regen ¶
type Regen struct {
// Format is the repository format ("maven", "npm").
Format string
// RepoID is the repository.
RepoID string
// PackageID and Name are the packages row the change touched.
PackageID string
Name string
// Attrs is the packages.attrs of that row (the maven group and artifact id,
// the npm scope); empty when it has none.
Attrs json.RawMessage
}
Regen asks for the derived metadata of a package to be regenerated after a replicated change, through the format's metadata worker (its RegenQueue). A change of any format reports one; the notifier ignores the formats whose metadata is generated on read.
type RepoState ¶
type RepoState struct {
RepoID string
LogID uuid.UUID
HeadSeq int64
EnabledAt time.Time
// VEXPublish serves the repository's local VEX decisions to its peers.
VEXPublish bool
}
RepoState is the log identity of a federated repository.
type Reservation ¶ added in v0.15.0
Reservation is quota to reserve before a unit is applied: the bytes of one file and 1 when that file counts as an artifact, as the quota_pending triggers of package_files consume them (migration 061): one reservation per file row the apply adds or re-points at another blob.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server answers the pull requests of peers under /federation/v1. It is mounted outside the RBAC chain: peers authenticate with a per-repository bearer token (see AuthenticateToken), which grants read access to the change log and the content of that one repository and nothing else.
func NewServer ¶
func NewServer(store *Store, db quarantine.Checker, blobs storage.BlobStore, log *logger.Logger) *Server
NewServer creates the peer endpoint handler.
func (*Server) Handler ¶
Handler returns the router of the peer endpoints, to be mounted at /federation/v1.
func (*Server) WithVEX ¶ added in v0.22.0
func (s *Server) WithVEX(p VEXPublisher) *Server
WithVEX makes the server answer GET /federation/v1/vex with the documents p builds, for the repositories that publish their VEX decisions.
type Stamp ¶
type Stamp struct {
Wall int64 `json:"wall"`
Counter int32 `json:"counter"`
Origin uuid.UUID `json:"origin"`
}
Stamp orders the changes of one unit across instances: a hybrid logical clock (wall microseconds, counter) with the origin instance as the last tie-breaker. The highest stamp wins; a stamp never compares equal for two different changes.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the SQL side of federation: the log of this instance, its peers, the inbound tokens and the deferred units. It works on the raw pool like the other background workers; the per-format rows are the codecs' business.
func (*Store) AuthenticateToken ¶
AuthenticateToken resolves a presented peer token to the repository it is bound to. Unknown, malformed and revoked tokens give ErrNotFound.
func (*Store) ClearDeferred ¶
ClearDeferred forgets a deferred unit (applied, or superseded).
func (*Store) CreatePeer ¶
CreatePeer adds a pull source to a federated repository.
func (*Store) CreateToken ¶
func (s *Store) CreateToken(ctx context.Context, repoID, name, createdBy string) (*Token, string, error)
CreateToken issues a peer token for a repository. The clear text is returned once and never stored.
func (*Store) Defer ¶
func (s *Store) Defer(ctx context.Context, peerID, key string, seq int64, reason string, cause error) error
Defer parks a unit that could not be applied; it is retried later on its own backoff (30s doubling to an hour) without holding up the stream. Only the classified reason of cause is stored (see Describe).
func (*Store) DeletePeer ¶
DeletePeer removes a peer and its deferred units.
func (*Store) Disable ¶
Disable stops federating a repository: its log, peers, tokens and deferred units are removed (the artifacts stay). Enabling it again starts a new log, so peers of the old one must resync.
func (*Store) DuePeers ¶
DuePeers lists the enabled peers whose next pull is due: not backing off and, unless a resync is requested, last tried at least poll ago.
func (*Store) Enable ¶
Enable makes a repository federated: it starts its log, registers every live unit of the repository in it (stamped with the row's last update time) and sets the repositories.federated flag, all in one transaction. Enabling an already federated repository does nothing.
func (*Store) GetEntry ¶
GetEntry returns the current log row of a unit, ErrNotFound when the unit is not logged.
func (*Store) InstanceID ¶
InstanceID returns the identity of this instance.
func (*Store) ListDeferred ¶
func (s *Store) ListDeferred(ctx context.Context, peerID string, dueOnly bool, limit int) ([]Deferred, error)
ListDeferred lists a peer's deferred units, oldest first.
func (*Store) ListEntries ¶
func (s *Store) ListEntries(ctx context.Context, repoID string, after int64, limit int) ([]Entry, error)
ListEntries returns up to limit log entries with seq > after, in seq order.
func (*Store) ListPeers ¶
ListPeers returns the peers of a repository by name; repoID "" lists the enabled peers of every repository (the pull scheduler).
func (*Store) ListTokens ¶
ListTokens lists a repository's peer tokens, newest first.
func (*Store) MarkAttempt ¶
MarkAttempt records that a pull of the peer started.
func (*Store) MarkFailure ¶
func (s *Store) MarkFailure(ctx context.Context, id string, cause error, retryIn time.Duration) error
MarkFailure records a failed pull and when the next one may start. Only the classified reason of cause is stored (see Describe): the cause itself can hold text of the peer or the network stack and is for the log.
func (*Store) MarkSuccess ¶
MarkSuccess records a pull that completed without error.
func (*Store) MarkVEXSync ¶ added in v0.22.0
MarkVEXSync records a fetch of the peer's VEX decisions. Only a client-safe summary of syncErr is stored (see Describe); nil clears the error.
func (*Store) PeerMetrics ¶
func (s *Store) PeerMetrics(ctx context.Context) ([]PeerMetric, error)
PeerMetrics returns the gauge values of every enabled peer.
func (*Store) PurgeTombstones ¶
PurgeTombstones removes tombstones older than retention from every log and returns how many it removed.
func (*Store) RepoBlobSizes ¶ added in v0.15.0
func (s *Store) RepoBlobSizes(ctx context.Context, repoID string, shas []string) (map[string]int64, error)
RepoBlobSizes returns the recorded size of every blob among shas that the repository already references (a package file, a docker blob or manifest, trashed or not). A blob that only another repository references is not in the result: what a peer names by digest may be linked to the repository without being downloaded only when it is.
func (*Store) RepoState ¶
RepoState returns the log state of a repository, ErrNotFederated when it has none.
func (*Store) RequestResync ¶
RequestResync flags a peer for a full resync: its cursor is reset to the start of the remote log and every unit is merged again (idempotently) on the next pull. Existing deferred units are retried at once.
func (*Store) RevokeToken ¶
RevokeToken revokes a peer token; its requests are refused from then on.
func (*Store) SaveProgress ¶
SaveProgress persists the cursor and counters after a page was applied.
func (*Store) SetVEXPublish ¶ added in v0.22.0
SetVEXPublish chooses whether a federated repository serves its VEX decisions to its peers.
func (*Store) TrashRetentionDays ¶
func (s *Store) TrashRetentionDays(ctx context.Context, q Querier, repoID string, def int) (int, error)
TrashRetentionDays resolves the effective trash retention of a repository, falling back to def (the server default).
func (*Store) UpdatePeer ¶
UpdatePeer applies a partial update. Changing the URL or a credential clears the peer's error state so the next pull starts at once.
The token is sent to the peer's URL, so a patch that moves the peer to another URL must carry the token for it (ErrInvalid otherwise); the stored token is never sent to a URL it was not entered for.
type Token ¶
type Token struct {
ID string
RepoID string
Name string
CreatedBy string
CreatedAt time.Time
LastUsedAt *time.Time
RevokedAt *time.Time
}
Token is an inbound credential: a peer presents it to pull one repository.
type UnitResponse ¶
UnitResponse is the body of GET /federation/v1/unit: the unit's current log row and, for a live unit, its content.
type VEXPublisher ¶ added in v0.22.0
type VEXPublisher interface {
PeerVEXDocument(ctx context.Context, repoID, format string) ([]byte, error)
}
VEXPublisher builds the VEX document a federated repository serves to its peers: its local decisions only.