Something went wrong. Try again.
Go port of clojure riemann
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798package riemann
import ( "sync")
// Subscription represents a client's subscription to a topic.type Subscription struct { id int64 ch chan *Event eval Evaluator Name string // Descriptive name for debugging/logging, e.g., "WS:127.0.0.1:5556"}
// PubSub implements a thread-safe event publishing and subscription registry.type PubSub struct { mu sync.RWMutex subscribers map[string][]*Subscription nextSubID int64 OnDrop func(topic string, sub *Subscription, e *Event) // Callback invoked when an event is dropped}
// NewPubSub creates a new PubSub broker.func NewPubSub() *PubSub { return &PubSub{ subscribers: make(map[string][]*Subscription), }}
// Subscribe registers a new subscriber for a given topic with default buffer size (256) and no name.func (ps *PubSub) Subscribe(topic string, eval Evaluator) (*Subscription, chan *Event) { return ps.SubscribeWithBufferAndName(topic, eval, 256, "")}
// SubscribeWithBufferAndName registers a new subscriber with custom buffer size and client identifier name.func (ps *PubSub) SubscribeWithBufferAndName(topic string, eval Evaluator, bufferSize int, name string) (*Subscription, chan *Event) { ps.mu.Lock() defer ps.mu.Unlock()
if bufferSize <= 0 { bufferSize = 256 }
ch := make(chan *Event, bufferSize) ps.nextSubID++ sub := &Subscription{ id: ps.nextSubID, ch: ch, eval: eval, Name: name, }
ps.subscribers[topic] = append(ps.subscribers[topic], sub) return sub, ch}
// Unsubscribe removes a subscription from a topic and closes its channel.func (ps *PubSub) Unsubscribe(topic string, sub *Subscription) { ps.mu.Lock() defer ps.mu.Unlock()
subs, ok := ps.subscribers[topic] if !ok { return } for i, s := range subs { if s.id == sub.id { // Remove sub from slice ps.subscribers[topic] = append(subs[:i], subs[i+1:]...) close(s.ch) return } }}
// Publish distributes an event to all subscribers matching the topic and evaluator.func (ps *PubSub) Publish(topic string, e *Event) { ps.mu.RLock() defer ps.mu.RUnlock()
subs, ok := ps.subscribers[topic] if !ok { return } for _, sub := range subs { if sub.eval == nil || sub.eval.Evaluate(e) { select { case sub.ch <- e: default: // Buffer full: drop the message and invoke callback if ps.OnDrop != nil { ps.OnDrop(topic, sub, e) } } } }}