Documentation
¶
Overview ¶
Package connection builds and shares the AWS clients of the relay: exactly one client per named connection (one bucket or endpoint, one region, one credentials identity) per process.
A Spec describes a connection. A Factory holds the specs by name, builds the client of a connection on first use, hands the same client to every caller, and on a reload (Factory.Replace) keeps the client of a connection whose Spec.Identity did not change. The AWS backed kinds live in this package; a backend that is not AWS gets its own spec type and factory method.
Every attempt of every request made through a client is reported to the RequestObserver of the factory, with the closed set of results defined in this package. The package does not import Prometheus: the relay maps the observer to its metric.
Region and endpoint come from the spec only, never from the process environment or the shared config files, and no state is global: two connections can use two endpoints in one process. The only environment access is the one of the AWS SDK for credentials of type chain (and assumeRole without source keys). The HTTP clients the factory builds do not follow redirects. An observation is one attempt of the SDK: the Go transport may replay an idempotent request, only when the first send got no response, without a new observation.
Index ¶
- Constants
- Variables
- func IsNotModified(err error) bool
- func NoRedirect(*http.Request, []*http.Request) error
- type AWSSpec
- type ChecksumMode
- type Common
- type Credentials
- type CredentialsType
- type Factory
- func (f *Factory) AWSConfig(ctx context.Context, name string) (aws.Config, error)
- func (f *Factory) Builds() map[string]int
- func (f *Factory) GoString() string
- func (f *Factory) Names() []string
- func (f *Factory) Remove(name string)
- func (f *Factory) Replace(specs map[string]Spec) error
- func (f *Factory) S3(ctx context.Context, name string) (*s3.Client, error)
- func (f *Factory) Set(name string, spec Spec) error
- func (f *Factory) String() string
- type KindError
- type Option
- type RequestObserver
- type Retry
- type S3Spec
- type Secret
- func (Secret) Format(state fmt.State, _ rune)
- func (Secret) GoString() string
- func (s Secret) IsZero() bool
- func (Secret) LogValue() slog.Value
- func (Secret) MarshalJSON() ([]byte, error)
- func (Secret) MarshalText() ([]byte, error)
- func (Secret) MarshalYAML() (any, error)
- func (s Secret) Reveal() string
- func (Secret) String() string
- type Spec
- type SpecError
- type UnknownConnectionError
Constants ¶
const ( // ResultOK is a 2xx answer. ResultOK = "ok" // ResultNotModified is a 304 answer to a conditional request. It is not a failure. ResultNotModified = "not_modified" // ResultNotFound is a 404 answer. ResultNotFound = "not_found" // ResultThrottled is a 429 answer, or an error whose code is a throttling code (for example SlowDown). ResultThrottled = "throttled" // ResultClientError is any other 4xx answer (403, 400, ...). ResultClientError = "client_error" // ResultRedirect is a 3xx answer other than 304: the factory clients never follow redirects, so the SDK // gets the redirect itself and the redirect is one observation. ResultRedirect = "redirect" // ResultServerError is a 5xx answer that is not a throttle. ResultServerError = "server_error" // ResultError is an attempt without a usable answer: transport error, timeout, cancellation, or a 2xx // answer the SDK could not decode. ResultError = "error" )
The results reported to a RequestObserver: a closed set.
const ( OperationGet = "get" OperationList = "list" OperationHead = "head" OperationPut = "put" OperationDelete = "delete" OperationOther = "other" )
The operation labels reported to a RequestObserver: a closed set, derived from the SDK operation name.
const ( // KindS3 is an S3 (or S3 compatible) bucket. KindS3 = "s3" // KindKinesis is a Kinesis stream backend. KindKinesis = "kinesis" // KindSQS is an SQS backend. KindSQS = "sqs" // KindRedshift is a Redshift data API backend. KindRedshift = "redshift" )
Kind names of the AWS backed connections the factory builds.
const RedactedValue = "[REDACTED]"
RedactedValue is what a Secret prints instead of its content.
Variables ¶
var ErrInvalidSpec = errors.New("invalid connection spec")
ErrInvalidSpec matches (errors.Is) the SpecError.
var ErrUnknownConnection = errors.New("unknown connection")
ErrUnknownConnection matches (errors.Is) the UnknownConnectionError.
var ErrWrongKind = errors.New("connection kind mismatch")
ErrWrongKind matches (errors.Is) the KindError.
Functions ¶
func IsNotModified ¶
IsNotModified reports whether err is the error the SDK returns for a conditional request answered with 304: an HTTP 304 in the response error, or the NotModified API error code. A caller checks it before any logging or counting, so a 304 is never handled as a failure.
func NoRedirect ¶
NoRedirect is the http.Client.CheckRedirect of every client the factory builds: a 3xx answer is returned to the SDK instead of followed, so a redirect never turns one SDK attempt into several requests.
Types ¶
type AWSSpec ¶
type AWSSpec struct {
Common
// Type is the connection kind: [KindKinesis], [KindSQS] or [KindRedshift].
Type string `json:"type"`
}
AWSSpec is the spec of a Kinesis, SQS or Redshift connection. Pass it to the factory as a pointer and do not change it after.
type ChecksumMode ¶
type ChecksumMode string
ChecksumMode is the value of a checksum setting.
const ( // ChecksumDefault keeps the SDK default. ChecksumDefault ChecksumMode = "" // ChecksumWhenSupported computes (or validates) a checksum whenever the operation supports it. ChecksumWhenSupported ChecksumMode = "whenSupported" // ChecksumWhenRequired computes (or validates) a checksum only when the operation requires it. ChecksumWhenRequired ChecksumMode = "whenRequired" )
The checksum modes. The empty value keeps the SDK default.
type Common ¶
type Common struct {
Credentials Credentials `json:"credentials"`
// Endpoint is the service endpoint (emulators, S3 compatible stores); empty means the AWS endpoint of
// the region. Environment endpoint variables (AWS_ENDPOINT_URL, AWS_ENDPOINT_URL_S3, ...) are ignored.
Endpoint string `json:"endpoint"`
// Region is the AWS region. It is required: a connection never takes its region from the process
// environment or the shared config files.
Region string `json:"region"`
// CABundleFile is a PEM file of certificate authorities trusted in addition to the system roots, for TLS
// emulators and private S3 compatible stores. Empty means the system roots only. The identity holds the
// path, not the content.
CABundleFile string `json:"caBundleFile"`
Retry Retry `json:"retry"`
// ConnectTimeout bounds the TCP connect only; zero means 30s. The TLS handshake is bounded by 10s.
// It is ignored when the factory has an HTTP client or round tripper override.
ConnectTimeout time.Duration `json:"connectTimeout"`
// RequestTimeout bounds the wait for the response headers of one HTTP attempt, once the request is
// written; zero means no limit besides the context. It does not bound the reading of the body, which
// only the context of the caller cancels. It is ignored when the factory has an HTTP client or round
// tripper override.
RequestTimeout time.Duration `json:"requestTimeout"`
}
Common holds the settings shared by every AWS backed connection.
type Credentials ¶
type Credentials struct {
// Type defaults to chain.
Type CredentialsType `json:"type"`
// AccessKeyID, SecretAccessKey and SessionToken are the static credentials (SessionToken is optional).
// With assumeRole they are the source credentials; without them the chain is the source.
AccessKeyID Secret `json:"accessKeyId"`
SecretAccessKey Secret `json:"secretAccessKey"`
SessionToken Secret `json:"sessionToken"`
// RoleARN is the role of assumeRole and webIdentity.
RoleARN string `json:"roleArn"`
// SessionName is the role session name (assumeRole, webIdentity); optional.
SessionName string `json:"sessionName"`
// ExternalID is the external id of assumeRole; optional.
ExternalID string `json:"externalId"`
// TokenFile is the web identity token file path.
TokenFile string `json:"tokenFile"`
// STSEndpoint overrides the STS endpoint of assumeRole and webIdentity; optional.
STSEndpoint string `json:"stsEndpoint"`
}
Credentials holds the credentials settings of a connection. Secret material is already resolved.
type CredentialsType ¶
type CredentialsType string
CredentialsType selects how the credentials of a connection are resolved.
const ( // CredentialsChain is the SDK default chain (environment, shared files, container, instance role). // It is the default when the type is empty. CredentialsChain CredentialsType = "chain" // CredentialsStatic is a fixed access key. CredentialsStatic CredentialsType = "static" // CredentialsAssumeRole assumes a role with the chain credentials as the source. CredentialsAssumeRole CredentialsType = "assumeRole" // CredentialsWebIdentity assumes a role with a web identity token file. CredentialsWebIdentity CredentialsType = "webIdentity" )
The credentials types.
type Factory ¶
type Factory struct {
// contains filtered or unexported fields
}
Factory holds the specs of the connections by name and builds exactly one AWS configuration (and S3 client) per connection and identity. It is safe for concurrent use.
No lock is held while a callback runs (logger, observer, ReadFile, Spec methods); a build holds only the lock of its own entry, and a reload waits for a build in progress on a replaced entry before closing it.
func New ¶
New returns an empty factory; load its connections with Factory.Replace or Factory.Set.
func (*Factory) AWSConfig ¶
AWSConfig returns a copy of the AWS configuration of the connection name, built once per identity. It serves any AWS backed connection (S3, Kinesis, SQS, Redshift). The configuration carries the endpoint and region of the spec and ignores the process environment and shared config files for them (and for service endpoints), but a service client built from it must not be given another endpoint.
The copy shares nothing mutable with the cached configuration, except what is shared on purpose: the HTTP client (the one connection pool of the connection) and the credentials provider (the one credentials cache). The provider prints as RedactedValue.
func (*Factory) Builds ¶
Builds returns, per connection name, how many AWS configurations (and with them the S3 client) the factory built for it since it was created. A connection used by any number of callers and never changed has one. A caller that builds several service clients (SQS, Kinesis, ...) from one Factory.AWSConfig is not counted: the factory only sees the configuration.
func (*Factory) Remove ¶
Remove drops the connection name and closes the idle connections of its client; it is a no-op for an unknown name. A caller that was about to build the client of the removed connection gets ErrUnknownConnection (or the client of the connection if the name was added again meanwhile).
func (*Factory) Replace ¶
Replace makes specs the whole set of connections, as a reload does: a connection whose identity did not change keeps its client, a changed one gets a new client on next use, and a connection that is not in specs is dropped. The idle connections of every dropped or replaced client are closed. An invalid spec changes nothing.
func (*Factory) S3 ¶
S3 returns the S3 client of the connection name: the same client for every caller until the identity of the connection changes.
func (*Factory) Set ¶
Set adds or updates the connection name. The client built for it is kept when the identity of spec is the one already held, and rebuilt on next use otherwise (the idle connections of the old one are closed). The CA bundle of the spec, if any, is read and parsed here, once. An invalid spec changes nothing.
func (*Factory) String ¶
String implements fmt.Stringer: the factory prints its size only, never its specs.
type KindError ¶
KindError is returned when a client is requested from a connection of another kind.
type Option ¶
type Option func(*Factory)
Option configures a Factory.
func WithHTTPClient ¶
func WithHTTPClient(client aws.HTTPClient) Option
WithHTTPClient makes every client use client instead of one HTTP client per connection (tests). The timeouts of the specs and the redirect policy are then the business of client: to keep the request metric exact, it must not follow redirects (see NoRedirect). The factory never closes it.
func WithLogger ¶
WithLogger sets the logger of the factory (client builds, at debug level). It never receives a secret.
func WithObserver ¶
func WithObserver(obs RequestObserver) Option
WithObserver reports every HTTP attempt of the AWS clients to obs.
func WithReadFile ¶
WithReadFile sets the function that reads the CA bundle files of the specs (default os.ReadFile).
func WithRoundTripper ¶
func WithRoundTripper(rt http.RoundTripper) Option
WithRoundTripper makes every client use rt as the transport of an HTTP client of its own (tests). That client does not follow redirects. The timeouts of the specs do not apply (they configure the transport the factory builds itself), and when a connection is dropped or replaced the factory calls CloseIdleConnections on rt if it has the method.
type RequestObserver ¶
type RequestObserver interface {
// Observe records one attempt of connection, with an operation (an Operation* constant) and a
// result (a Result* constant).
Observe(connection, operation, result string)
}
RequestObserver is told about every HTTP attempt made by the clients of a Factory: once per attempt, so an operation retried after a 503 is observed twice. An observation is an attempt of the SDK, not a write on the wire: the Go transport may replay an idempotent request on a kept-alive connection that died before any response byte, without another observation. The service answered none of the replayed requests, so it processed at most one of them. It is called on the goroutine of the request and must not block. The relay maps it to semaphore_s3_requests_total.
type Retry ¶
type Retry struct {
// MaxAttempts is the maximum number of attempts of one operation, the first one included.
MaxAttempts int `json:"maxAttempts"`
// MaxBackoff is the longest wait between two attempts.
MaxBackoff time.Duration `json:"maxBackoff"`
}
Retry holds the retry settings. A zero value keeps the SDK default.
type S3Spec ¶
type S3Spec struct {
Common
// Bucket is the bucket of the connection; it is not required by the factory, the users of the
// connection require it when they need one.
Bucket string `json:"bucket"`
// RequestChecksumCalculation and ResponseChecksumValidation default to the SDK default.
RequestChecksumCalculation ChecksumMode `json:"requestChecksumCalculation"`
ResponseChecksumValidation ChecksumMode `json:"responseChecksumValidation"`
PathStyle bool `json:"pathStyle"`
}
S3Spec is the spec of an S3 connection. Pass it to the factory as a pointer and do not change it after.
type Secret ¶
type Secret struct {
// contains filtered or unexported fields
}
Secret is secret material, already resolved to its value. Whatever the fmt verb (%v %+v %#v %s %q %d %x %c %U ...), the JSON or text encoder (as a value, a field, a map value or a map key), the YAML encoder or the slog handler, it prints RedactedValue. Use Secret.Reveal where the value is really needed.
It is a struct with one unexported field, so the content cannot be reached by a conversion, and a Secret cannot be a JSON map key without going through Secret.MarshalText.
A Secret is not meant to be a map key. As a key it encodes to the redaction marker like everywhere else, so several secret keys give several JSON members with the same name, and a decoder keeps only one of them. That is deliberate: the value is never emitted, whatever it costs in entries.
What cannot be covered: %p, reflection (including fmt's own printing of an unexported field holding a Secret), unsafe, and a debugger or a core dump.
func (Secret) Format ¶
Format implements fmt.Formatter: every verb prints RedactedValue.
func (Secret) MarshalJSON ¶
MarshalJSON implements [json.Marshaler].
func (Secret) MarshalText ¶
MarshalText implements encoding.TextMarshaler, also used by JSON for map keys. Every secret key gets the same name, so a map keyed by secrets loses entries when decoded: a Secret is not meant to be a map key.
func (Secret) MarshalYAML ¶
MarshalYAML implements the Marshaler interface of the YAML encoders.
type Spec ¶
type Spec interface {
// Kind is the connection type (s3, kinesis, sqs, redshift, ...).
Kind() string
// Identity is a stable fingerprint of everything that affects the client: two specs with the same
// identity build interchangeable clients. It never contains a secret in clear.
Identity() string
// Validate reports the first invalid field, as a [SpecError].
Validate() error
}
Spec describes one connection. The AWS backed kinds (S3Spec, AWSSpec) live in this package and are the only ones the Factory can build clients for; a backend that is not AWS gets its own spec type and its own factory method later, without changing the callers of the existing ones.
type SpecError ¶
SpecError is returned for a spec that fails validation. It never contains a secret value.
type UnknownConnectionError ¶
type UnknownConnectionError struct {
Name string
}
UnknownConnectionError is returned when a name has no spec in the factory.
func (*UnknownConnectionError) Error ¶
func (e *UnknownConnectionError) Error() string
Error implements error.
func (*UnknownConnectionError) Is ¶
func (*UnknownConnectionError) Is(target error) bool
Is reports whether target is ErrUnknownConnection.