-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathservice.go
334 lines (267 loc) · 6.34 KB
/
service.go
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package main
import (
"fmt"
"io/ioutil"
"net/http"
"reflect"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
type service struct {
gin *gin.Engine
wsUpgrder *websocket.Upgrader
currentSubscriptions subscriptions
timeout time.Duration
sync chan bool
cache *Cache
}
func newService(
currentSubscriptions subscriptions,
readBufferSize int,
writeBufferSize int,
timeout time.Duration,
debugMode string,
cache *Cache,
) *service {
if debugMode == "DEBUG" {
gin.SetMode(gin.ReleaseMode)
}
upgrader := &websocket.Upgrader{
ReadBufferSize: readBufferSize,
WriteBufferSize: writeBufferSize,
CheckOrigin: func(request *http.Request) bool { return true },
}
return &service{
gin.Default(),
upgrader,
currentSubscriptions,
timeout,
make(chan bool, 1),
cache,
}
}
func (s *service) run(
listen string,
sslCertificate string,
sslPrivateKey string,
) {
v1 := s.gin.Group("v1")
{
v1.GET("/subscribe", s.handleSubscription)
v1.PUT("/publish", s.handlePublish)
v1.PUT("/broadcast", s.handleBroadcast)
v1.GET("/stats", s.handleStats)
v1.GET("/stats/sessions", s.handleStatsSessions)
v1.GET("/health", s.handleHealth)
}
// ginpprof.Wrap(s.gin)
logger.Debugf("run service on %s", listen)
if sslCertificate != "" && sslPrivateKey != "" {
s.gin.RunTLS(
listen,
sslCertificate,
sslPrivateKey,
)
return
}
s.gin.Run(listen)
}
func (s *service) handleSubscription(context *gin.Context) {
logger.Debugf(
"handling new request from %s",
context.Request.RemoteAddr,
)
authInfo := make(chan string)
isDisconnected := make(chan bool, 1)
terminateAuthentication := make(chan bool, 1)
terminateKeepAlive := make(chan bool, 1)
incomingMessages := make(chan string)
connection, err := s.wsUpgrder.Upgrade(
context.Writer, context.Request, nil,
)
if err != nil {
logger.Errorf(
"something happing wrong during create websocket connection, "+
"reason %s",
err.Error(),
)
return
}
defer func() {
err := connection.Close()
if err != nil {
logger.Errorf(
"unable to close websocket connection from %s, reason: %s",
connection.RemoteAddr().String(),
err.Error(),
)
return
}
logger.Infof(
"websocket connection successfully closed for client %s",
connection.RemoteAddr().String(),
)
return
}()
connection.SetReadDeadline(time.Now().Add(s.timeout))
connection.SetWriteDeadline(time.Now().Add(s.timeout))
go readMessage(connection, isDisconnected, incomingMessages)
go authenticateUser(
incomingMessages,
authInfo,
terminateAuthentication,
)
var (
authToken string = ""
sessionNumber int = 0
messages chan []byte
)
for {
select {
case authToken = <-authInfo:
logger.Debugf(
"auth token received: %s",
authToken,
)
go keepAlive(connection, s.timeout, terminateKeepAlive, s.sync)
s.sync <- true
sessionNumber, messages = s.currentSubscriptions.subscribeUser(
authToken,
)
<-s.sync
logger.Infof(
"user %s was subscribed with ID %d",
connection.RemoteAddr().String(),
sessionNumber,
)
if len(s.cache.messages[authToken]) != 0 {
logger.Debugf(
"pop messages from cache for %s",
authToken,
)
go func() {
for _, cacheObject := range s.cache.pop(authToken) {
messages <- []byte(cacheObject.message)
}
}()
}
case <-isDisconnected:
s.sync <- true
logger.Infof(
"client %s with token %s with session %d will be disconnected",
context.Request.RemoteAddr,
authToken,
sessionNumber,
)
terminateAuthentication <- true
terminateKeepAlive <- true
logger.Infof(
"terminate message was successfully sended into keepalive" +
" and authentication processes",
)
activeSubscribers := s.currentSubscriptions.getActiveSubscribers(
authToken,
)
switch activeSubscribers {
case 0:
logger.Debug("there are no subscribers, exiting...")
case 1:
logger.Debugf(
"there is only one subscription for user %s, "+
"unsubscribe user",
authToken,
)
s.currentSubscriptions.unsubscribeUser(authToken)
default:
logger.Debugf(
"there are several sessions for user %s, "+
"trying deactivate session %d",
authToken,
sessionNumber,
)
s.currentSubscriptions.setInactive(authToken, sessionNumber)
}
<-s.sync
return
case message := <-messages:
s.sync <- true
logger.Debugf("got message %s", message)
err := connection.WriteMessage(websocket.TextMessage, message)
if err != nil {
logger.Errorf(
"%s: can`t write message to websocket, reason %s",
reflect.TypeOf(err).String(),
err.Error(),
)
<-s.sync
return
}
<-s.sync
}
}
}
func (s *service) handlePublish(context *gin.Context) {
authToken := strings.TrimSpace(
context.Request.Header.Get("Token"),
)
message, err := ioutil.ReadAll(context.Request.Body)
if err != nil {
logger.Errorf(
"could not read response body, reason: %s",
err.Error(),
)
context.JSON(makeInternalServerError(err.Error(), nil))
return
}
s.sync <- true
defer func() {
<-s.sync
}()
if _, exists := s.currentSubscriptions[authToken]; exists {
s.currentSubscriptions.publishMessage(authToken, message)
context.JSON(makeStatusOk("message published", string(message)))
return
}
s.cache.put(authToken, string(message))
context.JSON(makeNotFoundError(
fmt.Sprintf("recipient %s not found", authToken),
string(message),
))
return
}
func (s *service) handleStats(context *gin.Context) {
stat := ServiceStats{
SubscribersCount: len(s.currentSubscriptions),
}
context.JSON(makeStatusOk(
context.Request.URL.String(), stat,
))
return
}
func (s *service) handleStatsSessions(context *gin.Context) {
sessionsCount := make(map[string]int)
s.sync <- true
defer func() {
<-s.sync
}()
for authToken, sessions := range s.currentSubscriptions {
sessionsCount[authToken] = len(sessions)
}
sortedCurrentSessions := newSortedSessions(sessionsCount)
sortedCurrentSessions.Sort()
stat := ActiveSessions{
SubscribersSessionsCount: sessionsCount,
}
context.JSON(makeStatusOk(
context.Request.URL.String(), stat,
))
return
}
func (s *service) handleHealth(context *gin.Context) {
context.JSON(makeStatusOk(
context.Request.URL.String(), "OK",
))
return
}