integration

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package integration provides resilience patterns for external service communication.

Index

Constants

This section is empty.

Variables

View Source
var ErrCircuitOpen = errors.New("circuit breaker is open")

ErrCircuitOpen is returned when the circuit breaker is open.

View Source
var ErrTimeout = errors.New("operation timed out")

ErrTimeout is returned when an operation times out.

Functions

func DoWithResult

func DoWithResult[T any](ctx context.Context, r *Retryer, fn func(context.Context) (T, error)) (T, error)

DoWithResult executes a function that returns a result with retry logic.

func ExecuteWithResult

func ExecuteWithResult[T any](ctx context.Context, tm *TimeoutManager, timeout time.Duration, operation string, fn func(context.Context) (T, error)) (T, error)

ExecuteWithResult runs a function that returns a result with the specified timeout.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable checks if an error is retryable using the default logic.

func IsRetryableStatusCode

func IsRetryableStatusCode(statusCode int) bool

IsRetryableStatusCode checks if an HTTP status code should be retried.

func Retry

func Retry(ctx context.Context, fn func(context.Context) error) error

Retry executes a function with the default retry configuration.

func RetryWithConfig

func RetryWithConfig(ctx context.Context, config RetryConfig, fn func(context.Context) error) error

RetryWithConfig executes a function with the given retry configuration.

func WithTimeout

func WithTimeout(ctx context.Context, timeout time.Duration, fn func(context.Context) error) error

WithTimeout is a convenience function that runs a function with a timeout.

Types

type AuthConfig

type AuthConfig struct {
	// Type is the authentication type.
	Type AuthType

	// Token is the bearer token (for AuthBearer).
	Token string

	// APIKey is the API key (for AuthAPIKey).
	APIKey string

	// APIKeyHeader is the header name for API key (for AuthAPIKey).
	// Default: "X-API-Key"
	APIKeyHeader string

	// Username is the username (for AuthBasic).
	Username string

	// Password is the password (for AuthBasic).
	Password string

	// OAuth2Config is the OAuth2 configuration (for AuthOAuth2).
	OAuth2Config *OAuth2Config
}

AuthConfig configures authentication.

type AuthType

type AuthType string

AuthType represents the type of authentication.

const (
	AuthNone   AuthType = "none"
	AuthBearer AuthType = "bearer"
	AuthAPIKey AuthType = "api_key"
	AuthBasic  AuthType = "basic"
	AuthOAuth2 AuthType = "oauth2"
)

type CircuitBreaker

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

CircuitBreaker implements the circuit breaker pattern.

func NewCircuitBreaker

func NewCircuitBreaker(name string, config CircuitBreakerConfig) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker with the given name and configuration.

func (*CircuitBreaker) Allow

func (cb *CircuitBreaker) Allow() error

Allow checks if a request is allowed to proceed. Returns nil if allowed, ErrCircuitOpen if the circuit is open.

func (*CircuitBreaker) Execute

func (cb *CircuitBreaker) Execute(ctx context.Context, fn func(context.Context) error) error

Execute runs the given function with circuit breaker protection.

func (*CircuitBreaker) Name

func (cb *CircuitBreaker) Name() string

Name returns the name of the circuit breaker.

func (*CircuitBreaker) RecordFailure

func (cb *CircuitBreaker) RecordFailure()

RecordFailure records a failed request.

func (*CircuitBreaker) RecordSuccess

func (cb *CircuitBreaker) RecordSuccess()

RecordSuccess records a successful request.

func (*CircuitBreaker) Reset

func (cb *CircuitBreaker) Reset()

Reset resets the circuit breaker to its initial closed state.

func (*CircuitBreaker) State

func (cb *CircuitBreaker) State() CircuitState

State returns the current state of the circuit breaker.

func (*CircuitBreaker) Stats

func (cb *CircuitBreaker) Stats() CircuitBreakerStats

Stats returns the current statistics of the circuit breaker.

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	// FailureThreshold is the number of failures before opening the circuit.
	// Default: 5
	FailureThreshold int

	// Timeout is the duration the circuit stays open before transitioning to half-open.
	// Default: 60s
	Timeout time.Duration

	// HalfOpenRequests is the number of successful requests required in half-open state
	// to transition back to closed.
	// Default: 3
	HalfOpenRequests int

	// OnStateChange is called when the circuit state changes.
	OnStateChange func(from, to CircuitState)
}

CircuitBreakerConfig configures a circuit breaker.

func DefaultCircuitBreakerConfig

func DefaultCircuitBreakerConfig() CircuitBreakerConfig

DefaultCircuitBreakerConfig returns the default circuit breaker configuration.

type CircuitBreakerRegistry

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

