Documentation
¶
Overview ¶
Package notify delivers domain events to the outside world.
── THE SEAM ─────────────────────────────────────────────────────────────────────────────────────
A Type is `{kind, label, fields, validate, send}`. Types maps kind → type. Adding Slack, Discord or email later is one entry in that map: a Validate for its own config shape and a Send that formats its own body. No schema migration (the registration's config is opaque JSON), no change to the bus, no change to any route.
── NOTHING AWAITS DELIVERY ──────────────────────────────────────────────────────────────────────
Dispatch is called from the bus, which is called from inside a job's finish and from request handlers. It starts work and returns. Every attempt carries a timeout, and MaxInFlight bounds concurrent sockets: this process also runs docker, and an event burst across twenty notifiers would otherwise exhaust its file descriptors.
── WHY THE URL IS CHECKED, AND WHAT THAT IS NOT ─────────────────────────────────────────────────
The notifier URL is the one field that turns this control plane into an HTTP client aimed at an address of someone else's choosing — including 169.254.169.254 (cloud metadata) or 127.0.0.1:7878 (this very API). So loopback / link-local / private ranges are refused, and a redirect is a FAILURE rather than followed. This is not a privilege boundary: anyone who can register a notifier can already submit a spec whose hooks are `bash -c` on this host. The check exists so a typo aimed at an internal address fails loudly, and PSTACK_NOTIFY_ALLOW_PRIVATE=1 escapes it for an internal collector on the same box.
Index ¶
- Constants
- Variables
- func AssertDeliverableURL(raw string) (*url.URL, error)
- func Envelope(e events.Event) []byte
- func IsError(err error) bool
- func IsPrivateHost(hostname string) bool
- func PublicConfig(kind string, config *omap.Map) *omap.Map
- func RedactForNotifier(message, secret string, config *omap.Map) string
- func Sign(secret string, timestamp int64, body []byte) string
- func Summarize(e events.Event) string
- func ValidateConfig(kind string, config *omap.Map) error
- type Dispatcher
- type Error
- type Field
- type Result
- type Type
Constants ¶
const AttemptTimeout = 5 * time.Second
AttemptTimeout per attempt: long enough for a cold lambda, short enough that three attempts stay bounded.
const MaxInFlight = 8
MaxInFlight is concurrent in-flight deliveries across all notifiers.
const MaxQueuedPerNotifier = 200
MaxQueuedPerNotifier is how many events may wait for ONE notifier before the oldest is dropped. Sized for a burst, not for an outage — that is what redelivery is for.
Variables ¶
var DiscordType = chatType("discord", "Discord", "https://discord.com/api/webhooks/…/…", "content")
DiscordType posts `{content}`.
RetryDelays: attempt 1 is immediate; these are the waits BEFORE attempts 2 and 3. Worst case ~21s.
var SlackType = chatType("slack", "Slack", "https://hooks.slack.com/services/T…/B…/…", "text")
SlackType's host is deliberately NOT pinned to hooks.slack.com: Mattermost and Rocket.Chat speak the same `{text}` payload on their own domains.
var Types = []*Type{WebhookType, SlackType, DiscordType}
Types is the registry, in registration order (the order `known types:` lists them).
var WebhookType = &Type{ Kind: "webhook", Signs: true, Label: "HTTP webhook", Fields: []Field{{Key: "url", Label: "URL", Placeholder: "https://example.com/hooks/pstack", Required: true}}, Validate: func(config *omap.Map) error { u, ok := config.Get("url") s, isStr := u.(string) if !ok || !isStr || strings.TrimSpace(s) == "" { return &Error{"a webhook needs a `url`"} } _, err := AssertDeliverableURL(s) return err }, Send: func(ctx context.Context, e events.Event, config *omap.Map, secret string) Result { target := config.GetString("url") body := Envelope(e) headers := [][2]string{ {"content-type", "application/json"}, {"user-agent", "pstack"}, {"x-pstack-event", e.Event}, {"x-pstack-delivery", e.ID}, {"x-pstack-timestamp", strconv.FormatInt(e.At, 10)}, {"x-pstack-signature", Sign(secret, e.At, body)}, } if e.Replay { headers = append(headers, [2]string{"x-pstack-redelivery", "1"}) } return post(ctx, target, headers, body) }, }
WebhookType is the plain signed HTTP webhook. The URL is an address, not a credential — the HMAC secret proves authenticity, so the URL stays readable in the list view.
Functions ¶
func AssertDeliverableURL ¶
AssertDeliverableURL refuses anything but a public http(s) URL (unless PSTACK_NOTIFY_ALLOW_PRIVATE=1).
func Envelope ¶
Envelope is the four fields a receiver gets, and the exact bytes stored for redelivery — SERIALISED EXACTLY ONCE. events.Event marshals to {id,event,at,data}; Replay is `json:"-"`.
func IsPrivateHost ¶
IsPrivateHost: is this host one the control plane should refuse to call?
A classifier, not a regexp: decide what kind of host it is first, then apply the rule for that kind. A DNS name is never tested against IP rules (`fcm.googleapis.com` is not `fc00::`), and an IP literal is never tested against name rules. hostname is as url.Hostname() gives it — bare, brackets already stripped.
func PublicConfig ¶
PublicConfig is a type's config, safe to hand back: fields the type marked Secret become a mask.
func RedactForNotifier ¶
RedactForNotifier redacts a message the way the dispatcher does — every string in config, not just the signing secret, because for a chat webhook the URL is the credential.
func Summarize ¶
Summarize is one human-readable line per event, shared by every chat-shaped type, so Slack and Discord can never describe the same event differently. `data.test === true` is the contract flag from POST /:id/test: without it a test would render as a green "Deploy succeeded" nobody's deploy earned.
Types ¶
type Dispatcher ¶
type Dispatcher struct {
Hooks *webhooks.Webhooks
// RetryDelays and AttemptTimeout default to the package constants; tests shorten them.
RetryDelays []time.Duration
AttemptTimeout time.Duration
// contains filtered or unexported fields
}
Dispatcher delivers events to subscribed notifiers.
mu guards inFlight, busy, queues and order. At most ONE delivery per notifier runs at a time — a broken notifier must degrade itself, not everyone else — and events QUEUE per notifier, bounded: past the cap the OLDEST is dropped and recorded as such. The only goroutine is the delivery itself; Dispatch returns immediately.
func New ¶
func New(hooks *webhooks.Webhooks) *Dispatcher
New makes a dispatcher over a webhooks table.
func (*Dispatcher) Dispatch ¶
func (d *Dispatcher) Dispatch(e events.Event)
Dispatch is the bus listener. Returns immediately; every failure path is contained.
func (*Dispatcher) Queued ¶
func (d *Dispatcher) Queued(notifierID int64) int
Queued is how many events are waiting for a notifier.
func (*Dispatcher) Redeliver ¶
func (d *Dispatcher) Redeliver(row webhooks.NotifierRow, e events.Event)
Redeliver sends this exact event to this notifier again, as a REPLAY — queued like any other delivery and marked, so the receiver can tell a replay from the original.
type Error ¶
type Error struct{ Msg string }
Error is a refused config or an unknown type. The API maps it to 400.
type Field ¶
type Field struct {
Key string `json:"key"`
Label string `json:"label"`
Placeholder string `json:"placeholder"`
Required bool `json:"required"`
// Secret marks CREDENTIAL MATERIAL that must never be returned by a read path: a Slack incoming
// webhook URL is the credential, a plain webhook's url is not. The type knows; nothing else can.
// Genuinely absent on the wire for a plain webhook (rule 2: pointer + omitempty).
Secret *bool `json:"secret,omitempty"`
}
Field is a form field the UI renders for this type's config.
type Type ¶
type Type struct {
Kind string
Label string
Fields []Field
// Signs: does this type use the HMAC signing secret? false for anything whose config already
// carries its credential.
Signs bool
// Validate returns an *Error naming the fix. Called before anything is stored.
Validate func(config *omap.Map) error
// Send delivers one event. CONTRACT: never panics — return Result{OK:false, Error} instead. The
// dispatcher recovers anyway. `data.test === true` marks a TEST delivery.
Send func(ctx context.Context, e events.Event, config *omap.Map, secret string) Result
}
Type is one delivery module.