events

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package events starts runs from events: publish/subscribe inside the library (EV-01) and an inbound webhook handler that verifies a signature and enqueues (EV-03), with HMAC signing schemes for both directions (WH-03).

A Bus is not a message broker. Publish turns one event into one Enqueue per matching subscription on an ordinary workflow.Client, so an event is exactly as durable as the client's runs: on a durable driver, once Publish returns, every subscriber's run is stored. Subscriptions are code, registered at boot in every process that publishes, as workflows are. Delivery is at least once per subscription and deduplicated by the event's ID: each run carries the idempotency key "event/<subscription>/<id>", so publishing the same ID again (a retry after a timeout, a webhook delivered twice) starts nothing new while the first run is unfinished.

Index

Constants

View Source
const (
	// LabelEvent is the event's Name.
	LabelEvent = workflow.LabelPrefixInternal + "event"

	// LabelEventID is the event's ID.
	LabelEventID = workflow.LabelPrefixInternal + "event-id"

	// LabelSubscription is the subscription that started the run.
	LabelSubscription = workflow.LabelPrefixInternal + "subscription"
)

Labels every run started by Publish carries. Publish refuses reserved keys in Message.Labels and in the labels a Subscription.Job returns, and sets these itself, overwriting any value a job carried, and enqueues under workflow.AllowReservedLabels for these three keys only: they are refused on a public Enqueue unless the owner opts in (workflow.CheckJobLabels, on drivers that enforce it), so they cannot arrive by accident or from untrusted input. Like every reserved label they are a guard, not a sandbox.

View Source
const (
	HeaderWebhookID        = "webhook-id"
	HeaderWebhookTimestamp = "webhook-timestamp"
	HeaderWebhookSignature = "webhook-signature"
)

The Standard Webhooks headers.

View Source
const DefaultWebhookMaxBody = 1 << 20

DefaultWebhookMaxBody caps a webhook body when WebhookConfig.MaxBody is zero: 1 MiB.

View Source
const StandardWebhooksTolerance = 5 * time.Minute

StandardWebhooksTolerance is how far a delivery's timestamp may be from now, either way, by default.

Variables

View Source
var ErrSignature = errors.New("events: signature does not verify")

ErrSignature means a request's signature is missing, malformed, does not match, or (for a timestamped scheme) is too old or too new. The webhook handler answers it with 401 and never says which.

Functions

func NewWebhook

func NewWebhook(cfg WebhookConfig) (http.Handler, error)

NewWebhook returns an http.Handler that turns a signed delivery into a run (EV-03): it accepts POST only (405), reads at most MaxBody bytes (413), verifies the signature (401, with no detail), enqueues with the idempotency key "webhook/<workflow>/<id>" or publishes with the delivery's ID, and answers 200 with {"id": "<id>"} as soon as the run is stored, before it runs. An enqueue that fails because the backend is unavailable gets 503 and any other failure 500, so the sender retries; the retry carries the same ID and starts nothing twice.

It returns an error wrapping ErrInvalid when the config has no target, two targets, or no Verifier without Unsigned.

Types

type Bus

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

Bus routes published messages to subscriptions. It is safe for concurrent use; Subscribe may be called at any time.

func New

func New(client workflow.Client, opts ...Option) (*Bus, error)

New returns a bus that enqueues on client. It refuses a client without CapIdempotencyKey with an UnsupportedError, unless AllowDuplicates is given, because deduplication by ID is what makes a republish safe.

func (*Bus) Publish

func (b *Bus) Publish(ctx context.Context, m Message) (Published, error)

Publish starts one run per subscription matching m, and signals m to waiting runs under WithSignal. Every matching subscription is tried even when one fails; the error joins each failure (its Delivery holds it too), so the caller publishes again with the same ID and only the deliveries that failed start a run. A message matching nothing is not an error. m.Name is required and reserved labels in m.Labels are refused, both with ErrInvalid.

