webhook

package
v0.0.14 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CodeWebhookNotFound           = "WEBHOOK_NOT_FOUND"
	CodeWebhookAlreadyExists      = "WEBHOOK_ALREADY_EXISTS"
	CodeWebhookCreationFailed     = "WEBHOOK_CREATION_FAILED"
	CodeWebhookUpdateFailed       = "WEBHOOK_UPDATE_FAILED"
	CodeWebhookDeletionFailed     = "WEBHOOK_DELETION_FAILED"
	CodeInvalidEventType          = "INVALID_EVENT_TYPE"
	CodeInvalidURL                = "INVALID_URL"
	CodeInvalidRetryBackoff       = "INVALID_RETRY_BACKOFF"
	CodeDeliveryFailed            = "DELIVERY_FAILED"
	CodeEventCreationFailed       = "EVENT_CREATION_FAILED"
	CodeEventNotFound             = "EVENT_NOT_FOUND"
	CodeDeliveryNotFound          = "DELIVERY_NOT_FOUND"
	CodeMaxWebhooksReached        = "MAX_WEBHOOKS_REACHED"
	CodeMissingAppContext         = "MISSING_APP_CONTEXT"
	CodeMissingEnvironmentContext = "MISSING_ENVIRONMENT_CONTEXT"
)
View Source
const (
	EventUserCreated       = "user.created"
	EventUserUpdated       = "user.updated"
	EventUserDeleted       = "user.deleted"
	EventUserLogin         = "user.login"
	EventUserLogout        = "user.logout"
	EventSessionCreated    = "session.created"
	EventSessionRevoked    = "session.revoked"
	EventOrgCreated        = "organization.created"
	EventOrgUpdated        = "organization.updated"
	EventMemberAdded       = "member.added"
	EventMemberRemoved     = "member.removed"
	EventMemberRoleChanged = "member.role_changed"
)

EventType constants for webhook events

View Source
const (
	DeliveryStatusPending   = "pending"
	DeliveryStatusDelivered = "delivered"
	DeliveryStatusFailed    = "failed"
	DeliveryStatusRetrying  = "retrying"
)

DeliveryStatus constants

View Source
const (
	RetryBackoffExponential = "exponential"
	RetryBackoffLinear      = "linear"
)

RetryBackoff constants

Variables

View Source
var (
	ErrWebhookNotFound           = &errs.AuthsomeError{Code: CodeWebhookNotFound}
	ErrWebhookAlreadyExists      = &errs.AuthsomeError{Code: CodeWebhookAlreadyExists}
	ErrWebhookCreationFailed     = &errs.AuthsomeError{Code: CodeWebhookCreationFailed}
	ErrWebhookUpdateFailed       = &errs.AuthsomeError{Code: CodeWebhookUpdateFailed}
	ErrWebhookDeletionFailed     = &errs.AuthsomeError{Code: CodeWebhookDeletionFailed}
	ErrInvalidEventType          = &errs.AuthsomeError{Code: CodeInvalidEventType}
	ErrInvalidURL                = &errs.AuthsomeError{Code: CodeInvalidURL}
	ErrInvalidRetryBackoff       = &errs.AuthsomeError{Code: CodeInvalidRetryBackoff}
	ErrDeliveryFailed            = &errs.AuthsomeError{Code: CodeDeliveryFailed}
	ErrEventCreationFailed       = &errs.AuthsomeError{Code: CodeEventCreationFailed}
	ErrEventNotFound             = &errs.AuthsomeError{Code: CodeEventNotFound}
	ErrDeliveryNotFound          = &errs.AuthsomeError{Code: CodeDeliveryNotFound}
	ErrMaxWebhooksReached        = &errs.AuthsomeError{Code: CodeMaxWebhooksReached}
	ErrMissingAppContext         = &errs.AuthsomeError{Code: CodeMissingAppContext}
	ErrMissingEnvironmentContext = &errs.AuthsomeError{Code: CodeMissingEnvironmentContext}
)

Functions

