aboutsummaryrefslogtreecommitdiff
path: root/notification_controller.go
blob: 88c9e8c97405e4d85c609f3e080260c1d8c5048a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package main

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	log "github.com/sirupsen/logrus"
	"net"
	"net/http"
	"time"
)

const (
	InsertNotification = "insert"
	UpdateNotification = "update"
	DeleteNotification = "delete"

	writeWait      = 10 * time.Second
	pongWait       = 60 * time.Second
	pingPeriod     = (pongWait * 9) / 10
	maxMessageSize = 512
)

type NotificationController struct {
	upgrader           websocket.Upgrader
	clients            map[net.Addr]*client
	broadcast          chan interface{}
	register           chan *client
	unregister         chan *client
	applicationContext *ApplicationContext
}

func NewNotificationController(applicationContext *ApplicationContext) *NotificationController {
	return &NotificationController{
		upgrader: websocket.Upgrader{
			ReadBufferSize:  1024,
			WriteBufferSize: 1024,
		},
		clients:            make(map[net.Addr]*client),
		broadcast:          make(chan interface{}),
		register:           make(chan *client),
		unregister:         make(chan *client),
		applicationContext: applicationContext,
	}
}

type client struct {
	conn                   *websocket.Conn
	send                   chan interface{}
	notificationController *NotificationController
}

func (wc *NotificationController) NotificationHandler(w http.ResponseWriter, r *http.Request) error {
	conn, err := wc.upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.WithError(err).Error("failed to set websocket upgrade")
		return err
	}

	client := &client{
		conn:                   conn,
		send:                   make(chan interface{}),
		notificationController: wc,
	}
	wc.register <- client
	go client.readPump()
	go client.writePump()

	return nil
}

func (wc *NotificationController) Run() {
	for {
		select {
		case client := <-wc.register:
			wc.clients[client.conn.RemoteAddr()] = client
			payload := gin.H{"event": "connected", "message": gin.H{
				"version":           wc.applicationContext.Version,
				"is_configured":     wc.applicationContext.IsConfigured,
				"connected_clients": len(wc.clients),
			}}
			client.send <- payload
			log.WithField("connected_clients", len(wc.clients)).
				WithField("remote_address", client.conn.RemoteAddr()).
				Info("[+] a websocket client connected")
		case client := <-wc.unregister:
			if _, ok := wc.clients[client.conn.RemoteAddr()]; ok {
				close(client.send)
				_ = client.conn.WriteMessage(websocket.CloseMessage, nil)
				_ = client.conn.Close()
				delete(wc.clients, client.conn.RemoteAddr())
				log.WithField("connected_clients", len(wc.clients)).
					WithField("remote_address", client.conn.RemoteAddr()).
					Info("[-] a websocket client disconnected")
			}
		case payload := <-wc.broadcast:
			for _, client := range wc.clients {
				select {
				case client.send <- payload:
				default:
					close(client.send)
					delete(wc.clients, client.conn.RemoteAddr())
				}
			}
		}
	}
}

func (wc *NotificationController) Notify(event string, eventType string, message interface{}) {
	wc.broadcast <- gin.H{"event": event, "event_type": eventType, "message": message}
}

func (c *client) readPump() {
	c.conn.SetReadLimit(maxMessageSize)
	if err := c.conn.SetReadDeadline(time.Now().Add(pongWait)); err != nil {
		c.close()
		return
	}
	c.conn.SetPongHandler(func(string) error { return c.conn.SetReadDeadline(time.Now().Add(pongWait)) })
	for {
		if _, _, err := c.conn.ReadMessage(); err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				log.WithError(err).WithField("remote_address", c.conn.RemoteAddr()).
					Warn("unexpected websocket disconnection")
			}
			break
		}
	}

	c.close()
}

func (c *client) writePump() {
	ticker := time.NewTicker(pingPeriod)
	defer ticker.Stop()

	for {
		select {
		case payload, ok := <-c.send:
			if !ok {
				return
			}
			if err := c.conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil {
				c.close()
				return
			}
			if err := c.conn.WriteJSON(payload); err != nil {
				c.close()
				return
			}
		case <-ticker.C:
			if err := c.conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil {
				c.close()
				return
			}
			if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
				c.close()
				return
			}
		}
	}
}

func (c *client) close() {
	c.notificationController.unregister <- c
}