Documentation
¶
Overview ¶
Package webhook provides webhook delivery functionality for external system integration.
Index ¶
- Constants
- func CalculateNextRetry(attempt int, baseDelay time.Duration) time.Time
- func GenerateSecret() (secret, hash, prefix string, err error)
- func HashSecret(secret string) string
- func KnownEventTypes() []string
- func ParseEventAction(eventType string) string
- func ParseEventCategory(eventType string) string
- func ParseTimestamp(ts string) (time.Time, error)
- func ShouldRetry(statusCode int) bool
- func Sign(payload []byte, secret string, timestamp time.Time) string
- func ValidateEventPattern(pattern string) bool
- func Verify(payload []byte, signature, secret string, timestamp time.Time) bool
- type Config
- type DeliveryCallback
- type DeliveryResult
- type Dispatcher
- type Matcher
- type Payload
- type PermissionEventData
- type ResourceInfo
- type RunnerEventData
- type SessionEventData
- type TaskEventData
- type WebhookInfo
Constants ¶
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" )
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 ¶
CalculateNextRetry calculates the next retry time using exponential backoff.
func GenerateSecret ¶
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 ¶
HashSecret computes the SHA-256 hash of a secret.
func KnownEventTypes ¶
func KnownEventTypes() []string
KnownEventTypes returns all known webhook event types.
func ParseEventAction ¶
ParseEventAction extracts the action from an event type. For example, "task.created" returns "created".
func ParseEventCategory ¶
ParseEventCategory extracts the category from an event type. For example, "task.created" returns "task".
func ParseTimestamp ¶
ParseTimestamp parses a Unix timestamp string from the webhook headers.
func ShouldRetry ¶
ShouldRetry determines if a delivery should be retried based on status code.
func Sign ¶
Sign creates an HMAC-SHA256 signature for the given payload. The signature includes the timestamp to prevent replay attacks.
func ValidateEventPattern ¶
ValidateEventPattern checks if a pattern is valid. Valid patterns are:
- Exact event names: "task.created"
- Wildcard patterns: "task.*"
- Category patterns: "task"
- All events: "*"
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 ¶
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.
type Matcher ¶
type Matcher struct{}
Matcher checks if an event type matches a subscription pattern.
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.