notify

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: Apache-2.0 Imports: 13 Imported by: 6 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

Index

Constants

This section is empty.

Variables

View Source
var ErrManagerStarted = errors.New("manager already started")
View Source
var ErrManagerStopped = errors.New("manager stopped")

ErrManagerStopped means the manager no longer accepts notifications.

Functions

func DefaultRetryPolicy added in v0.1.0

func DefaultRetryPolicy(result DeliveryResult, err error) bool

DefaultRetryPolicy applies Notifykit's conservative transient-failure policy.

It retries classified transport failures, HTTP-style 408 and 429 responses, and 5xx responses. Other failures are not retried by default.

func IsPermanent added in v0.1.0

func IsPermanent(err error) bool

IsPermanent reports whether err was marked with Permanent.

func IsTransport added in v0.1.0

func IsTransport(err error) bool

IsTransport reports whether err was marked with Transport.

Permanent classification takes precedence when an error chain contains both.

func Permanent added in v0.1.0

func Permanent(err error) error

Permanent marks err as non-retryable for Notifykit's built-in retry policies.

Permanent classification takes precedence over transport classification. Custom policies remain free to inspect or retry the wrapped error.

func RetryOnError added in v0.1.0

func RetryOnError(_ DeliveryResult, err error) bool

RetryOnError retries every non-permanent error.

This matches Notifykit's original retry behavior and is useful when a target has no richer result or error classification.

func RetryOnNetworkError added in v0.1.0

func RetryOnNetworkError(_ DeliveryResult, err error) bool

RetryOnNetworkError retries non-timeout transport failures.

func RetryOnServerError added in v0.1.0

func RetryOnServerError(result DeliveryResult, err error) bool

RetryOnServerError retries status codes from 500 through 599.

func RetryOnTimeout added in v0.1.0

func RetryOnTimeout(_ DeliveryResult, err error) bool

RetryOnTimeout retries transport failures that represent a timeout.

func Send

func Send(ctx context.Context, notification Notification, receivers Receivers, logger *slog.Logger) error

Send synchronously delivers notification to the configured receivers.

Send is a convenience helper for simple use cases that do not need Manager's in-memory queue or asynchronous dispatcher. It resolves receivers using the same routing rule as Manager: ReceiverRouter.ReceiverIDs returns receiver map keys, and nil or empty receiver IDs send to all configured receivers.

If logger is nil, a discard logger is used. Send returns an error when the context, notification, receiver configuration, or resolved receiver set is invalid, or when one or more targets fail.

func SendTo

func SendTo(ctx context.Context, notification Notification, receivers ...*Receiver) error

SendTo synchronously delivers notification to receivers without requiring a map.

SendTo is a convenience wrapper around Send for simple usage. It builds a Receivers map from receivers, uses a discard logger, resolves receiver routing the same way as Send, and returns after delivery completes.

func Transport added in v0.1.0

func Transport(err error) error

Transport marks err as a transport failure for Notifykit's built-in retry policies.

Built-in targets use this for network and response-stream failures. Permanent errors are never reclassified as transport failures.

Types

type Completion added in v0.2.0

type Completion struct {
	QueueID        uuid.UUID
	NotificationID string
	Err            error
}

Completion reports the final outcome of one queued notification. Err can be inspected with errors.As for DeliveryError. Nil means delivery succeeded.

type DeliveryError added in v0.2.0

type DeliveryError struct {
	ReceiverID  ReceiverID
	TargetType  string
	TargetIndex int
	Attempts    int
	Result      DeliveryResult
	Err         error
}

DeliveryError identifies a failed target within its receiver. TargetIndex is zero-based. Result may contain sensitive response data and is never included in Error().

func (*DeliveryError) Error added in v0.2.0

func (e *DeliveryError) Error() string

func (*DeliveryError) Unwrap added in v0.2.0

func (e *DeliveryError) Unwrap() error

type DeliveryResult

type DeliveryResult struct {
	// Status is a target-specific delivery status such as sent or failed.
	Status string

	// StatusCode is the target response status code when one exists.
	StatusCode int

	// Response contains target-specific response details.
	//
	// Generic Notifykit loggers do not log this value because target responses
	// may contain sensitive data such as webhook URLs, tokens, echoed payloads,
	// or authentication diagnostics.
	Response string

	// RetryAfter requests a minimum delay before the next retry.
	//
	// Targets may set this from transport-specific hints such as HTTP Retry-After.
	RetryAfter time.Duration
}