func AllEventTypes

func AllEventTypes() []string

AllEventTypes returns all available event types

func DeliveryFailed

func DeliveryFailed(err error) *errs.AuthsomeError

func DeliveryNotFound

func DeliveryNotFound() *errs.AuthsomeError

func EventCreationFailed

func EventCreationFailed(err error) *errs.AuthsomeError

func EventNotFound

func EventNotFound() *errs.AuthsomeError

func InvalidEventType

func InvalidEventType(eventType string) *errs.AuthsomeError

func InvalidRetryBackoff

func InvalidRetryBackoff(backoff string) *errs.AuthsomeError

func InvalidURL

func InvalidURL(url string) *errs.AuthsomeError

func IsValidEventType

func IsValidEventType(eventType string) bool

IsValidEventType checks if an event type is valid

func MaxWebhooksReached

func MaxWebhooksReached(limit int) *errs.AuthsomeError

func MissingAppContext

func MissingAppContext() *errs.AuthsomeError

func MissingEnvironmentContext

func MissingEnvironmentContext() *errs.AuthsomeError

func WebhookAlreadyExists

func WebhookAlreadyExists() *errs.AuthsomeError

func WebhookCreationFailed

func WebhookCreationFailed(err error) *errs.AuthsomeError

func WebhookDeletionFailed

func WebhookDeletionFailed(err error) *errs.AuthsomeError

func WebhookNotFound

func WebhookNotFound() *errs.AuthsomeError

func WebhookUpdateFailed

func WebhookUpdateFailed(err error) *errs.AuthsomeError

Types

type Config

type Config struct {
	MaxRetries       int           `json:"max_retries"`
	DefaultTimeout   time.Duration `json:"default_timeout"`
	MaxDeliveryDelay time.Duration `json:"max_delivery_delay"`
	WorkerCount      int           `json:"worker_count"`
	BatchSize        int           `json:"batch_size"`
}

Config holds the webhook service configuration

type CreateWebhookRequest

type CreateWebhookRequest struct {
	AppID         xid.ID            `json:"appID" validate:"required"`
	EnvironmentID xid.ID            `json:"environmentID" validate:"required"`
	URL           string            `json:"url" validate:"required,url"`
	Events        []string          `json:"events" validate:"required,min=1"`
	MaxRetries    int               `json:"maxRetries" validate:"min=0,max=10"`
	RetryBackoff  string            `json:"retryBackoff" validate:"oneof=exponential linear"`
	Headers       map[string]string `json:"headers,omitempty"`
}

CreateWebhookRequest represents a request to create a webhook

type Delivery

type Delivery struct {
	ID          xid.ID     `json:"id"`
	WebhookID   xid.ID     `json:"webhookID"`
	EventID     xid.ID     `json:"eventID"`
	Attempt     int        `json:"attempt"`
	Status      string     `json:"status"` // "pending", "delivered", "failed", "retrying"
	StatusCode  int        `json:"statusCode,omitempty"`
	Response    string     `json:"response,omitempty"`
	Error       string     `json:"error,omitempty"`
	DeliveredAt *time.Time `json:"deliveredAt,omitempty"`
	CreatedAt   time.Time  `json:"createdAt"`
	UpdatedAt   time.Time  `json:"updatedAt"`
}

Delivery represents a webhook delivery attempt (DTO)

func FromSchemaDeliveries

func FromSchemaDeliveries(deliveries []*schema.Delivery) []*Delivery

FromSchemaDeliveries converts multiple schema.Delivery to Delivery DTOs

func FromSchemaDelivery

func FromSchemaDelivery(d *schema.Delivery) *Delivery

FromSchemaDelivery converts schema.Delivery to Delivery DTO

func (*Delivery) ToSchema

func (d *Delivery) ToSchema() *schema.Delivery

ToSchema converts Delivery DTO to schema.Delivery

type Event

