httpstore

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 22 Imported by: ? 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 httpstore is the objectstore.ObjectStore on a plain HTTP server (static hosting, a CDN). It cannot list. It refuses a redirect to another origin, a lower scheme or an address with credentials, and holds its headers as secrets. An http connection is a flag source whose sources name their flag set files by key. GitHubConfig sets the same store up for the contents API of a GitHub repository (the address, the raw media type, the branch and the rate limit answers of GitHub). It cannot list either.

Index

Constants

View Source
const (
	// BitbucketDefaultEndpoint is the API of bitbucket.org; the API path /2.0 is added to it.
	BitbucketDefaultEndpoint = "https://api.bitbucket.org"
	// BitbucketDefaultBranch is the branch that is read when none is set.
	BitbucketDefaultBranch = "main"
)
View Source
const (
	// GitHubDefaultEndpoint is the API of github.com.
	GitHubDefaultEndpoint = "https://api.github.com"
	// GitHubDefaultBranch is the branch that is read when none is set.
	GitHubDefaultBranch = "main"
)
View Source
const (
	// GitLabDefaultEndpoint is the address of gitlab.com; the API path /api/v4 is added to it.
	GitLabDefaultEndpoint = "https://gitlab.com"
	// GitLabDefaultBranch is the branch that is read when none is set.
	GitLabDefaultBranch = "main"
)
View Source
const (
	// MaxHTTPKeyBytes is the longest key of an http store.
	MaxHTTPKeyBytes = 1024
)

Variables

