Documentation
¶
Overview ¶
Package clients provides circuit breaker implementation for HTTP clients
Package clients provides connection pool management for HTTP clients ¶
Package clients provides high-performance HTTP client implementations ¶
Package clients provides HTTP metrics tracking ¶
Package clients provides OAuth2 authentication support ¶
Package clients provides rate limiting implementations
Index ¶
- type AdaptiveRateLimiter
- func (ar *AdaptiveRateLimiter) Allow() bool
- func (ar *AdaptiveRateLimiter) GetStats() RateLimiterStats
- func (ar *AdaptiveRateLimiter) RecordResponse(latency time.Duration, success bool)
- func (ar *AdaptiveRateLimiter) Reserve() Reservation
- func (ar *AdaptiveRateLimiter) SetBurst(burst int)
- func (ar *AdaptiveRateLimiter) SetRate(rate float64)
- func (ar *AdaptiveRateLimiter) Wait(ctx context.Context) error
- type CircuitBreaker
- type CircuitBreakerConfig
- type CircuitBreakerState
- type CircuitState
- type ConnectionPool
- type ConnectionPoolStats
- type DistributedRateLimiter
- func (dr *DistributedRateLimiter) Allow() bool
- func (dr *DistributedRateLimiter) GetStats() RateLimiterStats
- func (dr *DistributedRateLimiter) Reserve() Reservation
- func (dr *DistributedRateLimiter) SetBurst(burst int)
- func (dr *DistributedRateLimiter) SetRate(rate float64)
- func (dr *DistributedRateLimiter) Wait(ctx context.Context) error
- type EndpointMetrics
- type HTTP2Stats
- type HTTPCircuitBreaker
- type HTTPClient
- func (c *HTTPClient) Close() error
- func (c *HTTPClient) Delete(ctx context.Context, url string, headers map[string]string) (*http.Response, error)
- func (c *HTTPClient) Do(req *http.Request) (*http.Response, error)
- func (c *HTTPClient) Get(ctx context.Context, url string, headers map[string]string) (*http.Response, error)
- func (c *HTTPClient) GetStats() HTTPStats
- func (c *HTTPClient) Post(ctx context.Context, url string, body io.Reader, headers map[string]string) (*http.Response, error)
- func (c *HTTPClient) Put(ctx context.Context, url string, body io.Reader, headers map[string]string) (*http.Response, error)
- type HTTPConfig
- type HTTPMetrics
- func (hm *HTTPMetrics) GetAverageLatency() time.Duration
- func (hm *HTTPMetrics) GetConnectionReuseRate() float64
- func (hm *HTTPMetrics) GetEndpointMetrics(method, host string) EndpointMetrics
- func (hm *HTTPMetrics) GetErrorStats() map[string]int64
- func (hm *HTTPMetrics) GetHTTP2Stats() HTTP2Stats
- func (hm *HTTPMetrics) GetP95Latency() time.Duration
- func (hm *HTTPMetrics) GetP99Latency() time.Duration
- func (hm *HTTPMetrics) GetRequestRate() float64
- func (hm *HTTPMetrics) RecordConnectionReuse(reused bool)
- func (hm *HTTPMetrics) RecordHTTP2Usage(streams int)
- func (hm *HTTPMetrics) RecordRequest(method, host string, latency time.Duration, err error)
- func (hm *HTTPMetrics) Reset()
- type HTTPStats
- type LatencyBucket
- type OAuth2Client
- func (oc *OAuth2Client) ExchangeCode(ctx context.Context, code string) (*Token, error)
- func (oc *OAuth2Client) GetAuthorizationURL(state string) string
- func (oc *OAuth2Client) GetClientCredentialsToken(ctx context.Context) (*Token, error)
- func (oc *OAuth2Client) GetStats() OAuth2Stats
- func (oc *OAuth2Client) GetToken(ctx context.Context) (*Token, error)
- func (oc *OAuth2Client) OnTokenRefresh(callback func(*Token))
- func (oc *OAuth2Client) RefreshToken(ctx context.Context, refreshToken string) (*Token, error)
- func (oc *OAuth2Client) SetToken(token *Token)
- type OAuth2Config
- type OAuth2Error
- type OAuth2Stats
- type PooledConnection
- type PooledRequest
- type PooledResponse
- type RateLimiter
- type RateLimiterCoordinator
- type RateLimiterStats
- type Reservation
- type ResponseTimeStats
- type ResponseTimeWindow
- type SlidingWindow
- type Token
- type TokenBucketRateLimiter
- func (tb *TokenBucketRateLimiter) Allow() bool
- func (tb *TokenBucketRateLimiter) GetStats() RateLimiterStats
- func (tb *TokenBucketRateLimiter) Reserve() Reservation
- func (tb *TokenBucketRateLimiter) SetBurst(burst int)
- func (tb *TokenBucketRateLimiter) SetRate(rate float64)
- func (tb *TokenBucketRateLimiter) Wait(ctx context.Context) error
- type TokenManager
- type WindowStats
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AdaptiveRateLimiter ¶
type AdaptiveRateLimiter struct {
// contains filtered or unexported fields
}
AdaptiveRateLimiter adjusts rate based on response times and errors
func NewAdaptiveRateLimiter ¶
func NewAdaptiveRateLimiter(baseRate float64, burst int) *AdaptiveRateLimiter
NewAdaptiveRateLimiter creates a new adaptive rate limiter
func (*AdaptiveRateLimiter) Allow ¶
func (ar *AdaptiveRateLimiter) Allow() bool
Allow checks if a request is allowed
func (*AdaptiveRateLimiter) GetStats ¶
func (ar *AdaptiveRateLimiter) GetStats() RateLimiterStats
GetStats returns rate limiter statistics
func (*AdaptiveRateLimiter) RecordResponse ¶
func (ar *AdaptiveRateLimiter) RecordResponse(latency time.Duration, success bool)
RecordResponse records a response for adaptation
func (*AdaptiveRateLimiter) Reserve ¶
func (ar *AdaptiveRateLimiter) Reserve() Reservation
Reserve reserves a future request
func (*AdaptiveRateLimiter) SetBurst ¶
func (ar *AdaptiveRateLimiter) SetBurst(burst int)
SetBurst updates the burst size
func (*AdaptiveRateLimiter) SetRate ¶
func (ar *AdaptiveRateLimiter) SetRate(rate float64)
SetRate updates the base rate
type CircuitBreaker ¶
type CircuitBreaker = HTTPCircuitBreaker
CircuitBreaker is an alias for HTTPCircuitBreaker for backward compatibility
func NewCircuitBreaker ¶
func NewCircuitBreaker(config CircuitBreakerConfig) *CircuitBreaker
NewCircuitBreaker creates a new circuit breaker
type CircuitBreakerConfig ¶
type CircuitBreakerConfig struct {
FailureThreshold int // Number of failures before opening
SuccessThreshold int // Number of successes before closing
Timeout time.Duration // Timeout before retrying
}
CircuitBreakerConfig is the configuration for circuit breaker
type CircuitBreakerState ¶
type CircuitBreakerState struct {
State string `json:"state"`
LastStateChange time.Time `json:"last_state_change"`
ConsecutiveFailures int32 `json:"consecutive_failures"`
ConsecutiveSuccesses int32 `json:"consecutive_successes"`
TotalRequests int64 `json:"total_requests"`
FailedRequests int64 `json:"failed_requests"`
FailureRate float64 `json:"failure_rate"`
NextRetryTime time.Time `json:"next_retry_time,omitempty"`
}
CircuitBreakerState represents the circuit breaker state
type CircuitState ¶
type CircuitState int32
CircuitState represents the circuit breaker state
const ( StateClosed CircuitState = iota StateOpen StateHalfOpen )
type ConnectionPool ¶
type ConnectionPool struct {
// contains filtered or unexported fields
}
ConnectionPool manages HTTP connection pooling with advanced features
func NewConnectionPool ¶
func NewConnectionPool(config *HTTPConfig, logger *zap.Logger) *ConnectionPool
NewConnectionPool creates a new connection pool
func (*ConnectionPool) Close ¶
func (cp *ConnectionPool) Close()
Close closes all connections in the pool
func (*ConnectionPool) Get ¶
func (cp *ConnectionPool) Get(host string) (*PooledConnection, error)
Get retrieves a connection from the pool or creates a new one
func (*ConnectionPool) GetStats ¶
func (cp *ConnectionPool) GetStats() ConnectionPoolStats
GetStats returns connection pool statistics
func (*ConnectionPool) MarkUnhealthy ¶
func (cp *ConnectionPool) MarkUnhealthy(conn *PooledConnection)
MarkUnhealthy marks a connection as unhealthy
func (*ConnectionPool) Put ¶
func (cp *ConnectionPool) Put(conn *PooledConnection)
Put returns a connection to the pool
type ConnectionPoolStats ¶
type ConnectionPoolStats struct {
ActiveConnections int64 `json:"active_connections"`
IdleConnections int64 `json:"idle_connections"`
TotalConnections int64 `json:"total_connections"`
TotalCreated int64 `json:"total_created"`
TotalReused int64 `json:"total_reused"`
ReuseRate float64 `json:"reuse_rate"`
AverageUseCount float64 `json:"average_use_count"`
OldestConnection time.Duration `json:"oldest_connection_age"`
}
ConnectionPoolStats represents connection pool statistics
type DistributedRateLimiter ¶
type DistributedRateLimiter struct {
// contains filtered or unexported fields
}
DistributedRateLimiter provides distributed rate limiting
func NewDistributedRateLimiter ¶
func NewDistributedRateLimiter(nodeID string, globalRate float64, coordinator RateLimiterCoordinator) (*DistributedRateLimiter, error)
NewDistributedRateLimiter creates a new distributed rate limiter
func (*DistributedRateLimiter) Allow ¶
func (dr *DistributedRateLimiter) Allow() bool
Allow checks if a request is allowed
func (*DistributedRateLimiter) GetStats ¶
func (dr *DistributedRateLimiter) GetStats() RateLimiterStats
GetStats returns rate limiter statistics
func (*DistributedRateLimiter) Reserve ¶
func (dr *DistributedRateLimiter) Reserve() Reservation
Reserve reserves a future request
func (*DistributedRateLimiter) SetBurst ¶
func (dr *DistributedRateLimiter) SetBurst(burst int)
SetBurst updates the burst size
func (*DistributedRateLimiter) SetRate ¶
func (dr *DistributedRateLimiter) SetRate(rate float64)
SetRate updates the global rate
type EndpointMetrics ¶
type EndpointMetrics struct {
Host string `json:"host"`
Method string `json:"method"`
RequestCount int64 `json:"request_count"`
AverageLatency time.Duration `json:"average_latency"`
MinLatency time.Duration `json:"min_latency"`
MaxLatency time.Duration `json:"max_latency"`
}
EndpointMetrics represents metrics for a specific endpoint
type HTTP2Stats ¶
type HTTP2Stats struct {
Connections int64 `json:"connections"`
TotalStreams int64 `json:"total_streams"`
StreamsPerConn float64 `json:"streams_per_conn"`
}
HTTP2Stats represents HTTP/2 usage statistics
type HTTPCircuitBreaker ¶
type HTTPCircuitBreaker struct {
// contains filtered or unexported fields
}
HTTPCircuitBreaker implements circuit breaker pattern for HTTP requests
func NewHTTPCircuitBreaker ¶
func NewHTTPCircuitBreaker(config *HTTPConfig, logger *zap.Logger) *HTTPCircuitBreaker
NewHTTPCircuitBreaker creates a new circuit breaker
func (*HTTPCircuitBreaker) Allow ¶
func (cb *HTTPCircuitBreaker) Allow() bool
Allow determines if a request should be allowed
func (*HTTPCircuitBreaker) Execute ¶
func (cb *HTTPCircuitBreaker) Execute(fn func() error) error
Execute runs a function with circuit breaker protection
func (*HTTPCircuitBreaker) GetState ¶
func (cb *HTTPCircuitBreaker) GetState() CircuitBreakerState
GetState returns the current circuit breaker state
func (*HTTPCircuitBreaker) RecordFailure ¶
func (cb *HTTPCircuitBreaker) RecordFailure()
RecordFailure records a failed request
func (*HTTPCircuitBreaker) RecordSuccess ¶
func (cb *HTTPCircuitBreaker) RecordSuccess()
RecordSuccess records a successful request
type HTTPClient ¶
type HTTPClient struct {
// contains filtered or unexported fields
}
HTTPClient provides a high-performance HTTP client with connection pooling
func NewHTTPClient ¶
func NewHTTPClient(config *HTTPConfig, logger *zap.Logger) *HTTPClient
NewHTTPClient creates a new high-performance HTTP client
func (*HTTPClient) Close ¶
func (c *HTTPClient) Close() error
Close closes the HTTP client and releases resources
func (*HTTPClient) Delete ¶
func (c *HTTPClient) Delete(ctx context.Context, url string, headers map[string]string) (*http.Response, error)
Delete performs an HTTP DELETE request
func (*HTTPClient) Get ¶
func (c *HTTPClient) Get(ctx context.Context, url string, headers map[string]string) (*http.Response, error)
Get performs an HTTP GET request
func (*HTTPClient) GetStats ¶
func (c *HTTPClient) GetStats() HTTPStats
GetStats returns current client statistics
type HTTPConfig ¶
type HTTPConfig struct {
// Connection settings
MaxIdleConns int `json:"max_idle_conns"`
MaxIdleConnsPerHost int `json:"max_idle_conns_per_host"`
MaxConnsPerHost int `json:"max_conns_per_host"`
IdleConnTimeout time.Duration `json:"idle_conn_timeout"`
DisableKeepAlives bool `json:"disable_keep_alives"`
DisableCompression bool `json:"disable_compression"`
// HTTP/2 settings
EnableHTTP2 bool `json:"enable_http2"`
MaxConcurrentStreams int `json:"max_concurrent_streams"`
// Timeouts
DialTimeout time.Duration `json:"dial_timeout"`
TLSHandshakeTimeout time.Duration `json:"tls_handshake_timeout"`
ResponseHeaderTimeout time.Duration `json:"response_header_timeout"`
RequestTimeout time.Duration `json:"request_timeout"`
KeepAlive time.Duration `json:"keep_alive"`
// TLS settings
InsecureSkipVerify bool `json:"insecure_skip_verify"`
TLSMinVersion uint16 `json:"tls_min_version"`
// Performance settings
EnableConnectionReuse bool `json:"enable_connection_reuse"`
EnableRequestPooling bool `json:"enable_request_pooling"`
RequestPoolSize int `json:"request_pool_size"`
// Rate limiting
RateLimit float64 `json:"rate_limit"`
RateBurst int `json:"rate_burst"`
// Circuit breaker
CircuitBreakerEnabled bool `json:"circuit_breaker_enabled"`
FailureThreshold int `json:"failure_threshold"`
SuccessThreshold int `json:"success_threshold"`
Timeout time.Duration `json:"timeout"`
}
HTTPConfig configures the HTTP client
func DefaultHTTPConfig ¶
func DefaultHTTPConfig() *HTTPConfig
DefaultHTTPConfig returns optimized default configuration
type HTTPMetrics ¶
type HTTPMetrics struct {
// contains filtered or unexported fields
}
HTTPMetrics tracks HTTP client performance metrics
func NewHTTPMetrics ¶
func NewHTTPMetrics() *HTTPMetrics
NewHTTPMetrics creates a new HTTP metrics tracker
func (*HTTPMetrics) GetAverageLatency ¶
func (hm *HTTPMetrics) GetAverageLatency() time.Duration
GetAverageLatency returns the average latency
func (*HTTPMetrics) GetConnectionReuseRate ¶
func (hm *HTTPMetrics) GetConnectionReuseRate() float64
GetConnectionReuseRate returns the connection reuse rate
func (*HTTPMetrics) GetEndpointMetrics ¶
func (hm *HTTPMetrics) GetEndpointMetrics(method, host string) EndpointMetrics
GetEndpointMetrics returns metrics for a specific endpoint
func (*HTTPMetrics) GetErrorStats ¶
func (hm *HTTPMetrics) GetErrorStats() map[string]int64
GetErrorStats returns error statistics
func (*HTTPMetrics) GetHTTP2Stats ¶
func (hm *HTTPMetrics) GetHTTP2Stats() HTTP2Stats
GetHTTP2Stats returns HTTP/2 usage statistics
func (*HTTPMetrics) GetP95Latency ¶
func (hm *HTTPMetrics) GetP95Latency() time.Duration
GetP95Latency returns the 95th percentile latency
func (*HTTPMetrics) GetP99Latency ¶
func (hm *HTTPMetrics) GetP99Latency() time.Duration
GetP99Latency returns the 99th percentile latency
func (*HTTPMetrics) GetRequestRate ¶
func (hm *HTTPMetrics) GetRequestRate() float64
GetRequestRate returns the current request rate per second
func (*HTTPMetrics) RecordConnectionReuse ¶
func (hm *HTTPMetrics) RecordConnectionReuse(reused bool)
RecordConnectionReuse records connection reuse metrics
func (*HTTPMetrics) RecordHTTP2Usage ¶
func (hm *HTTPMetrics) RecordHTTP2Usage(streams int)
RecordHTTP2Usage records HTTP/2 connection usage
func (*HTTPMetrics) RecordRequest ¶
func (hm *HTTPMetrics) RecordRequest(method, host string, latency time.Duration, err error)
RecordRequest records a request and its outcome
type HTTPStats ¶
type HTTPStats struct {
ActiveConnections int64 `json:"active_connections"`
IdleConnections int64 `json:"idle_connections"`
TotalConnections int64 `json:"total_connections"`
TotalRequests int64 `json:"total_requests"`
FailedRequests int64 `json:"failed_requests"`
SuccessRate float64 `json:"success_rate"`
ConnectionReuse float64 `json:"connection_reuse_rate"`
AverageLatency time.Duration `json:"average_latency"`
P95Latency time.Duration `json:"p95_latency"`
P99Latency time.Duration `json:"p99_latency"`
}
HTTPStats represents HTTP client statistics
type LatencyBucket ¶
type LatencyBucket struct {
// contains filtered or unexported fields
}
LatencyBucket tracks latency for specific endpoints
type OAuth2Client ¶
type OAuth2Client struct {
// contains filtered or unexported fields
}
OAuth2Client provides OAuth2 authentication functionality
func NewOAuth2Client ¶
func NewOAuth2Client(config *OAuth2Config, httpClient *HTTPClient, logger *zap.Logger) *OAuth2Client
NewOAuth2Client creates a new OAuth2 client
func (*OAuth2Client) ExchangeCode ¶
ExchangeCode exchanges an authorization code for an access token
func (*OAuth2Client) GetAuthorizationURL ¶
func (oc *OAuth2Client) GetAuthorizationURL(state string) string
GetAuthorizationURL returns the authorization URL for the OAuth2 flow
func (*OAuth2Client) GetClientCredentialsToken ¶
func (oc *OAuth2Client) GetClientCredentialsToken(ctx context.Context) (*Token, error)
GetClientCredentialsToken gets a token using client credentials grant
func (*OAuth2Client) GetStats ¶
func (oc *OAuth2Client) GetStats() OAuth2Stats
GetStats returns OAuth2 client statistics
func (*OAuth2Client) GetToken ¶
func (oc *OAuth2Client) GetToken(ctx context.Context) (*Token, error)
GetToken returns a valid access token, refreshing if necessary
func (*OAuth2Client) OnTokenRefresh ¶
func (oc *OAuth2Client) OnTokenRefresh(callback func(*Token))
OnTokenRefresh sets a callback for token refresh events
func (*OAuth2Client) RefreshToken ¶
RefreshToken refreshes an access token using a refresh token
func (*OAuth2Client) SetToken ¶
func (oc *OAuth2Client) SetToken(token *Token)
SetToken manually sets a token
type OAuth2Config ¶
type OAuth2Config struct {
// Client credentials
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
RedirectURL string `json:"redirect_url,omitempty"`
// Token endpoints
AuthURL string `json:"auth_url"`
TokenURL string `json:"token_url"`
RefreshURL string `json:"refresh_url,omitempty"`
// Scopes
Scopes []string `json:"scopes"`
// Grant type
GrantType string `json:"grant_type"` // authorization_code, client_credentials, refresh_token
// Token settings
AutoRefresh bool `json:"auto_refresh"`
RefreshThreshold time.Duration `json:"refresh_threshold"`
MaxRetries int `json:"max_retries"`
RetryDelay time.Duration `json:"retry_delay"`
// Advanced settings
UseBasicAuth bool `json:"use_basic_auth"`
CustomHeaders map[string]string `json:"custom_headers,omitempty"`
CustomParams map[string]string `json:"custom_params,omitempty"`
}
OAuth2Config configures OAuth2 authentication
type OAuth2Error ¶
type OAuth2Error struct {
ErrorCode string `json:"error"`
ErrorDescription string `json:"error_description,omitempty"`
ErrorURI string `json:"error_uri,omitempty"`
}
OAuth2Error represents an OAuth2 error response
func (*OAuth2Error) Error ¶
func (e *OAuth2Error) Error() string
type OAuth2Stats ¶
type OAuth2Stats struct {
TokenRequests int64 `json:"token_requests"`
TokenRefreshes int64 `json:"token_refreshes"`
AuthFailures int64 `json:"auth_failures"`
CurrentTokenValid bool `json:"current_token_valid"`
}
OAuth2Stats represents OAuth2 client statistics
type PooledConnection ¶
type PooledConnection struct {
// contains filtered or unexported fields
}
PooledConnection represents a pooled HTTP connection
type PooledRequest ¶
PooledRequest represents a pooled HTTP request
func (*PooledRequest) Reset ¶
func (pr *PooledRequest) Reset()
Reset resets the pooled request for reuse
type PooledResponse ¶
type PooledResponse struct {
StatusCode int
Headers http.Header
Body io.ReadCloser
// contains filtered or unexported fields
}
PooledResponse represents a pooled HTTP response
func (*PooledResponse) Reset ¶
func (pr *PooledResponse) Reset()
Reset resets the pooled response for reuse
type RateLimiter ¶
type RateLimiter interface {
// Allow checks if a request is allowed
Allow() bool
// Wait blocks until a request is allowed
Wait(ctx context.Context) error
// Reserve reserves a future request
Reserve() Reservation
// SetRate updates the rate limit
SetRate(rate float64)
// SetBurst updates the burst size
SetBurst(burst int)
// GetStats returns rate limiter statistics
GetStats() RateLimiterStats
}
RateLimiter defines the interface for rate limiting
func NewRateLimiter ¶
func NewRateLimiter(rate int, burst int) RateLimiter
NewRateLimiter creates a new rate limiter with the specified rate and burst
type RateLimiterCoordinator ¶
type RateLimiterCoordinator interface {
// RegisterNode registers a node in the cluster
RegisterNode(nodeID string) error
// GetNodeCount returns the current number of nodes
GetNodeCount() (int, error)
// ReportUsage reports usage statistics
ReportUsage(nodeID string, used int64, timestamp time.Time) error
// GetGlobalUsage returns global usage statistics
GetGlobalUsage() (int64, error)
}
RateLimiterCoordinator coordinates distributed rate limiting
type RateLimiterStats ¶
type RateLimiterStats struct {
Rate float64 `json:"rate"`
Burst int `json:"burst"`
AllowedRequests int64 `json:"allowed_requests"`
BlockedRequests int64 `json:"blocked_requests"`
CurrentTokens float64 `json:"current_tokens"`
LastRefill time.Time `json:"last_refill"`
AverageWaitTime time.Duration `json:"average_wait_time"`
}
RateLimiterStats represents rate limiter statistics
type Reservation ¶
type Reservation interface {
// OK returns whether the reservation is valid
OK() bool
// Delay returns the delay before the request can proceed
Delay() time.Duration
// Cancel cancels the reservation
Cancel()
}
Reservation represents a rate limiter reservation
type ResponseTimeStats ¶
type ResponseTimeStats struct {
Count int `json:"count"`
ErrorRate float64 `json:"error_rate"`
P95Latency time.Duration `json:"p95_latency"`
P99Latency time.Duration `json:"p99_latency"`
MeanLatency time.Duration `json:"mean_latency"`
}
ResponseTimeStats represents response time statistics
type ResponseTimeWindow ¶
type ResponseTimeWindow struct {
// contains filtered or unexported fields
}
ResponseTimeWindow tracks response times in a sliding window
func NewResponseTimeWindow ¶
func NewResponseTimeWindow(duration time.Duration) *ResponseTimeWindow
NewResponseTimeWindow creates a new response time window
func (*ResponseTimeWindow) GetStats ¶
func (rtw *ResponseTimeWindow) GetStats() ResponseTimeStats
GetStats returns window statistics
type SlidingWindow ¶
type SlidingWindow struct {
// contains filtered or unexported fields
}
SlidingWindow tracks requests in a time window
func NewSlidingWindow ¶
func NewSlidingWindow(bucketSize, windowSize time.Duration) *SlidingWindow
NewSlidingWindow creates a new sliding window
func (*SlidingWindow) GetFailureRate ¶
func (sw *SlidingWindow) GetFailureRate() float64
GetFailureRate returns the current failure rate
func (*SlidingWindow) GetStats ¶
func (sw *SlidingWindow) GetStats() WindowStats
GetStats returns window statistics
func (*SlidingWindow) RecordRequest ¶
func (sw *SlidingWindow) RecordRequest(success bool)
RecordRequest records a request in the sliding window
type Token ¶
type Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
RefreshToken string `json:"refresh_token,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
Scopes []string `json:"scopes,omitempty"`
// Additional fields
IDToken string `json:"id_token,omitempty"`
Extra map[string]interface{} `json:"extra,omitempty"`
}
Token represents an OAuth2 access token
type TokenBucketRateLimiter ¶
type TokenBucketRateLimiter struct {
// contains filtered or unexported fields
}
TokenBucketRateLimiter implements token bucket algorithm
func NewTokenBucketRateLimiter ¶
func NewTokenBucketRateLimiter(rate float64, burst int) *TokenBucketRateLimiter
NewTokenBucketRateLimiter creates a new token bucket rate limiter
func (*TokenBucketRateLimiter) Allow ¶
func (tb *TokenBucketRateLimiter) Allow() bool
Allow checks if a request is allowed
func (*TokenBucketRateLimiter) GetStats ¶
func (tb *TokenBucketRateLimiter) GetStats() RateLimiterStats
GetStats returns rate limiter statistics
func (*TokenBucketRateLimiter) Reserve ¶
func (tb *TokenBucketRateLimiter) Reserve() Reservation
Reserve reserves a future request
func (*TokenBucketRateLimiter) SetBurst ¶
func (tb *TokenBucketRateLimiter) SetBurst(burst int)
SetBurst updates the burst size
func (*TokenBucketRateLimiter) SetRate ¶
func (tb *TokenBucketRateLimiter) SetRate(rate float64)
SetRate updates the rate limit
type TokenManager ¶
type TokenManager struct {
// contains filtered or unexported fields
}
TokenManager manages OAuth2 tokens with automatic refresh
func (*TokenManager) GetToken ¶
func (tm *TokenManager) GetToken(ctx context.Context) (*Token, error)
GetToken returns a valid token, refreshing if necessary
func (*TokenManager) IsTokenValid ¶
func (tm *TokenManager) IsTokenValid() bool
IsTokenValid checks if the current token is valid
func (*TokenManager) SetToken ¶
func (tm *TokenManager) SetToken(token *Token)
SetToken sets the current token
type WindowStats ¶
type WindowStats struct {
TotalRequests int64 `json:"total_requests"`
FailedRequests int64 `json:"failed_requests"`
FailureRate float64 `json:"failure_rate"`
}
WindowStats represents sliding window statistics