httpclient

package module
v0.0.0-...-8516231 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 41 Imported by: 0

README

go-http-client

go-http-client is a policy layer for typed outbound HTTP integrations. It is built on net/http, preserves standard requests and responses, and is neutral about vendor models and payload codecs.

The module is under active pre-v1 development. The current foundation provides finite transport defaults, immutable request specifications, deterministic operation and attempt middleware, origin-bound authentication, explicit transport ownership, response lifecycle management, and redacted errors.

The public API reference maps the complete Go documentation. Start with the transport guide, typed integration patterns, and error classification. Release-facing policies and additional guides are indexed in the repository docs directory.

Install

go get github.com/faustbrian/go-http-client

Quickstart

client, err := httpclient.New(httpclient.Config{})
if err != nil {
	return err
}
defer client.Close()

request, err := http.NewRequestWithContext(
	ctx,
	http.MethodGet,
	"https://api.example.com/widgets",
	nil,
)
if err != nil {
	return err
}

response, err := client.Do(request)
if err != nil {
	return err
}
defer response.Body.Close()

Reusable endpoint definitions can use an immutable request specification:

spec, err := httpclient.NewRequestSpec(
	"https://api.example.com/v1/",
	"widgets",
)
if err != nil {
	return err
}

spec, err = spec.WithQuery(
	httpclient.LayerRequest,
	"include",
	httpclient.RepeatedQuery("owner", "history"),
)
if err != nil {
	return err
}

request, err := spec.Build(ctx, http.MethodGet)

Each build returns an independent *http.Request; its URL, headers, and query state do not alias the specification or another build. See request construction and serialization for precedence, encoding, and body ownership details.

Request bodies include replayable byte and canonical form snapshots, replayable factories, explicitly one-shot streams, and bounded streaming multipart composition. Multipart bodies use a caller-supplied stable boundary, derive replay safety from every part, compute an exact length when possible, and close all owned part readers when encoding completes or is abandoned. Immutable layered trailers use standard net/http framing and remain replay-safe with replayable bodies.

Middleware is explicit, immutable, and local to a client or call. Register each handler with a stage, operation-or-attempt scope, layer, priority, and stable name:

observe, err := httpclient.NewCompletionMiddleware(
	httpclient.MiddlewareOptions{
		Name:  "observe",
		Scope: httpclient.ScopeOperation,
		Layer: httpclient.MiddlewareClient,
	},
	func(
		request *http.Request,
		response *http.Response,
		failure error,
	) error {
		return nil
	},
)

Pass registrations through Config.Middleware, or add invocation-local registrations with Client.DoWithMiddleware. See the middleware lifecycle guide for exact execution order, short-circuit behavior, ownership, and error semantics.

Credentials are immutable request editors applied to each trusted physical attempt. Authentication requires HTTPS and is same-origin by default, including redirects:

bearer, err := httpclient.NewBearerAuth(token)
if err != nil {
	return err
}

authentication, err := httpclient.NewAuthenticationMiddleware(
	httpclient.AuthenticationOptions{
		Name:  "vendor-auth",
		Layer: httpclient.MiddlewareClient,
	},
	bearer,
)
if err != nil {
	return err
}

client, err := httpclient.New(httpclient.Config{
	Middleware: authentication,
})

See the authentication cookbook for Basic, bearer, API-key, HMAC, OAuth2 token-source, client-credentials, redirect-boundary, and generated-client examples.

Optional egress enforcement applies exact scheme, host, port, origin, CIDR, and address-class policy to attempts, redirects, proxies, DNS answers, and connection targets. DNS answers are all validated before any numeric-address dial, preventing validation-to-connection rebinding. Immutable TLS policy can set roots, server name, client identity, and rotating SPKI pins without disabling normal certificate verification. See the egress security guide.

Opaque policy-scope keys separate transport, cookie, token, cache, coalescing, limiter, breaker, and metric state by explicit resource defaults. Cache and coalescing keys enforce origin, credential, tenant, and account separation. See the policy scope guide.

Named interactive/v1, batch/v1, streaming/v1, and webhook-delivery/v1 policy profiles expose finite defaults with deterministic profile, client, and request precedence. Resolved values and provenance are available to both operation and attempt middleware. See the policy profile guide.

Optional telemetry models one logical-operation lifecycle and numbered physical-attempt lifecycles for retries, redirects, and revalidation. It offers safe slog/go-log hooks, standard OpenTelemetry/go-telemetry adapter ports, strict W3C Trace Context, baggage allowlists, and an enforced low-cardinality metric projection. See the observability guide.

Strict ordered fixtures support deterministic vendor contract tests with bounded scripted failures, selected headers and trailers, and unused-script verification. An optional recorder persists only versioned sanitized data: request bodies become match-only digests, response bodies require an explicit redactor, and credentials, secret query fields, volatile headers, and raw transport errors are excluded. See the sanitized HTTP fixture guide.

Cookie state is disabled by default. Opt in with an isolated jar and a strict same-origin redirect policy:

client, err := httpclient.New(httpclient.Config{
	Session: &httpclient.SessionConfig{},
})

The secure default uses the maintained public-suffix list. Custom jars, cross-origin jar scope, persistence, and ownership are explicit; see the cookies and isolated sessions guide.

Every Client.Do receives one logical operation identity that remains stable across redirects and retry attempts. Endpoints can opt into a separate idempotency key policy:

idempotency, err := httpclient.NewIdempotencyMiddleware(
	httpclient.IdempotencyOptions{
		Name:  "create-widget-idempotency",
		Layer: httpclient.MiddlewareEndpoint,
	},
)

Generated keys use 128 bits of cryptographic entropy by default. A key does not make an unsafe operation retryable; retry policy must still classify the method, body replayability, endpoint contract, and outcome. See the operation identity and idempotency guide.

Retry is explicit endpoint policy and disabled unless registered:

retry, err := httpclient.NewRetryMiddleware(httpclient.RetryOptions{
	Name:            "list-widgets-retry",
	Layer:           httpclient.MiddlewareEndpoint,
	MaximumAttempts: 3,
})

The default policy retries replayable safe or idempotent methods for transient transport failures and selected transient statuses. Unsafe methods additionally require both endpoint opt-in and applied idempotency middleware. See the retry safety guide.

Proactive admission and server-directed throttling compose at the physical attempt boundary:

limiter, err := httpclient.NewTokenBucketLimiter(
	httpclient.TokenBucketOptions{Rate: 20, Burst: 40},
)
rateLimit, err := httpclient.NewRateLimitMiddleware(
	httpclient.RateLimitOptions{
		Name:    "vendor-rate-limit",
		Layer:   httpclient.MiddlewareClient,
		Limiter: limiter,
	},
)

Every wait is bounded and cancellation-aware. Retry-After is observed by default; vendor remaining/reset headers are opt-in and configurable. See the rate-limit and admission guide.

Circuit breaking wraps the complete logical operation, including its bounded retries, through a narrow port. The first-party adapter uses go-circuit-breaker for all state and half-open probe control:

classifier, err := httpclient.NewGoCircuitBreakerClassifier(nil)
circuit, err := breaker.New(breaker.Config{
	Name:       "widgets",
	Classifier: classifier,
})
adapter, err := httpclient.NewGoCircuitBreakerAdapter(circuit)
circuitPolicy, err := httpclient.NewCircuitBreakerMiddleware(
	httpclient.CircuitBreakerOptions{
		Name:    "widgets-circuit",
		Layer:   httpclient.MiddlewareClient,
		Breaker: adapter,
	},
)

The breaker remains caller-owned. See the circuit-breaker composition guide.

Typed pagination remains lazy and vendor-model neutral:

paginator, err := httpclient.NewCursorPaginator(
	httpclient.CursorPaginationOptions[Widget]{
		Fetch: func(
			ctx context.Context,
			cursor string,
		) (httpclient.CursorPaginationPage[Widget], error) {
			return widgetsPage(ctx, cursor)
		},
	},
)

widget, ok, err := paginator.Next(ctx)

Page, offset, cursor, Link-header, and custom continuations share the same finite budgets, cycle detection, cancellation, and exact resume state. See the pagination guide.

Bounded request pools provide controlled fan-out without creating one goroutine per request:

pool, err := httpclient.NewPool(
	httpclient.PoolOptions[WidgetID, Widget]{
		Concurrency: 4,
		Pending:     8,
		Key: func(id WidgetID) (string, error) {
			return id.String(), nil
		},
		Execute: func(
			ctx context.Context,
			id WidgetID,
		) (httpclient.PoolValue[Widget], error) {
			widget, responseBytes, err := getWidget(ctx, id)

			return httpclient.PoolValue[Widget]{
				Value:         widget,
				ResponseBytes: responseBytes,
			}, err
		},
	},
)
results, err := pool.RunSlice(ctx, widgetIDs)

Slice, generator, and channel sources share fixed or dynamically selected worker bounds, bounded pending work, fail-fast or collect-all behavior, stable input or completion ordering, and finite request, elapsed, response-byte, and memory budgets. See the request-pool guide.

Optional RFC-aware caching preserves standard HTTP access while bounding stored bodies and coalescing concurrent misses:

store, err := httpclient.NewMemoryCache(httpclient.MemoryCacheOptions{})
cache, err := httpclient.NewCacheMiddleware(httpclient.CacheOptions{
	Name:      "vendor-cache",
	Layer:     httpclient.MiddlewareClient,
	Namespace: "vendor-v1",
	Store:     store,
})

The cache supports freshness and age calculation, Vary, ETag and Last-Modified validation, safe shared-cache rules, explicit methods and statuses, request bypass and refresh modes, bounded stale behavior, hashed custom keys, same-origin invalidation, and response provenance. The in-memory backend is finite; applications can provide another CacheStore without adding a mandatory service dependency. Background revalidation requires an application-owned bounded scheduler. See the HTTP cache guide.

Bounded typed JSON and caller-selected codec decoding have an explicit consume-and-close contract:

widget, err := httpclient.DecodeJSONResponse[Widget](
	response,
	httpclient.DecodeOptions{MaximumBodyBytes: 1 << 20},
)

The generic codec helper requires explicit media types and rejects unread trailing bytes; the JSON helper understands JSON document boundaries. Both handle protocol-defined empty responses and return secret-safe typed limit, declared-length, decode, and body lifecycle errors. Independent status classification keeps accepted bodies caller-owned while boundedly draining and closing rejected responses. Callers can use DrainResponse to boundedly consume and close an otherwise unused final body for connection reuse. Safe vendor excerpts require an explicit redactor. See the response guide.

Explicit gzip policy keeps compressed input measurable and bounded:

compression, err := httpclient.NewCompressionMiddleware(
	httpclient.CompressionOptions{
		Name:                     "vendor-gzip",
		Layer:                    httpclient.MiddlewareClient,
		MaximumDecompressedBytes: 64 << 20,
		MaximumExpansionRatio:    100,
	},
)

Response decoding streams with absolute and expansion-ratio limits. Optional request gzip preserves replayability and joins its owned compressor worker on body close. See the compression guide.

Bounded streaming transfers copy into caller-owned writers with optional length, SHA-256 or SHA-512, cancellation, and throttled progress policy:

result, err := httpclient.CopyResponse(
	ctx,
	response,
	destination,
	httpclient.TransferOptions{MaximumBytes: 512 << 20},
)

Response bodies are always closed, destinations are never closed, and failures retain partial-byte results through secret-safe typed errors. Atomic file transfers validate and sync a same-directory temporary file before replacing the destination. Strict range helpers construct If-Range requests and distinguish validated continuation, restart fallback, and already-complete responses. High-level resume execution persists same-directory partial files, rolls rejected appends back to their safe offset, validates the complete file, and publishes atomically. See the transfer guide.

Callers retain direct access to the underlying standard client through Client.HTTPClient. Configuration must be completed before sharing a client between goroutines. Calls made directly through that standard client bypass the logical-operation pipeline; use Client.Do or Client.DoWithMiddleware when middleware policy must apply.

Ownership

The zero configuration creates an internally owned http.Transport. Client.Close cancels pending requests, closes response bodies that callers have not closed, and closes idle connections owned by the client.

A custom transport is borrowed by default and is not closed implicitly. Set TransportOwnership to TransportOwned only when the client should own its idle-connection lifecycle. Client.CloseIdleConnections is always explicit and therefore applies to either ownership mode.

Security

Transport errors intentionally omit their cause from rendered messages because standard-library URL errors can contain sensitive query parameters. The cause remains available through errors.Is, errors.As, and errors.Unwrap.

Do not put credentials in URLs. Query API keys require the explicitly named NewAPIKeyQuery constructor and remain visible to servers and intermediaries; prefer header credentials. Rendered authentication and transport errors omit credential values and query strings. See the maintained production hardening audit for the threat model, policy matrix, findings, evidence, and release verdict.

Documentation

Overview

Package httpclient provides policy and lifecycle primitives for typed outbound HTTP integrations while preserving the standard net/http API.

Index

Constants

View Source
const (
	// FixtureSchemaVersion is the current persisted fixture schema.
	FixtureSchemaVersion = 1
)

Variables

