telemetry.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. h.ring = append(h.ring, ringItem{ev: ev})
  109. if len(h.ring) > h.ringCap {
  110. h.ring = h.ring[len(h.ring)-h.ringCap:]
  111. }
  112. if len(h.ring) > 0 {
  113. h.oldestID = h.ring[0].ev.EventId
  114. h.newestID = h.ring[len(h.ring)-1].ev.EventId
  115. }
  116. if asSnap && ev.Snapshot != nil {
  117. for _, sub := range h.snaps {
  118. cp := proto.Clone(ev.Snapshot).(*hthv1.Snapshot)
  119. if sub.gap {
  120. cp.DataGap = true
  121. cp.DroppedTelemetryCount = sub.dropped
  122. }
  123. select {
  124. case sub.ch <- cp:
  125. sub.gap = false
  126. default:
  127. sub.dropped++
  128. sub.gap = true
  129. }
  130. }
  131. }
  132. for _, sub := range h.events {
  133. cp := proto.Clone(ev).(*hthv1.Event)
  134. if sub.gapPending {
  135. cp.DeliveryGap = h.deliveryGapLocked(sub)
  136. }
  137. select {
  138. case sub.ch <- cp:
  139. sub.lastContiguousEventID = ev.EventId
  140. sub.gapPending = false
  141. sub.dropped = 0
  142. default:
  143. sub.dropped++
  144. sub.gapPending = true
  145. }
  146. }
  147. }
  148. func (h *Hub) SubscribeSnapshots(resumeAfter uint64) (*SnapshotSub, []*hthv1.Snapshot, *hthv1.Event) {
  149. sub, replay, gap, _ := h.SubscribeSnapshotsPeer(resumeAfter, "")
  150. return sub, replay, gap
  151. }
  152. func (h *Hub) SubscribeSnapshotsPeer(resumeAfter uint64, peer string) (*SnapshotSub, []*hthv1.Snapshot, *hthv1.Event, error) {
  153. h.mu.Lock()
  154. defer h.mu.Unlock()
  155. if err := h.admitLocked(peer); err != nil {
  156. return nil, nil, nil, err
  157. }
  158. h.next++
  159. id := h.next
  160. ch := make(chan *hthv1.Snapshot, h.subBuf)
  161. sub := &SnapshotSub{C: ch, ch: ch, peer: peer}
  162. var gap *hthv1.Event
  163. var replay []*hthv1.Snapshot
  164. if resumeAfter > 0 {
  165. if h.oldestID > 0 && resumeAfter < h.oldestID-1 {
  166. gap = &hthv1.Event{
  167. Kind: hthv1.EventKind_EVENT_KIND_DATA_GAP,
  168. Message: "resume_after_event_id older than ring",
  169. ResumeAfterEventId: resumeAfter,
  170. DroppedCount: h.oldestID - resumeAfter - 1,
  171. LastContiguousEventId: resumeAfter,
  172. }
  173. h.stampGapLocked(gap)
  174. resumeAfter = h.oldestID - 1
  175. }
  176. for _, it := range h.ring {
  177. if it.ev.EventId > resumeAfter && it.ev.Kind == hthv1.EventKind_EVENT_KIND_SNAPSHOT && it.ev.Snapshot != nil {
  178. replay = append(replay, proto.Clone(it.ev.Snapshot).(*hthv1.Snapshot))
  179. }
  180. }
  181. }
  182. sub.Cancel = func() {
  183. h.mu.Lock()
  184. defer h.mu.Unlock()
  185. if _, ok := h.snaps[id]; ok {
  186. delete(h.snaps, id)
  187. close(ch)
  188. }
  189. }
  190. sub.Dropped = func() uint64 {
  191. h.mu.Lock()
  192. defer h.mu.Unlock()
  193. return sub.dropped
  194. }
  195. h.snaps[id] = sub
  196. return sub, replay, gap, nil
  197. }
  198. func (h *Hub) SubscribeEvents(resumeAfter uint64) (*EventSub, []*hthv1.Event, *hthv1.Event) {
  199. sub, replay, gap, _ := h.SubscribeEventsPeer(resumeAfter, "")
  200. return sub, replay, gap
  201. }
  202. func (h *Hub) SubscribeEventsPeer(resumeAfter uint64, peer string) (*EventSub, []*hthv1.Event, *hthv1.Event, error) {
  203. h.mu.Lock()
  204. defer h.mu.Unlock()
  205. if err := h.admitLocked(peer); err != nil {
  206. return nil, nil, nil, err
  207. }
  208. h.next++
  209. id := h.next
  210. ch := make(chan *hthv1.Event, h.subBuf)
  211. sub := &EventSub{C: ch, ch: ch, peer: peer, lastContiguousEventID: resumeAfter, resumeAfter: resumeAfter}
  212. var gap *hthv1.Event
  213. var replay []*hthv1.Event
  214. var resumeGap *hthv1.DeliveryGap
  215. if resumeAfter > 0 {
  216. if h.oldestID > 0 && resumeAfter < h.oldestID-1 {
  217. resumeGap = &hthv1.DeliveryGap{
  218. DroppedCount: h.oldestID - resumeAfter - 1,
  219. LastContiguousEventId: resumeAfter,
  220. RequestedResumeAfterEventId: resumeAfter,
  221. OldestAvailableEventId: h.oldestID,
  222. }
  223. resumeAfter = h.oldestID - 1
  224. }
  225. for _, it := range h.ring {
  226. if it.ev.EventId > resumeAfter {
  227. cp := proto.Clone(it.ev).(*hthv1.Event)
  228. if resumeGap != nil && len(replay) == 0 {
  229. cp.DeliveryGap = resumeGap
  230. resumeGap = nil
  231. }
  232. replay = append(replay, cp)
  233. }
  234. }
  235. if resumeGap != nil {
  236. sub.gapPending = true
  237. sub.dropped = resumeGap.DroppedCount
  238. }
  239. if len(replay) > 0 {
  240. sub.lastContiguousEventID = replay[len(replay)-1].EventId
  241. }
  242. }
  243. sub.Cancel = func() {
  244. h.mu.Lock()
  245. defer h.mu.Unlock()
  246. if _, ok := h.events[id]; ok {
  247. delete(h.events, id)
  248. close(ch)
  249. }
  250. }
  251. h.events[id] = sub
  252. return sub, replay, gap, nil
  253. }
  254. func (h *Hub) deliveryGapLocked(sub *EventSub) *hthv1.DeliveryGap {
  255. if sub == nil {
  256. return nil
  257. }
  258. return &hthv1.DeliveryGap{
  259. DroppedCount: sub.dropped,
  260. LastContiguousEventId: sub.lastContiguousEventID,
  261. RequestedResumeAfterEventId: sub.resumeAfter,
  262. OldestAvailableEventId: h.oldestID,
  263. }
  264. }
  265. func (h *Hub) stampGapLocked(gap *hthv1.Event) {
  266. if gap == nil {
  267. return
  268. }
  269. // Snapshot-subscribe still returns a descriptor Event. It must not
  270. // consume a global event_id used by the live stream.
  271. if gap.WallTime == nil {
  272. now := time.Now()
  273. gap.WallTime = timestamppb.New(now)
  274. if gap.MonotonicNs == 0 {
  275. gap.MonotonicNs = uint64(now.UnixNano())
  276. }
  277. }
  278. }
  279. func (h *Hub) admitLocked(peer string) error {
  280. if len(h.snaps)+len(h.events) >= h.maxSubs {
  281. return ErrTooManySubscribers
  282. }
  283. if peer != "" && h.peerStreamCountLocked(peer) >= h.maxPerPeer {
  284. return ErrTooManyPeerStreams
  285. }
  286. return nil
  287. }
  288. func (h *Hub) peerStreamCountLocked(peer string) int {
  289. n := 0
  290. for _, s := range h.snaps {
  291. if s.peer == peer {
  292. n++
  293. }
  294. }
  295. for _, s := range h.events {
  296. if s.peer == peer {
  297. n++
  298. }
  299. }
  300. return n
  301. }
  302. func (h *Hub) SubCount() (snaps, events int) {
  303. h.mu.Lock()
  304. defer h.mu.Unlock()
  305. return len(h.snaps), len(h.events)
  306. }