| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349 |
- package telemetry
- import (
- "fmt"
- "sync"
- "time"
- "google.golang.org/protobuf/proto"
- "google.golang.org/protobuf/types/known/timestamppb"
- hthv1 "hth/internal/gen/hth/api/v1"
- )
- var (
- ErrTooManySubscribers = fmt.Errorf("too many subscribers")
- ErrTooManyPeerStreams = fmt.Errorf("too many streams for this peer")
- ErrResumeOutOfRange = fmt.Errorf("resume_after_event_id is in the future")
- )
- type SnapshotSub struct {
- C <-chan *hthv1.Snapshot
- Cancel func()
- Dropped func() uint64
- ch chan *hthv1.Snapshot
- dropped uint64
- gap bool
- peer string
- }
- type EventSub struct {
- C <-chan *hthv1.Event
- Cancel func()
- ch chan *hthv1.Event
- dropped uint64
- gapPending bool
- lastContiguousEventID uint64
- resumeAfter uint64
- peer string
- }
- type ringItem struct {
- ev *hthv1.Event
- }
- type Hub struct {
- mu sync.Mutex
- snaps map[uint64]*SnapshotSub
- events map[uint64]*EventSub
- next uint64
- ring []ringItem
- ringCap int
- subBuf int
- maxSubs int
- maxPerPeer int
- oldestID uint64
- newestID uint64
- idAlloc func() uint64
- }
- func (h *Hub) SetIDAlloc(fn func() uint64) {
- h.mu.Lock()
- h.idAlloc = fn
- h.mu.Unlock()
- }
- func (h *Hub) allocEventID() uint64 {
- if h.idAlloc != nil {
- id := h.idAlloc()
- if id == 0 {
- return 1
- }
- return id
- }
- if h.newestID == 0 {
- return 1
- }
- return h.newestID + 1
- }
- func (h *Hub) NewestEventID() uint64 {
- h.mu.Lock()
- defer h.mu.Unlock()
- return h.newestID
- }
- func NewHub(ringCap, subBuf, maxSubs, maxPerPeer int) *Hub {
- if ringCap <= 0 {
- ringCap = 1024
- }
- if subBuf <= 0 {
- subBuf = 8
- }
- if maxSubs <= 0 {
- maxSubs = 64
- }
- if maxPerPeer <= 0 {
- maxPerPeer = 8
- }
- return &Hub{
- snaps: map[uint64]*SnapshotSub{},
- events: map[uint64]*EventSub{},
- ringCap: ringCap,
- subBuf: subBuf,
- maxSubs: maxSubs,
- maxPerPeer: maxPerPeer,
- }
- }
- func (h *Hub) PublishSnapshot(snap *hthv1.Snapshot, now time.Time) *hthv1.Event {
- ev := &hthv1.Event{
- EventId: snap.EventId,
- Kind: hthv1.EventKind_EVENT_KIND_SNAPSHOT,
- WallTime: timestamppb.New(now),
- MonotonicNs: snap.MonotonicNs,
- DeviceId: snap.DeviceId,
- Snapshot: proto.Clone(snap).(*hthv1.Snapshot),
- }
- h.publishEvent(ev, true)
- return ev
- }
- func (h *Hub) PublishEvent(ev *hthv1.Event) {
- h.publishEvent(proto.Clone(ev).(*hthv1.Event), ev.Kind == hthv1.EventKind_EVENT_KIND_SNAPSHOT)
- }
- func (h *Hub) publishEvent(ev *hthv1.Event, asSnap bool) {
- h.mu.Lock()
- defer h.mu.Unlock()
- if ev.EventId == 0 {
- ev.EventId = h.allocEventID()
- } else if ev.EventId <= h.newestID {
- if ev.SourceEventId == 0 {
- ev.SourceEventId = ev.EventId
- }
- ev.EventId = h.allocEventID()
- }
- h.ring = append(h.ring, ringItem{ev: ev})
- if len(h.ring) > h.ringCap {
- h.ring = h.ring[len(h.ring)-h.ringCap:]
- }
- if len(h.ring) > 0 {
- h.oldestID = h.ring[0].ev.EventId
- h.newestID = h.ring[len(h.ring)-1].ev.EventId
- }
- if asSnap && ev.Snapshot != nil {
- for _, sub := range h.snaps {
- cp := proto.Clone(ev.Snapshot).(*hthv1.Snapshot)
- if sub.gap {
- cp.DataGap = true
- cp.DroppedTelemetryCount = sub.dropped
- }
- select {
- case sub.ch <- cp:
- sub.gap = false
- default:
- sub.dropped++
- sub.gap = true
- }
- }
- }
- for _, sub := range h.events {
- cp := proto.Clone(ev).(*hthv1.Event)
- if sub.gapPending {
- cp.DeliveryGap = h.deliveryGapLocked(sub)
- }
- select {
- case sub.ch <- cp:
- sub.lastContiguousEventID = ev.EventId
- sub.gapPending = false
- sub.dropped = 0
- default:
- sub.dropped++
- sub.gapPending = true
- }
- }
- }
- func (h *Hub) SubscribeSnapshots(resumeAfter uint64) (*SnapshotSub, []*hthv1.Snapshot, *hthv1.Event) {
- sub, replay, gap, _ := h.SubscribeSnapshotsPeer(resumeAfter, "")
- return sub, replay, gap
- }
- func (h *Hub) SubscribeSnapshotsPeer(resumeAfter uint64, peer string) (*SnapshotSub, []*hthv1.Snapshot, *hthv1.Event, error) {
- h.mu.Lock()
- defer h.mu.Unlock()
- if resumeAfter > h.newestID {
- return nil, nil, nil, fmt.Errorf("%w: resume_after_event_id=%d newest_event_id=%d", ErrResumeOutOfRange, resumeAfter, h.newestID)
- }
- if err := h.admitLocked(peer); err != nil {
- return nil, nil, nil, err
- }
- h.next++
- id := h.next
- ch := make(chan *hthv1.Snapshot, h.subBuf)
- sub := &SnapshotSub{C: ch, ch: ch, peer: peer}
- var gap *hthv1.Event
- var replay []*hthv1.Snapshot
- if resumeAfter > 0 {
- if h.oldestID > 0 && resumeAfter < h.oldestID-1 {
- gap = &hthv1.Event{
- Kind: hthv1.EventKind_EVENT_KIND_DATA_GAP,
- Message: "resume_after_event_id older than ring",
- ResumeAfterEventId: resumeAfter,
- DroppedCount: h.oldestID - resumeAfter - 1,
- LastContiguousEventId: resumeAfter,
- }
- h.stampGapLocked(gap)
- resumeAfter = h.oldestID - 1
- }
- for _, it := range h.ring {
- if it.ev.EventId > resumeAfter && it.ev.Kind == hthv1.EventKind_EVENT_KIND_SNAPSHOT && it.ev.Snapshot != nil {
- replay = append(replay, proto.Clone(it.ev.Snapshot).(*hthv1.Snapshot))
- }
- }
- }
- sub.Cancel = func() {
- h.mu.Lock()
- defer h.mu.Unlock()
- if _, ok := h.snaps[id]; ok {
- delete(h.snaps, id)
- close(ch)
- }
- }
- sub.Dropped = func() uint64 {
- h.mu.Lock()
- defer h.mu.Unlock()
- return sub.dropped
- }
- h.snaps[id] = sub
- return sub, replay, gap, nil
- }
- func (h *Hub) SubscribeEvents(resumeAfter uint64) (*EventSub, []*hthv1.Event, *hthv1.Event) {
- sub, replay, gap, _ := h.SubscribeEventsPeer(resumeAfter, "")
- return sub, replay, gap
- }
- func (h *Hub) SubscribeEventsPeer(resumeAfter uint64, peer string) (*EventSub, []*hthv1.Event, *hthv1.Event, error) {
- h.mu.Lock()
- defer h.mu.Unlock()
- if resumeAfter > h.newestID {
- return nil, nil, nil, fmt.Errorf("%w: resume_after_event_id=%d newest_event_id=%d", ErrResumeOutOfRange, resumeAfter, h.newestID)
- }
- if err := h.admitLocked(peer); err != nil {
- return nil, nil, nil, err
- }
- h.next++
- id := h.next
- ch := make(chan *hthv1.Event, h.subBuf)
- sub := &EventSub{C: ch, ch: ch, peer: peer, lastContiguousEventID: resumeAfter, resumeAfter: resumeAfter}
- var gap *hthv1.Event
- var replay []*hthv1.Event
- var resumeGap *hthv1.DeliveryGap
- if resumeAfter > 0 {
- if h.oldestID > 0 && resumeAfter < h.oldestID-1 {
- resumeGap = &hthv1.DeliveryGap{
- DroppedCount: h.oldestID - resumeAfter - 1,
- LastContiguousEventId: resumeAfter,
- RequestedResumeAfterEventId: resumeAfter,
- OldestAvailableEventId: h.oldestID,
- }
- resumeAfter = h.oldestID - 1
- }
- for _, it := range h.ring {
- if it.ev.EventId > resumeAfter {
- cp := proto.Clone(it.ev).(*hthv1.Event)
- if resumeGap != nil && len(replay) == 0 {
- cp.DeliveryGap = resumeGap
- resumeGap = nil
- }
- replay = append(replay, cp)
- }
- }
- if resumeGap != nil {
- sub.gapPending = true
- sub.dropped = resumeGap.DroppedCount
- }
- if len(replay) > 0 {
- sub.lastContiguousEventID = replay[len(replay)-1].EventId
- }
- }
- sub.Cancel = func() {
- h.mu.Lock()
- defer h.mu.Unlock()
- if _, ok := h.events[id]; ok {
- delete(h.events, id)
- close(ch)
- }
- }
- h.events[id] = sub
- return sub, replay, gap, nil
- }
- func (h *Hub) deliveryGapLocked(sub *EventSub) *hthv1.DeliveryGap {
- if sub == nil {
- return nil
- }
- return &hthv1.DeliveryGap{
- DroppedCount: sub.dropped,
- LastContiguousEventId: sub.lastContiguousEventID,
- RequestedResumeAfterEventId: sub.resumeAfter,
- OldestAvailableEventId: h.oldestID,
- }
- }
- func (h *Hub) stampGapLocked(gap *hthv1.Event) {
- if gap == nil {
- return
- }
- // Snapshot-subscribe still returns a descriptor Event. It must not
- // consume a global event_id used by the live stream.
- if gap.WallTime == nil {
- now := time.Now()
- gap.WallTime = timestamppb.New(now)
- if gap.MonotonicNs == 0 {
- gap.MonotonicNs = uint64(now.UnixNano())
- }
- }
- }
- func (h *Hub) admitLocked(peer string) error {
- if len(h.snaps)+len(h.events) >= h.maxSubs {
- return ErrTooManySubscribers
- }
- if peer != "" && h.peerStreamCountLocked(peer) >= h.maxPerPeer {
- return ErrTooManyPeerStreams
- }
- return nil
- }
- func (h *Hub) peerStreamCountLocked(peer string) int {
- n := 0
- for _, s := range h.snaps {
- if s.peer == peer {
- n++
- }
- }
- for _, s := range h.events {
- if s.peer == peer {
- n++
- }
- }
- return n
- }
- func (h *Hub) SubCount() (snaps, events int) {
- h.mu.Lock()
- defer h.mu.Unlock()
- return len(h.snaps), len(h.events)
- }
|