View Source
var (
	// ErrInvalidBody indicates an invalid request-body policy or implementation.
	ErrInvalidBody = errors.New("invalid request body")
	// ErrBodyConsumed indicates that a one-shot streaming body was already used.
	ErrBodyConsumed = errors.New("request body is already consumed")
)
View Source
var (
	// ErrInvalidCache indicates malformed cache policy, storage, or metadata.
	ErrInvalidCache = errors.New("invalid HTTP cache")
	// ErrCacheLimit indicates that cache storage exceeded a finite bound.
	ErrCacheLimit = errors.New("HTTP cache limit reached")
)
View Source
var (
	// ErrInvalidCircuitBreaker indicates malformed breaker integration policy.
	ErrInvalidCircuitBreaker = errors.New("invalid HTTP circuit breaker policy")
	// ErrCircuitRejected indicates fail-fast rejection before network execution.
	ErrCircuitRejected = errors.New("HTTP circuit breaker rejected operation")
)
View Source
var (
	// ErrClientClosed indicates that an operation used a closed Client.
	ErrClientClosed = errors.New("http client is closed")
	// ErrInvalidConfig indicates that client configuration is invalid.
	ErrInvalidConfig = errors.New("invalid http client configuration")
	// ErrNilRequest indicates that Client.Do received a nil request.
	ErrNilRequest = errors.New("http request is nil")
)
View Source
var (
	// ErrInvalidCompression indicates invalid compression configuration.
	ErrInvalidCompression = errors.New("invalid HTTP compression policy")
	// ErrUnsupportedContentEncoding indicates an unconfigured response encoding.
	ErrUnsupportedContentEncoding = errors.New("unsupported HTTP content encoding")
	// ErrCompression indicates request compression failure.
	ErrCompression = errors.New("HTTP request compression failed")
	// ErrDecompression indicates malformed compressed data or decoder failure.
	ErrDecompression = errors.New("HTTP response decompression failed")
	// ErrDecompressionLimit indicates excessive output size or expansion.
	ErrDecompressionLimit = errors.New("HTTP response decompression limit reached")
)
View Source
var (
	// ErrInvalidEgressPolicy indicates malformed egress configuration.
	ErrInvalidEgressPolicy = errors.New("invalid HTTP egress policy")
	// ErrEgressDenied indicates that an outbound destination is not permitted.
	ErrEgressDenied = errors.New("HTTP egress destination denied")
)
View Source
var (
	// ErrInvalidFixture indicates malformed fixture data or policy.
	ErrInvalidFixture = errors.New("invalid HTTP fixture")
	// ErrFixtureUnmatched indicates that the next interaction did not match.
	ErrFixtureUnmatched = errors.New("HTTP fixture interaction unmatched")
	// ErrFixtureUnused indicates strict verification found remaining work.
	ErrFixtureUnused = errors.New("HTTP fixture interactions unused")
	// ErrFixtureBodyLimit indicates a configured capture bound was exceeded.
	ErrFixtureBodyLimit = errors.New("HTTP fixture body limit exceeded")
	// ErrFixtureTimeout indicates a scripted timeout.
	ErrFixtureTimeout = errors.New("HTTP fixture timeout")
	// ErrFixtureTransport indicates a scripted generic transport failure.
	ErrFixtureTransport = errors.New("HTTP fixture transport failure")
	// ErrFixtureMalformedResponse indicates a scripted malformed response.
	ErrFixtureMalformedResponse = errors.New("HTTP fixture malformed response")
)
View Source
var (
	// ErrFixtureSchema indicates an unsupported schema without a migrator.
	ErrFixtureSchema = errors.New("unsupported HTTP fixture schema")
	// ErrFixtureExpired indicates that fixture expiry is at or before now.
	ErrFixtureExpired = errors.New("HTTP fixture expired")
)
View Source
var (
	// ErrInvalidIdempotencyPolicy indicates malformed endpoint policy.
	ErrInvalidIdempotencyPolicy = errors.New("invalid HTTP idempotency policy")
	// ErrInvalidIdempotencyKey indicates a malformed or ambiguous key.
	ErrInvalidIdempotencyKey = errors.New("invalid HTTP idempotency key")
	// ErrIdempotencyKeyRequired indicates caller-required policy without a key.
	ErrIdempotencyKeyRequired = errors.New("HTTP idempotency key is required")
)
View Source
var (
	// ErrInvalidIdentifier indicates invalid identity generation policy.
	ErrInvalidIdentifier = errors.New("invalid HTTP operation identifier")
	// ErrInvalidOperationIdentity indicates a malformed logical operation ID.
	ErrInvalidOperationIdentity = errors.New("invalid HTTP operation identity")
)
View Source
var (
	// ErrInvalidMultipart indicates malformed multipart policy or metadata.
	ErrInvalidMultipart = errors.New("invalid multipart body")
	// ErrMultipartLimit indicates that a multipart body exceeded its limit.
	ErrMultipartLimit = errors.New("multipart body limit exceeded")
	// ErrMultipartPartLength indicates that a part did not match its declared length.
	ErrMultipartPartLength = errors.New("multipart part length mismatch")
)
View Source
var (
	// ErrInvalidPagination indicates malformed pagination policy or state.
	ErrInvalidPagination = errors.New("invalid HTTP pagination policy")
	// ErrPaginationLimit indicates that a finite pagination budget was reached.
	ErrPaginationLimit = errors.New("HTTP pagination limit reached")
	// ErrPaginationCycle indicates a repeated continuation identity.
	ErrPaginationCycle = errors.New("HTTP pagination continuation cycle")
	// ErrPaginationFetch indicates that a page fetcher failed.
	ErrPaginationFetch = errors.New("HTTP pagination fetch failed")
)
View Source
var (
	// ErrInvalidMiddleware indicates invalid middleware metadata or behavior.
	ErrInvalidMiddleware = errors.New("invalid HTTP middleware")
	// ErrInvalidMiddlewareResult indicates an impossible response/error pair.
	ErrInvalidMiddlewareResult = errors.New("invalid HTTP middleware result")
)
View Source
var (
	// ErrInvalidPool indicates malformed pool policy, source, or metadata.
	ErrInvalidPool = errors.New("invalid HTTP request pool")
	// ErrPoolLimit indicates that a finite pool-wide budget was reached.
	ErrPoolLimit = errors.New("HTTP request pool limit reached")
)
View Source
var (
	// ErrInvalidRange indicates invalid request or response range policy.
	ErrInvalidRange = errors.New("invalid HTTP range policy")
	// ErrRangeMismatch indicates a response does not describe the requested range.
	ErrRangeMismatch = errors.New("HTTP range response mismatch")
	// ErrRangeValidatorMismatch indicates representation identity changed.
	ErrRangeValidatorMismatch = errors.New("HTTP range validator mismatch")
	// ErrRangeRestartRequired indicates the server returned a full representation.
	ErrRangeRestartRequired = errors.New("HTTP range restart required")
)
View Source
var (
	// ErrInvalidRateLimitPolicy indicates malformed limiter configuration.
	ErrInvalidRateLimitPolicy = errors.New("invalid HTTP rate limit policy")
	// ErrRateLimitWaitExceeded indicates that admission exceeds its wait bound.
	ErrRateLimitWaitExceeded = errors.New("HTTP rate limit wait exceeds bound")
	// ErrRateLimitCapacity indicates that a bounded limiter queue is full.
	ErrRateLimitCapacity = errors.New("HTTP rate limit capacity exhausted")
)
View Source
var (
	// ErrInvalidRequestSpec indicates invalid request construction policy.
	ErrInvalidRequestSpec = errors.New("invalid request specification")
	// ErrInvalidURL indicates an unsafe or malformed base URL or reference.
	ErrInvalidURL = errors.New("invalid request URL")
	// ErrInvalidHeader indicates an invalid HTTP field name or value.
	ErrInvalidHeader = errors.New("invalid HTTP header")
	// ErrInvalidTrailer indicates an invalid HTTP trailer name, value, or use.
	ErrInvalidTrailer = errors.New("invalid HTTP trailer")
	// ErrInvalidQuery indicates an invalid query name, value, or encoding.
	ErrInvalidQuery = errors.New("invalid HTTP query")
)
View Source
var (
	// ErrInvalidResponsePolicy indicates invalid decoding configuration or state.
	ErrInvalidResponsePolicy = errors.New("invalid HTTP response policy")
	// ErrResponseBodyLimit indicates that a response exceeded its finite bound.
	ErrResponseBodyLimit = errors.New("HTTP response body limit reached")
	// ErrUnexpectedContentType indicates an incompatible response media type.
	ErrUnexpectedContentType = errors.New("unexpected HTTP response content type")
	// ErrTrailingResponseData indicates more than one encoded document.
	ErrTrailingResponseData = errors.New("trailing HTTP response data")
	// ErrEmptyResponseBody indicates a required representation was absent.
	ErrEmptyResponseBody = errors.New("empty HTTP response body")
	// ErrResponseLength indicates a declared response length mismatch.
	ErrResponseLength = errors.New("HTTP response content length mismatch")
	// ErrResponseDecoderPanic indicates that a caller decoder panicked.
	ErrResponseDecoderPanic = errors.New("HTTP response decoder panicked")
)
View Source
var (
	// ErrInvalidRetryPolicy indicates invalid retry configuration or behavior.
	ErrInvalidRetryPolicy = errors.New("invalid HTTP retry policy")
	// ErrRetryExhausted indicates that retry policy cannot make another attempt.
	ErrRetryExhausted = errors.New("HTTP retry attempts exhausted")
)
View Source
var (
	// ErrInvalidSession indicates invalid cookie or persistence policy.
	ErrInvalidSession = errors.New("invalid HTTP session")
	// ErrSessionDisabled indicates that a client has no session configuration.
	ErrSessionDisabled = errors.New("HTTP session is disabled")
	// ErrSessionPersistenceUnavailable indicates that no persistence port exists.
	ErrSessionPersistenceUnavailable = errors.New("HTTP session persistence is unavailable")
)
View Source
var (
	// ErrInvalidStatusPolicy indicates invalid response classification policy.
	ErrInvalidStatusPolicy = errors.New("invalid HTTP status policy")
	// ErrHTTPStatus indicates a response status rejected by caller policy.
	ErrHTTPStatus = errors.New("HTTP response status rejected")
)
View Source
var (
	// ErrInvalidTLSPolicy indicates malformed TLS roots, identity, or pins.
	ErrInvalidTLSPolicy = errors.New("invalid HTTP TLS policy")
	// ErrTLSPinMismatch indicates that no configured SPKI pin matched the peer.
	ErrTLSPinMismatch = errors.New("HTTP TLS public key pin mismatch")
)
View Source
var (
	// ErrInvalidTransfer indicates invalid streaming transfer policy or state.
	ErrInvalidTransfer = errors.New("invalid HTTP transfer policy")
	// ErrTransferLimit indicates that a finite transfer bound was exceeded.
	ErrTransferLimit = errors.New("HTTP transfer limit reached")
	// ErrTransferLength indicates transferred length mismatch.
	ErrTransferLength = errors.New("HTTP transfer length mismatch")
	// ErrDigestMismatch indicates transferred content failed validation.
	ErrDigestMismatch = errors.New("HTTP transfer digest mismatch")
	// ErrTransferProgressPanic indicates that a progress observer panicked.
	ErrTransferProgressPanic = errors.New("HTTP transfer progress observer panicked")
)
View Source
var (
	// ErrInvalidAuthentication indicates invalid credential policy or input.
	ErrInvalidAuthentication = errors.New("invalid HTTP authentication")
)
View Source
var (
	// ErrInvalidOAuth2Token indicates a missing, expired, or unsafe token.
	ErrInvalidOAuth2Token = errors.New("invalid OAuth2 token")
)
View Source
var (
	// ErrInvalidPolicyProfile indicates an unknown profile or invalid override.
	ErrInvalidPolicyProfile = errors.New("invalid HTTP policy profile")
)
View Source
var (
	// ErrInvalidPolicyScope indicates malformed scope state or resolution.
	ErrInvalidPolicyScope = errors.New("invalid HTTP policy scope")
)
View Source
var ErrInvalidTelemetry = errors.New("invalid HTTP telemetry policy")

ErrInvalidTelemetry indicates malformed telemetry adapters or header policy.

View Source
var ErrInvalidTraceContext = errors.New("invalid W3C trace context")

ErrInvalidTraceContext indicates malformed W3C propagation fields.

View Source
var (
	// ErrResponseDrainLimit indicates that bounded draining did not reach EOF.
	ErrResponseDrainLimit = errors.New("HTTP response drain limit reached")
)

Functions

func ClassifyResponse

func ClassifyResponse(response *http.Response, options StatusOptions) (resultErr error)

ClassifyResponse returns nil for an accepted response without touching its body. A rejected response is boundedly consumed and always closed.

func DecodeJSONResponse

func DecodeJSONResponse[T any](
	response *http.Response,
	options DecodeOptions,
) (value T, resultErr error)

DecodeJSONResponse decodes one bounded JSON document and always closes the response body. Status classification remains a separate caller policy.

func DecodeResponse

func DecodeResponse[T any](
	response *http.Response,
	options DecodeOptions,
	decode DecodeFunc[T],
) (value T, resultErr error)

DecodeResponse decodes one bounded representation with a caller-selected codec and always closes the response body. ExpectedMediaTypes is required; status classification remains a separate caller policy.

func DrainResponse

func DrainResponse(response *http.Response, options DrainOptions) (resultErr error)

DrainResponse boundedly consumes and always closes response.Body. Reaching EOF permits connection reuse; exceeding the bound returns a typed error.

func NewGoCircuitBreakerClassifier

func NewGoCircuitBreakerClassifier(
	classifier CircuitOutcomeClassifier,
) (breaker.Classifier, error)

NewGoCircuitBreakerClassifier maps the HTTP classifier into the first-party breaker's outcome contract. Nil selects DefaultCircuitOutcomeClassifier.

func ParseNextLink(value string) (string, bool, error)

ParseNextLink returns the single link target whose rel parameter contains next. It accepts commas inside URI references and quoted parameter values.

func ValidateRangeResponse

func ValidateRangeResponse(
	response *http.Response,
	options RangeResponseOptions,
) (RangeMetadata, RangeDisposition, error)

ValidateRangeResponse validates protocol metadata without consuming or closing response body. The caller retains response ownership on every exit.

func WithCacheMode

func WithCacheMode(ctx context.Context, mode CacheMode) (context.Context, error)

WithCacheMode returns a context carrying one explicit request cache mode.

func WithIdempotencyKey

func WithIdempotencyKey(ctx context.Context, key string) (context.Context, error)

WithIdempotencyKey returns a context carrying a caller-supplied key. The endpoint policy still applies its configured maximum length.

func WithOperationIdentity

func WithOperationIdentity(ctx context.Context, identifier string) (context.Context, error)

WithOperationIdentity returns a context carrying validated caller identity.

func WithPolicyOverrides

func WithPolicyOverrides(ctx context.Context, overrides PolicyOverrides) (context.Context, error)

WithPolicyOverrides attaches an immutable per-request override snapshot.

func WithPolicyScope

func WithPolicyScope(ctx context.Context, scope PolicyScope) (context.Context, error)

WithPolicyScope attaches an immutable scope snapshot to ctx.

func WithRange

func WithRange(request *http.Request, options RangeOptions) (*http.Request, error)

WithRange returns an independent GET or HEAD request with Range and optional If-Range headers. It never consumes or aliases a request body.

func WithW3CTraceContext

func WithW3CTraceContext(
	ctx context.Context,
	traceparent string,
	tracestate string,
) (context.Context, error)

WithW3CTraceContext attaches a validated immutable W3C Trace Context v00 snapshot. Baggage is configured independently through TelemetryOptions.

Types

type AroundMiddlewareFunc

type AroundMiddlewareFunc func(request *http.Request, next Next) (*http.Response, error)

AroundMiddlewareFunc handles request or transport stages.

type AuthenticationOptions

type AuthenticationOptions struct {
	Name             string
	Layer            MiddlewareLayer
	Priority         int
	AllowedOrigins   []string
	SensitiveHeaders []string
	// AllowInsecure permits credentials on trusted plain-HTTP origins. It is
	// intended only for local tests.
	AllowInsecure bool
}

AuthenticationOptions configures origin-bound attempt authentication. With no AllowedOrigins, credentials are restricted to the logical operation's initial origin. Additional sensitive headers are stripped whenever a redirect leaves the trusted origin set.

type BodyOpenError

type BodyOpenError struct {
	Cause error
}

BodyOpenError reports that a request body could not be opened. Its rendered message does not include the underlying error, which may contain payload details.

func (*BodyOpenError) Error

func (*BodyOpenError) Error() string

Error implements error.

func (*BodyOpenError) Unwrap

func (err *BodyOpenError) Unwrap() error

Unwrap returns the body factory failure.

type BodyOpener

type BodyOpener func() (io.ReadCloser, error)

BodyOpener creates a fresh body reader for one physical request attempt.

type CacheEntry

type CacheEntry struct {
	StatusCode       int
	Status           string
	Proto            string
	ProtoMajor       int
	ProtoMinor       int
	Header           http.Header
	Trailer          http.Header
	TransferEncoding []string
	Uncompressed     bool
	Body             []byte
	StoredAt         time.Time
	RequestTime      time.Time
	ResponseTime     time.Time
	Vary             []string
	VariantID        string
}

CacheEntry is one complete stored response variant. Store implementations must treat slices, headers, and times as caller-owned values.

type CacheError

type CacheError struct {
	Operation string
	Cause     error
}

CacheError reports cache storage or body processing failure without rendering backend, key, request, header, or body details.

func (*CacheError) Error

func (err *CacheError) Error() string

Error implements error without rendering the cause.

func (*CacheError) Unwrap

func (err *CacheError) Unwrap() error

Unwrap returns the cache failure cause.

type CacheFailureMode

type CacheFailureMode uint8

CacheFailureMode controls whether backend failures bypass cache or fail the logical operation.

const (
	// CacheFailOpen preserves origin availability when cache storage fails.
	CacheFailOpen CacheFailureMode = iota
	// CacheFailClosed surfaces cache storage failures as typed operation errors.
	CacheFailClosed
)

type CacheKeyFunc

type CacheKeyFunc func(*http.Request) (string, error)

CacheKeyFunc returns bounded caller-defined key material. The middleware hashes it before storage and the callback must not consume request bodies.

type CacheMetadata

type CacheMetadata struct {
	Provenance CacheProvenance
	Age        time.Duration
}

CacheMetadata describes cache handling without changing standard response access. It never contains a URL, cache key, credential, or response body.

func CacheMetadataFromResponse

func CacheMetadataFromResponse(response *http.Response) (CacheMetadata, bool)

CacheMetadataFromResponse returns immutable cache metadata when a configured cache handled response.

type CacheMode

type CacheMode uint8

CacheMode controls one request's cache lookup and storage behavior.

const (
	// CacheModeDefault applies normal RFC cache behavior.
	CacheModeDefault CacheMode = iota
	// CacheModeBypass skips cache lookup and storage.
	CacheModeBypass
	// CacheModeRefresh skips lookup and replaces a storable response.
	CacheModeRefresh
)

