hub.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. package sse
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "time"
  7. "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs"
  8. "github.com/gomodule/redigo/redis"
  9. context "github.com/kataras/iris/v12/context"
  10. )
  11. type Event struct {
  12. Timestamp int64 `json:"timestamp"`
  13. Payload string `json:"payload"`
  14. Kind string `json:"kind"`
  15. }
  16. type ChannelClient struct {
  17. // Context context.Context
  18. Flusher http.Flusher
  19. Response http.ResponseWriter
  20. Request *http.Request
  21. }
  22. type Channel struct {
  23. ID string
  24. Clients map[*ChannelClient]bool
  25. }
  26. func (channel *Channel) RemoveClient(client *ChannelClient) {
  27. delete(channel.Clients, client)
  28. }
  29. func (channel *Channel) AddClient(client *ChannelClient) {
  30. channel.Clients[client] = true
  31. }
  32. func (channel *Channel) Emit(event *Event) {
  33. var (
  34. err error
  35. )
  36. for client := range channel.Clients {
  37. if event.Kind != "" {
  38. if _, err = fmt.Fprintf(client.Response, "event: %s\n", event.Kind); err != nil {
  39. fmt.Println(fmt.Sprintf("%+v", err))
  40. continue
  41. }
  42. }
  43. if _, err = fmt.Fprintf(client.Response, "data: %s\n\n", event.Payload); err != nil {
  44. fmt.Println(fmt.Sprintf("%+v", err))
  45. continue
  46. }
  47. client.Flusher.Flush()
  48. }
  49. }
  50. type SSEHub struct {
  51. // New client connections
  52. newClients chan chan []byte
  53. // Closed client connections
  54. closingClients chan chan []byte
  55. // Client connections registry
  56. Channels map[string]*Channel
  57. ChannelCollection string
  58. RedisPool *redis.Pool
  59. }
  60. type SSEOptions struct {
  61. URI string
  62. Password string
  63. ChannelCollection string
  64. }
  65. func NewSSEHub(options *SSEOptions) *SSEHub {
  66. return &SSEHub{
  67. newClients: make(chan chan []byte),
  68. closingClients: make(chan chan []byte),
  69. Channels: make(map[string]*Channel),
  70. ChannelCollection: options.ChannelCollection,
  71. RedisPool: &redis.Pool{
  72. // Maximum number of idle connections in the pool.
  73. MaxIdle: 80,
  74. // max number of connections
  75. MaxActive: 12000,
  76. // Dial is an application supplied function for creating and
  77. // configuring a connection.
  78. Dial: func() (redis.Conn, error) {
  79. conn, err := redis.Dial("tcp", options.URI)
  80. if err != nil {
  81. panic(err.Error())
  82. }
  83. if options.Password != "" {
  84. if _, err := conn.Do("AUTH", options.Password); err != nil {
  85. conn.Close()
  86. return nil, err
  87. }
  88. }
  89. return conn, err
  90. },
  91. },
  92. }
  93. }
  94. func (hub *SSEHub) GetChannel(channelID string) *Channel {
  95. if _, exist := hub.Channels[channelID]; !exist {
  96. channel := &Channel{
  97. Clients: make(map[*ChannelClient]bool),
  98. ID: channelID,
  99. }
  100. hub.Channels[channelID] = channel
  101. }
  102. return hub.Channels[channelID]
  103. }
  104. func (hub *SSEHub) Dispatch(event *Event, channels ...string) {
  105. var (
  106. exists bool
  107. err error
  108. conn = hub.RedisPool.Get()
  109. )
  110. defer conn.Close()
  111. for _, channel := range channels {
  112. if exists, err = redis.Bool(conn.Do("HEXISTS", hub.ChannelCollection, channel)); err != nil || !exists {
  113. continue
  114. }
  115. eventBytes, _ := json.Marshal(event)
  116. conn.Do("RPUSH", channel, string(eventBytes))
  117. }
  118. }
  119. func (hub *SSEHub) UpgradeConnection(ctx context.Context, channelId string) (err *errs.Error) {
  120. var (
  121. conn = hub.RedisPool.Get()
  122. payload string
  123. count int
  124. ok bool
  125. redisErr error
  126. flusher http.Flusher
  127. response = ctx.ResponseWriter().Naive()
  128. request = ctx.Request()
  129. )
  130. defer conn.Close()
  131. if flusher, ok = response.(http.Flusher); !ok {
  132. err = errs.HTTPVersionNotSupported().Details(&errs.Detail{
  133. Dominio: "",
  134. Reason: "Streaming unsupported",
  135. Location: "hook.beforePersist",
  136. LocationType: "",
  137. })
  138. return
  139. }
  140. if _, redisErr = redis.Int(conn.Do("HSET", hub.ChannelCollection, channelId, true)); redisErr != nil {
  141. err = errs.Internal().Details(&errs.Detail{
  142. Dominio: "",
  143. Reason: "Fail on register channel",
  144. Location: "hook.beforePersist",
  145. LocationType: "",
  146. })
  147. return
  148. }
  149. header := response.Header()
  150. header.Set("Access-Control-Allow-Origin", "*")
  151. header.Set("Content-Type", "text/event-stream")
  152. header.Set("Cache-Control", "no-cache")
  153. header.Set("Connection", "keep-alive")
  154. flusher.Flush()
  155. client := &ChannelClient{
  156. Flusher: flusher,
  157. Response: response,
  158. Request: request,
  159. }
  160. channel := hub.GetChannel(channelId)
  161. channel.AddClient(client)
  162. finalizeMain := make(chan bool)
  163. // finalizePing := make(chan bool)
  164. finalized := false
  165. // Listen to connection close and when the entire request handler chain exits(this handler here) and un-register messageChan.
  166. notify := response.(http.CloseNotifier).CloseNotify()
  167. go func() {
  168. <-notify
  169. fmt.Println("SSE request end")
  170. defer func() {
  171. // recover from panic caused by writing to a closed channel
  172. recover()
  173. return
  174. }()
  175. if finalized {
  176. return
  177. }
  178. finalized = true
  179. // ctx.Application().Logger().Infof("notification.channel.disconect(%s)", channelId)
  180. // Remove this client from the map of connected clients
  181. // when this handler exits.
  182. redis.Int(conn.Do("HDEL", hub.ChannelCollection, channelId))
  183. // closesd = true
  184. finalizeMain <- finalized
  185. // finalizePing <- finalized
  186. channel.RemoveClient(client)
  187. }()
  188. // Essa thread dispara um ping para manter a conexão ativa com o client
  189. // go func() {
  190. // ticker := time.NewTicker(3 * time.Second)
  191. // defer ticker.Stop()
  192. // for {
  193. // select {
  194. // case <-ticker.C:
  195. // // ctx.Application().Logger().Warnf("init.notification.loop 2s")
  196. // // flusher.Flush()
  197. // case <-finalizePing:
  198. // // ctx.Application().Logger().Warnf("finalize init.notification.loop 2s")
  199. // close(finalizePing)
  200. // return
  201. // }
  202. // }
  203. // }()
  204. ticker5Second := time.NewTicker(5 * time.Second)
  205. defer ticker5Second.Stop()
  206. flusher.Flush()
  207. reset:
  208. for {
  209. select {
  210. case <-ticker5Second.C:
  211. // ctx.Application().Logger().Warnf("init.notification.loop 5s")
  212. if count, redisErr = redis.Int(conn.Do("LLEN", channelId)); count == 0 || redisErr != nil {
  213. continue reset
  214. }
  215. for ; count > 0; count-- {
  216. if payload, redisErr = redis.String(conn.Do("LPOP", channelId)); redisErr != nil {
  217. ctx.Application().Logger().Errorf("NotificationError:", redisErr)
  218. } else {
  219. event := &Event{}
  220. json.Unmarshal([]byte(payload), event)
  221. channel.Emit(event)
  222. break
  223. }
  224. }
  225. case <-finalizeMain:
  226. ctx.Application().Logger().Infof("notification.finalize.disconect(%s)", channelId)
  227. close(finalizeMain)
  228. return
  229. }
  230. }
  231. return
  232. }
  233. // ctx.OnClose(func() {
  234. // defer func() {
  235. // // recover from panic caused by writing to a closed channel
  236. // recover()
  237. // return
  238. // }()
  239. // if finalized {
  240. // return
  241. // }
  242. // finalized = true
  243. // // ctx.Application().Logger().Infof("notification.channel.disconect(%s)", channelId)
  244. // // Remove this client from the map of connected clients
  245. // // when this handler exits.
  246. // redis.Int(conn.Do("HDEL", hub.ChannelCollection, channelId))
  247. // // closesd = true
  248. // finalizeMain <- finalized
  249. // finalizePing <- finalized
  250. // channel.RemoveClient(client)
  251. // })
  252. // Set the headers related to event streaming, you can omit the "application/json" if you send plain text.
  253. // If you develop a go client, you must have: "Accept" : "application/json, text/event-stream" header as well.
  254. // header := ctx.ResponseWriter().Header()
  255. // header.Set("Access-Control-Allow-Origin", "*")
  256. // header.Set("Content-Type", "text/event-stream")
  257. // header.Set("Cache-Control", "no-cache")
  258. // header.Set("Connection", "keep-alive")
  259. // ctx.ContentType("text/event-stream")
  260. // ctx.Header("Cache-Control", "no-cache")
  261. // ctx.Header("Connection", "keep-alive")
  262. // ctx.Request().Response.Header.Set("Access-Control-Allow-Origin", "*")
  263. // Block waiting for messages broadcast on this connection's messageChan.
  264. // check notification in redis
  265. // go func() {
  266. // ctx.Application().Logger().Warnf("init.notification.loop %v", closesd)