webhook

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: Apache-2.0 Imports: 8 Imported by: 4

README

webhook-schema

A simple library for housing the webhook-schema and validation code.

Build Status codecov.io Go Report Card Apache V2 License GitHub Release GoDoc

Table of Contents

Code of Conduct

This project and everyone participating in it are governed by the XMiDT Code Of Conduct. By participating, you agree to this Code.

Examples

To use the webhook-schema library, it first should be added as an import in the file you plan to use it. Examples can be found at the top of the GoDoc.

Contributing

Refer to CONTRIBUTING.md.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidInput = fmt.Errorf("invalid input")
	ErrInvalidType  = fmt.Errorf("invalid type")
	ErrUknownType   = fmt.Errorf("unknown type")
)

Functions

This section is empty.

Types

type AlwaysValidOption added in v0.2.0

type AlwaysValidOption struct{}

func (AlwaysValidOption) String added in v0.2.0

func (a AlwaysValidOption) String() string

func (AlwaysValidOption) Validate added in v0.2.0

func (a AlwaysValidOption) Validate(any) error

type BatchHint added in v0.2.0

type BatchHint struct {
	// MaxLingerDuration is the maximum delay for batching if MaxMesasges has not been reached.
	// Default value will set no maximum value.
	MaxLingerDuration time.Duration `json:"max_linger_duration"`
	// MaxMesasges is the maximum number of events that will be sent in a single batch.
	// Default value will set no maximum value.
	MaxMesasges int `json:"max_messages"`
}

type ContactInfo added in v0.2.0

type ContactInfo struct {
	Name  string `json:"name"`
	Phone string `json:"phone"`
	Email string `json:"email"`
}

type CustomDuration

type CustomDuration time.Duration

CustomDuration is a custom type for time.Duration that allows for unmarshaling from a string or int. If unmarshaling from a string, the string must be parsable by time.ParseDuration. If unmarshaling from an int, the int is assumed to be in seconds. Wes

func (CustomDuration) MarshalJSON

func (cd CustomDuration) MarshalJSON() ([]byte, error)

func (CustomDuration) String

func (cd CustomDuration) String() string

func (*CustomDuration) UnmarshalJSON

func (cd *CustomDuration) UnmarshalJSON(b []byte) (err error)

type DNSSrvRecord added in v0.2.0

type DNSSrvRecord struct {
	// FQDNs is a list of FQDNs pointing to dns srv records
	FQDNs []string `json:"fqdns"`

	// LoadBalancingScheme is the scheme to use for load balancing. Either the
	// srv record attribute `weight` or `priortiy` can be used.
	LoadBalancingScheme string `json:"load_balancing_scheme"`
}

DNSSrvRecord is the substructure for configuration related to load balancing.

type DeliveryConfig deprecated

type DeliveryConfig struct {
	// URL is the HTTP URL to deliver messages to.
	ReceiverURL string `json:"url"`

	// ContentType is content type value to set WRP messages to (unless already specified in the WRP).
	ContentType string `json:"content_type"`

	// Secret is the string value for the SHA1 HMAC.
	// (Optional, set to "" to disable behavior).
	Secret string `json:"secret,omitempty"`

	// AlternativeURLs is a list of explicit URLs that should be round robin through on failure cases to the main URL.
	AlternativeURLs []string `json:"alt_urls,omitempty"`
}

Deprecated: This substructure should only be used for backwards compatibility matching. Use Webhook instead. DeliveryConfig is a Webhook substructure with data related to event delivery.

type FieldRegex added in v0.2.0

type FieldRegex struct {
	// Field is the wrp field to be used for regex.
	// All wrp field can be used, refer to the schema for examples.
	Field string `json:"field"`

	// FieldRegex is the regular expression to match `Field` against to.
	Regex string `json:"regex"`
}

FieldRegex is a substructure with data related to regular expressions.

type InvalidDurationError

type InvalidDurationError struct {
	Value string
}

func (*InvalidDurationError) Error

func (ide *InvalidDurationError) Error() string

type Kafka added in v0.2.0

type Kafka struct {
	// Accept is the encoding type of outgoing events. The following encoding types are supported, otherwise
	// a 406 response code is returned: application/octet-stream, application/json, application/jsonl, application/msgpack.
	// Note: An `Accept` of application/octet-stream or application/json will result in a single response for batch sizes of 0 or 1
	// and batch sizes greater than 1 will result in a multipart response. An `Accept` of application/jsonl or application/msgpack
	// will always result in a single response with a list of batched events for any batch size.
	Accept string `json:"accept"`

	// BootstrapServers is a list of kafka broker addresses.
	BootstrapServers []string `json:"bootstrap_servers"`

	// TODO: figure out which kafka configuration substructures we want to expose to users (to be set by users)
	// going to be based on https://pkg.go.dev/github.com/IBM/sarama#Config
	// this substructures also includes auth related secrets, noted `MaxOpenRequests` will be excluded since it's already exposed
	KafkaProducer struct{} `json:"kafka_producer"`

	//RetryHint is the substructure for configuration related to retrying requests.
	// (Optional, if omited then retries will be based on default values defined by server)
	RetryHint RetryHint `json:"retry_hint"`
}

