webhook

package
v1.42.0 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2026 License: GPL-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCircuitOpen = errors.New("circuit breaker is open")
)
View Source
var (
	ErrRateLimitExceeded = errors.New("rate limit exceeded")
)

Functions

This section is empty.

Types

type CircuitBreaker

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

CircuitBreaker implements the circuit breaker pattern

func NewCircuitBreaker

func NewCircuitBreaker(failureThreshold, successThreshold int, timeout time.Duration) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker

func (*CircuitBreaker) Execute

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

Execute runs the function through the circuit breaker

func (*CircuitBreaker) GetState

func (cb *CircuitBreaker) GetState() CircuitBreakerState

GetState returns the current state (for monitoring/metrics)

func (*CircuitBreaker) GetStats

func (cb *CircuitBreaker) GetStats() (state CircuitBreakerState, failures, successes int)

GetStats returns current statistics

type CircuitBreakerState

type CircuitBreakerState int

CircuitBreakerState represents the current state of the circuit breaker

const (
	// StateClosed - circuit is closed, requests pass through
	StateClosed CircuitBreakerState = iota
	// StateOpen - circuit is open, requests fail immediately
	StateOpen
	// StateHalfOpen - circuit is half-open, testing if backend recovered
	StateHalfOpen
)

func (CircuitBreakerState) String

func (s CircuitBreakerState) String() string

String returns the state as a string

type DiscordFormatter

type DiscordFormatter struct{}

DiscordFormatter formats messages for Discord using native embed structure: author / title / description / inline fields / footer.

func (*DiscordFormatter) Format

func (f *DiscordFormatter) Format(ctx SendContext, statusInfo config.StatusInfo) (interface{}, error)

type Formatter

type Formatter interface {
	Format(ctx SendContext, statusInfo config.StatusInfo) (interface{}, error)
}

Formatter renders a SendContext into a preset-specific webhook payload.

Implementations should treat ctx.Message as the pre-joined notification text and use the structured fields (RawBody, ActionSummary, SessionName, Folder, GitBranch) only when the underlying transport benefits from richer layouts.

type HTTPError

type HTTPError struct {
	StatusCode int
	Status     string
	Body       string
}

HTTPError represents an HTTP error response

func NewHTTPError

func NewHTTPError(resp *http.Response, body string) *HTTPError

NewHTTPError creates a new HTTPError from an HTTP response

func (*HTTPError) Error

func (e *HTTPError) Error() string

type LarkFormatter

type LarkFormatter struct{}

LarkFormatter formats messages for Feishu/Lark with interactive cards

func (*LarkFormatter) Format

func (f *LarkFormatter) Format(ctx SendContext, statusInfo config.StatusInfo) (interface{}, error)

type Metrics

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

Metrics tracks webhook statistics

func NewMetrics

func NewMetrics() *Metrics

NewMetrics creates a new metrics tracker

func (*Metrics) GetStats

func (m *Metrics) GetStats() Stats

GetStats returns current statistics

func (*Metrics) RecordCircuitOpen

func (m *Metrics) RecordCircuitOpen()

RecordCircuitOpen records a request blocked by circuit breaker

func (*Metrics) RecordFailure

func (m *Metrics) RecordFailure()

RecordFailure records a failed webhook delivery

func (*Metrics) RecordRateLimited

func (m *Metrics) RecordRateLimited()

RecordRateLimited records a rate-limited request

func (*Metrics) RecordRequest

func (m *Metrics) RecordRequest()

RecordRequest records a webhook request attempt

func (*Metrics) RecordRetry

func (m *Metrics) RecordRetry()

RecordRetry records a retry attempt

func (*Metrics) RecordSuccess

func (m *Metrics) RecordSuccess(status analyzer.Status, latency time.Duration)

RecordSuccess records a successful webhook delivery

func (*Metrics) Reset

func (m *Metrics) Reset()

Reset resets all metrics (useful for testing)

func (*Metrics) UpdateCircuitBreakerState

func (m *Metrics) UpdateCircuitBreakerState(state CircuitBreakerState)

UpdateCircuitBreakerState updates the circuit breaker state

type RateLimiter

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

RateLimiter implements token bucket rate limiting

func NewRateLimiter

func NewRateLimiter(requestsPerMinute int) *RateLimiter

