Files
deployment-manager/internal/events/bus.go
2026-02-01 20:22:29 +05:30

44 lines
659 B
Go

package events
import (
"context"
"log"
)
type Bus struct {
subscribers map[chan *Event]struct{}
}
func NewBus() *Bus {
return &Bus{
subscribers: make(map[chan *Event]struct{}),
}
}
func (b *Bus) Subscribe(ctx context.Context) chan *Event {
ch := make(chan *Event, 100)
b.subscribers[ch] = struct{}{}
go func() {
<-ctx.Done()
b.unsubscribe(ch)
close(ch)
}()
return ch
}
func (b *Bus) Publish(event *Event) {
for ch := range b.subscribers {
select {
case ch <- event:
default:
log.Printf("Event channel full, dropping event: %s", event.ID)
}
}
}
func (b *Bus) unsubscribe(ch chan *Event) {
delete(b.subscribers, ch)
}