hub.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package live
  2. import (
  3. "github.com/grafana/grafana/pkg/api/dtos"
  4. "github.com/grafana/grafana/pkg/components/simplejson"
  5. "github.com/grafana/grafana/pkg/log"
  6. )
  7. type hub struct {
  8. log log.Logger
  9. connections map[*connection]bool
  10. streams map[string]map[*connection]bool
  11. register chan *connection
  12. unregister chan *connection
  13. streamChannel chan *dtos.StreamMessage
  14. subChannel chan *streamSubscription
  15. }
  16. type streamSubscription struct {
  17. conn *connection
  18. name string
  19. remove bool
  20. }
  21. var h = hub{
  22. connections: make(map[*connection]bool),
  23. streams: make(map[string]map[*connection]bool),
  24. register: make(chan *connection),
  25. unregister: make(chan *connection),
  26. streamChannel: make(chan *dtos.StreamMessage),
  27. subChannel: make(chan *streamSubscription),
  28. log: log.New("live.hub"),
  29. }
  30. func (h *hub) removeConnection() {
  31. }
  32. func (h *hub) run() {
  33. for {
  34. select {
  35. case c := <-h.register:
  36. h.connections[c] = true
  37. h.log.Info("New connection", "total", len(h.connections))
  38. case c := <-h.unregister:
  39. if _, ok := h.connections[c]; ok {
  40. h.log.Info("Closing connection", "total", len(h.connections))
  41. delete(h.connections, c)
  42. close(c.send)
  43. }
  44. // hand stream subscriptions
  45. case sub := <-h.subChannel:
  46. h.log.Info("Subscribing", "channel", sub.name, "remove", sub.remove)
  47. subscribers, exists := h.streams[sub.name]
  48. // handle unsubscribe
  49. if exists && sub.remove {
  50. delete(subscribers, sub.conn)
  51. continue
  52. }
  53. if !exists {
  54. subscribers = make(map[*connection]bool)
  55. h.streams[sub.name] = subscribers
  56. }
  57. subscribers[sub.conn] = true
  58. // handle stream messages
  59. case message := <-h.streamChannel:
  60. subscribers, exists := h.streams[message.Stream]
  61. if !exists || len(subscribers) == 0 {
  62. h.log.Info("Message to stream without subscribers", "stream", message.Stream)
  63. continue
  64. }
  65. messageBytes, _ := simplejson.NewFromAny(message).Encode()
  66. for sub := range subscribers {
  67. // check if channel is open
  68. if _, ok := h.connections[sub]; !ok {
  69. delete(subscribers, sub)
  70. continue
  71. }
  72. select {
  73. case sub.send <- messageBytes:
  74. default:
  75. close(sub.send)
  76. delete(h.connections, sub)
  77. delete(subscribers, sub)
  78. }
  79. }
  80. }
  81. }
  82. }