webhook

package
v0.0.0-...-6a3e998 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2025 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultEventHandlers

func DefaultEventHandlers() map[string]HandlerFunc

DefaultEventHandlers returns a map of default event handlers

func JSONSchemas

func JSONSchemas() map[string][]byte

JSONSchemas returns a map of event types to JSON schemas

Types

type DefaultEventHandler

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

DefaultEventHandler implements a simple webhook handler

func NewDefaultEventHandler

func NewDefaultEventHandler(logger observability.Logger, metrics observability.MetricsClient) *DefaultEventHandler

NewDefaultEventHandler creates a new default webhook handler

func (*DefaultEventHandler) HandleEvent

func (h *DefaultEventHandler) HandleEvent(ctx context.Context, event *WebhookEvent) error

HandleEvent handles a webhook event

type DeliveryCache

type DeliveryCache interface {
	// Has checks if a delivery ID exists in the cache
	Has(deliveryID string) bool

	// Add adds a delivery ID to the cache
	Add(deliveryID string, timestamp time.Time) error

	// GC performs garbage collection on the cache
	GC() error
}

DeliveryCache defines the interface for caching delivery IDs

type Event

type Event struct {
	Type               string         // GitHub event type
	DeliveryID         string         // GitHub delivery ID
	Payload            map[string]any // Raw event payload
	RawPayload         []byte         // Raw JSON payload
	Headers            http.Header    // HTTP headers
	Action             string         // Action (e.g. "opened", "closed", "edited")
	RepositoryID       int64          // Repository ID
	RepositoryName     string         // Repository name
	RepositoryOwner    string         // Repository owner
	RepositoryFullName string         // Repository full name (owner/name)
	RefName            string         // Reference name (for push events)
	SenderLogin        string         // Sender login
	ReceivedAt         string         // Time when the event was received
}

Event represents a GitHub webhook event

func ParseEvent

func ParseEvent(eventType string, payload []byte, headers http.Header) (Event, error)

ParseEvent parses a webhook event from payload and headers

type Filter

type Filter struct {
	EventTypes   []string         // Event types to handle
	Repositories []string         // Repositories to handle
	Branches     []string         // Branches to handle
	Actions      []string         // Actions to handle
	Custom       func(Event) bool // Custom filter function
}

Filter represents a filter for webhook events

func (*Filter) Matches

func (f *Filter) Matches(event Event) bool

Matches checks if an event matches the filter

type Handler

type Handler struct {
	ID      string
	Handler HandlerFunc
	Filter  *Filter
}

Handler represents a webhook event handler

type HandlerFunc

type HandlerFunc func(ctx context.Context, event Event) error

HandlerFunc is a function that handles a webhook event

type IPRange

type IPRange struct {
	CIDR  string
	IPNet *net.IPNet
}

IPRange represents an IP address range

type InMemoryDeliveryCache

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

InMemoryDeliveryCache is a simple in-memory implementation of DeliveryCache

func NewInMemoryDeliveryCache

func NewInMemoryDeliveryCache(maxAge time.Duration) *InMemoryDeliveryCache

NewInMemoryDeliveryCache creates a new in-memory delivery cache

func (*InMemoryDeliveryCache) Add

func (c *InMemoryDeliveryCache) Add(deliveryID string, timestamp time.Time) error

Add adds a delivery ID to the cache

func (*InMemoryDeliveryCache) GC

func (c *InMemoryDeliveryCache) GC() error

GC performs garbage collection on the cache

func (*InMemoryDeliveryCache) Has

func (c *InMemoryDeliveryCache) Has(deliveryID string) bool

Has checks if a delivery ID exists in the cache

type InMemoryRetryStorage

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

InMemoryRetryStorage is a simple in-memory implementation of RetryStorage

func NewInMemoryRetryStorage

func NewInMemoryRetryStorage() *InMemoryRetryStorage

NewInMemoryRetryStorage creates a new in-memory retry storage

func (*InMemoryRetryStorage) Delete

func (s *InMemoryRetryStorage) Delete(ctx context.Context, deliveryID string) error

Delete deletes retry information for an event

func (*InMemoryRetryStorage) Get

func (s *InMemoryRetryStorage) Get(ctx context.Context, deliveryID string) (*RetryInfo, error)

Get gets retry information for an event

func (*InMemoryRetryStorage) List

func (s *InMemoryRetryStorage) List(ctx context.Context, filter RetryFilter) ([]*RetryInfo, error)

List lists all retry information matching a filter

func (*InMemoryRetryStorage) Store

func (s *InMemoryRetryStorage) Store(ctx context.Context, event Event, status RetryStatus, retryCount int, nextRetry time.Time, err error) error

