forked from gophergala2016/rex
/
server.go
318 lines (280 loc) · 7.22 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
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
package room
import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"strconv"
"strings"
"time"
)
// BestAddr returns the best address at which a server should bind. It
// attempts to locate the interface address for the local network. When no
// address can be found the discovery server may just attempt to bind to the
// default address ":0".
func BestAddr() string {
var best string
addrs, err := net.InterfaceAddrs()
if err == nil {
for _, addr := range addrs {
str := addr.String()
if strings.HasPrefix(str, "10.") || strings.HasPrefix(str, "192.") {
// looks like a local address. we will try to bind to it.
best = addr.String()
best = strings.SplitN(best, "/", 2)[0]
best += ":0"
}
}
}
return best
}
// ServerConfig controls how a server advertises itself to potential clients as
// well as miscelaneous communication behaviors.
type ServerConfig struct {
Room *Room
Bus *Bus
// Addr is an optional address to bind. If empty, the address of ":0" will
// be used.
Addr string
}
// Server is a server used by a TV application to run a game or collaborative
// procedure.
type Server struct {
config *ServerConfig
handler *httpBus
tcp *net.TCPListener
http *http.Server
serving chan struct{}
serveErr chan error
}
// NewServer initializes a new server, but does not start serving clients.
func NewServer(config *ServerConfig) *Server {
if config == nil {
panic("nil config")
}
s := &Server{}
s.config = config
s.initHTTP()
return s
}
func (s *Server) initHTTP() {
if s.handler != nil {
panic("already initialized")
}
s.handler = newHTTPBus(s.bus())
s.serving = make(chan struct{})
s.serveErr = make(chan error, 1)
s.http = &http.Server{
Addr: s.config.Addr, // FIXME not correct
Handler: s.handler,
ReadTimeout: 250 * time.Millisecond,
WriteTimeout: 0,
}
}
// Room returns the Room s is hosting.
func (s *Server) Room() *Room {
return s.config.Room
}
func (s *Server) bus() *Bus {
return s.config.Bus
}
// Start binds the server to a port and beigns allowing clients to connect.
// Start must not be called more than once.
func (s *Server) Start() error {
go func() {
defer close(s.serveErr)
err := s.listenTCP()
if err != nil {
s.serveErr <- err
return
}
s.serveErr <- nil
s.serveErr <- s.http.Serve(s.tcp)
}()
err := <-s.serveErr
if err == nil {
// signal that we are serving clients
close(s.serving)
}
return err
}
// Wait returns when the server has terminated. Wait must not be called more
// than once.
func (s *Server) Wait() error {
select {
case <-s.serving:
// we have started serving traffic... righteous.
default:
panic("Wait called before Start")
}
err, ok := <-s.serveErr
if !ok {
return fmt.Errorf("too main goroutines waiting")
}
return err
}
// Run binds to a random port, begins broadcasting service metadata using mDNS,
// and begins streaming client events and dispatching client messages.
// Typically, Run never returns a value. If any critical error is encountered
// it will be returned.
//
// Run is equivalent to calling Start, followed by s.Wait.
func (s *Server) Run() error {
err := s.Start()
if err != nil {
return err
}
return s.Wait()
}
func (s *Server) listenTCP() error {
var err error
addr := s.config.Addr
laddr := &net.TCPAddr{}
if addr != "" {
host, _port, err := net.SplitHostPort(addr)
if err != nil {
return err
}
laddr.Port, err = strconv.Atoi(_port)
if err != nil {
return fmt.Errorf("invalid address port")
}
laddr.IP = net.ParseIP(host)
if laddr.IP == nil && host != "" {
return fmt.Errorf("invalid address host")
}
}
s.tcp, err = net.ListenTCP("tcp", laddr)
if err != nil {
return err
}
return nil
}
// Addr returns the string address the bus is listening on for HTTP requests.
func (s *Server) Addr() string {
return s.tcp.Addr().String()
}
// Event broadcasts c to all connected clients, giving it the next unused event
// index.
func (s *Server) Event(c Content) {
s.bus().Event(c)
}
func newBusHandler(b *Bus) http.Handler {
return newHTTPBus(b)
}
// httpBus exposes the bus functions Subscribe and Message over http endpoints.
type httpBus struct {
b *Bus
mux *http.ServeMux // FIXME use something that is faster
}
func newHTTPBus(b *Bus) *httpBus {
h := &httpBus{
b: b,
mux: http.NewServeMux(),
}
// register all api routes
h.mux.HandleFunc("/rex/v0/events", busEventsHandler(b))
h.mux.HandleFunc("/rex/v0/messages", busMessagesHandler(b))
// TODO: a way for new clients to catch up without log compaction
// h.mux.HandleFunc("/rex/v0/state", busStateHandler(b))
return h
}
func jsonError(id, reason string) string {
return fmt.Sprintf(`{"error":%q, "reason":%q}`, id, reason)
}
func jsonMethodNotAllowed(allow ...string) string {
return jsonError("http_method_invalid", fmt.Sprintf("request method must be one of %v", allow))
}
func busEventsHandler(b *Bus) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if r.Method != "GET" {
w.Header().Set("Allow", "GET")
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintln(w, jsonMethodNotAllowed)
return
}
q := r.URL.Query()
_start := q.Get("start")
start := 0
if _start != "" {
var err error
start, err = strconv.Atoi(_start)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, jsonError("parameter_invalid", "invalid start index"))
return
}
}
sub := b.Subscribe(start)
defer b.Unsubscribe(sub)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
enc := json.NewEncoder(w)
var timeout <-chan time.Time
for sub.Next(timeout) {
if timeout == nil {
timeout = time.After(time.Millisecond)
}
event := sub.Event()
ejs := newJSONEvent(event)
err := enc.Encode(ejs)
if err != nil {
log.Printf("[INFO] Failed to deliver event to client: %v", err)
return
}
}
}
}
func busMessagesHandler(b *Bus) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if r.Method != "POST" {
w.Header().Set("Allow", "POST")
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintln(w, jsonMethodNotAllowed)
return
}
msg := map[string]interface{}{}
err := json.NewDecoder(r.Body).Decode(&msg)
if err != nil {
var resp string
switch e := err.(type) {
case *json.SyntaxError:
resp = e.Error()
default:
log.Printf("[INFO] message i/o error: %v", err)
resp = "could not read a complete entity"
}
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, jsonError("http_request_invalid", resp))
return
}
log.Printf("[INFO] message received %v", msg)
var content string
_content, ok := msg["data"]
if ok {
content, ok = _content.(string)
}
if !ok {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, jsonError("protocol_error", "missing message content"))
return
}
var session string
_session, ok := msg["session"]
if ok {
session, ok = _session.(string)
}
if !ok {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, jsonError("protocol_error", "missing message content"))
return
}
b.Message(session, String(content))
}
}
func (b *httpBus) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b.mux.ServeHTTP(w, r)
}