CircuitBreakerRegistry manages multiple circuit breakers.

func NewCircuitBreakerRegistry

func NewCircuitBreakerRegistry(defaultConfig CircuitBreakerConfig) *CircuitBreakerRegistry

NewCircuitBreakerRegistry creates a new circuit breaker registry.

func (*CircuitBreakerRegistry) All

All returns all registered circuit breakers.

func (*CircuitBreakerRegistry) Get

Get returns the circuit breaker for the given service name, creating one if it doesn't exist.

func (*CircuitBreakerRegistry) Register

Register registers a circuit breaker with a custom configuration.

func (*CircuitBreakerRegistry) Stats

Stats returns statistics for all circuit breakers.

type CircuitBreakerStats

type CircuitBreakerStats struct {
	Name              string
	State             CircuitState
	Failures          int
	HalfOpenSuccesses int
	LastFailure       time.Time
	LastStateChange   time.Time
}

CircuitBreakerStats contains the current statistics of a circuit breaker.

type CircuitState

type CircuitState int32

CircuitState represents the state of a circuit breaker.

const (
	// StateClosed allows requests to pass through.
	StateClosed CircuitState = iota
	// StateOpen blocks all requests.
	StateOpen
	// StateHalfOpen allows limited requests to test recovery.
	StateHalfOpen
)

func (CircuitState) String

func (s CircuitState) String() string

String returns the string representation of the circuit state.

func (CircuitState) ToMetricsState

func (s CircuitState) ToMetricsState() metrics.CircuitBreakerState

ToMetricsState converts the CircuitState to a metrics state.

type Config

type Config struct {
	// ServiceName is the name of the external service.
	ServiceName string

	// BaseURL is the base URL of the external service.
	BaseURL string

	// Timeout configures timeout behavior.
	Timeout TimeoutConfig

	// Retry configures retry behavior.
	Retry RetryConfig

	// CircuitBreaker configures circuit breaker behavior.
	CircuitBreaker CircuitBreakerConfig

	// Headers are default headers to include in all requests.
	Headers map[string]string

	// Auth configures authentication.
	Auth AuthConfig

	// EnableMetrics enables metrics collection.
	EnableMetrics bool

	// EnableLogging enables request/response logging.
	EnableLogging bool

	// RedactFields specifies fields to redact in logs.
	RedactFields []string

	// UserAgent is the User-Agent header value.
	UserAgent string
}

Config holds the complete configuration for an integration client.

func ConfigFromEnv

func ConfigFromEnv(serviceName string) Config

ConfigFromEnv creates a configuration from environment variables. It uses the service name as a prefix (e.g., GITHUB_BASE_URL, GITHUB_TIMEOUT).

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a default configuration.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration.

type ConfigBuilder

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

ConfigBuilder provides a fluent interface for building configurations.

func NewConfigBuilder

func NewConfigBuilder(serviceName string) *ConfigBuilder

NewConfigBuilder creates a new configuration builder.

func (*ConfigBuilder) APIKeyAuth

func (b *ConfigBuilder) APIKeyAuth(apiKey, header string) *ConfigBuilder

APIKeyAuth sets API key authentication.

func (*ConfigBuilder) BaseURL

func (b *ConfigBuilder) BaseURL(url string) *ConfigBuilder

BaseURL sets the base URL.

func (*ConfigBuilder) BasicAuth

func (b *ConfigBuilder) BasicAuth(username, password string) *ConfigBuilder

BasicAuth sets basic authentication.

func (*ConfigBuilder) BearerAuth

func (b *ConfigBuilder) BearerAuth(token string) *ConfigBuilder

BearerAuth sets bearer token authentication.

func (*ConfigBuilder) Build

func (b *ConfigBuilder) Build() Config

Build returns the built configuration.

func (*ConfigBuilder) CircuitBreakerHalfOpenRequests

func (b *ConfigBuilder) CircuitBreakerHalfOpenRequests(requests int) *ConfigBuilder

CircuitBreakerHalfOpenRequests sets the number of half-open requests.

func (*ConfigBuilder) CircuitBreakerThreshold

func (b *ConfigBuilder) CircuitBreakerThreshold(threshold int) *ConfigBuilder

CircuitBreakerThreshold sets the circuit breaker failure threshold.

func (*ConfigBuilder) CircuitBreakerTimeout

func (b *ConfigBuilder) CircuitBreakerTimeout(timeout time.Duration) *ConfigBuilder

CircuitBreakerTimeout sets the circuit breaker timeout.

func (*ConfigBuilder) ConnectTimeout

func (b *ConfigBuilder) ConnectTimeout(timeout time.Duration) *ConfigBuilder