type CacheOptions

type CacheOptions struct {
	Name                  string
	Layer                 MiddlewareLayer
	Priority              int
	Namespace             string
	Shared                bool
	MaximumBodyBytes      int64
	TTLOverride           time.Duration
	Store                 CacheStore
	Clock                 RetryClock
	VariantKey            []byte
	Methods               []string
	Statuses              []int
	FailureMode           CacheFailureMode
	Key                   CacheKeyFunc
	RevalidationScheduler CacheRevalidationScheduler
}

CacheOptions configures RFC-aware operation cache middleware.

type CacheProvenance

type CacheProvenance uint8

CacheProvenance describes how a response was obtained.

const (
	// CacheMiss indicates that the response came from the next HTTP policy.
	CacheMiss CacheProvenance = iota
	// CacheHit indicates that a fresh stored response satisfied the request.
	CacheHit
	// CacheRevalidated indicates that a 304 freshened a stored response.
	CacheRevalidated
	// CacheStale indicates explicitly permitted stale response reuse.
	CacheStale
)

type CacheRevalidationScheduler

type CacheRevalidationScheduler interface {
	ScheduleCacheRevalidation(func(context.Context)) error
}

CacheRevalidationScheduler owns asynchronous cache revalidation work and supplies its lifecycle context. Implementations must queue tasks rather than execute them inline.

type CacheStore

type CacheStore interface {
	Load(context.Context, string) ([]CacheEntry, error)
	Save(context.Context, string, CacheEntry) error
	Delete(context.Context, string) error
}

CacheStore persists complete response variants under opaque primary keys. Implementations must be safe for concurrent use and honor context.

type CircuitBreaker

type CircuitBreaker interface {
	Execute(
		context.Context,
		func(context.Context) (*http.Response, error),
	) (*http.Response, error)
}

CircuitBreaker executes one complete logical HTTP operation. Implementations own admission, half-open probes, state, and outcome accounting.

func NewGoCircuitBreakerAdapter

func NewGoCircuitBreakerAdapter(value *breaker.Breaker) (CircuitBreaker, error)

NewGoCircuitBreakerAdapter adapts the first-party go-circuit-breaker. The breaker remains caller-owned and must be shut down by its owner.

type CircuitBreakerError

type CircuitBreakerError struct {
	Cause error
}

CircuitBreakerError reports fail-fast rejection without rendering breaker names, state details, retry timestamps, or underlying causes.

func (*CircuitBreakerError) Error

func (*CircuitBreakerError) Error() string

Error implements error without rendering potentially sensitive causes.

func (*CircuitBreakerError) Unwrap

func (err *CircuitBreakerError) Unwrap() []error

Unwrap preserves the stable rejection sentinel and provider cause.

type CircuitBreakerFunc

type CircuitBreakerFunc func(
	context.Context,
	func(context.Context) (*http.Response, error),
) (*http.Response, error)

CircuitBreakerFunc adapts a function to CircuitBreaker.

func (CircuitBreakerFunc) Execute

func (function CircuitBreakerFunc) Execute(
	ctx context.Context,
	operation func(context.Context) (*http.Response, error),
) (*http.Response, error)

Execute implements CircuitBreaker.

type CircuitBreakerOptions

type CircuitBreakerOptions struct {
	Name     string
	Layer    MiddlewareLayer
	Priority int
	Breaker  CircuitBreaker
}

CircuitBreakerOptions configures logical-operation breaker middleware.

type CircuitOutcome

type CircuitOutcome uint8

CircuitOutcome is the HTTP classification recorded by breaker state.

const (
	// CircuitOutcomeSuccess records a dependency success.
	CircuitOutcomeSuccess CircuitOutcome = iota
	// CircuitOutcomeFailure records a dependency failure.
	CircuitOutcomeFailure
	// CircuitOutcomeIgnored excludes a local or caller-controlled outcome.
	CircuitOutcomeIgnored
)

type CircuitOutcomeClassifier

type CircuitOutcomeClassifier interface {
	Classify(*http.Response, error) CircuitOutcome
}

CircuitOutcomeClassifier classifies one complete logical HTTP operation. It must not retain, mutate, consume, or close the response.

func DefaultCircuitOutcomeClassifier

func DefaultCircuitOutcomeClassifier() CircuitOutcomeClassifier

DefaultCircuitOutcomeClassifier classifies 5xx responses, deadlines, and other operation failures while ignoring caller cancellation and local rate rejection.

type CircuitOutcomeClassifierFunc

type CircuitOutcomeClassifierFunc func(*http.Response, error) CircuitOutcome

CircuitOutcomeClassifierFunc adapts a function to a classifier.

func (CircuitOutcomeClassifierFunc) Classify

func (function CircuitOutcomeClassifierFunc) Classify(
	response *http.Response,
	failure error,
) CircuitOutcome

Classify implements CircuitOutcomeClassifier.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client executes standard HTTP requests and owns their operation lifecycle. Callers own response bodies until they close the body or close the Client.

func New

func New(config Config) (*Client, error)

New constructs a Client without mutating any caller-provided transport.

func (*Client) Close

func (client *Client) Close() error

Close cancels pending operations, closes active response bodies, and closes idle connections on transports owned by the Client. It is idempotent.

func (*Client) CloseIdleConnections

func (client *Client) CloseIdleConnections()

CloseIdleConnections closes idle connections without changing client ownership or canceling active operations. This explicit call also applies to a borrowed transport.

func (*Client) Do

func (client *Client) Do(request *http.Request) (*http.Response, error)

Do executes request through the configured standard client. The returned response body must be closed by the caller. Closing Client also closes every response body still owned by the caller.

func (*Client) DoWithMiddleware

func (client *Client) DoWithMiddleware(
	request *http.Request,
	middleware ...Middleware,
) (*http.Response, error)

DoWithMiddleware executes request through an immutable pipeline derived from the client pipeline. The supplied registrations affect only this operation.

func (*Client) HTTPClient

func (client *Client) HTTPClient() *http.Client

HTTPClient returns the standard client used for requests. Configuration should be completed before the Client is shared between goroutines.

func (*Client) InspectPipeline

func (client *Client) InspectPipeline() PipelineInspection

InspectPipeline returns independent copies of the configured resolved plans.

func (*Client) InspectPolicy

func (client *Client) InspectPolicy(request *http.Request) (ResolvedPolicy, error)

InspectPolicy resolves the immutable operation policy without executing the request.

func (*Client) LoadSession

func (client *Client) LoadSession(ctx context.Context) error

LoadSession restores cookies through the configured persistence port.

func (*Client) SaveSession

func (client *Client) SaveSession(ctx context.Context) error

SaveSession persists cookies through the configured persistence port.

type ClientCredentialsError

type ClientCredentialsError struct {
	Cause error
}

ClientCredentialsError reports token endpoint failure without rendering the endpoint, client identity, secret, response, or underlying cause.

func (*ClientCredentialsError) Error

func (*ClientCredentialsError) Error() string

Error implements error without rendering sensitive token endpoint data.

func (*ClientCredentialsError) Unwrap

func (err *ClientCredentialsError) Unwrap() error

Unwrap returns the token request failure.

type ClientCredentialsOptions

type ClientCredentialsOptions struct {
	Client           *Client
	TokenURL         string
	ClientID         string
	ClientSecret     string
	Scopes           []string
	EndpointParams   url.Values
	AuthStyle        oauth2.AuthStyle
	AllowInsecureURL bool
	EarlyExpiry      time.Duration
	Now              func() time.Time
}

ClientCredentialsOptions configures an outbound OAuth2 client-credentials source. Client supplies the hardened transport and finite total timeout.

type ClientCredentialsTokenSource

type ClientCredentialsTokenSource struct {
	// contains filtered or unexported fields
}

ClientCredentialsTokenSource coordinates cached client-credentials tokens.

func NewClientCredentialsTokenSource

func NewClientCredentialsTokenSource(options ClientCredentialsOptions) (*ClientCredentialsTokenSource, error)

NewClientCredentialsTokenSource returns a context-aware, concurrency-safe OAuth2 client-credentials source. One caller performs a refresh while other callers wait cancelably. Token endpoint calls use Client.HTTPClient directly so integration middleware cannot recursively authenticate or retry them.

func (*ClientCredentialsTokenSource) Token

Token returns an independent token copy or refreshes it using ctx.

type CompletionMiddlewareFunc

type CompletionMiddlewareFunc func(request *http.Request, response *http.Response, failure error) error

CompletionMiddlewareFunc observes the final response and error for a scope.

type CompressionError

type CompressionError struct {
	Operation string
	Encoding  string
	Cause     error
}

CompressionError reports content-decoding failure without rendering the underlying decoder or body error.

func (*CompressionError) Error

func (err *CompressionError) Error() string

Error implements error.

func (*CompressionError) Unwrap

func (err *CompressionError) Unwrap() []error

Unwrap preserves both the stable category and underlying failure.

type CompressionOptions

type CompressionOptions struct {
	Name                     string
	Layer                    MiddlewareLayer
	Priority                 int
	CompressRequests         bool
	MinimumRequestBytes      int64
	MaximumDecompressedBytes int64
	MaximumExpansionRatio    float64
}

CompressionOptions configures explicit attempt-scoped response decoding.

type Config

type Config struct {
	// Profile selects a named versioned policy. Zero selects interactive/v1.
	Profile PolicyProfileID
	// Policy overrides profile values for every operation on this client.
	Policy PolicyOverrides
	// Timeout bounds the complete HTTP exchange. Zero selects 30 seconds.
	// When set, it is the legacy client-level operation-timeout override and
	// takes precedence over Policy.OperationTimeout.
	Timeout time.Duration
	// Transport replaces the default transport. It is borrowed unless
	// TransportOwnership is TransportOwned.
	Transport http.RoundTripper
	// TransportOwnership controls cleanup of a configured Transport.
	TransportOwnership TransportOwnership
	// Middleware contains client, endpoint, request, or one-shot registrations.
	// New resolves them into one immutable pipeline.
	Middleware []Middleware
	// Session opts into an isolated cookie jar and redirect policy. Nil disables
	// ambient cookie state.
	Session *SessionConfig
	// OperationIdentityGenerator replaces the default cryptographically random
	// 128-bit logical operation identifier generator.
	OperationIdentityGenerator IdentifierGenerator
	// Egress enables destination and dial-time address enforcement. It requires
	// the internally owned standard transport.
	Egress *EgressPolicy
	// TLS configures roots, server identity, client identity, and optional SPKI
	// pins. It requires the internally owned standard transport.
	TLS *TLSPolicy
	// Telemetry enables operation and physical-attempt observation and header
	// propagation without installing a mandatory exporter or logger.
	Telemetry *TelemetryOptions
}

Config configures a Client. A zero Config selects finite production-safe defaults and an internally owned standard transport.

type ContextCircuitOutcomeClassifier

type ContextCircuitOutcomeClassifier interface {
	ClassifyContext(context.Context, *http.Response, error) CircuitOutcome
}

ContextCircuitOutcomeClassifier can distinguish caller cancellation from a dependency that independently returns a cancellation-shaped error.

type ContextTokenSource

type ContextTokenSource interface {
	Token(context.Context) (*oauth2.Token, error)
}

ContextTokenSource obtains an OAuth2 token using the request context. Implementations must coordinate concurrent refreshes and honor cancellation.

type ContextTokenSourceFunc

type ContextTokenSourceFunc func(context.Context) (*oauth2.Token, error)

ContextTokenSourceFunc adapts a function to ContextTokenSource.

func (ContextTokenSourceFunc) Token

func (function ContextTokenSourceFunc) Token(ctx context.Context) (*oauth2.Token, error)

Token implements ContextTokenSource.

type CookieJarOwnership

type CookieJarOwnership uint8

CookieJarOwnership controls whether Client.Close closes a custom jar that also implements io.Closer. Internally created jars are always owned.

const (
	// CookieJarBorrowed leaves a custom jar under caller ownership.
	CookieJarBorrowed CookieJarOwnership = iota
	// CookieJarOwned transfers a closable custom jar to Client.
	CookieJarOwned
)

type CookieRedirectPolicy

type CookieRedirectPolicy uint8

CookieRedirectPolicy controls whether jar-selected cookies may cross the initial logical operation origin during redirects.

const (
	// CookieRedirectSameOrigin strips cookies when a redirect changes origin.
	CookieRedirectSameOrigin CookieRedirectPolicy = iota
	// CookieRedirectJar trusts the jar's domain, path, security, and suffix rules.
	CookieRedirectJar
)

type CursorPaginationFetcher

type CursorPaginationFetcher[Item any] func(
	context.Context,
	string,
) (CursorPaginationPage[Item], error)

CursorPaginationFetcher loads one opaque cursor without normalization.

type CursorPaginationOptions

type CursorPaginationOptions[Item any] struct {
	InitialCursor string
	Fetch         CursorPaginationFetcher[Item]
	Limits        PaginationLimits
	Clock         RetryClock
	Resume        *PaginationState[Item, string]
}

CursorPaginationOptions configures opaque-cursor iteration.

type CursorPaginationPage

type CursorPaginationPage[Item any] struct {
	Items         []Item
	NextCursor    string
	HasNext       bool
	ResponseBytes int64
}

CursorPaginationPage is one opaque-cursor fetch result.

type DecodeFunc

type DecodeFunc[T any] func(io.Reader) (T, error)

DecodeFunc decodes one complete typed representation from a bounded response stream. It must consume the complete representation so trailing-data policy can inspect any unread bytes.

type DecodeOptions

type DecodeOptions struct {
	MaximumBodyBytes   int64
	ExpectedMediaTypes []string
	AllowEmpty         bool
	AllowTrailingData  bool
}

DecodeOptions configures bounded response decoding. JSON decoding rejects trailing documents unless AllowTrailingData is explicit.

type DecompressionLimitError

type DecompressionLimitError struct {
	MaximumBytes      int64
	MaximumRatio      float64
	CompressedBytes   int64
	DecompressedBytes int64
}

DecompressionLimitError reports finite compressed and decoded byte counts.

func (*DecompressionLimitError) Error

Error implements error.

func (*DecompressionLimitError) Unwrap

func (*DecompressionLimitError) Unwrap() error

Unwrap returns the stable decompression limit sentinel.

type DigestAlgorithm

type DigestAlgorithm string

DigestAlgorithm identifies an explicitly supported transfer digest.

const (
	// DigestSHA256 computes SHA-256.
	DigestSHA256 DigestAlgorithm = "sha-256"
	// DigestSHA512 computes SHA-512.
	DigestSHA512 DigestAlgorithm = "sha-512"
)

type DigestMismatchError

type DigestMismatchError struct{ Algorithm DigestAlgorithm }

DigestMismatchError reports the algorithm without rendering digest values.

func (*DigestMismatchError) Error

func (*DigestMismatchError) Error() string

Error implements error.

func (*DigestMismatchError) Unwrap

func (*DigestMismatchError) Unwrap() error

Unwrap returns the stable digest sentinel.

type DrainOptions

type DrainOptions struct {
	MaximumBytes int64
}

DrainOptions configures bounded response draining for connection reuse.

type EgressError

type EgressError struct {
	Reason EgressReason
}

EgressError reports a destination denial without rendering host, path, query, credentials, or resolved addresses.

func (*EgressError) Error

func (*EgressError) Error() string

Error implements error.

func (*EgressError) Unwrap

func (*EgressError) Unwrap() error

Unwrap returns the stable egress-denial sentinel.

type EgressOptions

type EgressOptions struct {
	AllowedSchemes       []string
	AllowedHosts         []string
	AllowedPorts         []uint16
	AllowedOrigins       []string
	AllowedCIDRs         []string
	DeniedCIDRs          []string
	AllowPrivate         bool
	AllowLoopback        bool
	AllowLinkLocal       bool
	AllowMulticast       bool
	AllowMetadataService bool
	Resolver             EgressResolver
}

EgressOptions configures immutable outbound destination policy. Empty scheme and port lists default to HTTPS and port 443. Empty host, origin, and CIDR lists allow any value that passes the remaining checks.