Kafka is a substructure with data related to event delivery.

type MetadataMatcherConfig

type MetadataMatcherConfig struct {
	// DeviceID is the list of regular expressions to match device id type against.
	DeviceID []string `json:"device_id"`
}

MetadataMatcherConfig is Webhook substructure with config to match event metadata.

type Option

type Option interface {
	fmt.Stringer
	Validate(any) error
}

func AlwaysValid added in v0.2.0

func AlwaysValid() Option

func AtLeastOneEvent

func AtLeastOneEvent() Option

AtLeastOneEvent makes sure there is at least one value in Events and ensures that all values should parse into regex.

func DeviceIDRegexMustCompile

func DeviceIDRegexMustCompile() Option

DeviceIDRegexMustCompile ensures that all values in DeviceID parse into valid regex.

func Error

func Error(err error) Option

Error is an option that returns an error when called.

func EventRegexMustCompile

func EventRegexMustCompile() Option

EventRegexMustCompile ensures that all values in Events parse into valid regex.

func NoUntil

func NoUntil() Option

NoUntil is an option that ensures that the Until field is not set.

func ProvideAlternativeURLValidator

func ProvideAlternativeURLValidator(checker *urlegit.Checker) Option

ProvideAlternativeURLValidator is an option that allows the caller to provide a URL validator that is used to validate the AlternativeURL.

func ProvideFailureURLValidator

func ProvideFailureURLValidator(checker *urlegit.Checker) Option

ProvideFailureURLValidator is an option that allows the caller to provide a URL validator that is used to validate the FailureURL.

func ProvideReceiverURLValidator

func ProvideReceiverURLValidator(checker *urlegit.Checker) Option

ProvideReceiverURLValidator is an option that allows the caller to provide a URL validator that is used to validate the ReceiverURL.

func ProvideTimeNowFunc

func ProvideTimeNowFunc(nowFunc func() time.Time) Option

ProvideTimeNowFunc is an option that allows the caller to provide a function that returns the current time. This is used for testing.

func Until added in v0.2.0

func Until(now func() time.Time, jitter, max time.Duration) Option

func ValidateRegistrationDuration

func ValidateRegistrationDuration(ttl time.Duration) Option

ValidateRegistrationDuration ensures that the requsted registration duration of a webhook is valid. This option checks the values set in either the Duration or Until fields of the webhook. If the ttl is less than or equal to zero, this option will not boundary check the registration duration, but will still ensure that the Duration or Until fields are set.

type RegistrationV1 deprecated added in v0.2.0

type RegistrationV1 struct {
	// Address is the subscription request origin HTTP Address.
	Address string `json:"registered_from_address"`

	// Config contains data to inform how events are delivered.
	Config DeliveryConfig `json:"config"`

	// FailureURL is the URL used to notify subscribers when they've been cut off due to event overflow.
	// Optional, set to "" to disable notifications.
	FailureURL string `json:"failure_url"`

	// Events is the list of regular expressions to match an event type against.
	Events []string `json:"events"`

	// Matcher type contains values to match against the metadata.
	Matcher MetadataMatcherConfig `json:"matcher,omitempty"`

	// Duration describes how long the subscription lasts once added.
	Duration CustomDuration `json:"duration"`

	// Until describes the time this subscription expires.
	Until time.Time `json:"until"`
	// contains filtered or unexported fields
}

Deprecated: This structure should only be used for backwards compatibility matching. Use RegistrationV2 instead. RegistrationV1 is a special struct for unmarshaling a webhook as part of a webhook registration request.

func (*RegistrationV1) CheckUntil added in v0.2.0

func (v1 *RegistrationV1) CheckUntil(now func() time.Time, jitter, maxTTL time.Duration) error

func (*RegistrationV1) SetNowFunc added in v0.2.0

func (v1 *RegistrationV1) SetNowFunc(now func() time.Time)

func (*RegistrationV1) ValidateAltURL added in v0.2.0

func (v1 *RegistrationV1) ValidateAltURL(c *urlegit.Checker) error

func (*RegistrationV1) ValidateDeviceId added in v0.2.0

func (v1 *RegistrationV1) ValidateDeviceId() error

func (*RegistrationV1) ValidateDuration added in v0.2.0

func (v1 *RegistrationV1) ValidateDuration(ttl time.Duration) error

func (*RegistrationV1) ValidateEventRegex added in v0.2.0

func (v1 *RegistrationV1) ValidateEventRegex() error

func (*RegistrationV1) ValidateNoUntil added in v0.2.0

func (v1 *RegistrationV1) ValidateNoUntil() error

func (*RegistrationV1) ValidateOneEvent added in v0.2.0

func (v1 *RegistrationV1) ValidateOneEvent() error

func (*RegistrationV1) ValidateReceiverURL added in v0.2.0

func (v1 *RegistrationV1) ValidateReceiverURL(c *urlegit.Checker) error

func (*RegistrationV1) ValidateUntil added in v0.2.0

func (v1 *RegistrationV1) ValidateUntil(jitter time.Duration, maxTTL time.Duration, now func() time.Time) error