type Event struct {
	ID            xid.ID                 `json:"id"`
	AppID         xid.ID                 `json:"appID"`
	EnvironmentID xid.ID                 `json:"environmentID"`
	Type          string                 `json:"type"`
	Data          map[string]interface{} `json:"data"`
	OccurredAt    time.Time              `json:"occurredAt"`
	CreatedAt     time.Time              `json:"createdAt"`
}

Event represents a webhook event (DTO)

func FromSchemaEvent

func FromSchemaEvent(e *schema.Event) *Event

FromSchemaEvent converts schema.Event to Event DTO

func FromSchemaEvents

func FromSchemaEvents(events []*schema.Event) []*Event

FromSchemaEvents converts multiple schema.Event to Event DTOs

func (*Event) ToSchema

func (e *Event) ToSchema() *schema.Event

ToSchema converts Event DTO to schema.Event

type ListDeliveriesFilter

type ListDeliveriesFilter struct {
	pagination.PaginationParams
	WebhookID xid.ID  `json:"webhookId" query:"webhook_id"`
	Status    *string `json:"status,omitempty" query:"status"` // Filter by delivery status
}

ListDeliveriesFilter represents filter parameters for listing deliveries

type ListDeliveriesResponse

type ListDeliveriesResponse = pagination.PageResponse[*Delivery]

ListDeliveriesResponse is a type alias for paginated response

type ListEventsFilter

type ListEventsFilter struct {
	pagination.PaginationParams
	AppID         xid.ID  `json:"appId" query:"app_id"`
	EnvironmentID xid.ID  `json:"environmentId" query:"environment_id"`
	Type          *string `json:"type,omitempty" query:"type"` // Filter by event type
}

ListEventsFilter represents filter parameters for listing events

type ListEventsResponse

type ListEventsResponse = pagination.PageResponse[*Event]

ListEventsResponse is a type alias for paginated response

type ListWebhooksFilter

type ListWebhooksFilter struct {
	pagination.PaginationParams
	AppID         xid.ID  `json:"appId" query:"app_id"`
	EnvironmentID xid.ID  `json:"environmentId" query:"environment_id"`
	Enabled       *bool   `json:"enabled,omitempty" query:"enabled"`
	Event         *string `json:"event,omitempty" query:"event"` // Filter by specific event type
}

ListWebhooksFilter represents filter parameters for listing webhooks

type ListWebhooksResponse

type ListWebhooksResponse = pagination.PageResponse[*Webhook]

ListWebhooksResponse is a type alias for paginated response

type Repository

type Repository interface {
	// Webhook operations
	CreateWebhook(ctx context.Context, webhook *schema.Webhook) error
	FindWebhookByID(ctx context.Context, id xid.ID) (*schema.Webhook, error)
	ListWebhooks(ctx context.Context, filter *ListWebhooksFilter) (*pagination.PageResponse[*schema.Webhook], error)
	FindWebhooksByAppAndEvent(ctx context.Context, appID xid.ID, envID xid.ID, eventType string) ([]*schema.Webhook, error)
	UpdateWebhook(ctx context.Context, webhook *schema.Webhook) error
	DeleteWebhook(ctx context.Context, id xid.ID) error
	UpdateFailureCount(ctx context.Context, id xid.ID, count int) error
	UpdateLastDelivery(ctx context.Context, id xid.ID, timestamp time.Time) error

	// Event operations
	CreateEvent(ctx context.Context, event *schema.Event) error
	FindEventByID(ctx context.Context, id xid.ID) (*schema.Event, error)
	ListEvents(ctx context.Context, filter *ListEventsFilter) (*pagination.PageResponse[*schema.Event], error)

	// Delivery operations
	CreateDelivery(ctx context.Context, delivery *schema.Delivery) error
	FindDeliveryByID(ctx context.Context, id xid.ID) (*schema.Delivery, error)
	ListDeliveries(ctx context.Context, filter *ListDeliveriesFilter) (*pagination.PageResponse[*schema.Delivery], error)
	UpdateDelivery(ctx context.Context, delivery *schema.Delivery) error
	FindPendingDeliveries(ctx context.Context, limit int) ([]*schema.Delivery, error)
}