func (*Bus) Subscribe

func (b *Bus) Subscribe(s Subscription) error

Subscribe adds s. It returns an error wrapping ErrInvalid when s has no Name or Event, has neither Workflow nor Job, or reuses a Name.

func (*Bus) Subscriptions

func (b *Bus) Subscriptions() []string

Subscriptions returns the names of the subscriptions, in order.

type Delivery

type Delivery struct {
	Subscription string
	Ref          workflow.RunRef
	Err          error
}

Delivery is what one subscription did with one message.

type Encoding

type Encoding string

Encoding is how an HMAC scheme writes its digest.

const (
	EncodingHex    Encoding = "hex"
	EncodingBase64 Encoding = "base64"
)

The encodings.

type HMAC

type HMAC struct {
	// Header holds the signature. Required.
	Header string

	// Secrets are the keys; at least one.
	Secrets [][]byte

	// Prefix is written before the digest ("sha256="). Optional.
	Prefix string

	// Encoding of the digest. Empty means EncodingHex.
	Encoding Encoding

	// Hash builds the hash. Nil means SHA-256.
	Hash func() hash.Hash

	// IDHeader, when set, is the header carrying the delivery ID
	// ("X-GitHub-Delivery"), which Verify returns.
	IDHeader string
}

HMAC is a plain HMAC scheme: a header holding Prefix followed by the HMAC of the body, with no timestamp (the shape GitHub uses with X-Hub-Signature-256 and "sha256=", or Shopify with X-Shopify-Hmac-Sha256 and base64). It signs outgoing bodies (Sign) and verifies incoming ones (Verify). Several secrets verify, so a secret can be rotated without dropping deliveries; Sign uses the first.

It has no timestamp, so it cannot refuse a replayed request; the webhook handler's deduplication by delivery ID is what makes a replay start nothing new. Prefer StandardWebhooks where the sender supports it.

func (HMAC) Sign

func (h HMAC) Sign(body []byte) (string, error)

Sign returns the header value for body, signed with the first secret.

func (HMAC) Verify

func (h HMAC) Verify(r *http.Request, body []byte) (string, error)

Verify checks the header against body with every secret, in constant time per secret.

type Message

type Message struct {
	// ID identifies the event for deduplication; publish the same event
	// again with the same ID. Empty means the Bus makes a new one, so
	// that publish is never deduplicated.
	ID string

	// Name is what subscriptions match on, exactly ("order.paid").
	Name string

	// Key is passed to Signal under WithSignal (the WaitSpec key a waiting
	// run matches), and is there for Filter.
	Key string

	// Payload becomes each subscriber's Job.Payload (unless the
	// subscription's Job builds the job itself).
	Payload []byte

	// Labels are copied onto each subscriber's job, beside the bus's own.
	// Keys under a reserved prefix are refused.
	Labels map[string]string
}

Message is one event.

type Option

type Option func(*Bus)

Option configures a Bus.

func AllowDuplicates

func AllowDuplicates() Option

AllowDuplicates lets New accept a client without CapIdempotencyKey; on it, publishing an ID twice starts its runs twice.

func WithIDFunc

func WithIDFunc(f func() (string, error)) Option

WithIDFunc sets how the bus makes an ID for a message published without one (a UUIDv7 or ULID generator). The default is 16 random bytes in hex.

func WithSignal

func WithSignal() Option

WithSignal makes Publish also deliver each message to runs waiting on it, as client.Signal(Event{Name, Key, Payload}) would, so a run's wait step and a new subscriber's run see the same event.

type Published

type Published struct {
	// ID is the message's ID, the one given or the one the bus made.
	ID string

	// Deliveries has one entry per subscription the message matched, in
	// the order they were subscribed.
	Deliveries []Delivery

	// Signalled reports whether the message was also signalled to
	// waiting runs (WithSignal) without error.
	Signalled bool
}