type EgressPolicy

type EgressPolicy struct {
	// contains filtered or unexported fields
}

EgressPolicy is an immutable URL and resolved-address policy.

func NewEgressPolicy

func NewEgressPolicy(options EgressOptions) (*EgressPolicy, error)

NewEgressPolicy validates and snapshots outbound destination policy.

func (*EgressPolicy) ValidateIP

func (policy *EgressPolicy) ValidateIP(address net.IP) error

ValidateIP validates one address resolved for an outbound connection.

func (*EgressPolicy) ValidateURL

func (policy *EgressPolicy) ValidateURL(target *url.URL) error

ValidateURL validates scheme, authority, origin, and literal IP addresses. DNS hostnames receive their address validation at connection time.

type EgressReason

type EgressReason string

EgressReason is a stable low-cardinality denial category.

const (
	EgressReasonScheme    EgressReason = "scheme"
	EgressReasonHost      EgressReason = "host"
	EgressReasonPort      EgressReason = "port"
	EgressReasonOrigin    EgressReason = "origin"
	EgressReasonCIDR      EgressReason = "cidr"
	EgressReasonAddress   EgressReason = "address-class"
	EgressReasonMetadata  EgressReason = "metadata-service"
	EgressReasonMalformed EgressReason = "malformed"
)

type EgressResolver

type EgressResolver interface {
	LookupNetIP(context.Context, string, string) ([]netip.Addr, error)
}

EgressResolver resolves every candidate address before a connection is attempted. Implementations must be safe for concurrent use.

type EgressResolverFunc

type EgressResolverFunc func(context.Context, string, string) ([]netip.Addr, error)

EgressResolverFunc adapts a function to EgressResolver.

func (EgressResolverFunc) LookupNetIP

func (function EgressResolverFunc) LookupNetIP(
	ctx context.Context,
	network string,
	host string,
) ([]netip.Addr, error)

LookupNetIP implements EgressResolver.

type ErrorMiddlewareFunc

type ErrorMiddlewareFunc func(request *http.Request, failure error) (*http.Response, error)

ErrorMiddlewareFunc observes an error and may return a recovered response.

type ExcerptRedactor

type ExcerptRedactor func([]byte) ([]byte, error)

ExcerptRedactor returns an independent safe excerpt. It must not retain its input, which can contain sensitive response data.

type FileTransferError

type FileTransferError struct {
	Operation string
	Cause     error
}

FileTransferError reports filesystem failure without rendering paths or underlying errors.

func (*FileTransferError) Error

func (err *FileTransferError) Error() string

Error implements error.

func (*FileTransferError) Unwrap

func (err *FileTransferError) Unwrap() error

Unwrap returns the filesystem failure.

type FileTransferOptions

type FileTransferOptions struct {
	Mode     os.FileMode
	Transfer TransferOptions
}

FileTransferOptions configures atomic response-to-file replacement.

type FixedWindowOptions

type FixedWindowOptions struct {
	Limit  int
	Window time.Duration
	Clock  RetryClock
}

FixedWindowOptions configures a fixed-window request limiter.

type Fixture

type Fixture struct {
	SchemaVersion int                  `json:"schema_version"`
	RecordedAt    time.Time            `json:"recorded_at"`
	ExpiresAt     time.Time            `json:"expires_at,omitempty"`
	Match         FixtureMatchPolicy   `json:"match"`
	Interactions  []FixtureInteraction `json:"interactions"`
}

Fixture is one versioned deterministic HTTP interaction sequence.

func ReadFixture

func ReadFixture(reader io.Reader, options FixtureLoadOptions) (Fixture, error)

ReadFixture loads one bounded strict JSON document and applies only an explicitly registered schema migration.

type FixtureBodyFailure

type FixtureBodyFailure string

FixtureBodyFailure is a stable persisted response-read failure category.

const (
	// FixtureBodyFailureUnexpectedEOF returns partial bytes then io.ErrUnexpectedEOF.
	FixtureBodyFailureUnexpectedEOF FixtureBodyFailure = "unexpected_eof"
)

type FixtureBodyRedactor

type FixtureBodyRedactor interface {
	RedactFixtureBody([]byte) ([]byte, error)
}

FixtureBodyRedactor sanitizes one bounded response body before storage.

type FixtureBodyRedactorFunc

type FixtureBodyRedactorFunc func([]byte) ([]byte, error)

FixtureBodyRedactorFunc adapts a body-redaction function.

func (FixtureBodyRedactorFunc) RedactFixtureBody

func (function FixtureBodyRedactorFunc) RedactFixtureBody(content []byte) ([]byte, error)

RedactFixtureBody implements FixtureBodyRedactor.

type FixtureError

type FixtureError struct {
	Interaction int
	Cause       error
}

FixtureError identifies only the interaction index and stable cause.

func (*FixtureError) Error

func (*FixtureError) Error() string

Error implements error without rendering request or fixture data.

func (*FixtureError) Unwrap

func (err *FixtureError) Unwrap() error

Unwrap returns the stable fixture cause.

type FixtureFailure

type FixtureFailure string

FixtureFailure is a stable persisted pre-response failure category.

const (
	// FixtureFailureTimeout replays a net.Error timeout.
	FixtureFailureTimeout FixtureFailure = "timeout"
	// FixtureFailureCanceled replays context cancellation.
	FixtureFailureCanceled FixtureFailure = "canceled"
	// FixtureFailureTransport replays a generic transport failure.
	FixtureFailureTransport FixtureFailure = "transport"
	// FixtureFailureMalformedResponse replays malformed wire behavior.
	FixtureFailureMalformedResponse FixtureFailure = "malformed_response"
)

type FixtureInteraction

type FixtureInteraction struct {
	Request  FixtureRequest  `json:"request"`
	Response FixtureResponse `json:"response"`
}

FixtureInteraction pairs one canonical request with one replay response.

type FixtureLoadOptions

type FixtureLoadOptions struct {
	MaximumFileBytes int64
	Clock            RetryClock
	AllowExpired     bool
	Migrations       map[int]FixtureMigrator
}

FixtureLoadOptions controls bounded compatibility and expiry checks.

type FixtureMatchPolicy

type FixtureMatchPolicy struct {
	Headers                 []string `json:"headers,omitempty"`
	RedactedQueryParameters []string `json:"redacted_query_parameters,omitempty"`
}

FixtureMatchPolicy persists deterministic sanitized matching behavior.

type FixtureMigrator

type FixtureMigrator interface {
	MigrateFixture(json.RawMessage) (Fixture, error)
}

FixtureMigrator upgrades one explicitly supported raw schema to current.

type FixtureMigratorFunc

type FixtureMigratorFunc func(json.RawMessage) (Fixture, error)

FixtureMigratorFunc adapts a schema migration function.

func (FixtureMigratorFunc) MigrateFixture

func (function FixtureMigratorFunc) MigrateFixture(payload json.RawMessage) (Fixture, error)

MigrateFixture implements FixtureMigrator.

type FixtureReplayError

type FixtureReplayError struct{ Kind FixtureFailure }

FixtureReplayError is a stable secret-safe scripted transport failure.

func (*FixtureReplayError) Error

func (*FixtureReplayError) Error() string

Error implements error without rendering request or recorded error data.

func (*FixtureReplayError) Temporary

func (*FixtureReplayError) Temporary() bool

Temporary returns false because fixtures do not imply retry safety.

func (*FixtureReplayError) Timeout

func (err *FixtureReplayError) Timeout() bool

Timeout reports only explicit timeout fixtures.

func (*FixtureReplayError) Unwrap

func (err *FixtureReplayError) Unwrap() error

Unwrap returns the stable failure category.

type FixtureRequest

type FixtureRequest struct {
	Method string      `json:"method"`
	URL    string      `json:"url"`
	Header http.Header `json:"header,omitempty"`
	Body   []byte      `json:"body,omitempty"`
	// BodySHA256 matches a body without persisting its contents.
	BodySHA256 string `json:"body_sha256,omitempty"`
}

FixtureRequest contains bounded match material.

type FixtureResponse

type FixtureResponse struct {
	StatusCode    int                `json:"status_code,omitempty"`
	Header        http.Header        `json:"header,omitempty"`
	Body          []byte             `json:"body,omitempty"`
	Trailer       http.Header        `json:"trailer,omitempty"`
	ContentLength *int64             `json:"content_length,omitempty"`
	Failure       FixtureFailure     `json:"failure,omitempty"`
	BodyFailure   FixtureBodyFailure `json:"body_failure,omitempty"`
}

FixtureResponse contains a bounded response snapshot.

type GeneratedIdentifier

type GeneratedIdentifier struct {
	Value       string
	EntropyBits int
}

GeneratedIdentifier contains a generated value and its claimed entropy.

type HMACError

type HMACError struct {
	Phase HMACPhase
	Cause error
}

HMACError reports a signing failure without rendering its cause or inputs.

func (*HMACError) Error

func (err *HMACError) Error() string

Error implements error without rendering credential or canonical data.

func (*HMACError) Unwrap

func (err *HMACError) Unwrap() error

Unwrap returns the vendor callback or hash failure.

type HMACOptions

type HMACOptions struct {
	Secret         []byte
	NewHash        func() hash.Hash
	Canonicalize   func(request *http.Request) ([]byte, error)
	ApplySignature func(request *http.Request, signature []byte) error
}

HMACOptions supplies vendor-specific canonicalization and signature placement while core performs the HMAC calculation. Secret is copied.

type HMACPhase

type HMACPhase uint8

HMACPhase identifies the vendor-supplied signing step that failed.

const (
	// HMACCanonicalization identifies canonical-request construction.
	HMACCanonicalization HMACPhase = iota
	// HMACCalculation identifies message-authentication-code calculation.
	HMACCalculation
	// HMACApplication identifies signature placement on the request.
	HMACApplication
)

func (HMACPhase) String

func (phase HMACPhase) String() string

String returns a stable phase name.

type HTTPDoer

type HTTPDoer interface {
	Do(*http.Request) (*http.Response, error)
}

HTTPDoer executes one standard HTTP request.

type HTTPStatusError

type HTTPStatusError struct {
	StatusCode int
	Header     http.Header
	VendorCode string
	Excerpt    []byte
	RequestID  string
	Retryable  bool
	Cause      error
}

HTTPStatusError preserves safe structured response state. Error text never renders headers, excerpts, vendor messages, request IDs, or causes.

func (*HTTPStatusError) Error

func (*HTTPStatusError) Error() string

Error implements error.

func (*HTTPStatusError) Unwrap

func (err *HTTPStatusError) Unwrap() []error

Unwrap preserves the stable category and optional vendor cause.

type HeaderRateLimitOptions

type HeaderRateLimitOptions struct {
	RemainingHeader string
	ResetHeader     string
	Reset           RateLimitResetMode
}

HeaderRateLimitOptions configures vendor remaining/reset observation.

type IdempotencyAttemptPolicy

type IdempotencyAttemptPolicy interface {
	PreserveKey(original *http.Request, attempt *http.Request) bool
}

IdempotencyAttemptPolicy decides whether an attempt still represents the original operation for key propagation.

type IdempotencyAttemptPolicyFunc

type IdempotencyAttemptPolicyFunc func(original *http.Request, attempt *http.Request) bool

IdempotencyAttemptPolicyFunc adapts a function to IdempotencyAttemptPolicy.

func (IdempotencyAttemptPolicyFunc) PreserveKey

func (function IdempotencyAttemptPolicyFunc) PreserveKey(
	original *http.Request,
	attempt *http.Request,
) bool

PreserveKey implements IdempotencyAttemptPolicy.

type IdempotencyError

type IdempotencyError struct {
	Cause error
}

IdempotencyError reports key selection or propagation failure without rendering the key, generated candidate, or underlying cause.

func (*IdempotencyError) Error

func (*IdempotencyError) Error() string

Error implements error without rendering idempotency material.

func (*IdempotencyError) Unwrap

func (err *IdempotencyError) Unwrap() error

Unwrap returns the policy, generation, or validation failure.

type IdempotencyKey

type IdempotencyKey struct {
	Value      string
	Provenance IdempotencyProvenance
}

IdempotencyKey is stable for one logical operation. String and GoString redact Value; callers must access Value explicitly when setting a request.

func IdempotencyKeyFromContext

func IdempotencyKeyFromContext(ctx context.Context) (IdempotencyKey, bool)

IdempotencyKeyFromContext returns the resolved logical-operation key.

func (IdempotencyKey) GoString

func (key IdempotencyKey) GoString() string

GoString returns a redacted Go-syntax representation.

func (IdempotencyKey) String

func (key IdempotencyKey) String() string

String returns a redacted representation.

type IdempotencyMode

type IdempotencyMode uint8

IdempotencyMode controls whether a missing caller key is generated.

const (
	// IdempotencyGenerateIfMissing uses a caller key or generates one.
	IdempotencyGenerateIfMissing IdempotencyMode = iota
	// IdempotencyRequireCaller rejects operations without a caller key.
	IdempotencyRequireCaller
)

type IdempotencyOptions

type IdempotencyOptions struct {
	Name               string
	Layer              MiddlewareLayer
	Priority           int
	Mode               IdempotencyMode
	Header             string
	MaximumLength      int
	MinimumEntropyBits int
	Generator          IdentifierGenerator
	AttemptPolicy      IdempotencyAttemptPolicy
}

IdempotencyOptions configures explicit endpoint idempotency middleware.

type IdempotencyProvenance

type IdempotencyProvenance uint8

IdempotencyProvenance identifies how one operation key was selected.

const (
	// IdempotencyGenerated indicates a generated operation key.
	IdempotencyGenerated IdempotencyProvenance = iota
	// IdempotencyCallerHeader indicates a key supplied through the endpoint header.
	IdempotencyCallerHeader
	// IdempotencyCallerContext indicates a key supplied through context.
	IdempotencyCallerContext
)

type IdentifierGenerator

type IdentifierGenerator interface {
	Generate(context.Context) (GeneratedIdentifier, error)
}

IdentifierGenerator creates independent operation or idempotency values. Implementations must be safe for concurrent use and honor cancellation.

func NewRandomIdentifierGenerator

func NewRandomIdentifierGenerator(entropyBits int) (IdentifierGenerator, error)

NewRandomIdentifierGenerator returns a cryptographically random URL-safe generator. Entropy must be between 96 and 512 bits.

type IdentifierGeneratorFunc

type IdentifierGeneratorFunc func(context.Context) (GeneratedIdentifier, error)

IdentifierGeneratorFunc adapts a function to IdentifierGenerator.

func (IdentifierGeneratorFunc) Generate

Generate implements IdentifierGenerator.

type IndexedPaginationPage

type IndexedPaginationPage[Item any] struct {
	Items         []Item
	HasNext       bool
	ResponseBytes int64
}

IndexedPaginationPage is one page for numeric page and offset strategies.

type LeakyBucketOptions

type LeakyBucketOptions struct {
	Rate     float64
	Capacity int
	Clock    RetryClock
}

LeakyBucketOptions configures constant-rate admission with a bounded queue. Rate is requests per second.

type LinkPaginationFetcher

type LinkPaginationFetcher[Item any] func(
	context.Context,
	string,
) (LinkPaginationPage[Item], error)

LinkPaginationFetcher loads one absolute resolved HTTP reference.

type LinkPaginationOptions

type LinkPaginationOptions[Item any] struct {
	InitialURL string
	Fetch      LinkPaginationFetcher[Item]
	Limits     PaginationLimits
	Clock      RetryClock
	Resume     *PaginationState[Item, string]
}

LinkPaginationOptions configures RFC Link-header iteration.

type LinkPaginationPage

type LinkPaginationPage[Item any] struct {
	Items         []Item
	Link          string
	ResponseBytes int64
}

LinkPaginationPage is one RFC Link-header fetch result.

type MemoryCache

type MemoryCache struct {
	// contains filtered or unexported fields
}

MemoryCache is a finite concurrency-safe FIFO cache reference backend.

func NewMemoryCache

func NewMemoryCache(options MemoryCacheOptions) (*MemoryCache, error)

NewMemoryCache constructs an empty finite in-memory cache.

