main.go

  1package main
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"fmt"
  7	"log"
  8	"math/rand"
  9	"net/http"
 10	"os"
 11	"time"
 12
 13	"github.com/go-chi/chi"
 14	"github.com/go-chi/chi/middleware"
 15	"github.com/jessevdk/go-flags"
 16	"github.com/posener/ctxutil"
 17	"github.com/prometheus/client_golang/prometheus/promhttp"
 18	"github.com/tomwright/queryparam/v4"
 19	"github.com/zikaeroh/codies/internal/protocol"
 20	"github.com/zikaeroh/codies/internal/server"
 21	"github.com/zikaeroh/codies/internal/version"
 22	"golang.org/x/sync/errgroup"
 23	"nhooyr.io/websocket"
 24)
 25
 26var args = struct {
 27	Addr    string   `long:"addr" env:"CODIES_ADDR" description:"Address to listen at"`
 28	Origins []string `long:"origins" env:"CODIES_ORIGINS" env-delim:"," description:"Additional valid origins for WebSocket connections"`
 29	Prod    bool     `long:"prod" env:"CODIES_PROD" description:"Enables production mode"`
 30	Debug   bool     `long:"debug" env:"CODIES_DEBUG" description:"Enables debug mode"`
 31}{
 32	Addr: ":5000",
 33}
 34
 35var wsOpts *websocket.AcceptOptions
 36
 37func main() {
 38	rand.Seed(time.Now().Unix())
 39	log.SetFlags(log.LstdFlags | log.Lshortfile)
 40
 41	if _, err := flags.Parse(&args); err != nil {
 42		// Default flag parser prints messages, so just exit.
 43		os.Exit(1)
 44	}
 45
 46	if !args.Prod && !args.Debug {
 47		log.Fatal("missing required option --prod or --debug")
 48	} else if args.Prod && args.Debug {
 49		log.Fatal("must specify either --prod or --debug")
 50	}
 51
 52	log.Printf("starting codies server, version %s", version.Version())
 53
 54	wsOpts = &websocket.AcceptOptions{
 55		OriginPatterns: args.Origins,
 56	}
 57
 58	if args.Debug {
 59		log.Println("starting in debug mode, allowing any WebSocket origin host")
 60		wsOpts.OriginPatterns = []string{"*"}
 61	} else {
 62		if !version.VersionSet() {
 63			log.Fatal("running production build without version set")
 64		}
 65	}
 66
 67	g, ctx := errgroup.WithContext(ctxutil.Interrupt())
 68
 69	srv := server.NewServer()
 70
 71	r := chi.NewMux()
 72
 73	r.Use(func(next http.Handler) http.Handler {
 74		return promhttp.InstrumentHandlerCounter(metricRequest, next)
 75	})
 76
 77	r.Use(middleware.Heartbeat("/ping"))
 78	r.Use(middleware.Recoverer)
 79	r.NotFound(staticHandler().ServeHTTP)
 80
 81	r.Group(func(r chi.Router) {
 82		r.Use(middleware.NoCache)
 83
 84		r.Get("/api/time", func(w http.ResponseWriter, r *http.Request) {
 85			w.Header().Add("Content-Type", "application/json")
 86			_ = json.NewEncoder(w).Encode(&protocol.TimeResponse{Time: time.Now()})
 87		})
 88
 89		r.Get("/api/stats", func(w http.ResponseWriter, r *http.Request) {
 90			rooms, clients := srv.Stats()
 91
 92			enc := json.NewEncoder(w)
 93			enc.SetIndent("", "    ")
 94			_ = enc.Encode(&protocol.StatsResponse{
 95				Rooms:   rooms,
 96				Clients: clients,
 97			})
 98		})
 99
100		r.Group(func(r chi.Router) {
101			if !args.Debug {
102				r.Use(checkVersion)
103			}
104
105			r.Get("/api/exists", func(w http.ResponseWriter, r *http.Request) {
106				query := &protocol.ExistsQuery{}
107				if err := queryparam.Parse(r.URL.Query(), query); err != nil {
108					httpErr(w, http.StatusBadRequest)
109					return
110				}
111
112				room := srv.FindRoomByID(query.RoomID)
113				if room == nil {
114					w.WriteHeader(http.StatusNotFound)
115				} else {
116					w.WriteHeader(http.StatusOK)
117				}
118
119				_, _ = w.Write([]byte("."))
120			})
121
122			r.Post("/api/room", func(w http.ResponseWriter, r *http.Request) {
123				defer r.Body.Close()
124
125				req := &protocol.RoomRequest{}
126				if err := json.NewDecoder(r.Body).Decode(req); err != nil {
127					httpErr(w, http.StatusBadRequest)
128					return
129				}
130
131				if !req.Valid() {
132					httpErr(w, http.StatusBadRequest)
133					return
134				}
135
136				resp := &protocol.RoomResponse{}
137
138				w.Header().Add("Content-Type", "application/json")
139
140				if req.Create {
141					room, err := srv.CreateRoom(req.RoomName, req.RoomPass)
142					if err != nil {
143						switch err {
144						case server.ErrRoomExists:
145							resp.Error = stringPtr("Room already exists.")
146							w.WriteHeader(http.StatusBadRequest)
147						case server.ErrTooManyRooms:
148							resp.Error = stringPtr("Too many rooms.")
149							w.WriteHeader(http.StatusServiceUnavailable)
150						default:
151							resp.Error = stringPtr("An unknown error occurred.")
152							w.WriteHeader(http.StatusInternalServerError)
153						}
154					} else {
155						resp.ID = &room.ID
156						w.WriteHeader(http.StatusOK)
157					}
158				} else {
159					room := srv.FindRoom(req.RoomName)
160					if room == nil || room.Password != req.RoomPass {
161						resp.Error = stringPtr("Room not found or password does not match.")
162						w.WriteHeader(http.StatusNotFound)
163					} else {
164						resp.ID = &room.ID
165						w.WriteHeader(http.StatusOK)
166					}
167				}
168
169				_ = json.NewEncoder(w).Encode(resp)
170			})
171
172			r.Get("/api/ws", func(w http.ResponseWriter, r *http.Request) {
173				query := &protocol.WSQuery{}
174				if err := queryparam.Parse(r.URL.Query(), query); err != nil {
175					httpErr(w, http.StatusBadRequest)
176					return
177				}
178
179				if !query.Valid() {
180					httpErr(w, http.StatusBadRequest)
181					return
182				}
183
184				room := srv.FindRoomByID(query.RoomID)
185				if room == nil {
186					httpErr(w, http.StatusNotFound)
187					return
188				}
189
190				c, err := websocket.Accept(w, r, wsOpts)
191				if err != nil {
192					log.Println(err)
193					return
194				}
195
196				g.Go(func() error {
197					room.HandleConn(query.PlayerID, query.Nickname, c)
198					return nil
199				})
200			})
201		})
202	})
203
204	g.Go(func() error {
205		return srv.Run(ctx)
206	})
207
208	runServer(ctx, g, args.Addr, r)
209	runServer(ctx, g, ":2112", prometheusHandler())
210
211	log.Fatal(g.Wait())
212}
213
214func staticHandler() http.Handler {
215	fs := http.Dir("./frontend/build")
216	fsh := http.FileServer(fs)
217
218	r := chi.NewMux()
219	r.Use(middleware.Compress(5))
220
221	r.Handle("/static/*", fsh)
222	r.Handle("/favicon/*", fsh)
223
224	r.Group(func(r chi.Router) {
225		r.Use(middleware.NoCache)
226		r.Handle("/*", fsh)
227	})
228
229	return r
230}
231
232func checkVersion(next http.Handler) http.Handler {
233	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
234		want := version.Version()
235
236		toCheck := []string{
237			r.Header.Get("X-CODIES-VERSION"),
238			r.URL.Query().Get("codiesVersion"),
239		}
240
241		for _, got := range toCheck {
242			if got == want {
243				next.ServeHTTP(w, r)
244				return
245			}
246		}
247
248		reason := fmt.Sprintf("client version too old, please reload to get %s", want)
249
250		if r.Header.Get("Upgrade") == "websocket" {
251			c, err := websocket.Accept(w, r, wsOpts)
252			if err != nil {
253				log.Println(err)
254				return
255			}
256			c.Close(4418, reason)
257			return
258		}
259
260		w.WriteHeader(http.StatusTeapot)
261		fmt.Fprint(w, reason)
262	})
263}
264
265func runServer(ctx context.Context, g *errgroup.Group, addr string, handler http.Handler) {
266	httpSrv := http.Server{Addr: addr, Handler: handler}
267
268	g.Go(func() error {
269		<-ctx.Done()
270
271		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
272		defer cancel()
273
274		return httpSrv.Shutdown(ctx)
275	})
276
277	g.Go(func() error {
278		return httpSrv.ListenAndServe()
279	})
280}
281
282func prometheusHandler() http.Handler {
283	mux := http.NewServeMux()
284	mux.Handle("/metrics", promhttp.Handler())
285	return mux
286}