Documentation
¶
Index ¶
- Constants
- type Event
- type EventBus
- func (eb *EventBus) Emit(ctx context.Context, event Event) error
- func (eb *EventBus) EmitAsync(ctx context.Context, event Event)
- func (eb *EventBus) On(eventType string, handler EventHandler)
- func (eb *EventBus) Snapshot(eventType string) []EventHandler
- func (eb *EventBus) Subscribe(eventType string, handler EventHandler) (cancel func())
- type EventHandler
Constants ¶
const ( EntityCreated = "entity.created" EntityUpdated = "entity.updated" EntityDeleted = "entity.deleted" )
Pre-defined event types for entity lifecycle.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Event ¶
type Event struct {
Type string `json:"type"`
Data any `json:"data,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
Event represents something that happened in the system.
type EventBus ¶
type EventBus struct {
// contains filtered or unexported fields
}
EventBus provides in-process publish/subscribe event delivery.
Both On (no cancel) and Subscribe (returns cancel) are supported. Handlers are stored in registration order so Emit short-circuits deterministically on the first error.
func (*EventBus) Emit ¶
Emit publishes an event synchronously to all subscribers and returns the first error from a handler.
A handler that panics is recovered so a buggy subscriber can't bring down the request that triggered the event. The panic is swallowed (the event bus is fire-and-iterate, not a critical-path return channel); callers that need hard failures should propagate them through the returned error instead. A nil entry — which shouldn't happen given Subscribe's guard, but kept for defense-in-depth against direct map manipulation — is skipped.
func (*EventBus) EmitAsync ¶
EmitAsync publishes an event in a goroutine (fire-and-forget).
Each handler runs inside emitSafe so a panicking subscriber takes itself down without crashing the process. Nil entries are skipped defensively.
func (*EventBus) On ¶
func (eb *EventBus) On(eventType string, handler EventHandler)
On subscribes a handler to the given event type. The handler stays registered for the lifetime of the bus; use Subscribe instead when you need to remove the handler later.
func (*EventBus) Snapshot ¶
func (eb *EventBus) Snapshot(eventType string) []EventHandler
Snapshot returns a copy of the handlers registered for the event type, in registration order, so emission doesn't hold the lock while user code runs.
func (*EventBus) Subscribe ¶
func (eb *EventBus) Subscribe(eventType string, handler EventHandler) (cancel func())
Subscribe registers a handler and returns a cancel function. Calling cancel removes the handler. Cancel is safe to call multiple times.
A nil handler is refused — the bus never retains a nil subscription, so a later Emit can't crash by invoking nothing. The returned cancel is a no-op in that case.