connection

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 30 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package 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

View Source
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.

View Source
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.

View Source
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.

View Source
const RedactedValue = "[REDACTED]"

RedactedValue is what a Secret prints instead of its content.

Variables

View Source
var ErrInvalidSpec = errors.New("invalid connection spec")

ErrInvalidSpec matches (errors.Is) the SpecError.

View Source
var ErrUnknownConnection = errors.New("unknown connection")

ErrUnknownConnection matches (errors.Is) the UnknownConnectionError.

View Source
var ErrWrongKind = errors.New("connection kind mismatch")

ErrWrongKind matches (errors.Is) the KindError.

Functions

func IsNotModified

func IsNotModified(err error) bool

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

func NoRedirect(*http.Request, []*http.Request) error

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.

func (*AWSSpec) Identity

func (s *AWSSpec) Identity() string

Identity implements Spec.

func (*AWSSpec) Kind

func (s *AWSSpec) Kind() string

Kind implements Spec.

func (*AWSSpec) Validate

func (s *AWSSpec) Validate() error

Validate implements Spec.

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

func New(opts ...Option) *Factory

New returns an empty factory; load its connections with Factory.Replace or Factory.Set.

func (*Factory) AWSConfig

func (f *Factory) AWSConfig(ctx context.Context, name string) (aws.Config, error)

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

func (f *Factory) Builds() map[string]int

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) GoString

func (f *Factory) GoString() string

GoString implements fmt.GoStringer.

func (*Factory) Names

func (f *Factory) Names() []string

Names returns the connection names, sorted.

func (*Factory) Remove

func (f *Factory) Remove(name string)

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

func (f *Factory) Replace(specs map[string]Spec) error

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

func (f *Factory) S3(ctx context.Context, name string) (*s3.Client, error)

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

func (f *Factory) Set(name string, spec Spec) error

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

func (f *Factory) String() string

String implements fmt.Stringer: the factory prints its size only, never its specs.

type KindError

type KindError struct {
	Name string
	Want string
	Got  string
}

KindError is returned when a client is requested from a connection of another kind.

func (*KindError) Error

func (e *KindError) Error() string

Error implements error.

func (*KindError) Is

func (*KindError) Is(target error) bool

Is reports whether target is ErrWrongKind.

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

func WithLogger(logger *slog.Logger) Option

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

func WithReadFile(readFile func(string) ([]byte, error)) Option

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.

func (*S3Spec) Identity

func (s *S3Spec) Identity() string

Identity implements Spec.

func (*S3Spec) Kind

func (*S3Spec) Kind() string

Kind implements Spec.

func (*S3Spec) Validate

func (s *S3Spec) Validate() error

Validate implements Spec.

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 NewSecret

func NewSecret(value string) Secret

NewSecret returns the Secret holding value.

func (Secret) Format

func (Secret) Format(state fmt.State, _ rune)

Format implements fmt.Formatter: every verb prints RedactedValue.

func (Secret) GoString

func (Secret) GoString() string

GoString implements fmt.GoStringer.

func (Secret) IsZero

func (s Secret) IsZero() bool

IsZero reports whether the secret is empty.

func (Secret) LogValue

func (Secret) LogValue() slog.Value

LogValue implements slog.LogValuer.

func (Secret) MarshalJSON

func (Secret) MarshalJSON() ([]byte, error)

MarshalJSON implements [json.Marshaler].

func (Secret) MarshalText

func (Secret) MarshalText() ([]byte, error)

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

func (Secret) MarshalYAML() (any, error)

MarshalYAML implements the Marshaler interface of the YAML encoders.

func (Secret) Reveal

func (s Secret) Reveal() string

Reveal returns the secret value.

func (Secret) String

func (Secret) String() string

String implements fmt.Stringer.

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

type SpecError struct {
	Connection string
	Field      string
	Reason     string
}

SpecError is returned for a spec that fails validation. It never contains a secret value.

func (*SpecError) Error

func (e *SpecError) Error() string

Error implements error.

func (*SpecError) Is

func (*SpecError) Is(target error) bool

Is reports whether target is ErrInvalidSpec.

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.

Jump to

Keyboard shortcuts

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