package fed import ( "context" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" ) // SubscribeVisits returns the legitimate visits of the nodes. func (h *Hub) SubscribeVisits() (<-chan store.VisitMsg, func()) { ch := make(chan store.VisitMsg, 64) h.lmu.Lock() h.vsubs[ch] = struct{}{} h.lmu.Unlock() return ch, func() { h.lmu.Lock() delete(h.vsubs, ch) h.lmu.Unlock() } } func (h *Hub) publishVisit(m store.VisitMsg) { h.lmu.Lock() defer h.lmu.Unlock() for ch := range h.vsubs { select { case ch <- m: default: } } } // Subscribe returns the live events of the nodes; call stop when done. func (h *Hub) Subscribe() (<-chan store.LiveEvent, func()) { ch := make(chan store.LiveEvent, 64) h.lmu.Lock() h.subs[ch] = struct{}{} h.lmu.Unlock() return ch, func() { h.lmu.Lock() delete(h.subs, ch) h.lmu.Unlock() } } // Recent returns the newest live events of the nodes, newest first. func (h *Hub) Recent(n int) []store.LiveEvent { h.lmu.Lock() defer h.lmu.Unlock() total := len(h.recent) out := make([]store.LiveEvent, 0, min(n, total)) for i := 0; i < total && len(out) < n; i++ { idx := ((h.head-1-i)%total + total) % total out = append(out, h.recent[idx]) } return out } func (h *Hub) publish(e store.LiveEvent) { h.lmu.Lock() defer h.lmu.Unlock() if len(h.recent) < liveBuf { h.recent = append(h.recent, e) } else { h.recent[h.head] = e h.head = (h.head + 1) % liveBuf } for ch := range h.subs { select { case ch <- e: default: // slow client: drop } } } // Run keeps the live relay of every node (also those created later) until ctx is done. func (h *Hub) Run(ctx context.Context) { if h == nil { return } t := time.NewTicker(time.Second) defer t.Stop() defer func() { h.lmu.Lock() for _, stop := range h.attach { stop() } h.lmu.Unlock() }() for { h.sync(ctx) select { case <-ctx.Done(): return case <-t.C: } } } // sync starts the relay of the backends that appeared since the last call. func (h *Hub) sync(ctx context.Context) { for _, b := range h.backends("") { h.lmu.Lock() _, ok := h.attach[b.Name()] h.lmu.Unlock() if ok { continue } ev, stopEv := b.Subscribe() vis, stopVis := b.SubscribeVisits() cctx, cancel := context.WithCancel(ctx) h.lmu.Lock() h.attach[b.Name()] = func() { cancel(); stopEv(); stopVis() } h.lmu.Unlock() go func() { for { select { case <-cctx.Done(): return case e := <-ev: h.publish(e) case v := <-vis: h.publishVisit(v) } } }() } }