webhook

package
v0.0.0-...-1bb08d0 Latest Latest
Warning

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

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

Documentation

Overview

Package webhook provides webhook delivery functionality for external system integration.

Index

Constants

View Source
const (
	// SignatureHeader is the HTTP header containing the webhook signature.
	SignatureHeader = "X-Webhook-Signature"

	// TimestampHeader is the HTTP header containing the request timestamp.
	TimestampHeader = "X-Webhook-Timestamp"

	// IDHeader is the HTTP header containing the webhook event ID.
	IDHeader = "X-Webhook-ID"
)
View Source
const (
	// Session events
	EventSessionCreated    = "session.created"
	EventSessionSuspended  = "session.suspended"
	EventSessionResumed    = "session.resumed"
	EventSessionTerminated = "session.terminated"

	// Task events
	EventTaskCreated   = "task.created"
	EventTaskStarted   = "task.started"
	EventTaskCompleted = "task.completed"
	EventTaskFailed    = "task.failed"
	EventTaskCanceled  = "task.canceled"

	// Runner events
	EventRunnerConnected    = "runner.connected"
	EventRunnerDisconnected = "runner.disconnected"
	EventRunnerAssigned     = "runner.assigned"
	EventRunnerReleased     = "runner.released"

	// Permission events
	EventPermissionRequested = "permission.requested"
	EventPermissionApproved  = "permission.approved"
	EventPermissionDenied    = "permission.denied"
	EventPermissionCanceled  = "permission.canceled"
)

Event types for webhook subscriptions. Patterns support wildcards (e.g., "task.*" matches "task.created", "task.completed", etc.)

Variables

This section is empty.

Functions

func CalculateNextRetry

func CalculateNextRetry(attempt int, baseDelay time.Duration) time.Time

CalculateNextRetry calculates the next retry time using exponential backoff.

func GenerateSecret

func GenerateSecret() (secret, hash, prefix string, err error)

GenerateSecret generates a new random secret for webhook signing. Returns the secret (for display to user) and its SHA-256 hash (for storage).

func HashSecret

func HashSecret(secret string) string

HashSecret computes the SHA-256 hash of a secret.

func KnownEventTypes

func KnownEventTypes() []string

KnownEventTypes returns all known webhook event types.

func ParseEventAction

func ParseEventAction(eventType string) string

ParseEventAction extracts the action from an event type. For example, "task.created" returns "created".

func ParseEventCategory

func ParseEventCategory(eventType string) string

ParseEventCategory extracts the category from an event type. For example, "task.created" returns "task".

func ParseTimestamp

func ParseTimestamp(ts string) (time.Time, error)

ParseTimestamp parses a Unix timestamp string from the webhook headers.

func ShouldRetry

func ShouldRetry(statusCode int) bool

ShouldRetry determines if a delivery should be retried based on status code.

func Sign

func Sign(payload []byte, secret string, timestamp time.Time) string

Sign creates an HMAC-SHA256 signature for the given payload. The signature includes the timestamp to prevent replay attacks.

func ValidateEventPattern

func ValidateEventPattern(pattern string) bool

ValidateEventPattern checks if a pattern is valid. Valid patterns are:

  • Exact event names: "task.created"
  • Wildcard patterns: "task.*"
  • Category patterns: "task"
  • All events: "*"

func Verify

func Verify(payload []byte, signature, secret string, timestamp time.Time) bool

Verify checks if the signature is valid for the given payload and secret. It also validates that the timestamp is within the tolerance window.

Types

type Config

type Config struct {
	// DefaultMaxRetries is the default number of retry attempts for failed deliveries.
	DefaultMaxRetries int

	// DefaultRetryDelaySeconds is the default delay between retry attempts in seconds.
	DefaultRetryDelaySeconds int

	// DefaultTimeoutSeconds is the default HTTP timeout for webhook requests.
	DefaultTimeoutSeconds int

	// MaxPayloadSize is the maximum payload size in bytes (default: 10MB).
	MaxPayloadSize int

	// UserAgent is the User-Agent header sent with webhook requests.
	UserAgent string

	// WorkerCount is the number of concurrent delivery workers.
	WorkerCount int

	// BatchSize is the number of events to process in each batch.
	BatchSize int

	// EncryptionKey is the key used to encrypt webhook secrets (32 bytes for AES-256).
	// If not set, secrets will be stored in base64 encoding (not secure for production).
	EncryptionKey []byte
}

Config contains default configuration for webhook delivery.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default webhook configuration.

type DeliveryCallback

type DeliveryCallback func(result DeliveryResult)

DeliveryCallback is called after delivery attempt.

type DeliveryResult