Repository defines the interface for webhook storage operations Following ISP - works with schema types

type Service

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

Service provides webhook functionality

func NewService

func NewService(config Config, repo Repository, auditSvc *audit.Service) *Service

NewService creates a new webhook service

func (*Service) CreateWebhook

func (s *Service) CreateWebhook(ctx context.Context, req *CreateWebhookRequest) (*Webhook, error)

CreateWebhook creates a new webhook subscription

func (*Service) DeleteWebhook

func (s *Service) DeleteWebhook(ctx context.Context, id xid.ID) error

DeleteWebhook deletes a webhook

func (*Service) EmitEvent

func (s *Service) EmitEvent(ctx context.Context, appID, envID xid.ID, eventType string, data map[string]interface{}) error

EmitEvent emits an event to all subscribed webhooks

func (*Service) GetWebhook

func (s *Service) GetWebhook(ctx context.Context, id xid.ID) (*Webhook, error)

GetWebhook retrieves a webhook by ID

func (*Service) ListDeliveries

func (s *Service) ListDeliveries(ctx context.Context, filter *ListDeliveriesFilter) (*ListDeliveriesResponse, error)

ListDeliveries lists deliveries with filtering and pagination

func (*Service) ListWebhooks

func (s *Service) ListWebhooks(ctx context.Context, filter *ListWebhooksFilter) (*ListWebhooksResponse, error)

ListWebhooks lists webhooks with filtering and pagination

func (*Service) UpdateWebhook

func (s *Service) UpdateWebhook(ctx context.Context, id xid.ID, req *UpdateWebhookRequest) (*Webhook, error)

UpdateWebhook updates an existing webhook

func (*Service) VerifySignature

func (s *Service) VerifySignature(payload []byte, signature, secret string) bool

VerifySignature verifies webhook signature

type UpdateWebhookRequest

type UpdateWebhookRequest struct {
	URL          *string           `json:"url,omitempty" validate:"omitempty,url"`
	Events       []string          `json:"events,omitempty" validate:"omitempty,min=1"`
	Enabled      *bool             `json:"enabled,omitempty"`
	MaxRetries   *int              `json:"maxRetries,omitempty" validate:"omitempty,min=0,max=10"`
	RetryBackoff *string           `json:"retryBackoff,omitempty" validate:"omitempty,oneof=exponential linear"`
	Headers      map[string]string `json:"headers,omitempty"`
}

UpdateWebhookRequest represents a request to update a webhook

type Webhook

type Webhook struct {
	ID            xid.ID            `json:"id"`
	AppID         xid.ID            `json:"appID"`
	EnvironmentID xid.ID            `json:"environmentID"`
	URL           string            `json:"url"`
	Events        []string          `json:"events"`
	Secret        string            `json:"-"` // Never expose in JSON
	Enabled       bool              `json:"enabled"`
	MaxRetries    int               `json:"maxRetries"`
	RetryBackoff  string            `json:"retryBackoff"` // "exponential" or "linear"
	Headers       map[string]string `json:"headers,omitempty"`
	CreatedAt     time.Time         `json:"createdAt"`
	UpdatedAt     time.Time         `json:"updatedAt"`
	LastDelivery  *time.Time        `json:"lastDelivery,omitempty"`
	FailureCount  int               `json:"failureCount"`
}

Webhook represents a webhook subscription (DTO)

func FromSchemaWebhook

func FromSchemaWebhook(w *schema.Webhook) *Webhook

FromSchemaWebhook converts schema.Webhook to Webhook DTO

func FromSchemaWebhooks

func FromSchemaWebhooks(webhooks []*schema.Webhook) []*Webhook

FromSchemaWebhooks converts multiple schema.Webhook to Webhook DTOs

func (*Webhook) ToSchema

func (w *Webhook) ToSchema() *schema.Webhook

ToSchema converts Webhook DTO to schema.Webhook

Jump to

Keyboard shortcuts

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