This repository has been archived by the owner on Jul 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
service.go
232 lines (190 loc) · 4.83 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
package ws
import (
"encoding/json"
"net/http"
"sync"
"sync/atomic"
"github.com/gorilla/websocket"
"github.com/spiral/broadcast/v2"
"github.com/spiral/roadrunner/service/env"
rhttp "github.com/spiral/roadrunner/service/http"
"github.com/spiral/roadrunner/service/rpc"
)
// ID defines service id.
const ID = "ws"
// Service to manage websocket clients.
type Service struct {
cfg *Config
upgrade websocket.Upgrader
client *broadcast.Client
connPool *connPool
listeners []func(event int, ctx interface{})
mu sync.Mutex
stopped int32
stop chan error
}
// AddListener attaches server event controller.
func (s *Service) AddListener(l func(event int, ctx interface{})) {
s.listeners = append(s.listeners, l)
}
// Init the service.
func (s *Service) Init(
cfg *Config,
env env.Environment,
rttp *rhttp.Service,
rpc *rpc.Service,
broadcast *broadcast.Service,
) (bool, error) {
if broadcast == nil || rpc == nil {
// unable to activate
return false, nil
}
s.cfg = cfg
s.client = broadcast.NewClient()
s.connPool = newPool(s.client, s.reportError)
s.stopped = 0
if err := rpc.Register(ID, &rpcService{svc: s}); err != nil {
return false, err
}
if env != nil {
// ensure that underlying kernel knows what route to handle
env.SetEnv("RR_BROADCAST_PATH", cfg.Path)
}
// init all this stuff
s.upgrade = websocket.Upgrader{}
if s.cfg.NoOrigin {
s.upgrade.CheckOrigin = func(r *http.Request) bool {
return true
}
}
rttp.AddMiddleware(s.middleware)
return true, nil
}
// Serve the websocket connections.
func (s *Service) Serve() error {
defer s.client.Close()
defer s.connPool.close()
s.mu.Lock()
s.stop = make(chan error)
s.mu.Unlock()
return <-s.stop
}
// Stop the service and disconnect all connections.
func (s *Service) Stop() {
s.mu.Lock()
defer s.mu.Unlock()
if atomic.CompareAndSwapInt32(&s.stopped, 0, 1) {
close(s.stop)
}
}
// middleware intercepts websocket connections.
func (s *Service) middleware(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != s.cfg.Path {
f(w, r)
return
}
// checking server access
if err := newValidator().assertServerAccess(f, r); err != nil {
// show the error to the user
if av, ok := err.(*accessValidator); ok {
av.copy(w)
} else {
w.WriteHeader(400)
}
return
}
conn, err := s.upgrade.Upgrade(w, r, nil)
if err != nil {
s.reportError(err, nil)
return
}
s.throw(EventConnect, conn)
// manage connection
ctx, err := s.connPool.connect(conn)
if err != nil {
s.reportError(err, conn)
return
}
s.serveConn(ctx, f, r)
}
}
// send and receive messages over websocket
func (s *Service) serveConn(ctx *ConnContext, f http.HandlerFunc, r *http.Request) {
defer func() {
if err := s.connPool.disconnect(ctx.Conn); err != nil {
s.reportError(err, ctx.Conn)
}
s.throw(EventDisconnect, ctx.Conn)
}()
s.handleCommands(ctx, f, r)
}
func (s *Service) handleCommands(ctx *ConnContext, f http.HandlerFunc, r *http.Request) {
cmd := &broadcast.Message{}
for {
if err := ctx.Conn.ReadJSON(cmd); err != nil {
s.reportError(err, ctx.Conn)
return
}
switch cmd.Topic {
case "join":
topics := make([]string, 0)
if err := unmarshalCommand(cmd, &topics); err != nil {
s.reportError(err, ctx.Conn)
return
}
if len(topics) == 0 {
continue
}
if err := newValidator().assertTopicsAccess(f, r, topics...); err != nil {
s.reportError(err, ctx.Conn)
if err := ctx.SendMessage("#join", topics); err != nil {
s.reportError(err, ctx.Conn)
return
}
continue
}
if err := s.connPool.subscribe(ctx, topics...); err != nil {
s.reportError(err, ctx.Conn)
return
}
if err := ctx.SendMessage("@join", topics); err != nil {
s.reportError(err, ctx.Conn)
return
}
s.throw(EventJoin, &TopicEvent{Conn: ctx.Conn, Topics: topics})
case "leave":
topics := make([]string, 0)
if err := unmarshalCommand(cmd, &topics); err != nil {
s.reportError(err, ctx.Conn)
return
}
if len(topics) == 0 {
continue
}
if err := s.connPool.unsubscribe(ctx, topics...); err != nil {
s.reportError(err, ctx.Conn)
return
}
if err := ctx.SendMessage("@leave", topics); err != nil {
s.reportError(err, ctx.Conn)
return
}
s.throw(EventLeave, &TopicEvent{Conn: ctx.Conn, Topics: topics})
}
}
}
// handle connection error
func (s *Service) reportError(err error, conn *websocket.Conn) {
s.throw(EventError, &ErrorEvent{Conn: conn, Error: err})
}
// throw handles service, server and pool events.
func (s *Service) throw(event int, ctx interface{}) {
for _, l := range s.listeners {
l(event, ctx)
}
}
// unmarshalCommand command data.
func unmarshalCommand(msg *broadcast.Message, v interface{}) error {
return json.Unmarshal(msg.Payload, v)
}