broker

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 8 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 broker routes events to the subscribers that asked for them.

A Subscriber is one connected stream, for example an open `GET /v1/events` connection. It receives only the messages published to topics it explicitly subscribed to, and it can add and remove topics at any time while it stays connected. Topics are matched exactly: there are no wildcards, so a subscriber never receives anything it did not name.

Events and messages

An Event is something that happened and knows nothing about topics. A Message is an event addressed to a topic, which is what a subscriber receives. Deciding which topics an event goes to is the publisher's job, and this package does not know about sessions or any other part of the daemon.

Slow subscribers

Each subscriber has a bounded buffer. A subscriber that does not keep up is closed with ErrOverflow instead of silently losing messages, because a stream with a gap cannot be trusted. It must reconnect, resubscribe and reload its state.

Topic ring buffers & replay

Each topic maintains a ring buffer (DefaultRingSize capacity by default, configurable via WithTopicBufferSize). Subscriber.SubscribeSince replays messages with ID greater than a given cursor from the ring buffer, enabling gap-free reconnection. If the cursor is older than the oldest retained message, the subscription fails with ErrNeedSync.

Integration

github.com/masterkeysrd/tasksmith/internal/daemon/session.Session creates one Subscriber per connected event stream and registers it with the Broker. The session publishes [EventEntryAdded], [EventChunk], [EventPermissionRequested], and [EventCompleted] events to per-session topics, and Broker.DeleteTopic releases the ring buffer when a session ends.

Index

Constants

View Source
const (

	// DefaultRingSize is the default topic ring buffer capacity.
	DefaultRingSize = 128

	// MaxTopics bounds the number of topics a single subscriber may hold.
	MaxTopics = 256
)

Variables

View Source
var (
	// ErrClosed is the reason of a subscriber that was closed by its owner.
	ErrClosed = errors.New("broker: subscriber closed")

	// ErrOverflow is the reason of a subscriber that was closed because it
	// could not keep up and its buffer filled. It has missed messages, so it
	// must resubscribe and reload its state rather than carry on.
	ErrOverflow = errors.New("broker: subscriber fell behind")

	// ErrNotRegistered is returned when a subscriber that is not registered
	// with a [Broker] subscribes to a topic.
	ErrNotRegistered = errors.New("broker: subscriber is not registered")

	// ErrExists is returned when a subscriber ID is already registered.
	ErrExists = errors.New("broker: subscriber ID already registered")

	// ErrInvalidTopic is returned for a topic that is not a well-formed name.
	ErrInvalidTopic = errors.New("broker: invalid topic")

	// ErrTooManyTopics is returned when a subscription would exceed
	// [MaxTopics].
	ErrTooManyTopics = errors.New("broker: too many topics")

	// ErrInvalidCursor is returned when a non-empty since cursor is not a canonical UUIDv7.
	ErrInvalidCursor = errors.New("broker: invalid cursor")

	// ErrNeedSync is returned when a subscriber's since cursor is older than the
	// oldest retained message in a topic's ring buffer.
	ErrNeedSync = errors.New("broker: subscriber cursor is out of date")
)

Functions

func ValidateTopic

func ValidateTopic(topic string) error

ValidateTopic reports whether topic is a well-formed name: non-empty dot-separated segments with no whitespace and no wildcard characters. Topics are matched exactly, so there are no patterns.

Types

type Broker

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

Broker delivers published events to the subscribers that subscribed to their exact topic. It keeps an index from topic to subscribers, so publishing touches only the subscribers that asked for it.

Lock order is the broker's lock, then a subscriber's lock.

func New

func New(opts ...Option) *Broker

New returns a broker with no subscribers.

func (*Broker) Add

func (b *Broker) Add(sub *Subscriber) error

Add registers a subscriber. It returns ErrExists if the ID is taken or the subscriber already belongs to a broker, and the close reason if it was closed.

func (*Broker) DeleteTopic

func (b *Broker) DeleteTopic(topic string)

DeleteTopic deletes the ring buffer for topic so deleted sessions do not leak memory.

func (*Broker) Get

func (b *Broker) Get(id string) (*Subscriber, bool)

Get returns the registered subscriber with the given ID.

func (*Broker) HasSubscribers

func (b *Broker) HasSubscribers(topic string) bool

HasSubscribers reports whether any subscriber is currently subscribed to topic. Sessions use it to tell whether a client is attached that could answer an interactive prompt.

func (*Broker) Len

func (b *Broker) Len() int

Len returns the number of registered subscribers.

func (*Broker) Publish

func (b *Broker) Publish(topic string, event Event)

Publish delivers event to every subscriber subscribed to topic. A subscriber whose buffer is full is closed with ErrOverflow and removed, so a slow subscriber can never silently miss part of a stream.

func (*Broker) Remove

func (b *Broker) Remove(sub *Subscriber)

Remove unregisters a subscriber, drops all of its subscriptions and closes it with ErrClosed. It is safe to call more than once.

type Event

type Event interface {
	// EventType names the kind of event, such as "chunk". It is what a receiver
	// switches on to read the event; it is not a topic.
	EventType() string
}

Event is something that happened. It carries no routing information: which subscribers receive it is decided by the topics it is published to.

type Message

type Message struct {
	ID    string
	Topic string
	Event Event
}

Message is an Event addressed to a topic. It is what a Subscriber receives.

type Option

type Option func(*Broker)

Option configures a Broker.

func WithTopicBufferSize

func WithTopicBufferSize(fn func(topic string) int) Option

WithTopicBufferSize configures a function that returns the ring buffer capacity for a given topic. Values <= 0 fall back to DefaultRingSize.

type Subscriber

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

Subscriber is one connected stream of messages. It receives only the messages published to topics it explicitly subscribed to.

func NewSubscriber

func NewSubscriber(id string) *Subscriber

NewSubscriber returns a subscriber with the given ID and no subscriptions. Register it with Broker.Add before subscribing.

func (*Subscriber) Ch

func (s *Subscriber) Ch() <-chan Message

Ch returns the channel messages are delivered on. It is never closed: stop reading when Subscriber.Done is closed.

func (*Subscriber) Close

func (s *Subscriber) Close()

Close unregisters the subscriber and releases its subscriptions. It is safe to call more than once and from any goroutine.

func (*Subscriber) Done

func (s *Subscriber) Done() <-chan struct{}

Done is closed when the subscriber is closed.

func (*Subscriber) Err

func (s *Subscriber) Err() error

Err explains why the subscriber was closed: ErrClosed when its owner closed it, ErrOverflow when it fell behind. It is nil while open.

func (*Subscriber) ID

func (s *Subscriber) ID() string

ID returns the subscriber's identifier.

func (*Subscriber) Subscribe

func (s *Subscriber) Subscribe(topics ...string) ([]string, error)

Subscribe adds topics and returns the ones that were not already held. The subscriber must be registered with a broker. If any topic is invalid, or the topic limit would be exceeded, none are added.

func (*Subscriber) SubscribeSince

func (s *Subscriber) SubscribeSince(since string, topics ...string) ([]string, error)

SubscribeSince adds topics and replays messages with ID > since. The subscriber must be registered with a broker.

func (*Subscriber) Topics

func (s *Subscriber) Topics() []string

Topics returns the topics the subscriber is subscribed to, sorted.

func (*Subscriber) Unsubscribe

func (s *Subscriber) Unsubscribe(topics ...string) []string

Unsubscribe removes topics and returns the ones that were held. Topics the subscriber was not subscribed to are ignored.

Jump to

Keyboard shortcuts

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