func (*MemoryCache) Delete

func (cache *MemoryCache) Delete(ctx context.Context, key string) error

Delete removes every stored variant for key.

func (*MemoryCache) Load

func (cache *MemoryCache) Load(ctx context.Context, key string) ([]CacheEntry, error)

Load returns independent copies of every stored variant for key.

func (*MemoryCache) Save

func (cache *MemoryCache) Save(ctx context.Context, key string, entry CacheEntry) error

Save inserts or replaces one response variant.

type MemoryCacheOptions

type MemoryCacheOptions struct {
	MaximumEntries int
	MaximumBytes   int64
}

MemoryCacheOptions configures the finite in-memory reference store.

type Middleware

type Middleware struct {
	// contains filtered or unexported fields
}

Middleware is one immutable pipeline registration. Construct values with a stage-specific constructor.

func NewAuthenticationMiddleware

func NewAuthenticationMiddleware(options AuthenticationOptions, editor RequestEditor) ([]Middleware, error)

NewAuthenticationMiddleware creates paired operation and attempt middleware. The operation captures the trusted origin set once; every physical attempt independently applies or strips credentials.

func NewCacheMiddleware

func NewCacheMiddleware(options CacheOptions) (Middleware, error)

NewCacheMiddleware creates operation-scoped cache middleware.

func NewCircuitBreakerMiddleware

func NewCircuitBreakerMiddleware(options CircuitBreakerOptions) (Middleware, error)

NewCircuitBreakerMiddleware creates operation transport middleware outside retry so one logical completion is recorded across all physical attempts.

func NewCompletionMiddleware

func NewCompletionMiddleware(options MiddlewareOptions, handler CompletionMiddlewareFunc) (Middleware, error)

NewCompletionMiddleware constructs completion-stage middleware.

func NewCompressionMiddleware

func NewCompressionMiddleware(options CompressionOptions) (Middleware, error)

NewCompressionMiddleware creates explicit attempt-scoped gzip response decoding. The default transport disables net/http implicit decompression so compressed input remains measurable.

func NewErrorMiddleware

func NewErrorMiddleware(options MiddlewareOptions, handler ErrorMiddlewareFunc) (Middleware, error)

NewErrorMiddleware constructs error-stage middleware.

func NewIdempotencyMiddleware

func NewIdempotencyMiddleware(options IdempotencyOptions) ([]Middleware, error)

NewIdempotencyMiddleware creates paired operation and attempt middleware. Register it only for endpoints whose provider contract supports a key.

func NewRateLimitMiddleware

func NewRateLimitMiddleware(options RateLimitOptions) ([]Middleware, error)

NewRateLimitMiddleware creates attempt request and response middleware.

func NewRequestEditorMiddleware

func NewRequestEditorMiddleware(options MiddlewareOptions, editor RequestEditor) (Middleware, error)

NewRequestEditorMiddleware adapts a generated-client or application request editor to the deterministic request middleware stage.

func NewRequestMiddleware

func NewRequestMiddleware(options MiddlewareOptions, handler AroundMiddlewareFunc) (Middleware, error)

NewRequestMiddleware constructs request-stage middleware.

func NewResponseMiddleware

func NewResponseMiddleware(options MiddlewareOptions, handler ResponseMiddlewareFunc) (Middleware, error)

NewResponseMiddleware constructs response-stage middleware.

func NewRetryMiddleware

func NewRetryMiddleware(options RetryOptions) (Middleware, error)

NewRetryMiddleware creates operation-scoped transport middleware. The middleware retries only replayable requests accepted by endpoint policy.

func NewTransportMiddleware

func NewTransportMiddleware(options MiddlewareOptions, handler AroundMiddlewareFunc) (Middleware, error)

NewTransportMiddleware constructs transport-stage middleware.

type MiddlewareExecutionError

type MiddlewareExecutionError struct {
	Middleware MiddlewareInfo
	Cause      error
}

MiddlewareExecutionError reports a failure returned by response, error, or completion middleware while preserving its cause.

func (*MiddlewareExecutionError) Error

func (err *MiddlewareExecutionError) Error() string

Error implements error without rendering the cause.

func (*MiddlewareExecutionError) Unwrap

func (err *MiddlewareExecutionError) Unwrap() error

Unwrap returns the middleware failure.

type MiddlewareInfo

type MiddlewareInfo struct {
	Name     string
	Scope    MiddlewareScope
	Layer    MiddlewareLayer
	Stage    MiddlewareStage
	Priority int
}

MiddlewareInfo is an immutable inspection record for resolved middleware.

type MiddlewareLayer

type MiddlewareLayer uint8

MiddlewareLayer identifies where middleware was registered. Higher layers replace same-named middleware from lower layers at the same stage and scope.

const (
	// MiddlewareClient contains client-wide middleware.
	MiddlewareClient MiddlewareLayer = iota
	// MiddlewareEndpoint contains endpoint-specific middleware.
	MiddlewareEndpoint
	// MiddlewareRequest contains logical-request middleware.
	MiddlewareRequest
	// MiddlewareOneShot contains middleware for one invocation.
	MiddlewareOneShot
)

type MiddlewareOptions

type MiddlewareOptions struct {
	Name     string
	Scope    MiddlewareScope
	Layer    MiddlewareLayer
	Priority int
}

MiddlewareOptions supplies stable resolution metadata.

type MiddlewarePanicError

type MiddlewarePanicError struct {
	Middleware MiddlewareInfo
	Value      any
}

MiddlewarePanicError reports a contained middleware or transport panic. The panic value remains available to the caller but is not rendered.

func (*MiddlewarePanicError) Error

func (err *MiddlewarePanicError) Error() string

Error implements error without rendering the panic value.

type MiddlewareResultError

type MiddlewareResultError struct {
	Reason string
	Cause  error
}

MiddlewareResultError reports an invalid response/error combination without rendering an underlying failure or response-close error.

func (*MiddlewareResultError) Error

func (err *MiddlewareResultError) Error() string

Error implements error.

func (*MiddlewareResultError) Unwrap

func (err *MiddlewareResultError) Unwrap() []error

Unwrap preserves the stable sentinel and the underlying cause.

type MiddlewareScope

type MiddlewareScope uint8

MiddlewareScope determines whether middleware runs once for a logical operation or once for every physical transport attempt.

const (
	// ScopeOperation runs once around the complete logical operation.
	ScopeOperation MiddlewareScope = iota
	// ScopeAttempt runs for every physical transport attempt.
	ScopeAttempt
)

type MiddlewareStage

type MiddlewareStage uint8

MiddlewareStage identifies one deterministic lifecycle stage.

const (
	// StageRequest can mutate or reject a request before transport policy.
	StageRequest MiddlewareStage = iota
	// StageTransport surrounds the next inner scope or physical transport.
	StageTransport
	// StageResponse observes and may replace a successful response.
	StageResponse
	// StageError observes and may recover a failed exchange.
	StageError
	// StageCompletion always observes the final scope result.
	StageCompletion
)

func (MiddlewareStage) String

func (stage MiddlewareStage) String() string

type MultipartError

type MultipartError struct {
	Operation string
	Cause     error
}

MultipartError reports a multipart operation failure without rendering its underlying error, which may contain request payload details.

func (*MultipartError) Error

func (err *MultipartError) Error() string

Error implements error.

func (*MultipartError) Unwrap

func (err *MultipartError) Unwrap() error

Unwrap returns the underlying multipart failure.

type MultipartOptions

type MultipartOptions struct {
	Boundary     string
	MaximumBytes int64
	Parts        []MultipartPart
}

MultipartOptions configures a deterministic streaming multipart body.

type MultipartPart

type MultipartPart struct {
	Name     string
	FileName string
	Header   http.Header
	Body     RequestBody
}

MultipartPart describes one form-data part and its owned request body.

type Next

type Next func(request *http.Request) (*http.Response, error)

Next continues an around-middleware chain with request.

type OAuth2TokenError

type OAuth2TokenError struct {
	Cause error
}

OAuth2TokenError reports token acquisition or validation failure without rendering its cause, which may include credentials or endpoint data.

func (*OAuth2TokenError) Error

func (*OAuth2TokenError) Error() string

Error implements error without rendering the source failure or token.

func (*OAuth2TokenError) Unwrap

func (err *OAuth2TokenError) Unwrap() error

Unwrap returns the token-source or validation failure.

type OffsetContinuation

type OffsetContinuation struct {
	Offset int
	Limit  int
}

OffsetContinuation is an immutable offset/limit position.

type OffsetPaginationFetcher

type OffsetPaginationFetcher[Item any] func(
	context.Context,
	OffsetContinuation,
) (IndexedPaginationPage[Item], error)

OffsetPaginationFetcher loads one offset/limit position.

type OffsetPaginationOptions

type OffsetPaginationOptions[Item any] struct {
	InitialOffset int
	Limit         int
	Fetch         OffsetPaginationFetcher[Item]
	Limits        PaginationLimits
	Clock         RetryClock
	Resume        *PaginationState[Item, OffsetContinuation]
}

OffsetPaginationOptions configures offset/limit iteration.

type OperationIdentity

type OperationIdentity struct {
	ID         string
	Provenance OperationIdentityProvenance
}

OperationIdentity is stable across all physical attempts in one Client.Do.

func OperationIdentityFromContext

func OperationIdentityFromContext(ctx context.Context) (OperationIdentity, bool)

OperationIdentityFromContext returns resolved logical operation identity.

type OperationIdentityError

type OperationIdentityError struct {
	Cause error
}

OperationIdentityError reports generation or validation failure without rendering the generated value or underlying cause.

func (*OperationIdentityError) Error

func (*OperationIdentityError) Error() string

Error implements error without rendering identity material.

func (*OperationIdentityError) Unwrap

func (err *OperationIdentityError) Unwrap() error

Unwrap returns the generation or validation failure.

type OperationIdentityProvenance

type OperationIdentityProvenance uint8

OperationIdentityProvenance identifies who selected a logical operation ID.

const (
	// IdentityGenerated indicates client-generated operation identity.
	IdentityGenerated OperationIdentityProvenance = iota
	// IdentityCaller indicates an explicitly supplied caller identity.
	IdentityCaller
)

type PageNumberPaginationFetcher

type PageNumberPaginationFetcher[Item any] func(
	context.Context,
	int,
) (IndexedPaginationPage[Item], error)

PageNumberPaginationFetcher loads one positive page number.

type PageNumberPaginationOptions

type PageNumberPaginationOptions[Item any] struct {
	InitialPage int
	Fetch       PageNumberPaginationFetcher[Item]
	Limits      PaginationLimits
	Clock       RetryClock
	Resume      *PaginationState[Item, int]
}

PageNumberPaginationOptions configures page-number iteration.

type PaginationContinuationKey

type PaginationContinuationKey[Continuation any] func(Continuation) (string, error)

PaginationContinuationKey returns a deterministic bounded cycle key without exposing the continuation through errors or telemetry.

type PaginationError

type PaginationError struct {
	Kind  string
	Cause error
}

PaginationError reports a safe failure category without rendering a cursor, vendor response, item, or underlying cause.

func (*PaginationError) Error

func (err *PaginationError) Error() string

Error implements error without rendering pagination data.

func (*PaginationError) Unwrap

func (err *PaginationError) Unwrap() error

Unwrap returns the stable category and underlying cause.

type PaginationFetcher

type PaginationFetcher[Item any, Continuation any] func(
	context.Context,
	Continuation,
) (PaginationPage[Item, Continuation], error)

PaginationFetcher loads one page for an opaque typed continuation.

type PaginationLimits

type PaginationLimits struct {
	MaximumPages             int
	MaximumItems             int
	MaximumElapsed           time.Duration
	MaximumResponseBytes     int64
	MaximumEmptyPages        int
	MaximumContinuationBytes int
}

PaginationLimits are finite cumulative iterator budgets. Zero fields select production defaults.

type PaginationOptions

type PaginationOptions[Item any, Continuation any] struct {
	Initial Continuation
	Fetch   PaginationFetcher[Item, Continuation]
	Key     PaginationContinuationKey[Continuation]
	Limits  PaginationLimits
	Clock   RetryClock
	Resume  *PaginationState[Item, Continuation]
}

PaginationOptions configures one lazy typed iterator.

type PaginationPage

type PaginationPage[Item any, Continuation any] struct {
	Items         []Item
	Next          Continuation
	HasNext       bool
	ResponseBytes int64
}

PaginationPage is one typed fetch result and its next continuation.

type PaginationState

type PaginationState[Item any, Continuation any] struct {
	Continuation  Continuation
	HasNext       bool
	Done          bool
	Buffered      []Item
	BufferedIndex int
	Pages         int
	Items         int
	ResponseBytes int64
	EmptyPages    int
	Elapsed       time.Duration
	Seen          []string
}

PaginationState is a resumable snapshot including unconsumed typed items and continuation cycle history.

type Paginator

type Paginator[Item any, Continuation any] struct {
	// contains filtered or unexported fields
}

Paginator lazily yields typed items. It is safe for concurrent calls, which are serialized to preserve input order and continuation ownership.

func NewCursorPaginator

func NewCursorPaginator[Item any](
	options CursorPaginationOptions[Item],
) (*Paginator[Item, string], error)

NewCursorPaginator creates a lazy opaque-cursor iterator.

func NewLinkPaginator

func NewLinkPaginator[Item any](
	options LinkPaginationOptions[Item],
) (*Paginator[Item, string], error)

NewLinkPaginator creates a lazy RFC Link-header iterator.

func NewOffsetPaginator

func NewOffsetPaginator[Item any](
	options OffsetPaginationOptions[Item],
) (*Paginator[Item, OffsetContinuation], error)

NewOffsetPaginator creates a lazy offset/limit iterator.

func NewPageNumberPaginator

func NewPageNumberPaginator[Item any](
	options PageNumberPaginationOptions[Item],
) (*Paginator[Item, int], error)

NewPageNumberPaginator creates a lazy page-number iterator.

func NewPaginator

func NewPaginator[Item any, Continuation any](
	options PaginationOptions[Item, Continuation],
) (*Paginator[Item, Continuation], error)

NewPaginator validates policy and constructs a lazy iterator without fetching a page.

func (*Paginator[Item, Continuation]) Next

func (paginator *Paginator[Item, Continuation]) Next(ctx context.Context) (Item, bool, error)

Next returns the next item, false at clean exhaustion, or a typed failure.

func (*Paginator[Item, Continuation]) State

func (paginator *Paginator[Item, Continuation]) State() PaginationState[Item, Continuation]

State returns an independent resumable snapshot.

type Pipeline

type Pipeline struct {
	// contains filtered or unexported fields
}

Pipeline is an immutable resolved middleware plan. Its zero value is an empty valid pipeline.

func NewPipeline

func NewPipeline(middleware ...Middleware) (Pipeline, error)

NewPipeline resolves middleware into an immutable pipeline.

func (Pipeline) Execute

func (pipeline Pipeline) Execute(request *http.Request, transport http.RoundTripper) (*http.Response, error)

Execute runs the logical operation and every physical attempt through the resolved pipeline before delegating to transport.

func (Pipeline) Inspect

func (pipeline Pipeline) Inspect() PipelineInspection

Inspect returns independent copies of the resolved operation and attempt plans.

func (Pipeline) With

func (pipeline Pipeline) With(middleware ...Middleware) (Pipeline, error)

With returns a new pipeline containing middleware. The receiver remains unchanged.

type PipelineInspection

type PipelineInspection struct {
	Operation []MiddlewareInfo
	Attempt   []MiddlewareInfo
}

PipelineInspection contains resolved operation and attempt plans. Entries in each plan are ordered by stage, priority, layer, and name.

type PolicyField

type PolicyField string

PolicyField identifies one inspectable resolved value.