Published is the outcome of Publish.

type StandardWebhooks

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

StandardWebhooks is the Standard Webhooks scheme (standardwebhooks.com), offered as one convention among others, not a default: HMAC-SHA256 over "<id>.<timestamp>.<body>", sent as "v1,<base64>" in webhook-signature beside webhook-id and webhook-timestamp. The timestamp lets Verify refuse a replayed request older than the tolerance. Build it with NewStandardWebhooks.

func NewStandardWebhooks

func NewStandardWebhooks(secrets []string, tolerance time.Duration, clk clock.Clock) (*StandardWebhooks, error)

NewStandardWebhooks parses secrets ("whsec_" followed by base64; the first signs, all verify) and returns the scheme. tolerance zero means StandardWebhooksTolerance; clk nil means clock.Real.

func (*StandardWebhooks) Headers

func (s *StandardWebhooks) Headers(id string, body []byte) http.Header

Headers returns the three headers that sign body as delivery id at the clock's now, for an outgoing request.

func (*StandardWebhooks) Verify

func (s *StandardWebhooks) Verify(r *http.Request, body []byte) (string, error)

Verify checks the headers against body: an ID, a timestamp within the tolerance of now, and a "v1," signature that matches under any secret. It returns the webhook-id.

type Subscription

type Subscription struct {
	// Name identifies the subscription; unique within a Bus and stable
	// across deploys, because it is part of every run's idempotency key.
	Name string

	// Event is the message Name it matches.
	Event string

	// Workflow is the workflow to run. Ignored when Job is set.
	Workflow string

	// Filter, when set, must return true for the message to start a run.
	Filter func(Message) bool

	// Job, when set, builds the job from the message (a different payload,
	// a queue, a priority, RunAt). Reserved label keys in it are refused
	// (ErrInvalid). The bus still adds its labels and,
	// when the job has none, its idempotency key. Nil means
	// Job{Workflow: Workflow, Payload: m.Payload}.
	Job func(Message) (workflow.Job, error)
}

Subscription starts a run of Workflow for every published message whose Name is Event and that Filter accepts.

type Verifier

type Verifier interface {
	Verify(r *http.Request, body []byte) (id string, err error)
}

Verifier checks an inbound request's signature over its body (the raw bytes, read once by the handler). It returns the delivery ID the sender put on the request, or "" when the scheme has none, and an error matching ErrSignature when the request is not authentic.

type WebhookConfig

type WebhookConfig struct {
	// Verifier authenticates each request. Required unless Unsigned.
	Verifier Verifier

	// Unsigned accepts requests without verifying them. It must be set
	// on purpose: a nil Verifier without it is refused, so an endpoint is
	// never left open by omission.
	Unsigned bool

	// Bus and Event publish each delivery as Message{Name: Event}.
	Bus   *Bus
	Event string

	// Client and Workflow enqueue each delivery as a run of Workflow.
	Client   workflow.Client
	Workflow string

	// ID returns the delivery's deduplication ID when the Verifier gives
	// none. Nil means the SHA-256 of the body in hex, so a sender's retry
	// of the same body starts nothing new.
	ID func(r *http.Request, body []byte) string

	// MaxBody caps the body in bytes; a larger one gets 413. Zero means
	// DefaultWebhookMaxBody.
	MaxBody int64

	// Labels, when set, adds labels to the run (or event) from the
	// request (a tenant from the path). It runs per request, so a reserved
	// key cannot be refused at NewWebhook: such a request gets 500 and a
	// log line naming the config error.
	Labels func(r *http.Request) map[string]string

	// Logger gets enqueue failures, which the response does not detail.
	// Nil discards them.
	Logger *slog.Logger
}

WebhookConfig configures NewWebhook. Exactly one target is set: Bus with Event (publish the delivery as an event), or Client with Workflow (enqueue one run).

Jump to

Keyboard shortcuts

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