Skip to content

Event Bus (core/events) ​

github.com/mmycin/goforge/core/events is a generic, topic-based in-process pub/sub bus with buffered async delivery, synchronous execution, panic recovery, and graceful shutdown draining.


Creating & Configuring a Bus ​

boot/kernel.go provides *events.EventBus automatically via DI and registers bus.Shutdown on Lifecycle.OnStop. To construct one manually (e.g., in tests):

go
bus := events.New(
	events.WithBufferSize(256), // default: 100 per subscriber
	events.WithErrorHandler(func(topic string, err error) {
		log.Error().Str("topic", topic).Err(err).Msg("listener failed")
	}),
)

Listeners (Listener[T], On[T], Off[T]) ​

go
type Listener[T any] interface {
	Handle(ctx context.Context, event T) error
}
  • events.On[T any](bus *EventBus, topic string, listener Listener[T]) — spawns a dedicated goroutine + buffered channel for the subscriber. Deduplicates identical listener instances on the same topic using pointer identity ("%s@%x"), while allowing distinct instances of the same type to coexist.
  • events.Off[T any](bus *EventBus, topic string, listener Listener[T]) — removes the subscriber and closes its channel so its goroutine drains remaining items and exits.
  • bus.ListenerCount(topic string) int — returns active subscriber count for topic.

Dispatching Events ​

Async Fire-and-Forget (Dispatch[T]) ​

go
events.Dispatch(context.WithoutCancel(ctx), bus, TopicCreated, Payload{ID: 42})
  • Holds RLock during non-blocking channel sends (safe against concurrent Off or Shutdown).
  • If a subscriber's buffer is full, that subscriber's event is dropped and errorHandler is invoked with errSubscriberChannelFull (never blocks the HTTP request).
  • Always pass context.WithoutCancel(ctx) when dispatching from an HTTP handler so returning the HTTP response does not cancel in-flight async listeners.

Synchronous (DispatchSync[T]) ​

go
if err := events.DispatchSync(ctx, bus, TopicCreated, payload); err != nil {
	return err
}
  • Delivers to all matching subscribers, blocks until all complete or ctx.Done() fires, and returns errors.Join(errs...).
  • Returns an error immediately if the bus is already shut down.

Panic Recovery & Graceful Shutdown ​

  • invokeSafe recovers any panic inside Listener.Handle(), converts it into an error, passes it to errorHandler (and returns it in DispatchSync).
  • bus.Shutdown(ctx context.Context) error is idempotent: marks the bus closed, closes all subscriber channels, and waits for all queued/in-flight events to finish (or returns ctx.Err() on timeout).

Released under the Apache-2.0 License.