View Source
var (
	// ErrHTTPKeyRefused is the cause of a key that is not a clean relative slash path (see [storekit.ValidKey]) or that
	// is longer than [MaxHTTPKeyBytes].
	ErrHTTPKeyRefused = errors.New("objectstore: http key refused")
	// ErrHTTPAuth is the cause of a 401 or 403 answer.
	ErrHTTPAuth = errors.New("objectstore: 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("objectstore: 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("objectstore: 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("objectstore: http body is not delimited")
	// ErrHTTPRateLimited is the cause of an answer that says the request limit of the server is used up (see
	// [Config.RateLimitHeaders]). The error text names the time the server gives for the reset, when it gives one.
	ErrHTTPRateLimited = errors.New("objectstore: http request limit reached")
	// ErrHTTPDirectory is the cause of a key that the server answers with a directory listing instead of the object
	// (see [Config.DirectoryMedia]). The text names the key. It is not retryable.
	ErrHTTPDirectory = errors.New("objectstore: the key is a directory")
)

Causes carried by the *objectstore.FetchError of an Store, and by the errors of New. They are for errors.Is; the reader reports only the reason.

View Source
var ErrBitbucketSlug = errors.New("objectstore: expected a bitbucket repository slug of the form workspace/repo")

ErrBitbucketSlug is the cause of a repository slug that is not workspace/repo.

View Source
var ErrGitHubSlug = errors.New("objectstore: expected a github repository slug of the form owner/repo")

ErrGitHubSlug is the cause of a repository slug that is not owner/repo.

View Source
var ErrGitLabSlug = errors.New("objectstore: expected a gitlab project slug of the form group/project")

ErrGitLabSlug is the cause of a project slug that is not group/project (nested groups allowed).

Functions

func ValidHTTPKey

func ValidHTTPKey(key string) bool

ValidHTTPKey reports whether key is a clean relative slash path of at most MaxHTTPKeyBytes bytes.

Types

type BitbucketConfig added in v1.5.0

type BitbucketConfig struct {
	// Tracing are the OpenTelemetry providers: every request has a client span (see [Config.Tracing]).
	Tracing tracing.Providers
	// Now is the clock of the wait after a rate limit answer; nil means the clock of the module.
	Now func() time.Time `json:"-" yaml:"-"`
	// Token is the access token (a repository or workspace access token with read access to the repository). Empty
	// reads public repositories without one. It is sent to the endpoint only, never to another host.
	Token storekit.Secret
	// RepositorySlug is workspace/repo.
	RepositorySlug string
	// Branch is the branch, tag or commit that is read. Empty means [BitbucketDefaultBranch].
	Branch string
	// Endpoint is the address of the API without /2.0. Empty means [BitbucketDefaultEndpoint].
	Endpoint string
	// CABundlePEM holds certificate authorities trusted in addition to the system roots.
	CABundlePEM []byte
	// ConnectTimeout, HeaderTimeout and RequestTimeout are the timeouts of [Config].
	ConnectTimeout time.Duration
	HeaderTimeout  time.Duration
	RequestTimeout time.Duration
	// MinTLSVersion is a tls.Version constant; zero means TLS 1.2.
	MinTLSVersion uint16
}

BitbucketConfig is the setting of a Store on the source API of Bitbucket Cloud, see BitbucketConfig.StoreConfig.

func (*BitbucketConfig) StoreConfig added in v1.5.0

func (cfg *BitbucketConfig) StoreConfig() (*Config, error)

StoreConfig checks the setting and returns the Config of the Store that reads the source API of the repository and the branch: GET <endpoint>/2.0/repositories/<workspace>/<repo>/src/<branch>/<path>. The branch is one path segment (a "/" in it is %2F) and every element of the file path is one segment too. The ETag is the validator when Bitbucket sends one; the digest of the body keeps an unchanged file unchanged otherwise. A 429 is a throttling answer and the store sends no request before the reset time it gives (see Store); so is a count of requests that remain, read in X-RateLimit-Limit as GO Feature Flag does, of zero or less. A key that is a directory is refused with ErrHTTPDirectory when the body has the shape of the listing of Bitbucket. A redirect to another origin is not followed, so the token never leaves the endpoint.

type Config

type Config struct {
	// Tracing are the OpenTelemetry providers of the store: with them enabled every request has a client span and
	// carries the trace context and the baggage of the context of the call. The span is the stock one of the HTTP
	// instrumentation: it records the URL as it is (the base URL has no credentials and no query, and the headers are
	// not recorded). The zero value instruments nothing.
	Tracing tracing.Providers
	// DialContext opens the connections of the store. Nil means a [net.Dialer] bounded by ConnectTimeout, which also
	// refuses a cleartext connection to an address that is not a loopback one (unless AllowCleartext is set). A
	// function set here replaces that dialer and its checks: it is for a caller that owns the transport, such as a
	// test that runs the store over an in-memory connection.
	DialContext func(ctx context.Context, network, address string) (net.Conn, error) `json:"-" yaml:"-"`
	// 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
	// Now is the clock of the wait after a throttling answer (see [Store]); nil means [clock.Now].
	Now func() time.Time `json:"-" yaml:"-"`
	// BaseURL is the address the keys are resolved below: https://host/prefix. No credentials, query or fragment.
	BaseURL string
	// Accept is the Accept header of every request. Empty means "*/*".
	Accept string
	// Query is a fixed, already encoded query (a=b&c=d) added to the address of every key, without the "?". It is not
	// secret: the span of every request records the address as it is (url.full), and the error texts of the store can
	// name it. A caller must never put a credential in it; send a credential as a header.
	Query string
	// DirectoryMedia is a media type (for example application/json) that a 200 answer must not have: the server
	// answers a key that is a directory with a listing of that type, and the store refuses it with [ErrHTTPDirectory].
	// Empty means every 200 is the object.
	DirectoryMedia string
	// ListingBody recognises, by the shape of the body of a 200 answer, the listing that a server sends for a key that
	// is a directory (see [ErrHTTPDirectory]). It is for a server that serves a file with any media type, so that
	// DirectoryMedia cannot tell the two apart. It must be false for every body that a valid file can have. Nil means
	// no body is tested.
	ListingBody func(body []byte) bool `json:"-" yaml:"-"`
	// RemainingHeaders are more headers that carry the number of requests that remain, next to <prefix>Remaining. A
	// count of zero or less closes the store until the reset time on any answer, not only on a 403 or 429 (the
	// retriever of GO Feature Flag for Bitbucket reads X-RateLimit-Limit so). Empty means none. It only counts with
	// RateLimitHeaders.
	RemainingHeaders []string
	// KeySuffix is a fixed path added after the key (for example "/raw"), without credentials or query.
	KeySuffix string
	// RateLimitPrefix is the start of the names of the rate limit headers: <prefix>Remaining and <prefix>Reset. Empty
	// means "X-RateLimit-" (GitHub); "RateLimit-" is the GitLab one. It only counts with RateLimitHeaders.
	RateLimitPrefix 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
	// [storekit.DefaultHTTPConnectTimeout]. The timeouts are at most [storekit.MaxHTTPTimeout] and not negative.
	ConnectTimeout time.Duration
	// HeaderTimeout bounds the wait for the response headers. Zero means [storekit.DefaultHTTPHeaderTimeout].
	HeaderTimeout time.Duration
	// RequestTimeout bounds one Get, body included. Zero means [storekit.DefaultHTTPRequestTimeout].
	RequestTimeout time.Duration
	// MaxRetryAfter bounds the Retry-After that is passed on. Zero means [storekit.MaxHTTPRetryAfter].
	MaxRetryAfter time.Duration
	// MaxRedirects is the number of redirects followed: zero follows none. A negative value means
	// [storekit.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
	// RateLimitHeaders makes the store read the headers of a server that tells its request limit
	// (X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After): a 403 that says the limit is used up is a throttling
	// answer, not a refusal.
	RateLimitHeaders bool
	// KeyAsSegment sends the whole key as one path segment: every "/" of the key is sent as %2F (and "." as %2E, "+"
	// as %2B), as the repository files API of GitLab wants it. Otherwise each element of the key is a path segment.
	KeyAsSegment bool
}

Config is the setting of an Store.

type GitHubConfig added in v1.5.0

type GitHubConfig struct {
	// Tracing are the OpenTelemetry providers: every request has a client span (see [Config.Tracing]).
	Tracing tracing.Providers
	// Now is the clock of the wait after a rate limit answer; nil means the clock of the module.
	Now func() time.Time `json:"-" yaml:"-"`
	// Token is the access token (a personal access token, fine-grained with read access to Contents). Empty reads
	// public repositories without one. It is sent to the endpoint only, never to another host.
	Token storekit.Secret
	// RepositorySlug is owner/repo.
	RepositorySlug string
	// Branch is the branch, tag or commit that is read. Empty means [GitHubDefaultBranch].
	Branch string
	// Endpoint is the API address, for GitHub Enterprise Server https://host/api/v3. Empty means [GitHubDefaultEndpoint].
	Endpoint string
	// CABundlePEM holds certificate authorities trusted in addition to the system roots.
	CABundlePEM []byte
	// ConnectTimeout, HeaderTimeout and RequestTimeout are the timeouts of [Config].
	ConnectTimeout time.Duration
	HeaderTimeout  time.Duration
	RequestTimeout time.Duration
	// MinTLSVersion is a tls.Version constant; zero means TLS 1.2.
	MinTLSVersion uint16
}

GitHubConfig is the setting of a Store on the contents API of GitHub, see GitHubConfig.StoreConfig.

func (*GitHubConfig) StoreConfig added in v1.5.0

func (cfg *GitHubConfig) StoreConfig() (*Config, error)

StoreConfig checks the setting and returns the Config of the Store that reads the contents API of the repository and the branch. The ETag of GitHub is the validator: an unchanged file costs a 304, which GitHub does not count against the rate limit. A 403 or 429 that says the request limit is used up is a retryable throttling answer, not a refusal, and the store sends no request before the reset time it gives (see Store). A key that is a directory is refused with ErrHTTPDirectory. A redirect to another origin is not followed, so the token never leaves the endpoint.

type GitLabConfig added in v1.5.0

type GitLabConfig struct {
	// Tracing are the OpenTelemetry providers: every request has a client span (see [Config.Tracing]).
	Tracing tracing.Providers
	// Now is the clock of the wait after a rate limit answer; nil means the clock of the module.
	Now func() time.Time `json:"-" yaml:"-"`
	// Token is the access token (a project, group or personal access token with the read_repository scope). Empty reads
	// public projects without one. It is sent to the endpoint only, never to another host.
	Token storekit.Secret
	// RepositorySlug is the path of the project: group/project, or group/subgroup/project, or a numeric project ID.
	RepositorySlug string
	// Branch is the branch, tag or commit that is read. Empty means [GitLabDefaultBranch].
	Branch string
	// Endpoint is the address of GitLab without /api/v4, for a self-managed instance https://host or
	// https://host/gitlab. Empty means [GitLabDefaultEndpoint].
	Endpoint string
	// CABundlePEM holds certificate authorities trusted in addition to the system roots.
	CABundlePEM []byte
	// ConnectTimeout, HeaderTimeout and RequestTimeout are the timeouts of [Config].
	ConnectTimeout time.Duration
	HeaderTimeout  time.Duration
	RequestTimeout time.Duration
	// MinTLSVersion is a tls.Version constant; zero means TLS 1.2.
	MinTLSVersion uint16
}

GitLabConfig is the setting of a Store on the repository files API of GitLab, see GitLabConfig.StoreConfig.

func (*GitLabConfig) StoreConfig added in v1.5.0

func (cfg *GitLabConfig) StoreConfig() (*Config, error)

StoreConfig checks the setting and returns the Config of the Store that reads the raw files of the project and the branch: GET <endpoint>/api/v4/projects/<slug>/repository/files/<path>/raw?ref=<branch>, where the slug and the path are each one path segment (every "/" is %2F). The ETag of GitLab is the validator; when a server does not answer a conditional request with 304, the digest of the body keeps an unchanged file unchanged. A 429 is a throttling answer and the store sends no request before the reset time it gives (see Store). A redirect to another origin is not followed, so the token never leaves the endpoint.

type HTTPHeaders

type HTTPHeaders map[string]string

HTTPHeaders are the headers of an Store: 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 Store

type Store struct {
	objectstore.NoLifecycle
	// contains filtered or unexported fields
}

Store is an objectstore.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 objectstore.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.

With Config.RateLimitHeaders an answer that says the request limit is used up also closes the store for a while, like the retriever of GO Feature Flag, which does not call GitHub before the reset time: the store remembers, in memory, the time the server gives (the X-RateLimit-Reset time when no request remains, or now plus the Retry-After wait; the later one when both are given). Until then every Get returns the same retryable throttling error at once and sends no request, and after it the next Get goes out normally. The time is taken as the server gives it: no upper bound is applied to the reset time, as GO Feature Flag has none; a reset that is already past closes nothing.

VersionID is not supported: a request for one is answered with objectstore.ErrNotFound. Besides its connection pool and that closing time the store holds no state and is safe for concurrent use.

func New

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

New checks the setting and returns the store. A cleartext address is accepted only for a loopback host, or when Config.AllowCleartext is set.

func (*Store) CloseIdleConnections

func (s *Store) CloseIdleConnections()

CloseIdleConnections closes the idle connections of the pool.

func (*Store) Format

func (s *Store) Format(f fmt.State, _ rune)

Format implements fmt.Formatter: the store prints its origin and base path, never a header.

func (*Store) Get

Get implements objectstore.ObjectStore. See Store for the rules.

Jump to

Keyboard shortcuts

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