Store stores retry information for an event

func (*InMemoryRetryStorage) Update

func (s *InMemoryRetryStorage) Update(ctx context.Context, info *RetryInfo) error

Update updates retry information for an event

type Manager

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

Manager manages webhook event handlers

func NewManager

func NewManager(eventBus any, logger observability.Logger) *Manager

NewManager creates a new webhook handler manager

func (*Manager) List

func (m *Manager) List() []string

List lists all registered webhook handlers

func (*Manager) ProcessEvent

func (m *Manager) ProcessEvent(ctx context.Context, event Event) error

ProcessEvent processes a webhook event

func (*Manager) Register

func (m *Manager) Register(id string, handler HandlerFunc, filter *Filter) error

Register registers a new webhook handler

func (*Manager) Unregister

func (m *Manager) Unregister(id string) error

Unregister unregisters a webhook handler

type Processor

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

Processor processes webhook events asynchronously

func NewProcessor

func NewProcessor(config *ProcessorConfig) *Processor

NewProcessor creates a new webhook processor

func (*Processor) ProcessEvent

func (p *Processor) ProcessEvent(event *WebhookEvent) error

ProcessEvent processes a webhook event asynchronously

func (*Processor) RegisterHandler

func (p *Processor) RegisterHandler(eventType string, handler WebhookHandler)

RegisterHandler registers a webhook handler for a specific event type

func (*Processor) Start

func (p *Processor) Start()

Start starts the webhook processor

func (*Processor) Stop

func (p *Processor) Stop()

Stop stops the webhook processor

type ProcessorConfig

type ProcessorConfig struct {
	QueueSize   int
	WorkerCount int
	Logger      observability.Logger
	Metrics     observability.MetricsClient
}

ProcessorConfig holds configuration for the webhook processor

type RetryConfig

type RetryConfig struct {
	// MaxRetries is the maximum number of retries
	MaxRetries int

	// InitialBackoff is the initial backoff duration
	InitialBackoff time.Duration

	// MaxBackoff is the maximum backoff duration
	MaxBackoff time.Duration

	// BackoffFactor is the factor to multiply backoff on each retry
	BackoffFactor float64

	// Jitter is the jitter factor to randomize backoff
	Jitter float64
}

RetryConfig holds configuration for the retry manager

func DefaultRetryConfig

func DefaultRetryConfig() *RetryConfig

DefaultRetryConfig returns a default retry configuration

type RetryFilter

type RetryFilter struct {
	// DeliveryIDs are the delivery IDs to filter by
	DeliveryIDs []string

	// EventTypes are the event types to filter by
	EventTypes []string

	// Statuses are the statuses to filter by
	Statuses []RetryStatus

	// MinRetryCount is the minimum retry count to filter by
	MinRetryCount int

	// MaxRetryCount is the maximum retry count to filter by
	MaxRetryCount int

	// Since is the minimum creation time to filter by
	Since time.Time

	// Until is the maximum creation time to filter by
	Until time.Time
}

RetryFilter defines a filter for listing retry information

type RetryHandler

type RetryHandler func(ctx context.Context, event Event) error

RetryHandler defines the handler for retrying events

type RetryInfo

type RetryInfo struct {
	// DeliveryID is the GitHub delivery ID
	DeliveryID string

	// EventType is the GitHub event type
	EventType string

	// Event is the parsed webhook event
	Event Event

	// Status is the retry status
	Status RetryStatus

	// RetryCount is the number of retries attempted
	RetryCount int

	// NextRetry is the time of the next retry
	NextRetry time.Time

	// LastError is the error from the last retry attempt
	LastError string

	// CreatedAt is the time when the retry info was created
	CreatedAt time.Time

	// UpdatedAt is the time when the retry info was last updated
	UpdatedAt time.Time
}

RetryInfo holds information about a retried event

type RetryManager

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

RetryManager manages the retrying of webhook events

func NewRetryManager

func NewRetryManager(config *RetryConfig, storage RetryStorage, handler RetryHandler, logger observability.Logger) *RetryManager

NewRetryManager creates a new retry manager

func (*RetryManager) Cancel

func (m *RetryManager) Cancel(ctx context.Context, deliveryID string) error

Cancel cancels a scheduled retry

func (*RetryManager) Close

func (m *RetryManager) Close() error

Close closes the retry manager

func (*RetryManager) GetStatus

func (m *RetryManager) GetStatus(ctx context.Context, deliveryID string) (*RetryInfo, error)

GetStatus gets the status of a retried event

func (*RetryManager) List

func (m *RetryManager) List(ctx context.Context, filter RetryFilter) ([]*RetryInfo, error)

List lists all retry information matching a filter