DeliveryResult captures target response details returned by delivery targets.

type Manager

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

Manager owns notification queueing and dispatch infrastructure.

func NewManager

func NewManager(receivers Receivers, logger *slog.Logger, opts ...ManagerOption) (*Manager, error)

NewManager constructs a notification manager for queued asynchronous delivery.

The manager owns an in-memory store, buffered mailbox, dispatcher, and delivery engine. Enqueued notifications are routed by ReceiverRouter.ReceiverIDs: returned values are matched against the receiver map keys, and nil or empty receiver IDs send to all configured receivers.

If receivers is nil, the manager starts with no configured receivers. If logger is nil, a discard logger is used.

func (*Manager) Enqueue

func (m *Manager) Enqueue(ctx context.Context, n Notification) (uuid.UUID, error)

Enqueue stores a notification and queues it for delivery, returning its UUIDv7 queue ID.

func (*Manager) Receivers

func (m *Manager) Receivers() []*Receiver

Receivers returns snapshots sorted by ID. Structs, target slices and top-level CustomData maps are copied; targets and nested custom values remain shared.

func (*Manager) Shutdown added in v0.2.0

func (m *Manager) Shutdown(ctx context.Context) error

Shutdown stops admission and drains accepted notifications. If ctx expires, active deliveries are canceled and queued notifications are discarded with ErrManagerStopped completion outcomes. Canceling Start's context also aborts delivery. Shutdown before Start discards queued work. Managers cannot restart. Call Wait to observe completion after a timed-out Shutdown.

func (*Manager) Start

func (m *Manager) Start(ctx context.Context) error

Start begins asynchronous delivery processing.

Start launches the configured worker count. Each worker reads from the same queue, so different notifications may be delivered concurrently. Start may only be called once. Calling Start again returns ErrManagerStarted.

func (*Manager) Wait added in v0.2.0

func (m *Manager) Wait(ctx context.Context) error

Wait waits for all workers and completion callbacks to finish after shutdown or cancellation. It does not initiate shutdown. Custom targets must honor ctx.

type ManagerOption added in v0.0.8

type ManagerOption func(*managerConfig)

func WithOnComplete added in v0.2.0

func WithOnComplete(fn func(Completion)) ManagerOption

WithOnComplete installs a callback invoked once after delivery or discard. It runs synchronously on a worker or the shutdown cleanup goroutine; it must be concurrency-safe, return promptly, and must not wait for manager shutdown or enqueue into the same manager.

func WithQueueCapacity added in v0.2.0

func WithQueueCapacity(capacity int) ManagerOption

WithQueueCapacity bounds admitted queued notifications (excluding active deliveries). Values below one are rejected by NewManager. The default is 128.

func WithWorkers added in v0.0.8

func WithWorkers(workers int) ManagerOption

WithWorkers configures how many queued notifications may be processed concurrently.

Values less than 1 are ignored. The default is one worker. Targets used with more than one worker must be safe for concurrent calls.

type Notification

type Notification interface {
	ID() string
	Data(receiver string, customData map[string]any, subject string) any
}

Notification describes one notification and its template data. ID must return a non-empty application-owned identifier that remains stable for the notification. Enqueued notifications must remain immutable through completion. Data must support concurrent calls when notifications are reused across deliveries.

A notification may optionally implement ReceiverRouter to select specific receivers. Notifications that do not implement ReceiverRouter are sent to all configured receivers.

type Notifier

type Notifier interface {
	Enqueue(ctx context.Context, notification Notification) (uuid.UUID, error)
}

Notifier enqueues notifications for delivery.

type Payload

type Payload struct {
	// Notification is the original application notification.
	Notification Notification

	// Receiver is the receiver display name passed to template data.
	Receiver string

	// CustomData contains receiver-scoped custom template data.
	// Top-level maps are copied; nested values must remain immutable.
	CustomData map[string]any
}

Payload is the receiver-scoped notification payload given to targets.

func (Payload) Data

func (p Payload) Data(subject string) any

Data returns notification template data for this receiver and subject.

func (Payload) ID

func (p Payload) ID() string

ID returns the application-owned notification identifier.

type Receiver

