telemetry.go 8.2 KB

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