server.go

  1package server
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"errors"
  7	"log"
  8	"sync"
  9	"time"
 10
 11	"github.com/gofrs/uuid"
 12	"github.com/speps/go-hashids"
 13	"github.com/zikaeroh/codies/internal/game"
 14	"github.com/zikaeroh/codies/internal/protocol"
 15	"go.uber.org/atomic"
 16	"golang.org/x/sync/errgroup"
 17	"nhooyr.io/websocket"
 18	"nhooyr.io/websocket/wsjson"
 19)
 20
 21const maxRooms = 1000
 22
 23var (
 24	ErrRoomExists   = errors.New("server: rooms exist")
 25	ErrTooManyRooms = errors.New("server: too many rooms")
 26)
 27
 28type Server struct {
 29	clientCount atomic.Int64
 30	roomCount   atomic.Int64
 31	doPrune     chan struct{}
 32	ready       chan struct{}
 33
 34	mu sync.Mutex
 35
 36	ctx     context.Context
 37	rooms   map[string]*Room
 38	roomIDs map[string]*Room
 39
 40	hid    *hashids.HashID
 41	nextID int64
 42}
 43
 44func NewServer() *Server {
 45	hd := hashids.NewData()
 46	hd.MinLength = 8
 47	hd.Salt = uuid.Must(uuid.NewV4()).String() // IDs are only valid for this server instance; ok to randomize salt.
 48	hid, err := hashids.NewWithData(hd)
 49	if err != nil {
 50		panic(err)
 51	}
 52
 53	return &Server{
 54		ready:   make(chan struct{}),
 55		doPrune: make(chan struct{}, 1),
 56		rooms:   make(map[string]*Room),
 57		roomIDs: make(map[string]*Room),
 58		hid:     hid,
 59	}
 60}
 61
 62func (s *Server) Run(ctx context.Context) error {
 63	s.ctx = ctx
 64
 65	close(s.ready)
 66	ticker := time.NewTicker(5 * time.Minute)
 67	defer ticker.Stop()
 68
 69	for {
 70		select {
 71		case <-ctx.Done():
 72			return ctx.Err()
 73
 74		case <-s.doPrune:
 75			s.prune()
 76
 77		case <-ticker.C:
 78			s.prune()
 79		}
 80	}
 81}
 82
 83func (s *Server) FindRoom(name string) *Room {
 84	<-s.ready
 85
 86	s.mu.Lock()
 87	defer s.mu.Unlock()
 88	return s.rooms[name]
 89}
 90
 91func (s *Server) FindRoomByID(id string) *Room {
 92	<-s.ready
 93
 94	s.mu.Lock()
 95	defer s.mu.Unlock()
 96	return s.roomIDs[id]
 97}
 98
 99func (s *Server) CreateRoom(name, password string) (*Room, error) {
100	<-s.ready
101
102	s.mu.Lock()
103	defer s.mu.Unlock()
104
105	room := s.rooms[name]
106	if room != nil {
107		return nil, ErrRoomExists
108	}
109
110	if len(s.rooms) >= maxRooms {
111		return nil, ErrTooManyRooms
112	}
113
114	id, err := s.hid.EncodeInt64([]int64{s.nextID})
115	if err != nil {
116		return nil, err
117	}
118	s.nextID++
119
120	ctx, cancel := context.WithCancel(s.ctx)
121
122	room = &Room{
123		Name:        name,
124		Password:    password,
125		ID:          id,
126		clientCount: &s.clientCount,
127		roomCount:   &s.roomCount,
128		ctx:         ctx,
129		cancel:      cancel,
130		room:        game.NewRoom(nil),
131		players:     make(map[game.PlayerID]noteSender),
132		turnSeconds: 60,
133	}
134
135	room.lastSeen.Store(time.Now())
136
137	room.room.NewGame()
138
139	s.rooms[name] = room
140	s.roomIDs[room.ID] = room
141	s.roomCount.Inc()
142	metricRooms.Inc()
143
144	log.Printf("created new room '%s' (%s)", name, room.ID)
145
146	if s.nextID%100 == 0 {
147		s.triggerPrune()
148	}
149
150	return room, nil
151}
152
153func (s *Server) triggerPrune() {
154	select {
155	case s.doPrune <- struct{}{}:
156	default:
157	}
158}
159
160func (s *Server) prune() {
161	s.mu.Lock()
162	defer s.mu.Unlock()
163
164	toRemove := make([]string, 0, 1)
165
166	for name, room := range s.rooms {
167		lastSeen := room.lastSeen.Load().(time.Time)
168		if time.Since(lastSeen) > 10*time.Minute {
169			toRemove = append(toRemove, name)
170		}
171	}
172
173	if len(toRemove) == 0 {
174		return
175	}
176
177	for _, name := range toRemove {
178		room := s.rooms[name]
179		room.mu.Lock()
180		room.stopTimer()
181		room.mu.Unlock()
182
183		room.cancel()
184		delete(s.rooms, name)
185		delete(s.roomIDs, room.ID)
186		s.roomCount.Dec()
187		metricRooms.Dec()
188	}
189
190	log.Printf("pruned %d rooms", len(toRemove))
191}
192
193func (s *Server) Stats() (rooms, clients int) {
194	s.mu.Lock()
195	defer s.mu.Unlock()
196	return len(s.rooms), int(s.clientCount.Load())
197}
198
199type Room struct {
200	Name     string
201	Password string
202	ID       string
203
204	ctx         context.Context
205	cancel      context.CancelFunc
206	clientCount *atomic.Int64
207	roomCount   *atomic.Int64
208
209	mu       sync.Mutex
210	room     *game.Room
211	players  map[game.PlayerID]noteSender
212	state    *stateCache
213	lastSeen atomic.Value
214
215	timed        bool
216	turnSeconds  int
217	turnDeadline *time.Time
218	turnTimer    *time.Timer
219
220	hideBomb bool
221}
222
223type noteSender func(protocol.ServerNote)
224
225func (r *Room) HandleConn(playerID uuid.UUID, nickname string, c *websocket.Conn) {
226	metricClients.Inc()
227	defer metricClients.Dec()
228
229	clientCount := r.clientCount.Inc()
230	log.Printf("client connected to room '%s' (%s); %v clients currently connected to %v rooms", r.Name, r.ID, clientCount, r.roomCount.Load())
231
232	defer func() {
233		clientCount := r.clientCount.Dec()
234		log.Printf("client disconnected from room '%s' (%s); %v clients currently connected to %v rooms", r.Name, r.ID, clientCount, r.roomCount.Load())
235	}()
236
237	defer c.Close(websocket.StatusGoingAway, "going away")
238	g, ctx := errgroup.WithContext(r.ctx)
239
240	r.mu.Lock()
241	r.players[playerID] = func(s protocol.ServerNote) {
242		if ctx.Err() != nil {
243			return
244		}
245
246		// It's not safe to start more group goroutines concurrently; just use a regular
247		// goroutine and hope that errors here will be reflected later via ping/receive failures.
248		go func() {
249			ctx, cancel := context.WithTimeout(ctx, time.Second)
250			defer cancel()
251			if err := wsjson.Write(ctx, c, &s); err != nil {
252				return
253			}
254			metricSent.Inc()
255		}()
256	}
257	r.room.AddPlayer(playerID, nickname)
258	r.sendAll()
259	r.mu.Unlock()
260
261	defer func() {
262		r.mu.Lock()
263		defer r.mu.Unlock()
264		delete(r.players, playerID)
265		r.room.RemovePlayer(playerID)
266		r.sendAll()
267	}()
268
269	g.Go(func() error {
270		ticker := time.NewTicker(time.Minute)
271		defer ticker.Stop()
272
273		for {
274			select {
275			case <-ctx.Done():
276				return ctx.Err()
277			case <-ticker.C:
278			}
279
280			if err := c.Ping(ctx); err != nil {
281				return err
282			}
283
284			r.lastSeen.Store(time.Now())
285		}
286	})
287
288	g.Go(func() error {
289		for {
290			var note protocol.ClientNote
291
292			if err := wsjson.Read(ctx, c, &note); err != nil {
293				return err
294			}
295
296			r.lastSeen.Store(time.Now())
297			metricReceived.Inc()
298
299			if err := r.handleNote(playerID, &note); err != nil {
300				log.Println("error handling note:", err)
301				return err
302			}
303		}
304	})
305
306	_ = g.Wait()
307}
308
309var errMissingPlayer = errors.New("missing player during handleNote")
310
311func (r *Room) handleNote(playerID game.PlayerID, note *protocol.ClientNote) error {
312	r.mu.Lock()
313	defer r.mu.Unlock()
314
315	// The client's version was wrong; reject and send them the current state.
316	if note.Version != r.room.Version {
317		p := r.players[playerID]
318		if p == nil {
319			return errMissingPlayer
320		}
321		r.sendOne(playerID, p)
322		return nil
323	}
324
325	before := r.room.Version
326	resetTimer := false
327
328	defer func() {
329		if r.room.Version != before {
330			if r.timed && resetTimer {
331				r.startTimer()
332			}
333			r.sendAll()
334		}
335	}()
336
337	switch note.Method {
338	case protocol.RevealMethod:
339		var params protocol.RevealParams
340		if err := json.Unmarshal(note.Params, &params); err != nil {
341			return err
342		}
343		prevTurn := r.room.Turn
344		r.room.Reveal(playerID, params.Row, params.Col)
345		resetTimer = prevTurn != r.room.Turn
346
347	case protocol.NewGameMethod:
348		var params protocol.NewGameParams
349		if err := json.Unmarshal(note.Params, &params); err != nil {
350			return err
351		}
352		resetTimer = true
353		r.room.NewGame()
354
355	case protocol.EndTurnMethod:
356		var params protocol.EndTurnParams
357		if err := json.Unmarshal(note.Params, &params); err != nil {
358			return err
359		}
360		resetTimer = true
361		r.room.EndTurn(playerID)
362
363	case protocol.RandomizeTeamsMethod:
364		var params protocol.RandomizeTeamsParams
365		if err := json.Unmarshal(note.Params, &params); err != nil {
366			return err
367		}
368		r.room.RandomizeTeams()
369
370	case protocol.ChangeTeamMethod:
371		var params protocol.ChangeTeamParams
372		if err := json.Unmarshal(note.Params, &params); err != nil {
373			return err
374		}
375		r.room.ChangeTeam(playerID, params.Team)
376
377	case protocol.ChangeNicknameMethod:
378		var params protocol.ChangeNicknameParams
379		if err := json.Unmarshal(note.Params, &params); err != nil {
380			return err
381		}
382
383		// Sync with protocol.go's validation method.
384		if len(params.Nickname) == 0 || len(params.Nickname) > 16 {
385			return nil
386		}
387
388		r.room.AddPlayer(playerID, params.Nickname)
389
390	case protocol.ChangeRoleMethod:
391		var params protocol.ChangeRoleParams
392		if err := json.Unmarshal(note.Params, &params); err != nil {
393			return err
394		}
395		r.room.ChangeRole(playerID, params.Spymaster)
396
397	case protocol.ChangePackMethod:
398		var params protocol.ChangePackParams
399		if err := json.Unmarshal(note.Params, &params); err != nil {
400			return err
401		}
402		r.room.ChangePack(params.Num, params.Enable)
403
404	case protocol.ChangeTurnModeMethod:
405		var params protocol.ChangeTurnModeParams
406		if err := json.Unmarshal(note.Params, &params); err != nil {
407			return err
408		}
409		r.changeTurnMode(params.Timed)
410
411	case protocol.ChangeTurnTimeMethod:
412		var params protocol.ChangeTurnTimeParams
413		if err := json.Unmarshal(note.Params, &params); err != nil {
414			return err
415		}
416		r.changeTurnTime(params.Seconds)
417
418	case protocol.AddPacksMethod:
419		var params protocol.AddPacksParams
420		if err := json.Unmarshal(note.Params, &params); err != nil {
421			return err
422		}
423		for _, p := range params.Packs {
424			if len(p.Words) < 25 {
425				continue
426			}
427			r.room.AddPack(p.Name, p.Words)
428		}
429
430	case protocol.RemovePackMethod:
431		var params protocol.RemovePackParams
432		if err := json.Unmarshal(note.Params, &params); err != nil {
433			return err
434		}
435		r.room.RemovePack(params.Num)
436
437	case protocol.ChangeHideBombMethod:
438		var params protocol.ChangeHideBombParams
439		if err := json.Unmarshal(note.Params, &params); err != nil {
440			return err
441		}
442		r.changeHideBomb(params.HideBomb)
443
444	default:
445		log.Printf("unhandled method: %s", note.Method)
446	}
447
448	return nil
449}
450
451// Must be called with r.mu locked.
452func (r *Room) sendAll() {
453	for playerID, sender := range r.players {
454		r.sendOne(playerID, sender)
455	}
456}
457
458// Must be called with r.mu locked.
459func (r *Room) sendOne(playerID game.PlayerID, sender noteSender) {
460	state := r.createStateFor(playerID)
461	note := protocol.StateNote(state)
462	sender(note)
463}
464
465// Must be called with r.mu locked.
466func (r *Room) createStateFor(playerID game.PlayerID) *protocol.State {
467	if r.state == nil || r.state.version != r.room.Version {
468		r.state = r.createStateCache()
469	}
470
471	// Temporary verbose access to attempt to figure out which of these is (impossibly) failing.
472	room := r.room
473	players := room.Players
474	player := players[playerID]
475	spymaster := player.Spymaster
476
477	if spymaster {
478		return r.state.spymaster
479	}
480	return r.state.guesser
481}
482
483type stateCache struct {
484	version   int
485	guesser   *protocol.State
486	spymaster *protocol.State
487}
488
489func (r *Room) createStateCache() *stateCache {
490	return &stateCache{
491		version:   r.room.Version,
492		guesser:   r.createRoomState(false),
493		spymaster: r.createRoomState(true),
494	}
495}
496
497func (r *Room) createRoomState(spymaster bool) *protocol.State {
498	room := r.room
499
500	s := &protocol.State{
501		Version:   room.Version,
502		Teams:     make([][]*protocol.StatePlayer, len(room.Teams)),
503		Turn:      room.Turn,
504		Winner:    room.Winner,
505		Board:     make([][]*protocol.StateTile, room.Board.Rows),
506		WordsLeft: room.Board.WordCounts,
507		Lists:     make([]*protocol.StateWordList, len(room.WordLists)),
508		HideBomb:  r.hideBomb,
509	}
510
511	if r.turnDeadline != nil {
512		s.Timer = &protocol.StateTimer{
513			TurnTime: r.turnSeconds,
514			TurnEnd:  *r.turnDeadline,
515		}
516	}
517
518	for team, members := range room.Teams {
519		for _, id := range members {
520			p := room.Players[id]
521			s.Teams[team] = append(s.Teams[team], &protocol.StatePlayer{
522				PlayerID:  id,
523				Nickname:  p.Nickname,
524				Spymaster: p.Spymaster,
525			})
526		}
527
528		if s.Teams[team] == nil {
529			s.Teams[team] = []*protocol.StatePlayer{}
530		}
531	}
532
533	for row := range s.Board {
534		tiles := make([]*protocol.StateTile, room.Board.Cols)
535		for col := range tiles {
536			tile := room.Board.Get(row, col)
537			sTile := &protocol.StateTile{
538				Word:     tile.Word,
539				Revealed: tile.Revealed,
540			}
541
542			if spymaster || tile.Revealed || room.Winner != nil {
543				view := &protocol.StateView{
544					Team:    tile.Team,
545					Neutral: tile.Neutral,
546					Bomb:    tile.Bomb,
547				}
548
549				if view.Bomb && !tile.Revealed && room.Winner == nil && r.hideBomb {
550					view.Neutral = true
551					view.Bomb = false
552				}
553
554				sTile.View = view
555			}
556
557			tiles[col] = sTile
558		}
559
560		s.Board[row] = tiles
561	}
562
563	for i, wl := range room.WordLists {
564		s.Lists[i] = &protocol.StateWordList{
565			Name:    wl.Name,
566			Count:   wl.List.Len(),
567			Custom:  wl.Custom,
568			Enabled: wl.Enabled,
569		}
570	}
571
572	return s
573}
574
575// Must be called with r.mu locked.
576func (r *Room) changeTurnMode(timed bool) {
577	if r.timed == timed {
578		return
579	}
580
581	r.timed = timed
582
583	if timed {
584		r.startTimer()
585	} else {
586		r.stopTimer()
587	}
588
589	r.room.Version++
590}
591
592// Must be called with r.mu locked.
593func (r *Room) changeTurnTime(seconds int) {
594	if seconds <= 0 || r.turnSeconds == seconds {
595		return
596	}
597
598	r.turnSeconds = seconds
599
600	if r.timed {
601		r.startTimer()
602	}
603
604	r.room.Version++
605}
606
607func (r *Room) timerEndTurn() {
608	r.mu.Lock()
609	defer r.mu.Unlock()
610
611	stopped := r.stopTimer()
612	if !stopped {
613		// Room was pruned.
614		return
615	}
616
617	r.turnTimer = nil
618	r.turnDeadline = nil
619
620	if r.room.Winner != nil || r.turnSeconds == 0 {
621		return
622	}
623
624	r.room.ForceEndTurn()
625	r.startTimer()
626	r.sendAll()
627}
628
629// Must be called with r.mu locked.
630func (r *Room) stopTimer() (stopped bool) {
631	if r.turnTimer != nil {
632		r.turnTimer.Stop()
633		stopped = true
634	}
635	r.turnTimer = nil
636	r.turnDeadline = nil
637	return stopped
638}
639
640// Must be called with r.mu locked.
641func (r *Room) startTimer() {
642	if !r.timed {
643		panic("startTimer called on non-timed room")
644	}
645
646	if r.turnTimer != nil {
647		r.turnTimer.Stop()
648	}
649
650	dur := time.Second * time.Duration(r.turnSeconds)
651	deadline := time.Now().Add(dur)
652	r.turnDeadline = &deadline
653	r.turnTimer = time.AfterFunc(dur, r.timerEndTurn)
654}
655
656// Must be called with r.mu locked.
657func (r *Room) changeHideBomb(HideBomb bool) {
658	if r.hideBomb == HideBomb {
659		return
660	}
661
662	r.hideBomb = HideBomb
663	r.room.Version++
664}