func (*RetryManager) Retry

func (m *RetryManager) Retry(ctx context.Context, deliveryID string) error

Retry retries a webhook event immediately

func (*RetryManager) ScheduleRetry

func (m *RetryManager) ScheduleRetry(ctx context.Context, event Event, err error) error

ScheduleRetry schedules a webhook event for retry

func (*RetryManager) Start

func (m *RetryManager) Start(ctx context.Context) error

Start starts the retry manager

type RetryStatus

type RetryStatus string

RetryStatus represents the status of a retried event

const (
	// RetryStatusPending indicates the event is pending retry
	RetryStatusPending RetryStatus = "pending"

	// RetryStatusInProgress indicates the event is being retried
	RetryStatusInProgress RetryStatus = "in_progress"

	// RetryStatusSuccess indicates the event was successfully processed
	RetryStatusSuccess RetryStatus = "success"

	// RetryStatusFailed indicates the event processing failed after all retries
	RetryStatusFailed RetryStatus = "failed"

	// RetryStatusCancelled indicates the event retry was cancelled
	RetryStatusCancelled RetryStatus = "cancelled"
)

type RetryStorage

type RetryStorage interface {
	// Store stores retry information for an event
	Store(ctx context.Context, event Event, status RetryStatus, retryCount int, nextRetry time.Time, err error) error

	// Get gets retry information for an event
	Get(ctx context.Context, deliveryID string) (*RetryInfo, error)

	// List lists all retry information matching a filter
	List(ctx context.Context, filter RetryFilter) ([]*RetryInfo, error)

	// Update updates retry information for an event
	Update(ctx context.Context, info *RetryInfo) error

	// Delete deletes retry information for an event
	Delete(ctx context.Context, deliveryID string) error
}

RetryStorage defines the interface for storing retry information

type Validator

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

Validator validates webhook requests

func NewValidator

func NewValidator(secret string, deliveryCache DeliveryCache) *Validator

NewValidator creates a new webhook validator

func (*Validator) DisableIPValidation

func (v *Validator) DisableIPValidation()

DisableIPValidation disables IP validation

func (*Validator) DisableSignatureValidation

func (v *Validator) DisableSignatureValidation()

DisableSignatureValidation disables webhook signature validation (for testing only)

func (*Validator) EnableIPValidation

func (v *Validator) EnableIPValidation() error

EnableIPValidation enables IP validation and fetches GitHub's IP ranges

func (*Validator) EnableSignatureValidation

func (v *Validator) EnableSignatureValidation()

EnableSignatureValidation enables webhook signature validation (default behavior)

func (*Validator) RegisterSchema

func (v *Validator) RegisterSchema(eventType string, schema []byte) error

RegisterSchema registers a JSON schema for an event type

func (*Validator) SetDeliveryCache

func (v *Validator) SetDeliveryCache(cache DeliveryCache)

SetDeliveryCache sets the delivery cache

func (*Validator) SetSecret

func (v *Validator) SetSecret(secret string)

SetSecret sets the webhook secret

func (*Validator) Validate

func (v *Validator) Validate(eventType string, payload []byte, headers http.Header) error

Validate validates a webhook request

func (*Validator) ValidateDeliveryID

func (v *Validator) ValidateDeliveryID(deliveryID string) error

ValidateDeliveryID validates the delivery ID of a webhook request

func (*Validator) ValidateHeaders

func (v *Validator) ValidateHeaders(headers http.Header) error

ValidateHeaders validates the headers of a webhook request

func (*Validator) ValidatePayload

func (v *Validator) ValidatePayload(eventType string, payload []byte) error

ValidatePayload validates the payload of a webhook request against its JSON schema

func (*Validator) ValidateSignature

func (v *Validator) ValidateSignature(payload []byte, signature string) error

ValidateSignature validates the signature of a webhook request

func (*Validator) ValidateSourceIP

func (v *Validator) ValidateSourceIP(sourceIP string) error

ValidateSourceIP validates the source IP of a webhook request

func (*Validator) ValidateWithIP

func (v *Validator) ValidateWithIP(eventType string, payload []byte, headers http.Header, remoteAddr string) error

ValidateWithIP validates a webhook request with a remote IP address

type WebhookEvent

type WebhookEvent struct {
	ID        string
	Type      string
	Payload   []byte
	Timestamp time.Time
	Headers   map[string]string
}

WebhookEvent represents a GitHub webhook event

type WebhookHandler

type WebhookHandler interface {
	// HandleEvent handles a webhook event
	HandleEvent(ctx context.Context, event *WebhookEvent) error
}

WebhookHandler defines the interface for handling webhook events

Jump to

Keyboard shortcuts

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