SuperCoder/internal/pubsub/broker.go

117 lines
1.7 KiB
Go
Raw Normal View History

2025-03-21 18:20:28 +01:00
package pubsub
import (
"context"
"sync"
)
2025-04-21 13:33:51 +02:00
const bufferSize = 64
2025-03-21 18:20:28 +01:00
type Broker[T any] struct {
2025-04-21 13:33:51 +02:00
subs map[chan Event[T]]struct{}
mu sync.RWMutex
done chan struct{}
subCount int
maxEvents int
2025-03-21 18:20:28 +01:00
}
func NewBroker[T any]() *Broker[T] {
2025-04-21 13:33:51 +02:00
return NewBrokerWithOptions[T](bufferSize, 1000)
}
func NewBrokerWithOptions[T any](channelBufferSize, maxEvents int) *Broker[T] {
2025-03-21 18:20:28 +01:00
b := &Broker[T]{
2025-04-21 13:33:51 +02:00
subs: make(map[chan Event[T]]struct{}),
done: make(chan struct{}),
subCount: 0,
maxEvents: maxEvents,
2025-03-21 18:20:28 +01:00
}
return b
}
func (b *Broker[T]) Shutdown() {
2025-04-21 13:33:51 +02:00
select {
case <-b.done: // Already closed
return
default:
close(b.done)
}
2025-03-21 18:20:28 +01:00
b.mu.Lock()
defer b.mu.Unlock()
for ch := range b.subs {
delete(b.subs, ch)
close(ch)
}
2025-04-21 13:33:51 +02:00
b.subCount = 0
2025-03-21 18:20:28 +01:00
}
func (b *Broker[T]) Subscribe(ctx context.Context) <-chan Event[T] {
b.mu.Lock()
defer b.mu.Unlock()
select {
case <-b.done:
ch := make(chan Event[T])
close(ch)
return ch
default:
}
sub := make(chan Event[T], bufferSize)
b.subs[sub] = struct{}{}
2025-04-21 13:33:51 +02:00
b.subCount++
2025-03-21 18:20:28 +01:00
go func() {
<-ctx.Done()
b.mu.Lock()
defer b.mu.Unlock()
select {
case <-b.done:
return
default:
}
delete(b.subs, sub)
close(sub)
2025-04-21 13:33:51 +02:00
b.subCount--
2025-03-21 18:20:28 +01:00
}()
return sub
}
2025-04-21 13:33:51 +02:00
func (b *Broker[T]) GetSubscriberCount() int {
b.mu.RLock()
defer b.mu.RUnlock()
return b.subCount
}
2025-03-21 18:20:28 +01:00
func (b *Broker[T]) Publish(t EventType, payload T) {
2025-04-21 13:33:51 +02:00
b.mu.RLock()
select {
case <-b.done:
b.mu.RUnlock()
return
default:
}
2025-03-21 18:20:28 +01:00
2025-04-21 13:33:51 +02:00
subscribers := make([]chan Event[T], 0, len(b.subs))
2025-03-21 18:20:28 +01:00
for sub := range b.subs {
2025-04-21 13:33:51 +02:00
subscribers = append(subscribers, sub)
}
b.mu.RUnlock()
event := Event[T]{Type: t, Payload: payload}
for _, sub := range subscribers {
2025-03-21 18:20:28 +01:00
select {
2025-04-21 13:33:51 +02:00
case sub <- event:
default:
2025-03-21 18:20:28 +01:00
}
}
}