type Receiver struct {
	// ID is the receiver map key used for routing.
	//
	// NewManager and Send fill this from the Receivers map key when it is unset.
	ID ReceiverID

	// Name is the display name passed to notification template data.
	//
	// NewManager and Send default Name to the receiver ID when it is unset.
	Name string

	// Retry controls retry behavior for all targets on this receiver.
	Retry RetryConfig

	// Targets contains the delivery targets for this receiver.
	Targets []Target

	// CustomData contains receiver-scoped custom template data.
	// Top-level maps are copied; nested values must remain immutable.
	CustomData map[string]any
}

Receiver describes runtime delivery configuration.

func NewReceiver

func NewReceiver(id ReceiverID, targets ...Target) *Receiver

NewReceiver constructs a receiver with id and optional targets.

The receiver ID is the routing key used by ReceiverRouter.ReceiverIDs and Receivers maps. Name defaults to the ID during delivery when it is not set.

func (*Receiver) WithCustomData added in v0.0.11

func (r *Receiver) WithCustomData(customData map[string]any) *Receiver

WithCustomData sets receiver-scoped custom template data and returns r.

func (*Receiver) WithName

func (r *Receiver) WithName(name string) *Receiver

WithName sets the receiver display name and returns r.

The display name is passed to notification template data as the receiver name. It is not used as the routing ID.

func (*Receiver) WithRetry

func (r *Receiver) WithRetry(cfg RetryConfig) *Receiver

WithRetry sets the receiver retry configuration and returns r.

func (*Receiver) WithTargets

func (r *Receiver) WithTargets(targets ...Target) *Receiver

WithTargets appends targets to the receiver and returns r.

type ReceiverID

type ReceiverID string

ReceiverID identifies a receiver in a Receivers map.

Notification routing uses receiver IDs, not Receiver.Name. Receiver.Name is a display/runtime payload value, while ReceiverID is the stable map key used by ReceiverIDs and receiver lookup.

type ReceiverRouter

type ReceiverRouter interface {
	ReceiverIDs() []ReceiverID
}

ReceiverRouter optionally routes a notification to receiver IDs.

Returning nil or an empty slice sends to all configured receivers.

type Receivers

type Receivers map[ReceiverID]*Receiver

Receivers maps receiver IDs to receiver configuration.

func NewReceivers

func NewReceivers(receivers ...*Receiver) Receivers

NewReceivers constructs a receiver map from receiver values.

Nil receivers are ignored. If duplicate IDs are provided, the later receiver wins. Receivers with an empty ID are included under the empty key and will only be selected when all receivers are used or an empty ID is requested.

type RetryConfig

type RetryConfig struct {
	// Count is the number of retries after the initial attempt.
	//
	// For example, Count 2 means up to 3 total attempts.
	Count int

	// Backoff is the initial wait duration before retrying.
	//
	// Each later retry wait doubles this duration until MaxBackoff caps it.
	// If Backoff is zero or negative, retries happen immediately.
	Backoff time.Duration

	// MaxBackoff caps retry wait durations.
	//
	// If MaxBackoff is zero or negative, retry waits are not capped.
	MaxBackoff time.Duration

	// Jitter randomizes each local backoff between zero and its calculated delay.
	//
	// This reduces synchronized retries when many receivers fail at once.
	Jitter bool

	// Policy decides whether a failed target delivery should be retried.
	//
	// A nil policy disables retries.
	Policy RetryPolicy
}

RetryConfig defines retry behavior for a receiver.

type RetryPolicy added in v0.1.0

type RetryPolicy func(result DeliveryResult, err error) bool

RetryPolicy decides whether a failed delivery should be retried.

result contains target-specific delivery details such as an HTTP status code. err is the error returned by the target.

func AnyRetryPolicy added in v0.1.0

func AnyRetryPolicy(policies ...RetryPolicy) RetryPolicy

AnyRetryPolicy combines policies and retries when any policy accepts the failure.

func RetryOnStatusCode added in v0.1.0

func RetryOnStatusCode(codes ...int) RetryPolicy

RetryOnStatusCode returns a policy that retries the listed status codes.

type Target

type Target interface {
	Send(ctx context.Context, payload Payload) (DeliveryResult, error)
	Type() string
}

Target delivers a notification payload to one destination. Target configuration must remain immutable during delivery; implementations used by multiple workers must support concurrent Send calls.

Jump to

Keyboard shortcuts

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