44 lines
949 B
Go
44 lines
949 B
Go
package watch
|
|
|
|
import "sync"
|
|
|
|
// broker fans out change notifications to any number of subscribed SSE
|
|
// clients.
|
|
type broker struct {
|
|
mu sync.Mutex
|
|
clients map[chan struct{}]struct{}
|
|
}
|
|
|
|
func newBroker() *broker {
|
|
return &broker{clients: make(map[chan struct{}]struct{})}
|
|
}
|
|
|
|
// subscribe registers a new client and returns the channel it will receive
|
|
// notifications on. The caller must call unsubscribe when done.
|
|
func (b *broker) subscribe() chan struct{} {
|
|
ch := make(chan struct{}, 1)
|
|
b.mu.Lock()
|
|
b.clients[ch] = struct{}{}
|
|
b.mu.Unlock()
|
|
return ch
|
|
}
|
|
|
|
func (b *broker) unsubscribe(ch chan struct{}) {
|
|
b.mu.Lock()
|
|
delete(b.clients, ch)
|
|
b.mu.Unlock()
|
|
close(ch)
|
|
}
|
|
|
|
// notify wakes every subscribed client. Clients that are not currently
|
|
// waiting are skipped rather than blocked on.
|
|
func (b *broker) notify() {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
for ch := range b.clients {
|
|
select {
|
|
case ch <- struct{}{}:
|
|
default:
|
|
}
|
|
}
|
|
}
|