package fed import ( "context" "fmt" "net/url" "sync" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" ) const ( studyTTL = 30 * time.Second studyMax = 8 // cached studies per peer ) type studyCached struct { at time.Time s store.PeerStudy } func studyKey(q store.PeriodQuery) string { return fmt.Sprintf("%d-%d|%s|%s|%s|%d", q.From, q.To, q.IP, q.Cat, q.Fam, q.Gap) } // StudiesFor asks the online peers (or one) for their period and metrics // study of a window, on demand, cached for 30 s. The answers are sanitized // and carry the configured peer name. func (h *Hub) StudiesFor(ctx context.Context, q store.PeriodQuery, only string) map[string]store.PeerStudy { out := map[string]store.PeerStudy{} var mu sync.Mutex var wg sync.WaitGroup key := studyKey(q) for _, p := range h.Peers { if only != "" && only != p.Name { continue } h.mu.RLock() st := h.state[p.Name] online := st.online var hit *store.PeerStudy if c := st.studies[key]; c != nil && time.Since(c.at) < studyTTL { s := c.s hit = &s } h.mu.RUnlock() if !online { continue } if hit != nil { out[p.Name] = *hit continue } wg.Add(1) go func(p Peer) { defer wg.Done() v := url.Values{} v.Set("from", fmt.Sprint(q.From)) v.Set("to", fmt.Sprint(q.To)) for k, x := range map[string]string{"ip": q.IP, "cat": q.Cat, "fam": q.Fam} { if x != "" { v.Set(k, x) } } if q.Gap > 0 { v.Set("gap", fmt.Sprint(q.Gap)) } var s store.PeerStudy if _, err := h.get(ctx, p, "/api/v1/peer/period?"+v.Encode(), &s); err != nil || !s.Sanitize(p.Name) { return } h.mu.Lock() st := h.state[p.Name] if st.studies == nil || len(st.studies) >= studyMax { st.studies = map[string]*studyCached{} } st.studies[key] = &studyCached{time.Now(), s} h.mu.Unlock() mu.Lock() out[p.Name] = s mu.Unlock() }(p) } wg.Wait() return out }