telemetry.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. package telemetry
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. "google.golang.org/protobuf/proto"
  7. "google.golang.org/protobuf/types/known/timestamppb"
  8. hthv1 "hth/internal/gen/hth/api/v1"
  9. )
  10. var (
  11. ErrTooManySubscribers = fmt.Errorf("too many subscribers")
  12. ErrTooManyPeerStreams = fmt.Errorf("too many streams for this peer")
  13. )
  14. type SnapshotSub struct {
  15. C <-chan *hthv1.Snapshot
  16. Cancel func()
  17. Dropped func() uint64
  18. ch chan *hthv1.Snapshot
  19. dropped uint64
  20. gap bool
  21. peer string
  22. }
  23. type EventSub struct {
  24. C <-chan *hthv1.Event
  25. Cancel func()
  26. ch chan *hthv1.Event
  27. dropped uint64
  28. gapPending bool
  29. lastContiguousEventID uint64
  30. resumeAfter uint64
  31. peer string
  32. }
  33. type ringItem struct {
  34. ev *hthv1.Event
  35. }
  36. type Hub struct {
  37. mu sync.Mutex
  38. snaps map[uint64]*SnapshotSub
  39. events map[uint64]*EventSub
  40. next uint64
  41. ring []ringItem
  42. ringCap int
  43. subBuf int
  44. maxSubs int
  45. maxPerPeer int
  46. oldestID uint64
  47. newestID uint64
  48. idAlloc func() uint64
  49. }
  50. func (h *Hub) SetIDAlloc(fn func() uint64) {
  51. h.mu.Lock()
  52. h.idAlloc = fn
  53. h.mu.Unlock()
  54. }
  55. func (h *Hub) allocEventID() uint64 {
  56. if h.idAlloc != nil {
  57. id := h.idAlloc()
  58. if id == 0 {
  59. return 1
  60. }
  61. return id
  62. }
  63. if h.newestID == 0 {
  64. return 1
  65. }
  66. return h.newestID + 1
  67. }
  68. func NewHub(ringCap, subBuf, maxSubs, maxPerPeer int) *Hub {
  69. if ringCap <= 0 {
  70. ringCap = 1024
  71. }
  72. if subBuf <= 0 {
  73. subBuf = 8
  74. }
  75. if maxSubs <= 0 {
  76. maxSubs = 64
  77. }
  78. if maxPerPeer <= 0 {
  79. maxPerPeer = 8
  80. }
  81. return &Hub{
  82. snaps: map[uint64]*SnapshotSub{},
  83. events: map[uint64]*EventSub{},
  84. ringCap: ringCap,
  85. subBuf: subBuf,
  86. maxSubs: maxSubs,
  87. maxPerPeer: maxPerPeer,
  88. }
  89. }
  90. func (h *Hub) PublishSnapshot(snap *hthv1.Snapshot, now time.Time) *hthv1.Event {
  91. ev := &hthv1.Event{
  92. EventId: snap.EventId,
  93. Kind: hthv1.EventKind_EVENT_KIND_SNAPSHOT,
  94. WallTime: timestamppb.New(now),
  95. MonotonicNs: snap.MonotonicNs,
  96. DeviceId: snap.DeviceId,
  97. Snapshot: proto.Clone(snap).(*hthv1.Snapshot),
  98. }
  99. h.publishEvent(ev, true)
  100. return ev
  101. }
  102. func (h *Hub) PublishEvent(ev *hthv1.Event) {
  103. h.publishEvent(proto.Clone(ev).(*hthv1.Event), ev.Kind == hthv1.EventKind_EVENT_KIND_SNAPSHOT)
  104. }
  105. func (h *Hub) publishEvent(ev *hthv1.Event, asSnap bool) {
  106. h.mu.Lock()
  107. defer h.mu.Unlock()
  108. if ev.EventId == 0 {
  109. ev.EventId = h.allocEventID()
  110. }
  111. h.ring = append(h.ring, ringItem{ev: ev})
  112. if len(h.ring) > h.ringCap {
  113. h.ring = h.ring[len(h.ring)-h.ringCap:]
  114. }
  115. if len(h.ring) > 0 {
  116. h.oldestID = h.ring[0].ev.EventId
  117. h.newestID = h.ring[len(h.ring)-1].ev.EventId
  118. }
  119. if asSnap && ev.Snapshot != nil {
  120. for _, sub := range h.snaps {
  121. cp := proto.Clone(ev.Snapshot).(*hthv1.Snapshot)
  122. if sub.gap {
  123. cp.DataGap = true
  124. cp.DroppedTelemetryCount = sub.dropped
  125. }
  126. select {
  127. case sub.ch <- cp:
  128. sub.gap = false
  129. default:
  130. sub.dropped++
  131. sub.gap = true
  132. }
  133. }
  134. }
  135. for _, sub := range h.events {
  136. cp := proto.Clone(ev).(*hthv1.Event)
  137. if sub.gapPending {
  138. cp.DeliveryGap = h.deliveryGapLocked(sub)
  139. }
  140. select {
  141. case sub.ch <- cp:
  142. sub.lastContiguousEventID = ev.EventId
  143. sub.gapPending = false
  144. sub.dropped = 0
  145. default:
  146. sub.dropped++
  147. sub.gapPending = true
  148. }
  149. }
  150. }
  151. func (h *Hub) SubscribeSnapshots(resumeAfter uint64) (*SnapshotSub, []*hthv1.Snapshot, *hthv1.Event) {
  152. sub, replay, gap, _ := h.SubscribeSnapshotsPeer(resumeAfter, "")
  153. return sub, replay, gap
  154. }
  155. func (h *Hub) SubscribeSnapshotsPeer(resumeAfter uint64, peer string) (*SnapshotSub, []*hthv1.Snapshot, *hthv1.Event, error) {
  156. h.mu.Lock()
  157. defer h.mu.Unlock()
  158. if err := h.admitLocked(peer); err != nil {
  159. return nil, nil, nil, err
  160. }
  161. h.next++
  162. id := h.next
  163. ch := make(chan *hthv1.Snapshot, h.subBuf)
  164. sub := &SnapshotSub{C: ch, ch: ch, peer: peer}
  165. var gap *hthv1.Event
  166. var replay []*hthv1.Snapshot
  167. if resumeAfter > 0 {
  168. if h.oldestID > 0 && resumeAfter < h.oldestID-1 {
  169. gap = &hthv1.Event{
  170. Kind: hthv1.EventKind_EVENT_KIND_DATA_GAP,
  171. Message: "resume_after_event_id older than ring",
  172. ResumeAfterEventId: resumeAfter,
  173. DroppedCount: h.oldestID - resumeAfter - 1,
  174. LastContiguousEventId: resumeAfter,
  175. }
  176. h.stampGapLocked(gap)
  177. resumeAfter = h.oldestID - 1
  178. }
  179. for _, it := range h.ring {
  180. if it.ev.EventId > resumeAfter && it.ev.Kind == hthv1.EventKind_EVENT_KIND_SNAPSHOT && it.ev.Snapshot != nil {
  181. replay = append(replay, proto.Clone(it.ev.Snapshot).(*hthv1.Snapshot))
  182. }
  183. }
  184. }
  185. sub.Cancel = func() {
  186. h.mu.Lock()
  187. defer h.mu.Unlock()
  188. if _, ok := h.snaps[id]; ok {
  189. delete(h.snaps, id)
  190. close(ch)
  191. }
  192. }
  193. sub.Dropped = func() uint64 {
  194. h.mu.Lock()
  195. defer h.mu.Unlock()
  196. return sub.dropped
  197. }
  198. h.snaps[id] = sub
  199. return sub, replay, gap, nil
  200. }
  201. func (h *Hub) SubscribeEvents(resumeAfter uint64) (*EventSub, []*hthv1.Event, *hthv1.Event) {
  202. sub, replay, gap, _ := h.SubscribeEventsPeer(resumeAfter, "")
  203. return sub, replay, gap
  204. }
  205. func (h *Hub) SubscribeEventsPeer(resumeAfter uint64, peer string) (*EventSub, []*hthv1.Event, *hthv1.Event, error) {
  206. h.mu.Lock()
  207. defer h.mu.Unlock()
  208. if err := h.admitLocked(peer); err != nil {
  209. return nil, nil, nil, err
  210. }
  211. h.next++
  212. id := h.next
  213. ch := make(chan *hthv1.Event, h.subBuf)
  214. sub := &EventSub{C: ch, ch: ch, peer: peer, lastContiguousEventID: resumeAfter, resumeAfter: resumeAfter}
  215. var gap *hthv1.Event
  216. var replay []*hthv1.Event
  217. var resumeGap *hthv1.DeliveryGap
  218. if resumeAfter > 0 {
  219. if h.oldestID > 0 && resumeAfter < h.oldestID-1 {
  220. resumeGap = &hthv1.DeliveryGap{
  221. DroppedCount: h.oldestID - resumeAfter - 1,
  222. LastContiguousEventId: resumeAfter,
  223. RequestedResumeAfterEventId: resumeAfter,
  224. OldestAvailableEventId: h.oldestID,
  225. }
  226. resumeAfter = h.oldestID - 1
  227. }
  228. for _, it := range h.ring {
  229. if it.ev.EventId > resumeAfter {
  230. cp := proto.Clone(it.ev).(*hthv1.Event)
  231. if resumeGap != nil && len(replay) == 0 {
  232. cp.DeliveryGap = resumeGap
  233. resumeGap = nil
  234. }
  235. replay = append(replay, cp)
  236. }
  237. }
  238. if resumeGap != nil {
  239. sub.gapPending = true
  240. sub.dropped = resumeGap.DroppedCount
  241. }
  242. if len(replay) > 0 {
  243. sub.lastContiguousEventID = replay[len(replay)-1].EventId
  244. }
  245. }
  246. sub.Cancel = func() {
  247. h.mu.Lock()
  248. defer h.mu.Unlock()
  249. if _, ok := h.events[id]; ok {
  250. delete(h.events, id)
  251. close(ch)
  252. }
  253. }
  254. h.events[id] = sub
  255. return sub, replay, gap, nil
  256. }
  257. func (h *Hub) deliveryGapLocked(sub *EventSub) *hthv1.DeliveryGap {
  258. if sub == nil {
  259. return nil
  260. }
  261. return &hthv1.DeliveryGap{
  262. DroppedCount: sub.dropped,
  263. LastContiguousEventId: sub.lastContiguousEventID,
  264. RequestedResumeAfterEventId: sub.resumeAfter,
  265. OldestAvailableEventId: h.oldestID,
  266. }
  267. }
  268. func (h *Hub) stampGapLocked(gap *hthv1.Event) {
  269. if gap == nil {
  270. return
  271. }
  272. // Snapshot-subscribe still returns a descriptor Event. It must not
  273. // consume a global event_id used by the live stream.
  274. if gap.WallTime == nil {
  275. now := time.Now()
  276. gap.WallTime = timestamppb.New(now)
  277. if gap.MonotonicNs == 0 {
  278. gap.MonotonicNs = uint64(now.UnixNano())
  279. }
  280. }
  281. }
  282. func (h *Hub) admitLocked(peer string) error {
  283. if len(h.snaps)+len(h.events) >= h.maxSubs {
  284. return ErrTooManySubscribers
  285. }
  286. if peer != "" && h.peerStreamCountLocked(peer) >= h.maxPerPeer {
  287. return ErrTooManyPeerStreams
  288. }
  289. return nil
  290. }
  291. func (h *Hub) peerStreamCountLocked(peer string) int {
  292. n := 0
  293. for _, s := range h.snaps {
  294. if s.peer == peer {
  295. n++
  296. }
  297. }
  298. for _, s := range h.events {
  299. if s.peer == peer {
  300. n++
  301. }
  302. }
  303. return n
  304. }
  305. func (h *Hub) SubCount() (snaps, events int) {
  306. h.mu.Lock()
  307. defer h.mu.Unlock()
  308. return len(h.snaps), len(h.events)
  309. }