hub.go 2.2 KB

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