const (
	PolicyFieldOperationTimeout            PolicyField = "operation_timeout"
	PolicyFieldRetryMaximumAttempts        PolicyField = "retry_maximum_attempts"
	PolicyFieldRetryMaximumElapsed         PolicyField = "retry_maximum_elapsed"
	PolicyFieldPoolConcurrency             PolicyField = "pool_concurrency"
	PolicyFieldPoolMaximumElapsed          PolicyField = "pool_maximum_elapsed"
	PolicyFieldTransportMaximumConnections PolicyField = "transport_maximum_connections"
	PolicyFieldLimiterMaximumWait          PolicyField = "limiter_maximum_wait"
	PolicyFieldBreakerOpenTimeout          PolicyField = "breaker_open_timeout"
	PolicyFieldCacheMaximumBodyBytes       PolicyField = "cache_maximum_body_bytes"
	PolicyFieldBodyMaximumBytes            PolicyField = "body_maximum_bytes"
	PolicyFieldShutdownTimeout             PolicyField = "shutdown_timeout"
)

type PolicyOverrides

type PolicyOverrides struct {
	OperationTimeout            *time.Duration
	RetryMaximumAttempts        *int
	RetryMaximumElapsed         *time.Duration
	PoolConcurrency             *int
	PoolMaximumElapsed          *time.Duration
	TransportMaximumConnections *int
	LimiterMaximumWait          *time.Duration
	BreakerOpenTimeout          *time.Duration
	CacheMaximumBodyBytes       *int64
	BodyMaximumBytes            *int64
	ShutdownTimeout             *time.Duration
}

PolicyOverrides uses pointers so an explicit value is distinguishable from an omitted field. Every supplied value must be positive and bounded.

type PolicyProfileID

type PolicyProfileID string

PolicyProfileID is a stable name and major version for a built-in policy.

const (
	PolicyProfileInteractiveV1     PolicyProfileID = "interactive/v1"
	PolicyProfileBatchV1           PolicyProfileID = "batch/v1"
	PolicyProfileStreamingV1       PolicyProfileID = "streaming/v1"
	PolicyProfileWebhookDeliveryV1 PolicyProfileID = "webhook-delivery/v1"
)

type PolicyResource

type PolicyResource uint8

PolicyResource identifies independently scoped shared policy state.

const (
	PolicyResourceTransport PolicyResource = iota
	PolicyResourceCookies
	PolicyResourceOAuthTokens
	PolicyResourceCache
	PolicyResourceCoalescing
	PolicyResourceRateLimiter
	PolicyResourceCircuitBreaker
	PolicyResourceMetrics
)

type PolicyScope

type PolicyScope struct {
	// contains filtered or unexported fields
}

PolicyScope is an immutable identity scope attached to a request context.

func NewPolicyScope

func NewPolicyScope(options PolicyScopeOptions) (PolicyScope, error)

NewPolicyScope validates and snapshots identity scope values.

func PolicyScopeFromContext

func PolicyScopeFromContext(ctx context.Context) (PolicyScope, bool)

PolicyScopeFromContext returns an independent scope snapshot.

type PolicyScopeKey

type PolicyScopeKey struct {
	// contains filtered or unexported fields
}

PolicyScopeKey is an opaque stable resource key. String never renders raw scope values.

func ResolvePolicyScope

func ResolvePolicyScope(
	request *http.Request,
	resource PolicyResource,
	dimensions ...ScopeDimension,
) (PolicyScopeKey, error)

ResolvePolicyScope resolves a request to an opaque resource key. Empty dimensions select secure resource-specific defaults.

func (PolicyScopeKey) Dimensions

func (key PolicyScopeKey) Dimensions() []ScopeDimension

Dimensions returns an independent ordered provenance snapshot.

func (PolicyScopeKey) Resource

func (key PolicyScopeKey) Resource() PolicyResource

Resource returns the independently scoped resource.

func (PolicyScopeKey) String

func (key PolicyScopeKey) String() string

String returns the versioned opaque scope key.

type PolicyScopeOptions

type PolicyScopeOptions struct {
	Endpoint   string
	Credential string
	Tenant     string
	Account    string
	Custom     map[string]string
}

PolicyScopeOptions supplies identity and caller-defined scope values. Origin and host are always derived from the concrete request URL.

type PolicySource

type PolicySource string

PolicySource identifies the precedence layer that supplied a value.

const (
	PolicySourceProfile PolicySource = "profile"
	PolicySourceClient  PolicySource = "client"
	PolicySourceRequest PolicySource = "request"
)

type PolicyValues

type PolicyValues struct {
	OperationTimeout            time.Duration
	RetryMaximumAttempts        int
	RetryMaximumElapsed         time.Duration
	PoolConcurrency             int
	PoolMaximumElapsed          time.Duration
	TransportMaximumConnections int
	LimiterMaximumWait          time.Duration
	BreakerOpenTimeout          time.Duration
	CacheMaximumBodyBytes       int64
	BodyMaximumBytes            int64
	ShutdownTimeout             time.Duration
}

PolicyValues contains finite defaults resolved for one logical operation.

type Pool

type Pool[Input any, Output any] struct {
	// contains filtered or unexported fields
}

Pool is an immutable reusable worker policy.

func NewPool

func NewPool[Input any, Output any](
	options PoolOptions[Input, Output],
) (*Pool[Input, Output], error)

NewPool validates and constructs a reusable pool without starting workers.

func (*Pool[Input, Output]) RunChannel

func (pool *Pool[Input, Output]) RunChannel(
	ctx context.Context,
	input <-chan Input,
) ([]PoolResult[Input, Output], error)

RunChannel executes inputs until channel closure or cancellation.

func (*Pool[Input, Output]) RunGenerator

func (pool *Pool[Input, Output]) RunGenerator(
	ctx context.Context,
	generator PoolGenerator[Input],
) ([]PoolResult[Input, Output], error)

RunGenerator executes a lazy caller-owned source with bounded backpressure.

func (*Pool[Input, Output]) RunSlice

func (pool *Pool[Input, Output]) RunSlice(
	ctx context.Context,
	inputs []Input,
) ([]PoolResult[Input, Output], error)

RunSlice executes a finite snapshot of inputs.

type PoolConcurrencySelector

type PoolConcurrencySelector func(PoolWorkload) int

PoolConcurrencySelector chooses one run-wide worker count within configured minimum and maximum bounds.

type PoolError

type PoolError struct {
	Completed int
	Cause     error
}

PoolError reports source, cancellation, fail-fast, or budget termination without rendering input, key, response, or underlying error text.

func (*PoolError) Error

func (*PoolError) Error() string

Error implements error without rendering potentially sensitive causes.

func (*PoolError) Unwrap

func (err *PoolError) Unwrap() error

Unwrap returns the termination cause.

type PoolExecutor

type PoolExecutor[Input any, Output any] func(
	context.Context,
	Input,
) (PoolValue[Output], error)

PoolExecutor executes one input through caller-owned HTTP policy.

type PoolFailureMode

type PoolFailureMode uint8

PoolFailureMode controls request-error cancellation.

const (
	// PoolCollectAll retains every per-request result and error.
	PoolCollectAll PoolFailureMode = iota
	// PoolFailFast cancels pending work after the first request error.
	PoolFailFast
)

type PoolGenerator

type PoolGenerator[Input any] func(context.Context) (Input, bool, error)

PoolGenerator yields one input at a time and must honor context cancellation.

type PoolKey

type PoolKey[Input any] func(Input) (string, error)

PoolKey returns a stable low-cardinality result key.

type PoolLimits

type PoolLimits struct {
	MaximumRequests      int
	MaximumElapsed       time.Duration
	MaximumResponseBytes int64
	MaximumMemoryBytes   int64
}

PoolLimits are finite run-wide budgets. Zero fields select safe defaults.

type PoolOptions

type PoolOptions[Input any, Output any] struct {
	Concurrency        int
	MinimumConcurrency int
	MaximumConcurrency int
	SelectConcurrency  PoolConcurrencySelector
	Pending            int
	Order              PoolResultOrder
	Failure            PoolFailureMode
	Limits             PoolLimits
	Clock              RetryClock
	Key                PoolKey[Input]
	Execute            PoolExecutor[Input, Output]
}

PoolOptions configures one immutable typed execution pool.

type PoolPanicError

type PoolPanicError struct {
	Stage string
	Value any
}

PoolPanicError reports a contained selector, source, key, or executor panic. Value remains available programmatically but is never rendered.

func (*PoolPanicError) Error

func (err *PoolPanicError) Error() string

Error implements error without rendering the panic value.

type PoolResult

type PoolResult[Input any, Output any] struct {
	Index         int
	Key           string
	Input         Input
	Value         Output
	ResponseBytes int64
	MemoryBytes   int64
	Error         error
}

PoolResult preserves one source item, typed value, metadata, and independent request failure.

type PoolResultOrder

type PoolResultOrder uint8

PoolResultOrder controls result presentation independently from execution.

const (
	// PoolInputOrder returns results in stable source order.
	PoolInputOrder PoolResultOrder = iota
	// PoolCompletionOrder returns results as workers complete.
	PoolCompletionOrder
)

type PoolValue

type PoolValue[Output any] struct {
	Value         Output
	ResponseBytes int64
	MemoryBytes   int64
}

PoolValue is one successful typed value and its explicit budget accounting.

type PoolWorkload

type PoolWorkload struct {
	KnownRequests int
}

PoolWorkload describes source shape for bounded concurrency selection.

type QueryEncoder

type QueryEncoder interface {
	EncodeQuery(name string) ([]QueryPart, error)
}

QueryEncoder serializes one named custom query value into structured parts. Implementations must be deterministic and safe for concurrent use.

type QueryEncoderFunc

type QueryEncoderFunc func(name string) ([]QueryPart, error)

QueryEncoderFunc adapts a function to QueryEncoder.

func (QueryEncoderFunc) EncodeQuery

func (function QueryEncoderFunc) EncodeQuery(name string) ([]QueryPart, error)

EncodeQuery implements QueryEncoder.

type QueryEncodingError

type QueryEncodingError struct {
	Parameter string
	Cause     error
}

QueryEncodingError reports a custom encoder failure without exposing query values in the rendered error.

func (*QueryEncodingError) Error

func (err *QueryEncodingError) Error() string

Error implements error.

func (*QueryEncodingError) Unwrap

func (err *QueryEncodingError) Unwrap() error

Unwrap returns the custom encoder failure.

type QueryPart

type QueryPart struct {
	Name     string
	Value    string
	HasValue bool
}

QueryPart is one structurally encoded custom query field. HasValue false emits a bare field name and ignores Value.

type QueryStyle

type QueryStyle uint8

QueryStyle identifies a supported query array serialization style.

const (
	// QueryRepeated emits one key-value pair per item.
	QueryRepeated QueryStyle = iota
	// QueryCommaDelimited emits one comma-delimited value.
	QueryCommaDelimited
	// QuerySpaceDelimited emits one space-delimited value.
	QuerySpaceDelimited
	// QueryPipeDelimited emits one pipe-delimited value.
	QueryPipeDelimited
)

type QueryValue

type QueryValue struct {
	// contains filtered or unexported fields
}

QueryValue is an immutable query serialization instruction. Use a query constructor rather than its zero value.

func CustomQuery

func CustomQuery(encoder QueryEncoder) (QueryValue, error)

CustomQuery creates a structurally escaped custom query value.

func DeepObjectQuery

func DeepObjectQuery(fields map[string]string) QueryValue

DeepObjectQuery serializes fields as name[field]=value. The input map is copied and field names are ordered canonically at build time.

func NullQuery

func NullQuery() QueryValue

NullQuery serializes an explicitly present null value as a bare field name.

func QueryValues

func QueryValues(style QueryStyle, values ...string) (QueryValue, error)

QueryValues serializes values with any exported query array style.

func RepeatedQuery

func RepeatedQuery(values ...string) QueryValue

RepeatedQuery serializes every value as a separate key-value pair. Value order is preserved while parameter names are ordered canonically.

type RangeDisposition

type RangeDisposition uint8

RangeDisposition tells a download controller whether to append, restart, or finalize an already complete partial file.

const (
	// RangeContinue indicates a validated 206 response can be appended.
	RangeContinue RangeDisposition = iota
	// RangeRestart indicates a 200 response must replace partial content.
	RangeRestart
	// RangeComplete indicates a 416 response proves offset equals total length.
	RangeComplete
)

type RangeError

type RangeError struct {
	Operation string
	Cause     error
}

RangeError reports range protocol failure without rendering validators or response header values.

func (*RangeError) Error

func (err *RangeError) Error() string

Error implements error.

func (*RangeError) Unwrap

func (err *RangeError) Unwrap() error

Unwrap returns the stable range failure.

type RangeMetadata

type RangeMetadata struct {
	Start int64
	End   int64
	Total int64
}

RangeMetadata describes parsed representation byte positions. Total is -1 when the server did not disclose complete length.

type RangeOptions

type RangeOptions struct {
	Offset    int64
	Length    int64
	Validator RangeValidator
}

RangeOptions configures an immutable range request clone. Length zero means continue through the end of the representation.

type RangeResponseOptions

type RangeResponseOptions struct {
	Offset       int64
	Length       int64
	Validator    RangeValidator
	AllowRestart bool
}

RangeResponseOptions describes the request a response must satisfy.

type RangeValidator

type RangeValidator struct {
	ETag         string
	LastModified time.Time
}

RangeValidator identifies one representation for safe continuation. ETag must be strong. ETag and LastModified are mutually exclusive.

type RateLimitError

type RateLimitError struct {
	Wait  time.Duration
	Cause error
}

RateLimitError reports admission or observation failure without rendering a custom limiter cause or response header value.

func (*RateLimitError) Error

func (*RateLimitError) Error() string

Error implements error without rendering potentially sensitive causes.

func (*RateLimitError) Unwrap

func (err *RateLimitError) Unwrap() error

Unwrap returns the limiter or observation failure.

type RateLimitObserver

type RateLimitObserver interface {
	Delay(*http.Response, time.Time) (time.Duration, bool, error)
}

RateLimitObserver derives a future admission delay from one response. It must not mutate or consume the response.

func NewHeaderRateLimitObserver

func NewHeaderRateLimitObserver(options HeaderRateLimitOptions) (RateLimitObserver, error)

NewHeaderRateLimitObserver creates configurable remaining/reset observation.

type RateLimitObserverFunc

type RateLimitObserverFunc func(*http.Response, time.Time) (time.Duration, bool, error)

RateLimitObserverFunc adapts a function to RateLimitObserver.

func (RateLimitObserverFunc) Delay

func (function RateLimitObserverFunc) Delay(
	response *http.Response,
	now time.Time,
) (time.Duration, bool, error)

Delay implements RateLimitObserver.

type RateLimitOptions

type RateLimitOptions struct {
	Name               string
	Layer              MiddlewareLayer
	Priority           int
	Limiter            RateLimiter
	Observer           RateLimitObserver
	MaximumWait        time.Duration
	MaximumServerDelay time.Duration
}

RateLimitOptions configures attempt admission and response observation.

type RateLimitResetMode

type RateLimitResetMode uint8

RateLimitResetMode identifies vendor reset header representation.

const (
	// RateLimitResetDeltaSeconds interprets reset as seconds from observation.
	RateLimitResetDeltaSeconds RateLimitResetMode = iota
	// RateLimitResetUnixSeconds interprets reset as a Unix timestamp.
	RateLimitResetUnixSeconds
	// RateLimitResetHTTPDate interprets reset as an HTTP date.
	RateLimitResetHTTPDate
)

type RateLimiter

type RateLimiter interface {
	Acquire(context.Context, time.Duration) (time.Duration, error)
	DeferUntil(time.Time)
	Now() time.Time
}

RateLimiter admits one physical request and can defer future admission. Implementations must be safe for concurrent use.

func NewFixedWindowLimiter

func NewFixedWindowLimiter(options FixedWindowOptions) (RateLimiter, error)

NewFixedWindowLimiter constructs a fixed-window limiter.

func NewLeakyBucketLimiter

func NewLeakyBucketLimiter(options LeakyBucketOptions) (RateLimiter, error)

NewLeakyBucketLimiter constructs a constant-rate bounded-queue limiter.

func NewSlidingWindowLimiter

func NewSlidingWindowLimiter(options SlidingWindowOptions) (RateLimiter, error)

NewSlidingWindowLimiter constructs an exact sliding-window limiter.

func NewTokenBucketLimiter