type RegistrationV2 added in v0.2.0

type RegistrationV2 struct {
	// ContactInfo contains contact information used to reach the owner of the registration.
	// (Optional).
	ContactInfo ContactInfo `json:"contact_info,omitempty"`

	// CanonicalName is the canonical name of the registration request.
	// Reusing a CanonicalName will override the configurations set in that previous
	// registration request with the same CanonicalName.
	CanonicalName string `json:"canonical_name"`

	// Address is the subscription request origin HTTP Address.
	Address string `json:"registered_from_address"`

	// Webhooks contains data to inform how events are delivered to multiple urls.
	Webhooks []Webhook `json:"webhooks"`

	// Kafkas contains data to inform how events are delivered to multiple kafkas.
	Kafkas []Kafka `json:"kafkas"`

	// Hash is a substructure for configuration related to distributing events among sinks.
	// Note. Any failures due to a bad regex feild or regex expression will result in a silent failure.
	Hash FieldRegex `json:"hash"`

	// BatchHint is the substructure for configuration related to event batching.
	// (Optional, if omited then batches of singal events will be sent)
	// Default value will disable batch. All zeros will also disable batch.
	BatchHint BatchHint `json:"batch_hints"`

	// FailureURL is the URL used to notify subscribers when they've been cut off due to event overflow.
	// Optional, set to "" to disable notifications.
	FailureURL string `json:"failure_url"`

	// Matcher is the list of regular expressions to match incoming events against to.
	// Note. Any failures due to a bad regex field or regex expression will result in a silent failure.
	Matcher []FieldRegex `json:"matcher,omitempty"`

	// Expires describes the time this subscription expires.
	// TODO: list of supported formats
	Expires time.Time `json:"expires"`
}

RegistrationV2 is a special struct for unmarshaling sink information as part of a sink registration request.

func (*RegistrationV2) ValidateDuration added in v0.2.0

func (v2 *RegistrationV2) ValidateDuration() error

func (*RegistrationV2) ValidateEventRegex added in v0.2.0

func (v2 *RegistrationV2) ValidateEventRegex() error

func (*RegistrationV2) ValidateReceiverURL added in v0.2.0

func (v2 *RegistrationV2) ValidateReceiverURL(checker *urlegit.Checker) error

type RetryHint added in v0.2.0

type RetryHint struct {
	//RetryEachUrl is the amount of times a URL should be retried given a failed response until the next URL in the request is tried.
	//Default value will be set to none
	RetryEachUrl int `json:"retry_each_url"`

	//MaxRetry is the total amount times a request will be retried.
	MaxRetry int `json:"max_retry"`
}

RetryHint is the substructure for configuration related to retrying requests.

type Validators added in v0.2.0

type Validators []Option

func (Validators) Validate added in v0.2.0

func (vs Validators) Validate(r any) error

Validate is a method that validates the registration against a list of options.

type Webhook added in v0.2.0

type Webhook struct {
	// Accept is the encoding type of outgoing events. The following encoding types are supported, otherwise
	// a 406 response code is returned: application/octet-stream, application/json, application/jsonl, application/msgpack.
	/*
		Note:
			application/wrp+json - one json encoded wrp message
			application/wrp+msgpack - one msgpack encoded wrp message
			application/wrp+octet-stream - one message with the wrp payload in the http payload
			application/wrp+jsonl - multiple jsonl encoded wrp messages
			application/wrp+msgpackl - multiple msgpackl encoded wrp messages
	*/
	Accept string `json:"accept"`

	// AcceptEncoding is the content type of outgoing events. The following content types are supported, otherwise
	// a 406 response code is returned: gzip.
	AcceptEncoding string `json:"accept_encoding"`

	// Secret is the string value.
	// (Optional, set to "" to disable behavior).
	Secret string `json:"secret,omitempty"`

	// SecretHash is the hash algorithm to be used. Only sha256 HMAC and sha512 HMAC are supported.
	// (Optional).
	// The Default value is the largest sha HMAC supported, sha512 HMAC.
	SecretHash string `json:"secret_hash"`

	// If true, response will use the device content-type and wrp payload as its body
	// Otherwise, response will Accecpt as the content-type and wrp message as its body
	// Default: False (the entire wrp message is sent)
	PayloadOnly bool `json:"payload_only"`

	// ReceiverUrls is the list of receiver urls that will be used where as if the first url fails,
	// then the second url would be used and so on.
	// Note: either `ReceiverURLs` or `DNSSrvRecord` must be used but not both.
	ReceiverURLs []string `json:"receiver_urls"`

	// DNSSrvRecord is the substructure for configuration related to load balancing.
	// Note: either `ReceiverURLs` or `DNSSrvRecord` must be used but not both.
	DNSSrvRecord DNSSrvRecord `json:"dns_srv_record"`

	//RetryHint is the substructure for configuration related to retrying requests.
	// (Optional, if omited then retries will be based on default values defined by server)
	RetryHint RetryHint `json:"retry_hint"`
}

Webhook is a substructure with data related to event delivery.

Jump to

Keyboard shortcuts

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