-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.go
233 lines (202 loc) · 5.66 KB
/
server.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
package lightcable
import (
"context"
"errors"
"io"
"net/http"
"github.com/gorilla/websocket"
)
type readyState int8
const (
readyStateOpening readyState = iota
readyStateRunning
readyStateClosing
readyStateClosed
)
// Server is lightcable core Server. use callback notification message
// broadcast message, A Server auto create and manage multiple goroutines
// every room create worker
type Server struct {
config WorkerConfig
worker map[string]*worker
// Register requests from the clients.
register chan *Client
// Inbound messages from the clients.
broadcast chan Message
// Inbound All Room Message
broadcastAll chan Message
// Unregister requests from clients.
unregister chan *Client
readyState
onMessage func(*Message)
onConnected func(w http.ResponseWriter, r *http.Request) (room, name string, ok bool)
onRoomReady func(room string)
onConnReady func(*Client)
onConnClose func(*Client)
onRoomClose func(room string)
onServClose func()
}
// New creates a new Server.
func New(cfg *Config) *Server {
return &Server{
config: cfg.Worker,
worker: make(map[string]*worker),
readyState: readyStateOpening,
register: make(chan *Client, cfg.SignBufferCount),
broadcast: make(chan Message, cfg.CastBufferCount),
unregister: make(chan *Client, cfg.SignBufferCount),
broadcastAll: make(chan Message, cfg.CastBufferCount),
onMessage: func(*Message) {},
onConnected: func(w http.ResponseWriter, r *http.Request) (room, name string, ok bool) {
return r.URL.Path, getUniqueID(), true
},
onRoomReady: func(room string) {},
onConnReady: func(*Client) {},
onConnClose: func(*Client) {},
onRoomClose: func(room string) {},
onServClose: func() {},
}
}
// Run need use 'go server.Run(context.Background())' run daemon
// in order to concurrency. server instance only a run
func (s *Server) Run(ctx context.Context) {
s.readyState = readyStateRunning
defer func() {
for {
// Last room, server onClose
if len(s.worker) == 0 && s.readyState == readyStateClosing {
s.onServClose()
s.readyState = readyStateClosed
return
}
delete(s.worker, (<-s.unregister).Room)
}
}()
for {
select {
// unregister must first
// close and open concurrency
case c := <-s.unregister:
delete(s.worker, c.Room)
case c := <-s.register:
c.worker = s.worker[c.Room]
if c.worker == nil {
c.worker = newWorker(c.Room, s)
go c.worker.run(ctx)
s.worker[c.Room] = c.worker
}
c.worker.register <- c
case m := <-s.broadcast:
if worker, ok := s.worker[m.Room]; ok {
worker.broadcast <- m
}
case m := <-s.broadcastAll:
for _, worker := range s.worker {
// This should not be blocked
select {
case worker.broadcast <- m:
default:
}
}
case <-ctx.Done():
s.readyState = readyStateClosing
return
}
}
}
// ServeHTTP Interface 'http.Handler'.
// creates new websocket connection
// Maybe Create new Worker. worker == room
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if room, name, ok := s.onConnected(w, r); ok {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, err.Error())
return
}
if err := s.addClient(&Client{
Room: room,
Name: name,
conn: conn,
send: make(chan Message, s.config.CastBufferCount),
}); err != nil {
// The server lack of resources: close the connection
conn.WriteMessage(websocket.CloseMessage, []byte{})
}
}
}
// Add a New Websocket Client
func (s *Server) Upgrade(w http.ResponseWriter, r *http.Request, room, name string) error {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return err
}
return s.addClient(&Client{
Room: room,
Name: name,
conn: conn,
send: make(chan Message, s.config.CastBufferCount),
})
}
func (s *Server) addClient(c *Client) (err error) {
select {
case s.register <- c:
default:
err = errors.New("Buffer Always Full")
}
return
}
// Broadcast will room all websocket connection send message
// https://www.rfc-editor.org/rfc/rfc6455.html#section-11.8
// code is websocket Opcode
// name is custom name, this will be callback OnMessage
func (s *Server) Broadcast(room, name string, code int, data []byte) {
s.broadcast <- Message{
Name: name,
Room: room,
Code: code,
Data: data,
}
}
// BroadcastAll will all room all websocket connection send message
func (s *Server) BroadcastAll(name string, code int, data []byte) {
s.broadcastAll <- Message{
Name: name,
Code: code,
Data: data,
}
}
// OnMessage will all Websocket Conn Recv Message will callback this function
// This have Block worker. Block this room
func (s *Server) OnMessage(fn func(*Message)) {
s.onMessage = fn
}
// OnConnected auth this websocket connection callback
// ok: true Allows connection; false Reject connection
// Maybe Concurrent. unique ID need self use sync.Mutex
func (s *Server) OnConnected(fn func(w http.ResponseWriter, r *http.Request) (room, name string, ok bool)) {
s.onConnected = fn
}
// OnRoomReady Create a new room successfully
func (s *Server) OnRoomReady(fn func(room string)) {
s.onRoomReady = fn
}
// OnConnReady websocket connection successfully and join room
// this will block worker
func (s *Server) OnConnReady(fn func(*Client)) {
s.onConnReady = fn
}
// OnConnClose will Client error or websocket close or server close
// if context server closed err == nil
func (s *Server) OnConnClose(fn func(*Client)) {
s.onConnClose = fn
}
// OnRoomClose worker all websocket connection closed, worker close
func (s *Server) OnRoomClose(fn func(room string)) {
s.onRoomClose = fn
}
// OnServClose server safely shutdown done callback
func (s *Server) OnServClose(fn func()) {
s.onServClose = fn
}