Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
4.2 KB
Raw Blame
package events

import (
	"log/slog"
	"sync"
)

// ChannelReactionTarget retains the non-secret cleanup anchor when a transaction
// deletes the delivery row. It is internal bus metadata, never a client payload.
type ChannelReactionTarget struct {
	ChannelType    string
	InstallationID string
	MessageID      string
}

// Event represents a domain event published by handlers or services.
type Event struct {
	Type        string // e.g. "issue:created", "inbox:new"
	WorkspaceID string // routes to correct Hub room
	ActorType   string // "member", "agent", or "system"
	ActorID     string
	Payload     any // JSON-serializable, same shape as current WS payloads

	// Optional scope hints used by the realtime fanout layer to route the
	// event to a more specific scope than `workspace:{WorkspaceID}`. When set
	// these tell the listener which Redis stream / Hub room to publish on
	// without re-deserializing Payload. See MUL-1138 phase 1.
	TaskID                string
	ChatSessionID         string
	ChannelReactionTarget *ChannelReactionTarget `json:"-"`

	// ChatSessionOwnerID is the creator of the chat session the event belongs
	// to. A chat session is creator-private, so the realtime layer delivers
	// chat events and chat-task transcript events only to this user, and drops
	// them when it is empty rather than falling back to workspace fanout.
	ChatSessionOwnerID string

	// MemberPrivateUserID marks an event as private to one member of
	// WorkspaceID, such as their own preferences or a private saved view. The
	// realtime layer delivers it only to that user's connections bound to
	// WorkspaceID.
	MemberPrivateUserID string

	// ToolDetailsRestricted marks a task:message from an agent that restricts
	// its tool inputs and outputs to ToolDetailReaders (user ids). Every other
	// recipient, and every consumer that cannot tell recipients apart, must
	// use protocol.TaskMessagePayload.WithoutToolDetails().
	ToolDetailsRestricted bool
	ToolDetailReaders     map[string]bool
}

// Handler is a function that processes an event.
type Handler func(Event)

// Bus is an in-process synchronous pub/sub event bus.
type Bus struct {
	mu             sync.RWMutex
	listeners      map[string][]Handler
	globalHandlers []Handler
}

// New creates a new event bus.
func New() *Bus {
	return &Bus{
		listeners: make(map[string][]Handler),
	}
}

// Subscribe registers a handler for a given event type.
// Handlers are called synchronously in registration order.
func (b *Bus) Subscribe(eventType string, h Handler) {
	b.mu.Lock()
	defer b.mu.Unlock()
	b.listeners[eventType] = append(b.listeners[eventType], h)
}

// SubscriberCount reports how many type-specific handlers are registered for
// an event type. It exists for wiring guards: a subscriber that is never
// registered fails silently — the events keep flowing and nobody reads them —
// so "is anything listening" has to be assertable from outside the bus.
// Global (SubscribeAll) handlers are not counted; they answer a different
// question.
func (b *Bus) SubscriberCount(eventType string) int {
	b.mu.RLock()
	defer b.mu.RUnlock()
	return len(b.listeners[eventType])
}

// SubscribeAll registers a handler that receives ALL events regardless of type.
// Global handlers are called after type-specific handlers.
func (b *Bus) SubscribeAll(h Handler) {
	b.mu.Lock()
	defer b.mu.Unlock()
	b.globalHandlers = append(b.globalHandlers, h)
}

// Publish dispatches an event to all registered handlers for that event type.
// Type-specific handlers run first, then global (SubscribeAll) handlers.
// Each handler is called synchronously. Panics in individual handlers are
// recovered so one failing handler does not prevent others from executing.
func (b *Bus) Publish(e Event) {
	b.mu.RLock()
	handlers := b.listeners[e.Type]
	globals := b.globalHandlers
	b.mu.RUnlock()

	for _, h := range handlers {
		func() {
			defer func() {
				if r := recover(); r != nil {
					slog.Error("panic in event listener", "event_type", e.Type, "recovered", r)
				}
			}()
			h(e)
		}()
	}

	for _, h := range globals {
		func() {
			defer func() {
				if r := recover(); r != nil {
					slog.Error("panic in global event listener", "event_type", e.Type, "recovered", r)
				}
			}()
			h(e)
		}()
	}
}