telemetry.go 8.1 KB

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