bus

package
v0.9.14 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: 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 bus embeds a NATS server with JetStream inside the Outpost daemon to give every managed app a durable pub/sub event bus using CloudEvents 1.0.

Index

Constants

View Source
const (
	EnvURL   = "OUTPOST_BUS_URL"
	EnvCreds = "OUTPOST_BUS_CREDS"
	EnvApp   = "OUTPOST_APP"
)

Environment variables injected into every managed app when the bus is running.

View Source
const (
	// StreamEvents holds all app events on outpost.<app>.<object>.<action>[...].
	StreamEvents = "OUTPOST"
	// StreamDLQ holds dead-lettered events on outpost.dlq.<app>.
	StreamDLQ = "OUTPOST_DLQ"
)

JetStream stream names.

View Source
const CloudEventsSpecVersion = "1.0"

CloudEventsSpecVersion is the CloudEvents specification version Outpost uses.

View Source
const DefaultAckWait = 30 * time.Second

DefaultAckWait is how long a consumer has to ack a delivered message.

View Source
const DefaultDuplicateWindow = 2 * time.Minute

DefaultDuplicateWindow is the JetStream publisher-side deduplication window.

View Source
const DefaultMaxDeliver = 5

DefaultMaxDeliver is 5 failed deliveries before an event moves to the DLQ.

View Source
const DefaultRetention = 7 * 24 * time.Hour

DefaultRetention is 7 days, per the event bus spec.

View Source
const MaxSubjectTokens = 6

MaxSubjectTokens is the longest event subject the OUTPOST stream stores.

Variables

This section is empty.

Functions

func AppOwner

func AppOwner(subject string) string

AppOwner extracts the app name from a concrete subject "outpost.<app>.<obj>.<act>".

func ConsumerName

func ConsumerName(app, filterSubject string) string

ConsumerName returns the deterministic JetStream durable consumer name for app's subscription to filterSubject.

func MatchSubject

func MatchSubject(pattern, subject string) bool

MatchSubject reports whether a concrete NATS subject matches a NATS pattern (supporting single-token '*' and trailing multi-token '>').

func ValidateAppName

func ValidateAppName(app string) error

ValidateAppName reports whether app can be given a place on the bus. Its name becomes a subject token in outpost.<app>.> and a file name under creds/, so a dot, a wildcard or a path separator in it would reach into another app's subjects or out of that directory; and outpost.dlq.* is the dead-letter queue's.

func ValidatePattern

func ValidatePattern(pattern string) error

ValidatePattern checks a subject filter an operator asked to watch, such as outpost.> or outpost.*.notification.>: it has to stay under outpost., with whole tokens, '*' and a trailing '>' only.

func ValidateSubject

func ValidateSubject(subject string) error

ValidateSubject checks that subject is a valid concrete Outpost event subject (outpost.<app>.<object>.<action>[...]) and not in the reserved DLQ namespace.

Types

type AppDecl

type AppDecl struct {
	Name       string
	Publishes  []string
	Subscribes []string
}

AppDecl declares an app's bus subscriptions for credential minting and durable consumer provisioning.

type ConsumerInfo

type ConsumerInfo struct {
	Stream         string    `json:"stream"`
	Name           string    `json:"name"`
	App            string    `json:"app,omitempty"`
	FilterSubject  string    `json:"filter_subject"`
	Delivered      uint64    `json:"delivered"`
	AckFloor       uint64    `json:"ack_floor"`
	NumAckPending  int       `json:"num_ack_pending"`
	NumPending     uint64    `json:"num_pending"`
	NumRedelivered int       `json:"num_redelivered"`
	NumWaiting     int       `json:"num_waiting"`
	MaxDeliver     int       `json:"max_deliver"`
	Created        time.Time `json:"created"`
}

ConsumerInfo summarizes a durable JetStream consumer and its current lag.

type DLQEntry

type DLQEntry struct {
	ID              string    `json:"id"`
	Sequence        uint64    `json:"sequence"`
	App             string    `json:"app"`
	Consumer        string    `json:"consumer"`
	OriginalSubject string    `json:"original_subject"`
	OriginalSeq     uint64    `json:"original_seq"`
	Deliveries      uint64    `json:"deliveries"`
	FailedAt        time.Time `json:"failed_at"`
	Event           Event     `json:"event"`
	Raw             string    `json:"raw,omitempty"`
}

DLQEntry is one dead-lettered event stored in OUTPOST_DLQ under outpost.dlq.<app>.