func NewTokenBucketLimiter(options TokenBucketOptions) (RateLimiter, error)

NewTokenBucketLimiter constructs a token-bucket limiter.

type RecorderOptions

type RecorderOptions struct {
	MatchHeaders            []string
	RedactedQueryParameters []string
	ResponseHeaders         []string
	ResponseTrailers        []string
	VolatileHeaders         []string
	SensitiveHeaders        []string
	MaximumBodyBytes        int64
	TTL                     time.Duration
	Clock                   RetryClock
	ResponseBodyRedactor    FixtureBodyRedactor
}

RecorderOptions configures bounded sanitized fixture capture.

type RecorderTransport

type RecorderTransport struct {
	// contains filtered or unexported fields
}

RecorderTransport records sanitized successful exchanges around base.

func NewRecorderTransport

func NewRecorderTransport(base http.RoundTripper, options RecorderOptions) (*RecorderTransport, error)

NewRecorderTransport creates a bounded recorder with safe persistence defaults. Response bodies are omitted unless a redactor is configured.

func (*RecorderTransport) Fixture

func (recorder *RecorderTransport) Fixture() Fixture

Fixture returns an independently mutable sanitized snapshot.

func (*RecorderTransport) RoundTrip

func (recorder *RecorderTransport) RoundTrip(request *http.Request) (*http.Response, error)

RoundTrip records a sanitized interaction while returning original live response bytes and headers to the caller.

func (*RecorderTransport) WriteFixture

func (recorder *RecorderTransport) WriteFixture(writer io.Writer) error

WriteFixture writes a deterministic sanitized fixture JSON document.

type ReplayOptions

type ReplayOptions struct {
	MatchHeaders     []string
	MaximumBodyBytes int64
}

ReplayOptions configures deterministic bounded request matching.

type ReplayTransport

type ReplayTransport struct {
	// contains filtered or unexported fields
}

ReplayTransport replays one immutable ordered fixture safely across callers.

func NewReplayTransport

func NewReplayTransport(fixture Fixture, options ReplayOptions) (*ReplayTransport, error)

NewReplayTransport validates and snapshots a replay fixture.

func NewScriptedTransport

func NewScriptedTransport(
	interactions []FixtureInteraction,
	options ReplayOptions,
) (*ReplayTransport, error)

NewScriptedTransport constructs a current-schema ordered replay fixture.

func (*ReplayTransport) RoundTrip

func (replay *ReplayTransport) RoundTrip(request *http.Request) (*http.Response, error)

RoundTrip returns the next response only when request matches exactly.

func (*ReplayTransport) Verify

func (replay *ReplayTransport) Verify() error

Verify fails when one or more ordered interactions were not consumed.

type RequestBody

type RequestBody interface {
	Open() (io.ReadCloser, error)
	Replayable() bool
	ContentLength() int64
	ContentType() string
}

RequestBody opens request bodies and describes their replay and metadata policy. Implementations must be safe for concurrent calls when Replayable returns true.

func NewBytesBody

func NewBytesBody(contentType string, content []byte) (RequestBody, error)

NewBytesBody snapshots content and returns a replayable request body.

func NewFormBody

func NewFormBody(values url.Values) (RequestBody, error)

NewFormBody snapshots values as a canonical application/x-www-form-urlencoded body. Keys are sorted and repeated value order is preserved by url.Values.

func NewMultipartBody

func NewMultipartBody(options MultipartOptions) (RequestBody, error)

NewMultipartBody validates and snapshots a multipart/form-data request body. A boundary is required so retries produce byte-identical wire content.

func NewReplayableBody

func NewReplayableBody(contentType string, contentLength int64, opener BodyOpener) (RequestBody, error)

NewReplayableBody returns a body that calls opener for the initial request and every replay. Opener must return an independent reader on every call.

func NewStreamingBody

func NewStreamingBody(contentType string, contentLength int64, reader io.ReadCloser) (RequestBody, error)

NewStreamingBody transfers reader to the first build attempt that opens it. The body is not replayable, and subsequent build attempts return ErrBodyConsumed. If later request construction fails, the reader is closed.

type RequestEditor

type RequestEditor interface {
	EditRequest(request *http.Request) error
}

RequestEditor mutates one independently cloned HTTP request before it is sent. Implementations must be safe for concurrent use.

func NewAPIKeyHeader

func NewAPIKeyHeader(name string, value string) (RequestEditor, error)

NewAPIKeyHeader returns an immutable header API-key editor. Existing values for name are replaced rather than appended.

func NewAPIKeyQuery

func NewAPIKeyQuery(name string, value string) (RequestEditor, error)

NewAPIKeyQuery returns an immutable query API-key editor. Its explicit name makes URL placement opt-in; callers should prefer headers whenever the provider supports them.

func NewBasicAuth

func NewBasicAuth(username string, password string) (RequestEditor, error)

NewBasicAuth returns an immutable HTTP Basic authentication editor. User names containing a colon are rejected because the delimiter would make the credentials ambiguous.

func NewBearerAuth

func NewBearerAuth(token string) (RequestEditor, error)

NewBearerAuth returns an immutable RFC 6750 bearer-token editor.

func NewContextOAuth2Auth

func NewContextOAuth2Auth(source ContextTokenSource) (RequestEditor, error)

NewContextOAuth2Auth returns an editor that passes each request context to a context-aware token source.

func NewHMACAuth

func NewHMACAuth(options HMACOptions) (RequestEditor, error)

NewHMACAuth returns an immutable HMAC request editor. The vendor package retains control of canonicalization and signature syntax so core does not impose a provider-specific signing protocol.

func NewOAuth2Auth

func NewOAuth2Auth(source oauth2.TokenSource) (RequestEditor, error)

NewOAuth2Auth adapts a golang.org/x/oauth2 TokenSource to an immutable request editor. The source is wrapped with oauth2.ReuseTokenSource so valid tokens are shared and refresh calls are serialized.

type RequestEditorError

type RequestEditorError struct {
	Editor string
	Cause  error
}

RequestEditorError reports an editor failure without rendering its cause, which may contain credential material.

func (*RequestEditorError) Error

func (err *RequestEditorError) Error() string

Error implements error without rendering the underlying failure.

func (*RequestEditorError) Unwrap

func (err *RequestEditorError) Unwrap() error

Unwrap returns the underlying editor failure.

type RequestEditorFunc

type RequestEditorFunc func(request *http.Request) error

RequestEditorFunc adapts a function to RequestEditor.

func (RequestEditorFunc) EditRequest

func (function RequestEditorFunc) EditRequest(request *http.Request) error

EditRequest implements RequestEditor.

type RequestLayer

type RequestLayer uint8

RequestLayer defines deterministic precedence for request metadata. Higher layers replace values from lower layers.

const (
	// LayerClient contains client-wide defaults.
	LayerClient RequestLayer = iota
	// LayerEndpoint contains endpoint-specific defaults.
	LayerEndpoint
	// LayerRequest contains logical-operation values.
	LayerRequest
	// LayerAuthentication contains authentication decorator values.
	LayerAuthentication
	// LayerSigning contains request-signing values.
	LayerSigning
	// LayerOneShot contains values for one physical request build.
	LayerOneShot
)

func (RequestLayer) String

func (layer RequestLayer) String() string

String returns the stable policy name for a request layer.

type RequestSpec

type RequestSpec struct {
	// contains filtered or unexported fields
}

RequestSpec is an immutable reusable request description. It resolves one relative reference against a fixed base URL and layers request metadata without replacing standard HTTP request types.

func NewRequestSpec

func NewRequestSpec(baseURL string, reference string) (RequestSpec, error)

NewRequestSpec parses baseURL and resolves reference using RFC 3986 URL resolution. The base must be an absolute HTTP(S) URL without user information. The reference must not select another scheme or authority.

func (RequestSpec) AddHeader

func (spec RequestSpec) AddHeader(layer RequestLayer, name string, values ...string) (RequestSpec, error)

AddHeader returns a spec with values appended at layer. It does not comma-fold values because several standard fields prohibit folding.

func (RequestSpec) AddTrailer

func (spec RequestSpec) AddTrailer(layer RequestLayer, name string, values ...string) (RequestSpec, error)

AddTrailer returns a spec with values appended to a trailer at layer.

func (RequestSpec) Build

func (spec RequestSpec) Build(ctx context.Context, method string) (*http.Request, error)

Build creates an independent standard HTTP request. Mutable headers and the URL never alias the spec or another request built from it.

func (RequestSpec) WithBody

func (spec RequestSpec) WithBody(body RequestBody) (RequestSpec, error)

WithBody returns a spec using body. Replayable bodies can build any number of requests; streaming bodies are explicitly one-shot.

func (RequestSpec) WithHeader

func (spec RequestSpec) WithHeader(layer RequestLayer, name string, values ...string) (RequestSpec, error)

WithHeader returns a spec with name replaced at layer. Higher layers still take precedence. Values are copied and remain separate header field values.

func (RequestSpec) WithQuery

func (spec RequestSpec) WithQuery(layer RequestLayer, name string, value QueryValue) (RequestSpec, error)

WithQuery returns a spec with name replaced at layer.

func (RequestSpec) WithTrailer

func (spec RequestSpec) WithTrailer(layer RequestLayer, name string, values ...string) (RequestSpec, error)

WithTrailer returns a spec with trailer name replaced at layer. Trailer values are snapshotted and require a request body at build time.

func (RequestSpec) WithoutBody

func (spec RequestSpec) WithoutBody() RequestSpec

WithoutBody returns a spec without a request body.

func (RequestSpec) WithoutHeader

func (spec RequestSpec) WithoutHeader(layer RequestLayer, name string) (RequestSpec, error)

WithoutHeader returns a spec that removes an inherited header at layer.

func (RequestSpec) WithoutQuery

func (spec RequestSpec) WithoutQuery(layer RequestLayer, name string) (RequestSpec, error)

WithoutQuery returns a spec that removes an inherited query parameter at layer, including a parameter supplied by the relative reference.

func (RequestSpec) WithoutTrailer

func (spec RequestSpec) WithoutTrailer(layer RequestLayer, name string) (RequestSpec, error)

WithoutTrailer returns a spec that removes an inherited trailer at layer.

type ResolvedPolicy

type ResolvedPolicy struct {
	// contains filtered or unexported fields
}

ResolvedPolicy is an immutable policy and provenance snapshot.

func ResolvePolicy

func ResolvePolicy(
	profile PolicyProfileID,
	client PolicyOverrides,
	request PolicyOverrides,
) (ResolvedPolicy, error)

ResolvePolicy applies deterministic profile, client, then request precedence.

func ResolvedPolicyFromContext

func ResolvedPolicyFromContext(ctx context.Context) (ResolvedPolicy, bool)

ResolvedPolicyFromContext returns an immutable operation policy snapshot.

func (ResolvedPolicy) Profile

func (policy ResolvedPolicy) Profile() PolicyProfileID

Profile returns the stable profile identifier.

func (ResolvedPolicy) Provenance

func (policy ResolvedPolicy) Provenance(field PolicyField) PolicySource

Provenance returns the source of a resolved field, or an empty source for an unknown field.

func (ResolvedPolicy) ProvenanceSnapshot

func (policy ResolvedPolicy) ProvenanceSnapshot() map[PolicyField]PolicySource

ProvenanceSnapshot returns an independently mutable provenance map.

func (ResolvedPolicy) Values

func (policy ResolvedPolicy) Values() PolicyValues

Values returns a value copy of all resolved finite limits.

func (ResolvedPolicy) Version

func (policy ResolvedPolicy) Version() int

Version returns the profile schema major version.

type ResponseBodyError

type ResponseBodyError struct {
	Operation string
	Cause     error
}

ResponseBodyError reports response body lifecycle failure without rendering the underlying error.

func (*ResponseBodyError) Error

func (err *ResponseBodyError) Error() string

Error implements error.

func (*ResponseBodyError) Unwrap

func (err *ResponseBodyError) Unwrap() error

Unwrap returns the body lifecycle failure.

type ResponseDecodeError

type ResponseDecodeError struct{ Cause error }

ResponseDecodeError reports codec or reader failure without rendering its cause, which may contain response data.

func (*ResponseDecodeError) Error

func (*ResponseDecodeError) Error() string

Error implements error.

func (*ResponseDecodeError) Unwrap

func (err *ResponseDecodeError) Unwrap() error

Unwrap returns the decoding failure.

type ResponseDrainLimitError

type ResponseDrainLimitError struct {
	Limit   int64
	Drained int64
}

ResponseDrainLimitError reports that draining exceeded its finite bound.

func (*ResponseDrainLimitError) Error

Error implements error.

func (*ResponseDrainLimitError) Unwrap

func (*ResponseDrainLimitError) Unwrap() error

Unwrap returns the stable drain-limit sentinel.

type ResponseLengthError

type ResponseLengthError struct {
	Expected int64
	Actual   int64
}

ResponseLengthError reports declared and observed response byte counts.

func (*ResponseLengthError) Error

func (*ResponseLengthError) Error() string

Error implements error without rendering response-derived values.

func (*ResponseLengthError) Unwrap

func (*ResponseLengthError) Unwrap() error

Unwrap returns the stable response-length sentinel.

type ResponseLimitError

type ResponseLimitError struct{ Limit int64 }

ResponseLimitError reports a finite response bound without response data.

func (*ResponseLimitError) Error

func (*ResponseLimitError) Error() string

Error implements error.

func (*ResponseLimitError) Unwrap

func (*ResponseLimitError) Unwrap() error

Unwrap returns the stable limit sentinel.

type ResponseMiddlewareFunc

type ResponseMiddlewareFunc func(request *http.Request, response *http.Response) (*http.Response, error)

ResponseMiddlewareFunc observes or replaces a response.

type ResumeError

type ResumeError struct {
	Operation string
	Cause     error
}

ResumeError reports resume state or filesystem failure without rendering paths, validators, headers, or response data.

func (*ResumeError) Error

func (err *ResumeError) Error() string

Error implements error.

func (*ResumeError) Unwrap

func (err *ResumeError) Unwrap() error

Unwrap returns the resume failure.

type ResumeFileOptions

type ResumeFileOptions struct {
	PartialPath    string
	Mode           os.FileMode
	Validator      RangeValidator
	DisableRestart bool
	Transfer       TransferOptions
}

ResumeFileOptions configures persistent partial-file continuation.

type RetryAttempt

type RetryAttempt struct {
	Request        *http.Request
	Response       *http.Response
	Failure        error
	Attempt        int
	BodyReplayable bool
	HasIdempotency bool
}

RetryAttempt describes one completed physical exchange to custom policy. Response and Failure are mutually exclusive.

type RetryClock

type RetryClock interface {
	Now() time.Time
	Wait(context.Context, time.Duration) error
}

RetryClock supplies deterministic time and context-aware waits. Implementations must be safe for concurrent use.

type RetryExhaustedError

type RetryExhaustedError struct {
	Attempts   int
	Elapsed    time.Duration
	StatusCode int
	Cause      error
}

RetryExhaustedError reports a bounded retry stop without rendering the transport cause, response headers, or request data.

func (*RetryExhaustedError) Error

func (*RetryExhaustedError) Error() string

Error implements error without rendering potentially sensitive causes.

func (*RetryExhaustedError) Unwrap

func (err *RetryExhaustedError) Unwrap() []error

Unwrap preserves the stable sentinel and final cause.

type RetryJitter

type RetryJitter interface {
	Apply(time.Duration) time.Duration
}

RetryJitter bounds one exponential backoff delay. Implementations must be safe for concurrent use and return a value between zero and the input.

type RetryJitterFunc

type RetryJitterFunc func(time.Duration) time.Duration

RetryJitterFunc adapts a function to RetryJitter.

func (RetryJitterFunc) Apply

func (function RetryJitterFunc) Apply(delay time.Duration) time.Duration

Apply implements RetryJitter.

type RetryOptions

type RetryOptions struct {
	Name                       string
	Layer                      MiddlewareLayer
	Priority                   int
	MaximumAttempts            int
	MaximumElapsed             time.Duration
	BaseDelay                  time.Duration
	MaximumDelay               time.Duration
	MaximumRetryAfter          time.Duration
	RetryUnsafeWithIdempotency bool
	Clock                      RetryClock
	Jitter                     RetryJitter
	Policy                     RetryPolicy
}

