Documentation
¶
Overview ¶
Package httpclient provides policy and lifecycle primitives for typed outbound HTTP integrations while preserving the standard net/http API.
Index ¶
- Constants
- Variables
- func ClassifyResponse(response *http.Response, options StatusOptions) (resultErr error)
- func DecodeJSONResponse[T any](response *http.Response, options DecodeOptions) (value T, resultErr error)
- func DecodeResponse[T any](response *http.Response, options DecodeOptions, decode DecodeFunc[T]) (value T, resultErr error)
- func DrainResponse(response *http.Response, options DrainOptions) (resultErr error)
- func NewGoCircuitBreakerClassifier(classifier CircuitOutcomeClassifier) (breaker.Classifier, error)
- func ParseNextLink(value string) (string, bool, error)
- func ValidateRangeResponse(response *http.Response, options RangeResponseOptions) (RangeMetadata, RangeDisposition, error)
- func WithCacheMode(ctx context.Context, mode CacheMode) (context.Context, error)
- func WithIdempotencyKey(ctx context.Context, key string) (context.Context, error)
- func WithOperationIdentity(ctx context.Context, identifier string) (context.Context, error)
- func WithPolicyOverrides(ctx context.Context, overrides PolicyOverrides) (context.Context, error)
- func WithPolicyScope(ctx context.Context, scope PolicyScope) (context.Context, error)
- func WithRange(request *http.Request, options RangeOptions) (*http.Request, error)
- func WithW3CTraceContext(ctx context.Context, traceparent string, tracestate string) (context.Context, error)
- type AroundMiddlewareFunc
- type AuthenticationOptions
- type BodyOpenError
- type BodyOpener
- type CacheEntry
- type CacheError
- type CacheFailureMode
- type CacheKeyFunc
- type CacheMetadata
- type CacheMode
- type CacheOptions
- type CacheProvenance
- type CacheRevalidationScheduler
- type CacheStore
- type CircuitBreaker
- type CircuitBreakerError
- type CircuitBreakerFunc
- type CircuitBreakerOptions
- type CircuitOutcome
- type CircuitOutcomeClassifier
- type CircuitOutcomeClassifierFunc
- type Client
- func (client *Client) Close() error
- func (client *Client) CloseIdleConnections()
- func (client *Client) Do(request *http.Request) (*http.Response, error)
- func (client *Client) DoWithMiddleware(request *http.Request, middleware ...Middleware) (*http.Response, error)
- func (client *Client) HTTPClient() *http.Client
- func (client *Client) InspectPipeline() PipelineInspection
- func (client *Client) InspectPolicy(request *http.Request) (ResolvedPolicy, error)
- func (client *Client) LoadSession(ctx context.Context) error
- func (client *Client) SaveSession(ctx context.Context) error
- type ClientCredentialsError
- type ClientCredentialsOptions
- type ClientCredentialsTokenSource
- type CompletionMiddlewareFunc
- type CompressionError
- type CompressionOptions
- type Config
- type ContextCircuitOutcomeClassifier
- type ContextTokenSource
- type ContextTokenSourceFunc
- type CookieJarOwnership
- type CookieRedirectPolicy
- type CursorPaginationFetcher
- type CursorPaginationOptions
- type CursorPaginationPage
- type DecodeFunc
- type DecodeOptions
- type DecompressionLimitError
- type DigestAlgorithm
- type DigestMismatchError
- type DrainOptions
- type EgressError
- type EgressOptions
- type EgressPolicy
- type EgressReason
- type EgressResolver
- type EgressResolverFunc
- type ErrorMiddlewareFunc
- type ExcerptRedactor
- type FileTransferError
- type FileTransferOptions
- type FixedWindowOptions
- type Fixture
- type FixtureBodyFailure
- type FixtureBodyRedactor
- type FixtureBodyRedactorFunc
- type FixtureError
- type FixtureFailure
- type FixtureInteraction
- type FixtureLoadOptions
- type FixtureMatchPolicy
- type FixtureMigrator
- type FixtureMigratorFunc
- type FixtureReplayError
- type FixtureRequest
- type FixtureResponse
- type GeneratedIdentifier
- type HMACError
- type HMACOptions
- type HMACPhase
- type HTTPDoer
- type HTTPStatusError
- type HeaderRateLimitOptions
- type IdempotencyAttemptPolicy
- type IdempotencyAttemptPolicyFunc
- type IdempotencyError
- type IdempotencyKey
- type IdempotencyMode
- type IdempotencyOptions
- type IdempotencyProvenance
- type IdentifierGenerator
- type IdentifierGeneratorFunc
- type IndexedPaginationPage
- type LeakyBucketOptions
- type LinkPaginationFetcher
- type LinkPaginationOptions
- type LinkPaginationPage
- type MemoryCache
- type MemoryCacheOptions
- type Middleware
- func NewAuthenticationMiddleware(options AuthenticationOptions, editor RequestEditor) ([]Middleware, error)
- func NewCacheMiddleware(options CacheOptions) (Middleware, error)
- func NewCircuitBreakerMiddleware(options CircuitBreakerOptions) (Middleware, error)
- func NewCompletionMiddleware(options MiddlewareOptions, handler CompletionMiddlewareFunc) (Middleware, error)
- func NewCompressionMiddleware(options CompressionOptions) (Middleware, error)
- func NewErrorMiddleware(options MiddlewareOptions, handler ErrorMiddlewareFunc) (Middleware, error)
- func NewIdempotencyMiddleware(options IdempotencyOptions) ([]Middleware, error)
- func NewRateLimitMiddleware(options RateLimitOptions) ([]Middleware, error)
- func NewRequestEditorMiddleware(options MiddlewareOptions, editor RequestEditor) (Middleware, error)
- func NewRequestMiddleware(options MiddlewareOptions, handler AroundMiddlewareFunc) (Middleware, error)
- func NewResponseMiddleware(options MiddlewareOptions, handler ResponseMiddlewareFunc) (Middleware, error)
- func NewRetryMiddleware(options RetryOptions) (Middleware, error)
- func NewTransportMiddleware(options MiddlewareOptions, handler AroundMiddlewareFunc) (Middleware, error)
- type MiddlewareExecutionError
- type MiddlewareInfo
- type MiddlewareLayer
- type MiddlewareOptions
- type MiddlewarePanicError
- type MiddlewareResultError
- type MiddlewareScope
- type MiddlewareStage
- type MultipartError
- type MultipartOptions
- type MultipartPart
- type Next
- type OAuth2TokenError
- type OffsetContinuation
- type OffsetPaginationFetcher
- type OffsetPaginationOptions
- type OperationIdentity
- type OperationIdentityError
- type OperationIdentityProvenance
- type PageNumberPaginationFetcher
- type PageNumberPaginationOptions
- type PaginationContinuationKey
- type PaginationError
- type PaginationFetcher
- type PaginationLimits
- type PaginationOptions
- type PaginationPage
- type PaginationState
- type Paginator
- func NewCursorPaginator[Item any](options CursorPaginationOptions[Item]) (*Paginator[Item, string], error)
- func NewLinkPaginator[Item any](options LinkPaginationOptions[Item]) (*Paginator[Item, string], error)
- func NewOffsetPaginator[Item any](options OffsetPaginationOptions[Item]) (*Paginator[Item, OffsetContinuation], error)
- func NewPageNumberPaginator[Item any](options PageNumberPaginationOptions[Item]) (*Paginator[Item, int], error)
- func NewPaginator[Item any, Continuation any](options PaginationOptions[Item, Continuation]) (*Paginator[Item, Continuation], error)
- type Pipeline
- type PipelineInspection
- type PolicyField
- type PolicyOverrides
- type PolicyProfileID
- type PolicyResource
- type PolicyScope
- type PolicyScopeKey
- type PolicyScopeOptions
- type PolicySource
- type PolicyValues
- type Pool
- func (pool *Pool[Input, Output]) RunChannel(ctx context.Context, input <-chan Input) ([]PoolResult[Input, Output], error)
- func (pool *Pool[Input, Output]) RunGenerator(ctx context.Context, generator PoolGenerator[Input]) ([]PoolResult[Input, Output], error)
- func (pool *Pool[Input, Output]) RunSlice(ctx context.Context, inputs []Input) ([]PoolResult[Input, Output], error)
- type PoolConcurrencySelector
- type PoolError
- type PoolExecutor
- type PoolFailureMode
- type PoolGenerator
- type PoolKey
- type PoolLimits
- type PoolOptions
- type PoolPanicError
- type PoolResult
- type PoolResultOrder
- type PoolValue
- type PoolWorkload
- type QueryEncoder
- type QueryEncoderFunc
- type QueryEncodingError
- type QueryPart
- type QueryStyle
- type QueryValue
- type RangeDisposition
- type RangeError
- type RangeMetadata
- type RangeOptions
- type RangeResponseOptions
- type RangeValidator
- type RateLimitError
- type RateLimitObserver
- type RateLimitObserverFunc
- type RateLimitOptions
- type RateLimitResetMode
- type RateLimiter
- func NewFixedWindowLimiter(options FixedWindowOptions) (RateLimiter, error)
- func NewLeakyBucketLimiter(options LeakyBucketOptions) (RateLimiter, error)
- func NewSlidingWindowLimiter(options SlidingWindowOptions) (RateLimiter, error)
- func NewTokenBucketLimiter(options TokenBucketOptions) (RateLimiter, error)
- type RecorderOptions
- type RecorderTransport
- type ReplayOptions
- type ReplayTransport
- type RequestBody
- func NewBytesBody(contentType string, content []byte) (RequestBody, error)
- func NewFormBody(values url.Values) (RequestBody, error)
- func NewMultipartBody(options MultipartOptions) (RequestBody, error)
- func NewReplayableBody(contentType string, contentLength int64, opener BodyOpener) (RequestBody, error)
- func NewStreamingBody(contentType string, contentLength int64, reader io.ReadCloser) (RequestBody, error)
- type RequestEditor
- func NewAPIKeyHeader(name string, value string) (RequestEditor, error)
- func NewAPIKeyQuery(name string, value string) (RequestEditor, error)
- func NewBasicAuth(username string, password string) (RequestEditor, error)
- func NewBearerAuth(token string) (RequestEditor, error)
- func NewContextOAuth2Auth(source ContextTokenSource) (RequestEditor, error)
- func NewHMACAuth(options HMACOptions) (RequestEditor, error)
- func NewOAuth2Auth(source oauth2.TokenSource) (RequestEditor, error)
- type RequestEditorError
- type RequestEditorFunc
- type RequestLayer
- type RequestSpec
- func (spec RequestSpec) AddHeader(layer RequestLayer, name string, values ...string) (RequestSpec, error)
- func (spec RequestSpec) AddTrailer(layer RequestLayer, name string, values ...string) (RequestSpec, error)
- func (spec RequestSpec) Build(ctx context.Context, method string) (*http.Request, error)
- func (spec RequestSpec) WithBody(body RequestBody) (RequestSpec, error)
- func (spec RequestSpec) WithHeader(layer RequestLayer, name string, values ...string) (RequestSpec, error)
- func (spec RequestSpec) WithQuery(layer RequestLayer, name string, value QueryValue) (RequestSpec, error)
- func (spec RequestSpec) WithTrailer(layer RequestLayer, name string, values ...string) (RequestSpec, error)
- func (spec RequestSpec) WithoutBody() RequestSpec
- func (spec RequestSpec) WithoutHeader(layer RequestLayer, name string) (RequestSpec, error)
- func (spec RequestSpec) WithoutQuery(layer RequestLayer, name string) (RequestSpec, error)
- func (spec RequestSpec) WithoutTrailer(layer RequestLayer, name string) (RequestSpec, error)
- type ResolvedPolicy
- type ResponseBodyError
- type ResponseDecodeError
- type ResponseDrainLimitError
- type ResponseLengthError
- type ResponseLimitError
- type ResponseMiddlewareFunc
- type ResumeError
- type ResumeFileOptions
- type RetryAttempt
- type RetryClock
- type RetryExhaustedError
- type RetryJitter
- type RetryJitterFunc
- type RetryOptions
- type RetryPolicy
- type RetryPolicyFunc
- type ScopeDimension
- type SessionCloseError
- type SessionConfig
- type SessionPersistence
- type SessionPersistenceError
- type SessionPersistenceOperation
- type SlidingWindowOptions
- type SlogTelemetryObserver
- type StatusOptions
- type StatusSnapshot
- type TLSOptions
- type TLSPolicy
- type TelemetryCacheOutcome
- type TelemetryEvent
- type TelemetryMetricLabels
- type TelemetryObserver
- type TelemetryOptions
- type TelemetryOutcome
- type TelemetryPhase
- type TelemetryPropagator
- type TelemetryScope
- type TokenBucketOptions
- type TransferClock
- type TransferError
- type TransferLengthError
- type TransferLimitError
- type TransferOptions
- type TransferProgress
- type TransferProgressObserver
- type TransferResult
- func CopyResponse(ctx context.Context, response *http.Response, destination io.Writer, ...) (result TransferResult, resultErr error)
- func CopyResponseToFile(ctx context.Context, response *http.Response, destination string, ...) (result TransferResult, resultErr error)
- func ResumeDownloadToFile(ctx context.Context, doer HTTPDoer, request *http.Request, destination string, ...) (TransferResult, error)
- type TransportError
- type TransportFunc
- type TransportOwnership
- type UnexpectedContentTypeError
- type VendorErrorMapper
- type W3CTraceContext
- type W3CTraceContextPropagator
Constants ¶
const (
// FixtureSchemaVersion is the current persisted fixture schema.
FixtureSchemaVersion = 1
)
Variables ¶
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") )
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") )
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") )
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") )
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") )
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") )
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") )
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") )
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") )
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") )
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") )
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") )
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") )
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") )
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") )
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") )
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") )
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") )
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") )
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 = errors.New("HTTP session persistence is unavailable") )
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") )
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") )
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") )
var ( // ErrInvalidAuthentication indicates invalid credential policy or input. ErrInvalidAuthentication = errors.New("invalid HTTP authentication") )
var ( // ErrInvalidOAuth2Token indicates a missing, expired, or unsafe token. ErrInvalidOAuth2Token = errors.New("invalid OAuth2 token") )
var ( // ErrInvalidPolicyProfile indicates an unknown profile or invalid override. ErrInvalidPolicyProfile = errors.New("invalid HTTP policy profile") )
var ( // ErrInvalidPolicyScope indicates malformed scope state or resolution. ErrInvalidPolicyScope = errors.New("invalid HTTP policy scope") )
var ErrInvalidTelemetry = errors.New("invalid HTTP telemetry policy")
ErrInvalidTelemetry indicates malformed telemetry adapters or header policy.
var ErrInvalidTraceContext = errors.New("invalid W3C trace context")
ErrInvalidTraceContext indicates malformed W3C propagation fields.
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 ¶
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 ¶
WithCacheMode returns a context carrying one explicit request cache mode.
func WithIdempotencyKey ¶
WithIdempotencyKey returns a context carrying a caller-supplied key. The endpoint policy still applies its configured maximum length.
func WithOperationIdentity ¶
WithOperationIdentity returns a context carrying validated caller identity.
func WithPolicyOverrides ¶
WithPolicyOverrides attaches an immutable per-request override snapshot.
func WithPolicyScope ¶
WithPolicyScope attaches an immutable scope snapshot to ctx.
Types ¶
type AroundMiddlewareFunc ¶
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) 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 ¶
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 ¶
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.
type CacheOptions ¶
type CacheOptions struct {
Name string
Layer MiddlewareLayer
Priority int
Namespace string
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.
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 (*Client) Close ¶
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 ¶
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 ¶
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 ¶
LoadSession restores 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.
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 ¶
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 ¶
ContextTokenSource obtains an OAuth2 token using the request context. Implementations must coordinate concurrent refreshes and honor cancellation.
type ContextTokenSourceFunc ¶
ContextTokenSourceFunc adapts a function to 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 ¶
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 ¶
func (*DecompressionLimitError) Error() string
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) 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 ¶
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 ¶
ErrorMiddlewareFunc observes an error and may return a recovered response.
type ExcerptRedactor ¶
ExcerptRedactor returns an independent safe excerpt. It must not retain its input, which can contain sensitive response data.
type FileTransferError ¶
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 ¶
FixtureBodyRedactor sanitizes one bounded response body before storage.
type FixtureBodyRedactorFunc ¶
FixtureBodyRedactorFunc adapts a body-redaction function.
func (FixtureBodyRedactorFunc) RedactFixtureBody ¶
func (function FixtureBodyRedactorFunc) RedactFixtureBody(content []byte) ([]byte, error)
RedactFixtureBody implements FixtureBodyRedactor.
type FixtureError ¶
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 ¶
GeneratedIdentifier contains a generated value and its claimed entropy.
type HMACError ¶
HMACError reports a signing failure without rendering its cause or inputs.
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.
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) 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 ¶
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 ¶
func (function IdentifierGeneratorFunc) Generate(ctx context.Context) (GeneratedIdentifier, error)
Generate implements IdentifierGenerator.
type IndexedPaginationPage ¶
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 ¶
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 ¶
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 ¶
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 ¶
MultipartError reports a multipart operation failure without rendering its underlying error, which may contain request payload details.
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 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 ¶
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 ¶
PaginationContinuationKey returns a deterministic bounded cycle key without exposing the continuation through errors or telemetry.
type PaginationError ¶
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 ¶
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 ¶
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.
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 ¶
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.
type PoolConcurrencySelector ¶
type PoolConcurrencySelector func(PoolWorkload) int
PoolConcurrencySelector chooses one run-wide worker count within configured minimum and maximum bounds.
type PoolError ¶
PoolError reports source, cancellation, fail-fast, or budget termination without rendering input, key, response, or underlying error text.
type PoolExecutor ¶
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 ¶
PoolGenerator yields one input at a time and must honor context cancellation.
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 ¶
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 PoolWorkload ¶
type PoolWorkload struct {
KnownRequests int
}
PoolWorkload describes source shape for bounded concurrency selection.
type QueryEncoder ¶
QueryEncoder serializes one named custom query value into structured parts. Implementations must be deterministic and safe for concurrent use.
type QueryEncoderFunc ¶
QueryEncoderFunc adapts a function to QueryEncoder.
func (QueryEncoderFunc) EncodeQuery ¶
func (function QueryEncoderFunc) EncodeQuery(name string) ([]QueryPart, error)
EncodeQuery implements QueryEncoder.
type QueryEncodingError ¶
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 ¶
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 ¶
RangeError reports range protocol failure without rendering validators or response header values.
func (*RangeError) Unwrap ¶
func (err *RangeError) Unwrap() error
Unwrap returns the stable range failure.
type RangeMetadata ¶
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 ¶
RangeValidator identifies one representation for safe continuation. ETag must be strong. ETag and LastModified are mutually exclusive.
type RateLimitError ¶
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 ¶
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 ¶
RateLimitObserverFunc adapts a function to 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ResponseDrainLimitError reports that draining exceeded its finite bound.
func (*ResponseDrainLimitError) Error ¶
func (*ResponseDrainLimitError) Error() string
Error implements error.
func (*ResponseDrainLimitError) Unwrap ¶
func (*ResponseDrainLimitError) Unwrap() error
Unwrap returns the stable drain-limit sentinel.
type ResponseLengthError ¶
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 ¶
ResumeError reports resume state or filesystem failure without rendering paths, validators, headers, or response data.
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 ¶
RetryClock supplies deterministic time and context-aware waits. Implementations must be safe for concurrent use.
type RetryExhaustedError ¶
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 ¶
RetryJitter bounds one exponential backoff delay. Implementations must be safe for concurrent use and return a value between zero and the input.
type RetryJitterFunc ¶
RetryJitterFunc adapts a function to 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 ¶
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 ¶
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 ¶
TransferClock supplies deterministic progress and elapsed time.
type TransferError ¶
TransferError reports streaming I/O or observer failure without rendering its cause, which may contain destination or response data.
func (*TransferError) Unwrap ¶
func (err *TransferError) Unwrap() error
Unwrap returns the streaming failure.
type TransferLengthError ¶
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 ¶
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 ¶
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 ¶
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 ¶
TransportFunc adapts a function to 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 ¶
UnexpectedContentTypeError reports parsed media-type mismatch. The fields contain media types only, never body, URL, query, or credential data.
func (*UnexpectedContentTypeError) Error ¶
func (*UnexpectedContentTypeError) Error() string
Error implements error.
func (*UnexpectedContentTypeError) Unwrap ¶
func (*UnexpectedContentTypeError) Unwrap() error
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 ¶
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.
Source Files
¶
- auth.go
- body.go
- cache.go
- circuit_breaker.go
- client.go
- compression.go
- egress.go
- egress_transport.go
- fixture.go
- fixture_persistence.go
- fixture_record.go
- idempotency.go
- identity.go
- multipart.go
- oauth2.go
- observability.go
- observability_slog.go
- pagination.go
- pagination_strategies.go
- pipeline.go
- pool.go
- profile.go
- range.go
- rate_limit.go
- request.go
- response.go
- response_drain.go
- resume.go
- retry.go
- scope.go
- session.go
- status.go
- tls_policy.go
- trace_context.go
- transfer.go
- transfer_file.go