type Event

type Event struct {
	SpecVersion     string          `json:"specversion"`
	ID              string          `json:"id"`
	Source          string          `json:"source"`
	Type            string          `json:"type"`
	Time            time.Time       `json:"time"`
	Subject         string          `json:"subject,omitempty"`
	DataContentType string          `json:"datacontenttype,omitempty"`
	Data            json.RawMessage `json:"data,omitempty"`
	OutpostUser     string          `json:"outpostuser,omitempty"`
	Extensions      map[string]any  `json:"-"`
}

Event is a CloudEvents 1.0 envelope in JSON structured mode.

func NewEvent

func NewEvent(app, object, action, version, user, subjectID string, data any) (Event, error)

NewEvent constructs a CloudEvents 1.0 event with generated ID and UTC timestamp.

func (Event) MarshalJSON

func (e Event) MarshalJSON() ([]byte, error)

MarshalJSON encodes Event in CloudEvents 1.0 JSON structured mode, preserving any extra extension attributes at the top level.

func (*Event) UnmarshalJSON

func (e *Event) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes a CloudEvents 1.0 JSON structured payload, keeping any unknown extension attributes in Extensions.

func (Event) Validate

func (e Event) Validate() error

Validate checks that e carries the required CloudEvents 1.0 attributes.

type EventQuery

type EventQuery struct {
	Stream   string    `json:"stream,omitempty"`
	Subject  string    `json:"subject,omitempty"`
	User     string    `json:"user,omitempty"`
	Type     string    `json:"type,omitempty"`
	Contains string    `json:"contains,omitempty"`
	Since    time.Time `json:"since,omitzero"`
	Until    time.Time `json:"until,omitzero"`
	Limit    int       `json:"limit,omitempty"`
}

EventQuery filters browsed events.

type EventRecord

type EventRecord struct {
	Stream      string    `json:"stream,omitempty"`
	Sequence    uint64    `json:"sequence,omitempty"`
	Subject     string    `json:"subject"`
	PublishedAt time.Time `json:"published_at"`
	Event       Event     `json:"event"`
	Raw         string    `json:"raw,omitempty"`
}

EventRecord is a single event read from a stream or live tail.

type Options

type Options struct {
	// DataDir is where JetStream storage, NKey seeds, and app .creds files live.
	DataDir string
	// Listen is host:port for NATS client connections (default 127.0.0.1:47904).
	// Use "127.0.0.1:0" or ":0" for an ephemeral port in tests.
	Listen string
	// Retention is how long streams retain events (default 7 days).
	Retention time.Duration
	// MaxDeliver is how many failed deliveries move an event to the DLQ (default 5).
	MaxDeliver int
	// AckWait is how long consumers have to ack an event before redelivery (default 30s).
	AckWait time.Duration
	// Logf receives operational log lines.
	Logf func(format string, v ...any)
}

Options configures the embedded event bus.

type Overview

type Overview struct {
	URL     string       `json:"url"`
	Running bool         `json:"running"`
	Streams []StreamInfo `json:"streams"`
}

Overview is the bus status and its streams.

type PublishRequest

type PublishRequest struct {
	Subject   string          `json:"subject"`
	Source    string          `json:"source,omitempty"`
	Type      string          `json:"type,omitempty"`
	SubjectID string          `json:"subject_id,omitempty"`
	User      string          `json:"user,omitempty"`
	Data      json.RawMessage `json:"data,omitempty"`
}

PublishRequest is the input to Publish for test or operator events.

type PublishResult

type PublishResult struct {
	ID       string `json:"id"`
	Subject  string `json:"subject"`
	Stream   string `json:"stream"`
	Sequence uint64 `json:"sequence"`
	Event    Event  `json:"event"`
}

PublishResult is the confirmation returned by Publish.

type ReplayResult

type ReplayResult struct {
	DLQID    string `json:"dlq_id"`
	EventID  string `json:"event_id"`
	App      string `json:"app"`
	Subject  string `json:"subject"`
	Sequence uint64 `json:"sequence"`
}

ReplayResult describes a replayed dead-letter entry.

type Service

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

Service owns the embedded NATS server, JetStream streams, per-app credentials, durable consumers, and dead-letter router. It is safe for concurrent use.

func Open

func Open(opts Options) (*Service, error)

Open starts the embedded NATS server with JetStream, initializes the OUTPOST and OUTPOST_DLQ streams, and starts the dead-letter advisory router.