RetryOptions configures bounded operation retry middleware.

type RetryPolicy

type RetryPolicy interface {
	ShouldRetry(RetryAttempt) bool
}

RetryPolicy classifies completed physical exchanges. It must be safe for concurrent use and must not consume or close response bodies.

type RetryPolicyFunc

type RetryPolicyFunc func(RetryAttempt) bool

RetryPolicyFunc adapts a function to RetryPolicy.

func (RetryPolicyFunc) ShouldRetry

func (function RetryPolicyFunc) ShouldRetry(attempt RetryAttempt) bool

ShouldRetry implements RetryPolicy.

type ScopeDimension

type ScopeDimension string

ScopeDimension identifies one canonical policy-scope component.

const (
	ScopeOrigin     ScopeDimension = "origin"
	ScopeHost       ScopeDimension = "host"
	ScopeEndpoint   ScopeDimension = "endpoint"
	ScopeCredential ScopeDimension = "credential"
	ScopeTenant     ScopeDimension = "tenant"
	ScopeAccount    ScopeDimension = "account"
)

func CustomScopeDimension

func CustomScopeDimension(name string) (ScopeDimension, error)

CustomScopeDimension creates a validated caller-defined dimension.

type SessionCloseError

type SessionCloseError struct {
	Cause error
}

SessionCloseError reports an owned jar close failure without rendering it.

func (*SessionCloseError) Error

func (*SessionCloseError) Error() string

Error implements error without rendering jar state or cookie data.

func (*SessionCloseError) Unwrap

func (err *SessionCloseError) Unwrap() error

Unwrap returns the jar close failure.

type SessionConfig

type SessionConfig struct {
	Jar                http.CookieJar
	JarOwnership       CookieJarOwnership
	PublicSuffixList   cookiejar.PublicSuffixList
	RedirectPolicy     CookieRedirectPolicy
	Persistence        SessionPersistence
	LoadOnStart        bool
	SaveOnClose        bool
	PersistenceTimeout time.Duration
}

SessionConfig opts a client into isolated cookie and persistence behavior.

type SessionPersistence

type SessionPersistence interface {
	Load(context.Context, http.CookieJar) error
	Save(context.Context, http.CookieJar) error
}

SessionPersistence stores and restores one configured cookie jar. Methods must honor context cancellation and be safe for concurrent callers.

type SessionPersistenceError

type SessionPersistenceError struct {
	Operation SessionPersistenceOperation
	Cause     error
}

SessionPersistenceError reports a load or save failure without rendering its cause, which may contain cookie values or storage identifiers.

func (*SessionPersistenceError) Error

func (err *SessionPersistenceError) Error() string

Error implements error without rendering persistence data.

func (*SessionPersistenceError) Unwrap

func (err *SessionPersistenceError) Unwrap() error

Unwrap returns the persistence failure.

type SessionPersistenceOperation

type SessionPersistenceOperation uint8

SessionPersistenceOperation identifies a cookie persistence action.

const (
	// SessionPersistenceLoad restores cookies into a jar.
	SessionPersistenceLoad SessionPersistenceOperation = iota
	// SessionPersistenceSave stores cookies from a jar.
	SessionPersistenceSave
)

func (SessionPersistenceOperation) String

func (operation SessionPersistenceOperation) String() string

String returns a stable operation name.

type SlidingWindowOptions

type SlidingWindowOptions struct {
	Limit  int
	Window time.Duration
	Clock  RetryClock
}

SlidingWindowOptions configures an exact sliding-window request limiter.

type SlogTelemetryObserver

type SlogTelemetryObserver struct {
	// contains filtered or unexported fields
}

SlogTelemetryObserver emits safe fixed telemetry fields without URLs, headers, bodies, identity scope values, or error text.

func NewSlogTelemetryObserver

func NewSlogTelemetryObserver(logger *slog.Logger) (*SlogTelemetryObserver, error)

NewSlogTelemetryObserver adapts a standard-library structured logger.

func (*SlogTelemetryObserver) Finish

func (observer *SlogTelemetryObserver) Finish(ctx context.Context, event TelemetryEvent)

Finish logs one operation or attempt completion.

func (*SlogTelemetryObserver) Start

func (observer *SlogTelemetryObserver) Start(ctx context.Context, event TelemetryEvent) context.Context

Start logs one operation or attempt start and preserves ctx.

type StatusOptions

type StatusOptions struct {
	Accept              func(int) bool
	MaximumExcerptBytes int64
	MaximumDrainBytes   int64
	RedactExcerpt       ExcerptRedactor
	Retryable           func(int, http.Header) bool
	MapVendorError      VendorErrorMapper
	RequestIDHeaders    []string
}

StatusOptions configures independent status classification.

type StatusSnapshot

type StatusSnapshot struct {
	StatusCode int
	Header     http.Header
	Excerpt    []byte
	RequestID  string
}

StatusSnapshot supplies bounded redacted response state to vendor mapping.

type TLSOptions

type TLSOptions struct {
	MinimumVersion       uint16
	RootCertificatesPEM  []byte
	ServerName           string
	ClientCertificatePEM []byte
	ClientPrivateKeyPEM  []byte
	SPKISHA256Pins       [][sha256.Size]byte
}

TLSOptions configures immutable TLS trust and peer identity policy. Empty roots use the platform trust store. Zero minimum version selects TLS 1.2.

type TLSPolicy

type TLSPolicy struct {
	// contains filtered or unexported fields
}

TLSPolicy is an immutable standard-transport TLS configuration.

func NewTLSPolicy

func NewTLSPolicy(options TLSOptions) (*TLSPolicy, error)

NewTLSPolicy validates and snapshots TLS trust, identity, and pin policy.

type TelemetryCacheOutcome

type TelemetryCacheOutcome string

TelemetryCacheOutcome is a stable closed cache category.

const (
	// TelemetryCacheNone indicates no cache metadata.
	TelemetryCacheNone TelemetryCacheOutcome = "none"
	// TelemetryCacheMiss indicates transport policy supplied the response.
	TelemetryCacheMiss TelemetryCacheOutcome = "miss"
	// TelemetryCacheHit indicates a fresh stored response.
	TelemetryCacheHit TelemetryCacheOutcome = "hit"
	// TelemetryCacheRevalidated indicates a stored response freshened by 304.
	TelemetryCacheRevalidated TelemetryCacheOutcome = "revalidated"
	// TelemetryCacheStale indicates explicitly permitted stale reuse.
	TelemetryCacheStale TelemetryCacheOutcome = "stale"
)

type TelemetryEvent

type TelemetryEvent struct {
	Phase       TelemetryPhase
	Scope       TelemetryScope
	Attempt     int
	OperationID string
	Method      string
	Profile     PolicyProfileID
	Outcome     TelemetryOutcome
	StatusClass string
	Cache       TelemetryCacheOutcome
}

TelemetryEvent contains fixed bounded fields. It never contains URLs, headers, bodies, credentials, tenant identifiers, cursors, or error text.

func (TelemetryEvent) MetricLabels

func (event TelemetryEvent) MetricLabels() TelemetryMetricLabels

MetricLabels returns fields safe for use as bounded metric labels.

type TelemetryMetricLabels

type TelemetryMetricLabels struct {
	Scope       TelemetryScope
	Method      string
	Profile     PolicyProfileID
	Outcome     TelemetryOutcome
	StatusClass string
	Cache       TelemetryCacheOutcome
}

TelemetryMetricLabels is a closed low-cardinality projection. It excludes operation identity and any raw request, response, or error data.

type TelemetryObserver

type TelemetryObserver interface {
	Start(context.Context, TelemetryEvent) context.Context
	Finish(context.Context, TelemetryEvent)
}

TelemetryObserver creates derived trace contexts and receives completions. Implementations must be safe for concurrent use.

type TelemetryOptions

type TelemetryOptions struct {
	Observer          TelemetryObserver
	Propagator        TelemetryPropagator
	CorrelationHeader string
	BaggageAllowlist  []string
	SensitiveHeaders  []string
}

TelemetryOptions configures optional observation, propagation, and strict trust-boundary header handling.

type TelemetryOutcome

type TelemetryOutcome string

TelemetryOutcome is a stable closed completion category.

const (
	// TelemetryOutcomeSuccess indicates a response below status 400.
	TelemetryOutcomeSuccess TelemetryOutcome = "success"
	// TelemetryOutcomeHTTPError indicates a response status of 400 or greater.
	TelemetryOutcomeHTTPError TelemetryOutcome = "http_error"
	// TelemetryOutcomeTransport indicates transport failure before a response.
	TelemetryOutcomeTransport TelemetryOutcome = "transport_error"
	// TelemetryOutcomeCanceled indicates cancellation or deadline expiry.
	TelemetryOutcomeCanceled TelemetryOutcome = "canceled"
	// TelemetryOutcomeRateLimited indicates local admission rejection.
	TelemetryOutcomeRateLimited TelemetryOutcome = "rate_limited"
	// TelemetryOutcomeCircuitOpen indicates circuit admission rejection.
	TelemetryOutcomeCircuitOpen TelemetryOutcome = "circuit_open"
	// TelemetryOutcomeRetryFailure indicates exhausted retry policy.
	TelemetryOutcomeRetryFailure TelemetryOutcome = "retry_exhausted"
	// TelemetryOutcomeFailure indicates another bounded failure category.
	TelemetryOutcomeFailure TelemetryOutcome = "failure"
)

type TelemetryPhase

type TelemetryPhase string

TelemetryPhase identifies lifecycle start or completion.

const (
	// TelemetryStart begins one operation or attempt.
	TelemetryStart TelemetryPhase = "start"
	// TelemetryFinish completes one operation or attempt.
	TelemetryFinish TelemetryPhase = "finish"
)

type TelemetryPropagator

type TelemetryPropagator interface {
	Inject(context.Context, http.Header)
}

TelemetryPropagator injects trace context into a cloned physical-attempt header. Implementations must be safe for concurrent use.

type TelemetryScope

type TelemetryScope string

TelemetryScope distinguishes logical operations from physical attempts.

const (
	// TelemetryOperation covers one complete logical Client.Do call.
	TelemetryOperation TelemetryScope = "operation"
	// TelemetryAttempt covers one physical RoundTrip.
	TelemetryAttempt TelemetryScope = "attempt"
)

type TokenBucketOptions

type TokenBucketOptions struct {
	Rate  float64
	Burst int
	Clock RetryClock
}

TokenBucketOptions configures a continuously refilled token bucket. Rate is tokens per second and Burst is the maximum stored token count.

type TransferClock

type TransferClock interface{ Now() time.Time }

TransferClock supplies deterministic progress and elapsed time.

type TransferError

type TransferError struct {
	Operation string
	Cause     error
}

TransferError reports streaming I/O or observer failure without rendering its cause, which may contain destination or response data.

func (*TransferError) Error

func (err *TransferError) Error() string

Error implements error.

func (*TransferError) Unwrap

func (err *TransferError) Unwrap() error

Unwrap returns the streaming failure.

type TransferLengthError

type TransferLengthError struct {
	Expected int64
	Actual   int64
}

TransferLengthError reports expected and observed byte counts.

func (*TransferLengthError) Error

func (*TransferLengthError) Error() string

Error implements error.

func (*TransferLengthError) Unwrap

func (*TransferLengthError) Unwrap() error

Unwrap returns the stable transfer length sentinel.

type TransferLimitError

type TransferLimitError struct {
	MaximumBytes int64
	Bytes        int64
}

TransferLimitError reports the finite byte bound.

func (*TransferLimitError) Error

func (*TransferLimitError) Error() string

Error implements error.

func (*TransferLimitError) Unwrap

func (*TransferLimitError) Unwrap() error

Unwrap returns the stable transfer limit sentinel.

type TransferOptions

type TransferOptions struct {
	MaximumBytes     int64
	ExpectedBytes    int64
	DigestAlgorithm  DigestAlgorithm
	ExpectedDigest   []byte
	Progress         TransferProgressObserver
	ProgressInterval time.Duration
	ProgressBytes    int64
	Clock            TransferClock
}

TransferOptions configures a bounded response-to-writer transfer.

type TransferProgress

type TransferProgress struct {
	Bytes    int64
	Total    int64
	Elapsed  time.Duration
	Digest   []byte
	Complete bool
}

TransferProgress is an immutable progress snapshot.

type TransferProgressObserver

type TransferProgressObserver func(context.Context, TransferProgress) error

TransferProgressObserver receives bounded-frequency callbacks. It must not retain or mutate shared request state; Digest is an independent snapshot.

type TransferResult

type TransferResult struct {
	Bytes   int64
	Elapsed time.Duration
	Digest  []byte
}

TransferResult describes one completed transfer.

func CopyResponse

func CopyResponse(
	ctx context.Context,
	response *http.Response,
	destination io.Writer,
	options TransferOptions,
) (result TransferResult, resultErr error)

CopyResponse streams response body into destination, validates configured bounds and digest, and always closes the response body. Destination remains caller-owned and is never closed.

func CopyResponseToFile

func CopyResponseToFile(
	ctx context.Context,
	response *http.Response,
	destination string,
	options FileTransferOptions,
) (result TransferResult, resultErr error)

CopyResponseToFile streams into a same-directory temporary file and replaces destination only after transfer validation, file sync, and close succeed.

func ResumeDownloadToFile

func ResumeDownloadToFile(
	ctx context.Context,
	doer HTTPDoer,
	request *http.Request,
	destination string,
	options ResumeFileOptions,
) (TransferResult, error)

ResumeDownloadToFile continues a same-directory partial file, validates the complete representation, and atomically publishes destination. Failed range appends roll back to their prior safe offset.

type TransportError

type TransportError struct {
	Method string
	URL    string
	Cause  error
}

TransportError reports a failure before a usable HTTP response was returned. URL contains neither user information, query, nor fragment.

func (*TransportError) Error

func (err *TransportError) Error() string

Error implements error without rendering the cause, which may contain credentials or query parameters copied by net/http.

func (*TransportError) Unwrap

func (err *TransportError) Unwrap() error

Unwrap returns the original transport failure.

type TransportFunc

type TransportFunc func(request *http.Request) (*http.Response, error)

TransportFunc adapts a function to http.RoundTripper.

func (TransportFunc) RoundTrip

func (function TransportFunc) RoundTrip(request *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type TransportOwnership

type TransportOwnership uint8

TransportOwnership defines whether Client.Close manages a configured transport. Callers retain ownership by default.

const (
	// TransportBorrowed leaves the configured transport under caller ownership.
	TransportBorrowed TransportOwnership = iota
	// TransportOwned transfers idle-connection cleanup to the Client.
	TransportOwned
)

type UnexpectedContentTypeError

type UnexpectedContentTypeError struct {
	Actual   string
	Expected []string
}

UnexpectedContentTypeError reports parsed media-type mismatch. The fields contain media types only, never body, URL, query, or credential data.

func (*UnexpectedContentTypeError) Error

Error implements error.

func (*UnexpectedContentTypeError) Unwrap

Unwrap returns the stable content-type sentinel.

type VendorErrorMapper

type VendorErrorMapper func(StatusSnapshot) (string, error)

VendorErrorMapper maps safe bounded response state to a stable vendor code and optional cause.

type W3CTraceContext

type W3CTraceContext struct {
	Traceparent string
	Tracestate  string
}

W3CTraceContext contains validated Trace Context propagation fields.

func W3CTraceContextFromContext

func W3CTraceContextFromContext(ctx context.Context) (W3CTraceContext, bool)

W3CTraceContextFromContext returns a validated trace-context snapshot.

type W3CTraceContextPropagator

type W3CTraceContextPropagator struct{}

W3CTraceContextPropagator injects context fields into cloned attempt headers.

func (W3CTraceContextPropagator) Inject

func (W3CTraceContextPropagator) Inject(ctx context.Context, header http.Header)

Inject implements TelemetryPropagator.

Jump to

Keyboard shortcuts

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