NewRateLimiter creates a new rate limiter requestsPerMinute: maximum requests allowed per minute

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow() bool

Allow checks if a request is allowed under the rate limit Returns true if allowed, false if rate limit exceeded

func (*RateLimiter) GetStats

func (rl *RateLimiter) GetStats() (tokens float64, capacity int, rate float64)

GetStats returns current rate limiter stats

func (*RateLimiter) Wait

func (rl *RateLimiter) Wait(ctx context.Context) error

Wait blocks until a request is allowed (with context support) Returns error if context is cancelled

type RetryConfig

type RetryConfig struct {
	Enabled        bool
	MaxAttempts    int
	InitialBackoff time.Duration
	MaxBackoff     time.Duration
	Multiplier     float64
}

RetryConfig holds retry configuration

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns sensible defaults for retry

type RetryableFunc

type RetryableFunc func(ctx context.Context) error

RetryableFunc is a function that can be retried

type Retryer

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

Retryer handles retry logic with exponential backoff

func NewRetryer

func NewRetryer(config RetryConfig) *Retryer

NewRetryer creates a new Retryer

func (*Retryer) Do

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

Do executes the function with retry logic Returns error if all retries are exhausted

type SendContext

type SendContext struct {
	Status    analyzer.Status
	Message   string
	SessionID string
	CWD       string

	SessionName   string // friendly session label (e.g. "phoenix 439d1884")
	GitBranch     string // empty when CWD is not a git working tree
	Folder        string // filepath.Base(CWD); empty when CWD is empty
	RawBody       string // summary body without prefix/actions
	ActionSummary string // action segment only (e.g. "📝 1 new  ▶ 2 cmds  ⏱ 41s")
}

SendContext carries per-notification metadata used by webhook templates.

Message remains the pre-joined "[session|branch folder] body actions" string so existing ${{message}} templates and downstream consumers keep working. The structured fields below let formatters that render rich layouts (e.g. Discord embeds) avoid re-parsing the joined output.

type Sender

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

Sender sends webhook notifications with professional patterns

func New

func New(cfg *config.Config) *Sender

New creates a new professional webhook sender

func (*Sender) GetMetrics

func (s *Sender) GetMetrics() Stats

GetMetrics returns current metrics

func (*Sender) Send

func (s *Sender) Send(status analyzer.Status, message, sessionID string) error

Send sends a webhook notification with full professional stack.

func (*Sender) SendAsync

func (s *Sender) SendAsync(status analyzer.Status, message, sessionID string)

SendAsync sends a webhook asynchronously with graceful shutdown support.

func (*Sender) SendAsyncWithContext

func (s *Sender) SendAsyncWithContext(sendCtx SendContext)

SendAsyncWithContext sends a webhook asynchronously with optional runtime context.

func (*Sender) SendWithContext

func (s *Sender) SendWithContext(sendCtx SendContext) error

SendWithContext sends a webhook notification with optional runtime context.

func (*Sender) Shutdown

func (s *Sender) Shutdown(timeout time.Duration) error

Shutdown gracefully shuts down the webhook sender Waits for in-flight requests to complete (with timeout) Only cancels context if timeout is reached

type SlackFormatter

type SlackFormatter struct{}

SlackFormatter formats messages for Slack

func (*SlackFormatter) Format

func (f *SlackFormatter) Format(ctx SendContext, statusInfo config.StatusInfo) (interface{}, error)

type Stats

type Stats struct {
	TotalRequests       int64
	SuccessfulRequests  int64
	FailedRequests      int64
	RetriedRequests     int64
	RateLimitedRequests int64
	CircuitOpenRequests int64
	StatusCounts        map[analyzer.Status]int64
	AverageLatencyMs    int64
	CircuitBreakerState CircuitBreakerState
}

Stats represents a snapshot of metrics

func (*Stats) FailureRate

func (s *Stats) FailureRate() float64

FailureRate returns the failure rate as a percentage

func (*Stats) SuccessRate

func (s *Stats) SuccessRate() float64

SuccessRate returns the success rate as a percentage

type TelegramFormatter

type TelegramFormatter struct {
	ChatID string
}

TelegramFormatter formats messages for Telegram with HTML

func (*TelegramFormatter) Format

func (f *TelegramFormatter) Format(ctx SendContext, statusInfo config.StatusInfo) (interface{}, error)

Jump to

Keyboard shortcuts

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