Documentation
¶
Overview ¶
Package manifestreader polls the control-plane manifest and delivers verified objects.
A Reader sends one conditional GET of the manifest per poll interval (If-None-Match with the ETag it holds). While no object is failing, a 304 answer costs nothing else: no object request, no parsing, no snapshot. While an object is failing, a round costs the manifest GET plus one GET for each failing object (and, only when that fails, one more for each other entry that lists the same checksum). A new manifest is decoded and validated with the controlplane package, the generation rules are applied, and only the objects whose checksum is not already held are fetched, with a bounded number of concurrent requests. Every object is verified with its sha256 checksum before it is served. The reader never lists a bucket and never asks for the metadata of an object.
The result of a generation is one immutable Snapshot, sent on the channel of Reader.Snapshots with latest-wins delivery: the poller never blocks on a slow consumer. The state of the reader is readable at any time, without blocking the poller, from Reader.Status.
The reader talks to a backend through the small ObjectStore interface; S3Store is the implementation on the S3 client of a named connection of the connection factory, and FileStore the one on a local directory (a volume mount, a ConfigMap). The storetest package holds the conformance suite of a store, and the readertest package the one of a reader running on it; every connection type passes both.
Index ¶
- Constants
- Variables
- func CapUnknownFieldPaths(paths []string) []string
- func CheckHTTPHeaderName(name string) error
- func CheckHTTPHeaderValue(value string) error
- func FileKeyPath(key string) string
- func HTTPRedirectPolicy(limit int) func(*http.Request, []*http.Request) error
- func OpenFileRoot(dir string) (*os.Root, error)
- func RejectionReason(outcome, reason string) string
- func RejectionReasons() []string
- func ValidFileKey(key string) bool
- func ValidHTTPBaseURL(raw string, allowCleartext bool) error
- func ValidHTTPKey(key string) bool
- func ValidKey(key string) bool
- type BackoffStatus
- type CacheStatus
- type Config
- type Counts
- type FetchError
- type FileStore
- type GetRequest
- type HTTPHeaders
- type HTTPStore
- type HTTPStoreConfig
- type HookPanic
- type Hooks
- type ManifestStatus
- type Object
- type ObjectFailure
- type ObjectState
- type ObjectStore
- type Option
- type Persist
- type PollCount
- type PollStatus
- type Reader
- type RefreshResult
- type RejectionCount
- type Restored
- type S3Provider
- type S3Store
- type Scheduler
- type Snapshot
- type StaleObject
- type State
- type StateStatus
- type Status
Constants ¶
const ( // DefaultPollInterval is the poll interval of a manifest. DefaultPollInterval = 60 * time.Second // MaxJitterFraction is the exclusive upper bound of the jitter fraction. MaxJitterFraction = 1.0 // MinPollInterval is the shortest accepted poll interval, and the shortest wait between two rounds. MinPollInterval = time.Second // DefaultJitterFraction is the jitter of the poll interval: +/-10 %. DefaultJitterFraction = 0.1 // DefaultRequestTimeout bounds every request of the reader (the manifest and each object). DefaultRequestTimeout = 60 * time.Second // DefaultMaxManifestBytes bounds the manifest download. 20000 entries are about 10 MiB of JSON or YAML. DefaultMaxManifestBytes = 16 << 20 // DefaultMaxObjectBytes bounds one object download. DefaultMaxObjectBytes = 16 << 20 // DefaultMaxTotalBytes bounds the sum of the sizes of the distinct objects of a manifest. DefaultMaxTotalBytes = 1 << 30 // DefaultFetchConcurrency is the number of concurrent object downloads. DefaultFetchConcurrency = 4 // MaxFetchConcurrency is the largest accepted number of concurrent object downloads. MaxFetchConcurrency = 16 // DefaultBackoffMax caps the wait after consecutive failures, and the retry cadence of a failing object. DefaultBackoffMax = 5 * time.Minute // DefaultFetchSpread bounds the random delay before the object fetches of a new generation (and it is // bounded by the poll interval). DefaultFetchSpread = 5 * time.Second )
Defaults and bounds of Config.
const ( // MaxHTTPKeyBytes is the longest key of an http store. MaxHTTPKeyBytes = 1024 // DefaultHTTPMaxRedirects is the number of redirects an http store follows when the setting is left out. DefaultHTTPMaxRedirects = 3 // MaxHTTPRedirects is the largest number of redirects that can be set. MaxHTTPRedirects = 10 // MaxHTTPTimeout is the largest value of any of the timeouts of an http store. MaxHTTPTimeout = 10 * time.Minute // MaxHTTPRetryAfter bounds the Retry-After the store passes on to the reader. MaxHTTPRetryAfter = 5 * time.Minute // DefaultHTTPConnectTimeout bounds the dial, and the TLS handshake on its own. DefaultHTTPConnectTimeout = 10 * time.Second // DefaultHTTPHeaderTimeout bounds the wait for the response headers after the request was written. DefaultHTTPHeaderTimeout = 20 * time.Second // DefaultHTTPRequestTimeout bounds one Get from the dial to the last byte of the body. DefaultHTTPRequestTimeout = 30 * time.Second )
const ( // ReasonMissing is a 404 answer: the manifest lists an object that is not there. ReasonMissing = "missing" // ReasonChecksumMismatch is a download whose sha256 is not the listed one. ReasonChecksumMismatch = "checksum-mismatch" // ReasonTooLarge is an entry whose listed size is above the object limit: it is not requested. ReasonTooLarge = "too-large" // ReasonNotRestored is an object that the restored state did not have: it is fetched after the first poll of // the live manifest. ReasonNotRestored = "not-restored" // ReasonInvalidKey is an entry whose key is empty or starts with "/": keys are absolute bucket keys, and the // entry is not requested. ReasonInvalidKey = "invalid-key" // ReasonInvalidSize is an entry whose listed size is below 1: it is not requested. ReasonInvalidSize = "invalid-size" // ReasonSizeMismatch is a download that is shorter or longer than the listed size. ReasonSizeMismatch = "size-mismatch" // ReasonUnknownConnection is an object of a connection the reader has no store for. ReasonUnknownConnection = "unknown-connection" // ReasonUnsupportedVersion is an object whose content version is newer than this reader supports: it is not // requested, keeping its last good content as stale (or missing if none). ReasonUnsupportedVersion = string(controlplane.CodeUnsupportedVersion) )
Reasons of a failed object, besides ReasonError and ReasonDenied of the store. The set is closed.
const ( // PollNone is the result before the first round ended. PollNone = "none" // PollNotModified is a 304 answer to the conditional GET. PollNotModified = "not_modified" // PollUpdated is a 200 answer that was read: see [ManifestStatus] for what was done with it. PollUpdated = "updated" // PollNotFound is a 404 answer: the manifest is gone, the previous snapshot stays. PollNotFound = "not_found" // PollTooLarge is a manifest larger than the byte limit. PollTooLarge = "too_large" // PollError is any other failed request; Reason says what kind. PollError = "error" )
Results of a poll, in PollStatus.Result. The set is closed.
const ( // OutcomeNone: no manifest was read yet. OutcomeNone = "none" // OutcomeAccepted: the manifest is valid and is the held one. OutcomeAccepted = "accepted" // OutcomeInvalid: the manifest could not be decoded or is not valid; the previous one stays. OutcomeInvalid = "invalid" // OutcomeLowerGeneration: the generation is lower than the held one; the manifest is ignored. OutcomeLowerGeneration = "lower-generation" // OutcomeConflict: same generation as the held one with another object set or checksum (a publisher bug); // the manifest is rejected. OutcomeConflict = "generation-conflict" // OutcomeChannelMismatch: the manifest is of another channel than the expected one. OutcomeChannelMismatch = "channel-mismatch" )
Outcomes of the last manifest the reader read, in ManifestStatus.Outcome. The set is closed.
const ( // RestoreNone: the restore did not run, or no state hook is installed. RestoreNone = "" // RestoreRestored: a manifest and all its objects were restored. RestoreRestored = "restored" // RestorePartial: the manifest was restored, some objects were discarded (missing or corrupt). RestorePartial = "partial" // RestoreEmpty: there was no usable saved state (empty, other layout version, corrupt manifest). RestoreEmpty = "empty" // RestoreFailed: the saved state could not be read at all (an unreadable directory). RestoreFailed = "failed" // RestoreDisabled: the state directory is not used (it was refused: see [StateStatus.DisabledReason]). RestoreDisabled = "disabled" )
Results of the restore of the saved state, in StateStatus.Restore. The set is closed.
const ( // ParentSyncSkipped: a parent could not be opened for the flush for lack of permission. The state directory is // used all the same (it is a cache); after a power loss the directory entry itself may be missing, and the relay // then starts as on a first run. ParentSyncSkipped = "skipped" // ParentSyncPending: a flush failed and is retried by the next write. ParentSyncPending = "pending" )
States of the flush of the parent directories of a state directory that was created, in StateStatus.ParentSync. The set is closed; the empty value is "nothing to report".
const ( // ReasonError is a failure that may pass by itself: network, timeout, throttling, 5xx. ReasonError = "error" // ReasonTimeout is a request that ran into the request timeout of the reader. ReasonTimeout = "timeout" // ReasonDenied is a failure that a retry does not fix without a change of configuration: 403 and other // client errors. ReasonDenied = "denied" )
Failure reasons set by the stores of this package, and used by the reader in its status. The set is closed.
const FileOpenFlags = openFlags
FileOpenFlags are the flags with which a store opens a key to read it: read-only, and on Unix without blocking, so that a FIFO that took the place of a file is refused (after the type is read from the open handle) instead of waiting for a writer. The publisher opens keys with the same flags as the reader.
const MaxUnknownFieldPathBytes = 128
MaxUnknownFieldPathBytes is the maximum byte length kept for each unknown field path.
const MaxUnknownFieldPaths = 10
MaxUnknownFieldPaths is the maximum number of unknown field paths kept per document in status.
const ReasonTotalTooLarge = "too-large-total"
ReasonTotalTooLarge is the ManifestStatus.Reason of a manifest whose distinct objects add up to more than Config.MaxTotalBytes: it is rejected whole, before any object request.
Variables ¶
var ( // ErrKeyRefused is the cause of a key that is not a clean relative slash path: empty, absolute, with a ".", // ".." or empty element, a trailing slash, a backslash or a NUL byte. ErrKeyRefused = errors.New("manifestreader: file key refused") // ErrOutsideRoot is the cause of a path that leaves the root directory through a symbolic link. ErrOutsideRoot = errors.New("manifestreader: path leaves the root directory") // ErrNotRegular is the cause of a key that names a directory, a device, a socket or a FIFO. ErrNotRegular = errors.New("manifestreader: not a regular file") ErrRootUnavailable = errors.New("manifestreader: root directory unavailable") )
Causes carried by the *FetchError of a FileStore. They are for errors.Is; the reader reports only the reason.
var ( // ErrHTTPKeyRefused is the cause of a key that is not a clean relative slash path (see [ValidFileKey]) or that is // longer than [MaxHTTPKeyBytes]. ErrHTTPKeyRefused = errors.New("manifestreader: http key refused") // ErrHTTPRedirectRefused is the cause of a redirect that the store does not follow: to another origin, to a lower // scheme, to an address with credentials, or past the limit. ErrHTTPRedirectRefused = errors.New("manifestreader: http redirect refused") // ErrHTTPCleartextRefused is the cause of a connection that a cleartext store was about to open to an address that // is not a loopback address: the address that the host name resolved to is checked when the connection is made. ErrHTTPCleartextRefused = errors.New("manifestreader: http cleartext connection refused") // ErrHTTPAuth is the cause of a 401 or 403 answer. ErrHTTPAuth = errors.New("manifestreader: http access refused") // ErrHTTPStatus is the cause of an answer with a status the store does not map to a result of its own. ErrHTTPStatus = errors.New("manifestreader: unexpected http status") // ErrHTTPEncoding is the cause of an answer with a Content-Encoding other than identity: the store asks for // none and never decodes one. ErrHTTPEncoding = errors.New("manifestreader: http content encoding refused") // ErrHTTPUnboundedBody is the cause of an HTTP/1 answer whose end is marked by nothing but the close of the // connection (no Content-Length, not chunked): a body cut short would look complete. ErrHTTPUnboundedBody = errors.New("manifestreader: http body is not delimited") // ErrHTTPHeader is the cause of a header that cannot be configured. It never names a value. ErrHTTPHeader = errors.New("manifestreader: invalid http header") )
Causes carried by the *FetchError of an HTTPStore, and by the errors of NewHTTPStore. They are for errors.Is; the reader reports only the reason.
var ( // ErrNotModified is returned by a conditional Get whose ETag is still current. It is not a failure. ErrNotModified = errors.New("manifestreader: not modified") // ErrNotFound is returned when the object does not exist. ErrNotFound = errors.New("manifestreader: object not found") // ErrTooLarge is returned when the object is larger than the limit of the call. The store never buffers // more than limit bytes. ErrTooLarge = errors.New("manifestreader: object too large") )
Sentinel results of an ObjectStore call. Every other failure is a *FetchError.
var ErrAlreadyRunning = errors.New("manifestreader: reader already running")
ErrAlreadyRunning is returned by a second call of Reader.Run.
var ErrInvalidConfig = errors.New("manifestreader: invalid config")
ErrInvalidConfig is matched by the error New returns for a configuration it cannot use.
var ErrNotPolling = errors.New("manifestreader: the reader is not polling")
ErrNotPolling is returned by Reader.Refresh when the reader is not running: it was not started, or it stopped.
var ErrNothingRestored = errors.New("manifestreader: nothing to restore")
ErrNothingRestored is what Hooks.Restore returns when there is no saved state: not a failure.
Functions ¶
func CapUnknownFieldPaths ¶
CapUnknownFieldPaths returns at most MaxUnknownFieldPaths unknown field paths, each sanitized by replacing control characters with spaces and truncated to MaxUnknownFieldPathBytes bytes on a valid UTF-8 boundary.
func CheckHTTPHeaderName ¶
CheckHTTPHeaderName reports why a header name cannot be configured, or nil.
func CheckHTTPHeaderValue ¶
CheckHTTPHeaderValue reports why a value cannot be sent, or nil. The error never holds the value.
func FileKeyPath ¶
FileKeyPath maps a valid key (see ValidFileKey) to the path below the root of the store. It is the only key-to-path mapping of reader and publisher.
func HTTPRedirectPolicy ¶
HTTPRedirectPolicy is the redirect policy of an HTTPStore, for http.Client.CheckRedirect. The principle: the headers and the request never reach an origin (scheme, host, port) other than the configured one. A redirect is followed only when its target has the origin of the configured request, with one exception: the upgrade of an http request on port 80 to https on port 443 of the same host. Besides that, at most limit redirects are followed, never one back from https to http (also in a chain), and never one to an address with credentials. A path on the same origin is followed even when it leaves the base path: the server that received the headers decides its own paths. The store does not rely on the standard client for any of this: the client strips only Authorization, cookies and the like on a change of domain, and keeps every other header.
func OpenFileRoot ¶
OpenFileRoot opens the root directory of a file store the way the reader does: the lookup requires a directory, so a FIFO in its place is refused before it is opened. The error is ErrRootUnavailable. The publisher of a file store opens its root with this function, so reader and writer resolve a key in the same way.
func RejectionReason ¶
RejectionReason maps a manifest outcome and raw reason to the single closed rejection-reason vocabulary (RejectionReasons) shared by /info (config.reader.reason) and semaphore_config_reader_rejections_total. Any rejection reason outside RejectionReasons maps to "invalid". It returns "" for non-rejection outcomes.
func RejectionReasons ¶
func RejectionReasons() []string
RejectionReasons returns the closed, sorted set of reader rejection reasons exported in metrics.
func ValidFileKey ¶
ValidFileKey reports whether key is a clean relative slash path.
func ValidHTTPBaseURL ¶
ValidHTTPBaseURL reports why the base URL is not accepted, or nil. It is the check of NewHTTPStore, for the validation of a configuration file.
func ValidHTTPKey ¶
ValidHTTPKey reports whether key is a clean relative slash path of at most MaxHTTPKeyBytes bytes.
Types ¶
type BackoffStatus ¶
type BackoffStatus struct {
// Wait is the wait planned before the next round. It is encoded as a number of nanoseconds.
Wait time.Duration `json:"wait"`
// Failures is the number of consecutive failed manifest polls (an error, a timeout, a 404, a manifest above
// the byte limit); a 200 or a 304 resets it. A manifest that was read and rejected is not a failure of the poll.
Failures int `json:"failures"`
// ObjectsWaiting is the number of failed objects that are waiting for their next retry.
ObjectsWaiting int `json:"objectsWaiting"`
// Throttled tells that the last failure was a throttle: it backs off one step further.
Throttled bool `json:"throttled"`
}
BackoffStatus is the backoff state at the end of a round.
type CacheStatus ¶
CacheStatus counts the verified objects the reader holds, each content once however many names use it.
type Config ¶
type Config struct {
// ManifestKey is the absolute bucket key of the manifest, as the publisher wrote it (a key prefix is applied
// by the publisher only; the reader never adds one). Required; it must not start with "/".
ManifestKey string
// Connection is the name of the connection the store of the reader serves. Required: an object whose entry
// names another connection is failed with [ReasonUnknownConnection] unless [WithObjectStores] has a store
// for that name.
Connection string
// Channel is the expected channel of the manifest; a manifest of another channel is rejected. Empty
// accepts any channel.
Channel string
// MaxObjects is the largest number of objects a manifest may list; a bigger manifest is rejected whole.
MaxObjects int
// JitterFraction spreads the interval by +/- this fraction (0.1 is +/-10 %). Zero selects the default; it
// must be in [0, 1). Set DisableJitter to poll at exactly the interval.
JitterFraction float64
// RequestTimeout bounds every request of the reader: the manifest GET and each object GET.
RequestTimeout time.Duration
// PollInterval is the time between two rounds, before jitter; at least [MinPollInterval].
PollInterval time.Duration
// MaxManifestBytes bounds the manifest download. Decoding a 20000 entry manifest costs about 190 ms and
// 144 MB of allocations (measured with the controlplane decoder), and a hostile manifest near the cap can
// allocate far more before it is rejected: the cap is what bounds that cost. A larger body is refused
// without being buffered.
MaxManifestBytes int64
// MaxObjectBytes bounds one object: an entry that lists a larger size is not requested.
MaxObjectBytes int64
// MaxTotalBytes bounds the sum of the listed sizes of the distinct checksums of a manifest. A manifest
// above it is rejected whole before any object request; a checksum listed with several sizes counts with the
// largest. The worst-case memory of the reader is about this cap for the current content, plus the last good
// content that stale names still carry, plus FetchConcurrency times MaxObjectBytes in flight. Each carried
// object was within the limits when it was loaded, but the carried bytes of several older generations are not
// bounded by this cap: they are bounded by MaxObjects times MaxObjectBytes.
MaxTotalBytes int64
// FetchConcurrency is the number of concurrent object downloads, at most [MaxFetchConcurrency].
FetchConcurrency int
// BackoffMax caps the exponential backoff after consecutive failed manifest polls, the retry interval of a
// failing object, and is the fixed retry cadence of an object that failed for good. Default
// [DefaultBackoffMax]; it is never below the poll interval.
BackoffMax time.Duration
// FetchSpread bounds the random delay a replica waits before it fetches the objects of a new generation (a
// generation that replaces a held one: a cold start with no content does not wait). Default
// [DefaultFetchSpread]; never above the poll interval.
FetchSpread time.Duration
// DisableJitter turns the jitter off (and with it the random start phase). The full jitter of the backoff and
// the fetch spreading keep using the jitter source.
DisableJitter bool
// DisableFetchSpread fetches the objects of a new generation at once.
DisableFetchSpread bool
}
Config configures a Reader. A zero field takes its default, except where noted. New copies it.
type FetchError ¶
type FetchError struct {
// Err is the cause. It may name the bucket or the key; the reader never logs or reports it, only Reason.
Err error
// Reason is the closed code the reader reports: [ReasonError] or [ReasonDenied].
Reason string
// Retryable tells whether trying again can succeed without a change of configuration.
Retryable bool
// Throttled marks a throttling answer (429, SlowDown): the reader backs off one step further than for
// another error.
Throttled bool
// RetryAfter is the wait the backend asked for (an HTTP Retry-After), already bounded by the store; zero for
// none. The reader waits at least that long (at most BackoffMax) before its next try.
RetryAfter time.Duration
}
FetchError is a failed Get that is neither ErrNotModified, ErrNotFound nor ErrTooLarge.
type FileStore ¶
type FileStore struct {
// contains filtered or unexported fields
}
FileStore is an ObjectStore over a directory of the local file system (a development directory, a volume mount, a Kubernetes ConfigMap or Secret mount).
Keys are relative slash paths under the root. A key that is empty, absolute, or has a ".", ".." or empty element is refused (ErrKeyRefused, reason denied). Every path is resolved with os.Root, so it cannot leave the root: a symbolic link inside the root that points to somewhere inside the root is followed (a ConfigMap mount is a tree of such links), one that points outside, and any absolute link, is refused (ErrOutsideRoot, reason denied). Only regular files are served; a directory, device, socket or FIFO is refused without being read (ErrNotRegular), and opening never blocks.
The ETag is the quoted sha256 of the bytes. A conditional Get reads the file to decide: an unchanged file is answered with ErrNotModified after one streaming pass that allocates a fixed buffer and returns no body, a changed one costs a second pass. The answer never relies on the size or the modification time of the file, so a rewrite that keeps both is still seen. See docs/concepts/control-plane-file-store.md.
VersionID is not supported: a file has no versions, so a request for one is answered with ErrNotFound. The store holds no state and is safe for concurrent use; the root is opened on each call, so a root that is replaced (a swapped mount) is followed.
func NewFileStore ¶
NewFileStore returns the store of the directory root. It checks that root is a directory now; a root that disappears later (an unmounted volume) makes Get fail with a retryable *FetchError whose causes include ErrRootUnavailable, so the reader backs off and recovers when the root is back.
func (*FileStore) Get ¶
Get implements ObjectStore. See FileStore for the rules.
type GetRequest ¶
type GetRequest struct {
// Key is the key of the object.
Key string
// ETag makes the request conditional when not empty.
ETag string
// VersionID selects an object version when not empty.
VersionID string
// Limit is the largest body the store returns. It never returns, nor retains, more than Limit bytes of the
// body, and it may read one byte past Limit to tell an object of exactly Limit bytes from a larger one. A
// negative limit is a limit of zero: only an empty object is returned. Callers that know the size pass it,
// so a store can allocate the buffer once.
Limit int64
}
GetRequest is one Get. It is a struct so that it can grow without breaking the implementations.
type HTTPHeaders ¶
HTTPHeaders are the headers of an HTTPStore: their values are secrets, so no formatting, logging or encoding of the map shows one. Only the names and the count are printed.
func (HTTPHeaders) Format ¶
func (h HTTPHeaders) Format(f fmt.State, _ rune)
Format implements fmt.Formatter: every verb prints the count and never a value.
func (HTTPHeaders) LogValue ¶
func (HTTPHeaders) LogValue() slog.Value
LogValue implements slog.LogValuer.
func (HTTPHeaders) MarshalJSON ¶
func (HTTPHeaders) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler: a value is never written.
func (HTTPHeaders) MarshalYAML ¶
func (HTTPHeaders) MarshalYAML() (any, error)
MarshalYAML implements the Marshaler of gopkg.in/yaml.v3, which writes a map without asking for the other hooks.
type HTTPStore ¶
type HTTPStore struct {
// contains filtered or unexported fields
}
HTTPStore is an ObjectStore over an HTTP server (a static file host, an object store behind a CDN, an internal service): a Get of a key is a GET of <BaseURL>/<key>. See docs/concepts/control-plane-http-store.md.
The ETag the reader holds is a tag that remembers the validator it came from: the ETag of the server ("etag:..."), the Last-Modified date together with the digest of the body ("lm:...") or the digest of the body alone ("sha256:..."). When the key was served from an address other than the one asked for (a redirect), the first two tags end with a mark that names that address: a validator is only good for the resource it came from, so a 304 or a 200 with the same ETag from another address is no proof (the object is read again, without a condition). A conditional Get sends If-None-Match for the first, If-Modified-Since for the second and nothing for the third. A 304 costs no body. A 200 whose validator equals the one held (a server that ignores conditional requests) is answered with ErrNotModified too. A 304 counts only for a request that was conditional, and a Last-Modified date less than two seconds older than the answer is not used as a validator (the digest of the body alone is), so a second write within the same second is seen.
VersionID is not supported: a request for one is answered with ErrNotFound. The store holds no state besides its connection pool and is safe for concurrent use.
func NewHTTPStore ¶
func NewHTTPStore(cfg *HTTPStoreConfig) (*HTTPStore, error)
NewHTTPStore checks the setting and returns the store. A cleartext address is accepted only for a loopback host, or when HTTPStoreConfig.AllowCleartext is set.
func (*HTTPStore) CloseIdleConnections ¶
func (s *HTTPStore) CloseIdleConnections()
CloseIdleConnections closes the idle connections of the pool.
func (*HTTPStore) Format ¶
Format implements fmt.Formatter: the store prints its origin and base path, never a header.
func (*HTTPStore) Get ¶
Get implements ObjectStore. See HTTPStore for the rules.
type HTTPStoreConfig ¶
type HTTPStoreConfig struct {
// Headers are sent with every request, for example Authorization. The values are secrets: the store never
// prints them, and never sends them to another host.
Headers HTTPHeaders
// BaseURL is the address the keys are resolved below: https://host/prefix. No credentials, query or fragment.
BaseURL string
// CABundlePEM holds certificate authorities trusted in addition to the system roots.
CABundlePEM []byte
// ConnectTimeout bounds the dial, and the TLS handshake on its own. Zero means [DefaultHTTPConnectTimeout]. The
// timeouts are at most [MaxHTTPTimeout] and not negative.
ConnectTimeout time.Duration
// HeaderTimeout bounds the wait for the response headers. Zero means [DefaultHTTPHeaderTimeout].
HeaderTimeout time.Duration
// RequestTimeout bounds one Get, body included. Zero means [DefaultHTTPRequestTimeout].
RequestTimeout time.Duration
// MaxRetryAfter bounds the Retry-After that is passed on. Zero means [MaxHTTPRetryAfter].
MaxRetryAfter time.Duration
// MaxRedirects is the number of redirects followed: zero follows none. A negative value means
// [DefaultHTTPMaxRedirects].
MaxRedirects int
// MinTLSVersion is a tls.Version constant. Zero, and anything below TLS 1.2, mean TLS 1.2.
MinTLSVersion uint16
// AllowCleartext lets the store use http:// for a host that is not a loopback address.
AllowCleartext bool
}
HTTPStoreConfig is the setting of an HTTPStore.
type HookPanic ¶
type HookPanic struct {
// Name is "restore", "save" or "onRound".
Name string `json:"name"`
Count uint64 `json:"count"`
}
HookPanic is the count of recovered panics of one hook.
type Hooks ¶
type Hooks struct {
// Restore is called once when [Reader.Run] starts. It returns [ErrNothingRestored] when nothing was saved.
Restore func() (*Restored, error)
// Save is called after every published snapshot. It must return quickly: a state directory queues the write.
Save func(Persist)
// StateStatus is called every time the status is made (a restore and each live round) and returns the state
// of the persistence behind Save and Restore, for [Status.State]. It must not block.
StateStatus func() StateStatus
// OnRound is called at the end of every live poll round with the new status (not by the restore).
OnRound func(*Status)
}
Hooks are the seams the state directory (package statedir) plugs into. Every field is optional. A hook runs on the polling goroutine and must not block. A panic in a hook is recovered, logged once per hook, counted in Status.HookPanics, and polling goes on. The arguments of Save and OnRound are read-only: do not change them and do not keep them without copying.
type ManifestStatus ¶
type ManifestStatus struct {
// At is when the reader processed the last manifest (accepted or rejected), zero when none was read yet.
At time.Time `json:"at,omitzero"`
// Outcome is an Outcome* constant: what happened to the last manifest the reader read. A 304 does not
// change it: it confirms the same bytes.
Outcome string `json:"outcome"`
// Reason is the closed code of the problem (a controlplane validation code, "decode", "unsupported-version",
// "wrong-kind", "too-many-objects", ...), empty when accepted.
Reason string `json:"reason"`
// Channel and Generation are those of the held manifest, zero before the first accepted one.
Channel string `json:"channel"`
// UnknownFieldPaths lists the first MaxUnknownFieldPaths field paths of the held manifest that this version
// does not know (never field values).
UnknownFieldPaths []string `json:"unknownFieldPaths,omitempty"`
Generation uint64 `json:"generation"`
// Objects is the number of objects of the held manifest.
Objects int `json:"objects"`
// UnknownFields counts the fields of the held manifest that this version does not know.
UnknownFields int `json:"unknownFields"`
}
ManifestStatus describes the manifest the reader holds and the last one it read.
type Object ¶
type Object struct {
// ETag is the validator of the content as the store reports it; the reader sends it back on the next
// conditional Get of the same key. It is not an integrity check.
ETag string
// Bytes is the content, at most the limit of the call. The reader never changes it.
Bytes []byte
}
Object is the content of one Get.
type ObjectFailure ¶
type ObjectFailure struct {
// Name is the object name of the manifest.
Name string `json:"name"`
// State is [StateStale] or [StateMissing].
State State `json:"state"`
// Reason is the closed code of the failure.
Reason string `json:"reason"`
// Checksum is the listed (wanted) sha256 value.
Checksum string `json:"checksum"`
// Retryable tells whether a retry can succeed without a change of configuration.
Retryable bool `json:"retryable"`
}
ObjectFailure is an object that is not ok. It never holds bytes.
type ObjectState ¶
type ObjectState struct {
// Kind and Format are those of the entry that Bytes belong to ("flags" or "flagSets", "json", "yaml", "toml").
Kind string
Format string
// Checksum is the checksum of Bytes. For a missing or pending object it is the listed checksum.
Checksum controlplane.Checksum
// State and Reason: Reason is empty for an ok object, and for the others the closed code of the failure
// (the Reason* constants).
State State
Reason string
// Bytes is the verified content, nil for a missing or pending object. It is shared with other names of the
// same checksum and with later snapshots: never change it.
Bytes []byte
}
ObjectState is what a snapshot says about one object name.
type ObjectStore ¶
type ObjectStore interface {
// Get fetches req.Key and returns a body of at most req.Limit bytes (it may read one byte past the limit to
// detect an object that is larger, see [GetRequest.Limit]). With a non-empty req.ETag the request is
// conditional and an unchanged object is answered with [ErrNotModified]. A missing object (or version) is
// [ErrNotFound], a larger one [ErrTooLarge]. Any other failure is a [*FetchError]. Get honours ctx.
Get(ctx context.Context, req GetRequest) (Object, error)
}
ObjectStore is the seam between the reader and a backend. The conformance suite in the storetest package executes this contract; a store passes when storetest.Run passes on it.
The contract in short:
- The ETag of a result describes exactly the bytes returned with it, differs when the bytes differ, and a conditional Get that holds the current ETag is answered with ErrNotModified (and a zero Object). Equal bytes need not give an equal ETag: a row version, a commit SHA or a generation number is a valid ETag.
- A failed Get returns a zero Object. A Get that ended with its context returns an error that wraps the error of the context: context.Canceled for a cancellation, context.DeadlineExceeded for a deadline. The store ends a read when Done closes: Done is authoritative. A store may also use Deadline() to set a deadline on the I/O it starts, but that is an optimisation: a store that copies Deadline() into a one-shot deadline must still watch Done.
- A Get that starts after a write to the object has returned sees that write (read-after-write consistency).
- The size guarantee is the one of GetRequest.Limit: never a body of more than Limit bytes, though a store may read one byte past it. When Limit is below the size of the object, the answer is ErrTooLarge, or ErrNotModified if the request is conditional with the current ETag and the store answers before it looks at the size. Never a body.
- A negative Limit is a Limit of zero.
- The bytes returned are the caller's: a later write to the object never changes bytes already returned.
type Option ¶
type Option func(*Reader)
Option configures a Reader.
func WithClock ¶
WithClock sets the clock that measures how long a wait lasted before a refresh cut it short: the time of the wait that was cut counts in the retry schedule of the failed objects, so no number of refreshes postpones a retry that is due. The default is clock.Now.
func WithJitter ¶
WithJitter replaces the random source of the jitter: it returns a value in [0, 1). The default is math/rand/v2.
func WithLogger ¶
WithLogger sets the logger; the default discards. The reader logs names and closed codes only, never keys, bytes or the text of an error of the store.
func WithObjectStores ¶
func WithObjectStores(stores map[string]ObjectStore) Option
WithObjectStores gives the store of each connection name that objects of the manifest may name. With it an object of an unknown connection is failed with ReasonUnknownConnection. The store of the manifest always serves the connection named by Config.Connection, and only that one.
func WithRequestContext ¶
func WithRequestContext( create func(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc), ) Option
WithRequestContext replaces the creation of the context of each request (manifest and objects), which is context.WithTimeout by default. Tests use it to end a request without waiting for a real timer.
func WithScheduler ¶
WithScheduler replaces the timer of the polling loop (tests use it to drive the rounds).
type Persist ¶
type Persist struct {
Snapshot *Snapshot
// ETag and Manifest are the ACCEPTED manifest (the one the snapshot comes from), never a rejected one that
// was read later.
ETag string
Manifest []byte
}
Persist is what a Hooks.Save call gets after a snapshot was published. Every field is read-only and shared with the reader: a hook must copy what it keeps.
type PollStatus ¶
type PollStatus struct {
// At is the time the last round ended (the repository clock). It is zero before the first round.
At time.Time `json:"at"`
// Result is a Poll* constant.
Result string `json:"result"`
// Reason is the closed code of a failed poll (a Reason* constant of the store or the reader), else empty.
Reason string `json:"reason"`
}
PollStatus describes the last poll.
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader polls one manifest and fetches its objects. Build it with New, start it once with Reader.Run.
Everything below the "poller" comment is touched by the polling goroutine only; other goroutines use Reader.Snapshots and Reader.Status.
Request budget: a round is one logical conditional GET of the manifest. When it fails, the SDK of the store may retry it: those are extra attempts, each observed once by the connection observer. The steady state (every round answered 304, no failing object) is exactly one request per round.
func New ¶
func New(store ObjectStore, cfg *Config, opts ...Option) (*Reader, error)
New returns a reader of store. cfg is copied and never changed; nil selects the defaults (which still need a manifest key and a connection name, so nil is an error today).
func (*Reader) Refresh ¶
func (r *Reader) Refresh(ctx context.Context) (RefreshResult, error)
Refresh makes the reader poll the manifest now, through the loop that polls on schedule: there is no second poll path. Calls that arrive while a round is waiting to start share that round and its result. A call that arrives while a round runs is served by the next round: the round that runs read the manifest before the call arrived, so its result is never the answer. It returns when that round ended or ctx is done; the round itself is not cancelled by ctx, it is bounded by the request timeout of the reader.
func (*Reader) Run ¶
Run polls until ctx is done and returns nil then. It runs the rounds on the calling goroutine; object downloads run on a bounded group of workers that ends with each round, so no goroutine outlives Run.
The first round is delayed by a random start phase, jitter() x min(PollInterval, 5 s), so replicas started together do not poll together, unless the jitter is disabled or restored state already made a snapshot available. The other rounds follow the poll interval with jitter, and every wait is within [MinPollInterval, PollInterval x (1+jitter)]. A failed round is simply tried again at the next interval.
func (*Reader) Snapshots ¶
Snapshots returns the channel of snapshots. It has room for one: a snapshot that is not consumed when the next one is ready is replaced by it (latest wins) and the poller never blocks. The channel is closed when Reader.Run returns.
type RefreshResult ¶
type RefreshResult struct {
// Poll is the result of the poll of the manifest: a Poll* result and its reason.
Poll PollStatus
// Generation is the generation of the held manifest after the round, zero before the first accepted one.
Generation uint64
// Changed says that the round accepted a manifest of another generation than the one held before it.
Changed bool
// Revision is the number of the last snapshot the reader emitted, zero before the first: the snapshot the round
// produced, or the one that was already out when it produced none.
Revision uint64
}
RefreshResult is the outcome of the round a Reader.Refresh waited for. It is never serialised: the endpoint of the relay answers with a type of its own.
type RejectionCount ¶
RejectionCount is the number of manifest rejections for one closed reason.
type Restored ¶
type Restored struct {
// ETag and Manifest are the last accepted manifest as it was saved.
ETag string
Manifest []byte
// Objects are the saved verified objects. The reader hashes them: a corrupted one is simply not found by
// its checksum and fetched again.
Objects [][]byte
// Stale lists the names that were served from earlier content when the state was saved: the reader gives
// each of them that content (found in Objects by its checksum) as its last good one, so after the restart the
// name is stale with the same bytes, not missing.
Stale []StaleObject
}
Restored is persisted state handed back to the reader at start (see Hooks.Restore).
type S3Provider ¶
S3Provider gives the S3 client of a named connection. connection.Factory implements it. The store asks on every call, so a client the factory replaced after a reload is picked up and there is never a second client for the connection.
type S3Store ¶
type S3Store struct {
// contains filtered or unexported fields
}
S3Store is an ObjectStore on the S3 client of a connection. It issues GetObject and nothing else: no HeadObject and no ListObjects.
func NewS3Store ¶
func NewS3Store(provider S3Provider, connectionName, bucket string) *S3Store
NewS3Store returns the store of bucket on the connection named connectionName. Keys are absolute bucket keys, as the publisher writes them (a key prefix is applied by the publisher only): the store fetches exactly the key it is given and never adds a prefix.
func (*S3Store) Get ¶
Get implements ObjectStore with GetObject, IfNoneMatch and VersionId. The body is read into one buffer sized from the Content-Length (or from the limit when the answer has none), never beyond the limit.
type Scheduler ¶
type Scheduler interface {
// Wait blocks for d, or until ctx is done; it then returns the error of ctx.
Wait(ctx context.Context, d time.Duration) error
}
Scheduler is the clock seam of the polling loop: the one place that waits. Tests drive the rounds with a scheduler of their own, so no test depends on a real timer.
type Snapshot ¶
type Snapshot struct {
// CreatedAt is the createdAt of the manifest, the same on every replica that reads it; zero when the manifest has
// none.
CreatedAt time.Time
// Objects maps the name of every object of the manifest to its state. Never change it.
Objects map[string]ObjectState
// Channel is the channel of the manifest.
Channel string
// Generation is the generation of the manifest.
Generation uint64
// Revision is the sequence number of the snapshot: the reader numbers every snapshot it emits, from 1, so a second
// snapshot at the same generation (an object that recovered) has a revision of its own.
Revision uint64
}
Snapshot is the immutable result of one generation of the manifest. A later snapshot of the same generation carries a state change of an object (a retried object that succeeded or failed again).
type StaleObject ¶
type StaleObject struct {
Name string
Kind string
Format string
Checksum controlplane.Checksum
}
StaleObject is the entry a name was served from when it was stale: the content is in Restored.Objects.
type State ¶
type State string
State is the state of one object name in a Snapshot. The set is closed.
const ( // StateOK means the bytes are the verified content of the checksum the manifest of this generation lists. StateOK State = "ok" // StateStale means the fetch or the verification of the listed content failed, and an earlier verified // content of the same name exists: the snapshot carries those bytes and their own checksum. StateStale State = "stale" // StateMissing means the fetch or the verification failed and no content of the name was ever loaded. StateMissing State = "missing" )
type StateStatus ¶
type StateStatus struct {
// LastSave is the time of the last write that ended, zero when none did.
LastSave time.Time `json:"lastSave"`
// Restore is a Restore* constant.
Restore string `json:"restore"`
// LastSaveError is the closed code of the failure of the last write, empty when it worked.
LastSaveError string `json:"lastSaveError"`
// ParentSync is a ParentSync* constant, or empty.
ParentSync string `json:"parentSync"`
// DisabledReason is the closed code of the refusal of the state directory (with [RestoreDisabled]).
DisabledReason string `json:"disabledReason"`
// Saves and SaveErrors count the writes that ended, and the ones that failed.
Saves uint64 `json:"saves"`
SaveErrors uint64 `json:"saveErrors"`
// PartialSaves counts the writes that kept only part of the objects because of the byte budget; they are
// not errors, and LastSavePartial tells that the last write was one.
PartialSaves uint64 `json:"partialSaves"`
// RestoredObjects and DiscardedObjects count the saved objects that were restored and the ones that were
// discarded as missing or corrupt.
RestoredObjects int `json:"restoredObjects"`
DiscardedObjects int `json:"discardedObjects"`
// Enabled tells that a state hook is installed.
Enabled bool `json:"enabled"`
// LastSavePartial tells that the last write kept only part of the objects (the byte budget).
LastSavePartial bool `json:"lastSavePartial"`
// Pending tells that a write is queued or running.
Pending bool `json:"pending"`
}
StateStatus is what the persistence behind the hooks reports. A hook that is not installed reports the zero value.
type Status ¶
type Status struct {
LastSync time.Time `json:"lastSync"`
Poll PollStatus `json:"poll"`
Failures []ObjectFailure `json:"failures"`
// HookPanics lists the hooks that panicked (recovered), with counts; empty when none.
HookPanics []HookPanic `json:"hookPanics"`
// PollResults counts the polls by result (the Poll* constants), sorted by result; results that did not
// happen are absent.
PollResults []PollCount `json:"pollResults"`
// Rejections counts manifest rejections by closed reason, sorted by reason; reasons with zero count are absent.
Rejections []RejectionCount `json:"rejections,omitempty"`
Manifest ManifestStatus `json:"manifest"`
State StateStatus `json:"state"`
// Backoff is the backoff state: the consecutive failures of the manifest poll and the wait planned after
// this round.
Backoff BackoffStatus `json:"backoff"`
Counts Counts `json:"counts"`
// Cache is what the reader holds in memory: verified objects, by checksum.
Cache CacheStatus `json:"cache"`
Polls uint64 `json:"polls"`
NotModified uint64 `json:"notModified"`
}
Status is the immutable state of the reader at the end of a round. Take it with Reader.Status; never change the slice.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package readertest is the conformance suite of the manifest reader over a store: what a connection type gives the relay once its manifestreader.ObjectStore is plugged into a manifestreader.Reader.
|
Package readertest is the conformance suite of the manifest reader over a store: what a connection type gives the relay once its manifestreader.ObjectStore is plugged into a manifestreader.Reader. |
|
Package statedir keeps the last accepted manifest and its verified objects in a directory, so a restart serves the last content even when the store is unreachable, and costs one conditional GET (a 304) and no object GET when it is not.
|
Package statedir keeps the last accepted manifest and its verified objects in a directory, so a restart serves the last content even when the store is unreachable, and costs one conditional GET (a 304) and no object GET when it is not. |
|
Package storetest is the conformance suite of manifestreader.ObjectStore: the contract of a store as executable cases.
|
Package storetest is the conformance suite of manifestreader.ObjectStore: the contract of a store as executable cases. |