notify

package
v0.38.0 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: MIT, MIT Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const AttemptTimeout = 5 * time.Second

AttemptTimeout per attempt: long enough for a cold lambda, short enough that three attempts stay bounded.

View Source
const MaxInFlight = 8

MaxInFlight is concurrent in-flight deliveries across all notifiers.

View Source
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

View Source
var DiscordType = chatType("discord", "Discord", "https://discord.com/api/webhooks/…/…", "content")

DiscordType posts `{content}`.

View Source
var RetryDelays = []time.Duration{time.Second, 5 * time.Second}

RetryDelays: attempt 1 is immediate; these are the waits BEFORE attempts 2 and 3. Worst case ~21s.

View Source
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.

Types is the registry, in registration order (the order `known types:` lists them).

View Source
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

func AssertDeliverableURL(raw string) (*url.URL, error)

AssertDeliverableURL refuses anything but a public http(s) URL (unless PSTACK_NOTIFY_ALLOW_PRIVATE=1).

func Envelope

func Envelope(e events.Event) []byte

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 IsError

func IsError(err error) bool

IsError reports whether err is a *Error.

func IsPrivateHost

func IsPrivateHost(hostname string) bool

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

func PublicConfig(kind string, config *omap.Map) *omap.Map

PublicConfig is a type's config, safe to hand back: fields the type marked Secret become a mask.

func RedactForNotifier

func RedactForNotifier(message, secret string, config *omap.Map) string

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 Sign

func Sign(secret string, timestamp int64, body []byte) string

Sign is `sha256=` + hex(HMAC-SHA256(secret, "<timestamp>.<body>")).

func Summarize

func Summarize(e events.Event) string

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.

func ValidateConfig

func ValidateConfig(kind string, config *omap.Map) error

ValidateConfig is for POST /api/notifiers — validates without this package knowing the store.

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.

func (*Error) Error

func (e *Error) Error() string

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 Result

type Result struct {
	OK     bool
	Status *int64
	Error  string
}

Result is one attempt's verdict.

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.

func TypeOf

func TypeOf(kind string) (*Type, error)

TypeOf resolves a kind or returns the unknown-type *Error.

Jump to

Keyboard shortcuts

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