// Package hub fans notifications out to live subscribers, such as a // dashboard's stream. A note carries only what changed, never work: a // subscriber that falls behind is cut off and resyncs from its cursor, so // nothing depends on a note arriving. package hub import "sync" // buffer is how many notes a subscriber may fall behind before it is cut off. const buffer = 32 // WorkTopic carries a note whenever a run or an approval request moves, so a // mounted view re-reads what is running or waiting on a person. const WorkTopic = "work" // Note says something on a topic changed. Seq is the stream position a // subscriber reads from to catch up. type Note struct { Topic string `json:"topic"` Seq int64 `json:"seq"` } // Hub holds the live subscribers. type Hub struct { mu sync.Mutex subs map[chan Note]string } // New returns an empty hub. func New() *Hub { return &Hub{subs: map[chan Note]string{}} } // Publish sends n to every subscriber of its topic. A subscriber whose buffer // is full is closed rather than waited for. func (h *Hub) Publish(n Note) { h.mu.Lock() defer h.mu.Unlock() for ch, topic := range h.subs { if topic != n.Topic { continue } select { case ch <- n: default: delete(h.subs, ch) close(ch) } } } // Subscribe returns a channel of notes on topic, closed if the subscriber // falls behind, and a function that ends the subscription. func (h *Hub) Subscribe(topic string) (<-chan Note, func()) { ch := make(chan Note, buffer) h.mu.Lock() h.subs[ch] = topic h.mu.Unlock() return ch, func() { h.mu.Lock() defer h.mu.Unlock() if _, ok := h.subs[ch]; ok { delete(h.subs, ch) close(ch) } } }