ConnectTimeout sets the connection timeout.

func (*ConfigBuilder) EnableLogging

func (b *ConfigBuilder) EnableLogging(enable bool) *ConfigBuilder

EnableLogging enables or disables request/response logging.

func (*ConfigBuilder) EnableMetrics

func (b *ConfigBuilder) EnableMetrics(enable bool) *ConfigBuilder

EnableMetrics enables or disables metrics collection.

func (*ConfigBuilder) Header

func (b *ConfigBuilder) Header(key, value string) *ConfigBuilder

Header adds a default header.

func (*ConfigBuilder) Headers

func (b *ConfigBuilder) Headers(headers map[string]string) *ConfigBuilder

Headers sets multiple default headers.

func (*ConfigBuilder) MaxRetries

func (b *ConfigBuilder) MaxRetries(attempts int) *ConfigBuilder

MaxRetries sets the maximum number of retry attempts.

func (*ConfigBuilder) MaxRetryDelay

func (b *ConfigBuilder) MaxRetryDelay(delay time.Duration) *ConfigBuilder

MaxRetryDelay sets the maximum retry delay.

func (*ConfigBuilder) OAuth2Auth

func (b *ConfigBuilder) OAuth2Auth(config *OAuth2Config) *ConfigBuilder

OAuth2Auth sets OAuth2 authentication.

func (*ConfigBuilder) ReadTimeout

func (b *ConfigBuilder) ReadTimeout(timeout time.Duration) *ConfigBuilder

ReadTimeout sets the read timeout.

func (*ConfigBuilder) RedactFields

func (b *ConfigBuilder) RedactFields(fields ...string) *ConfigBuilder

RedactFields sets the fields to redact in logs.

func (*ConfigBuilder) RetryDelay

func (b *ConfigBuilder) RetryDelay(delay time.Duration) *ConfigBuilder

RetryDelay sets the initial retry delay.

func (*ConfigBuilder) RetryJitter

func (b *ConfigBuilder) RetryJitter(jitter float64) *ConfigBuilder

RetryJitter sets the retry jitter percentage.

func (*ConfigBuilder) RetryMultiplier

func (b *ConfigBuilder) RetryMultiplier(multiplier float64) *ConfigBuilder

RetryMultiplier sets the retry delay multiplier.

func (*ConfigBuilder) Timeout

func (b *ConfigBuilder) Timeout(timeout time.Duration) *ConfigBuilder

Timeout sets the default timeout.

func (*ConfigBuilder) UserAgent

func (b *ConfigBuilder) UserAgent(userAgent string) *ConfigBuilder

UserAgent sets the User-Agent header value.

func (*ConfigBuilder) WriteTimeout

func (b *ConfigBuilder) WriteTimeout(timeout time.Duration) *ConfigBuilder

WriteTimeout sets the write timeout.

type ConfigError

type ConfigError struct {
	Field   string
	Message string
}

ConfigError represents a configuration error.

func (*ConfigError) Error

func (e *ConfigError) Error() string

Error implements the error interface.

type HTTPError

type HTTPError struct {
	StatusCode int
	Message    string
	Body       []byte
}

HTTPError represents an HTTP error with status code.

func NewHTTPError

func NewHTTPError(statusCode int, message string) *HTTPError

NewHTTPError creates a new HTTP error.

func NewHTTPErrorWithBody

func NewHTTPErrorWithBody(statusCode int, message string, body []byte) *HTTPError

NewHTTPErrorWithBody creates a new HTTP error with response body.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error implements the error interface.

type OAuth2Config

type OAuth2Config struct {
	// ClientID is the OAuth2 client ID.
	ClientID string

	// ClientSecret is the OAuth2 client secret.
	ClientSecret string

	// TokenURL is the URL to obtain access tokens.
	TokenURL string

	// Scopes are the OAuth2 scopes.
	Scopes []string

	// Token is the current access token.
	Token string

	// RefreshToken is the refresh token.
	RefreshToken string

	// TokenExpiry is when the token expires.
	TokenExpiry time.Time
}

OAuth2Config configures OAuth2 authentication.

type RetryConfig

type RetryConfig struct {
	// MaxAttempts is the maximum number of attempts (including the first one).
	// Default: 3
	MaxAttempts int

	// BaseDelay is the initial delay between retries.
	// Default: 100ms
	BaseDelay time.Duration

	// MaxDelay is the maximum delay between retries.
	// Default: 30s
	MaxDelay time.Duration

	// Multiplier is the factor by which the delay increases.
	// Default: 2.0
	Multiplier float64

	// Jitter adds randomness to delays to prevent thundering herd.
	// Value between 0 and 1 representing the percentage of jitter (e.g., 0.25 = ±25%).
	// Default: 0.25
	Jitter float64

	// RetryIf is a function that determines if an error should be retried.
	// If nil, uses the default retryable check.
	RetryIf func(err error) bool

	// OnRetry is called before each retry attempt.
	OnRetry func(attempt int, err error, delay time.Duration)
}

