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 fortopic.
Dispatching Events
Async Fire-and-Forget (Dispatch[T])
go
events.Dispatch(context.WithoutCancel(ctx), bus, TopicCreated, Payload{ID: 42})- Holds
RLockduring non-blocking channel sends (safe against concurrentOfforShutdown). - If a subscriber's buffer is full, that subscriber's event is dropped and
errorHandleris invoked witherrSubscriberChannelFull(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 returnserrors.Join(errs...). - Returns an error immediately if the bus is already shut down.
Panic Recovery & Graceful Shutdown
invokeSaferecovers any panic insideListener.Handle(), converts it into anerror, passes it toerrorHandler(and returns it inDispatchSync).bus.Shutdown(ctx context.Context) erroris idempotent: marks the bus closed, closes all subscriber channels, and waits for all queued/in-flight events to finish (or returnsctx.Err()on timeout).