type DeliveryResult struct {
	Success    bool
	StatusCode int
	Error      error
	Duration   time.Duration
}

DeliveryResult contains the result of a webhook delivery attempt.

type Dispatcher

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

Dispatcher handles webhook delivery with retry support.

func NewDispatcher

func NewDispatcher(config Config, logger *zap.Logger) *Dispatcher

NewDispatcher creates a new webhook dispatcher.

func (*Dispatcher) Dispatch

func (d *Dispatcher) Dispatch(ctx context.Context, webhook *WebhookInfo, payload *Payload, eventID, secret string, callback DeliveryCallback) error

Dispatch queues a webhook for delivery.

func (*Dispatcher) DispatchSync

func (d *Dispatcher) DispatchSync(ctx context.Context, webhook *WebhookInfo, payload *Payload, eventID, secret string) DeliveryResult

DispatchSync delivers a webhook synchronously and returns the result.

func (*Dispatcher) Stop

func (d *Dispatcher) Stop()

Stop gracefully stops the dispatcher.

type Matcher

type Matcher struct{}

Matcher checks if an event type matches a subscription pattern.

func NewMatcher

func NewMatcher() *Matcher

NewMatcher creates a new event matcher.

func (*Matcher) Matches

func (m *Matcher) Matches(eventType string, patterns []string) bool

Matches checks if the event type matches any of the given patterns. Patterns support:

  • Exact match: "task.created" matches "task.created"
  • Wildcard suffix: "task.*" matches "task.created", "task.completed", etc.
  • Category match: "task" matches all task events

func (*Matcher) MatchesAny

func (m *Matcher) MatchesAny(eventType string, webhookEvents [][]string) []int

MatchesAny checks if the event type matches any webhook's subscription. This is a convenience method for filtering webhooks.

type Payload

type Payload struct {
	Event     string          `json:"event"`
	Timestamp time.Time       `json:"timestamp"`
	Resource  ResourceInfo    `json:"resource"`
	Data      json.RawMessage `json:"data"`
}

Payload is the webhook request payload sent to subscribers.

func BuildPayload

func BuildPayload(eventType string, resource ResourceInfo, data any) (*Payload, error)

BuildPayload creates a webhook payload from event data.

type PermissionEventData

type PermissionEventData struct {
	SessionID      string  `json:"session_id"`
	TaskID         string  `json:"task_id"`
	Tool           string  `json:"tool"`
	Action         string  `json:"action"`
	RiskLevel      string  `json:"risk_level"`
	Status         string  `json:"status"`
	RespondedBy    *string `json:"responded_by,omitempty"`
	ResponseReason *string `json:"response_reason,omitempty"`
}

PermissionEventData contains event-specific data for permission events.

type ResourceInfo

type ResourceInfo struct {
	ID          string            `json:"id"`
	Type        string            `json:"type"`
	Labels      map[string]string `json:"labels,omitempty"`
	Annotations map[string]string `json:"annotations,omitempty"`
}

ResourceInfo contains metadata about the resource that triggered the event.

type RunnerEventData

type RunnerEventData struct {
	Name        string  `json:"name"`
	Status      string  `json:"status"`
	PoolName    *string `json:"pool_name,omitempty"`
	SessionID   *string `json:"session_id,omitempty"`
	Provider    *string `json:"provider,omitempty"`
	SandboxMode string  `json:"sandbox_mode,omitempty"`
}

RunnerEventData contains event-specific data for runner events.

type SessionEventData

type SessionEventData struct {
	WorkspaceID   string  `json:"workspace_id"`
	Agent         string  `json:"agent"`
	Status        string  `json:"status"`
	RunnerID      *string `json:"runner_id,omitempty"`
	LifecycleMode string  `json:"lifecycle_mode,omitempty"`
}

SessionEventData contains event-specific data for session events.

type TaskEventData

type TaskEventData struct {
	SessionID       string  `json:"session_id"`
	Prompt          string  `json:"prompt,omitempty"` // Truncated for privacy
	Status          string  `json:"status"`
	DurationSeconds *int64  `json:"duration_seconds,omitempty"`
	ExitCode        *int    `json:"exit_code,omitempty"`
	Error           *string `json:"error,omitempty"`
	TokensInput     *int    `json:"tokens_input,omitempty"`
	TokensOutput    *int    `json:"tokens_output,omitempty"`
}

TaskEventData contains event-specific data for task events.

type WebhookInfo

type WebhookInfo struct {
	ID             string
	URL            string
	Headers        map[string]string
	TimeoutSeconds int
}

WebhookInfo contains webhook delivery configuration.

Jump to

Keyboard shortcuts

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