func (*Service) AdminConn

func (s *Service) AdminConn() *nats.Conn

AdminConn returns the daemon's internal NATS connection for built-in subscribers such as the notification service.

func (*Service) Close

func (s *Service) Close() error

Close stops the DLQ router, closes the internal NATS client, and shuts down the embedded NATS server cleanly.

func (*Service) Consumers

func (s *Service) Consumers(ctx context.Context, streamName string) ([]ConsumerInfo, error)

Consumers lists consumers and their lag for stream (default OUTPOST).

func (*Service) CredsPath

func (s *Service) CredsPath(app string) (string, bool)

CredsPath returns the on-disk .creds path for app if provisioned.

func (*Service) DLQList

func (s *Service) DLQList(ctx context.Context, app string, limit int) ([]DLQEntry, error)

DLQList returns dead-letter entries, optionally filtered to one app, newest first.

func (*Service) DLQReplay

func (s *Service) DLQReplay(ctx context.Context, id string) (ReplayResult, error)

DLQReplay republishes a dead-letter entry back onto its original subject on OUTPOST and removes it from OUTPOST_DLQ. id may be the DLQ entry ID, the CloudEvents event ID, or the DLQ stream sequence number.

func (*Service) EnsureApp

func (s *Service) EnsureApp(ctx context.Context, app string, subscribes []string) (credsPath string, rev string, err error)

EnsureApp ensures credentials and durable consumers exist for a single app.

func (*Service) EnsureInternalConsumer

func (s *Service) EnsureInternalConsumer(ctx context.Context, owner, consumerName, filterSubject string) (jetstream.Consumer, error)

EnsureInternalConsumer creates or updates a durable pull consumer on OUTPOST for an internal Outpost component (such as the shared push notification service), returning the consumer handle.

func (*Service) Events

func (s *Service) Events(ctx context.Context, q EventQuery) ([]EventRecord, error)

Events browses and searches stored events in a stream (default OUTPOST), returning newest matching events first.

func (*Service) JetStream

func (s *Service) JetStream() jetstream.JetStream

JetStream returns the daemon's internal JetStream handle.

func (*Service) Overview

func (s *Service) Overview(ctx context.Context) (Overview, error)

Overview returns the bus URL, running state, and all streams.

func (*Service) Publish

func (s *Service) Publish(ctx context.Context, req PublishRequest) (PublishResult, error)

Publish publishes a CloudEvents 1.0 event to the bus on behalf of an operator or test tool, filling standard CloudEvents defaults where omitted.

func (*Service) Resolve

func (s *Service) Resolve(service string) (map[string]string, string)

Resolve returns the OUTPOST_BUS_URL, OUTPOST_BUS_CREDS, and OUTPOST_APP environment variables for service, matching supervisor.Secrets.Resolve. If SyncApps hasn't seen service yet, it provisions default publish-only creds.

func (*Service) Streams

func (s *Service) Streams(ctx context.Context) ([]StreamInfo, error)

Streams lists every JetStream stream on the Outpost bus.

func (*Service) SyncApps

func (s *Service) SyncApps(ctx context.Context, decls []AppDecl) error

SyncApps reconciles per-app NATS credentials and durable JetStream consumers to match the declared app manifests. Apps removed from decls have their old user keys revoked and creds files removed.

func (*Service) Tail

func (s *Service) Tail(ctx context.Context, subject string, fn func(EventRecord) error) error

Tail streams live events matching subject (default "outpost.>") to fn until ctx ends or fn returns a non-nil error.

func (*Service) URL

func (s *Service) URL() string

URL is the NATS connection URL apps receive in OUTPOST_BUS_URL.

type StreamInfo

type StreamInfo struct {
	Name        string        `json:"name"`
	Description string        `json:"description,omitempty"`
	Subjects    []string      `json:"subjects"`
	Messages    uint64        `json:"messages"`
	Bytes       uint64        `json:"bytes"`
	FirstSeq    uint64        `json:"first_seq"`
	LastSeq     uint64        `json:"last_seq"`
	FirstTime   time.Time     `json:"first_time,omitzero"`
	LastTime    time.Time     `json:"last_time,omitzero"`
	Consumers   int           `json:"consumers"`
	MaxAge      time.Duration `json:"max_age"`
}

StreamInfo summarizes a JetStream stream's configuration and live state.

Jump to

Keyboard shortcuts

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