RetryConfig configures the retry behavior.

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns the default retry configuration.

type Retryer

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

Retryer implements retry logic with exponential backoff.

func NewRetryer

func NewRetryer(config RetryConfig) *Retryer

NewRetryer creates a new retryer with the given configuration.

func (*Retryer) Do

func (r *Retryer) Do(ctx context.Context, fn func(context.Context) error) error

Do executes the function with retry logic.

func (*Retryer) WithService

func (r *Retryer) WithService(serviceName, endpoint string) *Retryer

WithService returns a new retryer configured for a specific service and endpoint.

type TimeoutConfig

type TimeoutConfig struct {
	// Default is the default timeout for operations.
	// Default: 30s
	Default time.Duration

	// Connect is the timeout for establishing connections.
	// Default: 10s
	Connect time.Duration

	// Read is the timeout for reading response.
	// Default: 30s
	Read time.Duration

	// Write is the timeout for writing request.
	// Default: 30s
	Write time.Duration

	// OnTimeout is called when a timeout occurs.
	OnTimeout func(operation string, timeout time.Duration)
}

TimeoutConfig configures timeout behavior.

func DefaultTimeoutConfig

func DefaultTimeoutConfig() TimeoutConfig

DefaultTimeoutConfig returns the default timeout configuration.

type TimeoutContext

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

TimeoutContext wraps a context with timeout tracking.

func NewTimeoutContext

func NewTimeoutContext(ctx context.Context, timeout time.Duration) *TimeoutContext

NewTimeoutContext creates a new timeout context.

func (*TimeoutContext) Cancel

func (tc *TimeoutContext) Cancel()

Cancel cancels the context.

func (*TimeoutContext) Context

func (tc *TimeoutContext) Context() context.Context

Context returns the underlying context.

func (*TimeoutContext) Elapsed

func (tc *TimeoutContext) Elapsed() time.Duration

Elapsed returns the time elapsed since the context was created.

func (*TimeoutContext) Extend

func (tc *TimeoutContext) Extend(additional time.Duration) *TimeoutContext

Extend extends the timeout by the specified duration. Note: This creates a new context with a new deadline.

func (*TimeoutContext) IsExpired

func (tc *TimeoutContext) IsExpired() bool

IsExpired returns true if the context has expired.

func (*TimeoutContext) Remaining

func (tc *TimeoutContext) Remaining() time.Duration

Remaining returns the remaining time before timeout.

type TimeoutManager

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

TimeoutManager manages timeouts for operations.

func NewTimeoutManager

func NewTimeoutManager(config TimeoutConfig) *TimeoutManager

NewTimeoutManager creates a new timeout manager.

func (*TimeoutManager) Config

func (tm *TimeoutManager) Config() TimeoutConfig

Config returns the timeout configuration.

func (*TimeoutManager) Execute

func (tm *TimeoutManager) Execute(ctx context.Context, timeout time.Duration, operation string, fn func(context.Context) error) error

Execute runs a function with the specified timeout.

func (*TimeoutManager) WithDefaultTimeout

func (tm *TimeoutManager) WithDefaultTimeout(ctx context.Context) (context.Context, context.CancelFunc)

WithDefaultTimeout creates a context with the default timeout.

func (*TimeoutManager) WithService

func (tm *TimeoutManager) WithService(serviceName, endpoint string) *TimeoutManager

WithService returns a new timeout manager configured for a specific service.

func (*TimeoutManager) WithTimeout

func (tm *TimeoutManager) WithTimeout(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc)

WithTimeout creates a context with the specified timeout. If the parent context has a tighter deadline, that deadline is preserved.

Directories

Path Synopsis
Package brevo provides a client for the Brevo (Sendinblue) transactional email API.
Package brevo provides a client for the Brevo (Sendinblue) transactional email API.
Package graphql provides a GraphQL client with resilience patterns.
Package graphql provides a GraphQL client with resilience patterns.
Package redis provides a Redis client wrapper for the scheduler.
Package redis provides a Redis client wrapper for the scheduler.
Package rest provides a REST client with resilience patterns.
Package rest provides a REST client with resilience patterns.
Package temporal provides Temporal client integration utilities.
Package temporal provides Temporal client integration utilities.
Package webhook provides HTTP webhook client and types for external integrations.
Package webhook provides HTTP webhook client and types for external integrations.

Jump to

Keyboard shortcuts

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